// Local-device identity helpers for the chirp-sync architecture. // // `deviceId` is a stable UUID v4 generated on first call and persisted in // `chrome.storage.sync` so it roams across browser-profile reinstalls. // // `deviceName` defaults to a short, friendly browser+OS description and // can be overridden by the user from Settings → Sync. // // The local sync identity itself is derived deterministically from the // vault master key (`deriveSyncIdentityKeypair`); the function below is a // thin coordinator that pulls the master key out of `vault.ts` and exposes // only the public half to callers that don't need to sign. import { deriveSyncIdentityKeypair, pubkeyToHex } from "../shared/sync-identity"; import type { DeviceType } from "../shared/sync-types"; const DEVICE_ID_KEY = "peach_chirp_device_id"; const DEVICE_NAME_KEY = "peach_chirp_device_name"; export interface LocalChirpIdentity { deviceId: string; deviceName: string; deviceType: DeviceType; longTermPublicKeyHex: string; } export async function getOrCreateDeviceId(): Promise { const result = await chrome.storage.sync.get(DEVICE_ID_KEY); const current = (result as Record)[DEVICE_ID_KEY]; if (typeof current === "string" && current.length > 0) return current; const fresh = generateUuidV4(); await chrome.storage.sync.set({ [DEVICE_ID_KEY]: fresh }); return fresh; } export async function getDeviceName(): Promise { const result = await chrome.storage.sync.get(DEVICE_NAME_KEY); const stored = (result as Record)[DEVICE_NAME_KEY]; if (typeof stored === "string" && stored.length > 0) return stored; return defaultDeviceName(); } export async function setDeviceName(name: string): Promise { const trimmed = name.trim(); if (!trimmed) throw new Error("device name must not be empty"); if (trimmed.length > 64) throw new Error("device name must be 64 chars or fewer"); await chrome.storage.sync.set({ [DEVICE_NAME_KEY]: trimmed }); } /** * Build the public-facing identity record for the local extension. The * private key half (used only for ongoing Noise XX sessions) is not * exposed by this function — Phase-1 pairing uses ephemeral keys only. */ export async function buildLocalIdentity( masterKey: Uint8Array, ): Promise { const deviceId = await getOrCreateDeviceId(); const deviceName = await getDeviceName(); const kp = deriveSyncIdentityKeypair(masterKey, deviceId); return { deviceId, deviceName, deviceType: extensionDeviceType(), longTermPublicKeyHex: pubkeyToHex(kp.publicKey), }; } /** * Return the local sync identity keypair (public and private). Reserved * for the Phase-2 WebSocket sync coordinator that runs in the background. * Never surface the private key over a message handler. */ export function deriveLocalSyncKeypair(masterKey: Uint8Array, deviceId: string) { return deriveSyncIdentityKeypair(masterKey, deviceId); } function defaultDeviceName(): string { // Best-effort browser + platform string. Avoids userAgent parsing — the // user can rename via Settings. const ua = (typeof navigator !== "undefined" ? navigator.userAgent : "") || ""; if (/Firefox/i.test(ua)) return "Firefox"; if (/Edg\//i.test(ua)) return "Edge"; if (/Chrome/i.test(ua)) return "Chrome"; if (/Safari/i.test(ua)) return "Safari"; return "Browser"; } function extensionDeviceType(): DeviceType { // The same module ships in both the Chrome extension and the Capacitor // mobile build. On Capacitor, Peach acts as an iOS / Android sync host // rather than an extension; the `isNativePlatform` check toggles the tag. try { const native = (globalThis as unknown as { Capacitor?: { isNativePlatform?: () => boolean } }).Capacitor; if (native?.isNativePlatform?.()) { const platform = (globalThis as unknown as { Capacitor?: { getPlatform?: () => string } }).Capacitor?.getPlatform?.(); if (platform === "ios") return "ios"; return "android"; } } catch { /* not on Capacitor */ } return "extension"; } function generateUuidV4(): string { // crypto.randomUUID is available in MV3 service workers, popup pages, // and modern Capacitor WebView. Falls back to a manual assembly only if // a runtime is missing it (effectively unreachable for our targets). if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") { return crypto.randomUUID(); } const bytes = new Uint8Array(16); crypto.getRandomValues(bytes as Uint8Array); bytes[6] = (bytes[6] & 0x0f) | 0x40; bytes[8] = (bytes[8] & 0x3f) | 0x80; const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(""); return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; }