@ghostlytools/cli 1.13.1 → 1.13.3

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 (112) hide show
  1. package/README.md +15 -12
  2. package/dist/assets/api-DO0YMLiB.js +3 -0
  3. package/dist/assets/{api-Dnq86JAA.js → api-Dz2cw7WD.js} +512 -103
  4. package/dist/assets/api-Dz2cw7WD.js.map +1 -0
  5. package/dist/assets/{apiKit-nLK4jeTq.js → apiKit-DAFsWtyk.js} +53 -7
  6. package/dist/assets/apiKit-DAFsWtyk.js.map +1 -0
  7. package/dist/assets/{appFetch-wqBWi3Ry.js → appFetch-BQO5Pk7W.js} +2 -2
  8. package/dist/assets/{appFetch-wqBWi3Ry.js.map → appFetch-BQO5Pk7W.js.map} +1 -1
  9. package/dist/assets/{apps-DBVhKpfe.js → apps-B88rYWRm.js} +51 -23
  10. package/dist/assets/apps-B88rYWRm.js.map +1 -0
  11. package/dist/assets/{apps-nLtyhC2f.js → apps-D4KRpZB4.js} +1 -1
  12. package/dist/assets/{arkade-DryM-q5n.js → arkade-B6UNf5HI.js} +2 -2
  13. package/dist/assets/{arkade-DryM-q5n.js.map → arkade-B6UNf5HI.js.map} +1 -1
  14. package/dist/assets/{backup-D6s0LQdg.js → backup-BeXBtbVL.js} +1 -1
  15. package/dist/assets/{backup-Bczllmzf.js → backup-CNLY905d.js} +15 -8
  16. package/dist/assets/backup-CNLY905d.js.map +1 -0
  17. package/dist/assets/bark_ffi_wasm_bg-CjjCN3FD.js +5 -0
  18. package/dist/assets/{bitcoind-DML_-Xbv.js → bitcoind-BXZdQ1wZ.js} +2 -2
  19. package/dist/assets/{bitcoind-DML_-Xbv.js.map → bitcoind-BXZdQ1wZ.js.map} +1 -1
  20. package/dist/assets/bitcoindevkit_bg-D6IFIaJi.js +5 -0
  21. package/dist/assets/{buttons-B3C3vdhH.js → buttons-BKojbx0Q.js} +4 -4
  22. package/dist/assets/{buttons-B3C3vdhH.js.map → buttons-BKojbx0Q.js.map} +1 -1
  23. package/dist/assets/buttons-_5Fw8uHn.js +1 -0
  24. package/dist/assets/{client-B7jRrSnb.js → client-BtPhfWjK.js} +2 -2
  25. package/dist/assets/{client-B7jRrSnb.js.map → client-BtPhfWjK.js.map} +1 -1
  26. package/dist/assets/{engineErrors--9hfgKlK.js → engineErrors-wWlLy54D.js} +11 -3
  27. package/dist/assets/engineErrors-wWlLy54D.js.map +1 -0
  28. package/dist/assets/{fedimintSdk-D-6H9Pe7.js → fedimintSdk-eLXBrj9i.js} +2 -2
  29. package/dist/assets/{fedimintSdk-D-6H9Pe7.js.map → fedimintSdk-eLXBrj9i.js.map} +1 -1
  30. package/dist/assets/fedimint_client_wasm_bg-CRQlnJdu.js +5 -0
  31. package/dist/assets/{fixedHosts-H3i6o9Iy.js → fixedHosts-BJFL8Ell.js} +3 -3
  32. package/dist/assets/{fixedHosts-H3i6o9Iy.js.map → fixedHosts-BJFL8Ell.js.map} +1 -1
  33. package/dist/assets/{groupMeta--fxSh792.js → groupMeta-Cz95F6sX.js} +201 -43
  34. package/dist/assets/groupMeta-Cz95F6sX.js.map +1 -0
  35. package/dist/assets/{host-CGzVFfMz.js → host-BsBWxTtW.js} +276 -53
  36. package/dist/assets/host-BsBWxTtW.js.map +1 -0
  37. package/dist/assets/{hyperdhtRelay-Ce-gWsRY.js → hyperdhtRelay-B34Zhz4P.js} +2 -2
  38. package/dist/assets/{hyperdhtRelay-Ce-gWsRY.js.map → hyperdhtRelay-B34Zhz4P.js.map} +1 -1
  39. package/dist/assets/{hyperdhtRelay-B4_wdCtx.js → hyperdhtRelay-DDwU5b4P.js} +2 -2
  40. package/dist/assets/{hyperdhtRelay-B4_wdCtx.js.map → hyperdhtRelay-DDwU5b4P.js.map} +1 -1
  41. package/dist/assets/{identityProofs-Cksc_K7_.js → identityProofs-zI_Iy9uI.js} +154 -27
  42. package/dist/assets/identityProofs-zI_Iy9uI.js.map +1 -0
  43. package/dist/assets/{irohWeb-Dp1i8v6n.js → irohWeb-BLDcHwYz.js} +10866 -4829
  44. package/dist/assets/irohWeb-BLDcHwYz.js.map +1 -0
  45. package/dist/assets/{linkPreview-DdMf-YAc.js → linkPreview-5kHmKUTN.js} +20 -8
  46. package/dist/assets/linkPreview-5kHmKUTN.js.map +1 -0
  47. package/dist/assets/{main-C8J53SwH.js → main-D48Ben7C.js} +122 -49
  48. package/dist/assets/main-D48Ben7C.js.map +1 -0
  49. package/dist/assets/{mainline-DY95WbuK.js → mainline-CDUXtV-I.js} +2 -2
  50. package/dist/assets/{mainline-DY95WbuK.js.map → mainline-CDUXtV-I.js.map} +1 -1
  51. package/dist/assets/{networkReason-Be-hMghr.js → networkReason-DYlPZS5M.js} +2 -2
  52. package/dist/assets/{networkReason-Be-hMghr.js.map → networkReason-DYlPZS5M.js.map} +1 -1
  53. package/dist/assets/{ownDid-oa-T2vmZ.js → ownDid-CwxFBzOH.js} +6 -5
  54. package/dist/assets/ownDid-CwxFBzOH.js.map +1 -0
  55. package/dist/assets/{ownStatus-Bc08eNJY.js → ownStatus-DjD0sQKF.js} +34 -11
  56. package/dist/assets/ownStatus-DjD0sQKF.js.map +1 -0
  57. package/dist/assets/{pairedTransports-Dppn8lUN.js → pairedTransports-DAzupLYo.js} +21 -15
  58. package/dist/assets/pairedTransports-DAzupLYo.js.map +1 -0
  59. package/dist/assets/{paymentIntent-DySU3Ajm.js → paymentIntent-Cr3uZa_0.js} +2 -2
  60. package/dist/assets/{paymentIntent-DySU3Ajm.js.map → paymentIntent-Cr3uZa_0.js.map} +1 -1
  61. package/dist/assets/{profiles-B2uy04ph.js → profiles-BAJf0c9E.js} +33 -8
  62. package/dist/assets/profiles-BAJf0c9E.js.map +1 -0
  63. package/dist/assets/{registry-bLIfG619.js → registry-CHwHTWbK.js} +1 -1
  64. package/dist/assets/{registry-DbTLLs3y.js → registry-CPuexTle.js} +25 -13
  65. package/dist/assets/registry-CPuexTle.js.map +1 -0
  66. package/dist/assets/{relay-CHWg5hpZ.js → relay-gJTOYQJZ.js} +93 -7
  67. package/dist/assets/relay-gJTOYQJZ.js.map +1 -0
  68. package/dist/assets/{resolve-DNX-eecG.js → resolve-BqmGXKn4.js} +3 -3
  69. package/dist/assets/{resolve-DNX-eecG.js.map → resolve-BqmGXKn4.js.map} +1 -1
  70. package/dist/assets/{server-DWJ4RzJn.js → server-e4oKeNez.js} +901 -6262
  71. package/dist/assets/server-e4oKeNez.js.map +1 -0
  72. package/dist/assets/{sshForges-BnvwmNj-.js → sshForges-Cqt3qfWe.js} +2 -2
  73. package/dist/assets/{sshForges-BnvwmNj-.js.map → sshForges-Cqt3qfWe.js.map} +1 -1
  74. package/dist/assets/{translate-CHj_PdLg.js → translate-DnuQMfj0.js} +10 -4
  75. package/dist/assets/translate-DnuQMfj0.js.map +1 -0
  76. package/dist/assets/{usdt-CBJ4Q5Ji.js → usdt-DLmtf8F9.js} +4 -4
  77. package/dist/assets/{usdt-CBJ4Q5Ji.js.map → usdt-DLmtf8F9.js.map} +1 -1
  78. package/dist/assets/{waitNotice-Cvz5CiKR.js → waitNotice-mB0Ym145.js} +2 -2
  79. package/dist/assets/{waitNotice-Cvz5CiKR.js.map → waitNotice-mB0Ym145.js.map} +1 -1
  80. package/dist/ghostly.mjs +1 -1
  81. package/npm-shrinkwrap.json +2 -2
  82. package/package.json +1 -1
  83. package/dist/assets/api-DF36rBJK.js +0 -3
  84. package/dist/assets/api-Dnq86JAA.js.map +0 -1
  85. package/dist/assets/apiKit-nLK4jeTq.js.map +0 -1
  86. package/dist/assets/apps-DBVhKpfe.js.map +0 -1
  87. package/dist/assets/backup-Bczllmzf.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-DaY5FYlV.js +0 -1
  95. package/dist/assets/engineErrors--9hfgKlK.js.map +0 -1
  96. package/dist/assets/fedimint_client_wasm_bg-Cr5xGD-w.js +0 -5
  97. package/dist/assets/fedimint_client_wasm_bg-Cr5xGD-w.js.map +0 -1
  98. package/dist/assets/fedimint_client_wasm_bg-DeFtkIv6.wasm +0 -0
  99. package/dist/assets/groupMeta--fxSh792.js.map +0 -1
  100. package/dist/assets/host-CGzVFfMz.js.map +0 -1
  101. package/dist/assets/identityProofs-Cksc_K7_.js.map +0 -1
  102. package/dist/assets/irohWeb-Dp1i8v6n.js.map +0 -1
  103. package/dist/assets/linkPreview-DdMf-YAc.js.map +0 -1
  104. package/dist/assets/main-C8J53SwH.js.map +0 -1
  105. package/dist/assets/ownDid-oa-T2vmZ.js.map +0 -1
  106. package/dist/assets/ownStatus-Bc08eNJY.js.map +0 -1
  107. package/dist/assets/pairedTransports-Dppn8lUN.js.map +0 -1
  108. package/dist/assets/profiles-B2uy04ph.js.map +0 -1
  109. package/dist/assets/registry-DbTLLs3y.js.map +0 -1
  110. package/dist/assets/relay-CHWg5hpZ.js.map +0 -1
  111. package/dist/assets/server-DWJ4RzJn.js.map +0 -1
  112. package/dist/assets/translate-CHj_PdLg.js.map +0 -1
