@shware/security 8.0.1 → 9.1.0

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 (62) hide show
  1. package/README.md +15 -6
  2. package/dist/auth/error.cjs.map +1 -1
  3. package/dist/auth/error.d.cts +5 -2
  4. package/dist/auth/error.d.cts.map +1 -1
  5. package/dist/auth/error.d.mts +5 -2
  6. package/dist/auth/error.d.mts.map +1 -1
  7. package/dist/auth/error.mjs.map +1 -1
  8. package/dist/auth/index.cjs +45 -15
  9. package/dist/auth/index.cjs.map +1 -1
  10. package/dist/auth/index.d.cts +12 -3
  11. package/dist/auth/index.d.cts.map +1 -1
  12. package/dist/auth/index.d.mts +12 -3
  13. package/dist/auth/index.d.mts.map +1 -1
  14. package/dist/auth/index.mjs +45 -15
  15. package/dist/auth/index.mjs.map +1 -1
  16. package/dist/auth/types.d.cts +20 -9
  17. package/dist/auth/types.d.cts.map +1 -1
  18. package/dist/auth/types.d.mts +20 -9
  19. package/dist/auth/types.d.mts.map +1 -1
  20. package/dist/index.d.cts +2 -2
  21. package/dist/index.d.mts +2 -2
  22. package/dist/oauth2/client.cjs +10 -1
  23. package/dist/oauth2/client.cjs.map +1 -1
  24. package/dist/oauth2/client.d.cts +7 -1
  25. package/dist/oauth2/client.d.cts.map +1 -1
  26. package/dist/oauth2/client.d.mts +7 -1
  27. package/dist/oauth2/client.d.mts.map +1 -1
  28. package/dist/oauth2/client.mjs +10 -1
  29. package/dist/oauth2/client.mjs.map +1 -1
  30. package/dist/oauth2/provider/apple.cjs +4 -0
  31. package/dist/oauth2/provider/apple.cjs.map +1 -1
  32. package/dist/oauth2/provider/apple.d.cts.map +1 -1
  33. package/dist/oauth2/provider/apple.d.mts.map +1 -1
  34. package/dist/oauth2/provider/apple.mjs +4 -0
  35. package/dist/oauth2/provider/apple.mjs.map +1 -1
  36. package/dist/oauth2/provider/common.cjs +1 -0
  37. package/dist/oauth2/provider/common.cjs.map +1 -1
  38. package/dist/oauth2/provider/common.d.cts +1 -0
  39. package/dist/oauth2/provider/common.d.cts.map +1 -1
  40. package/dist/oauth2/provider/common.d.mts +1 -0
  41. package/dist/oauth2/provider/common.d.mts.map +1 -1
  42. package/dist/oauth2/provider/common.mjs +1 -0
  43. package/dist/oauth2/provider/common.mjs.map +1 -1
  44. package/dist/oauth2/provider/facebook.cjs +4 -0
  45. package/dist/oauth2/provider/facebook.cjs.map +1 -1
  46. package/dist/oauth2/provider/facebook.d.cts.map +1 -1
  47. package/dist/oauth2/provider/facebook.d.mts.map +1 -1
  48. package/dist/oauth2/provider/facebook.mjs +4 -0
  49. package/dist/oauth2/provider/facebook.mjs.map +1 -1
  50. package/dist/oauth2/provider/google.cjs +4 -0
  51. package/dist/oauth2/provider/google.cjs.map +1 -1
  52. package/dist/oauth2/provider/google.d.cts.map +1 -1
  53. package/dist/oauth2/provider/google.d.mts.map +1 -1
  54. package/dist/oauth2/provider/google.mjs +4 -0
  55. package/dist/oauth2/provider/google.mjs.map +1 -1
  56. package/dist/oauth2/types.cjs.map +1 -1
  57. package/dist/oauth2/types.d.cts +21 -0
  58. package/dist/oauth2/types.d.cts.map +1 -1
  59. package/dist/oauth2/types.d.mts +21 -0
  60. package/dist/oauth2/types.d.mts.map +1 -1
  61. package/dist/oauth2/types.mjs.map +1 -1
  62. package/package.json +1 -1
package/README.md CHANGED
@@ -200,7 +200,7 @@ server fault: `server_error` on the redirect, rethrown to your error handler on
200
200
  | `kvRepository` | `KVRepository` | Required. Short-lived values: OAuth2 state/nonce, verification and desktop codes. |
201
201
  | `cookie` | `CookieOptions & { name?: string }` | Session cookie. Defaults: name `SESSION`, `path: '/'`, `SameSite=None`, `Secure`, `HttpOnly`. |
202
202
  | `oauth2.client` | `OAuth2ClientConfig` | `baseUri`, `errorUri`, `successUri`, `providers` (object or async function). |
203
- | `oauth2.onetap` | `{ requireNonce? }` | One Tap: refuse a `credential` without an issued nonce (default `true`, see Google One Tap). |
203
+ | `oauth2.nonce` | `{ optional?: string[] }` | Providers whose logins may come without a nonce; every id-token flow requires one otherwise. |
204
204
  | `turnstileSecretKey` | `string` | Cloudflare Turnstile secret; required by `sendEmailVerificationCode`. |
205
205
  | `verificationCode` | `{ maxAttempts?, resendCooldown? }` | Email code limits: guesses per code (default 5), seconds between sends (default 60). |
206
206
  | `timing` | `boolean` | Adds a `Server-Timing` header to OAuth2 responses. |
@@ -213,7 +213,11 @@ cookie's `HttpOnly` keeps it from, and a cross-origin client needs the header in
213
213
  `Access-Control-Expose-Headers`. `Authorization` is never read: an API token is a different
214
214
  credential from a session and is not handled here.
215
215
  `logout` clears the cookie with the same attributes it was set with (`domain`, `path`, …), so a
