@workos/authkit-session 0.1.3 → 0.2.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 +144 -554
- package/dist/core/AuthKitCore.d.ts +109 -0
- package/dist/core/AuthKitCore.d.ts.map +1 -0
- package/dist/core/AuthKitCore.js +190 -0
- package/dist/core/AuthKitCore.js.map +1 -0
- package/dist/core/session/CookieSessionStorage.d.ts +2 -3
- package/dist/core/session/CookieSessionStorage.d.ts.map +1 -1
- package/dist/core/session/CookieSessionStorage.js +22 -9
- package/dist/core/session/CookieSessionStorage.js.map +1 -1
- package/dist/core/session/types.d.ts +35 -7
- package/dist/core/session/types.d.ts.map +1 -1
- package/dist/index.d.ts +28 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +49 -4
- package/dist/index.js.map +1 -1
- package/dist/operations/AuthOperations.d.ts +83 -0
- package/dist/operations/AuthOperations.d.ts.map +1 -0
- package/dist/operations/AuthOperations.js +137 -0
- package/dist/operations/AuthOperations.js.map +1 -0
- package/dist/service/AuthService.d.ts +137 -0
- package/dist/service/AuthService.d.ts.map +1 -0
- package/dist/service/AuthService.js +224 -0
- package/dist/service/AuthService.js.map +1 -0
- package/dist/service/factory.d.ts +37 -0
- package/dist/service/factory.d.ts.map +1 -0
- package/dist/service/factory.js +60 -0
- package/dist/service/factory.js.map +1 -0
- package/package.json +6 -6
- package/src/core/AuthKitCore.spec.ts +262 -0
- package/src/core/AuthKitCore.ts +243 -0
- package/src/core/config/ConfigurationProvider.spec.ts +1 -0
- package/src/core/session/CookieSessionStorage.spec.ts +64 -58
- package/src/core/session/CookieSessionStorage.ts +27 -10
- package/src/core/session/types.ts +38 -8
- package/src/index.ts +56 -4
- package/src/operations/AuthOperations.spec.ts +299 -0
- package/src/operations/AuthOperations.ts +179 -0
- package/src/service/AuthService.spec.ts +267 -0
- package/src/service/AuthService.ts +288 -0
- package/src/service/factory.spec.ts +120 -0
- package/src/service/factory.ts +82 -0
- package/dist/core/createAuthKitFactory.d.ts +0 -64
- package/dist/core/createAuthKitFactory.d.ts.map +0 -1
- package/dist/core/createAuthKitFactory.js +0 -95
- package/dist/core/createAuthKitFactory.js.map +0 -1
- package/dist/core/session/SessionManager.d.ts +0 -51
- package/dist/core/session/SessionManager.d.ts.map +0 -1
- package/dist/core/session/SessionManager.js +0 -238
- package/dist/core/session/SessionManager.js.map +0 -1
- package/src/core/createAuthKitFactory.spec.ts +0 -161
- package/src/core/createAuthKitFactory.ts +0 -195
- package/src/core/session/SessionManager.spec.ts +0 -357
- package/src/core/session/SessionManager.ts +0 -357
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { once } from '../utils.js';
|
|
2
|
+
import { getFullConfig } from '../core/config.js';
|
|
3
|
+
import { getWorkOS } from '../core/client/workos.js';
|
|
4
|
+
import sessionEncryption from '../core/encryption/ironWebcryptoEncryption.js';
|
|
5
|
+
import { AuthService } from './AuthService.js';
|
|
6
|
+
/**
|
|
7
|
+
* Creates an AuthService instance with lazy initialization support.
|
|
8
|
+
*
|
|
9
|
+
* This factory function provides ergonomic AuthService creation with sensible defaults.
|
|
10
|
+
* The returned service uses lazy initialization, allowing configure() to be called
|
|
11
|
+
* after instantiation but before first use.
|
|
12
|
+
*
|
|
13
|
+
* @param options - Configuration options
|
|
14
|
+
* @param options.sessionStorageFactory - Factory function to create storage adapter
|
|
15
|
+
* @param options.clientFactory - Optional factory for WorkOS client (defaults to getWorkOS)
|
|
16
|
+
* @param options.encryptionFactory - Optional factory for encryption (defaults to iron-webcrypto)
|
|
17
|
+
* @returns AuthService instance with lazy initialization
|
|
18
|
+
*
|
|
19
|
+
* @example
|
|
20
|
+
* ```typescript
|
|
21
|
+
* // Create service (config not needed yet)
|
|
22
|
+
* export const authService = createAuthService({
|
|
23
|
+
* sessionStorageFactory: (config) => new MyFrameworkStorage(config),
|
|
24
|
+
* });
|
|
25
|
+
*
|
|
26
|
+
* // Configure later
|
|
27
|
+
* configure({ clientId: '...' });
|
|
28
|
+
*
|
|
29
|
+
* // Use (triggers lazy init)
|
|
30
|
+
* await authService.withAuth(request);
|
|
31
|
+
* ```
|
|
32
|
+
*/
|
|
33
|
+
export function createAuthService(options) {
|
|
34
|
+
const { sessionStorageFactory, clientFactory = () => getWorkOS(), encryptionFactory = () => sessionEncryption, } = options;
|
|
35
|
+
// Lazily create the real AuthService with resolved config
|
|
36
|
+
const getService = once(() => {
|
|
37
|
+
const config = getFullConfig();
|
|
38
|
+
const storage = sessionStorageFactory(config);
|
|
39
|
+
const client = clientFactory(config);
|
|
40
|
+
const encryption = encryptionFactory(config);
|
|
41
|
+
return new AuthService(config, storage, client, encryption);
|
|
42
|
+
});
|
|
43
|
+
// Return proxy that lazily delegates to the real service
|
|
44
|
+
// This allows configure() to be called after createAuthService() but before first use
|
|
45
|
+
return {
|
|
46
|
+
withAuth: request => getService().withAuth(request),
|
|
47
|
+
getSession: request => getService().getSession(request),
|
|
48
|
+
saveSession: (response, sessionData) => getService().saveSession(response, sessionData),
|
|
49
|
+
clearSession: response => getService().clearSession(response),
|
|
50
|
+
signOut: (sessionId, opts) => getService().signOut(sessionId, opts),
|
|
51
|
+
switchOrganization: (session, organizationId) => getService().switchOrganization(session, organizationId),
|
|
52
|
+
refreshSession: (session, organizationId) => getService().refreshSession(session, organizationId),
|
|
53
|
+
getAuthorizationUrl: opts => getService().getAuthorizationUrl(opts),
|
|
54
|
+
getSignInUrl: opts => getService().getSignInUrl(opts),
|
|
55
|
+
getSignUpUrl: opts => getService().getSignUpUrl(opts),
|
|
56
|
+
getWorkOS: () => getService().getWorkOS(),
|
|
57
|
+
handleCallback: (request, response, opts) => getService().handleCallback(request, response, opts),
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
//# sourceMappingURL=factory.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"factory.js","sourceRoot":"","sources":["../../src/service/factory.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAC;AACnC,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAElD,OAAO,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AACrD,OAAO,iBAAiB,MAAM,+CAA+C,CAAC;AAK9E,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAE/C;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,MAAM,UAAU,iBAAiB,CAAsB,OAMtD;IACC,MAAM,EACJ,qBAAqB,EACrB,aAAa,GAAG,GAAG,EAAE,CAAC,SAAS,EAAE,EACjC,iBAAiB,GAAG,GAAG,EAAE,CAAC,iBAAiB,GAC5C,GAAG,OAAO,CAAC;IAEZ,0DAA0D;IAC1D,MAAM,UAAU,GAAG,IAAI,CAAC,GAAG,EAAE;QAC3B,MAAM,MAAM,GAAG,aAAa,EAAE,CAAC;QAC/B,MAAM,OAAO,GAAG,qBAAqB,CAAC,MAAM,CAAC,CAAC;QAC9C,MAAM,MAAM,GAAG,aAAa,CAAC,MAAM,CAAC,CAAC;QACrC,MAAM,UAAU,GAAG,iBAAiB,CAAC,MAAM,CAAC,CAAC;QAC7C,OAAO,IAAI,WAAW,CAAC,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,UAAU,CAAC,CAAC;IAC9D,CAAC,CAAC,CAAC;IAEH,yDAAyD;IACzD,sFAAsF;IACtF,OAAO;QACL,QAAQ,EAAE,OAAO,CAAC,EAAE,CAAC,UAAU,EAAE,CAAC,QAAQ,CAAC,OAAO,CAAC;QACnD,UAAU,EAAE,OAAO,CAAC,EAAE,CAAC,UAAU,EAAE,CAAC,UAAU,CAAC,OAAO,CAAC;QACvD,WAAW,EAAE,CAAC,QAAQ,EAAE,WAAW,EAAE,EAAE,CACrC,UAAU,EAAE,CAAC,WAAW,CAAC,QAAQ,EAAE,WAAW,CAAC;QACjD,YAAY,EAAE,QAAQ,CAAC,EAAE,CAAC,UAAU,EAAE,CAAC,YAAY,CAAC,QAAQ,CAAC;QAC7D,OAAO,EAAE,CAAC,SAAS,EAAE,IAAI,EAAE,EAAE,CAAC,UAAU,EAAE,CAAC,OAAO,CAAC,SAAS,EAAE,IAAI,CAAC;QACnE,kBAAkB,EAAE,CAAC,OAAO,EAAE,cAAc,EAAE,EAAE,CAC9C,UAAU,EAAE,CAAC,kBAAkB,CAAC,OAAO,EAAE,cAAc,CAAC;QAC1D,cAAc,EAAE,CAAC,OAAO,EAAE,cAAc,EAAE,EAAE,CAC1C,UAAU,EAAE,CAAC,cAAc,CAAC,OAAO,EAAE,cAAc,CAAC;QACtD,mBAAmB,EAAE,IAAI,CAAC,EAAE,CAAC,UAAU,EAAE,CAAC,mBAAmB,CAAC,IAAI,CAAC;QACnE,YAAY,EAAE,IAAI,CAAC,EAAE,CAAC,UAAU,EAAE,CAAC,YAAY,CAAC,IAAI,CAAC;QACrD,YAAY,EAAE,IAAI,CAAC,EAAE,CAAC,UAAU,EAAE,CAAC,YAAY,CAAC,IAAI,CAAC;QACrD,SAAS,EAAE,GAAG,EAAE,CAAC,UAAU,EAAE,CAAC,SAAS,EAAE;QACzC,cAAc,EAAE,CAAC,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,EAAE,CAC1C,UAAU,EAAE,CAAC,cAAc,CAAC,OAAO,EAAE,QAAQ,EAAE,IAAI,CAAC;KACnB,CAAC;AACxC,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@workos/authkit-session",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "",
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Framework-agnostic authentication library for WorkOS with pluggable storage adapters",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
7
7
|
"types": "./dist/index.d.ts",
|
|
@@ -29,16 +29,16 @@
|
|
|
29
29
|
"license": "MIT",
|
|
30
30
|
"devDependencies": {
|
|
31
31
|
"@types/node": "^20.17.0",
|
|
32
|
-
"@vitest/coverage-v8": "^
|
|
32
|
+
"@vitest/coverage-v8": "^4.0.10",
|
|
33
33
|
"prettier": "^3.6.2",
|
|
34
|
-
"typescript": "^5.9.
|
|
35
|
-
"vitest": "^
|
|
34
|
+
"typescript": "^5.9.3",
|
|
35
|
+
"vitest": "^4.0.10"
|
|
36
36
|
},
|
|
37
37
|
"dependencies": {
|
|
38
38
|
"@workos-inc/node": "^8.0.0-rc.3",
|
|
39
39
|
"iron-session": "^8.0.4",
|
|
40
40
|
"iron-webcrypto": "^1.2.1",
|
|
41
|
-
"jose": "^6.
|
|
41
|
+
"jose": "^6.1.2"
|
|
42
42
|
},
|
|
43
43
|
"engines": {
|
|
44
44
|
"node": ">=20.0.0"
|
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
import { AuthKitCore } from './AuthKitCore.js';
|
|
2
|
+
import { SessionEncryptionError, TokenRefreshError } from './errors.js';
|
|
3
|
+
|
|
4
|
+
const mockConfig = {
|
|
5
|
+
cookiePassword: 'test-password-that-is-32-chars-long!!',
|
|
6
|
+
clientId: 'test-client-id',
|
|
7
|
+
};
|
|
8
|
+
|
|
9
|
+
const mockUser = {
|
|
10
|
+
id: 'user_123',
|
|
11
|
+
email: 'test@example.com',
|
|
12
|
+
object: 'user',
|
|
13
|
+
firstName: 'Test',
|
|
14
|
+
lastName: 'User',
|
|
15
|
+
emailVerified: true,
|
|
16
|
+
profilePictureUrl: null,
|
|
17
|
+
createdAt: '2023-01-01T00:00:00Z',
|
|
18
|
+
updatedAt: '2023-01-01T00:00:00Z',
|
|
19
|
+
lastSignInAt: '2023-01-01T00:00:00Z',
|
|
20
|
+
locale: 'en-US',
|
|
21
|
+
externalId: null,
|
|
22
|
+
metadata: {},
|
|
23
|
+
} as const;
|
|
24
|
+
|
|
25
|
+
const mockClient = {
|
|
26
|
+
userManagement: {
|
|
27
|
+
getJwksUrl: () => 'https://api.workos.com/sso/jwks/test-client-id',
|
|
28
|
+
authenticateWithRefreshToken: async () => ({
|
|
29
|
+
accessToken: 'new-access-token',
|
|
30
|
+
refreshToken: 'new-refresh-token',
|
|
31
|
+
user: mockUser,
|
|
32
|
+
impersonator: undefined,
|
|
33
|
+
}),
|
|
34
|
+
},
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
const mockEncryption = {
|
|
38
|
+
sealData: async () => 'encrypted-session-data',
|
|
39
|
+
unsealData: async () => ({
|
|
40
|
+
accessToken: 'test-access-token',
|
|
41
|
+
refreshToken: 'test-refresh-token',
|
|
42
|
+
user: mockUser,
|
|
43
|
+
impersonator: undefined,
|
|
44
|
+
}),
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
describe('AuthKitCore', () => {
|
|
48
|
+
let core: AuthKitCore;
|
|
49
|
+
|
|
50
|
+
beforeEach(() => {
|
|
51
|
+
core = new AuthKitCore(
|
|
52
|
+
mockConfig as any,
|
|
53
|
+
mockClient as any,
|
|
54
|
+
mockEncryption as any,
|
|
55
|
+
);
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
describe('constructor', () => {
|
|
59
|
+
it('creates instance with required dependencies', () => {
|
|
60
|
+
expect(core).toBeInstanceOf(AuthKitCore);
|
|
61
|
+
});
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
describe('parseTokenClaims()', () => {
|
|
65
|
+
it('parses valid JWT payload', () => {
|
|
66
|
+
const validJwt =
|
|
67
|
+
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyXzEyMyIsInNpZCI6InNlc3Npb25fMTIzIiwiZXhwIjoxNzM2Mzc2MDAwfQ.fake-signature';
|
|
68
|
+
|
|
69
|
+
const result = core.parseTokenClaims(validJwt);
|
|
70
|
+
|
|
71
|
+
expect(result.sub).toBe('user_123');
|
|
72
|
+
expect(result.sid).toBe('session_123');
|
|
73
|
+
expect(result.exp).toBe(1736376000);
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
it('throws error for invalid JWT', () => {
|
|
77
|
+
expect(() => core.parseTokenClaims('invalid-jwt')).toThrow(
|
|
78
|
+
'Invalid token',
|
|
79
|
+
);
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
it('supports custom claims', () => {
|
|
83
|
+
const customJwt =
|
|
84
|
+
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyXzEyMyIsImN1c3RvbUZpZWxkIjoiY3VzdG9tLXZhbHVlIn0.fake-signature';
|
|
85
|
+
|
|
86
|
+
const result = core.parseTokenClaims<{ customField: string }>(customJwt);
|
|
87
|
+
|
|
88
|
+
expect(result.customField).toBe('custom-value');
|
|
89
|
+
});
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
describe('isTokenExpiring()', () => {
|
|
93
|
+
it('returns true when token expires soon', () => {
|
|
94
|
+
// Token expires in 5 seconds, which is within the default 10-second buffer
|
|
95
|
+
const soonExpiry = Math.floor(Date.now() / 1000) + 5;
|
|
96
|
+
const expiringJwt = `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.${btoa(JSON.stringify({ exp: soonExpiry }))}.fake-signature`;
|
|
97
|
+
|
|
98
|
+
const result = core.isTokenExpiring(expiringJwt);
|
|
99
|
+
|
|
100
|
+
expect(result).toBe(true);
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
it('returns false when token expires later', () => {
|
|
104
|
+
const laterExpiry = Math.floor(Date.now() / 1000) + 3600;
|
|
105
|
+
const validJwt = `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.${btoa(JSON.stringify({ exp: laterExpiry }))}.fake-signature`;
|
|
106
|
+
|
|
107
|
+
const result = core.isTokenExpiring(validJwt);
|
|
108
|
+
|
|
109
|
+
expect(result).toBe(false);
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
it('uses custom buffer time', () => {
|
|
113
|
+
const expiry = Math.floor(Date.now() / 1000) + 150;
|
|
114
|
+
const jwt = `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.${btoa(JSON.stringify({ exp: expiry }))}.fake-signature`;
|
|
115
|
+
|
|
116
|
+
const result = core.isTokenExpiring(jwt, 180);
|
|
117
|
+
|
|
118
|
+
expect(result).toBe(true);
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
it('returns false when token has no expiry', () => {
|
|
122
|
+
const noExpiryJwt =
|
|
123
|
+
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyXzEyMyJ9.fake-signature';
|
|
124
|
+
|
|
125
|
+
const result = core.isTokenExpiring(noExpiryJwt);
|
|
126
|
+
|
|
127
|
+
expect(result).toBe(false);
|
|
128
|
+
});
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
describe('verifyToken()', () => {
|
|
132
|
+
it('returns false for invalid tokens', async () => {
|
|
133
|
+
const result = await core.verifyToken('invalid-token');
|
|
134
|
+
|
|
135
|
+
expect(result).toBe(false);
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
it('returns false for malformed tokens', async () => {
|
|
139
|
+
const result = await core.verifyToken('not.a.jwt');
|
|
140
|
+
|
|
141
|
+
expect(result).toBe(false);
|
|
142
|
+
});
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
describe('encryptSession()', () => {
|
|
146
|
+
it('encrypts session data', async () => {
|
|
147
|
+
const session = {
|
|
148
|
+
accessToken: 'test-token',
|
|
149
|
+
refreshToken: 'test-refresh',
|
|
150
|
+
user: mockUser,
|
|
151
|
+
impersonator: undefined,
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
const result = await core.encryptSession(session);
|
|
155
|
+
|
|
156
|
+
expect(result).toBe('encrypted-session-data');
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
it('throws SessionEncryptionError on failure', async () => {
|
|
160
|
+
const failingEncryption = {
|
|
161
|
+
sealData: async () => {
|
|
162
|
+
throw new Error('Encryption failed');
|
|
163
|
+
},
|
|
164
|
+
unsealData: async () => ({}),
|
|
165
|
+
};
|
|
166
|
+
const failingCore = new AuthKitCore(
|
|
167
|
+
mockConfig as any,
|
|
168
|
+
mockClient as any,
|
|
169
|
+
failingEncryption as any,
|
|
170
|
+
);
|
|
171
|
+
|
|
172
|
+
await expect(
|
|
173
|
+
failingCore.encryptSession({
|
|
174
|
+
accessToken: 'test',
|
|
175
|
+
refreshToken: 'test',
|
|
176
|
+
user: mockUser,
|
|
177
|
+
impersonator: undefined,
|
|
178
|
+
}),
|
|
179
|
+
).rejects.toThrow(SessionEncryptionError);
|
|
180
|
+
});
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
describe('decryptSession()', () => {
|
|
184
|
+
it('decrypts session data', async () => {
|
|
185
|
+
const result = await core.decryptSession('encrypted-data');
|
|
186
|
+
|
|
187
|
+
expect(result.accessToken).toBe('test-access-token');
|
|
188
|
+
expect(result.user).toEqual(mockUser);
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
it('throws SessionEncryptionError on failure', async () => {
|
|
192
|
+
const failingEncryption = {
|
|
193
|
+
sealData: async () => 'encrypted',
|
|
194
|
+
unsealData: async () => {
|
|
195
|
+
throw new Error('Decryption failed');
|
|
196
|
+
},
|
|
197
|
+
};
|
|
198
|
+
const failingCore = new AuthKitCore(
|
|
199
|
+
mockConfig as any,
|
|
200
|
+
mockClient as any,
|
|
201
|
+
failingEncryption as any,
|
|
202
|
+
);
|
|
203
|
+
|
|
204
|
+
await expect(failingCore.decryptSession('bad-data')).rejects.toThrow(
|
|
205
|
+
SessionEncryptionError,
|
|
206
|
+
);
|
|
207
|
+
});
|
|
208
|
+
});
|
|
209
|
+
|
|
210
|
+
describe('refreshTokens()', () => {
|
|
211
|
+
it('refreshes tokens via WorkOS', async () => {
|
|
212
|
+
const result = await core.refreshTokens('refresh-token');
|
|
213
|
+
|
|
214
|
+
expect(result.accessToken).toBe('new-access-token');
|
|
215
|
+
expect(result.refreshToken).toBe('new-refresh-token');
|
|
216
|
+
expect(result.user).toEqual(mockUser);
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
it('includes organizationId when provided', async () => {
|
|
220
|
+
const clientWithSpy = {
|
|
221
|
+
userManagement: {
|
|
222
|
+
getJwksUrl: () => 'https://api.workos.com/sso/jwks/test-client-id',
|
|
223
|
+
authenticateWithRefreshToken: async ({ organizationId }: any) => ({
|
|
224
|
+
accessToken: organizationId ? 'org-token' : 'regular-token',
|
|
225
|
+
refreshToken: 'new-refresh-token',
|
|
226
|
+
user: mockUser,
|
|
227
|
+
impersonator: undefined,
|
|
228
|
+
}),
|
|
229
|
+
},
|
|
230
|
+
};
|
|
231
|
+
const testCore = new AuthKitCore(
|
|
232
|
+
mockConfig as any,
|
|
233
|
+
clientWithSpy as any,
|
|
234
|
+
mockEncryption as any,
|
|
235
|
+
);
|
|
236
|
+
|
|
237
|
+
const result = await testCore.refreshTokens('refresh-token', 'org_123');
|
|
238
|
+
|
|
239
|
+
expect(result.accessToken).toBe('org-token');
|
|
240
|
+
});
|
|
241
|
+
|
|
242
|
+
it('throws TokenRefreshError on failure', async () => {
|
|
243
|
+
const failingClient = {
|
|
244
|
+
userManagement: {
|
|
245
|
+
getJwksUrl: () => 'https://api.workos.com/sso/jwks/test-client-id',
|
|
246
|
+
authenticateWithRefreshToken: async () => {
|
|
247
|
+
throw new Error('Refresh failed');
|
|
248
|
+
},
|
|
249
|
+
},
|
|
250
|
+
};
|
|
251
|
+
const failingCore = new AuthKitCore(
|
|
252
|
+
mockConfig as any,
|
|
253
|
+
failingClient as any,
|
|
254
|
+
mockEncryption as any,
|
|
255
|
+
);
|
|
256
|
+
|
|
257
|
+
await expect(failingCore.refreshTokens('bad-token')).rejects.toThrow(
|
|
258
|
+
TokenRefreshError,
|
|
259
|
+
);
|
|
260
|
+
});
|
|
261
|
+
});
|
|
262
|
+
});
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
import type { Impersonator, User, WorkOS } from '@workos-inc/node';
|
|
2
|
+
import { createRemoteJWKSet, decodeJwt, jwtVerify } from 'jose';
|
|
3
|
+
import { once } from '../utils.js';
|
|
4
|
+
import type { AuthKitConfig } from './config/types.js';
|
|
5
|
+
import { SessionEncryptionError, TokenRefreshError } from './errors.js';
|
|
6
|
+
import type {
|
|
7
|
+
BaseTokenClaims,
|
|
8
|
+
CustomClaims,
|
|
9
|
+
Session,
|
|
10
|
+
SessionEncryption,
|
|
11
|
+
} from './session/types.js';
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* AuthKitCore provides pure business logic for authentication operations.
|
|
15
|
+
*
|
|
16
|
+
* This class contains no framework-specific code - all methods are pure functions
|
|
17
|
+
* that take data in and return data out. No TRequest/TResponse generics here.
|
|
18
|
+
*
|
|
19
|
+
* Responsibilities:
|
|
20
|
+
* - Token validation (JWT verification against JWKS)
|
|
21
|
+
* - Token claims parsing
|
|
22
|
+
* - Session encryption/decryption
|
|
23
|
+
* - Token refresh (calling WorkOS API)
|
|
24
|
+
* - Session validation orchestration
|
|
25
|
+
*/
|
|
26
|
+
export class AuthKitCore {
|
|
27
|
+
private config: AuthKitConfig;
|
|
28
|
+
private client: WorkOS;
|
|
29
|
+
private encryption: SessionEncryption;
|
|
30
|
+
private clientId: string;
|
|
31
|
+
|
|
32
|
+
constructor(
|
|
33
|
+
config: AuthKitConfig,
|
|
34
|
+
client: WorkOS,
|
|
35
|
+
encryption: SessionEncryption,
|
|
36
|
+
) {
|
|
37
|
+
this.config = config;
|
|
38
|
+
this.client = client;
|
|
39
|
+
this.encryption = encryption;
|
|
40
|
+
this.clientId = config.clientId;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* JWKS public key fetcher - cached for performance
|
|
45
|
+
*/
|
|
46
|
+
private readonly getPublicKey = once(() =>
|
|
47
|
+
createRemoteJWKSet(
|
|
48
|
+
new URL(this.client.userManagement.getJwksUrl(this.clientId)),
|
|
49
|
+
),
|
|
50
|
+
);
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Verify a JWT access token against WorkOS JWKS.
|
|
54
|
+
*
|
|
55
|
+
* @param token - The JWT access token to verify
|
|
56
|
+
* @returns true if valid, false otherwise
|
|
57
|
+
*/
|
|
58
|
+
async verifyToken(token: string): Promise<boolean> {
|
|
59
|
+
try {
|
|
60
|
+
await jwtVerify(token, this.getPublicKey());
|
|
61
|
+
return true;
|
|
62
|
+
} catch {
|
|
63
|
+
return false;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Check if a token is expiring soon.
|
|
69
|
+
*
|
|
70
|
+
* @param token - The JWT access token
|
|
71
|
+
* @param buffer - How many seconds before expiry to consider "expiring" (default: 60)
|
|
72
|
+
* @returns true if token expires within buffer period
|
|
73
|
+
*/
|
|
74
|
+
isTokenExpiring(token: string, buffer: number = 10): boolean {
|
|
75
|
+
const expiryTime = this.getTokenExpiryTime(token);
|
|
76
|
+
if (!expiryTime) {
|
|
77
|
+
return false;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const currentTime = Math.floor(Date.now() / 1000);
|
|
81
|
+
return expiryTime - currentTime <= buffer;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Get the expiry time from a token's claims.
|
|
86
|
+
*
|
|
87
|
+
* @param token - The JWT access token
|
|
88
|
+
* @returns Unix timestamp of expiry, or null if not present
|
|
89
|
+
*/
|
|
90
|
+
private getTokenExpiryTime(token: string): number | undefined {
|
|
91
|
+
const claims = this.parseTokenClaims(token);
|
|
92
|
+
return claims.exp;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Parse JWT claims from an access token.
|
|
97
|
+
*
|
|
98
|
+
* @param token - The JWT access token
|
|
99
|
+
* @returns Decoded token claims
|
|
100
|
+
* @throws Error if token is invalid
|
|
101
|
+
*/
|
|
102
|
+
parseTokenClaims<TCustomClaims = CustomClaims>(
|
|
103
|
+
token: string,
|
|
104
|
+
): BaseTokenClaims & TCustomClaims {
|
|
105
|
+
try {
|
|
106
|
+
return decodeJwt<BaseTokenClaims & TCustomClaims>(token);
|
|
107
|
+
} catch (error) {
|
|
108
|
+
throw new Error('Invalid token');
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Encrypt a session object into a string suitable for cookie storage.
|
|
114
|
+
*
|
|
115
|
+
* @param session - The session to encrypt
|
|
116
|
+
* @returns Encrypted session string
|
|
117
|
+
* @throws SessionEncryptionError if encryption fails
|
|
118
|
+
*/
|
|
119
|
+
async encryptSession(session: Session): Promise<string> {
|
|
120
|
+
try {
|
|
121
|
+
const encryptedSession = await this.encryption.sealData(session, {
|
|
122
|
+
password: this.config.cookiePassword,
|
|
123
|
+
ttl: 0,
|
|
124
|
+
});
|
|
125
|
+
return encryptedSession;
|
|
126
|
+
} catch (error) {
|
|
127
|
+
throw new SessionEncryptionError('Failed to encrypt session', error);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Decrypt an encrypted session string back into a session object.
|
|
133
|
+
*
|
|
134
|
+
* @param encryptedSession - The encrypted session string
|
|
135
|
+
* @returns Decrypted session object
|
|
136
|
+
* @throws SessionEncryptionError if decryption fails
|
|
137
|
+
*/
|
|
138
|
+
async decryptSession(encryptedSession: string): Promise<Session> {
|
|
139
|
+
try {
|
|
140
|
+
const session = await this.encryption.unsealData<Session>(
|
|
141
|
+
encryptedSession,
|
|
142
|
+
{ password: this.config.cookiePassword },
|
|
143
|
+
);
|
|
144
|
+
return session;
|
|
145
|
+
} catch (error) {
|
|
146
|
+
throw new SessionEncryptionError('Failed to decrypt session', error);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Refresh tokens using WorkOS API.
|
|
152
|
+
*
|
|
153
|
+
* @param refreshToken - The refresh token
|
|
154
|
+
* @param organizationId - Optional organization ID to switch to
|
|
155
|
+
* @returns New access token, refresh token, user, and impersonator
|
|
156
|
+
* @throws TokenRefreshError if refresh fails
|
|
157
|
+
*/
|
|
158
|
+
async refreshTokens(
|
|
159
|
+
refreshToken: string,
|
|
160
|
+
organizationId?: string,
|
|
161
|
+
): Promise<{
|
|
162
|
+
accessToken: string;
|
|
163
|
+
refreshToken: string;
|
|
164
|
+
user: User;
|
|
165
|
+
impersonator: Impersonator | undefined;
|
|
166
|
+
}> {
|
|
167
|
+
try {
|
|
168
|
+
const result =
|
|
169
|
+
await this.client.userManagement.authenticateWithRefreshToken({
|
|
170
|
+
refreshToken,
|
|
171
|
+
clientId: this.clientId,
|
|
172
|
+
organizationId,
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
return {
|
|
176
|
+
accessToken: result.accessToken,
|
|
177
|
+
refreshToken: result.refreshToken,
|
|
178
|
+
user: result.user,
|
|
179
|
+
impersonator: result.impersonator,
|
|
180
|
+
};
|
|
181
|
+
} catch (error) {
|
|
182
|
+
throw new TokenRefreshError('Failed to refresh tokens', error);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Validate a session and refresh if needed.
|
|
188
|
+
*
|
|
189
|
+
* Only refreshes when token is invalid (expired) or force is true.
|
|
190
|
+
*
|
|
191
|
+
* @param session - The current session with access and refresh tokens
|
|
192
|
+
* @param options - Optional settings
|
|
193
|
+
* @param options.force - Force refresh even if token is valid (for org switching)
|
|
194
|
+
* @param options.organizationId - Organization ID to switch to during refresh
|
|
195
|
+
* @returns Validation result with refreshed session if needed
|
|
196
|
+
* @throws TokenRefreshError if refresh fails
|
|
197
|
+
*/
|
|
198
|
+
async validateAndRefresh<TCustomClaims = CustomClaims>(
|
|
199
|
+
session: Session,
|
|
200
|
+
options?: { force?: boolean; organizationId?: string },
|
|
201
|
+
): Promise<{
|
|
202
|
+
valid: boolean;
|
|
203
|
+
refreshed: boolean;
|
|
204
|
+
session: Session;
|
|
205
|
+
claims: BaseTokenClaims & TCustomClaims;
|
|
206
|
+
}> {
|
|
207
|
+
const { accessToken } = session;
|
|
208
|
+
const { force = false, organizationId: explicitOrgId } = options ?? {};
|
|
209
|
+
|
|
210
|
+
const isValid = await this.verifyToken(accessToken);
|
|
211
|
+
|
|
212
|
+
// Return early if token is valid and not forced
|
|
213
|
+
if (isValid && !force) {
|
|
214
|
+
const claims = this.parseTokenClaims<TCustomClaims>(accessToken);
|
|
215
|
+
return { valid: true, refreshed: false, session, claims };
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// Determine organization ID: explicit > extracted from token
|
|
219
|
+
let organizationId = explicitOrgId;
|
|
220
|
+
if (!organizationId && isValid) {
|
|
221
|
+
try {
|
|
222
|
+
const oldClaims = this.parseTokenClaims(accessToken);
|
|
223
|
+
organizationId = oldClaims.org_id;
|
|
224
|
+
} catch {
|
|
225
|
+
// Token parsing failed - refresh without org context
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
const newSession = await this.refreshTokens(
|
|
230
|
+
session.refreshToken,
|
|
231
|
+
organizationId,
|
|
232
|
+
);
|
|
233
|
+
const newClaims = this.parseTokenClaims<TCustomClaims>(
|
|
234
|
+
newSession.accessToken,
|
|
235
|
+
);
|
|
236
|
+
return {
|
|
237
|
+
valid: true,
|
|
238
|
+
refreshed: true,
|
|
239
|
+
session: newSession,
|
|
240
|
+
claims: newClaims,
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
}
|