@workos/authkit-session 0.1.1 → 0.1.3

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.
Files changed (67) hide show
  1. package/dist/core/client/types.d.ts +75 -0
  2. package/dist/core/client/types.d.ts.map +1 -0
  3. package/dist/core/client/types.js +2 -0
  4. package/dist/core/client/types.js.map +1 -0
  5. package/dist/core/client/workos.d.ts +11 -0
  6. package/dist/core/client/workos.d.ts.map +1 -0
  7. package/dist/core/client/workos.js +33 -0
  8. package/dist/core/client/workos.js.map +1 -0
  9. package/dist/core/config/ConfigurationProvider.d.ts +43 -0
  10. package/dist/core/config/ConfigurationProvider.d.ts.map +1 -0
  11. package/dist/core/config/ConfigurationProvider.js +171 -0
  12. package/dist/core/config/ConfigurationProvider.js.map +1 -0
  13. package/dist/core/config/types.d.ts +62 -0
  14. package/dist/core/config/types.d.ts.map +1 -0
  15. package/dist/core/config/types.js +2 -0
  16. package/dist/core/config/types.js.map +1 -0
  17. package/dist/core/config.d.ts +69 -0
  18. package/dist/core/config.d.ts.map +1 -0
  19. package/dist/core/config.js +49 -0
  20. package/dist/core/config.js.map +1 -0
  21. package/dist/core/createAuthKitFactory.d.ts +64 -0
  22. package/dist/core/createAuthKitFactory.d.ts.map +1 -0
  23. package/dist/core/createAuthKitFactory.js +95 -0
  24. package/dist/core/createAuthKitFactory.js.map +1 -0
  25. package/dist/core/encryption/ironSessionEncryption.d.ts +16 -0
  26. package/dist/core/encryption/ironSessionEncryption.d.ts.map +1 -0
  27. package/dist/core/encryption/ironSessionEncryption.js +6 -0
  28. package/dist/core/encryption/ironSessionEncryption.js.map +1 -0
  29. package/dist/core/encryption/ironWebcryptoEncryption.d.ts +19 -0
  30. package/dist/core/encryption/ironWebcryptoEncryption.d.ts.map +1 -0
  31. package/dist/core/encryption/ironWebcryptoEncryption.js +84 -0
  32. package/dist/core/encryption/ironWebcryptoEncryption.js.map +1 -0
  33. package/dist/core/encryption/pureWebcryptoEncryption.d.ts +29 -0
  34. package/dist/core/encryption/pureWebcryptoEncryption.d.ts.map +1 -0
  35. package/dist/core/encryption/pureWebcryptoEncryption.js +182 -0
  36. package/dist/core/encryption/pureWebcryptoEncryption.js.map +1 -0
  37. package/dist/core/errors.d.ts +14 -0
  38. package/dist/core/errors.d.ts.map +1 -0
  39. package/dist/core/errors.js +28 -0
  40. package/dist/core/errors.js.map +1 -0
  41. package/dist/core/session/CookieSessionStorage.d.ts +33 -0
  42. package/dist/core/session/CookieSessionStorage.d.ts.map +1 -0
  43. package/dist/core/session/CookieSessionStorage.js +52 -0
  44. package/dist/core/session/CookieSessionStorage.js.map +1 -0
  45. package/dist/core/session/SessionManager.d.ts +51 -0
  46. package/dist/core/session/SessionManager.d.ts.map +1 -0
  47. package/dist/core/session/SessionManager.js +238 -0
  48. package/dist/core/session/SessionManager.js.map +1 -0
  49. package/dist/core/session/TokenManager.d.ts +14 -0
  50. package/dist/core/session/TokenManager.d.ts.map +1 -0
  51. package/dist/core/session/TokenManager.js +43 -0
  52. package/dist/core/session/TokenManager.js.map +1 -0
  53. package/dist/core/session/types.d.ts +101 -0
  54. package/dist/core/session/types.d.ts.map +1 -0
  55. package/dist/core/session/types.js +2 -0
  56. package/dist/core/session/types.js.map +1 -0
  57. package/dist/index.d.ts +10 -0
  58. package/dist/index.d.ts.map +1 -0
  59. package/dist/index.js +8 -796
  60. package/dist/index.js.map +1 -1
  61. package/dist/utils.d.ts +9 -0
  62. package/dist/utils.d.ts.map +1 -0
  63. package/dist/utils.js +19 -0
  64. package/dist/utils.js.map +1 -0
  65. package/package.json +3 -2
  66. package/dist/index.cjs +0 -797
  67. package/dist/index.cjs.map +0 -1