216
- cookie set with `Domain=.example.com` is actually removed.
216
+ cookie set with `Domain=.example.com` is actually removed. `logout(request, { scope })` widens what
217
+ it ends, named as Supabase's `signOut` names them: `local` (default) the request's own session,
218
+ `global` every session of its principal ("sign out everywhere": deleting the account, a password
219
+ change), `others` every session but this one, which keeps the caller signed in ("sign out other
220
+ devices"). `kick(principal)` is the same eviction for a principal other than the caller.
217
221
 
218
222
  Besides the route handlers, `Auth` exposes session helpers: `getPrincipal(request)`,
219
223
  `isAuthenticated(request)`, `getSession(request, create)`, `listSessions(principal)`,
@@ -539,10 +543,15 @@ if (result.authorized) {
539
543
  }
540
544
  ```
541
545
 
542
- While a front end that does not pass `nonce` yet is still deployed, set
543
- `oauth2: { onetap: { requireNonce: false } }`: credentials without a nonce are then accepted, and a
544
- nonce a credential does carry is still checked and consumed. Turn it back on once that front end is
545
- gone.
546
+ While a front end that does not pass `nonce` yet is still deployed, list the provider in
547
+ `oauth2: { nonce: { optional: ['google'] } }`: credentials without a nonce are then accepted, and a
548
+ nonce a credential does carry is still checked and consumed. Remove it once that front end is gone.
549
+
550
+ The same rule covers every flow in which an id token comes back: a provider declares which of its
551
+ flows echo a nonce (`Provider.nonce`: Apple web and native, Google web and One Tap, Facebook
552
+ Limited Login), and `Auth` requires it there. The redirect flow sends its own nonce with the
553
+ authorization request and refuses a callback whose id token does not carry it back; a native login
554
+ must carry one issued by `GET /oauth2/nonce/:provider`, which it consumes.
546
555
 
547
556
  ## Email sign-in
548
557
 
@@ -1 +1 @@
1
- {"version":3,"file":"error.cjs","names":["given"],"sources":["../../src/auth/error.ts"],"sourcesContent":["type Metadata = Record<string, string>;\n/** A reason that carries no metadata. */\ntype NoMetadata = { [key: string]: never };\n\n/**\n * The reasons `onAuthorized` may refuse a sign-in with, each with the metadata it carries (string\n * fields only: metadata travels as URL parameters and JSON). The built-in ones cover the account\n * states every host meets; add your own by augmenting the interface, and `AuthenticationError`\n * accepts exactly these reasons, requiring the metadata when one of its fields is required:\n *\n * ```ts\n * declare module '@shware/security' {\n * interface AuthenticationReasons {\n * CLOSED_BETA: { invite?: string };\n * }\n * }\n * ```\n */\nexport interface AuthenticationReasons {\n // Thrown by the SDK itself.\n /** The emailed code is wrong, or none is pending for the address. */\n INVALID_VERIFICATION_CODE: NoMetadata;\n /** More than `verificationCode.maxAttempts` guesses at the code; it is discarded. */\n VERIFICATION_CODE_ATTEMPTS_EXCEEDED: NoMetadata;\n /** The id token carries no nonce and one is required (`oauth2.onetap.requireNonce`). */\n NONCE_MISSING: NoMetadata;\n /** The id token's nonce was not issued for this provider, or was used already. */\n NONCE_MISMATCH: NoMetadata;\n /** The desktop sign-in code is unknown, expired, used, or its verifier does not match. */\n INVALID_DESKTOP_CODE: NoMetadata;\n\n // For the host's `onAuthorized`.\n /** The account is disabled: banned, or closed by its owner. */\n ACCOUNT_DISABLED: NoMetadata;\n /** The account is locked for now; `until` is when it opens again, when known. */\n ACCOUNT_LOCKED: { until?: string };\n /** The address belongs to another account; `provider` is the one to sign in with instead. */\n EMAIL_ALREADY_USED: { provider?: string };\n /** The host accepts only verified addresses and this provider did not verify it. */\n EMAIL_NOT_VERIFIED: { provider?: string };\n /** No new accounts: registration is closed or by invitation. */\n SIGNUP_DISABLED: NoMetadata;\n}\n\n/** The built-in reasons, for a client's message table or a check that every reason is handled. */\nexport const AUTHENTICATION_REASONS = [\n 'INVALID_VERIFICATION_CODE',\n 'VERIFICATION_CODE_ATTEMPTS_EXCEEDED',\n 'NONCE_MISSING',\n 'NONCE_MISMATCH',\n 'INVALID_DESKTOP_CODE',\n 'ACCOUNT_DISABLED',\n 'ACCOUNT_LOCKED',\n 'EMAIL_ALREADY_USED',\n 'EMAIL_NOT_VERIFIED',\n 'SIGNUP_DISABLED',\n] as const satisfies readonly (keyof AuthenticationReasons)[];\n\n/**\n * Each reason's metadata as declared; a field that is not a string makes the reason unusable\n * (`never`).\n */\ntype Reasons = {\n [K in keyof AuthenticationReasons]: AuthenticationReasons[K] extends Partial<Metadata>\n ? AuthenticationReasons[K]\n : never;\n};\n\n/** A reason `onAuthorized` may refuse with: the keys of `AuthenticationReasons`. */\nexport type AuthenticationReason = keyof Reasons;\n\n/** `true` when the reason's metadata has no required field, so it may be left out. */\ntype Optional<R extends AuthenticationReason> = Reasons[R] extends NoMetadata\n ? true\n : Partial<Reasons[R]> extends Reasons[R]\n ? true\n : false;\ntype Options<R extends AuthenticationReason> = {\n message?: string;\n cause?: unknown;\n} & (Optional<R> extends true ? { metadata?: Reasons[R] } : { metadata: Reasons[R] });\n\n/**\n * Thrown by the host's `onAuthorized` to refuse a sign-in it could complete but will not: an\n * address another account holds, a banned user, a closed beta. `reason` is the code the client\n * branches on, `metadata` what it needs to act (the provider to sign in with instead); both\n * travel as they are, so keep them short and free of secrets. `Auth` answers a refusal itself,\n * in the shape of the route it came through:\n *\n * - redirect flow (`loginOAuth2Code`): `errorUri?error=access_denied&reason=<reason>&<metadata>`;\n * - JSON routes (native, One Tap, email, desktop): `403` with a google.rpc error body whose\n * `ErrorInfo` holds `reason` and `metadata`.\n *\n * The SDK throws it too, for a credential it checked itself (a wrong emailed code, a replayed\n * nonce), so a client handles both the same way. Anything else `onAuthorized` throws is a server\n * fault: `server_error` on the redirect, rethrown to the host's error handler on the JSON routes.\n */\nexport class AuthenticationError<\n R extends AuthenticationReason = AuthenticationReason,\n> extends Error {\n readonly reason: R;\n readonly metadata: Metadata;\n\n constructor(reason: R, ...[options]: Optional<R> extends true ? [Options<R>?] : [Options<R>]) {\n const given = options;\n const { message, cause, metadata = {} } = given ?? {};\n super(message ?? `Sign-in refused: ${reason}`, { cause });\n this.name = 'AuthenticationError';\n this.reason = reason;\n this.metadata = {};\n for (const [key, value] of Object.entries(metadata)) {\n if (typeof value === 'string') this.metadata[key] = value;\n }\n Object.setPrototypeOf(this, AuthenticationError.prototype);\n }\n}\n"],"mappings":";;;AA6CA,MAAa,yBAAyB;CACpC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;;;;;;;;;;AAyCA,IAAa,sBAAb,MAAa,4BAEH,MAAM;CACd;CACA;CAEA,YAAY,QAAW,GAAG,CAAC,UAAmE;EAE5F,MAAM,EAAE,SAAS,OAAO,WAAW,CAAC,MAAMA,WAAS,CAAC;EACpD,MAAM,WAAW,oBAAoB,UAAU,EAAE,MAAM,CAAC;EACxD,KAAK,OAAO;EACZ,KAAK,SAAS;EACd,KAAK,WAAW,CAAC;EACjB,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,QAAQ,GAChD,IAAI,OAAO,UAAU,UAAU,KAAK,SAAS,OAAO;EAEtD,OAAO,eAAe,MAAM,oBAAoB,SAAS;CAC3D;AACF"}
1
+ {"version":3,"file":"error.cjs","names":["given"],"sources":["../../src/auth/error.ts"],"sourcesContent":["type Metadata = Record<string, string>;\n/** A reason that carries no metadata. */\ntype NoMetadata = { [key: string]: never };\n\n/**\n * The reasons `onAuthorized` may refuse a sign-in with, each with the metadata it carries (string\n * fields only: metadata travels as URL parameters and JSON). The built-in ones cover the account\n * states every host meets; add your own by augmenting the interface, and `AuthenticationError`\n * accepts exactly these reasons, requiring the metadata when one of its fields is required:\n *\n * ```ts\n * declare module '@shware/security' {\n * interface AuthenticationReasons {\n * CLOSED_BETA: { invite?: string };\n * }\n * }\n * ```\n */\nexport interface AuthenticationReasons {\n // Thrown by the SDK itself.\n /** The emailed code is wrong, or none is pending for the address. */\n INVALID_VERIFICATION_CODE: NoMetadata;\n /** More than `verificationCode.maxAttempts` guesses at the code; it is discarded. */\n VERIFICATION_CODE_ATTEMPTS_EXCEEDED: NoMetadata;\n /** The id token carries no nonce and the provider's flow requires one (`oauth2.nonce.optional`). */\n NONCE_MISSING: NoMetadata;\n /**\n * The id token's nonce is not the one this sign-in was started with: not issued for this\n * provider, used already, or (redirect flow) not the one sent with the authorization request.\n */\n NONCE_MISMATCH: NoMetadata;\n /** The desktop sign-in code is unknown, expired, used, or its verifier does not match. */\n INVALID_DESKTOP_CODE: NoMetadata;\n\n // For the host's `onAuthorized`.\n /** The account is disabled: banned, or closed by its owner. */\n ACCOUNT_DISABLED: NoMetadata;\n /** The account is locked for now; `until` is when it opens again, when known. */\n ACCOUNT_LOCKED: { until?: string };\n /** The address belongs to another account; `provider` is the one to sign in with instead. */\n EMAIL_ALREADY_USED: { provider?: string };\n /** The host accepts only verified addresses and this provider did not verify it. */\n EMAIL_NOT_VERIFIED: { provider?: string };\n /** No new accounts: registration is closed or by invitation. */\n SIGNUP_DISABLED: NoMetadata;\n}\n\n/** The built-in reasons, for a client's message table or a check that every reason is handled. */\nexport const AUTHENTICATION_REASONS = [\n 'INVALID_VERIFICATION_CODE',\n 'VERIFICATION_CODE_ATTEMPTS_EXCEEDED',\n 'NONCE_MISSING',\n 'NONCE_MISMATCH',\n 'INVALID_DESKTOP_CODE',\n 'ACCOUNT_DISABLED',\n 'ACCOUNT_LOCKED',\n 'EMAIL_ALREADY_USED',\n 'EMAIL_NOT_VERIFIED',\n 'SIGNUP_DISABLED',\n] as const satisfies readonly (keyof AuthenticationReasons)[];\n\n/**\n * Each reason's metadata as declared; a field that is not a string makes the reason unusable\n * (`never`).\n */\ntype Reasons = {\n [K in keyof AuthenticationReasons]: AuthenticationReasons[K] extends Partial<Metadata>\n ? AuthenticationReasons[K]\n : never;\n};\n\n/** A reason `onAuthorized` may refuse with: the keys of `AuthenticationReasons`. */\nexport type AuthenticationReason = keyof Reasons;\n\n/** `true` when the reason's metadata has no required field, so it may be left out. */\ntype Optional<R extends AuthenticationReason> = Reasons[R] extends NoMetadata\n ? true\n : Partial<Reasons[R]> extends Reasons[R]\n ? true\n : false;\ntype Options<R extends AuthenticationReason> = {\n message?: string;\n cause?: unknown;\n} & (Optional<R> extends true ? { metadata?: Reasons[R] } : { metadata: Reasons[R] });\n\n/**\n * Thrown by the host's `onAuthorized` to refuse a sign-in it could complete but will not: an\n * address another account holds, a banned user, a closed beta. `reason` is the code the client\n * branches on, `metadata` what it needs to act (the provider to sign in with instead); both\n * travel as they are, so keep them short and free of secrets. `Auth` answers a refusal itself,\n * in the shape of the route it came through:\n *\n * - redirect flow (`loginOAuth2Code`): `errorUri?error=access_denied&reason=<reason>&<metadata>`;\n * - JSON routes (native, One Tap, email, desktop): `403` with a google.rpc error body whose\n * `ErrorInfo` holds `reason` and `metadata`.\n *\n * The SDK throws it too, for a credential it checked itself (a wrong emailed code, a replayed\n * nonce), so a client handles both the same way. Anything else `onAuthorized` throws is a server\n * fault: `server_error` on the redirect, rethrown to the host's error handler on the JSON routes.\n */\nexport class AuthenticationError<\n R extends AuthenticationReason = AuthenticationReason,\n> extends Error {\n readonly reason: R;\n readonly metadata: Metadata;\n\n constructor(reason: R, ...[options]: Optional<R> extends true ? [Options<R>?] : [Options<R>]) {\n const given = options;\n const { message, cause, metadata = {} } = given ?? {};\n super(message ?? `Sign-in refused: ${reason}`, { cause });\n this.name = 'AuthenticationError';\n this.reason = reason;\n this.metadata = {};\n for (const [key, value] of Object.entries(metadata)) {\n if (typeof value === 'string') this.metadata[key] = value;\n }\n Object.setPrototypeOf(this, AuthenticationError.prototype);\n }\n}\n"],"mappings":";;;AAgDA,MAAa,yBAAyB;CACpC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;;;;;;;;;;AAyCA,IAAa,sBAAb,MAAa,4BAEH,MAAM;CACd;CACA;CAEA,YAAY,QAAW,GAAG,CAAC,UAAmE;EAE5F,MAAM,EAAE,SAAS,OAAO,WAAW,CAAC,MAAMA,WAAS,CAAC;EACpD,MAAM,WAAW,oBAAoB,UAAU,EAAE,MAAM,CAAC;EACxD,KAAK,OAAO;EACZ,KAAK,SAAS;EACd,KAAK,WAAW,CAAC;EACjB,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,QAAQ,GAChD,IAAI,OAAO,UAAU,UAAU,KAAK,SAAS,OAAO;EAEtD,OAAO,eAAe,MAAM,oBAAoB,SAAS;CAC3D;AACF"}
@@ -22,9 +22,12 @@ export interface AuthenticationReasons {
22
22
  INVALID_VERIFICATION_CODE: NoMetadata;
23
23
  /** More than `verificationCode.maxAttempts` guesses at the code; it is discarded. */
24
24
  VERIFICATION_CODE_ATTEMPTS_EXCEEDED: NoMetadata;
25
- /** The id token carries no nonce and one is required (`oauth2.onetap.requireNonce`). */
25
+ /** The id token carries no nonce and the provider's flow requires one (`oauth2.nonce.optional`). */
26
26
  NONCE_MISSING: NoMetadata;
27
- /** The id token's nonce was not issued for this provider, or was used already. */
27
+ /**
28
+ * The id token's nonce is not the one this sign-in was started with: not issued for this
29
+ * provider, used already, or (redirect flow) not the one sent with the authorization request.
30
+ */
28
31
  NONCE_MISMATCH: NoMetadata;
29
32
  /** The desktop sign-in code is unknown, expired, used, or its verifier does not match. */
30
33
  INVALID_DESKTOP_CODE: NoMetadata;
@@ -1 +1 @@
1
- {"version":3,"file":"error.d.cts","names":[],"sources":["../../src/auth/error.ts"],"mappings":"A,KAAK,WAAW;;KAEX;GAAgB;;;;;;;;;;;;;;;;iBAgBJ;;EAGf,2BAA2B;;EAE3B,qCAAqC;;EAErC,eAAe;;EAEf,gBAAgB;;EAEhB,sBAAsB;;EAItB,kBAAkB;;EAElB;IAAkB;;;EAElB;IAAsB;;;EAEtB;IAAsB;;;EAEtB,iBAAiB;;;qBAIN;;;;;KAiBR,aACF,WAAW,wBAAwB,sBAAsB,WAAW,QAAQ,YACzE,sBAAsB;;YAKhB,6BAA6B;;KAGpC,SAAS,UAAU,wBAAwB,QAAQ,WAAW,oBAE/D,QAAQ,QAAQ,YAAY,QAAQ;KAGnC,QAAQ,UAAU;EACrB;EACA;KACG,SAAS;EAAoB,WAAW,QAAQ;;EAAS,UAAU,QAAQ;;;;;;;;;;;;;;;;;qBAiBnE,oBACX,UAAU,uBAAuB,8BACzB;WACC,QAAQ;WACR,UAAU;EAEnB,YAAY,QAAQ,OAAO,UAAU,SAAS,mBAAmB,QAAQ,QAAQ,QAAQ"}
1
+ {"version":3,"file":"error.d.cts","names":[],"sources":["../../src/auth/error.ts"],"mappings":"A,KAAK,WAAW;;KAEX;GAAgB;;;;;;;;;;;;;;;;iBAgBJ;;EAGf,2BAA2B;;EAE3B,qCAAqC;;EAErC,eAAe;;;;;EAKf,gBAAgB;;EAEhB,sBAAsB;;EAItB,kBAAkB;;EAElB;IAAkB;;;EAElB;IAAsB;;;EAEtB;IAAsB;;;EAEtB,iBAAiB;;;qBAIN;;;;;KAiBR,aACF,WAAW,wBAAwB,sBAAsB,WAAW,QAAQ,YACzE,sBAAsB;;YAKhB,6BAA6B;;KAGpC,SAAS,UAAU,wBAAwB,QAAQ,WAAW,oBAE/D,QAAQ,QAAQ,YAAY,QAAQ;KAGnC,QAAQ,UAAU;EACrB;EACA;KACG,SAAS;EAAoB,WAAW,QAAQ;;EAAS,UAAU,QAAQ;;;;;;;;;;;;;;;;;qBAiBnE,oBACX,UAAU,uBAAuB,8BACzB;WACC,QAAQ;WACR,UAAU;EAEnB,YAAY,QAAQ,OAAO,UAAU,SAAS,mBAAmB,QAAQ,QAAQ,QAAQ"}
@@ -22,9 +22,12 @@ export interface AuthenticationReasons {
22
22
  INVALID_VERIFICATION_CODE: NoMetadata;
23
23
  /** More than `verificationCode.maxAttempts` guesses at the code; it is discarded. */
24
24
  VERIFICATION_CODE_ATTEMPTS_EXCEEDED: NoMetadata;
25
- /** The id token carries no nonce and one is required (`oauth2.onetap.requireNonce`). */
25
+ /** The id token carries no nonce and the provider's flow requires one (`oauth2.nonce.optional`). */
26
26
  NONCE_MISSING: NoMetadata;
27
- /** The id token's nonce was not issued for this provider, or was used already. */
27
+ /**
28
+ * The id token's nonce is not the one this sign-in was started with: not issued for this
29
+ * provider, used already, or (redirect flow) not the one sent with the authorization request.
30
+ */
28
31
  NONCE_MISMATCH: NoMetadata;
29
32
  /** The desktop sign-in code is unknown, expired, used, or its verifier does not match. */
30
33
  INVALID_DESKTOP_CODE: NoMetadata;
@@ -1 +1 @@
1
- {"version":3,"file":"error.d.mts","names":[],"sources":["../../src/auth/error.ts"],"mappings":"A,KAAK,WAAW;;KAEX;GAAgB;;;;;;;;;;;;;;;;iBAgBJ;;EAGf,2BAA2B;;EAE3B,qCAAqC;;EAErC,eAAe;;EAEf,gBAAgB;;EAEhB,sBAAsB;;EAItB,kBAAkB;;EAElB;IAAkB;;;EAElB;IAAsB;;;EAEtB;IAAsB;;;EAEtB,iBAAiB;;;qBAIN;;;;;KAiBR,aACF,WAAW,wBAAwB,sBAAsB,WAAW,QAAQ,YACzE,sBAAsB;;YAKhB,6BAA6B;;KAGpC,SAAS,UAAU,wBAAwB,QAAQ,WAAW,oBAE/D,QAAQ,QAAQ,YAAY,QAAQ;KAGnC,QAAQ,UAAU;EACrB;EACA;KACG,SAAS;EAAoB,WAAW,QAAQ;;EAAS,UAAU,QAAQ;;;;;;;;;;;;;;;;;qBAiBnE,oBACX,UAAU,uBAAuB,8BACzB;WACC,QAAQ;WACR,UAAU;EAEnB,YAAY,QAAQ,OAAO,UAAU,SAAS,mBAAmB,QAAQ,QAAQ,QAAQ"}
1
+ {"version":3,"file":"error.d.mts","names":[],"sources":["../../src/auth/error.ts"],"mappings":"A,KAAK,WAAW;;KAEX;GAAgB;;;;;;;;;;;;;;;;iBAgBJ;;EAGf,2BAA2B;;EAE3B,qCAAqC;;EAErC,eAAe;;;;;EAKf,gBAAgB;;EAEhB,sBAAsB;;EAItB,kBAAkB;;EAElB;IAAkB;;;EAElB;IAAsB;;;EAEtB;IAAsB;;;EAEtB,iBAAiB;;;qBAIN;;;;;KAiBR,aACF,WAAW,wBAAwB,sBAAsB,WAAW,QAAQ,YACzE,sBAAsB;;YAKhB,6BAA6B;;KAGpC,SAAS,UAAU,wBAAwB,QAAQ,WAAW,oBAE/D,QAAQ,QAAQ,YAAY,QAAQ;KAGnC,QAAQ,UAAU;EACrB;EACA;KACG,SAAS;EAAoB,WAAW,QAAQ;;EAAS,UAAU,QAAQ;;;;;;;;;;;;;;;;;qBAiBnE,oBACX,UAAU,uBAAuB,8BACzB;WACC,QAAQ;WACR,UAAU;EAEnB,YAAY,QAAQ,OAAO,UAAU,SAAS,mBAAmB,QAAQ,QAAQ,QAAQ"}
@@ -1 +1 @@
1
- {"version":3,"file":"error.mjs","names":["given"],"sources":["../../src/auth/error.ts"],"sourcesContent":["type Metadata = Record<string, string>;\n/** A reason that carries no metadata. */\ntype NoMetadata = { [key: string]: never };\n\n/**\n * The reasons `onAuthorized` may refuse a sign-in with, each with the metadata it carries (string\n * fields only: metadata travels as URL parameters and JSON). The built-in ones cover the account\n * states every host meets; add your own by augmenting the interface, and `AuthenticationError`\n * accepts exactly these reasons, requiring the metadata when one of its fields is required:\n *\n * ```ts\n * declare module '@shware/security' {\n * interface AuthenticationReasons {\n * CLOSED_BETA: { invite?: string };\n * }\n * }\n * ```\n */\nexport interface AuthenticationReasons {\n // Thrown by the SDK itself.\n /** The emailed code is wrong, or none is pending for the address. */\n INVALID_VERIFICATION_CODE: NoMetadata;\n /** More than `verificationCode.maxAttempts` guesses at the code; it is discarded. */\n VERIFICATION_CODE_ATTEMPTS_EXCEEDED: NoMetadata;\n /** The id token carries no nonce and one is required (`oauth2.onetap.requireNonce`). */\n NONCE_MISSING: NoMetadata;\n /** The id token's nonce was not issued for this provider, or was used already. */\n NONCE_MISMATCH: NoMetadata;\n /** The desktop sign-in code is unknown, expired, used, or its verifier does not match. */\n INVALID_DESKTOP_CODE: NoMetadata;\n\n // For the host's `onAuthorized`.\n /** The account is disabled: banned, or closed by its owner. */\n ACCOUNT_DISABLED: NoMetadata;\n /** The account is locked for now; `until` is when it opens again, when known. */\n ACCOUNT_LOCKED: { until?: string };\n /** The address belongs to another account; `provider` is the one to sign in with instead. */\n EMAIL_ALREADY_USED: { provider?: string };\n /** The host accepts only verified addresses and this provider did not verify it. */\n EMAIL_NOT_VERIFIED: { provider?: string };\n /** No new accounts: registration is closed or by invitation. */\n SIGNUP_DISABLED: NoMetadata;\n}\n\n/** The built-in reasons, for a client's message table or a check that every reason is handled. */\nexport const AUTHENTICATION_REASONS = [\n 'INVALID_VERIFICATION_CODE',\n 'VERIFICATION_CODE_ATTEMPTS_EXCEEDED',\n 'NONCE_MISSING',\n 'NONCE_MISMATCH',\n 'INVALID_DESKTOP_CODE',\n 'ACCOUNT_DISABLED',\n 'ACCOUNT_LOCKED',\n 'EMAIL_ALREADY_USED',\n 'EMAIL_NOT_VERIFIED',\n 'SIGNUP_DISABLED',\n] as const satisfies readonly (keyof AuthenticationReasons)[];\n\n/**\n * Each reason's metadata as declared; a field that is not a string makes the reason unusable\n * (`never`).\n */\ntype Reasons = {\n [K in keyof AuthenticationReasons]: AuthenticationReasons[K] extends Partial<Metadata>\n ? AuthenticationReasons[K]\n : never;\n};\n\n/** A reason `onAuthorized` may refuse with: the keys of `AuthenticationReasons`. */\nexport type AuthenticationReason = keyof Reasons;\n\n/** `true` when the reason's metadata has no required field, so it may be left out. */\ntype Optional<R extends AuthenticationReason> = Reasons[R] extends NoMetadata\n ? true\n : Partial<Reasons[R]> extends Reasons[R]\n ? true\n : false;\ntype Options<R extends AuthenticationReason> = {\n message?: string;\n cause?: unknown;\n} & (Optional<R> extends true ? { metadata?: Reasons[R] } : { metadata: Reasons[R] });\n\n/**\n * Thrown by the host's `onAuthorized` to refuse a sign-in it could complete but will not: an\n * address another account holds, a banned user, a closed beta. `reason` is the code the client\n * branches on, `metadata` what it needs to act (the provider to sign in with instead); both\n * travel as they are, so keep them short and free of secrets. `Auth` answers a refusal itself,\n * in the shape of the route it came through:\n *\n * - redirect flow (`loginOAuth2Code`): `errorUri?error=access_denied&reason=<reason>&<metadata>`;\n * - JSON routes (native, One Tap, email, desktop): `403` with a google.rpc error body whose\n * `ErrorInfo` holds `reason` and `metadata`.\n *\n * The SDK throws it too, for a credential it checked itself (a wrong emailed code, a replayed\n * nonce), so a client handles both the same way. Anything else `onAuthorized` throws is a server\n * fault: `server_error` on the redirect, rethrown to the host's error handler on the JSON routes.\n */\nexport class AuthenticationError<\n R extends AuthenticationReason = AuthenticationReason,\n> extends Error {\n readonly reason: R;\n readonly metadata: Metadata;\n\n constructor(reason: R, ...[options]: Optional<R> extends true ? [Options<R>?] : [Options<R>]) {\n const given = options;\n const { message, cause, metadata = {} } = given ?? {};\n super(message ?? `Sign-in refused: ${reason}`, { cause });\n this.name = 'AuthenticationError';\n this.reason = reason;\n this.metadata = {};\n for (const [key, value] of Object.entries(metadata)) {\n if (typeof value === 'string') this.metadata[key] = value;\n }\n Object.setPrototypeOf(this, AuthenticationError.prototype);\n }\n}\n"],"mappings":";;AA6CA,MAAa,yBAAyB;CACpC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;;;;;;;;;;AAyCA,IAAa,sBAAb,MAAa,4BAEH,MAAM;CACd;CACA;CAEA,YAAY,QAAW,GAAG,CAAC,UAAmE;EAE5F,MAAM,EAAE,SAAS,OAAO,WAAW,CAAC,MAAMA,WAAS,CAAC;EACpD,MAAM,WAAW,oBAAoB,UAAU,EAAE,MAAM,CAAC;EACxD,KAAK,OAAO;EACZ,KAAK,SAAS;EACd,KAAK,WAAW,CAAC;EACjB,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,QAAQ,GAChD,IAAI,OAAO,UAAU,UAAU,KAAK,SAAS,OAAO;EAEtD,OAAO,eAAe,MAAM,oBAAoB,SAAS;CAC3D;AACF"}
1
+ {"version":3,"file":"error.mjs","names":["given"],"sources":["../../src/auth/error.ts"],"sourcesContent":["type Metadata = Record<string, string>;\n/** A reason that carries no metadata. */\ntype NoMetadata = { [key: string]: never };\n\n/**\n * The reasons `onAuthorized` may refuse a sign-in with, each with the metadata it carries (string\n * fields only: metadata travels as URL parameters and JSON). The built-in ones cover the account\n * states every host meets; add your own by augmenting the interface, and `AuthenticationError`\n * accepts exactly these reasons, requiring the metadata when one of its fields is required:\n *\n * ```ts\n * declare module '@shware/security' {\n * interface AuthenticationReasons {\n * CLOSED_BETA: { invite?: string };\n * }\n * }\n * ```\n */\nexport interface AuthenticationReasons {\n // Thrown by the SDK itself.\n /** The emailed code is wrong, or none is pending for the address. */\n INVALID_VERIFICATION_CODE: NoMetadata;\n /** More than `verificationCode.maxAttempts` guesses at the code; it is discarded. */\n VERIFICATION_CODE_ATTEMPTS_EXCEEDED: NoMetadata;\n /** The id token carries no nonce and the provider's flow requires one (`oauth2.nonce.optional`). */\n NONCE_MISSING: NoMetadata;\n /**\n * The id token's nonce is not the one this sign-in was started with: not issued for this\n * provider, used already, or (redirect flow) not the one sent with the authorization request.\n */\n NONCE_MISMATCH: NoMetadata;\n /** The desktop sign-in code is unknown, expired, used, or its verifier does not match. */\n INVALID_DESKTOP_CODE: NoMetadata;\n\n // For the host's `onAuthorized`.\n /** The account is disabled: banned, or closed by its owner. */\n ACCOUNT_DISABLED: NoMetadata;\n /** The account is locked for now; `until` is when it opens again, when known. */\n ACCOUNT_LOCKED: { until?: string };\n /** The address belongs to another account; `provider` is the one to sign in with instead. */\n EMAIL_ALREADY_USED: { provider?: string };\n /** The host accepts only verified addresses and this provider did not verify it. */\n EMAIL_NOT_VERIFIED: { provider?: string };\n /** No new accounts: registration is closed or by invitation. */\n SIGNUP_DISABLED: NoMetadata;\n}\n\n/** The built-in reasons, for a client's message table or a check that every reason is handled. */\nexport const AUTHENTICATION_REASONS = [\n 'INVALID_VERIFICATION_CODE',\n 'VERIFICATION_CODE_ATTEMPTS_EXCEEDED',\n 'NONCE_MISSING',\n 'NONCE_MISMATCH',\n 'INVALID_DESKTOP_CODE',\n 'ACCOUNT_DISABLED',\n 'ACCOUNT_LOCKED',\n 'EMAIL_ALREADY_USED',\n 'EMAIL_NOT_VERIFIED',\n 'SIGNUP_DISABLED',\n] as const satisfies readonly (keyof AuthenticationReasons)[];\n\n/**\n * Each reason's metadata as declared; a field that is not a string makes the reason unusable\n * (`never`).\n */\ntype Reasons = {\n [K in keyof AuthenticationReasons]: AuthenticationReasons[K] extends Partial<Metadata>\n ? AuthenticationReasons[K]\n : never;\n};\n\n/** A reason `onAuthorized` may refuse with: the keys of `AuthenticationReasons`. */\nexport type AuthenticationReason = keyof Reasons;\n\n/** `true` when the reason's metadata has no required field, so it may be left out. */\ntype Optional<R extends AuthenticationReason> = Reasons[R] extends NoMetadata\n ? true\n : Partial<Reasons[R]> extends Reasons[R]\n ? true\n : false;\ntype Options<R extends AuthenticationReason> = {\n message?: string;\n cause?: unknown;\n} & (Optional<R> extends true ? { metadata?: Reasons[R] } : { metadata: Reasons[R] });\n\n/**\n * Thrown by the host's `onAuthorized` to refuse a sign-in it could complete but will not: an\n * address another account holds, a banned user, a closed beta. `reason` is the code the client\n * branches on, `metadata` what it needs to act (the provider to sign in with instead); both\n * travel as they are, so keep them short and free of secrets. `Auth` answers a refusal itself,\n * in the shape of the route it came through:\n *\n * - redirect flow (`loginOAuth2Code`): `errorUri?error=access_denied&reason=<reason>&<metadata>`;\n * - JSON routes (native, One Tap, email, desktop): `403` with a google.rpc error body whose\n * `ErrorInfo` holds `reason` and `metadata`.\n *\n * The SDK throws it too, for a credential it checked itself (a wrong emailed code, a replayed\n * nonce), so a client handles both the same way. Anything else `onAuthorized` throws is a server\n * fault: `server_error` on the redirect, rethrown to the host's error handler on the JSON routes.\n */\nexport class AuthenticationError<\n R extends AuthenticationReason = AuthenticationReason,\n> extends Error {\n readonly reason: R;\n readonly metadata: Metadata;\n\n constructor(reason: R, ...[options]: Optional<R> extends true ? [Options<R>?] : [Options<R>]) {\n const given = options;\n const { message, cause, metadata = {} } = given ?? {};\n super(message ?? `Sign-in refused: ${reason}`, { cause });\n this.name = 'AuthenticationError';\n this.reason = reason;\n this.metadata = {};\n for (const [key, value] of Object.entries(metadata)) {\n if (typeof value === 'string') this.metadata[key] = value;\n }\n Object.setPrototypeOf(this, AuthenticationError.prototype);\n }\n}\n"],"mappings":";;AAgDA,MAAa,yBAAyB;CACpC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;;;;;;;;;;AAyCA,IAAa,sBAAb,MAAa,4BAEH,MAAM;CACd;CACA;CAEA,YAAY,QAAW,GAAG,CAAC,UAAmE;EAE5F,MAAM,EAAE,SAAS,OAAO,WAAW,CAAC,MAAMA,WAAS,CAAC;EACpD,MAAM,WAAW,oBAAoB,UAAU,EAAE,MAAM,CAAC;EACxD,KAAK,OAAO;EACZ,KAAK,SAAS;EACd,KAAK,WAAW,CAAC;EACjB,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,QAAQ,GAChD,IAAI,OAAO,UAAU,UAAU,KAAK,SAAS,OAAO;EAEtD,OAAO,eAAe,MAAM,oBAAoB,SAAS;CAC3D;AACF"}
@@ -94,7 +94,8 @@ var Auth = class {
94
94
  emailCodes;
95
95
  desktopCodes;
96
96
  oauth2Client;
97
- onetapRequireNonce;
97
+ /** Provider keys whose logins may come without a nonce (`oauth2.nonce.optional`). */
98
+ nonceOptional;
98
99
  touchInterval;
99
100
  sessionHeader;
100
101
  ATTR_OAUTH2_AUTHORIZATION_REQUEST = "oauth2AuthorizationRequest";
@@ -122,7 +123,7 @@ var Auth = class {
122
123
  ...cookieOptions
123
124
  };
124
125
  this.oauth2Client = oauth2?.client ? new require_oauth2_client.OAuth2Client(oauth2.client) : null;
125
- this.onetapRequireNonce = oauth2?.onetap?.requireNonce ?? true;
126
+ this.nonceOptional = new Set(oauth2?.nonce?.optional);
126
127
  this.touchInterval = (session?.touchInterval ?? 3600) * 1e3;
127
128
  this.sessionHeader = session?.header ?? false;
128
129
  (0, _shware_utils.invariant)(this.touchInterval >= 0, "session.touchInterval must not be negative");
@@ -211,10 +212,20 @@ var Auth = class {
211
212
  });
212
213
  return response;
213
214
  };
214
- logout = async (request) => {
215
+ logout = async (request, options) => {
216
+ const scope = options?.scope ?? "local";
215
217
  const sessionId = this.getSessionId(request);
216
- if (sessionId) await this.repository.deleteById(sessionId);
218
+ if (scope !== "local" && sessionId) {
219
+ const session = await this.repository.findById(sessionId);
220
+ const principal = session && this.principalOf(session);
221
+ if (principal) {
222
+ const sessions = await this.repository.findByPrincipalName(principal.name);
223
+ for (const id of sessions.keys()) if (id !== sessionId) await this.repository.deleteById(id);
224
+ }
225
+ }
217
226
  const response = Response.json({});
227
+ if (scope === "others") return response;
228
+ if (sessionId) await this.repository.deleteById(sessionId);
218
229
  require_utils_http.deleteCookie(response, this.cookieName, this.cookieOptions);
219
230
  return response;
220
231
  };
@@ -251,6 +262,22 @@ var Auth = class {
251
262
  if (await this.kv.getItem(key) !== provider) throw new require_auth_error.AuthenticationError("NONCE_MISMATCH");
252
263
  await this.kv.removeItem(key);
253
264
  }
265
+ /**
266
+ * The nonce check of the JSON logins (One Tap, native), where the client obtained the id token
267
+ * and the nonce came from `oauth2Nonce`: spends the one the token carries, and refuses a token
268
+ * without one when the provider's flow echoes nonces (`required`) and the host has not listed the
269
+ * provider as optional. An id token is replayable until it expires; the nonce makes it sign in
270
+ * once.
271
+ */
272
+ async checkIssuedNonce(userInfo, provider, required) {
273
+ const { nonce } = userInfo.data;
274
+ if (typeof nonce === "string" && nonce) {
275
+ await this.consumeNonce(nonce, provider);
276
+ return true;
277
+ }
278
+ if (required && !this.nonceOptional.has(provider)) throw new require_auth_error.AuthenticationError("NONCE_MISSING");
279
+ return false;
280
+ }
254
281
  oauth2State = async (request) => {
255
282
  const { provider } = require_utils_http.param(request, PATH.OAUTH2_STATE);
256
283
  const state = (0, node_crypto.randomUUID)();
@@ -270,10 +297,12 @@ var Auth = class {
270
297
  const { provider } = require_utils_http.param(request, PATH.OAUTH2_AUTHORIZATION);
271
298
  const state = (0, node_crypto.randomUUID)();
272
299
  const pkce = this.createPkceParameters();
300
+ const nonce = (await this.oauth2Client.nonceSupport(provider)).web ? (0, node_crypto.randomUUID)() : void 0;
273
301
  const uri = await this.oauth2Client.createAuthorizationUri({
274
302
  provider,
275
303
  state,
276
- pkce
304
+ pkce,
305
+ nonce
277
306
  });
278
307
  let session = await this.loadSession(request);
279
308
  if (!session) {
@@ -286,6 +315,7 @@ var Auth = class {
286
315
  provider,
287
316
  authorizationRequestUri: uri.href,
288
317
  additionalParameters: pkce,
318
+ ...nonce ? { nonce } : {},
289
319
  ...attributes ? { attributes } : {}
290
320
  };
291
321
  session.setAttribute(this.ATTR_OAUTH2_AUTHORIZATION_REQUEST, JSON.stringify(authorizationRequest));
@@ -334,6 +364,12 @@ var Auth = class {
334
364
  response: user ? { user } : void 0
335
365
  });
336
366
  mark("exchange_code");
367
+ if (cached.nonce && token.id_token) {
368
+ const { nonce } = userInfo.data;
369
+ if (typeof nonce !== "string" || !nonce) throw new require_auth_error.AuthenticationError("NONCE_MISSING");
370
+ if (nonce !== cached.nonce) throw new require_auth_error.AuthenticationError("NONCE_MISMATCH");
371
+ mark("check_nonce");
372
+ }
337
373
  const principal = await handler(request, {
338
374
  provider,
339
375
  clientId,
@@ -390,11 +426,8 @@ var Auth = class {
390
426
  credentials
391
427
  });
392
428
  mark("login_oauth2_native");
393
- const { nonce } = userInfo.data;
394
- if (typeof nonce === "string" && nonce) {
395
- await this.consumeNonce(nonce, provider);
396
- mark("check_nonce");
397
- }
429
+ const required = (await this.oauth2Client.nonceSupport(provider)).native && !!token.id_token;
430
+ if (await this.checkIssuedNonce(userInfo, provider, required)) mark("check_nonce");
398
431
  return this.authorize(request, handler, {
399
432
  provider,
400
433
  clientId,
@@ -417,11 +450,8 @@ var Auth = class {
417
450
  credential: parsed.credential
418
451
  }));
419
452
  mark("verify_credential");
420
- const { nonce } = userInfo.data;
421
- if (typeof nonce === "string" && nonce) {
422
- await this.consumeNonce(nonce, provider);
423
- mark("check_nonce");
424
- } else if (this.onetapRequireNonce) throw new require_auth_error.AuthenticationError("NONCE_MISSING");
453
+ const required = (await this.oauth2Client.nonceSupport(provider)).web;
454
+ if (await this.checkIssuedNonce(userInfo, provider, required)) mark("check_nonce");
425
455
  } else if (parsed.code) {
426
456
  ({clientId, token} = await this.oauth2Client.exchangeAuthorizationCode({
427
457
  provider,
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["isKnownOAuth2ErrorType","attributesSize","MAX_ATTRIBUTES_BYTES","extend","googleOneTapSchema","attributesSchema","object","string","regex","literal","EmailVerificationCodes","DesktopCodes","OAuth2Client","getCookie","PRINCIPAL_NAME_INDEX_NAME","errorResponse","randomUUID","randomBytes","createHash","AuthenticationError","param","timing","query","oauth2RedirectQuerySchema","OAuth2Error","readJson","bodyAttributes","invalidArgument","readForm","parse","sendEmailVerificationCodeSchema","verifyTurnstileToken","loginEmailSchema","unauthenticated"],"sources":["../../src/auth/index.ts"],"sourcesContent":["import { createHash, randomBytes, randomUUID } from 'node:crypto';\nimport { invariant } from '@shware/utils';\nimport { extend, literal, object, regex, string } from 'zod/mini';\nimport type { Principal } from '../core/index';\nimport { loginEmailSchema, sendEmailVerificationCodeSchema } from '../email/schema';\nimport { OAuth2Client, googleOneTapSchema, oauth2RedirectQuerySchema } from '../oauth2/client';\nimport { OAuth2Error, type OAuth2ErrorType, isKnownOAuth2ErrorType } from '../oauth2/error';\nimport type {\n NativeCredential,\n OAuth2AuthorizationRequest,\n PkceParameters,\n StandardClaims,\n} from '../oauth2/types';\nimport { PRINCIPAL_NAME_INDEX_NAME } from '../session/common';\nimport type { KVRepository, Session, SessionRepository } from '../session/types';\nimport {\n type CookieOptions,\n deleteCookie,\n getCookie,\n param,\n query,\n setCookie,\n} from '../utils/http';\nimport { timing } from '../utils/timing';\nimport { parse, readForm, readJson, verifyTurnstileToken } from '../utils/valid';\nimport {\n MAX_ATTRIBUTES_BYTES,\n attributesSchema,\n attributesSize,\n bodyAttributes,\n} from './attributes';\nimport { DesktopCodes } from './desktop-codes';\nimport { type EmailSender, EmailVerificationCodes } from './email-codes';\nimport { AuthenticationError } from './error';\nimport { errorResponse, invalidArgument, unauthenticated } from './respond';\nimport type {\n AuthConfig,\n AuthService,\n Authorization,\n AuthorizedHandler,\n LoggedHandler,\n OAuth2AuthorizationOptions,\n} from './types';\n\n// PKCE per RFC 7636: code_verifier / code_challenge are 43-128 chars from\n// the unreserved set. We restrict to base64url (drops \".\" and \"~\") since\n// that's what S256 produces and what callers should be sending; rejecting\n// the rest shrinks the accepted input shape without losing legit clients.\n// A 32-byte random verifier base64url-encodes to exactly 43 chars.\nconst PKCE_FORMAT = /^[A-Za-z0-9_-]{43,128}$/;\n\n// A native app's `code_verifier` goes on to the provider, which checks it against the challenge\n// the app sent: accept the whole RFC 7636 unreserved set here, as the provider does.\nconst CODE_VERIFIER_FORMAT = /^[A-Za-z0-9._~-]{43,128}$/;\n\n/** The header a session id travels in besides the cookie, with `session.header` on. */\nconst SESSION_HEADER = 'X-Auth-Token';\n\n/** Seconds an OAuth2 state or nonce may be used within. */\nconst OAUTH2_PARAMETER_TTL = 10 * 60;\n\n// error_description forwarded to errorUri comes from the provider or an error message: cap it so\n// the redirect URL stays short and an attacker-crafted callback cannot stuff the page with text.\nconst MAX_ERROR_DESCRIPTION_LENGTH = 256;\n\n/** An error code safe to put on errorUri: a registered one as is, anything else as `fallback`. */\nfunction safeErrorType(error: string, fallback: OAuth2ErrorType): OAuth2ErrorType {\n return isKnownOAuth2ErrorType(error) ? error : fallback;\n}\n\n/**\n * The codes a failure past validation keeps on errorUri, each one the user can act on: the code\n * expired or was used (start again), they declined, or the provider is briefly down. Every other\n * failure there (a rejected client, a user info request that failed) is the app's or the\n * provider's problem, which the user sees as `server_error`.\n */\nconst CALLBACK_ERROR_TYPES: ReadonlySet<OAuth2ErrorType> = new Set([\n 'invalid_grant',\n 'access_denied',\n 'temporarily_unavailable',\n]);\n\nfunction authorizationAttributes(\n attributes: OAuth2AuthorizationOptions['attributes']\n): Record<string, string> | undefined {\n if (!attributes) return undefined;\n const defined: Record<string, string> = {};\n for (const [key, value] of Object.entries(attributes)) {\n if (value !== undefined) defined[key] = value;\n }\n if (Object.keys(defined).length === 0) return undefined;\n // The host's own values, written with the session: oversized is a bug in the host, not a 400.\n const size = attributesSize(defined);\n invariant(\n size <= MAX_ATTRIBUTES_BYTES,\n `oauth2 authorization attributes are ${size} bytes, at most ${MAX_ATTRIBUTES_BYTES} allowed`\n );\n return defined;\n}\n\n/** Sign in with Apple answers with `response_mode=form_post`; a charset parameter may follow. */\nfunction isFormPost(request: Request) {\n const contentType = request.headers.get('content-type')?.toLowerCase();\n return (\n request.method === 'POST' && !!contentType?.startsWith('application/x-www-form-urlencoded')\n );\n}\n\n/** Google's own form post carries no attributes; an app posting JSON may add them. */\nconst oneTapBodySchema = extend(googleOneTapSchema, { attributes: attributesSchema });\n\nconst desktopAuthorizeSchema = object({\n code_challenge: string().check(regex(PKCE_FORMAT)),\n code_challenge_method: literal('S256'),\n});\n\nconst desktopExchangeSchema = object({\n code: string(),\n code_verifier: string().check(regex(PKCE_FORMAT)),\n});\n\nexport const PATH = {\n CSRF: '/csrf',\n LOGOUT: '/logout',\n LOGGED: '/logged',\n\n OAUTH2_STATE: '/oauth2/state/:provider',\n OAUTH2_NONCE: '/oauth2/nonce/:provider',\n OAUTH2_AUTHORIZATION: '/oauth2/authorization/:provider',\n LOGIN_OAUTH2_CODE: '/login/oauth2/code/:provider',\n LOGIN_OAUTH2_NATIVE: '/login/oauth2/native/:provider',\n LOGIN_OAUTH2_ONETAP: '/login/oauth2/onetap/google',\n\n LOGIN_EMAIL: '/login/email',\n SEND_EMAIL_VERIFICATION_CODE: '/auth/sendEmailVerificationCode',\n\n // Desktop / native app sign-in via web loopback (RFC 8252 + OAuth 2.1 Auth Code Flow):\n // 1. user already authenticated with cookie session → POST DESKTOP_AUTHORIZE → { code }\n // 2. web redirects to desktop's loopback callback with the code\n // 3. desktop renderer POSTs DESKTOP_EXCHANGE with the code → server returns\n // Set-Cookie carrying a fresh session, single-use code is invalidated\n // The two-step flow keeps the actual session id off the redirect URL — only a\n // 5-minute single-use code transits via the loopback.\n DESKTOP_AUTHORIZE: '/auth/desktop/authorize',\n DESKTOP_EXCHANGE: '/auth/desktop/exchange',\n\n CLEANUP_EXPIRED_SESSIONS: '/sessions/expired/cleanup',\n} as const;\n\n/**\n * The login routes and session helpers. Every route is one straight line: read and validate the\n * request, check the credential, call the host's `onAuthorized`, sign in. Failures are thrown and\n * answered in one place per kind of route: a JSON route runs under `guard`, which maps a\n * `RequestError`, an `AuthenticationError` or an `OAuth2Error` to its google.rpc body (see\n * `respond.ts`); the redirect callback maps the same errors to `errorUri` parameters (`redirect`).\n */\nexport class Auth implements AuthService {\n private readonly timing: boolean;\n private readonly cookieName;\n private readonly cookieOptions: CookieOptions;\n private readonly kv: KVRepository;\n private readonly repository: SessionRepository;\n private readonly turnstileSecretKey?: string;\n private readonly emailCodes: EmailVerificationCodes;\n private readonly desktopCodes: DesktopCodes;\n private readonly oauth2Client: OAuth2Client | null;\n private readonly onetapRequireNonce: boolean;\n private readonly touchInterval: number;\n private readonly sessionHeader: boolean;\n private readonly ATTR_OAUTH2_AUTHORIZATION_REQUEST = 'oauth2AuthorizationRequest';\n\n constructor({\n sessionRepository,\n kvRepository,\n turnstileSecretKey,\n verificationCode,\n oauth2,\n cookie,\n session,\n timing,\n }: AuthConfig) {\n this.timing = timing ?? false;\n this.kv = kvRepository;\n this.repository = sessionRepository;\n this.turnstileSecretKey = turnstileSecretKey;\n const maxAttempts = verificationCode?.maxAttempts ?? 5;\n const resendCooldown = verificationCode?.resendCooldown ?? 60;\n invariant(maxAttempts >= 1, 'verificationCode.maxAttempts must be at least 1');\n invariant(resendCooldown >= 1, 'verificationCode.resendCooldown must be at least 1 second');\n this.emailCodes = new EmailVerificationCodes(kvRepository, { maxAttempts, resendCooldown });\n this.desktopCodes = new DesktopCodes(kvRepository);\n const { name, ...cookieOptions } = cookie ?? {};\n this.cookieName = name ?? 'SESSION';\n this.cookieOptions = {\n path: '/',\n sameSite: 'none',\n secure: true,\n httpOnly: true,\n ...cookieOptions,\n };\n this.oauth2Client = oauth2?.client ? new OAuth2Client(oauth2.client) : null;\n this.onetapRequireNonce = oauth2?.onetap?.requireNonce ?? true;\n this.touchInterval = (session?.touchInterval ?? 3600) * 1000;\n this.sessionHeader = session?.header ?? false;\n invariant(this.touchInterval >= 0, 'session.touchInterval must not be negative');\n }\n\n // ---- sessions and responses ------------------------------------------------------------------\n\n private getSessionId(request: Request): string | undefined {\n const fromCookie = getCookie(request, this.cookieName);\n if (fromCookie) return fromCookie;\n return (this.sessionHeader && request.headers.get(SESSION_HEADER)) || undefined;\n }\n\n /** The session the request carries, if it exists. */\n private async loadSession(request: Request): Promise<Session | null> {\n const sessionId = this.getSessionId(request);\n return sessionId ? this.repository.findById(sessionId) : null;\n }\n\n /** The signed-in principal of a session, if any. */\n private principalOf(session: Session): Principal | null {\n const name = session.getAttribute(PRINCIPAL_NAME_INDEX_NAME);\n return name ? { name: String(name) } : null;\n }\n\n /**\n * A new session signed in as `principal`. With `carryOver`, what the host kept in the pre-login\n * session moves to the new one; the authorization request (state, PKCE verifier, flow\n * attributes) is single-use and was consumed, and a principal left there from an earlier\n * sign-in is replaced. The new id is never the one the browser brought, which may have been\n * planted by an attacker who started the flow (session fixation).\n */\n private async signIn(principal: Principal, carryOver?: Session): Promise<Session> {\n const session = this.repository.createSession();\n for (const attribute of carryOver?.getAttributeNames() ?? []) {\n if (attribute === this.ATTR_OAUTH2_AUTHORIZATION_REQUEST) continue;\n if (attribute === PRINCIPAL_NAME_INDEX_NAME) continue;\n const value = carryOver?.getAttribute(attribute);\n if (value !== null && value !== undefined) session.setAttribute(attribute, value);\n }\n session.setAttribute(PRINCIPAL_NAME_INDEX_NAME, principal.name);\n await this.repository.save(session);\n return session;\n }\n\n /**\n * `response` carrying `session`: its cookie, renewed for the whole inactive interval, and with\n * `session.header` on, the `X-Auth-Token` header a client without a cookie jar reads.\n */\n private withSession(response: Response, session: Session, cookie?: CookieOptions): Response {\n const maxAge = session.getMaxInactiveInterval();\n setCookie(response, this.cookieName, session.getId(), {\n ...this.cookieOptions,\n ...cookie,\n maxAge,\n });\n if (this.sessionHeader) response.headers.set(SESSION_HEADER, session.getId());\n return response;\n }\n\n /** Runs a JSON route: a failure it knows is its response, anything else is the host's. */\n private async guard(run: () => Promise<Response>): Promise<Response> {\n try {\n return await run();\n } catch (error) {\n const response = errorResponse(error);\n if (response) return response;\n throw error;\n }\n }\n\n /** The error redirect of the callback flow; `refusal`'s reason and metadata ride along. */\n private redirect(\n error: OAuth2ErrorType,\n description?: string,\n refusal?: AuthenticationError\n ): Response {\n invariant(this.oauth2Client, 'oauth2Client is not initialized');\n const uri = new URL(this.oauth2Client.errorUri);\n // Metadata never replaces a parameter: not one errorUri carries itself, nor one set below.\n for (const [key, value] of Object.entries(refusal?.metadata ?? {})) {\n if (!uri.searchParams.has(key)) uri.searchParams.set(key, value);\n }\n uri.searchParams.set('error', error);\n if (description) {\n uri.searchParams.set('error_description', description.slice(0, MAX_ERROR_DESCRIPTION_LENGTH));\n }\n if (refusal) uri.searchParams.set('reason', refusal.reason);\n return Response.redirect(uri.href, 302);\n }\n\n // ---- basic -----------------------------------------------------------------------------------\n\n csrf = async (_request: Request): Promise<Response> => {\n const token = randomUUID();\n const response = Response.json({\n token,\n parameterName: '_csrf',\n headerName: 'X-XSRF-TOKEN',\n });\n\n // Double Submit Cookie Protection\n setCookie(response, 'XSRF-TOKEN', token, {\n path: '/',\n secure: true,\n httpOnly: false,\n sameSite: 'none',\n domain: this.cookieOptions.domain,\n });\n return response;\n };\n\n logout = async (request: Request): Promise<Response> => {\n const sessionId = this.getSessionId(request);\n if (sessionId) await this.repository.deleteById(sessionId);\n const response = Response.json({});\n // A Set-Cookie only replaces the stored cookie when Domain and Path match (RFC 6265),\n // so clear it with the same attributes it was set with.\n deleteCookie(response, this.cookieName, this.cookieOptions);\n return response;\n };\n\n logged = async (request: Request, onLogged?: LoggedHandler): Promise<Response> => {\n const session = await this.loadSession(request);\n if (!session) return Response.json({ data: false });\n\n session.setLastAccessedTime(Date.now());\n await this.repository.save(session);\n\n const principal = this.principalOf(session);\n if (principal) await onLogged?.(principal);\n return this.withSession(Response.json({ data: principal !== null }), session);\n };\n\n // ---- oauth2 ----------------------------------------------------------------------------------\n\n private createPkceParameters(): PkceParameters {\n // 32 random bytes: a 43-char base64url verifier, the RFC 7636 minimum (a UUID is 36).\n const code_verifier = randomBytes(32).toString('base64url');\n const code_challenge = createHash('sha256')\n .update(code_verifier)\n .digest()\n .toString('base64url');\n\n return { code_verifier, code_challenge, code_challenge_method: 'S256' };\n }\n\n private getOauth2StateKey(state: string) {\n return `oauth2:state:${state}`;\n }\n\n private getOauth2NonceKey(nonce: string) {\n return `oauth2:nonce:${nonce}`;\n }\n\n /**\n * Spends a nonce `oauth2Nonce` issued for `provider`: `NONCE_MISMATCH` for one that was not,\n * or was used already. An id token is replayable until it expires; the nonce it carries makes\n * it sign in once.\n */\n private async consumeNonce(nonce: string, provider: string): Promise<void> {\n const key = this.getOauth2NonceKey(nonce);\n if ((await this.kv.getItem(key)) !== provider) throw new AuthenticationError('NONCE_MISMATCH');\n await this.kv.removeItem(key);\n }\n\n oauth2State = async (request: Request): Promise<Response> => {\n const { provider } = param(request, PATH.OAUTH2_STATE);\n const state = randomUUID();\n await this.kv.setItem(this.getOauth2StateKey(state), provider, OAUTH2_PARAMETER_TTL);\n return Response.json({ state });\n };\n\n oauth2Nonce = async (request: Request): Promise<Response> => {\n const { provider } = param(request, PATH.OAUTH2_NONCE);\n const nonce = randomUUID();\n await this.kv.setItem(this.getOauth2NonceKey(nonce), provider, OAUTH2_PARAMETER_TTL);\n return Response.json({ nonce });\n };\n\n oauth2Authorization = (\n request: Request,\n options?: OAuth2AuthorizationOptions\n ): Promise<Response> =>\n this.guard(async () => {\n invariant(this.oauth2Client, 'oauth2Client is not initialized');\n const attributes = authorizationAttributes(options?.attributes);\n const { mark, setTiming } = timing({ enabled: this.timing });\n const { provider } = param(request, PATH.OAUTH2_AUTHORIZATION);\n const state = randomUUID();\n const pkce = this.createPkceParameters();\n const uri = await this.oauth2Client.createAuthorizationUri({ provider, state, pkce });\n let session = await this.loadSession(request);\n if (!session) {\n // A session made for the flow only has to outlive the state: an abandoned flow must not\n // keep a row for the default interval. Sign-in moves to a new session, with the default.\n session = this.repository.createSession();\n session.setMaxInactiveInterval(OAUTH2_PARAMETER_TTL);\n }\n mark('fetch_session');\n\n const authorizationRequest: OAuth2AuthorizationRequest = {\n state,\n provider,\n authorizationRequestUri: uri.href,\n additionalParameters: pkce,\n ...(attributes ? { attributes } : {}),\n };\n session.setAttribute(\n this.ATTR_OAUTH2_AUTHORIZATION_REQUEST,\n JSON.stringify(authorizationRequest)\n );\n await this.repository.save(session);\n mark('save_session');\n\n const response = new Response(null, { status: 302, headers: { location: uri.href } });\n setTiming(response);\n return this.withSession(response, session);\n });\n\n loginOAuth2Code = async (request: Request, handler: AuthorizedHandler): Promise<Response> => {\n invariant(this.oauth2Client, 'oauth2Client is not initialized');\n const { mark, setTiming } = timing({ enabled: this.timing });\n\n // 1. the session the flow started on, and the authorization request it stored\n const session = await this.loadSession(request);\n if (!session) return this.redirect('invalid_request', 'session not found');\n mark('load_session');\n const json = session.getAttribute(this.ATTR_OAUTH2_AUTHORIZATION_REQUEST) as string | null;\n if (!json) return this.redirect('invalid_request', 'authorization request not found');\n const cached: OAuth2AuthorizationRequest = JSON.parse(json);\n\n // 2. the provider's answer: query, or a form for Apple's response_mode=form_post\n const { provider } = param(request, PATH.LOGIN_OAUTH2_CODE);\n const data = isFormPost(request)\n ? Object.fromEntries(new URLSearchParams(await request.text()))\n : query(request);\n const parsed = oauth2RedirectQuerySchema.safeParse(data);\n if (!parsed.success) return this.redirect('invalid_request', 'invalid redirect query');\n // The provider answered with an error instead of a code (the user pressed Cancel →\n // access_denied, invalid_scope, server_error, ...). Forward it rather than reporting a\n // malformed query. This runs before the state check on purpose: providers echo state on\n // error responses, but not all reliably do, and a forged error callback can only make the\n // victim's popup show an error — nothing is exchanged or signed in. A present state that does\n // not match still wins, since that is the more accurate (and more alarming) diagnosis.\n if (parsed.data.error) {\n if (parsed.data.state && parsed.data.state !== cached.state) {\n return this.redirect('invalid_request', 'redirect state mismatch');\n }\n return this.redirect(\n safeErrorType(parsed.data.error, 'server_error'),\n parsed.data.error_description\n );\n }\n const { code, state, user } = parsed.data;\n if (!code || !state) return this.redirect('invalid_request', 'invalid redirect query');\n if (state !== cached.state) return this.redirect('invalid_request', 'redirect state mismatch');\n if (provider !== cached.provider) {\n return this.redirect('invalid_request', 'redirect provider mismatch');\n }\n mark('validate_session');\n\n // 3. exchange the code, load the user, sign in. Everything here can fail (an expired or reused\n // code, a network error, the host's handler or session store). The callback runs in a popup\n // the user is looking at, so every failure must land on errorUri, never as a JSON error.\n let signedIn: Session;\n try {\n const { clientId, token } = await this.oauth2Client.exchangeAuthorizationCode({\n provider,\n code,\n pkce: cached.additionalParameters,\n });\n // Apple posts the user's name alongside the code, once: hand it to the provider with the token.\n const userInfo = await this.oauth2Client.getUserInfo({\n provider,\n clientId,\n token,\n response: user ? { user } : undefined,\n });\n mark('exchange_code');\n\n const principal = await handler(request, {\n provider,\n clientId,\n userInfo,\n token,\n attributes: cached.attributes ?? {},\n });\n mark('save_principal');\n\n signedIn = await this.signIn(principal, session);\n await this.repository.deleteById(session.getId());\n mark('update_session');\n } catch (error) {\n // The details stay in the logs: an OAuth2Error message can carry a client id or a\n // provider's response, which has no place in a URL the browser keeps in its history.\n if (error instanceof OAuth2Error) {\n console.warn('OAuth2 callback failed', error);\n const type = CALLBACK_ERROR_TYPES.has(error.error) ? error.error : 'server_error';\n return this.redirect(type);\n }\n // A refusal is something the user can act on, so its reason and metadata reach the page,\n // as they reach a JSON client through the ErrorInfo.\n if (error instanceof AuthenticationError) {\n console.warn('OAuth2 sign-in refused', error.reason, error.metadata);\n return this.redirect('access_denied', undefined, error);\n }\n console.error('OAuth2 callback failed', error);\n return this.redirect('server_error');\n }\n\n const uri = new URL(this.oauth2Client.successUri);\n uri.searchParams.set('status', 'success');\n uri.searchParams.set('provider', provider);\n const response = new Response(null, { status: 302, headers: { location: uri.href } });\n setTiming(response);\n return this.withSession(response, signedIn);\n };\n\n /** The shared tail of the JSON login routes: the host's handler, then a signed-in session. */\n private async authorize(\n request: Request,\n handler: AuthorizedHandler,\n authorization: Authorization,\n setTiming: (response: Response) => void\n ): Promise<Response> {\n const principal = await handler(request, authorization);\n const session = await this.signIn(principal);\n const response = Response.json(principal);\n setTiming(response);\n return this.withSession(response, session);\n }\n\n loginOAuth2Native = (request: Request, handler: AuthorizedHandler): Promise<Response> =>\n this.guard(async () => {\n invariant(this.oauth2Client, 'oauth2Client is not initialized');\n const { mark, setTiming } = timing({ enabled: this.timing });\n const { provider } = param(request, PATH.LOGIN_OAUTH2_NATIVE);\n const body = await readJson(request);\n // Whatever the app sends besides its credentials for `onAuthorized` (a referral code, ...).\n const attributes = bodyAttributes(body);\n // Only the credentials go on to the provider client.\n const { attributes: _, ...credentials } = body as NativeCredential & { attributes?: unknown };\n const { code_verifier } = credentials as { code_verifier?: unknown };\n if (\n code_verifier !== undefined &&\n (typeof code_verifier !== 'string' || !CODE_VERIFIER_FORMAT.test(code_verifier))\n ) {\n throw invalidArgument(\n 'INVALID_CODE_VERIFIER',\n 'code_verifier must be 43-128 characters from [A-Za-z0-9-._~]'\n );\n }\n const { clientId, userInfo, token } = await this.oauth2Client.loginOAuth2Native({\n provider,\n credentials,\n });\n mark('login_oauth2_native');\n\n const { nonce } = userInfo.data as { nonce?: unknown };\n if (typeof nonce === 'string' && nonce) {\n await this.consumeNonce(nonce, provider);\n mark('check_nonce');\n }\n\n return this.authorize(\n request,\n handler,\n { provider, clientId, userInfo, token, attributes },\n setTiming\n );\n });\n\n loginOAuth2Onetap = (\n request: Request,\n handler: AuthorizedHandler,\n provider = 'google'\n ): Promise<Response> =>\n this.guard(async () => {\n invariant(this.oauth2Client, 'oauth2Client is not initialized');\n const { mark, setTiming } = timing({ enabled: this.timing });\n\n // Google's own form post, or an app's JSON.\n const contentType = request.headers.get('content-type') ?? '';\n const body = contentType.includes('application/json')\n ? await readJson(request)\n : await readForm(request);\n const { attributes = {}, ...parsed } = parse(oneTapBodySchema, body);\n\n // Both the credential and the code are issued to the provider's web client.\n let clientId: string;\n let token: Authorization['token'];\n let userInfo: Authorization['userInfo'];\n if (parsed.credential) {\n ({ clientId, token, userInfo } = await this.oauth2Client.getTokenInfo({\n provider,\n credential: parsed.credential,\n }));\n mark('verify_credential');\n\n // A credential is replayable until it expires, so it must carry a single-use nonce from\n // `oauth2Nonce`, which the front end passed to `prompt`. This replaces Google's\n // `g_csrf_token` double-submit cookie, which FedCM mode no longer sets.\n const { nonce } = userInfo.data as { nonce?: unknown };\n if (typeof nonce === 'string' && nonce) {\n await this.consumeNonce(nonce, provider);\n mark('check_nonce');\n } else if (this.onetapRequireNonce) {\n throw new AuthenticationError('NONCE_MISSING');\n }\n } else if (parsed.code) {\n ({ clientId, token } = await this.oauth2Client.exchangeAuthorizationCode({\n provider,\n code: parsed.code,\n }));\n userInfo = await this.oauth2Client.getUserInfo({ provider, clientId, token });\n } else {\n throw invalidArgument('INVALID_ARGUMENT', 'credential or code is required');\n }\n\n return this.authorize(\n request,\n handler,\n { provider, clientId, userInfo, token, attributes },\n setTiming\n );\n });\n\n // ---- email -----------------------------------------------------------------------------------\n\n sendEmailVerificationCode = (request: Request, sender: EmailSender): Promise<Response> =>\n this.guard(async () => {\n invariant(this.turnstileSecretKey, 'turnstileSecretKey is not configured');\n const { email, turnstileToken } = parse(\n sendEmailVerificationCodeSchema,\n await readJson(request)\n );\n await verifyTurnstileToken(this.turnstileSecretKey, turnstileToken);\n await this.emailCodes.send(email, sender);\n return Response.json({});\n });\n\n verifyEmailCode = (email: string, verificationCode: string): Promise<void> =>\n this.emailCodes.verify(email, verificationCode);\n\n loginEmail = (request: Request, handler: AuthorizedHandler): Promise<Response> =>\n this.guard(async () => {\n const { setTiming } = timing({ enabled: this.timing });\n const {\n email,\n verificationCode,\n attributes = {},\n } = parse(loginEmailSchema, await readJson(request));\n await this.emailCodes.verify(email, verificationCode);\n const claims: StandardClaims = { sub: email, email, email_verified: true };\n return this.authorize(\n request,\n handler,\n { provider: 'EMAIL', userInfo: { claims, data: {} }, attributes },\n setTiming\n );\n });\n\n // ---- desktop ---------------------------------------------------------------------------------\n\n /**\n * Step 1 of the desktop / native app sign-in handshake. The caller already completed normal\n * sign-in on the web (so a cookie session exists); this issues a 5-minute single-use code that\n * the web page hands off to the desktop client via a loopback redirect.\n *\n * PKCE (RFC 7636, S256 only): the desktop generates a random `code_verifier` before opening the\n * browser, derives `code_challenge = base64url(sha256(verifier))`, and threads the challenge\n * through the URL → web page → here. The challenge is pinned to the code; `desktopExchange`\n * enforces that the caller knows the matching verifier. This blocks an attacker who only\n * intercepts the auth code (browser history, malicious extension, packet capture on loopback)\n * from exchanging it.\n *\n * Requires an authenticated cookie session: anonymous callers get 401. Throttling / abuse\n * protection on this endpoint is the API layer's job (rate-limit per principal); the SDK does\n * not gate it because the upstream sign-in flow already passed CAPTCHA / OAuth / verification.\n */\n desktopAuthorize = (request: Request): Promise<Response> =>\n this.guard(async () => {\n const principal = await this.getPrincipal(request);\n if (!principal) throw unauthenticated('Sign in first');\n const { code_challenge } = parse(desktopAuthorizeSchema, await readJson(request));\n const code = await this.desktopCodes.issue(principal, code_challenge);\n return Response.json({ code });\n });\n\n /**\n * Step 2 of the desktop / native app sign-in handshake. The desktop client hands back the auth\n * code it received via the loopback callback, and we mint a fresh session for it, independent\n * of the web cookie session that originally authorized the code, so logging out on either side\n * does not cascade to the other.\n *\n * Cookie attributes: `SameSite=None; Secure` so the cookie survives cross-site fetches from the\n * desktop renderer's `file://` / `app://` origin. The configured `cookieOptions` provide\n * everything else (`domain`, `path`, `httpOnly`); the override is targeted at the\n * SameSite/Secure pair only. In a non-HTTPS dev backend this combination is rejected by\n * Chromium, see the desktop sign-in PRD for workarounds.\n *\n * No CSRF check needed: the request carries no cookie, the auth code itself is the credential,\n * and the code's single-use removal blocks replay.\n */\n desktopExchange = (request: Request): Promise<Response> =>\n this.guard(async () => {\n const { code, code_verifier } = parse(desktopExchangeSchema, await readJson(request));\n const principal = await this.desktopCodes.redeem(code, code_verifier);\n const session = await this.signIn(principal);\n session.setAttribute('client_type', 'desktop');\n await this.repository.save(session);\n return this.withSession(Response.json({ ok: true }), session, {\n sameSite: 'none',\n secure: true,\n });\n });\n\n // ---- session management ----------------------------------------------------------------------\n\n kick = async (principal: Principal): Promise<void> => {\n const sessions = await this.repository.findByPrincipalName(principal.name);\n for (const sessionId of sessions.keys()) {\n await this.repository.deleteById(sessionId);\n }\n };\n\n /**\n * Sliding expiration: an authenticated request renews the session, as `logged` does, so a user\n * who keeps using the app is never signed out after `maxInactiveInterval` of not calling one\n * particular endpoint. No extra read: the session was just loaded to authenticate, and its\n * `lastAccessedTime` is compared in memory; writes are spaced by `session.touchInterval` (see\n * `AuthConfig`), so a session accessed again within the interval is not rewritten.\n */\n private async touch(session: Session) {\n const now = Date.now();\n if (now - session.getLastAccessedTime() < this.touchInterval) return;\n session.setLastAccessedTime(now);\n await this.repository.save(session);\n }\n\n getPrincipal = async (request: Request): Promise<Principal | null> => {\n const session = await this.loadSession(request);\n const principal = session && this.principalOf(session);\n if (!principal) return null;\n await this.touch(session);\n return principal;\n };\n\n isAuthenticated = async (request: Request): Promise<boolean> => {\n return (await this.getPrincipal(request)) !== null;\n };\n\n getSession = async <T extends boolean>(\n request: Request,\n create: T\n ): Promise<T extends true ? Session : Session | null> => {\n type Result = T extends true ? Session : Session | null;\n const session = await this.loadSession(request);\n if (session || !create) return session as Result;\n const created = this.repository.createSession();\n await this.repository.save(created);\n return created;\n };\n\n deleteSession = async (sessionId: string): Promise<void> => {\n await this.repository.deleteById(sessionId);\n };\n\n listSessions = async (principal: Principal): Promise<Session[]> => {\n const sessions = await this.repository.findByPrincipalName(principal.name);\n return Array.from(sessions.values());\n };\n\n cleanupExpiredSessions = async (cleanupCount?: number): Promise<Response> => {\n await this.repository.cleanupExpiredSessions(cleanupCount);\n return Response.json({});\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAiDA,MAAM,cAAc;AAIpB,MAAM,uBAAuB;;AAG7B,MAAM,iBAAiB;;AAGvB,MAAM,uBAAuB;AAI7B,MAAM,+BAA+B;;AAGrC,SAAS,cAAc,OAAe,UAA4C;CAChF,OAAOA,qBAAAA,uBAAuB,KAAK,IAAI,QAAQ;AACjD;;;;;;;AAQA,MAAM,uCAAqD,IAAI,IAAI;CACjE;CACA;CACA;AACF,CAAC;AAED,SAAS,wBACP,YACoC;CACpC,IAAI,CAAC,YAAY,OAAO,KAAA;CACxB,MAAM,UAAkC,CAAC;CACzC,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,UAAU,GAClD,IAAI,UAAU,KAAA,GAAW,QAAQ,OAAO;CAE1C,IAAI,OAAO,KAAK,OAAO,CAAC,CAAC,WAAW,GAAG,OAAO,KAAA;CAE9C,MAAM,OAAOC,wBAAAA,eAAe,OAAO;CACnC,CAAA,GAAA,cAAA,UAAA,CACE,QAAQC,wBAAAA,sBACR,uCAAuC,KAAK,kBAAkBA,wBAAAA,qBAAqB,SACrF;CACA,OAAO;AACT;;AAGA,SAAS,WAAW,SAAkB;CACpC,MAAM,cAAc,QAAQ,QAAQ,IAAI,cAAc,CAAC,EAAE,YAAY;CACrE,OACE,QAAQ,WAAW,UAAU,CAAC,CAAC,aAAa,WAAW,mCAAmC;AAE9F;;AAGA,MAAM,oBAAA,GAAmBC,SAAAA,OAAAA,CAAOC,sBAAAA,oBAAoB,EAAE,YAAYC,wBAAAA,iBAAiB,CAAC;AAEpF,MAAM,0BA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AAK,CAAC,CAAC;CACzB;AACF"}
1
+ {"version":3,"file":"index.cjs","names":["isKnownOAuth2ErrorType","attributesSize","MAX_ATTRIBUTES_BYTES","extend","googleOneTapSchema","attributesSchema","object","string","regex","literal","EmailVerificationCodes","DesktopCodes","OAuth2Client","getCookie","PRINCIPAL_NAME_INDEX_NAME","errorResponse","randomUUID","randomBytes","createHash","AuthenticationError","param","timing","query","oauth2RedirectQuerySchema","OAuth2Error","readJson","bodyAttributes","invalidArgument","readForm","parse","sendEmailVerificationCodeSchema","verifyTurnstileToken","loginEmailSchema","unauthenticated"],"sources":["../../src/auth/index.ts"],"sourcesContent":["import { createHash, randomBytes, randomUUID } from 'node:crypto';\nimport { invariant } from '@shware/utils';\nimport { extend, literal, object, regex, string } from 'zod/mini';\nimport type { Principal } from '../core/index';\nimport { loginEmailSchema, sendEmailVerificationCodeSchema } from '../email/schema';\nimport { OAuth2Client, googleOneTapSchema, oauth2RedirectQuerySchema } from '../oauth2/client';\nimport { OAuth2Error, type OAuth2ErrorType, isKnownOAuth2ErrorType } from '../oauth2/error';\nimport type {\n NativeCredential,\n OAuth2AuthorizationRequest,\n PkceParameters,\n StandardClaims,\n} from '../oauth2/types';\nimport { PRINCIPAL_NAME_INDEX_NAME } from '../session/common';\nimport type { KVRepository, Session, SessionRepository } from '../session/types';\nimport {\n type CookieOptions,\n deleteCookie,\n getCookie,\n param,\n query,\n setCookie,\n} from '../utils/http';\nimport { timing } from '../utils/timing';\nimport { parse, readForm, readJson, verifyTurnstileToken } from '../utils/valid';\nimport {\n MAX_ATTRIBUTES_BYTES,\n attributesSchema,\n attributesSize,\n bodyAttributes,\n} from './attributes';\nimport { DesktopCodes } from './desktop-codes';\nimport { type EmailSender, EmailVerificationCodes } from './email-codes';\nimport { AuthenticationError } from './error';\nimport { errorResponse, invalidArgument, unauthenticated } from './respond';\nimport type {\n AuthConfig,\n AuthService,\n Authorization,\n AuthorizedHandler,\n LoggedHandler,\n LogoutOptions,\n OAuth2AuthorizationOptions,\n} from './types';\n\n// PKCE per RFC 7636: code_verifier / code_challenge are 43-128 chars from\n// the unreserved set. We restrict to base64url (drops \".\" and \"~\") since\n// that's what S256 produces and what callers should be sending; rejecting\n// the rest shrinks the accepted input shape without losing legit clients.\n// A 32-byte random verifier base64url-encodes to exactly 43 chars.\nconst PKCE_FORMAT = /^[A-Za-z0-9_-]{43,128}$/;\n\n// A native app's `code_verifier` goes on to the provider, which checks it against the challenge\n// the app sent: accept the whole RFC 7636 unreserved set here, as the provider does.\nconst CODE_VERIFIER_FORMAT = /^[A-Za-z0-9._~-]{43,128}$/;\n\n/** The header a session id travels in besides the cookie, with `session.header` on. */\nconst SESSION_HEADER = 'X-Auth-Token';\n\n/** Seconds an OAuth2 state or nonce may be used within. */\nconst OAUTH2_PARAMETER_TTL = 10 * 60;\n\n// error_description forwarded to errorUri comes from the provider or an error message: cap it so\n// the redirect URL stays short and an attacker-crafted callback cannot stuff the page with text.\nconst MAX_ERROR_DESCRIPTION_LENGTH = 256;\n\n/** An error code safe to put on errorUri: a registered one as is, anything else as `fallback`. */\nfunction safeErrorType(error: string, fallback: OAuth2ErrorType): OAuth2ErrorType {\n return isKnownOAuth2ErrorType(error) ? error : fallback;\n}\n\n/**\n * The codes a failure past validation keeps on errorUri, each one the user can act on: the code\n * expired or was used (start again), they declined, or the provider is briefly down. Every other\n * failure there (a rejected client, a user info request that failed) is the app's or the\n * provider's problem, which the user sees as `server_error`.\n */\nconst CALLBACK_ERROR_TYPES: ReadonlySet<OAuth2ErrorType> = new Set([\n 'invalid_grant',\n 'access_denied',\n 'temporarily_unavailable',\n]);\n\nfunction authorizationAttributes(\n attributes: OAuth2AuthorizationOptions['attributes']\n): Record<string, string> | undefined {\n if (!attributes) return undefined;\n const defined: Record<string, string> = {};\n for (const [key, value] of Object.entries(attributes)) {\n if (value !== undefined) defined[key] = value;\n }\n if (Object.keys(defined).length === 0) return undefined;\n // The host's own values, written with the session: oversized is a bug in the host, not a 400.\n const size = attributesSize(defined);\n invariant(\n size <= MAX_ATTRIBUTES_BYTES,\n `oauth2 authorization attributes are ${size} bytes, at most ${MAX_ATTRIBUTES_BYTES} allowed`\n );\n return defined;\n}\n\n/** Sign in with Apple answers with `response_mode=form_post`; a charset parameter may follow. */\nfunction isFormPost(request: Request) {\n const contentType = request.headers.get('content-type')?.toLowerCase();\n return (\n request.method === 'POST' && !!contentType?.startsWith('application/x-www-form-urlencoded')\n );\n}\n\n/** Google's own form post carries no attributes; an app posting JSON may add them. */\nconst oneTapBodySchema = extend(googleOneTapSchema, { attributes: attributesSchema });\n\nconst desktopAuthorizeSchema = object({\n code_challenge: string().check(regex(PKCE_FORMAT)),\n code_challenge_method: literal('S256'),\n});\n\nconst desktopExchangeSchema = object({\n code: string(),\n code_verifier: string().check(regex(PKCE_FORMAT)),\n});\n\nexport const PATH = {\n CSRF: '/csrf',\n LOGOUT: '/logout',\n LOGGED: '/logged',\n\n OAUTH2_STATE: '/oauth2/state/:provider',\n OAUTH2_NONCE: '/oauth2/nonce/:provider',\n OAUTH2_AUTHORIZATION: '/oauth2/authorization/:provider',\n LOGIN_OAUTH2_CODE: '/login/oauth2/code/:provider',\n LOGIN_OAUTH2_NATIVE: '/login/oauth2/native/:provider',\n LOGIN_OAUTH2_ONETAP: '/login/oauth2/onetap/google',\n\n LOGIN_EMAIL: '/login/email',\n SEND_EMAIL_VERIFICATION_CODE: '/auth/sendEmailVerificationCode',\n\n // Desktop / native app sign-in via web loopback (RFC 8252 + OAuth 2.1 Auth Code Flow):\n // 1. user already authenticated with cookie session → POST DESKTOP_AUTHORIZE → { code }\n // 2. web redirects to desktop's loopback callback with the code\n // 3. desktop renderer POSTs DESKTOP_EXCHANGE with the code → server returns\n // Set-Cookie carrying a fresh session, single-use code is invalidated\n // The two-step flow keeps the actual session id off the redirect URL — only a\n // 5-minute single-use code transits via the loopback.\n DESKTOP_AUTHORIZE: '/auth/desktop/authorize',\n DESKTOP_EXCHANGE: '/auth/desktop/exchange',\n\n CLEANUP_EXPIRED_SESSIONS: '/sessions/expired/cleanup',\n} as const;\n\n/**\n * The login routes and session helpers. Every route is one straight line: read and validate the\n * request, check the credential, call the host's `onAuthorized`, sign in. Failures are thrown and\n * answered in one place per kind of route: a JSON route runs under `guard`, which maps a\n * `RequestError`, an `AuthenticationError` or an `OAuth2Error` to its google.rpc body (see\n * `respond.ts`); the redirect callback maps the same errors to `errorUri` parameters (`redirect`).\n */\nexport class Auth implements AuthService {\n private readonly timing: boolean;\n private readonly cookieName;\n private readonly cookieOptions: CookieOptions;\n private readonly kv: KVRepository;\n private readonly repository: SessionRepository;\n private readonly turnstileSecretKey?: string;\n private readonly emailCodes: EmailVerificationCodes;\n private readonly desktopCodes: DesktopCodes;\n private readonly oauth2Client: OAuth2Client | null;\n /** Provider keys whose logins may come without a nonce (`oauth2.nonce.optional`). */\n private readonly nonceOptional: ReadonlySet<string>;\n private readonly touchInterval: number;\n private readonly sessionHeader: boolean;\n private readonly ATTR_OAUTH2_AUTHORIZATION_REQUEST = 'oauth2AuthorizationRequest';\n\n constructor({\n sessionRepository,\n kvRepository,\n turnstileSecretKey,\n verificationCode,\n oauth2,\n cookie,\n session,\n timing,\n }: AuthConfig) {\n this.timing = timing ?? false;\n this.kv = kvRepository;\n this.repository = sessionRepository;\n this.turnstileSecretKey = turnstileSecretKey;\n const maxAttempts = verificationCode?.maxAttempts ?? 5;\n const resendCooldown = verificationCode?.resendCooldown ?? 60;\n invariant(maxAttempts >= 1, 'verificationCode.maxAttempts must be at least 1');\n invariant(resendCooldown >= 1, 'verificationCode.resendCooldown must be at least 1 second');\n this.emailCodes = new EmailVerificationCodes(kvRepository, { maxAttempts, resendCooldown });\n this.desktopCodes = new DesktopCodes(kvRepository);\n const { name, ...cookieOptions } = cookie ?? {};\n this.cookieName = name ?? 'SESSION';\n this.cookieOptions = {\n path: '/',\n sameSite: 'none',\n secure: true,\n httpOnly: true,\n ...cookieOptions,\n };\n this.oauth2Client = oauth2?.client ? new OAuth2Client(oauth2.client) : null;\n this.nonceOptional = new Set(oauth2?.nonce?.optional);\n this.touchInterval = (session?.touchInterval ?? 3600) * 1000;\n this.sessionHeader = session?.header ?? false;\n invariant(this.touchInterval >= 0, 'session.touchInterval must not be negative');\n }\n\n // ---- sessions and responses ------------------------------------------------------------------\n\n private getSessionId(request: Request): string | undefined {\n const fromCookie = getCookie(request, this.cookieName);\n if (fromCookie) return fromCookie;\n return (this.sessionHeader && request.headers.get(SESSION_HEADER)) || undefined;\n }\n\n /** The session the request carries, if it exists. */\n private async loadSession(request: Request): Promise<Session | null> {\n const sessionId = this.getSessionId(request);\n return sessionId ? this.repository.findById(sessionId) : null;\n }\n\n /** The signed-in principal of a session, if any. */\n private principalOf(session: Session): Principal | null {\n const name = session.getAttribute(PRINCIPAL_NAME_INDEX_NAME);\n return name ? { name: String(name) } : null;\n }\n\n /**\n * A new session signed in as `principal`. With `carryOver`, what the host kept in the pre-login\n * session moves to the new one; the authorization request (state, PKCE verifier, flow\n * attributes) is single-use and was consumed, and a principal left there from an earlier\n * sign-in is replaced. The new id is never the one the browser brought, which may have been\n * planted by an attacker who started the flow (session fixation).\n */\n private async signIn(principal: Principal, carryOver?: Session): Promise<Session> {\n const session = this.repository.createSession();\n for (const attribute of carryOver?.getAttributeNames() ?? []) {\n if (attribute === this.ATTR_OAUTH2_AUTHORIZATION_REQUEST) continue;\n if (attribute === PRINCIPAL_NAME_INDEX_NAME) continue;\n const value = carryOver?.getAttribute(attribute);\n if (value !== null && value !== undefined) session.setAttribute(attribute, value);\n }\n session.setAttribute(PRINCIPAL_NAME_INDEX_NAME, principal.name);\n await this.repository.save(session);\n return session;\n }\n\n /**\n * `response` carrying `session`: its cookie, renewed for the whole inactive interval, and with\n * `session.header` on, the `X-Auth-Token` header a client without a cookie jar reads.\n */\n private withSession(response: Response, session: Session, cookie?: CookieOptions): Response {\n const maxAge = session.getMaxInactiveInterval();\n setCookie(response, this.cookieName, session.getId(), {\n ...this.cookieOptions,\n ...cookie,\n maxAge,\n });\n if (this.sessionHeader) response.headers.set(SESSION_HEADER, session.getId());\n return response;\n }\n\n /** Runs a JSON route: a failure it knows is its response, anything else is the host's. */\n private async guard(run: () => Promise<Response>): Promise<Response> {\n try {\n return await run();\n } catch (error) {\n const response = errorResponse(error);\n if (response) return response;\n throw error;\n }\n }\n\n /** The error redirect of the callback flow; `refusal`'s reason and metadata ride along. */\n private redirect(\n error: OAuth2ErrorType,\n description?: string,\n refusal?: AuthenticationError\n ): Response {\n invariant(this.oauth2Client, 'oauth2Client is not initialized');\n const uri = new URL(this.oauth2Client.errorUri);\n // Metadata never replaces a parameter: not one errorUri carries itself, nor one set below.\n for (const [key, value] of Object.entries(refusal?.metadata ?? {})) {\n if (!uri.searchParams.has(key)) uri.searchParams.set(key, value);\n }\n uri.searchParams.set('error', error);\n if (description) {\n uri.searchParams.set('error_description', description.slice(0, MAX_ERROR_DESCRIPTION_LENGTH));\n }\n if (refusal) uri.searchParams.set('reason', refusal.reason);\n return Response.redirect(uri.href, 302);\n }\n\n // ---- basic -----------------------------------------------------------------------------------\n\n csrf = async (_request: Request): Promise<Response> => {\n const token = randomUUID();\n const response = Response.json({\n token,\n parameterName: '_csrf',\n headerName: 'X-XSRF-TOKEN',\n });\n\n // Double Submit Cookie Protection\n setCookie(response, 'XSRF-TOKEN', token, {\n path: '/',\n secure: true,\n httpOnly: false,\n sameSite: 'none',\n domain: this.cookieOptions.domain,\n });\n return response;\n };\n\n logout = async (request: Request, options?: LogoutOptions): Promise<Response> => {\n const scope = options?.scope ?? 'local';\n const sessionId = this.getSessionId(request);\n // `global` and `others` reach the principal's other sessions through the one the request\n // carries; a request without a signed-in session has no principal to widen to, and ends as\n // `local` would.\n if (scope !== 'local' && sessionId) {\n const session = await this.repository.findById(sessionId);\n const principal = session && this.principalOf(session);\n if (principal) {\n const sessions = await this.repository.findByPrincipalName(principal.name);\n for (const id of sessions.keys()) {\n if (id !== sessionId) await this.repository.deleteById(id);\n }\n }\n }\n const response = Response.json({});\n if (scope === 'others') return response;\n if (sessionId) await this.repository.deleteById(sessionId);\n // A Set-Cookie only replaces the stored cookie when Domain and Path match (RFC 6265),\n // so clear it with the same attributes it was set with.\n deleteCookie(response, this.cookieName, this.cookieOptions);\n return response;\n };\n\n logged = async (request: Request, onLogged?: LoggedHandler): Promise<Response> => {\n const session = await this.loadSession(request);\n if (!session) return Response.json({ data: false });\n\n session.setLastAccessedTime(Date.now());\n await this.repository.save(session);\n\n const principal = this.principalOf(session);\n if (principal) await onLogged?.(principal);\n return this.withSession(Response.json({ data: principal !== null }), session);\n };\n\n // ---- oauth2 ----------------------------------------------------------------------------------\n\n private createPkceParameters(): PkceParameters {\n // 32 random bytes: a 43-char base64url verifier, the RFC 7636 minimum (a UUID is 36).\n const code_verifier = randomBytes(32).toString('base64url');\n const code_challenge = createHash('sha256')\n .update(code_verifier)\n .digest()\n .toString('base64url');\n\n return { code_verifier, code_challenge, code_challenge_method: 'S256' };\n }\n\n private getOauth2StateKey(state: string) {\n return `oauth2:state:${state}`;\n }\n\n private getOauth2NonceKey(nonce: string) {\n return `oauth2:nonce:${nonce}`;\n }\n\n /**\n * Spends a nonce `oauth2Nonce` issued for `provider`: `NONCE_MISMATCH` for one that was not,\n * or was used already. An id token is replayable until it expires; the nonce it carries makes\n * it sign in once.\n */\n private async consumeNonce(nonce: string, provider: string): Promise<void> {\n const key = this.getOauth2NonceKey(nonce);\n if ((await this.kv.getItem(key)) !== provider) throw new AuthenticationError('NONCE_MISMATCH');\n await this.kv.removeItem(key);\n }\n\n /**\n * The nonce check of the JSON logins (One Tap, native), where the client obtained the id token\n * and the nonce came from `oauth2Nonce`: spends the one the token carries, and refuses a token\n * without one when the provider's flow echoes nonces (`required`) and the host has not listed the\n * provider as optional. An id token is replayable until it expires; the nonce makes it sign in\n * once.\n */\n private async checkIssuedNonce(\n userInfo: Authorization['userInfo'],\n provider: string,\n required: boolean\n ): Promise<boolean> {\n const { nonce } = userInfo.data as { nonce?: unknown };\n if (typeof nonce === 'string' && nonce) {\n await this.consumeNonce(nonce, provider);\n return true;\n }\n if (required && !this.nonceOptional.has(provider)) {\n throw new AuthenticationError('NONCE_MISSING');\n }\n return false;\n }\n\n oauth2State = async (request: Request): Promise<Response> => {\n const { provider } = param(request, PATH.OAUTH2_STATE);\n const state = randomUUID();\n await this.kv.setItem(this.getOauth2StateKey(state), provider, OAUTH2_PARAMETER_TTL);\n return Response.json({ state });\n };\n\n oauth2Nonce = async (request: Request): Promise<Response> => {\n const { provider } = param(request, PATH.OAUTH2_NONCE);\n const nonce = randomUUID();\n await this.kv.setItem(this.getOauth2NonceKey(nonce), provider, OAUTH2_PARAMETER_TTL);\n return Response.json({ nonce });\n };\n\n oauth2Authorization = (\n request: Request,\n options?: OAuth2AuthorizationOptions\n ): Promise<Response> =>\n this.guard(async () => {\n invariant(this.oauth2Client, 'oauth2Client is not initialized');\n const attributes = authorizationAttributes(options?.attributes);\n const { mark, setTiming } = timing({ enabled: this.timing });\n const { provider } = param(request, PATH.OAUTH2_AUTHORIZATION);\n const state = randomUUID();\n const pkce = this.createPkceParameters();\n // Sent only to a provider whose id token echoes it: the callback then requires it back, so\n // a code that was swapped in for another sign-in's yields a token the session refuses.\n const nonce = (await this.oauth2Client.nonceSupport(provider)).web ? randomUUID() : undefined;\n const uri = await this.oauth2Client.createAuthorizationUri({ provider, state, pkce, nonce });\n let session = await this.loadSession(request);\n if (!session) {\n // A session made for the flow only has to outlive the state: an abandoned flow must not\n // keep a row for the default interval. Sign-in moves to a new session, with the default.\n session = this.repository.createSession();\n session.setMaxInactiveInterval(OAUTH2_PARAMETER_TTL);\n }\n mark('fetch_session');\n\n const authorizationRequest: OAuth2AuthorizationRequest = {\n state,\n provider,\n authorizationRequestUri: uri.href,\n additionalParameters: pkce,\n ...(nonce ? { nonce } : {}),\n ...(attributes ? { attributes } : {}),\n };\n session.setAttribute(\n this.ATTR_OAUTH2_AUTHORIZATION_REQUEST,\n JSON.stringify(authorizationRequest)\n );\n await this.repository.save(session);\n mark('save_session');\n\n const response = new Response(null, { status: 302, headers: { location: uri.href } });\n setTiming(response);\n return this.withSession(response, session);\n });\n\n loginOAuth2Code = async (request: Request, handler: AuthorizedHandler): Promise<Response> => {\n invariant(this.oauth2Client, 'oauth2Client is not initialized');\n const { mark, setTiming } = timing({ enabled: this.timing });\n\n // 1. the session the flow started on, and the authorization request it stored\n const session = await this.loadSession(request);\n if (!session) return this.redirect('invalid_request', 'session not found');\n mark('load_session');\n const json = session.getAttribute(this.ATTR_OAUTH2_AUTHORIZATION_REQUEST) as string | null;\n if (!json) return this.redirect('invalid_request', 'authorization request not found');\n const cached: OAuth2AuthorizationRequest = JSON.parse(json);\n\n // 2. the provider's answer: query, or a form for Apple's response_mode=form_post\n const { provider } = param(request, PATH.LOGIN_OAUTH2_CODE);\n const data = isFormPost(request)\n ? Object.fromEntries(new URLSearchParams(await request.text()))\n : query(request);\n const parsed = oauth2RedirectQuerySchema.safeParse(data);\n if (!parsed.success) return this.redirect('invalid_request', 'invalid redirect query');\n // The provider answered with an error instead of a code (the user pressed Cancel →\n // access_denied, invalid_scope, server_error, ...). Forward it rather than reporting a\n // malformed query. This runs before the state check on purpose: providers echo state on\n // error responses, but not all reliably do, and a forged error callback can only make the\n // victim's popup show an error — nothing is exchanged or signed in. A present state that does\n // not match still wins, since that is the more accurate (and more alarming) diagnosis.\n if (parsed.data.error) {\n if (parsed.data.state && parsed.data.state !== cached.state) {\n return this.redirect('invalid_request', 'redirect state mismatch');\n }\n return this.redirect(\n safeErrorType(parsed.data.error, 'server_error'),\n parsed.data.error_description\n );\n }\n const { code, state, user } = parsed.data;\n if (!code || !state) return this.redirect('invalid_request', 'invalid redirect query');\n if (state !== cached.state) return this.redirect('invalid_request', 'redirect state mismatch');\n if (provider !== cached.provider) {\n return this.redirect('invalid_request', 'redirect provider mismatch');\n }\n mark('validate_session');\n\n // 3. exchange the code, load the user, sign in. Everything here can fail (an expired or reused\n // code, a network error, the host's handler or session store). The callback runs in a popup\n // the user is looking at, so every failure must land on errorUri, never as a JSON error.\n let signedIn: Session;\n try {\n const { clientId, token } = await this.oauth2Client.exchangeAuthorizationCode({\n provider,\n code,\n pkce: cached.additionalParameters,\n });\n // Apple posts the user's name alongside the code, once: hand it to the provider with the token.\n const userInfo = await this.oauth2Client.getUserInfo({\n provider,\n clientId,\n token,\n response: user ? { user } : undefined,\n });\n mark('exchange_code');\n // The id token must carry the nonce this flow sent (stored with the state, not in KV: it\n // is bound to this session's request). A provider that gave no id token has nothing to\n // carry it, as has a request stored before nonces were sent.\n if (cached.nonce && token.id_token) {\n const { nonce } = userInfo.data as { nonce?: unknown };\n if (typeof nonce !== 'string' || !nonce) throw new AuthenticationError('NONCE_MISSING');\n if (nonce !== cached.nonce) throw new AuthenticationError('NONCE_MISMATCH');\n mark('check_nonce');\n }\n\n const principal = await handler(request, {\n provider,\n clientId,\n userInfo,\n token,\n attributes: cached.attributes ?? {},\n });\n mark('save_principal');\n\n signedIn = await this.signIn(principal, session);\n await this.repository.deleteById(session.getId());\n mark('update_session');\n } catch (error) {\n // The details stay in the logs: an OAuth2Error message can carry a client id or a\n // provider's response, which has no place in a URL the browser keeps in its history.\n if (error instanceof OAuth2Error) {\n console.warn('OAuth2 callback failed', error);\n const type = CALLBACK_ERROR_TYPES.has(error.error) ? error.error : 'server_error';\n return this.redirect(type);\n }\n // A refusal is something the user can act on, so its reason and metadata reach the page,\n // as they reach a JSON client through the ErrorInfo.\n if (error instanceof AuthenticationError) {\n console.warn('OAuth2 sign-in refused', error.reason, error.metadata);\n return this.redirect('access_denied', undefined, error);\n }\n console.error('OAuth2 callback failed', error);\n return this.redirect('server_error');\n }\n\n const uri = new URL(this.oauth2Client.successUri);\n uri.searchParams.set('status', 'success');\n uri.searchParams.set('provider', provider);\n const response = new Response(null, { status: 302, headers: { location: uri.href } });\n setTiming(response);\n return this.withSession(response, signedIn);\n };\n\n /** The shared tail of the JSON login routes: the host's handler, then a signed-in session. */\n private async authorize(\n request: Request,\n handler: AuthorizedHandler,\n authorization: Authorization,\n setTiming: (response: Response) => void\n ): Promise<Response> {\n const principal = await handler(request, authorization);\n const session = await this.signIn(principal);\n const response = Response.json(principal);\n setTiming(response);\n return this.withSession(response, session);\n }\n\n loginOAuth2Native = (request: Request, handler: AuthorizedHandler): Promise<Response> =>\n this.guard(async () => {\n invariant(this.oauth2Client, 'oauth2Client is not initialized');\n const { mark, setTiming } = timing({ enabled: this.timing });\n const { provider } = param(request, PATH.LOGIN_OAUTH2_NATIVE);\n const body = await readJson(request);\n // Whatever the app sends besides its credentials for `onAuthorized` (a referral code, ...).\n const attributes = bodyAttributes(body);\n // Only the credentials go on to the provider client.\n const { attributes: _, ...credentials } = body as NativeCredential & { attributes?: unknown };\n const { code_verifier } = credentials as { code_verifier?: unknown };\n if (\n code_verifier !== undefined &&\n (typeof code_verifier !== 'string' || !CODE_VERIFIER_FORMAT.test(code_verifier))\n ) {\n throw invalidArgument(\n 'INVALID_CODE_VERIFIER',\n 'code_verifier must be 43-128 characters from [A-Za-z0-9-._~]'\n );\n }\n const { clientId, userInfo, token } = await this.oauth2Client.loginOAuth2Native({\n provider,\n credentials,\n });\n mark('login_oauth2_native');\n\n // Required when the provider's native id token echoes a nonce and the login produced one\n // (Facebook's access_token login has none to carry it).\n const required = (await this.oauth2Client.nonceSupport(provider)).native && !!token.id_token;\n if (await this.checkIssuedNonce(userInfo, provider, required)) mark('check_nonce');\n\n return this.authorize(\n request,\n handler,\n { provider, clientId, userInfo, token, attributes },\n setTiming\n );\n });\n\n loginOAuth2Onetap = (\n request: Request,\n handler: AuthorizedHandler,\n provider = 'google'\n ): Promise<Response> =>\n this.guard(async () => {\n invariant(this.oauth2Client, 'oauth2Client is not initialized');\n const { mark, setTiming } = timing({ enabled: this.timing });\n\n // Google's own form post, or an app's JSON.\n const contentType = request.headers.get('content-type') ?? '';\n const body = contentType.includes('application/json')\n ? await readJson(request)\n : await readForm(request);\n const { attributes = {}, ...parsed } = parse(oneTapBodySchema, body);\n\n // Both the credential and the code are issued to the provider's web client.\n let clientId: string;\n let token: Authorization['token'];\n let userInfo: Authorization['userInfo'];\n if (parsed.credential) {\n ({ clientId, token, userInfo } = await this.oauth2Client.getTokenInfo({\n provider,\n credential: parsed.credential,\n }));\n mark('verify_credential');\n\n // The credential must carry a single-use nonce from `oauth2Nonce`, which the front end\n // passed to `prompt`. This replaces Google's `g_csrf_token` double-submit cookie, which\n // FedCM mode no longer sets.\n const required = (await this.oauth2Client.nonceSupport(provider)).web;\n if (await this.checkIssuedNonce(userInfo, provider, required)) mark('check_nonce');\n } else if (parsed.code) {\n ({ clientId, token } = await this.oauth2Client.exchangeAuthorizationCode({\n provider,\n code: parsed.code,\n }));\n userInfo = await this.oauth2Client.getUserInfo({ provider, clientId, token });\n } else {\n throw invalidArgument('INVALID_ARGUMENT', 'credential or code is required');\n }\n\n return this.authorize(\n request,\n handler,\n { provider, clientId, userInfo, token, attributes },\n setTiming\n );\n });\n\n // ---- email -----------------------------------------------------------------------------------\n\n sendEmailVerificationCode = (request: Request, sender: EmailSender): Promise<Response> =>\n this.guard(async () => {\n invariant(this.turnstileSecretKey, 'turnstileSecretKey is not configured');\n const { email, turnstileToken } = parse(\n sendEmailVerificationCodeSchema,\n await readJson(request)\n );\n await verifyTurnstileToken(this.turnstileSecretKey, turnstileToken);\n await this.emailCodes.send(email, sender);\n return Response.json({});\n });\n\n verifyEmailCode = (email: string, verificationCode: string): Promise<void> =>\n this.emailCodes.verify(email, verificationCode);\n\n loginEmail = (request: Request, handler: AuthorizedHandler): Promise<Response> =>\n this.guard(async () => {\n const { setTiming } = timing({ enabled: this.timing });\n const {\n email,\n verificationCode,\n attributes = {},\n } = parse(loginEmailSchema, await readJson(request));\n await this.emailCodes.verify(email, verificationCode);\n const claims: StandardClaims = { sub: email, email, email_verified: true };\n return this.authorize(\n request,\n handler,\n { provider: 'EMAIL', userInfo: { claims, data: {} }, attributes },\n setTiming\n );\n });\n\n // ---- desktop ---------------------------------------------------------------------------------\n\n /**\n * Step 1 of the desktop / native app sign-in handshake. The caller already completed normal\n * sign-in on the web (so a cookie session exists); this issues a 5-minute single-use code that\n * the web page hands off to the desktop client via a loopback redirect.\n *\n * PKCE (RFC 7636, S256 only): the desktop generates a random `code_verifier` before opening the\n * browser, derives `code_challenge = base64url(sha256(verifier))`, and threads the challenge\n * through the URL → web page → here. The challenge is pinned to the code; `desktopExchange`\n * enforces that the caller knows the matching verifier. This blocks an attacker who only\n * intercepts the auth code (browser history, malicious extension, packet capture on loopback)\n * from exchanging it.\n *\n * Requires an authenticated cookie session: anonymous callers get 401. Throttling / abuse\n * protection on this endpoint is the API layer's job (rate-limit per principal); the SDK does\n * not gate it because the upstream sign-in flow already passed CAPTCHA / OAuth / verification.\n */\n desktopAuthorize = (request: Request): Promise<Response> =>\n this.guard(async () => {\n const principal = await this.getPrincipal(request);\n if (!principal) throw unauthenticated('Sign in first');\n const { code_challenge } = parse(desktopAuthorizeSchema, await readJson(request));\n const code = await this.desktopCodes.issue(principal, code_challenge);\n return Response.json({ code });\n });\n\n /**\n * Step 2 of the desktop / native app sign-in handshake. The desktop client hands back the auth\n * code it received via the loopback callback, and we mint a fresh session for it, independent\n * of the web cookie session that originally authorized the code, so logging out on either side\n * does not cascade to the other.\n *\n * Cookie attributes: `SameSite=None; Secure` so the cookie survives cross-site fetches from the\n * desktop renderer's `file://` / `app://` origin. The configured `cookieOptions` provide\n * everything else (`domain`, `path`, `httpOnly`); the override is targeted at the\n * SameSite/Secure pair only. In a non-HTTPS dev backend this combination is rejected by\n * Chromium, see the desktop sign-in PRD for workarounds.\n *\n * No CSRF check needed: the request carries no cookie, the auth code itself is the credential,\n * and the code's single-use removal blocks replay.\n */\n desktopExchange = (request: Request): Promise<Response> =>\n this.guard(async () => {\n const { code, code_verifier } = parse(desktopExchangeSchema, await readJson(request));\n const principal = await this.desktopCodes.redeem(code, code_verifier);\n const session = await this.signIn(principal);\n session.setAttribute('client_type', 'desktop');\n await this.repository.save(session);\n return this.withSession(Response.json({ ok: true }), session, {\n sameSite: 'none',\n secure: true,\n });\n });\n\n // ---- session management ----------------------------------------------------------------------\n\n kick = async (principal: Principal): Promise<void> => {\n const sessions = await this.repository.findByPrincipalName(principal.name);\n for (const sessionId of sessions.keys()) {\n await this.repository.deleteById(sessionId);\n }\n };\n\n /**\n * Sliding expiration: an authenticated request renews the session, as `logged` does, so a user\n * who keeps using the app is never signed out after `maxInactiveInterval` of not calling one\n * particular endpoint. No extra read: the session was just loaded to authenticate, and its\n * `lastAccessedTime` is compared in memory; writes are spaced by `session.touchInterval` (see\n * `AuthConfig`), so a session accessed again within the interval is not rewritten.\n */\n private async touch(session: Session) {\n const now = Date.now();\n if (now - session.getLastAccessedTime() < this.touchInterval) return;\n session.setLastAccessedTime(now);\n await this.repository.save(session);\n }\n\n getPrincipal = async (request: Request): Promise<Principal | null> => {\n const session = await this.loadSession(request);\n const principal = session && this.principalOf(session);\n if (!principal) return null;\n await this.touch(session);\n return principal;\n };\n\n isAuthenticated = async (request: Request): Promise<boolean> => {\n return (await this.getPrincipal(request)) !== null;\n };\n\n getSession = async <T extends boolean>(\n request: Request,\n create: T\n ): Promise<T extends true ? Session : Session | null> => {\n type Result = T extends true ? Session : Session | null;\n const session = await this.loadSession(request);\n if (session || !create) return session as Result;\n const created = this.repository.createSession();\n await this.repository.save(created);\n return created;\n };\n\n deleteSession = async (sessionId: string): Promise<void> => {\n await this.repository.deleteById(sessionId);\n };\n\n listSessions = async (principal: Principal): Promise<Session[]> => {\n const sessions = await this.repository.findByPrincipalName(principal.name);\n return Array.from(sessions.values());\n };\n\n cleanupExpiredSessions = async (cleanupCount?: number): Promise<Response> => {\n await this.repository.cleanupExpiredSessions(cleanupCount);\n return Response.json({});\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAkDA,MAAM,cAAc;AAIpB,MAAM,uBAAuB;;AAG7B,MAAM,iBAAiB;;AAGvB,MAAM,uBAAuB;AAI7B,MAAM,+BAA+B;;AAGrC,SAAS,cAAc,OAAe,UAA4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,MAAM,OAAO;EACxB,OAAO;CACT;CAEA,kBAAkB,OAAO,YAAuC;EAC9D,OAAQ,MAAM,KAAK,aAAa,OAAO,MAAO;CAChD;CAEA,aAAa,OACX,SACA,WACuD;EAEvD,MAAM,UAAU,MAAM,KAAK,YAAY,OAAO;EAC9C,IAAI,WAAW,CAAC,QAAQ,OAAO;EAC/B,MAAM,UAAU,KAAK,WAAW,cAAc;EAC9C,MAAM,KAAK,WAAW,KAAK,OAAO;EAClC,OAAO;CACT;CAEA,gBAAgB,OAAO,cAAqC;EAC1D,MAAM,KAAK,WAAW,WAAW,SAAS;CAC5C;CAEA,eAAe,OAAO,cAA6C;EACjE,MAAM,WAAW,MAAM,KAAK,WAAW,oBAAoB,UAAU,IAAI;EACzE,OAAO,MAAM,KAAK,SAAS,OAAO,CAAC;CACrC;CAEA,yBAAyB,OAAO,iBAA6C;EAC3E,MAAM,KAAK,WAAW,uBAAuB,YAAY;EACzD,OAAO,SAAS,KAAK,CAAC,CAAC;CACzB;AACF"}
@@ -1,7 +1,7 @@
1
1
  import { Principal } from "../core/index.cjs";
2
2
  import { Session } from "../session/types.cjs";
3
3
  import { EmailSender } from "./email-codes.cjs";
4
- import { AuthConfig, AuthService, AuthorizedHandler, LoggedHandler, OAuth2AuthorizationOptions } from "./types.cjs";
4
+ import { AuthConfig, AuthService, AuthorizedHandler, LoggedHandler, LogoutOptions, OAuth2AuthorizationOptions } from "./types.cjs";
5
5
  export declare const PATH: {
6
6
  readonly CSRF: '/csrf';
7
7
  readonly LOGOUT: '/logout';
@@ -35,7 +35,8 @@ export declare class Auth implements AuthService {
35
35
  private readonly emailCodes;
36
36
  private readonly desktopCodes;
37
37
  private readonly oauth2Client;
38
- private readonly onetapRequireNonce;
38
+ /** Provider keys whose logins may come without a nonce (`oauth2.nonce.optional`). */
39
+ private readonly nonceOptional;
39
40
  private readonly touchInterval;
40
41
  private readonly sessionHeader;
41
42
  private readonly ATTR_OAUTH2_AUTHORIZATION_REQUEST;
@@ -63,7 +64,7 @@ export declare class Auth implements AuthService {
63
64
  /** The error redirect of the callback flow; `refusal`'s reason and metadata ride along. */
64
65
  private redirect;
65
66
  csrf: (_request: Request) => Promise<Response>;
66
- logout: (request: Request) => Promise<Response>;
67
+ logout: (request: Request, options?: LogoutOptions) => Promise<Response>;
67
68
  logged: (request: Request, onLogged?: LoggedHandler) => Promise<Response>;
68
69
  private createPkceParameters;
69
70
  private getOauth2StateKey;
@@ -74,6 +75,14 @@ export declare class Auth implements AuthService {
74
75
  * it sign in once.
75
76
  */
76
77
  private consumeNonce;
78
+ /**
79
+ * The nonce check of the JSON logins (One Tap, native), where the client obtained the id token
80
+ * and the nonce came from `oauth2Nonce`: spends the one the token carries, and refuses a token
81
+ * without one when the provider's flow echoes nonces (`required`) and the host has not listed the
82
+ * provider as optional. An id token is replayable until it expires; the nonce makes it sign in
83
+ * once.
84
+ */
85
+ private checkIssuedNonce;
77
86
  oauth2State: (request: Request) => Promise<Response>;
78
87
  oauth2Nonce: (request: Request) => Promise<Response>;
79
88
  oauth2Authorization: (request: Request, options?: OAuth2AuthorizationOptions) => Promise<Response>;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.cts","names":[],"sources":["../../src/auth/index.ts"],"mappings":";;;;qBAyHa;WACX;WACA;WACA;WAEA;WACA;WACA;WACA;WACA;WACA;WAEA;WACA;WASA;WACA;WAEA;;;;;;;;;qBAUW,gBAAgB;mBACV;mBACA;mBACA;mBACA;mBACA;mBACA;mBACA;mBACA;mBACA;mBACA;mBACA;mBACA;mBACA;EAEjB,cACE,mBACA,cACA,oBACA,kBACA,QACA,QACA,SACA,UACC;UA6BK;;UAOM;;UAMN;;;;;;;;UAYM;;;;;UAiBN;;UAYM;;UAWN;EAqBR,OAAI,UAAoB,YAAU,QAAQ;EAmB1C,SAAM,SAAmB,YAAU,QAAQ;EAU3C,SAAM,SAAmB,SAAO,WAAa,kBAAgB,QAAQ;UAc7D;UAWA;UAIA;;;;;;UASM;EAMd,cAAW,SAA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kBAAgB,QAAQ;UAc7D;UAWA;UAIA;;;;;;UASM;;;;;;;;UAaA;EAgBd,cAAW,SAAmB,YAAU,QAAQ;EAOhD,cAAW,SAAmB,YAAU,QAAQ;EAOhD,sBAAmB,SACR,SAAO,UACN,+BACT,QAAQ;EAyCX,kBAAe,SAAmB,SAAO,SAAW,sBAAoB,QAAQ;;UA6GlE;EAad,oBAAiB,SAAa,SAAO,SAAW,sBAAoB,QAAQ;EAuC5E,oBAAiB,SACN,SAAO,SACP,mBAAiB,sBAEzB,QAAQ;EAgDX,4BAAyB,SAAa,SAAO,QAAU,gBAAc,QAAQ;EAY7E,kBAAe,eAAiB,6BAA6B;EAG7D,aAAU,SAAa,SAAO,SAAW,sBAAoB,QAAQ;;;;;;;;;;;;;;;;;EAoCrE,mBAAgB,SAAa,YAAU,QAAQ;;;;;;;;;;;;;;;;EAwB/C,kBAAe,SAAa,YAAU,QAAQ;EAe9C,OAAI,WAAqB,cAAY;;;;;;;;UAcvB;EAOd,eAAY,SAAmB,YAAU,QAAQ;EAQjD,kBAAe,SAAmB,YAAU;EAI5C,aAAoB,mBAAiB,SAC1B,SAAO,QACR,MACP,QAAQ,iBAAiB,UAAU;EAStC,gBAAa,sBAA8B;EAI3C,eAAY,WAAqB,cAAY,QAAQ;EAKrD,yBAAsB,0BAAkC,QAAQ"}
@@ -1,7 +1,7 @@
1
1
  import { Principal } from "../core/index.mjs";
2
2
  import { Session } from "../session/types.mjs";
3
3
  import { EmailSender } from "./email-codes.mjs";
4
- import { AuthConfig, AuthService, AuthorizedHandler, LoggedHandler, OAuth2AuthorizationOptions } from "./types.mjs";
4
+ import { AuthConfig, AuthService, AuthorizedHandler, LoggedHandler, LogoutOptions, OAuth2AuthorizationOptions } from "./types.mjs";
5
5
  export declare const PATH: {
6
6
  readonly CSRF: '/csrf';
7
7
  readonly LOGOUT: '/logout';
@@ -35,7 +35,8 @@ export declare class Auth implements AuthService {
35
35
  private readonly emailCodes;
36
36
  private readonly desktopCodes;
37
37
  private readonly oauth2Client;
38
- private readonly onetapRequireNonce;
38
+ /** Provider keys whose logins may come without a nonce (`oauth2.nonce.optional`). */
39
+ private readonly nonceOptional;
39
40
  private readonly touchInterval;
40
41
  private readonly sessionHeader;
41
42
  private readonly ATTR_OAUTH2_AUTHORIZATION_REQUEST;
@@ -63,7 +64,7 @@ export declare class Auth implements AuthService {
63
64
  /** The error redirect of the callback flow; `refusal`'s reason and metadata ride along. */
64
65
  private redirect;
65
66
  csrf: (_request: Request) => Promise<Response>;
66
- logout: (request: Request) => Promise<Response>;
67
+ logout: (request: Request, options?: LogoutOptions) => Promise<Response>;
67
68
  logged: (request: Request, onLogged?: LoggedHandler) => Promise<Response>;
68
69
  private createPkceParameters;
69
70
  private getOauth2StateKey;
@@ -74,6 +75,14 @@ export declare class Auth implements AuthService {
74
75
  * it sign in once.
75
76
  */
76
77
  private consumeNonce;
78
+ /**
79
+ * The nonce check of the JSON logins (One Tap, native), where the client obtained the id token
80
+ * and the nonce came from `oauth2Nonce`: spends the one the token carries, and refuses a token
81
+ * without one when the provider's flow echoes nonces (`required`) and the host has not listed the
82
+ * provider as optional. An id token is replayable until it expires; the nonce makes it sign in
83
+ * once.
84
+ */
85
+ private checkIssuedNonce;
77
86
  oauth2State: (request: Request) => Promise<Response>;
78
87
  oauth2Nonce: (request: Request) => Promise<Response>;
79
88
  oauth2Authorization: (request: Request, options?: OAuth2AuthorizationOptions) => Promise<Response>;