@workos/authkit-session 0.0.1-alpha.3 → 0.1.2
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/README.md +80 -5
- package/dist/core/client/types.d.ts +75 -0
- package/dist/core/client/types.d.ts.map +1 -0
- package/dist/core/client/types.js +2 -0
- package/dist/core/client/types.js.map +1 -0
- package/dist/core/client/workos.d.ts +11 -0
- package/dist/core/client/workos.d.ts.map +1 -0
- package/dist/core/client/workos.js +33 -0
- package/dist/core/client/workos.js.map +1 -0
- package/dist/core/config/ConfigurationProvider.d.ts +43 -0
- package/dist/core/config/ConfigurationProvider.d.ts.map +1 -0
- package/dist/core/config/ConfigurationProvider.js +171 -0
- package/dist/core/config/ConfigurationProvider.js.map +1 -0
- package/dist/core/config/types.d.ts +62 -0
- package/dist/core/config/types.d.ts.map +1 -0
- package/dist/core/config/types.js +2 -0
- package/dist/core/config/types.js.map +1 -0
- package/dist/core/config.d.ts +69 -0
- package/dist/core/config.d.ts.map +1 -0
- package/dist/core/config.js +49 -0
- package/dist/core/config.js.map +1 -0
- package/dist/core/createAuthKitFactory.d.ts +64 -0
- package/dist/core/createAuthKitFactory.d.ts.map +1 -0
- package/dist/core/createAuthKitFactory.js +95 -0
- package/dist/core/createAuthKitFactory.js.map +1 -0
- package/dist/core/encryption/ironSessionEncryption.d.ts +16 -0
- package/dist/core/encryption/ironSessionEncryption.d.ts.map +1 -0
- package/dist/core/encryption/ironSessionEncryption.js +6 -0
- package/dist/core/encryption/ironSessionEncryption.js.map +1 -0
- package/dist/core/encryption/ironWebcryptoEncryption.d.ts +19 -0
- package/dist/core/encryption/ironWebcryptoEncryption.d.ts.map +1 -0
- package/dist/core/encryption/ironWebcryptoEncryption.js +84 -0
- package/dist/core/encryption/ironWebcryptoEncryption.js.map +1 -0
- package/dist/core/encryption/pureWebcryptoEncryption.d.ts +29 -0
- package/dist/core/encryption/pureWebcryptoEncryption.d.ts.map +1 -0
- package/dist/core/encryption/pureWebcryptoEncryption.js +182 -0
- package/dist/core/encryption/pureWebcryptoEncryption.js.map +1 -0
- package/dist/core/errors.d.ts +14 -0
- package/dist/core/errors.d.ts.map +1 -0
- package/dist/core/errors.js +28 -0
- package/dist/core/errors.js.map +1 -0
- package/dist/core/session/CookieSessionStorage.d.ts +33 -0
- package/dist/core/session/CookieSessionStorage.d.ts.map +1 -0
- package/dist/core/session/CookieSessionStorage.js +52 -0
- package/dist/core/session/CookieSessionStorage.js.map +1 -0
- package/dist/core/session/SessionManager.d.ts +51 -0
- package/dist/core/session/SessionManager.d.ts.map +1 -0
- package/dist/core/session/SessionManager.js +238 -0
- package/dist/core/session/SessionManager.js.map +1 -0
- package/dist/core/session/TokenManager.d.ts +14 -0
- package/dist/core/session/TokenManager.d.ts.map +1 -0
- package/dist/core/session/TokenManager.js +43 -0
- package/dist/core/session/TokenManager.js.map +1 -0
- package/dist/core/session/types.d.ts +101 -0
- package/dist/core/session/types.d.ts.map +1 -0
- package/dist/core/session/types.js +2 -0
- package/dist/core/session/types.js.map +1 -0
- package/dist/index.d.ts +10 -406
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +8 -923
- package/dist/index.js.map +1 -1
- package/dist/utils.d.ts +9 -0
- package/dist/utils.d.ts.map +1 -0
- package/dist/utils.js +19 -0
- package/dist/utils.js.map +1 -0
- package/package.json +19 -11
- package/src/core/client/types.ts +2 -7
- package/src/core/client/workos.ts +5 -5
- package/src/core/config/ConfigurationProvider.spec.ts +201 -0
- package/src/core/config/ConfigurationProvider.ts +75 -7
- package/src/core/config.spec.ts +160 -0
- package/src/core/config.ts +29 -3
- package/src/core/createAuthKitFactory.spec.ts +161 -0
- package/src/core/createAuthKitFactory.ts +28 -23
- package/src/core/encryption/ironWebcryptoEncryption.spec.ts +129 -0
- package/src/core/encryption/ironWebcryptoEncryption.ts +28 -23
- package/src/core/encryption/pureWebcryptoEncryption.spec.ts +177 -0
- package/src/core/encryption/pureWebcryptoEncryption.ts +339 -0
- package/src/core/errors.spec.ts +130 -0
- package/src/core/session/CookieSessionStorage.spec.ts +136 -0
- package/src/core/session/CookieSessionStorage.ts +40 -7
- package/src/core/session/SessionManager.spec.ts +357 -0
- package/src/core/session/SessionManager.ts +71 -72
- package/src/core/session/TokenManager.spec.ts +132 -0
- package/src/core/session/TokenManager.ts +8 -6
- package/src/core/session/types.ts +39 -3
- package/src/index.ts +20 -8
- package/src/utils.spec.ts +12 -0
- package/dist/index.cjs +0 -924
- package/dist/index.cjs.map +0 -1
- package/dist/index.d.cts +0 -406
- package/src/HttpClient.ts +0 -160
- package/src/adapters/chrome/ChromeExtensionStorage.ts +0 -34
- package/src/core/UserManagement.ts +0 -8
- package/src/core/client/WorkOSLite.ts +0 -284
- package/src/core/iron.ts +0 -103
|
@@ -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;
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import {
|
|
2
|
+
AuthKitError,
|
|
3
|
+
SessionEncryptionError,
|
|
4
|
+
TokenValidationError,
|
|
5
|
+
TokenRefreshError,
|
|
6
|
+
} from './errors.js';
|
|
7
|
+
|
|
8
|
+
describe('AuthKitError', () => {
|
|
9
|
+
it('creates error with message', () => {
|
|
10
|
+
const error = new AuthKitError('Test error');
|
|
11
|
+
|
|
12
|
+
expect(error.message).toBe('Test error');
|
|
13
|
+
expect(error.name).toBe('AuthKitError');
|
|
14
|
+
expect(error).toBeInstanceOf(Error);
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
it('creates error with cause', () => {
|
|
18
|
+
const originalError = new Error('Original error');
|
|
19
|
+
const error = new AuthKitError('Test error', originalError);
|
|
20
|
+
|
|
21
|
+
expect(error.cause).toBe(originalError);
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
it('creates error with data', () => {
|
|
25
|
+
const data = { userId: '123', action: 'login' };
|
|
26
|
+
const error = new AuthKitError('Test error', undefined, data);
|
|
27
|
+
|
|
28
|
+
expect(error.data).toEqual(data);
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
it('creates error with cause and data', () => {
|
|
32
|
+
const originalError = new Error('Original error');
|
|
33
|
+
const data = { userId: '123' };
|
|
34
|
+
const error = new AuthKitError('Test error', originalError, data);
|
|
35
|
+
|
|
36
|
+
expect(error.cause).toBe(originalError);
|
|
37
|
+
expect(error.data).toEqual(data);
|
|
38
|
+
});
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
describe('SessionEncryptionError', () => {
|
|
42
|
+
it('creates error with correct name', () => {
|
|
43
|
+
const error = new SessionEncryptionError('Encryption failed');
|
|
44
|
+
|
|
45
|
+
expect(error.name).toBe('SessionEncryptionError');
|
|
46
|
+
expect(error.message).toBe('Encryption failed');
|
|
47
|
+
expect(error).toBeInstanceOf(AuthKitError);
|
|
48
|
+
expect(error).toBeInstanceOf(Error);
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
it('creates error with cause', () => {
|
|
52
|
+
const originalError = new Error('Crypto error');
|
|
53
|
+
const error = new SessionEncryptionError(
|
|
54
|
+
'Encryption failed',
|
|
55
|
+
originalError,
|
|
56
|
+
);
|
|
57
|
+
|
|
58
|
+
expect(error.cause).toBe(originalError);
|
|
59
|
+
});
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
describe('TokenValidationError', () => {
|
|
63
|
+
it('creates error with correct name', () => {
|
|
64
|
+
const error = new TokenValidationError('Token invalid');
|
|
65
|
+
|
|
66
|
+
expect(error.name).toBe('TokenValidationError');
|
|
67
|
+
expect(error.message).toBe('Token invalid');
|
|
68
|
+
expect(error).toBeInstanceOf(AuthKitError);
|
|
69
|
+
expect(error).toBeInstanceOf(Error);
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
it('creates error with cause', () => {
|
|
73
|
+
const originalError = new Error('JWT malformed');
|
|
74
|
+
const error = new TokenValidationError('Token invalid', originalError);
|
|
75
|
+
|
|
76
|
+
expect(error.cause).toBe(originalError);
|
|
77
|
+
});
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
describe('TokenRefreshError', () => {
|
|
81
|
+
it('creates error with correct name', () => {
|
|
82
|
+
const error = new TokenRefreshError('Refresh failed');
|
|
83
|
+
|
|
84
|
+
expect(error.name).toBe('TokenRefreshError');
|
|
85
|
+
expect(error.message).toBe('Refresh failed');
|
|
86
|
+
expect(error).toBeInstanceOf(AuthKitError);
|
|
87
|
+
expect(error).toBeInstanceOf(Error);
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
it('creates error with cause', () => {
|
|
91
|
+
const originalError = new Error('Network error');
|
|
92
|
+
const error = new TokenRefreshError('Refresh failed', originalError);
|
|
93
|
+
|
|
94
|
+
expect(error.cause).toBe(originalError);
|
|
95
|
+
});
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
describe('error inheritance', () => {
|
|
99
|
+
it('maintains proper inheritance chain', () => {
|
|
100
|
+
const sessionError = new SessionEncryptionError('test');
|
|
101
|
+
const tokenError = new TokenValidationError('test');
|
|
102
|
+
const refreshError = new TokenRefreshError('test');
|
|
103
|
+
|
|
104
|
+
expect(sessionError).toBeInstanceOf(SessionEncryptionError);
|
|
105
|
+
expect(sessionError).toBeInstanceOf(AuthKitError);
|
|
106
|
+
expect(sessionError).toBeInstanceOf(Error);
|
|
107
|
+
|
|
108
|
+
expect(tokenError).toBeInstanceOf(TokenValidationError);
|
|
109
|
+
expect(tokenError).toBeInstanceOf(AuthKitError);
|
|
110
|
+
expect(tokenError).toBeInstanceOf(Error);
|
|
111
|
+
|
|
112
|
+
expect(refreshError).toBeInstanceOf(TokenRefreshError);
|
|
113
|
+
expect(refreshError).toBeInstanceOf(AuthKitError);
|
|
114
|
+
expect(refreshError).toBeInstanceOf(Error);
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
it('can be caught as AuthKitError', () => {
|
|
118
|
+
const errors = [
|
|
119
|
+
new SessionEncryptionError('test'),
|
|
120
|
+
new TokenValidationError('test'),
|
|
121
|
+
new TokenRefreshError('test'),
|
|
122
|
+
];
|
|
123
|
+
|
|
124
|
+
errors.forEach(error => {
|
|
125
|
+
expect(() => {
|
|
126
|
+
throw error;
|
|
127
|
+
}).toThrow(AuthKitError);
|
|
128
|
+
});
|
|
129
|
+
});
|
|
130
|
+
});
|