@workos/authkit-session 0.2.0 → 0.3.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.
@@ -75,10 +75,14 @@ export declare class AuthKitCore {
75
75
  *
76
76
  * @param refreshToken - The refresh token
77
77
  * @param organizationId - Optional organization ID to switch to
78
+ * @param context - Optional context for error reporting (userId, sessionId)
78
79
  * @returns New access token, refresh token, user, and impersonator
79
80
  * @throws TokenRefreshError if refresh fails
80
81
  */
81
- refreshTokens(refreshToken: string, organizationId?: string): Promise<{
82
+ refreshTokens(refreshToken: string, organizationId?: string, context?: {
83
+ userId?: string;
84
+ sessionId?: string;
85
+ }): Promise<{
82
86
  accessToken: string;
83
87
  refreshToken: string;
84
88
  user: User;
@@ -1 +1 @@
1
- {"version":3,"file":"AuthKitCore.d.ts","sourceRoot":"","sources":["../../src/core/AuthKitCore.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAGnE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAEvD,OAAO,KAAK,EACV,eAAe,EACf,YAAY,EACZ,OAAO,EACP,iBAAiB,EAClB,MAAM,oBAAoB,CAAC;AAE5B;;;;;;;;;;;;GAYG;AACH,qBAAa,WAAW;IACtB,OAAO,CAAC,MAAM,CAAgB;IAC9B,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,UAAU,CAAoB;IACtC,OAAO,CAAC,QAAQ,CAAS;gBAGvB,MAAM,EAAE,aAAa,EACrB,MAAM,EAAE,MAAM,EACd,UAAU,EAAE,iBAAiB;IAQ/B;;OAEG;IACH,OAAO,CAAC,QAAQ,CAAC,YAAY,CAI3B;IAEF;;;;;OAKG;IACG,WAAW,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IASlD;;;;;;OAMG;IACH,eAAe,CAAC,KAAK,E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kB,CAAC,aAAa,GAAG,YAAY,EACnD,OAAO,EAAE,OAAO,EAChB,OAAO,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,OAAO,CAAC;QAAC,cAAc,CAAC,EAAE,MAAM,CAAA;KAAE,GACrD,OAAO,CAAC;QACT,KAAK,EAAE,OAAO,CAAC;QACf,SAAS,EAAE,OAAO,CAAC;QACnB,OAAO,EAAE,OAAO,CAAC;QACjB,MAAM,EAAE,eAAe,GAAG,aAAa,CAAC;KACzC,CAAC;CA8CH"}
@@ -124,10 +124,11 @@ export class AuthKitCore {
124
124
  *
125
125
  * @param refreshToken - The refresh token
126
126
  * @param organizationId - Optional organization ID to switch to
127
+ * @param context - Optional context for error reporting (userId, sessionId)
127
128
  * @returns New access token, refresh token, user, and impersonator
128
129
  * @throws TokenRefreshError if refresh fails
129
130
  */
130
- async refreshTokens(refreshToken, organizationId) {
131
+ async refreshTokens(refreshToken, organizationId, context) {
131
132
  try {
132
133
  const result = await this.client.userManagement.authenticateWithRefreshToken({
133
134
  refreshToken,
@@ -142,7 +143,7 @@ export class AuthKitCore {
142
143
  };
143
144
  }
144
145
  catch (error) {
145
- throw new TokenRefreshError('Failed to refresh tokens', error);
146
+ throw new TokenRefreshError('Failed to refresh tokens', error, context);
146
147
  }
147
148
  }
148
149
  /**
@@ -177,7 +178,15 @@ export class AuthKitCore {
177
178
  // Token parsing failed - refresh without org context
178
179
  }
179
180
  }
180
- const newSession = await this.refreshTokens(session.refreshToken, organizationId);
181
+ // Extract session ID for error context (works on expired tokens too)
182
+ let sessionId;
183
+ try {
184
+ sessionId = this.parseTokenClaims(accessToken).sid;
185
+ }
186
+ catch {
187
+ // Token parsing failed - continue without session context
188
+ }
189
+ const newSession = await this.refreshTokens(session.refreshToken, organizationId, { userId: session.user?.id, sessionId });
181
190
  const newClaims = this.parseTokenClaims(newSession.accessToken);
182
191
  return {
183
192
  valid: true,
@@ -1 +1 @@
1
- {"version":3,"file":"AuthKitCore.js","sourceRoot":"","sources":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OAAO;YACL,KAAK,EAAE,IAAI;YACX,SAAS,EAAE,IAAI;YACf,OAAO,EAAE,UAAU;YACnB,MAAM,EAAE,SAAS;SAClB,CAAC;IACJ,CAAC;CACF"}
@@ -9,6 +9,11 @@ export declare class TokenValidationError extends AuthKitError {
9
9
  constructor(message: string, cause?: unknown);
10
10
  }
11
11
  export declare class TokenRefreshError extends AuthKitError {
12
- constructor(message: string, cause?: unknown);
12
+ readonly userId?: string;
13
+ readonly sessionId?: string;
14
+ constructor(message: string, cause?: unknown, context?: {
15
+ userId?: string;
16
+ sessionId?: string;
17
+ });
13
18
  }
14
19
  //# sourceMappingURL=errors.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../src/core/errors.ts"],"names":[],"mappings":"AAAA,qBAAa,YAAa,SAAQ,KAAK;IACrC,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;gBAEf,OAAO,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC;CAMzE;AAED,qBAAa,sBAAuB,SAAQ,YAAY;gBAC1C,OAAO,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,OAAO;CAI7C;AAED,qBAAa,oBAAqB,SAAQ,YAAY;gBACxC,OAAO,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,OAAO;CAI7C;AAED,qBAAa,iBAAkB,SAAQ,YAAY;gBACrC,OAAO,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,OAAO;CAI7C"}
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../src/core/errors.ts"],"names":[],"mappings":"AAAA,qBAAa,YAAa,SAAQ,KAAK;IACrC,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;gBAEf,OAAO,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC;CAMzE;AAED,qBAAa,sBAAuB,SAAQ,YAAY;gBAC1C,OAAO,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,OAAO;CAI7C;AAED,qBAAa,oBAAqB,SAAQ,YAAY;gBACxC,OAAO,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,OAAO;CAI7C;AAED,qBAAa,iBAAkB,SAAQ,YAAY;IACjD,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;gBAG1B,OAAO,EAAE,MAAM,EACf,KAAK,CAAC,EAAE,OAAO,EACf,OAAO,CAAC,EAAE;QAAE,MAAM,CAAC,EAAE,MAAM,CAAC;QAAC,SAAS,CAAC,EAAE,MAAM,CAAA;KAAE;CAOpD"}
@@ -20,9 +20,13 @@ export class TokenValidationError extends AuthKitError {
20
20
  }
21
21
  }
22
22
  export class TokenRefreshError extends AuthKitError {
23
- constructor(message, cause) {
23
+ userId;
24
+ sessionId;
25
+ constructor(message, cause, context) {
24
26
  super(message, cause);
25
27
  this.name = 'TokenRefreshError';
28
+ this.userId = context?.userId;
29
+ this.sessionId = context?.sessionId;
26
30
  }
27
31
  }
28
32
  //# sourceMappingURL=errors.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/core/errors.ts"],"names":[],"mappings":"AAAA,MAAM,OAAO,YAAa,SAAQ,KAAK;IACrC,IAAI,CAAuB;IAE3B,YAAY,OAAe,EAAE,KAAe,EAAE,IAA0B;QACtE,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,cAAc,CAAC;QAC3B,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IACnB,CAAC;CACF;AAED,MAAM,OAAO,sBAAuB,SAAQ,YAA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kB,SAAQ,YAAY;IACxC,MAAM,CAAU;IAChB,SAAS,CAAU;IAE5B,YACE,OAAe,EACf,KAAe,EACf,OAAiD;QAEjD,KAAK,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;QACtB,IAAI,CAAC,IAAI,GAAG,mBAAmB,CAAC;QAChC,IAAI,CAAC,MAAM,GAAG,OAAO,EAAE,MAAM,CAAC;QAC9B,IAAI,CAAC,SAAS,GAAG,OAAO,EAAE,SAAS,CAAC;IACtC,CAAC;CACF"}
package/dist/index.d.ts CHANGED
@@ -28,6 +28,7 @@ export { default as sessionEncryption } from './core/encryption/ironWebcryptoEnc
28
28
  export { configure, getConfig, getConfigurationProvider, validateConfig, } from './core/config.js';
29
29
  export { ConfigurationProvider } from './core/config/ConfigurationProvider.js';
30
30
  export { getWorkOS } from './core/client/workos.js';
31
+ export { AuthKitError, SessionEncryptionError, TokenValidationError, TokenRefreshError, } from './core/errors.js';
31
32
  export * from './core/session/types.js';
32
33
  export * from './core/config/types.js';
33
34
  export type { User, Impersonator, Organization, WorkOS, AuthenticationResponse, } from '@workos-inc/node';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAKH,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AACvD,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAKzD,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACpD,OAAO,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AAKhE,OAAO,EAAE,oBAAoB,EAAE,MAAM,wCAAwC,CAAC;AAK9E,OAAO,EAAE,OAAO,IAAI,iBAAiB,EAAE,MAAM,8CAA8C,CAAC;AAK5F,OAAO,EACL,SAAS,EACT,SAAS,EACT,wBAAwB,EACxB,cAAc,GACf,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,qBAAqB,EAAE,MAAM,wCAAwC,CAAC;AAK/E,OAAO,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AAKpD,cAAc,yBAAyB,CAAC;AACxC,cAAc,wBAAwB,CAAC;AACvC,YAAY,EACV,IAAI,EACJ,YAAY,EACZ,YAAY,EACZ,MAAM,EACN,sBAAsB,GACvB,MAAM,kBAAkB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAKH,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AACvD,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAKzD,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACpD,OAAO,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AAKhE,OAAO,EAAE,oBAAoB,EAAE,MAAM,wCAAwC,CAAC;AAK9E,OAAO,EAAE,OAAO,IAAI,iBAAiB,EAAE,MAAM,8CAA8C,CAAC;AAK5F,OAAO,EACL,SAAS,EACT,SAAS,EACT,wBAAwB,EACxB,cAAc,GACf,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,qBAAqB,EAAE,MAAM,wCAAwC,CAAC;AAK/E,OAAO,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AAKpD,OAAO,EACL,YAAY,EACZ,sBAAsB,EACtB,oBAAoB,EACpB,iBAAiB,GAClB,MAAM,kBAAkB,CAAC;AAK1B,cAAc,yBAAyB,CAAC;AACxC,cAAc,wBAAwB,CAAC;AACvC,YAAY,EACV,IAAI,EACJ,YAAY,EACZ,YAAY,EACZ,MAAM,EACN,sBAAsB,GACvB,MAAM,kBAAkB,CAAC"}
package/dist/index.js CHANGED
@@ -47,6 +47,10 @@ export { ConfigurationProvider } from './core/config/ConfigurationProvider.js';
47
47
  // ============================================
48
48
  export { getWorkOS } from './core/client/workos.js';
49
49
  // ============================================
50
+ // Errors
51
+ // ============================================
52
+ export { AuthKitError, SessionEncryptionError, TokenValidationError, TokenRefreshError, } from './core/errors.js';
53
+ // ============================================
50
54
  // Type Exports
51
55
  // ============================================
52
56
  export * from './core/session/types.js';
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,+CAA+C;AAC/C,aAAa;AACb,+CAA+C;AAC/C,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AACvD,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAEzD,+CAA+C;AAC/C,6BAA6B;AAC7B,+CAA+C;AAC/C,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACpD,OAAO,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AAEhE,+CAA+C;AAC/C,kBAAkB;AAClB,+CAA+C;AAC/C,OAAO,EAAE,oBAAoB,EAAE,MAAM,wCAAwC,CAAC;AAE9E,+CAA+C;AAC/C,sBAAsB;AACtB,+CAA+C;AAC/C,OAAO,EAAE,OAAO,IAAI,iBAAiB,EAAE,MAAM,8CAA8C,CAAC;AAE5F,+CAA+C;AAC/C,gBAAgB;AAChB,+CAA+C;AAC/C,OAAO,EACL,SAAS,EACT,SAAS,EACT,wBAAwB,EACxB,cAAc,GACf,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,qBAAqB,EAAE,MAAM,wCAAwC,CAAC;AAE/E,+CAA+C;AAC/C,iBAAiB;AACjB,+CAA+C;AAC/C,OAAO,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AAEpD,+CAA+C;AAC/C,eAAe;AACf,+CAA+C;AAC/C,cAAc,yBAAyB,CAAC;AACxC,cAAc,wBAAwB,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,+CAA+C;AAC/C,aAAa;AACb,+CAA+C;AAC/C,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AACvD,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAEzD,+CAA+C;AAC/C,6BAA6B;AAC7B,+CAA+C;AAC/C,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACpD,OAAO,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AAEhE,+CAA+C;AAC/C,kBAAkB;AAClB,+CAA+C;AAC/C,OAAO,EAAE,oBAAoB,EAAE,MAAM,wCAAwC,CAAC;AAE9E,+CAA+C;AAC/C,sBAAsB;AACtB,+CAA+C;AAC/C,OAAO,EAAE,OAAO,IAAI,iBAAiB,EAAE,MAAM,8CAA8C,CAAC;AAE5F,+CAA+C;AAC/C,gBAAgB;AAChB,+CAA+C;AAC/C,OAAO,EACL,SAAS,EACT,SAAS,EACT,wBAAwB,EACxB,cAAc,GACf,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,qBAAqB,EAAE,MAAM,wCAAwC,CAAC;AAE/E,+CAA+C;AAC/C,iBAAiB;AACjB,+CAA+C;AAC/C,OAAO,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AAEpD,+CAA+C;AAC/C,SAAS;AACT,+CAA+C;AAC/C,OAAO,EACL,YAAY,EACZ,sBAAsB,EACtB,oBAAoB,EACpB,iBAAiB,GAClB,MAAM,kBAAkB,CAAC;AAE1B,+CAA+C;AAC/C,eAAe;AACf,+CAA+C;AAC/C,cAAc,yBAAyB,CAAC;AACxC,cAAc,wBAAwB,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@workos/authkit-session",
3
- "version": "0.2.0",
3
+ "version": "0.3.1",
4
4
  "description": "Framework-agnostic authentication library for WorkOS with pluggable storage adapters",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -36,7 +36,6 @@
36
36
  },
37
37
  "dependencies": {
38
38
  "@workos-inc/node": "^8.0.0-rc.3",
39
- "iron-session": "^8.0.4",
40
39
  "iron-webcrypto": "^1.2.1",
41
40
  "jose": "^6.1.2"
42
41
  },
@@ -152,12 +152,14 @@ export class AuthKitCore {
152
152
  *
153
153
  * @param refreshToken - The refresh token
154
154
  * @param organizationId - Optional organization ID to switch to
155
+ * @param context - Optional context for error reporting (userId, sessionId)
155
156
  * @returns New access token, refresh token, user, and impersonator
156
157
  * @throws TokenRefreshError if refresh fails
157
158
  */
158
159
  async refreshTokens(
159
160
  refreshToken: string,
160
161
  organizationId?: string,
162
+ context?: { userId?: string; sessionId?: string },
161
163
  ): Promise<{
162
164
  accessToken: string;
163
165
  refreshToken: string;
@@ -179,7 +181,7 @@ export class AuthKitCore {
179
181
  impersonator: result.impersonator,
180
182
  };
181
183
  } catch (error) {
182
- throw new TokenRefreshError('Failed to refresh tokens', error);
184
+ throw new TokenRefreshError('Failed to refresh tokens', error, context);
183
185
  }
184
186
  }
185
187
 
@@ -226,9 +228,18 @@ export class AuthKitCore {
226
228
  }
227
229
  }
228
230
 
231
+ // Extract session ID for error context (works on expired tokens too)
232
+ let sessionId: string | undefined;
233
+ try {
234
+ sessionId = this.parseTokenClaims(accessToken).sid;
235
+ } catch {
236
+ // Token parsing failed - continue without session context
237
+ }
238
+
229
239
  const newSession = await this.refreshTokens(
230
240
  session.refreshToken,
231
241
  organizationId,
242
+ { userId: session.user?.id, sessionId },
232
243
  );
233
244
  const newClaims = this.parseTokenClaims<TCustomClaims>(
234
245
  newSession.accessToken,
@@ -1,82 +1,32 @@
1
- import {
2
- sealData as ironSessionSeal,
3
- unsealData as ironSessionUnseal,
4
- } from 'iron-session';
5
1
  import { SessionEncryption } from './ironWebcryptoEncryption.js';
6
- import ironSessionEncryption from './ironSessionEncryption.js';
7
2
 
8
3
  const testPassword = 'this-is-a-test-password-that-is-32-characters-long!';
9
4
  const testData = {
10
5
  userId: '123',
11
6
  email: 'test@example.com',
12
- timestamp: Date.now(),
13
7
  };
14
8
 
15
9
  describe('ironWebcryptoEncryption', () => {
16
10
  const encryption = new SessionEncryption();
17
11
 
18
- describe('cross-compatibility with iron-session', () => {
19
- it('can unseal data sealed by iron-session', async () => {
20
- const sealed = await ironSessionSeal(testData, {
21
- password: testPassword,
22
- });
23
-
24
- const unsealed = await encryption.unsealData(sealed, {
25
- password: testPassword,
26
- });
27
-
28
- expect(unsealed).toEqual(testData);
29
- });
30
-
31
- it('produces data that iron-session can unseal', async () => {
32
- const sealed = await encryption.sealData(testData, {
33
- password: testPassword,
34
- });
35
-
36
- const unsealed = await ironSessionUnseal(sealed, {
37
- password: testPassword,
38
- });
39
-
40
- expect(unsealed).toEqual(testData);
41
- });
42
-
43
- it('handles version 2 tokens correctly', async () => {
12
+ describe('seal/unseal', () => {
13
+ it('round-trips data correctly', async () => {
44
14
  const sealed = await encryption.sealData(testData, {
45
15
  password: testPassword,
46
16
  });
47
-
48
- expect(sealed).toMatch(/~2$/);
49
-
50
17
  const unsealed = await encryption.unsealData(sealed, {
51
18
  password: testPassword,
52
19
  });
53
- expect(unsealed).toEqual(testData);
54
- });
55
-
56
- it('handles legacy tokens without version', async () => {
57
- const legacySealed = await ironSessionSeal(testData, {
58
- password: testPassword,
59
- });
60
- const sealWithoutVersion = legacySealed.split('~')[0]!;
61
-
62
- const unsealed = await encryption.unsealData(sealWithoutVersion, {
63
- password: testPassword,
64
- });
65
20
 
66
21
  expect(unsealed).toEqual(testData);
67
22
  });
68
- });
69
23
 
70
- describe('basic functionality', () => {
71
- it('seals and unseals data correctly', async () => {
24
+ it('produces version 2 tokens', async () => {
72
25
  const sealed = await encryption.sealData(testData, {
73
26
  password: testPassword,
74
27
  });
75
- const unsealed = await encryption.unsealData(sealed, {
76
- password: testPassword,
77
- });
78
28
 
79
- expect(unsealed).toEqual(testData);
29
+ expect(sealed).toMatch(/~2$/);
80
30
  });
81
31
 
82
32
  it('handles TTL parameter', async () => {
@@ -99,27 +49,15 @@ describe('ironWebcryptoEncryption', () => {
99
49
  encryption.unsealData(sealed, { password: wrongPassword }),
100
50
  ).rejects.toThrow();
101
51
  });
102
- });
103
-
104
- describe('compatibility with ironSessionEncryption export', () => {
105
- it('can unseal data sealed by ironSessionEncryption', async () => {
106
- const sealed = await ironSessionEncryption.sealData(testData, {
107
- password: testPassword,
108
- });
109
-
110
- const unsealed = await encryption.unsealData(sealed, {
111
- password: testPassword,
112
- });
113
-
114
- expect(unsealed).toEqual(testData);
115
- });
116
52
 
117
- it('produces data that ironSessionEncryption can unseal', async () => {
53
+ it('unseals tokens without version suffix (v1 format)', async () => {
118
54
  const sealed = await encryption.sealData(testData, {
119
55
  password: testPassword,
120
56
  });
57
+ // Strip the ~2 version suffix to simulate legacy token
58
+ const legacySealed = sealed.replace(/~2$/, '');
121
59
 
122
- const unsealed = await ironSessionEncryption.unsealData(sealed, {
60
+ const unsealed = await encryption.unsealData(legacySealed, {
123
61
  password: testPassword,
124
62
  });
125
63
 
@@ -93,6 +93,53 @@ describe('TokenRefreshError', () => {
93
93
 
94
94
  expect(error.cause).toBe(originalError);
95
95
  });
96
+
97
+ it('creates error with userId and sessionId', () => {
98
+ const error = new TokenRefreshError('Refresh failed', undefined, {
99
+ userId: 'user_123',
100
+ sessionId: 'session_456',
101
+ });
102
+
103
+ expect(error.userId).toBe('user_123');
104
+ expect(error.sessionId).toBe('session_456');
105
+ });
106
+
107
+ it('creates error with cause and context', () => {
108
+ const originalError = new Error('Network error');
109
+ const error = new TokenRefreshError('Refresh failed', originalError, {
110
+ userId: 'user_123',
111
+ sessionId: 'session_456',
112
+ });
113
+
114
+ expect(error.cause).toBe(originalError);
115
+ expect(error.userId).toBe('user_123');
116
+ expect(error.sessionId).toBe('session_456');
117
+ });
118
+
119
+ it('creates error with partial context (userId only)', () => {
120
+ const error = new TokenRefreshError('Refresh failed', undefined, {
121
+ userId: 'user_123',
122
+ });
123
+
124
+ expect(error.userId).toBe('user_123');
125
+ expect(error.sessionId).toBeUndefined();
126
+ });
127
+
128
+ it('creates error with partial context (sessionId only)', () => {
129
+ const error = new TokenRefreshError('Refresh failed', undefined, {
130
+ sessionId: 'session_456',
131
+ });
132
+
133
+ expect(error.userId).toBeUndefined();
134
+ expect(error.sessionId).toBe('session_456');
135
+ });
136
+
137
+ it('has undefined properties when no context provided', () => {
138
+ const error = new TokenRefreshError('Refresh failed');
139
+
140
+ expect(error.userId).toBeUndefined();
141
+ expect(error.sessionId).toBeUndefined();
142
+ });
96
143
  });
97
144
 
98
145
  describe('error inheritance', () => {
@@ -24,8 +24,17 @@ export class TokenValidationError extends AuthKitError {
24
24
  }
25
25
 
26
26
  export class TokenRefreshError extends AuthKitError {
27
- constructor(message: string, cause?: unknown) {
27
+ readonly userId?: string;
28
+ readonly sessionId?: string;
29
+
30
+ constructor(
31
+ message: string,
32
+ cause?: unknown,
33
+ context?: { userId?: string; sessionId?: string },
34
+ ) {
28
35
  super(message, cause);
29
36
  this.name = 'TokenRefreshError';
37
+ this.userId = context?.userId;
38
+ this.sessionId = context?.sessionId;
30
39
  }
31
40
  }
package/src/index.ts CHANGED
@@ -58,6 +58,16 @@ export { ConfigurationProvider } from './core/config/ConfigurationProvider.js';
58
58
  // ============================================
59
59
  export { getWorkOS } from './core/client/workos.js';
60
60
 
61
+ // ============================================
62
+ // Errors
63
+ // ============================================
64
+ export {
65
+ AuthKitError,
66
+ SessionEncryptionError,
67
+ TokenValidationError,
68
+ TokenRefreshError,
69
+ } from './core/errors.js';
70
+
61
71
  // ============================================
62
72
  // Type Exports
63
73
  // ============================================
@@ -1,16 +0,0 @@
1
- declare const _default: {
2
- sealData: (data: unknown, { password, ttl, }: {
3
- password: string | {
4
- [x: string]: string;
5
- };
6
- ttl?: number;
7
- }) => Promise<string>;
8
- unsealData: <T>(seal: string, { password, ttl, }: {
9
- password: string | {
10
- [x: string]: string;
11
- };
12
- ttl?: number;
13
- }) => Promise<T>;
14
- };
15
- export default _default;
16
- //# sourceMappingURL=ironSessionEncryption.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"ironSessionEncryption.d.ts","sourceRoot":"","sources":["../../../src/core/encryption/ironSessionEncryption.ts"],"names":[],"mappings":";;;;;WAMi1G,CAAC;;;;;;WAAuK,CAAC;;;AAJ1/G,wBAGE"}
@@ -1,6 +0,0 @@
1
- import { sealData, unsealData } from 'iron-session';
2
- export default {
3
- sealData,
4
- unsealData,
5
- };
6
- //# sourceMappingURL=ironSessionEncryption.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"ironSessionEncryption.js","sourceRoot":"","sources":["../../../src/core/encryption/ironSessionEncryption.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAEpD,eAAe;IACb,QAAQ;IACR,UAAU;CACX,CAAC"}
@@ -1,29 +0,0 @@
1
- import type { SessionEncryption as SessionEncryptionInterface } from '../session/types.js';
2
- /**
3
- * Pure WebCrypto implementation compatible with iron-session
4
- * Based on reverse-engineered iron-session format (Fe26.2)
5
- */
6
- export declare class PureWebcryptoEncryption implements SessionEncryptionInterface {
7
- private readonly versionDelimiter;
8
- private readonly currentMajorVersion;
9
- private parseSeal;
10
- private base64urlToBytes;
11
- private bytesToBase64url;
12
- private bytesToHex;
13
- private generateRandomBytes;
14
- private deriveKeyBits;
15
- private parseLegacyFormat;
16
- private decryptLegacyData;
17
- private encryptLegacyData;
18
- private signSealedData;
19
- sealData(data: unknown, { password, ttl }: {
20
- password: string;
21
- ttl?: number | undefined;
22
- }): Promise<string>;
23
- unsealData<T = unknown>(encryptedData: string, { password }: {
24
- password: string;
25
- }): Promise<T>;
26
- }
27
- declare const pureWebcryptoEncryption: PureWebcryptoEncryption;
28
- export default pureWebcryptoEncryption;
29
- //# sourceMappingURL=pureWebcryptoEncryption.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"pureWebcryptoEncryption.d.ts","sourceRoot":"","sources":["../../../src/core/encryption/pureWebcryptoEncryption.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,IAAI,0BAA0B,EAAE,MAAM,qBAAqB,CAAC;AAE3F;;;GAGG;AACH,qBAAa,uBAAwB,YAAW,0BAA0B;IACxE,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAAO;IACxC,OAAO,CAAC,QAAQ,CAAC,mBAAmB,CAAK;IAGzC,OAAO,CAAC,SAAS;IAajB,OAAO,CAAC,gBAAgB;IAYxB,OAAO,CAAC,gBAAgB;IAKxB,OAAO,CAAC,UAAU;IAMlB,OAAO,CAAC,mBAAmB;YAKb,aAAa;IAiC3B,OAAO,CAAC,iBAAiB;YAmCX,iBAAiB;YAwCjB,iBAAiB;YAqCjB,cAAc;IAsCtB,QAAQ,CACZ,IAAI,EAAE,OAAO,EACb,EAAE,QAAQ,EAAE,GAAO,EAAE,EAAE;QAAE,QAAQ,EAAE,MAAM,CAAC;QAAC,GAAG,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;KAAE,GACpE,OAAO,CAAC,MAAM,CAAC;IAmDZ,UAAU,CAAC,CAAC,GAAG,OAAO,EAC1B,aAAa,EAAE,MAAM,EACrB,EAAE,QAAQ,EAAE,EAAE;QAAE,QAAQ,EAAE,MAAM,CAAA;KAAE,GACjC,OAAO,CAAC,CAAC,CAAC;CA0Cd;AAED,QAAA,MAAM,uBAAuB,yBAAgC,CAAC;AAE9D,eAAe,uBAAuB,CAAC"}
@@ -1,182 +0,0 @@
1
- /**
2
- * Pure WebCrypto implementation compatible with iron-session
3
- * Based on reverse-engineered iron-session format (Fe26.2)
4
- */
5
- export class PureWebcryptoEncryption {
6
- versionDelimiter = '~';
7
- currentMajorVersion = 2;
8
- // Parse version from sealed data
9
- parseSeal(seal) {
10
- const [sealWithoutVersion = '', tokenVersionAsString] = seal.split(this.versionDelimiter);
11
- const tokenVersion = tokenVersionAsString == null ? null : parseInt(tokenVersionAsString, 10);
12
- return { sealWithoutVersion, tokenVersion };
13
- }
14
- // Base64url utilities
15
- base64urlToBytes(base64url) {
16
- const base64 = base64url.replace(/-/g, '+').replace(/_/g, '/') +
17
- '='.repeat((4 - (base64url.length % 4)) % 4);
18
- const binaryString = atob(base64);
19
- const bytes = new Uint8Array(binaryString.length);
20
- for (let i = 0; i < binaryString.length; i++) {
21
- bytes[i] = binaryString.charCodeAt(i);
22
- }
23
- return bytes;
24
- }
25
- bytesToBase64url(bytes) {
26
- const base64 = btoa(String.fromCharCode.apply(null, Array.from(bytes)));
27
- return base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
28
- }
29
- bytesToHex(bytes) {
30
- return Array.from(bytes)
31
- .map(b => b.toString(16).padStart(2, '0'))
32
- .join('');
33
- }
34
- generateRandomBytes(length) {
35
- return globalThis.crypto.getRandomValues(new Uint8Array(length));
36
- }
37
- // Key derivation using PBKDF2 (iron-session compatible)
38
- async deriveKeyBits(options) {
39
- const keyMaterial = await globalThis.crypto.subtle.importKey('raw', new TextEncoder().encode(options.password), 'PBKDF2', false, ['deriveBits']);
40
- const saltBytes = typeof options.salt === 'string'
41
- ? new TextEncoder().encode(options.salt)
42
- : options.salt;
43
- return globalThis.crypto.subtle.deriveBits({
44
- name: 'PBKDF2',
45
- salt: saltBytes,
46
- iterations: options.iterations,
47
- hash: options.hashAlgorithm,
48
- }, keyMaterial, options.keyLength);
49
- }
50
- // Parse iron-session legacy format (Fe26.2)
51
- parseLegacyFormat(sealWithoutVersion) {
52
- const parts = sealWithoutVersion.split('*');
53
- if (parts.length < 6 || !parts[0]?.startsWith('Fe26.2')) {
54
- throw new Error('Invalid legacy sealed data format');
55
- }
56
- const [, , encryptionSalt, encryptionIv, encryptedB64, expiration, hmacSalt, signature,] = parts;
57
- return {
58
- encryptionSalt: encryptionSalt,
59
- encryptionIv: encryptionIv,
60
- encryptedB64: encryptedB64,
61
- expiration,
62
- hmacSalt,
63
- signature,
64
- };
65
- }
66
- // Decrypt legacy data using AES-CBC
67
- async decryptLegacyData(encryptedB64, encryptionIv, encryptionSalt, password) {
68
- const encryptedBuffer = this.base64urlToBytes(encryptedB64);
69
- const ivBuffer = this.base64urlToBytes(encryptionIv);
70
- // Derive decryption key using iron-session parameters
71
- const keyBits = await this.deriveKeyBits({
72
- password,
73
- salt: encryptionSalt,
74
- iterations: 1,
75
- hashAlgorithm: 'SHA-1',
76
- keyLength: 256,
77
- });
78
- const encryptionKey = await globalThis.crypto.subtle.importKey('raw', keyBits, { name: 'AES-CBC' }, false, ['decrypt']);
79
- // Decrypt using AES-256-CBC
80
- const decryptedBuffer = await globalThis.crypto.subtle.decrypt({
81
- name: 'AES-CBC',
82
- iv: ivBuffer,
83
- }, encryptionKey, encryptedBuffer);
84
- return new TextDecoder().decode(decryptedBuffer);
85
- }
86
- // Encrypt data using AES-CBC
87
- async encryptLegacyData(jsonString, encryptionIv, encryptionSalt, password) {
88
- // Derive encryption key using iron-session parameters
89
- const keyBits = await this.deriveKeyBits({
90
- password,
91
- salt: encryptionSalt,
92
- iterations: 1,
93
- hashAlgorithm: 'SHA-1',
94
- keyLength: 256,
95
- });
96
- const encryptionKey = await globalThis.crypto.subtle.importKey('raw', keyBits, { name: 'AES-CBC' }, false, ['encrypt']);
97
- // Encrypt the JSON string
98
- const encryptedBuffer = await globalThis.crypto.subtle.encrypt({
99
- name: 'AES-CBC',
100
- iv: encryptionIv,
101
- }, encryptionKey, new TextEncoder().encode(jsonString));
102
- return this.bytesToBase64url(new Uint8Array(encryptedBuffer));
103
- }
104
- // Create HMAC signature for iron-session format
105
- async signSealedData(encryptionSaltHex, encryptionIvB64, encryptedB64, hmacSaltHex, expiration, password) {
106
- // Create the unsigned data for HMAC
107
- const unsignedData = `Fe26.2*1*${encryptionSaltHex}*${encryptionIvB64}*${encryptedB64}*${expiration}`;
108
- // Derive HMAC key
109
- const hmacKeyBits = await this.deriveKeyBits({
110
- password,
111
- salt: hmacSaltHex,
112
- iterations: 1,
113
- hashAlgorithm: 'SHA-1',
114
- keyLength: 256,
115
- });
116
- const hmacKey = await globalThis.crypto.subtle.importKey('raw', hmacKeyBits, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
117
- // Calculate HMAC signature
118
- const signature = await globalThis.crypto.subtle.sign('HMAC', hmacKey, new TextEncoder().encode(unsignedData));
119
- return this.bytesToBase64url(new Uint8Array(signature));
120
- }
121
- async sealData(data, { password, ttl = 0 }) {
122
- if (password.length < 32) {
123
- throw new Error('Password must be at least 32 characters long');
124
- }
125
- const jsonString = JSON.stringify(data);
126
- // Generate encryption components (matching iron-session)
127
- const encryptionSalt = this.generateRandomBytes(32);
128
- const hmacSalt = this.generateRandomBytes(32);
129
- const encryptionIv = this.generateRandomBytes(16);
130
- // Convert salts to hex (iron-session format)
131
- const encryptionSaltHex = this.bytesToHex(encryptionSalt);
132
- const hmacSaltHex = this.bytesToHex(hmacSalt);
133
- // Encrypt the session data
134
- const encryptedB64 = await this.encryptLegacyData(jsonString, encryptionIv, encryptionSaltHex, password);
135
- const encryptionIvB64 = this.bytesToBase64url(encryptionIv);
136
- // Calculate expiration (iron-session uses milliseconds)
137
- const expiration = ttl > 0
138
- ? Date.now() + ttl * 1000
139
- : ttl < 0
140
- ? Date.now() + ttl * 1000
141
- : Date.now() + 24 * 60 * 60 * 1000;
142
- // Sign the sealed data
143
- const signatureB64 = await this.signSealedData(encryptionSaltHex, encryptionIvB64, encryptedB64, hmacSaltHex, expiration, password);
144
- // Build iron-session format string (Fe26.2)
145
- const sealed = `Fe26.2*1*${encryptionSaltHex}*${encryptionIvB64}*${encryptedB64}*${expiration}*${hmacSaltHex}*${signatureB64}`;
146
- // Add version suffix for compatibility
147
- return `${sealed}${this.versionDelimiter}${this.currentMajorVersion}`;
148
- }
149
- async unsealData(encryptedData, { password }) {
150
- if (password.length < 32) {
151
- throw new Error('Password must be at least 32 characters long');
152
- }
153
- // Parse version
154
- const { sealWithoutVersion, tokenVersion } = this.parseSeal(encryptedData);
155
- // Parse iron-session legacy format
156
- const { encryptionSalt, encryptionIv, encryptedB64, expiration } = this.parseLegacyFormat(sealWithoutVersion);
157
- // Check expiration if present
158
- if (expiration) {
159
- const expirationTime = parseInt(expiration, 10);
160
- if (Date.now() > expirationTime) {
161
- throw new Error('Sealed data has expired');
162
- }
163
- }
164
- // Decrypt the data
165
- const decryptedText = await this.decryptLegacyData(encryptedB64, encryptionIv, encryptionSalt, password);
166
- // Parse the JSON data
167
- const sessionData = JSON.parse(decryptedText);
168
- // Handle version-specific extraction (matching iron-session behavior)
169
- if (tokenVersion === 2) {
170
- return sessionData;
171
- }
172
- else if (tokenVersion !== null && tokenVersion !== 2) {
173
- // For older token versions, extract the persistent property
174
- return { ...sessionData.persistent };
175
- }
176
- // No version info - return as-is
177
- return sessionData;
178
- }
179
- }
180
- const pureWebcryptoEncryption = new PureWebcryptoEncryption();
181
- export default pureWebcryptoEncryption;
182
- //# sourceMappingURL=pureWebcryptoEncryption.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"pureWebcryptoEncryption.js","sourceRoot":"","sources":["../../../src/core/encryption/pureWebcryptoEncryption.ts"],"names":[],"mappings":"AAEA;;;GAGG;AACH,MAAM,OAAO,uBAAuB;IACjB,gBAAgB,GAAG,GAAG,CAAC;IACvB,mBAAmB,GAAG,CAAC,CAAC;IAEzC,iCAAiC;IACzB,SAAS,CAAC,IAAY;QAI5B,MAAM,CAAC,kBAAkB,GAAG,EAAE,EAAE,oBAAoB,CAAC,GAAG,IAAI,CAAC,KAAK,CAChE,IAAI,CAAC,gBAAgB,CACtB,CAAC;QACF,MAAM,YAAY,GAChB,oBAAoB,IAAI,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,QAAQ,CAAC,oBAAoB,EAAE,EAAE,CAAC,CAAC;QAC3E,OAAO,EAAE,kBAAkB,EAAE,YAAY,EAAE,CAAC;IAC9C,CAAC;IAED,sBAAsB;IACd,gBAAgB,CAAC,SAAiB;QACxC,MAAM,MAAM,GACV,SAAS,CAAC,OAAO,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C;QAEF,sBAAsB;QACtB,MAAM,WAAW,GAAG,IAAI,CAAC,KAAK,CAAC,aAAa,CAAC,CAAC;QAE9C,sEAAsE;QACtE,IAAI,YAAY,KAAK,CAAC,EAAE,CAAC;YACvB,OAAO,WAAgB,CAAC;QAC1B,CAAC;aAAM,IAAI,YAAY,KAAK,IAAI,IAAI,YAAY,KAAK,CAAC,EAAE,CAAC;YACvD,4DAA4D;YAC5D,OAAO,EAAE,GAAI,WAAmB,CAAC,UAAU,EAAO,CAAC;QACrD,CAAC;QAED,iCAAiC;QACjC,OAAO,WAAgB,CAAC;IAC1B,CAAC;CACF;AAED,MAAM,uBAAuB,GAAG,IAAI,uBAAuB,EAAE,CAAC;AAE9D,eAAe,uBAAuB,CAAC"}
@@ -1,6 +0,0 @@
1
- import { sealData, unsealData } from 'iron-session';
2
-
3
- export default {
4
- sealData,
5
- unsealData,
6
- };
@@ -1,177 +0,0 @@
1
- import {
2
- sealData as ironSessionSeal,
3
- unsealData as ironSessionUnseal,
4
- } from 'iron-session';
5
- import { PureWebcryptoEncryption } from './pureWebcryptoEncryption.js';
6
-
7
- const testPassword = 'this-is-a-test-password-that-is-32-characters-long!';
8
- const testData = {
9
- userId: '123',
10
- email: 'test@example.com',
11
- timestamp: Date.now(),
12
- };
13
-
14
- describe('pureWebcryptoEncryption', () => {
15
- const pureEncryption = new PureWebcryptoEncryption();
16
-
17
- describe('cross-compatibility with iron-session', () => {
18
- it('can unseal data sealed by iron-session', async () => {
19
- const sealed = await ironSessionSeal(testData, {
20
- password: testPassword,
21
- });
22
-
23
- const unsealed = await pureEncryption.unsealData(sealed, {
24
- password: testPassword,
25
- });
26
-
27
- expect(unsealed).toEqual(testData);
28
- });
29
-
30
- it('produces data that iron-session can unseal', async () => {
31
- const sealed = await pureEncryption.sealData(testData, {
32
- password: testPassword,
33
- });
34
-
35
- const unsealed = await ironSessionUnseal(sealed, {
36
- password: testPassword,
37
- });
38
-
39
- expect(unsealed).toEqual(testData);
40
- });
41
-
42
- it('handles version 2 tokens correctly', async () => {
43
- const sealed = await pureEncryption.sealData(testData, {
44
- password: testPassword,
45
- });
46
-
47
- expect(sealed).toMatch(/~2$/);
48
-
49
- const unsealed = await pureEncryption.unsealData(sealed, {
50
- password: testPassword,
51
- });
52
- expect(unsealed).toEqual(testData);
53
- });
54
-
55
- it('handles legacy tokens without version', async () => {
56
- const legacySealed = await ironSessionSeal(testData, {
57
- password: testPassword,
58
- });
59
- const sealWithoutVersion = legacySealed.split('~')[0]!;
60
-
61
- const unsealed = await pureEncryption.unsealData(sealWithoutVersion, {
62
- password: testPassword,
63
- });
64
-
65
- expect(unsealed).toEqual(testData);
66
- });
67
- });
68
-
69
- describe('basic functionality', () => {
70
- it('seals and unseals data correctly', async () => {
71
- const sealed = await pureEncryption.sealData(testData, {
72
- password: testPassword,
73
- });
74
- const unsealed = await pureEncryption.unsealData(sealed, {
75
- password: testPassword,
76
- });
77
-
78
- expect(unsealed).toEqual(testData);
79
- });
80
-
81
- it('handles TTL parameter', async () => {
82
- const sealed = await pureEncryption.sealData(testData, {
83
- password: testPassword,
84
- ttl: 3600,
85
- });
86
-
87
- expect(sealed).toBeDefined();
88
- expect(typeof sealed).toBe('string');
89
- expect(sealed).toMatch(/^Fe26\.2\*/); // Should use iron-session format
90
- });
91
-
92
- it('fails with wrong password', async () => {
93
- const sealed = await pureEncryption.sealData(testData, {
94
- password: testPassword,
95
- });
96
- const wrongPassword = 'wrong-password-that-is-32-chars!!';
97
-
98
- await expect(
99
- pureEncryption.unsealData(sealed, { password: wrongPassword }),
100
- ).rejects.toThrow();
101
- });
102
-
103
- it('enforces minimum password length', async () => {
104
- const shortPassword = 'short';
105
-
106
- await expect(
107
- pureEncryption.sealData(testData, { password: shortPassword }),
108
- ).rejects.toThrow('Password must be at least 32 characters long');
109
-
110
- await expect(
111
- pureEncryption.unsealData('fake-seal', { password: shortPassword }),
112
- ).rejects.toThrow('Password must be at least 32 characters long');
113
- });
114
-
115
- it('handles TTL expiration', async () => {
116
- const sealed = await pureEncryption.sealData(testData, {
117
- password: testPassword,
118
- ttl: -1, // Already expired
119
- });
120
-
121
- await expect(
122
- pureEncryption.unsealData(sealed, { password: testPassword }),
123
- ).rejects.toThrow('Sealed data has expired');
124
- });
125
-
126
- it('produces iron-session compatible format', async () => {
127
- const sealed = await pureEncryption.sealData(testData, {
128
- password: testPassword,
129
- });
130
-
131
- // Should start with Fe26.2 (iron-session format)
132
- expect(sealed).toMatch(/^Fe26\.2\*/);
133
-
134
- // Should end with ~2 (version delimiter)
135
- expect(sealed).toMatch(/~2$/);
136
-
137
- // Should have the correct number of parts when split by *
138
- const withoutVersion = sealed.split('~')[0]!;
139
- const parts = withoutVersion.split('*');
140
- expect(parts).toHaveLength(8); // Fe26.2 format has 8 parts
141
- });
142
-
143
- it('handles complex data structures', async () => {
144
- const complexData = {
145
- user: {
146
- id: '123',
147
- profile: {
148
- name: 'Test User',
149
- preferences: {
150
- theme: 'dark',
151
- notifications: true,
152
- },
153
- },
154
- },
155
- session: {
156
- id: 'sess_123',
157
- createdAt: new Date().toISOString(),
158
- metadata: {
159
- userAgent: 'Mozilla/5.0',
160
- ip: '192.168.1.1',
161
- },
162
- },
163
- permissions: ['read', 'write', 'admin'],
164
- };
165
-
166
- const sealed = await pureEncryption.sealData(complexData, {
167
- password: testPassword,
168
- });
169
-
170
- const unsealed = await pureEncryption.unsealData(sealed, {
171
- password: testPassword,
172
- });
173
-
174
- expect(unsealed).toEqual(complexData);
175
- });
176
- });
177
- });
@@ -1,339 +0,0 @@
1
- import type { SessionEncryption as SessionEncryptionInterface } from '../session/types.js';
2
-
3
- /**
4
- * Pure WebCrypto implementation compatible with iron-session
5
- * Based on reverse-engineered iron-session format (Fe26.2)
6
- */
7
- export class PureWebcryptoEncryption implements SessionEncryptionInterface {
8
- private readonly versionDelimiter = '~';
9
- private readonly currentMajorVersion = 2;
10
-
11
- // Parse version from sealed data
12
- private parseSeal(seal: string): {
13
- sealWithoutVersion: string;
14
- tokenVersion: number | null;
15
- } {
16
- const [sealWithoutVersion = '', tokenVersionAsString] = seal.split(
17
- this.versionDelimiter,
18
- );
19
- const tokenVersion =
20
- tokenVersionAsString == null ? null : parseInt(tokenVersionAsString, 10);
21
- return { sealWithoutVersion, tokenVersion };
22
- }
23
-
24
- // Base64url utilities
25
- private base64urlToBytes(base64url: string): Uint8Array {
26
- const base64 =
27
- base64url.replace(/-/g, '+').replace(/_/g, '/') +
28
- '='.repeat((4 - (base64url.length % 4)) % 4);
29
- const binaryString = atob(base64);
30
- const bytes = new Uint8Array(binaryString.length);
31
- for (let i = 0; i < binaryString.length; i++) {
32
- bytes[i] = binaryString.charCodeAt(i);
33
- }
34
- return bytes;
35
- }
36
-
37
- private bytesToBase64url(bytes: Uint8Array): string {
38
- const base64 = btoa(String.fromCharCode.apply(null, Array.from(bytes)));
39
- return base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
40
- }
41
-
42
- private bytesToHex(bytes: Uint8Array): string {
43
- return Array.from(bytes)
44
- .map(b => b.toString(16).padStart(2, '0'))
45
- .join('');
46
- }
47
-
48
- private generateRandomBytes(length: number): Uint8Array {
49
- return globalThis.crypto.getRandomValues(new Uint8Array(length));
50
- }
51
-
52
- // Key derivation using PBKDF2 (iron-session compatible)
53
- private async deriveKeyBits(options: {
54
- password: string;
55
- salt: string | Uint8Array;
56
- iterations: number;
57
- hashAlgorithm: string;
58
- keyLength: number;
59
- }): Promise<ArrayBuffer> {
60
- const keyMaterial = await globalThis.crypto.subtle.importKey(
61
- 'raw',
62
- new TextEncoder().encode(options.password),
63
- 'PBKDF2',
64
- false,
65
- ['deriveBits'],
66
- );
67
-
68
- const saltBytes =
69
- typeof options.salt === 'string'
70
- ? new TextEncoder().encode(options.salt)
71
- : options.salt;
72
-
73
- return globalThis.crypto.subtle.deriveBits(
74
- {
75
- name: 'PBKDF2',
76
- salt: saltBytes as BufferSource,
77
- iterations: options.iterations,
78
- hash: options.hashAlgorithm,
79
- },
80
- keyMaterial,
81
- options.keyLength,
82
- );
83
- }
84
-
85
- // Parse iron-session legacy format (Fe26.2)
86
- private parseLegacyFormat(sealWithoutVersion: string): {
87
- encryptionSalt: string;
88
- encryptionIv: string;
89
- encryptedB64: string;
90
- expiration?: string;
91
- hmacSalt?: string;
92
- signature?: string;
93
- } {
94
- const parts = sealWithoutVersion.split('*');
95
-
96
- if (parts.length < 6 || !parts[0]?.startsWith('Fe26.2')) {
97
- throw new Error('Invalid legacy sealed data format');
98
- }
99
-
100
- const [
101
- ,
102
- ,
103
- encryptionSalt,
104
- encryptionIv,
105
- encryptedB64,
106
- expiration,
107
- hmacSalt,
108
- signature,
109
- ] = parts;
110
- return {
111
- encryptionSalt: encryptionSalt!,
112
- encryptionIv: encryptionIv!,
113
- encryptedB64: encryptedB64!,
114
- expiration,
115
- hmacSalt,
116
- signature,
117
- };
118
- }
119
-
120
- // Decrypt legacy data using AES-CBC
121
- private async decryptLegacyData(
122
- encryptedB64: string,
123
- encryptionIv: string,
124
- encryptionSalt: string,
125
- password: string,
126
- ): Promise<string> {
127
- const encryptedBuffer = this.base64urlToBytes(encryptedB64);
128
- const ivBuffer = this.base64urlToBytes(encryptionIv);
129
-
130
- // Derive decryption key using iron-session parameters
131
- const keyBits = await this.deriveKeyBits({
132
- password,
133
- salt: encryptionSalt,
134
- iterations: 1,
135
- hashAlgorithm: 'SHA-1',
136
- keyLength: 256,
137
- });
138
-
139
- const encryptionKey = await globalThis.crypto.subtle.importKey(
140
- 'raw',
141
- keyBits,
142
- { name: 'AES-CBC' },
143
- false,
144
- ['decrypt'],
145
- );
146
-
147
- // Decrypt using AES-256-CBC
148
- const decryptedBuffer = await globalThis.crypto.subtle.decrypt(
149
- {
150
- name: 'AES-CBC',
151
- iv: ivBuffer as BufferSource,
152
- },
153
- encryptionKey,
154
- encryptedBuffer as BufferSource,
155
- );
156
-
157
- return new TextDecoder().decode(decryptedBuffer);
158
- }
159
-
160
- // Encrypt data using AES-CBC
161
- private async encryptLegacyData(
162
- jsonString: string,
163
- encryptionIv: Uint8Array,
164
- encryptionSalt: string,
165
- password: string,
166
- ): Promise<string> {
167
- // Derive encryption key using iron-session parameters
168
- const keyBits = await this.deriveKeyBits({
169
- password,
170
- salt: encryptionSalt,
171
- iterations: 1,
172
- hashAlgorithm: 'SHA-1',
173
- keyLength: 256,
174
- });
175
-
176
- const encryptionKey = await globalThis.crypto.subtle.importKey(
177
- 'raw',
178
- keyBits,
179
- { name: 'AES-CBC' },
180
- false,
181
- ['encrypt'],
182
- );
183
-
184
- // Encrypt the JSON string
185
- const encryptedBuffer = await globalThis.crypto.subtle.encrypt(
186
- {
187
- name: 'AES-CBC',
188
- iv: encryptionIv as BufferSource,
189
- },
190
- encryptionKey,
191
- new TextEncoder().encode(jsonString),
192
- );
193
-
194
- return this.bytesToBase64url(new Uint8Array(encryptedBuffer));
195
- }
196
-
197
- // Create HMAC signature for iron-session format
198
- private async signSealedData(
199
- encryptionSaltHex: string,
200
- encryptionIvB64: string,
201
- encryptedB64: string,
202
- hmacSaltHex: string,
203
- expiration: number,
204
- password: string,
205
- ): Promise<string> {
206
- // Create the unsigned data for HMAC
207
- const unsignedData = `Fe26.2*1*${encryptionSaltHex}*${encryptionIvB64}*${encryptedB64}*${expiration}`;
208
-
209
- // Derive HMAC key
210
- const hmacKeyBits = await this.deriveKeyBits({
211
- password,
212
- salt: hmacSaltHex,
213
- iterations: 1,
214
- hashAlgorithm: 'SHA-1',
215
- keyLength: 256,
216
- });
217
-
218
- const hmacKey = await globalThis.crypto.subtle.importKey(
219
- 'raw',
220
- hmacKeyBits,
221
- { name: 'HMAC', hash: 'SHA-256' },
222
- false,
223
- ['sign'],
224
- );
225
-
226
- // Calculate HMAC signature
227
- const signature = await globalThis.crypto.subtle.sign(
228
- 'HMAC',
229
- hmacKey,
230
- new TextEncoder().encode(unsignedData),
231
- );
232
-
233
- return this.bytesToBase64url(new Uint8Array(signature));
234
- }
235
-
236
- async sealData(
237
- data: unknown,
238
- { password, ttl = 0 }: { password: string; ttl?: number | undefined },
239
- ): Promise<string> {
240
- if (password.length < 32) {
241
- throw new Error('Password must be at least 32 characters long');
242
- }
243
-
244
- const jsonString = JSON.stringify(data);
245
-
246
- // Generate encryption components (matching iron-session)
247
- const encryptionSalt = this.generateRandomBytes(32);
248
- const hmacSalt = this.generateRandomBytes(32);
249
- const encryptionIv = this.generateRandomBytes(16);
250
-
251
- // Convert salts to hex (iron-session format)
252
- const encryptionSaltHex = this.bytesToHex(encryptionSalt);
253
- const hmacSaltHex = this.bytesToHex(hmacSalt);
254
-
255
- // Encrypt the session data
256
- const encryptedB64 = await this.encryptLegacyData(
257
- jsonString,
258
- encryptionIv,
259
- encryptionSaltHex,
260
- password,
261
- );
262
-
263
- const encryptionIvB64 = this.bytesToBase64url(encryptionIv);
264
-
265
- // Calculate expiration (iron-session uses milliseconds)
266
- const expiration =
267
- ttl > 0
268
- ? Date.now() + ttl * 1000
269
- : ttl < 0
270
- ? Date.now() + ttl * 1000
271
- : Date.now() + 24 * 60 * 60 * 1000;
272
-
273
- // Sign the sealed data
274
- const signatureB64 = await this.signSealedData(
275
- encryptionSaltHex,
276
- encryptionIvB64,
277
- encryptedB64,
278
- hmacSaltHex,
279
- expiration,
280
- password,
281
- );
282
-
283
- // Build iron-session format string (Fe26.2)
284
- const sealed = `Fe26.2*1*${encryptionSaltHex}*${encryptionIvB64}*${encryptedB64}*${expiration}*${hmacSaltHex}*${signatureB64}`;
285
-
286
- // Add version suffix for compatibility
287
- return `${sealed}${this.versionDelimiter}${this.currentMajorVersion}`;
288
- }
289
-
290
- async unsealData<T = unknown>(
291
- encryptedData: string,
292
- { password }: { password: string },
293
- ): Promise<T> {
294
- if (password.length < 32) {
295
- throw new Error('Password must be at least 32 characters long');
296
- }
297
-
298
- // Parse version
299
- const { sealWithoutVersion, tokenVersion } = this.parseSeal(encryptedData);
300
-
301
- // Parse iron-session legacy format
302
- const { encryptionSalt, encryptionIv, encryptedB64, expiration } =
303
- this.parseLegacyFormat(sealWithoutVersion);
304
-
305
- // Check expiration if present
306
- if (expiration) {
307
- const expirationTime = parseInt(expiration, 10);
308
- if (Date.now() > expirationTime) {
309
- throw new Error('Sealed data has expired');
310
- }
311
- }
312
-
313
- // Decrypt the data
314
- const decryptedText = await this.decryptLegacyData(
315
- encryptedB64,
316
- encryptionIv,
317
- encryptionSalt,
318
- password,
319
- );
320
-
321
- // Parse the JSON data
322
- const sessionData = JSON.parse(decryptedText);
323
-
324
- // Handle version-specific extraction (matching iron-session behavior)
325
- if (tokenVersion === 2) {
326
- return sessionData as T;
327
- } else if (tokenVersion !== null && tokenVersion !== 2) {
328
- // For older token versions, extract the persistent property
329
- return { ...(sessionData as any).persistent } as T;
330
- }
331
-
332
- // No version info - return as-is
333
- return sessionData as T;
334
- }
335
- }
336
-
337
- const pureWebcryptoEncryption = new PureWebcryptoEncryption();
338
-
339
- export default pureWebcryptoEncryption;