@workos/authkit-session 0.3.4 → 0.5.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 (88) hide show
  1. package/README.md +111 -27
  2. package/dist/core/AuthKitCore.d.ts +20 -0
  3. package/dist/core/AuthKitCore.d.ts.map +1 -1
  4. package/dist/core/AuthKitCore.js +36 -4
  5. package/dist/core/AuthKitCore.js.map +1 -1
  6. package/dist/core/encryption/ironWebcryptoEncryption.d.ts +2 -1
  7. package/dist/core/encryption/ironWebcryptoEncryption.d.ts.map +1 -1
  8. package/dist/core/encryption/ironWebcryptoEncryption.js +2 -2
  9. package/dist/core/encryption/ironWebcryptoEncryption.js.map +1 -1
  10. package/dist/core/errors.d.ts +9 -0
  11. package/dist/core/errors.d.ts.map +1 -1
  12. package/dist/core/errors.js +18 -0
  13. package/dist/core/errors.js.map +1 -1
  14. package/dist/core/pkce/cookieName.d.ts +17 -0
  15. package/dist/core/pkce/cookieName.d.ts.map +1 -0
  16. package/dist/core/pkce/cookieName.js +26 -0
  17. package/dist/core/pkce/cookieName.js.map +1 -0
  18. package/dist/core/pkce/cookieOptions.d.ts +34 -0
  19. package/dist/core/pkce/cookieOptions.d.ts.map +1 -0
  20. package/dist/core/pkce/cookieOptions.js +53 -0
  21. package/dist/core/pkce/cookieOptions.js.map +1 -0
  22. package/dist/core/pkce/generateAuthorizationUrl.d.ts +46 -0
  23. package/dist/core/pkce/generateAuthorizationUrl.d.ts.map +1 -0
  24. package/dist/core/pkce/generateAuthorizationUrl.js +85 -0
  25. package/dist/core/pkce/generateAuthorizationUrl.js.map +1 -0
  26. package/dist/core/pkce/state.d.ts +53 -0
  27. package/dist/core/pkce/state.d.ts.map +1 -0
  28. package/dist/core/pkce/state.js +91 -0
  29. package/dist/core/pkce/state.js.map +1 -0
  30. package/dist/core/session/CookieSessionStorage.d.ts +25 -15
  31. package/dist/core/session/CookieSessionStorage.d.ts.map +1 -1
  32. package/dist/core/session/CookieSessionStorage.js +20 -27
  33. package/dist/core/session/CookieSessionStorage.js.map +1 -1
  34. package/dist/core/session/TokenManager.js +2 -2
  35. package/dist/core/session/TokenManager.js.map +1 -1
  36. package/dist/core/session/serializeCookie.d.ts +13 -0
  37. package/dist/core/session/serializeCookie.d.ts.map +1 -0
  38. package/dist/core/session/serializeCookie.js +32 -0
  39. package/dist/core/session/serializeCookie.js.map +1 -0
  40. package/dist/core/session/types.d.ts +76 -2
  41. package/dist/core/session/types.d.ts.map +1 -1
  42. package/dist/index.d.ts +2 -1
  43. package/dist/index.d.ts.map +1 -1
  44. package/dist/index.js +5 -1
  45. package/dist/index.js.map +1 -1
  46. package/dist/operations/AuthOperations.d.ts +15 -13
  47. package/dist/operations/AuthOperations.d.ts.map +1 -1
  48. package/dist/operations/AuthOperations.js +22 -34
  49. package/dist/operations/AuthOperations.js.map +1 -1
  50. package/dist/service/AuthService.d.ts +64 -15
  51. package/dist/service/AuthService.d.ts.map +1 -1
  52. package/dist/service/AuthService.js +171 -70
  53. package/dist/service/AuthService.js.map +1 -1
  54. package/dist/service/factory.d.ts.map +1 -1
  55. package/dist/service/factory.js +4 -3
  56. package/dist/service/factory.js.map +1 -1
  57. package/dist/utils.d.ts +16 -0
  58. package/dist/utils.d.ts.map +1 -1
  59. package/dist/utils.js +23 -0
  60. package/dist/utils.js.map +1 -1
  61. package/package.json +23 -20
  62. package/src/core/AuthKitCore.spec.ts +109 -0
  63. package/src/core/AuthKitCore.ts +55 -4
  64. package/src/core/encryption/ironWebcryptoEncryption.spec.ts +62 -0
  65. package/src/core/encryption/ironWebcryptoEncryption.ts +2 -2
  66. package/src/core/errors.spec.ts +33 -142
  67. package/src/core/errors.ts +21 -0
  68. package/src/core/pkce/cookieName.spec.ts +56 -0
  69. package/src/core/pkce/cookieName.ts +27 -0
  70. package/src/core/pkce/cookieOptions.spec.ts +144 -0
  71. package/src/core/pkce/cookieOptions.ts +61 -0
  72. package/src/core/pkce/generateAuthorizationUrl.ts +123 -0
  73. package/src/core/pkce/pkce.spec.ts +175 -0
  74. package/src/core/pkce/state.spec.ts +216 -0
  75. package/src/core/pkce/state.ts +120 -0
  76. package/src/core/session/CookieSessionStorage.spec.ts +79 -3
  77. package/src/core/session/CookieSessionStorage.ts +56 -36
  78. package/src/core/session/TokenManager.ts +2 -2
  79. package/src/core/session/serializeCookie.ts +33 -0
  80. package/src/core/session/types.ts +83 -2
  81. package/src/index.ts +11 -0
  82. package/src/operations/AuthOperations.spec.ts +107 -62
  83. package/src/operations/AuthOperations.ts +34 -40
  84. package/src/service/AuthService.spec.ts +750 -97
  85. package/src/service/AuthService.ts +210 -72
  86. package/src/service/factory.spec.ts +4 -3
  87. package/src/service/factory.ts +6 -3
  88. package/src/utils.ts +22 -0
