import { BadRequestException, Controller, Get, Query, Req, } from '@nestjs/common' import { Address4, Address6 } from 'ip-address' import type { FastifyRequest } from 'fastify' import { type HKPOperation, VALID_OPS } from '../providers/abstract.provider.js' import { AllKeysProvider } from '../providers/all.provider.js' import { serializeIndexes } from '../indexes.js' @Controller() export class HKPController { constructor(private allKeysProvider: AllKeysProvider) {} @Get('pks/lookup') async lookup( @Req() req: FastifyRequest, @Query('search') search: string, @Query('op') op: HKPOperation ) { if (VALID_OPS.indexOf(op) === -1) { throw new BadRequestException( 'op MUST be one of: ' + VALID_OPS.join(', ') ) } let ip: Address4 | Address6 | null = null if (Address4.isValid(req.ip.replace(/^.*:/, ''))) { ip = new Address4(req.ip.replace(/^.*:/, '')) } else if (Address6.isValid(req.ip)) { ip = new Address6(req.ip) } if (ip === null) { ip = new Address4('127.0.0.1') } const miscData = { ip } switch (op) { case 'get': return this.allKeysProvider.get(search, miscData) case 'index': const indexes = await this.allKeysProvider.index( search, miscData ) return serializeIndexes(indexes) } } }