import { Injectable, NotFoundException, UnauthorizedException, } from "@nestjs/common"; import { PrismaService } from "../prisma/prisma.service"; import { CreateApiKeyDto } from "./dto/api-key.dto"; import * as crypto from "crypto"; @Injectable() export class ApiKeysService { constructor(private readonly prisma: PrismaService) {} private hashKey(key: string): string { return crypto.createHash("sha256").update(key).digest("hex"); } async findAll() { const keys = await this.prisma.apiKey.findMany({ orderBy: { createdAt: "desc" }, select: { id: true, name: true, keyPrefix: true, scopes: true, status: true, description: true, expiresAt: true, lastUsedAt: true, createdAt: true, updatedAt: true, }, }); return keys.map((k) => ({ ...k, scopes: k.scopes ? k.scopes.split(",").map((s) => s.trim()) : ["*"], isExpired: k.expiresAt ? new Date(k.expiresAt) < new Date() : false, })); } async create(dto: CreateApiKeyDto) { // Generate secure random key: cn_live_<32 hex chars> const randomBytes = crypto.randomBytes(24).toString("hex"); const rawKey = `cn_live_${randomBytes}`; const keyPrefix = rawKey.substring(0, 12); const keyHash = this.hashKey(rawKey); const scopesStr = dto.scopes && dto.scopes.length > 0 ? dto.scopes.join(",") : "*"; const apiKey = await this.prisma.apiKey.create({ data: { name: dto.name, keyHash, keyPrefix, scopes: scopesStr, description: dto.description || null, expiresAt: dto.expiresAt ? new Date(dto.expiresAt) : null, status: "ACTIVE", }, select: { id: true, name: true, keyPrefix: true, scopes: true, status: true, description: true, expiresAt: true, createdAt: true, }, }); return { apiKey: { ...apiKey, scopes: apiKey.scopes.split(","), }, rawKey, // Return raw secret only once upon creation }; } async toggleStatus(id: string) { const key = await this.prisma.apiKey.findUnique({ where: { id } }); if (!key) { throw new NotFoundException("کلید یافت نشد"); } const nextStatus = key.status === "ACTIVE" ? "REVOKED" : "ACTIVE"; const updated = await this.prisma.apiKey.update({ where: { id }, data: { status: nextStatus }, select: { id: true, name: true, keyPrefix: true, scopes: true, status: true, expiresAt: true, }, }); return { ...updated, scopes: updated.scopes.split(","), }; } async delete(id: string) { const key = await this.prisma.apiKey.findUnique({ where: { id } }); if (!key) { throw new NotFoundException("کلید یافت نشد"); } await this.prisma.apiKey.delete({ where: { id } }); return { success: true }; } async validateKey(rawKey: string) { if ( !rawKey || typeof rawKey !== "string" || !rawKey.startsWith("cn_live_") ) { throw new UnauthorizedException("API Key نامعتبر است"); } const keyHash = this.hashKey(rawKey); const key = await this.prisma.apiKey.findUnique({ where: { keyHash }, }); if (!key) { throw new UnauthorizedException("API Key یافت نشد یا معتبر نیست"); } if (key.status !== "ACTIVE") { throw new UnauthorizedException("این API Key باطل یا غیرفعال شده است"); } if (key.expiresAt && new Date(key.expiresAt) < new Date()) { throw new UnauthorizedException("این API Key منقضی شده است"); } // Update lastUsedAt asynchronously in background this.prisma.apiKey .update({ where: { id: key.id }, data: { lastUsedAt: new Date() }, }) .catch(() => {}); const scopes = key.scopes.split(",").map((s) => s.trim().toLowerCase()); // SEC-016: Disallow wildcard '*' from granting admin role; require explicit 'admin' scope const hasAdminScope = scopes.includes("admin"); return { id: key.id, name: key.name, role: hasAdminScope ? "Admin" : "USER", email: "apikey-system@canina.ir", scopes, isApiKey: true, }; } }