WIP IV improve UX [snapshot task 2]
This commit is contained in:
1 parent
28c90d1d71
commit
58c3e2af86
16 files changed
+779
-36
No files matched your search
@@ -0,0 +1,141 @@
|
||||
import { isRecord } from './validation.ts';
|
||||
|
||||
export interface Identity { publicKey: string; privateKey: CryptoKey }
|
||||
export interface IdentityHello { key: string; nonce: string }
|
||||
export interface Contact { key: string; name: string }
|
||||
export interface IdentityState { revision?: string; identity: Identity | null; contacts: Contact[] }
|
||||
export interface IdentityContext { offer: IdentityHello; answer: IdentityHello; offerFingerprint: string; answerFingerprint: string }
|
||||
const curve = { name: 'ECDSA', namedCurve: 'P-256' };
|
||||
const signing = { name: 'ECDSA', hash: 'SHA-256' };
|
||||
const bytes = (text: string) => new TextEncoder().encode(text);
|
||||
const hex = (data: ArrayBuffer | Uint8Array) => Array.from(data instanceof Uint8Array ? data : new Uint8Array(data), n => n.toString(16).padStart(2, '0')).join('');
|
||||
function unhex(value: unknown, length: number): Uint8Array<ArrayBuffer> {
|
||||
if (typeof value !== 'string' || value.length !== length * 2 || !/^[0-9a-f]+$/.test(value)) throw new Error('Invalid device identity.');
|
||||
return Uint8Array.from(value.match(/../g)!, n => parseInt(n, 16));
|
||||
}
|
||||
export function parseHello(value: unknown): IdentityHello {
|
||||
if (!isRecord(value)) throw new Error('Invalid device identity.');
|
||||
unhex(value.key, 65); unhex(value.nonce, 32);
|
||||
if (!(value.key as string).startsWith('04')) throw new Error('Invalid device identity.');
|
||||
return { key: value.key as string, nonce: value.nonce as string };
|
||||
}
|
||||
export async function createIdentity(): Promise<Identity> {
|
||||
// Extractable for explicit password-encrypted backups. Stored as a CryptoKey,
|
||||
// never plaintext JSON. Same-origin JavaScript can still use/export this key.
|
||||
const pair = await crypto.subtle.generateKey(curve, true, ['sign', 'verify']);
|
||||
return { publicKey: hex(await crypto.subtle.exportKey('raw', pair.publicKey)), privateKey: pair.privateKey };
|
||||
}
|
||||
export function hello(identity: Identity): IdentityHello {
|
||||
return { key: identity.publicKey, nonce: hex(crypto.getRandomValues(new Uint8Array(32))) };
|
||||
}
|
||||
function transcript(context: IdentityContext, initiator: boolean) {
|
||||
const offer = parseHello(context.offer), answer = parseHello(context.answer);
|
||||
const fingerprint = /^(?:[0-9A-F]{2} ){31}[0-9A-F]{2}$/;
|
||||
if (!fingerprint.test(context.offerFingerprint) || !fingerprint.test(context.answerFingerprint)) throw new Error('Invalid identity session binding.');
|
||||
return bytes(JSON.stringify(['HellCon device proof', 1, 4, initiator ? 'offerer' : 'answerer', offer.key, offer.nonce, answer.key, answer.nonce, context.offerFingerprint, context.answerFingerprint]));
|
||||
}
|
||||
export async function signIdentity(identity: Identity, context: IdentityContext, initiator: boolean) {
|
||||
if (identity.publicKey !== (initiator ? context.offer : context.answer).key) throw new Error('Device identity changed. Start a new connection.');
|
||||
return hex(await crypto.subtle.sign(signing, identity.privateKey, transcript(context, initiator)));
|
||||
}
|
||||
export async function verifyIdentity(proof: unknown, context: IdentityContext, initiator: boolean) {
|
||||
const key = await crypto.subtle.importKey('raw', unhex((initiator ? context.offer : context.answer).key, 65), curve, false, ['verify']);
|
||||
if (!await crypto.subtle.verify(signing, key, unhex(proof, 64), transcript(context, initiator))) throw new Error('Device proof failed. Disconnect and verify fresh codes.');
|
||||
}
|
||||
export function validateContacts(value: unknown): Contact[] {
|
||||
if (!Array.isArray(value) || value.length > 100) throw new Error('Invalid contact list.');
|
||||
const keys = new Set<string>();
|
||||
return value.map(item => {
|
||||
if (!isRecord(item) || typeof item.name !== 'string' || !item.name.trim() || item.name.length > 80) throw new Error('Invalid contact name.');
|
||||
unhex(item.key, 65);
|
||||
const key = item.key as string;
|
||||
if (keys.has(key)) throw new Error('Duplicate contact identity.');
|
||||
keys.add(key); return { key, name: item.name.trim() };
|
||||
});
|
||||
}
|
||||
|
||||
async function database() {
|
||||
return new Promise<IDBDatabase>((resolve, reject) => {
|
||||
const request = indexedDB.open('hellcon-devices', 1);
|
||||
request.onupgradeneeded = () => request.result.createObjectStore('settings');
|
||||
request.onsuccess = () => { request.result.onversionchange = () => request.result.close(); resolve(request.result); };
|
||||
request.onerror = () => reject(new Error('Device storage is unavailable. Use a temporary connection.'));
|
||||
request.onblocked = () => reject(new Error('Close other HellCon tabs and try again.'));
|
||||
});
|
||||
}
|
||||
export async function loadIdentityState(): Promise<IdentityState> {
|
||||
const db = await database();
|
||||
try {
|
||||
const state = await new Promise<IdentityState | undefined>((resolve, reject) => {
|
||||
const tx = db.transaction('settings', 'readonly');
|
||||
const request = tx.objectStore('settings').get('state');
|
||||
tx.oncomplete = () => resolve(request.result); tx.onabort = tx.onerror = () => reject(new Error('Could not read device storage.'));
|
||||
});
|
||||
if (!state) return { identity: null, contacts: [] };
|
||||
validateContacts(state.contacts);
|
||||
if (state.identity) {
|
||||
unhex(state.identity.publicKey, 65);
|
||||
if (!(state.identity.privateKey instanceof CryptoKey) || state.identity.privateKey.type !== 'private') throw new Error('Stored identity is invalid. Reset it or restore a backup.');
|
||||
}
|
||||
return state;
|
||||
} finally { db.close(); }
|
||||
}
|
||||
export async function saveIdentityState(state: IdentityState, expectedRevision = state.revision): Promise<IdentityState> {
|
||||
validateContacts(state.contacts);
|
||||
const db = await database();
|
||||
const next = { ...state, revision: crypto.randomUUID() };
|
||||
try {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const tx = db.transaction('settings', 'readwrite');
|
||||
const store = tx.objectStore('settings');
|
||||
const current = store.get('state');
|
||||
let conflict = false;
|
||||
current.onsuccess = () => {
|
||||
if (current.result?.revision !== expectedRevision) { conflict = true; tx.abort(); }
|
||||
else store.put(next, 'state');
|
||||
};
|
||||
tx.oncomplete = () => resolve();
|
||||
tx.onabort = tx.onerror = () => reject(new Error(conflict ? 'Device settings changed in another tab. Reload before editing them.' : 'Could not save device storage. Use a temporary connection.'));
|
||||
});
|
||||
return next;
|
||||
} finally { db.close(); }
|
||||
}
|
||||
export async function clearIdentityStorage() {
|
||||
const db = await database();
|
||||
try {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const tx = db.transaction('settings', 'readwrite');
|
||||
tx.objectStore('settings').delete('state');
|
||||
tx.oncomplete = () => resolve(); tx.onabort = tx.onerror = () => reject(new Error('Could not clear device storage.'));
|
||||
});
|
||||
} finally { db.close(); }
|
||||
}
|
||||
const iterations = 600000;
|
||||
async function backupKey(password: string, salt: Uint8Array<ArrayBuffer>) {
|
||||
if (password.length < 12 || password.length > 1024) throw new Error('Use a backup password between 12 and 1024 characters.');
|
||||
const material = await crypto.subtle.importKey('raw', bytes(password), 'PBKDF2', false, ['deriveKey']);
|
||||
return crypto.subtle.deriveKey({ name: 'PBKDF2', hash: 'SHA-256', salt, iterations }, material, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']);
|
||||
}
|
||||
export async function exportBackup(state: IdentityState, password: string) {
|
||||
if (!state.identity) throw new Error('Create a device identity first.');
|
||||
const salt = crypto.getRandomValues(new Uint8Array(16)), iv = crypto.getRandomValues(new Uint8Array(12));
|
||||
const data = bytes(JSON.stringify({ key: await crypto.subtle.exportKey('jwk', state.identity.privateKey), publicKey: state.identity.publicKey, contacts: validateContacts(state.contacts) }));
|
||||
const encrypted = await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: bytes('HellCon backup v1') }, await backupKey(password, salt), data);
|
||||
return JSON.stringify({ format: 'hellcon-identity', version: 1, iterations, salt: hex(salt), iv: hex(iv), data: hex(encrypted) });
|
||||
}
|
||||
export async function importBackup(text: string, password: string): Promise<IdentityState> {
|
||||
if (text.length > 100000) throw new Error('Backup is too large.');
|
||||
try {
|
||||
const value: unknown = JSON.parse(text);
|
||||
if (!isRecord(value) || value.format !== 'hellcon-identity' || value.version !== 1 || value.iterations !== iterations || typeof value.data !== 'string' || value.data.length < 32) throw new Error();
|
||||
const decrypted = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: unhex(value.iv, 12), additionalData: bytes('HellCon backup v1') }, await backupKey(password, unhex(value.salt, 16)), unhex(value.data, value.data.length / 2));
|
||||
const payload: unknown = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(decrypted));
|
||||
if (!isRecord(payload) || !isRecord(payload.key)) throw new Error();
|
||||
const publicKey = payload.publicKey as string;
|
||||
const pub = await crypto.subtle.importKey('raw', unhex(publicKey, 65), curve, false, ['verify']);
|
||||
const privateKey = await crypto.subtle.importKey('jwk', payload.key, curve, true, ['sign']);
|
||||
const challenge = crypto.getRandomValues(new Uint8Array(32));
|
||||
if (!await crypto.subtle.verify(signing, pub, await crypto.subtle.sign(signing, privateKey, challenge), challenge)) throw new Error();
|
||||
return { identity: { publicKey, privateKey }, contacts: validateContacts(payload.contacts) };
|
||||
} catch { throw new Error('Could not restore backup. Check the password and backup file.'); }
|
||||
}
|
||||
Reference in new issue
Block a user