import { createHmac, randomUUID } from "node:crypto"; import { getDbClient } from "./client.server.js"; import type { ApiKey, ApiKeyLog, Prisma, Tenant } from "./prisma-browser.js"; export type LegacyApiKeyUserSummary = { id: string; email: string; firstName: string; lastName: string; phone: string | null; locale: string | null; createdAt: Date; }; export type LegacyApiKeyWithDetails = ApiKey & { tenant: { id: string; name: string; slug: string; deactivatedReason: string | null }; createdByUser: LegacyApiKeyUserSummary; _count: { apiKeyLogs: number }; }; export type LegacyApiKeyLogWithDetails = ApiKeyLog & { apiKey: (ApiKey & { tenant: Tenant }) | null; }; export type LegacyApiKeyLogAdminDetails = ApiKeyLog & { apiKey: { alias: string; tenant: { id: string; name: string } } | null; tenant?: { id: string; name: string; slug: string } | null; }; export type LegacyApiKeyLogSummary = Record & { _avg: { duration: number | null }; _count: { _all: number }; }; export type LegacyApiKeyLogWhereInput = Prisma.ApiKeyLogWhereInput; export type LegacyApiKeyLogOrderByInput = Prisma.ApiKeyLogOrderByWithRelationInput; export type LegacyApiKeySimple = { id: string; alias: string; expires: Date | null; tenantId: string; createdByUserId: string; active: boolean; scopes: unknown; tenant: { id: string; name: string; slug: string; deactivatedReason: string | null }; }; export type LegacyActiveApiKey = ApiKey; export type LegacyApiKeyLogCreateData = { tenantId: string | null; apiKeyId: string | null; endpoint: string; ip: string; method: string; params: string; error?: string; status?: number; alias?: string; tenantName?: string; }; export type LegacyApiKeyHashMetadata = { keyHash: string; keyPrefix: string; keyLastFour: string; hashedAt: Date; keyVersion: 1; }; export type LegacyApiKeyCreateData = { tenantId: string; createdByUserId: string; alias: string; expires: Date | null; active: boolean; key?: string; scopes?: Prisma.InputJsonValue; }; export type LegacyApiKeyCreateStoredData = LegacyApiKeyCreateData & LegacyApiKeyHashMetadata & { key: string }; export type LegacyApiKeyCreateResult = ApiKey & { key: string }; export type LegacyApiKeyRotationResult = ApiKey & { key: string }; export type LegacyApiKeyBackfillRow = { id: string; key: string; keyHash: string | null; hashedAt: Date | null; }; export type LegacyApiKeyBackfillFailure = { id: string; error: string; }; export type LegacyApiKeyHashBackfillResult = { scanned: number; updated: number; skipped: number; failed: number; failures: LegacyApiKeyBackfillFailure[]; }; export type LegacyApiKeyHashBackfillClient = { apiKey: { findMany(args: { take: number; where: { OR: [{ keyHash: null }, { hashedAt: null }]; }; select: { id: true; key: true; keyHash: true; hashedAt: true }; orderBy: { createdAt: "asc" }; }): Promise; update(args: { where: { id: string }; data: LegacyApiKeyHashMetadata; }): Promise; }; }; export type LegacyApiKeyHashBackfillOptions = { batchSize?: number; hashSecret?: string | null; now?: Date; client?: LegacyApiKeyHashBackfillClient; }; export type LegacyApiKeyRotationClient = { apiKey: { updateMany(args: { where: { id: string; tenantId: string }; data: { key: string } & LegacyApiKeyHashMetadata; }): Promise; findFirst(args: { where: { id: string; tenantId: string } }): Promise; }; }; export type LegacyApiKeyUpdateData = { tenantId: string; alias: string; expires: Date | null; active: boolean; scopes?: Prisma.InputJsonValue; }; export type LegacyApiKeyReaderClient = { apiKey: { findMany(args: { where?: { tenantId: string }; include: typeof legacyApiKeyDetailsInclude; orderBy: { createdAt: "desc" }; }): Promise; findUnique(args: { where: { id: string }; include: typeof legacyApiKeyDetailsInclude; }): Promise; findFirst(args: { where: { key: string } | { keyHash: string } | { id: string; tenantId: string } | { tenantId: string; alias: string } | { tenantId: string; active: true }; select?: typeof legacyApiKeySimpleSelect; include?: typeof legacyApiKeyDetailsInclude; }): Promise; }; apiKeyLog: { findMany(args: { where: { apiKeyId: string; tenantId: string }; include: { apiKey: { include: { tenant: true } } }; orderBy: { createdAt: "desc" }; }): Promise; findMany(args: { take: number; skip: number; where: LegacyApiKeyLogWhereInput; include: { apiKey: { select: { alias: true; tenant: { select: { id: true; name: true } } } }; tenant?: { select: { id: true; name: true; slug: true } }; }; orderBy: LegacyApiKeyLogOrderByInput | LegacyApiKeyLogOrderByInput[]; }): Promise; count(args: { where: LegacyApiKeyLogWhereInput }): Promise; groupBy(args: { by: string[]; where: LegacyApiKeyLogWhereInput; _avg: { duration: true }; _count: { _all: true }; orderBy: { _avg: { duration: "desc" } }; }): Promise; }; }; export type LegacyApiKeyLookupOptions = { allowPlaintextFallback?: boolean; }; export function tenantLegacyApiKeyLogScope(tenantId: string): Prisma.ApiKeyLogWhereInput { return { tenantId, OR: [{ apiKeyId: null }, { apiKey: { tenantId } }], }; } export type LegacyApiKeyLogStatusUpdate = { status: number; startTime: number | null; error?: string | null; }; export type LegacyApiKeyLogWriterClient = { apiKey: { create(args: { data: LegacyApiKeyCreateStoredData & { active: boolean } }): Promise; updateMany(args: { where: { id: string; tenantId: string }; data: LegacyApiKeyUpdateData }): Promise; findFirst(args: { where: { id: string; tenantId: string } }): Promise; deleteMany(args: { where: { id: string; tenantId: string } }): Promise; }; apiKeyLog: { create(args: { data: LegacyApiKeyLogCreateData; }): Promise; update(args: { where: { id: string }; data: { status: number; error?: string | null; duration: number | null; }; }): Promise; updateMany(args: { where: Prisma.ApiKeyLogWhereInput; data: { status: number; error?: string | null; duration: number | null; }; }): Promise; count(args: { where: Prisma.ApiKeyLogWhereInput }): Promise; deleteMany(args: { where: Prisma.ApiKeyLogWhereInput }): Promise; }; }; const selectLegacyApiKeyUserSummary = { id: true, email: true, firstName: true, lastName: true, phone: true, locale: true, createdAt: true, } as const; export const LEGACY_API_KEY_HASH_VERSION = 1 as const; export const DEFAULT_LEGACY_API_KEY_HASH_SECRET = "hivegrid-api-key-hash-v1"; export const DEFAULT_LEGACY_API_KEY_HASH_BACKFILL_BATCH_SIZE = 100; export const LEGACY_API_KEY_PREFIX_LENGTH = 8; export const LEGACY_API_KEY_LAST_FOUR_LENGTH = 4; export function normalizeLegacyApiKeyHashSecret(secret: string | undefined | null): string { const normalized = secret?.trim(); if (!normalized) { return DEFAULT_LEGACY_API_KEY_HASH_SECRET; } return normalized; } export function deriveLegacyApiKeyHashMetadata( key: string, hashSecret: string | undefined | null, hashedAt: Date = new Date(), ): LegacyApiKeyHashMetadata { const secret = normalizeLegacyApiKeyHashSecret(hashSecret); return { keyHash: createHmac("sha256", secret).update(key).digest("hex"), keyPrefix: key.slice(0, LEGACY_API_KEY_PREFIX_LENGTH), keyLastFour: key.slice(-LEGACY_API_KEY_LAST_FOUR_LENGTH), hashedAt, keyVersion: LEGACY_API_KEY_HASH_VERSION, }; } function normalizeLegacyApiKeyHashBackfillBatchSize(batchSize: number | undefined): number { if (!Number.isFinite(batchSize) || batchSize === undefined) { return DEFAULT_LEGACY_API_KEY_HASH_BACKFILL_BATCH_SIZE; } return Math.max(1, Math.floor(batchSize)); } function redactLegacyApiKeyBackfillError(error: unknown): string { if (error instanceof Error) { return error.name || "Error"; } return "UnknownError"; } export async function backfillLegacyApiKeyHashes({ batchSize, hashSecret, now = new Date(), client = getDbClient() as unknown as LegacyApiKeyHashBackfillClient, }: LegacyApiKeyHashBackfillOptions = {}): Promise { const rows = await client.apiKey.findMany({ take: normalizeLegacyApiKeyHashBackfillBatchSize(batchSize), where: { OR: [{ keyHash: null }, { hashedAt: null }], }, select: { id: true, key: true, keyHash: true, hashedAt: true }, orderBy: { createdAt: "asc" }, }); const result: LegacyApiKeyHashBackfillResult = { scanned: rows.length, updated: 0, skipped: 0, failed: 0, failures: [], }; for (const row of rows) { if (!row.key || row.keyHash || row.hashedAt) { result.skipped += 1; continue; } try { await client.apiKey.update({ where: { id: row.id }, data: deriveLegacyApiKeyHashMetadata(row.key, hashSecret, now), }); result.updated += 1; } catch (error) { result.failed += 1; result.failures.push({ id: row.id, error: redactLegacyApiKeyBackfillError(error) }); } } return result; } export const legacyApiKeyDetailsInclude = { tenant: { select: { id: true, name: true, slug: true, deactivatedReason: true } }, createdByUser: { select: selectLegacyApiKeyUserSummary, }, _count: { select: { apiKeyLogs: true, }, }, } as const; const legacyApiKeySimpleSelect = { id: true, alias: true, expires: true, tenantId: true, createdByUserId: true, active: true, scopes: true, tenant: { select: { id: true, name: true, slug: true, deactivatedReason: true } }, } as const; export async function getAllLegacyApiKeys( client: LegacyApiKeyReaderClient = getDbClient() as unknown as LegacyApiKeyReaderClient, ): Promise { return client.apiKey.findMany({ include: legacyApiKeyDetailsInclude, orderBy: { createdAt: "desc", }, }); } export async function getLegacyApiKeysForTenant( tenantId: string, client: LegacyApiKeyReaderClient = getDbClient() as unknown as LegacyApiKeyReaderClient, ): Promise { return client.apiKey.findMany({ where: { tenantId, }, include: legacyApiKeyDetailsInclude, orderBy: { createdAt: "desc", }, }); } export async function adminFindLegacyApiKeyById( id: string, client: LegacyApiKeyReaderClient = getDbClient() as unknown as LegacyApiKeyReaderClient, ): Promise { return client.apiKey.findUnique({ where: { id }, include: legacyApiKeyDetailsInclude, }); } export async function findLegacyApiKeyById( { id, tenantId }: { id: string; tenantId: string }, client: LegacyApiKeyReaderClient = getDbClient() as unknown as LegacyApiKeyReaderClient, ): Promise { return (await client.apiKey.findFirst({ where: { id, tenantId }, include: legacyApiKeyDetailsInclude, })) as LegacyApiKeyWithDetails | null; } export async function findLegacyApiKeyByAlias( tenantId: string, alias: string, client: LegacyApiKeyReaderClient = getDbClient() as unknown as LegacyApiKeyReaderClient, ): Promise { return (await client.apiKey.findFirst({ where: { tenantId, alias }, include: legacyApiKeyDetailsInclude, })) as LegacyApiKeyWithDetails | null; } export async function getLegacyApiKeyLogsForKey( { id, tenantId }: { id: string; tenantId: string }, client: LegacyApiKeyReaderClient = getDbClient() as unknown as LegacyApiKeyReaderClient, ): Promise { return client.apiKeyLog.findMany({ where: { apiKeyId: id, tenantId, }, include: { apiKey: { include: { tenant: true, }, }, }, orderBy: { createdAt: "desc", }, }); } export async function countLegacyApiKeyLogsForKey( { id, tenantId }: { id: string; tenantId: string }, client: LegacyApiKeyReaderClient = getDbClient() as unknown as LegacyApiKeyReaderClient, ): Promise { return client.apiKeyLog.count({ where: { apiKeyId: id, tenantId, }, }); } export async function groupLegacyApiKeyLogs( args: { by: string[]; where: LegacyApiKeyLogWhereInput; }, client: LegacyApiKeyReaderClient = getDbClient() as unknown as LegacyApiKeyReaderClient, ): Promise { return client.apiKeyLog.groupBy({ by: args.by, where: args.where, _avg: { duration: true }, _count: { _all: true }, orderBy: { _avg: { duration: "desc" }, }, }); } export async function getLegacyApiKeyLogAdminDetails( args: { take: number; skip: number; where: LegacyApiKeyLogWhereInput; includeTenant: boolean; orderBy: LegacyApiKeyLogOrderByInput | LegacyApiKeyLogOrderByInput[]; }, client: LegacyApiKeyReaderClient = getDbClient() as unknown as LegacyApiKeyReaderClient, ): Promise { const include: { apiKey: { select: { alias: true; tenant: { select: { id: true; name: true } } } }; tenant?: { select: { id: true; name: true; slug: true } }; } = { apiKey: { select: { alias: true, tenant: { select: { id: true, name: true } } }, }, }; if (args.includeTenant) { include.tenant = { select: { id: true, name: true, slug: true } }; } return client.apiKeyLog.findMany({ take: args.take, skip: args.skip, where: args.where, include, orderBy: args.orderBy, }); } export async function countLegacyApiKeyLogs( where: LegacyApiKeyLogWhereInput, client: LegacyApiKeyReaderClient = getDbClient() as unknown as LegacyApiKeyReaderClient, ): Promise { return client.apiKeyLog.count({ where, }); } export async function findFirstLegacyActiveApiKey( tenantId: string | null, client: LegacyApiKeyReaderClient = getDbClient() as unknown as LegacyApiKeyReaderClient, ): Promise { if (!tenantId) { return null; } return (await client.apiKey .findFirst({ where: { tenantId, active: true, }, }) .catch(() => null)) as LegacyActiveApiKey | null; } export async function createLegacyApiKey( data: LegacyApiKeyCreateData, client: LegacyApiKeyLogWriterClient = getDbClient() as unknown as LegacyApiKeyLogWriterClient, hashSecret?: string | null, ): Promise { const key = data.key ?? randomUUID(); const hashMetadata = deriveLegacyApiKeyHashMetadata(key, hashSecret); const apiKey = await client.apiKey.create({ data: { ...data, key, ...hashMetadata, active: data.active ?? true, }, }); return { ...apiKey, key, } as LegacyApiKeyCreateResult; } export async function updateLegacyApiKey( id: string, data: LegacyApiKeyUpdateData, client: LegacyApiKeyLogWriterClient = getDbClient() as unknown as LegacyApiKeyLogWriterClient, ): Promise { const updated = await client.apiKey.updateMany({ where: { id, tenantId: data.tenantId }, data, }); if (updated.count !== 1) { throw new Error(`API key ${id} not found`); } const apiKey = await client.apiKey.findFirst({ where: { id, tenantId: data.tenantId } }); if (!apiKey) { throw new Error(`API key ${id} could not be reloaded`); } return apiKey; } export async function rotateLegacyApiKey( { id, tenantId }: { id: string; tenantId: string }, client: LegacyApiKeyRotationClient = getDbClient() as unknown as LegacyApiKeyRotationClient, hashSecret?: string | null, ): Promise { const key = randomUUID(); const updated = await client.apiKey.updateMany({ where: { id, tenantId }, data: { key, ...deriveLegacyApiKeyHashMetadata(key, hashSecret), }, }); if (updated.count !== 1) { throw new Error(`API key ${id} not found`); } const apiKey = await client.apiKey.findFirst({ where: { id, tenantId } }); if (!apiKey) { throw new Error(`API key ${id} could not be reloaded`); } return { ...apiKey, key, } as LegacyApiKeyRotationResult; } export async function deleteLegacyApiKey( { id, tenantId }: { id: string; tenantId: string }, client: LegacyApiKeyLogWriterClient = getDbClient() as unknown as LegacyApiKeyLogWriterClient, ): Promise { const apiKey = await client.apiKey.findFirst({ where: { id, tenantId } }); if (!apiKey) { throw new Error(`API key ${id} not found`); } const deleted = await client.apiKey.deleteMany({ where: { id, tenantId }, }); if (deleted.count !== 1) { throw new Error(`API key ${id} not found`); } return apiKey; } export async function setLegacyApiKeyLogStatus( scope: { id: string; tenantId: string }, data: LegacyApiKeyLogStatusUpdate, client: LegacyApiKeyLogWriterClient = getDbClient() as unknown as LegacyApiKeyLogWriterClient, ): Promise { let duration: number | null = null; if (data.startTime) { const endTime = performance.now(); duration = Number(endTime - data.startTime); } const updateData = { status: data.status, error: data.error, duration, }; const updated = await client.apiKeyLog.updateMany({ where: { id: scope.id, tenantId: scope.tenantId }, data: updateData, }); if (updated.count !== 1) { throw new Error(`API key log ${scope.id} not found`); } return updated; } export async function createLegacyApiKeyLog( data: LegacyApiKeyLogCreateData, client: LegacyApiKeyLogWriterClient = getDbClient() as unknown as LegacyApiKeyLogWriterClient, ): Promise { return client.apiKeyLog.create({ data, }); } export async function findLegacyApiKeyByKey( key: string, client: LegacyApiKeyReaderClient = getDbClient() as unknown as LegacyApiKeyReaderClient, hashSecret?: string | null, options: LegacyApiKeyLookupOptions = {}, ): Promise { const allowPlaintextFallback = options.allowPlaintextFallback ?? false; const { keyHash } = deriveLegacyApiKeyHashMetadata(key, hashSecret); const hashedApiKey = await client.apiKey .findFirst({ where: { keyHash }, select: legacyApiKeySimpleSelect, }) .then((apiKey) => apiKey as LegacyApiKeySimple | null) .catch(() => null); if (hashedApiKey) { return hashedApiKey; } if (!allowPlaintextFallback) { return null; } return client.apiKey .findFirst({ where: { key }, select: legacyApiKeySimpleSelect, }) .then((apiKey) => apiKey as LegacyApiKeySimple | null) .catch(() => { return null; }); } export async function countLegacyTenantApiKeyLogs( tenantId: string, client: LegacyApiKeyLogWriterClient = getDbClient() as unknown as LegacyApiKeyLogWriterClient, ): Promise { return client.apiKeyLog.count({ where: tenantLegacyApiKeyLogScope(tenantId), }); } export async function countLegacyTenantApiKeyUsage( { tenantId, statuses, ignoredEndpoints, period, }: { tenantId: string; statuses: number[]; ignoredEndpoints: string[]; period?: { start: Date; end: Date }; }, client: LegacyApiKeyLogWriterClient = getDbClient() as unknown as LegacyApiKeyLogWriterClient, ): Promise { return client.apiKeyLog.count({ where: { tenantId, status: { in: statuses }, endpoint: { notIn: ignoredEndpoints }, ...(period ? { createdAt: { gte: period.start, lt: period.end, }, } : {}), }, }); } export async function adminDeleteLegacyApiKeyLogsByIds( ids: string[], client: LegacyApiKeyLogWriterClient = getDbClient() as unknown as LegacyApiKeyLogWriterClient, ): Promise { return client.apiKeyLog.deleteMany({ where: { id: { in: ids }, }, }); } export async function deleteTenantLegacyApiKeyLogsByIds( { ids, tenantId }: { ids: string[]; tenantId: string | null }, client: LegacyApiKeyLogWriterClient = getDbClient() as unknown as LegacyApiKeyLogWriterClient, ): Promise { return client.apiKeyLog.deleteMany({ where: { id: { in: ids }, ...(tenantId ? tenantLegacyApiKeyLogScope(tenantId) : { tenantId: null, apiKeyId: null }), }, }); }