// Device manifest — v2 brief §4.3. // // A device manifest is a list of paired-device entries, signed by the // issuer's random per-installation Ed25519 signing key (the local device // identity in src/background/device-identity.ts). // Manifests are exchanged after the entry sync completes during a normal // `SyncSession`, encrypted under reconnect Noise KK along with everything else. // // Purpose: propagate trust between devices without repeating first-pair // confirmation. Any already-admitted, Noise-authenticated mesh peer may issue // a manifest. That makes membership a convergent pool instead of a graph whose // updates still depend on the device that performed the original pairing. // The receiver verifies the signature against that issuer's known Ed25519 // public key. A v3 entry that carries a valid relay route is auto-admitted as // same-vault "vouched" state and may propagate that signed graph onward. // See docs/mesh-vouching-authority.md for the full authority trace. // // Security properties: // - Authenticity: Ed25519 signature over a canonicalised JSON body. // Receiver rejects any manifest whose signature does not verify // against the issuer's stored signing pubkey. // - Freshness: `issuedAt` must be within DEVICE_MANIFEST_FRESHNESS_MS // of the receiver's clock; older manifests are silently discarded. // - Vault binding: the manifest is exchanged over Noise KK which has already // proven both locally-paired vault-derived static keys. import { DEVICE_MANIFEST_FRESHNESS_MS, DEVICE_MANIFEST_VERSION, DEVICE_REVOCATION_RECORD_VERSION, MAX_VOUCH_DEPTH, type DeviceManifestBody, type DeviceRevocation, type ManifestDeviceEntry, type SignedDeviceManifest, } from "./sync-types"; import { signEd25519, verifyEd25519 } from "./sync-identity"; import { normalizeRelayUrl } from "./rendezvous"; import { capDeviceName } from "./sync-limits"; export class DeviceManifestError extends Error { readonly kind: | "version" | "freshness" | "signature" | "issuer_mismatch" | "malformed"; constructor(kind: DeviceManifestError["kind"], message: string) { super(message); this.kind = kind; } } /** * Build + sign a device manifest with `issuedAt = now`. * * The body is canonicalised before signing using a stable JSON encoder * (keys sorted, no insignificant whitespace) so any two implementations * of this codec produce byte-identical signing input from equal inputs. */ export async function buildSignedDeviceManifest( issuerDeviceId: string, devices: ManifestDeviceEntry[], signingPrivateKey: CryptoKey, options: { now?: number; revoked?: DeviceRevocation[] } = {}, ): Promise { if (!issuerDeviceId) throw new Error("issuerDeviceId is required"); const body: DeviceManifestBody = { manifestVersion: DEVICE_MANIFEST_VERSION, issuerDeviceId, issuedAt: options.now ?? Date.now(), devices: devices.map(normaliseEntry), revoked: (options.revoked ?? []).map(normaliseRevocation), }; const canonical = canonicalise(body); const signature = await signEd25519( signingPrivateKey, new TextEncoder().encode(canonical), ); return { body, signatureHex: bytesToHex(signature) }; } /** Canonical fields authenticated by an issuer for one revocation record. */ export function canonicalDeviceRevocation(record: DeviceRevocation): string { return canonicalise({ deviceId: record.deviceId, longTermPublicKeyHex: record.longTermPublicKeyHex.toLowerCase(), recordVersion: record.recordVersion ?? DEVICE_REVOCATION_RECORD_VERSION, revokedAt: record.revokedAt, revokedByDeviceId: record.revokedByDeviceId, }); } export async function signDeviceRevocation( record: DeviceRevocation, signingPrivateKey: CryptoKey, ): Promise { const unsigned: DeviceRevocation = { ...record, longTermPublicKeyHex: record.longTermPublicKeyHex.toLowerCase(), recordVersion: record.recordVersion ?? DEVICE_REVOCATION_RECORD_VERSION, }; const signature = await signEd25519( signingPrivateKey, new TextEncoder().encode(canonicalDeviceRevocation(unsigned)), ); return { ...unsigned, signatureHex: bytesToHex(signature) }; } export async function verifyDeviceRevocation( record: DeviceRevocation, issuerSigningPubkey: Uint8Array, ): Promise { if (!record.signatureHex || !/^[0-9a-f]{128}$/i.test(record.signatureHex)) return false; try { return await verifyEd25519( issuerSigningPubkey, new TextEncoder().encode(canonicalDeviceRevocation(record)), hexToBytes(record.signatureHex), ); } catch { return false; } } /** * Verify a manifest's signature, version, and freshness window. Throws on * any failure; returns the body on success. The caller is responsible for * looking up the issuer's signing pubkey from the paired-device registry * and passing it in — that lookup is what enforces "manifest from a known * device" (§4.3 final paragraph). */ export async function verifyDeviceManifest( manifest: SignedDeviceManifest, issuerSigningPubkey: Uint8Array, options: { now?: number; freshnessMs?: number } = {}, ): Promise { if (!manifest || typeof manifest !== "object") { throw new DeviceManifestError("malformed", "manifest is not an object"); } if (!manifest.body || !manifest.signatureHex) { throw new DeviceManifestError("malformed", "manifest missing body or signature"); } if (manifest.body.manifestVersion !== DEVICE_MANIFEST_VERSION) { throw new DeviceManifestError( "version", `unsupported manifest version ${manifest.body.manifestVersion}`, ); } const now = options.now ?? Date.now(); const freshness = options.freshnessMs ?? DEVICE_MANIFEST_FRESHNESS_MS; if ( typeof manifest.body.issuedAt !== "number" || Math.abs(now - manifest.body.issuedAt) > freshness ) { throw new DeviceManifestError( "freshness", `manifest issuedAt ${manifest.body.issuedAt} outside ±${freshness}ms window`, ); } const signature = hexToBytes(manifest.signatureHex); if (signature.length !== 64) { throw new DeviceManifestError("signature", "signature must be 64 bytes"); } const canonical = canonicalise(manifest.body); const ok = await verifyEd25519( issuerSigningPubkey, new TextEncoder().encode(canonical), signature, ); if (!ok) throw new DeviceManifestError("signature", "Ed25519 signature did not verify"); // Body shape — minimum guarantees the caller relies on. We do not // enforce uniqueness of deviceId here; the registry-upsert side handles // duplicates by deviceId. if (!Array.isArray(manifest.body.devices)) { throw new DeviceManifestError("malformed", "devices is not an array"); } for (const d of manifest.body.devices) { if (typeof d.deviceId !== "string" || !d.deviceId) { throw new DeviceManifestError("malformed", "device.deviceId missing"); } if (typeof d.deviceName !== "string" || !d.deviceName) { throw new DeviceManifestError("malformed", "device.deviceName missing"); } if ( d.deviceType !== "extension" && d.deviceType !== "android" && d.deviceType !== "ios" ) { throw new DeviceManifestError("malformed", "device.deviceType invalid"); } if (typeof d.longTermPublicKeyHex !== "string" || d.longTermPublicKeyHex.length !== 64) { throw new DeviceManifestError("malformed", "device.longTermPublicKeyHex invalid"); } if (typeof d.signingPublicKeyHex !== "string" || d.signingPublicKeyHex.length !== 64) { throw new DeviceManifestError("malformed", "device.signingPublicKeyHex invalid"); } if (d.vouchDepth != null && (!Number.isInteger(d.vouchDepth) || d.vouchDepth < 0 || d.vouchDepth > MAX_VOUCH_DEPTH)) { throw new DeviceManifestError("malformed", "device.vouchDepth invalid"); } if ( d.wsPort != null && ( typeof d.wsPort !== "number" || !Number.isInteger(d.wsPort) || d.wsPort < 0 || d.wsPort > 65535 ) ) { throw new DeviceManifestError("malformed", "device.wsPort invalid"); } if (d.relayUrl != null) { try { normalizeRelayUrl(d.relayUrl); } catch { throw new DeviceManifestError("malformed", "device.relayUrl invalid"); } } } if (!Array.isArray(manifest.body.revoked)) { throw new DeviceManifestError("malformed", "revoked is not an array"); } for (const r of manifest.body.revoked) { if (typeof r.deviceId !== "string" || !r.deviceId) { throw new DeviceManifestError("malformed", "revocation.deviceId missing"); } if ( typeof r.longTermPublicKeyHex !== "string" || !/^[0-9a-fA-F]{64}$/.test(r.longTermPublicKeyHex) ) { throw new DeviceManifestError( "malformed", "revocation.longTermPublicKeyHex invalid", ); } if (typeof r.revokedAt !== "number" || !Number.isFinite(r.revokedAt)) { throw new DeviceManifestError("malformed", "revocation.revokedAt invalid"); } if (typeof r.revokedByDeviceId !== "string" || !r.revokedByDeviceId) { throw new DeviceManifestError( "malformed", "revocation.revokedByDeviceId missing", ); } if ( r.recordVersion != null && r.recordVersion !== DEVICE_REVOCATION_RECORD_VERSION ) { throw new DeviceManifestError( "malformed", `revocation.recordVersion unsupported (${r.recordVersion})`, ); } } return manifest.body; } function normaliseRevocation(r: DeviceRevocation): DeviceRevocation { const normalised: DeviceRevocation = { deviceId: r.deviceId, longTermPublicKeyHex: r.longTermPublicKeyHex.toLowerCase(), revokedAt: r.revokedAt, revokedByDeviceId: r.revokedByDeviceId, recordVersion: r.recordVersion ?? DEVICE_REVOCATION_RECORD_VERSION, }; if (r.signatureHex != null) normalised.signatureHex = r.signatureHex.toLowerCase(); return normalised; } function normaliseEntry(d: ManifestDeviceEntry): ManifestDeviceEntry { const normalised: ManifestDeviceEntry = { deviceId: d.deviceId, deviceName: capDeviceName(d.deviceName), deviceType: d.deviceType, longTermPublicKeyHex: d.longTermPublicKeyHex.toLowerCase(), signingPublicKeyHex: d.signingPublicKeyHex.toLowerCase(), pairedAt: d.pairedAt, vouchDepth: d.vouchDepth ?? 0, }; if (d.wsPort != null) normalised.wsPort = d.wsPort; if (d.relayUrl != null) normalised.relayUrl = normalizeRelayUrl(d.relayUrl); return normalised; } /** * Canonical JSON serialiser. Sorts object keys, no trailing whitespace, * stable number formatting. The serialiser intentionally only handles the * narrow set of shapes that occur inside a `DeviceManifestBody` — extending * it later means extending these branches in lockstep with the schema. */ export function canonicalise(value: unknown): string { if (value === null) return "null"; if (typeof value === "number") { if (!Number.isFinite(value)) throw new Error("non-finite number"); return Number.isInteger(value) ? value.toString() : value.toString(); } if (typeof value === "string") return JSON.stringify(value); if (typeof value === "boolean") return value ? "true" : "false"; if (Array.isArray(value)) { return "[" + value.map((v) => canonicalise(v)).join(",") + "]"; } if (typeof value === "object") { const obj = value as Record; const keys = Object.keys(obj).sort(); // ponytail: skip null values so canonical bytes match Android's // manifestEntryMap, which omits wsPort and relayUrl when null. const present = keys.filter((k) => obj[k] !== null); return ( "{" + present.map((k) => JSON.stringify(k) + ":" + canonicalise(obj[k])).join(",") + "}" ); } throw new Error(`cannot canonicalise ${typeof value}`); } function bytesToHex(b: Uint8Array): string { let s = ""; for (let i = 0; i < b.length; i++) s += b[i].toString(16).padStart(2, "0"); return s; } function hexToBytes(hex: string): Uint8Array { if (hex.length % 2 !== 0) throw new DeviceManifestError("malformed", "odd-length hex"); const out = new Uint8Array(hex.length / 2); for (let i = 0; i < out.length; i++) { const b = parseInt(hex.slice(i * 2, i * 2 + 2), 16); if (Number.isNaN(b)) throw new DeviceManifestError("malformed", "bad hex"); out[i] = b; } return out; }