package/dist/index.cjs DELETED
@@ -1,797 +0,0 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class; var _class2; var _class3;// src/core/client/workos.ts
2
- var _node = require('@workos-inc/node');
3
-
4
- // src/utils.ts
5
- function once(fn) {
6
- let called = false;
7
- let result;
8
- return (...args) => {
9
- if (!called) {
10
- result = fn(...args);
11
- called = true;
12
- }
13
- return result;
14
- };
15
- }
16
-
17
- // src/core/config/ConfigurationProvider.ts
18
- var defaultSource = (key) => {
19
- try {
20
- const processEnv = _optionalChain([globalThis, 'optionalAccess', _ => _.process, 'optionalAccess', _2 => _2.env]);
21
- return _optionalChain([processEnv, 'optionalAccess', _3 => _3[key]]);
22
- } catch (e2) {
23
- return void 0;
24
- }
25
- };
26
- var ConfigurationProvider = (_class = class {constructor() { _class.prototype.__init.call(this);_class.prototype.__init2.call(this);_class.prototype.__init3.call(this); }
27
- __init() {this.config = {
28
- cookieName: "wos-session",
29
- apiHttps: true,
30
- // Defaults to 400 days, the maximum allowed by Chrome
31
- // It's fine to have a long cookie expiry date as the access/refresh tokens
32
- // act as the actual time-limited aspects of the session.
33
- cookieMaxAge: 60 * 60 * 24 * 400,
34
- apiHostname: "api.workos.com"
35
- }}
36
- __init2() {this.valueSource = defaultSource}
37
- __init3() {this.requiredKeys = [
38
- "clientId",
39
- "apiKey",
40
- "redirectUri",
41
- "cookiePassword"
42
- ]}
43
- /**
44
- * Convert a camelCase string to an uppercase, underscore-separated environment variable name.
45
- * @param str The string to convert
46
- * @returns The environment variable name
47
- */
48
- getEnvironmentVariableName(str) {
49
- return `WORKOS_${str.replace(/([a-z])([A-Z])/g, "$1_$2").toUpperCase()}`;
50
- }
51
- updateConfig(config) {
52
- this.config = { ...this.config, ...config };
53
- }
54
- setValueSource(source) {
55
- this.valueSource = source;
56
- }
57
- configure(configOrSource, source) {
58
- if (typeof configOrSource === "function") {
59
- this.setValueSource(configOrSource);
60
- } else if (typeof configOrSource === "object" && !source) {
61
- this.updateConfig(configOrSource);
62
- } else if (typeof configOrSource === "object" && source) {
63
- this.updateConfig(configOrSource);
64
- this.setValueSource(source);
65
- }
66
- }
67
- getValue(key) {
68
- const envKey = this.getEnvironmentVariableName(key);
69
- const envValue = this.getEnvironmentValue(envKey);
70
- const rawValue = _nullishCoalesce(envValue, () => ( this.config[key]));
71
- if (rawValue != null) {
72
- return this.convertValueType(key, rawValue);
73
- }
74
- if (this.requiredKeys.includes(key)) {
75
- throw new Error(
76
- `Missing required configuration value for ${key} (${envKey}).`
77
- );
78
- }
79
- return void 0;
80
- }
81
- getEnvironmentValue(envKey) {
82
- const { valueSource } = this;
83
- if (typeof valueSource === "function") {
84
- return valueSource(envKey);
85
- }
86
- if (valueSource && envKey in valueSource) {
87
- return valueSource[envKey];
88
- }
89
- return void 0;
90
- }
91
- convertValueType(key, value) {
92
- if (typeof value !== "string") {
93
- return value;
94
- }
95
- if (key === "apiHttps") {
96
- return value === "true";
97
- }
98
- if (key === "apiPort" || key === "cookieMaxAge") {
99
- const num = parseInt(value, 10);
100
- return isNaN(num) ? void 0 : num;
101
- }
102
- return value;
103
- }
104
- /**
105
- * Validates that all required configuration values are present and meet requirements.
106
- * Collects all validation errors before throwing to provide comprehensive feedback.
107
- *
108
- * @throws {Error} If any required configuration is missing or invalid
109
- *
110
- * @example
111
- * ```typescript
112
- * const provider = new ConfigurationProvider();
113
- * try {
114
- * provider.validate();
115
- * } catch (error) {
116
- * console.error(error.message); // Shows all missing/invalid config at once
117
- * }
118
- * ```
119
- */
120
- validate() {
121
- const errors = [];
122
- for (const key of this.requiredKeys) {
123
- const envKey = this.getEnvironmentVariableName(key);
124
- const envValue = this.getEnvironmentValue(envKey);
125
- const configValue = this.config[key];
126
- const value = _nullishCoalesce(envValue, () => ( configValue));
127
- if (!value) {
128
- errors.push(`${envKey} is required`);
129
- } else if (key === "cookiePassword") {
130
- const password = String(value);
131
- if (password.length < 32) {
132
- errors.push(
133
- `${envKey} must be at least 32 characters (currently ${password.length})`
134
- );
135
- }
136
- }
137
- }
138
- if (errors.length > 0) {
139
- throw new Error(
140
- "AuthKit configuration error. Missing or invalid environment variables:\n\n" + errors.map((e) => ` \u2022 ${e}`).join("\n") + "\n\nSet these environment variables or call configure() with the required values.\nGet your values from the WorkOS Dashboard: https://dashboard.workos.com"
141
- );
142
- }
143
- }
144
- getConfig() {
145
- const fullConfig = {};
146
- const allKeys = /* @__PURE__ */ new Set([
147
- ...Object.keys(this.config),
148
- ...this.requiredKeys
149
- ]);
150
- for (const key of allKeys) {
151
- try {
152
- const value = this.getValue(key);
153
- if (value !== void 0) {
154
- fullConfig[key] = value;
155
- }
156
- } catch (error) {
157
- if (this.requiredKeys.includes(key)) {
158
- throw error;
159
- }
160
- }
161
- }
162
- return fullConfig;
163
- }
164
- }, _class);
165
-
166
- // src/core/config.ts
167
- var getConfigurationInstance = once(() => new ConfigurationProvider());
168
- function configure(configOrSource, source) {
169
- getConfigurationInstance().configure(configOrSource, source);
170
- }
171
- function getConfig(key) {
172
- return getConfigurationInstance().getValue(key);
173
- }
174
- function getConfigurationProvider() {
175
- return getConfigurationInstance();
176
- }
177
- function getFullConfig() {
178
- return getConfigurationInstance().getConfig();
179
- }
180
- function validateConfig() {
181
- return getConfigurationInstance().validate();
182
- }
183
-
184
- // package.json
185
- var package_default = {
186
- name: "@workos/authkit-session",
187
- version: "0.1.1",
188
- description: "",
189
- type: "module",
190
- main: "./dist/index.js",
191
- types: "./dist/index.d.ts",
192
- exports: {
193
- ".": {
194
- types: "./dist/index.d.ts",
195
- default: "./dist/index.js"
196
- }
197
- },
198
- scripts: {
199
- clean: "rm -rf dist",
200
- build: "tsc -p tsconfig.build.json",
201
- rebuild: "pnpm run clean && pnpm run build",
202
- dev: "tsc -p tsconfig.build.json --watch",
203
- prettier: "prettier --check .",
204
- format: "prettier --write .",
205
- typecheck: "tsc --noEmit",
206
- test: "vitest --run",
207
- "test:coverage": "vitest --run --coverage",
208
- "test:watch": "vitest --watch"
209
- },
210
- keywords: [],
211
- author: "WorkOS",
212
- license: "MIT",
213
- devDependencies: {
214
- "@types/node": "^20.17.0",
215
- "@vitest/coverage-v8": "^3.2.4",
216
- prettier: "^3.6.2",
217
- typescript: "^5.9.2",
218
- vitest: "^3.2.4"
219
- },
220
- dependencies: {
221
- "@workos-inc/node": "^8.0.0-beta.4",
222
- "iron-session": "^8.0.4",
223
- "iron-webcrypto": "^1.2.1",
224
- jose: "^6.0.12"
225
- },
226
- engines: {
227
- node: ">=20.0.0"
228
- },
229
- files: [
230
- "dist",
231
- "src",
232
- "README.md"
233
- ]
234
- };
235
-
236
- // src/core/client/workos.ts
237
- function createWorkOSInstance() {
238
- const apiKey = getConfig("apiKey");
239
- const apiHostname = getConfig("apiHostname");
240
- const apiHttps = getConfig("apiHttps");
241
- const apiPort = getConfig("apiPort");
242
- const options = {
243
- apiHostname,
244
- https: apiHttps,
245
- port: apiPort,
246
- appInfo: {
247
- name: "authkit-session",
248
- version: package_default.version
249
- }
250
- };
251
- const workos = new (0, _node.WorkOS)(apiKey, options);
252
- return workos;
253
- }
254
- var getWorkOS = once(createWorkOSInstance);
255
-
256
- // src/core/errors.ts
257
- var AuthKitError = class extends Error {
258
-
259
- constructor(message, cause, data) {
260
- super(message);
261
- this.name = "AuthKitError";
262
- this.cause = cause;
263
- this.data = data;
264
- }
265
- };
266
- var SessionEncryptionError = class extends AuthKitError {
267
- constructor(message, cause) {
268
- super(message, cause);
269
- this.name = "SessionEncryptionError";
270
- }
271
- };
272
- var TokenRefreshError = class extends AuthKitError {
273
- constructor(message, cause) {
274
- super(message, cause);
275
- this.name = "TokenRefreshError";
276
- }
277
- };
278
-
279
- // src/core/session/SessionManager.ts
280
- var SessionManager = class {
281
-
282
-
283
-
284
-
285
-
286
- constructor(config, storage, tokenManager, client, encryption) {
287
- this.config = config;
288
- this.storage = storage;
289
- this.tokenManager = tokenManager;
290
- this.client = client;
291
- this.encryption = encryption;
292
- }
293
- async encryptSession(session) {
294
- try {
295
- const password = this.config.getValue("cookiePassword");
296
- const encryptedSession = await this.encryption.sealData(session, {
297
- password,
298
- ttl: 0
299
- });
300
- return encryptedSession;
301
- } catch (error) {
302
- throw new SessionEncryptionError("Failed to encrypt session", error);
303
- }
304
- }
305
- async decryptSession(encryptedSession) {
306
- try {
307
- const password = this.config.getValue("cookiePassword");
308
- const session = await this.encryption.unsealData(
309
- encryptedSession,
310
- { password }
311
- );
312
- return session;
313
- } catch (error) {
314
- throw new SessionEncryptionError("Failed to decrypt session", error);
315
- }
316
- }
317
- async getSession(request) {
318
- const encryptedSession = await this.storage.getSession(request);
319
- if (!encryptedSession) {
320
- return null;
321
- }
322
- return this.decryptSession(encryptedSession);
323
- }
324
- async validateSession(encryptedSession) {
325
- try {
326
- const session = await this.decryptSession(encryptedSession);
327
- const isValid = await this.tokenManager.verifyToken(session.accessToken);
328
- const isExpiring = this.tokenManager.isTokenExpiring(session.accessToken);
329
- if (isValid && !isExpiring) {
330
- const claims = this.tokenManager.parseTokenClaims(
331
- session.accessToken
332
- );
333
- return {
334
- valid: true,
335
- session,
336
- claims
337
- };
338
- }
339
- try {
340
- const refreshResult = await this.refreshSession(session);
341
- return {
342
- valid: true,
343
- session: refreshResult.session,
344
- claims: refreshResult.claims
345
- };
346
- } catch (refreshError) {
347
- return {
348
- valid: false,
349
- error: refreshError instanceof Error ? refreshError : new TokenRefreshError(
350
- "Failed to refresh session",
351
- refreshError
352
- )
353
- };
354
- }
355
- } catch (decryptError) {
356
- return {
357
- valid: false,
358
- error: decryptError instanceof Error ? decryptError : new AuthKitError("Failed to decrypt session", decryptError)
359
- };
360
- }
361
- }
362
- async withAuth(request) {
363
- const encryptedSession = await this.storage.getSession(request);
364
- if (!encryptedSession) {
365
- return { user: null };
366
- }
367
- const { valid, session, claims } = await this.validateSession(encryptedSession);
368
- if (!valid || !session || !claims) {
369
- return { user: null };
370
- }
371
- return {
372
- user: session.user,
373
- sessionId: claims.sid,
374
- impersonator: session.impersonator,
375
- accessToken: session.accessToken,
376
- refreshToken: session.refreshToken,
377
- // TODO should this be here?
378
- claims
379
- };
380
- }
381
- async refreshSession(session, organizationId) {
382
- try {
383
- const currentClaims = this.tokenManager.parseTokenClaims(
384
- session.accessToken
385
- );
386
- const refreshResponse = await this.client.userManagement.authenticateWithRefreshToken({
387
- refreshToken: session.refreshToken,
388
- clientId: this.config.getValue("clientId"),
389
- organizationId: _nullishCoalesce(organizationId, () => ( currentClaims.org_id))
390
- });
391
- const newSession = {
392
- accessToken: refreshResponse.accessToken,
393
- refreshToken: refreshResponse.refreshToken,
394
- user: refreshResponse.user,
395
- impersonator: refreshResponse.impersonator
396
- };
397
- const sessionData = await this.encryptSession(newSession);
398
- const claims = this.tokenManager.parseTokenClaims(
399
- newSession.accessToken
400
- );
401
- return {
402
- user: newSession.user,
403
- sessionId: claims.sid,
404
- organizationId: claims.org_id,
405
- role: claims.role,
406
- roles: claims.roles,
407
- permissions: claims.permissions,
408
- entitlements: claims.entitlements,
409
- impersonator: newSession.impersonator,
410
- accessToken: newSession.accessToken,
411
- claims,
412
- sessionData,
413
- session: newSession
414
- };
415
- } catch (error) {
416
- throw new TokenRefreshError("Failed to refresh session", error);
417
- }
418
- }
419
- async getAuthorizationUrl({
420
- returnPathname,
421
- redirectUri,
422
- screenHint,
423
- organizationId,
424
- loginHint,
425
- prompt
426
- } = {}) {
427
- return this.client.userManagement.getAuthorizationUrl({
428
- provider: "authkit",
429
- redirectUri: _nullishCoalesce(redirectUri, () => ( this.config.getValue("redirectUri"))),
430
- screenHint,
431
- organizationId,
432
- loginHint,
433
- prompt,
434
- clientId: this.config.getValue("clientId"),
435
- state: returnPathname ? btoa(JSON.stringify({ returnPathname })) : void 0
436
- });
437
- }
438
- async createSession(authResponse, response) {
439
- const { accessToken, refreshToken, user, impersonator } = authResponse;
440
- if (!accessToken || !refreshToken) {
441
- throw new AuthKitError("Missing access or refresh token");
442
- }
443
- const session = {
444
- accessToken,
445
- refreshToken,
446
- user,
447
- impersonator
448
- };
449
- const encryptedSession = await this.encryptSession(session);
450
- return this.storage.saveSession(response, encryptedSession);
451
- }
452
- async switchToOrganization(request, response, organizationId) {
453
- const session = await this.getSession(request);
454
- if (!session) {
455
- throw new AuthKitError("No active session to switch organization");
456
- }
457
- try {
458
- const refreshResult = await this.refreshSession(
459
- session,
460
- organizationId
461
- );
462
- const updatedResponse = await this.storage.saveSession(
463
- response,
464
- refreshResult.sessionData
465
- );
466
- return {
467
- response: updatedResponse.response,
468
- headers: updatedResponse.headers,
469
- authResult: {
470
- user: refreshResult.user,
471
- sessionId: refreshResult.sessionId,
472
- impersonator: refreshResult.impersonator,
473
- accessToken: refreshResult.accessToken,
474
- refreshToken: refreshResult.session.refreshToken,
475
- claims: refreshResult.claims
476
- }
477
- };
478
- } catch (error) {
479
- throw await this.handleSwitchOrganizationError(error, organizationId);
480
- }
481
- }
482
- async handleSwitchOrganizationError(error, organizationId) {
483
- const errorCodeToMessage = {
484
- sso_required: `SSO required for organization ${organizationId}`,
485
- mfa_enrollment: `MFA enrollment required for organization ${organizationId}`
486
- };
487
- const errorMessage = errorCodeToMessage[_optionalChain([error, 'optionalAccess', _4 => _4.code])];
488
- if (errorMessage) {
489
- const authUrl = await this.getAuthorizationUrl({
490
- redirectUri: this.config.getValue("redirectUri")
491
- });
492
- return new AuthKitError(errorMessage, error, { authUrl });
493
- }
494
- if (_optionalChain([error, 'optionalAccess', _5 => _5.authkit_redirect_url])) {
495
- return new AuthKitError(
496
- "Organization switch requires authentication",
497
- error,
498
- { authUrl: error.authkit_redirect_url }
499
- );
500
- }
501
- return new AuthKitError(
502
- `Failed to switch to organization ${organizationId}`,
503
- error
504
- );
505
- }
506
- async terminateSession(session, response, options) {
507
- const claims = this.tokenManager.parseTokenClaims(session.accessToken);
508
- try {
509
- await this.client.userManagement.revokeSession({
510
- sessionId: claims.sid
511
- });
512
- } catch (error) {
513
- console.error("Failed to revoke session on WorkOS:", error);
514
- }
515
- const cleared = await this.storage.clearSession(response);
516
- const logoutUrl = this.client.userManagement.getLogoutUrl({
517
- sessionId: claims.sid,
518
- returnTo: _optionalChain([options, 'optionalAccess', _6 => _6.returnTo])
519
- });
520
- return {
521
- response: cleared.response,
522
- headers: cleared.headers,
523
- logoutUrl
524
- };
525
- }
526
- };
527
-
528
- // src/core/session/CookieSessionStorage.ts
529
- var CookieSessionStorage = class {
530
-
531
-
532
-
533
- constructor(config) {
534
- this.config = config;
535
- this.cookieName = config.getValue("cookieName") || "wos_session";
536
- this.cookieOptions = {
537
- path: "/",
538
- httpOnly: true,
539
- sameSite: _nullishCoalesce(config.getValue("cookieSameSite"), () => ( "lax")),
540
- secure: _nullishCoalesce(config.getValue("apiHttps"), () => ( true)),
541
- maxAge: config.getValue("cookieMaxAge") || 60 * 60 * 24 * 400,
542
- // 400 days
543
- domain: config.getValue("cookieDomain")
544
- };
545
- }
546
- async applyHeaders(_response, _headers) {
547
- }
548
- buildSetCookie(value, expired) {
549
- const a = [`${this.cookieName}=${encodeURIComponent(value)}`];
550
- const o = this.cookieOptions;
551
- if (o.path) a.push(`Path=${o.path}`);
552
- if (o.domain) a.push(`Domain=${o.domain}`);
553
- if (o.maxAge || expired) a.push(`Max-Age=${expired ? 0 : o.maxAge}`);
554
- if (o.httpOnly) a.push("HttpOnly");
555
- if (o.secure) a.push("Secure");
556
- if (o.sameSite) a.push(`SameSite=${o.sameSite}`);
557
- if (o.priority) a.push(`Priority=${o.priority}`);
558
- if (o.partitioned) a.push("Partitioned");
559
- return a.join("; ");
560
- }
561
- async saveSession(response, sessionData) {
562
- const header = this.buildSetCookie(sessionData);
563
- const mutated = await this.applyHeaders(response, { "Set-Cookie": header });
564
- return _nullishCoalesce(mutated, () => ( { headers: { "Set-Cookie": header } }));
565
- }
566
- async clearSession(response) {
567
- const header = this.buildSetCookie("", true);
568
- const mutated = await this.applyHeaders(response, { "Set-Cookie": header });
569
- return _nullishCoalesce(mutated, () => ( { headers: { "Set-Cookie": header } }));
570
- }
571
- };
572
-
573
- // src/core/encryption/ironWebcryptoEncryption.ts
574
- var _ironwebcrypto = require('iron-webcrypto');
575
- var ironCrypto = globalThis.crypto;
576
- var SessionEncryption = (_class2 = class {constructor() { _class2.prototype.__init4.call(this);_class2.prototype.__init5.call(this); }
577
- __init4() {this.versionDelimiter = "~"}
578
- __init5() {this.currentMajorVersion = 2}
579
- // Parse an iron-session seal to extract the version
580
- parseSeal(seal) {
581
- const [sealWithoutVersion = "", tokenVersionAsString] = seal.split(
582
- this.versionDelimiter
583
- );
584
- const tokenVersion = tokenVersionAsString == null ? null : parseInt(tokenVersionAsString, 10);
585
- return { sealWithoutVersion, tokenVersion };
586
- }
587
- // Encrypt data in a way that's compatible with iron-session
588
- async sealData(data, { password, ttl = 0 }) {
589
- const passwordObj = {
590
- id: "1",
591
- secret: password
592
- };
593
- const seal = await _ironwebcrypto.seal.call(void 0, ironCrypto, data, passwordObj, {
594
- encryption: {
595
- saltBits: 256,
596
- algorithm: "aes-256-cbc",
597
- iterations: 1,
598
- minPasswordlength: 32
599
- },
600
- integrity: {
601
- saltBits: 256,
602
- algorithm: "sha256",
603
- iterations: 1,
604
- minPasswordlength: 32
605
- },
606
- ttl: ttl * 1e3,
607
- // Convert seconds to milliseconds
608
- timestampSkewSec: 60,
609
- localtimeOffsetMsec: 0
610
- });
611
- return `${seal}${this.versionDelimiter}${this.currentMajorVersion}`;
612
- }
613
- // Decrypt data from iron-session with HMAC verification
614
- async unsealData(encryptedData, { password }) {
615
- const { sealWithoutVersion, tokenVersion } = this.parseSeal(encryptedData);
616
- const passwordMap = { 1: password };
617
- const data = await _ironwebcrypto.unseal.call(void 0, ironCrypto, sealWithoutVersion, passwordMap, {
618
- encryption: {
619
- saltBits: 256,
620
- algorithm: "aes-256-cbc",
621
- iterations: 1,
622
- minPasswordlength: 32
623
- },
624
- integrity: {
625
- saltBits: 256,
626
- algorithm: "sha256",
627
- iterations: 1,
628
- minPasswordlength: 32
629
- },
630
- ttl: 0,
631
- timestampSkewSec: 60,
632
- localtimeOffsetMsec: 0
633
- });
634
- if (tokenVersion === 2) {
635
- return data;
636
- } else if (tokenVersion !== null) {
637
- return { ...data.persistent };
638
- }
639
- return data;
640
- }
641
- }, _class2);
642
- var ironWebcryptoEncryption = new SessionEncryption();
643
- var ironWebcryptoEncryption_default = ironWebcryptoEncryption;
644
-
645
- // src/core/session/TokenManager.ts
646
- var _jose = require('jose');
647
- var TokenManager = (_class3 = class {
648
-
649
-
650
- constructor(clientId, client) {;_class3.prototype.__init6.call(this);
651
- this.clientId = clientId;
652
- this.client = client;
653
- }
654
- __init6() {this.getPublicKey = once(
655
- () => _jose.createRemoteJWKSet.call(void 0,
656
- new URL(this.client.userManagement.getJwksUrl(this.clientId))
657
- )
658
- )}
659
- async verifyToken(token) {
660
- try {
661
- await _jose.jwtVerify.call(void 0, token, this.getPublicKey());
662
- return true;
663
- } catch (e3) {
664
- return false;
665
- }
666
- }
667
- parseTokenClaims(token) {
668
- try {
669
- return _jose.decodeJwt.call(void 0, token);
670
- } catch (error) {
671
- throw new Error("Invalid token");
672
- }
673
- }
674
- isTokenExpiring(token, bufferSeconds) {
675
- const expiryTime = this.getTokenExpiryTime(token);
676
- if (!expiryTime) {
677
- return false;
678
- }
679
- const buffer = _nullishCoalesce(bufferSeconds, () => ( 60));
680
- const currentTime = Math.floor(Date.now() / 1e3);
681
- return expiryTime - currentTime <= buffer;
682
- }
683
- getTokenExpiryTime(token) {
684
- const claims = this.parseTokenClaims(token);
685
- return _nullishCoalesce(claims.exp, () => ( null));
686
- }
687
- }, _class3);
688
- var TokenManager_default = TokenManager;
689
-
690
- // src/core/createAuthKitFactory.ts
691
- var createAuthKitFactory = once(function createAuthKit(options) {
692
- const {
693
- sessionStorageFactory,
694
- clientFactory = () => getWorkOS(),
695
- sessionEncryptionFactory = () => ironWebcryptoEncryption_default
696
- } = options;
697
- const getTokenManager = once(
698
- () => new TokenManager_default(getConfig("clientId"), clientFactory(getFullConfig()))
699
- );
700
- const getSessionManager = once(
701
- () => new SessionManager(
702
- getConfigurationProvider(),
703
- sessionStorageFactory(getFullConfig()),
704
- getTokenManager(),
705
- clientFactory(getFullConfig()),
706
- sessionEncryptionFactory(getFullConfig())
707
- )
708
- );
709
- return {
710
- withAuth: (...args) => getSessionManager().withAuth(...args),
711
- getAuthorizationUrl: (...args) => getSessionManager().getAuthorizationUrl(...args),
712
- refreshSession: (...args) => getSessionManager().refreshSession(...args),
713
- saveSession: (...args) => sessionStorageFactory(getFullConfig()).saveSession(...args),
714
- getSignInUrl: (options2) => getSessionManager().getAuthorizationUrl({
715
- ...options2,
716
- screenHint: "sign-in"
717
- }),
718
- getSignUpUrl: (options2) => getSessionManager().getAuthorizationUrl({
719
- ...options2,
720
- screenHint: "sign-up"
721
- }),
722
- // Expose getWorkOS for direct client access
723
- getWorkOS: () => clientFactory(getFullConfig()),
724
- // Expose SessionManager's getSession directly
725
- getSession: (request) => getSessionManager().getSession(request),
726
- // terminateSession uses the standard SessionManager signature
727
- terminateSession: (...args) => getSessionManager().terminateSession(...args),
728
- signOut: async (request, response, options2) => {
729
- const authResult = await getSessionManager().withAuth(request);
730
- if (!authResult.user || !authResult.accessToken || !authResult.refreshToken) {
731
- return sessionStorageFactory(getFullConfig()).clearSession(response);
732
- }
733
- const session = {
734
- accessToken: authResult.accessToken,
735
- refreshToken: authResult.refreshToken,
736
- user: authResult.user,
737
- impersonator: authResult.impersonator
738
- };
739
- const result = await getSessionManager().terminateSession(
740
- session,
741
- response,
742
- options2
743
- );
744
- return result.response;
745
- },
746
- switchToOrganization: (...args) => getSessionManager().switchToOrganization(...args),
747
- handleCallback: async (_request, response, options2) => {
748
- const config = getFullConfig();
749
- const clientId = config.clientId;
750
- const client = clientFactory(config);
751
- const authResponse = await client.userManagement.authenticateWithCode({
752
- code: options2.code,
753
- clientId
754
- });
755
- const updatedResponse = await getSessionManager().createSession(
756
- authResponse,
757
- response
758
- );
759
- let returnPathname = "/";
760
- if (options2.state) {
761
- try {
762
- const decoded = JSON.parse(atob(options2.state));
763
- returnPathname = decoded.returnPathname || "/";
764
- } catch (e4) {
765
- }
766
- }
767
- return {
768
- response: updatedResponse,
769
- returnPathname,
770
- authResponse
771
- };
772
- },
773
- getTokenClaims: async (request, accessToken) => {
774
- const tokenToUse = accessToken || (await getSessionManager().withAuth(request)).accessToken;
775
- if (!tokenToUse) {
776
- return {};
777
- }
778
- try {
779
- return getTokenManager().parseTokenClaims(tokenToUse);
780
- } catch (e5) {
781
- return {};
782
- }
783
- }
784
- };
785
- });
786
-
787
-
788
-
789
-
790
-
791
-
792
-
793
-
794
-
795
-
796
- exports.ConfigurationProvider = ConfigurationProvider; exports.CookieSessionStorage = CookieSessionStorage; exports.SessionManager = SessionManager; exports.configure = configure; exports.createAuthKitFactory = createAuthKitFactory; exports.getConfig = getConfig; exports.getConfigurationProvider = getConfigurationProvider; exports.getWorkOS = getWorkOS; exports.validateConfig = validateConfig;
797
- //# sourceMappingURL=index.cjs.map