Repository Public
1// SPV1 key hierarchy: ARK, account keyset, device certificates, ARK envelopes, recovery, vault keys, pairing.2import { type Bytes, b64u, concat, ctEqual, ctx, fromUtf8, random, unb64u, utf8 } from "./bytes.ts";3import {4 type KeyPair, aeadOpen, aeadSeal, exportPrivateX963, generateKemKey, generateSigKey, hkdf, hmac, hpkeOpen, hpkeSeal,5 importPrivateX963, sha256, sign, verify,6} from "./primitives.ts";78const EMPTY = new Uint8Array(0);910// ── Account keyset ────────────────────────────────────────────────────────────────────────────────────────────1112export interface AccountKeys { sig: KeyPair; enc: KeyPair }13export interface KeysetBlob { nonce: string; ct: string }1415export async function generateAccountKeys(): Promise<AccountKeys> {16 // extractable once, to be serialized into the encrypted keyset; re-imported non-extractable on every unlock17 return { sig: await generateSigKey(true), enc: await generateKemKey(true) };18}1920const keysetKey = (ark: Bytes, accountId: string) => hkdf(ark, EMPTY, ctx("keyset-key", accountId));2122export async function sealKeyset(ark: Bytes, accountId: string, keys: AccountKeys): Promise<KeysetBlob> {23 const pt = utf8(JSON.stringify({ sig: b64u(await exportPrivateX963(keys.sig.privateKey)), enc: b64u(await exportPrivateX963(keys.enc.privateKey)) }));24 return sealKeysetRaw(ark, accountId, pt, random(12));25}26export async function sealKeysetRaw(ark: Bytes, accountId: string, pt: Bytes, nonce: Bytes): Promise<KeysetBlob> {27 return { nonce: b64u(nonce), ct: b64u(await aeadSeal(await keysetKey(ark, accountId), nonce, pt, ctx("keyset", accountId))) };28}2930export async function openKeyset(ark: Bytes, accountId: string, blob: KeysetBlob): Promise<AccountKeys> {31 const pt = await aeadOpen(await keysetKey(ark, accountId), unb64u(blob.nonce), unb64u(blob.ct), ctx("keyset", accountId));32 const j = JSON.parse(fromUtf8(pt)) as { sig: string; enc: string };33 return { sig: await importPrivateX963(unb64u(j.sig), "sig"), enc: await importPrivateX963(unb64u(j.enc), "kem") };34}3536/** Re-encrypts the keyset under a new ARK without changing the account keys (account rekey). */37export async function rewrapKeyset(oldArk: Bytes, newArk: Bytes, accountId: string, blob: KeysetBlob): Promise<KeysetBlob> {38 const pt = await aeadOpen(await keysetKey(oldArk, accountId), unb64u(blob.nonce), unb64u(blob.ct), ctx("keyset", accountId));39 return sealKeysetRaw(newArk, accountId, pt, random(12));40}4142// ── Devices ───────────────────────────────────────────────────────────────────────────────────────────────────4344export interface DeviceKeys { enc: { privateKey: CryptoKey; publicKey: CryptoKey; pub: Bytes }; sig: { privateKey: CryptoKey; publicKey: CryptoKey; pub: Bytes } }45export interface DevicePublic { deviceId: string; encPub: string; sigPub: string; createdAt: string; cert: string }4647export async function generateDeviceKeys(): Promise<DeviceKeys> {48 return { enc: await generateKemKey(false), sig: await generateSigKey(false) }; // non-extractable49}5051const certMsg = (accountId: string, d: Omit<DevicePublic, "cert">) => ctx("device-cert", accountId, d.deviceId, d.encPub, d.sigPub, d.createdAt);5253export async function signDeviceCert(account: AccountKeys, accountId: string, d: Omit<DevicePublic, "cert">): Promise<string> {54 return b64u(await sign(account.sig.privateKey, certMsg(accountId, d)));55}56export async function verifyDeviceCert(accountSigPub: Bytes, accountId: string, d: DevicePublic): Promise<boolean> {57 try { return await verify(accountSigPub, certMsg(accountId, d), unb64u(d.cert)); } catch { return false; }58}5960export const wrapArkForDevice = async (ark: Bytes, accountId: string, deviceId: string, devEncPub: Bytes): Promise<string> =>61 b64u(await hpkeSeal(devEncPub, ctx("ark-wrap", accountId, deviceId), ark));6263export async function unwrapArk(device: DeviceKeys, accountId: string, deviceId: string, envelope: string): Promise<Bytes> {64 const ark = await hpkeOpen(device.enc, ctx("ark-wrap", accountId, deviceId), unb64u(envelope));65 if (ark.length !== 32) throw new Error("invalid ARK");66 return ark;67}6869// ── Recovery key ──────────────────────────────────────────────────────────────────────────────────────────────7071const B32 = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"; // Crockford7273async function rkChecksum(rk: Bytes): Promise<Bytes> { return (await sha256(concat(utf8("SPV1 recovery checksum"), rk))).slice(0, 3); }7475export async function encodeRecoveryKey(rk: Bytes): Promise<string> {76 if (rk.length !== 32) throw new Error("recovery key must be 32 bytes");77 const data = concat(rk, await rkChecksum(rk)); // 35 bytes = 280 bits = 56 chars78 let bits = 0, acc = 0, out = "";79 for (const byte of data) { acc = (acc << 8) | byte; bits += 8; while (bits >= 5) { out += B32[(acc >> (bits - 5)) & 31]; bits -= 5; } acc &= (1 << bits) - 1; }80 return "SPV1-" + out.match(/.{4}/g)!.join("-");81}8283export async function decodeRecoveryKey(text: string): Promise<Bytes> {84 // tolerant: case, separators, O→0, I/L→1 (also inside the prefix); the prefix is dropped only when the length shows it is there85 let s = text.toUpperCase().replace(/[\s-]/g, "").replace(/O/g, "0").replace(/[IL]/g, "1");86 if (s.length === 60 && s.startsWith("SPV1")) s = s.slice(4);87 if (s.length !== 56 || [...s].some((c) => !B32.includes(c))) throw new Error("recovery key is malformed");88 const data = new Uint8Array(35);89 let bits = 0, acc = 0, o = 0;90 for (const c of s) { acc = (acc << 5) | B32.indexOf(c); bits += 5; if (bits >= 8) { data[o++] = (acc >> (bits - 8)) & 0xff; bits -= 8; acc &= (1 << bits) - 1; } }91 const rk = data.slice(0, 32);92 if (!ctEqual(data.slice(32), await rkChecksum(rk))) throw new Error("recovery key checksum mismatch (typo?)");93 return rk;94}9596export const generateRecoveryKey = (): Bytes => random(32);9798export const recoveryAuth = (rk: Bytes, accountId: string) => hkdf(rk, EMPTY, ctx("recovery-auth", accountId));99export async function recoveryAuthHash(rk: Bytes, accountId: string): Promise<string> { return b64u(await sha256(await recoveryAuth(rk, accountId))); }100101export async function sealRecoveryEnvelope(rk: Bytes, accountId: string, epoch: number, ark: Bytes, nonce: Bytes = random(12)): Promise<string> {102 const k = await hkdf(rk, EMPTY, ctx("recovery-wrap", accountId));103 return b64u(concat(nonce, await aeadSeal(k, nonce, ark, ctx("recovery", accountId, epoch))));104}105export async function openRecoveryEnvelope(rk: Bytes, accountId: string, epoch: number, envelope: string): Promise<Bytes> {106 const raw = unb64u(envelope);107 const k = await hkdf(rk, EMPTY, ctx("recovery-wrap", accountId));108 const ark = await aeadOpen(k, raw.slice(0, 12), raw.slice(12), ctx("recovery", accountId, epoch));109 if (ark.length !== 32) throw new Error("invalid ARK");110 return ark;111}112113// ── Vault keys ────────────────────────────────────────────────────────────────────────────────────────────────114115export type Role = "owner" | "editor" | "reader";116export interface VaultGrant { vaultId: string; epoch: number; memberAccountId: string; role: Role; envelope: string; granterAccountId: string; sig: string }117118const grantMsg = async (g: Omit<VaultGrant, "sig" | "granterAccountId">) =>119 ctx("vault-grant", g.vaultId, g.epoch, g.memberAccountId, g.role, b64u(await sha256(unb64u(g.envelope))));120121export async function grantVaultKey(granter: AccountKeys, granterAccountId: string, vk: Bytes, vaultId: string, epoch: number, memberAccountId: string, memberEncPub: Bytes, role: Role): Promise<VaultGrant> {122 if (vk.length !== 32) throw new Error("vault key must be 32 bytes");123 const envelope = b64u(await hpkeSeal(memberEncPub, ctx("vault-key", vaultId, epoch, memberAccountId), vk));124 const base = { vaultId, epoch, memberAccountId, role, envelope };125 return { ...base, granterAccountId, sig: b64u(await sign(granter.sig.privateKey, await grantMsg(base))) };126}127128/** Verifies the granter's signature, then unwraps the vault key with the member's account encryption key. */129export async function acceptVaultGrant(member: AccountKeys, grant: VaultGrant, granterSigPub: Bytes): Promise<Bytes> {130 if (!(await verify(granterSigPub, await grantMsg(grant), unb64u(grant.sig)))) throw new Error("vault grant signature invalid");131 const vk = await hpkeOpen(member.enc, ctx("vault-key", grant.vaultId, grant.epoch, grant.memberAccountId), unb64u(grant.envelope));132 if (vk.length !== 32) throw new Error("invalid vault key");133 return vk;134}135136// ── Pairing ───────────────────────────────────────────────────────────────────────────────────────────────────137138export const pairingTag = async (secret: Bytes, pairingId: string, encPub: string, sigPub: string): Promise<string> =>139 b64u(await hmac(secret, ctx("pair", pairingId, encPub, sigPub)));140141export async function verifyPairingTag(secret: Bytes, pairingId: string, encPub: string, sigPub: string, tag: string): Promise<boolean> {142 try { return ctEqual(unb64u(tag), unb64u(await pairingTag(secret, pairingId, encPub, sigPub))); } catch { return false; }143}144145/** 6-digit fingerprint both devices display. */146export async function pairingSas(pairingId: string, encPub: string, sigPub: string): Promise<string> {147 const h = await sha256(ctx("sas", pairingId, encPub, sigPub));148 const n = ((h[0]! << 24) | (h[1]! << 16) | (h[2]! << 8) | h[3]!) >>> 0;149 return String(n % 1_000_000).padStart(6, "0");150}151152export const encodePairingCode = (pairingId: string, secret: Bytes) => `spvault-pair:${pairingId}:${b64u(secret)}`;153export function decodePairingCode(code: string): { pairingId: string; secret: Bytes } {154 const m = /^spvault-pair:([0-9a-f-]{36}):([A-Za-z0-9_-]{22})$/.exec(code.trim());155 if (!m) throw new Error("not an SP Vault pairing code");156 return { pairingId: m[1]!, secret: unb64u(m[2]!) };157}158159/** Short fingerprint of an account's public keys, for out-of-band comparison when sharing. */160export async function accountFingerprint(sigPub: Bytes, encPub: Bytes): Promise<string> {161 const h = await sha256(ctx("account-fp", b64u(sigPub), b64u(encPub)));162 return Array.from(h.slice(0, 10), (x) => x.toString(16).padStart(2, "0")).join("").toUpperCase().match(/.{4}/g)!.join(" ");163}164