1234567891011121314151617181920212223import type { DeviceRevocation, PairedDevice } from "../shared/sync-types";24import { constantTimeEqualHex } from "../shared/constant-time";25import { clampSyncTimestamp } from "../shared/sync-limits";2627const REGISTRY_KEY = "peach_paired_devices_v3";28const REVOCATIONS_KEY = "peach_device_revocations_v1";2930const MAX_REVOCATIONS = 500;31const LAST_IP_KEY_PREFIX = "peach_last_known_ip_v3:";32const LAST_SYNC_AT_KEY = "peach_last_sync_at";33const LAST_SYNC_RESULT_KEY = "peach_last_sync_result";3435export async function listPairedDevices(): Promise<PairedDevice[]> {36 try {37 const result = await chrome.storage.local.get(REGISTRY_KEY);38 const devices = (result as Record<string, unknown>)[REGISTRY_KEY];39 if (Array.isArray(devices)) return devices.filter(isPairedDevice);40 return [];41 } catch {42 return [];43 }44}4546export async function findPairedDeviceById(deviceId: string): Promise<PairedDevice | null> {47 const devices = await listPairedDevices();48 return devices.find((d) => d.deviceId === deviceId) ?? null;49}5051export async function findPairedDeviceByPubkey(pubkeyHex: string): Promise<PairedDevice | null> {52 const devices = await listPairedDevices();53 return devices.find((d) =>54 d.longTermPublicKeyHex !== undefined &&55 constantTimeEqualHex(d.longTermPublicKeyHex, pubkeyHex)56 ) ?? null;57}58596061626364export async function upsertPairedDevice(device: PairedDevice): Promise<void> {65 if (!device.deviceId) throw new Error("device.deviceId is required");66 if (!device.longTermPublicKeyHex) throw new Error("device.longTermPublicKeyHex is required");67 if (!device.deviceName) throw new Error("device.deviceName is required");68 if (!device.deviceType) throw new Error("device.deviceType is required");6970 const devices = await listPairedDevices();71 const idx = devices.findIndex((d) => d.deviceId === device.deviceId);72 if (idx >= 0) {73 devices[idx] = { ...devices[idx], ...device };74 } else {75 devices.push(device);76 }77 await chrome.storage.local.set({ [REGISTRY_KEY]: devices });78}7980818283848586export async function setRelayUrlForAllPairedDevices(87 relayUrl: string,88): Promise<void> {89 const devices = await listPairedDevices();90 if (devices.length === 0) return;91 await chrome.storage.local.set({92 [REGISTRY_KEY]: devices.map((device) => ({ ...device, relayUrl })),93 });94}9596979899100101102103104105106107108109110export async function removePairedDeviceById(deviceId: string): Promise<void> {111 const devices = await listPairedDevices();112 const filtered = devices.filter((d) => d.deviceId !== deviceId);113 114 115 116 await chrome.storage.local.set({ [REGISTRY_KEY]: filtered });117 118 const device = devices.find((d) => d.deviceId === deviceId);119 if (device?.longTermPublicKeyHex) {120 await chrome.storage.local.remove(LAST_IP_KEY_PREFIX + device.longTermPublicKeyHex);121 }122}123124125126127128export async function listDeviceRevocations(): Promise<DeviceRevocation[]> {129 try {130 const result = await chrome.storage.local.get(REVOCATIONS_KEY);131 const value = (result as Record<string, unknown>)[REVOCATIONS_KEY];132 if (Array.isArray(value)) return value.filter(isDeviceRevocation);133 return [];134 } catch {135 return [];136 }137}138139export async function isDeviceRevoked(deviceId: string): Promise<boolean> {140 return (await listDeviceRevocations()).some((r) => r.deviceId === deviceId);141}142143144145146147148export async function revokeDeviceById(149 deviceId: string,150 revokedByDeviceId: string,151 options: { now?: number } = {},152): Promise<DeviceRevocation | null> {153 const device = await findPairedDeviceById(deviceId);154 const existing = await listDeviceRevocations();155 if (existing.some((r) => r.deviceId === deviceId)) return null;156157 const record: DeviceRevocation = {158 deviceId,159 160 161 162 longTermPublicKeyHex: device?.longTermPublicKeyHex ?? "0".repeat(64),163 revokedAt: options.now ?? Date.now(),164 revokedByDeviceId,165 };166 await storeRevocations([...existing, record]);167 await removePairedDeviceById(deviceId);168 return record;169}170171172173174175176177178179export async function mergeDeviceRevocations(180 incoming: DeviceRevocation[],181): Promise<string[]> {182 const existing = await listDeviceRevocations();183 const known = new Set(existing.map((r) => r.deviceId));184 const fresh = incoming185 .filter((r) => !known.has(r.deviceId))186 187 188 189 .map((r) => ({ ...r, revokedAt: clampSyncTimestamp(r.revokedAt) }));190 if (fresh.length === 0) return [];191 await storeRevocations([...existing, ...fresh].slice(-MAX_REVOCATIONS));192 return fresh.map((r) => r.deviceId);193}194195196197198199200201export async function clearDeviceRevocation(deviceId: string): Promise<void> {202 const existing = await listDeviceRevocations();203 const filtered = existing.filter((r) => r.deviceId !== deviceId);204 if (filtered.length === existing.length) return;205 await storeRevocations(filtered);206}207208async function storeRevocations(records: DeviceRevocation[]): Promise<void> {209 await chrome.storage.local.set({ [REVOCATIONS_KEY]: records });210}211212function isDeviceRevocation(x: unknown): x is DeviceRevocation {213 if (typeof x !== "object" || x === null) return false;214 const r = x as Record<string, unknown>;215 return (216 typeof r.deviceId === "string" &&217 !!r.deviceId &&218 typeof r.longTermPublicKeyHex === "string" &&219 typeof r.revokedAt === "number" &&220 typeof r.revokedByDeviceId === "string"221 );222}223224export async function clearPairedDevices(): Promise<void> {225 await chrome.storage.local.remove(REGISTRY_KEY);226}227228export async function markLastSyncedAt(deviceId: string, when: number): Promise<void> {229 const devices = await listPairedDevices();230 const idx = devices.findIndex((d) => d.deviceId === deviceId);231 if (idx < 0) return;232 devices[idx] = { ...devices[idx], lastSyncedAt: when };233 await chrome.storage.local.set({ [REGISTRY_KEY]: devices });234}235236export async function getLastKnownIp(pubkeyHex: string): Promise<string | null> {237 try {238 const key = LAST_IP_KEY_PREFIX + pubkeyHex;239 const result = await chrome.storage.local.get(key);240 const value = (result as Record<string, unknown>)[key];241 return typeof value === "string" ? value : null;242 } catch {243 return null;244 }245}246247export async function setLastKnownIp(pubkeyHex: string, ip: string): Promise<void> {248 await chrome.storage.local.set({ [LAST_IP_KEY_PREFIX + pubkeyHex]: ip });249}250251export async function clearLastKnownIp(pubkeyHex: string): Promise<void> {252 await chrome.storage.local.remove(LAST_IP_KEY_PREFIX + pubkeyHex);253}254255export async function getLastSyncAt(): Promise<number | null> {256 try {257 const result = await chrome.storage.local.get(LAST_SYNC_AT_KEY);258 const value = (result as Record<string, unknown>)[LAST_SYNC_AT_KEY];259 if (typeof value === "number") return value;260 if (typeof value === "string" && value !== "") {261 const n = Number.parseInt(value, 10);262 return Number.isFinite(n) ? n : null;263 }264 return null;265 } catch {266 return null;267 }268}269270export async function setLastSyncAt(when: number): Promise<void> {271 await chrome.storage.local.set({ [LAST_SYNC_AT_KEY]: when });272}273274export interface SyncResult {275 entriesReceived: number;276 entriesSent: number;277}278279export async function getLastSyncResult(): Promise<SyncResult | null> {280 try {281 const result = await chrome.storage.local.get(LAST_SYNC_RESULT_KEY);282 const value = (result as Record<string, unknown>)[LAST_SYNC_RESULT_KEY];283 if (284 value &&285 typeof value === "object" &&286 typeof (value as Record<string, unknown>).entriesReceived === "number" &&287 typeof (value as Record<string, unknown>).entriesSent === "number"288 ) {289 return value as SyncResult;290 }291 return null;292 } catch {293 return null;294 }295}296297export async function setLastSyncResult(result: SyncResult): Promise<void> {298 await chrome.storage.local.set({ [LAST_SYNC_RESULT_KEY]: result });299}300301function isPairedDevice(x: unknown): x is PairedDevice {302 if (typeof x !== "object" || x === null) return false;303 const r = x as Record<string, unknown>;304 if (typeof r.deviceId !== "string" || !r.deviceId) return false;305 if (typeof r.pairedAt !== "number") return false;306 if (307 r.rendezvousSecretHex !== undefined &&308 (typeof r.rendezvousSecretHex !== "string" || !/^[0-9a-f]{64}$/.test(r.rendezvousSecretHex))309 ) {310 return false;311 }312 if (r.relayUrl !== undefined) {313 if (typeof r.relayUrl !== "string") return false;314 try {315 if (new URL(r.relayUrl).protocol !== "wss:") return false;316 } catch {317 return false;318 }319 }320 return true;321}