@workos/authkit-session 0.3.2 → 0.4.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 (84) hide show
  1. package/README.md +94 -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/client/types.d.ts.map +1 -1
  7. package/dist/core/encryption/ironWebcryptoEncryption.d.ts +2 -1
  8. package/dist/core/encryption/ironWebcryptoEncryption.d.ts.map +1 -1
  9. package/dist/core/encryption/ironWebcryptoEncryption.js +2 -2
  10. package/dist/core/encryption/ironWebcryptoEncryption.js.map +1 -1
  11. package/dist/core/errors.d.ts +9 -0
  12. package/dist/core/errors.d.ts.map +1 -1
  13. package/dist/core/errors.js +18 -0
  14. package/dist/core/errors.js.map +1 -1
  15. package/dist/core/pkce/cookieOptions.d.ts +36 -0
  16. package/dist/core/pkce/cookieOptions.d.ts.map +1 -0
  17. package/dist/core/pkce/cookieOptions.js +55 -0
  18. package/dist/core/pkce/cookieOptions.js.map +1 -0
  19. package/dist/core/pkce/generateAuthorizationUrl.d.ts +45 -0
  20. package/dist/core/pkce/generateAuthorizationUrl.d.ts.map +1 -0
  21. package/dist/core/pkce/generateAuthorizationUrl.js +82 -0
  22. package/dist/core/pkce/generateAuthorizationUrl.js.map +1 -0
  23. package/dist/core/pkce/state.d.ts +53 -0
  24. package/dist/core/pkce/state.d.ts.map +1 -0
  25. package/dist/core/pkce/state.js +91 -0
  26. package/dist/core/pkce/state.js.map +1 -0
  27. package/dist/core/session/CookieSessionStorage.d.ts +25 -15
  28. package/dist/core/session/CookieSessionStorage.d.ts.map +1 -1
  29. package/dist/core/session/CookieSessionStorage.js +20 -27
  30. package/dist/core/session/CookieSessionStorage.js.map +1 -1
  31. package/dist/core/session/TokenManager.js +2 -2
  32. package/dist/core/session/TokenManager.js.map +1 -1
  33. package/dist/core/session/serializeCookie.d.ts +13 -0
  34. package/dist/core/session/serializeCookie.d.ts.map +1 -0
  35. package/dist/core/session/serializeCookie.js +32 -0
  36. package/dist/core/session/serializeCookie.js.map +1 -0
  37. package/dist/core/session/types.d.ts +71 -2
  38. package/dist/core/session/types.d.ts.map +1 -1
  39. package/dist/index.d.ts +1 -1
  40. package/dist/index.d.ts.map +1 -1
  41. package/dist/index.js +1 -1
  42. package/dist/index.js.map +1 -1
  43. package/dist/operations/AuthOperations.d.ts +15 -13
  44. package/dist/operations/AuthOperations.d.ts.map +1 -1
  45. package/dist/operations/AuthOperations.js +22 -34
  46. package/dist/operations/AuthOperations.js.map +1 -1
  47. package/dist/service/AuthService.d.ts +58 -15
  48. package/dist/service/AuthService.d.ts.map +1 -1
  49. package/dist/service/AuthService.js +157 -71
  50. package/dist/service/AuthService.js.map +1 -1
  51. package/dist/service/factory.d.ts.map +1 -1
  52. package/dist/service/factory.js +4 -3
  53. package/dist/service/factory.js.map +1 -1
  54. package/dist/utils.d.ts +16 -0
  55. package/dist/utils.d.ts.map +1 -1
  56. package/dist/utils.js +23 -0
  57. package/dist/utils.js.map +1 -1
  58. package/package.json +35 -29
  59. package/src/core/AuthKitCore.spec.ts +109 -0
  60. package/src/core/AuthKitCore.ts +55 -4
  61. package/src/core/client/types.ts +3 -6
  62. package/src/core/encryption/ironWebcryptoEncryption.spec.ts +62 -0
  63. package/src/core/encryption/ironWebcryptoEncryption.ts +2 -2
  64. package/src/core/errors.spec.ts +33 -142
  65. package/src/core/errors.ts +21 -0
  66. package/src/core/pkce/cookieOptions.spec.ts +144 -0
  67. package/src/core/pkce/cookieOptions.ts +64 -0
  68. package/src/core/pkce/generateAuthorizationUrl.ts +123 -0
  69. package/src/core/pkce/pkce.spec.ts +166 -0
  70. package/src/core/pkce/state.spec.ts +216 -0
  71. package/src/core/pkce/state.ts +120 -0
  72. package/src/core/session/CookieSessionStorage.spec.ts +79 -3
  73. package/src/core/session/CookieSessionStorage.ts +60 -39
  74. package/src/core/session/TokenManager.ts +2 -2
  75. package/src/core/session/serializeCookie.ts +33 -0
  76. package/src/core/session/types.ts +79 -2
  77. package/src/index.ts +3 -0
  78. package/src/operations/AuthOperations.spec.ts +107 -62
  79. package/src/operations/AuthOperations.ts +34 -40
  80. package/src/service/AuthService.spec.ts +615 -98
  81. package/src/service/AuthService.ts +198 -73
  82. package/src/service/factory.spec.ts +4 -3
  83. package/src/service/factory.ts +6 -3
  84. package/src/utils.ts +22 -0
