@ghostlytools/cli 1.9.0 → 1.10.0

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 (107) hide show
  1. package/README.md +28 -20
  2. package/SKILL.md +5 -1
  3. package/dist/assets/{api-DFCgr6RH.js → api-BF_KwecF.js} +84 -38
  4. package/dist/assets/api-BF_KwecF.js.map +1 -0
  5. package/dist/assets/{api-raWw9j_m.js → api-DdrA86Ur.js} +2 -2
  6. package/dist/assets/{apiKit-CCavJJcl.js → apiKit-Du1u2l4x.js} +8 -8
  7. package/dist/assets/apiKit-Du1u2l4x.js.map +1 -0
  8. package/dist/assets/{apps-B7o2BPj6.js → apps-Bti9fDoW.js} +1 -1
  9. package/dist/assets/{apps-DmxEG147.js → apps-DwPfp54I.js} +5 -3
  10. package/dist/assets/apps-DwPfp54I.js.map +1 -0
  11. package/dist/assets/{arkade-DtYR9H0c.js → arkade-DOWpA2Kr.js} +2 -2
  12. package/dist/assets/{arkade-DtYR9H0c.js.map → arkade-DOWpA2Kr.js.map} +1 -1
  13. package/dist/assets/{backup-BserdrNk.js → backup-CeRckyl2.js} +1 -1
  14. package/dist/assets/{backup-YIB2XIES.js → backup-DZ_Q1eSu.js} +6 -6
  15. package/dist/assets/{backup-YIB2XIES.js.map → backup-DZ_Q1eSu.js.map} +1 -1
  16. package/dist/assets/bitcoindevkit_bg-B-iLWrmX.js.map +1 -1
  17. package/dist/assets/{blobFiles-DOQDRdDI.js → blobFiles-BnjN_Vrz.js} +3 -3
  18. package/dist/assets/{blobFiles-DOQDRdDI.js.map → blobFiles-BnjN_Vrz.js.map} +1 -1
  19. package/dist/assets/buttons-BxIThdg9.js +332 -0
  20. package/dist/assets/buttons-BxIThdg9.js.map +1 -0
  21. package/dist/assets/buttons-D9QBHS9Y.js +2 -0
  22. package/dist/assets/client-D5E1RQYB.js +473 -0
  23. package/dist/assets/client-D5E1RQYB.js.map +1 -0
  24. package/dist/assets/{endpoint-BdaeBw2L.js → endpoint-DWHkXWVM.js} +101 -16
  25. package/dist/assets/endpoint-DWHkXWVM.js.map +1 -0
  26. package/dist/assets/{envelope-Dt75vrmY.js → envelope-CugS9qwQ.js} +2 -2
  27. package/dist/assets/{envelope-Dt75vrmY.js.map → envelope-CugS9qwQ.js.map} +1 -1
  28. package/dist/assets/fedimint_client_wasm_bg-BtHHlFpp.js.map +1 -1
  29. package/dist/assets/{fileBytes-BPDKufla.js → fileBytes-DMzrIdCu.js} +1 -1
  30. package/dist/assets/{fileBytes-DNgrRL0R.js → fileBytes-DjBYYyXT.js} +3 -3
  31. package/dist/assets/{fileBytes-DNgrRL0R.js.map → fileBytes-DjBYYyXT.js.map} +1 -1
  32. package/dist/assets/{fileBytes-Q3ehcEr8.js → fileBytes-Douk1yOp.js} +2 -2
  33. package/dist/assets/{fileBytes-Q3ehcEr8.js.map → fileBytes-Douk1yOp.js.map} +1 -1
  34. package/dist/assets/fileBytesIdb-CD5Uv490.js +2 -0
  35. package/dist/assets/{fileBytesIdb-Dm1EyEbT.js → fileBytesIdb-CkClu9YI.js} +3 -3
  36. package/dist/assets/{fileBytesIdb-Dm1EyEbT.js.map → fileBytesIdb-CkClu9YI.js.map} +1 -1
  37. package/dist/assets/{fileBytesOpfs-ZGD21c4Q.js → fileBytesOpfs-WryQuOgK.js} +3 -3
  38. package/dist/assets/{fileBytesOpfs-ZGD21c4Q.js.map → fileBytesOpfs-WryQuOgK.js.map} +1 -1
  39. package/dist/assets/{fixedHosts-B598JzbC.js → fixedHosts-B4E4VrYE.js} +4 -4
  40. package/dist/assets/{fixedHosts-B598JzbC.js.map → fixedHosts-B4E4VrYE.js.map} +1 -1
  41. package/dist/assets/{groupFiles-FXel6zIc.js → groupFiles-NonOYBKN.js} +378 -59
  42. package/dist/assets/groupFiles-NonOYBKN.js.map +1 -0
  43. package/dist/assets/{host-DIBeK_c_.js → host-DvcVt5YI.js} +79 -23
  44. package/dist/assets/{host-DIBeK_c_.js.map → host-DvcVt5YI.js.map} +1 -1
  45. package/dist/assets/{hyperdhtRelay-D185dETu.js → hyperdhtRelay-Ce42sR8x.js} +2 -2
  46. package/dist/assets/{hyperdhtRelay-D185dETu.js.map → hyperdhtRelay-Ce42sR8x.js.map} +1 -1
  47. package/dist/assets/{idb-BkOJES5_.js → idb-BHsAqENE.js} +37 -6
  48. package/dist/assets/idb-BHsAqENE.js.map +1 -0
  49. package/dist/assets/{irohWeb-BSv_BWyG.js → irohWeb-C9ChbD-c.js} +57 -3
  50. package/dist/assets/{irohWeb-BSv_BWyG.js.map → irohWeb-C9ChbD-c.js.map} +1 -1
  51. package/dist/assets/{main-BbhfMTt8.js → main-4qE381KM.js} +194 -276
  52. package/dist/assets/main-4qE381KM.js.map +1 -0
  53. package/dist/assets/{mainline-9Vc3c3SA.js → mainline-DOwZDHVy.js} +2 -2
  54. package/dist/assets/{mainline-9Vc3c3SA.js.map → mainline-DOwZDHVy.js.map} +1 -1
  55. package/dist/assets/{networkReason-BncJ9KSM.js → networkReason-MInk1Y63.js} +3 -3
  56. package/dist/assets/{networkReason-BncJ9KSM.js.map → networkReason-MInk1Y63.js.map} +1 -1
  57. package/dist/assets/{nwc-QX3Yt1Sb.js → nwc-CHLWFV1R.js} +3 -3
  58. package/dist/assets/{nwc-QX3Yt1Sb.js.map → nwc-CHLWFV1R.js.map} +1 -1
  59. package/dist/assets/{nwcProvider-CzX3xH47.js → nwcProvider-BlkPOJen.js} +2 -2
  60. package/dist/assets/{nwcProvider-CzX3xH47.js.map → nwcProvider-BlkPOJen.js.map} +1 -1
  61. package/dist/assets/{ownDid-D8z5gwGI.js → ownDid-yXtY_1B5.js} +3 -3
  62. package/dist/assets/ownDid-yXtY_1B5.js.map +1 -0
  63. package/dist/assets/{profiles-MFtCmJwK.js → profiles-vbXHs0Mq.js} +40 -3
  64. package/dist/assets/profiles-vbXHs0Mq.js.map +1 -0
  65. package/dist/assets/{registry-PTtBMaYZ.js → registry-BN9r2pR4.js} +1 -1
  66. package/dist/assets/{registry-B2Dtnibo.js → registry-chCD0KWS.js} +5 -5
  67. package/dist/assets/registry-chCD0KWS.js.map +1 -0
  68. package/dist/assets/{resolve-ZxVzwFNA.js → resolve-Dtzogt2W.js} +2 -2
  69. package/dist/assets/{resolve-ZxVzwFNA.js.map → resolve-Dtzogt2W.js.map} +1 -1
  70. package/dist/assets/{restoredRows-BCRCjhdF.js → restoredRows-CRYwIx3g.js} +2 -2
  71. package/dist/assets/{restoredRows-BCRCjhdF.js.map → restoredRows-CRYwIx3g.js.map} +1 -1
  72. package/dist/assets/{buttons-CuRfKnPI.js → secretGuard-CSVNxXVW.js} +80 -330
  73. package/dist/assets/secretGuard-CSVNxXVW.js.map +1 -0
  74. package/dist/assets/secretGuard-Q2BKq0q0.js +2 -0
  75. package/dist/assets/{server-Dw1o8z1o.js → server-BZnsm5X5.js} +1749 -335
  76. package/dist/assets/server-BZnsm5X5.js.map +1 -0
  77. package/dist/assets/{src-BD8RBVEp.js → src-DZagapGt.js} +1043 -197
  78. package/dist/assets/src-DZagapGt.js.map +1 -0
  79. package/dist/assets/{sshForges-DWrESWkK.js → sshForges-BkTgy5rx.js} +16 -9
  80. package/dist/assets/{sshForges-DWrESWkK.js.map → sshForges-BkTgy5rx.js.map} +1 -1
  81. package/dist/assets/{translate-D1uP0q32.js → translate-B9SMd6uf.js} +8 -7
  82. package/dist/assets/translate-B9SMd6uf.js.map +1 -0
  83. package/dist/assets/{usdt-DhVN8geQ.js → usdt-BU4ezonh.js} +3 -3
  84. package/dist/assets/{usdt-DhVN8geQ.js.map → usdt-BU4ezonh.js.map} +1 -1
  85. package/dist/assets/{words-DdXPkB3n.js → words-jYy7lTcb.js} +4 -2
  86. package/dist/assets/words-jYy7lTcb.js.map +1 -0
  87. package/dist/ghostly.mjs +1 -1
  88. package/package.json +1 -1
  89. package/dist/assets/api-DFCgr6RH.js.map +0 -1
  90. package/dist/assets/apiKit-CCavJJcl.js.map +0 -1
  91. package/dist/assets/apps-DmxEG147.js.map +0 -1
  92. package/dist/assets/buttons-CuRfKnPI.js.map +0 -1
  93. package/dist/assets/buttons-De3LPdSG.js +0 -2
  94. package/dist/assets/daemonProof-DtrL5lE5.js +0 -236
  95. package/dist/assets/daemonProof-DtrL5lE5.js.map +0 -1
  96. package/dist/assets/endpoint-BdaeBw2L.js.map +0 -1
  97. package/dist/assets/fileBytesIdb-DZcESfTt.js +0 -2
  98. package/dist/assets/groupFiles-FXel6zIc.js.map +0 -1
  99. package/dist/assets/idb-BkOJES5_.js.map +0 -1
  100. package/dist/assets/main-BbhfMTt8.js.map +0 -1
  101. package/dist/assets/ownDid-D8z5gwGI.js.map +0 -1
  102. package/dist/assets/profiles-MFtCmJwK.js.map +0 -1
  103. package/dist/assets/registry-B2Dtnibo.js.map +0 -1
  104. package/dist/assets/server-Dw1o8z1o.js.map +0 -1
  105. package/dist/assets/src-BD8RBVEp.js.map +0 -1
  106. package/dist/assets/translate-D1uP0q32.js.map +0 -1
  107. package/dist/assets/words-DdXPkB3n.js.map +0 -1
@@ -1,17 +1,17 @@
1
1
  import { n as traceJoin } from "./joinTrace-CjRDFy85.js";
2
- import { $a as replySnippet, $l as readTurnPacket, $r as readPin, $s as sealHandoffPiece, $t as SEPOLIA_TEST_USDT, A as knockIdentity, Aa as EDIT_RATE_WINDOW_MS, Ac as REQUEST_LIFETIME_MS, Al as inviteLink, An as fedimintRequestPayload, Ao as rosterAdmin, Ar as pickHubs, As as handoffCancelFrame, Au as verify, Ba as COMMUNITY_REACTION_FRAME, Bc as readLinkRecord, Bl as devicePingFrame, Bn as stripPictureMetadata, Bo as DHT_POLL_INTERVALS, Br as transferEnded, Bs as handoffReleaseFrame, Bu as utf8Decode, C as communityHasFrame, Cc as inboxRecord, Ci as HoldRefusedError, Cl as createDeviceInvite, Co as shownTime, Cr as doorHubs, Cs as HANDOFF_VERIFIED, D as decodeGroupEntryLink, Dc as takeRequest, Dl as createChatInvite, Dn as decodeBolt11, Do as MEMBER_KEY, Dr as mergeBeacon, Ds as handoffAttemptFailed, Du as identityFromSeed, Ec as settleRequest, Ei as readManifest, El as OwnInviteError, Er as lobbyRecords, Es as handoffAttemptAllowed, Eu as createIdentity, F as GroupWakeLimiter, Fc as linkRecords, Fl as HANDOFF_CAPABILITY, Fo as RatchetBox, Fr as shouldBeHub, Fs as handoffEphemeral, Fu as fromBase64Url, Ga as queueReaction, Gc as APP_ICON_PATH, Gl as TURN_RAISE_READ_TIMEOUT_MS, Gn as PAIRED_FRAME_TOO_LARGE, Go as presenceSeenAt, Gs as readHandoffAck, Gt as encodeDidDhtDeactivated, H as GroupSession, Ha as REACTION_LIMITS, Hc as seenEntry, Hi as DHT_TEXT_CAPABILITY, Hl as seedSigner, Hn as GhostLink, Ho as PRESENCE_WINDOW, Hs as handoffStreamKey, I as groupWakeFrame, Ic as makeStampPaced, Il as deviceEchoFrame, Io as emptyRatchetState, Ir as ChatFiles, Is as handoffHelloFrame, J as parseCommunityEdit, Ja as readReaction, Jc as appViewOf, Jl as turnPutSummary, Jn as EngineError, Jo as parseLocalTarget, Jr as PIN_LIMITS, Js as readHandoffHave, Jt as signDidDhtPacket, K as GROUP_EDIT_TEXT_BYTES, Ka as reactionEmoji, Kl as TURN_SETTLE_MS, Kn as pairedMessageFits, Ko as GhostlyHttpError, Kr as typingActivity, Ks as readHandoffCancel, Kt as encodeDidDhtPacket, L as groupWakes, La as parseLinkPreview, Lc as mergeContactKnocks, Ll as deviceEchoNonce, Ln as NO_PICTURE_METADATA, Lo as ratchetSessionOf, Lr as FILE_LIMITS, Ls as handoffManifestFrames, Lu as randomBytes, M as mergeKnocks, Ma as REMOVED_TEXT, Mc as knockSlotIdentity, Mn as isFederationId, Mo as verifyCommitSignature, Mr as readBeacon, Ms as handoffContextProof, Mu as sanitizeAvatar, N as readKnocks, Na as RateWindow, Nc as knockSlotOf, Nl as DEVICES_CAPABILITY, Nn as parseCashuRequestPayload, No as edgeParams, Nr as readBeaconHead, Ns as handoffDataFrame, Nu as sanitizeDisplayText, O as encodeGroupEntryLink, Oa as parseVideoMeta, Oc as turnOff, Ol as decodeInviteCode, On as ENDPOINT, Oo as commitHash, Or as mergeLobby, Os as handoffAttemptSucceeded, Ou as identityFromSeedB64, Pa as dhtEditId, Pc as knockSlotRecords, Pl as ENROLL_CAPABILITY, Pn as parseFedimintRequestPayload, Po as RATCHET_CAPABILITY, Pr as readLobby, Ps as handoffDigest, Pu as bytesEqual, Qa as readReply, Qc as pacer, Ql as nextTurnPosition, Qn as GROUP_FILE_LIMITS, Qo as encodeControl, Qr as pinNumberHolds, Qs as readHandoffVerified, Qt as PaymentPreflightError, R as parseGroupWakeFrame, Ra as forwardedAgain, Rc as openRequest, Rl as deviceKeyZ32, Rn as PICTURE_METADATA_LIMITS, Ro as DirectPathWatch, Rs as handoffOfferFrame, Ru as toBase64Url, S as GROUP_READ_NOTE_COMMUNITY, Sc as endedRequests, Si as HoldKeys, Sl as readContactLink, So as receivedTimestamp, Sr as beaconRecords, Ss as HANDOFF_TIMINGS, Su as createRelayPayload, T as encodeCommunityLink, Ta as parseVoiceMeta, Tc as planKnocks, Ti as newMailbox, Tl as readDeviceInvite, To as GROUP_MEMBER_CAP, Tr as lobbyKeys, Ts as filePartName, U as frameBytes, Ua as ReactionWindow, Uc as APP_BUNDLE_LIMITS, Ui as capsDescriptors, Ul as webCryptoSigner, Un as INVITE_TAKEN, Uo as RELAY_POLL_INTERVALS, Us as handoffVersions, Ut as didDhtDocument, V as GROUP_READ_NOTE, Va as GROUP_REACTION_FRAME, Vc as requestRecords, Vi as CapsExchange, Vl as newDeviceSetSecret, Vr as transferStalled, Vs as handoffRetryAfter, Vu as utf8Encode, Wa as nextReactionNumber, Wc as APP_BUNDLE_MAGIC, Wi as dialDescriptors, Wn as LIVENESS_PING_MS, Wo as WATCH_PEER_MS, Wr as TypingSender, Ws as newHandoffId, Wt as didDhtFromPublicKey, X as groupName, Xa as wireReaction, Xl as TURN_MAX, Xn as engineText, Xo as LIMITS, Xr as nextPinNumber, Xs as readHandoffPake, Xt as EVM_TEST_CHAINS, Y as mentionsMember, Ya as validReactionNumber, Yl as TURN_LAST_SEQUENCE, Yn as engineError, Yo as webLocalFetch, Yr as mayPin, Ys as readHandoffHello, Yt as ETHEREUM_USDT, Za as pairedReplyAuthor, Zc as isAppUrl, Zi as emptyIdentityLedger, Zl as firstDeviceSetSecret, Zn as parseEngineError, Zo as decodeControl, Zr as pinIsNewer, Zs as readHandoffTurnFrame, Zt as ONCHAIN_PROVIDER, _ as groupTypingEpoch, _a as sanitizeFileName, _c as enrollProofFrame, _i as STATUS_CARD_CAPABILITY, _l as canonicalJson, _r as mayBeHub, _s as HANDOFF_HELLO, _t as normalizeAtprotoHandle, _u as budgetRetryMs, a as appRevocationFor, aa as emptyProofLedger, ac as signTombstone, ai as relayRequest, al as appRef, an as assertTokenUnits, ar as readGroupFileMeta, as as contactRtcConfig, au as turnStatedVerifier, b as COMMUNITY_LIMITS, bc as verifyEnrollProof, bi as HOLD_DATED_BACK_MS, bl as createContactLink, bo as claimedTime, br as COMMUNITY_TOPOLOGY, bs as HANDOFF_PIECE_BYTES, bu as PacketTooLargeError, c as checkAppBeforeRun, ca as automaticTransport, ci as vapidKeysMatch, cl as isAppKey, cn as validatePaymentTarget, co as STATUS_CARD_LIMITS, dc as enrollCancelFrame, dn as SPARK_PROVIDER, ds as LEGACY_SERVICES, ei as WAKE_CALL_INTERVAL_MS, el as readAppBundleAsync, eo as BUTTON_ID, es as RTC_CONFIG, eu as signTurnPacket, fa as DHT_MESSAGE_TTL, fc as enrollCancelReason, fi as chatAppId, fn as sparkAddressKind, fs as serviceIdFromName, g as GroupTypingBoard, ga as formatFileSize, gc as enrollHelloFrame, gi as EDIT_CAPABILITY, gn as isPubkyKey, go as sameButtonText, gr as MESH_HUBS, gs as HANDOFF_HAVE, gt as isAtprotoDid, gu as traceLink, ha as dhtFileId, hc as enrollGrantFrame, hi as BUTTONS_CAPABILITY, hl as parseImageMeta, ho as checkStatusCard, hr as readGroupSignal, hs as HANDOFF_DONE, i as addedAppPermissions, ia as PeerProofs, ic as setUpdateFrame, ii as parseWakeFrame, il as appFingerprint, in as arkAddressPrefix, iu as turnName, j as knockRecords, ja as MAX_REMOVAL_NUMBER, jc as contactDay, jl as inviteOwnership, jn as findEndpoint, jo as rosterHas, jr as rankHubs, js as handoffContext, k as entryParams, ka as EDIT_BUFFER_MS, kc as ContactRequestError, kl as encodeInviteCode, kn as cashuRequestPayload, ko as parseGroupCommit, kr as newerHead, ks as handoffBusyFrame, ku as publicKeyFromZ32, l as planAppUpdate, li as APP_RANGE_LIMITS, ll as isAppRef, ln as walletNetworkOf, lr as CarriedTransport, ls as emptyLinkRecords, ma as DHT_FILE_CAPABILITY, mc as enrollDoneFrame, mi as APPS_CAPABILITY, mn as isBitcoinAddress, mr as groupSignalFrame, ms as HANDOFF_CANCEL, mu as normalizeRelayUrl, n as readX401SdJwtVc, nc as readSetUpdate, ni as deviceWakeRequest, nn as USDT_PUBLIC_RPC, nu as turnInstance, o as appStoreDecision, oa as validExternalKey, oc as verifySetUpdate, oi as wakeRequest, on as assertWholeSats, ou as turnVerifierMark, p as readAppStoreSteps, pa as peekDhtMailbox, pc as enrollDigits, pi as isAppVersion, pn as sparkInvoiceDetails, ps as HANDOFF_ACK, pu as currentRelays, q as carryMentions, qa as reactionIsNewer, qc as appDigest, ql as classifyTurnRead, qn as pairedMessageFrame, qo as formatLocalTarget, qs as readHandoffDone, r as sameX401HolderJwk, ra as lastSharedWithMe, rc as setAckFrame, ri as newWakeToken, rl as APP_STATEMENT_LIMITS, rn as WALLET_NETWORKS, rr as groupFileFallback, ru as turnKeys, s as appUpdateDecision, sa as TRANSPORTS, si as checkPushEndpoint, sl as isAppHash, sn as formatPaymentAmount, ss as parseCallSignal, su as DEFAULT_RELAYS, t as newX401HolderKey, ta as receivedIdentityStatus, ti as WakeLimiter, tl as sha256Paced, tn as TEST_USDT_FAUCET_AMOUNT, tu as signTurnRelease, u as APP_STORE_LIMITS, ui as isServeId, ul as readAppRevocation, un as SPARK_NETWORKS, us as HTTP_SERVICE_PROTO, uu as RelayTransport, v as openGroupTyping, va as sanitizeMime, vc as readEnrollGrant, vi as UPGRADE_CAPABILITY, vo as statusCardText, vr as meshHubs, vs as HANDOFF_OFFER, vu as isDiscoveryBudgetError, w as decodeCommunityLink, wa as fileMessageText, wc as newInbox, wi as isHoldUrl, wl as deviceInviteJoinerParams, wo as GROUP_ADMIN_OFF_ERROR, wr as freshHubs, ws as NO_ATTEMPTS, x as CommunitySession, xc as clearMissed, xi as HOLD_LIMITS, xl as encodeContactLink, xo as heardTime, xr as beaconKeys, xs as HANDOFF_REQUEST, y as sealGroupTyping, yc as readEnrollHello, yi as HOLD_CAPABILITY, yl as readCanonicalJson, yo as arrivalKey, yr as pickMeshHubs, ys as HANDOFF_PAKE, yu as withRequestOptions, z as GROUP_LIMITS, za as readForwarded, zc as readKnockSlot, zl as deviceLinkPairing, zn as isStrippedPicture, zr as sentWhole, zs as handoffPakeFrame, zu as toZ32 } from "./src-BD8RBVEp.js";
2
+ import { $a as wireReaction, $c as appViewOf, $i as emptyIdentityLedger, $l as TURN_SETTLE_MS, $n as parseEngineError, $o as LIMITS, $r as pinIsNewer, $s as readHandoffPake, $t as PaymentPreflightError, A as knockIdentity, Ac as takeRequest, Al as createDeviceInvite, An as cashuRequestPayload, Ao as MEMBER_KEY, Ar as mergeLobby, As as handoffAttemptFailed, Ba as parseLinkPreview, Bc as linkRecords, Bl as DEVICES_CAPABILITY, Bn as PICTURE_METADATA_LIMITS, Bo as ratchetSessionOf, Bs as handoffManifestFrames, Bu as sanitizeDisplayText, C as communityHasFrame, Cc as verifyEnrollProof, Ci as HOLD_LIMITS, Co as claimedTime, Cr as beaconKeys, Cs as HANDOFF_PIECE_BYTES, Cu as traceLink, D as decodeGroupEntryLink, Da as fileMessageText, Dc as newInbox, Di as newMailbox, Dl as createContactLink, Do as GROUP_ADMIN_OFF_ERROR, Dr as lobbyKeys, Ds as NO_ATTEMPTS, Du as PacketTooLargeError, Ec as inboxRecord, Ei as isHoldUrl, El as readCanonicalJson, Eo as shownTime, Er as freshHubs, Es as HANDOFF_VERIFIED, Eu as withRequestOptions, F as GroupWakeLimiter, Fa as REMOVED_TEXT, Fc as contactAskerHolds, Fl as decodeInviteCode, Fn as parseFedimintRequestPayload, Fo as verifyCommitSignature, Fr as readBeaconHead, Fs as handoffContextProof, Fu as identityFromSeedB64, Ga as REACTION_LIMITS, Gc as readLinkRecord, Gi as capsDescriptors, Gl as deviceKeyZ32, Gn as INVITE_TAKEN, Go as PRESENCE_WINDOW, Gs as handoffStreamKey, Gt as didDhtFromPublicKey, Gu as toBase64Url, H as GroupSession, Ha as readForwarded, Hc as mergeContactKnocks, Hl as HANDOFF_CAPABILITY, Hn as stripPictureMetadata, Hr as transferEnded, Hs as handoffPakeFrame, Hu as fromBase64Url, I as groupWakeFrame, Ia as RateWindow, Ic as contactDay, Il as encodeInviteCode, Io as edgeParams, Ir as readLobby, Is as handoffDataFrame, Iu as publicKeyFromZ32, Ja as queueReaction, Jc as APP_BUNDLE_LIMITS, Jl as newDeviceSetSecret, Jn as pairedMessageFits, Jo as presenceSeenAt, Jr as typingActivity, Js as readHandoffAck, Ju as utf8Encode, K as GROUP_EDIT_TEXT_BYTES, Ka as ReactionWindow, Kc as requestRecords, Ki as dialDescriptors, Kl as deviceLinkPairing, Kn as LIVENESS_PING_MS, Ko as RELAY_POLL_INTERVALS, Kr as TypingSender, Ks as handoffVersions, Kt as encodeDidDhtDeactivated, Ku as toZ32, L as groupWakes, La as dhtEditId, Lc as knockSlotIdentity, Ll as inviteLink, Ln as videoMetadataPatches, Lo as RATCHET_CAPABILITY, Lr as shouldBeHub, Ls as handoffDigest, Lu as verify, M as mergeKnocks, Ma as EDIT_BUFFER_MS, Mc as ContactRequestError, Ml as readDeviceInvite, Mn as findEndpoint, Mo as parseGroupCommit, Mr as pickHubs, Ms as handoffBusyFrame, N as readKnocks, Na as EDIT_RATE_WINDOW_MS, Nc as REQUEST_LIFETIME_MS, Nl as OwnInviteError, Nn as isFederationId, No as rosterAdmin, Nr as rankHubs, Ns as handoffCancelFrame, Nu as createIdentity, O as encodeGroupEntryLink, Oa as parseVoiceMeta, Oc as planKnocks, Oi as readManifest, Ol as encodeContactLink, On as decodeBolt11, Oo as GROUP_MEMBER_CAP, Or as lobbyRecords, Os as filePartName, Pa as MAX_REMOVAL_NUMBER, Pc as contactAskerFrame, Pl as createChatInvite, Pn as parseCashuRequestPayload, Po as rosterHas, Pr as readBeacon, Ps as handoffContext, Pu as identityFromSeed, Qa as validReactionNumber, Qc as appDigest, Ql as TURN_RAISE_READ_TIMEOUT_MS, Qn as engineText, Qo as webLocalFetch, Qr as nextPinNumber, Qs as readHandoffHello, Qt as ONCHAIN_PROVIDER, R as parseGroupWakeFrame, Rc as knockSlotOf, Rl as inviteOwnership, Rn as withoutVideoMetadata, Ro as RatchetBox, Rr as ChatFiles, Rs as handoffEphemeral, S as GROUP_READ_NOTE_COMMUNITY, Sc as readEnrollHello, Si as HOLD_DATED_BACK_MS, Sl as parseImageMeta, So as arrivalKey, Sr as COMMUNITY_TOPOLOGY, Ss as HANDOFF_PAKE, T as encodeCommunityLink, Tc as endedRequests, Ti as HoldRefusedError, To as receivedTimestamp, Tr as doorHubs, Ts as HANDOFF_TIMINGS, Tu as isDiscoveryBudgetError, U as frameBytes, Ua as COMMUNITY_REACTION_FRAME, Uc as openRequest, Ui as CapsExchange, Ul as deviceEchoFrame, Uo as DHT_POLL_INTERVALS, Ur as transferStalled, Us as handoffReleaseFrame, V as GROUP_READ_NOTE, Va as forwardedAgain, Vc as makeStampPaced, Vl as ENROLL_CAPABILITY, Vn as isStrippedPicture, Vo as DirectPathWatch, Vr as sentWhole, Vs as handoffOfferFrame, Vu as bytesEqual, Wa as GROUP_REACTION_FRAME, Wc as readKnockSlot, Wi as DHT_TEXT_CAPABILITY, Wl as deviceEchoNonce, Wn as GhostLink, Ws as handoffRetryAfter, Wt as didDhtDocument, Wu as randomBytes, X as mentionsMember, Xa as reactionIsNewer, Xc as APP_ICON_PATH, Xl as webCryptoSigner, Xn as EngineError, Xo as formatLocalTarget, Xr as PIN_LIMITS, Xs as readHandoffDone, Xt as ETHEREUM_USDT, Y as parseCommunityEdit, Ya as reactionEmoji, Yc as APP_BUNDLE_MAGIC, Yl as seedSigner, Yn as pairedMessageFrame, Yo as GhostlyHttpError, Ys as readHandoffCancel, Yt as signDidDhtPacket, Z as groupName, Za as readReaction, Zn as engineError, Zo as parseLocalTarget, Zr as mayPin, Zs as readHandoffHave, Zt as EVM_TEST_CHAINS, _ as groupTypingEpoch, _a as DHT_FILE_CAPABILITY, _c as enrollDoneFrame, _i as BUTTONS_CAPABILITY, _l as readAppRevocationShape, _n as isPubkyKey, _r as readGroupSignal, _s as HANDOFF_CANCEL, _t as isAtprotoDid, _u as RelayTransport, a as appRevocationFor, ac as readSetUpdate, ai as newWakeToken, al as readAppBundleAsync, an as arkAddressPrefix, ar as groupFileFallback, au as nextTurnPosition, b as COMMUNITY_LIMITS, ba as sanitizeFileName, bc as enrollProofFrame, bi as UPGRADE_CAPABILITY, br as meshHubs, bs as HANDOFF_HELLO, bu as currentRelays, c as checkAppBeforeRun, ca as emptyProofLedger, cc as signTombstone, ci as wakeRequest, cl as APP_STATEMENT_LIMITS, cn as formatPaymentAmount, cs as contactRtcConfig, cu as signTurnRelease, da as automaticTransport, di as APP_RANGE_LIMITS, dl as appRefPublisher, dn as SPARK_NETWORKS, do as STATUS_CARD_LIMITS, dr as CarriedTransport, du as turnName, ec as readHandoffTurnFrame, ei as pinNumberHolds, en as SEPOLIA_TEST_USDT, eo as pairedReplyAuthor, er as GROUP_FILE_LIMITS, es as decodeControl, eu as classifyTurnRead, fi as isServeId, fn as SPARK_PROVIDER, fs as emptyLinkRecords, fu as turnStatedVerifier, g as GroupTypingBoard, ga as peekDhtMailbox, gc as enrollDigits, gi as APPS_CAPABILITY, gl as readAppRevocation, gr as groupSignalFrame, gs as HANDOFF_ACK, ha as DHT_MESSAGE_TTL, hc as enrollCancelReason, hi as isAppVersion, hl as isAppRef, hn as isBitcoinAddress, hs as serviceIdFromName, i as addedAppPermissions, ia as receivedIdentityStatus, ii as deviceWakeRequest, in as WALLET_NETWORKS, iu as firstDeviceSetSecret, j as knockRecords, ja as parseVideoMeta, jc as turnOff, jl as deviceInviteJoinerParams, jn as fedimintRequestPayload, jo as commitHash, jr as newerHead, js as handoffAttemptSucceeded, k as entryParams, kc as settleRequest, kl as readContactLink, kn as ENDPOINT, kr as mergeBeacon, ks as handoffAttemptAllowed, ku as createRelayPayload, l as planAppUpdate, la as validExternalKey, lc as verifySetUpdate, li as checkPushEndpoint, ll as appFingerprint, ln as validatePaymentTarget, lu as turnInstance, mc as enrollCancelFrame, mi as chatAppId, ml as isAppKey, mn as sparkInvoiceDetails, ms as LEGACY_SERVICES, mu as DEFAULT_RELAYS, n as readX401SdJwtVc, nc as sealHandoffPiece, ni as WAKE_CALL_INTERVAL_MS, nl as isAppUrl, nn as TEST_USDT_FAUCET_AMOUNT, no as replySnippet, nu as TURN_LAST_SEQUENCE, o as appStoreDecision, oa as lastSharedWithMe, oc as setAckFrame, oi as parseWakeFrame, ol as sha256Paced, on as assertTokenUnits, ou as readTurnPacket, p as readAppStoreSteps, pl as isAppHash, pn as sparkAddressKind, ps as HTTP_SERVICE_PROTO, pu as turnVerifierMark, q as carryMentions, qa as nextReactionNumber, qc as seenEntry, ql as devicePingFrame, qn as PAIRED_FRAME_TOO_LARGE, qo as WATCH_PEER_MS, qs as newHandoffId, qt as encodeDidDhtPacket, qu as utf8Decode, r as sameX401HolderJwk, ri as WakeLimiter, rl as pacer, rn as USDT_PUBLIC_RPC, ro as BUTTON_ID, rs as RTC_CONFIG, ru as TURN_MAX, s as appUpdateDecision, sa as PeerProofs, sc as setUpdateFrame, si as relayRequest, sn as assertWholeSats, sr as readGroupFileMeta, su as signTurnPacket, t as newX401HolderKey, tc as readHandoffVerified, ti as readPin, to as readReply, tr as GROUP_HAVE_FRAME, ts as encodeControl, tu as turnPutSummary, u as APP_STORE_LIMITS, ua as TRANSPORTS, ui as vapidKeysMatch, ul as appRef, un as walletNetworkOf, us as parseCallSignal, uu as turnKeys, v as openGroupTyping, va as dhtFileId, vc as enrollGrantFrame, vi as EDIT_CAPABILITY, vo as checkStatusCard, vr as MESH_HUBS, vs as HANDOFF_DONE, vt as normalizeAtprotoHandle, w as decodeCommunityLink, wc as clearMissed, wi as HoldKeys, wl as canonicalJson, wo as heardTime, wr as beaconRecords, ws as HANDOFF_REQUEST, wu as budgetRetryMs, x as CommunitySession, xa as sanitizeMime, xc as readEnrollGrant, xi as HOLD_CAPABILITY, xo as statusCardText, xr as pickMeshHubs, xs as HANDOFF_OFFER, xu as normalizeRelayUrl, y as sealGroupTyping, ya as formatFileSize, yc as enrollHelloFrame, yi as STATUS_CARD_CAPABILITY, yo as sameButtonText, yr as mayBeHub, ys as HANDOFF_HAVE, z as GROUP_LIMITS, zc as knockSlotRecords, zn as NO_PICTURE_METADATA, zo as emptyRatchetState, zr as FILE_LIMITS, zs as handoffHelloFrame, zu as sanitizeAvatar } from "./src-DZagapGt.js";
3
3
  import { i as SourceUnreachableError, n as PROVIDER_PLATFORMS, o as isNothingSpentError, r as SourceConfigError, t as NothingSpentError, u as redact } from "./types-C4_KafL_.js";
4
4
  import { t as bitcoindRpc } from "./bitcoindProvider-DGw3xBSa.js";
