@codemem/core 0.47.0 → 0.47.2

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.
Files changed (33) hide show
  1. package/dist/account-owner-association-directory.d.ts +11 -0
  2. package/dist/account-owner-association-directory.d.ts.map +1 -1
  3. package/dist/better-sqlite-coordinator-store.d.ts +1 -0
  4. package/dist/better-sqlite-coordinator-store.d.ts.map +1 -1
  5. package/dist/coordinator-api.d.ts.map +1 -1
  6. package/dist/coordinator-device-ownership-evidence-queries.d.ts +6 -0
  7. package/dist/coordinator-device-ownership-evidence-queries.d.ts.map +1 -1
  8. package/dist/coordinator-device-ownership-evidence.d.ts.map +1 -1
  9. package/dist/coordinator-peer-discovery.d.ts +1 -1
  10. package/dist/coordinator-peer-discovery.d.ts.map +1 -1
  11. package/dist/coordinator-store-contract.d.ts +1 -0
  12. package/dist/coordinator-store-contract.d.ts.map +1 -1
  13. package/dist/d1-coordinator-store.d.ts +1 -0
  14. package/dist/d1-coordinator-store.d.ts.map +1 -1
  15. package/dist/index.d.ts +2 -1
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +8954 -8938
  18. package/dist/index.js.map +1 -1
  19. package/dist/ingest-prompts.d.ts.map +1 -1
  20. package/dist/internal/cloudflare-coordinator.js +7 -2
  21. package/dist/internal/cloudflare-coordinator.js.map +1 -1
  22. package/dist/{owner-enrollment-start-XwN1p7du.js → owner-enrollment-start-DHh8A5hh.js} +1602 -1590
  23. package/dist/owner-enrollment-start-DHh8A5hh.js.map +1 -0
  24. package/dist/semantic-worker-entry.js +1 -1
  25. package/dist/{semantic-worker-job-a7S-qbRH.js → semantic-worker-job-CO2R4WlZ.js} +2 -2
  26. package/dist/{semantic-worker-job-a7S-qbRH.js.map → semantic-worker-job-CO2R4WlZ.js.map} +1 -1
  27. package/dist/{semantic-worker-ranking-hRyoWJtp.js → semantic-worker-ranking-D6VCmP_p.js} +7 -2
  28. package/dist/{semantic-worker-ranking-hRyoWJtp.js.map → semantic-worker-ranking-D6VCmP_p.js.map} +1 -1
  29. package/dist/{workspace-identity-C2g2-ZRR.js → workspace-identity-nF_U-y6A.js} +1432 -1391
  30. package/dist/workspace-identity-nF_U-y6A.js.map +1 -0
  31. package/package.json +3 -3
  32. package/dist/owner-enrollment-start-XwN1p7du.js.map +0 -1
  33. package/dist/workspace-identity-C2g2-ZRR.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"cloudflare-coordinator.js","names":[],"sources":["../../src/coordinator-account-change-browser.ts","../../src/coordinator-browser-account.ts","../../src/coordinator-browser-auth-callback.ts","../../src/coordinator-browser-link.ts","../../src/coordinator-browser-link-completion.ts","../../src/coordinator-browser-link-start.ts","../../src/coordinator-browser-signin-start.ts","../../src/coordinator-device-rebind-view.ts","../../src/coordinator-device-rebind-browser.ts","../../src/coordinator-owner-enrollment-http.ts","../../src/owner-browser-admission-body.ts","../../src/owner-browser-admission.ts","../../src/coordinator-browser-auth-app.ts","../../src/coordinator-owner-enrollment-qualification.ts","../../src/coordinator-owner-qualification-route.ts","../../src/coordinator-owner-qualification-http.ts","../../src/d1-coordinator-store.ts","../../src/d1-coordinator-runtime.ts"],"sourcesContent":["import type { AccountChangeOperations } from \"./coordinator-account-change.js\";\nimport type {\n\tCoordinatorAuthBrowserConfig,\n\tCoordinatorAuthBrowserTransactionPurposeStore,\n\tCoordinatorAuthBrowserTransactionStore,\n} from \"./coordinator-auth-browser-transaction-contract.js\";\nimport {\n\ttype CoordinatorAuthBrowserPage,\n\tprojectAccountProfileView,\n\trenderAuthBrowserNotice,\n\trenderAuthLinkCompletionHopPage,\n\trenderAuthSigninContinuePage,\n} from \"./coordinator-auth-browser-view.js\";\nimport { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport {\n\tdecodeCoordinatorAuthProof32,\n\tencodeCoordinatorAuthProof32,\n\thashCoordinatorAuthProofBytes32,\n} from \"./coordinator-auth-proof.js\";\nimport { captureCoordinatorBrowserAuthConfig } from \"./coordinator-browser-auth-config.js\";\nimport {\n\tclearBrowserCookie,\n\tissueBrowserCookie,\n\treadBrowserCookie,\n\treissueStartCookieAsTransaction,\n} from \"./coordinator-browser-credential.js\";\nimport {\n\ttype BrowserCsrfKey,\n\tisBrowserCsrfKey,\n\tissueBrowserCsrfToken,\n} from \"./coordinator-browser-csrf.js\";\nimport { checkBrowserAuthRequestRate, guardBrowserForm } from \"./coordinator-browser-form-guard.js\";\nimport { snapshotBrowserRequest } from \"./coordinator-browser-request.js\";\nimport { readBrowserStartTransaction } from \"./coordinator-browser-start-transaction.js\";\nimport {\n\ttype CoordinatorOidcClient,\n\ttype CoordinatorOidcOptions,\n\tcreateCoordinatorOidcClient,\n} from \"./coordinator-oidc.js\";\nimport type { InMemoryRequestRateLimiter } from \"./request-rate-limit.js\";\n\ntype Pins = { attemptId: string; binderHash: string; stateHash: string };\ntype Operations = Pick<\n\tAccountChangeOperations,\n\t| \"claimBrowser\"\n\t| \"hasPendingCallback\"\n\t| \"consumeCallback\"\n\t| \"recordVerifiedCallback\"\n\t| \"confirmDisconnect\"\n\t| \"failConsumed\"\n\t| \"readBrowserView\"\n\t| \"readCallbackView\"\n>;\ntype Existing = Pick<CoordinatorAuthBrowserTransactionStore, \"readAuthBrowserTransactionActivity\"> &\n\tCoordinatorAuthBrowserTransactionPurposeStore;\n\n/** Private storage capabilities, never public status DTOs or request-nominated context. */\nexport type AccountChangeBrowserReaders = Pick<\n\tAccountChangeOperations,\n\t\"readStart\" | \"readManagementActivity\" | \"readBrowserBinding\"\n>;\ntype BrowserView = NonNullable<Awaited<ReturnType<Operations[\"readBrowserView\"]>>> & {\n\tstateHash: string;\n};\nexport interface AccountChangeBrowserInput {\n\tconfig: unknown;\n\tcsrfKey: BrowserCsrfKey;\n\toperations: Operations;\n\treaders: AccountChangeBrowserReaders;\n\texisting: Existing;\n\tlimiter: InMemoryRequestRateLimiter;\n\toidcOptions?: CoordinatorOidcOptions;\n}\nexport const ACCOUNT_CHANGE_BROWSER_PATHS = Object.freeze({\n\tstart: \"/auth/account/change/start\",\n\tconfirm: \"/auth/account/change/confirm\",\n});\n\nfunction pageResponse(page: CoordinatorAuthBrowserPage, status = 200) {\n\treturn new Response(page.body, { status, headers: page.headers });\n}\nfunction escapeHtml(value: string) {\n\treturn value\n\t\t.replaceAll(\"&\", \"&amp;\")\n\t\t.replaceAll(\"<\", \"&lt;\")\n\t\t.replaceAll(\">\", \"&gt;\")\n\t\t.replaceAll('\"', \"&quot;\")\n\t\t.replaceAll(\"'\", \"&#39;\");\n}\nasync function notice(status = 403): Promise<Response> {\n\ttry {\n\t\treturn pageResponse(await renderAuthBrowserNotice(\"auth_unavailable\"), status);\n\t} catch {\n\t\treturn new Response(\"Account change unavailable. Return to your terminal and try again.\", {\n\t\t\tstatus: 503,\n\t\t\theaders: {\n\t\t\t\t\"Cache-Control\": \"no-store\",\n\t\t\t\t\"Referrer-Policy\": \"no-referrer\",\n\t\t\t\t\"X-Content-Type-Options\": \"nosniff\",\n\t\t\t},\n\t\t});\n\t}\n}\nasync function formPage(\n\ttitle: string,\n\taction: string,\n\tfields: Record<string, string>,\n\tdetail = \"\",\n) {\n\tconst headers = (await renderAuthBrowserNotice(\"auth_unavailable\")).headers;\n\theaders[\"Referrer-Policy\"] = \"same-origin\";\n\tconst hidden = Object.entries(fields)\n\t\t.map(\n\t\t\t([name, value]) =>\n\t\t\t\t`<input type=\"hidden\" name=\"${escapeHtml(name)}\" value=\"${escapeHtml(value)}\">`,\n\t\t)\n\t\t.join(\"\");\n\treturn new Response(\n\t\t`<!doctype html><html lang=\"en\"><meta charset=\"utf-8\"><meta name=\"referrer\" content=\"same-origin\"><title>${escapeHtml(title)}</title><main><h1>${escapeHtml(title)}</h1><p>${escapeHtml(detail)}</p><form method=\"post\" action=\"${action}\">${hidden}<button type=\"submit\">${escapeHtml(title)}</button></form></main></html>`,\n\t\t{ headers },\n\t);\n}\nasync function stateHash(state: string) {\n\tconst digest = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(state));\n\treturn Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\nfunction startQuery(text: string, startUrl: string) {\n\tif (text.length > 8192 || text.includes(\"#\")) return null;\n\tconst url = new URL(text);\n\tif (\n\t\turl.href !== text ||\n\t\t`${url.origin}${url.pathname}` !== startUrl ||\n\t\turl.username ||\n\t\turl.password\n\t)\n\t\treturn null;\n\tif (\n\t\t[...url.searchParams].length !== 2 ||\n\t\turl.searchParams.getAll(\"attempt_id\").length !== 1 ||\n\t\turl.searchParams.getAll(\"start_code\").length !== 1\n\t)\n\t\treturn null;\n\tconst attemptId = url.searchParams.get(\"attempt_id\"),\n\t\tstartCode = url.searchParams.get(\"start_code\");\n\tif (!isAuthControllerId(attemptId) || !startCode || !decodeCoordinatorAuthProof32(startCode))\n\t\treturn null;\n\treturn { attemptId, startCode };\n}\nasync function privateStart(\n\treaders: AccountChangeBrowserReaders,\n\tattemptId: string,\n\tstartCode: string,\n\tconfig: CoordinatorAuthBrowserConfig,\n) {\n\tconst bytes = decodeCoordinatorAuthProof32(startCode);\n\tif (!bytes) return null;\n\tconst browserStartHash = await hashCoordinatorAuthProofBytes32(bytes);\n\tconst view = await readers.readStart({ attemptId, browserStartHash }, config);\n\tif (!view || (view.intent !== \"refresh\" && view.intent !== \"disconnect\")) return null;\n\treturn { browserStartHash, intent: view.intent };\n}\nasync function inactive(\n\tcookie: string | null,\n\tinput: AccountChangeBrowserInput,\n\tconfig: CoordinatorAuthBrowserConfig,\n) {\n\tconst ordinary = await readBrowserStartTransaction(cookie, input.existing, config);\n\tif (ordinary === \"invalid\" || ordinary === \"active\") return false;\n\tconst transaction = await readBrowserCookie(cookie, \"transaction\");\n\tif (transaction.kind === \"absent\") return true;\n\tif (transaction.kind !== \"present\") return false;\n\treturn (\n\t\t(await input.readers.readManagementActivity({ binderHash: transaction.cookieHash }, config))\n\t\t\t.kind === \"inactive\"\n\t);\n}\nasync function completion(view: { loopbackRedirect: string; attemptId: string }, secret: string) {\n\treturn pageResponse(\n\t\tawait renderAuthLinkCompletionHopPage({\n\t\t\tdestination: view.loopbackRedirect,\n\t\t\tattemptId: view.attemptId,\n\t\t\tcompletionSecret: secret,\n\t\t}),\n\t);\n}\n\n/** Hosted handlers mounted by the schema-ready browser composition.\n * The composition root provides private, proof-bound readers.\n * Only a successful credential POST promotes a cookie; no GET/callback clears one.\n * Device-signed finalization remains separate. Never log queries, forms or proofs.\n */\ntype Context = {\n\tinput: AccountChangeBrowserInput;\n\tconfig: CoordinatorAuthBrowserConfig;\n\tscope: { publicOrigin: string; store: CoordinatorAuthBrowserConfig };\n\tclient: CoordinatorOidcClient;\n\tstartUrl: string;\n\tconfirmUrl: string;\n};\nasync function startCookie(cookieHeader: string | null) {\n\tconst existing = await readBrowserCookie(cookieHeader, \"start\");\n\tif (existing.kind === \"invalid\") return null;\n\treturn existing.kind === \"present\" ? existing : issueBrowserCookie(\"start\");\n}\nasync function startPage(context: Context, request: Request): Promise<Response> {\n\tconst { input, config, scope, startUrl } = context;\n\ttry {\n\t\tconst snapshot = snapshotBrowserRequest(request);\n\t\tif (snapshot.method !== \"GET\") return notice(405);\n\t\tconst query = startQuery(snapshot.url, startUrl);\n\t\tif (!query) return notice(400);\n\t\tif (!(await privateStart(input.readers, query.attemptId, query.startCode, config)))\n\t\t\treturn notice();\n\t\tif (!(await inactive(snapshot.cookie, input, config))) return notice(409);\n\t\tconst cookie = await startCookie(snapshot.cookie);\n\t\tif (!cookie) return notice(400);\n\t\tconst csrf = await issueBrowserCsrfToken(input.csrfKey, cookie.secret, \"start\", scope);\n\t\tconst response = await formPage(\"Continue with Google\", ACCOUNT_CHANGE_BROWSER_PATHS.start, {\n\t\t\tattempt_id: query.attemptId,\n\t\t\tstart_code: query.startCode,\n\t\t\tcsrf,\n\t\t});\n\t\tif (\"setCookie\" in cookie) response.headers.append(\"Set-Cookie\", cookie.setCookie);\n\t\treturn response;\n\t} catch {\n\t\treturn notice(503);\n\t}\n}\nasync function start(context: Context, request: Request, clientKey: string): Promise<Response> {\n\tconst { input, config, scope, startUrl } = context;\n\ttry {\n\t\tconst snapshot = snapshotBrowserRequest(request);\n\t\tif (snapshot.method !== \"POST\") return notice(405);\n\t\tif (snapshot.url !== startUrl) return notice(404);\n\t\tconst guard = await guardBrowserForm({\n\t\t\trequest,\n\t\t\tclientKey,\n\t\t\tscope,\n\t\t\tcsrfKey: input.csrfKey,\n\t\t\tlimiter: input.limiter,\n\t\t\taction: \"link_start\",\n\t\t});\n\t\tif (!guard.ok) return notice(guard.error === \"rate_limited\" ? 429 : 403);\n\t\tif (guard.action !== \"link_start\") return notice();\n\t\tif (!(await inactive(snapshot.cookie, input, config))) return notice(409);\n\t\treturn await admitStart(context, snapshot.cookie, guard);\n\t} catch {\n\t\treturn notice(503);\n\t}\n}\nasync function admitStart(\n\tcontext: Context,\n\tcookieHeader: string | null,\n\tguard: { attemptId: string; startCode: string; cookieHash: string },\n) {\n\tconst { input, config, client } = context;\n\tconst proof = await privateStart(input.readers, guard.attemptId, guard.startCode, config);\n\tconst cookie = await readBrowserCookie(cookieHeader, \"start\");\n\tif (!proof || cookie.kind !== \"present\" || cookie.cookieHash !== guard.cookieHash)\n\t\treturn notice();\n\tconst authorization = await client.createAuthorizationRequest();\n\tconst response = pageResponse(\n\t\tawait renderAuthSigninContinuePage({ authorizationUrl: authorization.authorizationUrl }),\n\t);\n\tconst claimed = await input.operations.claimBrowser(\n\t\t{\n\t\t\tattemptId: guard.attemptId,\n\t\t\tbrowserStartHash: proof.browserStartHash,\n\t\t\tstateHash: await stateHash(authorization.material.state),\n\t\t\tbinderHash: guard.cookieHash,\n\t\t\tnonce: authorization.material.nonce,\n\t\t\tpkceVerifier: authorization.material.pkceVerifier,\n\t\t},\n\t\tconfig,\n\t);\n\tif (!claimed) return notice(409);\n\tresponse.headers.append(\"Set-Cookie\", reissueStartCookieAsTransaction(cookie.secret));\n\tresponse.headers.append(\"Set-Cookie\", clearBrowserCookie(\"start\"));\n\treturn response;\n}\nasync function callbackPins(context: Context, request: Request) {\n\tconst { config } = context;\n\tconst snapshot = snapshotBrowserRequest(request);\n\tif (snapshot.method !== \"GET\" || snapshot.url.length > 8192 || snapshot.url.includes(\"#\"))\n\t\treturn null;\n\tconst url = new URL(snapshot.url),\n\t\tredirect = new URL(config.redirectUri);\n\tif (\n\t\turl.origin !== redirect.origin ||\n\t\turl.pathname !== redirect.pathname ||\n\t\turl.username ||\n\t\turl.password ||\n\t\turl.searchParams.getAll(\"state\").length !== 1\n\t)\n\t\treturn null;\n\tconst state = url.searchParams.get(\"state\");\n\tif (!state || !/^[A-Za-z0-9._~-]{43,128}$/.test(state)) return null;\n\tconst cookie = await readBrowserCookie(snapshot.cookie, \"transaction\");\n\tif (cookie.kind !== \"present\") return null;\n\treturn {\n\t\tstate,\n\t\tstateHash: await stateHash(state),\n\t\tbinderHash: cookie.cookieHash,\n\t\tcookie,\n\t\tcallbackUrl: snapshot.url,\n\t};\n}\nasync function matchesCallback(context: Context, request: Request): Promise<boolean> {\n\tconst { input, config } = context;\n\ttry {\n\t\tconst pins = await callbackPins(context, request);\n\t\treturn (\n\t\t\t!!pins &&\n\t\t\t(await input.operations.hasPendingCallback(\n\t\t\t\t{ stateHash: pins.stateHash, binderHash: pins.binderHash },\n\t\t\t\tconfig,\n\t\t\t))\n\t\t);\n\t} catch {\n\t\treturn false;\n\t}\n}\nasync function prepareVerifiedResponse(\n\tcontext: Context,\n\tpins: Pins,\n\tsecret: string,\n\tcookie: Extract<Awaited<ReturnType<typeof readBrowserCookie>>, { kind: \"present\" }>,\n\tverifiedProfile: Parameters<typeof projectAccountProfileView>[0],\n) {\n\tconst { input, config, scope } = context;\n\tconst view = await input.operations.readCallbackView(pins, config);\n\tif (!view || view.attemptId !== pins.attemptId) throw new Error(\"callback_unavailable\");\n\tif (view.intent === \"refresh\") return completion(view, secret);\n\tif (view.intent !== \"disconnect\") throw new Error(\"callback_unavailable\");\n\tconst csrf = await issueBrowserCsrfToken(input.csrfKey, cookie.secret, \"transaction\", scope);\n\tconst profile = projectAccountProfileView(verifiedProfile, config.issuer);\n\treturn formPage(\n\t\t\"Disconnect Google account\",\n\t\tACCOUNT_CHANGE_BROWSER_PATHS.confirm,\n\t\t{ attempt_id: pins.attemptId, csrf },\n\t\t`${profile.email ?? profile.title}. Disconnecting ends browser sessions for this connection and removes its display profile. Identity, device keys, history, membership, and access grants stay unchanged.`,\n\t);\n}\nasync function browserView(context: Context, pins: { attemptId: string; binderHash: string }) {\n\tconst { input, config } = context;\n\tconst binding = await input.readers.readBrowserBinding(pins, config);\n\tif (!binding || !/^[a-f0-9]{64}$/.test(binding.stateHash)) return null;\n\tconst view = await input.operations.readBrowserView(\n\t\t{ ...pins, stateHash: binding.stateHash },\n\t\tconfig,\n\t);\n\treturn view ? { ...view, stateHash: binding.stateHash } : null;\n}\nasync function callback(context: Context, request: Request, clientKey: string): Promise<Response> {\n\tconst { input, config } = context;\n\ttry {\n\t\tif (!isAuthControllerId(clientKey)) return notice(503);\n\t\tconst rate = checkBrowserAuthRequestRate(\n\t\t\trequest,\n\t\t\tinput.limiter,\n\t\t\tJSON.stringify([\"browser-callback\", config.coordinatorId, clientKey]),\n\t\t\t20,\n\t\t);\n\t\tif (!rate.allowed) return notice(429);\n\t\tconst material = await callbackPins(context, request);\n\t\tif (!material) return notice();\n\t\tconst lookup = { stateHash: material.stateHash, binderHash: material.binderHash };\n\t\t// Shared-purpose collisions never consume either ceremony or contact Google.\n\t\tif (await input.existing.readAuthBrowserTransactionPurpose(lookup, config)) return notice();\n\t\tconst consumed = await input.operations.consumeCallback(lookup, config);\n\t\tif (!consumed) return notice();\n\t\tconst pins = { ...lookup, attemptId: consumed.attemptId };\n\t\treturn await exchange(context, material, consumed, pins);\n\t} catch {\n\t\treturn notice(503);\n\t}\n}\nasync function exchange(\n\tcontext: Context,\n\tmaterial: NonNullable<Awaited<ReturnType<typeof callbackPins>>>,\n\tconsumed: NonNullable<Awaited<ReturnType<Operations[\"consumeCallback\"]>>>,\n\tpins: Pins,\n) {\n\tconst { input, config, client } = context;\n\ttry {\n\t\tif (!consumed.nonce || !consumed.pkceVerifier) throw new Error(\"missing_material\");\n\t\tconst verified = await client.verifyCallback({\n\t\t\tcallbackUrl: material.callbackUrl,\n\t\t\tmaterial: {\n\t\t\t\tstate: material.state,\n\t\t\t\tnonce: consumed.nonce,\n\t\t\t\tpkceVerifier: consumed.pkceVerifier,\n\t\t\t},\n\t\t});\n\t\tif (!verified.ok) throw new Error(\"provider_rejected\");\n\t\tconst bytes = crypto.getRandomValues(new Uint8Array(32));\n\t\tconst secret = encodeCoordinatorAuthProof32(bytes);\n\t\tconst response = await prepareVerifiedResponse(\n\t\t\tcontext,\n\t\t\tpins,\n\t\t\tsecret,\n\t\t\tmaterial.cookie,\n\t\t\tverified.profile,\n\t\t);\n\t\tconst recorded = await input.operations.recordVerifiedCallback(\n\t\t\t{\n\t\t\t\t...pins,\n\t\t\t\tissuer: verified.account.issuer,\n\t\t\t\tsubject: verified.account.subject,\n\t\t\t\tprofile: verified.profile,\n\t\t\t\tcompletionSecretHash: await hashCoordinatorAuthProofBytes32(bytes),\n\t\t\t},\n\t\t\tconfig,\n\t\t);\n\t\tif (!recorded) throw new Error(\"account_rejected\");\n\t\treturn response;\n\t} catch {\n\t\tawait input.operations.failConsumed(pins, config);\n\t\treturn notice();\n\t}\n}\nasync function confirm(context: Context, request: Request, clientKey: string): Promise<Response> {\n\tconst { input, config, scope, confirmUrl } = context;\n\ttry {\n\t\tconst snapshot = snapshotBrowserRequest(request);\n\t\tif (snapshot.method !== \"POST\") return notice(405);\n\t\tif (snapshot.url !== confirmUrl) return notice(404);\n\t\tconst guard = await guardBrowserForm({\n\t\t\trequest,\n\t\t\tclientKey,\n\t\t\tscope,\n\t\t\tcsrfKey: input.csrfKey,\n\t\t\tlimiter: input.limiter,\n\t\t\taction: \"transaction_attempt\",\n\t\t});\n\t\tif (!guard.ok) return notice(guard.error === \"rate_limited\" ? 429 : 403);\n\t\tif (guard.action !== \"transaction_attempt\") return notice();\n\t\tconst view = await browserView(context, {\n\t\t\tattemptId: guard.attemptId,\n\t\t\tbinderHash: guard.cookieHash,\n\t\t});\n\t\tif (!view || !confirmable(view, guard)) return notice();\n\t\tconst bytes = crypto.getRandomValues(new Uint8Array(32));\n\t\tconst response = await completion(view, encodeCoordinatorAuthProof32(bytes));\n\t\tif (\n\t\t\t!(await input.operations.confirmDisconnect(\n\t\t\t\t{\n\t\t\t\t\tattemptId: view.attemptId,\n\t\t\t\t\tstateHash: view.stateHash,\n\t\t\t\t\tbinderHash: guard.cookieHash,\n\t\t\t\t\tcompletionSecretHash: await hashCoordinatorAuthProofBytes32(bytes),\n\t\t\t\t},\n\t\t\t\tconfig,\n\t\t\t))\n\t\t)\n\t\t\treturn notice();\n\t\treturn response;\n\t} catch {\n\t\treturn notice(503);\n\t}\n}\nfunction confirmable(view: BrowserView, guard: { attemptId: string; cookieHash: string }) {\n\treturn (\n\t\tview.attemptId === guard.attemptId && view.intent === \"disconnect\" && view.state === \"verified\"\n\t);\n}\nexport async function createCoordinatorAccountChangeBrowser(input: AccountChangeBrowserInput) {\n\tconst settings = captureCoordinatorBrowserAuthConfig(input.config);\n\tif (settings.kind !== \"enabled\") return { ok: false as const, error: \"browser_auth_unavailable\" };\n\tif (\n\t\t!isBrowserCsrfKey(input.csrfKey) ||\n\t\t!input.readers ||\n\t\t[\"readStart\", \"readManagementActivity\", \"readBrowserBinding\"].some(\n\t\t\t(name) => typeof Reflect.get(input.readers, name) !== \"function\",\n\t\t)\n\t)\n\t\treturn { ok: false as const, error: \"private_reader_required\" };\n\tconst oidc = await createCoordinatorOidcClient(settings.oidc, input.oidcOptions);\n\tif (!oidc.ok) return oidc;\n\tconst context: Context = {\n\t\tinput,\n\t\tclient: oidc.client,\n\t\tconfig: settings.store,\n\t\tscope: { publicOrigin: settings.publicOrigin, store: settings.store },\n\t\tstartUrl: `${settings.publicOrigin}${ACCOUNT_CHANGE_BROWSER_PATHS.start}`,\n\t\tconfirmUrl: `${settings.publicOrigin}${ACCOUNT_CHANGE_BROWSER_PATHS.confirm}`,\n\t};\n\treturn {\n\t\tok: true as const,\n\t\thandlers: Object.freeze({\n\t\t\tstartPage: (request: Request) => startPage(context, request),\n\t\t\tstart: (request: Request, key: string) => start(context, request, key),\n\t\t\tmatchesCallback: (request: Request) => matchesCallback(context, request),\n\t\t\tcallback: (request: Request, key: string) => callback(context, request, key),\n\t\t\tconfirm: (request: Request, key: string) => confirm(context, request, key),\n\t\t}),\n\t};\n}\n","import type { CoordinatorAuthAccountProfileStore } from \"./coordinator-auth-account-profile-contract.js\";\nimport {\n\tAUTH_BROWSER_FORM_ACTIONS,\n\ttype CoordinatorAuthBrowserPage,\n\trenderAuthBrowserNotice,\n\trenderCurrentAccountPage,\n} from \"./coordinator-auth-browser-view.js\";\nimport { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport type { CoordinatorAuthSessionStore } from \"./coordinator-auth-session-contract.js\";\nimport {\n\ttype CoordinatorBrowserAuthConfigField,\n\ttype CoordinatorBrowserAuthSettings,\n\tcaptureCoordinatorBrowserAuthConfig,\n} from \"./coordinator-browser-auth-config.js\";\nimport { clearBrowserCookie, readBrowserCookie } from \"./coordinator-browser-credential.js\";\nimport {\n\ttype BrowserCsrfKey,\n\ttype BrowserCsrfScope,\n\tissueBrowserCsrfToken,\n} from \"./coordinator-browser-csrf.js\";\nimport { type BrowserFormGuardResult, guardBrowserForm } from \"./coordinator-browser-form-guard.js\";\nimport { snapshotBrowserRequest as snapshotRequest } from \"./coordinator-browser-request.js\";\nimport type { InMemoryRequestRateLimiter } from \"./request-rate-limit.js\";\n\ntype AccountStore = Pick<CoordinatorAuthAccountProfileStore, \"readAuthSessionAccount\"> &\n\tPick<CoordinatorAuthSessionStore, \"readAuthSession\" | \"signOutAuthSession\">;\ntype StoreConfig = Extract<CoordinatorBrowserAuthSettings, { kind: \"enabled\" }>[\"store\"];\nexport interface CoordinatorBrowserAccountInput {\n\tconfig: unknown;\n\tcsrfKey: BrowserCsrfKey;\n\tstore: AccountStore;\n\tlimiter: InMemoryRequestRateLimiter;\n}\nexport type CoordinatorBrowserAccountOutcome =\n\t| \"account_page\"\n\t| \"signed_out\"\n\t| \"already_signed_out\"\n\t| \"method_not_allowed\"\n\t| \"not_found\"\n\t| \"cookie_invalid\"\n\t| \"origin_rejected\"\n\t| \"rate_limited\"\n\t| \"unsupported_media_type\"\n\t| \"body_too_large\"\n\t| \"form_invalid\"\n\t| \"csrf_invalid\"\n\t| \"signout_unconfirmed\"\n\t| \"internal_error\";\nexport type CoordinatorBrowserAccountResponse = Readonly<{\n\tresponse: Response;\n\toutcome: CoordinatorBrowserAccountOutcome;\n}>;\nexport interface CoordinatorBrowserAccountHandlers {\n\taccount(request: Request): Promise<CoordinatorBrowserAccountResponse>;\n\tlogout(request: Request, clientKey: string): Promise<CoordinatorBrowserAccountResponse>;\n}\nexport type CoordinatorBrowserAccountResult =\n\t| Readonly<{ ok: true; handlers: Readonly<CoordinatorBrowserAccountHandlers> }>\n\t| Readonly<{\n\t\t\tok: false;\n\t\t\terror: \"browser_auth_config_invalid\";\n\t\t\tfield: CoordinatorBrowserAuthConfigField;\n\t }>\n\t| Readonly<{ ok: false; error: \"browser_auth_disabled\" | \"invalid_input\" }>;\n\nfunction object(value: unknown): asserts value is object {\n\tif (value === null || typeof value !== \"object\" || Array.isArray(value)) throw new Error();\n}\nfunction plain(value: unknown): void {\n\tobject(value);\n\tconst prototype = Object.getPrototypeOf(value);\n\tif (prototype !== Object.prototype && prototype !== null) throw new Error();\n}\nfunction ownData(value: unknown, name: string): unknown {\n\tobject(value);\n\tconst descriptor = Object.getOwnPropertyDescriptor(value, name);\n\tif (!descriptor || !Object.hasOwn(descriptor, \"value\")) throw new Error();\n\treturn descriptor.value;\n}\nfunction dataMethod(value: unknown, name: string): unknown {\n\tobject(value);\n\tconst seen = new Set<object>();\n\tlet cursor: object | null = value;\n\twhile (cursor !== null) {\n\t\tif (seen.has(cursor)) throw new Error();\n\t\tseen.add(cursor);\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(cursor, name);\n\t\tif (descriptor) {\n\t\t\tif (!Object.hasOwn(descriptor, \"value\") || typeof descriptor.value !== \"function\")\n\t\t\t\tthrow new Error();\n\t\t\treturn descriptor.value;\n\t\t}\n\t\tcursor = Object.getPrototypeOf(cursor);\n\t}\n\tthrow new Error();\n}\ntype Context = Readonly<{\n\tstoreConfig: StoreConfig;\n\tpublicOrigin: string;\n\tscope: BrowserCsrfScope;\n\tsignoutScope: Readonly<{ coordinatorId: string }>;\n\tcsrfKey: BrowserCsrfKey;\n\tstore: AccountStore;\n\tlimiter: InMemoryRequestRateLimiter;\n}>;\nfunction result(\n\tresponse: Response,\n\toutcome: CoordinatorBrowserAccountOutcome,\n): CoordinatorBrowserAccountResponse {\n\treturn Object.freeze({ response, outcome });\n}\nfunction pageResponse(\n\tpage: CoordinatorAuthBrowserPage,\n\tstatus = 200,\n\textra?: Record<string, string>,\n) {\n\tconst headers = new Headers(page.headers);\n\theaders.set(\"Cache-Control\", \"no-store\");\n\tif (extra)\n\t\tnew Headers(extra).forEach((value, name) => {\n\t\t\theaders.set(name, value);\n\t\t});\n\treturn new Response(page.body, { status, headers });\n}\nfunction fallback(): CoordinatorBrowserAccountResponse {\n\treturn result(\n\t\tnew Response(\"Account unavailable. Try again.\", {\n\t\t\tstatus: 503,\n\t\t\theaders: {\n\t\t\t\t\"Content-Type\": \"text/plain;charset=utf-8\",\n\t\t\t\t\"Cache-Control\": \"no-store\",\n\t\t\t\t\"Referrer-Policy\": \"no-referrer\",\n\t\t\t\t\"X-Content-Type-Options\": \"nosniff\",\n\t\t\t},\n\t\t}),\n\t\t\"internal_error\",\n\t);\n}\nasync function notice(\n\tstatus: number,\n\toutcome: CoordinatorBrowserAccountOutcome,\n\textra?: Record<string, string>,\n): Promise<CoordinatorBrowserAccountResponse> {\n\ttry {\n\t\tconst kind = status === 200 ? \"signed_out\" : \"auth_unavailable\";\n\t\treturn result(pageResponse(await renderAuthBrowserNotice(kind), status, extra), outcome);\n\t} catch {\n\t\treturn fallback();\n\t}\n}\nfunction routeError(snapshot: ReturnType<typeof snapshotRequest>, url: string, method: string) {\n\tif (snapshot.method !== method) return notice(405, \"method_not_allowed\", { Allow: method });\n\tif (snapshot.url !== url) return notice(404, \"not_found\");\n\treturn null;\n}\nfunction captureSession(value: unknown, context: Context): string {\n\tplain(value);\n\tconst account = ownData(value, \"account\");\n\tplain(account);\n\tconst issuer = ownData(account, \"issuer\");\n\tconst identityId = ownData(value, \"identityId\");\n\tif (issuer !== context.storeConfig.issuer || !isAuthControllerId(identityId)) throw new Error();\n\treturn identityId;\n}\nasync function account(\n\tcontext: Context,\n\trequest: Request,\n): Promise<CoordinatorBrowserAccountResponse> {\n\ttry {\n\t\tconst snapshot = snapshotRequest(request);\n\t\tconst routing = routeError(snapshot, `${context.publicOrigin}/auth/account`, \"GET\");\n\t\tif (routing) return await routing;\n\t\tconst cookie = await readBrowserCookie(snapshot.cookie, \"session\");\n\t\tif (cookie.kind === \"invalid\") return await notice(200, \"cookie_invalid\");\n\t\tif (cookie.kind === \"absent\") return await notice(200, \"signed_out\");\n\t\tconst current = await context.store.readAuthSessionAccount(\n\t\t\tcookie.cookieHash,\n\t\t\tcontext.storeConfig,\n\t\t);\n\t\tif (current === null) return await notice(200, \"signed_out\");\n\t\tplain(current);\n\t\tconst identityId = captureSession(ownData(current, \"session\"), context);\n\t\tconst profile = ownData(current, \"profile\");\n\t\tconst csrfToken = await issueBrowserCsrfToken(\n\t\t\tcontext.csrfKey,\n\t\t\tcookie.secret,\n\t\t\t\"session\",\n\t\t\tcontext.scope,\n\t\t);\n\t\treturn result(\n\t\t\tpageResponse(\n\t\t\t\tawait renderCurrentAccountPage({\n\t\t\t\t\tprofile,\n\t\t\t\t\tissuer: context.storeConfig.issuer,\n\t\t\t\t\tidentity: { id: identityId },\n\t\t\t\t\tcsrfToken,\n\t\t\t\t}),\n\t\t\t),\n\t\t\t\"account_page\",\n\t\t);\n\t} catch {\n\t\treturn await notice(503, \"internal_error\");\n\t}\n}\nfunction guardFailure(guard: Extract<BrowserFormGuardResult, { ok: false }>) {\n\tswitch (guard.error) {\n\t\tcase \"origin_rejected\":\n\t\t\treturn notice(403, guard.error);\n\t\tcase \"rate_limited\":\n\t\t\treturn notice(429, guard.error, { \"Retry-After\": String(guard.retryAfterS) });\n\t\tcase \"cookie_missing\":\n\t\t\treturn notice(200, \"signed_out\");\n\t\tcase \"unsupported_media_type\":\n\t\t\treturn notice(415, guard.error);\n\t\tcase \"body_too_large\":\n\t\t\treturn notice(413, guard.error);\n\t\tcase \"form_invalid\":\n\t\t\treturn notice(400, guard.error);\n\t\tcase \"cookie_invalid\":\n\t\tcase \"csrf_invalid\":\n\t\t\treturn notice(403, guard.error);\n\t\tdefault:\n\t\t\treturn notice(503, \"internal_error\");\n\t}\n}\nasync function signOut(context: Context, hash: string): Promise<CoordinatorBrowserAccountResponse> {\n\t// Build before touching persistence. Failure must keep the credential available for retry.\n\tconst response = pageResponse(await renderAuthBrowserNotice(\"signed_out\"));\n\tresponse.headers.append(\"Set-Cookie\", clearBrowserCookie(\"session\"));\n\tconst before = await context.store.readAuthSession(hash, context.storeConfig);\n\t// Current-config absence deliberately clears only the browser, without revoking old rows.\n\tif (before === null) return result(response, \"already_signed_out\");\n\tcaptureSession(before, context);\n\tconst written = await context.store.signOutAuthSession(hash, context.signoutScope);\n\tplain(written);\n\tif (ownData(written, \"kind\") !== \"signed_out\") return notice(503, \"internal_error\");\n\tconst after = await context.store.readAuthSession(hash, context.storeConfig);\n\tif (after === null) return result(response, \"signed_out\");\n\tcaptureSession(after, context);\n\treturn notice(503, \"signout_unconfirmed\");\n}\nasync function logout(\n\tcontext: Context,\n\trequest: Request,\n\tclientKey: string,\n): Promise<CoordinatorBrowserAccountResponse> {\n\ttry {\n\t\tconst snapshot = snapshotRequest(request);\n\t\tconst routing = routeError(\n\t\t\tsnapshot,\n\t\t\t`${context.publicOrigin}${AUTH_BROWSER_FORM_ACTIONS.signOut}`,\n\t\t\t\"POST\",\n\t\t);\n\t\tif (routing) return await routing;\n\t\t// No asynchronous boundary between our cookie snapshot and the guard's native snapshot.\n\t\tconst pendingGuard = guardBrowserForm({\n\t\t\trequest,\n\t\t\tscope: context.scope,\n\t\t\tcsrfKey: context.csrfKey,\n\t\t\taction: \"session_logout\",\n\t\t\tlimiter: context.limiter,\n\t\t\tclientKey,\n\t\t});\n\t\tconst guard = await pendingGuard;\n\t\tif (!guard.ok) return await guardFailure(guard);\n\t\tif (guard.action !== \"session_logout\") return await notice(503, \"internal_error\");\n\t\tconst cookie = await readBrowserCookie(snapshot.cookie, \"session\");\n\t\tif (cookie.kind !== \"present\" || cookie.cookieHash !== guard.cookieHash)\n\t\t\treturn await notice(503, \"internal_error\");\n\t\treturn await signOut(context, cookie.cookieHash);\n\t} catch {\n\t\treturn await notice(503, \"internal_error\");\n\t}\n}\nfunction captureStore(receiver: unknown): AccountStore {\n\tconst readAccount = dataMethod(\n\t\treceiver,\n\t\t\"readAuthSessionAccount\",\n\t) as AccountStore[\"readAuthSessionAccount\"];\n\tconst read = dataMethod(receiver, \"readAuthSession\") as AccountStore[\"readAuthSession\"];\n\tconst signout = dataMethod(receiver, \"signOutAuthSession\") as AccountStore[\"signOutAuthSession\"];\n\treturn Object.freeze({\n\t\treadAuthSessionAccount: readAccount.bind(receiver),\n\t\treadAuthSession: read.bind(receiver),\n\t\tsignOutAuthSession: signout.bind(receiver),\n\t});\n}\n/** Unmounted local account/logout only. No provider client, profile writes or route registration. */\nexport async function createCoordinatorBrowserAccount(\n\tinput: CoordinatorBrowserAccountInput,\n): Promise<CoordinatorBrowserAccountResult> {\n\ttry {\n\t\tconst config = ownData(input, \"config\");\n\t\tconst settings = captureCoordinatorBrowserAuthConfig(config);\n\t\tif (settings.kind === \"disabled\")\n\t\t\treturn Object.freeze({ ok: false, error: \"browser_auth_disabled\" });\n\t\tif (settings.kind === \"invalid\")\n\t\t\treturn Object.freeze({\n\t\t\t\tok: false,\n\t\t\t\terror: \"browser_auth_config_invalid\",\n\t\t\t\tfield: settings.field,\n\t\t\t});\n\t\tconst csrfKey = ownData(input, \"csrfKey\") as BrowserCsrfKey;\n\t\tobject(csrfKey);\n\t\tconst store = captureStore(ownData(input, \"store\"));\n\t\tconst limiter = ownData(input, \"limiter\") as InMemoryRequestRateLimiter;\n\t\tdataMethod(limiter, \"check\");\n\t\tconst context: Context = Object.freeze({\n\t\t\tstoreConfig: settings.store,\n\t\t\tpublicOrigin: settings.publicOrigin,\n\t\t\tscope: Object.freeze({ publicOrigin: settings.publicOrigin, store: settings.store }),\n\t\t\tsignoutScope: Object.freeze({ coordinatorId: settings.store.coordinatorId }),\n\t\t\tcsrfKey,\n\t\t\tstore,\n\t\t\tlimiter,\n\t\t});\n\t\treturn Object.freeze({\n\t\t\tok: true,\n\t\t\thandlers: Object.freeze({\n\t\t\t\taccount: (request: Request) => account(context, request),\n\t\t\t\tlogout: (request: Request, clientKey: string) => logout(context, request, clientKey),\n\t\t\t}),\n\t\t});\n\t} catch {\n\t\treturn Object.freeze({ ok: false, error: \"invalid_input\" });\n\t}\n}\n","import type { CoordinatorAuthAccountProfileStore } from \"./coordinator-auth-account-profile-contract.js\";\nimport type {\n\tCoordinatorAuthBrowserTransactionConsumeResult,\n\tCoordinatorAuthBrowserTransactionPurposeStore,\n\tCoordinatorAuthBrowserTransactionStore,\n} from \"./coordinator-auth-browser-transaction-contract.js\";\nimport { renderAuthBrowserNotice } from \"./coordinator-auth-browser-view.js\";\nimport type { CoordinatorAuthSessionStore } from \"./coordinator-auth-session-contract.js\";\nimport {\n\ttype CoordinatorBrowserAuthConfigField,\n\ttype CoordinatorBrowserAuthSettings,\n\tcaptureCoordinatorBrowserAuthConfig,\n} from \"./coordinator-browser-auth-config.js\";\nimport {\n\ttype BrowserCookieReadResult,\n\ttype BrowserCookieSecret,\n\tissueBrowserCookie,\n\treadBrowserCookie,\n} from \"./coordinator-browser-credential.js\";\nimport {\n\ttype CoordinatorOidcClient,\n\ttype CoordinatorOidcOptions,\n\tcreateCoordinatorOidcClient,\n} from \"./coordinator-oidc.js\";\n\ntype CallbackStore = Pick<CoordinatorAuthBrowserTransactionStore, \"consumeAuthBrowserTransaction\"> &\n\tPick<CoordinatorAuthSessionStore, \"readAuthSession\" | \"signInWithConsumedBrowserTransaction\"> &\n\tPick<CoordinatorAuthAccountProfileStore, \"recordAuthAccountProfile\">;\ntype Settings = Extract<CoordinatorBrowserAuthSettings, { kind: \"enabled\" }>;\ntype Consumed = Extract<CoordinatorAuthBrowserTransactionConsumeResult, { kind: \"consumed\" }>;\ntype TransactionCookie = Extract<BrowserCookieReadResult, { kind: \"present\" }>;\ntype Verification = Awaited<ReturnType<CoordinatorOidcClient[\"verifyCallback\"]>>;\nexport type CoordinatorBrowserAuthLinkCompletionInput = Readonly<{\n\tattemptId: string;\n\tbrowserTransactionHash: string;\n\ttransactionCookie: BrowserCookieSecret;\n\ttransactionCookieHash: string;\n\tverification: Readonly<Verification>;\n}>;\nexport interface CoordinatorBrowserAuthCallbackInput {\n\tconfig: unknown;\n\tstore: CallbackStore;\n\tcompleteLink: (input: CoordinatorBrowserAuthLinkCompletionInput) => Promise<Response>;\n\toidcOptions?: CoordinatorOidcOptions;\n\townerCallback?: (request: Request, trustedClientKey: string) => Promise<Response>;\n\tpurposeStore?: CoordinatorAuthBrowserTransactionPurposeStore;\n\taccountChangeCallback?: (\n\t\trequest: Request,\n\t\ttrustedClientKey: string,\n\t\tbinderHash: string,\n\t) => Promise<Response | null>;\n\t/**\n\t * Device rebind (ADR 0005 Section 8). Its transactions reuse the\n\t * `owner_enroll` purpose, so it runs only for that stored purpose and before\n\t * owner dispatch; null means the callback is not a rebind.\n\t */\n\tdeviceRebindCallback?: (request: Request) => Promise<Response | null>;\n}\nexport type CoordinatorBrowserAuthCallbackOutcome =\n\t| \"signed_in\"\n\t| \"signed_in_profile_not_recorded\"\n\t| \"session_live\"\n\t| \"link_dispatched\"\n\t| \"owner_dispatched\"\n\t| \"account_change_dispatched\"\n\t| \"device_rebind_dispatched\"\n\t| \"method_not_allowed\"\n\t| \"not_found\"\n\t| \"callback_invalid\"\n\t| \"state_invalid\"\n\t| \"cookie_invalid\"\n\t| \"cookie_missing\"\n\t| \"transaction_unavailable\"\n\t| \"verification_failed\"\n\t| \"signin_rejected\"\n\t| \"link_continuation_failed\"\n\t| \"internal_error\";\nexport type CoordinatorBrowserAuthCallbackResponse = Readonly<{\n\tresponse: Response;\n\toutcome: CoordinatorBrowserAuthCallbackOutcome;\n}>;\nexport interface CoordinatorBrowserAuthCallbackHandlers {\n\tcallback(\n\t\trequest: Request,\n\t\ttrustedClientKey?: string,\n\t): Promise<CoordinatorBrowserAuthCallbackResponse>;\n}\nexport type CoordinatorBrowserAuthCallbackResult =\n\t| Readonly<{ ok: true; handlers: Readonly<CoordinatorBrowserAuthCallbackHandlers> }>\n\t| Readonly<{\n\t\t\tok: false;\n\t\t\terror: \"browser_auth_config_invalid\";\n\t\t\tfield: CoordinatorBrowserAuthConfigField;\n\t }>\n\t| Readonly<{\n\t\t\tok: false;\n\t\t\terror:\n\t\t\t\t| \"browser_auth_disabled\"\n\t\t\t\t| \"invalid_input\"\n\t\t\t\t| \"oidc_discovery_failed\"\n\t\t\t\t| \"invalid_provider_configuration\";\n\t }>;\n\nfunction ownData(value: unknown, name: string): unknown {\n\tif (value === null || typeof value !== \"object\" || Array.isArray(value)) throw new Error();\n\tconst descriptor = Object.getOwnPropertyDescriptor(value, name);\n\tif (descriptor && !Object.hasOwn(descriptor, \"value\")) throw new Error();\n\treturn descriptor?.value;\n}\nfunction dataMethod(value: unknown, name: string): unknown {\n\tif (value === null || typeof value !== \"object\" || Array.isArray(value)) throw new Error();\n\tconst seen = new Set<object>();\n\tlet cursor: object | null = value;\n\twhile (cursor !== null) {\n\t\tif (seen.has(cursor)) throw new Error();\n\t\tseen.add(cursor);\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(cursor, name);\n\t\tif (descriptor) {\n\t\t\tif (!Object.hasOwn(descriptor, \"value\") || typeof descriptor.value !== \"function\")\n\t\t\t\tthrow new Error();\n\t\t\treturn descriptor.value;\n\t\t}\n\t\tcursor = Object.getPrototypeOf(cursor);\n\t}\n\tthrow new Error();\n}\nfunction captureStore(receiver: unknown): CallbackStore {\n\tconst consume = dataMethod(\n\t\treceiver,\n\t\t\"consumeAuthBrowserTransaction\",\n\t) as CallbackStore[\"consumeAuthBrowserTransaction\"];\n\tconst read = dataMethod(receiver, \"readAuthSession\") as CallbackStore[\"readAuthSession\"];\n\tconst signin = dataMethod(\n\t\treceiver,\n\t\t\"signInWithConsumedBrowserTransaction\",\n\t) as CallbackStore[\"signInWithConsumedBrowserTransaction\"];\n\tconst profile = dataMethod(\n\t\treceiver,\n\t\t\"recordAuthAccountProfile\",\n\t) as CallbackStore[\"recordAuthAccountProfile\"];\n\treturn Object.freeze({\n\t\tconsumeAuthBrowserTransaction: (...args) => Reflect.apply(consume, receiver, args),\n\t\treadAuthSession: (...args) => Reflect.apply(read, receiver, args),\n\t\tsignInWithConsumedBrowserTransaction: (...args) => Reflect.apply(signin, receiver, args),\n\t\trecordAuthAccountProfile: (...args) => Reflect.apply(profile, receiver, args),\n\t});\n}\nfunction captureOidcOptions(input: unknown): CoordinatorOidcOptions | undefined {\n\tconst supplied = ownData(input, \"oidcOptions\");\n\tif (supplied === undefined) return undefined;\n\tconst fetch = ownData(supplied, \"fetch\") as CoordinatorOidcOptions[\"fetch\"];\n\tconst timeoutSeconds = ownData(\n\t\tsupplied,\n\t\t\"timeoutSeconds\",\n\t) as CoordinatorOidcOptions[\"timeoutSeconds\"];\n\treturn Object.freeze({ fetch, timeoutSeconds });\n}\nfunction nativeGetter(prototype: object, name: string): ((this: Request) => unknown) | undefined {\n\tlet cursor: object | null = prototype;\n\twhile (cursor !== null) {\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(cursor, name);\n\t\tif (descriptor) return descriptor.get;\n\t\tcursor = Object.getPrototypeOf(cursor);\n\t}\n\treturn undefined;\n}\nconst requestGetters = Object.freeze({\n\tmethod: nativeGetter(Request.prototype, \"method\"),\n\turl: nativeGetter(Request.prototype, \"url\"),\n\theaders: nativeGetter(Request.prototype, \"headers\"),\n});\nconst headersGet = Headers.prototype.get;\nconst responseStatus = nativeGetter(Response.prototype, \"status\");\nfunction snapshotRequest(request: Request) {\n\tconst method = requestGetters.method?.call(request);\n\tconst url = requestGetters.url?.call(request);\n\tconst headers = requestGetters.headers?.call(request) as Headers;\n\tif (typeof method !== \"string\" || typeof url !== \"string\") throw new Error();\n\treturn Object.freeze({ method, url, cookie: headersGet.call(headers, \"cookie\") });\n}\ntype Snapshot = ReturnType<typeof snapshotRequest>;\ntype Context = Readonly<{\n\tstoreConfig: Settings[\"store\"];\n\tpublicOrigin: string;\n\tcallbackURI: string;\n\tclient: CoordinatorOidcClient;\n\tstore: CallbackStore;\n\tcompleteLink: CoordinatorBrowserAuthCallbackInput[\"completeLink\"];\n\townerCallback?: CoordinatorBrowserAuthCallbackInput[\"ownerCallback\"];\n\taccountChangeCallback?: CoordinatorBrowserAuthCallbackInput[\"accountChangeCallback\"];\n\tdeviceRebindCallback?: CoordinatorBrowserAuthCallbackInput[\"deviceRebindCallback\"];\n\treadPurpose?: CoordinatorAuthBrowserTransactionPurposeStore[\"readAuthBrowserTransactionPurpose\"];\n}>;\n\nfunction result(\n\tresponse: Response,\n\toutcome: CoordinatorBrowserAuthCallbackOutcome,\n): CoordinatorBrowserAuthCallbackResponse {\n\treturn Object.freeze({ response, outcome });\n}\nasync function notice(\n\tstatus: number,\n\toutcome: CoordinatorBrowserAuthCallbackOutcome,\n\toptions: { allow?: string } = {},\n): Promise<CoordinatorBrowserAuthCallbackResponse> {\n\ttry {\n\t\tconst page = await renderAuthBrowserNotice(\"auth_unavailable\");\n\t\tconst headers = new Headers(page.headers);\n\t\tif (options.allow) headers.set(\"Allow\", options.allow);\n\t\treturn result(new Response(page.body, { status, headers }), outcome);\n\t} catch {\n\t\tconst headers = new Headers({\n\t\t\t\"Content-Type\": \"text/plain;charset=utf-8\",\n\t\t\t\"Cache-Control\": \"no-store\",\n\t\t\t\"Referrer-Policy\": \"no-referrer\",\n\t\t\t\"X-Content-Type-Options\": \"nosniff\",\n\t\t});\n\t\tif (options.allow) headers.set(\"Allow\", options.allow);\n\t\treturn result(\n\t\t\tnew Response(\n\t\t\t\t\"Sign-in or linking unavailable. Return to the flow you started and try again.\",\n\t\t\t\t{ status: 503, headers },\n\t\t\t),\n\t\t\t\"internal_error\",\n\t\t);\n\t}\n}\nfunction accountResponse(context: Context, sessionCookie?: string): Response {\n\tconst headers = new Headers({\n\t\tLocation: new URL(\"/auth/account\", context.publicOrigin).href,\n\t\t\"Cache-Control\": \"no-store\",\n\t\t\"Referrer-Policy\": \"no-referrer\",\n\t});\n\tif (sessionCookie) headers.append(\"Set-Cookie\", sessionCookie);\n\treturn new Response(null, { status: 303, headers });\n}\nfunction callbackState(\n\tcontext: Context,\n\tsnapshot: Snapshot,\n): { state: string } | { error: \"callback_invalid\" | \"not_found\" | \"state_invalid\" } {\n\tif (snapshot.url.length > 8192 || snapshot.url.includes(\"#\"))\n\t\treturn { error: \"callback_invalid\" };\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(snapshot.url);\n\t} catch {\n\t\treturn { error: \"callback_invalid\" };\n\t}\n\tconst redirect = new URL(context.callbackURI);\n\tif (url.origin !== redirect.origin || url.pathname !== redirect.pathname)\n\t\treturn { error: \"not_found\" };\n\tconst states = url.searchParams.getAll(\"state\");\n\tconst state = states[0];\n\tif (\n\t\tstates.length !== 1 ||\n\t\ttypeof state !== \"string\" ||\n\t\tstate.length < 43 ||\n\t\tstate.length > 128 ||\n\t\t!/^[A-Za-z0-9._~-]+$/.test(state)\n\t)\n\t\treturn { error: \"state_invalid\" };\n\treturn { state };\n}\nasync function hashState(state: string): Promise<string> {\n\tconst digest = await globalThis.crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(state));\n\treturn Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\nasync function verify(\n\tcontext: Context,\n\tsnapshot: Snapshot,\n\tstate: string,\n\tconsumed: Consumed,\n): Promise<Readonly<Verification>> {\n\ttry {\n\t\tconst verified = await context.client.verifyCallback({\n\t\t\tcallbackUrl: snapshot.url,\n\t\t\tmaterial: { state, nonce: consumed.nonce, pkceVerifier: consumed.pkceVerifier },\n\t\t});\n\t\tif (!verified.ok) return Object.freeze({ ok: false, error: verified.error });\n\t\tif (verified.account.issuer !== context.storeConfig.issuer) throw new Error();\n\t\treturn Object.freeze({\n\t\t\tok: true,\n\t\t\taccount: Object.freeze({ ...verified.account }),\n\t\t\tprofile: Object.freeze({ ...verified.profile }),\n\t\t});\n\t} catch {\n\t\treturn Object.freeze({ ok: false, error: \"oidc_verification_failed\" });\n\t}\n}\nasync function dispatchLink(\n\tcontext: Context,\n\tconsumed: Extract<Consumed, { purpose: \"link\" }>,\n\tcookie: TransactionCookie,\n\tverification: Readonly<Verification>,\n): Promise<CoordinatorBrowserAuthCallbackResponse> {\n\ttry {\n\t\tconst response = await context.completeLink(\n\t\t\tObject.freeze({\n\t\t\t\tattemptId: consumed.attemptId,\n\t\t\t\tbrowserTransactionHash: consumed.browserTransactionHash,\n\t\t\t\ttransactionCookie: cookie.secret,\n\t\t\t\ttransactionCookieHash: cookie.cookieHash,\n\t\t\t\tverification,\n\t\t\t}),\n\t\t);\n\t\t// Use the native brand check, not an overridable status property or instanceof.\n\t\tif (!responseStatus || typeof Reflect.apply(responseStatus, response, []) !== \"number\")\n\t\t\tthrow new Error();\n\t\treturn result(response, \"link_dispatched\");\n\t} catch {\n\t\treturn notice(503, \"link_continuation_failed\");\n\t}\n}\nasync function recordProfile(\n\tcontext: Context,\n\tcredentialHash: string,\n\tverification: Extract<Verification, { ok: true }>,\n\tresponse: Response,\n): Promise<CoordinatorBrowserAuthCallbackResponse> {\n\ttry {\n\t\tconst recorded = await context.store.recordAuthAccountProfile(\n\t\t\t{ credentialHash, profile: verification.profile },\n\t\t\tcontext.storeConfig,\n\t\t);\n\t\tif (recorded.kind === \"recorded\") return result(response, \"signed_in\");\n\t} catch {\n\t\t// Display metadata failure must not discard a durably issued session response.\n\t}\n\treturn result(response, \"signed_in_profile_not_recorded\");\n}\nasync function signIn(\n\tcontext: Context,\n\tsnapshot: Snapshot,\n\tconsumed: Consumed,\n\tverification: Readonly<Verification>,\n): Promise<CoordinatorBrowserAuthCallbackResponse> {\n\tif (!verification.ok) return notice(403, \"verification_failed\");\n\tconst existing = await readBrowserCookie(snapshot.cookie, \"session\");\n\tif (existing.kind === \"invalid\") throw new Error();\n\tif (\n\t\texisting.kind === \"present\" &&\n\t\t(await context.store.readAuthSession(existing.cookieHash, context.storeConfig))\n\t)\n\t\treturn result(accountResponse(context), \"session_live\");\n\tconst issued = await issueBrowserCookie(\"session\");\n\tconst response = accountResponse(context, issued.setCookie);\n\t// Prebuild cookies locally; release the session bearer only after guarded persistence.\n\tconst persisted = await context.store.signInWithConsumedBrowserTransaction(\n\t\t{\n\t\t\tbrowserTransactionHash: consumed.browserTransactionHash,\n\t\t\taccount: verification.account,\n\t\t\tcredentialHash: issued.cookieHash,\n\t\t},\n\t\tcontext.storeConfig,\n\t);\n\tif (persisted.kind !== \"issued\") return notice(403, \"signin_rejected\");\n\treturn recordProfile(context, issued.cookieHash, verification, response);\n}\nasync function dispatchOwnerCallback(\n\tcontext: Context,\n\trequest: Request,\n\ttrustedClientKey: string,\n\tstateHash: string,\n\tbinderHash: string,\n): Promise<CoordinatorBrowserAuthCallbackResponse | null> {\n\tif (!context.readPurpose) return null;\n\tconst purpose = await context.readPurpose({ stateHash, binderHash }, context.storeConfig);\n\tconst rebind = purpose === \"owner_enroll\" ? await context.deviceRebindCallback?.(request) : null;\n\tif (rebind) return result(rebind, \"device_rebind_dispatched\");\n\tif (purpose === \"owner_enroll\" && context.ownerCallback)\n\t\treturn result(await context.ownerCallback(request, trustedClientKey), \"owner_dispatched\");\n\tif (purpose === \"signin\" || purpose === \"link\") return null;\n\treturn notice(403, \"transaction_unavailable\");\n}\n\nasync function callback(\n\tcontext: Context,\n\trequest: Request,\n\ttrustedClientKey: string,\n): Promise<CoordinatorBrowserAuthCallbackResponse> {\n\ttry {\n\t\tconst snapshot = snapshotRequest(request);\n\t\tif (snapshot.method !== \"GET\") return await notice(405, \"method_not_allowed\", { allow: \"GET\" });\n\t\tconst parsed = callbackState(context, snapshot);\n\t\tif (\"error\" in parsed)\n\t\t\treturn await notice(parsed.error === \"not_found\" ? 404 : 400, parsed.error);\n\t\tconst cookie = await readBrowserCookie(snapshot.cookie, \"transaction\");\n\t\tif (cookie.kind === \"invalid\") return await notice(400, \"cookie_invalid\");\n\t\tif (cookie.kind === \"absent\") return await notice(403, \"cookie_missing\");\n\t\tconst stateHash = await hashState(parsed.state);\n\t\tconst change = await context.accountChangeCallback?.(\n\t\t\trequest,\n\t\t\ttrustedClientKey ?? \"\",\n\t\t\tcookie.cookieHash,\n\t\t);\n\t\tif (change) return result(change, \"account_change_dispatched\");\n\t\tconst owner = await dispatchOwnerCallback(\n\t\t\tcontext,\n\t\t\trequest,\n\t\t\ttrustedClientKey,\n\t\t\tstateHash,\n\t\t\tcookie.cookieHash,\n\t\t);\n\t\tif (owner) return owner;\n\t\t// Atomic consumption burns matching material before any provider verification.\n\t\tconst consumed = await context.store.consumeAuthBrowserTransaction(\n\t\t\t{ stateHash, binderHash: cookie.cookieHash },\n\t\t\tcontext.storeConfig,\n\t\t);\n\t\tif (consumed.kind !== \"consumed\") return await notice(403, \"transaction_unavailable\");\n\t\tconst verification = await verify(context, snapshot, parsed.state, consumed);\n\t\tif (consumed.purpose === \"link\")\n\t\t\treturn await dispatchLink(context, consumed, cookie, verification);\n\t\tif (consumed.purpose !== \"signin\") throw new Error();\n\t\treturn await signIn(context, snapshot, consumed, verification);\n\t} catch {\n\t\t// Terminal replies may arrive after a newer start has replaced the shared cookie.\n\t\treturn notice(503, \"internal_error\");\n\t}\n}\n\n/** Unmounted callback only. Linking lifecycle and route registration belong to callers. */\nexport async function createCoordinatorBrowserAuthCallback(\n\tinput: CoordinatorBrowserAuthCallbackInput,\n): Promise<CoordinatorBrowserAuthCallbackResult> {\n\ttry {\n\t\tconst settings = captureCoordinatorBrowserAuthConfig(ownData(input, \"config\"));\n\t\tif (settings.kind === \"disabled\")\n\t\t\treturn Object.freeze({ ok: false, error: \"browser_auth_disabled\" });\n\t\tif (settings.kind === \"invalid\")\n\t\t\treturn Object.freeze({\n\t\t\t\tok: false,\n\t\t\t\terror: \"browser_auth_config_invalid\",\n\t\t\t\tfield: settings.field,\n\t\t\t});\n\t\tconst completeLink = ownData(input, \"completeLink\");\n\t\tif (typeof completeLink !== \"function\") throw new Error();\n\t\tconst store = captureStore(ownData(input, \"store\"));\n\t\tconst ownerCallback = ownData(input, \"ownerCallback\");\n\t\tconst accountChangeCallback = ownData(input, \"accountChangeCallback\");\n\t\tif (accountChangeCallback !== undefined && typeof accountChangeCallback !== \"function\")\n\t\t\tthrow new Error();\n\t\tconst deviceRebindCallback = ownData(input, \"deviceRebindCallback\");\n\t\tif (deviceRebindCallback !== undefined && typeof deviceRebindCallback !== \"function\")\n\t\t\tthrow new Error();\n\t\tlet readPurpose: Context[\"readPurpose\"];\n\t\tif (ownerCallback !== undefined && typeof ownerCallback !== \"function\") throw new Error();\n\t\tif (ownerCallback !== undefined || deviceRebindCallback !== undefined) {\n\t\t\tconst receiver = ownData(input, \"purposeStore\");\n\t\t\tconst method = dataMethod(\n\t\t\t\treceiver,\n\t\t\t\t\"readAuthBrowserTransactionPurpose\",\n\t\t\t) as CoordinatorAuthBrowserTransactionPurposeStore[\"readAuthBrowserTransactionPurpose\"];\n\t\t\treadPurpose = (...args) => Reflect.apply(method, receiver, args);\n\t\t}\n\t\tconst options = captureOidcOptions(input);\n\t\tconst oidc = await createCoordinatorOidcClient(settings.oidc, options);\n\t\tif (!oidc.ok) return Object.freeze({ ok: false, error: oidc.error });\n\t\tconst context: Context = Object.freeze({\n\t\t\tstoreConfig: settings.store,\n\t\t\tpublicOrigin: settings.publicOrigin,\n\t\t\tcallbackURI: settings.store.redirectUri,\n\t\t\tclient: oidc.client,\n\t\t\tstore,\n\t\t\tcompleteLink: completeLink as CoordinatorBrowserAuthCallbackInput[\"completeLink\"],\n\t\t\townerCallback: ownerCallback as CoordinatorBrowserAuthCallbackInput[\"ownerCallback\"],\n\t\t\taccountChangeCallback:\n\t\t\t\taccountChangeCallback as CoordinatorBrowserAuthCallbackInput[\"accountChangeCallback\"],\n\t\t\tdeviceRebindCallback:\n\t\t\t\tdeviceRebindCallback as CoordinatorBrowserAuthCallbackInput[\"deviceRebindCallback\"],\n\t\t\treadPurpose,\n\t\t});\n\t\treturn Object.freeze({\n\t\t\tok: true,\n\t\t\thandlers: Object.freeze({\n\t\t\t\tcallback: (request: Request, trustedClientKey = \"\") =>\n\t\t\t\t\tcallback(context, request, trustedClientKey),\n\t\t\t}),\n\t\t});\n\t} catch {\n\t\treturn Object.freeze({ ok: false, error: \"invalid_input\" });\n\t}\n}\n","import type {\n\tCoordinatorAuthBrowserConfig,\n\tCoordinatorAuthBrowserTransactionStore,\n} from \"./coordinator-auth-browser-transaction-contract.js\";\nimport {\n\tAUTH_BROWSER_FORM_ACTIONS,\n\ttype CoordinatorAuthBrowserPage,\n\trenderAuthBrowserNotice,\n\trenderAuthLinkCompletionHopPage,\n\trenderAuthLinkConfirmPage,\n} from \"./coordinator-auth-browser-view.js\";\nimport type { CoordinatorAuthLinkStore } from \"./coordinator-auth-link-contract.js\";\nimport type { CoordinatorBrowserAuthLinkCompletionInput } from \"./coordinator-browser-auth-callback.js\";\nimport {\n\tBROWSER_COOKIE_NAMES,\n\ttype BrowserCookieSecret,\n\tbrowserCookieValue,\n\treadBrowserCookie,\n} from \"./coordinator-browser-credential.js\";\nimport {\n\ttype BrowserCsrfKey,\n\ttype BrowserCsrfScope,\n\tissueBrowserCsrfToken,\n} from \"./coordinator-browser-csrf.js\";\nimport { type BrowserFormGuardResult, guardBrowserForm } from \"./coordinator-browser-form-guard.js\";\nimport { snapshotBrowserRequest } from \"./coordinator-browser-request.js\";\nimport type { InMemoryRequestRateLimiter } from \"./request-rate-limit.js\";\n\ntype LinkStore = Pick<\n\tCoordinatorAuthBrowserTransactionStore,\n\t\"resolveAuthLinkBrowserTransaction\" | \"retireAuthBrowserTransactions\"\n> &\n\tPick<\n\t\tCoordinatorAuthLinkStore,\n\t\t| \"recordAuthLinkOidcVerified\"\n\t\t| \"readAuthLinkCompletionDestination\"\n\t\t| \"confirmAuthLinkAttempt\"\n\t\t| \"failAuthLinkAttempt\"\n\t>;\nexport interface CoordinatorBrowserLinkInput {\n\tconfig: CoordinatorAuthBrowserConfig;\n\tcsrfKey: BrowserCsrfKey;\n\tstore: LinkStore;\n\tlimiter: InMemoryRequestRateLimiter;\n}\nexport type CoordinatorBrowserLinkCallback = (\n\tinput: CoordinatorBrowserAuthLinkCompletionInput,\n) => Promise<Response>;\nexport type CoordinatorBrowserLinkOutcome =\n\t| \"link_confirmation\"\n\t| \"link_confirmed\"\n\t| \"link_cancelled\"\n\t| \"method_not_allowed\"\n\t| \"not_found\"\n\t| \"link_rejected\"\n\t| \"origin_rejected\"\n\t| \"rate_limited\"\n\t| \"unsupported_media_type\"\n\t| \"body_too_large\"\n\t| \"form_invalid\"\n\t| \"cookie_missing\"\n\t| \"cookie_invalid\"\n\t| \"csrf_invalid\"\n\t| \"internal_error\";\nexport type CoordinatorBrowserLinkResponse = Readonly<{\n\tresponse: Response;\n\toutcome: CoordinatorBrowserLinkOutcome;\n}>;\nexport interface CoordinatorBrowserLinkHandlers {\n\tcompleteLink: CoordinatorBrowserLinkCallback;\n\tconfirm(request: Request, clientKey: string): Promise<CoordinatorBrowserLinkResponse>;\n\tcancel(request: Request, clientKey: string): Promise<CoordinatorBrowserLinkResponse>;\n}\nexport type CoordinatorBrowserLinkResult =\n\t| Readonly<{ ok: false; error: \"browser_auth_disabled\" }>\n\t| Readonly<{ ok: true; handlers: Readonly<CoordinatorBrowserLinkHandlers> }>;\ntype Context = Readonly<CoordinatorBrowserLinkInput & { scope: BrowserCsrfScope }>;\n\nfunction result(\n\tresponse: Response,\n\toutcome: CoordinatorBrowserLinkOutcome,\n): CoordinatorBrowserLinkResponse {\n\treturn Object.freeze({ response, outcome });\n}\nfunction pageResponse(\n\tpage: CoordinatorAuthBrowserPage,\n\tstatus = 200,\n\textra?: Record<string, string>,\n): Response {\n\tconst headers = new Headers(page.headers);\n\theaders.set(\"Cache-Control\", \"no-store\");\n\tif (extra)\n\t\tnew Headers(extra).forEach((value, name) => {\n\t\t\theaders.set(name, value);\n\t\t});\n\treturn new Response(page.body, { status, headers });\n}\nfunction fallback(): CoordinatorBrowserLinkResponse {\n\treturn result(\n\t\tnew Response(\"Account linking unavailable. Try again.\", {\n\t\t\tstatus: 503,\n\t\t\theaders: {\n\t\t\t\t\"Content-Type\": \"text/plain;charset=utf-8\",\n\t\t\t\t\"Cache-Control\": \"no-store\",\n\t\t\t\t\"Referrer-Policy\": \"no-referrer\",\n\t\t\t\t\"X-Content-Type-Options\": \"nosniff\",\n\t\t\t},\n\t\t}),\n\t\t\"internal_error\",\n\t);\n}\nasync function notice(\n\tstatus: number,\n\toutcome: CoordinatorBrowserLinkOutcome,\n\textra?: Record<string, string>,\n): Promise<CoordinatorBrowserLinkResponse> {\n\ttry {\n\t\treturn result(\n\t\t\tpageResponse(await renderAuthBrowserNotice(\"auth_unavailable\"), status, extra),\n\t\t\toutcome,\n\t\t);\n\t} catch {\n\t\treturn fallback();\n\t}\n}\nfunction guardFailure(guard: Extract<BrowserFormGuardResult, { ok: false }>) {\n\tswitch (guard.error) {\n\t\tcase \"rate_limited\":\n\t\t\treturn notice(429, guard.error, { \"Retry-After\": String(guard.retryAfterS) });\n\t\tcase \"unsupported_media_type\":\n\t\t\treturn notice(415, guard.error);\n\t\tcase \"body_too_large\":\n\t\t\treturn notice(413, guard.error);\n\t\tcase \"form_invalid\":\n\t\t\treturn notice(400, guard.error);\n\t\tcase \"origin_rejected\":\n\t\tcase \"cookie_missing\":\n\t\tcase \"cookie_invalid\":\n\t\tcase \"csrf_invalid\":\n\t\t\treturn notice(403, guard.error);\n\t\tdefault:\n\t\t\treturn notice(503, \"internal_error\");\n\t}\n}\nasync function failAttempt(\n\tcontext: Context,\n\tattemptId: string,\n\tbrowserTransactionHash: string,\n\treason: \"cancelled\" | \"provider_failure\",\n): Promise<CoordinatorBrowserLinkResponse> {\n\t// Build the response before persistence; rendering failure leaves a retry possible.\n\tconst page = await renderAuthBrowserNotice(\n\t\treason === \"cancelled\" ? \"link_cancelled\" : \"auth_unavailable\",\n\t);\n\tconst response = pageResponse(page, reason === \"cancelled\" ? 200 : 403);\n\tconst written = await context.store.failAuthLinkAttempt(\n\t\t{\n\t\t\tattemptId,\n\t\t\trequester: { kind: \"browser\", browserTransactionHash },\n\t\t\treason,\n\t\t},\n\t\tcontext.config,\n\t);\n\tif (\n\t\t(written.kind !== \"applied\" && written.kind !== \"existing\") ||\n\t\twritten.status.state !== \"failed\"\n\t)\n\t\treturn notice(403, \"link_rejected\");\n\tconst retired = await context.store.retireAuthBrowserTransactions(context.config, { attemptId });\n\tif (retired.kind !== \"retired\" || retired.more) return notice(503, \"internal_error\");\n\tif (reason === \"cancelled\") return result(response, \"link_cancelled\");\n\treturn result(response, \"link_rejected\");\n}\nasync function completeLink(\n\tcontext: Context,\n\tinput: CoordinatorBrowserAuthLinkCompletionInput,\n): Promise<Response> {\n\ttry {\n\t\tconst value = callbackCookieValue(input);\n\t\tif (value === null) return (await notice(403, \"link_rejected\")).response;\n\t\tconst cookie = await readBrowserCookie(\n\t\t\t`${BROWSER_COOKIE_NAMES.transaction}=${value}`,\n\t\t\t\"transaction\",\n\t\t);\n\t\tif (cookie.kind !== \"present\" || cookie.cookieHash !== input.transactionCookieHash)\n\t\t\treturn (await notice(403, \"link_rejected\")).response;\n\t\tconst transaction = await context.store.resolveAuthLinkBrowserTransaction(\n\t\t\t{\n\t\t\t\tattemptId: input.attemptId,\n\t\t\t\tbinderHash: cookie.cookieHash,\n\t\t\t},\n\t\t\tcontext.config,\n\t\t);\n\t\tif (!transaction || transaction.browserTransactionHash !== input.browserTransactionHash)\n\t\t\treturn (await notice(403, \"link_rejected\")).response;\n\t\tif (!input.verification.ok)\n\t\t\treturn (\n\t\t\t\tawait failAttempt(\n\t\t\t\t\tcontext,\n\t\t\t\t\tinput.attemptId,\n\t\t\t\t\ttransaction.browserTransactionHash,\n\t\t\t\t\t\"provider_failure\",\n\t\t\t\t)\n\t\t\t).response;\n\t\tif (input.verification.account.issuer !== context.config.issuer)\n\t\t\treturn (await notice(403, \"link_rejected\")).response;\n\t\tconst recorded = await context.store.recordAuthLinkOidcVerified(\n\t\t\t{\n\t\t\t\tattemptId: input.attemptId,\n\t\t\t\tbrowserTransactionHash: transaction.browserTransactionHash,\n\t\t\t\taccount: input.verification.account,\n\t\t\t\tprofile: input.verification.profile,\n\t\t\t},\n\t\t\tcontext.config,\n\t\t);\n\t\tif (recorded.kind !== \"applied\") return (await notice(403, \"link_rejected\")).response;\n\t\treturn await confirmationPage(\n\t\t\tcontext,\n\t\t\tinput.attemptId,\n\t\t\tcookie.secret,\n\t\t\tinput.verification.profile,\n\t\t\trecorded.target,\n\t\t);\n\t} catch {\n\t\treturn (await notice(503, \"internal_error\")).response;\n\t}\n}\nasync function confirmationPage(\n\tcontext: Context,\n\tattemptId: string,\n\tcookie: BrowserCookieSecret,\n\tprofile: unknown,\n\ttarget: { identityId: string; deviceId: string; groupId: string },\n): Promise<Response> {\n\tconst csrfToken = await issueBrowserCsrfToken(\n\t\tcontext.csrfKey,\n\t\tcookie,\n\t\t\"transaction\",\n\t\tcontext.scope,\n\t);\n\treturn pageResponse(\n\t\tawait renderAuthLinkConfirmPage({\n\t\t\tprofile,\n\t\t\tissuer: context.config.issuer,\n\t\t\tidentity: { id: target.identityId },\n\t\t\tdevice: { id: target.deviceId },\n\t\t\tgroup: { id: target.groupId },\n\t\t\tattemptId,\n\t\t\tcsrfToken,\n\t\t}),\n\t);\n}\nfunction callbackCookieValue(input: CoordinatorBrowserAuthLinkCompletionInput): string | null {\n\ttry {\n\t\treturn browserCookieValue(input.transactionCookie, \"transaction\");\n\t} catch {\n\t\treturn null;\n\t}\n}\nasync function confirmAttempt(\n\tcontext: Context,\n\tattemptId: string,\n\tbrowserTransactionHash: string,\n): Promise<CoordinatorBrowserLinkResponse> {\n\tconst destination = await context.store.readAuthLinkCompletionDestination(\n\t\t{ attemptId, browserTransactionHash },\n\t\tcontext.config,\n\t);\n\tif (!destination) return notice(403, \"link_rejected\");\n\tconst bytes = globalThis.crypto.getRandomValues(new Uint8Array(32));\n\tconst completionSecret = btoa(String.fromCharCode(...bytes))\n\t\t.replaceAll(\"+\", \"-\")\n\t\t.replaceAll(\"/\", \"_\")\n\t\t.replace(/=+$/, \"\");\n\t// The loopback protocol hashes decoded raw bytes, not the encoded string.\n\tconst digest = await globalThis.crypto.subtle.digest(\"SHA-256\", bytes);\n\tconst completionSecretHash = Array.from(new Uint8Array(digest), (byte) =>\n\t\tbyte.toString(16).padStart(2, \"0\"),\n\t).join(\"\");\n\tconst response = pageResponse(\n\t\tawait renderAuthLinkCompletionHopPage({\n\t\t\tdestination: destination.destination,\n\t\t\tattemptId,\n\t\t\tcompletionSecret,\n\t\t}),\n\t);\n\tconst written = await context.store.confirmAuthLinkAttempt(\n\t\t{ attemptId, browserTransactionHash, completionSecretHash },\n\t\tcontext.config,\n\t);\n\tif (written.kind !== \"applied\") return notice(403, \"link_rejected\");\n\t// Retain the transaction cookie for later original-browser session redemption.\n\treturn result(response, \"link_confirmed\");\n}\nasync function post(\n\tcontext: Context,\n\trequest: Request,\n\tclientKey: string,\n\taction: \"confirmLink\" | \"cancelLink\",\n): Promise<CoordinatorBrowserLinkResponse> {\n\ttry {\n\t\tconst snapshot = snapshotBrowserRequest(request);\n\t\tif (snapshot.method !== \"POST\")\n\t\t\treturn await notice(405, \"method_not_allowed\", { Allow: \"POST\" });\n\t\tif (snapshot.url !== `${context.scope.publicOrigin}${AUTH_BROWSER_FORM_ACTIONS[action]}`)\n\t\t\treturn await notice(404, \"not_found\");\n\t\t// The guard captures native headers in this same tick, before either caller awaits.\n\t\tconst pendingGuard = guardBrowserForm({\n\t\t\trequest,\n\t\t\tclientKey,\n\t\t\tscope: context.scope,\n\t\t\tcsrfKey: context.csrfKey,\n\t\t\tlimiter: context.limiter,\n\t\t\taction: \"transaction_attempt\",\n\t\t});\n\t\tconst guard = await pendingGuard;\n\t\tif (!guard.ok) return await guardFailure(guard);\n\t\tif (guard.action !== \"transaction_attempt\") return await notice(503, \"internal_error\");\n\t\tconst cookie = await readBrowserCookie(snapshot.cookie, \"transaction\");\n\t\tif (cookie.kind !== \"present\" || cookie.cookieHash !== guard.cookieHash)\n\t\t\treturn await notice(403, \"link_rejected\");\n\t\tconst transaction = await context.store.resolveAuthLinkBrowserTransaction(\n\t\t\t{\n\t\t\t\tattemptId: guard.attemptId,\n\t\t\t\tbinderHash: guard.cookieHash,\n\t\t\t},\n\t\t\tcontext.config,\n\t\t);\n\t\tif (!transaction) return await notice(403, \"link_rejected\");\n\t\tif (action === \"cancelLink\")\n\t\t\treturn await failAttempt(\n\t\t\t\tcontext,\n\t\t\t\tguard.attemptId,\n\t\t\t\ttransaction.browserTransactionHash,\n\t\t\t\t\"cancelled\",\n\t\t\t);\n\t\treturn await confirmAttempt(context, guard.attemptId, transaction.browserTransactionHash);\n\t} catch {\n\t\treturn await notice(503, \"internal_error\");\n\t}\n}\n\n/** Requires trusted store config from captureCoordinatorBrowserAuthConfig, never HTTP input.\n * The verified callback stages display claims; no session writes or finalization.\n */\nexport function createCoordinatorBrowserLinkHandlers(\n\tinput: CoordinatorBrowserLinkInput,\n): CoordinatorBrowserLinkResult {\n\tconst config = Object.freeze({\n\t\tcoordinatorId: input.config.coordinatorId,\n\t\tissuer: input.config.issuer,\n\t\trevision: input.config.revision,\n\t\tredirectUri: input.config.redirectUri,\n\t\tenabled: input.config.enabled,\n\t});\n\tif (!config.enabled) return Object.freeze({ ok: false, error: \"browser_auth_disabled\" });\n\tconst receiver = input.store;\n\tconst store: LinkStore = Object.freeze({\n\t\tresolveAuthLinkBrowserTransaction: receiver.resolveAuthLinkBrowserTransaction.bind(receiver),\n\t\tretireAuthBrowserTransactions: receiver.retireAuthBrowserTransactions.bind(receiver),\n\t\trecordAuthLinkOidcVerified: receiver.recordAuthLinkOidcVerified.bind(receiver),\n\t\treadAuthLinkCompletionDestination: receiver.readAuthLinkCompletionDestination.bind(receiver),\n\t\tconfirmAuthLinkAttempt: receiver.confirmAuthLinkAttempt.bind(receiver),\n\t\tfailAuthLinkAttempt: receiver.failAuthLinkAttempt.bind(receiver),\n\t});\n\tconst scope = Object.freeze({ publicOrigin: new URL(config.redirectUri).origin, store: config });\n\tconst context: Context = Object.freeze({\n\t\tconfig,\n\t\tscope,\n\t\tstore,\n\t\tcsrfKey: input.csrfKey,\n\t\tlimiter: input.limiter,\n\t});\n\treturn Object.freeze({\n\t\tok: true,\n\t\thandlers: Object.freeze({\n\t\t\tcompleteLink: (completion: CoordinatorBrowserAuthLinkCompletionInput) =>\n\t\t\t\tcompleteLink(context, completion),\n\t\t\tconfirm: (request: Request, clientKey: string) =>\n\t\t\t\tpost(context, request, clientKey, \"confirmLink\"),\n\t\t\tcancel: (request: Request, clientKey: string) =>\n\t\t\t\tpost(context, request, clientKey, \"cancelLink\"),\n\t\t}),\n\t});\n}\n","import type {\n\tCoordinatorAuthBrowserConfig,\n\tCoordinatorAuthBrowserTransactionStore,\n} from \"./coordinator-auth-browser-transaction-contract.js\";\nimport {\n\tAUTH_BROWSER_FORM_ACTIONS,\n\ttype CoordinatorAuthBrowserPage,\n\trenderAuthBrowserNotice,\n\trenderAuthLinkCompletionPage,\n} from \"./coordinator-auth-browser-view.js\";\nimport { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport type { CoordinatorAuthLinkStore } from \"./coordinator-auth-link-contract.js\";\nimport type { CoordinatorAuthSessionStore } from \"./coordinator-auth-session-contract.js\";\nimport { issueBrowserCookie, readBrowserCookie } from \"./coordinator-browser-credential.js\";\nimport {\n\ttype BrowserCsrfKey,\n\ttype BrowserCsrfScope,\n\tissueBrowserCsrfToken,\n} from \"./coordinator-browser-csrf.js\";\nimport { type BrowserFormGuardResult, guardBrowserForm } from \"./coordinator-browser-form-guard.js\";\nimport { snapshotBrowserRequest } from \"./coordinator-browser-request.js\";\nimport type { InMemoryRequestRateLimiter } from \"./request-rate-limit.js\";\n\ntype CompletionStore = Pick<\n\tCoordinatorAuthBrowserTransactionStore,\n\t\"resolveAuthLinkBrowserTransaction\"\n> &\n\tPick<CoordinatorAuthLinkStore, \"getAuthLinkAttemptStatus\"> &\n\tPick<\n\t\tCoordinatorAuthSessionStore,\n\t\t| \"readAuthSession\"\n\t\t| \"redeemAuthLinkSessionWithBrowserTransaction\"\n\t\t| \"preserveAuthLinkSessionCompletion\"\n\t>;\nexport interface CoordinatorBrowserLinkCompletionInput {\n\tconfig?: CoordinatorAuthBrowserConfig;\n\tcsrfKey: BrowserCsrfKey;\n\tstore: CompletionStore;\n\tlimiter: InMemoryRequestRateLimiter;\n}\nexport type CoordinatorBrowserLinkCompletionOutcome =\n\t| \"waiting\"\n\t| \"ready\"\n\t| \"session_preserved\"\n\t| \"session_issued\"\n\t| \"method_not_allowed\"\n\t| \"not_found\"\n\t| \"query_invalid\"\n\t| \"completion_rejected\"\n\t| \"origin_rejected\"\n\t| \"rate_limited\"\n\t| \"unsupported_media_type\"\n\t| \"body_too_large\"\n\t| \"form_invalid\"\n\t| \"cookie_invalid\"\n\t| \"csrf_invalid\"\n\t| \"internal_error\";\nexport type CoordinatorBrowserLinkCompletionResponse = Readonly<{\n\tresponse: Response;\n\toutcome: CoordinatorBrowserLinkCompletionOutcome;\n}>;\nexport interface CoordinatorBrowserLinkCompletionHandlers {\n\tpage(request: Request): Promise<CoordinatorBrowserLinkCompletionResponse>;\n\tcomplete(request: Request, clientKey: string): Promise<CoordinatorBrowserLinkCompletionResponse>;\n}\nexport type CoordinatorBrowserLinkCompletionResult =\n\t| Readonly<{ ok: false; error: \"browser_auth_disabled\" }>\n\t| Readonly<{ ok: true; handlers: Readonly<CoordinatorBrowserLinkCompletionHandlers> }>;\ntype Context = Readonly<{\n\tconfig: Readonly<CoordinatorAuthBrowserConfig>;\n\tpublicOrigin: string;\n\tscope: BrowserCsrfScope;\n\tcsrfKey: BrowserCsrfKey;\n\tstore: CompletionStore;\n\tlimiter: InMemoryRequestRateLimiter;\n}>;\n\nfunction result(response: Response, outcome: CoordinatorBrowserLinkCompletionOutcome) {\n\treturn Object.freeze({ response, outcome });\n}\nfunction pageResponse(\n\tpage: CoordinatorAuthBrowserPage,\n\tstatus = 200,\n\textra?: Record<string, string>,\n) {\n\tconst headers = new Headers(page.headers);\n\tif (extra)\n\t\tnew Headers(extra).forEach((value, name) => {\n\t\t\theaders.set(name, value);\n\t\t});\n\treturn new Response(page.body, { status, headers });\n}\nasync function notice(\n\tstatus: number,\n\toutcome: CoordinatorBrowserLinkCompletionOutcome,\n\textra?: Record<string, string>,\n): Promise<CoordinatorBrowserLinkCompletionResponse> {\n\ttry {\n\t\treturn result(\n\t\t\tpageResponse(await renderAuthBrowserNotice(\"auth_unavailable\"), status, extra),\n\t\t\toutcome,\n\t\t);\n\t} catch {\n\t\treturn result(\n\t\t\tnew Response(\"Linking unavailable. Try again.\", {\n\t\t\t\tstatus: 503,\n\t\t\t\theaders: {\n\t\t\t\t\t\"Content-Type\": \"text/plain;charset=utf-8\",\n\t\t\t\t\t\"Cache-Control\": \"no-store\",\n\t\t\t\t\t\"Referrer-Policy\": \"no-referrer\",\n\t\t\t\t\t\"X-Content-Type-Options\": \"nosniff\",\n\t\t\t\t},\n\t\t\t}),\n\t\t\t\"internal_error\",\n\t\t);\n\t}\n}\nfunction pageAttempt(url: URL): string | null {\n\tconst entries = [...url.searchParams];\n\tconst entry = entries[0];\n\tif (entries.length !== 1 || !entry || entry[0] !== \"attempt_id\") return null;\n\tconst attemptId = entry[1];\n\tif (!isAuthControllerId(attemptId)) return null;\n\treturn attemptId;\n}\nasync function boundStatus(context: Context, attemptId: string, binderHash: string) {\n\tconst resolved = await context.store.resolveAuthLinkBrowserTransaction(\n\t\t{ attemptId, binderHash },\n\t\tcontext.config,\n\t);\n\tif (resolved === null) return null;\n\tconst browserTransactionHash = resolved.browserTransactionHash;\n\tconst status = await context.store.getAuthLinkAttemptStatus(\n\t\tattemptId,\n\t\t{ kind: \"browser\", browserTransactionHash },\n\t\tcontext.config,\n\t);\n\tif (status === null) return null;\n\treturn { browserTransactionHash, state: status.state };\n}\nasync function page(\n\tcontext: Context,\n\trequest: Request,\n): Promise<CoordinatorBrowserLinkCompletionResponse> {\n\ttry {\n\t\tconst snapshot = snapshotBrowserRequest(request);\n\t\tif (snapshot.method !== \"GET\") return await notice(405, \"method_not_allowed\", { Allow: \"GET\" });\n\t\tif (snapshot.url.length > 8192) return await notice(400, \"query_invalid\");\n\t\tconst url = new URL(snapshot.url);\n\t\tif (\n\t\t\tsnapshot.url.includes(\"#\") ||\n\t\t\t`${url.origin}${url.pathname}` !==\n\t\t\t\t`${context.publicOrigin}${AUTH_BROWSER_FORM_ACTIONS.completeLink}` ||\n\t\t\turl.username ||\n\t\t\turl.password\n\t\t)\n\t\t\treturn await notice(404, \"not_found\");\n\t\tconst attemptId = pageAttempt(url);\n\t\tif (attemptId === null) return await notice(400, \"query_invalid\");\n\t\tconst cookie = await readBrowserCookie(snapshot.cookie, \"transaction\");\n\t\tif (cookie.kind !== \"present\") return await notice(403, \"cookie_invalid\");\n\t\tconst status = await boundStatus(context, attemptId, cookie.cookieHash);\n\t\tif (status?.state === \"confirmed\")\n\t\t\treturn result(\n\t\t\t\tpageResponse(await renderAuthLinkCompletionPage({ attemptId, state: \"waiting\" })),\n\t\t\t\t\"waiting\",\n\t\t\t);\n\t\tif (status?.state !== \"finalized\") return await notice(403, \"completion_rejected\");\n\t\tconst csrfToken = await issueBrowserCsrfToken(\n\t\t\tcontext.csrfKey,\n\t\t\tcookie.secret,\n\t\t\t\"transaction\",\n\t\t\tcontext.scope,\n\t\t);\n\t\treturn result(\n\t\t\tpageResponse(await renderAuthLinkCompletionPage({ attemptId, state: \"ready\", csrfToken })),\n\t\t\t\"ready\",\n\t\t);\n\t} catch {\n\t\treturn await notice(503, \"internal_error\");\n\t}\n}\nfunction guardFailure(guard: Extract<BrowserFormGuardResult, { ok: false }>) {\n\tswitch (guard.error) {\n\t\tcase \"origin_rejected\":\n\t\tcase \"cookie_invalid\":\n\t\tcase \"csrf_invalid\":\n\t\t\treturn notice(403, guard.error);\n\t\tcase \"cookie_missing\":\n\t\t\treturn notice(403, \"cookie_invalid\");\n\t\tcase \"client_unidentified\":\n\t\t\treturn notice(503, \"internal_error\");\n\t\tcase \"rate_limited\":\n\t\t\treturn notice(429, guard.error, { \"Retry-After\": String(guard.retryAfterS) });\n\t\tcase \"unsupported_media_type\":\n\t\t\treturn notice(415, guard.error);\n\t\tcase \"body_too_large\":\n\t\t\treturn notice(413, guard.error);\n\t\tcase \"form_invalid\":\n\t\t\treturn notice(400, guard.error);\n\t\tdefault:\n\t\t\treturn notice(503, \"internal_error\");\n\t}\n}\nfunction accountRedirect(context: Context, setCookie?: string): Response {\n\tconst headers = new Headers({\n\t\tLocation: `${context.publicOrigin}/auth/account`,\n\t\t\"Cache-Control\": \"no-store\",\n\t\t\"Referrer-Policy\": \"no-referrer\",\n\t});\n\tif (setCookie) headers.append(\"Set-Cookie\", setCookie);\n\treturn new Response(null, { status: 303, headers });\n}\nasync function finishSession(\n\tcontext: Context,\n\tcookieHeader: string | null,\n\tattemptId: string,\n\tbinderHash: string,\n\tbrowserTransactionHash: string,\n) {\n\tconst session = await readBrowserCookie(cookieHeader, \"session\");\n\tif (session.kind === \"invalid\") return notice(403, \"cookie_invalid\");\n\tif (session.kind === \"present\") {\n\t\tconst live = await context.store.readAuthSession(session.cookieHash, context.config);\n\t\tif (live !== null) {\n\t\t\tconst response = accountRedirect(context);\n\t\t\tconst preserved = await context.store.preserveAuthLinkSessionCompletion(\n\t\t\t\t{ attemptId, browserTransactionHash, binderHash, credentialHash: session.cookieHash },\n\t\t\t\tcontext.config,\n\t\t\t);\n\t\t\tif (preserved.kind !== \"preserved\") return notice(403, \"completion_rejected\");\n\t\t\treturn result(response, \"session_preserved\");\n\t\t}\n\t}\n\tconst issued = await issueBrowserCookie(\"session\");\n\t// Construct all bearer-bearing output before the atomic write; release only its issued result.\n\tconst response = accountRedirect(context, issued.setCookie);\n\tconst redeemed = await context.store.redeemAuthLinkSessionWithBrowserTransaction(\n\t\t{ attemptId, browserTransactionHash, binderHash, credentialHash: issued.cookieHash },\n\t\tcontext.config,\n\t);\n\tif (redeemed.kind !== \"issued\") return notice(403, \"completion_rejected\");\n\treturn result(response, \"session_issued\");\n}\nasync function complete(\n\tcontext: Context,\n\trequest: Request,\n\tclientKey: string,\n): Promise<CoordinatorBrowserLinkCompletionResponse> {\n\ttry {\n\t\tconst snapshot = snapshotBrowserRequest(request);\n\t\tif (snapshot.method !== \"POST\")\n\t\t\treturn await notice(405, \"method_not_allowed\", { Allow: \"POST\" });\n\t\tif (snapshot.url !== `${context.publicOrigin}${AUTH_BROWSER_FORM_ACTIONS.completeLink}`)\n\t\t\treturn await notice(404, \"not_found\");\n\t\t// Invoke synchronously so the shared guard captures the same native headers before any await.\n\t\tconst pendingGuard = guardBrowserForm({\n\t\t\trequest,\n\t\t\tscope: context.scope,\n\t\t\tcsrfKey: context.csrfKey,\n\t\t\taction: \"transaction_attempt\",\n\t\t\tlimiter: context.limiter,\n\t\t\tclientKey,\n\t\t});\n\t\tconst guard = await pendingGuard;\n\t\tif (!guard.ok) return await guardFailure(guard);\n\t\tif (guard.action !== \"transaction_attempt\") return await notice(503, \"internal_error\");\n\t\tconst cookie = await readBrowserCookie(snapshot.cookie, \"transaction\");\n\t\tif (cookie.kind !== \"present\" || cookie.cookieHash !== guard.cookieHash)\n\t\t\treturn await notice(403, \"cookie_invalid\");\n\t\tconst status = await boundStatus(context, guard.attemptId, guard.cookieHash);\n\t\t// Even preserving an existing session requires independent device-finalized proof.\n\t\tif (status?.state !== \"finalized\") return await notice(403, \"completion_rejected\");\n\t\treturn await finishSession(\n\t\t\tcontext,\n\t\t\tsnapshot.cookie,\n\t\t\tguard.attemptId,\n\t\t\tguard.cookieHash,\n\t\t\tstatus.browserTransactionHash,\n\t\t);\n\t} catch {\n\t\treturn await notice(503, \"internal_error\");\n\t}\n}\n\n/** Trusted captured config/key/store only. Unmounted; wiring faults may throw to the composition root. */\nexport function createCoordinatorBrowserLinkCompletionHandlers(\n\tinput: CoordinatorBrowserLinkCompletionInput,\n): CoordinatorBrowserLinkCompletionResult {\n\tif (!input.config?.enabled) return Object.freeze({ ok: false, error: \"browser_auth_disabled\" });\n\tconst config = Object.freeze({\n\t\tenabled: input.config.enabled,\n\t\tcoordinatorId: input.config.coordinatorId,\n\t\tissuer: input.config.issuer,\n\t\trevision: input.config.revision,\n\t\tredirectUri: input.config.redirectUri,\n\t});\n\tconst receiver = input.store;\n\tconst store: CompletionStore = Object.freeze({\n\t\tresolveAuthLinkBrowserTransaction: receiver.resolveAuthLinkBrowserTransaction.bind(receiver),\n\t\tgetAuthLinkAttemptStatus: receiver.getAuthLinkAttemptStatus.bind(receiver),\n\t\treadAuthSession: receiver.readAuthSession.bind(receiver),\n\t\tpreserveAuthLinkSessionCompletion: receiver.preserveAuthLinkSessionCompletion.bind(receiver),\n\t\tredeemAuthLinkSessionWithBrowserTransaction:\n\t\t\treceiver.redeemAuthLinkSessionWithBrowserTransaction.bind(receiver),\n\t});\n\tconst publicOrigin = new URL(config.redirectUri).origin;\n\tconst context: Context = Object.freeze({\n\t\tconfig,\n\t\tpublicOrigin,\n\t\tscope: Object.freeze({ publicOrigin, store: config }),\n\t\tcsrfKey: input.csrfKey,\n\t\tstore,\n\t\tlimiter: input.limiter,\n\t});\n\treturn Object.freeze({\n\t\tok: true,\n\t\thandlers: Object.freeze({\n\t\t\tpage: (request: Request) => page(context, request),\n\t\t\tcomplete: (request: Request, clientKey: string) => complete(context, request, clientKey),\n\t\t}),\n\t});\n}\n","import type { CoordinatorAuthBrowserTransactionStore } from \"./coordinator-auth-browser-transaction-contract.js\";\nimport {\n\ttype CoordinatorAuthBrowserPage,\n\trenderAuthBrowserNotice,\n\trenderAuthLinkStartPage,\n\trenderAuthSigninContinuePage,\n} from \"./coordinator-auth-browser-view.js\";\nimport { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport {\n\tdecodeCoordinatorAuthProof32,\n\thashCoordinatorAuthProofBytes32,\n} from \"./coordinator-auth-proof.js\";\nimport {\n\ttype CoordinatorBrowserAuthConfigField,\n\ttype CoordinatorBrowserAuthSettings,\n\tcaptureCoordinatorBrowserAuthConfig,\n} from \"./coordinator-browser-auth-config.js\";\nimport {\n\tclearBrowserCookie,\n\tissueBrowserCookie,\n\treadBrowserCookie,\n\treissueStartCookieAsTransaction,\n} from \"./coordinator-browser-credential.js\";\nimport {\n\ttype BrowserCsrfKey,\n\ttype BrowserCsrfScope,\n\tissueBrowserCsrfToken,\n} from \"./coordinator-browser-csrf.js\";\nimport { type BrowserFormGuardResult, guardBrowserForm } from \"./coordinator-browser-form-guard.js\";\nimport { snapshotBrowserRequest, snapshotBrowserRoute } from \"./coordinator-browser-request.js\";\nimport { readBrowserStartTransaction } from \"./coordinator-browser-start-transaction.js\";\nimport {\n\ttype CoordinatorOidcClient,\n\ttype CoordinatorOidcOptions,\n\tcreateCoordinatorOidcClient,\n} from \"./coordinator-oidc.js\";\nimport type { InMemoryRequestRateLimiter } from \"./request-rate-limit.js\";\n\ntype LinkStartStore = Pick<\n\tCoordinatorAuthBrowserTransactionStore,\n\t\"startAuthBrowserTransaction\" | \"readAuthBrowserTransactionActivity\"\n>;\ntype Settings = Extract<CoordinatorBrowserAuthSettings, { kind: \"enabled\" }>;\nexport interface CoordinatorBrowserLinkStartInput {\n\tconfig: unknown;\n\tcsrfKey: BrowserCsrfKey;\n\tstore: LinkStartStore;\n\tlimiter: InMemoryRequestRateLimiter;\n\toidcOptions?: CoordinatorOidcOptions;\n}\nexport type CoordinatorBrowserLinkStartOutcome =\n\t| \"link_start_page\"\n\t| \"link_started\"\n\t| \"link_in_progress\"\n\t| \"method_not_allowed\"\n\t| \"not_found\"\n\t| \"form_invalid\"\n\t| \"cookie_invalid\"\n\t| \"origin_rejected\"\n\t| \"rate_limited\"\n\t| \"unsupported_media_type\"\n\t| \"body_too_large\"\n\t| \"cookie_missing\"\n\t| \"csrf_invalid\"\n\t| \"attempt_unavailable\"\n\t| \"start_conflict\"\n\t| \"start_limited\"\n\t| \"provider_request_failed\"\n\t| \"internal_error\";\nexport type CoordinatorBrowserLinkStartResponse = Readonly<{\n\tresponse: Response;\n\toutcome: CoordinatorBrowserLinkStartOutcome;\n}>;\nexport interface CoordinatorBrowserLinkStartHandlers {\n\tlinkStartPage(request: Request): Promise<CoordinatorBrowserLinkStartResponse>;\n\tlinkStart(request: Request, clientKey: string): Promise<CoordinatorBrowserLinkStartResponse>;\n}\nexport type CoordinatorBrowserLinkStartResult =\n\t| Readonly<{ ok: true; handlers: Readonly<CoordinatorBrowserLinkStartHandlers> }>\n\t| Readonly<{\n\t\t\tok: false;\n\t\t\terror: \"browser_auth_config_invalid\";\n\t\t\tfield: CoordinatorBrowserAuthConfigField;\n\t }>\n\t| Readonly<{\n\t\t\tok: false;\n\t\t\terror:\n\t\t\t\t| \"browser_auth_disabled\"\n\t\t\t\t| \"invalid_input\"\n\t\t\t\t| \"oidc_discovery_failed\"\n\t\t\t\t| \"invalid_provider_configuration\";\n\t }>;\ntype Context = Readonly<{\n\tstoreConfig: Settings[\"store\"];\n\tscope: BrowserCsrfScope;\n\tcsrfKey: BrowserCsrfKey;\n\tstore: LinkStartStore;\n\tlimiter: InMemoryRequestRateLimiter;\n\tclient: CoordinatorOidcClient;\n\tstartUrl: string;\n}>;\ntype Snapshot = ReturnType<typeof snapshotBrowserRequest>;\ntype LinkGuard = Extract<BrowserFormGuardResult, { ok: true; action: \"link_start\" }>;\nconst requestHeaders = Object.getOwnPropertyDescriptor(Request.prototype, \"headers\")?.get;\nconst headersGet = Headers.prototype.get;\nconst MAX_START_URL_LENGTH = 8192;\n\nfunction ownData(value: unknown, name: string): unknown {\n\tif (value === null || typeof value !== \"object\" || Array.isArray(value)) throw new Error();\n\tconst descriptor = Object.getOwnPropertyDescriptor(value, name);\n\tif (descriptor && !Object.hasOwn(descriptor, \"value\")) throw new Error();\n\treturn descriptor?.value;\n}\nfunction dataMethod(value: unknown, name: string): unknown {\n\tif (value === null || typeof value !== \"object\" || Array.isArray(value)) throw new Error();\n\tconst seen = new Set<object>();\n\tlet cursor: object | null = value;\n\twhile (cursor !== null) {\n\t\tif (seen.has(cursor)) throw new Error();\n\t\tseen.add(cursor);\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(cursor, name);\n\t\tif (descriptor) {\n\t\t\tif (!Object.hasOwn(descriptor, \"value\") || typeof descriptor.value !== \"function\")\n\t\t\t\tthrow new Error();\n\t\t\treturn descriptor.value;\n\t\t}\n\t\tcursor = Object.getPrototypeOf(cursor);\n\t}\n\tthrow new Error();\n}\nfunction result(\n\tresponse: Response,\n\toutcome: CoordinatorBrowserLinkStartOutcome,\n): CoordinatorBrowserLinkStartResponse {\n\treturn Object.freeze({ response, outcome });\n}\nfunction pageResponse(\n\tpage: CoordinatorAuthBrowserPage,\n\tstatus = 200,\n\textra?: Record<string, string>,\n): Response {\n\tconst headers = new Headers(page.headers);\n\tif (extra)\n\t\tnew Headers(extra).forEach((value, name) => {\n\t\t\theaders.set(name, value);\n\t\t});\n\treturn new Response(page.body, { status, headers });\n}\nasync function notice(\n\tstatus: number,\n\toutcome: CoordinatorBrowserLinkStartOutcome,\n\textra?: Record<string, string>,\n): Promise<CoordinatorBrowserLinkStartResponse> {\n\ttry {\n\t\treturn result(\n\t\t\tpageResponse(await renderAuthBrowserNotice(\"unavailable\"), status, extra),\n\t\t\toutcome,\n\t\t);\n\t} catch {\n\t\treturn result(\n\t\t\tnew Response(\"Account linking unavailable. Return to your terminal and try again.\", {\n\t\t\t\tstatus: 503,\n\t\t\t\theaders: {\n\t\t\t\t\t\"Content-Type\": \"text/plain;charset=utf-8\",\n\t\t\t\t\t\"Cache-Control\": \"no-store\",\n\t\t\t\t\t\"Referrer-Policy\": \"no-referrer\",\n\t\t\t\t\t\"X-Content-Type-Options\": \"nosniff\",\n\t\t\t\t},\n\t\t\t}),\n\t\t\t\"internal_error\",\n\t\t);\n\t}\n}\nfunction parseStartQuery(context: Context, text: string) {\n\tconst url = new URL(text);\n\tif (\n\t\ttext.includes(\"#\") ||\n\t\turl.href !== text ||\n\t\t`${url.origin}${url.pathname}` !== context.startUrl ||\n\t\turl.username ||\n\t\turl.password\n\t)\n\t\treturn null;\n\tconst entries = [...url.searchParams];\n\tif (\n\t\tentries.length !== 2 ||\n\t\turl.searchParams.getAll(\"attempt_id\").length !== 1 ||\n\t\turl.searchParams.getAll(\"start_code\").length !== 1\n\t)\n\t\treturn null;\n\tconst attemptId = url.searchParams.get(\"attempt_id\");\n\tconst startCode = url.searchParams.get(\"start_code\");\n\tif (\n\t\t!isAuthControllerId(attemptId) ||\n\t\ttypeof startCode !== \"string\" ||\n\t\t!decodeCoordinatorAuthProof32(startCode)\n\t)\n\t\treturn null;\n\treturn Object.freeze({ attemptId, startCode });\n}\nasync function linkStartPage(\n\tcontext: Context,\n\trequest: Request,\n): Promise<CoordinatorBrowserLinkStartResponse> {\n\ttry {\n\t\tconst route = snapshotBrowserRoute(request);\n\t\tif (route.method !== \"GET\") return await notice(405, \"method_not_allowed\", { Allow: \"GET\" });\n\t\tif (route.url.length > MAX_START_URL_LENGTH) return await notice(400, \"form_invalid\");\n\t\tconst url = new URL(route.url);\n\t\tif (`${url.origin}${url.pathname}` !== context.startUrl || url.username || url.password)\n\t\t\treturn await notice(404, \"not_found\");\n\t\tconst query = parseStartQuery(context, route.url);\n\t\tif (!query) return await notice(400, \"form_invalid\");\n\t\tconst snapshot = snapshotBrowserRequest(request);\n\t\tconst transaction = await readBrowserStartTransaction(\n\t\t\tsnapshot.cookie,\n\t\t\tcontext.store,\n\t\t\tcontext.storeConfig,\n\t\t);\n\t\tif (transaction === \"invalid\") return await notice(400, \"cookie_invalid\");\n\t\tif (transaction === \"active\") return await notice(409, \"link_in_progress\");\n\t\tconst existing = await readBrowserCookie(snapshot.cookie, \"start\");\n\t\tif (existing.kind === \"invalid\") return await notice(400, \"cookie_invalid\");\n\t\tconst cookie = existing.kind === \"present\" ? existing : await issueBrowserCookie(\"start\");\n\t\tconst csrfToken = await issueBrowserCsrfToken(\n\t\t\tcontext.csrfKey,\n\t\t\tcookie.secret,\n\t\t\t\"start\",\n\t\t\tcontext.scope,\n\t\t);\n\t\tconst response = pageResponse(await renderAuthLinkStartPage({ ...query, csrfToken }));\n\t\tif (\"setCookie\" in cookie) response.headers.append(\"Set-Cookie\", cookie.setCookie);\n\t\treturn result(response, \"link_start_page\");\n\t} catch {\n\t\treturn await notice(503, \"internal_error\");\n\t}\n}\nfunction guardPriority(guard: BrowserFormGuardResult) {\n\tif (guard.ok) return null;\n\tif (guard.error === \"origin_rejected\") return notice(403, \"origin_rejected\");\n\tif (guard.error === \"rate_limited\")\n\t\treturn notice(429, \"rate_limited\", { \"Retry-After\": String(guard.retryAfterS) });\n\tif (guard.error === \"client_unidentified\" || guard.error === \"invalid_input\")\n\t\treturn notice(503, \"internal_error\");\n\treturn null;\n}\nfunction guardFailure(guard: Extract<BrowserFormGuardResult, { ok: false }>) {\n\tswitch (guard.error) {\n\t\tcase \"unsupported_media_type\":\n\t\t\treturn notice(415, guard.error);\n\t\tcase \"body_too_large\":\n\t\t\treturn notice(413, guard.error);\n\t\tcase \"form_invalid\":\n\t\t\treturn notice(400, guard.error);\n\t\tcase \"cookie_invalid\":\n\t\tcase \"cookie_missing\":\n\t\tcase \"csrf_invalid\":\n\t\t\treturn notice(403, guard.error);\n\t\tdefault:\n\t\t\treturn notice(503, \"internal_error\");\n\t}\n}\nasync function admitStart(\n\tcontext: Context,\n\tsnapshot: Snapshot,\n\tguard: LinkGuard,\n): Promise<CoordinatorBrowserLinkStartResponse> {\n\tconst start = await readBrowserCookie(snapshot.cookie, \"start\");\n\tif (start.kind !== \"present\" || start.cookieHash !== guard.cookieHash)\n\t\treturn notice(503, \"internal_error\");\n\tconst bytes = decodeCoordinatorAuthProof32(guard.startCode);\n\tif (!bytes) return notice(400, \"form_invalid\");\n\tconst browserStartHash = await hashCoordinatorAuthProofBytes32(bytes);\n\tlet authorization: Awaited<ReturnType<CoordinatorOidcClient[\"createAuthorizationRequest\"]>>;\n\ttry {\n\t\tauthorization = await context.client.createAuthorizationRequest();\n\t} catch {\n\t\treturn notice(503, \"provider_request_failed\");\n\t}\n\tconst digest = await globalThis.crypto.subtle.digest(\n\t\t\"SHA-256\",\n\t\tnew TextEncoder().encode(authorization.material.state),\n\t);\n\tconst stateHash = Array.from(new Uint8Array(digest), (byte) =>\n\t\tbyte.toString(16).padStart(2, \"0\"),\n\t).join(\"\");\n\tconst response = pageResponse(\n\t\tawait renderAuthSigninContinuePage({ authorizationUrl: authorization.authorizationUrl }),\n\t);\n\tresponse.headers.append(\"Set-Cookie\", reissueStartCookieAsTransaction(start.secret));\n\tresponse.headers.append(\"Set-Cookie\", clearBrowserCookie(\"start\"));\n\t// Release promotion only after both private-proof and unique-binder SQL guards commit.\n\tconst admitted = await context.store.startAuthBrowserTransaction(\n\t\t{\n\t\t\tpurpose: \"link\",\n\t\t\tattemptId: guard.attemptId,\n\t\t\tbrowserStartHash,\n\t\t\tstateHash,\n\t\t\tbinderHash: guard.cookieHash,\n\t\t\tnonce: authorization.material.nonce,\n\t\t\tpkceVerifier: authorization.material.pkceVerifier,\n\t\t},\n\t\tcontext.storeConfig,\n\t);\n\tif (admitted.kind === \"started\") return result(response, \"link_started\");\n\tif (admitted.kind === \"rejected\") {\n\t\tif (admitted.error === \"attempt_unavailable\" || admitted.error === \"attempt_expired\")\n\t\t\treturn notice(409, \"attempt_unavailable\");\n\t\tif (admitted.error === \"transaction_conflict\") return notice(409, \"start_conflict\");\n\t\tif (admitted.error === \"transaction_limited\" || admitted.error === \"clock_retention_blocked\")\n\t\t\treturn notice(503, \"start_limited\");\n\t}\n\treturn notice(503, \"internal_error\");\n}\nasync function linkStart(\n\tcontext: Context,\n\trequest: Request,\n\tclientKey: string,\n): Promise<CoordinatorBrowserLinkStartResponse> {\n\ttry {\n\t\tconst route = snapshotBrowserRoute(request);\n\t\tif (route.method !== \"POST\") return await notice(405, \"method_not_allowed\", { Allow: \"POST\" });\n\t\tif (route.url.length > MAX_START_URL_LENGTH) return await notice(400, \"form_invalid\");\n\t\tconst headers = requestHeaders?.call(request) as Headers;\n\t\tif (\n\t\t\tnew URL(route.url).origin !== context.scope.publicOrigin ||\n\t\t\theadersGet.call(headers, \"origin\") !== context.scope.publicOrigin\n\t\t)\n\t\t\treturn await notice(403, \"origin_rejected\");\n\t\tif (route.url !== context.startUrl) return await notice(404, \"not_found\");\n\t\tconst snapshot = snapshotBrowserRequest(request);\n\t\t// Capture the guard's native fields in the same synchronous tick.\n\t\tconst pendingGuard = guardBrowserForm({\n\t\t\trequest,\n\t\t\tscope: context.scope,\n\t\t\tcsrfKey: context.csrfKey,\n\t\t\taction: \"link_start\",\n\t\t\tlimiter: context.limiter,\n\t\t\tclientKey,\n\t\t});\n\t\tconst guard = await pendingGuard;\n\t\tconst priority = guardPriority(guard);\n\t\tif (priority) return await priority;\n\t\tconst transaction = await readBrowserStartTransaction(\n\t\t\tsnapshot.cookie,\n\t\t\tcontext.store,\n\t\t\tcontext.storeConfig,\n\t\t);\n\t\tif (transaction === \"invalid\") return await notice(400, \"cookie_invalid\");\n\t\tif (transaction === \"active\") return await notice(409, \"link_in_progress\");\n\t\tif (!guard.ok) return await guardFailure(guard);\n\t\tif (guard.action !== \"link_start\") return await notice(503, \"internal_error\");\n\t\treturn await admitStart(context, snapshot, guard);\n\t} catch {\n\t\treturn await notice(503, \"internal_error\");\n\t}\n}\nfunction captureOidcOptions(input: unknown): CoordinatorOidcOptions | undefined {\n\tconst supplied = ownData(input, \"oidcOptions\");\n\tif (supplied === undefined) return undefined;\n\treturn Object.freeze({\n\t\tfetch: ownData(supplied, \"fetch\") as CoordinatorOidcOptions[\"fetch\"],\n\t\ttimeoutSeconds: ownData(supplied, \"timeoutSeconds\") as CoordinatorOidcOptions[\"timeoutSeconds\"],\n\t});\n}\n/** Unmounted private-code entry only; sessions, completion and cleanup are independent.\n * A future gateway must redact the handoff query, Referer and form body from logs.\n */\nexport async function createCoordinatorBrowserLinkStart(\n\tinput: CoordinatorBrowserLinkStartInput,\n): Promise<CoordinatorBrowserLinkStartResult> {\n\ttry {\n\t\tconst settings = captureCoordinatorBrowserAuthConfig(ownData(input, \"config\"));\n\t\tif (settings.kind === \"disabled\")\n\t\t\treturn Object.freeze({ ok: false, error: \"browser_auth_disabled\" });\n\t\tif (settings.kind === \"invalid\")\n\t\t\treturn Object.freeze({\n\t\t\t\tok: false,\n\t\t\t\terror: \"browser_auth_config_invalid\",\n\t\t\t\tfield: settings.field,\n\t\t\t});\n\t\tconst csrfKey = ownData(input, \"csrfKey\") as BrowserCsrfKey;\n\t\tconst receiver = ownData(input, \"store\");\n\t\tconst start = dataMethod(\n\t\t\treceiver,\n\t\t\t\"startAuthBrowserTransaction\",\n\t\t) as LinkStartStore[\"startAuthBrowserTransaction\"];\n\t\tconst activity = dataMethod(\n\t\t\treceiver,\n\t\t\t\"readAuthBrowserTransactionActivity\",\n\t\t) as LinkStartStore[\"readAuthBrowserTransactionActivity\"];\n\t\tconst store = Object.freeze({\n\t\t\tstartAuthBrowserTransaction: start.bind(receiver),\n\t\t\treadAuthBrowserTransactionActivity: activity.bind(receiver),\n\t\t});\n\t\tconst limiter = ownData(input, \"limiter\") as InMemoryRequestRateLimiter;\n\t\tdataMethod(limiter, \"check\");\n\t\tconst oidcOptions = captureOidcOptions(input);\n\t\tconst scope = Object.freeze({ publicOrigin: settings.publicOrigin, store: settings.store });\n\t\tconst startUrl = new URL(\"/auth/link/start\", settings.publicOrigin).href;\n\t\tconst oidc = await createCoordinatorOidcClient(settings.oidc, oidcOptions);\n\t\tif (!oidc.ok) return Object.freeze({ ok: false, error: oidc.error });\n\t\tconst context: Context = Object.freeze({\n\t\t\tstoreConfig: settings.store,\n\t\t\tscope,\n\t\t\tcsrfKey,\n\t\t\tstore,\n\t\t\tlimiter,\n\t\t\tclient: oidc.client,\n\t\t\tstartUrl,\n\t\t});\n\t\treturn Object.freeze({\n\t\t\tok: true,\n\t\t\thandlers: Object.freeze({\n\t\t\t\tlinkStartPage: (request: Request) => linkStartPage(context, request),\n\t\t\t\tlinkStart: (request: Request, clientKey: string) => linkStart(context, request, clientKey),\n\t\t\t}),\n\t\t});\n\t} catch {\n\t\treturn Object.freeze({ ok: false, error: \"invalid_input\" });\n\t}\n}\n","import type { CoordinatorAuthBrowserTransactionStore } from \"./coordinator-auth-browser-transaction-contract.js\";\nimport {\n\ttype CoordinatorAuthBrowserPage,\n\trenderAuthBrowserNotice,\n\trenderAuthSigninContinuePage,\n\trenderAuthSigninPage,\n} from \"./coordinator-auth-browser-view.js\";\nimport type { CoordinatorAuthSessionStore } from \"./coordinator-auth-session-contract.js\";\nimport {\n\ttype CoordinatorBrowserAuthConfigField,\n\ttype CoordinatorBrowserAuthSettings,\n\tcaptureCoordinatorBrowserAuthConfig,\n} from \"./coordinator-browser-auth-config.js\";\nimport {\n\tclearBrowserCookie,\n\tissueBrowserCookie,\n\treadBrowserCookie,\n\treissueStartCookieAsTransaction,\n} from \"./coordinator-browser-credential.js\";\nimport {\n\ttype BrowserCsrfKey,\n\ttype BrowserCsrfScope,\n\tissueBrowserCsrfToken,\n} from \"./coordinator-browser-csrf.js\";\nimport { type BrowserFormGuardResult, guardBrowserForm } from \"./coordinator-browser-form-guard.js\";\nimport { readBrowserStartTransaction } from \"./coordinator-browser-start-transaction.js\";\nimport {\n\ttype CoordinatorOidcClient,\n\ttype CoordinatorOidcOptions,\n\tcreateCoordinatorOidcClient,\n} from \"./coordinator-oidc.js\";\nimport type { InMemoryRequestRateLimiter } from \"./request-rate-limit.js\";\n\ntype SigninStore = Pick<\n\tCoordinatorAuthBrowserTransactionStore,\n\t\"startAuthBrowserTransaction\" | \"readAuthBrowserTransactionActivity\"\n> &\n\tPick<CoordinatorAuthSessionStore, \"readAuthSession\">;\ntype Settings = Extract<CoordinatorBrowserAuthSettings, { kind: \"enabled\" }>;\nexport interface CoordinatorBrowserSigninStartInput {\n\tconfig: unknown;\n\tcsrfKey: BrowserCsrfKey;\n\tstore: SigninStore;\n\tlimiter: InMemoryRequestRateLimiter;\n\toidcOptions?: CoordinatorOidcOptions;\n}\nexport type CoordinatorBrowserSigninStartOutcome =\n\t| \"signin_page\"\n\t| \"signin_started\"\n\t| \"session_live\"\n\t| \"signin_in_progress\"\n\t| \"method_not_allowed\"\n\t| \"not_found\"\n\t| \"cookie_invalid\"\n\t| \"origin_rejected\"\n\t| \"rate_limited\"\n\t| \"unsupported_media_type\"\n\t| \"body_too_large\"\n\t| \"form_invalid\"\n\t| \"cookie_missing\"\n\t| \"csrf_invalid\"\n\t| \"start_conflict\"\n\t| \"start_limited\"\n\t| \"provider_request_failed\"\n\t| \"internal_error\";\nexport type CoordinatorBrowserSigninStartResponse = Readonly<{\n\tresponse: Response;\n\toutcome: CoordinatorBrowserSigninStartOutcome;\n}>;\nexport interface CoordinatorBrowserSigninStartHandlers {\n\tsignInPage(request: Request): Promise<CoordinatorBrowserSigninStartResponse>;\n\tsignInStart(request: Request, clientKey: string): Promise<CoordinatorBrowserSigninStartResponse>;\n}\nexport type CoordinatorBrowserSigninStartResult =\n\t| Readonly<{ ok: true; handlers: Readonly<CoordinatorBrowserSigninStartHandlers> }>\n\t| Readonly<{\n\t\t\tok: false;\n\t\t\terror: \"browser_auth_config_invalid\";\n\t\t\tfield: CoordinatorBrowserAuthConfigField;\n\t }>\n\t| Readonly<{\n\t\t\tok: false;\n\t\t\terror:\n\t\t\t\t| \"browser_auth_disabled\"\n\t\t\t\t| \"invalid_input\"\n\t\t\t\t| \"oidc_discovery_failed\"\n\t\t\t\t| \"invalid_provider_configuration\";\n\t }>;\n\nfunction ownData(value: unknown, name: string): unknown {\n\tif (value === null || typeof value !== \"object\" || Array.isArray(value)) throw new Error();\n\tconst descriptor = Object.getOwnPropertyDescriptor(value, name);\n\tif (descriptor && !Object.hasOwn(descriptor, \"value\")) throw new Error();\n\treturn descriptor?.value;\n}\n\nfunction dataMethod(value: unknown, name: string): unknown {\n\tif (value === null || typeof value !== \"object\" || Array.isArray(value)) throw new Error();\n\tconst seen = new Set<object>();\n\tlet cursor: object | null = value;\n\twhile (cursor !== null) {\n\t\tif (seen.has(cursor)) throw new Error();\n\t\tseen.add(cursor);\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(cursor, name);\n\t\tif (descriptor) {\n\t\t\tif (!Object.hasOwn(descriptor, \"value\") || typeof descriptor.value !== \"function\")\n\t\t\t\tthrow new Error();\n\t\t\treturn descriptor.value;\n\t\t}\n\t\tcursor = Object.getPrototypeOf(cursor);\n\t}\n\tthrow new Error();\n}\n\nfunction nativeRequestGetter(name: string): ((this: Request) => unknown) | undefined {\n\tlet prototype: object | null = Request.prototype;\n\twhile (prototype !== null) {\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(prototype, name);\n\t\tif (descriptor) return descriptor.get;\n\t\tprototype = Object.getPrototypeOf(prototype);\n\t}\n\treturn undefined;\n}\nconst requestGetters = Object.freeze({\n\tmethod: nativeRequestGetter(\"method\"),\n\turl: nativeRequestGetter(\"url\"),\n\theaders: nativeRequestGetter(\"headers\"),\n});\nconst headersGet = Headers.prototype.get;\nfunction snapshotRequest(request: Request) {\n\tconst method = requestGetters.method?.call(request);\n\tconst url = requestGetters.url?.call(request);\n\tconst headers = requestGetters.headers?.call(request) as Headers;\n\tif (typeof method !== \"string\" || typeof url !== \"string\") throw new Error();\n\treturn Object.freeze({ method, url, cookie: headersGet.call(headers, \"cookie\") });\n}\ntype Snapshot = ReturnType<typeof snapshotRequest>;\ntype Context = Readonly<{\n\tstoreConfig: Settings[\"store\"];\n\tscope: BrowserCsrfScope;\n\tcsrfKey: BrowserCsrfKey;\n\tstore: SigninStore;\n\tlimiter: InMemoryRequestRateLimiter;\n\tclient: CoordinatorOidcClient;\n\tsigninUrl: string;\n\taccountUrl: string;\n}>;\n\nfunction result(\n\tresponse: Response,\n\toutcome: CoordinatorBrowserSigninStartOutcome,\n): CoordinatorBrowserSigninStartResponse {\n\treturn Object.freeze({ response, outcome });\n}\nfunction pageResponse(\n\tpage: CoordinatorAuthBrowserPage,\n\tstatus = 200,\n\textra?: Record<string, string>,\n): Response {\n\tconst headers = new Headers(page.headers);\n\theaders.set(\"Cache-Control\", \"no-store\");\n\tif (extra) {\n\t\tnew Headers(extra).forEach((value, name) => {\n\t\t\theaders.set(name, value);\n\t\t});\n\t}\n\treturn new Response(page.body, { status, headers });\n}\nfunction fallback(): CoordinatorBrowserSigninStartResponse {\n\treturn result(\n\t\tnew Response(\"Sign-in unavailable. Try again.\", {\n\t\t\tstatus: 503,\n\t\t\theaders: {\n\t\t\t\t\"Content-Type\": \"text/plain;charset=utf-8\",\n\t\t\t\t\"Cache-Control\": \"no-store\",\n\t\t\t\t\"Referrer-Policy\": \"no-referrer\",\n\t\t\t\t\"X-Content-Type-Options\": \"nosniff\",\n\t\t\t},\n\t\t}),\n\t\t\"internal_error\",\n\t);\n}\nasync function notice(\n\tstatus: number,\n\toutcome: CoordinatorBrowserSigninStartOutcome,\n\textra?: Record<string, string>,\n): Promise<CoordinatorBrowserSigninStartResponse> {\n\ttry {\n\t\tconst inProgress = outcome === \"signin_in_progress\" || outcome === \"start_conflict\";\n\t\tconst kind = inProgress ? \"signin_in_progress\" : \"signin_unavailable\";\n\t\treturn result(pageResponse(await renderAuthBrowserNotice(kind), status, extra), outcome);\n\t} catch {\n\t\treturn fallback();\n\t}\n}\nfunction accountRedirect(context: Context): CoordinatorBrowserSigninStartResponse {\n\treturn result(\n\t\tnew Response(null, {\n\t\t\tstatus: 303,\n\t\t\theaders: {\n\t\t\t\tLocation: context.accountUrl,\n\t\t\t\t\"Cache-Control\": \"no-store\",\n\t\t\t\t\"Referrer-Policy\": \"no-referrer\",\n\t\t\t},\n\t\t}),\n\t\t\"session_live\",\n\t);\n}\nasync function liveSession(context: Context, snapshot: Snapshot): Promise<boolean> {\n\tconst session = await readBrowserCookie(snapshot.cookie, \"session\");\n\tif (session.kind === \"invalid\") throw new Error();\n\tif (session.kind === \"absent\") return false;\n\treturn (await context.store.readAuthSession(session.cookieHash, context.storeConfig)) !== null;\n}\nfunction routeError(context: Context, snapshot: Snapshot, method: \"GET\" | \"POST\") {\n\tif (snapshot.method !== method) return notice(405, \"method_not_allowed\", { Allow: method });\n\tif (snapshot.url !== context.signinUrl) return notice(404, \"not_found\");\n\treturn null;\n}\nasync function signInPage(\n\tcontext: Context,\n\trequest: Request,\n): Promise<CoordinatorBrowserSigninStartResponse> {\n\ttry {\n\t\tconst snapshot = snapshotRequest(request);\n\t\tconst routing = routeError(context, snapshot, \"GET\");\n\t\tif (routing) return await routing;\n\t\tconst transaction = await readBrowserStartTransaction(\n\t\t\tsnapshot.cookie,\n\t\t\tcontext.store,\n\t\t\tcontext.storeConfig,\n\t\t);\n\t\tif (transaction === \"invalid\") return await notice(400, \"cookie_invalid\");\n\t\tif (transaction === \"active\") return await notice(409, \"signin_in_progress\");\n\t\tif (await liveSession(context, snapshot)) return accountRedirect(context);\n\t\tconst existing = await readBrowserCookie(snapshot.cookie, \"start\");\n\t\tif (existing.kind === \"invalid\") return await notice(400, \"cookie_invalid\");\n\t\tconst cookie = existing.kind === \"present\" ? existing : await issueBrowserCookie(\"start\");\n\t\tconst csrfToken = await issueBrowserCsrfToken(\n\t\t\tcontext.csrfKey,\n\t\t\tcookie.secret,\n\t\t\t\"start\",\n\t\t\tcontext.scope,\n\t\t);\n\t\tconst response = pageResponse(await renderAuthSigninPage({ csrfToken }));\n\t\tif (\"setCookie\" in cookie) response.headers.append(\"Set-Cookie\", cookie.setCookie);\n\t\treturn result(response, \"signin_page\");\n\t} catch {\n\t\treturn await notice(503, \"internal_error\");\n\t}\n}\n\nfunction guardPriority(guard: BrowserFormGuardResult) {\n\tif (guard.ok) return null;\n\tif (guard.error === \"origin_rejected\") return notice(403, \"origin_rejected\");\n\tif (guard.error === \"rate_limited\")\n\t\treturn notice(429, \"rate_limited\", { \"Retry-After\": String(guard.retryAfterS) });\n\tif (guard.error === \"client_unidentified\" || guard.error === \"invalid_input\")\n\t\treturn notice(503, \"internal_error\");\n\treturn null;\n}\nfunction guardFailure(guard: Extract<BrowserFormGuardResult, { ok: false }>) {\n\tswitch (guard.error) {\n\t\tcase \"unsupported_media_type\":\n\t\t\treturn notice(415, guard.error);\n\t\tcase \"body_too_large\":\n\t\t\treturn notice(413, guard.error);\n\t\tcase \"form_invalid\":\n\t\t\treturn notice(400, guard.error);\n\t\tcase \"cookie_invalid\":\n\t\tcase \"cookie_missing\":\n\t\tcase \"csrf_invalid\":\n\t\t\treturn notice(403, guard.error);\n\t\tdefault:\n\t\t\treturn notice(503, \"internal_error\");\n\t}\n}\n\nasync function admitStart(\n\tcontext: Context,\n\tsnapshot: Snapshot,\n\tbinderHash: string,\n): Promise<CoordinatorBrowserSigninStartResponse> {\n\tconst start = await readBrowserCookie(snapshot.cookie, \"start\");\n\tif (start.kind !== \"present\" || start.cookieHash !== binderHash)\n\t\treturn notice(503, \"internal_error\");\n\tlet authorization: Awaited<ReturnType<CoordinatorOidcClient[\"createAuthorizationRequest\"]>>;\n\ttry {\n\t\tauthorization = await context.client.createAuthorizationRequest();\n\t} catch {\n\t\treturn notice(503, \"provider_request_failed\");\n\t}\n\tconst digest = await globalThis.crypto.subtle.digest(\n\t\t\"SHA-256\",\n\t\tnew TextEncoder().encode(authorization.material.state),\n\t);\n\tconst stateHash = Array.from(new Uint8Array(digest), (byte) =>\n\t\tbyte.toString(16).padStart(2, \"0\"),\n\t).join(\"\");\n\tconst response = pageResponse(\n\t\tawait renderAuthSigninContinuePage({ authorizationUrl: authorization.authorizationUrl }),\n\t);\n\tresponse.headers.append(\"Set-Cookie\", reissueStartCookieAsTransaction(start.secret));\n\tresponse.headers.append(\"Set-Cookie\", clearBrowserCookie(\"start\"));\n\t// Prebuild locally; cookies leave only after durable unique-binder admission.\n\tconst admitted = await context.store.startAuthBrowserTransaction(\n\t\t{\n\t\t\tpurpose: \"signin\",\n\t\t\tstateHash,\n\t\t\tbinderHash,\n\t\t\tnonce: authorization.material.nonce,\n\t\t\tpkceVerifier: authorization.material.pkceVerifier,\n\t\t},\n\t\tcontext.storeConfig,\n\t);\n\tif (admitted.kind === \"started\") return result(response, \"signin_started\");\n\tif (admitted.kind === \"rejected\") {\n\t\tif (admitted.error === \"transaction_conflict\") return notice(409, \"start_conflict\");\n\t\tif (admitted.error === \"transaction_limited\" || admitted.error === \"clock_retention_blocked\")\n\t\t\treturn notice(503, \"start_limited\");\n\t}\n\treturn notice(503, \"internal_error\");\n}\n\nasync function signInStart(\n\tcontext: Context,\n\trequest: Request,\n\tclientKey: string,\n): Promise<CoordinatorBrowserSigninStartResponse> {\n\ttry {\n\t\tconst snapshot = snapshotRequest(request);\n\t\tconst routing = routeError(context, snapshot, \"POST\");\n\t\tif (routing) return await routing;\n\t\t// Guard snapshots native request fields in this same synchronous tick.\n\t\tconst pendingGuard = guardBrowserForm({\n\t\t\trequest,\n\t\t\tscope: context.scope,\n\t\t\tcsrfKey: context.csrfKey,\n\t\t\taction: \"signin_start\",\n\t\t\tlimiter: context.limiter,\n\t\t\tclientKey,\n\t\t});\n\t\tconst guard = await pendingGuard;\n\t\tconst priority = guardPriority(guard);\n\t\tif (priority) return await priority;\n\t\tconst transaction = await readBrowserStartTransaction(\n\t\t\tsnapshot.cookie,\n\t\t\tcontext.store,\n\t\t\tcontext.storeConfig,\n\t\t);\n\t\tif (transaction === \"invalid\") return await notice(400, \"cookie_invalid\");\n\t\tif (transaction === \"active\") return await notice(409, \"signin_in_progress\");\n\t\tif (!guard.ok) return await guardFailure(guard);\n\t\tif (guard.action !== \"signin_start\") return await notice(503, \"internal_error\");\n\t\tif (await liveSession(context, snapshot)) return accountRedirect(context);\n\t\treturn await admitStart(context, snapshot, guard.cookieHash);\n\t} catch {\n\t\treturn await notice(503, \"internal_error\");\n\t}\n}\n\nfunction captureOidcOptions(input: unknown): CoordinatorOidcOptions | undefined {\n\tconst supplied = ownData(input, \"oidcOptions\");\n\tif (supplied === undefined) return undefined;\n\tconst fetch = ownData(supplied, \"fetch\") as CoordinatorOidcOptions[\"fetch\"];\n\tconst timeoutSeconds = ownData(\n\t\tsupplied,\n\t\t\"timeoutSeconds\",\n\t) as CoordinatorOidcOptions[\"timeoutSeconds\"];\n\treturn Object.freeze({ fetch, timeoutSeconds });\n}\n\n/** Unmounted start handlers only. No callback, cleanup, session rotation or route registration. */\nexport async function createCoordinatorBrowserSigninStart(\n\tinput: CoordinatorBrowserSigninStartInput,\n): Promise<CoordinatorBrowserSigninStartResult> {\n\ttry {\n\t\tconst settings = captureCoordinatorBrowserAuthConfig(ownData(input, \"config\"));\n\t\tif (settings.kind === \"disabled\")\n\t\t\treturn Object.freeze({ ok: false, error: \"browser_auth_disabled\" });\n\t\tif (settings.kind === \"invalid\")\n\t\t\treturn Object.freeze({\n\t\t\t\tok: false,\n\t\t\t\terror: \"browser_auth_config_invalid\",\n\t\t\t\tfield: settings.field,\n\t\t\t});\n\t\tconst csrfKey = ownData(input, \"csrfKey\") as BrowserCsrfKey;\n\t\tconst receiver = ownData(input, \"store\");\n\t\tconst start = dataMethod(\n\t\t\treceiver,\n\t\t\t\"startAuthBrowserTransaction\",\n\t\t) as SigninStore[\"startAuthBrowserTransaction\"];\n\t\tconst read = dataMethod(receiver, \"readAuthSession\") as SigninStore[\"readAuthSession\"];\n\t\tconst activity = dataMethod(\n\t\t\treceiver,\n\t\t\t\"readAuthBrowserTransactionActivity\",\n\t\t) as SigninStore[\"readAuthBrowserTransactionActivity\"];\n\t\tconst store: SigninStore = Object.freeze({\n\t\t\tstartAuthBrowserTransaction: start.bind(receiver),\n\t\t\treadAuthSession: read.bind(receiver),\n\t\t\treadAuthBrowserTransactionActivity: activity.bind(receiver),\n\t\t});\n\t\tconst limiter = ownData(input, \"limiter\") as InMemoryRequestRateLimiter;\n\t\tdataMethod(limiter, \"check\");\n\t\tconst oidcOptions = captureOidcOptions(input);\n\t\tconst scope = Object.freeze({ publicOrigin: settings.publicOrigin, store: settings.store });\n\t\tconst signinUrl = new URL(\"/auth/sign-in\", settings.publicOrigin).href;\n\t\tconst accountUrl = new URL(\"/auth/account\", settings.publicOrigin).href;\n\t\tconst oidc = await createCoordinatorOidcClient(settings.oidc, oidcOptions);\n\t\tif (!oidc.ok) return Object.freeze({ ok: false, error: oidc.error });\n\t\tconst context: Context = Object.freeze({\n\t\t\tstoreConfig: settings.store,\n\t\t\tscope,\n\t\t\tcsrfKey,\n\t\t\tstore,\n\t\t\tlimiter,\n\t\t\tclient: oidc.client,\n\t\t\tsigninUrl,\n\t\t\taccountUrl,\n\t\t});\n\t\treturn Object.freeze({\n\t\t\tok: true,\n\t\t\thandlers: Object.freeze({\n\t\t\t\tsignInPage: (request: Request) => signInPage(context, request),\n\t\t\t\tsignInStart: (request: Request, clientKey: string) =>\n\t\t\t\t\tsignInStart(context, request, clientKey),\n\t\t\t}),\n\t\t});\n\t} catch {\n\t\treturn Object.freeze({ ok: false, error: \"invalid_input\" });\n\t}\n}\n","/** Browser pages for ADR 0005 Section 8 rebinding. Presentation only; the ceremony decides. */\nimport {\n\tbuildPage,\n\ttype CoordinatorAuthBrowserPage,\n\tescapeHtml,\n} from \"./coordinator-auth-browser-view.js\";\nimport { parseCoordinatorAuthLoopback } from \"./coordinator-auth-loopback.js\";\nimport type {\n\tDeviceRebindConfirmation,\n\tDeviceRebindRefusal,\n} from \"./coordinator-device-rebind-ceremony.js\";\n\nexport const DEVICE_REBIND_BROWSER_PATHS = Object.freeze({\n\tstart: \"/auth/rebind/start\",\n\tconfirm: \"/auth/rebind/confirm\",\n});\n\nfunction hidden(fields: Record<string, string>): string {\n\treturn Object.entries(fields)\n\t\t.map(\n\t\t\t([name, value]) =>\n\t\t\t\t`<input type=\"hidden\" name=\"${escapeHtml(name)}\" value=\"${escapeHtml(value)}\">`,\n\t\t)\n\t\t.join(\"\");\n}\n\nfunction form(action: string, fields: Record<string, string>, label: string): string {\n\treturn `<form method=\"post\" action=\"${action}\">${hidden(fields)}<button type=\"submit\">${escapeHtml(label)}</button></form>`;\n}\n\n/** Private start code stays in hidden form data; the page submits itself. */\nexport function renderDeviceRebindStartPage(input: {\n\tattemptId: string;\n\tstartCode: string;\n\tcsrf: string;\n}): Promise<CoordinatorAuthBrowserPage> {\n\tconst fields = { csrf: input.csrf, attempt_id: input.attemptId, start_code: input.startCode };\n\treturn buildPage(\n\t\t\"Sign in on this device\",\n\t\t`<h1>Connecting to Google…</h1><p>You’ll choose an account and confirm before this device changes.</p><p class=\"note\">If nothing happens, continue below. Do not share this page.</p><div class=\"actions\">${form(DEVICE_REBIND_BROWSER_PATHS.start, fields, \"Continue with Google\")}</div>`,\n\t\tundefined,\n\t\t{ referrerPolicy: \"same-origin\", autoSubmit: true },\n\t);\n}\n\nfunction detail(label: string, value: string): string {\n\treturn `<dt>${escapeHtml(label)}</dt><dd><code>${escapeHtml(value)}</code></dd>`;\n}\n\n/** Self-bind: the account already belongs to this device's Identity. */\nfunction renderSelfBindConfirmPage(input: {\n\tconfirmation: DeviceRebindConfirmation;\n\tcsrf: string;\n}): Promise<CoordinatorAuthBrowserPage> {\n\tconst c = input.confirmation;\n\tconst details =\n\t\tdetail(\"Device\", c.deviceId) +\n\t\tdetail(\"Key fingerprint\", c.fingerprint) +\n\t\tdetail(\"Identity\", c.currentIdentityId);\n\tconst fields = {\n\t\tcsrf: input.csrf,\n\t\tattempt_id: c.attemptId,\n\t\tconfirmation_hash: c.confirmationHash,\n\t};\n\treturn buildPage(\n\t\t\"Use this account on this device\",\n\t\t`<h1>Use this account on this device</h1><p>This Google account already belongs to this device’s Identity. Confirming lets this device refresh and unlink it too.</p><section aria-label=\"Device\"><dl>${details}</dl></section><p>A device can do this only once.</p><div class=\"actions\">${form(DEVICE_REBIND_BROWSER_PATHS.confirm, fields, \"Confirm\")}</div>`,\n\t\tundefined,\n\t\t{ referrerPolicy: \"same-origin\" },\n\t);\n}\n\nexport function renderDeviceRebindConfirmPage(input: {\n\tconfirmation: DeviceRebindConfirmation;\n\tcsrf: string;\n}): Promise<CoordinatorAuthBrowserPage> {\n\tconst c = input.confirmation;\n\tif (c.targetIdentityId === c.currentIdentityId) return renderSelfBindConfirmPage(input);\n\tconst teams = c.groupsWithoutAccess.length ? c.groupsWithoutAccess.join(\", \") : \"None\";\n\tconst details =\n\t\tdetail(\"Device\", c.deviceId) +\n\t\tdetail(\"Key fingerprint\", c.fingerprint) +\n\t\tdetail(\"Current Identity\", c.currentIdentityId) +\n\t\tdetail(\"New Identity\", c.targetIdentityId) +\n\t\tdetail(\"Teams without access yet\", teams);\n\tconst fields = {\n\t\tcsrf: input.csrf,\n\t\tattempt_id: c.attemptId,\n\t\tconfirmation_hash: c.confirmationHash,\n\t};\n\treturn buildPage(\n\t\t\"Sign in on this device\",\n\t\t`<h1>Sign in on this device</h1><p>This device will use the Identity of the Google account you chose. Its existing memories keep their author.</p><section aria-label=\"Change\"><dl>${details}</dl></section><p>Teams the new Identity isn’t in won’t sync on this device until a Team admin adds it. A device can switch only once.</p><div class=\"actions\">${form(DEVICE_REBIND_BROWSER_PATHS.confirm, fields, \"Switch this device\")}</div>`,\n\t\tundefined,\n\t\t{ referrerPolicy: \"same-origin\" },\n\t);\n}\n\n/** Caller releases this secret-bearing page only after confirmation commits. */\nexport function renderDeviceRebindHopPage(input: {\n\tloopbackRedirect: string;\n\tattemptId: string;\n\tcompletionSecret: string;\n\tconfirmationHash: string;\n}): Promise<CoordinatorAuthBrowserPage> {\n\tconst parsed = parseCoordinatorAuthLoopback(input.loopbackRedirect);\n\tif (\n\t\t!parsed.ok ||\n\t\t!/^[A-Za-z0-9_-]{43}$/.test(input.completionSecret) ||\n\t\t!/^[a-f0-9]{64}$/.test(input.confirmationHash)\n\t)\n\t\tthrow new Error(\"device_rebind_view_invalid_input\");\n\t// Concatenation preserves the saved literal, including an explicit :80.\n\tconst href = `${parsed.destination}?attempt_id=${encodeURIComponent(input.attemptId)}&completion=${input.completionSecret}&confirmation=${input.confirmationHash}`;\n\treturn buildPage(\n\t\t\"Finishing sign-in\",\n\t\t`<h1>Finishing sign-in…</h1><p>Returning to Codemem on this computer. If nothing happens, continue below.</p><p class=\"note\">Do not share this link.</p><div class=\"actions\"><a class=\"link\" href=\"${escapeHtml(href)}\" referrerpolicy=\"no-referrer\" rel=\"noreferrer\">Continue on this computer</a></div>`,\n\t\tundefined,\n\t\t{ refreshUrl: href },\n\t);\n}\n\n/** Browser-only states on top of the ceremony's refusals. */\nexport type DeviceRebindNotice = DeviceRebindRefusal | \"unknown\" | \"rate_limited\" | \"busy\";\n\nconst REFUSAL_COPY: Record<DeviceRebindNotice, [string, string]> = {\n\trate_limited: [\"Too many tries\", \"Wait a minute, then start again from Codemem on this device.\"],\n\tbusy: [\n\t\t\"Another sign-in is open\",\n\t\t\"Finish or close the other sign-in, then start again from Codemem on this device.\",\n\t],\n\tunavailable: [\"Sign-in can’t continue\", \"Start again from Codemem on this device.\"],\n\tunknown: [\n\t\t\"Sign-in result unknown\",\n\t\t\"Return to Codemem on this device. It will check whether the change finished.\",\n\t],\n\tretry: [\"Something changed\", \"Start again from Codemem on this device.\"],\n\tcurrent_identity_linked: [\n\t\t\"This device already has an account\",\n\t\t\"Its Identity is linked to a Google account. Unlink that account first.\",\n\t],\n\tdevice_already_bound: [\"This device already switched\", \"A device can switch accounts only once.\"],\n\taccount_not_linked: [\n\t\t\"This Google account isn’t set up\",\n\t\t\"Link this Google account from a device that uses the Identity you want, then try again.\",\n\t],\n\talready_this_identity: [\n\t\t\"Already using this account\",\n\t\t\"This device already uses that Google account’s Identity.\",\n\t],\n\tdaily_limit: [\n\t\t\"Too many switches today\",\n\t\t\"This account’s Identity reached today’s limit for switching devices. Try again tomorrow.\",\n\t],\n};\n\n/**\n * A refusal at the Google callback: explain it here and send the browser back\n * to the device, which stops waiting and shows the next step.\n */\nexport function renderDeviceRebindReturnPage(input: {\n\treason: DeviceRebindRefusal;\n\tloopbackRedirect: string;\n\tattemptId: string;\n}): Promise<CoordinatorAuthBrowserPage> {\n\tconst parsed = parseCoordinatorAuthLoopback(input.loopbackRedirect);\n\tif (!parsed.ok) throw new Error(\"device_rebind_view_invalid_input\");\n\tconst [title, body] = REFUSAL_COPY[input.reason];\n\tconst href = `${parsed.destination}?attempt_id=${encodeURIComponent(input.attemptId)}&refused=${input.reason}`;\n\treturn buildPage(\n\t\ttitle,\n\t\t`<h1>${escapeHtml(title)}</h1><p>${escapeHtml(body)}</p><p>Returning to Codemem on this computer.</p><div class=\"actions\"><a class=\"link\" href=\"${escapeHtml(href)}\" referrerpolicy=\"no-referrer\" rel=\"noreferrer\">Return to Codemem</a></div>`,\n\t\tundefined,\n\t\t{ refreshUrl: href },\n\t);\n}\n\nexport function renderDeviceRebindNotice(\n\treason: DeviceRebindNotice,\n): Promise<CoordinatorAuthBrowserPage> {\n\tconst [title, body] = REFUSAL_COPY[reason];\n\treturn buildPage(title, `<h1>${escapeHtml(title)}</h1><p>${escapeHtml(body)}</p>`);\n}\n","/** Browser routes for ADR 0005 Section 8 rebinding; the ceremony re-checks every step. */\nimport { CoordinatorAuthBrowserTransactions } from \"./coordinator-auth-browser-transaction.js\";\nimport {\n\ttype CoordinatorAuthBrowserPage,\n\trenderAuthSigninContinuePage,\n} from \"./coordinator-auth-browser-view.js\";\nimport { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport type { AuthLinkBackend } from \"./coordinator-auth-link.js\";\nimport { decodeCoordinatorAuthProof32 } from \"./coordinator-auth-proof.js\";\nimport { captureCoordinatorBrowserAuthConfig } from \"./coordinator-browser-auth-config.js\";\nimport {\n\tclearBrowserCookie,\n\tissueBrowserCookie,\n\treadBrowserCookie,\n} from \"./coordinator-browser-credential.js\";\nimport { type BrowserCsrfKey, issueBrowserCsrfToken } from \"./coordinator-browser-csrf.js\";\nimport { readBrowserFormBody } from \"./coordinator-browser-form-body.js\";\nimport { checkBrowserAuthRequestRate } from \"./coordinator-browser-form-guard.js\";\nimport { snapshotBrowserRequest } from \"./coordinator-browser-request.js\";\nimport { readBrowserStartTransaction } from \"./coordinator-browser-start-transaction.js\";\nimport {\n\tcreateDeviceRebindCeremony,\n\ttype DeviceRebindResult,\n} from \"./coordinator-device-rebind-ceremony.js\";\nimport {\n\tDEVICE_REBIND_BROWSER_PATHS,\n\trenderDeviceRebindConfirmPage,\n\trenderDeviceRebindHopPage,\n\trenderDeviceRebindNotice,\n\trenderDeviceRebindReturnPage,\n\trenderDeviceRebindStartPage,\n} from \"./coordinator-device-rebind-view.js\";\nimport {\n\ttype CoordinatorOidcClient,\n\ttype CoordinatorOidcOptions,\n\tcreateCoordinatorOidcClient,\n} from \"./coordinator-oidc.js\";\nimport type { InMemoryRequestRateLimiter } from \"./request-rate-limit.js\";\n\nexport interface DeviceRebindBrowserInput {\n\tconfig: unknown;\n\tcsrfKey: BrowserCsrfKey;\n\tlimiter: InMemoryRequestRateLimiter;\n\t/** Must already have the rebind tables; see readDeviceRebindBackend. */\n\tbackend: AuthLinkBackend;\n\toidcOptions?: CoordinatorOidcOptions;\n\tnow?: () => number;\n}\n\ntype Ceremony = ReturnType<typeof createDeviceRebindCeremony>;\ninterface Context {\n\tceremony: Ceremony;\n\tcsrfKey: BrowserCsrfKey;\n\tlimiter: InMemoryRequestRateLimiter;\n\tscope: { publicOrigin: string; store: Parameters<typeof readBrowserStartTransaction>[2] };\n\tstartUrl: string;\n\ttransactions: CoordinatorAuthBrowserTransactions;\n}\n\nfunction pageResponse(page: CoordinatorAuthBrowserPage, status = 200): Response {\n\treturn new Response(page.body, { status, headers: page.headers });\n}\n\nasync function notice(result: DeviceRebindResult | null, status = 403): Promise<Response> {\n\tconst reason = result?.kind === \"refused\" ? result.reason : \"unknown\";\n\treturn pageResponse(await renderDeviceRebindNotice(reason), reason === \"unknown\" ? 503 : status);\n}\n\nasync function browserNotice(kind: \"rate_limited\" | \"busy\", status: 409 | 429): Promise<Response> {\n\treturn pageResponse(await renderDeviceRebindNotice(kind), status);\n}\n\n/** Exactly `attempt_id` and a canonical 32-byte `start_code` at the start URL. */\nfunction startQuery(text: string, startUrl: string) {\n\tif (text.length > 8192 || text.includes(\"#\")) return null;\n\tconst url = new URL(text);\n\tif (`${url.origin}${url.pathname}` !== startUrl || url.username || url.password) return null;\n\tconst attemptId = url.searchParams.get(\"attempt_id\");\n\tconst startCode = url.searchParams.get(\"start_code\");\n\tif (\n\t\t[...url.searchParams].length !== 2 ||\n\t\t!isAuthControllerId(attemptId) ||\n\t\t!startCode ||\n\t\t!decodeCoordinatorAuthProof32(startCode)\n\t)\n\t\treturn null;\n\treturn { attemptId, startCode };\n}\n\nasync function startPage(context: Context, request: Request, clientKey: string) {\n\tconst snapshot = snapshotBrowserRequest(request);\n\tconst rateKey = JSON.stringify([\"device-rebind-start-page\", clientKey]);\n\tif (!checkBrowserAuthRequestRate(request, context.limiter, rateKey, 30).allowed)\n\t\treturn browserNotice(\"rate_limited\", 429);\n\tconst query = startQuery(snapshot.url, context.startUrl);\n\tif (!query) return notice({ kind: \"refused\", reason: \"unavailable\" }, 400);\n\tconst transaction = await readBrowserStartTransaction(\n\t\tsnapshot.cookie,\n\t\tcontext.transactions,\n\t\tcontext.scope.store,\n\t);\n\tconst current = await readBrowserCookie(snapshot.cookie, \"start\");\n\tif (transaction === \"active\") return browserNotice(\"busy\", 409);\n\tif (transaction === \"invalid\" || current.kind === \"invalid\")\n\t\treturn notice({ kind: \"refused\", reason: \"unavailable\" }, 400);\n\tconst issued = current.kind === \"absent\" ? await issueBrowserCookie(\"start\") : null;\n\tconst secret = current.kind === \"present\" ? current.secret : issued?.secret;\n\tif (!secret) return notice(null);\n\tconst csrf = await issueBrowserCsrfToken(context.csrfKey, secret, \"start\", context.scope);\n\tconst response = pageResponse(await renderDeviceRebindStartPage({ ...query, csrf }));\n\tif (issued) response.headers.append(\"Set-Cookie\", issued.setCookie);\n\treturn response;\n}\n\nasync function start(context: Context, request: Request, clientKey: string) {\n\tconst result = await context.ceremony.claimBrowser(request, clientKey);\n\tif (result?.kind !== \"browser_claimed\") return notice(result);\n\tconst response = pageResponse(\n\t\tawait renderAuthSigninContinuePage({ authorizationUrl: result.authorizationUrl }),\n\t);\n\tfor (const cookie of result.setCookies) response.headers.append(\"Set-Cookie\", cookie);\n\treturn response;\n}\n\n/**\n * The form carries the confirmation hash the person saw. It is removed before\n * the shared form guard reads the body, then checked by the ceremony.\n */\nasync function confirmationForm(request: Request, origin: string) {\n\tif (\n\t\trequest.headers.get(\"origin\") !== origin ||\n\t\t!/^application\\/x-www-form-urlencoded(?:\\s*;\\s*charset=utf-8)?$/i.test(\n\t\t\trequest.headers.get(\"content-type\") ?? \"\",\n\t\t)\n\t)\n\t\treturn null;\n\tconst copy = request.clone();\n\tconst read = await readBrowserFormBody({\n\t\tbody: copy.body,\n\t\tcontentLength: copy.headers.get(\"content-length\"),\n\t});\n\tif (!read.ok) return null;\n\tlet text: string;\n\ttry {\n\t\ttext = new TextDecoder(\"utf-8\", { fatal: true }).decode(read.bytes);\n\t} catch {\n\t\treturn null;\n\t}\n\tconst fields = new URLSearchParams(text);\n\tconst hashes = fields.getAll(\"confirmation_hash\");\n\tconst attemptId = fields.get(\"attempt_id\");\n\tif (hashes.length !== 1 || !/^[a-f0-9]{64}$/.test(hashes[0] ?? \"\") || !attemptId) return null;\n\tfields.delete(\"confirmation_hash\");\n\tconst headers = new Headers(request.headers);\n\theaders.delete(\"content-length\");\n\tconst checked = new Request(request.url, { method: \"POST\", headers, body: fields.toString() });\n\treturn { checked, attemptId, confirmationHash: hashes[0] as string };\n}\n\nasync function confirm(context: Context, request: Request, clientKey: string) {\n\tconst form = await confirmationForm(request, context.scope.publicOrigin);\n\tif (!form) return notice({ kind: \"refused\", reason: \"unavailable\" }, 400);\n\tconst result = await context.ceremony.confirm(form.checked, clientKey, form.confirmationHash);\n\tif (result?.kind !== \"confirmed\") return notice(result);\n\tconst response = pageResponse(\n\t\tawait renderDeviceRebindHopPage({\n\t\t\tloopbackRedirect: result.loopbackRedirect,\n\t\t\tattemptId: form.attemptId,\n\t\t\tcompletionSecret: result.completionSecret,\n\t\t\tconfirmationHash: form.confirmationHash,\n\t\t}),\n\t);\n\tresponse.headers.append(\"Set-Cookie\", clearBrowserCookie(\"transaction\"));\n\treturn response;\n}\n\n/** null when the callback belongs to another ceremony. */\nasync function callback(context: Context, request: Request): Promise<Response | null> {\n\tconst result = await context.ceremony.verifyCallback(request);\n\tif (result === null) return null;\n\tif (result.kind === \"refused\" && result.retired) {\n\t\tconst response = result.returnTo\n\t\t\t? pageResponse(\n\t\t\t\t\tawait renderDeviceRebindReturnPage({ reason: result.reason, ...result.returnTo }),\n\t\t\t\t)\n\t\t\t: await notice(result);\n\t\t// Without this, the spent transaction blocks a fresh start until it expires.\n\t\tresponse.headers.append(\"Set-Cookie\", clearBrowserCookie(\"transaction\"));\n\t\treturn response;\n\t}\n\tif (result.kind !== \"verified\") return notice(result);\n\treturn pageResponse(\n\t\tawait renderDeviceRebindConfirmPage({ confirmation: result.confirmation, csrf: result.csrf }),\n\t);\n}\n\n/** Unexpected errors render the unknown-outcome page; the device then reads status. */\nfunction guarded<A extends unknown[]>(\n\tstep: (context: Context, ...args: A) => Promise<Response>,\n\tcontext: Context,\n) {\n\treturn async (...args: A): Promise<Response> => {\n\t\ttry {\n\t\t\treturn await step(context, ...args);\n\t\t} catch {\n\t\t\treturn notice(null);\n\t\t}\n\t};\n}\n\nexport async function createDeviceRebindBrowser(input: DeviceRebindBrowserInput) {\n\tconst settings = captureCoordinatorBrowserAuthConfig(input.config);\n\tif (settings.kind !== \"enabled\") return { ok: false as const };\n\tconst now = input.now ?? (() => Date.now());\n\t// Discovery waits for the first rebind. Only a finished client is kept, so\n\t// concurrent requests never share another request's discovery.\n\tlet finished: CoordinatorOidcClient | undefined;\n\tconst oidc = async () => {\n\t\tif (finished) return finished;\n\t\tconst created = await createCoordinatorOidcClient(settings.oidc, input.oidcOptions);\n\t\tif (!created.ok) throw new Error(\"device_rebind_oidc_unavailable\");\n\t\tfinished ??= created.client;\n\t\treturn finished;\n\t};\n\tconst client: Pick<CoordinatorOidcClient, \"createAuthorizationRequest\" | \"verifyCallback\"> = {\n\t\tcreateAuthorizationRequest: async () => (await oidc()).createAuthorizationRequest(),\n\t\tverifyCallback: async (...args) => (await oidc()).verifyCallback(...args),\n\t};\n\tconst context: Context = {\n\t\tceremony: createDeviceRebindCeremony({\n\t\t\tbackend: input.backend,\n\t\t\tconfig: settings.store,\n\t\t\tpublicOrigin: settings.publicOrigin,\n\t\t\tcsrfKey: input.csrfKey,\n\t\t\tlimiter: input.limiter,\n\t\t\tclient,\n\t\t\tnow,\n\t\t}),\n\t\tcsrfKey: input.csrfKey,\n\t\tlimiter: input.limiter,\n\t\tscope: { publicOrigin: settings.publicOrigin, store: settings.store },\n\t\tstartUrl: `${settings.publicOrigin}${DEVICE_REBIND_BROWSER_PATHS.start}`,\n\t\ttransactions: new CoordinatorAuthBrowserTransactions(input.backend, now),\n\t};\n\treturn {\n\t\tok: true as const,\n\t\thandlers: Object.freeze({\n\t\t\tstartPage: guarded(startPage, context),\n\t\t\tstart: guarded(start, context),\n\t\t\tconfirm: guarded(confirm, context),\n\t\t\tcallback: async (request: Request): Promise<Response | null> => {\n\t\t\t\ttry {\n\t\t\t\t\treturn await callback(context, request);\n\t\t\t\t} catch {\n\t\t\t\t\treturn notice(null);\n\t\t\t\t}\n\t\t\t},\n\t\t}),\n\t};\n}\n","/** Opt-in owner transport; production admission and server dependencies are explicit. */\nimport { CoordinatorAuthBrowserTransactions } from \"./coordinator-auth-browser-transaction.js\";\nimport { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport type { AuthLinkBackend } from \"./coordinator-auth-link.js\";\nimport { parseCoordinatorAuthLoopback } from \"./coordinator-auth-loopback.js\";\nimport { captureCoordinatorBrowserAuthConfig } from \"./coordinator-browser-auth-config.js\";\nimport {\n\tclearBrowserCookie,\n\tissueBrowserCookie,\n\treadBrowserCookie,\n} from \"./coordinator-browser-credential.js\";\nimport {\n\ttype BrowserCsrfKey,\n\ttype BrowserCsrfScope,\n\timportBrowserCsrfKey,\n\tissueBrowserCsrfToken,\n} from \"./coordinator-browser-csrf.js\";\nimport { parseBrowserFormBody, readBrowserFormBody } from \"./coordinator-browser-form-body.js\";\nimport { checkBrowserAuthRequestRate } from \"./coordinator-browser-form-guard.js\";\nimport { readBrowserStartTransaction } from \"./coordinator-browser-start-transaction.js\";\nimport type { CoordinatorOidcOptions } from \"./coordinator-oidc.js\";\nimport type { OwnerEnrollmentAdmissionKey } from \"./owner-enrollment-admission.js\";\nimport {\n\tcreateCoordinatorOwnerEnrollment,\n\ttype OwnerEnrollmentStart,\n\ttype OwnerEnrollmentStartResult,\n} from \"./owner-enrollment-start.js\";\nimport {\n\tcreateInMemoryRequestRateLimiter,\n\ttype InMemoryRequestRateLimiter,\n} from \"./request-rate-limit.js\";\n\ninterface HttpOptionsBase {\n\tconfig: unknown;\n\tbackend: AuthLinkBackend;\n\toidcOptions: CoordinatorOidcOptions;\n\tclock?: () => number;\n}\nexport type CoordinatorOwnerEnrollmentHttpOptions = HttpOptionsBase &\n\t(\n\t\t| { mode?: \"private\" | \"local_test\"; csrfKey?: never; limiter?: never; admissionKey?: never }\n\t\t| {\n\t\t\t\tmode: \"production\";\n\t\t\t\tcsrfKey: BrowserCsrfKey;\n\t\t\t\tlimiter: InMemoryRequestRateLimiter;\n\t\t\t\tadmissionKey: OwnerEnrollmentAdmissionKey;\n\t\t }\n\t);\nexport interface CoordinatorOwnerEnrollmentHttp {\n\treadonly pin: BrowserCsrfScope[\"store\"] & { origin: string; issuer: string };\n\t/** Trusted browser issuer uses the same production ceremony as the HTTP routes. */\n\treadonly startOwnerBound: Enrollment[\"startOwnerBound\"];\n\t/** Owner-only paths, never the shared OIDC callback. */\n\tmatchesPath(path: string): boolean;\n\thandle(request: Request, trustedClientKey: string): Promise<Response>;\n\t/** Call only after shared dispatch has picked the persisted owner_enroll purpose. */\n\thandleCallback(request: Request, trustedClientKey: string): Promise<Response>;\n}\ntype Enrollment = Extract<\n\tAwaited<ReturnType<typeof createCoordinatorOwnerEnrollment>>,\n\t{ ok: true }\n>[\"enrollment\"];\ntype Verified = Extract<OwnerEnrollmentStartResult, { kind: \"verified\" }>;\nconst START_PATH = \"/auth/owner/start\";\nconst CONFIRM_PATH = \"/auth/owner/confirm\";\nconst ATTEMPTS_PATH = \"/v1/auth/owner-attempts\";\n\nfunction respond(\n\tbody: string | null,\n\tstatus: number,\n\theaders: ConstructorParameters<typeof Headers>[0] = {},\n): Response {\n\tconst safe = new Headers(headers);\n\tsafe.set(\"Cache-Control\", \"no-store\");\n\tsafe.set(\"Referrer-Policy\", \"no-referrer\");\n\tsafe.set(\"X-Content-Type-Options\", \"nosniff\");\n\tsafe.set(\n\t\t\"Content-Security-Policy\",\n\t\t\"default-src 'none'; frame-ancestors 'none'; base-uri 'none'\",\n\t);\n\treturn new Response(body, { status, headers: safe });\n}\nfunction reject(status = 400): Response {\n\treturn respond(\"Owner enrollment unavailable.\", status);\n}\nfunction json(value: unknown): Response {\n\treturn respond(JSON.stringify(value), 200, { \"Content-Type\": \"application/json\" });\n}\nfunction escapeHtml(value: string): string {\n\treturn value.replace(/[&<>\"']/g, (character) => {\n\t\tconst entities: Record<string, string> = {\n\t\t\t\"&\": \"&amp;\",\n\t\t\t\"<\": \"&lt;\",\n\t\t\t\">\": \"&gt;\",\n\t\t\t'\"': \"&quot;\",\n\t\t\t\"'\": \"&#39;\",\n\t\t};\n\t\treturn entities[character] ?? \"\";\n\t});\n}\nfunction hidden(name: string, value: string): string {\n\treturn `<input type=\"hidden\" name=\"${escapeHtml(name)}\" value=\"${escapeHtml(value)}\">`;\n}\nfunction form(action: string, fields: Record<string, string>, button: string): string {\n\treturn `<form method=\"post\" action=\"${action}\">${Object.entries(fields)\n\t\t.map(([name, value]) => hidden(name, value))\n\t\t.join(\"\")}<button type=\"submit\">${button}</button></form>`;\n}\nfunction page(content: string, cookies: string[] = []): Response {\n\tconst headers = new Headers({ \"Content-Type\": \"text/html; charset=utf-8\" });\n\tfor (const cookie of cookies) headers.append(\"Set-Cookie\", cookie);\n\treturn respond(\n\t\t`<!doctype html><html lang=\"en\"><meta charset=\"utf-8\"><title>Enroll owner device</title><body>${content}</body></html>`,\n\t\t200,\n\t\theaders,\n\t);\n}\nfunction redirect(location: string, cookies: string[]): Response {\n\tconst headers = new Headers({ Location: location });\n\tfor (const cookie of cookies) headers.append(\"Set-Cookie\", cookie);\n\treturn respond(null, 303, headers);\n}\nasync function startPage(request: Request, context: HttpContext): Promise<Response> {\n\tconst url = new URL(request.url);\n\tconst attemptId = url.searchParams.get(\"attempt_id\");\n\tconst startCode = url.searchParams.get(\"start_code\");\n\tconst fields = new URLSearchParams({\n\t\tcsrf: \"\",\n\t\tattempt_id: attemptId ?? \"\",\n\t\tstart_code: startCode ?? \"\",\n\t});\n\tif (\n\t\turl.searchParams.size !== 2 ||\n\t\t!parseBrowserFormBody(new TextEncoder().encode(fields.toString()), \"link_start\").ok\n\t)\n\t\treturn reject();\n\treturn renderOwnerEnrollmentStartForm(request, context, {\n\t\tattemptId: attemptId ?? \"\",\n\t\tstartCode: startCode ?? \"\",\n\t});\n}\n/** Only call with a newly started attempt; never use this to redeliver an old start. */\nexport async function renderOwnerEnrollmentStartForm(\n\trequest: Request,\n\tcontext: Pick<HttpContext, \"scope\" | \"key\" | \"transactionActivity\">,\n\tstart: { attemptId: string; startCode: string; deviceId?: string; fingerprint?: string },\n): Promise<Response> {\n\tconst { scope, key } = context;\n\tconst transaction = await context.transactionActivity(request.headers.get(\"cookie\"));\n\tconst current = await readBrowserCookie(request.headers.get(\"cookie\"), \"start\");\n\tif (transaction === \"active\" || transaction === \"invalid\" || current.kind === \"invalid\")\n\t\treturn reject();\n\tconst issued = current.kind === \"absent\" ? await issueBrowserCookie(\"start\") : null;\n\tconst secret = current.kind === \"present\" ? current.secret : issued?.secret;\n\tif (!secret) return reject();\n\tconst csrf = await issueBrowserCsrfToken(key, secret, \"start\", scope);\n\tconst display =\n\t\tstart.deviceId && start.fingerprint\n\t\t\t? `<p>Compare these details with your local device review before choosing an account.</p><dl><dt>Device ID</dt><dd>${escapeHtml(start.deviceId)}</dd><dt>Key fingerprint</dt><dd>${escapeHtml(start.fingerprint)}</dd></dl>`\n\t\t\t: \"\";\n\treturn page(\n\t\t`<h1>Enroll owner device</h1>${display}${form(START_PATH, { csrf, attempt_id: start.attemptId, start_code: start.startCode }, \"Choose account\")}`,\n\t\tissued ? [issued.setCookie] : [],\n\t);\n}\nfunction confirmationPage(result: Verified): Response {\n\tconst c = result.confirmation;\n\tconst details = {\n\t\t\"Verified account subject\": c.subject,\n\t\tIssuer: c.issuer,\n\t\tIdentity: c.identityId,\n\t\t\"Pending device ID\": c.deviceId,\n\t\tFingerprint: c.fingerprint,\n\t\tGroups: c.groups.join(\", \"),\n\t};\n\tconst display = Object.entries(details)\n\t\t.map(([label, value]) => `<dt>${escapeHtml(label)}</dt><dd>${escapeHtml(value)}</dd>`)\n\t\t.join(\"\");\n\treturn page(\n\t\t`<h1>Confirm owner device</h1><dl>${display}</dl>${form(CONFIRM_PATH, { csrf: result.csrf, attempt_id: c.attemptId, confirmation_hash: c.confirmationHash }, \"Enroll this device\")}`,\n\t);\n}\nfunction formHeadersValid(request: Request, origin: string): boolean {\n\treturn (\n\t\trequest.headers.get(\"origin\") === origin &&\n\t\t/^application\\/x-www-form-urlencoded(?:\\s*;\\s*charset=utf-8)?$/i.test(\n\t\t\trequest.headers.get(\"content-type\") ?? \"\",\n\t\t)\n\t);\n}\nasync function confirmBrowser(\n\trequest: Request,\n\tapi: Enrollment,\n\tclientKey: string,\n\torigin: string,\n): Promise<Response> {\n\t// Check original transport/cookie headers before reading a bounded clone. The API\n\t// authenticates the same cookie and CSRF after removing the display commitment.\n\tif (!formHeadersValid(request, origin)) return reject();\n\tconst cookie = await readBrowserCookie(request.headers.get(\"cookie\"), \"transaction\");\n\tif (cookie.kind !== \"present\") return reject();\n\tconst copy = request.clone();\n\tconst read = await readBrowserFormBody({\n\t\tbody: copy.body,\n\t\tcontentLength: copy.headers.get(\"content-length\"),\n\t});\n\tif (!read.ok) return reject();\n\tconst raw = new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: true }).decode(read.bytes);\n\tif (!/^[A-Za-z0-9*._%+=&-]+$/.test(raw)) return reject();\n\tconst fields = new URLSearchParams(raw);\n\tconst hashes = fields.getAll(\"confirmation_hash\");\n\tif (hashes.length !== 1 || !/^[a-f0-9]{64}$/.test(hashes[0] ?? \"\")) return reject();\n\tfields.delete(\"confirmation_hash\");\n\tconst body = fields.toString();\n\tif (!parseBrowserFormBody(new TextEncoder().encode(body), \"transaction_attempt\").ok)\n\t\treturn reject();\n\tconst headers = new Headers(request.headers);\n\theaders.delete(\"content-length\");\n\tconst checked = new Request(request.url, { method: \"POST\", headers, body });\n\tconst result = await api.confirm(checked, clientKey, hashes[0] as string);\n\tif (result.kind !== \"confirmed\") return reject();\n\tconst destination = parseCoordinatorAuthLoopback(result.loopbackRedirect);\n\tif (!destination.ok) return reject();\n\tconst location = new URL(destination.destination);\n\tlocation.searchParams.set(\"attempt_id\", result.confirmation.attemptId);\n\tlocation.searchParams.set(\"completion\", result.completionSecret);\n\tlocation.searchParams.set(\"confirmation\", result.confirmation.confirmationHash);\n\treturn redirect(location.href, [clearBrowserCookie(\"transaction\")]);\n}\nasync function jsonAction(request: Request, api: Enrollment, clientKey: string): Promise<Response> {\n\tif (\n\t\t!/^application\\/json(?:\\s*;\\s*charset=utf-8)?$/i.test(request.headers.get(\"content-type\") ?? \"\")\n\t)\n\t\treturn reject(415);\n\tconst read = await readBrowserFormBody({\n\t\tbody: request.body,\n\t\tcontentLength: request.headers.get(\"content-length\"),\n\t});\n\tif (!read.ok) return reject();\n\tconst body: unknown = JSON.parse(new TextDecoder(\"utf-8\", { fatal: true }).decode(read.bytes));\n\tif (!body || typeof body !== \"object\" || Array.isArray(body)) return reject();\n\tconst finalize = new URL(request.url).pathname.endsWith(\"/finalize\");\n\tconst keys = finalize\n\t\t? [\"attemptId\", \"completionSecret\", \"signature\"]\n\t\t: [\"attemptId\", \"deviceId\", \"publicKey\", \"loopbackRedirect\", \"browserStartCode\", \"signature\"];\n\tif (\n\t\tObject.keys(body).length !== keys.length ||\n\t\tkeys.some((name) => typeof Reflect.get(body, name) !== \"string\")\n\t)\n\t\treturn reject();\n\tconst result = finalize\n\t\t? await api.finalize(body as Parameters<Enrollment[\"finalize\"]>[0])\n\t\t: await api.start(\n\t\t\t\tbody as OwnerEnrollmentStart,\n\t\t\t\tclientKey,\n\t\t\t\t/^Bearer (v1\\.[A-Za-z0-9._-]+)$/.exec(request.headers.get(\"authorization\") ?? \"\")?.[1],\n\t\t\t);\n\tif (result.kind === \"started\" || result.kind === \"finalized\" || result.kind === \"prior_commit\")\n\t\treturn json(result);\n\treturn reject();\n}\nexport function coordinatorOwnerEnrollmentHttpMethods(\n\tpath: string,\n\tcallback: string,\n\tpinPath = \"/v1/auth/owner-pilot\",\n): string | null {\n\tif (path === pinPath || path === callback) return \"GET\";\n\tif (path === START_PATH) return \"GET, POST\";\n\tif (path === CONFIRM_PATH || path === ATTEMPTS_PATH || path === `${ATTEMPTS_PATH}/finalize`)\n\t\treturn \"POST\";\n\treturn null;\n}\nexport function matchesCoordinatorOwnerEnrollmentHttpPath(\n\tpath: string,\n\tmode: \"private\" | \"production\" = \"private\",\n): boolean {\n\treturn (\n\t\tcoordinatorOwnerEnrollmentHttpMethods(\n\t\t\tpath,\n\t\t\t\"\",\n\t\t\tmode === \"production\" ? \"/v1/auth/owner-config\" : \"/v1/auth/owner-pilot\",\n\t\t) !== null && path !== \"\"\n\t);\n}\nasync function dispatch(\n\trequest: Request,\n\tclientKey: string,\n\tcontext: HttpContext,\n): Promise<Response> {\n\tconst { api, scope, pin, callback } = context;\n\tconst path = new URL(request.url).pathname;\n\tif (path === context.pinPath) return json(pin);\n\tif (path === ATTEMPTS_PATH || path === `${ATTEMPTS_PATH}/finalize`)\n\t\treturn jsonAction(request, api, clientKey);\n\tif (path === START_PATH && request.method === \"GET\") return startPage(request, context);\n\tif (path === START_PATH) {\n\t\tconst result = await api.claimBrowser(request, clientKey);\n\t\treturn result.kind === \"browser_claimed\"\n\t\t\t? redirect(result.authorizationUrl, result.setCookies)\n\t\t\t: reject();\n\t}\n\tif (path === CONFIRM_PATH) return confirmBrowser(request, api, clientKey, scope.publicOrigin);\n\tif (path === callback) {\n\t\tconst result = await api.verifyCallback(request);\n\t\treturn result.kind === \"verified\" ? confirmationPage(result) : reject();\n\t}\n\treturn reject(404);\n}\n\ntype HttpContext = {\n\tapi: Enrollment;\n\tscope: BrowserCsrfScope;\n\tkey: BrowserCsrfKey;\n\tpin: BrowserCsrfScope[\"store\"] & { origin: string; issuer: string };\n\tcallback: string;\n\tpinPath: string;\n\tlimiter: InMemoryRequestRateLimiter;\n\ttransactionActivity(cookie: string | null): ReturnType<typeof readBrowserStartTransaction>;\n};\nexport function checkCoordinatorOwnerEnrollmentTransport(\n\trequest: Request,\n\tcontext: Pick<HttpContext, \"pin\" | \"callback\" | \"pinPath\">,\n): Response | null {\n\tconst url = new URL(request.url);\n\tif (\n\t\trequest.url.length > 8192 ||\n\t\turl.origin !== context.pin.origin ||\n\t\turl.username ||\n\t\turl.password ||\n\t\turl.hash\n\t)\n\t\treturn reject();\n\tconst methods = coordinatorOwnerEnrollmentHttpMethods(\n\t\turl.pathname,\n\t\tcontext.callback,\n\t\tcontext.pinPath,\n\t);\n\tif (!methods) return reject(404);\n\tif (!methods.split(\", \").includes(request.method)) return respond(null, 405, { Allow: methods });\n\tif (url.search && ![START_PATH, context.callback].includes(url.pathname)) return reject();\n\tif (request.method === \"POST\" && url.search) return reject();\n\tconst origin = request.headers.get(\"origin\");\n\tif (origin !== null && origin !== context.pin.origin) return reject();\n\treturn null;\n}\nasync function handleOwnerRequest(\n\trequest: Request,\n\ttrustedClientKey: string,\n\tcontext: HttpContext,\n): Promise<Response> {\n\ttry {\n\t\tconst error = checkCoordinatorOwnerEnrollmentTransport(request, context);\n\t\tif (error) return error;\n\t\tif (!isAuthControllerId(trustedClientKey) || trustedClientKey.length > 128) return reject();\n\t\tif (\n\t\t\t!checkBrowserAuthRequestRate(\n\t\t\t\trequest,\n\t\t\t\tcontext.limiter,\n\t\t\t\tJSON.stringify([\"owner-http\", context.pin.coordinatorId, trustedClientKey]),\n\t\t\t\t60,\n\t\t\t).allowed\n\t\t)\n\t\t\treturn reject(429);\n\t\treturn await dispatch(request, trustedClientKey, context);\n\t} catch {\n\t\treturn reject();\n\t}\n}\n\nfunction ownerComposition(\n\toptions: CoordinatorOwnerEnrollmentHttpOptions,\n\tcsrfKey: BrowserCsrfKey,\n\tlimiter: InMemoryRequestRateLimiter,\n\tmode: { production: boolean },\n) {\n\tif (mode.production) {\n\t\tif (options.mode !== \"production\") throw new Error(\"owner_enrollment_http_unavailable\");\n\t\treturn {\n\t\t\t...options,\n\t\t\tmode: \"production\" as const,\n\t\t\tpurpose: \"owner_enroll\" as const,\n\t\t\tcsrfKey,\n\t\t\tlimiter,\n\t\t};\n\t}\n\treturn {\n\t\t...options,\n\t\tmode: \"local_test\" as const,\n\t\tpurpose: \"owner_enroll\" as const,\n\t\tcsrfKey,\n\t\tlimiter,\n\t\tadmissionKey: undefined,\n\t};\n}\n\n/** Server supplies the trusted client key; no header or request body can override it. */\nexport async function createCoordinatorOwnerEnrollmentHttp(\n\toptions: CoordinatorOwnerEnrollmentHttpOptions,\n): Promise<CoordinatorOwnerEnrollmentHttp> {\n\tif (\n\t\toptions.mode !== undefined &&\n\t\toptions.mode !== \"private\" &&\n\t\toptions.mode !== \"local_test\" &&\n\t\toptions.mode !== \"production\"\n\t)\n\t\tthrow new Error(\"owner_enrollment_http_unavailable\");\n\tconst settings = captureCoordinatorBrowserAuthConfig(options.config);\n\tif (settings.kind !== \"enabled\") throw new Error(\"owner_enrollment_http_unavailable\");\n\tconst callback = new URL(settings.store.redirectUri).pathname;\n\tif (\n\t\tmatchesCoordinatorOwnerEnrollmentHttpPath(callback, \"private\") ||\n\t\tmatchesCoordinatorOwnerEnrollmentHttpPath(callback, \"production\")\n\t)\n\t\tthrow new Error(\"owner_enrollment_http_unavailable\");\n\tconst production = options.mode === \"production\";\n\tconst csrfKey = production\n\t\t? options.csrfKey\n\t\t: await importBrowserCsrfKey(globalThis.crypto.getRandomValues(new Uint8Array(32)));\n\tconst limiter = production\n\t\t? options.limiter\n\t\t: createInMemoryRequestRateLimiter({ now: options.clock });\n\tconst composition = ownerComposition(options, csrfKey, limiter, { production });\n\tconst created = await createCoordinatorOwnerEnrollment(composition);\n\tif (!created.ok) throw new Error(\"owner_enrollment_http_unavailable\");\n\tconst pin = Object.freeze({\n\t\tcoordinatorId: settings.store.coordinatorId,\n\t\torigin: settings.publicOrigin,\n\t\tissuer: settings.store.issuer,\n\t\trevision: settings.store.revision,\n\t});\n\tconst scope = { publicOrigin: pin.origin, store: settings.store };\n\tconst pinPath = production ? \"/v1/auth/owner-config\" : \"/v1/auth/owner-pilot\";\n\tconst transactions = new CoordinatorAuthBrowserTransactions(\n\t\tcomposition.backend,\n\t\tcomposition.clock,\n\t);\n\tconst context: HttpContext = {\n\t\tapi: created.enrollment,\n\t\tscope,\n\t\tkey: csrfKey,\n\t\tpin,\n\t\tcallback,\n\t\tpinPath,\n\t\tlimiter,\n\t\ttransactionActivity: (cookie) =>\n\t\t\treadBrowserStartTransaction(cookie, transactions, settings.store),\n\t};\n\treturn httpAdapter(context, { production });\n}\n\nfunction httpAdapter(\n\tcontext: HttpContext,\n\toptions: { production: boolean },\n): CoordinatorOwnerEnrollmentHttp {\n\tconst { pin, callback } = context;\n\tconst { production } = options;\n\treturn {\n\t\tpin,\n\t\tstartOwnerBound: (...args) => context.api.startOwnerBound(...args),\n\t\tmatchesPath: (path) =>\n\t\t\tmatchesCoordinatorOwnerEnrollmentHttpPath(path, production ? \"production\" : \"private\"),\n\t\thandle: (request: Request, trustedClientKey: string) =>\n\t\t\tproduction && new URL(request.url).pathname === callback\n\t\t\t\t? Promise.resolve(reject(404))\n\t\t\t\t: handleOwnerRequest(request, trustedClientKey, context),\n\t\thandleCallback: (request: Request, trustedClientKey: string) =>\n\t\t\tnew URL(request.url).pathname === callback\n\t\t\t\t? handleOwnerRequest(request, trustedClientKey, context)\n\t\t\t\t: Promise.resolve(reject(404)),\n\t};\n}\n","import type { OwnerEnrollmentStart } from \"./owner-enrollment-start.js\";\n\nexport const OWNER_ADMISSION_BODY_MAX_BYTES = 16 * 1024;\nconst START_FIELDS = [\n\t\"attemptId\",\n\t\"deviceId\",\n\t\"publicKey\",\n\t\"loopbackRedirect\",\n\t\"browserStartCode\",\n\t\"signature\",\n];\n\n/** Dedicated multipart limit. The ordinary browser forms stay at 4 KiB. */\nasync function readBytes(request: Request): Promise<Uint8Array<ArrayBuffer> | null> {\n\tconst declared = request.headers.get(\"content-length\");\n\tif (\n\t\tdeclared !== null &&\n\t\t(!/^[0-9]{1,10}$/.test(declared) || Number(declared) > OWNER_ADMISSION_BODY_MAX_BYTES)\n\t)\n\t\treturn null;\n\tif (!request.body) return null;\n\tconst reader = request.body.getReader();\n\tconst bytes = new Uint8Array(OWNER_ADMISSION_BODY_MAX_BYTES);\n\tlet size = 0;\n\ttry {\n\t\tfor (;;) {\n\t\t\tconst chunk = await reader.read();\n\t\t\tif (chunk.done) return bytes.subarray(0, size);\n\t\t\tif (!(chunk.value instanceof Uint8Array) || chunk.value.byteLength > bytes.length - size) {\n\t\t\t\tvoid reader.cancel().catch(() => {});\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tbytes.set(chunk.value, size);\n\t\t\tsize += chunk.value.byteLength;\n\t\t}\n\t} catch {\n\t\tvoid reader.cancel().catch(() => {});\n\t\treturn null;\n\t} finally {\n\t\treader.releaseLock();\n\t}\n}\n\n/** The file format is deliberately only two object levels with string leaves.\n * Validate that grammar before JSON.parse so duplicate keys (including escaped aliases)\n * cannot disappear during parsing. No general JSON parser or permissive normalization.\n */\nfunction parseStart(raw: string): OwnerEnrollmentStart | null {\n\tconst string = '\"(?:[^\"\\\\\\\\\\u0000-\\u001f]|\\\\\\\\(?:[\"\\\\\\\\/bfnrt]|u[0-9a-fA-F]{4}))*\"';\n\tconst pair = `${string}\\\\s*:\\\\s*${string}`;\n\tif (\n\t\t!new RegExp(\n\t\t\t`^\\\\s*\\\\{\\\\s*\"start\"\\\\s*:\\\\s*\\\\{\\\\s*${pair}(?:\\\\s*,\\\\s*${pair})*\\\\s*\\\\}\\\\s*\\\\}\\\\s*$`,\n\t\t).test(raw)\n\t)\n\t\treturn null;\n\tconst fields = new Set<string>();\n\tfor (const match of raw.matchAll(new RegExp(`(${string})\\\\s*:\\\\s*${string}`, \"g\"))) {\n\t\tconst name: unknown = JSON.parse(match[1] ?? \"null\");\n\t\tif (typeof name !== \"string\" || !START_FIELDS.includes(name) || fields.has(name)) return null;\n\t\tfields.add(name);\n\t}\n\tif (fields.size !== START_FIELDS.length) return null;\n\treturn Object.freeze((JSON.parse(raw) as { start: OwnerEnrollmentStart }).start);\n}\n\n/** Read the entire bounded body BEFORE invoking the runtime multipart parser. */\nexport async function readOwnerAdmissionUpload(\n\trequest: Request,\n): Promise<{ csrf: string; start: OwnerEnrollmentStart } | null> {\n\ttry {\n\t\tconst contentType = request.headers.get(\"content-type\") ?? \"\";\n\t\tif (contentType.length > 256 || !/^multipart\\/form-data\\s*;/i.test(contentType)) return null;\n\t\tconst bytes = await readBytes(request);\n\t\tif (!bytes) return null;\n\t\tconst form = await new Request(request.url, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: { \"Content-Type\": contentType },\n\t\t\tbody: bytes,\n\t\t}).formData();\n\t\tconst entries = [...form.entries()];\n\t\tif (\n\t\t\tentries.length !== 2 ||\n\t\t\tform.getAll(\"csrf\").length !== 1 ||\n\t\t\tform.getAll(\"request\").length !== 1\n\t\t)\n\t\t\treturn null;\n\t\tconst csrf = form.get(\"csrf\");\n\t\tconst file = form.get(\"request\");\n\t\tif (typeof csrf !== \"string\" || !(file instanceof File)) return null;\n\t\tconst start = parseStart(\n\t\t\tnew TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: true }).decode(await file.arrayBuffer()),\n\t\t);\n\t\treturn start ? { csrf, start } : null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n","import { CoordinatorAuthBrowserTransactions } from \"./coordinator-auth-browser-transaction.js\";\nimport { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport type { AuthLinkBackend } from \"./coordinator-auth-link.js\";\nimport { authLinkNow } from \"./coordinator-auth-link.js\";\nimport type { CoordinatorAuthSessionStore } from \"./coordinator-auth-session-contract.js\";\nimport { captureCoordinatorBrowserAuthConfig } from \"./coordinator-browser-auth-config.js\";\nimport {\n\ttype BrowserCookieReadResult,\n\treadBrowserCookie,\n} from \"./coordinator-browser-credential.js\";\nimport {\n\ttype BrowserCsrfKey,\n\tisBrowserCsrfKey,\n\tissueBrowserCsrfToken,\n\tverifyBrowserCsrfToken,\n} from \"./coordinator-browser-csrf.js\";\nimport { readBrowserStartTransaction } from \"./coordinator-browser-start-transaction.js\";\nimport { renderOwnerEnrollmentStartForm } from \"./coordinator-owner-enrollment-http.js\";\nimport {\n\townerAdmissionSchemaReady,\n\treadOwnerAdmissionAuthority,\n} from \"./owner-browser-admission-authority.js\";\nimport { readOwnerAdmissionUpload } from \"./owner-browser-admission-body.js\";\nimport {\n\tisOwnerEnrollmentAdmissionKey,\n\tissueOwnerEnrollmentAdmissionV2,\n\ttype OwnerEnrollmentAdmissionKey,\n\ttype OwnerEnrollmentResolvedOwner,\n} from \"./owner-enrollment-admission.js\";\nimport {\n\ttype createCoordinatorOwnerEnrollment,\n\townerEnrollmentHash,\n} from \"./owner-enrollment-start.js\";\nimport type { InMemoryRequestRateLimiter } from \"./request-rate-limit.js\";\n\nexport const OWNER_BROWSER_ADMISSION_PATH = \"/auth/owner/admit\";\ntype Enrollment = Extract<\n\tAwaited<ReturnType<typeof createCoordinatorOwnerEnrollment>>,\n\t{ ok: true }\n>[\"enrollment\"];\nexport interface OwnerBrowserAdmissionOptions {\n\t/** Explicit owner opt-in, independent of management sign-in being enabled. */\n\tenabled: boolean;\n\tconfig: unknown;\n\tbackend: AuthLinkBackend;\n\treadSession: CoordinatorAuthSessionStore[\"readAuthSession\"];\n\tcsrfKey: BrowserCsrfKey;\n\tadmissionKey: OwnerEnrollmentAdmissionKey;\n\tlimiter: InMemoryRequestRateLimiter;\n\tclock?: () => number;\n\t/** Lazy production owner composition. No OIDC discovery may run during setup. */\n\tgetEnrollment(): Promise<Pick<Enrollment, \"startOwnerBound\">>;\n}\n\nfunction response(body: string, status = 400, cookies: string[] = []): Response {\n\tconst headers = new Headers({\n\t\t\"Content-Type\": \"text/html; charset=utf-8\",\n\t\t\"Cache-Control\": \"no-store\",\n\t\t\"Referrer-Policy\": \"no-referrer\",\n\t\t\"X-Content-Type-Options\": \"nosniff\",\n\t\t\"Content-Security-Policy\":\n\t\t\t\"default-src 'none'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'\",\n\t});\n\tfor (const cookie of cookies) headers.append(\"Set-Cookie\", cookie);\n\treturn new Response(body, { status, headers });\n}\nfunction denied(status = 400) {\n\treturn response(\n\t\t'Owner admission unavailable. Sign in at <a href=\"/auth/sign-in\">Sign in</a> and prepare a new device request on this computer.',\n\t\tstatus,\n\t);\n}\nfunction escapeHtml(value: string): string {\n\treturn value.replace(\n\t\t/[&<>\"']/g,\n\t\t(c) => ({ \"&\": \"&amp;\", \"<\": \"&lt;\", \">\": \"&gt;\", '\"': \"&quot;\", \"'\": \"&#39;\" })[c] ?? \"\",\n\t);\n}\nfunction uploadPage(csrf: string): Response {\n\treturn response(\n\t\t`<!doctype html><html lang=\"en\"><meta charset=\"utf-8\"><title>Authorize device request</title><body>\n<h1>Authorize device request</h1>\n<p>Upload the private capability-request.json created on this computer. Do not upload a request sent by someone else: its signature proves possession of a key, not that the key belongs to this computer.</p>\n<p>Read your local device review first. Compare the device ID and key fingerprint shown in the next step before choosing an account. This authorizes a request; it does not finish enrollment. A fresh account check and device confirmation still follow.</p>\n<form method=\"post\" action=\"${OWNER_BROWSER_ADMISSION_PATH}\" enctype=\"multipart/form-data\">\n<input type=\"hidden\" name=\"csrf\" value=\"${escapeHtml(csrf)}\">\n<label>Private device request <input type=\"file\" name=\"request\" accept=\"application/json,.json\" required></label>\n<button type=\"submit\">Authorize device request</button></form></body></html>`,\n\t\t200,\n\t);\n}\nfunction transportValid(request: Request, origin: string): boolean {\n\tconst url = new URL(request.url);\n\tconst source = request.headers.get(\"origin\");\n\treturn (\n\t\trequest.url.length <= 8192 &&\n\t\turl.origin === origin &&\n\t\t!url.username &&\n\t\t!url.password &&\n\t\t!url.search &&\n\t\t!url.hash &&\n\t\t(source === null || source === origin) &&\n\t\t(request.method !== \"POST\" || source === origin)\n\t);\n}\n\n/** Caller must reserve this path and dispatch BEFORE browser/OIDC setup.\n * No capability is returned to the browser. Session authority admits only a new exact start;\n * it never replaces the later fresh owner-purpose OIDC proof or pending-key finalization.\n */\nexport function createOwnerBrowserAdmissionHandler(options: OwnerBrowserAdmissionOptions) {\n\tconst settings = captureCoordinatorBrowserAuthConfig(options.config);\n\tif (\n\t\tsettings.kind === \"enabled\" &&\n\t\tnew URL(settings.store.redirectUri).pathname === OWNER_BROWSER_ADMISSION_PATH\n\t)\n\t\tthrow new Error(\"owner_admission_callback_collision\");\n\tconst enabled =\n\t\toptions.enabled &&\n\t\tsettings.kind === \"enabled\" &&\n\t\tisBrowserCsrfKey(options.csrfKey) &&\n\t\tisOwnerEnrollmentAdmissionKey(options.admissionKey);\n\treturn async (request: Request, trustedClientKey: string): Promise<Response | null> => {\n\t\tif (new URL(request.url).pathname !== OWNER_BROWSER_ADMISSION_PATH) return null;\n\t\tif (!enabled || settings.kind !== \"enabled\") return denied(404);\n\t\ttry {\n\t\t\tconst rejection = checkTransport(request, trustedClientKey, options, settings);\n\t\t\tif (rejection) return rejection;\n\t\t\treturn await handle(request, trustedClientKey, options, settings);\n\t\t} catch {\n\t\t\treturn denied();\n\t\t}\n\t};\n}\ntype Settings = Extract<\n\tReturnType<typeof captureCoordinatorBrowserAuthConfig>,\n\t{ kind: \"enabled\" }\n>;\nfunction checkTransport(\n\trequest: Request,\n\tclientKey: string,\n\toptions: OwnerBrowserAdmissionOptions,\n\tsettings: Settings,\n): Response | null {\n\tif (!transportValid(request, settings.publicOrigin)) return denied();\n\tif (request.method !== \"GET\" && request.method !== \"POST\") return denied(405);\n\tif (!isAuthControllerId(clientKey) || clientKey.length > 128) return denied();\n\tif (\n\t\t!options.limiter.check(\n\t\t\tJSON.stringify([\"owner-admit-client\", settings.store.coordinatorId, clientKey]),\n\t\t\t20,\n\t\t).allowed\n\t)\n\t\treturn denied(429);\n\treturn null;\n}\nasync function availableTransaction(\n\trequest: Request,\n\tbackend: AuthLinkBackend,\n\tsettings: Settings,\n\tnow: () => number,\n) {\n\tconst transactions = new CoordinatorAuthBrowserTransactions(backend, now);\n\tconst activity = (header: string | null) =>\n\t\treadBrowserStartTransaction(header, transactions, settings.store);\n\tconst transaction = await activity(request.headers.get(\"cookie\"));\n\tif (transaction === \"active\" || transaction === \"invalid\") return null;\n\tconst startCookie = await readBrowserCookie(request.headers.get(\"cookie\"), \"start\");\n\treturn startCookie.kind === \"invalid\" ? null : activity;\n}\nasync function handle(\n\trequest: Request,\n\tclientKey: string,\n\toptions: OwnerBrowserAdmissionOptions,\n\tsettings: Settings,\n): Promise<Response> {\n\tconst { backend, csrfKey } = options;\n\tif (!(await ownerAdmissionSchemaReady(backend))) return denied();\n\tconst cookie = await readBrowserCookie(request.headers.get(\"cookie\"), \"session\");\n\tif (cookie.kind !== \"present\") return denied(403);\n\tconst session = await options.readSession(cookie.cookieHash, settings.store);\n\tif (!session) return denied(403);\n\tconst now = () => authLinkNow(options.clock ?? Date.now);\n\tconst base = { backend, config: settings.store, sessionCookieHash: cookie.cookieHash };\n\t// GET has no pending key yet. This checks trusted grants and orphan exclusions;\n\t// POST repeats the same predicate with the exact signed device and canonical key.\n\tconst owner = await readOwnerAdmissionAuthority({\n\t\t...base,\n\t\ttime: now(),\n\t\tdeviceId: \"\",\n\t\tfingerprint: \"\",\n\t});\n\tif (\n\t\t!owner ||\n\t\towner.identityId !== session.identityId ||\n\t\towner.linkId !== session.linkId ||\n\t\towner.issuer !== session.account.issuer ||\n\t\towner.subject !== session.account.subject\n\t)\n\t\treturn denied(403);\n\tif (\n\t\t!options.limiter.check(\n\t\t\tJSON.stringify([\"owner-admit-identity\", owner.coordinatorId, owner.identityId]),\n\t\t\t10,\n\t\t).allowed\n\t)\n\t\treturn denied(429);\n\tconst scope = { publicOrigin: settings.publicOrigin, store: settings.store };\n\tconst transactionActivity = await availableTransaction(request, backend, settings, now);\n\tif (!transactionActivity) return denied();\n\tif (request.method === \"GET\")\n\t\treturn uploadPage(await issueBrowserCsrfToken(csrfKey, cookie.secret, \"session\", scope));\n\treturn submitUpload(request, clientKey, options, settings, {\n\t\tcookie,\n\t\towner,\n\t\ttransactionActivity,\n\t\tnow,\n\t});\n}\ninterface UploadContext {\n\tcookie: Extract<BrowserCookieReadResult, { kind: \"present\" }>;\n\towner: OwnerEnrollmentResolvedOwner;\n\ttransactionActivity: NonNullable<Awaited<ReturnType<typeof availableTransaction>>>;\n\tnow: () => number;\n}\nasync function submitUpload(\n\trequest: Request,\n\tclientKey: string,\n\toptions: OwnerBrowserAdmissionOptions,\n\tsettings: Settings,\n\tcontext: UploadContext,\n): Promise<Response> {\n\tconst { cookie, owner, transactionActivity, now } = context;\n\tconst { backend, csrfKey, admissionKey } = options;\n\tconst scope = { publicOrigin: settings.publicOrigin, store: settings.store };\n\tconst upload = await readOwnerAdmissionUpload(request);\n\tif (\n\t\t!upload ||\n\t\t!(await verifyBrowserCsrfToken(csrfKey, cookie.secret, \"session\", scope, upload.csrf))\n\t)\n\t\treturn denied();\n\tconst { start } = upload;\n\tconst fingerprint = await ownerEnrollmentHash(start.publicKey);\n\tconst current = await readOwnerAdmissionAuthority({\n\t\tbackend,\n\t\tconfig: settings.store,\n\t\tsessionCookieHash: cookie.cookieHash,\n\t\ttime: now(),\n\t\tdeviceId: start.deviceId,\n\t\tfingerprint,\n\t});\n\tif (!current || JSON.stringify(current) !== JSON.stringify(owner)) return denied(403);\n\tconst pin = {\n\t\tcoordinatorId: settings.store.coordinatorId,\n\t\torigin: settings.publicOrigin,\n\t\tissuer: settings.store.issuer,\n\t\trevision: settings.store.revision,\n\t};\n\tconst admissionToken = await issueOwnerEnrollmentAdmissionV2(admissionKey, pin, start, {\n\t\tresolvedOwner: current,\n\t\tnowMs: now(),\n\t\tttlMs: 60_000,\n\t});\n\tconst enrollment = await options.getEnrollment();\n\tconst result = await enrollment.startOwnerBound(start, clientKey, {\n\t\tadmissionToken,\n\t\tresolvedOwner: current,\n\t\tsessionCookieHash: cookie.cookieHash,\n\t});\n\tif (result.kind !== \"started\") return denied();\n\treturn renderOwnerEnrollmentStartForm(\n\t\trequest,\n\t\t{ scope, key: csrfKey, transactionActivity },\n\t\t{\n\t\t\tattemptId: start.attemptId,\n\t\t\tstartCode: start.browserStartCode,\n\t\t\tdeviceId: start.deviceId,\n\t\t\tfingerprint,\n\t\t},\n\t);\n}\n","import type { Context, Hono } from \"hono\";\nimport type { AccountChangeOperations } from \"./coordinator-account-change.js\";\nimport {\n\tACCOUNT_CHANGE_BROWSER_PATHS,\n\tcreateCoordinatorAccountChangeBrowser,\n} from \"./coordinator-account-change-browser.js\";\nimport type {\n\tCoordinatorAuthBrowserConfig,\n\tCoordinatorAuthBrowserTransactionPurposeStore,\n\tCoordinatorAuthBrowserTransactionStore,\n} from \"./coordinator-auth-browser-transaction-contract.js\";\nimport { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport type { AuthLinkBackend } from \"./coordinator-auth-link.js\";\nimport type { CoordinatorAuthLinkStore } from \"./coordinator-auth-link-contract.js\";\nimport {\n\tAUTH_SCHEMA_UPGRADE_REQUIRED,\n\tassertConfiguredAuthSchema,\n\ttype CoordinatorAuthSchemaStore,\n\tCoordinatorAuthSchemaUpgradeRequiredError,\n} from \"./coordinator-auth-schema.js\";\nimport type { CoordinatorAuthSessionStore } from \"./coordinator-auth-session-contract.js\";\nimport {\n\ttype CoordinatorBrowserAccountInput,\n\tcreateCoordinatorBrowserAccount,\n} from \"./coordinator-browser-account.js\";\nimport {\n\ttype CoordinatorBrowserAuthCallbackInput,\n\tcreateCoordinatorBrowserAuthCallback,\n} from \"./coordinator-browser-auth-callback.js\";\nimport {\n\ttype CoordinatorBrowserAuthConfig,\n\ttype CoordinatorBrowserAuthConfigField,\n\ttype CoordinatorBrowserAuthSettings,\n\tcaptureCoordinatorBrowserAuthConfig,\n} from \"./coordinator-browser-auth-config.js\";\nimport { type BrowserCsrfKey, isBrowserCsrfKey } from \"./coordinator-browser-csrf.js\";\nimport {\n\tadmitBrowserFormSetup,\n\tcheckBrowserAuthRequestRate,\n} from \"./coordinator-browser-form-guard.js\";\nimport {\n\ttype CoordinatorBrowserLinkInput,\n\tcreateCoordinatorBrowserLinkHandlers,\n} from \"./coordinator-browser-link.js\";\nimport {\n\ttype CoordinatorBrowserLinkCompletionInput,\n\tcreateCoordinatorBrowserLinkCompletionHandlers,\n} from \"./coordinator-browser-link-completion.js\";\nimport {\n\ttype CoordinatorBrowserLinkStartInput,\n\tcreateCoordinatorBrowserLinkStart,\n} from \"./coordinator-browser-link-start.js\";\nimport {\n\ttype CoordinatorBrowserSigninStartInput,\n\tcreateCoordinatorBrowserSigninStart,\n} from \"./coordinator-browser-signin-start.js\";\nimport { createDeviceRebindBrowser } from \"./coordinator-device-rebind-browser.js\";\nimport { DEVICE_REBIND_BROWSER_PATHS } from \"./coordinator-device-rebind-view.js\";\nimport type { CoordinatorOidcOptions } from \"./coordinator-oidc.js\";\nimport {\n\tcheckCoordinatorOwnerEnrollmentTransport,\n\tcoordinatorOwnerEnrollmentHttpMethods,\n} from \"./coordinator-owner-enrollment-http.js\";\nimport { OWNER_BROWSER_ADMISSION_PATH } from \"./owner-browser-admission.js\";\nimport type { InMemoryRequestRateLimiter } from \"./request-rate-limit.js\";\n\nexport interface CoordinatorBrowserAuthOptions {\n\tconfig: unknown;\n\tcsrfKey?: BrowserCsrfKey;\n\toidcOptions?: CoordinatorOidcOptions;\n\townerEnrollment?: CoordinatorBrowserOwnerEnrollmentFactory;\n}\nexport interface CoordinatorBrowserOwnerEnrollmentAdapter {\n\thandle(request: Request, trustedClientKey: string): Promise<Response | null>;\n\thandleCallback(request: Request, trustedClientKey: string): Promise<Response>;\n}\nexport type CoordinatorBrowserOwnerEnrollmentFactory = (\n\tinput: Readonly<{\n\t\tconfig: Readonly<CoordinatorBrowserAuthConfig>;\n\t\tcsrfKey: BrowserCsrfKey;\n\t\toidcOptions: Readonly<CoordinatorOidcOptions>;\n\t\tlimiter: InMemoryRequestRateLimiter;\n\t}>,\n) => Promise<CoordinatorBrowserOwnerEnrollmentAdapter>;\ntype EnabledSettings = Extract<CoordinatorBrowserAuthSettings, { kind: \"enabled\" }>;\nexport type CoordinatorBrowserAuthSnapshot =\n\t| Readonly<{ kind: \"disabled\" }>\n\t| Readonly<{\n\t\t\tkind: \"invalid\";\n\t\t\terror: \"browser_auth_config_invalid\";\n\t\t\tfield: CoordinatorBrowserAuthConfigField | \"csrfKey\" | \"oidcOptions\" | \"ownerEnrollment\";\n\t }>\n\t| Readonly<{ kind: \"enabled\" }>;\ntype EnabledPayload = Readonly<{\n\tsettings: EnabledSettings;\n\tconfig: Readonly<CoordinatorBrowserAuthConfig>;\n\tcsrfKey: BrowserCsrfKey;\n\toidcOptions: Readonly<CoordinatorOidcOptions>;\n\tcallbackPath: string;\n\townerEnrollment?: CoordinatorBrowserOwnerEnrollmentFactory;\n}>;\nconst enabledPayloads = new WeakMap<object, EnabledPayload>();\nconst disabledMaintenancePins = new WeakMap<object, string>();\nexport type CoordinatorBrowserAuthStore = CoordinatorBrowserAccountInput[\"store\"] &\n\tCoordinatorBrowserAuthCallbackInput[\"store\"] &\n\tCoordinatorBrowserLinkInput[\"store\"] &\n\tCoordinatorBrowserLinkCompletionInput[\"store\"] &\n\tCoordinatorBrowserLinkStartInput[\"store\"] &\n\tCoordinatorBrowserSigninStartInput[\"store\"] &\n\tPartial<CoordinatorAuthBrowserTransactionPurposeStore & CoordinatorAuthSchemaStore>;\nexport type CoordinatorBrowserAuthClientKey = (context: Context) => string | null;\nexport interface CoordinatorBrowserAuth {\n\treadonly storeConfig: Readonly<CoordinatorAuthBrowserConfig>;\n\treadonly resolveAccountChanges?: typeof resolveAccountChanges;\n\tregister(app: Hono, clientKey: CoordinatorBrowserAuthClientKey): void;\n}\nexport type CoordinatorBrowserAuthResult =\n\t| Readonly<{ ok: true; auth: CoordinatorBrowserAuth }>\n\t| Readonly<{\n\t\t\tok: false;\n\t\t\terror:\n\t\t\t\t| \"browser_auth_disabled\"\n\t\t\t\t| \"browser_auth_config_invalid\"\n\t\t\t\t| \"browser_auth_setup_failed\"\n\t\t\t\t| \"browser_auth_store_unavailable\"\n\t\t\t\t| typeof AUTH_SCHEMA_UPGRADE_REQUIRED;\n\t }>;\n\nconst FIXED_PATHS: Readonly<Record<string, readonly string[]>> = {\n\t\"/auth/sign-in\": [\"GET\", \"POST\"],\n\t\"/auth/link/start\": [\"GET\", \"POST\"],\n\t\"/auth/link/confirm\": [\"POST\"],\n\t\"/auth/link/cancel\": [\"POST\"],\n\t\"/auth/link/complete\": [\"GET\", \"POST\"],\n\t\"/auth/account\": [\"GET\"],\n\t\"/auth/logout\": [\"POST\"],\n\t\"/auth/owner/start\": [\"GET\", \"POST\"],\n\t\"/auth/owner/confirm\": [\"POST\"],\n\t\"/auth/account/change/start\": [\"GET\", \"POST\"],\n\t\"/auth/account/change/confirm\": [\"POST\"],\n\t[DEVICE_REBIND_BROWSER_PATHS.start]: [\"GET\", \"POST\"],\n\t[DEVICE_REBIND_BROWSER_PATHS.confirm]: [\"POST\"],\n};\nconst OWNER_PATHS = [\n\t\"/auth/owner/start\",\n\t\"/auth/owner/confirm\",\n\t\"/v1/auth/owner-config\",\n\t\"/v1/auth/owner-attempts\",\n\t\"/v1/auth/owner-attempts/finalize\",\n];\nfunction ownData(value: unknown, name: string): unknown {\n\tif (value === null || typeof value !== \"object\" || Array.isArray(value)) throw new Error();\n\tconst descriptor = Object.getOwnPropertyDescriptor(value, name);\n\tif (descriptor && !Object.hasOwn(descriptor, \"value\")) throw new Error();\n\treturn descriptor?.value;\n}\nfunction invalid(\n\tfield: Extract<CoordinatorBrowserAuthSnapshot, { kind: \"invalid\" }>[\"field\"],\n): CoordinatorBrowserAuthSnapshot {\n\treturn Object.freeze({ kind: \"invalid\", error: \"browser_auth_config_invalid\", field });\n}\nfunction captureOidcOptions(value: unknown): Readonly<CoordinatorOidcOptions> {\n\tif (value === undefined) return Object.freeze({});\n\tconst fetch = ownData(value, \"fetch\");\n\tconst timeoutSeconds = ownData(value, \"timeoutSeconds\");\n\tif (fetch !== undefined && typeof fetch !== \"function\") throw new Error();\n\tif (\n\t\ttimeoutSeconds !== undefined &&\n\t\t(typeof timeoutSeconds !== \"number\" ||\n\t\t\t!Number.isFinite(timeoutSeconds) ||\n\t\t\ttimeoutSeconds < 1 ||\n\t\t\ttimeoutSeconds > 30)\n\t)\n\t\tthrow new Error();\n\treturn Object.freeze({\n\t\tfetch: fetch as CoordinatorOidcOptions[\"fetch\"],\n\t\ttimeoutSeconds: timeoutSeconds as number | undefined,\n\t});\n}\n/** Capture secrets and transport references before any discovery awaits. */\nexport function captureCoordinatorBrowserAuthOptions(\n\tinput: CoordinatorBrowserAuthOptions,\n): CoordinatorBrowserAuthSnapshot {\n\ttry {\n\t\tconst configInput = ownData(input, \"config\");\n\t\tconst settings = captureCoordinatorBrowserAuthConfig(configInput);\n\t\tif (settings.kind === \"disabled\") {\n\t\t\tconst snapshot = Object.freeze({ kind: \"disabled\" as const });\n\t\t\tconst coordinatorId =\n\t\t\t\tconfigInput === undefined ? undefined : ownData(configInput, \"coordinatorId\");\n\t\t\tif (isAuthControllerId(coordinatorId)) disabledMaintenancePins.set(snapshot, coordinatorId);\n\t\t\treturn snapshot;\n\t\t}\n\t\tif (settings.kind === \"invalid\") return invalid(settings.field);\n\t\tconst callbackPath = new URL(settings.store.redirectUri).pathname;\n\t\tif (\n\t\t\t!/^\\/auth\\/[A-Za-z0-9._~/-]+$/.test(callbackPath) ||\n\t\t\tcallbackPath === OWNER_BROWSER_ADMISSION_PATH ||\n\t\t\tObject.hasOwn(FIXED_PATHS, callbackPath)\n\t\t)\n\t\t\treturn invalid(\"redirectUri\");\n\t\tlet csrfKey: unknown;\n\t\ttry {\n\t\t\tcsrfKey = ownData(input, \"csrfKey\");\n\t\t} catch {\n\t\t\treturn invalid(\"csrfKey\");\n\t\t}\n\t\tif (!isBrowserCsrfKey(csrfKey)) return invalid(\"csrfKey\");\n\t\tlet oidcOptions: Readonly<CoordinatorOidcOptions>;\n\t\ttry {\n\t\t\toidcOptions = captureOidcOptions(ownData(input, \"oidcOptions\"));\n\t\t} catch {\n\t\t\treturn invalid(\"oidcOptions\");\n\t\t}\n\t\tconst config = Object.freeze({\n\t\t\t...settings.store,\n\t\t\tclientId: settings.oidc.clientId,\n\t\t\tclientSecret: settings.oidc.clientSecret,\n\t\t});\n\t\tconst ownerEnrollment = ownData(input, \"ownerEnrollment\");\n\t\tif (ownerEnrollment !== undefined && typeof ownerEnrollment !== \"function\")\n\t\t\treturn invalid(\"ownerEnrollment\");\n\t\tconst handle = Object.freeze({ kind: \"enabled\" as const });\n\t\tenabledPayloads.set(\n\t\t\thandle,\n\t\t\tObject.freeze({\n\t\t\t\tsettings,\n\t\t\t\tconfig,\n\t\t\t\tcsrfKey,\n\t\t\t\toidcOptions,\n\t\t\t\tcallbackPath,\n\t\t\t\townerEnrollment: ownerEnrollment as CoordinatorBrowserOwnerEnrollmentFactory | undefined,\n\t\t\t}),\n\t\t);\n\t\treturn handle;\n\t} catch {\n\t\treturn invalid(\"config\");\n\t}\n}\n\n/** Device routes need the pinned store config, not Google discovery or browser handlers. */\nexport function coordinatorBrowserAuthDeviceRoutes(\n\tsnapshot: CoordinatorBrowserAuthSnapshot,\n): CoordinatorBrowserAuth | undefined {\n\tconst payload = enabledPayloads.get(snapshot);\n\tif (!payload) return undefined;\n\treturn { storeConfig: payload.settings.store, resolveAccountChanges, register: () => {} };\n}\n\n/** null skips setup; a Response rejects before I/O; true admits the actual mounted route. */\nexport function admitCoordinatorBrowserAuthSetup(\n\tsnapshot: CoordinatorBrowserAuthSnapshot,\n\trequest: Request,\n\tlimiter: InMemoryRequestRateLimiter,\n\tclientKey: string,\n): true | Response | null {\n\tconst payload = enabledPayloads.get(snapshot);\n\tif (!payload) return null;\n\tconst url = new URL(request.url);\n\tconst ownerMethods =\n\t\tpayload.ownerEnrollment && url.pathname !== payload.callbackPath\n\t\t\t? coordinatorOwnerEnrollmentHttpMethods(\n\t\t\t\t\turl.pathname,\n\t\t\t\t\tpayload.callbackPath,\n\t\t\t\t\t\"/v1/auth/owner-config\",\n\t\t\t\t)\n\t\t\t: null;\n\tlet methods = FIXED_PATHS[url.pathname];\n\tif (OWNER_PATHS.includes(url.pathname)) methods = ownerMethods?.split(\", \") ?? [];\n\tif (url.pathname === payload.callbackPath) methods = [\"GET\"];\n\tif (!methods?.length) return null;\n\tif (!methods.includes(request.method))\n\t\treturn new Response(\"Method not allowed.\", {\n\t\t\tstatus: 405,\n\t\t\theaders: { Allow: methods.join(\", \") },\n\t\t});\n\tif (url.origin !== payload.settings.publicOrigin)\n\t\treturn new Response(\"Not found.\", { status: 404 });\n\tif (ownerMethods) return admitOwnerSetup(payload, request, limiter, clientKey);\n\treturn admitFormSetup(payload, request, limiter, clientKey);\n}\n\nfunction admitOwnerSetup(\n\tpayload: EnabledPayload,\n\trequest: Request,\n\tlimiter: InMemoryRequestRateLimiter,\n\tclientKey: string,\n): true | Response {\n\tconst transportError = checkCoordinatorOwnerEnrollmentTransport(request, {\n\t\tpin: {\n\t\t\tcoordinatorId: payload.config.coordinatorId,\n\t\t\trevision: payload.config.revision,\n\t\t\tissuer: payload.config.issuer,\n\t\t\torigin: payload.settings.publicOrigin,\n\t\t},\n\t\tcallback: payload.callbackPath,\n\t\tpinPath: \"/v1/auth/owner-config\",\n\t});\n\tif (transportError) return transportError;\n\tif (!isAuthControllerId(clientKey) || clientKey.length > 128)\n\t\treturn new Response(\"Invalid request.\", { status: 400 });\n\tconst rate = checkBrowserAuthRequestRate(\n\t\trequest,\n\t\tlimiter,\n\t\tJSON.stringify([\"owner-http\", payload.config.coordinatorId, clientKey]),\n\t\t60,\n\t\t{ admitSetup: true },\n\t);\n\tif (!rate.allowed)\n\t\treturn new Response(\"Too many requests.\", {\n\t\t\tstatus: 429,\n\t\t\theaders: { \"Retry-After\": String(rate.retryAfterS) },\n\t\t});\n\treturn true;\n}\n\nfunction admitFormSetup(\n\tpayload: EnabledPayload,\n\trequest: Request,\n\tlimiter: InMemoryRequestRateLimiter,\n\tclientKey: string,\n): true | Response {\n\tif (request.method !== \"POST\") return true;\n\tconst url = new URL(request.url);\n\tlet action: \"session_logout\" | \"signin_start\" | \"link_start\" | \"transaction_attempt\" =\n\t\t\"transaction_attempt\";\n\tif (url.pathname === \"/auth/logout\") action = \"session_logout\";\n\tif (url.pathname === \"/auth/sign-in\") action = \"signin_start\";\n\tif (url.pathname === \"/auth/link/start\") action = \"link_start\";\n\tif (url.pathname === ACCOUNT_CHANGE_BROWSER_PATHS.start) action = \"link_start\";\n\tif (url.pathname === DEVICE_REBIND_BROWSER_PATHS.start) action = \"link_start\";\n\tconst failure = admitBrowserFormSetup({\n\t\trequest,\n\t\tscope: payload.settings,\n\t\tcsrfKey: payload.csrfKey,\n\t\taction,\n\t\tlimiter,\n\t\tclientKey,\n\t});\n\tif (!failure) return true;\n\tlet status = 503;\n\tif (failure.error === \"rate_limited\") status = 429;\n\tif (failure.error === \"origin_rejected\") status = 403;\n\treturn new Response(\"Authentication request rejected.\", {\n\t\tstatus,\n\t\theaders: {\n\t\t\t\"Cache-Control\": \"no-store\",\n\t\t\t\"Referrer-Policy\": \"no-referrer\",\n\t\t\t\"X-Content-Type-Options\": \"nosniff\",\n\t\t\t...(failure.retryAfterS ? { \"Retry-After\": String(failure.retryAfterS) } : {}),\n\t\t},\n\t});\n}\n\nexport function coordinatorBrowserAuthUnavailableResponse(): Response {\n\treturn new Response(\"Authentication unavailable. Try again.\", {\n\t\tstatus: 503,\n\t\theaders: {\n\t\t\t\"Content-Type\": \"text/plain;charset=utf-8\",\n\t\t\t\"Cache-Control\": \"no-store\",\n\t\t\t\"Referrer-Policy\": \"no-referrer\",\n\t\t\t\"X-Content-Type-Options\": \"nosniff\",\n\t\t},\n\t});\n}\ntype BrowserHandler = (\n\trequest: Request,\n\tclientKey: string,\n) => Promise<Readonly<{ response: Response }>>;\ntype Route = Readonly<{ path: string; get?: BrowserHandler; post?: BrowserHandler }>;\nfunction registerRoutes(\n\tapp: Hono,\n\troutes: readonly Route[],\n\tclientKey: CoordinatorBrowserAuthClientKey,\n): void {\n\tfor (const route of routes) {\n\t\tapp.all(route.path, async (context) => {\n\t\t\ttry {\n\t\t\t\tconst request = context.req.raw;\n\t\t\t\tlet handler: BrowserHandler | undefined;\n\t\t\t\tif (request.method === \"GET\") handler = route.get;\n\t\t\t\tif (request.method === \"POST\") handler = route.post;\n\t\t\t\tif (!handler)\n\t\t\t\t\treturn new Response(\"Method not allowed.\", {\n\t\t\t\t\t\tstatus: 405,\n\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\tAllow: [route.get && \"GET\", route.post && \"POST\"].filter(Boolean).join(\", \"),\n\t\t\t\t\t\t\t\"Cache-Control\": \"no-store\",\n\t\t\t\t\t\t\t\"Referrer-Policy\": \"no-referrer\",\n\t\t\t\t\t\t\t\"X-Content-Type-Options\": \"nosniff\",\n\t\t\t\t\t\t\t\"Content-Type\": \"text/plain;charset=utf-8\",\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\t\t\t\treturn (await handler(request, clientKey(context) ?? \"\")).response;\n\t\t\t} catch {\n\t\t\t\treturn coordinatorBrowserAuthUnavailableResponse();\n\t\t\t}\n\t\t});\n\t}\n}\n/** The purpose store is read only when a ceremony shares the `owner_enroll` purpose. */\nfunction createSharedCallback(\n\tinput: Omit<CoordinatorBrowserAuthCallbackInput, \"completeLink\" | \"store\"> & {\n\t\tstore: CoordinatorBrowserAuthStore;\n\t},\n\thandlers: Pick<\n\t\tCoordinatorBrowserAuthCallbackInput,\n\t\t\"completeLink\" | \"ownerCallback\" | \"accountChangeCallback\" | \"deviceRebindCallback\"\n\t>,\n) {\n\tconst sharesOwnerPurpose = handlers.ownerCallback || handlers.deviceRebindCallback;\n\treturn createCoordinatorBrowserAuthCallback({\n\t\t...input,\n\t\t...handlers,\n\t\tpurposeStore: sharesOwnerPurpose ? capturePurposeStore(input.store) : undefined,\n\t});\n}\n\n/** Owns handlers, not the store lifetime. Nothing is mounted until all factories succeed. */\nexport async function createCoordinatorBrowserAuth(\n\tsnapshot: CoordinatorBrowserAuthSnapshot,\n\tstore: CoordinatorBrowserAuthStore,\n\tlimiter: InMemoryRequestRateLimiter,\n): Promise<CoordinatorBrowserAuthResult> {\n\tif (snapshot.kind === \"disabled\")\n\t\treturn Object.freeze({ ok: false, error: \"browser_auth_disabled\" });\n\tif (snapshot.kind === \"invalid\")\n\t\treturn Object.freeze({ ok: false, error: \"browser_auth_config_invalid\" });\n\ttry {\n\t\tconst payload = enabledPayloads.get(snapshot);\n\t\tif (!payload) return Object.freeze({ ok: false, error: \"browser_auth_setup_failed\" });\n\t\tconst checked = await browserAuthStoreState(store);\n\t\tif (\"error\" in checked) return Object.freeze({ ok: false, error: checked.error });\n\t\tconst rebind = createRebindAdapter(payload, store, limiter);\n\t\tconst input = Object.freeze({\n\t\t\tconfig: payload.config,\n\t\t\tcsrfKey: payload.csrfKey,\n\t\t\toidcOptions: payload.oidcOptions,\n\t\t\tstore,\n\t\t\tlimiter,\n\t\t});\n\t\tconst link = createCoordinatorBrowserLinkHandlers({\n\t\t\t...input,\n\t\t\tconfig: payload.settings.store,\n\t\t});\n\t\tconst completion = createCoordinatorBrowserLinkCompletionHandlers({\n\t\t\t...input,\n\t\t\tconfig: payload.settings.store,\n\t\t});\n\t\tif (!link.ok || !completion.ok)\n\t\t\treturn Object.freeze({ ok: false, error: \"browser_auth_setup_failed\" });\n\t\tconst signin = await createCoordinatorBrowserSigninStart(input);\n\t\tconst start = await createCoordinatorBrowserLinkStart(input);\n\t\tconst owner = await createOwnerAdapter(payload, limiter);\n\t\tconst change = await createChangeAdapter(payload, store, limiter, checked.operations);\n\t\tconst callback = await createSharedCallback(input, {\n\t\t\tcompleteLink: link.handlers.completeLink,\n\t\t\townerCallback: owner?.handleCallback,\n\t\t\taccountChangeCallback: change.callback,\n\t\t\tdeviceRebindCallback: rebind.callback,\n\t\t});\n\t\tconst account = await createCoordinatorBrowserAccount(input);\n\t\tif (!signin.ok || !start.ok || !callback.ok || !account.ok)\n\t\t\treturn Object.freeze({ ok: false, error: \"browser_auth_setup_failed\" });\n\t\tconst routes: readonly Route[] = Object.freeze([\n\t\t\t{ path: \"/auth/sign-in\", get: signin.handlers.signInPage, post: signin.handlers.signInStart },\n\t\t\t{\n\t\t\t\tpath: \"/auth/link/start\",\n\t\t\t\tget: start.handlers.linkStartPage,\n\t\t\t\tpost: start.handlers.linkStart,\n\t\t\t},\n\t\t\t{ path: payload.callbackPath, get: callback.handlers.callback },\n\t\t\t{ path: \"/auth/link/confirm\", post: link.handlers.confirm },\n\t\t\t{ path: \"/auth/link/cancel\", post: link.handlers.cancel },\n\t\t\t{\n\t\t\t\tpath: \"/auth/link/complete\",\n\t\t\t\tget: completion.handlers.page,\n\t\t\t\tpost: completion.handlers.complete,\n\t\t\t},\n\t\t\t{ path: \"/auth/account\", get: account.handlers.account },\n\t\t\t{ path: \"/auth/logout\", post: account.handlers.logout },\n\t\t\t...ownerRoutes(owner),\n\t\t\t...change.routes,\n\t\t\t...rebind.routes,\n\t\t]);\n\t\treturn browserAuthReady(payload.settings.store, routes, { accountChanges: change.enabled });\n\t} catch (error) {\n\t\treturn browserAuthSetupFailure(error);\n\t}\n}\n\nasync function createChangeAdapter(\n\tpayload: EnabledPayload,\n\tstore: CoordinatorBrowserAuthStore,\n\tlimiter: InMemoryRequestRateLimiter,\n\toperations: AccountChangeOperations | null,\n): Promise<{\n\tenabled: boolean;\n\troutes: Route[];\n\tcallback?: CoordinatorBrowserAuthCallbackInput[\"accountChangeCallback\"];\n}> {\n\tif (!operations) return { enabled: false, routes: [] };\n\tconst change = await createCoordinatorAccountChangeBrowser({\n\t\tconfig: payload.config,\n\t\tcsrfKey: payload.csrfKey,\n\t\toidcOptions: payload.oidcOptions,\n\t\tlimiter,\n\t\toperations,\n\t\treaders: {\n\t\t\treadStart: operations.readStart.bind(operations),\n\t\t\treadManagementActivity: operations.readManagementActivity.bind(operations),\n\t\t\treadBrowserBinding: operations.readBrowserBinding.bind(operations),\n\t\t},\n\t\texisting: {\n\t\t\t...capturePurposeStore(store),\n\t\t\treadAuthBrowserTransactionActivity: store.readAuthBrowserTransactionActivity.bind(store),\n\t\t},\n\t});\n\tif (!change.ok) throw new Error();\n\treturn {\n\t\tenabled: true,\n\t\troutes: [\n\t\t\t{\n\t\t\t\tpath: ACCOUNT_CHANGE_BROWSER_PATHS.start,\n\t\t\t\tget: async (request) => ({ response: await change.handlers.startPage(request) }),\n\t\t\t\tpost: async (request, key) => ({ response: await change.handlers.start(request, key) }),\n\t\t\t},\n\t\t\t{\n\t\t\t\tpath: ACCOUNT_CHANGE_BROWSER_PATHS.confirm,\n\t\t\t\tpost: async (request, key) => ({ response: await change.handlers.confirm(request, key) }),\n\t\t\t},\n\t\t],\n\t\tcallback: async (request, key, binderHash) => {\n\t\t\tconst activity = await operations.readManagementActivity(\n\t\t\t\t{ binderHash },\n\t\t\t\tpayload.settings.store,\n\t\t\t);\n\t\t\tif ((await change.handlers.matchesCallback(request)) || activity.kind !== \"inactive\")\n\t\t\t\treturn change.handlers.callback(request, key);\n\t\t\treturn null;\n\t\t},\n\t};\n}\n\ntype RebindHandlers = Extract<\n\tAwaited<ReturnType<typeof createDeviceRebindBrowser>>,\n\t{ ok: true }\n>[\"handlers\"];\n\n/**\n * Rebind is optional and does no I/O at setup. Each use first checks for its\n * tables (absent on a D1 database before migration 0038); until they exist\n * the pages report not found and the callback hook steps aside, so sign-in\n * and owner enrollment are unaffected. Only a ready composition is kept.\n */\nfunction createRebindAdapter(\n\tpayload: EnabledPayload,\n\tstore: CoordinatorBrowserAuthStore,\n\tlimiter: InMemoryRequestRateLimiter,\n): { routes: Route[]; callback?: (request: Request) => Promise<Response | null> } {\n\tconst read = storeMethod(store, \"readDeviceRebindBackend\");\n\tif (!read) return { routes: [] };\n\tlet ready: RebindHandlers | undefined;\n\tconst resolve = async (): Promise<RebindHandlers | null> => {\n\t\tif (ready) return ready;\n\t\tconst backend = (await read()) as AuthLinkBackend | null;\n\t\tif (!backend) return null;\n\t\tconst created = await createDeviceRebindBrowser({\n\t\t\tconfig: payload.config,\n\t\t\tcsrfKey: payload.csrfKey,\n\t\t\toidcOptions: payload.oidcOptions,\n\t\t\tlimiter,\n\t\t\tbackend,\n\t\t});\n\t\tif (!created.ok) return null;\n\t\tready ??= created.handlers;\n\t\treturn ready;\n\t};\n\tconst page =\n\t\t(step: \"startPage\" | \"start\" | \"confirm\"): BrowserHandler =>\n\t\tasync (request, key) => {\n\t\t\tconst handlers = await resolve();\n\t\t\treturn { response: handlers ? await handlers[step](request, key) : rebindNotFound() };\n\t\t};\n\treturn {\n\t\troutes: [\n\t\t\t{ path: DEVICE_REBIND_BROWSER_PATHS.start, get: page(\"startPage\"), post: page(\"start\") },\n\t\t\t{ path: DEVICE_REBIND_BROWSER_PATHS.confirm, post: page(\"confirm\") },\n\t\t],\n\t\tcallback: async (request) => {\n\t\t\ttry {\n\t\t\t\treturn (await (await resolve())?.callback(request)) ?? null;\n\t\t\t} catch {\n\t\t\t\t// Unreadable rebind storage: owner dispatch decides, and fails closed.\n\t\t\t\treturn null;\n\t\t\t}\n\t\t},\n\t};\n}\n\nfunction rebindNotFound(): Response {\n\treturn new Response(\"Not found.\", {\n\t\tstatus: 404,\n\t\theaders: { \"Cache-Control\": \"no-store\", \"X-Content-Type-Options\": \"nosniff\" },\n\t});\n}\n\nfunction browserAuthReady(\n\tstoreConfig: CoordinatorAuthBrowserConfig,\n\troutes: readonly Route[],\n\toptions: { accountChanges: boolean },\n): CoordinatorBrowserAuthResult {\n\treturn Object.freeze({\n\t\tok: true,\n\t\tauth: Object.freeze({\n\t\t\tstoreConfig,\n\t\t\tresolveAccountChanges: options.accountChanges ? resolveAccountChanges : undefined,\n\t\t\tregister: (app: Hono, clientKey: CoordinatorBrowserAuthClientKey) =>\n\t\t\t\tregisterRoutes(app, routes, clientKey),\n\t\t}),\n\t});\n}\n\nasync function browserAuthStoreState(\n\tstore: CoordinatorBrowserAuthStore,\n): Promise<\n\t| { operations: AccountChangeOperations | null }\n\t| { error: typeof AUTH_SCHEMA_UPGRADE_REQUIRED | \"browser_auth_store_unavailable\" }\n> {\n\ttry {\n\t\tconst read = storeMethod(store, \"readAccountChangeCapability\");\n\t\tif (read) return { operations: (await read()) as AccountChangeOperations | null };\n\t\tawait assertConfiguredAuthSchema(store);\n\t\treturn { operations: await resolveAccountChanges(store) };\n\t} catch (error) {\n\t\tif (error instanceof CoordinatorAuthSchemaUpgradeRequiredError)\n\t\t\treturn { error: AUTH_SCHEMA_UPGRADE_REQUIRED };\n\t\treturn { error: \"browser_auth_store_unavailable\" };\n\t}\n}\n\nfunction browserAuthSetupFailure(error: unknown): CoordinatorBrowserAuthResult {\n\tif (error instanceof CoordinatorAuthSchemaUpgradeRequiredError)\n\t\treturn Object.freeze({ ok: false, error: AUTH_SCHEMA_UPGRADE_REQUIRED });\n\treturn Object.freeze({ ok: false, error: \"browser_auth_setup_failed\" });\n}\n\nfunction ownerRoutes(owner: CoordinatorBrowserOwnerEnrollmentAdapter | undefined): Route[] {\n\tif (!owner) return [];\n\tconst handler: BrowserHandler = async (request, key) => ({\n\t\tresponse: (await owner.handle(request, key)) ?? coordinatorBrowserAuthUnavailableResponse(),\n\t});\n\treturn OWNER_PATHS.map((path) => ({ path, get: handler, post: handler }));\n}\n\nasync function createOwnerAdapter(\n\tpayload: EnabledPayload,\n\tlimiter: InMemoryRequestRateLimiter,\n): Promise<CoordinatorBrowserOwnerEnrollmentAdapter | undefined> {\n\tif (!payload.ownerEnrollment) return undefined;\n\tconst adapter = await payload.ownerEnrollment(\n\t\tObject.freeze({\n\t\t\tconfig: payload.config,\n\t\t\tcsrfKey: payload.csrfKey,\n\t\t\toidcOptions: payload.oidcOptions,\n\t\t\tlimiter,\n\t\t}),\n\t);\n\tconst handle = ownData(adapter, \"handle\");\n\tconst handleCallback = ownData(adapter, \"handleCallback\");\n\tif (typeof handle !== \"function\" || typeof handleCallback !== \"function\") throw new Error();\n\treturn Object.freeze({\n\t\thandle: (...args: Parameters<CoordinatorBrowserOwnerEnrollmentAdapter[\"handle\"]>) =>\n\t\t\tReflect.apply(handle, adapter, args),\n\t\thandleCallback: (\n\t\t\t...args: Parameters<CoordinatorBrowserOwnerEnrollmentAdapter[\"handleCallback\"]>\n\t\t) => Reflect.apply(handleCallback, adapter, args),\n\t});\n}\n\nfunction storeMethod(receiver: unknown, name: string): ((...args: never[]) => unknown) | undefined {\n\tif (!receiver || typeof receiver !== \"object\") throw new Error();\n\tlet cursor: object | null = receiver;\n\tconst seen = new Set<object>();\n\twhile (cursor) {\n\t\tif (seen.has(cursor)) throw new Error();\n\t\tseen.add(cursor);\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(cursor, name);\n\t\tif (descriptor) {\n\t\t\tif (!Object.hasOwn(descriptor, \"value\") || typeof descriptor.value !== \"function\")\n\t\t\t\tthrow new Error();\n\t\t\tconst method = descriptor.value;\n\t\t\treturn (...args) => Reflect.apply(method, receiver, args);\n\t\t}\n\t\tcursor = Object.getPrototypeOf(cursor);\n\t}\n\treturn undefined;\n}\nasync function resolveAccountChanges(store: unknown): Promise<AccountChangeOperations | null> {\n\tconst checked = storeMethod(store, \"readAccountChangeCapability\");\n\tif (checked) return (await checked()) as AccountChangeOperations | null;\n\tconst read = storeMethod(store, \"readAccountConnectionSchemaState\");\n\tconst get = storeMethod(store, \"getAccountChanges\");\n\tif (!read && !get) return null;\n\tif (!read || !get) throw new Error();\n\tconst state = await read();\n\tif (state === \"v2\") return null;\n\tif (state !== \"ready\") throw new CoordinatorAuthSchemaUpgradeRequiredError();\n\treturn (await get()) as AccountChangeOperations;\n}\nfunction capturePurposeStore(\n\tstore: CoordinatorBrowserAuthStore,\n): CoordinatorAuthBrowserTransactionPurposeStore {\n\tlet cursor: object | null = store;\n\tconst seen = new Set<object>();\n\twhile (cursor !== null) {\n\t\tif (seen.has(cursor)) throw new Error();\n\t\tseen.add(cursor);\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(cursor, \"readAuthBrowserTransactionPurpose\");\n\t\tif (descriptor) {\n\t\t\tif (!Object.hasOwn(descriptor, \"value\") || typeof descriptor.value !== \"function\")\n\t\t\t\tthrow new Error();\n\t\t\tconst method =\n\t\t\t\tdescriptor.value as CoordinatorAuthBrowserTransactionPurposeStore[\"readAuthBrowserTransactionPurpose\"];\n\t\t\treturn Object.freeze({\n\t\t\t\treadAuthBrowserTransactionPurpose: (\n\t\t\t\t\t...args: Parameters<\n\t\t\t\t\t\tCoordinatorAuthBrowserTransactionPurposeStore[\"readAuthBrowserTransactionPurpose\"]\n\t\t\t\t\t>\n\t\t\t\t) => Reflect.apply(method, store, args),\n\t\t\t});\n\t\t}\n\t\tcursor = Object.getPrototypeOf(cursor);\n\t}\n\tthrow new Error();\n}\n\nexport type CoordinatorBrowserAuthMaintenanceStore = Pick<\n\tCoordinatorAuthLinkStore,\n\t\"maintainAuthLinkAttempts\"\n> &\n\tPick<\n\t\tCoordinatorAuthBrowserTransactionStore,\n\t\t| \"retireAuthBrowserTransactions\"\n\t\t| \"purgeAuthSigninBrowserTransactions\"\n\t\t| \"maintainAuthBrowserTransactions\"\n\t> &\n\tPick<\n\t\tCoordinatorAuthSessionStore,\n\t\t\"purgeAuthGuardedSigninSessions\" | \"purgeAuthGuardedSigninReceipts\"\n\t>;\nexport type CoordinatorBrowserAuthMaintenanceStep =\n\t| \"link_attempts\"\n\t| \"browser_retirement\"\n\t| \"browser_expiry\"\n\t| \"signin_transactions\"\n\t| \"signin_sessions\"\n\t| \"signin_receipts\"\n\t| \"account_changes\";\nexport type CoordinatorBrowserAuthMaintenanceResult =\n\t| Readonly<{ kind: \"disabled\" }>\n\t| Readonly<{\n\t\t\tkind: \"failed\";\n\t\t\terror: \"maintenance_failed\";\n\t\t\tstep: CoordinatorBrowserAuthMaintenanceStep | \"options\";\n\t }>\n\t| Readonly<{ kind: \"maintained\"; processedCount: number; more: boolean }>;\n/** Explicit operator/scheduled work only; budgets apply independently to each stage. */\nexport async function maintainCoordinatorBrowserAuth(\n\tsnapshot: CoordinatorBrowserAuthSnapshot,\n\tstore: CoordinatorBrowserAuthMaintenanceStore,\n\toptions: { maxBatches?: number } = {},\n): Promise<CoordinatorBrowserAuthMaintenanceResult> {\n\tif (snapshot.kind === \"disabled\") return maintainDisabledAccountChanges(snapshot, store);\n\tlet step: CoordinatorBrowserAuthMaintenanceStep | \"options\" = \"options\";\n\ttry {\n\t\tconst payload = enabledPayloads.get(snapshot);\n\t\tconst maxBatches = options.maxBatches ?? 4;\n\t\tif (\n\t\t\tsnapshot.kind !== \"enabled\" ||\n\t\t\t!payload ||\n\t\t\t!Number.isSafeInteger(maxBatches) ||\n\t\t\tmaxBatches < 1 ||\n\t\t\tmaxBatches > 8\n\t\t)\n\t\t\tthrow new Error();\n\t\tconst config = payload.settings.store;\n\t\tconst changes = await resolveAccountChanges(store);\n\t\tconst scope = Object.freeze({ coordinatorId: config.coordinatorId });\n\t\tconst stages = [\n\t\t\t{ step: \"link_attempts\", run: () => store.maintainAuthLinkAttempts(config, { limit: 32 }) },\n\t\t\t{\n\t\t\t\tstep: \"browser_retirement\",\n\t\t\t\trun: () => store.retireAuthBrowserTransactions(config, { limit: 32 }),\n\t\t\t},\n\t\t\t{\n\t\t\t\tstep: \"browser_expiry\",\n\t\t\t\trun: () => store.maintainAuthBrowserTransactions(scope, { limit: 32 }),\n\t\t\t},\n\t\t\t{\n\t\t\t\tstep: \"signin_transactions\",\n\t\t\t\trun: () => store.purgeAuthSigninBrowserTransactions(scope, { limit: 256 }),\n\t\t\t},\n\t\t\t{\n\t\t\t\tstep: \"signin_sessions\",\n\t\t\t\trun: () => store.purgeAuthGuardedSigninSessions(scope, { limit: 256 }),\n\t\t\t},\n\t\t\t{\n\t\t\t\tstep: \"signin_receipts\",\n\t\t\t\trun: () => store.purgeAuthGuardedSigninReceipts(scope, { limit: 256 }),\n\t\t\t},\n\t\t\t...(changes\n\t\t\t\t? [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tstep: \"account_changes\" as const,\n\t\t\t\t\t\t\trun: async () => {\n\t\t\t\t\t\t\t\tconst processedCount = await changes.maintainExpired(config.coordinatorId, 32);\n\t\t\t\t\t\t\t\treturn { kind: \"maintained\", processedCount, more: processedCount === 32 };\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t]\n\t\t\t\t: []),\n\t\t] as const;\n\t\tlet processedCount = 0;\n\t\tlet more = false;\n\t\tfor (const stage of stages) {\n\t\t\tstep = stage.step;\n\t\t\tconst result = await runMaintenanceStage(stage.run, maxBatches);\n\t\t\tprocessedCount += result.processedCount;\n\t\t\tif (!Number.isSafeInteger(processedCount)) throw new Error();\n\t\t\tmore ||= result.more;\n\t\t}\n\t\treturn Object.freeze({ kind: \"maintained\", processedCount, more });\n\t} catch {\n\t\treturn Object.freeze({ kind: \"failed\", error: \"maintenance_failed\", step });\n\t}\n}\n\n/** Disabled auth needs only a captured coordinator pin, never issuer or secret material. */\nasync function maintainDisabledAccountChanges(\n\tsnapshot: CoordinatorBrowserAuthSnapshot,\n\tstore: CoordinatorBrowserAuthMaintenanceStore,\n): Promise<CoordinatorBrowserAuthMaintenanceResult> {\n\tconst coordinatorId = disabledMaintenancePins.get(snapshot);\n\tif (!coordinatorId) return Object.freeze({ kind: \"disabled\" });\n\ttry {\n\t\tconst changes = await resolveAccountChanges(store);\n\t\tif (!changes) return Object.freeze({ kind: \"disabled\" });\n\t\tconst processedCount = await changes.maintainExpired(coordinatorId, 32);\n\t\treturn Object.freeze({ kind: \"maintained\", processedCount, more: processedCount === 32 });\n\t} catch {\n\t\treturn Object.freeze({ kind: \"failed\", error: \"maintenance_failed\", step: \"account_changes\" });\n\t}\n}\nasync function runMaintenanceStage(\n\trun: () => Promise<{ kind: string; processedCount?: number; more?: boolean }>,\n\tmaxBatches: number,\n): Promise<{ processedCount: number; more: boolean }> {\n\tlet processedCount = 0;\n\tfor (let batch = 0; batch < maxBatches; batch++) {\n\t\tconst result = await run();\n\t\tif (\n\t\t\tresult.kind === \"rejected\" ||\n\t\t\ttypeof result.processedCount !== \"number\" ||\n\t\t\t!Number.isSafeInteger(result.processedCount) ||\n\t\t\tresult.processedCount < 0 ||\n\t\t\ttypeof result.more !== \"boolean\"\n\t\t)\n\t\t\tthrow new Error();\n\t\tprocessedCount += result.processedCount;\n\t\tif (!Number.isSafeInteger(processedCount)) throw new Error();\n\t\tif (!result.more) return { processedCount, more: false };\n\t}\n\treturn { processedCount, more: true };\n}\n","import { connectionRequesterGuard } from \"./coordinator-account-connection-link.js\";\nimport { readConnectionSchemaState } from \"./coordinator-account-connection-schema.js\";\nimport { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport { authSchemaDefinitionCheck } from \"./coordinator-auth-device-claim-schema.js\";\nimport {\n\ttype AuthLinkBackend,\n\ttype AuthLinkStatement,\n\tauthLinkNow,\n} from \"./coordinator-auth-link.js\";\nimport type { CoordinatorAuthLinkConfig } from \"./coordinator-auth-link-contract.js\";\nimport { capture, captureAuthLinkConfig, isHash } from \"./coordinator-auth-link-input.js\";\nimport { authLinkLiveGenerationSql } from \"./coordinator-auth-link-liveness.js\";\nimport { authDeviceClaimProvenanceSql } from \"./coordinator-auth-link-provenance.js\";\nimport { ed25519KeyIdForRevocation } from \"./coordinator-ed25519-key-id-compat.js\";\nimport {\n\tCOORDINATOR_OWNER_ENROLLMENT_QUALIFICATION_SCHEMA_STATEMENTS,\n\ttype CoordinatorOwnerEnrollmentQualificationRow,\n} from \"./coordinator-owner-enrollment-qualification-schema.js\";\n\n/** Internal admin capability only. No route, store startup, grant or owner consumer uses it. */\nexport type OwnerQualificationRejected = {\n\tkind: \"rejected\";\n\terror: \"invalid_input\" | \"unavailable\" | \"preview_changed\" | \"qualification_conflict\";\n};\n/** The write may have committed. This is not a denial or proof of rollback. */\nexport type OwnerQualificationOutcomeUnknown = { kind: \"outcome_unknown\" };\nexport interface OwnerQualificationPreview {\n\tkind: \"ready\";\n\tdigest: string;\n\tattestationId: string;\n\treviewReceiptId: string;\n\tlinkId: string;\n\tclaimId: string;\n\tidentityId: string;\n\tgroupId: string;\n\tdeviceId: string;\n\tfingerprint: string;\n}\n\n// Fixed order is the canonical encoding, shared by the digest and winning SQL.\n// Include actual current enrollment separately from the review's historical label.\nconst BIRTH = {\n\tcoordinator_id: \"l.coordinator_id\",\n\tlink_id: \"l.link_id\",\n\tdevice_claim_id: \"d.claim_id\",\n\tidentity_id: \"l.identity_id\",\n\tsource_group_id: \"a.group_id\",\n\tdevice_id: \"a.device_id\",\n\tpublic_key: \"a.public_key\",\n\tfingerprint: \"a.fingerprint\",\n\tkey_id: \"d.key_id\",\n\tcontroller_attestation_id: \"a.attestation_id\",\n\tcontroller_attestation_revision: \"a.revision\",\n\tcontroller_attestation_created_at: \"a.created_at\",\n\treview_receipt_id: \"a.review_receipt_id\",\n\tevidence_digest: \"a.evidence_digest\",\n\tenrollment_identity_id: \"a.enrollment_identity_id\",\n\tlink_attempt_id: \"l.attempt_id\",\n\tlink_auth_config_revision: \"l.auth_config_revision\",\n\tlink_created_at_ms: \"l.created_at_ms\",\n} as const;\ntype Birth = Omit<\n\tCoordinatorOwnerEnrollmentQualificationRow,\n\t\"qualification_id\" | \"created_at_ms\" | \"revoked_at_ms\"\n>;\ninterface Source extends Birth {\n\tsnapshot: string;\n}\nconst SNAPSHOT = `json_array(${[\n\t...Object.values(BIRTH),\n\t\"l.issuer\",\n\t\"l.subject\",\n\t\"l.authority_kind\",\n\t\"l.controller_attestation_id\",\n\t\"l.signin_floor\",\n\t\"l.revoked_at_ms\",\n\t\"d.identity_id\",\n\t\"d.group_id\",\n\t\"d.device_id\",\n\t\"d.public_key\",\n\t\"d.fingerprint\",\n\t\"d.attempt_id\",\n\t\"d.issuer\",\n\t\"d.auth_config_revision\",\n\t\"d.created_at_ms\",\n\t\"e.identity_id\",\n\t\"e.public_key\",\n\t\"e.fingerprint\",\n\t\"e.enabled\",\n\t\"e.created_at\",\n\t\"e.display_name\",\n].join(\",\")})`;\nconst SOURCE = `FROM coordinator_auth_controller_attestations a\n JOIN enrolled_devices e ON e.group_id=a.group_id AND e.device_id=a.device_id\n JOIN groups g ON g.group_id=e.group_id\n JOIN coordinator_auth_account_links l ON l.coordinator_id=a.coordinator_id AND l.identity_id=a.identity_id\n JOIN coordinator_auth_device_claims d ON d.coordinator_id=l.coordinator_id AND d.claim_id=l.device_claim_id\n WHERE (a.coordinator_id=? AND a.attestation_id=? AND l.issuer=?)\n AND (a.revoked_at IS NULL AND a.revision=1 AND length(a.review_receipt_id)>0 AND length(a.evidence_digest)=64)\n AND (e.public_key=a.public_key AND e.fingerprint=a.fingerprint AND e.enabled=1 AND g.archived_at IS NULL)\n AND (e.identity_id IS NULL OR e.identity_id=a.identity_id)\n AND e.identity_id IS a.enrollment_identity_id\n AND (a.enrollment_identity_id IS NULL OR a.enrollment_identity_id=a.identity_id)\n AND (d.identity_id=a.identity_id AND d.group_id=a.group_id AND d.device_id=a.device_id\n AND d.public_key=a.public_key AND d.fingerprint=a.fingerprint)\n AND (${authLinkLiveGenerationSql({ link: \"l\", connections: true })})\n AND (${authDeviceClaimProvenanceSql({ link: \"l\", connections: true })})`;\nconst SOURCE_COLUMNS = Object.entries(BIRTH)\n\t.map(([name, expression]) => `${expression} AS ${name}`)\n\t.join(\",\");\nconst QUALIFICATION_READY = COORDINATOR_OWNER_ENROLLMENT_QUALIFICATION_SCHEMA_STATEMENTS.map(\n\t(sql, index) =>\n\t\tauthSchemaDefinitionCheck(\n\t\t\tsql.replace(/^(?:\\s|--[^\\n]*\\n)*/u, \"\").replace(/;\\s*$/u, \"\"),\n\t\t\tindex === 0 ? { auxiliaryObjects: 5 } : undefined,\n\t\t).matches,\n).join(\" AND \");\n\nasync function digestSource(source: Source, config: CoordinatorAuthLinkConfig): Promise<string> {\n\tconst bytes = new TextEncoder().encode(\n\t\tJSON.stringify([\n\t\t\t\"codemem.owner-enrollment-qualification.preview.v1\",\n\t\t\tconfig.enabled,\n\t\t\tconfig.coordinatorId,\n\t\t\tconfig.issuer,\n\t\t\tconfig.revision,\n\t\t\tsource.snapshot,\n\t\t]),\n\t);\n\tconst digest = await crypto.subtle.digest(\"SHA-256\", bytes);\n\treturn Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\nfunction preview(source: Source, digest: string): OwnerQualificationPreview {\n\treturn {\n\t\tkind: \"ready\",\n\t\tdigest,\n\t\tattestationId: source.controller_attestation_id,\n\t\treviewReceiptId: source.review_receipt_id,\n\t\tlinkId: source.link_id,\n\t\tclaimId: source.device_claim_id,\n\t\tidentityId: source.identity_id,\n\t\tgroupId: source.source_group_id,\n\t\tdeviceId: source.device_id,\n\t\tfingerprint: source.fingerprint,\n\t};\n}\nconst unavailable = (): OwnerQualificationRejected => ({ kind: \"rejected\", error: \"unavailable\" });\ninterface Prepared {\n\tsource: Source;\n\tguard: AuthLinkStatement;\n\tdigest: string;\n}\n\nexport class OwnerEnrollmentQualificationOps {\n\tprivate readonly config: CoordinatorAuthLinkConfig | null;\n\tconstructor(\n\t\tprivate readonly backend: AuthLinkBackend,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t\tprivate readonly clock: () => number = Date.now,\n\t) {\n\t\t// Capture trusted configuration before the first asynchronous operation.\n\t\tthis.config = captureAuthLinkConfig(config);\n\t}\n\t/** Read-only deployment check; operations repeat it before resolving authority. */\n\tasync schemaReady(): Promise<boolean> {\n\t\tif ((await readConnectionSchemaState(this.backend)) !== \"ready\") return false;\n\t\treturn (\n\t\t\t(\n\t\t\t\tawait this.backend.first<{ ready: number }>({\n\t\t\t\t\tsql: `SELECT (${QUALIFICATION_READY}) AS ready`,\n\t\t\t\t\tvalues: [],\n\t\t\t\t})\n\t\t\t)?.ready === 1\n\t\t);\n\t}\n\tprivate async prepare(attestationId: string, now: number): Promise<Prepared | null> {\n\t\tconst c = this.config;\n\t\tif (!c?.enabled || !(await this.schemaReady())) return null;\n\t\tconst source = await this.backend.first<Source>({\n\t\t\tsql: `SELECT ${SOURCE_COLUMNS}, ${SNAPSHOT} AS snapshot ${SOURCE}`,\n\t\t\tvalues: [c.coordinatorId, attestationId, c.issuer],\n\t\t});\n\t\tif (!source || !isHash(source.evidence_digest)) return null;\n\t\tconst keyId = await ed25519KeyIdForRevocation(source.public_key);\n\t\tif (!keyId || keyId !== source.key_id) return null;\n\t\tconst guard = await connectionRequesterGuard(\n\t\t\tthis.backend,\n\t\t\tsource.identity_id,\n\t\t\t{\n\t\t\t\tgroupId: source.source_group_id,\n\t\t\t\tdeviceId: source.device_id,\n\t\t\t\tpublicKey: source.public_key,\n\t\t\t\tfingerprint: source.fingerprint,\n\t\t\t},\n\t\t\tc,\n\t\t\tnow,\n\t\t);\n\t\tconst digest = await digestSource(source, c);\n\t\tconst prepared = { source, guard, digest };\n\t\t// Key classification and hashing await; never trust the earlier SELECT alone.\n\t\tif (!(await this.live(prepared))) return null;\n\t\treturn prepared;\n\t}\n\tprivate liveStatement(p: Prepared): AuthLinkStatement {\n\t\tconst c = this.config;\n\t\tif (!c) return { sql: \"SELECT 1 WHERE 0\", values: [] };\n\t\treturn {\n\t\t\tsql: `${SOURCE} AND (${SNAPSHOT}=?) AND (${p.guard.sql})\n AND NOT EXISTS (SELECT 1 FROM coordinator_device_revocations r\n WHERE (r.subject_kind='device_id' AND r.subject_value=a.device_id)\n OR (r.subject_kind='ed25519_key' AND r.subject_value=d.key_id))`,\n\t\t\tvalues: [\n\t\t\t\tc.coordinatorId,\n\t\t\t\tp.source.controller_attestation_id,\n\t\t\t\tc.issuer,\n\t\t\t\tp.source.snapshot,\n\t\t\t\t...p.guard.values,\n\t\t\t],\n\t\t};\n\t}\n\tprivate async live(p: Prepared): Promise<boolean> {\n\t\tconst s = this.liveStatement(p);\n\t\treturn !!(await this.backend.first({ sql: `SELECT 1 ${s.sql}`, values: s.values }));\n\t}\n\tasync preview(input: {\n\t\tattestationId: string;\n\t}): Promise<OwnerQualificationPreview | OwnerQualificationRejected> {\n\t\tconst i = capture(input, [\"attestationId\"]);\n\t\tif (!isAuthControllerId(i?.attestationId)) return { kind: \"rejected\", error: \"invalid_input\" };\n\t\ttry {\n\t\t\tconst p = await this.prepare(i.attestationId, authLinkNow(this.clock));\n\t\t\tif (!p) return unavailable();\n\t\t\tconst existing = await this.existing(p);\n\t\t\tif (existing && !this.matches(existing, p.source))\n\t\t\t\treturn { kind: \"rejected\", error: \"qualification_conflict\" };\n\t\t\treturn preview(p.source, p.digest);\n\t\t} catch {\n\t\t\treturn unavailable();\n\t\t}\n\t}\n\tasync issue(input: {\n\t\tattestationId: string;\n\t\texpectedDigest: string;\n\t}): Promise<\n\t\t| { kind: \"created\" | \"existing\"; qualificationId: string }\n\t\t| OwnerQualificationRejected\n\t\t| OwnerQualificationOutcomeUnknown\n\t> {\n\t\tconst i = capture(input, [\"attestationId\", \"expectedDigest\"]);\n\t\tif (!isAuthControllerId(i?.attestationId) || !isHash(i?.expectedDigest))\n\t\t\treturn { kind: \"rejected\", error: \"invalid_input\" };\n\t\tlet writeAttempted = false;\n\t\ttry {\n\t\t\tconst now = authLinkNow(this.clock);\n\t\t\tconst p = await this.prepare(i.attestationId, now);\n\t\t\tif (!p) return unavailable();\n\t\t\tif (p.digest !== i.expectedDigest) return { kind: \"rejected\", error: \"preview_changed\" };\n\t\t\tconst qualificationId = crypto.randomUUID();\n\t\t\tconst s = this.liveStatement(p);\n\t\t\tconst statement: AuthLinkStatement = {\n\t\t\t\tsql: `INSERT INTO coordinator_owner_enrollment_qualifications\n (qualification_id,${Object.keys(BIRTH).join(\",\")},created_at_ms,revoked_at_ms)\n SELECT ?,${Object.values(BIRTH).join(\",\")},?,NULL ${s.sql}\n AND l.created_at_ms<=? AND NOT EXISTS (SELECT 1 FROM coordinator_owner_enrollment_qualifications q\n WHERE q.coordinator_id=l.coordinator_id AND q.link_id=l.link_id)`,\n\t\t\t\tvalues: [qualificationId, now, ...s.values, now],\n\t\t\t};\n\t\t\t// A backend can commit and then lose the response. Never infer rollback.\n\t\t\twriteAttempted = true;\n\t\t\tconst changes = await this.backend.run(statement);\n\t\t\tif (changes === 1) return { kind: \"created\", qualificationId };\n\t\t\treturn await this.retry(p);\n\t\t} catch {\n\t\t\tif (writeAttempted) return { kind: \"outcome_unknown\" };\n\t\t\treturn unavailable();\n\t\t}\n\t}\n\tprivate existing(p: Prepared): Promise<CoordinatorOwnerEnrollmentQualificationRow | null> {\n\t\treturn this.backend.first({\n\t\t\tsql: \"SELECT * FROM coordinator_owner_enrollment_qualifications WHERE coordinator_id=? AND link_id=?\",\n\t\t\tvalues: [p.source.coordinator_id, p.source.link_id],\n\t\t});\n\t}\n\t/** Revoke only a fixed server-resolved record/link pair; never require the old device to live. */\n\tasync revoke(input: {\n\t\tqualificationId: string;\n\t\tlinkId: string;\n\t}): Promise<\n\t\t| { kind: \"revoked\"; qualificationId: string }\n\t\t| OwnerQualificationRejected\n\t\t| OwnerQualificationOutcomeUnknown\n\t> {\n\t\tconst i = capture(input, [\"qualificationId\", \"linkId\"]);\n\t\tif (!isAuthControllerId(i?.qualificationId) || !isAuthControllerId(i?.linkId))\n\t\t\treturn { kind: \"rejected\", error: \"invalid_input\" };\n\t\tlet writeAttempted = false;\n\t\ttry {\n\t\t\tconst c = this.config;\n\t\t\tconst now = authLinkNow(this.clock);\n\t\t\tif (!c?.enabled || !(await this.schemaReady())) return unavailable();\n\t\t\tconst values = [c.coordinatorId, i.qualificationId, i.linkId];\n\t\t\tconst statement: AuthLinkStatement = {\n\t\t\t\t// Clock rollback must not delay revocation or rewrite an earlier receipt.\n\t\t\t\tsql: `UPDATE coordinator_owner_enrollment_qualifications SET revoked_at_ms=MAX(?,created_at_ms)\n WHERE coordinator_id=? AND qualification_id=? AND link_id=? AND revoked_at_ms IS NULL`,\n\t\t\t\tvalues: [now, ...values],\n\t\t\t};\n\t\t\twriteAttempted = true;\n\t\t\tawait this.backend.run(statement);\n\t\t\tconst row = await this.backend.first<{ qualification_id: string }>({\n\t\t\t\tsql: `SELECT qualification_id FROM coordinator_owner_enrollment_qualifications\n WHERE coordinator_id=? AND qualification_id=? AND link_id=? AND revoked_at_ms IS NOT NULL`,\n\t\t\t\tvalues,\n\t\t\t});\n\t\t\treturn row ? { kind: \"revoked\", qualificationId: row.qualification_id } : unavailable();\n\t\t} catch {\n\t\t\tif (writeAttempted) return { kind: \"outcome_unknown\" };\n\t\t\treturn unavailable();\n\t\t}\n\t}\n\tprivate matches(row: CoordinatorOwnerEnrollmentQualificationRow, source: Source): boolean {\n\t\treturn (\n\t\t\trow.revoked_at_ms === null &&\n\t\t\tObject.keys(BIRTH).every((key) => {\n\t\t\t\tconst field = key as keyof Birth;\n\t\t\t\treturn row[field] === source[field];\n\t\t\t})\n\t\t);\n\t}\n\tprivate async retry(\n\t\tp: Prepared,\n\t): Promise<{ kind: \"existing\"; qualificationId: string } | OwnerQualificationRejected> {\n\t\t// Keep one atomic snapshot, but isolate full provenance from birth matching:\n\t\t// native D1 counts both trees toward its depth limit when nested together.\n\t\tconst s = this.liveStatement(p);\n\t\tconst row = await this.backend.first<CoordinatorOwnerEnrollmentQualificationRow>({\n\t\t\tsql: `WITH qualification_live_source AS MATERIALIZED (\n SELECT ${SOURCE_COLUMNS} ${s.sql})\n SELECT q.* FROM coordinator_owner_enrollment_qualifications q\n JOIN qualification_live_source source ON ${Object.keys(BIRTH)\n\t\t.map((key) => `q.${key} IS source.${key}`)\n\t\t.join(\" AND \")}\n WHERE q.revoked_at_ms IS NULL`,\n\t\t\tvalues: s.values,\n\t\t});\n\t\treturn row\n\t\t\t? { kind: \"existing\", qualificationId: row.qualification_id }\n\t\t\t: { kind: \"rejected\", error: \"qualification_conflict\" };\n\t}\n}\n","import type { Context } from \"hono\";\nimport type { CoordinatorControllerReviewDeps } from \"./coordinator-auth-controller-review-route.js\";\nimport { authSchemaDefinitionCheck } from \"./coordinator-auth-device-claim-schema.js\";\nimport type { AuthLinkBackend } from \"./coordinator-auth-link.js\";\nimport type { CoordinatorAuthLinkConfig } from \"./coordinator-auth-link-contract.js\";\nimport { captureAuthLinkConfig, isHash } from \"./coordinator-auth-link-input.js\";\nimport { isCoordinatorControllerAttestationReference } from \"./coordinator-identity-group-grant-client.js\";\nimport { OwnerEnrollmentQualificationOps } from \"./coordinator-owner-enrollment-qualification.js\";\nimport { COORDINATOR_OWNER_ENROLLMENT_SCHEMA_SQL } from \"./coordinator-owner-enrollment-schema.js\";\n\nexport interface OwnerQualificationRouteDeps\n\textends Pick<\n\t\tCoordinatorControllerReviewDeps,\n\t\t\"adminSecret\" | \"readRequestBytes\" | \"parseJsonObject\" | \"rateLimitedResponse\"\n\t> {\n\tconfig: CoordinatorAuthLinkConfig | null;\n\t/** Must be the backend of the selected runtime store, never a separate database. */\n\tbackend: AuthLinkBackend | null;\n}\n\n// These are frozen repository DDL statements, not caller-supplied SQL. Check the\n// complete 0036 table, indexes and triggers without applying or rebuilding them.\n// ALTER TABLE ... RENAME in 0036 quotes this one table identifier. Normalize\n// only that exact leading header, never quotes within CHECK/string literals.\nconst RENAMED_TABLE_HEADER = 'CREATE TABLE \"coordinator_owner_enrollment_attempts\"';\nconst ATTEMPT_TABLE_SQL = `CASE WHEN substr(sql, 1, ${RENAMED_TABLE_HEADER.length}) = '${RENAMED_TABLE_HEADER}'\n THEN 'CREATE TABLE coordinator_owner_enrollment_attempts' || substr(sql, ${RENAMED_TABLE_HEADER.length + 1}) ELSE sql END`;\nexport const ownerQualificationAttemptDefinitionChecks =\n\tCOORDINATOR_OWNER_ENROLLMENT_SCHEMA_SQL.replace(/^--[^\\n]*$/gm, \"\")\n\t\t.trim()\n\t\t.split(/\\n(?=CREATE )/u)\n\t\t.map((sql, index) => {\n\t\t\tconst check = authSchemaDefinitionCheck(\n\t\t\t\tsql.trim().replace(/;$/u, \"\"),\n\t\t\t\tindex === 0 ? { auxiliaryObjects: 13 } : undefined,\n\t\t\t);\n\t\t\tif (index !== 0) return check;\n\t\t\t// The generated predicate references sqlite_master.sql once. Preserve its\n\t\t\t// full-definition comparison and exact auxiliary-object count.\n\t\t\treturn { ...check, matches: check.matches.replace(/\\bsql\\b/u, ATTEMPT_TABLE_SQL) };\n\t\t});\nconst ATTEMPT_READY = ownerQualificationAttemptDefinitionChecks\n\t.map((check) => check.matches)\n\t.join(\" AND \");\n\nasync function authenticate(provided: string | undefined, configured: string | null) {\n\tif (!provided || !configured || provided.length > 8192) return false;\n\tconst digest = (value: string) =>\n\t\tcrypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(value));\n\tconst [expected, actual] = await Promise.all([digest(configured), digest(provided)]);\n\tconst key = await crypto.subtle.importKey(\n\t\t\"raw\",\n\t\texpected,\n\t\t{ name: \"HMAC\", hash: \"SHA-256\" },\n\t\tfalse,\n\t\t[\"sign\", \"verify\"],\n\t);\n\tconst signature = await crypto.subtle.sign(\"HMAC\", key, expected);\n\treturn crypto.subtle.verify(\"HMAC\", key, signature, actual);\n}\n\nfunction parseInput(data: Record<string, unknown> | null) {\n\tif (\n\t\t!data ||\n\t\tObject.keys(data).some((key) => ![\"attestation_id\", \"confirm_evidence_digest\"].includes(key))\n\t)\n\t\treturn null;\n\tif (!isCoordinatorControllerAttestationReference(data.attestation_id)) return null;\n\tif (Object.hasOwn(data, \"confirm_evidence_digest\") && !isHash(data.confirm_evidence_digest))\n\t\treturn null;\n\treturn {\n\t\tattestationId: data.attestation_id,\n\t\texpectedDigest: data.confirm_evidence_digest as string | undefined,\n\t};\n}\n\nasync function authorize(c: Context, deps: OwnerQualificationRouteDeps): Promise<Response | null> {\n\tconst authenticated = await authenticate(\n\t\tc.req.header(\"X-Codemem-Coordinator-Admin\"),\n\t\tdeps.adminSecret(),\n\t);\n\tconst limited = deps.rateLimitedResponse(\n\t\tc,\n\t\t`owner-qualification:${authenticated ? \"admin\" : \"anonymous\"}`,\n\t\t{ authenticated },\n\t);\n\tif (limited) return limited;\n\tif (!authenticated) return c.json({ error: \"unauthorized\" }, 401);\n\treturn null;\n}\n\nasync function rejectedResponse(c: Context, ops: OwnerEnrollmentQualificationOps, error: string) {\n\tif (error === \"unavailable\") {\n\t\ttry {\n\t\t\tif (!(await ops.schemaReady())) return c.json({ error: \"qualification_unavailable\" }, 503);\n\t\t} catch {\n\t\t\treturn c.json({ error: \"qualification_unavailable\" }, 503);\n\t\t}\n\t}\n\treturn c.json({ error }, 409);\n}\n\nasync function previewResponse(\n\tc: Context,\n\tops: OwnerEnrollmentQualificationOps,\n\tattestationId: string,\n\tcoordinatorId: string,\n) {\n\tconst result = await ops.preview({ attestationId });\n\tif (result.kind === \"rejected\") return rejectedResponse(c, ops, result.error);\n\treturn c.json({\n\t\tstate: \"ready\",\n\t\tcoordinator_id: coordinatorId,\n\t\tevidence_digest: result.digest,\n\t\tattestation_id: result.attestationId,\n\t\treview_receipt_id: result.reviewReceiptId,\n\t\tlink_id: result.linkId,\n\t\tclaim_id: result.claimId,\n\t\tidentity_id: result.identityId,\n\t\tgroup_id: result.groupId,\n\t\tdevice_id: result.deviceId,\n\t\tfingerprint: result.fingerprint,\n\t});\n}\n\nasync function issueResponse(\n\tc: Context,\n\tops: OwnerEnrollmentQualificationOps,\n\tinput: { attestationId: string; expectedDigest: string },\n\tcoordinatorId: string,\n) {\n\ttry {\n\t\tconst result = await ops.issue(input);\n\t\tif (result.kind === \"outcome_unknown\")\n\t\t\treturn c.json({ error: \"qualification_outcome_unknown\" }, 503);\n\t\tif (result.kind === \"rejected\") return await rejectedResponse(c, ops, result.error);\n\t\treturn c.json(\n\t\t\t{\n\t\t\t\tstate: result.kind,\n\t\t\t\tqualification_id: result.qualificationId,\n\t\t\t\tattestation_id: input.attestationId,\n\t\t\t\tcoordinator_id: coordinatorId,\n\t\t\t\tevidence_digest: input.expectedDigest,\n\t\t\t},\n\t\t\tresult.kind === \"created\" ? 201 : 200,\n\t\t);\n\t} catch {\n\t\treturn c.json({ error: \"qualification_outcome_unknown\" }, 503);\n\t}\n}\n\nasync function qualificationSchemasReady(\n\tbackend: AuthLinkBackend,\n\tops: OwnerEnrollmentQualificationOps,\n): Promise<boolean> {\n\tconst ready = await backend.first<{ ready: number }>({\n\t\tsql: `SELECT (${ATTEMPT_READY}) AS ready`,\n\t\tvalues: [],\n\t});\n\treturn ready?.ready === 1 && (await ops.schemaReady());\n}\n\n/** Explicit operator operation using only the selected runtime backend. */\nexport function createOwnerQualificationHandler(\n\tdeps: OwnerQualificationRouteDeps,\n): (c: Context) => Promise<Response> {\n\tconst config = captureAuthLinkConfig(deps.config);\n\tconst captured = { ...deps };\n\tconst backend = captured.backend;\n\tconst ops = config && backend ? new OwnerEnrollmentQualificationOps(backend, config) : null;\n\treturn async (c) => {\n\t\tc.header(\"Cache-Control\", \"no-store\");\n\t\tc.header(\"Referrer-Policy\", \"no-referrer\");\n\t\tc.header(\"X-Content-Type-Options\", \"nosniff\");\n\t\ttry {\n\t\t\tconst denied = await authorize(c, captured);\n\t\t\tif (denied) return denied;\n\t\t\tif (!config?.enabled || !ops || !backend)\n\t\t\t\treturn c.json({ error: \"qualification_unavailable\" }, 503);\n\t\t\tconst raw = await captured.readRequestBytes(c, 4096);\n\t\t\tif (!raw) return c.json({ error: \"body_too_large\" }, 413);\n\t\t\tconst input = parseInput(captured.parseJsonObject(raw));\n\t\t\tif (!input) return c.json({ error: \"qualification_invalid_input\" }, 400);\n\t\t\tif (!(await qualificationSchemasReady(backend, ops)))\n\t\t\t\treturn c.json({ error: \"qualification_unavailable\" }, 503);\n\t\t\tif (input.expectedDigest === undefined)\n\t\t\t\treturn await previewResponse(c, ops, input.attestationId, config.coordinatorId);\n\t\t\treturn await issueResponse(\n\t\t\t\tc,\n\t\t\t\tops,\n\t\t\t\t{ attestationId: input.attestationId, expectedDigest: input.expectedDigest },\n\t\t\t\tconfig.coordinatorId,\n\t\t\t);\n\t\t} catch {\n\t\t\treturn c.json({ error: \"qualification_unavailable\" }, 503);\n\t\t}\n\t};\n}\n","import { type Context, Hono } from \"hono\";\nimport {\n\tcreateOwnerQualificationHandler,\n\ttype OwnerQualificationRouteDeps,\n} from \"./coordinator-owner-qualification-route.js\";\nimport type { InMemoryRequestRateLimiter } from \"./request-rate-limit.js\";\n\nexport const OWNER_QUALIFICATION_PATH = \"/v1/admin/owner-qualifications\";\nconst BODY_DEADLINE_MS = 5000;\n\nfunction transportError(c: Context, origin: string | null): Response | null {\n\tconst request = c.req.raw;\n\tconst url = new URL(request.url);\n\tif (request.method !== \"POST\") return c.json({ error: \"method_not_allowed\" }, 405);\n\tif (\n\t\turl.origin !== origin ||\n\t\turl.protocol !== \"https:\" ||\n\t\turl.search ||\n\t\turl.hash ||\n\t\turl.username ||\n\t\turl.password ||\n\t\trequest.headers.has(\"Origin\")\n\t)\n\t\treturn c.json({ error: \"qualification_invalid_input\" }, 400);\n\tif (request.headers.has(\"Transfer-Encoding\"))\n\t\treturn c.json({ error: \"qualification_invalid_input\" }, 400);\n\tif (\n\t\t!/^application\\/json(?:\\s*;\\s*charset=utf-8)?$/i.test(\n\t\t\trequest.headers.get(\"Content-Type\") ?? \"\",\n\t\t) ||\n\t\trequest.headers.has(\"Content-Encoding\")\n\t)\n\t\treturn c.json({ error: \"invalid_content_type\" }, 415);\n\tconst length = request.headers.get(\"Content-Length\");\n\tif (length !== null && !/^[0-9]{1,10}$/.test(length))\n\t\treturn c.json({ error: \"qualification_invalid_input\" }, 400);\n\tif (length !== null && Number(length) > 4096) return c.json({ error: \"body_too_large\" }, 413);\n\treturn null;\n}\n\n/** One fixed buffer, one deadline, and cancellation that never holds up refusal. */\nasync function readBody(c: Context, maxBytes: number): Promise<Uint8Array | null> {\n\tconst request = c.req.raw;\n\tif (request.signal.aborted || !request.body) return null;\n\tconst reader = request.body.getReader();\n\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\tlet stop = () => {};\n\tconst interrupted = new Promise<null>((resolve) => {\n\t\tstop = () => resolve(null);\n\t\ttimer = setTimeout(stop, BODY_DEADLINE_MS);\n\t\trequest.signal.addEventListener(\"abort\", stop, { once: true });\n\t\tif (request.signal.aborted) stop();\n\t});\n\ttry {\n\t\treturn await readChunks(request, reader, interrupted, maxBytes);\n\t} catch {\n\t\treturn null;\n\t} finally {\n\t\tclearTimeout(timer);\n\t\trequest.signal.removeEventListener(\"abort\", stop);\n\t\tvoid reader.cancel().catch(() => undefined);\n\t\treader.releaseLock();\n\t}\n}\n\nasync function readChunks(\n\trequest: Request,\n\treader: ReadableStreamDefaultReader<Uint8Array>,\n\tinterrupted: Promise<null>,\n\tmaxBytes: number,\n): Promise<Uint8Array | null> {\n\tconst bytes = new Uint8Array(maxBytes);\n\tlet size = 0;\n\tfor (;;) {\n\t\tconst next = await Promise.race([reader.read(), interrupted]);\n\t\tif (!next || request.signal.aborted) return null;\n\t\tif (next.done) {\n\t\t\tconst declared = request.headers.get(\"Content-Length\");\n\t\t\tif (declared !== null && Number(declared) !== size) return null;\n\t\t\treturn bytes.subarray(0, size);\n\t\t}\n\t\tif (!(next.value instanceof Uint8Array) || next.value.byteLength > maxBytes - size) return null;\n\t\tbytes.set(next.value, size);\n\t\tsize += next.value.byteLength;\n\t}\n}\n\nfunction parseJsonObject(bytes: Uint8Array): Record<string, unknown> | null {\n\ttry {\n\t\tconst value: unknown = JSON.parse(new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes));\n\t\treturn value && typeof value === \"object\" && !Array.isArray(value)\n\t\t\t? (value as Record<string, unknown>)\n\t\t\t: null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/** Private HTTP composition only: no sessions, provider discovery, or store startup. */\nexport function createOwnerQualificationHttp(options: {\n\tconfig: OwnerQualificationRouteDeps[\"config\"];\n\tbackend: OwnerQualificationRouteDeps[\"backend\"];\n\tadminSecret: string | null;\n\torigin: string | null;\n\tlimiter: InMemoryRequestRateLimiter;\n}) {\n\tconst captured = { ...options };\n\tconst handler = createOwnerQualificationHandler({\n\t\tconfig: captured.config,\n\t\tbackend: captured.backend,\n\t\tadminSecret: () => captured.adminSecret,\n\t\treadRequestBytes: readBody,\n\t\tparseJsonObject,\n\t\trateLimitedResponse: (c, key, { authenticated }) => {\n\t\t\tconst budget = captured.limiter.check(key, authenticated ? 20 : 60);\n\t\t\tif (!budget.allowed) {\n\t\t\t\tc.header(\"Retry-After\", String(budget.retryAfterS));\n\t\t\t\treturn c.json({ error: \"rate_limited\" }, 429);\n\t\t\t}\n\t\t\tif (!authenticated || !captured.config || !captured.backend) return null;\n\t\t\treturn transportError(c, captured.origin);\n\t\t},\n\t});\n\tconst app = new Hono();\n\tapp.all(OWNER_QUALIFICATION_PATH, handler);\n\treturn { fetch: (request: Request) => app.fetch(request) };\n}\n","import { AccountChangeOperations } from \"./coordinator-account-change.js\";\nimport {\n\ttype ConnectionSchemaState,\n\treadConnectionSchemaState,\n} from \"./coordinator-account-connection-schema.js\";\nimport { AccountLinkStatusOperations } from \"./coordinator-account-link-status.js\";\nimport { AccountOwnerTargetOperations } from \"./coordinator-account-owner-target.js\";\nimport {\n\tAuthAccountProfileOperations,\n\ttype CoordinatorAuthAccountProfileInput,\n} from \"./coordinator-auth-account-profile.js\";\nimport {\n\ttype CoordinatorAuthBrowserConfig,\n\ttype CoordinatorAuthBrowserTransactionConsumeInput,\n\ttype CoordinatorAuthBrowserTransactionMaintenanceOptions,\n\ttype CoordinatorAuthBrowserTransactionRetirementOptions,\n\ttype CoordinatorAuthBrowserTransactionScope,\n\ttype CoordinatorAuthBrowserTransactionStartInput,\n\tCoordinatorAuthBrowserTransactions,\n\ttype CoordinatorAuthLinkBrowserTransactionResolveInput,\n\ttype CoordinatorAuthSigninBrowserTransactionCancelInput,\n} from \"./coordinator-auth-browser-transaction.js\";\nimport {\n\tAUTH_CONTROLLER_ACTIVE_SQL,\n\tAUTH_CONTROLLER_CONFLICT_SQL,\n\tAUTH_CONTROLLER_CURRENT_ENROLLMENT_SQL,\n\tAUTH_CONTROLLER_ENROLLMENT_SQL,\n\tAUTH_CONTROLLER_INSERT_SQL,\n\tAUTH_CONTROLLER_RETRY_ACTIVE_SQL,\n\tAUTH_CONTROLLER_RETRY_ELIGIBLE_SQL,\n\tAUTH_CONTROLLER_REVOKE_SQL,\n\tauthControllerAuthorityValues,\n\tauthControllerConflictValues,\n\tauthControllerInsertValues,\n\tauthControllerRetryActiveValues,\n\tauthControllerRetryEligibleValues,\n\tauthControllerRetryResult,\n\tauthControllerReviewSql,\n\tauthControllerSubjectOwnerConflictValues,\n\tauthControllerUnavailableResult,\n\ttype CoordinatorAuthControllerAttestation,\n\ttype CoordinatorAuthControllerCreateResult,\n\ttype CoordinatorAuthControllerReviewInput,\n\ttype CoordinatorAuthControllerSubjectOwnerInput,\n\tcaptureAuthControllerReview,\n\tisAuthControllerId,\n\tisAuthControllerUniqueError,\n} from \"./coordinator-auth-controller.js\";\nimport {\n\ttype ControllerHistoryInput,\n\tcaptureControllerHistory,\n} from \"./coordinator-auth-controller-history.js\";\nimport { AUTH_CONTROLLER_SUBJECT_OWNER_CONFLICT_SQL } from \"./coordinator-auth-controller-owner.js\";\nimport {\n\ttype AuthLinkBackend,\n\tAuthLinkOperations,\n\ttype AuthLinkStatement,\n} from \"./coordinator-auth-link.js\";\nimport type {\n\tCoordinatorAuthLinkClaimInput,\n\tCoordinatorAuthLinkConfig,\n\tCoordinatorAuthLinkConfirmInput,\n\tCoordinatorAuthLinkCreateInput,\n\tCoordinatorAuthLinkFailInput,\n\tCoordinatorAuthLinkFinalizeInput,\n\tCoordinatorAuthLinkMaintenanceOptions,\n\tCoordinatorAuthLinkOidcInput,\n\tCoordinatorAuthLinkOptions,\n\tCoordinatorAuthLinkRequester,\n} from \"./coordinator-auth-link-contract.js\";\nimport {\n\tassertCoordinatorAuthSchema,\n\tCoordinatorAuthSchemaUpgradeRequiredError,\n\twithCoordinatorAuthSchema,\n} from \"./coordinator-auth-schema.js\";\nimport { AuthSessionOperations } from \"./coordinator-auth-session.js\";\nimport type {\n\tCoordinatorAuthAccountSignInInput,\n\tCoordinatorAuthBoundLinkSessionRedeemInput,\n\tCoordinatorAuthLinkSessionRedeemInput,\n\tCoordinatorAuthSessionPurgeOptions,\n\tCoordinatorAuthSessionScope,\n} from \"./coordinator-auth-session-contract.js\";\nimport {\n\tBOOTSTRAP_AUTHORIZATION_SOURCE_SQL,\n\ttype BootstrapAuthorizationRow,\n\tbootstrapAuthorizationDecision,\n\tbootstrapAuthorizationResult,\n\tbootstrapAuthorizationSourceError,\n\tcaptureBootstrapAuthorizationInput,\n\trejectBootstrapAuthorization,\n} from \"./coordinator-bootstrap-grant-authorization.js\";\nimport {\n\tBOOTSTRAP_PARTICIPANT_SOURCE_SQL,\n\tBOOTSTRAP_PARTICIPANTS_REVOKED_SQL,\n\tBOOTSTRAP_RAW_INSERT_SQL,\n\ttype BootstrapParticipantSource,\n\tbootstrapRawInsertValues,\n\tcaptureBootstrapParticipantSource,\n} from \"./coordinator-bootstrap-grant-issuance.js\";\nimport { readDeviceRebindBackend } from \"./coordinator-device-rebind-schema.js\";\nimport {\n\ttype CoordinatorCreateDeviceRevocationInput,\n\ttype CoordinatorListDeviceRevocationsInput,\n\ttype CoordinatorRecordAuthorizedNonceInput,\n\tDEVICE_REVOCATION_SUBJECT_EXISTS_SQL,\n\tDeviceRevocationOperations,\n} from \"./coordinator-device-revocation.js\";\nimport { ed25519KeyIdForRevocation } from \"./coordinator-ed25519-key-id-compat.js\";\nimport {\n\tENROLLMENT_OWNERSHIP_COLUMNS,\n\twithEnrollmentOwnership,\n} from \"./coordinator-enrollment-ownership.js\";\nimport {\n\ttype CoordinatorIdentityGroupGrant,\n\ttype CoordinatorIdentityGroupGrantIssueInput,\n\ttype CoordinatorIdentityGroupGrantIssueResult,\n\ttype CoordinatorIdentityGroupGrantRevokeInput,\n\ttype CoordinatorIdentityGroupGrantScope,\n\tcaptureIdentityGroupGrantInput,\n\tIDENTITY_GROUP_GRANT_INSERT_SQL,\n\tIDENTITY_GROUP_GRANT_LIST_SQL,\n\tIDENTITY_GROUP_GRANT_RETRY_SQL,\n\tIDENTITY_GROUP_GRANT_REVOKE_SQL,\n\tIDENTITY_GROUP_GRANT_SOURCE_SQL,\n} from \"./coordinator-identity-group-grant.js\";\nimport {\n\tassertJoinReviewConfirmation,\n\tJOIN_REVIEW_COLUMNS,\n\tjoinReviewGuardEvidence,\n\tjoinReviewResultChanges,\n} from \"./coordinator-join-review-guards.js\";\nimport {\n\tcaptureLegacyCompletionOwnerProof,\n\tlegacyCompletionOwnerProofSql,\n} from \"./coordinator-legacy-completion-owner-proof.js\";\nimport {\n\tassertLegacyDeviceScope,\n\tcaptureLegacyEnrollment,\n\tcaptureLegacyEnrollmentPublicKey,\n\tcaptureLegacyProjectInviteInput,\n\tDEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL,\n\tLEGACY_DEVICE_DENIAL_SQL,\n\tLEGACY_ENROLLMENT_DENIAL_SQL,\n\tLEGACY_ENROLLMENT_WRITE_SQL,\n\tlegacyDeviceAuthorizationFailure,\n\tlegacyDeviceDenial,\n\tlegacyDeviceWriteChanges,\n\tlegacyProjectInviteOwnershipEvidence,\n} from \"./coordinator-legacy-device-ownership.js\";\nimport {\n\tLEGACY_OWNER_INPUT_SQL,\n\tLEGACY_OWNER_KEYS_SQL,\n\tLEGACY_OWNER_SOURCE_CURRENT_SQL,\n\tlegacyCompletionWriteResult,\n\tlegacyOwnerKeyMetadata,\n} from \"./coordinator-legacy-owner-compatibility.js\";\nimport type {\n\tCoordinatorLegacyTeamCompletionManifestV1,\n\tCoordinatorLegacyTeamCompletionRecord,\n\tCoordinatorLegacyTeamCompletionScopeBinding,\n\tCoordinatorLegacyTeamCompletionWriteResult,\n} from \"./coordinator-legacy-team-completion.js\";\nimport {\n\tCOORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BATCH_BYTES,\n\tCOORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES,\n\tCOORDINATOR_LEGACY_TEAM_COMPLETION_MAX_RECORDS,\n\tCoordinatorLegacyTeamCompletionConflictError,\n\tcanonicalCoordinatorLegacyTeamCompletionManifestJson,\n\tnormalizeCoordinatorLegacyTeamCompletionCandidateRef,\n\tnormalizeCoordinatorLegacyTeamCompletionGroupIds,\n\tnormalizeCoordinatorLegacyTeamCompletionManifest,\n\trequireCoordinatorLegacyTeamCompletionScopeBindings,\n\trequireCoordinatorLegacyTeamCompletionTeamBinding,\n} from \"./coordinator-legacy-team-completion.js\";\nimport {\n\tassertMatchingMembershipEffectReceipt,\n\ttype CoordinatorMembershipEffectReceipt,\n\tCoordinatorMembershipError,\n\tgrantMembershipEffectRequestJson,\n\tmembershipFromEffectReceipt,\n\tnormalizeMembershipEffectId,\n\trevokeMembershipEffectRequestJson,\n} from \"./coordinator-membership-effects.js\";\nimport {\n\ttype NegativeOwnerConsistency,\n\tprepareNegativeOwnerConsistency,\n\twithNegativeOwnerConsistency,\n} from \"./coordinator-owner-negative-consistency.js\";\nimport { OwnerResolutionReviewOperations } from \"./coordinator-owner-resolution-review.js\";\nimport {\n\tCAPTURE_PEER_ENROLLMENTS_SQL,\n\ttype CapturedPeerEnrollment,\n\tcapturePeerEnrollments,\n\tREAD_CURRENT_PEERS_SQL,\n\trequirePeerDiscoveryRows,\n} from \"./coordinator-peer-discovery.js\";\nimport { projectInviteGuardEvidence } from \"./coordinator-project-invite-guards.js\";\nimport {\n\tassertRecipientOwnerConsistency,\n\tprepareRecipientOwnerConsistency,\n\trecipientOwnerWriteSql,\n\tvalidateRecipientOwnerInput,\n} from \"./coordinator-recipient-owner-consistency.js\";\nimport { ResolvedAccountOwnerStatusOperations } from \"./coordinator-resolved-account-owner-status.js\";\nimport {\n\ttype CapturedScopeMember,\n\tcaptureScopeAuthorizationInput,\n\tENROLLMENT_FIELDS,\n\tisCurrentScopeMember,\n\tMEMBERSHIP_FIELDS,\n\tparseScopeAuthorizationMembers,\n\tREAD_SCOPE_AUTHORIZATION_SQL,\n\trequireScopeAuthorizationRecord,\n\tSCOPE_FIELDS,\n\tscopeAuthorizationError,\n} from \"./coordinator-scope-authorization.js\";\nimport type {\n\tCoordinatorBootstrapGrant,\n\tCoordinatorBootstrapGrantAuthorizationInput,\n\tCoordinatorBootstrapGrantAuthorizationResult,\n\tCoordinatorConsumeProjectInviteInput,\n\tCoordinatorConsumeRecipientInviteInput,\n\tCoordinatorCreateBootstrapGrantInput,\n\tCoordinatorCreateInviteInput,\n\tCoordinatorCreateJoinRequestInput,\n\tCoordinatorCreateReciprocalApprovalInput,\n\tCoordinatorCreateScopeInput,\n\tCoordinatorEnrollDeviceInput,\n\tCoordinatorEnrollment,\n\tCoordinatorGrantScopeMembershipInput,\n\tCoordinatorGroup,\n\tCoordinatorInspectRecipientInviteInput,\n\tCoordinatorInvite,\n\tCoordinatorJoinRequest,\n\tCoordinatorJoinRequestReviewResult,\n\tCoordinatorListReciprocalApprovalsInput,\n\tCoordinatorListScopeMembershipAuditInput,\n\tCoordinatorListScopesInput,\n\tCoordinatorPeerRecord,\n\tCoordinatorPresenceRecord,\n\tCoordinatorProjectInviteAcceptance,\n\tCoordinatorRecipientInviteAcceptance,\n\tCoordinatorRecipientInviteInspection,\n\tCoordinatorReciprocalApproval,\n\tCoordinatorReviewJoinRequestInput,\n\tCoordinatorRevokeScopeMembershipInput,\n\tCoordinatorScope,\n\tCoordinatorScopeAuthorizationInput,\n\tCoordinatorScopeAuthorizationResult,\n\tCoordinatorScopeMembership,\n\tCoordinatorScopeMembershipAuditEvent,\n\tCoordinatorStore,\n\tCoordinatorUpdateScopeInput,\n\tCoordinatorUpsertPresenceInput,\n} from \"./coordinator-store-contract.js\";\nimport {\n\tCoordinatorReciprocalApprovalRequestChangedError,\n\tnormalizeInviteExpiresAt,\n\trecipientInviteAuthoritativeIdentityId,\n} from \"./coordinator-store-contract.js\";\nimport {\n\tclean,\n\tinspectCoordinatorRecipientInvite as inspectInvite,\n\tmergeCoordinatorAddresses,\n\tnormalizeCoordinatorAuditLimit,\n\tnormalizeCoordinatorBootstrapGrantInput,\n\tnormalizeCoordinatorBootstrapGrantRequest,\n\tnormalizeCoordinatorCreateScopeInput,\n\tnormalizeCoordinatorGrantScopeMembershipInput,\n\tnormalizeCoordinatorInviteMetadata,\n\tnormalizeCoordinatorUpdateScopeInput,\n\tnormalizeEpoch,\n} from \"./coordinator-store-input-rules.js\";\nimport { fingerprintPublicKey } from \"./sync-fingerprint.js\";\n\ninterface D1RunResultLike {\n\tmeta?: {\n\t\tchanges?: number;\n\t};\n}\n\n/**\n * Experimental D1 adapter scaffold.\n *\n * This is intentionally internal for now while the sync-only store contract\n * is still being validated against an async backend shape.\n */\n\nexport interface D1PreparedStatementLike {\n\tbind(...values: unknown[]): D1PreparedStatementLike;\n\tfirst<T = unknown>(): Promise<T | null>;\n\trun(): Promise<unknown>;\n\tall<T = unknown>(): Promise<{ results?: T[] }>;\n\traw<T = unknown>(): Promise<T[]>;\n}\n\nexport interface D1DatabaseLike {\n\tprepare(query: string): D1PreparedStatementLike;\n\tbatch?(statements: D1PreparedStatementLike[]): Promise<unknown[]>;\n\texec?(query: string): Promise<unknown>;\n}\n\nfunction rowToRecord<T>(row: unknown): T {\n\tif (row == null) throw new Error(\"expected row\");\n\treturn row as T;\n}\n\nfunction rowToEnrollmentWithPresence(row: unknown): CoordinatorEnrollment {\n\tconst record = rowToRecord<Record<string, unknown>>(row);\n\tconst {\n\t\tpresence_capabilities_json: capabilitiesJson,\n\t\tpresence_expires_at: expiresAt,\n\t\t...base\n\t} = record;\n\tif (typeof expiresAt !== \"string\" || typeof capabilitiesJson !== \"string\") {\n\t\treturn base as unknown as CoordinatorEnrollment;\n\t}\n\ttry {\n\t\tconst capabilities = JSON.parse(capabilitiesJson) as unknown;\n\t\tif (!capabilities || typeof capabilities !== \"object\" || Array.isArray(capabilities)) {\n\t\t\treturn base as unknown as CoordinatorEnrollment;\n\t\t}\n\t\tconst capabilityRecord = capabilities as Record<string, unknown>;\n\t\treturn {\n\t\t\t...(base as unknown as CoordinatorEnrollment),\n\t\t\tpresence_expires_at: expiresAt,\n\t\t\tpresence_capabilities: {\n\t\t\t\tsync_capability: capabilityRecord.sync_capability,\n\t\t\t\tsync_features: capabilityRecord.sync_features,\n\t\t\t},\n\t\t};\n\t} catch {\n\t\treturn base as unknown as CoordinatorEnrollment;\n\t}\n}\n\nfunction nowISO(): string {\n\treturn new Date().toISOString();\n}\n\nfunction reciprocalPendingPair(\n\trequestingDeviceId: string,\n\trequestedDeviceId: string,\n): {\n\tlow: string;\n\thigh: string;\n} {\n\treturn requestingDeviceId <= requestedDeviceId\n\t\t? { low: requestingDeviceId, high: requestedDeviceId }\n\t\t: { low: requestedDeviceId, high: requestingDeviceId };\n}\n\nfunction isUniqueConstraintError(error: unknown): boolean {\n\treturn error instanceof Error && /unique|constraint/i.test(error.message);\n}\n\nfunction tokenUrlSafe(bytes: number): string {\n\tconst alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\";\n\tconst random = new Uint8Array(bytes);\n\tglobalThis.crypto.getRandomValues(random);\n\tconst output: string[] = [];\n\tfor (const byte of random) {\n\t\toutput.push(alphabet[byte % alphabet.length] ?? \"A\");\n\t}\n\treturn output.join(\"\");\n}\n\nasync function tokenDigest(token: string): Promise<string> {\n\tconst digest = await globalThis.crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(token));\n\treturn Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nconst INVITE_COLUMNS = `invite_id, group_id, token, policy, expires_at, created_at, created_by,\n\tteam_name_snapshot, revoked_at, operation_id, reviewed_project_set_digest, token_digest,\n\tinviter_actor_id, inviter_display_name, inviter_device_id, pending_person_id,\n\tproject_summaries_json, project_intent_json, consumed_at, bound_device_id, bound_public_key, bound_fingerprint,\n\trecipient_actor_id, recipient_display_name, recipient_device_display_name, trust_state,\n\tbootstrap_grant_id, invite_kind, policy_team_id, target_identity_id, assigned_identity_id,\n\treviewed_preview_digest, reviewed_intent_json`;\n\nconst ENROLLMENT_COLUMNS =\n\t\"group_id, device_id, public_key, fingerprint, identity_id, display_name, enabled, created_at\";\n\nconst ENROLLMENT_PRESENCE_COLUMNS = `enrolled_devices.group_id, enrolled_devices.device_id,\n\tenrolled_devices.public_key, enrolled_devices.fingerprint, enrolled_devices.identity_id,\n\tenrolled_devices.display_name, enrolled_devices.enabled, enrolled_devices.created_at,\n\tpresence_records.expires_at AS presence_expires_at,\n\tpresence_records.capabilities_json AS presence_capabilities_json`;\n\nfunction prepareMembershipAuditFromCurrentRow(\n\tdb: D1DatabaseLike,\n\tinput: {\n\t\teffectId: string;\n\t\trequestJson: string;\n\t\taction: \"grant\" | \"revoke\";\n\t\tprevious: CoordinatorScopeMembership | null;\n\t\tscopeId: string;\n\t\tdeviceId: string;\n\t\tstatus: string;\n\t\tmembershipEpoch: number;\n\t\tupdatedAt: string;\n\t\tactorType: string | null;\n\t\tactorId: string | null;\n\t\tcreatedAt: string;\n\t},\n): D1PreparedStatementLike {\n\t// The immediately preceding statement inserts the immutable effect receipt.\n\t// changes() therefore emits an audit row only for the request that won the\n\t// receipt insert, while outcome_applied excludes persisted no-op revokes.\n\treturn db\n\t\t.prepare(`INSERT INTO coordinator_scope_membership_audit_log(\n\t\t\teffect_id, action, scope_id, device_id, role, status, membership_epoch,\n\t\t\tprevious_role, previous_status, previous_membership_epoch,\n\t\t\tcoordinator_id, group_id, actor_type, actor_id, manifest_hash, created_at\n\t\t)\n\t\tSELECT receipt.effect_id, ?, membership.scope_id, membership.device_id, membership.role, membership.status,\n\t\t\tmembership.membership_epoch, ?, ?, ?, membership.coordinator_id, membership.group_id,\n\t\t\t?, ?, membership.manifest_hash, ?\n\t\tFROM (SELECT 1 WHERE changes() > 0) AS required\n\t\tJOIN coordinator_scope_membership_effect_receipts AS receipt\n\t\t\tON receipt.effect_id = ? AND receipt.action = ? AND receipt.request_json = ?\n\t\t\tAND receipt.outcome_applied = 1\n\t\tLEFT JOIN coordinator_scope_memberships AS membership\n\t\t\tON membership.scope_id = ?\n\t\t\tAND membership.device_id = ?\n\t\t\tAND membership.status = ?\n\t\t\tAND membership.membership_epoch = ?\n\t\t\tAND membership.updated_at = ?`)\n\t\t.bind(\n\t\t\tinput.action,\n\t\t\tinput.previous?.role ?? null,\n\t\t\tinput.previous?.status ?? null,\n\t\t\tinput.previous?.membership_epoch ?? null,\n\t\t\tinput.actorType,\n\t\t\tinput.actorId,\n\t\t\tinput.createdAt,\n\t\t\tinput.effectId,\n\t\t\tinput.action,\n\t\t\tinput.requestJson,\n\t\t\tinput.scopeId,\n\t\t\tinput.deviceId,\n\t\t\tinput.status,\n\t\t\tinput.membershipEpoch,\n\t\t\tinput.updatedAt,\n\t\t);\n}\n\nasync function getMembershipEffectReceipt(\n\tdb: D1DatabaseLike,\n\teffectId: string,\n): Promise<CoordinatorMembershipEffectReceipt | null> {\n\treturn await firstRow<CoordinatorMembershipEffectReceipt>(\n\t\tdb\n\t\t\t.prepare(`SELECT effect_id, action, request_json, outcome_applied, scope_id, device_id,\n\t\t\t\trole, status, membership_epoch, coordinator_id, group_id, manifest_issuer_device_id,\n\t\t\t\tmanifest_hash, signed_manifest_json, updated_at, created_at\n\t\t\t FROM coordinator_scope_membership_effect_receipts WHERE effect_id = ?`)\n\t\t\t.bind(effectId),\n\t);\n}\n\nfunction prepareGrantEffectReceipt(\n\tdb: D1DatabaseLike,\n\tinput: {\n\t\teffectId: string;\n\t\trequestJson: string;\n\t\tscopeId: string;\n\t\tdeviceId: string;\n\t\tcreatedAt: string;\n\t},\n): D1PreparedStatementLike {\n\treturn db\n\t\t.prepare(`INSERT INTO coordinator_scope_membership_effect_receipts(\n\t\t\teffect_id, action, request_json, outcome_applied, scope_id, device_id,\n\t\t\trole, status, membership_epoch, coordinator_id, group_id, manifest_issuer_device_id,\n\t\t\tmanifest_hash, signed_manifest_json, updated_at, created_at\n\t\t)\n\t\tSELECT ?, 'grant', ?, 1, membership.scope_id, membership.device_id,\n\t\t\tmembership.role, membership.status, membership.membership_epoch,\n\t\t\tmembership.coordinator_id, membership.group_id, membership.manifest_issuer_device_id,\n\t\t\tmembership.manifest_hash, membership.signed_manifest_json, membership.updated_at, ?\n\t\tFROM coordinator_scope_memberships AS membership\n\t\tWHERE changes() > 0 AND membership.scope_id = ? AND membership.device_id = ?`)\n\t\t.bind(input.effectId, input.requestJson, input.createdAt, input.scopeId, input.deviceId);\n}\n\nfunction prepareRevokeEffectReceipt(\n\tdb: D1DatabaseLike,\n\tinput: {\n\t\teffectId: string;\n\t\trequestJson: string;\n\t\tscopeId: string;\n\t\tdeviceId: string;\n\t\tcreatedAt: string;\n\t},\n): D1PreparedStatementLike {\n\treturn db\n\t\t.prepare(`INSERT INTO coordinator_scope_membership_effect_receipts(\n\t\t\teffect_id, action, request_json, outcome_applied, scope_id, device_id,\n\t\t\trole, status, membership_epoch, coordinator_id, group_id, manifest_issuer_device_id,\n\t\t\tmanifest_hash, signed_manifest_json, updated_at, created_at\n\t\t)\n\t\tSELECT ?, 'revoke', ?, changed.applied, ?, ?, membership.role, membership.status,\n\t\t\tmembership.membership_epoch, membership.coordinator_id, membership.group_id,\n\t\t\tmembership.manifest_issuer_device_id, membership.manifest_hash,\n\t\t\tmembership.signed_manifest_json, membership.updated_at, ?\n\t\tFROM (SELECT CASE WHEN changes() > 0 THEN 1 ELSE 0 END AS applied) AS changed\n\t\tLEFT JOIN coordinator_scope_memberships AS membership\n\t\t\tON changed.applied = 1 AND membership.scope_id = ? AND membership.device_id = ?\n\t\tWHERE NOT EXISTS (\n\t\t\tSELECT 1 FROM coordinator_scope_membership_effect_receipts WHERE effect_id = ?\n\t\t)`)\n\t\t.bind(\n\t\t\tinput.effectId,\n\t\t\tinput.requestJson,\n\t\t\tinput.scopeId,\n\t\t\tinput.deviceId,\n\t\t\tinput.createdAt,\n\t\t\tinput.scopeId,\n\t\t\tinput.deviceId,\n\t\t\tinput.effectId,\n\t\t);\n}\n\nasync function runAuditedBatch(\n\tdb: D1DatabaseLike,\n\tstatements: D1PreparedStatementLike[],\n): Promise<unknown[]> {\n\tif (!db.batch) {\n\t\tthrow new Error(\"D1 batch support is required for audited scope membership changes.\");\n\t}\n\treturn await db.batch(statements);\n}\n\nfunction batchResultChanges(result: unknown): number {\n\treturn Number((result as D1RunResultLike | undefined)?.meta?.changes ?? 0);\n}\n\n/** Narrow SQL capability; multi-statement writes require D1's atomic batch. */\nexport function createD1AuthLinkBackend(\n\tdb: D1DatabaseLike,\n\toptions: { connections?: boolean } = {},\n): AuthLinkBackend {\n\treturn withCoordinatorAuthSchema(createRawD1AuthLinkBackend(db), options);\n}\n\n/** No auth-schema check per statement; callers gate on their own tables. */\nfunction createRawD1AuthLinkBackend(db: D1DatabaseLike): AuthLinkBackend {\n\treturn {\n\t\tfirst: <T>(statement: AuthLinkStatement) =>\n\t\t\tdb\n\t\t\t\t.prepare(statement.sql)\n\t\t\t\t.bind(...statement.values)\n\t\t\t\t.first<T>(),\n\t\tall: async <T>(statement: AuthLinkStatement) => {\n\t\t\tconst result = await db\n\t\t\t\t.prepare(statement.sql)\n\t\t\t\t.bind(...statement.values)\n\t\t\t\t.all<T>();\n\t\t\tif (!Array.isArray(result.results)) throw new Error(\"ownership_evidence_reader_unavailable\");\n\t\t\treturn result.results;\n\t\t},\n\t\trun: (statement) => runChanges(db.prepare(statement.sql).bind(...statement.values)),\n\t\tbatch: async (statements) => {\n\t\t\tif (!db.batch) throw new Error(\"auth_link_atomic_batch_required\");\n\t\t\tconst results = await db.batch(\n\t\t\t\tstatements.map((statement) => db.prepare(statement.sql).bind(...statement.values)),\n\t\t\t);\n\t\t\treturn results.map(batchResultChanges);\n\t\t},\n\t};\n}\n\nasync function allRows<T>(statement: D1PreparedStatementLike): Promise<T[]> {\n\tconst result = await statement.all<T>();\n\treturn Array.isArray(result?.results) ? result.results : [];\n}\n\nasync function firstRow<T>(statement: D1PreparedStatementLike): Promise<T | null> {\n\treturn await statement.first<T>();\n}\n\nfunction requireScopeAuthorizationRows<T>(result: { results?: T[] }): T[] {\n\t// A lost read receipt is not an empty authority source.\n\tif (\n\t\t!result ||\n\t\tArray.isArray(result) ||\n\t\t(\"success\" in result && result.success !== true) ||\n\t\t!Array.isArray(result.results)\n\t)\n\t\tthrow new Error(\"scope_authorization_unavailable\");\n\treturn result.results;\n}\n\nasync function runChanges(statement: D1PreparedStatementLike): Promise<number> {\n\tconst result = (await statement.run()) as D1RunResultLike | undefined;\n\treturn Number(result?.meta?.changes ?? 0);\n}\n\nconst RECIPIENT_REVOCATION_SQL = `${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL}\n\tOR ${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL}`;\nconst RECIPIENT_OWNERSHIP_SQL = DEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL;\n// Each sensitive statement pins the evidence used to derive the inviter's canonical key.\n// Zero-row changes do not abort a D1 batch; downstream statements own the same guard.\nconst RECIPIENT_ELIGIBILITY_SQL = `EXISTS (\n\tSELECT 1 FROM coordinator_invites ri\n\tJOIN groups rg ON rg.group_id = ri.group_id AND rg.archived_at IS NULL\n\tWHERE ri.invite_id = ? AND ri.group_id = ? AND ri.revoked_at IS NULL\n\tAND ri.invite_kind = ? AND ri.reviewed_intent_json IS ?\n\tAND ri.reviewed_preview_digest IS ? AND ri.policy_team_id IS ?\n\tAND ri.target_identity_id IS ? AND ri.assigned_identity_id IS ?\n\tAND ri.inviter_device_id IS ?\n\tAND ri.token_digest IS ? AND (ri.token = ? OR ri.token = 'consumed:' || ri.invite_id)\n\tAND (ri.consumed_at IS NULL OR (ri.bound_device_id = ? AND ri.bound_public_key = ?\n\t\tAND ri.bound_fingerprint = ? AND ri.recipient_actor_id = ?))\n\tAND ((? = 0 AND NOT EXISTS (SELECT 1 FROM enrolled_devices se\n\t\tWHERE se.group_id = ri.group_id AND se.device_id = ri.inviter_device_id))\n\t\tOR (? = 1 AND EXISTS (SELECT 1 FROM enrolled_devices se\n\t\t\tWHERE se.group_id = ri.group_id AND se.device_id = ri.inviter_device_id\n\t\t\tAND se.public_key = ? AND se.fingerprint = ? AND se.enabled = ?)))\n\tAND NOT EXISTS (SELECT 1 FROM enrolled_devices re\n\t\tWHERE re.group_id = ri.group_id AND re.device_id = ?\n\t\tAND (re.public_key <> ? OR re.fingerprint <> ?\n\t\t\tOR (re.identity_id IS NOT NULL AND re.identity_id <> ?)))\n\tAND NOT (${RECIPIENT_REVOCATION_SQL}) AND NOT (${RECIPIENT_OWNERSHIP_SQL}))`;\nconst RECIPIENT_BINDING_SQL = `EXISTS (SELECT 1 FROM coordinator_invites bi\n\tWHERE bi.invite_id = ? AND bi.consumed_at IS NOT NULL\n\tAND bi.bound_device_id = ? AND bi.bound_public_key = ?\n\tAND bi.bound_fingerprint = ? AND bi.recipient_actor_id = ?)`;\n\nfunction validateRecipientEnrollmentTuple(\n\tenrollment: CoordinatorEnrollment | null,\n\topts: Pick<CoordinatorConsumeRecipientInviteInput, \"publicKey\" | \"fingerprint\" | \"identityId\">,\n): void {\n\tif (!enrollment) return;\n\tif (\n\t\tenrollment.public_key !== opts.publicKey ||\n\t\tenrollment.fingerprint !== opts.fingerprint ||\n\t\t(enrollment.identity_id !== null && enrollment.identity_id !== opts.identityId)\n\t) {\n\t\tthrow new Error(\"invite_identity_conflict\");\n\t}\n}\n\nfunction validateRecipientInviteBinding(\n\tinvite: Pick<\n\t\tCoordinatorInvite,\n\t\t| \"consumed_at\"\n\t\t| \"bound_device_id\"\n\t\t| \"bound_public_key\"\n\t\t| \"bound_fingerprint\"\n\t\t| \"recipient_actor_id\"\n\t>,\n\topts: Pick<\n\t\tCoordinatorConsumeRecipientInviteInput,\n\t\t\"deviceId\" | \"publicKey\" | \"fingerprint\" | \"identityId\"\n\t>,\n\toptions: { requireBinding: boolean },\n): void {\n\tif (!invite.consumed_at && !options.requireBinding) return;\n\tif (\n\t\tinvite.bound_device_id !== opts.deviceId ||\n\t\tinvite.bound_public_key !== opts.publicKey ||\n\t\tinvite.bound_fingerprint !== opts.fingerprint\n\t)\n\t\tthrow new Error(\"invite_already_bound\");\n\tif (invite.recipient_actor_id !== opts.identityId) throw new Error(\"invite_identity_conflict\");\n}\n\nfunction validateAcceptedRecipientEnrollment(\n\tenrollment: CoordinatorEnrollment | null,\n\topts: CoordinatorConsumeRecipientInviteInput,\n): void {\n\tif (!enrollment) throw new Error(\"invite_acceptance_incomplete\");\n\tvalidateRecipientEnrollmentTuple(enrollment, opts);\n\tif (enrollment.identity_id !== opts.identityId) throw new Error(\"invite_identity_conflict\");\n}\n\nfunction recipientInviteGuardEvidence(\n\tinitial: CoordinatorInvite,\n\topts: CoordinatorConsumeRecipientInviteInput,\n\tinviter: CoordinatorEnrollment | null,\n\tkeyIds: { recipient: string | null; inviter: string | null },\n) {\n\tconst revocationValues = [\n\t\topts.deviceId,\n\t\tkeyIds.recipient,\n\t\tinitial.inviter_device_id,\n\t\tkeyIds.inviter,\n\t];\n\t// Only the recipient enrollment is mutated; inviter ownership is not transferred.\n\tconst ownershipValues = [opts.deviceId, keyIds.recipient];\n\tconst eligibilityValues = [\n\t\tinitial.invite_id,\n\t\tinitial.group_id,\n\t\topts.inviteKind,\n\t\tinitial.reviewed_intent_json,\n\t\tinitial.reviewed_preview_digest,\n\t\tinitial.policy_team_id,\n\t\tinitial.target_identity_id,\n\t\tinitial.assigned_identity_id,\n\t\tinitial.inviter_device_id,\n\t\tinitial.token_digest,\n\t\tinitial.token,\n\t\topts.deviceId,\n\t\topts.publicKey,\n\t\topts.fingerprint,\n\t\topts.identityId,\n\t\tinviter ? 1 : 0,\n\t\tinviter ? 1 : 0,\n\t\tinviter?.public_key ?? null,\n\t\tinviter?.fingerprint ?? null,\n\t\tinviter?.enabled ?? null,\n\t\topts.deviceId,\n\t\topts.publicKey,\n\t\topts.fingerprint,\n\t\topts.identityId,\n\t\t...revocationValues,\n\t\t...ownershipValues,\n\t];\n\tconst bindingValues = [\n\t\tinitial.invite_id,\n\t\topts.deviceId,\n\t\topts.publicKey,\n\t\topts.fingerprint,\n\t\topts.identityId,\n\t];\n\treturn {\n\t\trevocationValues,\n\t\townershipValues,\n\t\teligibilitySql: RECIPIENT_ELIGIBILITY_SQL,\n\t\teligibilityValues,\n\t\tboundEligibilitySql: `${RECIPIENT_ELIGIBILITY_SQL} AND ${RECIPIENT_BINDING_SQL}`,\n\t\tboundEligibilityValues: [...eligibilityValues, ...bindingValues],\n\t};\n}\n\nasync function readRecipientInviteDecision<K extends string>(\n\tprepare: () => D1PreparedStatementLike,\n\tfields: K[],\n): Promise<Record<K, number>> {\n\ttry {\n\t\tconst row = await firstRow<Record<K, number>>(prepare());\n\t\tif (\n\t\t\t!row ||\n\t\t\t(\"success\" in row && row.success === false) ||\n\t\t\tfields.some((field) => row[field] !== 0 && row[field] !== 1)\n\t\t)\n\t\t\tthrow new Error(\"device_ownership_authorization_unavailable\");\n\t\treturn row;\n\t} catch {\n\t\tthrow new Error(\"device_ownership_authorization_unavailable\");\n\t}\n}\n\nasync function prepareRecipientInviteGuards(\n\tdb: D1DatabaseLike,\n\tinitial: CoordinatorInvite,\n\topts: CoordinatorConsumeRecipientInviteInput,\n) {\n\tconst recipientKeyId = await ed25519KeyIdForRevocation(opts.publicKey);\n\tconst inviterRow = initial.inviter_device_id\n\t\t? await firstRow<CoordinatorEnrollment>(\n\t\t\t\tdb\n\t\t\t\t\t.prepare(`SELECT ${ENROLLMENT_COLUMNS}\n\t\t\tFROM enrolled_devices WHERE group_id = ? AND device_id = ?`)\n\t\t\t\t\t.bind(initial.group_id, initial.inviter_device_id),\n\t\t\t)\n\t\t: null;\n\tconst inviter = inviterRow ? { ...inviterRow } : null;\n\tconst inviterKeyId = inviter ? await ed25519KeyIdForRevocation(inviter.public_key) : null;\n\tconst evidence = recipientInviteGuardEvidence(initial, opts, inviter, {\n\t\trecipient: recipientKeyId,\n\t\tinviter: inviterKeyId,\n\t});\n\tconst assertEligible = async (options: { requireBinding: boolean }): Promise<void> => {\n\t\tconst sql = options.requireBinding\n\t\t\t? `${evidence.boundEligibilitySql} AND EXISTS (SELECT 1 FROM enrolled_devices\n\t\t\t\tWHERE group_id = ? AND device_id = ? AND public_key = ? AND fingerprint = ? AND enabled = 1)`\n\t\t\t: evidence.eligibilitySql;\n\t\tconst values = options.requireBinding\n\t\t\t? [\n\t\t\t\t\t...evidence.boundEligibilityValues,\n\t\t\t\t\tinitial.group_id,\n\t\t\t\t\topts.deviceId,\n\t\t\t\t\topts.publicKey,\n\t\t\t\t\topts.fingerprint,\n\t\t\t\t]\n\t\t\t: evidence.eligibilityValues;\n\t\tconst revocation = await readRecipientInviteDecision(\n\t\t\t() =>\n\t\t\t\tdb\n\t\t\t\t\t.prepare(`SELECT (${RECIPIENT_REVOCATION_SQL}) AS revoked`)\n\t\t\t\t\t.bind(...evidence.revocationValues),\n\t\t\t[\"revoked\"],\n\t\t);\n\t\tif (revocation.revoked === 1) throw new Error(\"device_revoked\");\n\t\tconst row = await readRecipientInviteDecision(\n\t\t\t() =>\n\t\t\t\tdb\n\t\t\t\t\t.prepare(`SELECT (${RECIPIENT_REVOCATION_SQL}) AS revoked,\n\t\t\t\t(${RECIPIENT_OWNERSHIP_SQL}) AS owned, (${sql}) AS eligible`)\n\t\t\t\t\t.bind(...evidence.revocationValues, ...evidence.ownershipValues, ...values),\n\t\t\t[\"revoked\", \"owned\", \"eligible\"],\n\t\t);\n\t\tif (row.revoked === 1) throw new Error(\"device_revoked\");\n\t\tif (row.eligible === 0) {\n\t\t\tawait rejectStaleRecipientInviteEvidence(db, initial, opts, recipientKeyId, {\n\t\t\t\towned: row.owned === 1,\n\t\t\t});\n\t\t}\n\t};\n\treturn { ...evidence, assertEligible };\n}\n\nasync function runRecipientInviteBatch(\n\tdb: D1DatabaseLike,\n\tstatements: D1PreparedStatementLike[],\n\tguard: {\n\t\tsql: string;\n\t\tvalues: unknown[];\n\t\tassertEligible: (options: { requireBinding: boolean }) => Promise<void>;\n\t\tnegative?: AuthLinkStatement;\n\t},\n): Promise<number> {\n\tif (!db.batch) throw new Error(\"device_ownership_authorization_unavailable\");\n\tconst negative = guard.negative ?? { sql: \"SELECT 1 AS matches\", values: [] };\n\ttry {\n\t\tconst results = await db.batch([\n\t\t\t...statements,\n\t\t\tdb\n\t\t\t\t.prepare(`WITH recipient_negative AS MATERIALIZED (${negative.sql})\n SELECT CASE WHEN (${guard.sql}) AND (SELECT matches FROM recipient_negative)\n THEN 1 ELSE json('recipient_invite_authorization_failed') END AS confirmed`)\n\t\t\t\t.bind(...negative.values, ...guard.values),\n\t\t]);\n\t\tconst confirmation = results[statements.length] as\n\t\t\t| { results?: { confirmed?: unknown }[] }\n\t\t\t| undefined;\n\t\tif (legacyDeviceWriteChanges(confirmation) !== 0 || confirmation?.results?.[0]?.confirmed !== 1)\n\t\t\tthrow new Error(\"device_ownership_authorization_unavailable\");\n\t\tfor (const result of results.slice(0, statements.length)) legacyDeviceWriteChanges(result);\n\t\treturn legacyDeviceWriteChanges(results[0]);\n\t} catch {\n\t\t// A SQL assertion rolls back the batch; malformed metadata may arrive after commit.\n\t\tawait guard.assertEligible({ requireBinding: false });\n\t\tthrow new Error(\"device_ownership_authorization_unavailable\");\n\t}\n}\n\nfunction prepareRecipientOwnerStatement(\n\tdb: D1DatabaseLike,\n\tsql: string,\n\tnegative?: AuthLinkStatement,\n) {\n\tconst statement = db.prepare(negative ? recipientOwnerWriteSql(sql, negative) : sql);\n\treturn { bind: (...values: unknown[]) => statement.bind(...(negative?.values ?? []), ...values) };\n}\n\nfunction createRecipientOwnerBackend(db: D1DatabaseLike) {\n\treturn {\n\t\tfirst: <T>({ sql, values }: AuthLinkStatement) =>\n\t\t\tdb\n\t\t\t\t.prepare(sql)\n\t\t\t\t.bind(...values)\n\t\t\t\t.first<T>(),\n\t\tall: async <T>({ sql, values }: AuthLinkStatement) => {\n\t\t\tconst result = await db\n\t\t\t\t.prepare(sql)\n\t\t\t\t.bind(...values)\n\t\t\t\t.all<T>();\n\t\t\tif (!Array.isArray(result.results)) throw new Error(\"ownership_evidence_reader_unavailable\");\n\t\t\treturn result.results;\n\t\t},\n\t};\n}\n\nasync function repairBoundRecipientInviteIdentity(\n\tdb: D1DatabaseLike,\n\topts: CoordinatorConsumeRecipientInviteInput,\n\tinvite: CoordinatorInvite,\n\tguard: Parameters<typeof runRecipientInviteBatch>[2],\n\tfirstWrite: { winningChanges: number; consistency: NegativeOwnerConsistency },\n): Promise<AuthLinkStatement> {\n\tvalidateRecipientInviteBinding(invite, opts, { requireBinding: true });\n\t// A zero-row token UPDATE (including another invocation's winner) did\n\t// not consume this invocation's full initial evidence pin.\n\tconst firstWriteNegative =\n\t\tfirstWrite.winningChanges === 1\n\t\t\t? firstWrite.consistency.retainedRecheck\n\t\t\t: firstWrite.consistency;\n\tconst repaired = await runRecipientInviteBatch(\n\t\tdb,\n\t\t[\n\t\t\tprepareRecipientOwnerStatement(\n\t\t\t\tdb,\n\t\t\t\t`UPDATE enrolled_devices SET identity_id = ?\n\t\tWHERE group_id = ? AND device_id = ? AND identity_id IS NULL\n\t\tAND public_key = ? AND fingerprint = ? AND ${guard.sql}`,\n\t\t\t\tfirstWriteNegative,\n\t\t\t).bind(\n\t\t\t\topts.identityId,\n\t\t\t\tinvite.group_id,\n\t\t\t\topts.deviceId,\n\t\t\t\topts.publicKey,\n\t\t\t\topts.fingerprint,\n\t\t\t\t...guard.values,\n\t\t\t),\n\t\t],\n\t\t{\n\t\t\t...guard,\n\t\t\tnegative: {\n\t\t\t\t// Only the immediately preceding identity UPDATE can consume the full pin.\n\t\t\t\t// A no-op must still check it inside this batch, then carry it to recovery.\n\t\t\t\tsql: `SELECT (changes() = 1 OR (SELECT matches FROM (${firstWriteNegative.sql})))\n\t\t\t\tAND (SELECT matches FROM (${firstWrite.consistency.retainedRecheck.sql})) AS matches`,\n\t\t\t\tvalues: [...firstWriteNegative.values, ...firstWrite.consistency.retainedRecheck.values],\n\t\t\t},\n\t\t},\n\t);\n\treturn repaired === 1 ? firstWrite.consistency.retainedRecheck : firstWriteNegative;\n}\n\nasync function rejectStaleRecipientInviteEvidence(\n\tdb: D1DatabaseLike,\n\tinvite: CoordinatorInvite,\n\topts: Pick<\n\t\tCoordinatorConsumeRecipientInviteInput,\n\t\t\"deviceId\" | \"publicKey\" | \"fingerprint\" | \"identityId\"\n\t>,\n\trecipientKeyId: string | null,\n\toptions: { owned?: boolean } = {},\n): Promise<never> {\n\tconst current = await firstRow<{ public_key: string }>(\n\t\tdb\n\t\t\t.prepare(`SELECT public_key\n\t\tFROM enrolled_devices WHERE group_id = ? AND device_id = ?`)\n\t\t\t.bind(invite.group_id, invite.inviter_device_id),\n\t);\n\tconst currentKeyId = current ? await ed25519KeyIdForRevocation(current.public_key) : null;\n\tconst revoked = await firstRow<{ revoked: number }>(\n\t\tdb\n\t\t\t.prepare(`SELECT 1 AS revoked\n\t\tWHERE ${RECIPIENT_REVOCATION_SQL}`)\n\t\t\t.bind(opts.deviceId, recipientKeyId, invite.inviter_device_id, currentKeyId),\n\t);\n\tif (revoked) throw new Error(\"device_revoked\");\n\t// These fresh reads classify denial only; they never replace the pinned write evidence.\n\tconst state = await firstRow<{\n\t\trevoked_at: string | null;\n\t\tcurrent_group_id: string | null;\n\t\tarchived_at: string | null;\n\t\tconsumed_at: string | null;\n\t\tbound_device_id: string | null;\n\t\tbound_public_key: string | null;\n\t\tbound_fingerprint: string | null;\n\t\trecipient_actor_id: string | null;\n\t}>(\n\t\tdb\n\t\t\t.prepare(`SELECT i.revoked_at, g.group_id AS current_group_id, g.archived_at,\n\t\t\ti.consumed_at, i.bound_device_id, i.bound_public_key, i.bound_fingerprint, i.recipient_actor_id\n\t\t\tFROM coordinator_invites i LEFT JOIN groups g ON g.group_id = i.group_id\n\t\t\tWHERE i.invite_id = ?`)\n\t\t\t.bind(invite.invite_id),\n\t);\n\tif (!state || state.revoked_at) throw new Error(\"invite_invalid\");\n\tif (state.current_group_id === null) throw new Error(\"group_not_found\");\n\tif (state.archived_at) throw new Error(\"group_archived\");\n\tif (options.owned) throw new Error(\"device_ownership_requires_verified_identity\");\n\tvalidateRecipientInviteBinding(state, opts, { requireBinding: false });\n\tthrow new Error(\"invite_acceptance_incomplete\");\n}\n\nfunction prepareProjectInviteDecision(\n\tdb: D1DatabaseLike,\n\tinitial: CoordinatorInvite,\n\topts: CoordinatorConsumeProjectInviteInput,\n\tguard: ReturnType<typeof legacyProjectInviteOwnershipEvidence>,\n\toptions: { requireBinding: boolean },\n): D1PreparedStatementLike {\n\tconst sql = options.requireBinding ? guard.boundEligibilitySql : guard.eligibilitySql;\n\tconst values = options.requireBinding ? guard.boundEligibilityValues : guard.eligibilityValues;\n\tconst enrollmentSql =\n\t\tinitial.consumed_at || options.requireBinding ? PROJECT_INVITE_ACTIVE_ENROLLMENT_SQL : \"1\";\n\tconst enrollmentValues = enrollmentSql === \"1\" ? [] : [initial.group_id, opts.deviceId];\n\treturn db\n\t\t.prepare(`SELECT (${guard.revocationSql}) AS revoked, (${guard.ownershipSql}) AS owned,\n\t\t(${sql} AND ${enrollmentSql}) AS eligible`)\n\t\t.bind(...guard.revocationValues, ...guard.ownershipValues, ...values, ...enrollmentValues);\n}\n\nasync function prepareProjectInviteGuards(\n\tdb: D1DatabaseLike,\n\tinitial: CoordinatorInvite,\n\topts: CoordinatorConsumeProjectInviteInput,\n) {\n\tconst participantOpts = { ...opts, identityId: opts.recipientActorId };\n\tconst enrollmentRow = await firstRow<CoordinatorEnrollment>(\n\t\tdb\n\t\t\t.prepare(\n\t\t\t\t`SELECT ${ENROLLMENT_COLUMNS} FROM enrolled_devices WHERE group_id = ? AND device_id = ?`,\n\t\t\t)\n\t\t\t.bind(initial.group_id, opts.deviceId),\n\t);\n\tconst currentPublicKey = captureLegacyEnrollmentPublicKey(enrollmentRow);\n\tconst enrollment = enrollmentRow ? { ...enrollmentRow } : null;\n\tconst recipientKeyId = await ed25519KeyIdForRevocation(opts.publicKey);\n\tconst currentKeyId =\n\t\tcurrentPublicKey === null ? null : await ed25519KeyIdForRevocation(currentPublicKey);\n\tconst inviterRow = initial.inviter_device_id\n\t\t? await firstRow<CoordinatorEnrollment>(\n\t\t\t\tdb\n\t\t\t\t\t.prepare(`SELECT ${ENROLLMENT_COLUMNS}\n\t\t\tFROM enrolled_devices WHERE group_id = ? AND device_id = ?`)\n\t\t\t\t\t.bind(initial.group_id, initial.inviter_device_id),\n\t\t\t)\n\t\t: null;\n\tconst inviterPublicKey = captureLegacyEnrollmentPublicKey(inviterRow);\n\tconst inviter = inviterRow ? { ...inviterRow } : null;\n\tconst inviterKeyId =\n\t\tinviterPublicKey === null ? null : await ed25519KeyIdForRevocation(inviterPublicKey);\n\tconst evidence = projectInviteGuardEvidence(initial, opts, inviter, {\n\t\trecipient: recipientKeyId,\n\t\tinviter: inviterKeyId,\n\t});\n\tconst guard = legacyProjectInviteOwnershipEvidence(evidence, opts.deviceId, {\n\t\tincoming: recipientKeyId,\n\t\tcurrent: currentKeyId,\n\t});\n\tconst assertEligible = async (options: { requireBinding: boolean }): Promise<void> => {\n\t\tconst state = await readRecipientInviteDecision(\n\t\t\t() => prepareProjectInviteDecision(db, initial, opts, guard, options),\n\t\t\t[\"revoked\", \"owned\", \"eligible\"],\n\t\t);\n\t\tif (state.revoked === 1) throw new Error(\"device_revoked\");\n\t\tif (state.eligible === 0) {\n\t\t\tif (state.owned === 0) validateRecipientEnrollmentTuple(enrollment, participantOpts);\n\t\t\tawait rejectStaleRecipientInviteEvidence(db, initial, participantOpts, recipientKeyId, {\n\t\t\t\towned: state.owned === 1,\n\t\t\t});\n\t\t}\n\t};\n\tawait assertEligible({ requireBinding: false });\n\tvalidateRecipientEnrollmentTuple(enrollment, participantOpts);\n\treturn { ...guard, assertEligible };\n}\n\nfunction prepareBoundProjectInviteIdentityRepair(\n\tdb: D1DatabaseLike,\n\topts: CoordinatorConsumeProjectInviteInput,\n\tinvite: CoordinatorInvite,\n\tguard: ReturnType<typeof projectInviteGuardEvidence>,\n): D1PreparedStatementLike {\n\treturn db\n\t\t.prepare(`UPDATE enrolled_devices SET identity_id = ?\n\t\tWHERE group_id = ? AND device_id = ? AND identity_id IS NULL AND enabled = 1\n\t\tAND public_key = ? AND fingerprint = ? AND ${guard.boundEligibilitySql}`)\n\t\t.bind(\n\t\t\topts.recipientActorId,\n\t\t\tinvite.group_id,\n\t\t\topts.deviceId,\n\t\t\topts.publicKey,\n\t\t\topts.fingerprint,\n\t\t\t...guard.boundEligibilityValues,\n\t\t);\n}\n\nfunction assertProjectInviteBinding(\n\tinvite: CoordinatorInvite,\n\topts: CoordinatorConsumeProjectInviteInput,\n): void {\n\tif (\n\t\tinvite.bound_device_id !== opts.deviceId ||\n\t\tinvite.bound_public_key !== opts.publicKey ||\n\t\tinvite.bound_fingerprint !== opts.fingerprint\n\t)\n\t\tthrow new Error(\"invite_already_bound\");\n\tif (\n\t\tinvite.recipient_actor_id !== opts.recipientActorId ||\n\t\tinvite.recipient_display_name !== opts.recipientDisplayName ||\n\t\tinvite.recipient_device_display_name !== opts.deviceDisplayName\n\t)\n\t\tthrow new Error(\"invite_identity_conflict\");\n}\n\nconst PROJECT_INVITE_ENROLLMENT_SQL = `EXISTS (SELECT 1 FROM enrolled_devices WHERE group_id = ?\n\tAND device_id = ? AND public_key = ? AND fingerprint = ? AND identity_id = ? AND enabled = 1)`;\n\nconst PROJECT_INVITE_ACTIVE_ENROLLMENT_SQL = `EXISTS (SELECT 1 FROM enrolled_devices\n\tWHERE group_id = ? AND device_id = ? AND enabled = 1)`;\n\nfunction projectInviteEnrollmentValues(\n\tinvite: CoordinatorInvite,\n\topts: CoordinatorConsumeProjectInviteInput,\n): string[] {\n\treturn [invite.group_id, opts.deviceId, opts.publicKey, opts.fingerprint, opts.recipientActorId];\n}\n\nasync function runProjectInviteBatch(\n\tdb: D1DatabaseLike,\n\tstatements: D1PreparedStatementLike[],\n\tinitial: CoordinatorInvite,\n\topts: CoordinatorConsumeProjectInviteInput,\n\tguard: Awaited<ReturnType<typeof prepareProjectInviteGuards>>,\n\tenrollmentValues: string[],\n): Promise<boolean> {\n\t// A retry repairs only its pinned enrollment; fresh enrollment requires this batch's consume winner.\n\tif (initial.consumed_at)\n\t\tstatements.splice(1, 1, prepareBoundProjectInviteIdentityRepair(db, opts, initial, guard));\n\tconst changed = await runRecipientInviteBatch(db, statements, {\n\t\tsql: `${guard.boundEligibilitySql} AND ${PROJECT_INVITE_ENROLLMENT_SQL}`,\n\t\tvalues: [...guard.boundEligibilityValues, ...enrollmentValues],\n\t\tassertEligible: guard.assertEligible,\n\t});\n\treturn !initial.consumed_at && changed === 1;\n}\n\nexport class D1CoordinatorStore implements CoordinatorStore {\n\tprivate readonly accountChangeBackend: AuthLinkBackend;\n\tprivate readonly accountChangesCapability: AccountChangeOperations;\n\treadonly db: D1DatabaseLike;\n\tprivate readonly authLinks: AuthLinkOperations;\n\tasync assertAuthSchemaReady(): Promise<void> {\n\t\tawait assertCoordinatorAuthSchema({\n\t\t\tfirst: <T>({ sql, values }: AuthLinkStatement) =>\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(sql)\n\t\t\t\t\t.bind(...values)\n\t\t\t\t\t.first<T>(),\n\t\t});\n\t}\n\tprivate readonly accountLinkStatus: AccountLinkStatusOperations;\n\tprivate readonly accountOwnerTarget: AccountOwnerTargetOperations;\n\tprivate readonly deviceRevocations: DeviceRevocationOperations;\n\tprivate readonly authSessions: AuthSessionOperations;\n\tprivate readonly authAccountProfiles: AuthAccountProfileOperations;\n\tprivate readonly authBrowserTransactions: CoordinatorAuthBrowserTransactions;\n\n\tconstructor(db: D1DatabaseLike, options: CoordinatorAuthLinkOptions = {}) {\n\t\tthis.db = db;\n\t\tthis.deviceRevocations = new DeviceRevocationOperations(\n\t\t\t{\n\t\t\t\tall: (statement) =>\n\t\t\t\t\tdb\n\t\t\t\t\t\t.prepare(statement.sql)\n\t\t\t\t\t\t.bind(...statement.values)\n\t\t\t\t\t\t.all(),\n\t\t\t\tbatch: async (statements) => {\n\t\t\t\t\tif (!db.batch) throw new Error(\"device_revocation_atomic_batch_required\");\n\t\t\t\t\treturn db.batch(\n\t\t\t\t\t\tstatements.map((statement) => db.prepare(statement.sql).bind(...statement.values)),\n\t\t\t\t\t);\n\t\t\t\t},\n\t\t\t},\n\t\t\toptions.authClock,\n\t\t);\n\t\tconst authBackend = createD1AuthLinkBackend(db);\n\t\tthis.accountChangeBackend = createD1AuthLinkBackend(db, { connections: true });\n\t\tthis.accountChangesCapability = new AccountChangeOperations(\n\t\t\tthis.accountChangeBackend,\n\t\t\toptions.authClock,\n\t\t);\n\t\tthis.authLinks = new AuthLinkOperations(authBackend, options.authClock);\n\t\tthis.accountLinkStatus = new AccountLinkStatusOperations(authBackend, options.authClock);\n\t\tthis.accountOwnerTarget = new AccountOwnerTargetOperations(authBackend, this);\n\t\tthis.authSessions = new AuthSessionOperations(authBackend, options.authClock);\n\t\tthis.authAccountProfiles = new AuthAccountProfileOperations(authBackend, options.authClock);\n\t\tthis.authBrowserTransactions = new CoordinatorAuthBrowserTransactions(\n\t\t\tauthBackend,\n\t\t\toptions.authClock,\n\t\t);\n\t}\n\t/**\n\t * ADR 0005 Section 8 rebind storage; null until migration 0038 is applied.\n\t * Raw like SQLite's: the rebind tables are gated here, not per statement.\n\t */\n\treadDeviceRebindBackend(): Promise<AuthLinkBackend | null> {\n\t\treturn readDeviceRebindBackend(createRawD1AuthLinkBackend(this.db));\n\t}\n\tasync getAccountChanges(): Promise<AccountChangeOperations> {\n\t\tawait this.accountChangeBackend.first({ sql: \"SELECT 1\", values: [] });\n\t\treturn this.accountChangesCapability;\n\t}\n\treadAccountConnectionSchemaState(): Promise<ConnectionSchemaState> {\n\t\treturn readConnectionSchemaState({\n\t\t\tfirst: <T>({ sql, values }: AuthLinkStatement) =>\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(sql)\n\t\t\t\t\t.bind(...values)\n\t\t\t\t\t.first<T>(),\n\t\t});\n\t}\n\n\t/** One fresh startup lookup; returned operations still check every SQL entry. */\n\tasync readAccountChangeCapability(): Promise<AccountChangeOperations | null> {\n\t\tconst state = await this.readAccountConnectionSchemaState();\n\t\tif (state === \"upgrade_required\") throw new CoordinatorAuthSchemaUpgradeRequiredError();\n\t\treturn state === \"ready\" ? this.accountChangesCapability : null;\n\t}\n\tasync readAuthBrowserTransactionActivity(\n\t\tinput: { binderHash: string },\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t) {\n\t\treturn this.authBrowserTransactions.readAuthBrowserTransactionActivity(input, config);\n\t}\n\tasync startAuthBrowserTransaction(\n\t\tinput: CoordinatorAuthBrowserTransactionStartInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t) {\n\t\treturn this.authBrowserTransactions.startAuthBrowserTransaction(input, config);\n\t}\n\tasync consumeAuthBrowserTransaction(\n\t\tinput: CoordinatorAuthBrowserTransactionConsumeInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t) {\n\t\treturn this.authBrowserTransactions.consumeAuthBrowserTransaction(input, config);\n\t}\n\tasync readAuthBrowserTransactionPurpose(\n\t\tinput: CoordinatorAuthBrowserTransactionConsumeInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t) {\n\t\treturn this.authBrowserTransactions.readAuthBrowserTransactionPurpose(input, config);\n\t}\n\tasync resolveAuthLinkBrowserTransaction(\n\t\tinput: CoordinatorAuthLinkBrowserTransactionResolveInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t) {\n\t\treturn this.authBrowserTransactions.resolveAuthLinkBrowserTransaction(input, config);\n\t}\n\tasync cancelAuthSigninBrowserTransaction(\n\t\tinput: CoordinatorAuthSigninBrowserTransactionCancelInput,\n\t\tscope: CoordinatorAuthBrowserTransactionScope,\n\t) {\n\t\treturn this.authBrowserTransactions.cancelAuthSigninBrowserTransaction(input, scope);\n\t}\n\tasync retireAuthBrowserTransactions(\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t\toptions?: CoordinatorAuthBrowserTransactionRetirementOptions,\n\t) {\n\t\treturn this.authBrowserTransactions.retireAuthBrowserTransactions(config, options);\n\t}\n\tasync purgeAuthSigninBrowserTransactions(\n\t\tscope: CoordinatorAuthBrowserTransactionScope,\n\t\toptions?: CoordinatorAuthBrowserTransactionMaintenanceOptions,\n\t) {\n\t\treturn this.authBrowserTransactions.purgeAuthSigninBrowserTransactions(scope, options);\n\t}\n\tasync maintainAuthBrowserTransactions(\n\t\tscope: CoordinatorAuthBrowserTransactionScope,\n\t\toptions?: CoordinatorAuthBrowserTransactionMaintenanceOptions,\n\t) {\n\t\treturn this.authBrowserTransactions.maintainAuthBrowserTransactions(scope, options);\n\t}\n\n\tasync redeemAuthLinkSession(\n\t\tinput: CoordinatorAuthLinkSessionRedeemInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authSessions.redeemAuthLinkSession(input, config);\n\t}\n\tasync redeemAuthLinkSessionWithBrowserTransaction(\n\t\tinput: CoordinatorAuthBoundLinkSessionRedeemInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t) {\n\t\treturn this.authSessions.redeemAuthLinkSessionWithBrowserTransaction(input, config);\n\t}\n\tasync preserveAuthLinkSessionCompletion(\n\t\tinput: CoordinatorAuthBoundLinkSessionRedeemInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t) {\n\t\treturn this.authSessions.preserveAuthLinkSessionCompletion(input, config);\n\t}\n\tasync purgeAuthGuardedSigninSessions(\n\t\tscope: CoordinatorAuthSessionScope,\n\t\toptions?: CoordinatorAuthSessionPurgeOptions,\n\t) {\n\t\treturn this.authSessions.purgeAuthGuardedSigninSessions(scope, options);\n\t}\n\tasync purgeAuthGuardedSigninReceipts(\n\t\tscope: CoordinatorAuthSessionScope,\n\t\toptions?: CoordinatorAuthSessionPurgeOptions,\n\t) {\n\t\treturn this.authSessions.purgeAuthGuardedSigninReceipts(scope, options);\n\t}\n\tasync signInWithAuthAccount(\n\t\tinput: CoordinatorAuthAccountSignInInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authSessions.signInWithAuthAccount(input, config);\n\t}\n\tasync signInWithConsumedBrowserTransaction(\n\t\tinput: CoordinatorAuthAccountSignInInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t) {\n\t\treturn this.authSessions.signInWithConsumedBrowserTransaction(input, config);\n\t}\n\tasync readAuthSession(credentialHash: string, config: CoordinatorAuthLinkConfig) {\n\t\treturn this.authSessions.readAuthSession(credentialHash, config);\n\t}\n\tasync recordAuthAccountProfile(\n\t\tinput: CoordinatorAuthAccountProfileInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authAccountProfiles.recordAuthAccountProfile(input, config);\n\t}\n\tasync readAuthSessionAccount(credentialHash: string, config: CoordinatorAuthLinkConfig) {\n\t\treturn this.authAccountProfiles.readAuthSessionAccount(credentialHash, config);\n\t}\n\tasync clearRevokedAuthAccountProfile(\n\t\tinput: { linkId: string },\n\t\tscope: { coordinatorId: string },\n\t) {\n\t\treturn this.authAccountProfiles.clearRevokedAuthAccountProfile(input, scope);\n\t}\n\tasync signOutAuthSession(credentialHash: string, scope: CoordinatorAuthSessionScope) {\n\t\treturn this.authSessions.signOutAuthSession(credentialHash, scope);\n\t}\n\tasync revokeAuthAccountLink(input: { linkId: string }, scope: CoordinatorAuthSessionScope) {\n\t\treturn this.authSessions.revokeAuthAccountLink(input, scope);\n\t}\n\n\tasync maintainAuthLinkAttempts(\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t\toptions?: CoordinatorAuthLinkMaintenanceOptions,\n\t) {\n\t\treturn this.authLinks.maintainAuthLinkAttempts(config, options);\n\t}\n\treadAccountLinkStatus(...args: Parameters<AccountLinkStatusOperations[\"readAccountLinkStatus\"]>) {\n\t\treturn this.accountLinkStatus.readAccountLinkStatus(...args);\n\t}\n\treadAccountOwnerTarget(\n\t\t...args: Parameters<AccountOwnerTargetOperations[\"readAccountOwnerTarget\"]>\n\t) {\n\t\treturn this.accountOwnerTarget.readAccountOwnerTarget(...args);\n\t}\n\treadResolvedAccountOwnerStatus(\n\t\t...args: Parameters<ResolvedAccountOwnerStatusOperations[\"readResolvedAccountOwnerStatus\"]>\n\t) {\n\t\treturn new ResolvedAccountOwnerStatusOperations({\n\t\t\t...this.accountChangeBackend,\n\t\t\tall: async <T>({ sql, values }: AuthLinkStatement) => {\n\t\t\t\tconst result = await this.db\n\t\t\t\t\t.prepare(sql)\n\t\t\t\t\t.bind(...values)\n\t\t\t\t\t.all<T>();\n\t\t\t\tif (!result.results) throw new Error(\"resolved_account_owner_status_unavailable\");\n\t\t\t\treturn result.results;\n\t\t\t},\n\t\t}).readResolvedAccountOwnerStatus(...args);\n\t}\n\tprivate ownerResolutionReviews(): OwnerResolutionReviewOperations {\n\t\treturn new OwnerResolutionReviewOperations({\n\t\t\t...createD1AuthLinkBackend(this.db),\n\t\t\tall: async <T>({ sql, values }: AuthLinkStatement) => {\n\t\t\t\tconst result = await this.db\n\t\t\t\t\t.prepare(sql)\n\t\t\t\t\t.bind(...values)\n\t\t\t\t\t.all<T>();\n\t\t\t\tif (!result.results) throw new Error(\"owner_resolution_rows_unavailable\");\n\t\t\t\treturn result.results;\n\t\t\t},\n\t\t});\n\t}\n\tpreviewOwnerResolutionReview(\n\t\t...args: Parameters<OwnerResolutionReviewOperations[\"previewOwnerResolutionReview\"]>\n\t) {\n\t\treturn this.ownerResolutionReviews().previewOwnerResolutionReview(...args);\n\t}\n\tconfirmOwnerResolutionReview(\n\t\t...args: Parameters<OwnerResolutionReviewOperations[\"confirmOwnerResolutionReview\"]>\n\t) {\n\t\treturn this.ownerResolutionReviews().confirmOwnerResolutionReview(...args);\n\t}\n\treadAuthDeviceClaimReadiness(\n\t\t...args: Parameters<AccountLinkStatusOperations[\"readAuthDeviceClaimReadiness\"]>\n\t) {\n\t\treturn this.accountLinkStatus.readAuthDeviceClaimReadiness(...args);\n\t}\n\tasync createAuthLinkAttempt(\n\t\tinput: CoordinatorAuthLinkCreateInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authLinks.createAuthLinkAttempt(input, config);\n\t}\n\tasync claimAuthLinkAttempt(\n\t\tinput: CoordinatorAuthLinkClaimInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authLinks.claimAuthLinkAttempt(input, config);\n\t}\n\tasync recordAuthLinkOidcVerified(\n\t\tinput: CoordinatorAuthLinkOidcInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authLinks.recordAuthLinkOidcVerified(input, config);\n\t}\n\tasync confirmAuthLinkAttempt(\n\t\tinput: CoordinatorAuthLinkConfirmInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authLinks.confirmAuthLinkAttempt(input, config);\n\t}\n\tasync readAuthLinkCompletionDestination(\n\t\tinput: CoordinatorAuthLinkClaimInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authLinks.readAuthLinkCompletionDestination(input, config);\n\t}\n\tasync finalizeAuthLinkAttempt(\n\t\tinput: CoordinatorAuthLinkFinalizeInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authLinks.finalizeAuthLinkAttempt(input, config);\n\t}\n\tasync failAuthLinkAttempt(\n\t\tinput: CoordinatorAuthLinkFailInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authLinks.failAuthLinkAttempt(input, config);\n\t}\n\tasync getAuthLinkAttemptStatus(\n\t\tattemptId: string,\n\t\trequester: CoordinatorAuthLinkRequester,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authLinks.getAuthLinkAttemptStatus(attemptId, requester, config);\n\t}\n\n\tasync close(): Promise<void> {\n\t\t// No-op for D1 bindings.\n\t}\n\n\tasync issueIdentityGroupGrantFromControllerAttestation(\n\t\tinput: CoordinatorIdentityGroupGrantIssueInput,\n\t): Promise<CoordinatorIdentityGroupGrantIssueResult> {\n\t\tconst captured = captureIdentityGroupGrantInput(input, [\"coordinatorId\", \"attestationId\"]);\n\t\tif (!captured) return { kind: \"rejected\", error: \"invalid_grant_input\" };\n\t\ttry {\n\t\t\tconst source = await firstRow<CoordinatorEnrollment>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(IDENTITY_GROUP_GRANT_SOURCE_SQL)\n\t\t\t\t\t.bind(captured.coordinatorId, captured.attestationId),\n\t\t\t);\n\t\t\tif (!source) return { kind: \"rejected\", error: \"grant_authority_unavailable\" };\n\t\t\tconst authority = [\n\t\t\t\tcaptured.coordinatorId,\n\t\t\t\tcaptured.attestationId,\n\t\t\t\tsource.group_id,\n\t\t\t\tsource.device_id,\n\t\t\t\tsource.public_key,\n\t\t\t\tsource.fingerprint,\n\t\t\t\tsource.identity_id,\n\t\t\t\tsource.device_id,\n\t\t\t\tawait ed25519KeyIdForRevocation(source.public_key),\n\t\t\t];\n\t\t\tconst grant = await firstRow<CoordinatorIdentityGroupGrant>(\n\t\t\t\tthis.db.prepare(IDENTITY_GROUP_GRANT_INSERT_SQL).bind(nowISO(), ...authority),\n\t\t\t);\n\t\t\tif (grant) return { kind: \"created\", grant };\n\t\t\t// Never return a separately fetched grant after an authority check.\n\t\t\tconst existing = await firstRow<CoordinatorIdentityGroupGrant>(\n\t\t\t\tthis.db.prepare(IDENTITY_GROUP_GRANT_RETRY_SQL).bind(...authority),\n\t\t\t);\n\t\t\tif (existing) return { kind: \"existing\", grant: existing };\n\t\t\treturn { kind: \"rejected\", error: \"grant_authority_unavailable\" };\n\t\t} catch {\n\t\t\tthrow new Error(\"identity_group_grant_write_incomplete\");\n\t\t}\n\t}\n\n\tasync listIdentityGroupGrantRevisions(\n\t\tinput: CoordinatorIdentityGroupGrantScope,\n\t): Promise<CoordinatorIdentityGroupGrant[]> {\n\t\tconst captured = captureIdentityGroupGrantInput(input, [\"coordinatorId\", \"identityId\"]);\n\t\tif (!captured) throw new Error(\"invalid_grant_input\");\n\t\tconst result = await this.db\n\t\t\t.prepare(IDENTITY_GROUP_GRANT_LIST_SQL)\n\t\t\t.bind(captured.coordinatorId, captured.identityId)\n\t\t\t.all<CoordinatorIdentityGroupGrant>();\n\t\tif (!Array.isArray(result?.results)) throw new Error(\"identity_group_grant_read_incomplete\");\n\t\treturn result.results;\n\t}\n\n\tasync revokeIdentityGroupGrant(\n\t\tinput: CoordinatorIdentityGroupGrantRevokeInput,\n\t): Promise<boolean> {\n\t\tconst captured = captureIdentityGroupGrantInput(input, [\n\t\t\t\"coordinatorId\",\n\t\t\t\"identityId\",\n\t\t\t\"groupId\",\n\t\t\t\"expectedRevision\",\n\t\t]);\n\t\tif (!captured) return false;\n\t\tconst result = (await this.db\n\t\t\t.prepare(IDENTITY_GROUP_GRANT_REVOKE_SQL)\n\t\t\t.bind(\n\t\t\t\tnowISO(),\n\t\t\t\tcaptured.coordinatorId,\n\t\t\t\tcaptured.identityId,\n\t\t\t\tcaptured.groupId,\n\t\t\t\tcaptured.expectedRevision,\n\t\t\t)\n\t\t\t.run()) as D1RunResultLike | undefined;\n\t\tconst changes = result?.meta?.changes;\n\t\tif (typeof changes !== \"number\" || !Number.isSafeInteger(changes) || changes < 0 || changes > 1)\n\t\t\tthrow new Error(\"identity_group_grant_write_incomplete\");\n\t\treturn changes === 1;\n\t}\n\n\tasync createAuthControllerAttestation(\n\t\tinput: CoordinatorAuthControllerReviewInput,\n\t): Promise<CoordinatorAuthControllerCreateResult> {\n\t\tconst review = captureAuthControllerReview(input);\n\t\tif (!review) return { kind: \"rejected\", error: \"invalid_review_input\" };\n\t\tconst source = await firstRow<CoordinatorEnrollment>(\n\t\t\tthis.db.prepare(AUTH_CONTROLLER_ENROLLMENT_SQL).bind(review.groupId, review.deviceId),\n\t\t);\n\t\tif (!source) return authControllerUnavailableResult(review);\n\t\tconst authority = authControllerAuthorityValues(\n\t\t\tsource,\n\t\t\tawait ed25519KeyIdForRevocation(source.public_key),\n\t\t);\n\t\tconst conflict = await firstRow<CoordinatorAuthControllerAttestation>(\n\t\t\tthis.db.prepare(AUTH_CONTROLLER_CONFLICT_SQL).bind(...authControllerConflictValues(review)),\n\t\t);\n\t\tif (conflict) return this.resolveAuthControllerRetry(review, authority);\n\t\tconst consistency = await this.prepareAuthControllerConsistency(review);\n\t\tif (!consistency) return authControllerUnavailableResult(review);\n\t\ttry {\n\t\t\tconst statement = withNegativeOwnerConsistency(\n\t\t\t\t{\n\t\t\t\t\tsql: authControllerReviewSql(AUTH_CONTROLLER_INSERT_SQL, review),\n\t\t\t\t\tvalues: authControllerInsertValues(review, nowISO(), authority),\n\t\t\t\t},\n\t\t\t\tconsistency,\n\t\t\t);\n\t\t\tconst inserted = await runChanges(this.db.prepare(statement.sql).bind(...statement.values));\n\t\t\tif (inserted === 0) {\n\t\t\t\t// The winner changes the evidence pin. Recapture without accepting new conflicts.\n\t\t\t\tconst retryConsistency = await this.prepareAuthControllerConsistency(review);\n\t\t\t\tif (!retryConsistency) return authControllerUnavailableResult(review);\n\t\t\t\treturn this.resolveAuthControllerRetry(review, authority, retryConsistency);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (!isAuthControllerUniqueError(error)) throw error;\n\t\t\treturn this.resolveAuthControllerRetry(review, authority);\n\t\t}\n\t\tconst attestation = await firstRow<CoordinatorAuthControllerAttestation>(\n\t\t\tthis.db\n\t\t\t\t.prepare(AUTH_CONTROLLER_ACTIVE_SQL)\n\t\t\t\t.bind(review.coordinatorId, review.attestationId, ...authority),\n\t\t);\n\t\tif (!attestation) throw new Error(\"auth_controller_persistence_incomplete\");\n\t\treturn { kind: \"created\", attestation };\n\t}\n\n\tprivate prepareAuthControllerConsistency(review: CoordinatorAuthControllerReviewInput) {\n\t\treturn prepareNegativeOwnerConsistency(\n\t\t\t{\n\t\t\t\tfirst: <T>({ sql, values }: AuthLinkStatement) =>\n\t\t\t\t\tthis.db\n\t\t\t\t\t\t.prepare(sql)\n\t\t\t\t\t\t.bind(...values)\n\t\t\t\t\t\t.first<T>(),\n\t\t\t\tall: async <T>({ sql, values }: AuthLinkStatement) => {\n\t\t\t\t\tconst result = await this.db\n\t\t\t\t\t\t.prepare(sql)\n\t\t\t\t\t\t.bind(...values)\n\t\t\t\t\t\t.all<T>();\n\t\t\t\t\tif (!Array.isArray(result.results)) throw new Error(\"ownership_evidence_unavailable\");\n\t\t\t\t\treturn result.results;\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\t...review,\n\t\t\t\townerIdentityId: review.identityId,\n\t\t\t\tenrollment: { groupId: review.groupId },\n\t\t\t\tverifiedHistory: review.verifiedSnapshot?.legacyHistory,\n\t\t\t},\n\t\t);\n\t}\n\n\tprivate async resolveAuthControllerRetry(\n\t\tinput: CoordinatorAuthControllerReviewInput,\n\t\tauthority: (string | null)[],\n\t\tconsistency?: AuthLinkStatement,\n\t): Promise<CoordinatorAuthControllerCreateResult> {\n\t\tconst eligible = await firstRow<{ eligible: number }>(\n\t\t\tthis.db\n\t\t\t\t.prepare(authControllerReviewSql(AUTH_CONTROLLER_RETRY_ELIGIBLE_SQL, input))\n\t\t\t\t.bind(...authControllerRetryEligibleValues(input, authority)),\n\t\t);\n\t\tif (!eligible) return authControllerUnavailableResult(input);\n\t\tconst row = await firstRow<CoordinatorAuthControllerAttestation>(\n\t\t\tthis.db.prepare(AUTH_CONTROLLER_CONFLICT_SQL).bind(...authControllerConflictValues(input)),\n\t\t);\n\t\tconst result = authControllerRetryResult(input, row);\n\t\tif (result.kind === \"rejected\") return result;\n\t\tlet statement: AuthLinkStatement = {\n\t\t\tsql: authControllerReviewSql(AUTH_CONTROLLER_RETRY_ACTIVE_SQL, input),\n\t\t\tvalues: authControllerRetryActiveValues(input, authority),\n\t\t};\n\t\tif (consistency) statement = withNegativeOwnerConsistency(statement, consistency);\n\t\tconst active = await firstRow<CoordinatorAuthControllerAttestation>(\n\t\t\tthis.db.prepare(statement.sql).bind(...statement.values),\n\t\t);\n\t\t// A change after the conflict read makes this review stale, including revocation.\n\t\tif (!active)\n\t\t\treturn {\n\t\t\t\tkind: \"rejected\",\n\t\t\t\terror: input.verifiedSnapshot ? \"review_stale\" : \"enrollment_mismatch\",\n\t\t\t};\n\t\treturn authControllerRetryResult(input, active);\n\t}\n\n\tasync getActiveAuthControllerAttestation(\n\t\tcoordinatorId: string,\n\t\tattestationId: string,\n\t): Promise<CoordinatorAuthControllerAttestation | null> {\n\t\tif (!isAuthControllerId(coordinatorId) || !isAuthControllerId(attestationId)) return null;\n\t\tconst source = await firstRow<CoordinatorEnrollment>(\n\t\t\tthis.db.prepare(AUTH_CONTROLLER_CURRENT_ENROLLMENT_SQL).bind(coordinatorId, attestationId),\n\t\t);\n\t\tif (!source) return null;\n\t\tconst authority = authControllerAuthorityValues(\n\t\t\tsource,\n\t\t\tawait ed25519KeyIdForRevocation(source.public_key),\n\t\t);\n\t\treturn firstRow<CoordinatorAuthControllerAttestation>(\n\t\t\tthis.db.prepare(AUTH_CONTROLLER_ACTIVE_SQL).bind(coordinatorId, attestationId, ...authority),\n\t\t);\n\t}\n\n\tasync readAuthControllerAttestationForSnapshot(\n\t\tinput: CoordinatorAuthControllerReviewInput,\n\t): Promise<CoordinatorAuthControllerAttestation | null> {\n\t\tconst review = captureAuthControllerReview(input);\n\t\tif (!review?.verifiedSnapshot?.accountOwnerTarget) return null;\n\t\tconst source = await firstRow<CoordinatorEnrollment>(\n\t\t\tthis.db.prepare(AUTH_CONTROLLER_ENROLLMENT_SQL).bind(review.groupId, review.deviceId),\n\t\t);\n\t\tif (!source) return null;\n\t\tconst authority = authControllerAuthorityValues(\n\t\t\tsource,\n\t\t\tawait ed25519KeyIdForRevocation(source.public_key),\n\t\t);\n\t\treturn firstRow<CoordinatorAuthControllerAttestation>(\n\t\t\tthis.db\n\t\t\t\t.prepare(authControllerReviewSql(AUTH_CONTROLLER_RETRY_ACTIVE_SQL, review))\n\t\t\t\t.bind(...authControllerRetryActiveValues(review, authority)),\n\t\t);\n\t}\n\n\tasync hasAuthControllerSubjectOwnerConflict(\n\t\tinput: CoordinatorAuthControllerSubjectOwnerInput,\n\t): Promise<boolean> {\n\t\treturn !!(await firstRow<{ conflict: number }>(\n\t\t\tthis.db\n\t\t\t\t.prepare(AUTH_CONTROLLER_SUBJECT_OWNER_CONFLICT_SQL)\n\t\t\t\t.bind(...authControllerSubjectOwnerConflictValues(input)),\n\t\t));\n\t}\n\n\tasync revokeAuthControllerAttestation(\n\t\tcoordinatorId: string,\n\t\tattestationId: string,\n\t): Promise<boolean> {\n\t\tif (!isAuthControllerId(coordinatorId) || !isAuthControllerId(attestationId)) return false;\n\t\treturn (\n\t\t\t(await runChanges(\n\t\t\t\tthis.db.prepare(AUTH_CONTROLLER_REVOKE_SQL).bind(nowISO(), coordinatorId, attestationId),\n\t\t\t)) > 0\n\t\t);\n\t}\n\n\tasync createGroup(_groupId: string, _displayName?: string | null): Promise<void> {\n\t\tawait this.db\n\t\t\t.prepare(\n\t\t\t\t\"INSERT OR IGNORE INTO groups(group_id, display_name, archived_at, created_at) VALUES (?, ?, NULL, ?)\",\n\t\t\t)\n\t\t\t.bind(_groupId, _displayName ?? null, nowISO())\n\t\t\t.run();\n\t}\n\n\tasync getGroup(_groupId: string): Promise<CoordinatorGroup | null> {\n\t\tconst row = await firstRow<CoordinatorGroup>(\n\t\t\tthis.db\n\t\t\t\t.prepare(\n\t\t\t\t\t\"SELECT group_id, display_name, archived_at, created_at FROM groups WHERE group_id = ?\",\n\t\t\t\t)\n\t\t\t\t.bind(_groupId),\n\t\t);\n\t\treturn row ? rowToRecord<CoordinatorGroup>(row) : null;\n\t}\n\n\tasync listGroups(_includeArchived = false): Promise<CoordinatorGroup[]> {\n\t\tconst where = _includeArchived ? \"\" : \"WHERE archived_at IS NULL\";\n\t\treturn (\n\t\t\tawait allRows<CoordinatorGroup>(\n\t\t\t\tthis.db.prepare(\n\t\t\t\t\t`SELECT group_id, display_name, archived_at, created_at FROM groups ${where} ORDER BY created_at ASC`,\n\t\t\t\t),\n\t\t\t)\n\t\t).map((row) => rowToRecord<CoordinatorGroup>(row));\n\t}\n\n\tasync renameGroup(_groupId: string, _displayName: string): Promise<boolean> {\n\t\treturn (\n\t\t\t(await runChanges(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(\"UPDATE groups SET display_name = ? WHERE group_id = ?\")\n\t\t\t\t\t.bind(_displayName, _groupId),\n\t\t\t)) > 0\n\t\t);\n\t}\n\n\tasync archiveGroup(_groupId: string, _archivedAt = nowISO()): Promise<boolean> {\n\t\treturn (\n\t\t\t(await runChanges(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(\"UPDATE groups SET archived_at = ? WHERE group_id = ? AND archived_at IS NULL\")\n\t\t\t\t\t.bind(_archivedAt, _groupId),\n\t\t\t)) > 0\n\t\t);\n\t}\n\n\tasync unarchiveGroup(_groupId: string): Promise<boolean> {\n\t\treturn (\n\t\t\t(await runChanges(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\"UPDATE groups SET archived_at = NULL WHERE group_id = ? AND archived_at IS NOT NULL\",\n\t\t\t\t\t)\n\t\t\t\t\t.bind(_groupId),\n\t\t\t)) > 0\n\t\t);\n\t}\n\n\tasync enrollDevice(_groupId: string, _opts: CoordinatorEnrollDeviceInput): Promise<void> {\n\t\tconst { deviceId, publicKey, fingerprint, identityId, displayName } = captureLegacyEnrollment(\n\t\t\t_groupId,\n\t\t\t_opts,\n\t\t);\n\t\ttry {\n\t\t\tconst currentPublicKey = captureLegacyEnrollmentPublicKey(\n\t\t\t\tawait firstRow<unknown>(\n\t\t\t\t\tthis.db\n\t\t\t\t\t\t.prepare(\"SELECT public_key FROM enrolled_devices WHERE group_id = ? AND device_id = ?\")\n\t\t\t\t\t\t.bind(_groupId, deviceId),\n\t\t\t\t),\n\t\t\t);\n\t\t\tconst keyId = await ed25519KeyIdForRevocation(publicKey);\n\t\t\tconst currentKeyId =\n\t\t\t\tcurrentPublicKey === null ? null : await ed25519KeyIdForRevocation(currentPublicKey);\n\t\t\tconst source = [currentPublicKey, _groupId, deviceId, _groupId, deviceId, currentPublicKey];\n\t\t\tconst result = await this.db\n\t\t\t\t.prepare(LEGACY_ENROLLMENT_WRITE_SQL)\n\t\t\t\t.bind(\n\t\t\t\t\t_groupId,\n\t\t\t\t\tdeviceId,\n\t\t\t\t\tpublicKey,\n\t\t\t\t\tfingerprint,\n\t\t\t\t\tidentityId ?? null,\n\t\t\t\t\tdisplayName ?? null,\n\t\t\t\t\tnowISO(),\n\t\t\t\t\tdeviceId,\n\t\t\t\t\tkeyId,\n\t\t\t\t\tdeviceId,\n\t\t\t\t\tkeyId,\n\t\t\t\t\tdeviceId,\n\t\t\t\t\tcurrentKeyId,\n\t\t\t\t\t...source,\n\t\t\t\t\tdeviceId,\n\t\t\t\t\tkeyId,\n\t\t\t\t\tdeviceId,\n\t\t\t\t\tcurrentKeyId,\n\t\t\t\t\tcurrentPublicKey,\n\t\t\t\t)\n\t\t\t\t.run();\n\t\t\tif (legacyDeviceWriteChanges(result) === 1) return;\n\t\t\tconst denial = await firstRow<unknown>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(LEGACY_ENROLLMENT_DENIAL_SQL)\n\t\t\t\t\t.bind(deviceId, keyId, deviceId, keyId, deviceId, currentKeyId, ...source),\n\t\t\t);\n\t\t\tthrow new Error(legacyDeviceDenial(denial));\n\t\t} catch (error) {\n\t\t\tlegacyDeviceAuthorizationFailure(error);\n\t\t}\n\t}\n\n\tasync listEnrolledDevices(\n\t\t_groupId: string,\n\t\t_includeDisabled?: boolean,\n\t): Promise<CoordinatorEnrollment[]> {\n\t\tconst where = _includeDisabled ? \"\" : \"AND enrolled_devices.enabled = 1\";\n\t\tconst rows = (\n\t\t\tawait allRows<CoordinatorEnrollment>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT ${ENROLLMENT_PRESENCE_COLUMNS}, ${ENROLLMENT_OWNERSHIP_COLUMNS}\n\t\t\t\t\t\t FROM enrolled_devices\n\t\t\t\t\t\t LEFT JOIN presence_records\n\t\t\t\t\t\t ON presence_records.group_id = enrolled_devices.group_id\n\t\t\t\t\t\t AND presence_records.device_id = enrolled_devices.device_id\n\t\t\t\t\t\t WHERE enrolled_devices.group_id = ? ${where}\n\t\t\t\t\t\t ORDER BY enrolled_devices.created_at ASC, enrolled_devices.device_id ASC`)\n\t\t\t\t\t.bind(_groupId),\n\t\t\t)\n\t\t).map(rowToEnrollmentWithPresence);\n\t\treturn withEnrollmentOwnership(rows);\n\t}\n\n\tasync getEnrollment(\n\t\t_groupId: string,\n\t\t_deviceId: string,\n\t\t_includeDisabled = false,\n\t): Promise<CoordinatorEnrollment | null> {\n\t\tconst enabledClause = _includeDisabled ? \"\" : \"AND enabled = 1\";\n\t\tconst row = await firstRow<CoordinatorEnrollment>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT ${ENROLLMENT_COLUMNS}\n\t\t\t\t\t FROM enrolled_devices\n\t\t\t\t\t WHERE group_id = ? AND device_id = ? ${enabledClause}`)\n\t\t\t\t.bind(_groupId, _deviceId),\n\t\t);\n\t\treturn row ? rowToRecord<CoordinatorEnrollment>(row) : null;\n\t}\n\n\tasync renameDevice(_groupId: string, _deviceId: string, _displayName: string): Promise<boolean> {\n\t\treturn (\n\t\t\t(await runChanges(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`UPDATE enrolled_devices SET display_name = ?\n\t\t\t\t\t WHERE group_id = ? AND device_id = ?`)\n\t\t\t\t\t.bind(_displayName, _groupId, _deviceId),\n\t\t\t)) > 0\n\t\t);\n\t}\n\n\tasync setDeviceEnabled(_groupId: string, _deviceId: string, _enabled: boolean): Promise<boolean> {\n\t\tassertLegacyDeviceScope(_groupId, _deviceId);\n\t\tif (typeof _enabled !== \"boolean\") throw new Error(\"invalid_input\");\n\t\tif (_enabled) {\n\t\t\ttry {\n\t\t\t\tconst enrollment = await firstRow<{ public_key: string }>(\n\t\t\t\t\tthis.db\n\t\t\t\t\t\t.prepare(\"SELECT public_key FROM enrolled_devices WHERE group_id = ? AND device_id = ?\")\n\t\t\t\t\t\t.bind(_groupId, _deviceId),\n\t\t\t\t);\n\t\t\t\tif (enrollment === null) return false;\n\t\t\t\tif (!enrollment) throw new Error(\"device_ownership_authorization_unavailable\");\n\t\t\t\tconst publicKey = enrollment.public_key;\n\t\t\t\tif (typeof publicKey !== \"string\")\n\t\t\t\t\tthrow new Error(\"device_ownership_authorization_unavailable\");\n\t\t\t\tconst keyId = await ed25519KeyIdForRevocation(publicKey);\n\t\t\t\tconst result = await this.db\n\t\t\t\t\t.prepare(`UPDATE enrolled_devices SET enabled = 1\n\t\t\t\t\t\tWHERE group_id = ? AND device_id = ? AND public_key = ?\n\t\t\t\t\t\tAND NOT ${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL}\n\t\t\t\t\t\tAND NOT ${DEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL}`)\n\t\t\t\t\t.bind(_groupId, _deviceId, publicKey, _deviceId, keyId, _deviceId, keyId)\n\t\t\t\t\t.run();\n\t\t\t\tif (legacyDeviceWriteChanges(result) === 1) return true;\n\t\t\t\tconst denial = legacyDeviceDenial(\n\t\t\t\t\tawait firstRow<unknown>(\n\t\t\t\t\t\tthis.db.prepare(LEGACY_DEVICE_DENIAL_SQL).bind(_deviceId, keyId, _deviceId, keyId),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\tif (denial === \"device_ownership_requires_verified_identity\") throw new Error(denial);\n\t\t\t\treturn false;\n\t\t\t} catch (error) {\n\t\t\t\tlegacyDeviceAuthorizationFailure(error);\n\t\t\t}\n\t\t}\n\t\treturn (\n\t\t\t(await runChanges(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`UPDATE enrolled_devices SET enabled = ?\n\t\t\t\t\t WHERE group_id = ? AND device_id = ?`)\n\t\t\t\t\t.bind(_enabled ? 1 : 0, _groupId, _deviceId),\n\t\t\t)) > 0\n\t\t);\n\t}\n\n\tasync removeDevice(_groupId: string, _deviceId: string): Promise<boolean> {\n\t\t// Presence, reciprocal approvals, and the enrollment row must be removed\n\t\t// all-or-nothing. Running them as independent statements can orphan rows\n\t\t// (an enrolled device with no presence/approvals, or vice versa) if any\n\t\t// one statement fails. D1 batch() is the transaction boundary here, the\n\t\t// same convention used for audited membership changes via runAuditedBatch.\n\t\tif (!this.db.batch) {\n\t\t\tthrow new Error(\"D1 batch support is required for atomic device removal.\");\n\t\t}\n\t\tconst results = await this.db.batch([\n\t\t\tthis.db\n\t\t\t\t.prepare(\"DELETE FROM presence_records WHERE group_id = ? AND device_id = ?\")\n\t\t\t\t.bind(_groupId, _deviceId),\n\t\t\tthis.db\n\t\t\t\t.prepare(\n\t\t\t\t\t\"DELETE FROM coordinator_reciprocal_approvals WHERE group_id = ? AND (requesting_device_id = ? OR requested_device_id = ?)\",\n\t\t\t\t)\n\t\t\t\t.bind(_groupId, _deviceId, _deviceId),\n\t\t\tthis.db\n\t\t\t\t.prepare(\"DELETE FROM enrolled_devices WHERE group_id = ? AND device_id = ?\")\n\t\t\t\t.bind(_groupId, _deviceId),\n\t\t]);\n\t\t// The enrolled_devices delete is the last statement; its changes() tells us\n\t\t// whether the device existed, preserving the boolean return contract.\n\t\treturn batchResultChanges(results[2]) > 0;\n\t}\n\n\tasync recordNonce(_deviceId: string, _nonce: string, _createdAt: string): Promise<boolean> {\n\t\treturn (\n\t\t\t(await runChanges(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\"INSERT OR IGNORE INTO request_nonces(device_id, nonce, created_at) VALUES (?, ?, ?)\",\n\t\t\t\t\t)\n\t\t\t\t\t.bind(_deviceId, _nonce, _createdAt),\n\t\t\t)) > 0\n\t\t);\n\t}\n\n\tasync cleanupNonces(_cutoff: string): Promise<void> {\n\t\tawait this.db.prepare(\"DELETE FROM request_nonces WHERE created_at < ?\").bind(_cutoff).run();\n\t}\n\n\tasync createDeviceRevocation(input: CoordinatorCreateDeviceRevocationInput) {\n\t\treturn this.deviceRevocations.createDeviceRevocation(input);\n\t}\n\n\tasync listDeviceRevocations(input: CoordinatorListDeviceRevocationsInput) {\n\t\treturn this.deviceRevocations.listDeviceRevocations(input);\n\t}\n\n\tasync recordAuthorizedNonce(input: CoordinatorRecordAuthorizedNonceInput) {\n\t\treturn this.deviceRevocations.recordAuthorizedNonce(input);\n\t}\n\n\tasync createInvite(_opts: CoordinatorCreateInviteInput): Promise<CoordinatorInvite> {\n\t\tconst now = nowISO();\n\t\tconst inviteId = tokenUrlSafe(12);\n\t\tconst token = tokenUrlSafe(24);\n\t\tconst digest = await tokenDigest(token);\n\t\tconst expiresAt = normalizeInviteExpiresAt(_opts.expiresAt);\n\t\tconst group = await this.getGroup(_opts.groupId);\n\t\tconst operationId = String(_opts.operationId ?? \"\").trim() || null;\n\t\tconst reviewedProjectSetDigest = String(_opts.reviewedProjectSetDigest ?? \"\").trim() || null;\n\t\tconst metadata = await normalizeCoordinatorInviteMetadata(_opts);\n\t\tconst assignedIdentityId =\n\t\t\tmetadata.inviteKind === \"team_member\" ? `identity:${tokenUrlSafe(18)}` : null;\n\t\tif (Boolean(operationId) !== Boolean(reviewedProjectSetDigest)) {\n\t\t\tthrow new Error(\"operationId and reviewedProjectSetDigest must be provided together.\");\n\t\t}\n\t\tconst readOperationInvite = async (): Promise<CoordinatorInvite | null> => {\n\t\t\tif (!operationId) return null;\n\t\t\tconst existing = await firstRow<CoordinatorInvite>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT ${INVITE_COLUMNS} FROM coordinator_invites WHERE operation_id = ?`)\n\t\t\t\t\t.bind(operationId),\n\t\t\t);\n\t\t\tif (!existing) return null;\n\t\t\t// Pre-consume create retries can recover the bearer token. Successful\n\t\t\t// consume clears it, so post-consume create retries fail closed.\n\t\t\tif (existing.consumed_at) throw new Error(\"invite_already_bound\");\n\t\t\tif (\n\t\t\t\texisting.group_id !== _opts.groupId ||\n\t\t\t\texisting.policy !== _opts.policy ||\n\t\t\t\texisting.invite_kind !== metadata.inviteKind ||\n\t\t\t\texisting.reviewed_project_set_digest !== reviewedProjectSetDigest ||\n\t\t\t\texisting.inviter_actor_id !== (String(_opts.inviterActorId ?? \"\").trim() || null) ||\n\t\t\t\texisting.inviter_display_name !== (String(_opts.inviterDisplayName ?? \"\").trim() || null) ||\n\t\t\t\texisting.inviter_device_id !== (String(_opts.inviterDeviceId ?? \"\").trim() || null) ||\n\t\t\t\texisting.pending_person_id !== (String(_opts.pendingPersonId ?? \"\").trim() || null) ||\n\t\t\t\texisting.project_summaries_json !==\n\t\t\t\t\t(_opts.projectSummaries ? JSON.stringify(_opts.projectSummaries) : null) ||\n\t\t\t\texisting.project_intent_json !==\n\t\t\t\t\t(_opts.projectIntent ? JSON.stringify(_opts.projectIntent) : null) ||\n\t\t\t\texisting.policy_team_id !== metadata.policyTeamId ||\n\t\t\t\texisting.target_identity_id !== metadata.targetIdentityId ||\n\t\t\t\texisting.reviewed_preview_digest !== metadata.reviewedPreviewDigest ||\n\t\t\t\texisting.reviewed_intent_json !== metadata.reviewedIntentJson\n\t\t\t) {\n\t\t\t\tthrow new Error(\"invite_operation_intent_conflict\");\n\t\t\t}\n\t\t\treturn rowToRecord<CoordinatorInvite>(existing);\n\t\t};\n\t\tconst renewOperationInvite = async (\n\t\t\texisting: CoordinatorInvite,\n\t\t): Promise<CoordinatorInvite> => {\n\t\t\tif (!existing.revoked_at && existing.expires_at > now) return existing;\n\t\t\tawait runChanges(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`UPDATE coordinator_invites\n\t\t\t\t\t\tSET token = ?, token_digest = ?, expires_at = ?, created_at = ?, created_by = ?,\n\t\t\t\t\t\t\tteam_name_snapshot = ?, revoked_at = NULL\n\t\t\t\t\t\tWHERE operation_id = ? AND token = ?\n\t\t\t\t\t\t AND (revoked_at IS NOT NULL OR expires_at <= ?)`)\n\t\t\t\t\t.bind(\n\t\t\t\t\t\ttoken,\n\t\t\t\t\t\tdigest,\n\t\t\t\t\t\texpiresAt,\n\t\t\t\t\t\tnow,\n\t\t\t\t\t\t_opts.createdBy ?? null,\n\t\t\t\t\t\tgroup?.display_name ?? null,\n\t\t\t\t\t\toperationId,\n\t\t\t\t\t\texisting.token,\n\t\t\t\t\t\tnow,\n\t\t\t\t\t),\n\t\t\t);\n\t\t\tconst renewed = await readOperationInvite();\n\t\t\tif (!renewed) throw new Error(\"invite_operation_reissue_failed\");\n\t\t\treturn renewed;\n\t\t};\n\t\tif (operationId) {\n\t\t\tconst existing = await readOperationInvite();\n\t\t\tif (existing) return await renewOperationInvite(existing);\n\t\t}\n\t\ttry {\n\t\t\tawait this.db\n\t\t\t\t.prepare(`INSERT INTO coordinator_invites(\n\t\t\t\tinvite_id, group_id, token, policy, expires_at, created_at, created_by,\n\t\t\t\tteam_name_snapshot, revoked_at, operation_id, reviewed_project_set_digest,\n\t\t\t\ttoken_digest, inviter_actor_id, inviter_display_name, inviter_device_id,\n\t\t\t\tpending_person_id, project_summaries_json, project_intent_json, trust_state,\n\t\t\t\tinvite_kind, policy_team_id, target_identity_id, assigned_identity_id,\n\t\t\t\treviewed_preview_digest, reviewed_intent_json\n\t\t\t) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)\n\t\t\t\t.bind(\n\t\t\t\t\tinviteId,\n\t\t\t\t\t_opts.groupId,\n\t\t\t\t\ttoken,\n\t\t\t\t\t_opts.policy,\n\t\t\t\t\texpiresAt,\n\t\t\t\t\tnow,\n\t\t\t\t\t_opts.createdBy ?? null,\n\t\t\t\t\tgroup?.display_name ?? null,\n\t\t\t\t\toperationId,\n\t\t\t\t\treviewedProjectSetDigest,\n\t\t\t\t\tdigest,\n\t\t\t\t\tString(_opts.inviterActorId ?? \"\").trim() || null,\n\t\t\t\t\tString(_opts.inviterDisplayName ?? \"\").trim() || null,\n\t\t\t\t\tString(_opts.inviterDeviceId ?? \"\").trim() || null,\n\t\t\t\t\tString(_opts.pendingPersonId ?? \"\").trim() || null,\n\t\t\t\t\t_opts.projectSummaries ? JSON.stringify(_opts.projectSummaries) : null,\n\t\t\t\t\t_opts.projectIntent ? JSON.stringify(_opts.projectIntent) : null,\n\t\t\t\t\toperationId ? \"pending\" : null,\n\t\t\t\t\tmetadata.inviteKind,\n\t\t\t\t\tmetadata.policyTeamId,\n\t\t\t\t\tmetadata.targetIdentityId,\n\t\t\t\t\tassignedIdentityId,\n\t\t\t\t\tmetadata.reviewedPreviewDigest,\n\t\t\t\t\tmetadata.reviewedIntentJson,\n\t\t\t\t)\n\t\t\t\t.run();\n\t\t} catch (error) {\n\t\t\tif (operationId) {\n\t\t\t\tconst existing = await readOperationInvite();\n\t\t\t\tif (existing) return await renewOperationInvite(existing);\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t\tconst row = await firstRow<CoordinatorInvite>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT ${INVITE_COLUMNS} FROM coordinator_invites WHERE invite_id = ?`)\n\t\t\t\t.bind(inviteId),\n\t\t);\n\t\treturn rowToRecord<CoordinatorInvite>(row);\n\t}\n\n\tasync getInviteByToken(_token: string): Promise<CoordinatorInvite | null> {\n\t\tconst digest = await tokenDigest(_token);\n\t\tconst row = await firstRow<CoordinatorInvite>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT ${INVITE_COLUMNS}\n\t\t\t\t\t FROM coordinator_invites\n\t\t\t\t\t WHERE (token_digest = ? OR token = ?)\n\t\t\t\t\t AND revoked_at IS NULL\n\t\t\t\t\t AND expires_at > ?`)\n\t\t\t\t.bind(digest, _token, nowISO()),\n\t\t);\n\t\treturn row ? rowToRecord<CoordinatorInvite>(row) : null;\n\t}\n\n\tasync getInviteByTokenForInspection(_token: string): Promise<CoordinatorInvite | null> {\n\t\tconst digest = await tokenDigest(_token);\n\t\tconst row = await firstRow<CoordinatorInvite>(\n\t\t\tthis.db\n\t\t\t\t.prepare(\n\t\t\t\t\t`SELECT ${INVITE_COLUMNS} FROM coordinator_invites WHERE token_digest = ? OR token = ?`,\n\t\t\t\t)\n\t\t\t\t.bind(digest, _token),\n\t\t);\n\t\treturn row ? rowToRecord<CoordinatorInvite>(row) : null;\n\t}\n\n\tasync inspectRecipientInvite(\n\t\t_opts: CoordinatorInspectRecipientInviteInput,\n\t): Promise<CoordinatorRecipientInviteInspection | null> {\n\t\tconst invite = await this.getInviteByTokenForInspection(_opts.token);\n\t\tif (!invite) return null;\n\t\tconst inspection = await inspectInvite(invite);\n\t\tif (!inspection) return null;\n\t\tif (invite.revoked_at) throw new Error(\"invite_invalid\");\n\t\tif (\n\t\t\t!invite.consumed_at &&\n\t\t\tnew Date(invite.expires_at) <= new Date(normalizeInviteExpiresAt(_opts.now))\n\t\t) {\n\t\t\tthrow new Error(\"invite_expired\");\n\t\t}\n\t\tconst group = await this.getGroup(invite.group_id);\n\t\tif (!group) throw new Error(\"group_not_found\");\n\t\tif (group.archived_at) throw new Error(\"group_archived\");\n\t\treturn inspection;\n\t}\n\n\tprivate async recoverRecipientInviteGrant(\n\t\tinvite: CoordinatorInvite,\n\t\topts: CoordinatorConsumeRecipientInviteInput,\n\t\tguard: {\n\t\t\tsql: string;\n\t\t\tvalues: unknown[];\n\t\t\tconsumedAt: string;\n\t\t\tnegative?: AuthLinkStatement;\n\t\t\tassertEligible: (options: { requireBinding: boolean }) => Promise<void>;\n\t\t},\n\t): Promise<void> {\n\t\tif (!this.db.batch)\n\t\t\tthrow new Error(\"D1 batch support is required for atomic bootstrap grant recovery.\");\n\t\tawait runRecipientInviteBatch(\n\t\t\tthis.db,\n\t\t\t[\n\t\t\t\tprepareRecipientOwnerStatement(\n\t\t\t\t\tthis.db,\n\t\t\t\t\t`UPDATE coordinator_invites SET bootstrap_grant_id = ?,\n\t\t\t\ttrust_state = 'bootstrap_grant_created'\n\t\t\t\tWHERE invite_id = ? AND invite_kind = 'add_device'\n\t\t\t\tAND bootstrap_grant_id IS NULL AND inviter_device_id IS NOT NULL\n\t\t\t\tAND bound_device_id = ? AND recipient_actor_id = ? AND expires_at > ?\n\t\t\t\tAND EXISTS (SELECT 1 FROM enrolled_devices e\n\t\t\t\t\tWHERE e.group_id = coordinator_invites.group_id\n\t\t\t\t\tAND e.device_id = coordinator_invites.inviter_device_id AND e.enabled = 1)\n\t\t\t\tAND ${guard.sql}`,\n\t\t\t\t\tguard.negative,\n\t\t\t\t).bind(\n\t\t\t\t\ttokenUrlSafe(12),\n\t\t\t\t\tinvite.invite_id,\n\t\t\t\t\topts.deviceId,\n\t\t\t\t\topts.identityId,\n\t\t\t\t\tguard.consumedAt,\n\t\t\t\t\t...guard.values,\n\t\t\t\t),\n\t\t\t\tprepareRecipientOwnerStatement(\n\t\t\t\t\tthis.db,\n\t\t\t\t\t`INSERT OR IGNORE INTO coordinator_bootstrap_grants(\n\t\t\t\tgrant_id, group_id, seed_device_id, worker_device_id, expires_at,\n\t\t\t\tcreated_at, created_by, revoked_at\n\t\t\t) SELECT i.bootstrap_grant_id, i.group_id, i.inviter_device_id, i.bound_device_id,\n\t\t\t\ti.expires_at, ?, i.recipient_actor_id, NULL FROM coordinator_invites i\n\t\t\tJOIN enrolled_devices e ON e.group_id = i.group_id\n\t\t\t\tAND e.device_id = i.inviter_device_id AND e.enabled = 1\n\t\t\tWHERE i.invite_id = ? AND i.invite_kind = 'add_device'\n\t\t\t\tAND i.bootstrap_grant_id IS NOT NULL AND i.bound_device_id = ?\n\t\t\t\tAND ${guard.sql}`,\n\t\t\t\t\tguard.negative,\n\t\t\t\t).bind(guard.consumedAt, invite.invite_id, opts.deviceId, ...guard.values),\n\t\t\t],\n\t\t\tguard,\n\t\t);\n\t}\n\n\tprivate async prepareEligibleRecipientOwner(opts: CoordinatorConsumeRecipientInviteInput) {\n\t\tconst backend = createRecipientOwnerBackend(this.db);\n\t\tconst consistency = await prepareRecipientOwnerConsistency(backend, opts);\n\t\tif (!consistency) throw new Error(\"device_ownership_authorization_unavailable\");\n\t\tawait assertRecipientOwnerConsistency(backend, consistency);\n\t\treturn consistency;\n\t}\n\n\tasync consumeRecipientInvite(\n\t\tinput: CoordinatorConsumeRecipientInviteInput,\n\t): Promise<CoordinatorRecipientInviteAcceptance> {\n\t\tconst _opts = { ...input };\n\t\tconst consumedAt = normalizeInviteExpiresAt(_opts.now);\n\t\tconst recipientDisplayName = _opts.recipientDisplayName ?? null;\n\t\tconst deviceDisplayName = _opts.deviceDisplayName ?? null;\n\t\tvalidateRecipientOwnerInput(_opts);\n\t\tconst digest = await tokenDigest(_opts.token);\n\t\tconst initial = structuredClone(await this.getInviteByTokenForInspection(_opts.token));\n\t\tconst inspection = initial ? await inspectInvite(initial) : null;\n\t\tif (!initial || !inspection || inspection.kind !== _opts.inviteKind || initial.revoked_at) {\n\t\t\tthrow new Error(\"invite_invalid\");\n\t\t}\n\t\tconst group = await this.getGroup(initial.group_id);\n\t\tif (!group) throw new Error(\"group_not_found\");\n\t\tif (group.archived_at) throw new Error(\"group_archived\");\n\t\tif (!initial.consumed_at && new Date(initial.expires_at) <= new Date(consumedAt)) {\n\t\t\tthrow new Error(\"invite_expired\");\n\t\t}\n\t\tif (fingerprintPublicKey(_opts.publicKey) !== _opts.fingerprint) {\n\t\t\tthrow new Error(\"fingerprint_mismatch\");\n\t\t}\n\t\tconst authoritativeIdentityId = recipientInviteAuthoritativeIdentityId(inspection);\n\t\tif (authoritativeIdentityId !== _opts.identityId) {\n\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\t}\n\t\tvalidateRecipientInviteBinding(initial, _opts, { requireBinding: false });\n\t\tconst existingEnrollment = await firstRow<CoordinatorEnrollment>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT ${ENROLLMENT_COLUMNS}\n\t\t\t\t\tFROM enrolled_devices WHERE group_id = ? AND device_id = ?`)\n\t\t\t\t.bind(initial.group_id, _opts.deviceId),\n\t\t);\n\t\tvalidateRecipientEnrollmentTuple(existingEnrollment, _opts);\n\t\tconst {\n\t\t\teligibilitySql,\n\t\t\teligibilityValues,\n\t\t\tboundEligibilitySql,\n\t\t\tboundEligibilityValues,\n\t\t\tassertEligible,\n\t\t} = await prepareRecipientInviteGuards(this.db, initial, _opts);\n\t\tawait assertEligible({ requireBinding: Boolean(initial.consumed_at) });\n\t\tconst consistency = await this.prepareEligibleRecipientOwner(_opts);\n\t\tconst negative = consistency.retainedRecheck;\n\t\tlet changed = 0;\n\t\tconst bootstrapGrantId = tokenUrlSafe(12);\n\t\tif (!initial.consumed_at) {\n\t\t\tif (!this.db.batch)\n\t\t\t\tthrow new Error(\"D1 batch support is required for atomic invite consume.\");\n\t\t\tchanged = await runRecipientInviteBatch(\n\t\t\t\tthis.db,\n\t\t\t\t[\n\t\t\t\t\tprepareRecipientOwnerStatement(\n\t\t\t\t\t\tthis.db,\n\t\t\t\t\t\t`UPDATE coordinator_invites SET token = ?, consumed_at = ?, bound_device_id = ?,\n\t\t\t\t\t\tbound_public_key = ?, bound_fingerprint = ?, recipient_actor_id = ?,\n\t\t\t\t\t\trecipient_display_name = ?, recipient_device_display_name = ?\n\t\t\t\t\t\tWHERE (token_digest = ? OR token = ?) AND consumed_at IS NULL\n\t\t\t\t\t\tAND invite_id = ? AND group_id = ?\n\t\t\t\t\t\tAND revoked_at IS NULL AND expires_at > ? AND invite_kind = ?\n\t\t\t\t\t\tAND reviewed_intent_json = ? AND reviewed_preview_digest = ?\n\t\t\t\t\t\tAND ((invite_kind = 'team_member' AND assigned_identity_id = ?)\n\t\t\t\t\t\t\tOR (invite_kind = 'add_device' AND target_identity_id = ?))\n\t\t\t\t\t\tAND NOT EXISTS (\n\t\t\t\t\t\t\tSELECT 1 FROM enrolled_devices e\n\t\t\t\t\t\t\tWHERE e.group_id = coordinator_invites.group_id AND e.device_id = ?\n\t\t\t\t\t\t\t\tAND (e.public_key <> ? OR e.fingerprint <> ?\n\t\t\t\t\t\t\t\t\tOR (e.identity_id IS NOT NULL AND e.identity_id <> ?))\n\t\t\t\t\t\t)\n\t\t\t\t\t\tAND EXISTS (SELECT 1 FROM groups g WHERE g.group_id = coordinator_invites.group_id\n\t\t\t\t\t\t\tAND g.archived_at IS NULL)\n\t\t\t\t\t\tAND ${eligibilitySql}`,\n\t\t\t\t\t\tconsistency,\n\t\t\t\t\t).bind(\n\t\t\t\t\t\t`consumed:${initial.invite_id}`,\n\t\t\t\t\t\tconsumedAt,\n\t\t\t\t\t\t_opts.deviceId,\n\t\t\t\t\t\t_opts.publicKey,\n\t\t\t\t\t\t_opts.fingerprint,\n\t\t\t\t\t\tauthoritativeIdentityId,\n\t\t\t\t\t\trecipientDisplayName,\n\t\t\t\t\t\tdeviceDisplayName,\n\t\t\t\t\t\tdigest,\n\t\t\t\t\t\t_opts.token,\n\t\t\t\t\t\tinitial.invite_id,\n\t\t\t\t\t\tinitial.group_id,\n\t\t\t\t\t\tconsumedAt,\n\t\t\t\t\t\t_opts.inviteKind,\n\t\t\t\t\t\tinitial.reviewed_intent_json,\n\t\t\t\t\t\tinitial.reviewed_preview_digest,\n\t\t\t\t\t\tauthoritativeIdentityId,\n\t\t\t\t\t\tauthoritativeIdentityId,\n\t\t\t\t\t\t_opts.deviceId,\n\t\t\t\t\t\t_opts.publicKey,\n\t\t\t\t\t\t_opts.fingerprint,\n\t\t\t\t\t\tauthoritativeIdentityId,\n\t\t\t\t\t\t...eligibilityValues,\n\t\t\t\t\t),\n\t\t\t\t\tprepareRecipientOwnerStatement(\n\t\t\t\t\t\tthis.db,\n\t\t\t\t\t\t`INSERT INTO enrolled_devices(\n\t\t\t\t\t\tgroup_id, device_id, public_key, fingerprint, identity_id, display_name, enabled, created_at\n\t\t\t\t\t) SELECT i.group_id, i.bound_device_id, i.bound_public_key, i.bound_fingerprint,\n\t\t\t\t\t\ti.recipient_actor_id, i.recipient_device_display_name, 1, ? FROM coordinator_invites i\n\t\t\t\t\tJOIN groups g ON g.group_id = i.group_id AND g.archived_at IS NULL\n\t\t\t\t\tWHERE (i.token_digest = ? OR i.token = ?) AND i.bound_device_id = ?\n\t\t\t\t\t\tAND i.invite_id = ? AND i.group_id = ? AND changes() = 1\n\t\t\t\t\t\tAND i.bound_public_key = ? AND i.bound_fingerprint = ?\n\t\t\t\t\t\tAND i.recipient_actor_id = ?\n\t\t\t\t\t\tAND ${boundEligibilitySql}\n\t\t\t\t\tON CONFLICT(group_id, device_id) DO UPDATE SET\n\t\t\t\t\t\tidentity_id = COALESCE(enrolled_devices.identity_id, excluded.identity_id),\n\t\t\t\t\t\tdisplay_name = COALESCE(enrolled_devices.display_name, excluded.display_name),\n\t\t\t\t\t\tenabled = 1\n\t\t\t\t\tWHERE enrolled_devices.identity_id IS NULL\n\t\t\t\t\t\tOR enrolled_devices.identity_id = excluded.identity_id`,\n\t\t\t\t\t\tnegative,\n\t\t\t\t\t).bind(\n\t\t\t\t\t\tconsumedAt,\n\t\t\t\t\t\tdigest,\n\t\t\t\t\t\t_opts.token,\n\t\t\t\t\t\t_opts.deviceId,\n\t\t\t\t\t\tinitial.invite_id,\n\t\t\t\t\t\tinitial.group_id,\n\t\t\t\t\t\t_opts.publicKey,\n\t\t\t\t\t\t_opts.fingerprint,\n\t\t\t\t\t\tauthoritativeIdentityId,\n\t\t\t\t\t\t...boundEligibilityValues,\n\t\t\t\t\t),\n\t\t\t\t\t// Enrollment follows the winning token write. Keep bootstrap writes on\n\t\t\t\t\t// that changes() chain; a loser still needs its full pin during repair.\n\t\t\t\t\tprepareRecipientOwnerStatement(\n\t\t\t\t\t\tthis.db,\n\t\t\t\t\t\t`UPDATE coordinator_invites SET bootstrap_grant_id = ?,\n\t\t\t\t\t\ttrust_state = 'bootstrap_grant_created'\n\t\t\t\t\t\tWHERE (token_digest = ? OR token = ?) AND invite_kind = 'add_device'\n\t\t\t\t\t\tAND invite_id = ? AND group_id = ?\n\t\t\t\t\t\tAND bootstrap_grant_id IS NULL AND inviter_device_id IS NOT NULL\n\t\t\t\t\t\tAND expires_at > ?\n\t\t\t\t\t\tAND EXISTS (SELECT 1 FROM enrolled_devices e\n\t\t\t\t\t\t\tWHERE e.group_id = coordinator_invites.group_id\n\t\t\t\t\t\t\tAND e.device_id = coordinator_invites.inviter_device_id AND e.enabled = 1)\n\t\t\t\t\t\tAND changes() = 1 AND ${boundEligibilitySql}`,\n\t\t\t\t\t\tnegative,\n\t\t\t\t\t).bind(\n\t\t\t\t\t\tbootstrapGrantId,\n\t\t\t\t\t\tdigest,\n\t\t\t\t\t\t_opts.token,\n\t\t\t\t\t\tinitial.invite_id,\n\t\t\t\t\t\tinitial.group_id,\n\t\t\t\t\t\tconsumedAt,\n\t\t\t\t\t\t...boundEligibilityValues,\n\t\t\t\t\t),\n\t\t\t\t\tprepareRecipientOwnerStatement(\n\t\t\t\t\t\tthis.db,\n\t\t\t\t\t\t`INSERT OR IGNORE INTO coordinator_bootstrap_grants(\n\t\t\t\t\t\tgrant_id, group_id, seed_device_id, worker_device_id, expires_at,\n\t\t\t\t\t\tcreated_at, created_by, revoked_at\n\t\t\t\t\t) SELECT i.bootstrap_grant_id, i.group_id, i.inviter_device_id, i.bound_device_id,\n\t\t\t\t\t\ti.expires_at, ?, i.recipient_actor_id, NULL FROM coordinator_invites i\n\t\t\t\t\tJOIN enrolled_devices e ON e.group_id = i.group_id\n\t\t\t\t\t\tAND e.device_id = i.inviter_device_id AND e.enabled = 1\n\t\t\t\t\tWHERE (i.token_digest = ? OR i.token = ?) AND i.invite_kind = 'add_device'\n\t\t\t\t\t\tAND i.invite_id = ? AND i.group_id = ?\n\t\t\t\t\t\tAND i.bootstrap_grant_id IS NOT NULL AND i.bound_device_id = ?\n\t\t\t\t\t\tAND changes() = 1 AND ${boundEligibilitySql}`,\n\t\t\t\t\t\tnegative,\n\t\t\t\t\t).bind(\n\t\t\t\t\t\tconsumedAt,\n\t\t\t\t\t\tdigest,\n\t\t\t\t\t\t_opts.token,\n\t\t\t\t\t\tinitial.invite_id,\n\t\t\t\t\t\tinitial.group_id,\n\t\t\t\t\t\t_opts.deviceId,\n\t\t\t\t\t\t...boundEligibilityValues,\n\t\t\t\t\t),\n\t\t\t\t],\n\t\t\t\t{ sql: eligibilitySql, values: eligibilityValues, assertEligible, negative },\n\t\t\t);\n\t\t}\n\t\tawait assertEligible({ requireBinding: false });\n\t\tconst currentGroup = await this.getGroup(initial.group_id);\n\t\tif (!currentGroup) throw new Error(\"group_not_found\");\n\t\tif (currentGroup.archived_at) throw new Error(\"group_archived\");\n\t\tconst currentEnrollment = await firstRow<CoordinatorEnrollment>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT ${ENROLLMENT_COLUMNS}\n\t\t\t\t\tFROM enrolled_devices WHERE group_id = ? AND device_id = ?`)\n\t\t\t\t.bind(initial.group_id, _opts.deviceId),\n\t\t);\n\t\tvalidateRecipientEnrollmentTuple(currentEnrollment, _opts);\n\t\tconst saved = await this.getInviteByTokenForInspection(_opts.token);\n\t\tif (\n\t\t\t!saved ||\n\t\t\tsaved.revoked_at ||\n\t\t\t(!saved.consumed_at && new Date(saved.expires_at) <= new Date(consumedAt))\n\t\t) {\n\t\t\tthrow new Error(\"invite_invalid\");\n\t\t}\n\t\tconst savedInspection = await inspectInvite(saved);\n\t\tif (!savedInspection || savedInspection.kind !== _opts.inviteKind) {\n\t\t\tthrow new Error(\"invite_invalid\");\n\t\t}\n\t\tconst savedIdentityId = recipientInviteAuthoritativeIdentityId(savedInspection);\n\t\tif (savedIdentityId !== authoritativeIdentityId) {\n\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\t}\n\t\tconst recoveryNegative = await repairBoundRecipientInviteIdentity(\n\t\t\tthis.db,\n\t\t\t_opts,\n\t\t\tsaved,\n\t\t\t{ sql: boundEligibilitySql, values: boundEligibilityValues, assertEligible, negative },\n\t\t\t{ winningChanges: changed, consistency },\n\t\t);\n\t\tawait assertEligible({ requireBinding: true });\n\t\tconst enrollment = await this.getEnrollment(saved.group_id, _opts.deviceId);\n\t\tvalidateAcceptedRecipientEnrollment(enrollment, _opts);\n\t\tlet savedWithGrant = saved;\n\t\tif (\n\t\t\tsavedInspection.kind === \"add_device\" &&\n\t\t\tsaved.inviter_device_id &&\n\t\t\t!saved.bootstrap_grant_id &&\n\t\t\tnew Date(saved.expires_at) > new Date(consumedAt)\n\t\t) {\n\t\t\tawait this.recoverRecipientInviteGrant(saved, _opts, {\n\t\t\t\tsql: boundEligibilitySql,\n\t\t\t\tvalues: boundEligibilityValues,\n\t\t\t\tconsumedAt,\n\t\t\t\tassertEligible,\n\t\t\t\tnegative: recoveryNegative,\n\t\t\t});\n\t\t\tconst refreshed = await this.getInviteByTokenForInspection(_opts.token);\n\t\t\tif (!refreshed) throw new Error(\"invite_invalid\");\n\t\t\tsavedWithGrant = refreshed;\n\t\t}\n\t\tconst bootstrapGrant = savedWithGrant.bootstrap_grant_id\n\t\t\t? await this.getBootstrapGrant(savedWithGrant.bootstrap_grant_id)\n\t\t\t: null;\n\t\tawait assertEligible({ requireBinding: true });\n\t\treturn {\n\t\t\tstatus: changed === 1 ? \"accepted\" : \"existing\",\n\t\t\tinvite: savedWithGrant,\n\t\t\treviewed_intent: savedInspection.reviewed_intent,\n\t\t\tbootstrap_grant: bootstrapGrant,\n\t\t};\n\t}\n\n\tasync consumeProjectInvite(\n\t\tinput: CoordinatorConsumeProjectInviteInput,\n\t): Promise<CoordinatorProjectInviteAcceptance> {\n\t\tconst _opts = captureLegacyProjectInviteInput(input);\n\t\tif (!this.db.batch) throw new Error(\"D1 batch support is required for atomic invite consume.\");\n\t\tconst consumedAt = normalizeInviteExpiresAt(_opts.now);\n\t\tconst digest = await tokenDigest(_opts.token);\n\t\tconst initialRow = await this.getInviteByTokenForInspection(_opts.token);\n\t\tconst initial = initialRow ? { ...initialRow } : null;\n\t\tif (!initial?.operation_id || !initial.project_intent_json || initial.revoked_at) {\n\t\t\tthrow new Error(\"invite_invalid\");\n\t\t}\n\t\tconst group = await this.getGroup(initial.group_id);\n\t\tif (!group) throw new Error(\"group_not_found\");\n\t\tif (group.archived_at) throw new Error(\"group_archived\");\n\t\tif (initial.operation_id !== _opts.operationId) throw new Error(\"invite_invalid\");\n\t\tif (fingerprintPublicKey(_opts.publicKey) !== _opts.fingerprint) {\n\t\t\tthrow new Error(\"fingerprint_mismatch\");\n\t\t}\n\t\tif (!initial.consumed_at && new Date(initial.expires_at) <= new Date(consumedAt)) {\n\t\t\tthrow new Error(\"invite_expired\");\n\t\t}\n\t\tif (initial.consumed_at) assertProjectInviteBinding(initial, _opts);\n\t\tconst guard = await prepareProjectInviteGuards(this.db, initial, _opts);\n\t\tconst grantId = tokenUrlSafe(12);\n\t\tconst enrollmentValues = projectInviteEnrollmentValues(initial, _opts);\n\t\tconst statements = [\n\t\t\tthis.db\n\t\t\t\t.prepare(`UPDATE coordinator_invites SET token = ?, consumed_at = ?, bound_device_id = ?,\n\t\t\t\t\tbound_public_key = ?, bound_fingerprint = ?, recipient_actor_id = ?,\n\t\t\t\t\trecipient_display_name = ?, recipient_device_display_name = ?,\n\t\t\t\t\ttrust_state = 'pending_inviter_device'\n\t\t\t\t\tWHERE (token_digest = ? OR token = ?) AND consumed_at IS NULL\n\t\t\t\t\tAND EXISTS (SELECT 1 FROM groups g WHERE g.group_id = coordinator_invites.group_id\n\t\t\t\t\t\tAND g.archived_at IS NULL)\n\t\t\t\t\tAND revoked_at IS NULL AND expires_at > ? AND ${guard.eligibilitySql}`)\n\t\t\t\t.bind(\n\t\t\t\t\t`consumed:${initial.invite_id}`,\n\t\t\t\t\tconsumedAt,\n\t\t\t\t\t_opts.deviceId,\n\t\t\t\t\t_opts.publicKey,\n\t\t\t\t\t_opts.fingerprint,\n\t\t\t\t\t_opts.recipientActorId,\n\t\t\t\t\t_opts.recipientDisplayName,\n\t\t\t\t\t_opts.deviceDisplayName,\n\t\t\t\t\tdigest,\n\t\t\t\t\t_opts.token,\n\t\t\t\t\tconsumedAt,\n\t\t\t\t\t...guard.eligibilityValues,\n\t\t\t\t),\n\t\t\tthis.db\n\t\t\t\t.prepare(`INSERT INTO enrolled_devices(\n\t\t\t\t\tgroup_id, device_id, public_key, fingerprint, identity_id, display_name, enabled, created_at\n\t\t\t\t) SELECT i.group_id, i.bound_device_id, i.bound_public_key, i.bound_fingerprint,\n\t\t\t\t\ti.recipient_actor_id, i.recipient_device_display_name, 1, ? FROM coordinator_invites i\n\t\t\t\t\tJOIN groups g ON g.group_id = i.group_id AND g.archived_at IS NULL\n\t\t\t\t\tWHERE (i.token_digest = ? OR i.token = ?) AND i.bound_device_id = ? AND changes() = 1\n\t\t\t\t\tAND ${guard.boundEligibilitySql}\n\t\t\t\tON CONFLICT(group_id, device_id) DO UPDATE SET\n\t\t\t\t\tidentity_id = COALESCE(enrolled_devices.identity_id, excluded.identity_id),\n\t\t\t\t\tdisplay_name = excluded.display_name, enabled = 1\n\t\t\t\t\tWHERE (enrolled_devices.identity_id IS NULL\n\t\t\t\t\tOR enrolled_devices.identity_id = excluded.identity_id)\n\t\t\t\t\tAND ${guard.boundEligibilitySql}`)\n\t\t\t\t.bind(\n\t\t\t\t\tconsumedAt,\n\t\t\t\t\tdigest,\n\t\t\t\t\t_opts.token,\n\t\t\t\t\t_opts.deviceId,\n\t\t\t\t\t...guard.boundEligibilityValues,\n\t\t\t\t\t...guard.boundEligibilityValues,\n\t\t\t\t),\n\t\t\tthis.db\n\t\t\t\t.prepare(`UPDATE coordinator_invites SET bootstrap_grant_id = ?,\n\t\t\t\t\ttrust_state = 'bootstrap_grant_created'\n\t\t\t\t\tWHERE (token_digest = ? OR token = ?) AND bootstrap_grant_id IS NULL\n\t\t\t\t\tAND bound_device_id = ?\n\t\t\t\t\tAND (changes() = 1 OR ? = 1) AND ${PROJECT_INVITE_ENROLLMENT_SQL}\n\t\t\t\t\tAND EXISTS (SELECT 1 FROM groups g WHERE g.group_id = coordinator_invites.group_id\n\t\t\t\t\t\tAND g.archived_at IS NULL)\n\t\t\t\t\tAND expires_at > ?\n\t\t\t\t\tAND EXISTS (SELECT 1 FROM enrolled_devices e WHERE e.group_id = coordinator_invites.group_id\n\t\t\t\t\t\tAND e.device_id = coordinator_invites.inviter_device_id AND e.enabled = 1)\n\t\t\t\t\tAND ${guard.boundEligibilitySql}`)\n\t\t\t\t.bind(\n\t\t\t\t\tgrantId,\n\t\t\t\t\tdigest,\n\t\t\t\t\t_opts.token,\n\t\t\t\t\t_opts.deviceId,\n\t\t\t\t\tinitial.consumed_at ? 1 : 0,\n\t\t\t\t\t...enrollmentValues,\n\t\t\t\t\tconsumedAt,\n\t\t\t\t\t...guard.boundEligibilityValues,\n\t\t\t\t),\n\t\t\tthis.db\n\t\t\t\t.prepare(`INSERT OR IGNORE INTO coordinator_bootstrap_grants(\n\t\t\t\t\tgrant_id, group_id, seed_device_id, worker_device_id, expires_at, created_at,\n\t\t\t\t\tcreated_by, revoked_at\n\t\t\t\t) SELECT i.bootstrap_grant_id, i.group_id, i.inviter_device_id, i.bound_device_id,\n\t\t\t\t\ti.expires_at, ?, i.inviter_actor_id, NULL FROM coordinator_invites i\n\t\t\t\t\tJOIN groups g ON g.group_id = i.group_id AND g.archived_at IS NULL\n\t\t\t\t\tJOIN enrolled_devices e ON e.group_id = i.group_id AND e.device_id = i.inviter_device_id\n\t\t\t\t\tWHERE (i.token_digest = ? OR i.token = ?)\n\t\t\t\t\tAND ((i.bootstrap_grant_id = ? AND changes() = 1)\n\t\t\t\t\t\tOR (i.bootstrap_grant_id = ? AND ? = 1))\n\t\t\t\t\tAND i.bound_device_id = ? AND e.enabled = 1\n\t\t\t\t\tAND ${guard.boundEligibilitySql} AND ${PROJECT_INVITE_ENROLLMENT_SQL}`)\n\t\t\t\t.bind(\n\t\t\t\t\tconsumedAt,\n\t\t\t\t\tdigest,\n\t\t\t\t\t_opts.token,\n\t\t\t\t\tgrantId,\n\t\t\t\t\tinitial.bootstrap_grant_id ?? null,\n\t\t\t\t\tinitial.consumed_at ? 1 : 0,\n\t\t\t\t\t_opts.deviceId,\n\t\t\t\t\t...guard.boundEligibilityValues,\n\t\t\t\t\t...enrollmentValues,\n\t\t\t\t),\n\t\t];\n\t\tconst accepted = await runProjectInviteBatch(\n\t\t\tthis.db,\n\t\t\tstatements,\n\t\t\tinitial,\n\t\t\t_opts,\n\t\t\tguard,\n\t\t\tenrollmentValues,\n\t\t);\n\t\t// This is a post-commit denial, not a claim that the committed batch was rolled back.\n\t\tawait guard.assertEligible({ requireBinding: false });\n\t\tconst currentGroup = await this.getGroup(initial.group_id);\n\t\tif (!currentGroup) throw new Error(\"group_not_found\");\n\t\tif (currentGroup.archived_at) throw new Error(\"group_archived\");\n\t\tconst saved = await this.getInviteByTokenForInspection(_opts.token);\n\t\tif (!saved) throw new Error(\"invite_invalid\");\n\t\tassertProjectInviteBinding(saved, _opts);\n\t\tconst enrollment = await this.getEnrollment(saved.group_id, _opts.deviceId);\n\t\tconst seed = saved.inviter_device_id\n\t\t\t? await this.getEnrollment(saved.group_id, saved.inviter_device_id)\n\t\t\t: null;\n\t\tconst grant = saved.bootstrap_grant_id\n\t\t\t? await this.getBootstrapGrant(saved.bootstrap_grant_id)\n\t\t\t: null;\n\t\tawait guard.assertEligible({ requireBinding: true });\n\t\tif (!enrollment) throw new Error(\"invite_acceptance_incomplete\");\n\t\tif (enrollment.identity_id !== _opts.recipientActorId) {\n\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\t}\n\t\treturn {\n\t\t\tstatus: accepted ? \"accepted\" : \"existing\",\n\t\t\tinvite: saved,\n\t\t\tenrollment,\n\t\t\tseed_enrollment: seed,\n\t\t\tbootstrap_grant: grant,\n\t\t};\n\t}\n\n\tasync listInvites(_groupId: string): Promise<CoordinatorInvite[]> {\n\t\treturn (\n\t\t\tawait allRows<CoordinatorInvite>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT ${INVITE_COLUMNS}\n\t\t\t\t\t FROM coordinator_invites WHERE group_id = ?\n\t\t\t\t\t ORDER BY created_at DESC`)\n\t\t\t\t\t.bind(_groupId),\n\t\t\t)\n\t\t).map((row) => rowToRecord<CoordinatorInvite>(row));\n\t}\n\n\tasync createJoinRequest(\n\t\t_opts: CoordinatorCreateJoinRequestInput,\n\t): Promise<CoordinatorJoinRequest> {\n\t\tconst now = nowISO();\n\t\tconst requestId = tokenUrlSafe(12);\n\t\tawait this.db\n\t\t\t.prepare(`INSERT INTO coordinator_join_requests(\n\t\t\t\trequest_id, group_id, device_id, public_key, fingerprint, display_name, token, status, created_at, reviewed_at, reviewed_by\n\t\t\t) VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', ?, NULL, NULL)`)\n\t\t\t.bind(\n\t\t\t\trequestId,\n\t\t\t\t_opts.groupId,\n\t\t\t\t_opts.deviceId,\n\t\t\t\t_opts.publicKey,\n\t\t\t\t_opts.fingerprint,\n\t\t\t\t_opts.displayName ?? null,\n\t\t\t\t_opts.token,\n\t\t\t\tnow,\n\t\t\t)\n\t\t\t.run();\n\t\tconst row = await firstRow<CoordinatorJoinRequest>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT request_id, group_id, device_id, public_key, fingerprint, display_name, token, status, created_at, reviewed_at, reviewed_by\n\t\t\t\t\t FROM coordinator_join_requests WHERE request_id = ?`)\n\t\t\t\t.bind(requestId),\n\t\t);\n\t\treturn rowToRecord<CoordinatorJoinRequest>(row);\n\t}\n\n\tasync listJoinRequests(_groupId: string, _status?: string): Promise<CoordinatorJoinRequest[]> {\n\t\tconst status = _status ?? \"pending\";\n\t\treturn (\n\t\t\tawait allRows<CoordinatorJoinRequest>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT request_id, group_id, device_id, public_key, fingerprint, display_name, token, status, created_at, reviewed_at, reviewed_by\n\t\t\t\t\t\t FROM coordinator_join_requests\n\t\t\t\t\t\t WHERE group_id = ? AND status = ?\n\t\t\t\t\t\t ORDER BY created_at ASC, device_id ASC`)\n\t\t\t\t\t.bind(_groupId, status),\n\t\t\t)\n\t\t).map((row) => rowToRecord<CoordinatorJoinRequest>(row));\n\t}\n\n\tasync reviewJoinRequest(\n\t\t_opts: CoordinatorReviewJoinRequestInput,\n\t): Promise<CoordinatorJoinRequestReviewResult | null> {\n\t\t_opts = {\n\t\t\t..._opts,\n\t\t\tbootstrapGrant: _opts.bootstrapGrant ? { ..._opts.bootstrapGrant } : _opts.bootstrapGrant,\n\t\t};\n\t\tconst sourceRow = await firstRow<CoordinatorJoinRequest & { public_key: string }>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT request_id, group_id, device_id, public_key, fingerprint, display_name, token, status,\n\t\t\t\t\t created_at, reviewed_at, reviewed_by\n\t\t\t\t\t FROM coordinator_join_requests WHERE request_id = ?`)\n\t\t\t\t.bind(_opts.requestId),\n\t\t);\n\t\tif (!sourceRow) return null;\n\t\tconst row = { ...sourceRow };\n\t\tif (row.status !== \"pending\") {\n\t\t\treturn { ...rowToRecord<CoordinatorJoinRequest>(row), _no_transition: true };\n\t\t}\n\t\tconst bootstrapGrantRequest = normalizeCoordinatorBootstrapGrantRequest(_opts.bootstrapGrant);\n\t\tif (!_opts.approved) return this.denyJoinRequest(_opts);\n\t\tif (!this.db.batch) throw new Error(\"join_review_unavailable\");\n\t\tconst reviewedAt = nowISO();\n\t\tconst { guard, bootstrapGrantInput } = await this.prepareJoinApproval(\n\t\t\trow,\n\t\t\tbootstrapGrantRequest,\n\t\t);\n\t\tconst statements: D1PreparedStatementLike[] = [\n\t\t\tthis.db\n\t\t\t\t.prepare(`UPDATE coordinator_join_requests\n\t\t\t\t\t\t SET status = ?, reviewed_at = ?, reviewed_by = ?\n\t\t\t\t\t\t WHERE request_id = ? AND status = 'pending'\n\t\t\t\t\t\t AND ${guard.eligibilitySql} AND ${guard.sourceSql}`)\n\t\t\t\t.bind(\n\t\t\t\t\t\"approved\",\n\t\t\t\t\treviewedAt,\n\t\t\t\t\t_opts.reviewedBy ?? null,\n\t\t\t\t\t_opts.requestId,\n\t\t\t\t\t...guard.eligibilityValues,\n\t\t\t\t\t...guard.sourceValues,\n\t\t\t\t),\n\t\t];\n\t\tconst bootstrapGrantId = bootstrapGrantInput ? tokenUrlSafe(12) : null;\n\t\tstatements.push(\n\t\t\t...this.prepareJoinApprovalStatements(\n\t\t\t\trow,\n\t\t\t\tguard,\n\t\t\t\treviewedAt,\n\t\t\t\t_opts.reviewedBy ?? null,\n\t\t\t\tbootstrapGrantInput,\n\t\t\t\tbootstrapGrantId,\n\t\t\t),\n\t\t);\n\t\tif (!(await this.executeJoinApprovalBatch(statements, { requestId: _opts.requestId, guard })))\n\t\t\treturn this.classifyJoinReviewFailure(_opts.requestId, guard);\n\t\treturn this.readCompletedJoinReview(_opts.requestId, bootstrapGrantId);\n\t}\n\n\tprivate async prepareJoinApproval(\n\t\trow: CoordinatorJoinRequest & { public_key: string },\n\t\tbootstrapGrantRequest: ReturnType<typeof normalizeCoordinatorBootstrapGrantRequest>,\n\t) {\n\t\tlet bootstrapGrantInput: CoordinatorCreateBootstrapGrantInput | null = null;\n\t\tlet seedEnrollment: CoordinatorEnrollment | null = null;\n\t\tif (bootstrapGrantRequest) {\n\t\t\tseedEnrollment = await firstRow<CoordinatorEnrollment>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(\n\t\t\t\t\t\t`SELECT * FROM enrolled_devices WHERE group_id = ? AND device_id = ? AND enabled = 1`,\n\t\t\t\t\t)\n\t\t\t\t\t.bind(row.group_id, bootstrapGrantRequest.seedDeviceId),\n\t\t\t);\n\t\t\tif (!seedEnrollment) {\n\t\t\t\tthrow new Error(\"bootstrap grant seed device is not enrolled in the group.\");\n\t\t\t}\n\t\t\tseedEnrollment = { ...seedEnrollment };\n\t\t\tif (bootstrapGrantRequest.seedDeviceId === row.device_id) {\n\t\t\t\tthrow new Error(\"bootstrap grant seed and worker device ids must differ.\");\n\t\t\t}\n\t\t\tbootstrapGrantInput = {\n\t\t\t\t...bootstrapGrantRequest,\n\t\t\t\tgroupId: row.group_id,\n\t\t\t\tworkerDeviceId: row.device_id,\n\t\t\t};\n\t\t}\n\t\tconst currentPublicKey = captureLegacyEnrollmentPublicKey(\n\t\t\tawait firstRow<{ public_key: string }>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT public_key FROM enrolled_devices WHERE group_id = ? AND device_id = ?`)\n\t\t\t\t\t.bind(row.group_id, row.device_id),\n\t\t\t),\n\t\t);\n\t\tconst guard = joinReviewGuardEvidence(\n\t\t\trow,\n\t\t\tseedEnrollment,\n\t\t\t{\n\t\t\t\trecipient: await ed25519KeyIdForRevocation(row.public_key),\n\t\t\t\tseed: seedEnrollment ? await ed25519KeyIdForRevocation(seedEnrollment.public_key) : null,\n\t\t\t\tcurrent:\n\t\t\t\t\tcurrentPublicKey === null ? null : await ed25519KeyIdForRevocation(currentPublicKey),\n\t\t\t},\n\t\t\tcurrentPublicKey,\n\t\t);\n\t\tawait this.assertJoinOwnershipAvailable(guard);\n\t\treturn { guard, bootstrapGrantInput };\n\t}\n\n\tprivate async assertJoinOwnershipAvailable(guard: ReturnType<typeof joinReviewGuardEvidence>) {\n\t\tconst revocation = await readRecipientInviteDecision(\n\t\t\t() =>\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT (${guard.revocationSql}) AS revoked`)\n\t\t\t\t\t.bind(...guard.revocationValues),\n\t\t\t[\"revoked\"],\n\t\t);\n\t\tif (revocation.revoked === 1) throw new Error(\"device_revoked\");\n\t\tconst state = await readRecipientInviteDecision(\n\t\t\t() =>\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT (${guard.revocationSql}) AS revoked, (${guard.ownershipSql}) AS owned`)\n\t\t\t\t\t.bind(...guard.revocationValues, ...guard.ownershipValues),\n\t\t\t[\"revoked\", \"owned\"],\n\t\t);\n\t\tif (state.revoked === 1) throw new Error(\"device_revoked\");\n\t\tif (state.owned === 1) throw new Error(\"device_ownership_requires_verified_identity\");\n\t}\n\n\tprivate async executeJoinApprovalBatch(\n\t\tstatements: D1PreparedStatementLike[],\n\t\toptions: { requestId: string; guard: ReturnType<typeof joinReviewGuardEvidence> },\n\t): Promise<boolean> {\n\t\tif (!this.db.batch) throw new Error(\"join_review_unavailable\");\n\t\tlet results: unknown[];\n\t\ttry {\n\t\t\tresults = await this.db.batch(statements);\n\t\t} catch {\n\t\t\t// A transport error may follow commit. Only a still-pending request permits denial diagnosis.\n\t\t\tlet latest: { status: unknown } | null;\n\t\t\ttry {\n\t\t\t\tlatest = await firstRow<{ status: unknown }>(\n\t\t\t\t\tthis.db\n\t\t\t\t\t\t.prepare(`SELECT status FROM coordinator_join_requests WHERE request_id = ?`)\n\t\t\t\t\t\t.bind(options.requestId),\n\t\t\t\t);\n\t\t\t} catch {\n\t\t\t\tthrow new Error(\"join_review_incomplete\");\n\t\t\t}\n\t\t\tif (latest?.status === \"pending\") await this.assertJoinOwnershipAvailable(options.guard);\n\t\t\tthrow new Error(\"join_review_incomplete\");\n\t\t}\n\t\tif (results.length !== statements.length) throw new Error(\"join_review_incomplete\");\n\t\tassertJoinReviewConfirmation(results.at(-1));\n\t\tconst changes = results.slice(0, -1).map(joinReviewResultChanges);\n\t\tconst winner = changes[0];\n\t\tif ((winner !== 0 && winner !== 1) || changes.some((count) => count !== winner))\n\t\t\tthrow new Error(\"join_review_incomplete\");\n\t\treturn winner === 1;\n\t}\n\n\tprivate async denyJoinRequest(\n\t\topts: CoordinatorReviewJoinRequestInput,\n\t): Promise<CoordinatorJoinRequestReviewResult | null> {\n\t\tconst statement = this.db\n\t\t\t.prepare(`UPDATE coordinator_join_requests SET status = 'denied', reviewed_at = ?, reviewed_by = ?\n\t\t\tWHERE request_id = ? AND status = 'pending'`)\n\t\t\t.bind(nowISO(), opts.reviewedBy ?? null, opts.requestId);\n\t\tconst changes = this.db.batch\n\t\t\t? joinReviewResultChanges((await this.db.batch([statement]))[0])\n\t\t\t: await runChanges(statement);\n\t\tif (changes === 0) return this.classifyJoinReviewFailure(opts.requestId, null);\n\t\tif (changes !== 1) throw new Error(\"join_review_incomplete\");\n\t\treturn this.readCompletedJoinReview(opts.requestId, null);\n\t}\n\n\tprivate async readCompletedJoinReview(\n\t\trequestId: string,\n\t\tgrantId: string | null,\n\t): Promise<CoordinatorJoinRequestReviewResult> {\n\t\tconst updated = await firstRow<CoordinatorJoinRequestReviewResult>(\n\t\t\tthis.db\n\t\t\t\t.prepare(\n\t\t\t\t\t`SELECT ${JOIN_REVIEW_COLUMNS} FROM coordinator_join_requests WHERE request_id = ?`,\n\t\t\t\t)\n\t\t\t\t.bind(requestId),\n\t\t);\n\t\tif (!updated) throw new Error(\"join_review_incomplete\");\n\t\tconst grant = grantId ? await this.getBootstrapGrant(grantId) : null;\n\t\tif (grantId && !grant) throw new Error(\"join_review_incomplete\");\n\t\treturn { ...updated, bootstrap_grant: grant };\n\t}\n\n\tprivate prepareJoinApprovalStatements(\n\t\trow: CoordinatorJoinRequest & { public_key: string },\n\t\tguard: ReturnType<typeof joinReviewGuardEvidence>,\n\t\treviewedAt: string,\n\t\treviewedBy: string | null,\n\t\tgrant: CoordinatorCreateBootstrapGrantInput | null,\n\t\tgrantId: string | null,\n\t): D1PreparedStatementLike[] {\n\t\tconst approvedSql = `${guard.eligibilitySql} AND EXISTS (SELECT 1 FROM coordinator_join_requests\n\t\t\tWHERE request_id = ? AND status = 'approved' AND reviewed_at = ? AND reviewed_by IS ?)`;\n\t\tconst approvedValues = [...guard.eligibilityValues, row.request_id, reviewedAt, reviewedBy];\n\t\tconst enrolledSql = `${approvedSql} AND EXISTS (SELECT 1 FROM enrolled_devices\n\t\t\tWHERE group_id = ? AND device_id = ? AND public_key = ? AND fingerprint = ? AND enabled = 1)`;\n\t\tconst enrolledValues = [\n\t\t\t...approvedValues,\n\t\t\trow.group_id,\n\t\t\trow.device_id,\n\t\t\trow.public_key,\n\t\t\trow.fingerprint,\n\t\t];\n\t\t// changes() carries this batch's CAS, not a timestamp that another reviewer can share.\n\t\t// CASE raises a SQL error on trigger-side drift rather than committing a zero-row sibling.\n\t\tconst statements = [\n\t\t\tthis.db\n\t\t\t\t.prepare(`INSERT INTO enrolled_devices(\n\t\t\tgroup_id, device_id, public_key, fingerprint, display_name, enabled, created_at)\n\t\t\tSELECT ?, ?, ?, ?, ?, 1, ? FROM (SELECT 1 WHERE changes() = 1) AS winner\n\t\t\tWHERE CASE WHEN ${approvedSql} AND ${guard.sourceSql} THEN 1 ELSE json('join_review_incomplete') END\n\t\t\tON CONFLICT(group_id, device_id) DO UPDATE SET public_key = excluded.public_key,\n\t\t\tfingerprint = excluded.fingerprint, display_name = excluded.display_name, enabled = 1\n\t\t\tWHERE CASE WHEN ${guard.eligibilitySql} AND ${guard.sourceSql}\n\t\t\tTHEN 1 ELSE json('join_review_incomplete') END`)\n\t\t\t\t.bind(\n\t\t\t\t\trow.group_id,\n\t\t\t\t\trow.device_id,\n\t\t\t\t\trow.public_key,\n\t\t\t\t\trow.fingerprint,\n\t\t\t\t\trow.display_name ?? null,\n\t\t\t\t\tnowISO(),\n\t\t\t\t\t...approvedValues,\n\t\t\t\t\t...guard.sourceValues,\n\t\t\t\t\t...guard.eligibilityValues,\n\t\t\t\t\t...guard.sourceValues,\n\t\t\t\t),\n\t\t];\n\t\tif (grant && grantId) {\n\t\t\tstatements.push(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`INSERT INTO coordinator_bootstrap_grants(\n\t\t\t\tgrant_id, group_id, seed_device_id, worker_device_id, expires_at, created_at, created_by, revoked_at)\n\t\t\t\tSELECT ?, ?, ?, ?, ?, ?, ?, NULL FROM (SELECT 1 WHERE changes() = 1) AS winner\n\t\t\t\tWHERE CASE WHEN ${enrolledSql} THEN 1 ELSE json('join_review_incomplete') END`)\n\t\t\t\t\t.bind(\n\t\t\t\t\t\tgrantId,\n\t\t\t\t\t\tgrant.groupId,\n\t\t\t\t\t\tgrant.seedDeviceId,\n\t\t\t\t\t\tgrant.workerDeviceId,\n\t\t\t\t\t\tgrant.expiresAt,\n\t\t\t\t\t\tnowISO(),\n\t\t\t\t\t\tgrant.createdBy ?? null,\n\t\t\t\t\t\t...enrolledValues,\n\t\t\t\t\t),\n\t\t\t);\n\t\t}\n\t\tstatements.push(\n\t\t\tthis.prepareJoinApprovalConfirmation(\n\t\t\t\trow,\n\t\t\t\treviewedAt,\n\t\t\t\treviewedBy,\n\t\t\t\tguard,\n\t\t\t\tenrolledSql,\n\t\t\t\tenrolledValues,\n\t\t\t\tgrant,\n\t\t\t\tgrantId,\n\t\t\t),\n\t\t);\n\t\treturn statements;\n\t}\n\n\tprivate prepareJoinApprovalConfirmation(\n\t\trow: CoordinatorJoinRequest,\n\t\treviewedAt: string,\n\t\treviewedBy: string | null,\n\t\tguard: ReturnType<typeof joinReviewGuardEvidence>,\n\t\tenrolledSql: string,\n\t\tenrolledValues: unknown[],\n\t\tgrant: CoordinatorCreateBootstrapGrantInput | null,\n\t\tgrantId: string | null,\n\t): D1PreparedStatementLike {\n\t\tconst completeSql = `${enrolledSql} AND (? IS NULL OR EXISTS (\n\t\t\tSELECT 1 FROM coordinator_bootstrap_grants WHERE grant_id = ? AND group_id = ?\n\t\t\tAND seed_device_id = ? AND worker_device_id = ? AND expires_at = ? AND revoked_at IS NULL))`;\n\t\t// A zero changes() chain must not commit a newly owned/revoked target after CAS.\n\t\t// Missing effects/receipts still report incomplete, not a fictional atomic rollback.\n\t\tconst zeroChainSql = `NOT EXISTS (SELECT 1 FROM coordinator_join_requests\n\t\t\tWHERE request_id = ? AND status = 'approved' AND reviewed_at = ? AND reviewed_by IS ?)\n\t\t\tOR (${guard.eligibilitySql})`;\n\t\treturn this.db\n\t\t\t.prepare(`SELECT CASE WHEN changes() = 0 THEN\n\t\t\tCASE WHEN ${zeroChainSql} THEN 1 ELSE json('join_review_incomplete') END\n\t\t\tWHEN ${completeSql} THEN 1 ELSE json('join_review_incomplete') END AS confirmed`)\n\t\t\t.bind(\n\t\t\t\trow.request_id,\n\t\t\t\treviewedAt,\n\t\t\t\treviewedBy,\n\t\t\t\t...guard.eligibilityValues,\n\t\t\t\t...enrolledValues,\n\t\t\t\tgrantId,\n\t\t\t\tgrantId,\n\t\t\t\trow.group_id,\n\t\t\t\tgrant?.seedDeviceId ?? null,\n\t\t\t\trow.device_id,\n\t\t\t\tgrant?.expiresAt ?? null,\n\t\t\t);\n\t}\n\n\tprivate async classifyJoinReviewFailure(\n\t\trequestId: string,\n\t\tguard: ReturnType<typeof joinReviewGuardEvidence> | null,\n\t): Promise<CoordinatorJoinRequestReviewResult | null> {\n\t\tconst latest = await firstRow<CoordinatorJoinRequestReviewResult>(\n\t\t\tthis.db\n\t\t\t\t.prepare(\n\t\t\t\t\t`SELECT ${JOIN_REVIEW_COLUMNS} FROM coordinator_join_requests WHERE request_id = ?`,\n\t\t\t\t)\n\t\t\t\t.bind(requestId),\n\t\t);\n\t\tif (!latest) return null;\n\t\tif (latest.status !== \"pending\") return { ...latest, _no_transition: true };\n\t\tif (guard) await this.assertJoinOwnershipAvailable(guard);\n\t\tthrow new Error(\"join_review_incomplete\");\n\t}\n\n\tasync createReciprocalApproval(\n\t\topts: CoordinatorCreateReciprocalApprovalInput,\n\t): Promise<CoordinatorReciprocalApproval> {\n\t\tconst groupId = opts.groupId.trim();\n\t\tconst requestingDeviceId = opts.requestingDeviceId.trim();\n\t\tconst requestedDeviceId = opts.requestedDeviceId.trim();\n\t\tconst hasExpectedIncomingRequestId = opts.expectedIncomingRequestId !== undefined;\n\t\tconst expectedIncomingRequestId = opts.expectedIncomingRequestId?.trim() ?? \"\";\n\t\tif (!groupId || !requestingDeviceId || !requestedDeviceId) {\n\t\t\tthrow new Error(\"groupId, requestingDeviceId, and requestedDeviceId are required.\");\n\t\t}\n\t\tif (requestingDeviceId === requestedDeviceId) {\n\t\t\tthrow new Error(\"requesting and requested device ids must differ.\");\n\t\t}\n\t\tif (hasExpectedIncomingRequestId) {\n\t\t\tconst resolvedAt = nowISO();\n\t\t\tconst changes = await runChanges(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`UPDATE coordinator_reciprocal_approvals\n\t\t\t\t\t\t SET status = 'completed', resolved_at = ?\n\t\t\t\t\t\t WHERE request_id = ?\n\t\t\t\t\t\t AND group_id = ?\n\t\t\t\t\t\t AND requesting_device_id = ?\n\t\t\t\t\t\t AND requested_device_id = ?\n\t\t\t\t\t\t AND status = 'pending'`)\n\t\t\t\t\t.bind(\n\t\t\t\t\t\tresolvedAt,\n\t\t\t\t\t\texpectedIncomingRequestId,\n\t\t\t\t\t\tgroupId,\n\t\t\t\t\t\trequestedDeviceId,\n\t\t\t\t\t\trequestingDeviceId,\n\t\t\t\t\t),\n\t\t\t);\n\t\t\tif (changes !== 1) {\n\t\t\t\tthrow new CoordinatorReciprocalApprovalRequestChangedError();\n\t\t\t}\n\t\t\tconst completed = await firstRow<CoordinatorReciprocalApproval>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t\t\t FROM coordinator_reciprocal_approvals WHERE request_id = ?`)\n\t\t\t\t\t.bind(expectedIncomingRequestId),\n\t\t\t);\n\t\t\treturn rowToRecord<CoordinatorReciprocalApproval>(completed);\n\t\t}\n\t\tconst pendingPair = reciprocalPendingPair(requestingDeviceId, requestedDeviceId);\n\t\tconst existing = await firstRow<CoordinatorReciprocalApproval>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t\t FROM coordinator_reciprocal_approvals\n\t\t\t\t\t WHERE group_id = ? AND requesting_device_id = ? AND requested_device_id = ? AND status = 'pending'\n\t\t\t\t\t ORDER BY created_at DESC LIMIT 1`)\n\t\t\t\t.bind(groupId, requestingDeviceId, requestedDeviceId),\n\t\t);\n\t\tif (existing) return rowToRecord<CoordinatorReciprocalApproval>(existing);\n\t\tconst reverse = await firstRow<CoordinatorReciprocalApproval>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t\t FROM coordinator_reciprocal_approvals\n\t\t\t\t\t WHERE group_id = ? AND requesting_device_id = ? AND requested_device_id = ? AND status = 'pending'\n\t\t\t\t\t ORDER BY created_at DESC LIMIT 1`)\n\t\t\t\t.bind(groupId, requestedDeviceId, requestingDeviceId),\n\t\t);\n\t\tif (reverse) {\n\t\t\tconst resolvedAt = nowISO();\n\t\t\tawait this.db\n\t\t\t\t.prepare(\n\t\t\t\t\t`UPDATE coordinator_reciprocal_approvals SET status = 'completed', resolved_at = ? WHERE request_id = ?`,\n\t\t\t\t)\n\t\t\t\t.bind(resolvedAt, reverse.request_id)\n\t\t\t\t.run();\n\t\t\tconst completed = await firstRow<CoordinatorReciprocalApproval>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t\t\t FROM coordinator_reciprocal_approvals WHERE request_id = ?`)\n\t\t\t\t\t.bind(reverse.request_id),\n\t\t\t);\n\t\t\treturn rowToRecord<CoordinatorReciprocalApproval>(completed);\n\t\t}\n\t\tconst requestId = tokenUrlSafe(12);\n\t\tconst createdAt = nowISO();\n\t\ttry {\n\t\t\tawait this.db\n\t\t\t\t.prepare(`INSERT INTO coordinator_reciprocal_approvals(\n\t\t\t\t\t\trequest_id,\n\t\t\t\t\t\tgroup_id,\n\t\t\t\t\t\trequesting_device_id,\n\t\t\t\t\t\trequested_device_id,\n\t\t\t\t\t\tpending_pair_low_device_id,\n\t\t\t\t\t\tpending_pair_high_device_id,\n\t\t\t\t\t\tstatus,\n\t\t\t\t\t\tcreated_at,\n\t\t\t\t\t\tresolved_at\n\t\t\t\t\t) VALUES (?, ?, ?, ?, ?, ?, 'pending', ?, NULL)`)\n\t\t\t\t.bind(\n\t\t\t\t\trequestId,\n\t\t\t\t\tgroupId,\n\t\t\t\t\trequestingDeviceId,\n\t\t\t\t\trequestedDeviceId,\n\t\t\t\t\tpendingPair.low,\n\t\t\t\t\tpendingPair.high,\n\t\t\t\t\tcreatedAt,\n\t\t\t\t)\n\t\t\t\t.run();\n\t\t} catch (error) {\n\t\t\tif (!isUniqueConstraintError(error)) throw error;\n\t\t\tconst sameDirection = await firstRow<CoordinatorReciprocalApproval>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t\t\t FROM coordinator_reciprocal_approvals\n\t\t\t\t\t\t WHERE group_id = ? AND requesting_device_id = ? AND requested_device_id = ? AND status = 'pending'\n\t\t\t\t\t\t ORDER BY created_at DESC LIMIT 1`)\n\t\t\t\t\t.bind(groupId, requestingDeviceId, requestedDeviceId),\n\t\t\t);\n\t\t\tif (sameDirection) return rowToRecord<CoordinatorReciprocalApproval>(sameDirection);\n\t\t\tconst reverseAfterConflict = await firstRow<CoordinatorReciprocalApproval>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t\t\t FROM coordinator_reciprocal_approvals\n\t\t\t\t\t\t WHERE group_id = ? AND requesting_device_id = ? AND requested_device_id = ? AND status = 'pending'\n\t\t\t\t\t\t ORDER BY created_at DESC LIMIT 1`)\n\t\t\t\t\t.bind(groupId, requestedDeviceId, requestingDeviceId),\n\t\t\t);\n\t\t\tif (reverseAfterConflict) {\n\t\t\t\tconst resolvedAt = nowISO();\n\t\t\t\tawait this.db\n\t\t\t\t\t.prepare(\n\t\t\t\t\t\t`UPDATE coordinator_reciprocal_approvals SET status = 'completed', resolved_at = ? WHERE request_id = ?`,\n\t\t\t\t\t)\n\t\t\t\t\t.bind(resolvedAt, reverseAfterConflict.request_id)\n\t\t\t\t\t.run();\n\t\t\t\tconst completed = await firstRow<CoordinatorReciprocalApproval>(\n\t\t\t\t\tthis.db\n\t\t\t\t\t\t.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t\t\t\t FROM coordinator_reciprocal_approvals WHERE request_id = ?`)\n\t\t\t\t\t\t.bind(reverseAfterConflict.request_id),\n\t\t\t\t);\n\t\t\t\treturn rowToRecord<CoordinatorReciprocalApproval>(completed);\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t\tconst created = await firstRow<CoordinatorReciprocalApproval>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t\t FROM coordinator_reciprocal_approvals WHERE request_id = ?`)\n\t\t\t\t.bind(requestId),\n\t\t);\n\t\treturn rowToRecord<CoordinatorReciprocalApproval>(created);\n\t}\n\n\tprivate async getBootstrapParticipantSource(groupId: string, deviceId: string) {\n\t\tconst row = await firstRow<BootstrapParticipantSource>(\n\t\t\tthis.db.prepare(BOOTSTRAP_PARTICIPANT_SOURCE_SQL).bind(groupId, deviceId),\n\t\t);\n\t\treturn captureBootstrapParticipantSource(row);\n\t}\n\n\tasync createBootstrapGrant(\n\t\topts: CoordinatorCreateBootstrapGrantInput,\n\t): Promise<CoordinatorBootstrapGrant> {\n\t\tconst input = normalizeCoordinatorBootstrapGrantInput(opts);\n\t\ttry {\n\t\t\tconst revoked = () => this.db.prepare(BOOTSTRAP_PARTICIPANTS_REVOKED_SQL);\n\t\t\tif (await firstRow(revoked().bind(input.seedDeviceId, null, input.workerDeviceId, null))) {\n\t\t\t\tthrow new Error(\"device_revoked\");\n\t\t\t}\n\t\t\tconst seed = await this.getBootstrapParticipantSource(input.groupId, input.seedDeviceId);\n\t\t\tconst worker = await this.getBootstrapParticipantSource(input.groupId, input.workerDeviceId);\n\t\t\t// Copy both source tuples before hashing yields; never infer keys from legacy fingerprints.\n\t\t\tconst subjects = [\n\t\t\t\tinput.seedDeviceId,\n\t\t\t\tseed ? await ed25519KeyIdForRevocation(seed.public_key) : null,\n\t\t\t\tinput.workerDeviceId,\n\t\t\t\tworker ? await ed25519KeyIdForRevocation(worker.public_key) : null,\n\t\t\t];\n\t\t\tif (await firstRow(revoked().bind(...subjects))) throw new Error(\"device_revoked\");\n\t\t\tconst values = bootstrapRawInsertValues(\n\t\t\t\tinput,\n\t\t\t\t{ grantId: tokenUrlSafe(12), createdAt: nowISO() },\n\t\t\t\t{ seed, worker },\n\t\t\t\tsubjects,\n\t\t\t);\n\t\t\tconst row = await firstRow<CoordinatorBootstrapGrant>(\n\t\t\t\tthis.db.prepare(BOOTSTRAP_RAW_INSERT_SQL).bind(...values),\n\t\t\t);\n\t\t\tif (row) return rowToRecord<CoordinatorBootstrapGrant>(row);\n\t\t\tif (await firstRow(revoked().bind(...subjects))) throw new Error(\"device_revoked\");\n\t\t\tthrow new Error(\"bootstrap_grant_write_incomplete\");\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error && error.message === \"device_revoked\") throw error;\n\t\t\tthrow new Error(\"bootstrap_grant_write_incomplete\");\n\t\t}\n\t}\n\n\tprivate async getScope(scopeId: string): Promise<CoordinatorScope | null> {\n\t\tconst row = await firstRow<CoordinatorScope>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT scope_id, label, kind, authority_type, coordinator_id, group_id,\n\t\t\t\t\t\tmanifest_issuer_device_id, membership_epoch, manifest_hash, status, created_at, updated_at\n\t\t\t\t\t FROM coordinator_scopes WHERE scope_id = ?`)\n\t\t\t\t.bind(scopeId),\n\t\t);\n\t\treturn row ? rowToRecord<CoordinatorScope>(row) : null;\n\t}\n\n\tprivate async getScopeMembership(\n\t\tscopeId: string,\n\t\tdeviceId: string,\n\t): Promise<CoordinatorScopeMembership | null> {\n\t\tconst row = await firstRow<CoordinatorScopeMembership>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT scope_id, device_id, role, status, membership_epoch, coordinator_id, group_id,\n\t\t\t\t\t\tmanifest_issuer_device_id, manifest_hash, signed_manifest_json, updated_at\n\t\t\t\t\t FROM coordinator_scope_memberships\n\t\t\t\t\t WHERE scope_id = ? AND device_id = ?`)\n\t\t\t\t.bind(scopeId, deviceId),\n\t\t);\n\t\treturn row ? rowToRecord<CoordinatorScopeMembership>(row) : null;\n\t}\n\n\tasync createScope(opts: CoordinatorCreateScopeInput): Promise<CoordinatorScope> {\n\t\tconst normalized = normalizeCoordinatorCreateScopeInput(opts);\n\t\tif (await this.getScope(normalized.scopeId)) throw new Error(\"scopeId already exists.\");\n\t\tconst now = nowISO();\n\t\tawait this.db\n\t\t\t.prepare(`INSERT INTO coordinator_scopes(\n\t\t\t\t\tscope_id, label, kind, authority_type, coordinator_id, group_id,\n\t\t\t\t\tmanifest_issuer_device_id, membership_epoch, manifest_hash, status, created_at, updated_at\n\t\t\t\t) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)\n\t\t\t.bind(\n\t\t\t\tnormalized.scopeId,\n\t\t\t\tnormalized.label,\n\t\t\t\tnormalized.kind,\n\t\t\t\tnormalized.authorityType,\n\t\t\t\tnormalized.coordinatorId,\n\t\t\t\tnormalized.groupId,\n\t\t\t\tnormalized.manifestIssuerDeviceId,\n\t\t\t\tnormalized.membershipEpoch,\n\t\t\t\tnormalized.manifestHash,\n\t\t\t\tnormalized.status,\n\t\t\t\tnow,\n\t\t\t\tnow,\n\t\t\t)\n\t\t\t.run();\n\t\tconst scope = await this.getScope(normalized.scopeId);\n\t\tif (!scope) throw new Error(\"scope insert returned no row\");\n\t\treturn scope;\n\t}\n\n\tasync updateScope(opts: CoordinatorUpdateScopeInput): Promise<CoordinatorScope | null> {\n\t\tconst scopeId = clean(opts.scopeId);\n\t\tconst existing = scopeId ? await this.getScope(scopeId) : null;\n\t\tif (!existing) return null;\n\t\tconst normalized = normalizeCoordinatorUpdateScopeInput(opts, existing);\n\t\tawait this.db\n\t\t\t.prepare(`UPDATE coordinator_scopes\n\t\t\t\t SET label = ?,\n\t\t\t\t\t kind = ?,\n\t\t\t\t\t authority_type = ?,\n\t\t\t\t\t coordinator_id = ?,\n\t\t\t\t\t group_id = ?,\n\t\t\t\t\t manifest_issuer_device_id = ?,\n\t\t\t\t\t membership_epoch = ?,\n\t\t\t\t\t manifest_hash = ?,\n\t\t\t\t\t status = ?,\n\t\t\t\t\t updated_at = ?\n\t\t\t\t WHERE scope_id = ?`)\n\t\t\t.bind(\n\t\t\t\tnormalized.label,\n\t\t\t\tnormalized.kind,\n\t\t\t\tnormalized.authorityType,\n\t\t\t\tnormalized.coordinatorId,\n\t\t\t\tnormalized.groupId,\n\t\t\t\tnormalized.manifestIssuerDeviceId,\n\t\t\t\tnormalized.membershipEpoch,\n\t\t\t\tnormalized.manifestHash,\n\t\t\t\tnormalized.status,\n\t\t\t\tnowISO(),\n\t\t\t\tnormalized.scopeId,\n\t\t\t)\n\t\t\t.run();\n\t\treturn await this.getScope(normalized.scopeId);\n\t}\n\n\tasync listScopes(opts: CoordinatorListScopesInput = {}): Promise<CoordinatorScope[]> {\n\t\tconst where: string[] = [];\n\t\tconst params: unknown[] = [];\n\t\tconst coordinatorId = clean(opts.coordinatorId);\n\t\tconst groupId = clean(opts.groupId);\n\t\tconst status = clean(opts.status);\n\t\tif (coordinatorId) {\n\t\t\twhere.push(\"coordinator_id = ?\");\n\t\t\tparams.push(coordinatorId);\n\t\t}\n\t\tif (groupId) {\n\t\t\twhere.push(\"group_id = ?\");\n\t\t\tparams.push(groupId);\n\t\t}\n\t\tif (status) {\n\t\t\twhere.push(\"status = ?\");\n\t\t\tparams.push(status);\n\t\t} else if (!opts.includeInactive) {\n\t\t\twhere.push(\"status = 'active'\");\n\t\t}\n\t\tconst whereSql = where.length ? `WHERE ${where.join(\" AND \")}` : \"\";\n\t\tconst statement =\n\t\t\tthis.db.prepare(`SELECT scope_id, label, kind, authority_type, coordinator_id, group_id,\n\t\t\t\tmanifest_issuer_device_id, membership_epoch, manifest_hash, status, created_at, updated_at\n\t\t\t FROM coordinator_scopes ${whereSql}\n\t\t\t ORDER BY coordinator_id ASC, group_id ASC, scope_id ASC`);\n\t\treturn (\n\t\t\tawait allRows<CoordinatorScope>(params.length ? statement.bind(...params) : statement)\n\t\t).map((row) => rowToRecord<CoordinatorScope>(row));\n\t}\n\n\tasync getScopeAuthorization(\n\t\traw: CoordinatorScopeAuthorizationInput,\n\t): Promise<CoordinatorScopeAuthorizationResult> {\n\t\ttry {\n\t\t\tconst input = captureScopeAuthorizationInput(raw);\n\t\t\tconst source = await this.db\n\t\t\t\t.prepare(`SELECT ${SCOPE_FIELDS.join(\", \")} FROM coordinator_scopes WHERE scope_id = ?`)\n\t\t\t\t.bind(input.scopeId)\n\t\t\t\t.first<CoordinatorScope>();\n\t\t\tif (source === null) return { kind: \"rejected\", error: \"scope_not_found\" };\n\t\t\trequireScopeAuthorizationRecord(source, SCOPE_FIELDS);\n\t\t\tconst scope = { ...source };\n\t\t\tif (scope.scope_id !== input.scopeId) throw new Error(\"scope_authorization_unavailable\");\n\t\t\tconst error = scopeAuthorizationError(scope, input.groupId);\n\t\t\tif (error) return { kind: \"rejected\", error };\n\t\t\tconst group = await this.db\n\t\t\t\t.prepare(\"SELECT group_id, archived_at FROM groups WHERE group_id = ?\")\n\t\t\t\t.bind(input.groupId)\n\t\t\t\t.first<{ group_id: string; archived_at: string | null }>();\n\t\t\tif (group === null) return { kind: \"rejected\", error: \"scope_source_mismatch\" };\n\t\t\trequireScopeAuthorizationRecord(group, [\"group_id\"]);\n\t\t\tif (group.group_id !== input.groupId) throw new Error(\"scope_authorization_unavailable\");\n\t\t\tif (group.archived_at !== null) {\n\t\t\t\trequireScopeAuthorizationRecord(group, [\"archived_at\"]);\n\t\t\t\treturn { kind: \"rejected\", error: \"group_archived\" };\n\t\t\t}\n\t\t\tconst members = await this.captureScopeAuthorizationMembers(scope, input.groupId);\n\t\t\tconst current = await this.db\n\t\t\t\t.prepare(READ_SCOPE_AUTHORIZATION_SQL)\n\t\t\t\t.bind(JSON.stringify([scope]), JSON.stringify(members))\n\t\t\t\t.first<CoordinatorScope & { members_json: string }>();\n\t\t\trequireScopeAuthorizationRecord(current, SCOPE_FIELDS);\n\t\t\tif (!current || SCOPE_FIELDS.some((field) => current[field] !== scope[field]))\n\t\t\t\tthrow new Error(\"scope_authorization_unavailable\");\n\t\t\treturn {\n\t\t\t\tkind: \"authorized\",\n\t\t\t\tauthorizationVersion: 1,\n\t\t\t\tscope,\n\t\t\t\tmembers: parseScopeAuthorizationMembers(current.members_json, members),\n\t\t\t};\n\t\t} catch {\n\t\t\treturn { kind: \"rejected\", error: \"scope_authorization_unavailable\" };\n\t\t}\n\t}\n\n\tprivate async captureScopeAuthorizationMembers(\n\t\tscope: CoordinatorScope,\n\t\tgroupId: string,\n\t): Promise<CapturedScopeMember[]> {\n\t\tconst result = await this.db\n\t\t\t.prepare(\n\t\t\t\t`SELECT ${MEMBERSHIP_FIELDS.join(\", \")} FROM coordinator_scope_memberships WHERE scope_id = ? ORDER BY device_id ASC`,\n\t\t\t)\n\t\t\t.bind(scope.scope_id)\n\t\t\t.all<CoordinatorScopeMembership>();\n\t\tconst memberships = requireScopeAuthorizationRows(result).flatMap((membership) => {\n\t\t\trequireScopeAuthorizationRecord(membership, [\"status\"]);\n\t\t\tif (membership.status !== \"active\") return [];\n\t\t\trequireScopeAuthorizationRecord(membership, MEMBERSHIP_FIELDS);\n\t\t\treturn isCurrentScopeMember(scope, membership) ? [{ ...membership }] : [];\n\t\t});\n\t\tconst enrollments = await this.captureScopeAuthorizationEnrollments(memberships, groupId);\n\t\tconst captured: Array<Omit<CapturedScopeMember, \"keyId\">> = [];\n\t\tfor (const membership of memberships) {\n\t\t\tconst enrollment = enrollments.get(membership.device_id);\n\t\t\tif (enrollment?.enabled !== 1) continue;\n\t\t\tcaptured.push({ membership, enrollment });\n\t\t}\n\t\t// Complete every DTO copy before async hashing can change another source tuple.\n\t\tconst members: CapturedScopeMember[] = [];\n\t\tfor (const member of captured) {\n\t\t\tconst keyId = await ed25519KeyIdForRevocation(member.enrollment.public_key);\n\t\t\tif (keyId !== null) members.push({ ...member, keyId });\n\t\t}\n\t\treturn members;\n\t}\n\n\tprivate async captureScopeAuthorizationEnrollments(\n\t\tmemberships: CoordinatorScopeMembership[],\n\t\tgroupId: string,\n\t): Promise<Map<string, CoordinatorEnrollment>> {\n\t\tconst deviceIds = new Set(memberships.map((membership) => membership.device_id));\n\t\tconst result = await this.db\n\t\t\t.prepare(\n\t\t\t\t`SELECT ${ENROLLMENT_FIELDS.join(\", \")} FROM enrolled_devices WHERE group_id = ?\n\t\t\t\tAND device_id IN (SELECT value FROM json_each(?))`,\n\t\t\t)\n\t\t\t.bind(groupId, JSON.stringify([...deviceIds]))\n\t\t\t.all<CoordinatorEnrollment>();\n\t\tconst enrollments = new Map<string, CoordinatorEnrollment>();\n\t\tfor (const enrollment of requireScopeAuthorizationRows(result)) {\n\t\t\trequireScopeAuthorizationRecord(enrollment, ENROLLMENT_FIELDS);\n\t\t\tif (enrollment.group_id !== groupId || !deviceIds.delete(enrollment.device_id))\n\t\t\t\tthrow new Error(\"scope_authorization_unavailable\");\n\t\t\tenrollments.set(enrollment.device_id, { ...enrollment });\n\t\t}\n\t\treturn enrollments;\n\t}\n\n\tasync grantScopeMembership(\n\t\topts: CoordinatorGrantScopeMembershipInput,\n\t): Promise<CoordinatorScopeMembership> {\n\t\tconst effectId = normalizeMembershipEffectId(opts.effectId);\n\t\tconst requestJson = grantMembershipEffectRequestJson(opts);\n\t\tconst priorReceipt = await getMembershipEffectReceipt(this.db, effectId);\n\t\tif (priorReceipt) {\n\t\t\tassertMatchingMembershipEffectReceipt(priorReceipt, \"grant\", requestJson);\n\t\t\treturn membershipFromEffectReceipt(priorReceipt);\n\t\t}\n\t\tconst scopeId = clean(opts.scopeId);\n\t\tconst deviceId = clean(opts.deviceId);\n\t\tconst scope = scopeId ? await this.getScope(scopeId) : null;\n\t\tif (!scope) throw new CoordinatorMembershipError(\"scope_not_found\");\n\t\tif (scope.status !== \"active\") throw new CoordinatorMembershipError(\"scope_inactive\");\n\t\tconst existing = scopeId && deviceId ? await this.getScopeMembership(scopeId, deviceId) : null;\n\t\tconst normalized = normalizeCoordinatorGrantScopeMembershipInput(opts, scope, existing);\n\t\tif (normalized.groupId) {\n\t\t\tconst enrollment = await this.getEnrollment(normalized.groupId, normalized.deviceId);\n\t\t\tif (!enrollment) {\n\t\t\t\tthrow new CoordinatorMembershipError(\"device_not_enrolled\");\n\t\t\t}\n\t\t}\n\t\tconst now = nowISO();\n\t\tawait runAuditedBatch(this.db, [\n\t\t\tthis.db\n\t\t\t\t.prepare(`INSERT INTO coordinator_scope_memberships(\n\t\t\t\t\tscope_id, device_id, role, status, membership_epoch, coordinator_id, group_id,\n\t\t\t\t\tmanifest_issuer_device_id, manifest_hash, signed_manifest_json, updated_at\n\t\t\t\t) SELECT ?, ?, ?, 'active', ?, ?, ?, ?, ?, ?, ?\n\t\t\t\tWHERE NOT EXISTS (\n\t\t\t\t\tSELECT 1 FROM coordinator_scope_membership_effect_receipts WHERE effect_id = ?\n\t\t\t\t)\n\t\t\t\tON CONFLICT(scope_id, device_id) DO UPDATE SET\n\t\t\t\t\trole = excluded.role,\n\t\t\t\t\tstatus = 'active',\n\t\t\t\t\tmembership_epoch = excluded.membership_epoch,\n\t\t\t\t\tcoordinator_id = excluded.coordinator_id,\n\t\t\t\t\tgroup_id = excluded.group_id,\n\t\t\t\t\tmanifest_issuer_device_id = excluded.manifest_issuer_device_id,\n\t\t\t\t\tmanifest_hash = excluded.manifest_hash,\n\t\t\t\t\tsigned_manifest_json = excluded.signed_manifest_json,\n\t\t\t\t\tupdated_at = excluded.updated_at\n\t\t\t\tWHERE excluded.membership_epoch > coordinator_scope_memberships.membership_epoch\n\t\t\t\t OR (\n\t\t\t\t\texcluded.membership_epoch = coordinator_scope_memberships.membership_epoch\n\t\t\t\t\tAND coordinator_scope_memberships.status != 'revoked'\n\t\t\t\t )`)\n\t\t\t\t.bind(\n\t\t\t\t\tnormalized.scopeId,\n\t\t\t\t\tnormalized.deviceId,\n\t\t\t\t\tnormalized.role,\n\t\t\t\t\tnormalized.membershipEpoch,\n\t\t\t\t\tnormalized.coordinatorId,\n\t\t\t\t\tnormalized.groupId,\n\t\t\t\t\tnormalized.manifestIssuerDeviceId,\n\t\t\t\t\tnormalized.manifestHash,\n\t\t\t\t\tnormalized.signedManifestJson,\n\t\t\t\t\tnow,\n\t\t\t\t\teffectId,\n\t\t\t\t),\n\t\t\tprepareGrantEffectReceipt(this.db, {\n\t\t\t\teffectId,\n\t\t\t\trequestJson,\n\t\t\t\tscopeId: normalized.scopeId,\n\t\t\t\tdeviceId: normalized.deviceId,\n\t\t\t\tcreatedAt: now,\n\t\t\t}),\n\t\t\tprepareMembershipAuditFromCurrentRow(this.db, {\n\t\t\t\teffectId,\n\t\t\t\trequestJson,\n\t\t\t\taction: \"grant\",\n\t\t\t\tprevious: existing,\n\t\t\t\tscopeId: normalized.scopeId,\n\t\t\t\tdeviceId: normalized.deviceId,\n\t\t\t\tstatus: \"active\",\n\t\t\t\tmembershipEpoch: normalized.membershipEpoch,\n\t\t\t\tupdatedAt: now,\n\t\t\t\tactorType: normalized.actorType,\n\t\t\t\tactorId: normalized.actorId,\n\t\t\t\tcreatedAt: now,\n\t\t\t}),\n\t\t]);\n\t\tconst receipt = await getMembershipEffectReceipt(this.db, effectId);\n\t\tif (!receipt) throw new Error(\"scope membership grant was not applied.\");\n\t\tassertMatchingMembershipEffectReceipt(receipt, \"grant\", requestJson);\n\t\treturn membershipFromEffectReceipt(receipt);\n\t}\n\n\tasync revokeScopeMembership(opts: CoordinatorRevokeScopeMembershipInput): Promise<boolean> {\n\t\tconst scopeId = clean(opts.scopeId);\n\t\tconst deviceId = clean(opts.deviceId);\n\t\tif (!scopeId || !deviceId) throw new Error(\"scopeId and deviceId are required.\");\n\t\tconst effectId = normalizeMembershipEffectId(opts.effectId);\n\t\tconst requestJson = revokeMembershipEffectRequestJson(opts);\n\t\tconst priorReceipt = await getMembershipEffectReceipt(this.db, effectId);\n\t\tif (priorReceipt) {\n\t\t\tassertMatchingMembershipEffectReceipt(priorReceipt, \"revoke\", requestJson);\n\t\t\treturn priorReceipt.outcome_applied === 1;\n\t\t}\n\t\tconst membershipEpoch =\n\t\t\topts.membershipEpoch == null ? null : normalizeEpoch(opts.membershipEpoch);\n\t\tconst requestedGroupId = clean(opts.groupId);\n\t\tconst scope = requestedGroupId ? await this.getScope(scopeId) : null;\n\t\tif (requestedGroupId && requestedGroupId !== scope?.group_id) {\n\t\t\tthrow new CoordinatorMembershipError(\"scope_group_mismatch\");\n\t\t}\n\t\tconst existing = await this.getScopeMembership(scopeId, deviceId);\n\t\tif (membershipEpoch != null && existing && membershipEpoch <= existing.membership_epoch) {\n\t\t\tthrow new Error(\"membershipEpoch must increase on revoke.\");\n\t\t}\n\t\tconst now = nowISO();\n\t\tconst revokedEpoch = membershipEpoch ?? (existing?.membership_epoch ?? -1) + 1;\n\t\tconst updateStatement = this.db\n\t\t\t.prepare(`UPDATE coordinator_scope_memberships\n\t\t\t\t\t\t SET status = 'revoked',\n\t\t\t\t\t\t\t membership_epoch = CASE WHEN ? IS NULL THEN membership_epoch + 1 ELSE ? END,\n\t\t\t\t\t\t\t manifest_hash = COALESCE(?, manifest_hash),\n\t\t\t\t\t\t\t signed_manifest_json = COALESCE(?, signed_manifest_json),\n\t\t\t\t\t\t\t updated_at = ?\n\t\t\t\t\t\t WHERE scope_id = ? AND device_id = ? AND membership_epoch = ? AND status = ?\n\t\t\t\t\t\t AND NOT EXISTS (\n\t\t\t\t\t\t\tSELECT 1 FROM coordinator_scope_membership_effect_receipts WHERE effect_id = ?\n\t\t\t\t\t\t )`)\n\t\t\t.bind(\n\t\t\t\tmembershipEpoch,\n\t\t\t\tmembershipEpoch,\n\t\t\t\tclean(opts.manifestHash),\n\t\t\t\tclean(opts.signedManifestJson),\n\t\t\t\tnow,\n\t\t\t\tscopeId,\n\t\t\t\tdeviceId,\n\t\t\t\texisting?.membership_epoch ?? -1,\n\t\t\t\texisting?.status ?? \"\",\n\t\t\t\teffectId,\n\t\t\t);\n\t\tconst receiptStatement = prepareRevokeEffectReceipt(this.db, {\n\t\t\teffectId,\n\t\t\trequestJson,\n\t\t\tscopeId,\n\t\t\tdeviceId,\n\t\t\tcreatedAt: now,\n\t\t});\n\t\tconst auditStatement = prepareMembershipAuditFromCurrentRow(this.db, {\n\t\t\teffectId,\n\t\t\trequestJson,\n\t\t\taction: \"revoke\",\n\t\t\tprevious: existing,\n\t\t\tscopeId,\n\t\t\tdeviceId,\n\t\t\tstatus: \"revoked\",\n\t\t\tmembershipEpoch: revokedEpoch,\n\t\t\tupdatedAt: now,\n\t\t\tactorType: clean(opts.actorType),\n\t\t\tactorId: clean(opts.actorId),\n\t\t\tcreatedAt: now,\n\t\t});\n\t\ttry {\n\t\t\tawait runAuditedBatch(this.db, [updateStatement, receiptStatement, auditStatement]);\n\t\t} catch (err) {\n\t\t\tconst current = await this.getScopeMembership(scopeId, deviceId);\n\t\t\tif (\n\t\t\t\texisting &&\n\t\t\t\t(!current ||\n\t\t\t\t\tcurrent.membership_epoch !== existing.membership_epoch ||\n\t\t\t\t\tcurrent.status !== existing.status)\n\t\t\t) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tthrow err;\n\t\t}\n\t\tconst receipt = await getMembershipEffectReceipt(this.db, effectId);\n\t\tif (!receipt) throw new Error(\"scope membership revoke receipt was not persisted.\");\n\t\tassertMatchingMembershipEffectReceipt(receipt, \"revoke\", requestJson);\n\t\treturn receipt.outcome_applied === 1;\n\t}\n\n\tasync listScopeMemberships(\n\t\tscopeId: string,\n\t\tincludeRevoked = false,\n\t): Promise<CoordinatorScopeMembership[]> {\n\t\tconst normalizedScopeId = clean(scopeId);\n\t\tif (!normalizedScopeId) throw new Error(\"scopeId is required.\");\n\t\tconst statusWhere = includeRevoked ? \"\" : \"AND status = 'active'\";\n\t\treturn (\n\t\t\tawait allRows<CoordinatorScopeMembership>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT scope_id, device_id, role, status, membership_epoch, coordinator_id, group_id,\n\t\t\t\t\t\t\tmanifest_issuer_device_id, manifest_hash, signed_manifest_json, updated_at\n\t\t\t\t\t\t FROM coordinator_scope_memberships\n\t\t\t\t\t\t WHERE scope_id = ? ${statusWhere}\n\t\t\t\t\t\t ORDER BY device_id ASC`)\n\t\t\t\t\t.bind(normalizedScopeId),\n\t\t\t)\n\t\t).map((row) => rowToRecord<CoordinatorScopeMembership>(row));\n\t}\n\n\tasync listDeviceScopeMemberships(\n\t\tdeviceId: string,\n\t\tincludeRevoked = false,\n\t): Promise<CoordinatorScopeMembership[]> {\n\t\tconst normalizedDeviceId = clean(deviceId);\n\t\tif (!normalizedDeviceId) throw new Error(\"deviceId is required.\");\n\t\t// Served by idx_coordinator_scope_memberships_device_status.\n\t\tconst statusWhere = includeRevoked ? \"\" : \"AND status = 'active'\";\n\t\treturn (\n\t\t\tawait allRows<CoordinatorScopeMembership>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT scope_id, device_id, role, status, membership_epoch, coordinator_id, group_id,\n\t\t\t\t\t\t\tmanifest_issuer_device_id, manifest_hash, signed_manifest_json, updated_at\n\t\t\t\t\t\t FROM coordinator_scope_memberships\n\t\t\t\t\t\t WHERE device_id = ? ${statusWhere}\n\t\t\t\t\t\t ORDER BY scope_id ASC`)\n\t\t\t\t\t.bind(normalizedDeviceId),\n\t\t\t)\n\t\t).map((row) => rowToRecord<CoordinatorScopeMembership>(row));\n\t}\n\n\tasync listScopeMembershipAuditEvents(\n\t\topts: CoordinatorListScopeMembershipAuditInput,\n\t): Promise<CoordinatorScopeMembershipAuditEvent[]> {\n\t\tconst scopeId = clean(opts.scopeId);\n\t\tif (!scopeId) throw new Error(\"scopeId is required.\");\n\t\tconst deviceId = clean(opts.deviceId);\n\t\tconst limit = normalizeCoordinatorAuditLimit(opts.limit);\n\t\tconst where = deviceId ? \"scope_id = ? AND device_id = ?\" : \"scope_id = ?\";\n\t\tconst params = deviceId ? [scopeId, deviceId, limit] : [scopeId, limit];\n\t\treturn (\n\t\t\tawait allRows<CoordinatorScopeMembershipAuditEvent>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT event_id, effect_id, action, scope_id, device_id, role, status, membership_epoch,\n\t\t\t\t\t\t\tprevious_role, previous_status, previous_membership_epoch,\n\t\t\t\t\t\t\tcoordinator_id, group_id, actor_type, actor_id, manifest_hash, created_at\n\t\t\t\t\t\t FROM coordinator_scope_membership_audit_log\n\t\t\t\t\t\t WHERE ${where}\n\t\t\t\t\t\t ORDER BY event_id ASC\n\t\t\t\t\t\t LIMIT ?`)\n\t\t\t\t\t.bind(...params),\n\t\t\t)\n\t\t).map((row) => rowToRecord<CoordinatorScopeMembershipAuditEvent>(row));\n\t}\n\n\tasync getBootstrapGrant(grantId: string): Promise<CoordinatorBootstrapGrant | null> {\n\t\tconst row = await firstRow<CoordinatorBootstrapGrant>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT grant_id, group_id, seed_device_id, worker_device_id, expires_at, created_at, created_by, revoked_at\n\t\t\t\t\t FROM coordinator_bootstrap_grants WHERE grant_id = ?`)\n\t\t\t\t.bind(grantId),\n\t\t);\n\t\treturn row ? rowToRecord<CoordinatorBootstrapGrant>(row) : null;\n\t}\n\n\tasync getBootstrapGrantAuthorization(\n\t\traw: CoordinatorBootstrapGrantAuthorizationInput,\n\t): Promise<CoordinatorBootstrapGrantAuthorizationResult> {\n\t\ttry {\n\t\t\tconst input = captureBootstrapAuthorizationInput(raw);\n\t\t\tconst source = await firstRow<BootstrapAuthorizationRow>(\n\t\t\t\tthis.db.prepare(BOOTSTRAP_AUTHORIZATION_SOURCE_SQL).bind(input.grantId),\n\t\t\t);\n\t\t\tconst sourceError = bootstrapAuthorizationSourceError(input, source);\n\t\t\tif (sourceError) return rejectBootstrapAuthorization(sourceError);\n\t\t\tif (!source) return rejectBootstrapAuthorization(\"bootstrap_authorization_unavailable\");\n\t\t\tconst captured = { ...source };\n\t\t\tconst keys = {\n\t\t\t\tseed:\n\t\t\t\t\tcaptured.seed_enrollment_public_key === null\n\t\t\t\t\t\t? null\n\t\t\t\t\t\t: await ed25519KeyIdForRevocation(captured.seed_enrollment_public_key),\n\t\t\t\tworker:\n\t\t\t\t\tcaptured.worker_enrollment_public_key === null\n\t\t\t\t\t\t? null\n\t\t\t\t\t\t: await ed25519KeyIdForRevocation(captured.worker_enrollment_public_key),\n\t\t\t};\n\t\t\tconst decision = bootstrapAuthorizationDecision(input, captured, keys);\n\t\t\tconst current = await firstRow<BootstrapAuthorizationRow>(\n\t\t\t\tthis.db.prepare(decision.sql).bind(...decision.values),\n\t\t\t);\n\t\t\treturn bootstrapAuthorizationResult(current);\n\t\t} catch {\n\t\t\treturn rejectBootstrapAuthorization(\"bootstrap_authorization_unavailable\");\n\t\t}\n\t}\n\n\tasync listBootstrapGrants(groupId: string): Promise<CoordinatorBootstrapGrant[]> {\n\t\treturn (\n\t\t\tawait allRows<CoordinatorBootstrapGrant>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT grant_id, group_id, seed_device_id, worker_device_id, expires_at, created_at, created_by, revoked_at\n\t\t\t\t\t\t FROM coordinator_bootstrap_grants WHERE group_id = ?\n\t\t\t\t\t\t ORDER BY created_at DESC, grant_id DESC`)\n\t\t\t\t\t.bind(groupId),\n\t\t\t)\n\t\t).map((row) => rowToRecord<CoordinatorBootstrapGrant>(row));\n\t}\n\n\tasync revokeBootstrapGrant(grantId: string, revokedAt = nowISO()): Promise<boolean> {\n\t\treturn (\n\t\t\t(await runChanges(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`UPDATE coordinator_bootstrap_grants\n\t\t\t\t\t\t SET revoked_at = COALESCE(revoked_at, ?)\n\t\t\t\t\t\t WHERE grant_id = ?`)\n\t\t\t\t\t.bind(revokedAt, grantId),\n\t\t\t)) > 0\n\t\t);\n\t}\n\n\tasync listReciprocalApprovals(\n\t\topts: CoordinatorListReciprocalApprovalsInput,\n\t): Promise<CoordinatorReciprocalApproval[]> {\n\t\tconst directionColumn =\n\t\t\topts.direction === \"incoming\" ? \"requested_device_id\" : \"requesting_device_id\";\n\t\tconst status = opts.status?.trim() || \"pending\";\n\t\treturn (\n\t\t\tawait allRows<CoordinatorReciprocalApproval>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t\t\t FROM coordinator_reciprocal_approvals\n\t\t\t\t\t\t WHERE group_id = ? AND ${directionColumn} = ? AND status = ?\n\t\t\t\t\t\t ORDER BY created_at ASC, request_id ASC`)\n\t\t\t\t\t.bind(opts.groupId, opts.deviceId, status),\n\t\t\t)\n\t\t).map((row) => rowToRecord<CoordinatorReciprocalApproval>(row));\n\t}\n\n\tasync createLegacyTeamCompletion(\n\t\tgroupId: string,\n\t\tmanifest: CoordinatorLegacyTeamCompletionManifestV1,\n\t): Promise<CoordinatorLegacyTeamCompletionWriteResult> {\n\t\tconst [normalizedGroupId] = normalizeCoordinatorLegacyTeamCompletionGroupIds([groupId]);\n\t\tif (!normalizedGroupId) throw new Error(\"completion_manifest_invalid\");\n\t\tconst group = await this.getGroup(normalizedGroupId);\n\t\tif (!group) throw new Error(\"group_not_found\");\n\t\tif (group.archived_at) throw new Error(\"group_archived\");\n\t\tconst manifestJson = canonicalCoordinatorLegacyTeamCompletionManifestJson(manifest);\n\t\tconst normalized = JSON.parse(manifestJson) as CoordinatorLegacyTeamCompletionManifestV1;\n\t\trequireCoordinatorLegacyTeamCompletionTeamBinding(normalized);\n\t\tconst existing = await firstRow<{ manifest_json: string }>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT manifest_json FROM coordinator_legacy_team_completions\n\t\t\t\t\tWHERE group_id = ? AND candidate_ref = ?`)\n\t\t\t\t.bind(normalizedGroupId, normalized.candidate_ref),\n\t\t);\n\t\tif (existing) {\n\t\t\treturn legacyCompletionWriteResult(existing.manifest_json, manifestJson, \"existing\");\n\t\t}\n\t\tconst coordinatorId = await this.requireLegacyTeamCompletionSources(\n\t\t\tnormalizedGroupId,\n\t\t\tnormalized,\n\t\t\tmanifestJson,\n\t\t);\n\t\tconst ownerProof = await this.prepareLegacyTeamCompletionOwnerProof(\n\t\t\tnormalizedGroupId,\n\t\t\tmanifestJson,\n\t\t);\n\t\tconst changes = await runChanges(\n\t\t\tthis.db\n\t\t\t\t.prepare(`${LEGACY_OWNER_INPUT_SQL}${ownerProof.ctes}\n\t\t\t\tINSERT OR IGNORE INTO coordinator_legacy_team_completions(\n\t\t\t\t\tgroup_id, candidate_ref, manifest_version, manifest_json, completed_at, created_at\n\t\t\t\t\t) SELECT ?, ?, ?, ?, ?, ?\n\t\t\t\t\t FROM groups\n\t\t\t\t\t WHERE group_id = ? AND archived_at IS NULL\n\t\t\t\t\t AND NOT EXISTS (\n\t\t\t\t\t SELECT 1\n\t\t\t\t\t FROM json_each(?, '$.project_mappings') AS requested\n\t\t\t\t\t LEFT JOIN coordinator_scopes AS scope\n\t\t\t\t\t ON scope.scope_id = json_extract(requested.value, '$.scope_id')\n\t\t\t\t\t AND scope.authority_type = 'coordinator'\n\t\t\t\t\t AND scope.coordinator_id = ?\n\t\t\t\t\t AND scope.group_id = ?\n\t\t\t\t\t AND scope.status = 'active'\n\t\t\t\t\t WHERE scope.scope_id IS NULL\n\t\t\t\t\t )\n\t\t\t\t\t AND NOT EXISTS (\n\t\t\t\t\t SELECT 1 FROM enrolled_devices AS enrolled\n\t\t\t\t\t WHERE enrolled.group_id = ?\n\t\t\t\t\t AND NOT EXISTS (\n\t\t\t\t\t SELECT 1 FROM json_each(?, '$.device_decisions') AS requested\n\t\t\t\t\t WHERE json_extract(requested.value, '$.device_id') = enrolled.device_id\n\t\t\t\t\t AND json_extract(requested.value, '$.key_fingerprint') = enrolled.fingerprint\n\t\t\t\t\t AND json_extract(requested.value, '$.enabled') = enrolled.enabled\n\t\t\t\t\t )\n\t\t\t\t\t )\n\t\t\t\t\t AND NOT EXISTS (\n\t\t\t\t\t SELECT 1 FROM json_each(?, '$.device_decisions') AS requested\n\t\t\t\t\t WHERE json_extract(requested.value, '$.decision') = 'included'\n\t\t\t\t\t AND NOT EXISTS (\n\t\t\t\t\t SELECT 1 FROM enrolled_devices AS enrolled\n\t\t\t\t\t WHERE enrolled.group_id = ?\n\t\t\t\t\t AND enrolled.device_id = json_extract(requested.value, '$.device_id')\n\t\t\t\t\t AND enrolled.fingerprint = json_extract(requested.value, '$.key_fingerprint')\n\t\t\t\t\t AND enrolled.enabled = 1\n\t\t\t\t\t )\n\t\t\t\t\t ) AND ${LEGACY_OWNER_SOURCE_CURRENT_SQL}\n\t\t\t\t\t AND (${ownerProof.currentSql}) AND (${ownerProof.compatibleSql})`)\n\t\t\t\t.bind(\n\t\t\t\t\t...ownerProof.values,\n\t\t\t\t\tnormalizedGroupId,\n\t\t\t\t\tnormalized.candidate_ref,\n\t\t\t\t\tnormalized.version,\n\t\t\t\t\tmanifestJson,\n\t\t\t\t\tnormalized.completed_at,\n\t\t\t\t\tnowISO(),\n\t\t\t\t\tnormalizedGroupId,\n\t\t\t\t\tmanifestJson,\n\t\t\t\t\tcoordinatorId,\n\t\t\t\t\tnormalizedGroupId,\n\t\t\t\t\tnormalizedGroupId,\n\t\t\t\t\tmanifestJson,\n\t\t\t\t\tmanifestJson,\n\t\t\t\t\tnormalizedGroupId,\n\t\t\t\t),\n\t\t);\n\t\tconst stored = await firstRow<{ manifest_json: string }>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT manifest_json FROM coordinator_legacy_team_completions\n\t\t\t\t\tWHERE group_id = ? AND candidate_ref = ?`)\n\t\t\t\t.bind(normalizedGroupId, normalized.candidate_ref),\n\t\t);\n\t\tif (!stored) {\n\t\t\tawait this.requireLegacyTeamCompletionSources(normalizedGroupId, normalized, manifestJson);\n\t\t\tconst denial = await firstRow<{ denial: string }>(\n\t\t\t\tthis.db.prepare(ownerProof.denialSql).bind(...ownerProof.values),\n\t\t\t);\n\t\t\tif (denial?.denial === \"completion_conflict\") {\n\t\t\t\tthrow new CoordinatorLegacyTeamCompletionConflictError();\n\t\t\t}\n\t\t\tthrow new Error(\"completion_manifest_unavailable\");\n\t\t}\n\t\treturn legacyCompletionWriteResult(\n\t\t\tstored.manifest_json,\n\t\t\tmanifestJson,\n\t\t\tchanges === 1 ? \"created\" : \"existing\",\n\t\t);\n\t}\n\n\tprivate async prepareLegacyTeamCompletionOwnerProof(groupId: string, manifestJson: string) {\n\t\tconst keyMetadata = await legacyOwnerKeyMetadata(\n\t\t\tawait allRows<{ public_key: string }>(\n\t\t\t\tthis.db.prepare(LEGACY_OWNER_KEYS_SQL).bind(manifestJson, groupId),\n\t\t\t),\n\t\t);\n\t\tconst proof = legacyCompletionOwnerProofSql(\n\t\t\tawait captureLegacyCompletionOwnerProof({\n\t\t\t\tbackend: {\n\t\t\t\t\tfirst: <T>({ sql, values }: AuthLinkStatement) =>\n\t\t\t\t\t\tfirstRow<T>(this.db.prepare(sql).bind(...values)),\n\t\t\t\t\tall: <T>({ sql, values }: AuthLinkStatement) =>\n\t\t\t\t\t\tallRows<T>(this.db.prepare(sql).bind(...values)),\n\t\t\t\t},\n\t\t\t\tgroupId,\n\t\t\t\tmanifestJson,\n\t\t\t\tkeyMetadata,\n\t\t\t}),\n\t\t);\n\t\treturn {\n\t\t\t...proof,\n\t\t\tvalues: [manifestJson, groupId, keyMetadata, ...proof.values],\n\t\t\tdenialSql: `${LEGACY_OWNER_INPUT_SQL}${proof.ctes}\n\t\t SELECT CASE WHEN NOT (${LEGACY_OWNER_SOURCE_CURRENT_SQL}) OR NOT (${proof.currentSql})\n\t\t THEN 'completion_manifest_unavailable'\n\t\t WHEN NOT (${proof.compatibleSql}) THEN 'completion_conflict'\n\t\t ELSE 'completion_manifest_unavailable' END AS denial`,\n\t\t};\n\t}\n\n\tprivate async requireLegacyTeamCompletionSources(\n\t\tgroupId: string,\n\t\tmanifest: CoordinatorLegacyTeamCompletionManifestV1,\n\t\tmanifestJson: string,\n\t): Promise<string | null> {\n\t\tconst group = await this.getGroup(groupId);\n\t\tif (!group) throw new Error(\"group_not_found\");\n\t\tif (group.archived_at) throw new Error(\"group_archived\");\n\t\tconst bindings = await allRows<CoordinatorLegacyTeamCompletionScopeBinding>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT DISTINCT requested.scope_id, scope.authority_type,\n\t\t\t\t\tscope.coordinator_id, scope.group_id, scope.status\n\t\t\t\t FROM (SELECT json_extract(value, '$.scope_id') AS scope_id\n\t\t\t\t\tFROM json_each(?, '$.project_mappings')) AS requested\n\t\t\t\t LEFT JOIN coordinator_scopes AS scope ON scope.scope_id = requested.scope_id`)\n\t\t\t\t.bind(manifestJson),\n\t\t);\n\t\treturn requireCoordinatorLegacyTeamCompletionScopeBindings(manifest, groupId, bindings);\n\t}\n\n\tasync getLegacyTeamCompletion(\n\t\tgroupId: string,\n\t\tcandidateRef: string,\n\t): Promise<CoordinatorLegacyTeamCompletionManifestV1 | null> {\n\t\tconst [normalizedGroupId] = normalizeCoordinatorLegacyTeamCompletionGroupIds([groupId]);\n\t\tconst normalizedCandidateRef =\n\t\t\tnormalizeCoordinatorLegacyTeamCompletionCandidateRef(candidateRef);\n\t\tif (!normalizedGroupId) throw new Error(\"completion_manifest_invalid\");\n\t\tconst row = await firstRow<{ manifest_json: string }>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT manifest_json FROM coordinator_legacy_team_completions\n\t\t\t\t\tWHERE group_id = ? AND candidate_ref = ?`)\n\t\t\t\t.bind(normalizedGroupId, normalizedCandidateRef),\n\t\t);\n\t\treturn row\n\t\t\t? normalizeCoordinatorLegacyTeamCompletionManifest(JSON.parse(row.manifest_json))\n\t\t\t: null;\n\t}\n\n\tasync listLegacyTeamCompletions(\n\t\tgroupIds: string[],\n\t): Promise<CoordinatorLegacyTeamCompletionRecord[]> {\n\t\tconst normalizedGroupIds = normalizeCoordinatorLegacyTeamCompletionGroupIds(groupIds);\n\t\tif (normalizedGroupIds.length === 0) return [];\n\t\tconst placeholders = normalizedGroupIds.map(() => \"?\").join(\", \");\n\t\tconst stats = await firstRow<{\n\t\t\trecord_count: number;\n\t\t\tbatch_bytes: number;\n\t\t\tmax_manifest_bytes: number;\n\t\t}>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT\n\t\t\t\t\tCOUNT(*) AS record_count,\n\t\t\t\t\tCOALESCE(SUM(\n\t\t\t\t\t\tLENGTH(CAST(group_id AS BLOB)) + LENGTH(CAST(manifest_json AS BLOB))\n\t\t\t\t\t), 0) AS batch_bytes,\n\t\t\t\t\tCOALESCE(MAX(LENGTH(CAST(manifest_json AS BLOB))), 0) AS max_manifest_bytes\n\t\t\t\tFROM coordinator_legacy_team_completions\n\t\t\t\tWHERE group_id IN (${placeholders})`)\n\t\t\t\t.bind(...normalizedGroupIds),\n\t\t);\n\t\tif (\n\t\t\t!stats ||\n\t\t\tstats.record_count > COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_RECORDS ||\n\t\t\tstats.batch_bytes > COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BATCH_BYTES ||\n\t\t\tstats.max_manifest_bytes > COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES\n\t\t) {\n\t\t\tthrow new Error(\"completion_results_too_large\");\n\t\t}\n\t\tconst rows = await allRows<{ group_id: string; manifest_json: string }>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`WITH completion_stats AS (\n\t\t\t\t\tSELECT\n\t\t\t\t\t\tCOUNT(*) AS record_count,\n\t\t\t\t\t\tCOALESCE(SUM(\n\t\t\t\t\t\t\tLENGTH(CAST(group_id AS BLOB)) + LENGTH(CAST(manifest_json AS BLOB))\n\t\t\t\t\t\t), 0) AS batch_bytes,\n\t\t\t\t\t\tCOALESCE(MAX(LENGTH(CAST(manifest_json AS BLOB))), 0) AS max_manifest_bytes\n\t\t\t\t\tFROM coordinator_legacy_team_completions\n\t\t\t\t\tWHERE group_id IN (${placeholders})\n\t\t\t\t)\n\t\t\t\tSELECT completions.group_id, completions.manifest_json\n\t\t\t\tFROM coordinator_legacy_team_completions AS completions\n\t\t\t\tCROSS JOIN completion_stats\n\t\t\t\tWHERE completions.group_id IN (${placeholders})\n\t\t\t\t\t AND completion_stats.record_count <= ${COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_RECORDS}\n\t\t\t\t\t AND completion_stats.batch_bytes <= ${COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BATCH_BYTES}\n\t\t\t\t\t AND completion_stats.max_manifest_bytes <= ${COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES}\n\t\t\t\t\t AND LENGTH(completions.manifest_json) <= ${COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES}\n\t\t\t\t\t AND LENGTH(CAST(completions.manifest_json AS BLOB)) <= ${COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES}\n\t\t\t\t\tORDER BY completions.group_id, completions.completed_at, completions.candidate_ref\n\t\t\t\t\tLIMIT ${COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_RECORDS + 1}`)\n\t\t\t\t.bind(...normalizedGroupIds, ...normalizedGroupIds),\n\t\t);\n\t\tif (rows.length === 0 && stats.record_count > 0) {\n\t\t\tthrow new Error(\"completion_results_too_large\");\n\t\t}\n\t\tif (rows.length > COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_RECORDS) {\n\t\t\tthrow new Error(\"completion_results_too_large\");\n\t\t}\n\t\tconst batchBytes = rows.reduce(\n\t\t\t(total, row) =>\n\t\t\t\ttotal +\n\t\t\t\tnew TextEncoder().encode(row.group_id).byteLength +\n\t\t\t\tnew TextEncoder().encode(row.manifest_json).byteLength,\n\t\t\t0,\n\t\t);\n\t\tif (batchBytes > COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BATCH_BYTES) {\n\t\t\tthrow new Error(\"completion_results_too_large\");\n\t\t}\n\t\treturn rows.map((row) => ({\n\t\t\tgroup_id: row.group_id,\n\t\t\tmanifest: normalizeCoordinatorLegacyTeamCompletionManifest(JSON.parse(row.manifest_json)),\n\t\t}));\n\t}\n\n\tasync captureAuthControllerLegacyHistory(input: ControllerHistoryInput) {\n\t\treturn captureControllerHistory(input, <T>(sql: string, values: string[]) =>\n\t\t\tallRows<T>(this.db.prepare(sql).bind(...values)),\n\t\t);\n\t}\n\n\tasync upsertPresence(_opts: CoordinatorUpsertPresenceInput): Promise<CoordinatorPresenceRecord> {\n\t\tconst now = new Date();\n\t\tconst expiresAt = new Date(now.getTime() + _opts.ttlS * 1000).toISOString();\n\t\tconst normalized = mergeCoordinatorAddresses([], _opts.addresses);\n\t\tawait this.db\n\t\t\t.prepare(`INSERT INTO presence_records(group_id, device_id, addresses_json, last_seen_at, expires_at, capabilities_json)\n\t\t\t\t VALUES (?, ?, ?, ?, ?, ?)\n\t\t\t\t ON CONFLICT(group_id, device_id) DO UPDATE SET\n\t\t\t\t\taddresses_json = excluded.addresses_json,\n\t\t\t\t\tlast_seen_at = excluded.last_seen_at,\n\t\t\t\t\texpires_at = excluded.expires_at,\n\t\t\t\t\tcapabilities_json = excluded.capabilities_json`)\n\t\t\t.bind(\n\t\t\t\t_opts.groupId,\n\t\t\t\t_opts.deviceId,\n\t\t\t\tJSON.stringify(normalized),\n\t\t\t\tnow.toISOString(),\n\t\t\t\texpiresAt,\n\t\t\t\tJSON.stringify(_opts.capabilities ?? {}),\n\t\t\t)\n\t\t\t.run();\n\t\treturn {\n\t\t\tgroup_id: _opts.groupId,\n\t\t\tdevice_id: _opts.deviceId,\n\t\t\taddresses: normalized,\n\t\t\texpires_at: expiresAt,\n\t\t};\n\t}\n\n\tasync listGroupPeers(\n\t\tgroupId: string,\n\t\trequestingDeviceId: string,\n\t): Promise<CoordinatorPeerRecord[]> {\n\t\ttry {\n\t\t\treturn await this.readGroupPeers(groupId, requestingDeviceId);\n\t\t} catch {\n\t\t\tthrow new Error(\"peer_discovery_unavailable\");\n\t\t}\n\t}\n\n\tprivate async readGroupPeers(\n\t\t_groupId: string,\n\t\t_requestingDeviceId: string,\n\t): Promise<CoordinatorPeerRecord[]> {\n\t\tconst now = nowISO();\n\t\tconst capturedResult = await this.db\n\t\t\t.prepare(CAPTURE_PEER_ENROLLMENTS_SQL)\n\t\t\t.bind(_groupId, _requestingDeviceId)\n\t\t\t.all<CapturedPeerEnrollment>();\n\t\tif (\n\t\t\t!Array.isArray(capturedResult?.results) ||\n\t\t\t(capturedResult as { success?: boolean }).success === false\n\t\t) {\n\t\t\tthrow new Error(\"peer_discovery_unavailable\");\n\t\t}\n\t\tconst captured = capturePeerEnrollments(capturedResult.results);\n\t\tconst candidates = await Promise.all(\n\t\t\tcaptured.map(async (row) => ({\n\t\t\t\t...row,\n\t\t\t\tkeyId: await ed25519KeyIdForRevocation(row.public_key),\n\t\t\t})),\n\t\t);\n\t\tconst currentResult = await this.db\n\t\t\t.prepare(READ_CURRENT_PEERS_SQL)\n\t\t\t.bind(JSON.stringify(candidates), _groupId, _requestingDeviceId)\n\t\t\t.all<Record<string, unknown>>();\n\t\tif ((currentResult as { success?: boolean } | null)?.success === false) {\n\t\t\tthrow new Error(\"peer_discovery_unavailable\");\n\t\t}\n\t\tconst rows = requirePeerDiscoveryRows(currentResult?.results);\n\t\treturn rows.map((row) => {\n\t\t\tconst expiresRaw = String(row.expires_at ?? \"\").trim();\n\t\t\tlet stale = true;\n\t\t\tif (expiresRaw) {\n\t\t\t\tconst expiresAt = new Date(expiresRaw);\n\t\t\t\tstale = Number.isNaN(expiresAt.getTime()) || expiresAt.toISOString() <= now;\n\t\t\t}\n\t\t\tconst addresses = stale\n\t\t\t\t? []\n\t\t\t\t: mergeCoordinatorAddresses([], JSON.parse(String(row.addresses_json ?? \"[]\")) as string[]);\n\t\t\treturn {\n\t\t\t\tdevice_id: String(row.device_id ?? \"\"),\n\t\t\t\tpublic_key: String(row.public_key ?? \"\"),\n\t\t\t\tfingerprint: String(row.fingerprint ?? \"\"),\n\t\t\t\tdisplay_name: (row.display_name as string | null) ?? null,\n\t\t\t\taddresses,\n\t\t\t\tlast_seen_at: (row.last_seen_at as string | null) ?? null,\n\t\t\t\texpires_at: (row.expires_at as string | null) ?? null,\n\t\t\t\tstale,\n\t\t\t\tcapabilities: JSON.parse(String(row.capabilities_json ?? \"{}\")) as Record<string, unknown>,\n\t\t\t} satisfies CoordinatorPeerRecord;\n\t\t});\n\t}\n}\n","import {\n\ttype CoordinatorAppBrowserAuthOptions,\n\ttype CoordinatorRequestRateLimitOptions,\n\ttype CoordinatorRequestVerifier,\n\ttype CoordinatorRuntimeDeps,\n\tcreateCoordinatorApp,\n} from \"./coordinator-api.js\";\nimport type { CoordinatorDeviceRevocationContext } from \"./coordinator-device-revocation-route.js\";\nimport { D1CoordinatorStore, type D1DatabaseLike } from \"./d1-coordinator-store.js\";\n\nexport interface CreateD1CoordinatorAppOptions {\n\tdb: D1DatabaseLike;\n\tadminSecret?: string | null;\n\tnow?: () => string;\n\trequestVerifier: CoordinatorRequestVerifier;\n\trequestRateLimit?: CoordinatorRequestRateLimitOptions;\n\tdeviceRevocation?: CoordinatorDeviceRevocationContext;\n\trecipientInviteCoordinatorId?: string;\n\tbrowserAuth?:\n\t\t| Exclude<CoordinatorAppBrowserAuthOptions, { kind: \"ready\" }>\n\t\t| Omit<Extract<CoordinatorAppBrowserAuthOptions, { kind: \"ready\" }>, \"storeFactory\">;\n}\n\nexport function createD1CoordinatorApp(\n\topts: CreateD1CoordinatorAppOptions,\n): ReturnType<typeof createCoordinatorApp> {\n\tconst db = opts.db;\n\tconst runtime: CoordinatorRuntimeDeps = {\n\t\tadminSecret: () => String(opts.adminSecret ?? \"\").trim() || null,\n\t\tnow: opts.now ?? (() => new Date().toISOString()),\n\t};\n\treturn createCoordinatorApp({\n\t\tstoreFactory: () => new D1CoordinatorStore(db),\n\t\tdeviceRevocation: opts.deviceRevocation,\n\t\trecipientInviteCoordinatorId: opts.recipientInviteCoordinatorId,\n\t\truntime,\n\t\trequestVerifier: opts.requestVerifier,\n\t\trequestRateLimit: opts.requestRateLimit,\n\t\tbrowserAuth:\n\t\t\topts.browserAuth?.kind === \"ready\"\n\t\t\t\t? { ...opts.browserAuth, storeFactory: () => new D1CoordinatorStore(db) }\n\t\t\t\t: opts.browserAuth,\n\t});\n}\n"],"mappings":";;;AAyEA,IAAa,KAA+B,OAAO,OAAO;CACzD,OAAO;CACP,SAAS;AACV,CAAC;AAED,SAAS,GAAa,GAAkC,IAAS,KAAK;CACrE,OAAO,IAAI,SAAS,EAAK,MAAM;EAAE;EAAQ,SAAS,EAAK;CAAQ,CAAC;AACjE;AACA,SAAS,GAAW,GAAe;CAClC,OAAO,EACL,WAAW,KAAK,OAAO,CAAC,CACxB,WAAW,KAAK,MAAM,CAAC,CACvB,WAAW,KAAK,MAAM,CAAC,CACvB,WAAW,MAAK,QAAQ,CAAC,CACzB,WAAW,KAAK,OAAO;AAC1B;AACA,eAAe,EAAO,IAAS,KAAwB;CACtD,IAAI;EACH,OAAO,GAAa,MAAM,EAAwB,kBAAkB,GAAG,CAAM;CAC9E,QAAQ;EACP,OAAO,IAAI,SAAS,sEAAsE;GACzF,QAAQ;GACR,SAAS;IACR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jD,IAAQ;GACZ,IAAI,GAAY;IACf,IAAM,IAAY,IAAI,KAAK,CAAU;IACrC,IAAQ,OAAO,MAAM,EAAU,QAAQ,CAAC,KAAK,EAAU,YAAY,KAAK;GACzE;GACA,IAAM,IAAY,IACf,CAAC,IACD,GAA0B,CAAC,GAAG,KAAK,MAAM,OAAO,EAAI,kBAAkB,IAAI,CAAC,CAAa;GAC3F,OAAO;IACN,WAAW,OAAO,EAAI,aAAa,EAAE;IACrC,YAAY,OAAO,EAAI,cAAc,EAAE;IACvC,aAAa,OAAO,EAAI,eAAe,EAAE;IACzC,cAAe,EAAI,gBAAkC;IACrD;IACA,cAAe,EAAI,gBAAkC;IACrD,YAAa,EAAI,cAAgC;IACjD;IACA,cAAc,KAAK,MAAM,OAAO,EAAI,qBAAqB,IAAI,CAAC;GAC/D;EACD,CAAC;CACF;AACD;;;ACp8HA,SAAgB,GACf,GAC0C;CAC1C,IAAM,IAAK,EAAK,IACV,IAAkC;EACvC,mBAAmB,OAAO,EAAK,eAAe,EAAE,CAAC,CAAC,KAAK,KAAK;EAC5D,KAAK,EAAK,+BAAc,IAAI,KAAK,EAAA,CAAE,YAAY;CAChD;CACA,OAAO,GAAqB;EAC3B,oBAAoB,IAAI,GAAmB,CAAE;EAC7C,kBAAkB,EAAK;EACvB,8BAA8B,EAAK;EACnC;EACA,iBAAiB,EAAK;EACtB,kBAAkB,EAAK;EACvB,aACC,EAAK,aAAa,SAAS,UACxB;GAAE,GAAG,EAAK;GAAa,oBAAoB,IAAI,GAAmB,CAAE;EAAE,IACtE,EAAK;CACV,CAAC;AACF"}
1
+ {"version":3,"file":"cloudflare-coordinator.js","names":[],"sources":["../../src/coordinator-account-change-browser.ts","../../src/coordinator-browser-account.ts","../../src/coordinator-browser-auth-callback.ts","../../src/coordinator-browser-link.ts","../../src/coordinator-browser-link-completion.ts","../../src/coordinator-browser-link-start.ts","../../src/coordinator-browser-signin-start.ts","../../src/coordinator-device-rebind-view.ts","../../src/coordinator-device-rebind-browser.ts","../../src/coordinator-owner-enrollment-http.ts","../../src/owner-browser-admission-body.ts","../../src/owner-browser-admission.ts","../../src/coordinator-browser-auth-app.ts","../../src/coordinator-owner-enrollment-qualification.ts","../../src/coordinator-owner-qualification-route.ts","../../src/coordinator-owner-qualification-http.ts","../../src/d1-coordinator-store.ts","../../src/d1-coordinator-runtime.ts"],"sourcesContent":["import type { AccountChangeOperations } from \"./coordinator-account-change.js\";\nimport type {\n\tCoordinatorAuthBrowserConfig,\n\tCoordinatorAuthBrowserTransactionPurposeStore,\n\tCoordinatorAuthBrowserTransactionStore,\n} from \"./coordinator-auth-browser-transaction-contract.js\";\nimport {\n\ttype CoordinatorAuthBrowserPage,\n\tprojectAccountProfileView,\n\trenderAuthBrowserNotice,\n\trenderAuthLinkCompletionHopPage,\n\trenderAuthSigninContinuePage,\n} from \"./coordinator-auth-browser-view.js\";\nimport { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport {\n\tdecodeCoordinatorAuthProof32,\n\tencodeCoordinatorAuthProof32,\n\thashCoordinatorAuthProofBytes32,\n} from \"./coordinator-auth-proof.js\";\nimport { captureCoordinatorBrowserAuthConfig } from \"./coordinator-browser-auth-config.js\";\nimport {\n\tclearBrowserCookie,\n\tissueBrowserCookie,\n\treadBrowserCookie,\n\treissueStartCookieAsTransaction,\n} from \"./coordinator-browser-credential.js\";\nimport {\n\ttype BrowserCsrfKey,\n\tisBrowserCsrfKey,\n\tissueBrowserCsrfToken,\n} from \"./coordinator-browser-csrf.js\";\nimport { checkBrowserAuthRequestRate, guardBrowserForm } from \"./coordinator-browser-form-guard.js\";\nimport { snapshotBrowserRequest } from \"./coordinator-browser-request.js\";\nimport { readBrowserStartTransaction } from \"./coordinator-browser-start-transaction.js\";\nimport {\n\ttype CoordinatorOidcClient,\n\ttype CoordinatorOidcOptions,\n\tcreateCoordinatorOidcClient,\n} from \"./coordinator-oidc.js\";\nimport type { InMemoryRequestRateLimiter } from \"./request-rate-limit.js\";\n\ntype Pins = { attemptId: string; binderHash: string; stateHash: string };\ntype Operations = Pick<\n\tAccountChangeOperations,\n\t| \"claimBrowser\"\n\t| \"hasPendingCallback\"\n\t| \"consumeCallback\"\n\t| \"recordVerifiedCallback\"\n\t| \"confirmDisconnect\"\n\t| \"failConsumed\"\n\t| \"readBrowserView\"\n\t| \"readCallbackView\"\n>;\ntype Existing = Pick<CoordinatorAuthBrowserTransactionStore, \"readAuthBrowserTransactionActivity\"> &\n\tCoordinatorAuthBrowserTransactionPurposeStore;\n\n/** Private storage capabilities, never public status DTOs or request-nominated context. */\nexport type AccountChangeBrowserReaders = Pick<\n\tAccountChangeOperations,\n\t\"readStart\" | \"readManagementActivity\" | \"readBrowserBinding\"\n>;\ntype BrowserView = NonNullable<Awaited<ReturnType<Operations[\"readBrowserView\"]>>> & {\n\tstateHash: string;\n};\nexport interface AccountChangeBrowserInput {\n\tconfig: unknown;\n\tcsrfKey: BrowserCsrfKey;\n\toperations: Operations;\n\treaders: AccountChangeBrowserReaders;\n\texisting: Existing;\n\tlimiter: InMemoryRequestRateLimiter;\n\toidcOptions?: CoordinatorOidcOptions;\n}\nexport const ACCOUNT_CHANGE_BROWSER_PATHS = Object.freeze({\n\tstart: \"/auth/account/change/start\",\n\tconfirm: \"/auth/account/change/confirm\",\n});\n\nfunction pageResponse(page: CoordinatorAuthBrowserPage, status = 200) {\n\treturn new Response(page.body, { status, headers: page.headers });\n}\nfunction escapeHtml(value: string) {\n\treturn value\n\t\t.replaceAll(\"&\", \"&amp;\")\n\t\t.replaceAll(\"<\", \"&lt;\")\n\t\t.replaceAll(\">\", \"&gt;\")\n\t\t.replaceAll('\"', \"&quot;\")\n\t\t.replaceAll(\"'\", \"&#39;\");\n}\nasync function notice(status = 403): Promise<Response> {\n\ttry {\n\t\treturn pageResponse(await renderAuthBrowserNotice(\"auth_unavailable\"), status);\n\t} catch {\n\t\treturn new Response(\"Account change unavailable. Return to your terminal and try again.\", {\n\t\t\tstatus: 503,\n\t\t\theaders: {\n\t\t\t\t\"Cache-Control\": \"no-store\",\n\t\t\t\t\"Referrer-Policy\": \"no-referrer\",\n\t\t\t\t\"X-Content-Type-Options\": \"nosniff\",\n\t\t\t},\n\t\t});\n\t}\n}\nasync function formPage(\n\ttitle: string,\n\taction: string,\n\tfields: Record<string, string>,\n\tdetail = \"\",\n) {\n\tconst headers = (await renderAuthBrowserNotice(\"auth_unavailable\")).headers;\n\theaders[\"Referrer-Policy\"] = \"same-origin\";\n\tconst hidden = Object.entries(fields)\n\t\t.map(\n\t\t\t([name, value]) =>\n\t\t\t\t`<input type=\"hidden\" name=\"${escapeHtml(name)}\" value=\"${escapeHtml(value)}\">`,\n\t\t)\n\t\t.join(\"\");\n\treturn new Response(\n\t\t`<!doctype html><html lang=\"en\"><meta charset=\"utf-8\"><meta name=\"referrer\" content=\"same-origin\"><title>${escapeHtml(title)}</title><main><h1>${escapeHtml(title)}</h1><p>${escapeHtml(detail)}</p><form method=\"post\" action=\"${action}\">${hidden}<button type=\"submit\">${escapeHtml(title)}</button></form></main></html>`,\n\t\t{ headers },\n\t);\n}\nasync function stateHash(state: string) {\n\tconst digest = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(state));\n\treturn Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\nfunction startQuery(text: string, startUrl: string) {\n\tif (text.length > 8192 || text.includes(\"#\")) return null;\n\tconst url = new URL(text);\n\tif (\n\t\turl.href !== text ||\n\t\t`${url.origin}${url.pathname}` !== startUrl ||\n\t\turl.username ||\n\t\turl.password\n\t)\n\t\treturn null;\n\tif (\n\t\t[...url.searchParams].length !== 2 ||\n\t\turl.searchParams.getAll(\"attempt_id\").length !== 1 ||\n\t\turl.searchParams.getAll(\"start_code\").length !== 1\n\t)\n\t\treturn null;\n\tconst attemptId = url.searchParams.get(\"attempt_id\"),\n\t\tstartCode = url.searchParams.get(\"start_code\");\n\tif (!isAuthControllerId(attemptId) || !startCode || !decodeCoordinatorAuthProof32(startCode))\n\t\treturn null;\n\treturn { attemptId, startCode };\n}\nasync function privateStart(\n\treaders: AccountChangeBrowserReaders,\n\tattemptId: string,\n\tstartCode: string,\n\tconfig: CoordinatorAuthBrowserConfig,\n) {\n\tconst bytes = decodeCoordinatorAuthProof32(startCode);\n\tif (!bytes) return null;\n\tconst browserStartHash = await hashCoordinatorAuthProofBytes32(bytes);\n\tconst view = await readers.readStart({ attemptId, browserStartHash }, config);\n\tif (!view || (view.intent !== \"refresh\" && view.intent !== \"disconnect\")) return null;\n\treturn { browserStartHash, intent: view.intent };\n}\nasync function inactive(\n\tcookie: string | null,\n\tinput: AccountChangeBrowserInput,\n\tconfig: CoordinatorAuthBrowserConfig,\n) {\n\tconst ordinary = await readBrowserStartTransaction(cookie, input.existing, config);\n\tif (ordinary === \"invalid\" || ordinary === \"active\") return false;\n\tconst transaction = await readBrowserCookie(cookie, \"transaction\");\n\tif (transaction.kind === \"absent\") return true;\n\tif (transaction.kind !== \"present\") return false;\n\treturn (\n\t\t(await input.readers.readManagementActivity({ binderHash: transaction.cookieHash }, config))\n\t\t\t.kind === \"inactive\"\n\t);\n}\nasync function completion(view: { loopbackRedirect: string; attemptId: string }, secret: string) {\n\treturn pageResponse(\n\t\tawait renderAuthLinkCompletionHopPage({\n\t\t\tdestination: view.loopbackRedirect,\n\t\t\tattemptId: view.attemptId,\n\t\t\tcompletionSecret: secret,\n\t\t}),\n\t);\n}\n\n/** Hosted handlers mounted by the schema-ready browser composition.\n * The composition root provides private, proof-bound readers.\n * Only a successful credential POST promotes a cookie; no GET/callback clears one.\n * Device-signed finalization remains separate. Never log queries, forms or proofs.\n */\ntype Context = {\n\tinput: AccountChangeBrowserInput;\n\tconfig: CoordinatorAuthBrowserConfig;\n\tscope: { publicOrigin: string; store: CoordinatorAuthBrowserConfig };\n\tclient: CoordinatorOidcClient;\n\tstartUrl: string;\n\tconfirmUrl: string;\n};\nasync function startCookie(cookieHeader: string | null) {\n\tconst existing = await readBrowserCookie(cookieHeader, \"start\");\n\tif (existing.kind === \"invalid\") return null;\n\treturn existing.kind === \"present\" ? existing : issueBrowserCookie(\"start\");\n}\nasync function startPage(context: Context, request: Request): Promise<Response> {\n\tconst { input, config, scope, startUrl } = context;\n\ttry {\n\t\tconst snapshot = snapshotBrowserRequest(request);\n\t\tif (snapshot.method !== \"GET\") return notice(405);\n\t\tconst query = startQuery(snapshot.url, startUrl);\n\t\tif (!query) return notice(400);\n\t\tif (!(await privateStart(input.readers, query.attemptId, query.startCode, config)))\n\t\t\treturn notice();\n\t\tif (!(await inactive(snapshot.cookie, input, config))) return notice(409);\n\t\tconst cookie = await startCookie(snapshot.cookie);\n\t\tif (!cookie) return notice(400);\n\t\tconst csrf = await issueBrowserCsrfToken(input.csrfKey, cookie.secret, \"start\", scope);\n\t\tconst response = await formPage(\"Continue with Google\", ACCOUNT_CHANGE_BROWSER_PATHS.start, {\n\t\t\tattempt_id: query.attemptId,\n\t\t\tstart_code: query.startCode,\n\t\t\tcsrf,\n\t\t});\n\t\tif (\"setCookie\" in cookie) response.headers.append(\"Set-Cookie\", cookie.setCookie);\n\t\treturn response;\n\t} catch {\n\t\treturn notice(503);\n\t}\n}\nasync function start(context: Context, request: Request, clientKey: string): Promise<Response> {\n\tconst { input, config, scope, startUrl } = context;\n\ttry {\n\t\tconst snapshot = snapshotBrowserRequest(request);\n\t\tif (snapshot.method !== \"POST\") return notice(405);\n\t\tif (snapshot.url !== startUrl) return notice(404);\n\t\tconst guard = await guardBrowserForm({\n\t\t\trequest,\n\t\t\tclientKey,\n\t\t\tscope,\n\t\t\tcsrfKey: input.csrfKey,\n\t\t\tlimiter: input.limiter,\n\t\t\taction: \"link_start\",\n\t\t});\n\t\tif (!guard.ok) return notice(guard.error === \"rate_limited\" ? 429 : 403);\n\t\tif (guard.action !== \"link_start\") return notice();\n\t\tif (!(await inactive(snapshot.cookie, input, config))) return notice(409);\n\t\treturn await admitStart(context, snapshot.cookie, guard);\n\t} catch {\n\t\treturn notice(503);\n\t}\n}\nasync function admitStart(\n\tcontext: Context,\n\tcookieHeader: string | null,\n\tguard: { attemptId: string; startCode: string; cookieHash: string },\n) {\n\tconst { input, config, client } = context;\n\tconst proof = await privateStart(input.readers, guard.attemptId, guard.startCode, config);\n\tconst cookie = await readBrowserCookie(cookieHeader, \"start\");\n\tif (!proof || cookie.kind !== \"present\" || cookie.cookieHash !== guard.cookieHash)\n\t\treturn notice();\n\tconst authorization = await client.createAuthorizationRequest();\n\tconst response = pageResponse(\n\t\tawait renderAuthSigninContinuePage({ authorizationUrl: authorization.authorizationUrl }),\n\t);\n\tconst claimed = await input.operations.claimBrowser(\n\t\t{\n\t\t\tattemptId: guard.attemptId,\n\t\t\tbrowserStartHash: proof.browserStartHash,\n\t\t\tstateHash: await stateHash(authorization.material.state),\n\t\t\tbinderHash: guard.cookieHash,\n\t\t\tnonce: authorization.material.nonce,\n\t\t\tpkceVerifier: authorization.material.pkceVerifier,\n\t\t},\n\t\tconfig,\n\t);\n\tif (!claimed) return notice(409);\n\tresponse.headers.append(\"Set-Cookie\", reissueStartCookieAsTransaction(cookie.secret));\n\tresponse.headers.append(\"Set-Cookie\", clearBrowserCookie(\"start\"));\n\treturn response;\n}\nasync function callbackPins(context: Context, request: Request) {\n\tconst { config } = context;\n\tconst snapshot = snapshotBrowserRequest(request);\n\tif (snapshot.method !== \"GET\" || snapshot.url.length > 8192 || snapshot.url.includes(\"#\"))\n\t\treturn null;\n\tconst url = new URL(snapshot.url),\n\t\tredirect = new URL(config.redirectUri);\n\tif (\n\t\turl.origin !== redirect.origin ||\n\t\turl.pathname !== redirect.pathname ||\n\t\turl.username ||\n\t\turl.password ||\n\t\turl.searchParams.getAll(\"state\").length !== 1\n\t)\n\t\treturn null;\n\tconst state = url.searchParams.get(\"state\");\n\tif (!state || !/^[A-Za-z0-9._~-]{43,128}$/.test(state)) return null;\n\tconst cookie = await readBrowserCookie(snapshot.cookie, \"transaction\");\n\tif (cookie.kind !== \"present\") return null;\n\treturn {\n\t\tstate,\n\t\tstateHash: await stateHash(state),\n\t\tbinderHash: cookie.cookieHash,\n\t\tcookie,\n\t\tcallbackUrl: snapshot.url,\n\t};\n}\nasync function matchesCallback(context: Context, request: Request): Promise<boolean> {\n\tconst { input, config } = context;\n\ttry {\n\t\tconst pins = await callbackPins(context, request);\n\t\treturn (\n\t\t\t!!pins &&\n\t\t\t(await input.operations.hasPendingCallback(\n\t\t\t\t{ stateHash: pins.stateHash, binderHash: pins.binderHash },\n\t\t\t\tconfig,\n\t\t\t))\n\t\t);\n\t} catch {\n\t\treturn false;\n\t}\n}\nasync function prepareVerifiedResponse(\n\tcontext: Context,\n\tpins: Pins,\n\tsecret: string,\n\tcookie: Extract<Awaited<ReturnType<typeof readBrowserCookie>>, { kind: \"present\" }>,\n\tverifiedProfile: Parameters<typeof projectAccountProfileView>[0],\n) {\n\tconst { input, config, scope } = context;\n\tconst view = await input.operations.readCallbackView(pins, config);\n\tif (!view || view.attemptId !== pins.attemptId) throw new Error(\"callback_unavailable\");\n\tif (view.intent === \"refresh\") return completion(view, secret);\n\tif (view.intent !== \"disconnect\") throw new Error(\"callback_unavailable\");\n\tconst csrf = await issueBrowserCsrfToken(input.csrfKey, cookie.secret, \"transaction\", scope);\n\tconst profile = projectAccountProfileView(verifiedProfile, config.issuer);\n\treturn formPage(\n\t\t\"Disconnect Google account\",\n\t\tACCOUNT_CHANGE_BROWSER_PATHS.confirm,\n\t\t{ attempt_id: pins.attemptId, csrf },\n\t\t`${profile.email ?? profile.title}. Disconnecting ends browser sessions for this connection and removes its display profile. Identity, device keys, history, membership, and access grants stay unchanged.`,\n\t);\n}\nasync function browserView(context: Context, pins: { attemptId: string; binderHash: string }) {\n\tconst { input, config } = context;\n\tconst binding = await input.readers.readBrowserBinding(pins, config);\n\tif (!binding || !/^[a-f0-9]{64}$/.test(binding.stateHash)) return null;\n\tconst view = await input.operations.readBrowserView(\n\t\t{ ...pins, stateHash: binding.stateHash },\n\t\tconfig,\n\t);\n\treturn view ? { ...view, stateHash: binding.stateHash } : null;\n}\nasync function callback(context: Context, request: Request, clientKey: string): Promise<Response> {\n\tconst { input, config } = context;\n\ttry {\n\t\tif (!isAuthControllerId(clientKey)) return notice(503);\n\t\tconst rate = checkBrowserAuthRequestRate(\n\t\t\trequest,\n\t\t\tinput.limiter,\n\t\t\tJSON.stringify([\"browser-callback\", config.coordinatorId, clientKey]),\n\t\t\t20,\n\t\t);\n\t\tif (!rate.allowed) return notice(429);\n\t\tconst material = await callbackPins(context, request);\n\t\tif (!material) return notice();\n\t\tconst lookup = { stateHash: material.stateHash, binderHash: material.binderHash };\n\t\t// Shared-purpose collisions never consume either ceremony or contact Google.\n\t\tif (await input.existing.readAuthBrowserTransactionPurpose(lookup, config)) return notice();\n\t\tconst consumed = await input.operations.consumeCallback(lookup, config);\n\t\tif (!consumed) return notice();\n\t\tconst pins = { ...lookup, attemptId: consumed.attemptId };\n\t\treturn await exchange(context, material, consumed, pins);\n\t} catch {\n\t\treturn notice(503);\n\t}\n}\nasync function exchange(\n\tcontext: Context,\n\tmaterial: NonNullable<Awaited<ReturnType<typeof callbackPins>>>,\n\tconsumed: NonNullable<Awaited<ReturnType<Operations[\"consumeCallback\"]>>>,\n\tpins: Pins,\n) {\n\tconst { input, config, client } = context;\n\ttry {\n\t\tif (!consumed.nonce || !consumed.pkceVerifier) throw new Error(\"missing_material\");\n\t\tconst verified = await client.verifyCallback({\n\t\t\tcallbackUrl: material.callbackUrl,\n\t\t\tmaterial: {\n\t\t\t\tstate: material.state,\n\t\t\t\tnonce: consumed.nonce,\n\t\t\t\tpkceVerifier: consumed.pkceVerifier,\n\t\t\t},\n\t\t});\n\t\tif (!verified.ok) throw new Error(\"provider_rejected\");\n\t\tconst bytes = crypto.getRandomValues(new Uint8Array(32));\n\t\tconst secret = encodeCoordinatorAuthProof32(bytes);\n\t\tconst response = await prepareVerifiedResponse(\n\t\t\tcontext,\n\t\t\tpins,\n\t\t\tsecret,\n\t\t\tmaterial.cookie,\n\t\t\tverified.profile,\n\t\t);\n\t\tconst recorded = await input.operations.recordVerifiedCallback(\n\t\t\t{\n\t\t\t\t...pins,\n\t\t\t\tissuer: verified.account.issuer,\n\t\t\t\tsubject: verified.account.subject,\n\t\t\t\tprofile: verified.profile,\n\t\t\t\tcompletionSecretHash: await hashCoordinatorAuthProofBytes32(bytes),\n\t\t\t},\n\t\t\tconfig,\n\t\t);\n\t\tif (!recorded) throw new Error(\"account_rejected\");\n\t\treturn response;\n\t} catch {\n\t\tawait input.operations.failConsumed(pins, config);\n\t\treturn notice();\n\t}\n}\nasync function confirm(context: Context, request: Request, clientKey: string): Promise<Response> {\n\tconst { input, config, scope, confirmUrl } = context;\n\ttry {\n\t\tconst snapshot = snapshotBrowserRequest(request);\n\t\tif (snapshot.method !== \"POST\") return notice(405);\n\t\tif (snapshot.url !== confirmUrl) return notice(404);\n\t\tconst guard = await guardBrowserForm({\n\t\t\trequest,\n\t\t\tclientKey,\n\t\t\tscope,\n\t\t\tcsrfKey: input.csrfKey,\n\t\t\tlimiter: input.limiter,\n\t\t\taction: \"transaction_attempt\",\n\t\t});\n\t\tif (!guard.ok) return notice(guard.error === \"rate_limited\" ? 429 : 403);\n\t\tif (guard.action !== \"transaction_attempt\") return notice();\n\t\tconst view = await browserView(context, {\n\t\t\tattemptId: guard.attemptId,\n\t\t\tbinderHash: guard.cookieHash,\n\t\t});\n\t\tif (!view || !confirmable(view, guard)) return notice();\n\t\tconst bytes = crypto.getRandomValues(new Uint8Array(32));\n\t\tconst response = await completion(view, encodeCoordinatorAuthProof32(bytes));\n\t\tif (\n\t\t\t!(await input.operations.confirmDisconnect(\n\t\t\t\t{\n\t\t\t\t\tattemptId: view.attemptId,\n\t\t\t\t\tstateHash: view.stateHash,\n\t\t\t\t\tbinderHash: guard.cookieHash,\n\t\t\t\t\tcompletionSecretHash: await hashCoordinatorAuthProofBytes32(bytes),\n\t\t\t\t},\n\t\t\t\tconfig,\n\t\t\t))\n\t\t)\n\t\t\treturn notice();\n\t\treturn response;\n\t} catch {\n\t\treturn notice(503);\n\t}\n}\nfunction confirmable(view: BrowserView, guard: { attemptId: string; cookieHash: string }) {\n\treturn (\n\t\tview.attemptId === guard.attemptId && view.intent === \"disconnect\" && view.state === \"verified\"\n\t);\n}\nexport async function createCoordinatorAccountChangeBrowser(input: AccountChangeBrowserInput) {\n\tconst settings = captureCoordinatorBrowserAuthConfig(input.config);\n\tif (settings.kind !== \"enabled\") return { ok: false as const, error: \"browser_auth_unavailable\" };\n\tif (\n\t\t!isBrowserCsrfKey(input.csrfKey) ||\n\t\t!input.readers ||\n\t\t[\"readStart\", \"readManagementActivity\", \"readBrowserBinding\"].some(\n\t\t\t(name) => typeof Reflect.get(input.readers, name) !== \"function\",\n\t\t)\n\t)\n\t\treturn { ok: false as const, error: \"private_reader_required\" };\n\tconst oidc = await createCoordinatorOidcClient(settings.oidc, input.oidcOptions);\n\tif (!oidc.ok) return oidc;\n\tconst context: Context = {\n\t\tinput,\n\t\tclient: oidc.client,\n\t\tconfig: settings.store,\n\t\tscope: { publicOrigin: settings.publicOrigin, store: settings.store },\n\t\tstartUrl: `${settings.publicOrigin}${ACCOUNT_CHANGE_BROWSER_PATHS.start}`,\n\t\tconfirmUrl: `${settings.publicOrigin}${ACCOUNT_CHANGE_BROWSER_PATHS.confirm}`,\n\t};\n\treturn {\n\t\tok: true as const,\n\t\thandlers: Object.freeze({\n\t\t\tstartPage: (request: Request) => startPage(context, request),\n\t\t\tstart: (request: Request, key: string) => start(context, request, key),\n\t\t\tmatchesCallback: (request: Request) => matchesCallback(context, request),\n\t\t\tcallback: (request: Request, key: string) => callback(context, request, key),\n\t\t\tconfirm: (request: Request, key: string) => confirm(context, request, key),\n\t\t}),\n\t};\n}\n","import type { CoordinatorAuthAccountProfileStore } from \"./coordinator-auth-account-profile-contract.js\";\nimport {\n\tAUTH_BROWSER_FORM_ACTIONS,\n\ttype CoordinatorAuthBrowserPage,\n\trenderAuthBrowserNotice,\n\trenderCurrentAccountPage,\n} from \"./coordinator-auth-browser-view.js\";\nimport { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport type { CoordinatorAuthSessionStore } from \"./coordinator-auth-session-contract.js\";\nimport {\n\ttype CoordinatorBrowserAuthConfigField,\n\ttype CoordinatorBrowserAuthSettings,\n\tcaptureCoordinatorBrowserAuthConfig,\n} from \"./coordinator-browser-auth-config.js\";\nimport { clearBrowserCookie, readBrowserCookie } from \"./coordinator-browser-credential.js\";\nimport {\n\ttype BrowserCsrfKey,\n\ttype BrowserCsrfScope,\n\tissueBrowserCsrfToken,\n} from \"./coordinator-browser-csrf.js\";\nimport { type BrowserFormGuardResult, guardBrowserForm } from \"./coordinator-browser-form-guard.js\";\nimport { snapshotBrowserRequest as snapshotRequest } from \"./coordinator-browser-request.js\";\nimport type { InMemoryRequestRateLimiter } from \"./request-rate-limit.js\";\n\ntype AccountStore = Pick<CoordinatorAuthAccountProfileStore, \"readAuthSessionAccount\"> &\n\tPick<CoordinatorAuthSessionStore, \"readAuthSession\" | \"signOutAuthSession\">;\ntype StoreConfig = Extract<CoordinatorBrowserAuthSettings, { kind: \"enabled\" }>[\"store\"];\nexport interface CoordinatorBrowserAccountInput {\n\tconfig: unknown;\n\tcsrfKey: BrowserCsrfKey;\n\tstore: AccountStore;\n\tlimiter: InMemoryRequestRateLimiter;\n}\nexport type CoordinatorBrowserAccountOutcome =\n\t| \"account_page\"\n\t| \"signed_out\"\n\t| \"already_signed_out\"\n\t| \"method_not_allowed\"\n\t| \"not_found\"\n\t| \"cookie_invalid\"\n\t| \"origin_rejected\"\n\t| \"rate_limited\"\n\t| \"unsupported_media_type\"\n\t| \"body_too_large\"\n\t| \"form_invalid\"\n\t| \"csrf_invalid\"\n\t| \"signout_unconfirmed\"\n\t| \"internal_error\";\nexport type CoordinatorBrowserAccountResponse = Readonly<{\n\tresponse: Response;\n\toutcome: CoordinatorBrowserAccountOutcome;\n}>;\nexport interface CoordinatorBrowserAccountHandlers {\n\taccount(request: Request): Promise<CoordinatorBrowserAccountResponse>;\n\tlogout(request: Request, clientKey: string): Promise<CoordinatorBrowserAccountResponse>;\n}\nexport type CoordinatorBrowserAccountResult =\n\t| Readonly<{ ok: true; handlers: Readonly<CoordinatorBrowserAccountHandlers> }>\n\t| Readonly<{\n\t\t\tok: false;\n\t\t\terror: \"browser_auth_config_invalid\";\n\t\t\tfield: CoordinatorBrowserAuthConfigField;\n\t }>\n\t| Readonly<{ ok: false; error: \"browser_auth_disabled\" | \"invalid_input\" }>;\n\nfunction object(value: unknown): asserts value is object {\n\tif (value === null || typeof value !== \"object\" || Array.isArray(value)) throw new Error();\n}\nfunction plain(value: unknown): void {\n\tobject(value);\n\tconst prototype = Object.getPrototypeOf(value);\n\tif (prototype !== Object.prototype && prototype !== null) throw new Error();\n}\nfunction ownData(value: unknown, name: string): unknown {\n\tobject(value);\n\tconst descriptor = Object.getOwnPropertyDescriptor(value, name);\n\tif (!descriptor || !Object.hasOwn(descriptor, \"value\")) throw new Error();\n\treturn descriptor.value;\n}\nfunction dataMethod(value: unknown, name: string): unknown {\n\tobject(value);\n\tconst seen = new Set<object>();\n\tlet cursor: object | null = value;\n\twhile (cursor !== null) {\n\t\tif (seen.has(cursor)) throw new Error();\n\t\tseen.add(cursor);\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(cursor, name);\n\t\tif (descriptor) {\n\t\t\tif (!Object.hasOwn(descriptor, \"value\") || typeof descriptor.value !== \"function\")\n\t\t\t\tthrow new Error();\n\t\t\treturn descriptor.value;\n\t\t}\n\t\tcursor = Object.getPrototypeOf(cursor);\n\t}\n\tthrow new Error();\n}\ntype Context = Readonly<{\n\tstoreConfig: StoreConfig;\n\tpublicOrigin: string;\n\tscope: BrowserCsrfScope;\n\tsignoutScope: Readonly<{ coordinatorId: string }>;\n\tcsrfKey: BrowserCsrfKey;\n\tstore: AccountStore;\n\tlimiter: InMemoryRequestRateLimiter;\n}>;\nfunction result(\n\tresponse: Response,\n\toutcome: CoordinatorBrowserAccountOutcome,\n): CoordinatorBrowserAccountResponse {\n\treturn Object.freeze({ response, outcome });\n}\nfunction pageResponse(\n\tpage: CoordinatorAuthBrowserPage,\n\tstatus = 200,\n\textra?: Record<string, string>,\n) {\n\tconst headers = new Headers(page.headers);\n\theaders.set(\"Cache-Control\", \"no-store\");\n\tif (extra)\n\t\tnew Headers(extra).forEach((value, name) => {\n\t\t\theaders.set(name, value);\n\t\t});\n\treturn new Response(page.body, { status, headers });\n}\nfunction fallback(): CoordinatorBrowserAccountResponse {\n\treturn result(\n\t\tnew Response(\"Account unavailable. Try again.\", {\n\t\t\tstatus: 503,\n\t\t\theaders: {\n\t\t\t\t\"Content-Type\": \"text/plain;charset=utf-8\",\n\t\t\t\t\"Cache-Control\": \"no-store\",\n\t\t\t\t\"Referrer-Policy\": \"no-referrer\",\n\t\t\t\t\"X-Content-Type-Options\": \"nosniff\",\n\t\t\t},\n\t\t}),\n\t\t\"internal_error\",\n\t);\n}\nasync function notice(\n\tstatus: number,\n\toutcome: CoordinatorBrowserAccountOutcome,\n\textra?: Record<string, string>,\n): Promise<CoordinatorBrowserAccountResponse> {\n\ttry {\n\t\tconst kind = status === 200 ? \"signed_out\" : \"auth_unavailable\";\n\t\treturn result(pageResponse(await renderAuthBrowserNotice(kind), status, extra), outcome);\n\t} catch {\n\t\treturn fallback();\n\t}\n}\nfunction routeError(snapshot: ReturnType<typeof snapshotRequest>, url: string, method: string) {\n\tif (snapshot.method !== method) return notice(405, \"method_not_allowed\", { Allow: method });\n\tif (snapshot.url !== url) return notice(404, \"not_found\");\n\treturn null;\n}\nfunction captureSession(value: unknown, context: Context): string {\n\tplain(value);\n\tconst account = ownData(value, \"account\");\n\tplain(account);\n\tconst issuer = ownData(account, \"issuer\");\n\tconst identityId = ownData(value, \"identityId\");\n\tif (issuer !== context.storeConfig.issuer || !isAuthControllerId(identityId)) throw new Error();\n\treturn identityId;\n}\nasync function account(\n\tcontext: Context,\n\trequest: Request,\n): Promise<CoordinatorBrowserAccountResponse> {\n\ttry {\n\t\tconst snapshot = snapshotRequest(request);\n\t\tconst routing = routeError(snapshot, `${context.publicOrigin}/auth/account`, \"GET\");\n\t\tif (routing) return await routing;\n\t\tconst cookie = await readBrowserCookie(snapshot.cookie, \"session\");\n\t\tif (cookie.kind === \"invalid\") return await notice(200, \"cookie_invalid\");\n\t\tif (cookie.kind === \"absent\") return await notice(200, \"signed_out\");\n\t\tconst current = await context.store.readAuthSessionAccount(\n\t\t\tcookie.cookieHash,\n\t\t\tcontext.storeConfig,\n\t\t);\n\t\tif (current === null) return await notice(200, \"signed_out\");\n\t\tplain(current);\n\t\tconst identityId = captureSession(ownData(current, \"session\"), context);\n\t\tconst profile = ownData(current, \"profile\");\n\t\tconst csrfToken = await issueBrowserCsrfToken(\n\t\t\tcontext.csrfKey,\n\t\t\tcookie.secret,\n\t\t\t\"session\",\n\t\t\tcontext.scope,\n\t\t);\n\t\treturn result(\n\t\t\tpageResponse(\n\t\t\t\tawait renderCurrentAccountPage({\n\t\t\t\t\tprofile,\n\t\t\t\t\tissuer: context.storeConfig.issuer,\n\t\t\t\t\tidentity: { id: identityId },\n\t\t\t\t\tcsrfToken,\n\t\t\t\t}),\n\t\t\t),\n\t\t\t\"account_page\",\n\t\t);\n\t} catch {\n\t\treturn await notice(503, \"internal_error\");\n\t}\n}\nfunction guardFailure(guard: Extract<BrowserFormGuardResult, { ok: false }>) {\n\tswitch (guard.error) {\n\t\tcase \"origin_rejected\":\n\t\t\treturn notice(403, guard.error);\n\t\tcase \"rate_limited\":\n\t\t\treturn notice(429, guard.error, { \"Retry-After\": String(guard.retryAfterS) });\n\t\tcase \"cookie_missing\":\n\t\t\treturn notice(200, \"signed_out\");\n\t\tcase \"unsupported_media_type\":\n\t\t\treturn notice(415, guard.error);\n\t\tcase \"body_too_large\":\n\t\t\treturn notice(413, guard.error);\n\t\tcase \"form_invalid\":\n\t\t\treturn notice(400, guard.error);\n\t\tcase \"cookie_invalid\":\n\t\tcase \"csrf_invalid\":\n\t\t\treturn notice(403, guard.error);\n\t\tdefault:\n\t\t\treturn notice(503, \"internal_error\");\n\t}\n}\nasync function signOut(context: Context, hash: string): Promise<CoordinatorBrowserAccountResponse> {\n\t// Build before touching persistence. Failure must keep the credential available for retry.\n\tconst response = pageResponse(await renderAuthBrowserNotice(\"signed_out\"));\n\tresponse.headers.append(\"Set-Cookie\", clearBrowserCookie(\"session\"));\n\tconst before = await context.store.readAuthSession(hash, context.storeConfig);\n\t// Current-config absence deliberately clears only the browser, without revoking old rows.\n\tif (before === null) return result(response, \"already_signed_out\");\n\tcaptureSession(before, context);\n\tconst written = await context.store.signOutAuthSession(hash, context.signoutScope);\n\tplain(written);\n\tif (ownData(written, \"kind\") !== \"signed_out\") return notice(503, \"internal_error\");\n\tconst after = await context.store.readAuthSession(hash, context.storeConfig);\n\tif (after === null) return result(response, \"signed_out\");\n\tcaptureSession(after, context);\n\treturn notice(503, \"signout_unconfirmed\");\n}\nasync function logout(\n\tcontext: Context,\n\trequest: Request,\n\tclientKey: string,\n): Promise<CoordinatorBrowserAccountResponse> {\n\ttry {\n\t\tconst snapshot = snapshotRequest(request);\n\t\tconst routing = routeError(\n\t\t\tsnapshot,\n\t\t\t`${context.publicOrigin}${AUTH_BROWSER_FORM_ACTIONS.signOut}`,\n\t\t\t\"POST\",\n\t\t);\n\t\tif (routing) return await routing;\n\t\t// No asynchronous boundary between our cookie snapshot and the guard's native snapshot.\n\t\tconst pendingGuard = guardBrowserForm({\n\t\t\trequest,\n\t\t\tscope: context.scope,\n\t\t\tcsrfKey: context.csrfKey,\n\t\t\taction: \"session_logout\",\n\t\t\tlimiter: context.limiter,\n\t\t\tclientKey,\n\t\t});\n\t\tconst guard = await pendingGuard;\n\t\tif (!guard.ok) return await guardFailure(guard);\n\t\tif (guard.action !== \"session_logout\") return await notice(503, \"internal_error\");\n\t\tconst cookie = await readBrowserCookie(snapshot.cookie, \"session\");\n\t\tif (cookie.kind !== \"present\" || cookie.cookieHash !== guard.cookieHash)\n\t\t\treturn await notice(503, \"internal_error\");\n\t\treturn await signOut(context, cookie.cookieHash);\n\t} catch {\n\t\treturn await notice(503, \"internal_error\");\n\t}\n}\nfunction captureStore(receiver: unknown): AccountStore {\n\tconst readAccount = dataMethod(\n\t\treceiver,\n\t\t\"readAuthSessionAccount\",\n\t) as AccountStore[\"readAuthSessionAccount\"];\n\tconst read = dataMethod(receiver, \"readAuthSession\") as AccountStore[\"readAuthSession\"];\n\tconst signout = dataMethod(receiver, \"signOutAuthSession\") as AccountStore[\"signOutAuthSession\"];\n\treturn Object.freeze({\n\t\treadAuthSessionAccount: readAccount.bind(receiver),\n\t\treadAuthSession: read.bind(receiver),\n\t\tsignOutAuthSession: signout.bind(receiver),\n\t});\n}\n/** Unmounted local account/logout only. No provider client, profile writes or route registration. */\nexport async function createCoordinatorBrowserAccount(\n\tinput: CoordinatorBrowserAccountInput,\n): Promise<CoordinatorBrowserAccountResult> {\n\ttry {\n\t\tconst config = ownData(input, \"config\");\n\t\tconst settings = captureCoordinatorBrowserAuthConfig(config);\n\t\tif (settings.kind === \"disabled\")\n\t\t\treturn Object.freeze({ ok: false, error: \"browser_auth_disabled\" });\n\t\tif (settings.kind === \"invalid\")\n\t\t\treturn Object.freeze({\n\t\t\t\tok: false,\n\t\t\t\terror: \"browser_auth_config_invalid\",\n\t\t\t\tfield: settings.field,\n\t\t\t});\n\t\tconst csrfKey = ownData(input, \"csrfKey\") as BrowserCsrfKey;\n\t\tobject(csrfKey);\n\t\tconst store = captureStore(ownData(input, \"store\"));\n\t\tconst limiter = ownData(input, \"limiter\") as InMemoryRequestRateLimiter;\n\t\tdataMethod(limiter, \"check\");\n\t\tconst context: Context = Object.freeze({\n\t\t\tstoreConfig: settings.store,\n\t\t\tpublicOrigin: settings.publicOrigin,\n\t\t\tscope: Object.freeze({ publicOrigin: settings.publicOrigin, store: settings.store }),\n\t\t\tsignoutScope: Object.freeze({ coordinatorId: settings.store.coordinatorId }),\n\t\t\tcsrfKey,\n\t\t\tstore,\n\t\t\tlimiter,\n\t\t});\n\t\treturn Object.freeze({\n\t\t\tok: true,\n\t\t\thandlers: Object.freeze({\n\t\t\t\taccount: (request: Request) => account(context, request),\n\t\t\t\tlogout: (request: Request, clientKey: string) => logout(context, request, clientKey),\n\t\t\t}),\n\t\t});\n\t} catch {\n\t\treturn Object.freeze({ ok: false, error: \"invalid_input\" });\n\t}\n}\n","import type { CoordinatorAuthAccountProfileStore } from \"./coordinator-auth-account-profile-contract.js\";\nimport type {\n\tCoordinatorAuthBrowserTransactionConsumeResult,\n\tCoordinatorAuthBrowserTransactionPurposeStore,\n\tCoordinatorAuthBrowserTransactionStore,\n} from \"./coordinator-auth-browser-transaction-contract.js\";\nimport { renderAuthBrowserNotice } from \"./coordinator-auth-browser-view.js\";\nimport type { CoordinatorAuthSessionStore } from \"./coordinator-auth-session-contract.js\";\nimport {\n\ttype CoordinatorBrowserAuthConfigField,\n\ttype CoordinatorBrowserAuthSettings,\n\tcaptureCoordinatorBrowserAuthConfig,\n} from \"./coordinator-browser-auth-config.js\";\nimport {\n\ttype BrowserCookieReadResult,\n\ttype BrowserCookieSecret,\n\tissueBrowserCookie,\n\treadBrowserCookie,\n} from \"./coordinator-browser-credential.js\";\nimport {\n\ttype CoordinatorOidcClient,\n\ttype CoordinatorOidcOptions,\n\tcreateCoordinatorOidcClient,\n} from \"./coordinator-oidc.js\";\n\ntype CallbackStore = Pick<CoordinatorAuthBrowserTransactionStore, \"consumeAuthBrowserTransaction\"> &\n\tPick<CoordinatorAuthSessionStore, \"readAuthSession\" | \"signInWithConsumedBrowserTransaction\"> &\n\tPick<CoordinatorAuthAccountProfileStore, \"recordAuthAccountProfile\">;\ntype Settings = Extract<CoordinatorBrowserAuthSettings, { kind: \"enabled\" }>;\ntype Consumed = Extract<CoordinatorAuthBrowserTransactionConsumeResult, { kind: \"consumed\" }>;\ntype TransactionCookie = Extract<BrowserCookieReadResult, { kind: \"present\" }>;\ntype Verification = Awaited<ReturnType<CoordinatorOidcClient[\"verifyCallback\"]>>;\nexport type CoordinatorBrowserAuthLinkCompletionInput = Readonly<{\n\tattemptId: string;\n\tbrowserTransactionHash: string;\n\ttransactionCookie: BrowserCookieSecret;\n\ttransactionCookieHash: string;\n\tverification: Readonly<Verification>;\n}>;\nexport interface CoordinatorBrowserAuthCallbackInput {\n\tconfig: unknown;\n\tstore: CallbackStore;\n\tcompleteLink: (input: CoordinatorBrowserAuthLinkCompletionInput) => Promise<Response>;\n\toidcOptions?: CoordinatorOidcOptions;\n\townerCallback?: (request: Request, trustedClientKey: string) => Promise<Response>;\n\tpurposeStore?: CoordinatorAuthBrowserTransactionPurposeStore;\n\taccountChangeCallback?: (\n\t\trequest: Request,\n\t\ttrustedClientKey: string,\n\t\tbinderHash: string,\n\t) => Promise<Response | null>;\n\t/**\n\t * Device rebind (ADR 0005 Section 8). Its transactions reuse the\n\t * `owner_enroll` purpose, so it runs only for that stored purpose and before\n\t * owner dispatch; null means the callback is not a rebind.\n\t */\n\tdeviceRebindCallback?: (request: Request) => Promise<Response | null>;\n}\nexport type CoordinatorBrowserAuthCallbackOutcome =\n\t| \"signed_in\"\n\t| \"signed_in_profile_not_recorded\"\n\t| \"session_live\"\n\t| \"link_dispatched\"\n\t| \"owner_dispatched\"\n\t| \"account_change_dispatched\"\n\t| \"device_rebind_dispatched\"\n\t| \"method_not_allowed\"\n\t| \"not_found\"\n\t| \"callback_invalid\"\n\t| \"state_invalid\"\n\t| \"cookie_invalid\"\n\t| \"cookie_missing\"\n\t| \"transaction_unavailable\"\n\t| \"verification_failed\"\n\t| \"signin_rejected\"\n\t| \"link_continuation_failed\"\n\t| \"internal_error\";\nexport type CoordinatorBrowserAuthCallbackResponse = Readonly<{\n\tresponse: Response;\n\toutcome: CoordinatorBrowserAuthCallbackOutcome;\n}>;\nexport interface CoordinatorBrowserAuthCallbackHandlers {\n\tcallback(\n\t\trequest: Request,\n\t\ttrustedClientKey?: string,\n\t): Promise<CoordinatorBrowserAuthCallbackResponse>;\n}\nexport type CoordinatorBrowserAuthCallbackResult =\n\t| Readonly<{ ok: true; handlers: Readonly<CoordinatorBrowserAuthCallbackHandlers> }>\n\t| Readonly<{\n\t\t\tok: false;\n\t\t\terror: \"browser_auth_config_invalid\";\n\t\t\tfield: CoordinatorBrowserAuthConfigField;\n\t }>\n\t| Readonly<{\n\t\t\tok: false;\n\t\t\terror:\n\t\t\t\t| \"browser_auth_disabled\"\n\t\t\t\t| \"invalid_input\"\n\t\t\t\t| \"oidc_discovery_failed\"\n\t\t\t\t| \"invalid_provider_configuration\";\n\t }>;\n\nfunction ownData(value: unknown, name: string): unknown {\n\tif (value === null || typeof value !== \"object\" || Array.isArray(value)) throw new Error();\n\tconst descriptor = Object.getOwnPropertyDescriptor(value, name);\n\tif (descriptor && !Object.hasOwn(descriptor, \"value\")) throw new Error();\n\treturn descriptor?.value;\n}\nfunction dataMethod(value: unknown, name: string): unknown {\n\tif (value === null || typeof value !== \"object\" || Array.isArray(value)) throw new Error();\n\tconst seen = new Set<object>();\n\tlet cursor: object | null = value;\n\twhile (cursor !== null) {\n\t\tif (seen.has(cursor)) throw new Error();\n\t\tseen.add(cursor);\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(cursor, name);\n\t\tif (descriptor) {\n\t\t\tif (!Object.hasOwn(descriptor, \"value\") || typeof descriptor.value !== \"function\")\n\t\t\t\tthrow new Error();\n\t\t\treturn descriptor.value;\n\t\t}\n\t\tcursor = Object.getPrototypeOf(cursor);\n\t}\n\tthrow new Error();\n}\nfunction captureStore(receiver: unknown): CallbackStore {\n\tconst consume = dataMethod(\n\t\treceiver,\n\t\t\"consumeAuthBrowserTransaction\",\n\t) as CallbackStore[\"consumeAuthBrowserTransaction\"];\n\tconst read = dataMethod(receiver, \"readAuthSession\") as CallbackStore[\"readAuthSession\"];\n\tconst signin = dataMethod(\n\t\treceiver,\n\t\t\"signInWithConsumedBrowserTransaction\",\n\t) as CallbackStore[\"signInWithConsumedBrowserTransaction\"];\n\tconst profile = dataMethod(\n\t\treceiver,\n\t\t\"recordAuthAccountProfile\",\n\t) as CallbackStore[\"recordAuthAccountProfile\"];\n\treturn Object.freeze({\n\t\tconsumeAuthBrowserTransaction: (...args) => Reflect.apply(consume, receiver, args),\n\t\treadAuthSession: (...args) => Reflect.apply(read, receiver, args),\n\t\tsignInWithConsumedBrowserTransaction: (...args) => Reflect.apply(signin, receiver, args),\n\t\trecordAuthAccountProfile: (...args) => Reflect.apply(profile, receiver, args),\n\t});\n}\nfunction captureOidcOptions(input: unknown): CoordinatorOidcOptions | undefined {\n\tconst supplied = ownData(input, \"oidcOptions\");\n\tif (supplied === undefined) return undefined;\n\tconst fetch = ownData(supplied, \"fetch\") as CoordinatorOidcOptions[\"fetch\"];\n\tconst timeoutSeconds = ownData(\n\t\tsupplied,\n\t\t\"timeoutSeconds\",\n\t) as CoordinatorOidcOptions[\"timeoutSeconds\"];\n\treturn Object.freeze({ fetch, timeoutSeconds });\n}\nfunction nativeGetter(prototype: object, name: string): ((this: Request) => unknown) | undefined {\n\tlet cursor: object | null = prototype;\n\twhile (cursor !== null) {\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(cursor, name);\n\t\tif (descriptor) return descriptor.get;\n\t\tcursor = Object.getPrototypeOf(cursor);\n\t}\n\treturn undefined;\n}\nconst requestGetters = Object.freeze({\n\tmethod: nativeGetter(Request.prototype, \"method\"),\n\turl: nativeGetter(Request.prototype, \"url\"),\n\theaders: nativeGetter(Request.prototype, \"headers\"),\n});\nconst headersGet = Headers.prototype.get;\nconst responseStatus = nativeGetter(Response.prototype, \"status\");\nfunction snapshotRequest(request: Request) {\n\tconst method = requestGetters.method?.call(request);\n\tconst url = requestGetters.url?.call(request);\n\tconst headers = requestGetters.headers?.call(request) as Headers;\n\tif (typeof method !== \"string\" || typeof url !== \"string\") throw new Error();\n\treturn Object.freeze({ method, url, cookie: headersGet.call(headers, \"cookie\") });\n}\ntype Snapshot = ReturnType<typeof snapshotRequest>;\ntype Context = Readonly<{\n\tstoreConfig: Settings[\"store\"];\n\tpublicOrigin: string;\n\tcallbackURI: string;\n\tclient: CoordinatorOidcClient;\n\tstore: CallbackStore;\n\tcompleteLink: CoordinatorBrowserAuthCallbackInput[\"completeLink\"];\n\townerCallback?: CoordinatorBrowserAuthCallbackInput[\"ownerCallback\"];\n\taccountChangeCallback?: CoordinatorBrowserAuthCallbackInput[\"accountChangeCallback\"];\n\tdeviceRebindCallback?: CoordinatorBrowserAuthCallbackInput[\"deviceRebindCallback\"];\n\treadPurpose?: CoordinatorAuthBrowserTransactionPurposeStore[\"readAuthBrowserTransactionPurpose\"];\n}>;\n\nfunction result(\n\tresponse: Response,\n\toutcome: CoordinatorBrowserAuthCallbackOutcome,\n): CoordinatorBrowserAuthCallbackResponse {\n\treturn Object.freeze({ response, outcome });\n}\nasync function notice(\n\tstatus: number,\n\toutcome: CoordinatorBrowserAuthCallbackOutcome,\n\toptions: { allow?: string } = {},\n): Promise<CoordinatorBrowserAuthCallbackResponse> {\n\ttry {\n\t\tconst page = await renderAuthBrowserNotice(\"auth_unavailable\");\n\t\tconst headers = new Headers(page.headers);\n\t\tif (options.allow) headers.set(\"Allow\", options.allow);\n\t\treturn result(new Response(page.body, { status, headers }), outcome);\n\t} catch {\n\t\tconst headers = new Headers({\n\t\t\t\"Content-Type\": \"text/plain;charset=utf-8\",\n\t\t\t\"Cache-Control\": \"no-store\",\n\t\t\t\"Referrer-Policy\": \"no-referrer\",\n\t\t\t\"X-Content-Type-Options\": \"nosniff\",\n\t\t});\n\t\tif (options.allow) headers.set(\"Allow\", options.allow);\n\t\treturn result(\n\t\t\tnew Response(\n\t\t\t\t\"Sign-in or linking unavailable. Return to the flow you started and try again.\",\n\t\t\t\t{ status: 503, headers },\n\t\t\t),\n\t\t\t\"internal_error\",\n\t\t);\n\t}\n}\nfunction accountResponse(context: Context, sessionCookie?: string): Response {\n\tconst headers = new Headers({\n\t\tLocation: new URL(\"/auth/account\", context.publicOrigin).href,\n\t\t\"Cache-Control\": \"no-store\",\n\t\t\"Referrer-Policy\": \"no-referrer\",\n\t});\n\tif (sessionCookie) headers.append(\"Set-Cookie\", sessionCookie);\n\treturn new Response(null, { status: 303, headers });\n}\nfunction callbackState(\n\tcontext: Context,\n\tsnapshot: Snapshot,\n): { state: string } | { error: \"callback_invalid\" | \"not_found\" | \"state_invalid\" } {\n\tif (snapshot.url.length > 8192 || snapshot.url.includes(\"#\"))\n\t\treturn { error: \"callback_invalid\" };\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(snapshot.url);\n\t} catch {\n\t\treturn { error: \"callback_invalid\" };\n\t}\n\tconst redirect = new URL(context.callbackURI);\n\tif (url.origin !== redirect.origin || url.pathname !== redirect.pathname)\n\t\treturn { error: \"not_found\" };\n\tconst states = url.searchParams.getAll(\"state\");\n\tconst state = states[0];\n\tif (\n\t\tstates.length !== 1 ||\n\t\ttypeof state !== \"string\" ||\n\t\tstate.length < 43 ||\n\t\tstate.length > 128 ||\n\t\t!/^[A-Za-z0-9._~-]+$/.test(state)\n\t)\n\t\treturn { error: \"state_invalid\" };\n\treturn { state };\n}\nasync function hashState(state: string): Promise<string> {\n\tconst digest = await globalThis.crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(state));\n\treturn Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\nasync function verify(\n\tcontext: Context,\n\tsnapshot: Snapshot,\n\tstate: string,\n\tconsumed: Consumed,\n): Promise<Readonly<Verification>> {\n\ttry {\n\t\tconst verified = await context.client.verifyCallback({\n\t\t\tcallbackUrl: snapshot.url,\n\t\t\tmaterial: { state, nonce: consumed.nonce, pkceVerifier: consumed.pkceVerifier },\n\t\t});\n\t\tif (!verified.ok) return Object.freeze({ ok: false, error: verified.error });\n\t\tif (verified.account.issuer !== context.storeConfig.issuer) throw new Error();\n\t\treturn Object.freeze({\n\t\t\tok: true,\n\t\t\taccount: Object.freeze({ ...verified.account }),\n\t\t\tprofile: Object.freeze({ ...verified.profile }),\n\t\t});\n\t} catch {\n\t\treturn Object.freeze({ ok: false, error: \"oidc_verification_failed\" });\n\t}\n}\nasync function dispatchLink(\n\tcontext: Context,\n\tconsumed: Extract<Consumed, { purpose: \"link\" }>,\n\tcookie: TransactionCookie,\n\tverification: Readonly<Verification>,\n): Promise<CoordinatorBrowserAuthCallbackResponse> {\n\ttry {\n\t\tconst response = await context.completeLink(\n\t\t\tObject.freeze({\n\t\t\t\tattemptId: consumed.attemptId,\n\t\t\t\tbrowserTransactionHash: consumed.browserTransactionHash,\n\t\t\t\ttransactionCookie: cookie.secret,\n\t\t\t\ttransactionCookieHash: cookie.cookieHash,\n\t\t\t\tverification,\n\t\t\t}),\n\t\t);\n\t\t// Use the native brand check, not an overridable status property or instanceof.\n\t\tif (!responseStatus || typeof Reflect.apply(responseStatus, response, []) !== \"number\")\n\t\t\tthrow new Error();\n\t\treturn result(response, \"link_dispatched\");\n\t} catch {\n\t\treturn notice(503, \"link_continuation_failed\");\n\t}\n}\nasync function recordProfile(\n\tcontext: Context,\n\tcredentialHash: string,\n\tverification: Extract<Verification, { ok: true }>,\n\tresponse: Response,\n): Promise<CoordinatorBrowserAuthCallbackResponse> {\n\ttry {\n\t\tconst recorded = await context.store.recordAuthAccountProfile(\n\t\t\t{ credentialHash, profile: verification.profile },\n\t\t\tcontext.storeConfig,\n\t\t);\n\t\tif (recorded.kind === \"recorded\") return result(response, \"signed_in\");\n\t} catch {\n\t\t// Display metadata failure must not discard a durably issued session response.\n\t}\n\treturn result(response, \"signed_in_profile_not_recorded\");\n}\nasync function signIn(\n\tcontext: Context,\n\tsnapshot: Snapshot,\n\tconsumed: Consumed,\n\tverification: Readonly<Verification>,\n): Promise<CoordinatorBrowserAuthCallbackResponse> {\n\tif (!verification.ok) return notice(403, \"verification_failed\");\n\tconst existing = await readBrowserCookie(snapshot.cookie, \"session\");\n\tif (existing.kind === \"invalid\") throw new Error();\n\tif (\n\t\texisting.kind === \"present\" &&\n\t\t(await context.store.readAuthSession(existing.cookieHash, context.storeConfig))\n\t)\n\t\treturn result(accountResponse(context), \"session_live\");\n\tconst issued = await issueBrowserCookie(\"session\");\n\tconst response = accountResponse(context, issued.setCookie);\n\t// Prebuild cookies locally; release the session bearer only after guarded persistence.\n\tconst persisted = await context.store.signInWithConsumedBrowserTransaction(\n\t\t{\n\t\t\tbrowserTransactionHash: consumed.browserTransactionHash,\n\t\t\taccount: verification.account,\n\t\t\tcredentialHash: issued.cookieHash,\n\t\t},\n\t\tcontext.storeConfig,\n\t);\n\tif (persisted.kind !== \"issued\") return notice(403, \"signin_rejected\");\n\treturn recordProfile(context, issued.cookieHash, verification, response);\n}\nasync function dispatchOwnerCallback(\n\tcontext: Context,\n\trequest: Request,\n\ttrustedClientKey: string,\n\tstateHash: string,\n\tbinderHash: string,\n): Promise<CoordinatorBrowserAuthCallbackResponse | null> {\n\tif (!context.readPurpose) return null;\n\tconst purpose = await context.readPurpose({ stateHash, binderHash }, context.storeConfig);\n\tconst rebind = purpose === \"owner_enroll\" ? await context.deviceRebindCallback?.(request) : null;\n\tif (rebind) return result(rebind, \"device_rebind_dispatched\");\n\tif (purpose === \"owner_enroll\" && context.ownerCallback)\n\t\treturn result(await context.ownerCallback(request, trustedClientKey), \"owner_dispatched\");\n\tif (purpose === \"signin\" || purpose === \"link\") return null;\n\treturn notice(403, \"transaction_unavailable\");\n}\n\nasync function callback(\n\tcontext: Context,\n\trequest: Request,\n\ttrustedClientKey: string,\n): Promise<CoordinatorBrowserAuthCallbackResponse> {\n\ttry {\n\t\tconst snapshot = snapshotRequest(request);\n\t\tif (snapshot.method !== \"GET\") return await notice(405, \"method_not_allowed\", { allow: \"GET\" });\n\t\tconst parsed = callbackState(context, snapshot);\n\t\tif (\"error\" in parsed)\n\t\t\treturn await notice(parsed.error === \"not_found\" ? 404 : 400, parsed.error);\n\t\tconst cookie = await readBrowserCookie(snapshot.cookie, \"transaction\");\n\t\tif (cookie.kind === \"invalid\") return await notice(400, \"cookie_invalid\");\n\t\tif (cookie.kind === \"absent\") return await notice(403, \"cookie_missing\");\n\t\tconst stateHash = await hashState(parsed.state);\n\t\tconst change = await context.accountChangeCallback?.(\n\t\t\trequest,\n\t\t\ttrustedClientKey ?? \"\",\n\t\t\tcookie.cookieHash,\n\t\t);\n\t\tif (change) return result(change, \"account_change_dispatched\");\n\t\tconst owner = await dispatchOwnerCallback(\n\t\t\tcontext,\n\t\t\trequest,\n\t\t\ttrustedClientKey,\n\t\t\tstateHash,\n\t\t\tcookie.cookieHash,\n\t\t);\n\t\tif (owner) return owner;\n\t\t// Atomic consumption burns matching material before any provider verification.\n\t\tconst consumed = await context.store.consumeAuthBrowserTransaction(\n\t\t\t{ stateHash, binderHash: cookie.cookieHash },\n\t\t\tcontext.storeConfig,\n\t\t);\n\t\tif (consumed.kind !== \"consumed\") return await notice(403, \"transaction_unavailable\");\n\t\tconst verification = await verify(context, snapshot, parsed.state, consumed);\n\t\tif (consumed.purpose === \"link\")\n\t\t\treturn await dispatchLink(context, consumed, cookie, verification);\n\t\tif (consumed.purpose !== \"signin\") throw new Error();\n\t\treturn await signIn(context, snapshot, consumed, verification);\n\t} catch {\n\t\t// Terminal replies may arrive after a newer start has replaced the shared cookie.\n\t\treturn notice(503, \"internal_error\");\n\t}\n}\n\n/** Unmounted callback only. Linking lifecycle and route registration belong to callers. */\nexport async function createCoordinatorBrowserAuthCallback(\n\tinput: CoordinatorBrowserAuthCallbackInput,\n): Promise<CoordinatorBrowserAuthCallbackResult> {\n\ttry {\n\t\tconst settings = captureCoordinatorBrowserAuthConfig(ownData(input, \"config\"));\n\t\tif (settings.kind === \"disabled\")\n\t\t\treturn Object.freeze({ ok: false, error: \"browser_auth_disabled\" });\n\t\tif (settings.kind === \"invalid\")\n\t\t\treturn Object.freeze({\n\t\t\t\tok: false,\n\t\t\t\terror: \"browser_auth_config_invalid\",\n\t\t\t\tfield: settings.field,\n\t\t\t});\n\t\tconst completeLink = ownData(input, \"completeLink\");\n\t\tif (typeof completeLink !== \"function\") throw new Error();\n\t\tconst store = captureStore(ownData(input, \"store\"));\n\t\tconst ownerCallback = ownData(input, \"ownerCallback\");\n\t\tconst accountChangeCallback = ownData(input, \"accountChangeCallback\");\n\t\tif (accountChangeCallback !== undefined && typeof accountChangeCallback !== \"function\")\n\t\t\tthrow new Error();\n\t\tconst deviceRebindCallback = ownData(input, \"deviceRebindCallback\");\n\t\tif (deviceRebindCallback !== undefined && typeof deviceRebindCallback !== \"function\")\n\t\t\tthrow new Error();\n\t\tlet readPurpose: Context[\"readPurpose\"];\n\t\tif (ownerCallback !== undefined && typeof ownerCallback !== \"function\") throw new Error();\n\t\tif (ownerCallback !== undefined || deviceRebindCallback !== undefined) {\n\t\t\tconst receiver = ownData(input, \"purposeStore\");\n\t\t\tconst method = dataMethod(\n\t\t\t\treceiver,\n\t\t\t\t\"readAuthBrowserTransactionPurpose\",\n\t\t\t) as CoordinatorAuthBrowserTransactionPurposeStore[\"readAuthBrowserTransactionPurpose\"];\n\t\t\treadPurpose = (...args) => Reflect.apply(method, receiver, args);\n\t\t}\n\t\tconst options = captureOidcOptions(input);\n\t\tconst oidc = await createCoordinatorOidcClient(settings.oidc, options);\n\t\tif (!oidc.ok) return Object.freeze({ ok: false, error: oidc.error });\n\t\tconst context: Context = Object.freeze({\n\t\t\tstoreConfig: settings.store,\n\t\t\tpublicOrigin: settings.publicOrigin,\n\t\t\tcallbackURI: settings.store.redirectUri,\n\t\t\tclient: oidc.client,\n\t\t\tstore,\n\t\t\tcompleteLink: completeLink as CoordinatorBrowserAuthCallbackInput[\"completeLink\"],\n\t\t\townerCallback: ownerCallback as CoordinatorBrowserAuthCallbackInput[\"ownerCallback\"],\n\t\t\taccountChangeCallback:\n\t\t\t\taccountChangeCallback as CoordinatorBrowserAuthCallbackInput[\"accountChangeCallback\"],\n\t\t\tdeviceRebindCallback:\n\t\t\t\tdeviceRebindCallback as CoordinatorBrowserAuthCallbackInput[\"deviceRebindCallback\"],\n\t\t\treadPurpose,\n\t\t});\n\t\treturn Object.freeze({\n\t\t\tok: true,\n\t\t\thandlers: Object.freeze({\n\t\t\t\tcallback: (request: Request, trustedClientKey = \"\") =>\n\t\t\t\t\tcallback(context, request, trustedClientKey),\n\t\t\t}),\n\t\t});\n\t} catch {\n\t\treturn Object.freeze({ ok: false, error: \"invalid_input\" });\n\t}\n}\n","import type {\n\tCoordinatorAuthBrowserConfig,\n\tCoordinatorAuthBrowserTransactionStore,\n} from \"./coordinator-auth-browser-transaction-contract.js\";\nimport {\n\tAUTH_BROWSER_FORM_ACTIONS,\n\ttype CoordinatorAuthBrowserPage,\n\trenderAuthBrowserNotice,\n\trenderAuthLinkCompletionHopPage,\n\trenderAuthLinkConfirmPage,\n} from \"./coordinator-auth-browser-view.js\";\nimport type { CoordinatorAuthLinkStore } from \"./coordinator-auth-link-contract.js\";\nimport type { CoordinatorBrowserAuthLinkCompletionInput } from \"./coordinator-browser-auth-callback.js\";\nimport {\n\tBROWSER_COOKIE_NAMES,\n\ttype BrowserCookieSecret,\n\tbrowserCookieValue,\n\treadBrowserCookie,\n} from \"./coordinator-browser-credential.js\";\nimport {\n\ttype BrowserCsrfKey,\n\ttype BrowserCsrfScope,\n\tissueBrowserCsrfToken,\n} from \"./coordinator-browser-csrf.js\";\nimport { type BrowserFormGuardResult, guardBrowserForm } from \"./coordinator-browser-form-guard.js\";\nimport { snapshotBrowserRequest } from \"./coordinator-browser-request.js\";\nimport type { InMemoryRequestRateLimiter } from \"./request-rate-limit.js\";\n\ntype LinkStore = Pick<\n\tCoordinatorAuthBrowserTransactionStore,\n\t\"resolveAuthLinkBrowserTransaction\" | \"retireAuthBrowserTransactions\"\n> &\n\tPick<\n\t\tCoordinatorAuthLinkStore,\n\t\t| \"recordAuthLinkOidcVerified\"\n\t\t| \"readAuthLinkCompletionDestination\"\n\t\t| \"confirmAuthLinkAttempt\"\n\t\t| \"failAuthLinkAttempt\"\n\t>;\nexport interface CoordinatorBrowserLinkInput {\n\tconfig: CoordinatorAuthBrowserConfig;\n\tcsrfKey: BrowserCsrfKey;\n\tstore: LinkStore;\n\tlimiter: InMemoryRequestRateLimiter;\n}\nexport type CoordinatorBrowserLinkCallback = (\n\tinput: CoordinatorBrowserAuthLinkCompletionInput,\n) => Promise<Response>;\nexport type CoordinatorBrowserLinkOutcome =\n\t| \"link_confirmation\"\n\t| \"link_confirmed\"\n\t| \"link_cancelled\"\n\t| \"method_not_allowed\"\n\t| \"not_found\"\n\t| \"link_rejected\"\n\t| \"origin_rejected\"\n\t| \"rate_limited\"\n\t| \"unsupported_media_type\"\n\t| \"body_too_large\"\n\t| \"form_invalid\"\n\t| \"cookie_missing\"\n\t| \"cookie_invalid\"\n\t| \"csrf_invalid\"\n\t| \"internal_error\";\nexport type CoordinatorBrowserLinkResponse = Readonly<{\n\tresponse: Response;\n\toutcome: CoordinatorBrowserLinkOutcome;\n}>;\nexport interface CoordinatorBrowserLinkHandlers {\n\tcompleteLink: CoordinatorBrowserLinkCallback;\n\tconfirm(request: Request, clientKey: string): Promise<CoordinatorBrowserLinkResponse>;\n\tcancel(request: Request, clientKey: string): Promise<CoordinatorBrowserLinkResponse>;\n}\nexport type CoordinatorBrowserLinkResult =\n\t| Readonly<{ ok: false; error: \"browser_auth_disabled\" }>\n\t| Readonly<{ ok: true; handlers: Readonly<CoordinatorBrowserLinkHandlers> }>;\ntype Context = Readonly<CoordinatorBrowserLinkInput & { scope: BrowserCsrfScope }>;\n\nfunction result(\n\tresponse: Response,\n\toutcome: CoordinatorBrowserLinkOutcome,\n): CoordinatorBrowserLinkResponse {\n\treturn Object.freeze({ response, outcome });\n}\nfunction pageResponse(\n\tpage: CoordinatorAuthBrowserPage,\n\tstatus = 200,\n\textra?: Record<string, string>,\n): Response {\n\tconst headers = new Headers(page.headers);\n\theaders.set(\"Cache-Control\", \"no-store\");\n\tif (extra)\n\t\tnew Headers(extra).forEach((value, name) => {\n\t\t\theaders.set(name, value);\n\t\t});\n\treturn new Response(page.body, { status, headers });\n}\nfunction fallback(): CoordinatorBrowserLinkResponse {\n\treturn result(\n\t\tnew Response(\"Account linking unavailable. Try again.\", {\n\t\t\tstatus: 503,\n\t\t\theaders: {\n\t\t\t\t\"Content-Type\": \"text/plain;charset=utf-8\",\n\t\t\t\t\"Cache-Control\": \"no-store\",\n\t\t\t\t\"Referrer-Policy\": \"no-referrer\",\n\t\t\t\t\"X-Content-Type-Options\": \"nosniff\",\n\t\t\t},\n\t\t}),\n\t\t\"internal_error\",\n\t);\n}\nasync function notice(\n\tstatus: number,\n\toutcome: CoordinatorBrowserLinkOutcome,\n\textra?: Record<string, string>,\n): Promise<CoordinatorBrowserLinkResponse> {\n\ttry {\n\t\treturn result(\n\t\t\tpageResponse(await renderAuthBrowserNotice(\"auth_unavailable\"), status, extra),\n\t\t\toutcome,\n\t\t);\n\t} catch {\n\t\treturn fallback();\n\t}\n}\nfunction guardFailure(guard: Extract<BrowserFormGuardResult, { ok: false }>) {\n\tswitch (guard.error) {\n\t\tcase \"rate_limited\":\n\t\t\treturn notice(429, guard.error, { \"Retry-After\": String(guard.retryAfterS) });\n\t\tcase \"unsupported_media_type\":\n\t\t\treturn notice(415, guard.error);\n\t\tcase \"body_too_large\":\n\t\t\treturn notice(413, guard.error);\n\t\tcase \"form_invalid\":\n\t\t\treturn notice(400, guard.error);\n\t\tcase \"origin_rejected\":\n\t\tcase \"cookie_missing\":\n\t\tcase \"cookie_invalid\":\n\t\tcase \"csrf_invalid\":\n\t\t\treturn notice(403, guard.error);\n\t\tdefault:\n\t\t\treturn notice(503, \"internal_error\");\n\t}\n}\nasync function failAttempt(\n\tcontext: Context,\n\tattemptId: string,\n\tbrowserTransactionHash: string,\n\treason: \"cancelled\" | \"provider_failure\",\n): Promise<CoordinatorBrowserLinkResponse> {\n\t// Build the response before persistence; rendering failure leaves a retry possible.\n\tconst page = await renderAuthBrowserNotice(\n\t\treason === \"cancelled\" ? \"link_cancelled\" : \"auth_unavailable\",\n\t);\n\tconst response = pageResponse(page, reason === \"cancelled\" ? 200 : 403);\n\tconst written = await context.store.failAuthLinkAttempt(\n\t\t{\n\t\t\tattemptId,\n\t\t\trequester: { kind: \"browser\", browserTransactionHash },\n\t\t\treason,\n\t\t},\n\t\tcontext.config,\n\t);\n\tif (\n\t\t(written.kind !== \"applied\" && written.kind !== \"existing\") ||\n\t\twritten.status.state !== \"failed\"\n\t)\n\t\treturn notice(403, \"link_rejected\");\n\tconst retired = await context.store.retireAuthBrowserTransactions(context.config, { attemptId });\n\tif (retired.kind !== \"retired\" || retired.more) return notice(503, \"internal_error\");\n\tif (reason === \"cancelled\") return result(response, \"link_cancelled\");\n\treturn result(response, \"link_rejected\");\n}\nasync function completeLink(\n\tcontext: Context,\n\tinput: CoordinatorBrowserAuthLinkCompletionInput,\n): Promise<Response> {\n\ttry {\n\t\tconst value = callbackCookieValue(input);\n\t\tif (value === null) return (await notice(403, \"link_rejected\")).response;\n\t\tconst cookie = await readBrowserCookie(\n\t\t\t`${BROWSER_COOKIE_NAMES.transaction}=${value}`,\n\t\t\t\"transaction\",\n\t\t);\n\t\tif (cookie.kind !== \"present\" || cookie.cookieHash !== input.transactionCookieHash)\n\t\t\treturn (await notice(403, \"link_rejected\")).response;\n\t\tconst transaction = await context.store.resolveAuthLinkBrowserTransaction(\n\t\t\t{\n\t\t\t\tattemptId: input.attemptId,\n\t\t\t\tbinderHash: cookie.cookieHash,\n\t\t\t},\n\t\t\tcontext.config,\n\t\t);\n\t\tif (!transaction || transaction.browserTransactionHash !== input.browserTransactionHash)\n\t\t\treturn (await notice(403, \"link_rejected\")).response;\n\t\tif (!input.verification.ok)\n\t\t\treturn (\n\t\t\t\tawait failAttempt(\n\t\t\t\t\tcontext,\n\t\t\t\t\tinput.attemptId,\n\t\t\t\t\ttransaction.browserTransactionHash,\n\t\t\t\t\t\"provider_failure\",\n\t\t\t\t)\n\t\t\t).response;\n\t\tif (input.verification.account.issuer !== context.config.issuer)\n\t\t\treturn (await notice(403, \"link_rejected\")).response;\n\t\tconst recorded = await context.store.recordAuthLinkOidcVerified(\n\t\t\t{\n\t\t\t\tattemptId: input.attemptId,\n\t\t\t\tbrowserTransactionHash: transaction.browserTransactionHash,\n\t\t\t\taccount: input.verification.account,\n\t\t\t\tprofile: input.verification.profile,\n\t\t\t},\n\t\t\tcontext.config,\n\t\t);\n\t\tif (recorded.kind !== \"applied\") return (await notice(403, \"link_rejected\")).response;\n\t\treturn await confirmationPage(\n\t\t\tcontext,\n\t\t\tinput.attemptId,\n\t\t\tcookie.secret,\n\t\t\tinput.verification.profile,\n\t\t\trecorded.target,\n\t\t);\n\t} catch {\n\t\treturn (await notice(503, \"internal_error\")).response;\n\t}\n}\nasync function confirmationPage(\n\tcontext: Context,\n\tattemptId: string,\n\tcookie: BrowserCookieSecret,\n\tprofile: unknown,\n\ttarget: { identityId: string; deviceId: string; groupId: string },\n): Promise<Response> {\n\tconst csrfToken = await issueBrowserCsrfToken(\n\t\tcontext.csrfKey,\n\t\tcookie,\n\t\t\"transaction\",\n\t\tcontext.scope,\n\t);\n\treturn pageResponse(\n\t\tawait renderAuthLinkConfirmPage({\n\t\t\tprofile,\n\t\t\tissuer: context.config.issuer,\n\t\t\tidentity: { id: target.identityId },\n\t\t\tdevice: { id: target.deviceId },\n\t\t\tgroup: { id: target.groupId },\n\t\t\tattemptId,\n\t\t\tcsrfToken,\n\t\t}),\n\t);\n}\nfunction callbackCookieValue(input: CoordinatorBrowserAuthLinkCompletionInput): string | null {\n\ttry {\n\t\treturn browserCookieValue(input.transactionCookie, \"transaction\");\n\t} catch {\n\t\treturn null;\n\t}\n}\nasync function confirmAttempt(\n\tcontext: Context,\n\tattemptId: string,\n\tbrowserTransactionHash: string,\n): Promise<CoordinatorBrowserLinkResponse> {\n\tconst destination = await context.store.readAuthLinkCompletionDestination(\n\t\t{ attemptId, browserTransactionHash },\n\t\tcontext.config,\n\t);\n\tif (!destination) return notice(403, \"link_rejected\");\n\tconst bytes = globalThis.crypto.getRandomValues(new Uint8Array(32));\n\tconst completionSecret = btoa(String.fromCharCode(...bytes))\n\t\t.replaceAll(\"+\", \"-\")\n\t\t.replaceAll(\"/\", \"_\")\n\t\t.replace(/=+$/, \"\");\n\t// The loopback protocol hashes decoded raw bytes, not the encoded string.\n\tconst digest = await globalThis.crypto.subtle.digest(\"SHA-256\", bytes);\n\tconst completionSecretHash = Array.from(new Uint8Array(digest), (byte) =>\n\t\tbyte.toString(16).padStart(2, \"0\"),\n\t).join(\"\");\n\tconst response = pageResponse(\n\t\tawait renderAuthLinkCompletionHopPage({\n\t\t\tdestination: destination.destination,\n\t\t\tattemptId,\n\t\t\tcompletionSecret,\n\t\t}),\n\t);\n\tconst written = await context.store.confirmAuthLinkAttempt(\n\t\t{ attemptId, browserTransactionHash, completionSecretHash },\n\t\tcontext.config,\n\t);\n\tif (written.kind !== \"applied\") return notice(403, \"link_rejected\");\n\t// Retain the transaction cookie for later original-browser session redemption.\n\treturn result(response, \"link_confirmed\");\n}\nasync function post(\n\tcontext: Context,\n\trequest: Request,\n\tclientKey: string,\n\taction: \"confirmLink\" | \"cancelLink\",\n): Promise<CoordinatorBrowserLinkResponse> {\n\ttry {\n\t\tconst snapshot = snapshotBrowserRequest(request);\n\t\tif (snapshot.method !== \"POST\")\n\t\t\treturn await notice(405, \"method_not_allowed\", { Allow: \"POST\" });\n\t\tif (snapshot.url !== `${context.scope.publicOrigin}${AUTH_BROWSER_FORM_ACTIONS[action]}`)\n\t\t\treturn await notice(404, \"not_found\");\n\t\t// The guard captures native headers in this same tick, before either caller awaits.\n\t\tconst pendingGuard = guardBrowserForm({\n\t\t\trequest,\n\t\t\tclientKey,\n\t\t\tscope: context.scope,\n\t\t\tcsrfKey: context.csrfKey,\n\t\t\tlimiter: context.limiter,\n\t\t\taction: \"transaction_attempt\",\n\t\t});\n\t\tconst guard = await pendingGuard;\n\t\tif (!guard.ok) return await guardFailure(guard);\n\t\tif (guard.action !== \"transaction_attempt\") return await notice(503, \"internal_error\");\n\t\tconst cookie = await readBrowserCookie(snapshot.cookie, \"transaction\");\n\t\tif (cookie.kind !== \"present\" || cookie.cookieHash !== guard.cookieHash)\n\t\t\treturn await notice(403, \"link_rejected\");\n\t\tconst transaction = await context.store.resolveAuthLinkBrowserTransaction(\n\t\t\t{\n\t\t\t\tattemptId: guard.attemptId,\n\t\t\t\tbinderHash: guard.cookieHash,\n\t\t\t},\n\t\t\tcontext.config,\n\t\t);\n\t\tif (!transaction) return await notice(403, \"link_rejected\");\n\t\tif (action === \"cancelLink\")\n\t\t\treturn await failAttempt(\n\t\t\t\tcontext,\n\t\t\t\tguard.attemptId,\n\t\t\t\ttransaction.browserTransactionHash,\n\t\t\t\t\"cancelled\",\n\t\t\t);\n\t\treturn await confirmAttempt(context, guard.attemptId, transaction.browserTransactionHash);\n\t} catch {\n\t\treturn await notice(503, \"internal_error\");\n\t}\n}\n\n/** Requires trusted store config from captureCoordinatorBrowserAuthConfig, never HTTP input.\n * The verified callback stages display claims; no session writes or finalization.\n */\nexport function createCoordinatorBrowserLinkHandlers(\n\tinput: CoordinatorBrowserLinkInput,\n): CoordinatorBrowserLinkResult {\n\tconst config = Object.freeze({\n\t\tcoordinatorId: input.config.coordinatorId,\n\t\tissuer: input.config.issuer,\n\t\trevision: input.config.revision,\n\t\tredirectUri: input.config.redirectUri,\n\t\tenabled: input.config.enabled,\n\t});\n\tif (!config.enabled) return Object.freeze({ ok: false, error: \"browser_auth_disabled\" });\n\tconst receiver = input.store;\n\tconst store: LinkStore = Object.freeze({\n\t\tresolveAuthLinkBrowserTransaction: receiver.resolveAuthLinkBrowserTransaction.bind(receiver),\n\t\tretireAuthBrowserTransactions: receiver.retireAuthBrowserTransactions.bind(receiver),\n\t\trecordAuthLinkOidcVerified: receiver.recordAuthLinkOidcVerified.bind(receiver),\n\t\treadAuthLinkCompletionDestination: receiver.readAuthLinkCompletionDestination.bind(receiver),\n\t\tconfirmAuthLinkAttempt: receiver.confirmAuthLinkAttempt.bind(receiver),\n\t\tfailAuthLinkAttempt: receiver.failAuthLinkAttempt.bind(receiver),\n\t});\n\tconst scope = Object.freeze({ publicOrigin: new URL(config.redirectUri).origin, store: config });\n\tconst context: Context = Object.freeze({\n\t\tconfig,\n\t\tscope,\n\t\tstore,\n\t\tcsrfKey: input.csrfKey,\n\t\tlimiter: input.limiter,\n\t});\n\treturn Object.freeze({\n\t\tok: true,\n\t\thandlers: Object.freeze({\n\t\t\tcompleteLink: (completion: CoordinatorBrowserAuthLinkCompletionInput) =>\n\t\t\t\tcompleteLink(context, completion),\n\t\t\tconfirm: (request: Request, clientKey: string) =>\n\t\t\t\tpost(context, request, clientKey, \"confirmLink\"),\n\t\t\tcancel: (request: Request, clientKey: string) =>\n\t\t\t\tpost(context, request, clientKey, \"cancelLink\"),\n\t\t}),\n\t});\n}\n","import type {\n\tCoordinatorAuthBrowserConfig,\n\tCoordinatorAuthBrowserTransactionStore,\n} from \"./coordinator-auth-browser-transaction-contract.js\";\nimport {\n\tAUTH_BROWSER_FORM_ACTIONS,\n\ttype CoordinatorAuthBrowserPage,\n\trenderAuthBrowserNotice,\n\trenderAuthLinkCompletionPage,\n} from \"./coordinator-auth-browser-view.js\";\nimport { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport type { CoordinatorAuthLinkStore } from \"./coordinator-auth-link-contract.js\";\nimport type { CoordinatorAuthSessionStore } from \"./coordinator-auth-session-contract.js\";\nimport { issueBrowserCookie, readBrowserCookie } from \"./coordinator-browser-credential.js\";\nimport {\n\ttype BrowserCsrfKey,\n\ttype BrowserCsrfScope,\n\tissueBrowserCsrfToken,\n} from \"./coordinator-browser-csrf.js\";\nimport { type BrowserFormGuardResult, guardBrowserForm } from \"./coordinator-browser-form-guard.js\";\nimport { snapshotBrowserRequest } from \"./coordinator-browser-request.js\";\nimport type { InMemoryRequestRateLimiter } from \"./request-rate-limit.js\";\n\ntype CompletionStore = Pick<\n\tCoordinatorAuthBrowserTransactionStore,\n\t\"resolveAuthLinkBrowserTransaction\"\n> &\n\tPick<CoordinatorAuthLinkStore, \"getAuthLinkAttemptStatus\"> &\n\tPick<\n\t\tCoordinatorAuthSessionStore,\n\t\t| \"readAuthSession\"\n\t\t| \"redeemAuthLinkSessionWithBrowserTransaction\"\n\t\t| \"preserveAuthLinkSessionCompletion\"\n\t>;\nexport interface CoordinatorBrowserLinkCompletionInput {\n\tconfig?: CoordinatorAuthBrowserConfig;\n\tcsrfKey: BrowserCsrfKey;\n\tstore: CompletionStore;\n\tlimiter: InMemoryRequestRateLimiter;\n}\nexport type CoordinatorBrowserLinkCompletionOutcome =\n\t| \"waiting\"\n\t| \"ready\"\n\t| \"session_preserved\"\n\t| \"session_issued\"\n\t| \"method_not_allowed\"\n\t| \"not_found\"\n\t| \"query_invalid\"\n\t| \"completion_rejected\"\n\t| \"origin_rejected\"\n\t| \"rate_limited\"\n\t| \"unsupported_media_type\"\n\t| \"body_too_large\"\n\t| \"form_invalid\"\n\t| \"cookie_invalid\"\n\t| \"csrf_invalid\"\n\t| \"internal_error\";\nexport type CoordinatorBrowserLinkCompletionResponse = Readonly<{\n\tresponse: Response;\n\toutcome: CoordinatorBrowserLinkCompletionOutcome;\n}>;\nexport interface CoordinatorBrowserLinkCompletionHandlers {\n\tpage(request: Request): Promise<CoordinatorBrowserLinkCompletionResponse>;\n\tcomplete(request: Request, clientKey: string): Promise<CoordinatorBrowserLinkCompletionResponse>;\n}\nexport type CoordinatorBrowserLinkCompletionResult =\n\t| Readonly<{ ok: false; error: \"browser_auth_disabled\" }>\n\t| Readonly<{ ok: true; handlers: Readonly<CoordinatorBrowserLinkCompletionHandlers> }>;\ntype Context = Readonly<{\n\tconfig: Readonly<CoordinatorAuthBrowserConfig>;\n\tpublicOrigin: string;\n\tscope: BrowserCsrfScope;\n\tcsrfKey: BrowserCsrfKey;\n\tstore: CompletionStore;\n\tlimiter: InMemoryRequestRateLimiter;\n}>;\n\nfunction result(response: Response, outcome: CoordinatorBrowserLinkCompletionOutcome) {\n\treturn Object.freeze({ response, outcome });\n}\nfunction pageResponse(\n\tpage: CoordinatorAuthBrowserPage,\n\tstatus = 200,\n\textra?: Record<string, string>,\n) {\n\tconst headers = new Headers(page.headers);\n\tif (extra)\n\t\tnew Headers(extra).forEach((value, name) => {\n\t\t\theaders.set(name, value);\n\t\t});\n\treturn new Response(page.body, { status, headers });\n}\nasync function notice(\n\tstatus: number,\n\toutcome: CoordinatorBrowserLinkCompletionOutcome,\n\textra?: Record<string, string>,\n): Promise<CoordinatorBrowserLinkCompletionResponse> {\n\ttry {\n\t\treturn result(\n\t\t\tpageResponse(await renderAuthBrowserNotice(\"auth_unavailable\"), status, extra),\n\t\t\toutcome,\n\t\t);\n\t} catch {\n\t\treturn result(\n\t\t\tnew Response(\"Linking unavailable. Try again.\", {\n\t\t\t\tstatus: 503,\n\t\t\t\theaders: {\n\t\t\t\t\t\"Content-Type\": \"text/plain;charset=utf-8\",\n\t\t\t\t\t\"Cache-Control\": \"no-store\",\n\t\t\t\t\t\"Referrer-Policy\": \"no-referrer\",\n\t\t\t\t\t\"X-Content-Type-Options\": \"nosniff\",\n\t\t\t\t},\n\t\t\t}),\n\t\t\t\"internal_error\",\n\t\t);\n\t}\n}\nfunction pageAttempt(url: URL): string | null {\n\tconst entries = [...url.searchParams];\n\tconst entry = entries[0];\n\tif (entries.length !== 1 || !entry || entry[0] !== \"attempt_id\") return null;\n\tconst attemptId = entry[1];\n\tif (!isAuthControllerId(attemptId)) return null;\n\treturn attemptId;\n}\nasync function boundStatus(context: Context, attemptId: string, binderHash: string) {\n\tconst resolved = await context.store.resolveAuthLinkBrowserTransaction(\n\t\t{ attemptId, binderHash },\n\t\tcontext.config,\n\t);\n\tif (resolved === null) return null;\n\tconst browserTransactionHash = resolved.browserTransactionHash;\n\tconst status = await context.store.getAuthLinkAttemptStatus(\n\t\tattemptId,\n\t\t{ kind: \"browser\", browserTransactionHash },\n\t\tcontext.config,\n\t);\n\tif (status === null) return null;\n\treturn { browserTransactionHash, state: status.state };\n}\nasync function page(\n\tcontext: Context,\n\trequest: Request,\n): Promise<CoordinatorBrowserLinkCompletionResponse> {\n\ttry {\n\t\tconst snapshot = snapshotBrowserRequest(request);\n\t\tif (snapshot.method !== \"GET\") return await notice(405, \"method_not_allowed\", { Allow: \"GET\" });\n\t\tif (snapshot.url.length > 8192) return await notice(400, \"query_invalid\");\n\t\tconst url = new URL(snapshot.url);\n\t\tif (\n\t\t\tsnapshot.url.includes(\"#\") ||\n\t\t\t`${url.origin}${url.pathname}` !==\n\t\t\t\t`${context.publicOrigin}${AUTH_BROWSER_FORM_ACTIONS.completeLink}` ||\n\t\t\turl.username ||\n\t\t\turl.password\n\t\t)\n\t\t\treturn await notice(404, \"not_found\");\n\t\tconst attemptId = pageAttempt(url);\n\t\tif (attemptId === null) return await notice(400, \"query_invalid\");\n\t\tconst cookie = await readBrowserCookie(snapshot.cookie, \"transaction\");\n\t\tif (cookie.kind !== \"present\") return await notice(403, \"cookie_invalid\");\n\t\tconst status = await boundStatus(context, attemptId, cookie.cookieHash);\n\t\tif (status?.state === \"confirmed\")\n\t\t\treturn result(\n\t\t\t\tpageResponse(await renderAuthLinkCompletionPage({ attemptId, state: \"waiting\" })),\n\t\t\t\t\"waiting\",\n\t\t\t);\n\t\tif (status?.state !== \"finalized\") return await notice(403, \"completion_rejected\");\n\t\tconst csrfToken = await issueBrowserCsrfToken(\n\t\t\tcontext.csrfKey,\n\t\t\tcookie.secret,\n\t\t\t\"transaction\",\n\t\t\tcontext.scope,\n\t\t);\n\t\treturn result(\n\t\t\tpageResponse(await renderAuthLinkCompletionPage({ attemptId, state: \"ready\", csrfToken })),\n\t\t\t\"ready\",\n\t\t);\n\t} catch {\n\t\treturn await notice(503, \"internal_error\");\n\t}\n}\nfunction guardFailure(guard: Extract<BrowserFormGuardResult, { ok: false }>) {\n\tswitch (guard.error) {\n\t\tcase \"origin_rejected\":\n\t\tcase \"cookie_invalid\":\n\t\tcase \"csrf_invalid\":\n\t\t\treturn notice(403, guard.error);\n\t\tcase \"cookie_missing\":\n\t\t\treturn notice(403, \"cookie_invalid\");\n\t\tcase \"client_unidentified\":\n\t\t\treturn notice(503, \"internal_error\");\n\t\tcase \"rate_limited\":\n\t\t\treturn notice(429, guard.error, { \"Retry-After\": String(guard.retryAfterS) });\n\t\tcase \"unsupported_media_type\":\n\t\t\treturn notice(415, guard.error);\n\t\tcase \"body_too_large\":\n\t\t\treturn notice(413, guard.error);\n\t\tcase \"form_invalid\":\n\t\t\treturn notice(400, guard.error);\n\t\tdefault:\n\t\t\treturn notice(503, \"internal_error\");\n\t}\n}\nfunction accountRedirect(context: Context, setCookie?: string): Response {\n\tconst headers = new Headers({\n\t\tLocation: `${context.publicOrigin}/auth/account`,\n\t\t\"Cache-Control\": \"no-store\",\n\t\t\"Referrer-Policy\": \"no-referrer\",\n\t});\n\tif (setCookie) headers.append(\"Set-Cookie\", setCookie);\n\treturn new Response(null, { status: 303, headers });\n}\nasync function finishSession(\n\tcontext: Context,\n\tcookieHeader: string | null,\n\tattemptId: string,\n\tbinderHash: string,\n\tbrowserTransactionHash: string,\n) {\n\tconst session = await readBrowserCookie(cookieHeader, \"session\");\n\tif (session.kind === \"invalid\") return notice(403, \"cookie_invalid\");\n\tif (session.kind === \"present\") {\n\t\tconst live = await context.store.readAuthSession(session.cookieHash, context.config);\n\t\tif (live !== null) {\n\t\t\tconst response = accountRedirect(context);\n\t\t\tconst preserved = await context.store.preserveAuthLinkSessionCompletion(\n\t\t\t\t{ attemptId, browserTransactionHash, binderHash, credentialHash: session.cookieHash },\n\t\t\t\tcontext.config,\n\t\t\t);\n\t\t\tif (preserved.kind !== \"preserved\") return notice(403, \"completion_rejected\");\n\t\t\treturn result(response, \"session_preserved\");\n\t\t}\n\t}\n\tconst issued = await issueBrowserCookie(\"session\");\n\t// Construct all bearer-bearing output before the atomic write; release only its issued result.\n\tconst response = accountRedirect(context, issued.setCookie);\n\tconst redeemed = await context.store.redeemAuthLinkSessionWithBrowserTransaction(\n\t\t{ attemptId, browserTransactionHash, binderHash, credentialHash: issued.cookieHash },\n\t\tcontext.config,\n\t);\n\tif (redeemed.kind !== \"issued\") return notice(403, \"completion_rejected\");\n\treturn result(response, \"session_issued\");\n}\nasync function complete(\n\tcontext: Context,\n\trequest: Request,\n\tclientKey: string,\n): Promise<CoordinatorBrowserLinkCompletionResponse> {\n\ttry {\n\t\tconst snapshot = snapshotBrowserRequest(request);\n\t\tif (snapshot.method !== \"POST\")\n\t\t\treturn await notice(405, \"method_not_allowed\", { Allow: \"POST\" });\n\t\tif (snapshot.url !== `${context.publicOrigin}${AUTH_BROWSER_FORM_ACTIONS.completeLink}`)\n\t\t\treturn await notice(404, \"not_found\");\n\t\t// Invoke synchronously so the shared guard captures the same native headers before any await.\n\t\tconst pendingGuard = guardBrowserForm({\n\t\t\trequest,\n\t\t\tscope: context.scope,\n\t\t\tcsrfKey: context.csrfKey,\n\t\t\taction: \"transaction_attempt\",\n\t\t\tlimiter: context.limiter,\n\t\t\tclientKey,\n\t\t});\n\t\tconst guard = await pendingGuard;\n\t\tif (!guard.ok) return await guardFailure(guard);\n\t\tif (guard.action !== \"transaction_attempt\") return await notice(503, \"internal_error\");\n\t\tconst cookie = await readBrowserCookie(snapshot.cookie, \"transaction\");\n\t\tif (cookie.kind !== \"present\" || cookie.cookieHash !== guard.cookieHash)\n\t\t\treturn await notice(403, \"cookie_invalid\");\n\t\tconst status = await boundStatus(context, guard.attemptId, guard.cookieHash);\n\t\t// Even preserving an existing session requires independent device-finalized proof.\n\t\tif (status?.state !== \"finalized\") return await notice(403, \"completion_rejected\");\n\t\treturn await finishSession(\n\t\t\tcontext,\n\t\t\tsnapshot.cookie,\n\t\t\tguard.attemptId,\n\t\t\tguard.cookieHash,\n\t\t\tstatus.browserTransactionHash,\n\t\t);\n\t} catch {\n\t\treturn await notice(503, \"internal_error\");\n\t}\n}\n\n/** Trusted captured config/key/store only. Unmounted; wiring faults may throw to the composition root. */\nexport function createCoordinatorBrowserLinkCompletionHandlers(\n\tinput: CoordinatorBrowserLinkCompletionInput,\n): CoordinatorBrowserLinkCompletionResult {\n\tif (!input.config?.enabled) return Object.freeze({ ok: false, error: \"browser_auth_disabled\" });\n\tconst config = Object.freeze({\n\t\tenabled: input.config.enabled,\n\t\tcoordinatorId: input.config.coordinatorId,\n\t\tissuer: input.config.issuer,\n\t\trevision: input.config.revision,\n\t\tredirectUri: input.config.redirectUri,\n\t});\n\tconst receiver = input.store;\n\tconst store: CompletionStore = Object.freeze({\n\t\tresolveAuthLinkBrowserTransaction: receiver.resolveAuthLinkBrowserTransaction.bind(receiver),\n\t\tgetAuthLinkAttemptStatus: receiver.getAuthLinkAttemptStatus.bind(receiver),\n\t\treadAuthSession: receiver.readAuthSession.bind(receiver),\n\t\tpreserveAuthLinkSessionCompletion: receiver.preserveAuthLinkSessionCompletion.bind(receiver),\n\t\tredeemAuthLinkSessionWithBrowserTransaction:\n\t\t\treceiver.redeemAuthLinkSessionWithBrowserTransaction.bind(receiver),\n\t});\n\tconst publicOrigin = new URL(config.redirectUri).origin;\n\tconst context: Context = Object.freeze({\n\t\tconfig,\n\t\tpublicOrigin,\n\t\tscope: Object.freeze({ publicOrigin, store: config }),\n\t\tcsrfKey: input.csrfKey,\n\t\tstore,\n\t\tlimiter: input.limiter,\n\t});\n\treturn Object.freeze({\n\t\tok: true,\n\t\thandlers: Object.freeze({\n\t\t\tpage: (request: Request) => page(context, request),\n\t\t\tcomplete: (request: Request, clientKey: string) => complete(context, request, clientKey),\n\t\t}),\n\t});\n}\n","import type { CoordinatorAuthBrowserTransactionStore } from \"./coordinator-auth-browser-transaction-contract.js\";\nimport {\n\ttype CoordinatorAuthBrowserPage,\n\trenderAuthBrowserNotice,\n\trenderAuthLinkStartPage,\n\trenderAuthSigninContinuePage,\n} from \"./coordinator-auth-browser-view.js\";\nimport { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport {\n\tdecodeCoordinatorAuthProof32,\n\thashCoordinatorAuthProofBytes32,\n} from \"./coordinator-auth-proof.js\";\nimport {\n\ttype CoordinatorBrowserAuthConfigField,\n\ttype CoordinatorBrowserAuthSettings,\n\tcaptureCoordinatorBrowserAuthConfig,\n} from \"./coordinator-browser-auth-config.js\";\nimport {\n\tclearBrowserCookie,\n\tissueBrowserCookie,\n\treadBrowserCookie,\n\treissueStartCookieAsTransaction,\n} from \"./coordinator-browser-credential.js\";\nimport {\n\ttype BrowserCsrfKey,\n\ttype BrowserCsrfScope,\n\tissueBrowserCsrfToken,\n} from \"./coordinator-browser-csrf.js\";\nimport { type BrowserFormGuardResult, guardBrowserForm } from \"./coordinator-browser-form-guard.js\";\nimport { snapshotBrowserRequest, snapshotBrowserRoute } from \"./coordinator-browser-request.js\";\nimport { readBrowserStartTransaction } from \"./coordinator-browser-start-transaction.js\";\nimport {\n\ttype CoordinatorOidcClient,\n\ttype CoordinatorOidcOptions,\n\tcreateCoordinatorOidcClient,\n} from \"./coordinator-oidc.js\";\nimport type { InMemoryRequestRateLimiter } from \"./request-rate-limit.js\";\n\ntype LinkStartStore = Pick<\n\tCoordinatorAuthBrowserTransactionStore,\n\t\"startAuthBrowserTransaction\" | \"readAuthBrowserTransactionActivity\"\n>;\ntype Settings = Extract<CoordinatorBrowserAuthSettings, { kind: \"enabled\" }>;\nexport interface CoordinatorBrowserLinkStartInput {\n\tconfig: unknown;\n\tcsrfKey: BrowserCsrfKey;\n\tstore: LinkStartStore;\n\tlimiter: InMemoryRequestRateLimiter;\n\toidcOptions?: CoordinatorOidcOptions;\n}\nexport type CoordinatorBrowserLinkStartOutcome =\n\t| \"link_start_page\"\n\t| \"link_started\"\n\t| \"link_in_progress\"\n\t| \"method_not_allowed\"\n\t| \"not_found\"\n\t| \"form_invalid\"\n\t| \"cookie_invalid\"\n\t| \"origin_rejected\"\n\t| \"rate_limited\"\n\t| \"unsupported_media_type\"\n\t| \"body_too_large\"\n\t| \"cookie_missing\"\n\t| \"csrf_invalid\"\n\t| \"attempt_unavailable\"\n\t| \"start_conflict\"\n\t| \"start_limited\"\n\t| \"provider_request_failed\"\n\t| \"internal_error\";\nexport type CoordinatorBrowserLinkStartResponse = Readonly<{\n\tresponse: Response;\n\toutcome: CoordinatorBrowserLinkStartOutcome;\n}>;\nexport interface CoordinatorBrowserLinkStartHandlers {\n\tlinkStartPage(request: Request): Promise<CoordinatorBrowserLinkStartResponse>;\n\tlinkStart(request: Request, clientKey: string): Promise<CoordinatorBrowserLinkStartResponse>;\n}\nexport type CoordinatorBrowserLinkStartResult =\n\t| Readonly<{ ok: true; handlers: Readonly<CoordinatorBrowserLinkStartHandlers> }>\n\t| Readonly<{\n\t\t\tok: false;\n\t\t\terror: \"browser_auth_config_invalid\";\n\t\t\tfield: CoordinatorBrowserAuthConfigField;\n\t }>\n\t| Readonly<{\n\t\t\tok: false;\n\t\t\terror:\n\t\t\t\t| \"browser_auth_disabled\"\n\t\t\t\t| \"invalid_input\"\n\t\t\t\t| \"oidc_discovery_failed\"\n\t\t\t\t| \"invalid_provider_configuration\";\n\t }>;\ntype Context = Readonly<{\n\tstoreConfig: Settings[\"store\"];\n\tscope: BrowserCsrfScope;\n\tcsrfKey: BrowserCsrfKey;\n\tstore: LinkStartStore;\n\tlimiter: InMemoryRequestRateLimiter;\n\tclient: CoordinatorOidcClient;\n\tstartUrl: string;\n}>;\ntype Snapshot = ReturnType<typeof snapshotBrowserRequest>;\ntype LinkGuard = Extract<BrowserFormGuardResult, { ok: true; action: \"link_start\" }>;\nconst requestHeaders = Object.getOwnPropertyDescriptor(Request.prototype, \"headers\")?.get;\nconst headersGet = Headers.prototype.get;\nconst MAX_START_URL_LENGTH = 8192;\n\nfunction ownData(value: unknown, name: string): unknown {\n\tif (value === null || typeof value !== \"object\" || Array.isArray(value)) throw new Error();\n\tconst descriptor = Object.getOwnPropertyDescriptor(value, name);\n\tif (descriptor && !Object.hasOwn(descriptor, \"value\")) throw new Error();\n\treturn descriptor?.value;\n}\nfunction dataMethod(value: unknown, name: string): unknown {\n\tif (value === null || typeof value !== \"object\" || Array.isArray(value)) throw new Error();\n\tconst seen = new Set<object>();\n\tlet cursor: object | null = value;\n\twhile (cursor !== null) {\n\t\tif (seen.has(cursor)) throw new Error();\n\t\tseen.add(cursor);\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(cursor, name);\n\t\tif (descriptor) {\n\t\t\tif (!Object.hasOwn(descriptor, \"value\") || typeof descriptor.value !== \"function\")\n\t\t\t\tthrow new Error();\n\t\t\treturn descriptor.value;\n\t\t}\n\t\tcursor = Object.getPrototypeOf(cursor);\n\t}\n\tthrow new Error();\n}\nfunction result(\n\tresponse: Response,\n\toutcome: CoordinatorBrowserLinkStartOutcome,\n): CoordinatorBrowserLinkStartResponse {\n\treturn Object.freeze({ response, outcome });\n}\nfunction pageResponse(\n\tpage: CoordinatorAuthBrowserPage,\n\tstatus = 200,\n\textra?: Record<string, string>,\n): Response {\n\tconst headers = new Headers(page.headers);\n\tif (extra)\n\t\tnew Headers(extra).forEach((value, name) => {\n\t\t\theaders.set(name, value);\n\t\t});\n\treturn new Response(page.body, { status, headers });\n}\nasync function notice(\n\tstatus: number,\n\toutcome: CoordinatorBrowserLinkStartOutcome,\n\textra?: Record<string, string>,\n): Promise<CoordinatorBrowserLinkStartResponse> {\n\ttry {\n\t\treturn result(\n\t\t\tpageResponse(await renderAuthBrowserNotice(\"unavailable\"), status, extra),\n\t\t\toutcome,\n\t\t);\n\t} catch {\n\t\treturn result(\n\t\t\tnew Response(\"Account linking unavailable. Return to your terminal and try again.\", {\n\t\t\t\tstatus: 503,\n\t\t\t\theaders: {\n\t\t\t\t\t\"Content-Type\": \"text/plain;charset=utf-8\",\n\t\t\t\t\t\"Cache-Control\": \"no-store\",\n\t\t\t\t\t\"Referrer-Policy\": \"no-referrer\",\n\t\t\t\t\t\"X-Content-Type-Options\": \"nosniff\",\n\t\t\t\t},\n\t\t\t}),\n\t\t\t\"internal_error\",\n\t\t);\n\t}\n}\nfunction parseStartQuery(context: Context, text: string) {\n\tconst url = new URL(text);\n\tif (\n\t\ttext.includes(\"#\") ||\n\t\turl.href !== text ||\n\t\t`${url.origin}${url.pathname}` !== context.startUrl ||\n\t\turl.username ||\n\t\turl.password\n\t)\n\t\treturn null;\n\tconst entries = [...url.searchParams];\n\tif (\n\t\tentries.length !== 2 ||\n\t\turl.searchParams.getAll(\"attempt_id\").length !== 1 ||\n\t\turl.searchParams.getAll(\"start_code\").length !== 1\n\t)\n\t\treturn null;\n\tconst attemptId = url.searchParams.get(\"attempt_id\");\n\tconst startCode = url.searchParams.get(\"start_code\");\n\tif (\n\t\t!isAuthControllerId(attemptId) ||\n\t\ttypeof startCode !== \"string\" ||\n\t\t!decodeCoordinatorAuthProof32(startCode)\n\t)\n\t\treturn null;\n\treturn Object.freeze({ attemptId, startCode });\n}\nasync function linkStartPage(\n\tcontext: Context,\n\trequest: Request,\n): Promise<CoordinatorBrowserLinkStartResponse> {\n\ttry {\n\t\tconst route = snapshotBrowserRoute(request);\n\t\tif (route.method !== \"GET\") return await notice(405, \"method_not_allowed\", { Allow: \"GET\" });\n\t\tif (route.url.length > MAX_START_URL_LENGTH) return await notice(400, \"form_invalid\");\n\t\tconst url = new URL(route.url);\n\t\tif (`${url.origin}${url.pathname}` !== context.startUrl || url.username || url.password)\n\t\t\treturn await notice(404, \"not_found\");\n\t\tconst query = parseStartQuery(context, route.url);\n\t\tif (!query) return await notice(400, \"form_invalid\");\n\t\tconst snapshot = snapshotBrowserRequest(request);\n\t\tconst transaction = await readBrowserStartTransaction(\n\t\t\tsnapshot.cookie,\n\t\t\tcontext.store,\n\t\t\tcontext.storeConfig,\n\t\t);\n\t\tif (transaction === \"invalid\") return await notice(400, \"cookie_invalid\");\n\t\tif (transaction === \"active\") return await notice(409, \"link_in_progress\");\n\t\tconst existing = await readBrowserCookie(snapshot.cookie, \"start\");\n\t\tif (existing.kind === \"invalid\") return await notice(400, \"cookie_invalid\");\n\t\tconst cookie = existing.kind === \"present\" ? existing : await issueBrowserCookie(\"start\");\n\t\tconst csrfToken = await issueBrowserCsrfToken(\n\t\t\tcontext.csrfKey,\n\t\t\tcookie.secret,\n\t\t\t\"start\",\n\t\t\tcontext.scope,\n\t\t);\n\t\tconst response = pageResponse(await renderAuthLinkStartPage({ ...query, csrfToken }));\n\t\tif (\"setCookie\" in cookie) response.headers.append(\"Set-Cookie\", cookie.setCookie);\n\t\treturn result(response, \"link_start_page\");\n\t} catch {\n\t\treturn await notice(503, \"internal_error\");\n\t}\n}\nfunction guardPriority(guard: BrowserFormGuardResult) {\n\tif (guard.ok) return null;\n\tif (guard.error === \"origin_rejected\") return notice(403, \"origin_rejected\");\n\tif (guard.error === \"rate_limited\")\n\t\treturn notice(429, \"rate_limited\", { \"Retry-After\": String(guard.retryAfterS) });\n\tif (guard.error === \"client_unidentified\" || guard.error === \"invalid_input\")\n\t\treturn notice(503, \"internal_error\");\n\treturn null;\n}\nfunction guardFailure(guard: Extract<BrowserFormGuardResult, { ok: false }>) {\n\tswitch (guard.error) {\n\t\tcase \"unsupported_media_type\":\n\t\t\treturn notice(415, guard.error);\n\t\tcase \"body_too_large\":\n\t\t\treturn notice(413, guard.error);\n\t\tcase \"form_invalid\":\n\t\t\treturn notice(400, guard.error);\n\t\tcase \"cookie_invalid\":\n\t\tcase \"cookie_missing\":\n\t\tcase \"csrf_invalid\":\n\t\t\treturn notice(403, guard.error);\n\t\tdefault:\n\t\t\treturn notice(503, \"internal_error\");\n\t}\n}\nasync function admitStart(\n\tcontext: Context,\n\tsnapshot: Snapshot,\n\tguard: LinkGuard,\n): Promise<CoordinatorBrowserLinkStartResponse> {\n\tconst start = await readBrowserCookie(snapshot.cookie, \"start\");\n\tif (start.kind !== \"present\" || start.cookieHash !== guard.cookieHash)\n\t\treturn notice(503, \"internal_error\");\n\tconst bytes = decodeCoordinatorAuthProof32(guard.startCode);\n\tif (!bytes) return notice(400, \"form_invalid\");\n\tconst browserStartHash = await hashCoordinatorAuthProofBytes32(bytes);\n\tlet authorization: Awaited<ReturnType<CoordinatorOidcClient[\"createAuthorizationRequest\"]>>;\n\ttry {\n\t\tauthorization = await context.client.createAuthorizationRequest();\n\t} catch {\n\t\treturn notice(503, \"provider_request_failed\");\n\t}\n\tconst digest = await globalThis.crypto.subtle.digest(\n\t\t\"SHA-256\",\n\t\tnew TextEncoder().encode(authorization.material.state),\n\t);\n\tconst stateHash = Array.from(new Uint8Array(digest), (byte) =>\n\t\tbyte.toString(16).padStart(2, \"0\"),\n\t).join(\"\");\n\tconst response = pageResponse(\n\t\tawait renderAuthSigninContinuePage({ authorizationUrl: authorization.authorizationUrl }),\n\t);\n\tresponse.headers.append(\"Set-Cookie\", reissueStartCookieAsTransaction(start.secret));\n\tresponse.headers.append(\"Set-Cookie\", clearBrowserCookie(\"start\"));\n\t// Release promotion only after both private-proof and unique-binder SQL guards commit.\n\tconst admitted = await context.store.startAuthBrowserTransaction(\n\t\t{\n\t\t\tpurpose: \"link\",\n\t\t\tattemptId: guard.attemptId,\n\t\t\tbrowserStartHash,\n\t\t\tstateHash,\n\t\t\tbinderHash: guard.cookieHash,\n\t\t\tnonce: authorization.material.nonce,\n\t\t\tpkceVerifier: authorization.material.pkceVerifier,\n\t\t},\n\t\tcontext.storeConfig,\n\t);\n\tif (admitted.kind === \"started\") return result(response, \"link_started\");\n\tif (admitted.kind === \"rejected\") {\n\t\tif (admitted.error === \"attempt_unavailable\" || admitted.error === \"attempt_expired\")\n\t\t\treturn notice(409, \"attempt_unavailable\");\n\t\tif (admitted.error === \"transaction_conflict\") return notice(409, \"start_conflict\");\n\t\tif (admitted.error === \"transaction_limited\" || admitted.error === \"clock_retention_blocked\")\n\t\t\treturn notice(503, \"start_limited\");\n\t}\n\treturn notice(503, \"internal_error\");\n}\nasync function linkStart(\n\tcontext: Context,\n\trequest: Request,\n\tclientKey: string,\n): Promise<CoordinatorBrowserLinkStartResponse> {\n\ttry {\n\t\tconst route = snapshotBrowserRoute(request);\n\t\tif (route.method !== \"POST\") return await notice(405, \"method_not_allowed\", { Allow: \"POST\" });\n\t\tif (route.url.length > MAX_START_URL_LENGTH) return await notice(400, \"form_invalid\");\n\t\tconst headers = requestHeaders?.call(request) as Headers;\n\t\tif (\n\t\t\tnew URL(route.url).origin !== context.scope.publicOrigin ||\n\t\t\theadersGet.call(headers, \"origin\") !== context.scope.publicOrigin\n\t\t)\n\t\t\treturn await notice(403, \"origin_rejected\");\n\t\tif (route.url !== context.startUrl) return await notice(404, \"not_found\");\n\t\tconst snapshot = snapshotBrowserRequest(request);\n\t\t// Capture the guard's native fields in the same synchronous tick.\n\t\tconst pendingGuard = guardBrowserForm({\n\t\t\trequest,\n\t\t\tscope: context.scope,\n\t\t\tcsrfKey: context.csrfKey,\n\t\t\taction: \"link_start\",\n\t\t\tlimiter: context.limiter,\n\t\t\tclientKey,\n\t\t});\n\t\tconst guard = await pendingGuard;\n\t\tconst priority = guardPriority(guard);\n\t\tif (priority) return await priority;\n\t\tconst transaction = await readBrowserStartTransaction(\n\t\t\tsnapshot.cookie,\n\t\t\tcontext.store,\n\t\t\tcontext.storeConfig,\n\t\t);\n\t\tif (transaction === \"invalid\") return await notice(400, \"cookie_invalid\");\n\t\tif (transaction === \"active\") return await notice(409, \"link_in_progress\");\n\t\tif (!guard.ok) return await guardFailure(guard);\n\t\tif (guard.action !== \"link_start\") return await notice(503, \"internal_error\");\n\t\treturn await admitStart(context, snapshot, guard);\n\t} catch {\n\t\treturn await notice(503, \"internal_error\");\n\t}\n}\nfunction captureOidcOptions(input: unknown): CoordinatorOidcOptions | undefined {\n\tconst supplied = ownData(input, \"oidcOptions\");\n\tif (supplied === undefined) return undefined;\n\treturn Object.freeze({\n\t\tfetch: ownData(supplied, \"fetch\") as CoordinatorOidcOptions[\"fetch\"],\n\t\ttimeoutSeconds: ownData(supplied, \"timeoutSeconds\") as CoordinatorOidcOptions[\"timeoutSeconds\"],\n\t});\n}\n/** Unmounted private-code entry only; sessions, completion and cleanup are independent.\n * A future gateway must redact the handoff query, Referer and form body from logs.\n */\nexport async function createCoordinatorBrowserLinkStart(\n\tinput: CoordinatorBrowserLinkStartInput,\n): Promise<CoordinatorBrowserLinkStartResult> {\n\ttry {\n\t\tconst settings = captureCoordinatorBrowserAuthConfig(ownData(input, \"config\"));\n\t\tif (settings.kind === \"disabled\")\n\t\t\treturn Object.freeze({ ok: false, error: \"browser_auth_disabled\" });\n\t\tif (settings.kind === \"invalid\")\n\t\t\treturn Object.freeze({\n\t\t\t\tok: false,\n\t\t\t\terror: \"browser_auth_config_invalid\",\n\t\t\t\tfield: settings.field,\n\t\t\t});\n\t\tconst csrfKey = ownData(input, \"csrfKey\") as BrowserCsrfKey;\n\t\tconst receiver = ownData(input, \"store\");\n\t\tconst start = dataMethod(\n\t\t\treceiver,\n\t\t\t\"startAuthBrowserTransaction\",\n\t\t) as LinkStartStore[\"startAuthBrowserTransaction\"];\n\t\tconst activity = dataMethod(\n\t\t\treceiver,\n\t\t\t\"readAuthBrowserTransactionActivity\",\n\t\t) as LinkStartStore[\"readAuthBrowserTransactionActivity\"];\n\t\tconst store = Object.freeze({\n\t\t\tstartAuthBrowserTransaction: start.bind(receiver),\n\t\t\treadAuthBrowserTransactionActivity: activity.bind(receiver),\n\t\t});\n\t\tconst limiter = ownData(input, \"limiter\") as InMemoryRequestRateLimiter;\n\t\tdataMethod(limiter, \"check\");\n\t\tconst oidcOptions = captureOidcOptions(input);\n\t\tconst scope = Object.freeze({ publicOrigin: settings.publicOrigin, store: settings.store });\n\t\tconst startUrl = new URL(\"/auth/link/start\", settings.publicOrigin).href;\n\t\tconst oidc = await createCoordinatorOidcClient(settings.oidc, oidcOptions);\n\t\tif (!oidc.ok) return Object.freeze({ ok: false, error: oidc.error });\n\t\tconst context: Context = Object.freeze({\n\t\t\tstoreConfig: settings.store,\n\t\t\tscope,\n\t\t\tcsrfKey,\n\t\t\tstore,\n\t\t\tlimiter,\n\t\t\tclient: oidc.client,\n\t\t\tstartUrl,\n\t\t});\n\t\treturn Object.freeze({\n\t\t\tok: true,\n\t\t\thandlers: Object.freeze({\n\t\t\t\tlinkStartPage: (request: Request) => linkStartPage(context, request),\n\t\t\t\tlinkStart: (request: Request, clientKey: string) => linkStart(context, request, clientKey),\n\t\t\t}),\n\t\t});\n\t} catch {\n\t\treturn Object.freeze({ ok: false, error: \"invalid_input\" });\n\t}\n}\n","import type { CoordinatorAuthBrowserTransactionStore } from \"./coordinator-auth-browser-transaction-contract.js\";\nimport {\n\ttype CoordinatorAuthBrowserPage,\n\trenderAuthBrowserNotice,\n\trenderAuthSigninContinuePage,\n\trenderAuthSigninPage,\n} from \"./coordinator-auth-browser-view.js\";\nimport type { CoordinatorAuthSessionStore } from \"./coordinator-auth-session-contract.js\";\nimport {\n\ttype CoordinatorBrowserAuthConfigField,\n\ttype CoordinatorBrowserAuthSettings,\n\tcaptureCoordinatorBrowserAuthConfig,\n} from \"./coordinator-browser-auth-config.js\";\nimport {\n\tclearBrowserCookie,\n\tissueBrowserCookie,\n\treadBrowserCookie,\n\treissueStartCookieAsTransaction,\n} from \"./coordinator-browser-credential.js\";\nimport {\n\ttype BrowserCsrfKey,\n\ttype BrowserCsrfScope,\n\tissueBrowserCsrfToken,\n} from \"./coordinator-browser-csrf.js\";\nimport { type BrowserFormGuardResult, guardBrowserForm } from \"./coordinator-browser-form-guard.js\";\nimport { readBrowserStartTransaction } from \"./coordinator-browser-start-transaction.js\";\nimport {\n\ttype CoordinatorOidcClient,\n\ttype CoordinatorOidcOptions,\n\tcreateCoordinatorOidcClient,\n} from \"./coordinator-oidc.js\";\nimport type { InMemoryRequestRateLimiter } from \"./request-rate-limit.js\";\n\ntype SigninStore = Pick<\n\tCoordinatorAuthBrowserTransactionStore,\n\t\"startAuthBrowserTransaction\" | \"readAuthBrowserTransactionActivity\"\n> &\n\tPick<CoordinatorAuthSessionStore, \"readAuthSession\">;\ntype Settings = Extract<CoordinatorBrowserAuthSettings, { kind: \"enabled\" }>;\nexport interface CoordinatorBrowserSigninStartInput {\n\tconfig: unknown;\n\tcsrfKey: BrowserCsrfKey;\n\tstore: SigninStore;\n\tlimiter: InMemoryRequestRateLimiter;\n\toidcOptions?: CoordinatorOidcOptions;\n}\nexport type CoordinatorBrowserSigninStartOutcome =\n\t| \"signin_page\"\n\t| \"signin_started\"\n\t| \"session_live\"\n\t| \"signin_in_progress\"\n\t| \"method_not_allowed\"\n\t| \"not_found\"\n\t| \"cookie_invalid\"\n\t| \"origin_rejected\"\n\t| \"rate_limited\"\n\t| \"unsupported_media_type\"\n\t| \"body_too_large\"\n\t| \"form_invalid\"\n\t| \"cookie_missing\"\n\t| \"csrf_invalid\"\n\t| \"start_conflict\"\n\t| \"start_limited\"\n\t| \"provider_request_failed\"\n\t| \"internal_error\";\nexport type CoordinatorBrowserSigninStartResponse = Readonly<{\n\tresponse: Response;\n\toutcome: CoordinatorBrowserSigninStartOutcome;\n}>;\nexport interface CoordinatorBrowserSigninStartHandlers {\n\tsignInPage(request: Request): Promise<CoordinatorBrowserSigninStartResponse>;\n\tsignInStart(request: Request, clientKey: string): Promise<CoordinatorBrowserSigninStartResponse>;\n}\nexport type CoordinatorBrowserSigninStartResult =\n\t| Readonly<{ ok: true; handlers: Readonly<CoordinatorBrowserSigninStartHandlers> }>\n\t| Readonly<{\n\t\t\tok: false;\n\t\t\terror: \"browser_auth_config_invalid\";\n\t\t\tfield: CoordinatorBrowserAuthConfigField;\n\t }>\n\t| Readonly<{\n\t\t\tok: false;\n\t\t\terror:\n\t\t\t\t| \"browser_auth_disabled\"\n\t\t\t\t| \"invalid_input\"\n\t\t\t\t| \"oidc_discovery_failed\"\n\t\t\t\t| \"invalid_provider_configuration\";\n\t }>;\n\nfunction ownData(value: unknown, name: string): unknown {\n\tif (value === null || typeof value !== \"object\" || Array.isArray(value)) throw new Error();\n\tconst descriptor = Object.getOwnPropertyDescriptor(value, name);\n\tif (descriptor && !Object.hasOwn(descriptor, \"value\")) throw new Error();\n\treturn descriptor?.value;\n}\n\nfunction dataMethod(value: unknown, name: string): unknown {\n\tif (value === null || typeof value !== \"object\" || Array.isArray(value)) throw new Error();\n\tconst seen = new Set<object>();\n\tlet cursor: object | null = value;\n\twhile (cursor !== null) {\n\t\tif (seen.has(cursor)) throw new Error();\n\t\tseen.add(cursor);\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(cursor, name);\n\t\tif (descriptor) {\n\t\t\tif (!Object.hasOwn(descriptor, \"value\") || typeof descriptor.value !== \"function\")\n\t\t\t\tthrow new Error();\n\t\t\treturn descriptor.value;\n\t\t}\n\t\tcursor = Object.getPrototypeOf(cursor);\n\t}\n\tthrow new Error();\n}\n\nfunction nativeRequestGetter(name: string): ((this: Request) => unknown) | undefined {\n\tlet prototype: object | null = Request.prototype;\n\twhile (prototype !== null) {\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(prototype, name);\n\t\tif (descriptor) return descriptor.get;\n\t\tprototype = Object.getPrototypeOf(prototype);\n\t}\n\treturn undefined;\n}\nconst requestGetters = Object.freeze({\n\tmethod: nativeRequestGetter(\"method\"),\n\turl: nativeRequestGetter(\"url\"),\n\theaders: nativeRequestGetter(\"headers\"),\n});\nconst headersGet = Headers.prototype.get;\nfunction snapshotRequest(request: Request) {\n\tconst method = requestGetters.method?.call(request);\n\tconst url = requestGetters.url?.call(request);\n\tconst headers = requestGetters.headers?.call(request) as Headers;\n\tif (typeof method !== \"string\" || typeof url !== \"string\") throw new Error();\n\treturn Object.freeze({ method, url, cookie: headersGet.call(headers, \"cookie\") });\n}\ntype Snapshot = ReturnType<typeof snapshotRequest>;\ntype Context = Readonly<{\n\tstoreConfig: Settings[\"store\"];\n\tscope: BrowserCsrfScope;\n\tcsrfKey: BrowserCsrfKey;\n\tstore: SigninStore;\n\tlimiter: InMemoryRequestRateLimiter;\n\tclient: CoordinatorOidcClient;\n\tsigninUrl: string;\n\taccountUrl: string;\n}>;\n\nfunction result(\n\tresponse: Response,\n\toutcome: CoordinatorBrowserSigninStartOutcome,\n): CoordinatorBrowserSigninStartResponse {\n\treturn Object.freeze({ response, outcome });\n}\nfunction pageResponse(\n\tpage: CoordinatorAuthBrowserPage,\n\tstatus = 200,\n\textra?: Record<string, string>,\n): Response {\n\tconst headers = new Headers(page.headers);\n\theaders.set(\"Cache-Control\", \"no-store\");\n\tif (extra) {\n\t\tnew Headers(extra).forEach((value, name) => {\n\t\t\theaders.set(name, value);\n\t\t});\n\t}\n\treturn new Response(page.body, { status, headers });\n}\nfunction fallback(): CoordinatorBrowserSigninStartResponse {\n\treturn result(\n\t\tnew Response(\"Sign-in unavailable. Try again.\", {\n\t\t\tstatus: 503,\n\t\t\theaders: {\n\t\t\t\t\"Content-Type\": \"text/plain;charset=utf-8\",\n\t\t\t\t\"Cache-Control\": \"no-store\",\n\t\t\t\t\"Referrer-Policy\": \"no-referrer\",\n\t\t\t\t\"X-Content-Type-Options\": \"nosniff\",\n\t\t\t},\n\t\t}),\n\t\t\"internal_error\",\n\t);\n}\nasync function notice(\n\tstatus: number,\n\toutcome: CoordinatorBrowserSigninStartOutcome,\n\textra?: Record<string, string>,\n): Promise<CoordinatorBrowserSigninStartResponse> {\n\ttry {\n\t\tconst inProgress = outcome === \"signin_in_progress\" || outcome === \"start_conflict\";\n\t\tconst kind = inProgress ? \"signin_in_progress\" : \"signin_unavailable\";\n\t\treturn result(pageResponse(await renderAuthBrowserNotice(kind), status, extra), outcome);\n\t} catch {\n\t\treturn fallback();\n\t}\n}\nfunction accountRedirect(context: Context): CoordinatorBrowserSigninStartResponse {\n\treturn result(\n\t\tnew Response(null, {\n\t\t\tstatus: 303,\n\t\t\theaders: {\n\t\t\t\tLocation: context.accountUrl,\n\t\t\t\t\"Cache-Control\": \"no-store\",\n\t\t\t\t\"Referrer-Policy\": \"no-referrer\",\n\t\t\t},\n\t\t}),\n\t\t\"session_live\",\n\t);\n}\nasync function liveSession(context: Context, snapshot: Snapshot): Promise<boolean> {\n\tconst session = await readBrowserCookie(snapshot.cookie, \"session\");\n\tif (session.kind === \"invalid\") throw new Error();\n\tif (session.kind === \"absent\") return false;\n\treturn (await context.store.readAuthSession(session.cookieHash, context.storeConfig)) !== null;\n}\nfunction routeError(context: Context, snapshot: Snapshot, method: \"GET\" | \"POST\") {\n\tif (snapshot.method !== method) return notice(405, \"method_not_allowed\", { Allow: method });\n\tif (snapshot.url !== context.signinUrl) return notice(404, \"not_found\");\n\treturn null;\n}\nasync function signInPage(\n\tcontext: Context,\n\trequest: Request,\n): Promise<CoordinatorBrowserSigninStartResponse> {\n\ttry {\n\t\tconst snapshot = snapshotRequest(request);\n\t\tconst routing = routeError(context, snapshot, \"GET\");\n\t\tif (routing) return await routing;\n\t\tconst transaction = await readBrowserStartTransaction(\n\t\t\tsnapshot.cookie,\n\t\t\tcontext.store,\n\t\t\tcontext.storeConfig,\n\t\t);\n\t\tif (transaction === \"invalid\") return await notice(400, \"cookie_invalid\");\n\t\tif (transaction === \"active\") return await notice(409, \"signin_in_progress\");\n\t\tif (await liveSession(context, snapshot)) return accountRedirect(context);\n\t\tconst existing = await readBrowserCookie(snapshot.cookie, \"start\");\n\t\tif (existing.kind === \"invalid\") return await notice(400, \"cookie_invalid\");\n\t\tconst cookie = existing.kind === \"present\" ? existing : await issueBrowserCookie(\"start\");\n\t\tconst csrfToken = await issueBrowserCsrfToken(\n\t\t\tcontext.csrfKey,\n\t\t\tcookie.secret,\n\t\t\t\"start\",\n\t\t\tcontext.scope,\n\t\t);\n\t\tconst response = pageResponse(await renderAuthSigninPage({ csrfToken }));\n\t\tif (\"setCookie\" in cookie) response.headers.append(\"Set-Cookie\", cookie.setCookie);\n\t\treturn result(response, \"signin_page\");\n\t} catch {\n\t\treturn await notice(503, \"internal_error\");\n\t}\n}\n\nfunction guardPriority(guard: BrowserFormGuardResult) {\n\tif (guard.ok) return null;\n\tif (guard.error === \"origin_rejected\") return notice(403, \"origin_rejected\");\n\tif (guard.error === \"rate_limited\")\n\t\treturn notice(429, \"rate_limited\", { \"Retry-After\": String(guard.retryAfterS) });\n\tif (guard.error === \"client_unidentified\" || guard.error === \"invalid_input\")\n\t\treturn notice(503, \"internal_error\");\n\treturn null;\n}\nfunction guardFailure(guard: Extract<BrowserFormGuardResult, { ok: false }>) {\n\tswitch (guard.error) {\n\t\tcase \"unsupported_media_type\":\n\t\t\treturn notice(415, guard.error);\n\t\tcase \"body_too_large\":\n\t\t\treturn notice(413, guard.error);\n\t\tcase \"form_invalid\":\n\t\t\treturn notice(400, guard.error);\n\t\tcase \"cookie_invalid\":\n\t\tcase \"cookie_missing\":\n\t\tcase \"csrf_invalid\":\n\t\t\treturn notice(403, guard.error);\n\t\tdefault:\n\t\t\treturn notice(503, \"internal_error\");\n\t}\n}\n\nasync function admitStart(\n\tcontext: Context,\n\tsnapshot: Snapshot,\n\tbinderHash: string,\n): Promise<CoordinatorBrowserSigninStartResponse> {\n\tconst start = await readBrowserCookie(snapshot.cookie, \"start\");\n\tif (start.kind !== \"present\" || start.cookieHash !== binderHash)\n\t\treturn notice(503, \"internal_error\");\n\tlet authorization: Awaited<ReturnType<CoordinatorOidcClient[\"createAuthorizationRequest\"]>>;\n\ttry {\n\t\tauthorization = await context.client.createAuthorizationRequest();\n\t} catch {\n\t\treturn notice(503, \"provider_request_failed\");\n\t}\n\tconst digest = await globalThis.crypto.subtle.digest(\n\t\t\"SHA-256\",\n\t\tnew TextEncoder().encode(authorization.material.state),\n\t);\n\tconst stateHash = Array.from(new Uint8Array(digest), (byte) =>\n\t\tbyte.toString(16).padStart(2, \"0\"),\n\t).join(\"\");\n\tconst response = pageResponse(\n\t\tawait renderAuthSigninContinuePage({ authorizationUrl: authorization.authorizationUrl }),\n\t);\n\tresponse.headers.append(\"Set-Cookie\", reissueStartCookieAsTransaction(start.secret));\n\tresponse.headers.append(\"Set-Cookie\", clearBrowserCookie(\"start\"));\n\t// Prebuild locally; cookies leave only after durable unique-binder admission.\n\tconst admitted = await context.store.startAuthBrowserTransaction(\n\t\t{\n\t\t\tpurpose: \"signin\",\n\t\t\tstateHash,\n\t\t\tbinderHash,\n\t\t\tnonce: authorization.material.nonce,\n\t\t\tpkceVerifier: authorization.material.pkceVerifier,\n\t\t},\n\t\tcontext.storeConfig,\n\t);\n\tif (admitted.kind === \"started\") return result(response, \"signin_started\");\n\tif (admitted.kind === \"rejected\") {\n\t\tif (admitted.error === \"transaction_conflict\") return notice(409, \"start_conflict\");\n\t\tif (admitted.error === \"transaction_limited\" || admitted.error === \"clock_retention_blocked\")\n\t\t\treturn notice(503, \"start_limited\");\n\t}\n\treturn notice(503, \"internal_error\");\n}\n\nasync function signInStart(\n\tcontext: Context,\n\trequest: Request,\n\tclientKey: string,\n): Promise<CoordinatorBrowserSigninStartResponse> {\n\ttry {\n\t\tconst snapshot = snapshotRequest(request);\n\t\tconst routing = routeError(context, snapshot, \"POST\");\n\t\tif (routing) return await routing;\n\t\t// Guard snapshots native request fields in this same synchronous tick.\n\t\tconst pendingGuard = guardBrowserForm({\n\t\t\trequest,\n\t\t\tscope: context.scope,\n\t\t\tcsrfKey: context.csrfKey,\n\t\t\taction: \"signin_start\",\n\t\t\tlimiter: context.limiter,\n\t\t\tclientKey,\n\t\t});\n\t\tconst guard = await pendingGuard;\n\t\tconst priority = guardPriority(guard);\n\t\tif (priority) return await priority;\n\t\tconst transaction = await readBrowserStartTransaction(\n\t\t\tsnapshot.cookie,\n\t\t\tcontext.store,\n\t\t\tcontext.storeConfig,\n\t\t);\n\t\tif (transaction === \"invalid\") return await notice(400, \"cookie_invalid\");\n\t\tif (transaction === \"active\") return await notice(409, \"signin_in_progress\");\n\t\tif (!guard.ok) return await guardFailure(guard);\n\t\tif (guard.action !== \"signin_start\") return await notice(503, \"internal_error\");\n\t\tif (await liveSession(context, snapshot)) return accountRedirect(context);\n\t\treturn await admitStart(context, snapshot, guard.cookieHash);\n\t} catch {\n\t\treturn await notice(503, \"internal_error\");\n\t}\n}\n\nfunction captureOidcOptions(input: unknown): CoordinatorOidcOptions | undefined {\n\tconst supplied = ownData(input, \"oidcOptions\");\n\tif (supplied === undefined) return undefined;\n\tconst fetch = ownData(supplied, \"fetch\") as CoordinatorOidcOptions[\"fetch\"];\n\tconst timeoutSeconds = ownData(\n\t\tsupplied,\n\t\t\"timeoutSeconds\",\n\t) as CoordinatorOidcOptions[\"timeoutSeconds\"];\n\treturn Object.freeze({ fetch, timeoutSeconds });\n}\n\n/** Unmounted start handlers only. No callback, cleanup, session rotation or route registration. */\nexport async function createCoordinatorBrowserSigninStart(\n\tinput: CoordinatorBrowserSigninStartInput,\n): Promise<CoordinatorBrowserSigninStartResult> {\n\ttry {\n\t\tconst settings = captureCoordinatorBrowserAuthConfig(ownData(input, \"config\"));\n\t\tif (settings.kind === \"disabled\")\n\t\t\treturn Object.freeze({ ok: false, error: \"browser_auth_disabled\" });\n\t\tif (settings.kind === \"invalid\")\n\t\t\treturn Object.freeze({\n\t\t\t\tok: false,\n\t\t\t\terror: \"browser_auth_config_invalid\",\n\t\t\t\tfield: settings.field,\n\t\t\t});\n\t\tconst csrfKey = ownData(input, \"csrfKey\") as BrowserCsrfKey;\n\t\tconst receiver = ownData(input, \"store\");\n\t\tconst start = dataMethod(\n\t\t\treceiver,\n\t\t\t\"startAuthBrowserTransaction\",\n\t\t) as SigninStore[\"startAuthBrowserTransaction\"];\n\t\tconst read = dataMethod(receiver, \"readAuthSession\") as SigninStore[\"readAuthSession\"];\n\t\tconst activity = dataMethod(\n\t\t\treceiver,\n\t\t\t\"readAuthBrowserTransactionActivity\",\n\t\t) as SigninStore[\"readAuthBrowserTransactionActivity\"];\n\t\tconst store: SigninStore = Object.freeze({\n\t\t\tstartAuthBrowserTransaction: start.bind(receiver),\n\t\t\treadAuthSession: read.bind(receiver),\n\t\t\treadAuthBrowserTransactionActivity: activity.bind(receiver),\n\t\t});\n\t\tconst limiter = ownData(input, \"limiter\") as InMemoryRequestRateLimiter;\n\t\tdataMethod(limiter, \"check\");\n\t\tconst oidcOptions = captureOidcOptions(input);\n\t\tconst scope = Object.freeze({ publicOrigin: settings.publicOrigin, store: settings.store });\n\t\tconst signinUrl = new URL(\"/auth/sign-in\", settings.publicOrigin).href;\n\t\tconst accountUrl = new URL(\"/auth/account\", settings.publicOrigin).href;\n\t\tconst oidc = await createCoordinatorOidcClient(settings.oidc, oidcOptions);\n\t\tif (!oidc.ok) return Object.freeze({ ok: false, error: oidc.error });\n\t\tconst context: Context = Object.freeze({\n\t\t\tstoreConfig: settings.store,\n\t\t\tscope,\n\t\t\tcsrfKey,\n\t\t\tstore,\n\t\t\tlimiter,\n\t\t\tclient: oidc.client,\n\t\t\tsigninUrl,\n\t\t\taccountUrl,\n\t\t});\n\t\treturn Object.freeze({\n\t\t\tok: true,\n\t\t\thandlers: Object.freeze({\n\t\t\t\tsignInPage: (request: Request) => signInPage(context, request),\n\t\t\t\tsignInStart: (request: Request, clientKey: string) =>\n\t\t\t\t\tsignInStart(context, request, clientKey),\n\t\t\t}),\n\t\t});\n\t} catch {\n\t\treturn Object.freeze({ ok: false, error: \"invalid_input\" });\n\t}\n}\n","/** Browser pages for ADR 0005 Section 8 rebinding. Presentation only; the ceremony decides. */\nimport {\n\tbuildPage,\n\ttype CoordinatorAuthBrowserPage,\n\tescapeHtml,\n} from \"./coordinator-auth-browser-view.js\";\nimport { parseCoordinatorAuthLoopback } from \"./coordinator-auth-loopback.js\";\nimport type {\n\tDeviceRebindConfirmation,\n\tDeviceRebindRefusal,\n} from \"./coordinator-device-rebind-ceremony.js\";\n\nexport const DEVICE_REBIND_BROWSER_PATHS = Object.freeze({\n\tstart: \"/auth/rebind/start\",\n\tconfirm: \"/auth/rebind/confirm\",\n});\n\nfunction hidden(fields: Record<string, string>): string {\n\treturn Object.entries(fields)\n\t\t.map(\n\t\t\t([name, value]) =>\n\t\t\t\t`<input type=\"hidden\" name=\"${escapeHtml(name)}\" value=\"${escapeHtml(value)}\">`,\n\t\t)\n\t\t.join(\"\");\n}\n\nfunction form(action: string, fields: Record<string, string>, label: string): string {\n\treturn `<form method=\"post\" action=\"${action}\">${hidden(fields)}<button type=\"submit\">${escapeHtml(label)}</button></form>`;\n}\n\n/** Private start code stays in hidden form data; the page submits itself. */\nexport function renderDeviceRebindStartPage(input: {\n\tattemptId: string;\n\tstartCode: string;\n\tcsrf: string;\n}): Promise<CoordinatorAuthBrowserPage> {\n\tconst fields = { csrf: input.csrf, attempt_id: input.attemptId, start_code: input.startCode };\n\treturn buildPage(\n\t\t\"Sign in on this device\",\n\t\t`<h1>Connecting to Google…</h1><p>You’ll choose an account and confirm before this device changes.</p><p class=\"note\">If nothing happens, continue below. Do not share this page.</p><div class=\"actions\">${form(DEVICE_REBIND_BROWSER_PATHS.start, fields, \"Continue with Google\")}</div>`,\n\t\tundefined,\n\t\t{ referrerPolicy: \"same-origin\", autoSubmit: true },\n\t);\n}\n\nfunction detail(label: string, value: string): string {\n\treturn `<dt>${escapeHtml(label)}</dt><dd><code>${escapeHtml(value)}</code></dd>`;\n}\n\n/** Self-bind: the account already belongs to this device's Identity. */\nfunction renderSelfBindConfirmPage(input: {\n\tconfirmation: DeviceRebindConfirmation;\n\tcsrf: string;\n}): Promise<CoordinatorAuthBrowserPage> {\n\tconst c = input.confirmation;\n\tconst details =\n\t\tdetail(\"Device\", c.deviceId) +\n\t\tdetail(\"Key fingerprint\", c.fingerprint) +\n\t\tdetail(\"Identity\", c.currentIdentityId);\n\tconst fields = {\n\t\tcsrf: input.csrf,\n\t\tattempt_id: c.attemptId,\n\t\tconfirmation_hash: c.confirmationHash,\n\t};\n\treturn buildPage(\n\t\t\"Use this account on this device\",\n\t\t`<h1>Use this account on this device</h1><p>This Google account already belongs to this device’s Identity. Confirming lets this device refresh and unlink it too.</p><section aria-label=\"Device\"><dl>${details}</dl></section><p>A device can do this only once.</p><div class=\"actions\">${form(DEVICE_REBIND_BROWSER_PATHS.confirm, fields, \"Confirm\")}</div>`,\n\t\tundefined,\n\t\t{ referrerPolicy: \"same-origin\" },\n\t);\n}\n\nexport function renderDeviceRebindConfirmPage(input: {\n\tconfirmation: DeviceRebindConfirmation;\n\tcsrf: string;\n}): Promise<CoordinatorAuthBrowserPage> {\n\tconst c = input.confirmation;\n\tif (c.targetIdentityId === c.currentIdentityId) return renderSelfBindConfirmPage(input);\n\tconst teams = c.groupsWithoutAccess.length ? c.groupsWithoutAccess.join(\", \") : \"None\";\n\tconst details =\n\t\tdetail(\"Device\", c.deviceId) +\n\t\tdetail(\"Key fingerprint\", c.fingerprint) +\n\t\tdetail(\"Current Identity\", c.currentIdentityId) +\n\t\tdetail(\"New Identity\", c.targetIdentityId) +\n\t\tdetail(\"Teams without access yet\", teams);\n\tconst fields = {\n\t\tcsrf: input.csrf,\n\t\tattempt_id: c.attemptId,\n\t\tconfirmation_hash: c.confirmationHash,\n\t};\n\treturn buildPage(\n\t\t\"Sign in on this device\",\n\t\t`<h1>Sign in on this device</h1><p>This device will use the Identity of the Google account you chose. Its existing memories keep their author.</p><section aria-label=\"Change\"><dl>${details}</dl></section><p>Teams the new Identity isn’t in won’t sync on this device until a Team admin adds it. A device can switch only once.</p><div class=\"actions\">${form(DEVICE_REBIND_BROWSER_PATHS.confirm, fields, \"Switch this device\")}</div>`,\n\t\tundefined,\n\t\t{ referrerPolicy: \"same-origin\" },\n\t);\n}\n\n/** Caller releases this secret-bearing page only after confirmation commits. */\nexport function renderDeviceRebindHopPage(input: {\n\tloopbackRedirect: string;\n\tattemptId: string;\n\tcompletionSecret: string;\n\tconfirmationHash: string;\n}): Promise<CoordinatorAuthBrowserPage> {\n\tconst parsed = parseCoordinatorAuthLoopback(input.loopbackRedirect);\n\tif (\n\t\t!parsed.ok ||\n\t\t!/^[A-Za-z0-9_-]{43}$/.test(input.completionSecret) ||\n\t\t!/^[a-f0-9]{64}$/.test(input.confirmationHash)\n\t)\n\t\tthrow new Error(\"device_rebind_view_invalid_input\");\n\t// Concatenation preserves the saved literal, including an explicit :80.\n\tconst href = `${parsed.destination}?attempt_id=${encodeURIComponent(input.attemptId)}&completion=${input.completionSecret}&confirmation=${input.confirmationHash}`;\n\treturn buildPage(\n\t\t\"Finishing sign-in\",\n\t\t`<h1>Finishing sign-in…</h1><p>Returning to Codemem on this computer. If nothing happens, continue below.</p><p class=\"note\">Do not share this link.</p><div class=\"actions\"><a class=\"link\" href=\"${escapeHtml(href)}\" referrerpolicy=\"no-referrer\" rel=\"noreferrer\">Continue on this computer</a></div>`,\n\t\tundefined,\n\t\t{ refreshUrl: href },\n\t);\n}\n\n/** Browser-only states on top of the ceremony's refusals. */\nexport type DeviceRebindNotice = DeviceRebindRefusal | \"unknown\" | \"rate_limited\" | \"busy\";\n\nconst REFUSAL_COPY: Record<DeviceRebindNotice, [string, string]> = {\n\trate_limited: [\"Too many tries\", \"Wait a minute, then start again from Codemem on this device.\"],\n\tbusy: [\n\t\t\"Another sign-in is open\",\n\t\t\"Finish or close the other sign-in, then start again from Codemem on this device.\",\n\t],\n\tunavailable: [\"Sign-in can’t continue\", \"Start again from Codemem on this device.\"],\n\tunknown: [\n\t\t\"Sign-in result unknown\",\n\t\t\"Return to Codemem on this device. It will check whether the change finished.\",\n\t],\n\tretry: [\"Something changed\", \"Start again from Codemem on this device.\"],\n\tcurrent_identity_linked: [\n\t\t\"This device already has an account\",\n\t\t\"Its Identity is linked to a Google account. Unlink that account first.\",\n\t],\n\tdevice_already_bound: [\"This device already switched\", \"A device can switch accounts only once.\"],\n\taccount_not_linked: [\n\t\t\"This Google account isn’t set up\",\n\t\t\"Link this Google account from a device that uses the Identity you want, then try again.\",\n\t],\n\talready_this_identity: [\n\t\t\"Already using this account\",\n\t\t\"This device already uses that Google account’s Identity.\",\n\t],\n\tdaily_limit: [\n\t\t\"Too many switches today\",\n\t\t\"This account’s Identity reached today’s limit for switching devices. Try again tomorrow.\",\n\t],\n};\n\n/**\n * A refusal at the Google callback: explain it here and send the browser back\n * to the device, which stops waiting and shows the next step.\n */\nexport function renderDeviceRebindReturnPage(input: {\n\treason: DeviceRebindRefusal;\n\tloopbackRedirect: string;\n\tattemptId: string;\n}): Promise<CoordinatorAuthBrowserPage> {\n\tconst parsed = parseCoordinatorAuthLoopback(input.loopbackRedirect);\n\tif (!parsed.ok) throw new Error(\"device_rebind_view_invalid_input\");\n\tconst [title, body] = REFUSAL_COPY[input.reason];\n\tconst href = `${parsed.destination}?attempt_id=${encodeURIComponent(input.attemptId)}&refused=${input.reason}`;\n\treturn buildPage(\n\t\ttitle,\n\t\t`<h1>${escapeHtml(title)}</h1><p>${escapeHtml(body)}</p><p>Returning to Codemem on this computer.</p><div class=\"actions\"><a class=\"link\" href=\"${escapeHtml(href)}\" referrerpolicy=\"no-referrer\" rel=\"noreferrer\">Return to Codemem</a></div>`,\n\t\tundefined,\n\t\t{ refreshUrl: href },\n\t);\n}\n\nexport function renderDeviceRebindNotice(\n\treason: DeviceRebindNotice,\n): Promise<CoordinatorAuthBrowserPage> {\n\tconst [title, body] = REFUSAL_COPY[reason];\n\treturn buildPage(title, `<h1>${escapeHtml(title)}</h1><p>${escapeHtml(body)}</p>`);\n}\n","/** Browser routes for ADR 0005 Section 8 rebinding; the ceremony re-checks every step. */\nimport { CoordinatorAuthBrowserTransactions } from \"./coordinator-auth-browser-transaction.js\";\nimport {\n\ttype CoordinatorAuthBrowserPage,\n\trenderAuthSigninContinuePage,\n} from \"./coordinator-auth-browser-view.js\";\nimport { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport type { AuthLinkBackend } from \"./coordinator-auth-link.js\";\nimport { decodeCoordinatorAuthProof32 } from \"./coordinator-auth-proof.js\";\nimport { captureCoordinatorBrowserAuthConfig } from \"./coordinator-browser-auth-config.js\";\nimport {\n\tclearBrowserCookie,\n\tissueBrowserCookie,\n\treadBrowserCookie,\n} from \"./coordinator-browser-credential.js\";\nimport { type BrowserCsrfKey, issueBrowserCsrfToken } from \"./coordinator-browser-csrf.js\";\nimport { readBrowserFormBody } from \"./coordinator-browser-form-body.js\";\nimport { checkBrowserAuthRequestRate } from \"./coordinator-browser-form-guard.js\";\nimport { snapshotBrowserRequest } from \"./coordinator-browser-request.js\";\nimport { readBrowserStartTransaction } from \"./coordinator-browser-start-transaction.js\";\nimport {\n\tcreateDeviceRebindCeremony,\n\ttype DeviceRebindResult,\n} from \"./coordinator-device-rebind-ceremony.js\";\nimport {\n\tDEVICE_REBIND_BROWSER_PATHS,\n\trenderDeviceRebindConfirmPage,\n\trenderDeviceRebindHopPage,\n\trenderDeviceRebindNotice,\n\trenderDeviceRebindReturnPage,\n\trenderDeviceRebindStartPage,\n} from \"./coordinator-device-rebind-view.js\";\nimport {\n\ttype CoordinatorOidcClient,\n\ttype CoordinatorOidcOptions,\n\tcreateCoordinatorOidcClient,\n} from \"./coordinator-oidc.js\";\nimport type { InMemoryRequestRateLimiter } from \"./request-rate-limit.js\";\n\nexport interface DeviceRebindBrowserInput {\n\tconfig: unknown;\n\tcsrfKey: BrowserCsrfKey;\n\tlimiter: InMemoryRequestRateLimiter;\n\t/** Must already have the rebind tables; see readDeviceRebindBackend. */\n\tbackend: AuthLinkBackend;\n\toidcOptions?: CoordinatorOidcOptions;\n\tnow?: () => number;\n}\n\ntype Ceremony = ReturnType<typeof createDeviceRebindCeremony>;\ninterface Context {\n\tceremony: Ceremony;\n\tcsrfKey: BrowserCsrfKey;\n\tlimiter: InMemoryRequestRateLimiter;\n\tscope: { publicOrigin: string; store: Parameters<typeof readBrowserStartTransaction>[2] };\n\tstartUrl: string;\n\ttransactions: CoordinatorAuthBrowserTransactions;\n}\n\nfunction pageResponse(page: CoordinatorAuthBrowserPage, status = 200): Response {\n\treturn new Response(page.body, { status, headers: page.headers });\n}\n\nasync function notice(result: DeviceRebindResult | null, status = 403): Promise<Response> {\n\tconst reason = result?.kind === \"refused\" ? result.reason : \"unknown\";\n\treturn pageResponse(await renderDeviceRebindNotice(reason), reason === \"unknown\" ? 503 : status);\n}\n\nasync function browserNotice(kind: \"rate_limited\" | \"busy\", status: 409 | 429): Promise<Response> {\n\treturn pageResponse(await renderDeviceRebindNotice(kind), status);\n}\n\n/** Exactly `attempt_id` and a canonical 32-byte `start_code` at the start URL. */\nfunction startQuery(text: string, startUrl: string) {\n\tif (text.length > 8192 || text.includes(\"#\")) return null;\n\tconst url = new URL(text);\n\tif (`${url.origin}${url.pathname}` !== startUrl || url.username || url.password) return null;\n\tconst attemptId = url.searchParams.get(\"attempt_id\");\n\tconst startCode = url.searchParams.get(\"start_code\");\n\tif (\n\t\t[...url.searchParams].length !== 2 ||\n\t\t!isAuthControllerId(attemptId) ||\n\t\t!startCode ||\n\t\t!decodeCoordinatorAuthProof32(startCode)\n\t)\n\t\treturn null;\n\treturn { attemptId, startCode };\n}\n\nasync function startPage(context: Context, request: Request, clientKey: string) {\n\tconst snapshot = snapshotBrowserRequest(request);\n\tconst rateKey = JSON.stringify([\"device-rebind-start-page\", clientKey]);\n\tif (!checkBrowserAuthRequestRate(request, context.limiter, rateKey, 30).allowed)\n\t\treturn browserNotice(\"rate_limited\", 429);\n\tconst query = startQuery(snapshot.url, context.startUrl);\n\tif (!query) return notice({ kind: \"refused\", reason: \"unavailable\" }, 400);\n\tconst transaction = await readBrowserStartTransaction(\n\t\tsnapshot.cookie,\n\t\tcontext.transactions,\n\t\tcontext.scope.store,\n\t);\n\tconst current = await readBrowserCookie(snapshot.cookie, \"start\");\n\tif (transaction === \"active\") return browserNotice(\"busy\", 409);\n\tif (transaction === \"invalid\" || current.kind === \"invalid\")\n\t\treturn notice({ kind: \"refused\", reason: \"unavailable\" }, 400);\n\tconst issued = current.kind === \"absent\" ? await issueBrowserCookie(\"start\") : null;\n\tconst secret = current.kind === \"present\" ? current.secret : issued?.secret;\n\tif (!secret) return notice(null);\n\tconst csrf = await issueBrowserCsrfToken(context.csrfKey, secret, \"start\", context.scope);\n\tconst response = pageResponse(await renderDeviceRebindStartPage({ ...query, csrf }));\n\tif (issued) response.headers.append(\"Set-Cookie\", issued.setCookie);\n\treturn response;\n}\n\nasync function start(context: Context, request: Request, clientKey: string) {\n\tconst result = await context.ceremony.claimBrowser(request, clientKey);\n\tif (result?.kind !== \"browser_claimed\") return notice(result);\n\tconst response = pageResponse(\n\t\tawait renderAuthSigninContinuePage({ authorizationUrl: result.authorizationUrl }),\n\t);\n\tfor (const cookie of result.setCookies) response.headers.append(\"Set-Cookie\", cookie);\n\treturn response;\n}\n\n/**\n * The form carries the confirmation hash the person saw. It is removed before\n * the shared form guard reads the body, then checked by the ceremony.\n */\nasync function confirmationForm(request: Request, origin: string) {\n\tif (\n\t\trequest.headers.get(\"origin\") !== origin ||\n\t\t!/^application\\/x-www-form-urlencoded(?:\\s*;\\s*charset=utf-8)?$/i.test(\n\t\t\trequest.headers.get(\"content-type\") ?? \"\",\n\t\t)\n\t)\n\t\treturn null;\n\tconst copy = request.clone();\n\tconst read = await readBrowserFormBody({\n\t\tbody: copy.body,\n\t\tcontentLength: copy.headers.get(\"content-length\"),\n\t});\n\tif (!read.ok) return null;\n\tlet text: string;\n\ttry {\n\t\ttext = new TextDecoder(\"utf-8\", { fatal: true }).decode(read.bytes);\n\t} catch {\n\t\treturn null;\n\t}\n\tconst fields = new URLSearchParams(text);\n\tconst hashes = fields.getAll(\"confirmation_hash\");\n\tconst attemptId = fields.get(\"attempt_id\");\n\tif (hashes.length !== 1 || !/^[a-f0-9]{64}$/.test(hashes[0] ?? \"\") || !attemptId) return null;\n\tfields.delete(\"confirmation_hash\");\n\tconst headers = new Headers(request.headers);\n\theaders.delete(\"content-length\");\n\tconst checked = new Request(request.url, { method: \"POST\", headers, body: fields.toString() });\n\treturn { checked, attemptId, confirmationHash: hashes[0] as string };\n}\n\nasync function confirm(context: Context, request: Request, clientKey: string) {\n\tconst form = await confirmationForm(request, context.scope.publicOrigin);\n\tif (!form) return notice({ kind: \"refused\", reason: \"unavailable\" }, 400);\n\tconst result = await context.ceremony.confirm(form.checked, clientKey, form.confirmationHash);\n\tif (result?.kind !== \"confirmed\") return notice(result);\n\tconst response = pageResponse(\n\t\tawait renderDeviceRebindHopPage({\n\t\t\tloopbackRedirect: result.loopbackRedirect,\n\t\t\tattemptId: form.attemptId,\n\t\t\tcompletionSecret: result.completionSecret,\n\t\t\tconfirmationHash: form.confirmationHash,\n\t\t}),\n\t);\n\tresponse.headers.append(\"Set-Cookie\", clearBrowserCookie(\"transaction\"));\n\treturn response;\n}\n\n/** null when the callback belongs to another ceremony. */\nasync function callback(context: Context, request: Request): Promise<Response | null> {\n\tconst result = await context.ceremony.verifyCallback(request);\n\tif (result === null) return null;\n\tif (result.kind === \"refused\" && result.retired) {\n\t\tconst response = result.returnTo\n\t\t\t? pageResponse(\n\t\t\t\t\tawait renderDeviceRebindReturnPage({ reason: result.reason, ...result.returnTo }),\n\t\t\t\t)\n\t\t\t: await notice(result);\n\t\t// Without this, the spent transaction blocks a fresh start until it expires.\n\t\tresponse.headers.append(\"Set-Cookie\", clearBrowserCookie(\"transaction\"));\n\t\treturn response;\n\t}\n\tif (result.kind !== \"verified\") return notice(result);\n\treturn pageResponse(\n\t\tawait renderDeviceRebindConfirmPage({ confirmation: result.confirmation, csrf: result.csrf }),\n\t);\n}\n\n/** Unexpected errors render the unknown-outcome page; the device then reads status. */\nfunction guarded<A extends unknown[]>(\n\tstep: (context: Context, ...args: A) => Promise<Response>,\n\tcontext: Context,\n) {\n\treturn async (...args: A): Promise<Response> => {\n\t\ttry {\n\t\t\treturn await step(context, ...args);\n\t\t} catch {\n\t\t\treturn notice(null);\n\t\t}\n\t};\n}\n\nexport async function createDeviceRebindBrowser(input: DeviceRebindBrowserInput) {\n\tconst settings = captureCoordinatorBrowserAuthConfig(input.config);\n\tif (settings.kind !== \"enabled\") return { ok: false as const };\n\tconst now = input.now ?? (() => Date.now());\n\t// Discovery waits for the first rebind. Only a finished client is kept, so\n\t// concurrent requests never share another request's discovery.\n\tlet finished: CoordinatorOidcClient | undefined;\n\tconst oidc = async () => {\n\t\tif (finished) return finished;\n\t\tconst created = await createCoordinatorOidcClient(settings.oidc, input.oidcOptions);\n\t\tif (!created.ok) throw new Error(\"device_rebind_oidc_unavailable\");\n\t\tfinished ??= created.client;\n\t\treturn finished;\n\t};\n\tconst client: Pick<CoordinatorOidcClient, \"createAuthorizationRequest\" | \"verifyCallback\"> = {\n\t\tcreateAuthorizationRequest: async () => (await oidc()).createAuthorizationRequest(),\n\t\tverifyCallback: async (...args) => (await oidc()).verifyCallback(...args),\n\t};\n\tconst context: Context = {\n\t\tceremony: createDeviceRebindCeremony({\n\t\t\tbackend: input.backend,\n\t\t\tconfig: settings.store,\n\t\t\tpublicOrigin: settings.publicOrigin,\n\t\t\tcsrfKey: input.csrfKey,\n\t\t\tlimiter: input.limiter,\n\t\t\tclient,\n\t\t\tnow,\n\t\t}),\n\t\tcsrfKey: input.csrfKey,\n\t\tlimiter: input.limiter,\n\t\tscope: { publicOrigin: settings.publicOrigin, store: settings.store },\n\t\tstartUrl: `${settings.publicOrigin}${DEVICE_REBIND_BROWSER_PATHS.start}`,\n\t\ttransactions: new CoordinatorAuthBrowserTransactions(input.backend, now),\n\t};\n\treturn {\n\t\tok: true as const,\n\t\thandlers: Object.freeze({\n\t\t\tstartPage: guarded(startPage, context),\n\t\t\tstart: guarded(start, context),\n\t\t\tconfirm: guarded(confirm, context),\n\t\t\tcallback: async (request: Request): Promise<Response | null> => {\n\t\t\t\ttry {\n\t\t\t\t\treturn await callback(context, request);\n\t\t\t\t} catch {\n\t\t\t\t\treturn notice(null);\n\t\t\t\t}\n\t\t\t},\n\t\t}),\n\t};\n}\n","/** Opt-in owner transport; production admission and server dependencies are explicit. */\nimport { CoordinatorAuthBrowserTransactions } from \"./coordinator-auth-browser-transaction.js\";\nimport { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport type { AuthLinkBackend } from \"./coordinator-auth-link.js\";\nimport { parseCoordinatorAuthLoopback } from \"./coordinator-auth-loopback.js\";\nimport { captureCoordinatorBrowserAuthConfig } from \"./coordinator-browser-auth-config.js\";\nimport {\n\tclearBrowserCookie,\n\tissueBrowserCookie,\n\treadBrowserCookie,\n} from \"./coordinator-browser-credential.js\";\nimport {\n\ttype BrowserCsrfKey,\n\ttype BrowserCsrfScope,\n\timportBrowserCsrfKey,\n\tissueBrowserCsrfToken,\n} from \"./coordinator-browser-csrf.js\";\nimport { parseBrowserFormBody, readBrowserFormBody } from \"./coordinator-browser-form-body.js\";\nimport { checkBrowserAuthRequestRate } from \"./coordinator-browser-form-guard.js\";\nimport { readBrowserStartTransaction } from \"./coordinator-browser-start-transaction.js\";\nimport type { CoordinatorOidcOptions } from \"./coordinator-oidc.js\";\nimport type { OwnerEnrollmentAdmissionKey } from \"./owner-enrollment-admission.js\";\nimport {\n\tcreateCoordinatorOwnerEnrollment,\n\ttype OwnerEnrollmentStart,\n\ttype OwnerEnrollmentStartResult,\n} from \"./owner-enrollment-start.js\";\nimport {\n\tcreateInMemoryRequestRateLimiter,\n\ttype InMemoryRequestRateLimiter,\n} from \"./request-rate-limit.js\";\n\ninterface HttpOptionsBase {\n\tconfig: unknown;\n\tbackend: AuthLinkBackend;\n\toidcOptions: CoordinatorOidcOptions;\n\tclock?: () => number;\n}\nexport type CoordinatorOwnerEnrollmentHttpOptions = HttpOptionsBase &\n\t(\n\t\t| { mode?: \"private\" | \"local_test\"; csrfKey?: never; limiter?: never; admissionKey?: never }\n\t\t| {\n\t\t\t\tmode: \"production\";\n\t\t\t\tcsrfKey: BrowserCsrfKey;\n\t\t\t\tlimiter: InMemoryRequestRateLimiter;\n\t\t\t\tadmissionKey: OwnerEnrollmentAdmissionKey;\n\t\t }\n\t);\nexport interface CoordinatorOwnerEnrollmentHttp {\n\treadonly pin: BrowserCsrfScope[\"store\"] & { origin: string; issuer: string };\n\t/** Trusted browser issuer uses the same production ceremony as the HTTP routes. */\n\treadonly startOwnerBound: Enrollment[\"startOwnerBound\"];\n\t/** Owner-only paths, never the shared OIDC callback. */\n\tmatchesPath(path: string): boolean;\n\thandle(request: Request, trustedClientKey: string): Promise<Response>;\n\t/** Call only after shared dispatch has picked the persisted owner_enroll purpose. */\n\thandleCallback(request: Request, trustedClientKey: string): Promise<Response>;\n}\ntype Enrollment = Extract<\n\tAwaited<ReturnType<typeof createCoordinatorOwnerEnrollment>>,\n\t{ ok: true }\n>[\"enrollment\"];\ntype Verified = Extract<OwnerEnrollmentStartResult, { kind: \"verified\" }>;\nconst START_PATH = \"/auth/owner/start\";\nconst CONFIRM_PATH = \"/auth/owner/confirm\";\nconst ATTEMPTS_PATH = \"/v1/auth/owner-attempts\";\n\nfunction respond(\n\tbody: string | null,\n\tstatus: number,\n\theaders: ConstructorParameters<typeof Headers>[0] = {},\n): Response {\n\tconst safe = new Headers(headers);\n\tsafe.set(\"Cache-Control\", \"no-store\");\n\tsafe.set(\"Referrer-Policy\", \"no-referrer\");\n\tsafe.set(\"X-Content-Type-Options\", \"nosniff\");\n\tsafe.set(\n\t\t\"Content-Security-Policy\",\n\t\t\"default-src 'none'; frame-ancestors 'none'; base-uri 'none'\",\n\t);\n\treturn new Response(body, { status, headers: safe });\n}\nfunction reject(status = 400): Response {\n\treturn respond(\"Owner enrollment unavailable.\", status);\n}\nfunction json(value: unknown): Response {\n\treturn respond(JSON.stringify(value), 200, { \"Content-Type\": \"application/json\" });\n}\nfunction escapeHtml(value: string): string {\n\treturn value.replace(/[&<>\"']/g, (character) => {\n\t\tconst entities: Record<string, string> = {\n\t\t\t\"&\": \"&amp;\",\n\t\t\t\"<\": \"&lt;\",\n\t\t\t\">\": \"&gt;\",\n\t\t\t'\"': \"&quot;\",\n\t\t\t\"'\": \"&#39;\",\n\t\t};\n\t\treturn entities[character] ?? \"\";\n\t});\n}\nfunction hidden(name: string, value: string): string {\n\treturn `<input type=\"hidden\" name=\"${escapeHtml(name)}\" value=\"${escapeHtml(value)}\">`;\n}\nfunction form(action: string, fields: Record<string, string>, button: string): string {\n\treturn `<form method=\"post\" action=\"${action}\">${Object.entries(fields)\n\t\t.map(([name, value]) => hidden(name, value))\n\t\t.join(\"\")}<button type=\"submit\">${button}</button></form>`;\n}\nfunction page(content: string, cookies: string[] = []): Response {\n\tconst headers = new Headers({ \"Content-Type\": \"text/html; charset=utf-8\" });\n\tfor (const cookie of cookies) headers.append(\"Set-Cookie\", cookie);\n\treturn respond(\n\t\t`<!doctype html><html lang=\"en\"><meta charset=\"utf-8\"><title>Enroll owner device</title><body>${content}</body></html>`,\n\t\t200,\n\t\theaders,\n\t);\n}\nfunction redirect(location: string, cookies: string[]): Response {\n\tconst headers = new Headers({ Location: location });\n\tfor (const cookie of cookies) headers.append(\"Set-Cookie\", cookie);\n\treturn respond(null, 303, headers);\n}\nasync function startPage(request: Request, context: HttpContext): Promise<Response> {\n\tconst url = new URL(request.url);\n\tconst attemptId = url.searchParams.get(\"attempt_id\");\n\tconst startCode = url.searchParams.get(\"start_code\");\n\tconst fields = new URLSearchParams({\n\t\tcsrf: \"\",\n\t\tattempt_id: attemptId ?? \"\",\n\t\tstart_code: startCode ?? \"\",\n\t});\n\tif (\n\t\turl.searchParams.size !== 2 ||\n\t\t!parseBrowserFormBody(new TextEncoder().encode(fields.toString()), \"link_start\").ok\n\t)\n\t\treturn reject();\n\treturn renderOwnerEnrollmentStartForm(request, context, {\n\t\tattemptId: attemptId ?? \"\",\n\t\tstartCode: startCode ?? \"\",\n\t});\n}\n/** Only call with a newly started attempt; never use this to redeliver an old start. */\nexport async function renderOwnerEnrollmentStartForm(\n\trequest: Request,\n\tcontext: Pick<HttpContext, \"scope\" | \"key\" | \"transactionActivity\">,\n\tstart: { attemptId: string; startCode: string; deviceId?: string; fingerprint?: string },\n): Promise<Response> {\n\tconst { scope, key } = context;\n\tconst transaction = await context.transactionActivity(request.headers.get(\"cookie\"));\n\tconst current = await readBrowserCookie(request.headers.get(\"cookie\"), \"start\");\n\tif (transaction === \"active\" || transaction === \"invalid\" || current.kind === \"invalid\")\n\t\treturn reject();\n\tconst issued = current.kind === \"absent\" ? await issueBrowserCookie(\"start\") : null;\n\tconst secret = current.kind === \"present\" ? current.secret : issued?.secret;\n\tif (!secret) return reject();\n\tconst csrf = await issueBrowserCsrfToken(key, secret, \"start\", scope);\n\tconst display =\n\t\tstart.deviceId && start.fingerprint\n\t\t\t? `<p>Compare these details with your local device review before choosing an account.</p><dl><dt>Device ID</dt><dd>${escapeHtml(start.deviceId)}</dd><dt>Key fingerprint</dt><dd>${escapeHtml(start.fingerprint)}</dd></dl>`\n\t\t\t: \"\";\n\treturn page(\n\t\t`<h1>Enroll owner device</h1>${display}${form(START_PATH, { csrf, attempt_id: start.attemptId, start_code: start.startCode }, \"Choose account\")}`,\n\t\tissued ? [issued.setCookie] : [],\n\t);\n}\nfunction confirmationPage(result: Verified): Response {\n\tconst c = result.confirmation;\n\tconst details = {\n\t\t\"Verified account subject\": c.subject,\n\t\tIssuer: c.issuer,\n\t\tIdentity: c.identityId,\n\t\t\"Pending device ID\": c.deviceId,\n\t\tFingerprint: c.fingerprint,\n\t\tGroups: c.groups.join(\", \"),\n\t};\n\tconst display = Object.entries(details)\n\t\t.map(([label, value]) => `<dt>${escapeHtml(label)}</dt><dd>${escapeHtml(value)}</dd>`)\n\t\t.join(\"\");\n\treturn page(\n\t\t`<h1>Confirm owner device</h1><dl>${display}</dl>${form(CONFIRM_PATH, { csrf: result.csrf, attempt_id: c.attemptId, confirmation_hash: c.confirmationHash }, \"Enroll this device\")}`,\n\t);\n}\nfunction formHeadersValid(request: Request, origin: string): boolean {\n\treturn (\n\t\trequest.headers.get(\"origin\") === origin &&\n\t\t/^application\\/x-www-form-urlencoded(?:\\s*;\\s*charset=utf-8)?$/i.test(\n\t\t\trequest.headers.get(\"content-type\") ?? \"\",\n\t\t)\n\t);\n}\nasync function confirmBrowser(\n\trequest: Request,\n\tapi: Enrollment,\n\tclientKey: string,\n\torigin: string,\n): Promise<Response> {\n\t// Check original transport/cookie headers before reading a bounded clone. The API\n\t// authenticates the same cookie and CSRF after removing the display commitment.\n\tif (!formHeadersValid(request, origin)) return reject();\n\tconst cookie = await readBrowserCookie(request.headers.get(\"cookie\"), \"transaction\");\n\tif (cookie.kind !== \"present\") return reject();\n\tconst copy = request.clone();\n\tconst read = await readBrowserFormBody({\n\t\tbody: copy.body,\n\t\tcontentLength: copy.headers.get(\"content-length\"),\n\t});\n\tif (!read.ok) return reject();\n\tconst raw = new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: true }).decode(read.bytes);\n\tif (!/^[A-Za-z0-9*._%+=&-]+$/.test(raw)) return reject();\n\tconst fields = new URLSearchParams(raw);\n\tconst hashes = fields.getAll(\"confirmation_hash\");\n\tif (hashes.length !== 1 || !/^[a-f0-9]{64}$/.test(hashes[0] ?? \"\")) return reject();\n\tfields.delete(\"confirmation_hash\");\n\tconst body = fields.toString();\n\tif (!parseBrowserFormBody(new TextEncoder().encode(body), \"transaction_attempt\").ok)\n\t\treturn reject();\n\tconst headers = new Headers(request.headers);\n\theaders.delete(\"content-length\");\n\tconst checked = new Request(request.url, { method: \"POST\", headers, body });\n\tconst result = await api.confirm(checked, clientKey, hashes[0] as string);\n\tif (result.kind !== \"confirmed\") return reject();\n\tconst destination = parseCoordinatorAuthLoopback(result.loopbackRedirect);\n\tif (!destination.ok) return reject();\n\tconst location = new URL(destination.destination);\n\tlocation.searchParams.set(\"attempt_id\", result.confirmation.attemptId);\n\tlocation.searchParams.set(\"completion\", result.completionSecret);\n\tlocation.searchParams.set(\"confirmation\", result.confirmation.confirmationHash);\n\treturn redirect(location.href, [clearBrowserCookie(\"transaction\")]);\n}\nasync function jsonAction(request: Request, api: Enrollment, clientKey: string): Promise<Response> {\n\tif (\n\t\t!/^application\\/json(?:\\s*;\\s*charset=utf-8)?$/i.test(request.headers.get(\"content-type\") ?? \"\")\n\t)\n\t\treturn reject(415);\n\tconst read = await readBrowserFormBody({\n\t\tbody: request.body,\n\t\tcontentLength: request.headers.get(\"content-length\"),\n\t});\n\tif (!read.ok) return reject();\n\tconst body: unknown = JSON.parse(new TextDecoder(\"utf-8\", { fatal: true }).decode(read.bytes));\n\tif (!body || typeof body !== \"object\" || Array.isArray(body)) return reject();\n\tconst finalize = new URL(request.url).pathname.endsWith(\"/finalize\");\n\tconst keys = finalize\n\t\t? [\"attemptId\", \"completionSecret\", \"signature\"]\n\t\t: [\"attemptId\", \"deviceId\", \"publicKey\", \"loopbackRedirect\", \"browserStartCode\", \"signature\"];\n\tif (\n\t\tObject.keys(body).length !== keys.length ||\n\t\tkeys.some((name) => typeof Reflect.get(body, name) !== \"string\")\n\t)\n\t\treturn reject();\n\tconst result = finalize\n\t\t? await api.finalize(body as Parameters<Enrollment[\"finalize\"]>[0])\n\t\t: await api.start(\n\t\t\t\tbody as OwnerEnrollmentStart,\n\t\t\t\tclientKey,\n\t\t\t\t/^Bearer (v1\\.[A-Za-z0-9._-]+)$/.exec(request.headers.get(\"authorization\") ?? \"\")?.[1],\n\t\t\t);\n\tif (result.kind === \"started\" || result.kind === \"finalized\" || result.kind === \"prior_commit\")\n\t\treturn json(result);\n\treturn reject();\n}\nexport function coordinatorOwnerEnrollmentHttpMethods(\n\tpath: string,\n\tcallback: string,\n\tpinPath = \"/v1/auth/owner-pilot\",\n): string | null {\n\tif (path === pinPath || path === callback) return \"GET\";\n\tif (path === START_PATH) return \"GET, POST\";\n\tif (path === CONFIRM_PATH || path === ATTEMPTS_PATH || path === `${ATTEMPTS_PATH}/finalize`)\n\t\treturn \"POST\";\n\treturn null;\n}\nexport function matchesCoordinatorOwnerEnrollmentHttpPath(\n\tpath: string,\n\tmode: \"private\" | \"production\" = \"private\",\n): boolean {\n\treturn (\n\t\tcoordinatorOwnerEnrollmentHttpMethods(\n\t\t\tpath,\n\t\t\t\"\",\n\t\t\tmode === \"production\" ? \"/v1/auth/owner-config\" : \"/v1/auth/owner-pilot\",\n\t\t) !== null && path !== \"\"\n\t);\n}\nasync function dispatch(\n\trequest: Request,\n\tclientKey: string,\n\tcontext: HttpContext,\n): Promise<Response> {\n\tconst { api, scope, pin, callback } = context;\n\tconst path = new URL(request.url).pathname;\n\tif (path === context.pinPath) return json(pin);\n\tif (path === ATTEMPTS_PATH || path === `${ATTEMPTS_PATH}/finalize`)\n\t\treturn jsonAction(request, api, clientKey);\n\tif (path === START_PATH && request.method === \"GET\") return startPage(request, context);\n\tif (path === START_PATH) {\n\t\tconst result = await api.claimBrowser(request, clientKey);\n\t\treturn result.kind === \"browser_claimed\"\n\t\t\t? redirect(result.authorizationUrl, result.setCookies)\n\t\t\t: reject();\n\t}\n\tif (path === CONFIRM_PATH) return confirmBrowser(request, api, clientKey, scope.publicOrigin);\n\tif (path === callback) {\n\t\tconst result = await api.verifyCallback(request);\n\t\treturn result.kind === \"verified\" ? confirmationPage(result) : reject();\n\t}\n\treturn reject(404);\n}\n\ntype HttpContext = {\n\tapi: Enrollment;\n\tscope: BrowserCsrfScope;\n\tkey: BrowserCsrfKey;\n\tpin: BrowserCsrfScope[\"store\"] & { origin: string; issuer: string };\n\tcallback: string;\n\tpinPath: string;\n\tlimiter: InMemoryRequestRateLimiter;\n\ttransactionActivity(cookie: string | null): ReturnType<typeof readBrowserStartTransaction>;\n};\nexport function checkCoordinatorOwnerEnrollmentTransport(\n\trequest: Request,\n\tcontext: Pick<HttpContext, \"pin\" | \"callback\" | \"pinPath\">,\n): Response | null {\n\tconst url = new URL(request.url);\n\tif (\n\t\trequest.url.length > 8192 ||\n\t\turl.origin !== context.pin.origin ||\n\t\turl.username ||\n\t\turl.password ||\n\t\turl.hash\n\t)\n\t\treturn reject();\n\tconst methods = coordinatorOwnerEnrollmentHttpMethods(\n\t\turl.pathname,\n\t\tcontext.callback,\n\t\tcontext.pinPath,\n\t);\n\tif (!methods) return reject(404);\n\tif (!methods.split(\", \").includes(request.method)) return respond(null, 405, { Allow: methods });\n\tif (url.search && ![START_PATH, context.callback].includes(url.pathname)) return reject();\n\tif (request.method === \"POST\" && url.search) return reject();\n\tconst origin = request.headers.get(\"origin\");\n\tif (origin !== null && origin !== context.pin.origin) return reject();\n\treturn null;\n}\nasync function handleOwnerRequest(\n\trequest: Request,\n\ttrustedClientKey: string,\n\tcontext: HttpContext,\n): Promise<Response> {\n\ttry {\n\t\tconst error = checkCoordinatorOwnerEnrollmentTransport(request, context);\n\t\tif (error) return error;\n\t\tif (!isAuthControllerId(trustedClientKey) || trustedClientKey.length > 128) return reject();\n\t\tif (\n\t\t\t!checkBrowserAuthRequestRate(\n\t\t\t\trequest,\n\t\t\t\tcontext.limiter,\n\t\t\t\tJSON.stringify([\"owner-http\", context.pin.coordinatorId, trustedClientKey]),\n\t\t\t\t60,\n\t\t\t).allowed\n\t\t)\n\t\t\treturn reject(429);\n\t\treturn await dispatch(request, trustedClientKey, context);\n\t} catch {\n\t\treturn reject();\n\t}\n}\n\nfunction ownerComposition(\n\toptions: CoordinatorOwnerEnrollmentHttpOptions,\n\tcsrfKey: BrowserCsrfKey,\n\tlimiter: InMemoryRequestRateLimiter,\n\tmode: { production: boolean },\n) {\n\tif (mode.production) {\n\t\tif (options.mode !== \"production\") throw new Error(\"owner_enrollment_http_unavailable\");\n\t\treturn {\n\t\t\t...options,\n\t\t\tmode: \"production\" as const,\n\t\t\tpurpose: \"owner_enroll\" as const,\n\t\t\tcsrfKey,\n\t\t\tlimiter,\n\t\t};\n\t}\n\treturn {\n\t\t...options,\n\t\tmode: \"local_test\" as const,\n\t\tpurpose: \"owner_enroll\" as const,\n\t\tcsrfKey,\n\t\tlimiter,\n\t\tadmissionKey: undefined,\n\t};\n}\n\n/** Server supplies the trusted client key; no header or request body can override it. */\nexport async function createCoordinatorOwnerEnrollmentHttp(\n\toptions: CoordinatorOwnerEnrollmentHttpOptions,\n): Promise<CoordinatorOwnerEnrollmentHttp> {\n\tif (\n\t\toptions.mode !== undefined &&\n\t\toptions.mode !== \"private\" &&\n\t\toptions.mode !== \"local_test\" &&\n\t\toptions.mode !== \"production\"\n\t)\n\t\tthrow new Error(\"owner_enrollment_http_unavailable\");\n\tconst settings = captureCoordinatorBrowserAuthConfig(options.config);\n\tif (settings.kind !== \"enabled\") throw new Error(\"owner_enrollment_http_unavailable\");\n\tconst callback = new URL(settings.store.redirectUri).pathname;\n\tif (\n\t\tmatchesCoordinatorOwnerEnrollmentHttpPath(callback, \"private\") ||\n\t\tmatchesCoordinatorOwnerEnrollmentHttpPath(callback, \"production\")\n\t)\n\t\tthrow new Error(\"owner_enrollment_http_unavailable\");\n\tconst production = options.mode === \"production\";\n\tconst csrfKey = production\n\t\t? options.csrfKey\n\t\t: await importBrowserCsrfKey(globalThis.crypto.getRandomValues(new Uint8Array(32)));\n\tconst limiter = production\n\t\t? options.limiter\n\t\t: createInMemoryRequestRateLimiter({ now: options.clock });\n\tconst composition = ownerComposition(options, csrfKey, limiter, { production });\n\tconst created = await createCoordinatorOwnerEnrollment(composition);\n\tif (!created.ok) throw new Error(\"owner_enrollment_http_unavailable\");\n\tconst pin = Object.freeze({\n\t\tcoordinatorId: settings.store.coordinatorId,\n\t\torigin: settings.publicOrigin,\n\t\tissuer: settings.store.issuer,\n\t\trevision: settings.store.revision,\n\t});\n\tconst scope = { publicOrigin: pin.origin, store: settings.store };\n\tconst pinPath = production ? \"/v1/auth/owner-config\" : \"/v1/auth/owner-pilot\";\n\tconst transactions = new CoordinatorAuthBrowserTransactions(\n\t\tcomposition.backend,\n\t\tcomposition.clock,\n\t);\n\tconst context: HttpContext = {\n\t\tapi: created.enrollment,\n\t\tscope,\n\t\tkey: csrfKey,\n\t\tpin,\n\t\tcallback,\n\t\tpinPath,\n\t\tlimiter,\n\t\ttransactionActivity: (cookie) =>\n\t\t\treadBrowserStartTransaction(cookie, transactions, settings.store),\n\t};\n\treturn httpAdapter(context, { production });\n}\n\nfunction httpAdapter(\n\tcontext: HttpContext,\n\toptions: { production: boolean },\n): CoordinatorOwnerEnrollmentHttp {\n\tconst { pin, callback } = context;\n\tconst { production } = options;\n\treturn {\n\t\tpin,\n\t\tstartOwnerBound: (...args) => context.api.startOwnerBound(...args),\n\t\tmatchesPath: (path) =>\n\t\t\tmatchesCoordinatorOwnerEnrollmentHttpPath(path, production ? \"production\" : \"private\"),\n\t\thandle: (request: Request, trustedClientKey: string) =>\n\t\t\tproduction && new URL(request.url).pathname === callback\n\t\t\t\t? Promise.resolve(reject(404))\n\t\t\t\t: handleOwnerRequest(request, trustedClientKey, context),\n\t\thandleCallback: (request: Request, trustedClientKey: string) =>\n\t\t\tnew URL(request.url).pathname === callback\n\t\t\t\t? handleOwnerRequest(request, trustedClientKey, context)\n\t\t\t\t: Promise.resolve(reject(404)),\n\t};\n}\n","import type { OwnerEnrollmentStart } from \"./owner-enrollment-start.js\";\n\nexport const OWNER_ADMISSION_BODY_MAX_BYTES = 16 * 1024;\nconst START_FIELDS = [\n\t\"attemptId\",\n\t\"deviceId\",\n\t\"publicKey\",\n\t\"loopbackRedirect\",\n\t\"browserStartCode\",\n\t\"signature\",\n];\n\n/** Dedicated multipart limit. The ordinary browser forms stay at 4 KiB. */\nasync function readBytes(request: Request): Promise<Uint8Array<ArrayBuffer> | null> {\n\tconst declared = request.headers.get(\"content-length\");\n\tif (\n\t\tdeclared !== null &&\n\t\t(!/^[0-9]{1,10}$/.test(declared) || Number(declared) > OWNER_ADMISSION_BODY_MAX_BYTES)\n\t)\n\t\treturn null;\n\tif (!request.body) return null;\n\tconst reader = request.body.getReader();\n\tconst bytes = new Uint8Array(OWNER_ADMISSION_BODY_MAX_BYTES);\n\tlet size = 0;\n\ttry {\n\t\tfor (;;) {\n\t\t\tconst chunk = await reader.read();\n\t\t\tif (chunk.done) return bytes.subarray(0, size);\n\t\t\tif (!(chunk.value instanceof Uint8Array) || chunk.value.byteLength > bytes.length - size) {\n\t\t\t\tvoid reader.cancel().catch(() => {});\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tbytes.set(chunk.value, size);\n\t\t\tsize += chunk.value.byteLength;\n\t\t}\n\t} catch {\n\t\tvoid reader.cancel().catch(() => {});\n\t\treturn null;\n\t} finally {\n\t\treader.releaseLock();\n\t}\n}\n\n/** The file format is deliberately only two object levels with string leaves.\n * Validate that grammar before JSON.parse so duplicate keys (including escaped aliases)\n * cannot disappear during parsing. No general JSON parser or permissive normalization.\n */\nfunction parseStart(raw: string): OwnerEnrollmentStart | null {\n\tconst string = '\"(?:[^\"\\\\\\\\\\u0000-\\u001f]|\\\\\\\\(?:[\"\\\\\\\\/bfnrt]|u[0-9a-fA-F]{4}))*\"';\n\tconst pair = `${string}\\\\s*:\\\\s*${string}`;\n\tif (\n\t\t!new RegExp(\n\t\t\t`^\\\\s*\\\\{\\\\s*\"start\"\\\\s*:\\\\s*\\\\{\\\\s*${pair}(?:\\\\s*,\\\\s*${pair})*\\\\s*\\\\}\\\\s*\\\\}\\\\s*$`,\n\t\t).test(raw)\n\t)\n\t\treturn null;\n\tconst fields = new Set<string>();\n\tfor (const match of raw.matchAll(new RegExp(`(${string})\\\\s*:\\\\s*${string}`, \"g\"))) {\n\t\tconst name: unknown = JSON.parse(match[1] ?? \"null\");\n\t\tif (typeof name !== \"string\" || !START_FIELDS.includes(name) || fields.has(name)) return null;\n\t\tfields.add(name);\n\t}\n\tif (fields.size !== START_FIELDS.length) return null;\n\treturn Object.freeze((JSON.parse(raw) as { start: OwnerEnrollmentStart }).start);\n}\n\n/** Read the entire bounded body BEFORE invoking the runtime multipart parser. */\nexport async function readOwnerAdmissionUpload(\n\trequest: Request,\n): Promise<{ csrf: string; start: OwnerEnrollmentStart } | null> {\n\ttry {\n\t\tconst contentType = request.headers.get(\"content-type\") ?? \"\";\n\t\tif (contentType.length > 256 || !/^multipart\\/form-data\\s*;/i.test(contentType)) return null;\n\t\tconst bytes = await readBytes(request);\n\t\tif (!bytes) return null;\n\t\tconst form = await new Request(request.url, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: { \"Content-Type\": contentType },\n\t\t\tbody: bytes,\n\t\t}).formData();\n\t\tconst entries = [...form.entries()];\n\t\tif (\n\t\t\tentries.length !== 2 ||\n\t\t\tform.getAll(\"csrf\").length !== 1 ||\n\t\t\tform.getAll(\"request\").length !== 1\n\t\t)\n\t\t\treturn null;\n\t\tconst csrf = form.get(\"csrf\");\n\t\tconst file = form.get(\"request\");\n\t\tif (typeof csrf !== \"string\" || !(file instanceof File)) return null;\n\t\tconst start = parseStart(\n\t\t\tnew TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: true }).decode(await file.arrayBuffer()),\n\t\t);\n\t\treturn start ? { csrf, start } : null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n","import { CoordinatorAuthBrowserTransactions } from \"./coordinator-auth-browser-transaction.js\";\nimport { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport type { AuthLinkBackend } from \"./coordinator-auth-link.js\";\nimport { authLinkNow } from \"./coordinator-auth-link.js\";\nimport type { CoordinatorAuthSessionStore } from \"./coordinator-auth-session-contract.js\";\nimport { captureCoordinatorBrowserAuthConfig } from \"./coordinator-browser-auth-config.js\";\nimport {\n\ttype BrowserCookieReadResult,\n\treadBrowserCookie,\n} from \"./coordinator-browser-credential.js\";\nimport {\n\ttype BrowserCsrfKey,\n\tisBrowserCsrfKey,\n\tissueBrowserCsrfToken,\n\tverifyBrowserCsrfToken,\n} from \"./coordinator-browser-csrf.js\";\nimport { readBrowserStartTransaction } from \"./coordinator-browser-start-transaction.js\";\nimport { renderOwnerEnrollmentStartForm } from \"./coordinator-owner-enrollment-http.js\";\nimport {\n\townerAdmissionSchemaReady,\n\treadOwnerAdmissionAuthority,\n} from \"./owner-browser-admission-authority.js\";\nimport { readOwnerAdmissionUpload } from \"./owner-browser-admission-body.js\";\nimport {\n\tisOwnerEnrollmentAdmissionKey,\n\tissueOwnerEnrollmentAdmissionV2,\n\ttype OwnerEnrollmentAdmissionKey,\n\ttype OwnerEnrollmentResolvedOwner,\n} from \"./owner-enrollment-admission.js\";\nimport {\n\ttype createCoordinatorOwnerEnrollment,\n\townerEnrollmentHash,\n} from \"./owner-enrollment-start.js\";\nimport type { InMemoryRequestRateLimiter } from \"./request-rate-limit.js\";\n\nexport const OWNER_BROWSER_ADMISSION_PATH = \"/auth/owner/admit\";\ntype Enrollment = Extract<\n\tAwaited<ReturnType<typeof createCoordinatorOwnerEnrollment>>,\n\t{ ok: true }\n>[\"enrollment\"];\nexport interface OwnerBrowserAdmissionOptions {\n\t/** Explicit owner opt-in, independent of management sign-in being enabled. */\n\tenabled: boolean;\n\tconfig: unknown;\n\tbackend: AuthLinkBackend;\n\treadSession: CoordinatorAuthSessionStore[\"readAuthSession\"];\n\tcsrfKey: BrowserCsrfKey;\n\tadmissionKey: OwnerEnrollmentAdmissionKey;\n\tlimiter: InMemoryRequestRateLimiter;\n\tclock?: () => number;\n\t/** Lazy production owner composition. No OIDC discovery may run during setup. */\n\tgetEnrollment(): Promise<Pick<Enrollment, \"startOwnerBound\">>;\n}\n\nfunction response(body: string, status = 400, cookies: string[] = []): Response {\n\tconst headers = new Headers({\n\t\t\"Content-Type\": \"text/html; charset=utf-8\",\n\t\t\"Cache-Control\": \"no-store\",\n\t\t\"Referrer-Policy\": \"no-referrer\",\n\t\t\"X-Content-Type-Options\": \"nosniff\",\n\t\t\"Content-Security-Policy\":\n\t\t\t\"default-src 'none'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'\",\n\t});\n\tfor (const cookie of cookies) headers.append(\"Set-Cookie\", cookie);\n\treturn new Response(body, { status, headers });\n}\nfunction denied(status = 400) {\n\treturn response(\n\t\t'Owner admission unavailable. Sign in at <a href=\"/auth/sign-in\">Sign in</a> and prepare a new device request on this computer.',\n\t\tstatus,\n\t);\n}\nfunction escapeHtml(value: string): string {\n\treturn value.replace(\n\t\t/[&<>\"']/g,\n\t\t(c) => ({ \"&\": \"&amp;\", \"<\": \"&lt;\", \">\": \"&gt;\", '\"': \"&quot;\", \"'\": \"&#39;\" })[c] ?? \"\",\n\t);\n}\nfunction uploadPage(csrf: string): Response {\n\treturn response(\n\t\t`<!doctype html><html lang=\"en\"><meta charset=\"utf-8\"><title>Authorize device request</title><body>\n<h1>Authorize device request</h1>\n<p>Upload the private capability-request.json created on this computer. Do not upload a request sent by someone else: its signature proves possession of a key, not that the key belongs to this computer.</p>\n<p>Read your local device review first. Compare the device ID and key fingerprint shown in the next step before choosing an account. This authorizes a request; it does not finish enrollment. A fresh account check and device confirmation still follow.</p>\n<form method=\"post\" action=\"${OWNER_BROWSER_ADMISSION_PATH}\" enctype=\"multipart/form-data\">\n<input type=\"hidden\" name=\"csrf\" value=\"${escapeHtml(csrf)}\">\n<label>Private device request <input type=\"file\" name=\"request\" accept=\"application/json,.json\" required></label>\n<button type=\"submit\">Authorize device request</button></form></body></html>`,\n\t\t200,\n\t);\n}\nfunction transportValid(request: Request, origin: string): boolean {\n\tconst url = new URL(request.url);\n\tconst source = request.headers.get(\"origin\");\n\treturn (\n\t\trequest.url.length <= 8192 &&\n\t\turl.origin === origin &&\n\t\t!url.username &&\n\t\t!url.password &&\n\t\t!url.search &&\n\t\t!url.hash &&\n\t\t(source === null || source === origin) &&\n\t\t(request.method !== \"POST\" || source === origin)\n\t);\n}\n\n/** Caller must reserve this path and dispatch BEFORE browser/OIDC setup.\n * No capability is returned to the browser. Session authority admits only a new exact start;\n * it never replaces the later fresh owner-purpose OIDC proof or pending-key finalization.\n */\nexport function createOwnerBrowserAdmissionHandler(options: OwnerBrowserAdmissionOptions) {\n\tconst settings = captureCoordinatorBrowserAuthConfig(options.config);\n\tif (\n\t\tsettings.kind === \"enabled\" &&\n\t\tnew URL(settings.store.redirectUri).pathname === OWNER_BROWSER_ADMISSION_PATH\n\t)\n\t\tthrow new Error(\"owner_admission_callback_collision\");\n\tconst enabled =\n\t\toptions.enabled &&\n\t\tsettings.kind === \"enabled\" &&\n\t\tisBrowserCsrfKey(options.csrfKey) &&\n\t\tisOwnerEnrollmentAdmissionKey(options.admissionKey);\n\treturn async (request: Request, trustedClientKey: string): Promise<Response | null> => {\n\t\tif (new URL(request.url).pathname !== OWNER_BROWSER_ADMISSION_PATH) return null;\n\t\tif (!enabled || settings.kind !== \"enabled\") return denied(404);\n\t\ttry {\n\t\t\tconst rejection = checkTransport(request, trustedClientKey, options, settings);\n\t\t\tif (rejection) return rejection;\n\t\t\treturn await handle(request, trustedClientKey, options, settings);\n\t\t} catch {\n\t\t\treturn denied();\n\t\t}\n\t};\n}\ntype Settings = Extract<\n\tReturnType<typeof captureCoordinatorBrowserAuthConfig>,\n\t{ kind: \"enabled\" }\n>;\nfunction checkTransport(\n\trequest: Request,\n\tclientKey: string,\n\toptions: OwnerBrowserAdmissionOptions,\n\tsettings: Settings,\n): Response | null {\n\tif (!transportValid(request, settings.publicOrigin)) return denied();\n\tif (request.method !== \"GET\" && request.method !== \"POST\") return denied(405);\n\tif (!isAuthControllerId(clientKey) || clientKey.length > 128) return denied();\n\tif (\n\t\t!options.limiter.check(\n\t\t\tJSON.stringify([\"owner-admit-client\", settings.store.coordinatorId, clientKey]),\n\t\t\t20,\n\t\t).allowed\n\t)\n\t\treturn denied(429);\n\treturn null;\n}\nasync function availableTransaction(\n\trequest: Request,\n\tbackend: AuthLinkBackend,\n\tsettings: Settings,\n\tnow: () => number,\n) {\n\tconst transactions = new CoordinatorAuthBrowserTransactions(backend, now);\n\tconst activity = (header: string | null) =>\n\t\treadBrowserStartTransaction(header, transactions, settings.store);\n\tconst transaction = await activity(request.headers.get(\"cookie\"));\n\tif (transaction === \"active\" || transaction === \"invalid\") return null;\n\tconst startCookie = await readBrowserCookie(request.headers.get(\"cookie\"), \"start\");\n\treturn startCookie.kind === \"invalid\" ? null : activity;\n}\nasync function handle(\n\trequest: Request,\n\tclientKey: string,\n\toptions: OwnerBrowserAdmissionOptions,\n\tsettings: Settings,\n): Promise<Response> {\n\tconst { backend, csrfKey } = options;\n\tif (!(await ownerAdmissionSchemaReady(backend))) return denied();\n\tconst cookie = await readBrowserCookie(request.headers.get(\"cookie\"), \"session\");\n\tif (cookie.kind !== \"present\") return denied(403);\n\tconst session = await options.readSession(cookie.cookieHash, settings.store);\n\tif (!session) return denied(403);\n\tconst now = () => authLinkNow(options.clock ?? Date.now);\n\tconst base = { backend, config: settings.store, sessionCookieHash: cookie.cookieHash };\n\t// GET has no pending key yet. This checks trusted grants and orphan exclusions;\n\t// POST repeats the same predicate with the exact signed device and canonical key.\n\tconst owner = await readOwnerAdmissionAuthority({\n\t\t...base,\n\t\ttime: now(),\n\t\tdeviceId: \"\",\n\t\tfingerprint: \"\",\n\t});\n\tif (\n\t\t!owner ||\n\t\towner.identityId !== session.identityId ||\n\t\towner.linkId !== session.linkId ||\n\t\towner.issuer !== session.account.issuer ||\n\t\towner.subject !== session.account.subject\n\t)\n\t\treturn denied(403);\n\tif (\n\t\t!options.limiter.check(\n\t\t\tJSON.stringify([\"owner-admit-identity\", owner.coordinatorId, owner.identityId]),\n\t\t\t10,\n\t\t).allowed\n\t)\n\t\treturn denied(429);\n\tconst scope = { publicOrigin: settings.publicOrigin, store: settings.store };\n\tconst transactionActivity = await availableTransaction(request, backend, settings, now);\n\tif (!transactionActivity) return denied();\n\tif (request.method === \"GET\")\n\t\treturn uploadPage(await issueBrowserCsrfToken(csrfKey, cookie.secret, \"session\", scope));\n\treturn submitUpload(request, clientKey, options, settings, {\n\t\tcookie,\n\t\towner,\n\t\ttransactionActivity,\n\t\tnow,\n\t});\n}\ninterface UploadContext {\n\tcookie: Extract<BrowserCookieReadResult, { kind: \"present\" }>;\n\towner: OwnerEnrollmentResolvedOwner;\n\ttransactionActivity: NonNullable<Awaited<ReturnType<typeof availableTransaction>>>;\n\tnow: () => number;\n}\nasync function submitUpload(\n\trequest: Request,\n\tclientKey: string,\n\toptions: OwnerBrowserAdmissionOptions,\n\tsettings: Settings,\n\tcontext: UploadContext,\n): Promise<Response> {\n\tconst { cookie, owner, transactionActivity, now } = context;\n\tconst { backend, csrfKey, admissionKey } = options;\n\tconst scope = { publicOrigin: settings.publicOrigin, store: settings.store };\n\tconst upload = await readOwnerAdmissionUpload(request);\n\tif (\n\t\t!upload ||\n\t\t!(await verifyBrowserCsrfToken(csrfKey, cookie.secret, \"session\", scope, upload.csrf))\n\t)\n\t\treturn denied();\n\tconst { start } = upload;\n\tconst fingerprint = await ownerEnrollmentHash(start.publicKey);\n\tconst current = await readOwnerAdmissionAuthority({\n\t\tbackend,\n\t\tconfig: settings.store,\n\t\tsessionCookieHash: cookie.cookieHash,\n\t\ttime: now(),\n\t\tdeviceId: start.deviceId,\n\t\tfingerprint,\n\t});\n\tif (!current || JSON.stringify(current) !== JSON.stringify(owner)) return denied(403);\n\tconst pin = {\n\t\tcoordinatorId: settings.store.coordinatorId,\n\t\torigin: settings.publicOrigin,\n\t\tissuer: settings.store.issuer,\n\t\trevision: settings.store.revision,\n\t};\n\tconst admissionToken = await issueOwnerEnrollmentAdmissionV2(admissionKey, pin, start, {\n\t\tresolvedOwner: current,\n\t\tnowMs: now(),\n\t\tttlMs: 60_000,\n\t});\n\tconst enrollment = await options.getEnrollment();\n\tconst result = await enrollment.startOwnerBound(start, clientKey, {\n\t\tadmissionToken,\n\t\tresolvedOwner: current,\n\t\tsessionCookieHash: cookie.cookieHash,\n\t});\n\tif (result.kind !== \"started\") return denied();\n\treturn renderOwnerEnrollmentStartForm(\n\t\trequest,\n\t\t{ scope, key: csrfKey, transactionActivity },\n\t\t{\n\t\t\tattemptId: start.attemptId,\n\t\t\tstartCode: start.browserStartCode,\n\t\t\tdeviceId: start.deviceId,\n\t\t\tfingerprint,\n\t\t},\n\t);\n}\n","import type { Context, Hono } from \"hono\";\nimport type { AccountChangeOperations } from \"./coordinator-account-change.js\";\nimport {\n\tACCOUNT_CHANGE_BROWSER_PATHS,\n\tcreateCoordinatorAccountChangeBrowser,\n} from \"./coordinator-account-change-browser.js\";\nimport type {\n\tCoordinatorAuthBrowserConfig,\n\tCoordinatorAuthBrowserTransactionPurposeStore,\n\tCoordinatorAuthBrowserTransactionStore,\n} from \"./coordinator-auth-browser-transaction-contract.js\";\nimport { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport type { AuthLinkBackend } from \"./coordinator-auth-link.js\";\nimport type { CoordinatorAuthLinkStore } from \"./coordinator-auth-link-contract.js\";\nimport {\n\tAUTH_SCHEMA_UPGRADE_REQUIRED,\n\tassertConfiguredAuthSchema,\n\ttype CoordinatorAuthSchemaStore,\n\tCoordinatorAuthSchemaUpgradeRequiredError,\n} from \"./coordinator-auth-schema.js\";\nimport type { CoordinatorAuthSessionStore } from \"./coordinator-auth-session-contract.js\";\nimport {\n\ttype CoordinatorBrowserAccountInput,\n\tcreateCoordinatorBrowserAccount,\n} from \"./coordinator-browser-account.js\";\nimport {\n\ttype CoordinatorBrowserAuthCallbackInput,\n\tcreateCoordinatorBrowserAuthCallback,\n} from \"./coordinator-browser-auth-callback.js\";\nimport {\n\ttype CoordinatorBrowserAuthConfig,\n\ttype CoordinatorBrowserAuthConfigField,\n\ttype CoordinatorBrowserAuthSettings,\n\tcaptureCoordinatorBrowserAuthConfig,\n} from \"./coordinator-browser-auth-config.js\";\nimport { type BrowserCsrfKey, isBrowserCsrfKey } from \"./coordinator-browser-csrf.js\";\nimport {\n\tadmitBrowserFormSetup,\n\tcheckBrowserAuthRequestRate,\n} from \"./coordinator-browser-form-guard.js\";\nimport {\n\ttype CoordinatorBrowserLinkInput,\n\tcreateCoordinatorBrowserLinkHandlers,\n} from \"./coordinator-browser-link.js\";\nimport {\n\ttype CoordinatorBrowserLinkCompletionInput,\n\tcreateCoordinatorBrowserLinkCompletionHandlers,\n} from \"./coordinator-browser-link-completion.js\";\nimport {\n\ttype CoordinatorBrowserLinkStartInput,\n\tcreateCoordinatorBrowserLinkStart,\n} from \"./coordinator-browser-link-start.js\";\nimport {\n\ttype CoordinatorBrowserSigninStartInput,\n\tcreateCoordinatorBrowserSigninStart,\n} from \"./coordinator-browser-signin-start.js\";\nimport { createDeviceRebindBrowser } from \"./coordinator-device-rebind-browser.js\";\nimport { DEVICE_REBIND_BROWSER_PATHS } from \"./coordinator-device-rebind-view.js\";\nimport type { CoordinatorOidcOptions } from \"./coordinator-oidc.js\";\nimport {\n\tcheckCoordinatorOwnerEnrollmentTransport,\n\tcoordinatorOwnerEnrollmentHttpMethods,\n} from \"./coordinator-owner-enrollment-http.js\";\nimport { OWNER_BROWSER_ADMISSION_PATH } from \"./owner-browser-admission.js\";\nimport type { InMemoryRequestRateLimiter } from \"./request-rate-limit.js\";\n\nexport interface CoordinatorBrowserAuthOptions {\n\tconfig: unknown;\n\tcsrfKey?: BrowserCsrfKey;\n\toidcOptions?: CoordinatorOidcOptions;\n\townerEnrollment?: CoordinatorBrowserOwnerEnrollmentFactory;\n}\nexport interface CoordinatorBrowserOwnerEnrollmentAdapter {\n\thandle(request: Request, trustedClientKey: string): Promise<Response | null>;\n\thandleCallback(request: Request, trustedClientKey: string): Promise<Response>;\n}\nexport type CoordinatorBrowserOwnerEnrollmentFactory = (\n\tinput: Readonly<{\n\t\tconfig: Readonly<CoordinatorBrowserAuthConfig>;\n\t\tcsrfKey: BrowserCsrfKey;\n\t\toidcOptions: Readonly<CoordinatorOidcOptions>;\n\t\tlimiter: InMemoryRequestRateLimiter;\n\t}>,\n) => Promise<CoordinatorBrowserOwnerEnrollmentAdapter>;\ntype EnabledSettings = Extract<CoordinatorBrowserAuthSettings, { kind: \"enabled\" }>;\nexport type CoordinatorBrowserAuthSnapshot =\n\t| Readonly<{ kind: \"disabled\" }>\n\t| Readonly<{\n\t\t\tkind: \"invalid\";\n\t\t\terror: \"browser_auth_config_invalid\";\n\t\t\tfield: CoordinatorBrowserAuthConfigField | \"csrfKey\" | \"oidcOptions\" | \"ownerEnrollment\";\n\t }>\n\t| Readonly<{ kind: \"enabled\" }>;\ntype EnabledPayload = Readonly<{\n\tsettings: EnabledSettings;\n\tconfig: Readonly<CoordinatorBrowserAuthConfig>;\n\tcsrfKey: BrowserCsrfKey;\n\toidcOptions: Readonly<CoordinatorOidcOptions>;\n\tcallbackPath: string;\n\townerEnrollment?: CoordinatorBrowserOwnerEnrollmentFactory;\n}>;\nconst enabledPayloads = new WeakMap<object, EnabledPayload>();\nconst disabledMaintenancePins = new WeakMap<object, string>();\nexport type CoordinatorBrowserAuthStore = CoordinatorBrowserAccountInput[\"store\"] &\n\tCoordinatorBrowserAuthCallbackInput[\"store\"] &\n\tCoordinatorBrowserLinkInput[\"store\"] &\n\tCoordinatorBrowserLinkCompletionInput[\"store\"] &\n\tCoordinatorBrowserLinkStartInput[\"store\"] &\n\tCoordinatorBrowserSigninStartInput[\"store\"] &\n\tPartial<CoordinatorAuthBrowserTransactionPurposeStore & CoordinatorAuthSchemaStore>;\nexport type CoordinatorBrowserAuthClientKey = (context: Context) => string | null;\nexport interface CoordinatorBrowserAuth {\n\treadonly storeConfig: Readonly<CoordinatorAuthBrowserConfig>;\n\treadonly resolveAccountChanges?: typeof resolveAccountChanges;\n\tregister(app: Hono, clientKey: CoordinatorBrowserAuthClientKey): void;\n}\nexport type CoordinatorBrowserAuthResult =\n\t| Readonly<{ ok: true; auth: CoordinatorBrowserAuth }>\n\t| Readonly<{\n\t\t\tok: false;\n\t\t\terror:\n\t\t\t\t| \"browser_auth_disabled\"\n\t\t\t\t| \"browser_auth_config_invalid\"\n\t\t\t\t| \"browser_auth_setup_failed\"\n\t\t\t\t| \"browser_auth_store_unavailable\"\n\t\t\t\t| typeof AUTH_SCHEMA_UPGRADE_REQUIRED;\n\t }>;\n\nconst FIXED_PATHS: Readonly<Record<string, readonly string[]>> = {\n\t\"/auth/sign-in\": [\"GET\", \"POST\"],\n\t\"/auth/link/start\": [\"GET\", \"POST\"],\n\t\"/auth/link/confirm\": [\"POST\"],\n\t\"/auth/link/cancel\": [\"POST\"],\n\t\"/auth/link/complete\": [\"GET\", \"POST\"],\n\t\"/auth/account\": [\"GET\"],\n\t\"/auth/logout\": [\"POST\"],\n\t\"/auth/owner/start\": [\"GET\", \"POST\"],\n\t\"/auth/owner/confirm\": [\"POST\"],\n\t\"/auth/account/change/start\": [\"GET\", \"POST\"],\n\t\"/auth/account/change/confirm\": [\"POST\"],\n\t[DEVICE_REBIND_BROWSER_PATHS.start]: [\"GET\", \"POST\"],\n\t[DEVICE_REBIND_BROWSER_PATHS.confirm]: [\"POST\"],\n};\nconst OWNER_PATHS = [\n\t\"/auth/owner/start\",\n\t\"/auth/owner/confirm\",\n\t\"/v1/auth/owner-config\",\n\t\"/v1/auth/owner-attempts\",\n\t\"/v1/auth/owner-attempts/finalize\",\n];\nfunction ownData(value: unknown, name: string): unknown {\n\tif (value === null || typeof value !== \"object\" || Array.isArray(value)) throw new Error();\n\tconst descriptor = Object.getOwnPropertyDescriptor(value, name);\n\tif (descriptor && !Object.hasOwn(descriptor, \"value\")) throw new Error();\n\treturn descriptor?.value;\n}\nfunction invalid(\n\tfield: Extract<CoordinatorBrowserAuthSnapshot, { kind: \"invalid\" }>[\"field\"],\n): CoordinatorBrowserAuthSnapshot {\n\treturn Object.freeze({ kind: \"invalid\", error: \"browser_auth_config_invalid\", field });\n}\nfunction captureOidcOptions(value: unknown): Readonly<CoordinatorOidcOptions> {\n\tif (value === undefined) return Object.freeze({});\n\tconst fetch = ownData(value, \"fetch\");\n\tconst timeoutSeconds = ownData(value, \"timeoutSeconds\");\n\tif (fetch !== undefined && typeof fetch !== \"function\") throw new Error();\n\tif (\n\t\ttimeoutSeconds !== undefined &&\n\t\t(typeof timeoutSeconds !== \"number\" ||\n\t\t\t!Number.isFinite(timeoutSeconds) ||\n\t\t\ttimeoutSeconds < 1 ||\n\t\t\ttimeoutSeconds > 30)\n\t)\n\t\tthrow new Error();\n\treturn Object.freeze({\n\t\tfetch: fetch as CoordinatorOidcOptions[\"fetch\"],\n\t\ttimeoutSeconds: timeoutSeconds as number | undefined,\n\t});\n}\n/** Capture secrets and transport references before any discovery awaits. */\nexport function captureCoordinatorBrowserAuthOptions(\n\tinput: CoordinatorBrowserAuthOptions,\n): CoordinatorBrowserAuthSnapshot {\n\ttry {\n\t\tconst configInput = ownData(input, \"config\");\n\t\tconst settings = captureCoordinatorBrowserAuthConfig(configInput);\n\t\tif (settings.kind === \"disabled\") {\n\t\t\tconst snapshot = Object.freeze({ kind: \"disabled\" as const });\n\t\t\tconst coordinatorId =\n\t\t\t\tconfigInput === undefined ? undefined : ownData(configInput, \"coordinatorId\");\n\t\t\tif (isAuthControllerId(coordinatorId)) disabledMaintenancePins.set(snapshot, coordinatorId);\n\t\t\treturn snapshot;\n\t\t}\n\t\tif (settings.kind === \"invalid\") return invalid(settings.field);\n\t\tconst callbackPath = new URL(settings.store.redirectUri).pathname;\n\t\tif (\n\t\t\t!/^\\/auth\\/[A-Za-z0-9._~/-]+$/.test(callbackPath) ||\n\t\t\tcallbackPath === OWNER_BROWSER_ADMISSION_PATH ||\n\t\t\tObject.hasOwn(FIXED_PATHS, callbackPath)\n\t\t)\n\t\t\treturn invalid(\"redirectUri\");\n\t\tlet csrfKey: unknown;\n\t\ttry {\n\t\t\tcsrfKey = ownData(input, \"csrfKey\");\n\t\t} catch {\n\t\t\treturn invalid(\"csrfKey\");\n\t\t}\n\t\tif (!isBrowserCsrfKey(csrfKey)) return invalid(\"csrfKey\");\n\t\tlet oidcOptions: Readonly<CoordinatorOidcOptions>;\n\t\ttry {\n\t\t\toidcOptions = captureOidcOptions(ownData(input, \"oidcOptions\"));\n\t\t} catch {\n\t\t\treturn invalid(\"oidcOptions\");\n\t\t}\n\t\tconst config = Object.freeze({\n\t\t\t...settings.store,\n\t\t\tclientId: settings.oidc.clientId,\n\t\t\tclientSecret: settings.oidc.clientSecret,\n\t\t});\n\t\tconst ownerEnrollment = ownData(input, \"ownerEnrollment\");\n\t\tif (ownerEnrollment !== undefined && typeof ownerEnrollment !== \"function\")\n\t\t\treturn invalid(\"ownerEnrollment\");\n\t\tconst handle = Object.freeze({ kind: \"enabled\" as const });\n\t\tenabledPayloads.set(\n\t\t\thandle,\n\t\t\tObject.freeze({\n\t\t\t\tsettings,\n\t\t\t\tconfig,\n\t\t\t\tcsrfKey,\n\t\t\t\toidcOptions,\n\t\t\t\tcallbackPath,\n\t\t\t\townerEnrollment: ownerEnrollment as CoordinatorBrowserOwnerEnrollmentFactory | undefined,\n\t\t\t}),\n\t\t);\n\t\treturn handle;\n\t} catch {\n\t\treturn invalid(\"config\");\n\t}\n}\n\n/** Device routes need the pinned store config, not Google discovery or browser handlers. */\nexport function coordinatorBrowserAuthDeviceRoutes(\n\tsnapshot: CoordinatorBrowserAuthSnapshot,\n): CoordinatorBrowserAuth | undefined {\n\tconst payload = enabledPayloads.get(snapshot);\n\tif (!payload) return undefined;\n\treturn { storeConfig: payload.settings.store, resolveAccountChanges, register: () => {} };\n}\n\n/** null skips setup; a Response rejects before I/O; true admits the actual mounted route. */\nexport function admitCoordinatorBrowserAuthSetup(\n\tsnapshot: CoordinatorBrowserAuthSnapshot,\n\trequest: Request,\n\tlimiter: InMemoryRequestRateLimiter,\n\tclientKey: string,\n): true | Response | null {\n\tconst payload = enabledPayloads.get(snapshot);\n\tif (!payload) return null;\n\tconst url = new URL(request.url);\n\tconst ownerMethods =\n\t\tpayload.ownerEnrollment && url.pathname !== payload.callbackPath\n\t\t\t? coordinatorOwnerEnrollmentHttpMethods(\n\t\t\t\t\turl.pathname,\n\t\t\t\t\tpayload.callbackPath,\n\t\t\t\t\t\"/v1/auth/owner-config\",\n\t\t\t\t)\n\t\t\t: null;\n\tlet methods = FIXED_PATHS[url.pathname];\n\tif (OWNER_PATHS.includes(url.pathname)) methods = ownerMethods?.split(\", \") ?? [];\n\tif (url.pathname === payload.callbackPath) methods = [\"GET\"];\n\tif (!methods?.length) return null;\n\tif (!methods.includes(request.method))\n\t\treturn new Response(\"Method not allowed.\", {\n\t\t\tstatus: 405,\n\t\t\theaders: { Allow: methods.join(\", \") },\n\t\t});\n\tif (url.origin !== payload.settings.publicOrigin)\n\t\treturn new Response(\"Not found.\", { status: 404 });\n\tif (ownerMethods) return admitOwnerSetup(payload, request, limiter, clientKey);\n\treturn admitFormSetup(payload, request, limiter, clientKey);\n}\n\nfunction admitOwnerSetup(\n\tpayload: EnabledPayload,\n\trequest: Request,\n\tlimiter: InMemoryRequestRateLimiter,\n\tclientKey: string,\n): true | Response {\n\tconst transportError = checkCoordinatorOwnerEnrollmentTransport(request, {\n\t\tpin: {\n\t\t\tcoordinatorId: payload.config.coordinatorId,\n\t\t\trevision: payload.config.revision,\n\t\t\tissuer: payload.config.issuer,\n\t\t\torigin: payload.settings.publicOrigin,\n\t\t},\n\t\tcallback: payload.callbackPath,\n\t\tpinPath: \"/v1/auth/owner-config\",\n\t});\n\tif (transportError) return transportError;\n\tif (!isAuthControllerId(clientKey) || clientKey.length > 128)\n\t\treturn new Response(\"Invalid request.\", { status: 400 });\n\tconst rate = checkBrowserAuthRequestRate(\n\t\trequest,\n\t\tlimiter,\n\t\tJSON.stringify([\"owner-http\", payload.config.coordinatorId, clientKey]),\n\t\t60,\n\t\t{ admitSetup: true },\n\t);\n\tif (!rate.allowed)\n\t\treturn new Response(\"Too many requests.\", {\n\t\t\tstatus: 429,\n\t\t\theaders: { \"Retry-After\": String(rate.retryAfterS) },\n\t\t});\n\treturn true;\n}\n\nfunction admitFormSetup(\n\tpayload: EnabledPayload,\n\trequest: Request,\n\tlimiter: InMemoryRequestRateLimiter,\n\tclientKey: string,\n): true | Response {\n\tif (request.method !== \"POST\") return true;\n\tconst url = new URL(request.url);\n\tlet action: \"session_logout\" | \"signin_start\" | \"link_start\" | \"transaction_attempt\" =\n\t\t\"transaction_attempt\";\n\tif (url.pathname === \"/auth/logout\") action = \"session_logout\";\n\tif (url.pathname === \"/auth/sign-in\") action = \"signin_start\";\n\tif (url.pathname === \"/auth/link/start\") action = \"link_start\";\n\tif (url.pathname === ACCOUNT_CHANGE_BROWSER_PATHS.start) action = \"link_start\";\n\tif (url.pathname === DEVICE_REBIND_BROWSER_PATHS.start) action = \"link_start\";\n\tconst failure = admitBrowserFormSetup({\n\t\trequest,\n\t\tscope: payload.settings,\n\t\tcsrfKey: payload.csrfKey,\n\t\taction,\n\t\tlimiter,\n\t\tclientKey,\n\t});\n\tif (!failure) return true;\n\tlet status = 503;\n\tif (failure.error === \"rate_limited\") status = 429;\n\tif (failure.error === \"origin_rejected\") status = 403;\n\treturn new Response(\"Authentication request rejected.\", {\n\t\tstatus,\n\t\theaders: {\n\t\t\t\"Cache-Control\": \"no-store\",\n\t\t\t\"Referrer-Policy\": \"no-referrer\",\n\t\t\t\"X-Content-Type-Options\": \"nosniff\",\n\t\t\t...(failure.retryAfterS ? { \"Retry-After\": String(failure.retryAfterS) } : {}),\n\t\t},\n\t});\n}\n\nexport function coordinatorBrowserAuthUnavailableResponse(): Response {\n\treturn new Response(\"Authentication unavailable. Try again.\", {\n\t\tstatus: 503,\n\t\theaders: {\n\t\t\t\"Content-Type\": \"text/plain;charset=utf-8\",\n\t\t\t\"Cache-Control\": \"no-store\",\n\t\t\t\"Referrer-Policy\": \"no-referrer\",\n\t\t\t\"X-Content-Type-Options\": \"nosniff\",\n\t\t},\n\t});\n}\ntype BrowserHandler = (\n\trequest: Request,\n\tclientKey: string,\n) => Promise<Readonly<{ response: Response }>>;\ntype Route = Readonly<{ path: string; get?: BrowserHandler; post?: BrowserHandler }>;\nfunction registerRoutes(\n\tapp: Hono,\n\troutes: readonly Route[],\n\tclientKey: CoordinatorBrowserAuthClientKey,\n): void {\n\tfor (const route of routes) {\n\t\tapp.all(route.path, async (context) => {\n\t\t\ttry {\n\t\t\t\tconst request = context.req.raw;\n\t\t\t\tlet handler: BrowserHandler | undefined;\n\t\t\t\tif (request.method === \"GET\") handler = route.get;\n\t\t\t\tif (request.method === \"POST\") handler = route.post;\n\t\t\t\tif (!handler)\n\t\t\t\t\treturn new Response(\"Method not allowed.\", {\n\t\t\t\t\t\tstatus: 405,\n\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\tAllow: [route.get && \"GET\", route.post && \"POST\"].filter(Boolean).join(\", \"),\n\t\t\t\t\t\t\t\"Cache-Control\": \"no-store\",\n\t\t\t\t\t\t\t\"Referrer-Policy\": \"no-referrer\",\n\t\t\t\t\t\t\t\"X-Content-Type-Options\": \"nosniff\",\n\t\t\t\t\t\t\t\"Content-Type\": \"text/plain;charset=utf-8\",\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\t\t\t\treturn (await handler(request, clientKey(context) ?? \"\")).response;\n\t\t\t} catch {\n\t\t\t\treturn coordinatorBrowserAuthUnavailableResponse();\n\t\t\t}\n\t\t});\n\t}\n}\n/** The purpose store is read only when a ceremony shares the `owner_enroll` purpose. */\nfunction createSharedCallback(\n\tinput: Omit<CoordinatorBrowserAuthCallbackInput, \"completeLink\" | \"store\"> & {\n\t\tstore: CoordinatorBrowserAuthStore;\n\t},\n\thandlers: Pick<\n\t\tCoordinatorBrowserAuthCallbackInput,\n\t\t\"completeLink\" | \"ownerCallback\" | \"accountChangeCallback\" | \"deviceRebindCallback\"\n\t>,\n) {\n\tconst sharesOwnerPurpose = handlers.ownerCallback || handlers.deviceRebindCallback;\n\treturn createCoordinatorBrowserAuthCallback({\n\t\t...input,\n\t\t...handlers,\n\t\tpurposeStore: sharesOwnerPurpose ? capturePurposeStore(input.store) : undefined,\n\t});\n}\n\n/** Owns handlers, not the store lifetime. Nothing is mounted until all factories succeed. */\nexport async function createCoordinatorBrowserAuth(\n\tsnapshot: CoordinatorBrowserAuthSnapshot,\n\tstore: CoordinatorBrowserAuthStore,\n\tlimiter: InMemoryRequestRateLimiter,\n): Promise<CoordinatorBrowserAuthResult> {\n\tif (snapshot.kind === \"disabled\")\n\t\treturn Object.freeze({ ok: false, error: \"browser_auth_disabled\" });\n\tif (snapshot.kind === \"invalid\")\n\t\treturn Object.freeze({ ok: false, error: \"browser_auth_config_invalid\" });\n\ttry {\n\t\tconst payload = enabledPayloads.get(snapshot);\n\t\tif (!payload) return Object.freeze({ ok: false, error: \"browser_auth_setup_failed\" });\n\t\tconst checked = await browserAuthStoreState(store);\n\t\tif (\"error\" in checked) return Object.freeze({ ok: false, error: checked.error });\n\t\tconst rebind = createRebindAdapter(payload, store, limiter);\n\t\tconst input = Object.freeze({\n\t\t\tconfig: payload.config,\n\t\t\tcsrfKey: payload.csrfKey,\n\t\t\toidcOptions: payload.oidcOptions,\n\t\t\tstore,\n\t\t\tlimiter,\n\t\t});\n\t\tconst link = createCoordinatorBrowserLinkHandlers({\n\t\t\t...input,\n\t\t\tconfig: payload.settings.store,\n\t\t});\n\t\tconst completion = createCoordinatorBrowserLinkCompletionHandlers({\n\t\t\t...input,\n\t\t\tconfig: payload.settings.store,\n\t\t});\n\t\tif (!link.ok || !completion.ok)\n\t\t\treturn Object.freeze({ ok: false, error: \"browser_auth_setup_failed\" });\n\t\tconst signin = await createCoordinatorBrowserSigninStart(input);\n\t\tconst start = await createCoordinatorBrowserLinkStart(input);\n\t\tconst owner = await createOwnerAdapter(payload, limiter);\n\t\tconst change = await createChangeAdapter(payload, store, limiter, checked.operations);\n\t\tconst callback = await createSharedCallback(input, {\n\t\t\tcompleteLink: link.handlers.completeLink,\n\t\t\townerCallback: owner?.handleCallback,\n\t\t\taccountChangeCallback: change.callback,\n\t\t\tdeviceRebindCallback: rebind.callback,\n\t\t});\n\t\tconst account = await createCoordinatorBrowserAccount(input);\n\t\tif (!signin.ok || !start.ok || !callback.ok || !account.ok)\n\t\t\treturn Object.freeze({ ok: false, error: \"browser_auth_setup_failed\" });\n\t\tconst routes: readonly Route[] = Object.freeze([\n\t\t\t{ path: \"/auth/sign-in\", get: signin.handlers.signInPage, post: signin.handlers.signInStart },\n\t\t\t{\n\t\t\t\tpath: \"/auth/link/start\",\n\t\t\t\tget: start.handlers.linkStartPage,\n\t\t\t\tpost: start.handlers.linkStart,\n\t\t\t},\n\t\t\t{ path: payload.callbackPath, get: callback.handlers.callback },\n\t\t\t{ path: \"/auth/link/confirm\", post: link.handlers.confirm },\n\t\t\t{ path: \"/auth/link/cancel\", post: link.handlers.cancel },\n\t\t\t{\n\t\t\t\tpath: \"/auth/link/complete\",\n\t\t\t\tget: completion.handlers.page,\n\t\t\t\tpost: completion.handlers.complete,\n\t\t\t},\n\t\t\t{ path: \"/auth/account\", get: account.handlers.account },\n\t\t\t{ path: \"/auth/logout\", post: account.handlers.logout },\n\t\t\t...ownerRoutes(owner),\n\t\t\t...change.routes,\n\t\t\t...rebind.routes,\n\t\t]);\n\t\treturn browserAuthReady(payload.settings.store, routes, { accountChanges: change.enabled });\n\t} catch (error) {\n\t\treturn browserAuthSetupFailure(error);\n\t}\n}\n\nasync function createChangeAdapter(\n\tpayload: EnabledPayload,\n\tstore: CoordinatorBrowserAuthStore,\n\tlimiter: InMemoryRequestRateLimiter,\n\toperations: AccountChangeOperations | null,\n): Promise<{\n\tenabled: boolean;\n\troutes: Route[];\n\tcallback?: CoordinatorBrowserAuthCallbackInput[\"accountChangeCallback\"];\n}> {\n\tif (!operations) return { enabled: false, routes: [] };\n\tconst change = await createCoordinatorAccountChangeBrowser({\n\t\tconfig: payload.config,\n\t\tcsrfKey: payload.csrfKey,\n\t\toidcOptions: payload.oidcOptions,\n\t\tlimiter,\n\t\toperations,\n\t\treaders: {\n\t\t\treadStart: operations.readStart.bind(operations),\n\t\t\treadManagementActivity: operations.readManagementActivity.bind(operations),\n\t\t\treadBrowserBinding: operations.readBrowserBinding.bind(operations),\n\t\t},\n\t\texisting: {\n\t\t\t...capturePurposeStore(store),\n\t\t\treadAuthBrowserTransactionActivity: store.readAuthBrowserTransactionActivity.bind(store),\n\t\t},\n\t});\n\tif (!change.ok) throw new Error();\n\treturn {\n\t\tenabled: true,\n\t\troutes: [\n\t\t\t{\n\t\t\t\tpath: ACCOUNT_CHANGE_BROWSER_PATHS.start,\n\t\t\t\tget: async (request) => ({ response: await change.handlers.startPage(request) }),\n\t\t\t\tpost: async (request, key) => ({ response: await change.handlers.start(request, key) }),\n\t\t\t},\n\t\t\t{\n\t\t\t\tpath: ACCOUNT_CHANGE_BROWSER_PATHS.confirm,\n\t\t\t\tpost: async (request, key) => ({ response: await change.handlers.confirm(request, key) }),\n\t\t\t},\n\t\t],\n\t\tcallback: async (request, key, binderHash) => {\n\t\t\tconst activity = await operations.readManagementActivity(\n\t\t\t\t{ binderHash },\n\t\t\t\tpayload.settings.store,\n\t\t\t);\n\t\t\tif ((await change.handlers.matchesCallback(request)) || activity.kind !== \"inactive\")\n\t\t\t\treturn change.handlers.callback(request, key);\n\t\t\treturn null;\n\t\t},\n\t};\n}\n\ntype RebindHandlers = Extract<\n\tAwaited<ReturnType<typeof createDeviceRebindBrowser>>,\n\t{ ok: true }\n>[\"handlers\"];\n\n/**\n * Rebind is optional and does no I/O at setup. Each use first checks for its\n * tables (absent on a D1 database before migration 0038); until they exist\n * the pages report not found and the callback hook steps aside, so sign-in\n * and owner enrollment are unaffected. Only a ready composition is kept.\n */\nfunction createRebindAdapter(\n\tpayload: EnabledPayload,\n\tstore: CoordinatorBrowserAuthStore,\n\tlimiter: InMemoryRequestRateLimiter,\n): { routes: Route[]; callback?: (request: Request) => Promise<Response | null> } {\n\tconst read = storeMethod(store, \"readDeviceRebindBackend\");\n\tif (!read) return { routes: [] };\n\tlet ready: RebindHandlers | undefined;\n\tconst resolve = async (): Promise<RebindHandlers | null> => {\n\t\tif (ready) return ready;\n\t\tconst backend = (await read()) as AuthLinkBackend | null;\n\t\tif (!backend) return null;\n\t\tconst created = await createDeviceRebindBrowser({\n\t\t\tconfig: payload.config,\n\t\t\tcsrfKey: payload.csrfKey,\n\t\t\toidcOptions: payload.oidcOptions,\n\t\t\tlimiter,\n\t\t\tbackend,\n\t\t});\n\t\tif (!created.ok) return null;\n\t\tready ??= created.handlers;\n\t\treturn ready;\n\t};\n\tconst page =\n\t\t(step: \"startPage\" | \"start\" | \"confirm\"): BrowserHandler =>\n\t\tasync (request, key) => {\n\t\t\tconst handlers = await resolve();\n\t\t\treturn { response: handlers ? await handlers[step](request, key) : rebindNotFound() };\n\t\t};\n\treturn {\n\t\troutes: [\n\t\t\t{ path: DEVICE_REBIND_BROWSER_PATHS.start, get: page(\"startPage\"), post: page(\"start\") },\n\t\t\t{ path: DEVICE_REBIND_BROWSER_PATHS.confirm, post: page(\"confirm\") },\n\t\t],\n\t\tcallback: async (request) => {\n\t\t\ttry {\n\t\t\t\treturn (await (await resolve())?.callback(request)) ?? null;\n\t\t\t} catch {\n\t\t\t\t// Unreadable rebind storage: owner dispatch decides, and fails closed.\n\t\t\t\treturn null;\n\t\t\t}\n\t\t},\n\t};\n}\n\nfunction rebindNotFound(): Response {\n\treturn new Response(\"Not found.\", {\n\t\tstatus: 404,\n\t\theaders: { \"Cache-Control\": \"no-store\", \"X-Content-Type-Options\": \"nosniff\" },\n\t});\n}\n\nfunction browserAuthReady(\n\tstoreConfig: CoordinatorAuthBrowserConfig,\n\troutes: readonly Route[],\n\toptions: { accountChanges: boolean },\n): CoordinatorBrowserAuthResult {\n\treturn Object.freeze({\n\t\tok: true,\n\t\tauth: Object.freeze({\n\t\t\tstoreConfig,\n\t\t\tresolveAccountChanges: options.accountChanges ? resolveAccountChanges : undefined,\n\t\t\tregister: (app: Hono, clientKey: CoordinatorBrowserAuthClientKey) =>\n\t\t\t\tregisterRoutes(app, routes, clientKey),\n\t\t}),\n\t});\n}\n\nasync function browserAuthStoreState(\n\tstore: CoordinatorBrowserAuthStore,\n): Promise<\n\t| { operations: AccountChangeOperations | null }\n\t| { error: typeof AUTH_SCHEMA_UPGRADE_REQUIRED | \"browser_auth_store_unavailable\" }\n> {\n\ttry {\n\t\tconst read = storeMethod(store, \"readAccountChangeCapability\");\n\t\tif (read) return { operations: (await read()) as AccountChangeOperations | null };\n\t\tawait assertConfiguredAuthSchema(store);\n\t\treturn { operations: await resolveAccountChanges(store) };\n\t} catch (error) {\n\t\tif (error instanceof CoordinatorAuthSchemaUpgradeRequiredError)\n\t\t\treturn { error: AUTH_SCHEMA_UPGRADE_REQUIRED };\n\t\treturn { error: \"browser_auth_store_unavailable\" };\n\t}\n}\n\nfunction browserAuthSetupFailure(error: unknown): CoordinatorBrowserAuthResult {\n\tif (error instanceof CoordinatorAuthSchemaUpgradeRequiredError)\n\t\treturn Object.freeze({ ok: false, error: AUTH_SCHEMA_UPGRADE_REQUIRED });\n\treturn Object.freeze({ ok: false, error: \"browser_auth_setup_failed\" });\n}\n\nfunction ownerRoutes(owner: CoordinatorBrowserOwnerEnrollmentAdapter | undefined): Route[] {\n\tif (!owner) return [];\n\tconst handler: BrowserHandler = async (request, key) => ({\n\t\tresponse: (await owner.handle(request, key)) ?? coordinatorBrowserAuthUnavailableResponse(),\n\t});\n\treturn OWNER_PATHS.map((path) => ({ path, get: handler, post: handler }));\n}\n\nasync function createOwnerAdapter(\n\tpayload: EnabledPayload,\n\tlimiter: InMemoryRequestRateLimiter,\n): Promise<CoordinatorBrowserOwnerEnrollmentAdapter | undefined> {\n\tif (!payload.ownerEnrollment) return undefined;\n\tconst adapter = await payload.ownerEnrollment(\n\t\tObject.freeze({\n\t\t\tconfig: payload.config,\n\t\t\tcsrfKey: payload.csrfKey,\n\t\t\toidcOptions: payload.oidcOptions,\n\t\t\tlimiter,\n\t\t}),\n\t);\n\tconst handle = ownData(adapter, \"handle\");\n\tconst handleCallback = ownData(adapter, \"handleCallback\");\n\tif (typeof handle !== \"function\" || typeof handleCallback !== \"function\") throw new Error();\n\treturn Object.freeze({\n\t\thandle: (...args: Parameters<CoordinatorBrowserOwnerEnrollmentAdapter[\"handle\"]>) =>\n\t\t\tReflect.apply(handle, adapter, args),\n\t\thandleCallback: (\n\t\t\t...args: Parameters<CoordinatorBrowserOwnerEnrollmentAdapter[\"handleCallback\"]>\n\t\t) => Reflect.apply(handleCallback, adapter, args),\n\t});\n}\n\nfunction storeMethod(receiver: unknown, name: string): ((...args: never[]) => unknown) | undefined {\n\tif (!receiver || typeof receiver !== \"object\") throw new Error();\n\tlet cursor: object | null = receiver;\n\tconst seen = new Set<object>();\n\twhile (cursor) {\n\t\tif (seen.has(cursor)) throw new Error();\n\t\tseen.add(cursor);\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(cursor, name);\n\t\tif (descriptor) {\n\t\t\tif (!Object.hasOwn(descriptor, \"value\") || typeof descriptor.value !== \"function\")\n\t\t\t\tthrow new Error();\n\t\t\tconst method = descriptor.value;\n\t\t\treturn (...args) => Reflect.apply(method, receiver, args);\n\t\t}\n\t\tcursor = Object.getPrototypeOf(cursor);\n\t}\n\treturn undefined;\n}\nasync function resolveAccountChanges(store: unknown): Promise<AccountChangeOperations | null> {\n\tconst checked = storeMethod(store, \"readAccountChangeCapability\");\n\tif (checked) return (await checked()) as AccountChangeOperations | null;\n\tconst read = storeMethod(store, \"readAccountConnectionSchemaState\");\n\tconst get = storeMethod(store, \"getAccountChanges\");\n\tif (!read && !get) return null;\n\tif (!read || !get) throw new Error();\n\tconst state = await read();\n\tif (state === \"v2\") return null;\n\tif (state !== \"ready\") throw new CoordinatorAuthSchemaUpgradeRequiredError();\n\treturn (await get()) as AccountChangeOperations;\n}\nfunction capturePurposeStore(\n\tstore: CoordinatorBrowserAuthStore,\n): CoordinatorAuthBrowserTransactionPurposeStore {\n\tlet cursor: object | null = store;\n\tconst seen = new Set<object>();\n\twhile (cursor !== null) {\n\t\tif (seen.has(cursor)) throw new Error();\n\t\tseen.add(cursor);\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(cursor, \"readAuthBrowserTransactionPurpose\");\n\t\tif (descriptor) {\n\t\t\tif (!Object.hasOwn(descriptor, \"value\") || typeof descriptor.value !== \"function\")\n\t\t\t\tthrow new Error();\n\t\t\tconst method =\n\t\t\t\tdescriptor.value as CoordinatorAuthBrowserTransactionPurposeStore[\"readAuthBrowserTransactionPurpose\"];\n\t\t\treturn Object.freeze({\n\t\t\t\treadAuthBrowserTransactionPurpose: (\n\t\t\t\t\t...args: Parameters<\n\t\t\t\t\t\tCoordinatorAuthBrowserTransactionPurposeStore[\"readAuthBrowserTransactionPurpose\"]\n\t\t\t\t\t>\n\t\t\t\t) => Reflect.apply(method, store, args),\n\t\t\t});\n\t\t}\n\t\tcursor = Object.getPrototypeOf(cursor);\n\t}\n\tthrow new Error();\n}\n\nexport type CoordinatorBrowserAuthMaintenanceStore = Pick<\n\tCoordinatorAuthLinkStore,\n\t\"maintainAuthLinkAttempts\"\n> &\n\tPick<\n\t\tCoordinatorAuthBrowserTransactionStore,\n\t\t| \"retireAuthBrowserTransactions\"\n\t\t| \"purgeAuthSigninBrowserTransactions\"\n\t\t| \"maintainAuthBrowserTransactions\"\n\t> &\n\tPick<\n\t\tCoordinatorAuthSessionStore,\n\t\t\"purgeAuthGuardedSigninSessions\" | \"purgeAuthGuardedSigninReceipts\"\n\t>;\nexport type CoordinatorBrowserAuthMaintenanceStep =\n\t| \"link_attempts\"\n\t| \"browser_retirement\"\n\t| \"browser_expiry\"\n\t| \"signin_transactions\"\n\t| \"signin_sessions\"\n\t| \"signin_receipts\"\n\t| \"account_changes\";\nexport type CoordinatorBrowserAuthMaintenanceResult =\n\t| Readonly<{ kind: \"disabled\" }>\n\t| Readonly<{\n\t\t\tkind: \"failed\";\n\t\t\terror: \"maintenance_failed\";\n\t\t\tstep: CoordinatorBrowserAuthMaintenanceStep | \"options\";\n\t }>\n\t| Readonly<{ kind: \"maintained\"; processedCount: number; more: boolean }>;\n/** Explicit operator/scheduled work only; budgets apply independently to each stage. */\nexport async function maintainCoordinatorBrowserAuth(\n\tsnapshot: CoordinatorBrowserAuthSnapshot,\n\tstore: CoordinatorBrowserAuthMaintenanceStore,\n\toptions: { maxBatches?: number } = {},\n): Promise<CoordinatorBrowserAuthMaintenanceResult> {\n\tif (snapshot.kind === \"disabled\") return maintainDisabledAccountChanges(snapshot, store);\n\tlet step: CoordinatorBrowserAuthMaintenanceStep | \"options\" = \"options\";\n\ttry {\n\t\tconst payload = enabledPayloads.get(snapshot);\n\t\tconst maxBatches = options.maxBatches ?? 4;\n\t\tif (\n\t\t\tsnapshot.kind !== \"enabled\" ||\n\t\t\t!payload ||\n\t\t\t!Number.isSafeInteger(maxBatches) ||\n\t\t\tmaxBatches < 1 ||\n\t\t\tmaxBatches > 8\n\t\t)\n\t\t\tthrow new Error();\n\t\tconst config = payload.settings.store;\n\t\tconst changes = await resolveAccountChanges(store);\n\t\tconst scope = Object.freeze({ coordinatorId: config.coordinatorId });\n\t\tconst stages = [\n\t\t\t{ step: \"link_attempts\", run: () => store.maintainAuthLinkAttempts(config, { limit: 32 }) },\n\t\t\t{\n\t\t\t\tstep: \"browser_retirement\",\n\t\t\t\trun: () => store.retireAuthBrowserTransactions(config, { limit: 32 }),\n\t\t\t},\n\t\t\t{\n\t\t\t\tstep: \"browser_expiry\",\n\t\t\t\trun: () => store.maintainAuthBrowserTransactions(scope, { limit: 32 }),\n\t\t\t},\n\t\t\t{\n\t\t\t\tstep: \"signin_transactions\",\n\t\t\t\trun: () => store.purgeAuthSigninBrowserTransactions(scope, { limit: 256 }),\n\t\t\t},\n\t\t\t{\n\t\t\t\tstep: \"signin_sessions\",\n\t\t\t\trun: () => store.purgeAuthGuardedSigninSessions(scope, { limit: 256 }),\n\t\t\t},\n\t\t\t{\n\t\t\t\tstep: \"signin_receipts\",\n\t\t\t\trun: () => store.purgeAuthGuardedSigninReceipts(scope, { limit: 256 }),\n\t\t\t},\n\t\t\t...(changes\n\t\t\t\t? [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tstep: \"account_changes\" as const,\n\t\t\t\t\t\t\trun: async () => {\n\t\t\t\t\t\t\t\tconst processedCount = await changes.maintainExpired(config.coordinatorId, 32);\n\t\t\t\t\t\t\t\treturn { kind: \"maintained\", processedCount, more: processedCount === 32 };\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t]\n\t\t\t\t: []),\n\t\t] as const;\n\t\tlet processedCount = 0;\n\t\tlet more = false;\n\t\tfor (const stage of stages) {\n\t\t\tstep = stage.step;\n\t\t\tconst result = await runMaintenanceStage(stage.run, maxBatches);\n\t\t\tprocessedCount += result.processedCount;\n\t\t\tif (!Number.isSafeInteger(processedCount)) throw new Error();\n\t\t\tmore ||= result.more;\n\t\t}\n\t\treturn Object.freeze({ kind: \"maintained\", processedCount, more });\n\t} catch {\n\t\treturn Object.freeze({ kind: \"failed\", error: \"maintenance_failed\", step });\n\t}\n}\n\n/** Disabled auth needs only a captured coordinator pin, never issuer or secret material. */\nasync function maintainDisabledAccountChanges(\n\tsnapshot: CoordinatorBrowserAuthSnapshot,\n\tstore: CoordinatorBrowserAuthMaintenanceStore,\n): Promise<CoordinatorBrowserAuthMaintenanceResult> {\n\tconst coordinatorId = disabledMaintenancePins.get(snapshot);\n\tif (!coordinatorId) return Object.freeze({ kind: \"disabled\" });\n\ttry {\n\t\tconst changes = await resolveAccountChanges(store);\n\t\tif (!changes) return Object.freeze({ kind: \"disabled\" });\n\t\tconst processedCount = await changes.maintainExpired(coordinatorId, 32);\n\t\treturn Object.freeze({ kind: \"maintained\", processedCount, more: processedCount === 32 });\n\t} catch {\n\t\treturn Object.freeze({ kind: \"failed\", error: \"maintenance_failed\", step: \"account_changes\" });\n\t}\n}\nasync function runMaintenanceStage(\n\trun: () => Promise<{ kind: string; processedCount?: number; more?: boolean }>,\n\tmaxBatches: number,\n): Promise<{ processedCount: number; more: boolean }> {\n\tlet processedCount = 0;\n\tfor (let batch = 0; batch < maxBatches; batch++) {\n\t\tconst result = await run();\n\t\tif (\n\t\t\tresult.kind === \"rejected\" ||\n\t\t\ttypeof result.processedCount !== \"number\" ||\n\t\t\t!Number.isSafeInteger(result.processedCount) ||\n\t\t\tresult.processedCount < 0 ||\n\t\t\ttypeof result.more !== \"boolean\"\n\t\t)\n\t\t\tthrow new Error();\n\t\tprocessedCount += result.processedCount;\n\t\tif (!Number.isSafeInteger(processedCount)) throw new Error();\n\t\tif (!result.more) return { processedCount, more: false };\n\t}\n\treturn { processedCount, more: true };\n}\n","import { connectionRequesterGuard } from \"./coordinator-account-connection-link.js\";\nimport { readConnectionSchemaState } from \"./coordinator-account-connection-schema.js\";\nimport { isAuthControllerId } from \"./coordinator-auth-controller.js\";\nimport { authSchemaDefinitionCheck } from \"./coordinator-auth-device-claim-schema.js\";\nimport {\n\ttype AuthLinkBackend,\n\ttype AuthLinkStatement,\n\tauthLinkNow,\n} from \"./coordinator-auth-link.js\";\nimport type { CoordinatorAuthLinkConfig } from \"./coordinator-auth-link-contract.js\";\nimport { capture, captureAuthLinkConfig, isHash } from \"./coordinator-auth-link-input.js\";\nimport { authLinkLiveGenerationSql } from \"./coordinator-auth-link-liveness.js\";\nimport { authDeviceClaimProvenanceSql } from \"./coordinator-auth-link-provenance.js\";\nimport { ed25519KeyIdForRevocation } from \"./coordinator-ed25519-key-id-compat.js\";\nimport {\n\tCOORDINATOR_OWNER_ENROLLMENT_QUALIFICATION_SCHEMA_STATEMENTS,\n\ttype CoordinatorOwnerEnrollmentQualificationRow,\n} from \"./coordinator-owner-enrollment-qualification-schema.js\";\n\n/** Internal admin capability only. No route, store startup, grant or owner consumer uses it. */\nexport type OwnerQualificationRejected = {\n\tkind: \"rejected\";\n\terror: \"invalid_input\" | \"unavailable\" | \"preview_changed\" | \"qualification_conflict\";\n};\n/** The write may have committed. This is not a denial or proof of rollback. */\nexport type OwnerQualificationOutcomeUnknown = { kind: \"outcome_unknown\" };\nexport interface OwnerQualificationPreview {\n\tkind: \"ready\";\n\tdigest: string;\n\tattestationId: string;\n\treviewReceiptId: string;\n\tlinkId: string;\n\tclaimId: string;\n\tidentityId: string;\n\tgroupId: string;\n\tdeviceId: string;\n\tfingerprint: string;\n}\n\n// Fixed order is the canonical encoding, shared by the digest and winning SQL.\n// Include actual current enrollment separately from the review's historical label.\nconst BIRTH = {\n\tcoordinator_id: \"l.coordinator_id\",\n\tlink_id: \"l.link_id\",\n\tdevice_claim_id: \"d.claim_id\",\n\tidentity_id: \"l.identity_id\",\n\tsource_group_id: \"a.group_id\",\n\tdevice_id: \"a.device_id\",\n\tpublic_key: \"a.public_key\",\n\tfingerprint: \"a.fingerprint\",\n\tkey_id: \"d.key_id\",\n\tcontroller_attestation_id: \"a.attestation_id\",\n\tcontroller_attestation_revision: \"a.revision\",\n\tcontroller_attestation_created_at: \"a.created_at\",\n\treview_receipt_id: \"a.review_receipt_id\",\n\tevidence_digest: \"a.evidence_digest\",\n\tenrollment_identity_id: \"a.enrollment_identity_id\",\n\tlink_attempt_id: \"l.attempt_id\",\n\tlink_auth_config_revision: \"l.auth_config_revision\",\n\tlink_created_at_ms: \"l.created_at_ms\",\n} as const;\ntype Birth = Omit<\n\tCoordinatorOwnerEnrollmentQualificationRow,\n\t\"qualification_id\" | \"created_at_ms\" | \"revoked_at_ms\"\n>;\ninterface Source extends Birth {\n\tsnapshot: string;\n}\nconst SNAPSHOT = `json_array(${[\n\t...Object.values(BIRTH),\n\t\"l.issuer\",\n\t\"l.subject\",\n\t\"l.authority_kind\",\n\t\"l.controller_attestation_id\",\n\t\"l.signin_floor\",\n\t\"l.revoked_at_ms\",\n\t\"d.identity_id\",\n\t\"d.group_id\",\n\t\"d.device_id\",\n\t\"d.public_key\",\n\t\"d.fingerprint\",\n\t\"d.attempt_id\",\n\t\"d.issuer\",\n\t\"d.auth_config_revision\",\n\t\"d.created_at_ms\",\n\t\"e.identity_id\",\n\t\"e.public_key\",\n\t\"e.fingerprint\",\n\t\"e.enabled\",\n\t\"e.created_at\",\n\t\"e.display_name\",\n].join(\",\")})`;\nconst SOURCE = `FROM coordinator_auth_controller_attestations a\n JOIN enrolled_devices e ON e.group_id=a.group_id AND e.device_id=a.device_id\n JOIN groups g ON g.group_id=e.group_id\n JOIN coordinator_auth_account_links l ON l.coordinator_id=a.coordinator_id AND l.identity_id=a.identity_id\n JOIN coordinator_auth_device_claims d ON d.coordinator_id=l.coordinator_id AND d.claim_id=l.device_claim_id\n WHERE (a.coordinator_id=? AND a.attestation_id=? AND l.issuer=?)\n AND (a.revoked_at IS NULL AND a.revision=1 AND length(a.review_receipt_id)>0 AND length(a.evidence_digest)=64)\n AND (e.public_key=a.public_key AND e.fingerprint=a.fingerprint AND e.enabled=1 AND g.archived_at IS NULL)\n AND (e.identity_id IS NULL OR e.identity_id=a.identity_id)\n AND e.identity_id IS a.enrollment_identity_id\n AND (a.enrollment_identity_id IS NULL OR a.enrollment_identity_id=a.identity_id)\n AND (d.identity_id=a.identity_id AND d.group_id=a.group_id AND d.device_id=a.device_id\n AND d.public_key=a.public_key AND d.fingerprint=a.fingerprint)\n AND (${authLinkLiveGenerationSql({ link: \"l\", connections: true })})\n AND (${authDeviceClaimProvenanceSql({ link: \"l\", connections: true })})`;\nconst SOURCE_COLUMNS = Object.entries(BIRTH)\n\t.map(([name, expression]) => `${expression} AS ${name}`)\n\t.join(\",\");\nconst QUALIFICATION_READY = COORDINATOR_OWNER_ENROLLMENT_QUALIFICATION_SCHEMA_STATEMENTS.map(\n\t(sql, index) =>\n\t\tauthSchemaDefinitionCheck(\n\t\t\tsql.replace(/^(?:\\s|--[^\\n]*\\n)*/u, \"\").replace(/;\\s*$/u, \"\"),\n\t\t\tindex === 0 ? { auxiliaryObjects: 5 } : undefined,\n\t\t).matches,\n).join(\" AND \");\n\nasync function digestSource(source: Source, config: CoordinatorAuthLinkConfig): Promise<string> {\n\tconst bytes = new TextEncoder().encode(\n\t\tJSON.stringify([\n\t\t\t\"codemem.owner-enrollment-qualification.preview.v1\",\n\t\t\tconfig.enabled,\n\t\t\tconfig.coordinatorId,\n\t\t\tconfig.issuer,\n\t\t\tconfig.revision,\n\t\t\tsource.snapshot,\n\t\t]),\n\t);\n\tconst digest = await crypto.subtle.digest(\"SHA-256\", bytes);\n\treturn Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\nfunction preview(source: Source, digest: string): OwnerQualificationPreview {\n\treturn {\n\t\tkind: \"ready\",\n\t\tdigest,\n\t\tattestationId: source.controller_attestation_id,\n\t\treviewReceiptId: source.review_receipt_id,\n\t\tlinkId: source.link_id,\n\t\tclaimId: source.device_claim_id,\n\t\tidentityId: source.identity_id,\n\t\tgroupId: source.source_group_id,\n\t\tdeviceId: source.device_id,\n\t\tfingerprint: source.fingerprint,\n\t};\n}\nconst unavailable = (): OwnerQualificationRejected => ({ kind: \"rejected\", error: \"unavailable\" });\ninterface Prepared {\n\tsource: Source;\n\tguard: AuthLinkStatement;\n\tdigest: string;\n}\n\nexport class OwnerEnrollmentQualificationOps {\n\tprivate readonly config: CoordinatorAuthLinkConfig | null;\n\tconstructor(\n\t\tprivate readonly backend: AuthLinkBackend,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t\tprivate readonly clock: () => number = Date.now,\n\t) {\n\t\t// Capture trusted configuration before the first asynchronous operation.\n\t\tthis.config = captureAuthLinkConfig(config);\n\t}\n\t/** Read-only deployment check; operations repeat it before resolving authority. */\n\tasync schemaReady(): Promise<boolean> {\n\t\tif ((await readConnectionSchemaState(this.backend)) !== \"ready\") return false;\n\t\treturn (\n\t\t\t(\n\t\t\t\tawait this.backend.first<{ ready: number }>({\n\t\t\t\t\tsql: `SELECT (${QUALIFICATION_READY}) AS ready`,\n\t\t\t\t\tvalues: [],\n\t\t\t\t})\n\t\t\t)?.ready === 1\n\t\t);\n\t}\n\tprivate async prepare(attestationId: string, now: number): Promise<Prepared | null> {\n\t\tconst c = this.config;\n\t\tif (!c?.enabled || !(await this.schemaReady())) return null;\n\t\tconst source = await this.backend.first<Source>({\n\t\t\tsql: `SELECT ${SOURCE_COLUMNS}, ${SNAPSHOT} AS snapshot ${SOURCE}`,\n\t\t\tvalues: [c.coordinatorId, attestationId, c.issuer],\n\t\t});\n\t\tif (!source || !isHash(source.evidence_digest)) return null;\n\t\tconst keyId = await ed25519KeyIdForRevocation(source.public_key);\n\t\tif (!keyId || keyId !== source.key_id) return null;\n\t\tconst guard = await connectionRequesterGuard(\n\t\t\tthis.backend,\n\t\t\tsource.identity_id,\n\t\t\t{\n\t\t\t\tgroupId: source.source_group_id,\n\t\t\t\tdeviceId: source.device_id,\n\t\t\t\tpublicKey: source.public_key,\n\t\t\t\tfingerprint: source.fingerprint,\n\t\t\t},\n\t\t\tc,\n\t\t\tnow,\n\t\t);\n\t\tconst digest = await digestSource(source, c);\n\t\tconst prepared = { source, guard, digest };\n\t\t// Key classification and hashing await; never trust the earlier SELECT alone.\n\t\tif (!(await this.live(prepared))) return null;\n\t\treturn prepared;\n\t}\n\tprivate liveStatement(p: Prepared): AuthLinkStatement {\n\t\tconst c = this.config;\n\t\tif (!c) return { sql: \"SELECT 1 WHERE 0\", values: [] };\n\t\treturn {\n\t\t\tsql: `${SOURCE} AND (${SNAPSHOT}=?) AND (${p.guard.sql})\n AND NOT EXISTS (SELECT 1 FROM coordinator_device_revocations r\n WHERE (r.subject_kind='device_id' AND r.subject_value=a.device_id)\n OR (r.subject_kind='ed25519_key' AND r.subject_value=d.key_id))`,\n\t\t\tvalues: [\n\t\t\t\tc.coordinatorId,\n\t\t\t\tp.source.controller_attestation_id,\n\t\t\t\tc.issuer,\n\t\t\t\tp.source.snapshot,\n\t\t\t\t...p.guard.values,\n\t\t\t],\n\t\t};\n\t}\n\tprivate async live(p: Prepared): Promise<boolean> {\n\t\tconst s = this.liveStatement(p);\n\t\treturn !!(await this.backend.first({ sql: `SELECT 1 ${s.sql}`, values: s.values }));\n\t}\n\tasync preview(input: {\n\t\tattestationId: string;\n\t}): Promise<OwnerQualificationPreview | OwnerQualificationRejected> {\n\t\tconst i = capture(input, [\"attestationId\"]);\n\t\tif (!isAuthControllerId(i?.attestationId)) return { kind: \"rejected\", error: \"invalid_input\" };\n\t\ttry {\n\t\t\tconst p = await this.prepare(i.attestationId, authLinkNow(this.clock));\n\t\t\tif (!p) return unavailable();\n\t\t\tconst existing = await this.existing(p);\n\t\t\tif (existing && !this.matches(existing, p.source))\n\t\t\t\treturn { kind: \"rejected\", error: \"qualification_conflict\" };\n\t\t\treturn preview(p.source, p.digest);\n\t\t} catch {\n\t\t\treturn unavailable();\n\t\t}\n\t}\n\tasync issue(input: {\n\t\tattestationId: string;\n\t\texpectedDigest: string;\n\t}): Promise<\n\t\t| { kind: \"created\" | \"existing\"; qualificationId: string }\n\t\t| OwnerQualificationRejected\n\t\t| OwnerQualificationOutcomeUnknown\n\t> {\n\t\tconst i = capture(input, [\"attestationId\", \"expectedDigest\"]);\n\t\tif (!isAuthControllerId(i?.attestationId) || !isHash(i?.expectedDigest))\n\t\t\treturn { kind: \"rejected\", error: \"invalid_input\" };\n\t\tlet writeAttempted = false;\n\t\ttry {\n\t\t\tconst now = authLinkNow(this.clock);\n\t\t\tconst p = await this.prepare(i.attestationId, now);\n\t\t\tif (!p) return unavailable();\n\t\t\tif (p.digest !== i.expectedDigest) return { kind: \"rejected\", error: \"preview_changed\" };\n\t\t\tconst qualificationId = crypto.randomUUID();\n\t\t\tconst s = this.liveStatement(p);\n\t\t\tconst statement: AuthLinkStatement = {\n\t\t\t\tsql: `INSERT INTO coordinator_owner_enrollment_qualifications\n (qualification_id,${Object.keys(BIRTH).join(\",\")},created_at_ms,revoked_at_ms)\n SELECT ?,${Object.values(BIRTH).join(\",\")},?,NULL ${s.sql}\n AND l.created_at_ms<=? AND NOT EXISTS (SELECT 1 FROM coordinator_owner_enrollment_qualifications q\n WHERE q.coordinator_id=l.coordinator_id AND q.link_id=l.link_id)`,\n\t\t\t\tvalues: [qualificationId, now, ...s.values, now],\n\t\t\t};\n\t\t\t// A backend can commit and then lose the response. Never infer rollback.\n\t\t\twriteAttempted = true;\n\t\t\tconst changes = await this.backend.run(statement);\n\t\t\tif (changes === 1) return { kind: \"created\", qualificationId };\n\t\t\treturn await this.retry(p);\n\t\t} catch {\n\t\t\tif (writeAttempted) return { kind: \"outcome_unknown\" };\n\t\t\treturn unavailable();\n\t\t}\n\t}\n\tprivate existing(p: Prepared): Promise<CoordinatorOwnerEnrollmentQualificationRow | null> {\n\t\treturn this.backend.first({\n\t\t\tsql: \"SELECT * FROM coordinator_owner_enrollment_qualifications WHERE coordinator_id=? AND link_id=?\",\n\t\t\tvalues: [p.source.coordinator_id, p.source.link_id],\n\t\t});\n\t}\n\t/** Revoke only a fixed server-resolved record/link pair; never require the old device to live. */\n\tasync revoke(input: {\n\t\tqualificationId: string;\n\t\tlinkId: string;\n\t}): Promise<\n\t\t| { kind: \"revoked\"; qualificationId: string }\n\t\t| OwnerQualificationRejected\n\t\t| OwnerQualificationOutcomeUnknown\n\t> {\n\t\tconst i = capture(input, [\"qualificationId\", \"linkId\"]);\n\t\tif (!isAuthControllerId(i?.qualificationId) || !isAuthControllerId(i?.linkId))\n\t\t\treturn { kind: \"rejected\", error: \"invalid_input\" };\n\t\tlet writeAttempted = false;\n\t\ttry {\n\t\t\tconst c = this.config;\n\t\t\tconst now = authLinkNow(this.clock);\n\t\t\tif (!c?.enabled || !(await this.schemaReady())) return unavailable();\n\t\t\tconst values = [c.coordinatorId, i.qualificationId, i.linkId];\n\t\t\tconst statement: AuthLinkStatement = {\n\t\t\t\t// Clock rollback must not delay revocation or rewrite an earlier receipt.\n\t\t\t\tsql: `UPDATE coordinator_owner_enrollment_qualifications SET revoked_at_ms=MAX(?,created_at_ms)\n WHERE coordinator_id=? AND qualification_id=? AND link_id=? AND revoked_at_ms IS NULL`,\n\t\t\t\tvalues: [now, ...values],\n\t\t\t};\n\t\t\twriteAttempted = true;\n\t\t\tawait this.backend.run(statement);\n\t\t\tconst row = await this.backend.first<{ qualification_id: string }>({\n\t\t\t\tsql: `SELECT qualification_id FROM coordinator_owner_enrollment_qualifications\n WHERE coordinator_id=? AND qualification_id=? AND link_id=? AND revoked_at_ms IS NOT NULL`,\n\t\t\t\tvalues,\n\t\t\t});\n\t\t\treturn row ? { kind: \"revoked\", qualificationId: row.qualification_id } : unavailable();\n\t\t} catch {\n\t\t\tif (writeAttempted) return { kind: \"outcome_unknown\" };\n\t\t\treturn unavailable();\n\t\t}\n\t}\n\tprivate matches(row: CoordinatorOwnerEnrollmentQualificationRow, source: Source): boolean {\n\t\treturn (\n\t\t\trow.revoked_at_ms === null &&\n\t\t\tObject.keys(BIRTH).every((key) => {\n\t\t\t\tconst field = key as keyof Birth;\n\t\t\t\treturn row[field] === source[field];\n\t\t\t})\n\t\t);\n\t}\n\tprivate async retry(\n\t\tp: Prepared,\n\t): Promise<{ kind: \"existing\"; qualificationId: string } | OwnerQualificationRejected> {\n\t\t// Keep one atomic snapshot, but isolate full provenance from birth matching:\n\t\t// native D1 counts both trees toward its depth limit when nested together.\n\t\tconst s = this.liveStatement(p);\n\t\tconst row = await this.backend.first<CoordinatorOwnerEnrollmentQualificationRow>({\n\t\t\tsql: `WITH qualification_live_source AS MATERIALIZED (\n SELECT ${SOURCE_COLUMNS} ${s.sql})\n SELECT q.* FROM coordinator_owner_enrollment_qualifications q\n JOIN qualification_live_source source ON ${Object.keys(BIRTH)\n\t\t.map((key) => `q.${key} IS source.${key}`)\n\t\t.join(\" AND \")}\n WHERE q.revoked_at_ms IS NULL`,\n\t\t\tvalues: s.values,\n\t\t});\n\t\treturn row\n\t\t\t? { kind: \"existing\", qualificationId: row.qualification_id }\n\t\t\t: { kind: \"rejected\", error: \"qualification_conflict\" };\n\t}\n}\n","import type { Context } from \"hono\";\nimport type { CoordinatorControllerReviewDeps } from \"./coordinator-auth-controller-review-route.js\";\nimport { authSchemaDefinitionCheck } from \"./coordinator-auth-device-claim-schema.js\";\nimport type { AuthLinkBackend } from \"./coordinator-auth-link.js\";\nimport type { CoordinatorAuthLinkConfig } from \"./coordinator-auth-link-contract.js\";\nimport { captureAuthLinkConfig, isHash } from \"./coordinator-auth-link-input.js\";\nimport { isCoordinatorControllerAttestationReference } from \"./coordinator-identity-group-grant-client.js\";\nimport { OwnerEnrollmentQualificationOps } from \"./coordinator-owner-enrollment-qualification.js\";\nimport { COORDINATOR_OWNER_ENROLLMENT_SCHEMA_SQL } from \"./coordinator-owner-enrollment-schema.js\";\n\nexport interface OwnerQualificationRouteDeps\n\textends Pick<\n\t\tCoordinatorControllerReviewDeps,\n\t\t\"adminSecret\" | \"readRequestBytes\" | \"parseJsonObject\" | \"rateLimitedResponse\"\n\t> {\n\tconfig: CoordinatorAuthLinkConfig | null;\n\t/** Must be the backend of the selected runtime store, never a separate database. */\n\tbackend: AuthLinkBackend | null;\n}\n\n// These are frozen repository DDL statements, not caller-supplied SQL. Check the\n// complete 0036 table, indexes and triggers without applying or rebuilding them.\n// ALTER TABLE ... RENAME in 0036 quotes this one table identifier. Normalize\n// only that exact leading header, never quotes within CHECK/string literals.\nconst RENAMED_TABLE_HEADER = 'CREATE TABLE \"coordinator_owner_enrollment_attempts\"';\nconst ATTEMPT_TABLE_SQL = `CASE WHEN substr(sql, 1, ${RENAMED_TABLE_HEADER.length}) = '${RENAMED_TABLE_HEADER}'\n THEN 'CREATE TABLE coordinator_owner_enrollment_attempts' || substr(sql, ${RENAMED_TABLE_HEADER.length + 1}) ELSE sql END`;\nexport const ownerQualificationAttemptDefinitionChecks =\n\tCOORDINATOR_OWNER_ENROLLMENT_SCHEMA_SQL.replace(/^--[^\\n]*$/gm, \"\")\n\t\t.trim()\n\t\t.split(/\\n(?=CREATE )/u)\n\t\t.map((sql, index) => {\n\t\t\tconst check = authSchemaDefinitionCheck(\n\t\t\t\tsql.trim().replace(/;$/u, \"\"),\n\t\t\t\tindex === 0 ? { auxiliaryObjects: 13 } : undefined,\n\t\t\t);\n\t\t\tif (index !== 0) return check;\n\t\t\t// The generated predicate references sqlite_master.sql once. Preserve its\n\t\t\t// full-definition comparison and exact auxiliary-object count.\n\t\t\treturn { ...check, matches: check.matches.replace(/\\bsql\\b/u, ATTEMPT_TABLE_SQL) };\n\t\t});\nconst ATTEMPT_READY = ownerQualificationAttemptDefinitionChecks\n\t.map((check) => check.matches)\n\t.join(\" AND \");\n\nasync function authenticate(provided: string | undefined, configured: string | null) {\n\tif (!provided || !configured || provided.length > 8192) return false;\n\tconst digest = (value: string) =>\n\t\tcrypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(value));\n\tconst [expected, actual] = await Promise.all([digest(configured), digest(provided)]);\n\tconst key = await crypto.subtle.importKey(\n\t\t\"raw\",\n\t\texpected,\n\t\t{ name: \"HMAC\", hash: \"SHA-256\" },\n\t\tfalse,\n\t\t[\"sign\", \"verify\"],\n\t);\n\tconst signature = await crypto.subtle.sign(\"HMAC\", key, expected);\n\treturn crypto.subtle.verify(\"HMAC\", key, signature, actual);\n}\n\nfunction parseInput(data: Record<string, unknown> | null) {\n\tif (\n\t\t!data ||\n\t\tObject.keys(data).some((key) => ![\"attestation_id\", \"confirm_evidence_digest\"].includes(key))\n\t)\n\t\treturn null;\n\tif (!isCoordinatorControllerAttestationReference(data.attestation_id)) return null;\n\tif (Object.hasOwn(data, \"confirm_evidence_digest\") && !isHash(data.confirm_evidence_digest))\n\t\treturn null;\n\treturn {\n\t\tattestationId: data.attestation_id,\n\t\texpectedDigest: data.confirm_evidence_digest as string | undefined,\n\t};\n}\n\nasync function authorize(c: Context, deps: OwnerQualificationRouteDeps): Promise<Response | null> {\n\tconst authenticated = await authenticate(\n\t\tc.req.header(\"X-Codemem-Coordinator-Admin\"),\n\t\tdeps.adminSecret(),\n\t);\n\tconst limited = deps.rateLimitedResponse(\n\t\tc,\n\t\t`owner-qualification:${authenticated ? \"admin\" : \"anonymous\"}`,\n\t\t{ authenticated },\n\t);\n\tif (limited) return limited;\n\tif (!authenticated) return c.json({ error: \"unauthorized\" }, 401);\n\treturn null;\n}\n\nasync function rejectedResponse(c: Context, ops: OwnerEnrollmentQualificationOps, error: string) {\n\tif (error === \"unavailable\") {\n\t\ttry {\n\t\t\tif (!(await ops.schemaReady())) return c.json({ error: \"qualification_unavailable\" }, 503);\n\t\t} catch {\n\t\t\treturn c.json({ error: \"qualification_unavailable\" }, 503);\n\t\t}\n\t}\n\treturn c.json({ error }, 409);\n}\n\nasync function previewResponse(\n\tc: Context,\n\tops: OwnerEnrollmentQualificationOps,\n\tattestationId: string,\n\tcoordinatorId: string,\n) {\n\tconst result = await ops.preview({ attestationId });\n\tif (result.kind === \"rejected\") return rejectedResponse(c, ops, result.error);\n\treturn c.json({\n\t\tstate: \"ready\",\n\t\tcoordinator_id: coordinatorId,\n\t\tevidence_digest: result.digest,\n\t\tattestation_id: result.attestationId,\n\t\treview_receipt_id: result.reviewReceiptId,\n\t\tlink_id: result.linkId,\n\t\tclaim_id: result.claimId,\n\t\tidentity_id: result.identityId,\n\t\tgroup_id: result.groupId,\n\t\tdevice_id: result.deviceId,\n\t\tfingerprint: result.fingerprint,\n\t});\n}\n\nasync function issueResponse(\n\tc: Context,\n\tops: OwnerEnrollmentQualificationOps,\n\tinput: { attestationId: string; expectedDigest: string },\n\tcoordinatorId: string,\n) {\n\ttry {\n\t\tconst result = await ops.issue(input);\n\t\tif (result.kind === \"outcome_unknown\")\n\t\t\treturn c.json({ error: \"qualification_outcome_unknown\" }, 503);\n\t\tif (result.kind === \"rejected\") return await rejectedResponse(c, ops, result.error);\n\t\treturn c.json(\n\t\t\t{\n\t\t\t\tstate: result.kind,\n\t\t\t\tqualification_id: result.qualificationId,\n\t\t\t\tattestation_id: input.attestationId,\n\t\t\t\tcoordinator_id: coordinatorId,\n\t\t\t\tevidence_digest: input.expectedDigest,\n\t\t\t},\n\t\t\tresult.kind === \"created\" ? 201 : 200,\n\t\t);\n\t} catch {\n\t\treturn c.json({ error: \"qualification_outcome_unknown\" }, 503);\n\t}\n}\n\nasync function qualificationSchemasReady(\n\tbackend: AuthLinkBackend,\n\tops: OwnerEnrollmentQualificationOps,\n): Promise<boolean> {\n\tconst ready = await backend.first<{ ready: number }>({\n\t\tsql: `SELECT (${ATTEMPT_READY}) AS ready`,\n\t\tvalues: [],\n\t});\n\treturn ready?.ready === 1 && (await ops.schemaReady());\n}\n\n/** Explicit operator operation using only the selected runtime backend. */\nexport function createOwnerQualificationHandler(\n\tdeps: OwnerQualificationRouteDeps,\n): (c: Context) => Promise<Response> {\n\tconst config = captureAuthLinkConfig(deps.config);\n\tconst captured = { ...deps };\n\tconst backend = captured.backend;\n\tconst ops = config && backend ? new OwnerEnrollmentQualificationOps(backend, config) : null;\n\treturn async (c) => {\n\t\tc.header(\"Cache-Control\", \"no-store\");\n\t\tc.header(\"Referrer-Policy\", \"no-referrer\");\n\t\tc.header(\"X-Content-Type-Options\", \"nosniff\");\n\t\ttry {\n\t\t\tconst denied = await authorize(c, captured);\n\t\t\tif (denied) return denied;\n\t\t\tif (!config?.enabled || !ops || !backend)\n\t\t\t\treturn c.json({ error: \"qualification_unavailable\" }, 503);\n\t\t\tconst raw = await captured.readRequestBytes(c, 4096);\n\t\t\tif (!raw) return c.json({ error: \"body_too_large\" }, 413);\n\t\t\tconst input = parseInput(captured.parseJsonObject(raw));\n\t\t\tif (!input) return c.json({ error: \"qualification_invalid_input\" }, 400);\n\t\t\tif (!(await qualificationSchemasReady(backend, ops)))\n\t\t\t\treturn c.json({ error: \"qualification_unavailable\" }, 503);\n\t\t\tif (input.expectedDigest === undefined)\n\t\t\t\treturn await previewResponse(c, ops, input.attestationId, config.coordinatorId);\n\t\t\treturn await issueResponse(\n\t\t\t\tc,\n\t\t\t\tops,\n\t\t\t\t{ attestationId: input.attestationId, expectedDigest: input.expectedDigest },\n\t\t\t\tconfig.coordinatorId,\n\t\t\t);\n\t\t} catch {\n\t\t\treturn c.json({ error: \"qualification_unavailable\" }, 503);\n\t\t}\n\t};\n}\n","import { type Context, Hono } from \"hono\";\nimport {\n\tcreateOwnerQualificationHandler,\n\ttype OwnerQualificationRouteDeps,\n} from \"./coordinator-owner-qualification-route.js\";\nimport type { InMemoryRequestRateLimiter } from \"./request-rate-limit.js\";\n\nexport const OWNER_QUALIFICATION_PATH = \"/v1/admin/owner-qualifications\";\nconst BODY_DEADLINE_MS = 5000;\n\nfunction transportError(c: Context, origin: string | null): Response | null {\n\tconst request = c.req.raw;\n\tconst url = new URL(request.url);\n\tif (request.method !== \"POST\") return c.json({ error: \"method_not_allowed\" }, 405);\n\tif (\n\t\turl.origin !== origin ||\n\t\turl.protocol !== \"https:\" ||\n\t\turl.search ||\n\t\turl.hash ||\n\t\turl.username ||\n\t\turl.password ||\n\t\trequest.headers.has(\"Origin\")\n\t)\n\t\treturn c.json({ error: \"qualification_invalid_input\" }, 400);\n\tif (request.headers.has(\"Transfer-Encoding\"))\n\t\treturn c.json({ error: \"qualification_invalid_input\" }, 400);\n\tif (\n\t\t!/^application\\/json(?:\\s*;\\s*charset=utf-8)?$/i.test(\n\t\t\trequest.headers.get(\"Content-Type\") ?? \"\",\n\t\t) ||\n\t\trequest.headers.has(\"Content-Encoding\")\n\t)\n\t\treturn c.json({ error: \"invalid_content_type\" }, 415);\n\tconst length = request.headers.get(\"Content-Length\");\n\tif (length !== null && !/^[0-9]{1,10}$/.test(length))\n\t\treturn c.json({ error: \"qualification_invalid_input\" }, 400);\n\tif (length !== null && Number(length) > 4096) return c.json({ error: \"body_too_large\" }, 413);\n\treturn null;\n}\n\n/** One fixed buffer, one deadline, and cancellation that never holds up refusal. */\nasync function readBody(c: Context, maxBytes: number): Promise<Uint8Array | null> {\n\tconst request = c.req.raw;\n\tif (request.signal.aborted || !request.body) return null;\n\tconst reader = request.body.getReader();\n\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\tlet stop = () => {};\n\tconst interrupted = new Promise<null>((resolve) => {\n\t\tstop = () => resolve(null);\n\t\ttimer = setTimeout(stop, BODY_DEADLINE_MS);\n\t\trequest.signal.addEventListener(\"abort\", stop, { once: true });\n\t\tif (request.signal.aborted) stop();\n\t});\n\ttry {\n\t\treturn await readChunks(request, reader, interrupted, maxBytes);\n\t} catch {\n\t\treturn null;\n\t} finally {\n\t\tclearTimeout(timer);\n\t\trequest.signal.removeEventListener(\"abort\", stop);\n\t\tvoid reader.cancel().catch(() => undefined);\n\t\treader.releaseLock();\n\t}\n}\n\nasync function readChunks(\n\trequest: Request,\n\treader: ReadableStreamDefaultReader<Uint8Array>,\n\tinterrupted: Promise<null>,\n\tmaxBytes: number,\n): Promise<Uint8Array | null> {\n\tconst bytes = new Uint8Array(maxBytes);\n\tlet size = 0;\n\tfor (;;) {\n\t\tconst next = await Promise.race([reader.read(), interrupted]);\n\t\tif (!next || request.signal.aborted) return null;\n\t\tif (next.done) {\n\t\t\tconst declared = request.headers.get(\"Content-Length\");\n\t\t\tif (declared !== null && Number(declared) !== size) return null;\n\t\t\treturn bytes.subarray(0, size);\n\t\t}\n\t\tif (!(next.value instanceof Uint8Array) || next.value.byteLength > maxBytes - size) return null;\n\t\tbytes.set(next.value, size);\n\t\tsize += next.value.byteLength;\n\t}\n}\n\nfunction parseJsonObject(bytes: Uint8Array): Record<string, unknown> | null {\n\ttry {\n\t\tconst value: unknown = JSON.parse(new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes));\n\t\treturn value && typeof value === \"object\" && !Array.isArray(value)\n\t\t\t? (value as Record<string, unknown>)\n\t\t\t: null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/** Private HTTP composition only: no sessions, provider discovery, or store startup. */\nexport function createOwnerQualificationHttp(options: {\n\tconfig: OwnerQualificationRouteDeps[\"config\"];\n\tbackend: OwnerQualificationRouteDeps[\"backend\"];\n\tadminSecret: string | null;\n\torigin: string | null;\n\tlimiter: InMemoryRequestRateLimiter;\n}) {\n\tconst captured = { ...options };\n\tconst handler = createOwnerQualificationHandler({\n\t\tconfig: captured.config,\n\t\tbackend: captured.backend,\n\t\tadminSecret: () => captured.adminSecret,\n\t\treadRequestBytes: readBody,\n\t\tparseJsonObject,\n\t\trateLimitedResponse: (c, key, { authenticated }) => {\n\t\t\tconst budget = captured.limiter.check(key, authenticated ? 20 : 60);\n\t\t\tif (!budget.allowed) {\n\t\t\t\tc.header(\"Retry-After\", String(budget.retryAfterS));\n\t\t\t\treturn c.json({ error: \"rate_limited\" }, 429);\n\t\t\t}\n\t\t\tif (!authenticated || !captured.config || !captured.backend) return null;\n\t\t\treturn transportError(c, captured.origin);\n\t\t},\n\t});\n\tconst app = new Hono();\n\tapp.all(OWNER_QUALIFICATION_PATH, handler);\n\treturn { fetch: (request: Request) => app.fetch(request) };\n}\n","import { AccountChangeOperations } from \"./coordinator-account-change.js\";\nimport {\n\ttype ConnectionSchemaState,\n\treadConnectionSchemaState,\n} from \"./coordinator-account-connection-schema.js\";\nimport { AccountLinkStatusOperations } from \"./coordinator-account-link-status.js\";\nimport { AccountOwnerTargetOperations } from \"./coordinator-account-owner-target.js\";\nimport {\n\tAuthAccountProfileOperations,\n\ttype CoordinatorAuthAccountProfileInput,\n} from \"./coordinator-auth-account-profile.js\";\nimport {\n\ttype CoordinatorAuthBrowserConfig,\n\ttype CoordinatorAuthBrowserTransactionConsumeInput,\n\ttype CoordinatorAuthBrowserTransactionMaintenanceOptions,\n\ttype CoordinatorAuthBrowserTransactionRetirementOptions,\n\ttype CoordinatorAuthBrowserTransactionScope,\n\ttype CoordinatorAuthBrowserTransactionStartInput,\n\tCoordinatorAuthBrowserTransactions,\n\ttype CoordinatorAuthLinkBrowserTransactionResolveInput,\n\ttype CoordinatorAuthSigninBrowserTransactionCancelInput,\n} from \"./coordinator-auth-browser-transaction.js\";\nimport {\n\tAUTH_CONTROLLER_ACTIVE_SQL,\n\tAUTH_CONTROLLER_CONFLICT_SQL,\n\tAUTH_CONTROLLER_CURRENT_ENROLLMENT_SQL,\n\tAUTH_CONTROLLER_ENROLLMENT_SQL,\n\tAUTH_CONTROLLER_INSERT_SQL,\n\tAUTH_CONTROLLER_RETRY_ACTIVE_SQL,\n\tAUTH_CONTROLLER_RETRY_ELIGIBLE_SQL,\n\tAUTH_CONTROLLER_REVOKE_SQL,\n\tauthControllerAuthorityValues,\n\tauthControllerConflictValues,\n\tauthControllerInsertValues,\n\tauthControllerRetryActiveValues,\n\tauthControllerRetryEligibleValues,\n\tauthControllerRetryResult,\n\tauthControllerReviewSql,\n\tauthControllerSubjectOwnerConflictValues,\n\tauthControllerUnavailableResult,\n\ttype CoordinatorAuthControllerAttestation,\n\ttype CoordinatorAuthControllerCreateResult,\n\ttype CoordinatorAuthControllerReviewInput,\n\ttype CoordinatorAuthControllerSubjectOwnerInput,\n\tcaptureAuthControllerReview,\n\tisAuthControllerId,\n\tisAuthControllerUniqueError,\n} from \"./coordinator-auth-controller.js\";\nimport {\n\ttype ControllerHistoryInput,\n\tcaptureControllerHistory,\n} from \"./coordinator-auth-controller-history.js\";\nimport { AUTH_CONTROLLER_SUBJECT_OWNER_CONFLICT_SQL } from \"./coordinator-auth-controller-owner.js\";\nimport {\n\ttype AuthLinkBackend,\n\tAuthLinkOperations,\n\ttype AuthLinkStatement,\n} from \"./coordinator-auth-link.js\";\nimport type {\n\tCoordinatorAuthLinkClaimInput,\n\tCoordinatorAuthLinkConfig,\n\tCoordinatorAuthLinkConfirmInput,\n\tCoordinatorAuthLinkCreateInput,\n\tCoordinatorAuthLinkFailInput,\n\tCoordinatorAuthLinkFinalizeInput,\n\tCoordinatorAuthLinkMaintenanceOptions,\n\tCoordinatorAuthLinkOidcInput,\n\tCoordinatorAuthLinkOptions,\n\tCoordinatorAuthLinkRequester,\n} from \"./coordinator-auth-link-contract.js\";\nimport {\n\tassertCoordinatorAuthSchema,\n\tCoordinatorAuthSchemaUpgradeRequiredError,\n\twithCoordinatorAuthSchema,\n} from \"./coordinator-auth-schema.js\";\nimport { AuthSessionOperations } from \"./coordinator-auth-session.js\";\nimport type {\n\tCoordinatorAuthAccountSignInInput,\n\tCoordinatorAuthBoundLinkSessionRedeemInput,\n\tCoordinatorAuthLinkSessionRedeemInput,\n\tCoordinatorAuthSessionPurgeOptions,\n\tCoordinatorAuthSessionScope,\n} from \"./coordinator-auth-session-contract.js\";\nimport {\n\tBOOTSTRAP_AUTHORIZATION_SOURCE_SQL,\n\ttype BootstrapAuthorizationRow,\n\tbootstrapAuthorizationDecision,\n\tbootstrapAuthorizationResult,\n\tbootstrapAuthorizationSourceError,\n\tcaptureBootstrapAuthorizationInput,\n\trejectBootstrapAuthorization,\n} from \"./coordinator-bootstrap-grant-authorization.js\";\nimport {\n\tBOOTSTRAP_PARTICIPANT_SOURCE_SQL,\n\tBOOTSTRAP_PARTICIPANTS_REVOKED_SQL,\n\tBOOTSTRAP_RAW_INSERT_SQL,\n\ttype BootstrapParticipantSource,\n\tbootstrapRawInsertValues,\n\tcaptureBootstrapParticipantSource,\n} from \"./coordinator-bootstrap-grant-issuance.js\";\nimport { readDeviceRebindBackend } from \"./coordinator-device-rebind-schema.js\";\nimport {\n\ttype CoordinatorCreateDeviceRevocationInput,\n\ttype CoordinatorListDeviceRevocationsInput,\n\ttype CoordinatorRecordAuthorizedNonceInput,\n\tDEVICE_REVOCATION_SUBJECT_EXISTS_SQL,\n\tDeviceRevocationOperations,\n} from \"./coordinator-device-revocation.js\";\nimport { ed25519KeyIdForRevocation } from \"./coordinator-ed25519-key-id-compat.js\";\nimport {\n\tENROLLMENT_OWNERSHIP_COLUMNS,\n\twithEnrollmentOwnership,\n} from \"./coordinator-enrollment-ownership.js\";\nimport {\n\ttype CoordinatorIdentityGroupGrant,\n\ttype CoordinatorIdentityGroupGrantIssueInput,\n\ttype CoordinatorIdentityGroupGrantIssueResult,\n\ttype CoordinatorIdentityGroupGrantRevokeInput,\n\ttype CoordinatorIdentityGroupGrantScope,\n\tcaptureIdentityGroupGrantInput,\n\tIDENTITY_GROUP_GRANT_INSERT_SQL,\n\tIDENTITY_GROUP_GRANT_LIST_SQL,\n\tIDENTITY_GROUP_GRANT_RETRY_SQL,\n\tIDENTITY_GROUP_GRANT_REVOKE_SQL,\n\tIDENTITY_GROUP_GRANT_SOURCE_SQL,\n} from \"./coordinator-identity-group-grant.js\";\nimport {\n\tassertJoinReviewConfirmation,\n\tJOIN_REVIEW_COLUMNS,\n\tjoinReviewGuardEvidence,\n\tjoinReviewResultChanges,\n} from \"./coordinator-join-review-guards.js\";\nimport {\n\tcaptureLegacyCompletionOwnerProof,\n\tlegacyCompletionOwnerProofSql,\n} from \"./coordinator-legacy-completion-owner-proof.js\";\nimport {\n\tassertLegacyDeviceScope,\n\tcaptureLegacyEnrollment,\n\tcaptureLegacyEnrollmentPublicKey,\n\tcaptureLegacyProjectInviteInput,\n\tDEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL,\n\tLEGACY_DEVICE_DENIAL_SQL,\n\tLEGACY_ENROLLMENT_DENIAL_SQL,\n\tLEGACY_ENROLLMENT_WRITE_SQL,\n\tlegacyDeviceAuthorizationFailure,\n\tlegacyDeviceDenial,\n\tlegacyDeviceWriteChanges,\n\tlegacyProjectInviteOwnershipEvidence,\n} from \"./coordinator-legacy-device-ownership.js\";\nimport {\n\tLEGACY_OWNER_INPUT_SQL,\n\tLEGACY_OWNER_KEYS_SQL,\n\tLEGACY_OWNER_SOURCE_CURRENT_SQL,\n\tlegacyCompletionWriteResult,\n\tlegacyOwnerKeyMetadata,\n} from \"./coordinator-legacy-owner-compatibility.js\";\nimport type {\n\tCoordinatorLegacyTeamCompletionManifestV1,\n\tCoordinatorLegacyTeamCompletionRecord,\n\tCoordinatorLegacyTeamCompletionScopeBinding,\n\tCoordinatorLegacyTeamCompletionWriteResult,\n} from \"./coordinator-legacy-team-completion.js\";\nimport {\n\tCOORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BATCH_BYTES,\n\tCOORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES,\n\tCOORDINATOR_LEGACY_TEAM_COMPLETION_MAX_RECORDS,\n\tCoordinatorLegacyTeamCompletionConflictError,\n\tcanonicalCoordinatorLegacyTeamCompletionManifestJson,\n\tnormalizeCoordinatorLegacyTeamCompletionCandidateRef,\n\tnormalizeCoordinatorLegacyTeamCompletionGroupIds,\n\tnormalizeCoordinatorLegacyTeamCompletionManifest,\n\trequireCoordinatorLegacyTeamCompletionScopeBindings,\n\trequireCoordinatorLegacyTeamCompletionTeamBinding,\n} from \"./coordinator-legacy-team-completion.js\";\nimport {\n\tassertMatchingMembershipEffectReceipt,\n\ttype CoordinatorMembershipEffectReceipt,\n\tCoordinatorMembershipError,\n\tgrantMembershipEffectRequestJson,\n\tmembershipFromEffectReceipt,\n\tnormalizeMembershipEffectId,\n\trevokeMembershipEffectRequestJson,\n} from \"./coordinator-membership-effects.js\";\nimport {\n\ttype NegativeOwnerConsistency,\n\tprepareNegativeOwnerConsistency,\n\twithNegativeOwnerConsistency,\n} from \"./coordinator-owner-negative-consistency.js\";\nimport { OwnerResolutionReviewOperations } from \"./coordinator-owner-resolution-review.js\";\nimport {\n\tCAPTURE_PEER_ENROLLMENTS_SQL,\n\ttype CapturedPeerEnrollment,\n\tcapturePeerEnrollments,\n\tREAD_CURRENT_PEERS_SQL,\n\trequirePeerDiscoveryRows,\n} from \"./coordinator-peer-discovery.js\";\nimport { projectInviteGuardEvidence } from \"./coordinator-project-invite-guards.js\";\nimport {\n\tassertRecipientOwnerConsistency,\n\tprepareRecipientOwnerConsistency,\n\trecipientOwnerWriteSql,\n\tvalidateRecipientOwnerInput,\n} from \"./coordinator-recipient-owner-consistency.js\";\nimport { ResolvedAccountOwnerStatusOperations } from \"./coordinator-resolved-account-owner-status.js\";\nimport {\n\ttype CapturedScopeMember,\n\tcaptureScopeAuthorizationInput,\n\tENROLLMENT_FIELDS,\n\tisCurrentScopeMember,\n\tMEMBERSHIP_FIELDS,\n\tparseScopeAuthorizationMembers,\n\tREAD_SCOPE_AUTHORIZATION_SQL,\n\trequireScopeAuthorizationRecord,\n\tSCOPE_FIELDS,\n\tscopeAuthorizationError,\n} from \"./coordinator-scope-authorization.js\";\nimport type {\n\tCoordinatorBootstrapGrant,\n\tCoordinatorBootstrapGrantAuthorizationInput,\n\tCoordinatorBootstrapGrantAuthorizationResult,\n\tCoordinatorConsumeProjectInviteInput,\n\tCoordinatorConsumeRecipientInviteInput,\n\tCoordinatorCreateBootstrapGrantInput,\n\tCoordinatorCreateInviteInput,\n\tCoordinatorCreateJoinRequestInput,\n\tCoordinatorCreateReciprocalApprovalInput,\n\tCoordinatorCreateScopeInput,\n\tCoordinatorEnrollDeviceInput,\n\tCoordinatorEnrollment,\n\tCoordinatorGrantScopeMembershipInput,\n\tCoordinatorGroup,\n\tCoordinatorInspectRecipientInviteInput,\n\tCoordinatorInvite,\n\tCoordinatorJoinRequest,\n\tCoordinatorJoinRequestReviewResult,\n\tCoordinatorListReciprocalApprovalsInput,\n\tCoordinatorListScopeMembershipAuditInput,\n\tCoordinatorListScopesInput,\n\tCoordinatorPeerRecord,\n\tCoordinatorPresenceRecord,\n\tCoordinatorProjectInviteAcceptance,\n\tCoordinatorRecipientInviteAcceptance,\n\tCoordinatorRecipientInviteInspection,\n\tCoordinatorReciprocalApproval,\n\tCoordinatorReviewJoinRequestInput,\n\tCoordinatorRevokeScopeMembershipInput,\n\tCoordinatorScope,\n\tCoordinatorScopeAuthorizationInput,\n\tCoordinatorScopeAuthorizationResult,\n\tCoordinatorScopeMembership,\n\tCoordinatorScopeMembershipAuditEvent,\n\tCoordinatorStore,\n\tCoordinatorUpdateScopeInput,\n\tCoordinatorUpsertPresenceInput,\n} from \"./coordinator-store-contract.js\";\nimport {\n\tCoordinatorReciprocalApprovalRequestChangedError,\n\tnormalizeInviteExpiresAt,\n\trecipientInviteAuthoritativeIdentityId,\n} from \"./coordinator-store-contract.js\";\nimport {\n\tclean,\n\tinspectCoordinatorRecipientInvite as inspectInvite,\n\tmergeCoordinatorAddresses,\n\tnormalizeCoordinatorAuditLimit,\n\tnormalizeCoordinatorBootstrapGrantInput,\n\tnormalizeCoordinatorBootstrapGrantRequest,\n\tnormalizeCoordinatorCreateScopeInput,\n\tnormalizeCoordinatorGrantScopeMembershipInput,\n\tnormalizeCoordinatorInviteMetadata,\n\tnormalizeCoordinatorUpdateScopeInput,\n\tnormalizeEpoch,\n} from \"./coordinator-store-input-rules.js\";\nimport { fingerprintPublicKey } from \"./sync-fingerprint.js\";\n\ninterface D1RunResultLike {\n\tmeta?: {\n\t\tchanges?: number;\n\t};\n}\n\n/**\n * Experimental D1 adapter scaffold.\n *\n * This is intentionally internal for now while the sync-only store contract\n * is still being validated against an async backend shape.\n */\n\nexport interface D1PreparedStatementLike {\n\tbind(...values: unknown[]): D1PreparedStatementLike;\n\tfirst<T = unknown>(): Promise<T | null>;\n\trun(): Promise<unknown>;\n\tall<T = unknown>(): Promise<{ results?: T[] }>;\n\traw<T = unknown>(): Promise<T[]>;\n}\n\nexport interface D1DatabaseLike {\n\tprepare(query: string): D1PreparedStatementLike;\n\tbatch?(statements: D1PreparedStatementLike[]): Promise<unknown[]>;\n\texec?(query: string): Promise<unknown>;\n}\n\nfunction rowToRecord<T>(row: unknown): T {\n\tif (row == null) throw new Error(\"expected row\");\n\treturn row as T;\n}\n\nfunction rowToEnrollmentWithPresence(row: unknown): CoordinatorEnrollment {\n\tconst record = rowToRecord<Record<string, unknown>>(row);\n\tconst {\n\t\tpresence_capabilities_json: capabilitiesJson,\n\t\tpresence_expires_at: expiresAt,\n\t\t...base\n\t} = record;\n\tif (typeof expiresAt !== \"string\" || typeof capabilitiesJson !== \"string\") {\n\t\treturn base as unknown as CoordinatorEnrollment;\n\t}\n\ttry {\n\t\tconst capabilities = JSON.parse(capabilitiesJson) as unknown;\n\t\tif (!capabilities || typeof capabilities !== \"object\" || Array.isArray(capabilities)) {\n\t\t\treturn base as unknown as CoordinatorEnrollment;\n\t\t}\n\t\tconst capabilityRecord = capabilities as Record<string, unknown>;\n\t\treturn {\n\t\t\t...(base as unknown as CoordinatorEnrollment),\n\t\t\tpresence_expires_at: expiresAt,\n\t\t\tpresence_capabilities: {\n\t\t\t\tsync_capability: capabilityRecord.sync_capability,\n\t\t\t\tsync_features: capabilityRecord.sync_features,\n\t\t\t},\n\t\t};\n\t} catch {\n\t\treturn base as unknown as CoordinatorEnrollment;\n\t}\n}\n\nfunction nowISO(): string {\n\treturn new Date().toISOString();\n}\n\nfunction reciprocalPendingPair(\n\trequestingDeviceId: string,\n\trequestedDeviceId: string,\n): {\n\tlow: string;\n\thigh: string;\n} {\n\treturn requestingDeviceId <= requestedDeviceId\n\t\t? { low: requestingDeviceId, high: requestedDeviceId }\n\t\t: { low: requestedDeviceId, high: requestingDeviceId };\n}\n\nfunction isUniqueConstraintError(error: unknown): boolean {\n\treturn error instanceof Error && /unique|constraint/i.test(error.message);\n}\n\nfunction tokenUrlSafe(bytes: number): string {\n\tconst alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\";\n\tconst random = new Uint8Array(bytes);\n\tglobalThis.crypto.getRandomValues(random);\n\tconst output: string[] = [];\n\tfor (const byte of random) {\n\t\toutput.push(alphabet[byte % alphabet.length] ?? \"A\");\n\t}\n\treturn output.join(\"\");\n}\n\nasync function tokenDigest(token: string): Promise<string> {\n\tconst digest = await globalThis.crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(token));\n\treturn Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nconst INVITE_COLUMNS = `invite_id, group_id, token, policy, expires_at, created_at, created_by,\n\tteam_name_snapshot, revoked_at, operation_id, reviewed_project_set_digest, token_digest,\n\tinviter_actor_id, inviter_display_name, inviter_device_id, pending_person_id,\n\tproject_summaries_json, project_intent_json, consumed_at, bound_device_id, bound_public_key, bound_fingerprint,\n\trecipient_actor_id, recipient_display_name, recipient_device_display_name, trust_state,\n\tbootstrap_grant_id, invite_kind, policy_team_id, target_identity_id, assigned_identity_id,\n\treviewed_preview_digest, reviewed_intent_json`;\n\nconst ENROLLMENT_COLUMNS =\n\t\"group_id, device_id, public_key, fingerprint, identity_id, display_name, enabled, created_at\";\n\nconst ENROLLMENT_PRESENCE_COLUMNS = `enrolled_devices.group_id, enrolled_devices.device_id,\n\tenrolled_devices.public_key, enrolled_devices.fingerprint, enrolled_devices.identity_id,\n\tenrolled_devices.display_name, enrolled_devices.enabled, enrolled_devices.created_at,\n\tpresence_records.expires_at AS presence_expires_at,\n\tpresence_records.capabilities_json AS presence_capabilities_json`;\n\nfunction prepareMembershipAuditFromCurrentRow(\n\tdb: D1DatabaseLike,\n\tinput: {\n\t\teffectId: string;\n\t\trequestJson: string;\n\t\taction: \"grant\" | \"revoke\";\n\t\tprevious: CoordinatorScopeMembership | null;\n\t\tscopeId: string;\n\t\tdeviceId: string;\n\t\tstatus: string;\n\t\tmembershipEpoch: number;\n\t\tupdatedAt: string;\n\t\tactorType: string | null;\n\t\tactorId: string | null;\n\t\tcreatedAt: string;\n\t},\n): D1PreparedStatementLike {\n\t// The immediately preceding statement inserts the immutable effect receipt.\n\t// changes() therefore emits an audit row only for the request that won the\n\t// receipt insert, while outcome_applied excludes persisted no-op revokes.\n\treturn db\n\t\t.prepare(`INSERT INTO coordinator_scope_membership_audit_log(\n\t\t\teffect_id, action, scope_id, device_id, role, status, membership_epoch,\n\t\t\tprevious_role, previous_status, previous_membership_epoch,\n\t\t\tcoordinator_id, group_id, actor_type, actor_id, manifest_hash, created_at\n\t\t)\n\t\tSELECT receipt.effect_id, ?, membership.scope_id, membership.device_id, membership.role, membership.status,\n\t\t\tmembership.membership_epoch, ?, ?, ?, membership.coordinator_id, membership.group_id,\n\t\t\t?, ?, membership.manifest_hash, ?\n\t\tFROM (SELECT 1 WHERE changes() > 0) AS required\n\t\tJOIN coordinator_scope_membership_effect_receipts AS receipt\n\t\t\tON receipt.effect_id = ? AND receipt.action = ? AND receipt.request_json = ?\n\t\t\tAND receipt.outcome_applied = 1\n\t\tLEFT JOIN coordinator_scope_memberships AS membership\n\t\t\tON membership.scope_id = ?\n\t\t\tAND membership.device_id = ?\n\t\t\tAND membership.status = ?\n\t\t\tAND membership.membership_epoch = ?\n\t\t\tAND membership.updated_at = ?`)\n\t\t.bind(\n\t\t\tinput.action,\n\t\t\tinput.previous?.role ?? null,\n\t\t\tinput.previous?.status ?? null,\n\t\t\tinput.previous?.membership_epoch ?? null,\n\t\t\tinput.actorType,\n\t\t\tinput.actorId,\n\t\t\tinput.createdAt,\n\t\t\tinput.effectId,\n\t\t\tinput.action,\n\t\t\tinput.requestJson,\n\t\t\tinput.scopeId,\n\t\t\tinput.deviceId,\n\t\t\tinput.status,\n\t\t\tinput.membershipEpoch,\n\t\t\tinput.updatedAt,\n\t\t);\n}\n\nasync function getMembershipEffectReceipt(\n\tdb: D1DatabaseLike,\n\teffectId: string,\n): Promise<CoordinatorMembershipEffectReceipt | null> {\n\treturn await firstRow<CoordinatorMembershipEffectReceipt>(\n\t\tdb\n\t\t\t.prepare(`SELECT effect_id, action, request_json, outcome_applied, scope_id, device_id,\n\t\t\t\trole, status, membership_epoch, coordinator_id, group_id, manifest_issuer_device_id,\n\t\t\t\tmanifest_hash, signed_manifest_json, updated_at, created_at\n\t\t\t FROM coordinator_scope_membership_effect_receipts WHERE effect_id = ?`)\n\t\t\t.bind(effectId),\n\t);\n}\n\nfunction prepareGrantEffectReceipt(\n\tdb: D1DatabaseLike,\n\tinput: {\n\t\teffectId: string;\n\t\trequestJson: string;\n\t\tscopeId: string;\n\t\tdeviceId: string;\n\t\tcreatedAt: string;\n\t},\n): D1PreparedStatementLike {\n\treturn db\n\t\t.prepare(`INSERT INTO coordinator_scope_membership_effect_receipts(\n\t\t\teffect_id, action, request_json, outcome_applied, scope_id, device_id,\n\t\t\trole, status, membership_epoch, coordinator_id, group_id, manifest_issuer_device_id,\n\t\t\tmanifest_hash, signed_manifest_json, updated_at, created_at\n\t\t)\n\t\tSELECT ?, 'grant', ?, 1, membership.scope_id, membership.device_id,\n\t\t\tmembership.role, membership.status, membership.membership_epoch,\n\t\t\tmembership.coordinator_id, membership.group_id, membership.manifest_issuer_device_id,\n\t\t\tmembership.manifest_hash, membership.signed_manifest_json, membership.updated_at, ?\n\t\tFROM coordinator_scope_memberships AS membership\n\t\tWHERE changes() > 0 AND membership.scope_id = ? AND membership.device_id = ?`)\n\t\t.bind(input.effectId, input.requestJson, input.createdAt, input.scopeId, input.deviceId);\n}\n\nfunction prepareRevokeEffectReceipt(\n\tdb: D1DatabaseLike,\n\tinput: {\n\t\teffectId: string;\n\t\trequestJson: string;\n\t\tscopeId: string;\n\t\tdeviceId: string;\n\t\tcreatedAt: string;\n\t},\n): D1PreparedStatementLike {\n\treturn db\n\t\t.prepare(`INSERT INTO coordinator_scope_membership_effect_receipts(\n\t\t\teffect_id, action, request_json, outcome_applied, scope_id, device_id,\n\t\t\trole, status, membership_epoch, coordinator_id, group_id, manifest_issuer_device_id,\n\t\t\tmanifest_hash, signed_manifest_json, updated_at, created_at\n\t\t)\n\t\tSELECT ?, 'revoke', ?, changed.applied, ?, ?, membership.role, membership.status,\n\t\t\tmembership.membership_epoch, membership.coordinator_id, membership.group_id,\n\t\t\tmembership.manifest_issuer_device_id, membership.manifest_hash,\n\t\t\tmembership.signed_manifest_json, membership.updated_at, ?\n\t\tFROM (SELECT CASE WHEN changes() > 0 THEN 1 ELSE 0 END AS applied) AS changed\n\t\tLEFT JOIN coordinator_scope_memberships AS membership\n\t\t\tON changed.applied = 1 AND membership.scope_id = ? AND membership.device_id = ?\n\t\tWHERE NOT EXISTS (\n\t\t\tSELECT 1 FROM coordinator_scope_membership_effect_receipts WHERE effect_id = ?\n\t\t)`)\n\t\t.bind(\n\t\t\tinput.effectId,\n\t\t\tinput.requestJson,\n\t\t\tinput.scopeId,\n\t\t\tinput.deviceId,\n\t\t\tinput.createdAt,\n\t\t\tinput.scopeId,\n\t\t\tinput.deviceId,\n\t\t\tinput.effectId,\n\t\t);\n}\n\nasync function runAuditedBatch(\n\tdb: D1DatabaseLike,\n\tstatements: D1PreparedStatementLike[],\n): Promise<unknown[]> {\n\tif (!db.batch) {\n\t\tthrow new Error(\"D1 batch support is required for audited scope membership changes.\");\n\t}\n\treturn await db.batch(statements);\n}\n\nfunction batchResultChanges(result: unknown): number {\n\treturn Number((result as D1RunResultLike | undefined)?.meta?.changes ?? 0);\n}\n\n/** Narrow SQL capability; multi-statement writes require D1's atomic batch. */\nexport function createD1AuthLinkBackend(\n\tdb: D1DatabaseLike,\n\toptions: { connections?: boolean } = {},\n): AuthLinkBackend {\n\treturn withCoordinatorAuthSchema(createRawD1AuthLinkBackend(db), options);\n}\n\n/** No auth-schema check per statement; callers gate on their own tables. */\nfunction createRawD1AuthLinkBackend(db: D1DatabaseLike): AuthLinkBackend {\n\treturn {\n\t\tfirst: <T>(statement: AuthLinkStatement) =>\n\t\t\tdb\n\t\t\t\t.prepare(statement.sql)\n\t\t\t\t.bind(...statement.values)\n\t\t\t\t.first<T>(),\n\t\tall: async <T>(statement: AuthLinkStatement) => {\n\t\t\tconst result = await db\n\t\t\t\t.prepare(statement.sql)\n\t\t\t\t.bind(...statement.values)\n\t\t\t\t.all<T>();\n\t\t\tif (!Array.isArray(result.results)) throw new Error(\"ownership_evidence_reader_unavailable\");\n\t\t\treturn result.results;\n\t\t},\n\t\trun: (statement) => runChanges(db.prepare(statement.sql).bind(...statement.values)),\n\t\tbatch: async (statements) => {\n\t\t\tif (!db.batch) throw new Error(\"auth_link_atomic_batch_required\");\n\t\t\tconst results = await db.batch(\n\t\t\t\tstatements.map((statement) => db.prepare(statement.sql).bind(...statement.values)),\n\t\t\t);\n\t\t\treturn results.map(batchResultChanges);\n\t\t},\n\t};\n}\n\nasync function allRows<T>(statement: D1PreparedStatementLike): Promise<T[]> {\n\tconst result = await statement.all<T>();\n\treturn Array.isArray(result?.results) ? result.results : [];\n}\n\nasync function firstRow<T>(statement: D1PreparedStatementLike): Promise<T | null> {\n\treturn await statement.first<T>();\n}\n\nfunction requireScopeAuthorizationRows<T>(result: { results?: T[] }): T[] {\n\t// A lost read receipt is not an empty authority source.\n\tif (\n\t\t!result ||\n\t\tArray.isArray(result) ||\n\t\t(\"success\" in result && result.success !== true) ||\n\t\t!Array.isArray(result.results)\n\t)\n\t\tthrow new Error(\"scope_authorization_unavailable\");\n\treturn result.results;\n}\n\nasync function runChanges(statement: D1PreparedStatementLike): Promise<number> {\n\tconst result = (await statement.run()) as D1RunResultLike | undefined;\n\treturn Number(result?.meta?.changes ?? 0);\n}\n\nconst RECIPIENT_REVOCATION_SQL = `${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL}\n\tOR ${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL}`;\nconst RECIPIENT_OWNERSHIP_SQL = DEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL;\n// Each sensitive statement pins the evidence used to derive the inviter's canonical key.\n// Zero-row changes do not abort a D1 batch; downstream statements own the same guard.\nconst RECIPIENT_ELIGIBILITY_SQL = `EXISTS (\n\tSELECT 1 FROM coordinator_invites ri\n\tJOIN groups rg ON rg.group_id = ri.group_id AND rg.archived_at IS NULL\n\tWHERE ri.invite_id = ? AND ri.group_id = ? AND ri.revoked_at IS NULL\n\tAND ri.invite_kind = ? AND ri.reviewed_intent_json IS ?\n\tAND ri.reviewed_preview_digest IS ? AND ri.policy_team_id IS ?\n\tAND ri.target_identity_id IS ? AND ri.assigned_identity_id IS ?\n\tAND ri.inviter_device_id IS ?\n\tAND ri.token_digest IS ? AND (ri.token = ? OR ri.token = 'consumed:' || ri.invite_id)\n\tAND (ri.consumed_at IS NULL OR (ri.bound_device_id = ? AND ri.bound_public_key = ?\n\t\tAND ri.bound_fingerprint = ? AND ri.recipient_actor_id = ?))\n\tAND ((? = 0 AND NOT EXISTS (SELECT 1 FROM enrolled_devices se\n\t\tWHERE se.group_id = ri.group_id AND se.device_id = ri.inviter_device_id))\n\t\tOR (? = 1 AND EXISTS (SELECT 1 FROM enrolled_devices se\n\t\t\tWHERE se.group_id = ri.group_id AND se.device_id = ri.inviter_device_id\n\t\t\tAND se.public_key = ? AND se.fingerprint = ? AND se.enabled = ?)))\n\tAND NOT EXISTS (SELECT 1 FROM enrolled_devices re\n\t\tWHERE re.group_id = ri.group_id AND re.device_id = ?\n\t\tAND (re.public_key <> ? OR re.fingerprint <> ?\n\t\t\tOR (re.identity_id IS NOT NULL AND re.identity_id <> ?)))\n\tAND NOT (${RECIPIENT_REVOCATION_SQL}) AND NOT (${RECIPIENT_OWNERSHIP_SQL}))`;\nconst RECIPIENT_BINDING_SQL = `EXISTS (SELECT 1 FROM coordinator_invites bi\n\tWHERE bi.invite_id = ? AND bi.consumed_at IS NOT NULL\n\tAND bi.bound_device_id = ? AND bi.bound_public_key = ?\n\tAND bi.bound_fingerprint = ? AND bi.recipient_actor_id = ?)`;\n\nfunction validateRecipientEnrollmentTuple(\n\tenrollment: CoordinatorEnrollment | null,\n\topts: Pick<CoordinatorConsumeRecipientInviteInput, \"publicKey\" | \"fingerprint\" | \"identityId\">,\n): void {\n\tif (!enrollment) return;\n\tif (\n\t\tenrollment.public_key !== opts.publicKey ||\n\t\tenrollment.fingerprint !== opts.fingerprint ||\n\t\t(enrollment.identity_id !== null && enrollment.identity_id !== opts.identityId)\n\t) {\n\t\tthrow new Error(\"invite_identity_conflict\");\n\t}\n}\n\nfunction validateRecipientInviteBinding(\n\tinvite: Pick<\n\t\tCoordinatorInvite,\n\t\t| \"consumed_at\"\n\t\t| \"bound_device_id\"\n\t\t| \"bound_public_key\"\n\t\t| \"bound_fingerprint\"\n\t\t| \"recipient_actor_id\"\n\t>,\n\topts: Pick<\n\t\tCoordinatorConsumeRecipientInviteInput,\n\t\t\"deviceId\" | \"publicKey\" | \"fingerprint\" | \"identityId\"\n\t>,\n\toptions: { requireBinding: boolean },\n): void {\n\tif (!invite.consumed_at && !options.requireBinding) return;\n\tif (\n\t\tinvite.bound_device_id !== opts.deviceId ||\n\t\tinvite.bound_public_key !== opts.publicKey ||\n\t\tinvite.bound_fingerprint !== opts.fingerprint\n\t)\n\t\tthrow new Error(\"invite_already_bound\");\n\tif (invite.recipient_actor_id !== opts.identityId) throw new Error(\"invite_identity_conflict\");\n}\n\nfunction validateAcceptedRecipientEnrollment(\n\tenrollment: CoordinatorEnrollment | null,\n\topts: CoordinatorConsumeRecipientInviteInput,\n): void {\n\tif (!enrollment) throw new Error(\"invite_acceptance_incomplete\");\n\tvalidateRecipientEnrollmentTuple(enrollment, opts);\n\tif (enrollment.identity_id !== opts.identityId) throw new Error(\"invite_identity_conflict\");\n}\n\nfunction recipientInviteGuardEvidence(\n\tinitial: CoordinatorInvite,\n\topts: CoordinatorConsumeRecipientInviteInput,\n\tinviter: CoordinatorEnrollment | null,\n\tkeyIds: { recipient: string | null; inviter: string | null },\n) {\n\tconst revocationValues = [\n\t\topts.deviceId,\n\t\tkeyIds.recipient,\n\t\tinitial.inviter_device_id,\n\t\tkeyIds.inviter,\n\t];\n\t// Only the recipient enrollment is mutated; inviter ownership is not transferred.\n\tconst ownershipValues = [opts.deviceId, keyIds.recipient];\n\tconst eligibilityValues = [\n\t\tinitial.invite_id,\n\t\tinitial.group_id,\n\t\topts.inviteKind,\n\t\tinitial.reviewed_intent_json,\n\t\tinitial.reviewed_preview_digest,\n\t\tinitial.policy_team_id,\n\t\tinitial.target_identity_id,\n\t\tinitial.assigned_identity_id,\n\t\tinitial.inviter_device_id,\n\t\tinitial.token_digest,\n\t\tinitial.token,\n\t\topts.deviceId,\n\t\topts.publicKey,\n\t\topts.fingerprint,\n\t\topts.identityId,\n\t\tinviter ? 1 : 0,\n\t\tinviter ? 1 : 0,\n\t\tinviter?.public_key ?? null,\n\t\tinviter?.fingerprint ?? null,\n\t\tinviter?.enabled ?? null,\n\t\topts.deviceId,\n\t\topts.publicKey,\n\t\topts.fingerprint,\n\t\topts.identityId,\n\t\t...revocationValues,\n\t\t...ownershipValues,\n\t];\n\tconst bindingValues = [\n\t\tinitial.invite_id,\n\t\topts.deviceId,\n\t\topts.publicKey,\n\t\topts.fingerprint,\n\t\topts.identityId,\n\t];\n\treturn {\n\t\trevocationValues,\n\t\townershipValues,\n\t\teligibilitySql: RECIPIENT_ELIGIBILITY_SQL,\n\t\teligibilityValues,\n\t\tboundEligibilitySql: `${RECIPIENT_ELIGIBILITY_SQL} AND ${RECIPIENT_BINDING_SQL}`,\n\t\tboundEligibilityValues: [...eligibilityValues, ...bindingValues],\n\t};\n}\n\nasync function readRecipientInviteDecision<K extends string>(\n\tprepare: () => D1PreparedStatementLike,\n\tfields: K[],\n): Promise<Record<K, number>> {\n\ttry {\n\t\tconst row = await firstRow<Record<K, number>>(prepare());\n\t\tif (\n\t\t\t!row ||\n\t\t\t(\"success\" in row && row.success === false) ||\n\t\t\tfields.some((field) => row[field] !== 0 && row[field] !== 1)\n\t\t)\n\t\t\tthrow new Error(\"device_ownership_authorization_unavailable\");\n\t\treturn row;\n\t} catch {\n\t\tthrow new Error(\"device_ownership_authorization_unavailable\");\n\t}\n}\n\nasync function prepareRecipientInviteGuards(\n\tdb: D1DatabaseLike,\n\tinitial: CoordinatorInvite,\n\topts: CoordinatorConsumeRecipientInviteInput,\n) {\n\tconst recipientKeyId = await ed25519KeyIdForRevocation(opts.publicKey);\n\tconst inviterRow = initial.inviter_device_id\n\t\t? await firstRow<CoordinatorEnrollment>(\n\t\t\t\tdb\n\t\t\t\t\t.prepare(`SELECT ${ENROLLMENT_COLUMNS}\n\t\t\tFROM enrolled_devices WHERE group_id = ? AND device_id = ?`)\n\t\t\t\t\t.bind(initial.group_id, initial.inviter_device_id),\n\t\t\t)\n\t\t: null;\n\tconst inviter = inviterRow ? { ...inviterRow } : null;\n\tconst inviterKeyId = inviter ? await ed25519KeyIdForRevocation(inviter.public_key) : null;\n\tconst evidence = recipientInviteGuardEvidence(initial, opts, inviter, {\n\t\trecipient: recipientKeyId,\n\t\tinviter: inviterKeyId,\n\t});\n\tconst assertEligible = async (options: { requireBinding: boolean }): Promise<void> => {\n\t\tconst sql = options.requireBinding\n\t\t\t? `${evidence.boundEligibilitySql} AND EXISTS (SELECT 1 FROM enrolled_devices\n\t\t\t\tWHERE group_id = ? AND device_id = ? AND public_key = ? AND fingerprint = ? AND enabled = 1)`\n\t\t\t: evidence.eligibilitySql;\n\t\tconst values = options.requireBinding\n\t\t\t? [\n\t\t\t\t\t...evidence.boundEligibilityValues,\n\t\t\t\t\tinitial.group_id,\n\t\t\t\t\topts.deviceId,\n\t\t\t\t\topts.publicKey,\n\t\t\t\t\topts.fingerprint,\n\t\t\t\t]\n\t\t\t: evidence.eligibilityValues;\n\t\tconst revocation = await readRecipientInviteDecision(\n\t\t\t() =>\n\t\t\t\tdb\n\t\t\t\t\t.prepare(`SELECT (${RECIPIENT_REVOCATION_SQL}) AS revoked`)\n\t\t\t\t\t.bind(...evidence.revocationValues),\n\t\t\t[\"revoked\"],\n\t\t);\n\t\tif (revocation.revoked === 1) throw new Error(\"device_revoked\");\n\t\tconst row = await readRecipientInviteDecision(\n\t\t\t() =>\n\t\t\t\tdb\n\t\t\t\t\t.prepare(`SELECT (${RECIPIENT_REVOCATION_SQL}) AS revoked,\n\t\t\t\t(${RECIPIENT_OWNERSHIP_SQL}) AS owned, (${sql}) AS eligible`)\n\t\t\t\t\t.bind(...evidence.revocationValues, ...evidence.ownershipValues, ...values),\n\t\t\t[\"revoked\", \"owned\", \"eligible\"],\n\t\t);\n\t\tif (row.revoked === 1) throw new Error(\"device_revoked\");\n\t\tif (row.eligible === 0) {\n\t\t\tawait rejectStaleRecipientInviteEvidence(db, initial, opts, recipientKeyId, {\n\t\t\t\towned: row.owned === 1,\n\t\t\t});\n\t\t}\n\t};\n\treturn { ...evidence, assertEligible };\n}\n\nasync function runRecipientInviteBatch(\n\tdb: D1DatabaseLike,\n\tstatements: D1PreparedStatementLike[],\n\tguard: {\n\t\tsql: string;\n\t\tvalues: unknown[];\n\t\tassertEligible: (options: { requireBinding: boolean }) => Promise<void>;\n\t\tnegative?: AuthLinkStatement;\n\t},\n): Promise<number> {\n\tif (!db.batch) throw new Error(\"device_ownership_authorization_unavailable\");\n\tconst negative = guard.negative ?? { sql: \"SELECT 1 AS matches\", values: [] };\n\ttry {\n\t\tconst results = await db.batch([\n\t\t\t...statements,\n\t\t\tdb\n\t\t\t\t.prepare(`WITH recipient_negative AS MATERIALIZED (${negative.sql})\n SELECT CASE WHEN (${guard.sql}) AND (SELECT matches FROM recipient_negative)\n THEN 1 ELSE json('recipient_invite_authorization_failed') END AS confirmed`)\n\t\t\t\t.bind(...negative.values, ...guard.values),\n\t\t]);\n\t\tconst confirmation = results[statements.length] as\n\t\t\t| { results?: { confirmed?: unknown }[] }\n\t\t\t| undefined;\n\t\tif (legacyDeviceWriteChanges(confirmation) !== 0 || confirmation?.results?.[0]?.confirmed !== 1)\n\t\t\tthrow new Error(\"device_ownership_authorization_unavailable\");\n\t\tfor (const result of results.slice(0, statements.length)) legacyDeviceWriteChanges(result);\n\t\treturn legacyDeviceWriteChanges(results[0]);\n\t} catch {\n\t\t// A SQL assertion rolls back the batch; malformed metadata may arrive after commit.\n\t\tawait guard.assertEligible({ requireBinding: false });\n\t\tthrow new Error(\"device_ownership_authorization_unavailable\");\n\t}\n}\n\nfunction prepareRecipientOwnerStatement(\n\tdb: D1DatabaseLike,\n\tsql: string,\n\tnegative?: AuthLinkStatement,\n) {\n\tconst statement = db.prepare(negative ? recipientOwnerWriteSql(sql, negative) : sql);\n\treturn { bind: (...values: unknown[]) => statement.bind(...(negative?.values ?? []), ...values) };\n}\n\nfunction createRecipientOwnerBackend(db: D1DatabaseLike) {\n\treturn {\n\t\tfirst: <T>({ sql, values }: AuthLinkStatement) =>\n\t\t\tdb\n\t\t\t\t.prepare(sql)\n\t\t\t\t.bind(...values)\n\t\t\t\t.first<T>(),\n\t\tall: async <T>({ sql, values }: AuthLinkStatement) => {\n\t\t\tconst result = await db\n\t\t\t\t.prepare(sql)\n\t\t\t\t.bind(...values)\n\t\t\t\t.all<T>();\n\t\t\tif (!Array.isArray(result.results)) throw new Error(\"ownership_evidence_reader_unavailable\");\n\t\t\treturn result.results;\n\t\t},\n\t};\n}\n\nasync function repairBoundRecipientInviteIdentity(\n\tdb: D1DatabaseLike,\n\topts: CoordinatorConsumeRecipientInviteInput,\n\tinvite: CoordinatorInvite,\n\tguard: Parameters<typeof runRecipientInviteBatch>[2],\n\tfirstWrite: { winningChanges: number; consistency: NegativeOwnerConsistency },\n): Promise<AuthLinkStatement> {\n\tvalidateRecipientInviteBinding(invite, opts, { requireBinding: true });\n\t// A zero-row token UPDATE (including another invocation's winner) did\n\t// not consume this invocation's full initial evidence pin.\n\tconst firstWriteNegative =\n\t\tfirstWrite.winningChanges === 1\n\t\t\t? firstWrite.consistency.retainedRecheck\n\t\t\t: firstWrite.consistency;\n\tconst repaired = await runRecipientInviteBatch(\n\t\tdb,\n\t\t[\n\t\t\tprepareRecipientOwnerStatement(\n\t\t\t\tdb,\n\t\t\t\t`UPDATE enrolled_devices SET identity_id = ?\n\t\tWHERE group_id = ? AND device_id = ? AND identity_id IS NULL\n\t\tAND public_key = ? AND fingerprint = ? AND ${guard.sql}`,\n\t\t\t\tfirstWriteNegative,\n\t\t\t).bind(\n\t\t\t\topts.identityId,\n\t\t\t\tinvite.group_id,\n\t\t\t\topts.deviceId,\n\t\t\t\topts.publicKey,\n\t\t\t\topts.fingerprint,\n\t\t\t\t...guard.values,\n\t\t\t),\n\t\t],\n\t\t{\n\t\t\t...guard,\n\t\t\tnegative: {\n\t\t\t\t// Only the immediately preceding identity UPDATE can consume the full pin.\n\t\t\t\t// A no-op must still check it inside this batch, then carry it to recovery.\n\t\t\t\tsql: `SELECT (changes() = 1 OR (SELECT matches FROM (${firstWriteNegative.sql})))\n\t\t\t\tAND (SELECT matches FROM (${firstWrite.consistency.retainedRecheck.sql})) AS matches`,\n\t\t\t\tvalues: [...firstWriteNegative.values, ...firstWrite.consistency.retainedRecheck.values],\n\t\t\t},\n\t\t},\n\t);\n\treturn repaired === 1 ? firstWrite.consistency.retainedRecheck : firstWriteNegative;\n}\n\nasync function rejectStaleRecipientInviteEvidence(\n\tdb: D1DatabaseLike,\n\tinvite: CoordinatorInvite,\n\topts: Pick<\n\t\tCoordinatorConsumeRecipientInviteInput,\n\t\t\"deviceId\" | \"publicKey\" | \"fingerprint\" | \"identityId\"\n\t>,\n\trecipientKeyId: string | null,\n\toptions: { owned?: boolean } = {},\n): Promise<never> {\n\tconst current = await firstRow<{ public_key: string }>(\n\t\tdb\n\t\t\t.prepare(`SELECT public_key\n\t\tFROM enrolled_devices WHERE group_id = ? AND device_id = ?`)\n\t\t\t.bind(invite.group_id, invite.inviter_device_id),\n\t);\n\tconst currentKeyId = current ? await ed25519KeyIdForRevocation(current.public_key) : null;\n\tconst revoked = await firstRow<{ revoked: number }>(\n\t\tdb\n\t\t\t.prepare(`SELECT 1 AS revoked\n\t\tWHERE ${RECIPIENT_REVOCATION_SQL}`)\n\t\t\t.bind(opts.deviceId, recipientKeyId, invite.inviter_device_id, currentKeyId),\n\t);\n\tif (revoked) throw new Error(\"device_revoked\");\n\t// These fresh reads classify denial only; they never replace the pinned write evidence.\n\tconst state = await firstRow<{\n\t\trevoked_at: string | null;\n\t\tcurrent_group_id: string | null;\n\t\tarchived_at: string | null;\n\t\tconsumed_at: string | null;\n\t\tbound_device_id: string | null;\n\t\tbound_public_key: string | null;\n\t\tbound_fingerprint: string | null;\n\t\trecipient_actor_id: string | null;\n\t}>(\n\t\tdb\n\t\t\t.prepare(`SELECT i.revoked_at, g.group_id AS current_group_id, g.archived_at,\n\t\t\ti.consumed_at, i.bound_device_id, i.bound_public_key, i.bound_fingerprint, i.recipient_actor_id\n\t\t\tFROM coordinator_invites i LEFT JOIN groups g ON g.group_id = i.group_id\n\t\t\tWHERE i.invite_id = ?`)\n\t\t\t.bind(invite.invite_id),\n\t);\n\tif (!state || state.revoked_at) throw new Error(\"invite_invalid\");\n\tif (state.current_group_id === null) throw new Error(\"group_not_found\");\n\tif (state.archived_at) throw new Error(\"group_archived\");\n\tif (options.owned) throw new Error(\"device_ownership_requires_verified_identity\");\n\tvalidateRecipientInviteBinding(state, opts, { requireBinding: false });\n\tthrow new Error(\"invite_acceptance_incomplete\");\n}\n\nfunction prepareProjectInviteDecision(\n\tdb: D1DatabaseLike,\n\tinitial: CoordinatorInvite,\n\topts: CoordinatorConsumeProjectInviteInput,\n\tguard: ReturnType<typeof legacyProjectInviteOwnershipEvidence>,\n\toptions: { requireBinding: boolean },\n): D1PreparedStatementLike {\n\tconst sql = options.requireBinding ? guard.boundEligibilitySql : guard.eligibilitySql;\n\tconst values = options.requireBinding ? guard.boundEligibilityValues : guard.eligibilityValues;\n\tconst enrollmentSql =\n\t\tinitial.consumed_at || options.requireBinding ? PROJECT_INVITE_ACTIVE_ENROLLMENT_SQL : \"1\";\n\tconst enrollmentValues = enrollmentSql === \"1\" ? [] : [initial.group_id, opts.deviceId];\n\treturn db\n\t\t.prepare(`SELECT (${guard.revocationSql}) AS revoked, (${guard.ownershipSql}) AS owned,\n\t\t(${sql} AND ${enrollmentSql}) AS eligible`)\n\t\t.bind(...guard.revocationValues, ...guard.ownershipValues, ...values, ...enrollmentValues);\n}\n\nasync function prepareProjectInviteGuards(\n\tdb: D1DatabaseLike,\n\tinitial: CoordinatorInvite,\n\topts: CoordinatorConsumeProjectInviteInput,\n) {\n\tconst participantOpts = { ...opts, identityId: opts.recipientActorId };\n\tconst enrollmentRow = await firstRow<CoordinatorEnrollment>(\n\t\tdb\n\t\t\t.prepare(\n\t\t\t\t`SELECT ${ENROLLMENT_COLUMNS} FROM enrolled_devices WHERE group_id = ? AND device_id = ?`,\n\t\t\t)\n\t\t\t.bind(initial.group_id, opts.deviceId),\n\t);\n\tconst currentPublicKey = captureLegacyEnrollmentPublicKey(enrollmentRow);\n\tconst enrollment = enrollmentRow ? { ...enrollmentRow } : null;\n\tconst recipientKeyId = await ed25519KeyIdForRevocation(opts.publicKey);\n\tconst currentKeyId =\n\t\tcurrentPublicKey === null ? null : await ed25519KeyIdForRevocation(currentPublicKey);\n\tconst inviterRow = initial.inviter_device_id\n\t\t? await firstRow<CoordinatorEnrollment>(\n\t\t\t\tdb\n\t\t\t\t\t.prepare(`SELECT ${ENROLLMENT_COLUMNS}\n\t\t\tFROM enrolled_devices WHERE group_id = ? AND device_id = ?`)\n\t\t\t\t\t.bind(initial.group_id, initial.inviter_device_id),\n\t\t\t)\n\t\t: null;\n\tconst inviterPublicKey = captureLegacyEnrollmentPublicKey(inviterRow);\n\tconst inviter = inviterRow ? { ...inviterRow } : null;\n\tconst inviterKeyId =\n\t\tinviterPublicKey === null ? null : await ed25519KeyIdForRevocation(inviterPublicKey);\n\tconst evidence = projectInviteGuardEvidence(initial, opts, inviter, {\n\t\trecipient: recipientKeyId,\n\t\tinviter: inviterKeyId,\n\t});\n\tconst guard = legacyProjectInviteOwnershipEvidence(evidence, opts.deviceId, {\n\t\tincoming: recipientKeyId,\n\t\tcurrent: currentKeyId,\n\t});\n\tconst assertEligible = async (options: { requireBinding: boolean }): Promise<void> => {\n\t\tconst state = await readRecipientInviteDecision(\n\t\t\t() => prepareProjectInviteDecision(db, initial, opts, guard, options),\n\t\t\t[\"revoked\", \"owned\", \"eligible\"],\n\t\t);\n\t\tif (state.revoked === 1) throw new Error(\"device_revoked\");\n\t\tif (state.eligible === 0) {\n\t\t\tif (state.owned === 0) validateRecipientEnrollmentTuple(enrollment, participantOpts);\n\t\t\tawait rejectStaleRecipientInviteEvidence(db, initial, participantOpts, recipientKeyId, {\n\t\t\t\towned: state.owned === 1,\n\t\t\t});\n\t\t}\n\t};\n\tawait assertEligible({ requireBinding: false });\n\tvalidateRecipientEnrollmentTuple(enrollment, participantOpts);\n\treturn { ...guard, assertEligible };\n}\n\nfunction prepareBoundProjectInviteIdentityRepair(\n\tdb: D1DatabaseLike,\n\topts: CoordinatorConsumeProjectInviteInput,\n\tinvite: CoordinatorInvite,\n\tguard: ReturnType<typeof projectInviteGuardEvidence>,\n): D1PreparedStatementLike {\n\treturn db\n\t\t.prepare(`UPDATE enrolled_devices SET identity_id = ?\n\t\tWHERE group_id = ? AND device_id = ? AND identity_id IS NULL AND enabled = 1\n\t\tAND public_key = ? AND fingerprint = ? AND ${guard.boundEligibilitySql}`)\n\t\t.bind(\n\t\t\topts.recipientActorId,\n\t\t\tinvite.group_id,\n\t\t\topts.deviceId,\n\t\t\topts.publicKey,\n\t\t\topts.fingerprint,\n\t\t\t...guard.boundEligibilityValues,\n\t\t);\n}\n\nfunction assertProjectInviteBinding(\n\tinvite: CoordinatorInvite,\n\topts: CoordinatorConsumeProjectInviteInput,\n): void {\n\tif (\n\t\tinvite.bound_device_id !== opts.deviceId ||\n\t\tinvite.bound_public_key !== opts.publicKey ||\n\t\tinvite.bound_fingerprint !== opts.fingerprint\n\t)\n\t\tthrow new Error(\"invite_already_bound\");\n\tif (\n\t\tinvite.recipient_actor_id !== opts.recipientActorId ||\n\t\tinvite.recipient_display_name !== opts.recipientDisplayName ||\n\t\tinvite.recipient_device_display_name !== opts.deviceDisplayName\n\t)\n\t\tthrow new Error(\"invite_identity_conflict\");\n}\n\nconst PROJECT_INVITE_ENROLLMENT_SQL = `EXISTS (SELECT 1 FROM enrolled_devices WHERE group_id = ?\n\tAND device_id = ? AND public_key = ? AND fingerprint = ? AND identity_id = ? AND enabled = 1)`;\n\nconst PROJECT_INVITE_ACTIVE_ENROLLMENT_SQL = `EXISTS (SELECT 1 FROM enrolled_devices\n\tWHERE group_id = ? AND device_id = ? AND enabled = 1)`;\n\nfunction projectInviteEnrollmentValues(\n\tinvite: CoordinatorInvite,\n\topts: CoordinatorConsumeProjectInviteInput,\n): string[] {\n\treturn [invite.group_id, opts.deviceId, opts.publicKey, opts.fingerprint, opts.recipientActorId];\n}\n\nasync function runProjectInviteBatch(\n\tdb: D1DatabaseLike,\n\tstatements: D1PreparedStatementLike[],\n\tinitial: CoordinatorInvite,\n\topts: CoordinatorConsumeProjectInviteInput,\n\tguard: Awaited<ReturnType<typeof prepareProjectInviteGuards>>,\n\tenrollmentValues: string[],\n): Promise<boolean> {\n\t// A retry repairs only its pinned enrollment; fresh enrollment requires this batch's consume winner.\n\tif (initial.consumed_at)\n\t\tstatements.splice(1, 1, prepareBoundProjectInviteIdentityRepair(db, opts, initial, guard));\n\tconst changed = await runRecipientInviteBatch(db, statements, {\n\t\tsql: `${guard.boundEligibilitySql} AND ${PROJECT_INVITE_ENROLLMENT_SQL}`,\n\t\tvalues: [...guard.boundEligibilityValues, ...enrollmentValues],\n\t\tassertEligible: guard.assertEligible,\n\t});\n\treturn !initial.consumed_at && changed === 1;\n}\n\nexport class D1CoordinatorStore implements CoordinatorStore {\n\tprivate readonly accountChangeBackend: AuthLinkBackend;\n\tprivate readonly accountChangesCapability: AccountChangeOperations;\n\treadonly db: D1DatabaseLike;\n\tprivate readonly authLinks: AuthLinkOperations;\n\tasync assertAuthSchemaReady(): Promise<void> {\n\t\tawait assertCoordinatorAuthSchema({\n\t\t\tfirst: <T>({ sql, values }: AuthLinkStatement) =>\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(sql)\n\t\t\t\t\t.bind(...values)\n\t\t\t\t\t.first<T>(),\n\t\t});\n\t}\n\tprivate readonly accountLinkStatus: AccountLinkStatusOperations;\n\tprivate readonly accountOwnerTarget: AccountOwnerTargetOperations;\n\tprivate readonly deviceRevocations: DeviceRevocationOperations;\n\tprivate readonly authSessions: AuthSessionOperations;\n\tprivate readonly authAccountProfiles: AuthAccountProfileOperations;\n\tprivate readonly authBrowserTransactions: CoordinatorAuthBrowserTransactions;\n\n\tconstructor(db: D1DatabaseLike, options: CoordinatorAuthLinkOptions = {}) {\n\t\tthis.db = db;\n\t\tthis.deviceRevocations = new DeviceRevocationOperations(\n\t\t\t{\n\t\t\t\tall: (statement) =>\n\t\t\t\t\tdb\n\t\t\t\t\t\t.prepare(statement.sql)\n\t\t\t\t\t\t.bind(...statement.values)\n\t\t\t\t\t\t.all(),\n\t\t\t\tbatch: async (statements) => {\n\t\t\t\t\tif (!db.batch) throw new Error(\"device_revocation_atomic_batch_required\");\n\t\t\t\t\treturn db.batch(\n\t\t\t\t\t\tstatements.map((statement) => db.prepare(statement.sql).bind(...statement.values)),\n\t\t\t\t\t);\n\t\t\t\t},\n\t\t\t},\n\t\t\toptions.authClock,\n\t\t);\n\t\tconst authBackend = createD1AuthLinkBackend(db);\n\t\tthis.accountChangeBackend = createD1AuthLinkBackend(db, { connections: true });\n\t\tthis.accountChangesCapability = new AccountChangeOperations(\n\t\t\tthis.accountChangeBackend,\n\t\t\toptions.authClock,\n\t\t);\n\t\tthis.authLinks = new AuthLinkOperations(authBackend, options.authClock);\n\t\tthis.accountLinkStatus = new AccountLinkStatusOperations(authBackend, options.authClock);\n\t\tthis.accountOwnerTarget = new AccountOwnerTargetOperations(authBackend, this);\n\t\tthis.authSessions = new AuthSessionOperations(authBackend, options.authClock);\n\t\tthis.authAccountProfiles = new AuthAccountProfileOperations(authBackend, options.authClock);\n\t\tthis.authBrowserTransactions = new CoordinatorAuthBrowserTransactions(\n\t\t\tauthBackend,\n\t\t\toptions.authClock,\n\t\t);\n\t}\n\t/**\n\t * ADR 0005 Section 8 rebind storage; null until migration 0038 is applied.\n\t * Raw like SQLite's: the rebind tables are gated here, not per statement.\n\t */\n\treadDeviceRebindBackend(): Promise<AuthLinkBackend | null> {\n\t\treturn readDeviceRebindBackend(createRawD1AuthLinkBackend(this.db));\n\t}\n\tasync getAccountChanges(): Promise<AccountChangeOperations> {\n\t\tawait this.accountChangeBackend.first({ sql: \"SELECT 1\", values: [] });\n\t\treturn this.accountChangesCapability;\n\t}\n\treadAccountConnectionSchemaState(): Promise<ConnectionSchemaState> {\n\t\treturn readConnectionSchemaState({\n\t\t\tfirst: <T>({ sql, values }: AuthLinkStatement) =>\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(sql)\n\t\t\t\t\t.bind(...values)\n\t\t\t\t\t.first<T>(),\n\t\t});\n\t}\n\n\t/** One fresh startup lookup; returned operations still check every SQL entry. */\n\tasync readAccountChangeCapability(): Promise<AccountChangeOperations | null> {\n\t\tconst state = await this.readAccountConnectionSchemaState();\n\t\tif (state === \"upgrade_required\") throw new CoordinatorAuthSchemaUpgradeRequiredError();\n\t\treturn state === \"ready\" ? this.accountChangesCapability : null;\n\t}\n\tasync readAuthBrowserTransactionActivity(\n\t\tinput: { binderHash: string },\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t) {\n\t\treturn this.authBrowserTransactions.readAuthBrowserTransactionActivity(input, config);\n\t}\n\tasync startAuthBrowserTransaction(\n\t\tinput: CoordinatorAuthBrowserTransactionStartInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t) {\n\t\treturn this.authBrowserTransactions.startAuthBrowserTransaction(input, config);\n\t}\n\tasync consumeAuthBrowserTransaction(\n\t\tinput: CoordinatorAuthBrowserTransactionConsumeInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t) {\n\t\treturn this.authBrowserTransactions.consumeAuthBrowserTransaction(input, config);\n\t}\n\tasync readAuthBrowserTransactionPurpose(\n\t\tinput: CoordinatorAuthBrowserTransactionConsumeInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t) {\n\t\treturn this.authBrowserTransactions.readAuthBrowserTransactionPurpose(input, config);\n\t}\n\tasync resolveAuthLinkBrowserTransaction(\n\t\tinput: CoordinatorAuthLinkBrowserTransactionResolveInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t) {\n\t\treturn this.authBrowserTransactions.resolveAuthLinkBrowserTransaction(input, config);\n\t}\n\tasync cancelAuthSigninBrowserTransaction(\n\t\tinput: CoordinatorAuthSigninBrowserTransactionCancelInput,\n\t\tscope: CoordinatorAuthBrowserTransactionScope,\n\t) {\n\t\treturn this.authBrowserTransactions.cancelAuthSigninBrowserTransaction(input, scope);\n\t}\n\tasync retireAuthBrowserTransactions(\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t\toptions?: CoordinatorAuthBrowserTransactionRetirementOptions,\n\t) {\n\t\treturn this.authBrowserTransactions.retireAuthBrowserTransactions(config, options);\n\t}\n\tasync purgeAuthSigninBrowserTransactions(\n\t\tscope: CoordinatorAuthBrowserTransactionScope,\n\t\toptions?: CoordinatorAuthBrowserTransactionMaintenanceOptions,\n\t) {\n\t\treturn this.authBrowserTransactions.purgeAuthSigninBrowserTransactions(scope, options);\n\t}\n\tasync maintainAuthBrowserTransactions(\n\t\tscope: CoordinatorAuthBrowserTransactionScope,\n\t\toptions?: CoordinatorAuthBrowserTransactionMaintenanceOptions,\n\t) {\n\t\treturn this.authBrowserTransactions.maintainAuthBrowserTransactions(scope, options);\n\t}\n\n\tasync redeemAuthLinkSession(\n\t\tinput: CoordinatorAuthLinkSessionRedeemInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authSessions.redeemAuthLinkSession(input, config);\n\t}\n\tasync redeemAuthLinkSessionWithBrowserTransaction(\n\t\tinput: CoordinatorAuthBoundLinkSessionRedeemInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t) {\n\t\treturn this.authSessions.redeemAuthLinkSessionWithBrowserTransaction(input, config);\n\t}\n\tasync preserveAuthLinkSessionCompletion(\n\t\tinput: CoordinatorAuthBoundLinkSessionRedeemInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t) {\n\t\treturn this.authSessions.preserveAuthLinkSessionCompletion(input, config);\n\t}\n\tasync purgeAuthGuardedSigninSessions(\n\t\tscope: CoordinatorAuthSessionScope,\n\t\toptions?: CoordinatorAuthSessionPurgeOptions,\n\t) {\n\t\treturn this.authSessions.purgeAuthGuardedSigninSessions(scope, options);\n\t}\n\tasync purgeAuthGuardedSigninReceipts(\n\t\tscope: CoordinatorAuthSessionScope,\n\t\toptions?: CoordinatorAuthSessionPurgeOptions,\n\t) {\n\t\treturn this.authSessions.purgeAuthGuardedSigninReceipts(scope, options);\n\t}\n\tasync signInWithAuthAccount(\n\t\tinput: CoordinatorAuthAccountSignInInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authSessions.signInWithAuthAccount(input, config);\n\t}\n\tasync signInWithConsumedBrowserTransaction(\n\t\tinput: CoordinatorAuthAccountSignInInput,\n\t\tconfig: CoordinatorAuthBrowserConfig,\n\t) {\n\t\treturn this.authSessions.signInWithConsumedBrowserTransaction(input, config);\n\t}\n\tasync readAuthSession(credentialHash: string, config: CoordinatorAuthLinkConfig) {\n\t\treturn this.authSessions.readAuthSession(credentialHash, config);\n\t}\n\tasync recordAuthAccountProfile(\n\t\tinput: CoordinatorAuthAccountProfileInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authAccountProfiles.recordAuthAccountProfile(input, config);\n\t}\n\tasync readAuthSessionAccount(credentialHash: string, config: CoordinatorAuthLinkConfig) {\n\t\treturn this.authAccountProfiles.readAuthSessionAccount(credentialHash, config);\n\t}\n\tasync clearRevokedAuthAccountProfile(\n\t\tinput: { linkId: string },\n\t\tscope: { coordinatorId: string },\n\t) {\n\t\treturn this.authAccountProfiles.clearRevokedAuthAccountProfile(input, scope);\n\t}\n\tasync signOutAuthSession(credentialHash: string, scope: CoordinatorAuthSessionScope) {\n\t\treturn this.authSessions.signOutAuthSession(credentialHash, scope);\n\t}\n\tasync revokeAuthAccountLink(input: { linkId: string }, scope: CoordinatorAuthSessionScope) {\n\t\treturn this.authSessions.revokeAuthAccountLink(input, scope);\n\t}\n\n\tasync maintainAuthLinkAttempts(\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t\toptions?: CoordinatorAuthLinkMaintenanceOptions,\n\t) {\n\t\treturn this.authLinks.maintainAuthLinkAttempts(config, options);\n\t}\n\treadAccountLinkStatus(...args: Parameters<AccountLinkStatusOperations[\"readAccountLinkStatus\"]>) {\n\t\treturn this.accountLinkStatus.readAccountLinkStatus(...args);\n\t}\n\treadAccountOwnerTarget(\n\t\t...args: Parameters<AccountOwnerTargetOperations[\"readAccountOwnerTarget\"]>\n\t) {\n\t\treturn this.accountOwnerTarget.readAccountOwnerTarget(...args);\n\t}\n\treadResolvedAccountOwnerStatus(\n\t\t...args: Parameters<ResolvedAccountOwnerStatusOperations[\"readResolvedAccountOwnerStatus\"]>\n\t) {\n\t\treturn new ResolvedAccountOwnerStatusOperations({\n\t\t\t...this.accountChangeBackend,\n\t\t\tall: async <T>({ sql, values }: AuthLinkStatement) => {\n\t\t\t\tconst result = await this.db\n\t\t\t\t\t.prepare(sql)\n\t\t\t\t\t.bind(...values)\n\t\t\t\t\t.all<T>();\n\t\t\t\tif (!result.results) throw new Error(\"resolved_account_owner_status_unavailable\");\n\t\t\t\treturn result.results;\n\t\t\t},\n\t\t}).readResolvedAccountOwnerStatus(...args);\n\t}\n\tprivate ownerResolutionReviews(): OwnerResolutionReviewOperations {\n\t\treturn new OwnerResolutionReviewOperations({\n\t\t\t...createD1AuthLinkBackend(this.db),\n\t\t\tall: async <T>({ sql, values }: AuthLinkStatement) => {\n\t\t\t\tconst result = await this.db\n\t\t\t\t\t.prepare(sql)\n\t\t\t\t\t.bind(...values)\n\t\t\t\t\t.all<T>();\n\t\t\t\tif (!result.results) throw new Error(\"owner_resolution_rows_unavailable\");\n\t\t\t\treturn result.results;\n\t\t\t},\n\t\t});\n\t}\n\tpreviewOwnerResolutionReview(\n\t\t...args: Parameters<OwnerResolutionReviewOperations[\"previewOwnerResolutionReview\"]>\n\t) {\n\t\treturn this.ownerResolutionReviews().previewOwnerResolutionReview(...args);\n\t}\n\tconfirmOwnerResolutionReview(\n\t\t...args: Parameters<OwnerResolutionReviewOperations[\"confirmOwnerResolutionReview\"]>\n\t) {\n\t\treturn this.ownerResolutionReviews().confirmOwnerResolutionReview(...args);\n\t}\n\treadAuthDeviceClaimReadiness(\n\t\t...args: Parameters<AccountLinkStatusOperations[\"readAuthDeviceClaimReadiness\"]>\n\t) {\n\t\treturn this.accountLinkStatus.readAuthDeviceClaimReadiness(...args);\n\t}\n\tasync createAuthLinkAttempt(\n\t\tinput: CoordinatorAuthLinkCreateInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authLinks.createAuthLinkAttempt(input, config);\n\t}\n\tasync claimAuthLinkAttempt(\n\t\tinput: CoordinatorAuthLinkClaimInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authLinks.claimAuthLinkAttempt(input, config);\n\t}\n\tasync recordAuthLinkOidcVerified(\n\t\tinput: CoordinatorAuthLinkOidcInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authLinks.recordAuthLinkOidcVerified(input, config);\n\t}\n\tasync confirmAuthLinkAttempt(\n\t\tinput: CoordinatorAuthLinkConfirmInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authLinks.confirmAuthLinkAttempt(input, config);\n\t}\n\tasync readAuthLinkCompletionDestination(\n\t\tinput: CoordinatorAuthLinkClaimInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authLinks.readAuthLinkCompletionDestination(input, config);\n\t}\n\tasync finalizeAuthLinkAttempt(\n\t\tinput: CoordinatorAuthLinkFinalizeInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authLinks.finalizeAuthLinkAttempt(input, config);\n\t}\n\tasync failAuthLinkAttempt(\n\t\tinput: CoordinatorAuthLinkFailInput,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authLinks.failAuthLinkAttempt(input, config);\n\t}\n\tasync getAuthLinkAttemptStatus(\n\t\tattemptId: string,\n\t\trequester: CoordinatorAuthLinkRequester,\n\t\tconfig: CoordinatorAuthLinkConfig,\n\t) {\n\t\treturn this.authLinks.getAuthLinkAttemptStatus(attemptId, requester, config);\n\t}\n\n\tasync close(): Promise<void> {\n\t\t// No-op for D1 bindings.\n\t}\n\n\tasync issueIdentityGroupGrantFromControllerAttestation(\n\t\tinput: CoordinatorIdentityGroupGrantIssueInput,\n\t): Promise<CoordinatorIdentityGroupGrantIssueResult> {\n\t\tconst captured = captureIdentityGroupGrantInput(input, [\"coordinatorId\", \"attestationId\"]);\n\t\tif (!captured) return { kind: \"rejected\", error: \"invalid_grant_input\" };\n\t\ttry {\n\t\t\tconst source = await firstRow<CoordinatorEnrollment>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(IDENTITY_GROUP_GRANT_SOURCE_SQL)\n\t\t\t\t\t.bind(captured.coordinatorId, captured.attestationId),\n\t\t\t);\n\t\t\tif (!source) return { kind: \"rejected\", error: \"grant_authority_unavailable\" };\n\t\t\tconst authority = [\n\t\t\t\tcaptured.coordinatorId,\n\t\t\t\tcaptured.attestationId,\n\t\t\t\tsource.group_id,\n\t\t\t\tsource.device_id,\n\t\t\t\tsource.public_key,\n\t\t\t\tsource.fingerprint,\n\t\t\t\tsource.identity_id,\n\t\t\t\tsource.device_id,\n\t\t\t\tawait ed25519KeyIdForRevocation(source.public_key),\n\t\t\t];\n\t\t\tconst grant = await firstRow<CoordinatorIdentityGroupGrant>(\n\t\t\t\tthis.db.prepare(IDENTITY_GROUP_GRANT_INSERT_SQL).bind(nowISO(), ...authority),\n\t\t\t);\n\t\t\tif (grant) return { kind: \"created\", grant };\n\t\t\t// Never return a separately fetched grant after an authority check.\n\t\t\tconst existing = await firstRow<CoordinatorIdentityGroupGrant>(\n\t\t\t\tthis.db.prepare(IDENTITY_GROUP_GRANT_RETRY_SQL).bind(...authority),\n\t\t\t);\n\t\t\tif (existing) return { kind: \"existing\", grant: existing };\n\t\t\treturn { kind: \"rejected\", error: \"grant_authority_unavailable\" };\n\t\t} catch {\n\t\t\tthrow new Error(\"identity_group_grant_write_incomplete\");\n\t\t}\n\t}\n\n\tasync listIdentityGroupGrantRevisions(\n\t\tinput: CoordinatorIdentityGroupGrantScope,\n\t): Promise<CoordinatorIdentityGroupGrant[]> {\n\t\tconst captured = captureIdentityGroupGrantInput(input, [\"coordinatorId\", \"identityId\"]);\n\t\tif (!captured) throw new Error(\"invalid_grant_input\");\n\t\tconst result = await this.db\n\t\t\t.prepare(IDENTITY_GROUP_GRANT_LIST_SQL)\n\t\t\t.bind(captured.coordinatorId, captured.identityId)\n\t\t\t.all<CoordinatorIdentityGroupGrant>();\n\t\tif (!Array.isArray(result?.results)) throw new Error(\"identity_group_grant_read_incomplete\");\n\t\treturn result.results;\n\t}\n\n\tasync revokeIdentityGroupGrant(\n\t\tinput: CoordinatorIdentityGroupGrantRevokeInput,\n\t): Promise<boolean> {\n\t\tconst captured = captureIdentityGroupGrantInput(input, [\n\t\t\t\"coordinatorId\",\n\t\t\t\"identityId\",\n\t\t\t\"groupId\",\n\t\t\t\"expectedRevision\",\n\t\t]);\n\t\tif (!captured) return false;\n\t\tconst result = (await this.db\n\t\t\t.prepare(IDENTITY_GROUP_GRANT_REVOKE_SQL)\n\t\t\t.bind(\n\t\t\t\tnowISO(),\n\t\t\t\tcaptured.coordinatorId,\n\t\t\t\tcaptured.identityId,\n\t\t\t\tcaptured.groupId,\n\t\t\t\tcaptured.expectedRevision,\n\t\t\t)\n\t\t\t.run()) as D1RunResultLike | undefined;\n\t\tconst changes = result?.meta?.changes;\n\t\tif (typeof changes !== \"number\" || !Number.isSafeInteger(changes) || changes < 0 || changes > 1)\n\t\t\tthrow new Error(\"identity_group_grant_write_incomplete\");\n\t\treturn changes === 1;\n\t}\n\n\tasync createAuthControllerAttestation(\n\t\tinput: CoordinatorAuthControllerReviewInput,\n\t): Promise<CoordinatorAuthControllerCreateResult> {\n\t\tconst review = captureAuthControllerReview(input);\n\t\tif (!review) return { kind: \"rejected\", error: \"invalid_review_input\" };\n\t\tconst source = await firstRow<CoordinatorEnrollment>(\n\t\t\tthis.db.prepare(AUTH_CONTROLLER_ENROLLMENT_SQL).bind(review.groupId, review.deviceId),\n\t\t);\n\t\tif (!source) return authControllerUnavailableResult(review);\n\t\tconst authority = authControllerAuthorityValues(\n\t\t\tsource,\n\t\t\tawait ed25519KeyIdForRevocation(source.public_key),\n\t\t);\n\t\tconst conflict = await firstRow<CoordinatorAuthControllerAttestation>(\n\t\t\tthis.db.prepare(AUTH_CONTROLLER_CONFLICT_SQL).bind(...authControllerConflictValues(review)),\n\t\t);\n\t\tif (conflict) return this.resolveAuthControllerRetry(review, authority);\n\t\tconst consistency = await this.prepareAuthControllerConsistency(review);\n\t\tif (!consistency) return authControllerUnavailableResult(review);\n\t\ttry {\n\t\t\tconst statement = withNegativeOwnerConsistency(\n\t\t\t\t{\n\t\t\t\t\tsql: authControllerReviewSql(AUTH_CONTROLLER_INSERT_SQL, review),\n\t\t\t\t\tvalues: authControllerInsertValues(review, nowISO(), authority),\n\t\t\t\t},\n\t\t\t\tconsistency,\n\t\t\t);\n\t\t\tconst inserted = await runChanges(this.db.prepare(statement.sql).bind(...statement.values));\n\t\t\tif (inserted === 0) {\n\t\t\t\t// The winner changes the evidence pin. Recapture without accepting new conflicts.\n\t\t\t\tconst retryConsistency = await this.prepareAuthControllerConsistency(review);\n\t\t\t\tif (!retryConsistency) return authControllerUnavailableResult(review);\n\t\t\t\treturn this.resolveAuthControllerRetry(review, authority, retryConsistency);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (!isAuthControllerUniqueError(error)) throw error;\n\t\t\treturn this.resolveAuthControllerRetry(review, authority);\n\t\t}\n\t\tconst attestation = await firstRow<CoordinatorAuthControllerAttestation>(\n\t\t\tthis.db\n\t\t\t\t.prepare(AUTH_CONTROLLER_ACTIVE_SQL)\n\t\t\t\t.bind(review.coordinatorId, review.attestationId, ...authority),\n\t\t);\n\t\tif (!attestation) throw new Error(\"auth_controller_persistence_incomplete\");\n\t\treturn { kind: \"created\", attestation };\n\t}\n\n\tprivate prepareAuthControllerConsistency(review: CoordinatorAuthControllerReviewInput) {\n\t\treturn prepareNegativeOwnerConsistency(\n\t\t\t{\n\t\t\t\tfirst: <T>({ sql, values }: AuthLinkStatement) =>\n\t\t\t\t\tthis.db\n\t\t\t\t\t\t.prepare(sql)\n\t\t\t\t\t\t.bind(...values)\n\t\t\t\t\t\t.first<T>(),\n\t\t\t\tall: async <T>({ sql, values }: AuthLinkStatement) => {\n\t\t\t\t\tconst result = await this.db\n\t\t\t\t\t\t.prepare(sql)\n\t\t\t\t\t\t.bind(...values)\n\t\t\t\t\t\t.all<T>();\n\t\t\t\t\tif (!Array.isArray(result.results)) throw new Error(\"ownership_evidence_unavailable\");\n\t\t\t\t\treturn result.results;\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\t...review,\n\t\t\t\townerIdentityId: review.identityId,\n\t\t\t\tenrollment: { groupId: review.groupId },\n\t\t\t\tverifiedHistory: review.verifiedSnapshot?.legacyHistory,\n\t\t\t},\n\t\t);\n\t}\n\n\tprivate async resolveAuthControllerRetry(\n\t\tinput: CoordinatorAuthControllerReviewInput,\n\t\tauthority: (string | null)[],\n\t\tconsistency?: AuthLinkStatement,\n\t): Promise<CoordinatorAuthControllerCreateResult> {\n\t\tconst eligible = await firstRow<{ eligible: number }>(\n\t\t\tthis.db\n\t\t\t\t.prepare(authControllerReviewSql(AUTH_CONTROLLER_RETRY_ELIGIBLE_SQL, input))\n\t\t\t\t.bind(...authControllerRetryEligibleValues(input, authority)),\n\t\t);\n\t\tif (!eligible) return authControllerUnavailableResult(input);\n\t\tconst row = await firstRow<CoordinatorAuthControllerAttestation>(\n\t\t\tthis.db.prepare(AUTH_CONTROLLER_CONFLICT_SQL).bind(...authControllerConflictValues(input)),\n\t\t);\n\t\tconst result = authControllerRetryResult(input, row);\n\t\tif (result.kind === \"rejected\") return result;\n\t\tlet statement: AuthLinkStatement = {\n\t\t\tsql: authControllerReviewSql(AUTH_CONTROLLER_RETRY_ACTIVE_SQL, input),\n\t\t\tvalues: authControllerRetryActiveValues(input, authority),\n\t\t};\n\t\tif (consistency) statement = withNegativeOwnerConsistency(statement, consistency);\n\t\tconst active = await firstRow<CoordinatorAuthControllerAttestation>(\n\t\t\tthis.db.prepare(statement.sql).bind(...statement.values),\n\t\t);\n\t\t// A change after the conflict read makes this review stale, including revocation.\n\t\tif (!active)\n\t\t\treturn {\n\t\t\t\tkind: \"rejected\",\n\t\t\t\terror: input.verifiedSnapshot ? \"review_stale\" : \"enrollment_mismatch\",\n\t\t\t};\n\t\treturn authControllerRetryResult(input, active);\n\t}\n\n\tasync getActiveAuthControllerAttestation(\n\t\tcoordinatorId: string,\n\t\tattestationId: string,\n\t): Promise<CoordinatorAuthControllerAttestation | null> {\n\t\tif (!isAuthControllerId(coordinatorId) || !isAuthControllerId(attestationId)) return null;\n\t\tconst source = await firstRow<CoordinatorEnrollment>(\n\t\t\tthis.db.prepare(AUTH_CONTROLLER_CURRENT_ENROLLMENT_SQL).bind(coordinatorId, attestationId),\n\t\t);\n\t\tif (!source) return null;\n\t\tconst authority = authControllerAuthorityValues(\n\t\t\tsource,\n\t\t\tawait ed25519KeyIdForRevocation(source.public_key),\n\t\t);\n\t\treturn firstRow<CoordinatorAuthControllerAttestation>(\n\t\t\tthis.db.prepare(AUTH_CONTROLLER_ACTIVE_SQL).bind(coordinatorId, attestationId, ...authority),\n\t\t);\n\t}\n\n\tasync readAuthControllerAttestationForSnapshot(\n\t\tinput: CoordinatorAuthControllerReviewInput,\n\t): Promise<CoordinatorAuthControllerAttestation | null> {\n\t\tconst review = captureAuthControllerReview(input);\n\t\tif (!review?.verifiedSnapshot?.accountOwnerTarget) return null;\n\t\tconst source = await firstRow<CoordinatorEnrollment>(\n\t\t\tthis.db.prepare(AUTH_CONTROLLER_ENROLLMENT_SQL).bind(review.groupId, review.deviceId),\n\t\t);\n\t\tif (!source) return null;\n\t\tconst authority = authControllerAuthorityValues(\n\t\t\tsource,\n\t\t\tawait ed25519KeyIdForRevocation(source.public_key),\n\t\t);\n\t\treturn firstRow<CoordinatorAuthControllerAttestation>(\n\t\t\tthis.db\n\t\t\t\t.prepare(authControllerReviewSql(AUTH_CONTROLLER_RETRY_ACTIVE_SQL, review))\n\t\t\t\t.bind(...authControllerRetryActiveValues(review, authority)),\n\t\t);\n\t}\n\n\tasync hasAuthControllerSubjectOwnerConflict(\n\t\tinput: CoordinatorAuthControllerSubjectOwnerInput,\n\t): Promise<boolean> {\n\t\treturn !!(await firstRow<{ conflict: number }>(\n\t\t\tthis.db\n\t\t\t\t.prepare(AUTH_CONTROLLER_SUBJECT_OWNER_CONFLICT_SQL)\n\t\t\t\t.bind(...authControllerSubjectOwnerConflictValues(input)),\n\t\t));\n\t}\n\n\tasync revokeAuthControllerAttestation(\n\t\tcoordinatorId: string,\n\t\tattestationId: string,\n\t): Promise<boolean> {\n\t\tif (!isAuthControllerId(coordinatorId) || !isAuthControllerId(attestationId)) return false;\n\t\treturn (\n\t\t\t(await runChanges(\n\t\t\t\tthis.db.prepare(AUTH_CONTROLLER_REVOKE_SQL).bind(nowISO(), coordinatorId, attestationId),\n\t\t\t)) > 0\n\t\t);\n\t}\n\n\tasync createGroup(_groupId: string, _displayName?: string | null): Promise<void> {\n\t\tawait this.db\n\t\t\t.prepare(\n\t\t\t\t\"INSERT OR IGNORE INTO groups(group_id, display_name, archived_at, created_at) VALUES (?, ?, NULL, ?)\",\n\t\t\t)\n\t\t\t.bind(_groupId, _displayName ?? null, nowISO())\n\t\t\t.run();\n\t}\n\n\tasync getGroup(_groupId: string): Promise<CoordinatorGroup | null> {\n\t\tconst row = await firstRow<CoordinatorGroup>(\n\t\t\tthis.db\n\t\t\t\t.prepare(\n\t\t\t\t\t\"SELECT group_id, display_name, archived_at, created_at FROM groups WHERE group_id = ?\",\n\t\t\t\t)\n\t\t\t\t.bind(_groupId),\n\t\t);\n\t\treturn row ? rowToRecord<CoordinatorGroup>(row) : null;\n\t}\n\n\tasync listGroups(_includeArchived = false): Promise<CoordinatorGroup[]> {\n\t\tconst where = _includeArchived ? \"\" : \"WHERE archived_at IS NULL\";\n\t\treturn (\n\t\t\tawait allRows<CoordinatorGroup>(\n\t\t\t\tthis.db.prepare(\n\t\t\t\t\t`SELECT group_id, display_name, archived_at, created_at FROM groups ${where} ORDER BY created_at ASC`,\n\t\t\t\t),\n\t\t\t)\n\t\t).map((row) => rowToRecord<CoordinatorGroup>(row));\n\t}\n\n\tasync renameGroup(_groupId: string, _displayName: string): Promise<boolean> {\n\t\treturn (\n\t\t\t(await runChanges(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(\"UPDATE groups SET display_name = ? WHERE group_id = ?\")\n\t\t\t\t\t.bind(_displayName, _groupId),\n\t\t\t)) > 0\n\t\t);\n\t}\n\n\tasync archiveGroup(_groupId: string, _archivedAt = nowISO()): Promise<boolean> {\n\t\treturn (\n\t\t\t(await runChanges(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(\"UPDATE groups SET archived_at = ? WHERE group_id = ? AND archived_at IS NULL\")\n\t\t\t\t\t.bind(_archivedAt, _groupId),\n\t\t\t)) > 0\n\t\t);\n\t}\n\n\tasync unarchiveGroup(_groupId: string): Promise<boolean> {\n\t\treturn (\n\t\t\t(await runChanges(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\"UPDATE groups SET archived_at = NULL WHERE group_id = ? AND archived_at IS NOT NULL\",\n\t\t\t\t\t)\n\t\t\t\t\t.bind(_groupId),\n\t\t\t)) > 0\n\t\t);\n\t}\n\n\tasync enrollDevice(_groupId: string, _opts: CoordinatorEnrollDeviceInput): Promise<void> {\n\t\tconst { deviceId, publicKey, fingerprint, identityId, displayName } = captureLegacyEnrollment(\n\t\t\t_groupId,\n\t\t\t_opts,\n\t\t);\n\t\ttry {\n\t\t\tconst currentPublicKey = captureLegacyEnrollmentPublicKey(\n\t\t\t\tawait firstRow<unknown>(\n\t\t\t\t\tthis.db\n\t\t\t\t\t\t.prepare(\"SELECT public_key FROM enrolled_devices WHERE group_id = ? AND device_id = ?\")\n\t\t\t\t\t\t.bind(_groupId, deviceId),\n\t\t\t\t),\n\t\t\t);\n\t\t\tconst keyId = await ed25519KeyIdForRevocation(publicKey);\n\t\t\tconst currentKeyId =\n\t\t\t\tcurrentPublicKey === null ? null : await ed25519KeyIdForRevocation(currentPublicKey);\n\t\t\tconst source = [currentPublicKey, _groupId, deviceId, _groupId, deviceId, currentPublicKey];\n\t\t\tconst result = await this.db\n\t\t\t\t.prepare(LEGACY_ENROLLMENT_WRITE_SQL)\n\t\t\t\t.bind(\n\t\t\t\t\t_groupId,\n\t\t\t\t\tdeviceId,\n\t\t\t\t\tpublicKey,\n\t\t\t\t\tfingerprint,\n\t\t\t\t\tidentityId ?? null,\n\t\t\t\t\tdisplayName ?? null,\n\t\t\t\t\tnowISO(),\n\t\t\t\t\tdeviceId,\n\t\t\t\t\tkeyId,\n\t\t\t\t\tdeviceId,\n\t\t\t\t\tkeyId,\n\t\t\t\t\tdeviceId,\n\t\t\t\t\tcurrentKeyId,\n\t\t\t\t\t...source,\n\t\t\t\t\tdeviceId,\n\t\t\t\t\tkeyId,\n\t\t\t\t\tdeviceId,\n\t\t\t\t\tcurrentKeyId,\n\t\t\t\t\tcurrentPublicKey,\n\t\t\t\t)\n\t\t\t\t.run();\n\t\t\tif (legacyDeviceWriteChanges(result) === 1) return;\n\t\t\tconst denial = await firstRow<unknown>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(LEGACY_ENROLLMENT_DENIAL_SQL)\n\t\t\t\t\t.bind(deviceId, keyId, deviceId, keyId, deviceId, currentKeyId, ...source),\n\t\t\t);\n\t\t\tthrow new Error(legacyDeviceDenial(denial));\n\t\t} catch (error) {\n\t\t\tlegacyDeviceAuthorizationFailure(error);\n\t\t}\n\t}\n\n\tasync listEnrolledDevices(\n\t\t_groupId: string,\n\t\t_includeDisabled?: boolean,\n\t): Promise<CoordinatorEnrollment[]> {\n\t\tconst where = _includeDisabled ? \"\" : \"AND enrolled_devices.enabled = 1\";\n\t\tconst rows = (\n\t\t\tawait allRows<CoordinatorEnrollment>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT ${ENROLLMENT_PRESENCE_COLUMNS}, ${ENROLLMENT_OWNERSHIP_COLUMNS}\n\t\t\t\t\t\t FROM enrolled_devices\n\t\t\t\t\t\t LEFT JOIN presence_records\n\t\t\t\t\t\t ON presence_records.group_id = enrolled_devices.group_id\n\t\t\t\t\t\t AND presence_records.device_id = enrolled_devices.device_id\n\t\t\t\t\t\t WHERE enrolled_devices.group_id = ? ${where}\n\t\t\t\t\t\t ORDER BY enrolled_devices.created_at ASC, enrolled_devices.device_id ASC`)\n\t\t\t\t\t.bind(_groupId),\n\t\t\t)\n\t\t).map(rowToEnrollmentWithPresence);\n\t\treturn withEnrollmentOwnership(rows);\n\t}\n\n\tasync getEnrollment(\n\t\t_groupId: string,\n\t\t_deviceId: string,\n\t\t_includeDisabled = false,\n\t): Promise<CoordinatorEnrollment | null> {\n\t\tconst enabledClause = _includeDisabled ? \"\" : \"AND enabled = 1\";\n\t\tconst row = await firstRow<CoordinatorEnrollment>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT ${ENROLLMENT_COLUMNS}\n\t\t\t\t\t FROM enrolled_devices\n\t\t\t\t\t WHERE group_id = ? AND device_id = ? ${enabledClause}`)\n\t\t\t\t.bind(_groupId, _deviceId),\n\t\t);\n\t\treturn row ? rowToRecord<CoordinatorEnrollment>(row) : null;\n\t}\n\n\tasync renameDevice(_groupId: string, _deviceId: string, _displayName: string): Promise<boolean> {\n\t\treturn (\n\t\t\t(await runChanges(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`UPDATE enrolled_devices SET display_name = ?\n\t\t\t\t\t WHERE group_id = ? AND device_id = ?`)\n\t\t\t\t\t.bind(_displayName, _groupId, _deviceId),\n\t\t\t)) > 0\n\t\t);\n\t}\n\n\tasync setDeviceEnabled(_groupId: string, _deviceId: string, _enabled: boolean): Promise<boolean> {\n\t\tassertLegacyDeviceScope(_groupId, _deviceId);\n\t\tif (typeof _enabled !== \"boolean\") throw new Error(\"invalid_input\");\n\t\tif (_enabled) {\n\t\t\ttry {\n\t\t\t\tconst enrollment = await firstRow<{ public_key: string }>(\n\t\t\t\t\tthis.db\n\t\t\t\t\t\t.prepare(\"SELECT public_key FROM enrolled_devices WHERE group_id = ? AND device_id = ?\")\n\t\t\t\t\t\t.bind(_groupId, _deviceId),\n\t\t\t\t);\n\t\t\t\tif (enrollment === null) return false;\n\t\t\t\tif (!enrollment) throw new Error(\"device_ownership_authorization_unavailable\");\n\t\t\t\tconst publicKey = enrollment.public_key;\n\t\t\t\tif (typeof publicKey !== \"string\")\n\t\t\t\t\tthrow new Error(\"device_ownership_authorization_unavailable\");\n\t\t\t\tconst keyId = await ed25519KeyIdForRevocation(publicKey);\n\t\t\t\tconst result = await this.db\n\t\t\t\t\t.prepare(`UPDATE enrolled_devices SET enabled = 1\n\t\t\t\t\t\tWHERE group_id = ? AND device_id = ? AND public_key = ?\n\t\t\t\t\t\tAND NOT ${DEVICE_REVOCATION_SUBJECT_EXISTS_SQL}\n\t\t\t\t\t\tAND NOT ${DEVICE_OWNERSHIP_SUBJECT_EXISTS_SQL}`)\n\t\t\t\t\t.bind(_groupId, _deviceId, publicKey, _deviceId, keyId, _deviceId, keyId)\n\t\t\t\t\t.run();\n\t\t\t\tif (legacyDeviceWriteChanges(result) === 1) return true;\n\t\t\t\tconst denial = legacyDeviceDenial(\n\t\t\t\t\tawait firstRow<unknown>(\n\t\t\t\t\t\tthis.db.prepare(LEGACY_DEVICE_DENIAL_SQL).bind(_deviceId, keyId, _deviceId, keyId),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\tif (denial === \"device_ownership_requires_verified_identity\") throw new Error(denial);\n\t\t\t\treturn false;\n\t\t\t} catch (error) {\n\t\t\t\tlegacyDeviceAuthorizationFailure(error);\n\t\t\t}\n\t\t}\n\t\treturn (\n\t\t\t(await runChanges(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`UPDATE enrolled_devices SET enabled = ?\n\t\t\t\t\t WHERE group_id = ? AND device_id = ?`)\n\t\t\t\t\t.bind(_enabled ? 1 : 0, _groupId, _deviceId),\n\t\t\t)) > 0\n\t\t);\n\t}\n\n\tasync removeDevice(_groupId: string, _deviceId: string): Promise<boolean> {\n\t\t// Presence, reciprocal approvals, and the enrollment row must be removed\n\t\t// all-or-nothing. Running them as independent statements can orphan rows\n\t\t// (an enrolled device with no presence/approvals, or vice versa) if any\n\t\t// one statement fails. D1 batch() is the transaction boundary here, the\n\t\t// same convention used for audited membership changes via runAuditedBatch.\n\t\tif (!this.db.batch) {\n\t\t\tthrow new Error(\"D1 batch support is required for atomic device removal.\");\n\t\t}\n\t\tconst results = await this.db.batch([\n\t\t\tthis.db\n\t\t\t\t.prepare(\"DELETE FROM presence_records WHERE group_id = ? AND device_id = ?\")\n\t\t\t\t.bind(_groupId, _deviceId),\n\t\t\tthis.db\n\t\t\t\t.prepare(\n\t\t\t\t\t\"DELETE FROM coordinator_reciprocal_approvals WHERE group_id = ? AND (requesting_device_id = ? OR requested_device_id = ?)\",\n\t\t\t\t)\n\t\t\t\t.bind(_groupId, _deviceId, _deviceId),\n\t\t\tthis.db\n\t\t\t\t.prepare(\"DELETE FROM enrolled_devices WHERE group_id = ? AND device_id = ?\")\n\t\t\t\t.bind(_groupId, _deviceId),\n\t\t]);\n\t\t// The enrolled_devices delete is the last statement; its changes() tells us\n\t\t// whether the device existed, preserving the boolean return contract.\n\t\treturn batchResultChanges(results[2]) > 0;\n\t}\n\n\tasync recordNonce(_deviceId: string, _nonce: string, _createdAt: string): Promise<boolean> {\n\t\treturn (\n\t\t\t(await runChanges(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\"INSERT OR IGNORE INTO request_nonces(device_id, nonce, created_at) VALUES (?, ?, ?)\",\n\t\t\t\t\t)\n\t\t\t\t\t.bind(_deviceId, _nonce, _createdAt),\n\t\t\t)) > 0\n\t\t);\n\t}\n\n\tasync cleanupNonces(_cutoff: string): Promise<void> {\n\t\tawait this.db.prepare(\"DELETE FROM request_nonces WHERE created_at < ?\").bind(_cutoff).run();\n\t}\n\n\tasync createDeviceRevocation(input: CoordinatorCreateDeviceRevocationInput) {\n\t\treturn this.deviceRevocations.createDeviceRevocation(input);\n\t}\n\n\tasync listDeviceRevocations(input: CoordinatorListDeviceRevocationsInput) {\n\t\treturn this.deviceRevocations.listDeviceRevocations(input);\n\t}\n\n\tasync recordAuthorizedNonce(input: CoordinatorRecordAuthorizedNonceInput) {\n\t\treturn this.deviceRevocations.recordAuthorizedNonce(input);\n\t}\n\n\tasync createInvite(_opts: CoordinatorCreateInviteInput): Promise<CoordinatorInvite> {\n\t\tconst now = nowISO();\n\t\tconst inviteId = tokenUrlSafe(12);\n\t\tconst token = tokenUrlSafe(24);\n\t\tconst digest = await tokenDigest(token);\n\t\tconst expiresAt = normalizeInviteExpiresAt(_opts.expiresAt);\n\t\tconst group = await this.getGroup(_opts.groupId);\n\t\tconst operationId = String(_opts.operationId ?? \"\").trim() || null;\n\t\tconst reviewedProjectSetDigest = String(_opts.reviewedProjectSetDigest ?? \"\").trim() || null;\n\t\tconst metadata = await normalizeCoordinatorInviteMetadata(_opts);\n\t\tconst assignedIdentityId =\n\t\t\tmetadata.inviteKind === \"team_member\" ? `identity:${tokenUrlSafe(18)}` : null;\n\t\tif (Boolean(operationId) !== Boolean(reviewedProjectSetDigest)) {\n\t\t\tthrow new Error(\"operationId and reviewedProjectSetDigest must be provided together.\");\n\t\t}\n\t\tconst readOperationInvite = async (): Promise<CoordinatorInvite | null> => {\n\t\t\tif (!operationId) return null;\n\t\t\tconst existing = await firstRow<CoordinatorInvite>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT ${INVITE_COLUMNS} FROM coordinator_invites WHERE operation_id = ?`)\n\t\t\t\t\t.bind(operationId),\n\t\t\t);\n\t\t\tif (!existing) return null;\n\t\t\t// Pre-consume create retries can recover the bearer token. Successful\n\t\t\t// consume clears it, so post-consume create retries fail closed.\n\t\t\tif (existing.consumed_at) throw new Error(\"invite_already_bound\");\n\t\t\tif (\n\t\t\t\texisting.group_id !== _opts.groupId ||\n\t\t\t\texisting.policy !== _opts.policy ||\n\t\t\t\texisting.invite_kind !== metadata.inviteKind ||\n\t\t\t\texisting.reviewed_project_set_digest !== reviewedProjectSetDigest ||\n\t\t\t\texisting.inviter_actor_id !== (String(_opts.inviterActorId ?? \"\").trim() || null) ||\n\t\t\t\texisting.inviter_display_name !== (String(_opts.inviterDisplayName ?? \"\").trim() || null) ||\n\t\t\t\texisting.inviter_device_id !== (String(_opts.inviterDeviceId ?? \"\").trim() || null) ||\n\t\t\t\texisting.pending_person_id !== (String(_opts.pendingPersonId ?? \"\").trim() || null) ||\n\t\t\t\texisting.project_summaries_json !==\n\t\t\t\t\t(_opts.projectSummaries ? JSON.stringify(_opts.projectSummaries) : null) ||\n\t\t\t\texisting.project_intent_json !==\n\t\t\t\t\t(_opts.projectIntent ? JSON.stringify(_opts.projectIntent) : null) ||\n\t\t\t\texisting.policy_team_id !== metadata.policyTeamId ||\n\t\t\t\texisting.target_identity_id !== metadata.targetIdentityId ||\n\t\t\t\texisting.reviewed_preview_digest !== metadata.reviewedPreviewDigest ||\n\t\t\t\texisting.reviewed_intent_json !== metadata.reviewedIntentJson\n\t\t\t) {\n\t\t\t\tthrow new Error(\"invite_operation_intent_conflict\");\n\t\t\t}\n\t\t\treturn rowToRecord<CoordinatorInvite>(existing);\n\t\t};\n\t\tconst renewOperationInvite = async (\n\t\t\texisting: CoordinatorInvite,\n\t\t): Promise<CoordinatorInvite> => {\n\t\t\tif (!existing.revoked_at && existing.expires_at > now) return existing;\n\t\t\tawait runChanges(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`UPDATE coordinator_invites\n\t\t\t\t\t\tSET token = ?, token_digest = ?, expires_at = ?, created_at = ?, created_by = ?,\n\t\t\t\t\t\t\tteam_name_snapshot = ?, revoked_at = NULL\n\t\t\t\t\t\tWHERE operation_id = ? AND token = ?\n\t\t\t\t\t\t AND (revoked_at IS NOT NULL OR expires_at <= ?)`)\n\t\t\t\t\t.bind(\n\t\t\t\t\t\ttoken,\n\t\t\t\t\t\tdigest,\n\t\t\t\t\t\texpiresAt,\n\t\t\t\t\t\tnow,\n\t\t\t\t\t\t_opts.createdBy ?? null,\n\t\t\t\t\t\tgroup?.display_name ?? null,\n\t\t\t\t\t\toperationId,\n\t\t\t\t\t\texisting.token,\n\t\t\t\t\t\tnow,\n\t\t\t\t\t),\n\t\t\t);\n\t\t\tconst renewed = await readOperationInvite();\n\t\t\tif (!renewed) throw new Error(\"invite_operation_reissue_failed\");\n\t\t\treturn renewed;\n\t\t};\n\t\tif (operationId) {\n\t\t\tconst existing = await readOperationInvite();\n\t\t\tif (existing) return await renewOperationInvite(existing);\n\t\t}\n\t\ttry {\n\t\t\tawait this.db\n\t\t\t\t.prepare(`INSERT INTO coordinator_invites(\n\t\t\t\tinvite_id, group_id, token, policy, expires_at, created_at, created_by,\n\t\t\t\tteam_name_snapshot, revoked_at, operation_id, reviewed_project_set_digest,\n\t\t\t\ttoken_digest, inviter_actor_id, inviter_display_name, inviter_device_id,\n\t\t\t\tpending_person_id, project_summaries_json, project_intent_json, trust_state,\n\t\t\t\tinvite_kind, policy_team_id, target_identity_id, assigned_identity_id,\n\t\t\t\treviewed_preview_digest, reviewed_intent_json\n\t\t\t) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)\n\t\t\t\t.bind(\n\t\t\t\t\tinviteId,\n\t\t\t\t\t_opts.groupId,\n\t\t\t\t\ttoken,\n\t\t\t\t\t_opts.policy,\n\t\t\t\t\texpiresAt,\n\t\t\t\t\tnow,\n\t\t\t\t\t_opts.createdBy ?? null,\n\t\t\t\t\tgroup?.display_name ?? null,\n\t\t\t\t\toperationId,\n\t\t\t\t\treviewedProjectSetDigest,\n\t\t\t\t\tdigest,\n\t\t\t\t\tString(_opts.inviterActorId ?? \"\").trim() || null,\n\t\t\t\t\tString(_opts.inviterDisplayName ?? \"\").trim() || null,\n\t\t\t\t\tString(_opts.inviterDeviceId ?? \"\").trim() || null,\n\t\t\t\t\tString(_opts.pendingPersonId ?? \"\").trim() || null,\n\t\t\t\t\t_opts.projectSummaries ? JSON.stringify(_opts.projectSummaries) : null,\n\t\t\t\t\t_opts.projectIntent ? JSON.stringify(_opts.projectIntent) : null,\n\t\t\t\t\toperationId ? \"pending\" : null,\n\t\t\t\t\tmetadata.inviteKind,\n\t\t\t\t\tmetadata.policyTeamId,\n\t\t\t\t\tmetadata.targetIdentityId,\n\t\t\t\t\tassignedIdentityId,\n\t\t\t\t\tmetadata.reviewedPreviewDigest,\n\t\t\t\t\tmetadata.reviewedIntentJson,\n\t\t\t\t)\n\t\t\t\t.run();\n\t\t} catch (error) {\n\t\t\tif (operationId) {\n\t\t\t\tconst existing = await readOperationInvite();\n\t\t\t\tif (existing) return await renewOperationInvite(existing);\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t\tconst row = await firstRow<CoordinatorInvite>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT ${INVITE_COLUMNS} FROM coordinator_invites WHERE invite_id = ?`)\n\t\t\t\t.bind(inviteId),\n\t\t);\n\t\treturn rowToRecord<CoordinatorInvite>(row);\n\t}\n\n\tasync getInviteByOperationId(\n\t\tgroupId: string,\n\t\toperationId: string,\n\t): Promise<CoordinatorInvite | null> {\n\t\tconst row = await firstRow<CoordinatorInvite>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT ${INVITE_COLUMNS}\n\t\t\t\t\t FROM coordinator_invites WHERE group_id = ? AND operation_id = ?`)\n\t\t\t\t.bind(groupId, operationId),\n\t\t);\n\t\treturn row ? rowToRecord<CoordinatorInvite>(row) : null;\n\t}\n\n\tasync getInviteByToken(_token: string): Promise<CoordinatorInvite | null> {\n\t\tconst digest = await tokenDigest(_token);\n\t\tconst row = await firstRow<CoordinatorInvite>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT ${INVITE_COLUMNS}\n\t\t\t\t\t FROM coordinator_invites\n\t\t\t\t\t WHERE (token_digest = ? OR token = ?)\n\t\t\t\t\t AND revoked_at IS NULL\n\t\t\t\t\t AND expires_at > ?`)\n\t\t\t\t.bind(digest, _token, nowISO()),\n\t\t);\n\t\treturn row ? rowToRecord<CoordinatorInvite>(row) : null;\n\t}\n\n\tasync getInviteByTokenForInspection(_token: string): Promise<CoordinatorInvite | null> {\n\t\tconst digest = await tokenDigest(_token);\n\t\tconst row = await firstRow<CoordinatorInvite>(\n\t\t\tthis.db\n\t\t\t\t.prepare(\n\t\t\t\t\t`SELECT ${INVITE_COLUMNS} FROM coordinator_invites WHERE token_digest = ? OR token = ?`,\n\t\t\t\t)\n\t\t\t\t.bind(digest, _token),\n\t\t);\n\t\treturn row ? rowToRecord<CoordinatorInvite>(row) : null;\n\t}\n\n\tasync inspectRecipientInvite(\n\t\t_opts: CoordinatorInspectRecipientInviteInput,\n\t): Promise<CoordinatorRecipientInviteInspection | null> {\n\t\tconst invite = await this.getInviteByTokenForInspection(_opts.token);\n\t\tif (!invite) return null;\n\t\tconst inspection = await inspectInvite(invite);\n\t\tif (!inspection) return null;\n\t\tif (invite.revoked_at) throw new Error(\"invite_invalid\");\n\t\tif (\n\t\t\t!invite.consumed_at &&\n\t\t\tnew Date(invite.expires_at) <= new Date(normalizeInviteExpiresAt(_opts.now))\n\t\t) {\n\t\t\tthrow new Error(\"invite_expired\");\n\t\t}\n\t\tconst group = await this.getGroup(invite.group_id);\n\t\tif (!group) throw new Error(\"group_not_found\");\n\t\tif (group.archived_at) throw new Error(\"group_archived\");\n\t\treturn inspection;\n\t}\n\n\tprivate async recoverRecipientInviteGrant(\n\t\tinvite: CoordinatorInvite,\n\t\topts: CoordinatorConsumeRecipientInviteInput,\n\t\tguard: {\n\t\t\tsql: string;\n\t\t\tvalues: unknown[];\n\t\t\tconsumedAt: string;\n\t\t\tnegative?: AuthLinkStatement;\n\t\t\tassertEligible: (options: { requireBinding: boolean }) => Promise<void>;\n\t\t},\n\t): Promise<void> {\n\t\tif (!this.db.batch)\n\t\t\tthrow new Error(\"D1 batch support is required for atomic bootstrap grant recovery.\");\n\t\tawait runRecipientInviteBatch(\n\t\t\tthis.db,\n\t\t\t[\n\t\t\t\tprepareRecipientOwnerStatement(\n\t\t\t\t\tthis.db,\n\t\t\t\t\t`UPDATE coordinator_invites SET bootstrap_grant_id = ?,\n\t\t\t\ttrust_state = 'bootstrap_grant_created'\n\t\t\t\tWHERE invite_id = ? AND invite_kind = 'add_device'\n\t\t\t\tAND bootstrap_grant_id IS NULL AND inviter_device_id IS NOT NULL\n\t\t\t\tAND bound_device_id = ? AND recipient_actor_id = ? AND expires_at > ?\n\t\t\t\tAND EXISTS (SELECT 1 FROM enrolled_devices e\n\t\t\t\t\tWHERE e.group_id = coordinator_invites.group_id\n\t\t\t\t\tAND e.device_id = coordinator_invites.inviter_device_id AND e.enabled = 1)\n\t\t\t\tAND ${guard.sql}`,\n\t\t\t\t\tguard.negative,\n\t\t\t\t).bind(\n\t\t\t\t\ttokenUrlSafe(12),\n\t\t\t\t\tinvite.invite_id,\n\t\t\t\t\topts.deviceId,\n\t\t\t\t\topts.identityId,\n\t\t\t\t\tguard.consumedAt,\n\t\t\t\t\t...guard.values,\n\t\t\t\t),\n\t\t\t\tprepareRecipientOwnerStatement(\n\t\t\t\t\tthis.db,\n\t\t\t\t\t`INSERT OR IGNORE INTO coordinator_bootstrap_grants(\n\t\t\t\tgrant_id, group_id, seed_device_id, worker_device_id, expires_at,\n\t\t\t\tcreated_at, created_by, revoked_at\n\t\t\t) SELECT i.bootstrap_grant_id, i.group_id, i.inviter_device_id, i.bound_device_id,\n\t\t\t\ti.expires_at, ?, i.recipient_actor_id, NULL FROM coordinator_invites i\n\t\t\tJOIN enrolled_devices e ON e.group_id = i.group_id\n\t\t\t\tAND e.device_id = i.inviter_device_id AND e.enabled = 1\n\t\t\tWHERE i.invite_id = ? AND i.invite_kind = 'add_device'\n\t\t\t\tAND i.bootstrap_grant_id IS NOT NULL AND i.bound_device_id = ?\n\t\t\t\tAND ${guard.sql}`,\n\t\t\t\t\tguard.negative,\n\t\t\t\t).bind(guard.consumedAt, invite.invite_id, opts.deviceId, ...guard.values),\n\t\t\t],\n\t\t\tguard,\n\t\t);\n\t}\n\n\tprivate async prepareEligibleRecipientOwner(opts: CoordinatorConsumeRecipientInviteInput) {\n\t\tconst backend = createRecipientOwnerBackend(this.db);\n\t\tconst consistency = await prepareRecipientOwnerConsistency(backend, opts);\n\t\tif (!consistency) throw new Error(\"device_ownership_authorization_unavailable\");\n\t\tawait assertRecipientOwnerConsistency(backend, consistency);\n\t\treturn consistency;\n\t}\n\n\tasync consumeRecipientInvite(\n\t\tinput: CoordinatorConsumeRecipientInviteInput,\n\t): Promise<CoordinatorRecipientInviteAcceptance> {\n\t\tconst _opts = { ...input };\n\t\tconst consumedAt = normalizeInviteExpiresAt(_opts.now);\n\t\tconst recipientDisplayName = _opts.recipientDisplayName ?? null;\n\t\tconst deviceDisplayName = _opts.deviceDisplayName ?? null;\n\t\tvalidateRecipientOwnerInput(_opts);\n\t\tconst digest = await tokenDigest(_opts.token);\n\t\tconst initial = structuredClone(await this.getInviteByTokenForInspection(_opts.token));\n\t\tconst inspection = initial ? await inspectInvite(initial) : null;\n\t\tif (!initial || !inspection || inspection.kind !== _opts.inviteKind || initial.revoked_at) {\n\t\t\tthrow new Error(\"invite_invalid\");\n\t\t}\n\t\tconst group = await this.getGroup(initial.group_id);\n\t\tif (!group) throw new Error(\"group_not_found\");\n\t\tif (group.archived_at) throw new Error(\"group_archived\");\n\t\tif (!initial.consumed_at && new Date(initial.expires_at) <= new Date(consumedAt)) {\n\t\t\tthrow new Error(\"invite_expired\");\n\t\t}\n\t\tif (fingerprintPublicKey(_opts.publicKey) !== _opts.fingerprint) {\n\t\t\tthrow new Error(\"fingerprint_mismatch\");\n\t\t}\n\t\tconst authoritativeIdentityId = recipientInviteAuthoritativeIdentityId(inspection);\n\t\tif (authoritativeIdentityId !== _opts.identityId) {\n\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\t}\n\t\tvalidateRecipientInviteBinding(initial, _opts, { requireBinding: false });\n\t\tconst existingEnrollment = await firstRow<CoordinatorEnrollment>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT ${ENROLLMENT_COLUMNS}\n\t\t\t\t\tFROM enrolled_devices WHERE group_id = ? AND device_id = ?`)\n\t\t\t\t.bind(initial.group_id, _opts.deviceId),\n\t\t);\n\t\tvalidateRecipientEnrollmentTuple(existingEnrollment, _opts);\n\t\tconst {\n\t\t\teligibilitySql,\n\t\t\teligibilityValues,\n\t\t\tboundEligibilitySql,\n\t\t\tboundEligibilityValues,\n\t\t\tassertEligible,\n\t\t} = await prepareRecipientInviteGuards(this.db, initial, _opts);\n\t\tawait assertEligible({ requireBinding: Boolean(initial.consumed_at) });\n\t\tconst consistency = await this.prepareEligibleRecipientOwner(_opts);\n\t\tconst negative = consistency.retainedRecheck;\n\t\tlet changed = 0;\n\t\tconst bootstrapGrantId = tokenUrlSafe(12);\n\t\tif (!initial.consumed_at) {\n\t\t\tif (!this.db.batch)\n\t\t\t\tthrow new Error(\"D1 batch support is required for atomic invite consume.\");\n\t\t\tchanged = await runRecipientInviteBatch(\n\t\t\t\tthis.db,\n\t\t\t\t[\n\t\t\t\t\tprepareRecipientOwnerStatement(\n\t\t\t\t\t\tthis.db,\n\t\t\t\t\t\t`UPDATE coordinator_invites SET token = ?, consumed_at = ?, bound_device_id = ?,\n\t\t\t\t\t\tbound_public_key = ?, bound_fingerprint = ?, recipient_actor_id = ?,\n\t\t\t\t\t\trecipient_display_name = ?, recipient_device_display_name = ?\n\t\t\t\t\t\tWHERE (token_digest = ? OR token = ?) AND consumed_at IS NULL\n\t\t\t\t\t\tAND invite_id = ? AND group_id = ?\n\t\t\t\t\t\tAND revoked_at IS NULL AND expires_at > ? AND invite_kind = ?\n\t\t\t\t\t\tAND reviewed_intent_json = ? AND reviewed_preview_digest = ?\n\t\t\t\t\t\tAND ((invite_kind = 'team_member' AND assigned_identity_id = ?)\n\t\t\t\t\t\t\tOR (invite_kind = 'add_device' AND target_identity_id = ?))\n\t\t\t\t\t\tAND NOT EXISTS (\n\t\t\t\t\t\t\tSELECT 1 FROM enrolled_devices e\n\t\t\t\t\t\t\tWHERE e.group_id = coordinator_invites.group_id AND e.device_id = ?\n\t\t\t\t\t\t\t\tAND (e.public_key <> ? OR e.fingerprint <> ?\n\t\t\t\t\t\t\t\t\tOR (e.identity_id IS NOT NULL AND e.identity_id <> ?))\n\t\t\t\t\t\t)\n\t\t\t\t\t\tAND EXISTS (SELECT 1 FROM groups g WHERE g.group_id = coordinator_invites.group_id\n\t\t\t\t\t\t\tAND g.archived_at IS NULL)\n\t\t\t\t\t\tAND ${eligibilitySql}`,\n\t\t\t\t\t\tconsistency,\n\t\t\t\t\t).bind(\n\t\t\t\t\t\t`consumed:${initial.invite_id}`,\n\t\t\t\t\t\tconsumedAt,\n\t\t\t\t\t\t_opts.deviceId,\n\t\t\t\t\t\t_opts.publicKey,\n\t\t\t\t\t\t_opts.fingerprint,\n\t\t\t\t\t\tauthoritativeIdentityId,\n\t\t\t\t\t\trecipientDisplayName,\n\t\t\t\t\t\tdeviceDisplayName,\n\t\t\t\t\t\tdigest,\n\t\t\t\t\t\t_opts.token,\n\t\t\t\t\t\tinitial.invite_id,\n\t\t\t\t\t\tinitial.group_id,\n\t\t\t\t\t\tconsumedAt,\n\t\t\t\t\t\t_opts.inviteKind,\n\t\t\t\t\t\tinitial.reviewed_intent_json,\n\t\t\t\t\t\tinitial.reviewed_preview_digest,\n\t\t\t\t\t\tauthoritativeIdentityId,\n\t\t\t\t\t\tauthoritativeIdentityId,\n\t\t\t\t\t\t_opts.deviceId,\n\t\t\t\t\t\t_opts.publicKey,\n\t\t\t\t\t\t_opts.fingerprint,\n\t\t\t\t\t\tauthoritativeIdentityId,\n\t\t\t\t\t\t...eligibilityValues,\n\t\t\t\t\t),\n\t\t\t\t\tprepareRecipientOwnerStatement(\n\t\t\t\t\t\tthis.db,\n\t\t\t\t\t\t`INSERT INTO enrolled_devices(\n\t\t\t\t\t\tgroup_id, device_id, public_key, fingerprint, identity_id, display_name, enabled, created_at\n\t\t\t\t\t) SELECT i.group_id, i.bound_device_id, i.bound_public_key, i.bound_fingerprint,\n\t\t\t\t\t\ti.recipient_actor_id, i.recipient_device_display_name, 1, ? FROM coordinator_invites i\n\t\t\t\t\tJOIN groups g ON g.group_id = i.group_id AND g.archived_at IS NULL\n\t\t\t\t\tWHERE (i.token_digest = ? OR i.token = ?) AND i.bound_device_id = ?\n\t\t\t\t\t\tAND i.invite_id = ? AND i.group_id = ? AND changes() = 1\n\t\t\t\t\t\tAND i.bound_public_key = ? AND i.bound_fingerprint = ?\n\t\t\t\t\t\tAND i.recipient_actor_id = ?\n\t\t\t\t\t\tAND ${boundEligibilitySql}\n\t\t\t\t\tON CONFLICT(group_id, device_id) DO UPDATE SET\n\t\t\t\t\t\tidentity_id = COALESCE(enrolled_devices.identity_id, excluded.identity_id),\n\t\t\t\t\t\tdisplay_name = COALESCE(enrolled_devices.display_name, excluded.display_name),\n\t\t\t\t\t\tenabled = 1\n\t\t\t\t\tWHERE enrolled_devices.identity_id IS NULL\n\t\t\t\t\t\tOR enrolled_devices.identity_id = excluded.identity_id`,\n\t\t\t\t\t\tnegative,\n\t\t\t\t\t).bind(\n\t\t\t\t\t\tconsumedAt,\n\t\t\t\t\t\tdigest,\n\t\t\t\t\t\t_opts.token,\n\t\t\t\t\t\t_opts.deviceId,\n\t\t\t\t\t\tinitial.invite_id,\n\t\t\t\t\t\tinitial.group_id,\n\t\t\t\t\t\t_opts.publicKey,\n\t\t\t\t\t\t_opts.fingerprint,\n\t\t\t\t\t\tauthoritativeIdentityId,\n\t\t\t\t\t\t...boundEligibilityValues,\n\t\t\t\t\t),\n\t\t\t\t\t// Enrollment follows the winning token write. Keep bootstrap writes on\n\t\t\t\t\t// that changes() chain; a loser still needs its full pin during repair.\n\t\t\t\t\tprepareRecipientOwnerStatement(\n\t\t\t\t\t\tthis.db,\n\t\t\t\t\t\t`UPDATE coordinator_invites SET bootstrap_grant_id = ?,\n\t\t\t\t\t\ttrust_state = 'bootstrap_grant_created'\n\t\t\t\t\t\tWHERE (token_digest = ? OR token = ?) AND invite_kind = 'add_device'\n\t\t\t\t\t\tAND invite_id = ? AND group_id = ?\n\t\t\t\t\t\tAND bootstrap_grant_id IS NULL AND inviter_device_id IS NOT NULL\n\t\t\t\t\t\tAND expires_at > ?\n\t\t\t\t\t\tAND EXISTS (SELECT 1 FROM enrolled_devices e\n\t\t\t\t\t\t\tWHERE e.group_id = coordinator_invites.group_id\n\t\t\t\t\t\t\tAND e.device_id = coordinator_invites.inviter_device_id AND e.enabled = 1)\n\t\t\t\t\t\tAND changes() = 1 AND ${boundEligibilitySql}`,\n\t\t\t\t\t\tnegative,\n\t\t\t\t\t).bind(\n\t\t\t\t\t\tbootstrapGrantId,\n\t\t\t\t\t\tdigest,\n\t\t\t\t\t\t_opts.token,\n\t\t\t\t\t\tinitial.invite_id,\n\t\t\t\t\t\tinitial.group_id,\n\t\t\t\t\t\tconsumedAt,\n\t\t\t\t\t\t...boundEligibilityValues,\n\t\t\t\t\t),\n\t\t\t\t\tprepareRecipientOwnerStatement(\n\t\t\t\t\t\tthis.db,\n\t\t\t\t\t\t`INSERT OR IGNORE INTO coordinator_bootstrap_grants(\n\t\t\t\t\t\tgrant_id, group_id, seed_device_id, worker_device_id, expires_at,\n\t\t\t\t\t\tcreated_at, created_by, revoked_at\n\t\t\t\t\t) SELECT i.bootstrap_grant_id, i.group_id, i.inviter_device_id, i.bound_device_id,\n\t\t\t\t\t\ti.expires_at, ?, i.recipient_actor_id, NULL FROM coordinator_invites i\n\t\t\t\t\tJOIN enrolled_devices e ON e.group_id = i.group_id\n\t\t\t\t\t\tAND e.device_id = i.inviter_device_id AND e.enabled = 1\n\t\t\t\t\tWHERE (i.token_digest = ? OR i.token = ?) AND i.invite_kind = 'add_device'\n\t\t\t\t\t\tAND i.invite_id = ? AND i.group_id = ?\n\t\t\t\t\t\tAND i.bootstrap_grant_id IS NOT NULL AND i.bound_device_id = ?\n\t\t\t\t\t\tAND changes() = 1 AND ${boundEligibilitySql}`,\n\t\t\t\t\t\tnegative,\n\t\t\t\t\t).bind(\n\t\t\t\t\t\tconsumedAt,\n\t\t\t\t\t\tdigest,\n\t\t\t\t\t\t_opts.token,\n\t\t\t\t\t\tinitial.invite_id,\n\t\t\t\t\t\tinitial.group_id,\n\t\t\t\t\t\t_opts.deviceId,\n\t\t\t\t\t\t...boundEligibilityValues,\n\t\t\t\t\t),\n\t\t\t\t],\n\t\t\t\t{ sql: eligibilitySql, values: eligibilityValues, assertEligible, negative },\n\t\t\t);\n\t\t}\n\t\tawait assertEligible({ requireBinding: false });\n\t\tconst currentGroup = await this.getGroup(initial.group_id);\n\t\tif (!currentGroup) throw new Error(\"group_not_found\");\n\t\tif (currentGroup.archived_at) throw new Error(\"group_archived\");\n\t\tconst currentEnrollment = await firstRow<CoordinatorEnrollment>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT ${ENROLLMENT_COLUMNS}\n\t\t\t\t\tFROM enrolled_devices WHERE group_id = ? AND device_id = ?`)\n\t\t\t\t.bind(initial.group_id, _opts.deviceId),\n\t\t);\n\t\tvalidateRecipientEnrollmentTuple(currentEnrollment, _opts);\n\t\tconst saved = await this.getInviteByTokenForInspection(_opts.token);\n\t\tif (\n\t\t\t!saved ||\n\t\t\tsaved.revoked_at ||\n\t\t\t(!saved.consumed_at && new Date(saved.expires_at) <= new Date(consumedAt))\n\t\t) {\n\t\t\tthrow new Error(\"invite_invalid\");\n\t\t}\n\t\tconst savedInspection = await inspectInvite(saved);\n\t\tif (!savedInspection || savedInspection.kind !== _opts.inviteKind) {\n\t\t\tthrow new Error(\"invite_invalid\");\n\t\t}\n\t\tconst savedIdentityId = recipientInviteAuthoritativeIdentityId(savedInspection);\n\t\tif (savedIdentityId !== authoritativeIdentityId) {\n\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\t}\n\t\tconst recoveryNegative = await repairBoundRecipientInviteIdentity(\n\t\t\tthis.db,\n\t\t\t_opts,\n\t\t\tsaved,\n\t\t\t{ sql: boundEligibilitySql, values: boundEligibilityValues, assertEligible, negative },\n\t\t\t{ winningChanges: changed, consistency },\n\t\t);\n\t\tawait assertEligible({ requireBinding: true });\n\t\tconst enrollment = await this.getEnrollment(saved.group_id, _opts.deviceId);\n\t\tvalidateAcceptedRecipientEnrollment(enrollment, _opts);\n\t\tlet savedWithGrant = saved;\n\t\tif (\n\t\t\tsavedInspection.kind === \"add_device\" &&\n\t\t\tsaved.inviter_device_id &&\n\t\t\t!saved.bootstrap_grant_id &&\n\t\t\tnew Date(saved.expires_at) > new Date(consumedAt)\n\t\t) {\n\t\t\tawait this.recoverRecipientInviteGrant(saved, _opts, {\n\t\t\t\tsql: boundEligibilitySql,\n\t\t\t\tvalues: boundEligibilityValues,\n\t\t\t\tconsumedAt,\n\t\t\t\tassertEligible,\n\t\t\t\tnegative: recoveryNegative,\n\t\t\t});\n\t\t\tconst refreshed = await this.getInviteByTokenForInspection(_opts.token);\n\t\t\tif (!refreshed) throw new Error(\"invite_invalid\");\n\t\t\tsavedWithGrant = refreshed;\n\t\t}\n\t\tconst bootstrapGrant = savedWithGrant.bootstrap_grant_id\n\t\t\t? await this.getBootstrapGrant(savedWithGrant.bootstrap_grant_id)\n\t\t\t: null;\n\t\tawait assertEligible({ requireBinding: true });\n\t\treturn {\n\t\t\tstatus: changed === 1 ? \"accepted\" : \"existing\",\n\t\t\tinvite: savedWithGrant,\n\t\t\treviewed_intent: savedInspection.reviewed_intent,\n\t\t\tbootstrap_grant: bootstrapGrant,\n\t\t};\n\t}\n\n\tasync consumeProjectInvite(\n\t\tinput: CoordinatorConsumeProjectInviteInput,\n\t): Promise<CoordinatorProjectInviteAcceptance> {\n\t\tconst _opts = captureLegacyProjectInviteInput(input);\n\t\tif (!this.db.batch) throw new Error(\"D1 batch support is required for atomic invite consume.\");\n\t\tconst consumedAt = normalizeInviteExpiresAt(_opts.now);\n\t\tconst digest = await tokenDigest(_opts.token);\n\t\tconst initialRow = await this.getInviteByTokenForInspection(_opts.token);\n\t\tconst initial = initialRow ? { ...initialRow } : null;\n\t\tif (!initial?.operation_id || !initial.project_intent_json || initial.revoked_at) {\n\t\t\tthrow new Error(\"invite_invalid\");\n\t\t}\n\t\tconst group = await this.getGroup(initial.group_id);\n\t\tif (!group) throw new Error(\"group_not_found\");\n\t\tif (group.archived_at) throw new Error(\"group_archived\");\n\t\tif (initial.operation_id !== _opts.operationId) throw new Error(\"invite_invalid\");\n\t\tif (fingerprintPublicKey(_opts.publicKey) !== _opts.fingerprint) {\n\t\t\tthrow new Error(\"fingerprint_mismatch\");\n\t\t}\n\t\tif (!initial.consumed_at && new Date(initial.expires_at) <= new Date(consumedAt)) {\n\t\t\tthrow new Error(\"invite_expired\");\n\t\t}\n\t\tif (initial.consumed_at) assertProjectInviteBinding(initial, _opts);\n\t\tconst guard = await prepareProjectInviteGuards(this.db, initial, _opts);\n\t\tconst grantId = tokenUrlSafe(12);\n\t\tconst enrollmentValues = projectInviteEnrollmentValues(initial, _opts);\n\t\tconst statements = [\n\t\t\tthis.db\n\t\t\t\t.prepare(`UPDATE coordinator_invites SET token = ?, consumed_at = ?, bound_device_id = ?,\n\t\t\t\t\tbound_public_key = ?, bound_fingerprint = ?, recipient_actor_id = ?,\n\t\t\t\t\trecipient_display_name = ?, recipient_device_display_name = ?,\n\t\t\t\t\ttrust_state = 'pending_inviter_device'\n\t\t\t\t\tWHERE (token_digest = ? OR token = ?) AND consumed_at IS NULL\n\t\t\t\t\tAND EXISTS (SELECT 1 FROM groups g WHERE g.group_id = coordinator_invites.group_id\n\t\t\t\t\t\tAND g.archived_at IS NULL)\n\t\t\t\t\tAND revoked_at IS NULL AND expires_at > ? AND ${guard.eligibilitySql}`)\n\t\t\t\t.bind(\n\t\t\t\t\t`consumed:${initial.invite_id}`,\n\t\t\t\t\tconsumedAt,\n\t\t\t\t\t_opts.deviceId,\n\t\t\t\t\t_opts.publicKey,\n\t\t\t\t\t_opts.fingerprint,\n\t\t\t\t\t_opts.recipientActorId,\n\t\t\t\t\t_opts.recipientDisplayName,\n\t\t\t\t\t_opts.deviceDisplayName,\n\t\t\t\t\tdigest,\n\t\t\t\t\t_opts.token,\n\t\t\t\t\tconsumedAt,\n\t\t\t\t\t...guard.eligibilityValues,\n\t\t\t\t),\n\t\t\tthis.db\n\t\t\t\t.prepare(`INSERT INTO enrolled_devices(\n\t\t\t\t\tgroup_id, device_id, public_key, fingerprint, identity_id, display_name, enabled, created_at\n\t\t\t\t) SELECT i.group_id, i.bound_device_id, i.bound_public_key, i.bound_fingerprint,\n\t\t\t\t\ti.recipient_actor_id, i.recipient_device_display_name, 1, ? FROM coordinator_invites i\n\t\t\t\t\tJOIN groups g ON g.group_id = i.group_id AND g.archived_at IS NULL\n\t\t\t\t\tWHERE (i.token_digest = ? OR i.token = ?) AND i.bound_device_id = ? AND changes() = 1\n\t\t\t\t\tAND ${guard.boundEligibilitySql}\n\t\t\t\tON CONFLICT(group_id, device_id) DO UPDATE SET\n\t\t\t\t\tidentity_id = COALESCE(enrolled_devices.identity_id, excluded.identity_id),\n\t\t\t\t\tdisplay_name = excluded.display_name, enabled = 1\n\t\t\t\t\tWHERE (enrolled_devices.identity_id IS NULL\n\t\t\t\t\tOR enrolled_devices.identity_id = excluded.identity_id)\n\t\t\t\t\tAND ${guard.boundEligibilitySql}`)\n\t\t\t\t.bind(\n\t\t\t\t\tconsumedAt,\n\t\t\t\t\tdigest,\n\t\t\t\t\t_opts.token,\n\t\t\t\t\t_opts.deviceId,\n\t\t\t\t\t...guard.boundEligibilityValues,\n\t\t\t\t\t...guard.boundEligibilityValues,\n\t\t\t\t),\n\t\t\tthis.db\n\t\t\t\t.prepare(`UPDATE coordinator_invites SET bootstrap_grant_id = ?,\n\t\t\t\t\ttrust_state = 'bootstrap_grant_created'\n\t\t\t\t\tWHERE (token_digest = ? OR token = ?) AND bootstrap_grant_id IS NULL\n\t\t\t\t\tAND bound_device_id = ?\n\t\t\t\t\tAND (changes() = 1 OR ? = 1) AND ${PROJECT_INVITE_ENROLLMENT_SQL}\n\t\t\t\t\tAND EXISTS (SELECT 1 FROM groups g WHERE g.group_id = coordinator_invites.group_id\n\t\t\t\t\t\tAND g.archived_at IS NULL)\n\t\t\t\t\tAND expires_at > ?\n\t\t\t\t\tAND EXISTS (SELECT 1 FROM enrolled_devices e WHERE e.group_id = coordinator_invites.group_id\n\t\t\t\t\t\tAND e.device_id = coordinator_invites.inviter_device_id AND e.enabled = 1)\n\t\t\t\t\tAND ${guard.boundEligibilitySql}`)\n\t\t\t\t.bind(\n\t\t\t\t\tgrantId,\n\t\t\t\t\tdigest,\n\t\t\t\t\t_opts.token,\n\t\t\t\t\t_opts.deviceId,\n\t\t\t\t\tinitial.consumed_at ? 1 : 0,\n\t\t\t\t\t...enrollmentValues,\n\t\t\t\t\tconsumedAt,\n\t\t\t\t\t...guard.boundEligibilityValues,\n\t\t\t\t),\n\t\t\tthis.db\n\t\t\t\t.prepare(`INSERT OR IGNORE INTO coordinator_bootstrap_grants(\n\t\t\t\t\tgrant_id, group_id, seed_device_id, worker_device_id, expires_at, created_at,\n\t\t\t\t\tcreated_by, revoked_at\n\t\t\t\t) SELECT i.bootstrap_grant_id, i.group_id, i.inviter_device_id, i.bound_device_id,\n\t\t\t\t\ti.expires_at, ?, i.inviter_actor_id, NULL FROM coordinator_invites i\n\t\t\t\t\tJOIN groups g ON g.group_id = i.group_id AND g.archived_at IS NULL\n\t\t\t\t\tJOIN enrolled_devices e ON e.group_id = i.group_id AND e.device_id = i.inviter_device_id\n\t\t\t\t\tWHERE (i.token_digest = ? OR i.token = ?)\n\t\t\t\t\tAND ((i.bootstrap_grant_id = ? AND changes() = 1)\n\t\t\t\t\t\tOR (i.bootstrap_grant_id = ? AND ? = 1))\n\t\t\t\t\tAND i.bound_device_id = ? AND e.enabled = 1\n\t\t\t\t\tAND ${guard.boundEligibilitySql} AND ${PROJECT_INVITE_ENROLLMENT_SQL}`)\n\t\t\t\t.bind(\n\t\t\t\t\tconsumedAt,\n\t\t\t\t\tdigest,\n\t\t\t\t\t_opts.token,\n\t\t\t\t\tgrantId,\n\t\t\t\t\tinitial.bootstrap_grant_id ?? null,\n\t\t\t\t\tinitial.consumed_at ? 1 : 0,\n\t\t\t\t\t_opts.deviceId,\n\t\t\t\t\t...guard.boundEligibilityValues,\n\t\t\t\t\t...enrollmentValues,\n\t\t\t\t),\n\t\t];\n\t\tconst accepted = await runProjectInviteBatch(\n\t\t\tthis.db,\n\t\t\tstatements,\n\t\t\tinitial,\n\t\t\t_opts,\n\t\t\tguard,\n\t\t\tenrollmentValues,\n\t\t);\n\t\t// This is a post-commit denial, not a claim that the committed batch was rolled back.\n\t\tawait guard.assertEligible({ requireBinding: false });\n\t\tconst currentGroup = await this.getGroup(initial.group_id);\n\t\tif (!currentGroup) throw new Error(\"group_not_found\");\n\t\tif (currentGroup.archived_at) throw new Error(\"group_archived\");\n\t\tconst saved = await this.getInviteByTokenForInspection(_opts.token);\n\t\tif (!saved) throw new Error(\"invite_invalid\");\n\t\tassertProjectInviteBinding(saved, _opts);\n\t\tconst enrollment = await this.getEnrollment(saved.group_id, _opts.deviceId);\n\t\tconst seed = saved.inviter_device_id\n\t\t\t? await this.getEnrollment(saved.group_id, saved.inviter_device_id)\n\t\t\t: null;\n\t\tconst grant = saved.bootstrap_grant_id\n\t\t\t? await this.getBootstrapGrant(saved.bootstrap_grant_id)\n\t\t\t: null;\n\t\tawait guard.assertEligible({ requireBinding: true });\n\t\tif (!enrollment) throw new Error(\"invite_acceptance_incomplete\");\n\t\tif (enrollment.identity_id !== _opts.recipientActorId) {\n\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\t}\n\t\treturn {\n\t\t\tstatus: accepted ? \"accepted\" : \"existing\",\n\t\t\tinvite: saved,\n\t\t\tenrollment,\n\t\t\tseed_enrollment: seed,\n\t\t\tbootstrap_grant: grant,\n\t\t};\n\t}\n\n\tasync listInvites(_groupId: string): Promise<CoordinatorInvite[]> {\n\t\treturn (\n\t\t\tawait allRows<CoordinatorInvite>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT ${INVITE_COLUMNS}\n\t\t\t\t\t FROM coordinator_invites WHERE group_id = ?\n\t\t\t\t\t ORDER BY created_at DESC`)\n\t\t\t\t\t.bind(_groupId),\n\t\t\t)\n\t\t).map((row) => rowToRecord<CoordinatorInvite>(row));\n\t}\n\n\tasync createJoinRequest(\n\t\t_opts: CoordinatorCreateJoinRequestInput,\n\t): Promise<CoordinatorJoinRequest> {\n\t\tconst now = nowISO();\n\t\tconst requestId = tokenUrlSafe(12);\n\t\tawait this.db\n\t\t\t.prepare(`INSERT INTO coordinator_join_requests(\n\t\t\t\trequest_id, group_id, device_id, public_key, fingerprint, display_name, token, status, created_at, reviewed_at, reviewed_by\n\t\t\t) VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', ?, NULL, NULL)`)\n\t\t\t.bind(\n\t\t\t\trequestId,\n\t\t\t\t_opts.groupId,\n\t\t\t\t_opts.deviceId,\n\t\t\t\t_opts.publicKey,\n\t\t\t\t_opts.fingerprint,\n\t\t\t\t_opts.displayName ?? null,\n\t\t\t\t_opts.token,\n\t\t\t\tnow,\n\t\t\t)\n\t\t\t.run();\n\t\tconst row = await firstRow<CoordinatorJoinRequest>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT request_id, group_id, device_id, public_key, fingerprint, display_name, token, status, created_at, reviewed_at, reviewed_by\n\t\t\t\t\t FROM coordinator_join_requests WHERE request_id = ?`)\n\t\t\t\t.bind(requestId),\n\t\t);\n\t\treturn rowToRecord<CoordinatorJoinRequest>(row);\n\t}\n\n\tasync listJoinRequests(_groupId: string, _status?: string): Promise<CoordinatorJoinRequest[]> {\n\t\tconst status = _status ?? \"pending\";\n\t\treturn (\n\t\t\tawait allRows<CoordinatorJoinRequest>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT request_id, group_id, device_id, public_key, fingerprint, display_name, token, status, created_at, reviewed_at, reviewed_by\n\t\t\t\t\t\t FROM coordinator_join_requests\n\t\t\t\t\t\t WHERE group_id = ? AND status = ?\n\t\t\t\t\t\t ORDER BY created_at ASC, device_id ASC`)\n\t\t\t\t\t.bind(_groupId, status),\n\t\t\t)\n\t\t).map((row) => rowToRecord<CoordinatorJoinRequest>(row));\n\t}\n\n\tasync reviewJoinRequest(\n\t\t_opts: CoordinatorReviewJoinRequestInput,\n\t): Promise<CoordinatorJoinRequestReviewResult | null> {\n\t\t_opts = {\n\t\t\t..._opts,\n\t\t\tbootstrapGrant: _opts.bootstrapGrant ? { ..._opts.bootstrapGrant } : _opts.bootstrapGrant,\n\t\t};\n\t\tconst sourceRow = await firstRow<CoordinatorJoinRequest & { public_key: string }>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT request_id, group_id, device_id, public_key, fingerprint, display_name, token, status,\n\t\t\t\t\t created_at, reviewed_at, reviewed_by\n\t\t\t\t\t FROM coordinator_join_requests WHERE request_id = ?`)\n\t\t\t\t.bind(_opts.requestId),\n\t\t);\n\t\tif (!sourceRow) return null;\n\t\tconst row = { ...sourceRow };\n\t\tif (row.status !== \"pending\") {\n\t\t\treturn { ...rowToRecord<CoordinatorJoinRequest>(row), _no_transition: true };\n\t\t}\n\t\tconst bootstrapGrantRequest = normalizeCoordinatorBootstrapGrantRequest(_opts.bootstrapGrant);\n\t\tif (!_opts.approved) return this.denyJoinRequest(_opts);\n\t\tif (!this.db.batch) throw new Error(\"join_review_unavailable\");\n\t\tconst reviewedAt = nowISO();\n\t\tconst { guard, bootstrapGrantInput } = await this.prepareJoinApproval(\n\t\t\trow,\n\t\t\tbootstrapGrantRequest,\n\t\t);\n\t\tconst statements: D1PreparedStatementLike[] = [\n\t\t\tthis.db\n\t\t\t\t.prepare(`UPDATE coordinator_join_requests\n\t\t\t\t\t\t SET status = ?, reviewed_at = ?, reviewed_by = ?\n\t\t\t\t\t\t WHERE request_id = ? AND status = 'pending'\n\t\t\t\t\t\t AND ${guard.eligibilitySql} AND ${guard.sourceSql}`)\n\t\t\t\t.bind(\n\t\t\t\t\t\"approved\",\n\t\t\t\t\treviewedAt,\n\t\t\t\t\t_opts.reviewedBy ?? null,\n\t\t\t\t\t_opts.requestId,\n\t\t\t\t\t...guard.eligibilityValues,\n\t\t\t\t\t...guard.sourceValues,\n\t\t\t\t),\n\t\t];\n\t\tconst bootstrapGrantId = bootstrapGrantInput ? tokenUrlSafe(12) : null;\n\t\tstatements.push(\n\t\t\t...this.prepareJoinApprovalStatements(\n\t\t\t\trow,\n\t\t\t\tguard,\n\t\t\t\treviewedAt,\n\t\t\t\t_opts.reviewedBy ?? null,\n\t\t\t\tbootstrapGrantInput,\n\t\t\t\tbootstrapGrantId,\n\t\t\t),\n\t\t);\n\t\tif (!(await this.executeJoinApprovalBatch(statements, { requestId: _opts.requestId, guard })))\n\t\t\treturn this.classifyJoinReviewFailure(_opts.requestId, guard);\n\t\treturn this.readCompletedJoinReview(_opts.requestId, bootstrapGrantId);\n\t}\n\n\tprivate async prepareJoinApproval(\n\t\trow: CoordinatorJoinRequest & { public_key: string },\n\t\tbootstrapGrantRequest: ReturnType<typeof normalizeCoordinatorBootstrapGrantRequest>,\n\t) {\n\t\tlet bootstrapGrantInput: CoordinatorCreateBootstrapGrantInput | null = null;\n\t\tlet seedEnrollment: CoordinatorEnrollment | null = null;\n\t\tif (bootstrapGrantRequest) {\n\t\t\tseedEnrollment = await firstRow<CoordinatorEnrollment>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(\n\t\t\t\t\t\t`SELECT * FROM enrolled_devices WHERE group_id = ? AND device_id = ? AND enabled = 1`,\n\t\t\t\t\t)\n\t\t\t\t\t.bind(row.group_id, bootstrapGrantRequest.seedDeviceId),\n\t\t\t);\n\t\t\tif (!seedEnrollment) {\n\t\t\t\tthrow new Error(\"bootstrap grant seed device is not enrolled in the group.\");\n\t\t\t}\n\t\t\tseedEnrollment = { ...seedEnrollment };\n\t\t\tif (bootstrapGrantRequest.seedDeviceId === row.device_id) {\n\t\t\t\tthrow new Error(\"bootstrap grant seed and worker device ids must differ.\");\n\t\t\t}\n\t\t\tbootstrapGrantInput = {\n\t\t\t\t...bootstrapGrantRequest,\n\t\t\t\tgroupId: row.group_id,\n\t\t\t\tworkerDeviceId: row.device_id,\n\t\t\t};\n\t\t}\n\t\tconst currentPublicKey = captureLegacyEnrollmentPublicKey(\n\t\t\tawait firstRow<{ public_key: string }>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT public_key FROM enrolled_devices WHERE group_id = ? AND device_id = ?`)\n\t\t\t\t\t.bind(row.group_id, row.device_id),\n\t\t\t),\n\t\t);\n\t\tconst guard = joinReviewGuardEvidence(\n\t\t\trow,\n\t\t\tseedEnrollment,\n\t\t\t{\n\t\t\t\trecipient: await ed25519KeyIdForRevocation(row.public_key),\n\t\t\t\tseed: seedEnrollment ? await ed25519KeyIdForRevocation(seedEnrollment.public_key) : null,\n\t\t\t\tcurrent:\n\t\t\t\t\tcurrentPublicKey === null ? null : await ed25519KeyIdForRevocation(currentPublicKey),\n\t\t\t},\n\t\t\tcurrentPublicKey,\n\t\t);\n\t\tawait this.assertJoinOwnershipAvailable(guard);\n\t\treturn { guard, bootstrapGrantInput };\n\t}\n\n\tprivate async assertJoinOwnershipAvailable(guard: ReturnType<typeof joinReviewGuardEvidence>) {\n\t\tconst revocation = await readRecipientInviteDecision(\n\t\t\t() =>\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT (${guard.revocationSql}) AS revoked`)\n\t\t\t\t\t.bind(...guard.revocationValues),\n\t\t\t[\"revoked\"],\n\t\t);\n\t\tif (revocation.revoked === 1) throw new Error(\"device_revoked\");\n\t\tconst state = await readRecipientInviteDecision(\n\t\t\t() =>\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT (${guard.revocationSql}) AS revoked, (${guard.ownershipSql}) AS owned`)\n\t\t\t\t\t.bind(...guard.revocationValues, ...guard.ownershipValues),\n\t\t\t[\"revoked\", \"owned\"],\n\t\t);\n\t\tif (state.revoked === 1) throw new Error(\"device_revoked\");\n\t\tif (state.owned === 1) throw new Error(\"device_ownership_requires_verified_identity\");\n\t}\n\n\tprivate async executeJoinApprovalBatch(\n\t\tstatements: D1PreparedStatementLike[],\n\t\toptions: { requestId: string; guard: ReturnType<typeof joinReviewGuardEvidence> },\n\t): Promise<boolean> {\n\t\tif (!this.db.batch) throw new Error(\"join_review_unavailable\");\n\t\tlet results: unknown[];\n\t\ttry {\n\t\t\tresults = await this.db.batch(statements);\n\t\t} catch {\n\t\t\t// A transport error may follow commit. Only a still-pending request permits denial diagnosis.\n\t\t\tlet latest: { status: unknown } | null;\n\t\t\ttry {\n\t\t\t\tlatest = await firstRow<{ status: unknown }>(\n\t\t\t\t\tthis.db\n\t\t\t\t\t\t.prepare(`SELECT status FROM coordinator_join_requests WHERE request_id = ?`)\n\t\t\t\t\t\t.bind(options.requestId),\n\t\t\t\t);\n\t\t\t} catch {\n\t\t\t\tthrow new Error(\"join_review_incomplete\");\n\t\t\t}\n\t\t\tif (latest?.status === \"pending\") await this.assertJoinOwnershipAvailable(options.guard);\n\t\t\tthrow new Error(\"join_review_incomplete\");\n\t\t}\n\t\tif (results.length !== statements.length) throw new Error(\"join_review_incomplete\");\n\t\tassertJoinReviewConfirmation(results.at(-1));\n\t\tconst changes = results.slice(0, -1).map(joinReviewResultChanges);\n\t\tconst winner = changes[0];\n\t\tif ((winner !== 0 && winner !== 1) || changes.some((count) => count !== winner))\n\t\t\tthrow new Error(\"join_review_incomplete\");\n\t\treturn winner === 1;\n\t}\n\n\tprivate async denyJoinRequest(\n\t\topts: CoordinatorReviewJoinRequestInput,\n\t): Promise<CoordinatorJoinRequestReviewResult | null> {\n\t\tconst statement = this.db\n\t\t\t.prepare(`UPDATE coordinator_join_requests SET status = 'denied', reviewed_at = ?, reviewed_by = ?\n\t\t\tWHERE request_id = ? AND status = 'pending'`)\n\t\t\t.bind(nowISO(), opts.reviewedBy ?? null, opts.requestId);\n\t\tconst changes = this.db.batch\n\t\t\t? joinReviewResultChanges((await this.db.batch([statement]))[0])\n\t\t\t: await runChanges(statement);\n\t\tif (changes === 0) return this.classifyJoinReviewFailure(opts.requestId, null);\n\t\tif (changes !== 1) throw new Error(\"join_review_incomplete\");\n\t\treturn this.readCompletedJoinReview(opts.requestId, null);\n\t}\n\n\tprivate async readCompletedJoinReview(\n\t\trequestId: string,\n\t\tgrantId: string | null,\n\t): Promise<CoordinatorJoinRequestReviewResult> {\n\t\tconst updated = await firstRow<CoordinatorJoinRequestReviewResult>(\n\t\t\tthis.db\n\t\t\t\t.prepare(\n\t\t\t\t\t`SELECT ${JOIN_REVIEW_COLUMNS} FROM coordinator_join_requests WHERE request_id = ?`,\n\t\t\t\t)\n\t\t\t\t.bind(requestId),\n\t\t);\n\t\tif (!updated) throw new Error(\"join_review_incomplete\");\n\t\tconst grant = grantId ? await this.getBootstrapGrant(grantId) : null;\n\t\tif (grantId && !grant) throw new Error(\"join_review_incomplete\");\n\t\treturn { ...updated, bootstrap_grant: grant };\n\t}\n\n\tprivate prepareJoinApprovalStatements(\n\t\trow: CoordinatorJoinRequest & { public_key: string },\n\t\tguard: ReturnType<typeof joinReviewGuardEvidence>,\n\t\treviewedAt: string,\n\t\treviewedBy: string | null,\n\t\tgrant: CoordinatorCreateBootstrapGrantInput | null,\n\t\tgrantId: string | null,\n\t): D1PreparedStatementLike[] {\n\t\tconst approvedSql = `${guard.eligibilitySql} AND EXISTS (SELECT 1 FROM coordinator_join_requests\n\t\t\tWHERE request_id = ? AND status = 'approved' AND reviewed_at = ? AND reviewed_by IS ?)`;\n\t\tconst approvedValues = [...guard.eligibilityValues, row.request_id, reviewedAt, reviewedBy];\n\t\tconst enrolledSql = `${approvedSql} AND EXISTS (SELECT 1 FROM enrolled_devices\n\t\t\tWHERE group_id = ? AND device_id = ? AND public_key = ? AND fingerprint = ? AND enabled = 1)`;\n\t\tconst enrolledValues = [\n\t\t\t...approvedValues,\n\t\t\trow.group_id,\n\t\t\trow.device_id,\n\t\t\trow.public_key,\n\t\t\trow.fingerprint,\n\t\t];\n\t\t// changes() carries this batch's CAS, not a timestamp that another reviewer can share.\n\t\t// CASE raises a SQL error on trigger-side drift rather than committing a zero-row sibling.\n\t\tconst statements = [\n\t\t\tthis.db\n\t\t\t\t.prepare(`INSERT INTO enrolled_devices(\n\t\t\tgroup_id, device_id, public_key, fingerprint, display_name, enabled, created_at)\n\t\t\tSELECT ?, ?, ?, ?, ?, 1, ? FROM (SELECT 1 WHERE changes() = 1) AS winner\n\t\t\tWHERE CASE WHEN ${approvedSql} AND ${guard.sourceSql} THEN 1 ELSE json('join_review_incomplete') END\n\t\t\tON CONFLICT(group_id, device_id) DO UPDATE SET public_key = excluded.public_key,\n\t\t\tfingerprint = excluded.fingerprint, display_name = excluded.display_name, enabled = 1\n\t\t\tWHERE CASE WHEN ${guard.eligibilitySql} AND ${guard.sourceSql}\n\t\t\tTHEN 1 ELSE json('join_review_incomplete') END`)\n\t\t\t\t.bind(\n\t\t\t\t\trow.group_id,\n\t\t\t\t\trow.device_id,\n\t\t\t\t\trow.public_key,\n\t\t\t\t\trow.fingerprint,\n\t\t\t\t\trow.display_name ?? null,\n\t\t\t\t\tnowISO(),\n\t\t\t\t\t...approvedValues,\n\t\t\t\t\t...guard.sourceValues,\n\t\t\t\t\t...guard.eligibilityValues,\n\t\t\t\t\t...guard.sourceValues,\n\t\t\t\t),\n\t\t];\n\t\tif (grant && grantId) {\n\t\t\tstatements.push(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`INSERT INTO coordinator_bootstrap_grants(\n\t\t\t\tgrant_id, group_id, seed_device_id, worker_device_id, expires_at, created_at, created_by, revoked_at)\n\t\t\t\tSELECT ?, ?, ?, ?, ?, ?, ?, NULL FROM (SELECT 1 WHERE changes() = 1) AS winner\n\t\t\t\tWHERE CASE WHEN ${enrolledSql} THEN 1 ELSE json('join_review_incomplete') END`)\n\t\t\t\t\t.bind(\n\t\t\t\t\t\tgrantId,\n\t\t\t\t\t\tgrant.groupId,\n\t\t\t\t\t\tgrant.seedDeviceId,\n\t\t\t\t\t\tgrant.workerDeviceId,\n\t\t\t\t\t\tgrant.expiresAt,\n\t\t\t\t\t\tnowISO(),\n\t\t\t\t\t\tgrant.createdBy ?? null,\n\t\t\t\t\t\t...enrolledValues,\n\t\t\t\t\t),\n\t\t\t);\n\t\t}\n\t\tstatements.push(\n\t\t\tthis.prepareJoinApprovalConfirmation(\n\t\t\t\trow,\n\t\t\t\treviewedAt,\n\t\t\t\treviewedBy,\n\t\t\t\tguard,\n\t\t\t\tenrolledSql,\n\t\t\t\tenrolledValues,\n\t\t\t\tgrant,\n\t\t\t\tgrantId,\n\t\t\t),\n\t\t);\n\t\treturn statements;\n\t}\n\n\tprivate prepareJoinApprovalConfirmation(\n\t\trow: CoordinatorJoinRequest,\n\t\treviewedAt: string,\n\t\treviewedBy: string | null,\n\t\tguard: ReturnType<typeof joinReviewGuardEvidence>,\n\t\tenrolledSql: string,\n\t\tenrolledValues: unknown[],\n\t\tgrant: CoordinatorCreateBootstrapGrantInput | null,\n\t\tgrantId: string | null,\n\t): D1PreparedStatementLike {\n\t\tconst completeSql = `${enrolledSql} AND (? IS NULL OR EXISTS (\n\t\t\tSELECT 1 FROM coordinator_bootstrap_grants WHERE grant_id = ? AND group_id = ?\n\t\t\tAND seed_device_id = ? AND worker_device_id = ? AND expires_at = ? AND revoked_at IS NULL))`;\n\t\t// A zero changes() chain must not commit a newly owned/revoked target after CAS.\n\t\t// Missing effects/receipts still report incomplete, not a fictional atomic rollback.\n\t\tconst zeroChainSql = `NOT EXISTS (SELECT 1 FROM coordinator_join_requests\n\t\t\tWHERE request_id = ? AND status = 'approved' AND reviewed_at = ? AND reviewed_by IS ?)\n\t\t\tOR (${guard.eligibilitySql})`;\n\t\treturn this.db\n\t\t\t.prepare(`SELECT CASE WHEN changes() = 0 THEN\n\t\t\tCASE WHEN ${zeroChainSql} THEN 1 ELSE json('join_review_incomplete') END\n\t\t\tWHEN ${completeSql} THEN 1 ELSE json('join_review_incomplete') END AS confirmed`)\n\t\t\t.bind(\n\t\t\t\trow.request_id,\n\t\t\t\treviewedAt,\n\t\t\t\treviewedBy,\n\t\t\t\t...guard.eligibilityValues,\n\t\t\t\t...enrolledValues,\n\t\t\t\tgrantId,\n\t\t\t\tgrantId,\n\t\t\t\trow.group_id,\n\t\t\t\tgrant?.seedDeviceId ?? null,\n\t\t\t\trow.device_id,\n\t\t\t\tgrant?.expiresAt ?? null,\n\t\t\t);\n\t}\n\n\tprivate async classifyJoinReviewFailure(\n\t\trequestId: string,\n\t\tguard: ReturnType<typeof joinReviewGuardEvidence> | null,\n\t): Promise<CoordinatorJoinRequestReviewResult | null> {\n\t\tconst latest = await firstRow<CoordinatorJoinRequestReviewResult>(\n\t\t\tthis.db\n\t\t\t\t.prepare(\n\t\t\t\t\t`SELECT ${JOIN_REVIEW_COLUMNS} FROM coordinator_join_requests WHERE request_id = ?`,\n\t\t\t\t)\n\t\t\t\t.bind(requestId),\n\t\t);\n\t\tif (!latest) return null;\n\t\tif (latest.status !== \"pending\") return { ...latest, _no_transition: true };\n\t\tif (guard) await this.assertJoinOwnershipAvailable(guard);\n\t\tthrow new Error(\"join_review_incomplete\");\n\t}\n\n\tasync createReciprocalApproval(\n\t\topts: CoordinatorCreateReciprocalApprovalInput,\n\t): Promise<CoordinatorReciprocalApproval> {\n\t\tconst groupId = opts.groupId.trim();\n\t\tconst requestingDeviceId = opts.requestingDeviceId.trim();\n\t\tconst requestedDeviceId = opts.requestedDeviceId.trim();\n\t\tconst hasExpectedIncomingRequestId = opts.expectedIncomingRequestId !== undefined;\n\t\tconst expectedIncomingRequestId = opts.expectedIncomingRequestId?.trim() ?? \"\";\n\t\tif (!groupId || !requestingDeviceId || !requestedDeviceId) {\n\t\t\tthrow new Error(\"groupId, requestingDeviceId, and requestedDeviceId are required.\");\n\t\t}\n\t\tif (requestingDeviceId === requestedDeviceId) {\n\t\t\tthrow new Error(\"requesting and requested device ids must differ.\");\n\t\t}\n\t\tif (hasExpectedIncomingRequestId) {\n\t\t\tconst resolvedAt = nowISO();\n\t\t\tconst changes = await runChanges(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`UPDATE coordinator_reciprocal_approvals\n\t\t\t\t\t\t SET status = 'completed', resolved_at = ?\n\t\t\t\t\t\t WHERE request_id = ?\n\t\t\t\t\t\t AND group_id = ?\n\t\t\t\t\t\t AND requesting_device_id = ?\n\t\t\t\t\t\t AND requested_device_id = ?\n\t\t\t\t\t\t AND status = 'pending'`)\n\t\t\t\t\t.bind(\n\t\t\t\t\t\tresolvedAt,\n\t\t\t\t\t\texpectedIncomingRequestId,\n\t\t\t\t\t\tgroupId,\n\t\t\t\t\t\trequestedDeviceId,\n\t\t\t\t\t\trequestingDeviceId,\n\t\t\t\t\t),\n\t\t\t);\n\t\t\tif (changes !== 1) {\n\t\t\t\tthrow new CoordinatorReciprocalApprovalRequestChangedError();\n\t\t\t}\n\t\t\tconst completed = await firstRow<CoordinatorReciprocalApproval>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t\t\t FROM coordinator_reciprocal_approvals WHERE request_id = ?`)\n\t\t\t\t\t.bind(expectedIncomingRequestId),\n\t\t\t);\n\t\t\treturn rowToRecord<CoordinatorReciprocalApproval>(completed);\n\t\t}\n\t\tconst pendingPair = reciprocalPendingPair(requestingDeviceId, requestedDeviceId);\n\t\tconst existing = await firstRow<CoordinatorReciprocalApproval>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t\t FROM coordinator_reciprocal_approvals\n\t\t\t\t\t WHERE group_id = ? AND requesting_device_id = ? AND requested_device_id = ? AND status = 'pending'\n\t\t\t\t\t ORDER BY created_at DESC LIMIT 1`)\n\t\t\t\t.bind(groupId, requestingDeviceId, requestedDeviceId),\n\t\t);\n\t\tif (existing) return rowToRecord<CoordinatorReciprocalApproval>(existing);\n\t\tconst reverse = await firstRow<CoordinatorReciprocalApproval>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t\t FROM coordinator_reciprocal_approvals\n\t\t\t\t\t WHERE group_id = ? AND requesting_device_id = ? AND requested_device_id = ? AND status = 'pending'\n\t\t\t\t\t ORDER BY created_at DESC LIMIT 1`)\n\t\t\t\t.bind(groupId, requestedDeviceId, requestingDeviceId),\n\t\t);\n\t\tif (reverse) {\n\t\t\tconst resolvedAt = nowISO();\n\t\t\tawait this.db\n\t\t\t\t.prepare(\n\t\t\t\t\t`UPDATE coordinator_reciprocal_approvals SET status = 'completed', resolved_at = ? WHERE request_id = ?`,\n\t\t\t\t)\n\t\t\t\t.bind(resolvedAt, reverse.request_id)\n\t\t\t\t.run();\n\t\t\tconst completed = await firstRow<CoordinatorReciprocalApproval>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t\t\t FROM coordinator_reciprocal_approvals WHERE request_id = ?`)\n\t\t\t\t\t.bind(reverse.request_id),\n\t\t\t);\n\t\t\treturn rowToRecord<CoordinatorReciprocalApproval>(completed);\n\t\t}\n\t\tconst requestId = tokenUrlSafe(12);\n\t\tconst createdAt = nowISO();\n\t\ttry {\n\t\t\tawait this.db\n\t\t\t\t.prepare(`INSERT INTO coordinator_reciprocal_approvals(\n\t\t\t\t\t\trequest_id,\n\t\t\t\t\t\tgroup_id,\n\t\t\t\t\t\trequesting_device_id,\n\t\t\t\t\t\trequested_device_id,\n\t\t\t\t\t\tpending_pair_low_device_id,\n\t\t\t\t\t\tpending_pair_high_device_id,\n\t\t\t\t\t\tstatus,\n\t\t\t\t\t\tcreated_at,\n\t\t\t\t\t\tresolved_at\n\t\t\t\t\t) VALUES (?, ?, ?, ?, ?, ?, 'pending', ?, NULL)`)\n\t\t\t\t.bind(\n\t\t\t\t\trequestId,\n\t\t\t\t\tgroupId,\n\t\t\t\t\trequestingDeviceId,\n\t\t\t\t\trequestedDeviceId,\n\t\t\t\t\tpendingPair.low,\n\t\t\t\t\tpendingPair.high,\n\t\t\t\t\tcreatedAt,\n\t\t\t\t)\n\t\t\t\t.run();\n\t\t} catch (error) {\n\t\t\tif (!isUniqueConstraintError(error)) throw error;\n\t\t\tconst sameDirection = await firstRow<CoordinatorReciprocalApproval>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t\t\t FROM coordinator_reciprocal_approvals\n\t\t\t\t\t\t WHERE group_id = ? AND requesting_device_id = ? AND requested_device_id = ? AND status = 'pending'\n\t\t\t\t\t\t ORDER BY created_at DESC LIMIT 1`)\n\t\t\t\t\t.bind(groupId, requestingDeviceId, requestedDeviceId),\n\t\t\t);\n\t\t\tif (sameDirection) return rowToRecord<CoordinatorReciprocalApproval>(sameDirection);\n\t\t\tconst reverseAfterConflict = await firstRow<CoordinatorReciprocalApproval>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t\t\t FROM coordinator_reciprocal_approvals\n\t\t\t\t\t\t WHERE group_id = ? AND requesting_device_id = ? AND requested_device_id = ? AND status = 'pending'\n\t\t\t\t\t\t ORDER BY created_at DESC LIMIT 1`)\n\t\t\t\t\t.bind(groupId, requestedDeviceId, requestingDeviceId),\n\t\t\t);\n\t\t\tif (reverseAfterConflict) {\n\t\t\t\tconst resolvedAt = nowISO();\n\t\t\t\tawait this.db\n\t\t\t\t\t.prepare(\n\t\t\t\t\t\t`UPDATE coordinator_reciprocal_approvals SET status = 'completed', resolved_at = ? WHERE request_id = ?`,\n\t\t\t\t\t)\n\t\t\t\t\t.bind(resolvedAt, reverseAfterConflict.request_id)\n\t\t\t\t\t.run();\n\t\t\t\tconst completed = await firstRow<CoordinatorReciprocalApproval>(\n\t\t\t\t\tthis.db\n\t\t\t\t\t\t.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t\t\t\t FROM coordinator_reciprocal_approvals WHERE request_id = ?`)\n\t\t\t\t\t\t.bind(reverseAfterConflict.request_id),\n\t\t\t\t);\n\t\t\t\treturn rowToRecord<CoordinatorReciprocalApproval>(completed);\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t\tconst created = await firstRow<CoordinatorReciprocalApproval>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t\t FROM coordinator_reciprocal_approvals WHERE request_id = ?`)\n\t\t\t\t.bind(requestId),\n\t\t);\n\t\treturn rowToRecord<CoordinatorReciprocalApproval>(created);\n\t}\n\n\tprivate async getBootstrapParticipantSource(groupId: string, deviceId: string) {\n\t\tconst row = await firstRow<BootstrapParticipantSource>(\n\t\t\tthis.db.prepare(BOOTSTRAP_PARTICIPANT_SOURCE_SQL).bind(groupId, deviceId),\n\t\t);\n\t\treturn captureBootstrapParticipantSource(row);\n\t}\n\n\tasync createBootstrapGrant(\n\t\topts: CoordinatorCreateBootstrapGrantInput,\n\t): Promise<CoordinatorBootstrapGrant> {\n\t\tconst input = normalizeCoordinatorBootstrapGrantInput(opts);\n\t\ttry {\n\t\t\tconst revoked = () => this.db.prepare(BOOTSTRAP_PARTICIPANTS_REVOKED_SQL);\n\t\t\tif (await firstRow(revoked().bind(input.seedDeviceId, null, input.workerDeviceId, null))) {\n\t\t\t\tthrow new Error(\"device_revoked\");\n\t\t\t}\n\t\t\tconst seed = await this.getBootstrapParticipantSource(input.groupId, input.seedDeviceId);\n\t\t\tconst worker = await this.getBootstrapParticipantSource(input.groupId, input.workerDeviceId);\n\t\t\t// Copy both source tuples before hashing yields; never infer keys from legacy fingerprints.\n\t\t\tconst subjects = [\n\t\t\t\tinput.seedDeviceId,\n\t\t\t\tseed ? await ed25519KeyIdForRevocation(seed.public_key) : null,\n\t\t\t\tinput.workerDeviceId,\n\t\t\t\tworker ? await ed25519KeyIdForRevocation(worker.public_key) : null,\n\t\t\t];\n\t\t\tif (await firstRow(revoked().bind(...subjects))) throw new Error(\"device_revoked\");\n\t\t\tconst values = bootstrapRawInsertValues(\n\t\t\t\tinput,\n\t\t\t\t{ grantId: tokenUrlSafe(12), createdAt: nowISO() },\n\t\t\t\t{ seed, worker },\n\t\t\t\tsubjects,\n\t\t\t);\n\t\t\tconst row = await firstRow<CoordinatorBootstrapGrant>(\n\t\t\t\tthis.db.prepare(BOOTSTRAP_RAW_INSERT_SQL).bind(...values),\n\t\t\t);\n\t\t\tif (row) return rowToRecord<CoordinatorBootstrapGrant>(row);\n\t\t\tif (await firstRow(revoked().bind(...subjects))) throw new Error(\"device_revoked\");\n\t\t\tthrow new Error(\"bootstrap_grant_write_incomplete\");\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error && error.message === \"device_revoked\") throw error;\n\t\t\tthrow new Error(\"bootstrap_grant_write_incomplete\");\n\t\t}\n\t}\n\n\tprivate async getScope(scopeId: string): Promise<CoordinatorScope | null> {\n\t\tconst row = await firstRow<CoordinatorScope>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT scope_id, label, kind, authority_type, coordinator_id, group_id,\n\t\t\t\t\t\tmanifest_issuer_device_id, membership_epoch, manifest_hash, status, created_at, updated_at\n\t\t\t\t\t FROM coordinator_scopes WHERE scope_id = ?`)\n\t\t\t\t.bind(scopeId),\n\t\t);\n\t\treturn row ? rowToRecord<CoordinatorScope>(row) : null;\n\t}\n\n\tprivate async getScopeMembership(\n\t\tscopeId: string,\n\t\tdeviceId: string,\n\t): Promise<CoordinatorScopeMembership | null> {\n\t\tconst row = await firstRow<CoordinatorScopeMembership>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT scope_id, device_id, role, status, membership_epoch, coordinator_id, group_id,\n\t\t\t\t\t\tmanifest_issuer_device_id, manifest_hash, signed_manifest_json, updated_at\n\t\t\t\t\t FROM coordinator_scope_memberships\n\t\t\t\t\t WHERE scope_id = ? AND device_id = ?`)\n\t\t\t\t.bind(scopeId, deviceId),\n\t\t);\n\t\treturn row ? rowToRecord<CoordinatorScopeMembership>(row) : null;\n\t}\n\n\tasync createScope(opts: CoordinatorCreateScopeInput): Promise<CoordinatorScope> {\n\t\tconst normalized = normalizeCoordinatorCreateScopeInput(opts);\n\t\tif (await this.getScope(normalized.scopeId)) throw new Error(\"scopeId already exists.\");\n\t\tconst now = nowISO();\n\t\tawait this.db\n\t\t\t.prepare(`INSERT INTO coordinator_scopes(\n\t\t\t\t\tscope_id, label, kind, authority_type, coordinator_id, group_id,\n\t\t\t\t\tmanifest_issuer_device_id, membership_epoch, manifest_hash, status, created_at, updated_at\n\t\t\t\t) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)\n\t\t\t.bind(\n\t\t\t\tnormalized.scopeId,\n\t\t\t\tnormalized.label,\n\t\t\t\tnormalized.kind,\n\t\t\t\tnormalized.authorityType,\n\t\t\t\tnormalized.coordinatorId,\n\t\t\t\tnormalized.groupId,\n\t\t\t\tnormalized.manifestIssuerDeviceId,\n\t\t\t\tnormalized.membershipEpoch,\n\t\t\t\tnormalized.manifestHash,\n\t\t\t\tnormalized.status,\n\t\t\t\tnow,\n\t\t\t\tnow,\n\t\t\t)\n\t\t\t.run();\n\t\tconst scope = await this.getScope(normalized.scopeId);\n\t\tif (!scope) throw new Error(\"scope insert returned no row\");\n\t\treturn scope;\n\t}\n\n\tasync updateScope(opts: CoordinatorUpdateScopeInput): Promise<CoordinatorScope | null> {\n\t\tconst scopeId = clean(opts.scopeId);\n\t\tconst existing = scopeId ? await this.getScope(scopeId) : null;\n\t\tif (!existing) return null;\n\t\tconst normalized = normalizeCoordinatorUpdateScopeInput(opts, existing);\n\t\tawait this.db\n\t\t\t.prepare(`UPDATE coordinator_scopes\n\t\t\t\t SET label = ?,\n\t\t\t\t\t kind = ?,\n\t\t\t\t\t authority_type = ?,\n\t\t\t\t\t coordinator_id = ?,\n\t\t\t\t\t group_id = ?,\n\t\t\t\t\t manifest_issuer_device_id = ?,\n\t\t\t\t\t membership_epoch = ?,\n\t\t\t\t\t manifest_hash = ?,\n\t\t\t\t\t status = ?,\n\t\t\t\t\t updated_at = ?\n\t\t\t\t WHERE scope_id = ?`)\n\t\t\t.bind(\n\t\t\t\tnormalized.label,\n\t\t\t\tnormalized.kind,\n\t\t\t\tnormalized.authorityType,\n\t\t\t\tnormalized.coordinatorId,\n\t\t\t\tnormalized.groupId,\n\t\t\t\tnormalized.manifestIssuerDeviceId,\n\t\t\t\tnormalized.membershipEpoch,\n\t\t\t\tnormalized.manifestHash,\n\t\t\t\tnormalized.status,\n\t\t\t\tnowISO(),\n\t\t\t\tnormalized.scopeId,\n\t\t\t)\n\t\t\t.run();\n\t\treturn await this.getScope(normalized.scopeId);\n\t}\n\n\tasync listScopes(opts: CoordinatorListScopesInput = {}): Promise<CoordinatorScope[]> {\n\t\tconst where: string[] = [];\n\t\tconst params: unknown[] = [];\n\t\tconst coordinatorId = clean(opts.coordinatorId);\n\t\tconst groupId = clean(opts.groupId);\n\t\tconst status = clean(opts.status);\n\t\tif (coordinatorId) {\n\t\t\twhere.push(\"coordinator_id = ?\");\n\t\t\tparams.push(coordinatorId);\n\t\t}\n\t\tif (groupId) {\n\t\t\twhere.push(\"group_id = ?\");\n\t\t\tparams.push(groupId);\n\t\t}\n\t\tif (status) {\n\t\t\twhere.push(\"status = ?\");\n\t\t\tparams.push(status);\n\t\t} else if (!opts.includeInactive) {\n\t\t\twhere.push(\"status = 'active'\");\n\t\t}\n\t\tconst whereSql = where.length ? `WHERE ${where.join(\" AND \")}` : \"\";\n\t\tconst statement =\n\t\t\tthis.db.prepare(`SELECT scope_id, label, kind, authority_type, coordinator_id, group_id,\n\t\t\t\tmanifest_issuer_device_id, membership_epoch, manifest_hash, status, created_at, updated_at\n\t\t\t FROM coordinator_scopes ${whereSql}\n\t\t\t ORDER BY coordinator_id ASC, group_id ASC, scope_id ASC`);\n\t\treturn (\n\t\t\tawait allRows<CoordinatorScope>(params.length ? statement.bind(...params) : statement)\n\t\t).map((row) => rowToRecord<CoordinatorScope>(row));\n\t}\n\n\tasync getScopeAuthorization(\n\t\traw: CoordinatorScopeAuthorizationInput,\n\t): Promise<CoordinatorScopeAuthorizationResult> {\n\t\ttry {\n\t\t\tconst input = captureScopeAuthorizationInput(raw);\n\t\t\tconst source = await this.db\n\t\t\t\t.prepare(`SELECT ${SCOPE_FIELDS.join(\", \")} FROM coordinator_scopes WHERE scope_id = ?`)\n\t\t\t\t.bind(input.scopeId)\n\t\t\t\t.first<CoordinatorScope>();\n\t\t\tif (source === null) return { kind: \"rejected\", error: \"scope_not_found\" };\n\t\t\trequireScopeAuthorizationRecord(source, SCOPE_FIELDS);\n\t\t\tconst scope = { ...source };\n\t\t\tif (scope.scope_id !== input.scopeId) throw new Error(\"scope_authorization_unavailable\");\n\t\t\tconst error = scopeAuthorizationError(scope, input.groupId);\n\t\t\tif (error) return { kind: \"rejected\", error };\n\t\t\tconst group = await this.db\n\t\t\t\t.prepare(\"SELECT group_id, archived_at FROM groups WHERE group_id = ?\")\n\t\t\t\t.bind(input.groupId)\n\t\t\t\t.first<{ group_id: string; archived_at: string | null }>();\n\t\t\tif (group === null) return { kind: \"rejected\", error: \"scope_source_mismatch\" };\n\t\t\trequireScopeAuthorizationRecord(group, [\"group_id\"]);\n\t\t\tif (group.group_id !== input.groupId) throw new Error(\"scope_authorization_unavailable\");\n\t\t\tif (group.archived_at !== null) {\n\t\t\t\trequireScopeAuthorizationRecord(group, [\"archived_at\"]);\n\t\t\t\treturn { kind: \"rejected\", error: \"group_archived\" };\n\t\t\t}\n\t\t\tconst members = await this.captureScopeAuthorizationMembers(scope, input.groupId);\n\t\t\tconst current = await this.db\n\t\t\t\t.prepare(READ_SCOPE_AUTHORIZATION_SQL)\n\t\t\t\t.bind(JSON.stringify([scope]), JSON.stringify(members))\n\t\t\t\t.first<CoordinatorScope & { members_json: string }>();\n\t\t\trequireScopeAuthorizationRecord(current, SCOPE_FIELDS);\n\t\t\tif (!current || SCOPE_FIELDS.some((field) => current[field] !== scope[field]))\n\t\t\t\tthrow new Error(\"scope_authorization_unavailable\");\n\t\t\treturn {\n\t\t\t\tkind: \"authorized\",\n\t\t\t\tauthorizationVersion: 1,\n\t\t\t\tscope,\n\t\t\t\tmembers: parseScopeAuthorizationMembers(current.members_json, members),\n\t\t\t};\n\t\t} catch {\n\t\t\treturn { kind: \"rejected\", error: \"scope_authorization_unavailable\" };\n\t\t}\n\t}\n\n\tprivate async captureScopeAuthorizationMembers(\n\t\tscope: CoordinatorScope,\n\t\tgroupId: string,\n\t): Promise<CapturedScopeMember[]> {\n\t\tconst result = await this.db\n\t\t\t.prepare(\n\t\t\t\t`SELECT ${MEMBERSHIP_FIELDS.join(\", \")} FROM coordinator_scope_memberships WHERE scope_id = ? ORDER BY device_id ASC`,\n\t\t\t)\n\t\t\t.bind(scope.scope_id)\n\t\t\t.all<CoordinatorScopeMembership>();\n\t\tconst memberships = requireScopeAuthorizationRows(result).flatMap((membership) => {\n\t\t\trequireScopeAuthorizationRecord(membership, [\"status\"]);\n\t\t\tif (membership.status !== \"active\") return [];\n\t\t\trequireScopeAuthorizationRecord(membership, MEMBERSHIP_FIELDS);\n\t\t\treturn isCurrentScopeMember(scope, membership) ? [{ ...membership }] : [];\n\t\t});\n\t\tconst enrollments = await this.captureScopeAuthorizationEnrollments(memberships, groupId);\n\t\tconst captured: Array<Omit<CapturedScopeMember, \"keyId\">> = [];\n\t\tfor (const membership of memberships) {\n\t\t\tconst enrollment = enrollments.get(membership.device_id);\n\t\t\tif (enrollment?.enabled !== 1) continue;\n\t\t\tcaptured.push({ membership, enrollment });\n\t\t}\n\t\t// Complete every DTO copy before async hashing can change another source tuple.\n\t\tconst members: CapturedScopeMember[] = [];\n\t\tfor (const member of captured) {\n\t\t\tconst keyId = await ed25519KeyIdForRevocation(member.enrollment.public_key);\n\t\t\tif (keyId !== null) members.push({ ...member, keyId });\n\t\t}\n\t\treturn members;\n\t}\n\n\tprivate async captureScopeAuthorizationEnrollments(\n\t\tmemberships: CoordinatorScopeMembership[],\n\t\tgroupId: string,\n\t): Promise<Map<string, CoordinatorEnrollment>> {\n\t\tconst deviceIds = new Set(memberships.map((membership) => membership.device_id));\n\t\tconst result = await this.db\n\t\t\t.prepare(\n\t\t\t\t`SELECT ${ENROLLMENT_FIELDS.join(\", \")} FROM enrolled_devices WHERE group_id = ?\n\t\t\t\tAND device_id IN (SELECT value FROM json_each(?))`,\n\t\t\t)\n\t\t\t.bind(groupId, JSON.stringify([...deviceIds]))\n\t\t\t.all<CoordinatorEnrollment>();\n\t\tconst enrollments = new Map<string, CoordinatorEnrollment>();\n\t\tfor (const enrollment of requireScopeAuthorizationRows(result)) {\n\t\t\trequireScopeAuthorizationRecord(enrollment, ENROLLMENT_FIELDS);\n\t\t\tif (enrollment.group_id !== groupId || !deviceIds.delete(enrollment.device_id))\n\t\t\t\tthrow new Error(\"scope_authorization_unavailable\");\n\t\t\tenrollments.set(enrollment.device_id, { ...enrollment });\n\t\t}\n\t\treturn enrollments;\n\t}\n\n\tasync grantScopeMembership(\n\t\topts: CoordinatorGrantScopeMembershipInput,\n\t): Promise<CoordinatorScopeMembership> {\n\t\tconst effectId = normalizeMembershipEffectId(opts.effectId);\n\t\tconst requestJson = grantMembershipEffectRequestJson(opts);\n\t\tconst priorReceipt = await getMembershipEffectReceipt(this.db, effectId);\n\t\tif (priorReceipt) {\n\t\t\tassertMatchingMembershipEffectReceipt(priorReceipt, \"grant\", requestJson);\n\t\t\treturn membershipFromEffectReceipt(priorReceipt);\n\t\t}\n\t\tconst scopeId = clean(opts.scopeId);\n\t\tconst deviceId = clean(opts.deviceId);\n\t\tconst scope = scopeId ? await this.getScope(scopeId) : null;\n\t\tif (!scope) throw new CoordinatorMembershipError(\"scope_not_found\");\n\t\tif (scope.status !== \"active\") throw new CoordinatorMembershipError(\"scope_inactive\");\n\t\tconst existing = scopeId && deviceId ? await this.getScopeMembership(scopeId, deviceId) : null;\n\t\tconst normalized = normalizeCoordinatorGrantScopeMembershipInput(opts, scope, existing);\n\t\tif (normalized.groupId) {\n\t\t\tconst enrollment = await this.getEnrollment(normalized.groupId, normalized.deviceId);\n\t\t\tif (!enrollment) {\n\t\t\t\tthrow new CoordinatorMembershipError(\"device_not_enrolled\");\n\t\t\t}\n\t\t}\n\t\tconst now = nowISO();\n\t\tawait runAuditedBatch(this.db, [\n\t\t\tthis.db\n\t\t\t\t.prepare(`INSERT INTO coordinator_scope_memberships(\n\t\t\t\t\tscope_id, device_id, role, status, membership_epoch, coordinator_id, group_id,\n\t\t\t\t\tmanifest_issuer_device_id, manifest_hash, signed_manifest_json, updated_at\n\t\t\t\t) SELECT ?, ?, ?, 'active', ?, ?, ?, ?, ?, ?, ?\n\t\t\t\tWHERE NOT EXISTS (\n\t\t\t\t\tSELECT 1 FROM coordinator_scope_membership_effect_receipts WHERE effect_id = ?\n\t\t\t\t)\n\t\t\t\tON CONFLICT(scope_id, device_id) DO UPDATE SET\n\t\t\t\t\trole = excluded.role,\n\t\t\t\t\tstatus = 'active',\n\t\t\t\t\tmembership_epoch = excluded.membership_epoch,\n\t\t\t\t\tcoordinator_id = excluded.coordinator_id,\n\t\t\t\t\tgroup_id = excluded.group_id,\n\t\t\t\t\tmanifest_issuer_device_id = excluded.manifest_issuer_device_id,\n\t\t\t\t\tmanifest_hash = excluded.manifest_hash,\n\t\t\t\t\tsigned_manifest_json = excluded.signed_manifest_json,\n\t\t\t\t\tupdated_at = excluded.updated_at\n\t\t\t\tWHERE excluded.membership_epoch > coordinator_scope_memberships.membership_epoch\n\t\t\t\t OR (\n\t\t\t\t\texcluded.membership_epoch = coordinator_scope_memberships.membership_epoch\n\t\t\t\t\tAND coordinator_scope_memberships.status != 'revoked'\n\t\t\t\t )`)\n\t\t\t\t.bind(\n\t\t\t\t\tnormalized.scopeId,\n\t\t\t\t\tnormalized.deviceId,\n\t\t\t\t\tnormalized.role,\n\t\t\t\t\tnormalized.membershipEpoch,\n\t\t\t\t\tnormalized.coordinatorId,\n\t\t\t\t\tnormalized.groupId,\n\t\t\t\t\tnormalized.manifestIssuerDeviceId,\n\t\t\t\t\tnormalized.manifestHash,\n\t\t\t\t\tnormalized.signedManifestJson,\n\t\t\t\t\tnow,\n\t\t\t\t\teffectId,\n\t\t\t\t),\n\t\t\tprepareGrantEffectReceipt(this.db, {\n\t\t\t\teffectId,\n\t\t\t\trequestJson,\n\t\t\t\tscopeId: normalized.scopeId,\n\t\t\t\tdeviceId: normalized.deviceId,\n\t\t\t\tcreatedAt: now,\n\t\t\t}),\n\t\t\tprepareMembershipAuditFromCurrentRow(this.db, {\n\t\t\t\teffectId,\n\t\t\t\trequestJson,\n\t\t\t\taction: \"grant\",\n\t\t\t\tprevious: existing,\n\t\t\t\tscopeId: normalized.scopeId,\n\t\t\t\tdeviceId: normalized.deviceId,\n\t\t\t\tstatus: \"active\",\n\t\t\t\tmembershipEpoch: normalized.membershipEpoch,\n\t\t\t\tupdatedAt: now,\n\t\t\t\tactorType: normalized.actorType,\n\t\t\t\tactorId: normalized.actorId,\n\t\t\t\tcreatedAt: now,\n\t\t\t}),\n\t\t]);\n\t\tconst receipt = await getMembershipEffectReceipt(this.db, effectId);\n\t\tif (!receipt) throw new Error(\"scope membership grant was not applied.\");\n\t\tassertMatchingMembershipEffectReceipt(receipt, \"grant\", requestJson);\n\t\treturn membershipFromEffectReceipt(receipt);\n\t}\n\n\tasync revokeScopeMembership(opts: CoordinatorRevokeScopeMembershipInput): Promise<boolean> {\n\t\tconst scopeId = clean(opts.scopeId);\n\t\tconst deviceId = clean(opts.deviceId);\n\t\tif (!scopeId || !deviceId) throw new Error(\"scopeId and deviceId are required.\");\n\t\tconst effectId = normalizeMembershipEffectId(opts.effectId);\n\t\tconst requestJson = revokeMembershipEffectRequestJson(opts);\n\t\tconst priorReceipt = await getMembershipEffectReceipt(this.db, effectId);\n\t\tif (priorReceipt) {\n\t\t\tassertMatchingMembershipEffectReceipt(priorReceipt, \"revoke\", requestJson);\n\t\t\treturn priorReceipt.outcome_applied === 1;\n\t\t}\n\t\tconst membershipEpoch =\n\t\t\topts.membershipEpoch == null ? null : normalizeEpoch(opts.membershipEpoch);\n\t\tconst requestedGroupId = clean(opts.groupId);\n\t\tconst scope = requestedGroupId ? await this.getScope(scopeId) : null;\n\t\tif (requestedGroupId && requestedGroupId !== scope?.group_id) {\n\t\t\tthrow new CoordinatorMembershipError(\"scope_group_mismatch\");\n\t\t}\n\t\tconst existing = await this.getScopeMembership(scopeId, deviceId);\n\t\tif (membershipEpoch != null && existing && membershipEpoch <= existing.membership_epoch) {\n\t\t\tthrow new Error(\"membershipEpoch must increase on revoke.\");\n\t\t}\n\t\tconst now = nowISO();\n\t\tconst revokedEpoch = membershipEpoch ?? (existing?.membership_epoch ?? -1) + 1;\n\t\tconst updateStatement = this.db\n\t\t\t.prepare(`UPDATE coordinator_scope_memberships\n\t\t\t\t\t\t SET status = 'revoked',\n\t\t\t\t\t\t\t membership_epoch = CASE WHEN ? IS NULL THEN membership_epoch + 1 ELSE ? END,\n\t\t\t\t\t\t\t manifest_hash = COALESCE(?, manifest_hash),\n\t\t\t\t\t\t\t signed_manifest_json = COALESCE(?, signed_manifest_json),\n\t\t\t\t\t\t\t updated_at = ?\n\t\t\t\t\t\t WHERE scope_id = ? AND device_id = ? AND membership_epoch = ? AND status = ?\n\t\t\t\t\t\t AND NOT EXISTS (\n\t\t\t\t\t\t\tSELECT 1 FROM coordinator_scope_membership_effect_receipts WHERE effect_id = ?\n\t\t\t\t\t\t )`)\n\t\t\t.bind(\n\t\t\t\tmembershipEpoch,\n\t\t\t\tmembershipEpoch,\n\t\t\t\tclean(opts.manifestHash),\n\t\t\t\tclean(opts.signedManifestJson),\n\t\t\t\tnow,\n\t\t\t\tscopeId,\n\t\t\t\tdeviceId,\n\t\t\t\texisting?.membership_epoch ?? -1,\n\t\t\t\texisting?.status ?? \"\",\n\t\t\t\teffectId,\n\t\t\t);\n\t\tconst receiptStatement = prepareRevokeEffectReceipt(this.db, {\n\t\t\teffectId,\n\t\t\trequestJson,\n\t\t\tscopeId,\n\t\t\tdeviceId,\n\t\t\tcreatedAt: now,\n\t\t});\n\t\tconst auditStatement = prepareMembershipAuditFromCurrentRow(this.db, {\n\t\t\teffectId,\n\t\t\trequestJson,\n\t\t\taction: \"revoke\",\n\t\t\tprevious: existing,\n\t\t\tscopeId,\n\t\t\tdeviceId,\n\t\t\tstatus: \"revoked\",\n\t\t\tmembershipEpoch: revokedEpoch,\n\t\t\tupdatedAt: now,\n\t\t\tactorType: clean(opts.actorType),\n\t\t\tactorId: clean(opts.actorId),\n\t\t\tcreatedAt: now,\n\t\t});\n\t\ttry {\n\t\t\tawait runAuditedBatch(this.db, [updateStatement, receiptStatement, auditStatement]);\n\t\t} catch (err) {\n\t\t\tconst current = await this.getScopeMembership(scopeId, deviceId);\n\t\t\tif (\n\t\t\t\texisting &&\n\t\t\t\t(!current ||\n\t\t\t\t\tcurrent.membership_epoch !== existing.membership_epoch ||\n\t\t\t\t\tcurrent.status !== existing.status)\n\t\t\t) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tthrow err;\n\t\t}\n\t\tconst receipt = await getMembershipEffectReceipt(this.db, effectId);\n\t\tif (!receipt) throw new Error(\"scope membership revoke receipt was not persisted.\");\n\t\tassertMatchingMembershipEffectReceipt(receipt, \"revoke\", requestJson);\n\t\treturn receipt.outcome_applied === 1;\n\t}\n\n\tasync listScopeMemberships(\n\t\tscopeId: string,\n\t\tincludeRevoked = false,\n\t): Promise<CoordinatorScopeMembership[]> {\n\t\tconst normalizedScopeId = clean(scopeId);\n\t\tif (!normalizedScopeId) throw new Error(\"scopeId is required.\");\n\t\tconst statusWhere = includeRevoked ? \"\" : \"AND status = 'active'\";\n\t\treturn (\n\t\t\tawait allRows<CoordinatorScopeMembership>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT scope_id, device_id, role, status, membership_epoch, coordinator_id, group_id,\n\t\t\t\t\t\t\tmanifest_issuer_device_id, manifest_hash, signed_manifest_json, updated_at\n\t\t\t\t\t\t FROM coordinator_scope_memberships\n\t\t\t\t\t\t WHERE scope_id = ? ${statusWhere}\n\t\t\t\t\t\t ORDER BY device_id ASC`)\n\t\t\t\t\t.bind(normalizedScopeId),\n\t\t\t)\n\t\t).map((row) => rowToRecord<CoordinatorScopeMembership>(row));\n\t}\n\n\tasync listDeviceScopeMemberships(\n\t\tdeviceId: string,\n\t\tincludeRevoked = false,\n\t): Promise<CoordinatorScopeMembership[]> {\n\t\tconst normalizedDeviceId = clean(deviceId);\n\t\tif (!normalizedDeviceId) throw new Error(\"deviceId is required.\");\n\t\t// Served by idx_coordinator_scope_memberships_device_status.\n\t\tconst statusWhere = includeRevoked ? \"\" : \"AND status = 'active'\";\n\t\treturn (\n\t\t\tawait allRows<CoordinatorScopeMembership>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT scope_id, device_id, role, status, membership_epoch, coordinator_id, group_id,\n\t\t\t\t\t\t\tmanifest_issuer_device_id, manifest_hash, signed_manifest_json, updated_at\n\t\t\t\t\t\t FROM coordinator_scope_memberships\n\t\t\t\t\t\t WHERE device_id = ? ${statusWhere}\n\t\t\t\t\t\t ORDER BY scope_id ASC`)\n\t\t\t\t\t.bind(normalizedDeviceId),\n\t\t\t)\n\t\t).map((row) => rowToRecord<CoordinatorScopeMembership>(row));\n\t}\n\n\tasync listScopeMembershipAuditEvents(\n\t\topts: CoordinatorListScopeMembershipAuditInput,\n\t): Promise<CoordinatorScopeMembershipAuditEvent[]> {\n\t\tconst scopeId = clean(opts.scopeId);\n\t\tif (!scopeId) throw new Error(\"scopeId is required.\");\n\t\tconst deviceId = clean(opts.deviceId);\n\t\tconst limit = normalizeCoordinatorAuditLimit(opts.limit);\n\t\tconst where = deviceId ? \"scope_id = ? AND device_id = ?\" : \"scope_id = ?\";\n\t\tconst params = deviceId ? [scopeId, deviceId, limit] : [scopeId, limit];\n\t\treturn (\n\t\t\tawait allRows<CoordinatorScopeMembershipAuditEvent>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT event_id, effect_id, action, scope_id, device_id, role, status, membership_epoch,\n\t\t\t\t\t\t\tprevious_role, previous_status, previous_membership_epoch,\n\t\t\t\t\t\t\tcoordinator_id, group_id, actor_type, actor_id, manifest_hash, created_at\n\t\t\t\t\t\t FROM coordinator_scope_membership_audit_log\n\t\t\t\t\t\t WHERE ${where}\n\t\t\t\t\t\t ORDER BY event_id ASC\n\t\t\t\t\t\t LIMIT ?`)\n\t\t\t\t\t.bind(...params),\n\t\t\t)\n\t\t).map((row) => rowToRecord<CoordinatorScopeMembershipAuditEvent>(row));\n\t}\n\n\tasync getBootstrapGrant(grantId: string): Promise<CoordinatorBootstrapGrant | null> {\n\t\tconst row = await firstRow<CoordinatorBootstrapGrant>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT grant_id, group_id, seed_device_id, worker_device_id, expires_at, created_at, created_by, revoked_at\n\t\t\t\t\t FROM coordinator_bootstrap_grants WHERE grant_id = ?`)\n\t\t\t\t.bind(grantId),\n\t\t);\n\t\treturn row ? rowToRecord<CoordinatorBootstrapGrant>(row) : null;\n\t}\n\n\tasync getBootstrapGrantAuthorization(\n\t\traw: CoordinatorBootstrapGrantAuthorizationInput,\n\t): Promise<CoordinatorBootstrapGrantAuthorizationResult> {\n\t\ttry {\n\t\t\tconst input = captureBootstrapAuthorizationInput(raw);\n\t\t\tconst source = await firstRow<BootstrapAuthorizationRow>(\n\t\t\t\tthis.db.prepare(BOOTSTRAP_AUTHORIZATION_SOURCE_SQL).bind(input.grantId),\n\t\t\t);\n\t\t\tconst sourceError = bootstrapAuthorizationSourceError(input, source);\n\t\t\tif (sourceError) return rejectBootstrapAuthorization(sourceError);\n\t\t\tif (!source) return rejectBootstrapAuthorization(\"bootstrap_authorization_unavailable\");\n\t\t\tconst captured = { ...source };\n\t\t\tconst keys = {\n\t\t\t\tseed:\n\t\t\t\t\tcaptured.seed_enrollment_public_key === null\n\t\t\t\t\t\t? null\n\t\t\t\t\t\t: await ed25519KeyIdForRevocation(captured.seed_enrollment_public_key),\n\t\t\t\tworker:\n\t\t\t\t\tcaptured.worker_enrollment_public_key === null\n\t\t\t\t\t\t? null\n\t\t\t\t\t\t: await ed25519KeyIdForRevocation(captured.worker_enrollment_public_key),\n\t\t\t};\n\t\t\tconst decision = bootstrapAuthorizationDecision(input, captured, keys);\n\t\t\tconst current = await firstRow<BootstrapAuthorizationRow>(\n\t\t\t\tthis.db.prepare(decision.sql).bind(...decision.values),\n\t\t\t);\n\t\t\treturn bootstrapAuthorizationResult(current);\n\t\t} catch {\n\t\t\treturn rejectBootstrapAuthorization(\"bootstrap_authorization_unavailable\");\n\t\t}\n\t}\n\n\tasync listBootstrapGrants(groupId: string): Promise<CoordinatorBootstrapGrant[]> {\n\t\treturn (\n\t\t\tawait allRows<CoordinatorBootstrapGrant>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT grant_id, group_id, seed_device_id, worker_device_id, expires_at, created_at, created_by, revoked_at\n\t\t\t\t\t\t FROM coordinator_bootstrap_grants WHERE group_id = ?\n\t\t\t\t\t\t ORDER BY created_at DESC, grant_id DESC`)\n\t\t\t\t\t.bind(groupId),\n\t\t\t)\n\t\t).map((row) => rowToRecord<CoordinatorBootstrapGrant>(row));\n\t}\n\n\tasync revokeBootstrapGrant(grantId: string, revokedAt = nowISO()): Promise<boolean> {\n\t\treturn (\n\t\t\t(await runChanges(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`UPDATE coordinator_bootstrap_grants\n\t\t\t\t\t\t SET revoked_at = COALESCE(revoked_at, ?)\n\t\t\t\t\t\t WHERE grant_id = ?`)\n\t\t\t\t\t.bind(revokedAt, grantId),\n\t\t\t)) > 0\n\t\t);\n\t}\n\n\tasync listReciprocalApprovals(\n\t\topts: CoordinatorListReciprocalApprovalsInput,\n\t): Promise<CoordinatorReciprocalApproval[]> {\n\t\tconst directionColumn =\n\t\t\topts.direction === \"incoming\" ? \"requested_device_id\" : \"requesting_device_id\";\n\t\tconst status = opts.status?.trim() || \"pending\";\n\t\treturn (\n\t\t\tawait allRows<CoordinatorReciprocalApproval>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t\t\t FROM coordinator_reciprocal_approvals\n\t\t\t\t\t\t WHERE group_id = ? AND ${directionColumn} = ? AND status = ?\n\t\t\t\t\t\t ORDER BY created_at ASC, request_id ASC`)\n\t\t\t\t\t.bind(opts.groupId, opts.deviceId, status),\n\t\t\t)\n\t\t).map((row) => rowToRecord<CoordinatorReciprocalApproval>(row));\n\t}\n\n\tasync createLegacyTeamCompletion(\n\t\tgroupId: string,\n\t\tmanifest: CoordinatorLegacyTeamCompletionManifestV1,\n\t): Promise<CoordinatorLegacyTeamCompletionWriteResult> {\n\t\tconst [normalizedGroupId] = normalizeCoordinatorLegacyTeamCompletionGroupIds([groupId]);\n\t\tif (!normalizedGroupId) throw new Error(\"completion_manifest_invalid\");\n\t\tconst group = await this.getGroup(normalizedGroupId);\n\t\tif (!group) throw new Error(\"group_not_found\");\n\t\tif (group.archived_at) throw new Error(\"group_archived\");\n\t\tconst manifestJson = canonicalCoordinatorLegacyTeamCompletionManifestJson(manifest);\n\t\tconst normalized = JSON.parse(manifestJson) as CoordinatorLegacyTeamCompletionManifestV1;\n\t\trequireCoordinatorLegacyTeamCompletionTeamBinding(normalized);\n\t\tconst existing = await firstRow<{ manifest_json: string }>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT manifest_json FROM coordinator_legacy_team_completions\n\t\t\t\t\tWHERE group_id = ? AND candidate_ref = ?`)\n\t\t\t\t.bind(normalizedGroupId, normalized.candidate_ref),\n\t\t);\n\t\tif (existing) {\n\t\t\treturn legacyCompletionWriteResult(existing.manifest_json, manifestJson, \"existing\");\n\t\t}\n\t\tconst coordinatorId = await this.requireLegacyTeamCompletionSources(\n\t\t\tnormalizedGroupId,\n\t\t\tnormalized,\n\t\t\tmanifestJson,\n\t\t);\n\t\tconst ownerProof = await this.prepareLegacyTeamCompletionOwnerProof(\n\t\t\tnormalizedGroupId,\n\t\t\tmanifestJson,\n\t\t);\n\t\tconst changes = await runChanges(\n\t\t\tthis.db\n\t\t\t\t.prepare(`${LEGACY_OWNER_INPUT_SQL}${ownerProof.ctes}\n\t\t\t\tINSERT OR IGNORE INTO coordinator_legacy_team_completions(\n\t\t\t\t\tgroup_id, candidate_ref, manifest_version, manifest_json, completed_at, created_at\n\t\t\t\t\t) SELECT ?, ?, ?, ?, ?, ?\n\t\t\t\t\t FROM groups\n\t\t\t\t\t WHERE group_id = ? AND archived_at IS NULL\n\t\t\t\t\t AND NOT EXISTS (\n\t\t\t\t\t SELECT 1\n\t\t\t\t\t FROM json_each(?, '$.project_mappings') AS requested\n\t\t\t\t\t LEFT JOIN coordinator_scopes AS scope\n\t\t\t\t\t ON scope.scope_id = json_extract(requested.value, '$.scope_id')\n\t\t\t\t\t AND scope.authority_type = 'coordinator'\n\t\t\t\t\t AND scope.coordinator_id = ?\n\t\t\t\t\t AND scope.group_id = ?\n\t\t\t\t\t AND scope.status = 'active'\n\t\t\t\t\t WHERE scope.scope_id IS NULL\n\t\t\t\t\t )\n\t\t\t\t\t AND NOT EXISTS (\n\t\t\t\t\t SELECT 1 FROM enrolled_devices AS enrolled\n\t\t\t\t\t WHERE enrolled.group_id = ?\n\t\t\t\t\t AND NOT EXISTS (\n\t\t\t\t\t SELECT 1 FROM json_each(?, '$.device_decisions') AS requested\n\t\t\t\t\t WHERE json_extract(requested.value, '$.device_id') = enrolled.device_id\n\t\t\t\t\t AND json_extract(requested.value, '$.key_fingerprint') = enrolled.fingerprint\n\t\t\t\t\t AND json_extract(requested.value, '$.enabled') = enrolled.enabled\n\t\t\t\t\t )\n\t\t\t\t\t )\n\t\t\t\t\t AND NOT EXISTS (\n\t\t\t\t\t SELECT 1 FROM json_each(?, '$.device_decisions') AS requested\n\t\t\t\t\t WHERE json_extract(requested.value, '$.decision') = 'included'\n\t\t\t\t\t AND NOT EXISTS (\n\t\t\t\t\t SELECT 1 FROM enrolled_devices AS enrolled\n\t\t\t\t\t WHERE enrolled.group_id = ?\n\t\t\t\t\t AND enrolled.device_id = json_extract(requested.value, '$.device_id')\n\t\t\t\t\t AND enrolled.fingerprint = json_extract(requested.value, '$.key_fingerprint')\n\t\t\t\t\t AND enrolled.enabled = 1\n\t\t\t\t\t )\n\t\t\t\t\t ) AND ${LEGACY_OWNER_SOURCE_CURRENT_SQL}\n\t\t\t\t\t AND (${ownerProof.currentSql}) AND (${ownerProof.compatibleSql})`)\n\t\t\t\t.bind(\n\t\t\t\t\t...ownerProof.values,\n\t\t\t\t\tnormalizedGroupId,\n\t\t\t\t\tnormalized.candidate_ref,\n\t\t\t\t\tnormalized.version,\n\t\t\t\t\tmanifestJson,\n\t\t\t\t\tnormalized.completed_at,\n\t\t\t\t\tnowISO(),\n\t\t\t\t\tnormalizedGroupId,\n\t\t\t\t\tmanifestJson,\n\t\t\t\t\tcoordinatorId,\n\t\t\t\t\tnormalizedGroupId,\n\t\t\t\t\tnormalizedGroupId,\n\t\t\t\t\tmanifestJson,\n\t\t\t\t\tmanifestJson,\n\t\t\t\t\tnormalizedGroupId,\n\t\t\t\t),\n\t\t);\n\t\tconst stored = await firstRow<{ manifest_json: string }>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT manifest_json FROM coordinator_legacy_team_completions\n\t\t\t\t\tWHERE group_id = ? AND candidate_ref = ?`)\n\t\t\t\t.bind(normalizedGroupId, normalized.candidate_ref),\n\t\t);\n\t\tif (!stored) {\n\t\t\tawait this.requireLegacyTeamCompletionSources(normalizedGroupId, normalized, manifestJson);\n\t\t\tconst denial = await firstRow<{ denial: string }>(\n\t\t\t\tthis.db.prepare(ownerProof.denialSql).bind(...ownerProof.values),\n\t\t\t);\n\t\t\tif (denial?.denial === \"completion_conflict\") {\n\t\t\t\tthrow new CoordinatorLegacyTeamCompletionConflictError();\n\t\t\t}\n\t\t\tthrow new Error(\"completion_manifest_unavailable\");\n\t\t}\n\t\treturn legacyCompletionWriteResult(\n\t\t\tstored.manifest_json,\n\t\t\tmanifestJson,\n\t\t\tchanges === 1 ? \"created\" : \"existing\",\n\t\t);\n\t}\n\n\tprivate async prepareLegacyTeamCompletionOwnerProof(groupId: string, manifestJson: string) {\n\t\tconst keyMetadata = await legacyOwnerKeyMetadata(\n\t\t\tawait allRows<{ public_key: string }>(\n\t\t\t\tthis.db.prepare(LEGACY_OWNER_KEYS_SQL).bind(manifestJson, groupId),\n\t\t\t),\n\t\t);\n\t\tconst proof = legacyCompletionOwnerProofSql(\n\t\t\tawait captureLegacyCompletionOwnerProof({\n\t\t\t\tbackend: {\n\t\t\t\t\tfirst: <T>({ sql, values }: AuthLinkStatement) =>\n\t\t\t\t\t\tfirstRow<T>(this.db.prepare(sql).bind(...values)),\n\t\t\t\t\tall: <T>({ sql, values }: AuthLinkStatement) =>\n\t\t\t\t\t\tallRows<T>(this.db.prepare(sql).bind(...values)),\n\t\t\t\t},\n\t\t\t\tgroupId,\n\t\t\t\tmanifestJson,\n\t\t\t\tkeyMetadata,\n\t\t\t}),\n\t\t);\n\t\treturn {\n\t\t\t...proof,\n\t\t\tvalues: [manifestJson, groupId, keyMetadata, ...proof.values],\n\t\t\tdenialSql: `${LEGACY_OWNER_INPUT_SQL}${proof.ctes}\n\t\t SELECT CASE WHEN NOT (${LEGACY_OWNER_SOURCE_CURRENT_SQL}) OR NOT (${proof.currentSql})\n\t\t THEN 'completion_manifest_unavailable'\n\t\t WHEN NOT (${proof.compatibleSql}) THEN 'completion_conflict'\n\t\t ELSE 'completion_manifest_unavailable' END AS denial`,\n\t\t};\n\t}\n\n\tprivate async requireLegacyTeamCompletionSources(\n\t\tgroupId: string,\n\t\tmanifest: CoordinatorLegacyTeamCompletionManifestV1,\n\t\tmanifestJson: string,\n\t): Promise<string | null> {\n\t\tconst group = await this.getGroup(groupId);\n\t\tif (!group) throw new Error(\"group_not_found\");\n\t\tif (group.archived_at) throw new Error(\"group_archived\");\n\t\tconst bindings = await allRows<CoordinatorLegacyTeamCompletionScopeBinding>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT DISTINCT requested.scope_id, scope.authority_type,\n\t\t\t\t\tscope.coordinator_id, scope.group_id, scope.status\n\t\t\t\t FROM (SELECT json_extract(value, '$.scope_id') AS scope_id\n\t\t\t\t\tFROM json_each(?, '$.project_mappings')) AS requested\n\t\t\t\t LEFT JOIN coordinator_scopes AS scope ON scope.scope_id = requested.scope_id`)\n\t\t\t\t.bind(manifestJson),\n\t\t);\n\t\treturn requireCoordinatorLegacyTeamCompletionScopeBindings(manifest, groupId, bindings);\n\t}\n\n\tasync getLegacyTeamCompletion(\n\t\tgroupId: string,\n\t\tcandidateRef: string,\n\t): Promise<CoordinatorLegacyTeamCompletionManifestV1 | null> {\n\t\tconst [normalizedGroupId] = normalizeCoordinatorLegacyTeamCompletionGroupIds([groupId]);\n\t\tconst normalizedCandidateRef =\n\t\t\tnormalizeCoordinatorLegacyTeamCompletionCandidateRef(candidateRef);\n\t\tif (!normalizedGroupId) throw new Error(\"completion_manifest_invalid\");\n\t\tconst row = await firstRow<{ manifest_json: string }>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT manifest_json FROM coordinator_legacy_team_completions\n\t\t\t\t\tWHERE group_id = ? AND candidate_ref = ?`)\n\t\t\t\t.bind(normalizedGroupId, normalizedCandidateRef),\n\t\t);\n\t\treturn row\n\t\t\t? normalizeCoordinatorLegacyTeamCompletionManifest(JSON.parse(row.manifest_json))\n\t\t\t: null;\n\t}\n\n\tasync listLegacyTeamCompletions(\n\t\tgroupIds: string[],\n\t): Promise<CoordinatorLegacyTeamCompletionRecord[]> {\n\t\tconst normalizedGroupIds = normalizeCoordinatorLegacyTeamCompletionGroupIds(groupIds);\n\t\tif (normalizedGroupIds.length === 0) return [];\n\t\tconst placeholders = normalizedGroupIds.map(() => \"?\").join(\", \");\n\t\tconst stats = await firstRow<{\n\t\t\trecord_count: number;\n\t\t\tbatch_bytes: number;\n\t\t\tmax_manifest_bytes: number;\n\t\t}>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT\n\t\t\t\t\tCOUNT(*) AS record_count,\n\t\t\t\t\tCOALESCE(SUM(\n\t\t\t\t\t\tLENGTH(CAST(group_id AS BLOB)) + LENGTH(CAST(manifest_json AS BLOB))\n\t\t\t\t\t), 0) AS batch_bytes,\n\t\t\t\t\tCOALESCE(MAX(LENGTH(CAST(manifest_json AS BLOB))), 0) AS max_manifest_bytes\n\t\t\t\tFROM coordinator_legacy_team_completions\n\t\t\t\tWHERE group_id IN (${placeholders})`)\n\t\t\t\t.bind(...normalizedGroupIds),\n\t\t);\n\t\tif (\n\t\t\t!stats ||\n\t\t\tstats.record_count > COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_RECORDS ||\n\t\t\tstats.batch_bytes > COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BATCH_BYTES ||\n\t\t\tstats.max_manifest_bytes > COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES\n\t\t) {\n\t\t\tthrow new Error(\"completion_results_too_large\");\n\t\t}\n\t\tconst rows = await allRows<{ group_id: string; manifest_json: string }>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`WITH completion_stats AS (\n\t\t\t\t\tSELECT\n\t\t\t\t\t\tCOUNT(*) AS record_count,\n\t\t\t\t\t\tCOALESCE(SUM(\n\t\t\t\t\t\t\tLENGTH(CAST(group_id AS BLOB)) + LENGTH(CAST(manifest_json AS BLOB))\n\t\t\t\t\t\t), 0) AS batch_bytes,\n\t\t\t\t\t\tCOALESCE(MAX(LENGTH(CAST(manifest_json AS BLOB))), 0) AS max_manifest_bytes\n\t\t\t\t\tFROM coordinator_legacy_team_completions\n\t\t\t\t\tWHERE group_id IN (${placeholders})\n\t\t\t\t)\n\t\t\t\tSELECT completions.group_id, completions.manifest_json\n\t\t\t\tFROM coordinator_legacy_team_completions AS completions\n\t\t\t\tCROSS JOIN completion_stats\n\t\t\t\tWHERE completions.group_id IN (${placeholders})\n\t\t\t\t\t AND completion_stats.record_count <= ${COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_RECORDS}\n\t\t\t\t\t AND completion_stats.batch_bytes <= ${COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BATCH_BYTES}\n\t\t\t\t\t AND completion_stats.max_manifest_bytes <= ${COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES}\n\t\t\t\t\t AND LENGTH(completions.manifest_json) <= ${COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES}\n\t\t\t\t\t AND LENGTH(CAST(completions.manifest_json AS BLOB)) <= ${COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES}\n\t\t\t\t\tORDER BY completions.group_id, completions.completed_at, completions.candidate_ref\n\t\t\t\t\tLIMIT ${COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_RECORDS + 1}`)\n\t\t\t\t.bind(...normalizedGroupIds, ...normalizedGroupIds),\n\t\t);\n\t\tif (rows.length === 0 && stats.record_count > 0) {\n\t\t\tthrow new Error(\"completion_results_too_large\");\n\t\t}\n\t\tif (rows.length > COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_RECORDS) {\n\t\t\tthrow new Error(\"completion_results_too_large\");\n\t\t}\n\t\tconst batchBytes = rows.reduce(\n\t\t\t(total, row) =>\n\t\t\t\ttotal +\n\t\t\t\tnew TextEncoder().encode(row.group_id).byteLength +\n\t\t\t\tnew TextEncoder().encode(row.manifest_json).byteLength,\n\t\t\t0,\n\t\t);\n\t\tif (batchBytes > COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BATCH_BYTES) {\n\t\t\tthrow new Error(\"completion_results_too_large\");\n\t\t}\n\t\treturn rows.map((row) => ({\n\t\t\tgroup_id: row.group_id,\n\t\t\tmanifest: normalizeCoordinatorLegacyTeamCompletionManifest(JSON.parse(row.manifest_json)),\n\t\t}));\n\t}\n\n\tasync captureAuthControllerLegacyHistory(input: ControllerHistoryInput) {\n\t\treturn captureControllerHistory(input, <T>(sql: string, values: string[]) =>\n\t\t\tallRows<T>(this.db.prepare(sql).bind(...values)),\n\t\t);\n\t}\n\n\tasync upsertPresence(_opts: CoordinatorUpsertPresenceInput): Promise<CoordinatorPresenceRecord> {\n\t\tconst now = new Date();\n\t\tconst expiresAt = new Date(now.getTime() + _opts.ttlS * 1000).toISOString();\n\t\tconst normalized = mergeCoordinatorAddresses([], _opts.addresses);\n\t\tawait this.db\n\t\t\t.prepare(`INSERT INTO presence_records(group_id, device_id, addresses_json, last_seen_at, expires_at, capabilities_json)\n\t\t\t\t VALUES (?, ?, ?, ?, ?, ?)\n\t\t\t\t ON CONFLICT(group_id, device_id) DO UPDATE SET\n\t\t\t\t\taddresses_json = excluded.addresses_json,\n\t\t\t\t\tlast_seen_at = excluded.last_seen_at,\n\t\t\t\t\texpires_at = excluded.expires_at,\n\t\t\t\t\tcapabilities_json = excluded.capabilities_json`)\n\t\t\t.bind(\n\t\t\t\t_opts.groupId,\n\t\t\t\t_opts.deviceId,\n\t\t\t\tJSON.stringify(normalized),\n\t\t\t\tnow.toISOString(),\n\t\t\t\texpiresAt,\n\t\t\t\tJSON.stringify(_opts.capabilities ?? {}),\n\t\t\t)\n\t\t\t.run();\n\t\treturn {\n\t\t\tgroup_id: _opts.groupId,\n\t\t\tdevice_id: _opts.deviceId,\n\t\t\taddresses: normalized,\n\t\t\texpires_at: expiresAt,\n\t\t};\n\t}\n\n\tasync listGroupPeers(\n\t\tgroupId: string,\n\t\trequestingDeviceId: string,\n\t): Promise<CoordinatorPeerRecord[]> {\n\t\ttry {\n\t\t\treturn await this.readGroupPeers(groupId, requestingDeviceId);\n\t\t} catch {\n\t\t\tthrow new Error(\"peer_discovery_unavailable\");\n\t\t}\n\t}\n\n\tprivate async readGroupPeers(\n\t\t_groupId: string,\n\t\t_requestingDeviceId: string,\n\t): Promise<CoordinatorPeerRecord[]> {\n\t\tconst now = nowISO();\n\t\tconst capturedResult = await this.db\n\t\t\t.prepare(CAPTURE_PEER_ENROLLMENTS_SQL)\n\t\t\t.bind(_groupId, _requestingDeviceId)\n\t\t\t.all<CapturedPeerEnrollment>();\n\t\tif (\n\t\t\t!Array.isArray(capturedResult?.results) ||\n\t\t\t(capturedResult as { success?: boolean }).success === false\n\t\t) {\n\t\t\tthrow new Error(\"peer_discovery_unavailable\");\n\t\t}\n\t\tconst captured = capturePeerEnrollments(capturedResult.results);\n\t\tconst candidates = await Promise.all(\n\t\t\tcaptured.map(async (row) => ({\n\t\t\t\t...row,\n\t\t\t\tkeyId: await ed25519KeyIdForRevocation(row.public_key),\n\t\t\t})),\n\t\t);\n\t\tconst currentResult = await this.db\n\t\t\t.prepare(READ_CURRENT_PEERS_SQL)\n\t\t\t.bind(JSON.stringify(candidates), _groupId, _requestingDeviceId)\n\t\t\t.all<Record<string, unknown>>();\n\t\tif ((currentResult as { success?: boolean } | null)?.success === false) {\n\t\t\tthrow new Error(\"peer_discovery_unavailable\");\n\t\t}\n\t\tconst rows = requirePeerDiscoveryRows(currentResult?.results);\n\t\treturn rows.map((row) => {\n\t\t\tconst expiresRaw = String(row.expires_at ?? \"\").trim();\n\t\t\tlet stale = true;\n\t\t\tif (expiresRaw) {\n\t\t\t\tconst expiresAt = new Date(expiresRaw);\n\t\t\t\tstale = Number.isNaN(expiresAt.getTime()) || expiresAt.toISOString() <= now;\n\t\t\t}\n\t\t\tconst addresses = stale\n\t\t\t\t? []\n\t\t\t\t: mergeCoordinatorAddresses([], JSON.parse(String(row.addresses_json ?? \"[]\")) as string[]);\n\t\t\treturn {\n\t\t\t\tdevice_id: String(row.device_id ?? \"\"),\n\t\t\t\tpublic_key: String(row.public_key ?? \"\"),\n\t\t\t\tfingerprint: String(row.fingerprint ?? \"\"),\n\t\t\t\tdisplay_name: (row.display_name as string | null) ?? null,\n\t\t\t\taddresses,\n\t\t\t\tlast_seen_at: (row.last_seen_at as string | null) ?? null,\n\t\t\t\texpires_at: (row.expires_at as string | null) ?? null,\n\t\t\t\tstale,\n\t\t\t\tcapabilities: JSON.parse(String(row.capabilities_json ?? \"{}\")) as Record<string, unknown>,\n\t\t\t} satisfies CoordinatorPeerRecord;\n\t\t});\n\t}\n}\n","import {\n\ttype CoordinatorAppBrowserAuthOptions,\n\ttype CoordinatorRequestRateLimitOptions,\n\ttype CoordinatorRequestVerifier,\n\ttype CoordinatorRuntimeDeps,\n\tcreateCoordinatorApp,\n} from \"./coordinator-api.js\";\nimport type { CoordinatorDeviceRevocationContext } from \"./coordinator-device-revocation-route.js\";\nimport { D1CoordinatorStore, type D1DatabaseLike } from \"./d1-coordinator-store.js\";\n\nexport interface CreateD1CoordinatorAppOptions {\n\tdb: D1DatabaseLike;\n\tadminSecret?: string | null;\n\tnow?: () => string;\n\trequestVerifier: CoordinatorRequestVerifier;\n\trequestRateLimit?: CoordinatorRequestRateLimitOptions;\n\tdeviceRevocation?: CoordinatorDeviceRevocationContext;\n\trecipientInviteCoordinatorId?: string;\n\tbrowserAuth?:\n\t\t| Exclude<CoordinatorAppBrowserAuthOptions, { kind: \"ready\" }>\n\t\t| Omit<Extract<CoordinatorAppBrowserAuthOptions, { kind: \"ready\" }>, \"storeFactory\">;\n}\n\nexport function createD1CoordinatorApp(\n\topts: CreateD1CoordinatorAppOptions,\n): ReturnType<typeof createCoordinatorApp> {\n\tconst db = opts.db;\n\tconst runtime: CoordinatorRuntimeDeps = {\n\t\tadminSecret: () => String(opts.adminSecret ?? \"\").trim() || null,\n\t\tnow: opts.now ?? (() => new Date().toISOString()),\n\t};\n\treturn createCoordinatorApp({\n\t\tstoreFactory: () => new D1CoordinatorStore(db),\n\t\tdeviceRevocation: opts.deviceRevocation,\n\t\trecipientInviteCoordinatorId: opts.recipientInviteCoordinatorId,\n\t\truntime,\n\t\trequestVerifier: opts.requestVerifier,\n\t\trequestRateLimit: opts.requestRateLimit,\n\t\tbrowserAuth:\n\t\t\topts.browserAuth?.kind === \"ready\"\n\t\t\t\t? { ...opts.browserAuth, storeFactory: () => new D1CoordinatorStore(db) }\n\t\t\t\t: opts.browserAuth,\n\t});\n}\n"],"mappings":";;;AAyEA,IAAa,KAA+B,OAAO,OAAO;CACzD,OAAO;CACP,SAAS;AACV,CAAC;AAED,SAAS,GAAa,GAAkC,IAAS,KAAK;CACrE,OAAO,IAAI,SAAS,EAAK,MAAM;EAAE;EAAQ,SAAS,EAAK;CAAQ,CAAC;AACjE;AACA,SAAS,GAAW,GAAe;CAClC,OAAO,EACL,WAAW,KAAK,OAAO,CAAC,CACxB,WAAW,KAAK,MAAM,CAAC,CACvB,WAAW,KAAK,MAAM,CAAC,CACvB,WAAW,MAAK,QAAQ,CAAC,CACzB,WAAW,KAAK,OAAO;AAC1B;AACA,eAAe,EAAO,IAAS,KAAwB;CACtD,IAAI;EACH,OAAO,GAAa,MAAM,EAAwB,kBAAkB,GAAG,CAAM;CAC9E,QAAQ;EACP,OAAO,IAAI,SAAS,sEAAsE;GACzF,QAAQ;GACR,SAAS;IACR,iBAAiB;IACjB,mBAAmB;IACnB,0BAA0B;GAC3B;EACD,CAAC;CACF;AACD;AACA,eAAe,GACd,GACA,GACA,GACA,IAAS,IACR;CACD,IAAM,KAAW,MAAM,EAAwB,kBAAkB,EAAA,CAAG;CACpE,EAAQ,qBAAqB;CAC7B,IAAM,IAAS,OAAO,QAAQ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