@@ -1,5 +1,5 @@
1
1
  import { i as fromBase64Url } from "./bytes-C1DNGY18.js";
2
- import { n as hyperdhtRelayUrl, t as hyperdhtRelayProblem } from "./hyperdhtRelay-B4_wdCtx.js";
2
+ import { n as hyperdhtRelayUrl, t as hyperdhtRelayProblem } from "./hyperdhtRelay-DDwU5b4P.js";
3
3
  import { ed25519 } from "@noble/curves/ed25519.js";
4
4
  // ../browser/src/platform/hyperdhtRelay.ts
5
5
  /**
@@ -404,4 +404,4 @@ async function createRelayedHyperEndpoint(seedB64, url, options = {}) {
404
404
  }
405
405
  export { createRelayedHyperEndpoint };
406
406
 
407
- //# sourceMappingURL=hyperdhtRelay-Ce-gWsRY.js.map
407
+ //# sourceMappingURL=hyperdhtRelay-B34Zhz4P.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"hyperdhtRelay-Ce-gWsRY.js","names":[],"sources":["../../../browser/src/platform/hyperdhtRelay.ts"],"sourcesContent":["import { ed25519 } from \"@noble/curves/ed25519.js\";\nimport { fromBase64Url, type BoundChannel, type FrameChannel, type NativeEndpoint } from \"@ghostly/core\";\nimport { hyperdhtRelayProblem, hyperdhtRelayUrl } from \"../shared/hyperdhtRelay\";\n\nexport { hyperdhtRelayProblem as relayUrlProblem };\n\n/**\n * HyperDHT (WISP 103) for a browser, through a dht-relay: a server that runs the UDP half of HyperDHT and\n * talks to the browser over one WebSocket. It runs non-custodial: the browser keeps its keys, runs the\n * Noise handshake and the encrypted stream itself, and the relay moves handshake messages and ciphertext.\n * The binding (the handshake hash and both keys) is computed here, at the endpoint, as the Desktop does.\n *\n * What the relay sees: this browser's address, the HyperDHT keys it listens on and dials, and when and how\n * much it sends. Not the frames, not the keys' secrets, not the handshake hash.\n *\n * The wire is the Desktop's (native/transports/hyperdht/endpoint.mjs): the same preface, u32 length-prefixed\n * UTF-8 frames of at most 60 KiB, so a browser and a Desktop talk HyperDHT to each other.\n */\n\nconst PREFACE = \"ghostly/paired-chat/1\";\nconst MAX_FRAME = 60 * 1024;\n/** The top bit of a frame's length word: the frame is a binary message, not UTF-8 text (WISP 103). */\nconst BINARY = 0x80000000;\nconst SEND_BUDGET = 120 * 1024;\nconst HANDSHAKE_MS = 20_000;\nconst RELAY_OPEN_MS = 10_000;\nconst LISTEN_MS = 20_000;\nconst MAX_CHANNELS = 2;\n/**\n * Streams dialled in that have not sent the preface yet. They hold none of the MAX_CHANNELS: a new one past this many\n * drops the oldest of them, so streams that stall can never keep the contact's out.\n */\nconst MAX_UNPREFACED = 4;\n/** The places of the streams dialled in: those whose preface came, and those still waiting for it (oldest first). */\ninterface DialledIn { live: Set<RelayedChannel>; unprefaced: Set<RelayedChannel> }\n/**\n * How the relay client is always made: never custodial. dht-relay's default is custodial, which sends every\n * secret key to the relay so it can run the handshake and the stream itself. Nothing here takes this from\n * settings or options; test/hyperdhtRelay.test.ts fails if a secret key ever reaches the relay's wire.\n */\nconst NON_CUSTODIAL = Object.freeze({ custodial: false as const });\n\n/**\n * The descriptor a browser's HyperDHT endpoint gives out: its key, that it is reached only through a relay, and\n * which one (the connection panel names its host; a Desktop dialling it ignores both).\n */\nexport interface RelayedHyperDescriptor { publicKey: string; relayed: true; relay: string }\n\n/** The parts of dht-relay and its streams this adapter uses. */\ninterface SecretSocket {\n handshakeHash: Uint8Array | null;\n publicKey: Uint8Array;\n remotePublicKey: Uint8Array;\n opened?: Promise<boolean>;\n destroyed?: boolean;\n write(data: Uint8Array): boolean;\n destroy(error?: Error): void;\n on(event: string, listener: (...args: never[]) => void): unknown;\n once(event: string, listener: (...args: never[]) => void): unknown;\n off(event: string, listener: (...args: never[]) => void): unknown;\n}\ninterface RelayedServer {\n listen(keyPair: KeyPair): Promise<void>;\n /** Where the relay's node listens for it, as the relay said; port 0 when the relay refused the listen. */\n address(): { port: number } | null;\n close(): Promise<void>;\n once(event: \"close\", listener: () => void): unknown;\n}\ninterface RelayedNode {\n ready(): Promise<void>;\n connect(remotePublicKey: Uint8Array, options: { keyPair: KeyPair }): SecretSocket;\n createServer(options: object, onconnection: (socket: SecretSocket) => void): RelayedServer;\n destroy(): Promise<void>;\n}\ninterface KeyPair { publicKey: Uint8Array; secretKey: Uint8Array }\n\nconst hex = (bytes: Uint8Array) => Array.from(bytes, b => b.toString(16).padStart(2, \"0\")).join(\"\");\nconst fromHex = (text: string) => Uint8Array.from(text.match(/../g)!, byte => parseInt(byte, 16));\n\n/** HyperDHT's key pair for a seed: libsodium's layout (the seed, then the public key). */\nexport function hyperKeyPair(seed: Uint8Array): KeyPair {\n if (seed.length !== 32) throw new Error(\"Invalid HyperDHT seed\");\n const publicKey = ed25519.getPublicKey(seed);\n const secretKey = new Uint8Array(64);\n secretKey.set(seed); secretKey.set(publicKey, 32);\n return { publicKey, secretKey };\n}\n\n/**\n * One WebSocket per relay for the whole app, shared by every chat's endpoint (each listens on its own\n * key). It closes when the last endpoint does. When the relay goes away, every endpoint on it says it is\n * unavailable, and the next one to start opens a new connection.\n */\ninterface RelayClient {\n node: RelayedNode;\n endpoints: Set<{ unavailable(): void }>;\n gone: boolean;\n}\nconst clients = new Map<string, Promise<RelayClient>>();\n\nasync function relayClient(url: string, createSocket: (url: string) => WebSocket): Promise<RelayClient> {\n const existing = clients.get(url);\n if (existing) {\n const client = await existing.catch(() => null);\n if (client && !client.gone) return client;\n if (clients.get(url) === existing) clients.delete(url);\n }\n const opening = (async () => {\n const [{ default: RelayedDHT }, { default: WebSocketStream }] = await Promise.all([\n // @ts-expect-error dht-relay ships no types: RelayedNode and SecretSocket above describe what this uses.\n import(\"@hyperswarm/dht-relay\"),\n // @ts-expect-error The same package's WebSocket stream, untyped too.\n import(\"@hyperswarm/dht-relay/ws\"),\n ]);\n const socket = createSocket(url);\n socket.binaryType = \"arraybuffer\";\n await new Promise<void>((resolve, reject) => {\n const timer = setTimeout(() => { socket.close(); reject(new Error(\"The HyperDHT relay did not answer\")); }, RELAY_OPEN_MS);\n socket.addEventListener(\"open\", () => { clearTimeout(timer); resolve(); }, { once: true });\n socket.addEventListener(\"error\", () => { clearTimeout(timer); reject(new Error(\"Could not reach the HyperDHT relay\")); }, { once: true });\n socket.addEventListener(\"close\", () => { clearTimeout(timer); reject(new Error(\"The HyperDHT relay closed the connection\")); }, { once: true });\n });\n // Non-custodial: the relay is told public keys only, never a secret key (dht-relay's default sends them).\n // The node's own key is never used to listen or dial: a random one says nothing about this app.\n const node = new RelayedDHT(new WebSocketStream(true, socket), { ...NON_CUSTODIAL, keyPair: hyperKeyPair(crypto.getRandomValues(new Uint8Array(32))) }) as RelayedNode;\n const client: RelayClient = { node, endpoints: new Set(), gone: false };\n socket.addEventListener(\"close\", () => {\n client.gone = true;\n if (clients.get(url) === opening) clients.delete(url);\n for (const endpoint of [...client.endpoints]) endpoint.unavailable();\n });\n return client;\n })();\n clients.set(url, opening);\n opening.catch(() => { if (clients.get(url) === opening) clients.delete(url); });\n return opening;\n}\n\n/**\n * dht-relay 0.4.3's server waits for the relay connection to close (to close itself) and never stops waiting once it has\n * closed, so every listener ever opened on the connection, closed or refused, stayed in memory with its chat's endpoint\n * until the connection went. The relay forgets its own side the same way (infra/services/hyperdht-relay `Servers`).\n */\nfunction forgetServer(server: RelayedServer): void {\n const internal = server as unknown as { _protocol?: { _stream?: { off(event: string, listener: () => void): unknown } }; _onStreamClose?: () => void };\n if (internal._onStreamClose) internal._protocol?._stream?.off(\"close\", internal._onStreamClose);\n}\n\nfunction release(url: string, client: RelayClient, endpoint: { unavailable(): void }): void {\n client.endpoints.delete(endpoint);\n if (client.endpoints.size || client.gone) return;\n client.gone = true;\n void clients.get(url)?.then(current => { if (current === client) clients.delete(url); }).catch(() => {});\n void client.node.destroy().catch(() => {});\n}\n\n/** One authenticated stream as a frame channel, with a bounded queue before the session installs its reader. */\nclass RelayedChannel implements FrameChannel {\n private reader: FrameChannel[\"onMessage\"] = null;\n private buffered: (string | Uint8Array)[] = [];\n private closed = false;\n private pendingBytes = 0;\n /** It carries binary messages (WISP 100 § Text and binary messages), as the Desktop's own HyperDHT does. */\n readonly binary = true;\n onClose: FrameChannel[\"onClose\"] = null;\n constructor(private readonly socket: SecretSocket) {\n socket.on(\"drain\", () => { this.pendingBytes = 0; });\n }\n get bufferedAmount(): number { return this.pendingBytes; }\n readonly sendBudget = SEND_BUDGET;\n get onMessage() { return this.reader; }\n set onMessage(reader: FrameChannel[\"onMessage\"]) {\n this.reader = reader;\n if (reader) for (const text of this.buffered.splice(0)) reader(text);\n }\n receive(text: string | Uint8Array): boolean {\n if (this.closed) return true;\n if (this.reader) this.reader(text);\n else if (this.buffered.length < 64) this.buffered.push(text);\n else return false;\n return true;\n }\n send(data: string | Uint8Array): void {\n if (this.closed || !data.length) throw new Error(\"Native channel is closed or exceeds its frame budget\");\n const binary = typeof data !== \"string\";\n const payload = binary ? data : new TextEncoder().encode(data);\n if (payload.length > MAX_FRAME || this.pendingBytes + payload.length > SEND_BUDGET) throw new Error(\"Native channel is closed or exceeds its frame budget\");\n // The stream takes every write; past its high-water mark it says so until it drains.\n if (!writeFrame(this.socket, payload, binary) || this.pendingBytes) this.pendingBytes += payload.length + 4;\n }\n drained(): Promise<void> {\n if (!this.pendingBytes) return Promise.resolve();\n return new Promise((resolve, reject) => {\n const done = () => { this.socket.off(\"close\", gone); resolve(); };\n const gone = () => { this.socket.off(\"drain\", done); reject(new Error(\"Native channel closed\")); };\n this.socket.once(\"drain\", done); this.socket.once(\"close\", gone);\n });\n }\n closedByPeer(): void {\n if (this.closed) return;\n this.closed = true; this.buffered = [];\n this.onClose?.();\n }\n close(): void {\n if (this.closed) return;\n this.socket.destroy();\n this.closedByPeer();\n }\n}\n\nfunction writeFrame(socket: SecretSocket, payload: Uint8Array, binary = false): boolean {\n const frame = new Uint8Array(4 + payload.length);\n new DataView(frame.buffer).setUint32(0, (binary ? BINARY : 0) + payload.length);\n frame.set(payload, 4);\n return socket.write(frame);\n}\n\n/**\n * Waits for the peer's preface on an authenticated stream (sending ours as soon as the handshake is\n * done), then hands the channel over with the binding the stream itself gives. A frame of the wrong size,\n * bytes that are not UTF-8 or another protocol close the stream.\n *\n * `dialledIn`: the stream was dialled in, and takes one of its MAX_CHANNELS only once its preface came. This side's own\n * dials are not counted: one always goes out.\n */\nfunction attach(socket: SecretSocket, channels: Set<RelayedChannel>, dialledIn?: DialledIn): Promise<BoundChannel> {\n if (dialledIn && dialledIn.live.size >= MAX_CHANNELS) { socket.destroy(); return Promise.reject(new Error(\"Native connection limit reached\")); }\n if (dialledIn && dialledIn.unprefaced.size >= MAX_UNPREFACED) {\n const [oldest] = dialledIn.unprefaced;\n dialledIn.unprefaced.delete(oldest); oldest.close();\n }\n const channel = new RelayedChannel(socket);\n channels.add(channel); dialledIn?.unprefaced.add(channel);\n return new Promise<BoundChannel>((resolve, reject) => {\n let buffer = new Uint8Array(0);\n let prefaced = false;\n const decoder = new TextDecoder(\"utf-8\", { fatal: true });\n const timer = setTimeout(() => socket.destroy(new Error(\"HyperDHT handshake timed out\")), HANDSHAKE_MS);\n const fail = (error: Error) => { socket.destroy(error); };\n socket.on(\"error\", (error: Error) => reject(error));\n socket.on(\"close\", () => {\n clearTimeout(timer); channels.delete(channel); dialledIn?.live.delete(channel); dialledIn?.unprefaced.delete(channel);\n reject(new Error(\"Native channel closed\"));\n channel.closedByPeer();\n });\n const opened = () => {\n if (socket.handshakeHash?.length !== 64 || socket.publicKey?.length !== 32 || socket.remotePublicKey?.length !== 32) {\n fail(new Error(\"Noise session binding unavailable\")); return;\n }\n writeFrame(socket, new TextEncoder().encode(PREFACE));\n };\n if (socket.opened) void socket.opened.then(ok => { if (ok) opened(); else reject(new Error(\"Noise handshake failed\")); });\n else socket.once(\"open\", opened);\n socket.on(\"data\", (chunk: Uint8Array) => {\n // Frames are read by offset and only the partial one left is kept (a copy, once per chunk), as on the\n // Desktop: copying the rest of the buffer per frame made a burst of tiny frames cost quadratic time.\n let joined = chunk;\n if (buffer.length) {\n joined = new Uint8Array(buffer.length + chunk.length);\n joined.set(buffer); joined.set(chunk, buffer.length);\n }\n let offset = 0;\n while (joined.length - offset >= 4) {\n const word = new DataView(joined.buffer, joined.byteOffset + offset, 4).getUint32(0);\n const binary = word >= BINARY, length = word % BINARY;\n // A binary frame before the preface is another protocol.\n if (length === 0 || length > MAX_FRAME || (binary && !prefaced)) { fail(new Error(\"Invalid frame length\")); return; }\n if (joined.length - offset < 4 + length) break;\n const payload = joined.subarray(offset + 4, offset + 4 + length);\n offset += 4 + length;\n if (binary) {\n if (!channel.receive(new Uint8Array(payload))) { fail(new Error(\"Receive queue exceeded\")); return; }\n continue;\n }\n let text: string;\n try { text = decoder.decode(payload); }\n catch { fail(new Error(\"Invalid UTF-8 frame\")); return; }\n if (!prefaced) {\n if (text !== PREFACE) { fail(new Error(\"Unexpected application protocol\")); return; }\n prefaced = true; clearTimeout(timer);\n if (dialledIn) {\n dialledIn.unprefaced.delete(channel);\n if (dialledIn.live.size >= MAX_CHANNELS) { fail(new Error(\"Native connection limit reached\")); return; }\n dialledIn.live.add(channel);\n }\n resolve({ channel, binding: { transport: \"hyperdht/1\", context: hex(socket.handshakeHash!),\n identities: [hex(socket.publicKey), hex(socket.remotePublicKey)].sort() as [string, string] } });\n } else if (!channel.receive(text)) { fail(new Error(\"Receive queue exceeded\")); return; }\n }\n buffer = new Uint8Array(joined.subarray(offset));\n });\n });\n}\n\nexport interface RelayedHyperOptions {\n /** How to open the WebSocket (tests pass Node's `ws`). Default: the browser's. */\n createSocket?: (url: string) => WebSocket;\n}\n\n/**\n * A chat's HyperDHT endpoint through the relay at `url`: it listens on the key of `seedB64` (the chat's\n * own transport seed, as on the Desktop) and dials a contact's descriptor. Fails, and so is not offered,\n * when the relay cannot be reached or does not let it listen.\n *\n * dht-relay 0.4.3 has no message for a refused listen (the relay's node refuses a key it already listens on, for\n * another client or an old connection of this one), and its client drops a `closed` for a server that has not had\n * `listening`. So the relay answers a refusal with `listening` at no address (port 0), then `closed`: that fails here\n * at once. A relay that answers nothing leaves the listen to LISTEN_MS. A server the relay closes later says the\n * endpoint is unavailable, as when the whole connection goes.\n */\nexport async function createRelayedHyperEndpoint(seedB64: string, url: string, options: RelayedHyperOptions = {}): Promise<NativeEndpoint> {\n const problem = hyperdhtRelayProblem(url);\n if (problem) throw new Error(problem);\n const keyPair = hyperKeyPair(fromBase64Url(seedB64));\n const client = await relayClient(url, options.createSocket ?? (address => new WebSocket(address)));\n const channels = new Set<RelayedChannel>();\n const dialledIn: DialledIn = { live: new Set(), unprefaced: new Set() };\n let stopped = false;\n let handler: NativeEndpoint[\"onConnection\"] = null;\n const waiting: BoundChannel[] = [];\n let endpoint: NativeEndpoint | null = null;\n // Fails the listen below when the relay connection closes while it waits.\n let relayClosed: (() => void) | null = null;\n const member = {\n unavailable() {\n if (client.gone) relayClosed?.();\n if (stopped) return;\n stopped = true;\n for (const channel of channels) channel.close();\n endpoint?.onUnavailable?.();\n },\n };\n client.endpoints.add(member);\n const server = client.node.createServer({}, socket => {\n void attach(socket, channels, dialledIn).then(bound => {\n if (stopped) bound.channel.close();\n else if (handler) handler(bound);\n else if (waiting.length < MAX_CHANNELS) waiting.push(bound);\n else bound.channel.close();\n }).catch(() => {});\n });\n let serverClosed = false;\n server.once(\"close\", () => { serverClosed = true; forgetServer(server); member.unavailable(); });\n // Neither wait outlasts the listen: one on `client.closed` stayed there, holding this endpoint, closed or refused, for as\n // long as the relay connection stayed open.\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n await Promise.race([\n server.listen(keyPair),\n new Promise((_, reject) => {\n relayClosed = () => reject(new Error(\"The HyperDHT relay closed the connection\"));\n if (client.gone) relayClosed();\n timer = setTimeout(() => reject(new Error(\"The HyperDHT relay did not let this chat listen\")), LISTEN_MS);\n }),\n ]);\n if (client.gone) throw new Error(\"The HyperDHT relay closed the connection\");\n if (serverClosed || !server.address()?.port) throw new Error(\"The HyperDHT relay did not let this chat listen\");\n } catch (error) {\n stopped = true;\n void server.close().catch(() => {});\n release(url, client, member);\n throw error;\n } finally {\n clearTimeout(timer);\n relayClosed = null;\n }\n const descriptor: RelayedHyperDescriptor = { publicKey: hex(keyPair.publicKey), relayed: true, relay: hyperdhtRelayUrl(url) };\n endpoint = {\n transport: \"hyperdht/1\", descriptor, onDescriptor: null, onUnavailable: null,\n get onConnection() { return handler; },\n set onConnection(value) { handler = value; if (value) for (const bound of waiting.splice(0)) value(bound); },\n async connect(address) {\n const publicKey = (address as { publicKey?: unknown } | null)?.publicKey;\n if (stopped || typeof publicKey !== \"string\" || !/^[a-f0-9]{64}$/.test(publicKey)) throw new Error(\"Invalid HyperDHT endpoint\");\n return attach(client.node.connect(fromHex(publicKey), { keyPair }), channels);\n },\n async close() {\n stopped = true;\n for (const channel of channels) channel.close();\n waiting.length = 0;\n await server.close().catch(() => {});\n release(url, client, member);\n },\n };\n return endpoint;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAmBA,IAAM,UAAU;AAChB,IAAM,YAAY;;AAElB,IAAM,SAAS;AACf,IAAM,cAAc;AACpB,IAAM,eAAe;AACrB,IAAM,gBAAgB;AACtB,IAAM,YAAY;AAClB,IAAM,eAAe;;;;;AAKrB,IAAM,iBAAiB;;;;;;AAQvB,IAAM,gBAAgB,OAAO,OAAO,EAAE,WAAW,MAAe,CAAC;AAoCjE,IAAM,OAAO,UAAsB,MAAM,KAAK,QAAO,MAAK,EAAE,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG,CAAC,CAAC,CAAC,KAAK,EAAE;AAClG,IAAM,WAAW,SAAiB,WAAW,KAAK,KAAK,MAAM,KAAK,IAAI,SAAQ,SAAS,MAAM,EAAE,CAAC;;AAGhG,SAAgB,aAAa,MAA2B;CACtD,IAAI,KAAK,WAAW,IAAI,MAAM,IAAI,MAAM,uBAAuB;CAC/D,MAAM,YAAY,QAAQ,aAAa,IAAI;CAC3C,MAAM,4BAAY,IAAI,WAAW,EAAE;CACnC,UAAU,IAAI,IAAI;CAAG,UAAU,IAAI,WAAW,EAAE;CAChD,OAAO;EAAE;EAAW;CAAU;AAChC;AAYA,IAAM,0BAAU,IAAI,IAAkC;AAEtD,eAAe,YAAY,KAAa,cAAgE;CACtG,MAAM,WAAW,QAAQ,IAAI,GAAG;CAChC,IAAI,UAAU;EACZ,MAAM,SAAS,MAAM,SAAS,YAAY,IAAI;EAC9C,IAAI,UAAU,CAAC,OAAO,MAAM,OAAO;EACnC,IAAI,QAAQ,IAAI,GAAG,MAAM,UAAU,QAAQ,OAAO,GAAG;CACvD;CACA,MAAM,WAAW,YAAY;EAC3B,MAAM,CAAC,EAAE,SAAS,cAAc,EAAE,SAAS,qBAAqB,MAAM,QAAQ,IAAI,CAEhF,OAAO,0BAEP,OAA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CACA,OAAO;AACT"}
1
+ {"version":3,"file":"hyperdhtRelay-B34Zhz4P.js","names":[],"sources":["../../../browser/src/platform/hyperdhtRelay.ts"],"sourcesContent":["import { ed25519 } from \"@noble/curves/ed25519.js\";\nimport { fromBase64Url, type BoundChannel, type FrameChannel, type NativeEndpoint } from \"@ghostly/core\";\nimport { hyperdhtRelayProblem, hyperdhtRelayUrl } from \"../shared/hyperdhtRelay\";\n\nexport { hyperdhtRelayProblem as relayUrlProblem };\n\n/**\n * HyperDHT (WISP 103) for a browser, through a dht-relay: a server that runs the UDP half of HyperDHT and\n * talks to the browser over one WebSocket. It runs non-custodial: the browser keeps its keys, runs the\n * Noise handshake and the encrypted stream itself, and the relay moves handshake messages and ciphertext.\n * The binding (the handshake hash and both keys) is computed here, at the endpoint, as the Desktop does.\n *\n * What the relay sees: this browser's address, the HyperDHT keys it listens on and dials, and when and how\n * much it sends. Not the frames, not the keys' secrets, not the handshake hash.\n *\n * The wire is the Desktop's (native/transports/hyperdht/endpoint.mjs): the same preface, u32 length-prefixed\n * UTF-8 frames of at most 60 KiB, so a browser and a Desktop talk HyperDHT to each other.\n */\n\nconst PREFACE = \"ghostly/paired-chat/1\";\nconst MAX_FRAME = 60 * 1024;\n/** The top bit of a frame's length word: the frame is a binary message, not UTF-8 text (WISP 103). */\nconst BINARY = 0x80000000;\nconst SEND_BUDGET = 120 * 1024;\nconst HANDSHAKE_MS = 20_000;\nconst RELAY_OPEN_MS = 10_000;\nconst LISTEN_MS = 20_000;\nconst MAX_CHANNELS = 2;\n/**\n * Streams dialled in that have not sent the preface yet. They hold none of the MAX_CHANNELS: a new one past this many\n * drops the oldest of them, so streams that stall can never keep the contact's out.\n */\nconst MAX_UNPREFACED = 4;\n/** The places of the streams dialled in: those whose preface came, and those still waiting for it (oldest first). */\ninterface DialledIn { live: Set<RelayedChannel>; unprefaced: Set<RelayedChannel> }\n/**\n * How the relay client is always made: never custodial. dht-relay's default is custodial, which sends every\n * secret key to the relay so it can run the handshake and the stream itself. Nothing here takes this from\n * settings or options; test/hyperdhtRelay.test.ts fails if a secret key ever reaches the relay's wire.\n */\nconst NON_CUSTODIAL = Object.freeze({ custodial: false as const });\n\n/**\n * The descriptor a browser's HyperDHT endpoint gives out: its key, that it is reached only through a relay, and\n * which one (the connection panel names its host; a Desktop dialling it ignores both).\n */\nexport interface RelayedHyperDescriptor { publicKey: string; relayed: true; relay: string }\n\n/** The parts of dht-relay and its streams this adapter uses. */\ninterface SecretSocket {\n handshakeHash: Uint8Array | null;\n publicKey: Uint8Array;\n remotePublicKey: Uint8Array;\n opened?: Promise<boolean>;\n destroyed?: boolean;\n write(data: Uint8Array): boolean;\n destroy(error?: Error): void;\n on(event: string, listener: (...args: never[]) => void): unknown;\n once(event: string, listener: (...args: never[]) => void): unknown;\n off(event: string, listener: (...args: never[]) => void): unknown;\n}\ninterface RelayedServer {\n listen(keyPair: KeyPair): Promise<void>;\n /** Where the relay's node listens for it, as the relay said; port 0 when the relay refused the listen. */\n address(): { port: number } | null;\n close(): Promise<void>;\n once(event: \"close\", listener: () => void): unknown;\n}\ninterface RelayedNode {\n ready(): Promise<void>;\n connect(remotePublicKey: Uint8Array, options: { keyPair: KeyPair }): SecretSocket;\n createServer(options: object, onconnection: (socket: SecretSocket) => void): RelayedServer;\n destroy(): Promise<void>;\n}\ninterface KeyPair { publicKey: Uint8Array; secretKey: Uint8Array }\n\nconst hex = (bytes: Uint8Array) => Array.from(bytes, b => b.toString(16).padStart(2, \"0\")).join(\"\");\nconst fromHex = (text: string) => Uint8Array.from(text.match(/../g)!, byte => parseInt(byte, 16));\n\n/** HyperDHT's key pair for a seed: libsodium's layout (the seed, then the public key). */\nexport function hyperKeyPair(seed: Uint8Array): KeyPair {\n if (seed.length !== 32) throw new Error(\"Invalid HyperDHT seed\");\n const publicKey = ed25519.getPublicKey(seed);\n const secretKey = new Uint8Array(64);\n secretKey.set(seed); secretKey.set(publicKey, 32);\n return { publicKey, secretKey };\n}\n\n/**\n * One WebSocket per relay for the whole app, shared by every chat's endpoint (each listens on its own\n * key). It closes when the last endpoint does. When the relay goes away, every endpoint on it says it is\n * unavailable, and the next one to start opens a new connection.\n */\ninterface RelayClient {\n node: RelayedNode;\n endpoints: Set<{ unavailable(): void }>;\n gone: boolean;\n}\nconst clients = new Map<string, Promise<RelayClient>>();\n\nasync function relayClient(url: string, createSocket: (url: string) => WebSocket): Promise<RelayClient> {\n const existing = clients.get(url);\n if (existing) {\n const client = await existing.catch(() => null);\n if (client && !client.gone) return client;\n if (clients.get(url) === existing) clients.delete(url);\n }\n const opening = (async () => {\n const [{ default: RelayedDHT }, { default: WebSocketStream }] = await Promise.all([\n // @ts-expect-error dht-relay ships no types: RelayedNode and SecretSocket above describe what this uses.\n import(\"@hyperswarm/dht-relay\"),\n // @ts-expect-error The same package's WebSocket stream, untyped too.\n import(\"@hyperswarm/dht-relay/ws\"),\n ]);\n const socket = createSocket(url);\n socket.binaryType = \"arraybuffer\";\n await new Promise<void>((resolve, reject) => {\n const timer = setTimeout(() => { socket.close(); reject(new Error(\"The HyperDHT relay did not answer\")); }, RELAY_OPEN_MS);\n socket.addEventListener(\"open\", () => { clearTimeout(timer); resolve(); }, { once: true });\n socket.addEventListener(\"error\", () => { clearTimeout(timer); reject(new Error(\"Could not reach the HyperDHT relay\")); }, { once: true });\n socket.addEventListener(\"close\", () => { clearTimeout(timer); reject(new Error(\"The HyperDHT relay closed the connection\")); }, { once: true });\n });\n // Non-custodial: the relay is told public keys only, never a secret key (dht-relay's default sends them).\n // The node's own key is never used to listen or dial: a random one says nothing about this app.\n const node = new RelayedDHT(new WebSocketStream(true, socket), { ...NON_CUSTODIAL, keyPair: hyperKeyPair(crypto.getRandomValues(new Uint8Array(32))) }) as RelayedNode;\n const client: RelayClient = { node, endpoints: new Set(), gone: false };\n socket.addEventListener(\"close\", () => {\n client.gone = true;\n if (clients.get(url) === opening) clients.delete(url);\n for (const endpoint of [...client.endpoints]) endpoint.unavailable();\n });\n return client;\n })();\n clients.set(url, opening);\n opening.catch(() => { if (clients.get(url) === opening) clients.delete(url); });\n return opening;\n}\n\n/**\n * dht-relay 0.4.3's server waits for the relay connection to close (to close itself) and never stops waiting once it has\n * closed, so every listener ever opened on the connection, closed or refused, stayed in memory with its chat's endpoint\n * until the connection went. The relay forgets its own side the same way (infra/services/hyperdht-relay `Servers`).\n */\nfunction forgetServer(server: RelayedServer): void {\n const internal = server as unknown as { _protocol?: { _stream?: { off(event: string, listener: () => void): unknown } }; _onStreamClose?: () => void };\n if (internal._onStreamClose) internal._protocol?._stream?.off(\"close\", internal._onStreamClose);\n}\n\nfunction release(url: string, client: RelayClient, endpoint: { unavailable(): void }): void {\n client.endpoints.delete(endpoint);\n if (client.endpoints.size || client.gone) return;\n client.gone = true;\n void clients.get(url)?.then(current => { if (current === client) clients.delete(url); }).catch(() => {});\n void client.node.destroy().catch(() => {});\n}\n\n/** One authenticated stream as a frame channel, with a bounded queue before the session installs its reader. */\nclass RelayedChannel implements FrameChannel {\n private reader: FrameChannel[\"onMessage\"] = null;\n private buffered: (string | Uint8Array)[] = [];\n private closed = false;\n private pendingBytes = 0;\n /** It carries binary messages (WISP 100 § Text and binary messages), as the Desktop's own HyperDHT does. */\n readonly binary = true;\n onClose: FrameChannel[\"onClose\"] = null;\n constructor(private readonly socket: SecretSocket) {\n socket.on(\"drain\", () => { this.pendingBytes = 0; });\n }\n get bufferedAmount(): number { return this.pendingBytes; }\n readonly sendBudget = SEND_BUDGET;\n get onMessage() { return this.reader; }\n set onMessage(reader: FrameChannel[\"onMessage\"]) {\n this.reader = reader;\n if (reader) for (const text of this.buffered.splice(0)) reader(text);\n }\n receive(text: string | Uint8Array): boolean {\n if (this.closed) return true;\n if (this.reader) this.reader(text);\n else if (this.buffered.length < 64) this.buffered.push(text);\n else return false;\n return true;\n }\n send(data: string | Uint8Array): void {\n if (this.closed || !data.length) throw new Error(\"Native channel is closed or exceeds its frame budget\");\n const binary = typeof data !== \"string\";\n const payload = binary ? data : new TextEncoder().encode(data);\n if (payload.length > MAX_FRAME || this.pendingBytes + payload.length > SEND_BUDGET) throw new Error(\"Native channel is closed or exceeds its frame budget\");\n // The stream takes every write; past its high-water mark it says so until it drains.\n if (!writeFrame(this.socket, payload, binary) || this.pendingBytes) this.pendingBytes += payload.length + 4;\n }\n drained(): Promise<void> {\n if (!this.pendingBytes) return Promise.resolve();\n return new Promise((resolve, reject) => {\n const done = () => { this.socket.off(\"close\", gone); resolve(); };\n const gone = () => { this.socket.off(\"drain\", done); reject(new Error(\"Native channel closed\")); };\n this.socket.once(\"drain\", done); this.socket.once(\"close\", gone);\n });\n }\n closedByPeer(): void {\n if (this.closed) return;\n this.closed = true; this.buffered = [];\n this.onClose?.();\n }\n close(): void {\n if (this.closed) return;\n this.socket.destroy();\n this.closedByPeer();\n }\n}\n\nfunction writeFrame(socket: SecretSocket, payload: Uint8Array, binary = false): boolean {\n const frame = new Uint8Array(4 + payload.length);\n new DataView(frame.buffer).setUint32(0, (binary ? BINARY : 0) + payload.length);\n frame.set(payload, 4);\n return socket.write(frame);\n}\n\n/**\n * Waits for the peer's preface on an authenticated stream (sending ours as soon as the handshake is\n * done), then hands the channel over with the binding the stream itself gives. A frame of the wrong size,\n * bytes that are not UTF-8 or another protocol close the stream.\n *\n * `dialledIn`: the stream was dialled in, and takes one of its MAX_CHANNELS only once its preface came. This side's own\n * dials are not counted: one always goes out.\n */\nfunction attach(socket: SecretSocket, channels: Set<RelayedChannel>, dialledIn?: DialledIn): Promise<BoundChannel> {\n if (dialledIn && dialledIn.live.size >= MAX_CHANNELS) { socket.destroy(); return Promise.reject(new Error(\"Native connection limit reached\")); }\n if (dialledIn && dialledIn.unprefaced.size >= MAX_UNPREFACED) {\n const [oldest] = dialledIn.unprefaced;\n dialledIn.unprefaced.delete(oldest); oldest.close();\n }\n const channel = new RelayedChannel(socket);\n channels.add(channel); dialledIn?.unprefaced.add(channel);\n return new Promise<BoundChannel>((resolve, reject) => {\n let buffer = new Uint8Array(0);\n let prefaced = false;\n const decoder = new TextDecoder(\"utf-8\", { fatal: true });\n const timer = setTimeout(() => socket.destroy(new Error(\"HyperDHT handshake timed out\")), HANDSHAKE_MS);\n const fail = (error: Error) => { socket.destroy(error); };\n socket.on(\"error\", (error: Error) => reject(error));\n socket.on(\"close\", () => {\n clearTimeout(timer); channels.delete(channel); dialledIn?.live.delete(channel); dialledIn?.unprefaced.delete(channel);\n reject(new Error(\"Native channel closed\"));\n channel.closedByPeer();\n });\n const opened = () => {\n if (socket.handshakeHash?.length !== 64 || socket.publicKey?.length !== 32 || socket.remotePublicKey?.length !== 32) {\n fail(new Error(\"Noise session binding unavailable\")); return;\n }\n writeFrame(socket, new TextEncoder().encode(PREFACE));\n };\n if (socket.opened) void socket.opened.then(ok => { if (ok) opened(); else reject(new Error(\"Noise handshake failed\")); });\n else socket.once(\"open\", opened);\n socket.on(\"data\", (chunk: Uint8Array) => {\n // Frames are read by offset and only the partial one left is kept (a copy, once per chunk), as on the\n // Desktop: copying the rest of the buffer per frame made a burst of tiny frames cost quadratic time.\n let joined = chunk;\n if (buffer.length) {\n joined = new Uint8Array(buffer.length + chunk.length);\n joined.set(buffer); joined.set(chunk, buffer.length);\n }\n let offset = 0;\n while (joined.length - offset >= 4) {\n const word = new DataView(joined.buffer, joined.byteOffset + offset, 4).getUint32(0);\n const binary = word >= BINARY, length = word % BINARY;\n // A binary frame before the preface is another protocol.\n if (length === 0 || length > MAX_FRAME || (binary && !prefaced)) { fail(new Error(\"Invalid frame length\")); return; }\n if (joined.length - offset < 4 + length) break;\n const payload = joined.subarray(offset + 4, offset + 4 + length);\n offset += 4 + length;\n if (binary) {\n if (!channel.receive(new Uint8Array(payload))) { fail(new Error(\"Receive queue exceeded\")); return; }\n continue;\n }\n let text: string;\n try { text = decoder.decode(payload); }\n catch { fail(new Error(\"Invalid UTF-8 frame\")); return; }\n if (!prefaced) {\n if (text !== PREFACE) { fail(new Error(\"Unexpected application protocol\")); return; }\n prefaced = true; clearTimeout(timer);\n if (dialledIn) {\n dialledIn.unprefaced.delete(channel);\n if (dialledIn.live.size >= MAX_CHANNELS) { fail(new Error(\"Native connection limit reached\")); return; }\n dialledIn.live.add(channel);\n }\n resolve({ channel, binding: { transport: \"hyperdht/1\", context: hex(socket.handshakeHash!),\n identities: [hex(socket.publicKey), hex(socket.remotePublicKey)].sort() as [string, string] } });\n } else if (!channel.receive(text)) { fail(new Error(\"Receive queue exceeded\")); return; }\n }\n buffer = new Uint8Array(joined.subarray(offset));\n });\n });\n}\n\nexport interface RelayedHyperOptions {\n /** How to open the WebSocket (tests pass Node's `ws`). Default: the browser's. */\n createSocket?: (url: string) => WebSocket;\n}\n\n/**\n * A chat's HyperDHT endpoint through the relay at `url`: it listens on the key of `seedB64` (the chat's\n * own transport seed, as on the Desktop) and dials a contact's descriptor. Fails, and so is not offered,\n * when the relay cannot be reached or does not let it listen.\n *\n * dht-relay 0.4.3 has no message for a refused listen (the relay's node refuses a key it already listens on, for\n * another client or an old connection of this one), and its client drops a `closed` for a server that has not had\n * `listening`. So the relay answers a refusal with `listening` at no address (port 0), then `closed`: that fails here\n * at once. A relay that answers nothing leaves the listen to LISTEN_MS. A server the relay closes later says the\n * endpoint is unavailable, as when the whole connection goes.\n */\nexport async function createRelayedHyperEndpoint(seedB64: string, url: string, options: RelayedHyperOptions = {}): Promise<NativeEndpoint> {\n const problem = hyperdhtRelayProblem(url);\n if (problem) throw new Error(problem);\n const keyPair = hyperKeyPair(fromBase64Url(seedB64));\n const client = await relayClient(url, options.createSocket ?? (address => new WebSocket(address)));\n const channels = new Set<RelayedChannel>();\n const dialledIn: DialledIn = { live: new Set(), unprefaced: new Set() };\n let stopped = false;\n let handler: NativeEndpoint[\"onConnection\"] = null;\n const waiting: BoundChannel[] = [];\n let endpoint: NativeEndpoint | null = null;\n // Fails the listen below when the relay connection closes while it waits.\n let relayClosed: (() => void) | null = null;\n const member = {\n unavailable() {\n if (client.gone) relayClosed?.();\n if (stopped) return;\n stopped = true;\n for (const channel of channels) channel.close();\n endpoint?.onUnavailable?.();\n },\n };\n client.endpoints.add(member);\n const server = client.node.createServer({}, socket => {\n void attach(socket, channels, dialledIn).then(bound => {\n if (stopped) bound.channel.close();\n else if (handler) handler(bound);\n else if (waiting.length < MAX_CHANNELS) waiting.push(bound);\n else bound.channel.close();\n }).catch(() => {});\n });\n let serverClosed = false;\n server.once(\"close\", () => { serverClosed = true; forgetServer(server); member.unavailable(); });\n // Neither wait outlasts the listen: one on `client.closed` stayed there, holding this endpoint, closed or refused, for as\n // long as the relay connection stayed open.\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n await Promise.race([\n server.listen(keyPair),\n new Promise((_, reject) => {\n relayClosed = () => reject(new Error(\"The HyperDHT relay closed the connection\"));\n if (client.gone) relayClosed();\n timer = setTimeout(() => reject(new Error(\"The HyperDHT relay did not let this chat listen\")), LISTEN_MS);\n }),\n ]);\n if (client.gone) throw new Error(\"The HyperDHT relay closed the connection\");\n if (serverClosed || !server.address()?.port) throw new Error(\"The HyperDHT relay did not let this chat listen\");\n } catch (error) {\n stopped = true;\n void server.close().catch(() => {});\n release(url, client, member);\n throw error;\n } finally {\n clearTimeout(timer);\n relayClosed = null;\n }\n const descriptor: RelayedHyperDescriptor = { publicKey: hex(keyPair.publicKey), relayed: true, relay: hyperdhtRelayUrl(url) };\n endpoint = {\n transport: \"hyperdht/1\", descriptor, onDescriptor: null, onUnavailable: null,\n get onConnection() { return handler; },\n set onConnection(value) { handler = value; if (value) for (const bound of waiting.splice(0)) value(bound); },\n async connect(address) {\n const publicKey = (address as { publicKey?: unknown } | null)?.publicKey;\n if (stopped || typeof publicKey !== \"string\" || !/^[a-f0-9]{64}$/.test(publicKey)) throw new Error(\"Invalid HyperDHT endpoint\");\n return attach(client.node.connect(fromHex(publicKey), { keyPair }), channels);\n },\n async close() {\n stopped = true;\n for (const channel of channels) channel.close();\n waiting.length = 0;\n await server.close().catch(() => {});\n release(url, client, member);\n },\n };\n return endpoint;\n}\n"],"mappings":";;;;;;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lTooLong, u as relayUrl } from "./pairedTransports-DAzupLYo.js";
2
2
  // ../browser/src/shared/hyperdhtRelay.ts
3
3
  /**
4
4
  * Only `wss://`, or `ws://` to this machine (a relay for tests or development). Nothing but the server's address, as
@@ -29,4 +29,4 @@ function hyperdhtRelayProblem(url) {
29
29
  var hyperdhtRelayUrl = (url) => url.replace(/^[a-z]+:/i, (scheme) => scheme.toLowerCase());
30
30
  export { hyperdhtRelayUrl as n, hyperdhtRelayProblem as t };
31
31
 
32
- //# sourceMappingURL=hyperdhtRelay-B4_wdCtx.js.map
32
+ //# sourceMappingURL=hyperdhtRelay-DDwU5b4P.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"hyperdhtRelay-B4_wdCtx.js","names":[],"sources":["../../../browser/src/shared/hyperdhtRelay.ts"],"sourcesContent":["import { relayUrl, relayUrlTooLong } from \"@ghostly/core\";\n\n/**\n * The HyperDHT relay a browser reaches the HyperDHT through (WISP 103, browser profile). Empty: none, so a\n * browser offers no HyperDHT. Nobody runs a public one for Ghostly yet; this becomes Ghostly's own relay\n * once it is deployed.\n */\nexport const DEFAULT_HYPERDHT_RELAY = \"\";\n\n/**\n * Only `wss://`, or `ws://` to this machine (a relay for tests or development). Nothing but the server's address, as\n * an Iroh relay (irohWeb.ts `irohRelayProblem`): the endpoint names this URL as its descriptor's relay, which every\n * contact is told, so a login, a password, a query or a fragment in it would go to them all.\n */\nexport function hyperdhtRelayProblem(url: string): string | null {\n let parsed: URL;\n try { parsed = new URL(url); } catch { return \"Enter a relay address (wss://…)\"; }\n if (parsed.protocol !== \"wss:\" && !(parsed.protocol === \"ws:\" && [\"127.0.0.1\", \"localhost\", \"[::1]\"].includes(parsed.hostname))) return \"Use a wss:// relay address\";\n if (parsed.username || parsed.password || /[?#]/.test(url)) return `Not a relay address: ${url}`;\n // Nor one a contact would drop with the whole descriptor (`relayUrl`: a space in it, past 126 characters, a capital in\n // `localhost`), leaving the relay unused for reaching this browser without a word. One refused for its length alone\n // is a relay address all the same: what to do is said instead.\n const named = hyperdhtRelayUrl(url);\n if (url.length > 256 || !relayUrl(named)) return relayUrlTooLong(named) ? `Use a shorter relay address: ${url}` : `Not a relay address: ${url}`;\n return null;\n}\n\n/**\n * The relay as the endpoint names it to contacts: its scheme in lower case, as `relayUrl` reads it (`WSS://relay.example`\n * pasted is wss://relay.example), the rest as typed.\n */\nexport const hyperdhtRelayUrl = (url: string): string => url.replace(/^[a-z]+:/i, scheme => scheme.toLowerCase());\n"],"mappings":";;;;;;;AAcA,SAAgB,qBAAqB,KAA4B;CAC/D,IAAI;CACJ,IAAI;EAAE,SAAS,IAAI,IAAI,GAAG;CAAG,QAAQ;EAAE,OAAO;CAAmC;CACjF,IAAI,OAAO,aAAa,UAAU,EAAE,OAAO,aAAa,SAAS;EAAC;EAAa;EAAa;CAAO,CAAC,CAAC,SAAS,OAAO,QAAQ,IAAI,OAAO;CACxI,IAAI,OAAO,YAAY,OAAO,YAAY,OAAO,KAAK,GAAG,GAAG,OAAO,wBAAwB;CAI3F,MAAM,QAAQ,iBAAiB,GAAG;CAClC,IAAI,IAAI,SAAS,OAAO,CAAC,SAAS,KAAK,GAAG,OAAO,gBAAgB,KAAK,IAAI,gCAAgC,QAAQ,wBAAwB;CAC1I,OAAO;AACT;;;;;AAMA,IAAa,oBAAoB,QAAwB,IAAI,QAAQ,cAAa,WAAU,OAAO,YAAY,CAAC"}
1
+ {"version":3,"file":"hyperdhtRelay-DDwU5b4P.js","names":[],"sources":["../../../browser/src/shared/hyperdhtRelay.ts"],"sourcesContent":["import { relayUrl, relayUrlTooLong } from \"@ghostly/core\";\n\n/**\n * The HyperDHT relay a browser reaches the HyperDHT through (WISP 103, browser profile). Empty: none, so a\n * browser offers no HyperDHT. Nobody runs a public one for Ghostly yet; this becomes Ghostly's own relay\n * once it is deployed.\n */\nexport const DEFAULT_HYPERDHT_RELAY = \"\";\n\n/**\n * Only `wss://`, or `ws://` to this machine (a relay for tests or development). Nothing but the server's address, as\n * an Iroh relay (irohWeb.ts `irohRelayProblem`): the endpoint names this URL as its descriptor's relay, which every\n * contact is told, so a login, a password, a query or a fragment in it would go to them all.\n */\nexport function hyperdhtRelayProblem(url: string): string | null {\n let parsed: URL;\n try { parsed = new URL(url); } catch { return \"Enter a relay address (wss://…)\"; }\n if (parsed.protocol !== \"wss:\" && !(parsed.protocol === \"ws:\" && [\"127.0.0.1\", \"localhost\", \"[::1]\"].includes(parsed.hostname))) return \"Use a wss:// relay address\";\n if (parsed.username || parsed.password || /[?#]/.test(url)) return `Not a relay address: ${url}`;\n // Nor one a contact would drop with the whole descriptor (`relayUrl`: a space in it, past 126 characters, a capital in\n // `localhost`), leaving the relay unused for reaching this browser without a word. One refused for its length alone\n // is a relay address all the same: what to do is said instead.\n const named = hyperdhtRelayUrl(url);\n if (url.length > 256 || !relayUrl(named)) return relayUrlTooLong(named) ? `Use a shorter relay address: ${url}` : `Not a relay address: ${url}`;\n return null;\n}\n\n/**\n * The relay as the endpoint names it to contacts: its scheme in lower case, as `relayUrl` reads it (`WSS://relay.example`\n * pasted is wss://relay.example), the rest as typed.\n */\nexport const hyperdhtRelayUrl = (url: string): string => url.replace(/^[a-z]+:/i, scheme => scheme.toLowerCase());\n"],"mappings":";;;;;;;AAcA,SAAgB,qBAAqB,KAA4B;CAC/D,IAAI;CACJ,IAAI;EAAE,SAAS,IAAI,IAAI,GAAG;CAAG,QAAQ;EAAE,OAAO;CAAmC;CACjF,IAAI,OAAO,aAAa,UAAU,EAAE,OAAO,aAAa,SAAS;EAAC;EAAa;EAAa;CAAO,CAAC,CAAC,SAAS,OAAO,QAAQ,IAAI,OAAO;CACxI,IAAI,OAAO,YAAY,OAAO,YAAY,OAAO,KAAK,GAAG,GAAG,OAAO,wBAAwB;CAI3F,MAAM,QAAQ,iBAAiB,GAAG;CAClC,IAAI,IAAI,SAAS,OAAO,CAAC,SAAS,KAAK,GAAG,OAAO,gBAAgB,KAAK,IAAI,gCAAgC,QAAQ,wBAAwB;CAC1I,OAAO;AACT;;;;;AAMA,IAAa,oBAAoB,QAAwB,IAAI,QAAQ,cAAa,WAAU,OAAO,YAAY,CAAC"}
@@ -167,6 +167,12 @@ var MAX_CHALLENGES = 8;
167
167
  /** A challenge still open at `now` (seconds): a presentation for it is still taken. */