5
- import { t as nwc } from "./nwcProvider-CzX3xH47.js";
6
- import { a as clearProfileStores, c as deleteDatabase, d as newestWalletTx, f as openDb, g as wrap, h as transact, i as STORES$1, l as errorLine, m as store, n as APP_STORAGE_SCOPE_INDEX, o as committed, p as profileOpenFailure, r as CARD_INDEX, s as databaseName, t as APP_STORAGE_CHAT_INDEX, u as fileStore } from "./idb-BkOJES5_.js";
7
- import { a as sealSeed, i as newDeviceKey, o as unsealSeed, r as intentRepository } from "./networkReason-BncJ9KSM.js";
8
- import { $ as ModeChanged, A as IdentityProofs, B as INVOICE_PACE, C as FileAppender, D as streamStored, E as storedSize, F as LightningCards, G as cashuMint, H as ProviderSources, I as cardsKey, J as breezDatabasesFor, K as breezDatabase, L as isRecoveryPhrase, M as sealSecret, N as whenDataKeyDropped, P as CASHU_CARD, Q as relayOnlyProblem, R as normalizePhrase, S as WALLET_TYPES, T as removeStored, U as sourceKey, V as nextInvoiceAsk, W as CASHU_MINT_SOURCE, X as iceServerProblem, Y as dropBreezDatabase, Z as iceServerSetting, _ as crossNetwork, a as storedGroupFiles, at as requireTurn, b as walletInstances, c as receivedPairedReply, d as paymentAlias, et as ModeGate, f as paymentWireId, g as createTiming, h as createFailure, i as groupOfFile, it as refuseAway, j as openSecret, l as replyRef, m as assertConfirmedReal, n as groupFileId, nt as networkLabel, o as groupReply, ot as setAwayWallets, p as WALLET_NAMES, q as breezDatabaseInUse, r as groupFileText, rt as awayFrom, s as pairedWireReply, st as setSingleWriterGate, t as GroupFileDesk, tt as WrongNetworkError, u as replyTo, v as paymentNetwork, w as readStored$1, y as paymentNetworksOf, z as lightningPaying } from "./groupFiles-FXel6zIc.js";
9
- import { a as fedimintDatabase, i as onPublicIrohRelay, n as createIrohWebEndpoint, r as irohRelayProblem, s as loadFedimintSdk, t as DEFAULT_IROH_RELAYS } from "./irohWeb-BSv_BWyG.js";
5
+ import { t as nwc } from "./nwcProvider-BlkPOJen.js";
6
+ import { a as clearProfileStores, c as deleteDatabase, d as newestWalletTx, f as openDb, g as wrap, h as transact, i as STORES$1, l as errorLine, m as store, n as APP_STORAGE_SCOPE_INDEX, o as committed, p as profileOpenFailure, r as CARD_INDEX, s as databaseName, t as APP_STORAGE_CHAT_INDEX, u as fileStore } from "./idb-BHsAqENE.js";
7
+ import { a as sealSeed, i as newDeviceKey, o as unsealSeed, r as intentRepository } from "./networkReason-MInk1Y63.js";
8
+ import { $ as breezDatabasesFor, A as IdentityProofs, B as cardsKey, C as FileAppender, D as streamStored, E as storedSize, F as takesUnsealed, G as INVOICE_PACE, H as normalizePhrase, I as whenDataKeyDropped, J as sourceKey, K as nextInvoiceAsk, L as isSealedField, M as openSecret, N as sealPlace, P as sealSecret, Q as breezDatabaseInUse, R as CASHU_CARD, S as WALLET_TYPES, T as removeStored, U as journaledPayment, V as isRecoveryPhrase, W as lightningPaying, X as cashuMint, Y as CASHU_MINT_SOURCE, Z as breezDatabase, _ as crossNetwork, a as storedGroupFiles, at as ModeGate, b as walletInstances, c as receivedPairedReply, ct as awayFrom, d as paymentAlias, dt as setAwayWallets, et as dropBreezDatabase, f as paymentWireId, ft as setSingleWriterGate, g as createTiming, h as createFailure, i as groupOfFile, it as ModeChanged, j as hasDataKey, l as replyRef, lt as refuseAway, m as assertConfirmedReal, n as groupFileId, nt as iceServerSetting, o as groupReply, ot as WrongNetworkError, p as WALLET_NAMES, q as ProviderSources, r as groupFileText, rt as relayOnlyProblem, s as pairedWireReply, st as networkLabel, t as GroupFileDesk, tt as iceServerProblem, u as replyTo, ut as requireTurn, v as paymentNetwork, w as readStored$1, y as paymentNetworksOf, z as LightningCards } from "./groupFiles-NonOYBKN.js";
9
+ import { a as fedimintDatabase, i as onPublicIrohRelay, n as createIrohWebEndpoint, r as irohRelayProblem, s as loadFedimintSdk, t as DEFAULT_IROH_RELAYS } from "./irohWeb-C9ChbD-c.js";
10
10
  import { c as isTestMint, d as mintUrlSpelling, f as paysItsOwnInvoices, l as isWorthlessMint, n as DEFAULT_MINTS, o as fakesLightning, r as TEST_MINT, t as BITCOIN_INVOICE_ON_TESTNET, u as mintNetwork } from "./mints-j5XAOk4f.js";
11
- import { a as registeredLightningProviders, c as boundedIdentityFetch, d as testSwitch, n as setOwnDidSource, o as registeredOnchainProviders, r as onAdaptersChanged, s as reserveAdapterIds, u as testBuild } from "./ownDid-D8z5gwGI.js";
12
- import { n as MAX_BACKUP_BYTES, t as BACKUP_MEDIA_TYPE } from "./envelope-Dt75vrmY.js";
13
- import { d as chosenResolver, r as resolveAtprotoDid, t as assertPublicServer } from "./resolve-ZxVzwFNA.js";
14
- import { c as fileSpace, f as FILE_BYTES_STEP, o as fileBytes, r as blobDigest, s as fileBytesOf, u as removeFileBytes } from "./fileBytes-DNgrRL0R.js";
11
+ import { a as registeredLightningProviders, c as boundedIdentityFetch, d as testSwitch, n as setOwnDidSource, o as registeredOnchainProviders, r as onAdaptersChanged, s as reserveAdapterIds, u as testBuild } from "./ownDid-yXtY_1B5.js";
12
+ import { n as MAX_BACKUP_BYTES, t as BACKUP_MEDIA_TYPE } from "./envelope-CugS9qwQ.js";
13
+ import { d as chosenResolver, r as resolveAtprotoDid, t as assertPublicServer } from "./resolve-Dtzogt2W.js";
14
+ import { c as fileSpace, f as FILE_BYTES_STEP, o as fileBytes, r as blobDigest, s as fileBytesOf, u as removeFileBytes } from "./fileBytes-DjBYYyXT.js";
15
15
  import { t as hyperdhtRelayProblem } from "./hyperdhtRelay-1wzya_0L.js";
16
16
  import { sha256 } from "@noble/hashes/sha2.js";
17
17
  import { hkdf } from "@noble/hashes/hkdf.js";
