import 'server-only'; type Statement = { bind(...values: (string | number)[]): Statement; first(): Promise; }; export type StudioDatabase = { prepare(sql: string): Statement }; export type StudioLimits = { daily: number; perAccount: number; total: number }; const providerKey = 'studio-provider-usage-v1'; const authKey = 'studio-auth-usage-v1'; function boundedInteger(value: string | undefined, maximum: number) { if (!value || !/^[1-9][0-9]{0,6}$/.test(value)) return null; const numeric = Number(value); return numeric <= maximum ? numeric : null; } export function studioLimits(env: NodeJS.ProcessEnv = process.env): StudioLimits | null { if (env.LUMEN_STUDIO_ENABLED !== 'true') return null; const daily = boundedInteger(env.LUMEN_STUDIO_DAILY_CALLS, 1000); const perAccount = boundedInteger(env.LUMEN_STUDIO_ACCOUNT_DAILY_CALLS, 30); const total = boundedInteger(env.LUMEN_STUDIO_TOTAL_CALLS, 100_000); if (daily === null || perAccount === null || total === null || perAccount > daily || daily > total) return null; return { daily, perAccount, total }; } export function studioAuthLimits(env: NodeJS.ProcessEnv = process.env): StudioLimits | null { const daily = boundedInteger(env.LUMEN_STUDIO_AUTH_DAILY_SENDS, 1000); const perAccount = boundedInteger(env.LUMEN_STUDIO_AUTH_IP_DAILY_SENDS, 20); const total = boundedInteger(env.LUMEN_STUDIO_AUTH_TOTAL_SENDS, 100_000); if (daily === null || perAccount === null || total === null || perAccount > daily || daily > total) return null; return { daily, perAccount, total }; } export async function studioStoreReady(db: StudioDatabase) { // No schema changes: the integrations table already backs server-side data. // This checks its availability without mutating any user or quota records. await db.prepare('SELECT 1 AS ok FROM integrations WHERE key = ?').bind(providerKey).first(); } /** Atomically reserve exactly one upstream call. Keep one durable total and * the current UTC-day counters. On timeout/error the reservation is retained: * an upstream call can be billable even if we never got back an image. */ type QuotaScope = { kind: 'provider' } | { kind: 'auth'; email: string; salt: string }; async function identifier(value: string) { const hash = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(value)); return Array.from(new Uint8Array(hash), byte => byte.toString(16).padStart(2, '0')).join(''); } export async function reserveStudioCall( db: StudioDatabase, subjectId: string, limits: StudioLimits, scope: QuotaScope = {kind:'provider'}, ): Promise { const usageKey = scope.kind === 'provider' ? providerKey : authKey; const user = await identifier(scope.kind === 'auth' ? scope.salt + '\0ip\0' + subjectId : subjectId); const userPath = '$.users.' + user; // Distinct keyed identifiers for IP and email prevent accidental matching. // In provider scope the email predicates are disabled. const target = scope.kind === 'auth' ? await identifier(scope.salt + '\0email\0' + scope.email) : 'none'; const targetPath = '$.targets.' + target; const perEmail = scope.kind === 'auth' ? 2 : 0; const row = await db.prepare(` INSERT INTO integrations (key, value, updated_at) VALUES (?1, json_object('day', date('now'), 'daily', 1, 'total', 1, 'users', json_object(?2, 1), 'targets', json_object(?7, 1)), datetime('now')) ON CONFLICT (key) DO UPDATE SET value = CASE WHEN json_extract(integrations.value, '$.day') = date('now') THEN json_set(integrations.value, '$.daily', json_extract(integrations.value, '$.daily') + 1, '$.total', json_extract(integrations.value, '$.total') + 1, ?3, coalesce(json_extract(integrations.value, ?3), 0) + 1, ?8, coalesce(json_extract(integrations.value, ?8), 0) + 1) ELSE json_object('day', date('now'), 'daily', 1, 'total', json_extract(integrations.value, '$.total') + 1, 'users', json_object(?2, 1), 'targets', json_object(?7, 1)) END, updated_at = datetime('now') WHERE json_type(integrations.value, '$.total') = 'integer' AND json_extract(integrations.value, '$.total') >= 0 AND json_extract(integrations.value, '$.total') < ?4 AND (json_extract(integrations.value, '$.day') <> date('now') OR ( json_type(integrations.value, '$.daily') = 'integer' AND json_extract(integrations.value, '$.daily') < ?5 AND coalesce(json_extract(integrations.value, ?3), 0) < ?6 AND (?9 = 0 OR coalesce(json_extract(integrations.value, ?8), 0) < ?9) )) RETURNING key`).bind(usageKey, user, userPath, limits.total, limits.daily, limits.perAccount, target, targetPath, perEmail).first<{key: string}>(); return row?.key === usageKey; }