@vielzeug/archive 26.10.6 → 26.10.9

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 (53) hide show
  1. package/README.md +5 -3
  2. package/dist/_crypto.cjs +2 -0
  3. package/dist/_crypto.cjs.map +1 -0
  4. package/dist/_crypto.d.ts +7 -0
  5. package/dist/_crypto.d.ts.map +1 -0
  6. package/dist/_crypto.js +2 -0
  7. package/dist/_crypto.js.map +1 -0
  8. package/dist/auth/worker.cjs +4 -4
  9. package/dist/auth/worker.cjs.map +1 -1
  10. package/dist/auth/worker.d.ts.map +1 -1
  11. package/dist/auth/worker.js +4 -4
  12. package/dist/auth/worker.js.map +1 -1
  13. package/dist/auth.cjs +1 -1
  14. package/dist/auth.d.ts +0 -1
  15. package/dist/auth.d.ts.map +1 -1
  16. package/dist/auth.js +1 -1
  17. package/dist/collection.cjs +1 -1
  18. package/dist/collection.cjs.map +1 -1
  19. package/dist/collection.d.ts +9 -1
  20. package/dist/collection.d.ts.map +1 -1
  21. package/dist/collection.js +1 -1
  22. package/dist/collection.js.map +1 -1
  23. package/dist/contract.cjs.map +1 -1
  24. package/dist/contract.d.ts +4 -3
  25. package/dist/contract.d.ts.map +1 -1
  26. package/dist/contract.js.map +1 -1
  27. package/dist/errors.cjs.map +1 -1
  28. package/dist/errors.d.ts +1 -1
  29. package/dist/errors.d.ts.map +1 -1
  30. package/dist/errors.js.map +1 -1
  31. package/dist/worker/_pagination.cjs +1 -1
  32. package/dist/worker/_pagination.cjs.map +1 -1
  33. package/dist/worker/_pagination.d.ts +20 -7
  34. package/dist/worker/_pagination.d.ts.map +1 -1
  35. package/dist/worker/_pagination.js +1 -1
  36. package/dist/worker/_pagination.js.map +1 -1
  37. package/dist/worker/env.cjs +1 -1
  38. package/dist/worker/env.cjs.map +1 -1
  39. package/dist/worker/env.d.ts.map +1 -1
  40. package/dist/worker/env.js +1 -1
  41. package/dist/worker/env.js.map +1 -1
  42. package/dist/worker/publications.cjs +1 -1
  43. package/dist/worker/publications.cjs.map +1 -1
  44. package/dist/worker/publications.d.ts.map +1 -1
  45. package/dist/worker/publications.js +1 -1
  46. package/dist/worker/publications.js.map +1 -1
  47. package/dist/worker/sql.cjs +4 -4
  48. package/dist/worker/sql.cjs.map +1 -1
  49. package/dist/worker/sql.d.ts +3 -2
  50. package/dist/worker/sql.d.ts.map +1 -1
  51. package/dist/worker/sql.js +4 -4
  52. package/dist/worker/sql.js.map +1 -1
  53. package/package.json +2 -2
package/README.md CHANGED
@@ -50,8 +50,10 @@ are the same schemas the Worker uses. Payloads are stable JSON objects with
50
50
  sorted-key serialization; vocabularies are optional readonly arrays. The root
51
51
  entry is browser-safe. Deploy the sibling `@vielzeug/archive/auth` issuer with its
52
52
  required `AUTH_ARCHIVE` binding for coordinated account deletion, and bind the
53
- catalog's required `AUTH_ISSUER_SERVICE` to that issuer for an uncached
54
- session-version check after local JWT verification.
53
+ catalog's required `AUTH_ISSUER_SERVICE` to that issuer for signing-key retrieval
54
+ and an uncached session-version check after local JWT verification.
55
+ `JWT_JWKS_URL` selects the issuer's JWKS route; the catalog fetches it through
56
+ the service binding, not global `fetch`, including same-zone deployments.
55
57
 
56
58
  Issuer sessions carry the required `sessionVersion` claim backed by
57
59
  `auth_users.session_version`. `POST /api/v1/sign-out` only clears the current