@@ -199,7 +199,7 @@ function viewNews(before, after) {
199
199
  //#endregion
200
200
  //#region ../browser/src/engine/paymentAdapters/usdtWallet.ts
201
201
  /** The Ethereum libraries, a large part of the app: loaded once a USDT wallet is made, opened or restored, not with the engine. */
202
- var loadUsdt = () => import("./usdt-DhVN8geQ.js");
202
+ var loadUsdt = () => import("./usdt-BU4ezonh.js");
203
203
  /** Every new profile starts with this wallet: an address to receive on, nothing to set up. */
204
204
  var DEFAULT_USDT = {
205
205
  network: "ethereum",
@@ -686,7 +686,7 @@ async function restoreArkDatabase(walletId, snapshot) {
686
686
  //#endregion
687
687
  //#region ../browser/src/engine/paymentAdapters/arkWallet.ts
688
688
  /** The Ark SDK, a large part of the app: loaded once an Ark wallet is made, opened or restored, not with the engine. */
689
- var loadArkade = () => import("./arkade-DtYR9H0c.js");
689
+ var loadArkade = () => import("./arkade-DOWpA2Kr.js");
690
690
  /** How long a Testnet wallet about to make way for another waits for its server to say what it holds. */
691
691
  var RETIRE_READ_MS = 1e4;
692
692
  /** Every new profile starts with this wallet: nothing to set up before receiving. */
@@ -6265,7 +6265,7 @@ function networkNamed(name) {
6265
6265
  /** Mutinynet is a signet: its invoices say `lntbs`, like any signet's. */
6266
6266
  var sameChain = (a, b) => a === b || a === "mutinynet" && b === "signet";
6267
6267
  /** Calls the wallet, bounded in time and ended by the source's signal. A wallet that throws at once rejects too. */
6268
- function within$2(call, ms, what, signal) {
6268
+ function within$3(call, ms, what, signal) {
6269
6269
  return new Promise((resolve, reject) => {
6270
6270
  const timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`The browser wallet did not answer (${what})`)), ms);
6271
6271
  const abort = () => reject(/* @__PURE__ */ new Error("The browser wallet was disconnected"));
@@ -6318,17 +6318,17 @@ var WeblnLightning = class WeblnLightning {
6318
6318
  static async connect(webln, mode, signal) {
6319
6319
  if (!webln) throw new Error("No WebLN wallet in this browser. Install or unlock one (Alby, for example), then connect again");
6320
6320
  try {
6321
- const answer = await within$2(() => webln.enable(), PROMPT_MS, "connect", signal);
6321
+ const answer = await within$3(() => webln.enable(), PROMPT_MS, "connect", signal);
6322
6322
  if (answer && typeof answer === "object" && answer.enabled === false) throw new Error("not enabled");
6323
6323
  } catch (error) {
6324
6324
  if (signal?.aborted) throw error;
6325
6325
  throw Object.assign(/* @__PURE__ */ new Error(`The browser wallet refused the connection (${message$1(error)})`), { cause: error });
6326
6326
  }
6327
- const info = typeof webln.getInfo === "function" ? await within$2(() => webln.getInfo(), CALL_MS, "info", signal).catch(() => void 0) : void 0;
6327
+ const info = typeof webln.getInfo === "function" ? await within$3(() => webln.getInfo(), CALL_MS, "info", signal).catch(() => void 0) : void 0;
6328
6328
  const methods = Array.isArray(info?.methods) ? info.methods : void 0;
6329
6329
  const has = (method) => typeof webln[method] === "function" && (!methods || methods.includes(method));
6330
6330
  let balance = false;
6331
- if (has("getBalance")) balance = await within$2(() => webln.getBalance(), CALL_MS, "balance", signal).then((b) => sats$1(b) !== void 0, () => false);
6331
+ if (has("getBalance")) balance = await within$3(() => webln.getBalance(), CALL_MS, "balance", signal).then((b) => sats$1(b) !== void 0, () => false);
6332
6332
  const capabilities = {
6333
6333
  receive: has("makeInvoice"),
6334
6334
  send: has("sendPayment"),
@@ -6338,7 +6338,7 @@ var WeblnLightning = class WeblnLightning {
6338
6338
  if (!capabilities.receive && !capabilities.send) throw new Error("This browser wallet can neither make nor pay invoices");
6339
6339
  let network = networkNamed(info?.network) ?? networkNamed(info?.chain) ?? networkNamed(info?.node?.network);
6340
6340
  if (!network && capabilities.receive) {
6341
- const probe = await within$2(() => webln.makeInvoice({
6341
+ const probe = await within$3(() => webln.makeInvoice({
6342
6342
  amount: 1,
6343
6343
  defaultMemo: "Ghostly: which network is this wallet on?"
6344
6344
  }), CALL_MS, "invoice", signal);
@@ -6360,13 +6360,13 @@ var WeblnLightning = class WeblnLightning {
6360
6360
  return {
6361
6361
  network: this.network,
6362
6362
  alias: this.alias,
6363
- ...this.capabilities.balance ? { balance: sats$1(await within$2(() => this.webln.getBalance(), CALL_MS, "balance", this.signal)) ?? 0 } : {}
6363
+ ...this.capabilities.balance ? { balance: sats$1(await within$3(() => this.webln.getBalance(), CALL_MS, "balance", this.signal)) ?? 0 } : {}
6364
6364
  };
6365
6365
  }
6366
6366
  async createInvoice(amount, memo) {
6367
6367
  this.ready();
6368
6368
  if (!this.capabilities.receive) throw new Error("This browser wallet cannot make invoices");
6369
- const made = await within$2(() => this.webln.makeInvoice({
6369
+ const made = await within$3(() => this.webln.makeInvoice({
6370
6370
  amount,
6371
6371
  defaultMemo: memo?.slice(0, 140)
6372
6372
  }), CALL_MS, "invoice", this.signal);
@@ -6403,7 +6403,7 @@ var WeblnLightning = class WeblnLightning {
6403
6403
  if (!decoded?.paymentHash || decoded.amountSat === null) throw new Error("That is not an invoice this wallet can pay");
6404
6404
  if (!sameChain(this.network, decoded.network)) throw new Error(`That invoice is for ${decoded.network}, and this browser wallet is on ${this.network}`);
6405
6405
  if (this.capabilities.balance) {
6406
- const balance = sats$1(await within$2(() => this.webln.getBalance(), CALL_MS, "balance", this.signal));
6406
+ const balance = sats$1(await within$3(() => this.webln.getBalance(), CALL_MS, "balance", this.signal));
6407
6407
  if (balance !== void 0 && balance < decoded.amountSat) throw new Error(`Not enough in the browser wallet (${balance} sats)`);
6408
6408
  }
6409
6409
  } catch (error) {
@@ -6411,7 +6411,7 @@ var WeblnLightning = class WeblnLightning {
6411
6411
  }
6412
6412
  let answer;
6413
6413
  try {
6414
- answer = await within$2(() => this.webln.sendPayment(decoded.invoice), PROMPT_MS, "payment", this.signal);
6414
+ answer = await within$3(() => this.webln.sendPayment(decoded.invoice), PROMPT_MS, "payment", this.signal);
6415
6415
  } catch (error) {
6416
6416
  if (!this.signal?.aborted && error instanceof Error && (REFUSED_NAMES.has(error.name) || REFUSED.test(error.message) || NOT_SENT.test(error.message))) throw new NothingSpentError(`The browser wallet did not pay: ${message$1(error)}`);
6417
6417
  throw Object.assign(/* @__PURE__ */ new Error(`The browser wallet did not say whether it paid (${message$1(error)})`), { cause: error });
@@ -6438,7 +6438,7 @@ var WeblnLightning = class WeblnLightning {
6438
6438
  }
6439
6439
  async lookup(what) {
6440
6440
  if (!this.capabilities.lookup) throw new Error("This browser wallet cannot look up invoices");
6441
- const found = await within$2(() => this.webln.lookupInvoice({
6441
+ const found = await within$3(() => this.webln.lookupInvoice({
6442
6442
  paymentHash: what.paymentHash,
6443
6443
  paymentRequest: what.invoice
6444
6444
  }), CALL_MS, "lookup", this.signal);
@@ -6497,7 +6497,7 @@ function fakeInvoice(amount, paymentHash, memo = "", expirySeconds = 3600) {
6497
6497
  }
6498
6498
  /** A valid regtest P2WPKH address of nobody's. */
6499
6499
  var fakeAddress = () => bech32.encode("bcrt", [0, ...bech32.toWords(random$1(20))]);
6500
- var FIELDS = [
6500
+ var FIELDS$1 = [
6501
6501
  {
6502
6502
  name: "alias",
6503
6503
  label: "Name",
@@ -6725,7 +6725,7 @@ var fakeLightning = {
6725
6725
  description: "In-memory regtest node for tests. Holds nothing.",
6726
6726
  networks: ["regtest"],
6727
6727
  platforms: ["web", "desktop"],
6728
- fields: FIELDS,
6728
+ fields: FIELDS$1,
6729
6729
  experimental: true,
6730
6730
  validate,
6731
6731
  async create(settings) {
@@ -6739,7 +6739,7 @@ var fakeOnchain = {
6739
6739
  description: "In-memory regtest wallet for tests. Holds nothing.",
6740
6740
  networks: ["regtest"],
6741
6741
  platforms: ["web", "desktop"],
6742
- fields: FIELDS,
6742
+ fields: FIELDS$1,
6743
6743
  experimental: true,
6744
6744
  validate,
6745
6745
  async create(settings) {
@@ -7292,10 +7292,14 @@ var ContactLinks = class {
7292
7292
  */
7293
7293
  accept(id) {
7294
7294
  return this.serial(async () => {
7295
- const request = this.stored.current?.requests?.find((r) => r.key === id);
7296
- if (!request) throw new Error("This request is no longer waiting");
7295
+ const current = this.stored.current;
7296
+ const request = current?.requests?.find((r) => r.key === id);
7297
+ if (!current || !request) throw new Error("This request is no longer waiting");
7297
7298
  if (request.expires <= Date.now()) throw new Error("This request expired");
7298
- const linkId = await this.host.accept(request);
7299
+ const linkId = await this.host.accept({
7300
+ ...request,
7301
+ link: request.link ?? current.linkKeyZ32
7302
+ });
7299
7303
  await this.settle(id);
7300
7304
  return { linkId };
7301
7305
  });
@@ -7422,7 +7426,8 @@ var ContactLinks = class {
7422
7426
  taken.push({
7423
7427
  ...request,
7424
7428
  key,
7425
- receivedAt: now
7429
+ receivedAt: now,
7430
+ link: linkKey
7426
7431
  });
7427
7432
  }
7428
7433
  }
@@ -7593,6 +7598,15 @@ var ContactAsks = class {
7593
7598
  } catch {}
7594
7599
  });
7595
7600
  }
7601
+ /**
7602
+ * The proof that this profile asked, for the chat a request of its started (WISP 8xx § Accept): said on each live
7603
+ * session of that chat, so the owner's app shows the request's text as confirmed. Undefined for any other chat.
7604
+ */
7605
+ async proof(chatId, chat) {
7606
+ const ask = this.asks.find((a) => a.chatId === chatId);
7607
+ if (!ask) return void 0;
7608
+ return contactAskerFrame((await this.identity(ask)).seedB64, ask.link, chat);
7609
+ }
7596
7610
  /** Looks after every request not yet seen once (the timer does this at its pace). */
7597
7611
  tick() {
7598
7612
  return this.serial(() => this.look());
@@ -9186,7 +9200,7 @@ var HostNotContacted = class extends Error {};
9186
9200
  */
9187
9201
  function fixedHostsFetch(fetch) {
9188
9202
  return async (url, options) => {
9189
- const { fixedIdentityHosts } = await import("./fixedHosts-B598JzbC.js");
9203
+ const { fixedIdentityHosts } = await import("./fixedHosts-B4E4VrYE.js");
9190
9204
  const host = hostOf$1(url);
9191
9205
  if (!fixedIdentityHosts().has(host) && host !== hostOf$1("https://public.api.bsky.app") && host !== hostOf$1("https://nexus.pubky.app")) throw new HostNotContacted(`Hide my IP from contacts is on: ${host}, a server your contact chose, was not contacted`);
9192
9206
  return fetch(url, options);
@@ -9391,7 +9405,7 @@ var PUBLIC_PROFILE_READERS = {
9391
9405
  var KEY = "publicProfiles";
9392
9406
  /** Unused entries are dropped this often, so an expired proof's profile does not wait for the next change. */
9393
9407
  var PRUNE_MS = 6e5;
9394
- var keyOf$1 = (s) => `${s.provider}\n${s.subject}`;
9408
+ var keyOf$2 = (s) => `${s.provider}\n${s.subject}`;
9395
9409
  /**
9396
9410
  * The fetch an identity's public data is read with: a contact's, while Hide my IP from contacts is on, reaches only
9397
9411
  * hosts this app names, so a server the contact chose (their AT Protocol server) never learns this device's IP address.
@@ -9414,6 +9428,8 @@ var PublicProfiles = class {
9414
9428
  timer;
9415
9429
  /** Before the chats are loaded every contact's identity would look ineligible: nothing is pruned until then. */
9416
9430
  started = false;
9431
+ /** The engine stopped ("Clear all data" empties the stores next): an answer still on its way writes nothing. */
9432
+ stopped = false;
9417
9433
  fetch;
9418
9434
  constructor(host) {
9419
9435
  this.host = host;
@@ -9433,6 +9449,7 @@ var PublicProfiles = class {
9433
9449
  /** Starts the periodic clean-up; call once the chats are loaded, so `eligible` sees them. */
9434
9450
  start() {
9435
9451
  this.started = true;
9452
+ this.stopped = false;
9436
9453
  this.prune().catch(() => {});
9437
9454
  this.timer ??= setInterval(() => {
9438
9455
  this.prune().catch(() => {});
@@ -9441,8 +9458,10 @@ var PublicProfiles = class {
9441
9458
  stop() {
9442
9459
  if (this.timer) clearInterval(this.timer);
9443
9460
  this.timer = void 0;
9461
+ this.stopped = true;
9444
9462
  }
9445
9463
  async save() {
9464
+ if (this.stopped) return;
9446
9465
  await transact([STORES$1.settings], (stores) => {
9447
9466
  stores[STORES$1.settings].put(this.cache, KEY);
9448
9467
  });
@@ -9453,7 +9472,7 @@ var PublicProfiles = class {
9453
9472
  /** What a card shows for this identity; undefined with the setting off, for a provider without profiles, or never asked. */
9454
9473
  view(s) {
9455
9474
  if (!this.host.enabled() || !this.readers[s.provider]) return void 0;
9456
- const key = keyOf$1(s);
9475
+ const key = keyOf$2(s);
9457
9476
  const c = this.cache[key];
9458
9477
  const loading = this.inflight.has(key);
9459
9478
  const error = this.errors.get(key);
@@ -9486,7 +9505,7 @@ var PublicProfiles = class {
9486
9505
  async request(s) {
9487
9506
  const reader = this.readers[s.provider];
9488
9507
  if (!reader || !this.host.enabled() || !this.host.online() || !this.isEligible(s)) return;
9489
- const key = keyOf$1(s);
9508
+ const key = keyOf$2(s);
9490
9509
  const existing = this.inflight.get(key);
9491
9510
  if (existing) return existing;
9492
9511
  const c = this.cache[key];
@@ -9502,7 +9521,7 @@ var PublicProfiles = class {
9502
9521
  return task;
9503
9522
  }
9504
9523
  async ask(s, reader) {
9505
- const key = keyOf$1(s);
9524
+ const key = keyOf$2(s);
9506
9525
  const checkedAt = this.now;
9507
9526
  try {
9508
9527
  const data = await reader.read(s.subject, {
@@ -9551,7 +9570,7 @@ var PublicProfiles = class {
9551
9570
  /** Drops every profile whose identity is no longer eligible (expired, removed, withdrawn, revoked). */
9552
9571
  async prune() {
9553
9572
  if (!this.started) return;
9554
- const keep = new Set(this.host.eligible().map(keyOf$1));
9573
+ const keep = new Set(this.host.eligible().map(keyOf$2));
9555
9574
  const drop = Object.keys(this.cache).filter((k) => !keep.has(k));
9556
9575
  if (!drop.length) return;
9557
9576
  for (const k of drop) {
@@ -10078,7 +10097,7 @@ async function readPostImage(source, ctx) {
10078
10097
  var MAX_IMAGES_KEPT = 16;
10079
10098
  /** One ask, all its pages and hosts included. */
10080
10099
  var ASK_TIMEOUT_MS = 2e4;
10081
- var keyOf = (s) => `${s.provider}\n${s.subject}`;
10100
+ var keyOf$1 = (s) => `${s.provider}\n${s.subject}`;
10082
10101
  /**
10083
10102
  * A contact's verified identity's recent posts and follows, engine side (PUBLIC-PROFILES.md, "Posts and follows"):
10084
10103
  * asked one identity at a time when the reader chooses its card, only for a current, verified proof, only with Load
@@ -10177,7 +10196,7 @@ var PublicActivity = class {
10177
10196
  /** The identity's recent posts: the kept page when fresh, else asked; `more` adds the next page. */
10178
10197
  async loadPosts(s) {
10179
10198
  if (!this.allowed(s)) return null;
10180
- const key = keyOf(s);
10199
+ const key = keyOf$1(s);
10181
10200
  const kept = this.posts.get(key);
10182
10201
  if (kept) kept.used = Date.now();
10183
10202
  const fresh = kept && this.now - kept.fetchedAt < 600;
@@ -10232,7 +10251,7 @@ var PublicActivity = class {
10232
10251
  fetchedAt: 0
10233
10252
  };
10234
10253
  const following = new Set(g.following), followers = new Set(g.followers ?? []);
10235
- const theirList = (subject) => this.graphs.get(keyOf({
10254
+ const theirList = (subject) => this.graphs.get(keyOf$1({
10236
10255
  provider: s.provider,
10237
10256
  subject
10238
10257
  }));
@@ -10270,7 +10289,7 @@ var PublicActivity = class {
10270
10289
  */
10271
10290
  async loadGraph(s) {
10272
10291
  if (!this.allowed(s)) return null;
10273
- const key = keyOf(s);
10292
+ const key = keyOf$1(s);
10274
10293
  const { own, contacts } = this.known(s);
10275
10294
  const kept = this.graphs.get(key);
10276
10295
  if (kept) kept.used = Date.now();
@@ -10301,10 +10320,10 @@ var PublicActivity = class {
10301
10320
  /** One picture of a post already loaded, on the reader's tap; the source comes from the kept post, never the page. */
10302
10321
  async loadImage(s) {
10303
10322
  if (!this.allowed(s)) throw new Error("Public profiles are off, or this identity is no longer verified");
10304
- const post = this.posts.get(keyOf(s))?.posts.find((p) => p.id === s.postId);
10323
+ const post = this.posts.get(keyOf$1(s))?.posts.find((p) => p.id === s.postId);
10305
10324
  const image = Number.isSafeInteger(s.index) ? post?.images[s.index] : void 0;
10306
10325
  if (!image) throw new Error("That picture is no longer here: load the posts again");
10307
- const key = `${keyOf(s)}\n${s.postId}\n${s.index}`;
10326
+ const key = `${keyOf$1(s)}\n${s.postId}\n${s.index}`;
10308
10327
  const kept = this.images.get(key);
10309
10328
  if (kept) {
10310
10329
  kept.used = Date.now();
@@ -10335,7 +10354,7 @@ var PublicActivity = class {
10335
10354
  }
10336
10355
  /** Drops what belongs to identities that are no longer eligible (expired, removed, withdrawn, revoked). */
10337
10356
  prune() {
10338
- const keep = new Set(this.host.eligible().map(keyOf));
10357
+ const keep = new Set(this.host.eligible().map(keyOf$1));
10339
10358
  const owner = (k) => k.split("\n").slice(0, 2).join("\n");
10340
10359
  for (const map of [
10341
10360
  this.posts,
@@ -10403,14 +10422,46 @@ async function bytesHere(file) {
10403
10422
  if (file.blob) return file.blob.size;
10404
10423
  return await (file.bytes ? await fileBytesOf(file.bytes) : null)?.size(file.id) ?? 0;
10405
10424
  }
10425
+ /** `read` with the parts `patches` replace (zeros where a patch has no bytes). */
10426
+ function patchedRead(read, patches) {
10427
+ return async (offset, length) => {
10428
+ const part = (await read(offset, length)).slice();
10429
+ const end = offset + part.length;
10430
+ for (const { start, end: until, bytes } of patches) {
10431
+ if (until <= offset || start >= end) continue;
10432
+ const from = Math.max(start, offset), to = Math.min(until, end);
10433
+ if (bytes) part.set(bytes.subarray(from - start, to - start), from - offset);
10434
+ else part.fill(0, from - offset, to - offset);
10435
+ }
10436
+ return part;
10437
+ };
10438
+ }
10406
10439
  /**
10407
- * A received picture as it goes on: without its metadata (one from an app that sent it with them keeps where its author
10408
- * took it, the device, the time), read whole; undefined for any other file, copied as it is. Refused with
10409
- * `NO_PICTURE_METADATA` when its metadata cannot be removed, as a picture sent from here is.
10440
+ * A received picture or video as it goes on: without its metadata (one from an app that sent it with them keeps where
10441
+ * its author took it, the device, the time), as one sent from here; undefined for any other file, copied as it is. A
10442
+ * picture is read whole; a video's stripped bytes are a Blob when it is kept in one, else read through the parts
10443
+ * changed. Refused with `NO_PICTURE_METADATA` or `NO_VIDEO_METADATA` when its metadata cannot be removed.
10410
10444
  */
10411
10445
  async function withoutMetadata(source, size, file, read) {
10412
- if (file.voice || file.video || !size) return void 0;
10413
- if (!isStrippedPicture(await read(0, Math.min(PICTURE_METADATA_LIMITS.headBytes, size)), file.mime)) return void 0;
10446
+ if (file.voice || !size) return void 0;
10447
+ if (file.video || !isStrippedPicture(await read(0, Math.min(PICTURE_METADATA_LIMITS.headBytes, size)), file.mime)) {
10448
+ if (source.blob) return withoutVideoMetadata(source.blob, file.mime);
10449
+ const readFully = async (offset, length) => {
10450
+ const whole = new Uint8Array(Math.max(0, Math.min(length, size - offset)));
10451
+ for (let at = 0; at < whole.length;) {
10452
+ const part = await read(offset + at, whole.length - at);
10453
+ if (!part.length) break;
10454
+ whole.set(part, at);
10455
+ at += part.length;
10456
+ }
10457
+ return whole;
10458
+ };
10459
+ const patches = await videoMetadataPatches({
10460
+ size,
10461
+ read: readFully
10462
+ }, file.mime);
10463
+ return patches && patchedRead(read, patches);
10464
+ }
10414
10465
  if (size > PICTURE_METADATA_LIMITS.maxBytes) throw new Error(NO_PICTURE_METADATA);
10415
10466
  const whole = new Uint8Array(size);
10416
10467
  for (let offset = 0; offset < size;) {
@@ -10423,8 +10474,9 @@ async function withoutMetadata(source, size, file, read) {
10423
10474
  }
10424
10475
  /**
10425
10476
  * A copy of a file on this device, for sending in another chat under `file.id`: a small one whole, a larger one a
10426
- * step at a time, never whole in memory; a picture without its metadata, read whole. Refused while it is still
10427
- * arriving, or when its bytes are gone. Resolves to `file` as it goes: a stripped picture's size is its copy's.
10477
+ * step at a time, never whole in memory; a picture without its metadata, read whole, and a video without its. Refused
10478
+ * while it is still arriving, or when its bytes are gone. Resolves to `file` as it goes: a stripped file's size is its
10479
+ * copy's.
10428
10480
  */
10429
10481
  async function copyForForward(sourceId, target) {
10430
10482
  const source = await fileStore.get(sourceId);
@@ -10435,7 +10487,8 @@ async function copyForForward(sourceId, target) {
10435
10487
  const from = source.bytes ? await fileBytesOf(source.bytes) : null;
10436
10488
  const read = async (offset, length) => source.blob ? new Uint8Array(await source.blob.slice(offset, offset + length).arrayBuffer()) : from.read(source.id, offset, length);
10437
10489
  const stripped = await withoutMetadata(source, stored, target.file, read);
10438
- const blob = stripped ?? source.blob, size = stripped?.size ?? stored;
10490
+ const blob = typeof stripped === "function" ? void 0 : stripped ?? source.blob, size = blob && stripped ? blob.size : stored;
10491
+ const readCopy = typeof stripped === "function" ? stripped : read;
10439
10492
  const known = stripped ? void 0 : source.digest;
10440
10493
  const { linkId, wireId, timestamp } = target, file = stripped ? {
10441
10494
  ...target.file,
@@ -10477,7 +10530,7 @@ async function copyForForward(sourceId, target) {
10477
10530
  try {
10478
10531
  const appender = new FileAppender(bytes, file.id);
10479
10532
  for (let offset = 0; offset < size;) {
10480
- const part = blob ? new Uint8Array(await blob.slice(offset, offset + 1048576).arrayBuffer()) : await read(offset, Math.min(1048576, size - offset));
10533
+ const part = blob ? new Uint8Array(await blob.slice(offset, offset + 1048576).arrayBuffer()) : await readCopy(offset, Math.min(1048576, size - offset));
10481
10534
  if (!part.length) throw new Error("The file is shorter than it says");
10482
10535
  await appender.append(part);
10483
10536
  offset += part.length;
@@ -10934,6 +10987,11 @@ var APP_CHECK_TIMINGS = {
10934
10987
  };
10935
10988
  /** Apps the update check reads at once (their publishers' files, their sources' peeks): all on the same two hosts. */
10936
10989
  var APP_CHECK_PARALLEL = 6;
10990
+ /**
10991
+ * Stores a refresh reads at once: each read is two requests (its index and `.sig`), and a store behind the copy the
10992
+ * person took reads that copy beside them, so about as many requests as the update check's apps.
10993
+ */
10994
+ var STORE_READ_PARALLEL = 4;
10937
10995
  /** Revocations are checked this long at a time before the page's thread is let go. */
10938
10996
  var REVOCATIONS_SLICE_MS = 10;
10939
10997
  /**
@@ -11008,6 +11066,32 @@ function readCount(value) {
11008
11066
  }
11009
11067
  }
11010
11068
  /**
11069
+ * `run` on every item, at most `limit` at a time (the next one starts when one ends): one promise per item, in the
11070
+ * items' order, whatever order they end in.
11071
+ */
11072
+ function pooled(items, limit, run) {
11073
+ const ends = [];
11074
+ const out = items.map((_, i) => new Promise((resolve, reject) => {
11075
+ ends[i] = {
11076
+ resolve,
11077
+ reject
11078
+ };
11079
+ }));
11080
+ let next = 0;
11081
+ const worker = async () => {
11082
+ while (next < items.length) {
11083
+ const i = next++;
11084
+ try {
11085
+ ends[i].resolve(await run(items[i]));
11086
+ } catch (error) {
11087
+ ends[i].reject(error);
11088
+ }
11089
+ }
11090
+ };
11091
+ for (let w = 0; w < Math.min(limit, items.length); w++) worker();
11092
+ return out;
11093
+ }
11094
+ /**
11011
11095
  * A listing's URLs this client reads, in order, a jsDelivr copy first: one this client reads names a full commit, so it
11012
11096
  * holds exactly the version the store reviewed, where a raw `HEAD` may have moved on to one it has not (WISP 1200 §
11013
11097
  * Stores), and a 16 MiB bundle is not downloaded only to be skipped.
@@ -11068,6 +11152,63 @@ async function noteBundles(change) {
11068
11152
  };
11069
11153
  await done(tx);
11070
11154
  }
11155
+ /**
11156
+ * The key, in `STORES.settings`, of the revocations this profile verified, by app reference (one of
11157
+ * `PROFILE_SETTINGS_KEYS`: only "Clear all data" drops them). A client keeps every revocation it verified (WISP 1200 §
11158
+ * Publisher keys): kept beside the app's record, not in it, so Uninstall leaves them and the same version from a copy at
11159
+ * another URL, with no `ghostly-revoke.json` beside it, is still refused.
11160
+ */
11161
+ var APP_REVOCATIONS_KEY = "appRevocations";
11162
+ /**
11163
+ * Revocations kept there: at most `each` of one app and `all` in all, the ones kept longest ago dropped first. A
11164
+ * revocation is at most about 3.5 KiB (64 digests and a reason).
11165
+ */
11166
+ var REVOCATIONS_KEPT = {
11167
+ each: 64,
11168
+ all: 1024
11169
+ };
11170
+ /**
11171
+ * The revocations as kept, by reference, in the order they were last added to: read with nothing taken on trust but
11172
+ * their signatures (checked before they were kept), so an entry that is not one of that app's publisher is none.
11173
+ */
11174
+ function keptRevocations(kept) {
11175
+ const out = /* @__PURE__ */ new Map();
11176
+ if (!Array.isArray(kept)) return out;
11177
+ for (const entry of kept) {
11178
+ if (!Array.isArray(entry) || !isAppRef(entry[0]) || !Array.isArray(entry[1])) continue;
11179
+ const ref = entry[0];
11180
+ const list = entry[1].flatMap((r) => {
11181
+ const read = readAppRevocationShape(r);
11182
+ return read.ok && read.revocation.statement.app === ref && read.revocation.signature.key === appRefPublisher(ref) ? [read.revocation] : [];
11183
+ });
11184
+ if (list.length) out.set(ref, list);
11185
+ }
11186
+ return out;
11187
+ }
11188
+ /** Queues, on the settings store of an open transaction, these revocations of `ref` kept with the others (each once). */
11189
+ function keepRevocations(settings, ref, add) {
11190
+ if (!add.length) return;
11191
+ const read = settings.get(APP_REVOCATIONS_KEY);
11192
+ read.onsuccess = () => {
11193
+ const kept = keptRevocations(read.result);
11194
+ const before = kept.get(ref) ?? [];
11195
+ const merged = new Map(before.map((r) => [canonicalJson(r), r]));
11196
+ for (const r of add) if (r.statement.app === ref) merged.set(canonicalJson(r), r);
11197
+ if (merged.size === before.length) return;
11198
+ kept.delete(ref);
11199
+ kept.set(ref, [...merged.values()].slice(-REVOCATIONS_KEPT.each));
11200
+ let all = 0;
11201
+ for (const list of kept.values()) all += list.length;
11202
+ for (const [other, list] of kept) {
11203
+ if (all <= REVOCATIONS_KEPT.all || other === ref) break;
11204
+ const drop = Math.min(list.length, all - REVOCATIONS_KEPT.all);
11205
+ all -= drop;
11206
+ if (drop === list.length) kept.delete(other);
11207
+ else kept.set(other, list.slice(drop));
11208
+ }
11209
+ settings.put([...kept], APP_REVOCATIONS_KEY);
11210
+ };
11211
+ }
11071
11212
  var builtInRef = (app) => appRef(app.publisher, app.name);
11072
11213
  /**
11073
11214
  * The entries of the built-in list this profile is offered (WISP 1200 § Built-in apps): each reference once, not
@@ -11262,6 +11403,11 @@ var Apps = class {
11262
11403
  * index listing the same is not peeked again at every check.
11263
11404
  */
11264
11405
  listingMisses = /* @__PURE__ */ new Map();
11406
+ /**
11407
+ * The index a store's own URL served at its last read when it was not taken (behind the copy the person took, at a
11408
+ * commit): by store key, with that URL. The same bytes there again are not checked whole at every refresh.
11409
+ */
11410
+ behindReads = /* @__PURE__ */ new Map();
11265
11411
  /** `ghostly-revoke.json` files checked, by the SHA-256 of their bytes: their revocations, or null when refused, and the bytes the held list counts for. */
11266
11412
  revocationFiles = /* @__PURE__ */ new Map();
11267
11413
  /** Revocations read in a store's index and verified, by `appRevocationId`: at most `STORE_REVOCATIONS_KEPT`. */
@@ -11371,6 +11517,10 @@ var Apps = class {
11371
11517
  async builtInMarks() {
11372
11518
  return builtInMarks(await wrap((await store(STORES$1.settings, "readonly")).get(BUILT_IN_APPS_KEY)));
11373
11519
  }
11520
+ /** The revocations of this app this profile verified and keeps (`APP_REVOCATIONS_KEY`), installed or not. */
11521
+ async keptRevocationsOf(ref) {
11522
+ return keptRevocations(await wrap((await store(STORES$1.settings, "readonly")).get("appRevocations"))).get(ref) ?? [];
11523
+ }
11374
11524
  /**
11375
11525
  * The built-in apps this profile is offered (WISP 1200 § Built-in apps): shown with the installed ones, with nothing
11376
11526
  * stored and nothing granted. Opening one is an install like any other, from the bundle the build carries.
@@ -11484,14 +11634,18 @@ var Apps = class {
11484
11634
  * Writes an app's record back only while it is still the record `was` (`sameRecord`), read and written in one
11485
11635
  * transaction: an app uninstalled (or installed again) while the update check was reading is not put back, nor is the
11486
11636
  * version it read over an update the person accepted meanwhile. `was` undefined: only while the app has no record.
11637
+ * A store removed since the caller read the stores pins nothing: it is judged at the write, as `removeStore` unpins
11638
+ * only the records written before it.
11487
11639
  */
11488
11640
  async putAppIfUnchanged(app, was) {
11641
+ const stores = await this.records();
11489
11642
  const tx = (await openDb()).transaction(STORES$1.apps, "readwrite");
11490
11643
  let put = false;
11491
11644
  const read = tx.objectStore(STORES$1.apps).get(app.ref);
11492
11645
  read.onsuccess = () => {
11493
11646
  if (!sameRecord(read.result, was)) return;
11494
- tx.objectStore(STORES$1.apps).put(app);
11647
+ const { store: pin, ...unpinned } = app;
11648
+ tx.objectStore(STORES$1.apps).put(pin !== void 0 && stores.get(pin)?.removed ? unpinned : app);
11495
11649
  put = true;
11496
11650
  };
11497
11651
  try {
@@ -11745,13 +11899,18 @@ var Apps = class {
11745
11899
  }
11746
11900
  /**
11747
11901
  * Reads the index at `url`. With the index held for this store, bytes equal to it (by digest) are the held index: its
11748
- * signature and every revocation in it were checked when it was read, so only its expiry is taken again. Any other
11902
+ * signature and every revocation in it were checked when it was read, so only its expiry is taken again; the same for
11903
+ * `behind`, the index this URL served at its last read when it was not taken (`behindReads`). Any other
11749
11904
  * index is read with a pause every few ms (the engine shares the page's thread, and an index holds up to 4096
11750
11905
  * listings and 4096 revocations, each of these a signature check), and a revocation checked in an earlier read, of
11751
11906
  * this store or another, a preview included, is not checked again.
11752
11907
  */
11753
- async readStoreAt(url, heldKey, held) {
11908
+ async readStoreAt(url, heldKey, held, behind, unneeded) {
11754
11909
  const stop = new AbortController();
11910
+ if (unneeded?.aborted) stop.abort();
11911
+ unneeded?.addEventListener("abort", () => {
11912
+ stop.abort();
11913
+ }, { once: true });
11755
11914
  const read = (at, maxBytes) => this.host.fetch(at, {
11756
11915
  maxBytes,
11757
11916
  revalidate: true,
@@ -11761,14 +11920,22 @@ var Apps = class {
11761
11920
  throw error;
11762
11921
  });
11763
11922
  const [indexBytes, sigBytes] = await Promise.all([read(url, APP_FETCH_LIMITS.storeIndexBytes), read(besideUrl(url, "ghostly-store.sig"), APP_FETCH_LIMITS.sigBytes)]);
11764
- if (held?.index && held.digest !== void 0 && toBase64Url(await sha256Paced(indexBytes)) === held.digest) return {
11765
- ok: true,
11766
- store: {
11767
- index: held.index,
11768
- digest: held.digest,
11769
- expired: held.index.expires < this.nowS()
11770
- }
11771
- };
11923
+ const known = held?.index && held.digest !== void 0 ? [{
11924
+ index: held.index,
11925
+ digest: held.digest
11926
+ }, ...behind ? [behind] : []] : [];
11927
+ if (known.length) {
11928
+ const digest = toBase64Url(await sha256Paced(indexBytes));
11929
+ const same = known.find((k) => k.digest === digest);
11930
+ if (same) return {
11931
+ ok: true,
11932
+ store: {
11933
+ index: same.index,
11934
+ digest,
11935
+ expired: same.index.expires < this.nowS()
11936
+ }
11937
+ };
11938
+ }
11772
11939
  const steps = readAppStoreSteps(indexBytes, sigBytes, this.nowS(), heldKey, this.checkedRevocations);
11773
11940
  const pause = pacer(REVOCATIONS_SLICE_MS);
11774
11941
  for (;;) {
@@ -11871,7 +12038,10 @@ var Apps = class {
11871
12038
  this.previewedSweep = previewed ? setTimeout(() => this.keepPreviewed(null), STAGED.ms) : null;
11872
12039
  this.previewed = previewed;
11873
12040
  }
11874
- /** Reads a store at a URL for the person to see before adding it. Nothing is stored: the checked index waits in memory for `addStore`. */
12041
+ /**
12042
+ * Reads a store at a URL for the person to see before adding it. Nothing is added: the checked index waits in memory
12043
+ * for `addStore`. Only another index under the held one's sequence is kept, on the held store (its proof).
12044
+ */
11875
12045
  async previewStore({ url }) {
11876
12046
  const at = this.storeUrl(url);
11877
12047
  this.keepPreviewed(null);
@@ -11885,6 +12055,16 @@ var Apps = class {
11885
12055
  at: this.now()
11886
12056
  });
11887
12057
  const held = await this.storeRecord(index.key);
12058
+ const other = !!held && !held.removed && !!held.index && appStoreDecision({
12059
+ key: held.key,
12060
+ sequence: held.index.sequence,
12061
+ digest: held.digest ?? ""
12062
+ }, {
12063
+ key: index.key,
12064
+ sequence: index.sequence,
12065
+ digest
12066
+ }) === "equivocation";
12067
+ if (other && held.equivocation?.digest !== digest) await this.putStore(this.withIndex(held, index, digest));
11888
12068
  return {
11889
12069
  url: at,
11890
12070
  key: index.key,
@@ -11896,16 +12076,21 @@ var Apps = class {
11896
12076
  expired: read.store.expired,
11897
12077
  apps: index.apps.length,
11898
12078
  ...index.description !== void 0 && { description: index.description },
11899
- ...held && !held.removed && { held: held.index ? { sequence: held.index.sequence } : {} }
12079
+ ...held && !held.removed && { held: held.index ? {
12080
+ sequence: held.index.sequence,
12081
+ ...other && { equivocation: true }
12082
+ } : {} }
11900
12083
  };
11901
12084
  }
11902
12085
  /**
11903
12086
  * Adds a store the person chose: read at its URL and pinned to its key (`key`, when given, is the key the person saw,
11904
12087
  * and another one is refused). A store already added under that key keeps the URL it is read from and takes only a newer
11905
12088
  * index: a copy of its signed index at another URL, the same one or an older one, never moves it there (it would be
11906
- * read only there from then on, frozen). The same index is nothing to do, and an older one is refused with the held
11907
- * store left as it was: a copy the person chose is not a read of the store, so it marks no problem on it. The index the
11908
- * preview just read at that URL, under that key, is taken as it is (only its expiry again), not downloaded again.
12089
+ * read only there from then on, frozen). A newer one's URL is read too while the store's own URL is behind it (a URL at
12090
+ * a commit always is), so that URL's later indexes still arrive. The same index is nothing to do, and an older one is
12091
+ * refused with the held store left as it was: a copy the person chose is not a read of the store, so it marks no problem
12092
+ * on it. The index the preview just read at that URL, under that key, is taken as it is (only its expiry again), not
12093
+ * downloaded again.
11909
12094
  */
11910
12095
  async addStore({ url, key }) {
11911
12096
  if (key !== void 0 && !isAppKey(key)) fail("store-key", "Not a store key");
@@ -11945,7 +12130,14 @@ var Apps = class {
11945
12130
  if (decision === "same") return this.summary(held);
11946
12131
  if (decision === "rollback") fail("rollback", `This store's index is older than the one you have (sequence ${held.index.sequence})`);
11947
12132
  }
11948
- const record = held && !held.removed ? held : {
12133
+ let record;
12134
+ if (held && !held.removed) {
12135
+ const { copyUrl: _c, ...own } = held;
12136
+ record = at === held.url ? own : {
12137
+ ...own,
12138
+ copyUrl: at
12139
+ };
12140
+ } else record = {
11949
12141
  key: index.key,
11950
12142
  url: at,
11951
12143
  addedAt: this.now(),
@@ -11986,15 +12178,19 @@ var Apps = class {
11986
12178
  ...rest,
11987
12179
  problem: "rollback"
11988
12180
  };
11989
- case "equivocation": return {
11990
- ...rest,
11991
- equivocation: {
12181
+ case "equivocation": {
12182
+ const was = rest.equivocation;
12183
+ const equivocation = was?.sequence === index.sequence && was.digest === digest ? was : {
11992
12184
  sequence: index.sequence,
11993
12185
  digest,
11994
12186
  at: this.now()
11995
- },
11996
- problem: "equivocation"
11997
- };
12187
+ };
12188
+ return {
12189
+ ...rest,
12190
+ equivocation,
12191
+ problem: "equivocation"
12192
+ };
12193
+ }
11998
12194
  default: return {
11999
12195
  ...rest,
12000
12196
  problem: "store-key"
@@ -12004,6 +12200,7 @@ var Apps = class {
12004
12200
  async removeStore({ key }) {
12005
12201
  const held = await this.storeRecord(key);
12006
12202
  if (!held) return;
12203
+ this.behindReads.delete(key);
12007
12204
  await this.keepStoreRevocations(held);
12008
12205
  const seen = held.index ? {
12009
12206
  sequence: held.index.sequence,
@@ -12017,40 +12214,87 @@ var Apps = class {
12017
12214
  removed: true,
12018
12215
  ...seen && { seen }
12019
12216
  });
12020
- for (const app of await this.installed()) {
12021
- if (app.store !== key) continue;
12022
- const { store: _s, ...unpinned } = app;
12023
- await this.putApp(unpinned);
12217
+ for (const app of await this.installed()) if (app.store === key) await this.unpinApp(app.ref, key);
12218
+ }
12219
+ /**
12220
+ * Unpins an app from a store removed, read and written in one transaction: the record as it is now, not one read
12221
+ * before (an uninstall, or the update check's write, meanwhile is not undone). Gone, or pinned elsewhere: nothing.
12222
+ */
12223
+ async unpinApp(ref, key) {
12224
+ const tx = (await openDb()).transaction(STORES$1.apps, "readwrite");
12225
+ const read = tx.objectStore(STORES$1.apps).get(ref);
12226
+ read.onsuccess = () => {
12227
+ const now = read.result;
12228
+ if (now?.store !== key) return;
12229
+ const { store: _s, ...unpinned } = now;
12230
+ tx.objectStore(STORES$1.apps).put(unpinned);
12231
+ };
12232
+ try {
12233
+ await done(tx);
12234
+ } finally {
12235
+ this.held.delete(ref);
12024
12236
  }
12025
12237
  }
12026
12238
  /** Reads one store again, or every store (the person opened the Apps page, or the update check). */
12027
12239
  async refreshStores({ key } = {}) {
12028
12240
  const stores = (await this.stores()).filter((s) => key === void 0 || s.key === key);
12029
12241
  if (key !== void 0 && !stores.length) fail("no-store", "No such store");
12242
+ const reads = pooled(stores, STORE_READ_PARALLEL, (s) => this.readStore(s));
12030
12243
  const out = [];
12031
- for (const s of stores) {
12032
- let read;
12033
- try {
12034
- read = await this.readStoreAt(s.url, s.key, s);
12035
- } catch (error) {
12036
- read = {
12037
- ok: false,
12038
- reason: error instanceof AppFetchError ? error.code : "network"
12039
- };
12040
- }
12244
+ for (const [i, s] of stores.entries()) {
12245
+ const { read, copy } = await reads[i];
12041
12246
  const now = await this.storeRecord(s.key);
12042
12247
  if (!now || now.removed) continue;
12043
- const next = read.ok ? this.withIndex(now, read.store.index, read.store.digest) : {
12248
+ let next = read.ok ? this.withIndex(now, read.store.index, read.store.digest) : {
12044
12249
  ...now,
12045
12250
  problem: read.reason
12046
12251
  };
12047
- if (now === s && next.index === s.index && next.digest === s.digest && next.problem === s.problem && next.equivocation === s.equivocation) (await this.records()).set(s.key, next);
12252
+ const fromCopy = copy?.ok ? this.withIndex(now, copy.store.index, copy.store.digest) : null;
12253
+ if (next.copyUrl !== void 0 && !next.problem) {
12254
+ const { copyUrl: _c, ...own } = next;
12255
+ next = own;
12256
+ } else if (fromCopy && fromCopy.problem !== "rollback" && next.problem !== "equivocation") next = fromCopy;
12257
+ if (now === s && next.index === s.index && next.digest === s.digest && next.problem === s.problem && next.equivocation === s.equivocation && next.copyUrl === s.copyUrl) (await this.records()).set(s.key, next);
12048
12258
  else await this.putStore(next);
12049
12259
  out.push(this.summary(next));
12050
12260
  }
12051
12261
  return out;
12052
12262
  }
12053
12263
  /**
12264
+ * One store's reads for `refreshStores`; never throws. Its own URL, and the copy its index was taken from (`copyUrl`)
12265
+ * when the own URL is behind it (or not answering). That copy is read beside the own URL when that URL was behind at
12266
+ * its last read (`behindReads`: one at a commit stays so), and stopped when it turns out not to be; otherwise only
12267
+ * once the own URL showed it.
12268
+ */
12269
+ async readStore(s) {
12270
+ const last = this.behindReads.get(s.key);
12271
+ const lastBehind = last?.url === s.url ? last : void 0;
12272
+ const unneeded = new AbortController();
12273
+ const readCopy = (at) => this.readStoreAt(at, s.key, s, void 0, unneeded.signal).catch(() => null);
12274
+ const early = s.copyUrl !== void 0 && lastBehind ? readCopy(s.copyUrl) : null;
12275
+ let read;
12276
+ try {
12277
+ read = await this.readStoreAt(s.url, s.key, s, lastBehind);
12278
+ } catch (error) {
12279
+ read = {
12280
+ ok: false,
12281
+ reason: error instanceof AppFetchError ? error.code : "network"
12282
+ };
12283
+ }
12284
+ const behind = !read.ok || !!this.withIndex(s, read.store.index, read.store.digest).problem;
12285
+ if (read.ok && behind) this.behindReads.set(s.key, {
12286
+ url: s.url,
12287
+ index: read.store.index,
12288
+ digest: read.store.digest
12289
+ });
12290
+ else this.behindReads.delete(s.key);
12291
+ if (!behind) unneeded.abort();
12292
+ return {
12293
+ read,
12294
+ copy: behind && s.copyUrl !== void 0 ? await (early ?? readCopy(s.copyUrl)) : null
12295
+ };
12296
+ }
12297
+ /**
12054
12298
  * Fetches an app and checks it, for the install screen: from a pasted URL, a store's listing (its URLs in order) or a
12055
12299
  * chat card's pointer. A card's `sequence` and digest must hold: the same app, and that version or a newer one. A
12056
12300
  * store's listing must hold exactly: the version it lists, by digest, so a URL that already holds a newer version the
@@ -12099,9 +12343,10 @@ var Apps = class {
12099
12343
  };
12100
12344
  } else fail("bad-source", "No app to fetch");
12101
12345
  if (!urls.length) fail("host", "This listing has no URL Ghostly reads from");
12346
+ const kept = expect?.digest !== void 0 ? this.staged.get(expect.digest) : void 0;
12102
12347
  let last = null;
12103
12348
  for (const url of urls) try {
12104
- const { bundle, bytes } = await this.fetchBundle(url);
12349
+ const { bundle, bytes } = kept && kept.from === url && this.now() - kept.at <= STAGED.ms ? kept : await this.fetchBundle(url);
12105
12350
  const version = versionOf(bundle.manifest, bundle.digest);
12106
12351
  if (expect) {
12107
12352
  if (version.ref !== expect.ref) fail("other-app", "The URL holds another app");
@@ -12125,7 +12370,14 @@ var Apps = class {
12125
12370
  async stage(bundle, bytes, from, fromStore, carried = false) {
12126
12371
  const { manifest, digest } = bundle;
12127
12372
  const version = versionOf(manifest, digest);
12128
- const revocations = carried ? [] : await this.readRevocations(version.ref, [from, ...manifest.sources ?? []]) ?? [];
12373
+ const read = carried ? [] : await this.readRevocations(version.ref, [from, ...manifest.sources ?? []]) ?? [];
12374
+ const stops = stopping([version], read);
12375
+ if (stops.length) {
12376
+ const tx = (await openDb()).transaction(STORES$1.settings, "readwrite");
12377
+ keepRevocations(tx.objectStore(STORES$1.settings), version.ref, stops);
12378
+ await done(tx);
12379
+ }
12380
+ const revocations = [...await this.keptRevocationsOf(version.ref), ...read];
12129
12381
  for (const [d, s] of this.staged) if (this.now() - s.at > STAGED.ms) this.staged.delete(d);
12130
12382
  this.staged.delete(digest);
12131
12383
  while (this.staged.size >= STAGED.max) this.staged.delete(this.staged.keys().next().value);
@@ -12176,9 +12428,17 @@ var Apps = class {
12176
12428
  const version = versionOf(manifest, digest);
12177
12429
  let wrote;
12178
12430
  try {
12431
+ let read = false;
12179
12432
  for (;;) {
12180
- const [installed, stores] = await Promise.all([this.app(version.ref), this.stores()]);
12181
- const run = this.runStatus(version, this.storeViews(stores), [...installed?.revocations ?? [], ...revocations]);
12433
+ const [installed, stores, kept] = await Promise.all([
12434
+ this.app(version.ref),
12435
+ this.stores(),
12436
+ this.keptRevocationsOf(version.ref)
12437
+ ]);
12438
+ if (read && !installed) fail("not-installed", "This app is not installed");
12439
+ read = installed !== void 0;
12440
+ const known = [...kept, ...revocations];
12441
+ const run = this.runStatus(version, this.storeViews(stores), [...installed?.revocations ?? [], ...known]);
12182
12442
  if (run.status === "revoked") fail("revoked", "Its publisher revoked this version");
12183
12443
  if (run.status === "removed") fail("removed", `Removed by ${run.by[0].name}: ${run.by[0].reason}`);
12184
12444
  const decision = installDecision(installed, version);
@@ -12210,7 +12470,7 @@ var Apps = class {
12210
12470
  return this.view(await this.app(version.ref), stores);
12211
12471
  }
12212
12472
  const kind = wrote = await this.writeBundle(digest, bytes);
12213
- const next = withRevocations(this.versionRecord(installed, bundle, kind, from, fromStore), revocations);
12473
+ const next = withRevocations(this.versionRecord(installed, bundle, kind, from, fromStore), known);
12214
12474
  if (!await this.putAppIfUnchanged(next, installed)) continue;
12215
12475
  if (!installed && this.builtIn(version.ref)) await this.keepBuiltIn(version.ref);
12216
12476
  if (installed && installed.digest !== digest) await this.removeBundle(installed.bytes, installed.digest);
@@ -12325,16 +12585,7 @@ var Apps = class {
12325
12585
  if (!apps.length) return [];
12326
12586
  await this.refreshStores();
12327
12587
  const stores = await this.stores();
12328
- const out = [];
12329
- let next = 0;
12330
- const worker = async () => {
12331
- while (next < apps.length) {
12332
- const i = next++;
12333
- out[i] = await this.checkApp(apps[i], stores);
12334
- }
12335
- };
12336
- await Promise.all(Array.from({ length: Math.min(APP_CHECK_PARALLEL, apps.length) }, worker));
12337
- return out.filter((r) => r !== null);
12588
+ return (await Promise.all(pooled(apps, APP_CHECK_PARALLEL, (app) => this.checkApp(app, stores).catch(() => null)))).filter((r) => r !== null);
12338
12589
  }
12339
12590
  /** One app's part of the update check (`checkNow`); null when it is not installed any more. */
12340
12591
  async checkApp(listed, stores) {
@@ -12715,10 +12966,12 @@ var Apps = class {
12715
12966
  const tx = (await openDb()).transaction([
12716
12967
  STORES$1.apps,
12717
12968
  STORES$1.appStorage,
12718
- ...builtIn ? [STORES$1.settings] : []
12969
+ STORES$1.settings
12719
12970
  ], "readwrite");
12720
12971
  this.uninstalls.set(ref, (this.uninstalls.get(ref) ?? 0) + 1);
12721
12972
  this.held.delete(ref);
12973
+ const record = tx.objectStore(STORES$1.apps).get(ref);
12974
+ record.onsuccess = () => keepRevocations(tx.objectStore(STORES$1.settings), ref, record.result?.revocations ?? []);
12722
12975
  tx.objectStore(STORES$1.apps).delete(ref);
12723
12976
  tx.objectStore(STORES$1.appStorage).delete(rowsOf(ref));
12724
12977
  if (builtIn) markBuiltIns(tx.objectStore(STORES$1.settings), (marks) => {
@@ -13260,7 +13513,7 @@ function parseDeviceRecord(value) {
13260
13513
  if (!optional(r.tombstone, bytes)) return bad("tombstone");
13261
13514
  if (r.secretOffer !== void 0) {
13262
13515
  const o = r.secretOffer;
13263
- if (!o || typeof o !== "object" || o.why !== "takeover" || !count(o.at, Number.MAX_SAFE_INTEGER) || !optional(o.device, text) || o.lost !== void 0 && o.lost !== true) return bad("secretOffer");
13516
+ if (!o || typeof o !== "object" || o.why !== "takeover" || !count(o.at, Number.MAX_SAFE_INTEGER) || !optional(o.key, bytes) || !optional(o.device, text) || o.lost !== void 0 && o.lost !== true) return bad("secretOffer");
13264
13517
  }
13265
13518
  if (r.push !== void 0 && !isPush(r.push)) return bad("push");
13266
13519
  if (r.ownSet !== void 0) {
@@ -13554,7 +13807,7 @@ var DeviceReadTimeout = class extends Error {
13554
13807
  this.name = "DeviceReadTimeout";
13555
13808
  }
13556
13809
  };
13557
- function within$1(work, ms, what) {
13810
+ function within$2(work, ms, what) {
13558
13811
  return new Promise((resolve, reject) => {
13559
13812
  const timer = setTimeout(() => reject(new DeviceReadTimeout(what)), ms);
13560
13813
  work.then((value) => {
@@ -13626,7 +13879,7 @@ async function devicesDbExists() {
13626
13879
  });
13627
13880
  };
13628
13881
  try {
13629
- return await within$1(probe(), DEVICE_READ_TIMINGS.existsMs, "The list of databases");
13882
+ return await within$2(probe(), DEVICE_READ_TIMINGS.existsMs, "The list of databases");
13630
13883
  } catch {
13631
13884
  return false;
13632
13885
  }
@@ -13643,7 +13896,7 @@ async function readLocal(profile) {
13643
13896
  request.onerror = () => reject(request.error);
13644
13897
  });
13645
13898
  };
13646
- const stored = await within$1(read(), DEVICE_READ_TIMINGS.readMs, "The device state database");
13899
+ const stored = await within$2(read(), DEVICE_READ_TIMINGS.readMs, "The device state database");
13647
13900
  return stored === void 0 ? null : parseDeviceRecord(stored);
13648
13901
  }
13649
13902
  /**
@@ -13689,7 +13942,7 @@ async function swapMany(writes) {
13689
13942
  var DeviceFileInvalid = class extends Error {};
13690
13943
  /** The file's record: null when it holds none. */
13691
13944
  async function readMirror(profile) {
13692
- const text = await within$1(mirror.read(profile), DEVICE_READ_TIMINGS.readMs, "The device state file");
13945
+ const text = await within$2(mirror.read(profile), DEVICE_READ_TIMINGS.readMs, "The device state file");
13693
13946
  if (text === null) return null;
13694
13947
  let filed;
13695
13948
  try {
@@ -14515,6 +14768,23 @@ function deviceSetOf(record) {
14515
14768
  name: slot.name
14516
14769
  });
14517
14770
  }
14771
+ /**
14772
+ * The slots of the first record of a turn this device raises (WISP 06 § Who may raise the turn): those of the newest
14773
+ * record of the set it knows. The read the raise acts on may return a record above the one it stored (a device added or
14774
+ * renamed since its last read); when that record still lists this device in its own slot, its slots are written, with
14775
+ * any device of the stored set in a slot that record leaves empty (within one `D` a slot is never emptied). Undefined:
14776
+ * the stored set is the newest. Written as stored, the set would drop the device added, which keeps `D` and is listed
14777
+ * nowhere, and undo the rename.
14778
+ */
14779
+ function newestSlots(held, read) {
14780
+ const news = read.record;
14781
+ if (!news || news.tombstone || read.result === "clone") return void 0;
14782
+ if (held.storedRecord && news.sequence <= held.storedRecord.sequence) return void 0;
14783
+ const listed = news.slots[held.ownSlot];
14784
+ if (!listed || !bytesEqual(listed.key, held.ownKey)) return void 0;
14785
+ const set = deviceSetOf(news);
14786
+ return set.map((slot, i) => slot ?? (held.record.deviceSet[i] && !set.some((s) => s?.key === held.record.deviceSet[i].key) ? held.record.deviceSet[i] : null));
14787
+ }
14518
14788
  var TurnKeeper = class {
14519
14789
  options;
14520
14790
  store;
@@ -14770,10 +15040,11 @@ var TurnKeeper = class {
14770
15040
  step: `${TAKEOVER}${prior}`,
14771
15041
  ...stopping ? { peer: stopping } : {}
14772
15042
  } });
15043
+ const slots = options.slots ?? newestSlots(held, read);
14773
15044
  try {
14774
15045
  await this.writeWith(held, read.conditions, {
14775
15046
  turn,
14776
- ...options.slots ? { slots: options.slots } : {}
15047
+ ...slots ? { slots } : {}
14777
15048
  }, true);
14778
15049
  } catch (error) {
14779
15050
  if (!held.wroteNow) held.record = await this.store.move(this.options.profile, prior, {
@@ -14827,10 +15098,12 @@ var TurnKeeper = class {
14827
15098
  return this.settle(held, await this.readWith(held), true);
14828
15099
  }
14829
15100
  if (!fresh) return this.settle(held, read, true);
15101
+ const slots = newestSlots(held, read);
14830
15102
  try {
14831
15103
  await this.writeWith(held, read.conditions, {
14832
15104
  turn,
14833
- release
15105
+ release,
15106
+ ...slots ? { slots } : {}
14834
15107
  }, true);
14835
15108
  } catch (error) {
14836
15109
  if (error instanceof TurnClosedError) return this.exhausted(held, "taking", read);
@@ -14988,7 +15261,7 @@ var TurnKeeper = class {
14988
15261
  tombstone: toBase64Url(read.payload),
14989
15262
  ...storedActiveListed(held.record, read.record) ? {} : { reenroll: true }
14990
15263
  } : {};
14991
- const stopped = won && held.record.handoff?.peer ? held.record.deviceSet.find((slot) => slot?.key === held.record.handoff.peer)?.name : void 0;
15264
+ const stopped = won && held.record.handoff?.peer ? held.record.deviceSet.find((slot) => slot?.key === held.record.handoff.peer) : void 0;
14992
15265
  held.record = await this.store.move(this.options.profile, state, {
14993
15266
  ...takeover ? { handoff: void 0 } : {},
14994
15267
  ...held.record.settle ? { settle: void 0 } : {},
@@ -15001,7 +15274,10 @@ var TurnKeeper = class {
15001
15274
  secretOffer: {
15002
15275
  why: "takeover",
15003
15276
  at: this.now(),
15004
- ...stopped ? { device: stopped } : {}
15277
+ ...stopped ? {
15278
+ key: stopped.key,
15279
+ device: stopped.name
15280
+ } : {}
15005
15281
  }
15006
15282
  } : {}
15007
15283
  });
@@ -16629,7 +16905,9 @@ function verifierStands(record, latest) {
16629
16905
  const stated = turnStatedVerifier(latest.instance);
16630
16906
  return !stated || bytesEqual(stated, turnVerifierMark(record.verifier));
16631
16907
  }
16632
- var sameName = (a, b) => a.normalize("NFC").trim().toLocaleLowerCase() === b.normalize("NFC").trim().toLocaleLowerCase();
16908
+ /** A name as it is seen and typed: nobody types a joiner, a variation selector or a filler, which draw nothing. */
16909
+ var typedName = (name) => name.normalize("NFC").replace(/\p{Default_Ignorable_Code_Point}/gu, "").trim().toLocaleLowerCase();
16910
+ var sameName = (a, b) => typedName(a) === typedName(b);
16633
16911
  /** One try at a time on this device, whoever asks: tries sent at once would all be checked against the same count. */
16634
16912
  var tries = Promise.resolve();
16635
16913
  function oneTry(work) {
@@ -17139,6 +17417,7 @@ function deviceSetView(record, links) {
17139
17417
  name: slot.name
17140
17418
  }] : [];
17141
17419
  });
17420
+ const stopped = record.secretOffer ? offeredDevice(record, record.secretOffer) : void 0;
17142
17421
  return {
17143
17422
  state: record.state,
17144
17423
  devices,
@@ -17146,7 +17425,10 @@ function deviceSetView(record, links) {
17146
17425
  ...enrollmentUnfinished(record) ? { unfinished: true } : {},
17147
17426
  ...due?.why === "unfinished-grant" ? { newSecretDue: true } : {},
17148
17427
  ...record.state === "active" && record.secretOffer ? { secretOffer: {
17149
- ...record.secretOffer.device ? { device: record.secretOffer.device } : {},
17428
+ ...stopped ? {
17429
+ key: stopped.key,
17430
+ device: stopped.name
17431
+ } : {},
17150
17432
  ...record.secretOffer.lost ? { lost: true } : {}
17151
17433
  } } : {},
17152
17434
  ...record.state === "active" && waiting.length ? { waiting } : {},
@@ -17160,6 +17442,16 @@ function deviceSetView(record, links) {
17160
17442
  };
17161
17443
  }
17162
17444
  /**
17445
+ * The device a takeover's offer is about, as the set lists it now: found by its key, never this device. An offer an older
17446
+ * build stored has only the name, which a rename there may have moved to another device: it is trusted only when the
17447
+ * set has one other device and the name is that device's.
17448
+ */
17449
+ function offeredDevice(record, offer) {
17450
+ const others = record.deviceSet.filter((slot, index) => !!slot && index !== record.ownSlot);
17451
+ if (offer.key) return others.find((slot) => slot.key === offer.key);
17452
+ return others.length === 1 && others[0].name === offer.device ? others[0] : void 0;
17453
+ }
17454
+ /**
17163
17455
  * What the handoff hears when the capabilities agreed on a device link change (WISP 06 § Frames): `handoff/1` agreed
17164
17456
  * (true) or no longer (false). Agreed again on a new session that replaced the open one (the other device dialled in
17165
17457
  * again), the data link never closed and nothing else says so: the old session ended and this one opened. A frame sent
@@ -18298,13 +18590,13 @@ var reportOf = (busy) => busy === null ? null : typeof busy === "string" ? { why
18298
18590
  */
18299
18591
  var wireWhy = (report) => report.why === "call" ? "call" : "handoff";
18300
18592
  var name = (record, key) => record.deviceSet.find((slot) => slot?.key === key)?.name ?? "";
18301
- var slotOf = (record, key) => record.deviceSet.findIndex((slot) => slot?.key === key);
18593
+ var slotOf$1 = (record, key) => record.deviceSet.findIndex((slot) => slot?.key === key);
18302
18594
  /**
18303
18595
  * The counts of the devices still in the set: a removed device cannot pull (`onRequest` refuses it), and one added again
18304
18596
  * has a new key, so the list stays within the set's size instead of growing to the record's cap of 16 and refusing every
18305
18597
  * write after it.
18306
18598
  */
18307
- var setAttempts = (record, attempts) => Object.fromEntries(Object.entries(attempts ?? {}).filter(([key]) => slotOf(record, key) >= 0));
18599
+ var setAttempts = (record, attempts) => Object.fromEntries(Object.entries(attempts ?? {}).filter(([key]) => slotOf$1(record, key) >= 0));
18308
18600
  /** One session of a handoff with the other device: its own X25519 key, the other's hello, and the stream key. */
18309
18601
  var Session = class {
18310
18602
  transcript;
@@ -18581,7 +18873,7 @@ var HandoffGiver = class {
18581
18873
  if (this.phase !== "idle" && this.phase !== "failed") throw new Error("handoff-busy: Another move is in progress.");
18582
18874
  const record = await this.ports.records.read();
18583
18875
  if (!record || record.state !== "active") throw new Error("handoff-refused: Only the active device moves the profile.");
18584
- if (slotOf(record, key) < 0) throw new Error("handoff-refused: That device is not one of this profile's.");
18876
+ if (slotOf$1(record, key) < 0) throw new Error("handoff-refused: That device is not one of this profile's.");
18585
18877
  const busy = reportOf(await this.ports.busy(this.takerFacts(key)));
18586
18878
  if (busy) throw new Error(`handoff-${busy.why}:${busy.wallet ? `${busy.wallet}:` : ""} This device cannot move the profile now.`);
18587
18879
  if (!this.ports.links.live(key)) {
@@ -18776,7 +19068,7 @@ var HandoffGiver = class {
18776
19068
  if (this.phase !== "idle" && this.phase !== "failed") busy("handoff");
18777
19069
  return;
18778
19070
  }
18779
- if (slotOf(record, from) < 0) return busy("refused", 0);
19071
+ if (slotOf$1(record, from) < 0) return busy("refused", 0);
18780
19072
  const pushed = this.phase === "offered" && from === this.peer && request.id === this.id;
18781
19073
  if (this.phase !== "idle" && this.phase !== "failed" && !pushed) return busy("handoff");
18782
19074
  const session = this.sessionFor(from);
@@ -19052,7 +19344,7 @@ var HandoffGiver = class {
19052
19344
  }
19053
19345
  const record = await this.ports.records.read();
19054
19346
  if (!record || record.state !== "releasing") return;
19055
- const fromSlot = record.ownSlot, toSlot = slotOf(record, from);
19347
+ const fromSlot = record.ownSlot, toSlot = slotOf$1(record, from);
19056
19348
  if (toSlot < 0) return;
19057
19349
  const signed = await signTurnRelease(this.ports.turnAddress, this.turn + 1, fromSlot, toSlot, fromBase64Url(from), h, (bytes) => this.ports.sign(bytes));
19058
19350
  const release = {
@@ -19325,7 +19617,6 @@ async function renameDevice(options) {
19325
19617
  if (!record || record.state !== "active") throw new RenameRefusal("state", "Only the active device renames a device.");
19326
19618
  const at = record.deviceSet.findIndex((slot) => slot?.key === options.key);
19327
19619
  if (at < 0) throw new RenameRefusal("device", "That device is not in this profile.");
19328
- const old = record.deviceSet[at].name;
19329
19620
  const slots = Array.from({ length: 4 }, (_, i) => {
19330
19621
  const slot = record.deviceSet[i] ?? null;
19331
19622
  return slot && i === at ? {
@@ -19333,14 +19624,7 @@ async function renameDevice(options) {
19333
19624
  name
19334
19625
  } : slot;
19335
19626
  });
19336
- const offer = record.secretOffer?.device === old ? { secretOffer: {
19337
- ...record.secretOffer,
19338
- device: name
19339
- } } : {};
19340
- await options.keeper.write(turn.conditions, {
19341
- slots,
19342
- patch: offer
19343
- });
19627
+ await options.keeper.write(turn.conditions, { slots });
19344
19628
  return true;
19345
19629
  }
19346
19630
  //#endregion
@@ -21159,7 +21443,7 @@ var RESEND_POLICY = {
21159
21443
  };
21160
21444
  /** How long one turn of an outbox may hold the next one back: a send that never returns must not stop the chat. */
21161
21445
  var TURN_MS = 3e4;
21162
- /** The most rows a new message's look reads one by one (`Outbox.look`). */
21446
+ /** The most rows a new message's look reads one by one (`Outbox.look`), where the store cannot read them in one go. */
21163
21447
  var KNOWN_ROWS = 16;
21164
21448
  /**
21165
21449
  * A text of mine, not handed to store-and-forward, and still to go: queued, or waiting for the chat to carry it. (A
@@ -21367,17 +21651,18 @@ var Outbox = class {
21367
21651
  * The rows a new message's look needs, itself among them: those this outbox holds, by id, where it knows them all.
21368
21652
  * A text sent before the last one's receipt came, or while one waits for an away contact, read the chat's whole
21369
21653
  * history on the page's thread (20,000 rows per send at 20,000 messages), and so did each of the texts a bot asked
21370
- * for at the same time. Past `KNOWN_ROWS`, the history costs less.
21654
+ * for at the same time. Read one by one, past `KNOWN_ROWS` the history costs less; read in one go (`getMany`), they
21655
+ * are never more than the history.
21371
21656
  */
21372
21657
  async look(id) {
21373
- if (!this.store.get || !this.known || this.waiting.size + this.receipts.size + this.onTheirWay.size > KNOWN_ROWS) return this.store.read();
21658
+ if (!this.store.get || !this.known || !this.store.getMany && this.waiting.size + this.receipts.size + this.onTheirWay.size > KNOWN_ROWS) return this.store.read();
21374
21659
  const ids = /* @__PURE__ */ new Set([
21375
21660
  ...id === void 0 ? [] : [id],
21376
21661
  ...this.waiting.keys(),
21377
21662
  ...this.receipts.keys(),
21378
21663
  ...this.onTheirWay.keys()
21379
21664
  ]);
21380
- return (await Promise.all([...ids].map((known) => this.store.get(known)))).filter((row) => !!row);
21665
+ return (this.store.getMany ? await this.store.getMany([...ids]) : await Promise.all([...ids].map((known) => this.store.get(known)))).filter((row) => !!row);
21381
21666
  }
21382
21667
  /**
21383
21668
  * What a look at the chat takes up comes from: the rows this outbox holds, by id, where it knows them all (`look`);
@@ -21600,7 +21885,7 @@ var Outbox = class {
21600
21885
  */
21601
21886
  async check(id) {
21602
21887
  if (this.stopped) return;
21603
- if (this.waiting.get(id)?.timer || this.receipts.has(id)) return;
21888
+ if (!this.waiting.has(id) || this.waiting.get(id)?.timer || this.receipts.has(id)) return;
21604
21889
  const messages = await this.store.read(), message = messages.find((m) => m.id === id);
21605
21890
  if (!message || !(toGo(message) || this.file(message))) {
21606
21891
  await this.attempt(id);
@@ -22557,6 +22842,201 @@ function faucetError(error) {
22557
22842
  return /* @__PURE__ */ new Error(`The faucet did not pay: ${message}`);
22558
22843
  }
22559
22844
  //#endregion
22845
+ //#region ../browser/src/engine/sealedRows.ts
22846
+ /**
22847
+ * Phase 1 of the encrypted profile (WISP 04, What is encrypted): the fields of the peer database that let someone act
22848
+ * as the person or spend, by store, as paths into the row. With the data key set they are written sealed (version 2,
22849
+ * bound to the store, the row's key and the path) and opened as they are read; without it, rows are written and read
22850
+ * as they always were. A field is sealed as its JSON, so an object (transport seeds, epoch secrets) is one field.
22851
+ */
22852
+ var FIELDS = {
22853
+ [STORES$1.links]: [
22854
+ "seedB64",
22855
+ "encKeyB64",
22856
+ "participationSeed",
22857
+ "transportSeeds",
22858
+ "inviteCode",
22859
+ "pairedPeerKey",
22860
+ "peerTrust.verifiedKey",
22861
+ "ratchetState"
22862
+ ],
22863
+ [STORES$1.groups]: [
22864
+ "invitation.seedB64",
22865
+ "entry.seedB64",
22866
+ "joining.seedB64",
22867
+ "state.seedB64",
22868
+ "state.secrets",
22869
+ "community.seedB64",
22870
+ "community.secrets",
22871
+ "community.entry.seedB64",
22872
+ "community.rv"
22873
+ ],
22874
+ [STORES$1.swaps]: ["swap", "token"],
22875
+ [STORES$1.melts]: ["secrets", "outputs"]
22876
+ };
22877
+ /** A group removed and invited again keeps the group it was (`previous`), with secrets of its own. */
22878
+ var NESTED = { [STORES$1.groups]: "previous" };
22879
+ /**
22880
+ * A proof's secret is its row's key (`keyPath: "secret"`), and a sealed value can't be one: a sealed proof is kept under
22881
+ * this hash of its secret, the secret itself sealed beside it. The hash, not the secret, can be found again inside a
22882
+ * transaction, where WebCrypto can't be waited for.
22883
+ */
22884
+ var proofKey = (secret) => bytesToHex(sha256(utf8ToBytes(`ghostly-proof/1\n${secret}`)));
22885
+ var SEALED_SECRET = "sealedSecret";
22886
+ var keyOf = (store, row) => String(store === STORES$1.melts ? row.quote : row.id);
22887
+ function read(row, path) {
22888
+ return path.split(".").reduce((at, part) => at && typeof at === "object" ? at[part] : void 0, row);
22889
+ }
22890
+ /** The row with `value` at `path`, copied along the way: the caller's row is never changed. */
22891
+ function written(row, [part, ...rest], value) {
22892
+ return {
22893
+ ...row,
22894
+ [part]: rest.length ? written(row[part], rest, value) : value
22895
+ };
22896
+ }
22897
+ /** Every phase 1 value of a row that is there, with its path. */
22898
+ function places(store, row, prefix = "") {
22899
+ const found = (FIELDS[store] ?? []).map((path) => ({
22900
+ path: prefix + path,
22901
+ value: read(row, path)
22902
+ })).filter(({ value }) => value !== void 0);
22903
+ const nested = NESTED[store] && row[NESTED[store]];
22904
+ return nested && typeof nested === "object" ? [...found, ...places(store, nested, `${prefix}${NESTED[store]}.`)] : found;
22905
+ }
22906
+ function sealWith(store, value, seal) {
22907
+ const row = value;
22908
+ if (store === STORES$1.proofs) {
22909
+ if (row[SEALED_SECRET] !== void 0) return value;
22910
+ const secret = String(row.secret), key = proofKey(secret);
22911
+ return {
22912
+ ...row,
22913
+ secret: key,
22914
+ [SEALED_SECRET]: seal(JSON.stringify(secret), {
22915
+ store,
22916
+ key,
22917
+ field: "secret"
22918
+ })
22919
+ };
22920
+ }
22921
+ const key = keyOf(store, row);
22922
+ let out = row;
22923
+ for (const { path, value: at } of places(store, row)) if (!isSealedField(at)) out = written(out, path.split("."), seal(JSON.stringify(at), {
22924
+ store,
22925
+ key,
22926
+ field: path
22927
+ }));
22928
+ return out;
22929
+ }
22930
+ var slotOf = (json, at) => [
22931
+ at.store,
22932
+ at.key,
22933
+ at.field,
22934
+ json
22935
+ ].join("\n");
22936
+ /**
22937
+ * Seals made ahead of a transaction, for `row` to use inside it: IndexedDB commits a transaction that waits for
22938
+ * anything else, WebCrypto included. Whether rows are sealed is fixed when this is made, so a key dropped meanwhile
22939
+ * makes a write fail, never go out in the clear.
22940
+ */
22941
+ var RowSeals = class RowSeals {
22942
+ /** Seals are made one batch after another, so writes that seal first are saved in the order they were asked for. */
22943
+ static turn = Promise.resolve();
22944
+ on = hasDataKey();
22945
+ ready = /* @__PURE__ */ new Map();
22946
+ /** What these rows (or the proofs of these secrets) hold, sealed now. */
22947
+ async prepare(store, rows) {
22948
+ if (!this.on) return this;
22949
+ const wanted = /* @__PURE__ */ new Map();
22950
+ for (const row of rows) sealWith(store, row, (json, at) => {
22951
+ wanted.set(slotOf(json, at), [json, at]);
22952
+ return {
22953
+ v: 2,
22954
+ iv: "",
22955
+ ct: ""
22956
+ };
22957
+ });
22958
+ const sealing = RowSeals.turn.then(async () => {
22959
+ for (const [slot, [json, at]] of wanted) if (!this.ready.has(slot)) this.ready.set(slot, await sealPlace(json, at));
22960
+ });
22961
+ RowSeals.turn = sealing.catch(() => {});
22962
+ await sealing;
22963
+ return this;
22964
+ }
22965
+ /** The row as it is written. Throws for a value not prepared: its transaction aborts, and nothing goes out in the clear. */
22966
+ row(store, row) {
22967
+ if (!this.on) return row;
22968
+ return sealWith(store, row, (json, at) => {
22969
+ const sealed = this.ready.get(slotOf(json, at));
22970
+ if (!sealed) throw new Error("A secret was not sealed before it was saved");
22971
+ return sealed;
22972
+ });
22973
+ }
22974
+ };
22975
+ async function sealRow(store, row) {
22976
+ return (await new RowSeals().prepare(store, [row])).row(store, row);
22977
+ }
22978
+ /**
22979
+ * The store as a transaction's work sees it: what it puts is sealed from `seals`, and a proof is found by its secret.
22980
+ * Without the data key, the store itself.
22981
+ */
22982
+ function sealedStore(store, seals) {
22983
+ if (!seals.on) return store;
22984
+ const proofs = store.name === STORES$1.proofs;
22985
+ return new Proxy(store, { get(target, name) {
22986
+ if (name === "put") return (row, ...key) => target.put(seals.row(target.name, row), ...key);
22987
+ if (proofs && name === "delete") return (secret) => {
22988
+ target.delete(secret);
22989
+ return target.delete(proofKey(secret));
22990
+ };
22991
+ if (proofs && name === "get") return (secret) => target.get(proofKey(secret));
22992
+ const value = Reflect.get(target, name, target);
22993
+ return typeof value === "function" ? value.bind(target) : value;
22994
+ } });
22995
+ }
22996
+ function unsealed() {
22997
+ if (!takesUnsealed()) throw new Error("A secret of this profile was not sealed with its key");
22998
+ }
22999
+ /** The row as the engine uses it: every sealed value opened, where it was. */
23000
+ async function openRow(store, value) {
23001
+ if (!hasDataKey() || !value) return value;
23002
+ const row = value;
23003
+ if (store === STORES$1.proofs) {
23004
+ const sealed = row[SEALED_SECRET];
23005
+ if (sealed === void 0) {
23006
+ unsealed();
23007
+ return value;
23008
+ }
23009
+ const key = String(row.secret), secret = JSON.parse(await openSecret(sealed, {
23010
+ store,
23011
+ key,
23012
+ field: "secret"
23013
+ }));
23014
+ if (proofKey(secret) !== key) throw new Error("A sealed field could not be opened: it was changed, or it belongs to another record");
23015
+ const { [SEALED_SECRET]: _sealed, ...rest } = row;
23016
+ return {
23017
+ ...rest,
23018
+ secret
23019
+ };
23020
+ }
23021
+ const key = keyOf(store, row);
23022
+ let out = row;
23023
+ for (const { path, value: at } of places(store, row)) {
23024
+ if (!isSealedField(at)) {
23025
+ unsealed();
23026
+ continue;
23027
+ }
23028
+ out = written(out, path.split("."), JSON.parse(await openSecret(at, {
23029
+ store,
23030
+ key,
23031
+ field: path
23032
+ })));
23033
+ }
23034
+ return out;
23035
+ }
23036
+ function openRows(store, rows) {
23037
+ return hasDataKey() ? Promise.all(rows.map((row) => openRow(store, row))) : Promise.resolve(rows);
23038
+ }
23039
+ //#endregion
22560
23040
  //#region ../browser/src/engine/db.ts
22561
23041
  /**
22562
23042
  * The newest `count` rows of an index range, newest first: one descending read where IndexedDB has it (the options
@@ -22582,6 +23062,34 @@ function newestMessages(index, query, count) {
22582
23062
  }
22583
23063
  /** A write that waits for no disk sync of its own (in a browser, the engine's default already; on Node, the CLI's store). */
22584
23064
  var RELAXED = { durability: "relaxed" };
23065
+ var CHANGED = Symbol("changed");
23066
+ /**
23067
+ * A chat's pinned key, for the transaction that checks and changes it, and the seals of the keys that change writes.
23068
+ * Sealed (the data key is set), it is opened before the transaction, and holds inside it only while the row still has
23069
+ * the sealed value that was opened: `CHANGED` otherwise.
23070
+ */
23071
+ async function pinnedKey(linkId, key) {
23072
+ const seals = new RowSeals();
23073
+ if (!seals.on) return {
23074
+ seals,
23075
+ pinned: (link) => link?.pairedPeerKey
23076
+ };
23077
+ const seen = await wrap((await store(STORES$1.links, "readonly")).get(linkId));
23078
+ const opened = await openRow(STORES$1.links, seen);
23079
+ await seals.prepare(STORES$1.links, [{
23080
+ id: linkId,
23081
+ pairedPeerKey: key,
23082
+ peerTrust: { verifiedKey: key }
23083
+ }, {
23084
+ id: linkId,
23085
+ peerTrust: { verifiedKey: opened?.pairedPeerKey }
23086
+ }]);
23087
+ const then = JSON.stringify(seen?.pairedPeerKey);
23088
+ return {
23089
+ seals,
23090
+ pinned: (link) => JSON.stringify(link?.pairedPeerKey) === then ? opened?.pairedPeerKey : CHANGED
23091
+ };
23092
+ }
22585
23093
  /**
22586
23094
  * Durable local state of the browser peer. Identity seeds live here the same
22587
23095
  * way Desktop keeps them in its WebView storage: local to this profile, never
@@ -22589,11 +23097,12 @@ var RELAXED = { durability: "relaxed" };
22589
23097
  */
22590
23098
  var db = {
22591
23099
  async getLinks() {
22592
- return wrap((await store(STORES$1.links, "readonly")).getAll());
23100
+ return openRows(STORES$1.links, await wrap((await store(STORES$1.links, "readonly")).getAll()));
22593
23101
  },
22594
23102
  async putLink(link) {
23103
+ const row = await sealRow(STORES$1.links, link);
22595
23104
  const tx = (await openDb()).transaction(STORES$1.links, "readwrite");
22596
- tx.objectStore(STORES$1.links).put(link);
23105
+ tx.objectStore(STORES$1.links).put(row);
22597
23106
  await new Promise((resolve, reject) => {
22598
23107
  tx.oncomplete = () => resolve();
22599
23108
  tx.onerror = tx.onabort = () => reject(tx.error ?? /* @__PURE__ */ new Error("Link storage failed"));
@@ -22601,6 +23110,10 @@ var db = {
22601
23110
  },
22602
23111
  /** `relaxed`: for what a power cut may cost (a round trip, a note made again later), no disk sync of its own. */
22603
23112
  async patchLink(linkId, patch, relaxed = false) {
23113
+ const sealed = await sealRow(STORES$1.links, {
23114
+ ...patch,
23115
+ id: linkId
23116
+ });
22604
23117
  const tx = (await openDb()).transaction(STORES$1.links, "readwrite", relaxed ? RELAXED : void 0);
22605
23118
  const links = tx.objectStore(STORES$1.links);
22606
23119
  const request = links.get(linkId);
@@ -22611,8 +23124,7 @@ var db = {
22611
23124
  }
22612
23125
  links.put({
22613
23126
  ...request.result,
22614
- ...patch,
22615
- id: linkId
23127
+ ...sealed
22616
23128
  });
22617
23129
  };
22618
23130
  await new Promise((resolve, reject) => {
@@ -22674,25 +23186,27 @@ var db = {
22674
23186
  return result;
22675
23187
  },
22676
23188
  async pinPeer(linkId, key, signedSignals = false) {
23189
+ const { seals, pinned } = await pinnedKey(linkId, key);
22677
23190
  const tx = (await openDb()).transaction(STORES$1.links, "readwrite");
22678
23191
  const links = tx.objectStore(STORES$1.links);
22679
23192
  const request = links.get(linkId);
22680
23193
  request.onsuccess = () => {
22681
23194
  const link = request.result;
22682
- if (!link?.participationSeed || link.pairedPeerKey && link.pairedPeerKey !== key) {
23195
+ const before = pinned(link);
23196
+ if (!link?.participationSeed || before === CHANGED || before && before !== key) {
22683
23197
  tx.abort();
22684
23198
  return;
22685
23199
  }
22686
- links.put({
23200
+ links.put(seals.row(STORES$1.links, {
22687
23201
  ...link,
22688
23202
  peerTrust: link.peerTrust ?? {
22689
23203
  version: 1,
22690
- verifiedKey: link.pairedPeerKey
23204
+ verifiedKey: before
22691
23205
  },
22692
23206
  pairedPeerKey: key,
22693
23207
  requireSignedSignals: link.requireSignedSignals || signedSignals,
22694
23208
  inviteCode: void 0
22695
- });
23209
+ }));
22696
23210
  };
22697
23211
  await new Promise((resolve, reject) => {
22698
23212
  tx.oncomplete = () => resolve();
@@ -22700,23 +23214,24 @@ var db = {
22700
23214
  });
22701
23215
  },
22702
23216
  async verifyPeer(linkId, key) {
23217
+ const { seals, pinned } = await pinnedKey(linkId, key);
22703
23218
  const tx = (await openDb()).transaction(STORES$1.links, "readwrite");
22704
23219
  const links = tx.objectStore(STORES$1.links);
22705
23220
  const request = links.get(linkId);
22706
23221
  request.onsuccess = () => {
22707
23222
  const link = request.result;
22708
- if (!link?.pairedPeerKey || link.pairedPeerKey !== key) {
23223
+ if (!link?.pairedPeerKey || pinned(link) !== key) {
22709
23224
  tx.abort();
22710
23225
  return;
22711
23226
  }
22712
- links.put({
23227
+ links.put(seals.row(STORES$1.links, {
22713
23228
  ...link,
22714
23229
  peerTrust: {
22715
23230
  version: 1,
22716
23231
  verifiedKey: key,
22717
23232
  verifiedAt: Date.now()
22718
23233
  }
22719
- });
23234
+ }));
22720
23235
  };
22721
23236
  await new Promise((resolve, reject) => {
22722
23237
  tx.oncomplete = () => resolve();
@@ -22924,10 +23439,11 @@ var db = {
22924
23439
  await committed((await store(STORES$1.messages, "readwrite")).delete([linkId, messageId]));
22925
23440
  },
22926
23441
  async getGroups() {
22927
- return wrap((await store(STORES$1.groups, "readonly")).getAll());
23442
+ return openRows(STORES$1.groups, await wrap((await store(STORES$1.groups, "readonly")).getAll()));
22928
23443
  },
22929
23444
  async putGroup(group) {
22930
- await committed((await store(STORES$1.groups, "readwrite")).put(group));
23445
+ const row = await sealRow(STORES$1.groups, group);
23446
+ await committed((await store(STORES$1.groups, "readwrite")).put(row));
22931
23447
  },
22932
23448
  /** The group and its history. */
22933
23449
  async deleteGroup(groupId) {
@@ -23837,6 +24353,16 @@ var MAX_PENDING_ENTRIES$1 = 8;
23837
24353
  var ENTRY_TIMEOUT_MS$1 = 18e4;
23838
24354
  var ENTRY_UNANSWERED_MS = 9e4;
23839
24355
  /**
24356
+ * Knock records are written by anyone with the link: filled again and again with keys that have no app behind them,
24357
+ * they take every entry session the door opens, each for `ENTRY_UNANSWERED_MS`, and nobody real gets in (8 at a time,
24358
+ * a lone admin's door gave 64 such keys their session in 12 minutes while a real joiner waited the whole time). The
24359
+ * admin is told once this many keys went unanswered within `UNANSWERED_WINDOW_MS` (about 3 minutes of that), and
24360
+ * offered a new link. A busy link stays well under: a joiner whose session never comes up closed its app within
24361
+ * seconds of opening the link and did not open it again.
24362
+ */
24363
+ var UNANSWERED_TELL = 16;
24364
+ var UNANSWERED_WINDOW_MS = 6e5;
24365
+ /**
23840
24366
  * Each attempt to let one joiner in belongs to one hub for this long (see `answerKnocks`): it opens
23841
24367
  * the entry session in the first `KNOCK_SLOT_OPEN_MS` and gives up after `ENTRY_UNANSWERED_MS`,
23842
24368
  * before the turn ends. A paired session over Pkarr can take the better part of a minute to come up.
@@ -24152,7 +24678,8 @@ var Communities = class {
24152
24678
  community: {
24153
24679
  hub: live.hub,
24154
24680
  hubs: hubs.length,
24155
- connected: [...edges.keys()].filter(ready).length
24681
+ connected: [...edges.keys()].filter(ready).length,
24682
+ ...s.isAdmin && live.unansweredTold && { unansweredKnocks: live.unanswered.size }
24156
24683
  },
24157
24684
  members: roster.map(([key, role]) => ({
24158
24685
  key,
@@ -24438,6 +24965,11 @@ var Communities = class {
24438
24965
  const s = this.require(groupId);
24439
24966
  if (!s.isAdmin) throw new Error("Only the admin can replace or turn off the group's link");
24440
24967
  await this.closeEntries(groupId);
24968
+ const live = this.live.get(groupId);
24969
+ if (live) {
24970
+ live.unanswered = void 0;
24971
+ live.unansweredTold = false;
24972
+ }
24441
24973
  const key = await s.replaceLink(off);
24442
24974
  return key ? encodeCommunityLink({
24443
24975
  g: groupId,
@@ -24728,13 +25260,23 @@ var Communities = class {
24728
25260
  for (const [key, since] of live.pendingEntries) {
24729
25261
  const linkId = this.host.entries(groupId).get(key), up = !!linkId && this.host.linkReady(linkId, 2);
24730
25262
  const elsewhere = rosterHas(s.roster, key) && since < this.addedAt(s, key) + this.timings.knockFallbackMs;
24731
- if (!up && (elsewhere || now - since > ENTRY_UNANSWERED_MS)) live.pendingEntries.delete(key);
24732
- else if (now - since > ENTRY_TIMEOUT_MS$1) {
25263
+ if (!up && (elsewhere || now - since > ENTRY_UNANSWERED_MS)) {
25264
+ live.pendingEntries.delete(key);
25265
+ if (!elsewhere) (live.unanswered ??= /* @__PURE__ */ new Map()).set(key, now);
25266
+ } else if (now - since > ENTRY_TIMEOUT_MS$1) {
24733
25267
  live.pendingEntries.delete(key);
24734
25268
  this.refused.set(key, now + REFUSED_FOR_MS$1);
24735
25269
  } else continue;
24736
25270
  if (linkId) await this.host.closeEdge(linkId);
24737
25271
  }
25272
+ if (live.unanswered) {
25273
+ for (const [key, at] of live.unanswered) if (now - at > UNANSWERED_WINDOW_MS) live.unanswered.delete(key);
25274
+ const tell = live.unanswered.size >= UNANSWERED_TELL;
25275
+ if (tell !== !!live.unansweredTold) {
25276
+ live.unansweredTold = tell;
25277
+ this.host.emit();
25278
+ }
25279
+ }
24738
25280
  if ((s.needsCatchUp || live.tipCheck?.upAt) && now - (live.lastCatchUp ?? 0) >= 5e3 || now - (live.lastCatchUp ?? 0) >= 3e4) {
24739
25281
  live.lastCatchUp = now;
24740
25282
  const ready = [...this.host.edges(groupId)].filter(([key, id]) => this.host.linkReady(id, 2) && !s.wasRemoved(key)).map(([key]) => key);
@@ -24948,7 +25490,7 @@ var Communities = class {
24948
25490
  ts: now,
24949
25491
  load: this.beaconLoad(groupId, live, now),
24950
25492
  since: live.hubSince || now
24951
- } : null, now, (key) => !this.gone(live, key));
25493
+ } : null, now, (key) => !this.gone(live, key), (key) => rosterHas(live.session.roster, key));
24952
25494
  const newest = newerHead(head, this.newestFrame(live), now);
24953
25495
  await this.host.publish(keys.identity, beaconRecords(keys, live.hubClocks.asWritten(hubs), newest), !back, live.hub && !back, back);
24954
25496
  live.beacon = hubs;
@@ -24961,12 +25503,14 @@ var Communities = class {
24961
25503
  }
24962
25504
  /**
24963
25505
  * The beacon's hubs, less those the chain took out: hubs are members. Someone removed while its app was closed lists
24964
- * itself there when it comes back, believing it is a member, until it is told (`wantFarewell`).
25506
+ * itself there when it comes back, believing it is a member, until it is told (`wantFarewell`). A key my roster does
25507
+ * not have is nobody's hub here either (anyone holding the rendezvous secret can write one in), though it stays in the
25508
+ * beacon I write: a member behind on the roster must not erase the newest hubs.
24965
25509
  */
24966
25510
  hubs(live) {
24967
25511
  const top = live.session.top, leaves = live.session.state.pendingLeaves, memo = live.hubsMemo;
24968
25512
  if (memo && memo.beacon === live.beacon && memo.top === top && memo.leaves === leaves) return memo.hubs;
24969
- const hubs = live.beacon.filter((h) => !this.gone(live, h.key));
25513
+ const hubs = live.beacon.filter((h) => !this.gone(live, h.key) && rosterHas(live.session.roster, h.key));
24970
25514
  live.hubsMemo = {
24971
25515
  beacon: live.beacon,
24972
25516
  top,
@@ -25667,7 +26211,8 @@ var Communities = class {
25667
26211
  return;
25668
26212
  }
25669
26213
  if (!await live.session.handle(peerKey, frame) || !live.hub) return;
25670
- for (const [key, id] of this.hearers(groupId, f)) if (key !== peerKey) this.sendTo(id, f);
26214
+ const out = live.session.passOn(f);
26215
+ for (const [key, id] of this.hearers(groupId, f)) if (key !== peerKey) this.sendTo(id, out);
25671
26216
  }
25672
26217
  peerIsHub(live, key) {
25673
26218
  return this.recentHub(live, key) && !live.members.has(key) && !live.session.wasRemoved(key);
@@ -25743,7 +26288,6 @@ var Communities = class {
25743
26288
  const file = m.file && this.files && !this.stored.get(id)?.removedIds?.includes(m.id) ? await this.files.announced(id, {
25744
26289
  id: m.id,
25745
26290
  sender: m.sender,
25746
- ts: m.timestamp,
25747
26291
  file: m.file
25748
26292
  }, session.myKey) : void 0;
25749
26293
  const placing = this.lineOrder.placing(MESSAGE_LINK$1(id), {
@@ -25765,7 +26309,7 @@ var Communities = class {
25765
26309
  ...m.card && { card: m.card },
25766
26310
  ...file && { file },
25767
26311
  ...m.frame && { frame: m.frame }
25768
- });
26312
+ }, m.live);
25769
26313
  placing(stored !== false);
25770
26314
  if (stored === false && this.stored.get(id)?.removedIds?.includes(m.id)) return false;
25771
26315
  const came = m.sender === session.myKey ? timestamp : cameAt(timestamp, stored, arrivalNow(this.now()));
@@ -25778,6 +26322,7 @@ var Communities = class {
25778
26322
  },
25779
26323
  app: (m) => this.deliver(id, () => m.frame.t === "group-have" ? this.files?.communityApp(id, m.sender, m.frame) : this.host.communityApp?.(id, m.sender, m.frame)),
25780
26324
  lasting: (m) => m.frame.t === "pin" && m.sender === session.admin ? "pin" : void 0,
26325
+ fleeting: (frame) => frame.t === GROUP_HAVE_FRAME,
25781
26326
  pair: (m) => this.deliver(id, () => this.host.communityPair?.(id, m.sender, m.payload)),
25782
26327
  changed: () => {
25783
26328
  this.membershipChanged(id);
@@ -26619,7 +27164,8 @@ function authorOf(frame) {
26619
27164
  switch (frame.t) {
26620
27165
  case "group-msg":
26621
27166
  case "group-edit": return frame.s;
26622
- case "group-bye": return frame.k;
27167
+ case "group-bye":
27168
+ case "group-name": return frame.k;
26623
27169
  case "group-commit": return frame.commit.by;
26624
27170
  case "group-meta": return frame.by;
26625
27171
  default: return;
@@ -27166,6 +27712,14 @@ var KNOCK_VERIFY_SPREAD_MS = 700;
27166
27712
  /** Entry sessions the admin runs at once; a joiner who does not finish in time is not answered again for a while. */
27167
27713
  var MAX_PENDING_ENTRIES = 4;
27168
27714
  var ENTRY_TIMEOUT_MS = 18e4;
27715
+ /**
27716
+ * A link whose entry sessions keep timing out with nobody ever on the other side lets nobody in: anyone holding it can
27717
+ * write the knock record with keys no app holds, fresh each time, and they take the `MAX_PENDING_ENTRIES` places a
27718
+ * joiner is answered in. This many such sessions within `JAMMED_WINDOW_MS` tell the admin (`GroupView.entryJammed`),
27719
+ * whose new link reaches none of them; joiners who knock and close their app are a few.
27720
+ */
27721
+ var JAMMED_ENTRIES = 8;
27722
+ var JAMMED_WINDOW_MS = 9e5;
27169
27723
  /** A joiner refused (its app cannot follow the group) is not answered again for this long. */
27170
27724
  var REFUSED_FOR_MS = 6e5;
27171
27725
  /**
@@ -27199,6 +27753,13 @@ var ENTRY_RELEASE_MS = 2e3;
27199
27753
  var REMOVED_LINGER_MS = 15e3;
27200
27754
  /** How long the tombstone of a group I left waits for the admin to hear it. */
27201
27755
  var LEFT_KEPT_MS = 6048e5;
27756
+ /**
27757
+ * A tombstone the role reached (a hand-over that crossed my leave) hands it on this long after: a leave its giver said
27758
+ * right after its `role` commit (an admin's leave does) is heard first, so the role does not go back to a leaver.
27759
+ */
27760
+ var LEFT_HAND_ON_MS = 1e3;
27761
+ /** The commits of my chain since my leave said to the admin my leave follows, before the leave (it may lack them). */
27762
+ var LEFT_COMMITS = 16;
27202
27763
  /** Admin side: how long a contact invited over its chat is waited for. After, it holds no place and may be invited again. */
27203
27764
  var INVITED_KEPT_MS = LEFT_KEPT_MS;
27204
27765
  /**
@@ -27214,6 +27775,8 @@ var ACCEPT_AGAINS = 5;
27214
27775
  var REWELCOME_MS = ACCEPT_AGAIN_MS / 2;
27215
27776
  /** Invitee side: the invitations one contact chat may have waiting here at a time. More are answered as declined. */
27216
27777
  var MAX_INVITATIONS_PER_CHAT = 4;
27778
+ /** Other groups kept beside one under its id (`StoredGroup.others`), at most; an invitation past them is declined. */
27779
+ var MAX_OTHER_GROUPS = 4;
27217
27780
  /** Invitee side, removed and invited again: the chat that let me into the group I kept, if it is its admin's. */
27218
27781
  var keptAdminChat = (kept) => {
27219
27782
  const admin = kept?.state && rosterAdmin(kept.state.chain[kept.state.chain.length - 1].m);
@@ -27325,6 +27888,10 @@ var Groups = class {
27325
27888
  reconciling = Promise.resolve();
27326
27889
  /** Admin side: joiners with an entry session open, per group: member key → since when. */
27327
27890
  pendingEntries = /* @__PURE__ */ new Map();
27891
+ /** Admin side: of those, the ones whose other side was seen, once and for as long as they are open, per group. */
27892
+ entriesSeen = /* @__PURE__ */ new Map();
27893
+ /** Admin side: when entry sessions nobody was ever on the other side of timed out, per group (`JAMMED_ENTRIES`). */
27894
+ unansweredEntries = /* @__PURE__ */ new Map();
27328
27895
  /** Admin side: member keys whose entry did not finish, not answered again until then. */
27329
27896
  refused = /* @__PURE__ */ new Map();
27330
27897
  /** Admin side: entry sessions of a member key that timed out in a row, and when the last did. */
@@ -27332,6 +27899,8 @@ var Groups = class {
27332
27899
  lastPoll = /* @__PURE__ */ new Map();
27333
27900
  /** Admin side: when a link nobody is using was last read. Those links share one `pollMs` between them, read in turn. */
27334
27901
  lastQuietPoll = 0;
27902
+ /** Admin side: until when the relays' budget holds back reads of a group's link (`pollKnocks`). */
27903
+ knocksHeldUntil = /* @__PURE__ */ new Map();
27335
27904
  /** Admin side: until when a group's link is looked at the warm pace. */
27336
27905
  warmUntil = /* @__PURE__ */ new Map();
27337
27906
  lastKnock = /* @__PURE__ */ new Map();
@@ -27355,6 +27924,8 @@ var Groups = class {
27355
27924
  lingering = /* @__PURE__ */ new Map();
27356
27925
  /** Joiner side: groups whose knock is published, for the stage the joiner is shown. */
27357
27926
  knocked = /* @__PURE__ */ new Set();
27927
+ /** Joiner side: groups whose knock record held others' fresh knocks when I last read it (`othersKnocked`). */
27928
+ othersKnocked = /* @__PURE__ */ new Set();
27358
27929
  /**
27359
27930
  * Per mesh group, the member each unreachable member's messages were asked of (in a sync): asked of one member at a
27360
27931
  * time, not of everyone whose edge opens, so a member coming back is not sent the same messages by every other.
@@ -27591,7 +28162,8 @@ var Groups = class {
27591
28162
  ...peerMessageAt(this.lastPeerMessageAt, group.id),
27592
28163
  ...mentionAt(this.lastMentionAt, group.id),
27593
28164
  invited: [...this.invited.get(group.id) ?? []],
27594
- memberLinks: Object.fromEntries(contacts.map(([key, linkId]) => [linkId, key]))
28165
+ memberLinks: Object.fromEntries(contacts.map(([key, linkId]) => [linkId, key])),
28166
+ ...group.others?.length ? { others: group.others.map((other) => this.otherView(other)) } : {}
27595
28167
  };
27596
28168
  if (!session) {
27597
28169
  const invitation = group.invitation;
@@ -27613,7 +28185,8 @@ var Groups = class {
27613
28185
  ...invitation.entry ? {
27614
28186
  viaLink: true,
27615
28187
  stage: this.joinStage(group),
27616
- ...this.gaveUp.has(group.id) && { unanswered: true }
28188
+ ...this.gaveUp.has(group.id) && { unanswered: true },
28189
+ ...this.othersKnocked.has(group.id) && { othersKnocked: true }
27617
28190
  } : {}
27618
28191
  }
27619
28192
  };
@@ -27635,6 +28208,7 @@ var Groups = class {
27635
28208
  myKey: session.myKey,
27636
28209
  isAdmin: session.isAdmin,
27637
28210
  ...entry ? { entryLink: encodeGroupEntryLink(entry.link) } : {},
28211
+ ...entry && (this.unansweredEntries.get(group.id)?.length ?? 0) >= JAMMED_ENTRIES ? { entryJammed: true } : {},
27638
28212
  ...session.picture ? { picture: session.picture } : {},
27639
28213
  canSend: session.status === "active" && session.readableEpochs.includes(session.epoch),
27640
28214
  ...onHubs ? { hubs: { hub: this.hubs.isHub(group.id) } } : {},
@@ -27657,6 +28231,15 @@ var Groups = class {
27657
28231
  })
27658
28232
  };
27659
28233
  }
28234
+ otherView(other) {
28235
+ if ("link" in other) return { link: other.link };
28236
+ return {
28237
+ linkId: other.linkId,
28238
+ contact: this.host.contactName(other.linkId) ?? "",
28239
+ name: groupName(other.name) ?? "",
28240
+ members: Math.min(Math.max(other.n, 0), GROUP_MEMBER_CAP.max)
28241
+ };
28242
+ }
27660
28243
  messages(groupId) {
27661
28244
  return this.store.getMessages(MESSAGE_LINK(groupId));
27662
28245
  }
@@ -27823,12 +28406,80 @@ var Groups = class {
27823
28406
  if (!group.previous) return this.forget(groupId);
27824
28407
  await this.dropInvitation(group, this.sayDecline(groupId, group.invitation.linkId));
27825
28408
  }
28409
+ /**
28410
+ * Another group under the id of one held (`StoredGroup.others`): kept beside it and shown, for the person to pick. One
28411
+ * per contact chat (said again, it replaces its own) and one link; past `MAX_OTHER_GROUPS` a contact's is declined, so
28412
+ * its inviter is told rather than left counting me as invited.
28413
+ */
28414
+ async noteOther(group, other) {
28415
+ const kept = (group.others ?? []).filter((o) => "link" in other ? !("link" in o) : !("linkId" in o) || o.linkId !== other.linkId);
28416
+ if (kept.length >= MAX_OTHER_GROUPS) {
28417
+ if ("linkId" in other) this.sayDecline(group.id, other.linkId);
28418
+ return;
28419
+ }
28420
+ group.others = [...kept, other];
28421
+ await this.store.putGroup(group);
28422
+ this.host.emit();
28423
+ }
28424
+ /** The others under a group's id go, each contact who invited told no (best effort: its invitation ages out otherwise). */
28425
+ declineOthers(group) {
28426
+ for (const other of group.others ?? []) if ("linkId" in other) this.sayDecline(group.id, other.linkId);
28427
+ delete group.others;
28428
+ }
28429
+ /** The group held under this id is the real one: the others that came under it go, their inviters told no. */
28430
+ async keepGroup(groupId) {
28431
+ const group = this.stored.get(groupId);
28432
+ if (!group?.others) return;
28433
+ this.declineOthers(group);
28434
+ await this.store.putGroup(group);
28435
+ this.host.emit();
28436
+ }
28437
+ /**
28438
+ * Another group under this id is the real one (`to`: its contact chat, or its link): the group held goes as Delete
28439
+ * takes it (left, or its invitation declined), the rest of the others are told no, and the one picked takes its place:
28440
+ * a contact's invitation waits for Accept, a link is joined.
28441
+ */
28442
+ async switchGroup(groupId, to) {
28443
+ const group = this.stored.get(groupId);
28444
+ const other = group?.others?.find((o) => "link" in o ? o.link === to : o.linkId === to);
28445
+ if (!group || !other) throw new Error("No other group under this id");
28446
+ const others = group.others;
28447
+ group.others = others.filter((o) => o !== other);
28448
+ try {
28449
+ await this.forget(groupId);
28450
+ } catch (error) {
28451
+ group.others = others;
28452
+ throw error;
28453
+ }
28454
+ if ("link" in other) {
28455
+ await this.joinByLink(other.link);
28456
+ return;
28457
+ }
28458
+ const declined = this.stored.get(groupId)?.declined;
28459
+ const invitation = {
28460
+ id: groupId,
28461
+ createdAt: Date.now(),
28462
+ invitation: {
28463
+ name: other.name,
28464
+ admin: other.admin,
28465
+ linkId: other.linkId,
28466
+ e: other.e,
28467
+ n: other.n,
28468
+ pieces: []
28469
+ },
28470
+ ...declined ? { declined } : {}
28471
+ };
28472
+ this.stored.set(groupId, invitation);
28473
+ await this.store.putGroup(invitation);
28474
+ this.host.emit();
28475
+ }
27826
28476
  /** An invitation goes from the list: declined here (`owed`: the answer, when it could not be sent), or taken back by who sent it. */
27827
28477
  async dropInvitation(group, owed) {
27828
28478
  const previous = group.previous;
27829
28479
  if (!previous) return this.forget(group.id, false);
27830
28480
  if (owed) previous.declined = owed;
27831
28481
  else if (previous.declined?.linkId === group.invitation?.linkId) delete previous.declined;
28482
+ if (group.others) previous.others = group.others;
27832
28483
  this.acceptSaid.delete(group.id);
27833
28484
  this.stored.set(group.id, previous);
27834
28485
  if (previous.state) this.attach(previous.state);
@@ -28010,6 +28661,26 @@ var Groups = class {
28010
28661
  });
28011
28662
  }
28012
28663
  /**
28664
+ * Whom the role goes on to from a member it reached while its leave was under way (WISP 902 § Admission and
28665
+ * departure, "A role that reaches a leave"): `by`, who handed it to me, while it stays; else the first other member
28666
+ * whose edge is up, else the first in the roster. Never one whose leave I heard, nor one I handed the role to
28667
+ * myself (an admin who left): with two leavers the role would go back and forth between them.
28668
+ */
28669
+ nextAdmin(groupId, session, by) {
28670
+ const heard = this.leavesHeard.get(groupId), handed = new Set(session.state.chain.filter((c) => c.k === "role" && c.by === session.myKey).map((c) => c.s));
28671
+ const eligible = session.others.filter((key) => !heard?.has(key) && !handed.has(key));
28672
+ if (by && eligible.includes(by)) return by;
28673
+ const edges = this.host.edges(groupId);
28674
+ return eligible.find((key) => {
28675
+ const edge = edges.get(key);
28676
+ return !!edge && this.host.linkReady(edge);
28677
+ }) ?? eligible[0];
28678
+ }
28679
+ /** Members whose leave reached my tombstone of their group: the role a hand-over gave me does not go on to them. */
28680
+ leavesHeard = /* @__PURE__ */ new Map();
28681
+ /** Tombstones the role reached, and when they hand it on (`LEFT_HAND_ON_MS`). */
28682
+ handOnAt = /* @__PURE__ */ new Map();
28683
+ /**
28013
28684
  * Leaves, and the group is gone from this device at once: its row, its history, its files and every
28014
28685
  * edge but the one to the admin, which stays until the admin's commit removing me comes back (or a
28015
28686
  * week passes), so a leave said while the admin was away still reaches it. An admin with other
@@ -28045,8 +28716,11 @@ var Groups = class {
28045
28716
  bye: bye ?? session.byeFrame()
28046
28717
  };
28047
28718
  delete group.entry;
28719
+ this.declineOthers(group);
28048
28720
  this.takeBack(groupId, group);
28049
28721
  this.pendingEntries.delete(groupId);
28722
+ this.entriesSeen.delete(groupId);
28723
+ this.unansweredEntries.delete(groupId);
28050
28724
  this.welcomed.delete(groupId);
28051
28725
  this.lingering.delete(groupId);
28052
28726
  dropMarks(this.marks, groupId);
@@ -28066,14 +28740,22 @@ var Groups = class {
28066
28740
  } catch {}
28067
28741
  }
28068
28742
  }
28069
- await session.leave();
28743
+ await session.leave(() => this.nextAdmin(groupId, session, session.top.k === "role" && session.top.s === session.myKey ? session.top.by : void 0));
28744
+ const holder = session.admin, handed = !next && session.top.k === "role" && session.top.by === session.myKey ? holder : void 0;
28745
+ if (holder && holder !== admin && holder !== session.myKey && group.left) {
28746
+ group.left = {
28747
+ ...group.left,
28748
+ admin: holder
28749
+ };
28750
+ await this.store.putGroup(group);
28751
+ }
28070
28752
  if (bye) for (const key of hubs) {
28071
28753
  const edge = this.host.edges(groupId).get(key);
28072
28754
  if (edge && this.host.linkReady(edge)) try {
28073
28755
  this.host.sendOnLink(edge, bye);
28074
28756
  } catch {}
28075
28757
  }
28076
- const contact = group.contacts?.[admin];
28758
+ const contact = group.contacts?.[group.left?.admin ?? admin];
28077
28759
  if (contact) try {
28078
28760
  this.host.sendOnLink(contact, {
28079
28761
  t: "group-leave",
@@ -28082,7 +28764,7 @@ var Groups = class {
28082
28764
  } catch {}
28083
28765
  this.reconcileEdges(groupId);
28084
28766
  this.host.emit();
28085
- return next;
28767
+ return next ?? handed;
28086
28768
  }
28087
28769
  /**
28088
28770
  * The signed leave of my old key the admin has still to hear (`StoredGroup.owedBye`): none once the old key is out of
@@ -28298,16 +28980,22 @@ var Groups = class {
28298
28980
  }
28299
28981
  const gone = this.stored.get(groupId), invitation = answer && gone?.invitation && !gone.invitation.entry && !gone.invitation.takenBack ? gone.invitation : void 0;
28300
28982
  const owed = invitation && this.sayDecline(groupId, invitation.linkId);
28983
+ if (gone) this.declineOthers(gone);
28301
28984
  this.sessions.delete(groupId);
28302
28985
  this.stored.delete(groupId);
28986
+ this.leavesHeard.delete(groupId);
28987
+ this.handOnAt.delete(groupId);
28303
28988
  this.takeBack(groupId);
28304
28989
  this.acceptSaid.delete(groupId);
28305
28990
  this.entryHosts.delete(groupId);
28306
28991
  this.lastRoster.delete(groupId);
28307
28992
  this.lastTold.delete(groupId);
28308
28993
  this.pendingEntries.delete(groupId);
28994
+ this.entriesSeen.delete(groupId);
28995
+ this.unansweredEntries.delete(groupId);
28309
28996
  this.framesKept.delete(groupId);
28310
28997
  this.knocked.delete(groupId);
28998
+ this.othersKnocked.delete(groupId);
28311
28999
  this.knockCheckAt.delete(groupId);
28312
29000
  this.knockRewrites.delete(groupId);
28313
29001
  this.knockingSince.delete(groupId);
@@ -28368,6 +29056,7 @@ var Groups = class {
28368
29056
  };
28369
29057
  await this.store.putGroup(group);
28370
29058
  this.lastPoll.delete(groupId);
29059
+ this.knocksHeldUntil.delete(groupId);
28371
29060
  }
28372
29061
  this.warmUntil.set(groupId, Date.now() + this.timings.warmMs);
28373
29062
  this.host.emit();
@@ -28402,12 +29091,24 @@ var Groups = class {
28402
29091
  if (!link) throw new Error("This is not a link to a group");
28403
29092
  if (this.isCommunity(link.g)) throw new Error("This group is joined with its current link");
28404
29093
  const existing = this.stored.get(link.g);
28405
- if (existing?.state?.status === "active") return link.g;
29094
+ if (existing?.state?.status === "active") {
29095
+ if (!(this.sessions.get(link.g)?.isAdmin && this.entryOf(existing)?.link.host === link.host)) await this.noteOther(existing, {
29096
+ at: Date.now(),
29097
+ link: encodeGroupEntryLink(link)
29098
+ });
29099
+ return link.g;
29100
+ }
28406
29101
  if (existing?.invitation?.entry === link.host) {
28407
29102
  if (!existing.state) await this.knockAgain(existing);
28408
29103
  return link.g;
28409
29104
  }
28410
- if (existing?.invitation?.seedB64 && !existing.invitation.entry) throw new Error("You are already joining this group");
29105
+ if (existing?.invitation && !existing.invitation.entry && !existing.invitation.takenBack) {
29106
+ await this.noteOther(existing, {
29107
+ at: Date.now(),
29108
+ link: encodeGroupEntryLink(link)
29109
+ });
29110
+ return link.g;
29111
+ }
28411
29112
  if (existing?.invitation && !existing.invitation.entry) throw new Error("You have an invitation to this group. Answer it first.");
28412
29113
  if (existing?.state && !existing.left) throw new Error("You are out of this group and its history is still here. Delete it from this device to join with a link.");
28413
29114
  const owedBye = existing?.left?.bye ?? existing?.owedBye, declined = existing?.declined;
@@ -28447,7 +29148,12 @@ var Groups = class {
28447
29148
  const quiet = [];
28448
29149
  for (const group of [...this.stored.values()]) {
28449
29150
  if (group.left) {
28450
- if (now - group.left.at > LEFT_KEPT_MS) await this.forget(group.id);
29151
+ if (now - group.left.at > LEFT_KEPT_MS) {
29152
+ await this.forget(group.id);
29153
+ continue;
29154
+ }
29155
+ const session = this.sessions.get(group.id);
29156
+ if (session?.status === "left" && session.admin === session.myKey && now >= (this.handOnAt.get(group.id) ?? 0)) await this.handOn(group.id);
28451
29157
  continue;
28452
29158
  }
28453
29159
  if (group.declined) {
@@ -28485,9 +29191,11 @@ var Groups = class {
28485
29191
  await this.disableLink(group.id);
28486
29192
  continue;
28487
29193
  }
28488
- const pending = this.pendingEntries.get(group.id);
29194
+ const pending = this.pendingEntries.get(group.id), seen = this.seenEntries(group.id);
29195
+ let unanswered = 0;
28489
29196
  for (const [key, since] of pending ?? []) if (now - since > ENTRY_TIMEOUT_MS) {
28490
29197
  pending.delete(key);
29198
+ if (!seen.delete(key)) unanswered++;
28491
29199
  const timeouts = (this.entryTimeouts.get(key)?.count ?? 0) + 1;
28492
29200
  this.entryTimeouts.set(key, {
28493
29201
  count: timeouts,
@@ -28497,23 +29205,22 @@ var Groups = class {
28497
29205
  const linkId = this.host.entries(group.id).get(key);
28498
29206
  if (linkId) await this.host.closeEdge(linkId);
28499
29207
  }
29208
+ this.noteUnanswered(group.id, now, unanswered);
28500
29209
  const busy = (pending?.size ?? 0) >= MAX_PENDING_ENTRIES || session.roster.length + (pending?.size ?? 0) >= GROUP_MEMBER_CAP.max;
28501
29210
  const since = now - (this.lastPoll.get(group.id) ?? 0);
28502
29211
  if (busy) continue;
29212
+ const held = this.knocksHeldUntil.get(group.id);
29213
+ if (held !== void 0 && now < held) continue;
28503
29214
  if (now >= (this.warmUntil.get(group.id) ?? 0)) {
28504
- if (since >= this.timings.pollMs) quiet.push(group.id);
28505
- } else if (since >= this.timings.warmPollMs) {
28506
- this.lastPoll.set(group.id, now);
28507
- await this.answerKnocks(group, session, now).catch(() => {});
28508
- }
29215
+ if (since >= this.timings.pollMs || held !== void 0) quiet.push(group.id);
29216
+ } else if (since >= this.timings.warmPollMs || held !== void 0) await this.pollKnocks(group, session, now);
28509
29217
  }
28510
29218
  if (quiet.length && now - this.lastQuietPoll >= this.timings.pollMs) {
28511
29219
  const groupId = quiet.reduce((a, b) => (this.lastPoll.get(b) ?? 0) < (this.lastPoll.get(a) ?? 0) ? b : a);
28512
29220
  const group = this.stored.get(groupId), session = this.sessions.get(groupId);
28513
29221
  if (group?.entry && !group.left && session?.isAdmin) {
28514
29222
  this.lastQuietPoll = now;
28515
- this.lastPoll.set(groupId, now);
28516
- await this.answerKnocks(group, session, now).catch(() => {});
29223
+ await this.pollKnocks(group, session, now);
28517
29224
  }
28518
29225
  }
28519
29226
  for (const [key, until] of this.refused) if (until <= now) this.refused.delete(key);
@@ -28686,6 +29393,8 @@ var Groups = class {
28686
29393
  }
28687
29394
  async closeEntries(groupId) {
28688
29395
  this.pendingEntries.delete(groupId);
29396
+ this.entriesSeen.delete(groupId);
29397
+ this.unansweredEntries.delete(groupId);
28689
29398
  this.welcomed.delete(groupId);
28690
29399
  const invited = this.invited.get(groupId);
28691
29400
  for (const linkId of this.host.entries(groupId).values()) {
@@ -28707,6 +29416,7 @@ var Groups = class {
28707
29416
  this.knockingSince.set(group.id, now);
28708
29417
  this.lastKnock.delete(group.id);
28709
29418
  this.knocked.delete(group.id);
29419
+ this.othersKnocked.delete(group.id);
28710
29420
  this.knockRewrites.delete(group.id);
28711
29421
  await this.reopenEntry(group);
28712
29422
  this.host.emit();
@@ -28737,6 +29447,12 @@ var Groups = class {
28737
29447
  others: existing.length,
28738
29448
  ...mine ? { mine: now - mine.ts } : {}
28739
29449
  });
29450
+ const crowd = existing.some((k) => k.key !== key && now - k.ts < 3e4 + this.timings.knockMs);
29451
+ if (crowd !== this.othersKnocked.has(group.id)) {
29452
+ if (crowd) this.othersKnocked.add(group.id);
29453
+ else this.othersKnocked.delete(group.id);
29454
+ this.host.emit();
29455
+ }
28740
29456
  if (mine && now - mine.ts >= 0 && now - mine.ts < 3e4) {
28741
29457
  this.knockRewrites.delete(group.id);
28742
29458
  if (!this.knocked.has(group.id)) {
@@ -28758,13 +29474,45 @@ var Groups = class {
28758
29474
  this.host.emit();
28759
29475
  }
28760
29476
  }
29477
+ /**
29478
+ * Let in: my knock leaves the link's record. Left there until it aged out, the next joiner read it as someone still
29479
+ * waiting, and was told the admin's app may be busy letting them in. Once, in the background; if it fails, it ages out.
29480
+ */
29481
+ async unknock(link, seedB64) {
29482
+ const me = identityFromSeedB64(seedB64).pubKeyZ32, identity = knockIdentity(link);
29483
+ const knocks = readKnocks(link, await this.host.resolve(identity.pubKeyZ32, true) ?? []);
29484
+ if (!knocks.some((k) => k.key === me)) return;
29485
+ await this.host.publish(identity, knockRecords(link, knocks.filter((k) => k.key !== me)), true);
29486
+ }
29487
+ /**
29488
+ * Reads the link's knocks, and counts the read only if the relays answered it. One their budget held back answered
29489
+ * the record as last read: taken for a reading, the knock that came meanwhile waited for the next turn, and a burst's
29490
+ * tenth joiner waited ~40 s with the admin's app open. The link keeps its place and is read once the hold ends.
29491
+ */
29492
+ async pollKnocks(group, session, now) {
29493
+ const before = this.lastPoll.get(group.id);
29494
+ this.lastPoll.set(group.id, now);
29495
+ const held = await this.answerKnocks(group, session, now).catch(() => void 0);
29496
+ if (held === void 0) {
29497
+ this.knocksHeldUntil.delete(group.id);
29498
+ return;
29499
+ }
29500
+ this.knocksHeldUntil.set(group.id, now + held);
29501
+ if (before === void 0) this.lastPoll.delete(group.id);
29502
+ else this.lastPoll.set(group.id, before);
29503
+ }
29504
+ /** Answers the knocks in the link's record; how long the relays' budget still holds its reads back, if it held this one. */
28761
29505
  async answerKnocks(group, session, now) {
28762
29506
  const entry = this.entryOf(group);
28763
29507
  const started = Date.now();
28764
- const knocks = readKnocks(entry.link, await this.host.resolve(knockIdentity(entry.link).pubKeyZ32) ?? []);
29508
+ const knockKey = knockIdentity(entry.link).pubKeyZ32;
29509
+ const records = await this.host.resolve(knockKey).catch(() => null);
29510
+ const held = this.host.readHeldBackFor?.(knockKey);
29511
+ const knocks = readKnocks(entry.link, records ?? []);
28765
29512
  traceJoin(group.id, "knocks.read", {
28766
29513
  ms: Date.now() - started,
28767
- knocks: knocks.length
29514
+ knocks: knocks.length,
29515
+ ...held !== void 0 && { held }
28768
29516
  });
28769
29517
  let pending = this.pendingEntries.get(group.id);
28770
29518
  let ever;
@@ -28787,6 +29535,27 @@ var Groups = class {
28787
29535
  pending.delete(key);
28788
29536
  }
28789
29537
  }
29538
+ return held;
29539
+ }
29540
+ /** The admin's entry sessions of this group whose other side was seen, once and for as long as they are open. */
29541
+ seenEntries(groupId) {
29542
+ let seen = this.entriesSeen.get(groupId);
29543
+ if (!seen) this.entriesSeen.set(groupId, seen = /* @__PURE__ */ new Set());
29544
+ const pending = this.pendingEntries.get(groupId), entries = this.host.entries(groupId);
29545
+ for (const key of seen) if (!pending?.has(key)) seen.delete(key);
29546
+ for (const key of pending?.keys() ?? []) {
29547
+ const linkId = entries.get(key);
29548
+ if (linkId && (this.host.linkReady(linkId) || this.host.linkSeen?.(linkId))) seen.add(key);
29549
+ }
29550
+ return seen;
29551
+ }
29552
+ /** Entry sessions that timed out with nobody ever on the other side, kept for `JAMMED_WINDOW_MS`: the admin is told past `JAMMED_ENTRIES`. */
29553
+ noteUnanswered(groupId, now, count) {
29554
+ const before = this.unansweredEntries.get(groupId) ?? [];
29555
+ const times = [...before.filter((at) => now - at <= JAMMED_WINDOW_MS), ...Array(count).fill(now)];
29556
+ if (times.length) this.unansweredEntries.set(groupId, times);
29557
+ else this.unansweredEntries.delete(groupId);
29558
+ if (before.length >= JAMMED_ENTRIES !== times.length >= JAMMED_ENTRIES) this.host.emit();
28790
29559
  }
28791
29560
  /** The admin's entry session this link is, and whom it is pinned to. */
28792
29561
  hostEntry(groupId, linkId) {
@@ -28808,8 +29577,15 @@ var Groups = class {
28808
29577
  case "group-invite": {
28809
29578
  if (typeof frame.admin !== "string" || !MEMBER_KEY.test(frame.admin) || typeof frame.name !== "string") return;
28810
29579
  const existing = this.stored.get(g);
29580
+ const other = () => this.noteOther(existing, {
29581
+ at: Date.now(),
29582
+ linkId,
29583
+ name: groupName(frame.name) ?? "Group",
29584
+ admin: frame.admin,
29585
+ ...invitationClaims(frame)
29586
+ });
28811
29587
  if (existing?.invitation?.entry && !existing.state) {
28812
- if (existing.invitation.linkId !== linkId) return;
29588
+ if (existing.invitation.linkId !== linkId) return other();
28813
29589
  existing.invitation = {
28814
29590
  ...existing.invitation,
28815
29591
  name: groupName(frame.name) ?? "Group",
@@ -28832,11 +29608,14 @@ var Groups = class {
28832
29608
  t: "group-decline",
28833
29609
  g
28834
29610
  });
29611
+ const session = this.sessions.get(g);
29612
+ if (session && !rosterHas(session.roster, frame.admin)) await other();
28835
29613
  return;
28836
29614
  }
28837
- if (existing?.invitation?.seedB64 && (existing.invitation.linkId !== linkId || existing.invitation.admin !== frame.admin)) return;
29615
+ if (existing?.invitation?.seedB64 && existing.invitation.linkId !== linkId) return other();
29616
+ if (existing?.invitation?.seedB64 && existing.invitation.admin !== frame.admin) return;
28838
29617
  if (existing?.left && (existing.left.admin !== frame.admin || existing.contacts?.[existing.left.admin] !== linkId)) return;
28839
- if (existing?.invitation && !existing.state && existing.invitation.linkId !== linkId && !(existing.invitation.genesis && linkId === keptAdminChat(existing.previous)) && !existing.invitation.takenBack) return;
29618
+ if (existing?.invitation && !existing.state && existing.invitation.linkId !== linkId && !(existing.invitation.genesis && linkId === keptAdminChat(existing.previous)) && !existing.invitation.takenBack) return other();
28840
29619
  if ([...this.stored.values()].filter((x) => x.invitation && !x.invitation.takenBack).length >= 32) return;
28841
29620
  if (!(existing?.invitation && !existing.invitation.takenBack && existing.invitation.linkId === linkId) && [...this.stored.values()].filter((x) => x.invitation?.linkId === linkId && !x.invitation.takenBack).length >= MAX_INVITATIONS_PER_CHAT) {
28842
29621
  try {
@@ -28853,6 +29632,7 @@ var Groups = class {
28853
29632
  };
28854
29633
  const previous = existing?.state ? existing : existing?.previous;
28855
29634
  const genesis = existing?.state ? commitHash(existing.state.chain[0]) : existing?.invitation?.genesis;
29635
+ const others = existing?.others?.filter((o) => !("linkId" in o) || o.linkId !== linkId);
28856
29636
  const invitation = {
28857
29637
  id: g,
28858
29638
  createdAt: Date.now(),
@@ -28865,7 +29645,8 @@ var Groups = class {
28865
29645
  ...genesis ? { genesis } : {}
28866
29646
  },
28867
29647
  ...Object.keys(known).length ? { formerNames: known } : {},
28868
- ...previous ? { previous } : {}
29648
+ ...previous ? { previous } : {},
29649
+ ...others?.length ? { others } : {}
28869
29650
  };
28870
29651
  if (existing) {
28871
29652
  this.sessions.delete(g);
@@ -28954,6 +29735,12 @@ var Groups = class {
28954
29735
  await this.takeBackFrom(mine);
28955
29736
  return;
28956
29737
  }
29738
+ if (mine?.others?.some((o) => "linkId" in o && o.linkId === linkId)) {
29739
+ mine.others = mine.others.filter((o) => !("linkId" in o) || o.linkId !== linkId);
29740
+ if (!mine.others.length) delete mine.others;
29741
+ await this.store.putGroup(mine);
29742
+ this.host.emit();
29743
+ }
28957
29744
  const entryPeer = this.hostEntry(g, linkId);
28958
29745
  if (entryPeer) {
28959
29746
  this.pendingEntries.get(g)?.delete(entryPeer);
@@ -29012,7 +29799,8 @@ var Groups = class {
29012
29799
  state: joined.state,
29013
29800
  contacts: viaLink ? {} : { [group.invitation.admin]: linkId },
29014
29801
  ...group.owedBye ? { owedBye: group.owedBye } : {},
29015
- ...group.declined ? { declined: group.declined } : {}
29802
+ ...group.declined ? { declined: group.declined } : {},
29803
+ ...group.others ? { others: group.others } : {}
29016
29804
  };
29017
29805
  this.stored.set(g, member);
29018
29806
  this.acceptSaid.delete(g);
@@ -29029,8 +29817,13 @@ var Groups = class {
29029
29817
  await this.event(g, "joined", group.invitation.genesis ? "You joined again" : `You joined. ${GROUP_READ_NOTE}`, Date.now(), joined.state.chain.length - 1);
29030
29818
  if (viaLink) traceJoin(g, "welcome.received");
29031
29819
  if (viaLink) {
29820
+ if (this.lastKnock.has(g)) this.unknock({
29821
+ g,
29822
+ host: group.invitation.entry
29823
+ }, group.invitation.seedB64).catch(() => {});
29032
29824
  this.lastKnock.delete(g);
29033
29825
  this.knocked.delete(g);
29826
+ this.othersKnocked.delete(g);
29034
29827
  this.knockingSince.delete(g);
29035
29828
  if (this.host.linkReady(linkId, 5)) this.signals.keep(g, linkId);
29036
29829
  }
@@ -29086,6 +29879,7 @@ var Groups = class {
29086
29879
  if (this.isCommunity(groupId)) return this.communities.handleEdgeFrame(groupId, peerKey, frame);
29087
29880
  if (this.stored.get(groupId)?.left) {
29088
29881
  if (this.removesMe(groupId, peerKey, frame)) await this.leaveConfirmed(groupId);
29882
+ else await this.afterLeave(groupId, peerKey, frame);
29089
29883
  return;
29090
29884
  }
29091
29885
  const session = this.sessions.get(groupId);
@@ -29168,6 +29962,84 @@ var Groups = class {
29168
29962
  const session = this.sessions.get(groupId);
29169
29963
  return session?.status === "active" && this.hubs.enabled ? session.signReaction(reaction) : {};
29170
29964
  }
29965
+ /**
29966
+ * A group I left, and a frame from the admin my leave is owed to, or a hub carrying my leave (WISP 902 § Admission and
29967
+ * departure, "A role that reaches a leave"). A member's leave: the role does not go on to it. The next commit of my
29968
+ * chain, while it keeps me: kept, so my leave follows the role to whoever holds it now, and said to that admin; one
29969
+ * that makes me the admin goes on at the next tick (`handOn`). Taken in full while my leave is still under way: the
29970
+ * leave then hands the role on itself.
29971
+ */
29972
+ async afterLeave(groupId, from, raw) {
29973
+ const group = this.stored.get(groupId), left = group?.left, session = this.sessions.get(groupId);
29974
+ if (!group || !left || !session || from !== left.admin && !left.hubs?.includes(from) || !raw || typeof raw !== "object") return;
29975
+ const t = raw.t;
29976
+ if (t === "group-leave" && from !== session.myKey) {
29977
+ let heard = this.leavesHeard.get(groupId);
29978
+ if (!heard) this.leavesHeard.set(groupId, heard = /* @__PURE__ */ new Set());
29979
+ heard.add(from);
29980
+ return;
29981
+ }
29982
+ if (t !== "group-commit") return;
29983
+ if (session.status === "active") await session.handle(from, raw);
29984
+ if (session.status !== "left" || !await session.followAfterLeave(raw)) return;
29985
+ if (session.admin === session.myKey) {
29986
+ this.handOnAt.set(groupId, this.now() + LEFT_HAND_ON_MS);
29987
+ return;
29988
+ }
29989
+ await this.leaveFollows(groupId);
29990
+ }
29991
+ /** My tombstone's chain moved: my leave goes to the admin it names now, over our edge when it is up (and when it opens). */
29992
+ async leaveFollows(groupId) {
29993
+ const group = this.stored.get(groupId), left = group?.left, session = this.sessions.get(groupId);
29994
+ const admin = session?.admin;
29995
+ if (!group || !left || !session || !admin || admin === session.myKey) return;
29996
+ if (admin !== left.admin) {
29997
+ group.left = {
29998
+ ...left,
29999
+ admin
30000
+ };
30001
+ await this.store.putGroup(group);
30002
+ this.reconcileEdges(groupId);
30003
+ }
30004
+ const edge = this.host.edges(groupId).get(admin);
30005
+ if (edge && this.host.linkReady(edge)) try {
30006
+ this.sayLeave(groupId, session, group, edge);
30007
+ } catch {}
30008
+ const contact = group.contacts?.[admin];
30009
+ if (contact) try {
30010
+ this.host.sendOnLink(contact, {
30011
+ t: "group-leave",
30012
+ g: groupId
30013
+ });
30014
+ } catch {}
30015
+ }
30016
+ /**
30017
+ * My leave, to the admin it is owed to: first the commits of my chain since I left, which that admin may lack (the
30018
+ * role came to it from a leaver, whose edge with it is the only one up), then the leave.
30019
+ */
30020
+ sayLeave(groupId, session, group, linkId) {
30021
+ const since = group.left?.bye?.e ?? session.epoch;
30022
+ for (let e = Math.max(since + 1, session.epoch - LEFT_COMMITS + 1); e <= session.epoch; e++) this.host.sendOnLink(linkId, farewellCommit(groupId, session, e));
30023
+ this.host.sendOnLink(linkId, {
30024
+ t: "group-leave",
30025
+ g: groupId
30026
+ });
30027
+ }
30028
+ /** A tombstone the role reached: it goes on (`nextAdmin`), and my leave with it. */
30029
+ async handOn(groupId) {
30030
+ const session = this.sessions.get(groupId);
30031
+ if (!session || session.status !== "left" || session.admin !== session.myKey) {
30032
+ this.handOnAt.delete(groupId);
30033
+ return;
30034
+ }
30035
+ try {
30036
+ if (!await session.handOnAfterLeave((by) => this.nextAdmin(groupId, session, by))) return;
30037
+ } catch {
30038
+ return;
30039
+ }
30040
+ this.handOnAt.delete(groupId);
30041
+ await this.leaveFollows(groupId);
30042
+ }
29171
30043
  /** A validly signed commit, by the admin I told, that takes me out of the roster. */
29172
30044
  removesMe(groupId, from, raw) {
29173
30045
  const group = this.stored.get(groupId), session = this.sessions.get(groupId);
@@ -29184,8 +30056,10 @@ var Groups = class {
29184
30056
  }
29185
30057
  const left = this.stored.get(groupId)?.left;
29186
30058
  if (left) {
30059
+ const session = this.sessions.get(groupId), group = this.stored.get(groupId);
29187
30060
  if (peerKey === left.admin) try {
29188
- this.host.sendOnLink(linkId, {
30061
+ if (session) this.sayLeave(groupId, session, group, linkId);
30062
+ else this.host.sendOnLink(linkId, {
29189
30063
  t: "group-leave",
29190
30064
  g: groupId
29191
30065
  });
@@ -29217,6 +30091,12 @@ var Groups = class {
29217
30091
  } catch {
29218
30092
  return;
29219
30093
  }
30094
+ const name = session.nameFrame();
30095
+ if (name) try {
30096
+ this.host.sendOnLink(linkId, name);
30097
+ } catch {
30098
+ return;
30099
+ }
29220
30100
  if (peerKey === session.admin) {
29221
30101
  const owed = this.owedBye(group, session, this.now());
29222
30102
  try {
@@ -29639,6 +30519,7 @@ var Groups = class {
29639
30519
  for (const [groupId, session] of this.sessions) {
29640
30520
  if (session.status !== "active" || this.stored.get(groupId)?.left) continue;
29641
30521
  session.reseal().catch(() => {});
30522
+ session.sayName().catch(() => {});
29642
30523
  this.farewellsTick(groupId, session, now);
29643
30524
  this.heldSyncs(groupId, session, now);
29644
30525
  if (reconcile) {
@@ -29755,7 +30636,7 @@ var Groups = class {
29755
30636
  const file = m.file && this.files && !this.isRemoved(state.id, m.id) ? await this.files.announced(state.id, {
29756
30637
  id: m.id,
29757
30638
  sender: m.sender,
29758
- ts: m.timestamp,
30639
+ epoch: m.epoch,
29759
30640
  file: m.file
29760
30641
  }, session.myKey) : void 0;
29761
30642
  const message = {
@@ -29807,6 +30688,7 @@ var Groups = class {
29807
30688
  kept: async (id, frame) => {
29808
30689
  await this.host.keepFrame?.(MESSAGE_LINK(state.id), id, frame).catch(() => {});
29809
30690
  await this.frameKept(state.id, id, frame);
30691
+ this.files?.arrivedAgain(state.id, id, frame.e);
29810
30692
  },
29811
30693
  edit: (e) => this.host.groupEdit?.(state.id, e),
29812
30694
  changed: () => {
@@ -33253,6 +34135,8 @@ function amountlessUnderOptions(info) {
33253
34135
  }
33254
34136
  /** A Lightning payment can stay in flight for minutes or hours; the mint is asked again this often. */
33255
34137
  var MELT_POLL_MS = 3e4;
34138
+ /** Once its request can no longer land, a payment still pending is asked twice as late each time, up to this. */
34139
+ var MELT_SLOW_POLL_MS = 18e5;
33256
34140
  var MAX_AMOUNT = 1e6;
33257
34141
  /** How long "Get test coins" waits for the test mint to mark its invoice paid before saying the coins come later. */
33258
34142
  var TEST_COINS_WAIT_MS = 3e4;
@@ -33427,7 +34311,7 @@ var mintReason = (error) => (error instanceof Error ? error.message : String(err
33427
34311
  * that is down can hold a request for minutes; the next mint should get its turn well before that.
33428
34312
  */
33429
34313
  var MINT_TIMEOUT_MS = 12e3;
33430
- function within(ms, work, mint) {
34314
+ function within$1(ms, work, mint) {
33431
34315
  let timer;
33432
34316
  const late = new Promise((_, reject) => {
33433
34317
  timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`${new URL(mint).host} did not answer`)), ms);
@@ -33450,6 +34334,8 @@ var CashuWallet = class CashuWallet {
33450
34334
  /** Per quote the screen shows: until when (`watch`). */
33451
34335
  quoteWatched = /* @__PURE__ */ new Map();
33452
34336
  meltTimer = null;
34337
+ /** Per pending melt: when it is asked about next and the wait before that, in this run (a restart asks at once). */
34338
+ meltAsk = /* @__PURE__ */ new Map();
33453
34339
  restoredTimer = null;
33454
34340
  swapTimer = null;
33455
34341
  swapTimerAt = 0;
@@ -33539,7 +34425,7 @@ var CashuWallet = class CashuWallet {
33539
34425
  async readStored() {
33540
34426
  return {
33541
34427
  proofs: await this.allProofs(),
33542
- swaps: await wrap((await store(STORES$1.swaps, "readonly")).getAll())
34428
+ swaps: await this.readSwaps()
33543
34429
  };
33544
34430
  }
33545
34431
  /**
@@ -33561,7 +34447,7 @@ var CashuWallet = class CashuWallet {
33561
34447
  if (!proofs.length) return;
33562
34448
  const states = await (await this.wallet(mint)).checkProofsStates(proofs);
33563
34449
  if (states.length !== proofs.length) throw new Error("The mint answered for another number of proofs");
33564
- await transact([STORES$1.proofs], (stores) => {
34450
+ await this.sealedTransact([STORES$1.proofs], { [STORES$1.proofs]: proofs }, (stores) => {
33565
34451
  proofs.forEach((proof, i) => {
33566
34452
  const state = states[i]?.state;
33567
34453
  if (state === "SPENT") stores[STORES$1.proofs].delete(proof.secret);
@@ -33627,7 +34513,7 @@ var CashuWallet = class CashuWallet {
33627
34513
  for (const candidate of this.getMints(network)) try {
33628
34514
  created = {
33629
34515
  mint: candidate,
33630
- response: await within(MINT_TIMEOUT_MS, (await this.wallet(candidate)).createMintQuoteBolt11(amount, "Ghostly"), candidate)
34516
+ response: await within$1(MINT_TIMEOUT_MS, (await this.wallet(candidate)).createMintQuoteBolt11(amount, "Ghostly"), candidate)
33631
34517
  };
33632
34518
  break;
33633
34519
  } catch (error) {
@@ -33665,18 +34551,22 @@ var CashuWallet = class CashuWallet {
33665
34551
  /**
33666
34552
  * A payer says it paid this invoice of ours (a contact's app, once its payment went through). A held quote (a test
33667
34553
  * mint's, which reads paid by itself) is minted from now on; on any other mint the mint's own answer decides, as
33668
- * always. Returns whether the invoice is one of ours.
34554
+ * always. Returns whether the invoice is one of ours. `said` false: the payer spoke of another invoice, so this one is
34555
+ * only asked about, and a held one stays held. Only this invoice is asked about now: the others keep their pace.
33669
34556
  */
33670
- async vouch(invoice) {
34557
+ async vouch(invoice, said = true) {
33671
34558
  const wanted = invoice.trim().toLowerCase();
33672
- const quote = (await wrap((await store(STORES$1.quotes, "readonly")).getAll())).find((q) => q.invoice.toLowerCase() === wanted);
34559
+ let quote = (await wrap((await store(STORES$1.quotes, "readonly")).getAll())).find((q) => q.invoice.toLowerCase() === wanted);
33673
34560
  if (!quote) return false;
33674
- if (quote.held) await committed((await store(STORES$1.quotes, "readwrite")).put({
33675
- ...quote,
33676
- held: void 0
33677
- }));
34561
+ if (quote.held && said) {
34562
+ quote = {
34563
+ ...quote,
34564
+ held: void 0
34565
+ };
34566
+ await committed((await store(STORES$1.quotes, "readwrite")).put(quote));
34567
+ }
33678
34568
  this.quoteWatched.set(quote.quote, Date.now() + INVOICE_PACE.watchMs);
33679
- await this.pollQuotes(true);
34569
+ if (!(await this.settleQuotes([quote])).length && !quote.held && !quote.issuedUnclaimed) this.scheduleQuotes(this.nextAsk(quote, Date.now()));
33680
34570
  return true;
33681
34571
  }
33682
34572
  /** True while an invoice of ours waits for a payer's word (see `vouch`): whatever its mint says, it is not paid. */
@@ -33692,7 +34582,7 @@ var CashuWallet = class CashuWallet {
33692
34582
  assertAmount(amount);
33693
34583
  const mint = this.getMints(network).find(paysItsOwnInvoices);
33694
34584
  if (!mint) throw new Error("This wallet has no test mint to ask for test coins");
33695
- const response = await within(MINT_TIMEOUT_MS, (await this.wallet(mint)).createMintQuoteBolt11(amount, "Ghostly test coins"), mint);
34585
+ const response = await within$1(MINT_TIMEOUT_MS, (await this.wallet(mint)).createMintQuoteBolt11(amount, "Ghostly test coins"), mint);
33696
34586
  const quote = {
33697
34587
  quote: response.quote,
33698
34588
  mint,
@@ -33846,11 +34736,11 @@ var CashuWallet = class CashuWallet {
33846
34736
  ...walletTx(quote.mint, "lightning-in", minted, quote.amount - minted, quote.paymentId ? "Request paid over Lightning" : quote.testCoins ? TEST_COINS_NOTE : void 0),
33847
34737
  quote: quote.quote
33848
34738
  };
33849
- await transact([
34739
+ await this.sealedTransact([
33850
34740
  STORES$1.proofs,
33851
34741
  STORES$1.walletTx,
33852
34742
  STORES$1.quotes
33853
- ], (stores) => {
34743
+ ], { [STORES$1.proofs]: proofs }, (stores) => {
33854
34744
  for (const p of proofs) stores[STORES$1.proofs].put(toStored(quote.mint, p));
33855
34745
  stores[STORES$1.walletTx].put(tx);
33856
34746
  stores[STORES$1.quotes].delete(quote.quote);
@@ -33901,12 +34791,12 @@ var CashuWallet = class CashuWallet {
33901
34791
  const spent = total(inputs) - sats(keep);
33902
34792
  const tx = walletTx(mint, "ecash-out", amount, spent - amount, note);
33903
34793
  const kept = outbox?.(token, mint);
33904
- await transact([
34794
+ await this.sealedTransact([
33905
34795
  STORES$1.proofs,
33906
34796
  STORES$1.walletTx,
33907
34797
  STORES$1.swaps,
33908
34798
  ...kept ? [STORES$1.payments] : []
33909
- ], (stores) => {
34799
+ ], { [STORES$1.proofs]: keep }, (stores) => {
33910
34800
  this.queueReplace(stores[STORES$1.proofs], mint, inputs, keep);
33911
34801
  stores[STORES$1.walletTx].put(tx);
33912
34802
  if (swap) stores[STORES$1.swaps].delete(swap.id);
@@ -33942,9 +34832,9 @@ var CashuWallet = class CashuWallet {
33942
34832
  return this.locked(prepared.mint, async () => {
33943
34833
  const preview = (await loadCashu()).deserializeSwapPreview(prepared.swap);
33944
34834
  if (prepared.mint !== review.provider || preview.amount.toNumber() !== review.amount || await reviewedCashuFee(preview) !== review.fee) throw new PaymentPreflightError("Cashu preview does not match review");
33945
- const tx = (await openDb()).transaction(STORES$1.proofs, "readwrite");
34835
+ const seals = new RowSeals(), tx = (await openDb()).transaction(STORES$1.proofs, "readwrite");
33946
34836
  await new Promise((resolve, reject) => {
33947
- const proofs = tx.objectStore(STORES$1.proofs);
34837
+ const proofs = sealedStore(tx.objectStore(STORES$1.proofs), seals);
33948
34838
  for (const input of preview.inputs) {
33949
34839
  const request = proofs.get(input.secret);
33950
34840
  request.onsuccess = () => {
@@ -34036,11 +34926,11 @@ var CashuWallet = class CashuWallet {
34036
34926
  requestId: review.requestId,
34037
34927
  target: review
34038
34928
  };
34039
- await transact([
34929
+ await this.sealedTransact([
34040
34930
  STORES$1.proofs,
34041
34931
  STORES$1.payments,
34042
34932
  STORES$1.walletTx
34043
- ], (stores) => {
34933
+ ], { [STORES$1.proofs]: keep }, (stores) => {
34044
34934
  this.queueReplace(stores[STORES$1.proofs], prepared.mint, preview.inputs.map((p) => toStored(prepared.mint, p)), keep);
34045
34935
  stores[STORES$1.payments].put(record);
34046
34936
  stores[STORES$1.walletTx].put({
@@ -34102,7 +34992,7 @@ var CashuWallet = class CashuWallet {
34102
34992
  })));
34103
34993
  if (states.length !== preview.inputs.length) throw new Error("The mint answered for another number of proofs");
34104
34994
  const spent = new Set(preview.inputs.filter((_, i) => states[i]?.state === "SPENT").map((p) => p.secret));
34105
- await transact([STORES$1.proofs], (stores) => {
34995
+ await this.sealedTransact([STORES$1.proofs], {}, (stores) => {
34106
34996
  const proofs = stores[STORES$1.proofs];
34107
34997
  for (const input of preview.inputs) {
34108
34998
  const request = proofs.get(input.secret);
@@ -34129,7 +35019,7 @@ var CashuWallet = class CashuWallet {
34129
35019
  */
34130
35020
  async recheck(mint) {
34131
35021
  const free = (await this.allProofs()).filter((p) => p.mint === mint && !p.reserved && !p.unchecked);
34132
- if (free.length > 0) await transact([STORES$1.proofs], (stores) => {
35022
+ if (free.length > 0) await this.sealedTransact([STORES$1.proofs], { [STORES$1.proofs]: free }, (stores) => {
34133
35023
  for (const p of free) stores[STORES$1.proofs].put({
34134
35024
  ...p,
34135
35025
  unchecked: true
@@ -34141,7 +35031,7 @@ var CashuWallet = class CashuWallet {
34141
35031
  async releaseReviewedCashu(prepared) {
34142
35032
  const preview = (await loadCashu()).deserializeSwapPreview(prepared.swap);
34143
35033
  await this.locked(prepared.mint, async () => {
34144
- await transact([STORES$1.proofs], (stores) => {
35034
+ await this.sealedTransact([STORES$1.proofs], {}, (stores) => {
34145
35035
  const proofs = stores[STORES$1.proofs];
34146
35036
  for (const input of preview.inputs) {
34147
35037
  const request = proofs.get(input.secret);
@@ -34252,7 +35142,7 @@ var CashuWallet = class CashuWallet {
34252
35142
  token,
34253
35143
  ...records(preview.amount.toNumber())
34254
35144
  };
34255
- await committed((await store(STORES$1.swaps, "readwrite")).put(swap));
35145
+ await this.putSwap(swap);
34256
35146
  }
34257
35147
  const { keep } = await this.completeSwap(swap);
34258
35148
  const credited = sats(keep);
@@ -34312,7 +35202,10 @@ var CashuWallet = class CashuWallet {
34312
35202
  createdAt: Date.now()
34313
35203
  };
34314
35204
  const inputs = among(preview.inputs);
34315
- await transact([STORES$1.proofs, STORES$1.swaps], (stores) => {
35205
+ await this.sealedTransact([STORES$1.proofs, STORES$1.swaps], {
35206
+ [STORES$1.proofs]: inputs,
35207
+ [STORES$1.swaps]: [swap]
35208
+ }, (stores) => {
34316
35209
  for (const p of inputs) stores[STORES$1.proofs].put({
34317
35210
  ...p,
34318
35211
  reserved: true
@@ -34344,7 +35237,7 @@ var CashuWallet = class CashuWallet {
34344
35237
  ...swap,
34345
35238
  attemptEndedAt: Date.now()
34346
35239
  };
34347
- await (async () => committed((await store(STORES$1.swaps, "readwrite")).put(ended)))().catch(() => {});
35240
+ await this.putSwap(ended).catch(() => {});
34348
35241
  const outcome = await this.swapOutcome(ended, refused).catch(() => ({ state: "open" }));
34349
35242
  if (outcome.state === "done") return outcome;
34350
35243
  if (outcome.state === "never" && outcome.final) {
@@ -34435,12 +35328,12 @@ var CashuWallet = class CashuWallet {
34435
35328
  const inputs = (await this.allProofs()).filter((p) => p.mint === swap.mint && secrets.has(p.secret));
34436
35329
  const lost = swap.kind === "send" ? swapOf(swap).inputs.reduce((sum, p) => sum + Number(p.amount), 0) - sats(keep) - sats(send) : 0;
34437
35330
  let stored = false;
34438
- await transact([
35331
+ await this.sealedTransact([
34439
35332
  STORES$1.proofs,
34440
35333
  STORES$1.swaps,
34441
35334
  STORES$1.walletTx,
34442
35335
  ...swap.payment ? [STORES$1.payments] : []
34443
- ], (stores) => {
35336
+ ], { [STORES$1.proofs]: [...keep, ...send] }, (stores) => {
34444
35337
  const current = stores[STORES$1.swaps].get(swap.id);
34445
35338
  current.onsuccess = () => {
34446
35339
  const kept = current.result;
@@ -34475,7 +35368,10 @@ var CashuWallet = class CashuWallet {
34475
35368
  async dropSwap(swap, gone, watch = false) {
34476
35369
  const inputs = swap.kind === "send" && !swap.released ? await this.storedInputs(swap) : [];
34477
35370
  if (gone.size > 0 && inputs.length > 0) console.warn(`[wallet] ${gone.size} proofs of a swap at ${swap.mint} that never happened are spent`);
34478
- await transact([STORES$1.proofs, STORES$1.swaps], (stores) => {
35371
+ await this.sealedTransact([STORES$1.proofs, STORES$1.swaps], {
35372
+ [STORES$1.proofs]: inputs,
35373
+ [STORES$1.swaps]: [swap]
35374
+ }, (stores) => {
34479
35375
  for (const p of inputs) if (gone.has(p.secret)) stores[STORES$1.proofs].delete(p.secret);
34480
35376
  else {
34481
35377
  const { reserved: _released, ...free } = p;
@@ -34506,7 +35402,7 @@ var CashuWallet = class CashuWallet {
34506
35402
  return (await this.allProofs()).filter((p) => p.mint === swap.mint && p.reserved && secrets.has(p.secret));
34507
35403
  }
34508
35404
  async swapsAt(mint) {
34509
- return (await wrap((await store(STORES$1.swaps, "readonly")).getAll())).filter((s) => s.mint === mint);
35405
+ return (await this.readSwaps()).filter((s) => s.mint === mint);
34510
35406
  }
34511
35407
  /** Says what became of a swap to whoever follows it (the chat its payment is in), and waits for it to be taken in. */
34512
35408
  async tellSwap(swap, done) {
@@ -34541,7 +35437,7 @@ var CashuWallet = class CashuWallet {
34541
35437
  * pay the request, which another member may pay.
34542
35438
  */
34543
35439
  async redeemingFor(requestId) {
34544
- return (await wrap((await store(STORES$1.swaps, "readonly")).getAll())).some((s) => s.kind === "receive" && !s.released && s.payment?.requestId === requestId && !(s.stuck && Date.now() >= s.createdAt + SWAP_WATCH_MS));
35440
+ return (await this.readSwaps()).some((s) => s.kind === "receive" && !s.released && s.payment?.requestId === requestId && !(s.stuck && Date.now() >= s.createdAt + SWAP_WATCH_MS));
34545
35441
  }
34546
35442
  async pollSwaps(mints) {
34547
35443
  if (!mints) {
@@ -34549,13 +35445,13 @@ var CashuWallet = class CashuWallet {
34549
35445
  this.swapTimer = null;
34550
35446
  if (this.stopped) return;
34551
35447
  }
34552
- const open = (await wrap((await store(STORES$1.swaps, "readonly")).getAll())).filter((s) => !mints || mints.includes(s.mint));
35448
+ const open = (await this.readSwaps()).filter((s) => !mints || mints.includes(s.mint));
34553
35449
  let again = 0;
34554
35450
  const later = (ms) => {
34555
35451
  again = again ? Math.min(again, ms) : ms;
34556
35452
  };
34557
35453
  for (const { id, mint } of open) await this.locked(mint, async () => {
34558
- let swap = await wrap((await store(STORES$1.swaps, "readonly")).get(id));
35454
+ let swap = await openRow(STORES$1.swaps, await wrap((await store(STORES$1.swaps, "readonly")).get(id)));
34559
35455
  if (!swap) return;
34560
35456
  try {
34561
35457
  if (swap.finished) {
@@ -34572,7 +35468,7 @@ var CashuWallet = class CashuWallet {
34572
35468
  ...swap,
34573
35469
  attemptEndedAt: Date.now()
34574
35470
  };
34575
- await committed((await store(STORES$1.swaps, "readwrite")).put(swap));
35471
+ await this.putSwap(swap);
34576
35472
  }
34577
35473
  const outcome = await this.swapOutcome(swap);
34578
35474
  if (outcome.state === "open") {
@@ -34583,11 +35479,11 @@ var CashuWallet = class CashuWallet {
34583
35479
  if (outcome.slow) {
34584
35480
  const stuck = (swap.stuck ?? 0) + 1;
34585
35481
  const wait = stuck <= 6 ? SWAP_SLOW_POLL_MS : stuck <= 30 ? 36e5 : 864e5;
34586
- await committed((await store(STORES$1.swaps, "readwrite")).put({
35482
+ await this.putSwap({
34587
35483
  ...swap,
34588
35484
  stuck,
34589
35485
  askAt: Date.now() + wait
34590
- }));
35486
+ });
34591
35487
  if (stuck === 1) this.events.onChange();
34592
35488
  later(wait);
34593
35489
  } else if (outcome.idle && swap.kind === "receive" && !swap.released) {
@@ -34605,7 +35501,7 @@ var CashuWallet = class CashuWallet {
34605
35501
  ...swap,
34606
35502
  attemptEndedAt: Date.now()
34607
35503
  };
34608
- await committed((await store(STORES$1.swaps, "readwrite")).put(swap));
35504
+ await this.putSwap(swap);
34609
35505
  const refusal = mintRefused(error) ? await this.swapOutcome(swap, true).catch(() => void 0) : void 0;
34610
35506
  if (refusal?.state === "done") {
34611
35507
  if (await this.finishSwap(swap, refusal.keep, refusal.send, true)) {
@@ -34621,10 +35517,10 @@ var CashuWallet = class CashuWallet {
34621
35517
  }
34622
35518
  } else if (outcome.pending && swap.kind === "receive" && !swap.released && Date.now() >= swapOverdueAt(swap)) {
34623
35519
  if (Date.now() < swap.createdAt + SWAP_WATCH_MS) {
34624
- await committed((await store(STORES$1.swaps, "readwrite")).put({
35520
+ await this.putSwap({
34625
35521
  ...swap,
34626
35522
  askAt: Date.now() + SWAP_SLOW_POLL_MS
34627
- }));
35523
+ });
34628
35524
  later(SWAP_SLOW_POLL_MS);
34629
35525
  } else {
34630
35526
  await this.dropSwap(swap, /* @__PURE__ */ new Set());
@@ -34730,7 +35626,7 @@ var CashuWallet = class CashuWallet {
34730
35626
  const wallet = await this.wallet(mint);
34731
35627
  const { MeltChangeError, OutputData, getEncodedToken } = await loadCashu();
34732
35628
  const quote = await wallet.checkMeltQuoteBolt11(quoteId);
34733
- if ((await wrap((await store(STORES$1.melts, "readonly")).getAll())).some((m) => m.quote === quote.quote || m.request === quote.request)) throw new Error("This invoice is already being paid");
35629
+ if ((await this.readMelts()).some((m) => m.quote === quote.quote || m.request === quote.request)) throw new Error("This invoice is already being paid");
34734
35630
  const shown = this.shownQuotes.get(quoteId);
34735
35631
  const needed = quote.amount.toNumber() + quote.fee_reserve.toNumber();
34736
35632
  const proofs = await this.proofsAt(mint);
@@ -34745,7 +35641,7 @@ var CashuWallet = class CashuWallet {
34745
35641
  try {
34746
35642
  preview = await wallet.prepareMelt("bolt11", quote, send);
34747
35643
  } catch (error) {
34748
- await transact([STORES$1.proofs, STORES$1.swaps], (stores) => {
35644
+ await this.sealedTransact([STORES$1.proofs, STORES$1.swaps], { [STORES$1.proofs]: [...keep, ...send] }, (stores) => {
34749
35645
  this.queueReplace(stores[STORES$1.proofs], mint, inputs, [...keep, ...send]);
34750
35646
  if (swap) stores[STORES$1.swaps].delete(swap.id);
34751
35647
  });
@@ -34763,11 +35659,14 @@ var CashuWallet = class CashuWallet {
34763
35659
  paymentId,
34764
35660
  createdAt: Date.now()
34765
35661
  };
34766
- await transact([
35662
+ await this.sealedTransact([
34767
35663
  STORES$1.proofs,
34768
35664
  STORES$1.melts,
34769
35665
  STORES$1.swaps
34770
- ], (stores) => {
35666
+ ], {
35667
+ [STORES$1.proofs]: [...keep, ...send],
35668
+ [STORES$1.melts]: [melt]
35669
+ }, (stores) => {
34771
35670
  this.queueReplace(stores[STORES$1.proofs], mint, inputs, keep);
34772
35671
  for (const p of send) stores[STORES$1.proofs].put(toStored(mint, p, true));
34773
35672
  stores[STORES$1.melts].put(melt);
@@ -34799,27 +35698,44 @@ var CashuWallet = class CashuWallet {
34799
35698
  * its proofs, and `pollMelts` settles and reports it: an invoice with none never reached the mint's melt, or is done.
34800
35699
  */
34801
35700
  async meltInFlight(invoice) {
34802
- return (await wrap((await store(STORES$1.melts, "readonly")).getAll())).some((m) => m.request === invoice);
35701
+ return (await this.readMelts()).some((m) => m.request === invoice);
34803
35702
  }
34804
- /** Lightning payments left pending, asked about again until the mint settles each one. */
35703
+ /**
35704
+ * Lightning payments left pending, asked about again until the mint settles each one: every MELT_POLL_MS while its
35705
+ * request may still land, then each at its own pace, twice as late every time up to MELT_SLOW_POLL_MS.
35706
+ */
34805
35707
  async pollMelts() {
34806
35708
  if (this.meltTimer) clearTimeout(this.meltTimer);
34807
35709
  this.meltTimer = null;
34808
35710
  if (this.stopped) return;
34809
- const melts = await wrap((await store(STORES$1.melts, "readonly")).getAll());
34810
- for (const melt of melts) try {
34811
- const outcome = await this.locked(melt.mint, async () => {
34812
- const current = await wrap((await store(STORES$1.melts, "readonly")).get(melt.quote));
34813
- return current ? this.settleMelt(current) : null;
34814
- });
34815
- if (outcome === "paid" || outcome === "unpaid") {
34816
- this.takeFailedFee(melt.quote);
34817
- this.spentAway.delete(melt.quote);
34818
- this.events.onMeltResolved(melt, outcome === "paid");
34819
- this.events.onChange();
34820
- }
34821
- } catch {}
34822
- if (await wrap((await store(STORES$1.melts, "readonly")).count()) > 0 && !this.stopped) this.meltTimer = setTimeout(() => void this.pollMelts(), MELT_POLL_MS);
35711
+ const melts = await this.readMelts();
35712
+ for (const melt of melts) {
35713
+ const pace = this.meltAsk.get(melt.quote);
35714
+ if (pace && Date.now() < pace.at) continue;
35715
+ try {
35716
+ const outcome = await this.locked(melt.mint, async () => {
35717
+ const current = await openRow(STORES$1.melts, await wrap((await store(STORES$1.melts, "readonly")).get(melt.quote)));
35718
+ return current ? this.settleMelt(current) : null;
35719
+ });
35720
+ if (outcome === "paid" || outcome === "unpaid") {
35721
+ this.takeFailedFee(melt.quote);
35722
+ this.spentAway.delete(melt.quote);
35723
+ this.events.onMeltResolved(melt, outcome === "paid");
35724
+ this.events.onChange();
35725
+ }
35726
+ } catch {}
35727
+ const wait = Date.now() < meltOverdueAt(melt) ? MELT_POLL_MS : Math.min((pace?.wait ?? MELT_POLL_MS) * 2, MELT_SLOW_POLL_MS);
35728
+ this.meltAsk.set(melt.quote, {
35729
+ at: Date.now() + wait,
35730
+ wait
35731
+ });
35732
+ }
35733
+ const remaining = new Set((await this.readMelts()).map((m) => m.quote));
35734
+ for (const quote of this.meltAsk.keys()) if (!remaining.has(quote)) this.meltAsk.delete(quote);
35735
+ if (remaining.size === 0 || this.stopped) return;
35736
+ const next = Math.min(...[...remaining].map((quote) => this.meltAsk.get(quote)?.at ?? 0));
35737
+ if (this.meltTimer) clearTimeout(this.meltTimer);
35738
+ this.meltTimer = setTimeout(() => void this.pollMelts(), Math.max(0, next - Date.now()));
34823
35739
  }
34824
35740
  /**
34825
35741
  * Asks the mint where a recorded melt stands and books the answer. Paid: the reserved proofs are gone and
@@ -34853,11 +35769,11 @@ var CashuWallet = class CashuWallet {
34853
35769
  const spent = new Set(inputs.filter((_, i) => states[i]?.state === "SPENT").map((p) => p.secret));
34854
35770
  if (spent.size > 0) console.warn(`[wallet] melt ${melt.quote} is unpaid, yet ${spent.size} of its proofs are spent`);
34855
35771
  const lost = melt.outlay - inputs.reduce((sum, p) => sum + p.amount, 0);
34856
- await transact([
35772
+ await this.sealedTransact([
34857
35773
  STORES$1.proofs,
34858
35774
  STORES$1.melts,
34859
35775
  ...lost > 0 ? [STORES$1.walletTx] : []
34860
- ], (stores) => {
35776
+ ], { [STORES$1.proofs]: inputs }, (stores) => {
34861
35777
  for (const p of inputs) if (spent.has(p.secret)) stores[STORES$1.proofs].delete(p.secret);
34862
35778
  else stores[STORES$1.proofs].put({
34863
35779
  ...p,
@@ -34882,11 +35798,11 @@ var CashuWallet = class CashuWallet {
34882
35798
  /** The invoice is paid: the reserved proofs are spent, the change is ours, and the payment goes in the history. */
34883
35799
  async finishMelt(melt, change) {
34884
35800
  const tx = walletTx(melt.mint, "lightning-out", melt.amount, melt.outlay - sats(change) - melt.amount, melt.note);
34885
- await transact([
35801
+ await this.sealedTransact([
34886
35802
  STORES$1.proofs,
34887
35803
  STORES$1.melts,
34888
35804
  STORES$1.walletTx
34889
- ], (stores) => {
35805
+ ], { [STORES$1.proofs]: change }, (stores) => {
34890
35806
  for (const secret of melt.secrets) stores[STORES$1.proofs].delete(secret);
34891
35807
  for (const p of change) stores[STORES$1.proofs].put(toStored(melt.mint, p));
34892
35808
  stores[STORES$1.melts].delete(melt.quote);
@@ -34902,21 +35818,21 @@ var CashuWallet = class CashuWallet {
34902
35818
  async forget(mints, acceptLoss = false) {
34903
35819
  const at = new Set(mints);
34904
35820
  const inFlight = async () => {
34905
- if ((await wrap((await store(STORES$1.melts, "readonly")).getAll())).some((m) => at.has(m.mint))) throw new Error("A Lightning payment from this wallet is still in flight: wait for it to settle, then remove the wallet.");
35821
+ if ((await this.readMelts()).some((m) => at.has(m.mint))) throw new Error("A Lightning payment from this wallet is still in flight: wait for it to settle, then remove the wallet.");
34906
35822
  };
34907
35823
  await inFlight();
34908
35824
  await this.pollSwaps(mints).catch(() => {});
34909
35825
  await this.lockedAll(mints, async () => {
34910
35826
  await inFlight();
34911
- if ((await wrap((await store(STORES$1.swaps, "readonly")).getAll())).filter((s) => at.has(s.mint) && !s.released).length > 0 && !acceptLoss) throw new Error("An exchange of ecash with this wallet's mint is not finished yet: wait for the mint to answer, or confirm that what it would bring is lost to remove the wallet.");
35827
+ if ((await this.readSwaps()).filter((s) => at.has(s.mint) && !s.released).length > 0 && !acceptLoss) throw new Error("An exchange of ecash with this wallet's mint is not finished yet: wait for the mint to answer, or confirm that what it would bring is lost to remove the wallet.");
34912
35828
  const proofs = (await this.allProofs()).filter((p) => at.has(p.mint));
34913
35829
  const quotes = (await wrap((await store(STORES$1.quotes, "readonly")).getAll())).filter((q) => at.has(q.mint));
34914
- const swaps = (await wrap((await store(STORES$1.swaps, "readonly")).getAll())).filter((s) => at.has(s.mint));
34915
- await transact([
35830
+ const swaps = (await this.readSwaps()).filter((s) => at.has(s.mint));
35831
+ await this.sealedTransact([
34916
35832
  STORES$1.proofs,
34917
35833
  STORES$1.quotes,
34918
35834
  STORES$1.swaps
34919
- ], (stores) => {
35835
+ ], {}, (stores) => {
34920
35836
  for (const p of proofs) stores[STORES$1.proofs].delete(p.secret);
34921
35837
  for (const q of quotes) stores[STORES$1.quotes].delete(q.quote);
34922
35838
  for (const s of swaps) stores[STORES$1.swaps].delete(s.id);
@@ -34956,7 +35872,7 @@ var CashuWallet = class CashuWallet {
34956
35872
  if (!wallet) {
34957
35873
  wallet = (async () => {
34958
35874
  const instance = new (await (loadCashu())).Wallet(mint, { unit: UNIT$1 });
34959
- await within(MINT_TIMEOUT_MS, instance.loadMint(), mint);
35875
+ await within$1(MINT_TIMEOUT_MS, instance.loadMint(), mint);
34960
35876
  const info = instance.getMintInfo();
34961
35877
  if (info.isSupported(5).params.some(saysAmountlessBeside)) instance.loadMintFromCache(amountlessUnderOptions(info.cache), instance.keyChain.cache);
34962
35878
  return instance;
@@ -34989,7 +35905,28 @@ var CashuWallet = class CashuWallet {
34989
35905
  return [...new Set(mints)].sort().reduceRight((inner, mint) => () => this.locked(mint, inner), task)();
34990
35906
  }
34991
35907
  async allProofs() {
34992
- return wrap((await store(STORES$1.proofs, "readonly")).getAll());
35908
+ return openRows(STORES$1.proofs, await wrap((await store(STORES$1.proofs, "readonly")).getAll()));
35909
+ }
35910
+ async readSwaps() {
35911
+ return openRows(STORES$1.swaps, await wrap((await store(STORES$1.swaps, "readonly")).getAll()));
35912
+ }
35913
+ async readMelts() {
35914
+ return openRows(STORES$1.melts, await wrap((await store(STORES$1.melts, "readonly")).getAll()));
35915
+ }
35916
+ /** Sealed before its transaction opens (one that waits for WebCrypto commits early), when the profile is encrypted. */
35917
+ async putSwap(swap) {
35918
+ const row = await sealRow(STORES$1.swaps, swap);
35919
+ await committed((await store(STORES$1.swaps, "readwrite")).put(row));
35920
+ }
35921
+ /**
35922
+ * `transact`, with the wallet's secrets sealed as they are written when the profile is encrypted (WISP 04): `rows`,
35923
+ * the proofs, swaps and melts the work may put, are sealed before the transaction opens, and the work finds a proof
35924
+ * by its secret. Without the data key, `transact` itself.
35925
+ */
35926
+ async sealedTransact(names, rows, work) {
35927
+ const seals = new RowSeals();
35928
+ for (const [name, list] of Object.entries(rows)) await seals.prepare(name, list ?? []);
35929
+ return transact(names, (stores) => work(seals.on ? Object.fromEntries(names.map((name) => [name, sealedStore(stores[name], seals)])) : stores));
34993
35930
  }
34994
35931
  async proofsAt(mint) {
34995
35932
  return (await this.allProofs()).filter((p) => p.mint === mint && !p.reserved);
@@ -35058,6 +35995,13 @@ var ENDPOINT_OF = {
35058
35995
  bitcoin: ENDPOINT.bitcoin,
35059
35996
  spark: ENDPOINT.spark
35060
35997
  };
35998
+ /**
35999
+ * Every USDT request carries the wallet's one address: a transfer to it says which request it pays only by its amount.
36000
+ * So each asks for a little more than typed, 1 to USDT_TAG_SPAN-1 base units (under a thousandth of a USDT), an amount
36001
+ * no other open request of that network asks for; a transfer settles only the request of its exact amount.
36002
+ */
36003
+ var USDT_TAG_SPAN = 1e3;
36004
+ var USDT_TX_USED = "This transaction already paid another request";
35061
36005
  /** A `pay` frame that carries no receipt, only "I paid this from another wallet: look now". */
35062
36006
  var CHECK_PAYLOAD = JSON.stringify({ check: true });
35063
36007
  var isCheck = (payload) => {
@@ -35217,6 +36161,11 @@ var PaymentBook = class extends Map {
35217
36161
  * (`receiveCheck`): no more often than the wallet's own refresh, which runs the same look.
35218
36162
  */
35219
36163
  var RAIL_LOOK_MS = 1e4;
36164
+ /**
36165
+ * Whether `at` was less than `ms` ago, for the desk's paces. A time later than now (the device clock went back) is long
36166
+ * ago: otherwise a pace stays shut for as long as the clock went back.
36167
+ */
36168
+ var within = (now, at, ms) => at !== void 0 && at <= now && now - at < ms;
35220
36169
  var PaymentDesk = class {
35221
36170
  wallet;
35222
36171
  host;
@@ -35224,6 +36173,8 @@ var PaymentDesk = class {
35224
36173
  paying = /* @__PURE__ */ new Map();
35225
36174
  receiving = /* @__PURE__ */ new Map();
35226
36175
  reclaims = /* @__PURE__ */ new Map();
36176
+ /** Receipts older than `RECEIPT_FRESH_MS` said again in this run of the app, by payment id (`receiptOwed`). */
36177
+ receiptsSaid = /* @__PURE__ */ new Set();
35227
36178
  checkingArk = false;
35228
36179
  checkingUsdt = false;
35229
36180
  checkingBark = false;
@@ -35277,6 +36228,7 @@ var PaymentDesk = class {
35277
36228
  async start() {
35278
36229
  const stored = await wrap((await store(STORES$1.payments, "readonly")).getAll());
35279
36230
  for (const payment of stored) this.payments.set(payment.id, payment);
36231
+ for (const payment of stored) if (payment.kind === "request" && payment.direction === "in" && payment.lightningPending) await this.settleInterrupted(payment);
35280
36232
  const claims = await wrap((await store(STORES$1.settings, "readonly")).get(INVOICE_CLAIMS_KEY));
35281
36233
  this.claims = [...(claims ?? []).filter((c) => !this.claims.some((d) => sameClaim(c, d))), ...this.claims];
35282
36234
  }
@@ -35338,12 +36290,13 @@ var PaymentDesk = class {
35338
36290
  if (usdt.configured === false) throw new Error(mine("USDT"));
35339
36291
  const target = await usdt.target();
35340
36292
  const unit = target.asset === "USDT" ? "usdt" : "testusdt";
36293
+ const amount = this.uniqueUsdtAmount(params.amount, target.network);
35341
36294
  await this.save({
35342
36295
  id,
35343
36296
  linkId: params.linkId,
35344
36297
  kind: "request",
35345
36298
  direction: "out",
35346
- amount: params.amount,
36299
+ amount,
35347
36300
  unit,
35348
36301
  memo,
35349
36302
  state: "pending",
@@ -35355,7 +36308,7 @@ var PaymentDesk = class {
35355
36308
  await this.host.storeMessage({
35356
36309
  linkId: params.linkId,
35357
36310
  id: `me_${params.timestamp}`,
35358
- text: `Requested ${formatPaymentAmount(params.amount, target.decimals)} ${target.asset}`,
36311
+ text: `Requested ${formatPaymentAmount(amount, target.decimals)} ${target.asset}`,
35359
36312
  sender: "me",
35360
36313
  timestamp: params.timestamp,
35361
36314
  via: "datalink",
@@ -35365,7 +36318,7 @@ var PaymentDesk = class {
35365
36318
  id,
35366
36319
  timestamp: params.timestamp,
35367
36320
  amount: {
35368
- value: String(params.amount),
36321
+ value: String(amount),
35369
36322
  asset: unit
35370
36323
  },
35371
36324
  memo,
@@ -35965,7 +36918,8 @@ var PaymentDesk = class {
35965
36918
  */
35966
36919
  answering(linkId, request, method, amount, network) {
35967
36920
  const ask = request.ask ? this.asks.get(request.ask) : void 0;
35968
- if (!ask || ask.linkId !== linkId || ask.method !== method || ask.amount !== amount || ask.expiresAt < Date.now() || network !== ask.network) return void 0;
36921
+ if (!ask || ask.linkId !== linkId || ask.method !== method || ask.expiresAt < Date.now() || network !== ask.network) return void 0;
36922
+ if (method === "usdt" ? amount < ask.amount || amount >= ask.amount + USDT_TAG_SPAN : amount !== ask.amount) return void 0;
35969
36923
  this.asks.delete(request.ask);
35970
36924
  return request.ask;
35971
36925
  }
@@ -35977,7 +36931,7 @@ var PaymentDesk = class {
35977
36931
  const link = this.host.getLink(linkId);
35978
36932
  if (!link) return;
35979
36933
  const now = Date.now();
35980
- if (now - (this.lastAskFrom.get(linkId) ?? 0) < 3e3) return;
36934
+ if (within(now, this.lastAskFrom.get(linkId), 3e3)) return;
35981
36935
  this.lastAskFrom.set(linkId, now);
35982
36936
  if ([...this.payments.values()].filter((p) => p.linkId === linkId && p.kind === "request" && p.direction === "out" && p.state === "pending" && p.ask).length >= 5 || !/^[1-9]\d{0,15}$/.test(ask.amount.value)) return;
35983
36937
  if (ask.method === "bitcoin" && [...this.payments.values()].filter((p) => p.kind === "request" && p.direction === "out" && p.ask && p.target?.method === "bitcoin" && now - p.createdAt < 36e5).length >= 10) return;
@@ -36402,14 +37356,21 @@ var PaymentDesk = class {
36402
37356
  Promise.resolve(this.host.onReviewedPaymentResult?.(payment.id)).catch(() => {});
36403
37357
  return;
36404
37358
  }
36405
- if (!payment || payment.linkId !== linkId || payment.state !== "pending") return;
36406
- if (payment.kind === "request") {
36407
- if (payment.direction === "in" && result.ok) await this.save({
37359
+ if (result.ok && payment?.kind === "request" && payment.direction === "in" && payment.linkId === linkId) {
37360
+ const settles = payment.state === "pending";
37361
+ if (settles || !payment.payeeConfirmed) await this.save({
36408
37362
  ...payment,
36409
- state: "settled",
36410
- lightningPending: void 0
37363
+ ...settles && {
37364
+ state: "settled",
37365
+ lightningPending: void 0
37366
+ },
37367
+ payeeConfirmed: true
36411
37368
  });
36412
- else if (payment.direction === "in" && result.closed && !payment.lightningPending) await this.save({
37369
+ return;
37370
+ }
37371
+ if (!payment || payment.linkId !== linkId || payment.state !== "pending") return;
37372
+ if (payment.kind === "request") {
37373
+ if (payment.direction === "in" && result.closed && !payment.lightningPending) await this.save({
36413
37374
  ...payment,
36414
37375
  state: "failed",
36415
37376
  closed: true,
@@ -36481,7 +37442,7 @@ var PaymentDesk = class {
36481
37442
  const endpoint = request.target ? request.target.method === "fedimint" ? request.invoice ? [ENDPOINT.bolt11, request.invoice] : void 0 : request.target.method === "usdt" || request.target.method === "cashu" ? void 0 : [ENDPOINT_OF[request.target.method], CHECK_PAYLOAD] : request.invoice ? [ENDPOINT.bolt11, request.invoice] : void 0;
36482
37443
  if (!endpoint) throw new Error("This request cannot be paid from another wallet");
36483
37444
  const now = Date.now();
36484
- if (now - (this.lastCheck.get(request.id) ?? 0) < 5e3) return;
37445
+ if (within(now, this.lastCheck.get(request.id), 5e3)) return;
36485
37446
  this.lastCheck.set(request.id, now);
36486
37447
  const link = this.requireLink(params.linkId);
36487
37448
  await this.sendTo(link, {
@@ -36503,7 +37464,7 @@ var PaymentDesk = class {
36503
37464
  */
36504
37465
  async receiveCheck(linkId, payment) {
36505
37466
  const link = this.host.getLink(linkId);
36506
- if (link && !payment.requestId && payment.endpoint[0] === ENDPOINT.bolt11) return this.receiveInvoicePaid(linkId, link, payment.endpoint[1]);
37467
+ if (link && !payment.requestId && payment.endpoint[0] === ENDPOINT.bolt11) return this.receiveInvoicePaid(linkId, payment.endpoint[1]);
36507
37468
  const request = payment.requestId ? this.payments.get(payment.requestId) : void 0;
36508
37469
  if (!link || !request || request.kind !== "request" || request.direction !== "out" || !this.owns(request, linkId)) return;
36509
37470
  const rail = request.target ? request.target.method : request.invoice ? "lightning" : void 0;
@@ -36517,11 +37478,12 @@ var PaymentDesk = class {
36517
37478
  }
36518
37479
  const now = Date.now();
36519
37480
  const [key, every] = rail === "lightning" ? [request.id, 3e3] : [rail, RAIL_LOOK_MS];
36520
- if (now - (this.lastCheckFrom.get(key) ?? 0) < every) return;
37481
+ if (within(now, this.lastCheckFrom.get(key), every)) return;
36521
37482
  this.lastCheckFrom.set(key, now);
36522
37483
  try {
36523
- if (rail === "lightning") await this.lightning[paymentNetwork(request)].check?.(payment.endpoint[1].trim().toLowerCase() === request.invoice?.toLowerCase() ? request.invoice : void 0);
36524
- else if (rail === "bitcoin") await this.reconcileBitcoinReceipts();
37484
+ if (rail === "lightning") {
37485
+ if (request.invoice) await this.lightning[paymentNetwork(request)].check?.(request.invoice, payment.endpoint[1].trim().toLowerCase() === request.invoice.toLowerCase());
37486
+ } else if (rail === "bitcoin") await this.reconcileBitcoinReceipts();
36525
37487
  else if (rail === "bark") await this.reconcileBarkReceipts();
36526
37488
  else if (rail === "spark") await this.reconcileSparkReceipts();
36527
37489
  else await this.reconcileArkReceipts();
@@ -36533,27 +37495,27 @@ var PaymentDesk = class {
36533
37495
  * for by its own contact only (`receiveCheck`). Bounded: one look every 3 seconds per invoice of a chat, so two
36534
37496
  * invoices paid one right after the other are both let go, and `INVOICE_LOOKS_PER_CHAT` looks every 3 seconds per
36535
37497
  * chat: the invoice is the contact's text, and a frame per text made each one a read of every invoice of the wallet
36536
- * (2,000 frames, 2,000 reads), each also walking every key of the last 3 s (agents#1586).
37498
+ * (2,000 frames, 2,000 reads), each also walking every key of the last 3 s (agents#1586). Taken whatever the chat's
37499
+ * Lightning choice: a group's card tells the writer through their 1:1 chat, and the word lets go of our own invoice only.
36537
37500
  */
36538
- async receiveInvoicePaid(linkId, link, invoice) {
36539
- if (!link.allowsPayment("lightning")) return;
37501
+ async receiveInvoicePaid(linkId, invoice) {
36540
37502
  const now = Date.now();
36541
37503
  const wanted = invoice.trim().toLowerCase();
36542
37504
  const key = `${linkId}:${wanted}`;
36543
- if (now - (this.lastInvoiceCheck.get(key) ?? 0) < 3e3) return;
36544
- const looks = (this.invoiceLooks.get(linkId) ?? []).filter((at) => now - at < 3e3);
37505
+ if (within(now, this.lastInvoiceCheck.get(key), 3e3)) return;
37506
+ const looks = (this.invoiceLooks.get(linkId) ?? []).filter((at) => within(now, at, 3e3));
36545
37507
  if (looks.length >= 5) {
36546
37508
  this.invoiceLooks.set(linkId, looks);
36547
37509
  return;
36548
37510
  }
36549
37511
  this.invoiceLooks.set(linkId, [...looks, now]);
36550
37512
  for (const [seen, at] of this.lastInvoiceCheck) {
36551
- if (now - at < 3e3) break;
37513
+ if (within(now, at, 3e3)) break;
36552
37514
  this.lastInvoiceCheck.delete(seen);
36553
37515
  }
36554
37516
  this.lastInvoiceCheck.delete(key);
36555
37517
  this.lastInvoiceCheck.set(key, now);
36556
- for (const [chat, times] of this.invoiceLooks) if (chat !== linkId && times.every((at) => now - at >= 3e3)) this.invoiceLooks.delete(chat);
37518
+ for (const [chat, times] of this.invoiceLooks) if (chat !== linkId && times.every((at) => !within(now, at, 3e3))) this.invoiceLooks.delete(chat);
36557
37519
  try {
36558
37520
  const quote = (await this.wallet.quotes()).find((q) => q.held && !q.paymentId && q.invoice.toLowerCase() === wanted);
36559
37521
  if (quote) await this.wallet.vouch(quote.invoice);
@@ -36580,6 +37542,20 @@ var PaymentDesk = class {
36580
37542
  error: "The Lightning payment did not go through"
36581
37543
  });
36582
37544
  }
37545
+ /**
37546
+ * A contact's request marked as being paid over Lightning when the app was closed: the mark is written before the
37547
+ * source is asked, and only that run's answer cleared it. What the source and the mints wrote down decides: nothing
37548
+ * left the wallet and it can be paid again (and the group is not told it was sent), or it went through.
37549
+ */
37550
+ async settleInterrupted(request) {
37551
+ const lightning = this.lightning[paymentNetwork(request)];
37552
+ if (!lightning.interrupted || this.paying.has(`${request.linkId}:${request.id}`)) return;
37553
+ try {
37554
+ if (request.invoice && await this.wallet.meltInFlight?.(request.invoice)) return;
37555
+ const outcome = await lightning.interrupted(request.id);
37556
+ if (outcome !== "pending") await this.onLightningResolved({ paymentId: request.id }, outcome === "paid");
37557
+ } catch {}
37558
+ }
36583
37559
  onQuotePaid(quote) {
36584
37560
  return this.onLightningPaid(quote);
36585
37561
  }
@@ -36711,7 +37687,8 @@ var PaymentDesk = class {
36711
37687
  if (typeof txid !== "string" || !/^0x[a-fA-F0-9]{64}$/.test(txid)) return;
36712
37688
  if (this.repeatedReceipt(this.host.getLink(linkId), request, payment.id)) return;
36713
37689
  txid = txid.toLowerCase();
36714
- if ([...this.payments.values()].some((p) => p.txid?.toLowerCase() === txid && (p.linkId !== linkId || (p.kind === "request" ? p.id !== request.id : p.requestId !== request.id)))) return;
37690
+ const used = this.usdtTxUsed(txid, request.id);
37691
+ const paid = request.state === "settled";
36715
37692
  await this.save({
36716
37693
  id: payment.id,
36717
37694
  linkId,
@@ -36719,7 +37696,8 @@ var PaymentDesk = class {
36719
37696
  direction: "in",
36720
37697
  amount: request.amount,
36721
37698
  unit: request.unit,
36722
- state: "pending",
37699
+ state: used ? "failed" : "pending",
37700
+ error: used ? USDT_TX_USED : void 0,
36723
37701
  createdAt: payment.timestamp,
36724
37702
  target: request.target,
36725
37703
  requestId: request.id,
@@ -36728,13 +37706,32 @@ var PaymentDesk = class {
36728
37706
  await this.host.storeMessage({
36729
37707
  linkId,
36730
37708
  id: `peer_${payment.timestamp}`,
36731
- text: `${formatPaymentAmount(request.amount, request.target.decimals)} ${request.target.asset} — checking chain`,
37709
+ text: `${formatPaymentAmount(request.amount, request.target.decimals)} ${request.target.asset} — ${used ? USDT_TX_USED.toLowerCase() : "checking chain"}`,
36732
37710
  sender: "peer",
36733
37711
  timestamp: payment.timestamp,
36734
37712
  via: "datalink",
36735
37713
  paymentId: payment.id
36736
37714
  });
36737
- await this.reconcileUsdtReceipts();
37715
+ if (!used) await this.reconcileUsdtReceipts();
37716
+ if (paid) this.host.getLink(linkId)?.sendPaymentResult({
37717
+ id: request.id,
37718
+ ok: true
37719
+ });
37720
+ }
37721
+ /** Whether a USDT transaction already paid a request other than `requestId`. */
37722
+ usdtTxUsed(txid, requestId) {
37723
+ return [...this.payments.values()].some((p) => p.state === "settled" && p.txid?.toLowerCase() === txid.toLowerCase() && (p.kind === "request" ? p.id !== requestId : p.requestId !== requestId));
37724
+ }
37725
+ /** An amount of `amount` plus 1 to USDT_TAG_SPAN-1 base units that no open USDT request of `network` asks for. */
37726
+ uniqueUsdtAmount(amount, network) {
37727
+ const taken = /* @__PURE__ */ new Set();
37728
+ for (const p of this.payments.values()) if (p.kind === "request" && p.direction === "out" && p.state === "pending" && p.target?.method === "usdt" && p.target.network === network) taken.add(p.amount);
37729
+ const free = [];
37730
+ for (let tag = 1; tag < USDT_TAG_SPAN; tag++) if (!taken.has(amount + tag)) free.push(amount + tag);
37731
+ if (!free.length) throw new Error("Too many open USDT requests of this amount: wait for one to be paid");
37732
+ const unique = free[randomBytes(4).reduce((n, b) => n * 256 + b, 0) % free.length];
37733
+ assertTokenUnits(unique);
37734
+ return unique;
36738
37735
  }
36739
37736
  async reconcileUsdtReceipts() {
36740
37737
  if (this.checkingUsdt || !this.usdt) return;
@@ -36749,6 +37746,14 @@ var PaymentDesk = class {
36749
37746
  amount: payment.amount
36750
37747
  }).catch(() => null);
36751
37748
  if (!result?.settled && !result?.failed) continue;
37749
+ if (result.settled && this.usdtTxUsed(payment.txid, payment.requestId)) {
37750
+ await this.save({
37751
+ ...payment,
37752
+ state: "failed",
37753
+ error: USDT_TX_USED
37754
+ });
37755
+ continue;
37756
+ }
36752
37757
  await this.save({
36753
37758
  ...payment,
36754
37759
  state: result.settled ? "settled" : "failed",
@@ -36885,6 +37890,7 @@ var PaymentDesk = class {
36885
37890
  if ([...this.payments.values()].some((p) => p.txid === txid && (p.linkId !== linkId || (p.kind === "request" ? p.id !== request.id : p.requestId !== request.id)))) return;
36886
37891
  if (typeof txid !== "string" || !/^[a-f0-9]{64}$/.test(txid)) return;
36887
37892
  if (this.repeatedReceipt(link, request, payment.id)) return;
37893
+ const paid = request.state === "settled";
36888
37894
  await this.save({
36889
37895
  id: payment.id,
36890
37896
  linkId,
@@ -36908,6 +37914,10 @@ var PaymentDesk = class {
36908
37914
  paymentId: payment.id
36909
37915
  });
36910
37916
  await this.reconcileArkReceipts();
37917
+ if (paid) link.sendPaymentResult({
37918
+ id: request.id,
37919
+ ok: true
37920
+ });
36911
37921
  }
36912
37922
  /**
36913
37923
  * An Ark request is paid when a virtual output of at least the amount reached the address made for it,
@@ -37001,8 +38011,16 @@ var PaymentDesk = class {
37001
38011
  if (!link?.supportsBarkPayments || request?.target?.method !== "bark" || request.linkId !== linkId || request.direction !== "out" || request.kind !== "request") return;
37002
38012
  const existing = this.payments.get(payment.id);
37003
38013
  if (existing && (existing.linkId !== linkId || existing.direction !== "in" || existing.requestId !== request.id)) return;
37004
- if (existing || parseSats(payment.amount.value, payment.amount.asset) !== request.amount) return;
38014
+ if (existing) {
38015
+ if (request.state === "settled") link.sendPaymentResult({
38016
+ id: request.id,
38017
+ ok: true
38018
+ });
38019
+ return;
38020
+ }
38021
+ if (parseSats(payment.amount.value, payment.amount.asset) !== request.amount) return;
37005
38022
  if (this.repeatedReceipt(link, request, payment.id)) return;
38023
+ const settled = request.state === "settled";
37006
38024
  await this.save({
37007
38025
  id: payment.id,
37008
38026
  linkId,
@@ -37010,7 +38028,7 @@ var PaymentDesk = class {
37010
38028
  direction: "in",
37011
38029
  amount: request.amount,
37012
38030
  unit: UNIT,
37013
- state: request.state === "settled" ? "settled" : "pending",
38031
+ state: settled ? "settled" : "pending",
37014
38032
  createdAt: payment.timestamp,
37015
38033
  target: request.target,
37016
38034
  requestId: request.id,
@@ -37019,13 +38037,17 @@ var PaymentDesk = class {
37019
38037
  await this.host.storeMessage({
37020
38038
  linkId,
37021
38039
  id: `peer_${payment.timestamp}`,
37022
- text: `${request.amount} ${arkSats(request.target.network)} on Bark${request.state === "settled" ? "" : " — checking wallet"}`,
38040
+ text: `${request.amount} ${arkSats(request.target.network)} on Bark${settled ? "" : " — checking wallet"}`,
37023
38041
  sender: "peer",
37024
38042
  timestamp: payment.timestamp,
37025
38043
  via: "datalink",
37026
38044
  paymentId: payment.id
37027
38045
  });
37028
38046
  await this.reconcileBarkReceipts();
38047
+ if (settled) link.sendPaymentResult({
38048
+ id: request.id,
38049
+ ok: true
38050
+ });
37029
38051
  }
37030
38052
  /**
37031
38053
  * A Bark request is paid when this wallet received, on the address made for it, at least the amount asked,
@@ -37136,7 +38158,14 @@ var PaymentDesk = class {
37136
38158
  if (!link?.supportsBitcoinPayments || request?.target?.method !== "bitcoin" || request.linkId !== linkId || request.direction !== "out" || request.kind !== "request") return;
37137
38159
  const existing = this.payments.get(payment.id);
37138
38160
  if (existing && (existing.linkId !== linkId || existing.direction !== "in" || existing.requestId !== request.id)) return;
37139
- if (existing || parseSats(payment.amount.value, payment.amount.asset) !== request.amount) return;
38161
+ if (existing) {
38162
+ if (request.state === "settled") link.sendPaymentResult({
38163
+ id: request.id,
38164
+ ok: true
38165
+ });
38166
+ return;
38167
+ }
38168
+ if (parseSats(payment.amount.value, payment.amount.asset) !== request.amount) return;
37140
38169
  let hint;
37141
38170
  try {
37142
38171
  hint = JSON.parse(payment.endpoint[1]).txid;
@@ -37169,6 +38198,10 @@ var PaymentDesk = class {
37169
38198
  paymentId: payment.id
37170
38199
  });
37171
38200
  await this.reconcileBitcoinReceipts();
38201
+ if (settled) link.sendPaymentResult({
38202
+ id: request.id,
38203
+ ok: true
38204
+ });
37172
38205
  }
37173
38206
  /**
37174
38207
  * An on-chain request is paid when this wallet's source has a confirmed transaction paying the address made
@@ -37540,7 +38573,14 @@ var PaymentDesk = class {
37540
38573
  if (!link?.supportsSparkPayments || request?.target?.method !== "spark" || request.linkId !== linkId || request.direction !== "out" || request.kind !== "request") return;
37541
38574
  const existing = this.payments.get(payment.id);
37542
38575
  if (existing && (existing.linkId !== linkId || existing.direction !== "in" || existing.requestId !== request.id)) return;
37543
- if (existing || parseSats(payment.amount.value, payment.amount.asset) !== request.amount) return;
38576
+ if (existing) {
38577
+ if (request.state === "settled") link.sendPaymentResult({
38578
+ id: request.id,
38579
+ ok: true
38580
+ });
38581
+ return;
38582
+ }
38583
+ if (parseSats(payment.amount.value, payment.amount.asset) !== request.amount) return;
37544
38584
  if (this.repeatedReceipt(link, request, payment.id)) return;
37545
38585
  const settled = request.state === "settled";
37546
38586
  await this.save({
@@ -37566,6 +38606,10 @@ var PaymentDesk = class {
37566
38606
  paymentId: payment.id
37567
38607
  });
37568
38608
  await this.reconcileSparkReceipts();
38609
+ if (settled) link.sendPaymentResult({
38610
+ id: request.id,
38611
+ ok: true
38612
+ });
37569
38613
  }
37570
38614
  /**
37571
38615
  * A Spark request is paid when this wallet completed a receive on the invoice made for it, of at least the amount
@@ -37735,7 +38779,7 @@ var PaymentDesk = class {
37735
38779
  endpoints: [[ENDPOINT.usdt, JSON.stringify(payment.target)]],
37736
38780
  ask: payment.ask
37737
38781
  });
37738
- else if (payment.kind === "payment" && payment.txid && payment.state !== "failed") await this.sendTo(link, {
38782
+ else if (payment.kind === "payment" && payment.txid && payment.state !== "failed" && this.receiptOwed(payment)) await this.sendTo(link, {
37739
38783
  id: payment.id,
37740
38784
  timestamp: payment.createdAt,
37741
38785
  requestId: payment.requestId,
@@ -37760,7 +38804,7 @@ var PaymentDesk = class {
37760
38804
  endpoints: [[ENDPOINT.bark, JSON.stringify(payment.target)]],
37761
38805
  ask: payment.ask
37762
38806
  });
37763
- else if (payment.kind === "payment" && payment.state === "settled") await this.sendTo(link, {
38807
+ else if (payment.kind === "payment" && payment.state === "settled" && this.receiptOwed(payment)) await this.sendTo(link, {
37764
38808
  id: payment.id,
37765
38809
  timestamp: payment.createdAt,
37766
38810
  requestId: payment.requestId,
@@ -37801,7 +38845,7 @@ var PaymentDesk = class {
37801
38845
  endpoints: [[ENDPOINT.spark, JSON.stringify(payment.target)]],
37802
38846
  ask: payment.ask
37803
38847
  });
37804
- else if (payment.kind === "payment" && payment.state === "settled") await this.sendTo(link, {
38848
+ else if (payment.kind === "payment" && payment.state === "settled" && this.receiptOwed(payment)) await this.sendTo(link, {
37805
38849
  id: payment.id,
37806
38850
  timestamp: payment.createdAt,
37807
38851
  requestId: payment.requestId,
@@ -37826,7 +38870,7 @@ var PaymentDesk = class {
37826
38870
  endpoints: [[ENDPOINT.bitcoin, JSON.stringify(payment.target)]],
37827
38871
  ask: payment.ask
37828
38872
  });
37829
- else if (payment.kind === "payment" && payment.txid && payment.state !== "failed") await this.sendTo(link, {
38873
+ else if (payment.kind === "payment" && payment.txid && payment.state !== "failed" && this.receiptOwed(payment)) await this.sendTo(link, {
37830
38874
  id: payment.id,
37831
38875
  timestamp: payment.createdAt,
37832
38876
  requestId: payment.requestId,
@@ -37851,7 +38895,7 @@ var PaymentDesk = class {
37851
38895
  endpoints: [[ENDPOINT.arkade, JSON.stringify(payment.target)]],
37852
38896
  ask: payment.ask
37853
38897
  });
37854
- else if (payment.kind === "payment" && payment.txid && payment.state === "settled") await this.sendTo(link, {
38898
+ else if (payment.kind === "payment" && payment.txid && payment.state === "settled" && this.receiptOwed(payment)) await this.sendTo(link, {
37855
38899
  id: payment.id,
37856
38900
  timestamp: payment.createdAt,
37857
38901
  requestId: payment.requestId,
@@ -37863,6 +38907,13 @@ var PaymentDesk = class {
37863
38907
  });
37864
38908
  continue;
37865
38909
  }
38910
+ if (payment.kind === "request" && payment.state === "settled" && payment.invoice && !payment.group && Date.now() - payment.createdAt < 6048e5) {
38911
+ link.sendPaymentResult({
38912
+ id: payment.id,
38913
+ ok: true
38914
+ });
38915
+ continue;
38916
+ }
37866
38917
  if (payment.state !== "pending") continue;
37867
38918
  if (payment.kind === "payment" && payment.token) await this.sendTo(link, {
37868
38919
  id: payment.id,
@@ -37888,6 +38939,22 @@ var PaymentDesk = class {
37888
38939
  });
37889
38940
  }
37890
38941
  }
38942
+ /**
38943
+ * Whether a receipt of ours (an on-chain, Ark, Bark, Spark or USDT payment already made) is said again on this
38944
+ * reconnect. Never once the payee said the request it answers is paid (`payeeConfirmed`): its own wallet saw the
38945
+ * money, and the receipt is only a hint. Otherwise at every reconnect while it is under `RECEIPT_FRESH_MS` old, so a
38946
+ * frame lost with a link that went down goes again, and once per run of the app after that: a payee that was away
38947
+ * when we paid still gets it the first time its chat opens, and a long history of payments made before the payee's
38948
+ * app answered them no longer goes out at every reconnect and transport switch. Call it last: it counts a send.
38949
+ */
38950
+ receiptOwed(payment) {
38951
+ const request = payment.requestId ? this.payments.get(payment.requestId) : void 0;
38952
+ if (request?.payeeConfirmed && request.kind === "request" && request.direction === "in" && request.linkId === payment.linkId) return false;
38953
+ if (Date.now() - payment.createdAt < 6048e5) return true;
38954
+ if (this.receiptsSaid.has(payment.id)) return false;
38955
+ this.receiptsSaid.add(payment.id);
38956
+ return true;
38957
+ }
37891
38958
  requireLink(linkId) {
37892
38959
  const link = this.host.getLink(linkId);
37893
38960
  if (!link) throw new Error("You are offline");
@@ -38036,9 +39103,14 @@ function writtenAt(message, leads) {
38036
39103
  return Math.min(message.timestamp, message.sentAt - behind);
38037
39104
  }
38038
39105
  var JOIN_NOTICE = /^👋 (?:.+ )?joined$/;
39106
+ /**
39107
+ * The quiet "joined" line: a 1:1 contact's only when the engine took it as the chat's joined line (`joinLine`), since
39108
+ * any later row of theirs in those words is a message like the rest; mine and a group's by their words.
39109
+ */
39110
+ var joinLine = (type, message) => type === "message" && !message.linkId.startsWith("group:") ? !!message.joinLine : JOIN_NOTICE.test(message.text);
38039
39111
  /** What a newly stored row says, or null when it is quiet. `type`: "message" for the contact's, "sent" for mine. */
38040
39112
  function messageAttention(type, message, { startedAt, newest, now, lateAt }) {
38041
- if (message.timestamp < startedAt || message.file || message.paymentId || JOIN_NOTICE.test(message.text)) return null;
39113
+ if (message.timestamp < startedAt || message.file || message.paymentId || joinLine(type, message)) return null;
38042
39114
  if (message.event) {
38043
39115
  const cue = groupCue(message);
38044
39116
  return cue && type === "message" ? {
@@ -38201,6 +39273,17 @@ var WalletSetup = class {
38201
39273
  * they all came back in the same instant, more listens than its one HyperDHT node sends out in time.
38202
39274
  */
38203
39275
  var RELAY_RETRY_MS = 3e4;
39276
+ /**
39277
+ * A chat's relayed HyperDHT listener went with the relay connection (`relayHolds`): for this long the chat keeps first
39278
+ * claim on a listener, and another chat does not take the slot it held. A socket closed with no close reaching the relay
39279
+ * (a network switch, a NAT that forgot it) leaves the old connection holding the chat's key until the relay's ping drops
39280
+ * it, 30 to 60 s (55 s measured), and the relay refuses the key to the new connection meanwhile: chats with free keys
39281
+ * took every slot, and the chats used most stayed without a listener until each was used again. The relay's worst ping
39282
+ * drop plus a margin.
39283
+ */
39284
+ var RELAY_HOLD_MS = 9e4;
39285
+ /** How often such a chat tries to listen again within that time, while the relay still refuses its key. */
39286
+ var RELAY_HOLD_RETRY_MS = 1e4;
38204
39287
  /** Native listeners an app may hold per transport (the Desktop's Rust Iroh allows eight, `paired_transport.rs`). */
38205
39288
  var NATIVE_SLOTS = 8;
38206
39289
  /**
@@ -38209,7 +39292,7 @@ var NATIVE_SLOTS = 8;
38209
39292
  * relays took sixteen started one after another, as the queue here starts them (six of sixteen started at once were
38210
39293
  * refused). 1:1 chats hold eight of them at most, as before: the rest is room for group links. HyperDHT keeps eight
38211
39294
  * there too: a page's listeners share one WebSocket to its relay, which drops a client past sixteen listens (device
38212
- * links listen there as well), and each of the CLI's is a whole DHT node.
39295
+ * links listen there as well).
38213
39296
  */
38214
39297
  var IROH_WEB_SLOTS = 16;
38215
39298
  /**
@@ -38233,6 +39316,20 @@ var CLEAR_WITHDRAW_MS = 6e3;
38233
39316
  * session): a dial to a contact that is not there ends within its 20 s timeout, and leaves its slot free until the next.
38234
39317
  */
38235
39318
  var ACTIVE_SLOT_RETRY_MS = 3e3;
39319
+ /**
39320
+ * A 1:1 chat whose contact has not been seen this long (no packet that says it is online, no session, no text either
39321
+ * way, not on screen) lets its HyperDHT listener go: hyperdht keeps an announced listener reachable by pinging three DHT
39322
+ * nodes every 3 s, about 62 requests a minute, for a contact who is not there to dial it. It listens again as soon as
39323
+ * the contact is seen online (its next packet read: half a minute at most at the background pace), a text goes either
39324
+ * way, the chat is opened, or the contact's packet cannot be read (the relays out of reach: no read would say it is
39325
+ * back); its transport key is kept. A contact gone a little while (an app restarted, a laptop asleep for a few
39326
+ * minutes) finds it as before.
39327
+ */
39328
+ var NATIVE_GONE_MS = 6e5;
39329
+ /** How often the chats are looked at for that (`releaseGoneListeners`). */
39330
+ var NATIVE_GONE_CHECK_MS = 15e3;
39331
+ /** The transport that lets a gone contact's listener go: the one whose waiting costs the network (`NATIVE_GONE_MS`). */
39332
+ var GONE_TRANSPORT = "hyperdht/1";
38236
39333
  /** How long an edge passed over that way ranks after the others, before the group tries it again. */
38237
39334
  var GROUP_ANCHOR_PASSED_MS = 3e5;
38238
39335
  /** How often the edges groups keep are looked at for that (`groupAnchorsAnswered`). */
@@ -38252,9 +39349,25 @@ var DEFAULT_SETTINGS = {
38252
39349
  mints: [],
38253
39350
  mintsInitialized: false
38254
39351
  };
39352
+ /** How many deleted ids a link remembers: enough to outlast what a peer republishes. */
39353
+ var MAX_DELETED_IDS = 500;
38255
39354
  /** A link's `removedRefs` with `ref`, the newest `MAX_DELETED_IDS`. */
38256
39355
  var withRemovedRef = (refs, ref) => [...(refs ?? []).filter((r) => r !== ref), ref].slice(-500);
38257
39356
  /**
39357
+ * A 1:1 chat's `deletedIds` with `id`. Full (`MAX_DELETED_IDS`), the oldest of the side that has the most goes (the one
39358
+ * just noted's own on a tie), as a group's removed ids by author (`withRemovedId`): my deletions, as many as I make,
39359
+ * never push out an id of the contact's, so a copy of theirs that comes again stays deleted, nor theirs one of mine.
39360
+ */
39361
+ var withDeletedId = (ids, id) => {
39362
+ const next = [...ids ?? [], id];
39363
+ if (next.length <= MAX_DELETED_IDS) return next;
39364
+ const theirs = (row) => row.startsWith("peer_");
39365
+ const peer = next.filter(theirs).length;
39366
+ const side = peer * 2 === next.length ? theirs(id) : peer * 2 > next.length;
39367
+ next.splice(next.findIndex((row) => theirs(row) === side), 1);
39368
+ return next;
39369
+ };
39370
+ /**
38258
39371
  * A card that went on the DHT floor or into a hold goes again live (`restoreCards`) only for the newest this many
38259
39372
  * messages of a chat, sent within this long: an old chat's cards are not worth a burst of edits.
38260
39373
  */
@@ -38279,6 +39392,32 @@ var pkarrSeenAt = (messages) => messages.reduce((max, m) => m.sender === "peer"
38279
39392
  var waitsForLive = (m) => m.sender === "me" && m.delivery === "waiting" && (!!m.file || !!m.paymentId);
38280
39393
  /** A message of mine whose card went as its text alone and is due to go again live (`restoreCards`). */
38281
39394
  var cardDue = (m) => m.sender === "me" && (m.cardRestore ?? m.buttonsRestore) === "due";
39395
+ /**
39396
+ * A row id of the contact's own in a 1:1 chat: not the note a contact request carried (the chat's first row on the side
39397
+ * that accepted it, before the contact's joined line), nor a line of this app's about their payment (`shared/refusals.ts`).
39398
+ */
39399
+ var contactRowId = (id) => id.startsWith("peer_") && !id.startsWith("peer_contact_") && !isRefusalId(id);
39400
+ /** A row of the contact's own (`contactRowId`) in the words of the chat's joined line. */
39401
+ var contactJoinRow = (m) => m.sender === "peer" && contactRowId(m.id) && isJoinNotice(m.text);
39402
+ /**
39403
+ * Whether a 1:1 chat holds a row of the contact's in the joined line's words (`contactJoinRow`) other than `except`:
39404
+ * oldest first, a page at a time.
39405
+ */
39406
+ async function contactJoinRowStored(linkId, except) {
39407
+ for (let after = { timestamp: -Infinity };;) {
39408
+ const page = await db.getMessagePageAfter(linkId, {
39409
+ limit: 64,
39410
+ after
39411
+ });
39412
+ if (page.messages.some((m) => m.id !== except && contactJoinRow(m))) return true;
39413
+ const last = page.messages[page.messages.length - 1];
39414
+ if (!page.more || !last) return false;
39415
+ after = {
39416
+ timestamp: last.timestamp,
39417
+ id: last.id
39418
+ };
39419
+ }
39420
+ }
38282
39421
  /** The id a 1:1 chat's row goes by on both sides when its own row is not `peer_`/`me_` and that id (`resolveReply`). */
38283
39422
  var unkeyedRef = (m) => {
38284
39423
  const ref = replyRef(m, false);
@@ -38360,6 +39499,7 @@ function newLiveLink(stored, lastMessageAt, files = emptyLinkFiles()) {
38360
39499
  lastPacketAt: 0,
38361
39500
  services: null
38362
39501
  },
39502
+ onlineSeenAt: Date.now(),
38363
39503
  lastMessageAt,
38364
39504
  peerAck: 0,
38365
39505
  lastSyncAt: 0,
@@ -38576,6 +39716,8 @@ var GhostlyNode = class GhostlyNode {
38576
39716
  }
38577
39717
  /** The newest time written in each chat while this engine runs: a message written well before it is a catch-up. */
38578
39718
  newestAt = /* @__PURE__ */ new Map();
39719
+ /** The chats whose contact's joined line came while this engine runs (`firstContactRow`), whatever `stored` says. */
39720
+ contactSpoke = /* @__PURE__ */ new WeakSet();
38579
39721
  /** Per group: when the last message written well before it came, came. What comes after it, as old, is its catch-up. */
38580
39722
  lateAt = /* @__PURE__ */ new Map();
38581
39723
  /** The last place given in each chat while this engine runs (`arrivalKey`). */
@@ -38590,8 +39732,8 @@ var GhostlyNode = class GhostlyNode {
38590
39732
  return message.linkId.startsWith("group:") ? `${message.linkId} ${message.member ?? ""}` : message.linkId;
38591
39733
  }
38592
39734
  /**
38593
- * A contact's row came on the live session of a 1:1 chat, or a member's straight from its author (`live`, never one
38594
- * handed on or caught up): what it says of that clock is kept.
39735
+ * A contact's row came on the live session of a 1:1 chat, or a member's as it was written (`live`: straight from its
39736
+ * author, or in a community handed on at once by a hub that says so; never one caught up): what it says of that clock is kept.
38595
39737
  */
38596
39738
  clockSample(message, live = false) {
38597
39739
  if (message.sender !== "peer" || message.sentAt === void 0 || message.event || message.via !== "datalink") return;
@@ -38974,13 +40116,14 @@ var GhostlyNode = class GhostlyNode {
38974
40116
  note,
38975
40117
  paymentId
38976
40118
  }),
38977
- check: async (paid) => {
40119
+ check: async (invoice, named) => {
38978
40120
  await Promise.all([
38979
- this.lightnings[network].reconcile(),
38980
- paid ? this.wallet.vouch(paid) : this.wallet.checkQuotes(),
40121
+ this.lightnings[network].check(invoice),
40122
+ this.wallet.vouch(invoice, named),
38981
40123
  this.fedimintWallets[network].checkReceives()
38982
40124
  ]);
38983
- }
40125
+ },
40126
+ interrupted: journaledPayment
38984
40127
  })), this.bitcoins, this.fedimintWallets, perNetwork((network) => ({
38985
40128
  ready: () => !!this.sparkWallets[network].adapter,
38986
40129
  requestTarget: (amount, memo) => this.sparkWallets[network].target(amount, memo),
@@ -39277,22 +40420,87 @@ var GhostlyNode = class GhostlyNode {
39277
40420
  accept: async (request) => {
39278
40421
  const params = decodeInviteCode(request.invite);
39279
40422
  if (!params || inviteOwnership(params, [...this.links.values()].map((l) => l.stored)).kind !== "new") throw new Error("This request's invite is for a chat you already have.");
39280
- const { linkId } = await this.joinLink({ inviteCode: request.invite });
39281
- this.renameLink({
39282
- linkId,
39283
- label: request.name
39284
- });
39285
- await this.storeMessage({
39286
- linkId,
39287
- id: `peer_contact_${request.key.slice(0, 32)}`,
39288
- text: request.text,
39289
- sender: "peer",
39290
- timestamp: Math.min(request.issued, request.receivedAt),
39291
- via: "pkarr"
39292
- });
39293
- return linkId;
40423
+ this.accepting = true;
40424
+ try {
40425
+ const { linkId } = await this.joinLink({ inviteCode: request.invite });
40426
+ this.renameLink({
40427
+ linkId,
40428
+ label: request.name
40429
+ });
40430
+ const message = `peer_contact_${request.key.slice(0, 32)}`;
40431
+ const contactAsker = {
40432
+ link: request.link,
40433
+ key: request.key,
40434
+ message
40435
+ };
40436
+ const live = this.links.get(linkId);
40437
+ if (live) live.stored = {
40438
+ ...live.stored,
40439
+ contactAsker
40440
+ };
40441
+ await db.patchLink(linkId, { contactAsker });
40442
+ await this.storeMessage({
40443
+ linkId,
40444
+ id: message,
40445
+ text: request.text,
40446
+ sender: "peer",
40447
+ timestamp: Math.min(request.issued, request.receivedAt),
40448
+ via: "pkarr",
40449
+ unconfirmed: true
40450
+ });
40451
+ const heard = this.askerHeard.get(linkId);
40452
+ if (heard) await this.contactAskerHeard(linkId, heard.frame, heard.keys);
40453
+ return linkId;
40454
+ } finally {
40455
+ this.accepting = false;
40456
+ this.askerHeard.clear();
40457
+ }
39294
40458
  }
39295
40459
  });
40460
+ /** An accept of a contact request is under way, and the last asker's proof each chat said meanwhile. */
40461
+ accepting = false;
40462
+ askerHeard = /* @__PURE__ */ new Map();
40463
+ /**
40464
+ * The contact said it asked through this profile's link (WISP 8xx § Accept). The chat's request text is confirmed
40465
+ * when the proof is the asker key's for this chat; anything else changes nothing.
40466
+ */
40467
+ async contactAskerHeard(linkId, frame, keys) {
40468
+ const live = this.links.get(linkId);
40469
+ if (!live) return;
40470
+ const expected = live.stored.contactAsker;
40471
+ if (!expected) {
40472
+ if (this.accepting) this.askerHeard.set(linkId, {
40473
+ frame,
40474
+ keys
40475
+ });
40476
+ return;
40477
+ }
40478
+ if (!contactAskerHolds(frame, expected, {
40479
+ inviter: keys.peer,
40480
+ joiner: keys.mine
40481
+ })) return;
40482
+ live.stored = {
40483
+ ...live.stored,
40484
+ contactAsker: void 0
40485
+ };
40486
+ await db.patchLink(linkId, { contactAsker: void 0 });
40487
+ if (await db.patchMessage(linkId, expected.message, (m) => m.unconfirmed ? { unconfirmed: void 0 } : null)) await this.messagesChanged(linkId, [expected.message]);
40488
+ }
40489
+ /**
40490
+ * A chat a request of this profile's started is live: its proof that this side asked goes to the contact, on each
40491
+ * session (WISP 8xx § Accept). Nothing for any other chat.
40492
+ */
40493
+ sayContactAsker(linkId) {
40494
+ const link = this.links.get(linkId)?.link;
40495
+ const keys = link?.participationKeys;
40496
+ if (!link || !keys) return;
40497
+ this.contactAsks.proof(linkId, {
40498
+ inviter: keys.mine,
40499
+ joiner: keys.peer
40500
+ }).then((frame) => {
40501
+ if (frame) link.sendContactAsker(frame);
40502
+ }).catch(() => {});
40503
+ }
39296
40504
  /** Requests this profile sends through others' contact links (WISP 8xx). */
39297
40505
  contactAsks = new ContactAsks({
39298
40506
  online: () => this.networkOn,
@@ -40083,10 +41291,11 @@ var GhostlyNode = class GhostlyNode {
40083
41291
  this.groupsLoaded = true;
40084
41292
  this.groupsLoadedNow();
40085
41293
  this.emitState();
40086
- for (const stored of links) {
41294
+ for (let stored of links) {
40087
41295
  if (stored.group) continue;
40088
41296
  await this.settleHistory(stored.id);
40089
41297
  const messages = await db.getMessages(stored.id);
41298
+ stored = await this.settleJoinLine(stored, messages);
40090
41299
  const storedFiles = await fileStore.listForLink(stored.id);
40091
41300
  const notInterrupted = new Set(messages.flatMap((m) => m.sender === "me" && m.file && (m.delivery === "waiting" || m.via === "hold" && (m.delivery === "held" || m.delivery === "delivered")) ? [m.file.id] : []));
40092
41301
  for (const file of storedFiles) if (file.transfer && file.transfer.state !== "done" && !file.wire3 && !notInterrupted.has(file.id)) this.transfers.set(file.id, file.transfer.state === "transferring" ? {
@@ -40367,6 +41576,7 @@ var GhostlyNode = class GhostlyNode {
40367
41576
  this.startGroupEntries();
40368
41577
  this.prepareSpare(STARTUP_QUIET_MS);
40369
41578
  this.did.publishNow().catch(() => {});
41579
+ this.identities.networkBack();
40370
41580
  }
40371
41581
  this.emitState();
40372
41582
  if (failure) throw failure;
@@ -42229,6 +43439,7 @@ var GhostlyNode = class GhostlyNode {
42229
43439
  ...live.stored,
42230
43440
  removedRefs: withRemovedRef(live.stored.removedRefs, edit.id)
42231
43441
  };
43442
+ this.pinRemoved(linkId, edit.id);
42232
43443
  await this.writeDeletions(linkId, { removedRefs: live.stored.removedRefs });
42233
43444
  this.emitState();
42234
43445
  }
@@ -42502,6 +43713,7 @@ var GhostlyNode = class GhostlyNode {
42502
43713
  outbox = new Outbox({
42503
43714
  read: () => db.getMessages(linkId),
42504
43715
  get: (id) => db.getMessage(linkId, id),
43716
+ getMany: (ids) => db.getMessagesById(linkId, ids),
42505
43717
  update: async (id, delivery, error, extra) => {
42506
43718
  if (delivery === "delivered") await db.patchMessage(linkId, id, (message) => message.delivery === "delivered" ? null : {
42507
43719
  ...message.delivery && {
@@ -42789,9 +44001,13 @@ var GhostlyNode = class GhostlyNode {
42789
44001
  /**
42790
44002
  * The message of mine that carries a payment or a request, read by its id: `me_<the time the desk keeps for it>`.
42791
44003
  * The chat's history is read only when that row does not carry it, so it costs the same in a long chat as in a short one.
44004
+ * A contact's request or payment is never on a message of mine: nothing is read for it (the payee says a paid request
44005
+ * is paid again at each reconnect, `PaymentDesk.replay`).
42792
44006
  */
42793
44007
  async paymentMessage(linkId, paymentId) {
42794
- const at = this.desk.payment(paymentId)?.createdAt;
44008
+ const payment = this.desk.payment(paymentId);
44009
+ if (payment?.direction === "in") return void 0;
44010
+ const at = payment?.createdAt;
42795
44011
  const message = at === void 0 ? void 0 : await db.getMessage(linkId, `me_${at}`);
42796
44012
  if (message?.sender === "me" && message.paymentId === paymentId) return message;
42797
44013
  return (await db.getMessages(linkId)).find((m) => m.sender === "me" && m.paymentId === paymentId);
@@ -42896,6 +44112,23 @@ var GhostlyNode = class GhostlyNode {
42896
44112
  });
42897
44113
  return entry.done;
42898
44114
  }
44115
+ /**
44116
+ * A 1:1 chat's message `ref` was deleted for everyone: its pin is marked so (`StoredPin.removed`), shown as unpinned
44117
+ * however many removals come after and push `ref` out of `removedRefs`. Written at once, not merged with a burst's
44118
+ * write: a newer pin taken meanwhile writes after it.
44119
+ */
44120
+ pinRemoved(linkId, ref) {
44121
+ const live = this.links.get(linkId), pin = live?.stored.pin;
44122
+ if (!live || pin?.id !== ref || pin.removed) return;
44123
+ live.stored = {
44124
+ ...live.stored,
44125
+ pin: {
44126
+ ...pin,
44127
+ removed: true
44128
+ }
44129
+ };
44130
+ db.patchLink(linkId, { pin: live.stored.pin }).catch(() => {});
44131
+ }
42899
44132
  /** Whether a 1:1 chat's wire id names a message of mine: here, deleted here, removed, or a file or payment of mine. */
42900
44133
  async namesMine(linkId, wireId) {
42901
44134
  const stored = this.links.get(linkId)?.stored, row = `me_${wireId}`;
@@ -42907,7 +44140,7 @@ var GhostlyNode = class GhostlyNode {
42907
44140
  * Forgets one message of a chat on this device, the bytes of its file and any transfer of it, and keeps its id so a
42908
44141
  * copy that comes again is not stored: a delete here, or the contact's own removal (WISP 400 § Delete for everyone),
42909
44142
  * also of a message not here yet. `removed`: deleted for everyone (its row, when the caller read it), so the replies
42910
- * here that quote it lose its line too, and a pin of it goes (`removedRefs`).
44143
+ * here that quote it lose its line too, and a pin of it goes (`removedRefs`, and marked on the pin for good).
42911
44144
  */
42912
44145
  async forgetMessage(linkId, messageId, removed = false) {
42913
44146
  const live = this.links.get(linkId);
@@ -42918,15 +44151,24 @@ var GhostlyNode = class GhostlyNode {
42918
44151
  } : removed) : void 0;
42919
44152
  live.stored = {
42920
44153
  ...live.stored,
42921
- deletedIds: [...live.stored.deletedIds ?? [], messageId].slice(-500),
44154
+ deletedIds: withDeletedId(live.stored.deletedIds, messageId),
42922
44155
  ...ref && { removedRefs: withRemovedRef(live.stored.removedRefs, ref) }
42923
44156
  };
44157
+ if (ref) this.pinRemoved(linkId, ref);
42924
44158
  this.writeDeletions(linkId, {
42925
44159
  deletedIds: live.stored.deletedIds,
42926
44160
  ...ref && { removedRefs: live.stored.removedRefs }
42927
44161
  }).catch(() => {});
42928
44162
  this.hold.forget(linkId, messageId).catch(() => {});
42929
44163
  const message = await db.getMessage(linkId, messageId);
44164
+ if (message && contactJoinRow(message) && !live.stored.group && !live.stored.peerSpoke) {
44165
+ this.contactSpoke.add(live);
44166
+ live.stored = {
44167
+ ...live.stored,
44168
+ peerSpoke: true
44169
+ };
44170
+ await db.patchLink(linkId, { peerSpoke: true }).catch(() => {});
44171
+ }
42930
44172
  if (message?.paymentId && message.delivery === "waiting") await this.desk.withdraw(message.paymentId).catch(() => {});
42931
44173
  if (message?.paymentId && message.sender === "peer") await this.desk.dropReceipt(message.paymentId).catch(() => {});
42932
44174
  if (message?.sender === "me" && message.file && message.delivery === "waiting" && (message.fileOnFloor === "sent" || message.fileOnFloor === "seen")) {
@@ -43877,6 +45119,13 @@ var GhostlyNode = class GhostlyNode {
43877
45119
  declineGroupInvitation({ groupId }) {
43878
45120
  return this.groups.decline(groupId);
43879
45121
  }
45122
+ keepGroup({ groupId }) {
45123
+ return this.groups.keepGroup(groupId);
45124
+ }
45125
+ switchGroup({ groupId, to }) {
45126
+ if (typeof to !== "string") throw new Error("No other group under this id");
45127
+ return this.groups.switchGroup(groupId, to);
45128
+ }
43880
45129
  async enableGroupLink({ groupId, reset }) {
43881
45130
  return { link: await this.groups.enableLink(groupId, reset === true) };
43882
45131
  }
@@ -44464,6 +45713,11 @@ var GhostlyNode = class GhostlyNode {
44464
45713
  }
44465
45714
  /** Ranges the contact's apps asked, by chat, app and this engine's number for the ask, until a page answers them. */
44466
45715
  appRanges = /* @__PURE__ */ new Map();
45716
+ /**
45717
+ * Asks the session no longer serves (cancelled, the contact's app closed, the session ended) that a page may still be
45718
+ * reading: its answer sends nothing, and only gives the place back. At most 4 per chat app, the places they hold.
45719
+ */
45720
+ appRangesStopped = /* @__PURE__ */ new Map();
44467
45721
  nextAppRangeAsk = 0;
44468
45722
  /**
44469
45723
  * Every task stays until a page answers it, live or not: until the link settles it, it holds one of its app's places
@@ -44473,7 +45727,11 @@ var GhostlyNode = class GhostlyNode {
44473
45727
  */
44474
45728
  appRangeAsked(linkId, task) {
44475
45729
  const link = this.links.get(linkId)?.link;
44476
- for (const [key, held] of this.appRanges) if (key.startsWith(`${linkId} `) && (!link || !link.holdsAppRange(held))) this.appRanges.delete(key);
45730
+ for (const [key, held] of this.appRanges) if (key.startsWith(`${linkId} `) && !(held.live && link?.holdsAppRange(held))) {
45731
+ this.appRanges.delete(key);
45732
+ if (link?.holdsAppRange(held)) this.appRangesStopped.set(key, held);
45733
+ }
45734
+ for (const [key, held] of this.appRangesStopped) if (key.startsWith(`${linkId} `) && !link?.holdsAppRange(held)) this.appRangesStopped.delete(key);
44477
45735
  const request = ++this.nextAppRangeAsk;
44478
45736
  this.appRanges.set(`${linkId} ${task.app} ${request}`, task);
44479
45737
  const { app, serve, file, offset, length } = task;
@@ -44508,8 +45766,9 @@ var GhostlyNode = class GhostlyNode {
44508
45766
  /** A page's answer to an `app-range` it served: the bytes and the file's size go to the contact, or why they cannot. */
44509
45767
  async appRangeAnswer({ linkId, app, request, bytes, size, error }) {
44510
45768
  if (!this.appsOn) throw this.appsOff();
44511
- const key = `${linkId} ${app} ${request}`, task = this.appRanges.get(key);
45769
+ const key = `${linkId} ${app} ${request}`, task = this.appRanges.get(key) ?? this.appRangesStopped.get(key);
44512
45770
  this.appRanges.delete(key);
45771
+ this.appRangesStopped.delete(key);
44513
45772
  if (!task) return;
44514
45773
  const serving = this.appServing.get(`${linkId} ${app}`);
44515
45774
  const stopped = serving && await this.appChatRunnable(serving.ref, serving.digest).then(() => false, () => true);
@@ -44552,11 +45811,14 @@ var GhostlyNode = class GhostlyNode {
44552
45811
  }
44553
45812
  }
44554
45813
  /** Keeps a pin of a 1:1 chat when it is newer than the chat's; `out`: mine, to say until the contact confirms it. */
44555
- async keepLinkPin(linkId, pin, out) {
45814
+ async keepLinkPin(linkId, came, out) {
44556
45815
  const live = this.links.get(linkId);
44557
- if (!live || !pinIsNewer(live.stored.pin, pin)) return;
45816
+ if (!live || !pinIsNewer(live.stored.pin, came)) return;
44558
45817
  const patch = {
44559
- pin,
45818
+ pin: came.id && live.stored.removedRefs?.includes(came.id) ? {
45819
+ ...came,
45820
+ removed: true
45821
+ } : came,
44560
45822
  ...out && { pinOut: out }
44561
45823
  };
44562
45824
  live.stored = {
@@ -44596,7 +45858,7 @@ var GhostlyNode = class GhostlyNode {
44596
45858
  */
44597
45859
  async pinnedRowCame(linkId, ids) {
44598
45860
  const live = this.links.get(linkId), pin = live?.stored.pin;
44599
- if (!live || live.stored.group || !pin?.id || pin.messageId) return;
45861
+ if (!live || live.stored.group || !pin?.id || pin.messageId || pin.removed) return;
44600
45862
  for (const id of new Set(ids)) {
44601
45863
  const row = await db.getMessage(linkId, id);
44602
45864
  if (!row || replyRef(row) !== pin.id) continue;
@@ -45864,6 +47126,7 @@ var GhostlyNode = class GhostlyNode {
45864
47126
  this.startGroupEntries();
45865
47127
  this.prepareSpare(STARTUP_QUIET_MS);
45866
47128
  this.did.publishNow().catch(() => {});
47129
+ this.identities.networkBack();
45867
47130
  if (!this.options.singleDevice && knownDeviceGate()?.state === "active") this.startDeviceSet({ justRead: true }).catch(() => {});
45868
47131
  } else if (wasOnline && this.networkOn && relayOnlyChanged) await this.restartLinksForRelayOnly();
45869
47132
  if (relayOnlyChanged && this.settings.relayOnly !== true) this.hold.wake();
@@ -47434,6 +48697,9 @@ var GhostlyNode = class GhostlyNode {
47434
48697
  onHold: (state) => this.hold.peerSaid(linkId, state),
47435
48698
  onPeerProof: void 0,
47436
48699
  onIdentityProof: stored.profile ? (frame) => this.identities.frame(linkId, frame) : void 0,
48700
+ onContactAsker: stored.profile ? (frame, keys) => {
48701
+ this.contactAskerHeard(linkId, frame, keys).catch(() => {});
48702
+ } : void 0,
47437
48703
  onTransportsChanged: () => {
47438
48704
  if (live.link && !live.link.availableTransports.includes("hyperdht/1")) this.retryRelayLater();
47439
48705
  this.capsChanged(linkId);
@@ -47463,10 +48729,10 @@ var GhostlyNode = class GhostlyNode {
47463
48729
  onLiveAttempt: () => this.emitState(),
47464
48730
  onRtt: (ms) => this.noteRtt(live, ms),
47465
48731
  onDiscoveryError: (error) => {
47466
- if ((error ?? void 0) !== live.discoveryError) {
47467
- live.discoveryError = error ?? void 0;
47468
- this.emitState();
47469
- }
48732
+ if ((error ?? void 0) === live.discoveryError) return;
48733
+ live.discoveryError = error ?? void 0;
48734
+ if (live.goneListener && this.contactUnread(live)) this.listenAgain(live);
48735
+ this.emitState();
47470
48736
  },
47471
48737
  onTransportDiscovery: async (peerDescriptors, peerTransports, peerFallback) => {
47472
48738
  const patch = {
@@ -47483,8 +48749,10 @@ var GhostlyNode = class GhostlyNode {
47483
48749
  },
47484
48750
  onPairingState: (state) => {
47485
48751
  live.pairing = state;
47486
- if (state.status === "ready") this.identities.ready(linkId);
47487
- else this.identities.closed(linkId);
48752
+ if (state.status === "ready") {
48753
+ this.identities.ready(linkId);
48754
+ this.sayContactAsker(linkId);
48755
+ } else this.identities.closed(linkId);
47488
48756
  if (state.status === "ready" && live.link) this.hold.rememberPeerMethods(linkId, PAYMENT_METHODS.filter((m) => live.link.peerChoosesPayment(m))).catch(() => {});
47489
48757
  live.proofs?.stop();
47490
48758
  this.observeTransport(linkId);
@@ -47551,6 +48819,7 @@ var GhostlyNode = class GhostlyNode {
47551
48819
  this.wakeLimiter.reset(linkId);
47552
48820
  this.desk.replay(linkId).catch(() => {}).then(() => this.sendWaiting(linkId)).catch(() => {});
47553
48821
  this.identities.ready(linkId);
48822
+ this.sayContactAsker(linkId);
47554
48823
  }
47555
48824
  if (state !== "open") {
47556
48825
  live.proofs?.stop();
@@ -47587,6 +48856,10 @@ var GhostlyNode = class GhostlyNode {
47587
48856
  onPresence: (presence) => {
47588
48857
  let same = samePresence(live.presence, presence);
47589
48858
  live.presence = presence;
48859
+ if (presence.online) {
48860
+ live.onlineSeenAt = Date.now();
48861
+ if (live.goneListener) this.listenAgain(live);
48862
+ }
47590
48863
  if (!stored.profile && presence.nick && presence.nick !== live.stored.peerNick) {
47591
48864
  live.stored = {
47592
48865
  ...live.stored,
@@ -47807,7 +49080,7 @@ var GhostlyNode = class GhostlyNode {
47807
49080
  nativeFactoriesFor(relayOnly) {
47808
49081
  const relay = relayOnly || this.relaysHyperdhtNatively ? this.hyperdhtRelay : "";
47809
49082
  return {
47810
- ...relay ? { "hyperdht/1": async (seedB64) => (await import("./hyperdhtRelay-D185dETu.js")).createRelayedHyperEndpoint(seedB64, relay) } : {},
49083
+ ...relay ? { "hyperdht/1": async (seedB64) => (await import("./hyperdhtRelay-Ce42sR8x.js")).createRelayedHyperEndpoint(seedB64, relay) } : {},
47811
49084
  ...relayOnly ? {} : this.options.nativeTransports,
47812
49085
  ...this.ownIrohRelays && !relayOnly ? { "iroh/1": (seedB64) => this.options.nativeTransports["iroh/1"](seedB64, this.settings.irohRelays?.length ? { relays: [...this.settings.irohRelays] } : {}) } : {},
47813
49086
  ...this.options.irohWeb ? { "iroh/1": (seedB64) => createIrohWebEndpoint(seedB64, { relays: this.irohRelays }) } : {}
@@ -47903,9 +49176,21 @@ var GhostlyNode = class GhostlyNode {
47903
49176
  if (!this.relaysHyperdht || !this.hyperdhtRelay || this.relayRetry || this.shuttingDown) return;
47904
49177
  this.relayRetry = setTimeout(() => {
47905
49178
  this.relayRetry = null;
47906
- for (const [linkId, live] of this.links) if (live.link && live.stored.profile && (!live.stored.group || this.keepsGroupNative(live.stored)) && live.stored.deliveryMode !== "dht" && !live.link.availableTransports.includes("hyperdht/1") && this.keepsNativeEndpoints(linkId, live.stored)) this.ensureNativeEndpoints(linkId);
49179
+ const held = (linkId) => this.relayHeld(linkId, Date.now());
49180
+ const ids = [...this.links.keys()].sort((a, b) => Number(held(b)) - Number(held(a)));
49181
+ for (const linkId of ids) {
49182
+ const live = this.links.get(linkId);
49183
+ if (live.link && live.stored.profile && (!live.stored.group || this.keepsGroupNative(live.stored)) && live.stored.deliveryMode !== "dht" && !live.link.availableTransports.includes("hyperdht/1") && this.keepsNativeEndpoints(linkId, live.stored)) this.ensureNativeEndpoints(linkId);
49184
+ }
47907
49185
  }, RELAY_RETRY_MS / 2 + Math.random() * RELAY_RETRY_MS);
47908
49186
  }
49187
+ /** Chats whose relayed HyperDHT listener went with the relay connection, by link id: until when they keep first claim on a slot. */
49188
+ relayHolds = /* @__PURE__ */ new Map();
49189
+ relayHeld(linkId, now) {
49190
+ const until = this.relayHolds.get(linkId);
49191
+ if (until !== void 0 && now >= until) this.relayHolds.delete(linkId);
49192
+ return until !== void 0 && now < until;
49193
+ }
47909
49194
  /** A new relay (or none): chats give up their endpoints on the old one, as soon as none of them carries a session. */
47910
49195
  async relayChanged() {
47911
49196
  if (!this.relaysHyperdht) return;
@@ -48086,7 +49371,7 @@ var GhostlyNode = class GhostlyNode {
48086
49371
  else this.groupNativeWaiting.delete(linkId);
48087
49372
  }
48088
49373
  if ((group ? this.keepsGroupNative(live.stored) : this.keepsNativeEndpoints(linkId, live.stored)) && full.includes("failed")) {
48089
- const wait = Math.min(Math.max(NATIVE_RETRY_MS, (this.nativeFailed.get(linkId)?.wait ?? 0) * 2), NATIVE_FAILED_MAX_MS);
49374
+ const wait = this.relayHeld(linkId, Date.now()) ? RELAY_HOLD_RETRY_MS : Math.min(Math.max(NATIVE_RETRY_MS, (this.nativeFailed.get(linkId)?.wait ?? 0) * 2), NATIVE_FAILED_MAX_MS);
48090
49375
  this.nativeFailed.set(linkId, {
48091
49376
  at: Date.now() + wait,
48092
49377
  wait
@@ -48168,6 +49453,10 @@ var GhostlyNode = class GhostlyNode {
48168
49453
  if (group && !this.keepsGroupNative(live.stored)) return false;
48169
49454
  if (group && !this.groupNatives(live.stored).includes(key)) return false;
48170
49455
  if (link.availableTransports.includes(key)) return false;
49456
+ if (key === GONE_TRANSPORT && !inUse && this.contactGone(live, Date.now())) {
49457
+ live.goneListener = true;
49458
+ return false;
49459
+ }
48171
49460
  live.transportErrors ??= {};
48172
49461
  try {
48173
49462
  const owners = [...this.links.values()].filter((other) => other.link?.availableTransports.includes(key));
@@ -48187,6 +49476,21 @@ var GhostlyNode = class GhostlyNode {
48187
49476
  const used = (other) => this.lastUsed(other, viewOf);
48188
49477
  const extra = (other) => !!other.stored.group && !other.stored.groupEntry && !onScreen(other) && anchorOf(other.stored.group) !== other && !this.chosenByPeer(other, key);
48189
49478
  const full = owners.length >= slots, entry = !!live.stored.groupEntry;
49479
+ const claiming = key === "hyperdht/1" && this.relayHeld(linkId, now);
49480
+ const reserved = key !== "hyperdht/1" || inUse || this.activeLinkId === linkId ? 0 : [...this.relayHolds.keys()].filter((id) => {
49481
+ const other = this.links.get(id)?.link;
49482
+ return id !== linkId && this.relayHeld(id, now) && !!other && !other.availableTransports.includes(key);
49483
+ }).length;
49484
+ const free = slots - owners.length, chatFree = this.chatNativeSlots(key) - (owners.length - groups);
49485
+ if (reserved && free > 0 && (group || chatFree > 0) && (free <= reserved || !group && chatFree <= reserved)) {
49486
+ traceLink(live.myPubKeyZ32, "native-held-for-relay", {
49487
+ transport: key,
49488
+ reserved,
49489
+ group
49490
+ });
49491
+ if (group) return "no-slot";
49492
+ throw new Error("All native connection slots are in use. This chat takes one once a chat live over one has been quiet for 2 minutes. Disconnect a native connection in another chat to free one now.");
49493
+ }
48190
49494
  if (group && (entry || extra(live)) && (full || groups >= this.groupNativeSlots(key) || !entry && !anchorOf(live.stored.group)?.link?.availableTransports.includes(key))) return "no-slot";
48191
49495
  if (full || !group && owners.length - groups >= this.chatNativeSlots(key)) {
48192
49496
  const paired = !group && live.pairedAt !== void 0 && now - live.pairedAt < 6e5 ? live.pairedAt : void 0;
@@ -48214,6 +49518,7 @@ var GhostlyNode = class GhostlyNode {
48214
49518
  group
48215
49519
  });
48216
49520
  if (group) return "no-slot";
49521
+ if (claiming) return "failed";
48217
49522
  if (this.activeLinkId === linkId) this.retryActiveSlot(linkId);
48218
49523
  throw new Error("All native connection slots are in use. This chat takes one once a chat live over one has been quiet for 2 minutes. Disconnect a native connection in another chat to free one now.");
48219
49524
  } else {
@@ -48249,6 +49554,18 @@ var GhostlyNode = class GhostlyNode {
48249
49554
  return false;
48250
49555
  }
48251
49556
  link.registerEndpoint(endpoint);
49557
+ this.relayHolds.delete(linkId);
49558
+ if (key === "hyperdht/1" && this.relaysHyperdht) {
49559
+ const gone = endpoint.onUnavailable;
49560
+ endpoint.onUnavailable = () => {
49561
+ if (this.links.get(linkId)?.link === link) this.relayHolds.set(linkId, Date.now() + RELAY_HOLD_MS);
49562
+ gone?.();
49563
+ };
49564
+ }
49565
+ if (key === GONE_TRANSPORT && live.goneListener) {
49566
+ live.goneListener = false;
49567
+ link.knockOnReturn(key);
49568
+ }
48252
49569
  if (group) live.nativeUpAt = {
48253
49570
  ...live.nativeUpAt,
48254
49571
  [key]: Date.now()
@@ -48331,6 +49648,53 @@ var GhostlyNode = class GhostlyNode {
48331
49648
  }
48332
49649
  /** Group links waiting for a free native slot (`ensureNativeEndpoints`), by link id. */
48333
49650
  groupNativeWaiting = /* @__PURE__ */ new Set();
49651
+ /**
49652
+ * Whether a 1:1 chat's contact is gone: no packet read in this run that says it is online for `NATIVE_GONE_MS` (since
49653
+ * the chat started, before the first), and the chat neither live, nor on screen, nor used in that time (a text either
49654
+ * way, opened), nor paired in this run and not live yet. Nor while its packet cannot be read (`contactUnread`): the
49655
+ * contact may be back and only out of sight. With the Pkarr relays down, a contact back on the HyperDHT dialled a
49656
+ * listener let go here, and no read said it was online: the chat stayed offline for the whole outage, both apps up.
49657
+ */
49658
+ contactGone(live, now) {
49659
+ if (live.stored.group || live.presence.online || live.link?.isDataLinkOpen || live.pairedAt !== void 0) return false;
49660
+ if (this.contactUnread(live)) return false;
49661
+ if (live.stored.id === this.activeLinkId) return false;
49662
+ return now - Math.max(live.onlineSeenAt ?? 0, this.openedAt.get(live.stored.id) ?? 0, live.lastMessageAt) >= NATIVE_GONE_MS;
49663
+ }
49664
+ /** The last read of the contact's packet failed (the Pkarr relays out of reach), as its link says (`onDiscoveryError`). */
49665
+ contactUnread(live) {
49666
+ return !!live.discoveryError?.includes("Could not read discovery");
49667
+ }
49668
+ goneCheckAt = 0;
49669
+ /**
49670
+ * Every `NATIVE_GONE_CHECK_MS`, the 1:1 chats whose contact is gone (`contactGone`) let their HyperDHT listener go, as
49671
+ * one whose slot another chat takes does (its record then says it runs none). Not one dialling or switching
49672
+ * (`canReleaseEndpoint`).
49673
+ */
49674
+ releaseGoneListeners() {
49675
+ const now = Date.now();
49676
+ if (!this.nativeFactories[GONE_TRANSPORT] || now < this.goneCheckAt) return;
49677
+ this.goneCheckAt = now + NATIVE_GONE_CHECK_MS;
49678
+ for (const live of this.links.values()) {
49679
+ const link = live.link;
49680
+ if (!link || !link.availableTransports.includes(GONE_TRANSPORT) || !this.contactGone(live, now) || !link.canReleaseEndpoint(GONE_TRANSPORT)) continue;
49681
+ live.goneListener = true;
49682
+ traceLink(live.myPubKeyZ32, "native-gone", {
49683
+ transport: GONE_TRANSPORT,
49684
+ seen: now - (live.onlineSeenAt ?? 0)
49685
+ });
49686
+ link.releaseEndpoint(GONE_TRANSPORT).then(() => this.emitState(), () => {});
49687
+ }
49688
+ }
49689
+ /**
49690
+ * The contact of a chat whose HyperDHT listener was let go is back (`releaseGoneListeners`): it listens again (and
49691
+ * dials the contact once it does, `startNativeEndpoint`).
49692
+ */
49693
+ listenAgain(live) {
49694
+ const link = live.link;
49695
+ if (this.shuttingDown || !link || link.availableTransports.includes(GONE_TRANSPORT) || !this.keepsNativeEndpoints(live.stored.id, live.stored)) return;
49696
+ this.ensureNativeEndpoints(live.stored.id);
49697
+ }
48334
49698
  groupNativeRetryAt = 0;
48335
49699
  /** Chats and group links whose native listener failed to start, by link id: when each tries again, and how long it waited last. */
48336
49700
  nativeFailed = /* @__PURE__ */ new Map();
@@ -48343,6 +49707,7 @@ var GhostlyNode = class GhostlyNode {
48343
49707
  retryNative() {
48344
49708
  this.groupAnchorsAnswered();
48345
49709
  this.moveNative();
49710
+ this.releaseGoneListeners();
48346
49711
  const now = Date.now();
48347
49712
  for (const [linkId, failed] of this.nativeFailed) {
48348
49713
  if (now < failed.at || this.nativeRetrying.has(linkId)) continue;
@@ -48512,6 +49877,50 @@ var GhostlyNode = class GhostlyNode {
48512
49877
  await this.storeNewMessage(message);
48513
49878
  }
48514
49879
  /**
49880
+ * Whether this row is the contact's first in a 1:1 chat in the joined line's words, the only one of theirs that may be
49881
+ * drawn as that line (`StoredMessage.joinLine`). Not their first row: they say it once the chat first goes live (WISP
49882
+ * 1100), and what they wrote before that may come first. False at once for any later row in those words: the chat is
49883
+ * marked (`peerSpoke`) as the first one comes, before anything is awaited, so of two stored together only the first
49884
+ * is. A chat not marked yet is looked at once, for rows of the contact's this engine did not see come (a history
49885
+ * brought in while it runs).
49886
+ */
49887
+ firstContactRow(live, message) {
49888
+ const { stored } = live;
49889
+ if (stored.group || message.linkId !== stored.id || message.linkId.startsWith("group:") || !contactJoinRow(message)) return false;
49890
+ if (stored.peerSpoke || this.contactSpoke.has(live)) return false;
49891
+ this.contactSpoke.add(live);
49892
+ live.stored = {
49893
+ ...stored,
49894
+ peerSpoke: true
49895
+ };
49896
+ const marked = db.patchLink(stored.id, { peerSpoke: true }).catch(() => {});
49897
+ return Promise.all([contactJoinRowStored(stored.id, message.id), marked]).then(([had]) => !had, () => false);
49898
+ }
49899
+ /**
49900
+ * A chat stored before `peerSpoke` was kept, as the engine starts: the contact's oldest row left there in the joined
49901
+ * line's words is that line (as it was drawn before), and no later row of theirs is. Done once: the chat is marked.
49902
+ * One with no such row waits for it, whatever else of theirs was deleted: a deleted id does not say what its row said,
49903
+ * and one in those words deleted since `peerSpoke` was kept marked the chat as it went (`forgetMessage`).
49904
+ */
49905
+ async settleJoinLine(stored, messages) {
49906
+ if (stored.peerSpoke || stored.group) return stored;
49907
+ const at = messages.findIndex(contactJoinRow);
49908
+ if (at < 0) return stored;
49909
+ const first = messages[at];
49910
+ if (!first.joinLine) {
49911
+ await db.patchMessage(stored.id, first.id, () => ({ joinLine: true }));
49912
+ messages[at] = {
49913
+ ...first,
49914
+ joinLine: true
49915
+ };
49916
+ }
49917
+ await db.patchLink(stored.id, { peerSpoke: true });
49918
+ return {
49919
+ ...stored,
49920
+ peerSpoke: true
49921
+ };
49922
+ }
49923
+ /**
48515
49924
  * Stores a message; false when it was there already (or deleted here): nothing new came. `straight`: a group's,
48516
49925
  * straight from its author (`clockSample`). `place`: as `placed`.
48517
49926
  */
@@ -48535,7 +49944,12 @@ var GhostlyNode = class GhostlyNode {
48535
49944
  const live = this.links.get(message.linkId);
48536
49945
  if (live?.stored.deletedIds?.includes(message.id)) return false;
48537
49946
  if (message.linkId.startsWith("group:") && this.groups.isRemoved(message.linkId.slice(6), message.id)) return false;
49947
+ const first = live ? this.firstContactRow(live, message) : false;
48538
49948
  message = await this.resolveReply(message);
49949
+ if (first && isJoinNotice(message.text) && await first) message = {
49950
+ ...message,
49951
+ joinLine: true
49952
+ };
48539
49953
  if (message.sender === "peer" && live && !message.details?.received) message = {
48540
49954
  ...message,
48541
49955
  details: {
@@ -48612,7 +50026,7 @@ var GhostlyNode = class GhostlyNode {
48612
50026
  ...stored.wakeMuted && { wakeMuted: true }
48613
50027
  },
48614
50028
  ...this.reactionNotes.has(stored.id) && { lastReaction: this.reactionNotes.get(stored.id) },
48615
- ...stored.pin && { pin: pinView(stored.pin.id && stored.removedRefs?.includes(stored.pin.id) ? {
50029
+ ...stored.pin && { pin: pinView(stored.pin.id && (stored.pin.removed || stored.removedRefs?.includes(stored.pin.id)) ? {
48616
50030
  ...stored.pin,
48617
50031
  id: "",
48618
50032
  messageId: void 0
@@ -49032,4 +50446,4 @@ function signalKind(signal) {
49032
50446
  //#endregion
49033
50447
  export { EngineServer };
49034
50448
 
49035
- //# sourceMappingURL=server-Dw1o8z1o.js.map
50449
+ //# sourceMappingURL=server-BZnsm5X5.js.map