@workos/authkit-session 0.3.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@workos/authkit-session",
3
- "version": "0.3.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
  },
@@ -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
 
@@ -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,CA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C;YACf,MAAM,cAAc,GAAG,QAAQ,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC;YAChD,IAAI,IAAI,CAAC,GAAG,EAAE,GAAG,cAAc,EAAE,CAAC;gBAChC,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAC;YAC7C,CAAC;QACH,CAAC;QAED,mBAAmB;QACnB,MAAM,aAAa,GAAG,MAAM,IAAI,CAAC,iBAAiB,CAChD,YAAY,EACZ,YAAY,EACZ,cAAc,EACd,QAAQ,CACT,CAAC;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;