12345678910111213141516171819import type { DeviceRevocation, PairedDevice } from "../shared/sync-types";20import { constantTimeEqualHex } from "../shared/constant-time";21import { capDeviceName, clampSyncTimestamp } from "../shared/sync-limits";22import type { SyncOutcome } from "../shared/sync-outcome";2324const REGISTRY_KEY = "peach_paired_devices_v3";25const REVOCATIONS_KEY = "peach_device_revocations_v1";2627const MAX_REVOCATIONS = 500;28const LAST_SYNC_AT_KEY = "peach_last_sync_at";29const LAST_SYNC_RESULT_KEY = "peach_last_sync_result";3031export async function listPairedDevices(): Promise<PairedDevice[]> {32 try {33 const result = await chrome.storage.local.get(REGISTRY_KEY);34 const devices = (result as Record<string, unknown>)[REGISTRY_KEY];35 if (Array.isArray(devices)) return devices.filter(isPairedDevice);36 return [];37 } catch {38 return [];39 }40}4142export async function findPairedDeviceById(deviceId: string): Promise<PairedDevice | null> {43 const devices = await listPairedDevices();44 return devices.find((d) => d.deviceId === deviceId) ?? null;45}4647export async function findPairedDeviceByPubkey(pubkeyHex: string): Promise<PairedDevice | null> {48 const devices = await listPairedDevices();49 return devices.find((d) =>50 d.longTermPublicKeyHex !== undefined &&51 constantTimeEqualHex(d.longTermPublicKeyHex, pubkeyHex)52 ) ?? null;53}54555657585960export async function upsertPairedDevice(device: PairedDevice): Promise<void> {61 if (!device.deviceId) throw new Error("device.deviceId is required");62 if (!device.longTermPublicKeyHex) throw new Error("device.longTermPublicKeyHex is required");63 if (!device.deviceName) throw new Error("device.deviceName is required");64 if (!device.deviceType) throw new Error("device.deviceType is required");6566 67 68 69 const stored = { ...device, deviceName: capDeviceName(device.deviceName) };70 const devices = await listPairedDevices();71 const idx = devices.findIndex((d) => d.deviceId === stored.deviceId);72 if (idx >= 0) {73 devices[idx] = { ...devices[idx], ...stored };74 } else {75 devices.push(stored);76 }77 await chrome.storage.local.set({ [REGISTRY_KEY]: devices });78 79 80 81 82}8384export async function renamePairedDevice(deviceId: string, name: string): Promise<void> {85 const alias = name.trim();86 if (!alias) throw new Error("device name must not be empty");87 if (alias.length > 64) throw new Error("device name must be 64 chars or fewer");88 const devices = await listPairedDevices();89 const index = devices.findIndex((device) => device.deviceId === deviceId);90 if (index < 0) throw new Error("device_not_found");91 devices[index] = { ...devices[index], localAlias: alias };92 await chrome.storage.local.set({ [REGISTRY_KEY]: devices });93}949596979899100101export async function setRelayUrlForAllPairedDevices(102 relayUrl: string,103): Promise<void> {104 const devices = await listPairedDevices();105 if (devices.length === 0) return;106 await chrome.storage.local.set({107 [REGISTRY_KEY]: devices.map((device) => ({ ...device, relayUrl })),108 });109 110 111 112}113114115116117118119120121122123124125126127128export async function removePairedDeviceById(deviceId: string): Promise<void> {129 const devices = await listPairedDevices();130 const filtered = devices.filter((d) => d.deviceId !== deviceId);131 132 133 134 await chrome.storage.local.set({ [REGISTRY_KEY]: filtered });135 136 137}138139140141142143export async function listDeviceRevocations(): Promise<DeviceRevocation[]> {144 try {145 const result = await chrome.storage.local.get(REVOCATIONS_KEY);146 const value = (result as Record<string, unknown>)[REVOCATIONS_KEY];147 if (Array.isArray(value)) return value.filter(isDeviceRevocation);148 return [];149 } catch {150 return [];151 }152}153154155156157158159160161162export async function isDeviceRevoked(163 deviceId: string,164 longTermPublicKeyHex?: string,165): Promise<boolean> {166 167 168 const key = longTermPublicKeyHex?.toLowerCase();169 const keyIsRevocable = key !== undefined && key !== "0".repeat(64);170 return (await listDeviceRevocations()).some(171 (r) =>172 r.deviceId === deviceId ||173 (keyIsRevocable && r.longTermPublicKeyHex.toLowerCase() === key),174 );175}176177178179180181182183184export async function revokeDeviceById(185 deviceId: string,186 revokedByDeviceId: string,187 options: { now?: number } = {},188): Promise<DeviceRevocation | null> {189 const device = await findPairedDeviceById(deviceId);190 const existing = await listDeviceRevocations();191 if (existing.some((r) => r.deviceId === deviceId)) {192 193 194 195 196 if (device) await removePairedDeviceById(deviceId);197 return null;198 }199200 const record: DeviceRevocation = {201 deviceId,202 203 204 205 longTermPublicKeyHex: device?.longTermPublicKeyHex ?? "0".repeat(64),206 revokedAt: options.now ?? Date.now(),207 revokedByDeviceId,208 };209 const removeIndex = existing.length >= MAX_REVOCATIONS210 ? Math.max(0, existing.findIndex((r) => r.revokedByDeviceId !== revokedByDeviceId))211 : -1;212 const retained = removeIndex >= 0213 ? existing.filter((_, index) => index !== removeIndex)214 : existing;215 await storeRevocations([...retained, record]);216 await removePairedDeviceById(deviceId);217 return record;218}219220221222223224225226227228export async function mergeDeviceRevocations(229 incoming: DeviceRevocation[],230): Promise<string[]> {231 const existing = await listDeviceRevocations();232 const known = new Set(existing.map((r) => r.deviceId));233 const fresh = incoming234 .filter((r) => !known.has(r.deviceId))235 236 237 238 .map((r) => ({ ...r, revokedAt: clampSyncTimestamp(r.revokedAt) }));239 if (fresh.length === 0) return [];240 241 242 243 const admitted = fresh.slice(0, Math.max(0, MAX_REVOCATIONS - existing.length));244 if (admitted.length > 0) await storeRevocations([...existing, ...admitted]);245 return admitted.map((r) => r.deviceId);246}247248249250251252253254255256export async function repairPairedRevocationOverlaps(): Promise<{257 revocationsCleared: number;258 pairedRowsRemoved: number;259}> {260 const devices = await listPairedDevices();261 const revocations = await listDeviceRevocations();262 const revocationById = new Map(revocations.map((record) => [record.deviceId, record]));263 const revocationIdsToClear = new Set<string>();264 const pairedIdsToRemove = new Set<string>();265266 for (const device of devices) {267 const revocation = revocationById.get(device.deviceId);268 if (!revocation) continue;269 if (device.trustSource === "direct" && device.pairedAt > revocation.revokedAt) {270 revocationIdsToClear.add(device.deviceId);271 } else {272 pairedIdsToRemove.add(device.deviceId);273 }274 }275276 if (revocationIdsToClear.size === 0 && pairedIdsToRemove.size === 0) {277 return { revocationsCleared: 0, pairedRowsRemoved: 0 };278 }279280 await chrome.storage.local.set({281 [REGISTRY_KEY]: devices.filter((device) => !pairedIdsToRemove.has(device.deviceId)),282 [REVOCATIONS_KEY]: revocations.filter(283 (record) => !revocationIdsToClear.has(record.deviceId),284 ),285 });286 return {287 revocationsCleared: revocationIdsToClear.size,288 pairedRowsRemoved: pairedIdsToRemove.size,289 };290}291292async function storeRevocations(records: DeviceRevocation[]): Promise<void> {293 await chrome.storage.local.set({ [REVOCATIONS_KEY]: records });294}295296function isDeviceRevocation(x: unknown): x is DeviceRevocation {297 if (typeof x !== "object" || x === null) return false;298 const r = x as Record<string, unknown>;299 return (300 typeof r.deviceId === "string" &&301 !!r.deviceId &&302 typeof r.longTermPublicKeyHex === "string" &&303 typeof r.revokedAt === "number" &&304 typeof r.revokedByDeviceId === "string"305 );306}307308export async function clearPairedDevices(): Promise<void> {309 await chrome.storage.local.remove(REGISTRY_KEY);310}311312export async function markLastSyncedAt(deviceId: string, when: number): Promise<void> {313 const devices = await listPairedDevices();314 const idx = devices.findIndex((d) => d.deviceId === deviceId);315 if (idx < 0) return;316 devices[idx] = { ...devices[idx], lastSyncedAt: when };317 await chrome.storage.local.set({ [REGISTRY_KEY]: devices });318}319320export async function getLastSyncAt(): Promise<number | null> {321 try {322 const result = await chrome.storage.local.get(LAST_SYNC_AT_KEY);323 const value = (result as Record<string, unknown>)[LAST_SYNC_AT_KEY];324 if (typeof value === "number") return value;325 if (typeof value === "string" && value !== "") {326 const n = Number.parseInt(value, 10);327 return Number.isFinite(n) ? n : null;328 }329 return null;330 } catch {331 return null;332 }333}334335export async function setLastSyncAt(when: number): Promise<void> {336 await chrome.storage.local.set({ [LAST_SYNC_AT_KEY]: when });337}338339340341342343344345export interface SyncResult {346 outcome: SyncOutcome;347 detail?: string;348 349 at: number;350 entriesReceived: number;351 entriesSent: number;352}353354export async function getLastSyncResult(): Promise<SyncResult | null> {355 try {356 const result = await chrome.storage.local.get(LAST_SYNC_RESULT_KEY);357 const value = (result as Record<string, unknown>)[LAST_SYNC_RESULT_KEY];358 if (359 value &&360 typeof value === "object" &&361 typeof (value as Record<string, unknown>).outcome === "string" &&362 typeof (value as Record<string, unknown>).at === "number" &&363 typeof (value as Record<string, unknown>).entriesReceived === "number" &&364 typeof (value as Record<string, unknown>).entriesSent === "number"365 ) {366 return value as SyncResult;367 }368 return null;369 } catch {370 return null;371 }372}373374export async function setLastSyncResult(result: SyncResult): Promise<void> {375 await chrome.storage.local.set({ [LAST_SYNC_RESULT_KEY]: result });376}377378function isPairedDevice(x: unknown): x is PairedDevice {379 if (typeof x !== "object" || x === null) return false;380 const r = x as Record<string, unknown>;381 if (typeof r.deviceId !== "string" || !r.deviceId) return false;382 if (typeof r.pairedAt !== "number") return false;383 if (384 r.localAlias !== undefined &&385 (typeof r.localAlias !== "string" || !r.localAlias || r.localAlias.length > 64)386 ) {387 return false;388 }389 if (390 r.rendezvousSecretHex !== undefined &&391 (typeof r.rendezvousSecretHex !== "string" || !/^[0-9a-f]{64}$/.test(r.rendezvousSecretHex))392 ) {393 return false;394 }395 if (r.relayUrl !== undefined) {396 if (typeof r.relayUrl !== "string") return false;397 try {398 if (new URL(r.relayUrl).protocol !== "wss:") return false;399 } catch {400 return false;401 }402 }403 return true;404}