@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
package/src/core/AuthKitCore.ts
CHANGED
|
@@ -1,8 +1,14 @@
|
|
|
1
1
|
import type { Impersonator, User, WorkOS } from '@workos-inc/node';
|
|
2
2
|
import { createRemoteJWKSet, decodeJwt, jwtVerify } from 'jose';
|
|
3
|
-
import { once } from '../utils.js';
|
|
3
|
+
import { constantTimeEqual, once } from '../utils.js';
|
|
4
4
|
import type { AuthKitConfig } from './config/types.js';
|
|
5
|
-
import {
|
|
5
|
+
import {
|
|
6
|
+
OAuthStateMismatchError,
|
|
7
|
+
PKCECookieMissingError,
|
|
8
|
+
SessionEncryptionError,
|
|
9
|
+
TokenRefreshError,
|
|
10
|
+
} from './errors.js';
|
|
11
|
+
import { type PKCEState, unsealState } from './pkce/state.js';
|
|
6
12
|
import type {
|
|
7
13
|
BaseTokenClaims,
|
|
8
14
|
CustomClaims,
|
|
@@ -104,8 +110,8 @@ export class AuthKitCore {
|
|
|
104
110
|
): BaseTokenClaims & TCustomClaims {
|
|
105
111
|
try {
|
|
106
112
|
return decodeJwt<BaseTokenClaims & TCustomClaims>(token);
|
|
107
|
-
} catch (
|
|
108
|
-
throw new Error('Invalid token');
|
|
113
|
+
} catch (cause) {
|
|
114
|
+
throw new Error('Invalid token', { cause });
|
|
109
115
|
}
|
|
110
116
|
}
|
|
111
117
|
|
|
@@ -147,6 +153,51 @@ export class AuthKitCore {
|
|
|
147
153
|
}
|
|
148
154
|
}
|
|
149
155
|
|
|
156
|
+
/**
|
|
157
|
+
* Verify the OAuth callback state against the PKCE verifier cookie and
|
|
158
|
+
* return the unsealed state blob.
|
|
159
|
+
*
|
|
160
|
+
* Core owns encryption, so verification lives here rather than on
|
|
161
|
+
* AuthService. Byte-compares the query-string `state` against the cookie
|
|
162
|
+
* value BEFORE attempting to decrypt — smaller crypto attack surface and
|
|
163
|
+
* no decryption cost on obvious mismatches.
|
|
164
|
+
*
|
|
165
|
+
* @throws {OAuthStateMismatchError} state missing or does not match cookie
|
|
166
|
+
* @throws {PKCECookieMissingError} cookie not sent — typically a proxy or
|
|
167
|
+
* Set-Cookie propagation issue on the adapter's callback path
|
|
168
|
+
* @throws {SessionEncryptionError} seal tampered, wrong password, TTL expired,
|
|
169
|
+
* or schema mismatch on the unsealed payload
|
|
170
|
+
*/
|
|
171
|
+
async verifyCallbackState(params: {
|
|
172
|
+
stateFromUrl: string | undefined;
|
|
173
|
+
cookieValue: string | undefined;
|
|
174
|
+
}): Promise<PKCEState> {
|
|
175
|
+
const { stateFromUrl, cookieValue } = params;
|
|
176
|
+
|
|
177
|
+
if (!stateFromUrl) {
|
|
178
|
+
throw new OAuthStateMismatchError(
|
|
179
|
+
'Missing state parameter from callback URL',
|
|
180
|
+
);
|
|
181
|
+
}
|
|
182
|
+
if (!cookieValue) {
|
|
183
|
+
throw new PKCECookieMissingError(
|
|
184
|
+
'PKCE verifier cookie missing — cannot verify OAuth state. Ensure Set-Cookie headers are propagated on redirects.',
|
|
185
|
+
);
|
|
186
|
+
}
|
|
187
|
+
const encoder = new TextEncoder();
|
|
188
|
+
const urlBytes = encoder.encode(stateFromUrl);
|
|
189
|
+
const cookieBytes = encoder.encode(cookieValue);
|
|
190
|
+
if (!constantTimeEqual(urlBytes, cookieBytes)) {
|
|
191
|
+
throw new OAuthStateMismatchError('OAuth state mismatch');
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
return unsealState(
|
|
195
|
+
this.encryption,
|
|
196
|
+
this.config.cookiePassword,
|
|
197
|
+
cookieValue,
|
|
198
|
+
);
|
|
199
|
+
}
|
|
200
|
+
|
|
150
201
|
/**
|
|
151
202
|
* Refresh tokens using WorkOS API.
|
|
152
203
|
*
|
|
@@ -64,4 +64,66 @@ describe('ironWebcryptoEncryption', () => {
|
|
|
64
64
|
expect(unsealed).toEqual(testData);
|
|
65
65
|
});
|
|
66
66
|
});
|
|
67
|
+
|
|
68
|
+
describe('TTL enforcement', () => {
|
|
69
|
+
beforeEach(() => {
|
|
70
|
+
vi.useFakeTimers();
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
afterEach(() => {
|
|
74
|
+
vi.useRealTimers();
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
it('unseals successfully before TTL expires', async () => {
|
|
78
|
+
vi.setSystemTime(new Date('2026-01-01T00:00:00.000Z'));
|
|
79
|
+
const sealed = await encryption.sealData(testData, {
|
|
80
|
+
password: testPassword,
|
|
81
|
+
ttl: 600,
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
// Advance less than TTL
|
|
85
|
+
vi.setSystemTime(new Date('2026-01-01T00:09:00.000Z')); // +540s
|
|
86
|
+
const unsealed = await encryption.unsealData(sealed, {
|
|
87
|
+
password: testPassword,
|
|
88
|
+
ttl: 600,
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
expect(unsealed).toEqual(testData);
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
it('throws when TTL has expired on unseal', async () => {
|
|
95
|
+
vi.setSystemTime(new Date('2026-01-01T00:00:00.000Z'));
|
|
96
|
+
const sealed = await encryption.sealData(testData, {
|
|
97
|
+
password: testPassword,
|
|
98
|
+
ttl: 1,
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
// Advance past TTL + skew (60s default)
|
|
102
|
+
vi.setSystemTime(new Date('2026-01-01T00:02:00.000Z'));
|
|
103
|
+
await expect(
|
|
104
|
+
encryption.unsealData(sealed, {
|
|
105
|
+
password: testPassword,
|
|
106
|
+
ttl: 1,
|
|
107
|
+
}),
|
|
108
|
+
).rejects.toThrow();
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
it('preserves session-cookie flow: seal without TTL, unseal without TTL', async () => {
|
|
112
|
+
// This is the invariant AuthKitCore.encryptSession/decryptSession relies on.
|
|
113
|
+
vi.setSystemTime(new Date('2026-01-01T00:00:00.000Z'));
|
|
114
|
+
const sealed = await encryption.sealData(testData, {
|
|
115
|
+
password: testPassword,
|
|
116
|
+
// no ttl — matches AuthKitCore.encryptSession
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
// Advance time substantially — session cookies must still unseal.
|
|
120
|
+
vi.setSystemTime(new Date('2027-01-01T00:00:00.000Z'));
|
|
121
|
+
const unsealed = await encryption.unsealData(sealed, {
|
|
122
|
+
password: testPassword,
|
|
123
|
+
// no ttl — matches AuthKitCore.decryptSession
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
expect(unsealed).toEqual(testData);
|
|
127
|
+
});
|
|
128
|
+
});
|
|
67
129
|
});
|
|
@@ -58,7 +58,7 @@ export class SessionEncryption implements SessionEncryptionInterface {
|
|
|
58
58
|
// Decrypt data from iron-session with HMAC verification
|
|
59
59
|
async unsealData<T = unknown>(
|
|
60
60
|
encryptedData: string,
|
|
61
|
-
{ password }: { password: string },
|
|
61
|
+
{ password, ttl = 0 }: { password: string; ttl?: number | undefined },
|
|
62
62
|
): Promise<T> {
|
|
63
63
|
// First, parse the seal to extract the version
|
|
64
64
|
const { sealWithoutVersion, tokenVersion } = this.parseSeal(encryptedData);
|
|
@@ -80,7 +80,7 @@ export class SessionEncryption implements SessionEncryptionInterface {
|
|
|
80
80
|
iterations: 1,
|
|
81
81
|
minPasswordlength: 32,
|
|
82
82
|
},
|
|
83
|
-
ttl: 0
|
|
83
|
+
ttl: ttl * 1000, // Convert seconds to milliseconds. 0 = no TTL enforcement.
|
|
84
84
|
timestampSkewSec: 60,
|
|
85
85
|
localtimeOffsetMsec: 0,
|
|
86
86
|
});
|
package/src/core/errors.spec.ts
CHANGED
|
@@ -1,100 +1,29 @@
|
|
|
1
1
|
import {
|
|
2
2
|
AuthKitError,
|
|
3
|
+
OAuthStateMismatchError,
|
|
4
|
+
PKCECookieMissingError,
|
|
5
|
+
PKCEPayloadTooLargeError,
|
|
3
6
|
SessionEncryptionError,
|
|
4
7
|
TokenValidationError,
|
|
5
8
|
TokenRefreshError,
|
|
6
9
|
} from './errors.js';
|
|
7
10
|
|
|
8
11
|
describe('AuthKitError', () => {
|
|
9
|
-
it('
|
|
10
|
-
const
|
|
11
|
-
|
|
12
|
-
expect(error.message).toBe('Test error');
|
|
13
|
-
expect(error.name).toBe('AuthKitError');
|
|
14
|
-
expect(error).toBeInstanceOf(Error);
|
|
15
|
-
});
|
|
16
|
-
|
|
17
|
-
it('creates error with cause', () => {
|
|
18
|
-
const originalError = new Error('Original error');
|
|
19
|
-
const error = new AuthKitError('Test error', originalError);
|
|
20
|
-
|
|
21
|
-
expect(error.cause).toBe(originalError);
|
|
22
|
-
});
|
|
23
|
-
|
|
24
|
-
it('creates error with data', () => {
|
|
25
|
-
const data = { userId: '123', action: 'login' };
|
|
26
|
-
const error = new AuthKitError('Test error', undefined, data);
|
|
27
|
-
|
|
28
|
-
expect(error.data).toEqual(data);
|
|
29
|
-
});
|
|
30
|
-
|
|
31
|
-
it('creates error with cause and data', () => {
|
|
32
|
-
const originalError = new Error('Original error');
|
|
12
|
+
it('carries message, cause, and arbitrary data', () => {
|
|
13
|
+
const cause = new Error('Original');
|
|
33
14
|
const data = { userId: '123' };
|
|
34
|
-
const error = new AuthKitError('Test
|
|
15
|
+
const error = new AuthKitError('Test', cause, data);
|
|
35
16
|
|
|
36
|
-
expect(error.
|
|
17
|
+
expect(error.message).toBe('Test');
|
|
18
|
+
expect(error.name).toBe('AuthKitError');
|
|
19
|
+
expect(error.cause).toBe(cause);
|
|
37
20
|
expect(error.data).toEqual(data);
|
|
38
|
-
});
|
|
39
|
-
});
|
|
40
|
-
|
|
41
|
-
describe('SessionEncryptionError', () => {
|
|
42
|
-
it('creates error with correct name', () => {
|
|
43
|
-
const error = new SessionEncryptionError('Encryption failed');
|
|
44
|
-
|
|
45
|
-
expect(error.name).toBe('SessionEncryptionError');
|
|
46
|
-
expect(error.message).toBe('Encryption failed');
|
|
47
|
-
expect(error).toBeInstanceOf(AuthKitError);
|
|
48
21
|
expect(error).toBeInstanceOf(Error);
|
|
49
22
|
});
|
|
50
|
-
|
|
51
|
-
it('creates error with cause', () => {
|
|
52
|
-
const originalError = new Error('Crypto error');
|
|
53
|
-
const error = new SessionEncryptionError(
|
|
54
|
-
'Encryption failed',
|
|
55
|
-
originalError,
|
|
56
|
-
);
|
|
57
|
-
|
|
58
|
-
expect(error.cause).toBe(originalError);
|
|
59
|
-
});
|
|
60
23
|
});
|
|
61
24
|
|
|
62
|
-
describe('
|
|
63
|
-
it('
|
|
64
|
-
const error = new TokenValidationError('Token invalid');
|
|
65
|
-
|
|
66
|
-
expect(error.name).toBe('TokenValidationError');
|
|
67
|
-
expect(error.message).toBe('Token invalid');
|
|
68
|
-
expect(error).toBeInstanceOf(AuthKitError);
|
|
69
|
-
expect(error).toBeInstanceOf(Error);
|
|
70
|
-
});
|
|
71
|
-
|
|
72
|
-
it('creates error with cause', () => {
|
|
73
|
-
const originalError = new Error('JWT malformed');
|
|
74
|
-
const error = new TokenValidationError('Token invalid', originalError);
|
|
75
|
-
|
|
76
|
-
expect(error.cause).toBe(originalError);
|
|
77
|
-
});
|
|
78
|
-
});
|
|
79
|
-
|
|
80
|
-
describe('TokenRefreshError', () => {
|
|
81
|
-
it('creates error with correct name', () => {
|
|
82
|
-
const error = new TokenRefreshError('Refresh failed');
|
|
83
|
-
|
|
84
|
-
expect(error.name).toBe('TokenRefreshError');
|
|
85
|
-
expect(error.message).toBe('Refresh failed');
|
|
86
|
-
expect(error).toBeInstanceOf(AuthKitError);
|
|
87
|
-
expect(error).toBeInstanceOf(Error);
|
|
88
|
-
});
|
|
89
|
-
|
|
90
|
-
it('creates error with cause', () => {
|
|
91
|
-
const originalError = new Error('Network error');
|
|
92
|
-
const error = new TokenRefreshError('Refresh failed', originalError);
|
|
93
|
-
|
|
94
|
-
expect(error.cause).toBe(originalError);
|
|
95
|
-
});
|
|
96
|
-
|
|
97
|
-
it('creates error with userId and sessionId', () => {
|
|
25
|
+
describe('TokenRefreshError context', () => {
|
|
26
|
+
it('captures optional userId and sessionId', () => {
|
|
98
27
|
const error = new TokenRefreshError('Refresh failed', undefined, {
|
|
99
28
|
userId: 'user_123',
|
|
100
29
|
sessionId: 'session_456',
|
|
@@ -104,37 +33,7 @@ describe('TokenRefreshError', () => {
|
|
|
104
33
|
expect(error.sessionId).toBe('session_456');
|
|
105
34
|
});
|
|
106
35
|
|
|
107
|
-
it('
|
|
108
|
-
const originalError = new Error('Network error');
|
|
109
|
-
const error = new TokenRefreshError('Refresh failed', originalError, {
|
|
110
|
-
userId: 'user_123',
|
|
111
|
-
sessionId: 'session_456',
|
|
112
|
-
});
|
|
113
|
-
|
|
114
|
-
expect(error.cause).toBe(originalError);
|
|
115
|
-
expect(error.userId).toBe('user_123');
|
|
116
|
-
expect(error.sessionId).toBe('session_456');
|
|
117
|
-
});
|
|
118
|
-
|
|
119
|
-
it('creates error with partial context (userId only)', () => {
|
|
120
|
-
const error = new TokenRefreshError('Refresh failed', undefined, {
|
|
121
|
-
userId: 'user_123',
|
|
122
|
-
});
|
|
123
|
-
|
|
124
|
-
expect(error.userId).toBe('user_123');
|
|
125
|
-
expect(error.sessionId).toBeUndefined();
|
|
126
|
-
});
|
|
127
|
-
|
|
128
|
-
it('creates error with partial context (sessionId only)', () => {
|
|
129
|
-
const error = new TokenRefreshError('Refresh failed', undefined, {
|
|
130
|
-
sessionId: 'session_456',
|
|
131
|
-
});
|
|
132
|
-
|
|
133
|
-
expect(error.userId).toBeUndefined();
|
|
134
|
-
expect(error.sessionId).toBe('session_456');
|
|
135
|
-
});
|
|
136
|
-
|
|
137
|
-
it('has undefined properties when no context provided', () => {
|
|
36
|
+
it('leaves context fields undefined when omitted', () => {
|
|
138
37
|
const error = new TokenRefreshError('Refresh failed');
|
|
139
38
|
|
|
140
39
|
expect(error.userId).toBeUndefined();
|
|
@@ -142,36 +41,28 @@ describe('TokenRefreshError', () => {
|
|
|
142
41
|
});
|
|
143
42
|
});
|
|
144
43
|
|
|
145
|
-
describe('error
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
it('can be caught as AuthKitError', () => {
|
|
165
|
-
const errors = [
|
|
166
|
-
new SessionEncryptionError('test'),
|
|
167
|
-
new TokenValidationError('test'),
|
|
168
|
-
new TokenRefreshError('test'),
|
|
169
|
-
];
|
|
170
|
-
|
|
171
|
-
errors.forEach(error => {
|
|
44
|
+
describe('error subclasses', () => {
|
|
45
|
+
const cases: Array<[string, new (msg: string) => AuthKitError]> = [
|
|
46
|
+
['SessionEncryptionError', SessionEncryptionError],
|
|
47
|
+
['TokenValidationError', TokenValidationError],
|
|
48
|
+
['TokenRefreshError', TokenRefreshError],
|
|
49
|
+
['OAuthStateMismatchError', OAuthStateMismatchError],
|
|
50
|
+
['PKCECookieMissingError', PKCECookieMissingError],
|
|
51
|
+
['PKCEPayloadTooLargeError', PKCEPayloadTooLargeError],
|
|
52
|
+
];
|
|
53
|
+
|
|
54
|
+
it.each(cases)(
|
|
55
|
+
'%s preserves name, message, and AuthKitError inheritance',
|
|
56
|
+
(name, Ctor) => {
|
|
57
|
+
const error = new Ctor('msg');
|
|
58
|
+
|
|
59
|
+
expect(error.name).toBe(name);
|
|
60
|
+
expect(error.message).toBe('msg');
|
|
61
|
+
expect(error).toBeInstanceOf(Ctor);
|
|
62
|
+
expect(error).toBeInstanceOf(AuthKitError);
|
|
172
63
|
expect(() => {
|
|
173
64
|
throw error;
|
|
174
65
|
}).toThrow(AuthKitError);
|
|
175
|
-
}
|
|
176
|
-
|
|
66
|
+
},
|
|
67
|
+
);
|
|
177
68
|
});
|
package/src/core/errors.ts
CHANGED
|
@@ -23,6 +23,27 @@ export class TokenValidationError extends AuthKitError {
|
|
|
23
23
|
}
|
|
24
24
|
}
|
|
25
25
|
|
|
26
|
+
export class OAuthStateMismatchError extends AuthKitError {
|
|
27
|
+
constructor(message: string, cause?: unknown) {
|
|
28
|
+
super(message, cause);
|
|
29
|
+
this.name = 'OAuthStateMismatchError';
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export class PKCECookieMissingError extends AuthKitError {
|
|
34
|
+
constructor(message: string, cause?: unknown) {
|
|
35
|
+
super(message, cause);
|
|
36
|
+
this.name = 'PKCECookieMissingError';
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export class PKCEPayloadTooLargeError extends AuthKitError {
|
|
41
|
+
constructor(message: string, cause?: unknown) {
|
|
42
|
+
super(message, cause);
|
|
43
|
+
this.name = 'PKCEPayloadTooLargeError';
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
26
47
|
export class TokenRefreshError extends AuthKitError {
|
|
27
48
|
readonly userId?: string;
|
|
28
49
|
readonly sessionId?: string;
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest';
|
|
2
|
+
import {
|
|
3
|
+
PKCE_COOKIE_PREFIX,
|
|
4
|
+
getPKCECookieNameForState,
|
|
5
|
+
fnv1a32Hex,
|
|
6
|
+
} from './cookieName.js';
|
|
7
|
+
|
|
8
|
+
describe('fnv1a32Hex', () => {
|
|
9
|
+
// Known-answer tests against the reference FNV-1a 32-bit spec
|
|
10
|
+
// (http://www.isthe.com/chongo/tech/comp/fnv/). Empty string is the
|
|
11
|
+
// FNV offset basis 0x811c9dc5.
|
|
12
|
+
it('hashes the empty string to the FNV offset basis', () => {
|
|
13
|
+
expect(fnv1a32Hex('')).toBe('811c9dc5');
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
it('hashes "a" to 0xe40c292c', () => {
|
|
17
|
+
expect(fnv1a32Hex('a')).toBe('e40c292c');
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
it('hashes "foobar" to 0xbf9cf968', () => {
|
|
21
|
+
expect(fnv1a32Hex('foobar')).toBe('bf9cf968');
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
it('returns a zero-padded 8-char hex string', () => {
|
|
25
|
+
expect(fnv1a32Hex('x')).toMatch(/^[0-9a-f]{8}$/);
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
it('is deterministic', () => {
|
|
29
|
+
expect(fnv1a32Hex('some-sealed-state')).toBe(
|
|
30
|
+
fnv1a32Hex('some-sealed-state'),
|
|
31
|
+
);
|
|
32
|
+
});
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
describe('getPKCECookieNameForState', () => {
|
|
36
|
+
it('prefixes with wos-auth-verifier and appends an 8-char hex hash', () => {
|
|
37
|
+
expect(getPKCECookieNameForState('any-state')).toMatch(
|
|
38
|
+
/^wos-auth-verifier-[0-9a-f]{8}$/,
|
|
39
|
+
);
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
it('produces different names for different states', () => {
|
|
43
|
+
expect(getPKCECookieNameForState('state-a')).not.toBe(
|
|
44
|
+
getPKCECookieNameForState('state-b'),
|
|
45
|
+
);
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
it('is deterministic for the same input', () => {
|
|
49
|
+
const s = 'sealed-' + 'x'.repeat(200);
|
|
50
|
+
expect(getPKCECookieNameForState(s)).toBe(getPKCECookieNameForState(s));
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
it('exports the prefix constant', () => {
|
|
54
|
+
expect(PKCE_COOKIE_PREFIX).toBe('wos-auth-verifier');
|
|
55
|
+
});
|
|
56
|
+
});
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/** Stable prefix for all PKCE verifier cookies. */
|
|
2
|
+
export const PKCE_COOKIE_PREFIX = 'wos-auth-verifier';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* FNV-1a 32-bit hash of the input, returned as a zero-padded 8-char
|
|
6
|
+
* lowercase hex string. Used purely as a namespacing mechanism — not
|
|
7
|
+
* security-sensitive. Collision probability is ~1/4B per pair; a
|
|
8
|
+
* collision routes one flow's callback to the wrong cookie, which
|
|
9
|
+
* then fails byte-equality in `verifyCallbackState` (fail-closed).
|
|
10
|
+
*/
|
|
11
|
+
export function fnv1a32Hex(input: string): string {
|
|
12
|
+
let hash = 0x811c9dc5;
|
|
13
|
+
const bytes = new TextEncoder().encode(input);
|
|
14
|
+
for (const byte of bytes) {
|
|
15
|
+
hash = Math.imul(hash ^ byte, 0x01000193) >>> 0;
|
|
16
|
+
}
|
|
17
|
+
return hash.toString(16).padStart(8, '0');
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Derive a flow-specific PKCE verifier cookie name from the sealed
|
|
22
|
+
* state blob. Each concurrent OAuth flow gets its own cookie so
|
|
23
|
+
* parallel sign-ins from multiple tabs don't clobber each other.
|
|
24
|
+
*/
|
|
25
|
+
export function getPKCECookieNameForState(state: string): string {
|
|
26
|
+
return `${PKCE_COOKIE_PREFIX}-${fnv1a32Hex(state)}`;
|
|
27
|
+
}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import type { AuthKitConfig } from '../config/types.js';
|
|
2
|
+
import { getPKCECookieOptions } from './cookieOptions.js';
|
|
3
|
+
|
|
4
|
+
const baseConfig: AuthKitConfig = {
|
|
5
|
+
clientId: 'client_test',
|
|
6
|
+
apiKey: 'sk_test',
|
|
7
|
+
redirectUri: 'https://app.example.com/callback',
|
|
8
|
+
cookiePassword: 'x'.repeat(48),
|
|
9
|
+
} as AuthKitConfig;
|
|
10
|
+
|
|
11
|
+
describe('getPKCECookieOptions', () => {
|
|
12
|
+
describe('sameSite behavior', () => {
|
|
13
|
+
it.each([
|
|
14
|
+
['strict', 'lax'],
|
|
15
|
+
['lax', 'lax'],
|
|
16
|
+
['none', 'none'],
|
|
17
|
+
] as const)(
|
|
18
|
+
'maps cookieSameSite=%s to sameSite=%s',
|
|
19
|
+
(configured, expected) => {
|
|
20
|
+
const config = { ...baseConfig, cookieSameSite: configured };
|
|
21
|
+
const opts = getPKCECookieOptions(config);
|
|
22
|
+
|
|
23
|
+
expect(opts.sameSite).toBe(expected);
|
|
24
|
+
},
|
|
25
|
+
);
|
|
26
|
+
|
|
27
|
+
it('defaults to lax when cookieSameSite is undefined', () => {
|
|
28
|
+
const opts = getPKCECookieOptions(baseConfig);
|
|
29
|
+
|
|
30
|
+
expect(opts.sameSite).toBe('lax');
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
it('accepts mixed-case sameSite values', () => {
|
|
34
|
+
const config = { ...baseConfig, cookieSameSite: 'NONE' as any };
|
|
35
|
+
const opts = getPKCECookieOptions(config);
|
|
36
|
+
|
|
37
|
+
expect(opts.sameSite).toBe('none');
|
|
38
|
+
});
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
describe('secure flag', () => {
|
|
42
|
+
it('derives secure=true from https redirectUri', () => {
|
|
43
|
+
const opts = getPKCECookieOptions({
|
|
44
|
+
...baseConfig,
|
|
45
|
+
redirectUri: 'https://app.example.com/callback',
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
expect(opts.secure).toBe(true);
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
it('derives secure=false from http redirectUri', () => {
|
|
52
|
+
const opts = getPKCECookieOptions({
|
|
53
|
+
...baseConfig,
|
|
54
|
+
redirectUri: 'http://localhost:3000/callback',
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
expect(opts.secure).toBe(false);
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
it('prefers explicit redirectUri arg over config', () => {
|
|
61
|
+
const opts = getPKCECookieOptions(
|
|
62
|
+
{ ...baseConfig, redirectUri: 'https://prod.example.com/callback' },
|
|
63
|
+
'http://localhost:3000/callback',
|
|
64
|
+
);
|
|
65
|
+
|
|
66
|
+
expect(opts.secure).toBe(false);
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
it('fail-closes to secure=true on invalid URL', () => {
|
|
70
|
+
const opts = getPKCECookieOptions({
|
|
71
|
+
...baseConfig,
|
|
72
|
+
redirectUri: 'not-a-valid-url',
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
expect(opts.secure).toBe(true);
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
it('forces secure=true when sameSite=none regardless of protocol', () => {
|
|
79
|
+
const opts = getPKCECookieOptions({
|
|
80
|
+
...baseConfig,
|
|
81
|
+
cookieSameSite: 'none',
|
|
82
|
+
redirectUri: 'http://localhost:3000/callback',
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
expect(opts.secure).toBe(true);
|
|
86
|
+
});
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
describe('invariants', () => {
|
|
90
|
+
it('always sets httpOnly=true', () => {
|
|
91
|
+
const opts = getPKCECookieOptions(baseConfig);
|
|
92
|
+
|
|
93
|
+
expect(opts.httpOnly).toBe(true);
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
it('always sets maxAge=600', () => {
|
|
97
|
+
const opts = getPKCECookieOptions(baseConfig);
|
|
98
|
+
|
|
99
|
+
expect(opts.maxAge).toBe(600);
|
|
100
|
+
});
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
describe('path', () => {
|
|
104
|
+
it.each([
|
|
105
|
+
['config callback path', 'https://app.example.com/callback'],
|
|
106
|
+
['nested callback path', 'https://app.example.com/auth/v2/callback'],
|
|
107
|
+
['host-only', 'https://app.example.com'],
|
|
108
|
+
['invalid url', 'not-a-valid-url'],
|
|
109
|
+
])(
|
|
110
|
+
"is always '/' regardless of redirectUri (%s)",
|
|
111
|
+
(_label, redirectUri) => {
|
|
112
|
+
const opts = getPKCECookieOptions({ ...baseConfig, redirectUri });
|
|
113
|
+
|
|
114
|
+
expect(opts.path).toBe('/');
|
|
115
|
+
},
|
|
116
|
+
);
|
|
117
|
+
|
|
118
|
+
it("is '/' even when per-call redirectUri override is supplied", () => {
|
|
119
|
+
const opts = getPKCECookieOptions(
|
|
120
|
+
baseConfig,
|
|
121
|
+
'https://app.example.com/some/other/path',
|
|
122
|
+
);
|
|
123
|
+
|
|
124
|
+
expect(opts.path).toBe('/');
|
|
125
|
+
});
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
describe('domain passthrough', () => {
|
|
129
|
+
it('includes domain when configured', () => {
|
|
130
|
+
const opts = getPKCECookieOptions({
|
|
131
|
+
...baseConfig,
|
|
132
|
+
cookieDomain: '.example.com',
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
expect(opts.domain).toBe('.example.com');
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
it('omits domain when not configured', () => {
|
|
139
|
+
const opts = getPKCECookieOptions(baseConfig);
|
|
140
|
+
|
|
141
|
+
expect(opts.domain).toBeUndefined();
|
|
142
|
+
});
|
|
143
|
+
});
|
|
144
|
+
});
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import type { AuthKitConfig } from '../config/types.js';
|
|
2
|
+
import type { CookieOptions } from '../session/types.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* PKCE verifier cookie lifetime (seconds). Matches the 10-minute convention
|
|
6
|
+
* used by Arctic, openid-client, Clerk, and Okta for short-lived OAuth state
|
|
7
|
+
* cookies — long enough to accommodate slow sign-ins (out-of-band 2FA, tab
|
|
8
|
+
* switching) and short enough to keep the replay window tight if the sealed
|
|
9
|
+
* blob leaks.
|
|
10
|
+
*
|
|
11
|
+
* The same value is used as both the `Max-Age` cookie attribute and the
|
|
12
|
+
* sealed payload's TTL, so both layers reject a stale blob.
|
|
13
|
+
*/
|
|
14
|
+
export const PKCE_COOKIE_MAX_AGE = 600;
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Compute PKCE verifier cookie options from config + the resolved redirect URI.
|
|
18
|
+
*
|
|
19
|
+
* Behavior:
|
|
20
|
+
* - `sameSite: 'strict'` is downgraded to `'lax'` so the cookie survives the
|
|
21
|
+
* cross-site redirect back from WorkOS.
|
|
22
|
+
* - `sameSite: 'none'` is preserved (iframe/embed flows require it).
|
|
23
|
+
* - `secure` is forced to `true` when `sameSite === 'none'` (required by
|
|
24
|
+
* modern browsers). Otherwise it is inferred from the redirect URI's
|
|
25
|
+
* protocol, defaulting fail-closed to `true` on invalid/missing URLs.
|
|
26
|
+
* - `path` is always `/`. The cookie gets sent on every same-origin request
|
|
27
|
+
* during the 10-minute window, which is fine — it's HttpOnly and expires
|
|
28
|
+
* quickly. The tradeoff favors DX: path-scoped cookies are invisible in
|
|
29
|
+
* Chrome DevTools' Application panel from any page outside the scoped
|
|
30
|
+
* path, which makes PKCE wiring look broken even when it works.
|
|
31
|
+
*
|
|
32
|
+
* Internal helper — not exported from the package. Callers get cookie options
|
|
33
|
+
* indirectly via `AuthService.createSignIn` / `clearPendingVerifier`.
|
|
34
|
+
*/
|
|
35
|
+
export function getPKCECookieOptions(
|
|
36
|
+
config: AuthKitConfig,
|
|
37
|
+
redirectUri?: string,
|
|
38
|
+
): CookieOptions {
|
|
39
|
+
const configuredSameSite = (config.cookieSameSite ?? 'lax').toLowerCase();
|
|
40
|
+
const sameSite: 'lax' | 'none' =
|
|
41
|
+
configuredSameSite === 'none' ? 'none' : 'lax';
|
|
42
|
+
|
|
43
|
+
const urlString = redirectUri ?? config.redirectUri;
|
|
44
|
+
let secure = true;
|
|
45
|
+
if (urlString && sameSite !== 'none') {
|
|
46
|
+
try {
|
|
47
|
+
secure = new URL(urlString).protocol === 'https:';
|
|
48
|
+
} catch {
|
|
49
|
+
// Fail-closed: secure stays true.
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
return {
|
|
54
|
+
path: '/',
|
|
55
|
+
httpOnly: true,
|
|
56
|
+
secure,
|
|
57
|
+
sameSite,
|
|
58
|
+
maxAge: PKCE_COOKIE_MAX_AGE,
|
|
59
|
+
...(config.cookieDomain ? { domain: config.cookieDomain } : {}),
|
|
60
|
+
};
|
|
61
|
+
}
|