forked from Vero-protocol/vero-guardian-dashboard
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsession.ts
More file actions
293 lines (248 loc) · 8.19 KB
/
Copy pathsession.ts
File metadata and controls
293 lines (248 loc) · 8.19 KB
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
/**
* Inactive wallet session management and encryption (issue #15)
*/
type SessionCallback = () => void;
const STORAGE_KEY = 'vero_wallet_publicKey';
const PROVIDER_STORAGE_KEY = 'vero_wallet_provider';
const LAST_ACTIVE_KEY = 'vero_wallet_last_active';
const ACTIVITY_EVENTS = ['mousedown', 'keydown', 'scroll', 'touchstart', 'click'];
const IDLE_LIMIT_MS = 15 * 60 * 1000; // 15 minutes
const THROTTLE_LIMIT_MS = 10 * 1000; // 10 seconds
class MemoryStorage {
private store: Record<string, string> = {};
getItem(key: string) { return this.store[key] || null; }
setItem(key: string, value: string) { this.store[key] = value; }
removeItem(key: string) { delete this.store[key]; }
clear() { this.store = {}; }
}
const safeSessionStorage = typeof window !== 'undefined' && window.sessionStorage
? window.sessionStorage
: new MemoryStorage();
let cachedKey: CryptoKey | null = null;
function getCrypto(): Crypto {
if (typeof window !== 'undefined' && window.crypto && window.crypto.subtle) {
return window.crypto;
}
if (typeof globalThis !== 'undefined' && globalThis.crypto && (globalThis.crypto as any).subtle) {
return globalThis.crypto as unknown as Crypto;
}
if (typeof window !== 'undefined' && window.crypto) {
return window.crypto;
}
if (typeof globalThis !== 'undefined' && globalThis.crypto) {
return globalThis.crypto as unknown as Crypto;
}
throw new Error('Web Crypto API is not available.');
}
let keyPromise: Promise<CryptoKey> | null = null;
async function getEncryptionKey(): Promise<CryptoKey> {
if (cachedKey) return cachedKey;
if (keyPromise) return keyPromise;
keyPromise = (async () => {
const crypto = getCrypto();
const storedKeyJwk = safeSessionStorage.getItem('vero_session_key');
if (storedKeyJwk) {
try {
const jwk = JSON.parse(storedKeyJwk);
cachedKey = await crypto.subtle.importKey(
'jwk',
jwk,
{ name: 'AES-GCM', length: 256 },
false,
['encrypt', 'decrypt']
);
keyPromise = null;
return cachedKey;
} catch (e) {
console.error('Failed to import session encryption key from sessionStorage:', e);
}
}
// Generate new key
const key = await crypto.subtle.generateKey(
{ name: 'AES-GCM', length: 256 },
true,
['encrypt', 'decrypt']
);
try {
const exported = await crypto.subtle.exportKey('jwk', key);
safeSessionStorage.setItem('vero_session_key', JSON.stringify(exported));
} catch (e) {
console.error('Failed to export and store session encryption key:', e);
}
cachedKey = key;
keyPromise = null;
return key;
})();
return keyPromise;
}
function bytesToBase64(bytes: Uint8Array): string {
if (typeof Buffer !== 'undefined') {
return Buffer.from(bytes).toString('base64');
}
let binary = '';
for (const byte of bytes) {
binary += String.fromCharCode(byte);
}
return btoa(binary);
}
function base64ToBytes(value: string): Uint8Array {
if (typeof Buffer !== 'undefined') {
return new Uint8Array(Buffer.from(value, 'base64'));
}
const binary = atob(value);
return Uint8Array.from(binary, (char) => char.charCodeAt(0));
}
export async function encryptSessionData(value: string): Promise<string> {
const crypto = getCrypto();
const key = await getEncryptionKey();
const iv = new Uint8Array(12);
crypto.getRandomValues(iv);
const plaintext = new TextEncoder().encode(value);
const ciphertext = await crypto.subtle.encrypt(
{ name: 'AES-GCM', iv: iv as any },
key,
plaintext as any
);
const payload = {
iv: bytesToBase64(iv),
ciphertext: bytesToBase64(new Uint8Array(ciphertext)),
};
return JSON.stringify(payload);
}
export async function decryptSessionData(encrypted: string): Promise<string> {
const payload = JSON.parse(encrypted);
if (!payload.iv || !payload.ciphertext) {
throw new Error('Invalid encrypted payload structure');
}
const crypto = getCrypto();
const key = await getEncryptionKey();
const iv = base64ToBytes(payload.iv);
const ciphertext = base64ToBytes(payload.ciphertext);
const decrypted = await crypto.subtle.decrypt(
{ name: 'AES-GCM', iv: iv as any },
key,
ciphertext as any
);
return new TextDecoder().decode(decrypted);
}
export async function getSessionItem(key: string): Promise<string | null> {
if (typeof window === 'undefined') return null;
const value = localStorage.getItem(key);
if (!value) return null;
try {
return await decryptSessionData(value);
} catch (e) {
// Fallback: if value is not encrypted, return it directly.
// If it's not encrypted, it won't start with '{' or won't parse properly.
if (!value.startsWith('{') || !value.includes('ciphertext')) {
return value;
}
console.error(`Failed to decrypt session item for key ${key}:`, e);
return null;
}
}
export async function setSessionItem(key: string, value: string): Promise<void> {
if (typeof window === 'undefined') return;
const encrypted = await encryptSessionData(value);
localStorage.setItem(key, encrypted);
}
export function removeSessionItem(key: string): void {
if (typeof window === 'undefined') return;
localStorage.removeItem(key);
}
export class SessionManager {
private listeners: Set<SessionCallback> = new Set();
private checkInterval: ReturnType<typeof setInterval> | null = null;
private lastSavedTime = 0;
private isChecking = false;
private cleanupListeners?: () => void;
private activeUpdatePromise: Promise<void> | null = null;
subscribe(callback: SessionCallback): () => void {
this.listeners.add(callback);
return () => {
this.listeners.delete(callback);
};
}
private notifyLogout() {
this.listeners.forEach((callback) => callback());
}
startMonitoring(): Promise<void> {
if (typeof window === 'undefined') return Promise.resolve();
if (this.isChecking) return Promise.resolve();
this.isChecking = true;
// Reset last active to now on start
const initialUpdate = this.updateLastActive(true);
const handleActivity = () => {
void this.updateLastActive();
};
ACTIVITY_EVENTS.forEach((event) => {
window.addEventListener(event, handleActivity, { passive: true });
});
// Check every 10 seconds
this.checkInterval = setInterval(() => {
void this.checkIdleTimeout();
}, 10000);
this.cleanupListeners = () => {
ACTIVITY_EVENTS.forEach((event) => {
window.removeEventListener(event, handleActivity);
});
if (this.checkInterval) {
clearInterval(this.checkInterval);
this.checkInterval = null;
}
this.isChecking = false;
};
return initialUpdate;
}
stopMonitoring() {
if (this.cleanupListeners) {
this.cleanupListeners();
this.cleanupListeners = undefined;
}
}
async checkIdleTimeout() {
try {
const lastActiveStr = await getSessionItem(LAST_ACTIVE_KEY);
if (!lastActiveStr) {
// If logged in but last active key is missing, initialize it
await this.updateLastActive(true);
return;
}
const lastActive = parseInt(lastActiveStr, 10);
const now = Date.now();
if (now - lastActive >= IDLE_LIMIT_MS) {
this.notifyLogout();
}
} catch (e) {
console.error('Failed to check idle timeout:', e);
}
}
async updateLastActive(force = false): Promise<void> {
if (this.activeUpdatePromise) {
return this.activeUpdatePromise;
}
const now = Date.now();
if (force || now - this.lastSavedTime >= THROTTLE_LIMIT_MS) {
this.lastSavedTime = now;
this.activeUpdatePromise = (async () => {
try {
await setSessionItem(LAST_ACTIVE_KEY, now.toString());
} catch (err) {
console.error('Failed to update last active timestamp:', err);
} finally {
this.activeUpdatePromise = null;
}
})();
return this.activeUpdatePromise;
}
}
// Exposed for testing purposes
clearCache() {
cachedKey = null;
keyPromise = null;
this.activeUpdatePromise = null;
this.listeners.clear();
safeSessionStorage.removeItem('vero_session_key');
}
}
export const sessionManager = new SessionManager();