@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
|
@@ -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
|
+
}
|
|
@@ -72,9 +72,57 @@ export interface Session {
|
|
|
72
72
|
impersonator?: Impersonator;
|
|
73
73
|
}
|
|
74
74
|
|
|
75
|
+
/**
|
|
76
|
+
* Map of HTTP response headers.
|
|
77
|
+
*
|
|
78
|
+
* `Set-Cookie` MUST be represented as `string[]` when multiple values exist
|
|
79
|
+
* — adapters must append each entry as its own header, never comma-join.
|
|
80
|
+
* A comma-joined `Set-Cookie` string is not a valid single HTTP header.
|
|
81
|
+
*/
|
|
75
82
|
export type HeadersBag = Record<string, string | string[]>;
|
|
76
83
|
|
|
77
84
|
export interface SessionStorage<TRequest, TResponse, TOptions = unknown> {
|
|
85
|
+
/**
|
|
86
|
+
* Read a named cookie from a request.
|
|
87
|
+
*
|
|
88
|
+
* MUST return the URL-decoded value (the inverse of `setCookie`'s
|
|
89
|
+
* `encodeURIComponent` on write). Returning raw on-wire bytes will break
|
|
90
|
+
* byte-comparison against the original value — notably PKCE state
|
|
91
|
+
* verification — for any seal format that contains characters
|
|
92
|
+
* `encodeURIComponent` escapes (`+`, `=`, etc.).
|
|
93
|
+
*
|
|
94
|
+
* @param request Framework-specific request object.
|
|
95
|
+
* @param name Cookie name.
|
|
96
|
+
* @returns The URL-decoded cookie value or null if absent.
|
|
97
|
+
*/
|
|
98
|
+
getCookie(request: TRequest, name: string): Promise<string | null>;
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Write a named cookie to a response.
|
|
102
|
+
* @param response Framework-specific response object (or undefined to emit headers only).
|
|
103
|
+
* @param name Cookie name.
|
|
104
|
+
* @param value Cookie value (will be URL-encoded).
|
|
105
|
+
* @param options Per-call cookie options.
|
|
106
|
+
*/
|
|
107
|
+
setCookie(
|
|
108
|
+
response: TResponse | undefined,
|
|
109
|
+
name: string,
|
|
110
|
+
value: string,
|
|
111
|
+
options: CookieOptions,
|
|
112
|
+
): Promise<{ response?: TResponse; headers?: HeadersBag }>;
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Clear a named cookie by emitting a Set-Cookie with Max-Age=0.
|
|
116
|
+
* @param response Framework-specific response object (or undefined to emit headers only).
|
|
117
|
+
* @param name Cookie name.
|
|
118
|
+
* @param options Cookie options (must match those used at set time, especially `path`).
|
|
119
|
+
*/
|
|
120
|
+
clearCookie(
|
|
121
|
+
response: TResponse | undefined,
|
|
122
|
+
name: string,
|
|
123
|
+
options: CookieOptions,
|
|
124
|
+
): Promise<{ response?: TResponse; headers?: HeadersBag }>;
|
|
125
|
+
|
|
78
126
|
/*
|
|
79
127
|
* Extract session data from a request object
|
|
80
128
|
* @param request the framework-specific request object.
|
|
@@ -117,10 +165,30 @@ export interface SessionEncryption {
|
|
|
117
165
|
encryptedData: string,
|
|
118
166
|
options: {
|
|
119
167
|
password: string;
|
|
168
|
+
ttl?: number | undefined;
|
|
120
169
|
},
|
|
121
170
|
) => Promise<T>;
|
|
122
171
|
}
|
|
123
172
|
|
|
173
|
+
/**
|
|
174
|
+
* Result shape returned by `createAuthorization` / `createSignIn` / `createSignUp`.
|
|
175
|
+
*
|
|
176
|
+
* The verifier cookie is written internally via `SessionStorage.setCookie` — callers
|
|
177
|
+
* only need to redirect the browser to `url` and apply any returned `headers`/`response`.
|
|
178
|
+
*/
|
|
179
|
+
export type CreateAuthorizationResult<TResponse> = {
|
|
180
|
+
url: string;
|
|
181
|
+
response?: TResponse;
|
|
182
|
+
headers?: HeadersBag;
|
|
183
|
+
/**
|
|
184
|
+
* Name of the PKCE verifier cookie written during this call. Useful
|
|
185
|
+
* for assertion-in-tests and for adapters that want to log the flow
|
|
186
|
+
* identifier. NOT the shape `clearPendingVerifier` consumes — that
|
|
187
|
+
* method takes `state`, not `cookieName`.
|
|
188
|
+
*/
|
|
189
|
+
cookieName: string;
|
|
190
|
+
};
|
|
191
|
+
|
|
124
192
|
export interface CookieOptions {
|
|
125
193
|
path?: string;
|
|
126
194
|
domain?: string;
|
|
@@ -142,12 +210,25 @@ export interface AuthUrlOptions {
|
|
|
142
210
|
organizationId?: string;
|
|
143
211
|
loginHint?: string;
|
|
144
212
|
prompt?: 'login' | 'none' | 'consent' | 'select_account';
|
|
145
|
-
/**
|
|
213
|
+
/**
|
|
214
|
+
* Custom state to pass through the OAuth flow. Returned in handleCallback.
|
|
215
|
+
*
|
|
216
|
+
* Bounded at 2048 UTF-8 bytes. The value is sealed alongside the PKCE
|
|
217
|
+
* verifier and stored in the `wos-auth-verifier` cookie; oversized values
|
|
218
|
+
* would push the cookie past the per-cookie browser limit (~4 KB) and
|
|
219
|
+
* would be silently dropped. Values over the supported limit throw
|
|
220
|
+
* `PKCEPayloadTooLargeError` at sign-in time.
|
|
221
|
+
*
|
|
222
|
+
* Note: total sealed payload size — not just `state` — drives the hard
|
|
223
|
+
* failure. Combining a large `returnPathname`, `redirectUri`, or
|
|
224
|
+
* `cookieDomain` with near-limit `state` can still overflow.
|
|
225
|
+
*/
|
|
146
226
|
state?: string;
|
|
147
227
|
}
|
|
148
228
|
|
|
149
229
|
/**
|
|
150
|
-
* Options for
|
|
230
|
+
* Options for `createAuthorization` / `createSignIn` / `createSignUp`,
|
|
231
|
+
* including the `screenHint` selector used by the sign-in/sign-up variants.
|
|
151
232
|
*/
|
|
152
233
|
export interface GetAuthorizationUrlOptions extends AuthUrlOptions {
|
|
153
234
|
screenHint?: 'sign-up' | 'sign-in';
|
package/src/index.ts
CHANGED
|
@@ -37,6 +37,14 @@ export { AuthOperations } from './operations/AuthOperations.js';
|
|
|
37
37
|
// ============================================
|
|
38
38
|
export { CookieSessionStorage } from './core/session/CookieSessionStorage.js';
|
|
39
39
|
|
|
40
|
+
// ============================================
|
|
41
|
+
// PKCE Helpers
|
|
42
|
+
// ============================================
|
|
43
|
+
export {
|
|
44
|
+
PKCE_COOKIE_PREFIX,
|
|
45
|
+
getPKCECookieNameForState,
|
|
46
|
+
} from './core/pkce/cookieName.js';
|
|
47
|
+
|
|
40
48
|
// ============================================
|
|
41
49
|
// Encryption Fallback
|
|
42
50
|
// ============================================
|
|
@@ -63,6 +71,9 @@ export { getWorkOS } from './core/client/workos.js';
|
|
|
63
71
|
// ============================================
|
|
64
72
|
export {
|
|
65
73
|
AuthKitError,
|
|
74
|
+
OAuthStateMismatchError,
|
|
75
|
+
PKCECookieMissingError,
|
|
76
|
+
PKCEPayloadTooLargeError,
|
|
66
77
|
SessionEncryptionError,
|
|
67
78
|
TokenValidationError,
|
|
68
79
|
TokenRefreshError,
|
|
@@ -1,10 +1,13 @@
|
|
|
1
|
+
import sessionEncryption from '../core/encryption/ironWebcryptoEncryption.js';
|
|
2
|
+
import { unsealState } from '../core/pkce/state.js';
|
|
1
3
|
import { AuthOperations } from './AuthOperations.js';
|
|
2
4
|
|
|
3
5
|
const mockConfig = {
|
|
4
6
|
clientId: 'test-client-id',
|
|
5
7
|
redirectUri: 'http://localhost:3000/callback',
|
|
6
8
|
cookieName: 'wos-session',
|
|
7
|
-
|
|
9
|
+
cookiePassword: 'this-is-a-test-password-that-is-32-characters-long!',
|
|
10
|
+
} as const;
|
|
8
11
|
|
|
9
12
|
const mockUser = {
|
|
10
13
|
id: 'user_123',
|
|
@@ -42,23 +45,45 @@ const mockCore = {
|
|
|
42
45
|
encryptSession: async () => 'encrypted-session-data',
|
|
43
46
|
};
|
|
44
47
|
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
}
|
|
48
|
+
function makeAuthUrlClient(capture?: { last?: Record<string, unknown> }) {
|
|
49
|
+
return {
|
|
50
|
+
pkce: {
|
|
51
|
+
generate: async () => ({
|
|
52
|
+
codeVerifier: 'generated-verifier-1234567890abcdef',
|
|
53
|
+
codeChallenge: 'generated-challenge',
|
|
54
|
+
codeChallengeMethod: 'S256',
|
|
55
|
+
}),
|
|
56
|
+
},
|
|
57
|
+
userManagement: {
|
|
58
|
+
getLogoutUrl: ({ sessionId, returnTo }: any) =>
|
|
59
|
+
`https://api.workos.com/sso/logout?session_id=${sessionId}&return_to=${returnTo || ''}`,
|
|
60
|
+
getAuthorizationUrl: (opts: any) => {
|
|
61
|
+
if (capture) capture.last = opts;
|
|
62
|
+
const params = new URLSearchParams({
|
|
63
|
+
client_id: opts.clientId,
|
|
64
|
+
redirect_uri: opts.redirectUri,
|
|
65
|
+
state: opts.state ?? '',
|
|
66
|
+
screen_hint: opts.screenHint ?? '',
|
|
67
|
+
code_challenge: opts.codeChallenge ?? '',
|
|
68
|
+
code_challenge_method: opts.codeChallengeMethod ?? '',
|
|
69
|
+
});
|
|
70
|
+
return `https://api.workos.com/sso/authorize?${params.toString()}`;
|
|
71
|
+
},
|
|
72
|
+
},
|
|
73
|
+
};
|
|
74
|
+
}
|
|
53
75
|
|
|
54
76
|
describe('AuthOperations', () => {
|
|
55
77
|
let operations: AuthOperations;
|
|
78
|
+
let capture: { last?: Record<string, unknown> };
|
|
56
79
|
|
|
57
80
|
beforeEach(() => {
|
|
81
|
+
capture = {};
|
|
58
82
|
operations = new AuthOperations(
|
|
59
83
|
mockCore as any,
|
|
60
|
-
|
|
84
|
+
makeAuthUrlClient(capture) as any,
|
|
61
85
|
mockConfig as any,
|
|
86
|
+
sessionEncryption,
|
|
62
87
|
);
|
|
63
88
|
});
|
|
64
89
|
|
|
@@ -148,8 +173,9 @@ describe('AuthOperations', () => {
|
|
|
148
173
|
};
|
|
149
174
|
const testOps = new AuthOperations(
|
|
150
175
|
coreWithSpy as any,
|
|
151
|
-
|
|
176
|
+
makeAuthUrlClient() as any,
|
|
152
177
|
mockConfig as any,
|
|
178
|
+
sessionEncryption,
|
|
153
179
|
);
|
|
154
180
|
|
|
155
181
|
const session = {
|
|
@@ -193,8 +219,9 @@ describe('AuthOperations', () => {
|
|
|
193
219
|
};
|
|
194
220
|
const testOps = new AuthOperations(
|
|
195
221
|
coreWithSpy as any,
|
|
196
|
-
|
|
222
|
+
makeAuthUrlClient() as any,
|
|
197
223
|
mockConfig as any,
|
|
224
|
+
sessionEncryption,
|
|
198
225
|
);
|
|
199
226
|
|
|
200
227
|
const session = {
|
|
@@ -213,87 +240,105 @@ describe('AuthOperations', () => {
|
|
|
213
240
|
});
|
|
214
241
|
});
|
|
215
242
|
|
|
216
|
-
describe('
|
|
217
|
-
it('returns
|
|
218
|
-
const result = await operations.
|
|
243
|
+
describe('createAuthorization()', () => {
|
|
244
|
+
it('returns url + sealedState + cookieOptions for storage dispatch', async () => {
|
|
245
|
+
const result = await operations.createAuthorization();
|
|
219
246
|
|
|
220
|
-
expect(result).
|
|
221
|
-
expect(result).
|
|
247
|
+
expect(typeof result.url).toBe('string');
|
|
248
|
+
expect(typeof result.sealedState).toBe('string');
|
|
249
|
+
expect(result.sealedState.length).toBeGreaterThan(0);
|
|
250
|
+
expect(result.cookieOptions.maxAge).toBe(600);
|
|
251
|
+
expect(result.cookieOptions.path).toBe('/');
|
|
252
|
+
expect(result.url).toContain('client_id=test-client-id');
|
|
222
253
|
});
|
|
223
254
|
|
|
224
|
-
it('
|
|
225
|
-
const result = await operations.
|
|
226
|
-
|
|
227
|
-
|
|
255
|
+
it('passes the sealedState as the URL state param (identical string)', async () => {
|
|
256
|
+
const result = await operations.createAuthorization();
|
|
257
|
+
const urlState = decodeURIComponent(
|
|
258
|
+
new URL(result.url).searchParams.get('state') ?? '',
|
|
259
|
+
);
|
|
260
|
+
|
|
261
|
+
expect(urlState).toBe(result.sealedState);
|
|
262
|
+
});
|
|
228
263
|
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
expect(stateMatch).toBeTruthy();
|
|
264
|
+
it('includes codeChallenge + codeChallengeMethod in WorkOS URL', async () => {
|
|
265
|
+
await operations.createAuthorization();
|
|
232
266
|
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
const standardBase64 = urlSafeState.replace(/-/g, '+').replace(/_/g, '/');
|
|
236
|
-
const decoded = JSON.parse(atob(standardBase64));
|
|
237
|
-
expect(decoded.returnPathname).toBe('/dashboard');
|
|
267
|
+
expect(capture.last?.codeChallenge).toBe('generated-challenge');
|
|
268
|
+
expect(capture.last?.codeChallengeMethod).toBe('S256');
|
|
238
269
|
});
|
|
239
270
|
|
|
240
|
-
it('
|
|
241
|
-
const result = await operations.
|
|
242
|
-
returnPathname: '/
|
|
243
|
-
state: 'my-custom-state',
|
|
271
|
+
it('seals returnPathname into the state blob', async () => {
|
|
272
|
+
const result = await operations.createAuthorization({
|
|
273
|
+
returnPathname: '/dashboard',
|
|
244
274
|
});
|
|
275
|
+
const unsealed = await unsealState(
|
|
276
|
+
sessionEncryption,
|
|
277
|
+
mockConfig.cookiePassword,
|
|
278
|
+
result.sealedState,
|
|
279
|
+
);
|
|
245
280
|
|
|
246
|
-
expect(
|
|
247
|
-
|
|
248
|
-
|
|
281
|
+
expect(unsealed.returnPathname).toBe('/dashboard');
|
|
282
|
+
expect(unsealed.codeVerifier).toBe('generated-verifier-1234567890abcdef');
|
|
283
|
+
});
|
|
249
284
|
|
|
250
|
-
|
|
251
|
-
const
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
285
|
+
it('seals customState into the state blob', async () => {
|
|
286
|
+
const result = await operations.createAuthorization({
|
|
287
|
+
state: 'my-custom-state',
|
|
288
|
+
});
|
|
289
|
+
const unsealed = await unsealState(
|
|
290
|
+
sessionEncryption,
|
|
291
|
+
mockConfig.cookiePassword,
|
|
292
|
+
result.sealedState,
|
|
293
|
+
);
|
|
255
294
|
|
|
256
|
-
|
|
257
|
-
const standardBase64 = internal!.replace(/-/g, '+').replace(/_/g, '/');
|
|
258
|
-
const decoded = JSON.parse(atob(standardBase64));
|
|
259
|
-
expect(decoded.returnPathname).toBe('/profile');
|
|
295
|
+
expect(unsealed.customState).toBe('my-custom-state');
|
|
260
296
|
});
|
|
261
297
|
|
|
262
|
-
it('
|
|
263
|
-
const result = await operations.
|
|
264
|
-
|
|
298
|
+
it('seals both returnPathname and customState together', async () => {
|
|
299
|
+
const result = await operations.createAuthorization({
|
|
300
|
+
returnPathname: '/profile',
|
|
301
|
+
state: 'custom',
|
|
265
302
|
});
|
|
303
|
+
const unsealed = await unsealState(
|
|
304
|
+
sessionEncryption,
|
|
305
|
+
mockConfig.cookiePassword,
|
|
306
|
+
result.sealedState,
|
|
307
|
+
);
|
|
266
308
|
|
|
267
|
-
expect(
|
|
268
|
-
|
|
269
|
-
expect(stateMatch).toBeTruthy();
|
|
270
|
-
|
|
271
|
-
// State should be passed through directly without internal wrapper
|
|
272
|
-
expect(stateMatch![1]).toBe('only-user-state');
|
|
309
|
+
expect(unsealed.returnPathname).toBe('/profile');
|
|
310
|
+
expect(unsealed.customState).toBe('custom');
|
|
273
311
|
});
|
|
274
312
|
|
|
275
313
|
it('includes screenHint when provided', async () => {
|
|
276
|
-
const result = await operations.
|
|
314
|
+
const result = await operations.createAuthorization({
|
|
277
315
|
screenHint: 'sign-up',
|
|
278
316
|
});
|
|
279
317
|
|
|
280
|
-
expect(result).toContain('screen_hint=sign-up');
|
|
318
|
+
expect(result.url).toContain('screen_hint=sign-up');
|
|
319
|
+
});
|
|
320
|
+
|
|
321
|
+
it('generates a unique nonce per call (concurrent last-flow-wins)', async () => {
|
|
322
|
+
const a = await operations.createAuthorization();
|
|
323
|
+
const b = await operations.createAuthorization();
|
|
324
|
+
|
|
325
|
+
expect(a.sealedState).not.toBe(b.sealedState);
|
|
281
326
|
});
|
|
282
327
|
});
|
|
283
328
|
|
|
284
|
-
describe('
|
|
329
|
+
describe('createSignIn()', () => {
|
|
285
330
|
it('returns authorization URL with sign-in hint', async () => {
|
|
286
|
-
const result = await operations.
|
|
331
|
+
const result = await operations.createSignIn();
|
|
287
332
|
|
|
288
|
-
expect(result).toContain('screen_hint=sign-in');
|
|
333
|
+
expect(result.url).toContain('screen_hint=sign-in');
|
|
289
334
|
});
|
|
290
335
|
});
|
|
291
336
|
|
|
292
|
-
describe('
|
|
337
|
+
describe('createSignUp()', () => {
|
|
293
338
|
it('returns authorization URL with sign-up hint', async () => {
|
|
294
|
-
const result = await operations.
|
|
339
|
+
const result = await operations.createSignUp();
|
|
295
340
|
|
|
296
|
-
expect(result).toContain('screen_hint=sign-up');
|
|
341
|
+
expect(result.url).toContain('screen_hint=sign-up');
|
|
297
342
|
});
|
|
298
343
|
});
|
|
299
344
|
});
|