@jeffusion/bungee-core 5.26.0 → 6.0.1

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 (71) hide show
  1. package/dist/config-storage-worker.js +376 -223
  2. package/dist/main.js +799 -437
  3. package/dist/observability-worker.js +0 -10
  4. package/dist/plugins/anthropic-request-sanitizer/index.js.map +2 -2
  5. package/dist/plugins/anthropic-request-sanitizer/manifest.json +1 -1
  6. package/dist/plugins/anthropic-tool-name-transformer/index.js.map +2 -2
  7. package/dist/plugins/anthropic-tool-name-transformer/manifest.json +1 -1
  8. package/dist/plugins/chatgpt-oauth/control.js.map +1 -1
  9. package/dist/plugins/chatgpt-oauth/index.js.map +2 -2
  10. package/dist/plugins/chatgpt-oauth/manifest.json +1 -1
  11. package/dist/plugins/codex-router/control.js.map +1 -1
  12. package/dist/plugins/codex-router/index.js +2 -2
  13. package/dist/plugins/codex-router/index.js.map +3 -3
  14. package/dist/plugins/codex-router/manifest.json +1 -1
  15. package/dist/plugins/deepseek-reasoning-fix/index.js.map +2 -2
  16. package/dist/plugins/deepseek-reasoning-fix/manifest.json +1 -1
  17. package/dist/plugins/key-access/control.js.map +1 -1
  18. package/dist/plugins/key-access/index.js.map +2 -2
  19. package/dist/plugins/key-access/ingress.js.map +1 -1
  20. package/dist/plugins/key-access/manifest.json +1 -1
  21. package/dist/plugins/key-rate-limit/index.js.map +2 -2
  22. package/dist/plugins/key-rate-limit/manifest.json +1 -1
  23. package/dist/plugins/llm-protocol-adapter/control.js +2 -2
  24. package/dist/plugins/llm-protocol-adapter/control.js.map +4 -4
  25. package/dist/plugins/llm-protocol-adapter/index.js +2 -2
  26. package/dist/plugins/llm-protocol-adapter/index.js.map +3 -3
  27. package/dist/plugins/llm-protocol-adapter/manifest.json +1 -1
  28. package/dist/plugins/model-mapping/index.js.map +2 -2
  29. package/dist/plugins/model-mapping/manifest.json +1 -1
  30. package/dist/plugins/models-dev/index.js.map +2 -2
  31. package/dist/plugins/models-dev/manifest.json +1 -1
  32. package/dist/plugins/signature-repair/index.js.map +2 -2
  33. package/dist/plugins/signature-repair/manifest.json +1 -1
  34. package/dist/plugins/token-budget/control.js.map +1 -1
  35. package/dist/plugins/token-budget/index.js.map +2 -2
  36. package/dist/plugins/token-budget/manifest.json +1 -1
  37. package/dist/plugins/token-metering/index.js.map +2 -2
  38. package/dist/plugins/token-metering/manifest.json +1 -1
  39. package/dist/plugins/token-stats/control.js.map +1 -1
  40. package/dist/plugins/token-stats/index.js.map +2 -2
  41. package/dist/plugins/token-stats/manifest.json +1 -1
  42. package/dist/plugins/user-auth/control.js +3911 -0
  43. package/dist/plugins/{local-accounts → user-auth}/control.js.map +8 -5
  44. package/dist/plugins/{local-accounts → user-auth}/index.js +6 -6
  45. package/dist/plugins/{local-accounts → user-auth}/index.js.map +6 -6
  46. package/dist/plugins/user-auth/manifest.json +735 -0
  47. package/dist/plugins/user-auth/ui/ConnectionEditor.svelte +137 -0
  48. package/dist/plugins/user-auth/ui/Login.svelte +87 -0
  49. package/dist/plugins/user-auth/ui/LoginProviderIcon.svelte +19 -0
  50. package/dist/plugins/user-auth/ui/LoginSettings.svelte +141 -0
  51. package/dist/plugins/user-auth/ui/Profile.svelte +185 -0
  52. package/dist/plugins/{local-accounts → user-auth}/ui/RecoveryHelp.svelte +3 -3
  53. package/dist/plugins/user-auth/ui/SessionPolicy.svelte +104 -0
  54. package/dist/plugins/user-auth/ui/Settings.svelte +14 -0
  55. package/dist/plugins/user-auth/ui/SettingsSection.svelte +32 -0
  56. package/dist/plugins/user-auth/ui/Setup.svelte +38 -0
  57. package/dist/plugins/user-auth/ui/TurnstileChallenge.svelte +26 -0
  58. package/dist/plugins/user-auth/ui/TurnstileSettings.svelte +81 -0
  59. package/dist/plugins/user-auth/ui/Users.svelte +95 -0
  60. package/dist/plugins/user-auth/ui/assets/LICENSE.txt +30 -0
  61. package/dist/plugins/user-auth/ui/assets/github.svg +1 -0
  62. package/dist/plugins/user-auth/ui/assets/google.svg +1 -0
  63. package/dist/plugins/user-auth/ui/assets/microsoft.svg +1 -0
  64. package/dist/plugins/user-auth/ui/contracts.ts +16 -0
  65. package/dist/plugins/{local-accounts → user-auth}/ui/login-errors.ts +4 -1
  66. package/dist/plugins/user-auth/ui/turnstile.ts +21 -0
  67. package/package.json +2 -2
  68. package/dist/plugins/local-accounts/control.js +0 -715
  69. package/dist/plugins/local-accounts/manifest.json +0 -223
  70. package/dist/plugins/local-accounts/ui/Login.svelte +0 -47
  71. package/dist/plugins/local-accounts/ui/Settings.svelte +0 -117
@@ -1,11 +1,14 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../../../../../plugins/local-accounts/server/control.ts", "../../../src/plugin-logger.ts", "../../../src/hooks/impl.ts", "../../../src/plugin-extensions.ts", "../../../src/plugin-durable-state.ts", "../../../src/plugin-services/host-rpc.ts", "../../../src/plugin-services/wire-contract.ts", "../../../src/plugin-services/rpc-runtime.ts", "../../../src/plugin-services/peer-channel-protocol.ts", "../../../src/plugin-services/peer-channel-hub.ts", "../../../src/plugin-services/snapshot-store.ts", "../../../src/plugin-services.ts", "../../../src/gateway/retry-action.ts", "../../../src/token-stats-window.ts"],
3
+ "sources": ["../../../../../node_modules/oauth4webapi/build/index.js", "../../../../../node_modules/openid-client/build/index.js", "../../../../../plugins/user-auth/server/control.ts", "../../../../../plugins/user-auth/server/errors.ts", "../../../src/plugin-logger.ts", "../../../src/hooks/impl.ts", "../../../src/plugin-extensions.ts", "../../../src/plugin-durable-state.ts", "../../../src/plugin-services/host-rpc.ts", "../../../src/plugin-services/wire-contract.ts", "../../../src/plugin-services/rpc-runtime.ts", "../../../src/plugin-services/peer-channel-protocol.ts", "../../../src/plugin-services/peer-channel-hub.ts", "../../../src/plugin-services/snapshot-store.ts", "../../../src/plugin-services.ts", "../../../src/gateway/retry-action.ts", "../../../src/token-stats-window.ts"],
4
4
  "sourcesContent": [
5
- "import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';\nimport type { ControlHostContext, ControlApiHandlerContext, PluginControl, ControlPlugin } from '@jeffusion/bungee-core/plugin';\nimport type { ManagementProvider, ManagementSubject } from '@jeffusion/bungee-core/plugin';\nimport { isDurableStateConflictError, type DurableJson, type PluginDurableState, type DurableMutation, type DurableRecord } from '@jeffusion/bungee-core/plugin';\n\ninterface Administrator { id: string; username: string; disabled: boolean; passwordHash: string; temporary: boolean; generation: number; failureEpoch: number }\ninterface SessionPolicy { idleTimeoutMinutes: number; absoluteTimeoutMinutes: number }\ninterface Session { digest: string; administratorId: string; generation: number; created: number; touched: number; transport: 'cookie' | 'bearer'; policy?: SessionPolicy }\ninterface Failure { key: string; count: number; until: number; epoch: number }\ninterface Slot<T> { key: string; version: number; value: T | null }\nexport interface Dependencies { now?: () => number; trustedSource?: (request: Request) => string }\nconst PROVIDER = 'local-accounts';\nconst COOKIE = 'bungee_local_session';\nconst DEFAULT_SESSION_POLICY: Readonly<SessionPolicy> = Object.freeze({ idleTimeoutMinutes: 30, absoluteTimeoutMinutes: 480 });\n// Chromium caps persistent cookies at 400 days. Verification renews this browser lease,\n// never the server-side absolute deadline. Browser/user cleanup remains outside our control.\nconst COOKIE_LEASE_SECONDS = 400 * 24 * 60 * 60;\nconst MAX_TIMEOUT_MINUTES = Math.floor(Number.MAX_SAFE_INTEGER / 60_000);\nconst ALL = ['config.read', 'config.write', 'logs.read', 'logs.body', 'keys.read', 'keys.write', 'plugins.read', 'plugins.toggle', 'plugins.code', 'auth.mode', 'self.password', 'self.logout'];\nclass AccountError extends Error { constructor(readonly code: string, readonly status = 400) { super(code); } }\nfunction fail(code: string, status = 400): never { throw new AccountError(code, status); }\nfunction object(v: unknown): Record<string, unknown> { if (!v || typeof v !== 'object' || Array.isArray(v)) fail('invalid_input'); return v as Record<string, unknown>; }\nfunction exact(v: Record<string, unknown>, fields: string[]) { if (Object.keys(v).some(k => !fields.includes(k))) fail('invalid_input'); }\nfunction username(v: unknown): string { if (typeof v !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9_.@-]{0,63}$/.test(v)) fail('invalid_input'); return v.toLowerCase(); }\nfunction password(v: unknown): string { if (typeof v !== 'string' || [...v].length < 6 || [...v].length > 64) fail('invalid_password'); return v; }\nfunction digest(v: string): string { return createHash('sha256').update(v).digest('hex'); }\nfunction csrf(token: string): string { return createHmac('sha256', token).update('local-accounts/csrf/v1').digest('base64url'); }\nfunction constant(a: string, b: string): boolean { const aa = Buffer.from(a), bb = Buffer.from(b); return aa.length === bb.length && timingSafeEqual(aa, bb); }\nfunction dto(m: Administrator) { return { id: m.id, username: m.username, requiresPasswordChange: m.temporary }; }\nfunction json(v: unknown, status = 200, headers: Record<string, string> = {}): Response { return Response.json(v, { status, headers: { 'cache-control': 'no-store', ...headers } }); }\nfunction safe(error: unknown): Response { return error instanceof AccountError ? json({ error: error.code }, error.status) : json({ error: 'provider_unavailable' }, 503); }\nasync function body(request: Request): Promise<Record<string, unknown>> {\n const reader = request.body?.getReader(); if (!reader) fail('invalid_input');\n let size = 0; const chunks: Uint8Array[] = [];\n try { for (;;) { const r = await reader.read(); if (r.done) break; size += r.value.length; if (size > 8192) { await reader.cancel(); fail('body_limit', 413); } chunks.push(r.value); } }\n finally { reader.releaseLock(); }\n try { return object(JSON.parse(Buffer.concat(chunks).toString('utf8'))); } catch (e) { if (e instanceof AccountError) throw e; return fail('invalid_input'); }\n}\nfunction credentials(request: Request): { token: string; transport: Session['transport'] } | null {\n const auth = request.headers.get('authorization');\n if (auth !== null) { const m = /^Bearer ([A-Za-z0-9_-]{43})$/.exec(auth); return m ? { token: m[1]!, transport: 'bearer' } : null; }\n const tokens = (request.headers.get('cookie') ?? '').split(';').map(x => x.trim()).filter(x => x.startsWith(COOKIE + '='));\n if (tokens.length !== 1) return null; const token = tokens[0]!.slice(COOKIE.length + 1);\n return /^[A-Za-z0-9_-]{43}$/.test(token) ? { token, transport: 'cookie' } : null;\n}\nfunction origin(request: Request, expected?: string) { if (request.headers.get('origin') !== (expected ?? new URL(request.url).origin)) fail('invalid_origin', 403); }\nfunction cookie(request: Request, token: string, maxAge: number, managementOrigin?: string) { return `${COOKIE}=${token}; Path=/; HttpOnly; SameSite=Strict; Max-Age=${maxAge}${new URL(managementOrigin ?? request.url).protocol === 'https:' ? '; Secure' : ''}`; }\n\nfunction validateSessionPolicy(value: unknown, code = 'invalid_session_policy', status = 400): SessionPolicy {\n if (!value || typeof value !== 'object' || Array.isArray(value)) fail(code, status);\n const p = value as SessionPolicy;\n if (Object.keys(p).some(key => !['idleTimeoutMinutes', 'absoluteTimeoutMinutes'].includes(key))\n || ![p.idleTimeoutMinutes, p.absoluteTimeoutMinutes].every(n => Number.isSafeInteger(n) && n >= 0 && n <= MAX_TIMEOUT_MINUTES)) fail(code, status);\n return { idleTimeoutMinutes: p.idleTimeoutMinutes, absoluteTimeoutMinutes: p.absoluteTimeoutMinutes };\n}\n\n// Fixed slots keep expired sessions, logout markers and throttles bounded. Reuse always\n// compares the previous version; a stale touch cannot restore a replaced session.\nexport const ACCOUNT_RECORD_SCHEMA = 3;\nexport const MAX_SESSIONS = 512, MAX_FAILURES = 1024;\nconst asJson = (value: unknown) => value as DurableJson;\nfunction validateAdministrator(m: unknown): asserts m is Administrator {\n const a = m as Administrator;\n if (!a || typeof a.id !== 'string' || !a.id || typeof a.username !== 'string' || !/^[a-z0-9][a-z0-9_.@-]{0,63}$/.test(a.username) || typeof a.disabled !== 'boolean' || typeof a.temporary !== 'boolean' || typeof a.passwordHash !== 'string' || !a.passwordHash.startsWith('$argon2id$') || !Number.isSafeInteger(a.generation) || a.generation < 1 || !Number.isSafeInteger(a.failureEpoch) || a.failureEpoch < 1) fail('corrupt_state', 503);\n}\nfunction envelope(value: unknown, field: string): unknown {\n if (!value || typeof value !== 'object' || Array.isArray(value)) fail('corrupt_state', 503);\n const v = value as Record<string, unknown>;\n if (v.schema !== ACCOUNT_RECORD_SCHEMA || !Object.hasOwn(v, field) || Object.keys(v).some(k => k !== 'schema' && k !== field)) fail('corrupt_state', 503);\n return v[field];\n}\nfunction administratorValue(record: DurableRecord | null): Administrator | null {\n if (!record) return null;\n const a = envelope(record.value, 'administrator'); if (a !== null) validateAdministrator(a);\n return a as Administrator | null;\n}\nfunction validateSession(value: unknown): Session | null {\n if (value === null) return null;\n const s = value as Session;\n if (!s || !/^[a-f0-9]{64}$/.test(s.digest) || typeof s.administratorId !== 'string' || !s.administratorId || !Number.isSafeInteger(s.generation) || s.generation < 1 || !Number.isFinite(s.created) || !Number.isFinite(s.touched) || s.touched < s.created || !['cookie', 'bearer'].includes(s.transport)) fail('corrupt_state', 503);\n if (s.policy !== undefined) validateSessionPolicy(s.policy, 'corrupt_state', 503);\n return s;\n}\nfunction validateFailure(value: unknown): Failure | null {\n if (value === null) return null;\n const f = value as Failure;\n if (!f || typeof f.key !== 'string' || !/^(account|source):[a-f0-9]{64}$/.test(f.key) || !Number.isSafeInteger(f.count) || f.count < 0 || !Number.isFinite(f.until) || !Number.isSafeInteger(f.epoch) || f.epoch < 1) fail('corrupt_state', 503);\n return f;\n}\nfunction slots<T extends Session | Failure>(records: readonly DurableRecord[], kind: string, limit: number, validate: (v: unknown) => T | null): Slot<T>[] {\n const result: Slot<T>[] = Array.from({length: limit}, (_, i) => ({key: `${kind}:${i}`, version: 0, value: null}));\n const seen = new Set<string>();\n for (const r of records.filter(r => r.key.startsWith(kind + ':'))) {\n const index = Number(r.key.slice(kind.length + 1));\n if (!Number.isInteger(index) || index < 0 || index >= limit || r.key !== `${kind}:${index}`) fail('corrupt_state', 503);\n const value = validate(envelope(r.value, kind));\n const identity = value && (kind === 'session' ? (value as Session).digest : (value as Failure).key);\n if (identity && seen.has(identity)) fail('corrupt_state', 503); if (identity) seen.add(identity);\n result[index] = {key: r.key, version: r.version, value};\n }\n return result;\n}\nconst mutation = <T>(slot: Slot<T>, field: string, value: T | null): DurableMutation => ({key: slot.key, expectedVersion: slot.version, value: asJson({schema: ACCOUNT_RECORD_SCHEMA, [field]: value})});\nfunction next(value: number): number { if (!Number.isSafeInteger(value + 1)) fail('generation_overflow'); return value + 1; }\n\nexport class LocalAccountsControl implements PluginControl, ManagementProvider {\n readonly management = this;\n readonly rpc = [];\n readonly api;\n private readonly state: PluginDurableState;\n private readonly now: () => number;\n private readonly subjects = new WeakMap<ManagementSubject, {generation: number; digest: string}>();\n // Positive lookups only; bounded by the fixed session slots, never by attacker tokens.\n private readonly sessionSlots = new Map<string, string>();\n private dummy = '';\n private disposed = false;\n constructor(private readonly host: ControlHostContext, private readonly dependencies: Dependencies = {}) {\n if (!host.durableState) fail('durable_state_required', 503);\n this.state = host.durableState; this.now = dependencies.now ?? Date.now;\n const invoke = (fn: (c: ControlApiHandlerContext) => Promise<Response>) => async (c: ControlApiHandlerContext) => {\n try { this.alive(); if (c.requestSignal.aborted) fail('cancelled'); return await fn(c); } catch (e) { return safe(e); }\n };\n this.api = [\n {path: '/password', methods: ['POST'], handler: 'changePassword', invoke: invoke(async c => {\n await this.requireCapability(c, 'self.password', true); const b = await body(c.request); exact(b, ['currentPassword', 'password', 'passwordConfirmation']);\n await this.changePassword(c, b); return json({ok: true}, 200, {'set-cookie': cookie(c.request, '', 0, this.host.managementOrigin)});\n })},\n {path: '/logout', methods: ['POST'], handler: 'logout', invoke: invoke(async c => { await this.requireCapability(c, 'self.logout', true); return this.logout(c.request); })},\n {path: '/self', methods: ['GET'], handler: 'self', invoke: invoke(async c => {\n await this.requireCapability(c, 'self.password'); const m = (await this.readAdministrator()).value!; const creds = credentials(c.request);\n return json({administrator: dto(m), ...(creds?.transport === 'cookie' ? {csrfToken: csrf(creds.token)} : {})});\n })},\n {path: '/session-policy', methods: ['GET', 'PUT'], handler: 'sessionPolicy', invoke: invoke(async c => {\n await this.requireCapability(c, 'config.write', c.request.method === 'PUT');\n if (c.request.method === 'GET') return json(await this.readSessionPolicy());\n const b = await body(c.request); exact(b, ['version', 'policy']); if (!Number.isSafeInteger(b.version) || (b.version as number) < 0) fail('invalid_session_policy');\n const policy = validateSessionPolicy(b.policy); await this.requireCapability(c, 'config.write', true);\n try { await this.state.transact([{key: 'session-policy', expectedVersion: b.version as number, value: asJson(policy)}]); }\n catch (e) { if (isDurableStateConflictError(e)) fail('version_conflict', 409); throw e; }\n return json(await this.readSessionPolicy());\n })},\n ];\n }\n private alive() { if (this.disposed || this.host.signal.aborted) fail('provider_unavailable', 503); }\n private async readAdministrator(): Promise<Slot<Administrator>> {\n this.alive(); const record = await this.state.get('administrator'); return {key: 'administrator', version: record?.version ?? 0, value: administratorValue(record)};\n }\n private async records() {\n this.alive(); const records = await this.state.list();\n // No legacy runtime reader. A non-current namespace requires the offline converter.\n for (const r of records) if (!['administrator', 'session-policy', 'recovery-summary'].includes(r.key) && !r.key.startsWith('session:') && !r.key.startsWith('failure:')) fail('account_migration_required', 503);\n return records;\n }\n private async retry<T>(plan: () => Promise<{mutations: DurableMutation[]; result: T}>): Promise<T> {\n for (let i = 0; i < 64; i++) {\n const {mutations, result} = await plan(); if (!mutations.length) return result;\n this.alive(); try { await this.state.transact(mutations); return result; } catch (e) { if (!isDurableStateConflictError(e)) throw e; }\n }\n return fail('version_conflict', 409);\n }\n private async readSessionPolicy(): Promise<{version: number; policy: SessionPolicy}> {\n this.alive(); const record = await this.state.get('session-policy');\n return {version: record?.version ?? 0, policy: record ? validateSessionPolicy(record.value, 'corrupt_state', 503) : {...DEFAULT_SESSION_POLICY}};\n }\n async start() {\n await this.readAdministrator(); await this.readSessionPolicy(); const records = await this.records();\n slots(records, 'session', MAX_SESSIONS, validateSession); slots(records, 'failure', MAX_FAILURES, validateFailure);\n this.dummy = await this.hash(randomBytes(32).toString('base64url'));\n }\n dispose() { this.disposed = true; }\n private hash(p: string) { return Bun.password.hash(p, {algorithm: 'argon2id', memoryCost: 65536, timeCost: 3}); }\n async hasIdentity() { const a = (await this.readAdministrator()).value; return !!a && !a.disabled; }\n async revokeSessions() { await this.retry(async () => { const a = await this.readAdministrator(); return {mutations: a.value ? [mutation(a, 'administrator', {...a.value, generation: next(a.value.generation)})] : [], result: undefined}; }); }\n async bootstrap(input: unknown) {\n const b = object(input); exact(b, ['username', 'password', 'passwordConfirmation']); const name = username(b.username), p = password(b.password);\n if (b.passwordConfirmation !== p) fail('password_confirmation'); await this.records();\n const prior = (await this.readAdministrator()).value;\n if (prior) {\n if (prior.username !== name || prior.disabled || !await Bun.password.verify(p, prior.passwordHash)) fail('invalid_credentials', 401);\n const latest = (await this.readAdministrator()).value; if (!latest || latest.generation !== prior.generation || latest.disabled) fail('invalid_credentials', 401); return;\n }\n const hashed = await this.hash(p);\n await this.retry(async () => { const a = await this.readAdministrator(); if (a.value) fail('bootstrap_conflict', 409);\n return {mutations: [mutation(a, 'administrator', {id: randomUUID(), username: name, disabled: false, temporary: false, passwordHash: hashed, generation: 1, failureEpoch: 1})], result: undefined}; });\n }\n private live(m: Administrator | null, session: Session): Administrator | undefined {\n const now = this.now(), policy = session.policy ?? DEFAULT_SESSION_POLICY;\n if (now < session.touched || now < session.created || (policy.idleTimeoutMinutes > 0 && now - session.touched >= policy.idleTimeoutMinutes * 60_000) || (policy.absoluteTimeoutMinutes > 0 && now - session.created >= policy.absoluteTimeoutMinutes * 60_000)) return;\n return m && m.id === session.administratorId && !m.disabled && m.generation === session.generation ? m : undefined;\n }\n private async findSession(d: string): Promise<Slot<Session> | undefined> {\n this.alive(); const key = this.sessionSlots.get(d);\n if (key) {\n const record = await this.state.get(key), value = record && validateSession(envelope(record.value, 'session'));\n if (record && value?.digest === d) return {key, version: record.version, value};\n this.sessionSlots.delete(d);\n }\n const found = slots(await this.records(), 'session', MAX_SESSIONS, validateSession).find(x => x.value?.digest === d);\n if (found) { if (this.sessionSlots.size >= MAX_SESSIONS) this.sessionSlots.clear(); this.sessionSlots.set(d, found.key); }\n return found;\n }\n private cookieAge(policy: SessionPolicy, elapsedMs = 0): number { return policy.absoluteTimeoutMinutes === 0 ? COOKIE_LEASE_SECONDS : Math.max(0, Math.min(COOKIE_LEASE_SECONDS, Math.floor((policy.absoluteTimeoutMinutes * 60_000 - elapsedMs) / 1000))); }\n async sessionCookie(request: Request): Promise<string | undefined> {\n this.alive(); const creds = credentials(request); if (creds?.transport !== 'cookie') return;\n const slot = await this.findSession(digest(creds.token)), m = (await this.readAdministrator()).value, session = slot?.value;\n if (!session || session.transport !== 'cookie' || !this.live(m, session)) return;\n return cookie(request, creds.token, this.cookieAge(session.policy ?? DEFAULT_SESSION_POLICY, this.now() - session.created), this.host.managementOrigin);\n }\n async authenticate(request: Request): Promise<ManagementSubject | null> {\n this.alive(); const c = credentials(request); if (!c) return null;\n const authenticated = await this.retry(async () => {\n const slot = await this.findSession(digest(c.token)), m = (await this.readAdministrator()).value, session = slot?.value;\n const administrator = session && session.transport === c.transport && this.live(m, session);\n if (!slot || !session || !administrator) return {mutations: [], result: null};\n return {mutations: [mutation(slot, 'session', {...session, touched: this.now()})], result: {administrator, digest: session.digest}};\n });\n if (!authenticated) return null;\n // A concurrent generation change can invalidate the session while its own CAS succeeds.\n const m = (await this.readAdministrator()).value;\n if (!m || m.disabled || m.generation !== authenticated.administrator.generation || m.id !== authenticated.administrator.id) return null;\n const subject = Object.freeze({id: m.id, provider: PROVIDER, capabilities: Object.freeze([...ALL]), requiresPasswordChange: m.temporary});\n this.subjects.set(subject, {generation: m.generation, digest: authenticated.digest}); return subject;\n }\n async authorize(subject: ManagementSubject, _capability: string): Promise<boolean> {\n this.alive(); const issued = this.subjects.get(subject); if (!issued || subject.provider !== PROVIDER) return false;\n const slot = await this.findSession(issued.digest), session = slot?.value, m = session && this.live((await this.readAdministrator()).value, session);\n return !!m && m.id === subject.id && m.generation === issued.generation;\n }\n private async requireCapability(c: ControlApiHandlerContext, capability: string, write = false) { if (!c.subject || !await this.authorize(c.subject, capability)) fail('forbidden', 403); if (write) this.checkWrite(c.request); }\n validateWrite(request: Request) { this.checkWrite(request); }\n csrfToken(request: Request): string | undefined { const c = credentials(request); return c?.transport === 'cookie' ? csrf(c.token) : undefined; }\n private checkWrite(request: Request) { const c = credentials(request); if (!c) fail('unauthorized', 401); if (c.transport === 'cookie') { origin(request, this.host.managementOrigin); if (!constant(request.headers.get('x-csrf-token') ?? '', csrf(c.token))) fail('invalid_csrf', 403); } }\n async login(request: Request): Promise<Response> {\n try {\n this.alive(); if (request.method !== 'POST') fail('method_not_allowed', 405);\n const b = await body(request); exact(b, ['username', 'password', 'transport']); const name = username(b.username), p = typeof b.password === 'string' ? b.password : '';\n const transport = b.transport ?? 'cookie'; if (transport !== 'cookie' && transport !== 'bearer') fail('invalid_input');\n if (transport === 'cookie' || request.headers.has('origin')) origin(request, this.host.managementOrigin);\n const source = (this.dependencies.trustedSource ?? this.host.trustedSource)?.(request) ?? 'unknown'; const keys = ['account:' + digest(name), 'source:' + digest(source)];\n // Reserve both independent buckets atomically before password work.\n const reservation = await this.retry(async () => {\n const a = (await this.readAdministrator()).value, epoch = a?.failureEpoch ?? 1, now = this.now();\n const failures = slots(await this.records(), 'failure', MAX_FAILURES, validateFailure), selected: Slot<Failure>[] = [];\n for (const key of keys) {\n let slot = failures.find(x => !selected.includes(x) && x.value?.key === key);\n const active = slot?.value && slot.value.epoch === epoch && slot.value.until > now;\n if (active && slot!.value!.count >= 10) fail('login_limited', 429);\n slot ??= failures.find(x => !selected.includes(x) && (!x.value || x.value.epoch !== epoch || x.value.until <= now));\n if (!slot) fail('login_limited', 429); selected.push(slot);\n }\n return {mutations: selected.map((slot, i) => { const prior = slot.value; return mutation(slot, 'failure', {key: keys[i]!, count: prior && prior.key === keys[i] && prior.epoch === epoch && prior.until > now ? prior.count + 1 : 1, until: prior && prior.key === keys[i] && prior.epoch === epoch && prior.until > now ? prior.until : now + 15 * 60_000, epoch}); }), result: epoch};\n });\n const candidate = (await this.readAdministrator()).value, administrator = candidate?.username === name ? candidate : null;\n const valid = await Bun.password.verify(p, administrator?.passwordHash ?? (this.dummy || await this.hash('dummy-invalid-password')));\n if (!valid || !administrator || administrator.disabled) fail('invalid_credentials', 401);\n const token = randomBytes(32).toString('base64url'), policy = (await this.readSessionPolicy()).policy, created = this.now();\n await this.retry(async () => {\n const m = (await this.readAdministrator()).value;\n if (!m || m.id !== administrator.id || m.disabled || m.generation !== administrator.generation || m.failureEpoch !== reservation) fail('invalid_credentials', 401);\n const records = await this.records(), sessions = slots(records, 'session', MAX_SESSIONS, validateSession), slot = sessions.find(x => !x.value || !this.live(m, x.value));\n if (!slot) fail('session_limit', 429);\n const changes = [mutation(slot, 'session', {digest: digest(token), administratorId: m.id, generation: m.generation, created, touched: created, transport, policy})];\n const failures = slots(records, 'failure', MAX_FAILURES, validateFailure);\n const account = failures.find(x => x.value?.key === keys[0] && x.value.epoch === reservation); if (account) changes.push(mutation(account, 'failure', null));\n const source = failures.find(x => x.value?.key === keys[1] && x.value.epoch === reservation); if (source) changes.push(mutation(source, 'failure', {...source.value!, count: Math.max(0, source.value!.count - 1)}));\n return {mutations: changes, result: undefined};\n });\n const latest = (await this.readAdministrator()).value;\n if (!latest || latest.disabled || latest.generation !== administrator.generation || latest.id !== administrator.id) fail('invalid_credentials', 401);\n return transport === 'cookie' ? json({administrator: dto(administrator), csrfToken: csrf(token)}, 200, {'set-cookie': cookie(request, token, this.cookieAge(policy, this.now() - created), this.host.managementOrigin)}) : json({administrator: dto(administrator), token, expiresIn: policy.absoluteTimeoutMinutes === 0 ? null : policy.absoluteTimeoutMinutes * 60});\n } catch (e) { return safe(e); }\n }\n async logout(request: Request): Promise<Response> {\n try { this.alive(); if (request.method !== 'POST') fail('method_not_allowed', 405); this.checkWrite(request); const c = credentials(request)!;\n await this.retry(async () => { const slot = await this.findSession(digest(c.token)); return {mutations: slot?.value ? [mutation(slot, 'session', null)] : [], result: undefined}; });\n return json({ok: true}, 200, {'set-cookie': cookie(request, '', 0, this.host.managementOrigin)});\n } catch (e) { return safe(e); }\n }\n private async changePassword(c: ControlApiHandlerContext, b: Record<string, unknown>) {\n const p = password(b.password); if (b.passwordConfirmation !== p) fail('password_confirmation');\n const m = (await this.readAdministrator()).value, id = c.subject!.id;\n if (!m || m.id !== id || typeof b.currentPassword !== 'string' || !await Bun.password.verify(b.currentPassword, m.passwordHash)) fail('invalid_credentials', 401);\n if (constant(p, b.currentPassword)) fail('password_unchanged'); const hashed = await this.hash(p);\n await this.retry(async () => {\n await this.requireCapability(c, 'self.password', true); const a = await this.readAdministrator(), current = a.value;\n if (!current || current.id !== id || current.disabled || current.generation !== m.generation) fail('version_conflict', 409);\n const issued = this.subjects.get(c.subject!)!, slot = await this.findSession(issued.digest);\n if (!slot?.value || !this.live(current, slot.value)) fail('forbidden', 403);\n return {mutations: [mutation(a, 'administrator', {...current, passwordHash: hashed, temporary: false, generation: next(current.generation)}), mutation(slot, 'session', null)], result: undefined};\n });\n }\n}\nexport function createControl(host: ControlHostContext, dependencies: Dependencies = {}): LocalAccountsControl { return new LocalAccountsControl(host, dependencies); }\nexport const api = [\n {path: '/password', methods: ['POST'], handler: 'changePassword'},\n {path: '/logout', methods: ['POST'], handler: 'logout'},\n {path: '/self', methods: ['GET'], handler: 'self'},\n {path: '/session-policy', methods: ['GET', 'PUT'], handler: 'sessionPolicy'},\n] as const;\nexport const rpc = [], controlApi = api, controlRpc = rpc;\nexport async function recoverIdentity(input: unknown, context: {durableState: PluginDurableState}) {\n const b = object(input); exact(b, ['username', 'newUsername', 'password', 'reason']);\n const name = b.username === undefined ? undefined : username(b.username), p = password(b.password), newName = b.newUsername === undefined ? undefined : username(b.newUsername);\n if (typeof b.reason !== 'string' || !b.reason.trim() || b.reason.length > 512) fail('invalid_reason');\n const state = context.durableState; await readManagementSetup(state);\n const record = await state.get('administrator'), prior = administratorValue(record);\n if (prior && name !== undefined && prior.username !== name) fail('recovery_requires_existing_administrator');\n const passwordHash = await Bun.password.hash(p, {algorithm: 'argon2id', memoryCost: 65536, timeCost: 3});\n const administrator: Administrator = prior ? {...prior, username: newName ?? prior.username, passwordHash, disabled: false, temporary: false, generation: next(prior.generation), failureEpoch: next(prior.failureEpoch)} : {id: randomUUID(), username: newName ?? name ?? fail('invalid_input'), disabled: false, temporary: false, passwordHash, generation: 1, failureEpoch: 1};\n const summary = await state.get('recovery-summary');\n await state.transact([\n {key: 'administrator', expectedVersion: record?.version ?? 0, value: asJson({schema: ACCOUNT_RECORD_SCHEMA, administrator})},\n {key: 'recovery-summary', expectedVersion: summary?.version ?? 0, value: {schema: ACCOUNT_RECORD_SCHEMA, administratorId: administrator.id, reason: b.reason, at: Date.now()}},\n ]);\n return dto(administrator);\n}\nexport async function readManagementSetup(state: Pick<PluginDurableState, 'get' | 'list'>) {\n for (const r of await state.list()) if (!['administrator', 'session-policy', 'recovery-summary'].includes(r.key) && !r.key.startsWith('session:') && !r.key.startsWith('failure:')) fail('account_migration_required', 503);\n return {initialized: !!administratorValue(await state.get('administrator'))};\n}\nexport default {createControl, readManagementSetup, offlineRecovery: {kind: 'identity', recover: recoverIdentity}} satisfies ControlPlugin;\n",
5
+ "let USER_AGENT;\nif (typeof navigator === 'undefined' || !navigator.userAgent?.startsWith?.('Mozilla/5.0 ')) {\n const NAME = 'oauth4webapi';\n const VERSION = 'v3.8.8';\n USER_AGENT = `${NAME}/${VERSION}`;\n}\nfunction looseInstanceOf(input, expected) {\n if (input == null) {\n return false;\n }\n try {\n return (input instanceof expected ||\n Object.getPrototypeOf(input)[Symbol.toStringTag] === expected.prototype[Symbol.toStringTag]);\n }\n catch {\n return false;\n }\n}\nconst ERR_INVALID_ARG_VALUE = 'ERR_INVALID_ARG_VALUE';\nconst ERR_INVALID_ARG_TYPE = 'ERR_INVALID_ARG_TYPE';\nfunction CodedTypeError(message, code, cause) {\n const err = new TypeError(message, { cause });\n Object.assign(err, { code });\n return err;\n}\nexport const allowInsecureRequests = Symbol();\nexport const clockSkew = Symbol();\nexport const clockTolerance = Symbol();\nexport const customFetch = Symbol();\nexport const modifyAssertion = Symbol();\nexport const jweDecrypt = Symbol();\nexport const jwksCache = Symbol();\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\nfunction buf(input) {\n if (typeof input === 'string') {\n return encoder.encode(input);\n }\n return decoder.decode(input);\n}\nlet encodeBase64Url;\nif (Uint8Array.prototype.toBase64) {\n encodeBase64Url = (input) => {\n if (input instanceof ArrayBuffer) {\n input = new Uint8Array(input);\n }\n return input.toBase64({ alphabet: 'base64url', omitPadding: true });\n };\n}\nelse {\n const CHUNK_SIZE = 0x8000;\n encodeBase64Url = (input) => {\n if (input instanceof ArrayBuffer) {\n input = new Uint8Array(input);\n }\n const arr = [];\n for (let i = 0; i < input.byteLength; i += CHUNK_SIZE) {\n arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));\n }\n return btoa(arr.join('')).replace(/=/g, '').replace(/\\+/g, '-').replace(/\\//g, '_');\n };\n}\nlet decodeBase64Url;\nif (Uint8Array.fromBase64) {\n decodeBase64Url = (input) => {\n try {\n return Uint8Array.fromBase64(input, { alphabet: 'base64url' });\n }\n catch (cause) {\n throw CodedTypeError('The input to be decoded is not correctly encoded.', ERR_INVALID_ARG_VALUE, cause);\n }\n };\n}\nelse {\n decodeBase64Url = (input) => {\n try {\n const binary = atob(input.replace(/-/g, '+').replace(/_/g, '/').replace(/\\s/g, ''));\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n }\n catch (cause) {\n throw CodedTypeError('The input to be decoded is not correctly encoded.', ERR_INVALID_ARG_VALUE, cause);\n }\n };\n}\nfunction b64u(input) {\n if (typeof input === 'string') {\n return decodeBase64Url(input);\n }\n return encodeBase64Url(input);\n}\nexport class UnsupportedOperationError extends Error {\n code;\n constructor(message, options) {\n super(message, options);\n this.name = this.constructor.name;\n this.code = UNSUPPORTED_OPERATION;\n Error.captureStackTrace?.(this, this.constructor);\n }\n}\nexport class OperationProcessingError extends Error {\n code;\n constructor(message, options) {\n super(message, options);\n this.name = this.constructor.name;\n if (options?.code) {\n this.code = options?.code;\n }\n Error.captureStackTrace?.(this, this.constructor);\n }\n}\nfunction OPE(message, code, cause) {\n return new OperationProcessingError(message, { code, cause });\n}\nasync function calculateJwkThumbprint(jwk) {\n let components;\n switch (jwk.kty) {\n case 'EC':\n components = {\n crv: jwk.crv,\n kty: jwk.kty,\n x: jwk.x,\n y: jwk.y,\n };\n break;\n case 'OKP':\n components = {\n crv: jwk.crv,\n kty: jwk.kty,\n x: jwk.x,\n };\n break;\n case 'AKP':\n components = {\n alg: jwk.alg,\n kty: jwk.kty,\n pub: jwk.pub,\n };\n break;\n case 'RSA':\n components = {\n e: jwk.e,\n kty: jwk.kty,\n n: jwk.n,\n };\n break;\n default:\n throw new UnsupportedOperationError('unsupported JWK key type', { cause: jwk });\n }\n return b64u(await crypto.subtle.digest('SHA-256', buf(JSON.stringify(components))));\n}\nfunction assertCryptoKey(key, it) {\n if (!(key instanceof CryptoKey)) {\n throw CodedTypeError(`${it} must be a CryptoKey`, ERR_INVALID_ARG_TYPE);\n }\n}\nfunction assertPrivateKey(key, it) {\n assertCryptoKey(key, it);\n if (key.type !== 'private') {\n throw CodedTypeError(`${it} must be a private CryptoKey`, ERR_INVALID_ARG_VALUE);\n }\n}\nfunction assertPublicKey(key, it) {\n assertCryptoKey(key, it);\n if (key.type !== 'public') {\n throw CodedTypeError(`${it} must be a public CryptoKey`, ERR_INVALID_ARG_VALUE);\n }\n}\nfunction normalizeTyp(value) {\n return value.toLowerCase().replace(/^application\\//, '');\n}\nfunction isJsonObject(input) {\n if (input === null || typeof input !== 'object' || Array.isArray(input)) {\n return false;\n }\n return true;\n}\nfunction prepareHeaders(input) {\n if (looseInstanceOf(input, Headers)) {\n input = Object.fromEntries(input.entries());\n }\n const headers = new Headers(input ?? {});\n if (USER_AGENT && !headers.has('user-agent')) {\n headers.set('user-agent', USER_AGENT);\n }\n if (headers.has('authorization')) {\n throw CodedTypeError('\"options.headers\" must not include the \"authorization\" header name', ERR_INVALID_ARG_VALUE);\n }\n return headers;\n}\nfunction signal(url, value) {\n if (value !== undefined) {\n if (typeof value === 'function') {\n value = value(url.href);\n }\n if (!(value instanceof AbortSignal)) {\n throw CodedTypeError('\"options.signal\" must return or be an instance of AbortSignal', ERR_INVALID_ARG_TYPE);\n }\n return value;\n }\n return undefined;\n}\nfunction replaceDoubleSlash(pathname) {\n if (pathname.includes('//')) {\n return pathname.replace('//', '/');\n }\n return pathname;\n}\nfunction prependWellKnown(url, wellKnown, allowTerminatingSlash = false) {\n if (url.pathname === '/') {\n url.pathname = wellKnown;\n }\n else {\n url.pathname = replaceDoubleSlash(`${wellKnown}/${allowTerminatingSlash ? url.pathname : url.pathname.replace(/(\\/)$/, '')}`);\n }\n return url;\n}\nfunction appendWellKnown(url, wellKnown) {\n url.pathname = replaceDoubleSlash(`${url.pathname}/${wellKnown}`);\n return url;\n}\nasync function performDiscovery(input, urlName, transform, options) {\n if (!(input instanceof URL)) {\n throw CodedTypeError(`\"${urlName}\" must be an instance of URL`, ERR_INVALID_ARG_TYPE);\n }\n checkProtocol(input, options?.[allowInsecureRequests] !== true);\n const url = transform(new URL(input.href));\n const headers = prepareHeaders(options?.headers);\n headers.set('accept', 'application/json');\n return (options?.[customFetch] || fetch)(url.href, {\n body: undefined,\n headers: Object.fromEntries(headers.entries()),\n method: 'GET',\n redirect: 'manual',\n signal: signal(url, options?.signal),\n });\n}\nexport async function discoveryRequest(issuerIdentifier, options) {\n return performDiscovery(issuerIdentifier, 'issuerIdentifier', (url) => {\n switch (options?.algorithm) {\n case undefined:\n case 'oidc':\n appendWellKnown(url, '.well-known/openid-configuration');\n break;\n case 'oauth2':\n prependWellKnown(url, '.well-known/oauth-authorization-server');\n break;\n default:\n throw CodedTypeError('\"options.algorithm\" must be \"oidc\" (default), or \"oauth2\"', ERR_INVALID_ARG_VALUE);\n }\n return url;\n }, options);\n}\nfunction assertNumber(input, allow0, it, code, cause) {\n try {\n if (typeof input !== 'number' || !Number.isFinite(input)) {\n throw CodedTypeError(`${it} must be a number`, ERR_INVALID_ARG_TYPE, cause);\n }\n if (input > 0)\n return;\n if (allow0) {\n if (input !== 0) {\n throw CodedTypeError(`${it} must be a non-negative number`, ERR_INVALID_ARG_VALUE, cause);\n }\n return;\n }\n throw CodedTypeError(`${it} must be a positive number`, ERR_INVALID_ARG_VALUE, cause);\n }\n catch (err) {\n if (code) {\n throw OPE(err.message, code, cause);\n }\n throw err;\n }\n}\nfunction assertString(input, it, code, cause) {\n try {\n if (typeof input !== 'string') {\n throw CodedTypeError(`${it} must be a string`, ERR_INVALID_ARG_TYPE, cause);\n }\n if (input.length === 0) {\n throw CodedTypeError(`${it} must not be empty`, ERR_INVALID_ARG_VALUE, cause);\n }\n }\n catch (err) {\n if (code) {\n throw OPE(err.message, code, cause);\n }\n throw err;\n }\n}\nexport async function processDiscoveryResponse(expectedIssuerIdentifier, response) {\n const expected = expectedIssuerIdentifier;\n if (!(expected instanceof URL) && expected !== _nodiscoverycheck) {\n throw CodedTypeError('\"expectedIssuerIdentifier\" must be an instance of URL', ERR_INVALID_ARG_TYPE);\n }\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n if (response.status !== 200) {\n throw OPE('\"response\" is not a conform Authorization Server Metadata response (unexpected HTTP status code)', RESPONSE_IS_NOT_CONFORM, response);\n }\n assertReadableResponse(response);\n const json = await getResponseJsonBody(response);\n assertString(json.issuer, '\"response\" body \"issuer\" property', INVALID_RESPONSE, { body: json });\n if (expected !== _nodiscoverycheck && new URL(json.issuer).href !== expected.href) {\n throw OPE('\"response\" body \"issuer\" property does not match the expected value', JSON_ATTRIBUTE_COMPARISON, { expected: expected.href, body: json, attribute: 'issuer' });\n }\n return json;\n}\nfunction assertApplicationJson(response) {\n assertContentType(response, 'application/json');\n}\nfunction notJson(response, ...types) {\n let msg = '\"response\" content-type must be ';\n if (types.length > 2) {\n const last = types.pop();\n msg += `${types.join(', ')}, or ${last}`;\n }\n else if (types.length === 2) {\n msg += `${types[0]} or ${types[1]}`;\n }\n else {\n msg += types[0];\n }\n return OPE(msg, RESPONSE_IS_NOT_JSON, response);\n}\nfunction assertContentTypes(response, ...types) {\n if (!types.includes(getContentType(response))) {\n throw notJson(response, ...types);\n }\n}\nfunction assertContentType(response, contentType) {\n if (getContentType(response) !== contentType) {\n throw notJson(response, contentType);\n }\n}\nfunction randomBytes() {\n return b64u(crypto.getRandomValues(new Uint8Array(32)));\n}\nexport function generateRandomCodeVerifier() {\n return randomBytes();\n}\nexport function generateRandomState() {\n return randomBytes();\n}\nexport function generateRandomNonce() {\n return randomBytes();\n}\nexport async function calculatePKCECodeChallenge(codeVerifier) {\n assertString(codeVerifier, 'codeVerifier');\n return b64u(await crypto.subtle.digest('SHA-256', buf(codeVerifier)));\n}\nfunction getKeyAndKid(input) {\n if (input instanceof CryptoKey) {\n return { key: input };\n }\n if (!(input?.key instanceof CryptoKey)) {\n return {};\n }\n if (input.kid !== undefined) {\n assertString(input.kid, '\"kid\"');\n }\n return {\n key: input.key,\n kid: input.kid,\n };\n}\nfunction psAlg(key) {\n switch (key.algorithm.hash.name) {\n case 'SHA-256':\n return 'PS256';\n case 'SHA-384':\n return 'PS384';\n case 'SHA-512':\n return 'PS512';\n default:\n throw new UnsupportedOperationError('unsupported RsaHashedKeyAlgorithm hash name', {\n cause: key,\n });\n }\n}\nfunction rsAlg(key) {\n switch (key.algorithm.hash.name) {\n case 'SHA-256':\n return 'RS256';\n case 'SHA-384':\n return 'RS384';\n case 'SHA-512':\n return 'RS512';\n default:\n throw new UnsupportedOperationError('unsupported RsaHashedKeyAlgorithm hash name', {\n cause: key,\n });\n }\n}\nfunction esAlg(key) {\n switch (key.algorithm.namedCurve) {\n case 'P-256':\n return 'ES256';\n case 'P-384':\n return 'ES384';\n case 'P-521':\n return 'ES512';\n default:\n throw new UnsupportedOperationError('unsupported EcKeyAlgorithm namedCurve', { cause: key });\n }\n}\nfunction keyToJws(key) {\n switch (key.algorithm.name) {\n case 'RSA-PSS':\n return psAlg(key);\n case 'RSASSA-PKCS1-v1_5':\n return rsAlg(key);\n case 'ECDSA':\n return esAlg(key);\n case 'Ed25519':\n case 'ML-DSA-44':\n case 'ML-DSA-65':\n case 'ML-DSA-87':\n return key.algorithm.name;\n case 'EdDSA':\n return 'Ed25519';\n default:\n throw new UnsupportedOperationError('unsupported CryptoKey algorithm name', { cause: key });\n }\n}\nfunction getClockSkew(client) {\n const skew = client?.[clockSkew];\n return typeof skew === 'number' && Number.isFinite(skew) ? skew : 0;\n}\nfunction getClockTolerance(client) {\n const tolerance = client?.[clockTolerance];\n return typeof tolerance === 'number' && Number.isFinite(tolerance) && Math.sign(tolerance) !== -1\n ? tolerance\n : 30;\n}\nfunction epochTime() {\n return Math.floor(Date.now() / 1000);\n}\nfunction assertAs(as) {\n if (typeof as !== 'object' || as === null) {\n throw CodedTypeError('\"as\" must be an object', ERR_INVALID_ARG_TYPE);\n }\n assertString(as.issuer, '\"as.issuer\"');\n}\nfunction assertClient(client) {\n if (typeof client !== 'object' || client === null) {\n throw CodedTypeError('\"client\" must be an object', ERR_INVALID_ARG_TYPE);\n }\n assertString(client.client_id, '\"client.client_id\"');\n}\nfunction formUrlEncode(token) {\n return encodeURIComponent(token).replace(/(?:[-_.!~*'()]|%20)/g, (substring) => {\n switch (substring) {\n case '-':\n case '_':\n case '.':\n case '!':\n case '~':\n case '*':\n case \"'\":\n case '(':\n case ')':\n return `%${substring.charCodeAt(0).toString(16).toUpperCase()}`;\n case '%20':\n return '+';\n default:\n throw new Error();\n }\n });\n}\nexport function ClientSecretPost(clientSecret) {\n assertString(clientSecret, '\"clientSecret\"');\n return (_as, client, body, _headers) => {\n body.set('client_id', client.client_id);\n body.set('client_secret', clientSecret);\n };\n}\nexport function ClientSecretBasic(clientSecret) {\n assertString(clientSecret, '\"clientSecret\"');\n return (_as, client, _body, headers) => {\n const username = formUrlEncode(client.client_id);\n const password = formUrlEncode(clientSecret);\n const credentials = btoa(`${username}:${password}`);\n headers.set('authorization', `Basic ${credentials}`);\n };\n}\nfunction clientAssertionPayload(as, client) {\n const now = epochTime() + getClockSkew(client);\n return {\n jti: randomBytes(),\n aud: as.issuer,\n exp: now + 60,\n iat: now,\n nbf: now,\n iss: client.client_id,\n sub: client.client_id,\n };\n}\nexport function PrivateKeyJwt(clientPrivateKey, options) {\n const { key, kid } = getKeyAndKid(clientPrivateKey);\n assertPrivateKey(key, '\"clientPrivateKey.key\"');\n return async (as, client, body, _headers) => {\n const header = { alg: keyToJws(key), kid };\n const payload = clientAssertionPayload(as, client);\n options?.[modifyAssertion]?.(header, payload);\n body.set('client_id', client.client_id);\n body.set('client_assertion_type', 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer');\n body.set('client_assertion', await signJwt(header, payload, key));\n };\n}\nexport function ClientSecretJwt(clientSecret, options) {\n assertString(clientSecret, '\"clientSecret\"');\n const modify = options?.[modifyAssertion];\n let key;\n return async (as, client, body, _headers) => {\n key ||= await crypto.subtle.importKey('raw', buf(clientSecret), { hash: 'SHA-256', name: 'HMAC' }, false, ['sign']);\n const header = { alg: 'HS256' };\n const payload = clientAssertionPayload(as, client);\n modify?.(header, payload);\n const data = `${b64u(buf(JSON.stringify(header)))}.${b64u(buf(JSON.stringify(payload)))}`;\n const hmac = await crypto.subtle.sign(key.algorithm, key, buf(data));\n body.set('client_id', client.client_id);\n body.set('client_assertion_type', 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer');\n body.set('client_assertion', `${data}.${b64u(new Uint8Array(hmac))}`);\n };\n}\nexport function None() {\n return (_as, client, body, _headers) => {\n body.set('client_id', client.client_id);\n };\n}\nexport function TlsClientAuth() {\n return None();\n}\nasync function signJwt(header, payload, key) {\n if (!key.usages.includes('sign')) {\n throw CodedTypeError('CryptoKey instances used for signing assertions must include \"sign\" in their \"usages\"', ERR_INVALID_ARG_VALUE);\n }\n const input = `${b64u(buf(JSON.stringify(header)))}.${b64u(buf(JSON.stringify(payload)))}`;\n const signature = b64u(await crypto.subtle.sign(keyToSubtle(key), key, buf(input)));\n return `${input}.${signature}`;\n}\nexport async function issueRequestObject(as, client, parameters, privateKey, options) {\n assertAs(as);\n assertClient(client);\n parameters = new URLSearchParams(parameters);\n const { key, kid } = getKeyAndKid(privateKey);\n assertPrivateKey(key, '\"privateKey.key\"');\n parameters.set('client_id', client.client_id);\n const now = epochTime() + getClockSkew(client);\n const claims = {\n ...Object.fromEntries(parameters.entries()),\n jti: randomBytes(),\n aud: as.issuer,\n exp: now + 60,\n iat: now,\n nbf: now,\n iss: client.client_id,\n };\n let resource;\n if (parameters.has('resource') &&\n (resource = parameters.getAll('resource')) &&\n resource.length > 1) {\n claims.resource = resource;\n }\n {\n let value = parameters.get('max_age');\n if (value !== null) {\n claims.max_age = parseInt(value, 10);\n assertNumber(claims.max_age, true, '\"max_age\" parameter');\n }\n }\n {\n let value = parameters.get('claims');\n if (value !== null) {\n try {\n claims.claims = JSON.parse(value);\n }\n catch (cause) {\n throw OPE('failed to parse the \"claims\" parameter as JSON', PARSE_ERROR, cause);\n }\n if (!isJsonObject(claims.claims)) {\n throw CodedTypeError('\"claims\" parameter must be a JSON with a top level object', ERR_INVALID_ARG_VALUE);\n }\n }\n }\n {\n let value = parameters.get('authorization_details');\n if (value !== null) {\n try {\n claims.authorization_details = JSON.parse(value);\n }\n catch (cause) {\n throw OPE('failed to parse the \"authorization_details\" parameter as JSON', PARSE_ERROR, cause);\n }\n if (!Array.isArray(claims.authorization_details)) {\n throw CodedTypeError('\"authorization_details\" parameter must be a JSON with a top level array', ERR_INVALID_ARG_VALUE);\n }\n }\n }\n const header = {\n alg: keyToJws(key),\n typ: 'oauth-authz-req+jwt',\n kid,\n };\n options?.[modifyAssertion]?.(header, claims);\n return signJwt(header, claims, key);\n}\nlet jwkCache;\nasync function getSetPublicJwkCache(key, alg) {\n const { kty, e, n, x, y, crv, pub } = await crypto.subtle.exportKey('jwk', key);\n const jwk = { kty, e, n, x, y, crv, pub };\n if (kty === 'AKP')\n jwk.alg = alg;\n jwkCache.set(key, jwk);\n return jwk;\n}\nasync function publicJwk(key, alg) {\n jwkCache ||= new WeakMap();\n return jwkCache.get(key) || getSetPublicJwkCache(key, alg);\n}\nconst URLParse = URL.parse\n ?\n (url, base) => URL.parse(url, base)\n : (url, base) => {\n try {\n return new URL(url, base);\n }\n catch {\n return null;\n }\n };\nexport function checkProtocol(url, enforceHttps) {\n if (enforceHttps && url.protocol !== 'https:') {\n throw OPE('only requests to HTTPS are allowed', HTTP_REQUEST_FORBIDDEN, url);\n }\n if (url.protocol !== 'https:' && url.protocol !== 'http:') {\n throw OPE('only HTTP and HTTPS requests are allowed', REQUEST_PROTOCOL_FORBIDDEN, url);\n }\n}\nfunction validateEndpoint(value, endpoint, useMtlsAlias, enforceHttps) {\n let url;\n if (typeof value !== 'string' || !(url = URLParse(value))) {\n throw OPE(`authorization server metadata does not contain a valid ${useMtlsAlias ? `\"as.mtls_endpoint_aliases.${endpoint}\"` : `\"as.${endpoint}\"`}`, value === undefined ? MISSING_SERVER_METADATA : INVALID_SERVER_METADATA, { attribute: useMtlsAlias ? `mtls_endpoint_aliases.${endpoint}` : endpoint });\n }\n checkProtocol(url, enforceHttps);\n return url;\n}\nexport function resolveEndpoint(as, endpoint, useMtlsAlias, enforceHttps) {\n if (useMtlsAlias && as.mtls_endpoint_aliases && endpoint in as.mtls_endpoint_aliases) {\n return validateEndpoint(as.mtls_endpoint_aliases[endpoint], endpoint, useMtlsAlias, enforceHttps);\n }\n return validateEndpoint(as[endpoint], endpoint, useMtlsAlias, enforceHttps);\n}\nexport async function pushedAuthorizationRequest(as, client, clientAuthentication, parameters, options) {\n assertAs(as);\n assertClient(client);\n const url = resolveEndpoint(as, 'pushed_authorization_request_endpoint', client.use_mtls_endpoint_aliases, options?.[allowInsecureRequests] !== true);\n const body = new URLSearchParams(parameters);\n body.set('client_id', client.client_id);\n const headers = prepareHeaders(options?.headers);\n headers.set('accept', 'application/json');\n if (options?.DPoP !== undefined) {\n assertDPoP(options.DPoP);\n await options.DPoP.addProof(url, headers, 'POST');\n }\n const response = await authenticatedRequest(as, client, clientAuthentication, url, body, headers, options);\n options?.DPoP?.cacheNonce(response, url);\n return response;\n}\nclass DPoPHandler {\n #header;\n #privateKey;\n #publicKey;\n #clockSkew;\n #modifyAssertion;\n #map;\n #jkt;\n constructor(client, keyPair, options) {\n assertPrivateKey(keyPair?.privateKey, '\"DPoP.privateKey\"');\n assertPublicKey(keyPair?.publicKey, '\"DPoP.publicKey\"');\n if (!keyPair.publicKey.extractable) {\n throw CodedTypeError('\"DPoP.publicKey.extractable\" must be true', ERR_INVALID_ARG_VALUE);\n }\n this.#modifyAssertion = options?.[modifyAssertion];\n this.#clockSkew = getClockSkew(client);\n this.#privateKey = keyPair.privateKey;\n this.#publicKey = keyPair.publicKey;\n branded.add(this);\n }\n #get(key) {\n this.#map ||= new Map();\n let item = this.#map.get(key);\n if (item) {\n this.#map.delete(key);\n this.#map.set(key, item);\n }\n return item;\n }\n #set(key, val) {\n this.#map ||= new Map();\n this.#map.delete(key);\n if (this.#map.size === 100) {\n this.#map.delete(this.#map.keys().next().value);\n }\n this.#map.set(key, val);\n }\n async calculateThumbprint() {\n if (!this.#jkt) {\n const jwk = await crypto.subtle.exportKey('jwk', this.#publicKey);\n this.#jkt ||= await calculateJwkThumbprint(jwk);\n }\n return this.#jkt;\n }\n async addProof(url, headers, htm, accessToken) {\n const alg = keyToJws(this.#privateKey);\n this.#header ||= {\n alg,\n typ: 'dpop+jwt',\n jwk: await publicJwk(this.#publicKey, alg),\n };\n const nonce = this.#get(url.origin);\n const now = epochTime() + this.#clockSkew;\n const payload = {\n iat: now,\n jti: randomBytes(),\n htm,\n nonce,\n htu: `${url.origin}${url.pathname}`,\n ath: accessToken\n ? b64u(await crypto.subtle.digest('SHA-256', buf(accessToken)))\n : undefined,\n };\n this.#modifyAssertion?.(this.#header, payload);\n headers.set('dpop', await signJwt(this.#header, payload, this.#privateKey));\n }\n cacheNonce(response, url) {\n try {\n const nonce = response.headers.get('dpop-nonce');\n if (nonce) {\n this.#set(url.origin, nonce);\n }\n }\n catch { }\n }\n}\nexport function isDPoPNonceError(err) {\n if (err instanceof WWWAuthenticateChallengeError) {\n return err.cause.some((challenge) => challenge.scheme === 'dpop' && challenge.parameters.error === 'use_dpop_nonce');\n }\n if (err instanceof ResponseBodyError) {\n return err.error === 'use_dpop_nonce';\n }\n return false;\n}\nexport function DPoP(client, keyPair, options) {\n return new DPoPHandler(client, keyPair, options);\n}\nexport class ResponseBodyError extends Error {\n cause;\n code;\n error;\n status;\n error_description;\n response;\n constructor(message, options) {\n super(message, options);\n this.name = this.constructor.name;\n this.code = RESPONSE_BODY_ERROR;\n this.cause = options.cause;\n this.error = options.cause.error;\n this.status = options.response.status;\n this.error_description = options.cause.error_description;\n Object.defineProperty(this, 'response', { enumerable: false, value: options.response });\n Error.captureStackTrace?.(this, this.constructor);\n }\n}\nexport class AuthorizationResponseError extends Error {\n cause;\n code;\n error;\n error_description;\n constructor(message, options) {\n super(message, options);\n this.name = this.constructor.name;\n this.code = AUTHORIZATION_RESPONSE_ERROR;\n this.cause = options.cause;\n this.error = options.cause.get('error');\n this.error_description = options.cause.get('error_description') ?? undefined;\n Error.captureStackTrace?.(this, this.constructor);\n }\n}\nexport class WWWAuthenticateChallengeError extends Error {\n cause;\n code;\n response;\n status;\n constructor(message, options) {\n super(message, options);\n this.name = this.constructor.name;\n this.code = WWW_AUTHENTICATE_CHALLENGE;\n this.cause = options.cause;\n this.status = options.response.status;\n this.response = options.response;\n Object.defineProperty(this, 'response', { enumerable: false });\n Error.captureStackTrace?.(this, this.constructor);\n }\n}\nconst tokenMatch = \"[a-zA-Z0-9!#$%&\\\\'\\\\*\\\\+\\\\-\\\\.\\\\^_`\\\\|~]+\";\nconst token68Match = '[a-zA-Z0-9\\\\-\\\\._\\\\~\\\\+\\\\/]+={0,2}';\nconst quotedMatch = '\"((?:[^\"\\\\\\\\]|\\\\\\\\[\\\\s\\\\S])*)\"';\nconst quotedParamMatcher = '(' + tokenMatch + ')\\\\s*=\\\\s*' + quotedMatch;\nconst paramMatcher = '(' + tokenMatch + ')\\\\s*=\\\\s*(' + tokenMatch + ')';\nconst schemeRE = new RegExp('^[,\\\\s]*(' + tokenMatch + ')');\nconst quotedParamRE = new RegExp('^[,\\\\s]*' + quotedParamMatcher + '[,\\\\s]*(.*)');\nconst unquotedParamRE = new RegExp('^[,\\\\s]*' + paramMatcher + '[,\\\\s]*(.*)');\nconst token68ParamRE = new RegExp('^(' + token68Match + ')(?:$|[,\\\\s])(.*)');\nfunction parseWwwAuthenticateChallenges(response) {\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n const header = response.headers.get('www-authenticate');\n if (header === null) {\n return undefined;\n }\n const challenges = [];\n let rest = header;\n while (rest) {\n let match = rest.match(schemeRE);\n const scheme = match?.['1'].toLowerCase();\n if (!scheme) {\n return undefined;\n }\n const afterScheme = rest.substring(match[0].length);\n if (afterScheme && !afterScheme.match(/^[\\s,]/)) {\n return undefined;\n }\n const spaceMatch = afterScheme.match(/^\\s+(.*)$/);\n const hasParameters = !!spaceMatch;\n rest = spaceMatch ? spaceMatch[1] : undefined;\n const parameters = {};\n let token68;\n if (hasParameters) {\n while (rest) {\n let key;\n let value;\n if ((match = rest.match(quotedParamRE))) {\n ;\n [, key, value, rest] = match;\n if (value.includes('\\\\')) {\n value = value.replace(/\\\\([\\s\\S])/g, '$1');\n }\n parameters[key.toLowerCase()] = value;\n continue;\n }\n if ((match = rest.match(unquotedParamRE))) {\n ;\n [, key, value, rest] = match;\n parameters[key.toLowerCase()] = value;\n continue;\n }\n if ((match = rest.match(token68ParamRE))) {\n if (Object.keys(parameters).length) {\n break;\n }\n ;\n [, token68, rest] = match;\n break;\n }\n return undefined;\n }\n }\n else {\n rest = afterScheme || undefined;\n }\n const challenge = { scheme, parameters };\n if (token68) {\n challenge.token68 = token68;\n }\n challenges.push(challenge);\n }\n if (!challenges.length) {\n return undefined;\n }\n return challenges;\n}\nexport async function processPushedAuthorizationResponse(as, client, response) {\n assertAs(as);\n assertClient(client);\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n await checkOAuthBodyError(response, 201, 'Pushed Authorization Request Endpoint');\n assertReadableResponse(response);\n const json = await getResponseJsonBody(response);\n assertString(json.request_uri, '\"response\" body \"request_uri\" property', INVALID_RESPONSE, {\n body: json,\n });\n let expiresIn = typeof json.expires_in !== 'number' ? parseFloat(json.expires_in) : json.expires_in;\n assertNumber(expiresIn, true, '\"response\" body \"expires_in\" property', INVALID_RESPONSE, {\n body: json,\n });\n json.expires_in = expiresIn;\n return json;\n}\nasync function parseOAuthResponseErrorBody(response) {\n if (response.status > 399 && response.status < 500) {\n assertReadableResponse(response);\n assertApplicationJson(response);\n try {\n const json = await response.clone().json();\n if (isJsonObject(json) && typeof json.error === 'string' && json.error.length) {\n return json;\n }\n }\n catch { }\n }\n return undefined;\n}\nasync function checkOAuthBodyError(response, expected, label) {\n if (response.status !== expected) {\n checkAuthenticationChallenges(response);\n let err;\n if ((err = await parseOAuthResponseErrorBody(response))) {\n await response.body?.cancel();\n throw new ResponseBodyError('server responded with an error in the response body', {\n cause: err,\n response,\n });\n }\n throw OPE(`\"response\" is not a conform ${label} response (unexpected HTTP status code)`, RESPONSE_IS_NOT_CONFORM, response);\n }\n}\nfunction assertDPoP(option) {\n if (!branded.has(option)) {\n throw CodedTypeError('\"options.DPoP\" is not a valid DPoPHandle', ERR_INVALID_ARG_VALUE);\n }\n}\nasync function resourceRequest(accessToken, method, url, headers, body, options) {\n assertString(accessToken, '\"accessToken\"');\n if (!(url instanceof URL)) {\n throw CodedTypeError('\"url\" must be an instance of URL', ERR_INVALID_ARG_TYPE);\n }\n checkProtocol(url, options?.[allowInsecureRequests] !== true);\n headers = prepareHeaders(headers);\n if (options?.DPoP) {\n assertDPoP(options.DPoP);\n await options.DPoP.addProof(url, headers, method.toUpperCase(), accessToken);\n }\n headers.set('authorization', `${headers.has('dpop') ? 'DPoP' : 'Bearer'} ${accessToken}`);\n const response = await (options?.[customFetch] || fetch)(url.href, {\n duplex: looseInstanceOf(body, ReadableStream) ? 'half' : undefined,\n body,\n headers: Object.fromEntries(headers.entries()),\n method,\n redirect: 'manual',\n signal: signal(url, options?.signal),\n });\n options?.DPoP?.cacheNonce(response, url);\n return response;\n}\nexport async function protectedResourceRequest(accessToken, method, url, headers, body, options) {\n const response = await resourceRequest(accessToken, method, url, headers, body, options);\n checkAuthenticationChallenges(response);\n return response;\n}\nexport async function userInfoRequest(as, client, accessToken, options) {\n assertAs(as);\n assertClient(client);\n const url = resolveEndpoint(as, 'userinfo_endpoint', client.use_mtls_endpoint_aliases, options?.[allowInsecureRequests] !== true);\n const headers = prepareHeaders(options?.headers);\n if (client.userinfo_signed_response_alg) {\n headers.set('accept', 'application/jwt');\n }\n else {\n headers.set('accept', 'application/json');\n headers.append('accept', 'application/jwt');\n }\n return resourceRequest(accessToken, 'GET', url, headers, null, {\n ...options,\n [clockSkew]: getClockSkew(client),\n });\n}\nlet jwksMap;\nlet jwksRequests;\nlet jwksKeys;\nfunction setJwksCache(as, jwks, uat, cache) {\n jwksMap ||= new WeakMap();\n jwksMap.set(as, {\n jwks,\n uat,\n get age() {\n return epochTime() - this.uat;\n },\n });\n if (cache) {\n Object.assign(cache, { jwks: structuredClone(jwks), uat });\n }\n}\nfunction isFreshJwksCache(input) {\n if (typeof input !== 'object' || input === null) {\n return false;\n }\n if (!('uat' in input) || typeof input.uat !== 'number' || epochTime() - input.uat >= 300) {\n return false;\n }\n if (!('jwks' in input) ||\n !isJsonObject(input.jwks) ||\n !Array.isArray(input.jwks.keys) ||\n !Array.prototype.every.call(input.jwks.keys, isJsonObject)) {\n return false;\n }\n return true;\n}\nfunction clearJwksCache(as, cache) {\n jwksMap?.delete(as);\n delete cache?.jwks;\n delete cache?.uat;\n}\nasync function getPublicSigKeyFromIssuerJwksUri(as, options, header) {\n const { alg, kid } = header;\n checkSupportedJwsAlg(header);\n if (!jwksMap?.has(as) && isFreshJwksCache(options?.[jwksCache])) {\n setJwksCache(as, options?.[jwksCache].jwks, options?.[jwksCache].uat);\n }\n let jwks;\n let age;\n if (jwksMap?.has(as)) {\n ;\n ({ jwks, age } = jwksMap.get(as));\n if (age >= 300) {\n clearJwksCache(as, options?.[jwksCache]);\n return getPublicSigKeyFromIssuerJwksUri(as, options, header);\n }\n }\n else {\n const downloaded = await jwksRequest(as, options);\n jwks = downloaded.jwks;\n age = epochTime() - downloaded.uat;\n setJwksCache(as, jwks, downloaded.uat, options?.[jwksCache]);\n }\n let kty;\n switch (alg.slice(0, 2)) {\n case 'RS':\n case 'PS':\n kty = 'RSA';\n break;\n case 'ES':\n kty = 'EC';\n break;\n case 'Ed':\n kty = 'OKP';\n break;\n case 'ML':\n kty = 'AKP';\n break;\n default:\n throw new UnsupportedOperationError('unsupported JWS algorithm', { cause: { alg } });\n }\n const candidates = jwks.keys.filter((jwk) => {\n if (jwk.kty !== kty) {\n return false;\n }\n if (kid !== undefined && kid !== jwk.kid) {\n return false;\n }\n if (jwk.alg !== undefined && alg !== jwk.alg) {\n return false;\n }\n if (jwk.use !== undefined && jwk.use !== 'sig') {\n return false;\n }\n if (jwk.key_ops?.includes('verify') === false) {\n return false;\n }\n switch (true) {\n case alg === 'ES256' && jwk.crv !== 'P-256':\n case alg === 'ES384' && jwk.crv !== 'P-384':\n case alg === 'ES512' && jwk.crv !== 'P-521':\n case alg === 'Ed25519' && jwk.crv !== 'Ed25519':\n case alg === 'EdDSA' && jwk.crv !== 'Ed25519':\n return false;\n }\n return true;\n });\n const { 0: jwk, length } = candidates;\n if (!length) {\n if (age >= 60) {\n clearJwksCache(as, options?.[jwksCache]);\n return getPublicSigKeyFromIssuerJwksUri(as, options, header);\n }\n throw OPE('error when selecting a JWT verification key, no applicable keys found', KEY_SELECTION, { header, candidates, jwks_uri: new URL(as.jwks_uri) });\n }\n if (length !== 1) {\n throw OPE('error when selecting a JWT verification key, multiple applicable keys found, a \"kid\" JWT Header Parameter is required', KEY_SELECTION, { header, candidates, jwks_uri: new URL(as.jwks_uri) });\n }\n jwksKeys ||= new WeakMap();\n let keys = jwksKeys.get(jwk);\n if (!keys) {\n keys = new Map();\n jwksKeys.set(jwk, keys);\n }\n let key = keys.get(alg);\n if (!key) {\n key = importJwk(alg, jwk).catch((cause) => {\n keys.delete(alg);\n throw cause;\n });\n keys.set(alg, key);\n }\n return key;\n}\nexport const skipSubjectCheck = Symbol();\nexport function getContentType(input) {\n return input.headers.get('content-type')?.split(';')[0];\n}\nexport async function processUserInfoResponse(as, client, expectedSubject, response, options) {\n assertAs(as);\n assertClient(client);\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n checkAuthenticationChallenges(response);\n if (response.status !== 200) {\n throw OPE('\"response\" is not a conform UserInfo Endpoint response (unexpected HTTP status code)', RESPONSE_IS_NOT_CONFORM, response);\n }\n assertReadableResponse(response);\n let json;\n if (getContentType(response) === 'application/jwt') {\n const { claims, jwt } = await validateJwt(await response.text(), checkSigningAlgorithm.bind(undefined, client.userinfo_signed_response_alg, as.userinfo_signing_alg_values_supported, undefined), getClockSkew(client), getClockTolerance(client), options?.[jweDecrypt])\n .then(validateOptionalAudience.bind(undefined, client.client_id))\n .then(validateOptionalIssuer.bind(undefined, as));\n jwtRefs.set(response, jwt);\n json = claims;\n }\n else {\n if (client.userinfo_signed_response_alg) {\n throw OPE('JWT UserInfo Response expected', JWT_USERINFO_EXPECTED, response);\n }\n json = await getResponseJsonBody(response);\n }\n assertString(json.sub, '\"response\" body \"sub\" property', INVALID_RESPONSE, { body: json });\n switch (expectedSubject) {\n case skipSubjectCheck:\n break;\n default:\n assertString(expectedSubject, '\"expectedSubject\"');\n if (json.sub !== expectedSubject) {\n throw OPE('unexpected \"response\" body \"sub\" property value', JSON_ATTRIBUTE_COMPARISON, {\n expected: expectedSubject,\n body: json,\n attribute: 'sub',\n });\n }\n }\n return json;\n}\nasync function authenticatedRequest(as, client, clientAuthentication, url, body, headers, options) {\n await clientAuthentication(as, client, body, headers);\n headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8');\n return (options?.[customFetch] || fetch)(url.href, {\n body,\n headers: Object.fromEntries(headers.entries()),\n method: 'POST',\n redirect: 'manual',\n signal: signal(url, options?.signal),\n });\n}\nasync function tokenEndpointRequest(as, client, clientAuthentication, grantType, parameters, options) {\n const url = resolveEndpoint(as, 'token_endpoint', client.use_mtls_endpoint_aliases, options?.[allowInsecureRequests] !== true);\n parameters.set('grant_type', grantType);\n const headers = prepareHeaders(options?.headers);\n headers.set('accept', 'application/json');\n if (options?.DPoP !== undefined) {\n assertDPoP(options.DPoP);\n await options.DPoP.addProof(url, headers, 'POST');\n }\n const response = await authenticatedRequest(as, client, clientAuthentication, url, parameters, headers, options);\n options?.DPoP?.cacheNonce(response, url);\n return response;\n}\nexport async function refreshTokenGrantRequest(as, client, clientAuthentication, refreshToken, options) {\n assertAs(as);\n assertClient(client);\n assertString(refreshToken, '\"refreshToken\"');\n const parameters = new URLSearchParams(options?.additionalParameters);\n parameters.set('refresh_token', refreshToken);\n return tokenEndpointRequest(as, client, clientAuthentication, 'refresh_token', parameters, options);\n}\nconst idTokenClaims = new WeakMap();\nconst jwtRefs = new WeakMap();\nexport function getValidatedIdTokenClaims(ref) {\n if (!ref.id_token) {\n return undefined;\n }\n const claims = idTokenClaims.get(ref);\n if (!claims) {\n throw CodedTypeError('\"ref\" was already garbage collected or did not resolve from the proper sources', ERR_INVALID_ARG_VALUE);\n }\n return claims;\n}\nexport async function validateApplicationLevelSignature(as, ref, options) {\n assertAs(as);\n if (!jwtRefs.has(ref)) {\n throw CodedTypeError('\"ref\" does not contain a processed JWT Response to verify the signature of', ERR_INVALID_ARG_VALUE);\n }\n const { 0: protectedHeader, 1: payload, 2: encodedSignature } = jwtRefs.get(ref).split('.');\n const header = JSON.parse(buf(b64u(protectedHeader)));\n if (header.alg.startsWith('HS')) {\n throw new UnsupportedOperationError('unsupported JWS algorithm', { cause: { alg: header.alg } });\n }\n let key;\n key = await getPublicSigKeyFromIssuerJwksUri(as, options, header);\n await validateJwsSignature(protectedHeader, payload, key, b64u(encodedSignature));\n}\nasync function processGenericAccessTokenResponse(as, client, response, additionalRequiredIdTokenClaims, decryptFn, recognizedTokenTypes) {\n assertAs(as);\n assertClient(client);\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n await checkOAuthBodyError(response, 200, 'Token Endpoint');\n assertReadableResponse(response);\n const json = await getResponseJsonBody(response);\n assertString(json.access_token, '\"response\" body \"access_token\" property', INVALID_RESPONSE, {\n body: json,\n });\n assertString(json.token_type, '\"response\" body \"token_type\" property', INVALID_RESPONSE, {\n body: json,\n });\n json.token_type = json.token_type.toLowerCase();\n if (json.expires_in !== undefined) {\n let expiresIn = typeof json.expires_in !== 'number' ? parseFloat(json.expires_in) : json.expires_in;\n assertNumber(expiresIn, true, '\"response\" body \"expires_in\" property', INVALID_RESPONSE, {\n body: json,\n });\n json.expires_in = expiresIn;\n }\n if (json.refresh_token !== undefined) {\n assertString(json.refresh_token, '\"response\" body \"refresh_token\" property', INVALID_RESPONSE, {\n body: json,\n });\n }\n if (json.scope !== undefined && typeof json.scope !== 'string') {\n throw OPE('\"response\" body \"scope\" property must be a string', INVALID_RESPONSE, { body: json });\n }\n if (json.id_token !== undefined) {\n assertString(json.id_token, '\"response\" body \"id_token\" property', INVALID_RESPONSE, {\n body: json,\n });\n const requiredClaims = [];\n if (client.require_auth_time === true) {\n requiredClaims.push('auth_time');\n }\n if (client.default_max_age !== undefined) {\n assertNumber(client.default_max_age, true, '\"client.default_max_age\"');\n requiredClaims.push('auth_time');\n }\n if (additionalRequiredIdTokenClaims?.length) {\n requiredClaims.push(...additionalRequiredIdTokenClaims);\n }\n const { claims, jwt } = await validateIdTokenClaims(as, client, json.id_token, requiredClaims, decryptFn);\n validateIdTokenAuthorizedParty(client, claims);\n validateIdTokenAuthTimeClaim(claims);\n jwtRefs.set(response, jwt);\n idTokenClaims.set(json, claims);\n }\n if (recognizedTokenTypes?.[json.token_type] !== undefined) {\n recognizedTokenTypes[json.token_type](response, json);\n }\n else if (json.token_type !== 'dpop' && json.token_type !== 'bearer') {\n throw new UnsupportedOperationError('unsupported `token_type` value', { cause: { body: json } });\n }\n return json;\n}\nfunction checkAuthenticationChallenges(response) {\n let challenges;\n if ((challenges = parseWwwAuthenticateChallenges(response))) {\n throw new WWWAuthenticateChallengeError('server responded with a challenge in the WWW-Authenticate HTTP Header', { cause: challenges, response });\n }\n}\nexport async function processRefreshTokenResponse(as, client, response, options) {\n return processGenericAccessTokenResponse(as, client, response, undefined, options?.[jweDecrypt], options?.recognizedTokenTypes);\n}\nfunction validateOptionalAudience(expected, result) {\n if (result.claims.aud !== undefined) {\n return validateAudience(expected, result);\n }\n return result;\n}\nfunction validateAudience(expected, result) {\n if (Array.isArray(result.claims.aud)) {\n if (!result.claims.aud.includes(expected)) {\n throw OPE('unexpected JWT \"aud\" (audience) claim value', JWT_CLAIM_COMPARISON, {\n expected,\n claims: result.claims,\n claim: 'aud',\n });\n }\n }\n else if (result.claims.aud !== expected) {\n throw OPE('unexpected JWT \"aud\" (audience) claim value', JWT_CLAIM_COMPARISON, {\n expected,\n claims: result.claims,\n claim: 'aud',\n });\n }\n return result;\n}\nfunction validateOptionalIssuer(as, result) {\n if (result.claims.iss !== undefined) {\n return validateIssuer(as, result);\n }\n return result;\n}\nfunction validateIssuer(as, result) {\n const expected = as[_expectedIssuer]?.(result) ?? as.issuer;\n if (result.claims.iss !== expected) {\n throw OPE('unexpected JWT \"iss\" (issuer) claim value', JWT_CLAIM_COMPARISON, {\n expected,\n claims: result.claims,\n claim: 'iss',\n });\n }\n return result;\n}\nconst branded = new WeakSet();\nfunction brand(searchParams) {\n branded.add(searchParams);\n return searchParams;\n}\nexport const nopkce = Symbol();\nexport async function authorizationCodeGrantRequest(as, client, clientAuthentication, callbackParameters, redirectUri, codeVerifier, options) {\n assertAs(as);\n assertClient(client);\n if (!branded.has(callbackParameters)) {\n throw CodedTypeError('\"callbackParameters\" must be an instance of URLSearchParams obtained from \"validateAuthResponse()\", or \"validateJwtAuthResponse()', ERR_INVALID_ARG_VALUE);\n }\n assertString(redirectUri, '\"redirectUri\"');\n const code = getURLSearchParameter(callbackParameters, 'code');\n if (!code) {\n throw OPE('no authorization code in \"callbackParameters\"', INVALID_RESPONSE);\n }\n const parameters = new URLSearchParams(options?.additionalParameters);\n parameters.set('redirect_uri', redirectUri);\n parameters.set('code', code);\n if (codeVerifier !== nopkce) {\n assertString(codeVerifier, '\"codeVerifier\"');\n parameters.set('code_verifier', codeVerifier);\n }\n return tokenEndpointRequest(as, client, clientAuthentication, 'authorization_code', parameters, options);\n}\nconst jwtClaimNames = {\n aud: 'audience',\n c_hash: 'code hash',\n client_id: 'client id',\n exp: 'expiration time',\n iat: 'issued at',\n iss: 'issuer',\n jti: 'jwt id',\n nonce: 'nonce',\n s_hash: 'state hash',\n sub: 'subject',\n ath: 'access token hash',\n htm: 'http method',\n htu: 'http uri',\n cnf: 'confirmation',\n auth_time: 'authentication time',\n};\nfunction validatePresence(required, result) {\n for (const claim of required) {\n if (result.claims[claim] === undefined) {\n throw OPE(`JWT \"${claim}\" (${jwtClaimNames[claim]}) claim missing`, INVALID_RESPONSE, {\n claims: result.claims,\n });\n }\n }\n return result;\n}\nfunction validateStringClaim(claim, result) {\n if (typeof result.claims[claim] !== 'string') {\n throw OPE(`unexpected JWT \"${claim}\" (${jwtClaimNames[claim]}) claim type`, INVALID_RESPONSE, {\n claims: result.claims,\n });\n }\n return result;\n}\nfunction validateIdTokenClaims(as, client, idToken, requiredClaims, decryptFn) {\n return validateJwt(idToken, checkSigningAlgorithm.bind(undefined, client.id_token_signed_response_alg, as.id_token_signing_alg_values_supported, 'RS256'), getClockSkew(client), getClockTolerance(client), decryptFn)\n .then(validatePresence.bind(undefined, ['aud', 'exp', 'iat', 'iss', 'sub', ...requiredClaims]))\n .then(validateIssuer.bind(undefined, as))\n .then(validateAudience.bind(undefined, client.client_id))\n .then(validateStringClaim.bind(undefined, 'sub'));\n}\nfunction resolveIdTokenMaxAge(client, maxAge) {\n if (maxAge === skipAuthTimeCheck) {\n return maxAge;\n }\n const fromClient = maxAge === undefined;\n if (fromClient) {\n maxAge = client.default_max_age;\n }\n if (maxAge === undefined) {\n return skipAuthTimeCheck;\n }\n assertNumber(maxAge, true, fromClient ? '\"client.default_max_age\"' : '\"maxAge\" argument');\n return maxAge;\n}\nfunction validateIdTokenAuthTimeClaim(claims) {\n if (claims.auth_time !== undefined) {\n assertNumber(claims.auth_time, true, 'ID Token \"auth_time\" (authentication time)', INVALID_RESPONSE, { claims });\n }\n}\nfunction validateIdTokenAuthTime(client, claims, maxAge) {\n if (maxAge === skipAuthTimeCheck) {\n return;\n }\n const now = epochTime() + getClockSkew(client);\n const tolerance = getClockTolerance(client);\n if (claims.auth_time + maxAge < now - tolerance) {\n throw OPE('too much time has elapsed since the last End-User authentication', JWT_TIMESTAMP_CHECK, { claims, now, tolerance, claim: 'auth_time' });\n }\n}\nfunction validateIdTokenNonce(claims, expectedNonce) {\n const expected = expectedNonce === expectNoNonce ? undefined : expectedNonce;\n if (claims.nonce !== expected) {\n throw OPE('unexpected ID Token \"nonce\" claim value', JWT_CLAIM_COMPARISON, {\n expected,\n claims,\n claim: 'nonce',\n });\n }\n}\nfunction validateIdTokenAuthorizedParty(client, claims) {\n if (Array.isArray(claims.aud) && claims.aud.length !== 1) {\n if (claims.azp === undefined) {\n throw OPE('ID Token \"aud\" (audience) claim includes additional untrusted audiences', JWT_CLAIM_COMPARISON, { claims, claim: 'aud' });\n }\n if (claims.azp !== client.client_id) {\n throw OPE('unexpected ID Token \"azp\" (authorized party) claim value', JWT_CLAIM_COMPARISON, {\n expected: client.client_id,\n claims,\n claim: 'azp',\n });\n }\n }\n}\nexport const expectNoNonce = Symbol();\nexport const skipAuthTimeCheck = Symbol();\nexport async function processAuthorizationCodeResponse(as, client, response, options) {\n if (typeof options?.expectedNonce === 'string' ||\n typeof options?.maxAge === 'number' ||\n options?.requireIdToken) {\n return processAuthorizationCodeOpenIDResponse(as, client, response, options.expectedNonce, options.maxAge, options[jweDecrypt], options.recognizedTokenTypes);\n }\n return processAuthorizationCodeOAuth2Response(as, client, response, options?.maxAge, options?.[jweDecrypt], options?.recognizedTokenTypes);\n}\nasync function processAuthorizationCodeOpenIDResponse(as, client, response, expectedNonce, maxAge, decryptFn, recognizedTokenTypes) {\n const additionalRequiredClaims = [];\n switch (expectedNonce) {\n case undefined:\n expectedNonce = expectNoNonce;\n break;\n case expectNoNonce:\n break;\n default:\n assertString(expectedNonce, '\"expectedNonce\" argument');\n additionalRequiredClaims.push('nonce');\n }\n maxAge = resolveIdTokenMaxAge(client, maxAge);\n if (maxAge !== skipAuthTimeCheck) {\n additionalRequiredClaims.push('auth_time');\n }\n const result = await processGenericAccessTokenResponse(as, client, response, additionalRequiredClaims, decryptFn, recognizedTokenTypes);\n assertString(result.id_token, '\"response\" body \"id_token\" property', INVALID_RESPONSE, {\n body: result,\n });\n const claims = getValidatedIdTokenClaims(result);\n validateIdTokenAuthTime(client, claims, maxAge);\n validateIdTokenNonce(claims, expectedNonce);\n return result;\n}\nasync function processAuthorizationCodeOAuth2Response(as, client, response, maxAge, decryptFn, recognizedTokenTypes) {\n const result = await processGenericAccessTokenResponse(as, client, response, undefined, decryptFn, recognizedTokenTypes);\n const claims = getValidatedIdTokenClaims(result);\n if (claims) {\n validateIdTokenAuthTime(client, claims, resolveIdTokenMaxAge(client, maxAge));\n validateIdTokenNonce(claims, expectNoNonce);\n }\n return result;\n}\nexport const WWW_AUTHENTICATE_CHALLENGE = 'OAUTH_WWW_AUTHENTICATE_CHALLENGE';\nexport const RESPONSE_BODY_ERROR = 'OAUTH_RESPONSE_BODY_ERROR';\nexport const UNSUPPORTED_OPERATION = 'OAUTH_UNSUPPORTED_OPERATION';\nexport const AUTHORIZATION_RESPONSE_ERROR = 'OAUTH_AUTHORIZATION_RESPONSE_ERROR';\nexport const JWT_USERINFO_EXPECTED = 'OAUTH_JWT_USERINFO_EXPECTED';\nexport const PARSE_ERROR = 'OAUTH_PARSE_ERROR';\nexport const INVALID_RESPONSE = 'OAUTH_INVALID_RESPONSE';\nexport const INVALID_REQUEST = 'OAUTH_INVALID_REQUEST';\nexport const RESPONSE_IS_NOT_JSON = 'OAUTH_RESPONSE_IS_NOT_JSON';\nexport const RESPONSE_IS_NOT_CONFORM = 'OAUTH_RESPONSE_IS_NOT_CONFORM';\nexport const HTTP_REQUEST_FORBIDDEN = 'OAUTH_HTTP_REQUEST_FORBIDDEN';\nexport const REQUEST_PROTOCOL_FORBIDDEN = 'OAUTH_REQUEST_PROTOCOL_FORBIDDEN';\nexport const JWT_TIMESTAMP_CHECK = 'OAUTH_JWT_TIMESTAMP_CHECK_FAILED';\nexport const JWT_CLAIM_COMPARISON = 'OAUTH_JWT_CLAIM_COMPARISON_FAILED';\nexport const JSON_ATTRIBUTE_COMPARISON = 'OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED';\nexport const KEY_SELECTION = 'OAUTH_KEY_SELECTION_FAILED';\nexport const MISSING_SERVER_METADATA = 'OAUTH_MISSING_SERVER_METADATA';\nexport const INVALID_SERVER_METADATA = 'OAUTH_INVALID_SERVER_METADATA';\nfunction checkJwtType(expected, result) {\n if (typeof result.header.typ !== 'string' || normalizeTyp(result.header.typ) !== expected) {\n throw OPE('unexpected JWT \"typ\" header parameter value', INVALID_RESPONSE, {\n header: result.header,\n });\n }\n return result;\n}\nexport async function clientCredentialsGrantRequest(as, client, clientAuthentication, parameters, options) {\n assertAs(as);\n assertClient(client);\n return tokenEndpointRequest(as, client, clientAuthentication, 'client_credentials', new URLSearchParams(parameters), options);\n}\nexport async function genericTokenEndpointRequest(as, client, clientAuthentication, grantType, parameters, options) {\n assertAs(as);\n assertClient(client);\n assertString(grantType, '\"grantType\"');\n return tokenEndpointRequest(as, client, clientAuthentication, grantType, new URLSearchParams(parameters), options);\n}\nexport async function processGenericTokenEndpointResponse(as, client, response, options) {\n return processGenericAccessTokenResponse(as, client, response, undefined, options?.[jweDecrypt], options?.recognizedTokenTypes);\n}\nexport async function processClientCredentialsResponse(as, client, response, options) {\n return processGenericAccessTokenResponse(as, client, response, undefined, options?.[jweDecrypt], options?.recognizedTokenTypes);\n}\nexport async function revocationRequest(as, client, clientAuthentication, token, options) {\n assertAs(as);\n assertClient(client);\n assertString(token, '\"token\"');\n const url = resolveEndpoint(as, 'revocation_endpoint', client.use_mtls_endpoint_aliases, options?.[allowInsecureRequests] !== true);\n const body = new URLSearchParams(options?.additionalParameters);\n body.set('token', token);\n const headers = prepareHeaders(options?.headers);\n headers.delete('accept');\n return authenticatedRequest(as, client, clientAuthentication, url, body, headers, options);\n}\nexport async function processRevocationResponse(response) {\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n await checkOAuthBodyError(response, 200, 'Revocation Endpoint');\n return undefined;\n}\nfunction assertReadableResponse(response) {\n if (response.bodyUsed) {\n throw CodedTypeError('\"response\" body has been used already', ERR_INVALID_ARG_VALUE);\n }\n}\nexport async function introspectionRequest(as, client, clientAuthentication, token, options) {\n assertAs(as);\n assertClient(client);\n assertString(token, '\"token\"');\n const url = resolveEndpoint(as, 'introspection_endpoint', client.use_mtls_endpoint_aliases, options?.[allowInsecureRequests] !== true);\n const body = new URLSearchParams(options?.additionalParameters);\n body.set('token', token);\n const headers = prepareHeaders(options?.headers);\n if (options?.requestJwtResponse ?? client.introspection_signed_response_alg) {\n headers.set('accept', 'application/token-introspection+jwt');\n }\n else {\n headers.set('accept', 'application/json');\n }\n return authenticatedRequest(as, client, clientAuthentication, url, body, headers, options);\n}\nexport async function processIntrospectionResponse(as, client, response, options) {\n assertAs(as);\n assertClient(client);\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n await checkOAuthBodyError(response, 200, 'Introspection Endpoint');\n let json;\n if (getContentType(response) === 'application/token-introspection+jwt') {\n assertReadableResponse(response);\n const { claims, jwt } = await validateJwt(await response.text(), checkSigningAlgorithm.bind(undefined, client.introspection_signed_response_alg, as.introspection_signing_alg_values_supported, 'RS256'), getClockSkew(client), getClockTolerance(client), options?.[jweDecrypt])\n .then(checkJwtType.bind(undefined, 'token-introspection+jwt'))\n .then(validatePresence.bind(undefined, ['aud', 'iat', 'iss']))\n .then(validateIssuer.bind(undefined, as))\n .then(validateAudience.bind(undefined, client.client_id));\n jwtRefs.set(response, jwt);\n if (!isJsonObject(claims.token_introspection)) {\n throw OPE('JWT \"token_introspection\" claim must be a JSON object', INVALID_RESPONSE, {\n claims,\n });\n }\n json = claims.token_introspection;\n }\n else {\n assertReadableResponse(response);\n json = await getResponseJsonBody(response);\n }\n if (typeof json.active !== 'boolean') {\n throw OPE('\"response\" body \"active\" property must be a boolean', INVALID_RESPONSE, {\n body: json,\n });\n }\n return json;\n}\nasync function jwksRequest(as, options) {\n assertAs(as);\n const url = resolveEndpoint(as, 'jwks_uri', false, options?.[allowInsecureRequests] !== true);\n const headers = prepareHeaders(options?.headers);\n headers.set('accept', 'application/json');\n headers.append('accept', 'application/jwk-set+json');\n const requestHeaders = Object.fromEntries(headers.entries());\n const headersKey = JSON.stringify(requestHeaders);\n const fetcher = options?.[customFetch] || fetch;\n const requestSignal = signal(url, options?.signal);\n jwksRequests ||= new WeakMap();\n const requests = jwksRequests.get(as) ?? new Set();\n for (const pending of requests) {\n if (pending.url === url.href &&\n pending.headers === headersKey &&\n pending.fetch === fetcher &&\n pending.signal === requestSignal) {\n return pending.promise;\n }\n }\n const pending = {\n url: url.href,\n headers: headersKey,\n fetch: fetcher,\n signal: requestSignal,\n promise: Promise.resolve()\n .then(() => fetcher(url.href, {\n body: undefined,\n headers: requestHeaders,\n method: 'GET',\n redirect: 'manual',\n signal: requestSignal,\n }))\n .then(processJwksResponse)\n .then((jwks) => {\n const uat = epochTime();\n setJwksCache(as, jwks, uat);\n return { jwks, uat };\n })\n .finally(() => {\n requests.delete(pending);\n if (!requests.size) {\n jwksRequests.delete(as);\n }\n }),\n };\n requests.add(pending);\n jwksRequests.set(as, requests);\n return pending.promise;\n}\nasync function processJwksResponse(response) {\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n if (response.status !== 200) {\n throw OPE('\"response\" is not a conform JSON Web Key Set response (unexpected HTTP status code)', RESPONSE_IS_NOT_CONFORM, response);\n }\n assertReadableResponse(response);\n const json = await getResponseJsonBody(response, (response) => assertContentTypes(response, 'application/json', 'application/jwk-set+json'));\n if (!Array.isArray(json.keys)) {\n throw OPE('\"response\" body \"keys\" property must be an array', INVALID_RESPONSE, { body: json });\n }\n if (!Array.prototype.every.call(json.keys, isJsonObject)) {\n throw OPE('\"response\" body \"keys\" property members must be JWK formatted objects', INVALID_RESPONSE, { body: json });\n }\n return json;\n}\nfunction supported(alg) {\n switch (alg) {\n case 'PS256':\n case 'ES256':\n case 'RS256':\n case 'PS384':\n case 'ES384':\n case 'RS384':\n case 'PS512':\n case 'ES512':\n case 'RS512':\n case 'Ed25519':\n case 'EdDSA':\n case 'ML-DSA-44':\n case 'ML-DSA-65':\n case 'ML-DSA-87':\n return true;\n default:\n return false;\n }\n}\nfunction checkSupportedJwsAlg(header) {\n if (!supported(header.alg)) {\n throw new UnsupportedOperationError('unsupported JWS \"alg\" identifier', {\n cause: { alg: header.alg },\n });\n }\n}\nfunction checkRsaKeyAlgorithm(key) {\n const { algorithm } = key;\n if (typeof algorithm.modulusLength !== 'number' || algorithm.modulusLength < 2048) {\n throw new UnsupportedOperationError(`unsupported ${algorithm.name} modulusLength`, {\n cause: key,\n });\n }\n}\nfunction ecdsaHashName(key) {\n const { algorithm } = key;\n switch (algorithm.namedCurve) {\n case 'P-256':\n return 'SHA-256';\n case 'P-384':\n return 'SHA-384';\n case 'P-521':\n return 'SHA-512';\n default:\n throw new UnsupportedOperationError('unsupported ECDSA namedCurve', { cause: key });\n }\n}\nfunction keyToSubtle(key) {\n switch (key.algorithm.name) {\n case 'ECDSA':\n return {\n name: key.algorithm.name,\n hash: ecdsaHashName(key),\n };\n case 'RSA-PSS': {\n checkRsaKeyAlgorithm(key);\n switch (key.algorithm.hash.name) {\n case 'SHA-256':\n case 'SHA-384':\n case 'SHA-512':\n return {\n name: key.algorithm.name,\n saltLength: parseInt(key.algorithm.hash.name.slice(-3), 10) >> 3,\n };\n default:\n throw new UnsupportedOperationError('unsupported RSA-PSS hash name', { cause: key });\n }\n }\n case 'RSASSA-PKCS1-v1_5':\n checkRsaKeyAlgorithm(key);\n return key.algorithm.name;\n case 'ML-DSA-44':\n case 'ML-DSA-65':\n case 'ML-DSA-87':\n case 'Ed25519':\n return key.algorithm.name;\n }\n throw new UnsupportedOperationError('unsupported CryptoKey algorithm name', { cause: key });\n}\nasync function validateJwsSignature(protectedHeader, payload, key, signature) {\n const data = buf(`${protectedHeader}.${payload}`);\n const algorithm = keyToSubtle(key);\n const verified = await crypto.subtle.verify(algorithm, key, signature, data);\n if (!verified) {\n throw OPE('JWT signature verification failed', INVALID_RESPONSE, {\n key,\n data,\n signature,\n algorithm,\n });\n }\n}\nasync function validateJwt(jws, checkAlg, clockSkew, clockTolerance, decryptJwt) {\n let { 0: protectedHeader, 1: payload, length } = jws.split('.');\n if (length === 5) {\n if (decryptJwt !== undefined) {\n jws = await decryptJwt(jws);\n ({ 0: protectedHeader, 1: payload, length } = jws.split('.'));\n }\n else {\n throw new UnsupportedOperationError('JWE decryption is not configured', { cause: jws });\n }\n }\n if (length !== 3) {\n throw OPE('Invalid JWT', INVALID_RESPONSE, jws);\n }\n let header;\n try {\n header = JSON.parse(buf(b64u(protectedHeader)));\n }\n catch (cause) {\n throw OPE('failed to parse JWT Header body as base64url encoded JSON', PARSE_ERROR, cause);\n }\n if (!isJsonObject(header)) {\n throw OPE('JWT Header must be a top level object', INVALID_RESPONSE, jws);\n }\n checkAlg(header);\n if (header.crit !== undefined) {\n throw new UnsupportedOperationError('no JWT \"crit\" header parameter extensions are supported', {\n cause: { header },\n });\n }\n let claims;\n try {\n claims = JSON.parse(buf(b64u(payload)));\n }\n catch (cause) {\n throw OPE('failed to parse JWT Payload body as base64url encoded JSON', PARSE_ERROR, cause);\n }\n if (!isJsonObject(claims)) {\n throw OPE('JWT Payload must be a top level object', INVALID_RESPONSE, jws);\n }\n const now = epochTime() + clockSkew;\n if (claims.exp !== undefined) {\n if (typeof claims.exp !== 'number') {\n throw OPE('unexpected JWT \"exp\" (expiration time) claim type', INVALID_RESPONSE, { claims });\n }\n if (claims.exp <= now - clockTolerance) {\n throw OPE('unexpected JWT \"exp\" (expiration time) claim value, expiration is past current timestamp', JWT_TIMESTAMP_CHECK, { claims, now, tolerance: clockTolerance, claim: 'exp' });\n }\n }\n if (claims.iat !== undefined) {\n if (typeof claims.iat !== 'number') {\n throw OPE('unexpected JWT \"iat\" (issued at) claim type', INVALID_RESPONSE, { claims });\n }\n }\n if (claims.iss !== undefined) {\n if (typeof claims.iss !== 'string') {\n throw OPE('unexpected JWT \"iss\" (issuer) claim type', INVALID_RESPONSE, { claims });\n }\n }\n if (claims.nbf !== undefined) {\n if (typeof claims.nbf !== 'number') {\n throw OPE('unexpected JWT \"nbf\" (not before) claim type', INVALID_RESPONSE, { claims });\n }\n if (claims.nbf > now + clockTolerance) {\n throw OPE('unexpected JWT \"nbf\" (not before) claim value', JWT_TIMESTAMP_CHECK, {\n claims,\n now,\n tolerance: clockTolerance,\n claim: 'nbf',\n });\n }\n }\n if (claims.aud !== undefined) {\n if (typeof claims.aud !== 'string' && !Array.isArray(claims.aud)) {\n throw OPE('unexpected JWT \"aud\" (audience) claim type', INVALID_RESPONSE, { claims });\n }\n }\n return { header, claims, jwt: jws };\n}\nexport async function validateJwtAuthResponse(as, client, parameters, expectedState, options) {\n assertAs(as);\n assertClient(client);\n if (parameters instanceof URL) {\n parameters = parameters.searchParams;\n }\n if (!(parameters instanceof URLSearchParams)) {\n throw CodedTypeError('\"parameters\" must be an instance of URLSearchParams, or URL', ERR_INVALID_ARG_TYPE);\n }\n const response = getURLSearchParameter(parameters, 'response');\n if (!response) {\n throw OPE('\"parameters\" does not contain a JARM response', INVALID_RESPONSE);\n }\n const { claims, header, jwt } = await validateJwt(response, checkSigningAlgorithm.bind(undefined, client.authorization_signed_response_alg, as.authorization_signing_alg_values_supported, 'RS256'), getClockSkew(client), getClockTolerance(client), options?.[jweDecrypt])\n .then(validatePresence.bind(undefined, ['aud', 'exp', 'iss']))\n .then(validateIssuer.bind(undefined, as))\n .then(validateAudience.bind(undefined, client.client_id));\n const { 0: protectedHeader, 1: payload, 2: encodedSignature } = jwt.split('.');\n const signature = b64u(encodedSignature);\n const key = await getPublicSigKeyFromIssuerJwksUri(as, options, header);\n await validateJwsSignature(protectedHeader, payload, key, signature);\n const result = new URLSearchParams();\n for (const [key, value] of Object.entries(claims)) {\n if (typeof value === 'string' && key !== 'aud') {\n result.set(key, value);\n }\n }\n return validateAuthResponse(as, client, result, expectedState);\n}\nasync function idTokenHash(data, header, claimName) {\n let algorithm;\n switch (header.alg) {\n case 'RS256':\n case 'PS256':\n case 'ES256':\n algorithm = 'SHA-256';\n break;\n case 'RS384':\n case 'PS384':\n case 'ES384':\n algorithm = 'SHA-384';\n break;\n case 'RS512':\n case 'PS512':\n case 'ES512':\n case 'Ed25519':\n case 'EdDSA':\n algorithm = 'SHA-512';\n break;\n case 'ML-DSA-44':\n case 'ML-DSA-65':\n case 'ML-DSA-87':\n algorithm = { name: 'cSHAKE256', length: 512, outputLength: 512 };\n break;\n default:\n throw new UnsupportedOperationError(`unsupported JWS algorithm for ${claimName} calculation`, { cause: { alg: header.alg } });\n }\n const digest = await crypto.subtle.digest(algorithm, buf(data));\n return b64u(digest.slice(0, digest.byteLength / 2));\n}\nasync function idTokenHashMatches(data, actual, header, claimName) {\n const expected = await idTokenHash(data, header, claimName);\n return actual === expected;\n}\nexport async function validateDetachedSignatureResponse(as, client, parameters, expectedNonce, expectedState, maxAge, options) {\n return validateHybridResponse(as, client, parameters, expectedNonce, expectedState, maxAge, options, true);\n}\nexport async function validateCodeIdTokenResponse(as, client, parameters, expectedNonce, expectedState, maxAge, options) {\n return validateHybridResponse(as, client, parameters, expectedNonce, expectedState, maxAge, options, false);\n}\nasync function consumeStream(request) {\n if (request.bodyUsed) {\n throw CodedTypeError('form_post Request instances must contain a readable body', ERR_INVALID_ARG_VALUE, { cause: request });\n }\n return request.text();\n}\nexport async function formPostResponse(request) {\n if (request.method !== 'POST') {\n throw CodedTypeError('form_post responses are expected to use the POST method', ERR_INVALID_ARG_VALUE, { cause: request });\n }\n if (getContentType(request) !== 'application/x-www-form-urlencoded') {\n throw CodedTypeError('form_post responses are expected to use the application/x-www-form-urlencoded content-type', ERR_INVALID_ARG_VALUE, { cause: request });\n }\n return consumeStream(request);\n}\nasync function validateHybridResponse(as, client, parameters, expectedNonce, expectedState, maxAge, options, fapi) {\n assertAs(as);\n assertClient(client);\n if (parameters instanceof URL) {\n if (!parameters.hash.length) {\n throw CodedTypeError('\"parameters\" as an instance of URL must contain a hash (fragment) with the Authorization Response parameters', ERR_INVALID_ARG_VALUE);\n }\n parameters = new URLSearchParams(parameters.hash.slice(1));\n }\n else if (looseInstanceOf(parameters, Request)) {\n parameters = new URLSearchParams(await formPostResponse(parameters));\n }\n else if (parameters instanceof URLSearchParams) {\n parameters = new URLSearchParams(parameters);\n }\n else {\n throw CodedTypeError('\"parameters\" must be an instance of URLSearchParams, URL, or Response', ERR_INVALID_ARG_TYPE);\n }\n const id_token = getURLSearchParameter(parameters, 'id_token');\n parameters.delete('id_token');\n switch (expectedState) {\n case undefined:\n case expectNoState:\n break;\n default:\n assertString(expectedState, '\"expectedState\" argument');\n }\n const result = validateAuthResponse({\n ...as,\n authorization_response_iss_parameter_supported: false,\n }, client, parameters, expectedState);\n if (!id_token) {\n throw OPE('\"parameters\" does not contain an ID Token', INVALID_RESPONSE);\n }\n const code = getURLSearchParameter(parameters, 'code');\n if (!code) {\n throw OPE('\"parameters\" does not contain an Authorization Code', INVALID_RESPONSE);\n }\n const requiredClaims = ['nonce', 'c_hash'];\n const state = parameters.get('state');\n if (fapi && (typeof expectedState === 'string' || state !== null)) {\n requiredClaims.push('s_hash');\n }\n maxAge = resolveIdTokenMaxAge(client, maxAge);\n if (client.require_auth_time || maxAge !== skipAuthTimeCheck) {\n requiredClaims.push('auth_time');\n }\n const { claims, header, jwt } = await validateIdTokenClaims(as, client, id_token, requiredClaims, options?.[jweDecrypt]);\n const clockSkew = getClockSkew(client);\n const now = epochTime() + clockSkew;\n if (claims.iat < now - 3600) {\n throw OPE('unexpected JWT \"iat\" (issued at) claim value, it is too far in the past', JWT_TIMESTAMP_CHECK, { now, claims, claim: 'iat' });\n }\n assertString(claims.c_hash, 'ID Token \"c_hash\" (code hash) claim value', INVALID_RESPONSE, {\n claims,\n });\n validateIdTokenAuthTimeClaim(claims);\n validateIdTokenAuthTime(client, claims, maxAge);\n assertString(expectedNonce, '\"expectedNonce\" argument');\n validateIdTokenNonce(claims, expectedNonce);\n validateIdTokenAuthorizedParty(client, claims);\n const { 0: protectedHeader, 1: payload, 2: encodedSignature } = jwt.split('.');\n const signature = b64u(encodedSignature);\n const key = await getPublicSigKeyFromIssuerJwksUri(as, options, header);\n await validateJwsSignature(protectedHeader, payload, key, signature);\n if ((await idTokenHashMatches(code, claims.c_hash, header, 'c_hash')) !== true) {\n throw OPE('invalid ID Token \"c_hash\" (code hash) claim value', JWT_CLAIM_COMPARISON, {\n code,\n alg: header.alg,\n claim: 'c_hash',\n claims,\n });\n }\n if ((fapi && state !== null) || claims.s_hash !== undefined) {\n assertString(claims.s_hash, 'ID Token \"s_hash\" (state hash) claim value', INVALID_RESPONSE, {\n claims,\n });\n assertString(state, '\"state\" response parameter', INVALID_RESPONSE, { parameters });\n if ((await idTokenHashMatches(state, claims.s_hash, header, 's_hash')) !== true) {\n throw OPE('invalid ID Token \"s_hash\" (state hash) claim value', JWT_CLAIM_COMPARISON, {\n state,\n alg: header.alg,\n claim: 's_hash',\n claims,\n });\n }\n }\n return result;\n}\nfunction checkSigningAlgorithm(client, issuer, fallback, header) {\n if (client !== undefined) {\n if (typeof client === 'string' ? header.alg !== client : !client.includes(header.alg)) {\n throw OPE('unexpected JWT \"alg\" header parameter', INVALID_RESPONSE, {\n header,\n expected: client,\n reason: 'client configuration',\n });\n }\n return;\n }\n if (Array.isArray(issuer)) {\n if (!issuer.includes(header.alg)) {\n throw OPE('unexpected JWT \"alg\" header parameter', INVALID_RESPONSE, {\n header,\n expected: issuer,\n reason: 'authorization server metadata',\n });\n }\n return;\n }\n if (fallback !== undefined) {\n if (typeof fallback === 'string'\n ? header.alg !== fallback\n : typeof fallback === 'function'\n ? !fallback(header.alg)\n : !fallback.includes(header.alg)) {\n throw OPE('unexpected JWT \"alg\" header parameter', INVALID_RESPONSE, {\n header,\n expected: fallback,\n reason: 'default value',\n });\n }\n return;\n }\n throw OPE('missing client or server configuration to verify used JWT \"alg\" header parameter', undefined, { client, issuer, fallback });\n}\nfunction getURLSearchParameter(parameters, name) {\n const { 0: value, length } = parameters.getAll(name);\n if (length > 1) {\n throw OPE(`\"${name}\" parameter must be provided only once`, INVALID_RESPONSE);\n }\n return value;\n}\nexport const skipStateCheck = Symbol();\nexport const expectNoState = Symbol();\nexport function validateAuthResponse(as, client, parameters, expectedState) {\n assertAs(as);\n assertClient(client);\n if (parameters instanceof URL) {\n parameters = parameters.searchParams;\n }\n if (!(parameters instanceof URLSearchParams)) {\n throw CodedTypeError('\"parameters\" must be an instance of URLSearchParams, or URL', ERR_INVALID_ARG_TYPE);\n }\n if (getURLSearchParameter(parameters, 'response')) {\n throw OPE('\"parameters\" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()', INVALID_RESPONSE, { parameters });\n }\n const iss = getURLSearchParameter(parameters, 'iss');\n const state = getURLSearchParameter(parameters, 'state');\n if (!iss && as.authorization_response_iss_parameter_supported) {\n throw OPE('response parameter \"iss\" (issuer) missing', INVALID_RESPONSE, { parameters });\n }\n if (iss && iss !== as.issuer) {\n throw OPE('unexpected \"iss\" (issuer) response parameter value', INVALID_RESPONSE, {\n expected: as.issuer,\n parameters,\n });\n }\n switch (expectedState) {\n case undefined:\n case expectNoState:\n if (state !== undefined) {\n throw OPE('unexpected \"state\" response parameter encountered', INVALID_RESPONSE, {\n expected: undefined,\n parameters,\n });\n }\n break;\n case skipStateCheck:\n break;\n default:\n assertString(expectedState, '\"expectedState\" argument');\n if (state !== expectedState) {\n throw OPE(state === undefined\n ? 'response parameter \"state\" missing'\n : 'unexpected \"state\" response parameter value', INVALID_RESPONSE, { expected: expectedState, parameters });\n }\n }\n const error = getURLSearchParameter(parameters, 'error');\n if (error) {\n throw new AuthorizationResponseError('authorization response from the server is an error', {\n cause: parameters,\n });\n }\n const id_token = getURLSearchParameter(parameters, 'id_token');\n const token = getURLSearchParameter(parameters, 'token');\n if (id_token !== undefined || token !== undefined) {\n throw new UnsupportedOperationError('implicit and hybrid flows are not supported');\n }\n return brand(new URLSearchParams(parameters));\n}\nfunction algToSubtle(alg) {\n switch (alg) {\n case 'PS256':\n case 'PS384':\n case 'PS512':\n return { name: 'RSA-PSS', hash: `SHA-${alg.slice(-3)}` };\n case 'RS256':\n case 'RS384':\n case 'RS512':\n return { name: 'RSASSA-PKCS1-v1_5', hash: `SHA-${alg.slice(-3)}` };\n case 'ES256':\n case 'ES384':\n return { name: 'ECDSA', namedCurve: `P-${alg.slice(-3)}` };\n case 'ES512':\n return { name: 'ECDSA', namedCurve: 'P-521' };\n case 'EdDSA':\n return 'Ed25519';\n case 'Ed25519':\n case 'ML-DSA-44':\n case 'ML-DSA-65':\n case 'ML-DSA-87':\n return alg;\n default:\n throw new UnsupportedOperationError('unsupported JWS algorithm', { cause: { alg } });\n }\n}\nasync function importJwk(alg, jwk) {\n const { ext, key_ops, use, ...key } = jwk;\n return crypto.subtle.importKey('jwk', key, algToSubtle(alg), true, ['verify']);\n}\nexport async function deviceAuthorizationRequest(as, client, clientAuthentication, parameters, options) {\n assertAs(as);\n assertClient(client);\n const url = resolveEndpoint(as, 'device_authorization_endpoint', client.use_mtls_endpoint_aliases, options?.[allowInsecureRequests] !== true);\n const body = new URLSearchParams(parameters);\n body.set('client_id', client.client_id);\n const headers = prepareHeaders(options?.headers);\n headers.set('accept', 'application/json');\n return authenticatedRequest(as, client, clientAuthentication, url, body, headers, options);\n}\nexport async function processDeviceAuthorizationResponse(as, client, response) {\n assertAs(as);\n assertClient(client);\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n await checkOAuthBodyError(response, 200, 'Device Authorization Endpoint');\n assertReadableResponse(response);\n const json = await getResponseJsonBody(response);\n assertString(json.device_code, '\"response\" body \"device_code\" property', INVALID_RESPONSE, {\n body: json,\n });\n assertString(json.user_code, '\"response\" body \"user_code\" property', INVALID_RESPONSE, {\n body: json,\n });\n assertString(json.verification_uri, '\"response\" body \"verification_uri\" property', INVALID_RESPONSE, { body: json });\n let expiresIn = typeof json.expires_in !== 'number' ? parseFloat(json.expires_in) : json.expires_in;\n assertNumber(expiresIn, true, '\"response\" body \"expires_in\" property', INVALID_RESPONSE, {\n body: json,\n });\n json.expires_in = expiresIn;\n if (json.verification_uri_complete !== undefined) {\n assertString(json.verification_uri_complete, '\"response\" body \"verification_uri_complete\" property', INVALID_RESPONSE, { body: json });\n }\n if (json.interval !== undefined) {\n assertNumber(json.interval, false, '\"response\" body \"interval\" property', INVALID_RESPONSE, {\n body: json,\n });\n }\n return json;\n}\nexport async function deviceCodeGrantRequest(as, client, clientAuthentication, deviceCode, options) {\n assertAs(as);\n assertClient(client);\n assertString(deviceCode, '\"deviceCode\"');\n const parameters = new URLSearchParams(options?.additionalParameters);\n parameters.set('device_code', deviceCode);\n return tokenEndpointRequest(as, client, clientAuthentication, 'urn:ietf:params:oauth:grant-type:device_code', parameters, options);\n}\nexport async function processDeviceCodeResponse(as, client, response, options) {\n return processGenericAccessTokenResponse(as, client, response, undefined, options?.[jweDecrypt], options?.recognizedTokenTypes);\n}\nexport async function generateKeyPair(alg, options) {\n assertString(alg, '\"alg\"');\n const algorithm = algToSubtle(alg);\n if (alg.startsWith('PS') || alg.startsWith('RS')) {\n Object.assign(algorithm, {\n modulusLength: options?.modulusLength ?? 2048,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]),\n });\n }\n return crypto.subtle.generateKey(algorithm, options?.extractable ?? false, [\n 'sign',\n 'verify',\n ]);\n}\nfunction normalizeHtu(htu) {\n const url = new URL(htu);\n url.search = '';\n url.hash = '';\n return url.href;\n}\nasync function validateDPoP(request, accessToken, accessTokenClaims, options) {\n const headerValue = request.headers.get('dpop');\n if (headerValue === null) {\n throw OPE('operation indicated DPoP use but the request has no DPoP HTTP Header', INVALID_REQUEST, { headers: request.headers });\n }\n if (request.headers.get('authorization')?.toLowerCase().startsWith('dpop ') === false) {\n throw OPE(`operation indicated DPoP use but the request's Authorization HTTP Header scheme is not DPoP`, INVALID_REQUEST, { headers: request.headers });\n }\n if (typeof accessTokenClaims.cnf?.jkt !== 'string') {\n throw OPE('operation indicated DPoP use but the JWT Access Token has no jkt confirmation claim', INVALID_REQUEST, { claims: accessTokenClaims });\n }\n const clockSkew = getClockSkew(options);\n const proof = await validateJwt(headerValue, checkSigningAlgorithm.bind(undefined, options?.signingAlgorithms, undefined, supported), clockSkew, getClockTolerance(options), undefined)\n .then(checkJwtType.bind(undefined, 'dpop+jwt'))\n .then(validatePresence.bind(undefined, ['iat', 'jti', 'ath', 'htm', 'htu']))\n .then(validateStringClaim.bind(undefined, 'jti'));\n const now = epochTime() + clockSkew;\n const diff = Math.abs(now - proof.claims.iat);\n if (diff > 300) {\n throw OPE('DPoP Proof iat is not recent enough', JWT_TIMESTAMP_CHECK, {\n now,\n claims: proof.claims,\n claim: 'iat',\n });\n }\n if (proof.claims.htm !== request.method) {\n throw OPE('DPoP Proof htm mismatch', JWT_CLAIM_COMPARISON, {\n expected: request.method,\n claims: proof.claims,\n claim: 'htm',\n });\n }\n if (typeof proof.claims.htu !== 'string' ||\n normalizeHtu(proof.claims.htu) !== normalizeHtu(request.url)) {\n throw OPE('DPoP Proof htu mismatch', JWT_CLAIM_COMPARISON, {\n expected: normalizeHtu(request.url),\n claims: proof.claims,\n claim: 'htu',\n });\n }\n {\n const expected = b64u(await crypto.subtle.digest('SHA-256', buf(accessToken)));\n if (proof.claims.ath !== expected) {\n throw OPE('DPoP Proof ath mismatch', JWT_CLAIM_COMPARISON, {\n expected,\n claims: proof.claims,\n claim: 'ath',\n });\n }\n }\n const { jwk, alg } = proof.header;\n if (!isJsonObject(jwk)) {\n throw OPE('DPoP Proof jwk header parameter must be a JSON object', INVALID_REQUEST, {\n header: proof.header,\n });\n }\n {\n const expected = await calculateJwkThumbprint(jwk);\n if (accessTokenClaims.cnf.jkt !== expected) {\n throw OPE('JWT Access Token confirmation mismatch', JWT_CLAIM_COMPARISON, {\n expected,\n claims: accessTokenClaims,\n claim: 'cnf.jkt',\n });\n }\n }\n const { 0: protectedHeader, 1: payload, 2: encodedSignature } = headerValue.split('.');\n const signature = b64u(encodedSignature);\n const key = await importJwk(alg, jwk);\n if (key.type !== 'public') {\n throw OPE('DPoP Proof jwk header parameter must contain a public key', INVALID_REQUEST, {\n header: proof.header,\n });\n }\n await validateJwsSignature(protectedHeader, payload, key, signature);\n}\nexport async function validateJwtAccessToken(as, request, expectedAudience, options) {\n assertAs(as);\n if (!looseInstanceOf(request, Request)) {\n throw CodedTypeError('\"request\" must be an instance of Request', ERR_INVALID_ARG_TYPE);\n }\n assertString(expectedAudience, '\"expectedAudience\"');\n const authorization = request.headers.get('authorization');\n if (authorization === null) {\n throw OPE('\"request\" is missing an Authorization HTTP Header', INVALID_REQUEST, {\n headers: request.headers,\n });\n }\n let { 0: scheme, 1: accessToken, length } = authorization.split(/ +/);\n scheme = scheme.toLowerCase();\n switch (scheme) {\n case 'dpop':\n case 'bearer':\n break;\n default:\n throw new UnsupportedOperationError('unsupported Authorization HTTP Header scheme', {\n cause: { headers: request.headers },\n });\n }\n if (length !== 2) {\n throw OPE('invalid Authorization HTTP Header format', INVALID_REQUEST, {\n headers: request.headers,\n });\n }\n const requiredClaims = [\n 'iss',\n 'exp',\n 'aud',\n 'sub',\n 'iat',\n 'jti',\n 'client_id',\n ];\n if (options?.requireDPoP || scheme === 'dpop' || request.headers.has('dpop')) {\n requiredClaims.push('cnf');\n }\n const { claims, header } = await validateJwt(accessToken, checkSigningAlgorithm.bind(undefined, options?.signingAlgorithms, undefined, supported), getClockSkew(options), getClockTolerance(options), undefined)\n .then(checkJwtType.bind(undefined, 'at+jwt'))\n .then(validatePresence.bind(undefined, requiredClaims))\n .then(validateIssuer.bind(undefined, as))\n .then(validateAudience.bind(undefined, expectedAudience))\n .catch(reassignRSCode);\n for (const claim of ['client_id', 'jti', 'sub']) {\n if (typeof claims[claim] !== 'string') {\n throw OPE(`unexpected JWT \"${claim}\" claim type`, INVALID_REQUEST, { claims });\n }\n }\n if ('cnf' in claims) {\n if (!isJsonObject(claims.cnf)) {\n throw OPE('unexpected JWT \"cnf\" (confirmation) claim value', INVALID_REQUEST, { claims });\n }\n const { 0: cnf, length } = Object.keys(claims.cnf);\n if (length) {\n if (length !== 1) {\n throw new UnsupportedOperationError('multiple confirmation claims are not supported', {\n cause: { claims },\n });\n }\n if (cnf !== 'jkt') {\n throw new UnsupportedOperationError('unsupported JWT Confirmation method', {\n cause: { claims },\n });\n }\n }\n }\n const { 0: protectedHeader, 1: payload, 2: encodedSignature } = accessToken.split('.');\n const signature = b64u(encodedSignature);\n const key = await getPublicSigKeyFromIssuerJwksUri(as, options, header);\n await validateJwsSignature(protectedHeader, payload, key, signature);\n if (options?.requireDPoP ||\n scheme === 'dpop' ||\n claims.cnf?.jkt !== undefined ||\n request.headers.has('dpop')) {\n await validateDPoP(request, accessToken, claims, options).catch(reassignRSCode);\n }\n return claims;\n}\nfunction reassignRSCode(err) {\n if (err instanceof OperationProcessingError && err?.code === INVALID_REQUEST) {\n err.code = INVALID_RESPONSE;\n }\n throw err;\n}\nexport async function backchannelAuthenticationRequest(as, client, clientAuthentication, parameters, options) {\n assertAs(as);\n assertClient(client);\n const url = resolveEndpoint(as, 'backchannel_authentication_endpoint', client.use_mtls_endpoint_aliases, options?.[allowInsecureRequests] !== true);\n const body = new URLSearchParams(parameters);\n body.set('client_id', client.client_id);\n const headers = prepareHeaders(options?.headers);\n headers.set('accept', 'application/json');\n return authenticatedRequest(as, client, clientAuthentication, url, body, headers, options);\n}\nexport async function processBackchannelAuthenticationResponse(as, client, response) {\n assertAs(as);\n assertClient(client);\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n await checkOAuthBodyError(response, 200, 'Backchannel Authentication Endpoint');\n assertReadableResponse(response);\n const json = await getResponseJsonBody(response);\n assertString(json.auth_req_id, '\"response\" body \"auth_req_id\" property', INVALID_RESPONSE, {\n body: json,\n });\n let expiresIn = typeof json.expires_in !== 'number' ? parseFloat(json.expires_in) : json.expires_in;\n assertNumber(expiresIn, true, '\"response\" body \"expires_in\" property', INVALID_RESPONSE, {\n body: json,\n });\n json.expires_in = expiresIn;\n if (json.interval !== undefined) {\n assertNumber(json.interval, false, '\"response\" body \"interval\" property', INVALID_RESPONSE, {\n body: json,\n });\n }\n return json;\n}\nexport async function backchannelAuthenticationGrantRequest(as, client, clientAuthentication, authReqId, options) {\n assertAs(as);\n assertClient(client);\n assertString(authReqId, '\"authReqId\"');\n const parameters = new URLSearchParams(options?.additionalParameters);\n parameters.set('auth_req_id', authReqId);\n return tokenEndpointRequest(as, client, clientAuthentication, 'urn:openid:params:grant-type:ciba', parameters, options);\n}\nexport async function processBackchannelAuthenticationGrantResponse(as, client, response, options) {\n return processGenericAccessTokenResponse(as, client, response, undefined, options?.[jweDecrypt], options?.recognizedTokenTypes);\n}\nexport async function dynamicClientRegistrationRequest(as, metadata, options) {\n assertAs(as);\n const url = resolveEndpoint(as, 'registration_endpoint', metadata.use_mtls_endpoint_aliases, options?.[allowInsecureRequests] !== true);\n const headers = prepareHeaders(options?.headers);\n headers.set('accept', 'application/json');\n headers.set('content-type', 'application/json');\n const method = 'POST';\n if (options?.DPoP) {\n assertDPoP(options.DPoP);\n await options.DPoP.addProof(url, headers, method, options.initialAccessToken);\n }\n if (options?.initialAccessToken) {\n headers.set('authorization', `${headers.has('dpop') ? 'DPoP' : 'Bearer'} ${options.initialAccessToken}`);\n }\n const response = await (options?.[customFetch] || fetch)(url.href, {\n body: JSON.stringify(metadata),\n headers: Object.fromEntries(headers.entries()),\n method,\n redirect: 'manual',\n signal: signal(url, options?.signal),\n });\n options?.DPoP?.cacheNonce(response, url);\n return response;\n}\nexport async function processDynamicClientRegistrationResponse(response) {\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n await checkOAuthBodyError(response, 201, 'Dynamic Client Registration Endpoint');\n assertReadableResponse(response);\n const json = await getResponseJsonBody(response);\n assertString(json.client_id, '\"response\" body \"client_id\" property', INVALID_RESPONSE, {\n body: json,\n });\n if (json.client_secret !== undefined) {\n assertString(json.client_secret, '\"response\" body \"client_secret\" property', INVALID_RESPONSE, {\n body: json,\n });\n }\n if (json.client_secret) {\n assertNumber(json.client_secret_expires_at, true, '\"response\" body \"client_secret_expires_at\" property', INVALID_RESPONSE, {\n body: json,\n });\n }\n return json;\n}\nexport async function resourceDiscoveryRequest(resourceIdentifier, options) {\n return performDiscovery(resourceIdentifier, 'resourceIdentifier', (url) => {\n prependWellKnown(url, '.well-known/oauth-protected-resource', true);\n return url;\n }, options);\n}\nexport async function processResourceDiscoveryResponse(expectedResourceIdentifier, response) {\n const expected = expectedResourceIdentifier;\n if (!(expected instanceof URL) && expected !== _nodiscoverycheck) {\n throw CodedTypeError('\"expectedResourceIdentifier\" must be an instance of URL', ERR_INVALID_ARG_TYPE);\n }\n if (!looseInstanceOf(response, Response)) {\n throw CodedTypeError('\"response\" must be an instance of Response', ERR_INVALID_ARG_TYPE);\n }\n if (response.status !== 200) {\n throw OPE('\"response\" is not a conform Resource Server Metadata response (unexpected HTTP status code)', RESPONSE_IS_NOT_CONFORM, response);\n }\n assertReadableResponse(response);\n const json = await getResponseJsonBody(response);\n assertString(json.resource, '\"response\" body \"resource\" property', INVALID_RESPONSE, {\n body: json,\n });\n if (expected !== _nodiscoverycheck && new URL(json.resource).href !== expected.href) {\n throw OPE('\"response\" body \"resource\" property does not match the expected value', JSON_ATTRIBUTE_COMPARISON, { expected: expected.href, body: json, attribute: 'resource' });\n }\n return json;\n}\nasync function getResponseJsonBody(response, check = assertApplicationJson) {\n let json;\n try {\n json = await response.json();\n }\n catch (cause) {\n check(response);\n throw OPE('failed to parse \"response\" body as JSON', PARSE_ERROR, cause);\n }\n if (!isJsonObject(json)) {\n throw OPE('\"response\" body must be a top level object', INVALID_RESPONSE, { body: json });\n }\n return json;\n}\nexport const _nopkce = nopkce;\nexport const _nodiscoverycheck = Symbol();\nexport const _expectedIssuer = Symbol();\n//# sourceMappingURL=index.js.map",
6
+ "import * as oauth from 'oauth4webapi';\nimport { compactDecrypt } from 'jose/jwe/compact/decrypt';\nimport { JOSEError } from 'jose/errors';\nlet headers;\nlet USER_AGENT;\nif (typeof navigator === 'undefined' || !navigator.userAgent?.startsWith?.('Mozilla/5.0 ')) {\n const NAME = 'openid-client';\n const VERSION = 'v6.8.4';\n USER_AGENT = `${NAME}/${VERSION}`;\n headers = { 'user-agent': USER_AGENT };\n}\nconst int = (config) => {\n return props.get(config);\n};\nlet props;\nexport { AuthorizationResponseError, ResponseBodyError, WWWAuthenticateChallengeError, } from 'oauth4webapi';\nlet tbi;\nexport function ClientSecretPost(clientSecret) {\n if (clientSecret !== undefined) {\n return oauth.ClientSecretPost(clientSecret);\n }\n tbi ||= new WeakMap();\n return (as, client, body, headers) => {\n let auth;\n if (!(auth = tbi.get(client))) {\n assertString(client.client_secret, '\"metadata.client_secret\"');\n auth = oauth.ClientSecretPost(client.client_secret);\n tbi.set(client, auth);\n }\n return auth(as, client, body, headers);\n };\n}\nfunction assertString(input, it) {\n if (typeof input !== 'string') {\n throw CodedTypeError(`${it} must be a string`, ERR_INVALID_ARG_TYPE);\n }\n if (input.length === 0) {\n throw CodedTypeError(`${it} must not be empty`, ERR_INVALID_ARG_VALUE);\n }\n}\nexport function ClientSecretBasic(clientSecret) {\n if (clientSecret !== undefined) {\n return oauth.ClientSecretBasic(clientSecret);\n }\n tbi ||= new WeakMap();\n return (as, client, body, headers) => {\n let auth;\n if (!(auth = tbi.get(client))) {\n assertString(client.client_secret, '\"metadata.client_secret\"');\n auth = oauth.ClientSecretBasic(client.client_secret);\n tbi.set(client, auth);\n }\n return auth(as, client, body, headers);\n };\n}\nexport function ClientSecretJwt(clientSecret, options) {\n if (clientSecret !== undefined) {\n return oauth.ClientSecretJwt(clientSecret, options);\n }\n tbi ||= new WeakMap();\n return (as, client, body, headers) => {\n let auth;\n if (!(auth = tbi.get(client))) {\n assertString(client.client_secret, '\"metadata.client_secret\"');\n auth = oauth.ClientSecretJwt(client.client_secret, options);\n tbi.set(client, auth);\n }\n return auth(as, client, body, headers);\n };\n}\nexport function None() {\n return oauth.None();\n}\nexport function PrivateKeyJwt(clientPrivateKey, options) {\n return oauth.PrivateKeyJwt(clientPrivateKey, options);\n}\nexport function TlsClientAuth() {\n return oauth.TlsClientAuth();\n}\nexport const skipStateCheck = oauth.skipStateCheck;\nexport const skipSubjectCheck = oauth.skipSubjectCheck;\nexport const customFetch = oauth.customFetch;\nexport const modifyAssertion = oauth.modifyAssertion;\nexport const clockSkew = oauth.clockSkew;\nexport const clockTolerance = oauth.clockTolerance;\nconst ERR_INVALID_ARG_VALUE = 'ERR_INVALID_ARG_VALUE';\nconst ERR_INVALID_ARG_TYPE = 'ERR_INVALID_ARG_TYPE';\nfunction CodedTypeError(message, code, cause) {\n const err = new TypeError(message, { cause });\n Object.assign(err, { code });\n return err;\n}\nexport function calculatePKCECodeChallenge(codeVerifier) {\n return oauth.calculatePKCECodeChallenge(codeVerifier);\n}\nexport function randomPKCECodeVerifier() {\n return oauth.generateRandomCodeVerifier();\n}\nexport function randomNonce() {\n return oauth.generateRandomNonce();\n}\nexport function randomState() {\n return oauth.generateRandomState();\n}\nexport class ClientError extends Error {\n code;\n constructor(message, options) {\n super(message, options);\n this.name = this.constructor.name;\n this.code = options?.code;\n Error.captureStackTrace?.(this, this.constructor);\n }\n}\nconst decoder = new TextDecoder();\nfunction e(msg, cause, code) {\n return new ClientError(msg, { cause, code });\n}\nfunction errorHandler(err) {\n if (err instanceof TypeError ||\n err instanceof ClientError ||\n err instanceof oauth.ResponseBodyError ||\n err instanceof oauth.AuthorizationResponseError ||\n err instanceof oauth.WWWAuthenticateChallengeError) {\n throw err;\n }\n if (err instanceof oauth.OperationProcessingError) {\n switch (err.code) {\n case oauth.HTTP_REQUEST_FORBIDDEN:\n throw e('only requests to HTTPS are allowed', err, err.code);\n case oauth.REQUEST_PROTOCOL_FORBIDDEN:\n throw e('only requests to HTTP or HTTPS are allowed', err, err.code);\n case oauth.RESPONSE_IS_NOT_CONFORM:\n throw e('unexpected HTTP response status code', err.cause, err.code);\n case oauth.RESPONSE_IS_NOT_JSON:\n throw e('unexpected response content-type', err.cause, err.code);\n case oauth.PARSE_ERROR:\n throw e('parsing error occured', err, err.code);\n case oauth.INVALID_RESPONSE:\n throw e('invalid response encountered', err, err.code);\n case oauth.JWT_CLAIM_COMPARISON:\n throw e('unexpected JWT claim value encountered', err, err.code);\n case oauth.JSON_ATTRIBUTE_COMPARISON:\n throw e('unexpected JSON attribute value encountered', err, err.code);\n case oauth.JWT_TIMESTAMP_CHECK:\n throw e('JWT timestamp claim value failed validation', err, err.code);\n default:\n throw e(err.message, err, err.code);\n }\n }\n if (err instanceof oauth.UnsupportedOperationError) {\n throw e('unsupported operation', err, err.code);\n }\n if (err instanceof DOMException) {\n switch (err.name) {\n case 'OperationError':\n throw e('runtime operation error', err, oauth.UNSUPPORTED_OPERATION);\n case 'NotSupportedError':\n throw e('runtime unsupported operation', err, oauth.UNSUPPORTED_OPERATION);\n case 'TimeoutError':\n throw e('operation timed out', err, 'OAUTH_TIMEOUT');\n case 'AbortError':\n throw e('operation aborted', err, 'OAUTH_ABORT');\n }\n }\n throw new ClientError('something went wrong', { cause: err });\n}\nexport function randomDPoPKeyPair(alg, options) {\n return oauth\n .generateKeyPair(alg ?? 'ES256', {\n extractable: options?.extractable,\n })\n .catch(errorHandler);\n}\nfunction handleEntraId(server, as, options) {\n if (server.origin === 'https://login.microsoftonline.com' &&\n (!options?.algorithm || options.algorithm === 'oidc')) {\n as[kEntraId] = true;\n return true;\n }\n return false;\n}\nfunction handleB2Clogin(server, options) {\n if (server.hostname.endsWith('.b2clogin.com') &&\n (!options?.algorithm || options.algorithm === 'oidc')) {\n return true;\n }\n return false;\n}\nexport async function dynamicClientRegistration(server, metadata, clientAuthentication, options) {\n let as;\n if (options?.flag === retry) {\n as = options.as;\n }\n else {\n as = await performDiscovery(server, options);\n }\n const clockSkew = metadata[oauth.clockSkew] ?? 0;\n const clockTolerance = metadata[oauth.clockTolerance] ?? 30;\n metadata = structuredClone(metadata);\n const timeout = options?.timeout ?? 30;\n const signal = AbortSignal.timeout(timeout * 1000);\n let registered;\n try {\n registered = await oauth\n .dynamicClientRegistrationRequest(as, metadata, {\n initialAccessToken: options?.initialAccessToken,\n DPoP: options?.DPoP,\n headers: new Headers(headers),\n [oauth.customFetch]: options?.[customFetch],\n [oauth.allowInsecureRequests]: options?.execute?.includes(allowInsecureRequests),\n signal,\n })\n .then(oauth.processDynamicClientRegistrationResponse);\n }\n catch (err) {\n if (retryable(err, options)) {\n return dynamicClientRegistration(server, metadata, clientAuthentication, {\n ...options,\n flag: retry,\n as,\n });\n }\n errorHandler(err);\n }\n registered[oauth.clockSkew] = clockSkew;\n registered[oauth.clockTolerance] = clockTolerance;\n const instance = new Configuration(as, registered.client_id, registered, clientAuthentication);\n let internals = int(instance);\n if (options?.[customFetch]) {\n internals.fetch = options[customFetch];\n }\n if (options?.timeout) {\n internals.timeout = options.timeout;\n }\n if (options?.execute) {\n for (const extension of options.execute) {\n extension(instance);\n }\n }\n return instance;\n}\nexport async function discovery(server, clientId, metadata, clientAuthentication, options) {\n const as = await performDiscovery(server, options);\n const instance = new Configuration(as, clientId, metadata, clientAuthentication);\n let internals = int(instance);\n if (options?.[customFetch]) {\n internals.fetch = options[customFetch];\n }\n if (options?.timeout) {\n internals.timeout = options.timeout;\n }\n if (options?.execute) {\n for (const extension of options.execute) {\n extension(instance);\n }\n }\n return instance;\n}\nasync function performDiscovery(server, options) {\n if (!(server instanceof URL)) {\n throw CodedTypeError('\"server\" must be an instance of URL', ERR_INVALID_ARG_TYPE);\n }\n const resolve = !server.href.includes('/.well-known/');\n const timeout = options?.timeout ?? 30;\n const signal = AbortSignal.timeout(timeout * 1000);\n const as = await (resolve\n ? oauth.discoveryRequest(server, {\n algorithm: options?.algorithm,\n [oauth.customFetch]: options?.[customFetch],\n [oauth.allowInsecureRequests]: options?.execute?.includes(allowInsecureRequests),\n signal,\n headers: new Headers(headers),\n })\n : (options?.[customFetch] || fetch)((() => {\n oauth.checkProtocol(server, options?.execute?.includes(allowInsecureRequests) ? false : true);\n return server.href;\n })(), {\n headers: Object.fromEntries(new Headers({ accept: 'application/json', ...headers }).entries()),\n body: undefined,\n method: 'GET',\n redirect: 'manual',\n signal,\n }))\n .then((response) => oauth.processDiscoveryResponse(oauth._nodiscoverycheck, response))\n .catch(errorHandler);\n if (resolve && new URL(as.issuer).href !== server.href) {\n handleEntraId(server, as, options) ||\n handleB2Clogin(server, options) ||\n (() => {\n throw new ClientError('discovered metadata issuer does not match the expected issuer', {\n code: oauth.JSON_ATTRIBUTE_COMPARISON,\n cause: {\n expected: server.href,\n body: as,\n attribute: 'issuer',\n },\n });\n })();\n }\n return as;\n}\nfunction isRsaOaep(input) {\n return input.name === 'RSA-OAEP';\n}\nfunction isEcdh(input) {\n return input.name === 'ECDH';\n}\nconst ecdhEs = 'ECDH-ES';\nconst ecdhEsA128Kw = 'ECDH-ES+A128KW';\nconst ecdhEsA192Kw = 'ECDH-ES+A192KW';\nconst ecdhEsA256Kw = 'ECDH-ES+A256KW';\nfunction checkEcdhAlg(algs, alg, pk) {\n switch (alg) {\n case undefined:\n algs.add(ecdhEs);\n algs.add(ecdhEsA128Kw);\n algs.add(ecdhEsA192Kw);\n algs.add(ecdhEsA256Kw);\n break;\n case ecdhEs:\n case ecdhEsA128Kw:\n case ecdhEsA192Kw:\n case ecdhEsA256Kw:\n algs.add(alg);\n break;\n default:\n throw CodedTypeError('invalid key alg', ERR_INVALID_ARG_VALUE, { pk });\n }\n}\nexport function enableDecryptingResponses(config, contentEncryptionAlgorithms = [\n 'A128GCM',\n 'A192GCM',\n 'A256GCM',\n 'A128CBC-HS256',\n 'A192CBC-HS384',\n 'A256CBC-HS512',\n], ...keys) {\n if (int(config).decrypt !== undefined) {\n throw new TypeError('enableDecryptingResponses can only be called on a given Configuration instance once');\n }\n if (keys.length === 0) {\n throw CodedTypeError('no keys were provided', ERR_INVALID_ARG_VALUE);\n }\n const algs = new Set();\n const normalized = [];\n for (const pk of keys) {\n let key;\n if ('key' in pk) {\n key = { key: pk.key };\n if (typeof pk.alg === 'string')\n key.alg = pk.alg;\n if (typeof pk.kid === 'string')\n key.kid = pk.kid;\n }\n else {\n key = { key: pk };\n }\n if (key.key.type !== 'private') {\n throw CodedTypeError('only private keys must be provided', ERR_INVALID_ARG_VALUE);\n }\n if (isRsaOaep(key.key.algorithm)) {\n switch (key.key.algorithm.hash.name) {\n case 'SHA-1':\n case 'SHA-256':\n case 'SHA-384':\n case 'SHA-512': {\n let alg = 'RSA-OAEP';\n let sha;\n if ((sha = parseInt(key.key.algorithm.hash.name.slice(-3), 10))) {\n alg = `${alg}-${sha}`;\n }\n key.alg ||= alg;\n if (alg !== key.alg)\n throw CodedTypeError('invalid key alg', ERR_INVALID_ARG_VALUE, {\n pk,\n });\n algs.add(key.alg);\n break;\n }\n default:\n throw CodedTypeError('only SHA-512, SHA-384, SHA-256, and SHA-1 RSA-OAEP keys are supported', ERR_INVALID_ARG_VALUE);\n }\n }\n else if (isEcdh(key.key.algorithm)) {\n if (key.key.algorithm.namedCurve !== 'P-256') {\n throw CodedTypeError('Only P-256 ECDH keys are supported', ERR_INVALID_ARG_VALUE);\n }\n checkEcdhAlg(algs, key.alg, pk);\n }\n else if (key.key.algorithm.name === 'X25519') {\n checkEcdhAlg(algs, key.alg, pk);\n }\n else {\n throw CodedTypeError('only RSA-OAEP, ECDH, or X25519 keys are supported', ERR_INVALID_ARG_VALUE);\n }\n normalized.push(key);\n }\n int(config).decrypt = async (jwe) => decrypt(normalized, jwe, contentEncryptionAlgorithms, [...algs]).catch(errorHandler);\n}\nfunction checkCryptoKey(key, alg, epk) {\n if (alg.startsWith('RSA-OAEP')) {\n return key.algorithm.name === 'RSA-OAEP';\n }\n if (alg.startsWith('ECDH-ES')) {\n if (key.algorithm.name !== 'ECDH' && key.algorithm.name !== 'X25519') {\n return false;\n }\n if (key.algorithm.name === 'ECDH') {\n return epk?.crv === key.algorithm.namedCurve;\n }\n if (key.algorithm.name === 'X25519') {\n return epk?.crv === 'X25519';\n }\n }\n return false;\n}\nfunction selectCryptoKeyForDecryption(keys, alg, kid, epk) {\n const { 0: key, length } = keys.filter((key) => {\n if (kid !== key.kid) {\n return false;\n }\n if (key.alg && alg !== key.alg) {\n return false;\n }\n return checkCryptoKey(key.key, alg, epk);\n });\n if (!key) {\n throw e('no applicable decryption key selected', undefined, 'OAUTH_DECRYPTION_FAILED');\n }\n if (length !== 1) {\n throw e('multiple applicable decryption keys selected', undefined, 'OAUTH_DECRYPTION_FAILED');\n }\n return key.key;\n}\nasync function decrypt(keys, jwe, contentEncryptionAlgorithms, keyManagementAlgorithms) {\n return decoder.decode((await compactDecrypt(jwe, (header) => {\n const { kid, alg, epk } = header;\n return selectCryptoKeyForDecryption(keys, alg, kid, epk);\n }, { keyManagementAlgorithms, contentEncryptionAlgorithms }).catch((err) => {\n if (err instanceof JOSEError) {\n throw e('decryption failed', err, 'OAUTH_DECRYPTION_FAILED');\n }\n errorHandler(err);\n })).plaintext);\n}\nfunction getServerHelpers(metadata) {\n return {\n supportsPKCE: {\n __proto__: null,\n value(method = 'S256') {\n return (metadata.code_challenge_methods_supported?.includes(method) === true);\n },\n },\n };\n}\nfunction addServerHelpers(metadata) {\n Object.defineProperties(metadata, getServerHelpers(metadata));\n}\nconst kEntraId = Symbol();\nexport class Configuration {\n constructor(server, clientId, metadata, clientAuthentication) {\n if (typeof clientId !== 'string' || !clientId.length) {\n throw CodedTypeError('\"clientId\" must be a non-empty string', ERR_INVALID_ARG_TYPE);\n }\n if (typeof metadata === 'string') {\n metadata = { client_secret: metadata };\n }\n if (metadata?.client_id !== undefined && clientId !== metadata.client_id) {\n throw CodedTypeError('\"clientId\" and \"metadata.client_id\" must be the same', ERR_INVALID_ARG_VALUE);\n }\n const client = {\n ...structuredClone(metadata),\n client_id: clientId,\n };\n client[oauth.clockSkew] = metadata?.[oauth.clockSkew] ?? 0;\n client[oauth.clockTolerance] = metadata?.[oauth.clockTolerance] ?? 30;\n let auth;\n if (clientAuthentication) {\n auth = clientAuthentication;\n }\n else {\n if (typeof client.client_secret === 'string' &&\n client.client_secret.length) {\n auth = ClientSecretPost(client.client_secret);\n }\n else {\n auth = None();\n }\n }\n let c = Object.freeze(client);\n const clone = structuredClone(server);\n if (kEntraId in server) {\n clone[oauth._expectedIssuer] = ({ claims: { tid } }) => server.issuer.replace('{tenantid}', tid);\n }\n let as = Object.freeze(clone);\n props ||= new WeakMap();\n props.set(this, {\n __proto__: null,\n as,\n c,\n auth,\n tlsOnly: true,\n jwksCache: {},\n });\n }\n serverMetadata() {\n const metadata = structuredClone(int(this).as);\n addServerHelpers(metadata);\n return metadata;\n }\n clientMetadata() {\n const metadata = structuredClone(int(this).c);\n return metadata;\n }\n get timeout() {\n return int(this).timeout;\n }\n set timeout(value) {\n int(this).timeout = value;\n }\n get [customFetch]() {\n return int(this).fetch;\n }\n set [customFetch](value) {\n int(this).fetch = value;\n }\n}\nObject.freeze(Configuration.prototype);\nfunction getHelpers(response) {\n let exp = undefined;\n if (response.expires_in !== undefined) {\n const now = new Date();\n now.setSeconds(now.getSeconds() + response.expires_in);\n exp = now.getTime();\n }\n return {\n expiresIn: {\n __proto__: null,\n value() {\n if (exp) {\n const now = Date.now();\n if (exp > now) {\n return Math.floor((exp - now) / 1000);\n }\n return 0;\n }\n return undefined;\n },\n },\n claims: {\n __proto__: null,\n value() {\n try {\n return oauth.getValidatedIdTokenClaims(this);\n }\n catch {\n return undefined;\n }\n },\n },\n };\n}\nfunction addHelpers(response) {\n Object.defineProperties(response, getHelpers(response));\n}\nexport function getDPoPHandle(config, keyPair, options) {\n checkConfig(config);\n return oauth.DPoP(int(config).c, keyPair, options);\n}\nasync function handleRetryAfter(response, currentInterval, signal, throwIfInvalid = false) {\n const retryAfter = response.headers.get('retry-after')?.trim();\n if (retryAfter === undefined)\n return;\n let delaySeconds;\n if (/^\\d+$/.test(retryAfter)) {\n delaySeconds = parseInt(retryAfter, 10);\n }\n else {\n const retryDate = new Date(retryAfter);\n if (Number.isFinite(retryDate.getTime())) {\n const now = new Date();\n const delayMs = retryDate.getTime() - now.getTime();\n if (delayMs > 0) {\n delaySeconds = Math.ceil(delayMs / 1000);\n }\n }\n }\n if (throwIfInvalid && !Number.isFinite(delaySeconds)) {\n throw new oauth.OperationProcessingError('invalid Retry-After header value', { cause: response });\n }\n if (delaySeconds > currentInterval) {\n await wait(delaySeconds - currentInterval, signal);\n }\n}\nfunction wait(duration, signal) {\n return new Promise((resolve, reject) => {\n const waitStep = (remaining) => {\n try {\n signal.throwIfAborted();\n }\n catch (err) {\n reject(err);\n return;\n }\n if (remaining <= 0) {\n resolve();\n return;\n }\n const currentWait = Math.min(remaining, 5);\n setTimeout(() => waitStep(remaining - currentWait), currentWait * 1000);\n };\n waitStep(duration);\n });\n}\nfunction pollRequestSignal(pollingSignal, timeout) {\n const timeoutSignal = signal(timeout);\n if (!timeoutSignal) {\n return {\n signal: pollingSignal,\n cleanup() { },\n };\n }\n const controller = new AbortController();\n const abort = (event) => {\n const source = event.target;\n controller.abort(source.reason);\n };\n if (pollingSignal.aborted) {\n controller.abort(pollingSignal.reason);\n }\n else if (timeoutSignal.aborted) {\n controller.abort(timeoutSignal.reason);\n }\n else {\n pollingSignal.addEventListener('abort', abort, { once: true });\n timeoutSignal.addEventListener('abort', abort, { once: true });\n }\n return {\n signal: controller.signal,\n cleanup() {\n pollingSignal.removeEventListener('abort', abort);\n timeoutSignal.removeEventListener('abort', abort);\n },\n };\n}\nexport async function pollDeviceAuthorizationGrant(config, deviceAuthorizationResponse, parameters, options) {\n checkConfig(config);\n parameters = new URLSearchParams(parameters);\n let interval = deviceAuthorizationResponse.interval ?? 5;\n const pollingSignal = options?.signal ??\n AbortSignal.timeout(deviceAuthorizationResponse.expires_in * 1000);\n try {\n await wait(interval, pollingSignal);\n }\n catch (err) {\n errorHandler(err);\n }\n const { as, c, auth, fetch, tlsOnly, nonRepudiation, timeout, decrypt } = int(config);\n const retryPoll = (updatedInterval, flag) => pollDeviceAuthorizationGrant(config, {\n ...deviceAuthorizationResponse,\n interval: updatedInterval,\n }, parameters, {\n ...options,\n signal: pollingSignal,\n flag,\n });\n const requestSignal = pollRequestSignal(pollingSignal, timeout);\n const response = await oauth\n .deviceCodeGrantRequest(as, c, auth, deviceAuthorizationResponse.device_code, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n additionalParameters: parameters,\n DPoP: options?.DPoP,\n headers: new Headers(headers),\n signal: requestSignal.signal,\n })\n .catch(errorHandler)\n .finally(requestSignal.cleanup);\n if (response.status === 503 && response.headers.has('retry-after')) {\n await handleRetryAfter(response, interval, pollingSignal, true);\n await response.body?.cancel();\n return retryPoll(interval);\n }\n const p = oauth.processDeviceCodeResponse(as, c, response, {\n [oauth.jweDecrypt]: decrypt,\n });\n let result;\n try {\n result = await p;\n }\n catch (err) {\n if (retryable(err, options)) {\n return retryPoll(interval, retry);\n }\n if (err instanceof oauth.ResponseBodyError) {\n switch (err.error) {\n case 'slow_down':\n interval += 5;\n case 'authorization_pending':\n await handleRetryAfter(err.response, interval, pollingSignal);\n return retryPoll(interval);\n }\n }\n errorHandler(err);\n }\n result.id_token && (await nonRepudiation?.(response));\n addHelpers(result);\n return result;\n}\nexport async function initiateDeviceAuthorization(config, parameters) {\n checkConfig(config);\n const { as, c, auth, fetch, tlsOnly, timeout } = int(config);\n return oauth\n .deviceAuthorizationRequest(as, c, auth, parameters, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n headers: new Headers(headers),\n signal: signal(timeout),\n })\n .then((response) => oauth.processDeviceAuthorizationResponse(as, c, response))\n .catch(errorHandler);\n}\nexport async function initiateBackchannelAuthentication(config, parameters) {\n checkConfig(config);\n const { as, c, auth, fetch, tlsOnly, timeout } = int(config);\n return oauth\n .backchannelAuthenticationRequest(as, c, auth, parameters, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n headers: new Headers(headers),\n signal: signal(timeout),\n })\n .then((response) => oauth.processBackchannelAuthenticationResponse(as, c, response))\n .catch(errorHandler);\n}\nexport async function pollBackchannelAuthenticationGrant(config, backchannelAuthenticationResponse, parameters, options) {\n checkConfig(config);\n parameters = new URLSearchParams(parameters);\n let interval = backchannelAuthenticationResponse.interval ?? 5;\n const pollingSignal = options?.signal ??\n AbortSignal.timeout(backchannelAuthenticationResponse.expires_in * 1000);\n try {\n await wait(interval, pollingSignal);\n }\n catch (err) {\n errorHandler(err);\n }\n const { as, c, auth, fetch, tlsOnly, nonRepudiation, timeout, decrypt } = int(config);\n const retryPoll = (updatedInterval, flag) => pollBackchannelAuthenticationGrant(config, {\n ...backchannelAuthenticationResponse,\n interval: updatedInterval,\n }, parameters, {\n ...options,\n signal: pollingSignal,\n flag,\n });\n const requestSignal = pollRequestSignal(pollingSignal, timeout);\n const response = await oauth\n .backchannelAuthenticationGrantRequest(as, c, auth, backchannelAuthenticationResponse.auth_req_id, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n additionalParameters: parameters,\n DPoP: options?.DPoP,\n headers: new Headers(headers),\n signal: requestSignal.signal,\n })\n .catch(errorHandler)\n .finally(requestSignal.cleanup);\n if (response.status === 503 && response.headers.has('retry-after')) {\n await handleRetryAfter(response, interval, pollingSignal, true);\n await response.body?.cancel();\n return retryPoll(interval);\n }\n const p = oauth.processBackchannelAuthenticationGrantResponse(as, c, response, {\n [oauth.jweDecrypt]: decrypt,\n });\n let result;\n try {\n result = await p;\n }\n catch (err) {\n if (retryable(err, options)) {\n return retryPoll(interval, retry);\n }\n if (err instanceof oauth.ResponseBodyError) {\n switch (err.error) {\n case 'slow_down':\n interval += 5;\n case 'authorization_pending':\n await handleRetryAfter(err.response, interval, pollingSignal);\n return retryPoll(interval);\n }\n }\n errorHandler(err);\n }\n result.id_token && (await nonRepudiation?.(response));\n addHelpers(result);\n return result;\n}\nexport function allowInsecureRequests(config) {\n int(config).tlsOnly = false;\n}\nexport function setJwksCache(config, jwksCache) {\n int(config).jwksCache = structuredClone(jwksCache);\n}\nexport function getJwksCache(config) {\n const cache = int(config).jwksCache;\n if (cache.uat) {\n return cache;\n }\n return undefined;\n}\nexport function enableNonRepudiationChecks(config) {\n checkConfig(config);\n int(config).nonRepudiation = (response) => {\n const { as, fetch, tlsOnly, timeout, jwksCache } = int(config);\n return oauth\n .validateApplicationLevelSignature(as, response, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n headers: new Headers(headers),\n signal: signal(timeout),\n [oauth.jwksCache]: jwksCache,\n })\n .catch(errorHandler);\n };\n}\nexport function useJwtResponseMode(config) {\n checkConfig(config);\n const { hybrid, implicit } = int(config);\n if (hybrid || implicit) {\n throw e('JARM cannot be combined with a hybrid or implicit response types', undefined, oauth.UNSUPPORTED_OPERATION);\n }\n int(config).jarm = (authorizationResponse, expectedState) => validateJARMResponse(config, authorizationResponse, expectedState);\n}\nexport function enableDetachedSignatureResponseChecks(config) {\n if (!int(config).hybrid) {\n throw e('\"code id_token\" response type must be configured to be used first', undefined, oauth.UNSUPPORTED_OPERATION);\n }\n int(config).hybrid = (authorizationResponse, expectedNonce, expectedState, maxAge) => validateCodeIdTokenResponse(config, authorizationResponse, expectedNonce, expectedState, maxAge, true);\n}\nexport async function implicitAuthentication(config, currentUrl, expectedNonce, checks) {\n checkConfig(config);\n if (!(currentUrl instanceof URL) &&\n !webInstanceOf(currentUrl, 'Request')) {\n throw CodedTypeError('\"currentUrl\" must be an instance of URL, or Request', ERR_INVALID_ARG_TYPE);\n }\n if (typeof expectedNonce !== 'string') {\n throw CodedTypeError('\"expectedNonce\" must be a string', ERR_INVALID_ARG_TYPE);\n }\n const { as, c, fetch, tlsOnly, timeout, decrypt, implicit, jwksCache } = int(config);\n if (!implicit) {\n throw new TypeError('implicitAuthentication() cannot be used by clients using flows other than response_type=id_token');\n }\n let params;\n if (!(currentUrl instanceof URL)) {\n const request = currentUrl;\n switch (request.method) {\n case 'GET':\n params = new URLSearchParams(new URL(request.url).hash.slice(1));\n break;\n case 'POST':\n params = new URLSearchParams(await oauth.formPostResponse(request));\n break;\n default:\n throw CodedTypeError('unexpected Request HTTP method', ERR_INVALID_ARG_VALUE);\n }\n }\n else {\n params = new URLSearchParams(currentUrl.hash.slice(1));\n }\n try {\n {\n const decoy = new URLSearchParams(params);\n decoy.delete('id_token');\n oauth.validateAuthResponse({\n ...as,\n authorization_response_iss_parameter_supported: undefined,\n }, c, decoy, checks?.expectedState);\n }\n {\n const decoy = new Response(JSON.stringify({\n access_token: 'decoy',\n token_type: 'bearer',\n id_token: params.get('id_token'),\n }), {\n headers: new Headers({ 'content-type': 'application/json' }),\n });\n const ref = await oauth.processAuthorizationCodeResponse(as, c, decoy, {\n expectedNonce,\n maxAge: checks?.maxAge,\n [oauth.jweDecrypt]: decrypt,\n });\n await oauth.validateApplicationLevelSignature(as, decoy, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n headers: new Headers(headers),\n signal: signal(timeout),\n [oauth.jwksCache]: jwksCache,\n });\n return oauth.getValidatedIdTokenClaims(ref);\n }\n }\n catch (err) {\n errorHandler(err);\n }\n}\nexport function useCodeIdTokenResponseType(config) {\n checkConfig(config);\n const { jarm, implicit } = int(config);\n if (jarm || implicit) {\n throw e('\"code id_token\" response type cannot be combined with JARM or implicit response type', undefined, oauth.UNSUPPORTED_OPERATION);\n }\n int(config).hybrid = (authorizationResponse, expectedNonce, expectedState, maxAge) => validateCodeIdTokenResponse(config, authorizationResponse, expectedNonce, expectedState, maxAge, false);\n}\nexport function useIdTokenResponseType(config) {\n checkConfig(config);\n const { jarm, hybrid } = int(config);\n if (jarm || hybrid) {\n throw e('\"id_token\" response type cannot be combined with JARM or hybrid response type', undefined, oauth.UNSUPPORTED_OPERATION);\n }\n int(config).implicit = true;\n}\nfunction stripParams(url) {\n url = new URL(url);\n url.search = '';\n url.hash = '';\n return url.href;\n}\nfunction webInstanceOf(input, toStringTag) {\n try {\n return Object.getPrototypeOf(input)[Symbol.toStringTag] === toStringTag;\n }\n catch {\n return false;\n }\n}\nexport async function authorizationCodeGrant(config, currentUrl, checks, tokenEndpointParameters, options) {\n checkConfig(config);\n if (options?.flag !== retry &&\n !(currentUrl instanceof URL) &&\n !webInstanceOf(currentUrl, 'Request')) {\n throw CodedTypeError('\"currentUrl\" must be an instance of URL, or Request', ERR_INVALID_ARG_TYPE);\n }\n let authResponse;\n let redirectUri;\n const { as, c, auth, fetch, tlsOnly, jarm, hybrid, nonRepudiation, timeout, decrypt, implicit } = int(config);\n if (options?.flag === retry) {\n authResponse = options.authResponse;\n redirectUri = options.redirectUri;\n }\n else {\n if (!(currentUrl instanceof URL)) {\n const request = currentUrl;\n currentUrl = new URL(currentUrl.url);\n switch (request.method) {\n case 'GET':\n break;\n case 'POST':\n const params = new URLSearchParams(await oauth.formPostResponse(request));\n if (hybrid) {\n currentUrl.hash = params.toString();\n }\n else {\n for (const [k, v] of params.entries()) {\n currentUrl.searchParams.append(k, v);\n }\n }\n break;\n default:\n throw CodedTypeError('unexpected Request HTTP method', ERR_INVALID_ARG_VALUE);\n }\n }\n redirectUri = stripParams(currentUrl);\n switch (true) {\n case !!jarm:\n authResponse = await jarm(currentUrl, checks?.expectedState);\n break;\n case !!hybrid:\n authResponse = await hybrid(currentUrl, checks?.expectedNonce, checks?.expectedState, checks?.maxAge);\n break;\n case !!implicit:\n throw new TypeError('authorizationCodeGrant() cannot be used by response_type=id_token clients');\n default:\n try {\n authResponse = oauth.validateAuthResponse(as, c, currentUrl.searchParams, checks?.expectedState);\n }\n catch (err) {\n errorHandler(err);\n }\n }\n }\n const response = await oauth\n .authorizationCodeGrantRequest(as, c, auth, authResponse, redirectUri, checks?.pkceCodeVerifier || oauth.nopkce, {\n additionalParameters: tokenEndpointParameters,\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n DPoP: options?.DPoP,\n headers: new Headers(headers),\n signal: signal(timeout),\n })\n .catch(errorHandler);\n if (typeof checks?.expectedNonce === 'string' ||\n typeof checks?.maxAge === 'number') {\n checks.idTokenExpected = true;\n }\n const p = oauth.processAuthorizationCodeResponse(as, c, response, {\n expectedNonce: checks?.expectedNonce,\n maxAge: checks?.maxAge,\n requireIdToken: checks?.idTokenExpected,\n [oauth.jweDecrypt]: decrypt,\n });\n let result;\n try {\n result = await p;\n }\n catch (err) {\n if (retryable(err, options)) {\n return authorizationCodeGrant(config, undefined, checks, tokenEndpointParameters, {\n ...options,\n flag: retry,\n authResponse: authResponse,\n redirectUri: redirectUri,\n });\n }\n errorHandler(err);\n }\n result.id_token && (await nonRepudiation?.(response));\n addHelpers(result);\n return result;\n}\nasync function validateJARMResponse(config, authorizationResponse, expectedState) {\n const { as, c, fetch, tlsOnly, timeout, decrypt, jwksCache } = int(config);\n return oauth\n .validateJwtAuthResponse(as, c, authorizationResponse, expectedState, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n headers: new Headers(headers),\n signal: signal(timeout),\n [oauth.jweDecrypt]: decrypt,\n [oauth.jwksCache]: jwksCache,\n })\n .catch(errorHandler);\n}\nasync function validateCodeIdTokenResponse(config, authorizationResponse, expectedNonce, expectedState, maxAge, fapi) {\n if (typeof expectedNonce !== 'string') {\n throw CodedTypeError('\"expectedNonce\" must be a string', ERR_INVALID_ARG_TYPE);\n }\n if (expectedState !== undefined && typeof expectedState !== 'string') {\n throw CodedTypeError('\"expectedState\" must be a string', ERR_INVALID_ARG_TYPE);\n }\n const { as, c, fetch, tlsOnly, timeout, decrypt, jwksCache } = int(config);\n return (fapi\n ? oauth.validateDetachedSignatureResponse\n : oauth.validateCodeIdTokenResponse)(as, c, authorizationResponse, expectedNonce, expectedState, maxAge, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n headers: new Headers(headers),\n signal: signal(timeout),\n [oauth.jweDecrypt]: decrypt,\n [oauth.jwksCache]: jwksCache,\n }).catch(errorHandler);\n}\nexport async function refreshTokenGrant(config, refreshToken, parameters, options) {\n checkConfig(config);\n parameters = new URLSearchParams(parameters);\n const { as, c, auth, fetch, tlsOnly, nonRepudiation, timeout, decrypt } = int(config);\n const response = await oauth\n .refreshTokenGrantRequest(as, c, auth, refreshToken, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n additionalParameters: parameters,\n DPoP: options?.DPoP,\n headers: new Headers(headers),\n signal: signal(timeout),\n })\n .catch(errorHandler);\n const p = oauth.processRefreshTokenResponse(as, c, response, {\n [oauth.jweDecrypt]: decrypt,\n });\n let result;\n try {\n result = await p;\n }\n catch (err) {\n if (retryable(err, options)) {\n return refreshTokenGrant(config, refreshToken, parameters, {\n ...options,\n flag: retry,\n });\n }\n errorHandler(err);\n }\n result.id_token && (await nonRepudiation?.(response));\n addHelpers(result);\n return result;\n}\nexport async function clientCredentialsGrant(config, parameters, options) {\n checkConfig(config);\n parameters = new URLSearchParams(parameters);\n const { as, c, auth, fetch, tlsOnly, timeout } = int(config);\n const response = await oauth\n .clientCredentialsGrantRequest(as, c, auth, parameters, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n DPoP: options?.DPoP,\n headers: new Headers(headers),\n signal: signal(timeout),\n })\n .catch(errorHandler);\n const p = oauth.processClientCredentialsResponse(as, c, response);\n let result;\n try {\n result = await p;\n }\n catch (err) {\n if (retryable(err, options)) {\n return clientCredentialsGrant(config, parameters, {\n ...options,\n flag: retry,\n });\n }\n errorHandler(err);\n }\n addHelpers(result);\n return result;\n}\nexport function buildAuthorizationUrl(config, parameters) {\n checkConfig(config);\n const { as, c, tlsOnly, hybrid, jarm, implicit } = int(config);\n const authorizationEndpoint = oauth.resolveEndpoint(as, 'authorization_endpoint', false, tlsOnly);\n parameters = new URLSearchParams(parameters);\n if (!parameters.has('client_id')) {\n parameters.set('client_id', c.client_id);\n }\n if (!parameters.has('request_uri') && !parameters.has('request')) {\n if (!parameters.has('response_type')) {\n parameters.set('response_type', hybrid ? 'code id_token' : implicit ? 'id_token' : 'code');\n }\n if (implicit && !parameters.has('nonce')) {\n throw CodedTypeError('response_type=id_token clients must provide a nonce parameter in their authorization request parameters', ERR_INVALID_ARG_VALUE);\n }\n if (jarm) {\n parameters.set('response_mode', 'jwt');\n }\n }\n for (const [k, v] of parameters.entries()) {\n authorizationEndpoint.searchParams.append(k, v);\n }\n return authorizationEndpoint;\n}\nexport async function buildAuthorizationUrlWithJAR(config, parameters, signingKey, options) {\n checkConfig(config);\n const authorizationEndpoint = buildAuthorizationUrl(config, parameters);\n parameters = authorizationEndpoint.searchParams;\n if (!signingKey) {\n throw CodedTypeError('\"signingKey\" must be provided', ERR_INVALID_ARG_VALUE);\n }\n const { as, c } = int(config);\n const request = await oauth\n .issueRequestObject(as, c, parameters, signingKey, options)\n .catch(errorHandler);\n return buildAuthorizationUrl(config, { request });\n}\nexport async function buildAuthorizationUrlWithPAR(config, parameters, options) {\n checkConfig(config);\n const authorizationEndpoint = buildAuthorizationUrl(config, parameters);\n const { as, c, auth, fetch, tlsOnly, timeout } = int(config);\n const response = await oauth\n .pushedAuthorizationRequest(as, c, auth, authorizationEndpoint.searchParams, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n DPoP: options?.DPoP,\n headers: new Headers(headers),\n signal: signal(timeout),\n })\n .catch(errorHandler);\n const p = oauth.processPushedAuthorizationResponse(as, c, response);\n let result;\n try {\n result = await p;\n }\n catch (err) {\n if (retryable(err, options)) {\n return buildAuthorizationUrlWithPAR(config, parameters, {\n ...options,\n flag: retry,\n });\n }\n errorHandler(err);\n }\n return buildAuthorizationUrl(config, { request_uri: result.request_uri });\n}\nexport function buildEndSessionUrl(config, parameters) {\n checkConfig(config);\n const { as, c, tlsOnly } = int(config);\n const endSessionEndpoint = oauth.resolveEndpoint(as, 'end_session_endpoint', false, tlsOnly);\n parameters = new URLSearchParams(parameters);\n if (!parameters.has('client_id')) {\n parameters.set('client_id', c.client_id);\n }\n for (const [k, v] of parameters.entries()) {\n endSessionEndpoint.searchParams.append(k, v);\n }\n return endSessionEndpoint;\n}\nfunction checkConfig(input) {\n if (!(input instanceof Configuration)) {\n throw CodedTypeError('\"config\" must be an instance of Configuration', ERR_INVALID_ARG_TYPE);\n }\n if (Object.getPrototypeOf(input) !== Configuration.prototype) {\n throw CodedTypeError('subclassing Configuration is not allowed', ERR_INVALID_ARG_VALUE);\n }\n}\nfunction signal(timeout) {\n return timeout ? AbortSignal.timeout(timeout * 1000) : undefined;\n}\nexport async function fetchUserInfo(config, accessToken, expectedSubject, options) {\n checkConfig(config);\n const { as, c, fetch, tlsOnly, nonRepudiation, timeout, decrypt } = int(config);\n const response = await oauth\n .userInfoRequest(as, c, accessToken, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n DPoP: options?.DPoP,\n headers: new Headers(headers),\n signal: signal(timeout),\n })\n .catch(errorHandler);\n let exec = oauth.processUserInfoResponse(as, c, expectedSubject, response, {\n [oauth.jweDecrypt]: decrypt,\n });\n let result;\n try {\n result = await exec;\n }\n catch (err) {\n if (retryable(err, options)) {\n return fetchUserInfo(config, accessToken, expectedSubject, {\n ...options,\n flag: retry,\n });\n }\n errorHandler(err);\n }\n oauth.getContentType(response) === 'application/jwt' &&\n (await nonRepudiation?.(response));\n return result;\n}\nfunction retryable(err, options) {\n if (options?.DPoP && options.flag !== retry) {\n return oauth.isDPoPNonceError(err);\n }\n return false;\n}\nexport async function tokenIntrospection(config, token, parameters) {\n checkConfig(config);\n const { as, c, auth, fetch, tlsOnly, nonRepudiation, timeout, decrypt } = int(config);\n const response = await oauth\n .introspectionRequest(as, c, auth, token, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n additionalParameters: new URLSearchParams(parameters),\n headers: new Headers(headers),\n signal: signal(timeout),\n })\n .catch(errorHandler);\n const result = await oauth\n .processIntrospectionResponse(as, c, response, {\n [oauth.jweDecrypt]: decrypt,\n })\n .catch(errorHandler);\n oauth.getContentType(response) === 'application/token-introspection+jwt' &&\n (await nonRepudiation?.(response));\n return result;\n}\nconst retry = Symbol();\nexport async function genericGrantRequest(config, grantType, parameters, options) {\n checkConfig(config);\n const { as, c, auth, fetch, tlsOnly, timeout, decrypt, nonRepudiation } = int(config);\n const response = await oauth\n .genericTokenEndpointRequest(as, c, auth, grantType, new URLSearchParams(parameters), {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n DPoP: options?.DPoP,\n headers: new Headers(headers),\n signal: signal(timeout),\n })\n .catch(errorHandler);\n let recognizedTokenTypes;\n if (grantType === 'urn:ietf:params:oauth:grant-type:token-exchange') {\n recognizedTokenTypes = { n_a: () => { } };\n }\n const p = oauth.processGenericTokenEndpointResponse(as, c, response, {\n [oauth.jweDecrypt]: decrypt,\n recognizedTokenTypes,\n });\n let result;\n try {\n result = await p;\n }\n catch (err) {\n if (retryable(err, options)) {\n return genericGrantRequest(config, grantType, parameters, {\n ...options,\n flag: retry,\n });\n }\n errorHandler(err);\n }\n result.id_token && (await nonRepudiation?.(response));\n addHelpers(result);\n return result;\n}\nexport async function tokenRevocation(config, token, parameters) {\n checkConfig(config);\n const { as, c, auth, fetch, tlsOnly, timeout } = int(config);\n return oauth\n .revocationRequest(as, c, auth, token, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n additionalParameters: new URLSearchParams(parameters),\n headers: new Headers(headers),\n signal: signal(timeout),\n })\n .then(oauth.processRevocationResponse)\n .catch(errorHandler);\n}\nexport async function fetchProtectedResource(config, accessToken, url, method, body, headers, options) {\n checkConfig(config);\n headers ||= new Headers();\n if (!headers.has('user-agent')) {\n headers.set('user-agent', USER_AGENT);\n }\n const { fetch, tlsOnly, timeout } = int(config);\n const exec = oauth.protectedResourceRequest(accessToken, method, url, headers, body, {\n [oauth.customFetch]: fetch,\n [oauth.allowInsecureRequests]: !tlsOnly,\n DPoP: options?.DPoP,\n signal: signal(timeout),\n });\n let result;\n try {\n result = await exec;\n }\n catch (err) {\n if (retryable(err, options)) {\n return fetchProtectedResource(config, accessToken, url, method, body, headers, {\n ...options,\n flag: retry,\n });\n }\n errorHandler(err);\n }\n return result;\n}\n//# sourceMappingURL=index.js.map",
7
+ "import * as oidc from 'openid-client';\nimport { isDeepStrictEqual } from 'node:util';\nimport { AccountError, fail } from './errors';\nimport type { LoginConfiguration, LoginProvider, MicrosoftConfiguration, OidcConfiguration, VerifiedIdentity } from '../shared/login-connections';\nimport { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';\nimport type { ControlHostContext, ControlApiHandlerContext, PluginControl, ControlPlugin } from '@jeffusion/bungee-core/plugin';\nimport type { ManagementProvider, ManagementSubject } from '@jeffusion/bungee-core/plugin';\nimport { isDurableStateConflictError, type DurableJson, type PluginDurableState, type DurableMutation, type DurableRecord } from '@jeffusion/bungee-core/plugin';\nexport interface ProviderConnection { provider: LoginProvider; issuer: string; configuration: LoginConfiguration; clientId: string; scopes: string[] }\nconst GUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nconst MICROSOFT = 'https://login.microsoftonline.com/';\nconst CONSUMERS = '9188040d-6c67-4c5b-b112-36a304b66dad';\nconst ISSUER_TEMPLATE = MICROSOFT + '{tenantid}/v2.0';\nconst LIMIT = 1024 * 1024;\ntype Fetcher = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;\nfunction providerFields(value: Record<string, unknown>, fields: string[]) { if (Object.keys(value).some(key => !fields.includes(key))) fail('invalid_input'); }\nfunction providerRecord(value: unknown): Record<string, unknown> { if (!value || typeof value !== 'object' || Array.isArray(value)) fail('invalid_input'); return value as Record<string, unknown>; }\nexport function providerUrl(value: unknown): URL {\n let url: URL;\n try { if (typeof value !== 'string' || !value || value.length > 2048) fail('invalid_oidc_url'); url = new URL(value); } catch { return fail('invalid_oidc_url'); }\n if (url.username || url.password || url.hash || (typeof value === 'string' && (value.includes('#') || /^https?:\\/\\/[^/?#]*@/i.test(value))) || (url.protocol !== 'https:' && !(url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname)))) fail('invalid_oidc_url');\n return url;\n}\nexport function parseProvider(provider: unknown, input: unknown, scopesInput?: unknown): Pick<ProviderConnection, 'provider' | 'issuer' | 'configuration' | 'scopes'> {\n if (!['google', 'microsoft', 'github', 'oidc'].includes(provider as string)) fail('invalid_provider');\n const p = provider as LoginProvider, c = providerRecord(input);\n let issuer: string, configuration: LoginConfiguration;\n if (p === 'google' || p === 'github') { providerFields(c, []); issuer = p === 'google' ? 'https://accounts.google.com' : 'https://github.com'; configuration = {}; }\n else if (p === 'microsoft') {\n providerFields(c, ['accountType', 'tenantId']);\n if (!['tenant', 'organizations', 'consumers', 'common'].includes(c.accountType as string)) fail('invalid_microsoft_configuration');\n if (c.accountType === 'tenant' ? typeof c.tenantId !== 'string' || !GUID.test(c.tenantId) : Object.hasOwn(c, 'tenantId')) fail('invalid_microsoft_configuration');\n configuration = { accountType: c.accountType as MicrosoftConfiguration['accountType'], ...(c.accountType === 'tenant' ? { tenantId: (c.tenantId as string).toLowerCase() } : {}) };\n issuer = MICROSOFT + (configuration.tenantId ?? configuration.accountType) + '/v2.0';\n } else {\n if (!['issuer', 'discovery', 'manual'].includes(c.mode as string)) fail('invalid_oidc_configuration');\n const fields = c.mode === 'issuer' ? ['mode', 'issuer'] : c.mode === 'discovery' ? ['mode', 'issuer', 'discoveryUrl'] : ['mode', 'issuer', 'authorizationEndpoint', 'tokenEndpoint', 'jwksUri', 'tokenEndpointAuthMethod', 'idTokenSigningAlg'];\n providerFields(c, fields); providerUrl(c.issuer); issuer = c.issuer as string;\n if (new URL(issuer).search) fail('invalid_oidc_url');\n if (c.mode === 'discovery') providerUrl(c.discoveryUrl);\n if (c.mode === 'manual') {\n for (const field of ['authorizationEndpoint', 'tokenEndpoint', 'jwksUri']) providerUrl(c[field]);\n if (c.tokenEndpointAuthMethod !== undefined && !['client_secret_basic', 'client_secret_post'].includes(c.tokenEndpointAuthMethod as string)) fail('oidc_auth_method_unsupported');\n if (c.idTokenSigningAlg !== undefined && !['RS256', 'PS256', 'ES256'].includes(c.idTokenSigningAlg as string)) fail('oidc_signing_alg_unsupported');\n }\n configuration = { ...c } as OidcConfiguration;\n }\n if (p !== 'oidc' && scopesInput !== undefined) fail('preset_scopes_fixed');\n const scopes = p === 'github' ? ['read:user'] : scopesInput ?? ['openid', 'profile', 'email'];\n if (!Array.isArray(scopes) || !scopes.length || scopes.length > 16 || scopes.some(s => typeof s !== 'string' || !s || s.length > 128 || /\\s/.test(s)) || (p !== 'github' && !scopes.includes('openid'))) fail('invalid_input');\n return { provider: p, issuer, configuration, scopes };\n}\nasync function boundedResponse(response: Response): Promise<Response> {\n if (!response.body) return response;\n const reader = response.body.getReader();\n const chunks: Uint8Array[] = []; let size = 0;\n try {\n for (;;) {\n const chunk = await reader.read();\n if (chunk.done) break;\n size += chunk.value.length;\n if (size > LIMIT) { await reader.cancel(); fail('oidc_metadata_limit'); }\n chunks.push(chunk.value);\n }\n } finally { reader.releaseLock(); }\n const headers = new Headers(response.headers);\n headers.delete('content-encoding'); headers.delete('content-length');\n return new Response(Buffer.concat(chunks), {status: response.status, statusText: response.statusText, headers});\n}\nasync function limitedJson(response: Response): Promise<unknown> {\n if (!response.ok) fail('oidc_metadata_failed', 502);\n const reader = response.body?.getReader(); if (!reader) fail('oidc_metadata_invalid');\n let size = 0; const chunks: Uint8Array[] = [];\n try { for (;;) { const r = await reader.read(); if (r.done) break; size += r.value.length; if (size > LIMIT) { await reader.cancel(); fail('oidc_metadata_limit'); } chunks.push(r.value); } }\n catch (error) { if (error instanceof AccountError) throw error; fail('oidc_network_failed', 502); }\n finally { reader.releaseLock(); }\n try { return JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch { return fail('oidc_metadata_invalid'); }\n}\nexport interface DiscoveryResult { issuer: string; discoveryUrl: string; authorizationEndpoint: string; tokenEndpoint: string; jwksUri: string; tokenEndpointAuthMethods: string[]; idTokenSigningAlgs: string[] }\nfunction discoveryUrl(issuer: string) { const url = providerUrl(issuer); url.pathname = url.pathname.replace(/\\/$/, '') + '/.well-known/openid-configuration'; return url.href; }\nfunction metadataCheck(value: unknown, expected?: string): oidc.ServerMetadata {\n const m = providerRecord(value);\n if (typeof m.issuer !== 'string') fail('oidc_metadata_invalid');\n if (providerUrl(m.issuer).search) fail('invalid_oidc_url');\n if (expected !== undefined && m.issuer !== expected) fail('oidc_issuer_mismatch');\n for (const key of ['authorization_endpoint', 'token_endpoint', 'jwks_uri']) providerUrl(m[key]);\n for (const key of ['token_endpoint_auth_methods_supported', 'id_token_signing_alg_values_supported']) if (m[key] !== undefined && (!Array.isArray(m[key]) || (m[key] as unknown[]).some(v => typeof v !== 'string'))) fail('oidc_metadata_invalid');\n const methods = m.token_endpoint_auth_methods_supported as string[] | undefined;\n if (methods && !methods.some(m => ['client_secret_basic', 'client_secret_post'].includes(m))) fail('oidc_auth_method_unsupported');\n const algs = m.id_token_signing_alg_values_supported as string[] | undefined;\n if (!algs?.some(a => ['RS256', 'PS256', 'ES256'].includes(a))) fail('oidc_signing_alg_unsupported');\n if (m.code_challenge_methods_supported !== undefined && (!Array.isArray(m.code_challenge_methods_supported) || !m.code_challenge_methods_supported.includes('S256'))) fail('oidc_pkce_unsupported');\n return m as oidc.ServerMetadata;\n}\nexport class LoginProviders {\n constructor(private readonly fetcher: Fetcher, private readonly signal: AbortSignal) {}\n private async network(input: string | URL | Request, init: RequestInit = {}) {\n providerUrl(input instanceof Request ? input.url : String(input));\n try { return await boundedResponse(await this.fetcher(input, { ...init, redirect: 'error', signal: AbortSignal.any([this.signal, AbortSignal.timeout(5000), ...(init.signal ? [init.signal] : [])]) })); }\n catch (error) { if (error instanceof AccountError) throw error; fail('oidc_network_failed', 502); }\n }\n async discover(mode: unknown, value: unknown): Promise<DiscoveryResult> {\n if (mode !== 'issuer' && mode !== 'discovery') fail('invalid_input');\n const url = providerUrl(value); if (mode === 'issuer' && url.search) fail('invalid_oidc_url');\n const endpoint = mode === 'issuer' ? discoveryUrl(value as string) : url.href;\n const m = metadataCheck(await limitedJson(await this.network(endpoint)), mode === 'issuer' ? value as string : undefined);\n return { issuer: m.issuer, discoveryUrl: endpoint, authorizationEndpoint: m.authorization_endpoint!, tokenEndpoint: m.token_endpoint!, jwksUri: m.jwks_uri!, tokenEndpointAuthMethods: m.token_endpoint_auth_methods_supported ?? ['client_secret_basic'], idTokenSigningAlgs: m.id_token_signing_alg_values_supported! };\n }\n private async metadata(c: ProviderConnection): Promise<oidc.ServerMetadata> {\n // The authorization server issuer is distinct from the GitHub identity namespace.\n if (c.provider === 'github') return { issuer: 'https://github.com/login/oauth', authorization_response_iss_parameter_supported: true, authorization_endpoint: 'https://github.com/login/oauth/authorize', token_endpoint: 'https://github.com/login/oauth/access_token', token_endpoint_auth_methods_supported: ['client_secret_post'] };\n const configuration = c.configuration as OidcConfiguration;\n if (c.provider === 'oidc' && configuration.mode === 'manual') return metadataCheck({ issuer: c.issuer, authorization_endpoint: configuration.authorizationEndpoint, token_endpoint: configuration.tokenEndpoint, jwks_uri: configuration.jwksUri, token_endpoint_auth_methods_supported: [configuration.tokenEndpointAuthMethod ?? 'client_secret_basic'], id_token_signing_alg_values_supported: [configuration.idTokenSigningAlg ?? 'RS256'] }, c.issuer);\n const endpoint = c.provider === 'oidc' && configuration.mode === 'discovery' ? configuration.discoveryUrl! : discoveryUrl(c.issuer);\n const raw = await limitedJson(await this.network(endpoint));\n const ms = c.configuration as MicrosoftConfiguration;\n const expected = c.provider === 'microsoft' && ms.accountType !== 'tenant' ? (ms.accountType === 'consumers' ? MICROSOFT + CONSUMERS + '/v2.0' : ISSUER_TEMPLATE) : c.issuer;\n return metadataCheck(raw, expected);\n }\n async validate(c: ProviderConnection) { await this.metadata(c); }\n private microsoftIssuer(connection: ProviderConnection, claims: Record<string, unknown>): string {\n const c = connection.configuration as MicrosoftConfiguration, tid = claims.tid;\n if (typeof tid !== 'string' || !GUID.test(tid)) fail('invalid_microsoft_tenant', 401);\n const normalized = tid.toLowerCase();\n if (claims.iss !== MICROSOFT + tid + '/v2.0' || (c.accountType === 'tenant' && normalized !== c.tenantId) || (c.accountType === 'organizations' && normalized === CONSUMERS) || (c.accountType === 'consumers' && normalized !== CONSUMERS)) fail('microsoft_account_scope', 401);\n return claims.iss as string;\n }\n async configuration(c: ProviderConnection, secret: string): Promise<oidc.Configuration> {\n const metadata = await this.metadata(c);\n const custom = c.configuration as OidcConfiguration;\n const methods = metadata.token_endpoint_auth_methods_supported ?? ['client_secret_basic'];\n const method = c.provider === 'oidc' && custom.mode === 'manual' ? custom.tokenEndpointAuthMethod ?? 'client_secret_basic' : methods.includes('client_secret_post') ? 'client_secret_post' : 'client_secret_basic';\n const auth = method === 'client_secret_post' ? oidc.ClientSecretPost(secret) : oidc.ClientSecretBasic(secret);\n let actualIssuer: string | undefined;\n const customFetch: oidc.CustomFetch = async (input, init) => {\n const { body, ...options } = init;\n const response = await this.network(input, { ...options, body: body instanceof Uint8Array ? new Uint8Array(body).buffer : body });\n if (c.provider === 'github' && String(input) === metadata.token_endpoint) {\n // GitHub returns OAuth errors in JSON even with HTTP 200.\n // Interpret only documented error codes; never expose descriptions or URLs.\n let value: unknown;\n try { value = await response.clone().json(); } catch { fail('oauth_token_failed', 502); }\n if (value && typeof value === 'object' && 'error' in value) {\n switch (value.error) {\n case 'incorrect_client_credentials': fail('oauth_client_rejected', 502);\n case 'redirect_uri_mismatch': fail('oauth_callback_mismatch', 502);\n case 'bad_verification_code': fail('oauth_code_rejected', 401);\n case 'unverified_user_email': fail('oauth_email_unverified', 401);\n default: fail('oauth_token_failed', 502);\n }\n }\n }\n if (c.provider !== 'microsoft') return response;\n if (String(input) === metadata.token_endpoint && response.ok) {\n // Unverified claims only narrow the candidate key set. openid-client\n // must still verify the original token signature, issuer, audience,\n // nonce and lifetime before exchange() returns any identity.\n const value = await limitedJson(response.clone()) as {id_token?: unknown};\n try { if (typeof value.id_token !== 'string') fail('invalid_oidc_identity', 401); const claims = providerRecord(JSON.parse(Buffer.from(value.id_token.split('.')[1]!, 'base64url').toString())); actualIssuer = this.microsoftIssuer(c, claims); }\n catch (error) { if (error instanceof AccountError) throw error; fail('invalid_oidc_identity', 401); }\n }\n if (String(input) === metadata.jwks_uri) {\n if (!actualIssuer) fail('invalid_oidc_identity', 401);\n const value = providerRecord(await limitedJson(response));\n if (!Array.isArray(value.keys)) fail('oidc_metadata_invalid');\n const keys = value.keys.filter(key => key && typeof key === 'object' && typeof key.issuer === 'string' && key.issuer.replace('{tenantid}', actualIssuer!.slice(MICROSOFT.length, -'/v2.0'.length)) === actualIssuer);\n if (!keys.length) fail('microsoft_signing_key_issuer', 401);\n return Response.json({ keys });\n }\n return response;\n };\n const signingAlg = metadata.id_token_signing_alg_values_supported?.includes('RS256') ? 'RS256' : metadata.id_token_signing_alg_values_supported?.find(alg => ['PS256', 'ES256'].includes(alg));\n let config: oidc.Configuration;\n if (c.provider === 'microsoft') {\n // Discovery installs openid-client's Entra issuer-template validator. Feed\n // the metadata already checked above without a second network request.\n config = await oidc.discovery(new URL(c.issuer), c.clientId, {client_secret: secret, id_token_signed_response_alg: 'RS256'}, auth, { timeout: 5, [oidc.customFetch]: async () => Response.json(metadata) });\n } else config = new oidc.Configuration(metadata, c.clientId, { client_secret: secret, ...(c.provider !== 'github' ? {id_token_signed_response_alg: signingAlg} : {}) }, auth);\n config[oidc.customFetch] = customFetch; config.timeout = 5;\n if ([c.issuer, metadata.token_endpoint, metadata.jwks_uri].some(url => url?.startsWith('http:'))) oidc.allowInsecureRequests(config);\n if (c.provider !== 'github') oidc.enableNonRepudiationChecks(config);\n return config;\n }\n async exchange(c: ProviderConnection, config: oidc.Configuration, callback: URL, checks: {pkceCodeVerifier: string; expectedState: string; expectedNonce: string}): Promise<VerifiedIdentity> {\n const tokens = await oidc.authorizationCodeGrant(config, callback, c.provider === 'github' ? {pkceCodeVerifier: checks.pkceCodeVerifier, expectedState: checks.expectedState} : {...checks, idTokenExpected: true}).catch(error => {\n if (error instanceof AccountError) throw error;\n if (error instanceof oidc.ClientError && error.cause instanceof AccountError) throw error.cause;\n if (c.provider !== 'github') throw error;\n fail('oauth_token_failed', 502);\n });\n if (c.provider === 'github') {\n const response = await oidc.fetchProtectedResource(config, tokens.access_token, new URL('https://api.github.com/user'), 'GET', undefined, new Headers({'accept': 'application/vnd.github+json', 'x-github-api-version': '2022-11-28', 'user-agent': 'Bungee'}));\n const user = providerRecord(await limitedJson(response));\n if (!Number.isSafeInteger(user.id) || (user.id as number) <= 0) fail('invalid_oauth_identity', 401);\n return {protocol: 'oauth2', issuer: 'https://github.com', subject: String(user.id), displayName: typeof user.name === 'string' ? [...user.name].slice(0,128).join('') : 'GitHub user'};\n }\n const claims = tokens.claims();\n if (!claims || typeof claims.sub !== 'string' || !claims.sub || claims.sub.length > 255 || typeof claims.iss !== 'string') fail('invalid_oidc_identity', 401);\n if (c.provider === 'microsoft') this.microsoftIssuer(c, claims);\n return {protocol: 'oidc', issuer: claims.iss, subject: claims.sub, displayName: typeof claims.name === 'string' ? [...claims.name].slice(0,128).join('') : 'SSO user'};\n }\n}\n\ninterface User {\n id: string;\n username: string;\n displayName: string;\n disabled: boolean;\n generation: number;\n}\ninterface LocalCredential {\n passwordHash: string;\n temporary: boolean;\n}\ninterface Administrator extends User {\n passwordHash: string;\n temporary: boolean;\n}\ninterface Connection extends ProviderConnection {\n id: string;\n label: string;\n enabled: boolean;\n issuer: string;\n clientId: string;\n secretRef: string;\n scopes: string[];\n generation: number;\n deleting?: { secretRefs: string[] };\n}\ninterface Identity {\n id: string;\n userId: string;\n connectionId: string;\n issuer: string;\n subject: string;\n protocol: VerifiedIdentity['protocol'];\n}\ninterface LoginSettings {\n autoCreateUsers: boolean;\n sessionEpoch: number;\n failureEpoch: number;\n}\ninterface Turnstile {\n enabled: boolean;\n siteKey: string;\n secretRef: string;\n hostnames: string[];\n}\ninterface AuthFlow {\n id: string;\n state: string;\n nonce: string;\n verifierRef: string;\n connectionId: string;\n generation: number;\n created: number;\n expiresAt: number;\n epoch: number;\n returnTo: string;\n status: 'pending' | 'exchanging' | 'verified' | 'consumed';\n initiator?: {\n userId: string;\n generation: number;\n sessionDigest: string;\n };\n subject?: string;\n issuer?: string;\n protocol?: VerifiedIdentity['protocol'];\n}\nconst MAX_USERS = 128, MAX_CONNECTIONS = 32, MAX_IDENTITIES = 512, MAX_FLOWS = 128, MAX_AUDIT = 128;\nconst MAX_SECRETS = 512;\nconst FLOW_COOKIE = 'bungee_user_flow';\nconst EMPTY_SETTINGS: LoginSettings = { autoCreateUsers: false, sessionEpoch: 1, failureEpoch: 1 };\nconst EMPTY_TURNSTILE: Turnstile = { enabled: false, siteKey: '', secretRef: '', hostnames: [] };\ninterface SessionPolicy {\n idleTimeoutMinutes: number;\n absoluteTimeoutMinutes: number;\n}\ninterface Session {\n digest: string;\n administratorId: string;\n generation: number;\n created: number;\n touched: number;\n pendingTouch?: number;\n transport: 'cookie' | 'bearer';\n policy: SessionPolicy;\n epoch: number;\n connectionId?: string;\n connectionGeneration?: number;\n}\ninterface Failure {\n key: string;\n count: number;\n until: number;\n epoch: number;\n}\ninterface Slot<T> {\n key: string;\n version: number;\n value: T | null;\n}\nexport interface Dependencies {\n now?: () => number;\n trustedSource?: (request: Request) => string;\n fetch?: (input: string | URL | Request, init?: RequestInit) => Promise<Response>;\n}\nconst PROVIDER = 'user-auth';\nconst COOKIE = 'bungee_user_session';\nconst DEFAULT_SESSION_POLICY: Readonly<SessionPolicy> = Object.freeze({ idleTimeoutMinutes: 30, absoluteTimeoutMinutes: 480 });\n// Chromium caps persistent cookies at 400 days. Verification renews this browser lease,\n// never the server-side absolute deadline. Browser/user cleanup remains outside our control.\nconst COOKIE_LEASE_SECONDS = 400 * 24 * 60 * 60;\nconst MAX_TIMEOUT_MINUTES = 43200;\nconst ALL = ['config.read', 'config.write', 'logs.read', 'logs.body', 'keys.read', 'keys.write', 'plugins.read', 'plugins.toggle', 'plugins.code', 'auth.mode', 'self.password', 'self.logout'];\nfunction object(v: unknown): Record<string, unknown> { if (!v || typeof v !== 'object' || Array.isArray(v))\n fail('invalid_input'); return v as Record<string, unknown>; }\nfunction exact(v: Record<string, unknown>, fields: string[]) { if (Object.keys(v).some(k => !fields.includes(k)))\n fail('invalid_input'); }\nfunction username(v: unknown): string { if (typeof v !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9_.@-]{0,63}$/.test(v))\n fail('invalid_input'); return v.toLowerCase(); }\nfunction password(v: unknown): string { if (typeof v !== 'string' || [...v].length < 5 || [...v].length > 32)\n fail('invalid_password'); return v; }\nfunction digest(v: string): string { return createHash('sha256').update(v).digest('hex'); }\nfunction csrf(token: string): string { return createHmac('sha256', token).update('user-auth/csrf/v1').digest('base64url'); }\nfunction constant(a: string, b: string): boolean { const aa = Buffer.from(a), bb = Buffer.from(b); return aa.length === bb.length && timingSafeEqual(aa, bb); }\nfunction dto(m: Administrator) { return { id: m.id, username: m.username, displayName: m.displayName, disabled: m.disabled, hasLocalPassword: !!m.passwordHash, requiresPasswordChange: m.temporary }; }\nfunction json(v: unknown, status = 200, headers: Record<string, string> = {}): Response { return Response.json(v, { status, headers: { 'cache-control': 'no-store', ...headers } }); }\nfunction safe(error: unknown): Response { return error instanceof AccountError ? json({ error: error.code }, error.status) : json({ error: 'provider_unavailable' }, 503); }\nasync function body(request: Request): Promise<Record<string, unknown>> {\n const reader = request.body?.getReader();\n if (!reader)\n fail('invalid_input');\n let size = 0;\n const chunks: Uint8Array[] = [];\n try {\n for (;;) {\n const r = await reader.read();\n if (r.done)\n break;\n size += r.value.length;\n if (size > 8192) {\n await reader.cancel();\n fail('body_limit', 413);\n }\n chunks.push(r.value);\n }\n }\n finally {\n reader.releaseLock();\n }\n try {\n return object(JSON.parse(Buffer.concat(chunks).toString('utf8')));\n }\n catch (e) {\n if (e instanceof AccountError)\n throw e;\n return fail('invalid_input');\n }\n}\nfunction credentials(request: Request): {\n token: string;\n transport: Session['transport'];\n} | null {\n const auth = request.headers.get('authorization');\n if (auth !== null) {\n const m = /^Bearer ([A-Za-z0-9_-]{43})$/.exec(auth);\n return m ? { token: m[1]!, transport: 'bearer' } : null;\n }\n const tokens = (request.headers.get('cookie') ?? '').split(';').map(x => x.trim()).filter(x => x.startsWith(COOKIE + '='));\n if (tokens.length !== 1)\n return null;\n const token = tokens[0]!.slice(COOKIE.length + 1);\n return /^[A-Za-z0-9_-]{43}$/.test(token) ? { token, transport: 'cookie' } : null;\n}\nfunction origin(request: Request, expected?: string) { if (request.headers.get('origin') !== (expected ?? new URL(request.url).origin))\n fail('invalid_origin', 403); }\nfunction cookie(request: Request, token: string, maxAge: number, managementOrigin?: string) { return `${COOKIE}=${token}; Path=/; HttpOnly; SameSite=Strict; Max-Age=${maxAge}${new URL(managementOrigin ?? request.url).protocol === 'https:' ? '; Secure' : ''}`; }\nfunction validateSessionPolicy(value: unknown, code = 'invalid_session_policy', status = 400): SessionPolicy {\n if (!value || typeof value !== 'object' || Array.isArray(value))\n fail(code, status);\n const p = value as SessionPolicy;\n if (Object.keys(p).some(key => !['idleTimeoutMinutes', 'absoluteTimeoutMinutes'].includes(key))\n || ![p.idleTimeoutMinutes, p.absoluteTimeoutMinutes].every(n => Number.isSafeInteger(n) && n >= 0 && n <= MAX_TIMEOUT_MINUTES) || p.absoluteTimeoutMinutes === 0)\n fail(code, status);\n return { idleTimeoutMinutes: p.idleTimeoutMinutes, absoluteTimeoutMinutes: p.absoluteTimeoutMinutes };\n}\n// Fixed slots keep expired sessions, logout markers and throttles bounded. Reuse always\n// compares the previous version; a stale touch cannot restore a replaced session.\nexport const ACCOUNT_RECORD_SCHEMA = 3;\nexport const MAX_SESSIONS = 512, MAX_FAILURES = 1024;\nconst asJson = (value: unknown) => value as DurableJson;\nfunction validateUser(value: unknown): User {\n const u = value as User;\n if (!u || Object.keys(u).some(k => !['id', 'username', 'displayName', 'disabled', 'generation'].includes(k)) || typeof u.id !== 'string' || !/^[a-f0-9-]{36}$/.test(u.id) || typeof u.username !== 'string' || !/^[a-z0-9][a-z0-9_.@-]{0,63}$/.test(u.username) || typeof u.displayName !== 'string' || [...u.displayName].length > 128 || typeof u.disabled !== 'boolean' || !Number.isSafeInteger(u.generation) || u.generation < 1)\n fail('corrupt_state', 503);\n return u;\n}\nfunction localValue(record: DurableRecord | null | undefined): LocalCredential | null {\n if (!record)\n return null;\n const c = envelope(record.value, 'credential') as LocalCredential;\n if (!c || Object.keys(c).some(k => !['passwordHash', 'temporary'].includes(k)) || typeof c.passwordHash !== 'string' || !c.passwordHash.startsWith('$argon2id$') || typeof c.temporary !== 'boolean')\n fail('corrupt_state', 503);\n return c;\n}\nfunction entry<T>(records: readonly DurableRecord[], key: string, field: string, fallback: T): Slot<T> {\n const r = records.find(r => r.key === key);\n return { key, version: r?.version ?? 0, value: r ? envelope(r.value, field) as T : fallback };\n}\nfunction users(records: readonly DurableRecord[]): Administrator[] {\n const result = records.filter(r => r.key.startsWith('user:')).map(r => { const u = validateUser(envelope(r.value, 'user')); if (r.key !== 'user:' + u.id)\n fail('corrupt_state', 503); const c = localValue(records.find(r => r.key === 'credential:' + u.id)); return { ...u, passwordHash: c?.passwordHash ?? '', temporary: c?.temporary ?? false }; });\n if (result.length > MAX_USERS || new Set(result.map(u => u.username)).size !== result.length)\n fail('corrupt_state', 503);\n return result;\n}\nfunction settings(records: readonly DurableRecord[]): Slot<LoginSettings> {\n const s = entry(records, 'login-settings', 'settings', EMPTY_SETTINGS), v = s.value!;\n requireReadyRecord(records, s.version);\n if (!v || Object.keys(v).some(k => !['autoCreateUsers', 'sessionEpoch', 'failureEpoch'].includes(k)) || typeof v.autoCreateUsers !== 'boolean' || ![v.sessionEpoch, v.failureEpoch].every(n => Number.isSafeInteger(n) && n > 0))\n fail('corrupt_state', 503);\n return s;\n}\nfunction turnstile(records: readonly DurableRecord[]): Slot<Turnstile> {\n const s = entry(records, 'turnstile', 'turnstile', EMPTY_TURNSTILE), v = s.value!;\n requireReadyRecord(records, s.version);\n if (!v || Object.keys(v).some(k => !['enabled', 'siteKey', 'secretRef', 'hostnames'].includes(k)) || typeof v.enabled !== 'boolean' || typeof v.siteKey !== 'string' || typeof v.secretRef !== 'string' || !Array.isArray(v.hostnames) || v.hostnames.some(h => typeof h !== 'string') || (v.enabled && (!v.siteKey || !v.secretRef || !v.hostnames.length)))\n fail('corrupt_state', 503);\n return s;\n}\nfunction requireReadyRecord(records: readonly DurableRecord[], version: number) {\n const setup = records.find(r => r.key === 'setup');\n if (!version && setup && (envelope(setup.value, 'setup') as Setup).phase === 'ready') fail('corrupt_state', 503);\n}\nfunction connectionSlots(records: readonly DurableRecord[]): Slot<Connection>[] {\n const ids = new Set<string>();\n const result = records.filter(r => r.key.startsWith('connection:')).map(r => {\n const c = envelope(r.value, 'connection') as Connection | null;\n if (c === null) return { key: r.key, version: r.version, value: null };\n if (!c || (c.deleting !== undefined && (!c.deleting || c.enabled || Object.keys(c.deleting).some(k => k !== 'secretRefs') || !Array.isArray(c.deleting.secretRefs) || c.deleting.secretRefs.length > MAX_FLOWS + 1 || c.deleting.secretRefs.some(ref => typeof ref !== 'string' || !/^auth-secret:(\\d+):([1-9]\\d*)$/.test(ref)))) || Object.keys(c).some(k => !['id', 'label', 'enabled', 'issuer', 'provider', 'configuration', 'clientId', 'secretRef', 'scopes', 'generation', 'deleting'].includes(k)) || typeof c.id !== 'string' || !/^[a-f0-9-]{36}$/.test(c.id) || ids.has(c.id) || typeof c.label !== 'string' || typeof c.enabled !== 'boolean' || typeof c.issuer !== 'string' || typeof c.clientId !== 'string' || typeof c.secretRef !== 'string' || !Array.isArray(c.scopes) || (c.provider !== 'github' && !c.scopes.includes('openid')) || c.scopes.some(s => typeof s !== 'string') || !Number.isSafeInteger(c.generation) || c.generation < 1)\n fail('corrupt_state', 503);\n try { const parsed = parseProvider(c.provider, c.configuration, c.provider === 'oidc' ? c.scopes : undefined); if (JSON.stringify(parsed) !== JSON.stringify({provider: c.provider, issuer: c.issuer, configuration: c.configuration, scopes: c.scopes})) fail('corrupt_state', 503); } catch { fail('corrupt_state', 503); }\n ids.add(c.id);\n return { key: r.key, version: r.version, value: c };\n });\n if (result.length > MAX_CONNECTIONS)\n fail('corrupt_state', 503);\n return result;\n}\nfunction connections(records: readonly DurableRecord[]): Connection[] { return connectionSlots(records).flatMap(slot => slot.value && !slot.value.deleting ? [slot.value] : []); }\nfunction identities(records: readonly DurableRecord[]): Identity[] {\n const result = records.filter(r => r.key.startsWith('identity:')).flatMap(r => { const i = envelope(r.value, 'identity') as Identity | null; if (i === null)\n return []; if (!i || Object.keys(i).some(k => !['id', 'userId', 'connectionId', 'issuer', 'subject', 'protocol'].includes(k)) || typeof i.userId !== 'string' || typeof i.connectionId !== 'string' || typeof i.issuer !== 'string' || !['oidc', 'oauth2'].includes(i.protocol) || typeof i.subject !== 'string' || !i.subject || r.key !== 'identity:' + i.id || i.id !== digest(i.issuer + '\\0' + i.subject))\n fail('corrupt_state', 503); return [i]; });\n if (result.length > MAX_IDENTITIES)\n fail('corrupt_state', 503);\n return result;\n}\nfunction envelope(value: unknown, field: string): unknown {\n if (!value || typeof value !== 'object' || Array.isArray(value))\n fail('corrupt_state', 503);\n const v = value as Record<string, unknown>;\n if (v.schema !== ACCOUNT_RECORD_SCHEMA || !Object.hasOwn(v, field) || Object.keys(v).some(k => k !== 'schema' && k !== field))\n fail('corrupt_state', 503);\n return v[field];\n}\nfunction validateSession(value: unknown): Session | null {\n if (value === null)\n return null;\n const s = value as Session;\n if (!s || Object.keys(s).some(k => !['digest', 'administratorId', 'generation', 'created', 'touched', 'pendingTouch', 'transport', 'policy', 'epoch', 'connectionId', 'connectionGeneration'].includes(k)) || !/^[a-f0-9]{64}$/.test(s.digest) || typeof s.administratorId !== 'string' || !s.administratorId || !Number.isSafeInteger(s.generation) || s.generation < 1 || !Number.isSafeInteger(s.created) || s.created < 0 || !Number.isSafeInteger(s.touched) || s.touched < s.created || (s.pendingTouch !== undefined && (!Number.isSafeInteger(s.pendingTouch) || s.pendingTouch < s.touched)) || !Number.isSafeInteger(s.epoch) || s.epoch < 1 || (s.connectionId !== undefined && (typeof s.connectionId !== 'string' || !Number.isSafeInteger(s.connectionGeneration))) || !['cookie', 'bearer'].includes(s.transport))\n fail('corrupt_state', 503);\n validateSessionPolicy(s.policy, 'corrupt_state', 503);\n return s;\n}\nfunction validateFailure(value: unknown): Failure | null {\n if (value === null)\n return null;\n const f = value as Failure;\n if (!f || Object.keys(f).some(k => !['key', 'count', 'until', 'epoch'].includes(k)) || typeof f.key !== 'string' || !/^(account|source|challenge):[a-f0-9]{64}$/.test(f.key) || !Number.isSafeInteger(f.count) || f.count < 0 || !Number.isSafeInteger(f.until) || f.until < 0 || !Number.isSafeInteger(f.epoch) || f.epoch < 1)\n fail('corrupt_state', 503);\n return f;\n}\nfunction slots<T extends Session | Failure | AuthFlow>(records: readonly DurableRecord[], kind: string, limit: number, validate: (v: unknown) => T | null): Slot<T>[] {\n const result: Slot<T>[] = Array.from({ length: limit }, (_, i) => ({ key: `${kind}:${i}`, version: 0, value: null }));\n const seen = new Set<string>();\n for (const r of records.filter(r => r.key.startsWith(kind + ':'))) {\n const index = Number(r.key.slice(kind.length + 1));\n if (!Number.isInteger(index) || index < 0 || index >= limit || r.key !== `${kind}:${index}`)\n fail('corrupt_state', 503);\n const value = validate(envelope(r.value, kind));\n const identity = value && (kind === 'session' ? (value as Session).digest : kind === 'failure' ? (value as Failure).key : (value as AuthFlow).id);\n if (identity && seen.has(identity))\n fail('corrupt_state', 503);\n if (identity)\n seen.add(identity);\n result[index] = { key: r.key, version: r.version, value };\n }\n return result;\n}\nconst mutation = <T>(slot: Slot<T>, field: string, value: T | null): DurableMutation => ({ key: slot.key, expectedVersion: slot.version, value: asJson({ schema: ACCOUNT_RECORD_SCHEMA, [field]: value }) });\nfunction next(value: number): number { if (!Number.isSafeInteger(value + 1))\n fail('generation_overflow'); return value + 1; }\ninterface Setup {\n phase: 'uninitialized' | 'ready';\n code?: {\n digest: string;\n expiresAt: number;\n };\n}\ninterface Clock {\n version: number;\n value: number;\n readVersion?: number;\n}\ntype StateReader = Pick<PluginDurableState, 'get' | 'list'>;\ntype RecoveryContext = {\n durableState: PluginDurableState;\n now?: () => number;\n};\nfunction validateKeys(records: readonly DurableRecord[]) {\n for (const r of records)\n if (!['setup', 'clock', 'session-policy', 'recovery-summary', 'recovery-anchor', 'login-settings', 'turnstile'].includes(r.key) && !['session:', 'failure:', 'user:', 'credential:', 'identity:', 'connection:', 'flow:', 'audit:'].some(p => r.key.startsWith(p)))\n fail('corrupt_state', 503);\n}\nfunction validateAudit(records:readonly DurableRecord[]){\n for(const record of records.filter(r=>r.key.startsWith('audit:'))){\n const index=Number(record.key.slice(6));\n const value=envelope(record.value,'audit') as {actor:string;action:string;result:string;at:number};\n if(!Number.isInteger(index)||index<0||index>=MAX_AUDIT||record.key!=='audit:'+index||!value||Object.keys(value).some(k=>!['actor','action','result','at'].includes(k))||[value.actor,value.action,value.result].some(v=>typeof v!=='string'||!v||v.length>128)||!Number.isSafeInteger(value.at)||value.at<0)fail('corrupt_state',503);\n }\n}\nfunction clockValue(record: DurableRecord | undefined | null): number {\n if (!record)\n fail('corrupt_state', 503);\n const value = envelope(record.value, 'observedThrough');\n if (!Number.isSafeInteger(value) || (value as number) < 0)\n fail('corrupt_state', 503);\n return value as number;\n}\nfunction wallTime(now: () => number): number { const value = now(); if (!Number.isSafeInteger(value) || value < 0)\n fail('invalid_clock', 503); return value; }\nfunction clockMutation(clock: Clock): DurableMutation { return { key: 'clock', expectedVersion: clock.version, value: { schema: ACCOUNT_RECORD_SCHEMA, observedThrough: clock.value } }; }\nasync function observeClock(state: PluginDurableState, now: () => number): Promise<Clock> {\n for (let i = 0; i < 64; i++) {\n const record = await state.get('clock'), prior = clockValue(record), value = Math.max(prior, wallTime(now));\n if (value === prior)\n return { version: record!.version, value, readVersion: record!.version };\n try {\n const [saved] = await state.transact([clockMutation({ version: record!.version, value })]);\n return { version: saved!.version, value, readVersion: record!.version };\n }\n catch (e) {\n if (!isDurableStateConflictError(e))\n throw e;\n }\n }\n return fail('version_conflict', 409);\n}\nfunction setupRecord(records: readonly DurableRecord[]): {\n key: string;\n version: number;\n value: Setup;\n} {\n validateKeys(records);\n const record = records.find(r => r.key === 'setup');\n if (!record)\n fail('corrupt_state', 503);\n const value = envelope(record.value, 'setup') as Setup;\n if (!value || !['uninitialized', 'ready'].includes(value.phase) || Object.keys(value).some(k => !['phase', 'code'].includes(k)))\n fail('corrupt_state', 503);\n if (value.code !== undefined && (!value.code || !/^[a-f0-9]{64}$/.test(value.code.digest) || !Number.isSafeInteger(value.code.expiresAt) || value.code.expiresAt < 0 || Object.keys(value.code).some(k => !['digest', 'expiresAt'].includes(k))))\n fail('corrupt_state', 503);\n if (value.phase === 'ready' && value.code !== undefined)\n fail('corrupt_state', 503);\n const all = users(records), anchor = records.find(r => r.key === 'recovery-anchor');\n if ((value.phase === 'ready') !== !!all.length || (value.phase === 'ready' && (!anchor || typeof envelope(anchor.value, 'userId') !== 'string')))\n fail('corrupt_state', 503);\n validateAudit(records);\n settings(records);\n turnstile(records);\n connections(records);\n identities(records);\n clockValue(records.find(r => r.key === 'clock'));\n return { key: 'setup', version: record.version, value };\n}\nexport class UserAuthControl implements PluginControl, ManagementProvider {\n readonly management = this;\n readonly rpc = [];\n readonly api;\n private readonly state: PluginDurableState;\n private readonly now: () => number;\n private readonly subjects = new WeakMap<ManagementSubject, {\n generation: number;\n digest: string;\n }>();\n // Positive lookups only; bounded by the fixed session slots, never by attacker tokens.\n private readonly sessionSlots = new Map<string, string>();\n private dummy = '';\n private disposed = false;\n private stateTail: Promise<void> = Promise.resolve();\n private pendingStateOperations = 0;\n constructor(private readonly host: ControlHostContext, private readonly dependencies: Dependencies = {}) {\n if (!host.durableState)\n fail('durable_state_required', 503);\n this.state = host.durableState;\n this.now = dependencies.now ?? Date.now;\n const invoke = (fn: (c: ControlApiHandlerContext) => Promise<Response>) => async (c: ControlApiHandlerContext) => {\n try {\n this.alive();\n if (c.requestSignal.aborted)\n fail('cancelled');\n return await fn(c);\n }\n catch (e) {\n return safe(e);\n }\n };\n this.api = [\n { path: '/password', methods: ['POST'], handler: 'changePassword', invoke: invoke(async (c) => {\n await this.requireCapability(c, 'self.password', true);\n const b = await body(c.request);\n exact(b, ['currentPassword', 'password', 'passwordConfirmation']);\n await this.changePassword(c, b);\n return json({ ok: true }, 200, { 'set-cookie': cookie(c.request, '', 0, this.host.managementOrigin) });\n }) },\n { path: '/logout', methods: ['POST'], handler: 'logout', invoke: invoke(async (c) => { await this.requireCapability(c, 'self.logout', true); return this.logout(c.request); }) },\n { path: '/self', methods: ['GET'], handler: 'self', invoke: invoke(async (c) => {\n await this.requireCapability(c, 'self.password');\n return this.retry(async (time) => { const { user } = await this.guard(c, time), creds = credentials(c.request); return { mutations: [], result: json({ administrator: dto(user), ...(creds?.transport === 'cookie' ? { csrfToken: csrf(creds.token) } : {}) }) }; });\n }) },\n { path: '/session-policy', methods: ['GET', 'PUT'], handler: 'sessionPolicy', invoke: invoke(async (c) => {\n await this.requireCapability(c, 'config.write', c.request.method === 'PUT');\n if (c.request.method === 'GET')\n return this.retry(async (time) => { const policy = await this.readSessionPolicy(); await this.guard(c, time); return { mutations: [], result: json(policy) }; });\n const b = await body(c.request);\n exact(b, ['version', 'policy']);\n if (!Number.isSafeInteger(b.version) || (b.version as number) < 0)\n fail('invalid_session_policy');\n const policy = validateSessionPolicy(b.policy);\n await this.requireCapability(c, 'config.write', true);\n try {\n await this.retry(async (time) => { await this.guard(c, time); return { mutations: [{ key: 'session-policy', expectedVersion: b.version as number, value: asJson({ schema: ACCOUNT_RECORD_SCHEMA, policy }) }], result: undefined }; });\n }\n catch (e) {\n if (isDurableStateConflictError(e))\n fail('version_conflict', 409);\n throw e;\n }\n return json(await this.readSessionPolicy());\n }) },\n ...this.featureApi(invoke),\n ];\n }\n private alive() { if (this.disposed || this.host.signal.aborted)\n fail('provider_unavailable', 503); }\n private async readAdministrator(id?: string): Promise<Slot<Administrator>> {\n this.alive();\n if (!id) {\n const all = users(await this.records());\n id = all[0]?.id;\n }\n if (!id)\n return { key: 'user:missing', version: 0, value: null };\n const record = await this.state.get('user:' + id);\n if (!record)\n return { key: 'user:' + id, version: 0, value: null };\n const user = validateUser(envelope(record.value, 'user')), credential = localValue(await this.state.get('credential:' + id));\n if (user.id !== id)\n fail('corrupt_state', 503);\n return { key: record.key, version: record.version, value: { ...user, passwordHash: credential?.passwordHash ?? '', temporary: credential?.temporary ?? false } };\n }\n private userMutation(slot: Slot<Administrator>, value: Administrator): DurableMutation { const { passwordHash, temporary, ...user } = value; return mutation(slot, 'user', user); }\n private credentialMutation(records: readonly DurableRecord[], id: string, hash: string): DurableMutation { const r = records.find(r => r.key === 'credential:' + id); return { key: 'credential:' + id, expectedVersion: r?.version ?? 0, value: asJson({ schema: ACCOUNT_RECORD_SCHEMA, credential: { passwordHash: hash, temporary: false } }) }; }\n private async records() {\n this.alive();\n const records = await this.state.list();\n setupRecord(records);\n return records;\n }\n private async retry<T>(plan: (time: () => Promise<number>) => Promise<{\n mutations: DurableMutation[];\n result: T;\n }>): Promise<T> {\n // Serialize this instance's planners: parallel requests must not continually\n // invalidate each other's clock fences. Cross-instance changes still use CAS.\n if (this.pendingStateOperations >= 256)\n fail('provider_busy', 503);\n this.pendingStateOperations++;\n const task = this.stateTail.then(async () => {\n await this.cleanupDeletedConnections();\n const result = await this.retryState(plan);\n await this.cleanupDeletedConnections();\n return result;\n });\n this.stateTail = task.then(() => { }, () => { });\n try {\n return await task;\n }\n finally {\n this.pendingStateOperations--;\n }\n }\n private async retryState<T>(plan: (time: () => Promise<number>) => Promise<{\n mutations: DurableMutation[];\n result: T;\n }>): Promise<T> {\n for (let i = 0; i < 64; i++) {\n const before = await this.state.get('clock');\n clockValue(before);\n let clock: Clock | undefined;\n // Each planner reads its business records first and observes time last.\n // This prevents delayed reads from renewing an already expired session.\n const time = async () => { const prior = clock, observed = await observeClock(this.state, this.now); clock = prior && observed.readVersion === prior.version ? { ...observed, readVersion: prior.readVersion } : observed; return clock.value; };\n let planned: {\n mutations: DurableMutation[];\n result: T;\n };\n try {\n planned = await plan(time);\n }\n catch (error) {\n await time();\n throw error;\n }\n if (!clock)\n await time();\n // A different control may change identity or touch a slot while we read.\n // Its clock fence invalidates the entire read set, including read-only authorization.\n if (clock!.readVersion !== before!.version)\n continue;\n if (!planned.mutations.length)\n return planned.result;\n this.alive();\n try {\n await this.state.transact([...planned.mutations, clockMutation(clock!)]);\n return planned.result;\n }\n catch (e) {\n if (!isDurableStateConflictError(e))\n throw e;\n }\n }\n return fail('version_conflict', 409);\n }\n private async cleanupDeletedConnections(): Promise<void> {\n // Ordinary authentication must not add clock transactions for an absent job.\n // A concurrent deletion still invalidates the caller's business read via CAS;\n // its durable marker is resumed by the next cleanup check.\n if (!connectionSlots(await this.state.list()).some(slot => slot.value?.deleting)) return;\n // The deletion fence and user revocations commit together. The connection\n // retains all secret references until cleanup is confirmed, including after\n // a process exit or lost ACK. Cleanup does not depend on the deleting session.\n for (;;) {\n const pending = await this.retryState(async () => {\n const records = await this.records();\n const slot = connectionSlots(records).find(s => s.value?.deleting);\n if (!slot) return { mutations: [], result: { done: true, connection: null as Connection | null } };\n const id = slot.value!.id;\n const bindings = identities(records).filter(i => i.connectionId === id);\n const flows = this.flows(records).filter(f => f.value?.connectionId === id);\n const changes = [\n ...bindings.map(i => mutation(entry(records, 'identity:' + i.id, 'identity', null), 'identity', null)),\n ...flows.map(f => mutation(f, 'flow', null)),\n ];\n // Reserve the last mutation for the clock fence.\n return { mutations: changes.slice(0, 255), result: { done: false, connection: changes.length ? null : slot.value } };\n });\n if (pending.done) return;\n if (!pending.connection) continue;\n for (const ref of pending.connection.deleting!.secretRefs) {\n const match = /^auth-secret:(\\d+):([1-9]\\d*)$/.exec(ref)!;\n const key = 'auth-secret:' + match[1], version = Number(match[2]);\n const saved = await this.host.secretStore.get(key);\n // Another control may already have removed or reused the secret slot.\n if (saved?.version === version) await this.host.secretStore.delete(key, version);\n }\n await this.retryState(async () => {\n const records = await this.records();\n const slot = connectionSlots(records).find(s => s.value?.id === pending.connection!.id && s.value.deleting);\n return { mutations: slot ? [mutation(slot, 'connection', null)] : [], result: undefined };\n });\n }\n }\n private async readSessionPolicy(): Promise<{\n version: number;\n policy: SessionPolicy;\n }> {\n this.alive();\n const record = await this.state.get('session-policy');\n return { version: record?.version ?? 0, policy: record ? validateSessionPolicy(envelope(record.value, 'policy'), 'corrupt_state', 503) : { ...DEFAULT_SESSION_POLICY } };\n }\n async start() {\n await readManagementSetup(this.state);\n await observeClock(this.state, this.now);\n await this.readSessionPolicy();\n const records = await this.records();\n slots(records, 'session', MAX_SESSIONS, validateSession);\n slots(records, 'failure', MAX_FAILURES, validateFailure);\n this.flows(records);\n for (const r of records.filter(r => r.key.startsWith('credential:'))) {\n localValue(r);\n if (!users(records).some(u => r.key === 'credential:' + u.id))\n fail('corrupt_state', 503);\n }\n await this.cleanupDeletedConnections();\n this.dummy = await this.hash(randomBytes(32).toString('base64url'));\n }\n dispose() { this.disposed = true; }\n private hash(p: string) { return Bun.password.hash(p, { algorithm: 'argon2id', memoryCost: 65536, timeCost: 3 }); }\n async setupStatus(): Promise<'uninitialized' | 'ready'> { return (await readManagementSetup(this.state)).initialized ? 'ready' : 'uninitialized'; }\n async hasIdentity() { return await this.setupStatus() === 'ready' && users(await this.records()).some(u => !u.disabled); }\n async revokeSessions() { await this.retry(async () => { const s = settings(await this.records()); return { mutations: [mutation(s, 'settings', { ...s.value!, sessionEpoch: next(s.value!.sessionEpoch) })], result: undefined }; }); }\n async bootstrap(input: unknown) {\n const b = object(input);\n exact(b, ['username', 'password']);\n const name = username(b.username), p = password(b.password);\n if (await this.setupStatus() !== 'ready')\n fail('initialization_required', 409);\n const prior = users(await this.records()).find(u => u.username === name);\n if (!prior?.passwordHash)\n fail('invalid_credentials', 401);\n if (prior.username !== name || prior.disabled || !await Bun.password.verify(p, prior.passwordHash))\n fail('invalid_credentials', 401);\n const latest = (await this.readAdministrator(prior.id)).value;\n if (!latest || latest.id !== prior.id || latest.generation !== prior.generation || latest.username !== prior.username || latest.disabled)\n fail('invalid_credentials', 401);\n }\n private source(request: Request): string { return (this.dependencies.trustedSource ?? this.host.trustedSource)?.(request) ?? 'unknown'; }\n private async reserve(keys: string[]): Promise<number> {\n return this.retry(async (time) => {\n const epoch = settings(await this.records()).value!.failureEpoch;\n const failures = slots(await this.records(), 'failure', MAX_FAILURES, validateFailure), selected: Slot<Failure>[] = [], now = await time();\n for (const key of keys) {\n let slot = failures.find(x => !selected.includes(x) && x.value?.key === key);\n const active = slot?.value && slot.value.epoch === epoch && slot.value.until > now;\n if (active && slot!.value!.count >= 10)\n fail('login_limited', 429);\n slot ??= failures.find(x => !selected.includes(x) && (!x.value || x.value.epoch !== epoch || x.value.until <= now));\n if (!slot)\n fail('login_limited', 429);\n selected.push(slot);\n }\n return { mutations: selected.map((slot, i) => { const prior = slot.value; return mutation(slot, 'failure', { key: keys[i]!, count: prior && prior.key === keys[i] && prior.epoch === epoch && prior.until > now ? prior.count + 1 : 1, until: prior && prior.key === keys[i] && prior.epoch === epoch && prior.until > now ? prior.until : now + 15 * 60000, epoch }); }), result: epoch };\n });\n }\n async initialize(request: Request): Promise<Response> {\n try {\n this.alive();\n if (request.method !== 'POST')\n fail('method_not_allowed', 405);\n origin(request, this.host.managementOrigin);\n const b = await body(request);\n exact(b, ['setupCode', 'username', 'password', 'passwordConfirmation']);\n await this.reserve(['source:' + digest(this.source(request))]);\n const check = async (time: () => Promise<number>) => {\n const records = await this.records(), setup = setupRecord(records), now = await time();\n if (setup.value.phase !== 'uninitialized')\n fail('already_initialized', 409);\n if (!setup.value.code || now >= setup.value.code.expiresAt || typeof b.setupCode !== 'string' || !constant(digest(b.setupCode), setup.value.code.digest))\n fail('invalid_setup_code', 401);\n return { setup, records };\n };\n const initial = await this.retry(async (time) => ({ mutations: [], result: await check(time) }));\n const name = username(b.username), p = password(b.password);\n if (b.passwordConfirmation !== p)\n fail('password_confirmation');\n const passwordHash = await this.hash(p);\n await this.retry(async (time) => {\n const { setup, records } = await check(time);\n if (setup.version !== initial.setup.version)\n fail('invalid_setup_code', 401);\n const account: User = { id: randomUUID(), username: name, displayName: name, disabled: false, generation: 1 };\n return { mutations: [mutation(setup, 'setup', { phase: 'ready' } as Setup), mutation(settings(records), 'settings', EMPTY_SETTINGS), mutation(turnstile(records), 'turnstile', EMPTY_TURNSTILE), { key: 'user:' + account.id, expectedVersion: 0, value: asJson({ schema: ACCOUNT_RECORD_SCHEMA, user: account }) }, this.credentialMutation(records, account.id, passwordHash), { key: 'recovery-anchor', expectedVersion: 0, value: { schema: ACCOUNT_RECORD_SCHEMA, userId: account.id } }], result: undefined };\n });\n return json({ initialized: true });\n }\n catch (e) {\n return safe(e);\n }\n }\n private live(m: Administrator | null, session: Session, now: number, records: readonly DurableRecord[]): Administrator | undefined {\n if (session.epoch !== settings(records).value!.sessionEpoch)\n return;\n if (session.connectionId) {\n const c = connections(records).find(c => c.id === session.connectionId);\n if (!c?.enabled || c.generation !== session.connectionGeneration)\n return;\n }\n const policy = session.policy;\n if (now < session.touched || now < session.created || (policy.idleTimeoutMinutes > 0 && now - session.touched >= policy.idleTimeoutMinutes * 60000) || now - session.created >= policy.absoluteTimeoutMinutes * 60000)\n return;\n return m && m.id === session.administratorId && !m.disabled && m.generation === session.generation ? m : undefined;\n }\n private async findSession(d: string): Promise<Slot<Session> | undefined> {\n this.alive();\n const key = this.sessionSlots.get(d);\n if (key) {\n const record = await this.state.get(key), value = record && validateSession(envelope(record.value, 'session'));\n if (record && value?.digest === d)\n return { key, version: record.version, value };\n this.sessionSlots.delete(d);\n }\n const found = slots(await this.records(), 'session', MAX_SESSIONS, validateSession).find(x => x.value?.digest === d);\n if (found) {\n if (this.sessionSlots.size >= MAX_SESSIONS)\n this.sessionSlots.clear();\n this.sessionSlots.set(d, found.key);\n }\n return found;\n }\n private cookieAge(policy: SessionPolicy, elapsedMs = 0): number { return Math.max(0, Math.min(COOKIE_LEASE_SECONDS, Math.floor((policy.absoluteTimeoutMinutes * 60000 - elapsedMs) / 1000))); }\n async sessionCookie(request: Request): Promise<string | undefined> {\n this.alive();\n const creds = credentials(request);\n if (creds?.transport !== 'cookie')\n return;\n return this.retry(async (time) => {\n const slot = await this.findSession(digest(creds.token)), session = slot?.value, m = (await this.readAdministrator(session?.administratorId)).value, records = await this.records(), now = await time();\n return { mutations: [], result: session && session.transport === 'cookie' && this.live(m, session, now, records) ? cookie(request, creds.token, this.cookieAge(session.policy, now - session.created), this.host.managementOrigin) : undefined };\n });\n }\n async authenticate(request: Request): Promise<ManagementSubject | null> {\n this.alive();\n const c = credentials(request);\n if (!c)\n return null;\n const d = digest(c.token);\n // A queued write or a lost ACK must never publish an unchecked extension.\n // Pending activity shares the fixed slot but live() only trusts touched.\n const prepared = await this.retry(async (time) => {\n const slot = await this.findSession(d), session = slot?.value, m = (await this.readAdministrator(session?.administratorId)).value, records = await this.records(), now = await time();\n const administrator = session && session.transport === c.transport && this.live(m, session, now, records);\n if (!slot || !session || !administrator)\n return { mutations: [], result: false };\n return { mutations: session.pendingTouch === undefined ? [mutation(slot, 'session', { ...session, pendingTouch: now })] : [], result: true };\n }).catch(async (error) => {\n // A failed/unknown prepare still observes the error-return time when\n // storage is reachable. Preserve the original failure if the clock also\n // cannot be persisted; pending itself never extends the session.\n try {\n await observeClock(this.state, this.now);\n }\n catch { }\n throw error;\n });\n if (!prepared)\n return null;\n const authenticated = await this.retry(async (time) => {\n const slot = await this.findSession(d), session = slot?.value, m = (await this.readAdministrator(session?.administratorId)).value, records = await this.records(), now = await time();\n const administrator = session && session.transport === c.transport && this.live(m, session, now, records);\n if (!slot || !session || !administrator)\n return { mutations: [], result: null };\n // Observing committed pending activity before the old deadline qualifies\n // its renewal. Slot + clock CAS bind this observation to the exact session\n // and identity generation. Another reader may already have confirmed it.\n const { pendingTouch, ...confirmed } = session;\n // A pending marker may outlive a lost ACK; successful activity renews from\n // this confirmation observation, not from the earlier preparation time.\n return { mutations: pendingTouch === undefined ? [] : [mutation(slot, 'session', { ...confirmed, touched: now })], result: administrator };\n });\n if (!authenticated)\n return null;\n const subject = Object.freeze({ id: authenticated.id, provider: PROVIDER, capabilities: Object.freeze([...ALL]), requiresPasswordChange: authenticated.temporary });\n this.subjects.set(subject, { generation: authenticated.generation, digest: d });\n return await this.authorize(subject, 'config.read') ? subject : null;\n }\n async authorize(subject: ManagementSubject, _capability: string): Promise<boolean> {\n this.alive();\n const issued = this.subjects.get(subject);\n if (!issued || subject.provider !== PROVIDER)\n return false;\n return this.retry(async (time) => {\n const slot = await this.findSession(issued.digest), session = slot?.value, account = (await this.readAdministrator(session?.administratorId)).value, records = await this.records(), now = await time(), m = session && this.live(account, session, now, records);\n return { mutations: [], result: !!m && m.id === subject.id && m.generation === issued.generation };\n });\n }\n private async requireCapability(c: ControlApiHandlerContext, capability: string, write = false) { if (!c.subject || !credentials(c.request) || this.subjects.get(c.subject)?.digest !== digest(credentials(c.request)!.token) || !await this.authorize(c.subject, capability))\n fail('forbidden', 403); if (write)\n this.checkWrite(c.request); }\n validateWrite(request: Request) { this.checkWrite(request); }\n csrfToken(request: Request): string | undefined { const c = credentials(request); return c?.transport === 'cookie' ? csrf(c.token) : undefined; }\n private checkWrite(request: Request) { const c = credentials(request); if (!c)\n fail('unauthorized', 401); if (c.transport === 'cookie') {\n origin(request, this.host.managementOrigin);\n if (!constant(request.headers.get('x-csrf-token') ?? '', csrf(c.token)))\n fail('invalid_csrf', 403);\n } }\n async login(request: Request): Promise<Response> {\n try {\n this.alive();\n if (request.method !== 'POST')\n fail('method_not_allowed', 405);\n const b = await body(request);\n exact(b, ['username', 'password', 'transport', 'turnstileToken']);\n const name = username(b.username), p = typeof b.password === 'string' ? b.password : '';\n const transport = b.transport ?? 'cookie';\n if (transport !== 'cookie' && transport !== 'bearer')\n fail('invalid_input');\n if (transport === 'cookie' || request.headers.has('origin'))\n origin(request, this.host.managementOrigin);\n const keys = ['account:' + digest(name), 'source:' + digest(this.source(request))];\n const reservation = await this.reserve(keys);\n if (await this.setupStatus() !== 'ready')\n fail('invalid_credentials', 401);\n const turn = turnstile(await this.records());\n await this.verifyTurnstile(b.turnstileToken, turn.value!, request);\n const administrator = users(await this.records()).find(u => u.username === name);\n const valid = await Bun.password.verify(p, administrator?.passwordHash || this.dummy || await this.hash('dummy-invalid-password'));\n if (!valid || !administrator || !administrator.passwordHash || administrator.disabled)\n fail('invalid_credentials', 401);\n const token = randomBytes(32).toString('base64url');\n let policy: SessionPolicy = { ...DEFAULT_SESSION_POLICY };\n const created = await this.retry(async (time) => {\n const m = (await this.readAdministrator(administrator.id)).value;\n if (!m || m.id !== administrator.id || m.username !== administrator.username || m.disabled || m.generation !== administrator.generation)\n fail('invalid_credentials', 401);\n const records = await this.records();\n policy = (await this.readSessionPolicy()).policy;\n if (settings(records).value!.failureEpoch !== reservation || turnstile(records).version !== turn.version)\n fail('version_conflict', 409);\n const now = await time(), sessions = slots(records, 'session', MAX_SESSIONS, validateSession), slot = sessions.find(x => !x.value || !this.live(users(records).find(u => u.id === x.value!.administratorId) ?? null, x.value, now, records));\n if (!slot)\n fail('session_limit', 429);\n const changes = [mutation(slot, 'session', { digest: digest(token), administratorId: m.id, generation: m.generation, created: now, touched: now, transport, policy, epoch: settings(records).value!.sessionEpoch }), this.audit(records, m.id, 'local.login', now)];\n const failures = slots(records, 'failure', MAX_FAILURES, validateFailure);\n const account = failures.find(x => x.value?.key === keys[0] && x.value.epoch === reservation);\n if (account)\n changes.push(mutation(account, 'failure', null));\n const source = failures.find(x => x.value?.key === keys[1] && x.value.epoch === reservation);\n if (source)\n changes.push(mutation(source, 'failure', { ...source.value!, count: Math.max(0, source.value!.count - 1) }));\n return { mutations: changes, result: now };\n });\n const latest = (await this.readAdministrator(administrator.id)).value;\n if (!latest || latest.disabled || latest.generation !== administrator.generation || latest.id !== administrator.id)\n fail('invalid_credentials', 401);\n return transport === 'cookie' ? json({ administrator: dto(administrator), csrfToken: csrf(token) }, 200, { 'set-cookie': cookie(request, token, this.cookieAge(policy, (await observeClock(this.state, this.now)).value - created), this.host.managementOrigin) }) : json({ administrator: dto(administrator), token, expiresIn: policy.absoluteTimeoutMinutes * 60 });\n }\n catch (e) {\n await this.recordFailure('local.login',e);\n return safe(e);\n }\n }\n async logout(request: Request): Promise<Response> {\n try {\n this.alive();\n if (request.method !== 'POST')\n fail('method_not_allowed', 405);\n this.checkWrite(request);\n const c = credentials(request)!;\n await this.retry(async () => { const slot = await this.findSession(digest(c.token)); return { mutations: slot?.value ? [mutation(slot, 'session', null)] : [], result: undefined }; });\n return json({ ok: true }, 200, { 'set-cookie': cookie(request, '', 0, this.host.managementOrigin) });\n }\n catch (e) {\n return safe(e);\n }\n }\n private async changePassword(c: ControlApiHandlerContext, b: Record<string, unknown>) {\n const p = password(b.password);\n if (b.passwordConfirmation !== p)\n fail('password_confirmation');\n const id = c.subject!.id, m = (await this.readAdministrator(id)).value;\n if (!m || !m.passwordHash || m.id !== id || typeof b.currentPassword !== 'string' || !await Bun.password.verify(b.currentPassword, m.passwordHash))\n fail('invalid_credentials', 401);\n if (constant(p, b.currentPassword))\n fail('password_unchanged');\n const hashed = await this.hash(p);\n await this.retry(async (time) => {\n this.checkWrite(c.request);\n const a = await this.readAdministrator(id), current = a.value, records = await this.records();\n if (!current || current.id !== id || current.disabled || current.generation !== m.generation)\n fail('version_conflict', 409);\n const issued = this.subjects.get(c.subject!)!, slot = await this.findSession(issued.digest), now = await time();\n if (!slot?.value || !this.live(current, slot.value, now, records))\n fail('forbidden', 403);\n return { mutations: [this.userMutation(a, { ...current, generation: next(current.generation) }), this.credentialMutation(records, id, hashed), mutation(slot, 'session', null), this.audit(records, id, 'user.password.change', now)], result: undefined };\n });\n }\n private async guard(c: ControlApiHandlerContext, time: () => Promise<number>): Promise<{\n user: Administrator;\n records: readonly DurableRecord[];\n }> {\n this.checkWriteIfNeeded(c.request);\n const issued = c.subject && this.subjects.get(c.subject), creds = credentials(c.request);\n if (!issued || !creds || issued.digest !== digest(creds.token))\n fail('forbidden', 403);\n const slot = await this.findSession(issued.digest), records = await this.records(), user = users(records).find(u => u.id === c.subject!.id), now = await time();\n if (!slot?.value || slot.value.transport !== creds.transport || !user || user.generation !== issued.generation || !this.live(user, slot.value, now, records))\n fail('forbidden', 403);\n return { user, records };\n }\n private checkWriteIfNeeded(request: Request) { if (!['GET', 'HEAD'].includes(request.method))\n this.checkWrite(request); }\n private audit(records: readonly DurableRecord[], actor: string, action: string, at: number,result='success'): DurableMutation {\n const recordsBySlot = Array.from({ length: MAX_AUDIT }, (_, i) => records.find(r => r.key === 'audit:' + i));\n const index = recordsBySlot.findIndex(r => !r);\n const slot = index >= 0 ? index : recordsBySlot.reduce((best, r, i) => ((envelope(r!.value, 'audit') as {\n at: number;\n }).at < (envelope(recordsBySlot[best]!.value, 'audit') as {\n at: number;\n }).at ? i : best), 0);\n return { key: 'audit:' + slot, expectedVersion: recordsBySlot[slot]?.version ?? 0, value: asJson({ schema: ACCOUNT_RECORD_SCHEMA, audit: { actor, action, result, at } }) };\n }\n private async recordFailure(action:string,error:unknown){try{await this.retry(async time=>{const records=await this.records(),at=await time();return {mutations:[this.audit(records,'anonymous',action,at,error instanceof AccountError?error.code:'provider_unavailable')],result:undefined};});}catch{/* Audit failures cannot make a rejected authentication succeed. */}}\n private featureApi(invoke: (fn: (c: ControlApiHandlerContext) => Promise<Response>) => (c: ControlApiHandlerContext) => Promise<Response>) {\n const route = (path: string, methods: string[], handler: string, fn: (c: ControlApiHandlerContext) => Promise<Response>) => ({ path, methods, handler, invoke: invoke(fn) });\n return [\n route('/users', ['GET', 'POST'], 'users', async (c) => {\n await this.requireCapability(c, 'config.write', c.request.method === 'POST');\n if (c.request.method === 'GET')\n return this.retry(async (time) => { const { records } = await this.guard(c, time); return { mutations: [], result: json({ users: users(records).map(dto) }) }; });\n const b = await body(c.request);\n exact(b, ['username', 'displayName', 'password', 'passwordConfirmation']);\n const name = username(b.username), displayName = this.displayName(b.displayName ?? name);\n const hash = b.password === undefined ? '' : await this.hash(this.confirmPassword(b)), id = randomUUID();\n return this.retry(async (time) => {\n const { records, user } = await this.guard(c, time), all = users(records);\n if (all.length >= MAX_USERS)\n fail('user_limit', 409);\n if (all.some(u => u.username === name))\n fail('username_exists', 409);\n const u: Administrator = { id, username: name, displayName, disabled: false, generation: 1, passwordHash: hash, temporary: false };\n return { mutations: [this.userMutation({ key: 'user:' + id, version: 0, value: null }, u), ...(hash ? [this.credentialMutation(records, id, hash)] : []), this.audit(records, user.id, 'user.create', await time())], result: json({ user: dto(u) }, 201) };\n });\n }),\n route('/users/update', ['PUT'], 'updateUser', async (c) => {\n await this.requireCapability(c, 'config.write', true);\n const b = await body(c.request);\n exact(b, ['id', 'username', 'displayName', 'disabled']);\n const id = this.text(b.id, 64), name = username(b.username), displayName = this.displayName(b.displayName);\n if (typeof b.disabled !== 'boolean')\n fail('invalid_input');\n return this.retry(async (time) => {\n const { records, user } = await this.guard(c, time), all = users(records), u = all.find(u => u.id === id);\n if (!u)\n fail('not_found', 404);\n if (all.some(u => u.id !== id && u.username === name))\n fail('username_exists', 409);\n if (b.disabled && !u.disabled && u.passwordHash && !all.some(x => x.id !== id && !x.disabled && x.passwordHash))\n fail('last_local_user', 409);\n const updated = { ...u, username: name, displayName, disabled: b.disabled as boolean, generation: b.disabled !== u.disabled ? next(u.generation) : u.generation };\n const r = records.find(r => r.key === 'user:' + id)!;\n return { mutations: [this.userMutation({ key: r.key, version: r.version, value: u }, updated), this.audit(records, user.id, 'user.update', await time())], result: json({ user: dto(updated) }) };\n });\n }),\n route('/users/password', ['POST'], 'resetUserPassword', async (c) => {\n await this.requireCapability(c, 'config.write', true);\n const b = await body(c.request);\n exact(b, ['id', 'password', 'passwordConfirmation']);\n const id = this.text(b.id, 64), hash = await this.hash(this.confirmPassword(b));\n return this.retry(async (time) => {\n const { records, user } = await this.guard(c, time), u = users(records).find(u => u.id === id);\n if (!u)\n fail('not_found', 404);\n const r = records.find(r => r.key === 'user:' + id)!;\n return { mutations: [this.userMutation({ key: r.key, version: r.version, value: u }, { ...u, generation: next(u.generation) }), this.credentialMutation(records, id, hash), this.audit(records, user.id, 'user.password.reset', await time())], result: json({ ok: true }) };\n });\n }),\n route('/identities', ['GET', 'POST', 'DELETE'], 'identities', async (c) => {\n await this.requireCapability(c, 'config.write', c.request.method !== 'GET');\n const b = c.request.method === 'GET' ? {} : await body(c.request);\n exact(b, c.request.method === 'POST' ? ['userId', 'connectionId', 'subject'] : ['id']);\n return this.retry(async (time) => {\n const { records, user } = await this.guard(c, time), all = identities(records);\n if (c.request.method === 'GET') {\n const id = new URL(c.request.url).searchParams.get('userId');\n return { mutations: [], result: json({ identities: all.filter(i => !id || i.userId === id) }) };\n }\n let identity: Identity;\n if (c.request.method === 'POST') {\n const connection = connections(records).find(x => x.id === b.connectionId);\n if (!connection)\n fail('not_found', 404);\n const ms = connection.configuration as MicrosoftConfiguration;\n if (connection.provider === 'microsoft' && ['common', 'organizations'].includes(ms.accountType)) fail('verified_identity_required');\n const identityIssuer = connection.provider === 'microsoft' && ms.accountType === 'consumers' ? 'https://login.microsoftonline.com/9188040d-6c67-4c5b-b112-36a304b66dad/v2.0' : connection.issuer;\n const sub = this.text(b.subject, 255), id = digest(identityIssuer + '\\0' + sub);\n if (connection.provider === 'github' && (!/^[1-9][0-9]*$/.test(sub) || !Number.isSafeInteger(Number(sub)))) fail('invalid_oauth_identity');\n if (all.some(x => x.id === id))\n fail('identity_exists', 409);\n if (all.length >= MAX_IDENTITIES)\n fail('identity_limit', 409);\n identity = { id, userId: this.text(b.userId, 64), connectionId: connection.id, issuer: identityIssuer, subject: sub, protocol: connection.provider === 'github' ? 'oauth2' : 'oidc' };\n }\n else {\n const found = all.find(i => i.id === b.id);\n if (!found)\n fail('not_found', 404);\n identity = found;\n }\n const target = users(records).find(u => u.id === identity.userId);\n if (!target)\n fail('not_found', 404);\n const r = records.find(r => r.key === 'user:' + target.id)!, prior = entry(records, 'identity:' + identity.id, 'identity', null);\n return { mutations: [mutation(prior, 'identity', c.request.method === 'POST' ? identity : null), this.userMutation({ key: r.key, version: r.version, value: target }, { ...target, generation: next(target.generation) }), this.audit(records, user.id, c.request.method === 'POST' ? 'identity.bind' : 'identity.unbind', await time())], result: json({ ok: true }) };\n });\n }),\n route('/login-connections', ['GET', 'POST', 'PUT', 'DELETE'], 'loginConnections', async (c) => {\n await this.requireCapability(c, 'config.write', c.request.method !== 'GET');\n if (c.request.method === 'GET')\n return this.retry(async (time) => { const { records } = await this.guard(c, time); return { mutations: [], result: json({ publicOrigin: this.host.managementOrigin ? this.publicOrigin() : null, connections: connectionSlots(records).flatMap(slot => slot.value && !slot.value.deleting ? [{ ...this.connectionDto(slot.value), version: slot.version }] : []) }) }; });\n const b = await body(c.request);\n if (c.request.method === 'DELETE') {\n exact(b, ['id', 'version']);\n const id = this.text(b.id, 64);\n if (!Number.isSafeInteger(b.version) || (b.version as number) < 1) fail('invalid_input');\n return this.retry(async (time) => {\n const { records, user } = await this.guard(c, time);\n const slot = connectionSlots(records).find(s => s.value?.id === id && !s.value.deleting);\n if (!slot || slot.version !== b.version) fail('version_conflict', 409);\n const affectedIds = new Set(identities(records).filter(i => i.connectionId === id).map(i => i.userId));\n const affected = users(records).filter(u => affectedIds.has(u.id));\n const issued = this.subjects.get(c.subject!)!, session = await this.findSession(issued.digest);\n return {\n mutations: [\n mutation(slot, 'connection', { ...slot.value!, enabled: false, deleting: { secretRefs: [...new Set([slot.value!.secretRef, ...this.flows(records).filter(f => f.value?.connectionId === id).map(f => f.value!.verifierRef)])].filter(Boolean) } }),\n ...affected.map(u => {\n const r = records.find(r => r.key === 'user:' + u.id)!;\n return this.userMutation({ key: r.key, version: r.version, value: u }, { ...u, generation: next(u.generation) });\n }),\n this.audit(records, user.id, 'login.delete', await time()),\n ],\n result: json({ ok: true, sessionRevoked: affectedIds.has(user.id) || session?.value?.connectionId === id }),\n };\n });\n }\n exact(b, ['id', 'version', 'label', 'enabled', 'provider', 'configuration', 'clientId', 'clientSecret', 'scopes']);\n const id = this.text(b.id, 36), label = this.text(b.label, 128), clientId = this.text(b.clientId, 512);\n if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(id) || (b.enabled !== undefined && typeof b.enabled !== 'boolean') || (c.request.method === 'POST' && b.version !== undefined) || (c.request.method === 'PUT' && (!Number.isSafeInteger(b.version) || (b.version as number) < 1))) fail('invalid_input');\n const parsed = parseProvider(b.provider, b.configuration, b.scopes);\n const previous = c.request.method === 'PUT' ? await this.retry(async time => {\n const {records} = await this.guard(c, time);\n const slot = connectionSlots(records).find(slot => slot.value?.id === id && !slot.value.deleting);\n if (!slot?.value || slot.version !== b.version) fail('version_conflict', 409);\n if (slot.value.provider !== parsed.provider) fail('invalid_input');\n return {mutations: [], result: slot.value};\n }) : undefined;\n // Revocation must remain available while the identity provider is down.\n const disableOnly = previous && b.enabled === false && b.clientSecret === undefined\n && previous.clientId === clientId && previous.issuer === parsed.issuer\n && isDeepStrictEqual(previous.configuration, parsed.configuration)\n && isDeepStrictEqual(previous.scopes, parsed.scopes);\n if (!disableOnly) await this.loginProviders().validate({...parsed, clientId});\n const secretRef = b.clientSecret === undefined ? undefined : await this.storeSecret(this.text(b.clientSecret, 8192));\n let replacedRef: string | undefined;\n try {\n return await this.retry(async (time) => {\n const { records, user } = await this.guard(c, time), slots = connectionSlots(records), record = c.request.method === 'POST' ? slots.find(s => s.value?.id === id) ?? slots.find(s => s.key === 'connection:' + id) ?? slots.find(s => s.value === null) : slots.find(s => s.value?.id === id && !s.value.deleting), old = record?.value;\n if (c.request.method === 'PUT' && (!old || record?.version !== b.version))\n fail('version_conflict', 409);\n if (old && old.provider !== parsed.provider) fail('invalid_input');\n if (c.request.method === 'POST' && old) fail('version_conflict', 409);\n if (c.request.method === 'POST' && slots.filter(s => s.value !== null).length >= MAX_CONNECTIONS)\n fail('connection_limit', 409);\n replacedRef = old?.secretRef;\n const connection: Connection = { id, label, enabled: b.enabled as boolean ?? false, ...parsed, clientId, secretRef: secretRef ?? old?.secretRef ?? '', generation: next(old?.generation ?? 0) };\n if (connection.enabled && !connection.secretRef)\n fail('oidc_secret_required');\n return { mutations: [{ key: record?.key ?? 'connection:' + id, expectedVersion: record?.version ?? 0, value: asJson({ schema: ACCOUNT_RECORD_SCHEMA, connection }) }, this.audit(records, user.id, 'login.configure', await time())], result: json({ connection: { ...this.connectionDto(connection), version: (record?.version ?? 0) + 1 } }, c.request.method === 'POST' ? 201 : 200) };\n });\n }\n finally {\n if (secretRef)\n await this.discardUnpublishedSecret(secretRef);\n if (replacedRef)\n await this.discardUnpublishedSecret(replacedRef);\n }\n }),\n route('/login-connections/discover', ['POST'], 'discoverLoginConnection', async c => {\n await this.requireCapability(c, 'config.write', true);\n const b = await body(c.request); exact(b, ['mode', 'url']);\n const metadata = await this.loginProviders().discover(b.mode, b.url);\n return this.retry(async time => { await this.guard(c, time); return {mutations: [], result: json(metadata)}; });\n }),\n route('/login-settings', ['GET', 'PUT'], 'loginSettings', async (c) => {\n await this.requireCapability(c, 'config.write', c.request.method === 'PUT');\n const b = c.request.method === 'PUT' ? await body(c.request) : {};\n exact(b, ['version', 'autoCreateUsers']);\n return this.retry(async (time) => {\n const { records, user } = await this.guard(c, time), s = settings(records);\n if (c.request.method === 'GET')\n return { mutations: [], result: json({ version: s.version, autoCreateUsers: s.value!.autoCreateUsers }) };\n if (typeof b.autoCreateUsers !== 'boolean')\n fail('invalid_input');\n if (b.version !== s.version)\n fail('version_conflict', 409);\n return { mutations: [mutation(s, 'settings', { ...s.value!, autoCreateUsers: b.autoCreateUsers }), this.audit(records, user.id, 'login.configure', await time())], result: json({ version: s.version + 1, autoCreateUsers: b.autoCreateUsers }) };\n });\n }),\n route('/turnstile', ['GET', 'PUT'], 'turnstile', async (c) => {\n await this.requireCapability(c, 'config.write', c.request.method === 'PUT');\n if (c.request.method === 'GET')\n return this.retry(async (time) => { const { records } = await this.guard(c, time), s = turnstile(records); return { mutations: [], result: json(this.turnstileDto(s)) }; });\n const b = await body(c.request);\n exact(b, ['version', 'enabled', 'siteKey', 'secret', 'hostnames']);\n if (typeof b.enabled !== 'boolean' || typeof b.siteKey !== 'string' || b.siteKey.length > 256 || !Array.isArray(b.hostnames) || b.hostnames.length > 32 || b.hostnames.some(h => typeof h !== 'string' || !h || h.length > 253 || !/^([a-z0-9-]+\\.)*[a-z0-9-]+$/i.test(h)))\n fail('invalid_input');\n const ref = b.secret === undefined ? undefined : await this.storeSecret(this.text(b.secret, 8192));\n let replacedRef: string | undefined;\n try {\n return await this.retry(async (time) => {\n const { records, user } = await this.guard(c, time), s = turnstile(records);\n replacedRef = s.value!.secretRef;\n if (s.version !== b.version)\n fail('version_conflict', 409);\n const v: Turnstile = { enabled: b.enabled as boolean, siteKey: b.siteKey as string, secretRef: ref ?? s.value!.secretRef, hostnames: b.hostnames as string[] };\n if (v.enabled && (!v.siteKey || !v.secretRef || !v.hostnames.length))\n fail('turnstile_incomplete');\n return { mutations: [mutation(s, 'turnstile', v), this.audit(records, user.id, 'turnstile.configure', await time())], result: json(this.turnstileDto({ key: s.key, version: s.version + 1, value: v })) };\n });\n }\n finally {\n if (ref)\n await this.discardUnpublishedSecret(ref);\n if (replacedRef)\n await this.discardUnpublishedSecret(replacedRef);\n }\n }),\n route('/identities/link/start', ['POST'], 'beginIdentityLink', async (c) => { await this.requireCapability(c, 'config.write', true); const b = await body(c.request); exact(b, ['connectionId']); return this.startFlow(c.request, this.text(b.connectionId, 64), '/#/extensions/user-auth/profile', c); }),\n route('/identities/link/finish', ['POST'], 'finishIdentityLink', async (c) => { await this.requireCapability(c, 'config.write', true); const b = await body(c.request); exact(b, ['flowId']); return this.finishLink(c, this.text(b.flowId, 64)); }),\n ];\n }\n private displayName(v: unknown): string { if (typeof v !== 'string' || [...v].length > 128)\n fail('invalid_input'); return v; }\n private text(v: unknown, max: number): string { if (typeof v !== 'string' || !v || v.length > max)\n fail('invalid_input'); return v; }\n private confirmPassword(b: Record<string, unknown>): string { const p = password(b.password); if (p !== b.passwordConfirmation)\n fail('password_confirmation'); return p; }\n private connectionDto(v: Connection) { return { id: v.id, label: v.label, enabled: v.enabled, provider: v.provider, configuration: v.configuration, issuer: v.issuer, clientId: v.clientId, scopes: v.scopes, hasSecret: !!v.secretRef }; }\n private turnstileDto(s: Slot<Turnstile>) { return { version: s.version, enabled: s.value!.enabled, siteKey: s.value!.siteKey, hostnames: s.value!.hostnames, hasSecret: !!s.value!.secretRef }; }\n private async storeSecret(secret: string): Promise<string> {\n const encoded = JSON.stringify({owner: randomUUID(), value: secret});\n for (let index = 0; index < MAX_SECRETS; index++) {\n const key = 'auth-secret:' + index;\n if (await this.host.secretStore.get(key)) continue;\n try {\n const version = await this.host.secretStore.compareAndSet(key, null, encoded);\n return key + ':' + version;\n }\n catch (error) {\n const saved = await this.host.secretStore.get(key);\n if (saved && constant(saved.value, encoded)) return key + ':' + saved.version;\n if (error && typeof error === 'object' && 'code' in error && error.code === 'version_conflict') continue;\n throw error;\n }\n }\n return fail('secret_limit', 503);\n }\n private async readSecret(ref: string) {\n const match = /^auth-secret:(\\d+):([1-9]\\d*)$/.exec(ref);\n if (!match || Number(match[1]) >= MAX_SECRETS) return null;\n const key = 'auth-secret:' + match[1], saved = await this.host.secretStore.get(key);\n if (saved?.version !== Number(match[2])) return null;\n try {\n const value = JSON.parse(saved.value) as {owner?: unknown; value?: unknown};\n return typeof value?.owner === 'string' && typeof value.value === 'string' ? {version:saved.version, value:value.value, key} : null;\n } catch { return null; }\n }\n private async deleteSecret(ref: string) {\n const saved = await this.readSecret(ref);\n if (saved) await this.host.secretStore.delete(saved.key, saved.version);\n }\n private async discardUnpublishedSecret(ref: string) {\n try {\n const records = await this.records();\n if (records.some(r => JSON.stringify(r.value).includes(ref)))\n return;\n await this.deleteSecret(ref);\n }\n catch { /* Unknown publication must retain the reference until a later bounded-slot cleanup. */ }\n }\n private async verifyTurnstile(token: unknown, config: Turnstile, request: Request) {\n if (!config.enabled)\n return;\n if (typeof token !== 'string' || !token || token.length > 2048)\n fail('turnstile_required', 401);\n await this.retry(async (time) => {\n const records = await this.records(), s = settings(records).value!, all = slots(records, 'failure', MAX_FAILURES, validateFailure), key = 'challenge:' + digest(token), now = await time();\n if (all.some(f => f.value?.key === key && f.value.until > now))\n fail('turnstile_failed', 401);\n const slot = all.find(f => !f.value || f.value.until <= now);\n if (!slot)\n fail('login_limited', 429);\n return { mutations: [mutation(slot, 'failure', { key, count: 1, until: now + 5 * 60000, epoch: s.failureEpoch })], result: undefined };\n });\n const secret = await this.readSecret(config.secretRef);\n if (!secret)\n fail('turnstile_failed', 401);\n try {\n const response = await (this.dependencies.fetch ?? fetch)('https://challenges.cloudflare.com/turnstile/v0/siteverify', { method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ secret: secret.value, response: token }), signal: AbortSignal.any([request.signal, this.host.signal, AbortSignal.timeout(5000)]), redirect: 'error' });\n const result = await response.json() as {\n success?: unknown;\n hostname?: unknown;\n action?: unknown;\n };\n if (!response.ok || result.success !== true || typeof result.hostname !== 'string' || !config.hostnames.includes(result.hostname) || result.action !== 'local-login')\n fail('turnstile_failed', 401);\n }\n catch (e) {\n if (e instanceof AccountError)\n throw e;\n fail('turnstile_failed', 401);\n }\n }\n private publicOrigin(): string {\n const configured = this.host.managementOrigin;\n if (!configured) fail('management_origin_required', 503);\n let url: URL;\n try { url = new URL(configured); }\n catch { fail('management_origin_required', 503); }\n if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.pathname !== '/' || url.search || url.hash || url.origin !== configured)\n fail('management_origin_required', 503);\n return url.origin;\n }\n private returnPath(value: unknown): string { if (value === undefined)\n return '/#/'; if (typeof value !== 'string' || !value.startsWith('/') || value.startsWith('//') || value.includes('\\\\') || /[\\x00-\\x20]/.test(value) || value.length > 2048)\n fail('invalid_return_to'); const u = new URL(value, this.publicOrigin()); if (u.origin !== this.publicOrigin())\n fail('invalid_return_to'); return u.pathname + u.search + u.hash; }\n private flowCookie(token: string, maxAge = 600) { return `${FLOW_COOKIE}=${token}; Path=/api/auth/login/callback/; HttpOnly; SameSite=Lax; Max-Age=${maxAge}${this.publicOrigin().startsWith('https:') ? '; Secure' : ''}`; }\n private flows(records: readonly DurableRecord[]): Slot<AuthFlow>[] {\n return slots(records, 'flow', MAX_FLOWS, v => { if (v === null)\n return null; const f = v as AuthFlow; if (!f || Object.keys(f).some(k => !['id', 'state', 'nonce', 'verifierRef', 'connectionId', 'generation', 'created', 'expiresAt', 'epoch', 'returnTo', 'status', 'initiator', 'subject', 'issuer', 'protocol'].includes(k)) || typeof f.id !== 'string' || typeof f.state !== 'string' || typeof f.nonce !== 'string' || typeof f.verifierRef !== 'string' || typeof f.connectionId !== 'string' || !Number.isSafeInteger(f.generation) || !Number.isSafeInteger(f.created) || !Number.isSafeInteger(f.expiresAt) || !Number.isSafeInteger(f.epoch) || !['pending', 'exchanging', 'verified', 'consumed'].includes(f.status) || typeof f.returnTo !== 'string' || (f.subject !== undefined && typeof f.subject !== 'string') || (f.issuer !== undefined && typeof f.issuer !== 'string') || (f.protocol !== undefined && !['oidc', 'oauth2'].includes(f.protocol)) || (f.status === 'verified' && (!f.subject || !f.issuer || !f.protocol)) || (f.initiator !== undefined && (!f.initiator || typeof f.initiator.userId !== 'string' || typeof f.initiator.sessionDigest !== 'string' || !Number.isSafeInteger(f.initiator.generation))))\n fail('corrupt_state', 503); return f; });\n }\n private loginProviders() { return new LoginProviders(this.dependencies.fetch ?? fetch, this.host.signal); }\n private async oidcConfig(connection: Connection): Promise<oidc.Configuration> {\n const secret = await this.readSecret(connection.secretRef);\n if (!secret) fail('oidc_unavailable', 503);\n return this.loginProviders().configuration(connection, secret.value);\n }\n async loginOptions(_request: Request): Promise<Response> { try {\n this.alive();\n const records = await this.records(), t = turnstile(records).value!;\n return json({ local: { enabled: true, turnstile: { enabled: t.enabled, ...(t.enabled ? { siteKey: t.siteKey } : {}) } }, methods: connections(records).filter(c => c.enabled).map(c => ({ id: c.id, label: c.label, provider: c.provider })) });\n }\n catch (e) {\n return safe(e);\n } }\n async beginLogin(request: Request): Promise<Response> { try {\n this.alive();\n origin(request, this.host.managementOrigin);\n const b = await body(request);\n exact(b, ['methodId', 'returnTo']);\n return await this.startFlow(request, this.text(b.methodId, 64), this.returnPath(b.returnTo));\n }\n catch (e) {\n return safe(e);\n } }\n private async startFlow(request: Request, methodId: string, returnTo: string, c?: ControlApiHandlerContext): Promise<Response> {\n const publicOrigin = this.publicOrigin();\n await this.reserve(['source:' + digest(this.source(request))]);\n const connection = connections(await this.records()).find(c => c.id === methodId && c.enabled);\n if (!connection)\n fail('oidc_unavailable', 401);\n const config = await this.oidcConfig(connection), state = oidc.randomState(), nonce = oidc.randomNonce(), verifier = oidc.randomPKCECodeVerifier(), challenge = await oidc.calculatePKCECodeChallenge(verifier), verifierRef = await this.storeSecret(verifier), id = randomUUID();\n let replacedRef: string | undefined;\n try {\n await this.retry(async (time) => {\n const guarded = c ? await this.guard(c, time) : undefined, records = guarded?.records ?? await this.records(), current = connections(records).find(x => x.id === methodId), now = await time();\n if (!current?.enabled || current.generation !== connection.generation)\n fail('version_conflict', 409);\n const slot = this.flows(records).find(s => !s.value || s.value.expiresAt <= now || s.value.status === 'consumed');\n if (!slot)\n fail('flow_limit', 429);\n replacedRef = slot.value?.verifierRef;\n const flow: AuthFlow = { id, state, nonce, verifierRef, connectionId: methodId, generation: current.generation, created: now, expiresAt: now + 10 * 60000, epoch: settings(records).value!.sessionEpoch, returnTo, status: 'pending', ...(guarded ? { initiator: { userId: guarded.user.id, generation: guarded.user.generation, sessionDigest: this.subjects.get(c!.subject!)!.digest } } : {}) };\n return { mutations: [mutation(slot, 'flow', flow)], result: undefined };\n });\n const authorizationUrl = oidc.buildAuthorizationUrl(config, { redirect_uri: publicOrigin + '/api/auth/login/callback/' + methodId, scope: connection.scopes.join(' '), response_type: 'code', code_challenge: challenge, code_challenge_method: 'S256', state, ...(connection.provider === 'github' ? {} : { nonce }) }).href;\n return json({ authorizationUrl, flowId: id }, 200, { 'set-cookie': this.flowCookie(state) });\n }\n finally {\n await this.discardUnpublishedSecret(verifierRef);\n if (replacedRef)\n await this.discardUnpublishedSecret(replacedRef);\n }\n }\n async completeLogin(request: Request): Promise<Response> {\n let verifierRef: string | undefined;\n try {\n this.alive();\n const publicOrigin = this.publicOrigin(), incoming = new URL(request.url), methodId = incoming.pathname.split('/').at(-1)!, state = incoming.searchParams.get('state');\n const cookies = (request.headers.get('cookie') ?? '').split(';').map(c => c.trim()).filter(c => c.startsWith(FLOW_COOKIE + '='));\n if (!state || cookies.length !== 1 || !constant(cookies[0]!.slice(FLOW_COOKIE.length + 1), state))\n fail('invalid_oidc_state', 401);\n const flow = await this.retry(async (time) => {\n const records = await this.records(), slot = this.flows(records).find(s => s.value?.state === state), connection = connections(records).find(c => c.id === methodId), now = await time(), f = slot?.value;\n if (!slot || !f || f.connectionId !== methodId || f.status !== 'pending' || f.epoch !== settings(records).value!.sessionEpoch || f.expiresAt <= now || !connection?.enabled || connection.generation !== f.generation)\n fail('invalid_oidc_flow', 401);\n return { mutations: [mutation(slot, 'flow', { ...f, status: 'exchanging' })], result: { flow: f, connection } };\n });\n verifierRef = flow.flow.verifierRef;\n const verifier = await this.readSecret(verifierRef);\n if (!verifier)\n fail('invalid_oidc_flow', 401);\n const config = await this.oidcConfig(flow.connection);\n const canonical = new URL(publicOrigin + '/api/auth/login/callback/' + methodId);\n canonical.search = incoming.search;\n const identityResult = await this.loginProviders().exchange(flow.connection, config, canonical, {pkceCodeVerifier: verifier.value, expectedState: state, expectedNonce: flow.flow.nonce});\n const token = randomBytes(32).toString('base64url');\n const result = await this.retry<{\n link: boolean;\n returnTo: string;\n policy?: SessionPolicy;\n }>(async (time) => {\n const records = await this.records(), slot = this.flows(records).find(s => s.value?.id === flow.flow.id), f = slot?.value, current = connections(records).find(c => c.id === methodId), policy = (await this.readSessionPolicy()).policy, initiatingSession = f?.initiator ? await this.findSession(f.initiator.sessionDigest) : undefined, now = await time();\n if (!slot || !f || f.status !== 'exchanging' || f.epoch !== settings(records).value!.sessionEpoch || f.expiresAt <= now || !current?.enabled || current.generation !== f.generation)\n fail('invalid_oidc_flow', 401);\n if (f.initiator) {\n const u = users(records).find(u => u.id === f.initiator!.userId), session = initiatingSession;\n if (!u || u.generation !== f.initiator.generation || !session?.value || !this.live(u, session.value, now, records))\n fail('forbidden', 403);\n return { mutations: [mutation(slot, 'flow', { ...f, status: 'verified', subject: identityResult.subject, issuer: identityResult.issuer, protocol: identityResult.protocol })], result: { link: true, returnTo: '/#/extensions/user-auth/profile?oidcLink=' + f.id } };\n }\n const id = digest(identityResult.issuer + '\\0' + identityResult.subject), binding = identities(records).find(i => i.id === id), all = users(records);\n let u = binding && all.find(u => u.id === binding.userId);\n const changes: DurableMutation[] = [];\n if (binding && !u)\n fail('corrupt_state', 503);\n if (binding && (binding.connectionId !== current.id || binding.protocol !== identityResult.protocol))\n fail('identity_connection_mismatch', 401);\n if (!u) {\n if (!settings(records).value!.autoCreateUsers)\n fail('unknown_identity', 401);\n if (all.length >= MAX_USERS || identities(records).length >= MAX_IDENTITIES)\n fail('user_limit', 409);\n const userId = randomUUID();\n u = { id: userId, username: 'sso-' + userId, displayName: identityResult.displayName, disabled: false, generation: 1, passwordHash: '', temporary: false };\n changes.push(this.userMutation({ key: 'user:' + userId, version: 0, value: null }, u));\n const identity: Identity = { id, userId, connectionId: current.id, issuer: identityResult.issuer, subject: identityResult.subject, protocol: identityResult.protocol };\n changes.push(mutation(entry(records, 'identity:' + id, 'identity', null), 'identity', identity));\n }\n if (u.disabled)\n fail('disabled_user', 401);\n const sessions = slots(records, 'session', MAX_SESSIONS, validateSession), session = sessions.find(s => !s.value || !this.live(all.find(u => u.id === s.value!.administratorId) ?? null, s.value, now, records));\n if (!session)\n fail('session_limit', 429);\n changes.push(mutation(session, 'session', { digest: digest(token), administratorId: u.id, generation: u.generation, created: now, touched: now, transport: 'cookie', policy, epoch: settings(records).value!.sessionEpoch, connectionId: current.id, connectionGeneration: current.generation }), mutation(slot, 'flow', { ...f, status: 'consumed' }), this.audit(records, u.id, 'oidc.login', now));\n return { mutations: changes, result: { link: false, returnTo: f.returnTo, policy } };\n });\n const headers = new Headers({ 'location': new URL(result.returnTo, publicOrigin).href, 'cache-control': 'no-store' });\n headers.append('set-cookie', this.flowCookie('', 0));\n if (!result.link && result.policy)\n headers.append('set-cookie', cookie(request, token, this.cookieAge(result.policy), publicOrigin));\n return new Response(null, { status: 302, headers });\n }\n catch (error) {\n const code=error instanceof AccountError?error.code:'oidc_failed';\n await this.recordFailure('oidc.login',error);\n try {\n return new Response(null, { status: 302, headers: { location: this.publicOrigin() + '/#/login?oidcError=' + encodeURIComponent(code), 'cache-control': 'no-store', 'set-cookie': this.flowCookie('', 0) } });\n }\n catch {\n return safe(error);\n }\n }\n finally {\n if (verifierRef) {\n try {\n await this.deleteSecret(verifierRef);\n }\n catch { }\n }\n }\n }\n private async finishLink(c: ControlApiHandlerContext, id: string): Promise<Response> {\n return this.retry(async (time) => {\n const { records, user } = await this.guard(c, time), slot = this.flows(records).find(s => s.value?.id === id), f = slot?.value, now = await time(), connection = f && connections(records).find(x => x.id === f.connectionId), issued = this.subjects.get(c.subject!)!;\n if (!slot || !f || f.status !== 'verified' || f.epoch !== settings(records).value!.sessionEpoch || f.expiresAt <= now || !f.subject || !f.issuer || !f.protocol || !f.initiator || f.initiator.userId !== user.id || f.initiator.generation !== user.generation || f.initiator.sessionDigest !== issued.digest || !connection?.enabled || connection.generation !== f.generation)\n fail('invalid_oidc_flow', 401);\n const identity: Identity = { id: digest(f.issuer + '\\0' + f.subject), userId: user.id, connectionId: connection.id, issuer: f.issuer, subject: f.subject, protocol: f.protocol };\n if (identities(records).some(i => i.id === identity.id))\n fail('identity_exists', 409);\n if (identities(records).length >= MAX_IDENTITIES)\n fail('identity_limit', 409);\n const u = records.find(r => r.key === 'user:' + user.id)!;\n return { mutations: [mutation(entry(records, 'identity:' + identity.id, 'identity', null), 'identity', identity), this.userMutation({ key: u.key, version: u.version, value: user }, { ...user, generation: next(user.generation) }), mutation(slot, 'flow', { ...f, status: 'consumed' }), this.audit(records, user.id, 'identity.link', now)], result: json({ ok: true }) };\n });\n }\n}\nexport function createControl(host: ControlHostContext, dependencies: Dependencies = {}): UserAuthControl { return new UserAuthControl(host, dependencies); }\nexport const api = [\n { path: '/password', methods: ['POST'], handler: 'changePassword' },\n { path: '/logout', methods: ['POST'], handler: 'logout' },\n { path: '/self', methods: ['GET'], handler: 'self' },\n { path: '/session-policy', methods: ['GET', 'PUT'], handler: 'sessionPolicy' },\n ...[['/users', ['GET', 'POST'], 'users'], ['/users/update', ['PUT'], 'updateUser'], ['/users/password', ['POST'], 'resetUserPassword'], ['/identities', ['GET', 'POST', 'DELETE'], 'identities'], ['/login-connections', ['GET', 'POST', 'PUT', 'DELETE'], 'loginConnections'], ['/login-connections/discover', ['POST'], 'discoverLoginConnection'], ['/login-settings', ['GET', 'PUT'], 'loginSettings'], ['/turnstile', ['GET', 'PUT'], 'turnstile'], ['/identities/link/start', ['POST'], 'beginIdentityLink'], ['/identities/link/finish', ['POST'], 'finishIdentityLink']].map(([path, methods, handler]) => ({ path, methods, handler })),\n] as const;\nexport const rpc = [], controlApi = api, controlRpc = rpc;\nexport async function readManagementSetup(state: StateReader): Promise<{\n initialized: boolean;\n}> {\n const records = await state.list(), setup = setupRecord(records);\n slots(records, 'session', MAX_SESSIONS, validateSession);\n slots(records, 'failure', MAX_FAILURES, validateFailure);\n const policy = records.find(r => r.key === 'session-policy');\n if (policy)\n validateSessionPolicy(envelope(policy.value, 'policy'), 'corrupt_state', 503);\n return { initialized: setup.value.phase === 'ready' };\n}\n/** Only the stopped-instance host may create the namespace or rotate its code. */\nexport async function prepareInitialization(context: RecoveryContext): Promise<{\n code: string;\n expiresAt: number;\n}> {\n const state = context.durableState, now = context.now ?? Date.now;\n for (let i = 0; i < 64; i++) {\n const records = await state.list(), fresh = !records.length;\n if (!fresh)\n await readManagementSetup(state);\n const setup = fresh ? undefined : setupRecord(records);\n if (setup?.value.phase === 'ready')\n fail('already_initialized', 409);\n const clock = fresh ? { version: 0, value: wallTime(now) } : await observeClock(state, now), code = randomBytes(32).toString('base64url'), expiresAt = clock.value + 30 * 60000;\n try {\n await state.transact([{ key: 'setup', expectedVersion: setup?.version ?? 0, value: asJson({ schema: ACCOUNT_RECORD_SCHEMA, setup: { phase: 'uninitialized', code: { digest: digest(code), expiresAt } } }) }, clockMutation(clock)]);\n return { code, expiresAt };\n }\n catch (e) {\n if (!isDurableStateConflictError(e))\n throw e;\n }\n }\n return fail('version_conflict', 409);\n}\n/** An explicit offline reset restores only the stable recovery anchor. */\nexport async function recoverIdentity(input: unknown, context: RecoveryContext) {\n const b = object(input);\n exact(b, ['operation', 'username', 'password', 'passwordConfirmation', 'reason', 'disableTurnstile']);\n if (b.operation !== 'reset' || (b.disableTurnstile !== undefined && !['', 'yes', 'no'].includes(b.disableTurnstile as string)))\n fail('invalid_input');\n const name = username(b.username), p = password(b.password);\n if (b.passwordConfirmation !== p)\n fail('password_confirmation');\n if (typeof b.reason !== 'string' || !b.reason.trim() || b.reason.length > 512)\n fail('invalid_reason');\n const state = context.durableState, now = context.now ?? Date.now, hash = await Bun.password.hash(p, { algorithm: 'argon2id', memoryCost: 65536, timeCost: 3 });\n for (let i = 0; i < 64; i++) {\n const records = await state.list();\n validateKeys(records);\n const anchor = records.find(r => r.key === 'recovery-anchor');\n let anchorId: string | undefined;\n if (anchor) {\n const id = envelope(anchor.value, 'userId');\n if (typeof id !== 'string' || !/^[a-f0-9-]{36}$/.test(id))\n fail('corrupt_state', 503);\n anchorId = id;\n }\n // Recovery deliberately does not accept a previous record schema or infer an anchor from a username.\n for (const r of records)\n if ((r.value as {\n schema?: unknown;\n })?.schema !== ACCOUNT_RECORD_SCHEMA)\n fail('corrupt_state', 503);\n const id = anchorId ?? randomUUID(), record = records.find(r => r.key === 'user:' + id);\n let prior: User | undefined;\n if (record) {\n try {\n prior = validateUser(envelope(record.value, 'user'));\n }\n catch (error) {\n if (!(error instanceof AccountError))\n throw error;\n }\n }\n const other = records.filter(r => r.key.startsWith('user:') && r.key !== 'user:' + id).map(r => validateUser(envelope(r.value, 'user')));\n if (other.some(u => u.username === name))\n fail('username_exists', 409);\n const s = settings(records), turn = turnstile(records), clockRecord = records.find(r => r.key === 'clock');\n let observed = 0;\n try {\n observed = clockValue(clockRecord);\n }\n catch (error) {\n if (!(error instanceof AccountError))\n throw error;\n }\n const at = Math.max(observed, wallTime(now)), user: User = { id, username: name, displayName: prior?.displayName ?? name, disabled: false, generation: next(prior?.generation ?? 0) }, credential = records.find(r => r.key === 'credential:' + id);\n const failures = slots(records, 'failure', MAX_FAILURES, validateFailure);\n slots(records, 'session', MAX_SESSIONS, validateSession);\n connections(records);\n identities(records);\n const changes: DurableMutation[] = [\n { key: 'user:' + id, expectedVersion: record?.version ?? 0, value: asJson({ schema: ACCOUNT_RECORD_SCHEMA, user }) },\n { key: 'credential:' + id, expectedVersion: credential?.version ?? 0, value: { schema: ACCOUNT_RECORD_SCHEMA, credential: { passwordHash: hash, temporary: false } } },\n { key: 'recovery-anchor', expectedVersion: anchor?.version ?? 0, value: { schema: ACCOUNT_RECORD_SCHEMA, userId: id } },\n { key: 'setup', expectedVersion: records.find(r => r.key === 'setup')?.version ?? 0, value: { schema: ACCOUNT_RECORD_SCHEMA, setup: { phase: 'ready' } } },\n { key: 'clock', expectedVersion: clockRecord?.version ?? 0, value: { schema: ACCOUNT_RECORD_SCHEMA, observedThrough: at } },\n mutation(s, 'settings', { ...s.value!, sessionEpoch: next(s.value!.sessionEpoch), failureEpoch: next(Math.max(s.value!.failureEpoch, ...failures.map(f => f.value?.epoch ?? 0))) }),\n { key: 'recovery-summary', expectedVersion: records.find(r => r.key === 'recovery-summary')?.version ?? 0, value: { schema: ACCOUNT_RECORD_SCHEMA, userId: id, reason: b.reason, at } },\n mutation(turn, 'turnstile', { ...turn.value!, ...(b.disableTurnstile === 'yes' ? {enabled: false} : {}) }),\n ];\n try {\n await state.transact(changes);\n return dto({ ...user, passwordHash: hash, temporary: false });\n }\n catch (e) {\n if (!isDurableStateConflictError(e))\n throw e;\n }\n }\n return fail('version_conflict', 409);\n}\nexport default { createControl, readManagementSetup, offlineRecovery: { kind: 'identity', prepareInitialization,\n prompts: [{ name: 'username', label: 'Recovery username', secret: false }, { name: 'password', label: 'New password', secret: true }, { name: 'passwordConfirmation', label: 'Confirm password', secret: true }, { name: 'reason', label: 'Recovery reason', secret: false }, { name: 'disableTurnstile', label: 'Disable Turnstile? Type yes to disable; default no', secret: false }], recover: recoverIdentity } } satisfies ControlPlugin;\n",
8
+ "export class AccountError extends Error {\n constructor(readonly code: string, readonly status = 400) { super(code); }\n}\nexport function fail(code: string, status = 400): never { throw new AccountError(code, status); }\n",
6
9
  "/** Shared process sink; the public SDK must not bundle file transports into plugins. */\ntype Context = Readonly<Record<string, unknown>>;\ntype LogMethod = { (context: Context, message?: string): void; (message: string): void };\nexport interface PluginLogSink {\n info: LogMethod; warn: LogMethod; error: LogMethod; debug: LogMethod; fatal: LogMethod;\n child(bindings: Context): PluginLogSink;\n}\nconst sinkKey = Symbol.for('@jeffusion/bungee/plugin-log-sink');\nexport function installPluginLogSink(sink: PluginLogSink): void {\n (globalThis as Record<symbol, unknown>)[sinkKey] = sink;\n}\nfunction createLogger(bindings: Context = {}): PluginLogSink {\n const method = (level: 'info' | 'warn' | 'error' | 'debug' | 'fatal'): LogMethod =>\n (value: Context | string, message?: string) => {\n const sink = (globalThis as Record<symbol, unknown>)[sinkKey] as PluginLogSink | undefined;\n if (sink) {\n if (typeof value === 'string') sink[level](bindings, value);\n else sink[level]({...bindings, ...value}, message);\n } else if (level !== 'debug' || process.env.LOG_LEVEL === 'debug') {\n const write = level === 'fatal' ? console.error : console[level];\n write(message ?? (typeof value === 'string' ? value : ''), typeof value === 'string' ? bindings : {...bindings, ...value});\n }\n };\n return {info: method('info'), warn: method('warn'), error: method('error'), debug: method('debug'),\n fatal: method('fatal'), child: extra => createLogger({...bindings, ...extra})};\n}\nexport const logger = createLogger();\n",
7
10
  "/**\n * Hook 实现类\n *\n * 提供 4 种 Hook 类型的实现:\n * - AsyncParallelHook: 异步并行执行\n * - AsyncSeriesHook: 异步串行执行\n * - AsyncSeriesBailHook: 异步串行可中断\n * - AsyncSeriesWaterfallHook: 异步串行瀑布\n */\n\nimport { logger } from '../plugin-logger';\n/** Host-supplied view refresh, run between every waterfall tap. */\nexport const WATERFALL_VIEW_TRANSFORM = Symbol('waterfall-view-transform');\nimport type {\n TapInfo,\n Tap,\n IAsyncParallelHook,\n IAsyncSeriesHook,\n IAsyncSeriesBailHook,\n IAsyncSeriesWaterfallHook,\n IAsyncSeriesMapHook,\n HookStats,\n} from './types';\n\n/**\n * 标准化 TapInfo\n */\nfunction normalizeTapInfo(info: TapInfo | string): TapInfo {\n if (typeof info === 'string') {\n return { name: info, stage: 0 };\n }\n return { ...info, stage: info.stage ?? 0 };\n}\n\n/**\n * 基础 Hook 类\n */\nabstract class BaseHook<T extends any[]> {\n protected taps: Tap<T, any>[] = [];\n protected name: string;\n protected callCount = 0;\n protected totalTimeMs = 0;\n\n constructor(name?: string) {\n this.name = name ?? 'anonymous';\n }\n\n /**\n * 同步注册\n */\n tap(info: TapInfo | string, fn: (...args: T) => any): void {\n const tapInfo = normalizeTapInfo(info);\n this.taps.push({ info: tapInfo, type: 'sync', fn });\n this.sortTaps();\n }\n\n /**\n * 异步回调风格注册\n */\n tapAsync(info: TapInfo | string, fn: (...args: any[]) => void): void {\n const tapInfo = normalizeTapInfo(info);\n this.taps.push({ info: tapInfo, type: 'async', fn });\n this.sortTaps();\n }\n\n /**\n * Promise 风格注册\n */\n tapPromise(info: TapInfo | string, fn: (...args: T) => Promise<any>): void {\n const tapInfo = normalizeTapInfo(info);\n this.taps.push({ info: tapInfo, type: 'promise', fn });\n this.sortTaps();\n }\n\n /**\n * 检查是否有注册的回调\n */\n hasCallbacks(): boolean {\n return this.taps.length > 0;\n }\n\n /**\n * 获取统计信息\n */\n getStats(): HookStats {\n return {\n name: this.name,\n tapCount: this.taps.length,\n callCount: this.callCount,\n totalTimeMs: this.totalTimeMs,\n avgTimeMs: this.callCount > 0 ? this.totalTimeMs / this.callCount : 0,\n };\n }\n\n /**\n * 重置统计信息\n */\n resetStats(): void {\n this.callCount = 0;\n this.totalTimeMs = 0;\n }\n\n /**\n * 清空所有注册的回调\n */\n clear(): void {\n this.taps = [];\n }\n\n /**\n * 按 stage 排序(稳定排序)\n */\n private sortTaps(): void {\n this.taps.sort((a, b) => (a.info.stage ?? 0) - (b.info.stage ?? 0));\n }\n\n /**\n * 执行单个 tap\n */\n protected async executeTap<R>(\n tap: Tap<T, R>,\n args: T\n ): Promise<R | undefined> {\n try {\n if (tap.type === 'sync') {\n return tap.fn(...args);\n } else if (tap.type === 'promise') {\n return await tap.fn(...args);\n } else {\n // async (callback style)\n return await new Promise<R | undefined>((resolve, reject) => {\n const done = (err?: Error, result?: R) => {\n if (err) reject(err);\n else resolve(result);\n };\n tap.fn(...args, done);\n });\n }\n } catch (error) {\n logger.error(\n { error, hookName: this.name, pluginName: tap.info.name },\n 'Error in hook callback'\n );\n throw error;\n }\n }\n}\n\n/** Synchronous providers use the same registration, ordering and statistics as async hooks. */\nexport class SyncBailHook<T extends any[] = [], R = unknown> extends BaseHook<T> {\n override tapAsync(): never { throw new Error('synchronous provider requires tap'); }\n override tapPromise(): never { throw new Error('synchronous provider requires tap'); }\n call(...args: T): R | undefined {\n const started = performance.now();\n this.callCount++;\n try {\n for (const tap of this.taps) {\n const result = tap.fn(...args);\n if (result && typeof result.then === 'function') throw new Error('synchronous provider returned a Promise');\n if (result !== undefined) return result as R;\n }\n return undefined;\n } finally { this.totalTimeMs += performance.now() - started; }\n }\n}\n\n/**\n * 异步并行 Hook\n * 所有回调并行执行,全部完成后返回\n */\nexport class AsyncParallelHook<T extends any[] = []>\n extends BaseHook<T>\n implements IAsyncParallelHook<T>\n{\n async promise(...args: T): Promise<void> {\n if (this.taps.length === 0) return;\n\n const startTime = performance.now();\n this.callCount++;\n\n try {\n // 并行执行所有回调,错误独立处理不影响其他\n await Promise.all(\n this.taps.map(async (tap) => {\n try {\n await this.executeTap(tap, args);\n } catch (error) {\n // 并行 Hook 中单个回调的错误不应影响其他回调\n logger.error(\n { error, hookName: this.name, pluginName: tap.info.name },\n 'Error in parallel hook callback (ignored)'\n );\n }\n })\n );\n } finally {\n this.totalTimeMs += performance.now() - startTime;\n }\n }\n}\n\n/**\n * 异步串行 Hook\n * 所有回调按顺序串行执行\n */\nexport class AsyncSeriesHook<T extends any[] = []>\n extends BaseHook<T>\n implements IAsyncSeriesHook<T>\n{\n async promise(...args: T): Promise<void> {\n if (this.taps.length === 0) return;\n\n const startTime = performance.now();\n this.callCount++;\n\n try {\n for (const tap of this.taps) {\n await this.executeTap(tap, args);\n }\n } finally {\n this.totalTimeMs += performance.now() - startTime;\n }\n }\n}\n\n/**\n * 异步串行可中断 Hook\n * 任意回调返回非 undefined 值则停止执行并返回该值\n */\nexport class AsyncSeriesBailHook<T extends any[] = [], R = any>\n extends BaseHook<T>\n implements IAsyncSeriesBailHook<T, R>\n{\n async promise(...args: T): Promise<R | undefined> {\n if (this.taps.length === 0) return undefined;\n\n const startTime = performance.now();\n this.callCount++;\n\n try {\n for (const tap of this.taps) {\n const result = await this.executeTap<R>(tap, args);\n if (result !== undefined) {\n logger.debug(\n { hookName: this.name, pluginName: tap.info.name },\n 'Hook bailed with result'\n );\n return result;\n }\n }\n return undefined;\n } finally {\n this.totalTimeMs += performance.now() - startTime;\n }\n }\n}\n\n/**\n * 异步串行瀑布 Hook\n * 每个回调的返回值作为下一个回调的第一个参数\n */\nexport class AsyncSeriesWaterfallHook<T, A extends any[] = []>\n extends BaseHook<[T, ...A]>\n implements IAsyncSeriesWaterfallHook<T, A>\n{\n async promise(value: T, ...args: A): Promise<T> {\n if (this.taps.length === 0) return value;\n\n const startTime = performance.now();\n this.callCount++;\n\n try {\n let current = value;\n for (const tap of this.taps) {\n const result = await this.executeTap<T>(tap, [current, ...args] as [T, ...A]);\n // 只有返回非 undefined 时才更新值\n if (result !== undefined) {\n const transform = args[0]?.[WATERFALL_VIEW_TRANSFORM];\n current = typeof transform === 'function' ? await transform(result,current) : result;\n }\n }\n return current;\n } finally {\n this.totalTimeMs += performance.now() - startTime;\n }\n }\n}\n\n/**\n * 异步串行映射 Hook\n * 支持 N:M 转换:每个回调处理输入,可以返回 0 到多个输出\n *\n * 执行流程:\n * 1. 初始输入:单个 chunk\n * 2. 每个插件处理当前的所有 chunks,返回新的 chunks 数组\n * 3. 下一个插件处理上一步的所有输出\n *\n * 返回值约定:\n * - null/undefined: 不处理,原样输出当前 chunk\n * - []: 缓冲当前 chunk,不输出(N:0)\n * - [chunk]: 1:1 转换\n * - [chunk1, chunk2, ...]: 1:M 拆分\n *\n * 性能优化:\n * - 同步优先执行:sync tap 直接同步调用,跳过 Promise 开销\n * - 适用于流式响应处理等高频调用场景\n */\nexport class AsyncSeriesMapHook<T, A extends any[] = []>\n extends BaseHook<[T, ...A]>\n implements IAsyncSeriesMapHook<T, A>\n{\n /**\n * 同步执行单个 tap(跳过 Promise 开销)\n */\n private executeTapSync<R>(tap: Tap<[T, ...A], R>, args: [T, ...A]): R | undefined {\n try {\n return tap.fn(...args);\n } catch (error) {\n logger.error(\n { error, hookName: this.name, pluginName: tap.info.name },\n 'Error in hook callback'\n );\n throw error;\n }\n }\n\n async promise(value: T, ...args: A): Promise<T[]> {\n // 如果没有注册任何回调,直接返回原始值\n if (this.taps.length === 0) return [value];\n\n const startTime = performance.now();\n this.callCount++;\n\n try {\n // 初始输入为单个 chunk\n let chunks: T[] = [value];\n\n // 依次应用每个插件的转换\n for (const tap of this.taps) {\n const newChunks: T[] = [];\n\n // 对当前的每个 chunk 应用转换\n for (const chunk of chunks) {\n try {\n // 同步优先执行:sync tap 直接同步调用,跳过 Promise 开销\n const result = tap.type === 'sync'\n ? this.executeTapSync<T[] | null | undefined>(tap, [chunk, ...args] as [T, ...A])\n : await this.executeTap<T[] | null | undefined>(tap, [chunk, ...args] as [T, ...A]);\n\n if (result === null || result === undefined) {\n // 不处理,原样输出\n newChunks.push(chunk);\n } else if (Array.isArray(result)) {\n // N:M 转换\n // [] = 缓冲(不输出)\n // [item] = 1:1 转换\n // [item1, item2, ...] = 1:M 拆分\n newChunks.push(...result);\n } else {\n // 非法返回值,警告并原样输出\n logger.warn(\n { hookName: this.name, pluginName: tap.info.name, result },\n 'AsyncSeriesMapHook callback must return an array or null'\n );\n newChunks.push(chunk);\n }\n } catch (error) {\n // 单个 chunk 处理失败,记录错误并原样输出\n logger.error(\n { error, hookName: this.name, pluginName: tap.info.name },\n 'Error in AsyncSeriesMapHook callback'\n );\n if ((args[0] as { strict?: boolean } | undefined)?.strict) {\n throw error;\n }\n newChunks.push(chunk);\n }\n }\n\n chunks = newChunks;\n }\n\n return chunks;\n } finally {\n this.totalTimeMs += performance.now() - startTime;\n }\n }\n}\n",
8
- "import type { PluginDurableState, DurableJson } from './plugin-durable-state';\n\n/** Anonymous is an explicit, signed data identity; it carries no key authority. */\nexport type DataPrincipal = { readonly domain: string; readonly keyId: string; readonly credentialVersion: number };\nexport const ANONYMOUS_PRINCIPAL: DataPrincipal = Object.freeze({domain: 'anonymous', keyId: '', credentialVersion: 0});\nexport interface AdmissionRequirement { readonly plugin: string; readonly routeIds: readonly string[] }\n/** Public contracts. Business rules belong to the implementing plugin. */\nexport interface ManagementSubject {\n readonly id: string;\n readonly provider: string;\n readonly capabilities: readonly string[];\n readonly requiresPasswordChange?: boolean;\n}\nexport interface ManagementProvider {\n authenticate(request: Request): Promise<ManagementSubject | null>;\n authorize(subject: ManagementSubject, capability: string): Promise<boolean>;\n login(request: Request): Promise<Response>;\n logout(request: Request): Promise<Response>;\n bootstrap(input: unknown): Promise<void>;\n hasIdentity(): Promise<boolean>;\n revokeSessions(): Promise<void>;\n validateWrite?(request: Request): void;\n csrfToken?(request: Request): string | undefined;\n /** Optional browser cookie renewal after successful session verification. Must not extend the server-side absolute deadline. */\n sessionCookie?(request: Request): Promise<string | undefined>;\n}\nexport interface AdmissionTarget {\n /** Host-pinned entry scope for one internal handoff. */\n readonly entryRouteId?: string;\n readonly requestId: string;\n readonly attemptId: string;\n readonly principal: DataPrincipal;\n readonly routeId: string;\n readonly serviceId: string | null;\n readonly upstreamId: string;\n readonly url: string;\n readonly model: string | null;\n readonly now: number;\n}\nexport interface AdmissionDenial {\n readonly error: string;\n readonly status: 401 | 403 | 429 | 503 | 422;\n readonly retryAfter?: number;\n}\nexport interface AdmissionPlan {\n /** A complete JSON state replacement, staged by Host before the common decision. */\n readonly state?: DurableJson;\n /** Immutable policy snapshot retained by the grant for subsequent attempts. */\n readonly snapshot?: DurableJson;\n readonly denial?: AdmissionDenial;\n}\nexport interface IngressPlugin {\n /** Effective policy demand; no policy means no content decoding. */\n bodyRequirements(target: AdmissionTarget, policy: DurableJson): { readonly request: 'none' | 'json-read' };\n /** Optional per-principal state. Policies are frozen; plans receive only this key's clones.\n * Expiry must mean absence is behaviorally equivalent to retaining the state. */\n keyedState?: {\n readonly capacity: number;\n policyForKey(policy: DurableJson, keyId: string): DurableJson;\n expiresAt(state: DurableJson): number;\n reconcile(state: DurableJson, policy: DurableJson, now: number): DurableJson;\n };\n authenticate?(request: Request, policy: DurableJson, now: number): DataPrincipal | null;\n resolveIdentity?(target: AdmissionTarget, policy: DurableJson): DataPrincipal;\n /** Pure access decision before preparation/cache reuse; never plans or debits state. */\n authorize?(target: AdmissionTarget, policy: DurableJson): AdmissionDenial | null;\n plan(target: AdmissionTarget, policy: DurableJson, state: DurableJson): AdmissionPlan;\n beforeAttempt?(target: AdmissionTarget, snapshot: DurableJson): AdmissionDenial | null;\n}\nexport interface IngressPluginModule { createIngress(): IngressPlugin }\nexport interface PluginStateRpcContext {\n readonly state: PluginDurableState;\n readonly requestId: string;\n readonly attemptId: string;\n readonly principal: DataPrincipal;\n}\nexport interface PluginPolicyPublication {\n readonly version: number;\n readonly value: DurableJson;\n}\n",
11
+ "import type { PluginDurableState, DurableJson } from './plugin-durable-state';\n\n/** Anonymous is an explicit, signed data identity; it carries no key authority. */\nexport type DataPrincipal = { readonly domain: string; readonly keyId: string; readonly credentialVersion: number };\nexport const ANONYMOUS_PRINCIPAL: DataPrincipal = Object.freeze({domain: 'anonymous', keyId: '', credentialVersion: 0});\nexport interface AdmissionRequirement { readonly plugin: string; readonly routeIds: readonly string[] }\n/** Public contracts. Business rules belong to the implementing plugin. */\nexport interface ManagementSubject {\n readonly id: string;\n readonly provider: string;\n readonly capabilities: readonly string[];\n readonly requiresPasswordChange?: boolean;\n}\nexport interface ManagementProvider {\n setupStatus(): Promise<'uninitialized' | 'ready'>;\n initialize(request: Request): Promise<Response>;\n authenticate(request: Request): Promise<ManagementSubject | null>;\n authorize(subject: ManagementSubject, capability: string): Promise<boolean>;\n login(request: Request): Promise<Response>;\n /** Public login interactions are dispatched only to the selected provider. */\n loginOptions?(request: Request): Promise<Response>;\n beginLogin?(request: Request): Promise<Response>;\n completeLogin?(request: Request): Promise<Response>;\n logout(request: Request): Promise<Response>;\n bootstrap(input: unknown): Promise<void>;\n hasIdentity(): Promise<boolean>;\n revokeSessions(): Promise<void>;\n validateWrite?(request: Request): void;\n csrfToken?(request: Request): string | undefined;\n /** Optional browser cookie renewal after successful session verification. Must not extend the server-side absolute deadline. */\n sessionCookie?(request: Request): Promise<string | undefined>;\n}\nexport interface AdmissionTarget {\n /** Host-pinned entry scope for one internal handoff. */\n readonly entryRouteId?: string;\n readonly requestId: string;\n readonly attemptId: string;\n readonly principal: DataPrincipal;\n readonly routeId: string;\n readonly serviceId: string | null;\n readonly upstreamId: string;\n readonly url: string;\n readonly model: string | null;\n readonly now: number;\n}\nexport interface AdmissionDenial {\n readonly error: string;\n readonly status: 401 | 403 | 429 | 503 | 422;\n readonly retryAfter?: number;\n}\nexport interface AdmissionPlan {\n /** A complete JSON state replacement, staged by Host before the common decision. */\n readonly state?: DurableJson;\n /** Immutable policy snapshot retained by the grant for subsequent attempts. */\n readonly snapshot?: DurableJson;\n readonly denial?: AdmissionDenial;\n}\nexport interface IngressPlugin {\n /** Effective policy demand; no policy means no content decoding. */\n bodyRequirements(target: AdmissionTarget, policy: DurableJson): { readonly request: 'none' | 'json-read' };\n /** Optional per-principal state. Policies are frozen; plans receive only this key's clones.\n * Expiry must mean absence is behaviorally equivalent to retaining the state. */\n keyedState?: {\n readonly capacity: number;\n policyForKey(policy: DurableJson, keyId: string): DurableJson;\n expiresAt(state: DurableJson): number;\n reconcile(state: DurableJson, policy: DurableJson, now: number): DurableJson;\n };\n authenticate?(request: Request, policy: DurableJson, now: number): DataPrincipal | null;\n resolveIdentity?(target: AdmissionTarget, policy: DurableJson): DataPrincipal;\n /** Pure access decision before preparation/cache reuse; never plans or debits state. */\n authorize?(target: AdmissionTarget, policy: DurableJson): AdmissionDenial | null;\n plan(target: AdmissionTarget, policy: DurableJson, state: DurableJson): AdmissionPlan;\n beforeAttempt?(target: AdmissionTarget, snapshot: DurableJson): AdmissionDenial | null;\n}\nexport interface IngressPluginModule { createIngress(): IngressPlugin }\nexport interface PluginStateRpcContext {\n readonly state: PluginDurableState;\n readonly requestId: string;\n readonly attemptId: string;\n readonly principal: DataPrincipal;\n}\nexport interface PluginPolicyPublication {\n readonly version: number;\n readonly value: DurableJson;\n}\n",
9
12
  "import type { Database } from 'bun:sqlite';\n\n/** Plugin state initialization owns this DDL; constructors never modify schema. */\nexport const PLUGIN_DURABLE_STATE_SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS plugin_durable_records (\n namespace TEXT NOT NULL, key TEXT NOT NULL, version INTEGER NOT NULL CHECK(version > 0),\n value_json TEXT NOT NULL, PRIMARY KEY(namespace, key)\n) STRICT;\n`;\nexport type DurableJson = null | boolean | number | string | DurableJson[] | { [key: string]: DurableJson };\nexport interface DurableRecord { readonly key: string; readonly version: number; readonly value: DurableJson }\nexport interface DurableMutation { key: string; expectedVersion: number; value: DurableJson }\n/** Pure data outbox request; callbacks and command identifiers are never accepted. */\nexport interface DurableTransactionOptions {\n readonly outbox: { readonly topic: string; readonly major: number;\n readonly maxEvents: number; readonly payload: Uint8Array };\n}\nexport interface PluginDurableState {\n get(key: string): Promise<DurableRecord | null>;\n list(): Promise<readonly DurableRecord[]>;\n transact(mutations: readonly DurableMutation[], options?: DurableTransactionOptions): Promise<readonly DurableRecord[]>;\n}\n/** Synchronous leaf, usable only by storage workers and offline tooling. */\nexport interface StorageDurableState {\n get(key: string): DurableRecord | null;\n list(): readonly DurableRecord[];\n transact(mutations: readonly DurableMutation[], extend?: () => void): readonly DurableRecord[];\n}\nexport class DurableStateConflictError extends Error {\n readonly code = 'durable_state_conflict';\n constructor() { super('Durable state version conflict'); this.name = 'DurableStateConflictError'; }\n}\n/** Plugins load as independent bundles, so the host's error has a different constructor. */\nexport function isDurableStateConflictError(error: unknown): error is DurableStateConflictError {\n return error instanceof Error && 'code' in error && error.code === 'durable_state_conflict';\n}\nconst MAX_BYTES = 1024 * 1024;\nfunction identifier(value: unknown): asserts value is string {\n if (typeof value !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/.test(value)) throw new Error('Invalid durable state identifier');\n}\n/** Reject objects with behavior, lossy JSON values and cycles before JSON.stringify. */\nfunction encode(value: unknown): string {\n const ancestors = new Set<object>();\n function check(current: unknown, depth: number): void {\n if (depth > 64) throw new Error('Durable state nesting limit exceeded');\n if (current === null || typeof current === 'string' || typeof current === 'boolean') return;\n if (typeof current === 'number' && Number.isFinite(current)) return;\n if (typeof current !== 'object' || current === null || ancestors.has(current)) throw new Error('Durable state must be pure JSON');\n const array = Array.isArray(current);\n if (!array && Object.getPrototypeOf(current) !== Object.prototype && Object.getPrototypeOf(current) !== null) throw new Error('Durable state must be pure JSON');\n ancestors.add(current);\n const descriptors = Object.getOwnPropertyDescriptors(current);\n if (Reflect.ownKeys(current).some(key => typeof key === 'symbol')) throw new Error('Durable state must be pure JSON');\n if (array) {\n const length = (current as unknown[]).length;\n const indices = Object.keys(descriptors).filter(key => key !== 'length');\n if (indices.length !== length || indices.some((key, index) => key !== String(index))) throw new Error('Durable state must be pure JSON');\n }\n for (const [key, descriptor] of Object.entries(descriptors)) {\n if (array && key === 'length') continue;\n if (!descriptor.enumerable || !('value' in descriptor)) throw new Error('Durable state must be pure JSON');\n check(descriptor.value, depth + 1);\n }\n ancestors.delete(current);\n }\n check(value, 0);\n const json = JSON.stringify(value);\n if (Buffer.byteLength(json) > MAX_BYTES) throw new Error('Durable state size limit exceeded');\n return json;\n}\n/** Validate data before IPC structured cloning can erase prototypes or evaluate getters. */\nexport function validateDurableJson(value: unknown): void { encode(value); }\ntype Row = { key: string; version: number; value_json: string };\nfunction record(row: Row): DurableRecord {\n return Object.freeze({ key: row.key, version: row.version, value: JSON.parse(row.value_json) as DurableJson });\n}\n\n/** Host-only factory. Inject only the returned namespace capability into trusted plugins.\n * Consumers validate their own record schema. expectedVersion=0 requires absence.\n * Null values are retained records, so versions never reset.\n */\nexport class PluginDurableStateStore {\n constructor(private readonly db: Database) {}\n /**\n * Host-only: the shared database this store's records live in, so a host-owned\n * durable journal can run its own atomic planner/reader against exactly the\n * same `plugin_durable_records` rows the plugin sees. Never exposed through\n * `PluginServices` and never handed to a plugin.\n */\n get database(): Database { return this.db; }\n /** Async SDK shape for offline tools and leaf fixtures; production uses PluginStateClient. */\n forNamespace(namespace: string): PluginDurableState {\n const leaf = this.forStorageNamespace(namespace);\n return Object.freeze({get: async (key: string) => leaf.get(key), list: async () => leaf.list(),\n transact: async (mutations: readonly DurableMutation[], options?: DurableTransactionOptions) => {\n if (options !== undefined) throw new Error('Outbox requires the storage worker');\n return leaf.transact(mutations);\n }});\n }\n forStorageNamespace(namespace: string): StorageDurableState {\n identifier(namespace);\n const db = this.db;\n const get = (key: string): DurableRecord | null => {\n identifier(key);\n const row = db.query<Row, [string, string]>('SELECT key,version,value_json FROM plugin_durable_records WHERE namespace = ? AND key = ?').get(namespace, key);\n return row ? record(row) : null;\n };\n return Object.freeze({\n get,\n list: () => Object.freeze(db.query<Row, [string]>('SELECT key,version,value_json FROM plugin_durable_records WHERE namespace = ? ORDER BY key').all(namespace).map(record)),\n transact: (input: readonly DurableMutation[], extend?: () => void): readonly DurableRecord[] => {\n if (!Array.isArray(input) || input.length === 0 || input.length > 256) throw new Error('Invalid durable state command');\n const keys = new Set<string>();\n const mutations = input.map(mutation => {\n identifier(mutation.key);\n if (keys.has(mutation.key) || !Number.isSafeInteger(mutation.expectedVersion) || mutation.expectedVersion < 0 || mutation.expectedVersion >= Number.MAX_SAFE_INTEGER) throw new Error('Invalid durable state mutation');\n keys.add(mutation.key);\n return { key: mutation.key, expectedVersion: mutation.expectedVersion, json: encode(mutation.value) };\n });\n const commandJson = JSON.stringify(mutations);\n if (Buffer.byteLength(commandJson) > MAX_BYTES) throw new Error('Durable state command size limit exceeded');\n return db.transaction(() => {\n const results: DurableRecord[] = [];\n for (const mutation of mutations) {\n const current = get(mutation.key);\n if ((current?.version ?? 0) !== mutation.expectedVersion) throw new DurableStateConflictError();\n const version = mutation.expectedVersion + 1;\n db.query(`INSERT INTO plugin_durable_records(namespace,key,version,value_json) VALUES (?,?,?,?)\n ON CONFLICT(namespace,key) DO UPDATE SET version=excluded.version,value_json=excluded.value_json`).run(namespace, mutation.key, version, mutation.json);\n results.push(record({ key: mutation.key, version, value_json: mutation.json }));\n }\n extend?.();\n return Object.freeze(results);\n }).immediate();\n },\n });\n }\n}\n",
10
13
  "import { logger } from '../logger';\nimport type { AtomicReadSetResolver } from '../plugin-state/client';\n/**\n * Same-process host RPC adapter (P4): lets the canonical `PluginServiceHost`\n * lifecycle own RPC publications/consumption without a second plugin framework\n * and without faking a wire transport.\n *\n * The parent injects the trusted owner token, endpoint identity, required\n * placement/callee/journal callbacks, and the real host lease callback. Real\n * cross-process transport is NOT implemented: the required placement resolver\n * returns an exact endpoint registered in the exposed runtime, `ambiguous`, or\n * `null` meaning \"use the explicit local channel\". Commands run only through the\n * accepted runtime kernel. Journal-backed policies require `CommandJournal`;\n * application-owned `none` commands may execute without a journal and expose no\n * journal result/reconciliation capability. Caller identity, purpose, scope,\n * leases, and deadlines are host decisions; plugin call options may only carry\n * `signal`/`timeoutMs`/`operationId`, snapshotted without invoking accessors.\n *\n * Command binding errors are mapped once by the kernel to its fixed-code\n * `RpcInvocationError` (own `code`, no cause/message/raw operation id); the\n * client rebuilds a fresh public `RpcServiceError` from that code and the\n * validated operation id of the current call. No error instance is reused.\n */\nimport { assertSupportedServiceDeclarations, isCrossProcessSelfService } from './contracts';\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport { isProxy } from 'node:util/types';\nimport type {\n PluginServiceConsumption,\n PluginServiceDeclarations,\n PluginServiceProcess,\n PluginServicePublication,\n PluginServiceScope,\n} from './contracts';\nimport {\n RpcServiceRuntime,\n type RpcAdmissionGrant,\n type RpcAdmissionRequest,\n type RpcCaller,\n type RpcCommandAction,\n type RpcCommandExecution,\n type RpcCommandExecutor,\n type RpcDrainResult,\n type RpcEndpointBinding,\n type RpcEndpointHandle,\n type RpcHandlerContext,\n type RpcHandlerMap,\n type RpcInvocationErrorCode,\n type RpcInvokeRequest,\n type RpcRuntimeLimits,\n type RpcRuntimeStatus,\n} from './rpc-runtime';\nimport {\n type CommandAtomicPlanner,\n type CommandExternalExecutor,\n type CommandJournal,\n} from './command-journal';\nimport type { AsyncCommandJournal } from '../plugin-state/client';\nimport {\n defineRpcService,\n assertRpcData,\n encodeRpcJson,\n decodeRpcJson,\n RPC_JSON_MAX_BYTES,\n type RpcCallPurpose,\n type InferRpcData,\n type RpcCommandPolicy,\n type RpcJson,\n type RpcMethodDefinition,\n} from './wire-contract';\n\n/* -------------------------------------------------------------------------- */\n/* Fixed-code public errors */\n/* -------------------------------------------------------------------------- */\n\nexport type RpcServiceErrorCode =\n | RpcInvocationErrorCode\n | 'undeclared'\n | 'unavailable'\n | 'ambiguous_placement'\n | 'invalid_registration';\n\nconst SERVICE_ERROR_MESSAGES: Record<RpcServiceErrorCode, string> = {\n unauthorized: 'RPC call is not authorized',\n not_ready: 'RPC endpoint is not ready',\n retired: 'RPC endpoint is retiring',\n revoked: 'RPC endpoint generation was revoked',\n unsupported_method: 'RPC method is not published',\n wrong_purpose: 'RPC method is not published for this purpose',\n invalid_input: 'RPC input is not valid',\n invalid_output: 'RPC output is not valid',\n invalid_operation_id: 'RPC command operation id is invalid',\n overloaded: 'RPC runtime is at capacity',\n cancelled: 'RPC call was cancelled',\n timeout: 'RPC call deadline exceeded',\n unknown: 'RPC command outcome is unknown',\n capability_unavailable: 'RPC command execution is unavailable',\n closed: 'RPC runtime is closed',\n failed: 'RPC call failed',\n conflict: 'RPC command identity conflicts with an existing record',\n expired: 'RPC command result has expired',\n pending: 'RPC command is still pending',\n rejected: 'RPC command was rejected',\n missing: 'RPC command has no stored result',\n storage_failure: 'RPC command storage failed',\n deadlock: 'RPC call chain would deadlock',\n call_depth_exceeded: 'RPC call depth exceeded',\n undeclared: 'RPC service is not declared by the manifest',\n unavailable: 'RPC service is unavailable',\n ambiguous_placement: 'RPC service placement is ambiguous',\n invalid_registration: 'RPC registration is invalid',\n};\n\nconst SERVICE_ERROR_CODES = new Set<RpcServiceErrorCode>(Object.keys(SERVICE_ERROR_MESSAGES) as RpcServiceErrorCode[]);\n\n/** Fixed-code error. It never carries a provider cause, message, or payload. */\nexport class RpcServiceError extends Error {\n readonly name = 'RpcServiceError';\n readonly code: RpcServiceErrorCode;\n readonly operationId: string | null;\n\n constructor(code: RpcServiceErrorCode, operationId: string | null = null) {\n super(SERVICE_ERROR_MESSAGES[code]);\n this.code = code;\n this.operationId = operationId;\n }\n}\n\nfunction ownStringProperty(target: unknown, name: string): string | null {\n if (target === null || (typeof target !== 'object' && typeof target !== 'function')) return null;\n let descriptor: PropertyDescriptor | undefined;\n try { descriptor = Object.getOwnPropertyDescriptor(target, name); } catch { return null; }\n if (descriptor === undefined || !('value' in descriptor) || typeof descriptor.value !== 'string') return null;\n return descriptor.value;\n}\n\n/**\n * Rebuilds a fresh public error from the kernel's fixed code and the validated\n * operation id of THIS call. It never reuses the incoming instance, never reads\n * its operation id, and never reads a cause or message.\n */\nexport function toRpcServiceError(error: unknown, operationId: string | null): RpcServiceError {\n const raw = ownStringProperty(error, 'code');\n const code = raw !== null && SERVICE_ERROR_CODES.has(raw as RpcServiceErrorCode)\n ? raw as RpcServiceErrorCode\n : 'failed';\n return new RpcServiceError(code, operationId);\n}\n\n/* -------------------------------------------------------------------------- */\n/* Public types */\n/* -------------------------------------------------------------------------- */\n\nexport interface RpcCallOptions {\n readonly signal?: AbortSignal;\n readonly timeoutMs?: number;\n readonly operationId?: string;\n}\n\nexport type RpcCommandClientExtras<D extends RpcMethodDefinition> = D extends { readonly command: RpcCommandPolicy }\n ? {\n /** Durable committed result query; runs through the same runtime lease/deadline as execute. */\n queryResult(operationId: string): Promise<InferRpcData<D['output']>>;\n /** Explicit host-authorized reconciliation for an unknown command outcome. */\n reconcile(operationId: string, input: InferRpcData<D['input']>): Promise<InferRpcData<D['output']>>;\n }\n : Record<never, never>;\n\nexport type RpcMethodClient<D extends RpcMethodDefinition> =\n ((input: InferRpcData<D['input']>, options?: RpcCallOptions) => Promise<InferRpcData<D['output']>>)\n & RpcCommandClientExtras<D>;\n\n/** Public plugin-facing RPC client derived from a literal contract. */\nexport type AsyncRpcClient<M extends Record<string, RpcMethodDefinition>> = {\n readonly [K in keyof M]: RpcMethodClient<M[K]>;\n};\n\n/** Logical placement identity, independent of any physical address or generation. */\nexport interface HostRpcServiceDescriptor {\n readonly provider: string;\n readonly service: string;\n readonly major: number;\n readonly kind: 'rpc';\n readonly process: PluginServiceProcess;\n readonly scope: PluginServiceScope;\n}\n\n/** Physical endpoint identity supplied by the trusted host for one owner instance. */\nexport interface HostRpcLifecycleIdentity {\n readonly endpoint: string;\n readonly instance: string;\n readonly generation: number;\n readonly catalog: string;\n /** Trusted callee subject; never derived from plugin input. */\n readonly subject: string;\n}\n\n/** Canonical owner lifecycle view; the adapter never keeps a second copy. */\nexport interface HostRpcLifecycleState {\n readonly ready: boolean;\n readonly retiring: boolean;\n readonly revoked: boolean;\n}\n\n/** Host-minted invocation frame; the real principal lives in the host callee frame. */\nexport interface HostRpcInvocationContext {\n readonly purpose: RpcCallPurpose;\n /** Opaque host correlation token; the leaf only trusts the required resolver. */\n readonly token: object;\n readonly signal?: AbortSignal;\n readonly deadlineAt?: number;\n}\n\nexport interface HostRpcLeaseRequest {\n readonly role: 'caller' | 'callee';\n readonly plugin: string;\n readonly scope: string;\n readonly state: HostRpcLifecycleState;\n readonly purpose: RpcCallPurpose;\n readonly operationId: string | null;\n /** Logical target provider. */\n readonly provider: string;\n}\n\nexport interface HostRpcLeaseGrant {\n readonly release: () => void;\n /** Host-verified existing request lease; only honored for request/attempt. */\n readonly allowRetired?: boolean;\n}\n\nexport type HostRpcAcquireLease = (request: HostRpcLeaseRequest) => HostRpcLeaseGrant;\n\nexport interface HostRpcMethodCapability {\n /** Synchronous private-state CAS planner for a `local-transaction` command. */\n readonly atomic?: CommandAtomicPlanner;\n /** Explicit bounded read set for the production storage Worker. */\n readonly atomicReadSet?: AtomicReadSetResolver;\n /** Reconcile capability for an `external-contract` command. */\n readonly external?: CommandExternalExecutor;\n}\n\nexport type HostRpcCommandCapabilities<M extends Record<string, RpcMethodDefinition>> = {\n readonly [K in keyof M]?: HostRpcMethodCapability;\n};\n\n/** Everything the canonical host exposes for one owner to use RPC services. */\nexport interface HostRpcOwnerInput {\n readonly token: object;\n readonly plugin: string;\n /** Canonical owner scope: `'global'` or a trusted binding scope key. */\n readonly scope: string;\n readonly declarations: PluginServiceDeclarations;\n readonly dependencies: Readonly<Record<string, string>>;\n readonly lifecycle: HostRpcLifecycleIdentity;\n /** Canonical lifecycle source of truth; the adapter copies nothing. */\n readonly getLifecycleState: () => HostRpcLifecycleState;\n readonly acquireLease: HostRpcAcquireLease;\n readonly registerPublication?: (publication: PluginServicePublication) => void;\n readonly registerConsumption?: (consumption: PluginServiceConsumption, localProviderToken?: object) => void;\n readonly onDispose?: (cleanup: () => void) => void;\n readonly canCall?: (target: { readonly provider: string; readonly service: string; readonly major: number; readonly method: string }) => boolean;\n /** Required host invocation-frame resolver; null for plain plugin background calls. */\n readonly resolveInvocationContext: () => HostRpcInvocationContext | null;\n}\n\n/** Trusted peer broker input. This capability is never part of PluginServices. */\nexport interface HostRpcRemoteCallerInput extends HostRpcOwnerInput {\n readonly process: PluginServiceProcess;\n /** Must verify the current authenticated peer frame and logical caller authority. */\n readonly authorizeIncoming: (request: RpcAdmissionRequest, endpoint: NonNullable<ReturnType<RpcServiceRuntime['endpointInfo']>>) => boolean;\n}\n\nexport interface HostRpcRemoteCallerHandle {\n invokeTracked(request: Omit<RpcInvokeRequest, 'caller' | 'callerToken'>): ReturnType<RpcServiceRuntime['invokeTracked']>;\n dispose(): Promise<RpcDrainResult>;\n}\n\n/** Exact placement delegated to the host. `null` means \"use the explicit local channel\". */\nexport type HostRpcPlacementResolution =\n | { readonly kind: 'endpoint'; readonly endpoint: RpcEndpointHandle }\n | { readonly kind: 'ambiguous' }\n | null\n | undefined;\n\nexport interface HostRpcPlacementRequest {\n readonly provider: string;\n readonly service: string;\n readonly major: number;\n readonly method: string;\n readonly scope: PluginServiceScope;\n readonly bindingScope?: string;\n readonly caller: RpcCaller;\n readonly purpose?: RpcCallPurpose;\n}\n\nexport type HostRpcPlacementResolver = (request: HostRpcPlacementRequest) => HostRpcPlacementResolution;\n\nexport interface HostRpcJournalRequest {\n readonly provider: string;\n readonly service: string;\n readonly major: number;\n readonly method: string;\n readonly scope: PluginServiceScope;\n /** Binding scope key when `scope` is `binding`; keeps two bindings apart. */\n readonly bindingScope?: string;\n readonly policy: RpcCommandPolicy;\n readonly atomic?: CommandAtomicPlanner;\n /** Explicit bounded read set for the production storage Worker. */\n readonly atomicReadSet?: AtomicReadSetResolver;\n readonly external?: CommandExternalExecutor;\n}\n\n/** Host-owned durable journal factory; `null` refuses commands for this key. */\nexport type HostRpcJournalResolver = (request: HostRpcJournalRequest) => AsyncCommandJournal | CommandJournal | null;\n\n/** Trusted opaque callee context resolver. */\nexport type HostRpcCalleeResolver = (request: RpcAdmissionRequest, publication: HostRpcServiceDescriptor) => unknown;\n\n/**\n * Host-provided frame for one admitted native RPC handler. It lets the SAME\n * `PluginServiceHost` invocation store the real purpose/deadline/cancellation\n * for the duration of the handler, bound to the exact published owner, so a\n * channel operation started inside a native handler is authorized by the real\n * frame (never downgraded to `background`, never given a forged purpose).\n */\nexport interface HostRpcHandlerFrame {\n readonly purpose: RpcCallPurpose;\n readonly deadlineAt?: number;\n readonly signal?: AbortSignal;\n /** Exact published owner the call targets; `null` for a remote (peer) route. */\n readonly ownerToken: object | null;\n readonly operationId: string | null;\n}\n\nexport interface HostRpcJournalCleanupFailure {\n readonly operationId: string;\n readonly code: string;\n}\nexport interface HostRpcAdapterOptions {\n /** Resource cleanup reports separately and never replaces a business outcome. */\n readonly onJournalCleanupFailure?: (failure:HostRpcJournalCleanupFailure)=>void;\n readonly process: PluginServiceProcess;\n readonly limits?: RpcRuntimeLimits;\n readonly hostLifetime?: AbortSignal;\n readonly maxCallDepth?: number;\n /** Required host placement authority. */\n readonly resolvePlacement: HostRpcPlacementResolver;\n /** Required host journal authority. */\n readonly resolveJournal: HostRpcJournalResolver;\n /** Required trusted opaque callee frame authority. */\n readonly resolveCallee: HostRpcCalleeResolver;\n /**\n * Host callback that enters the exact published owner's trusted invocation\n * frame for one native handler call. The canonical `PluginServiceHost` wires\n * it to its OWN invocation store, so a native RPC handler shares one\n * purpose/deadline/cancel resolver with local dispatch and channel work.\n */\n readonly enterHostHandlerFrame?: (frame: HostRpcHandlerFrame, run: () => unknown) => unknown;\n}\n\nexport interface HostRpcPublication {\n readonly descriptor: HostRpcServiceDescriptor;\n}\n\n/** Host-only readonly directory entry for one real registered publication. */\nexport interface HostRpcPublicationView {\n readonly provider: string;\n readonly service: string;\n readonly major: number;\n readonly scope: PluginServiceScope;\n readonly scopeKey: string;\n readonly ready: boolean;\n readonly lifecycle: HostRpcLifecycleIdentity;\n /** The kernel-selected binding of the exact endpoint handle; never re-derived. */\n readonly binding: RpcEndpointBinding;\n}\n\nexport interface HostRpcOwnerHandle {\n readonly owner: HostRpcOwnerInput;\n publish<const M extends Record<string, RpcMethodDefinition>>(\n contract: { readonly id: string; readonly version: number; readonly methods: M },\n handlers: RpcHandlerMap<M, unknown>,\n capabilities?: HostRpcCommandCapabilities<M>,\n ): HostRpcPublication;\n consume<const M extends Record<string, RpcMethodDefinition>>(\n provider: string,\n contract: { readonly id: string; readonly version: number; readonly methods: M },\n ): AsyncRpcClient<M>;\n /** Canonical host hook: ready maps to kernel `markReady`. */\n markReady(): void;\n /** Canonical host hook: retirement maps to kernel `retire`. */\n retire(): void;\n /**\n * Canonical host hook: disposal maps to kernel `revoke` + bounded `drain`.\n * Returns the REAL drain verdict; `drained: false` is reported, never hidden.\n */\n dispose(): Promise<RpcDrainResult>;\n}\n\n/* -------------------------------------------------------------------------- */\n/* Internal helpers */\n/* -------------------------------------------------------------------------- */\n\nconst SEP = '\\0';\nconst DEFAULT_MAX_CALL_DEPTH = 32;\nconst CALL_OPTION_KEYS = ['signal', 'timeoutMs', 'operationId'] as const;\nconst EMPTY_OPTIONS: RpcCallOptions = Object.freeze({});\n\ninterface ActiveFrame {\n readonly purpose: RpcCallPurpose;\n readonly depth: number;\n readonly chain: readonly string[];\n readonly deadlineAt: number;\n readonly signal: AbortSignal;\n}\n\n/** Host frame inheritance only: purpose, call chain, deadline, and cancellation. */\nconst FRAME_STORE = new AsyncLocalStorage<ActiveFrame>();\n\ninterface RegisteredPublication {\n readonly key: string;\n readonly handle: RpcEndpointHandle;\n readonly provider: string;\n readonly scopeKey: string;\n readonly scope: PluginServiceScope;\n readonly contractId: string;\n readonly contractVersion: number;\n readonly ownerState: OwnerState;\n}\n\ninterface OwnerState {\n readonly owner: HostRpcOwnerInput;\n readonly plugin: string;\n readonly scope: string;\n readonly scopeKind: PluginServiceScope;\n readonly callerSubject: string;\n readonly lifecycle: HostRpcLifecycleIdentity;\n readonly publications: Set<RegisteredPublication>;\n readonly process: PluginServiceProcess;\n readonly local: boolean;\n readonly authorizeIncoming?: HostRpcRemoteCallerInput['authorizeIncoming'];\n /** RPC capability revocation, independent of eventual resource reclamation. */\n revoked: boolean;\n released: boolean;\n}\n\ninterface CalleeInfo {\n readonly provider: string;\n readonly scopeKey: string;\n readonly scope: PluginServiceScope;\n readonly frame: unknown;\n /** Exact published owner token, or `null` for a remote (peer) route. */\n readonly ownerToken: object | null;\n}\n\ntype Handler = (input: unknown, context: RpcHandlerContext<unknown>) => unknown;\n\ntype RouteResolution =\n | { readonly kind: 'publication'; readonly publication: RegisteredPublication }\n | { readonly kind: 'remote'; readonly handle: RpcEndpointHandle }\n | { readonly kind: 'ambiguous' }\n | { readonly kind: 'missing' };\n\nconst CALLEE_INFO = new WeakMap<object, CalleeInfo>();\n\n/** Reads the trusted opaque callee frame the host resolver produced for an admitted call. */\nexport function readHostRpcCalleeFrame(callee: unknown): unknown {\n if (callee === null || typeof callee !== 'object') return null;\n return CALLEE_INFO.get(callee as object)?.frame ?? null;\n}\n\nfunction publicationKey(provider: string, scopeKey: string, service: string, major: number): string {\n return `${provider}${SEP}${scopeKey}${SEP}${service}${SEP}${major}`;\n}\n\nfunction scopeKindOf(scope: string): PluginServiceScope {\n return scope === 'global' ? 'global' : 'binding';\n}\n\nfunction callerSubjectFor(plugin: string, scope: string): string {\n return scope === 'global' ? plugin : `${plugin}@${scope}`;\n}\n\nfunction normalizeOperationId(operationId: unknown): string {\n if (typeof operationId !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(operationId)) {\n throw new RpcServiceError('invalid_operation_id');\n }\n return operationId;\n}\n\n/** Combines cancellation signals without depending on `AbortSignal.any` being present. */\nfunction anySignal(signals: readonly AbortSignal[]): AbortSignal {\n if (signals.length === 1) return signals[0];\n const native = (AbortSignal as unknown as { any?: (values: AbortSignal[]) => AbortSignal }).any;\n if (typeof native === 'function') return native.call(AbortSignal, [...signals]);\n const controller = new AbortController();\n const abort = (): void => controller.abort();\n for (const signal of signals) {\n if (signal.aborted) { abort(); break; }\n signal.addEventListener('abort', abort, { once: true });\n }\n return controller.signal;\n}\n\nfunction requirePurpose(definition: RpcMethodDefinition, purpose: RpcCallPurpose): RpcCallPurpose {\n if (!definition.purposes.includes(purpose)) throw new RpcServiceError('wrong_purpose');\n return purpose;\n}\n\n/** Own-descriptor snapshot of the trusted lifecycle identity; no accessor ever runs. */\nfunction snapshotLifecycle(value: unknown): HostRpcLifecycleIdentity {\n if (value === null || typeof value !== 'object' || isProxy(value)) throw new RpcServiceError('invalid_registration');\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) throw new RpcServiceError('invalid_registration');\n const read = (name: string): unknown => {\n const descriptor = Object.getOwnPropertyDescriptor(value, name);\n if (descriptor === undefined || !descriptor.enumerable || !('value' in descriptor)) {\n throw new RpcServiceError('invalid_registration');\n }\n return descriptor.value;\n };\n const allowed = new Set(['endpoint', 'instance', 'generation', 'catalog', 'subject']);\n for (const key of Reflect.ownKeys(value)) {\n if (typeof key !== 'string' || !allowed.has(key)) throw new RpcServiceError('invalid_registration');\n }\n const endpoint = read('endpoint');\n const instance = read('instance');\n const generation = read('generation');\n const catalog = read('catalog');\n const subject = read('subject');\n if (typeof endpoint !== 'string' || !endpoint || typeof instance !== 'string' || !instance\n || !Number.isSafeInteger(generation) || (generation as number) < 1\n || typeof catalog !== 'string' || typeof subject !== 'string' || !subject) {\n throw new RpcServiceError('invalid_registration');\n }\n return Object.freeze({ endpoint, instance, generation: generation as number, catalog, subject });\n}\n\n/** Own-descriptor snapshot of a dependencies record; accessors are rejected, never invoked. */\nfunction snapshotDependencies(value: unknown): Readonly<Record<string, string>> {\n if (value === undefined) return Object.freeze({});\n if (value === null || typeof value !== 'object' || isProxy(value)) throw new RpcServiceError('invalid_registration');\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) throw new RpcServiceError('invalid_registration');\n const result: Record<string, string> = {};\n for (const key of Reflect.ownKeys(value)) {\n if (typeof key !== 'string') throw new RpcServiceError('invalid_registration');\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (descriptor === undefined || !descriptor.enumerable || !('value' in descriptor) || typeof descriptor.value !== 'string') {\n throw new RpcServiceError('invalid_registration');\n }\n result[key] = descriptor.value;\n }\n return Object.freeze(result);\n}\n\n/**\n * Copies own enumerable data-function properties only. Accessors, proxies,\n * prototype methods, symbol keys, and unknown keys are rejected before any value\n * is read, so no plugin getter ever runs.\n */\nfunction snapshotHandlers(methods: Record<string, RpcMethodDefinition>, handler: unknown): Map<string, Handler> {\n if (handler === null || typeof handler !== 'object' || isProxy(handler)) throw new RpcServiceError('invalid_registration');\n const prototype = Object.getPrototypeOf(handler);\n if (prototype !== Object.prototype && prototype !== null) throw new RpcServiceError('invalid_registration');\n const allowed = new Set(Object.keys(methods));\n const collected = new Map<string, Handler>();\n for (const key of Reflect.ownKeys(handler)) {\n if (typeof key !== 'string' || !allowed.has(key)) throw new RpcServiceError('invalid_registration');\n const descriptor = Object.getOwnPropertyDescriptor(handler, key);\n if (descriptor === undefined || !descriptor.enumerable || !('value' in descriptor) || typeof descriptor.value !== 'function') {\n throw new RpcServiceError('invalid_registration');\n }\n collected.set(key, descriptor.value as Handler);\n }\n for (const name of allowed) if (!collected.has(name)) throw new RpcServiceError('invalid_registration');\n return collected;\n}\n\n/**\n * Snapshots one command capability through own descriptors only. Proxies, accessors,\n * unknown keys, and non-function planner/reconcile values are rejected before any\n * value is read, so no plugin getter ever runs and no mutable capability object is\n * retained.\n */\nfunction snapshotCapability(value: unknown): HostRpcMethodCapability {\n if (value === null || typeof value !== 'object' || isProxy(value)) throw new RpcServiceError('invalid_registration');\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) throw new RpcServiceError('invalid_registration');\n let atomic: CommandAtomicPlanner | undefined;\n let atomicReadSet: AtomicReadSetResolver | undefined;\n let external: CommandExternalExecutor | undefined;\n for (const key of Reflect.ownKeys(value)) {\n if (typeof key !== 'string' || (key !== 'atomic' && key !== 'atomicReadSet' && key !== 'external')) throw new RpcServiceError('invalid_registration');\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (descriptor === undefined || !descriptor.enumerable || !('value' in descriptor)) {\n throw new RpcServiceError('invalid_registration');\n }\n if (key === 'atomicReadSet') {\n if (typeof descriptor.value !== 'function') throw new RpcServiceError('invalid_registration');\n atomicReadSet = descriptor.value as AtomicReadSetResolver;\n } else if (key === 'atomic') {\n if (typeof descriptor.value !== 'function') throw new RpcServiceError('invalid_registration');\n atomic = descriptor.value as CommandAtomicPlanner;\n } else {\n external = snapshotExternal(descriptor.value);\n }\n }\n const record: { atomic?: CommandAtomicPlanner; atomicReadSet?: AtomicReadSetResolver; external?: CommandExternalExecutor } = {};\n if (atomic !== undefined) record.atomic = atomic;\n if (atomicReadSet !== undefined) record.atomicReadSet = atomicReadSet;\n if (external !== undefined) record.external = external;\n return Object.freeze(record);\n}\n\n/** Snapshots the `external.reconcile` function without retaining the plugin's object. */\nfunction snapshotExternal(value: unknown): CommandExternalExecutor {\n if (value === null || typeof value !== 'object' || isProxy(value)) throw new RpcServiceError('invalid_registration');\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) throw new RpcServiceError('invalid_registration');\n for (const key of Reflect.ownKeys(value)) {\n if (key !== 'reconcile') throw new RpcServiceError('invalid_registration');\n }\n const descriptor = Object.getOwnPropertyDescriptor(value, 'reconcile');\n if (descriptor === undefined || !descriptor.enumerable || !('value' in descriptor) || typeof descriptor.value !== 'function') {\n throw new RpcServiceError('invalid_registration');\n }\n return Object.freeze({ reconcile: descriptor.value as CommandExternalExecutor['reconcile'] });\n}\n\n/**\n * Descriptor-safe snapshot of the command capabilities record. Every key must name a\n * declared command method; accessors, proxies, symbol keys, unknown/non-command\n * methods, and unknown capability fields are rejected before `register`, so a failed\n * snapshot can never leave a ghost endpoint. The snapshot is frozen and independent\n * of the plugin's mutable objects.\n */\nfunction snapshotCapabilities(\n methodTable: Record<string, RpcMethodDefinition>,\n value: unknown,\n): Readonly<Record<string, HostRpcMethodCapability>> | null {\n if (value === undefined) return null;\n if (value === null || typeof value !== 'object' || isProxy(value)) throw new RpcServiceError('invalid_registration');\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) throw new RpcServiceError('invalid_registration');\n const record: Record<string, HostRpcMethodCapability> = {};\n for (const key of Reflect.ownKeys(value)) {\n if (typeof key !== 'string' || !Object.hasOwn(methodTable, key)) throw new RpcServiceError('invalid_registration');\n const definition = methodTable[key];\n if (definition === undefined || definition.kind !== 'command') throw new RpcServiceError('invalid_registration');\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (descriptor === undefined || !descriptor.enumerable || !('value' in descriptor)) {\n throw new RpcServiceError('invalid_registration');\n }\n if (descriptor.value === undefined) continue;\n record[key] = snapshotCapability(descriptor.value);\n }\n return Object.freeze(record);\n}\n\n/** Snapshots plugin call options without invoking accessors or accepting unknown keys. */\nfunction snapshotCallOptions(options: RpcCallOptions | undefined): RpcCallOptions {\n if (options === undefined) return EMPTY_OPTIONS;\n if (options === null || typeof options !== 'object' || isProxy(options)) throw new RpcServiceError('invalid_input');\n const prototype = Object.getPrototypeOf(options);\n if (prototype !== Object.prototype && prototype !== null) throw new RpcServiceError('invalid_input');\n const result: { signal?: AbortSignal; timeoutMs?: number; operationId?: string } = {};\n for (const key of Reflect.ownKeys(options)) {\n if (typeof key !== 'string' || !(CALL_OPTION_KEYS as readonly string[]).includes(key)) {\n throw new RpcServiceError('invalid_input');\n }\n const descriptor = Object.getOwnPropertyDescriptor(options, key);\n if (descriptor === undefined || !descriptor.enumerable || !('value' in descriptor)) {\n throw new RpcServiceError('invalid_input');\n }\n (result as Record<string, unknown>)[key] = descriptor.value;\n }\n if (result.signal !== undefined && !(result.signal instanceof AbortSignal)) throw new RpcServiceError('invalid_input');\n if (result.timeoutMs !== undefined\n && (typeof result.timeoutMs !== 'number' || !Number.isSafeInteger(result.timeoutMs) || result.timeoutMs < 0)) {\n throw new RpcServiceError('invalid_input');\n }\n if (result.operationId !== undefined && typeof result.operationId !== 'string') throw new RpcServiceError('invalid_input');\n return Object.freeze(result);\n}\n\nfunction defineContract<const M extends Record<string, RpcMethodDefinition>>(\n contract: { readonly id: string; readonly version: number; readonly methods: M },\n): { readonly id: string; readonly version: number; readonly methods: M } {\n try {\n return defineRpcService(contract) as unknown as { readonly id: string; readonly version: number; readonly methods: M };\n } catch {\n throw new RpcServiceError('invalid_registration');\n }\n}\n\n/* -------------------------------------------------------------------------- */\n/* Adapter */\n/* -------------------------------------------------------------------------- */\n\nexport class HostRpcAdapter {\n readonly runtime: RpcServiceRuntime<unknown>;\n readonly #options: HostRpcAdapterOptions;\n readonly #process: PluginServiceProcess;\n readonly #maxCallDepth: number;\n readonly #ownersByToken = new WeakMap<object, OwnerState>();\n readonly #ownersByCaller = new Map<string, OwnerState>();\n readonly #publications = new Map<string, RegisteredPublication>();\n readonly #capabilities = new Map<string, Readonly<Record<string, HostRpcMethodCapability>>>();\n #closed = false;\n\n constructor(options: HostRpcAdapterOptions) {\n if (options === null || typeof options !== 'object' || typeof options.process !== 'string') {\n throw new RpcServiceError('invalid_registration');\n }\n if (typeof options.resolvePlacement !== 'function' || typeof options.resolveJournal !== 'function'\n || typeof options.resolveCallee !== 'function') {\n throw new RpcServiceError('invalid_registration');\n }\n this.#options = options;\n this.#process = options.process;\n this.#maxCallDepth = Number.isSafeInteger(options.maxCallDepth) && (options.maxCallDepth as number) > 0\n ? options.maxCallDepth as number : DEFAULT_MAX_CALL_DEPTH;\n this.runtime = new RpcServiceRuntime<unknown>({\n admit: (request) => this.#admit(request),\n commandExecutor: this.#commandExecutor(),\n hostLifetime: options.hostLifetime,\n limits: options.limits,\n });\n }\n\n status(): RpcRuntimeStatus {\n return this.runtime.status();\n }\n\n /**\n * Host-only readonly directory of this adapter's *real* registered\n * publications: the kernel-selected binding (endpoint/process/instance/\n * generation/catalog/scope/subject) of the exact endpoint handle, its owner\n * lifecycle identity and its current readiness. It is a plain snapshot for\n * host decision making (peer routing/validation); it grants nothing, exposes\n * no SDK surface and is never exposed through `PluginServices`.\n */\n publicationView(): readonly HostRpcPublicationView[] {\n const view: HostRpcPublicationView[] = [];\n for (const publication of this.#publications.values()) {\n const info = this.runtime.endpointInfo(publication.handle);\n if (info === null) continue;\n const lifecycle = publication.ownerState.lifecycle;\n const state = publication.ownerState.owner.getLifecycleState();\n view.push(Object.freeze({\n provider: publication.provider,\n service: publication.contractId,\n major: publication.contractVersion,\n scope: publication.scope,\n scopeKey: publication.scopeKey,\n ready: state.ready && !state.retiring && !state.revoked,\n lifecycle: Object.freeze({\n endpoint: lifecycle.endpoint, instance: lifecycle.instance,\n generation: lifecycle.generation, catalog: lifecycle.catalog, subject: lifecycle.subject,\n }),\n binding: info.binding,\n }));\n }\n return Object.freeze(view);\n }\n\n /** Closes the process runtime; the parent awaits this in the canonical shutdown. */\n async dispose(options: { readonly timeoutMs?: number } = {}) {\n this.#closed = true;\n return this.runtime.dispose(options);\n }\n\n /* ------------------------------ owners ---------------------------------- */\n\n createOwner(input: HostRpcOwnerInput): HostRpcOwnerHandle {\n return this.#ownerHandle(this.#createOwnerState(input, this.#process, true));\n }\n\n /** Imports an authenticated concrete caller, not a plugin instance or SDK facade. */\n createRemoteCaller(input: HostRpcRemoteCallerInput): HostRpcRemoteCallerHandle {\n if (!['control', 'worker', 'ingress'].includes(input?.process) || typeof input?.authorizeIncoming !== 'function') {\n throw new RpcServiceError('invalid_registration');\n }\n const authorize = input.authorizeIncoming;\n const state = this.#createOwnerState(input, input.process, false, authorize);\n return Object.freeze({\n invokeTracked: (request: Omit<RpcInvokeRequest, 'caller' | 'callerToken'>) => this.runtime.invokeTracked({\n ...request, caller: Object.freeze({ subject: state.callerSubject, scope: state.scopeKind }), callerToken: state.owner.token,\n }),\n dispose: () => this.#disposeOwner(state),\n });\n }\n\n #createOwnerState(input: HostRpcOwnerInput, process: PluginServiceProcess, local: boolean,\n authorizeIncoming?: HostRpcRemoteCallerInput['authorizeIncoming']): OwnerState {\n if (this.#closed) throw new RpcServiceError('closed');\n if (input === null || typeof input !== 'object' || input.token === null || typeof input.token !== 'object') {\n throw new RpcServiceError('invalid_registration');\n }\n if (typeof input.plugin !== 'string' || !input.plugin || typeof input.scope !== 'string' || !input.scope) {\n throw new RpcServiceError('invalid_registration');\n }\n if (typeof input.getLifecycleState !== 'function' || typeof input.acquireLease !== 'function'\n || typeof input.resolveInvocationContext !== 'function') {\n throw new RpcServiceError('invalid_registration');\n }\n if (this.#ownersByToken.has(input.token)) throw new RpcServiceError('invalid_registration');\n const callerSubject = callerSubjectFor(input.plugin, input.scope);\n if (local && this.#ownersByCaller.has(callerSubject)) throw new RpcServiceError('invalid_registration');\n const state: OwnerState = {\n owner: input,\n plugin: input.plugin,\n scope: input.scope,\n scopeKind: scopeKindOf(input.scope),\n callerSubject,\n lifecycle: snapshotLifecycle(input.lifecycle),\n publications: new Set(),\n process, local, authorizeIncoming,\n revoked: false,\n released: false,\n };\n // Fail closed before any publication: dependency records must be snapshot-clean.\n snapshotDependencies(input.dependencies);\n if (Object.hasOwn(input, 'optionalDependencies')) throw new RpcServiceError('invalid_registration');\n try { assertSupportedServiceDeclarations(input.declarations); } catch { throw new RpcServiceError('invalid_registration'); }\n this.#ownersByToken.set(input.token, state);\n if (local) this.#ownersByCaller.set(callerSubject, state);\n return state;\n }\n\n #ownerHandle(state: OwnerState): HostRpcOwnerHandle {\n return Object.freeze({\n owner: state.owner,\n publish: <const M extends Record<string, RpcMethodDefinition>>(\n contract: { readonly id: string; readonly version: number; readonly methods: M },\n handlers: RpcHandlerMap<M, unknown>,\n capabilities?: HostRpcCommandCapabilities<M>,\n ) => this.#publish(state, contract, handlers, capabilities),\n consume: <const M extends Record<string, RpcMethodDefinition>>(\n provider: string,\n contract: { readonly id: string; readonly version: number; readonly methods: M },\n ) => this.#consume(state, provider, contract),\n markReady: () => { this.#markReady(state); },\n retire: () => { this.#retire(state); },\n dispose: () => this.#disposeOwner(state),\n });\n }\n\n #markReady(state: OwnerState): void {\n if (state.revoked || state.released || this.#closed) throw new RpcServiceError('closed');\n for (const publication of state.publications) this.runtime.markReady(publication.handle);\n }\n\n #retire(state: OwnerState): void {\n if (state.released) return;\n for (const publication of state.publications) this.runtime.retire(publication.handle);\n }\n\n /** Revoke + REAL bounded drain. Resources are dropped only after a drained verdict. */\n async #disposeOwner(state: OwnerState): Promise<RpcDrainResult> {\n if (state.released) return Object.freeze({ drained: true, active: 0 });\n state.revoked = true;\n this.runtime.revokeCaller(state.callerSubject, state.owner.token);\n for (const publication of state.publications) this.runtime.revoke(publication.handle);\n const result = await this.runtime.drainOwner(state.callerSubject, [...state.publications].map(publication => publication.handle), { callerToken: state.owner.token });\n if (result.drained) this.#releaseOwner(state);\n return result;\n }\n\n /** Drops publication/capability/owner mapping so the same logical owner can be recreated. */\n #releaseOwner(state: OwnerState): void {\n for (const publication of state.publications) {\n this.#publications.delete(publication.key);\n this.#capabilities.delete(publication.key);\n }\n state.publications.clear();\n state.released = true;\n if (this.#ownersByCaller.get(state.callerSubject) === state) this.#ownersByCaller.delete(state.callerSubject);\n }\n\n /* ---------------------------- publications ------------------------------ */\n\n #publish<const M extends Record<string, RpcMethodDefinition>>(\n state: OwnerState,\n contractInput: { readonly id: string; readonly version: number; readonly methods: M },\n handlers: RpcHandlerMap<M, unknown>,\n capabilities?: HostRpcCommandCapabilities<M>,\n ): HostRpcPublication {\n const lifecycleState = state.owner.getLifecycleState();\n if (state.revoked || state.released || this.#closed || lifecycleState.revoked || lifecycleState.retiring) {\n throw new RpcServiceError('closed');\n }\n const contract = defineContract(contractInput);\n if (this.#matchPublication(state, contract.id, contract.version) === null) throw new RpcServiceError('undeclared');\n const key = publicationKey(state.plugin, state.scope, contract.id, contract.version);\n // Duplicate detection happens BEFORE register so no ghost endpoint is created.\n if (this.#publications.has(key)) throw new RpcServiceError('invalid_registration');\n const methodTable = contract.methods as Record<string, RpcMethodDefinition>;\n const collected = snapshotHandlers(methodTable, handlers);\n // Snapshot capabilities BEFORE `register`: a hostile accessor must fail closed with\n // zero endpoints and no parent publication callback, never leave a ghost endpoint.\n const capabilityRecord = snapshotCapabilities(methodTable, capabilities);\n const wrapped: Record<string, Handler> = {};\n for (const [name, definition] of Object.entries(methodTable)) {\n const chainKey = `${state.plugin}${SEP}${state.scope}${SEP}${contract.id}${SEP}${contract.version}${SEP}${name}`;\n wrapped[name] = this.#wrapHandler(collected.get(name) as Handler, definition, chainKey);\n }\n const binding: RpcEndpointBinding = {\n endpoint: state.lifecycle.endpoint,\n process: this.#process,\n instance: state.lifecycle.instance,\n generation: state.lifecycle.generation,\n catalog: state.lifecycle.catalog,\n scope: state.scopeKind,\n subject: state.lifecycle.subject,\n };\n let handle: RpcEndpointHandle;\n try {\n handle = this.runtime.register({\n provider: state.plugin,\n binding,\n contract,\n handler: wrapped as unknown as RpcHandlerMap<M, unknown>,\n });\n } catch {\n throw new RpcServiceError('invalid_registration');\n }\n const descriptor: HostRpcServiceDescriptor = Object.freeze({\n provider: state.plugin, service: contract.id, major: contract.version, kind: 'rpc',\n process: this.#process, scope: state.scopeKind,\n });\n const publication: RegisteredPublication = {\n key, handle, provider: state.plugin, scopeKey: state.scope, scope: state.scopeKind,\n contractId: contract.id, contractVersion: contract.version, ownerState: state,\n };\n this.#publications.set(key, publication);\n state.publications.add(publication);\n if (capabilityRecord !== null && Object.keys(capabilityRecord).length > 0) {\n this.#capabilities.set(key, capabilityRecord);\n }\n try {\n state.owner.registerPublication?.({\n id: contract.id, version: contract.version, kind: 'rpc', process: this.#process, scope: 'global',\n });\n } catch {\n // Roll back completely: no ghost endpoint, no reservation, no capability.\n this.runtime.revoke(handle);\n this.#publications.delete(key);\n this.#capabilities.delete(key);\n state.publications.delete(publication);\n throw new RpcServiceError('invalid_registration');\n }\n return Object.freeze({ descriptor });\n }\n\n #wrapHandler(original: Handler, definition: RpcMethodDefinition, chainKey: string): Handler {\n // Commands are framed once by `#commandExecutor` for the whole journal capability\n // (execute/query/reconcile); framing the business handler again here would inflate\n // depth and could manufacture false same-method cycles.\n if (definition.kind === 'command') return original;\n return (input, context) => this.#runInFrame(context, chainKey, () => original(input, context));\n }\n\n /** Runs `run` inside one inherited host frame: purpose, chain, deadline, cancellation. */\n #runInFrame(context: RpcHandlerContext<unknown>, chainKey: string, run: () => unknown): unknown {\n const parent = FRAME_STORE.getStore() ?? null;\n const depth = (parent?.depth ?? 0) + 1;\n if (depth > this.#maxCallDepth) throw new RpcServiceError('call_depth_exceeded', context.operationId);\n const actualDeadline = typeof context.deadlineAt === 'number' ? context.deadlineAt : Number.POSITIVE_INFINITY;\n const frame: ActiveFrame = Object.freeze({\n purpose: context.purpose,\n depth,\n chain: Object.freeze([...(parent?.chain ?? []), chainKey]),\n deadlineAt: parent === null ? actualDeadline : Math.min(parent.deadlineAt, actualDeadline),\n // A nested call must also abort when the parent call is cancelled.\n signal: parent === null ? context.signal : anySignal([parent.signal, context.signal]),\n });\n const enter = this.#options.enterHostHandlerFrame;\n if (enter === undefined) return FRAME_STORE.run(frame, run);\n // The canonical host enters its OWN live invocation frame for the exact\n // published owner, so channel work and nested local dispatch inside this\n // handler inherit the real purpose/deadline/cancel and the exact owner\n // authority instead of being re-interpreted as an unauthenticated background\n // task. `ownerToken` is host-private (`CALLEE_INFO`), never a payload field.\n const info = context.callee !== null && typeof context.callee === 'object'\n ? CALLEE_INFO.get(context.callee as object)\n : undefined;\n const hostFrame: HostRpcHandlerFrame = {\n purpose: frame.purpose,\n ...(Number.isFinite(frame.deadlineAt) ? { deadlineAt: frame.deadlineAt } : {}),\n signal: frame.signal,\n ownerToken: info?.ownerToken ?? null,\n operationId: context.operationId ?? null,\n };\n return FRAME_STORE.run(frame, () => enter(hostFrame, run));\n }\n\n /* ----------------------------- consumption ------------------------------ */\n\n #consume<const M extends Record<string, RpcMethodDefinition>>(\n state: OwnerState,\n provider: string,\n contractInput: { readonly id: string; readonly version: number; readonly methods: M },\n ): AsyncRpcClient<M> {\n if (state.released || this.#closed) throw new RpcServiceError('closed');\n if (typeof provider !== 'string' || !provider) throw new RpcServiceError('invalid_registration');\n const contract = defineContract(contractInput);\n const declaration = this.#matchConsumption(state, provider, contract.id, contract.version);\n if (declaration === null) throw new RpcServiceError('undeclared');\n if (!isCrossProcessSelfService(state.plugin, declaration, state.owner.declarations) && (provider === state.plugin || !Object.hasOwn(state.owner.dependencies, provider))) throw new RpcServiceError('undeclared');\n const scopeKey = 'global';\n const firstMethod = Object.keys(contract.methods as Record<string, RpcMethodDefinition>)[0];\n const route = this.#resolveRoute(state, { provider, service: contract.id, major: contract.version, method: firstMethod }, scopeKey);\n if (route.kind === 'ambiguous') throw new RpcServiceError('ambiguous_placement');\n if (route.kind === 'missing') {\n throw new RpcServiceError('unavailable');\n }\n state.owner.registerConsumption?.(declaration, route.kind === 'publication' ? route.publication.ownerState.owner.token : undefined);\n const methodTable = contract.methods as Record<string, RpcMethodDefinition>;\n const client: Record<string, unknown> = {};\n for (const [method, definition] of Object.entries(methodTable)) {\n client[method] = this.#makeMethodClient(state, provider, contract, method, definition);\n }\n return Object.freeze(client) as AsyncRpcClient<M>;\n }\n\n #makeMethodClient<const M extends Record<string, RpcMethodDefinition>>(\n state: OwnerState,\n provider: string,\n contract: { readonly id: string; readonly version: number; readonly methods: M },\n method: string,\n definition: RpcMethodDefinition,\n ): unknown {\n const target = { provider, service: contract.id, major: contract.version, method };\n const invoke = (action: RpcCommandAction | undefined, input: unknown, operationId: string | null, options: RpcCallOptions) =>\n this.#invokeAction(state, target, definition, action, input, operationId, options);\n const call = async (input: unknown, options?: RpcCallOptions): Promise<unknown> => {\n const snapshot = snapshotCallOptions(options);\n const operationId = this.#operationId(definition, snapshot);\n return invoke(definition.kind === 'command' ? 'execute' : undefined, input, operationId, snapshot);\n };\n if (definition.kind !== 'command') return call;\n const queryResult = (operationId: string): Promise<unknown> =>\n invoke('query-result', null, normalizeOperationId(operationId), EMPTY_OPTIONS);\n const reconcile = (operationId: string, input: unknown): Promise<unknown> =>\n invoke('reconcile', input, normalizeOperationId(operationId), EMPTY_OPTIONS);\n return Object.assign(call, { queryResult, reconcile });\n }\n\n #operationId(definition: RpcMethodDefinition, options: RpcCallOptions): string | null {\n const raw = options.operationId;\n if (definition.kind === 'query') {\n if (raw !== undefined) throw new RpcServiceError('invalid_operation_id');\n return null;\n }\n if (raw === undefined) throw new RpcServiceError('invalid_operation_id');\n return normalizeOperationId(raw);\n }\n\n async #invokeAction(\n state: OwnerState,\n target: { readonly provider: string; readonly service: string; readonly major: number; readonly method: string },\n definition: RpcMethodDefinition,\n action: RpcCommandAction | undefined,\n input: unknown,\n operationId: string | null,\n options: RpcCallOptions,\n ): Promise<RpcJson> {\n if (state.revoked || state.released || this.#closed) throw new RpcServiceError('closed', operationId);\n // The manifest consumption and its canonical dependency record are re-validated on\n // every call: a removed declaration or dependency is refused.\n const scopeKey = this.#targetScope(state, target);\n if (scopeKey === null) throw new RpcServiceError('undeclared', operationId);\n const parent = FRAME_STORE.getStore() ?? null;\n if (parent !== null && parent.chain.includes(`${target.provider}${SEP}${scopeKey}${SEP}${target.service}${SEP}${target.major}${SEP}${target.method}`)) {\n throw new RpcServiceError('deadlock');\n }\n // Enforce the consumer contract's own input schema/byte bound before the provider\n // sees the call. `query-result` carries only the null control DTO, never business input.\n if (action !== 'query-result') {\n try {\n const limit = definition.maxInputBytes ?? RPC_JSON_MAX_BYTES;\n input = decodeRpcJson(encodeRpcJson(input, limit), limit);\n assertRpcData(definition.input, input, limit);\n } catch {\n throw new RpcServiceError('invalid_input', operationId);\n }\n }\n const caller = Object.freeze({ subject: state.callerSubject, scope: state.scopeKind });\n // Resolve the host invocation frame exactly once; purpose and request share that snapshot.\n const invocation = state.owner.resolveInvocationContext();\n const purpose = this.#selectPurpose(state, definition, invocation);\n const route = this.#resolveRoute(state, target, scopeKey, purpose);\n if (route.kind === 'ambiguous') throw new RpcServiceError('ambiguous_placement');\n if (route.kind === 'missing') throw new RpcServiceError('unavailable');\n const request = this.#buildRequest(target, caller, purpose, input, operationId, action, options, parent, invocation, state.owner.token);\n try {\n const result = await this.runtime.invoke(request);\n try { assertRpcData(definition.output, result, definition.maxOutputBytes); }\n catch { throw new RpcServiceError('invalid_output', operationId); }\n return result;\n } catch (error) {\n throw toRpcServiceError(error, operationId);\n }\n }\n\n /** Purpose is inherited, never rank-converted; the method must explicitly allow it. */\n #selectPurpose(state: OwnerState, definition: RpcMethodDefinition, invocation: HostRpcInvocationContext | null): RpcCallPurpose {\n const parent = FRAME_STORE.getStore() ?? null;\n if (parent !== null) return requirePurpose(definition, parent.purpose);\n if (invocation !== null) return requirePurpose(definition, invocation.purpose);\n const ready = state.owner.getLifecycleState().ready;\n return requirePurpose(definition, ready ? 'background' : 'bootstrap');\n }\n\n #buildRequest(\n target: { readonly provider: string; readonly service: string; readonly major: number; readonly method: string },\n caller: RpcCaller,\n purpose: RpcCallPurpose,\n input: unknown,\n operationId: string | null,\n action: RpcCommandAction | undefined,\n options: RpcCallOptions,\n parent: ActiveFrame | null,\n invocation: HostRpcInvocationContext | null,\n callerToken: object,\n ) {\n let timeoutMs = options.timeoutMs;\n const deadlineAt = Math.min(parent?.deadlineAt ?? Infinity, invocation?.deadlineAt ?? Infinity);\n if (parent !== null && Number.isFinite(parent.deadlineAt)) {\n const remaining = Math.floor(parent.deadlineAt - Date.now());\n timeoutMs = timeoutMs === undefined ? remaining : Math.min(timeoutMs, remaining);\n }\n if (invocation?.deadlineAt !== undefined) {\n const remaining = Math.floor(invocation.deadlineAt - Date.now());\n timeoutMs = timeoutMs === undefined ? remaining : Math.min(timeoutMs, remaining);\n }\n if (timeoutMs !== undefined && (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0)) {\n throw new RpcServiceError('timeout', operationId);\n }\n const explicitSignal = options.signal;\n const parentSignal = parent?.signal;\n let signal = explicitSignal === undefined\n ? parentSignal\n : parentSignal === undefined ? explicitSignal : anySignal([explicitSignal, parentSignal]);\n if (invocation?.signal !== undefined) signal = signal === undefined ? invocation.signal : anySignal([signal, invocation.signal]);\n const request: {\n target: { provider: string; service: string; major: number; method: string };\n caller: RpcCaller;\n callerToken: object;\n purpose: RpcCallPurpose;\n input: unknown;\n operationId?: string;\n commandAction?: RpcCommandAction;\n signal?: AbortSignal;\n timeoutMs?: number;\n deadlineAt?: number;\n } = {\n target: { provider: target.provider, service: target.service, major: target.major, method: target.method },\n caller,\n callerToken,\n purpose,\n input,\n };\n if (operationId !== null) request.operationId = operationId;\n if (action !== undefined) request.commandAction = action;\n if (signal !== undefined) request.signal = signal;\n if (timeoutMs !== undefined) request.timeoutMs = timeoutMs;\n if (Number.isFinite(deadlineAt)) request.deadlineAt = deadlineAt;\n return request;\n }\n\n /* ------------------------------- routing -------------------------------- */\n\n #matchPublication(state: OwnerState, id: string, version: number): PluginServicePublication | null {\n return state.owner.declarations.provides?.find((value) =>\n value.id === id && value.version === version\n && (value.kind ?? 'local') === 'rpc'\n && value.process === this.#process\n && (value.scope ?? 'global') === 'global' && state.scope === 'global') ?? null;\n }\n\n #matchConsumption(state: OwnerState, provider: string, id: string, version: number): PluginServiceConsumption | null {\n return state.owner.declarations.consumes?.find((value) =>\n value.plugin === provider && value.id === id && value.version === version\n && (value.kind ?? 'local') === 'rpc'\n && value.process === state.process) ?? null;\n }\n\n #targetScope(\n state: OwnerState,\n target: { readonly provider: string; readonly service: string; readonly major: number },\n ): string | null {\n const consumption = state.owner.declarations.consumes?.find((value) =>\n value.plugin === target.provider && value.id === target.service && value.version === target.major\n && (value.kind ?? 'local') === 'rpc' && value.process === state.process) ?? null;\n if (consumption === null) return null;\n if (!isCrossProcessSelfService(state.plugin, consumption, state.owner.declarations) && (target.provider === state.plugin || !Object.hasOwn(state.owner.dependencies, target.provider))) return null;\n return 'global';\n }\n\n /** Host placement authority runs first; `null` opts into the explicit local channel. */\n #resolveRoute(\n state: OwnerState,\n target: { readonly provider: string; readonly service: string; readonly major: number; readonly method: string },\n scopeKey: string,\n purpose?: RpcCallPurpose,\n ): RouteResolution {\n let placement: HostRpcPlacementResolution;\n try {\n placement = this.#options.resolvePlacement({\n provider: target.provider,\n service: target.service,\n major: target.major,\n method: target.method,\n scope: scopeKey === 'global' ? 'global' : 'binding',\n ...(scopeKey === 'global' ? {} : { bindingScope: scopeKey }),\n caller: Object.freeze({ subject: state.callerSubject, scope: state.scopeKind }),\n purpose,\n });\n } catch {\n return { kind: 'missing' };\n }\n if (placement !== null && placement !== undefined) {\n if (placement.kind === 'ambiguous') return { kind: 'ambiguous' };\n return { kind: 'remote', handle: placement.endpoint };\n }\n const publication = this.#publications.get(publicationKey(target.provider, scopeKey, target.service, target.major));\n return publication === undefined ? { kind: 'missing' } : { kind: 'publication', publication };\n }\n\n /* ----------------------------- admission -------------------------------- */\n\n #admit(request: RpcAdmissionRequest): RpcAdmissionGrant<unknown> | null {\n if (this.#closed) return null;\n const state = request.callerToken === undefined ? this.#ownersByCaller.get(request.caller.subject)\n : this.#ownersByToken.get(request.callerToken);\n if (state === undefined || state.revoked || state.released) return null;\n if (state.callerSubject !== request.caller.subject\n || (request.caller.scope !== undefined && state.scopeKind !== request.caller.scope)) return null;\n const callerState = state.owner.getLifecycleState();\n if (callerState.revoked) return null;\n if (state.owner.canCall !== undefined && !state.owner.canCall({ ...request.target })) return null;\n if (!callerState.ready && request.purpose !== 'bootstrap') return null;\n const target = { ...request.target };\n const scopeKey = this.#targetScope(state, target);\n if (scopeKey === null) return null;\n const route = this.#resolveRoute(state, target, scopeKey, request.purpose);\n if (route.kind === 'ambiguous' || route.kind === 'missing') return null;\n const publication = route.kind === 'publication' ? route.publication : null;\n const endpoint = route.kind === 'publication' ? route.publication.handle : route.handle;\n // The callee publication is built from the REAL kernel-bound endpoint identity, never\n // from the adapter process or a plugin-supplied location. A foreign/unconfirmable\n // endpoint, or one whose provider/service/major/scope disagrees with the requested\n // target, is refused before any lease or callee frame is produced.\n const info = this.runtime.endpointInfo(endpoint);\n if (info === null) return null;\n if (info.provider !== target.provider || info.contract.id !== target.service || info.contract.version !== target.major) {\n return null;\n }\n const scope = info.binding.scope;\n if ((scopeKey === 'global') !== (scope === 'global')) return null;\n if (!state.local) {\n try { if (state.authorizeIncoming?.(request, info) !== true) return null; }\n catch { return null; }\n if (state.revoked || state.released || this.#closed) return null;\n }\n const provider = info.provider;\n // Logical clients can be relocated without retaining an unrelated local provider.\n const consumption = this.#matchConsumption(state, target.provider, target.service, target.major)!;\n state.owner.registerConsumption?.(consumption, publication?.ownerState.owner.token);\n // Resolve the trusted callee frame before any lease so a throwing host\n // resolver cannot leak leases.\n const hostFrame = this.#options.resolveCallee(\n request,\n Object.freeze({ provider, service: target.service, major: target.major, kind: 'rpc', process: info.binding.process, scope }),\n );\n // Caller lease holds the issuing owner for the whole call lifespan.\n let callerRelease: () => void = () => undefined;\n try {\n const lease = state.owner.acquireLease({\n role: 'caller', plugin: state.plugin, scope: state.scope, state: callerState,\n purpose: request.purpose, operationId: request.operationId, provider: target.provider,\n });\n if (lease === null || typeof lease !== 'object' || typeof lease.release !== 'function') return null;\n callerRelease = once(() => { try { lease.release(); } catch { /* host-owned */ } });\n } catch { return null; }\n // Callee lease holds the provider (local only). A callee the kernel will refuse\n // (revoked / retiring without an existing-lease proof / unready non-bootstrap)\n // is NOT leased here, so the kernel reports the exact state instead of a lease error.\n let calleeRelease: (() => void) | null = null;\n let allowRetired = false;\n if (publication !== null) {\n const calleeState = publication.ownerState.owner.getLifecycleState();\n const runnable = calleeState.revoked ? false\n : calleeState.retiring ? (request.purpose === 'request' || request.purpose === 'attempt')\n : (calleeState.ready || request.purpose === 'bootstrap');\n if (runnable) {\n try {\n const lease = publication.ownerState.owner.acquireLease({\n role: 'callee', plugin: publication.provider, scope: publication.scopeKey, state: calleeState,\n purpose: request.purpose, operationId: request.operationId, provider: target.provider,\n });\n if (lease === null || typeof lease !== 'object' || typeof lease.release !== 'function') {\n callerRelease();\n return null;\n }\n calleeRelease = once(() => { try { lease.release(); } catch { /* host-owned */ } });\n allowRetired = lease.allowRetired === true\n && (request.purpose === 'request' || request.purpose === 'attempt');\n } catch { callerRelease(); return null; }\n }\n }\n const callee = Object.freeze({});\n CALLEE_INFO.set(callee, { provider, scopeKey, scope, frame: hostFrame, ownerToken: publication?.ownerState.owner.token ?? null });\n const release = once(() => {\n try { calleeRelease?.(); } catch { /* host-owned */ }\n try { callerRelease(); } catch { /* host-owned */ }\n });\n // A host callback can synchronously dispose this capability before a task exists.\n // Recheck after every admission callback has returned, before handing the kernel a grant.\n if (state.revoked || state.released || this.#closed) { release(); return null; }\n return {\n endpoint, callee, release, callerToken: state.owner.token,\n allowUnready: request.purpose === 'bootstrap',\n allowRetired,\n };\n }\n\n /* ------------------------------ commands -------------------------------- */\n\n #commandExecutor(): RpcCommandExecutor<unknown> {\n const run = async (\n execution: Omit<RpcCommandExecution<unknown>, 'executeBusiness'>,\n action: RpcCommandAction,\n ): Promise<unknown> => {\n const callee = execution.context.callee;\n const info = callee !== null && typeof callee === 'object' ? CALLEE_INFO.get(callee as object) : undefined;\n if (info === undefined) throw new RpcServiceError('capability_unavailable', execution.operationId);\n const chainKey = `${info.provider}${SEP}${info.scopeKey}${SEP}${execution.contract.id}${SEP}${execution.contract.version}${SEP}${execution.method}`;\n const journal = this.#journalFor(info, execution);\n // Application-owned CAS/idempotency (e.g. a budget ledger or credential\n // version fence) has one transaction authority. No parallel journal is\n // created for an explicitly non-deduplicated command.\n if (journal === null && execution.definition.command?.deduplication === 'none') {\n if (action !== 'execute') throw new RpcServiceError('capability_unavailable', execution.operationId);\n return this.#runInFrame(execution.context, chainKey, () => (execution as RpcCommandExecution<unknown>).executeBusiness());\n }\n if (journal === null) throw new RpcServiceError('capability_unavailable', execution.operationId);\n // Every journal action (execute/query/reconcile) runs inside the real RPC frame so\n // the business handler and any nested external-reconcile RPC inherit purpose,\n // chain, deadline, and cancellation. Commands are framed once here, not in #wrapHandler.\n try {\n return await this.#runInFrame(execution.context, chainKey, () => {\n if (action === 'execute') return journal.execute(execution as RpcCommandExecution<unknown>);\n if (action === 'query-result') return journal.query(execution.operationId, execution.context.caller);\n return journal.reconcile(execution);\n });\n } finally {\n if ('close' in journal) {\n // Capability release is resource cleanup, separate from the acknowledged command.\n // A stuck or failed cleanup must not replace success, unknown, or its operation ID.\n void Promise.resolve().then(()=>journal.close()).catch(error=>{\n const rawCode=ownStringProperty(error,'code');\n const code=rawCode!==null&&['worker_failed','request_timeout','request_failed','close_unconfirmed','cleanup_overloaded','queue_full','result_unknown','storage_failure'].includes(rawCode)?rawCode:'failed';\n const failure=Object.freeze({operationId:execution.operationId,code});\n try{logger.error(failure,'Host RPC journal cleanup failed');}catch{/* Reporting cannot change the command outcome. */}\n try{this.#options.onJournalCleanupFailure?.(failure);}catch{/* Host reporting is independent of business completion. */}\n });\n }\n }\n\n };\n return {\n execute: (execution) => run(execution, 'execute'),\n queryResult: (execution) => run(execution, 'query-result'),\n reconcile: (execution) => run(execution, 'reconcile'),\n };\n }\n\n #journalFor(\n info: CalleeInfo,\n execution: Omit<RpcCommandExecution<unknown>, 'executeBusiness'>,\n ): AsyncCommandJournal | CommandJournal | null {\n const policy = execution.definition.command;\n if (policy === undefined) throw new RpcServiceError('capability_unavailable', execution.operationId);\n const capability = this.#capabilities.get(\n publicationKey(info.provider, info.scopeKey, execution.contract.id, execution.contract.version),\n )?.[execution.method];\n try {\n return this.#options.resolveJournal({\n provider: info.provider,\n service: execution.contract.id,\n major: execution.contract.version,\n method: execution.method,\n scope: info.scope,\n ...(info.scope === 'binding' ? { bindingScope: info.scopeKey } : {}),\n policy,\n ...(capability?.atomic === undefined ? {} : { atomic: capability.atomic }),\n ...(capability?.atomicReadSet === undefined ? {} : { atomicReadSet: capability.atomicReadSet }),\n ...(capability?.external === undefined ? {} : { external: capability.external }),\n }) ?? null;\n } catch {\n throw new RpcServiceError('capability_unavailable', execution.operationId);\n }\n }\n}\n\nfunction once(action: () => void): () => void {\n let done = false;\n return () => { if (done) return; done = true; action(); };\n}\n",
11
14
  "/**\n * Plugin service RPC data contract (P1/P4): a dependency-free schema DSL, a\n * bounded strict-JSON codec, and service/method contract validation.\n *\n * Scope boundary: this module validates *data shapes only*. It deliberately\n * grants no wire authorization — host identity, generation, scope/lease, call\n * context, and permissions must be enforced by the host RPC adapter, never by a\n * schema check here. In particular `command.deduplication` is a declared intent;\n * real local transactions and any cross-system exactly-once behavior belong to\n * the host and to the external contract, not to this file.\n *\n * Everything that reaches validation is first cloned from own property\n * descriptors into bounded pure JSON, so no getter, proxy trap, or `toJSON` is\n * ever invoked and no non-JSON shape is silently accepted.\n */\nimport { isProxy } from 'node:util/types';\n\nexport type RpcCallKind = 'query' | 'command';\nexport type RpcCallPurpose = 'bootstrap' | 'background' | 'management' | 'request' | 'attempt';\nexport type RpcCommandDeduplication = 'local-transaction' | 'external-contract' | 'none';\n\n/** Declared intent only; the host owns the actual transaction and retention. */\nexport interface RpcCommandPolicy {\n readonly deduplication: RpcCommandDeduplication;\n /**\n * `null` means the result is retained permanently and durably: it survives a\n * restart and is never recomputed. A positive number is a retention window in\n * milliseconds. Retention is a host/storage concern; this is declaration only.\n */\n readonly resultRetentionMs: number | null;\n readonly quotaBytes: number;\n readonly maxResultBytes: number;\n}\n\n/** Pure JSON: null, boolean, finite number, string, arrays, and plain records. */\nexport type RpcJson =\n | null\n | boolean\n | number\n | string\n | readonly RpcJson[]\n | { readonly [key: string]: RpcJson };\n\n/**\n * Data schema DSL. `object` rejects unknown fields, `optional` lists real\n * optional keys, and `json` carries an optional explicit byte bound (default:\n * the RPC envelope).\n */\nexport type RpcDataSchema =\n | { readonly type: 'string'; readonly minLength?: number; readonly maxLength?: number }\n | { readonly type: 'number'; readonly integer?: boolean; readonly minimum?: number; readonly maximum?: number }\n | { readonly type: 'boolean' }\n | { readonly type: 'null' }\n | { readonly type: 'literal'; readonly value: RpcJson }\n | { readonly type: 'array'; readonly items: RpcDataSchema; readonly maxItems?: number }\n | {\n readonly type: 'object';\n readonly properties: { readonly [key: string]: RpcDataSchema };\n readonly optional?: readonly string[];\n }\n | { readonly type: 'record'; readonly values: RpcDataSchema; readonly maxEntries?: number }\n | { readonly type: 'union'; readonly variants: readonly RpcDataSchema[] }\n | { readonly type: 'json'; readonly maxBytes?: number };\n\n/** Flattens intersections so optional modifiers survive as real optional keys. */\ntype Simplify<T> = { [K in keyof T]: T[K] };\n\ntype OptionalNames<S> = S extends { readonly optional: readonly (infer K extends string)[] } ? K : never;\n\ntype InferObject<P extends Record<string, RpcDataSchema>, O extends string> = Simplify<\n { [K in keyof P as K extends O ? never : K]: InferRpcData<P[K]> } &\n { [K in Extract<keyof P, O>]?: InferRpcData<P[K]> }\n>;\n\n/** Derives the TypeScript type described by a `RpcDataSchema`. */\nexport type InferRpcData<S> =\n RpcDataSchema extends S ? RpcJson : S extends { readonly type: 'string' }\n ? string\n : S extends { readonly type: 'number' }\n ? number\n : S extends { readonly type: 'boolean' }\n ? boolean\n : S extends { readonly type: 'null' }\n ? null\n : S extends { readonly type: 'literal'; readonly value: infer V extends RpcJson }\n ? V\n : S extends { readonly type: 'json' }\n ? RpcJson\n : S extends { readonly type: 'array'; readonly items: infer I extends RpcDataSchema }\n ? InferRpcData<I>[]\n : S extends { readonly type: 'record'; readonly values: infer V extends RpcDataSchema }\n ? { [key: string]: InferRpcData<V> }\n : S extends { readonly type: 'union'; readonly variants: infer VS }\n ? VS extends readonly (infer V extends RpcDataSchema)[]\n ? InferRpcData<V>\n : never\n : S extends { readonly type: 'object'; readonly properties: infer P extends Record<string, RpcDataSchema> }\n ? InferObject<P, OptionalNames<S>>\n : never;\n\nexport interface RpcMethodDefinition {\n readonly kind: RpcCallKind;\n readonly input: RpcDataSchema;\n readonly output: RpcDataSchema;\n readonly purposes: readonly RpcCallPurpose[];\n readonly timeoutMs?: number;\n readonly maxInputBytes?: number;\n readonly maxOutputBytes?: number;\n readonly command?: RpcCommandPolicy;\n}\n\nexport interface RpcServiceContract<\n M extends Record<string, RpcMethodDefinition> = Record<string, RpcMethodDefinition>,\n> {\n readonly id: string;\n readonly version: number;\n readonly methods: M;\n}\n\nexport const RPC_JSON_MAX_BYTES = 64 * 1024;\n/** Metadata contract/schema inputs are pure JSON and bounded well below the envelope. */\nexport const RPC_CONTRACT_MAX_BYTES = 256 * 1024;\n\nconst JSON_MAX_DEPTH = 64;\nconst SCHEMA_MAX_DEPTH = 64;\nconst RPC_MAX_TIMEOUT_MS = 300_000;\nconst RPC_MAX_METHODS = 128;\nconst RPC_SERVICE_ID = /^[a-z][a-z0-9.-]{0,127}$/;\nconst RPC_METHOD_NAME = /^[A-Za-z_][A-Za-z0-9_.-]{0,127}$/;\nconst RPC_CALL_PURPOSES = new Set<RpcCallPurpose>(['bootstrap', 'background', 'management', 'request', 'attempt']);\nconst RPC_COMMAND_DEDUPLICATION = new Set<RpcCommandDeduplication>(['local-transaction', 'external-contract', 'none']);\nconst RPC_COMMAND_POLICY_KEYS = new Set(['deduplication', 'resultRetentionMs', 'quotaBytes', 'maxResultBytes']);\nconst CONTRACT_KEYS = ['id', 'version', 'methods'] as const;\nconst METHOD_KEYS = [\n 'kind',\n 'input',\n 'output',\n 'purposes',\n 'timeoutMs',\n 'maxInputBytes',\n 'maxOutputBytes',\n 'command',\n] as const;\n\nexport type RpcProtocolErrorCode = 'invalid_data' | 'size_limit' | 'invalid_contract';\n\n/** Fixed-code error. It never carries payload, secrets, keys, or arbitrary objects. */\nexport class RpcProtocolError extends Error {\n readonly name = 'RpcProtocolError';\n\n constructor(\n readonly code: RpcProtocolErrorCode,\n message: string,\n ) {\n super(message);\n }\n}\n\n/** Reports a fixed schema category only — never a user property name or value. */\nfunction failData(category: string): never {\n throw new RpcProtocolError('invalid_data', `invalid_data in ${category}`);\n}\n\nfunction failSize(): never {\n throw new RpcProtocolError('size_limit', 'size_limit: JSON value exceeds the byte limit');\n}\n\nfunction failContract(reason: string): never {\n throw new RpcProtocolError('invalid_contract', `invalid_contract: ${reason}`);\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;\n if (isProxy(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction isPositiveSafeInteger(value: unknown): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value) && value > 0;\n}\n\nfunction isNonNegativeSafeInteger(value: unknown): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;\n}\n\nfunction hasLoneSurrogate(value: string): boolean {\n for (let index = 0; index < value.length; index += 1) {\n const code = value.charCodeAt(index);\n if (code >= 0xd800 && code <= 0xdbff) {\n if (index + 1 >= value.length) return true;\n const next = value.charCodeAt(index + 1);\n if (next < 0xdc00 || next > 0xdfff) return true;\n index += 1;\n } else if (code >= 0xdc00 && code <= 0xdfff) {\n return true;\n }\n }\n return false;\n}\n\nfunction isArrayIndex(key: string, length: number): boolean {\n if (!/^(?:0|[1-9]\\d*)$/.test(key)) return false;\n const index = Number(key);\n return Number.isSafeInteger(index) && index >= 0 && index < length;\n}\n\nfunction assertKnownKeys(input: Record<string, unknown>, allowed: readonly string[], category: string): void {\n for (const key of Object.keys(input)) {\n if (!allowed.includes(key)) failContract(`unknown ${category} field`);\n }\n}\n\n/**\n * Running lower bound of the JSON byte size, used to reject oversized input\n * before it is fully cloned or stringified. Every accounting term is an\n * underestimate (escapes only ever add bytes), so a positive budget never\n * rejects a value that would actually fit.\n */\ninterface SnapshotBudget {\n left: number;\n}\n\nfunction spend(budget: SnapshotBudget, bytes: number): void {\n budget.left -= bytes;\n if (budget.left < 0) failSize();\n}\n\n/**\n * Validates and deep-clones a value into a plain pure-JSON graph. Object\n * descriptors are inspected before any value is read, so accessors and `toJSON`\n * are never invoked. Cycles, holes, non-plain objects, non-enumerable or symbol\n * keys, non-finite numbers, lone surrogates, and over-deep nesting are rejected;\n * the budget rejects oversized values early.\n */\nfunction snapshot(value: unknown, depth: number, ancestors: Set<object>, budget: SnapshotBudget): RpcJson {\n if (value === null) {\n spend(budget, 4);\n return null;\n }\n if (typeof value === 'boolean') {\n spend(budget, value ? 4 : 5);\n return value;\n }\n if (typeof value === 'string') {\n if (hasLoneSurrogate(value)) failData('string');\n spend(budget, Buffer.byteLength(value, 'utf8') + 2);\n return value;\n }\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) failData('number');\n spend(budget, 1);\n return value;\n }\n if (typeof value !== 'object') failData('json');\n const object = value as object;\n if (isProxy(object)) failData('json');\n if (ancestors.has(object)) failData('json');\n const nextDepth = depth + 1;\n if (nextDepth > JSON_MAX_DEPTH) failData('json');\n if (Array.isArray(object)) {\n if (Object.getPrototypeOf(object) !== Array.prototype) failData('array');\n const lengthDescriptor = Object.getOwnPropertyDescriptor(object, 'length');\n if (!lengthDescriptor || !('value' in lengthDescriptor) || typeof lengthDescriptor.value !== 'number') {\n failData('array');\n }\n const length = lengthDescriptor.value;\n if (!Number.isSafeInteger(length) || length < 0) failData('array');\n if (length > budget.left) failSize();\n spend(budget, 2);\n if (length > 1) spend(budget, length - 1);\n ancestors.add(object);\n const items: RpcJson[] = new Array(length);\n let count = 0;\n for (const key of Reflect.ownKeys(object)) {\n if (key === 'length') continue;\n if (typeof key !== 'string' || !isArrayIndex(key, length)) failData('array');\n const descriptor = Object.getOwnPropertyDescriptor(object, key);\n if (!descriptor || !descriptor.enumerable || !('value' in descriptor)) failData('array');\n items[Number(key)] = snapshot(descriptor.value, nextDepth, ancestors, budget);\n count += 1;\n }\n if (count !== length) failData('array');\n ancestors.delete(object);\n return items;\n }\n const prototype = Object.getPrototypeOf(object);\n if (prototype !== Object.prototype && prototype !== null) failData('object');\n const keys = Reflect.ownKeys(object);\n if (keys.length > budget.left) failSize();\n spend(budget, 2);\n if (keys.length > 1) spend(budget, keys.length - 1);\n ancestors.add(object);\n const result: Record<string, RpcJson> = {};\n for (const key of keys) {\n if (typeof key !== 'string') failData('object');\n if (hasLoneSurrogate(key)) failData('object');\n const descriptor = Object.getOwnPropertyDescriptor(object, key);\n if (!descriptor || !descriptor.enumerable || !('value' in descriptor)) failData('object');\n spend(budget, Buffer.byteLength(key, 'utf8') + 3);\n // defineProperty keeps a literal `__proto__` key an own data property instead of polluting the prototype.\n Object.defineProperty(result, key, {\n value: snapshot(descriptor.value, nextDepth, ancestors, budget),\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n ancestors.delete(object);\n return result;\n}\n\n/** Clones a contract/schema input as bounded pure JSON, mapping pure-JSON errors to invalid_contract. */\nfunction snapshotPureInput(input: unknown): RpcJson {\n try {\n const pure = snapshot(input, 0, new Set(), { left: RPC_CONTRACT_MAX_BYTES });\n if (Buffer.byteLength(JSON.stringify(pure), 'utf8') > RPC_CONTRACT_MAX_BYTES) failContract('input must be bounded pure JSON data');\n return pure;\n } catch (error) {\n if (error instanceof RpcProtocolError && (error.code === 'invalid_data' || error.code === 'size_limit')) {\n failContract('input must be bounded pure JSON data');\n }\n throw error;\n }\n}\n\n/** Strict scanner: rejects duplicate keys, trailing content, and deep nesting. */\nfunction scanJson(text: string): void {\n let index = 0;\n const numberPattern = /-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?/y;\n const fail = (): never => {\n throw new RpcProtocolError('invalid_data', 'invalid JSON text');\n };\n const whitespace = (): void => {\n while (index < text.length) {\n const character = text[index];\n if (character === ' ' || character === '\\t' || character === '\\n' || character === '\\r') index += 1;\n else break;\n }\n };\n const string = (): string => {\n if (text[index] !== '\"') return fail();\n const start = index;\n index += 1;\n while (index < text.length) {\n const character = text[index];\n if (character === '\"') {\n index += 1;\n try {\n const value: unknown = JSON.parse(text.slice(start, index));\n if (typeof value !== 'string') return fail();\n return value;\n } catch (error) {\n if (error instanceof RpcProtocolError) throw error;\n return fail();\n }\n }\n if (character === undefined) return fail();\n if (character.charCodeAt(0) < 0x20) return fail();\n if (character === '\\\\') {\n index += 1;\n const escape = text[index];\n if (escape === 'u') {\n if (!/^[0-9a-fA-F]{4}$/.test(text.slice(index + 1, index + 5))) return fail();\n index += 5;\n continue;\n }\n if (escape === undefined || !'\"\\\\/bfnrt'.includes(escape)) return fail();\n index += 1;\n continue;\n }\n index += 1;\n }\n return fail();\n };\n const value = (depth: number): void => {\n whitespace();\n const character = text[index];\n if (character === '{') {\n if (depth >= JSON_MAX_DEPTH) return fail();\n index += 1;\n whitespace();\n const keys = new Set<string>();\n if (text[index] === '}') {\n index += 1;\n return;\n }\n while (true) {\n whitespace();\n const key = string();\n if (keys.has(key)) return fail();\n keys.add(key);\n whitespace();\n if (text[index] !== ':') return fail();\n index += 1;\n value(depth + 1);\n whitespace();\n if (text[index] === '}') {\n index += 1;\n return;\n }\n if (text[index] !== ',') return fail();\n index += 1;\n }\n }\n if (character === '[') {\n if (depth >= JSON_MAX_DEPTH) return fail();\n index += 1;\n whitespace();\n if (text[index] === ']') {\n index += 1;\n return;\n }\n while (true) {\n value(depth + 1);\n whitespace();\n if (text[index] === ']') {\n index += 1;\n return;\n }\n if (text[index] !== ',') return fail();\n index += 1;\n }\n }\n if (character === '\"') {\n string();\n return;\n }\n if (text.startsWith('true', index)) {\n index += 4;\n return;\n }\n if (text.startsWith('false', index)) {\n index += 5;\n return;\n }\n if (text.startsWith('null', index)) {\n index += 4;\n return;\n }\n numberPattern.lastIndex = index;\n const match = numberPattern.exec(text);\n if (match === null) return fail();\n index = numberPattern.lastIndex;\n };\n value(0);\n whitespace();\n if (index !== text.length) fail();\n}\n\n/** Rejects numbers that overflowed to Infinity and lone surrogates after parsing. */\nfunction assertJsonGraph(value: unknown): void {\n const stack: unknown[] = [value];\n while (stack.length > 0) {\n const current = stack.pop();\n if (typeof current === 'number') {\n if (!Number.isFinite(current)) failData('json');\n continue;\n }\n if (typeof current === 'string') {\n if (hasLoneSurrogate(current)) failData('string');\n continue;\n }\n if (Array.isArray(current)) {\n for (const item of current) stack.push(item);\n continue;\n }\n if (current !== null && typeof current === 'object') {\n for (const key of Object.keys(current)) {\n if (hasLoneSurrogate(key)) failData('object');\n stack.push((current as Record<string, unknown>)[key]);\n }\n }\n }\n}\n\n/**\n * Serializes a pure-JSON value under a UTF-8 byte bound. Oversized values are\n * rejected by the running budget before a large clone is built. `maxBytes` may\n * be raised for independent, larger data channels; the default stays the control\n * envelope limit.\n */\nexport function encodeRpcJson(value: unknown, maxBytes: number = RPC_JSON_MAX_BYTES): string {\n assertByteLimit(maxBytes);\n const clone = snapshot(value, 0, new Set(), { left: maxBytes });\n const text = JSON.stringify(clone);\n if (typeof text !== 'string') failData('json');\n if (Buffer.byteLength(text, 'utf8') > maxBytes) failSize();\n return text;\n}\n\n/** Deterministic encoding for signed RPC metadata, retaining every legal JSON key. */\nexport function encodeCanonicalRpcJson(value: unknown, maxBytes: number = RPC_JSON_MAX_BYTES): string {\n assertByteLimit(maxBytes);\n const clone = snapshot(value, 0, new Set(), { left: maxBytes });\n const canonical = (item: RpcJson): string => {\n if (item === null || typeof item !== 'object') return JSON.stringify(item);\n if (Array.isArray(item)) return `[${item.map(canonical).join(',')}]`;\n const record = item as Readonly<Record<string, RpcJson>>;\n return `{${Object.keys(record).sort().map(key => `${JSON.stringify(key)}:${canonical(record[key])}`).join(',')}}`;\n };\n const text = canonical(clone);\n if (Buffer.byteLength(text, 'utf8') > maxBytes) failSize();\n return text;\n}\n\n/** Parses strict, bounded pure JSON. Non-finite numbers and lone surrogates are rejected. */\nexport function decodeRpcJson(text: string, maxBytes: number = RPC_JSON_MAX_BYTES): RpcJson {\n assertByteLimit(maxBytes);\n if (typeof text !== 'string') failData('json');\n if (Buffer.byteLength(text, 'utf8') > maxBytes) failSize();\n scanJson(text);\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n throw new RpcProtocolError('invalid_data', 'invalid JSON text');\n }\n assertJsonGraph(parsed);\n return parsed as RpcJson;\n}\n\nfunction jsonEquals(left: RpcJson, right: RpcJson): boolean {\n if (left === right) return true;\n if (typeof left !== typeof right) return false;\n if (Array.isArray(left) !== Array.isArray(right)) return false;\n if (Array.isArray(left)) {\n if (!Array.isArray(right) || left.length !== right.length) return false;\n for (let index = 0; index < left.length; index += 1) {\n if (!jsonEquals(left[index], right[index])) return false;\n }\n return true;\n }\n if (typeof left === 'object' && left !== null && right !== null && typeof right === 'object') {\n const leftRecord = left as Record<string, RpcJson>;\n const rightRecord = right as Record<string, RpcJson>;\n const keys = Object.keys(leftRecord);\n if (keys.length !== Object.keys(rightRecord).length) return false;\n for (const key of keys) {\n if (!Object.prototype.hasOwnProperty.call(rightRecord, key)) return false;\n if (!jsonEquals(leftRecord[key], rightRecord[key])) return false;\n }\n return true;\n }\n return false;\n}\n\nfunction checkOptionalNonNegative(value: unknown, field: string): number | undefined {\n if (value === undefined) return undefined;\n if (!isNonNegativeSafeInteger(value)) failContract(`${field} must be a non-negative safe integer`);\n return value;\n}\n\nfunction checkOptionalFinite(value: unknown, field: string): number | undefined {\n if (value === undefined) return undefined;\n if (typeof value !== 'number' || !Number.isFinite(value)) failContract(`${field} must be a finite number`);\n return value;\n}\n\nfunction checkSchema(input: unknown, depth: number, seen: Set<object>): void {\n if (depth > SCHEMA_MAX_DEPTH) failContract('schema nesting exceeds the limit');\n if (!isPlainObject(input)) failContract('schema must be a plain object');\n if (seen.has(input)) failContract('schema must not contain cycles');\n seen.add(input);\n const type = input.type;\n if (type === 'string') {\n assertKnownKeys(input, ['type', 'minLength', 'maxLength'], 'schema');\n const min = checkOptionalNonNegative(input.minLength, 'minLength');\n const max = checkOptionalNonNegative(input.maxLength, 'maxLength');\n if (min !== undefined && max !== undefined && min > max) failContract('string minLength must not exceed maxLength');\n } else if (type === 'number') {\n assertKnownKeys(input, ['type', 'integer', 'minimum', 'maximum'], 'schema');\n if (input.integer !== undefined && typeof input.integer !== 'boolean') failContract('number integer flag must be boolean');\n const min = checkOptionalFinite(input.minimum, 'minimum');\n const max = checkOptionalFinite(input.maximum, 'maximum');\n if (min !== undefined && max !== undefined && min > max) failContract('number minimum must not exceed maximum');\n } else if (type === 'boolean') {\n assertKnownKeys(input, ['type'], 'schema');\n } else if (type === 'null') {\n assertKnownKeys(input, ['type'], 'schema');\n } else if (type === 'literal') {\n assertKnownKeys(input, ['type', 'value'], 'schema');\n if (!Object.prototype.hasOwnProperty.call(input, 'value')) failContract('literal schema requires a value');\n try {\n snapshot(input.value, 0, new Set(), { left: Infinity });\n } catch (error) {\n if (error instanceof RpcProtocolError && error.code === 'invalid_data') {\n failContract('literal value must be pure JSON');\n }\n throw error;\n }\n } else if (type === 'array') {\n assertKnownKeys(input, ['type', 'items', 'maxItems'], 'schema');\n if (!Object.prototype.hasOwnProperty.call(input, 'items')) failContract('array schema requires items');\n checkSchema(input.items, depth + 1, seen);\n checkOptionalNonNegative(input.maxItems, 'maxItems');\n } else if (type === 'object') {\n assertKnownKeys(input, ['type', 'properties', 'optional'], 'schema');\n const properties = input.properties;\n if (!isPlainObject(properties)) failContract('object schema requires a properties record');\n for (const key of Object.keys(properties)) checkSchema(properties[key], depth + 1, seen);\n const optional = input.optional;\n if (optional !== undefined) {\n if (!Array.isArray(optional)) failContract('object optional must be an array of field names');\n const names = new Set<string>();\n for (const name of optional) {\n if (typeof name !== 'string') failContract('object optional entries must be strings');\n if (names.has(name)) failContract('object optional entries must be unique');\n names.add(name);\n if (!Object.prototype.hasOwnProperty.call(properties, name)) {\n failContract('object optional names must exist in properties');\n }\n }\n }\n } else if (type === 'record') {\n assertKnownKeys(input, ['type', 'values', 'maxEntries'], 'schema');\n if (!Object.prototype.hasOwnProperty.call(input, 'values')) failContract('record schema requires values');\n checkSchema(input.values, depth + 1, seen);\n checkOptionalNonNegative(input.maxEntries, 'maxEntries');\n } else if (type === 'union') {\n assertKnownKeys(input, ['type', 'variants'], 'schema');\n const variants = input.variants;\n if (!Array.isArray(variants) || variants.length === 0) {\n failContract('union schema requires a non-empty variants array');\n }\n for (const variant of variants) checkSchema(variant, depth + 1, seen);\n } else if (type === 'json') {\n assertKnownKeys(input, ['type', 'maxBytes'], 'schema');\n if (input.maxBytes !== undefined && !isPositiveSafeInteger(input.maxBytes)) {\n failContract('json schema maxBytes must be a positive safe integer');\n }\n } else {\n failContract('unknown schema type');\n }\n seen.delete(input);\n}\n\nfunction validateValue(schema: RpcDataSchema, value: unknown): void {\n switch (schema.type) {\n case 'string': {\n if (typeof value !== 'string') failData('string');\n if (schema.minLength !== undefined && value.length < schema.minLength) failData('string');\n if (schema.maxLength !== undefined && value.length > schema.maxLength) failData('string');\n return;\n }\n case 'number': {\n if (typeof value !== 'number' || !Number.isFinite(value)) failData('number');\n if (schema.integer === true && !Number.isInteger(value)) failData('number');\n if (schema.minimum !== undefined && value < schema.minimum) failData('number');\n if (schema.maximum !== undefined && value > schema.maximum) failData('number');\n return;\n }\n case 'boolean': {\n if (typeof value !== 'boolean') failData('boolean');\n return;\n }\n case 'null': {\n if (value !== null) failData('null');\n return;\n }\n case 'literal': {\n if (!jsonEquals(schema.value, value as RpcJson)) failData('literal');\n return;\n }\n case 'array': {\n if (!Array.isArray(value)) failData('array');\n if (schema.maxItems !== undefined && value.length > schema.maxItems) failData('array');\n for (const item of value) validateValue(schema.items, item);\n return;\n }\n case 'object': {\n if (!isPlainObject(value)) failData('object');\n const optional = new Set(schema.optional ?? []);\n for (const key of Object.keys(value)) {\n if (!Object.prototype.hasOwnProperty.call(schema.properties, key)) failData('object');\n }\n for (const key of Object.keys(schema.properties)) {\n if (!Object.prototype.hasOwnProperty.call(value, key)) {\n if (!optional.has(key)) failData('object');\n continue;\n }\n validateValue(schema.properties[key], value[key]);\n }\n return;\n }\n case 'record': {\n if (!isPlainObject(value)) failData('record');\n const keys = Object.keys(value);\n if (schema.maxEntries !== undefined && keys.length > schema.maxEntries) failData('record');\n for (const key of keys) validateValue(schema.values, value[key]);\n return;\n }\n case 'union': {\n for (const variant of schema.variants) {\n try {\n validateValue(variant, value);\n return;\n } catch (error) {\n if (!(error instanceof RpcProtocolError) || error.code !== 'invalid_data') throw error;\n }\n }\n failData('union');\n }\n case 'json': {\n const maxBytes = schema.maxBytes ?? RPC_JSON_MAX_BYTES;\n const text = JSON.stringify(value);\n if (typeof text !== 'string' || Buffer.byteLength(text, 'utf8') > maxBytes) failData('json');\n return;\n }\n }\n}\n\n/**\n * Asserts a runtime value matches the schema. The whole value is first cloned\n * into bounded pure JSON without invoking accessors, then validated. Throws\n * `RpcProtocolError` with `invalid_data` (value) or `invalid_contract` (malformed\n * schema).\n */\n/** Validates a standalone data schema (lane contract registration) without a value. */\nexport function assertRpcDataSchema(schema: RpcDataSchema): void {\n const pure = snapshotPureInput(schema);\n checkSchema(pure, 0, new Set());\n}\n\nexport function assertRpcData<S extends RpcDataSchema>(\n schema: S,\n value: unknown,\n maxBytes?: number,\n): asserts value is InferRpcData<S> { const pureSchema = snapshotPureInput(schema);\n checkSchema(pureSchema, 0, new Set());\n const checkedSchema = pureSchema as unknown as RpcDataSchema;\n const limit = maxBytes ?? (checkedSchema.type === 'json' ? checkedSchema.maxBytes ?? RPC_JSON_MAX_BYTES : RPC_JSON_MAX_BYTES);\n assertByteLimit(limit);\n let pureValue: RpcJson;\n try { pureValue = snapshot(value, 0, new Set(), { left: limit }); }\n catch (error) {\n if (error instanceof RpcProtocolError && error.code === 'size_limit') failData('json');\n throw error;\n }\n if (Buffer.byteLength(JSON.stringify(pureValue), 'utf8') > limit) failData('json');\n validateValue(checkedSchema, pureValue);\n}\n\nfunction assertByteLimit(maxBytes: number): void {\n if (!isPositiveSafeInteger(maxBytes)) failContract('maxBytes must be a positive safe integer');\n}\n\nfunction checkByteLimit(value: unknown, field: string): number | undefined {\n if (value === undefined) return undefined;\n if (!isPositiveSafeInteger(value) || value > RPC_JSON_MAX_BYTES) {\n failContract(`${field} must be a positive integer no larger than the RPC envelope`);\n }\n return value;\n}\n\nfunction checkCommandPolicy(policy: Record<string, unknown>, maxOutputBytes: number): void {\n const keys = Object.keys(policy);\n if (keys.length !== RPC_COMMAND_POLICY_KEYS.size || keys.some((key) => !RPC_COMMAND_POLICY_KEYS.has(key))) {\n failContract('command policy fields are fixed');\n }\n const deduplication = policy.deduplication;\n if (typeof deduplication !== 'string' || !RPC_COMMAND_DEDUPLICATION.has(deduplication as RpcCommandDeduplication)) {\n failContract('invalid command deduplication');\n }\n const retention = policy.resultRetentionMs;\n if (retention !== null && !isPositiveSafeInteger(retention)) {\n failContract('resultRetentionMs must be a positive integer or null');\n }\n const maxResultBytes = policy.maxResultBytes;\n if (!isPositiveSafeInteger(maxResultBytes)) failContract('maxResultBytes must be a positive safe integer');\n if (maxResultBytes > maxOutputBytes) failContract('maxResultBytes must not exceed maxOutputBytes');\n const quotaBytes = policy.quotaBytes;\n if (!isPositiveSafeInteger(quotaBytes)) failContract('quotaBytes must be a positive safe integer');\n if (quotaBytes < maxResultBytes) failContract('quotaBytes must be able to hold maxResultBytes');\n}\n\nfunction checkMethod(definition: Record<string, unknown>): void {\n assertKnownKeys(definition, METHOD_KEYS, 'method');\n const kind = definition.kind;\n if (kind !== 'query' && kind !== 'command') failContract('method kind must be query or command');\n checkSchema(definition.input, 0, new Set());\n checkSchema(definition.output, 0, new Set());\n const purposes = definition.purposes;\n if (!Array.isArray(purposes) || purposes.length === 0) failContract('purposes must be a non-empty array');\n const seenPurposes = new Set<string>();\n for (const purpose of purposes) {\n if (typeof purpose !== 'string' || !RPC_CALL_PURPOSES.has(purpose as RpcCallPurpose)) failContract('invalid purpose');\n if (seenPurposes.has(purpose)) failContract('purposes must be unique');\n seenPurposes.add(purpose);\n }\n if (definition.timeoutMs !== undefined) {\n if (!isPositiveSafeInteger(definition.timeoutMs) || definition.timeoutMs > RPC_MAX_TIMEOUT_MS) {\n failContract('timeoutMs must be a positive integer no larger than the timeout bound');\n }\n }\n checkByteLimit(definition.maxInputBytes, 'maxInputBytes');\n const maxOutputBytes = checkByteLimit(definition.maxOutputBytes, 'maxOutputBytes');\n const command = definition.command;\n if (kind === 'command') {\n if (!isPlainObject(command)) failContract('command methods require an explicit command policy');\n checkCommandPolicy(command, maxOutputBytes ?? RPC_JSON_MAX_BYTES);\n } else if (command !== undefined) {\n failContract('query methods must not declare a command policy');\n }\n}\n\nfunction checkContract(contract: unknown): void {\n if (!isPlainObject(contract)) failContract('contract must be a plain object');\n assertKnownKeys(contract, CONTRACT_KEYS, 'contract');\n if (typeof contract.id !== 'string' || !RPC_SERVICE_ID.test(contract.id)) failContract('invalid service id');\n if (!isPositiveSafeInteger(contract.version)) failContract('service version must be a positive safe integer');\n const methods = contract.methods;\n if (!isPlainObject(methods)) failContract('methods must be a plain object');\n const names = Object.keys(methods);\n if (names.length === 0) failContract('service must declare at least one method');\n if (names.length > RPC_MAX_METHODS) failContract('service declares too many methods');\n for (const name of names) {\n if (!RPC_METHOD_NAME.test(name)) failContract('invalid method name');\n const definition = methods[name];\n if (!isPlainObject(definition)) failContract('method definition must be a plain object');\n checkMethod(definition);\n }\n}\n\nfunction deepFreeze(value: unknown): unknown {\n if (Array.isArray(value)) {\n for (const item of value) deepFreeze(item);\n return Object.freeze(value);\n }\n if (isPlainObject(value)) {\n for (const key of Object.keys(value)) deepFreeze(value[key]);\n return Object.freeze(value);\n }\n return value;\n}\n\n/**\n * Validates a service contract and returns a deep-frozen pure clone. The caller's\n * objects are never read through accessors, never frozen, and never modified;\n * `methods` keeps its literal types so clients can derive call signatures.\n */\nexport function defineRpcService<const M extends Record<string, RpcMethodDefinition>>(contract: {\n readonly id: string;\n readonly version: number;\n readonly methods: M;\n}): RpcServiceContract<M> {\n const pure = snapshotPureInput(contract);\n checkContract(pure);\n return deepFreeze(pure) as unknown as RpcServiceContract<M>;\n}\n",
@@ -17,7 +20,7 @@
17
20
  "/** Declarative repair request; the host owns the next upstream attempt. */\nconst retryActionBrand=Symbol.for('@jeffusion/bungee/request-retry-action');\nexport class RequestRetryAction extends Error {\n readonly body:unknown;\n constructor(body: unknown, readonly reason: string) {\n super('gateway request repair retry');\n this.name = 'RequestRetryAction';\n Object.defineProperty(this,retryActionBrand,{value:true});\n Object.defineProperty(this,'body',{value:body,enumerable:false});\n }\n /** Plugins and host may bundle the SDK independently in the same process. */\n static [Symbol.hasInstance](value:unknown):boolean {\n return value instanceof Error && (value as unknown as Record<symbol,unknown>)[retryActionBrand]===true;\n }\n}\n",
18
21
  "import type { TokenStatsRange } from './plugin.types';\n\nconst HOUR = 3_600_000;\nexport const TOKEN_STATS_RETENTION_MS = 31 * 24 * HOUR;\nexport const TOKEN_STATS_RANGES = ['1h', '12h', '24h', '1d', '7d', '30d', 'day', 'week', 'month'] as const;\n\n/** Recent page ranges are consecutive elapsed hours; calendar ranges use local dates. */\nexport function tokenStatsWindow(range: TokenStatsRange, asOfMs: number, timeZone = 'UTC') {\n if (range === '1h' || range === '12h' || range === '24h') {\n const duration = { '1h': HOUR, '12h': 12 * HOUR, '24h': 24 * HOUR };\n const bucketMs = { '1h': 300_000, '12h': HOUR, '24h': 2 * HOUR }[range];\n return { startMs: asOfMs - duration[range], endMs: asOfMs, bucketMs };\n }\n if (range === '1d' || range === '7d' || range === '30d') {\n const days = { '1d': 1, '7d': 7, '30d': 30 }[range];\n const bucketMs = range === '1d' ? HOUR : 24 * HOUR;\n const startMs = asOfMs - days * 24 * HOUR;\n const bucketStarts = Array.from({ length: range === '1d' ? 24 : days }, (_, i) => startMs + i * bucketMs);\n return { startMs, endMs: asOfMs, bucketMs, bucketStarts };\n }\n const format = new Intl.DateTimeFormat('en-US', {\n timeZone, year: 'numeric', month: 'numeric', day: 'numeric',\n hour: 'numeric', minute: 'numeric', second: 'numeric', hourCycle: 'h23',\n });\n const parts = (ms: number) => Object.fromEntries(format.formatToParts(ms)\n .filter(part => part.type !== 'literal').map(part => [part.type, Number(part.value)]));\n const today = parts(asOfMs);\n const day = Date.UTC(today.year!, today.month! - 1, today.day!);\n // Resolve each local midnight separately so DST days can contain 23 or 25 hours.\n const midnight = (date: number) => {\n let candidate = date;\n for (let i = 0; i < 4; i++) {\n const p = parts(candidate);\n const local = Date.UTC(p.year!, p.month! - 1, p.day!, p.hour!, p.minute!, p.second!);\n const next = candidate + date - local;\n if (next === candidate) return candidate;\n candidate = next;\n }\n return candidate;\n };\n if (range === 'day') {\n const startMs = midnight(day);\n const bucketEndMs = midnight(day + 24 * HOUR);\n const bucketStarts = Array.from({ length: Math.ceil((bucketEndMs - startMs) / HOUR) }, (_, i) => startMs + i * HOUR);\n return { startMs, endMs: asOfMs, bucketMs: HOUR, bucketStarts, bucketEndMs };\n }\n const firstDay = range === 'month' ? Date.UTC(today.year!, today.month! - 1, 1)\n : day - ((new Date(day).getUTCDay() + 6) % 7) * 24 * HOUR;\n const nextPeriod = range === 'month' ? Date.UTC(today.year!, today.month!, 1) : firstDay + 7 * 24 * HOUR;\n const days = (nextPeriod - firstDay) / (24 * HOUR);\n const bucketStarts = Array.from({ length: days }, (_, i) => midnight(firstDay + i * 24 * HOUR));\n return { startMs: bucketStarts[0]!, endMs: asOfMs, bucketMs: 24 * HOUR, bucketStarts, bucketEndMs: midnight(nextPeriod) };\n}\n"
19
22
  ],
20
- "mappings": ";;AAAA;;;ACOA,IAAM,UAAU,OAAO,IAAI,mCAAmC;AAI9D,SAAS,YAAY,CAAC,WAAoB,CAAC,GAAkB;AAAA,EAC3D,MAAM,SAAS,CAAC,UACd,CAAC,OAAyB,YAAqB;AAAA,IAC7C,MAAM,OAAQ,WAAuC;AAAA,IACrD,IAAI,MAAM;AAAA,MACR,IAAI,OAAO,UAAU;AAAA,QAAU,KAAK,OAAO,UAAU,KAAK;AAAA,MACrD;AAAA,aAAK,OAAO,KAAI,aAAa,MAAK,GAAG,OAAO;AAAA,IACnD,EAAO,SAAI,UAAU,WAAW,QAAQ,IAAI,cAAc,SAAS;AAAA,MACjE,MAAM,QAAQ,UAAU,UAAU,QAAQ,QAAQ,QAAQ;AAAA,MAC1D,MAAM,YAAY,OAAO,UAAU,WAAW,QAAQ,KAAK,OAAO,UAAU,WAAW,WAAW,KAAI,aAAa,MAAK,CAAC;AAAA,IAC3H;AAAA;AAAA,EAEJ,OAAO;AAAA,IAAC,MAAM,OAAO,MAAM;AAAA,IAAG,MAAM,OAAO,MAAM;AAAA,IAAG,OAAO,OAAO,OAAO;AAAA,IAAG,OAAO,OAAO,OAAO;AAAA,IAC/F,OAAO,OAAO,OAAO;AAAA,IAAG,OAAO,WAAS,aAAa,KAAI,aAAa,MAAK,CAAC;AAAA,EAAC;AAAA;AAE1E,IAAM,SAAS,aAAa;;;ACd5B,IAAM,2BAA2B,OAAO,0BAA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