@workos/authkit-session 0.0.1-alpha.2 → 0.1.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.
Files changed (35) hide show
  1. package/README.md +184 -11
  2. package/dist/index.cjs +229 -356
  3. package/dist/index.cjs.map +1 -1
  4. package/dist/index.js +225 -352
  5. package/dist/index.js.map +1 -1
  6. package/package.json +20 -12
  7. package/src/core/client/types.ts +2 -7
  8. package/src/core/client/workos.ts +5 -5
  9. package/src/core/config/ConfigurationProvider.spec.ts +201 -0
  10. package/src/core/config/ConfigurationProvider.ts +80 -12
  11. package/src/core/config.spec.ts +160 -0
  12. package/src/core/config.ts +29 -3
  13. package/src/core/createAuthKitFactory.spec.ts +161 -0
  14. package/src/core/createAuthKitFactory.ts +33 -25
  15. package/src/core/encryption/ironWebcryptoEncryption.spec.ts +129 -0
  16. package/src/core/encryption/ironWebcryptoEncryption.ts +28 -23
  17. package/src/core/encryption/pureWebcryptoEncryption.spec.ts +177 -0
  18. package/src/core/encryption/pureWebcryptoEncryption.ts +339 -0
  19. package/src/core/errors.spec.ts +130 -0
  20. package/src/core/session/CookieSessionStorage.spec.ts +136 -0
  21. package/src/core/session/CookieSessionStorage.ts +40 -7
  22. package/src/core/session/SessionManager.spec.ts +357 -0
  23. package/src/core/session/SessionManager.ts +78 -75
  24. package/src/core/session/TokenManager.spec.ts +132 -0
  25. package/src/core/session/TokenManager.ts +8 -6
  26. package/src/core/session/types.ts +39 -3
  27. package/src/index.ts +20 -8
  28. package/src/utils.spec.ts +12 -0
  29. package/dist/index.d.cts +0 -406
  30. package/dist/index.d.ts +0 -406
  31. package/src/HttpClient.ts +0 -160
  32. package/src/adapters/chrome/ChromeExtensionStorage.ts +0 -34
  33. package/src/core/UserManagement.ts +0 -8
  34. package/src/core/client/WorkOSLite.ts +0 -284
  35. package/src/core/iron.ts +0 -103
@@ -0,0 +1,129 @@
1
+ import {
2
+ sealData as ironSessionSeal,
3
+ unsealData as ironSessionUnseal,
4
+ } from 'iron-session';
5
+ import { SessionEncryption } from './ironWebcryptoEncryption.js';
6
+ import ironSessionEncryption from './ironSessionEncryption.js';
7
+
8
+ const testPassword = 'this-is-a-test-password-that-is-32-characters-long!';
9
+ const testData = {
10
+ userId: '123',
11
+ email: 'test@example.com',
12
+ timestamp: Date.now(),
13
+ };
14
+
15
+ describe('ironWebcryptoEncryption', () => {
16
+ const encryption = new SessionEncryption();
17
+
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 () => {
44
+ const sealed = await encryption.sealData(testData, {
45
+ password: testPassword,
46
+ });
47
+
48
+ expect(sealed).toMatch(/~2$/);
49
+
50
+ const unsealed = await encryption.unsealData(sealed, {
51
+ password: testPassword,
52
+ });
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
+
66
+ expect(unsealed).toEqual(testData);
67
+ });
68
+ });
69
+
70
+ describe('basic functionality', () => {
71
+ it('seals and unseals data correctly', async () => {
72
+ const sealed = await encryption.sealData(testData, {
73
+ password: testPassword,
74
+ });
75
+ const unsealed = await encryption.unsealData(sealed, {
76
+ password: testPassword,
77
+ });
78
+
79
+ expect(unsealed).toEqual(testData);
80
+ });
81
+
82
+ it('handles TTL parameter', async () => {
83
+ const sealed = await encryption.sealData(testData, {
84
+ password: testPassword,
85
+ ttl: 3600,
86
+ });
87
+
88
+ expect(sealed).toBeDefined();
89
+ expect(typeof sealed).toBe('string');
90
+ });
91
+
92
+ it('fails with wrong password', async () => {
93
+ const sealed = await encryption.sealData(testData, {
94
+ password: testPassword,
95
+ });
96
+ const wrongPassword = 'wrong-password-that-is-32-chars!!';
97
+
98
+ await expect(
99
+ encryption.unsealData(sealed, { password: wrongPassword }),
100
+ ).rejects.toThrow();
101
+ });
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
+
117
+ it('produces data that ironSessionEncryption can unseal', async () => {
118
+ const sealed = await encryption.sealData(testData, {
119
+ password: testPassword,
120
+ });
121
+
122
+ const unsealed = await ironSessionEncryption.unsealData(sealed, {
123
+ password: testPassword,
124
+ });
125
+
126
+ expect(unsealed).toEqual(testData);
127
+ });
128
+ });
129
+ });
@@ -1,5 +1,15 @@
1
1
  import { seal as sealData, unseal as unsealData } from 'iron-webcrypto';
