-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
278 lines (241 loc) · 7.98 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
import { webcrypto } from 'crypto';
// JWT helpers
/**
* Splits a locked token into its components. To be performed on the server.
* @param {string} lockedToken - The locked token.
* @returns {object} An object containing the JWT, timestamped JWT, timestamp, signature, and public key.
*/
export function splitLockedToken(lockedToken) {
const substrings = lockedToken.split('.');
const jwtElements = substrings.slice(0, 3);
const jwtPayload = JSON.parse(atob(jwtElements[1]));
const jwt = jwtElements.join('.');
const timestampedJwt = substrings.slice(0, 4).join('.');
const timestamp = substrings[3];
const signature = substrings[4];
const publicKey = jwtPayload.publicKey;
return { jwt, timestampedJwt, timestamp, signature, publicKey };
}
// IndexedDB helpers
const dbName = 'session-lock-keystore';
const storeName = 'slkeystore';
/**
* Opens the IndexedDB database.
* @returns {Promise<IDBDatabase>} A promise that resolves with the opened database.
*/
function openDatabase() {
return new Promise((resolve, reject) => {
const request = indexedDB.open(dbName, 1);
request.onupgradeneeded = (event) => {
const db = event.target.result;
db.createObjectStore(storeName);
};
request.onsuccess = (event) => {
resolve(event.target.result);
};
request.onerror = (event) => {
reject(new Error('Error opening the IndexedDB database.'));
};
});
}
/**
* Retrieves an item from the IndexedDB database.
* @param {string} key - The key of the item to retrieve.
* @returns {Promise<any>} A promise that resolves with the retrieved item.
*/
async function getItem(key) {
const db = await openDatabase();
return new Promise((resolve, reject) => {
const transaction = db.transaction(storeName, 'readonly');
const store = transaction.objectStore(storeName);
const request = store.get(key);
request.onsuccess = (event) => {
resolve(event.target.result);
};
request.onerror = (event) => {
reject(
new Error(
`Error getting item with key "${key}" from the IndexedDB database.`
)
);
};
});
}
/**
* Stores an item in the IndexedDB database.
* @param {string} key - The key of the item to store.
* @param {any} value - The value of the item to store.
* @returns {Promise<void>} A promise that resolves when the item has been stored.
*/
async function setItem(key, value) {
const db = await openDatabase();
return new Promise((resolve, reject) => {
const transaction = db.transaction(storeName, 'readwrite');
const store = transaction.objectStore(storeName);
const request = store.put(value, key);
request.onsuccess = (event) => {
resolve();
};
request.onerror = (event) => {
reject(
new Error(
`Error setting item with key "${key}" in the IndexedDB database.`
)
);
};
});
}
/**
* Clears the IndexedDB database.
* @returns {Promise<void>} A promise that resolves when the database has been cleared.
*/
export async function clearIdb() {
const db = await openDatabase();
return new Promise((resolve, reject) => {
const transaction = db.transaction(storeName, 'readwrite');
const store = transaction.objectStore(storeName);
const request = store.clear();
request.onsuccess = (event) => {
resolve();
};
request.onerror = (event) => {
reject(new Error('Error clearing the IndexedDB database.'));
};
});
}
// Core cryptographic functions
/**
Converts an ArrayBuffer to a string.
@param {ArrayBuffer} buf - The ArrayBuffer to convert.
@returns {string} The converted string.
*/
function ab2str(buf) {
return String.fromCharCode.apply(null, new Uint8Array(buf));
}
/**
Converts a base64 string to an ArrayBuffer.
@param {string} base64 - The base64 string to convert.
@returns {ArrayBuffer} The converted ArrayBuffer.
*/
function base64ToArrayBuffer(base64) {
const binaryString = atob(base64);
const len = binaryString.length;
const bytes = new Uint8Array(len);
for (let i = 0; i < len; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
return bytes.buffer;
}
/**
Exports a public key to a base64 string.
@param {CryptoKey} key - The public key to export.
@returns {Promise<string>} A promise that resolves with the base64-encoded public key.
*/
async function exportPublicKey(key) {
const exportRaw = await window.crypto.subtle.exportKey('raw', key);
const exportBuffer = new Uint8Array(exportRaw);
const exportString = ab2str(exportBuffer);
const exportB64 = btoa(exportString);
return exportB64;
}
// To be run on the client / browser
/**
Generates an ECDSA key pair and stores the private key in IndexedDB.
@returns {Promise<string>} A promise that resolves with the base64-encoded public key.
*/
export async function generateKeyPair() {
const keyPair = await window.crypto.subtle.generateKey(
{
name: 'ECDSA',
namedCurve: 'P-256',
},
false,
['sign', 'verify'] // verify not strictly needed
);
await setItem('privateKey', keyPair.privateKey);
const publicKey = await exportPublicKey(keyPair.publicKey);
return publicKey;
}
/**
Locks a JWT with a timestamp and ECDSA signature. To be run on the client / browser.
@param {string} token - The JWT to lock.
@returns {Promise<string>} A promise that resolves with the locked token.
*/
export async function lockToken(token) {
const clientTimestamp = Date.now();
const timeStampedJwt = `${token}.${clientTimestamp}`;
const privateKey = await getItem('privateKey');
const signatureBuffer = await window.crypto.subtle.sign(
{
name: 'ECDSA',
hash: { name: 'SHA-256' },
},
privateKey,
new TextEncoder().encode(timeStampedJwt)
);
const signatureString = ab2str(signatureBuffer);
const signatureB64 = btoa(signatureString);
const lockedToken = `${timeStampedJwt}.${signatureB64}`;
return lockedToken;
}
// To be run on the client / browser
/**
Imports a base64-encoded public key as a CryptoKey object. To be run on the client / browser.
@param {string} publicKeyB64 - The base64-encoded public key to import.
@returns {Promise<CryptoKey>} A promise that resolves with the imported public key.
*/
async function importPublicKey(publicKeyB64) {
const binaryString = atob(publicKeyB64);
const len = binaryString.length;
const bytes = new Uint8Array(len);
for (let i = 0; i < len; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
const publicKey = await webcrypto.subtle.importKey(
'raw',
bytes.buffer,
{ name: 'ECDSA', namedCurve: 'P-256' },
true,
['verify']
);
return publicKey;
}
// To be run on the server
/**
Verifies a locked token's timestamp and signature. To be run on the server.
@param {string} lockedToken - The locked token to verify.
@param {number} [validityInterval=2000] - The interval for token validity.
@param {string} [externalPublicKey] - Optional external public key.
@returns {Promise<string>} A promise that resolves with a validation message: 'valid' | 'Invalid signature' | 'Token expired'
*/
export async function verifyLockedToken(
lockedToken,
validityInterval = 2000,
externalPublicKey
) {
try {
const tokenElements = splitLockedToken(lockedToken);
const timestampedJwt = tokenElements.timestampedJwt;
const signature = base64ToArrayBuffer(tokenElements.signature);
const publicKey = externalPublicKey
? await importPublicKey(externalPublicKey)
: await importPublicKey(tokenElements.publicKey);
const timestamp = tokenElements.timestamp;
const validInterval = Date.now() - timestamp <= validityInterval;
const ec = new TextEncoder();
const validSignature = await webcrypto.subtle.verify(
{ name: 'ECDSA', hash: { name: 'SHA-256' } },
publicKey,
signature,
ec.encode(timestampedJwt)
);
const validation = !validInterval
? 'Token expired'
: !validSignature
? 'Invalid signature'
: 'valid';
return validation;
} catch (error) {
throw new Error('Error verifying locked token: ' + error.message);
}
}