@tangle-network/agent-app 4.0.30 → 4.0.32
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chat-routes/index.js +5 -5
- package/dist/{chunk-RK2VCJQW.js → chunk-5L3X42ES.js} +2 -2
- package/dist/{chunk-LSUJ2RIC.js → chunk-AG5Q273U.js} +2 -2
- package/dist/{chunk-GHBQUZYG.js → chunk-DSFMSRWT.js} +4 -4
- package/dist/{chunk-7TZX2KSH.js → chunk-G3W3EIP4.js} +11 -4
- package/dist/chunk-G3W3EIP4.js.map +1 -0
- package/dist/{chunk-H7NMUXNZ.js → chunk-JLKH2VYF.js} +5 -4
- package/dist/chunk-JLKH2VYF.js.map +1 -0
- package/dist/platform/agent-spend.d.ts +2 -1
- package/dist/platform/delegated-keys.d.ts +2 -1
- package/dist/platform/index.js +47 -23
- package/dist/platform/index.js.map +1 -1
- package/dist/platform/platform-busy.d.ts +17 -0
- package/dist/preset-cloudflare/index.js +1 -1
- package/dist/public-consultation/index.d.ts +1 -1
- package/dist/public-consultation/index.js +4 -4
- package/dist/runtime/index.js +3 -3
- package/dist/runtime/router-turn.js +2 -2
- package/dist/sandbox/index.js +2 -2
- package/dist/turn-trace/index.js +1 -1
- package/dist/turn-trace/recorder.d.ts +2 -1
- package/package.json +1 -1
- package/dist/chunk-7TZX2KSH.js.map +0 -1
- package/dist/chunk-H7NMUXNZ.js.map +0 -1
- /package/dist/{chunk-RK2VCJQW.js.map → chunk-5L3X42ES.js.map} +0 -0
- /package/dist/{chunk-LSUJ2RIC.js.map → chunk-AG5Q273U.js.map} +0 -0
- /package/dist/{chunk-GHBQUZYG.js.map → chunk-DSFMSRWT.js.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/platform/sso-identity-store.ts","../../src/platform/hub-connect-callback.ts","../../src/platform/hub-settings.ts","../../src/platform/billing.ts","../../src/platform/agent-spend.ts","../../src/platform/billing-consent.ts","../../src/platform/deployment.ts","../../src/platform/delegated-keys.ts","../../src/platform/delegated-turn-keys.ts","../../src/platform/billable-turn-admission.ts"],"sourcesContent":["/**\n * Better Auth `account`-table store for first-party Tangle identity sign-in\n * (`protocol: 'identity'`) on D1 / SQLite.\n *\n * The platform link is Better Auth's own external-identity row:\n * `account(providerId = 'tangle', accountId = <platform user id>, userId)`.\n * Run {@link TANGLE_IDENTITY_ACCOUNT_INDEXES_SQL} in a product migration; its\n * two partial unique indexes make the link one-per-user and\n * one-per-platform-user, which the write path relies on.\n *\n * The default schema is Better Auth's singular SQLite model with camelCase\n * columns. {@link D1TangleIdentityStoreOptions.hostSchema} maps an existing\n * host's physical table and column names without changing those defaults.\n * Timestamps are unix-second integers (Drizzle `mode: 'timestamp'`). D1 is\n * structural: Cloudflare `D1Database` satisfies {@link TangleIdentityD1Like}.\n */\n\nimport {\n normalizeTangleSsoEmail,\n resolveTangleSsoAccount,\n TangleSsoAccountConflictError,\n TangleSsoUserCreateError,\n type TangleIdentitySsoAccountStore,\n type TangleSsoAccountResolution,\n type TangleSsoLocalAccount,\n} from './sso'\n\n/** Better Auth `account.providerId` for the Tangle platform link. */\nexport const TANGLE_IDENTITY_PROVIDER_ID = 'tangle'\n\n/** Partial unique indexes the store requires on Better Auth's `account` table. */\nexport const TANGLE_IDENTITY_ACCOUNT_INDEXES_SQL = [\n `CREATE UNIQUE INDEX IF NOT EXISTS account_tangle_platform_user ON account(accountId) WHERE providerId = '${TANGLE_IDENTITY_PROVIDER_ID}'`,\n `CREATE UNIQUE INDEX IF NOT EXISTS account_tangle_user ON account(userId) WHERE providerId = '${TANGLE_IDENTITY_PROVIDER_ID}'`,\n] as const\n\n/** A prepared D1 statement; Cloudflare `D1PreparedStatement` satisfies it. */\nexport interface TangleIdentityD1Statement {\n bind(...values: unknown[]): TangleIdentityD1Statement\n first<T = Record<string, unknown>>(): Promise<T | null>\n all<T = Record<string, unknown>>(): Promise<{ results: T[] }>\n run(): Promise<unknown>\n}\n\n/** The D1 surface the store needs. `batch` must be atomic, as D1's is. */\nexport interface TangleIdentityD1Like {\n prepare(query: string): TangleIdentityD1Statement\n batch(statements: TangleIdentityD1Statement[]): Promise<Array<{ meta?: { changes?: number } }>>\n}\n\n/**\n * A link table the product used before this store. During migration the store\n * reads it after `account` and mirrors new links into it, so a link that\n * exists in either place still signs in and a rollback still finds new links.\n * Remove the option once a reconcile query proves every legacy row has an\n * equal `account` row.\n */\nexport interface TangleIdentityLegacyLinkTable {\n table: string\n /** Column holding the local `user.id`; must be unique. */\n userIdColumn: string\n /** Column holding the platform user id; must be unique. */\n platformUserIdColumn: string\n}\n\nexport interface TangleIdentityHostTable<Column extends string> {\n table: string\n columns: Record<Column, string>\n}\n\n/** Better Auth table and physical column names used by the identity store. */\nexport interface TangleIdentityHostSchema {\n user: TangleIdentityHostTable<'id' | 'name' | 'email' | 'emailVerified' | 'createdAt' | 'updatedAt'>\n session: TangleIdentityHostTable<'id' | 'userId' | 'token' | 'expiresAt' | 'ipAddress' | 'userAgent' | 'createdAt' | 'updatedAt'>\n account: TangleIdentityHostTable<'id' | 'userId' | 'accountId' | 'providerId' | 'createdAt' | 'updatedAt'>\n}\n\nexport interface D1TangleIdentityStoreOptions {\n db: TangleIdentityD1Like\n /** Physical Better Auth names. Default: singular tables with camelCase columns.\n * Custom account tables need the same two partial unique indexes, using their\n * mapped column names; the default index SQL only targets the default schema. */\n hostSchema?: TangleIdentityHostSchema\n /**\n * The signed-in local user for an explicit \"connect Tangle\" flow. A live\n * local session plus a verified platform exchange jointly authorize linking\n * that user, even when its local email is unverified or differs. The host\n * must prove the session started this flow (for example with a signed,\n * session-bound cookie).\n */\n linkingUserId?: string\n legacyLinkTable?: TangleIdentityLegacyLinkTable\n}\n\nconst SQL_IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/\n\nfunction identifier(value: string, field: string): string {\n if (!SQL_IDENTIFIER.test(value)) throw new Error(`createD1TangleIdentityStore: invalid ${field}`)\n return value\n}\n\nconst DEFAULT_HOST_SCHEMA = {\n user: {\n table: 'user',\n columns: { id: 'id', name: 'name', email: 'email', emailVerified: 'emailVerified', createdAt: 'createdAt', updatedAt: 'updatedAt' },\n },\n session: {\n table: 'session',\n columns: { id: 'id', userId: 'userId', token: 'token', expiresAt: 'expiresAt', ipAddress: 'ipAddress', userAgent: 'userAgent', createdAt: 'createdAt', updatedAt: 'updatedAt' },\n },\n account: {\n table: 'account',\n columns: { id: 'id', userId: 'userId', accountId: 'accountId', providerId: 'providerId', createdAt: 'createdAt', updatedAt: 'updatedAt' },\n },\n} satisfies TangleIdentityHostSchema\n\nfunction hostTable<Column extends string>(value: TangleIdentityHostTable<Column>, field: string): TangleIdentityHostTable<Column> {\n return {\n table: identifier(value.table, `${field}.table`),\n columns: Object.fromEntries((Object.entries(value.columns) as Array<[Column, string]>).map(([column, physical]) =>\n [column, identifier(physical, `${field}.columns.${column}`)])) as Record<Column, string>,\n }\n}\n\ninterface CandidateRow {\n userId: string\n email: string\n emailVerified: number | boolean | null\n accountPlatformUserId: string | null\n legacyPlatformUserId: string | null\n}\n\ninterface Candidate extends TangleSsoLocalAccount {\n /** The account row and the legacy row name different platform users. */\n divergent: boolean\n}\n\nfunction randomToken(): string {\n return Array.from(crypto.getRandomValues(new Uint8Array(32)), byte => byte.toString(16).padStart(2, '0')).join('')\n}\n\n/** Create the identity-protocol account store for one request. */\nexport function createD1TangleIdentityStore(options: D1TangleIdentityStoreOptions): TangleIdentitySsoAccountStore {\n const { db, linkingUserId } = options\n const provider = TANGLE_IDENTITY_PROVIDER_ID\n const host = options.hostSchema ?? DEFAULT_HOST_SCHEMA\n const userTable = hostTable(host.user, 'hostSchema.user')\n const sessionTable = hostTable(host.session, 'hostSchema.session')\n const accountTable = hostTable(host.account, 'hostSchema.account')\n const u = userTable.columns\n const s = sessionTable.columns\n const a = accountTable.columns\n const legacy = options.legacyLinkTable && {\n table: identifier(options.legacyLinkTable.table, 'legacyLinkTable.table'),\n userId: identifier(options.legacyLinkTable.userIdColumn, 'legacyLinkTable.userIdColumn'),\n platformUserId: identifier(options.legacyLinkTable.platformUserIdColumn, 'legacyLinkTable.platformUserIdColumn'),\n }\n\n const selectAccount = `SELECT u.${u.id} AS userId, u.${u.email} AS email, u.${u.emailVerified} AS emailVerified,\n a.${a.accountId} AS accountPlatformUserId,\n ${legacy ? `l.${legacy.platformUserId}` : 'NULL'} AS legacyPlatformUserId\n FROM ${userTable.table} u\n LEFT JOIN ${accountTable.table} a ON a.${a.userId} = u.${u.id} AND a.${a.providerId} = '${provider}'\n ${legacy ? `LEFT JOIN ${legacy.table} l ON l.${legacy.userId} = u.${u.id}` : ''}`\n\n function toCandidate(row: CandidateRow): Candidate {\n const fromAccount = row.accountPlatformUserId?.trim() || null\n const fromLegacy = row.legacyPlatformUserId?.trim() || null\n return {\n userId: row.userId,\n email: row.email,\n emailVerified: row.emailVerified === 1 || row.emailVerified === true,\n platformUserId: fromAccount ?? fromLegacy,\n divergent: Boolean(fromAccount && fromLegacy && fromAccount !== fromLegacy),\n }\n }\n\n async function candidates(email: string, platformUserId: string) {\n const where = legacy\n ? `WHERE lower(trim(u.${u.email})) = ? OR a.${a.accountId} = ? OR l.${legacy.platformUserId} = ?`\n : `WHERE lower(trim(u.${u.email})) = ? OR a.${a.accountId} = ?`\n const values = legacy ? [email, platformUserId, platformUserId] : [email, platformUserId]\n const { results } = await db.prepare(`${selectAccount} ${where}`).bind(...values).all<CandidateRow>()\n const rows = results.map(toCandidate)\n return {\n divergent: rows.some(row => row.divergent),\n platformMatches: rows.filter(row => row.platformUserId === platformUserId),\n emailMatches: rows.filter(row => normalizeTangleSsoEmail(row.email) === email),\n }\n }\n\n const store: TangleIdentitySsoAccountStore = {\n async resolveAccount({ email, platformUserId }): Promise<TangleSsoAccountResolution> {\n const normalizedEmail = normalizeTangleSsoEmail(email)\n const stableId = platformUserId.trim()\n const found = await candidates(normalizedEmail, stableId)\n if (found.divergent) return { kind: 'reject', reason: 'platform-id-email-conflict' }\n if (!linkingUserId) {\n return resolveTangleSsoAccount({\n email: normalizedEmail,\n platformUserId: stableId,\n platformMatches: found.platformMatches,\n emailMatches: found.emailMatches,\n })\n }\n\n const ownRow = await db.prepare(`${selectAccount} WHERE u.${u.id} = ?`).bind(linkingUserId).first<CandidateRow>()\n if (!ownRow) return { kind: 'reject', reason: 'email-match-mismatch' }\n const own = toCandidate(ownRow)\n if (own.divergent) return { kind: 'reject', reason: 'platform-id-email-conflict' }\n if (own.platformUserId && own.platformUserId !== stableId) {\n return { kind: 'reject', reason: 'email-platform-id-conflict' }\n }\n if (found.platformMatches.some(row => row.userId !== linkingUserId)\n || found.emailMatches.some(row => row.userId !== linkingUserId)) {\n return { kind: 'reject', reason: 'platform-id-email-conflict' }\n }\n return { kind: 'existing', userId: linkingUserId, matchedBy: 'platform-id' }\n },\n\n async upsertUserByEmail({ email, name, tangleUserId, resolution }) {\n const normalizedEmail = normalizeTangleSsoEmail(email)\n const platformUserId = tangleUserId.trim()\n const current = await store.resolveAccount({ email: normalizedEmail, platformUserId })\n if (current.kind === 'reject') throw new TangleSsoAccountConflictError(current.reason)\n if (current.kind === 'existing') {\n if (resolution.kind === 'existing' && resolution.userId !== current.userId) {\n throw new TangleSsoAccountConflictError('platform-id-email-conflict')\n }\n return { userId: current.userId }\n }\n\n if (resolution.kind !== 'create') throw new TangleSsoUserCreateError('The selected account changed')\n const userId = crypto.randomUUID()\n try {\n await db.prepare(`INSERT INTO ${userTable.table} (${u.id}, ${u.name}, ${u.email}, ${u.emailVerified}, ${u.createdAt}, ${u.updatedAt})\n VALUES (?, ?, ?, 1, unixepoch(), unixepoch())`)\n .bind(userId, name || normalizedEmail, normalizedEmail).run()\n } catch {\n // A concurrent callback may have won the email UNIQUE race. Re-apply the\n // policy; never adopt that row by email alone.\n const after = await store.resolveAccount({ email: normalizedEmail, platformUserId })\n if (after.kind === 'reject') throw new TangleSsoAccountConflictError(after.reason)\n if (after.kind === 'existing') return { userId: after.userId }\n throw new TangleSsoUserCreateError()\n }\n return { userId }\n },\n\n async createSession({ userId, expiresAt, ipAddress, userAgent }) {\n const token = randomToken()\n await db.prepare(`INSERT INTO ${sessionTable.table} (${s.id}, ${s.userId}, ${s.token}, ${s.expiresAt}, ${s.ipAddress}, ${s.userAgent}, ${s.createdAt}, ${s.updatedAt})\n VALUES (?, ?, ?, ?, ?, ?, unixepoch(), unixepoch())`)\n .bind(crypto.randomUUID(), userId, token, Math.floor(expiresAt.getTime() / 1000), ipAddress, userAgent)\n .run()\n return { token }\n },\n\n async saveTangleLink({ userId, sessionToken, tangleUserId, email }) {\n const platformUserId = tangleUserId.trim()\n const normalizedEmail = normalizeTangleSsoEmail(email)\n const session = await db.prepare(`SELECT ${s.userId} AS userId FROM ${sessionTable.table} WHERE ${s.token} = ? AND ${s.expiresAt} > unixepoch()`)\n .bind(sessionToken).first<{ userId: string }>()\n if (session?.userId !== userId) throw new TangleSsoAccountConflictError('email-platform-id-conflict')\n const current = await store.resolveAccount({ email: normalizedEmail, platformUserId })\n if (current.kind === 'reject') throw new TangleSsoAccountConflictError(current.reason)\n if (current.kind !== 'existing' || current.userId !== userId) {\n throw new TangleSsoAccountConflictError('platform-id-email-conflict')\n }\n\n // One atomic batch: every statement re-checks the live session and the\n // email owner, and the final verified-email update runs only when this\n // exact link exists, so a lost race commits nothing and rejects.\n const liveSession = `EXISTS (SELECT 1 FROM ${sessionTable.table} WHERE ${s.token} = ? AND ${s.userId} = ? AND ${s.expiresAt} > unixepoch())`\n const emailFree = `NOT EXISTS (SELECT 1 FROM ${userTable.table} WHERE lower(trim(${u.email})) = ? AND ${u.id} <> ?)`\n const linked = `EXISTS (SELECT 1 FROM ${accountTable.table} WHERE ${a.providerId} = '${provider}' AND ${a.userId} = ? AND ${a.accountId} = ?)`\n const statements = [\n db.prepare(`INSERT INTO ${accountTable.table} (${a.id}, ${a.userId}, ${a.accountId}, ${a.providerId}, ${a.createdAt}, ${a.updatedAt})\n SELECT ?, ?, ?, '${provider}', unixepoch(), unixepoch()\n WHERE EXISTS (SELECT 1 FROM ${userTable.table} WHERE ${u.id} = ?) AND ${liveSession} AND ${emailFree}\n ON CONFLICT DO NOTHING`)\n .bind(crypto.randomUUID(), userId, platformUserId, userId, sessionToken, userId, normalizedEmail, userId),\n ]\n if (legacy) {\n statements.push(db.prepare(`INSERT INTO ${legacy.table} (${legacy.userId}, ${legacy.platformUserId})\n SELECT ?, ? WHERE ${linked}\n ON CONFLICT DO NOTHING`)\n .bind(userId, platformUserId, userId, platformUserId))\n }\n statements.push(db.prepare(`UPDATE ${userTable.table} SET ${u.emailVerified} = CASE WHEN lower(trim(${u.email})) = ? THEN 1 ELSE ${u.emailVerified} END,\n ${u.updatedAt} = unixepoch()\n WHERE ${u.id} = ? AND ${liveSession} AND ${linked} AND ${emailFree}`)\n .bind(normalizedEmail, userId, sessionToken, userId, userId, platformUserId, normalizedEmail, userId))\n const results = await db.batch(statements)\n if (results[results.length - 1]?.meta?.changes !== 1) {\n throw new TangleSsoAccountConflictError('email-platform-id-conflict')\n }\n },\n\n // `saveTangleLink` is one atomic batch, so a rejected call wrote nothing;\n // removing the unpublished session is the whole cleanup.\n async deleteSession({ sessionToken }) {\n await db.prepare(`DELETE FROM ${sessionTable.table} WHERE ${s.token} = ?`).bind(sessionToken).run()\n },\n }\n return store\n}\n","/**\n * The OAuth return contract shared by the browser popup and the settings\n * server. The popup appends exactly these parameters to the host's callback\n * path; the server accepts a return URL only in that shape.\n */\nconst HUB_CONNECT_CALLBACK_PARAMS = ['provider', 'nonce', 'context'] as const\n\n/** True when `returnUrl` is the host's callback for `provider`, as the popup builds it. */\nexport function isHubConnectCallbackUrl(returnUrl: URL, callbackPath: string, provider: string): boolean {\n if (returnUrl.pathname !== callbackPath || returnUrl.hash) return false\n const keys = [...returnUrl.searchParams.keys()]\n if (keys.length !== HUB_CONNECT_CALLBACK_PARAMS.length) return false\n if (!HUB_CONNECT_CALLBACK_PARAMS.every((key) => returnUrl.searchParams.getAll(key).length === 1)) return false\n const opaque = (value: string | null) => !!value && value.length <= 128 && /^[A-Za-z0-9_-]+$/.test(value)\n return returnUrl.searchParams.get('provider') === provider\n && opaque(returnUrl.searchParams.get('nonce'))\n && opaque(returnUrl.searchParams.get('context'))\n}\n","/** Finite, application-authorized account settings over the existing Hub SDK. */\nimport { parseJsonObjectBody } from '../web/core'\nimport { isHubConnectCallbackUrl } from './hub-connect-callback'\n\n/** Non-secret API-key setup shapes supported by the Hub SDK. */\nexport type HubSettingsApiKeyMetadata =\n | { propertyId: string; currency?: string }\n | { listings: Array<{ id: string; pms: string }> }\n\n/** Browser OAuth setup, excluding CLI mode and identity/credential overrides. */\nexport interface HubSettingsOAuthInput {\n returnUrl: string\n connectionParameters?: Record<string, string>\n requestedScopes?: readonly string[]\n}\n\ntype PolicyDecision = 'allow' | 'ask' | 'deny'\n\n/**\n * Structural subset of the existing SDK, with no execution methods. Keeping\n * this structural avoids imposing a Hub SDK peer on existing platform imports.\n */\nexport interface HubSettingsClient {\n connections: {\n providers(): Promise<unknown>\n list(): Promise<unknown>\n start(provider: string, input: HubSettingsOAuthInput): Promise<unknown>\n connectApiKey(provider: string, apiKey: string, metadata?: HubSettingsApiKeyMetadata): Promise<unknown>\n revoke(connectionId: string): Promise<unknown>\n health(connectionId: string): Promise<unknown>\n }\n tools: {\n search(query: string, options: { provider: string; limit: number }): Promise<unknown>\n }\n permissions: {\n list(connectionId: string): Promise<unknown>\n set(input: { connectionId: string; actionPath: string; decision: PolicyDecision }): Promise<unknown>\n delete(input: { connectionId: string; actionPath: string }): Promise<unknown>\n }\n}\n\n/** Validated, exact intent. The provider API key is deliberately not copied here. */\nexport type HubSettingsOperation =\n | { readonly operation: 'providers.list' | 'connections.list'; readonly target: 'caller-account' }\n | { readonly operation: 'oauth.start'; readonly provider: string; readonly input: Readonly<HubSettingsOAuthInput> }\n | { readonly operation: 'api-key.connect'; readonly provider: string; readonly metadata?: HubSettingsApiKeyMetadata }\n | { readonly operation: 'connection.revoke' | 'connection.health' | 'policies.list'; readonly connectionId: string }\n | { readonly operation: 'provider.actions'; readonly provider: string; readonly query: string; readonly limit: number }\n | { readonly operation: 'policy.set'; readonly connectionId: string; readonly actionPath: string; readonly decision: PolicyDecision }\n | { readonly operation: 'policy.reset'; readonly connectionId: string; readonly actionPath: string }\n\n/** Server-derived application identity, not fields read from browser input. */\nexport interface HubSettingsPrincipal {\n readonly userId: string\n readonly sessionId: string\n readonly workspaceId: string\n}\n\nexport interface HubSettingsGrant {\n readonly authorized: true\n readonly principal: HubSettingsPrincipal\n}\n\nexport interface HubSettingsClientBinding {\n readonly client: HubSettingsClient\n /** Reassert the identity against which the credential was actually resolved. */\n readonly principal: HubSettingsPrincipal\n /** Never env/admin credentials, another owner's key, or a brokered execution token. */\n readonly credentialSource: 'caller-account'\n}\n\nexport interface HubSettingsContext {\n /** Application-owned mount path, without a trailing slash. Default /api/hub/settings. */\n basePath?: string\n /**\n * Local path of the page that renders `HubConnectCallbackPage`. When set, an\n * OAuth start must return to exactly this path with the provider, nonce and\n * context that the integrations panel adds, and nothing else.\n */\n oauthCallbackPath?: string\n /**\n * Required on EVERY valid operation, including reads. Validate the current\n * session, CSRF protection, workspace role and exact target/decision here.\n * Return a denial Response or throw the app's auth Response to reject.\n * The body has been consumed; use the validated intent, not request.json().\n * OAuth success, connection ownership/policy, app consent and workspace\n * binding are separate facts. An execution grant is not a settings grant.\n */\n authorize(request: Request, operation: HubSettingsOperation): Promise<HubSettingsGrant | Response>\n /** Called only after authorization. Resolve the caller's linked account SDK client server-side. */\n resolveClient(principal: HubSettingsPrincipal): Promise<HubSettingsClientBinding>\n}\n\nexport interface HubSettingsRoutes {\n /** Exact method/path allowlist under basePath; never forwards request headers or arbitrary paths. */\n handle(request: Request): Promise<Response>\n}\n\nfunction json(value: unknown, status = 200, headers: Record<string, string> = {}): Response {\n return Response.json(value, { status, headers: { 'Cache-Control': 'no-store', ...headers } })\n}\n\nfunction invalid(): never {\n // Do not reflect request values: API keys and OAuth parameters can be sensitive.\n throw json({ error: 'Invalid Hub settings request', code: 'HUB_INVALID_INPUT' }, 400)\n}\n\nfunction record(value: unknown): Record<string, unknown> {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) invalid()\n return value as Record<string, unknown>\n}\n\nfunction onlyKeys(value: Record<string, unknown>, allowed: readonly string[]): void {\n if (Object.keys(value).some((key) => !allowed.includes(key))) invalid()\n}\n\nfunction text(value: unknown, max = 256): string {\n if (typeof value !== 'string' || !value.trim() || value.length > max || /[\\u0000-\\u001f\\u007f]/.test(value)) invalid()\n return value\n}\n\nfunction identifier(value: unknown): string {\n const id = text(value, 128)\n if (!/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(id)) invalid()\n return id\n}\n\nfunction action(value: unknown): string {\n const path = text(value)\n // An exact dotted action, never a provider wildcard, path, glob or pattern.\n if (!/^[A-Za-z0-9_-]+(?:\\.[A-Za-z0-9_-]+)+$/.test(path)) invalid()\n return path\n}\n\nfunction metadata(value: unknown): HubSettingsApiKeyMetadata {\n const input = record(value)\n if ('propertyId' in input) {\n onlyKeys(input, ['propertyId', 'currency'])\n return { propertyId: text(input.propertyId), ...(input.currency === undefined ? {} : { currency: text(input.currency) }) }\n }\n onlyKeys(input, ['listings'])\n if (!Array.isArray(input.listings) || input.listings.length === 0 || input.listings.length > 200) invalid()\n return { listings: input.listings.map((item) => {\n const listing = record(item)\n onlyKeys(listing, ['id', 'pms'])\n return { id: text(listing.id), pms: text(listing.pms) }\n }) }\n}\n\nfunction oauthInput(body: Record<string, unknown>, url: URL, provider: string, callbackPath: string | undefined): HubSettingsOAuthInput {\n onlyKeys(body, ['returnUrl', 'connectionParameters', 'requestedScopes'])\n const returnUrl = text(body.returnUrl, 2048)\n let destination: URL\n try { destination = new URL(returnUrl) } catch { invalid() }\n if (!['https:', 'http:'].includes(destination.protocol) || destination.origin !== url.origin || destination.username || destination.password) invalid()\n if (callbackPath !== undefined && !isHubConnectCallbackUrl(destination, callbackPath, provider)) invalid()\n const input: HubSettingsOAuthInput = { returnUrl }\n if (body.connectionParameters !== undefined) {\n const parameters = record(body.connectionParameters)\n if (Object.keys(parameters).length > 20) invalid()\n input.connectionParameters = Object.fromEntries(Object.entries(parameters).map(([key, value]) => {\n identifier(key)\n // These are non-secret provider setup values, never Hub auth or identity overrides.\n if (/^(?:user|userid|owner|ownerid|workspace|workspaceid|team|teamid|principal|principalid|session|sessionid|authorization|headers|cookie|apikey|token|accesstoken|refreshtoken|clientsecret|secret|credentials?|appid|clientid)$/.test(key.replace(/[_-]/g, '').toLowerCase())) invalid()\n return [key, text(value, 1024)]\n }))\n }\n if (body.requestedScopes !== undefined) {\n if (!Array.isArray(body.requestedScopes) || body.requestedScopes.length === 0 || body.requestedScopes.length > 100) invalid()\n input.requestedScopes = body.requestedScopes.map(scope => text(scope, 2048))\n if (new Set(input.requestedScopes).size !== input.requestedScopes.length) invalid()\n }\n return input\n}\n\nfunction query(url: URL, allowed: readonly string[]): void {\n for (const key of url.searchParams.keys()) {\n if (!allowed.includes(key) || url.searchParams.getAll(key).length !== 1) invalid()\n }\n}\n\nasync function body(request: Request): Promise<Record<string, unknown>> {\n if ((request.headers.get('content-type')?.split(';')[0] ?? '').trim().toLowerCase() !== 'application/json') {\n throw json({ error: 'Expected application/json', code: 'HUB_INVALID_INPUT' }, 415)\n }\n const [value, error] = await parseJsonObjectBody(request, { maxBytes: 64 * 1024 })\n if (error) { error.headers.set('Cache-Control', 'no-store'); throw error }\n return value\n}\n\n/** Snapshot nested intent before application callbacks can observe it. */\nfunction freeze<T>(value: T): T {\n if (value !== null && typeof value === 'object') {\n for (const child of Object.values(value)) freeze(child)\n Object.freeze(value)\n }\n return value\n}\n\nfunction isPrincipal(value: unknown): value is HubSettingsPrincipal {\n if (value === null || typeof value !== 'object') return false\n const principal = value as Partial<HubSettingsPrincipal>\n return [principal.userId, principal.sessionId, principal.workspaceId].every((part) => typeof part === 'string' && part.trim().length > 0)\n}\n\ninterface Prepared {\n intent: HubSettingsOperation\n call(client: HubSettingsClient): Promise<unknown>\n}\n\nconst ROUTES = [\n { kind: 'providers', path: /^\\/providers$/, methods: ['GET'] },\n { kind: 'connections', path: /^\\/connections$/, methods: ['GET'] },\n { kind: 'oauth', path: /^\\/connections\\/([^/]+)\\/start$/, methods: ['POST'] },\n { kind: 'api-key', path: /^\\/connections\\/([^/]+)\\/connect-key$/, methods: ['POST'] },\n { kind: 'revoke', path: /^\\/connections\\/([^/]+)$/, methods: ['DELETE'] },\n { kind: 'health', path: /^\\/connections\\/([^/]+)\\/health$/, methods: ['POST'] },\n { kind: 'actions', path: /^\\/providers\\/([^/]+)\\/actions$/, methods: ['GET'] },\n { kind: 'policies', path: /^\\/policies$/, methods: ['GET', 'PUT', 'DELETE'] },\n] as const\n\nasync function prepare(request: Request, basePath: string, callbackPath: string | undefined): Promise<Prepared | Response> {\n const url = new URL(request.url)\n if (!url.pathname.startsWith(`${basePath}/`)) return json({ error: 'Not found' }, 404)\n const path = url.pathname.slice(basePath.length)\n const route = ROUTES.find((candidate) => candidate.path.test(path))\n if (!route) return json({ error: 'Not found' }, 404)\n if (!(route.methods as readonly string[]).includes(request.method)) {\n return json({ error: 'Method not allowed' }, 405, { Allow: route.methods.join(', ') })\n }\n const target = route.path.exec(path)?.[1]\n const isPolicyRead = route.kind === 'policies' && request.method === 'GET'\n const isActions = route.kind === 'actions'\n query(url, isPolicyRead ? ['connectionId'] : isActions ? ['query', 'limit'] : [])\n const hasJson = route.kind === 'oauth' || route.kind === 'api-key' || (route.kind === 'policies' && !isPolicyRead)\n if (!hasJson && request.body !== null) {\n // Workers may expose an empty body stream for a bodyless POST.\n const reader = request.body.getReader()\n let emptyChunks = 0\n try {\n for (;;) {\n const chunk = await reader.read()\n if (chunk.done) break\n if (chunk.value.byteLength > 0) invalid()\n // Limit empty chunks before authorization; bodyless requests reach EOF.\n if (++emptyChunks > 16) invalid()\n }\n } finally {\n await reader.cancel().catch(() => undefined)\n reader.releaseLock()\n }\n }\n\n if (route.kind === 'providers') return { intent: { operation: 'providers.list', target: 'caller-account' }, call: (hub) => hub.connections.providers() }\n if (route.kind === 'connections') return { intent: { operation: 'connections.list', target: 'caller-account' }, call: (hub) => hub.connections.list() }\n if (isPolicyRead) {\n const connectionId = identifier(url.searchParams.get('connectionId'))\n return { intent: { operation: 'policies.list', connectionId }, call: (hub) => hub.permissions.list(connectionId) }\n }\n if (route.kind === 'policies') {\n const input = await body(request)\n onlyKeys(input, request.method === 'PUT' ? ['connectionId', 'actionPath', 'decision'] : ['connectionId', 'actionPath'])\n const connectionId = identifier(input.connectionId)\n const actionPath = action(input.actionPath)\n if (request.method === 'DELETE') return { intent: { operation: 'policy.reset', connectionId, actionPath }, call: (hub) => hub.permissions.delete({ connectionId, actionPath }) }\n const decision = input.decision\n if (decision !== 'allow' && decision !== 'ask' && decision !== 'deny') invalid()\n return { intent: { operation: 'policy.set', connectionId, actionPath, decision }, call: (hub) => hub.permissions.set({ connectionId, actionPath, decision }) }\n }\n const id = identifier(target)\n if (isActions) {\n const search = url.searchParams.get('query') ?? ''\n if (search.length > 512 || /[\\u0000-\\u001f\\u007f]/.test(search)) invalid()\n const rawLimit = url.searchParams.get('limit') ?? '200'\n if (!/^[1-9][0-9]*$/.test(rawLimit)) invalid()\n const limit = Number(rawLimit)\n if (limit > 200) invalid()\n return { intent: { operation: 'provider.actions', provider: id, query: search, limit }, call: (hub) => hub.tools.search(search, { provider: id, limit }) }\n }\n if (route.kind === 'oauth') {\n const input = freeze(oauthInput(await body(request), url, id, callbackPath))\n return { intent: { operation: 'oauth.start', provider: id, input }, call: (hub) => hub.connections.start(id, input) }\n }\n if (route.kind === 'api-key') {\n const input = await body(request)\n onlyKeys(input, ['apiKey', 'metadata'])\n const apiKey = text(input.apiKey, 16 * 1024)\n const setup = input.metadata === undefined ? undefined : freeze(metadata(input.metadata))\n return { intent: { operation: 'api-key.connect', provider: id, ...(setup === undefined ? {} : { metadata: setup }) }, call: (hub) => hub.connections.connectApiKey(id, apiKey, setup) }\n }\n if (route.kind === 'health') return { intent: { operation: 'connection.health', connectionId: id }, call: (hub) => hub.connections.health(id) }\n if (route.kind === 'revoke') return { intent: { operation: 'connection.revoke', connectionId: id }, call: (hub) => hub.connections.revoke(id) }\n return invalid()\n}\n\n/** Build the finite, application-authorized Hub settings server boundary. */\nexport function createHubSettingsRoutes(ctx: HubSettingsContext): HubSettingsRoutes {\n if (typeof ctx.authorize !== 'function' || typeof ctx.resolveClient !== 'function') {\n throw new TypeError('Hub settings requires authorize and resolveClient callbacks')\n }\n const basePath = ctx.basePath ?? '/api/hub/settings'\n if (!/^\\/(?:[A-Za-z0-9_-]+\\/)*[A-Za-z0-9_-]+$/.test(basePath)) throw new TypeError('Invalid Hub settings basePath')\n const callbackPath = ctx.oauthCallbackPath\n if (callbackPath !== undefined && !/^\\/(?:[A-Za-z0-9_-]+\\/)*[A-Za-z0-9_-]+$/.test(callbackPath)) throw new TypeError('Invalid Hub OAuth callback path')\n\n return { async handle(request) {\n let prepared: Prepared | Response\n try { prepared = await prepare(request, basePath, callbackPath) } catch (error) {\n if (error instanceof Response) return error\n throw error\n }\n if (prepared instanceof Response) return prepared\n // Auth throws intentionally propagate. No SDK/client lookup has occurred.\n const grant = await ctx.authorize(request, freeze(prepared.intent))\n if (grant instanceof Response) return grant\n if (grant?.authorized !== true || !isPrincipal(grant.principal)) {\n return json({ error: 'Hub settings authorization required', code: 'HUB_FORBIDDEN' }, 403)\n }\n const principal = Object.freeze({ userId: grant.principal.userId, sessionId: grant.principal.sessionId, workspaceId: grant.principal.workspaceId })\n try {\n const bound = await ctx.resolveClient(principal)\n if (bound?.credentialSource !== 'caller-account' || !isPrincipal(bound.principal) ||\n bound.principal.userId !== principal.userId || bound.principal.sessionId !== principal.sessionId || bound.principal.workspaceId !== principal.workspaceId) {\n return json({ error: 'Hub settings caller binding mismatch', code: 'HUB_FORBIDDEN' }, 403)\n }\n // Client resolution can outlive a session or role grant. Recheck before the Hub effect.\n const renewed = await ctx.authorize(request, prepared.intent)\n if (renewed instanceof Response) return renewed\n if (renewed?.authorized !== true || !isPrincipal(renewed.principal) ||\n renewed.principal.userId !== principal.userId || renewed.principal.sessionId !== principal.sessionId || renewed.principal.workspaceId !== principal.workspaceId) {\n return json({ error: 'Hub settings authorization required', code: 'HUB_FORBIDDEN' }, 403)\n }\n return json(await prepared.call(bound.client))\n } catch (error) {\n // Structural detection survives SDK copies without a runtime peer import.\n if (error instanceof Error && error.name === 'HubSdkError' && typeof (error as { code?: unknown }).code === 'string') {\n const { code, status } = error as Error & { code: string; status?: number }\n const fallback = code === 'HUB_INVALID_INPUT' ? 400 : code === 'HUB_UNAUTHENTICATED' ? 401 : code === 'HUB_FORBIDDEN' ? 403 : 502\n const httpStatus = typeof status === 'number' && Number.isInteger(status) && status >= 400 && status <= 599 ? status : fallback\n // Never echo upstream details/message: they can contain submitted credentials.\n return json({ error: 'Hub settings request failed', code }, httpStatus)\n }\n throw error\n }\n } }\n}\n","/**\n * Platform billing HTTP transport + tier state for apps on the shared\n * Tangle balance model (id.tangle.tools). Reads authenticate as the user via\n * their per-user platform key (the platform resolves the caller from the\n * key; service or impersonation headers on read routes are rejected). The\n * deduct write authenticates as the product service (`Bearer <serviceToken>`\n * + `X-Service-Name`) and names the target user in the body. Also provides a\n * fetch-backed implementation of the `/billing` module's\n * `PlatformBillingClient` seam (type-only import — no runtime coupling).\n */\n\nimport type { PlatformBillingClient, PlatformIdentity } from '../billing/index'\nimport { resolveTangleExecutionEnvironment } from '../runtime/model'\n\n/** Define available subscription tiers for the TanglePlan service */\nexport type TanglePlanTier = 'free' | 'pro' | 'enterprise'\n\n/** 'pro' | 'enterprise' pass through; anything else (null, unknown) → 'free'. */\nexport function normalizeTanglePlanTier(plan: string | null | undefined): TanglePlanTier {\n return plan === 'pro' || plan === 'enterprise' ? plan : 'free'\n}\n\n/** Represent platform billing HTTP errors with status code and detailed message */\nexport class PlatformBillingHttpError extends Error {\n constructor(\n readonly status: number,\n detail: string,\n ) {\n super(`Platform request failed (${status}): ${detail}`)\n this.name = 'PlatformBillingHttpError'\n }\n}\n\n/** Structural guard (name + numeric status) — robust across module instances. */\nexport function isPlatformBillingHttpError(error: unknown): error is PlatformBillingHttpError {\n return (\n error instanceof Error &&\n error.name === 'PlatformBillingHttpError' &&\n typeof (error as { status?: unknown }).status === 'number'\n )\n}\n\n/** Define HTTP options for platform billing including base URL, service token, product slug, fetch implementation, and timeout */\nexport interface PlatformBillingHttpOptions {\n /** Platform root, e.g. https://id.tangle.tools (trailing slashes stripped). */\n baseUrl: string\n /** Used only by `deduct()`; resolved lazily so reads never require it.\n * Throws at call time when empty. Default: the deployment's\n * `PLATFORM_SERVICE_TOKEN`. */\n serviceToken?: string | (() => string | undefined)\n /** Product slug — the `X-Service-Name` header and the deduct `product` field. */\n productSlug: string\n fetchImpl?: typeof fetch\n /** Default 10 000. */\n timeoutMs?: number\n}\n\n/** Describe subscription tier and status information for a platform user */\nexport interface PlatformSubscriptionInfo {\n tier: TanglePlanTier\n status: string | null\n}\n\n/** Describe the platform balance and lifetime spending with an optional update timestamp */\nexport interface PlatformBalanceSnapshot {\n balance: number\n lifetimeSpent: number\n updatedAt?: string\n}\n\n/** Describe a product's usage and spending metrics on the platform */\nexport interface PlatformUsageProductRow {\n product: string | null\n totalSpent: number\n count: number\n}\n\n/** Lifecycle of a per-product seat subscription, mirroring the Stripe states\n * the platform persists. 'none' = the user has never held this seat. */\nexport type SeatStatus = 'none' | 'active' | 'trialing' | 'past_due' | 'canceled'\n\n/** Price and included shared-wallet credit for one seat billing period. */\nexport interface ProductSeatOfferPeriod {\n priceCents: number\n includedCreditsCents: number\n}\n\n/** Commercial terms returned by the platform's product catalog. Products use\n * this exact object for display instead of duplicating prices in UI copy. */\nexport interface ProductSeatOffer {\n currency: 'usd'\n interval: 'month'\n recurring: ProductSeatOfferPeriod\n introductory: ProductSeatOfferPeriod | null\n}\n\n/**\n * Per-product entitlement snapshot from the platform — the single read that\n * tells a product whether to show its workspace or the seat paywall. Shape\n * matches `GET /v1/billing/product-entitlement?product=<id>`.\n *\n * `hasSeat` is computed platform-side from the raw seat row.\n * It is true for an active or trialing seat whose period has not lapsed.\n * `onFreeTier` remains in the wire shape for compatibility, but this client\n * always returns false and never uses it for access.\n */\nexport interface ProductEntitlement {\n seatStatus: SeatStatus\n /** ISO timestamp the active seat's paid period runs until; null when none. */\n currentPeriodEnd: string | null\n /** Cumulative inference spend across the whole suite, in dollars. */\n lifetimeSpentUsd: number\n hasSeat: boolean\n /** Platform access decision, including funded balance and identity policy. */\n paidAccess?: boolean\n onFreeTier: boolean\n /** Present when the platform exposes catalog-backed commercial terms. */\n offer?: ProductSeatOffer\n}\n\nfunction productSeatOffer(value: unknown): ProductSeatOffer | undefined {\n if (!value || typeof value !== 'object') return undefined\n const candidate = value as Record<string, unknown>\n if (candidate.currency !== 'usd' || candidate.interval !== 'month') return undefined\n\n const period = (input: unknown, allowZeroPrice: boolean): ProductSeatOfferPeriod | undefined => {\n if (!input || typeof input !== 'object') return undefined\n const data = input as Record<string, unknown>\n const priceCents = data.priceCents\n const includedCreditsCents = data.includedCreditsCents\n if (\n typeof priceCents !== 'number' ||\n !Number.isSafeInteger(priceCents) ||\n (allowZeroPrice ? priceCents < 0 : priceCents <= 0) ||\n typeof includedCreditsCents !== 'number' ||\n !Number.isSafeInteger(includedCreditsCents) ||\n includedCreditsCents < 0\n ) {\n return undefined\n }\n return { priceCents, includedCreditsCents }\n }\n\n const recurring = period(candidate.recurring, false)\n const introductory =\n candidate.introductory === null\n ? null\n : period(candidate.introductory, true)\n if (!recurring || introductory === undefined) return undefined\n return {\n currency: 'usd',\n interval: 'month',\n recurring,\n introductory,\n }\n}\n\n/** Define methods to interact with platform billing endpoints using user or service authentication */\nexport interface PlatformBillingHttp {\n /** GET /v1/plans/current (user bearer). */\n getSubscription(userApiKey: string): Promise<PlatformSubscriptionInfo>\n /** GET /v1/billing/balance (user bearer). */\n getBalance(userApiKey: string): Promise<PlatformBalanceSnapshot>\n /** GET /v1/billing/usage (user bearer). */\n getUsageByProduct(userApiKey: string): Promise<PlatformUsageProductRow[]>\n /** GET /v1/billing/product-entitlement?product=<id> (user bearer). */\n getProductEntitlement(userApiKey: string, productId: string): Promise<ProductEntitlement>\n /** POST /v1/billing/deduct (service token). Platform refuses a deduct without\n * `keyId`, the id of a key the charged user owns (their sign-in key). */\n deduct(input: {\n platformUserId: string\n amountUsd: number\n type: string\n description: string\n referenceId: string\n keyId?: string\n }): Promise<void>\n /** Absolute URL of the platform's billing-management surface. */\n billingUrl(): string\n /** Absolute URL of the catalog-backed seat checkout for `productId`. */\n seatCheckoutUrl(productId: string): string\n}\n\n/** Create a PlatformBillingHttp instance configured with given options and default behaviors */\nexport function createPlatformBillingHttp(opts: PlatformBillingHttpOptions): PlatformBillingHttp {\n const baseUrl = opts.baseUrl.replace(/\\/+$/, '')\n if (!baseUrl) throw new Error('PlatformBillingHttpOptions.baseUrl is required')\n if (!opts.productSlug) throw new Error('PlatformBillingHttpOptions.productSlug is required')\n const fetchImpl = opts.fetchImpl ?? fetch\n const timeoutMs = opts.timeoutMs ?? 10_000\n\n function resolveServiceToken(): string {\n if (opts.serviceToken === undefined) {\n const token = (typeof process !== 'undefined' ? process.env.PLATFORM_SERVICE_TOKEN : undefined)?.trim()\n if (!token) throw new Error('PLATFORM_SERVICE_TOKEN is required for platform billing calls')\n return token\n }\n const token = typeof opts.serviceToken === 'function' ? opts.serviceToken() : opts.serviceToken\n if (!token) throw new Error('A platform service token is required for deduct')\n return token\n }\n\n async function request<T>(path: string, init: RequestInit, headers: Headers): Promise<T> {\n const res = await fetchImpl(`${baseUrl}${path}`, {\n ...init,\n headers,\n signal: AbortSignal.timeout(timeoutMs),\n })\n if (!res.ok) {\n const body = (await res.json().catch(() => null)) as { error?: { message?: string } } | null\n throw new PlatformBillingHttpError(res.status, body?.error?.message ?? res.statusText)\n }\n return res.json() as Promise<T>\n }\n\n function userRead<T>(userApiKey: string, path: string): Promise<T> {\n const headers = new Headers()\n headers.set('Authorization', `Bearer ${userApiKey}`)\n return request<T>(path, {}, headers)\n }\n\n return {\n async getSubscription(userApiKey) {\n const body = await userRead<{\n success: boolean\n data?: { subscription?: { plan?: string | null; status?: string | null } | null }\n }>(userApiKey, '/v1/plans/current')\n const sub = body.data?.subscription ?? null\n return { tier: normalizeTanglePlanTier(sub?.plan), status: sub?.status ?? null }\n },\n\n async getBalance(userApiKey) {\n const body = await userRead<{\n success: boolean\n data?: { balance?: number; lifetimeSpent?: number; updatedAt?: string }\n }>(userApiKey, '/v1/billing/balance')\n return {\n balance: body.data?.balance ?? 0,\n lifetimeSpent: body.data?.lifetimeSpent ?? 0,\n updatedAt: body.data?.updatedAt,\n }\n },\n\n async getUsageByProduct(userApiKey) {\n const body = await userRead<{\n success: boolean\n data?: Array<{ product?: string | null; totalSpent?: number; count?: number }>\n }>(userApiKey, '/v1/billing/usage')\n return (body.data ?? []).map((row) => ({\n product: row.product ?? null,\n totalSpent: row.totalSpent ?? 0,\n count: row.count ?? 0,\n }))\n },\n\n async getProductEntitlement(userApiKey, productId) {\n const slug = encodeURIComponent(productId)\n const body = await userRead<{\n success: boolean\n data?: {\n seatStatus?: SeatStatus | null\n currentPeriodEnd?: string | null\n lifetimeSpentUsd?: number | null\n hasSeat?: boolean | null\n paidAccess?: unknown\n onFreeTier?: boolean | null\n offer?: unknown\n }\n }>(userApiKey, `/v1/billing/product-entitlement?product=${slug}`)\n const data = body.data ?? {}\n const hasSeat = data.hasSeat === true\n const offer = productSeatOffer(data.offer)\n return {\n seatStatus: data.seatStatus ?? 'none',\n currentPeriodEnd: data.currentPeriodEnd ?? null,\n lifetimeSpentUsd: data.lifetimeSpentUsd ?? 0,\n hasSeat,\n ...('paidAccess' in data ? { paidAccess: data.paidAccess === true } : {}),\n // Product-funded free access is retired. Ignore stale server signals.\n onFreeTier: false,\n ...(offer ? { offer } : {}),\n }\n },\n\n async deduct(input) {\n const headers = new Headers()\n headers.set('Authorization', `Bearer ${resolveServiceToken()}`)\n headers.set('X-Service-Name', opts.productSlug)\n headers.set('Content-Type', 'application/json')\n await request('/v1/billing/deduct', {\n method: 'POST',\n body: JSON.stringify({\n userId: input.platformUserId,\n amount: input.amountUsd,\n type: input.type,\n product: opts.productSlug,\n description: input.description,\n referenceId: input.referenceId,\n ...(input.keyId ? { keyId: input.keyId } : {}),\n }),\n }, headers)\n },\n\n billingUrl() {\n return `${baseUrl}/app/billing`\n },\n\n seatCheckoutUrl(productId) {\n return seatCheckoutUrl(baseUrl, productId)\n },\n }\n}\n\n/**\n * Platform Stripe checkout URL for a product's catalog-backed seat. The\n * platform resolves the product-specific price and introductory offer from the\n * `product` query param. Mirrors the `billingUrl()` shape — a deterministic\n * platform-rooted URL with no client-side pricing decisions.\n */\nexport function seatCheckoutUrl(baseUrl: string, productId: string): string {\n const root = baseUrl.replace(/\\/+$/, '')\n return `${root}/app/billing/seat/checkout?product=${encodeURIComponent(productId)}`\n}\n\n// ── Tier policy + composed state ────────────────────────────────────────────\n\n/** Define policy settings for concurrency and overage allowance in a tangle tier */\nexport interface TangleTierPolicy {\n concurrency: number\n overageAllowed: boolean\n}\n\n/** Define default concurrency and overage policies for each TanglePlanTier level */\nexport const DEFAULT_TANGLE_TIER_POLICY: Record<TanglePlanTier, TangleTierPolicy> = {\n free: { concurrency: 1, overageAllowed: false },\n pro: { concurrency: Number.POSITIVE_INFINITY, overageAllowed: true },\n enterprise: { concurrency: Number.POSITIVE_INFINITY, overageAllowed: true },\n}\n\n/** Describe the state of a Tangle plan tier including subscription, balance, spending, and concurrency details */\nexport interface TangleTierState {\n tier: TanglePlanTier\n subscriptionStatus: string | null\n remainingBalanceUsd: number\n lifetimeSpentUsd: number\n concurrency: number\n overageAllowed: boolean\n}\n\n/**\n * Read subscription + balance and project them onto the tier policy. A\n * null/absent key fails CLOSED (free tier, zero balance) — a billable run is\n * never started against an unknown balance. Platform errors throw; callers\n * on the billable path choose their posture explicitly.\n */\nexport async function readTangleTierState(\n http: PlatformBillingHttp,\n userApiKey: string | null | undefined,\n policy: Record<TanglePlanTier, TangleTierPolicy> = DEFAULT_TANGLE_TIER_POLICY,\n): Promise<TangleTierState> {\n if (!userApiKey) {\n return {\n tier: 'free',\n subscriptionStatus: null,\n remainingBalanceUsd: 0,\n lifetimeSpentUsd: 0,\n ...policy.free,\n }\n }\n const [subscription, balance] = await Promise.all([\n http.getSubscription(userApiKey),\n http.getBalance(userApiKey),\n ])\n return {\n tier: subscription.tier,\n subscriptionStatus: subscription.status,\n remainingBalanceUsd: balance.balance,\n lifetimeSpentUsd: balance.lifetimeSpent,\n ...policy[subscription.tier],\n }\n}\n\n// ── Per-product seat entitlement ────────────────────────────────────────────\n\n/** Product-funded free inference spend is disabled. */\nexport const FREE_TIER_SPEND_CAP_USD = 0\n\n/**\n * Default name of the per-app feature flag that controls seat billing.\n * Explicit values override the environment default.\n */\nexport const DEFAULT_SEAT_BILLING_ENABLED_ENV_VAR = 'SEAT_BILLING_ENABLED'\n\n/** Define options to configure seat billing flag environment variables and override flag name */\nexport interface SeatBillingFlagOptions {\n env?: Record<string, string | undefined>\n /** Override the flag name; default {@link DEFAULT_SEAT_BILLING_ENABLED_ENV_VAR}. */\n flagEnvVar?: string\n}\n\n/**\n * An explicit flag controls seat billing in every environment.\n * Without a flag, known development and test environments default to OFF.\n * Deployed and unknown environments default to ON.\n */\nexport function isSeatBillingEnabled(opts: SeatBillingFlagOptions = {}): boolean {\n const env =\n opts.env ??\n (typeof process !== 'undefined' ? (process.env as Record<string, string | undefined>) : undefined)\n if (!env) return true\n const flag = env[opts.flagEnvVar ?? DEFAULT_SEAT_BILLING_ENABLED_ENV_VAR]?.trim().toLowerCase()\n if (flag) return !['false', '0', 'off', 'disabled', 'no'].includes(flag)\n const environment = resolveTangleExecutionEnvironment(env)\n return environment !== 'development' && environment !== 'test'\n}\n\n/**\n * Read a user's entitlement for one product.\n * An absent key or disabled flag returns no access.\n * Transport failures propagate so the product can return a retryable error.\n *\n * @param flag — pass {@link isSeatBillingEnabled} (or your own boolean) so the\n * product owns when the gate engages. When false, no network call is made.\n */\nexport async function getProductEntitlement(\n http: Pick<PlatformBillingHttp, 'getProductEntitlement'>,\n userApiKey: string | null | undefined,\n productId: string,\n flag = true,\n): Promise<ProductEntitlement> {\n if (!flag) return unavailableEntitlement()\n if (!userApiKey) return unavailableEntitlement()\n return http.getProductEntitlement(userApiKey, productId)\n}\n\nfunction unavailableEntitlement(): ProductEntitlement {\n return {\n seatStatus: 'none',\n currentPeriodEnd: null,\n lifetimeSpentUsd: 0,\n hasSeat: false,\n onFreeTier: false,\n }\n}\n\n/** Honor platform access policy; older endpoints provide only seat authority. */\nexport function isProductEntitled(ent: ProductEntitlement): boolean {\n return ent.paidAccess === undefined ? ent.hasSeat === true : ent.paidAccess === true\n}\n\n// ── Bridge onto the /billing seam ───────────────────────────────────────────\n\n/** Define a contract for resolving platform identities based on user identifiers */\nexport interface PlatformIdentityStore {\n resolveIdentity(userId: string): Promise<PlatformIdentity | null>\n}\n\n/** Concrete fetch-backed `PlatformBillingClient<TanglePlanTier>` for\n * `createPlatformBalanceManager` (from `/billing`). */\nexport function createTanglePlatformBillingClient(\n http: PlatformBillingHttp,\n identity: PlatformIdentityStore,\n): PlatformBillingClient<TanglePlanTier> {\n return {\n resolveIdentity: (userId) => identity.resolveIdentity(userId),\n getPlan: async (apiKey) => (await http.getSubscription(apiKey)).tier,\n getBalance: async (apiKey) => {\n const snapshot = await http.getBalance(apiKey)\n return { balance: snapshot.balance, lifetimeSpent: snapshot.lifetimeSpent }\n },\n getUsageByProduct: (apiKey) => http.getUsageByProduct(apiKey),\n deduct: (input) => http.deduct(input),\n }\n}\n","/**\n * Bill work an agent app runs for a Platform agent key to that key's one cap.\n *\n * The cap is shared across every product and is spent even when the owner\n * already has their own credential in the app:\n *\n * - Model calls: `modelKey` delegates a spend-through Router key, which Router\n * refuses once the cap is spent.\n * - Other work, such as sandbox compute the owner's credential pays for: `hold`\n * reserves its maximum before it starts, and `consume` spends what it\n * measured, up to the hold, without charging the owner's wallet again.\n *\n * A spent or insufficient cap answers 402 `agent_key.budget_exhausted`; any\n * other refusal keeps Platform's code. Web-standard fetch only.\n */\n\nexport interface AgentSpendRefusal {\n status: 402 | 403 | 503\n code: string\n message: string\n /** Platform's own error code for a refusal this client does not type. */\n platformCode?: string\n}\n\nexport type AgentSpendOutcome<T> =\n | { succeeded: true; value: T }\n | { succeeded: false; error: AgentSpendRefusal }\n\nexport interface PlatformAgentSpendOptions {\n /** Platform origin, e.g. `https://id.tangle.tools`. */\n platformUrl: string\n /** This app's Platform service name. */\n serviceName: string\n serviceToken: string | (() => string)\n /** The Platform product this app bills, e.g. `gtm-agent`. */\n product: string\n fetch?: typeof fetch\n}\n\nexport interface PlatformAgentSpend {\n /**\n * A Router key whose charges spend the agent key's cap. `name` must start\n * `auto:`; give each piece of work its own.\n */\n modelKey(input: { agentKey: string; name: string; expiresAt: Date }): Promise<AgentSpendOutcome<{ key: string; keyId: string | null }>>\n /** Reserve up to `amountUsd` of the agent key's cap for work billed elsewhere. */\n hold(input: { keyId: string; amountUsd: number; referenceId: string; expiresAt: Date }): Promise<AgentSpendOutcome<{ authorizationId: string }>>\n /** Spend what the work measured, at most the hold. A retry repeats the amount. */\n consume(input: { authorizationId: string; amountUsd: number }): Promise<AgentSpendOutcome<{ consumedUsd: number }>>\n /** Return a hold whose work never ran. */\n release(authorizationId: string): Promise<AgentSpendOutcome<null>>\n}\n\nconst REQUEST_TIMEOUT_MS = 10_000\n\nfunction refusal(status: number, error?: PlatformBody['error']): AgentSpendRefusal {\n const code = error?.code\n if (code === 'KEY_BUDGET_EXHAUSTED' || code === 'KEY_BUDGET_EXCEEDED' || code === 'PRODUCT_BUDGET_EXCEEDED') {\n return { status: 402, code: 'agent_key.budget_exhausted', message: 'The key has spent, or cannot cover, the cap its owner approved.' }\n }\n if (code === 'INSUFFICIENT_BALANCE') {\n return { status: 402, code: 'agent_key.payment_required', message: \"The key owner's Tangle account has no credit.\" }\n }\n if (code === 'EMAIL_VERIFICATION_REQUIRED') {\n return { status: 403, code: 'agent_key.owner_unverified', message: 'The key owner must verify their Tangle email.' }\n }\n if (status >= 500 || status === 429 || code === 'PLATFORM_BUSY') {\n return { status: 503, code: 'agent_key.spend_unavailable', message: 'Platform could not record the spend; retry.' }\n }\n // Carry Platform's cause (e.g. AUTHORIZATION_CONFLICT and its message), never a credential.\n const platformCode = typeof code === 'string' && /^[A-Z][A-Z0-9_]{0,63}$/.test(code) ? code : undefined\n const detail = typeof error?.message === 'string' ? error.message.replace(/\\b(?:sk-tan-|svc_)[\\w-]+/g, '[redacted]').slice(0, 240) : ''\n const cause = [platformCode, detail].filter(Boolean).join(': ')\n return { status: 403, code: 'agent_key.spend_refused', message: `Platform refused to bill this work to the key${cause ? ` (${cause})` : ''}.`, ...(platformCode ? { platformCode } : {}) }\n}\n\ninterface PlatformBody {\n success?: unknown\n data?: { key?: unknown; id?: unknown; consumedAmount?: unknown }\n error?: { code?: unknown; message?: unknown }\n}\n\nexport function createPlatformAgentSpend(options: PlatformAgentSpendOptions): PlatformAgentSpend {\n const fetchImpl = options.fetch ?? fetch\n const base = options.platformUrl.replace(/\\/+$/, '')\n\n async function call(path: string, body: unknown): Promise<{ status: number; body: PlatformBody } | null> {\n const token = typeof options.serviceToken === 'function' ? options.serviceToken() : options.serviceToken\n try {\n const response = await fetchImpl(`${base}${path}`, {\n method: 'POST',\n headers: {\n authorization: `Bearer ${token}`,\n 'x-service-name': options.serviceName,\n 'content-type': 'application/json',\n },\n body: JSON.stringify(body),\n redirect: 'manual',\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),\n })\n return { status: response.status, body: (await response.json().catch(() => ({}))) as PlatformBody }\n } catch {\n return null\n }\n }\n\n const unavailable = (): { succeeded: false; error: AgentSpendRefusal } => ({ succeeded: false, error: refusal(503) })\n\n return {\n async modelKey({ agentKey, name, expiresAt }) {\n const result = await call('/v1/keys/delegate', {\n sourceKey: agentKey, name, product: 'router', spendThrough: true, expiresAt: expiresAt.toISOString(),\n })\n if (!result) return unavailable()\n const key = result.body.data?.key\n if (result.status !== 201 || typeof key !== 'string') {\n return { succeeded: false, error: refusal(result.status, result.body.error) }\n }\n const keyId = result.body.data?.id\n return { succeeded: true, value: { key, keyId: typeof keyId === 'string' ? keyId : null } }\n },\n async hold({ keyId, amountUsd, referenceId, expiresAt }) {\n const result = await call('/v1/billing/authorizations', {\n keyId, amount: amountUsd, type: 'key_cap', product: options.product, referenceId, expiresAt: expiresAt.toISOString(),\n })\n if (!result) return unavailable()\n const id = result.body.data?.id\n if (result.status !== 201 || typeof id !== 'string') {\n return { succeeded: false, error: refusal(result.status, result.body.error) }\n }\n return { succeeded: true, value: { authorizationId: id } }\n },\n async consume({ authorizationId, amountUsd }) {\n const result = await call(`/v1/billing/authorizations/${encodeURIComponent(authorizationId)}/consume`, { amount: amountUsd })\n if (!result) return unavailable()\n const consumed = result.body.data?.consumedAmount\n if (result.status !== 200 || typeof consumed !== 'number') {\n return { succeeded: false, error: refusal(result.status, result.body.error) }\n }\n return { succeeded: true, value: { consumedUsd: consumed } }\n },\n async release(authorizationId) {\n const result = await call(`/v1/billing/authorizations/${encodeURIComponent(authorizationId)}/release`, {})\n if (!result) return unavailable()\n if (result.status !== 200) return { succeeded: false, error: refusal(result.status, result.body.error) }\n return { succeeded: true, value: null }\n },\n }\n}\n","/**\n * Record a person's consent that this app's Sandbox service key may bill them.\n *\n * An app that creates sandboxes under its own service key and names the\n * signed-in person as `billingOwnerId` needs that person's billing delegation\n * grant, or the Sandbox API refuses the create with\n * `BILLING_DELEGATION_GRANT_REQUIRED`. Platform records the grant from the key\n * the person gave the app at sign-in (`POST /v1/keys/billing-delegation-grants`),\n * so the app records it before its first delegated create. The call is\n * idempotent on Platform.\n *\n * A refusal answers a typed code and a message written for the person, so an\n * app can show it as is. Web-standard fetch only.\n */\n\nexport interface BillingConsentRefusal {\n status: 402 | 403 | 503\n code: 'billing_consent.payer_not_chargeable' | 'billing_consent.refused' | 'billing_consent.unavailable'\n /** Written for the person whose account would pay. */\n message: string\n /** Platform's own code, for logs. */\n platformCode: string | null\n}\n\nexport type BillingConsentOutcome =\n | { succeeded: true; value: { created: boolean } }\n | { succeeded: false; error: BillingConsentRefusal }\n\nexport interface PlatformBillingConsentOptions {\n /** Platform origin, e.g. `https://id.tangle.tools`. */\n platformUrl: string\n /** This app's Platform service name. */\n serviceName: string\n serviceToken: string | (() => string)\n fetch?: typeof fetch\n}\n\nexport interface PlatformBillingConsent {\n /**\n * Record that the owner of `payerKey` consents to `serviceKey` billing them\n * for sandboxes. `payerKey` is the key the person gave this app at sign-in;\n * `serviceKey` is the listed key the app creates sandboxes under.\n */\n consent(input: { payerKey: string; serviceKey: string }): Promise<BillingConsentOutcome>\n}\n\nconst REQUEST_TIMEOUT_MS = 10_000\n\nconst notChargeable: BillingConsentRefusal = {\n status: 402,\n code: 'billing_consent.payer_not_chargeable',\n message: 'Your Tangle account has no credit for sandbox use yet. Add credit in your Tangle account, then open the terminal again.',\n platformCode: 'PAYER_NOT_CHARGEABLE',\n}\n\nfunction refusal(status: number | null, platformCode: string | null): BillingConsentRefusal {\n if (platformCode === 'PAYER_NOT_CHARGEABLE') return notChargeable\n if (status === null || status >= 500 || status === 429) {\n return {\n status: 503,\n code: 'billing_consent.unavailable',\n message: 'Tangle could not record your sandbox billing consent right now. Try again in a moment.',\n platformCode,\n }\n }\n return {\n status: 403,\n code: 'billing_consent.refused',\n message: 'Tangle did not accept your sign-in for sandbox billing. Sign out and sign in again.',\n platformCode,\n }\n}\n\ninterface PlatformBody {\n data?: { id?: unknown; created?: unknown }\n error?: { code?: unknown }\n}\n\nexport function createPlatformBillingConsent(options: PlatformBillingConsentOptions): PlatformBillingConsent {\n const fetchImpl = options.fetch ?? fetch\n const base = options.platformUrl.replace(/\\/+$/, '')\n // Resolved values only: a cancelled request never settles, so a shared\n // in-flight promise would hang every later caller.\n let delegate: { serviceKey: string; keyId: string } | null = null\n\n async function request(path: string, init: RequestInit): Promise<{ status: number; body: PlatformBody } | null> {\n try {\n const response = await fetchImpl(`${base}${path}`, {\n ...init,\n redirect: 'manual',\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),\n })\n return { status: response.status, body: (await response.json().catch(() => ({}))) as PlatformBody }\n } catch {\n return null\n }\n }\n\n const codeOf = (body: PlatformBody): string | null => (typeof body.error?.code === 'string' ? body.error.code : null)\n\n return {\n async consent({ payerKey, serviceKey }) {\n if (delegate?.serviceKey !== serviceKey) {\n const self = await request('/v1/keys/self', { headers: { authorization: `Bearer ${serviceKey}` } })\n const keyId = self?.body.data?.id\n if (!self || self.status !== 200 || typeof keyId !== 'string' || !keyId) {\n return { succeeded: false, error: refusal(self ? Math.max(self.status, 500) : null, self ? codeOf(self.body) : null) }\n }\n delegate = { serviceKey, keyId }\n }\n const token = typeof options.serviceToken === 'function' ? options.serviceToken() : options.serviceToken\n const result = await request('/v1/keys/billing-delegation-grants', {\n method: 'POST',\n headers: {\n authorization: `Bearer ${token}`,\n 'x-service-name': options.serviceName,\n 'content-type': 'application/json',\n },\n body: JSON.stringify({ sourceKey: payerKey, delegateKeyId: delegate.keyId }),\n })\n if (!result) return { succeeded: false, error: refusal(null, null) }\n if (result.status === 200 || result.status === 201) {\n return { succeeded: true, value: { created: result.status === 201 } }\n }\n const platformCode = codeOf(result.body)\n // The service key's own account pays for itself and needs no grant.\n if (platformCode === 'PAYER_IS_DELEGATE_OWNER') return { succeeded: true, value: { created: false } }\n return { succeeded: false, error: refusal(result.status, platformCode) }\n },\n }\n}\n","/**\n * Where this deployment reaches the Tangle platform, read from its environment\n * at call time so a Worker's bindings are current.\n */\n\n/**\n * The platform base URL: `TANGLE_PLATFORM_URL`, or the legacy `TANGLE_SSO_URL`\n * until every environment is migrated.\n */\nconst env = (): Record<string, string | undefined> =>\n (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env ?? {}\n\nexport function platformBaseUrlFromEnv(): string {\n const url = env().TANGLE_PLATFORM_URL ?? env().TANGLE_SSO_URL\n if (!url) throw new Error('TANGLE_PLATFORM_URL is required (or legacy TANGLE_SSO_URL)')\n return url\n}\n\n/**\n * Options for the platform's cross-site SSO client: the base URL, the app id\n * registered in the platform's trusted-apps registry (`TANGLE_PLATFORM_APP_ID`,\n * else the product's own), and a fetch the client can call as a method. A\n * Worker's `fetch` stored on an instance and called as `this.fetchImpl()`\n * throws \"Illegal invocation\", so the global is wrapped in a free call.\n */\nexport function platformAuthClientOptionsFromEnv(\n defaultAppId: string,\n overrides: { baseUrl?: string; appId?: string; fetchImpl?: typeof fetch } = {},\n): { baseUrl: string; appId: string; fetchImpl: typeof fetch } {\n return {\n baseUrl: overrides.baseUrl ?? platformBaseUrlFromEnv(),\n appId: overrides.appId ?? env().TANGLE_PLATFORM_APP_ID ?? defaultAppId,\n fetchImpl: overrides.fetchImpl ?? ((input, init) => globalThis.fetch(input, init)),\n }\n}\n","/**\n * Delegated product keys: a child key minted from the paying user's linked\n * Tangle key, scoped to one product, its models and its budget, so an app\n * never sends the user's own key to Router or Sandbox.\n *\n * WHY ONE. Seven apps minted these by hand (Tax, Legal, GTM, Creative,\n * Builder, Hardware, workcomp; survey) with different scope,\n * expiry and revocation rules, and four never noticed a key Platform had\n * revoked, superseded or expired.\n *\n * THREE WAYS TO HOLD ONE.\n * - Per turn: `client.delegate` before the turn, `client.revoke` after it.\n * Nothing is cached, so nothing stale can be handed out.\n * - Pre-minted per turn: `createDelegatedTurnKeys` (`./delegated-turn-keys`) gives each turn its own\n * child, same cap and expiry, but mints the next turn's child in the\n * background and parks it in D1, so the ~320 ms mint leaves the turn's\n * critical path. A parked key is taken exactly once; anything else mints\n * inline as before.\n * - Per workspace: `createDelegatedKeyProvisioner` plugs this client into\n * `createIdentityBoundWorkspaceKeyManager` (`./billing`), which owns the\n * durable, lease-fenced slot. Its `getKey` asks Platform's\n * `verify-by-id`, which also refuses superseded generations, and reports\n * any key that is not valid as missing, so the manager marks it revoked\n * and mints a fresh one on the next use.\n *\n * THE MINT CONTRACT (`POST /v1/keys/delegate`, service-authenticated; the\n * response is the key row plus `attribution`, and the granted expiry is\n * `attribution.expiresAt`). The child is checked field by field: an\n * `sk-tan-` key that is not the source, the canonical name, this service as\n * provisioner and attribution origin, the requested product, resource, model\n * set and payer, a budget no larger than requested, and an expiry in the\n * future and no later than requested. A child that fails is revoked and\n * refused; if that revoke fails too, the refusal carries the child's id (never\n * its key) so the app can retire it.\n *\n * Errors carry a code and status, never a response body, a source key or a\n * child key.\n */\n\nimport { platformBaseUrlFromEnv } from './deployment'\n\nconst REQUEST_TIMEOUT_MS = 10_000\n// Backoff while Platform cannot answer a delegation: 250 ms doubling to 5 s, with jitter.\nconst UNAVAILABLE_BASE_DELAY_MS = 250\nconst UNAVAILABLE_MAX_DELAY_MS = 5_000\nconst KEY_PREFIX = 'sk-tan-'\nconst AUTO_PREFIX = 'auto:'\n/** Products whose key names Platform qualifies as `auto:<service>:<product>:...` (key-provenance.ts). */\nconst PRODUCT_QUALIFIED = new Set(['router', 'sandbox'])\n\nexport type DelegatedKeyCode =\n | 'delegated_key.payment_required'\n | 'delegated_key.budget_exhausted'\n | 'delegated_key.owner_unverified'\n | 'delegated_key.unavailable'\n | 'delegated_key.refused'\n | 'delegated_key.failed'\n | 'delegated_key.response_invalid'\n | 'delegated_key.invalid_request'\n | 'delegated_key.slot_not_revoked'\n\nexport interface DelegatedKeyRefusal {\n status: number\n code: DelegatedKeyCode\n message: string\n /** Set when an untrusted child could not be revoked: the id (never the key) the app must retire. */\n unrevokedKeyId?: string\n /** Platform's own error code (never its message) for a decision this client does not type, for logs. */\n platformCode?: string\n}\n\nexport type DelegatedKeyOutcome<T> =\n | { succeeded: true; value: T }\n | { succeeded: false; error: DelegatedKeyRefusal }\n\n/** How the child is paid for: its own budget, or spending the source's budget directly. */\nexport type DelegatedKeyBudget =\n | { usd: number; monthlyUsd?: number }\n | { spendThrough: true; monthlyUsd?: number }\n\nexport interface DelegatedKeyRequest {\n /** The payer's linked `sk-tan-` key. Never a shared app key. */\n sourceKey: string\n /** The logical slot, e.g. `turn:<id>`. Sent as Platform's canonical name; see {@link canonicalDelegatedKeyName}.\n * A slot holds one key: a new delegation under the same name revokes (or supersedes) the key holding it\n * (Platform key-provisioning `revokeKeySubtrees`). Two attempts that may run at once, such as a transport retry\n * beside the attempt it replaces, need distinct names, or the second revokes the first mid-turn. */\n name: string\n product: 'router' | 'sandbox' | (string & {})\n resource?: { type: string; id: string }\n /** The only models the child may call. */\n allowedModels?: readonly string[]\n budget?: DelegatedKeyBudget\n rpmLimit?: number\n expiresAt: Date\n /** Checked against the child's attribution when given: the payer's Platform user id, the source key's id, and\n * the origin app Platform carries over from the source (an app's SSO key; a personal key has none). */\n expect?: { payerId?: string; sourceKeyId?: string; originAppId?: string | null }\n /**\n * Keep asking while Platform answers `delegated_key.unavailable` (no answer, 5xx, 429, busy), with jittered\n * backoff, for at most `forMs` from the first attempt; then return that refusal. Platform's origin was unreachable\n * for 84.8 s and 54.5 s across restarts, and each such failure ended a member's Router turn, so a\n * turn-scoped mint passes about 90 000 here, inside its turn's budget. `signal` stops the wait early. A retried\n * request may have reached Platform; the next attempt uses the same name, so it replaces that child in its slot\n * rather than leaving a second one.\n */\n retryUnavailable?: { forMs: number; signal?: AbortSignal }\n}\n\nexport interface DelegatedKey {\n key: string\n id: string\n /** The canonical name Platform stored. */\n name: string\n product: string\n /** The expiry Platform granted (`attribution.expiresAt`), never later than requested. */\n expiresAt: Date\n allowedModels: readonly string[] | null\n budgetUsd: number | null\n}\n\nexport interface PlatformDelegatedKeyClientOptions {\n /** Platform origin. Default: TANGLE_PLATFORM_URL or TANGLE_SSO_URL from the request environment. */\n platformUrl?: string\n /** This app's Platform service name; Platform admits delegation per named service. */\n serviceName: string\n /** Default: lazily read PLATFORM_SERVICE_TOKEN; missing configuration fails closed. */\n serviceToken?: string | (() => string)\n fetch?: typeof fetch\n now?: () => number\n}\n\n/** Platform's `verify-by-id` verdict on one key, secret-free. */\nexport interface DelegatedKeyVerdict {\n valid: boolean\n /** Platform's reason when not valid, e.g. `key_revoked`, `budget_exhausted`. */\n invalidReason?: string\n budgetUsd?: number\n budgetRemaining?: number\n expiresAt?: string\n}\n\n/**\n * Identifies a key's slot for Platform's service-authenticated `revoke-slot`. Without `name`, `product` or\n * `sourceKeyId`, the client reads them from the key itself (`GET /v1/keys/:id`, which an SSO source may\n * call; the child's parent is its source key), so a provisioner restarted since the mint can still retire\n * the key. Health, Tax and Legal bind the slot to its source key; GTM and Builder admit `revoke-slot` only\n * for their protected and preview keys, so their other keys keep the refused DELETE as a typed error.\n */\nexport interface DelegatedKeySlotRef {\n userId: string\n name?: string\n product?: string\n sourceKeyId?: string\n}\n\nexport interface PlatformDelegatedKeyClient {\n delegate(request: DelegatedKeyRequest): Promise<DelegatedKeyOutcome<DelegatedKey>>\n /** Platform's authoritative verdict (`verify-by-id`), including revoked, expired and spent keys. */\n verify(input: { keyId: string; product: string }): Promise<DelegatedKeyOutcome<DelegatedKeyVerdict>>\n /**\n * `DELETE /v1/keys/:id` with the source key; a key already gone counts as revoked. Platform refuses key\n * mutations from a service-provisioned source (an app's SSO key) or a sibling source with 403, and a source it no\n * longer accepts with 401; given `slot`, the client then retires the slot through `revoke-slot` with the service\n * token. A `revoke-slot` that revokes nothing is a 409 `delegated_key.slot_not_revoked` refusal.\n */\n revoke(input: { sourceKey: string; keyId: string; slot?: DelegatedKeySlotRef }): Promise<DelegatedKeyOutcome<null>>\n /** Children of the source key in one slot, from `GET /v1/keys` with the source key. */\n listChildren(input: { sourceKey: string; name: string; product: string }): Promise<DelegatedKeyOutcome<Array<{ id: string }>>>\n}\n\n/**\n * The name Platform stores for a slot: `auto:<service>:<product>:<logical>` for\n * Router and Sandbox keys (Platform's `canonicalProvisionedKeyName`), so the\n * echo can be checked exactly. A name already qualified is kept.\n */\nexport function canonicalDelegatedKeyName(input: { serviceName: string; product: string; name: string }): string {\n const logical = input.name.startsWith(AUTO_PREFIX) ? input.name.slice(AUTO_PREFIX.length) : input.name\n if (!PRODUCT_QUALIFIED.has(input.product)) return `${AUTO_PREFIX}${logical}`\n if (logical.startsWith(`${input.serviceName}:${input.product}:`)) return `${AUTO_PREFIX}${logical}`\n const withoutService = logical.startsWith(`${input.serviceName}:`) ? logical.slice(input.serviceName.length + 1) : logical\n return `${AUTO_PREFIX}${input.serviceName}:${input.product}:${withoutService}`\n}\n\nfunction refusal(status: number, code: unknown): DelegatedKeyRefusal {\n if (code === 'INSUFFICIENT_BALANCE') {\n return { status: 402, code: 'delegated_key.payment_required', message: \"The payer's Tangle account has no credit.\" }\n }\n if (code === 'KEY_BUDGET_EXHAUSTED' || code === 'KEY_BUDGET_EXCEEDED' || code === 'PRODUCT_BUDGET_EXCEEDED') {\n return { status: 402, code: 'delegated_key.budget_exhausted', message: \"The payer's key has spent the budget it allows.\" }\n }\n if (code === 'EMAIL_VERIFICATION_REQUIRED') {\n return { status: 403, code: 'delegated_key.owner_unverified', message: 'The payer must verify their Tangle email.' }\n }\n if (status >= 500 || status === 429 || code === 'PLATFORM_BUSY') {\n return { status: 503, code: 'delegated_key.unavailable', message: 'Platform could not answer; retry.' }\n }\n // Only an authorization answer is a refusal. Any other 4xx is a decision about this request (Platform's\n // 400 DELEGATION_FAILED, say), kept as its own status with Platform's code so it is not mistaken for\n // a credential problem. The message stays out: it can name Platform internals.\n const platformCode = typeof code === 'string' && /^[A-Z][A-Z0-9_]{0,63}$/.test(code) ? code : undefined\n if (status === 401 || status === 403 || status < 400) {\n return { status: 403, code: 'delegated_key.refused', message: 'Platform refused to delegate this key.', ...(platformCode ? { platformCode } : {}) }\n }\n return {\n status,\n code: 'delegated_key.failed',\n message: `Platform declined this delegation${platformCode ? ` (${platformCode})` : ''}.`,\n ...(platformCode ? { platformCode } : {}),\n }\n}\n\nconst failure = <T,>(status: number, code: DelegatedKeyCode, message: string, extra: Partial<DelegatedKeyRefusal> = {}): DelegatedKeyOutcome<T> =>\n ({ succeeded: false, error: { status, code, message, ...extra } })\n\nconst record = (value: unknown): Record<string, unknown> | null =>\n value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : null\n\nfunction sameSet(granted: unknown, requested: readonly string[]): boolean {\n if (!Array.isArray(granted) || granted.some(model => typeof model !== 'string')) return false\n const a = [...new Set(granted as string[])].sort()\n const b = [...new Set(requested)].sort()\n return granted.length === a.length && a.length === b.length && a.every((model, index) => model === b[index])\n}\n\n/** Why the minted child cannot be trusted, or null. Each check names its field, never its value. */\nfunction childProblem(data: Record<string, unknown>, request: DelegatedKeyRequest, name: string, serviceName: string, nowMs: number): string | null {\n const key = data.key\n const id = data.id\n if (typeof id !== 'string' || !id) return 'no key id'\n if (typeof key !== 'string' || !key.startsWith(KEY_PREFIX) || key.length <= KEY_PREFIX.length) return 'not an sk-tan child key'\n if (key === request.sourceKey) return 'the source key itself'\n if (typeof data.prefix === 'string' && !key.startsWith(data.prefix)) return 'a key that does not match its prefix'\n if (data.name !== name) return 'a different name'\n if (data.product !== request.product) return 'a different product'\n if (data.provisionedByService !== serviceName) return 'a different provisioner'\n if (data.scopes !== null && !(Array.isArray(data.scopes) && data.scopes.length === 0)) return 'control-plane scopes'\n // Omitted, the child inherits the source's model restriction, which only narrows it.\n if (request.allowedModels && !sameSet(data.allowedModels, request.allowedModels)) return 'a different model set'\n const budget = request.budget\n if (budget && 'usd' in budget && !(typeof data.budgetUsd === 'number' && data.budgetUsd <= budget.usd)) return 'a budget larger than requested'\n if (budget?.monthlyUsd !== undefined && !(typeof data.monthlyBudgetUsd === 'number' && data.monthlyBudgetUsd <= budget.monthlyUsd)) {\n return 'a monthly budget larger than requested'\n }\n\n const attribution = record(data.attribution)\n if (!attribution) return 'no attribution'\n if (attribution.version !== 1 || attribution.targetService !== request.product) return 'attribution for another target'\n if (request.expect?.originAppId !== undefined && (attribution.originAppId ?? null) !== request.expect.originAppId) {\n return 'attribution from another app'\n }\n const parent = attribution.delegatedFromKeyId\n if (typeof parent !== 'string' || !parent || parent === id) return 'attribution without its parent key'\n if (request.expect?.sourceKeyId !== undefined && parent !== request.expect.sourceKeyId) return 'attribution for another source key'\n if (attribution.payerType !== 'user') return 'attribution to a non-user payer'\n if (request.expect?.payerId !== undefined && attribution.payerId !== request.expect.payerId) return 'attribution to another payer'\n if ((attribution.resourceType ?? null) !== (request.resource?.type ?? null) || (attribution.resourceId ?? null) !== (request.resource?.id ?? null)) {\n return 'attribution for another resource'\n }\n const expiresAt = typeof attribution.expiresAt === 'string' ? Date.parse(attribution.expiresAt) : NaN\n if (!Number.isFinite(expiresAt) || expiresAt <= nowMs || expiresAt > request.expiresAt.getTime()) return 'an expiry in the past or past the request'\n return null\n}\n\nexport function createPlatformDelegatedKeyClient(options: PlatformDelegatedKeyClientOptions): PlatformDelegatedKeyClient {\n const fetchImpl = options.fetch ?? fetch\n const now = options.now ?? Date.now\n const env = () => (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env\n const origin = options.platformUrl ?? platformBaseUrlFromEnv()\n const base = options.platformUrl ? origin.replace(/\\/+$/, '') : new URL(origin).origin\n const serviceToken = () => {\n if (options.serviceToken !== undefined) return typeof options.serviceToken === 'function' ? options.serviceToken() : options.serviceToken\n const token = env()?.PLATFORM_SERVICE_TOKEN?.trim()\n if (!token) throw new Error('PLATFORM_SERVICE_TOKEN is required for delegated product keys')\n return token\n }\n\n async function call(path: string, init: { method: string; bearer: string; service: boolean; body?: unknown }) {\n try {\n const response = await fetchImpl(`${base}${path}`, {\n method: init.method,\n headers: {\n authorization: `Bearer ${init.bearer}`,\n ...(init.service ? { 'x-service-name': options.serviceName } : {}),\n ...(init.body === undefined ? {} : { 'content-type': 'application/json' }),\n },\n ...(init.body === undefined ? {} : { body: JSON.stringify(init.body) }),\n redirect: 'manual',\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),\n })\n return { status: response.status, body: record(await response.json().catch(() => null)) }\n } catch {\n return null\n }\n }\n\n async function delegateOnce(request: DelegatedKeyRequest): Promise<DelegatedKeyOutcome<DelegatedKey>> {\n if (!request.sourceKey.startsWith(KEY_PREFIX)) return failure(400, 'delegated_key.invalid_request', 'The source must be a linked sk-tan- key.')\n if (request.expiresAt.getTime() <= now()) return failure(400, 'delegated_key.invalid_request', 'The expiry must be in the future.')\n const name = canonicalDelegatedKeyName({ serviceName: options.serviceName, product: request.product, name: request.name })\n const budget = request.budget\n const result = await call('/v1/keys/delegate', {\n method: 'POST', bearer: serviceToken(), service: true, body: {\n sourceKey: request.sourceKey,\n name,\n product: request.product,\n ...(request.resource ? { resourceType: request.resource.type, resourceId: request.resource.id } : {}),\n ...(budget && 'usd' in budget ? { budgetUsd: budget.usd } : {}),\n ...(budget && 'spendThrough' in budget ? { spendThrough: true } : {}),\n ...(budget?.monthlyUsd !== undefined ? { monthlyBudgetUsd: budget.monthlyUsd } : {}),\n ...(request.allowedModels ? { allowedModels: [...new Set(request.allowedModels)] } : {}),\n ...(request.rpmLimit !== undefined ? { rpmLimit: request.rpmLimit } : {}),\n // Omitted, Platform copies the source's scopes onto the child; a product key carries none.\n scopes: [],\n expiresAt: request.expiresAt.toISOString(),\n },\n })\n if (!result) return { succeeded: false, error: refusal(503, null) }\n const data = record(result.body?.data)\n if (result.status !== 201 || result.body?.success !== true || !data) {\n return { succeeded: false, error: refusal(result.status, record(result.body?.error)?.code) }\n }\n const problem = childProblem(data, request, name, options.serviceName, now())\n if (problem) {\n // A child Platform minted but this app cannot trust is retired, never returned.\n const id = typeof data.id === 'string' && data.id ? data.id : null\n const owner = request.expect?.payerId\n ? { userId: request.expect.payerId, name, product: request.product,\n ...(request.expect.sourceKeyId ? { sourceKeyId: request.expect.sourceKeyId } : {}) }\n : undefined\n const revoked = id ? await client.revoke({ sourceKey: request.sourceKey, keyId: id, ...(owner ? { slot: owner } : {}) }) : null\n return failure(502, 'delegated_key.response_invalid', `Platform returned ${problem}.`,\n id && !revoked?.succeeded ? { unrevokedKeyId: id } : {})\n }\n const attribution = record(data.attribution)!\n return { succeeded: true, value: {\n key: data.key as string, id: data.id as string, name, product: request.product,\n expiresAt: new Date(attribution.expiresAt as string),\n allowedModels: request.allowedModels ? [...new Set(request.allowedModels)] : null,\n budgetUsd: typeof data.budgetUsd === 'number' ? data.budgetUsd : null,\n } }\n }\n\n /** Wait before the next attempt, or answer false when the window or the signal says stop. */\n async function backoff(attempt: number, deadline: number, signal: AbortSignal | undefined): Promise<boolean> {\n const delay = Math.min(UNAVAILABLE_MAX_DELAY_MS, UNAVAILABLE_BASE_DELAY_MS * 2 ** attempt) * (0.5 + Math.random() / 2)\n if (signal?.aborted || Date.now() + delay > deadline) return false\n await new Promise<void>((resolve) => {\n const timer = setTimeout(resolve, delay)\n signal?.addEventListener('abort', () => { clearTimeout(timer); resolve() }, { once: true })\n })\n return !signal?.aborted\n }\n\n const client: PlatformDelegatedKeyClient = {\n async delegate(request) {\n const retry = request.retryUnavailable\n const deadline = Date.now() + Math.max(0, retry?.forMs ?? 0)\n for (let attempt = 0; ; attempt++) {\n const outcome = await delegateOnce(request)\n if (outcome.succeeded || outcome.error.code !== 'delegated_key.unavailable' || !retry) return outcome\n if (!(await backoff(attempt, deadline, retry.signal))) return outcome\n }\n },\n\n async verify({ keyId, product }) {\n const result = await call('/v1/keys/verify-by-id', {\n method: 'POST', bearer: serviceToken(), service: true, body: { keyId, expectedProduct: product },\n })\n // Fail closed: anything but a well-formed verdict for this key is not evidence about it.\n if (!result || result.status >= 500 || result.status === 429) return { succeeded: false, error: refusal(503, null) }\n const body = result.body\n if (result.status !== 200 || typeof body?.valid !== 'boolean' || (body.valid && body.keyId !== keyId)) {\n return failure(502, 'delegated_key.response_invalid', 'Platform returned no verification verdict for this key.')\n }\n const number = (value: unknown) => typeof value === 'number' && Number.isFinite(value) ? value : undefined\n return { succeeded: true, value: {\n valid: body.valid,\n ...(typeof body.invalidReason === 'string' ? { invalidReason: body.invalidReason } : {}),\n ...(number(body.budgetUsd) !== undefined ? { budgetUsd: number(body.budgetUsd) } : {}),\n ...(number(body.budgetRemaining) !== undefined ? { budgetRemaining: number(body.budgetRemaining) } : {}),\n ...(typeof body.expiresAt === 'string' ? { expiresAt: body.expiresAt } : {}),\n } }\n },\n\n async revoke({ sourceKey, keyId, slot }) {\n const result = await call(`/v1/keys/${encodeURIComponent(keyId)}`, { method: 'DELETE', bearer: sourceKey, service: false })\n if (!result) return { succeeded: false, error: refusal(503, null) }\n if (result.status === 404 || (result.status >= 200 && result.status < 300 && result.body?.success === true)) {\n return { succeeded: true, value: null }\n }\n if ((result.status === 403 || result.status === 401) && slot) {\n let { name, product, sourceKeyId } = slot\n if (!name || !product || !sourceKeyId) {\n const row = await call(`/v1/keys/${encodeURIComponent(keyId)}`, { method: 'GET', bearer: sourceKey, service: false })\n if (row?.status === 404) return { succeeded: true, value: null }\n const data = row?.status === 200 ? record(row.body?.data) : null\n if (data?.revokedAt) return { succeeded: true, value: null }\n const text = (value: unknown) => typeof value === 'string' && value ? value : undefined\n name ||= text(data?.name)\n product ||= text(data?.product)\n // The child's parent is the source key a source-bound slot names.\n sourceKeyId ||= text(data?.parentKeyId)\n if (!name || !product) return { succeeded: false, error: refusal(row?.status ?? 503, null) }\n }\n // Platform checks the `auto:` prefix before it canonicalizes, so a logical slot name is sent canonical.\n const retired = await call('/v1/keys/auto-provisioned/revoke-slot', {\n method: 'POST', bearer: serviceToken(), service: true, body: {\n userId: slot.userId, name: canonicalDelegatedKeyName({ serviceName: options.serviceName, product, name }), product, childKeyId: keyId,\n ...(sourceKeyId ? { sourceKeyId } : {}),\n },\n })\n if (!retired) return { succeeded: false, error: refusal(503, null) }\n const ok = retired.status >= 200 && retired.status < 300 && retired.body?.success === true\n // Nothing revoked: the slot named another source, or no live child matched. Never assumed done.\n if (ok && record(retired.body?.data)?.revoked === 0) {\n return failure<null>(409, 'delegated_key.slot_not_revoked', 'Platform revoked nothing in this slot.')\n }\n if (ok) return { succeeded: true, value: null }\n return { succeeded: false, error: refusal(retired.status, record(retired.body?.error)?.code) }\n }\n return { succeeded: false, error: refusal(result.status, record(result.body?.error)?.code) }\n },\n\n async listChildren({ sourceKey, name, product }) {\n const canonical = canonicalDelegatedKeyName({ serviceName: options.serviceName, product, name })\n const result = await call('/v1/keys', { method: 'GET', bearer: sourceKey, service: false })\n if (!result) return { succeeded: false, error: refusal(503, null) }\n const rows = result.body?.data\n if (result.status !== 200 || result.body?.success !== true || !Array.isArray(rows)) {\n return { succeeded: false, error: refusal(result.status, record(result.body?.error)?.code) }\n }\n return { succeeded: true, value: rows.flatMap((row) => {\n const value = record(row)\n return value && typeof value.id === 'string' && value.name === canonical && value.product === product && !value.revokedAt\n ? [{ id: value.id }] : []\n }) }\n },\n }\n return client\n}\n\n/** The `DurableWorkspaceKeyProvisioner` shape (`./billing`), kept structural so this module stays standalone. */\nexport interface DelegatedKeyProvisioner {\n createKey(input: { name: string; product: string; budgetUsd: number; spendThrough?: true; expiresAt: string; idempotencyKey: string }): Promise<{\n id: string; key: string; budgetUsd?: number | null; spendThrough?: true; expiresAt?: string | null\n }>\n getKey(id: string): Promise<{ budgetUsd?: number | null; budgetRemaining?: number; expiresAt?: string | null }>\n revokeKey(id: string, slot?: { name: string | null; sourceKeyId: string | null; platformUserId: string }): Promise<unknown>\n findCreatedKeys(input: { name: string; product: string; sourceKeyId?: string | null }): Promise<Array<{ id: string }>>\n}\n\n/** A remote key the durable manager must treat as gone (it marks the row revoked and mints again). */\nexport class DelegatedKeyMissingError extends Error {\n readonly status = 404\n readonly code = 'not_found'\n constructor(keyId: string) {\n super(`Platform no longer accepts key ${keyId}`)\n this.name = 'DelegatedKeyMissingError'\n }\n}\n\n/** A Platform refusal surfaced to the durable manager. Carries the typed refusal, never a key. */\nexport class DelegatedKeyRefusalError extends Error {\n constructor(readonly refusal: DelegatedKeyRefusal) {\n super(refusal.message)\n this.name = 'DelegatedKeyRefusalError'\n }\n}\n\n/**\n * Platform reasons that mean the key will never work again: the manager revokes the row and mints a fresh key.\n * The rest are lapses the same key can recover from (funding, email, team seat, caller permission).\n */\nconst GONE_REASONS = new Set([\n 'key_not_found', 'key_revoked', 'key_expired', 'key_lineage_revoked',\n 'parent_key_not_found', 'parent_key_revoked', 'parent_key_expired', 'parent_key_lineage_revoked',\n 'ancestor_key_not_found', 'ancestor_key_revoked', 'ancestor_key_expired', 'ancestor_key_lineage_revoked',\n 'key_hierarchy_too_deep', 'team_member_unrecorded', 'attribution_unresolved', 'billing_account_missing', 'account_not_found',\n 'product_mismatch', 'key_attribution_missing', 'key_provisioner_unknown', 'key_name_not_product_specific',\n])\nconst SPENT_REASONS = new Set(['budget_exhausted', 'monthly_budget_exhausted'])\n\n/**\n * Plug the client into `createIdentityBoundWorkspaceKeyManager` for a\n * workspace-held key. Pass the manager `nameForIdentity` returning a logical\n * slot name (the client sends Platform's canonical `auto:` form).\n *\n * `getKey` reads Platform's verdict: a key gone for good is reported missing\n * (the manager marks it revoked and mints again); a spent key is reported\n * exhausted (the manager revokes a sized child and mints again, and keeps a\n * spend-through child, whose spent source Router refuses per request); a funding or\n * eligibility refusal is a typed error, so a lapse never retires a key that\n * still works.\n */\nexport function createDelegatedKeyProvisioner(input: {\n client: PlatformDelegatedKeyClient\n sourceKey: string\n product: string\n resource?: { type: string; id: string }\n allowedModels?: readonly string[]\n monthlyBudgetUsd?: number\n rpmLimit?: number\n expect?: { payerId?: string; sourceKeyId?: string; originAppId?: string | null }\n /** The `revoke-slot` payer for a `revokeKey` call that carries no slot (Platform refuses an SSO key's key mutations). */\n payerId?: string\n}): DelegatedKeyProvisioner {\n const product = input.product\n // The revoke-slot fallback needs the payer; the client reads each key's slot name itself.\n const slotOwner: DelegatedKeySlotRef | undefined = input.payerId\n ? { userId: input.payerId, ...(input.expect?.sourceKeyId ? { sourceKeyId: input.expect.sourceKeyId } : {}) }\n : undefined\n return {\n async createKey(create) {\n const minted = await input.client.delegate({\n sourceKey: input.sourceKey, name: create.name, product,\n ...(input.resource ? { resource: input.resource } : {}),\n ...(input.allowedModels ? { allowedModels: input.allowedModels } : {}),\n budget: { ...(create.spendThrough ? { spendThrough: true as const } : { usd: create.budgetUsd }),\n ...(input.monthlyBudgetUsd !== undefined ? { monthlyUsd: input.monthlyBudgetUsd } : {}) },\n ...(input.rpmLimit !== undefined ? { rpmLimit: input.rpmLimit } : {}),\n expiresAt: new Date(create.expiresAt),\n ...(input.expect ? { expect: input.expect } : {}),\n })\n if (!minted.succeeded) throw new DelegatedKeyRefusalError(minted.error)\n // Platform granted no budget of its own to a spend-through request: confirm it, so the manager never rotates it on spend.\n const spendThrough = create.spendThrough && minted.value.budgetUsd === null ? { spendThrough: true as const } : {}\n return { id: minted.value.id, key: minted.value.key, budgetUsd: minted.value.budgetUsd, ...spendThrough, expiresAt: minted.value.expiresAt.toISOString() }\n },\n async getKey(id) {\n const verdict = await input.client.verify({ keyId: id, product })\n if (!verdict.succeeded) throw new DelegatedKeyRefusalError(verdict.error)\n const v = verdict.value\n if (v.valid) {\n return {\n ...(v.budgetUsd !== undefined ? { budgetUsd: v.budgetUsd } : {}),\n ...(v.budgetUsd !== undefined && v.budgetRemaining !== undefined ? { budgetSpent: Math.max(0, v.budgetUsd - v.budgetRemaining) } : {}),\n // No budget of its own: a spend-through child, whose remainder is its source's.\n ...(v.budgetUsd === undefined && v.budgetRemaining !== undefined ? { budgetRemaining: v.budgetRemaining } : {}),\n ...(v.expiresAt ? { expiresAt: v.expiresAt } : {}),\n }\n }\n if (v.invalidReason && GONE_REASONS.has(v.invalidReason)) throw new DelegatedKeyMissingError(id)\n if (v.invalidReason && SPENT_REASONS.has(v.invalidReason)) {\n // Spent: the manager revokes a sized child before minting again; a spend-through child's spent source is not its own.\n return { budgetUsd: v.budgetUsd ?? 0, budgetSpent: v.budgetUsd ?? 0, ...(v.expiresAt ? { expiresAt: v.expiresAt } : {}) }\n }\n throw new DelegatedKeyRefusalError({ status: 403, code: 'delegated_key.refused',\n message: `Platform refused the key for now (${v.invalidReason ?? 'no reason'}).` })\n },\n async revokeKey(id, slot) {\n // A child is retired through its own slot: the source that minted it, never the current one (a sibling may not touch it).\n const owner: DelegatedKeySlotRef | undefined = slot\n ? { userId: slot.platformUserId, product, ...(slot.name ? { name: slot.name } : {}), ...(slot.sourceKeyId ? { sourceKeyId: slot.sourceKeyId } : {}) }\n : slotOwner\n const revoked = await input.client.revoke({ sourceKey: input.sourceKey, keyId: id, ...(owner ? { slot: owner } : {}) })\n if (!revoked.succeeded) throw new DelegatedKeyRefusalError(revoked.error)\n return null\n },\n async findCreatedKeys(find) {\n const listed = await input.client.listChildren({ sourceKey: input.sourceKey, name: find.name, product: find.product })\n if (!listed.succeeded) throw new DelegatedKeyRefusalError(listed.error)\n return listed.value\n },\n }\n}\n","import type { KeyCrypto } from '../billing'\nimport { assertWorkspaceKeyCryptoUsable } from '../billing/crypto-probe'\nimport { sha256Hex } from '../crypto/digest'\nimport type { DelegatedKeyOutcome, DelegatedKeyRequest, PlatformDelegatedKeyClient } from './delegated-keys'\n\n/**\n * Pre-minted turn keys. Creative minted each Router turn's child on the turn's critical path, ~320 ms of a\n * 6,419 ms first-visible p50 (router-spec). `createDelegatedTurnKeys` keeps one child per turn with\n * the same cap and expiry, and mints the next turn's child in the background (`waitUntil`) into a D1 slot. The\n * next turn takes it with one `DELETE ... RETURNING`, so a parked key serves exactly one turn and a racing second\n * turn mints inline. A parked key is used only when it was minted for the same request (source key, product,\n * models, budget, resource, payer: the slot's `scope` digest) and has `minRemainingMs` of life; otherwise the turn\n * mints inline exactly as before. A parked child Platform revoked or let expire is refused by the Router (401\n * `invalid_key` with that reason); the turn's `fetchImpl` mints inline once and resends. A spent budget\n * never re-mints: the turn keeps one cap. Each slot holds at most one unused key; a displaced key, or one minted\n * but not stored, is revoked, and one whose revoke fails expires on its own. The secret is stored encrypted.\n */\n\n/** Paste into a migration. `expires_at` is epoch ms; `scope` is the digest of the request the key was minted for. */\nexport const DELEGATED_KEY_PREMINT_TABLE_DDL = `CREATE TABLE IF NOT EXISTS delegated_key_premint (\n slot TEXT PRIMARY KEY,\n scope TEXT NOT NULL,\n turn_id TEXT NOT NULL,\n key_id TEXT NOT NULL,\n key_encrypted TEXT NOT NULL,\n expires_at INTEGER NOT NULL\n)`\n\n/** The D1 surface the slot store uses. A real `D1Database` satisfies it. */\nexport interface DelegatedKeyPremintD1Like {\n prepare(query: string): {\n bind(...values: unknown[]): { first<T = Record<string, unknown>>(): Promise<T | null>; run(): Promise<unknown> }\n }\n}\n\n/** What a turn's key is minted for. Its digest decides whether a parked key may serve a turn. */\nexport type DelegatedTurnKeyScope = Omit<DelegatedKeyRequest, 'name' | 'expiresAt' | 'retryUnavailable'>\n\nexport interface DelegatedTurnKeyInput {\n /** One parked key per slot, e.g. `<userId>:<workspaceId>:router`. */\n slot: string\n scope: DelegatedTurnKeyScope\n /** Life asked of Platform for each child; `notAfter` caps it. */\n ttlMs: number\n notAfter?: Date\n retryUnavailable?: DelegatedKeyRequest['retryUnavailable']\n /** The payer's Platform user id. Platform refuses `DELETE` from an app-provisioned (SSO) source key, so an unused\n * child is retired through `revoke-slot` with it; without it (or `scope.expect.payerId`) such a child just expires. */\n payerId?: string\n}\n\nexport interface DelegatedTurnKey {\n key: string\n id: string\n /** The logical id supplied to the mint: the turn's own id inline, a random id when pre-minted. Platform's\n * child name adds a per-mint suffix, so concurrent attempts never supersede one another. */\n turnId: string\n expiresAt: Date\n /** Parked before this turn: a revoked or expired refusal of it means mint inline (`delegatedKeyFallbackFetch`). */\n preminted: boolean\n}\n\n/** One turn owns its claimed/inline key and any revoked-key replacement until it calls `revoke`. */\nexport interface DelegatedTurnKeyLease extends DelegatedTurnKey {\n /** Use with the initial `key`; handles a first-request revoked/expired premint refusal automatically. */\n fetchImpl: typeof fetch\n /** Close this lease and retire every key it held, including a replacement still being minted. Idempotent. */\n revoke(): Promise<void>\n}\n\nexport interface DelegatedTurnKeyClaimTiming { digestMs: number; storeMs: number; decryptMs?: number }\n\nexport type DelegatedTurnKeyEvent =\n /** `timing` splits the claim on the turn's path: the scope digest, the slot's `DELETE … RETURNING` round trip, and\n * (claimed only) the decrypt. */\n | { type: 'claimed' | 'missed'; slot: string; timing?: DelegatedTurnKeyClaimTiming }\n | { type: 'parked' | 'park_kept'; slot: string }\n /** `keyId` names a child minted but not parked (retired best effort); never its key. */\n | { type: 'park_failed'; slot: string; code: string; keyId?: string }\n\nexport interface DelegatedTurnKeysOptions {\n client: Pick<PlatformDelegatedKeyClient, 'delegate' | 'revoke'>\n /** Null turns pre-minting off: every turn mints inline, as before. */\n db: DelegatedKeyPremintD1Like | null\n /** The app's at-rest crypto (`createFieldCrypto` from `./crypto`). */\n crypto: KeyCrypto\n /** Defaults to `delegated_key_premint`. */\n table?: string\n /** A parked key serves a turn only with at least this much life left. Default 10 min, above a turn's budget. */\n minRemainingMs?: number\n onEvent?: (event: DelegatedTurnKeyEvent) => void\n now?: () => number\n}\n\nexport interface DelegatedTurnKeys {\n /**\n * This turn's key: the slot's parked key, taken exactly once, else a fresh mint with a unique name. Then the\n * next turn's key is minted and parked through `waitUntil` (the Worker's `ctx.waitUntil`), off this turn's path.\n * Pass `value` as the shared Router producer's `apiKey`; the producer owns fallback fetch and cleanup.\n * Direct HTTP callers use `value.fetchImpl` and close `value.revoke()` themselves, including refusals.\n */\n forTurn(input: DelegatedTurnKeyInput & { turnId: string; waitUntil?: (promise: Promise<unknown>) => void }):\n Promise<DelegatedKeyOutcome<DelegatedTurnKeyLease>>\n /** Mint and park a key for the slot's next turn, e.g. when a member session opens. Never throws. */\n park(input: DelegatedTurnKeyInput): Promise<boolean>\n /** Retire only the parked key matching this exact slot and scope after a live domain refusal. Never throws. */\n forget(input: Pick<DelegatedTurnKeyInput, 'slot' | 'scope' | 'payerId'>): Promise<void>\n /** Mint inline, as a turn did before pre-minting. */\n mint(input: DelegatedTurnKeyInput & { turnId: string }): Promise<DelegatedKeyOutcome<DelegatedTurnKey>>\n}\n\nconst PREMINT_TABLE = 'delegated_key_premint'\nconst PREMINT_MIN_REMAINING_MS = 10 * 60_000\n// A parked key is kept rather than replaced while it has this much more life than a claim needs.\nconst PREMINT_KEEP_SLACK_MS = 5 * 60_000\n\n/** The digest of everything a child is minted for, so a key minted for another request never serves this one. */\nasync function scopeDigest(scope: DelegatedTurnKeyScope): Promise<string> {\n const budget = scope.budget\n return sha256Hex(JSON.stringify([\n scope.sourceKey, scope.product, scope.resource?.type ?? null, scope.resource?.id ?? null,\n scope.allowedModels ? [...new Set(scope.allowedModels)].sort() : null,\n budget && 'usd' in budget ? budget.usd : null, budget && 'spendThrough' in budget ? true : null, budget?.monthlyUsd ?? null,\n scope.rpmLimit ?? null, scope.expect?.payerId ?? null, scope.expect?.sourceKeyId ?? null, scope.expect?.originAppId ?? null,\n ]))\n}\n\nexport function createDelegatedTurnKeys(options: DelegatedTurnKeysOptions): DelegatedTurnKeys {\n const table = options.table ?? PREMINT_TABLE\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(table)) throw new Error(`Invalid delegated key premint table: ${JSON.stringify(table)}`)\n const now = options.now ?? Date.now\n const minRemainingMs = options.minRemainingMs ?? PREMINT_MIN_REMAINING_MS\n const emit = (event: DelegatedTurnKeyEvent) => { try { options.onEvent?.(event) } catch { /* a log hook never fails a turn */ } }\n const db = options.db\n\n async function mint(input: DelegatedTurnKeyInput & { turnId: string }, preminted: boolean): Promise<DelegatedKeyOutcome<DelegatedTurnKey>> {\n const expiresAt = new Date(Math.min(now() + input.ttlMs, input.notAfter?.getTime() ?? Infinity))\n const outcome = await options.client.delegate({\n ...input.scope, name: `turn:${input.turnId}:${crypto.randomUUID()}`, expiresAt,\n ...(input.retryUnavailable ? { retryUnavailable: input.retryUnavailable } : {}),\n })\n if (!outcome.succeeded) return outcome\n const { key, id } = outcome.value\n return { succeeded: true, value: { key, id, turnId: input.turnId, expiresAt: outcome.value.expiresAt, preminted } }\n }\n\n // Best effort: a key nobody will use is retired now, or expires on its own.\n async function retire(input: Pick<DelegatedTurnKeyInput, 'scope' | 'payerId'>, keyId: string): Promise<void> {\n const { scope } = input\n const payerId = scope.expect?.payerId ?? input.payerId\n await options.client.revoke({ sourceKey: scope.sourceKey, keyId,\n ...(payerId ? { slot: { userId: payerId, product: scope.product,\n ...(scope.expect?.sourceKeyId ? { sourceKeyId: scope.expect.sourceKeyId } : {}) } } : {}),\n }).catch(() => null)\n }\n\n function lease(input: DelegatedTurnKeyInput & { turnId: string }, key: DelegatedTurnKey): DelegatedTurnKeyLease {\n const turn = { ...input, scope: { ...input.scope,\n ...(input.scope.allowedModels ? { allowedModels: [...input.scope.allowedModels] } : {}),\n ...(input.scope.budget ? { budget: { ...input.scope.budget } } : {}),\n ...(input.scope.resource ? { resource: { ...input.scope.resource } } : {}),\n ...(input.scope.expect ? { expect: { ...input.scope.expect } } : {}),\n }, ...(input.notAfter ? { notAfter: new Date(input.notAfter) } : {}) }\n const held = new Set([key.id])\n const closed = { succeeded: false as const, error: {\n status: 409, code: 'delegated_key.refused' as const, message: 'The turn key lease is closed.',\n } }\n let released = false\n let replacement: Promise<DelegatedKeyOutcome<DelegatedTurnKey>> | undefined\n let retirement: Promise<void> | undefined\n const fetchImpl = delegatedKeyFallbackFetch({\n key,\n fetch: (resource, init) => released\n ? Promise.reject(new Error(closed.error.message)) : fetch(resource, init),\n remint: () => {\n if (released) return Promise.resolve(closed)\n return replacement ??= mint(turn, false).then(outcome => {\n if (outcome.succeeded) held.add(outcome.value.id)\n return released ? closed : outcome\n })\n },\n })\n return { ...key, fetchImpl, revoke() {\n released = true\n return retirement ??= (async () => {\n await replacement?.catch(() => undefined)\n await Promise.all([...held].map(id => retire(turn, id)))\n })()\n } }\n }\n\n async function claim(input: DelegatedTurnKeyInput, timing: Partial<DelegatedTurnKeyClaimTiming>): Promise<DelegatedTurnKey | null> {\n if (!db) return null\n const { slot, scope } = input\n let at = Date.now()\n const digest = await scopeDigest(scope)\n timing.digestMs = Date.now() - at\n at = Date.now()\n const row = await db.prepare(`DELETE FROM ${table} WHERE slot = ?1 AND scope = ?2 AND expires_at > ?3 AND expires_at <= ?4\nRETURNING turn_id, key_id, key_encrypted, expires_at`).bind(slot, digest, now() + minRemainingMs, input.notAfter?.getTime() ?? Number.MAX_SAFE_INTEGER)\n .first<{ turn_id: string; key_id: string; key_encrypted: string; expires_at: number }>()\n timing.storeMs = Date.now() - at\n if (!row) return null\n try {\n at = Date.now()\n const key = await options.crypto.decrypt(row.key_encrypted)\n timing.decryptMs = Date.now() - at\n return { key, id: row.key_id, turnId: row.turn_id, expiresAt: new Date(row.expires_at), preminted: true }\n } catch {\n await retire(input, row.key_id)\n return null\n }\n }\n\n async function park(input: DelegatedTurnKeyInput): Promise<boolean> {\n if (!db) return false\n let scope: string\n try {\n scope = await scopeDigest(input.scope)\n const held = await db.prepare(`SELECT scope, expires_at FROM ${table} WHERE slot = ?1`).bind(input.slot)\n .first<{ scope: string; expires_at: number }>()\n if (held?.scope === scope && held.expires_at > now() + minRemainingMs + PREMINT_KEEP_SLACK_MS\n && held.expires_at <= (input.notAfter?.getTime() ?? Infinity)) {\n emit({ type: 'park_kept', slot: input.slot })\n return true\n }\n } catch {\n emit({ type: 'park_failed', slot: input.slot, code: 'premint_store_failed' })\n return false\n }\n // The at-rest key is proven before Platform mints, so a crypto fault never orphans a billable child.\n try {\n await assertWorkspaceKeyCryptoUsable(options.crypto)\n } catch {\n emit({ type: 'park_failed', slot: input.slot, code: 'premint_crypto_unusable' })\n return false\n }\n const minted = await mint({ ...input, turnId: crypto.randomUUID() }, true).catch(() => ({\n succeeded: false as const, error: { status: 502, code: 'delegated_key.failed' as const, message: 'Background turn-key mint failed.' },\n }))\n if (!minted.succeeded) {\n emit({ type: 'park_failed', slot: input.slot, code: minted.error.code })\n return false\n }\n try {\n const encrypted = await options.crypto.encrypt(minted.value.key)\n // An unclaimed key this one replaces (another request's, or near expiry) is never handed out again.\n const displaced = await db.prepare(`DELETE FROM ${table} WHERE slot = ?1 RETURNING key_id`).bind(input.slot)\n .first<{ key_id: string }>()\n if (displaced) await retire(input, displaced.key_id)\n const stored = await db.prepare(`INSERT INTO ${table} (slot, scope, turn_id, key_id, key_encrypted, expires_at)\nVALUES (?1, ?2, ?3, ?4, ?5, ?6) ON CONFLICT(slot) DO NOTHING RETURNING slot`)\n .bind(input.slot, scope, minted.value.turnId, minted.value.id, encrypted, minted.value.expiresAt.getTime()).first()\n if (!stored) {\n // No row came back (a racing park filled the slot first): nothing will hand this key out.\n await retire(input, minted.value.id)\n emit({ type: 'park_kept', slot: input.slot })\n return true\n }\n emit({ type: 'parked', slot: input.slot })\n return true\n } catch {\n // The minted child never reached the slot, so nothing will hand it out: retire it now (best effort).\n await retire(input, minted.value.id)\n emit({ type: 'park_failed', slot: input.slot, code: 'premint_store_failed', keyId: minted.value.id })\n return false\n }\n }\n\n return {\n async forTurn(input) {\n // A slot store that fails (no table, D1 down) is a miss: the turn mints inline as before.\n const timing: Partial<DelegatedTurnKeyClaimTiming> = {}\n const claimed = await claim(input, timing).catch(() => null)\n if (db) {\n const next = park({ slot: input.slot, scope: input.scope, ttlMs: input.ttlMs,\n ...(input.notAfter ? { notAfter: input.notAfter } : {}), ...(input.payerId ? { payerId: input.payerId } : {}) })\n input.waitUntil?.(next)\n }\n emit({ type: claimed ? 'claimed' : 'missed', slot: input.slot,\n ...(timing.digestMs !== undefined && timing.storeMs !== undefined ? { timing: timing as DelegatedTurnKeyClaimTiming } : {}) })\n const outcome = claimed ? { succeeded: true as const, value: claimed } : await mint(input, false)\n return outcome.succeeded ? { succeeded: true, value: lease(input, outcome.value) } : outcome\n },\n park,\n async forget(input) {\n if (!db) return\n try {\n const row = await db.prepare(`DELETE FROM ${table} WHERE slot = ?1 AND scope = ?2 RETURNING key_id`)\n .bind(input.slot, await scopeDigest(input.scope)).first<{ key_id: string }>()\n if (row) await retire(input, row.key_id)\n } catch { /* a refused turn never hands out the slot; its key expires if retirement is unavailable */ }\n },\n mint: (input) => mint(input, false),\n }\n}\n\n/** 401 codes that mean Platform no longer honours the key itself (tangle-router lib/key-refusal.ts and\n * app/api/chat/auth-admission.ts): `invalid_key` naming `key_revoked`/`key_expired`, and the codes reviewers named. */\nconst REFUSED_KEY_CODES = new Set(['key_revoked', 'key_expired', 'invalid_api_key', 'invalid_key_contract'])\n\n/** Whether the Router refused the key as revoked, expired or invalid. Only a 401 counts: Router's 403s\n * (email verification, product scope, routing rules) are not revocation, a 402 `key_budget_exhausted` is the\n * turn's own cap, and a bare `invalid_key` can be a spent key; re-minting for any of those would give the turn\n * a second cap. */\nasync function refusedKey(response: Response): Promise<boolean> {\n if (response.status !== 401) return false\n const body = await response.clone().json().catch(() => null) as { error?: { code?: unknown; reason?: unknown } } | null\n const code = body?.error?.code\n return typeof code === 'string' && (REFUSED_KEY_CODES.has(code) ||\n (code === 'invalid_key' && (body?.error?.reason === 'key_revoked' || body?.error?.reason === 'key_expired')))\n}\n\n/**\n * A fetch for one turn that sends a pre-minted key. When the Router refuses the turn's FIRST request with it as\n * revoked, expired or invalid (Platform retired the parked child), it mints inline once and resends that request\n * with the fresh key; later requests carry the fresh key. Any other refusal, and any refusal later in the turn, is\n * the turn's answer. A stream body on the first request is buffered so it can be resent. Requests whose\n * `init.headers` carry another credential, and keys minted inline, pass through. Make one per turn.\n */\nexport function delegatedKeyFallbackFetch(input: {\n key: DelegatedTurnKey\n remint: () => Promise<DelegatedKeyOutcome<DelegatedTurnKey>>\n fetch?: typeof fetch\n onReplaced?: (key: DelegatedTurnKey) => void\n}): typeof fetch {\n const base = input.fetch ?? fetch\n if (!input.key.preminted) return base\n const parked = `Bearer ${input.key.key}`\n let first = true\n let fresh: string | undefined\n return async (resource, init) => {\n const headers = new Headers(init?.headers)\n if (headers.get('authorization') !== parked) return base(resource, init)\n if (fresh) {\n headers.set('authorization', fresh)\n return base(resource, { ...init, headers })\n }\n if (!first) return base(resource, init)\n first = false\n const body = init?.body instanceof ReadableStream ? await new Response(init.body).arrayBuffer() : init?.body\n const send = () => base(resource, { ...init, headers, ...(body !== undefined ? { body } : {}) })\n const response = await send()\n if (!(await refusedKey(response))) return response\n const reminted = await input.remint()\n if (!reminted.succeeded) return response\n await response.body?.cancel().catch(() => {})\n fresh = `Bearer ${reminted.value.key}`\n headers.set('authorization', fresh)\n input.onReplaced?.(reminted.value)\n return send()\n }\n}\n","import { createWarmCache, type WarmCacheOptions, type WarmCacheSource } from '../sandbox/warm-cache'\n\n/**\n * A billable turn's seat and balance verdict, read from Platform once per user\n * per window instead of on every turn. Lifted from Creative\n * (creative-agent#692): in production its seat and balance reads\n * took 723 ms each, most of the 949 ms of its turn gates.\n *\n * Only a passing verdict is kept. A refusal is never cached, so a seatless or\n * unfunded user always gets the live read and its 402. Within the window the\n * balance stays enforced where money moves: the Tangle Router holds spend\n * before it calls a provider and refuses a balance at or below zero. The entry\n * ends at `windowMs` or at the seat's `paidThrough`, whichever is first, and is\n * dropped on any refusal: a seat or balance refusal read here, or one the\n * product sees elsewhere and reports with `forget` (Creative calls it when\n * Platform refuses to fund a turn's Router key). Only the data center's cache\n * holds it (no isolate copy), so that drop reaches every isolate in the data\n * center where it runs. The Workers cache is per data center: a verdict kept\n * in another data center lives on until its own window ends, and the Tangle\n * Router still refuses an unfunded key there.\n *\n * The verdict is keyed by `userId` unless `key` says otherwise: an app whose\n * seat or balance read depends on more than the user (a workspace, an\n * organization) must pass `key`, or one scope's verdict admits another.\n *\n * Passing verdicts are kept for five minutes by default, capped by the paid\n * period. `windowMs` declares a product entitlement freshness requirement; it\n * does not enable caching. Spend is still enforced live by the model service.\n */\n\n/** A Platform read's verdict: only `allowed` decides admission. */\nexport interface BillableTurnVerdict {\n allowed: boolean\n}\n\n/** A seat verdict; `paidThrough` (ISO) ends a kept verdict early, `null` when access is not a dated seat. */\nexport interface BillableTurnSeatVerdict extends BillableTurnVerdict {\n paidThrough?: string | null\n}\n\nexport interface BillableTurnAdmissionOptions<\n Input extends { userId: string },\n Seat extends BillableTurnSeatVerdict,\n Balance extends BillableTurnVerdict,\n> {\n /** The cache URL's host, one per product, such as `billing-admission.creative.internal`. */\n namespace: string\n /** A product entitlement freshness limit. Default five minutes, capped by `paidThrough`. */\n windowMs?: number\n readSeat(input: Input): Promise<Seat>\n /** A separate funding read, when funding is not already part of readSeat's entitlement verdict. */\n readBalance?(input: Input): Promise<Balance>\n /** The deployment environment in the cache key (see {@link WarmCacheOptions.env}). */\n env?: WarmCacheOptions['env']\n /** What a verdict is kept under: everything `readSeat` and `readBalance` depend on. Default `input.userId`. */\n key?(input: Input): string\n}\n\nexport interface AdmitBillableTurnOptions {\n /** Turns a Platform read failure into the caller's error. */\n mapError?: (error: unknown) => never\n /** Names each Platform read (`gate_seat`, `gate_balance`) for the turn's timing. */\n track?: <T>(name: string, work: Promise<T>) => Promise<T>\n /** Read Platform even over a kept verdict, so the window starts now (a prewarm step). */\n refresh?: boolean\n}\n\nexport type BillableTurnAdmissionResult<Seat, Balance> =\n | { source: WarmCacheSource; allowed: true; paidThrough: string | null }\n | { source: 'platform'; allowed: boolean; paidThrough: string | null; seat: Seat; balance?: Balance }\n\nexport interface BillableTurnAdmission<Input extends { userId: string }, Seat, Balance> {\n /**\n * Entitlement and any separate balance read run concurrently: an entitlement refusal or read failure\n * wins over anything the balance read returned. A kept verdict returns\n * without calling Platform. `balance` is absent when the entitlement refused or no separate read is needed.\n */\n admit(input: Input & AdmitBillableTurnOptions): Promise<BillableTurnAdmissionResult<Seat, Balance>>\n /** A refusal seen elsewhere: the next turn under this key (the user id unless `key` is set) reads Platform again. */\n forget(key: string): Promise<void>\n /** How long a verdict read now is kept: the window, or less when `paidThrough` comes first. */\n heldMs(paidThrough: string | null | undefined): number\n}\n\nexport function createBillableTurnAdmission<\n Input extends { userId: string },\n Seat extends BillableTurnSeatVerdict,\n Balance extends BillableTurnVerdict,\n>(options: BillableTurnAdmissionOptions<Input, Seat, Balance>): BillableTurnAdmission<Input, Seat, Balance> {\n const windowMs = options.windowMs ?? 5 * 60_000\n if (!(Number.isFinite(windowMs) && windowMs > 0)) {\n throw new Error('createBillableTurnAdmission: windowMs must be a positive number of milliseconds')\n }\n const verdicts = createWarmCache<{ paidThrough: string | null }>(options.namespace, { isolate: false, env: options.env })\n const keyOf = options.key ?? ((input: Input) => input.userId)\n const heldMs = (paidThrough: string | null | undefined) =>\n Math.min(windowMs, paidThrough ? Date.parse(paidThrough) - Date.now() : Infinity)\n\n return {\n heldMs,\n forget: key => verdicts.forget(key),\n async admit(input) {\n const key = keyOf(input)\n const warm = input.refresh ? null : await verdicts.read(key)\n if (warm && (warm.value.paidThrough === null || Date.parse(warm.value.paidThrough) > Date.now())) {\n return { source: warm.source, allowed: true, paidThrough: warm.value.paidThrough }\n }\n const track = input.track ?? (<T>(_name: string, work: Promise<T>) => work)\n const mapError = input.mapError ?? ((error: unknown): never => { throw error })\n const [seatSettled, balanceSettled] = await Promise.allSettled([\n track('gate_seat', options.readSeat(input).catch(mapError)),\n options.readBalance ? track('gate_balance', options.readBalance(input).catch(mapError)) : Promise.resolve(undefined),\n ])\n if (seatSettled.status === 'rejected') throw seatSettled.reason\n const seat = seatSettled.value\n if (!seat.allowed) {\n await verdicts.forget(key)\n return { source: 'platform', allowed: false, paidThrough: seat.paidThrough ?? null, seat }\n }\n if (balanceSettled.status === 'rejected') throw balanceSettled.reason\n const balance = balanceSettled.value\n if (options.readBalance && !balance!.allowed) {\n await verdicts.forget(key)\n return { source: 'platform', allowed: false, paidThrough: seat.paidThrough ?? null, seat, balance }\n }\n const paidThrough = seat.paidThrough ?? null\n const ttlMs = heldMs(paidThrough)\n if (ttlMs > 0) await verdicts.write(key, { paidThrough }, ttlMs)\n return { source: 'platform', allowed: true, paidThrough, seat, balance }\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BO,IAAM,8BAA8B;AAGpC,IAAM,sCAAsC;AAAA,EACjD,4GAA4G,2BAA2B;AAAA,EACvI,gGAAgG,2BAA2B;AAC7H;AA4DA,IAAM,iBAAiB;AAEvB,SAAS,WAAW,OAAe,OAAuB;AACxD,MAAI,CAAC,eAAe,KAAK,KAAK,EAAG,OAAM,IAAI,MAAM,wCAAwC,KAAK,EAAE;AAChG,SAAO;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AK;AAC/D,aAAO,EAAE,QAAQ,YAAY,SAAS,MAAM,aAAa,MAAM,QAAQ;AAAA,IACzE;AAAA,EACF;AACF;","names":["identifier","body","token","body","env","body","REQUEST_TIMEOUT_MS","refusal","body","REQUEST_TIMEOUT_MS","refusal","record","env","body","text","body"]}
|
|
1
|
+
{"version":3,"sources":["../../src/platform/sso-identity-store.ts","../../src/platform/hub-connect-callback.ts","../../src/platform/hub-settings.ts","../../src/platform/billing.ts","../../src/platform/platform-busy.ts","../../src/platform/agent-spend.ts","../../src/platform/billing-consent.ts","../../src/platform/deployment.ts","../../src/platform/delegated-keys.ts","../../src/platform/delegated-turn-keys.ts","../../src/platform/billable-turn-admission.ts"],"sourcesContent":["/**\n * Better Auth `account`-table store for first-party Tangle identity sign-in\n * (`protocol: 'identity'`) on D1 / SQLite.\n *\n * The platform link is Better Auth's own external-identity row:\n * `account(providerId = 'tangle', accountId = <platform user id>, userId)`.\n * Run {@link TANGLE_IDENTITY_ACCOUNT_INDEXES_SQL} in a product migration; its\n * two partial unique indexes make the link one-per-user and\n * one-per-platform-user, which the write path relies on.\n *\n * The default schema is Better Auth's singular SQLite model with camelCase\n * columns. {@link D1TangleIdentityStoreOptions.hostSchema} maps an existing\n * host's physical table and column names without changing those defaults.\n * Timestamps are unix-second integers (Drizzle `mode: 'timestamp'`). D1 is\n * structural: Cloudflare `D1Database` satisfies {@link TangleIdentityD1Like}.\n */\n\nimport {\n normalizeTangleSsoEmail,\n resolveTangleSsoAccount,\n TangleSsoAccountConflictError,\n TangleSsoUserCreateError,\n type TangleIdentitySsoAccountStore,\n type TangleSsoAccountResolution,\n type TangleSsoLocalAccount,\n} from './sso'\n\n/** Better Auth `account.providerId` for the Tangle platform link. */\nexport const TANGLE_IDENTITY_PROVIDER_ID = 'tangle'\n\n/** Partial unique indexes the store requires on Better Auth's `account` table. */\nexport const TANGLE_IDENTITY_ACCOUNT_INDEXES_SQL = [\n `CREATE UNIQUE INDEX IF NOT EXISTS account_tangle_platform_user ON account(accountId) WHERE providerId = '${TANGLE_IDENTITY_PROVIDER_ID}'`,\n `CREATE UNIQUE INDEX IF NOT EXISTS account_tangle_user ON account(userId) WHERE providerId = '${TANGLE_IDENTITY_PROVIDER_ID}'`,\n] as const\n\n/** A prepared D1 statement; Cloudflare `D1PreparedStatement` satisfies it. */\nexport interface TangleIdentityD1Statement {\n bind(...values: unknown[]): TangleIdentityD1Statement\n first<T = Record<string, unknown>>(): Promise<T | null>\n all<T = Record<string, unknown>>(): Promise<{ results: T[] }>\n run(): Promise<unknown>\n}\n\n/** The D1 surface the store needs. `batch` must be atomic, as D1's is. */\nexport interface TangleIdentityD1Like {\n prepare(query: string): TangleIdentityD1Statement\n batch(statements: TangleIdentityD1Statement[]): Promise<Array<{ meta?: { changes?: number } }>>\n}\n\n/**\n * A link table the product used before this store. During migration the store\n * reads it after `account` and mirrors new links into it, so a link that\n * exists in either place still signs in and a rollback still finds new links.\n * Remove the option once a reconcile query proves every legacy row has an\n * equal `account` row.\n */\nexport interface TangleIdentityLegacyLinkTable {\n table: string\n /** Column holding the local `user.id`; must be unique. */\n userIdColumn: string\n /** Column holding the platform user id; must be unique. */\n platformUserIdColumn: string\n}\n\nexport interface TangleIdentityHostTable<Column extends string> {\n table: string\n columns: Record<Column, string>\n}\n\n/** Better Auth table and physical column names used by the identity store. */\nexport interface TangleIdentityHostSchema {\n user: TangleIdentityHostTable<'id' | 'name' | 'email' | 'emailVerified' | 'createdAt' | 'updatedAt'>\n session: TangleIdentityHostTable<'id' | 'userId' | 'token' | 'expiresAt' | 'ipAddress' | 'userAgent' | 'createdAt' | 'updatedAt'>\n account: TangleIdentityHostTable<'id' | 'userId' | 'accountId' | 'providerId' | 'createdAt' | 'updatedAt'>\n}\n\nexport interface D1TangleIdentityStoreOptions {\n db: TangleIdentityD1Like\n /** Physical Better Auth names. Default: singular tables with camelCase columns.\n * Custom account tables need the same two partial unique indexes, using their\n * mapped column names; the default index SQL only targets the default schema. */\n hostSchema?: TangleIdentityHostSchema\n /**\n * The signed-in local user for an explicit \"connect Tangle\" flow. A live\n * local session plus a verified platform exchange jointly authorize linking\n * that user, even when its local email is unverified or differs. The host\n * must prove the session started this flow (for example with a signed,\n * session-bound cookie).\n */\n linkingUserId?: string\n legacyLinkTable?: TangleIdentityLegacyLinkTable\n}\n\nconst SQL_IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/\n\nfunction identifier(value: string, field: string): string {\n if (!SQL_IDENTIFIER.test(value)) throw new Error(`createD1TangleIdentityStore: invalid ${field}`)\n return value\n}\n\nconst DEFAULT_HOST_SCHEMA = {\n user: {\n table: 'user',\n columns: { id: 'id', name: 'name', email: 'email', emailVerified: 'emailVerified', createdAt: 'createdAt', updatedAt: 'updatedAt' },\n },\n session: {\n table: 'session',\n columns: { id: 'id', userId: 'userId', token: 'token', expiresAt: 'expiresAt', ipAddress: 'ipAddress', userAgent: 'userAgent', createdAt: 'createdAt', updatedAt: 'updatedAt' },\n },\n account: {\n table: 'account',\n columns: { id: 'id', userId: 'userId', accountId: 'accountId', providerId: 'providerId', createdAt: 'createdAt', updatedAt: 'updatedAt' },\n },\n} satisfies TangleIdentityHostSchema\n\nfunction hostTable<Column extends string>(value: TangleIdentityHostTable<Column>, field: string): TangleIdentityHostTable<Column> {\n return {\n table: identifier(value.table, `${field}.table`),\n columns: Object.fromEntries((Object.entries(value.columns) as Array<[Column, string]>).map(([column, physical]) =>\n [column, identifier(physical, `${field}.columns.${column}`)])) as Record<Column, string>,\n }\n}\n\ninterface CandidateRow {\n userId: string\n email: string\n emailVerified: number | boolean | null\n accountPlatformUserId: string | null\n legacyPlatformUserId: string | null\n}\n\ninterface Candidate extends TangleSsoLocalAccount {\n /** The account row and the legacy row name different platform users. */\n divergent: boolean\n}\n\nfunction randomToken(): string {\n return Array.from(crypto.getRandomValues(new Uint8Array(32)), byte => byte.toString(16).padStart(2, '0')).join('')\n}\n\n/** Create the identity-protocol account store for one request. */\nexport function createD1TangleIdentityStore(options: D1TangleIdentityStoreOptions): TangleIdentitySsoAccountStore {\n const { db, linkingUserId } = options\n const provider = TANGLE_IDENTITY_PROVIDER_ID\n const host = options.hostSchema ?? DEFAULT_HOST_SCHEMA\n const userTable = hostTable(host.user, 'hostSchema.user')\n const sessionTable = hostTable(host.session, 'hostSchema.session')\n const accountTable = hostTable(host.account, 'hostSchema.account')\n const u = userTable.columns\n const s = sessionTable.columns\n const a = accountTable.columns\n const legacy = options.legacyLinkTable && {\n table: identifier(options.legacyLinkTable.table, 'legacyLinkTable.table'),\n userId: identifier(options.legacyLinkTable.userIdColumn, 'legacyLinkTable.userIdColumn'),\n platformUserId: identifier(options.legacyLinkTable.platformUserIdColumn, 'legacyLinkTable.platformUserIdColumn'),\n }\n\n const selectAccount = `SELECT u.${u.id} AS userId, u.${u.email} AS email, u.${u.emailVerified} AS emailVerified,\n a.${a.accountId} AS accountPlatformUserId,\n ${legacy ? `l.${legacy.platformUserId}` : 'NULL'} AS legacyPlatformUserId\n FROM ${userTable.table} u\n LEFT JOIN ${accountTable.table} a ON a.${a.userId} = u.${u.id} AND a.${a.providerId} = '${provider}'\n ${legacy ? `LEFT JOIN ${legacy.table} l ON l.${legacy.userId} = u.${u.id}` : ''}`\n\n function toCandidate(row: CandidateRow): Candidate {\n const fromAccount = row.accountPlatformUserId?.trim() || null\n const fromLegacy = row.legacyPlatformUserId?.trim() || null\n return {\n userId: row.userId,\n email: row.email,\n emailVerified: row.emailVerified === 1 || row.emailVerified === true,\n platformUserId: fromAccount ?? fromLegacy,\n divergent: Boolean(fromAccount && fromLegacy && fromAccount !== fromLegacy),\n }\n }\n\n async function candidates(email: string, platformUserId: string) {\n const where = legacy\n ? `WHERE lower(trim(u.${u.email})) = ? OR a.${a.accountId} = ? OR l.${legacy.platformUserId} = ?`\n : `WHERE lower(trim(u.${u.email})) = ? OR a.${a.accountId} = ?`\n const values = legacy ? [email, platformUserId, platformUserId] : [email, platformUserId]\n const { results } = await db.prepare(`${selectAccount} ${where}`).bind(...values).all<CandidateRow>()\n const rows = results.map(toCandidate)\n return {\n divergent: rows.some(row => row.divergent),\n platformMatches: rows.filter(row => row.platformUserId === platformUserId),\n emailMatches: rows.filter(row => normalizeTangleSsoEmail(row.email) === email),\n }\n }\n\n const store: TangleIdentitySsoAccountStore = {\n async resolveAccount({ email, platformUserId }): Promise<TangleSsoAccountResolution> {\n const normalizedEmail = normalizeTangleSsoEmail(email)\n const stableId = platformUserId.trim()\n const found = await candidates(normalizedEmail, stableId)\n if (found.divergent) return { kind: 'reject', reason: 'platform-id-email-conflict' }\n if (!linkingUserId) {\n return resolveTangleSsoAccount({\n email: normalizedEmail,\n platformUserId: stableId,\n platformMatches: found.platformMatches,\n emailMatches: found.emailMatches,\n })\n }\n\n const ownRow = await db.prepare(`${selectAccount} WHERE u.${u.id} = ?`).bind(linkingUserId).first<CandidateRow>()\n if (!ownRow) return { kind: 'reject', reason: 'email-match-mismatch' }\n const own = toCandidate(ownRow)\n if (own.divergent) return { kind: 'reject', reason: 'platform-id-email-conflict' }\n if (own.platformUserId && own.platformUserId !== stableId) {\n return { kind: 'reject', reason: 'email-platform-id-conflict' }\n }\n if (found.platformMatches.some(row => row.userId !== linkingUserId)\n || found.emailMatches.some(row => row.userId !== linkingUserId)) {\n return { kind: 'reject', reason: 'platform-id-email-conflict' }\n }\n return { kind: 'existing', userId: linkingUserId, matchedBy: 'platform-id' }\n },\n\n async upsertUserByEmail({ email, name, tangleUserId, resolution }) {\n const normalizedEmail = normalizeTangleSsoEmail(email)\n const platformUserId = tangleUserId.trim()\n const current = await store.resolveAccount({ email: normalizedEmail, platformUserId })\n if (current.kind === 'reject') throw new TangleSsoAccountConflictError(current.reason)\n if (current.kind === 'existing') {\n if (resolution.kind === 'existing' && resolution.userId !== current.userId) {\n throw new TangleSsoAccountConflictError('platform-id-email-conflict')\n }\n return { userId: current.userId }\n }\n\n if (resolution.kind !== 'create') throw new TangleSsoUserCreateError('The selected account changed')\n const userId = crypto.randomUUID()\n try {\n await db.prepare(`INSERT INTO ${userTable.table} (${u.id}, ${u.name}, ${u.email}, ${u.emailVerified}, ${u.createdAt}, ${u.updatedAt})\n VALUES (?, ?, ?, 1, unixepoch(), unixepoch())`)\n .bind(userId, name || normalizedEmail, normalizedEmail).run()\n } catch {\n // A concurrent callback may have won the email UNIQUE race. Re-apply the\n // policy; never adopt that row by email alone.\n const after = await store.resolveAccount({ email: normalizedEmail, platformUserId })\n if (after.kind === 'reject') throw new TangleSsoAccountConflictError(after.reason)\n if (after.kind === 'existing') return { userId: after.userId }\n throw new TangleSsoUserCreateError()\n }\n return { userId }\n },\n\n async createSession({ userId, expiresAt, ipAddress, userAgent }) {\n const token = randomToken()\n await db.prepare(`INSERT INTO ${sessionTable.table} (${s.id}, ${s.userId}, ${s.token}, ${s.expiresAt}, ${s.ipAddress}, ${s.userAgent}, ${s.createdAt}, ${s.updatedAt})\n VALUES (?, ?, ?, ?, ?, ?, unixepoch(), unixepoch())`)\n .bind(crypto.randomUUID(), userId, token, Math.floor(expiresAt.getTime() / 1000), ipAddress, userAgent)\n .run()\n return { token }\n },\n\n async saveTangleLink({ userId, sessionToken, tangleUserId, email }) {\n const platformUserId = tangleUserId.trim()\n const normalizedEmail = normalizeTangleSsoEmail(email)\n const session = await db.prepare(`SELECT ${s.userId} AS userId FROM ${sessionTable.table} WHERE ${s.token} = ? AND ${s.expiresAt} > unixepoch()`)\n .bind(sessionToken).first<{ userId: string }>()\n if (session?.userId !== userId) throw new TangleSsoAccountConflictError('email-platform-id-conflict')\n const current = await store.resolveAccount({ email: normalizedEmail, platformUserId })\n if (current.kind === 'reject') throw new TangleSsoAccountConflictError(current.reason)\n if (current.kind !== 'existing' || current.userId !== userId) {\n throw new TangleSsoAccountConflictError('platform-id-email-conflict')\n }\n\n // One atomic batch: every statement re-checks the live session and the\n // email owner, and the final verified-email update runs only when this\n // exact link exists, so a lost race commits nothing and rejects.\n const liveSession = `EXISTS (SELECT 1 FROM ${sessionTable.table} WHERE ${s.token} = ? AND ${s.userId} = ? AND ${s.expiresAt} > unixepoch())`\n const emailFree = `NOT EXISTS (SELECT 1 FROM ${userTable.table} WHERE lower(trim(${u.email})) = ? AND ${u.id} <> ?)`\n const linked = `EXISTS (SELECT 1 FROM ${accountTable.table} WHERE ${a.providerId} = '${provider}' AND ${a.userId} = ? AND ${a.accountId} = ?)`\n const statements = [\n db.prepare(`INSERT INTO ${accountTable.table} (${a.id}, ${a.userId}, ${a.accountId}, ${a.providerId}, ${a.createdAt}, ${a.updatedAt})\n SELECT ?, ?, ?, '${provider}', unixepoch(), unixepoch()\n WHERE EXISTS (SELECT 1 FROM ${userTable.table} WHERE ${u.id} = ?) AND ${liveSession} AND ${emailFree}\n ON CONFLICT DO NOTHING`)\n .bind(crypto.randomUUID(), userId, platformUserId, userId, sessionToken, userId, normalizedEmail, userId),\n ]\n if (legacy) {\n statements.push(db.prepare(`INSERT INTO ${legacy.table} (${legacy.userId}, ${legacy.platformUserId})\n SELECT ?, ? WHERE ${linked}\n ON CONFLICT DO NOTHING`)\n .bind(userId, platformUserId, userId, platformUserId))\n }\n statements.push(db.prepare(`UPDATE ${userTable.table} SET ${u.emailVerified} = CASE WHEN lower(trim(${u.email})) = ? THEN 1 ELSE ${u.emailVerified} END,\n ${u.updatedAt} = unixepoch()\n WHERE ${u.id} = ? AND ${liveSession} AND ${linked} AND ${emailFree}`)\n .bind(normalizedEmail, userId, sessionToken, userId, userId, platformUserId, normalizedEmail, userId))\n const results = await db.batch(statements)\n if (results[results.length - 1]?.meta?.changes !== 1) {\n throw new TangleSsoAccountConflictError('email-platform-id-conflict')\n }\n },\n\n // `saveTangleLink` is one atomic batch, so a rejected call wrote nothing;\n // removing the unpublished session is the whole cleanup.\n async deleteSession({ sessionToken }) {\n await db.prepare(`DELETE FROM ${sessionTable.table} WHERE ${s.token} = ?`).bind(sessionToken).run()\n },\n }\n return store\n}\n","/**\n * The OAuth return contract shared by the browser popup and the settings\n * server. The popup appends exactly these parameters to the host's callback\n * path; the server accepts a return URL only in that shape.\n */\nconst HUB_CONNECT_CALLBACK_PARAMS = ['provider', 'nonce', 'context'] as const\n\n/** True when `returnUrl` is the host's callback for `provider`, as the popup builds it. */\nexport function isHubConnectCallbackUrl(returnUrl: URL, callbackPath: string, provider: string): boolean {\n if (returnUrl.pathname !== callbackPath || returnUrl.hash) return false\n const keys = [...returnUrl.searchParams.keys()]\n if (keys.length !== HUB_CONNECT_CALLBACK_PARAMS.length) return false\n if (!HUB_CONNECT_CALLBACK_PARAMS.every((key) => returnUrl.searchParams.getAll(key).length === 1)) return false\n const opaque = (value: string | null) => !!value && value.length <= 128 && /^[A-Za-z0-9_-]+$/.test(value)\n return returnUrl.searchParams.get('provider') === provider\n && opaque(returnUrl.searchParams.get('nonce'))\n && opaque(returnUrl.searchParams.get('context'))\n}\n","/** Finite, application-authorized account settings over the existing Hub SDK. */\nimport { parseJsonObjectBody } from '../web/core'\nimport { isHubConnectCallbackUrl } from './hub-connect-callback'\n\n/** Non-secret API-key setup shapes supported by the Hub SDK. */\nexport type HubSettingsApiKeyMetadata =\n | { propertyId: string; currency?: string }\n | { listings: Array<{ id: string; pms: string }> }\n\n/** Browser OAuth setup, excluding CLI mode and identity/credential overrides. */\nexport interface HubSettingsOAuthInput {\n returnUrl: string\n connectionParameters?: Record<string, string>\n requestedScopes?: readonly string[]\n}\n\ntype PolicyDecision = 'allow' | 'ask' | 'deny'\n\n/**\n * Structural subset of the existing SDK, with no execution methods. Keeping\n * this structural avoids imposing a Hub SDK peer on existing platform imports.\n */\nexport interface HubSettingsClient {\n connections: {\n providers(): Promise<unknown>\n list(): Promise<unknown>\n start(provider: string, input: HubSettingsOAuthInput): Promise<unknown>\n connectApiKey(provider: string, apiKey: string, metadata?: HubSettingsApiKeyMetadata): Promise<unknown>\n revoke(connectionId: string): Promise<unknown>\n health(connectionId: string): Promise<unknown>\n }\n tools: {\n search(query: string, options: { provider: string; limit: number }): Promise<unknown>\n }\n permissions: {\n list(connectionId: string): Promise<unknown>\n set(input: { connectionId: string; actionPath: string; decision: PolicyDecision }): Promise<unknown>\n delete(input: { connectionId: string; actionPath: string }): Promise<unknown>\n }\n}\n\n/** Validated, exact intent. The provider API key is deliberately not copied here. */\nexport type HubSettingsOperation =\n | { readonly operation: 'providers.list' | 'connections.list'; readonly target: 'caller-account' }\n | { readonly operation: 'oauth.start'; readonly provider: string; readonly input: Readonly<HubSettingsOAuthInput> }\n | { readonly operation: 'api-key.connect'; readonly provider: string; readonly metadata?: HubSettingsApiKeyMetadata }\n | { readonly operation: 'connection.revoke' | 'connection.health' | 'policies.list'; readonly connectionId: string }\n | { readonly operation: 'provider.actions'; readonly provider: string; readonly query: string; readonly limit: number }\n | { readonly operation: 'policy.set'; readonly connectionId: string; readonly actionPath: string; readonly decision: PolicyDecision }\n | { readonly operation: 'policy.reset'; readonly connectionId: string; readonly actionPath: string }\n\n/** Server-derived application identity, not fields read from browser input. */\nexport interface HubSettingsPrincipal {\n readonly userId: string\n readonly sessionId: string\n readonly workspaceId: string\n}\n\nexport interface HubSettingsGrant {\n readonly authorized: true\n readonly principal: HubSettingsPrincipal\n}\n\nexport interface HubSettingsClientBinding {\n readonly client: HubSettingsClient\n /** Reassert the identity against which the credential was actually resolved. */\n readonly principal: HubSettingsPrincipal\n /** Never env/admin credentials, another owner's key, or a brokered execution token. */\n readonly credentialSource: 'caller-account'\n}\n\nexport interface HubSettingsContext {\n /** Application-owned mount path, without a trailing slash. Default /api/hub/settings. */\n basePath?: string\n /**\n * Local path of the page that renders `HubConnectCallbackPage`. When set, an\n * OAuth start must return to exactly this path with the provider, nonce and\n * context that the integrations panel adds, and nothing else.\n */\n oauthCallbackPath?: string\n /**\n * Required on EVERY valid operation, including reads. Validate the current\n * session, CSRF protection, workspace role and exact target/decision here.\n * Return a denial Response or throw the app's auth Response to reject.\n * The body has been consumed; use the validated intent, not request.json().\n * OAuth success, connection ownership/policy, app consent and workspace\n * binding are separate facts. An execution grant is not a settings grant.\n */\n authorize(request: Request, operation: HubSettingsOperation): Promise<HubSettingsGrant | Response>\n /** Called only after authorization. Resolve the caller's linked account SDK client server-side. */\n resolveClient(principal: HubSettingsPrincipal): Promise<HubSettingsClientBinding>\n}\n\nexport interface HubSettingsRoutes {\n /** Exact method/path allowlist under basePath; never forwards request headers or arbitrary paths. */\n handle(request: Request): Promise<Response>\n}\n\nfunction json(value: unknown, status = 200, headers: Record<string, string> = {}): Response {\n return Response.json(value, { status, headers: { 'Cache-Control': 'no-store', ...headers } })\n}\n\nfunction invalid(): never {\n // Do not reflect request values: API keys and OAuth parameters can be sensitive.\n throw json({ error: 'Invalid Hub settings request', code: 'HUB_INVALID_INPUT' }, 400)\n}\n\nfunction record(value: unknown): Record<string, unknown> {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) invalid()\n return value as Record<string, unknown>\n}\n\nfunction onlyKeys(value: Record<string, unknown>, allowed: readonly string[]): void {\n if (Object.keys(value).some((key) => !allowed.includes(key))) invalid()\n}\n\nfunction text(value: unknown, max = 256): string {\n if (typeof value !== 'string' || !value.trim() || value.length > max || /[\\u0000-\\u001f\\u007f]/.test(value)) invalid()\n return value\n}\n\nfunction identifier(value: unknown): string {\n const id = text(value, 128)\n if (!/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(id)) invalid()\n return id\n}\n\nfunction action(value: unknown): string {\n const path = text(value)\n // An exact dotted action, never a provider wildcard, path, glob or pattern.\n if (!/^[A-Za-z0-9_-]+(?:\\.[A-Za-z0-9_-]+)+$/.test(path)) invalid()\n return path\n}\n\nfunction metadata(value: unknown): HubSettingsApiKeyMetadata {\n const input = record(value)\n if ('propertyId' in input) {\n onlyKeys(input, ['propertyId', 'currency'])\n return { propertyId: text(input.propertyId), ...(input.currency === undefined ? {} : { currency: text(input.currency) }) }\n }\n onlyKeys(input, ['listings'])\n if (!Array.isArray(input.listings) || input.listings.length === 0 || input.listings.length > 200) invalid()\n return { listings: input.listings.map((item) => {\n const listing = record(item)\n onlyKeys(listing, ['id', 'pms'])\n return { id: text(listing.id), pms: text(listing.pms) }\n }) }\n}\n\nfunction oauthInput(body: Record<string, unknown>, url: URL, provider: string, callbackPath: string | undefined): HubSettingsOAuthInput {\n onlyKeys(body, ['returnUrl', 'connectionParameters', 'requestedScopes'])\n const returnUrl = text(body.returnUrl, 2048)\n let destination: URL\n try { destination = new URL(returnUrl) } catch { invalid() }\n if (!['https:', 'http:'].includes(destination.protocol) || destination.origin !== url.origin || destination.username || destination.password) invalid()\n if (callbackPath !== undefined && !isHubConnectCallbackUrl(destination, callbackPath, provider)) invalid()\n const input: HubSettingsOAuthInput = { returnUrl }\n if (body.connectionParameters !== undefined) {\n const parameters = record(body.connectionParameters)\n if (Object.keys(parameters).length > 20) invalid()\n input.connectionParameters = Object.fromEntries(Object.entries(parameters).map(([key, value]) => {\n identifier(key)\n // These are non-secret provider setup values, never Hub auth or identity overrides.\n if (/^(?:user|userid|owner|ownerid|workspace|workspaceid|team|teamid|principal|principalid|session|sessionid|authorization|headers|cookie|apikey|token|accesstoken|refreshtoken|clientsecret|secret|credentials?|appid|clientid)$/.test(key.replace(/[_-]/g, '').toLowerCase())) invalid()\n return [key, text(value, 1024)]\n }))\n }\n if (body.requestedScopes !== undefined) {\n if (!Array.isArray(body.requestedScopes) || body.requestedScopes.length === 0 || body.requestedScopes.length > 100) invalid()\n input.requestedScopes = body.requestedScopes.map(scope => text(scope, 2048))\n if (new Set(input.requestedScopes).size !== input.requestedScopes.length) invalid()\n }\n return input\n}\n\nfunction query(url: URL, allowed: readonly string[]): void {\n for (const key of url.searchParams.keys()) {\n if (!allowed.includes(key) || url.searchParams.getAll(key).length !== 1) invalid()\n }\n}\n\nasync function body(request: Request): Promise<Record<string, unknown>> {\n if ((request.headers.get('content-type')?.split(';')[0] ?? '').trim().toLowerCase() !== 'application/json') {\n throw json({ error: 'Expected application/json', code: 'HUB_INVALID_INPUT' }, 415)\n }\n const [value, error] = await parseJsonObjectBody(request, { maxBytes: 64 * 1024 })\n if (error) { error.headers.set('Cache-Control', 'no-store'); throw error }\n return value\n}\n\n/** Snapshot nested intent before application callbacks can observe it. */\nfunction freeze<T>(value: T): T {\n if (value !== null && typeof value === 'object') {\n for (const child of Object.values(value)) freeze(child)\n Object.freeze(value)\n }\n return value\n}\n\nfunction isPrincipal(value: unknown): value is HubSettingsPrincipal {\n if (value === null || typeof value !== 'object') return false\n const principal = value as Partial<HubSettingsPrincipal>\n return [principal.userId, principal.sessionId, principal.workspaceId].every((part) => typeof part === 'string' && part.trim().length > 0)\n}\n\ninterface Prepared {\n intent: HubSettingsOperation\n call(client: HubSettingsClient): Promise<unknown>\n}\n\nconst ROUTES = [\n { kind: 'providers', path: /^\\/providers$/, methods: ['GET'] },\n { kind: 'connections', path: /^\\/connections$/, methods: ['GET'] },\n { kind: 'oauth', path: /^\\/connections\\/([^/]+)\\/start$/, methods: ['POST'] },\n { kind: 'api-key', path: /^\\/connections\\/([^/]+)\\/connect-key$/, methods: ['POST'] },\n { kind: 'revoke', path: /^\\/connections\\/([^/]+)$/, methods: ['DELETE'] },\n { kind: 'health', path: /^\\/connections\\/([^/]+)\\/health$/, methods: ['POST'] },\n { kind: 'actions', path: /^\\/providers\\/([^/]+)\\/actions$/, methods: ['GET'] },\n { kind: 'policies', path: /^\\/policies$/, methods: ['GET', 'PUT', 'DELETE'] },\n] as const\n\nasync function prepare(request: Request, basePath: string, callbackPath: string | undefined): Promise<Prepared | Response> {\n const url = new URL(request.url)\n if (!url.pathname.startsWith(`${basePath}/`)) return json({ error: 'Not found' }, 404)\n const path = url.pathname.slice(basePath.length)\n const route = ROUTES.find((candidate) => candidate.path.test(path))\n if (!route) return json({ error: 'Not found' }, 404)\n if (!(route.methods as readonly string[]).includes(request.method)) {\n return json({ error: 'Method not allowed' }, 405, { Allow: route.methods.join(', ') })\n }\n const target = route.path.exec(path)?.[1]\n const isPolicyRead = route.kind === 'policies' && request.method === 'GET'\n const isActions = route.kind === 'actions'\n query(url, isPolicyRead ? ['connectionId'] : isActions ? ['query', 'limit'] : [])\n const hasJson = route.kind === 'oauth' || route.kind === 'api-key' || (route.kind === 'policies' && !isPolicyRead)\n if (!hasJson && request.body !== null) {\n // Workers may expose an empty body stream for a bodyless POST.\n const reader = request.body.getReader()\n let emptyChunks = 0\n try {\n for (;;) {\n const chunk = await reader.read()\n if (chunk.done) break\n if (chunk.value.byteLength > 0) invalid()\n // Limit empty chunks before authorization; bodyless requests reach EOF.\n if (++emptyChunks > 16) invalid()\n }\n } finally {\n await reader.cancel().catch(() => undefined)\n reader.releaseLock()\n }\n }\n\n if (route.kind === 'providers') return { intent: { operation: 'providers.list', target: 'caller-account' }, call: (hub) => hub.connections.providers() }\n if (route.kind === 'connections') return { intent: { operation: 'connections.list', target: 'caller-account' }, call: (hub) => hub.connections.list() }\n if (isPolicyRead) {\n const connectionId = identifier(url.searchParams.get('connectionId'))\n return { intent: { operation: 'policies.list', connectionId }, call: (hub) => hub.permissions.list(connectionId) }\n }\n if (route.kind === 'policies') {\n const input = await body(request)\n onlyKeys(input, request.method === 'PUT' ? ['connectionId', 'actionPath', 'decision'] : ['connectionId', 'actionPath'])\n const connectionId = identifier(input.connectionId)\n const actionPath = action(input.actionPath)\n if (request.method === 'DELETE') return { intent: { operation: 'policy.reset', connectionId, actionPath }, call: (hub) => hub.permissions.delete({ connectionId, actionPath }) }\n const decision = input.decision\n if (decision !== 'allow' && decision !== 'ask' && decision !== 'deny') invalid()\n return { intent: { operation: 'policy.set', connectionId, actionPath, decision }, call: (hub) => hub.permissions.set({ connectionId, actionPath, decision }) }\n }\n const id = identifier(target)\n if (isActions) {\n const search = url.searchParams.get('query') ?? ''\n if (search.length > 512 || /[\\u0000-\\u001f\\u007f]/.test(search)) invalid()\n const rawLimit = url.searchParams.get('limit') ?? '200'\n if (!/^[1-9][0-9]*$/.test(rawLimit)) invalid()\n const limit = Number(rawLimit)\n if (limit > 200) invalid()\n return { intent: { operation: 'provider.actions', provider: id, query: search, limit }, call: (hub) => hub.tools.search(search, { provider: id, limit }) }\n }\n if (route.kind === 'oauth') {\n const input = freeze(oauthInput(await body(request), url, id, callbackPath))\n return { intent: { operation: 'oauth.start', provider: id, input }, call: (hub) => hub.connections.start(id, input) }\n }\n if (route.kind === 'api-key') {\n const input = await body(request)\n onlyKeys(input, ['apiKey', 'metadata'])\n const apiKey = text(input.apiKey, 16 * 1024)\n const setup = input.metadata === undefined ? undefined : freeze(metadata(input.metadata))\n return { intent: { operation: 'api-key.connect', provider: id, ...(setup === undefined ? {} : { metadata: setup }) }, call: (hub) => hub.connections.connectApiKey(id, apiKey, setup) }\n }\n if (route.kind === 'health') return { intent: { operation: 'connection.health', connectionId: id }, call: (hub) => hub.connections.health(id) }\n if (route.kind === 'revoke') return { intent: { operation: 'connection.revoke', connectionId: id }, call: (hub) => hub.connections.revoke(id) }\n return invalid()\n}\n\n/** Build the finite, application-authorized Hub settings server boundary. */\nexport function createHubSettingsRoutes(ctx: HubSettingsContext): HubSettingsRoutes {\n if (typeof ctx.authorize !== 'function' || typeof ctx.resolveClient !== 'function') {\n throw new TypeError('Hub settings requires authorize and resolveClient callbacks')\n }\n const basePath = ctx.basePath ?? '/api/hub/settings'\n if (!/^\\/(?:[A-Za-z0-9_-]+\\/)*[A-Za-z0-9_-]+$/.test(basePath)) throw new TypeError('Invalid Hub settings basePath')\n const callbackPath = ctx.oauthCallbackPath\n if (callbackPath !== undefined && !/^\\/(?:[A-Za-z0-9_-]+\\/)*[A-Za-z0-9_-]+$/.test(callbackPath)) throw new TypeError('Invalid Hub OAuth callback path')\n\n return { async handle(request) {\n let prepared: Prepared | Response\n try { prepared = await prepare(request, basePath, callbackPath) } catch (error) {\n if (error instanceof Response) return error\n throw error\n }\n if (prepared instanceof Response) return prepared\n // Auth throws intentionally propagate. No SDK/client lookup has occurred.\n const grant = await ctx.authorize(request, freeze(prepared.intent))\n if (grant instanceof Response) return grant\n if (grant?.authorized !== true || !isPrincipal(grant.principal)) {\n return json({ error: 'Hub settings authorization required', code: 'HUB_FORBIDDEN' }, 403)\n }\n const principal = Object.freeze({ userId: grant.principal.userId, sessionId: grant.principal.sessionId, workspaceId: grant.principal.workspaceId })\n try {\n const bound = await ctx.resolveClient(principal)\n if (bound?.credentialSource !== 'caller-account' || !isPrincipal(bound.principal) ||\n bound.principal.userId !== principal.userId || bound.principal.sessionId !== principal.sessionId || bound.principal.workspaceId !== principal.workspaceId) {\n return json({ error: 'Hub settings caller binding mismatch', code: 'HUB_FORBIDDEN' }, 403)\n }\n // Client resolution can outlive a session or role grant. Recheck before the Hub effect.\n const renewed = await ctx.authorize(request, prepared.intent)\n if (renewed instanceof Response) return renewed\n if (renewed?.authorized !== true || !isPrincipal(renewed.principal) ||\n renewed.principal.userId !== principal.userId || renewed.principal.sessionId !== principal.sessionId || renewed.principal.workspaceId !== principal.workspaceId) {\n return json({ error: 'Hub settings authorization required', code: 'HUB_FORBIDDEN' }, 403)\n }\n return json(await prepared.call(bound.client))\n } catch (error) {\n // Structural detection survives SDK copies without a runtime peer import.\n if (error instanceof Error && error.name === 'HubSdkError' && typeof (error as { code?: unknown }).code === 'string') {\n const { code, status } = error as Error & { code: string; status?: number }\n const fallback = code === 'HUB_INVALID_INPUT' ? 400 : code === 'HUB_UNAUTHENTICATED' ? 401 : code === 'HUB_FORBIDDEN' ? 403 : 502\n const httpStatus = typeof status === 'number' && Number.isInteger(status) && status >= 400 && status <= 599 ? status : fallback\n // Never echo upstream details/message: they can contain submitted credentials.\n return json({ error: 'Hub settings request failed', code }, httpStatus)\n }\n throw error\n }\n } }\n}\n","/**\n * Platform billing HTTP transport + tier state for apps on the shared\n * Tangle balance model (id.tangle.tools). Reads authenticate as the user via\n * their per-user platform key (the platform resolves the caller from the\n * key; service or impersonation headers on read routes are rejected). The\n * deduct write authenticates as the product service (`Bearer <serviceToken>`\n * + `X-Service-Name`) and names the target user in the body. Also provides a\n * fetch-backed implementation of the `/billing` module's\n * `PlatformBillingClient` seam (type-only import — no runtime coupling).\n */\n\nimport type { PlatformBillingClient, PlatformIdentity } from '../billing/index'\nimport { resolveTangleExecutionEnvironment } from '../runtime/model'\n\n/** Define available subscription tiers for the TanglePlan service */\nexport type TanglePlanTier = 'free' | 'pro' | 'enterprise'\n\n/** 'pro' | 'enterprise' pass through; anything else (null, unknown) → 'free'. */\nexport function normalizeTanglePlanTier(plan: string | null | undefined): TanglePlanTier {\n return plan === 'pro' || plan === 'enterprise' ? plan : 'free'\n}\n\n/** Represent platform billing HTTP errors with status code and detailed message */\nexport class PlatformBillingHttpError extends Error {\n constructor(\n readonly status: number,\n detail: string,\n ) {\n super(`Platform request failed (${status}): ${detail}`)\n this.name = 'PlatformBillingHttpError'\n }\n}\n\n/** Structural guard (name + numeric status) — robust across module instances. */\nexport function isPlatformBillingHttpError(error: unknown): error is PlatformBillingHttpError {\n return (\n error instanceof Error &&\n error.name === 'PlatformBillingHttpError' &&\n typeof (error as { status?: unknown }).status === 'number'\n )\n}\n\n/** Define HTTP options for platform billing including base URL, service token, product slug, fetch implementation, and timeout */\nexport interface PlatformBillingHttpOptions {\n /** Platform root, e.g. https://id.tangle.tools (trailing slashes stripped). */\n baseUrl: string\n /** Used only by `deduct()`; resolved lazily so reads never require it.\n * Throws at call time when empty. Default: the deployment's\n * `PLATFORM_SERVICE_TOKEN`. */\n serviceToken?: string | (() => string | undefined)\n /** Product slug — the `X-Service-Name` header and the deduct `product` field. */\n productSlug: string\n fetchImpl?: typeof fetch\n /** Default 10 000. */\n timeoutMs?: number\n}\n\n/** Describe subscription tier and status information for a platform user */\nexport interface PlatformSubscriptionInfo {\n tier: TanglePlanTier\n status: string | null\n}\n\n/** Describe the platform balance and lifetime spending with an optional update timestamp */\nexport interface PlatformBalanceSnapshot {\n balance: number\n lifetimeSpent: number\n updatedAt?: string\n}\n\n/** Describe a product's usage and spending metrics on the platform */\nexport interface PlatformUsageProductRow {\n product: string | null\n totalSpent: number\n count: number\n}\n\n/** Lifecycle of a per-product seat subscription, mirroring the Stripe states\n * the platform persists. 'none' = the user has never held this seat. */\nexport type SeatStatus = 'none' | 'active' | 'trialing' | 'past_due' | 'canceled'\n\n/** Price and included shared-wallet credit for one seat billing period. */\nexport interface ProductSeatOfferPeriod {\n priceCents: number\n includedCreditsCents: number\n}\n\n/** Commercial terms returned by the platform's product catalog. Products use\n * this exact object for display instead of duplicating prices in UI copy. */\nexport interface ProductSeatOffer {\n currency: 'usd'\n interval: 'month'\n recurring: ProductSeatOfferPeriod\n introductory: ProductSeatOfferPeriod | null\n}\n\n/**\n * Per-product entitlement snapshot from the platform — the single read that\n * tells a product whether to show its workspace or the seat paywall. Shape\n * matches `GET /v1/billing/product-entitlement?product=<id>`.\n *\n * `hasSeat` is computed platform-side from the raw seat row.\n * It is true for an active or trialing seat whose period has not lapsed.\n * `onFreeTier` remains in the wire shape for compatibility, but this client\n * always returns false and never uses it for access.\n */\nexport interface ProductEntitlement {\n seatStatus: SeatStatus\n /** ISO timestamp the active seat's paid period runs until; null when none. */\n currentPeriodEnd: string | null\n /** Cumulative inference spend across the whole suite, in dollars. */\n lifetimeSpentUsd: number\n hasSeat: boolean\n /** Platform access decision, including funded balance and identity policy. */\n paidAccess?: boolean\n onFreeTier: boolean\n /** Present when the platform exposes catalog-backed commercial terms. */\n offer?: ProductSeatOffer\n}\n\nfunction productSeatOffer(value: unknown): ProductSeatOffer | undefined {\n if (!value || typeof value !== 'object') return undefined\n const candidate = value as Record<string, unknown>\n if (candidate.currency !== 'usd' || candidate.interval !== 'month') return undefined\n\n const period = (input: unknown, allowZeroPrice: boolean): ProductSeatOfferPeriod | undefined => {\n if (!input || typeof input !== 'object') return undefined\n const data = input as Record<string, unknown>\n const priceCents = data.priceCents\n const includedCreditsCents = data.includedCreditsCents\n if (\n typeof priceCents !== 'number' ||\n !Number.isSafeInteger(priceCents) ||\n (allowZeroPrice ? priceCents < 0 : priceCents <= 0) ||\n typeof includedCreditsCents !== 'number' ||\n !Number.isSafeInteger(includedCreditsCents) ||\n includedCreditsCents < 0\n ) {\n return undefined\n }\n return { priceCents, includedCreditsCents }\n }\n\n const recurring = period(candidate.recurring, false)\n const introductory =\n candidate.introductory === null\n ? null\n : period(candidate.introductory, true)\n if (!recurring || introductory === undefined) return undefined\n return {\n currency: 'usd',\n interval: 'month',\n recurring,\n introductory,\n }\n}\n\n/** Define methods to interact with platform billing endpoints using user or service authentication */\nexport interface PlatformBillingHttp {\n /** GET /v1/plans/current (user bearer). */\n getSubscription(userApiKey: string): Promise<PlatformSubscriptionInfo>\n /** GET /v1/billing/balance (user bearer). */\n getBalance(userApiKey: string): Promise<PlatformBalanceSnapshot>\n /** GET /v1/billing/usage (user bearer). */\n getUsageByProduct(userApiKey: string): Promise<PlatformUsageProductRow[]>\n /** GET /v1/billing/product-entitlement?product=<id> (user bearer). */\n getProductEntitlement(userApiKey: string, productId: string): Promise<ProductEntitlement>\n /** POST /v1/billing/deduct (service token). Platform refuses a deduct without\n * `keyId`, the id of a key the charged user owns (their sign-in key). */\n deduct(input: {\n platformUserId: string\n amountUsd: number\n type: string\n description: string\n referenceId: string\n keyId?: string\n }): Promise<void>\n /** Absolute URL of the platform's billing-management surface. */\n billingUrl(): string\n /** Absolute URL of the catalog-backed seat checkout for `productId`. */\n seatCheckoutUrl(productId: string): string\n}\n\n/** Create a PlatformBillingHttp instance configured with given options and default behaviors */\nexport function createPlatformBillingHttp(opts: PlatformBillingHttpOptions): PlatformBillingHttp {\n const baseUrl = opts.baseUrl.replace(/\\/+$/, '')\n if (!baseUrl) throw new Error('PlatformBillingHttpOptions.baseUrl is required')\n if (!opts.productSlug) throw new Error('PlatformBillingHttpOptions.productSlug is required')\n const fetchImpl = opts.fetchImpl ?? fetch\n const timeoutMs = opts.timeoutMs ?? 10_000\n\n function resolveServiceToken(): string {\n if (opts.serviceToken === undefined) {\n const token = (typeof process !== 'undefined' ? process.env.PLATFORM_SERVICE_TOKEN : undefined)?.trim()\n if (!token) throw new Error('PLATFORM_SERVICE_TOKEN is required for platform billing calls')\n return token\n }\n const token = typeof opts.serviceToken === 'function' ? opts.serviceToken() : opts.serviceToken\n if (!token) throw new Error('A platform service token is required for deduct')\n return token\n }\n\n async function request<T>(path: string, init: RequestInit, headers: Headers): Promise<T> {\n const res = await fetchImpl(`${baseUrl}${path}`, {\n ...init,\n headers,\n signal: AbortSignal.timeout(timeoutMs),\n })\n if (!res.ok) {\n const body = (await res.json().catch(() => null)) as { error?: { message?: string } } | null\n throw new PlatformBillingHttpError(res.status, body?.error?.message ?? res.statusText)\n }\n return res.json() as Promise<T>\n }\n\n function userRead<T>(userApiKey: string, path: string): Promise<T> {\n const headers = new Headers()\n headers.set('Authorization', `Bearer ${userApiKey}`)\n return request<T>(path, {}, headers)\n }\n\n return {\n async getSubscription(userApiKey) {\n const body = await userRead<{\n success: boolean\n data?: { subscription?: { plan?: string | null; status?: string | null } | null }\n }>(userApiKey, '/v1/plans/current')\n const sub = body.data?.subscription ?? null\n return { tier: normalizeTanglePlanTier(sub?.plan), status: sub?.status ?? null }\n },\n\n async getBalance(userApiKey) {\n const body = await userRead<{\n success: boolean\n data?: { balance?: number; lifetimeSpent?: number; updatedAt?: string }\n }>(userApiKey, '/v1/billing/balance')\n return {\n balance: body.data?.balance ?? 0,\n lifetimeSpent: body.data?.lifetimeSpent ?? 0,\n updatedAt: body.data?.updatedAt,\n }\n },\n\n async getUsageByProduct(userApiKey) {\n const body = await userRead<{\n success: boolean\n data?: Array<{ product?: string | null; totalSpent?: number; count?: number }>\n }>(userApiKey, '/v1/billing/usage')\n return (body.data ?? []).map((row) => ({\n product: row.product ?? null,\n totalSpent: row.totalSpent ?? 0,\n count: row.count ?? 0,\n }))\n },\n\n async getProductEntitlement(userApiKey, productId) {\n const slug = encodeURIComponent(productId)\n const body = await userRead<{\n success: boolean\n data?: {\n seatStatus?: SeatStatus | null\n currentPeriodEnd?: string | null\n lifetimeSpentUsd?: number | null\n hasSeat?: boolean | null\n paidAccess?: unknown\n onFreeTier?: boolean | null\n offer?: unknown\n }\n }>(userApiKey, `/v1/billing/product-entitlement?product=${slug}`)\n const data = body.data ?? {}\n const hasSeat = data.hasSeat === true\n const offer = productSeatOffer(data.offer)\n return {\n seatStatus: data.seatStatus ?? 'none',\n currentPeriodEnd: data.currentPeriodEnd ?? null,\n lifetimeSpentUsd: data.lifetimeSpentUsd ?? 0,\n hasSeat,\n ...('paidAccess' in data ? { paidAccess: data.paidAccess === true } : {}),\n // Product-funded free access is retired. Ignore stale server signals.\n onFreeTier: false,\n ...(offer ? { offer } : {}),\n }\n },\n\n async deduct(input) {\n const headers = new Headers()\n headers.set('Authorization', `Bearer ${resolveServiceToken()}`)\n headers.set('X-Service-Name', opts.productSlug)\n headers.set('Content-Type', 'application/json')\n await request('/v1/billing/deduct', {\n method: 'POST',\n body: JSON.stringify({\n userId: input.platformUserId,\n amount: input.amountUsd,\n type: input.type,\n product: opts.productSlug,\n description: input.description,\n referenceId: input.referenceId,\n ...(input.keyId ? { keyId: input.keyId } : {}),\n }),\n }, headers)\n },\n\n billingUrl() {\n return `${baseUrl}/app/billing`\n },\n\n seatCheckoutUrl(productId) {\n return seatCheckoutUrl(baseUrl, productId)\n },\n }\n}\n\n/**\n * Platform Stripe checkout URL for a product's catalog-backed seat. The\n * platform resolves the product-specific price and introductory offer from the\n * `product` query param. Mirrors the `billingUrl()` shape — a deterministic\n * platform-rooted URL with no client-side pricing decisions.\n */\nexport function seatCheckoutUrl(baseUrl: string, productId: string): string {\n const root = baseUrl.replace(/\\/+$/, '')\n return `${root}/app/billing/seat/checkout?product=${encodeURIComponent(productId)}`\n}\n\n// ── Tier policy + composed state ────────────────────────────────────────────\n\n/** Define policy settings for concurrency and overage allowance in a tangle tier */\nexport interface TangleTierPolicy {\n concurrency: number\n overageAllowed: boolean\n}\n\n/** Define default concurrency and overage policies for each TanglePlanTier level */\nexport const DEFAULT_TANGLE_TIER_POLICY: Record<TanglePlanTier, TangleTierPolicy> = {\n free: { concurrency: 1, overageAllowed: false },\n pro: { concurrency: Number.POSITIVE_INFINITY, overageAllowed: true },\n enterprise: { concurrency: Number.POSITIVE_INFINITY, overageAllowed: true },\n}\n\n/** Describe the state of a Tangle plan tier including subscription, balance, spending, and concurrency details */\nexport interface TangleTierState {\n tier: TanglePlanTier\n subscriptionStatus: string | null\n remainingBalanceUsd: number\n lifetimeSpentUsd: number\n concurrency: number\n overageAllowed: boolean\n}\n\n/**\n * Read subscription + balance and project them onto the tier policy. A\n * null/absent key fails CLOSED (free tier, zero balance) — a billable run is\n * never started against an unknown balance. Platform errors throw; callers\n * on the billable path choose their posture explicitly.\n */\nexport async function readTangleTierState(\n http: PlatformBillingHttp,\n userApiKey: string | null | undefined,\n policy: Record<TanglePlanTier, TangleTierPolicy> = DEFAULT_TANGLE_TIER_POLICY,\n): Promise<TangleTierState> {\n if (!userApiKey) {\n return {\n tier: 'free',\n subscriptionStatus: null,\n remainingBalanceUsd: 0,\n lifetimeSpentUsd: 0,\n ...policy.free,\n }\n }\n const [subscription, balance] = await Promise.all([\n http.getSubscription(userApiKey),\n http.getBalance(userApiKey),\n ])\n return {\n tier: subscription.tier,\n subscriptionStatus: subscription.status,\n remainingBalanceUsd: balance.balance,\n lifetimeSpentUsd: balance.lifetimeSpent,\n ...policy[subscription.tier],\n }\n}\n\n// ── Per-product seat entitlement ────────────────────────────────────────────\n\n/** Product-funded free inference spend is disabled. */\nexport const FREE_TIER_SPEND_CAP_USD = 0\n\n/**\n * Default name of the per-app feature flag that controls seat billing.\n * Explicit values override the environment default.\n */\nexport const DEFAULT_SEAT_BILLING_ENABLED_ENV_VAR = 'SEAT_BILLING_ENABLED'\n\n/** Define options to configure seat billing flag environment variables and override flag name */\nexport interface SeatBillingFlagOptions {\n env?: Record<string, string | undefined>\n /** Override the flag name; default {@link DEFAULT_SEAT_BILLING_ENABLED_ENV_VAR}. */\n flagEnvVar?: string\n}\n\n/**\n * An explicit flag controls seat billing in every environment.\n * Without a flag, known development and test environments default to OFF.\n * Deployed and unknown environments default to ON.\n */\nexport function isSeatBillingEnabled(opts: SeatBillingFlagOptions = {}): boolean {\n const env =\n opts.env ??\n (typeof process !== 'undefined' ? (process.env as Record<string, string | undefined>) : undefined)\n if (!env) return true\n const flag = env[opts.flagEnvVar ?? DEFAULT_SEAT_BILLING_ENABLED_ENV_VAR]?.trim().toLowerCase()\n if (flag) return !['false', '0', 'off', 'disabled', 'no'].includes(flag)\n const environment = resolveTangleExecutionEnvironment(env)\n return environment !== 'development' && environment !== 'test'\n}\n\n/**\n * Read a user's entitlement for one product.\n * An absent key or disabled flag returns no access.\n * Transport failures propagate so the product can return a retryable error.\n *\n * @param flag — pass {@link isSeatBillingEnabled} (or your own boolean) so the\n * product owns when the gate engages. When false, no network call is made.\n */\nexport async function getProductEntitlement(\n http: Pick<PlatformBillingHttp, 'getProductEntitlement'>,\n userApiKey: string | null | undefined,\n productId: string,\n flag = true,\n): Promise<ProductEntitlement> {\n if (!flag) return unavailableEntitlement()\n if (!userApiKey) return unavailableEntitlement()\n return http.getProductEntitlement(userApiKey, productId)\n}\n\nfunction unavailableEntitlement(): ProductEntitlement {\n return {\n seatStatus: 'none',\n currentPeriodEnd: null,\n lifetimeSpentUsd: 0,\n hasSeat: false,\n onFreeTier: false,\n }\n}\n\n/** Honor platform access policy; older endpoints provide only seat authority. */\nexport function isProductEntitled(ent: ProductEntitlement): boolean {\n return ent.paidAccess === undefined ? ent.hasSeat === true : ent.paidAccess === true\n}\n\n// ── Bridge onto the /billing seam ───────────────────────────────────────────\n\n/** Define a contract for resolving platform identities based on user identifiers */\nexport interface PlatformIdentityStore {\n resolveIdentity(userId: string): Promise<PlatformIdentity | null>\n}\n\n/** Concrete fetch-backed `PlatformBillingClient<TanglePlanTier>` for\n * `createPlatformBalanceManager` (from `/billing`). */\nexport function createTanglePlatformBillingClient(\n http: PlatformBillingHttp,\n identity: PlatformIdentityStore,\n): PlatformBillingClient<TanglePlanTier> {\n return {\n resolveIdentity: (userId) => identity.resolveIdentity(userId),\n getPlan: async (apiKey) => (await http.getSubscription(apiKey)).tier,\n getBalance: async (apiKey) => {\n const snapshot = await http.getBalance(apiKey)\n return { balance: snapshot.balance, lifetimeSpent: snapshot.lifetimeSpent }\n },\n getUsageByProduct: (apiKey) => http.getUsageByProduct(apiKey),\n deduct: (input) => http.deduct(input),\n }\n}\n","/**\n * Send a Platform request through a busy writer. Platform answers 503 `PLATFORM_BUSY` with `Retry-After` when its\n * one SQLite writer is backed up past about 1 s (agent-container #19577, #19603, #19614): a service key write such as\n * `POST /v1/keys/delegate` is refused before it queues, and a write that met a locked writer is rolled back. That\n * answer carries no verdict, so the same request is sent again after Retry-After × (1 + U[0, 1)), spread so a shed\n * burst does not come back in lockstep, while the deadline leaves the next attempt room. Any other answer, or a fetch\n * that throws, is returned at once. The Sandbox Worker's Platform client waits the same way inside its 8 s delegation\n * budget (agent-container `products/sandbox/api/src/lib/platform-client-errors.ts`).\n */\n\n/** Longest one Platform call waits out a busy writer, from its first attempt. */\nconst PLATFORM_BUSY_BUDGET_MS = 8_000\n/** Longest one attempt waits for Platform; an attempt after a busy answer also ends at the deadline. */\nconst PLATFORM_REQUEST_TIMEOUT_MS = 10_000\n/** Least time a further attempt needs to be worth sending. */\nconst MIN_ATTEMPT_MS = 250\n\n/** A caller's own end for the wait, when it comes before the 8 s budget, and a signal that stops it early. */\nexport interface PlatformBusyWait { deadline?: number; signal?: AbortSignal }\n\n/** Wait `ms`, or less when `signal` aborts first; answers whether the wait ran its course. */\nexport async function sleepUnlessAborted(ms: number, signal?: AbortSignal): Promise<boolean> {\n if (!signal?.aborted) await new Promise<void>((resolve) => {\n const timer = setTimeout(resolve, ms)\n signal?.addEventListener('abort', () => { clearTimeout(timer); resolve() }, { once: true })\n })\n return !signal?.aborted\n}\n\n/** The wait a busy answer asks for, jittered, or null when the answer is not busy. */\nasync function busyWaitMs(response: Response): Promise<number | null> {\n if (response.status !== 503) return null\n const body = await response.clone().json().catch(() => null) as { error?: { code?: unknown } } | null\n if (body?.error?.code !== 'PLATFORM_BUSY') return null\n // Retry-After is whole seconds; a missing, past or unreadable one means Platform's usual 1 s.\n return Math.max(1, Number(response.headers.get('retry-after')) || 0) * 1_000 * (1 + Math.random())\n}\n\nexport async function sendThroughPlatformBusy(send: (signal: AbortSignal) => Promise<Response>, wait: PlatformBusyWait = {}): Promise<Response> {\n const deadline = Math.min(Date.now() + PLATFORM_BUSY_BUDGET_MS, wait.deadline ?? Number.POSITIVE_INFINITY)\n let response = await send(AbortSignal.timeout(PLATFORM_REQUEST_TIMEOUT_MS))\n for (;;) {\n const delay = await busyWaitMs(response)\n if (delay === null || Date.now() + delay + MIN_ATTEMPT_MS > deadline) return response\n if (!(await sleepUnlessAborted(delay, wait.signal))) return response\n await response.body?.cancel().catch(() => {})\n response = await send(AbortSignal.timeout(Math.min(PLATFORM_REQUEST_TIMEOUT_MS, deadline - Date.now())))\n }\n}\n","import { sendThroughPlatformBusy } from './platform-busy'\n\n/**\n * Bill work an agent app runs for a Platform agent key to that key's one cap.\n *\n * The cap is shared across every product and is spent even when the owner\n * already has their own credential in the app:\n *\n * - Model calls: `modelKey` delegates a spend-through Router key, which Router\n * refuses once the cap is spent.\n * - Other work, such as sandbox compute the owner's credential pays for: `hold`\n * reserves its maximum before it starts, and `consume` spends what it\n * measured, up to the hold, without charging the owner's wallet again.\n *\n * A spent or insufficient cap answers 402 `agent_key.budget_exhausted`; any\n * other refusal keeps Platform's code. A busy Platform (`PLATFORM_BUSY`) is\n * waited out on its Retry-After for at most 8 s. Web-standard fetch only.\n */\n\nexport interface AgentSpendRefusal {\n status: 402 | 403 | 503\n code: string\n message: string\n /** Platform's own error code for a refusal this client does not type. */\n platformCode?: string\n}\n\nexport type AgentSpendOutcome<T> =\n | { succeeded: true; value: T }\n | { succeeded: false; error: AgentSpendRefusal }\n\nexport interface PlatformAgentSpendOptions {\n /** Platform origin, e.g. `https://id.tangle.tools`. */\n platformUrl: string\n /** This app's Platform service name. */\n serviceName: string\n serviceToken: string | (() => string)\n /** The Platform product this app bills, e.g. `gtm-agent`. */\n product: string\n fetch?: typeof fetch\n}\n\nexport interface PlatformAgentSpend {\n /**\n * A Router key whose charges spend the agent key's cap. `name` must start\n * `auto:`; give each piece of work its own.\n */\n modelKey(input: { agentKey: string; name: string; expiresAt: Date }): Promise<AgentSpendOutcome<{ key: string; keyId: string | null }>>\n /** Reserve up to `amountUsd` of the agent key's cap for work billed elsewhere. */\n hold(input: { keyId: string; amountUsd: number; referenceId: string; expiresAt: Date }): Promise<AgentSpendOutcome<{ authorizationId: string }>>\n /** Spend what the work measured, at most the hold. A retry repeats the amount. */\n consume(input: { authorizationId: string; amountUsd: number }): Promise<AgentSpendOutcome<{ consumedUsd: number }>>\n /** Return a hold whose work never ran. */\n release(authorizationId: string): Promise<AgentSpendOutcome<null>>\n}\n\nfunction refusal(status: number, error?: PlatformBody['error']): AgentSpendRefusal {\n const code = error?.code\n if (code === 'KEY_BUDGET_EXHAUSTED' || code === 'KEY_BUDGET_EXCEEDED' || code === 'PRODUCT_BUDGET_EXCEEDED') {\n return { status: 402, code: 'agent_key.budget_exhausted', message: 'The key has spent, or cannot cover, the cap its owner approved.' }\n }\n if (code === 'INSUFFICIENT_BALANCE') {\n return { status: 402, code: 'agent_key.payment_required', message: \"The key owner's Tangle account has no credit.\" }\n }\n if (code === 'EMAIL_VERIFICATION_REQUIRED') {\n return { status: 403, code: 'agent_key.owner_unverified', message: 'The key owner must verify their Tangle email.' }\n }\n if (status >= 500 || status === 429 || code === 'PLATFORM_BUSY') {\n return { status: 503, code: 'agent_key.spend_unavailable', message: 'Platform could not record the spend; retry.' }\n }\n // Carry Platform's cause (e.g. AUTHORIZATION_CONFLICT and its message), never a credential.\n const platformCode = typeof code === 'string' && /^[A-Z][A-Z0-9_]{0,63}$/.test(code) ? code : undefined\n const detail = typeof error?.message === 'string' ? error.message.replace(/\\b(?:sk-tan-|svc_)[\\w-]+/g, '[redacted]').slice(0, 240) : ''\n const cause = [platformCode, detail].filter(Boolean).join(': ')\n return { status: 403, code: 'agent_key.spend_refused', message: `Platform refused to bill this work to the key${cause ? ` (${cause})` : ''}.`, ...(platformCode ? { platformCode } : {}) }\n}\n\ninterface PlatformBody {\n success?: unknown\n data?: { key?: unknown; id?: unknown; consumedAmount?: unknown }\n error?: { code?: unknown; message?: unknown }\n}\n\nexport function createPlatformAgentSpend(options: PlatformAgentSpendOptions): PlatformAgentSpend {\n const fetchImpl = options.fetch ?? fetch\n const base = options.platformUrl.replace(/\\/+$/, '')\n\n async function call(path: string, body: unknown): Promise<{ status: number; body: PlatformBody } | null> {\n const token = typeof options.serviceToken === 'function' ? options.serviceToken() : options.serviceToken\n try {\n const response = await sendThroughPlatformBusy(signal => fetchImpl(`${base}${path}`, {\n method: 'POST',\n headers: {\n authorization: `Bearer ${token}`,\n 'x-service-name': options.serviceName,\n 'content-type': 'application/json',\n },\n body: JSON.stringify(body),\n redirect: 'manual',\n signal,\n }))\n return { status: response.status, body: (await response.json().catch(() => ({}))) as PlatformBody }\n } catch {\n return null\n }\n }\n\n const unavailable = (): { succeeded: false; error: AgentSpendRefusal } => ({ succeeded: false, error: refusal(503) })\n\n return {\n async modelKey({ agentKey, name, expiresAt }) {\n const result = await call('/v1/keys/delegate', {\n sourceKey: agentKey, name, product: 'router', spendThrough: true, expiresAt: expiresAt.toISOString(),\n })\n if (!result) return unavailable()\n const key = result.body.data?.key\n if (result.status !== 201 || typeof key !== 'string') {\n return { succeeded: false, error: refusal(result.status, result.body.error) }\n }\n const keyId = result.body.data?.id\n return { succeeded: true, value: { key, keyId: typeof keyId === 'string' ? keyId : null } }\n },\n async hold({ keyId, amountUsd, referenceId, expiresAt }) {\n const result = await call('/v1/billing/authorizations', {\n keyId, amount: amountUsd, type: 'key_cap', product: options.product, referenceId, expiresAt: expiresAt.toISOString(),\n })\n if (!result) return unavailable()\n const id = result.body.data?.id\n if (result.status !== 201 || typeof id !== 'string') {\n return { succeeded: false, error: refusal(result.status, result.body.error) }\n }\n return { succeeded: true, value: { authorizationId: id } }\n },\n async consume({ authorizationId, amountUsd }) {\n const result = await call(`/v1/billing/authorizations/${encodeURIComponent(authorizationId)}/consume`, { amount: amountUsd })\n if (!result) return unavailable()\n const consumed = result.body.data?.consumedAmount\n if (result.status !== 200 || typeof consumed !== 'number') {\n return { succeeded: false, error: refusal(result.status, result.body.error) }\n }\n return { succeeded: true, value: { consumedUsd: consumed } }\n },\n async release(authorizationId) {\n const result = await call(`/v1/billing/authorizations/${encodeURIComponent(authorizationId)}/release`, {})\n if (!result) return unavailable()\n if (result.status !== 200) return { succeeded: false, error: refusal(result.status, result.body.error) }\n return { succeeded: true, value: null }\n },\n }\n}\n","/**\n * Record a person's consent that this app's Sandbox service key may bill them.\n *\n * An app that creates sandboxes under its own service key and names the\n * signed-in person as `billingOwnerId` needs that person's billing delegation\n * grant, or the Sandbox API refuses the create with\n * `BILLING_DELEGATION_GRANT_REQUIRED`. Platform records the grant from the key\n * the person gave the app at sign-in (`POST /v1/keys/billing-delegation-grants`),\n * so the app records it before its first delegated create. The call is\n * idempotent on Platform.\n *\n * A refusal answers a typed code and a message written for the person, so an\n * app can show it as is. Web-standard fetch only.\n */\n\nexport interface BillingConsentRefusal {\n status: 402 | 403 | 503\n code: 'billing_consent.payer_not_chargeable' | 'billing_consent.refused' | 'billing_consent.unavailable'\n /** Written for the person whose account would pay. */\n message: string\n /** Platform's own code, for logs. */\n platformCode: string | null\n}\n\nexport type BillingConsentOutcome =\n | { succeeded: true; value: { created: boolean } }\n | { succeeded: false; error: BillingConsentRefusal }\n\nexport interface PlatformBillingConsentOptions {\n /** Platform origin, e.g. `https://id.tangle.tools`. */\n platformUrl: string\n /** This app's Platform service name. */\n serviceName: string\n serviceToken: string | (() => string)\n fetch?: typeof fetch\n}\n\nexport interface PlatformBillingConsent {\n /**\n * Record that the owner of `payerKey` consents to `serviceKey` billing them\n * for sandboxes. `payerKey` is the key the person gave this app at sign-in;\n * `serviceKey` is the listed key the app creates sandboxes under.\n */\n consent(input: { payerKey: string; serviceKey: string }): Promise<BillingConsentOutcome>\n}\n\nconst REQUEST_TIMEOUT_MS = 10_000\n\nconst notChargeable: BillingConsentRefusal = {\n status: 402,\n code: 'billing_consent.payer_not_chargeable',\n message: 'Your Tangle account has no credit for sandbox use yet. Add credit in your Tangle account, then open the terminal again.',\n platformCode: 'PAYER_NOT_CHARGEABLE',\n}\n\nfunction refusal(status: number | null, platformCode: string | null): BillingConsentRefusal {\n if (platformCode === 'PAYER_NOT_CHARGEABLE') return notChargeable\n if (status === null || status >= 500 || status === 429) {\n return {\n status: 503,\n code: 'billing_consent.unavailable',\n message: 'Tangle could not record your sandbox billing consent right now. Try again in a moment.',\n platformCode,\n }\n }\n return {\n status: 403,\n code: 'billing_consent.refused',\n message: 'Tangle did not accept your sign-in for sandbox billing. Sign out and sign in again.',\n platformCode,\n }\n}\n\ninterface PlatformBody {\n data?: { id?: unknown; created?: unknown }\n error?: { code?: unknown }\n}\n\nexport function createPlatformBillingConsent(options: PlatformBillingConsentOptions): PlatformBillingConsent {\n const fetchImpl = options.fetch ?? fetch\n const base = options.platformUrl.replace(/\\/+$/, '')\n // Resolved values only: a cancelled request never settles, so a shared\n // in-flight promise would hang every later caller.\n let delegate: { serviceKey: string; keyId: string } | null = null\n\n async function request(path: string, init: RequestInit): Promise<{ status: number; body: PlatformBody } | null> {\n try {\n const response = await fetchImpl(`${base}${path}`, {\n ...init,\n redirect: 'manual',\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),\n })\n return { status: response.status, body: (await response.json().catch(() => ({}))) as PlatformBody }\n } catch {\n return null\n }\n }\n\n const codeOf = (body: PlatformBody): string | null => (typeof body.error?.code === 'string' ? body.error.code : null)\n\n return {\n async consent({ payerKey, serviceKey }) {\n if (delegate?.serviceKey !== serviceKey) {\n const self = await request('/v1/keys/self', { headers: { authorization: `Bearer ${serviceKey}` } })\n const keyId = self?.body.data?.id\n if (!self || self.status !== 200 || typeof keyId !== 'string' || !keyId) {\n return { succeeded: false, error: refusal(self ? Math.max(self.status, 500) : null, self ? codeOf(self.body) : null) }\n }\n delegate = { serviceKey, keyId }\n }\n const token = typeof options.serviceToken === 'function' ? options.serviceToken() : options.serviceToken\n const result = await request('/v1/keys/billing-delegation-grants', {\n method: 'POST',\n headers: {\n authorization: `Bearer ${token}`,\n 'x-service-name': options.serviceName,\n 'content-type': 'application/json',\n },\n body: JSON.stringify({ sourceKey: payerKey, delegateKeyId: delegate.keyId }),\n })\n if (!result) return { succeeded: false, error: refusal(null, null) }\n if (result.status === 200 || result.status === 201) {\n return { succeeded: true, value: { created: result.status === 201 } }\n }\n const platformCode = codeOf(result.body)\n // The service key's own account pays for itself and needs no grant.\n if (platformCode === 'PAYER_IS_DELEGATE_OWNER') return { succeeded: true, value: { created: false } }\n return { succeeded: false, error: refusal(result.status, platformCode) }\n },\n }\n}\n","/**\n * Where this deployment reaches the Tangle platform, read from its environment\n * at call time so a Worker's bindings are current.\n */\n\n/**\n * The platform base URL: `TANGLE_PLATFORM_URL`, or the legacy `TANGLE_SSO_URL`\n * until every environment is migrated.\n */\nconst env = (): Record<string, string | undefined> =>\n (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env ?? {}\n\nexport function platformBaseUrlFromEnv(): string {\n const url = env().TANGLE_PLATFORM_URL ?? env().TANGLE_SSO_URL\n if (!url) throw new Error('TANGLE_PLATFORM_URL is required (or legacy TANGLE_SSO_URL)')\n return url\n}\n\n/**\n * Options for the platform's cross-site SSO client: the base URL, the app id\n * registered in the platform's trusted-apps registry (`TANGLE_PLATFORM_APP_ID`,\n * else the product's own), and a fetch the client can call as a method. A\n * Worker's `fetch` stored on an instance and called as `this.fetchImpl()`\n * throws \"Illegal invocation\", so the global is wrapped in a free call.\n */\nexport function platformAuthClientOptionsFromEnv(\n defaultAppId: string,\n overrides: { baseUrl?: string; appId?: string; fetchImpl?: typeof fetch } = {},\n): { baseUrl: string; appId: string; fetchImpl: typeof fetch } {\n return {\n baseUrl: overrides.baseUrl ?? platformBaseUrlFromEnv(),\n appId: overrides.appId ?? env().TANGLE_PLATFORM_APP_ID ?? defaultAppId,\n fetchImpl: overrides.fetchImpl ?? ((input, init) => globalThis.fetch(input, init)),\n }\n}\n","/**\n * Delegated product keys: a child key minted from the paying user's linked\n * Tangle key, scoped to one product, its models and its budget, so an app\n * never sends the user's own key to Router or Sandbox.\n *\n * WHY ONE. Seven apps minted these by hand (Tax, Legal, GTM, Creative,\n * Builder, Hardware, workcomp; survey) with different scope,\n * expiry and revocation rules, and four never noticed a key Platform had\n * revoked, superseded or expired.\n *\n * THREE WAYS TO HOLD ONE.\n * - Per turn: `client.delegate` before the turn, `client.revoke` after it.\n * Nothing is cached, so nothing stale can be handed out.\n * - Pre-minted per turn: `createDelegatedTurnKeys` (`./delegated-turn-keys`) gives each turn its own\n * child, same cap and expiry, but mints the next turn's child in the\n * background and parks it in D1, so the ~320 ms mint leaves the turn's\n * critical path. A parked key is taken exactly once; anything else mints\n * inline as before.\n * - Per workspace: `createDelegatedKeyProvisioner` plugs this client into\n * `createIdentityBoundWorkspaceKeyManager` (`./billing`), which owns the\n * durable, lease-fenced slot. Its `getKey` asks Platform's\n * `verify-by-id`, which also refuses superseded generations, and reports\n * any key that is not valid as missing, so the manager marks it revoked\n * and mints a fresh one on the next use.\n *\n * THE MINT CONTRACT (`POST /v1/keys/delegate`, service-authenticated; the\n * response is the key row plus `attribution`, and the granted expiry is\n * `attribution.expiresAt`). The child is checked field by field: an\n * `sk-tan-` key that is not the source, the canonical name, this service as\n * provisioner and attribution origin, the requested product, resource, model\n * set and payer, a budget no larger than requested, and an expiry in the\n * future and no later than requested. A child that fails is revoked and\n * refused; if that revoke fails too, the refusal carries the child's id (never\n * its key) so the app can retire it.\n *\n * Errors carry a code and status, never a response body, a source key or a\n * child key.\n */\n\nimport { platformBaseUrlFromEnv } from './deployment'\nimport { type PlatformBusyWait, sendThroughPlatformBusy, sleepUnlessAborted } from './platform-busy'\n\n// Backoff while Platform cannot answer a delegation: 250 ms doubling to 5 s, with jitter.\nconst UNAVAILABLE_BASE_DELAY_MS = 250\nconst UNAVAILABLE_MAX_DELAY_MS = 5_000\nconst KEY_PREFIX = 'sk-tan-'\nconst AUTO_PREFIX = 'auto:'\n/** Products whose key names Platform qualifies as `auto:<service>:<product>:...` (key-provenance.ts). */\nconst PRODUCT_QUALIFIED = new Set(['router', 'sandbox'])\n\nexport type DelegatedKeyCode =\n | 'delegated_key.payment_required'\n | 'delegated_key.budget_exhausted'\n | 'delegated_key.owner_unverified'\n | 'delegated_key.unavailable'\n | 'delegated_key.refused'\n | 'delegated_key.failed'\n | 'delegated_key.response_invalid'\n | 'delegated_key.invalid_request'\n | 'delegated_key.slot_not_revoked'\n\nexport interface DelegatedKeyRefusal {\n status: number\n code: DelegatedKeyCode\n message: string\n /** Set when an untrusted child could not be revoked: the id (never the key) the app must retire. */\n unrevokedKeyId?: string\n /** Platform's own error code (never its message) for a decision this client does not type, for logs. */\n platformCode?: string\n}\n\nexport type DelegatedKeyOutcome<T> =\n | { succeeded: true; value: T }\n | { succeeded: false; error: DelegatedKeyRefusal }\n\n/** How the child is paid for: its own budget, or spending the source's budget directly. */\nexport type DelegatedKeyBudget =\n | { usd: number; monthlyUsd?: number }\n | { spendThrough: true; monthlyUsd?: number }\n\nexport interface DelegatedKeyRequest {\n /** The payer's linked `sk-tan-` key. Never a shared app key. */\n sourceKey: string\n /** The logical slot, e.g. `turn:<id>`. Sent as Platform's canonical name; see {@link canonicalDelegatedKeyName}.\n * A slot holds one key: a new delegation under the same name revokes (or supersedes) the key holding it\n * (Platform key-provisioning `revokeKeySubtrees`). Two attempts that may run at once, such as a transport retry\n * beside the attempt it replaces, need distinct names, or the second revokes the first mid-turn. */\n name: string\n product: 'router' | 'sandbox' | (string & {})\n resource?: { type: string; id: string }\n /** The only models the child may call. */\n allowedModels?: readonly string[]\n budget?: DelegatedKeyBudget\n rpmLimit?: number\n expiresAt: Date\n /** Checked against the child's attribution when given: the payer's Platform user id, the source key's id, and\n * the origin app Platform carries over from the source (an app's SSO key; a personal key has none). */\n expect?: { payerId?: string; sourceKeyId?: string; originAppId?: string | null }\n /**\n * Keep asking while Platform answers `delegated_key.unavailable` (no answer, 5xx, 429, busy), with jittered\n * backoff, for at most `forMs` from the first attempt; then return that refusal. Without it, only a busy Platform\n * (`PLATFORM_BUSY`) is waited out, on its Retry-After, for at most 8 s. Platform's origin was unreachable\n * for 84.8 s and 54.5 s across restarts, and each such failure ended a member's Router turn, so a\n * turn-scoped mint passes about 90 000 here, inside its turn's budget. `signal` stops the wait early. A retried\n * request may have reached Platform; the next attempt uses the same name, so it replaces that child in its slot\n * rather than leaving a second one.\n */\n retryUnavailable?: { forMs: number; signal?: AbortSignal }\n}\n\nexport interface DelegatedKey {\n key: string\n id: string\n /** The canonical name Platform stored. */\n name: string\n product: string\n /** The expiry Platform granted (`attribution.expiresAt`), never later than requested. */\n expiresAt: Date\n allowedModels: readonly string[] | null\n budgetUsd: number | null\n}\n\nexport interface PlatformDelegatedKeyClientOptions {\n /** Platform origin. Default: TANGLE_PLATFORM_URL or TANGLE_SSO_URL from the request environment. */\n platformUrl?: string\n /** This app's Platform service name; Platform admits delegation per named service. */\n serviceName: string\n /** Default: lazily read PLATFORM_SERVICE_TOKEN; missing configuration fails closed. */\n serviceToken?: string | (() => string)\n fetch?: typeof fetch\n now?: () => number\n}\n\n/** Platform's `verify-by-id` verdict on one key, secret-free. */\nexport interface DelegatedKeyVerdict {\n valid: boolean\n /** Platform's reason when not valid, e.g. `key_revoked`, `budget_exhausted`. */\n invalidReason?: string\n budgetUsd?: number\n budgetRemaining?: number\n expiresAt?: string\n}\n\n/**\n * Identifies a key's slot for Platform's service-authenticated `revoke-slot`. Without `name`, `product` or\n * `sourceKeyId`, the client reads them from the key itself (`GET /v1/keys/:id`, which an SSO source may\n * call; the child's parent is its source key), so a provisioner restarted since the mint can still retire\n * the key. Health, Tax and Legal bind the slot to its source key; GTM and Builder admit `revoke-slot` only\n * for their protected and preview keys, so their other keys keep the refused DELETE as a typed error.\n */\nexport interface DelegatedKeySlotRef {\n userId: string\n name?: string\n product?: string\n sourceKeyId?: string\n}\n\nexport interface PlatformDelegatedKeyClient {\n delegate(request: DelegatedKeyRequest): Promise<DelegatedKeyOutcome<DelegatedKey>>\n /** Platform's authoritative verdict (`verify-by-id`), including revoked, expired and spent keys. */\n verify(input: { keyId: string; product: string }): Promise<DelegatedKeyOutcome<DelegatedKeyVerdict>>\n /**\n * `DELETE /v1/keys/:id` with the source key; a key already gone counts as revoked. Platform refuses key\n * mutations from a service-provisioned source (an app's SSO key) or a sibling source with 403, and a source it no\n * longer accepts with 401; given `slot`, the client then retires the slot through `revoke-slot` with the service\n * token. A `revoke-slot` that revokes nothing is a 409 `delegated_key.slot_not_revoked` refusal.\n */\n revoke(input: { sourceKey: string; keyId: string; slot?: DelegatedKeySlotRef }): Promise<DelegatedKeyOutcome<null>>\n /** Children of the source key in one slot, from `GET /v1/keys` with the source key. */\n listChildren(input: { sourceKey: string; name: string; product: string }): Promise<DelegatedKeyOutcome<Array<{ id: string }>>>\n}\n\n/**\n * The name Platform stores for a slot: `auto:<service>:<product>:<logical>` for\n * Router and Sandbox keys (Platform's `canonicalProvisionedKeyName`), so the\n * echo can be checked exactly. A name already qualified is kept.\n */\nexport function canonicalDelegatedKeyName(input: { serviceName: string; product: string; name: string }): string {\n const logical = input.name.startsWith(AUTO_PREFIX) ? input.name.slice(AUTO_PREFIX.length) : input.name\n if (!PRODUCT_QUALIFIED.has(input.product)) return `${AUTO_PREFIX}${logical}`\n if (logical.startsWith(`${input.serviceName}:${input.product}:`)) return `${AUTO_PREFIX}${logical}`\n const withoutService = logical.startsWith(`${input.serviceName}:`) ? logical.slice(input.serviceName.length + 1) : logical\n return `${AUTO_PREFIX}${input.serviceName}:${input.product}:${withoutService}`\n}\n\nfunction refusal(status: number, code: unknown): DelegatedKeyRefusal {\n if (code === 'INSUFFICIENT_BALANCE') {\n return { status: 402, code: 'delegated_key.payment_required', message: \"The payer's Tangle account has no credit.\" }\n }\n if (code === 'KEY_BUDGET_EXHAUSTED' || code === 'KEY_BUDGET_EXCEEDED' || code === 'PRODUCT_BUDGET_EXCEEDED') {\n return { status: 402, code: 'delegated_key.budget_exhausted', message: \"The payer's key has spent the budget it allows.\" }\n }\n if (code === 'EMAIL_VERIFICATION_REQUIRED') {\n return { status: 403, code: 'delegated_key.owner_unverified', message: 'The payer must verify their Tangle email.' }\n }\n if (status >= 500 || status === 429 || code === 'PLATFORM_BUSY') {\n return { status: 503, code: 'delegated_key.unavailable', message: 'Platform could not answer; retry.' }\n }\n // Only an authorization answer is a refusal. Any other 4xx is a decision about this request (Platform's\n // 400 DELEGATION_FAILED, say), kept as its own status with Platform's code so it is not mistaken for\n // a credential problem. The message stays out: it can name Platform internals.\n const platformCode = typeof code === 'string' && /^[A-Z][A-Z0-9_]{0,63}$/.test(code) ? code : undefined\n if (status === 401 || status === 403 || status < 400) {\n return { status: 403, code: 'delegated_key.refused', message: 'Platform refused to delegate this key.', ...(platformCode ? { platformCode } : {}) }\n }\n return {\n status,\n code: 'delegated_key.failed',\n message: `Platform declined this delegation${platformCode ? ` (${platformCode})` : ''}.`,\n ...(platformCode ? { platformCode } : {}),\n }\n}\n\nconst failure = <T,>(status: number, code: DelegatedKeyCode, message: string, extra: Partial<DelegatedKeyRefusal> = {}): DelegatedKeyOutcome<T> =>\n ({ succeeded: false, error: { status, code, message, ...extra } })\n\nconst record = (value: unknown): Record<string, unknown> | null =>\n value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : null\n\nfunction sameSet(granted: unknown, requested: readonly string[]): boolean {\n if (!Array.isArray(granted) || granted.some(model => typeof model !== 'string')) return false\n const a = [...new Set(granted as string[])].sort()\n const b = [...new Set(requested)].sort()\n return granted.length === a.length && a.length === b.length && a.every((model, index) => model === b[index])\n}\n\n/** Why the minted child cannot be trusted, or null. Each check names its field, never its value. */\nfunction childProblem(data: Record<string, unknown>, request: DelegatedKeyRequest, name: string, serviceName: string, nowMs: number): string | null {\n const key = data.key\n const id = data.id\n if (typeof id !== 'string' || !id) return 'no key id'\n if (typeof key !== 'string' || !key.startsWith(KEY_PREFIX) || key.length <= KEY_PREFIX.length) return 'not an sk-tan child key'\n if (key === request.sourceKey) return 'the source key itself'\n if (typeof data.prefix === 'string' && !key.startsWith(data.prefix)) return 'a key that does not match its prefix'\n if (data.name !== name) return 'a different name'\n if (data.product !== request.product) return 'a different product'\n if (data.provisionedByService !== serviceName) return 'a different provisioner'\n if (data.scopes !== null && !(Array.isArray(data.scopes) && data.scopes.length === 0)) return 'control-plane scopes'\n // Omitted, the child inherits the source's model restriction, which only narrows it.\n if (request.allowedModels && !sameSet(data.allowedModels, request.allowedModels)) return 'a different model set'\n const budget = request.budget\n if (budget && 'usd' in budget && !(typeof data.budgetUsd === 'number' && data.budgetUsd <= budget.usd)) return 'a budget larger than requested'\n if (budget?.monthlyUsd !== undefined && !(typeof data.monthlyBudgetUsd === 'number' && data.monthlyBudgetUsd <= budget.monthlyUsd)) {\n return 'a monthly budget larger than requested'\n }\n\n const attribution = record(data.attribution)\n if (!attribution) return 'no attribution'\n if (attribution.version !== 1 || attribution.targetService !== request.product) return 'attribution for another target'\n if (request.expect?.originAppId !== undefined && (attribution.originAppId ?? null) !== request.expect.originAppId) {\n return 'attribution from another app'\n }\n const parent = attribution.delegatedFromKeyId\n if (typeof parent !== 'string' || !parent || parent === id) return 'attribution without its parent key'\n if (request.expect?.sourceKeyId !== undefined && parent !== request.expect.sourceKeyId) return 'attribution for another source key'\n if (attribution.payerType !== 'user') return 'attribution to a non-user payer'\n if (request.expect?.payerId !== undefined && attribution.payerId !== request.expect.payerId) return 'attribution to another payer'\n if ((attribution.resourceType ?? null) !== (request.resource?.type ?? null) || (attribution.resourceId ?? null) !== (request.resource?.id ?? null)) {\n return 'attribution for another resource'\n }\n const expiresAt = typeof attribution.expiresAt === 'string' ? Date.parse(attribution.expiresAt) : NaN\n if (!Number.isFinite(expiresAt) || expiresAt <= nowMs || expiresAt > request.expiresAt.getTime()) return 'an expiry in the past or past the request'\n return null\n}\n\nexport function createPlatformDelegatedKeyClient(options: PlatformDelegatedKeyClientOptions): PlatformDelegatedKeyClient {\n const fetchImpl = options.fetch ?? fetch\n const now = options.now ?? Date.now\n const env = () => (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env\n const origin = options.platformUrl ?? platformBaseUrlFromEnv()\n const base = options.platformUrl ? origin.replace(/\\/+$/, '') : new URL(origin).origin\n const serviceToken = () => {\n if (options.serviceToken !== undefined) return typeof options.serviceToken === 'function' ? options.serviceToken() : options.serviceToken\n const token = env()?.PLATFORM_SERVICE_TOKEN?.trim()\n if (!token) throw new Error('PLATFORM_SERVICE_TOKEN is required for delegated product keys')\n return token\n }\n\n async function call(path: string, init: { method: string; bearer: string; service: boolean; body?: unknown }, wait?: PlatformBusyWait) {\n try {\n const response = await sendThroughPlatformBusy(signal => fetchImpl(`${base}${path}`, {\n method: init.method,\n headers: {\n authorization: `Bearer ${init.bearer}`,\n ...(init.service ? { 'x-service-name': options.serviceName } : {}),\n ...(init.body === undefined ? {} : { 'content-type': 'application/json' }),\n },\n ...(init.body === undefined ? {} : { body: JSON.stringify(init.body) }),\n redirect: 'manual',\n signal,\n }), wait)\n return { status: response.status, body: record(await response.json().catch(() => null)) }\n } catch {\n return null\n }\n }\n\n async function delegateOnce(request: DelegatedKeyRequest, wait?: PlatformBusyWait): Promise<DelegatedKeyOutcome<DelegatedKey>> {\n if (!request.sourceKey.startsWith(KEY_PREFIX)) return failure(400, 'delegated_key.invalid_request', 'The source must be a linked sk-tan- key.')\n if (request.expiresAt.getTime() <= now()) return failure(400, 'delegated_key.invalid_request', 'The expiry must be in the future.')\n const name = canonicalDelegatedKeyName({ serviceName: options.serviceName, product: request.product, name: request.name })\n const budget = request.budget\n const result = await call('/v1/keys/delegate', {\n method: 'POST', bearer: serviceToken(), service: true, body: {\n sourceKey: request.sourceKey,\n name,\n product: request.product,\n ...(request.resource ? { resourceType: request.resource.type, resourceId: request.resource.id } : {}),\n ...(budget && 'usd' in budget ? { budgetUsd: budget.usd } : {}),\n ...(budget && 'spendThrough' in budget ? { spendThrough: true } : {}),\n ...(budget?.monthlyUsd !== undefined ? { monthlyBudgetUsd: budget.monthlyUsd } : {}),\n ...(request.allowedModels ? { allowedModels: [...new Set(request.allowedModels)] } : {}),\n ...(request.rpmLimit !== undefined ? { rpmLimit: request.rpmLimit } : {}),\n // Omitted, Platform copies the source's scopes onto the child; a product key carries none.\n scopes: [],\n expiresAt: request.expiresAt.toISOString(),\n },\n }, wait)\n if (!result) return { succeeded: false, error: refusal(503, null) }\n const data = record(result.body?.data)\n if (result.status !== 201 || result.body?.success !== true || !data) {\n return { succeeded: false, error: refusal(result.status, record(result.body?.error)?.code) }\n }\n const problem = childProblem(data, request, name, options.serviceName, now())\n if (problem) {\n // A child Platform minted but this app cannot trust is retired, never returned.\n const id = typeof data.id === 'string' && data.id ? data.id : null\n const owner = request.expect?.payerId\n ? { userId: request.expect.payerId, name, product: request.product,\n ...(request.expect.sourceKeyId ? { sourceKeyId: request.expect.sourceKeyId } : {}) }\n : undefined\n const revoked = id ? await client.revoke({ sourceKey: request.sourceKey, keyId: id, ...(owner ? { slot: owner } : {}) }) : null\n return failure(502, 'delegated_key.response_invalid', `Platform returned ${problem}.`,\n id && !revoked?.succeeded ? { unrevokedKeyId: id } : {})\n }\n const attribution = record(data.attribution)!\n return { succeeded: true, value: {\n key: data.key as string, id: data.id as string, name, product: request.product,\n expiresAt: new Date(attribution.expiresAt as string),\n allowedModels: request.allowedModels ? [...new Set(request.allowedModels)] : null,\n budgetUsd: typeof data.budgetUsd === 'number' ? data.budgetUsd : null,\n } }\n }\n\n /** Wait before the next attempt, or answer false when the window or the signal says stop. */\n async function backoff(attempt: number, deadline: number, signal: AbortSignal | undefined): Promise<boolean> {\n const delay = Math.min(UNAVAILABLE_MAX_DELAY_MS, UNAVAILABLE_BASE_DELAY_MS * 2 ** attempt) * (0.5 + Math.random() / 2)\n if (Date.now() + delay > deadline) return false\n return sleepUnlessAborted(delay, signal)\n }\n\n const client: PlatformDelegatedKeyClient = {\n async delegate(request) {\n const retry = request.retryUnavailable\n const deadline = Date.now() + Math.max(0, retry?.forMs ?? 0)\n for (let attempt = 0; ; attempt++) {\n // A busy Platform is waited out inside 8 s, or inside the retry window when that ends sooner.\n const outcome = await delegateOnce(request, retry && { deadline, signal: retry.signal })\n if (outcome.succeeded || outcome.error.code !== 'delegated_key.unavailable' || !retry) return outcome\n if (!(await backoff(attempt, deadline, retry.signal))) return outcome\n }\n },\n\n async verify({ keyId, product }) {\n const result = await call('/v1/keys/verify-by-id', {\n method: 'POST', bearer: serviceToken(), service: true, body: { keyId, expectedProduct: product },\n })\n // Fail closed: anything but a well-formed verdict for this key is not evidence about it.\n if (!result || result.status >= 500 || result.status === 429) return { succeeded: false, error: refusal(503, null) }\n const body = result.body\n if (result.status !== 200 || typeof body?.valid !== 'boolean' || (body.valid && body.keyId !== keyId)) {\n return failure(502, 'delegated_key.response_invalid', 'Platform returned no verification verdict for this key.')\n }\n const number = (value: unknown) => typeof value === 'number' && Number.isFinite(value) ? value : undefined\n return { succeeded: true, value: {\n valid: body.valid,\n ...(typeof body.invalidReason === 'string' ? { invalidReason: body.invalidReason } : {}),\n ...(number(body.budgetUsd) !== undefined ? { budgetUsd: number(body.budgetUsd) } : {}),\n ...(number(body.budgetRemaining) !== undefined ? { budgetRemaining: number(body.budgetRemaining) } : {}),\n ...(typeof body.expiresAt === 'string' ? { expiresAt: body.expiresAt } : {}),\n } }\n },\n\n async revoke({ sourceKey, keyId, slot }) {\n const result = await call(`/v1/keys/${encodeURIComponent(keyId)}`, { method: 'DELETE', bearer: sourceKey, service: false })\n if (!result) return { succeeded: false, error: refusal(503, null) }\n if (result.status === 404 || (result.status >= 200 && result.status < 300 && result.body?.success === true)) {\n return { succeeded: true, value: null }\n }\n if ((result.status === 403 || result.status === 401) && slot) {\n let { name, product, sourceKeyId } = slot\n if (!name || !product || !sourceKeyId) {\n const row = await call(`/v1/keys/${encodeURIComponent(keyId)}`, { method: 'GET', bearer: sourceKey, service: false })\n if (row?.status === 404) return { succeeded: true, value: null }\n const data = row?.status === 200 ? record(row.body?.data) : null\n if (data?.revokedAt) return { succeeded: true, value: null }\n const text = (value: unknown) => typeof value === 'string' && value ? value : undefined\n name ||= text(data?.name)\n product ||= text(data?.product)\n // The child's parent is the source key a source-bound slot names.\n sourceKeyId ||= text(data?.parentKeyId)\n if (!name || !product) return { succeeded: false, error: refusal(row?.status ?? 503, null) }\n }\n // Platform checks the `auto:` prefix before it canonicalizes, so a logical slot name is sent canonical.\n const retired = await call('/v1/keys/auto-provisioned/revoke-slot', {\n method: 'POST', bearer: serviceToken(), service: true, body: {\n userId: slot.userId, name: canonicalDelegatedKeyName({ serviceName: options.serviceName, product, name }), product, childKeyId: keyId,\n ...(sourceKeyId ? { sourceKeyId } : {}),\n },\n })\n if (!retired) return { succeeded: false, error: refusal(503, null) }\n const ok = retired.status >= 200 && retired.status < 300 && retired.body?.success === true\n // Nothing revoked: the slot named another source, or no live child matched. Never assumed done.\n if (ok && record(retired.body?.data)?.revoked === 0) {\n return failure<null>(409, 'delegated_key.slot_not_revoked', 'Platform revoked nothing in this slot.')\n }\n if (ok) return { succeeded: true, value: null }\n return { succeeded: false, error: refusal(retired.status, record(retired.body?.error)?.code) }\n }\n return { succeeded: false, error: refusal(result.status, record(result.body?.error)?.code) }\n },\n\n async listChildren({ sourceKey, name, product }) {\n const canonical = canonicalDelegatedKeyName({ serviceName: options.serviceName, product, name })\n const result = await call('/v1/keys', { method: 'GET', bearer: sourceKey, service: false })\n if (!result) return { succeeded: false, error: refusal(503, null) }\n const rows = result.body?.data\n if (result.status !== 200 || result.body?.success !== true || !Array.isArray(rows)) {\n return { succeeded: false, error: refusal(result.status, record(result.body?.error)?.code) }\n }\n return { succeeded: true, value: rows.flatMap((row) => {\n const value = record(row)\n return value && typeof value.id === 'string' && value.name === canonical && value.product === product && !value.revokedAt\n ? [{ id: value.id }] : []\n }) }\n },\n }\n return client\n}\n\n/** The `DurableWorkspaceKeyProvisioner` shape (`./billing`), kept structural so this module stays standalone. */\nexport interface DelegatedKeyProvisioner {\n createKey(input: { name: string; product: string; budgetUsd: number; spendThrough?: true; expiresAt: string; idempotencyKey: string }): Promise<{\n id: string; key: string; budgetUsd?: number | null; spendThrough?: true; expiresAt?: string | null\n }>\n getKey(id: string): Promise<{ budgetUsd?: number | null; budgetRemaining?: number; expiresAt?: string | null }>\n revokeKey(id: string, slot?: { name: string | null; sourceKeyId: string | null; platformUserId: string }): Promise<unknown>\n findCreatedKeys(input: { name: string; product: string; sourceKeyId?: string | null }): Promise<Array<{ id: string }>>\n}\n\n/** A remote key the durable manager must treat as gone (it marks the row revoked and mints again). */\nexport class DelegatedKeyMissingError extends Error {\n readonly status = 404\n readonly code = 'not_found'\n constructor(keyId: string) {\n super(`Platform no longer accepts key ${keyId}`)\n this.name = 'DelegatedKeyMissingError'\n }\n}\n\n/** A Platform refusal surfaced to the durable manager. Carries the typed refusal, never a key. */\nexport class DelegatedKeyRefusalError extends Error {\n constructor(readonly refusal: DelegatedKeyRefusal) {\n super(refusal.message)\n this.name = 'DelegatedKeyRefusalError'\n }\n}\n\n/**\n * Platform reasons that mean the key will never work again: the manager revokes the row and mints a fresh key.\n * The rest are lapses the same key can recover from (funding, email, team seat, caller permission).\n */\nconst GONE_REASONS = new Set([\n 'key_not_found', 'key_revoked', 'key_expired', 'key_lineage_revoked',\n 'parent_key_not_found', 'parent_key_revoked', 'parent_key_expired', 'parent_key_lineage_revoked',\n 'ancestor_key_not_found', 'ancestor_key_revoked', 'ancestor_key_expired', 'ancestor_key_lineage_revoked',\n 'key_hierarchy_too_deep', 'team_member_unrecorded', 'attribution_unresolved', 'billing_account_missing', 'account_not_found',\n 'product_mismatch', 'key_attribution_missing', 'key_provisioner_unknown', 'key_name_not_product_specific',\n])\nconst SPENT_REASONS = new Set(['budget_exhausted', 'monthly_budget_exhausted'])\n\n/**\n * Plug the client into `createIdentityBoundWorkspaceKeyManager` for a\n * workspace-held key. Pass the manager `nameForIdentity` returning a logical\n * slot name (the client sends Platform's canonical `auto:` form).\n *\n * `getKey` reads Platform's verdict: a key gone for good is reported missing\n * (the manager marks it revoked and mints again); a spent key is reported\n * exhausted (the manager revokes a sized child and mints again, and keeps a\n * spend-through child, whose spent source Router refuses per request); a funding or\n * eligibility refusal is a typed error, so a lapse never retires a key that\n * still works.\n */\nexport function createDelegatedKeyProvisioner(input: {\n client: PlatformDelegatedKeyClient\n sourceKey: string\n product: string\n resource?: { type: string; id: string }\n allowedModels?: readonly string[]\n monthlyBudgetUsd?: number\n rpmLimit?: number\n expect?: { payerId?: string; sourceKeyId?: string; originAppId?: string | null }\n /** The `revoke-slot` payer for a `revokeKey` call that carries no slot (Platform refuses an SSO key's key mutations). */\n payerId?: string\n}): DelegatedKeyProvisioner {\n const product = input.product\n // The revoke-slot fallback needs the payer; the client reads each key's slot name itself.\n const slotOwner: DelegatedKeySlotRef | undefined = input.payerId\n ? { userId: input.payerId, ...(input.expect?.sourceKeyId ? { sourceKeyId: input.expect.sourceKeyId } : {}) }\n : undefined\n return {\n async createKey(create) {\n const minted = await input.client.delegate({\n sourceKey: input.sourceKey, name: create.name, product,\n ...(input.resource ? { resource: input.resource } : {}),\n ...(input.allowedModels ? { allowedModels: input.allowedModels } : {}),\n budget: { ...(create.spendThrough ? { spendThrough: true as const } : { usd: create.budgetUsd }),\n ...(input.monthlyBudgetUsd !== undefined ? { monthlyUsd: input.monthlyBudgetUsd } : {}) },\n ...(input.rpmLimit !== undefined ? { rpmLimit: input.rpmLimit } : {}),\n expiresAt: new Date(create.expiresAt),\n ...(input.expect ? { expect: input.expect } : {}),\n })\n if (!minted.succeeded) throw new DelegatedKeyRefusalError(minted.error)\n // Platform granted no budget of its own to a spend-through request: confirm it, so the manager never rotates it on spend.\n const spendThrough = create.spendThrough && minted.value.budgetUsd === null ? { spendThrough: true as const } : {}\n return { id: minted.value.id, key: minted.value.key, budgetUsd: minted.value.budgetUsd, ...spendThrough, expiresAt: minted.value.expiresAt.toISOString() }\n },\n async getKey(id) {\n const verdict = await input.client.verify({ keyId: id, product })\n if (!verdict.succeeded) throw new DelegatedKeyRefusalError(verdict.error)\n const v = verdict.value\n if (v.valid) {\n return {\n ...(v.budgetUsd !== undefined ? { budgetUsd: v.budgetUsd } : {}),\n ...(v.budgetUsd !== undefined && v.budgetRemaining !== undefined ? { budgetSpent: Math.max(0, v.budgetUsd - v.budgetRemaining) } : {}),\n // No budget of its own: a spend-through child, whose remainder is its source's.\n ...(v.budgetUsd === undefined && v.budgetRemaining !== undefined ? { budgetRemaining: v.budgetRemaining } : {}),\n ...(v.expiresAt ? { expiresAt: v.expiresAt } : {}),\n }\n }\n if (v.invalidReason && GONE_REASONS.has(v.invalidReason)) throw new DelegatedKeyMissingError(id)\n if (v.invalidReason && SPENT_REASONS.has(v.invalidReason)) {\n // Spent: the manager revokes a sized child before minting again; a spend-through child's spent source is not its own.\n return { budgetUsd: v.budgetUsd ?? 0, budgetSpent: v.budgetUsd ?? 0, ...(v.expiresAt ? { expiresAt: v.expiresAt } : {}) }\n }\n throw new DelegatedKeyRefusalError({ status: 403, code: 'delegated_key.refused',\n message: `Platform refused the key for now (${v.invalidReason ?? 'no reason'}).` })\n },\n async revokeKey(id, slot) {\n // A child is retired through its own slot: the source that minted it, never the current one (a sibling may not touch it).\n const owner: DelegatedKeySlotRef | undefined = slot\n ? { userId: slot.platformUserId, product, ...(slot.name ? { name: slot.name } : {}), ...(slot.sourceKeyId ? { sourceKeyId: slot.sourceKeyId } : {}) }\n : slotOwner\n const revoked = await input.client.revoke({ sourceKey: input.sourceKey, keyId: id, ...(owner ? { slot: owner } : {}) })\n if (!revoked.succeeded) throw new DelegatedKeyRefusalError(revoked.error)\n return null\n },\n async findCreatedKeys(find) {\n const listed = await input.client.listChildren({ sourceKey: input.sourceKey, name: find.name, product: find.product })\n if (!listed.succeeded) throw new DelegatedKeyRefusalError(listed.error)\n return listed.value\n },\n }\n}\n","import type { KeyCrypto } from '../billing'\nimport { assertWorkspaceKeyCryptoUsable } from '../billing/crypto-probe'\nimport { sha256Hex } from '../crypto/digest'\nimport type { DelegatedKeyOutcome, DelegatedKeyRequest, PlatformDelegatedKeyClient } from './delegated-keys'\n\n/**\n * Pre-minted turn keys. Creative minted each Router turn's child on the turn's critical path, ~320 ms of a\n * 6,419 ms first-visible p50 (router-spec). `createDelegatedTurnKeys` keeps one child per turn with\n * the same cap and expiry, and mints the next turn's child in the background (`waitUntil`) into a D1 slot. The\n * next turn takes it with one `DELETE ... RETURNING`, so a parked key serves exactly one turn and a racing second\n * turn mints inline. A parked key is used only when it was minted for the same request (source key, product,\n * models, budget, resource, payer: the slot's `scope` digest) and has `minRemainingMs` of life; otherwise the turn\n * mints inline exactly as before. A parked child Platform revoked or let expire is refused by the Router (401\n * `invalid_key` with that reason); the turn's `fetchImpl` mints inline once and resends. A spent budget\n * never re-mints: the turn keeps one cap. Each slot holds at most one unused key; a displaced key, or one minted\n * but not stored, is revoked, and one whose revoke fails expires on its own. The secret is stored encrypted.\n */\n\n/** Paste into a migration. `expires_at` is epoch ms; `scope` is the digest of the request the key was minted for. */\nexport const DELEGATED_KEY_PREMINT_TABLE_DDL = `CREATE TABLE IF NOT EXISTS delegated_key_premint (\n slot TEXT PRIMARY KEY,\n scope TEXT NOT NULL,\n turn_id TEXT NOT NULL,\n key_id TEXT NOT NULL,\n key_encrypted TEXT NOT NULL,\n expires_at INTEGER NOT NULL\n)`\n\n/** The D1 surface the slot store uses. A real `D1Database` satisfies it. */\nexport interface DelegatedKeyPremintD1Like {\n prepare(query: string): {\n bind(...values: unknown[]): { first<T = Record<string, unknown>>(): Promise<T | null>; run(): Promise<unknown> }\n }\n}\n\n/** What a turn's key is minted for. Its digest decides whether a parked key may serve a turn. */\nexport type DelegatedTurnKeyScope = Omit<DelegatedKeyRequest, 'name' | 'expiresAt' | 'retryUnavailable'>\n\nexport interface DelegatedTurnKeyInput {\n /** One parked key per slot, e.g. `<userId>:<workspaceId>:router`. */\n slot: string\n scope: DelegatedTurnKeyScope\n /** Life asked of Platform for each child; `notAfter` caps it. */\n ttlMs: number\n notAfter?: Date\n retryUnavailable?: DelegatedKeyRequest['retryUnavailable']\n /** The payer's Platform user id. Platform refuses `DELETE` from an app-provisioned (SSO) source key, so an unused\n * child is retired through `revoke-slot` with it; without it (or `scope.expect.payerId`) such a child just expires. */\n payerId?: string\n}\n\nexport interface DelegatedTurnKey {\n key: string\n id: string\n /** The logical id supplied to the mint: the turn's own id inline, a random id when pre-minted. Platform's\n * child name adds a per-mint suffix, so concurrent attempts never supersede one another. */\n turnId: string\n expiresAt: Date\n /** Parked before this turn: a revoked or expired refusal of it means mint inline (`delegatedKeyFallbackFetch`). */\n preminted: boolean\n}\n\n/** One turn owns its claimed/inline key and any revoked-key replacement until it calls `revoke`. */\nexport interface DelegatedTurnKeyLease extends DelegatedTurnKey {\n /** Use with the initial `key`; handles a first-request revoked/expired premint refusal automatically. */\n fetchImpl: typeof fetch\n /** Close this lease and retire every key it held, including a replacement still being minted. Idempotent. */\n revoke(): Promise<void>\n}\n\nexport interface DelegatedTurnKeyClaimTiming { digestMs: number; storeMs: number; decryptMs?: number }\n\nexport type DelegatedTurnKeyEvent =\n /** `timing` splits the claim on the turn's path: the scope digest, the slot's `DELETE … RETURNING` round trip, and\n * (claimed only) the decrypt. */\n | { type: 'claimed' | 'missed'; slot: string; timing?: DelegatedTurnKeyClaimTiming }\n | { type: 'parked' | 'park_kept'; slot: string }\n /** `keyId` names a child minted but not parked (retired best effort); never its key. */\n | { type: 'park_failed'; slot: string; code: string; keyId?: string }\n\nexport interface DelegatedTurnKeysOptions {\n client: Pick<PlatformDelegatedKeyClient, 'delegate' | 'revoke'>\n /** Null turns pre-minting off: every turn mints inline, as before. */\n db: DelegatedKeyPremintD1Like | null\n /** The app's at-rest crypto (`createFieldCrypto` from `./crypto`). */\n crypto: KeyCrypto\n /** Defaults to `delegated_key_premint`. */\n table?: string\n /** A parked key serves a turn only with at least this much life left. Default 10 min, above a turn's budget. */\n minRemainingMs?: number\n onEvent?: (event: DelegatedTurnKeyEvent) => void\n now?: () => number\n}\n\nexport interface DelegatedTurnKeys {\n /**\n * This turn's key: the slot's parked key, taken exactly once, else a fresh mint with a unique name. Then the\n * next turn's key is minted and parked through `waitUntil` (the Worker's `ctx.waitUntil`), off this turn's path.\n * Pass `value` as the shared Router producer's `apiKey`; the producer owns fallback fetch and cleanup.\n * Direct HTTP callers use `value.fetchImpl` and close `value.revoke()` themselves, including refusals.\n */\n forTurn(input: DelegatedTurnKeyInput & { turnId: string; waitUntil?: (promise: Promise<unknown>) => void }):\n Promise<DelegatedKeyOutcome<DelegatedTurnKeyLease>>\n /** Mint and park a key for the slot's next turn, e.g. when a member session opens. Never throws. */\n park(input: DelegatedTurnKeyInput): Promise<boolean>\n /** Retire only the parked key matching this exact slot and scope after a live domain refusal. Never throws. */\n forget(input: Pick<DelegatedTurnKeyInput, 'slot' | 'scope' | 'payerId'>): Promise<void>\n /** Mint inline, as a turn did before pre-minting. */\n mint(input: DelegatedTurnKeyInput & { turnId: string }): Promise<DelegatedKeyOutcome<DelegatedTurnKey>>\n}\n\nconst PREMINT_TABLE = 'delegated_key_premint'\nconst PREMINT_MIN_REMAINING_MS = 10 * 60_000\n// A parked key is kept rather than replaced while it has this much more life than a claim needs.\nconst PREMINT_KEEP_SLACK_MS = 5 * 60_000\n\n/** The digest of everything a child is minted for, so a key minted for another request never serves this one. */\nasync function scopeDigest(scope: DelegatedTurnKeyScope): Promise<string> {\n const budget = scope.budget\n return sha256Hex(JSON.stringify([\n scope.sourceKey, scope.product, scope.resource?.type ?? null, scope.resource?.id ?? null,\n scope.allowedModels ? [...new Set(scope.allowedModels)].sort() : null,\n budget && 'usd' in budget ? budget.usd : null, budget && 'spendThrough' in budget ? true : null, budget?.monthlyUsd ?? null,\n scope.rpmLimit ?? null, scope.expect?.payerId ?? null, scope.expect?.sourceKeyId ?? null, scope.expect?.originAppId ?? null,\n ]))\n}\n\nexport function createDelegatedTurnKeys(options: DelegatedTurnKeysOptions): DelegatedTurnKeys {\n const table = options.table ?? PREMINT_TABLE\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(table)) throw new Error(`Invalid delegated key premint table: ${JSON.stringify(table)}`)\n const now = options.now ?? Date.now\n const minRemainingMs = options.minRemainingMs ?? PREMINT_MIN_REMAINING_MS\n const emit = (event: DelegatedTurnKeyEvent) => { try { options.onEvent?.(event) } catch { /* a log hook never fails a turn */ } }\n const db = options.db\n\n async function mint(input: DelegatedTurnKeyInput & { turnId: string }, preminted: boolean): Promise<DelegatedKeyOutcome<DelegatedTurnKey>> {\n const expiresAt = new Date(Math.min(now() + input.ttlMs, input.notAfter?.getTime() ?? Infinity))\n const outcome = await options.client.delegate({\n ...input.scope, name: `turn:${input.turnId}:${crypto.randomUUID()}`, expiresAt,\n ...(input.retryUnavailable ? { retryUnavailable: input.retryUnavailable } : {}),\n })\n if (!outcome.succeeded) return outcome\n const { key, id } = outcome.value\n return { succeeded: true, value: { key, id, turnId: input.turnId, expiresAt: outcome.value.expiresAt, preminted } }\n }\n\n // Best effort: a key nobody will use is retired now, or expires on its own.\n async function retire(input: Pick<DelegatedTurnKeyInput, 'scope' | 'payerId'>, keyId: string): Promise<void> {\n const { scope } = input\n const payerId = scope.expect?.payerId ?? input.payerId\n await options.client.revoke({ sourceKey: scope.sourceKey, keyId,\n ...(payerId ? { slot: { userId: payerId, product: scope.product,\n ...(scope.expect?.sourceKeyId ? { sourceKeyId: scope.expect.sourceKeyId } : {}) } } : {}),\n }).catch(() => null)\n }\n\n function lease(input: DelegatedTurnKeyInput & { turnId: string }, key: DelegatedTurnKey): DelegatedTurnKeyLease {\n const turn = { ...input, scope: { ...input.scope,\n ...(input.scope.allowedModels ? { allowedModels: [...input.scope.allowedModels] } : {}),\n ...(input.scope.budget ? { budget: { ...input.scope.budget } } : {}),\n ...(input.scope.resource ? { resource: { ...input.scope.resource } } : {}),\n ...(input.scope.expect ? { expect: { ...input.scope.expect } } : {}),\n }, ...(input.notAfter ? { notAfter: new Date(input.notAfter) } : {}) }\n const held = new Set([key.id])\n const closed = { succeeded: false as const, error: {\n status: 409, code: 'delegated_key.refused' as const, message: 'The turn key lease is closed.',\n } }\n let released = false\n let replacement: Promise<DelegatedKeyOutcome<DelegatedTurnKey>> | undefined\n let retirement: Promise<void> | undefined\n const fetchImpl = delegatedKeyFallbackFetch({\n key,\n fetch: (resource, init) => released\n ? Promise.reject(new Error(closed.error.message)) : fetch(resource, init),\n remint: () => {\n if (released) return Promise.resolve(closed)\n return replacement ??= mint(turn, false).then(outcome => {\n if (outcome.succeeded) held.add(outcome.value.id)\n return released ? closed : outcome\n })\n },\n })\n return { ...key, fetchImpl, revoke() {\n released = true\n return retirement ??= (async () => {\n await replacement?.catch(() => undefined)\n await Promise.all([...held].map(id => retire(turn, id)))\n })()\n } }\n }\n\n async function claim(input: DelegatedTurnKeyInput, timing: Partial<DelegatedTurnKeyClaimTiming>): Promise<DelegatedTurnKey | null> {\n if (!db) return null\n const { slot, scope } = input\n let at = Date.now()\n const digest = await scopeDigest(scope)\n timing.digestMs = Date.now() - at\n at = Date.now()\n const row = await db.prepare(`DELETE FROM ${table} WHERE slot = ?1 AND scope = ?2 AND expires_at > ?3 AND expires_at <= ?4\nRETURNING turn_id, key_id, key_encrypted, expires_at`).bind(slot, digest, now() + minRemainingMs, input.notAfter?.getTime() ?? Number.MAX_SAFE_INTEGER)\n .first<{ turn_id: string; key_id: string; key_encrypted: string; expires_at: number }>()\n timing.storeMs = Date.now() - at\n if (!row) return null\n try {\n at = Date.now()\n const key = await options.crypto.decrypt(row.key_encrypted)\n timing.decryptMs = Date.now() - at\n return { key, id: row.key_id, turnId: row.turn_id, expiresAt: new Date(row.expires_at), preminted: true }\n } catch {\n await retire(input, row.key_id)\n return null\n }\n }\n\n async function park(input: DelegatedTurnKeyInput): Promise<boolean> {\n if (!db) return false\n let scope: string\n try {\n scope = await scopeDigest(input.scope)\n const held = await db.prepare(`SELECT scope, expires_at FROM ${table} WHERE slot = ?1`).bind(input.slot)\n .first<{ scope: string; expires_at: number }>()\n if (held?.scope === scope && held.expires_at > now() + minRemainingMs + PREMINT_KEEP_SLACK_MS\n && held.expires_at <= (input.notAfter?.getTime() ?? Infinity)) {\n emit({ type: 'park_kept', slot: input.slot })\n return true\n }\n } catch {\n emit({ type: 'park_failed', slot: input.slot, code: 'premint_store_failed' })\n return false\n }\n // The at-rest key is proven before Platform mints, so a crypto fault never orphans a billable child.\n try {\n await assertWorkspaceKeyCryptoUsable(options.crypto)\n } catch {\n emit({ type: 'park_failed', slot: input.slot, code: 'premint_crypto_unusable' })\n return false\n }\n const minted = await mint({ ...input, turnId: crypto.randomUUID() }, true).catch(() => ({\n succeeded: false as const, error: { status: 502, code: 'delegated_key.failed' as const, message: 'Background turn-key mint failed.' },\n }))\n if (!minted.succeeded) {\n emit({ type: 'park_failed', slot: input.slot, code: minted.error.code })\n return false\n }\n try {\n const encrypted = await options.crypto.encrypt(minted.value.key)\n // An unclaimed key this one replaces (another request's, or near expiry) is never handed out again.\n const displaced = await db.prepare(`DELETE FROM ${table} WHERE slot = ?1 RETURNING key_id`).bind(input.slot)\n .first<{ key_id: string }>()\n if (displaced) await retire(input, displaced.key_id)\n const stored = await db.prepare(`INSERT INTO ${table} (slot, scope, turn_id, key_id, key_encrypted, expires_at)\nVALUES (?1, ?2, ?3, ?4, ?5, ?6) ON CONFLICT(slot) DO NOTHING RETURNING slot`)\n .bind(input.slot, scope, minted.value.turnId, minted.value.id, encrypted, minted.value.expiresAt.getTime()).first()\n if (!stored) {\n // No row came back (a racing park filled the slot first): nothing will hand this key out.\n await retire(input, minted.value.id)\n emit({ type: 'park_kept', slot: input.slot })\n return true\n }\n emit({ type: 'parked', slot: input.slot })\n return true\n } catch {\n // The minted child never reached the slot, so nothing will hand it out: retire it now (best effort).\n await retire(input, minted.value.id)\n emit({ type: 'park_failed', slot: input.slot, code: 'premint_store_failed', keyId: minted.value.id })\n return false\n }\n }\n\n return {\n async forTurn(input) {\n // A slot store that fails (no table, D1 down) is a miss: the turn mints inline as before.\n const timing: Partial<DelegatedTurnKeyClaimTiming> = {}\n const claimed = await claim(input, timing).catch(() => null)\n if (db) {\n const next = park({ slot: input.slot, scope: input.scope, ttlMs: input.ttlMs,\n ...(input.notAfter ? { notAfter: input.notAfter } : {}), ...(input.payerId ? { payerId: input.payerId } : {}) })\n input.waitUntil?.(next)\n }\n emit({ type: claimed ? 'claimed' : 'missed', slot: input.slot,\n ...(timing.digestMs !== undefined && timing.storeMs !== undefined ? { timing: timing as DelegatedTurnKeyClaimTiming } : {}) })\n const outcome = claimed ? { succeeded: true as const, value: claimed } : await mint(input, false)\n return outcome.succeeded ? { succeeded: true, value: lease(input, outcome.value) } : outcome\n },\n park,\n async forget(input) {\n if (!db) return\n try {\n const row = await db.prepare(`DELETE FROM ${table} WHERE slot = ?1 AND scope = ?2 RETURNING key_id`)\n .bind(input.slot, await scopeDigest(input.scope)).first<{ key_id: string }>()\n if (row) await retire(input, row.key_id)\n } catch { /* a refused turn never hands out the slot; its key expires if retirement is unavailable */ }\n },\n mint: (input) => mint(input, false),\n }\n}\n\n/** 401 codes that mean Platform no longer honours the key itself (tangle-router lib/key-refusal.ts and\n * app/api/chat/auth-admission.ts): `invalid_key` naming `key_revoked`/`key_expired`, and the codes reviewers named. */\nconst REFUSED_KEY_CODES = new Set(['key_revoked', 'key_expired', 'invalid_api_key', 'invalid_key_contract'])\n\n/** Whether the Router refused the key as revoked, expired or invalid. Only a 401 counts: Router's 403s\n * (email verification, product scope, routing rules) are not revocation, a 402 `key_budget_exhausted` is the\n * turn's own cap, and a bare `invalid_key` can be a spent key; re-minting for any of those would give the turn\n * a second cap. */\nasync function refusedKey(response: Response): Promise<boolean> {\n if (response.status !== 401) return false\n const body = await response.clone().json().catch(() => null) as { error?: { code?: unknown; reason?: unknown } } | null\n const code = body?.error?.code\n return typeof code === 'string' && (REFUSED_KEY_CODES.has(code) ||\n (code === 'invalid_key' && (body?.error?.reason === 'key_revoked' || body?.error?.reason === 'key_expired')))\n}\n\n/**\n * A fetch for one turn that sends a pre-minted key. When the Router refuses the turn's FIRST request with it as\n * revoked, expired or invalid (Platform retired the parked child), it mints inline once and resends that request\n * with the fresh key; later requests carry the fresh key. Any other refusal, and any refusal later in the turn, is\n * the turn's answer. A stream body on the first request is buffered so it can be resent. Requests whose\n * `init.headers` carry another credential, and keys minted inline, pass through. Make one per turn.\n */\nexport function delegatedKeyFallbackFetch(input: {\n key: DelegatedTurnKey\n remint: () => Promise<DelegatedKeyOutcome<DelegatedTurnKey>>\n fetch?: typeof fetch\n onReplaced?: (key: DelegatedTurnKey) => void\n}): typeof fetch {\n const base = input.fetch ?? fetch\n if (!input.key.preminted) return base\n const parked = `Bearer ${input.key.key}`\n let first = true\n let fresh: string | undefined\n return async (resource, init) => {\n const headers = new Headers(init?.headers)\n if (headers.get('authorization') !== parked) return base(resource, init)\n if (fresh) {\n headers.set('authorization', fresh)\n return base(resource, { ...init, headers })\n }\n if (!first) return base(resource, init)\n first = false\n const body = init?.body instanceof ReadableStream ? await new Response(init.body).arrayBuffer() : init?.body\n const send = () => base(resource, { ...init, headers, ...(body !== undefined ? { body } : {}) })\n const response = await send()\n if (!(await refusedKey(response))) return response\n const reminted = await input.remint()\n if (!reminted.succeeded) return response\n await response.body?.cancel().catch(() => {})\n fresh = `Bearer ${reminted.value.key}`\n headers.set('authorization', fresh)\n input.onReplaced?.(reminted.value)\n return send()\n }\n}\n","import { createWarmCache, type WarmCacheOptions, type WarmCacheSource } from '../sandbox/warm-cache'\n\n/**\n * A billable turn's seat and balance verdict, read from Platform once per user\n * per window instead of on every turn. Lifted from Creative\n * (creative-agent#692): in production its seat and balance reads\n * took 723 ms each, most of the 949 ms of its turn gates.\n *\n * Only a passing verdict is kept. A refusal is never cached, so a seatless or\n * unfunded user always gets the live read and its 402. Within the window the\n * balance stays enforced where money moves: the Tangle Router holds spend\n * before it calls a provider and refuses a balance at or below zero. The entry\n * ends at `windowMs` or at the seat's `paidThrough`, whichever is first, and is\n * dropped on any refusal: a seat or balance refusal read here, or one the\n * product sees elsewhere and reports with `forget` (Creative calls it when\n * Platform refuses to fund a turn's Router key). Only the data center's cache\n * holds it (no isolate copy), so that drop reaches every isolate in the data\n * center where it runs. The Workers cache is per data center: a verdict kept\n * in another data center lives on until its own window ends, and the Tangle\n * Router still refuses an unfunded key there.\n *\n * The verdict is keyed by `userId` unless `key` says otherwise: an app whose\n * seat or balance read depends on more than the user (a workspace, an\n * organization) must pass `key`, or one scope's verdict admits another.\n *\n * Passing verdicts are kept for five minutes by default, capped by the paid\n * period. `windowMs` declares a product entitlement freshness requirement; it\n * does not enable caching. Spend is still enforced live by the model service.\n */\n\n/** A Platform read's verdict: only `allowed` decides admission. */\nexport interface BillableTurnVerdict {\n allowed: boolean\n}\n\n/** A seat verdict; `paidThrough` (ISO) ends a kept verdict early, `null` when access is not a dated seat. */\nexport interface BillableTurnSeatVerdict extends BillableTurnVerdict {\n paidThrough?: string | null\n}\n\nexport interface BillableTurnAdmissionOptions<\n Input extends { userId: string },\n Seat extends BillableTurnSeatVerdict,\n Balance extends BillableTurnVerdict,\n> {\n /** The cache URL's host, one per product, such as `billing-admission.creative.internal`. */\n namespace: string\n /** A product entitlement freshness limit. Default five minutes, capped by `paidThrough`. */\n windowMs?: number\n readSeat(input: Input): Promise<Seat>\n /** A separate funding read, when funding is not already part of readSeat's entitlement verdict. */\n readBalance?(input: Input): Promise<Balance>\n /** The deployment environment in the cache key (see {@link WarmCacheOptions.env}). */\n env?: WarmCacheOptions['env']\n /** What a verdict is kept under: everything `readSeat` and `readBalance` depend on. Default `input.userId`. */\n key?(input: Input): string\n}\n\nexport interface AdmitBillableTurnOptions {\n /** Turns a Platform read failure into the caller's error. */\n mapError?: (error: unknown) => never\n /** Names each Platform read (`gate_seat`, `gate_balance`) for the turn's timing. */\n track?: <T>(name: string, work: Promise<T>) => Promise<T>\n /** Read Platform even over a kept verdict, so the window starts now (a prewarm step). */\n refresh?: boolean\n}\n\nexport type BillableTurnAdmissionResult<Seat, Balance> =\n | { source: WarmCacheSource; allowed: true; paidThrough: string | null }\n | { source: 'platform'; allowed: boolean; paidThrough: string | null; seat: Seat; balance?: Balance }\n\nexport interface BillableTurnAdmission<Input extends { userId: string }, Seat, Balance> {\n /**\n * Entitlement and any separate balance read run concurrently: an entitlement refusal or read failure\n * wins over anything the balance read returned. A kept verdict returns\n * without calling Platform. `balance` is absent when the entitlement refused or no separate read is needed.\n */\n admit(input: Input & AdmitBillableTurnOptions): Promise<BillableTurnAdmissionResult<Seat, Balance>>\n /** A refusal seen elsewhere: the next turn under this key (the user id unless `key` is set) reads Platform again. */\n forget(key: string): Promise<void>\n /** How long a verdict read now is kept: the window, or less when `paidThrough` comes first. */\n heldMs(paidThrough: string | null | undefined): number\n}\n\nexport function createBillableTurnAdmission<\n Input extends { userId: string },\n Seat extends BillableTurnSeatVerdict,\n Balance extends BillableTurnVerdict,\n>(options: BillableTurnAdmissionOptions<Input, Seat, Balance>): BillableTurnAdmission<Input, Seat, Balance> {\n const windowMs = options.windowMs ?? 5 * 60_000\n if (!(Number.isFinite(windowMs) && windowMs > 0)) {\n throw new Error('createBillableTurnAdmission: windowMs must be a positive number of milliseconds')\n }\n const verdicts = createWarmCache<{ paidThrough: string | null }>(options.namespace, { isolate: false, env: options.env })\n const keyOf = options.key ?? ((input: Input) => input.userId)\n const heldMs = (paidThrough: string | null | undefined) =>\n Math.min(windowMs, paidThrough ? Date.parse(paidThrough) - Date.now() : Infinity)\n\n return {\n heldMs,\n forget: key => verdicts.forget(key),\n async admit(input) {\n const key = keyOf(input)\n const warm = input.refresh ? null : await verdicts.read(key)\n if (warm && (warm.value.paidThrough === null || Date.parse(warm.value.paidThrough) > Date.now())) {\n return { source: warm.source, allowed: true, paidThrough: warm.value.paidThrough }\n }\n const track = input.track ?? (<T>(_name: string, work: Promise<T>) => work)\n const mapError = input.mapError ?? ((error: unknown): never => { throw error })\n const [seatSettled, balanceSettled] = await Promise.allSettled([\n track('gate_seat', options.readSeat(input).catch(mapError)),\n options.readBalance ? track('gate_balance', options.readBalance(input).catch(mapError)) : Promise.resolve(undefined),\n ])\n if (seatSettled.status === 'rejected') throw seatSettled.reason\n const seat = seatSettled.value\n if (!seat.allowed) {\n await verdicts.forget(key)\n return { source: 'platform', allowed: false, paidThrough: seat.paidThrough ?? null, seat }\n }\n if (balanceSettled.status === 'rejected') throw balanceSettled.reason\n const balance = balanceSettled.value\n if (options.readBalance && !balance!.allowed) {\n await verdicts.forget(key)\n return { source: 'platform', allowed: false, paidThrough: seat.paidThrough ?? null, seat, balance }\n }\n const paidThrough = seat.paidThrough ?? null\n const ttlMs = heldMs(paidThrough)\n if (ttlMs > 0) await verdicts.write(key, { paidThrough }, ttlMs)\n return { source: 'platform', allowed: true, paidThrough, seat, balance }\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BO,IAAM,8BAA8B;AAGpC,IAAM,sCAAsC;AAAA,EACjD,4GAA4G,2BAA2B;AAAA,EACvI,gGAAgG,2BAA2B;AAC7H;AA4DA,IAAM,iBAAiB;AAEvB,SAAS,WAAW,OAAe,OAAuB;AACxD,MAAI,CAAC,eAAe,KAAK,KAAK,EAAG,OAAM,IAAI,MAAM,wCAAwC,KAAK,EAAE;AAChG,SAAO;AACT;AAEA,IAAM,sBAAsB;AAAA,EAC1B,MAAM;AAAA,IACJ,OAAO;AAAA,IACP,SAAS,EAAE,IAAI,MAAM,MAAM,QAAQ,OAAO,SAAS,eAAe,iBAAiB,WAAW,aAAa,WAAW,YAAY;AAAA,EACpI;AAAA,EACA,SAAS;AAAA,IACP,OAAO;AAAA,IACP,SAAS,EAAE,IAAI,MAAM,QAAQ,UAAU,OAAO,SAAS,WAAW,aAAa,WAAW,aAAa,WAAW,aAAa,WAAW,aAAa,WAAW,YAAY;AAAA,EAChL;AAAA,EACA,SAAS;AAAA,IACP,OAAO;AAAA,IACP,SAAS,EAAE,IAAI,MAAM,QA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