@@ -0,0 +1,166 @@
1
+ import { AuthKitCore } from '../AuthKitCore.js';
2
+ import sessionEncryption from '../encryption/ironWebcryptoEncryption.js';
3
+ import {
4
+ OAuthStateMismatchError,
5
+ PKCECookieMissingError,
6
+ PKCEPayloadTooLargeError,
7
+ } from '../errors.js';
8
+ import {
9
+ generateAuthorizationUrl,
10
+ PKCE_MAX_COOKIE_BYTES,
11
+ PKCE_MAX_STATE_BYTES,
12
+ } from './generateAuthorizationUrl.js';
13
+
14
+ const config = {
15
+ clientId: 'test-client-id',
16
+ apiKey: 'test-api-key',
17
+ redirectUri: 'https://app.example.com/callback',
18
+ cookiePassword: 'this-is-a-test-password-that-is-32-characters-long!',
19
+ } as const;
20
+
21
+ const mockClient = {
22
+ pkce: {
23
+ generate: async () => ({
24
+ codeVerifier: 'verifier-' + crypto.randomUUID(),
25
+ codeChallenge: 'challenge-' + crypto.randomUUID(),
26
+ codeChallengeMethod: 'S256',
27
+ }),
28
+ },
29
+ userManagement: {
30
+ getAuthorizationUrl: (opts: any) => {
31
+ const params = new URLSearchParams({
32
+ client_id: opts.clientId,
33
+ redirect_uri: opts.redirectUri,
34
+ state: opts.state ?? '',
35
+ code_challenge: opts.codeChallenge ?? '',
36
+ code_challenge_method: opts.codeChallengeMethod ?? '',
37
+ });
38
+ return `https://api.workos.com/sso/authorize?${params.toString()}`;
39
+ },
40
+ getJwksUrl: () => 'https://api.workos.com/sso/jwks/test-client-id',
41
+ },
42
+ } as const;
43
+
44
+ function makeCore() {
45
+ return new AuthKitCore(config as any, mockClient as any, sessionEncryption);
46
+ }
47
+
48
+ function generate(
49
+ options: Parameters<typeof generateAuthorizationUrl>[0]['options'] = {},
50
+ ) {
51
+ return generateAuthorizationUrl({
52
+ client: mockClient as any,
53
+ config: config as any,
54
+ encryption: sessionEncryption,
55
+ options,
56
+ });
57
+ }
58
+
59
+ // Tamper, missing cookie, missing state, TTL, and single-byte custom-state
60
+ // round-trip are covered in state.spec.ts and AuthKitCore.spec.ts. These
61
+ // tests exercise the integration seam (generateAuthorizationUrl →
62
+ // verifyCallbackState) for behaviors that only emerge when both modules
63
+ // run together.
64
+ describe('PKCE end-to-end round-trip', () => {
65
+ it('verifyCallbackState recovers the sealed state after generateAuthorizationUrl', async () => {
66
+ const core = makeCore();
67
+ const { sealedState } = await generate({
68
+ returnPathname: '/dashboard',
69
+ state: 'user-opaque',
70
+ });
71
+
72
+ const result = await core.verifyCallbackState({
73
+ stateFromUrl: sealedState,
74
+ cookieValue: sealedState,
75
+ });
76
+
77
+ expect(result.returnPathname).toBe('/dashboard');
78
+ expect(result.customState).toBe('user-opaque');
79
+ expect(typeof result.codeVerifier).toBe('string');
80
+ expect(typeof result.nonce).toBe('string');
81
+ });
82
+
83
+ it('empty-string cookieValue is treated as missing (falsy check)', async () => {
84
+ const core = makeCore();
85
+ const { sealedState } = await generate();
86
+
87
+ await expect(
88
+ core.verifyCallbackState({ stateFromUrl: sealedState, cookieValue: '' }),
89
+ ).rejects.toThrow(PKCECookieMissingError);
90
+ });
91
+
92
+ it('concurrent sign-ins produce distinct sealedStates (cross-flow rejection)', async () => {
93
+ const core = makeCore();
94
+ const a = await generate();
95
+ const b = await generate();
96
+
97
+ expect(a.sealedState).not.toBe(b.sealedState);
98
+ await expect(
99
+ core.verifyCallbackState({
100
+ stateFromUrl: a.sealedState,
101
+ cookieValue: b.sealedState,
102
+ }),
103
+ ).rejects.toThrow(OAuthStateMismatchError);
104
+ });
105
+ });
106
+
107
+ describe('PKCE payload size guards', () => {
108
+ it(`accepts custom state at the ${PKCE_MAX_STATE_BYTES}-byte supported limit`, async () => {
109
+ const state = 'a'.repeat(PKCE_MAX_STATE_BYTES);
110
+ await expect(generate({ state })).resolves.toMatchObject({
111
+ sealedState: expect.any(String),
112
+ });
113
+ });
114
+
115
+ it(`rejects custom state ${PKCE_MAX_STATE_BYTES + 1} bytes or larger before sealing`, async () => {
116
+ const state = 'a'.repeat(PKCE_MAX_STATE_BYTES + 1);
117
+ await expect(generate({ state })).rejects.toThrow(PKCEPayloadTooLargeError);
118
+ });
119
+
120
+ it('counts state size in UTF-8 bytes, not JS characters (multibyte input)', async () => {
121
+ // 2-byte UTF-8 char; 1025 chars = 2050 bytes > 2048.
122
+ const state = '\u00e9'.repeat(1025);
123
+ await expect(generate({ state })).rejects.toThrow(PKCEPayloadTooLargeError);
124
+ });
125
+
126
+ it('rejects oversized serialized cookie from large returnPathname + near-limit state', async () => {
127
+ // Under the per-field state cap, but the sealed cookie still overflows
128
+ // once returnPathname is concatenated into the payload.
129
+ const state = 'a'.repeat(PKCE_MAX_STATE_BYTES);
130
+ const returnPathname = '/' + 'p'.repeat(2048);
131
+ await expect(generate({ state, returnPathname })).rejects.toThrow(
132
+ PKCEPayloadTooLargeError,
133
+ );
134
+ });
135
+
136
+ it('shrinks the effective budget when cookieDomain adds attribute bytes', async () => {
137
+ // cookieDomain=<long> is serialized into every Set-Cookie and counts
138
+ // against the browser's per-cookie budget. A state payload that fits
139
+ // without a Domain attribute can push the serialized header over the
140
+ // limit when Domain is present.
141
+ const longDomain = 'sub.' + 'd'.repeat(200) + '.example.com';
142
+ const configWithDomain = { ...config, cookieDomain: longDomain } as any;
143
+
144
+ const state = 'a'.repeat(PKCE_MAX_STATE_BYTES);
145
+ await expect(
146
+ generateAuthorizationUrl({
147
+ client: mockClient as any,
148
+ config: configWithDomain,
149
+ encryption: sessionEncryption,
150
+ options: { state, returnPathname: '/' + 'p'.repeat(700) },
151
+ }),
152
+ ).rejects.toThrow(PKCEPayloadTooLargeError);
153
+ });
154
+
155
+ it(`error message names PKCE_MAX_COOKIE_BYTES (${PKCE_MAX_COOKIE_BYTES})`, async () => {
156
+ const state = 'a'.repeat(PKCE_MAX_STATE_BYTES);
157
+ const returnPathname = '/' + 'p'.repeat(2048);
158
+ try {
159
+ await generate({ state, returnPathname });
160
+ throw new Error('expected throw');
161
+ } catch (err) {
162
+ expect(err).toBeInstanceOf(PKCEPayloadTooLargeError);
163
+ expect((err as Error).message).toContain(String(PKCE_MAX_COOKIE_BYTES));
164
+ }
165
+ });
166
+ });
@@ -0,0 +1,216 @@
1
+ import sessionEncryption from '../encryption/ironWebcryptoEncryption.js';
2
+ import { SessionEncryptionError } from '../errors.js';
3
+ import { sealState, unsealState, type PKCEStateInput } from './state.js';
4
+
5
+ const testPassword = 'this-is-a-test-password-that-is-32-characters-long!';
6
+
7
+ const validState: PKCEStateInput = {
8
+ nonce: '8b7b1c32-7d8f-44f9-aa51-4c3a6c8fb8d9',
9
+ codeVerifier: 'verifier-12345678901234567890123456789012345678',
10
+ returnPathname: '/dashboard',
11
+ customState: 'user-custom',
12
+ };
13
+
14
+ describe('PKCE state seal/unseal', () => {
15
+ it('round-trips a valid state', async () => {
16
+ const sealed = await sealState(sessionEncryption, testPassword, validState);
17
+ const unsealed = await unsealState(sessionEncryption, testPassword, sealed);
18
+
19
+ expect(unsealed).toMatchObject(validState);
20
+ expect(typeof unsealed.issuedAt).toBe('number');
21
+ });
22
+
23
+ it('round-trips without optional fields', async () => {
24
+ const minimal: PKCEStateInput = {
25
+ nonce: 'n',
26
+ codeVerifier: 'v',
27
+ };
28
+ const sealed = await sealState(sessionEncryption, testPassword, minimal);
29
+ const unsealed = await unsealState(sessionEncryption, testPassword, sealed);
30
+
31
+ expect(unsealed).toMatchObject(minimal);
32
+ expect(typeof unsealed.issuedAt).toBe('number');
33
+ });
34
+
35
+ it('stamps issuedAt with Date.now() at seal time', async () => {
36
+ vi.useFakeTimers();
37
+ try {
38
+ const fixedNow = new Date('2026-01-01T00:00:00.000Z').getTime();
39
+ vi.setSystemTime(fixedNow);
40
+
41
+ const sealed = await sealState(
42
+ sessionEncryption,
43
+ testPassword,
44
+ validState,
45
+ );
46
+ const unsealed = await unsealState(
47
+ sessionEncryption,
48
+ testPassword,
49
+ sealed,
50
+ );
51
+
52
+ expect(unsealed.issuedAt).toBe(fixedNow);
53
+ } finally {
54
+ vi.useRealTimers();
55
+ }
56
+ });
57
+
58
+ it.each<[string, string]>([
59
+ ['dots', 'has.many.dots.in.it'],
60
+ ['JSON-like', '{"key":"value","nested":{"a":1}}'],
61
+ ['2KB payload', 'x'.repeat(2048)],
62
+ ])(
63
+ 'preserves %s customState byte-identically',
64
+ async (_label, customState) => {
65
+ const input: PKCEStateInput = {
66
+ nonce: 'n',
67
+ codeVerifier: 'v',
68
+ customState,
69
+ };
70
+ const sealed = await sealState(sessionEncryption, testPassword, input);
71
+ const unsealed = await unsealState(
72
+ sessionEncryption,
73
+ testPassword,
74
+ sealed,
75
+ );
76
+
77
+ expect(unsealed.customState).toBe(customState);
78
+ },
79
+ );
80
+
81
+ it('throws SessionEncryptionError on tampered ciphertext', async () => {
82
+ const sealed = await sealState(sessionEncryption, testPassword, validState);
83
+ // Flip one char in the middle of the sealed string (avoiding the ~2 suffix).
84
+ const mid = Math.floor(sealed.length / 2);
85
+ const tampered =
86
+ sealed.slice(0, mid) +
87
+ (sealed[mid] === 'a' ? 'b' : 'a') +
88
+ sealed.slice(mid + 1);
89
+
90
+ await expect(
91
+ unsealState(sessionEncryption, testPassword, tampered),
92
+ ).rejects.toThrow(SessionEncryptionError);
93
+ });
94
+
95
+ it('throws SessionEncryptionError with wrong password', async () => {
96
+ const sealed = await sealState(sessionEncryption, testPassword, validState);
97
+ const wrongPassword =
98
+ 'this-is-a-completely-different-password-that-is-long';
99
+
100
+ await expect(
101
+ unsealState(sessionEncryption, wrongPassword, sealed),
102
+ ).rejects.toThrow(SessionEncryptionError);
103
+ });
104
+
105
+ it('throws SessionEncryptionError on schema mismatch', async () => {
106
+ // Seal something that passes encryption but fails the StateSchema check.
107
+ const wrongShape = await sessionEncryption.sealData(
108
+ { foo: 'bar', baz: 42 },
109
+ { password: testPassword, ttl: 600 },
110
+ );
111
+
112
+ await expect(
113
+ unsealState(sessionEncryption, testPassword, wrongShape),
114
+ ).rejects.toThrow(SessionEncryptionError);
115
+ await expect(
116
+ unsealState(sessionEncryption, testPassword, wrongShape),
117
+ ).rejects.toThrow(/Malformed PKCE state payload/);
118
+ });
119
+
120
+ describe('TTL enforcement', () => {
121
+ beforeEach(() => {
122
+ vi.useFakeTimers();
123
+ });
124
+ afterEach(() => {
125
+ vi.useRealTimers();
126
+ });
127
+
128
+ it('succeeds well before expiry', async () => {
129
+ vi.setSystemTime(new Date('2026-01-01T00:00:00.000Z'));
130
+ const sealed = await sealState(
131
+ sessionEncryption,
132
+ testPassword,
133
+ validState,
134
+ );
135
+
136
+ vi.setSystemTime(new Date('2026-01-01T00:09:59.000Z')); // +599s
137
+ const unsealed = await unsealState(
138
+ sessionEncryption,
139
+ testPassword,
140
+ sealed,
141
+ );
142
+
143
+ expect(unsealed).toMatchObject(validState);
144
+ });
145
+
146
+ it('throws just past the 600s payload-level expiry', async () => {
147
+ vi.setSystemTime(new Date('2026-01-01T00:00:00.000Z'));
148
+ const sealed = await sealState(
149
+ sessionEncryption,
150
+ testPassword,
151
+ validState,
152
+ );
153
+
154
+ // Payload-level expiry is strict at 600s (no positive skew grace).
155
+ vi.setSystemTime(new Date('2026-01-01T00:10:01.000Z')); // +601s
156
+
157
+ await expect(
158
+ unsealState(sessionEncryption, testPassword, sealed),
159
+ ).rejects.toThrow(SessionEncryptionError);
160
+ });
161
+
162
+ it('rejects payloads older than 600s even when the encryptor ignores ttl', async () => {
163
+ // Custom SessionEncryption that ignores the ttl option — simulates an
164
+ // adapter that would let a stale blob through. The payload-level
165
+ // issuedAt check in unsealState is the authoritative guard.
166
+ const ignoresTtl = {
167
+ sealData: (data: unknown, options: { password: string }) =>
168
+ sessionEncryption.sealData(data, { password: options.password }),
169
+ unsealData: <T>(sealed: string, options: { password: string }) =>
170
+ sessionEncryption.unsealData<T>(sealed, {
171
+ password: options.password,
172
+ }),
173
+ };
174
+
175
+ vi.setSystemTime(new Date('2026-01-01T00:00:00.000Z'));
176
+ const sealed = await sealState(ignoresTtl, testPassword, validState);
177
+
178
+ // 605s — inside iron's default 60s skew grace, outside the strict 600s
179
+ // payload-level check.
180
+ vi.setSystemTime(new Date('2026-01-01T00:10:05.000Z'));
181
+
182
+ await expect(
183
+ unsealState(ignoresTtl, testPassword, sealed),
184
+ ).rejects.toThrow(/PKCE state expired/);
185
+ });
186
+
187
+ it('tolerates bounded negative skew (issuedAt up to 60s ahead of now)', async () => {
188
+ // Simulates sign-in on a node whose clock is ahead of the callback
189
+ // node by 30s — within the 60s tolerance.
190
+ vi.setSystemTime(new Date('2026-01-01T00:00:00.000Z'));
191
+ const sealed = await sessionEncryption.sealData(
192
+ { ...validState, issuedAt: Date.now() + 30_000 },
193
+ { password: testPassword, ttl: 600 },
194
+ );
195
+
196
+ const unsealed = await unsealState(
197
+ sessionEncryption,
198
+ testPassword,
199
+ sealed,
200
+ );
201
+ expect(unsealed).toMatchObject(validState);
202
+ });
203
+
204
+ it('rejects payloads meaningfully in the future (issuedAt beyond skew)', async () => {
205
+ vi.setSystemTime(new Date('2026-01-01T00:00:00.000Z'));
206
+ const sealed = await sessionEncryption.sealData(
207
+ { ...validState, issuedAt: Date.now() + 120_000 },
208
+ { password: testPassword, ttl: 600 },
209
+ );
210
+
211
+ await expect(
212
+ unsealState(sessionEncryption, testPassword, sealed),
213
+ ).rejects.toThrow(/PKCE state expired/);
214
+ });
215
+ });
216
+ });
@@ -0,0 +1,120 @@
1
+ import * as v from 'valibot';
2
+ import { SessionEncryptionError } from '../errors.js';
3
+ import type { SessionEncryption } from '../session/types.js';
4
+ import { PKCE_COOKIE_MAX_AGE } from './cookieOptions.js';
5
+
6
+ /**
7
+ * Clock-skew tolerance (ms) for the payload-level `issuedAt` check.
8
+ *
9
+ * Applied asymmetrically, only to the negative (future-`issuedAt`) side:
10
+ * allows a sign-in issued on node A to be verified on node B whose clock
11
+ * is up to 60s behind without failing a legitimate callback. The upper
12
+ * bound (expiry) is strict — `PKCE_COOKIE_MAX_AGE` with no grace — so
13
+ * this payload check is always at least as strict as iron-webcrypto's
14
+ * symmetric 60s skew on `ttl`, making it the authoritative expiry guard
15
+ * regardless of how a custom `SessionEncryption` adapter treats `ttl`.
16
+ */
17
+ const PKCE_CLOCK_SKEW_MS = 60_000;
18
+
19
+ /**
20
+ * Runtime schema for the sealed PKCE state blob.
21
+ *
22
+ * Validated at unseal time as defense-in-depth against any future code path
23
+ * accidentally sealing the wrong shape. Shape mismatch is treated as an
24
+ * integrity failure (same category as a tampered blob).
25
+ *
26
+ * `issuedAt` (ms since epoch) lets `unsealState` enforce the TTL on its own
27
+ * rather than trusting the encryption adapter's `ttl` handling. Custom
28
+ * `SessionEncryption` implementations may silently ignore the `ttl` field —
29
+ * the payload-level age check closes that gap.
30
+ */
31
+ export const StateSchema = v.object({
32
+ nonce: v.string(),
33
+ codeVerifier: v.string(),
34
+ issuedAt: v.number(),
35
+ returnPathname: v.optional(v.string()),
36
+ customState: v.optional(v.string()),
37
+ /**
38
+ * The per-request `redirectUri` override resolved at sign-in time, if the
39
+ * caller supplied one. Persisted so `handleCallback` can recompute the
40
+ * exact cookie options used at `setCookie` time — notably `secure`, which
41
+ * is inferred from the redirect URI's protocol. Omitted when the caller
42
+ * relied on the configured default.
43
+ */
44
+ redirectUri: v.optional(v.string()),
45
+ });
46
+
47
+ export type PKCEState = v.InferOutput<typeof StateSchema>;
48
+
49
+ export type PKCEStateInput = Omit<PKCEState, 'issuedAt'>;
50
+
51
+ /**
52
+ * Seal a PKCE state object for use as both the OAuth `state` query param
53
+ * and the `wos-auth-verifier` cookie value. Seal embeds a 600s TTL and
54
+ * stamps `issuedAt` so the unseal path can enforce age independently.
55
+ */
56
+ export async function sealState(
57
+ encryption: SessionEncryption,
58
+ password: string,
59
+ state: PKCEStateInput,
60
+ ): Promise<string> {
61
+ return encryption.sealData(
62
+ { ...state, issuedAt: Date.now() },
63
+ {
64
+ password,
65
+ ttl: PKCE_COOKIE_MAX_AGE,
66
+ },
67
+ );
68
+ }
69
+
70
+ /**
71
+ * Unseal a PKCE state blob, enforcing TTL and shape.
72
+ *
73
+ * Age is verified twice:
74
+ * 1. The encryption adapter's `ttl` check (iron-webcrypto enforces this by
75
+ * default — custom adapters MAY ignore it).
76
+ * 2. A payload-level `issuedAt` comparison against `Date.now()`. This is the
77
+ * authoritative check — it runs regardless of how the adapter treats
78
+ * `ttl`.
79
+ *
80
+ * Any failure — expired TTL, tamper, wrong password, or schema mismatch —
81
+ * is wrapped as `SessionEncryptionError`. Callers differentiate via the
82
+ * `cause` chain, not the message string.
83
+ */
84
+ export async function unsealState(
85
+ encryption: SessionEncryption,
86
+ password: string,
87
+ sealed: string,
88
+ ): Promise<PKCEState> {
89
+ let raw: unknown;
90
+ try {
91
+ raw = await encryption.unsealData<unknown>(sealed, {
92
+ password,
93
+ ttl: PKCE_COOKIE_MAX_AGE,
94
+ });
95
+ } catch (cause) {
96
+ throw new SessionEncryptionError('Failed to unseal PKCE state', cause);
97
+ }
98
+
99
+ const result = v.safeParse(StateSchema, raw);
100
+ if (!result.success) {
101
+ throw new SessionEncryptionError(
102
+ 'Malformed PKCE state payload',
103
+ result.issues,
104
+ );
105
+ }
106
+
107
+ const ageMs = Date.now() - result.output.issuedAt;
108
+ if (ageMs < -PKCE_CLOCK_SKEW_MS || ageMs > PKCE_COOKIE_MAX_AGE * 1000) {
109
+ // Attach age context so production logs can diagnose clock-skew issues
110
+ // via the `cause` chain without leaking the sealed blob itself.
111
+ throw new SessionEncryptionError(
112
+ 'PKCE state expired',
113
+ new Error(
114
+ `age=${ageMs}ms, maxAge=${PKCE_COOKIE_MAX_AGE * 1000}ms, skew=±${PKCE_CLOCK_SKEW_MS}ms`,
115
+ ),
116
+ );
117
+ }
118
+
119
+ return result.output;
120
+ }
@@ -19,7 +19,7 @@ const createMockConfig = (
19
19
 
20
20
  // Concrete implementation for testing the abstract class
21
21
  class TestCookieSessionStorage extends CookieSessionStorage<string, string> {
22
- async getSession(): Promise<string | null> {
22
+ async getCookie(_request: string, _name: string): Promise<string | null> {
23
23
  return null;
24
24
  }
25
25
  }
@@ -110,7 +110,7 @@ describe('CookieSessionStorage', () => {
110
110
  it('concrete implementation works', async () => {
111
111
  const storage = new TestCookieSessionStorage(createMockConfig());
112
112
 
113
- const session = await storage.getSession();
113
+ const session = await storage.getSession('request');
114
114
  expect(session).toBeNull();
115
115
 
116
116
  const savedResult = await storage.saveSession(undefined, 'session-data');
@@ -123,7 +123,7 @@ describe('CookieSessionStorage', () => {
123
123
  });
124
124
  });
125
125
 
126
- describe('buildSetCookie', () => {
126
+ describe('serializeCookie', () => {
127
127
  it('capitalizes SameSite values for Safari compatibility', async () => {
128
128
  const testCases = [
129
129
  { input: 'lax' as const, expected: 'SameSite=Lax' },
@@ -139,4 +139,80 @@ describe('CookieSessionStorage', () => {
139
139
  }
140
140
  });
141
141
  });
142
+
143
+ describe('generic cookie primitives', () => {
144
+ it('setCookie emits a Set-Cookie with the passed name, value, and options', async () => {
145
+ const storage = new TestCookieSessionStorage(createMockConfig());
146
+
147
+ const result = await storage.setCookie(undefined, 'foo', 'bar', {
148
+ path: '/x',
149
+ maxAge: 60,
150
+ httpOnly: true,
151
+ secure: true,
152
+ sameSite: 'lax',
153
+ });
154
+
155
+ const header = result.headers?.['Set-Cookie'];
156
+ expect(header).toContain('foo=bar');
157
+ expect(header).toContain('Path=/x');
158
+ expect(header).toContain('Max-Age=60');
159
+ expect(header).toContain('HttpOnly');
160
+ expect(header).toContain('Secure');
161
+ expect(header).toContain('SameSite=Lax');
162
+ });
163
+
164
+ it('clearCookie emits Max-Age=0 with empty value', async () => {
165
+ const storage = new TestCookieSessionStorage(createMockConfig());
166
+
167
+ const result = await storage.clearCookie(undefined, 'foo', {
168
+ path: '/x',
169
+ });
170
+
171
+ const header = result.headers?.['Set-Cookie'] as string;
172
+ expect(header).toContain('foo=;');
173
+ expect(header).toContain('Max-Age=0');
174
+ });
175
+
176
+ it('getCookie is abstract — subclass must implement it', async () => {
177
+ const storage = new TestCookieSessionStorage(createMockConfig());
178
+
179
+ const value = await storage.getCookie('request', 'anything');
180
+ expect(value).toBeNull();
181
+ });
182
+
183
+ it('getSession wraps getCookie with the configured cookie name', async () => {
184
+ class CapturingStorage extends CookieSessionStorage<string, string> {
185
+ captured?: { name: string };
186
+ async getCookie(_req: string, name: string): Promise<string | null> {
187
+ this.captured = { name };
188
+ return 'stored-value';
189
+ }
190
+ }
191
+ const storage = new CapturingStorage(
192
+ createMockConfig({ cookieName: 'my-session' }),
193
+ );
194
+
195
+ const value = await storage.getSession('request');
196
+
197
+ expect(storage.captured).toEqual({ name: 'my-session' });
198
+ expect(value).toBe('stored-value');
199
+ });
200
+
201
+ it('saveSession and setCookie produce identical headers for the session cookie', async () => {
202
+ const config = createMockConfig();
203
+ const storage = new TestCookieSessionStorage(config);
204
+
205
+ const saved = await storage.saveSession(undefined, 'data');
206
+ const explicit = await storage.setCookie(
207
+ undefined,
208
+ storage['cookieName'],
209
+ 'data',
210
+ storage['cookieOptions'],
211
+ );
212
+
213
+ expect(saved.headers?.['Set-Cookie']).toBe(
214
+ explicit.headers?.['Set-Cookie'],
215
+ );
216
+ });
217
+ });
142
218
  });