2
- import type { SessionEncryption as SessionEncryptionInterface } from '../session/types';
2
+ import type { SessionEncryption as SessionEncryptionInterface } from '../session/types.js';
3
+
4
+ // Extract the precise Crypto type that iron-webcrypto expects
5
+ // This avoids importing iron-webcrypto's private _Crypto type
6
+ type IronCrypto = Parameters<typeof sealData>[0];
7
+
8
+ // Cast globalThis.crypto to iron-webcrypto's expected type
9
+ // Runtime-safe: DOM Crypto is fully compatible with iron-webcrypto's _Crypto
10
+ // Type-level workaround: iron-webcrypto's _Crypto expects Uint8Array<ArrayBuffer>
11
+ // while DOM Crypto provides Uint8Array<ArrayBufferLike>
12
+ const ironCrypto: IronCrypto = globalThis.crypto as unknown as IronCrypto;
3
13
 
4
14
  /**
5
15
  * A compatible implementation that works with iron-session
@@ -33,7 +43,7 @@ export class SessionEncryption implements SessionEncryptionInterface {
33
43
  };
34
44
 
35
45
  // Seal the data using iron-webcrypto with properly formatted password
36
- const seal = await sealData(globalThis.crypto, data, passwordObj, {
46
+ const seal = await sealData(ironCrypto, data, passwordObj, {
37
47
  encryption: {
38
48
  saltBits: 256,
39
49
  algorithm: 'aes-256-cbc',
@@ -67,28 +77,23 @@ export class SessionEncryption implements SessionEncryptionInterface {
67
77
  const passwordMap = { 1: password };
68
78
 
69
79
  // Use iron-webcrypto's unseal function
70
- const data = await unsealData(
71
- globalThis.crypto,
72
- sealWithoutVersion,
73
- passwordMap,
74
- {
75
- encryption: {
76
- saltBits: 256,
77
- algorithm: 'aes-256-cbc',
78
- iterations: 1,
79
- minPasswordlength: 32,
80
- },
81
- integrity: {
82
- saltBits: 256,
83
- algorithm: 'sha256',
84
- iterations: 1,
85
- minPasswordlength: 32,
86
- },
87
- ttl: 0,
88
- timestampSkewSec: 60,
89
- localtimeOffsetMsec: 0,
80
+ const data = await unsealData(ironCrypto, sealWithoutVersion, passwordMap, {
81
+ encryption: {
82
+ saltBits: 256,
83
+ algorithm: 'aes-256-cbc',
84
+ iterations: 1,
85
+ minPasswordlength: 32,
90
86
  },
91
- );
87
+ integrity: {
88
+ saltBits: 256,
89
+ algorithm: 'sha256',
90
+ iterations: 1,
91
+ minPasswordlength: 32,
92
+ },
93
+ ttl: 0,
94
+ timestampSkewSec: 60,
95
+ localtimeOffsetMsec: 0,
96
+ });
92
97
 
93
98
  // Check the token version if needed
94
99
  if (tokenVersion === 2) {
@@ -0,0 +1,177 @@
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
+ });
@@ -0,0 +1,339 @@
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;