@workos/authkit-session 0.0.1-alpha.1

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/dist/index.cjs ADDED
@@ -0,0 +1,878 @@
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;// package.json
2
+ var version = "0.0.1-alpha.1";
3
+
4
+ // src/HttpClient.ts
5
+ var HttpClient = class {
6
+
7
+
8
+
9
+
10
+ constructor(config) {
11
+ this.baseUrl = config.baseUrl.replace(/\/$/, "");
12
+ this.defaultHeaders = {
13
+ "Content-Type": "application/json",
14
+ Accept: "application/json",
15
+ ...config.defaultHeaders
16
+ };
17
+ this.timeout = config.timeout || 3e4;
18
+ this.credentials = config.credentials || "same-origin";
19
+ }
20
+ createError(message, status, details) {
21
+ return { message, status, details };
22
+ }
23
+ async request(endpoint, options) {
24
+ let url = `${this.baseUrl}${endpoint}`;
25
+ const headers = { ...this.defaultHeaders, ...options.headers };
26
+ const fetchOptions = {
27
+ method: options.method,
28
+ headers,
29
+ credentials: _nullishCoalesce(options.credentials, () => ( this.credentials)),
30
+ mode: _nullishCoalesce(options.mode, () => ( "cors"))
31
+ };
32
+ if (options.params) {
33
+ url += new URLSearchParams(options.params).toString();
34
+ }
35
+ if (options.body) {
36
+ if (options.body instanceof FormData) {
37
+ fetchOptions.body = options.body;
38
+ const headerRecord = fetchOptions.headers;
39
+ delete headerRecord["Content-Type"];
40
+ } else {
41
+ fetchOptions.body = typeof options.body === "string" ? options.body : JSON.stringify(options.body);
42
+ }
43
+ }
44
+ try {
45
+ const controller = new AbortController();
46
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
47
+ const response = await fetch(url, {
48
+ ...fetchOptions,
49
+ signal: controller.signal
50
+ });
51
+ clearTimeout(timeoutId);
52
+ const responseData = await response.json();
53
+ const responseHeaders = {};
54
+ response.headers.forEach((value, key) => {
55
+ responseHeaders[key] = value;
56
+ });
57
+ return {
58
+ data: responseData,
59
+ status: response.status,
60
+ headers: responseHeaders,
61
+ ok: response.ok
62
+ };
63
+ } catch (error) {
64
+ if (error instanceof Error) {
65
+ if (error.name === "AbortController") {
66
+ throw this.createError("Request timeout", 408);
67
+ }
68
+ throw this.createError(error.message);
69
+ }
70
+ throw this.createError("Unknown error occurred");
71
+ }
72
+ }
73
+ async get(endpoint, options = {}) {
74
+ return this.request(endpoint, { ...options, method: "GET" });
75
+ }
76
+ async post(endpoint, body, options = {}) {
77
+ return this.request(endpoint, { ...options, method: "POST", body });
78
+ }
79
+ async put(endpoint, body, options = {}) {
80
+ return this.request(endpoint, { ...options, method: "PUT", body });
81
+ }
82
+ async delete(endpoint, options = {}) {
83
+ return this.request(endpoint, { ...options, method: "DELETE" });
84
+ }
85
+ async patch(endpoint, body, options = {}) {
86
+ return this.request(endpoint, { ...options, method: "PATCH", body });
87
+ }
88
+ };
89
+ var HttpClient_default = HttpClient;
90
+
91
+ // src/utils.ts
92
+ function once(fn) {
93
+ let called = false;
94
+ let result;
95
+ return (...args) => {
96
+ if (!called) {
97
+ result = fn(...args);
98
+ called = true;
99
+ }
100
+ return result;
101
+ };
102
+ }
103
+
104
+ // src/core/config/ConfigurationProvider.ts
105
+ var defaultSource = (key) => {
106
+ try {
107
+ const processEnv = _optionalChain([globalThis, 'optionalAccess', _ => _.process, 'optionalAccess', _2 => _2.env]);
108
+ return _optionalChain([processEnv, 'optionalAccess', _3 => _3[key]]);
109
+ } catch (e) {
110
+ return void 0;
111
+ }
112
+ };
113
+ var ConfigurationProvider = (_class = class {constructor() { _class.prototype.__init.call(this);_class.prototype.__init2.call(this);_class.prototype.__init3.call(this); }
114
+ __init() {this.config = {
115
+ cookieName: "wos-session",
116
+ apiHttps: true,
117
+ // Defaults to 400 days, the maximum allowed by Chrome
118
+ // It's fine to have a long cookie expiry date as the access/refresh tokens
119
+ // act as the actual time-limited aspects of the session.
120
+ cookieMaxAge: 60 * 60 * 24 * 400,
121
+ apiHostname: "api.workos.com"
122
+ }}
123
+ __init2() {this.valueSource = defaultSource}
124
+ __init3() {this.requiredKeys = [
125
+ "clientId",
126
+ "apiKey",
127
+ "redirectUri",
128
+ "cookiePassword"
129
+ ]}
130
+ /**
131
+ * Convert a camelCase string to an uppercase, underscore-separated environment variable name.
132
+ * @param str The string to convert
133
+ * @returns The environment variable name
134
+ */
135
+ getEnvironmentVariableName(str) {
136
+ return `WORKOS_${str.replace(/([a-z])([A-Z])/g, "$1_$2").toUpperCase()}`;
137
+ }
138
+ updateConfig(config) {
139
+ this.config = { ...this.config, ...config };
140
+ }
141
+ setValueSource(source) {
142
+ this.valueSource = source;
143
+ }
144
+ configure(configOrSource, source) {
145
+ if (typeof configOrSource === "function") {
146
+ this.setValueSource(configOrSource);
147
+ } else if (typeof configOrSource === "object" && !source) {
148
+ this.updateConfig(configOrSource);
149
+ } else if (typeof configOrSource === "object" && source) {
150
+ this.updateConfig(configOrSource);
151
+ this.setValueSource(source);
152
+ }
153
+ if (this.config.cookiePassword && this.config.cookiePassword.length < 32) {
154
+ throw new Error("cookiePassword must be at least 32 characters long");
155
+ }
156
+ }
157
+ getValue(key) {
158
+ const envKey = this.getEnvironmentVariableName(key);
159
+ let envValue = void 0;
160
+ const { valueSource, config } = this;
161
+ if (typeof valueSource === "function") {
162
+ envValue = valueSource(envKey);
163
+ } else if (valueSource && envKey in valueSource) {
164
+ envValue = valueSource[envKey];
165
+ }
166
+ if (envValue != null) {
167
+ if (key === "apiHttps" && typeof envValue === "string") {
168
+ return envValue === "true";
169
+ }
170
+ if ((key === "apiPort" || key === "cookieMaxAge") && typeof envValue === "string") {
171
+ const num = parseInt(envValue, 10);
172
+ return isNaN(num) ? void 0 : num;
173
+ }
174
+ return envValue;
175
+ }
176
+ if (key in config && config[key] != void 0) {
177
+ return config[key];
178
+ }
179
+ if (this.requiredKeys.includes(key)) {
180
+ throw new Error(
181
+ `Missing required configuration value for ${key} (${envKey}).`
182
+ );
183
+ }
184
+ return void 0;
185
+ }
186
+ getConfig() {
187
+ return this.config;
188
+ }
189
+ }, _class);
190
+
191
+ // src/core/config.ts
192
+ var getConfigurationInstance = once(() => new ConfigurationProvider());
193
+ function configure(configOrSource, source) {
194
+ const config = getConfigurationInstance();
195
+ config.configure(configOrSource, source);
196
+ }
197
+ function getConfig(key) {
198
+ const config = getConfigurationInstance();
199
+ return config.getValue(key);
200
+ }
201
+ function getConfigurationProvider() {
202
+ return getConfigurationInstance();
203
+ }
204
+ function getFullConfig() {
205
+ const config = getConfigurationInstance();
206
+ return config.getConfig();
207
+ }
208
+
209
+ // src/core/client/WorkOSLite.ts
210
+ var UserManagement = class {
211
+
212
+
213
+
214
+ constructor(apiKey, baseURL, options = {}) {
215
+ this.key = apiKey;
216
+ this.baseURL = baseURL;
217
+ this.client = new HttpClient_default({
218
+ baseUrl: this.baseURL,
219
+ defaultHeaders: {
220
+ Authorization: `Bearer ${apiKey}`,
221
+ "User-Agent": options.appInfo ? `${options.appInfo.name}/${options.appInfo.version}` : "authkit-session"
222
+ }
223
+ });
224
+ }
225
+ // Helper method to create a query string
226
+ toQueryString(params) {
227
+ const searchParams = new URLSearchParams();
228
+ const keys = Object.keys(params).sort();
229
+ for (const key of keys) {
230
+ const value = params[key];
231
+ if (value) {
232
+ searchParams.append(key, value);
233
+ }
234
+ }
235
+ return searchParams.toString();
236
+ }
237
+ async getJwksUrl(clientId) {
238
+ if (!clientId) {
239
+ throw TypeError("clientId must be a valid clientId");
240
+ }
241
+ return `${this.baseURL}/sso/jwks/${clientId}`;
242
+ }
243
+ getLogoutUrl({
244
+ sessionId,
245
+ returnTo
246
+ }) {
247
+ if (!sessionId) {
248
+ throw new TypeError(`Incomplete arguments. Need to specify 'sessionId'.`);
249
+ }
250
+ const url = new URL(`${this.baseURL}/user_management/sessions/logout`);
251
+ url.searchParams.set("session_id", sessionId);
252
+ if (returnTo) {
253
+ url.searchParams.set("return_to", returnTo);
254
+ }
255
+ return url.toString();
256
+ }
257
+ getAuthorizationUrl({
258
+ connectionId,
259
+ codeChallenge,
260
+ codeChallengeMethod,
261
+ context,
262
+ clientId,
263
+ domainHint,
264
+ loginHint,
265
+ organizationId,
266
+ provider,
267
+ redirectUri,
268
+ state,
269
+ screenHint
270
+ }) {
271
+ if (!provider && !connectionId && !organizationId) {
272
+ throw new TypeError(
273
+ `Incomplete arguments. Need to specify either a 'connectionId', 'organizationId', or 'provider'.`
274
+ );
275
+ }
276
+ if (provider !== "authkit" && screenHint) {
277
+ throw new TypeError(
278
+ `'screenHint' is only supported for 'authkit' provider`
279
+ );
280
+ }
281
+ const query = this.toQueryString({
282
+ connection_id: connectionId,
283
+ code_challenge: codeChallenge,
284
+ code_challenge_method: codeChallengeMethod,
285
+ context,
286
+ organization_id: organizationId,
287
+ domain_hint: domainHint,
288
+ login_hint: loginHint,
289
+ provider,
290
+ client_id: clientId,
291
+ redirect_uri: redirectUri,
292
+ response_type: "code",
293
+ state,
294
+ screen_hint: screenHint
295
+ });
296
+ return `${this.baseURL}/user_management/authorize?${query}`;
297
+ }
298
+ async authenticateWithRefreshToken(options) {
299
+ const { data } = await this.client.post(
300
+ "/user_management/authenticate",
301
+ {
302
+ grant_type: "refresh_token",
303
+ client_id: options.clientId,
304
+ client_secret: this.key,
305
+ refresh_token: options.refreshToken,
306
+ organization_id: options.organizationId,
307
+ ip_address: options.ipAddress,
308
+ user_agent: options.userAgent
309
+ }
310
+ );
311
+ return this.deserializeAuthResponse(data);
312
+ }
313
+ async authenticateWithCode(options) {
314
+ const { data } = await this.client.post(
315
+ "/user_management/authenticate",
316
+ {
317
+ grant_type: "authorization_code",
318
+ client_id: options.clientId,
319
+ client_secret: this.key,
320
+ code: options.code,
321
+ code_verifier: options.codeVerifier,
322
+ invitation_token: options.invitationToken,
323
+ ip_address: options.ipAddress,
324
+ user_agent: options.userAgent
325
+ }
326
+ );
327
+ return this.deserializeAuthResponse(data);
328
+ }
329
+ async authenticateWithEmailVerification(options) {
330
+ const { data } = await this.client.post(
331
+ "/user_management/authenticate",
332
+ {
333
+ grant_type: "urn:workos:oauth:grant-type:email-verification:code",
334
+ client_id: options.clientId,
335
+ client_secret: this.key,
336
+ pending_authentication_token: options.pendingAuthenticationToken,
337
+ code: options.code,
338
+ ip_address: options.ipAddress,
339
+ user_agent: options.userAgent
340
+ }
341
+ );
342
+ return this.deserializeAuthResponse(data);
343
+ }
344
+ // Helper to deserialize auth response
345
+ deserializeAuthResponse(data) {
346
+ return {
347
+ user: {
348
+ object: data.user.object,
349
+ id: data.user.id,
350
+ email: data.user.email,
351
+ emailVerified: data.user.email_verified,
352
+ firstName: data.user.first_name,
353
+ profilePictureUrl: data.user.profile_picture_url,
354
+ lastName: data.user.last_name,
355
+ lastSignInAt: data.user.last_sign_in_at,
356
+ createdAt: data.user.created_at,
357
+ updatedAt: data.user.updated_at,
358
+ externalId: _nullishCoalesce(data.user.external_id, () => ( null)),
359
+ metadata: _nullishCoalesce(data.user.metadata, () => ( {}))
360
+ },
361
+ organizationId: data.organization_id,
362
+ accessToken: data.access_token,
363
+ refreshToken: data.refresh_token,
364
+ impersonator: data.impersonator,
365
+ authenticationMethod: data.authentication_method
366
+ };
367
+ }
368
+ };
369
+ var WorkOSLite = class {
370
+
371
+
372
+
373
+ constructor(apiKey, options) {
374
+ this.apiKey = apiKey;
375
+ const hostname = options.apiHostname || "api.workos.com";
376
+ const protocol = options.https !== false ? "https" : "http";
377
+ const port = options.port ? `:${options.port}` : "";
378
+ this.baseURL = `${protocol}://${hostname}${port}`;
379
+ this.userManagement = new UserManagement(this.apiKey, this.baseURL);
380
+ }
381
+ getJwksUrl(clientId) {
382
+ if (!clientId) {
383
+ throw TypeError("clientId must be a valid clientId");
384
+ }
385
+ return `${this.baseURL}/sso/jwks/${clientId}`;
386
+ }
387
+ };
388
+ function createWorkOSInstance() {
389
+ const apiKey = getConfig("apiKey");
390
+ const apiHostname = getConfig("apiHostname");
391
+ const apiHttps = getConfig("apiHttps");
392
+ const apiPort = getConfig("apiPort");
393
+ const clientId = getConfig("clientId");
394
+ const options = {
395
+ apiHostname,
396
+ https: apiHttps,
397
+ port: apiPort,
398
+ clientId,
399
+ appInfo: {
400
+ name: "authkit-session",
401
+ version
402
+ }
403
+ };
404
+ const workos = new WorkOSLite(apiKey, options);
405
+ return workos;
406
+ }
407
+ var getWorkOS = once(createWorkOSInstance);
408
+
409
+ // src/core/errors.ts
410
+ var AuthKitError = class extends Error {
411
+
412
+ constructor(message, cause, data) {
413
+ super(message);
414
+ this.name = "AuthKitError";
415
+ this.cause = cause;
416
+ this.data = data;
417
+ }
418
+ };
419
+ var SessionEcnryptionError = class extends AuthKitError {
420
+ constructor(message, cause) {
421
+ super(message, cause);
422
+ this.name = "SessionEncryptionError";
423
+ }
424
+ };
425
+ var TokenRefreshError = class extends AuthKitError {
426
+ constructor(message, cause) {
427
+ super(message, cause);
428
+ this.name = "TokenRefreshError";
429
+ }
430
+ };
431
+
432
+ // src/core/session/SessionManager.ts
433
+ var SessionManager = class {
434
+
435
+
436
+
437
+
438
+
439
+ constructor(config, storage, tokenManager, client, encryption) {
440
+ this.config = config;
441
+ this.storage = storage;
442
+ this.tokenManager = tokenManager;
443
+ this.client = client;
444
+ this.encryption = encryption;
445
+ }
446
+ async encryptSession(session) {
447
+ try {
448
+ const password = this.config.getValue("cookiePassword");
449
+ const encryptedSession = await this.encryption.sealData(session, {
450
+ password,
451
+ ttl: 0
452
+ });
453
+ return encryptedSession;
454
+ } catch (error) {
455
+ throw new SessionEcnryptionError("Failed to encrypt session", error);
456
+ }
457
+ }
458
+ async decryptSession(encryptedSession) {
459
+ try {
460
+ const password = this.config.getValue("cookiePassword");
461
+ const session = await this.encryption.unsealData(
462
+ encryptedSession,
463
+ { password }
464
+ );
465
+ return session;
466
+ } catch (error) {
467
+ console.error("Detailed error:", error);
468
+ throw new SessionEcnryptionError("Failed to decrypt session", error);
469
+ }
470
+ }
471
+ async getSession(request) {
472
+ const encryptedSession = await this.storage.getSession(request);
473
+ if (!encryptedSession) {
474
+ return null;
475
+ }
476
+ return this.decryptSession(encryptedSession);
477
+ }
478
+ async validateSession(encryptedSession) {
479
+ try {
480
+ const session = await this.decryptSession(encryptedSession);
481
+ const isValid = await this.tokenManager.verifyToken(session.accessToken);
482
+ if (isValid) {
483
+ if (this.tokenManager.isTokenExpiring(session.accessToken)) {
484
+ const refreshResult = await this.refreshSession(session);
485
+ return {
486
+ valid: true,
487
+ session: refreshResult.session,
488
+ claims: refreshResult.claims
489
+ };
490
+ }
491
+ const claims = this.tokenManager.parseTokenClaims(
492
+ session.accessToken
493
+ );
494
+ return {
495
+ valid: true,
496
+ session,
497
+ claims
498
+ };
499
+ } else {
500
+ try {
501
+ const refreshResult = await this.refreshSession(session);
502
+ return {
503
+ valid: true,
504
+ session: refreshResult.session,
505
+ claims: refreshResult.claims
506
+ };
507
+ } catch (error) {
508
+ return {
509
+ valid: false,
510
+ error: error instanceof Error ? error : new TokenRefreshError("Failed to refresh session", error)
511
+ };
512
+ }
513
+ }
514
+ } catch (error) {
515
+ return {
516
+ valid: false,
517
+ error: error instanceof Error ? error : new AuthKitError("Failed to decrypt session", error)
518
+ };
519
+ }
520
+ }
521
+ async withAuth(request) {
522
+ const encryptedSession = await this.storage.getSession(request);
523
+ if (!encryptedSession) {
524
+ return { user: null };
525
+ }
526
+ const { valid, session, claims } = await this.validateSession(encryptedSession);
527
+ if (!valid || !session || !claims) {
528
+ return { user: null };
529
+ }
530
+ return {
531
+ user: session.user,
532
+ sessionId: claims.sid,
533
+ impersonator: session.impersonator,
534
+ accessToken: session.accessToken,
535
+ refreshToken: session.refreshToken,
536
+ // TODO should this be here?
537
+ claims
538
+ };
539
+ }
540
+ async refreshSession(session, organizationId) {
541
+ try {
542
+ const currentClaims = this.tokenManager.parseTokenClaims(
543
+ session.accessToken
544
+ );
545
+ const refreshResponse = await this.client.userManagement.authenticateWithRefreshToken({
546
+ refreshToken: session.refreshToken,
547
+ clientId: this.config.getValue("clientId"),
548
+ organizationId: _nullishCoalesce(organizationId, () => ( currentClaims.org_id))
549
+ });
550
+ const newSession = {
551
+ accessToken: refreshResponse.accessToken,
552
+ refreshToken: refreshResponse.refreshToken,
553
+ user: refreshResponse.user,
554
+ impersonator: refreshResponse.impersonator
555
+ };
556
+ const sessionData = await this.encryptSession(newSession);
557
+ const claims = this.tokenManager.parseTokenClaims(
558
+ newSession.accessToken
559
+ );
560
+ return {
561
+ user: newSession.user,
562
+ sessionId: claims.sid,
563
+ organizationId: claims.org_id,
564
+ role: claims.role,
565
+ permissions: claims.permissions,
566
+ entitlements: claims.entitlements,
567
+ impersonator: newSession.impersonator,
568
+ accessToken: newSession.accessToken,
569
+ claims,
570
+ sessionData,
571
+ session: newSession
572
+ };
573
+ } catch (error) {
574
+ throw new TokenRefreshError("Failed to refresh session", error);
575
+ }
576
+ }
577
+ async getAuthorizationUrl({
578
+ returnPathname = "/",
579
+ redirectUri,
580
+ screenHint
581
+ }) {
582
+ return this.client.userManagement.getAuthorizationUrl({
583
+ provider: "authkit",
584
+ redirectUri: _nullishCoalesce(redirectUri, () => ( this.config.getValue("redirectUri"))),
585
+ screenHint,
586
+ clientId: this.config.getValue("clientId"),
587
+ state: returnPathname ? btoa(JSON.stringify({ returnPathname })) : void 0
588
+ });
589
+ }
590
+ async createSession(authResponse, response) {
591
+ const { accessToken, refreshToken, user, impersonator } = authResponse;
592
+ if (!accessToken || !refreshToken) {
593
+ throw new AuthKitError("Missing access or refresh token");
594
+ }
595
+ const session = {
596
+ accessToken,
597
+ refreshToken,
598
+ user,
599
+ impersonator
600
+ };
601
+ const encryptedSession = await this.encryptSession(session);
602
+ return this.storage.saveSession(response, encryptedSession);
603
+ }
604
+ async switchToOrganization(request, response, organizationId) {
605
+ const session = await this.getSession(request);
606
+ if (!session) {
607
+ throw new AuthKitError("No active session to switch organization");
608
+ }
609
+ try {
610
+ const refreshResult = await this.refreshSession(
611
+ session,
612
+ organizationId
613
+ );
614
+ const updatedResponse = await this.storage.saveSession(
615
+ response,
616
+ refreshResult.sessionData
617
+ );
618
+ return {
619
+ response: updatedResponse,
620
+ authResult: {
621
+ user: refreshResult.user,
622
+ sessionId: refreshResult.sessionId,
623
+ impersonator: refreshResult.impersonator,
624
+ accessToken: refreshResult.accessToken,
625
+ refreshToken: refreshResult.session.refreshToken,
626
+ claims: refreshResult.claims
627
+ }
628
+ };
629
+ } catch (error) {
630
+ if (_optionalChain([error, 'optionalAccess', _4 => _4.code]) === "sso_required") {
631
+ const authUrl = await this.getAuthorizationUrl({
632
+ redirectUri: this.config.getValue("redirectUri")
633
+ });
634
+ throw new AuthKitError(
635
+ `SSO required for organization ${organizationId}`,
636
+ error,
637
+ { authUrl }
638
+ );
639
+ }
640
+ if (_optionalChain([error, 'optionalAccess', _5 => _5.code]) === "mfa_enrollment") {
641
+ const authUrl = await this.getAuthorizationUrl({
642
+ redirectUri: this.config.getValue("redirectUri")
643
+ });
644
+ throw new AuthKitError(
645
+ `MFA enrollment required for organization ${organizationId}`,
646
+ error,
647
+ { authUrl }
648
+ );
649
+ }
650
+ if (_optionalChain([error, 'optionalAccess', _6 => _6.authkit_redirect_url])) {
651
+ throw new AuthKitError(
652
+ "Organization switch requires authentication",
653
+ error,
654
+ { authUrl: error.authkit_redirect_url }
655
+ );
656
+ }
657
+ throw new AuthKitError(
658
+ `Failed to switch to organization ${organizationId}`,
659
+ error
660
+ );
661
+ }
662
+ }
663
+ async terminateSession(session, response, options) {
664
+ const clearedResponse = await this.storage.clearSession(response);
665
+ const claims = this.tokenManager.parseTokenClaims(session.accessToken);
666
+ const logoutUrl = this.client.userManagement.getLogoutUrl({
667
+ sessionId: claims.sid,
668
+ returnTo: _optionalChain([options, 'optionalAccess', _7 => _7.returnTo])
669
+ });
670
+ return {
671
+ response: clearedResponse,
672
+ logoutUrl
673
+ };
674
+ }
675
+ };
676
+
677
+ // src/core/session/CookieSessionStorage.ts
678
+ var CookieSessionStorage = class {
679
+
680
+
681
+ constructor(config) {
682
+ this.cookieName = config.getValue("cookieName") || "workos_session";
683
+ this.cookieOptions = {
684
+ path: "/",
685
+ httpOnly: true,
686
+ sameSite: _nullishCoalesce(config.getValue("cookieSameSite"), () => ( "lax")),
687
+ secure: _nullishCoalesce(config.getValue("apiHttps"), () => ( true)),
688
+ maxAge: config.getValue("cookieMaxAge") || 60 * 60 * 24 * 400,
689
+ // 400 days
690
+ domain: config.getValue("cookieDomain")
691
+ };
692
+ }
693
+ };
694
+
695
+ // src/core/encryption/ironWebcryptoEncryption.ts
696
+ var _ironwebcrypto = require('iron-webcrypto');
697
+ var SessionEncryption = (_class2 = class {constructor() { _class2.prototype.__init4.call(this);_class2.prototype.__init5.call(this); }
698
+ __init4() {this.versionDelimiter = "~"}
699
+ __init5() {this.currentMajorVersion = 2}
700
+ // Parse an iron-session seal to extract the version
701
+ parseSeal(seal) {
702
+ const [sealWithoutVersion = "", tokenVersionAsString] = seal.split(
703
+ this.versionDelimiter
704
+ );
705
+ const tokenVersion = tokenVersionAsString == null ? null : parseInt(tokenVersionAsString, 10);
706
+ return { sealWithoutVersion, tokenVersion };
707
+ }
708
+ // Encrypt data in a way that's compatible with iron-session
709
+ async sealData(data, { password, ttl = 0 }) {
710
+ const passwordObj = {
711
+ id: "1",
712
+ secret: password
713
+ };
714
+ const seal = await _ironwebcrypto.seal.call(void 0, globalThis.crypto, data, passwordObj, {
715
+ encryption: {
716
+ saltBits: 256,
717
+ algorithm: "aes-256-cbc",
718
+ iterations: 1,
719
+ minPasswordlength: 32
720
+ },
721
+ integrity: {
722
+ saltBits: 256,
723
+ algorithm: "sha256",
724
+ iterations: 1,
725
+ minPasswordlength: 32
726
+ },
727
+ ttl: ttl * 1e3,
728
+ // Convert seconds to milliseconds
729
+ timestampSkewSec: 60,
730
+ localtimeOffsetMsec: 0
731
+ });
732
+ return `${seal}${this.versionDelimiter}${this.currentMajorVersion}`;
733
+ }
734
+ // Decrypt data from iron-session with HMAC verification
735
+ async unsealData(encryptedData, { password }) {
736
+ const { sealWithoutVersion, tokenVersion } = this.parseSeal(encryptedData);
737
+ const passwordMap = { 1: password };
738
+ const data = await _ironwebcrypto.unseal.call(void 0,
739
+ globalThis.crypto,
740
+ sealWithoutVersion,
741
+ passwordMap,
742
+ {
743
+ encryption: {
744
+ saltBits: 256,
745
+ algorithm: "aes-256-cbc",
746
+ iterations: 1,
747
+ minPasswordlength: 32
748
+ },
749
+ integrity: {
750
+ saltBits: 256,
751
+ algorithm: "sha256",
752
+ iterations: 1,
753
+ minPasswordlength: 32
754
+ },
755
+ ttl: 0,
756
+ timestampSkewSec: 60,
757
+ localtimeOffsetMsec: 0
758
+ }
759
+ );
760
+ if (tokenVersion === 2) {
761
+ return data;
762
+ } else if (tokenVersion !== null) {
763
+ return { ...data.persistent };
764
+ }
765
+ return data;
766
+ }
767
+ }, _class2);
768
+ var ironWebcryptoEncryption = new SessionEncryption();
769
+ var ironWebcryptoEncryption_default = ironWebcryptoEncryption;
770
+
771
+ // src/core/session/TokenManager.ts
772
+ var _jose = require('jose');
773
+ var TokenManager = (_class3 = class {
774
+
775
+
776
+ constructor(clientId, client) {;_class3.prototype.__init6.call(this);
777
+ this.clientId = clientId;
778
+ this.client = client;
779
+ }
780
+ __init6() {this.getPublicKey = once(
781
+ () => _jose.createRemoteJWKSet.call(void 0, new URL(this.client.getJwksUrl(this.clientId)))
782
+ )}
783
+ async verifyToken(token) {
784
+ try {
785
+ await _jose.jwtVerify.call(void 0, token, this.getPublicKey());
786
+ return true;
787
+ } catch (e2) {
788
+ return false;
789
+ }
790
+ }
791
+ parseTokenClaims(token) {
792
+ try {
793
+ return _jose.decodeJwt.call(void 0, token);
794
+ } catch (error) {
795
+ throw new Error("Invalid token");
796
+ }
797
+ }
798
+ isTokenExpiring(token, bufferSeconds) {
799
+ const expiryTime = this.getTokenExpiryTime(token);
800
+ if (!expiryTime) {
801
+ return false;
802
+ }
803
+ const buffer = _nullishCoalesce(bufferSeconds, () => ( 60));
804
+ const currentTime = Math.floor(Date.now() / 1e3);
805
+ return expiryTime - currentTime <= buffer;
806
+ }
807
+ getTokenExpiryTime(token) {
808
+ const claims = this.parseTokenClaims(token);
809
+ return claims.exp ? claims.exp : null;
810
+ }
811
+ }, _class3);
812
+ var TokenManager_default = TokenManager;
813
+
814
+ // src/core/createAuthKitFactory.ts
815
+ var createAuthKitFactory = once(function createAuthKit(options) {
816
+ const {
817
+ sessionStorageFactory,
818
+ clientFactory = () => getWorkOS(),
819
+ sessionEncryptionFactory = () => ironWebcryptoEncryption_default
820
+ } = options;
821
+ const getTokenManager = once(
822
+ () => new TokenManager_default(getConfig("clientId"), clientFactory(getFullConfig()))
823
+ );
824
+ const getSessionManager = once(
825
+ () => new SessionManager(
826
+ getConfigurationProvider(),
827
+ sessionStorageFactory(getFullConfig()),
828
+ getTokenManager(),
829
+ clientFactory(getFullConfig()),
830
+ sessionEncryptionFactory(getFullConfig())
831
+ )
832
+ );
833
+ return {
834
+ withAuth: (...args) => getSessionManager().withAuth(...args),
835
+ getAuthorizationUrl: (...args) => getSessionManager().getAuthorizationUrl(...args),
836
+ refreshSession: (...args) => getSessionManager().refreshSession(...args),
837
+ saveSession: (...args) => sessionStorageFactory(getFullConfig()).saveSession(...args),
838
+ getSignInUrl: (options2) => getSessionManager().getAuthorizationUrl({
839
+ ...options2,
840
+ screenHint: "sign-in"
841
+ }),
842
+ getSignUpUrl: (options2) => getSessionManager().getAuthorizationUrl({
843
+ ...options2,
844
+ screenHint: "sign-up"
845
+ }),
846
+ getLogoutUrl: (...args) => getSessionManager().terminateSession(...args),
847
+ switchToOrganization: (...args) => getSessionManager().switchToOrganization(...args),
848
+ getTokenClaims: async (request, accessToken) => {
849
+ if (accessToken) {
850
+ try {
851
+ return getTokenManager().parseTokenClaims(accessToken);
852
+ } catch (e3) {
853
+ return {};
854
+ }
855
+ }
856
+ const authResult = await getSessionManager().withAuth(request);
857
+ if (!authResult.accessToken) {
858
+ return {};
859
+ }
860
+ try {
861
+ return getTokenManager().parseTokenClaims(
862
+ authResult.accessToken
863
+ );
864
+ } catch (e4) {
865
+ return {};
866
+ }
867
+ }
868
+ };
869
+ });
870
+
871
+
872
+
873
+
874
+
875
+
876
+
877
+ exports.CookieSessionStorage = CookieSessionStorage; exports.SessionManager = SessionManager; exports.configure = configure; exports.createAuthKitFactory = createAuthKitFactory; exports.getConfig = getConfig; exports.getWorkOS = getWorkOS;
878
+ //# sourceMappingURL=index.cjs.map