@@ -0,0 +1,46 @@
1
+ import type { WorkOS } from '@workos-inc/node';
2
+ import type { AuthKitConfig } from '../config/types.js';
3
+ import type { CookieOptions, GetAuthorizationUrlOptions, SessionEncryption } from '../session/types.js';
4
+ /**
5
+ * Maximum UTF-8 byte length for caller-supplied `options.state`. Enforced
6
+ * as an early, user-facing check so large custom state fails with a clear
7
+ * error before any crypto work — ahead of the authoritative sealed-cookie
8
+ * length guard below.
9
+ */
10
+ export declare const PKCE_MAX_STATE_BYTES = 2048;
11
+ /**
12
+ * Maximum serialized `Set-Cookie` header length (bytes) for the verifier.
13
+ * Browsers start dropping cookies past ~4096 bytes per RFC 6265; 3800
14
+ * leaves headroom for proxies that cap lower and for the handful of
15
+ * cookie attributes whose size isn't known until serialization time
16
+ * (notably `Domain=` when `cookieDomain` is set).
17
+ */
18
+ export declare const PKCE_MAX_COOKIE_BYTES = 3800;
19
+ /**
20
+ * Internal authorization-URL generation result.
21
+ *
22
+ * Not exported: AuthService consumes `sealedState` + `cookieOptions` to write
23
+ * the verifier cookie via `storage.setCookie`, then returns only `{ url, response?, headers? }`
24
+ * to callers.
25
+ */
26
+ export interface GeneratedAuthorizationUrl {
27
+ url: string;
28
+ sealedState: string;
29
+ cookieName: string;
30
+ cookieOptions: CookieOptions;
31
+ }
32
+ /**
33
+ * Generate a WorkOS authorization URL bound to a PKCE verifier.
34
+ *
35
+ * Returns the URL, the sealed state blob (used as both the OAuth `state`
36
+ * query param AND the cookie value — identical string; the callback does a
37
+ * byte-compare before decrypting), and the cookie options the verifier
38
+ * cookie should be written with.
39
+ */
40
+ export declare function generateAuthorizationUrl(params: {
41
+ client: WorkOS;
42
+ config: AuthKitConfig;
43
+ encryption: SessionEncryption;
44
+ options: GetAuthorizationUrlOptions;
45
+ }): Promise<GeneratedAuthorizationUrl>;
46
+ //# sourceMappingURL=generateAuthorizationUrl.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generateAuthorizationUrl.d.ts","sourceRoot":"","sources":["../../../src/core/pkce/generateAuthorizationUrl.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAGxD,OAAO,KAAK,EACV,aAAa,EACb,0BAA0B,EAC1B,iBAAiB,EAClB,MAAM,qBAAqB,CAAC;AAK7B;;;;;GAKG;AACH,eAAO,MAAM,oBAAoB,OAAO,CAAC;AAEzC;;;;;;GAMG;AACH,eAAO,MAAM,qBAAqB,OAAO,CAAC;AAE1C;;;;;;GAMG;AACH,MAAM,WAAW,yBAAyB;IACxC,GAAG,EAAE,MAAM,CAAC;IACZ,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,EAAE,MAAM,CAAC;IACnB,aAAa,EAAE,aAAa,CAAC;CAC9B;AAED;;;;;;;GAOG;AACH,wBAAsB,wBAAwB,CAAC,MAAM,EAAE;IACrD,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,aAAa,CAAC;IACtB,UAAU,EAAE,iBAAiB,CAAC;IAC9B,OAAO,EAAE,0BAA0B,CAAC;CACrC,GAAG,OAAO,CAAC,yBAAyB,CAAC,CAiErC"}
@@ -0,0 +1,85 @@
1
+ import { PKCEPayloadTooLargeError } from '../errors.js';
2
+ import { serializeCookie } from '../session/serializeCookie.js';
3
+ import { getPKCECookieNameForState } from './cookieName.js';
4
+ import { getPKCECookieOptions } from './cookieOptions.js';
5
+ import { sealState } from './state.js';
6
+ /**
7
+ * Maximum UTF-8 byte length for caller-supplied `options.state`. Enforced
8
+ * as an early, user-facing check so large custom state fails with a clear
9
+ * error before any crypto work — ahead of the authoritative sealed-cookie
10
+ * length guard below.
11
+ */
12
+ export const PKCE_MAX_STATE_BYTES = 2048;
13
+ /**
14
+ * Maximum serialized `Set-Cookie` header length (bytes) for the verifier.
15
+ * Browsers start dropping cookies past ~4096 bytes per RFC 6265; 3800
16
+ * leaves headroom for proxies that cap lower and for the handful of
17
+ * cookie attributes whose size isn't known until serialization time
18
+ * (notably `Domain=` when `cookieDomain` is set).
19
+ */
20
+ export const PKCE_MAX_COOKIE_BYTES = 3800;
21
+ /**
22
+ * Generate a WorkOS authorization URL bound to a PKCE verifier.
23
+ *
24
+ * Returns the URL, the sealed state blob (used as both the OAuth `state`
25
+ * query param AND the cookie value — identical string; the callback does a
26
+ * byte-compare before decrypting), and the cookie options the verifier
27
+ * cookie should be written with.
28
+ */
29
+ export async function generateAuthorizationUrl(params) {
30
+ const { client, config, encryption, options } = params;
31
+ const redirectUri = options.redirectUri ?? config.redirectUri;
32
+ // Early bound on caller-supplied `state` so oversized input fails with a
33
+ // clear error before any crypto work. The authoritative guard on the
34
+ // serialized cookie runs below — this one just avoids confusing users.
35
+ if (options.state !== undefined) {
36
+ const stateBytes = new TextEncoder().encode(options.state).byteLength;
37
+ if (stateBytes > PKCE_MAX_STATE_BYTES) {
38
+ throw new PKCEPayloadTooLargeError(`Custom OAuth state is ${stateBytes} bytes, exceeds supported limit of ${PKCE_MAX_STATE_BYTES} bytes. ` +
39
+ `The sealed state is stored as the wos-auth-verifier cookie; oversized values would be silently dropped by the browser.`);
40
+ }
41
+ }
42
+ const pkce = await client.pkce.generate();
43
+ const nonce = crypto.randomUUID();
44
+ const sealedState = await sealState(encryption, config.cookiePassword, {
45
+ nonce,
46
+ codeVerifier: pkce.codeVerifier,
47
+ returnPathname: options.returnPathname,
48
+ customState: options.state,
49
+ // Persisted so handleCallback's verifier-delete cookie uses the same
50
+ // computed attributes as the original setCookie — notably `secure`,
51
+ // which depends on the redirect URI's protocol.
52
+ redirectUri: options.redirectUri,
53
+ });
54
+ // Authoritative guard: measure the actual Set-Cookie header the adapter
55
+ // will emit. Catches cases the input-only check can't, like oversized
56
+ // returnPathname combined with near-max state, or an unusually long
57
+ // cookieDomain attribute.
58
+ const cookieOptions = getPKCECookieOptions(config, redirectUri);
59
+ const cookieName = getPKCECookieNameForState(sealedState);
60
+ const serialized = serializeCookie(cookieName, sealedState, cookieOptions);
61
+ const cookieBytes = new TextEncoder().encode(serialized).byteLength;
62
+ if (cookieBytes > PKCE_MAX_COOKIE_BYTES) {
63
+ throw new PKCEPayloadTooLargeError(`Sealed PKCE verifier cookie is ${cookieBytes} bytes, exceeds supported limit of ${PKCE_MAX_COOKIE_BYTES} bytes. ` +
64
+ `Reduce the size of options.state, options.returnPathname, or options.redirectUri.`);
65
+ }
66
+ const url = client.userManagement.getAuthorizationUrl({
67
+ provider: 'authkit',
68
+ clientId: config.clientId,
69
+ redirectUri,
70
+ screenHint: options.screenHint,
71
+ organizationId: options.organizationId,
72
+ loginHint: options.loginHint,
73
+ prompt: options.prompt,
74
+ state: sealedState,
75
+ codeChallenge: pkce.codeChallenge,
76
+ codeChallengeMethod: pkce.codeChallengeMethod,
77
+ });
78
+ return {
79
+ url,
80
+ sealedState,
81
+ cookieName,
82
+ cookieOptions,
83
+ };
84
+ }
85
+ //# sourceMappingURL=generateAuthorizationUrl.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generateAuthorizationUrl.js","sourceRoot":"","sources":["../../../src/core/pkce/generateAuthorizationUrl.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,wBAAwB,EAAE,MAA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AAC,cAAc;QACtC,WAAW,EAAE,OAAO,CAAC,KAAK;QAC1B,qEAAqE;QACrE,oEAAoE;QACpE,gDAAgD;QAChD,WAAW,EAAE,OAAO,CAAC,WAAW;KACjC,CAAC,CAAC;IAEH,wEAAwE;IACxE,sEAAsE;IACtE,oEAAoE;IACpE,0BAA0B;IAC1B,MAAM,aAAa,GAAG,oBAAoB,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC;IAChE,MAAM,UAAU,GAAG,yBAAyB,CAAC,WAAW,CAAC,CAAC;IAC1D,MAAM,UAAU,GAAG,eAAe,CAAC,UAAU,EAAE,WAAW,EAAE,aAAa,CAAC,CAAC;IAC3E,MAAM,WAAW,GAAG,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,UAAU,CAAC;IACpE,IAAI,WAAW,GAAG,qBAAqB,EAAE,CAAC;QACxC,MAAM,IAAI,wBAAwB,CAChC,kCAAkC,WAAW,sCAAsC,qBAAqB,UAAU;YAChH,mFAAmF,CACtF,CAAC;IACJ,CAAC;IAED,MAAM,GAAG,GAAG,MAAM,CAAC,cAAc,CAAC,mBAAmB,CAAC;QACpD,QAAQ,EAAE,SAAS;QACnB,QAAQ,EAAE,MAAM,CAAC,QAAQ;QACzB,WAAW;QACX,UAAU,EAAE,OAAO,CAAC,UAAU;QAC9B,cAAc,EAAE,OAAO,CAAC,cAAc;QACtC,SAAS,EAAE,OAAO,CAAC,SAAS;QAC5B,MAAM,EAAE,OAAO,CAAC,MAAM;QACtB,KAAK,EAAE,WAAW;QAClB,aAAa,EAAE,IAAI,CAAC,aAAa;QACjC,mBAAmB,EAAE,IAAI,CAAC,mBAAmB;KAC9C,CAAC,CAAC;IAEH,OAAO;QACL,GAAG;QACH,WAAW;QACX,UAAU;QACV,aAAa;KACd,CAAC;AACJ,CAAC"}
@@ -0,0 +1,53 @@
1
+ import * as v from 'valibot';
2
+ import type { SessionEncryption } from '../session/types.js';
3
+ /**
4
+ * Runtime schema for the sealed PKCE state blob.
5
+ *
6
+ * Validated at unseal time as defense-in-depth against any future code path
7
+ * accidentally sealing the wrong shape. Shape mismatch is treated as an
8
+ * integrity failure (same category as a tampered blob).
9
+ *
10
+ * `issuedAt` (ms since epoch) lets `unsealState` enforce the TTL on its own
11
+ * rather than trusting the encryption adapter's `ttl` handling. Custom
12
+ * `SessionEncryption` implementations may silently ignore the `ttl` field —
13
+ * the payload-level age check closes that gap.
14
+ */
15
+ export declare const StateSchema: v.ObjectSchema<{
16
+ readonly nonce: v.StringSchema<undefined>;
17
+ readonly codeVerifier: v.StringSchema<undefined>;
18
+ readonly issuedAt: v.NumberSchema<undefined>;
19
+ readonly returnPathname: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
20
+ readonly customState: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
21
+ /**
22
+ * The per-request `redirectUri` override resolved at sign-in time, if the
23
+ * caller supplied one. Persisted so `handleCallback` can recompute the
24
+ * exact cookie options used at `setCookie` time — notably `secure`, which
25
+ * is inferred from the redirect URI's protocol. Omitted when the caller
26
+ * relied on the configured default.
27
+ */
28
+ readonly redirectUri: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
29
+ }, undefined>;
30
+ export type PKCEState = v.InferOutput<typeof StateSchema>;
31
+ export type PKCEStateInput = Omit<PKCEState, 'issuedAt'>;
32
+ /**
33
+ * Seal a PKCE state object for use as both the OAuth `state` query param
34
+ * and the `wos-auth-verifier` cookie value. Seal embeds a 600s TTL and
35
+ * stamps `issuedAt` so the unseal path can enforce age independently.
36
+ */
37
+ export declare function sealState(encryption: SessionEncryption, password: string, state: PKCEStateInput): Promise<string>;
38
+ /**
39
+ * Unseal a PKCE state blob, enforcing TTL and shape.
40
+ *
41
+ * Age is verified twice:
42
+ * 1. The encryption adapter's `ttl` check (iron-webcrypto enforces this by
43
+ * default — custom adapters MAY ignore it).
44
+ * 2. A payload-level `issuedAt` comparison against `Date.now()`. This is the
45
+ * authoritative check — it runs regardless of how the adapter treats
46
+ * `ttl`.
47
+ *
48
+ * Any failure — expired TTL, tamper, wrong password, or schema mismatch —
49
+ * is wrapped as `SessionEncryptionError`. Callers differentiate via the
50
+ * `cause` chain, not the message string.
51
+ */
52
+ export declare function unsealState(encryption: SessionEncryption, password: string, sealed: string): Promise<PKCEState>;
53
+ //# sourceMappingURL=state.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"state.d.ts","sourceRoot":"","sources":["../../../src/core/pkce/state.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,CAAC,MAAM,SAAS,CAAC;AAE7B,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAgB7D;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,WAAW;;;;;;IAMtB;;;;;;OAMG;;aAEH,CAAC;AAEH,MAAM,MAAM,SAAS,GAAG,CAAC,CAAC,WAAW,CAAC,OAAO,WAAW,CAAC,CAAC;AAE1D,MAAM,MAAM,cAAc,GAAG,IAAI,CAAC,SAAS,EAAE,UAAU,CAAC,CAAC;AAEzD;;;;GAIG;AACH,wBAAsB,SAAS,CAC7B,UAAU,EAAE,iBAAiB,EAC7B,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE,cAAc,GACpB,OAAO,CAAC,MAAM,CAAC,CAQjB;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAsB,WAAW,CAC/B,UAAU,EAAE,iBAAiB,EAC7B,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,MAAM,GACb,OAAO,CAAC,SAAS,CAAC,CAgCpB"}
@@ -0,0 +1,91 @@
1
+ import * as v from 'valibot';
2
+ import { SessionEncryptionError } from '../errors.js';
3
+ import { PKCE_COOKIE_MAX_AGE } from './cookieOptions.js';
4
+ /**
5
+ * Clock-skew tolerance (ms) for the payload-level `issuedAt` check.
6
+ *
7
+ * Applied asymmetrically, only to the negative (future-`issuedAt`) side:
8
+ * allows a sign-in issued on node A to be verified on node B whose clock
9
+ * is up to 60s behind without failing a legitimate callback. The upper
10
+ * bound (expiry) is strict — `PKCE_COOKIE_MAX_AGE` with no grace — so
11
+ * this payload check is always at least as strict as iron-webcrypto's
12
+ * symmetric 60s skew on `ttl`, making it the authoritative expiry guard
13
+ * regardless of how a custom `SessionEncryption` adapter treats `ttl`.
14
+ */
15
+ const PKCE_CLOCK_SKEW_MS = 60_000;
16
+ /**
17
+ * Runtime schema for the sealed PKCE state blob.
18
+ *
19
+ * Validated at unseal time as defense-in-depth against any future code path
20
+ * accidentally sealing the wrong shape. Shape mismatch is treated as an
21
+ * integrity failure (same category as a tampered blob).
22
+ *
23
+ * `issuedAt` (ms since epoch) lets `unsealState` enforce the TTL on its own
24
+ * rather than trusting the encryption adapter's `ttl` handling. Custom
25
+ * `SessionEncryption` implementations may silently ignore the `ttl` field —
26
+ * the payload-level age check closes that gap.
27
+ */
28
+ export const StateSchema = v.object({
29
+ nonce: v.string(),
30
+ codeVerifier: v.string(),
31
+ issuedAt: v.number(),
32
+ returnPathname: v.optional(v.string()),
33
+ customState: v.optional(v.string()),
34
+ /**
35
+ * The per-request `redirectUri` override resolved at sign-in time, if the
36
+ * caller supplied one. Persisted so `handleCallback` can recompute the
37
+ * exact cookie options used at `setCookie` time — notably `secure`, which
38
+ * is inferred from the redirect URI's protocol. Omitted when the caller
39
+ * relied on the configured default.
40
+ */
41
+ redirectUri: v.optional(v.string()),
42
+ });
43
+ /**
44
+ * Seal a PKCE state object for use as both the OAuth `state` query param
45
+ * and the `wos-auth-verifier` cookie value. Seal embeds a 600s TTL and
46
+ * stamps `issuedAt` so the unseal path can enforce age independently.
47
+ */
48
+ export async function sealState(encryption, password, state) {
49
+ return encryption.sealData({ ...state, issuedAt: Date.now() }, {
50
+ password,
51
+ ttl: PKCE_COOKIE_MAX_AGE,
52
+ });
53
+ }
54
+ /**
55
+ * Unseal a PKCE state blob, enforcing TTL and shape.
56
+ *
57
+ * Age is verified twice:
58
+ * 1. The encryption adapter's `ttl` check (iron-webcrypto enforces this by
59
+ * default — custom adapters MAY ignore it).
60
+ * 2. A payload-level `issuedAt` comparison against `Date.now()`. This is the
61
+ * authoritative check — it runs regardless of how the adapter treats
62
+ * `ttl`.
63
+ *
64
+ * Any failure — expired TTL, tamper, wrong password, or schema mismatch —
65
+ * is wrapped as `SessionEncryptionError`. Callers differentiate via the
66
+ * `cause` chain, not the message string.
67
+ */
68
+ export async function unsealState(encryption, password, sealed) {
69
+ let raw;
70
+ try {
71
+ raw = await encryption.unsealData(sealed, {
72
+ password,
73
+ ttl: PKCE_COOKIE_MAX_AGE,
74
+ });
75
+ }
76
+ catch (cause) {
77
+ throw new SessionEncryptionError('Failed to unseal PKCE state', cause);
78
+ }
79
+ const result = v.safeParse(StateSchema, raw);
80
+ if (!result.success) {
81
+ throw new SessionEncryptionError('Malformed PKCE state payload', result.issues);
82
+ }
83
+ const ageMs = Date.now() - result.output.issuedAt;
84
+ if (ageMs < -PKCE_CLOCK_SKEW_MS || ageMs > PKCE_COOKIE_MAX_AGE * 1000) {
85
+ // Attach age context so production logs can diagnose clock-skew issues
86
+ // via the `cause` chain without leaking the sealed blob itself.
87
+ throw new SessionEncryptionError('PKCE state expired', new Error(`age=${ageMs}ms, maxAge=${PKCE_COOKIE_MAX_AGE * 1000}ms, skew=±${PKCE_CLOCK_SKEW_MS}ms`));
88
+ }
89
+ return result.output;
90
+ }
91
+ //# sourceMappingURL=state.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"state.js","sourceRoot":"","sources":["../../../src/core/pkce/state.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,CAAC,MAAM,SAAS,CAAC;AAC7B,OAAO,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC;AAEtD,OAAO,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AAEzD;;;;;;;;;;GAUG;AACH,MAAM,kBAAkB,GAAG,MAAM,CAAC;AAElC;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,CAAC,CAAC,MAAM,CA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AC;IACJ,CAAC;IAED,MAAM,KAAK,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC;IAClD,IAAI,KAAK,GAAG,CAAC,kBAAkB,IAAI,KAAK,GAAG,mBAAmB,GAAG,IAAI,EAAE,CAAC;QACtE,uEAAuE;QACvE,gEAAgE;QAChE,MAAM,IAAI,sBAAsB,CAC9B,oBAAoB,EACpB,IAAI,KAAK,CACP,OAAO,KAAK,cAAc,mBAAmB,GAAG,IAAI,aAAa,kBAAkB,IAAI,CACxF,CACF,CAAC;IACJ,CAAC;IAED,OAAO,MAAM,CAAC,MAAM,CAAC;AACvB,CAAC"}
@@ -1,16 +1,6 @@
1
1
  import type { AuthKitConfig } from '../config/types.js';
