BlueGit

ict rusty-teams

Files

rusty-teams / crates / session / assets / unseal.js

unseal.js

unseal.js 1.9 KiB Download Raw
1// Newer MSAL.js seals its localStorage cache: AES-GCM under a key from the msal.cache.encryption session cookie.
2// Answers [key, entry] for every sealed entry it could open. `memo` keeps opened entries by nonce.
3async (sealed, memo) => {
4 const opened = [];
5 const cookie = document.cookie.split(';').map((part) => part.trim()).find((part) => part.startsWith('msal.cache.encryption='));
6 let sealing = null;
7 try { sealing = cookie && JSON.parse(decodeURIComponent(cookie.slice(cookie.indexOf('=') + 1))); } catch (error) {}
8 if (!sealing || !sealing.key || !sealing.id || !sealed.length) return opened;
9 const bytes = (text) => Uint8Array.from(atob(text.replace(/-/g, '+').replace(/_/g, '/').padEnd(Math.ceil(text.length / 4) * 4, '=')),
10 (character) => character.charCodeAt(0));
11 const base = await crypto.subtle.importKey('raw', bytes(sealing.key), 'HKDF', false, ['deriveKey']);
12 for (const [key, entry] of sealed) {
13 if (entry.id !== sealing.id) continue;
14 if (!memo.has(entry.nonce)) {
15 // MSAL binds an entry to the client id in its key, or to an empty context when the key has none.
16 const contexts = [...(String(key).match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi) || []), ''];
17 for (const context of new Set(contexts)) {
18 try {
19 const derived = await crypto.subtle.deriveKey(
20 {name: 'HKDF', salt: bytes(entry.nonce), hash: 'SHA-256', info: new TextEncoder().encode(context)},
21 base, {name: 'AES-GCM', length: 256}, false, ['decrypt']);
22 const data = await crypto.subtle.decrypt({name: 'AES-GCM', iv: new Uint8Array(12)}, derived, bytes(entry.data));
23 memo.set(entry.nonce, JSON.parse(new TextDecoder().decode(data)));
24 break;
25 } catch (error) {}
26 }
27 }
28 if (memo.has(entry.nonce)) opened.push([key, memo.get(entry.nonce)]);
29 }
30 return opened;
31}