1234567891011121314151617181920212223import type { DeviceRevocation, PairedDevice } from "../shared/sync-types";24import { constantTimeEqualHex } from "../shared/constant-time";25import { clampSyncTimestamp } from "../shared/sync-limits";26import type { SyncOutcome } from "../shared/sync-outcome";2728const REGISTRY_KEY = "peach_paired_devices_v3";29const REVOCATIONS_KEY = "peach_device_revocations_v1";3031const MAX_REVOCATIONS = 500;32const LAST_IP_KEY_PREFIX = "peach_last_known_ip_v3:";33const LAST_SYNC_AT_KEY = "peach_last_sync_at";34const LAST_SYNC_RESULT_KEY = "peach_last_sync_result";3536export async function listPairedDevices(): Promise<PairedDevice[]> {37 try {38 const result = await chrome.storage.local.get(REGISTRY_KEY);39 const devices = (result as Record<string, unknown>)[REGISTRY_KEY];40 if (Array.isArray(devices)) return devices.filter(isPairedDevice);41 return [];42 } catch {43 return [];44 }45}4647export async function findPairedDeviceById(deviceId: string): Promise<PairedDevice | null> {48 const devices = await listPairedDevices();49 return devices.find((d) => d.deviceId === deviceId) ?? null;50}5152export async function findPairedDeviceByPubkey(pubkeyHex: string): Promise<PairedDevice | null> {53 const devices = await listPairedDevices();54 return devices.find((d) =>55 d.longTermPublicKeyHex !== undefined &&56 constantTimeEqualHex(d.longTermPublicKeyHex, pubkeyHex)57 ) ?? null;58}59606162636465export async function upsertPairedDevice(device: PairedDevice): Promise<void> {66 if (!device.deviceId) throw new Error("device.deviceId is required");67 if (!device.longTermPublicKeyHex) throw new Error("device.longTermPublicKeyHex is required");68 if (!device.deviceName) throw new Error("device.deviceName is required");69 if (!device.deviceType) throw new Error("device.deviceType is required");7071 const devices = await listPairedDevices();72 const idx = devices.findIndex((d) => d.deviceId === device.deviceId);73 if (idx >= 0) {74 devices[idx] = { ...devices[idx], ...device };75 } else {76 devices.push(device);77 }78 await chrome.storage.local.set({ [REGISTRY_KEY]: devices });79 80 81 82 83}8485868788899091export async function setRelayUrlForAllPairedDevices(92 relayUrl: string,93): Promise<void> {94 const devices = await listPairedDevices();95 if (devices.length === 0) return;96 await chrome.storage.local.set({97 [REGISTRY_KEY]: devices.map((device) => ({ ...device, relayUrl })),98 });99 100 101 102}103104105106107108109110111112113114115116117118export async function removePairedDeviceById(deviceId: string): Promise<void> {119 const devices = await listPairedDevices();120 const filtered = devices.filter((d) => d.deviceId !== deviceId);121 122 123 124 await chrome.storage.local.set({ [REGISTRY_KEY]: filtered });125 126 const device = devices.find((d) => d.deviceId === deviceId);127 if (device?.longTermPublicKeyHex) {128 await chrome.storage.local.remove(LAST_IP_KEY_PREFIX + device.longTermPublicKeyHex);129 }130 131 132}133134135136137138export async function listDeviceRevocations(): Promise<DeviceRevocation[]> {139 try {140 const result = await chrome.storage.local.get(REVOCATIONS_KEY);141 const value = (result as Record<string, unknown>)[REVOCATIONS_KEY];142 if (Array.isArray(value)) return value.filter(isDeviceRevocation);143 return [];144 } catch {145 return [];146 }147}148149150151152153154155156157export async function isDeviceRevoked(158 deviceId: string,159 longTermPublicKeyHex?: string,160): Promise<boolean> {161 162 163 const key = longTermPublicKeyHex?.toLowerCase();164 const keyIsRevocable = key !== undefined && key !== "0".repeat(64);165 return (await listDeviceRevocations()).some(166 (r) =>167 r.deviceId === deviceId ||168 (keyIsRevocable && r.longTermPublicKeyHex.toLowerCase() === key),169 );170}171172173174175176177178179export async function revokeDeviceById(180 deviceId: string,181 revokedByDeviceId: string,182 options: { now?: number } = {},183): Promise<DeviceRevocation | null> {184 const device = await findPairedDeviceById(deviceId);185 const existing = await listDeviceRevocations();186 if (existing.some((r) => r.deviceId === deviceId)) return null;187188 const record: DeviceRevocation = {189 deviceId,190 191 192 193 longTermPublicKeyHex: device?.longTermPublicKeyHex ?? "0".repeat(64),194 revokedAt: options.now ?? Date.now(),195 revokedByDeviceId,196 };197 await storeRevocations([...existing, record]);198 await removePairedDeviceById(deviceId);199 return record;200}201202203204205206207208209210export async function mergeDeviceRevocations(211 incoming: DeviceRevocation[],212): Promise<string[]> {213 const existing = await listDeviceRevocations();214 const known = new Set(existing.map((r) => r.deviceId));215 const fresh = incoming216 .filter((r) => !known.has(r.deviceId))217 218 219 220 .map((r) => ({ ...r, revokedAt: clampSyncTimestamp(r.revokedAt) }));221 if (fresh.length === 0) return [];222 await storeRevocations([...existing, ...fresh].slice(-MAX_REVOCATIONS));223 return fresh.map((r) => r.deviceId);224}225226227228229230231232export async function clearDeviceRevocation(deviceId: string): Promise<void> {233 const existing = await listDeviceRevocations();234 const filtered = existing.filter((r) => r.deviceId !== deviceId);235 if (filtered.length === existing.length) return;236 await storeRevocations(filtered);237}238239async function storeRevocations(records: DeviceRevocation[]): Promise<void> {240 await chrome.storage.local.set({ [REVOCATIONS_KEY]: records });241}242243function isDeviceRevocation(x: unknown): x is DeviceRevocation {244 if (typeof x !== "object" || x === null) return false;245 const r = x as Record<string, unknown>;246 return (247 typeof r.deviceId === "string" &&248 !!r.deviceId &&249 typeof r.longTermPublicKeyHex === "string" &&250 typeof r.revokedAt === "number" &&251 typeof r.revokedByDeviceId === "string"252 );253}254255export async function clearPairedDevices(): Promise<void> {256 await chrome.storage.local.remove(REGISTRY_KEY);257}258259export async function markLastSyncedAt(deviceId: string, when: number): Promise<void> {260 const devices = await listPairedDevices();261 const idx = devices.findIndex((d) => d.deviceId === deviceId);262 if (idx < 0) return;263 devices[idx] = { ...devices[idx], lastSyncedAt: when };264 await chrome.storage.local.set({ [REGISTRY_KEY]: devices });265}266267export async function getLastKnownIp(pubkeyHex: string): Promise<string | null> {268 try {269 const key = LAST_IP_KEY_PREFIX + pubkeyHex;270 const result = await chrome.storage.local.get(key);271 const value = (result as Record<string, unknown>)[key];272 return typeof value === "string" ? value : null;273 } catch {274 return null;275 }276}277278export async function setLastKnownIp(pubkeyHex: string, ip: string): Promise<void> {279 await chrome.storage.local.set({ [LAST_IP_KEY_PREFIX + pubkeyHex]: ip });280}281282export async function clearLastKnownIp(pubkeyHex: string): Promise<void> {283 await chrome.storage.local.remove(LAST_IP_KEY_PREFIX + pubkeyHex);284}285286export async function getLastSyncAt(): Promise<number | null> {287 try {288 const result = await chrome.storage.local.get(LAST_SYNC_AT_KEY);289 const value = (result as Record<string, unknown>)[LAST_SYNC_AT_KEY];290 if (typeof value === "number") return value;291 if (typeof value === "string" && value !== "") {292 const n = Number.parseInt(value, 10);293 return Number.isFinite(n) ? n : null;294 }295 return null;296 } catch {297 return null;298 }299}300301export async function setLastSyncAt(when: number): Promise<void> {302 await chrome.storage.local.set({ [LAST_SYNC_AT_KEY]: when });303}304305306307308309310311export interface SyncResult {312 outcome: SyncOutcome;313 detail?: string;314 315 at: number;316 entriesReceived: number;317 entriesSent: number;318}319320export async function getLastSyncResult(): Promise<SyncResult | null> {321 try {322 const result = await chrome.storage.local.get(LAST_SYNC_RESULT_KEY);323 const value = (result as Record<string, unknown>)[LAST_SYNC_RESULT_KEY];324 if (325 value &&326 typeof value === "object" &&327 typeof (value as Record<string, unknown>).outcome === "string" &&328 typeof (value as Record<string, unknown>).at === "number" &&329 typeof (value as Record<string, unknown>).entriesReceived === "number" &&330 typeof (value as Record<string, unknown>).entriesSent === "number"331 ) {332 return value as SyncResult;333 }334 return null;335 } catch {336 return null;337 }338}339340export async function setLastSyncResult(result: SyncResult): Promise<void> {341 await chrome.storage.local.set({ [LAST_SYNC_RESULT_KEY]: result });342}343344function isPairedDevice(x: unknown): x is PairedDevice {345 if (typeof x !== "object" || x === null) return false;346 const r = x as Record<string, unknown>;347 if (typeof r.deviceId !== "string" || !r.deviceId) return false;348 if (typeof r.pairedAt !== "number") return false;349 if (350 r.rendezvousSecretHex !== undefined &&351 (typeof r.rendezvousSecretHex !== "string" || !/^[0-9a-f]{64}$/.test(r.rendezvousSecretHex))352 ) {353 return false;354 }355 if (r.relayUrl !== undefined) {356 if (typeof r.relayUrl !== "string") return false;357 try {358 if (new URL(r.relayUrl).protocol !== "wss:") return false;359 } catch {360 return false;361 }362 }363 return true;364}