sync-identity-glue.ts

957 B · raw

1/**2 * Local device id helpers shared between the lifecycle tick and the3 * 6-digit pairing flow. Both need the same base64url-encoded 16-byte id4 * the native host expects in `Advertise` / `StartPairingServer`.5 */67const DEVICE_ID_KEY = "peach_device_id";89export async function getOrCreateLocalDeviceId(): Promise<string> {10  try {11    const stored = await chrome.storage.local.get(DEVICE_ID_KEY);12    const value = (stored as Record<string, string | undefined>)[DEVICE_ID_KEY];13    if (typeof value === "string" && value) return value;14  } catch {15    // fall through to generation16  }17  const random = crypto.getRandomValues(new Uint8Array(16));18  let binary = "";19  for (const byte of random) binary += String.fromCharCode(byte);20  const id = btoa(binary)21    .replace(/\+/g, "-")22    .replace(/\//g, "_")23    .replace(/=+$/g, "");24  try {25    await chrome.storage.local.set({ [DEVICE_ID_KEY]: id });26  } catch {27    // best-effort28  }29  return id;30}