@@ -75,7 +77,7 @@ not update existing rows.
75
77
  - [Usage Guide](https://vielzeug.dev/archive/usage)
76
78
  - [API Reference](https://vielzeug.dev/archive/api)
77
79
  - [Examples](https://vielzeug.dev/archive/examples)
78
- - [Release Status](https://vielzeug.dev/archive/migration)
80
+ - [Migration](https://vielzeug.dev/archive/migration)
79
81
 
80
82
  ## License
81
83
 
@@ -0,0 +1,2 @@
1
+ var sha256Hex=async e=>[...new Uint8Array(await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e)))].map(e=>e.toString(16).padStart(2,`0`)).join(``);exports.sha256Hex=sha256Hex;
2
+ //# sourceMappingURL=_crypto.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"_crypto.cjs","names":[],"sources":["../src/_crypto.ts"],"sourcesContent":["/**\n * The one SHA-256→hex helper shared by both server surfaces: the collection content\n * hash (browser-safe root) and the issuer's sign-in-link token hash. Web Crypto\n * only; no D1, JWKS or binding machinery.\n */\nexport const sha256Hex = async (text: string): Promise<string> =>\n [...new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text)))]\n .map((byte) => byte.toString(16).padStart(2, '0'))\n .join('');\n"],"mappings":"AAKA,IAAa,UAAY,KAAO,IAC9B,CAAC,GAAG,IAAI,WAAW,MAAM,OAAO,OAAO,OAAO,UAAW,IAAI,YAAY,CAAC,CAAC,OAAO,CAAI,CAAC,CAAC,CAAC,CAAC,CACvF,IAAK,GAAS,EAAK,SAAS,EAAE,CAAC,CAAC,SAAS,EAAG,GAAG,CAAC,CAAC,CACjD,KAAK,EAAE"}
@@ -0,0 +1,7 @@
1
+ /**
2
+ * The one SHA-256→hex helper shared by both server surfaces: the collection content
3
+ * hash (browser-safe root) and the issuer's sign-in-link token hash. Web Crypto
4
+ * only; no D1, JWKS or binding machinery.
5
+ */
6
+ export declare const sha256Hex: (text: string) => Promise<string>;
7
+ //# sourceMappingURL=_crypto.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"_crypto.d.ts","sourceRoot":"","sources":["../src/_crypto.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,eAAO,MAAM,SAAS,GAAU,MAAM,MAAM,KAAG,OAAO,CAAC,MAAM,CAGhD,CAAC"}
@@ -0,0 +1,2 @@
1
+ var sha256Hex=async e=>[...new Uint8Array(await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e)))].map(e=>e.toString(16).padStart(2,`0`)).join(``);export{sha256Hex};
2
+ //# sourceMappingURL=_crypto.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"_crypto.js","names":[],"sources":["../src/_crypto.ts"],"sourcesContent":["/**\n * The one SHA-256→hex helper shared by both server surfaces: the collection content\n * hash (browser-safe root) and the issuer's sign-in-link token hash. Web Crypto\n * only; no D1, JWKS or binding machinery.\n */\nexport const sha256Hex = async (text: string): Promise<string> =>\n [...new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text)))]\n .map((byte) => byte.toString(16).padStart(2, '0'))\n .join('');\n"],"mappings":"AAKA,IAAa,UAAY,KAAO,IAC9B,CAAC,GAAG,IAAI,WAAW,MAAM,OAAO,OAAO,OAAO,UAAW,IAAI,YAAY,CAAC,CAAC,OAAO,CAAI,CAAC,CAAC,CAAC,CAAC,CACvF,IAAK,GAAS,EAAK,SAAS,EAAE,CAAC,CAAC,SAAS,EAAG,GAAG,CAAC,CAAC,CACjD,KAAK,EAAE"}
@@ -1,16 +1,16 @@
1
- const e=require("../contract.cjs"),t=require("../worker/_service.cjs"),n=require("../worker/http.cjs"),r=require("./errors.cjs"),i=require("./config.cjs"),a=require("./store.cjs");let o=require("jose");var s={account:/^\/api\/v1\/auth\/account$/,health:/^\/api\/v1\/auth\/health$/,jwks:/^\/api\/v1\/auth\/jwks\.json$/,session:/^\/api\/v1\/auth\/session$/,signIn:/^\/api\/v1\/auth\/sign-in$/,signOutAll:/^\/api\/v1\/auth\/sign-out-all$/,verify:/^\/api\/v1\/auth\/verify$/},c={account:[`GET`,`DELETE`],health:[`GET`],jwks:[`GET`],session:[`GET`],signIn:[`POST`],signOutAll:[`POST`],verify:[`GET`,`POST`]},l={account:`/auth/account`,health:`/auth/health`,jwks:`/auth/jwks.json`,session:`/auth/session`,signIn:`/auth/sign-in`,signOutAll:`/auth/sign-out-all`,verify:`/auth/verify`},matchRoute=e=>Object.keys(s).find(t=>s[t].test(new URL(e.url).pathname)),u=32,d=/^[A-Za-z0-9_-]{43}$/,f=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,p=256,m=5,hex=e=>[...new Uint8Array(e)].map(e=>e.toString(16).padStart(2,`0`)).join(``),hashToken=async e=>hex(await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e))),randomToken=()=>btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(u)))).replaceAll(`+`,`-`).replaceAll(`/`,`_`).replace(/=+$/,``),escapeHtml=e=>e.replace(/[&<>"']/g,e=>`&#${e.charCodeAt(0)};`),unavailable=()=>new r.AuthOperationError(503,`catalog`);function requireMutationGuard(e,t,r=!1){let i=e.headers.get(`origin`);if(i===null||!t.allowedOrigins.has(i)&&!(r&&i===t.publicOrigin)||e.headers.get(`x-archive-request`)!==`1`)throw n.forbidden();return i}function corsHeaders(e,t){let n=e.headers.get(`origin`);return n===null||!t.allowedOrigins.has(n)&&(matchRoute(e)!==`verify`||n!==t.publicOrigin)?{}:{"access-control-allow-credentials":`true`,"access-control-allow-origin":n,vary:`Origin`}}function preflight(t,r,i){let a=corsHeaders(t,r);if(Object.keys(a).length===0)throw n.forbidden();return new Response(null,{headers:{...a,"access-control-allow-headers":`Content-Type, ${e.ACCOUNT_HEADER}, ${e.PUBLISHER_HEADER}, ${e.REQUEST_MARKER_HEADER}`,"access-control-allow-methods":[...i,`OPTIONS`].join(`, `),"access-control-max-age":`600`},status:204})}var secure=e=>e.appEnv===`production`;async function mintSession(t,n,r,i){let a=r?900:e.SESSION_MAX_AGE_SECONDS;return{maxAge:a,token:await new o.SignJWT({sessionVersion:i,...r?{roles:[e.ARCHIVE_OPERATOR_ROLE]}:{}}).setProtectedHeader({alg:`RS256`,kid:t.signing.kid,typ:`JWT`}).setIssuedAt().setJti(crypto.randomUUID()).setIssuer(t.issuer).setAudience(t.audience).setSubject(n).setExpirationTime(`${a}s`).sign(t.signing.key)}}async function requireSession(t,r,i){let s=n.sessionToken(t);if(s===null)throw n.unauthenticated();try{let{payload:t}=await(0,o.jwtVerify)(s,r.verifier,{algorithms:[`RS256`],audience:r.audience,clockTolerance:m,issuer:r.issuer,maxTokenAge:e.SESSION_MAX_AGE_SECONDS,requiredClaims:[`sub`,`iss`,`aud`,`iat`,`exp`,`sessionVersion`]}),c=t.sub??``;if(c.length===0||c.length>p||!e.isWellFormedText(c))throw n.unauthenticated();let l=t.sessionVersion;if(typeof l!=`number`||!Number.isSafeInteger(l)||l<0||typeof t.iat!=`number`||t.iat>Date.now()/1e3+m||Array.isArray(t.roles)&&t.roles.includes(`archive-operator`)&&(typeof t.exp!=`number`||t.exp-t.iat>900||Date.now()/1e3-t.iat>900+m))throw n.unauthenticated();let u=await a.readAccount(i.AUTH_DB,c);if(u===null||u.session_version!==l)throw n.unauthenticated();return{sessionVersion:l,subject:c,token:s}}catch(e){throw e instanceof o.errors.JOSEError?n.unauthenticated():e}}async function sendLink(e,t,n,r){let i=t.appName,o=`The link works once and expires in ${a.LINK_TTL_MS/6e4} minutes. If you did not request it, ignore this email.`;await e.AUTH_EMAIL.send({from:t.senderAddress,html:`<p>Open this link to sign in to ${escapeHtml(i)}:</p><p><a href="${escapeHtml(r)}">${escapeHtml(r)}</a></p><p>${o}</p>`,subject:`Your ${i} sign-in link`,text:`Open this link to sign in to ${i}:\n\n${r}\n\n${o}`,to:n})}async function handleSignIn(e,t,o){requireMutationGuard(e,o);let s=await n.readJsonBody(e);if(typeof s!=`object`||!s||Array.isArray(s))throw n.badRequest();let c=Object.keys(s),l=Reflect.get(s,`email`);if(c.length!==1||c[0]!==`email`||typeof l!=`string`)throw n.badRequest();let u=l.trim().toLowerCase();if(!i.isWellFormedEmail(u))throw n.badRequest();let d=Date.now(),f=await a.spendSignInBudget(t.AUTH_DB,d);if(f!==null)throw new n.ApiError(429,`rate-limited`,`Too many sign-in requests. Try again later.`,{retryAfterSeconds:f});let p=await a.ensureUser(t.AUTH_DB,u),m=await a.spendLinkBudget(t.AUTH_DB,p.id,d);if(m!==null)throw new n.ApiError(429,`rate-limited`,`Too many sign-in emails. Try again later.`,{retryAfterSeconds:m});let h=randomToken(),g=await hashToken(h);await a.insertToken(t.AUTH_DB,g,p.id,d);try{await sendLink(t,o,p.email,`${o.publicOrigin}/api/v1/auth/verify?token=${h}`)}catch(e){throw await a.deleteToken(t.AUTH_DB,g).catch(()=>void 0),new r.AuthOperationError(503,`email`,{cause:e})}return n.json(202,{ok:!0},n.noStore)}async function handleVerify(t,r,i){if(t.method===`GET`){let r=n.queryParams(new URL(t.url),[`token`]).get(`token`)??``;if(!d.test(r))throw n.badRequest(`The link is not valid.`);let a=randomToken(),o=`<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Confirm sign-in</title><h1>Sign in to ${escapeHtml(i.appName)}</h1><p>Continue only if you requested this sign-in link.</p><button type="button" id="confirm">Confirm sign-in</button><p role="status" id="status"></p><script nonce="${a}">
1
+ const e=require("../_crypto.cjs"),t=require("../contract.cjs"),n=require("../worker/_service.cjs"),r=require("../worker/http.cjs"),i=require("./errors.cjs"),a=require("./config.cjs"),o=require("./store.cjs");let s=require("jose");var c={account:/^\/api\/v1\/auth\/account$/,health:/^\/api\/v1\/auth\/health$/,jwks:/^\/api\/v1\/auth\/jwks\.json$/,session:/^\/api\/v1\/auth\/session$/,signIn:/^\/api\/v1\/auth\/sign-in$/,signOutAll:/^\/api\/v1\/auth\/sign-out-all$/,verify:/^\/api\/v1\/auth\/verify$/},l={account:[`GET`,`DELETE`],health:[`GET`],jwks:[`GET`],session:[`GET`],signIn:[`POST`],signOutAll:[`POST`],verify:[`GET`,`POST`]},u={account:`/auth/account`,health:`/auth/health`,jwks:`/auth/jwks.json`,session:`/auth/session`,signIn:`/auth/sign-in`,signOutAll:`/auth/sign-out-all`,verify:`/auth/verify`},matchRoute=e=>Object.keys(c).find(t=>c[t].test(new URL(e.url).pathname)),d=32,f=/^[A-Za-z0-9_-]{43}$/,p=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,m=256,h=5,randomToken=()=>btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(d)))).replaceAll(`+`,`-`).replaceAll(`/`,`_`).replace(/=+$/,``),escapeHtml=e=>e.replace(/[&<>"']/g,e=>`&#${e.charCodeAt(0)};`),unavailable=()=>new i.AuthOperationError(503,`catalog`);function requireMutationGuard(e,t,n=!1){let i=e.headers.get(`origin`);if(i===null||!t.allowedOrigins.has(i)&&!(n&&i===t.publicOrigin)||e.headers.get(`x-archive-request`)!==`1`)throw r.forbidden();return i}function corsHeaders(e,t){let n=e.headers.get(`origin`);return n===null||!t.allowedOrigins.has(n)&&(matchRoute(e)!==`verify`||n!==t.publicOrigin)?{}:{"access-control-allow-credentials":`true`,"access-control-allow-origin":n,vary:`Origin`}}function preflight(e,n,i){let a=corsHeaders(e,n);if(Object.keys(a).length===0)throw r.forbidden();return new Response(null,{headers:{...a,"access-control-allow-headers":`Content-Type, ${t.ACCOUNT_HEADER}, ${t.PUBLISHER_HEADER}, ${t.REQUEST_MARKER_HEADER}`,"access-control-allow-methods":[...i,`OPTIONS`].join(`, `),"access-control-max-age":`600`},status:204})}var secure=e=>e.appEnv===`production`;async function mintSession(e,n,r,i){let a=r?900:t.SESSION_MAX_AGE_SECONDS;return{maxAge:a,token:await new s.SignJWT({sessionVersion:i,...r?{roles:[t.ARCHIVE_OPERATOR_ROLE]}:{}}).setProtectedHeader({alg:`RS256`,kid:e.signing.kid,typ:`JWT`}).setIssuedAt().setJti(crypto.randomUUID()).setIssuer(e.issuer).setAudience(e.audience).setSubject(n).setExpirationTime(`${a}s`).sign(e.signing.key)}}async function requireSession(e,n,i){let a=r.sessionToken(e);if(a===null)throw r.unauthenticated();try{let{payload:e}=await(0,s.jwtVerify)(a,n.verifier,{algorithms:[`RS256`],audience:n.audience,clockTolerance:h,issuer:n.issuer,maxTokenAge:t.SESSION_MAX_AGE_SECONDS,requiredClaims:[`sub`,`iss`,`aud`,`iat`,`exp`,`sessionVersion`]}),c=e.sub??``;if(c.length===0||c.length>m||!t.isWellFormedText(c))throw r.unauthenticated();let l=e.sessionVersion;if(typeof l!=`number`||!Number.isSafeInteger(l)||l<0||typeof e.iat!=`number`||e.iat>Date.now()/1e3+h||Array.isArray(e.roles)&&e.roles.includes(`archive-operator`)&&(typeof e.exp!=`number`||e.exp-e.iat>900||Date.now()/1e3-e.iat>900+h))throw r.unauthenticated();let u=await o.readAccount(i.AUTH_DB,c);if(u===null||u.session_version!==l)throw r.unauthenticated();return{sessionVersion:l,subject:c,token:a}}catch(e){throw e instanceof s.errors.JOSEError?r.unauthenticated():e}}async function sendLink(e,t,n,r){let i=t.appName,a=`The link works once and expires in ${o.LINK_TTL_MS/6e4} minutes. If you did not request it, ignore this email.`;await e.AUTH_EMAIL.send({from:t.senderAddress,html:`<p>Open this link to sign in to ${escapeHtml(i)}:</p><p><a href="${escapeHtml(r)}">${escapeHtml(r)}</a></p><p>${a}</p>`,subject:`Your ${i} sign-in link`,text:`Open this link to sign in to ${i}:\n\n${r}\n\n${a}`,to:n})}async function handleSignIn(t,n,s){requireMutationGuard(t,s);let c=await r.readJsonBody(t);if(typeof c!=`object`||!c||Array.isArray(c))throw r.badRequest();let l=Object.keys(c),u=Reflect.get(c,`email`);if(l.length!==1||l[0]!==`email`||typeof u!=`string`)throw r.badRequest();let d=u.trim().toLowerCase();if(!a.isWellFormedEmail(d))throw r.badRequest();let f=Date.now(),p=await o.spendSignInBudget(n.AUTH_DB,f);if(p!==null)throw new r.ApiError(429,`rate-limited`,`Too many sign-in requests. Try again later.`,{retryAfterSeconds:p});let m=await o.ensureUser(n.AUTH_DB,d),h=await o.spendLinkBudget(n.AUTH_DB,m.id,f);if(h!==null)throw new r.ApiError(429,`rate-limited`,`Too many sign-in emails. Try again later.`,{retryAfterSeconds:h});let g=randomToken(),_=await e.sha256Hex(g);await o.insertToken(n.AUTH_DB,_,m.id,f);try{await sendLink(n,s,m.email,`${s.publicOrigin}/api/v1/auth/verify?token=${g}`)}catch(e){throw await o.deleteToken(n.AUTH_DB,_).catch(()=>void 0),new i.AuthOperationError(503,`email`,{cause:e})}return r.json(202,{ok:!0},r.noStore)}async function handleVerify(n,i,a){if(n.method===`GET`){let e=r.queryParams(new URL(n.url),[`token`]).get(`token`)??``;if(!f.test(e))throw r.badRequest(`The link is not valid.`);let i=randomToken(),o=`<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Confirm sign-in</title><h1>Sign in to ${escapeHtml(a.appName)}</h1><p>Continue only if you requested this sign-in link.</p><button type="button" id="confirm">Confirm sign-in</button><p role="status" id="status"></p><script nonce="${i}">
2
2
  history.replaceState(null, '', location.pathname);
3
3
  document.getElementById('confirm').addEventListener('click', async () => {
4
4
  const button = document.getElementById('confirm');
5
5
  button.disabled = true;
6
6
  try {
7
- const response = await fetch(location.pathname, { method: 'POST', credentials: 'same-origin', headers: { 'content-type': 'application/json', '${e.REQUEST_MARKER_HEADER}': '1' }, body: JSON.stringify({ token: '${r}' }) });
7
+ const response = await fetch(location.pathname, { method: 'POST', credentials: 'same-origin', headers: { 'content-type': 'application/json', '${t.REQUEST_MARKER_HEADER}': '1' }, body: JSON.stringify({ token: '${e}' }) });
8
8
  if (!response.ok) throw new Error();
9
- location.replace(${JSON.stringify(`${i.publicOrigin}/signed-in`)});
9
+ location.replace(${JSON.stringify(`${a.publicOrigin}/signed-in`)});
10
10
  } catch {
11
11
  document.getElementById('status').textContent = 'Sign-in failed. Request a new link or try again.';
12
12
  button.disabled = false;
13
13
  }
14
14
  });
15
- <\/script></html>`;return new Response(o,{headers:{...n.noStore,"content-security-policy":`default-src 'none'; script-src 'nonce-${a}'; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`,"content-type":`text/html; charset=utf-8`,"referrer-policy":`no-referrer`,"x-content-type-options":`nosniff`}})}requireMutationGuard(t,i,!0),n.queryParams(new URL(t.url),[]);let o=await n.readJsonBody(t);if(typeof o!=`object`||!o||Array.isArray(o)||Object.keys(o).length!==1)throw n.badRequest(`The link is not valid.`);let s=Reflect.get(o,`token`);if(typeof s!=`string`||!d.test(s))throw n.badRequest(`The link is not valid.`);let c=await a.consumeToken(r.AUTH_DB,await hashToken(s),Date.now());if(c===null)throw new n.ApiError(410,`gone`,`That link has expired or was already used.`);let l=await mintSession(i,c.id,i.operatorEmails.has(c.email),c.sessionVersion);return new Response(null,{headers:{...n.noStore,"set-cookie":e.sessionCookieValue(l.token,{maxAgeSeconds:l.maxAge,secure:secure(i)})},status:204})}async function handleExport(e,t,r){let{subject:i}=await requireSession(e,r,t),o=await a.readAccount(t.AUTH_DB,i);if(o===null)throw n.unauthenticated();return n.json(200,{createdAt:o.created_at,email:o.email,id:o.id,lastSignInAt:o.last_sign_in_at},n.noStore)}async function archiveFailure(t){let r=await t.text().catch(()=>``),i=null;try{i=JSON.parse(r)}catch{i=null}let a=e.archiveErrorResponseSchema.safeParse(i);if(!a.success||t.status<400||t.status>599)throw unavailable();let{code:o,message:s,requestId:c}=a.data.error,l=t.headers.get(`retry-after`);return n.json(t.status,{error:{code:o,message:s,requestId:c}},l!==null&&/^\d{1,6}$/.test(l)?{...n.noStore,"retry-after":l}:n.noStore)}async function handleErase(i,o,s){let c=requireMutationGuard(i,s),{subject:l,token:u}=await requireSession(i,s,o),d=i.headers.get(e.ACCOUNT_HEADER);if(d===null||!e.uuidSchema.safeParse(d).success)throw n.badRequest();if(d!==l)throw new n.ApiError(409,`account-changed`,`The signed-in account changed since this request was prepared.`);let p=new Headers({cookie:`${e.SESSION_COOKIE_NAME}=${u}`,origin:c,[e.REQUEST_MARKER_HEADER]:`1`}),m=i.headers.get(e.PUBLISHER_HEADER);if(m!==null){if(!f.test(m))throw n.badRequest();p.set(e.PUBLISHER_HEADER,m)}let h;try{h=await t.serviceRequest(o.AUTH_ARCHIVE,new Request(`${s.publicOrigin}/api/v1/me/account`,{headers:p,method:`DELETE`,redirect:`manual`}),async e=>e.status===204?(await e.body?.cancel(),e):archiveFailure(e))}catch(e){throw new r.AuthOperationError(503,`catalog`,{cause:e})}return h.status===204?(await a.deleteAccount(o.AUTH_DB,l),new Response(null,{headers:{...n.noStore,"set-cookie":n.expiredSessionCookie(secure(s))},status:204})):h}async function handleSignOutAll(t,r,i){requireMutationGuard(t,i);let{subject:o,sessionVersion:s}=await requireSession(t,i,r),c=t.headers.get(e.ACCOUNT_HEADER);if(c===null||!e.uuidSchema.safeParse(c).success)throw n.badRequest();if(c!==o)throw new n.ApiError(409,`account-changed`,`The signed-in account changed since this request was prepared.`);if(await a.revokeSessions(r.AUTH_DB,o,s)===null)throw n.unauthenticated();return n.json(200,{ok:!0},{...n.noStore,"set-cookie":n.expiredSessionCookie(secure(i))})}async function handleHealth(t){let r=null,o=null;try{await i.authConfig(t)}catch{r=`configuration-unavailable`}if(r===null)try{o=await a.authReadiness(t.AUTH_DB),o!==1&&(r=`schema-mismatch`)}catch{r=`database-unavailable`}return n.json(r===null?200:503,e.archiveAuthHealthSchema.parse({dbSchemaVersion:o,reason:r,schemaVersion:1,status:r===null?`ok`:`degraded`}),n.noStore)}async function route(e,t){let r=e.method.toUpperCase(),a=matchRoute(e);if(a===void 0)throw new n.ApiError(404,`not-found`,`No such route.`);if(a===`health`&&r===`GET`)return handleHealth(t);let o=await i.authConfig(t),s=corsHeaders(e,o);if(r===`OPTIONS`)return preflight(e,o,c[a]);if(!c[a].includes(r))throw new n.ApiError(405,`method-not-allowed`,`That method is not allowed here.`);let l;switch(a){case`health`:l=await handleHealth(t);break;case`session`:await requireSession(e,o,t),l=n.json(200,{ok:!0},n.noStore);break;case`signOutAll`:l=await handleSignOutAll(e,t,o);break;case`jwks`:l=n.json(200,{keys:o.jwks},n.noStore);break;case`signIn`:l=await handleSignIn(e,t,o);break;case`verify`:l=await handleVerify(e,t,o);break;case`account`:l=r===`GET`?await handleExport(e,t,o):await handleErase(e,t,o)}return withCors(l,s)}function withCors(e,t){if(Object.keys(t).length===0)return e;let n=new Response(e.body,e);for(let[e,r]of Object.entries(t))n.headers.set(e,r);return n}var diagnostic=e=>e instanceof r.AuthOperationError?e.authDiagnostic:{kind:`internal`};function createAuthWorker(){let t=new Set,emit=e=>{for(let n of t)try{n(e)}catch{}};return{async fetch(r,a){let o=crypto.randomUUID(),s=Date.now(),c,u;try{c=await route(r,a)}catch(e){u=e,c=n.toErrorResponse(e,o);let t=await i.authConfig(a).catch(()=>null);t!==null&&(c=withCors(c,corsHeaders(r,t)))}if(matchRoute(r)===`verify`&&(c.headers.set(`cache-control`,`no-store`),c.headers.set(`referrer-policy`,`no-referrer`),c.headers.set(`x-content-type-options`,`nosniff`),c.headers.has(`content-security-policy`)||c.headers.set(`content-security-policy`,`default-src 'none'; base-uri 'none'; frame-ancestors 'none'`)),t.size>0){let t=matchRoute(r),i=c.status<400?`ok`:t===`health`?`unavailable`:u instanceof n.ApiError?u.code:`internal`,a=u===void 0&&c.status>=400?e.archiveErrorResponseSchema.safeParse(await c.clone().json().catch(()=>null)):null,d=t===`health`&&c.status===503?e.archiveAuthHealthSchema.safeParse(await c.clone().json().catch(()=>null)):null;emit({code:a?.success?a.data.error.code:i,ms:Math.max(0,Date.now()-s),requestId:o,route:t===void 0?`unmatched`:l[t],status:c.status,type:`request`,...c.status>=500?{diagnostic:d?.success?{kind:d.data.reason===`configuration-unavailable`?`configuration`:d.data.reason===`schema-mismatch`?`schema`:`database`}:u===void 0?{kind:`catalog`}:diagnostic(u)}:{}})}return c},async scheduled(e,n){try{await i.authConfig(n);let e=await a.sweep(n.AUTH_DB,Date.now());t.size>0&&emit({removed:e,status:`ok`,type:`scheduled`})}catch(e){throw t.size>0&&emit({diagnostic:diagnostic(e),status:`failed`,type:`scheduled`}),e}},tap(e,n){if(n?.signal?.aborted)return()=>void 0;let observer=t=>e(t),unsubscribe=()=>{t.delete(observer),n?.signal?.removeEventListener(`abort`,unsubscribe)};return t.add(observer),n?.signal?.addEventListener(`abort`,unsubscribe,{once:!0}),unsubscribe}}}exports.createAuthWorker=createAuthWorker;
15
+ <\/script></html>`;return new Response(o,{headers:{...r.noStore,"content-security-policy":`default-src 'none'; script-src 'nonce-${i}'; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`,"content-type":`text/html; charset=utf-8`,"referrer-policy":`no-referrer`,"x-content-type-options":`nosniff`}})}requireMutationGuard(n,a,!0),r.queryParams(new URL(n.url),[]);let s=await r.readJsonBody(n);if(typeof s!=`object`||!s||Array.isArray(s)||Object.keys(s).length!==1)throw r.badRequest(`The link is not valid.`);let c=Reflect.get(s,`token`);if(typeof c!=`string`||!f.test(c))throw r.badRequest(`The link is not valid.`);let l=await o.consumeToken(i.AUTH_DB,await e.sha256Hex(c),Date.now());if(l===null)throw new r.ApiError(410,`gone`,`That link has expired or was already used.`);let u=await mintSession(a,l.id,a.operatorEmails.has(l.email),l.sessionVersion);return new Response(null,{headers:{...r.noStore,"set-cookie":t.sessionCookieValue(u.token,{maxAgeSeconds:u.maxAge,secure:secure(a)})},status:204})}async function handleExport(e,t,n){let{subject:i}=await requireSession(e,n,t),a=await o.readAccount(t.AUTH_DB,i);if(a===null)throw r.unauthenticated();return r.json(200,{createdAt:a.created_at,email:a.email,id:a.id,lastSignInAt:a.last_sign_in_at},r.noStore)}async function archiveFailure(e){let n=await e.text().catch(()=>``),i=null;try{i=JSON.parse(n)}catch{i=null}let a=t.archiveErrorResponseSchema.safeParse(i);if(!a.success||e.status<400||e.status>599)throw unavailable();let{code:o,message:s,requestId:c}=a.data.error,l=e.headers.get(`retry-after`);return r.json(e.status,{error:{code:o,message:s,requestId:c}},l!==null&&/^\d{1,6}$/.test(l)?{...r.noStore,"retry-after":l}:r.noStore)}async function handleErase(e,a,s){let c=requireMutationGuard(e,s),{subject:l,token:u}=await requireSession(e,s,a),d=e.headers.get(t.ACCOUNT_HEADER);if(d===null||!t.uuidSchema.safeParse(d).success)throw r.badRequest();if(d!==l)throw new r.ApiError(409,`account-changed`,`The signed-in account changed since this request was prepared.`);let f=new Headers({cookie:`${t.SESSION_COOKIE_NAME}=${u}`,origin:c,[t.REQUEST_MARKER_HEADER]:`1`}),m=e.headers.get(t.PUBLISHER_HEADER);if(m!==null){if(!p.test(m))throw r.badRequest();f.set(t.PUBLISHER_HEADER,m)}let h;try{h=await n.serviceRequest(a.AUTH_ARCHIVE,new Request(`${s.publicOrigin}/api/v1/me/account`,{headers:f,method:`DELETE`,redirect:`manual`}),async e=>e.status===204?(await e.body?.cancel(),e):archiveFailure(e))}catch(e){throw new i.AuthOperationError(503,`catalog`,{cause:e})}return h.status===204?(await o.deleteAccount(a.AUTH_DB,l),new Response(null,{headers:{...r.noStore,"set-cookie":r.expiredSessionCookie(secure(s))},status:204})):h}async function handleSignOutAll(e,n,i){requireMutationGuard(e,i);let{subject:a,sessionVersion:s}=await requireSession(e,i,n),c=e.headers.get(t.ACCOUNT_HEADER);if(c===null||!t.uuidSchema.safeParse(c).success)throw r.badRequest();if(c!==a)throw new r.ApiError(409,`account-changed`,`The signed-in account changed since this request was prepared.`);if(await o.revokeSessions(n.AUTH_DB,a,s)===null)throw r.unauthenticated();return r.json(200,{ok:!0},{...r.noStore,"set-cookie":r.expiredSessionCookie(secure(i))})}async function handleHealth(e){let n=null,i=null;try{await a.authConfig(e)}catch{n=`configuration-unavailable`}if(n===null)try{i=await o.authReadiness(e.AUTH_DB),i!==1&&(n=`schema-mismatch`)}catch{n=`database-unavailable`}return r.json(n===null?200:503,t.archiveAuthHealthSchema.parse({dbSchemaVersion:i,reason:n,schemaVersion:1,status:n===null?`ok`:`degraded`}),r.noStore)}async function route(e,t){let n=e.method.toUpperCase(),i=matchRoute(e);if(i===void 0)throw new r.ApiError(404,`not-found`,`No such route.`);if(i===`health`&&n===`GET`)return handleHealth(t);let o=await a.authConfig(t),s=corsHeaders(e,o);if(n===`OPTIONS`)return preflight(e,o,l[i]);if(!l[i].includes(n))throw new r.ApiError(405,`method-not-allowed`,`That method is not allowed here.`);let c;switch(i){case`health`:c=await handleHealth(t);break;case`session`:await requireSession(e,o,t),c=r.json(200,{ok:!0},r.noStore);break;case`signOutAll`:c=await handleSignOutAll(e,t,o);break;case`jwks`:c=r.json(200,{keys:o.jwks},r.noStore);break;case`signIn`:c=await handleSignIn(e,t,o);break;case`verify`:c=await handleVerify(e,t,o);break;case`account`:c=n===`GET`?await handleExport(e,t,o):await handleErase(e,t,o)}return withCors(c,s)}function withCors(e,t){if(Object.keys(t).length===0)return e;let n=new Response(e.body,e);for(let[e,r]of Object.entries(t))n.headers.set(e,r);return n}var diagnostic=e=>e instanceof i.AuthOperationError?e.authDiagnostic:{kind:`internal`};function createAuthWorker(){let e=new Set,emit=t=>{for(let n of e)try{n(t)}catch{}};return{async fetch(n,i){let o=crypto.randomUUID(),s=Date.now(),c,l;try{c=await route(n,i)}catch(e){l=e,c=r.toErrorResponse(e,o);let t=await a.authConfig(i).catch(()=>null);t!==null&&(c=withCors(c,corsHeaders(n,t)))}if(matchRoute(n)===`verify`&&(c.headers.set(`cache-control`,`no-store`),c.headers.set(`referrer-policy`,`no-referrer`),c.headers.set(`x-content-type-options`,`nosniff`),c.headers.has(`content-security-policy`)||c.headers.set(`content-security-policy`,`default-src 'none'; base-uri 'none'; frame-ancestors 'none'`)),e.size>0){let e=matchRoute(n),i=c.status<400?`ok`:e===`health`?`unavailable`:l instanceof r.ApiError?l.code:`internal`,a=l===void 0&&c.status>=400?t.archiveErrorResponseSchema.safeParse(await c.clone().json().catch(()=>null)):null,d=e===`health`&&c.status===503?t.archiveAuthHealthSchema.safeParse(await c.clone().json().catch(()=>null)):null;emit({code:a?.success?a.data.error.code:i,ms:Math.max(0,Date.now()-s),requestId:o,route:e===void 0?`unmatched`:u[e],status:c.status,type:`request`,...c.status>=500?{diagnostic:d?.success?{kind:d.data.reason===`configuration-unavailable`?`configuration`:d.data.reason===`schema-mismatch`?`schema`:`database`}:l===void 0?{kind:`catalog`}:diagnostic(l)}:{}})}return c},async scheduled(t,n){try{await a.authConfig(n);let t=await o.sweep(n.AUTH_DB,Date.now());e.size>0&&emit({removed:t,status:`ok`,type:`scheduled`})}catch(t){throw e.size>0&&emit({diagnostic:diagnostic(t),status:`failed`,type:`scheduled`}),t}},tap(t,n){if(n?.signal?.aborted)return()=>void 0;let observer=e=>t(e),unsubscribe=()=>{e.delete(observer),n?.signal?.removeEventListener(`abort`,unsubscribe)};return e.add(observer),n?.signal?.addEventListener(`abort`,unsubscribe,{once:!0}),unsubscribe}}}exports.createAuthWorker=createAuthWorker;
16
16
  //# sourceMappingURL=worker.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"worker.cjs","names":[],"sources":["../../src/auth/worker.ts"],"sourcesContent":["import { errors, jwtVerify, SignJWT } from 'jose';\nimport {\n ACCOUNT_HEADER,\n ARCHIVE_OPERATOR_ROLE,\n type ArchiveErrorCode,\n AUTH_SCHEMA_VERSION,\n archiveAuthHealthSchema,\n archiveErrorResponseSchema,\n isWellFormedText,\n OPERATOR_SESSION_MAX_AGE_SECONDS,\n PUBLISHER_HEADER,\n REQUEST_MARKER_HEADER,\n SESSION_COOKIE_NAME,\n SESSION_MAX_AGE_SECONDS,\n sessionCookieValue,\n uuidSchema,\n} from '../contract';\nimport { serviceRequest } from '../worker/_service';\nimport {\n ApiError,\n badRequest,\n expiredSessionCookie,\n forbidden,\n json,\n noStore,\n queryParams,\n readJsonBody,\n sessionToken,\n toErrorResponse,\n unauthenticated,\n} from '../worker/http';\nimport type { ArchiveExecutionContext } from '../worker/worker';\nimport { type AuthConfig, type AuthWorkerEnv, authConfig, isWellFormedEmail } from './config';\nimport { type AuthDiagnostic, AuthOperationError } from './errors';\nimport {\n authReadiness,\n consumeToken,\n deleteAccount,\n deleteToken,\n ensureUser,\n insertToken,\n LINK_TTL_MS,\n readAccount,\n revokeSessions,\n spendLinkBudget,\n spendSignInBudget,\n sweep,\n} from './store';\n\n/**\n * The reference identity issuer: passwordless email accounts. A POST with an email\n * address ensures the account row and sends a single-use magic link; consuming it\n * signs the browser in by setting the `archive_session` cookie a catalog Worker\n * verifies — an RS256 JWT minted by the active private key, verifiable through\n * `/jwks.json` alongside any configured retired public keys. `OPERATOR_EMAILS` is\n * the one operator-membership truth; operator sessions are short-lived so a revoked\n * operator loses authority within minutes. The account routes export the issuer's\n * own record and erase it together with the catalog profile.\n */\nexport interface AuthWorkerHandler<E extends AuthWorkerEnv = AuthWorkerEnv> {\n fetch(request: Request, env: E, ctx?: ArchiveExecutionContext): Promise<Response>;\n /** The cron sweep: expired links, closed send windows and never-verified accounts. */\n scheduled(controller: unknown, env: E, ctx?: ArchiveExecutionContext): Promise<void>;\n tap(handler: (event: AuthEvent) => void, options?: { readonly signal?: AbortSignal }): () => void;\n}\n\nexport type AuthEvent =\n | {\n readonly type: 'request';\n readonly requestId: string;\n readonly route:\n | '/auth/account'\n | '/auth/jwks.json'\n | '/auth/sign-in'\n | '/auth/verify'\n | '/auth/session'\n | '/auth/sign-out-all'\n | '/auth/health'\n | 'unmatched';\n readonly status: number;\n readonly code: ArchiveErrorCode | 'ok';\n readonly ms: number;\n readonly diagnostic?: AuthDiagnostic;\n }\n | { readonly type: 'scheduled'; readonly status: 'ok'; readonly removed: number }\n | { readonly type: 'scheduled'; readonly status: 'failed'; readonly diagnostic: AuthDiagnostic };\n\nconst ROUTES = {\n account: /^\\/api\\/v1\\/auth\\/account$/,\n health: /^\\/api\\/v1\\/auth\\/health$/,\n jwks: /^\\/api\\/v1\\/auth\\/jwks\\.json$/,\n session: /^\\/api\\/v1\\/auth\\/session$/,\n signIn: /^\\/api\\/v1\\/auth\\/sign-in$/,\n signOutAll: /^\\/api\\/v1\\/auth\\/sign-out-all$/,\n verify: /^\\/api\\/v1\\/auth\\/verify$/,\n} as const;\n\nconst ROUTE_METHODS: Record<keyof typeof ROUTES, readonly string[]> = {\n account: ['GET', 'DELETE'],\n health: ['GET'],\n jwks: ['GET'],\n session: ['GET'],\n signIn: ['POST'],\n signOutAll: ['POST'],\n verify: ['GET', 'POST'],\n};\n\nconst ROUTE_LABELS = {\n account: '/auth/account',\n health: '/auth/health',\n jwks: '/auth/jwks.json',\n session: '/auth/session',\n signIn: '/auth/sign-in',\n signOutAll: '/auth/sign-out-all',\n verify: '/auth/verify',\n} as const;\n\nconst matchRoute = (request: Request): keyof typeof ROUTES | undefined =>\n (Object.keys(ROUTES) as (keyof typeof ROUTES)[]).find((id) => ROUTES[id].test(new URL(request.url).pathname));\n\nconst TOKEN_BYTES = 32;\n// Base64url of TOKEN_BYTES random bytes, unpadded.\nconst LINK_TOKEN = /^[A-Za-z0-9_-]{43}$/;\nconst PUBLISHER_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;\nconst SUBJECT_MAX = 256;\nconst CLOCK_TOLERANCE_SECONDS = 5;\n\nconst hex = (bytes: ArrayBuffer): string =>\n [...new Uint8Array(bytes)].map((byte) => byte.toString(16).padStart(2, '0')).join('');\n\nconst hashToken = async (token: string): Promise<string> =>\n hex(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(token)));\n\nconst randomToken = (): string =>\n btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(TOKEN_BYTES))))\n .replaceAll('+', '-')\n .replaceAll('/', '_')\n .replace(/=+$/, '');\n\nconst escapeHtml = (value: string): string => value.replace(/[&<>\"']/g, (char) => `&#${char.charCodeAt(0)};`);\n\nconst unavailable = (): ApiError => new AuthOperationError(503, 'catalog');\n\n/** Exact allowed Origin plus the request marker, like the catalog's mutation guard. */\nfunction requireMutationGuard(request: Request, config: AuthConfig, allowPublicOrigin = false): string {\n const origin = request.headers.get('origin');\n if (origin === null || (!config.allowedOrigins.has(origin) && !(allowPublicOrigin && origin === config.publicOrigin)))\n throw forbidden();\n if (request.headers.get(REQUEST_MARKER_HEADER) !== '1') throw forbidden();\n return origin;\n}\n\nfunction corsHeaders(request: Request, config: AuthConfig): Record<string, string> {\n const origin = request.headers.get('origin');\n if (\n origin === null ||\n (!config.allowedOrigins.has(origin) && !(matchRoute(request) === 'verify' && origin === config.publicOrigin))\n )\n return {};\n return { 'access-control-allow-credentials': 'true', 'access-control-allow-origin': origin, vary: 'Origin' };\n}\n\nfunction preflight(request: Request, config: AuthConfig, methods: readonly string[]): Response {\n const cors = corsHeaders(request, config);\n if (Object.keys(cors).length === 0) throw forbidden();\n return new Response(null, {\n headers: {\n ...cors,\n 'access-control-allow-headers': `Content-Type, ${ACCOUNT_HEADER}, ${PUBLISHER_HEADER}, ${REQUEST_MARKER_HEADER}`,\n 'access-control-allow-methods': [...methods, 'OPTIONS'].join(', '),\n 'access-control-max-age': '600',\n },\n status: 204,\n });\n}\n\nconst secure = (config: AuthConfig): boolean => config.appEnv === 'production';\n\nasync function mintSession(\n config: AuthConfig,\n subject: string,\n operator: boolean,\n sessionVersion: number,\n): Promise<{ maxAge: number; token: string }> {\n const maxAge = operator ? OPERATOR_SESSION_MAX_AGE_SECONDS : SESSION_MAX_AGE_SECONDS;\n const token = await new SignJWT({ sessionVersion, ...(operator ? { roles: [ARCHIVE_OPERATOR_ROLE] } : {}) })\n .setProtectedHeader({ alg: 'RS256', kid: config.signing.kid, typ: 'JWT' })\n .setIssuedAt()\n .setJti(crypto.randomUUID())\n .setIssuer(config.issuer)\n .setAudience(config.audience)\n .setSubject(subject)\n .setExpirationTime(`${maxAge}s`)\n .sign(config.signing.key);\n return { maxAge, token };\n}\n\n/** Verifies the request's own session cookie against every published key; returns the token and subject. */\nasync function requireSession(\n request: Request,\n config: AuthConfig,\n env: AuthWorkerEnv,\n): Promise<{ subject: string; token: string; sessionVersion: number }> {\n const token = sessionToken(request);\n if (token === null) throw unauthenticated();\n try {\n const { payload } = await jwtVerify(token, config.verifier, {\n algorithms: ['RS256'],\n audience: config.audience,\n clockTolerance: CLOCK_TOLERANCE_SECONDS,\n issuer: config.issuer,\n maxTokenAge: SESSION_MAX_AGE_SECONDS,\n requiredClaims: ['sub', 'iss', 'aud', 'iat', 'exp', 'sessionVersion'],\n });\n const subject = payload.sub ?? '';\n if (subject.length === 0 || subject.length > SUBJECT_MAX || !isWellFormedText(subject)) throw unauthenticated();\n const version = payload.sessionVersion;\n if (typeof version !== 'number' || !Number.isSafeInteger(version) || version < 0) throw unauthenticated();\n if (typeof payload.iat !== 'number' || payload.iat > Date.now() / 1000 + CLOCK_TOLERANCE_SECONDS)\n throw unauthenticated();\n if (\n Array.isArray(payload.roles) &&\n payload.roles.includes(ARCHIVE_OPERATOR_ROLE) &&\n (typeof payload.exp !== 'number' ||\n payload.exp - payload.iat > OPERATOR_SESSION_MAX_AGE_SECONDS ||\n Date.now() / 1000 - payload.iat > OPERATOR_SESSION_MAX_AGE_SECONDS + CLOCK_TOLERANCE_SECONDS)\n )\n throw unauthenticated();\n const account = await readAccount(env.AUTH_DB, subject);\n if (account === null || account.session_version !== version) throw unauthenticated();\n return { sessionVersion: version, subject, token };\n } catch (error) {\n if (error instanceof errors.JOSEError) throw unauthenticated();\n throw error;\n }\n}\n\nasync function sendLink(env: AuthWorkerEnv, config: AuthConfig, to: string, link: string): Promise<void> {\n const name = config.appName;\n const minutes = LINK_TTL_MS / 60_000;\n const notice = `The link works once and expires in ${minutes} minutes. If you did not request it, ignore this email.`;\n await env.AUTH_EMAIL.send({\n from: config.senderAddress,\n html: `<p>Open this link to sign in to ${escapeHtml(name)}:</p><p><a href=\"${escapeHtml(link)}\">${escapeHtml(link)}</a></p><p>${notice}</p>`,\n subject: `Your ${name} sign-in link`,\n text: `Open this link to sign in to ${name}:\\n\\n${link}\\n\\n${notice}`,\n to,\n });\n}\n\nasync function handleSignIn(request: Request, env: AuthWorkerEnv, config: AuthConfig): Promise<Response> {\n requireMutationGuard(request, config);\n const body = await readJsonBody(request);\n if (typeof body !== 'object' || body === null || Array.isArray(body)) throw badRequest();\n const keys = Object.keys(body);\n const requestedEmail: unknown = Reflect.get(body, 'email');\n if (keys.length !== 1 || keys[0] !== 'email' || typeof requestedEmail !== 'string') {\n throw badRequest();\n }\n const email = requestedEmail.trim().toLowerCase();\n if (!isWellFormedEmail(email)) {\n throw badRequest();\n }\n const nowMs = Date.now();\n const admissionRetry = await spendSignInBudget(env.AUTH_DB, nowMs);\n if (admissionRetry !== null) {\n throw new ApiError(429, 'rate-limited', 'Too many sign-in requests. Try again later.', {\n retryAfterSeconds: admissionRetry,\n });\n }\n const user = await ensureUser(env.AUTH_DB, email);\n const retryAfterSeconds = await spendLinkBudget(env.AUTH_DB, user.id, nowMs);\n if (retryAfterSeconds !== null) {\n throw new ApiError(429, 'rate-limited', 'Too many sign-in emails. Try again later.', { retryAfterSeconds });\n }\n const token = randomToken();\n const tokenHash = await hashToken(token);\n await insertToken(env.AUTH_DB, tokenHash, user.id, nowMs);\n try {\n await sendLink(env, config, user.email, `${config.publicOrigin}/api/v1/auth/verify?token=${token}`);\n } catch (error) {\n // An unsent link is useless; the spent allowance is deliberately not refunded.\n await deleteToken(env.AUTH_DB, tokenHash).catch(() => undefined);\n throw new AuthOperationError(503, 'email', { cause: error });\n }\n return json(202, { ok: true }, noStore);\n}\n\nasync function handleVerify(request: Request, env: AuthWorkerEnv, config: AuthConfig): Promise<Response> {\n if (request.method === 'GET') {\n const token = queryParams(new URL(request.url), ['token']).get('token') ?? '';\n if (!LINK_TOKEN.test(token)) throw badRequest('The link is not valid.');\n const nonce = randomToken();\n // No automatic redemption, external assets or referrers. Only a deliberate\n // button click makes the same-origin marked POST; scanners can safely GET.\n const html = `<!doctype html><html lang=\"en\"><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width\"><title>Confirm sign-in</title><h1>Sign in to ${escapeHtml(config.appName)}</h1><p>Continue only if you requested this sign-in link.</p><button type=\"button\" id=\"confirm\">Confirm sign-in</button><p role=\"status\" id=\"status\"></p><script nonce=\"${nonce}\">\nhistory.replaceState(null, '', location.pathname);\ndocument.getElementById('confirm').addEventListener('click', async () => {\n const button = document.getElementById('confirm');\n button.disabled = true;\n try {\n const response = await fetch(location.pathname, { method: 'POST', credentials: 'same-origin', headers: { 'content-type': 'application/json', '${REQUEST_MARKER_HEADER}': '1' }, body: JSON.stringify({ token: '${token}' }) });\n if (!response.ok) throw new Error();\n location.replace(${JSON.stringify(`${config.publicOrigin}/signed-in`)});\n } catch {\n document.getElementById('status').textContent = 'Sign-in failed. Request a new link or try again.';\n button.disabled = false;\n }\n});\n</script></html>`;\n return new Response(html, {\n headers: {\n ...noStore,\n 'content-security-policy': `default-src 'none'; script-src 'nonce-${nonce}'; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`,\n 'content-type': 'text/html; charset=utf-8',\n 'referrer-policy': 'no-referrer',\n 'x-content-type-options': 'nosniff',\n },\n });\n }\n requireMutationGuard(request, config, true);\n queryParams(new URL(request.url), []);\n const body = await readJsonBody(request);\n if (typeof body !== 'object' || body === null || Array.isArray(body) || Object.keys(body).length !== 1) {\n throw badRequest('The link is not valid.');\n }\n const token: unknown = Reflect.get(body, 'token');\n if (typeof token !== 'string') throw badRequest('The link is not valid.');\n if (!LINK_TOKEN.test(token)) throw badRequest('The link is not valid.');\n const user = await consumeToken(env.AUTH_DB, await hashToken(token), Date.now());\n if (user === null) throw new ApiError(410, 'gone', 'That link has expired or was already used.');\n const session = await mintSession(config, user.id, config.operatorEmails.has(user.email), user.sessionVersion);\n return new Response(null, {\n headers: {\n ...noStore,\n 'set-cookie': sessionCookieValue(session.token, { maxAgeSeconds: session.maxAge, secure: secure(config) }),\n },\n status: 204,\n });\n}\n\n/** The issuer's half of a complete export: the account record only, never tokens or budget state. */\nasync function handleExport(request: Request, env: AuthWorkerEnv, config: AuthConfig): Promise<Response> {\n const { subject } = await requireSession(request, config, env);\n const row = await readAccount(env.AUTH_DB, subject);\n if (row === null) throw unauthenticated();\n return json(\n 200,\n { createdAt: row.created_at, email: row.email, id: row.id, lastSignInAt: row.last_sign_in_at },\n noStore,\n );\n}\n\n/** Re-serializes a failed catalog response into the public envelope; anything unrecognizable is 503. */\nasync function archiveFailure(response: Response): Promise<Response> {\n const text = await response.text().catch(() => '');\n let parsed: unknown = null;\n try {\n parsed = JSON.parse(text);\n } catch {\n parsed = null;\n }\n const envelope = archiveErrorResponseSchema.safeParse(parsed);\n if (!envelope.success || response.status < 400 || response.status > 599) throw unavailable();\n const { code, message, requestId } = envelope.data.error;\n const retryAfter = response.headers.get('retry-after');\n return json(\n response.status,\n { error: { code, message, requestId } },\n retryAfter !== null && /^\\d{1,6}$/.test(retryAfter) ? { ...noStore, 'retry-after': retryAfter } : noStore,\n );\n}\n\n/**\n * Full erasure: catalog session revocation and profile erasure first (through the AUTH_ARCHIVE service binding,\n * presenting the caller's own session), then the issuer's account row, and only then\n * the cookie is expired. Any failure keeps the browser session so the same request\n * can be retried; both halves are idempotent, so a retry after a partial success\n * re-runs the catalog no-op and finishes the issuer side. The account precondition\n * pins every attempt to the confirmed issuer subject, even without a publisher.\n */\nasync function handleErase(request: Request, env: AuthWorkerEnv, config: AuthConfig): Promise<Response> {\n const origin = requireMutationGuard(request, config);\n const { subject, token } = await requireSession(request, config, env);\n const account = request.headers.get(ACCOUNT_HEADER);\n if (account === null || !uuidSchema.safeParse(account).success) throw badRequest();\n if (account !== subject) {\n throw new ApiError(409, 'account-changed', 'The signed-in account changed since this request was prepared.');\n }\n const headers = new Headers({\n cookie: `${SESSION_COOKIE_NAME}=${token}`,\n origin,\n [REQUEST_MARKER_HEADER]: '1',\n });\n const publisher = request.headers.get(PUBLISHER_HEADER);\n if (publisher !== null) {\n if (!PUBLISHER_ID.test(publisher)) throw badRequest();\n headers.set(PUBLISHER_HEADER, publisher);\n }\n let archived: Response;\n try {\n archived = await serviceRequest(\n env.AUTH_ARCHIVE,\n new Request(`${config.publicOrigin}/api/v1/me/account`, { headers, method: 'DELETE', redirect: 'manual' }),\n async (response) => {\n if (response.status === 204) {\n await response.body?.cancel();\n return response;\n }\n return archiveFailure(response);\n },\n );\n } catch (error) {\n throw new AuthOperationError(503, 'catalog', { cause: error });\n }\n if (archived.status !== 204) return archived;\n await deleteAccount(env.AUTH_DB, subject);\n return new Response(null, {\n headers: { ...noStore, 'set-cookie': expiredSessionCookie(secure(config)) },\n status: 204,\n });\n}\n\nasync function handleSignOutAll(request: Request, env: AuthWorkerEnv, config: AuthConfig): Promise<Response> {\n requireMutationGuard(request, config);\n const { subject, sessionVersion } = await requireSession(request, config, env);\n const account = request.headers.get(ACCOUNT_HEADER);\n if (account === null || !uuidSchema.safeParse(account).success) throw badRequest();\n if (account !== subject)\n throw new ApiError(409, 'account-changed', 'The signed-in account changed since this request was prepared.');\n if ((await revokeSessions(env.AUTH_DB, subject, sessionVersion)) === null) throw unauthenticated();\n return json(200, { ok: true }, { ...noStore, 'set-cookie': expiredSessionCookie(secure(config)) });\n}\n\nasync function handleHealth(env: AuthWorkerEnv): Promise<Response> {\n let reason: 'configuration-unavailable' | 'database-unavailable' | 'schema-mismatch' | null = null;\n let dbSchemaVersion: number | null = null;\n try {\n await authConfig(env);\n } catch {\n reason = 'configuration-unavailable';\n }\n if (reason === null) {\n try {\n dbSchemaVersion = await authReadiness(env.AUTH_DB);\n if (dbSchemaVersion !== AUTH_SCHEMA_VERSION) reason = 'schema-mismatch';\n } catch {\n reason = 'database-unavailable';\n }\n }\n return json(\n reason === null ? 200 : 503,\n archiveAuthHealthSchema.parse({\n dbSchemaVersion,\n reason,\n schemaVersion: AUTH_SCHEMA_VERSION,\n status: reason === null ? 'ok' : 'degraded',\n }),\n noStore,\n );\n}\nasync function route(request: Request, env: AuthWorkerEnv): Promise<Response> {\n const method = request.method.toUpperCase();\n const routeId = matchRoute(request);\n if (routeId === undefined) throw new ApiError(404, 'not-found', 'No such route.');\n if (routeId === 'health' && method === 'GET') return handleHealth(env);\n const config = await authConfig(env);\n const cors = corsHeaders(request, config);\n if (method === 'OPTIONS') return preflight(request, config, ROUTE_METHODS[routeId]);\n if (!ROUTE_METHODS[routeId].includes(method)) {\n throw new ApiError(405, 'method-not-allowed', 'That method is not allowed here.');\n }\n let response: Response;\n switch (routeId) {\n case 'health':\n response = await handleHealth(env);\n break;\n case 'session':\n await requireSession(request, config, env);\n response = json(200, { ok: true }, noStore);\n break;\n case 'signOutAll':\n response = await handleSignOutAll(request, env, config);\n break;\n case 'jwks':\n response = json(200, { keys: config.jwks }, noStore);\n break;\n case 'signIn':\n response = await handleSignIn(request, env, config);\n break;\n case 'verify':\n response = await handleVerify(request, env, config);\n break;\n case 'account':\n response = method === 'GET' ? await handleExport(request, env, config) : await handleErase(request, env, config);\n break;\n }\n return withCors(response, cors);\n}\n\nfunction withCors(response: Response, cors: Record<string, string>): Response {\n if (Object.keys(cors).length === 0) return response;\n const next = new Response(response.body, response);\n for (const [key, value] of Object.entries(cors)) next.headers.set(key, value);\n return next;\n}\n\nconst diagnostic = (error: unknown): AuthDiagnostic =>\n error instanceof AuthOperationError ? error.authDiagnostic : { kind: 'internal' };\n\n/**\n * Builds the reference identity issuer. Route behavior is fixed; every deployment\n * difference is validated configuration — the app name, trusted origins, audience and\n * issuer claims, signing keys, operator roster, the catalog service binding, and\n * where links and redirects land.\n */\nexport function createAuthWorker<E extends AuthWorkerEnv>(): AuthWorkerHandler<E> {\n const tappers = new Set<(event: AuthEvent) => void>();\n const emit = (event: AuthEvent): void => {\n for (const handler of tappers) {\n try {\n handler(event);\n } catch {\n // Observers never change request or scheduled outcomes.\n }\n }\n };\n return {\n async fetch(request: Request, env: E): Promise<Response> {\n const requestId = crypto.randomUUID();\n const started = Date.now();\n let response: Response;\n let failure: unknown;\n try {\n response = await route(request, env);\n } catch (error) {\n failure = error;\n response = toErrorResponse(error, requestId);\n // Failures stay readable by allowed origins; config faults have no trusted origin set.\n const config = await authConfig(env).catch(() => null);\n if (config !== null) response = withCors(response, corsHeaders(request, config));\n }\n if (matchRoute(request) === 'verify') {\n response.headers.set('cache-control', 'no-store');\n response.headers.set('referrer-policy', 'no-referrer');\n response.headers.set('x-content-type-options', 'nosniff');\n if (!response.headers.has('content-security-policy')) {\n response.headers.set(\n 'content-security-policy',\n \"default-src 'none'; base-uri 'none'; frame-ancestors 'none'\",\n );\n }\n }\n if (tappers.size > 0) {\n const routeId = matchRoute(request);\n const code =\n response.status < 400\n ? 'ok'\n : routeId === 'health'\n ? 'unavailable'\n : failure instanceof ApiError\n ? failure.code\n : 'internal';\n // Account erasure may forward a catalog error response rather than throw.\n const forwardedCode =\n failure === undefined && response.status >= 400\n ? archiveErrorResponseSchema.safeParse(\n await response\n .clone()\n .json()\n .catch(() => null),\n )\n : null;\n const health =\n routeId === 'health' && response.status === 503\n ? archiveAuthHealthSchema.safeParse(\n await response\n .clone()\n .json()\n .catch(() => null),\n )\n : null;\n emit({\n code: forwardedCode?.success ? forwardedCode.data.error.code : code,\n ms: Math.max(0, Date.now() - started),\n requestId,\n route: routeId === undefined ? 'unmatched' : ROUTE_LABELS[routeId],\n status: response.status,\n type: 'request',\n ...(response.status >= 500\n ? {\n diagnostic: health?.success\n ? {\n kind:\n health.data.reason === 'configuration-unavailable'\n ? 'configuration'\n : health.data.reason === 'schema-mismatch'\n ? 'schema'\n : 'database',\n }\n : failure === undefined\n ? { kind: 'catalog' as const }\n : diagnostic(failure),\n }\n : {}),\n });\n }\n return response;\n },\n\n async scheduled(_controller: unknown, env: E): Promise<void> {\n try {\n await authConfig(env);\n const removed = await sweep(env.AUTH_DB, Date.now());\n if (tappers.size > 0) emit({ removed, status: 'ok', type: 'scheduled' });\n } catch (error) {\n if (tappers.size > 0) emit({ diagnostic: diagnostic(error), status: 'failed', type: 'scheduled' });\n throw error;\n }\n },\n tap(handler, options) {\n if (options?.signal?.aborted) return () => undefined;\n const observer = (event: AuthEvent): void => handler(event);\n const unsubscribe = (): void => {\n tappers.delete(observer);\n options?.signal?.removeEventListener('abort', unsubscribe);\n };\n tappers.add(observer);\n options?.signal?.addEventListener('abort', unsubscribe, { once: true });\n return unsubscribe;\n },\n };\n}\n"],"mappings":"0MAuFA,IAAM,EAAS,CACb,QAAS,6BACT,OAAQ,4BACR,KAAM,gCACN,QAAS,6BACT,OAAQ,6BACR,WAAY,kCACZ,OAAQ,2BACV,EAEM,EAAgE,CACpE,QAAS,CAAC,MAAO,QAAQ,EACzB,OAAQ,CAAC,KAAK,EACd,KAAM,CAAC,KAAK,EACZ,QAAS,CAAC,KAAK,EACf,OAAQ,CAAC,MA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AAQ,EAAS,OACjB,KAAM,UACN,GAAI,EAAS,QAAU,IACnB,CACE,WAAY,GAAQ,QAChB,CACE,KACE,EAAO,KAAK,SAAW,4BACnB,gBACA,EAAO,KAAK,SAAW,kBACrB,SACA,UACV,EACA,IAAY,IAAA,GACV,CAAE,KAAM,SAAmB,EAC3B,WAAW,CAAO,CAC1B,EACA,CAAC,CACP,CAAC,CACH,CACA,OAAO,CACT,EAEA,MAAM,UAAU,EAAsB,EAAuB,CAC3D,GAAI,CACF,MAAM,EAAA,WAAW,CAAG,EACpB,IAAM,EAAU,MAAM,EAAA,MAAM,EAAI,QAAS,KAAK,IAAI,CAAC,EAC/C,EAAQ,KAAO,GAAG,KAAK,CAAE,UAAS,OAAQ,KAAM,KAAM,WAAY,CAAC,CACzE,OAAS,EAAO,CAEd,MADI,EAAQ,KAAO,GAAG,KAAK,CAAE,WAAY,WAAW,CAAK,EAAG,OAAQ,SAAU,KAAM,WAAY,CAAC,EAC3F,CACR,CACF,EACA,IAAI,EAAS,EAAS,CACpB,GAAI,GAAS,QAAQ,QAAS,UAAa,IAAA,GAC3C,IAAM,SAAY,GAA2B,EAAQ,CAAK,EACpD,gBAA0B,CAC9B,EAAQ,OAAO,QAAQ,EACvB,GAAS,QAAQ,oBAAoB,QAAS,WAAW,CAC3D,EAGA,OAFA,EAAQ,IAAI,QAAQ,EACpB,GAAS,QAAQ,iBAAiB,QAAS,YAAa,CAAE,KAAM,EAAK,CAAC,EAC/D,WACT,CACF,CACF"}
