99 lines
5.9 KiB
TypeScript
99 lines
5.9 KiB
TypeScript
import { isRecord } from './validation.ts';
|
|
|
|
export interface Identity { publicKey: string; privateKey: CryptoKey }
|
|
export interface IdentityHello { key: string; nonce: string }
|
|
export interface IdentityState { revision?: string; identity: Identity | null }
|
|
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> {
|
|
// Store the private key as a non-extractable CryptoKey. Same-origin JavaScript
|
|
// can still use it to sign, so the app code must remain trusted.
|
|
const pair = await crypto.subtle.generateKey(curve, false, ['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.');
|
|
}
|
|
|
|
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 };
|
|
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. Clear device storage and create a new identity.');
|
|
}
|
|
return { revision: state.revision, identity: state.identity ?? null };
|
|
} finally { db.close(); }
|
|
}
|
|
export async function saveIdentityState(state: IdentityState, expectedRevision = state.revision): Promise<IdentityState> {
|
|
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(); }
|
|
}
|