168
168
  var liveAt = (c, now) => c.issuedAt > now - 300;
169
169
  var IDENTITY_FRAME_WINDOW_MS = 6e4;
170
+ var IDENTITY_SEND_WINDOW_MS = 7e4;
171
+ /**
172
+ * A request or withdraw the contact did not answer is sent again after this (ms), twice as long each time, at most
173
+ * `IDENTITY_RESENDS` times a connection; past that it waits for the next one, as before.
174
+ */
175
+ var IDENTITY_RESEND_MS = 6e4;
170
176
  var IDENTITY_PROVIDER_ID = /^[a-z][a-z0-9-]{0,31}$/;
171
177
  /** Printable ASCII without spaces, so the statement can be built but never needs parsing. */
172
178
  var IDENTITY_SUBJECT = /^[\x21-\x7e]{1,512}$/;
@@ -374,14 +380,30 @@ var identityRefusal = (error) => typeof error === "string" && (CONTACT_REFUSALS.
374
380
  * idp-result {id, ok, error?} verifier, after saving the outcome
375
381
  * idp-withdraw {id} / idp-withdrawn {id}
376
382
  */
377
- var IdentityExchange = class {
383
+ var IdentityExchange = class IdentityExchange {
378
384
  options;
379
385
  peerProviders;
380
386
  requested = /* @__PURE__ */ new Set();
381
387
  /** The nonces of the presentations in their provider's check now. */
382
388
  checking = /* @__PURE__ */ new Set();
389
+ /**
390
+ * The nonces of the challenges sent on this connection. A presentation is signed for its session, so a challenge
391
+ * from a closed link that is not in its check now can no longer be answered.
392
+ */
393
+ issued = /* @__PURE__ */ new Set();
383
394
  /** When the contact's presentations were checked with their provider (seconds), for `IDENTITY_MAX_CHECKS_PER_HOUR`. */
384
395
  checks = [];
396
+ /** When this side sent its recent frames (ms), for `IDENTITY_SEND_LIMIT`. Kept across connections, as the contact's count is. */
397
+ sentAt = [];
398
+ /** Hello, answers and presentations waiting for room in that window, in order (`proof`: a presentation's). */
399
+ outbox = [];
400
+ /**
401
+ * This connection's request or withdraw per proof: when it (or its presentation) last went, how often, and whether its
402
+ * presentation went. Requests and withdraws are built from the ledger when their turn comes, so one stopped or
403
+ * answered meanwhile never goes.
404
+ */
405
+ attempts = /* @__PURE__ */ new Map();
406
+ timer;
385
407
  constructor(options) {
386
408
  this.options = options;
387
409
  }
@@ -403,9 +425,111 @@ var IdentityExchange = class {
403
425
  audience: s.subject
404
426
  };
405
427
  }
406
- send(frame) {
428
+ send(frame, proof) {
407
429
  if (JSON.stringify(frame).length > 32768) throw new Error("Identity proof too large");
408
- this.options.send(frame);
430
+ if (this.outbox.length >= 40) return;
431
+ this.outbox.push({
432
+ frame,
433
+ proof
434
+ });
435
+ this.pump();
436
+ }
437
+ /** Sends one frame and counts it; false when the channel is gone (what waits is sent on the next connection). */
438
+ transmit(frame, at) {
439
+ try {
440
+ this.options.send(frame);
441
+ } catch {
442
+ this.outbox = [];
443
+ return false;
444
+ }
445
+ this.sentAt.push(at);
446
+ return true;
447
+ }
448
+ static resendAfter(tries) {
449
+ return IDENTITY_RESEND_MS * 2 ** (tries - 1);
450
+ }
451
+ /**
452
+ * Sends what fits the contact's limits now and sets a timer for the rest: the waiting answers first, then requests
453
+ * (at most `MAX_CHALLENGES` open, each keeping room in the window for its presentation) and withdraws, then the
454
+ * unanswered ones again once their time is up.
455
+ */
456
+ pump() {
457
+ if (this.timer !== void 0) clearTimeout(this.timer);
458
+ this.timer = void 0;
459
+ const paced = this.options.paced !== false;
460
+ const [limit, maxOpen] = paced ? [36, MAX_CHALLENGES] : [Infinity, Infinity];
461
+ const at = Date.now();
462
+ this.sentAt = paced ? this.sentAt.filter((t) => t > at - 7e4 && t <= at) : [];
463
+ /** When the window has room for one more frame under `n`. */
464
+ const roomAt = (n) => this.sentAt[this.sentAt.length - n] + IDENTITY_SEND_WINDOW_MS;
465
+ let wake = Infinity;
466
+ while (this.outbox.length && this.sentAt.length < limit) {
467
+ const { frame, proof } = this.outbox.shift();
468
+ if (!this.transmit(frame, at)) return;
469
+ const a = proof ? this.attempts.get(proof) : void 0;
470
+ if (a) {
471
+ a.at = at;
472
+ a.presented = true;
473
+ }
474
+ }
475
+ if (this.outbox.length) wake = roomAt(limit);
476
+ const shared = this.options.storage.read().shared;
477
+ const kindOf = (s) => s.status === "queued" || s.status === "pending" ? "request" : s.status === "withdrawal-pending" ? "withdraw" : void 0;
478
+ for (const [id, a] of this.attempts) {
479
+ const s = shared.find((x) => x.id === id);
480
+ if (!s || kindOf(s) !== a.kind) this.attempts.delete(id);
481
+ }
482
+ const dueAt = (a) => !paced || a.tries > 4 ? Infinity : a.at + IdentityExchange.resendAfter(a.tries);
483
+ const opened = [...this.attempts.values()].filter((a) => a.kind === "request" && a.tries <= 4 && dueAt(a) > at);
484
+ let open = opened.length;
485
+ /** Presentations still to come for the open requests: room kept for them. */
486
+ let owed = opened.filter((a) => !a.presented).length;
487
+ for (const s of shared) {
488
+ const kind = kindOf(s);
489
+ if (!kind) continue;
490
+ const a = this.attempts.get(s.id);
491
+ if (a && dueAt(a) > at) {
492
+ wake = Math.min(wake, dueAt(a));
493
+ continue;
494
+ }
495
+ if (a && (!paced || a.tries > 4)) continue;
496
+ if (kind === "request" && open >= maxOpen) continue;
497
+ const need = kind === "request" ? 2 : 1;
498
+ if (this.sentAt.length + owed + need > limit) {
499
+ wake = Math.min(wake, roomAt(limit - owed - need + 1));
500
+ break;
501
+ }
502
+ const frame = kind === "request" ? {
503
+ t: "idp-request",
504
+ id: s.id,
505
+ provider: s.provider
506
+ } : {
507
+ t: "idp-withdraw",
508
+ id: s.id
509
+ };
510
+ if (!this.transmit(frame, at)) return;
511
+ if (kind === "request") {
512
+ this.requested.add(s.id);
513
+ open++;
514
+ owed++;
515
+ }
516
+ const tries = (a?.tries ?? 0) + 1;
517
+ this.attempts.set(s.id, {
518
+ kind,
519
+ at,
520
+ tries
521
+ });
522
+ wake = Math.min(wake, dueAt({
523
+ at,
524
+ tries
525
+ }));
526
+ }
527
+ if (!paced) this.sentAt = [];
528
+ if (wake === Infinity) return;
529
+ const timer = this.timer = setTimeout(() => {
530
+ if (this.timer === timer) this.pump();
531
+ }, Math.max(0, wake - at) + 1);
532
+ timer.unref?.();
409
533
  }
410
534
  shared(id) {
411
535
  return this.options.storage.read().shared.find((s) => s.id === id);
@@ -423,22 +547,23 @@ var IdentityExchange = class {
423
547
  get contactProviders() {
424
548
  return this.peerProviders;
425
549
  }
426
- /** The channel is ready: say what we verify, then send what the person queued while offline. */
550
+ /** The channel is ready: say what we verify, then send what the person queued while offline, paced (`pump`). */
427
551
  ready() {
428
552
  this.options.scope();
553
+ this.attempts.clear();
429
554
  this.send({
430
555
  t: "idp-hello",
431
556
  providers: [...this.options.providers()]
432
557
  });
433
- for (const s of this.options.storage.read().shared) if (s.status === "queued" || s.status === "pending") this.request(s);
434
- else if (s.status === "withdrawal-pending") this.send({
435
- t: "idp-withdraw",
436
- id: s.id
437
- });
438
558
  }
439
559
  stop() {
440
560
  this.requested.clear();
441
561
  this.peerProviders = void 0;
562
+ this.issued.clear();
563
+ this.outbox = [];
564
+ this.attempts.clear();
565
+ if (this.timer !== void 0) clearTimeout(this.timer);
566
+ this.timer = void 0;
442
567
  }
443
568
  /**
444
569
  * The challenges whose window ended unanswered go, and with them their requests' lines still verifying: a contact
@@ -482,15 +607,8 @@ var IdentityExchange = class {
482
607
  provider,
483
608
  subject
484
609
  });
485
- if (connected) this.request(entry);
486
- }
487
- request(s) {
488
- this.requested.add(s.id);
489
- this.send({
490
- t: "idp-request",
491
- id: s.id,
492
- provider: s.provider
493
- });
610
+ this.attempts.delete(id);
611
+ if (connected) this.pump();
494
612
  }
495
613
  /** Stop sharing here. The contact is told (now or on reconnect); a copy it kept cannot be erased. */
496
614
  async withdraw(id, connected) {
@@ -526,12 +644,7 @@ var IdentityExchange = class {
526
644
  subject: s.subject,
527
645
  reason: "withdrawn"
528
646
  });
529
- if (connected) try {
530
- this.send({
531
- t: "idp-withdraw",
532
- id
533
- });
534
- } catch {}
647
+ if (connected) this.pump();
535
648
  }
536
649
  /**
537
650
  * Run the checks again on a received proof: its revocation record, then (unless `revocationOnly`) the
@@ -621,7 +734,12 @@ var IdentityExchange = class {
621
734
  }
622
735
  case "idp-result": {
623
736
  const s = id ? this.shared(id) : void 0;
624
- if (!s || s.status !== "pending") return;
737
+ const asked = id ? this.attempts.get(id) : void 0;
738
+ if (asked?.kind === "request" && s?.status === "queued") asked.tries = 5;
739
+ if (!s || s.status !== "pending") {
740
+ this.pump();
741
+ return;
742
+ }
625
743
  const ok = frame.ok === true;
626
744
  const error = ok ? void 0 : typeof frame.error === "string" && CONTACT_REFUSALS.has(frame.error) ? frame.error : CONTACT_REFUSED;
627
745
  const entry = {
@@ -652,6 +770,7 @@ var IdentityExchange = class {
652
770
  ok,
653
771
  error
654
772
  })));
773
+ this.pump();
655
774
  return;
656
775
  }
657
776
  case "idp-withdraw": {
@@ -719,6 +838,11 @@ var IdentityExchange = class {
719
838
  id
720
839
  };
721
840
  await this.options.storage.update((l) => {
841
+ const stale = (c) => c.id === id && !this.issued.has(c.nonce) && !this.checking.has(c.nonce);
842
+ if (l.challenges.some(stale)) l = {
843
+ ...l,
844
+ challenges: l.challenges.filter((c) => !stale(c))
845
+ };
722
846
  if (l.challenges.filter((c) => liveAt(c, now)).length >= MAX_CHALLENGES) throw new Error("Too many identity challenges");
723
847
  return this.withoutExpired(this.log({
724
848
  ...l,
@@ -730,6 +854,9 @@ var IdentityExchange = class {
730
854
  provider
731
855
  }), now);
732
856
  });
857
+ const held = new Set(this.options.storage.read().challenges.map((c) => c.nonce));
858
+ for (const n of this.issued) if (!held.has(n)) this.issued.delete(n);
859
+ this.issued.add(challenge.nonce);
733
860
  this.send({
734
861
  t: "idp-challenge",
735
862
  id,
@@ -786,7 +913,7 @@ var IdentityExchange = class {
786
913
  binding: local.statement.binding,
787
914
  evidence: local.evidence,
788
915
  sig
789
- });
916
+ }, id);
790
917
  }
791
918
  async onPresent(frame) {
792
919
  const { nonce, issuedAt, binding, evidence, sig } = frame;
@@ -937,4 +1064,4 @@ var IdentityExchange = class {
937
1064
  };
938
1065
  export { receivedIdentityStatus as _, IDENTITY_PROOF_CAPABILITY as a, IdentityExchange as c, emptyIdentityLedger as d, identityRefusal as f, newIdentityBinding as g, isIdentityBinding as h, IDENTITY_MAX_VALIDITY as i, boundIdentityDisplay as l, identityStatement as m, IDENTITY_MAX_EVIDENCE as n, IDENTITY_REVOCATION_LABEL as o, identityRevocationValue as p, IDENTITY_MAX_FRAME as r, IdentityCheckUnavailable as s, IDENTITY_FRAME_WINDOW_MS as t, boundVerifiedIdentity as u, revokesIdentity as v, lastSharedWithMe as y };
939
1066
 
940
- //# sourceMappingURL=identityProofs-Cksc_K7_.js.map
1067
+ //# sourceMappingURL=identityProofs-zI_Iy9uI.js.map