@ghostlytools/cli 1.13.2 → 1.13.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/README.md +9 -8
  2. package/dist/assets/{api-DV52o7A8.js → api-B5qxNMgg.js} +2 -2
  3. package/dist/assets/{api-O57SNJcb.js → api-iiij_pP5.js} +213 -59
  4. package/dist/assets/api-iiij_pP5.js.map +1 -0
  5. package/dist/assets/{apiKit-CPTFJHA7.js → apiKit-BPuHOoXF.js} +17 -3
  6. package/dist/assets/apiKit-BPuHOoXF.js.map +1 -0
  7. package/dist/assets/{appFetch-Ca9DNQQ2.js → appFetch-D89FnCxr.js} +2 -2
  8. package/dist/assets/{appFetch-Ca9DNQQ2.js.map → appFetch-D89FnCxr.js.map} +1 -1
  9. package/dist/assets/{apps-uZTu5FlR.js → apps-BpZcd86Y.js} +1 -1
  10. package/dist/assets/{apps-gXpGFPiv.js → apps-D2YGSPJe.js} +45 -19
  11. package/dist/assets/apps-D2YGSPJe.js.map +1 -0
  12. package/dist/assets/{backup-CxH3auHB.js → backup-BrMe9VPY.js} +11 -6
  13. package/dist/assets/backup-BrMe9VPY.js.map +1 -0
  14. package/dist/assets/{backup-Di2U6QVH.js → backup-COkkM8Yy.js} +1 -1
  15. package/dist/assets/bark_ffi_wasm_bg-CjjCN3FD.js +5 -0
  16. package/dist/assets/{bitcoind-BpZn3bRN.js → bitcoind-CK1QEUHn.js} +2 -2
  17. package/dist/assets/{bitcoind-BpZn3bRN.js.map → bitcoind-CK1QEUHn.js.map} +1 -1
  18. package/dist/assets/bitcoindevkit_bg-D6IFIaJi.js +5 -0
  19. package/dist/assets/{blobFiles-DDs34n0r.js → blobFiles-DA3UEn37.js} +3 -3
  20. package/dist/assets/{blobFiles-DDs34n0r.js.map → blobFiles-DA3UEn37.js.map} +1 -1
  21. package/dist/assets/buttons-BWEdoxgK.js +1 -0
  22. package/dist/assets/{buttons-D4udKEvT.js → buttons-UsDPQJsQ.js} +4 -4
  23. package/dist/assets/{buttons-D4udKEvT.js.map → buttons-UsDPQJsQ.js.map} +1 -1
  24. package/dist/assets/{client-DGx7E8b3.js → client-Cj-VLeTs.js} +2 -2
  25. package/dist/assets/{client-DGx7E8b3.js.map → client-Cj-VLeTs.js.map} +1 -1
  26. package/dist/assets/{fedimintSdk-D-6H9Pe7.js → fedimintSdk-eLXBrj9i.js} +2 -2
  27. package/dist/assets/{fedimintSdk-D-6H9Pe7.js.map → fedimintSdk-eLXBrj9i.js.map} +1 -1
  28. package/dist/assets/fedimint_client_wasm_bg-CRQlnJdu.js +5 -0
  29. package/dist/assets/{fileBytes-CfvUXdSy.js → fileBytes-B2jXQI8e.js} +3 -3
  30. package/dist/assets/{fileBytes-CfvUXdSy.js.map → fileBytes-B2jXQI8e.js.map} +1 -1
  31. package/dist/assets/{fileBytes-tj6-VZcB.js → fileBytes-BQrW3m-d.js} +2 -2
  32. package/dist/assets/{fileBytes-tj6-VZcB.js.map → fileBytes-BQrW3m-d.js.map} +1 -1
  33. package/dist/assets/{fileBytes-CCKbwqG_.js → fileBytes-CtjxJ6AL.js} +1 -1
  34. package/dist/assets/{fileBytesIdb-BJirUAjI.js → fileBytesIdb-B7Wjw0S8.js} +3 -3
  35. package/dist/assets/{fileBytesIdb-BJirUAjI.js.map → fileBytesIdb-B7Wjw0S8.js.map} +1 -1
  36. package/dist/assets/fileBytesIdb-Fcj2mwj6.js +1 -0
  37. package/dist/assets/{fileBytesOpfs-DRUYLER4.js → fileBytesOpfs-BW0u-_f_.js} +3 -3
  38. package/dist/assets/{fileBytesOpfs-DRUYLER4.js.map → fileBytesOpfs-BW0u-_f_.js.map} +1 -1
  39. package/dist/assets/{fixedHosts-CODN2pTL.js → fixedHosts-CrO01M_y.js} +3 -3
  40. package/dist/assets/{fixedHosts-CODN2pTL.js.map → fixedHosts-CrO01M_y.js.map} +1 -1
  41. package/dist/assets/{groupMeta-CeZpqVVC.js → groupMeta-DHJxOu0K.js} +99 -10
  42. package/dist/assets/groupMeta-DHJxOu0K.js.map +1 -0
  43. package/dist/assets/{host-CRA7h5A2.js → host-C4J4y-Zq.js} +187 -29
  44. package/dist/assets/host-C4J4y-Zq.js.map +1 -0
  45. package/dist/assets/{idb-ewvbqyDI.js → idb-CmIR_bxg.js} +2 -1
  46. package/dist/assets/idb-CmIR_bxg.js.map +1 -0
  47. package/dist/assets/{identityProofs-B8zCp5_0.js → identityProofs-C0rIGT6y.js} +20 -3
  48. package/dist/assets/identityProofs-C0rIGT6y.js.map +1 -0
  49. package/dist/assets/{irohWeb-mnOi2Jp7.js → irohWeb-BXgunUhu.js} +113 -33
  50. package/dist/assets/irohWeb-BXgunUhu.js.map +1 -0
  51. package/dist/assets/{main-Chc871HV.js → main-BLs-zUTt.js} +68 -28
  52. package/dist/assets/main-BLs-zUTt.js.map +1 -0
  53. package/dist/assets/{mainline-CDUXtV-I.js → mainline-CYek1H10.js} +2 -2
  54. package/dist/assets/{mainline-CDUXtV-I.js.map → mainline-CYek1H10.js.map} +1 -1
  55. package/dist/assets/{networkReason-DYlPZS5M.js → networkReason-C6LYbjF2.js} +2 -2
  56. package/dist/assets/{networkReason-DYlPZS5M.js.map → networkReason-C6LYbjF2.js.map} +1 -1
  57. package/dist/assets/{ownDid-BOuSlDv-.js → ownDid-Dg-8e_hs.js} +6 -5
  58. package/dist/assets/ownDid-Dg-8e_hs.js.map +1 -0
  59. package/dist/assets/{ownStatus-CLA1VPkL.js → ownStatus-BOx4vLi6.js} +34 -11
  60. package/dist/assets/ownStatus-BOx4vLi6.js.map +1 -0
  61. package/dist/assets/{profiles-BH1bH9aE.js → profiles-BA0ePikY.js} +33 -8
  62. package/dist/assets/profiles-BA0ePikY.js.map +1 -0
  63. package/dist/assets/{registry-DAq16T-V.js → registry-DuSwXntJ.js} +1 -1
  64. package/dist/assets/{registry-DP_-RA-v.js → registry-OoIgxDrO.js} +25 -13
  65. package/dist/assets/registry-OoIgxDrO.js.map +1 -0
  66. package/dist/assets/{relay-gJTOYQJZ.js → relay-NT5bf1WA.js} +9 -6
  67. package/dist/assets/relay-NT5bf1WA.js.map +1 -0
  68. package/dist/assets/{resolve-B1eQ4dVQ.js → resolve-DUmE70Eo.js} +3 -3
  69. package/dist/assets/{resolve-B1eQ4dVQ.js.map → resolve-DUmE70Eo.js.map} +1 -1
  70. package/dist/assets/{restoredRows-D_WSHE7H.js → restoredRows-Cgaxx1xW.js} +2 -2
  71. package/dist/assets/{restoredRows-D_WSHE7H.js.map → restoredRows-Cgaxx1xW.js.map} +1 -1
  72. package/dist/assets/{server-Bd2ofxc1.js → server-WWlXICVB.js} +555 -110
  73. package/dist/assets/server-WWlXICVB.js.map +1 -0
  74. package/dist/assets/{sshForges-As7dbGXM.js → sshForges-Cfu-dSwc.js} +2 -2
  75. package/dist/assets/{sshForges-As7dbGXM.js.map → sshForges-Cfu-dSwc.js.map} +1 -1
  76. package/dist/assets/translate-DnuQMfj0.js.map +1 -1
  77. package/dist/assets/{usdt-DLmtf8F9.js → usdt-BkO4SY07.js} +2 -2
  78. package/dist/assets/{usdt-DLmtf8F9.js.map → usdt-BkO4SY07.js.map} +1 -1
  79. package/dist/assets/{waitNotice-BHuMofaH.js → waitNotice-DSECf6II.js} +2 -2
  80. package/dist/assets/{waitNotice-BHuMofaH.js.map → waitNotice-DSECf6II.js.map} +1 -1
  81. package/dist/ghostly.mjs +1 -1
  82. package/npm-shrinkwrap.json +2 -2
  83. package/package.json +1 -1
  84. package/dist/assets/api-O57SNJcb.js.map +0 -1
  85. package/dist/assets/apiKit-CPTFJHA7.js.map +0 -1
  86. package/dist/assets/apps-gXpGFPiv.js.map +0 -1
  87. package/dist/assets/backup-CxH3auHB.js.map +0 -1
  88. package/dist/assets/bark_ffi_wasm_bg-CcafsJla.js +0 -5
  89. package/dist/assets/bark_ffi_wasm_bg-CcafsJla.js.map +0 -1
  90. package/dist/assets/bark_ffi_wasm_bg-VNmaJsc9.wasm +0 -0
  91. package/dist/assets/bitcoindevkit_bg-BWQHx7vd.js +0 -5
  92. package/dist/assets/bitcoindevkit_bg-BWQHx7vd.js.map +0 -1
  93. package/dist/assets/bitcoindevkit_bg-DXil67yS.wasm +0 -0
  94. package/dist/assets/buttons-YTYEqvGC.js +0 -1
  95. package/dist/assets/fedimint_client_wasm_bg-Cr5xGD-w.js +0 -5
  96. package/dist/assets/fedimint_client_wasm_bg-Cr5xGD-w.js.map +0 -1
  97. package/dist/assets/fedimint_client_wasm_bg-DeFtkIv6.wasm +0 -0
  98. package/dist/assets/fileBytesIdb-B0zzJ6p7.js +0 -1
  99. package/dist/assets/groupMeta-CeZpqVVC.js.map +0 -1
  100. package/dist/assets/host-CRA7h5A2.js.map +0 -1
  101. package/dist/assets/idb-ewvbqyDI.js.map +0 -1
  102. package/dist/assets/identityProofs-B8zCp5_0.js.map +0 -1
  103. package/dist/assets/irohWeb-mnOi2Jp7.js.map +0 -1
  104. package/dist/assets/main-Chc871HV.js.map +0 -1
  105. package/dist/assets/ownDid-BOuSlDv-.js.map +0 -1
  106. package/dist/assets/ownStatus-CLA1VPkL.js.map +0 -1
  107. package/dist/assets/profiles-BH1bH9aE.js.map +0 -1
  108. package/dist/assets/registry-DP_-RA-v.js.map +0 -1
  109. package/dist/assets/relay-gJTOYQJZ.js.map +0 -1
  110. package/dist/assets/server-Bd2ofxc1.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"idb-ewvbqyDI.js","names":[],"sources":["../../../browser/src/shared/idb.ts"],"sourcesContent":["/**\n * The extension's one IndexedDB database. The peer (offscreen document) and\n * the pages share an origin, so both open it: that is also how file contents\n * move between them without squeezing through runtime messages.\n */\nlet dbName = \"ghostly\";\n\n/** Before first use: keeps profiles that share a browser storage area apart (Desktop's GHOSTLY_PROFILE). */\nexport function setDatabaseName(name: string): void {\n dbName = name;\n}\n/** The peer database this page uses: its profile's (WISP 04). */\nexport function databaseName(): string {\n return dbName;\n}\n/** The schema this build reads and writes. A database stored at a higher one is a newer build's: it is never opened. */\nexport const DB_VERSION = 16;\n\n/**\n * Why the profile's database did not open. `newer`: a newer Ghostly stored it (IndexedDB never opens a database below\n * its stored version). `blocked`: another window still holds it open at an older version. `full`: no storage space.\n * `denied`: the browser gives this page no storage (a private window, storage blocked for the site). `failed`:\n * anything else, a damaged database included (browsers do not tell that one apart).\n */\nexport type ProfileOpenReason = \"newer\" | \"blocked\" | \"full\" | \"denied\" | \"failed\";\n\n/** What the pages are told (a plain object: it crosses the extension's port), and what a bot reads in `details`. */\nexport interface ProfileOpenFailure {\n reason: ProfileOpenReason;\n /** The schema version this build reads (`DB_VERSION`). */\n supportedVersion: number;\n /** The version the database is stored at, when it could be read (`newer`). */\n storedVersion?: number;\n /** What the browser said, in its own words. */\n detail?: string;\n}\n\n/** The profile's database did not open. Nothing was changed, and nothing is ever deleted or reset because of it. */\nexport class ProfileOpenError extends Error {\n constructor(readonly failure: ProfileOpenFailure) {\n super(profileOpenMessage(failure));\n this.name = \"ProfileOpenError\";\n }\n}\n\n/** The failure in plain English, for logs, the CLI and anything that shows an engine error as it came. */\nexport function profileOpenMessage(failure: ProfileOpenFailure): string {\n const could = \"Ghostly could not open this profile's data\";\n switch (failure.reason) {\n case \"newer\":\n return `This profile was last used by a newer version of Ghostly (its data is version ${failure.storedVersion ?? \"above \" + failure.supportedVersion}, this version reads up to ${failure.supportedVersion}). Update Ghostly to open it.`;\n case \"blocked\": return `${could}: another Ghostly window or tab still has it open with an older version. Close it and try again.`;\n case \"full\": return `${could}: this device is out of storage space. Free some space and try again.`;\n case \"denied\": return `${could}: storage is not allowed here (a private window, or storage blocked for this site).`;\n default: return `${could}${failure.detail ? `: ${failure.detail}` : \"\"}`;\n }\n}\n\n/** What the start of the engine failed with, as the failure the pages show: a database that did not open, or anything else. */\nexport function profileOpenFailure(error: unknown): ProfileOpenFailure {\n if (error instanceof ProfileOpenError) return error.failure;\n // The database opened but a first write found no room (Chromium aborts the transaction with an empty message).\n const quota = quotaError(error);\n if (quota) return failureOf(quota);\n const detail = error instanceof Error ? error.message : String(error);\n return { reason: \"failed\", supportedVersion: DB_VERSION, ...(detail ? { detail } : {}) };\n}\n\n/**\n * A failed call as the client hears it (engine/server.ts): the error's message. Only the message travels, so a storage\n * write the browser refused for want of space (Chromium's QuotaExceededError has an empty message) says so, its name\n * kept for the ⓘ.\n */\nexport function errorLine(error: unknown): string {\n if ((error as { name?: unknown } | null)?.name === \"QuotaExceededError\") {\n const message = error instanceof Error ? error.message.trim() : \"\";\n return `Not enough space on this device (QuotaExceededError${message ? `: ${message}` : \"\"})`;\n }\n return error instanceof Error ? error.message : String(error);\n}\n\n/** The no-room error's names: the standard one and Firefox's (its legacy code, 22, is read as well). */\nconst QUOTA_NAMES: ReadonlySet<unknown> = new Set([\"QuotaExceededError\", \"NS_ERROR_DOM_QUOTA_REACHED\"]);\n\n/**\n * The no-room error behind `error`, as thrown or wrapped: a transaction's abort (`error`, an event's `target.error`)\n * or an Error's `cause`. Undefined when it is not one.\n */\nfunction quotaError(error: unknown, depth = 0): { name?: unknown; message?: unknown } | undefined {\n if (!error || typeof error !== \"object\" || depth > 3) return undefined;\n const e = error as { name?: unknown; code?: unknown; error?: unknown; target?: { error?: unknown } | null; cause?: unknown };\n if (QUOTA_NAMES.has(e.name) || (typeof DOMException !== \"undefined\" && error instanceof DOMException && e.code === 22)) return e;\n return quotaError(e.error, depth + 1) ?? quotaError(e.target?.error, depth + 1) ?? quotaError(e.cause, depth + 1);\n}\n\n/**\n * `blockedMs`: how long an open that another window blocks may wait for that window to let go before it is said to be\n * blocked. `silentMs`: how long an open may go without any answer from the browser (no success, error, blocked or\n * upgrade) before it is said to have failed. An upgrade that started has its answer and may take as long as it needs.\n */\nexport const OPEN_TIMINGS = { blockedMs: 10_000, silentMs: 30_000 };\n\nfunction failureOf(error: unknown): ProfileOpenFailure {\n const name = (error as { name?: unknown } | null)?.name;\n const message = (error as { message?: unknown } | null)?.message;\n const detail = [typeof name === \"string\" ? name : \"\", typeof message === \"string\" ? message : \"\"].filter(Boolean).join(\": \");\n const reason: ProfileOpenReason = name === \"VersionError\" ? \"newer\"\n : quotaError(error) ? \"full\"\n // Firefox's private windows of old, storage blocked for the site, or no IndexedDB at all.\n : name === \"BlockedError\" ? \"blocked\"\n : name === \"SecurityError\" || name === \"InvalidStateError\" || name === \"ReferenceError\" || name === \"TypeError\" ? \"denied\"\n : \"failed\";\n return { reason, supportedVersion: DB_VERSION, ...(detail ? { detail } : {}) };\n}\n\n/**\n * The version a database is stored at, read without changing it: an open that names no version opens what is there.\n * Only for a database known to exist (an open without a version would make a missing one).\n */\nfunction storedVersion(name: string): Promise<number | undefined> {\n return new Promise((resolve) => {\n try {\n const request = indexedDB.open(name);\n // It did not exist after all: leave nothing behind.\n request.onupgradeneeded = () => { try { request.transaction?.abort(); } catch { /* already over */ } };\n request.onsuccess = () => { const { version } = request.result; request.result.close(); resolve(version); };\n request.onerror = request.onblocked = () => resolve(undefined);\n } catch { resolve(undefined); }\n });\n}\n/** The messages store's index of card messages (`card.kind`): what `db.getCardMessages` reads. */\nexport const CARD_INDEX = \"byCardKind\";\n/** The messages store's index of the messages that carry a file, by chat (`linkId`, `file.id`): what `db.getFileMessages` reads. */\nexport const FILE_INDEX = \"byLinkFile\";\n/** The wallet history's index by (mint, time): what `newestWalletTx` reads. */\nexport const WALLET_TX_INDEX = \"byMintTime\";\n\nexport const STORES = {\n links: \"links\",\n messages: \"messages\",\n services: \"services\",\n settings: \"settings\",\n files: \"files\",\n proofs: \"proofs\",\n payments: \"payments\",\n quotes: \"quotes\",\n walletTx: \"walletTx\",\n melts: \"melts\",\n /** Swaps at a mint that have not finished (`PendingSwap`): what gets their outputs back when an answer is missed. */\n swaps: \"swaps\",\n intents: \"paymentIntents\",\n /** Private groups (WISP 900): membership chain, epoch secrets and my own recent messages, by group id. */\n groups: \"groups\",\n /** Files kept in 1 MiB pieces where the platform has no file system for them (see `fileBytesIdb.ts`). */\n fileChunks: \"fileChunks\",\n /**\n * What changes about a stored file after it is stored, by file id. A `files` record is written once and never\n * again: WebKit loses the Blob of a record written back with the Blob it read (see `fileStore`).\n */\n fileState: \"fileState\",\n /** Installed mini-apps (WISP 1200 § Updates and rollback), by app reference: `InstalledApp` (`engine/apps.ts`). */\n apps: \"apps\",\n /** The app stores the person added, by store key: `AddedAppStore`. A store is its key; its URL is kept on the record. */\n appStores: \"appStores\",\n /** Each installed app's own storage, by (app reference, scope, key): `AppStorageRow`. Scope: a chat's link id, or `alone`. */\n appStorage: \"appStorage\",\n} as const;\n\n/** The app storage store's index by (app reference, scope): one scope's rows, for its 5 MiB cap and its keys. */\nexport const APP_STORAGE_SCOPE_INDEX = \"byAppScope\";\n/** The app storage store's index by scope: every app's rows of one chat, which go with the chat. */\nexport const APP_STORAGE_CHAT_INDEX = \"byScope\";\n\n/**\n * A file's contents. Metadata travels with the chat message; this is only the bytes: in `blob` for a file\n * small enough to hold whole, or in the platform's file storage (`bytes`, see `fileBytes.ts`) under the same id.\n * Ids are `<link id>-out-<random>` for files we send and `<link id>-in-<random>` for\n * files we receive, both chosen here. Files stored before that are `<link id>-<wire id>`\n * without `direction` and are still read under their old id.\n */\nexport interface StoredFile {\n id: string;\n linkId: string;\n blob?: Blob;\n /** Where the bytes are when there is no `blob`. */\n bytes?: import(\"./fileBytes\").FileBytesKind;\n createdAt: number;\n direction?: \"in\" | \"out\";\n /** The id the file had on the data link. */\n wireId?: string;\n digest?: string;\n metadata?: { name: string; size: number; mime: string; timestamp: number; voice?: import(\"@ghostly/core\").VoiceMeta; video?: import(\"@ghostly/core\").VideoMeta; image?: import(\"@ghostly/core\").ImageMeta };\n transfer?: { state: \"transferring\" | \"done\" | \"failed\"; transferred: number; size: number; error?: string };\n /** files/3: the transfer's own record (`@ghostly/core` `FileTransferRecord`), kept so it resumes after a restart. */\n wire3?: import(\"@ghostly/core\").FileTransferRecord;\n /** Its bytes were left out of the light backup this profile was restored from (WISP 05 § Light backups). */\n leftOut?: boolean;\n /**\n * A file the contact said on the DHT floor (WISP 403 § Files), by its wire id: its bubble waits for its offer on the\n * live session, and no byte is here yet. Gone once the offer came (`wireId` and `wire3` then).\n */\n announced?: string;\n /**\n * A file of a group (WISP 503), its `linkId` `group:<id>`: the message that announced it and its author, whether this\n * device fetched it without asking (it counts toward the group's automatic limit), and whether its person asked for it.\n * `digest` is the author's, which the bytes are checked against.\n */\n /**\n * A group's file (WISP 503): its message, author and, when its announcement reached this device said again under a\n * later epoch than the message's own, that epoch (`arrived`). A `ts` on records from before is not read.\n */\n group?: { message: string; author: string; arrived?: number; auto?: boolean; asked?: boolean; paused?: boolean };\n}\n\n/** The fields of a stored file that change after it is stored: kept in `STORES.fileState`, read over the record's own. */\ntype FileStateFields = Partial<Pick<StoredFile, \"bytes\" | \"digest\" | \"transfer\" | \"wire3\" | \"group\" | \"leftOut\">>;\ntype FileState = { id: string } & FileStateFields;\n\nlet dbPromise: Promise<IDBDatabase> | null = null;\n\nexport function openDb(): Promise<IDBDatabase> {\n dbPromise ??= new Promise((resolve, reject) => {\n let settled = false;\n let blocked: ReturnType<typeof setTimeout> | undefined;\n // A browser fault (WebKit had one on a first page load): an open that never answers, which left the app looking\n // alive with an engine that never started. Without an answer in time it is said as a failure, and Try again reloads.\n const silent = setTimeout(() => fail({ name: \"TimeoutError\", message: `the browser did not answer in ${Math.round(OPEN_TIMINGS.silentMs / 1000)} s` }), OPEN_TIMINGS.silentMs);\n // Said once, as what it is (`ProfileOpenError`): the engine does not start, and the pages show why.\n const fail = (error: unknown) => {\n if (settled) return;\n settled = true;\n clearTimeout(blocked);\n clearTimeout(silent);\n const failure = failureOf(error);\n if (failure.reason !== \"newer\") { reject(new ProfileOpenError(failure)); return; }\n void storedVersion(dbName).then((version) => reject(new ProfileOpenError({ ...failure, ...(version !== undefined ? { storedVersion: version } : {}) })));\n };\n let request: IDBOpenDBRequest;\n try {\n request = indexedDB.open(dbName, DB_VERSION);\n } catch (error) {\n fail(error);\n return;\n }\n request.onupgradeneeded = () => {\n clearTimeout(silent);\n const db = request.result;\n const has = (name: string) => db.objectStoreNames.contains(name);\n if (!has(STORES.links)) db.createObjectStore(STORES.links, { keyPath: \"id\" });\n if (!has(STORES.services)) db.createObjectStore(STORES.services, { keyPath: \"id\" });\n if (!has(STORES.settings)) db.createObjectStore(STORES.settings);\n if (!has(STORES.messages)) {\n db.createObjectStore(STORES.messages, { keyPath: [\"linkId\", \"id\"] }).createIndex(\"byLink\", \"linkId\");\n }\n if (!has(STORES.proofs)) db.createObjectStore(STORES.proofs, { keyPath: \"secret\" });\n if (!has(STORES.payments)) db.createObjectStore(STORES.payments, { keyPath: \"id\" });\n if (!has(STORES.quotes)) db.createObjectStore(STORES.quotes, { keyPath: \"quote\" });\n if (!has(STORES.walletTx)) db.createObjectStore(STORES.walletTx, { keyPath: \"id\" });\n // v5: Lightning payments the mint has not settled yet, and the proofs they hold.\n if (!has(STORES.melts)) db.createObjectStore(STORES.melts, { keyPath: \"quote\" });\n if (!has(STORES.intents)) db.createObjectStore(STORES.intents, { keyPath: \"review.id\" });\n if (!has(STORES.files)) {\n db.createObjectStore(STORES.files, { keyPath: \"id\" }).createIndex(\"byLink\", \"linkId\");\n }\n // v7: private groups.\n if (!has(STORES.groups)) db.createObjectStore(STORES.groups, { keyPath: \"id\" });\n // v8: files in pieces, for platforms without the origin-private file system.\n if (!has(STORES.fileChunks)) db.createObjectStore(STORES.fileChunks, { keyPath: [\"id\", \"index\"] });\n // v9: what changes about a stored file, apart from its record (see `fileStore`).\n if (!has(STORES.fileState)) db.createObjectStore(STORES.fileState, { keyPath: \"id\" });\n // v10: a chat's messages in time order, so its latest page is read without the rest.\n const messages = request.transaction!.objectStore(STORES.messages);\n if (!messages.indexNames.contains(\"byLinkTime\")) messages.createIndex(\"byLinkTime\", [\"linkId\", \"timestamp\"]);\n // v11: the messages that carry a status card, by the card's kind, across every chat and group (the Tasks board).\n // A message without a card has no such key and is not in it, so the index is as small as the cards are few.\n if (!messages.indexNames.contains(CARD_INDEX)) messages.createIndex(CARD_INDEX, \"card.kind\");\n // v12: swaps at a mint, written down before the mint is asked.\n if (!has(STORES.swaps)) db.createObjectStore(STORES.swaps, { keyPath: \"id\" });\n // v13: no change of the schema. A build from here can hold a frozen copy of a profile on a standby device (WISP 06\n // § Compatibility and rollout): the step keeps an older build (1.0.3 reads 12) from opening and starting one.\n // v14: mini-apps (WISP 1200): the installed apps, the stores added and each app's storage per scope. Empty until the\n // apps feature is on; the bundles themselves are in file storage under `app-<digest>`, outside every store here.\n if (!has(STORES.apps)) db.createObjectStore(STORES.apps, { keyPath: \"ref\" });\n if (!has(STORES.appStores)) db.createObjectStore(STORES.appStores, { keyPath: \"key\" });\n if (!has(STORES.appStorage)) {\n const storage = db.createObjectStore(STORES.appStorage, { keyPath: [\"ref\", \"scope\", \"key\"] });\n storage.createIndex(APP_STORAGE_SCOPE_INDEX, [\"ref\", \"scope\"]);\n storage.createIndex(APP_STORAGE_CHAT_INDEX, \"scope\");\n }\n // v15: the wallet history by mint and time, so a refresh reads each network's newest movements without the rest.\n const walletTx = request.transaction!.objectStore(STORES.walletTx);\n if (!walletTx.indexNames.contains(WALLET_TX_INDEX)) walletTx.createIndex(WALLET_TX_INDEX, [\"mint\", \"timestamp\"]);\n // v16: the messages that carry a file, by chat or group, so a chat's files are read without its texts (`file list`).\n // A message without a file has no such key and is not in it.\n if (!messages.indexNames.contains(FILE_INDEX)) messages.createIndex(FILE_INDEX, [\"linkId\", \"file.id\"]);\n };\n request.onsuccess = () => {\n // Opened after it was said to be blocked: nobody uses this connection, and it must not block the next open.\n if (settled) { request.result.close(); return; }\n settled = true;\n clearTimeout(blocked);\n clearTimeout(silent);\n // Let the other context upgrade the schema instead of blocking it.\n request.result.onversionchange = () => {\n request.result.close();\n dbPromise = null;\n };\n resolve(request.result);\n };\n // The event's default aborts nothing here, but an unhandled one is logged as an uncaught error in some browsers.\n request.onerror = (event) => { event.preventDefault?.(); fail(request.error); };\n // Another window holds the database at an older version and has not let go (ours do, on `versionchange`). The\n // open stays pending for as long as that lasts: before, the engine waited with it, silently and for good.\n request.onblocked = () => {\n clearTimeout(silent);\n blocked ??= setTimeout(() => fail({ name: \"BlockedError\", message: \"another connection holds an older version open\" }), OPEN_TIMINGS.blockedMs);\n };\n });\n return dbPromise;\n}\n\n/** The stores \"Clear all data\" empties: chats and their keys, messages, files, shared services, groups, mini-apps and their data. */\nexport const PROFILE_STORES = [STORES.links, STORES.messages, STORES.files, STORES.fileState, STORES.fileChunks, STORES.services, STORES.groups, STORES.apps, STORES.appStores, STORES.appStorage] as const;\n\n/**\n * Records of the settings store that belong to the profile, not to a wallet: its DID and its key, its identity proofs\n * with their keys and revocations and when the contacts' were last looked up for one (and which, of a lookup under way), its own Nostr data, the public profiles it read, the built-in mini-apps it removed\n * (`BUILT_IN_APPS_KEY` of `engine/apps.ts`), the digests of the mini-app bundles it may hold (`APP_BUNDLES_KEY`) and the mini-app revocations it verified (`APP_REVOCATIONS_KEY`), its x401 credentials and their keys (`engine/x401.ts`), its contact links\n * (`engine/contactLinks.ts`), the requests it sent through others' (`engine/contactAsks.ts`) and its saved messages\n * (`engine/saved.ts`). A list of what goes\n * rather than of what stays, on purpose: every other record of that store is a wallet's (seeds, configuration, pending\n * operations), and a wallet record a newer version adds must never be deleted by mistake.\n */\nexport const PROFILE_SETTINGS_KEYS = [\"profileDid\", \"identityProofs\", \"identityRevocations\", \"identityRevocationsCheckedAt\", \"identityRevocationsRound\", \"nostrSocial\", \"publicProfiles\", \"appBuiltIns\", \"appBundles\", \"appRevocations\", \"x401Credentials\", \"contactLinks\", \"contactAsks\", \"savedMessages\"] as const;\n\n/** A private group's small row in the settings store (`GroupLive`, `engine/groupRows.ts`): the profile's too. */\nexport const groupLiveKey = (groupId: string): string => `groupLive:${groupId}`;\nexport const GROUP_LIVE_RANGE = (): IDBKeyRange => IDBKeyRange.bound(groupLiveKey(\"\"), `${groupLiveKey(\"\")}￿`);\n/** A private group's pin and deletions for everyone, while its record is behind on them (`GroupLight`): the profile's too. */\nexport const groupLightKey = (groupId: string): string => `groupLight:${groupId}`;\nexport const GROUP_LIGHT_RANGE = (): IDBKeyRange => IDBKeyRange.bound(groupLightKey(\"\"), `${groupLightKey(\"\")}￿`);\n\n/**\n * The fields of the peer's `settings` record that are a wallet's, kept by \"Clear all data\": the mint list, the first-run\n * wallet setup and the backup reminders. Everything else in it is the profile's (name, picture, network settings,\n * storage credentials for held items, the push subscription and who holds it) and goes.\n */\nexport const WALLET_SETTINGS_FIELDS = [\"mints\", \"mintsInitialized\", \"walletSetup\", \"backupReminders\"] as const;\n\n/**\n * \"Clear all data\" (WISP 04): everything of the profile in its peer database except its wallets. The chats' stores are\n * emptied, the profile's records of the settings store are deleted and the `settings` record keeps only its wallet\n * fields. The wallets (proofs, payments, quotes, history, payment journal, wallet records) stay: ecash is money, and\n * nothing else holds a copy of it. The caller stops the peer first, or it may write back what was just deleted.\n */\nexport async function clearProfileStores(): Promise<void> {\n if (typeof indexedDB === \"undefined\") return;\n const db = await openDb();\n const names = [...PROFILE_STORES, STORES.settings].filter((name) => db.objectStoreNames.contains(name));\n const tx = db.transaction(names, \"readwrite\");\n for (const name of names) if (name !== STORES.settings) tx.objectStore(name).clear();\n if (names.includes(STORES.settings)) {\n const settings = tx.objectStore(STORES.settings);\n for (const key of PROFILE_SETTINGS_KEYS) settings.delete(key);\n settings.delete(GROUP_LIVE_RANGE());\n settings.delete(GROUP_LIGHT_RANGE());\n const read = settings.get(\"settings\");\n read.onsuccess = () => {\n const record = read.result as Record<string, unknown> | undefined;\n if (!record || typeof record !== \"object\") return;\n const kept = Object.fromEntries(WALLET_SETTINGS_FIELDS.filter((field) => field in record).map((field) => [field, record[field]]));\n settings.put(kept, \"settings\");\n };\n }\n await new Promise<void>((resolve, reject) => {\n tx.oncomplete = () => resolve();\n tx.onerror = tx.onabort = () => reject(tx.error);\n });\n}\n\n/** Deletes a database of the origin by name (an SDK's own), as far as the browser lets it: blocked or failed, it gives up quietly. */\nexport function deleteDatabase(name: string): Promise<void> {\n return new Promise<void>((resolve) => {\n try { const request = indexedDB.deleteDatabase(name); request.onsuccess = request.onerror = request.onblocked = () => resolve(); } catch { resolve(); }\n });\n}\n\n/** A read. A write goes through `committed`: its request's success does not mean the browser kept it. */\nexport function wrap<T>(request: IDBRequest<T>): Promise<T> {\n return new Promise((resolve, reject) => {\n request.onsuccess = () => resolve(request.result);\n request.onerror = () => reject(request.error);\n });\n}\n\n/** What a write the device had no room for says (Chromium's own QuotaExceededError has no message). */\nexport const NO_ROOM_TO_SAVE = \"This device has no room left to save this\";\n\n/**\n * A write, settled when its transaction is: kept once it commits, refused when it aborts. On a device out of storage\n * Chromium fires the request's success and then aborts the transaction with QuotaExceededError, so a write awaited on\n * its request alone reads as saved and is gone. The last request of its transaction: the transaction ends before this\n * settles. Several in one transaction settle together.\n */\nexport function committed<T>(request: IDBRequest<T>): Promise<T> {\n const tx = request.transaction!;\n return new Promise((resolve, reject) => {\n tx.addEventListener(\"complete\", () => resolve(request.result));\n tx.addEventListener(\"abort\", () => {\n const error = tx.error ?? request.error;\n reject(error?.name === \"QuotaExceededError\" ? Object.assign(new Error(NO_ROOM_TO_SAVE), { name: \"QuotaExceededError\", cause: error })\n : error ?? new Error(\"The write was not saved\"));\n });\n });\n}\n\nexport async function store(name: string, mode: IDBTransactionMode): Promise<IDBObjectStore> {\n return (await openDb()).transaction(name, mode).objectStore(name);\n}\n\n/**\n * Several writes across stores in one transaction: they all land, or none does.\n * `work` only queues requests; the promise settles when the transaction does.\n */\nexport async function transact(names: string[], work: (stores: Record<string, IDBObjectStore>) => void): Promise<void> {\n const tx = (await openDb()).transaction(names, \"readwrite\");\n const done = new Promise<void>((resolve, reject) => {\n tx.oncomplete = () => resolve();\n tx.onabort = () => reject(tx.error ?? new Error(\"The wallet could not save\"));\n tx.onerror = () => reject(tx.error ?? new Error(\"The wallet could not save\"));\n });\n try {\n work(Object.fromEntries(names.map((name) => [name, tx.objectStore(name)])));\n } catch (error) {\n tx.abort();\n await done.catch(() => {});\n throw error;\n }\n return done;\n}\n\n/**\n * The `count` newest wallet movements of the mints `wanted` picks, newest first. Read backwards on the history index, a\n * mint at a time: a mint not wanted, or one whose `count` newest are read, is stepped over at once. What it reads grows\n * with the number of mints, never with the history's length.\n */\nexport async function newestWalletTx<T extends { timestamp: number }>(wanted: (mint: string) => boolean, count: number): Promise<T[]> {\n const index = (await store(STORES.walletTx, \"readonly\")).index(WALLET_TX_INDEX);\n const rows: T[] = [];\n await new Promise<void>((resolve, reject) => {\n let mint: string | undefined, taken = 0;\n const read = (below: IDBKeyRange | null) => {\n const request = index.openCursor(below, \"prev\");\n request.onerror = () => reject(request.error);\n request.onsuccess = () => {\n const cursor = request.result;\n if (!cursor) { resolve(); return; }\n const [at] = cursor.key as [string, number];\n if (at !== mint) { mint = at; taken = 0; }\n // A new cursor below every key of this mint starts at the next mint's newest movement. Not `continue(key)`:\n // fake-indexeddb (the CLI's and Desktop-headless' IndexedDB) walks every key that skips.\n if (taken >= count || !wanted(at)) { read(IDBKeyRange.upperBound([at, -Infinity], true)); return; }\n rows.push(cursor.value as T);\n taken++;\n cursor.continue();\n };\n };\n read(null);\n });\n return rows.sort((a, b) => b.timestamp - a.timestamp).slice(0, count);\n}\n\n/** A stored file as it stands: its record, with what changed since it was stored read over it. */\nfunction withState(file: StoredFile, state: FileState | undefined): StoredFile {\n if (!state) return file;\n const { id: _id, ...fields } = state;\n return { ...file, ...fields };\n}\n\n/**\n * The files store. A record is written once, by `put`, and never written back: what changes later (`patch`,\n * `updateTransfer`) goes to `STORES.fileState` and is read over it. WebKit (Safari, the macOS app) keeps a stored\n * Blob as a file the record points to, and a record written back with the Blob it read can lose that file: from\n * then on every read of it fails with \"The object can not be found here.\" For the same reason a Blob read from\n * here is never put here again, under any id (a forward copies the bytes into a Blob of its own).\n */\nexport const fileStore = {\n /** Stores a file anew: whatever changed about an earlier file under this id is forgotten. */\n async put(file: StoredFile): Promise<void> {\n await transact([STORES.files, STORES.fileState], stores => {\n stores[STORES.files].put(file);\n stores[STORES.fileState].delete(file.id);\n });\n },\n async updateTransfer(id: string, transfer: NonNullable<StoredFile[\"transfer\"]>): Promise<void> {\n await fileStore.patch(id, { transfer });\n },\n /** Changes some fields of a stored file (never its record, see above); nothing happens to one that was deleted. */\n async patch(id: string, fields: FileStateFields): Promise<void> {\n await transact([STORES.files, STORES.fileState], stores => {\n const exists = stores[STORES.files].getKey(id);\n exists.onsuccess = () => {\n if (exists.result === undefined) return;\n const state = stores[STORES.fileState].get(id);\n state.onsuccess = () => { stores[STORES.fileState].put({ ...(state.result as FileState | undefined), ...fields, id } satisfies FileState); };\n };\n });\n },\n async get(id: string): Promise<StoredFile | undefined> {\n const tx = (await openDb()).transaction([STORES.files, STORES.fileState], \"readonly\");\n const [file, state] = await Promise.all([\n wrap<StoredFile | undefined>(tx.objectStore(STORES.files).get(id)),\n wrap<FileState | undefined>(tx.objectStore(STORES.fileState).get(id)),\n ]);\n return file && withState(file, state);\n },\n /**\n * A link's files in two requests: what changed about them is read as one range, from the least of their ids to the\n * greatest. A link's file ids share its prefix (`<link>-in-`, `group-<id>-out-`…), so the range holds little else, and\n * whatever else it holds is not theirs. A read per file was 16,000 requests at every start with 200 files per chat\n * and 300 per group (50 chats, 20 groups).\n */\n async listForLink(linkId: string): Promise<StoredFile[]> {\n const tx = (await openDb()).transaction([STORES.files, STORES.fileState], \"readonly\");\n const files = await wrap<StoredFile[]>(tx.objectStore(STORES.files).index(\"byLink\").getAll(linkId));\n if (!files.length) return files;\n // Strings sort by UTF-16 code unit, as IndexedDB orders its keys.\n const ids = files.map(file => file.id).sort();\n const states = new Map((await wrap<FileState[]>(tx.objectStore(STORES.fileState).getAll(IDBKeyRange.bound(ids[0], ids[ids.length - 1])))).map(state => [state.id, state]));\n return files.map(file => withState(file, states.get(file.id)));\n },\n /** The id of every group a stored file is of (`linkId` `group:<id>`), read off the index: no record is loaded. */\n async groupIds(): Promise<string[]> {\n const index = (await store(STORES.files, \"readonly\")).index(\"byLink\"), ids: string[] = [];\n await new Promise<void>((resolve, reject) => {\n const request = index.openKeyCursor(IDBKeyRange.bound(\"group:\", \"group:\\uffff\"), \"nextunique\");\n request.onerror = () => reject(request.error);\n request.onsuccess = () => {\n const cursor = request.result;\n if (!cursor) return resolve();\n ids.push(String(cursor.key).slice(\"group:\".length));\n cursor.continue();\n };\n });\n return ids;\n },\n /** The id of every stored file whose bytes are a Blob in its record. */\n async blobIds(): Promise<string[]> {\n const files = await store(STORES.files, \"readonly\"), ids: string[] = [];\n await new Promise<void>((resolve, reject) => {\n const request = files.openCursor();\n request.onerror = () => reject(request.error);\n request.onsuccess = () => {\n const cursor = request.result;\n if (!cursor) return resolve();\n if ((cursor.value as StoredFile).blob) ids.push(String(cursor.key));\n cursor.continue();\n };\n });\n return ids;\n },\n /**\n * A file whose Blob was copied to file storage (`kind`, under its id): its record without the Blob from now on. Written\n * back without the Blob it read, so not what WebKit loses (see above); what changed about it since (`fileState`) stays.\n * False when the record is gone or holds no Blob any more: the copy is the caller's to remove.\n */\n async movedToBytes(id: string, kind: NonNullable<StoredFile[\"bytes\"]>): Promise<boolean> {\n let moved = false;\n await transact([STORES.files], stores => {\n const read = stores[STORES.files].get(id);\n read.onsuccess = () => {\n const record = read.result as StoredFile | undefined;\n if (!record?.blob) return;\n const { blob: _blob, ...rest } = record;\n stores[STORES.files].put({ ...rest, bytes: kind } satisfies StoredFile);\n moved = true;\n };\n });\n return moved;\n },\n async delete(id: string): Promise<void> {\n await transact([STORES.files, STORES.fileState], stores => {\n stores[STORES.files].delete(id);\n stores[STORES.fileState].delete(id);\n });\n },\n async deleteForLink(linkId: string): Promise<void> {\n const tx = (await openDb()).transaction([STORES.files, STORES.fileState], \"readwrite\");\n const files = tx.objectStore(STORES.files), state = tx.objectStore(STORES.fileState);\n const keys = await wrap(files.index(\"byLink\").getAllKeys(linkId));\n await Promise.all(keys.flatMap((key) => [committed(files.delete(key)), committed(state.delete(key))]));\n },\n};\n"],"mappings":";;;;;;AAKA,IAAI,SAAS;;AAOb,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,CAAG,YAAY,CAAC,OAAO,OAAO,OAAO,SAAS,GAAG,WAAW;EACrF,MAAM,QAAQ,GAAG,YAAY,OAAO,KAAK,GAAG,QAAQ,GAAG,YAAY,OAAO,SAAS;EACnF,MAAM,OAAO,MAAM,KAAK,MAAM,MAAM,QAAQ,CAAC,CAAC,WAAW,MAAM,CAAC;EAChE,MAAM,QAAQ,IAAI,KAAK,SAAS,QAAQ,CAAC,UAAU,MAAM,OAAO,GAAG,CAAC,GAAG,UAAU,MAAM,OAAO,GAAG,CAAC,CAAC,CAAC,CAAC;CACvG;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"identityProofs-B8zCp5_0.js","names":[],"sources":["../../../core/src/identityTimeline.ts","../../../core/src/identityProofs.ts"],"sourcesContent":["/**\n * What a chat's timeline shows of the identity-proof exchange (WISP 300, \"In the conversation\"): one entry when\n * an identity is shared, on both sides, turning verified or failed as the exchange settles, and one when it stops\n * (withdrawn by its owner, or found revoked). Local only: made from the exchange's own steps, stored with the\n * chat's identity ledger, never sent. Nothing new goes on the wire.\n */\n\n/** \"mine\": this side shared it. \"theirs\": the contact did. */\nexport type IdentityTimelineSide = \"mine\" | \"theirs\";\nexport type IdentityTimelineState = \"verifying\" | \"verified\" | \"failed\";\n\nexport interface IdentityTimelineEntry {\n /**\n * Unique in the chat: side, proof and one past the highest number that proof's kept entries on that side have. A\n * contact's later attempt that took the entry over keeps it (see applyIdentityEvent).\n */\n id: string;\n /** The proof's id (identityStatement().id). */\n proof: string;\n side: IdentityTimelineSide;\n kind: \"shared\" | \"stopped\";\n provider: string;\n /** The identity, once known: at once on the sharer's side, from the presentation on the contact's. */\n subject?: string;\n /** A share only: where the contact's check stands. */\n state?: IdentityTimelineState;\n /** A failed share: why, as the verifier said it. */\n error?: string;\n /** A stop only: its owner withdrew it here, or its proof key published a revocation. */\n reason?: \"withdrawn\" | \"revoked\";\n /** Milliseconds. When it happened; later steps of the same share leave it in place. */\n at: number;\n}\n\n/** One step of the exchange, as the timeline needs it. */\nexport type IdentityTimelineEvent =\n /** A share began: this side shared, or the contact asked for a challenge. `requested`: the id the request named. */\n | { type: \"shared\"; side: IdentityTimelineSide; proof: string; provider: string; subject?: string }\n /** The contact's check settled. `requested`: the id the request named, when the presented proof is another. */\n | { type: \"result\"; side: IdentityTimelineSide; proof: string; requested?: string; provider?: string; subject?: string; ok: boolean; error?: string }\n | { type: \"stopped\"; side: IdentityTimelineSide; proof: string; provider: string; subject?: string; reason: \"withdrawn\" | \"revoked\" }\n /** A share taken back before it ever left this side (queued, the contact never heard of it): its entry goes. */\n | { type: \"unsent\"; side: \"mine\"; proof: string }\n /** The contact asked for a challenge and presented nothing within its window: its entry goes, as `unsent` does. */\n | { type: \"unanswered\"; side: \"theirs\"; proof: string };\n\n/** Entries a chat keeps, newest last. */\nexport const IDENTITY_TIMELINE_MAX = 100;\n\nconst lastOf = (timeline: readonly IdentityTimelineEntry[], side: IdentityTimelineSide, proofs: readonly (string | undefined)[]) => {\n for (let i = timeline.length - 1; i >= 0; i--) if (timeline[i].side === side && proofs.includes(timeline[i].proof)) return i;\n return -1;\n};\n\n/** The contact's share of this kind still not verified (checking, or failed): the one its next attempt takes over. */\nconst unverifiedOf = (timeline: readonly IdentityTimelineEntry[], provider: string | undefined) => {\n for (let i = timeline.length - 1; i >= 0; i--) {\n const e = timeline[i];\n if (e.side === \"theirs\" && e.kind === \"shared\" && e.state !== \"verified\" && e.provider === provider) return i;\n }\n return -1;\n};\n\n/**\n * The timeline after one step. A share already on it is updated in place, never repeated: a request sent again at\n * a reconnect, a second share of a proof the contact already verified. A new attempt after a failure or a stop is\n * a new entry, except the contact's own not verified: those keep one entry per kind, which its next attempt takes\n * over in place (its id and time stay, so no new sound and the chat does not move). The ids and the kind are the\n * contact's to choose, so otherwise its requests alone could push every other entry, this side's too, out of the\n * bound. A stop is written once; a withdrawal later found revoked becomes a revocation in place.\n */\nexport function applyIdentityEvent(timeline: readonly IdentityTimelineEntry[], event: IdentityTimelineEvent, at: number): IdentityTimelineEntry[] {\n const out = [...timeline];\n const i = lastOf(out, event.side, event.type === \"result\" ? [event.proof, event.requested] : [event.proof]);\n const last = i >= 0 ? out[i] : undefined;\n /** Puts the contact's attempt on the entry of its kind still not verified, if there is one. */\n const takeOver = (entry: Omit<IdentityTimelineEntry, \"id\" | \"at\" | \"side\" | \"kind\">) => {\n const j = event.side === \"theirs\" ? unverifiedOf(out, entry.provider) : -1;\n if (j < 0) return false;\n out[j] = { id: out[j].id, proof: entry.proof, side: \"theirs\", kind: \"shared\", provider: entry.provider, ...(entry.subject ? { subject: entry.subject } : {}),\n state: entry.state, ...(entry.error ? { error: entry.error } : {}), at: out[j].at };\n return true;\n };\n const add = (entry: Omit<IdentityTimelineEntry, \"id\" | \"at\">) => {\n // One past the highest number kept, not the count: the bound may have cut this proof's earlier entries.\n const prefix = `${entry.side}:${entry.proof}:`;\n let n = 0;\n for (const e of out) if (e.id.startsWith(prefix)) n = Math.max(n, Number(e.id.slice(prefix.length)) + 1 || 0);\n out.push({ ...entry, id: `${prefix}${n}`, at });\n };\n switch (event.type) {\n case \"shared\":\n if (last?.kind === \"shared\" && last.state !== \"failed\") {\n out[i] = { ...last, provider: event.provider, subject: event.subject ?? last.subject };\n break;\n }\n if (takeOver({ proof: event.proof, provider: event.provider, subject: event.subject, state: \"verifying\" })) break;\n add({ proof: event.proof, side: event.side, kind: \"shared\", provider: event.provider, ...(event.subject ? { subject: event.subject } : {}), state: \"verifying\" });\n break;\n case \"result\": {\n const settled = { state: event.ok ? \"verified\" as const : \"failed\" as const, ...(event.ok || !event.error ? {} : { error: event.error }) };\n if (last?.kind === \"shared\") {\n const { error: _, ...rest } = last;\n out[i] = { ...rest, proof: event.proof, provider: event.provider ?? last.provider, subject: event.subject ?? last.subject, ...settled };\n break;\n }\n // Its start is no longer kept (the timeline is bounded, or a later attempt took it over): the outcome stands\n // alone, a failed one on the contact's entry of its kind still not verified.\n if (!event.ok && event.provider && takeOver({ proof: event.proof, provider: event.provider, subject: event.subject, ...settled })) break;\n if (event.provider) add({ proof: event.proof, side: event.side, kind: \"shared\", provider: event.provider, ...(event.subject ? { subject: event.subject } : {}), ...settled });\n break;\n }\n case \"stopped\":\n // A revocation found after the withdrawal (a removal is both, WISP 300) says what the stop was: the same entry.\n if (last?.kind === \"stopped\") { if (last.reason === \"withdrawn\" && event.reason === \"revoked\") out[i] = { ...last, reason: \"revoked\" }; break; }\n add({ proof: event.proof, side: event.side, kind: \"stopped\", provider: event.provider, subject: event.subject ?? last?.subject, reason: event.reason });\n break;\n case \"unsent\":\n case \"unanswered\":\n if (last?.kind === \"shared\" && last.state === \"verifying\") out.splice(i, 1);\n break;\n }\n return out.length > IDENTITY_TIMELINE_MAX ? out.slice(-IDENTITY_TIMELINE_MAX) : out;\n}\n\n/** When the contact last shared an identity here (milliseconds), for the chat list: 0 when never. */\nexport function lastSharedWithMe(timeline: readonly IdentityTimelineEntry[] | undefined): number {\n let at = 0;\n for (const e of timeline ?? []) if (e.side === \"theirs\" && e.kind === \"shared\" && e.at > at) at = e.at;\n return at;\n}\n","import { sha256 } from \"@noble/hashes/sha2.js\";\nimport { fromBase64Url, isZ32Key, randomBytes, toBase64Url, utf8Encode } from \"./bytes\";\nimport { identityFromSeed, publicKeyFromZ32, sign, verify } from \"./identity\";\nimport { applyIdentityEvent, type IdentityTimelineEntry, type IdentityTimelineEvent } from \"./identityTimeline\";\nimport { hasVisible, stripHidden } from \"./text\";\n\n/**\n * Identity proofs (WISP 300), provider-agnostic half.\n *\n * A proof is made once per profile: the external identity (a Nostr key, a domain, an SSH key, an\n * OpenID Connect account…) signs or attests the canonical **statement** below, which authorizes a\n * fresh Ed25519 **proof key** that only this profile holds. Sharing it with a contact is then a\n * challenge-response on that contact's authenticated paired channel: the contact sends a fresh nonce,\n * the proof key signs a **presentation** binding the proof to both participation keys, the\n * conversation, the session and that nonce. A copy replayed to anyone else fails: wrong audience,\n * unknown nonce, and nobody else has the proof key.\n *\n * Providers (browser side, `packages/browser/src/proofs/`) only know how to produce and check the\n * evidence over the statement bytes; everything here is shared, so every provider signs the same bytes.\n */\n\nexport const IDENTITY_PROOF_CAPABILITY = \"identity-proof/1\";\n/** Domain separation: the first words of every statement. */\nexport const IDENTITY_STATEMENT_PREFIX = \"Ghostly identity proof v1\";\n/** No binding is valid for longer than this, whatever the provider allows. */\nexport const IDENTITY_MAX_VALIDITY = 400 * 86_400;\n/** A binding issued this far in the future is refused (seconds of clock disagreement tolerated). */\nexport const IDENTITY_CLOCK_SKEW = 300;\n/** A contact's challenge must be answered within this many seconds. */\nexport const IDENTITY_CHALLENGE_WINDOW = 300;\n/** Evidence, serialized as JSON, is at most this many characters. */\nexport const IDENTITY_MAX_EVIDENCE = 16 * 1024;\n/** A whole `idp-*` frame, serialized. */\nexport const IDENTITY_MAX_FRAME = 32 * 1024;\n/** Unanswered challenges a verifier keeps per conversation. */\nconst MAX_CHALLENGES = 8;\n/** A challenge still open at `now` (seconds): a presentation for it is still taken. */\nconst liveAt = (c: { issuedAt: number }, now: number) => c.issuedAt > now - IDENTITY_CHALLENGE_WINDOW;\n/**\n * Proofs a verifier keeps from one contact. A newer proof of the same identity replaces the older one, and one no longer\n * standing (withdrawn, revoked, expired) gives its place to a new one; past that a presentation is refused before it is\n * checked, so a contact cannot make this side store, re-send to its pages and look up its proofs without end.\n */\nexport const IDENTITY_MAX_RECEIVED = 16;\n/** `idp-*` frames a paired session reads from the contact per `IDENTITY_FRAME_WINDOW_MS`; the rest are dropped unread. */\nexport const IDENTITY_FRAME_LIMIT = 40;\nexport const IDENTITY_FRAME_WINDOW_MS = 60_000;\n/**\n * `idp-*` frames this side sends a contact per `IDENTITY_SEND_WINDOW_MS`, so that the person's own shares and stops fit\n * the contact's per-chat limits above and none is dropped unread there. Lower than the contact's count over a longer\n * window: frames can arrive closer together than they left.\n */\nexport const IDENTITY_SEND_LIMIT = IDENTITY_FRAME_LIMIT - 4;\nexport const IDENTITY_SEND_WINDOW_MS = IDENTITY_FRAME_WINDOW_MS + 10_000;\n/**\n * A request or withdraw the contact did not answer is sent again after this (ms), twice as long each time, at most\n * `IDENTITY_RESENDS` times a connection; past that it waits for the next one, as before.\n */\nexport const IDENTITY_RESEND_MS = 60_000;\nexport const IDENTITY_RESENDS = 4;\n/**\n * A proof this side holds verified, presented again with the same evidence between the same keys, is answered from that\n * check while it is younger than this (seconds): the contact chooses how often it presents, and each check costs this\n * device a provider lookup (a forge's per-IP quota, a DNS query, a contact's server) and a Pkarr read. An hour keeps an\n * answer as fresh as a re-share can expect; past it, and between, the daily re-check (or Check again) asks the provider.\n */\nexport const IDENTITY_REUSE_CHECK_S = 3600;\n/**\n * Presentations a verifier checks with their provider per contact in an hour; past it the contact is told the check\n * could not run. Room for every proof it may keep (`IDENTITY_MAX_RECEIVED`) and a few retries: a contact making fresh\n * proofs cannot spend a forge's per-IP quota (GitHub: 60 an hour) for every chat and app on this network.\n */\nexport const IDENTITY_MAX_CHECKS_PER_HOUR = 20;\n\nexport const IDENTITY_PROVIDER_ID = /^[a-z][a-z0-9-]{0,31}$/;\n/** Printable ASCII without spaces, so the statement can be built but never needs parsing. */\nexport const IDENTITY_SUBJECT = /^[\\x21-\\x7e]{1,512}$/;\nconst BINDING_NONCE = /^[A-Za-z0-9_-]{22}$/;\nconst CHALLENGE_NONCE = /^[A-Za-z0-9_-]{43}$/;\nconst HEX64 = /^[a-f0-9]{64}$/;\nconst SIG = /^[A-Za-z0-9_-]{86}$/;\n\n/** What the external identity signs, as fields. `key` is the proof key (z-base-32 Ed25519). */\nexport interface IdentityBinding {\n v: 1;\n provider: string;\n subject: string;\n key: string;\n issuedAt: number;\n expiresAt: number;\n nonce: string;\n}\n\n/** A binding with its exact bytes. Providers sign `text` (UTF-8 `bytes`) and never rebuild it. */\nexport interface IdentityStatement {\n binding: IdentityBinding;\n text: string;\n bytes: Uint8Array;\n /** SHA-256 of `bytes`, lowercase hex: the proof's id everywhere (storage, frames, OIDC nonce input). */\n id: string;\n}\n\n/** What a provider's `verify` established. Stored by the verifier with the evidence. */\nexport interface VerifiedIdentity {\n /** The identity that was proven, canonical. Self-custodied providers: exactly `binding.subject`. */\n subject: string;\n /** How it was checked, for people: \"Nostr signature (BIP-340)\", \"ID token signed by accounts.google.com\". */\n source: string;\n /** Provider-attested only: who vouches for `subject` (an issuer host). */\n attester?: string;\n /** Earlier than the binding's own expiry when the evidence says so (a key or certificate expiring). */\n expiresAt?: number;\n /** Optional name/picture carried by the evidence itself, with where it came from. */\n display?: IdentityDisplay;\n}\n\nexport interface IdentityDisplay {\n name?: string;\n /** A sanitized `data:image/…` URL, never a remote one. */\n avatar?: string;\n /** Where the person can see the identity (a profile page), https only. */\n url?: string;\n /** Where name/picture came from: \"Nostr kind-0 metadata (self-described)\". */\n source: string;\n fetchedAt: number;\n}\n\nexport interface IdentityScope { subject: string; audience: string; context: string; session: string }\n\n/**\n * Early revocation: the proof key publishes, under its own Pkarr key, a TXT record naming the proof it\n * revokes. Anyone holding a copy can look it up by the key in the binding; nothing else is published,\n * and the key is random, so the record says nothing about the identity or its contacts.\n */\nexport const IDENTITY_REVOCATION_LABEL = \"_ghostly-revoked\";\nexport const identityRevocationValue = (id: string, at: number) => `v=1;id=${id};at=${at}`;\n/** True when these records (resolved and signature-checked under the proof key) revoke proof `id`. */\nexport function revokesIdentity(records: { label: string; value: string }[], id: string): boolean {\n return records.some(r => r.label === IDENTITY_REVOCATION_LABEL && new RegExp(`^v=1;id=${id};at=\\\\d{1,12}$`).test(r.value));\n}\n\nconst nowSeconds = () => Math.floor(Date.now() / 1000);\nconst hex = (bytes: Uint8Array) => Array.from(bytes, b => b.toString(16).padStart(2, \"0\")).join(\"\");\nconst iso = (seconds: number) => new Date(seconds * 1000).toISOString().replace(/\\.\\d{3}Z$/, \"Z\");\nconst isInt = (v: unknown): v is number => Number.isSafeInteger(v) && (v as number) > 0;\n\nexport function isIdentityBinding(value: unknown): value is IdentityBinding {\n const b = value as IdentityBinding;\n return !!b && typeof b === \"object\" && !Array.isArray(b) &&\n Object.keys(b).sort().join(\",\") === \"expiresAt,issuedAt,key,nonce,provider,subject,v\" && b.v === 1 &&\n typeof b.provider === \"string\" && IDENTITY_PROVIDER_ID.test(b.provider) &&\n typeof b.subject === \"string\" && IDENTITY_SUBJECT.test(b.subject) &&\n isZ32Key(b.key) && typeof b.nonce === \"string\" && BINDING_NONCE.test(b.nonce) &&\n isInt(b.issuedAt) && isInt(b.expiresAt) && b.expiresAt > b.issuedAt && b.expiresAt - b.issuedAt <= IDENTITY_MAX_VALIDITY &&\n // ISO dates in the text need years 1970–9999.\n b.expiresAt < 253_402_300_800;\n}\n\n/**\n * The canonical statement, one line, so it survives every tool and clipboard (no line-ending\n * ambiguity). Every field is space-free and the order is fixed, so the text is injective.\n */\nexport function identityStatementText(b: IdentityBinding): string {\n if (!isIdentityBinding(b)) throw new Error(\"Invalid identity binding\");\n return `${IDENTITY_STATEMENT_PREFIX}: I control ${b.provider}:${b.subject} and authorize the Ghostly key ${b.key} ` +\n `to present it to contacts I choose, from ${iso(b.issuedAt)} until ${iso(b.expiresAt)}. Nonce: ${b.nonce}`;\n}\n\nexport function identityStatement(binding: IdentityBinding): IdentityStatement {\n const text = identityStatementText(binding);\n const bytes = utf8Encode(text);\n return { binding: { ...binding }, text, bytes, id: hex(sha256(bytes)) };\n}\n\n/** A new binding and the seed of its proof key. The seed stays in this profile; never share it. */\nexport function newIdentityBinding(options: { provider: string; subject: string; validitySeconds: number; now?: number }): { binding: IdentityBinding; seed: Uint8Array } {\n const issuedAt = options.now ?? nowSeconds();\n const seed = randomBytes(32);\n const binding: IdentityBinding = { v: 1, provider: options.provider, subject: options.subject,\n key: identityFromSeed(seed).pubKeyZ32, issuedAt, expiresAt: issuedAt + options.validitySeconds, nonce: toBase64Url(randomBytes(16)) };\n if (!isIdentityBinding(binding)) { seed.fill(0); throw new Error(\"Invalid identity provider, subject or validity\"); }\n return { binding, seed };\n}\n\n/** Bytes the proof key signs for one contact. `scope` is the presenter's view (subject = presenter). */\nexport function identityPresentationBytes(proofId: string, scope: IdentityScope, nonce: string, issuedAt: number): Uint8Array {\n return utf8Encode(JSON.stringify([\"ghostly-identity-presentation\", 1, proofId, scope.subject, scope.audience, scope.context, scope.session, nonce, issuedAt]));\n}\n\nexport function signIdentityPresentation(seed: Uint8Array, proofId: string, scope: IdentityScope, nonce: string, issuedAt: number): string {\n return toBase64Url(sign(identityPresentationBytes(proofId, scope, nonce, issuedAt), seed));\n}\n\nexport function verifyIdentityPresentation(key: string, sig: string, proofId: string, scope: IdentityScope, nonce: string, issuedAt: number): boolean {\n if (typeof sig !== \"string\" || !SIG.test(sig) || !isZ32Key(key)) return false;\n return verify(fromBase64Url(sig), identityPresentationBytes(proofId, scope, nonce, issuedAt), publicKeyFromZ32(key));\n}\n\nconst clean = (value: unknown, max: number): string | undefined => {\n if (typeof value !== \"string\") return undefined;\n // One line of plain text, as a nickname: no control, format, bidi or line-separator character from peer-supplied text.\n const text = stripHidden(value).trim();\n return text && hasVisible(text) ? text.slice(0, max) : undefined;\n};\n\n/**\n * Room for a line that names a domain (up to 253 characters) once or twice: a How line or a reason cut inside the name\n * names a record that does not exist, and the app no longer knows the reason to say it in the person's language.\n */\nconst SOURCE_MAX = 640;\nconst ERROR_MAX = 512;\n\n/** Bounds a provider's result so a buggy provider cannot store or show arbitrary data. */\nexport function boundVerifiedIdentity(v: VerifiedIdentity): VerifiedIdentity {\n if (!v || typeof v.subject !== \"string\" || !IDENTITY_SUBJECT.test(v.subject)) throw new Error(\"Provider returned an invalid subject\");\n const source = clean(v.source, SOURCE_MAX);\n if (!source) throw new Error(\"Provider did not say how it verified\");\n const out: VerifiedIdentity = { subject: v.subject, source };\n const attester = clean(v.attester, 253);\n if (attester) out.attester = attester;\n if (v.expiresAt !== undefined) { if (!isInt(v.expiresAt)) throw new Error(\"Provider returned an invalid expiry\"); out.expiresAt = v.expiresAt; }\n if (v.display) out.display = boundIdentityDisplay(v.display);\n return out;\n}\n\n/** Bounds a provider's public name/picture (from a proof or `lookupDisplay`): a name with nothing visible left is dropped. */\nexport function boundIdentityDisplay(d: IdentityDisplay): IdentityDisplay {\n const display: IdentityDisplay = { source: clean(d.source, 120) ?? \"Self-described\", fetchedAt: isInt(d.fetchedAt) ? d.fetchedAt : nowSeconds() };\n const name = clean(d.name, 64);\n if (name) display.name = name;\n if (typeof d.avatar === \"string\" && d.avatar.length <= 48 * 1024 && /^data:image\\/(png|jpeg);base64,[A-Za-z0-9+/=]+$/.test(d.avatar)) display.avatar = d.avatar;\n if (typeof d.url === \"string\" && d.url.length <= 512) { try { const u = new URL(d.url); if (u.protocol === \"https:\" && !u.username && !u.password) display.url = u.href; } catch { /* dropped */ } }\n return display;\n}\n\n// ---------------------------------------------------------------------------------------------\n// Per-conversation exchange\n\n/** Sharer side, one per proof shared in this conversation. */\nexport interface SharedIdentity {\n id: string;\n provider: string;\n subject: string;\n /**\n * The identity the contact keeps it under (the provider's verified subject: an OIDC binding names the issuer, its\n * account is the issuer and `sub`). Absent in older ledgers.\n */\n account?: string;\n /** queued: the person chose to share, the contact is not connected yet. */\n status: \"queued\" | \"pending\" | \"accepted\" | \"rejected\" | \"withdrawal-pending\" | \"withdrawn\";\n /** Seconds. When the status last changed. */\n at: number;\n error?: string;\n}\n\n/** Verifier side: a contact's proof as this app checked it. */\nexport interface ReceivedIdentity {\n id: string;\n binding: IdentityBinding;\n evidence: unknown;\n verified: VerifiedIdentity;\n /** The participation keys it was presented between (presenter, then this side). */\n presenter: string;\n audience: string;\n context: string;\n verifiedAt: number;\n checkedAt: number;\n /**\n * unconfirmed: a re-check failed (the domain record is gone, the account cannot be confirmed).\n * revoked: its proof key published a revocation (the person removed it from their profile).\n */\n status: \"verified\" | \"withdrawn\" | \"unconfirmed\" | \"revoked\";\n error?: string;\n /** A name/picture looked up on the person's request (Nostr kind-0), with its source. */\n display?: IdentityDisplay;\n}\n\n/** `id`: the proof the request named, kept here only (never sent) so the timeline can settle its entry.\n * `withdrawn`: its owner withdrew that proof while this side was checking its presentation. */\nexport interface IdentityChallenge { nonce: string; issuedAt: number; provider: string; id?: string; withdrawn?: true }\n\nexport interface IdentityLedger {\n challenges: IdentityChallenge[];\n shared: SharedIdentity[];\n received: ReceivedIdentity[];\n /** What the chat's timeline shows of this exchange (identityTimeline.ts). Local only; absent in older ledgers. */\n timeline?: IdentityTimelineEntry[];\n}\nexport const emptyIdentityLedger = (): IdentityLedger => ({ challenges: [], shared: [], received: [] });\n\n/** `account`: the subject its provider verified (`VerifiedIdentity.subject`); the binding's subject when not given. */\nexport interface LocalIdentityProof { statement: IdentityStatement; evidence: unknown; seed: Uint8Array; account?: string }\n\nexport interface IdentityExchangeOptions {\n /** This side's view of the authenticated channel; throws when there is none. */\n scope(): IdentityScope;\n send(frame: object): void;\n storage: { read(): IdentityLedger; update(change: (ledger: IdentityLedger) => IdentityLedger): Promise<void> };\n /** Providers this app can verify. */\n providers(): readonly string[];\n /** A proof of this profile, by id; undefined once removed. */\n localProof(id: string): LocalIdentityProof | undefined | Promise<LocalIdentityProof | undefined>;\n /** Parses and checks untrusted evidence for a statement (the registry's `verifyIdentity`). */\n verify(statement: IdentityStatement, evidence: unknown): Promise<VerifiedIdentity>;\n /** Looks up the proof key's revocation record. Resolves false when there is none or it cannot be read. */\n revoked?(statement: IdentityStatement): Promise<boolean>;\n now?(): number;\n onError?(error: string): void;\n /**\n * Off: every frame goes at once and nothing unanswered is sent again in a connection (for tests that play a contact\n * sending past the limits). On by default: `IDENTITY_SEND_LIMIT`, `IDENTITY_RESEND_MS`.\n */\n paced?: boolean;\n}\n\nexport type IdentityStatus = \"verified\" | \"expired\" | \"withdrawn\" | \"revoked\" | \"unconfirmed\" | \"previous-key\";\n\n/** What the verifier should show for a received proof right now. */\nexport function receivedIdentityStatus(r: ReceivedIdentity, presenter: string | undefined, audience: string | undefined, now = nowSeconds()): IdentityStatus {\n if (r.presenter !== presenter || r.audience !== audience) return \"previous-key\";\n if (r.status === \"withdrawn\") return \"withdrawn\";\n if (r.status === \"revoked\") return \"revoked\";\n if (Math.min(r.binding.expiresAt, r.verified.expiresAt ?? Infinity) <= now) return \"expired\";\n return r.status === \"unconfirmed\" ? \"unconfirmed\" : \"verified\";\n}\n\nconst standing = (r: ReceivedIdentity, now: number) =>\n r.status !== \"withdrawn\" && r.status !== \"revoked\" && Math.min(r.binding.expiresAt, r.verified.expiresAt ?? Infinity) > now;\n/**\n * `received` with room for one more proof: `replaced` (the older proof of the same identity) dropped, then the oldest ones\n * no longer standing; undefined when every place is still taken.\n */\nfunction receivedWithRoom(received: ReceivedIdentity[], id: string, replaced: (r: ReceivedIdentity) => boolean, now: number): ReceivedIdentity[] | undefined {\n const kept = received.filter(r => r.id !== id && !replaced(r));\n const gone = kept.filter(r => !standing(r, now)).sort((a, b) => a.verifiedAt - b.verifiedAt);\n const drop = new Set(gone.slice(0, Math.max(0, kept.length - IDENTITY_MAX_RECEIVED + 1)));\n const out = kept.filter(r => !drop.has(r));\n return out.length < IDENTITY_MAX_RECEIVED ? out : undefined;\n}\n\nconst REVOKED = \"Its owner revoked this proof\";\n/** Revoked is final: a later lookup that fails or finds nothing (the relays forgot it) does not undo it. */\nconst revokedHere = (received: ReceivedIdentity[], id: string) => received.some(r => r.id === id && r.status === \"revoked\");\n\nconst shortError = (e: unknown) => clean(e instanceof Error ? e.message : String(e), ERROR_MAX) ?? \"Invalid proof\";\n\n/**\n * A check this side could not finish because of what its own network did: a host it refused to contact, a server\n * that did not answer or answered an error. The message is for this side only. The contact is told the proof could\n * not be checked, never which host, address or status was seen, so a proof cannot make a contact's app report on\n * the network it sits in.\n */\nexport class IdentityCheckUnavailable extends Error {\n constructor(message: string) { super(message); this.name = \"IdentityCheckUnavailable\"; }\n}\n\n/** What the contact is told when the check failed with an IdentityCheckUnavailable. */\nexport const IDENTITY_CHECK_UNAVAILABLE = \"Your contact's app could not check it. Try again later.\";\n\nconst TOO_MANY_RECEIVED = \"Your contact keeps too many identities from you already\";\n\nconst NEWER_HELD = \"Your contact keeps a newer proof of this identity from you\";\n\nconst peerError = (e: unknown) => e instanceof IdentityCheckUnavailable ? IDENTITY_CHECK_UNAVAILABLE : shortError(e);\n\nconst UNSUPPORTED_KIND = \"Your contact's app cannot verify this kind of identity yet\";\nconst NOT_IN_PROFILE = \"That identity is no longer in your profile\";\nconst CONTACT_REFUSED = \"Your contact could not verify it\";\nconst EXPIRED = \"The proof has expired\";\n/** The refusals a contact's app writes itself (onRequest, onPresent): the only words of its `idp-result` kept as they came. */\nconst CONTACT_REFUSALS = new Set([UNSUPPORTED_KIND, IDENTITY_CHECK_UNAVAILABLE, TOO_MANY_RECEIVED, REVOKED, EXPIRED, NEWER_HELD]);\n\n/**\n * Why a share of mine was not accepted, as this app may say it under my identity: one of the refusals above or my own\n * app's line; else nothing past \"not verified\". Any other words came from the contact (a ledger kept before this check)\n * and would read as this app's own notice.\n */\nexport const identityRefusal = (error: unknown): string | undefined =>\n typeof error === \"string\" && (CONTACT_REFUSALS.has(error) || error === NOT_IN_PROFILE) ? error : undefined;\n\n/**\n * The `idp-*` exchange of one conversation. Frames (all JSON, additive, over the paired channel,\n * only when both offers carry `identity-proof/1`):\n *\n * idp-hello {providers} each side, when the channel is ready\n * idp-request {id, provider} sharer → verifier: \"give me a challenge for this proof\"\n * idp-challenge {id, nonce, issuedAt} verifier, after saving the nonce\n * idp-present {nonce, issuedAt, binding, evidence, sig}\n * idp-result {id, ok, error?} verifier, after saving the outcome\n * idp-withdraw {id} / idp-withdrawn {id}\n */\nexport class IdentityExchange {\n private peerProviders: readonly string[] | undefined;\n private requested = new Set<string>();\n /** The nonces of the presentations in their provider's check now. */\n private checking = new Set<string>();\n /** When the contact's presentations were checked with their provider (seconds), for `IDENTITY_MAX_CHECKS_PER_HOUR`. */\n private checks: number[] = [];\n /** When this side sent its recent frames (ms), for `IDENTITY_SEND_LIMIT`. Kept across connections, as the contact's count is. */\n private sentAt: number[] = [];\n /** Hello, answers and presentations waiting for room in that window, in order (`proof`: a presentation's). */\n private outbox: { frame: object; proof?: string }[] = [];\n /**\n * This connection's request or withdraw per proof: when it (or its presentation) last went, how often, and whether its\n * presentation went. Requests and withdraws are built from the ledger when their turn comes, so one stopped or\n * answered meanwhile never goes.\n */\n private attempts = new Map<string, { kind: \"request\" | \"withdraw\"; at: number; tries: number; presented?: true }>();\n private timer: ReturnType<typeof setTimeout> | undefined;\n constructor(private options: IdentityExchangeOptions) {}\n private now() { return (this.options.now ?? nowSeconds)(); }\n /** The ledger with one more step on the chat's timeline, in milliseconds (a test's clock, in seconds, when given). */\n private log(l: IdentityLedger, event: IdentityTimelineEvent): IdentityLedger {\n return { ...l, timeline: applyIdentityEvent(l.timeline ?? [], event, this.options.now ? this.now() * 1000 : Date.now()) };\n }\n private incomingScope(): IdentityScope { const s = this.options.scope(); return { ...s, subject: s.audience, audience: s.subject }; }\n private send(frame: object, proof?: string) {\n if (JSON.stringify(frame).length > IDENTITY_MAX_FRAME) throw new Error(\"Identity proof too large\");\n // A contact sending past what it can read itself gets no more answers waiting here than it could read.\n if (this.outbox.length >= IDENTITY_FRAME_LIMIT) return;\n this.outbox.push({ frame, proof });\n this.pump();\n }\n /** Sends one frame and counts it; false when the channel is gone (what waits is sent on the next connection). */\n private transmit(frame: object, at: number): boolean {\n try { this.options.send(frame); } catch { this.outbox = []; return false; }\n this.sentAt.push(at);\n return true;\n }\n private static resendAfter(tries: number) { return IDENTITY_RESEND_MS * 2 ** (tries - 1); }\n /**\n * Sends what fits the contact's limits now and sets a timer for the rest: the waiting answers first, then requests\n * (at most `MAX_CHALLENGES` open, each keeping room in the window for its presentation) and withdraws, then the\n * unanswered ones again once their time is up.\n */\n private pump(): void {\n if (this.timer !== undefined) clearTimeout(this.timer);\n this.timer = undefined;\n const paced = this.options.paced !== false;\n const [limit, maxOpen] = paced ? [IDENTITY_SEND_LIMIT, MAX_CHALLENGES] : [Infinity, Infinity];\n const at = Date.now();\n this.sentAt = paced ? this.sentAt.filter(t => t > at - IDENTITY_SEND_WINDOW_MS && t <= at) : [];\n /** When the window has room for one more frame under `n`. */\n const roomAt = (n: number) => this.sentAt[this.sentAt.length - n] + IDENTITY_SEND_WINDOW_MS;\n let wake = Infinity;\n while (this.outbox.length && this.sentAt.length < limit) {\n const { frame, proof } = this.outbox.shift()!;\n if (!this.transmit(frame, at)) return;\n const a = proof ? this.attempts.get(proof) : undefined;\n if (a) { a.at = at; a.presented = true; }\n }\n if (this.outbox.length) wake = roomAt(limit);\n const shared = this.options.storage.read().shared;\n const kindOf = (s: SharedIdentity) => s.status === \"queued\" || s.status === \"pending\" ? \"request\" as const : s.status === \"withdrawal-pending\" ? \"withdraw\" as const : undefined;\n for (const [id, a] of this.attempts) { const s = shared.find(x => x.id === id); if (!s || kindOf(s) !== a.kind) this.attempts.delete(id); }\n const dueAt = (a: { at: number; tries: number }) => !paced || a.tries > IDENTITY_RESENDS ? Infinity : a.at + IdentityExchange.resendAfter(a.tries);\n // A request given up for this connection (answered without a challenge, or sent as often as it may be) holds no place.\n const opened = [...this.attempts.values()].filter(a => a.kind === \"request\" && a.tries <= IDENTITY_RESENDS && dueAt(a) > at);\n let open = opened.length;\n /** Presentations still to come for the open requests: room kept for them. */\n let owed = opened.filter(a => !a.presented).length;\n for (const s of shared) {\n const kind = kindOf(s);\n if (!kind) continue;\n const a = this.attempts.get(s.id);\n if (a && dueAt(a) > at) { wake = Math.min(wake, dueAt(a)); continue; }\n if (a && (!paced || a.tries > IDENTITY_RESENDS)) continue;\n if (kind === \"request\" && open >= maxOpen) continue;\n // A request needs room for itself and for its presentation, beside the presentations still owed.\n const need = kind === \"request\" ? 2 : 1;\n if (this.sentAt.length + owed + need > limit) { wake = Math.min(wake, roomAt(limit - owed - need + 1)); break; }\n const frame = kind === \"request\" ? { t: \"idp-request\", id: s.id, provider: s.provider } : { t: \"idp-withdraw\", id: s.id };\n if (!this.transmit(frame, at)) return;\n if (kind === \"request\") { this.requested.add(s.id); open++; owed++; }\n const tries = (a?.tries ?? 0) + 1;\n this.attempts.set(s.id, { kind, at, tries });\n wake = Math.min(wake, dueAt({ at, tries }));\n }\n if (!paced) this.sentAt = [];\n if (wake === Infinity) return;\n const timer = this.timer = setTimeout(() => { if (this.timer === timer) this.pump(); }, Math.max(0, wake - at) + 1);\n (timer as { unref?: () => void }).unref?.();\n }\n private shared(id: string) { return this.options.storage.read().shared.find(s => s.id === id); }\n private async setShared(entry: SharedIdentity, event?: IdentityTimelineEvent) {\n await this.options.storage.update(l => {\n const next = { ...l, shared: [...l.shared.filter(s => s.id !== entry.id), entry] };\n return event ? this.log(next, event) : next;\n });\n }\n\n /** The providers the contact said it verifies; undefined until its hello. */\n get contactProviders(): readonly string[] | undefined { return this.peerProviders; }\n\n /** The channel is ready: say what we verify, then send what the person queued while offline, paced (`pump`). */\n ready(): void {\n this.options.scope();\n // A new connection: what went on the last one may not have arrived, so everything unanswered is due again.\n this.attempts.clear();\n this.send({ t: \"idp-hello\", providers: [...this.options.providers()] });\n }\n stop(): void {\n this.requested.clear(); this.peerProviders = undefined;\n this.outbox = []; this.attempts.clear();\n if (this.timer !== undefined) clearTimeout(this.timer);\n this.timer = undefined;\n }\n\n /**\n * The challenges whose window ended unanswered go, and with them their requests' lines still verifying: a contact\n * whose app closed, or whose proof left its profile, before it presented tells this side nothing, and its line read\n * \"verifying\" for good. No write when none ended.\n */\n async expire(): Promise<void> {\n const now = this.now();\n if (!this.options.storage.read().challenges.some(c => !liveAt(c, now))) return;\n await this.options.storage.update(l => this.withoutExpired(l, now));\n }\n private withoutExpired(l: IdentityLedger, now: number): IdentityLedger {\n const live = l.challenges.filter(c => liveAt(c, now));\n if (live.length === l.challenges.length) return l;\n // A request sent again (a reconnect) has a live challenge of the same id, whose line it shares.\n const ended = new Set(l.challenges.filter(c => c.id !== undefined && !liveAt(c, now) && !live.some(x => x.id === c.id)).map(c => c.id!));\n return [...ended].reduce((out, proof) => this.log(out, { type: \"unanswered\", side: \"theirs\", proof }), { ...l, challenges: live });\n }\n\n /** Share a proof of this profile with this contact: now if connected, else when it next is. */\n async share(id: string, connected: boolean): Promise<void> {\n const local = await this.options.localProof(id);\n if (!local) throw new Error(\"That identity is no longer in your profile\");\n const { provider, subject } = local.statement.binding;\n const entry: SharedIdentity = { id, provider, subject, account: local.account ?? subject, status: \"queued\", at: this.now() };\n await this.setShared(entry, { type: \"shared\", side: \"mine\", proof: id, provider, subject });\n this.attempts.delete(id);\n if (connected) this.pump();\n }\n\n /** Stop sharing here. The contact is told (now or on reconnect); a copy it kept cannot be erased. */\n async withdraw(id: string, connected: boolean): Promise<void> {\n let s = this.shared(id);\n if (!s || s.status === \"withdrawn\") return;\n this.requested.delete(id);\n if (s.status === \"queued\") {\n // Unless its challenge was answered meanwhile: that presentation is out, so it is withdrawn as a pending one.\n let answered: SharedIdentity | undefined;\n await this.options.storage.update(l => {\n answered = l.shared.find(x => x.id === id && x.status === \"pending\");\n return answered ? l : this.log({ ...l, shared: l.shared.filter(x => x.id !== id) }, { type: \"unsent\", side: \"mine\", proof: id });\n });\n if (!answered) return;\n s = answered;\n }\n // One the contact refused, it never held: its app writes no stop, and neither does this side.\n await this.setShared({ ...s, status: \"withdrawal-pending\", at: this.now(), error: undefined },\n s.status === \"rejected\" ? undefined : { type: \"stopped\", side: \"mine\", proof: id, provider: s.provider, subject: s.subject, reason: \"withdrawn\" });\n // A link that closed during that write: the withdrawal stays pending and ready() sends it on reconnect.\n if (connected) this.pump();\n }\n\n /**\n * Run the checks again on a received proof: its revocation record, then (unless `revocationOnly`) the\n * provider's check (a domain record may be gone). `keepUnavailable`: a check that could not run (IdentityCheckUnavailable)\n * is thrown, and the proof is left as it was, for a check this side started on its own.\n */\n async recheck(id: string, { revocationOnly = false, keepUnavailable = false } = {}): Promise<ReceivedIdentity> {\n const r = this.options.storage.read().received.find(x => x.id === id);\n if (!r) throw new Error(\"Unknown identity\");\n if (r.status === \"revoked\") return r;\n if (await this.options.revoked?.(identityStatement(r.binding)).catch(() => false)) {\n return await this.settleRecheck(id, x => x.status === \"revoked\" ? x : { ...x, status: \"revoked\", checkedAt: this.now(), error: undefined },\n { type: \"stopped\", side: \"theirs\", proof: id, provider: r.binding.provider, subject: r.verified.subject, reason: \"revoked\" }) ?? r;\n }\n if (revocationOnly) return r;\n let outcome: (x: ReceivedIdentity) => ReceivedIdentity;\n try {\n const verified = boundVerifiedIdentity(await this.options.verify(identityStatement(r.binding), r.evidence));\n if (verified.subject !== r.verified.subject) throw new Error(\"The identity changed\");\n outcome = x => ({ ...x, verified: { ...verified, display: verified.display ?? x.verified.display }, checkedAt: this.now(), status: \"verified\", error: undefined });\n } catch (e) {\n if (keepUnavailable && e instanceof IdentityCheckUnavailable) throw e;\n const error = shortError(e);\n outcome = x => ({ ...x, checkedAt: this.now(), status: \"unconfirmed\", error });\n }\n // Applied to the record as it is once the check is back: a withdraw or revocation that landed meanwhile holds.\n return await this.settleRecheck(id, x => x.status === \"revoked\" ? x : x.status === \"withdrawn\" ? { ...outcome(x), status: \"withdrawn\" } : outcome(x)) ?? r;\n }\n private async settleRecheck(id: string, outcome: (x: ReceivedIdentity) => ReceivedIdentity, event?: IdentityTimelineEvent): Promise<ReceivedIdentity | undefined> {\n let next: ReceivedIdentity | undefined;\n await this.options.storage.update(l => {\n const x = l.received.find(y => y.id === id);\n if (!x) return l;\n next = outcome(x);\n const out = { ...l, received: l.received.map(y => y.id === id ? next! : y) };\n return event && x.status !== \"revoked\" ? this.log(out, event) : out;\n });\n return next;\n }\n\n async receive(frame: Record<string, unknown>): Promise<void> {\n try {\n if (JSON.stringify(frame).length > IDENTITY_MAX_FRAME) throw new Error(\"Identity proof too large\");\n const id = typeof frame.id === \"string\" && HEX64.test(frame.id) ? frame.id : undefined;\n switch (frame.t) {\n case \"idp-hello\":\n if (Array.isArray(frame.providers) && frame.providers.length <= 64)\n this.peerProviders = frame.providers.filter((p): p is string => typeof p === \"string\" && IDENTITY_PROVIDER_ID.test(p));\n return;\n case \"idp-request\": return await this.onRequest(id, frame.provider);\n case \"idp-challenge\": return await this.onChallenge(id, frame.nonce, frame.issuedAt);\n case \"idp-present\": {\n // The engine checks a presentation beside the chat's other frames, not before them: a copy of one still in\n // its check is refused here, so it never reaches the provider twice.\n const nonce = typeof frame.nonce === \"string\" ? frame.nonce : \"\";\n if (this.checking.has(nonce)) throw new Error(\"Unknown or reused identity challenge\");\n this.checking.add(nonce);\n try { return await this.onPresent(frame); } finally { this.checking.delete(nonce); }\n }\n case \"idp-result\": {\n const s = id ? this.shared(id) : undefined;\n // Answered without a challenge (a kind the contact does not verify): asked again only on the next connection.\n const asked = id ? this.attempts.get(id) : undefined;\n if (asked?.kind === \"request\" && s?.status === \"queued\") asked.tries = IDENTITY_RESENDS + 1;\n if (!s || s.status !== \"pending\") { this.pump(); return; }\n const ok = frame.ok === true;\n // Only a refusal its app writes: any other text is the contact's own, never shown as this app's line.\n const error = ok ? undefined : typeof frame.error === \"string\" && CONTACT_REFUSALS.has(frame.error) ? frame.error : CONTACT_REFUSED;\n const entry: SharedIdentity = { ...s, status: ok ? \"accepted\" : \"rejected\", at: this.now(), error };\n // The contact keeps one proof per identity (onPresent): the one it accepted replaced any other of the same\n // provider and verified identity it held from here, so that one is no longer shared in this chat. Matched on\n // the account, not the binding's subject (two OIDC accounts at one issuer are two identities there); one whose\n // account this side does not know stays shared, so Stop sharing still reaches it.\n // Its share stops on the timeline too, as the contact's does (onPresent).\n const replaced = (x: SharedIdentity) => ok && x.status === \"accepted\" && x.provider === s.provider &&\n x.account !== undefined && x.account === s.account;\n await this.options.storage.update(l => l.shared.filter(x => x.id !== s.id && replaced(x)).reduce(\n (out, x) => this.log(out, { type: \"stopped\", side: \"mine\", proof: x.id, provider: x.provider, subject: x.subject, reason: \"withdrawn\" }),\n this.log({ ...l, shared: [\n ...l.shared.filter(x => x.id !== s.id).map(x => replaced(x) ? { ...x, status: \"withdrawn\" as const, at: entry.at } : x), entry,\n ] }, { type: \"result\", side: \"mine\", proof: s.id, ok, error })));\n // Its place among the open requests is free for the next one.\n this.pump();\n return;\n }\n case \"idp-withdraw\": {\n if (!id) return;\n // A durable write only for a proof this side actually received and still holds: a withdraw naming an\n // unknown (or already-withdrawn) id is only acknowledged, never written, so it cannot be repeated for a\n // durable write each time. The ack is always sent (a share the contact refused is withdrawn this way too).\n // A revoked one stays revoked: the owner revoked it everywhere, which says more than a withdraw from here.\n const r = this.options.storage.read().received.find(x => x.id === id);\n if (r && r.status !== \"withdrawn\" && r.status !== \"revoked\")\n await this.options.storage.update(l => this.log(\n { ...l, received: l.received.map(x => x.id === id ? { ...x, status: \"withdrawn\" as const } : x) },\n { type: \"stopped\", side: \"theirs\", proof: id, provider: r.binding.provider, subject: r.verified.subject, reason: \"withdrawn\" }));\n // A presentation of it may still be in its check (a withdraw on a new session after a reconnect): noted on\n // the challenge, so the check's outcome is stored withdrawn. Once per challenge, and challenges are bounded.\n if (this.options.storage.read().challenges.some(c => c.id === id && !c.withdrawn))\n await this.options.storage.update(l => ({ ...l, challenges: l.challenges.map(c => c.id === id ? { ...c, withdrawn: true as const } : c) }));\n this.send({ t: \"idp-withdrawn\", id });\n return;\n }\n case \"idp-withdrawn\": {\n const s = id ? this.shared(id) : undefined;\n if (s?.status === \"withdrawal-pending\") await this.setShared({ ...s, status: \"withdrawn\", at: this.now() });\n return;\n }\n }\n } catch (e) { this.options.onError?.(shortError(e)); }\n }\n\n private async onRequest(id: string | undefined, provider: unknown) {\n if (!id) return;\n if (typeof provider !== \"string\" || !this.options.providers().includes(provider)) {\n // A kind this app does not verify: told so at once (`idp-result`), no durable write. The provider is the\n // contact's to choose, so a write here would let it fill the timeline (one entry per fresh id, the real\n // verified line pushed out) and ring the identity cue, with no limit.\n const error = UNSUPPORTED_KIND;\n this.send({ t: \"idp-result\", id, ok: false, error });\n return;\n }\n this.options.scope();\n const now = this.now();\n const challenge: IdentityChallenge = { nonce: toBase64Url(randomBytes(32)), issuedAt: now, provider, id };\n // Saved before it is sent: a presentation for a nonce this side never saved is always refused.\n await this.options.storage.update(l => {\n if (l.challenges.filter(c => liveAt(c, now)).length >= MAX_CHALLENGES) throw new Error(\"Too many identity challenges\");\n // The request's line first, the ended challenges after: a line of this kind an ended one left verifying is\n // taken over in place (its id and time stay), and only the other ended ones' lines go.\n return this.withoutExpired(this.log({ ...l, challenges: [...l.challenges, challenge] }, { type: \"shared\", side: \"theirs\", proof: id, provider }), now);\n });\n this.send({ t: \"idp-challenge\", id, nonce: challenge.nonce, issuedAt: challenge.issuedAt });\n }\n\n private async onChallenge(id: string | undefined, nonce: unknown, issuedAt: unknown) {\n if (!id || !this.requested.has(id) || typeof nonce !== \"string\" || !CHALLENGE_NONCE.test(nonce) || !isInt(issuedAt)) return;\n const s = this.shared(id);\n if (!s || (s.status !== \"queued\" && s.status !== \"pending\")) return;\n this.requested.delete(id);\n const local = await this.options.localProof(id);\n if (!local) {\n const error = NOT_IN_PROFILE;\n await this.setShared({ ...s, status: \"rejected\", at: this.now(), error }, { type: \"result\", side: \"mine\", proof: id, ok: false, error });\n return;\n }\n const scope = this.options.scope();\n const sig = signIdentityPresentation(local.seed, id, scope, nonce, issuedAt);\n // Read again in the write: a Remove or Unshare while the proof key was opened holds, and nothing is presented.\n let stopped = false;\n await this.options.storage.update(l => {\n const x = l.shared.find(y => y.id === id);\n if (!x || (x.status !== \"queued\" && x.status !== \"pending\")) { stopped = true; return l; }\n return { ...l, shared: [...l.shared.filter(y => y.id !== id), { ...x, status: \"pending\", at: this.now(), error: undefined }] };\n });\n if (stopped) return;\n this.send({ t: \"idp-present\", nonce, issuedAt, binding: local.statement.binding, evidence: local.evidence, sig }, id);\n }\n\n private async onPresent(frame: Record<string, unknown>) {\n const { nonce, issuedAt, binding, evidence, sig } = frame;\n if (typeof nonce !== \"string\" || !CHALLENGE_NONCE.test(nonce) || !isInt(issuedAt) || !isIdentityBinding(binding)) return;\n const statement = identityStatement(binding);\n const id = statement.id;\n const scope = this.incomingScope();\n const now = this.now();\n const challengeOf = (l: IdentityLedger) => l.challenges.find(c => c.nonce === nonce && c.issuedAt === issuedAt && c.provider === binding.provider && liveAt(c, now));\n const known = (l: IdentityLedger) => !!challengeOf(l);\n if (!known(this.options.storage.read())) throw new Error(\"Unknown or reused identity challenge\");\n let verified: VerifiedIdentity | undefined;\n // Only what the contact may know: see IdentityCheckUnavailable.\n let error: string | undefined;\n /** The same, as this side's own timeline says it. */\n let reason: string | undefined;\n /** Its owner withdrew the proof while this check ran: no result goes out (see below). */\n let withdrawn = false;\n /** The check could not run on this side (IdentityCheckUnavailable). */\n let unavailable = false;\n /** The same proof this side holds verified, checked recently: its answer is reused (`IDENTITY_REUSE_CHECK_S`). */\n let reused: ReceivedIdentity | undefined;\n try {\n // Before anything is checked or looked up: a contact past the bound costs this side nothing more.\n // The checked subject is not known yet: an identity kept under the binding's subject may be the one replaced.\n const mayReplace = (r: ReceivedIdentity) => r.binding.provider === binding.provider && (r.binding.subject === binding.subject || r.verified.subject === binding.subject);\n if (revokedHere(this.options.storage.read().received, id)) throw new Error(REVOKED);\n if (!receivedWithRoom(this.options.storage.read().received, id, mayReplace, now)) throw new Error(TOO_MANY_RECEIVED);\n if (JSON.stringify(evidence ?? null).length > IDENTITY_MAX_EVIDENCE) throw new Error(\"Evidence too large\");\n if (!verifyIdentityPresentation(binding.key, sig as string, id, scope, nonce, issuedAt)) throw new Error(\"The proof key did not sign this conversation's challenge\");\n if (binding.issuedAt > now + IDENTITY_CLOCK_SKEW) throw new Error(\"The proof is dated in the future\");\n const evidenceJson = JSON.stringify(evidence ?? null);\n reused = this.options.storage.read().received.find(r => r.id === id && r.status === \"verified\" && r.presenter === scope.subject &&\n r.audience === scope.audience && r.context === scope.context && r.checkedAt <= now && now - r.checkedAt < IDENTITY_REUSE_CHECK_S &&\n JSON.stringify(r.evidence ?? null) === evidenceJson);\n if (!reused) {\n this.checks = this.checks.filter(t => t > now - 3600 && t <= now);\n if (this.checks.length >= IDENTITY_MAX_CHECKS_PER_HOUR) throw new IdentityCheckUnavailable(\"Too many of this contact's proofs to check this hour\");\n this.checks.push(now);\n }\n const result = reused ? reused.verified : boundVerifiedIdentity(await this.options.verify(statement, evidence));\n if (Math.min(binding.expiresAt, result.expiresAt ?? Infinity) <= now) throw new Error(EXPIRED);\n // A presentation needs the proof key, so this only matters when its seed leaked: a lookup that\n // fails is not a refusal, a revocation found is. A held proof was looked up with its check.\n if (!reused && await this.options.revoked?.(statement).catch(() => false)) throw new Error(REVOKED);\n verified = result;\n } catch (e) { error = peerError(e); reason = shortError(e); unavailable = e instanceof IdentityCheckUnavailable; }\n // Consuming the nonce and recording the outcome are one transaction.\n await this.options.storage.update(l => {\n const challenge = challengeOf(l);\n if (!challenge) throw new Error(\"Unknown or reused identity challenge\");\n const challenges = l.challenges.filter(c => c.nonce !== nonce);\n withdrawn = !!challenge.withdrawn;\n // Withdrawn while it was checked, then shared again: the newer share decides, so this outcome is dropped. A withdraw\n // marks every challenge and record of that proof, so one of them still unmarked came with the newer share.\n if (withdrawn && (challenges.some(c => c.id === challenge.id && !c.withdrawn) ||\n l.received.some(r => r.id === challenge.id && r.status !== \"withdrawn\" && r.status !== \"revoked\"))) return { ...l, challenges };\n // A newer proof of the same identity replaces the older one; the bound holds for presentations checked at once.\n const subject = verified?.subject;\n // A re-check may have found it revoked while it was being checked.\n if (verified && revokedHere(l.received, id)) { verified = undefined; error = reason = REVOKED; }\n // Checked beside a newer one that is stored already: the binding's date decides, not which check ended last.\n if (verified && l.received.some(r => r.id !== id && r.binding.provider === binding.provider && r.verified.subject === subject &&\n r.binding.issuedAt > binding.issuedAt && standing(r, now))) { verified = undefined; error = reason = NEWER_HELD; }\n // A held proof's record as it is now: one a re-check found unconfirmed meanwhile is not written back verified.\n const prior = reused && l.received.find(r => r.id === id);\n if (verified && reused && prior?.status !== (withdrawn ? \"withdrawn\" : \"verified\")) {\n verified = undefined; error = IDENTITY_CHECK_UNAVAILABLE; reason = \"It was checked again while it was presented\";\n }\n const received = verified && receivedWithRoom(l.received, id, r => r.binding.provider === binding.provider && r.verified.subject === subject, now);\n if (verified && !received) { verified = undefined; error = reason = TOO_MANY_RECEIVED; }\n // This proof, held from this contact already, presented again (its result was lost, so it was asked again): the\n // check settles the held copy. One that could not run leaves a verified copy standing, and the contact is told it\n // is held; one that failed turns it unconfirmed, as a re-check does.\n const held = verified ? undefined : l.received.find(r => r.id === id && r.presenter === scope.subject && r.audience === scope.audience &&\n (r.status === \"verified\" || r.status === \"unconfirmed\"));\n const stands = held?.status === \"verified\" && unavailable;\n if (stands) { verified = held.verified; error = reason = undefined; }\n const logged = this.log(l, { type: \"result\", side: \"theirs\", proof: id, requested: challenge.id, provider: binding.provider,\n subject: verified?.subject ?? binding.subject, ok: !!verified, ...(reason ? { error: reason } : {}) });\n if (stands) return { ...logged, challenges };\n if (!verified || !received) return { ...logged, challenges, received: held && !unavailable\n ? l.received.map(r => r === held ? { ...r, checkedAt: now, status: \"unconfirmed\" as const, error: reason } : r) : l.received };\n // Its owner withdrew it while it was being checked: kept as if the withdraw had come just after.\n const record: ReceivedIdentity = { id, binding, evidence, verified, presenter: scope.subject, audience: scope.audience, context: scope.context,\n verifiedAt: prior?.verifiedAt ?? now, checkedAt: prior?.checkedAt ?? now, status: withdrawn ? \"withdrawn\" : \"verified\" };\n // The older proof it replaced is no longer held: its share stops on the timeline (one already stopped has its stop).\n const replaced = l.received.filter(r => r.id !== id && !received.includes(r) && r.binding.provider === binding.provider && r.verified.subject === subject\n && r.status !== \"withdrawn\" && r.status !== \"revoked\");\n const kept = replaced.reduce((out, r) => this.log(out, { type: \"stopped\", side: \"theirs\", proof: r.id, provider: r.binding.provider, subject: r.verified.subject, reason: \"withdrawn\" }),\n { ...logged, challenges, received: [...received, record] });\n return withdrawn ? this.log(kept, { type: \"stopped\", side: \"theirs\", proof: id, provider: binding.provider, subject: verified.subject, reason: \"withdrawn\" }) : kept;\n });\n // A withdrawn one gets no result, verified or not: the owner has it withdrawn (`idp-withdrawn` went out), and a late\n // one would settle a new share of the same proof made since.\n if (!withdrawn) this.send(verified ? { t: \"idp-result\", id, ok: true } : { t: \"idp-result\", id, ok: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