@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.
- package/README.md +111 -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/cookieName.d.ts +17 -0
- package/dist/core/pkce/cookieName.d.ts.map +1 -0
- package/dist/core/pkce/cookieName.js +26 -0
- package/dist/core/pkce/cookieName.js.map +1 -0
- package/dist/core/pkce/cookieOptions.d.ts +34 -0
- package/dist/core/pkce/cookieOptions.d.ts.map +1 -0
- package/dist/core/pkce/cookieOptions.js +53 -0
- package/dist/core/pkce/cookieOptions.js.map +1 -0
- package/dist/core/pkce/generateAuthorizationUrl.d.ts +46 -0
- package/dist/core/pkce/generateAuthorizationUrl.d.ts.map +1 -0
- package/dist/core/pkce/generateAuthorizationUrl.js +85 -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 +76 -2
- package/dist/core/session/types.d.ts.map +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -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 +64 -15
- package/dist/service/AuthService.d.ts.map +1 -1
- package/dist/service/AuthService.js +171 -70
- 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/cookieName.spec.ts +56 -0
- package/src/core/pkce/cookieName.ts +27 -0
- package/src/core/pkce/cookieOptions.spec.ts +144 -0
- package/src/core/pkce/cookieOptions.ts +61 -0
- package/src/core/pkce/generateAuthorizationUrl.ts +123 -0
- package/src/core/pkce/pkce.spec.ts +175 -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 +83 -2
- package/src/index.ts +11 -0
- package/src/operations/AuthOperations.spec.ts +107 -62
- package/src/operations/AuthOperations.ts +34 -40
- package/src/service/AuthService.spec.ts +750 -97
- package/src/service/AuthService.ts +210 -72
- package/src/service/factory.spec.ts +4 -3
- package/src/service/factory.ts +6 -3
- package/src/utils.ts +22 -0
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import type { WorkOS } from '@workos-inc/node';
|
|
2
|
+
import type { AuthKitConfig } from '../config/types.js';
|
|
3
|
+
import { PKCEPayloadTooLargeError } from '../errors.js';
|
|
4
|
+
import { serializeCookie } from '../session/serializeCookie.js';
|
|
5
|
+
import type {
|
|
6
|
+
CookieOptions,
|
|
7
|
+
GetAuthorizationUrlOptions,
|
|
8
|
+
SessionEncryption,
|
|
9
|
+
} from '../session/types.js';
|
|
10
|
+
import { getPKCECookieNameForState } from './cookieName.js';
|
|
11
|
+
import { getPKCECookieOptions } from './cookieOptions.js';
|
|
12
|
+
import { sealState } from './state.js';
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Maximum UTF-8 byte length for caller-supplied `options.state`. Enforced
|
|
16
|
+
* as an early, user-facing check so large custom state fails with a clear
|
|
17
|
+
* error before any crypto work — ahead of the authoritative sealed-cookie
|
|
18
|
+
* length guard below.
|
|
19
|
+
*/
|
|
20
|
+
export const PKCE_MAX_STATE_BYTES = 2048;
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Maximum serialized `Set-Cookie` header length (bytes) for the verifier.
|
|
24
|
+
* Browsers start dropping cookies past ~4096 bytes per RFC 6265; 3800
|
|
25
|
+
* leaves headroom for proxies that cap lower and for the handful of
|
|
26
|
+
* cookie attributes whose size isn't known until serialization time
|
|
27
|
+
* (notably `Domain=` when `cookieDomain` is set).
|
|
28
|
+
*/
|
|
29
|
+
export const PKCE_MAX_COOKIE_BYTES = 3800;
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Internal authorization-URL generation result.
|
|
33
|
+
*
|
|
34
|
+
* Not exported: AuthService consumes `sealedState` + `cookieOptions` to write
|
|
35
|
+
* the verifier cookie via `storage.setCookie`, then returns only `{ url, response?, headers? }`
|
|
36
|
+
* to callers.
|
|
37
|
+
*/
|
|
38
|
+
export interface GeneratedAuthorizationUrl {
|
|
39
|
+
url: string;
|
|
40
|
+
sealedState: string;
|
|
41
|
+
cookieName: string;
|
|
42
|
+
cookieOptions: CookieOptions;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Generate a WorkOS authorization URL bound to a PKCE verifier.
|
|
47
|
+
*
|
|
48
|
+
* Returns the URL, the sealed state blob (used as both the OAuth `state`
|
|
49
|
+
* query param AND the cookie value — identical string; the callback does a
|
|
50
|
+
* byte-compare before decrypting), and the cookie options the verifier
|
|
51
|
+
* cookie should be written with.
|
|
52
|
+
*/
|
|
53
|
+
export async function generateAuthorizationUrl(params: {
|
|
54
|
+
client: WorkOS;
|
|
55
|
+
config: AuthKitConfig;
|
|
56
|
+
encryption: SessionEncryption;
|
|
57
|
+
options: GetAuthorizationUrlOptions;
|
|
58
|
+
}): Promise<GeneratedAuthorizationUrl> {
|
|
59
|
+
const { client, config, encryption, options } = params;
|
|
60
|
+
const redirectUri = options.redirectUri ?? config.redirectUri;
|
|
61
|
+
|
|
62
|
+
// Early bound on caller-supplied `state` so oversized input fails with a
|
|
63
|
+
// clear error before any crypto work. The authoritative guard on the
|
|
64
|
+
// serialized cookie runs below — this one just avoids confusing users.
|
|
65
|
+
if (options.state !== undefined) {
|
|
66
|
+
const stateBytes = new TextEncoder().encode(options.state).byteLength;
|
|
67
|
+
if (stateBytes > PKCE_MAX_STATE_BYTES) {
|
|
68
|
+
throw new PKCEPayloadTooLargeError(
|
|
69
|
+
`Custom OAuth state is ${stateBytes} bytes, exceeds supported limit of ${PKCE_MAX_STATE_BYTES} bytes. ` +
|
|
70
|
+
`The sealed state is stored as the wos-auth-verifier cookie; oversized values would be silently dropped by the browser.`,
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const pkce = await client.pkce.generate();
|
|
76
|
+
const nonce = crypto.randomUUID();
|
|
77
|
+
|
|
78
|
+
const sealedState = await sealState(encryption, config.cookiePassword, {
|
|
79
|
+
nonce,
|
|
80
|
+
codeVerifier: pkce.codeVerifier,
|
|
81
|
+
returnPathname: options.returnPathname,
|
|
82
|
+
customState: options.state,
|
|
83
|
+
// Persisted so handleCallback's verifier-delete cookie uses the same
|
|
84
|
+
// computed attributes as the original setCookie — notably `secure`,
|
|
85
|
+
// which depends on the redirect URI's protocol.
|
|
86
|
+
redirectUri: options.redirectUri,
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
// Authoritative guard: measure the actual Set-Cookie header the adapter
|
|
90
|
+
// will emit. Catches cases the input-only check can't, like oversized
|
|
91
|
+
// returnPathname combined with near-max state, or an unusually long
|
|
92
|
+
// cookieDomain attribute.
|
|
93
|
+
const cookieOptions = getPKCECookieOptions(config, redirectUri);
|
|
94
|
+
const cookieName = getPKCECookieNameForState(sealedState);
|
|
95
|
+
const serialized = serializeCookie(cookieName, sealedState, cookieOptions);
|
|
96
|
+
const cookieBytes = new TextEncoder().encode(serialized).byteLength;
|
|
97
|
+
if (cookieBytes > PKCE_MAX_COOKIE_BYTES) {
|
|
98
|
+
throw new PKCEPayloadTooLargeError(
|
|
99
|
+
`Sealed PKCE verifier cookie is ${cookieBytes} bytes, exceeds supported limit of ${PKCE_MAX_COOKIE_BYTES} bytes. ` +
|
|
100
|
+
`Reduce the size of options.state, options.returnPathname, or options.redirectUri.`,
|
|
101
|
+
);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const url = client.userManagement.getAuthorizationUrl({
|
|
105
|
+
provider: 'authkit',
|
|
106
|
+
clientId: config.clientId,
|
|
107
|
+
redirectUri,
|
|
108
|
+
screenHint: options.screenHint,
|
|
109
|
+
organizationId: options.organizationId,
|
|
110
|
+
loginHint: options.loginHint,
|
|
111
|
+
prompt: options.prompt,
|
|
112
|
+
state: sealedState,
|
|
113
|
+
codeChallenge: pkce.codeChallenge,
|
|
114
|
+
codeChallengeMethod: pkce.codeChallengeMethod,
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
return {
|
|
118
|
+
url,
|
|
119
|
+
sealedState,
|
|
120
|
+
cookieName,
|
|
121
|
+
cookieOptions,
|
|
122
|
+
};
|
|
123
|
+
}
|
|
@@ -0,0 +1,175 @@
|
|
|
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 { getPKCECookieNameForState } from './cookieName.js';
|
|
9
|
+
import {
|
|
10
|
+
generateAuthorizationUrl,
|
|
11
|
+
PKCE_MAX_COOKIE_BYTES,
|
|
12
|
+
PKCE_MAX_STATE_BYTES,
|
|
13
|
+
} from './generateAuthorizationUrl.js';
|
|
14
|
+
|
|
15
|
+
const config = {
|
|
16
|
+
clientId: 'test-client-id',
|
|
17
|
+
apiKey: 'test-api-key',
|
|
18
|
+
redirectUri: 'https://app.example.com/callback',
|
|
19
|
+
cookiePassword: 'this-is-a-test-password-that-is-32-characters-long!',
|
|
20
|
+
} as const;
|
|
21
|
+
|
|
22
|
+
const mockClient = {
|
|
23
|
+
pkce: {
|
|
24
|
+
generate: async () => ({
|
|
25
|
+
codeVerifier: 'verifier-' + crypto.randomUUID(),
|
|
26
|
+
codeChallenge: 'challenge-' + crypto.randomUUID(),
|
|
27
|
+
codeChallengeMethod: 'S256',
|
|
28
|
+
}),
|
|
29
|
+
},
|
|
30
|
+
userManagement: {
|
|
31
|
+
getAuthorizationUrl: (opts: any) => {
|
|
32
|
+
const params = new URLSearchParams({
|
|
33
|
+
client_id: opts.clientId,
|
|
34
|
+
redirect_uri: opts.redirectUri,
|
|
35
|
+
state: opts.state ?? '',
|
|
36
|
+
code_challenge: opts.codeChallenge ?? '',
|
|
37
|
+
code_challenge_method: opts.codeChallengeMethod ?? '',
|
|
38
|
+
});
|
|
39
|
+
return `https://api.workos.com/sso/authorize?${params.toString()}`;
|
|
40
|
+
},
|
|
41
|
+
getJwksUrl: () => 'https://api.workos.com/sso/jwks/test-client-id',
|
|
42
|
+
},
|
|
43
|
+
} as const;
|
|
44
|
+
|
|
45
|
+
function makeCore() {
|
|
46
|
+
return new AuthKitCore(config as any, mockClient as any, sessionEncryption);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function generate(
|
|
50
|
+
options: Parameters<typeof generateAuthorizationUrl>[0]['options'] = {},
|
|
51
|
+
) {
|
|
52
|
+
return generateAuthorizationUrl({
|
|
53
|
+
client: mockClient as any,
|
|
54
|
+
config: config as any,
|
|
55
|
+
encryption: sessionEncryption,
|
|
56
|
+
options,
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// Tamper, missing cookie, missing state, TTL, and single-byte custom-state
|
|
61
|
+
// round-trip are covered in state.spec.ts and AuthKitCore.spec.ts. These
|
|
62
|
+
// tests exercise the integration seam (generateAuthorizationUrl →
|
|
63
|
+
// verifyCallbackState) for behaviors that only emerge when both modules
|
|
64
|
+
// run together.
|
|
65
|
+
describe('PKCE end-to-end round-trip', () => {
|
|
66
|
+
it('verifyCallbackState recovers the sealed state after generateAuthorizationUrl', async () => {
|
|
67
|
+
const core = makeCore();
|
|
68
|
+
const { sealedState } = await generate({
|
|
69
|
+
returnPathname: '/dashboard',
|
|
70
|
+
state: 'user-opaque',
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
const result = await core.verifyCallbackState({
|
|
74
|
+
stateFromUrl: sealedState,
|
|
75
|
+
cookieValue: sealedState,
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
expect(result.returnPathname).toBe('/dashboard');
|
|
79
|
+
expect(result.customState).toBe('user-opaque');
|
|
80
|
+
expect(typeof result.codeVerifier).toBe('string');
|
|
81
|
+
expect(typeof result.nonce).toBe('string');
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
it('empty-string cookieValue is treated as missing (falsy check)', async () => {
|
|
85
|
+
const core = makeCore();
|
|
86
|
+
const { sealedState } = await generate();
|
|
87
|
+
|
|
88
|
+
await expect(
|
|
89
|
+
core.verifyCallbackState({ stateFromUrl: sealedState, cookieValue: '' }),
|
|
90
|
+
).rejects.toThrow(PKCECookieMissingError);
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
it('returns cookieName derived from the sealed state', async () => {
|
|
94
|
+
const result = await generate();
|
|
95
|
+
expect(result.cookieName).toBe(
|
|
96
|
+
getPKCECookieNameForState(result.sealedState),
|
|
97
|
+
);
|
|
98
|
+
expect(result.cookieName).toMatch(/^wos-auth-verifier-[0-9a-f]{8}$/);
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
it('concurrent sign-ins produce distinct sealedStates (cross-flow rejection)', async () => {
|
|
102
|
+
const core = makeCore();
|
|
103
|
+
const a = await generate();
|
|
104
|
+
const b = await generate();
|
|
105
|
+
|
|
106
|
+
expect(a.sealedState).not.toBe(b.sealedState);
|
|
107
|
+
await expect(
|
|
108
|
+
core.verifyCallbackState({
|
|
109
|
+
stateFromUrl: a.sealedState,
|
|
110
|
+
cookieValue: b.sealedState,
|
|
111
|
+
}),
|
|
112
|
+
).rejects.toThrow(OAuthStateMismatchError);
|
|
113
|
+
});
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
describe('PKCE payload size guards', () => {
|
|
117
|
+
it(`accepts custom state at the ${PKCE_MAX_STATE_BYTES}-byte supported limit`, async () => {
|
|
118
|
+
const state = 'a'.repeat(PKCE_MAX_STATE_BYTES);
|
|
119
|
+
await expect(generate({ state })).resolves.toMatchObject({
|
|
120
|
+
sealedState: expect.any(String),
|
|
121
|
+
});
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
it(`rejects custom state ${PKCE_MAX_STATE_BYTES + 1} bytes or larger before sealing`, async () => {
|
|
125
|
+
const state = 'a'.repeat(PKCE_MAX_STATE_BYTES + 1);
|
|
126
|
+
await expect(generate({ state })).rejects.toThrow(PKCEPayloadTooLargeError);
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
it('counts state size in UTF-8 bytes, not JS characters (multibyte input)', async () => {
|
|
130
|
+
// 2-byte UTF-8 char; 1025 chars = 2050 bytes > 2048.
|
|
131
|
+
const state = '\u00e9'.repeat(1025);
|
|
132
|
+
await expect(generate({ state })).rejects.toThrow(PKCEPayloadTooLargeError);
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
it('rejects oversized serialized cookie from large returnPathname + near-limit state', async () => {
|
|
136
|
+
// Under the per-field state cap, but the sealed cookie still overflows
|
|
137
|
+
// once returnPathname is concatenated into the payload.
|
|
138
|
+
const state = 'a'.repeat(PKCE_MAX_STATE_BYTES);
|
|
139
|
+
const returnPathname = '/' + 'p'.repeat(2048);
|
|
140
|
+
await expect(generate({ state, returnPathname })).rejects.toThrow(
|
|
141
|
+
PKCEPayloadTooLargeError,
|
|
142
|
+
);
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
it('shrinks the effective budget when cookieDomain adds attribute bytes', async () => {
|
|
146
|
+
// cookieDomain=<long> is serialized into every Set-Cookie and counts
|
|
147
|
+
// against the browser's per-cookie budget. A state payload that fits
|
|
148
|
+
// without a Domain attribute can push the serialized header over the
|
|
149
|
+
// limit when Domain is present.
|
|
150
|
+
const longDomain = 'sub.' + 'd'.repeat(200) + '.example.com';
|
|
151
|
+
const configWithDomain = { ...config, cookieDomain: longDomain } as any;
|
|
152
|
+
|
|
153
|
+
const state = 'a'.repeat(PKCE_MAX_STATE_BYTES);
|
|
154
|
+
await expect(
|
|
155
|
+
generateAuthorizationUrl({
|
|
156
|
+
client: mockClient as any,
|
|
157
|
+
config: configWithDomain,
|
|
158
|
+
encryption: sessionEncryption,
|
|
159
|
+
options: { state, returnPathname: '/' + 'p'.repeat(700) },
|
|
160
|
+
}),
|
|
161
|
+
).rejects.toThrow(PKCEPayloadTooLargeError);
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
it(`error message names PKCE_MAX_COOKIE_BYTES (${PKCE_MAX_COOKIE_BYTES})`, async () => {
|
|
165
|
+
const state = 'a'.repeat(PKCE_MAX_STATE_BYTES);
|
|
166
|
+
const returnPathname = '/' + 'p'.repeat(2048);
|
|
167
|
+
try {
|
|
168
|
+
await generate({ state, returnPathname });
|
|
169
|
+
throw new Error('expected throw');
|
|
170
|
+
} catch (err) {
|
|
171
|
+
expect(err).toBeInstanceOf(PKCEPayloadTooLargeError);
|
|
172
|
+
expect((err as Error).message).toContain(String(PKCE_MAX_COOKIE_BYTES));
|
|
173
|
+
}
|
|
174
|
+
});
|
|
175
|
+
});
|
|
@@ -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
|
+
}
|