@workos/authkit-session 0.3.4 → 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.
- package/README.md +94 -27
- package/dist/core/AuthKitCore.d.ts +20 -0
- package/dist/core/AuthKitCore.d.ts.map +1 -1
- package/dist/core/AuthKitCore.js +36 -4
- package/dist/core/AuthKitCore.js.map +1 -1
- package/dist/core/encryption/ironWebcryptoEncryption.d.ts +2 -1
- package/dist/core/encryption/ironWebcryptoEncryption.d.ts.map +1 -1
- package/dist/core/encryption/ironWebcryptoEncryption.js +2 -2
- package/dist/core/encryption/ironWebcryptoEncryption.js.map +1 -1
- package/dist/core/errors.d.ts +9 -0
- package/dist/core/errors.d.ts.map +1 -1
- package/dist/core/errors.js +18 -0
- package/dist/core/errors.js.map +1 -1
- package/dist/core/pkce/cookieOptions.d.ts +36 -0
- package/dist/core/pkce/cookieOptions.d.ts.map +1 -0
- package/dist/core/pkce/cookieOptions.js +55 -0
- package/dist/core/pkce/cookieOptions.js.map +1 -0
- package/dist/core/pkce/generateAuthorizationUrl.d.ts +45 -0
- package/dist/core/pkce/generateAuthorizationUrl.d.ts.map +1 -0
- package/dist/core/pkce/generateAuthorizationUrl.js +82 -0
- package/dist/core/pkce/generateAuthorizationUrl.js.map +1 -0
- package/dist/core/pkce/state.d.ts +53 -0
- package/dist/core/pkce/state.d.ts.map +1 -0
- package/dist/core/pkce/state.js +91 -0
- package/dist/core/pkce/state.js.map +1 -0
- package/dist/core/session/CookieSessionStorage.d.ts +25 -15
- package/dist/core/session/CookieSessionStorage.d.ts.map +1 -1
- package/dist/core/session/CookieSessionStorage.js +20 -27
- package/dist/core/session/CookieSessionStorage.js.map +1 -1
- package/dist/core/session/TokenManager.js +2 -2
- package/dist/core/session/TokenManager.js.map +1 -1
- package/dist/core/session/serializeCookie.d.ts +13 -0
- package/dist/core/session/serializeCookie.d.ts.map +1 -0
- package/dist/core/session/serializeCookie.js +32 -0
- package/dist/core/session/serializeCookie.js.map +1 -0
- package/dist/core/session/types.d.ts +71 -2
- package/dist/core/session/types.d.ts.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/operations/AuthOperations.d.ts +15 -13
- package/dist/operations/AuthOperations.d.ts.map +1 -1
- package/dist/operations/AuthOperations.js +22 -34
- package/dist/operations/AuthOperations.js.map +1 -1
- package/dist/service/AuthService.d.ts +58 -15
- package/dist/service/AuthService.d.ts.map +1 -1
- package/dist/service/AuthService.js +157 -71
- package/dist/service/AuthService.js.map +1 -1
- package/dist/service/factory.d.ts.map +1 -1
- package/dist/service/factory.js +4 -3
- package/dist/service/factory.js.map +1 -1
- package/dist/utils.d.ts +16 -0
- package/dist/utils.d.ts.map +1 -1
- package/dist/utils.js +23 -0
- package/dist/utils.js.map +1 -1
- package/package.json +23 -20
- package/src/core/AuthKitCore.spec.ts +109 -0
- package/src/core/AuthKitCore.ts +55 -4
- package/src/core/encryption/ironWebcryptoEncryption.spec.ts +62 -0
- package/src/core/encryption/ironWebcryptoEncryption.ts +2 -2
- package/src/core/errors.spec.ts +33 -142
- package/src/core/errors.ts +21 -0
- package/src/core/pkce/cookieOptions.spec.ts +144 -0
- package/src/core/pkce/cookieOptions.ts +64 -0
- package/src/core/pkce/generateAuthorizationUrl.ts +123 -0
- package/src/core/pkce/pkce.spec.ts +166 -0
- package/src/core/pkce/state.spec.ts +216 -0
- package/src/core/pkce/state.ts +120 -0
- package/src/core/session/CookieSessionStorage.spec.ts +79 -3
- package/src/core/session/CookieSessionStorage.ts +56 -36
- package/src/core/session/TokenManager.ts +2 -2
- package/src/core/session/serializeCookie.ts +33 -0
- package/src/core/session/types.ts +79 -2
- package/src/index.ts +3 -0
- package/src/operations/AuthOperations.spec.ts +107 -62
- package/src/operations/AuthOperations.ts +34 -40
- package/src/service/AuthService.spec.ts +615 -98
- package/src/service/AuthService.ts +198 -73
- package/src/service/factory.spec.ts +4 -3
- package/src/service/factory.ts +6 -3
- package/src/utils.ts +22 -0
|
@@ -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
|
|
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('
|
|
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
|
});
|
|
@@ -1,17 +1,8 @@
|
|
|
1
1
|
import type { AuthKitConfig } from '../config/types.js';
|
|
2
|
-
import
|
|
2
|
+
import { serializeCookie } from './serializeCookie.js';
|
|
3
|
+
import type { CookieOptions, HeadersBag, SessionStorage } from './types.js';
|
|
3
4
|
|
|
4
|
-
export
|
|
5
|
-
path?: string;
|
|
6
|
-
domain?: string;
|
|
7
|
-
maxAge?: number;
|
|
8
|
-
expires?: Date;
|
|
9
|
-
httpOnly?: boolean;
|
|
10
|
-
secure?: boolean;
|
|
11
|
-
sameSite?: 'lax' | 'strict' | 'none';
|
|
12
|
-
priority?: 'low' | 'medium' | 'high';
|
|
13
|
-
partitioned?: boolean;
|
|
14
|
-
}
|
|
5
|
+
export type { CookieOptions } from './types.js';
|
|
15
6
|
|
|
16
7
|
export abstract class CookieSessionStorage<
|
|
17
8
|
TRequest,
|
|
@@ -21,7 +12,10 @@ export abstract class CookieSessionStorage<
|
|
|
21
12
|
protected readonly cookieOptions: CookieOptions;
|
|
22
13
|
|
|
23
14
|
constructor(config: AuthKitConfig) {
|
|
24
|
-
|
|
15
|
+
// Matches the canonical default in ConfigurationProvider. This fallback
|
|
16
|
+
// only fires when a caller instantiates the class with a config that
|
|
17
|
+
// hasn't been resolved through the provider.
|
|
18
|
+
this.cookieName = config.cookieName ?? 'wos-session';
|
|
25
19
|
|
|
26
20
|
const sameSite = config.cookieSameSite ?? 'lax';
|
|
27
21
|
|
|
@@ -54,40 +48,66 @@ export abstract class CookieSessionStorage<
|
|
|
54
48
|
/* default no-op. Adapters can override if they CAN mutate a native response */
|
|
55
49
|
}
|
|
56
50
|
|
|
57
|
-
protected
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
if (o.secure) a.push('Secure');
|
|
65
|
-
if (o.sameSite) {
|
|
66
|
-
const capitalizedSameSite =
|
|
67
|
-
o.sameSite.charAt(0).toUpperCase() + o.sameSite.slice(1).toLowerCase();
|
|
68
|
-
a.push(`SameSite=${capitalizedSameSite}`);
|
|
69
|
-
}
|
|
70
|
-
if (o.priority) a.push(`Priority=${o.priority}`);
|
|
71
|
-
if (o.partitioned) a.push('Partitioned');
|
|
72
|
-
return a.join('; ');
|
|
51
|
+
protected serializeCookie(
|
|
52
|
+
name: string,
|
|
53
|
+
value: string,
|
|
54
|
+
options: CookieOptions,
|
|
55
|
+
flags: { expired?: boolean } = {},
|
|
56
|
+
): string {
|
|
57
|
+
return serializeCookie(name, value, options, flags);
|
|
73
58
|
}
|
|
74
59
|
|
|
75
|
-
|
|
60
|
+
/**
|
|
61
|
+
* Read a named cookie from the framework-specific request.
|
|
62
|
+
*
|
|
63
|
+
* Implementations MUST return the URL-decoded value — the inverse of
|
|
64
|
+
* `serializeCookie`'s `encodeURIComponent` on write. Returning the raw
|
|
65
|
+
* on-wire bytes will silently break byte-comparison against the original
|
|
66
|
+
* value (e.g. PKCE state verification) for any seal containing characters
|
|
67
|
+
* that `encodeURIComponent` escapes.
|
|
68
|
+
*/
|
|
69
|
+
abstract getCookie(request: TRequest, name: string): Promise<string | null>;
|
|
76
70
|
|
|
77
|
-
async
|
|
71
|
+
async setCookie(
|
|
78
72
|
response: TResponse | undefined,
|
|
79
|
-
|
|
73
|
+
name: string,
|
|
74
|
+
value: string,
|
|
75
|
+
options: CookieOptions,
|
|
80
76
|
): Promise<{ response?: TResponse; headers?: HeadersBag }> {
|
|
81
|
-
const header = this.
|
|
77
|
+
const header = this.serializeCookie(name, value, options);
|
|
82
78
|
const mutated = await this.applyHeaders(response, { 'Set-Cookie': header });
|
|
83
79
|
return mutated ?? { headers: { 'Set-Cookie': header } };
|
|
84
80
|
}
|
|
85
81
|
|
|
86
|
-
async
|
|
87
|
-
response: TResponse,
|
|
82
|
+
async clearCookie(
|
|
83
|
+
response: TResponse | undefined,
|
|
84
|
+
name: string,
|
|
85
|
+
options: CookieOptions,
|
|
88
86
|
): Promise<{ response?: TResponse; headers?: HeadersBag }> {
|
|
89
|
-
const header = this.
|
|
87
|
+
const header = this.serializeCookie(name, '', options, { expired: true });
|
|
90
88
|
const mutated = await this.applyHeaders(response, { 'Set-Cookie': header });
|
|
91
89
|
return mutated ?? { headers: { 'Set-Cookie': header } };
|
|
92
90
|
}
|
|
91
|
+
|
|
92
|
+
getSession(request: TRequest): Promise<string | null> {
|
|
93
|
+
return this.getCookie(request, this.cookieName);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
saveSession(
|
|
97
|
+
response: TResponse | undefined,
|
|
98
|
+
sessionData: string,
|
|
99
|
+
): Promise<{ response?: TResponse; headers?: HeadersBag }> {
|
|
100
|
+
return this.setCookie(
|
|
101
|
+
response,
|
|
102
|
+
this.cookieName,
|
|
103
|
+
sessionData,
|
|
104
|
+
this.cookieOptions,
|
|
105
|
+
);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
clearSession(
|
|
109
|
+
response: TResponse | undefined,
|
|
110
|
+
): Promise<{ response?: TResponse; headers?: HeadersBag }> {
|
|
111
|
+
return this.clearCookie(response, this.cookieName, this.cookieOptions);
|
|
112
|
+
}
|
|
93
113
|
}
|
|
@@ -32,8 +32,8 @@ export class TokenManager {
|
|
|
32
32
|
): BaseTokenClaims & TCustomClaims {
|
|
33
33
|
try {
|
|
34
34
|
return decodeJwt<BaseTokenClaims & TCustomClaims>(token);
|
|
35
|
-
} catch (
|
|
36
|
-
throw new Error('Invalid token');
|
|
35
|
+
} catch (cause) {
|
|
36
|
+
throw new Error('Invalid token', { cause });
|
|
37
37
|
}
|
|
38
38
|
}
|
|
39
39
|
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { CookieOptions } from './types.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Serialize a `Set-Cookie` header value from (name, value, options).
|
|
5
|
+
*
|
|
6
|
+
* Shared between `CookieSessionStorage` (writes the header on response) and
|
|
7
|
+
* the PKCE flow's pre-write size guard (must measure the exact bytes the
|
|
8
|
+
* browser will see, including attribute overhead, to detect oversized
|
|
9
|
+
* verifier cookies before they silently get dropped).
|
|
10
|
+
*/
|
|
11
|
+
export function serializeCookie(
|
|
12
|
+
name: string,
|
|
13
|
+
value: string,
|
|
14
|
+
options: CookieOptions,
|
|
15
|
+
{ expired }: { expired?: boolean } = {},
|
|
16
|
+
): string {
|
|
17
|
+
const parts = [`${name}=${encodeURIComponent(value)}`];
|
|
18
|
+
if (options.path) parts.push(`Path=${options.path}`);
|
|
19
|
+
if (options.domain) parts.push(`Domain=${options.domain}`);
|
|
20
|
+
if (options.maxAge != null || expired)
|
|
21
|
+
parts.push(`Max-Age=${expired ? 0 : options.maxAge}`);
|
|
22
|
+
if (options.httpOnly) parts.push('HttpOnly');
|
|
23
|
+
if (options.secure) parts.push('Secure');
|
|
24
|
+
if (options.sameSite) {
|
|
25
|
+
const capitalized =
|
|
26
|
+
options.sameSite.charAt(0).toUpperCase() +
|
|
27
|
+
options.sameSite.slice(1).toLowerCase();
|
|
28
|
+
parts.push(`SameSite=${capitalized}`);
|
|
29
|
+
}
|
|
30
|
+
if (options.priority) parts.push(`Priority=${options.priority}`);
|
|
31
|
+
if (options.partitioned) parts.push('Partitioned');
|
|
32
|
+
return parts.join('; ');
|
|
33
|
+
}
|