1
+ {"version":3,"file":"worker.cjs","names":[],"sources":["../../src/auth/worker.ts"],"sourcesContent":["import { errors, jwtVerify, SignJWT } from 'jose';\nimport { sha256Hex } from '../_crypto';\nimport {\n ACCOUNT_HEADER,\n ARCHIVE_OPERATOR_ROLE,\n type ArchiveErrorCode,\n AUTH_SCHEMA_VERSION,\n archiveAuthHealthSchema,\n archiveErrorResponseSchema,\n isWellFormedText,\n OPERATOR_SESSION_MAX_AGE_SECONDS,\n PUBLISHER_HEADER,\n REQUEST_MARKER_HEADER,\n SESSION_COOKIE_NAME,\n SESSION_MAX_AGE_SECONDS,\n sessionCookieValue,\n uuidSchema,\n} from '../contract';\nimport { serviceRequest } from '../worker/_service';\nimport {\n ApiError,\n badRequest,\n expiredSessionCookie,\n forbidden,\n json,\n noStore,\n queryParams,\n readJsonBody,\n sessionToken,\n toErrorResponse,\n unauthenticated,\n} from '../worker/http';\nimport type { ArchiveExecutionContext } from '../worker/worker';\nimport { type AuthConfig, type AuthWorkerEnv, authConfig, isWellFormedEmail } from './config';\nimport { type AuthDiagnostic, AuthOperationError } from './errors';\nimport {\n authReadiness,\n consumeToken,\n deleteAccount,\n deleteToken,\n ensureUser,\n insertToken,\n LINK_TTL_MS,\n readAccount,\n revokeSessions,\n spendLinkBudget,\n spendSignInBudget,\n sweep,\n} from './store';\n\n/**\n * The reference identity issuer: passwordless email accounts. A POST with an email\n * address ensures the account row and sends a single-use magic link; consuming it\n * signs the browser in by setting the `archive_session` cookie a catalog Worker\n * verifies — an RS256 JWT minted by the active private key, verifiable through\n * `/jwks.json` alongside any configured retired public keys. `OPERATOR_EMAILS` is\n * the one operator-membership truth; operator sessions are short-lived so a revoked\n * operator loses authority within minutes. The account routes export the issuer's\n * own record and erase it together with the catalog profile.\n */\nexport interface AuthWorkerHandler<E extends AuthWorkerEnv = AuthWorkerEnv> {\n fetch(request: Request, env: E, ctx?: ArchiveExecutionContext): Promise<Response>;\n /** The cron sweep: expired links, closed send windows and never-verified accounts. */\n scheduled(controller: unknown, env: E, ctx?: ArchiveExecutionContext): Promise<void>;\n tap(handler: (event: AuthEvent) => void, options?: { readonly signal?: AbortSignal }): () => void;\n}\n\nexport type AuthEvent =\n | {\n readonly type: 'request';\n readonly requestId: string;\n readonly route:\n | '/auth/account'\n | '/auth/jwks.json'\n | '/auth/sign-in'\n | '/auth/verify'\n | '/auth/session'\n | '/auth/sign-out-all'\n | '/auth/health'\n | 'unmatched';\n readonly status: number;\n readonly code: ArchiveErrorCode | 'ok';\n readonly ms: number;\n readonly diagnostic?: AuthDiagnostic;\n }\n | { readonly type: 'scheduled'; readonly status: 'ok'; readonly removed: number }\n | { readonly type: 'scheduled'; readonly status: 'failed'; readonly diagnostic: AuthDiagnostic };\n\nconst ROUTES = {\n account: /^\\/api\\/v1\\/auth\\/account$/,\n health: /^\\/api\\/v1\\/auth\\/health$/,\n jwks: /^\\/api\\/v1\\/auth\\/jwks\\.json$/,\n session: /^\\/api\\/v1\\/auth\\/session$/,\n signIn: /^\\/api\\/v1\\/auth\\/sign-in$/,\n signOutAll: /^\\/api\\/v1\\/auth\\/sign-out-all$/,\n verify: /^\\/api\\/v1\\/auth\\/verify$/,\n} as const;\n\nconst ROUTE_METHODS: Record<keyof typeof ROUTES, readonly string[]> = {\n account: ['GET', 'DELETE'],\n health: ['GET'],\n jwks: ['GET'],\n session: ['GET'],\n signIn: ['POST'],\n signOutAll: ['POST'],\n verify: ['GET', 'POST'],\n};\n\nconst ROUTE_LABELS = {\n account: '/auth/account',\n health: '/auth/health',\n jwks: '/auth/jwks.json',\n session: '/auth/session',\n signIn: '/auth/sign-in',\n signOutAll: '/auth/sign-out-all',\n verify: '/auth/verify',\n} as const;\n\nconst matchRoute = (request: Request): keyof typeof ROUTES | undefined =>\n (Object.keys(ROUTES) as (keyof typeof ROUTES)[]).find((id) => ROUTES[id].test(new URL(request.url).pathname));\n\nconst TOKEN_BYTES = 32;\n// Base64url of TOKEN_BYTES random bytes, unpadded.\nconst LINK_TOKEN = /^[A-Za-z0-9_-]{43}$/;\nconst PUBLISHER_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;\nconst SUBJECT_MAX = 256;\nconst CLOCK_TOLERANCE_SECONDS = 5;\n\nconst randomToken = (): string =>\n btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(TOKEN_BYTES))))\n .replaceAll('+', '-')\n .replaceAll('/', '_')\n .replace(/=+$/, '');\n\nconst escapeHtml = (value: string): string => value.replace(/[&<>\"']/g, (char) => `&#${char.charCodeAt(0)};`);\n\nconst unavailable = (): ApiError => new AuthOperationError(503, 'catalog');\n\n/** Exact allowed Origin plus the request marker, like the catalog's mutation guard. */\nfunction requireMutationGuard(request: Request, config: AuthConfig, allowPublicOrigin = false): string {\n const origin = request.headers.get('origin');\n if (origin === null || (!config.allowedOrigins.has(origin) && !(allowPublicOrigin && origin === config.publicOrigin)))\n throw forbidden();\n if (request.headers.get(REQUEST_MARKER_HEADER) !== '1') throw forbidden();\n return origin;\n}\n\nfunction corsHeaders(request: Request, config: AuthConfig): Record<string, string> {\n const origin = request.headers.get('origin');\n if (\n origin === null ||\n (!config.allowedOrigins.has(origin) && !(matchRoute(request) === 'verify' && origin === config.publicOrigin))\n )\n return {};\n return { 'access-control-allow-credentials': 'true', 'access-control-allow-origin': origin, vary: 'Origin' };\n}\n\nfunction preflight(request: Request, config: AuthConfig, methods: readonly string[]): Response {\n const cors = corsHeaders(request, config);\n if (Object.keys(cors).length === 0) throw forbidden();\n return new Response(null, {\n headers: {\n ...cors,\n 'access-control-allow-headers': `Content-Type, ${ACCOUNT_HEADER}, ${PUBLISHER_HEADER}, ${REQUEST_MARKER_HEADER}`,\n 'access-control-allow-methods': [...methods, 'OPTIONS'].join(', '),\n 'access-control-max-age': '600',\n },\n status: 204,\n });\n}\n\nconst secure = (config: AuthConfig): boolean => config.appEnv === 'production';\n\nasync function mintSession(\n config: AuthConfig,\n subject: string,\n operator: boolean,\n sessionVersion: number,\n): Promise<{ maxAge: number; token: string }> {\n const maxAge = operator ? OPERATOR_SESSION_MAX_AGE_SECONDS : SESSION_MAX_AGE_SECONDS;\n const token = await new SignJWT({ sessionVersion, ...(operator ? { roles: [ARCHIVE_OPERATOR_ROLE] } : {}) })\n .setProtectedHeader({ alg: 'RS256', kid: config.signing.kid, typ: 'JWT' })\n .setIssuedAt()\n .setJti(crypto.randomUUID())\n .setIssuer(config.issuer)\n .setAudience(config.audience)\n .setSubject(subject)\n .setExpirationTime(`${maxAge}s`)\n .sign(config.signing.key);\n return { maxAge, token };\n}\n\n/** Verifies the request's own session cookie against every published key; returns the token and subject. */\nasync function requireSession(\n request: Request,\n config: AuthConfig,\n env: AuthWorkerEnv,\n): Promise<{ subject: string; token: string; sessionVersion: number }> {\n const token = sessionToken(request);\n if (token === null) throw unauthenticated();\n try {\n const { payload } = await jwtVerify(token, config.verifier, {\n algorithms: ['RS256'],\n audience: config.audience,\n clockTolerance: CLOCK_TOLERANCE_SECONDS,\n issuer: config.issuer,\n maxTokenAge: SESSION_MAX_AGE_SECONDS,\n requiredClaims: ['sub', 'iss', 'aud', 'iat', 'exp', 'sessionVersion'],\n });\n const subject = payload.sub ?? '';\n if (subject.length === 0 || subject.length > SUBJECT_MAX || !isWellFormedText(subject)) throw unauthenticated();\n const version = payload.sessionVersion;\n if (typeof version !== 'number' || !Number.isSafeInteger(version) || version < 0) throw unauthenticated();\n if (typeof payload.iat !== 'number' || payload.iat > Date.now() / 1000 + CLOCK_TOLERANCE_SECONDS)\n throw unauthenticated();\n if (\n Array.isArray(payload.roles) &&\n payload.roles.includes(ARCHIVE_OPERATOR_ROLE) &&\n (typeof payload.exp !== 'number' ||\n payload.exp - payload.iat > OPERATOR_SESSION_MAX_AGE_SECONDS ||\n Date.now() / 1000 - payload.iat > OPERATOR_SESSION_MAX_AGE_SECONDS + CLOCK_TOLERANCE_SECONDS)\n )\n throw unauthenticated();\n const account = await readAccount(env.AUTH_DB, subject);\n if (account === null || account.session_version !== version) throw unauthenticated();\n return { sessionVersion: version, subject, token };\n } catch (error) {\n if (error instanceof errors.JOSEError) throw unauthenticated();\n throw error;\n }\n}\n\nasync function sendLink(env: AuthWorkerEnv, config: AuthConfig, to: string, link: string): Promise<void> {\n const name = config.appName;\n const minutes = LINK_TTL_MS / 60_000;\n const notice = `The link works once and expires in ${minutes} minutes. If you did not request it, ignore this email.`;\n await env.AUTH_EMAIL.send({\n from: config.senderAddress,\n html: `<p>Open this link to sign in to ${escapeHtml(name)}:</p><p><a href=\"${escapeHtml(link)}\">${escapeHtml(link)}</a></p><p>${notice}</p>`,\n subject: `Your ${name} sign-in link`,\n text: `Open this link to sign in to ${name}:\\n\\n${link}\\n\\n${notice}`,\n to,\n });\n}\n\nasync function handleSignIn(request: Request, env: AuthWorkerEnv, config: AuthConfig): Promise<Response> {\n requireMutationGuard(request, config);\n const body = await readJsonBody(request);\n if (typeof body !== 'object' || body === null || Array.isArray(body)) throw badRequest();\n const keys = Object.keys(body);\n const requestedEmail: unknown = Reflect.get(body, 'email');\n if (keys.length !== 1 || keys[0] !== 'email' || typeof requestedEmail !== 'string') {\n throw badRequest();\n }\n const email = requestedEmail.trim().toLowerCase();\n if (!isWellFormedEmail(email)) {\n throw badRequest();\n }\n const nowMs = Date.now();\n const admissionRetry = await spendSignInBudget(env.AUTH_DB, nowMs);\n if (admissionRetry !== null) {\n throw new ApiError(429, 'rate-limited', 'Too many sign-in requests. Try again later.', {\n retryAfterSeconds: admissionRetry,\n });\n }\n const user = await ensureUser(env.AUTH_DB, email);\n const retryAfterSeconds = await spendLinkBudget(env.AUTH_DB, user.id, nowMs);\n if (retryAfterSeconds !== null) {\n throw new ApiError(429, 'rate-limited', 'Too many sign-in emails. Try again later.', { retryAfterSeconds });\n }\n const token = randomToken();\n const tokenHash = await sha256Hex(token);\n await insertToken(env.AUTH_DB, tokenHash, user.id, nowMs);\n try {\n await sendLink(env, config, user.email, `${config.publicOrigin}/api/v1/auth/verify?token=${token}`);\n } catch (error) {\n // An unsent link is useless; the spent allowance is deliberately not refunded.\n await deleteToken(env.AUTH_DB, tokenHash).catch(() => undefined);\n throw new AuthOperationError(503, 'email', { cause: error });\n }\n return json(202, { ok: true }, noStore);\n}\n\nasync function handleVerify(request: Request, env: AuthWorkerEnv, config: AuthConfig): Promise<Response> {\n if (request.method === 'GET') {\n const token = queryParams(new URL(request.url), ['token']).get('token') ?? '';\n if (!LINK_TOKEN.test(token)) throw badRequest('The link is not valid.');\n const nonce = randomToken();\n // No automatic redemption, external assets or referrers. Only a deliberate\n // button click makes the same-origin marked POST; scanners can safely GET.\n const html = `<!doctype html><html lang=\"en\"><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width\"><title>Confirm sign-in</title><h1>Sign in to ${escapeHtml(config.appName)}</h1><p>Continue only if you requested this sign-in link.</p><button type=\"button\" id=\"confirm\">Confirm sign-in</button><p role=\"status\" id=\"status\"></p><script nonce=\"${nonce}\">\nhistory.replaceState(null, '', location.pathname);\ndocument.getElementById('confirm').addEventListener('click', async () => {\n const button = document.getElementById('confirm');\n button.disabled = true;\n try {\n const response = await fetch(location.pathname, { method: 'POST', credentials: 'same-origin', headers: { 'content-type': 'application/json', '${REQUEST_MARKER_HEADER}': '1' }, body: JSON.stringify({ token: '${token}' }) });\n if (!response.ok) throw new Error();\n location.replace(${JSON.stringify(`${config.publicOrigin}/signed-in`)});\n } catch {\n document.getElementById('status').textContent = 'Sign-in failed. Request a new link or try again.';\n button.disabled = false;\n }\n});\n</script></html>`;\n return new Response(html, {\n headers: {\n ...noStore,\n 'content-security-policy': `default-src 'none'; script-src 'nonce-${nonce}'; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`,\n 'content-type': 'text/html; charset=utf-8',\n 'referrer-policy': 'no-referrer',\n 'x-content-type-options': 'nosniff',\n },\n });\n }\n requireMutationGuard(request, config, true);\n queryParams(new URL(request.url), []);\n const body = await readJsonBody(request);\n if (typeof body !== 'object' || body === null || Array.isArray(body) || Object.keys(body).length !== 1) {\n throw badRequest('The link is not valid.');\n }\n const token: unknown = Reflect.get(body, 'token');\n if (typeof token !== 'string') throw badRequest('The link is not valid.');\n if (!LINK_TOKEN.test(token)) throw badRequest('The link is not valid.');\n const user = await consumeToken(env.AUTH_DB, await sha256Hex(token), Date.now());\n if (user === null) throw new ApiError(410, 'gone', 'That link has expired or was already used.');\n const session = await mintSession(config, user.id, config.operatorEmails.has(user.email), user.sessionVersion);\n return new Response(null, {\n headers: {\n ...noStore,\n 'set-cookie': sessionCookieValue(session.token, { maxAgeSeconds: session.maxAge, secure: secure(config) }),\n },\n status: 204,\n });\n}\n\n/** The issuer's half of a complete export: the account record only, never tokens or budget state. */\nasync function handleExport(request: Request, env: AuthWorkerEnv, config: AuthConfig): Promise<Response> {\n const { subject } = await requireSession(request, config, env);\n const row = await readAccount(env.AUTH_DB, subject);\n if (row === null) throw unauthenticated();\n return json(\n 200,\n { createdAt: row.created_at, email: row.email, id: row.id, lastSignInAt: row.last_sign_in_at },\n noStore,\n );\n}\n\n/** Re-serializes a failed catalog response into the public envelope; anything unrecognizable is 503. */\nasync function archiveFailure(response: Response): Promise<Response> {\n const text = await response.text().catch(() => '');\n let parsed: unknown = null;\n try {\n parsed = JSON.parse(text);\n } catch {\n parsed = null;\n }\n const envelope = archiveErrorResponseSchema.safeParse(parsed);\n if (!envelope.success || response.status < 400 || response.status > 599) throw unavailable();\n const { code, message, requestId } = envelope.data.error;\n const retryAfter = response.headers.get('retry-after');\n return json(\n response.status,\n { error: { code, message, requestId } },\n retryAfter !== null && /^\\d{1,6}$/.test(retryAfter) ? { ...noStore, 'retry-after': retryAfter } : noStore,\n );\n}\n\n/**\n * Full erasure: catalog session revocation and profile erasure first (through the AUTH_ARCHIVE service binding,\n * presenting the caller's own session), then the issuer's account row, and only then\n * the cookie is expired. Any failure keeps the browser session so the same request\n * can be retried; both halves are idempotent, so a retry after a partial success\n * re-runs the catalog no-op and finishes the issuer side. The account precondition\n * pins every attempt to the confirmed issuer subject, even without a publisher.\n */\nasync function handleErase(request: Request, env: AuthWorkerEnv, config: AuthConfig): Promise<Response> {\n const origin = requireMutationGuard(request, config);\n const { subject, token } = await requireSession(request, config, env);\n const account = request.headers.get(ACCOUNT_HEADER);\n if (account === null || !uuidSchema.safeParse(account).success) throw badRequest();\n if (account !== subject) {\n throw new ApiError(409, 'account-changed', 'The signed-in account changed since this request was prepared.');\n }\n const headers = new Headers({\n cookie: `${SESSION_COOKIE_NAME}=${token}`,\n origin,\n [REQUEST_MARKER_HEADER]: '1',\n });\n const publisher = request.headers.get(PUBLISHER_HEADER);\n if (publisher !== null) {\n if (!PUBLISHER_ID.test(publisher)) throw badRequest();\n headers.set(PUBLISHER_HEADER, publisher);\n }\n let archived: Response;\n try {\n archived = await serviceRequest(\n env.AUTH_ARCHIVE,\n new Request(`${config.publicOrigin}/api/v1/me/account`, { headers, method: 'DELETE', redirect: 'manual' }),\n async (response) => {\n if (response.status === 204) {\n await response.body?.cancel();\n return response;\n }\n return archiveFailure(response);\n },\n );\n } catch (error) {\n throw new AuthOperationError(503, 'catalog', { cause: error });\n }\n if (archived.status !== 204) return archived;\n await deleteAccount(env.AUTH_DB, subject);\n return new Response(null, {\n headers: { ...noStore, 'set-cookie': expiredSessionCookie(secure(config)) },\n status: 204,\n });\n}\n\nasync function handleSignOutAll(request: Request, env: AuthWorkerEnv, config: AuthConfig): Promise<Response> {\n requireMutationGuard(request, config);\n const { subject, sessionVersion } = await requireSession(request, config, env);\n const account = request.headers.get(ACCOUNT_HEADER);\n if (account === null || !uuidSchema.safeParse(account).success) throw badRequest();\n if (account !== subject)\n throw new ApiError(409, 'account-changed', 'The signed-in account changed since this request was prepared.');\n if ((await revokeSessions(env.AUTH_DB, subject, sessionVersion)) === null) throw unauthenticated();\n return json(200, { ok: true }, { ...noStore, 'set-cookie': expiredSessionCookie(secure(config)) });\n}\n\nasync function handleHealth(env: AuthWorkerEnv): Promise<Response> {\n let reason: 'configuration-unavailable' | 'database-unavailable' | 'schema-mismatch' | null = null;\n let dbSchemaVersion: number | null = null;\n try {\n await authConfig(env);\n } catch {\n reason = 'configuration-unavailable';\n }\n if (reason === null) {\n try {\n dbSchemaVersion = await authReadiness(env.AUTH_DB);\n if (dbSchemaVersion !== AUTH_SCHEMA_VERSION) reason = 'schema-mismatch';\n } catch {\n reason = 'database-unavailable';\n }\n }\n return json(\n reason === null ? 200 : 503,\n archiveAuthHealthSchema.parse({\n dbSchemaVersion,\n reason,\n schemaVersion: AUTH_SCHEMA_VERSION,\n status: reason === null ? 'ok' : 'degraded',\n }),\n noStore,\n );\n}\nasync function route(request: Request, env: AuthWorkerEnv): Promise<Response> {\n const method = request.method.toUpperCase();\n const routeId = matchRoute(request);\n if (routeId === undefined) throw new ApiError(404, 'not-found', 'No such route.');\n if (routeId === 'health' && method === 'GET') return handleHealth(env);\n const config = await authConfig(env);\n const cors = corsHeaders(request, config);\n if (method === 'OPTIONS') return preflight(request, config, ROUTE_METHODS[routeId]);\n if (!ROUTE_METHODS[routeId].includes(method)) {\n throw new ApiError(405, 'method-not-allowed', 'That method is not allowed here.');\n }\n let response: Response;\n switch (routeId) {\n case 'health':\n response = await handleHealth(env);\n break;\n case 'session':\n await requireSession(request, config, env);\n response = json(200, { ok: true }, noStore);\n break;\n case 'signOutAll':\n response = await handleSignOutAll(request, env, config);\n break;\n case 'jwks':\n response = json(200, { keys: config.jwks }, noStore);\n break;\n case 'signIn':\n response = await handleSignIn(request, env, config);\n break;\n case 'verify':\n response = await handleVerify(request, env, config);\n break;\n case 'account':\n response = method === 'GET' ? await handleExport(request, env, config) : await handleErase(request, env, config);\n break;\n }\n return withCors(response, cors);\n}\n\nfunction withCors(response: Response, cors: Record<string, string>): Response {\n if (Object.keys(cors).length === 0) return response;\n const next = new Response(response.body, response);\n for (const [key, value] of Object.entries(cors)) next.headers.set(key, value);\n return next;\n}\n\nconst diagnostic = (error: unknown): AuthDiagnostic =>\n error instanceof AuthOperationError ? error.authDiagnostic : { kind: 'internal' };\n\n/**\n * Builds the reference identity issuer. Route behavior is fixed; every deployment\n * difference is validated configuration — the app name, trusted origins, audience and\n * issuer claims, signing keys, operator roster, the catalog service binding, and\n * where links and redirects land.\n */\nexport function createAuthWorker<E extends AuthWorkerEnv>(): AuthWorkerHandler<E> {\n const tappers = new Set<(event: AuthEvent) => void>();\n const emit = (event: AuthEvent): void => {\n for (const handler of tappers) {\n try {\n handler(event);\n } catch {\n // Observers never change request or scheduled outcomes.\n }\n }\n };\n return {\n async fetch(request: Request, env: E): Promise<Response> {\n const requestId = crypto.randomUUID();\n const started = Date.now();\n let response: Response;\n let failure: unknown;\n try {\n response = await route(request, env);\n } catch (error) {\n failure = error;\n response = toErrorResponse(error, requestId);\n // Failures stay readable by allowed origins; config faults have no trusted origin set.\n const config = await authConfig(env).catch(() => null);\n if (config !== null) response = withCors(response, corsHeaders(request, config));\n }\n if (matchRoute(request) === 'verify') {\n response.headers.set('cache-control', 'no-store');\n response.headers.set('referrer-policy', 'no-referrer');\n response.headers.set('x-content-type-options', 'nosniff');\n if (!response.headers.has('content-security-policy')) {\n response.headers.set(\n 'content-security-policy',\n \"default-src 'none'; base-uri 'none'; frame-ancestors 'none'\",\n );\n }\n }\n if (tappers.size > 0) {\n const routeId = matchRoute(request);\n const code =\n response.status < 400\n ? 'ok'\n : routeId === 'health'\n ? 'unavailable'\n : failure instanceof ApiError\n ? failure.code\n : 'internal';\n // Account erasure may forward a catalog error response rather than throw.\n const forwardedCode =\n failure === undefined && response.status >= 400\n ? archiveErrorResponseSchema.safeParse(\n await response\n .clone()\n .json()\n .catch(() => null),\n )\n : null;\n const health =\n routeId === 'health' && response.status === 503\n ? archiveAuthHealthSchema.safeParse(\n await response\n .clone()\n .json()\n .catch(() => null),\n )\n : null;\n emit({\n code: forwardedCode?.success ? forwardedCode.data.error.code : code,\n ms: Math.max(0, Date.now() - started),\n requestId,\n route: routeId === undefined ? 'unmatched' : ROUTE_LABELS[routeId],\n status: response.status,\n type: 'request',\n ...(response.status >= 500\n ? {\n diagnostic: health?.success\n ? {\n kind:\n health.data.reason === 'configuration-unavailable'\n ? 'configuration'\n : health.data.reason === 'schema-mismatch'\n ? 'schema'\n : 'database',\n }\n : failure === undefined\n ? { kind: 'catalog' as const }\n : diagnostic(failure),\n }\n : {}),\n });\n }\n return response;\n },\n\n async scheduled(_controller: unknown, env: E): Promise<void> {\n try {\n await authConfig(env);\n const removed = await sweep(env.AUTH_DB, Date.now());\n if (tappers.size > 0) emit({ removed, status: 'ok', type: 'scheduled' });\n } catch (error) {\n if (tappers.size > 0) emit({ diagnostic: diagnostic(error), status: 'failed', type: 'scheduled' });\n throw error;\n }\n },\n tap(handler, options) {\n if (options?.signal?.aborted) return () => undefined;\n const observer = (event: AuthEvent): void => handler(event);\n const unsubscribe = (): void => {\n tappers.delete(observer);\n options?.signal?.removeEventListener('abort', unsubscribe);\n };\n tappers.add(observer);\n options?.signal?.addEventListener('abort', unsubscribe, { once: true });\n return unsubscribe;\n },\n };\n}\n"],"mappings":"sOAwFA,IAAM,EAAS,CACb,QAAS,6BACT,OAAQ,4BACR,KAAM,gCACN,QAAS,6BACT,OAAQ,6BACR,WAAY,kCACZ,OAAQ,2BACV,EAEM,EAAgE,CACpE,QAAS,CAAC,MAAO,QAAQ,EACzB,OAAQ,CAAC,KAAK,EACd,KAAM,CAAC,KAAK,EACZ,QAAS,CAAC,KAAK,EACf,OAAQ,CAAC,MAAM,EACf,WAAY,CAAC,MAAM,EACnB,OAAQ,CAAC,MAAO,MAAM,CACxB,EAEM,EAAe,CACnB,QAAS,gBACT,OAAQ,eACR,KAAM,kBACN,QAAS,gBACT,OAAQ,gBACR,WAAY,qBACZ,OAAQ,cACV,EAEM,WAAc,GACjB,OAAO,KAAK,CAAM,CAAC,CAA6B,KAAM,GAAO,EAAO,EAAG,CAAC,KAAK,IAAI,IAAI,EAAQ,GAAG,CAAC,CAAC,QAAQ,CAAC,EAExG,EAAc,GAEd,EAAa,sBACb,EAAe,iEACf,EAAc,IACd,EAA0B,EAE1B,gBACJ,KAAK,OAAO,aAAa,GAAG,OAAO,gBAAgB,IAAI,WAAW,CAAW,CAAC,CAAC,CAAC,CAAC,CAC9E,WAAW,IAAK,GAAG,CAAC,CACpB,WAAW,IAAK,GAAG,CAAC,CACpB,QAAQ,MAAO,EAAE,EAEhB,WAAc,GAA0B,EAAM,QAAQ,WAAa,GAAS,KAAK,EAAK,WAAW,CAAC,EAAE,EAAE,EAEtG,gBAA8B,IA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AE,QAAQ,CAAC,MAAM,CAAC,EAAE,WAAW,CAAA;KAAE,GAAG,MAAM,IAAI,CAAC;CACnG;AAED,MAAM,MAAM,SAAS,GACjB;IACE,QAAQ,CAAC,IAAI,EAAE,SAAS,CAAC;IACzB,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,KAAK,EACV,eAAe,GACf,iBAAiB,GACjB,eAAe,GACf,cAAc,GACd,eAAe,GACf,oBAAoB,GACpB,cAAc,GACd,WAAW,CAAC;IAChB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,IAAI,EAAE,gBAAgB,GAAG,IAAI,CAAC;IACvC,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,UAAU,CAAC,EAAE,cAAc,CAAC;CACtC,GACD;IAAE,QAAQ,CAAC,IAAI,EAAE,WAAW,CAAC;IAAC,QAAQ,CAAC,MAAM,EAAE,IAAI,CAAC;IAAC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAA;CAAE,GAC/E;IAAE,QAAQ,CAAC,IAAI,EAAE,WAAW,CAAC;IAAC,QAAQ,CAAC,MAAM,EAAE,QAAQ,CAAC;IAAC,QAAQ,CAAC,UAAU,EAAE,cAAc,CAAA;CAAE,CAAC;AAmanG;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,CAAC,SAAS,aAAa,KAAK,iBAAiB,CAAC,CAAC,CAAC,CAoHhF"}
@@ -1,16 +1,16 @@
1
- import{ACCOUNT_HEADER as e,ARCHIVE_OPERATOR_ROLE as t,PUBLISHER_HEADER as n,REQUEST_MARKER_HEADER as r,SESSION_COOKIE_NAME as i,SESSION_MAX_AGE_SECONDS as a,archiveAuthHealthSchema as o,archiveErrorResponseSchema as s,isWellFormedText as c,sessionCookieValue as l,uuidSchema as u}from"../contract.js";import{serviceRequest as d}from"../worker/_service.js";import{ApiError as f,badRequest as p,expiredSessionCookie as m,forbidden as h,json as g,noStore as _,queryParams as v,readJsonBody as y,sessionToken as b,toErrorResponse as x,unauthenticated as S}from"../worker/http.js";import{AuthOperationError as C}from"./errors.js";import{authConfig as w,isWellFormedEmail as T}from"./config.js";import{LINK_TTL_MS as E,authReadiness as D,consumeToken as O,deleteAccount as k,deleteToken as A,ensureUser as j,insertToken as M,readAccount as N,revokeSessions as P,spendLinkBudget as F,spendSignInBudget as I,sweep as L}from"./store.js";import{SignJWT as R,errors as z,jwtVerify as B}from"jose";var V={account:/^\/api\/v1\/auth\/account$/,health:/^\/api\/v1\/auth\/health$/,jwks:/^\/api\/v1\/auth\/jwks\.json$/,session:/^\/api\/v1\/auth\/session$/,signIn:/^\/api\/v1\/auth\/sign-in$/,signOutAll:/^\/api\/v1\/auth\/sign-out-all$/,verify:/^\/api\/v1\/auth\/verify$/},H={account:[`GET`,`DELETE`],health:[`GET`],jwks:[`GET`],session:[`GET`],signIn:[`POST`],signOutAll:[`POST`],verify:[`GET`,`POST`]},U={account:`/auth/account`,health:`/auth/health`,jwks:`/auth/jwks.json`,session:`/auth/session`,signIn:`/auth/sign-in`,signOutAll:`/auth/sign-out-all`,verify:`/auth/verify`},matchRoute=e=>Object.keys(V).find(t=>V[t].test(new URL(e.url).pathname)),W=32,G=/^[A-Za-z0-9_-]{43}$/,K=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,q=256,J=5,hex=e=>[...new Uint8Array(e)].map(e=>e.toString(16).padStart(2,`0`)).join(``),hashToken=async e=>hex(await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e))),randomToken=()=>btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(W)))).replaceAll(`+`,`-`).replaceAll(`/`,`_`).replace(/=+$/,``),escapeHtml=e=>e.replace(/[&<>"']/g,e=>`&#${e.charCodeAt(0)};`),unavailable=()=>new C(503,`catalog`);function requireMutationGuard(e,t,n=!1){let r=e.headers.get(`origin`);if(r===null||!t.allowedOrigins.has(r)&&!(n&&r===t.publicOrigin)||e.headers.get(`x-archive-request`)!==`1`)throw h();return r}function corsHeaders(e,t){let n=e.headers.get(`origin`);return n===null||!t.allowedOrigins.has(n)&&(matchRoute(e)!==`verify`||n!==t.publicOrigin)?{}:{"access-control-allow-credentials":`true`,"access-control-allow-origin":n,vary:`Origin`}}function preflight(t,i,a){let o=corsHeaders(t,i);if(Object.keys(o).length===0)throw h();return new Response(null,{headers:{...o,"access-control-allow-headers":`Content-Type, ${e}, ${n}, ${r}`,"access-control-allow-methods":[...a,`OPTIONS`].join(`, `),"access-control-max-age":`600`},status:204})}var secure=e=>e.appEnv===`production`;async function mintSession(e,n,r,i){let o=r?900:a;return{maxAge:o,token:await new R({sessionVersion:i,...r?{roles:[t]}:{}}).setProtectedHeader({alg:`RS256`,kid:e.signing.kid,typ:`JWT`}).setIssuedAt().setJti(crypto.randomUUID()).setIssuer(e.issuer).setAudience(e.audience).setSubject(n).setExpirationTime(`${o}s`).sign(e.signing.key)}}async function requireSession(e,t,n){let r=b(e);if(r===null)throw S();try{let{payload:e}=await B(r,t.verifier,{algorithms:[`RS256`],audience:t.audience,clockTolerance:J,issuer:t.issuer,maxTokenAge:a,requiredClaims:[`sub`,`iss`,`aud`,`iat`,`exp`,`sessionVersion`]}),i=e.sub??``;if(i.length===0||i.length>q||!c(i))throw S();let o=e.sessionVersion;if(typeof o!=`number`||!Number.isSafeInteger(o)||o<0||typeof e.iat!=`number`||e.iat>Date.now()/1e3+J||Array.isArray(e.roles)&&e.roles.includes(`archive-operator`)&&(typeof e.exp!=`number`||e.exp-e.iat>900||Date.now()/1e3-e.iat>900+J))throw S();let s=await N(n.AUTH_DB,i);if(s===null||s.session_version!==o)throw S();return{sessionVersion:o,subject:i,token:r}}catch(e){throw e instanceof z.JOSEError?S():e}}async function sendLink(e,t,n,r){let i=t.appName,a=`The link works once and expires in ${E/6e4} minutes. If you did not request it, ignore this email.`;await e.AUTH_EMAIL.send({from:t.senderAddress,html:`<p>Open this link to sign in to ${escapeHtml(i)}:</p><p><a href="${escapeHtml(r)}">${escapeHtml(r)}</a></p><p>${a}</p>`,subject:`Your ${i} sign-in link`,text:`Open this link to sign in to ${i}:\n\n${r}\n\n${a}`,to:n})}async function handleSignIn(e,t,n){requireMutationGuard(e,n);let r=await y(e);if(typeof r!=`object`||!r||Array.isArray(r))throw p();let i=Object.keys(r),a=Reflect.get(r,`email`);if(i.length!==1||i[0]!==`email`||typeof a!=`string`)throw p();let o=a.trim().toLowerCase();if(!T(o))throw p();let s=Date.now(),c=await I(t.AUTH_DB,s);if(c!==null)throw new f(429,`rate-limited`,`Too many sign-in requests. Try again later.`,{retryAfterSeconds:c});let l=await j(t.AUTH_DB,o),u=await F(t.AUTH_DB,l.id,s);if(u!==null)throw new f(429,`rate-limited`,`Too many sign-in emails. Try again later.`,{retryAfterSeconds:u});let d=randomToken(),m=await hashToken(d);await M(t.AUTH_DB,m,l.id,s);try{await sendLink(t,n,l.email,`${n.publicOrigin}/api/v1/auth/verify?token=${d}`)}catch(e){throw await A(t.AUTH_DB,m).catch(()=>void 0),new C(503,`email`,{cause:e})}return g(202,{ok:!0},_)}async function handleVerify(e,t,n){if(e.method===`GET`){let t=v(new URL(e.url),[`token`]).get(`token`)??``;if(!G.test(t))throw p(`The link is not valid.`);let i=randomToken(),a=`<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Confirm sign-in</title><h1>Sign in to ${escapeHtml(n.appName)}</h1><p>Continue only if you requested this sign-in link.</p><button type="button" id="confirm">Confirm sign-in</button><p role="status" id="status"></p><script nonce="${i}">
1
+ import{sha256Hex as e}from"../_crypto.js";import{ACCOUNT_HEADER as t,ARCHIVE_OPERATOR_ROLE as n,PUBLISHER_HEADER as r,REQUEST_MARKER_HEADER as i,SESSION_COOKIE_NAME as a,SESSION_MAX_AGE_SECONDS as o,archiveAuthHealthSchema as s,archiveErrorResponseSchema as c,isWellFormedText as l,sessionCookieValue as u,uuidSchema as d}from"../contract.js";import{serviceRequest as f}from"../worker/_service.js";import{ApiError as p,badRequest as m,expiredSessionCookie as h,forbidden as g,json as _,noStore as v,queryParams as y,readJsonBody as b,sessionToken as x,toErrorResponse as S,unauthenticated as C}from"../worker/http.js";import{AuthOperationError as w}from"./errors.js";import{authConfig as T,isWellFormedEmail as E}from"./config.js";import{LINK_TTL_MS as D,authReadiness as O,consumeToken as k,deleteAccount as A,deleteToken as j,ensureUser as M,insertToken as N,readAccount as P,revokeSessions as F,spendLinkBudget as I,spendSignInBudget as L,sweep as R}from"./store.js";import{SignJWT as z,errors as B,jwtVerify as V}from"jose";var H={account:/^\/api\/v1\/auth\/account$/,health:/^\/api\/v1\/auth\/health$/,jwks:/^\/api\/v1\/auth\/jwks\.json$/,session:/^\/api\/v1\/auth\/session$/,signIn:/^\/api\/v1\/auth\/sign-in$/,signOutAll:/^\/api\/v1\/auth\/sign-out-all$/,verify:/^\/api\/v1\/auth\/verify$/},U={account:[`GET`,`DELETE`],health:[`GET`],jwks:[`GET`],session:[`GET`],signIn:[`POST`],signOutAll:[`POST`],verify:[`GET`,`POST`]},W={account:`/auth/account`,health:`/auth/health`,jwks:`/auth/jwks.json`,session:`/auth/session`,signIn:`/auth/sign-in`,signOutAll:`/auth/sign-out-all`,verify:`/auth/verify`},matchRoute=e=>Object.keys(H).find(t=>H[t].test(new URL(e.url).pathname)),G=32,K=/^[A-Za-z0-9_-]{43}$/,q=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,J=256,Y=5,randomToken=()=>btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(G)))).replaceAll(`+`,`-`).replaceAll(`/`,`_`).replace(/=+$/,``),escapeHtml=e=>e.replace(/[&<>"']/g,e=>`&#${e.charCodeAt(0)};`),unavailable=()=>new w(503,`catalog`);function requireMutationGuard(e,t,n=!1){let r=e.headers.get(`origin`);if(r===null||!t.allowedOrigins.has(r)&&!(n&&r===t.publicOrigin)||e.headers.get(`x-archive-request`)!==`1`)throw g();return r}function corsHeaders(e,t){let n=e.headers.get(`origin`);return n===null||!t.allowedOrigins.has(n)&&(matchRoute(e)!==`verify`||n!==t.publicOrigin)?{}:{"access-control-allow-credentials":`true`,"access-control-allow-origin":n,vary:`Origin`}}function preflight(e,n,a){let o=corsHeaders(e,n);if(Object.keys(o).length===0)throw g();return new Response(null,{headers:{...o,"access-control-allow-headers":`Content-Type, ${t}, ${r}, ${i}`,"access-control-allow-methods":[...a,`OPTIONS`].join(`, `),"access-control-max-age":`600`},status:204})}var secure=e=>e.appEnv===`production`;async function mintSession(e,t,r,i){let a=r?900:o;return{maxAge:a,token:await new z({sessionVersion:i,...r?{roles:[n]}:{}}).setProtectedHeader({alg:`RS256`,kid:e.signing.kid,typ:`JWT`}).setIssuedAt().setJti(crypto.randomUUID()).setIssuer(e.issuer).setAudience(e.audience).setSubject(t).setExpirationTime(`${a}s`).sign(e.signing.key)}}async function requireSession(e,t,n){let r=x(e);if(r===null)throw C();try{let{payload:e}=await V(r,t.verifier,{algorithms:[`RS256`],audience:t.audience,clockTolerance:Y,issuer:t.issuer,maxTokenAge:o,requiredClaims:[`sub`,`iss`,`aud`,`iat`,`exp`,`sessionVersion`]}),i=e.sub??``;if(i.length===0||i.length>J||!l(i))throw C();let a=e.sessionVersion;if(typeof a!=`number`||!Number.isSafeInteger(a)||a<0||typeof e.iat!=`number`||e.iat>Date.now()/1e3+Y||Array.isArray(e.roles)&&e.roles.includes(`archive-operator`)&&(typeof e.exp!=`number`||e.exp-e.iat>900||Date.now()/1e3-e.iat>900+Y))throw C();let s=await P(n.AUTH_DB,i);if(s===null||s.session_version!==a)throw C();return{sessionVersion:a,subject:i,token:r}}catch(e){throw e instanceof B.JOSEError?C():e}}async function sendLink(e,t,n,r){let i=t.appName,a=`The link works once and expires in ${D/6e4} minutes. If you did not request it, ignore this email.`;await e.AUTH_EMAIL.send({from:t.senderAddress,html:`<p>Open this link to sign in to ${escapeHtml(i)}:</p><p><a href="${escapeHtml(r)}">${escapeHtml(r)}</a></p><p>${a}</p>`,subject:`Your ${i} sign-in link`,text:`Open this link to sign in to ${i}:\n\n${r}\n\n${a}`,to:n})}async function handleSignIn(t,n,r){requireMutationGuard(t,r);let i=await b(t);if(typeof i!=`object`||!i||Array.isArray(i))throw m();let a=Object.keys(i),o=Reflect.get(i,`email`);if(a.length!==1||a[0]!==`email`||typeof o!=`string`)throw m();let s=o.trim().toLowerCase();if(!E(s))throw m();let c=Date.now(),l=await L(n.AUTH_DB,c);if(l!==null)throw new p(429,`rate-limited`,`Too many sign-in requests. Try again later.`,{retryAfterSeconds:l});let u=await M(n.AUTH_DB,s),d=await I(n.AUTH_DB,u.id,c);if(d!==null)throw new p(429,`rate-limited`,`Too many sign-in emails. Try again later.`,{retryAfterSeconds:d});let f=randomToken(),h=await e(f);await N(n.AUTH_DB,h,u.id,c);try{await sendLink(n,r,u.email,`${r.publicOrigin}/api/v1/auth/verify?token=${f}`)}catch(e){throw await j(n.AUTH_DB,h).catch(()=>void 0),new w(503,`email`,{cause:e})}return _(202,{ok:!0},v)}async function handleVerify(t,n,r){if(t.method===`GET`){let e=y(new URL(t.url),[`token`]).get(`token`)??``;if(!K.test(e))throw m(`The link is not valid.`);let n=randomToken(),a=`<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Confirm sign-in</title><h1>Sign in to ${escapeHtml(r.appName)}</h1><p>Continue only if you requested this sign-in link.</p><button type="button" id="confirm">Confirm sign-in</button><p role="status" id="status"></p><script nonce="${n}">
2
2
  history.replaceState(null, '', location.pathname);
3
3
  document.getElementById('confirm').addEventListener('click', async () => {
4
4
  const button = document.getElementById('confirm');
5
5
  button.disabled = true;
6
6
  try {
7
- const response = await fetch(location.pathname, { method: 'POST', credentials: 'same-origin', headers: { 'content-type': 'application/json', '${r}': '1' }, body: JSON.stringify({ token: '${t}' }) });
7
+ const response = await fetch(location.pathname, { method: 'POST', credentials: 'same-origin', headers: { 'content-type': 'application/json', '${i}': '1' }, body: JSON.stringify({ token: '${e}' }) });
8
8
  if (!response.ok) throw new Error();
9
- location.replace(${JSON.stringify(`${n.publicOrigin}/signed-in`)});
9
+ location.replace(${JSON.stringify(`${r.publicOrigin}/signed-in`)});
10
10
  } catch {
11
11
  document.getElementById('status').textContent = 'Sign-in failed. Request a new link or try again.';
12
12
  button.disabled = false;
13
13
  }
14
14
  });
15
- <\/script></html>`;return new Response(a,{headers:{..._,"content-security-policy":`default-src 'none'; script-src 'nonce-${i}'; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`,"content-type":`text/html; charset=utf-8`,"referrer-policy":`no-referrer`,"x-content-type-options":`nosniff`}})}requireMutationGuard(e,n,!0),v(new URL(e.url),[]);let i=await y(e);if(typeof i!=`object`||!i||Array.isArray(i)||Object.keys(i).length!==1)throw p(`The link is not valid.`);let a=Reflect.get(i,`token`);if(typeof a!=`string`||!G.test(a))throw p(`The link is not valid.`);let o=await O(t.AUTH_DB,await hashToken(a),Date.now());if(o===null)throw new f(410,`gone`,`That link has expired or was already used.`);let s=await mintSession(n,o.id,n.operatorEmails.has(o.email),o.sessionVersion);return new Response(null,{headers:{..._,"set-cookie":l(s.token,{maxAgeSeconds:s.maxAge,secure:secure(n)})},status:204})}async function handleExport(e,t,n){let{subject:r}=await requireSession(e,n,t),i=await N(t.AUTH_DB,r);if(i===null)throw S();return g(200,{createdAt:i.created_at,email:i.email,id:i.id,lastSignInAt:i.last_sign_in_at},_)}async function archiveFailure(e){let t=await e.text().catch(()=>``),n=null;try{n=JSON.parse(t)}catch{n=null}let r=s.safeParse(n);if(!r.success||e.status<400||e.status>599)throw unavailable();let{code:i,message:a,requestId:o}=r.data.error,c=e.headers.get(`retry-after`);return g(e.status,{error:{code:i,message:a,requestId:o}},c!==null&&/^\d{1,6}$/.test(c)?{..._,"retry-after":c}:_)}async function handleErase(t,a,o){let s=requireMutationGuard(t,o),{subject:c,token:l}=await requireSession(t,o,a),h=t.headers.get(e);if(h===null||!u.safeParse(h).success)throw p();if(h!==c)throw new f(409,`account-changed`,`The signed-in account changed since this request was prepared.`);let g=new Headers({cookie:`${i}=${l}`,origin:s,[r]:`1`}),v=t.headers.get(n);if(v!==null){if(!K.test(v))throw p();g.set(n,v)}let y;try{y=await d(a.AUTH_ARCHIVE,new Request(`${o.publicOrigin}/api/v1/me/account`,{headers:g,method:`DELETE`,redirect:`manual`}),async e=>e.status===204?(await e.body?.cancel(),e):archiveFailure(e))}catch(e){throw new C(503,`catalog`,{cause:e})}return y.status===204?(await k(a.AUTH_DB,c),new Response(null,{headers:{..._,"set-cookie":m(secure(o))},status:204})):y}async function handleSignOutAll(t,n,r){requireMutationGuard(t,r);let{subject:i,sessionVersion:a}=await requireSession(t,r,n),o=t.headers.get(e);if(o===null||!u.safeParse(o).success)throw p();if(o!==i)throw new f(409,`account-changed`,`The signed-in account changed since this request was prepared.`);if(await P(n.AUTH_DB,i,a)===null)throw S();return g(200,{ok:!0},{..._,"set-cookie":m(secure(r))})}async function handleHealth(e){let t=null,n=null;try{await w(e)}catch{t=`configuration-unavailable`}if(t===null)try{n=await D(e.AUTH_DB),n!==1&&(t=`schema-mismatch`)}catch{t=`database-unavailable`}return g(t===null?200:503,o.parse({dbSchemaVersion:n,reason:t,schemaVersion:1,status:t===null?`ok`:`degraded`}),_)}async function route(e,t){let n=e.method.toUpperCase(),r=matchRoute(e);if(r===void 0)throw new f(404,`not-found`,`No such route.`);if(r===`health`&&n===`GET`)return handleHealth(t);let i=await w(t),a=corsHeaders(e,i);if(n===`OPTIONS`)return preflight(e,i,H[r]);if(!H[r].includes(n))throw new f(405,`method-not-allowed`,`That method is not allowed here.`);let o;switch(r){case`health`:o=await handleHealth(t);break;case`session`:await requireSession(e,i,t),o=g(200,{ok:!0},_);break;case`signOutAll`:o=await handleSignOutAll(e,t,i);break;case`jwks`:o=g(200,{keys:i.jwks},_);break;case`signIn`:o=await handleSignIn(e,t,i);break;case`verify`:o=await handleVerify(e,t,i);break;case`account`:o=n===`GET`?await handleExport(e,t,i):await handleErase(e,t,i)}return withCors(o,a)}function withCors(e,t){if(Object.keys(t).length===0)return e;let n=new Response(e.body,e);for(let[e,r]of Object.entries(t))n.headers.set(e,r);return n}var diagnostic=e=>e instanceof C?e.authDiagnostic:{kind:`internal`};function createAuthWorker(){let e=new Set,emit=t=>{for(let n of e)try{n(t)}catch{}};return{async fetch(t,n){let r=crypto.randomUUID(),i=Date.now(),a,c;try{a=await route(t,n)}catch(e){c=e,a=x(e,r);let i=await w(n).catch(()=>null);i!==null&&(a=withCors(a,corsHeaders(t,i)))}if(matchRoute(t)===`verify`&&(a.headers.set(`cache-control`,`no-store`),a.headers.set(`referrer-policy`,`no-referrer`),a.headers.set(`x-content-type-options`,`nosniff`),a.headers.has(`content-security-policy`)||a.headers.set(`content-security-policy`,`default-src 'none'; base-uri 'none'; frame-ancestors 'none'`)),e.size>0){let e=matchRoute(t),n=a.status<400?`ok`:e===`health`?`unavailable`:c instanceof f?c.code:`internal`,l=c===void 0&&a.status>=400?s.safeParse(await a.clone().json().catch(()=>null)):null,u=e===`health`&&a.status===503?o.safeParse(await a.clone().json().catch(()=>null)):null;emit({code:l?.success?l.data.error.code:n,ms:Math.max(0,Date.now()-i),requestId:r,route:e===void 0?`unmatched`:U[e],status:a.status,type:`request`,...a.status>=500?{diagnostic:u?.success?{kind:u.data.reason===`configuration-unavailable`?`configuration`:u.data.reason===`schema-mismatch`?`schema`:`database`}:c===void 0?{kind:`catalog`}:diagnostic(c)}:{}})}return a},async scheduled(t,n){try{await w(n);let t=await L(n.AUTH_DB,Date.now());e.size>0&&emit({removed:t,status:`ok`,type:`scheduled`})}catch(t){throw e.size>0&&emit({diagnostic:diagnostic(t),status:`failed`,type:`scheduled`}),t}},tap(t,n){if(n?.signal?.aborted)return()=>void 0;let observer=e=>t(e),unsubscribe=()=>{e.delete(observer),n?.signal?.removeEventListener(`abort`,unsubscribe)};return e.add(observer),n?.signal?.addEventListener(`abort`,unsubscribe,{once:!0}),unsubscribe}}}export{createAuthWorker};
15
+ <\/script></html>`;return new Response(a,{headers:{...v,"content-security-policy":`default-src 'none'; script-src 'nonce-${n}'; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`,"content-type":`text/html; charset=utf-8`,"referrer-policy":`no-referrer`,"x-content-type-options":`nosniff`}})}requireMutationGuard(t,r,!0),y(new URL(t.url),[]);let a=await b(t);if(typeof a!=`object`||!a||Array.isArray(a)||Object.keys(a).length!==1)throw m(`The link is not valid.`);let o=Reflect.get(a,`token`);if(typeof o!=`string`||!K.test(o))throw m(`The link is not valid.`);let s=await k(n.AUTH_DB,await e(o),Date.now());if(s===null)throw new p(410,`gone`,`That link has expired or was already used.`);let c=await mintSession(r,s.id,r.operatorEmails.has(s.email),s.sessionVersion);return new Response(null,{headers:{...v,"set-cookie":u(c.token,{maxAgeSeconds:c.maxAge,secure:secure(r)})},status:204})}async function handleExport(e,t,n){let{subject:r}=await requireSession(e,n,t),i=await P(t.AUTH_DB,r);if(i===null)throw C();return _(200,{createdAt:i.created_at,email:i.email,id:i.id,lastSignInAt:i.last_sign_in_at},v)}async function archiveFailure(e){let t=await e.text().catch(()=>``),n=null;try{n=JSON.parse(t)}catch{n=null}let r=c.safeParse(n);if(!r.success||e.status<400||e.status>599)throw unavailable();let{code:i,message:a,requestId:o}=r.data.error,s=e.headers.get(`retry-after`);return _(e.status,{error:{code:i,message:a,requestId:o}},s!==null&&/^\d{1,6}$/.test(s)?{...v,"retry-after":s}:v)}async function handleErase(e,n,o){let s=requireMutationGuard(e,o),{subject:c,token:l}=await requireSession(e,o,n),u=e.headers.get(t);if(u===null||!d.safeParse(u).success)throw m();if(u!==c)throw new p(409,`account-changed`,`The signed-in account changed since this request was prepared.`);let g=new Headers({cookie:`${a}=${l}`,origin:s,[i]:`1`}),_=e.headers.get(r);if(_!==null){if(!q.test(_))throw m();g.set(r,_)}let y;try{y=await f(n.AUTH_ARCHIVE,new Request(`${o.publicOrigin}/api/v1/me/account`,{headers:g,method:`DELETE`,redirect:`manual`}),async e=>e.status===204?(await e.body?.cancel(),e):archiveFailure(e))}catch(e){throw new w(503,`catalog`,{cause:e})}return y.status===204?(await A(n.AUTH_DB,c),new Response(null,{headers:{...v,"set-cookie":h(secure(o))},status:204})):y}async function handleSignOutAll(e,n,r){requireMutationGuard(e,r);let{subject:i,sessionVersion:a}=await requireSession(e,r,n),o=e.headers.get(t);if(o===null||!d.safeParse(o).success)throw m();if(o!==i)throw new p(409,`account-changed`,`The signed-in account changed since this request was prepared.`);if(await F(n.AUTH_DB,i,a)===null)throw C();return _(200,{ok:!0},{...v,"set-cookie":h(secure(r))})}async function handleHealth(e){let t=null,n=null;try{await T(e)}catch{t=`configuration-unavailable`}if(t===null)try{n=await O(e.AUTH_DB),n!==1&&(t=`schema-mismatch`)}catch{t=`database-unavailable`}return _(t===null?200:503,s.parse({dbSchemaVersion:n,reason:t,schemaVersion:1,status:t===null?`ok`:`degraded`}),v)}async function route(e,t){let n=e.method.toUpperCase(),r=matchRoute(e);if(r===void 0)throw new p(404,`not-found`,`No such route.`);if(r===`health`&&n===`GET`)return handleHealth(t);let i=await T(t),a=corsHeaders(e,i);if(n===`OPTIONS`)return preflight(e,i,U[r]);if(!U[r].includes(n))throw new p(405,`method-not-allowed`,`That method is not allowed here.`);let o;switch(r){case`health`:o=await handleHealth(t);break;case`session`:await requireSession(e,i,t),o=_(200,{ok:!0},v);break;case`signOutAll`:o=await handleSignOutAll(e,t,i);break;case`jwks`:o=_(200,{keys:i.jwks},v);break;case`signIn`:o=await handleSignIn(e,t,i);break;case`verify`:o=await handleVerify(e,t,i);break;case`account`:o=n===`GET`?await handleExport(e,t,i):await handleErase(e,t,i)}return withCors(o,a)}function withCors(e,t){if(Object.keys(t).length===0)return e;let n=new Response(e.body,e);for(let[e,r]of Object.entries(t))n.headers.set(e,r);return n}var diagnostic=e=>e instanceof w?e.authDiagnostic:{kind:`internal`};function createAuthWorker(){let e=new Set,emit=t=>{for(let n of e)try{n(t)}catch{}};return{async fetch(t,n){let r=crypto.randomUUID(),i=Date.now(),a,o;try{a=await route(t,n)}catch(e){o=e,a=S(e,r);let i=await T(n).catch(()=>null);i!==null&&(a=withCors(a,corsHeaders(t,i)))}if(matchRoute(t)===`verify`&&(a.headers.set(`cache-control`,`no-store`),a.headers.set(`referrer-policy`,`no-referrer`),a.headers.set(`x-content-type-options`,`nosniff`),a.headers.has(`content-security-policy`)||a.headers.set(`content-security-policy`,`default-src 'none'; base-uri 'none'; frame-ancestors 'none'`)),e.size>0){let e=matchRoute(t),n=a.status<400?`ok`:e===`health`?`unavailable`:o instanceof p?o.code:`internal`,l=o===void 0&&a.status>=400?c.safeParse(await a.clone().json().catch(()=>null)):null,u=e===`health`&&a.status===503?s.safeParse(await a.clone().json().catch(()=>null)):null;emit({code:l?.success?l.data.error.code:n,ms:Math.max(0,Date.now()-i),requestId:r,route:e===void 0?`unmatched`:W[e],status:a.status,type:`request`,...a.status>=500?{diagnostic:u?.success?{kind:u.data.reason===`configuration-unavailable`?`configuration`:u.data.reason===`schema-mismatch`?`schema`:`database`}:o===void 0?{kind:`catalog`}:diagnostic(o)}:{}})}return a},async scheduled(t,n){try{await T(n);let t=await R(n.AUTH_DB,Date.now());e.size>0&&emit({removed:t,status:`ok`,type:`scheduled`})}catch(t){throw e.size>0&&emit({diagnostic:diagnostic(t),status:`failed`,type:`scheduled`}),t}},tap(t,n){if(n?.signal?.aborted)return()=>void 0;let observer=e=>t(e),unsubscribe=()=>{e.delete(observer),n?.signal?.removeEventListener(`abort`,unsubscribe)};return e.add(observer),n?.signal?.addEventListener(`abort`,unsubscribe,{once:!0}),unsubscribe}}}export{createAuthWorker};
16
16
  //# sourceMappingURL=worker.js.map