-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpasskey.ts
More file actions
515 lines (447 loc) · 16.6 KB
/
passkey.ts
File metadata and controls
515 lines (447 loc) · 16.6 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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
/**
* WebAuthn passkey authentication with PRF extension for key encryption.
*
* Three independent secrets per home:
* - Device seed (sr25519): per-device transaction signing, encrypted via PRF
* - Home secret: per-home membership proof (commitment in Merkle tree)
* - Identity key: per-home nullifier derivation + ZK proof generation (origin device only)
*/
export const storageKeyDeviceSeed = "gov-device-seed";
export const storageKeyHomeSecret = "gov-home-secret";
export const storageKeyIdentityKey = "gov-identity-key";
export const storageKeyIsOrigin = "gov-is-origin";
export const storageKeyVotedProposals = "gov-voted-proposals";
const storageKeyCredentialId = "gov-credential-id";
/** Check if WebAuthn is available in this browser. */
export function isWebAuthnAvailable(): boolean {
return (
typeof window !== "undefined" &&
typeof window.PublicKeyCredential !== "undefined" &&
typeof window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable ===
"function"
);
}
/** Check if PRF extension is likely available (Chrome 116+, Safari 18+). */
export function isPrfLikelyAvailable(): boolean {
if (!isWebAuthnAvailable()) return false;
const ua = navigator.userAgent;
const chromeMatch = ua.match(/Chrome\/(\d+)/);
if (chromeMatch !== null && parseInt(chromeMatch[1]) >= 116) return true;
const safariMatch = ua.match(/Version\/(\d+).*Safari/);
if (safariMatch !== null && parseInt(safariMatch[1]) >= 18) return true;
return false;
}
/** Check if a passkey credential is stored. */
export function hasStoredCredential(): boolean {
return localStorage.getItem(storageKeyCredentialId) !== null;
}
/** Get the stored credential ID. */
export function getStoredCredentialId(): Uint8Array | null {
const stored = localStorage.getItem(storageKeyCredentialId);
if (stored === null || stored === "") return null;
return Uint8Array.from(atob(stored), (c) => c.charCodeAt(0));
}
// ── Home secret helpers ─────────────────────────────────────────
/** Get the stored home secret (hex string -> Uint8Array). */
export function getHomeSecret(): Uint8Array | null {
const hex = localStorage.getItem(storageKeyHomeSecret);
if (hex?.length !== 64) return null;
const matched = hex.match(/.{1,2}/g);
if (matched === null) return null;
return new Uint8Array(matched.map((b) => parseInt(b, 16)));
}
/** Store the home secret (Uint8Array -> hex string). */
export function setHomeSecret(seed: Uint8Array): void {
const hex = Array.from(seed)
.map((b) => b.toString(16).padStart(2, "0"))
.join("");
localStorage.setItem(storageKeyHomeSecret, hex);
}
// ── Identity key helpers (origin device only) ───────────────────
/** Check if this device is the origin device. */
export function isOriginDevice(): boolean {
return localStorage.getItem(storageKeyIsOrigin) === "true";
}
/** Set this device as origin. */
export function setIsOrigin(value: boolean): void {
if (value) {
localStorage.setItem(storageKeyIsOrigin, "true");
} else {
localStorage.removeItem(storageKeyIsOrigin);
}
}
/** Get the stored identity key (encrypted, needs PRF or passphrase to decrypt). */
export function getEncryptedIdentityKey(): EncryptedData | null {
const stored = localStorage.getItem(storageKeyIdentityKey);
if (stored === null || stored === "") return null;
return JSON.parse(stored) as EncryptedData;
}
/** Store the encrypted identity key. */
export function setEncryptedIdentityKey(data: EncryptedData): void {
localStorage.setItem(storageKeyIdentityKey, JSON.stringify(data));
}
// ── Voted proposals cache ───────────────────────────────────────
/** Get the list of proposal IDs this home has voted on. */
export function getVotedProposals(): number[] {
const stored = localStorage.getItem(storageKeyVotedProposals);
if (stored === null || stored === "") return [];
return JSON.parse(stored) as number[];
}
/** Record a proposal as voted. */
export function addVotedProposal(proposalId: number): void {
const voted = getVotedProposals();
if (!voted.includes(proposalId)) {
voted.push(proposalId);
localStorage.setItem(storageKeyVotedProposals, JSON.stringify(voted));
}
}
// ── AES-GCM encryption helpers ──────────────────────────────────
/**
* Encrypt a secret with an AES-256-GCM key.
* Returns: 12-byte IV + encrypted data + 16-byte auth tag.
*/
export async function encryptWithKey(
plaintext: Uint8Array,
key: CryptoKey,
): Promise<EncryptedData> {
const iv = crypto.getRandomValues(new Uint8Array(12));
const encrypted = await crypto.subtle.encrypt({ name: "AES-GCM", iv }, key, plaintext);
return {
iv: Array.from(iv),
data: Array.from(new Uint8Array(encrypted)),
};
}
/**
* Decrypt a secret with an AES-256-GCM key.
* Returns null if decryption fails (wrong key).
*/
export async function decryptWithKey(
encrypted: EncryptedData,
key: CryptoKey,
): Promise<Uint8Array | null> {
try {
const decrypted = await crypto.subtle.decrypt(
{ name: "AES-GCM", iv: new Uint8Array(encrypted.iv) },
key,
new Uint8Array(encrypted.data),
);
return new Uint8Array(decrypted);
} catch {
return null;
}
}
// ── PBKDF2 + AES-256-GCM fallback ──────────────────────────────
/**
* Derive an AES-256-GCM key from a user-chosen passphrase.
* Uses PBKDF2 with 100K iterations + SHA-256.
*/
export async function deriveKeyFromPassphrase(
passphrase: string,
salt: Uint8Array,
): Promise<CryptoKey> {
const encoder = new TextEncoder();
const baseKey = await crypto.subtle.importKey(
"raw",
encoder.encode(passphrase),
"PBKDF2",
false,
["deriveKey"],
);
return crypto.subtle.deriveKey(
{ name: "PBKDF2", salt, iterations: 100_000, hash: "SHA-256" },
baseKey,
{ name: "AES-GCM", length: 256 },
false,
["encrypt", "decrypt"],
);
}
/** Encrypt a secret with a user-chosen passphrase (PBKDF2 + AES-256-GCM). */
export async function encryptWithPassphrase(
plaintext: Uint8Array,
passphrase: string,
): Promise<{ salt: number[]; encrypted: EncryptedData }> {
const salt = crypto.getRandomValues(new Uint8Array(16));
const key = await deriveKeyFromPassphrase(passphrase, salt);
const encrypted = await encryptWithKey(plaintext, key);
return { salt: Array.from(salt), encrypted };
}
/** Decrypt a secret with a user-chosen passphrase. */
export async function decryptWithPassphrase(
data: { salt: number[]; encrypted: EncryptedData },
passphrase: string,
): Promise<Uint8Array | null> {
const key = await deriveKeyFromPassphrase(passphrase, new Uint8Array(data.salt));
return decryptWithKey(data.encrypted, key);
}
// ── Passkey registration & authentication ───────────────────────
/**
* Register a new passkey and generate key seeds.
* Returns device seed, home secret, and identity key.
*/
export async function registerPasskey(
username: string,
): Promise<{ deviceSeed: Uint8Array; homeSecret: Uint8Array; identityKey: Uint8Array }> {
const deviceSeed = crypto.getRandomValues(new Uint8Array(32));
const homeSecret = crypto.getRandomValues(new Uint8Array(32));
const rpId = window.location.hostname;
const userId = crypto.getRandomValues(new Uint8Array(32));
const isSecure = window.isSecureContext;
if (!isSecure) {
throw new Error(`Not a secure context. WebAuthn requires HTTPS or localhost.`);
}
if (typeof navigator.credentials.create !== "function") {
throw new Error("navigator.credentials.create not available");
}
const publicKeyOptions: PublicKeyCredentialCreationOptions = {
challenge: crypto.getRandomValues(new Uint8Array(32)),
rp: { name: "Community Governance", id: rpId },
user: { id: userId, name: username, displayName: username },
pubKeyCredParams: [
{ alg: -7, type: "public-key" }, // ES256
{ alg: -257, type: "public-key" }, // RS256
],
authenticatorSelection: {
userVerification: "preferred",
residentKey: "preferred",
},
timeout: 60000,
};
// Try with PRF extension first
let credential: PublicKeyCredential | null = null;
try {
credential = (await navigator.credentials.create({
publicKey: {
...publicKeyOptions,
extensions: {
// @ts-expect-error PRF extension (WebAuthn Level 3)
prf: {
eval: {
first: new TextEncoder().encode("community-gov-device"),
},
},
},
},
})) as PublicKeyCredential | null;
} catch (prfError) {
console.warn("[Passkey] PRF attempt failed, retrying without PRF:", prfError);
try {
credential = (await navigator.credentials.create({
publicKey: publicKeyOptions,
})) as PublicKeyCredential | null;
} catch (fallbackError) {
console.error("[Passkey] Fallback (no PRF) also failed:", fallbackError);
}
}
if (credential !== null) {
const credIdBase64 = btoa(String.fromCharCode(...new Uint8Array(credential.rawId)));
localStorage.setItem(storageKeyCredentialId, credIdBase64);
const ext = credential.getClientExtensionResults();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const prfResult: ArrayBuffer | undefined = (ext as any).prf?.results?.first;
if (prfResult !== undefined) {
// Encrypt device seed with PRF-derived key
const prfKey = await crypto.subtle.importKey(
"raw",
prfResult,
{ name: "AES-GCM" },
false,
["encrypt"],
);
const encrypted = await encryptWithKey(deviceSeed, prfKey);
localStorage.setItem(storageKeyDeviceSeed, JSON.stringify(encrypted));
} else {
console.warn("[Passkey] No PRF support, storing device seed unencrypted");
storeDeviceSeedFallback(deviceSeed);
}
} else {
console.warn("[Passkey] WebAuthn unavailable. Storing device seed unencrypted.");
storeDeviceSeedFallback(deviceSeed);
}
// Store home secret (plaintext in localStorage: shared via QR pairing)
setHomeSecret(homeSecret);
// Identity key will be derived from mnemonic and stored separately
// (see mnemonic.ts for derivation, stored encrypted via PRF or passphrase)
return { deviceSeed, homeSecret, identityKey: new Uint8Array(0) };
}
function storeDeviceSeedFallback(deviceSeed: Uint8Array): void {
localStorage.setItem(
storageKeyDeviceSeed,
JSON.stringify({ fallback: true, data: Array.from(deviceSeed) }),
);
}
/**
* Authenticate with an existing passkey and recover the device seed.
*/
export async function authenticatePasskey(): Promise<{
deviceSeed: Uint8Array;
homeSecret: Uint8Array;
} | null> {
const homeSecret = getHomeSecret();
const deviceStored: { fallback?: boolean; data?: number[]; iv?: number[] } | null = JSON.parse(
localStorage.getItem(storageKeyDeviceSeed) ?? "null",
) as { fallback?: boolean; data?: number[]; iv?: number[] } | null;
// If stored in fallback mode, return directly
if (deviceStored?.fallback === true && deviceStored.data !== undefined) {
const deviceSeed = new Uint8Array(deviceStored.data);
return {
deviceSeed,
homeSecret: homeSecret ?? deviceSeed,
};
}
// Need passkey to decrypt
const credentialId = getStoredCredentialId();
if (credentialId === null) return null;
const assertion = (await navigator.credentials.get({
publicKey: {
challenge: crypto.getRandomValues(new Uint8Array(32)),
rpId: window.location.hostname,
allowCredentials: [{ id: credentialId, type: "public-key" }],
userVerification: "preferred",
extensions: {
// @ts-expect-error PRF extension
prf: {
eval: {
first: new TextEncoder().encode("community-gov-device"),
},
},
},
},
})) as PublicKeyCredential | null;
if (assertion === null) return null;
const ext = assertion.getClientExtensionResults();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const prfResult: ArrayBuffer | undefined = (ext as any).prf?.results?.first;
if (deviceStored === null) return null;
if (prfResult === undefined) throw new Error("PRF extension not available for decryption");
const prfKey = await crypto.subtle.importKey("raw", prfResult, { name: "AES-GCM" }, false, [
"decrypt",
]);
const deviceSeed = await decryptWithKey(deviceStored as EncryptedData, prfKey);
if (deviceSeed === null) throw new Error("Failed to decrypt device seed");
return {
deviceSeed,
homeSecret: homeSecret ?? deviceSeed,
};
}
// ── Identity key encryption/decryption (origin device only) ────
/**
* Encrypt and store the identity key using WebAuthn PRF.
* Uses a separate PRF salt ("community-gov-identity") from the device seed.
*/
export async function storeIdentityKeyWithPrf(identityKey: Uint8Array): Promise<void> {
const credentialId = getStoredCredentialId();
if (credentialId === null) {
// No credential: use passphrase fallback
storeIdentityKeyFallback(identityKey);
return;
}
try {
const assertion = (await navigator.credentials.get({
publicKey: {
challenge: crypto.getRandomValues(new Uint8Array(32)),
rpId: window.location.hostname,
allowCredentials: [{ id: credentialId, type: "public-key" }],
userVerification: "preferred",
extensions: {
// @ts-expect-error PRF extension
prf: {
eval: {
first: new TextEncoder().encode("community-gov-identity"),
},
},
},
},
})) as PublicKeyCredential | null;
if (assertion === null) throw new Error("Assertion cancelled");
const ext = assertion.getClientExtensionResults();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const prfResult: ArrayBuffer | undefined = (ext as any).prf?.results?.first;
if (prfResult !== undefined) {
const prfKey = await crypto.subtle.importKey(
"raw",
prfResult,
{ name: "AES-GCM" },
false,
["encrypt"],
);
const encrypted = await encryptWithKey(identityKey, prfKey);
const withPrf = { ...encrypted, prf: true } as unknown as EncryptedData;
setEncryptedIdentityKey(withPrf);
return;
}
} catch (e) {
console.warn("[Passkey] PRF encryption for identity key failed:", e);
}
// Fallback
storeIdentityKeyFallback(identityKey);
}
function storeIdentityKeyFallback(identityKey: Uint8Array): void {
// Store with a flag indicating it needs passphrase encryption.
// In a real deployment, prompt user for a passphrase here.
// For now, store encrypted with a placeholder (dev mode).
setEncryptedIdentityKey({
fallback: true,
data: Array.from(identityKey),
} as unknown as EncryptedData);
}
/**
* Decrypt and return the identity key using WebAuthn PRF.
* Returns null if not available (not origin device, or decryption failed).
*/
export async function decryptIdentityKey(): Promise<Uint8Array | null> {
if (!isOriginDevice()) return null;
const stored = getEncryptedIdentityKey();
if (stored === null) return null;
// Check fallback mode
if ((stored as unknown as { fallback?: boolean }).fallback === true) {
return new Uint8Array((stored as unknown as { data: number[] }).data);
}
const credentialId = getStoredCredentialId();
if (credentialId === null) return null;
try {
const assertion = (await navigator.credentials.get({
publicKey: {
challenge: crypto.getRandomValues(new Uint8Array(32)),
rpId: window.location.hostname,
allowCredentials: [{ id: credentialId, type: "public-key" }],
userVerification: "preferred",
extensions: {
// @ts-expect-error PRF extension
prf: {
eval: {
first: new TextEncoder().encode("community-gov-identity"),
},
},
},
},
})) as PublicKeyCredential | null;
if (assertion === null) return null;
const ext = assertion.getClientExtensionResults();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const prfResult: ArrayBuffer | undefined = (ext as any).prf?.results?.first;
if (prfResult === undefined) return null;
const prfKey = await crypto.subtle.importKey("raw", prfResult, { name: "AES-GCM" }, false, [
"decrypt",
]);
return await decryptWithKey(stored, prfKey);
} catch (e) {
console.warn("[Passkey] Failed to decrypt identity key:", e);
return null;
}
}
/** Clear all stored passkey data. */
export function clearPasskeyData(): void {
localStorage.removeItem(storageKeyDeviceSeed);
localStorage.removeItem(storageKeyHomeSecret);
localStorage.removeItem(storageKeyIdentityKey);
localStorage.removeItem(storageKeyIsOrigin);
localStorage.removeItem(storageKeyVotedProposals);
localStorage.removeItem(storageKeyCredentialId);
localStorage.removeItem("gov-community-private-key");
localStorage.removeItem("gov-committee-private-key");
}
// ── Types ───────────────────────────────────────────────────────
export interface EncryptedData {
iv: number[];
data: number[];
}