|
| 1 | +// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * `/keys` domain — extracted dispatcher body (ADR-0076 D11 step ③, PR-3). |
| 5 | + * |
| 6 | + * Generates a `sys_api_key` and returns the raw secret EXACTLY ONCE |
| 7 | + * (`POST /keys`). This is the only mint path — the raw key is never stored |
| 8 | + * (only its sha256 hash) and never re-displayable. |
| 9 | + * |
| 10 | + * Security (zero-tolerance): |
| 11 | + * - Requires an authenticated principal; `user_id` is PINNED to that |
| 12 | + * caller and is NEVER read from the request body (no impersonation). |
| 13 | + * - Body is whitelisted to `name` (+ optional `expires_at`); any |
| 14 | + * `key` / `id` / `user_id` / `revoked` in the body is ignored, so a |
| 15 | + * caller cannot forge a known-secret or escalate. |
| 16 | + * - `scopes` are intentionally NOT accepted from the body in v1: the |
| 17 | + * verify path ADDS scopes to the principal's permissions, so honouring |
| 18 | + * arbitrary body scopes would be an escalation vector. A generated key |
| 19 | + * therefore acts exactly AS the caller (via `user_id` resolution). |
| 20 | + * Narrowing/scoped keys need subset-enforcement — deferred. |
| 21 | + * - The raw key and its hash never enter logs or error messages. |
| 22 | + * - The row is written with an elevated `{ isSystem: true }` context |
| 23 | + * because `sys_api_key` is protection-locked; safe because the row's |
| 24 | + * contents are fully server-controlled (user_id pinned to caller). |
| 25 | + */ |
| 26 | + |
| 27 | +import { generateApiKey } from '../security/api-key.js'; |
| 28 | +import type { HttpProtocolContext, HttpDispatcherResult } from '../http-dispatcher.js'; |
| 29 | +import type { DomainHandlerDeps, DomainRoute } from '../domain-handler-registry.js'; |
| 30 | + |
| 31 | +/** |
| 32 | + * The legacy branch matched `=== '/keys' || startsWith('/keys/') || |
| 33 | + * startsWith('/keys?')` — a segment match PLUS the query-string form some |
| 34 | + * adapters pass through in `path`. Two entries reproduce that exactly. |
| 35 | + */ |
| 36 | +export function createKeysDomains(deps: DomainHandlerDeps): DomainRoute[] { |
| 37 | + const handler: DomainRoute['handler'] = (req, context) => |
| 38 | + handleKeysRequest(deps, req.method, req.body, context); |
| 39 | + return [ |
| 40 | + { prefix: '/keys', match: 'segment', handler }, |
| 41 | + { prefix: '/keys?', handler }, |
| 42 | + ]; |
| 43 | +} |
| 44 | + |
| 45 | +/** Body kept signature-compatible with the legacy `HttpDispatcher.handleKeys`. */ |
| 46 | +export async function handleKeysRequest( |
| 47 | + deps: DomainHandlerDeps, |
| 48 | + method: string, |
| 49 | + body: any, |
| 50 | + context: HttpProtocolContext, |
| 51 | +): Promise<HttpDispatcherResult> { |
| 52 | + if (method !== 'POST') { |
| 53 | + return { handled: true, response: deps.error('Method not allowed', 405) }; |
| 54 | + } |
| 55 | + |
| 56 | + const ec = context.executionContext; |
| 57 | + if (!ec || !ec.userId) { |
| 58 | + return { handled: true, response: deps.error('Unauthorized: sign in to generate an API key', 401) }; |
| 59 | + } |
| 60 | + |
| 61 | + // ── Whitelist the body. Only `name` and optional `expires_at`. ── |
| 62 | + const rawName = typeof body?.name === 'string' ? body.name.trim() : ''; |
| 63 | + const name = rawName || 'API Key'; |
| 64 | + |
| 65 | + let expiresAt: string | undefined; |
| 66 | + if (body?.expires_at != null && body.expires_at !== '') { |
| 67 | + const ms = typeof body.expires_at === 'number' |
| 68 | + ? (body.expires_at < 1e12 ? body.expires_at * 1000 : body.expires_at) |
| 69 | + : Date.parse(String(body.expires_at)); |
| 70 | + if (Number.isNaN(ms)) { |
| 71 | + return { handled: true, response: deps.error('Invalid expires_at: must be a parseable date', 400) }; |
| 72 | + } |
| 73 | + if (ms <= Date.now()) { |
| 74 | + return { handled: true, response: deps.error('Invalid expires_at: must be in the future', 400) }; |
| 75 | + } |
| 76 | + expiresAt = new Date(ms).toISOString(); |
| 77 | + } |
| 78 | + |
| 79 | + const ql = (await deps.getObjectQL(context.environmentId)) |
| 80 | + ?? (await deps.resolveService('objectql', context.environmentId)); |
| 81 | + if (!ql || typeof ql.insert !== 'function') { |
| 82 | + return { handled: true, response: deps.error('Data service not available', 503) }; |
| 83 | + } |
| 84 | + |
| 85 | + // Generate AFTER validation so we never mint on a rejected request. |
| 86 | + const generated = generateApiKey(); |
| 87 | + |
| 88 | + // Server-controlled row. user_id is pinned to the caller; only the hash |
| 89 | + // is persisted. NOTHING from the body can set key/id/user_id/revoked. |
| 90 | + const row: Record<string, unknown> = { |
| 91 | + name, |
| 92 | + key: generated.hash, |
| 93 | + prefix: generated.prefix, |
| 94 | + user_id: ec.userId, |
| 95 | + revoked: false, |
| 96 | + }; |
| 97 | + if (expiresAt) row.expires_at = expiresAt; |
| 98 | + |
| 99 | + let inserted: any; |
| 100 | + try { |
| 101 | + inserted = await ql.insert('sys_api_key', row, { context: { isSystem: true } }); |
| 102 | + } catch { |
| 103 | + // Never surface the underlying error (could echo row contents). |
| 104 | + return { handled: true, response: deps.error('Failed to create API key', 500) }; |
| 105 | + } |
| 106 | + const id = inserted?.id ?? (Array.isArray(inserted) ? inserted[0]?.id : undefined); |
| 107 | + |
| 108 | + // Raw key returned ONCE. Do not log it. |
| 109 | + return { |
| 110 | + handled: true, |
| 111 | + response: { |
| 112 | + status: 201, |
| 113 | + body: { |
| 114 | + success: true, |
| 115 | + data: { |
| 116 | + id, |
| 117 | + name, |
| 118 | + prefix: generated.prefix, |
| 119 | + key: generated.raw, |
| 120 | + ...(expiresAt ? { expires_at: expiresAt } : {}), |
| 121 | + }, |
| 122 | + }, |
| 123 | + }, |
| 124 | + }; |
| 125 | +} |
0 commit comments