All files / src/platform/developer-platform developer.service.ts

0% Statements 0/28
0% Branches 0/16
0% Functions 0/6
0% Lines 0/26

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95                                                                                                                                                                                             
import { Injectable, Logger, UnauthorizedException } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { ApiKey, ApiRequestLog } from './schemas/developer.schema';
import * as crypto from 'crypto';
 
@Injectable()
export class DeveloperPlatformService {
  private readonly logger = new Logger(DeveloperPlatformService.name);
 
  constructor(
    @InjectModel(ApiKey.name) private readonly apiKeyModel: Model<ApiKey>,
    @InjectModel(ApiRequestLog.name)
    private readonly requestLogModel: Model<ApiRequestLog>,
  ) {}
 
  async createKey(
    tenantId: string,
    scopes: string[],
    expiresInDays?: number,
  ): Promise<{ rawKey: string; key: ApiKey }> {
    const rawSecret = crypto.randomBytes(32).toString('hex');
    const rawKey = `bv_live_${rawSecret}`;
 
    // Hash key for DB lookup safety
    const keyHash = crypto.createHash('sha256').update(rawKey).digest('hex');
    const keyMask = `bv_live_******${rawSecret.substring(rawSecret.length - 6)}`;
 
    const expiresAt = expiresInDays
      ? new Date(Date.now() + expiresInDays * 86400000)
      : null;
 
    const key = await this.apiKeyModel.create({
      tenantId,
      keyMask,
      keyHash,
      scopes,
      expiresAt,
      isActive: true,
    });
 
    return {
      rawKey,
      key,
    };
  }
 
  async validateKey(rawKey: string): Promise<ApiKey> {
    const keyHash = crypto.createHash('sha256').update(rawKey).digest('hex');
    const key = await this.apiKeyModel
      .findOne({ keyHash, isActive: true })
      .exec();
 
    if (!key) {
      throw new UnauthorizedException('Invalid API Key credentials');
    }
 
    if (key.expiresAt && key.expiresAt < new Date()) {
      throw new UnauthorizedException('API Key credentials have expired');
    }
 
    return key;
  }
 
  async logRequest(
    tenantId: string,
    apiKeyId: string,
    path: string,
    method: string,
    statusCode: number,
    latencyMs: number,
    ipAddress?: string,
  ): Promise<void> {
    await this.requestLogModel.create({
      tenantId,
      apiKeyId,
      path,
      method,
      statusCode,
      latencyMs,
      ipAddress,
    });
  }
 
  async getKeys(tenantId: string): Promise<ApiKey[]> {
    return this.apiKeyModel.find({ tenantId }).exec();
  }
 
  async revokeKey(tenantId: string, keyId: string): Promise<void> {
    await this.apiKeyModel
      .findOneAndUpdate({ tenantId, _id: keyId }, { isActive: false })
      .exec();
  }
}