2
- import type { HeadersBag, SessionStorage } from './types.js';
3
- export interface CookieOptions {
4
- path?: string;
5
- domain?: string;
6
- maxAge?: number;
7
- expires?: Date;
8
- httpOnly?: boolean;
9
- secure?: boolean;
10
- sameSite?: 'lax' | 'strict' | 'none';
11
- priority?: 'low' | 'medium' | 'high';
12
- partitioned?: boolean;
13
- }
2
+ import type { CookieOptions, HeadersBag, SessionStorage } from './types.js';
3
+ export type { CookieOptions } from './types.js';
14
4
  export declare abstract class CookieSessionStorage<TRequest, TResponse> implements SessionStorage<TRequest, TResponse> {
15
5
  protected cookieName: string;
16
6
  protected readonly cookieOptions: CookieOptions;
@@ -18,13 +8,33 @@ export declare abstract class CookieSessionStorage<TRequest, TResponse> implemen
18
8
  protected applyHeaders(_response: TResponse | undefined, _headers: HeadersBag): Promise<{
19
9
  response: TResponse;
20
10
  } | void>;
21
- protected buildSetCookie(value: string, expired?: boolean): string;
22
- abstract getSession(request: TRequest): Promise<string | null>;
11
+ protected serializeCookie(name: string, value: string, options: CookieOptions, flags?: {
12
+ expired?: boolean;
13
+ }): string;
14
+ /**
15
+ * Read a named cookie from the framework-specific request.
16
+ *
17
+ * Implementations MUST return the URL-decoded value — the inverse of
18
+ * `serializeCookie`'s `encodeURIComponent` on write. Returning the raw
19
+ * on-wire bytes will silently break byte-comparison against the original
20
+ * value (e.g. PKCE state verification) for any seal containing characters
21
+ * that `encodeURIComponent` escapes.
22
+ */
23
+ abstract getCookie(request: TRequest, name: string): Promise<string | null>;
24
+ setCookie(response: TResponse | undefined, name: string, value: string, options: CookieOptions): Promise<{
25
+ response?: TResponse;
26
+ headers?: HeadersBag;
27
+ }>;
28
+ clearCookie(response: TResponse | undefined, name: string, options: CookieOptions): Promise<{
29
+ response?: TResponse;
30
+ headers?: HeadersBag;
31
+ }>;
32
+ getSession(request: TRequest): Promise<string | null>;
23
33
  saveSession(response: TResponse | undefined, sessionData: string): Promise<{
24
34
  response?: TResponse;
25
35
  headers?: HeadersBag;
26
36
  }>;
27
- clearSession(response: TResponse): Promise<{
37
+ clearSession(response: TResponse | undefined): Promise<{
28
38
  response?: TResponse;
29
39
  headers?: HeadersBag;
30
40
  }>;
@@ -1 +1 @@
1
- {"version":3,"file":"CookieSessionStorage.d.ts","sourceRoot":"","sources":["../../../src/core/session/CookieSessionStorage.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACxD,OAAO,KAAK,EAAE,UAAU,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAE7D,MAAM,WAAW,aAAa;IAC5B,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,IAAI,CAAC;IACf,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,QAAQ,CAAC,EAAE,KAAK,GAAG,QAAQ,GAAG,MAAM,CAAC;IACrC,QAAQ,CAAC,EAAE,KAAK,GAAG,QAAQ,GAAG,MAAM,CAAC;IACrC,WAAW,CAAC,EAAE,OAAO,CAAC;CACvB;AAED,8BAAsB,oB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,OAAO,CAAC,EAAE,UAAU,CAAA;KAAE,CAAC;IAS1D,YAAY,CACV,QAAQ,EAAE,SAAS,GAAG,SAAS,GAC9B,OAAO,CAAC;QAAE,QAAQ,CAAC,EAAE,SAAS,CAAC;QAAC,OAAO,CAAC,EAAE,UAAU,CAAA;KAAE,CAAC;CAG3D"}
@@ -1,8 +1,12 @@
1
+ import { serializeCookie } from './serializeCookie.js';
1
2
  export class CookieSessionStorage {
2
3
  cookieName;
3
4
  cookieOptions;
4
5
  constructor(config) {
5
- this.cookieName = config.cookieName ?? 'wos_session';
6
+ // Matches the canonical default in ConfigurationProvider. This fallback
7
+ // only fires when a caller instantiates the class with a config that
8
+ // hasn't been resolved through the provider.
9
+ this.cookieName = config.cookieName ?? 'wos-session';
6
10
  const sameSite = config.cookieSameSite ?? 'lax';
7
11
  // Infer secure flag from redirectUri protocol
8
12
  // sameSite='none' requires secure=true (browser requirement)
@@ -28,38 +32,27 @@ export class CookieSessionStorage {
28
32
  async applyHeaders(_response, _headers) {
29
33
  /* default no-op. Adapters can override if they CAN mutate a native response */
30
34
  }
31
- buildSetCookie(value, expired) {
32
- const a = [`${this.cookieName}=${encodeURIComponent(value)}`];
33
- const o = this.cookieOptions;
34
- if (o.path)
35
- a.push(`Path=${o.path}`);
36
- if (o.domain)
37
- a.push(`Domain=${o.domain}`);
38
- if (o.maxAge || expired)
39
- a.push(`Max-Age=${expired ? 0 : o.maxAge}`);
40
- if (o.httpOnly)
41
- a.push('HttpOnly');
42
- if (o.secure)
43
- a.push('Secure');
44
- if (o.sameSite) {
45
- const capitalizedSameSite = o.sameSite.charAt(0).toUpperCase() + o.sameSite.slice(1).toLowerCase();
46
- a.push(`SameSite=${capitalizedSameSite}`);
47
- }
48
- if (o.priority)
49
- a.push(`Priority=${o.priority}`);
50
- if (o.partitioned)
51
- a.push('Partitioned');
52
- return a.join('; ');
35
+ serializeCookie(name, value, options, flags = {}) {
36
+ return serializeCookie(name, value, options, flags);
53
37
  }
54
- async saveSession(response, sessionData) {
55
- const header = this.buildSetCookie(sessionData);
38
+ async setCookie(response, name, value, options) {
39
+ const header = this.serializeCookie(name, value, options);
56
40
  const mutated = await this.applyHeaders(response, { 'Set-Cookie': header });
57
41
  return mutated ?? { headers: { 'Set-Cookie': header } };
58
42
  }
59
- async clearSession(response) {
60
- const header = this.buildSetCookie('', true);
43
+ async clearCookie(response, name, options) {
44
+ const header = this.serializeCookie(name, '', options, { expired: true });
61
45
  const mutated = await this.applyHeaders(response, { 'Set-Cookie': header });
62
46
  return mutated ?? { headers: { 'Set-Cookie': header } };
63
47
  }
48
+ getSession(request) {
49
+ return this.getCookie(request, this.cookieName);
50
+ }
51
+ saveSession(response, sessionData) {
52
+ return this.setCookie(response, this.cookieName, sessionData, this.cookieOptions);
53
+ }
54
+ clearSession(response) {
55
+ return this.clearCookie(response, this.cookieName, this.cookieOptions);
56
+ }
64
57
  }
65
58
  //# sourceMappingURL=CookieSessionStorage.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"CookieSessionStorage.js","sourceRoot":"","sources":["../../../src/core/session/CookieSessionStorage.ts"],"names":[],"mappings":"AAeA,MAAM,OAAgB,oBAAoB;IAI9B,UAAU,CAAS;IACV,aAAa,CAAgB;IAEhD,YAAY,MAAqB;QAC/B,IAAI,CAAC,UAAU,GAAG,MAAM,CAAC,UAAU,IAAI,aAAa,CAAC;QAErD,MAAM,QAAQ,GAAG,MAAM,CAAC,cAAc,IAAI,KAAK,CAAC;QAEhD,8CAA8C;QAC9C,6DAA6D;QAC7D,IAAI,MAAM,GAAG,IAAI,CAAC;QAClB,IAAI,QAAQ,CAAC,WAAW,EAAE,KAAK,MAAM,EAAE,CAAC;YACtC,IAAI,CAAC;gBACH,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;gBACxC,MAAM,GAAG,GAAG,CAAC,QAAQ,KAAK,QAAQ,CAAC;YACrC,CAAC;YAAC,MAAM,CAAC;gBACP,iDAAiD;Y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AG,MAAM,IAAI,CAAC,YAAY,CAAC,QAAQ,EAAE,EAAE,YAAY,EAAE,MAAM,EAAE,CAAC,CAAC;QAC5E,OAAO,OAAO,IAAI,EAAE,OAAO,EAAE,EAAE,YAAY,EAAE,MAAM,EAAE,EAAE,CAAC;IAC1D,CAAC;IAED,KAAK,CAAC,WAAW,CACf,QAA+B,EAC/B,IAAY,EACZ,OAAsB;QAEtB,MAAM,MAAM,GAAG,IAAI,CAAC,eAAe,CAAC,IAAI,EAAE,EAAE,EAAE,OAAO,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC;QAC1E,MAAM,OAAO,GAAG,MAAM,IAAI,CAAC,YAAY,CAAC,QAAQ,EAAE,EAAE,YAAY,EAAE,MAAM,EAAE,CAAC,CAAC;QAC5E,OAAO,OAAO,IAAI,EAAE,OAAO,EAAE,EAAE,YAAY,EAAE,MAAM,EAAE,EAAE,CAAC;IAC1D,CAAC;IAED,UAAU,CAAC,OAAiB;QAC1B,OAAO,IAAI,CAAC,SAAS,CAAC,OAAO,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC;IAClD,CAAC;IAED,WAAW,CACT,QAA+B,EAC/B,WAAmB;QAEnB,OAAO,IAAI,CAAC,SAAS,CACnB,QAAQ,EACR,IAAI,CAAC,UAAU,EACf,WAAW,EACX,IAAI,CAAC,aAAa,CACnB,CAAC;IACJ,CAAC;IAED,YAAY,CACV,QAA+B;QAE/B,OAAO,IAAI,CAAC,WAAW,CAAC,QAAQ,EAAE,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,aAAa,CAAC,CAAC;IACzE,CAAC;CACF"}
@@ -21,8 +21,8 @@ export class TokenManager {
21
21
  try {
22
22
  return decodeJwt(token);
23
23
  }
24
- catch (error) {
25
- throw new Error('Invalid token');
24
+ catch (cause) {
25
+ throw new Error('Invalid token', { cause });
26
26
  }
27
27
  }
28
28
  isTokenExpiring(token, bufferSeconds) {
@@ -1 +1 @@
1
- {"version":3,"file":"TokenMan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D,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,IAAI,KAAK,CAAC,eAAe,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;QAC9C,CAAC;IACH,CAAC;IAED,eAAe,CAAC,KAAa,EAAE,aAAsB;QACnD,MAAM,UAAU,GAAG,IAAI,CAAC,kBAAkB,CAAC,KAAK,CAAC,CAAC;QAClD,IAAI,CAAC,UAAU,EAAE,CAAC;YAChB,OAAO,KAAK,CAAC;QACf,CAAC;QAED,MAAM,MAAM,GAAG,aAAa,IAAI,EAAE,CAAC,CAAC,sBAAsB;QAC1D,MAAM,WAAW,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,CAAC,CAAC,0BAA0B;QAC7E,OAAO,UAAU,GAAG,WAAW,IAAI,MAAM,CAAC;IAC5C,CAAC;IAED,kBAAkB,CAAC,KAAa;QAC9B,MAAM,MAAM,GAAG,IAAI,CAAC,gBAAgB,CAAC,KAAK,CAAC,CAAC;QAC5C,OAAO,MAAM,CAAC,GAAG,IAAI,IAAI,CAAC;IAC5B,CAAC;CACF;AAED,eAAe,YAAY,CAAC"}
@@ -0,0 +1,13 @@
1
+ import type { CookieOptions } from './types.js';
2
+ /**
3
+ * Serialize a `Set-Cookie` header value from (name, value, options).
4
+ *
5
+ * Shared between `CookieSessionStorage` (writes the header on response) and
6
+ * the PKCE flow's pre-write size guard (must measure the exact bytes the
7
+ * browser will see, including attribute overhead, to detect oversized
8
+ * verifier cookies before they silently get dropped).
9
+ */
10
+ export declare function serializeCookie(name: string, value: string, options: CookieOptions, { expired }?: {
11
+ expired?: boolean;
12
+ }): string;
13
+ //# sourceMappingURL=serializeCookie.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"serializeCookie.d.ts","sourceRoot":"","sources":["../../../src/core/session/serializeCookie.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAEhD;;;;;;;GAOG;AACH,wBAAgB,eAAe,CAC7B,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE,MAAM,EACb,OAAO,EAAE,aAAa,EACtB,EAAE,OAAO,EAAE,GAAE;IAAE,OAAO,CAAC,EAAE,OAAO,CAAA;CAAO,GACtC,MAAM,CAiBR"}
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Serialize a `Set-Cookie` header value from (name, value, options).
3
+ *
4
+ * Shared between `CookieSessionStorage` (writes the header on response) and
5
+ * the PKCE flow's pre-write size guard (must measure the exact bytes the
6
+ * browser will see, including attribute overhead, to detect oversized
7
+ * verifier cookies before they silently get dropped).
8
+ */
9
+ export function serializeCookie(name, value, options, { expired } = {}) {
10
+ const parts = [`${name}=${encodeURIComponent(value)}`];
11
+ if (options.path)
12
+ parts.push(`Path=${options.path}`);
13
+ if (options.domain)
14
+ parts.push(`Domain=${options.domain}`);
15
+ if (options.maxAge != null || expired)
16
+ parts.push(`Max-Age=${expired ? 0 : options.maxAge}`);
17
+ if (options.httpOnly)
18
+ parts.push('HttpOnly');
19
+ if (options.secure)
20
+ parts.push('Secure');
21
+ if (options.sameSite) {
22
+ const capitalized = options.sameSite.charAt(0).toUpperCase() +
23
+ options.sameSite.slice(1).toLowerCase();
24
+ parts.push(`SameSite=${capitalized}`);
25
+ }
26
+ if (options.priority)
27
+ parts.push(`Priority=${options.priority}`);
28
+ if (options.partitioned)
29
+ parts.push('Partitioned');
30
+ return parts.join('; ');
31
+ }
32
+ //# sourceMappingURL=serializeCookie.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"serializeCookie.js","sourceRoot":"","sources":["../../../src/core/session/serializeCookie.ts"],"names":[],"mappings":"AAEA;;;;;;;GAOG;AACH,MAAM,UAAU,eAAe,CAC7B,IAAY,EACZ,KAAa,EACb,OAAsB,EACtB,EAAE,OAAO,KAA4B,EAAE;IAEvC,MAAM,KAAK,GAAG,CAAC,GAAG,IAAI,IAAI,kBAAkB,CAAC,KAAK,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string[]` when multiple values exist
72
+ * — adapters must append each entry as its own header, never comma-join.
73
+ * A comma-joined `Set-Cookie` string is not a valid single HTTP header.
74
+ */
68
75
  export type HeadersBag = Record<string, string | string[]>;
69
76
  export interface SessionStorage<TRequest, TResponse, TOptions = unknown> {
77
+ /**
78
+ * Read a named cookie from a request.
79
+ *
80
+ * MUST return the URL-decoded value (the inverse of `setCookie`'s
81
+ * `encodeURIComponent` on write). Returning raw on-wire bytes will break
82
+ * byte-comparison against the original value — notably PKCE state
83
+ * verification — for any seal format that contains characters
84
+ * `encodeURIComponent` escapes (`+`, `=`, etc.).
85
+ *
86
+ * @param request Framework-specific request object.
87
+ * @param name Cookie name.
88
+ * @returns The URL-decoded cookie value or null if absent.
89
+ */
90
+ getCookie(request: TRequest, name: string): Promise<string | null>;
91
+ /**
92
+ * Write a named cookie to a response.
93
+ * @param response Framework-specific response object (or undefined to emit headers only).
94
+ * @param name Cookie name.
95
+ * @param value Cookie value (will be URL-encoded).
96
+ * @param options Per-call cookie options.
97
+ */
98
+ setCookie(response: TResponse | undefined, name: string, value: string, options: CookieOptions): Promise<{
99
+ response?: TResponse;
100
+ headers?: HeadersBag;
101
+ }>;
102
+ /**
103
+ * Clear a named cookie by emitting a Set-Cookie with Max-Age=0.
104
+ * @param response Framework-specific response object (or undefined to emit headers only).
105
+ * @param name Cookie name.
106
+ * @param options Cookie options (must match those used at set time, especially `path`).
107
+ */
108
+ clearCookie(response: TResponse | undefined, name: string, options: CookieOptions): Promise<{
109
+ response?: TResponse;
110
+ headers?: HeadersBag;
111
+ }>;
70
112
  getSession(request: TRequest): Promise<string | null>;
71
113
  /**
72
114
  * Save session data to a response object.
@@ -95,8 +137,27 @@ export interface SessionEncryption {
95
137
  }) => Promise<string>;
96
138
  unsealData: <T>(encryptedData: string, options: {
97
139
  password: string;
140
+ ttl?: number | undefined;
98
141
  }) => Promise<T>;
99
142
  }
143
+ /**
144
+ * Result shape returned by `createAuthorization` / `createSignIn` / `createSignUp`.
145
+ *
146
+ * The verifier cookie is written internally via `SessionStorage.setCookie` — callers
147
+ * only need to redirect the browser to `url` and apply any returned `headers`/`response`.
148
+ */
149
+ export type CreateAuthorizationResult<TResponse> = {
150
+ url: string;
151
+ response?: TResponse;
152
+ headers?: HeadersBag;
153
+ /**
154
+ * Name of the PKCE verifier cookie written during this call. Useful
155
+ * for assertion-in-tests and for adapters that want to log the flow
156
+ * identifier. NOT the shape `clearPendingVerifier` consumes — that
157
+ * method takes `state`, not `cookieName`.
158
+ */
159
+ cookieName: string;
160
+ };
100
161
  export interface CookieOptions {
101
162
  path?: string;
102
163
  domain?: string;
@@ -117,11 +178,24 @@ export interface AuthUrlOptions {
117
178
  organizationId?: string;
118
179
  loginHint?: string;
119
180
  prompt?: 'login' | 'none' | 'consent' | 'select_account';
120
- /** Custom state to pass through the OAuth flow. Returned in handleCallback. */
181
+ /**
182
+ * Custom state to pass through the OAuth flow. Returned in handleCallback.
183
+ *
184
+ * Bounded at 2048 UTF-8 bytes. The value is sealed alongside the PKCE
185
+ * verifier and stored in the `wos-auth-verifier` cookie; oversized values
186
+ * would push the cookie past the per-cookie browser limit (~4 KB) and
187
+ * would be silently dropped. Values over the supported limit throw
188
+ * `PKCEPayloadTooLargeError` at sign-in time.
189
+ *
190
+ * Note: total sealed payload size — not just `state` — drives the hard
191
+ * failure. Combining a large `returnPathname`, `redirectUri`, or
192
+ * `cookieDomain` with near-limit `state` can still overflow.
193
+ */
121
194
  state?: string;
122
195
  }
123
196
  /**
124
- * Options for getAuthorizationUrl, including screenHint
197
+ * Options for `createAuthorization` / `createSignIn` / `createSignUp`,
198
+ * including the `screenHint` selector used by the sign-in/sign-up variants.
125
199
  */
126
200
  export interface GetAuthorizationUrlOptions extends AuthUrlOptions {
127
201
  screenHint?: 'sign-up' | 'sign-in';