@ghostlytools/cli 1.4.4 → 1.5.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 (88) hide show
  1. package/README.md +14 -7
  2. package/dist/assets/{api-Cr5NjA-g.js → api-C_IHKsrl.js} +2 -2
  3. package/dist/assets/{api-N5IiCxB7.js → api-ClHM_G5A.js} +87 -60
  4. package/dist/assets/api-ClHM_G5A.js.map +1 -0
  5. package/dist/assets/{apiKit-BDB40JPK.js → apiKit-gS-yfb25.js} +2 -2
  6. package/dist/assets/{apiKit-BDB40JPK.js.map → apiKit-gS-yfb25.js.map} +1 -1
  7. package/dist/assets/{apps-Cf_TQYPs.js → apps-DP8pElH-.js} +2 -2
  8. package/dist/assets/{apps-Cf_TQYPs.js.map → apps-DP8pElH-.js.map} +1 -1
  9. package/dist/assets/{apps-C3H4yttJ.js → apps-DyihkNO-.js} +1 -1
  10. package/dist/assets/{arkade-DCovElLt.js → arkade-GzJoov-w.js} +2 -2
  11. package/dist/assets/{arkade-DCovElLt.js.map → arkade-GzJoov-w.js.map} +1 -1
  12. package/dist/assets/{backup-lrj6hQ3t.js → backup-A_C4hYNO.js} +1 -1
  13. package/dist/assets/{backup-Dnh7GFXh.js → backup-DKDXkaS1.js} +6 -6
  14. package/dist/assets/{backup-Dnh7GFXh.js.map → backup-DKDXkaS1.js.map} +1 -1
  15. package/dist/assets/{blobFiles-B0rNnHlO.js → blobFiles-1wUBd8ZD.js} +3 -3
  16. package/dist/assets/{blobFiles-B0rNnHlO.js.map → blobFiles-1wUBd8ZD.js.map} +1 -1
  17. package/dist/assets/{buttons-BCzrFo-d.js → buttons-BDw8cqDq.js} +3 -3
  18. package/dist/assets/{buttons-BCzrFo-d.js.map → buttons-BDw8cqDq.js.map} +1 -1
  19. package/dist/assets/buttons-CNkxiN2c.js +2 -0
  20. package/dist/assets/daemonProof-CWTVNUmr.js +254 -0
  21. package/dist/assets/daemonProof-CWTVNUmr.js.map +1 -0
  22. package/dist/assets/{envelope-BKSHUJnt.js → envelope-DEvU5FA9.js} +2 -2
  23. package/dist/assets/{envelope-BKSHUJnt.js.map → envelope-DEvU5FA9.js.map} +1 -1
  24. package/dist/assets/{fileBytes-B-fqGdEd.js → fileBytes-B8eTZfAT.js} +3 -3
  25. package/dist/assets/{fileBytes-B-fqGdEd.js.map → fileBytes-B8eTZfAT.js.map} +1 -1
  26. package/dist/assets/{fileBytes-C2jycN_7.js → fileBytes-gTd_8l-P.js} +1 -1
  27. package/dist/assets/{fileBytes-D6fqFQEX.js → fileBytes-uRqLyxa0.js} +2 -2
  28. package/dist/assets/{fileBytes-D6fqFQEX.js.map → fileBytes-uRqLyxa0.js.map} +1 -1
  29. package/dist/assets/{fileBytesIdb-_HnxdacI.js → fileBytesIdb-BIFKtgln.js} +3 -3
  30. package/dist/assets/{fileBytesIdb-_HnxdacI.js.map → fileBytesIdb-BIFKtgln.js.map} +1 -1
  31. package/dist/assets/fileBytesIdb-BVVr_rWX.js +2 -0
  32. package/dist/assets/{fileBytesOpfs-p_CANncD.js → fileBytesOpfs-ChrHcCVV.js} +3 -3
  33. package/dist/assets/{fileBytesOpfs-p_CANncD.js.map → fileBytesOpfs-ChrHcCVV.js.map} +1 -1
  34. package/dist/assets/{groupFiles-Dw0BA5-Z.js → groupFiles-Cr4Gj9-R.js} +49 -16
  35. package/dist/assets/groupFiles-Cr4Gj9-R.js.map +1 -0
  36. package/dist/assets/{host-BjTfNkxj.js → host-D0MIWyOe.js} +47 -129
  37. package/dist/assets/host-D0MIWyOe.js.map +1 -0
  38. package/dist/assets/{hyperdhtRelay-CmqjYDch.js → hyperdhtRelay-SBo4aoMk.js} +2 -2
  39. package/dist/assets/{hyperdhtRelay-CmqjYDch.js.map → hyperdhtRelay-SBo4aoMk.js.map} +1 -1
  40. package/dist/assets/{idb-CMVgtn2k.js → idb-BJARz3Qi.js} +5 -3
  41. package/dist/assets/idb-BJARz3Qi.js.map +1 -0
  42. package/dist/assets/{irohWeb-4Q4EdaCa.js → irohWeb-D2WaYPdN.js} +2 -2
  43. package/dist/assets/{irohWeb-4Q4EdaCa.js.map → irohWeb-D2WaYPdN.js.map} +1 -1
  44. package/dist/assets/{main-Dd5INTcu.js → main-DUG0nGLw.js} +279 -67
  45. package/dist/assets/main-DUG0nGLw.js.map +1 -0
  46. package/dist/assets/{mainline-o7bmeZsk.js → mainline-B8NGRodL.js} +79 -15
  47. package/dist/assets/mainline-B8NGRodL.js.map +1 -0
  48. package/dist/assets/{networkReason-ve6jyxIs.js → networkReason-BAnNO1Ji.js} +3 -3
  49. package/dist/assets/{networkReason-ve6jyxIs.js.map → networkReason-BAnNO1Ji.js.map} +1 -1
  50. package/dist/assets/{nwc-CL27LJx-.js → nwc-DQT3rx-s.js} +3 -3
  51. package/dist/assets/{nwc-CL27LJx-.js.map → nwc-DQT3rx-s.js.map} +1 -1
  52. package/dist/assets/{nwcProvider-CIlvpLT5.js → nwcProvider-Dq647EAl.js} +2 -2
  53. package/dist/assets/{nwcProvider-CIlvpLT5.js.map → nwcProvider-Dq647EAl.js.map} +1 -1
  54. package/dist/assets/{profiles-DSxPYdlU.js → profiles-BehWURA9.js} +18 -4
  55. package/dist/assets/profiles-BehWURA9.js.map +1 -0
  56. package/dist/assets/{registry-dG_Wm7fC.js → registry-DFiOxH5q.js} +1 -1
  57. package/dist/assets/{registry-CWJRfG2e.js → registry-ieI8INKT.js} +3 -3
  58. package/dist/assets/registry-ieI8INKT.js.map +1 -0
  59. package/dist/assets/{resolve-BDoQLkJR.js → resolve-C39pc4Kf.js} +2 -2
  60. package/dist/assets/{resolve-BDoQLkJR.js.map → resolve-C39pc4Kf.js.map} +1 -1
  61. package/dist/assets/{restoredRows-DeBImGRd.js → restoredRows-DGuKtIBz.js} +2 -2
  62. package/dist/assets/{restoredRows-DeBImGRd.js.map → restoredRows-DGuKtIBz.js.map} +1 -1
  63. package/dist/assets/{server-CYCzKx-R.js → server-DIICuvgy.js} +1150 -192
  64. package/dist/assets/server-DIICuvgy.js.map +1 -0
  65. package/dist/assets/{src-D1X4uVPW.js → src-CwMTZ5Hj.js} +864 -82
  66. package/dist/assets/src-CwMTZ5Hj.js.map +1 -0
  67. package/dist/assets/{usdt-Byi5OFic.js → usdt-CxSyuXq4.js} +3 -3
  68. package/dist/assets/{usdt-Byi5OFic.js.map → usdt-CxSyuXq4.js.map} +1 -1
  69. package/dist/assets/{turnRefs-BJeWWYlJ.js → words-31VaDW5h.js} +61 -3
  70. package/dist/assets/words-31VaDW5h.js.map +1 -0
  71. package/dist/ghostly.mjs +1 -1
  72. package/package.json +1 -1
  73. package/skills/ghostly/scripts/status +3 -2
  74. package/dist/assets/api-N5IiCxB7.js.map +0 -1
  75. package/dist/assets/buttons-B5dhQKnU.js +0 -2
  76. package/dist/assets/daemonProof-B53VnZ1Z.js +0 -100
  77. package/dist/assets/daemonProof-B53VnZ1Z.js.map +0 -1
  78. package/dist/assets/fileBytesIdb-DOxm_BKt.js +0 -2
  79. package/dist/assets/groupFiles-Dw0BA5-Z.js.map +0 -1
  80. package/dist/assets/host-BjTfNkxj.js.map +0 -1
  81. package/dist/assets/idb-CMVgtn2k.js.map +0 -1
  82. package/dist/assets/main-Dd5INTcu.js.map +0 -1
  83. package/dist/assets/mainline-o7bmeZsk.js.map +0 -1
  84. package/dist/assets/profiles-DSxPYdlU.js.map +0 -1
  85. package/dist/assets/registry-CWJRfG2e.js.map +0 -1
  86. package/dist/assets/server-CYCzKx-R.js.map +0 -1
  87. package/dist/assets/src-D1X4uVPW.js.map +0 -1
  88. package/dist/assets/turnRefs-BJeWWYlJ.js.map +0 -1
@@ -1,16 +1,16 @@
1
1
  import { n as traceJoin } from "./joinTrace-CjRDFy85.js";
2
- import { $a as GROUP_MEMBER_CAP, $c as DEVICES_CAPABILITY, $i as DHT_MESSAGE_TTL, $l as randomBytes, $o as handoffContextProof, $r as chatAppId, $s as knockSlotIdentity, A as knockRecords, Aa as wireReaction, Ac as isAppRef, Ai as capsDescriptors, Al as normalizeRelayUrl, An as findEndpoint, Ar as transferStalled, B as GROUP_READ_NOTE, Bc as createContactLink, Bi as identityStatement, Bn as engineError, Bo as HANDOFF_OFFER, Br as pinIsNewer, Bs as readEnrollHello, C as decodeCommunityLink, Ca as ReactionWindow, Cl as turnKeys, Co as RTC_CONFIG, Cr as readBeacon, Cs as readSetUpdate, D as encodeGroupEntryLink, Da as reactionIsNewer, Dl as DEFAULT_RELAYS, Dn as ENDPOINT, Dr as ChatFiles, Ds as verifySetUpdate, E as decodeGroupEntryLink, Ea as reactionEmoji, Ec as appRef, El as turnVerifierMark, En as decodeBolt11, Er as shouldBeHub, Es as signTombstone, F as groupWakeFrame, Fc as parseImageMeta, Fl as withRequestOptions, Fn as INVITE_TAKEN, Fo as HANDOFF_ACK, Fr as typingActivity, Fs as enrollDoneFrame, G as GROUP_EDIT_TEXT_BYTES, Ga as sameButtonText, Gc as readDeviceInvite, Gi as PeerProofs, Gl as publicKeyFromZ32, Go as HANDOFF_VERIFIED, Gr as deviceWakeRequest, Gs as newInbox, Gt as encodeDidDhtPacket, H as frameBytes, Hc as readContactLink, Hi as receivedIdentityStatus, Hl as createIdentity, Hn as parseEngineError, Ho as HANDOFF_PIECE_BYTES, Hr as readPin, Hs as clearMissed, Ht as didDhtDocument, I as groupWakes, Ii as IdentityExchange, Il as PacketTooLargeError, In as LIVENESS_PING_MS, Io as HANDOFF_CANCEL, Is as enrollGrantFrame, J as mentionsMember, Ja as claimedTime, Jc as decodeInviteCode, Ji as TRANSPORTS, Jl as sanitizeAvatar, Jn as groupFileFallback, Jo as handoffAttemptFailed, Jr as relayRequest, Js as takeRequest, Jt as ETHEREUM_USDT, K as carryMentions, Ka as statusCardText, Kc as OwnInviteError, Ki as emptyProofLedger, Kl as verify, Ko as filePartName, Kr as newWakeToken, Ks as planKnocks, L as parseGroupWakeFrame, Lc as canonicalJson, Ln as PAIRED_FRAME_TOO_LARGE, Lo as HANDOFF_DONE, Lr as PIN_LIMITS, Ls as enrollHelloFrame, M as readKnocks, Ma as readReply, Ml as traceLink, Mn as parseCashuRequestPayload, Mo as HTTP_SERVICE_PROTO, Ms as enrollCancelFrame, Na as replySnippet, Nl as budgetRetryMs, Nn as parseFedimintRequestPayload, No as LEGACY_SERVICES, Nr as TypingSender, Ns as enrollCancelReason, O as entryParams, Oa as readReaction, Oc as isAppHash, Oi as CapsExchange, Ol as RelayTransport, On as cashuRequestPayload, Or as FILE_LIMITS, P as GroupWakeLimiter, Pa as BUTTON_ID, Pi as IDENTITY_REVOCATION_LABEL, Pl as isDiscoveryBudgetError, Pn as GhostLink, Po as serviceIdFromName, Ps as enrollDigits, Qa as GROUP_ADMIN_OFF_ERROR, Qo as handoffContext, Qs as contactDay, Qt as SEPOLIA_TEST_USDT, R as GROUP_LIMITS, Ri as emptyIdentityLedger, Rl as createRelayPayload, Rn as pairedMessageFits, Ro as HANDOFF_HAVE, Rr as mayPin, Rs as enrollProofFrame, S as communityHasFrame, Sa as REACTION_LIMITS, Sc as sha256Paced, Sl as turnInstance, Sr as rankHubs, Ta as queueReaction, Tc as appFingerprint, Tl as turnStatedVerifier, Tr as readLobby, Ts as setUpdateFrame, Uc as createDeviceInvite, Ui as revokesIdentity, Ul as identityFromSeed, Un as GROUP_FILE_LIMITS, Uo as HANDOFF_REQUEST, Ur as WAKE_CALL_INTERVAL_MS, Us as endedRequests, Ut as didDhtFromPublicKey, V as GroupSession, Vc as encodeContactLink, Vi as newIdentityBinding, Vn as engineText, Vo as HANDOFF_PAKE, Vr as pinNumberHolds, Vs as verifyEnrollProof, Wa as checkStatusCard, Wc as deviceInviteJoinerParams, Wi as lastSharedWithMe, Wl as identityFromSeedB64, Wo as HANDOFF_TIMINGS, Wr as WakeLimiter, Ws as inboxRecord, Wt as encodeDidDhtDeactivated, Xa as receivedTimestamp, Xc as inviteLink, Xl as bytesEqual, Xn as readGroupFileMeta, Xo as handoffBusyFrame, Xr as checkPushEndpoint, Xs as ContactRequestError, Xt as ONCHAIN_PROVIDER, Y as groupName, Ya as heardTime, Yc as encodeInviteCode, Yi as automaticTransport, Yl as sanitizeDisplayText, Yo as handoffAttemptSucceeded, Yr as wakeRequest, Ys as turnOff, Yt as EVM_TEST_CHAINS, Za as shownTime, Zc as inviteOwnership, Zl as fromBase64Url, Zo as handoffCancelFrame, Zr as vapidKeysMatch, Zs as REQUEST_LIFETIME_MS, Zt as PaymentPreflightError, _ as openGroupTyping, _a as parseLinkPreview, _l as firstDeviceSetSecret, _o as parseLocalTarget, _r as lobbyRecords, _s as readHandoffPake, a as appStoreDecision, aa as sanitizeMime, ac as openRequest, ai as UPGRADE_CAPABILITY, al as deviceLinkPairing, an as assertWholeSats, ao as rosterHas, ar as groupSignalFrame, as as handoffOfferFrame, b as CommunitySession, ba as COMMUNITY_REACTION_FRAME, bl as signTurnPacket, bo as decodeControl, br as newerHead, bs as sealHandoffPiece, c as planAppUpdate, cc as requestRecords, ci as HOLD_LIMITS, cl as seedSigner, cn as walletNetworkOf, co as DirectPathWatch, cr as mayBeHub, cs as handoffRetryAfter, dc as APP_BUNDLE_MAGIC, di as isHoldUrl, dl as TURN_RAISE_READ_TIMEOUT_MS, dn as sparkAddressKind, dr as COMMUNITY_TOPOLOGY, ds as newHandoffId, ea as peekDhtMailbox, ec as knockSlotOf, ei as isAppVersion, el as ENROLL_CAPABILITY, en as TEST_USDT_FAUCET_AMOUNT, er as CarriedTransport, es as handoffDataFrame, eu as toBase64Url, f as readAppStoreSteps, fa as parseVideoMeta, fc as APP_ICON_PATH, fi as newMailbox, fl as TURN_SETTLE_MS, fn as sparkInvoiceDetails, fo as RELAY_POLL_INTERVALS, fr as beaconKeys, fs as readHandoffAck, g as groupTypingEpoch, ga as dhtEditId, gl as TURN_MAX, go as formatLocalTarget, gr as lobbyKeys, gs as readHandoffHello, gt as normalizeAtprotoHandle, h as GroupTypingBoard, ha as RateWindow, hc as appViewOf, hl as TURN_LAST_SEQUENCE, hn as isPubkyKey, ho as GhostlyHttpError, hr as freshHubs, hs as readHandoffHave, ht as isAtprotoDid, i as appRevocationFor, ia as sanitizeFileName, ic as mergeContactKnocks, ii as STATUS_CARD_CAPABILITY, il as deviceKeyZ32, in as assertTokenUnits, io as rosterAdmin, is as handoffManifestFrames, j as mergeKnocks, ja as pairedReplyAuthor, jc as readAppRevocation, ji as dialDescriptors, jn as isFederationId, jo as emptyLinkRecords, k as knockIdentity, ka as validReactionNumber, kc as isAppKey, ki as DHT_TEXT_CAPABILITY, kl as currentRelays, kn as fedimintRequestPayload, ko as parseCallSignal, kr as transferEnded, l as APP_STORE_LIMITS, la as fileMessageText, lc as seenEntry, li as HoldKeys, ll as webCryptoSigner, ln as SPARK_NETWORKS, lr as meshHubs, ls as handoffStreamKey, ma as EDIT_RATE_WINDOW_MS, mc as appDigest, ml as turnPutSummary, mo as presenceSeenAt, mr as doorHubs, ms as readHandoffDone, n as readX401SdJwtVc, na as dhtFileId, nc as linkRecords, ni as BUTTONS_CAPABILITY, nl as deviceEchoFrame, nn as WALLET_NETWORKS, no as commitHash, ns as handoffEphemeral, nu as utf8Decode, o as appUpdateDecision, oc as readKnockSlot, oi as HOLD_CAPABILITY, ol as devicePingFrame, on as formatPaymentAmount, oo as verifyCommitSignature, or as readGroupSignal, os as handoffPakeFrame, pa as EDIT_BUFFER_MS, pi as readManifest, pl as classifyTurnRead, pn as isBitcoinAddress, po as WATCH_PEER_MS, pr as beaconRecords, ps as readHandoffCancel, q as parseCommunityEdit, qa as arrivalKey, qc as createChatInvite, qi as validExternalKey, qo as handoffAttemptAllowed, qr as parseWakeFrame, qs as settleRequest, qt as signDidDhtPacket, r as sameX401HolderJwk, ra as formatFileSize, rc as makeStampPaced, ri as EDIT_CAPABILITY, rl as deviceEchoNonce, rn as arkAddressPrefix, ro as parseGroupCommit, rs as handoffHelloFrame, ru as utf8Encode, s as checkAppBeforeRun, sc as readLinkRecord, si as HOLD_DATED_BACK_MS, sl as newDeviceSetSecret, sn as validatePaymentTarget, so as edgeParams, sr as MESH_HUBS, ss as handoffReleaseFrame, t as newX401HolderKey, ta as DHT_FILE_CAPABILITY, tc as knockSlotRecords, ti as APPS_CAPABILITY, tl as HANDOFF_CAPABILITY, tn as USDT_PUBLIC_RPC, to as MEMBER_KEY, ts as handoffDigest, tu as toZ32, ua as parseVoiceMeta, uc as APP_BUNDLE_LIMITS, ui as HoldRefusedError, un as SPARK_PROVIDER, uo as DHT_POLL_INTERVALS, ur as pickMeshHubs, us as handoffVersions, v as sealGroupTyping, va as forwardedAgain, vc as isAppUrl, vl as nextTurnPosition, vo as webLocalFetch, vr as mergeBeacon, vs as readHandoffTurnFrame, w as encodeCommunityLink, wa as nextReactionNumber, wc as APP_STATEMENT_LIMITS, wl as turnName, wr as readBeaconHead, ws as setAckFrame, x as GROUP_READ_NOTE_COMMUNITY, xa as GROUP_REACTION_FRAME, xc as readAppBundleAsync, xl as signTurnRelease, xo as encodeControl, xr as pickHubs, y as COMMUNITY_LIMITS, ya as readForwarded, yc as pacer, yl as readTurnPacket, yo as LIMITS, yr as mergeLobby, ys as readHandoffVerified, za as STATUS_CARD_LIMITS, zc as readCanonicalJson, zi as identityRevocationValue, zn as pairedMessageFrame, zo as HANDOFF_HELLO, zr as nextPinNumber, zs as readEnrollGrant } from "./src-D1X4uVPW.js";
2
+ import { $a as statusCardText, $c as readDeviceInvite, $l as createIdentity, $o as HANDOFF_VERIFIED, $r as isServeId, $s as newInbox, A as knockRecords, Aa as reactionEmoji, Ac as sha256Paced, Ai as CapsExchange, Al as turnInstance, An as findEndpoint, Ao as RTC_CONFIG, Ar as transferStalled, B as GROUP_READ_NOTE, Bi as emptyIdentityLedger, Bl as currentRelays, Bn as engineError, Bo as HTTP_SERVICE_PROTO, Br as pinIsNewer, Bs as enrollCancelFrame, C as decodeCommunityLink, Ca as readForwarded, Cc as appViewOf, Cl as TURN_LAST_SEQUENCE, Co as formatLocalTarget, Cr as readBeacon, Cs as readHandoffHave, D as encodeGroupEntryLink, Da as ReactionWindow, Dc as pacer, Dl as readTurnPacket, Dn as ENDPOINT, Do as decodeControl, Dr as ChatFiles, Ds as readHandoffVerified, E as decodeGroupEntryLink, Ea as REACTION_LIMITS, Ec as isAppUrl, El as nextTurnPosition, En as decodeBolt11, Eo as LIMITS, Er as shouldBeHub, Es as readHandoffTurnFrame, F as groupWakeFrame, Fa as pairedReplyAuthor, Fl as DEFAULT_RELAYS, Fn as INVITE_TAKEN, Fo as contactRtcConfig, Fr as typingActivity, Fs as verifySetUpdate, G as GROUP_EDIT_TEXT_BYTES, Ga as STATUS_CARD_LIMITS, Gc as canonicalJson, Gi as revokesIdentity, Gl as isDiscoveryBudgetError, Go as HANDOFF_DONE, Gr as deviceWakeRequest, Gs as enrollHelloFrame, Gt as encodeDidDhtPacket, H as frameBytes, Hi as identityStatement, Hn as parseEngineError, Ho as serviceIdFromName, Hr as readPin, Hs as enrollDigits, Ht as didDhtDocument, I as groupWakes, Ia as readReply, Ic as isAppHash, Ii as IDENTITY_REVOCATION_LABEL, In as LIVENESS_PING_MS, J as mentionsMember, Jc as createContactLink, Ji as emptyProofLedger, Jn as groupFileFallback, Jo as HANDOFF_OFFER, Jr as relayRequest, Js as readEnrollHello, Jt as ETHEREUM_USDT, K as carryMentions, Ki as lastSharedWithMe, Kl as withRequestOptions, Ko as HANDOFF_HAVE, Kr as newWakeToken, Ks as enrollProofFrame, L as parseGroupWakeFrame, La as replySnippet, Lc as isAppKey, Ll as RelayTransport, Ln as PAIRED_FRAME_TOO_LARGE, Lo as parseCallSignal, Lr as PIN_LIMITS, M as readKnocks, Ma as readReaction, Mc as APP_STATEMENT_LIMITS, Mi as capsDescriptors, Ml as turnName, Mn as parseCashuRequestPayload, Ms as setAckFrame, Na as validReactionNumber, Nc as appFingerprint, Ni as dialDescriptors, Nl as turnStatedVerifier, Nn as parseFedimintRequestPayload, Nr as TypingSender, Ns as setUpdateFrame, O as entryParams, Oa as nextReactionNumber, Ol as signTurnPacket, On as cashuRequestPayload, Oo as encodeControl, Or as FILE_LIMITS, Os as sealHandoffPiece, P as GroupWakeLimiter, Pa as wireReaction, Pc as appRef, Pl as turnVerifierMark, Pn as GhostLink, Ps as signTombstone, Qa as sameButtonText, Qc as deviceInviteJoinerParams, Qo as HANDOFF_TIMINGS, Qr as APP_RANGE_LIMITS, Qs as inboxRecord, Qt as SEPOLIA_TEST_USDT, R as GROUP_LIMITS, Ra as BUTTON_ID, Rc as isAppRef, Ri as IdentityExchange, Rn as pairedMessageFits, Rr as mayPin, S as communityHasFrame, Sa as forwardedAgain, Sc as appDigest, Sl as turnPutSummary, So as GhostlyHttpError, Sr as rankHubs, Ss as readHandoffDone, Ta as GROUP_REACTION_FRAME, Tl as firstDeviceSetSecret, To as webLocalFetch, Tr as readLobby, Ts as readHandoffPake, Uc as parseImageMeta, Ui as newIdentityBinding, Ul as traceLink, Un as GROUP_FILE_LIMITS, Uo as HANDOFF_ACK, Ur as WAKE_CALL_INTERVAL_MS, Us as enrollDoneFrame, Ut as didDhtFromPublicKey, V as GroupSession, Vi as identityRevocationValue, Vl as normalizeRelayUrl, Vn as engineText, Vo as LEGACY_SERVICES, Vr as pinNumberHolds, Vs as enrollCancelReason, Wi as receivedIdentityStatus, Wl as budgetRetryMs, Wo as HANDOFF_CANCEL, Wr as WakeLimiter, Ws as enrollGrantFrame, Wt as encodeDidDhtDeactivated, Xc as readContactLink, Xi as TRANSPORTS, Xn as readGroupFileMeta, Xo as HANDOFF_PIECE_BYTES, Xr as checkPushEndpoint, Xs as clearMissed, Xt as ONCHAIN_PROVIDER, Y as groupName, Yc as encodeContactLink, Yi as validExternalKey, Yl as createRelayPayload, Yo as HANDOFF_PAKE, Yr as wakeRequest, Ys as verifyEnrollProof, Yt as EVM_TEST_CHAINS, Za as checkStatusCard, Zc as createDeviceInvite, Zi as automaticTransport, Zo as HANDOFF_REQUEST, Zr as vapidKeysMatch, Zs as endedRequests, Zt as PaymentPreflightError, _ as openGroupTyping, _a as MAX_REMOVAL_NUMBER, _c as seenEntry, _l as webCryptoSigner, _o as DHT_POLL_INTERVALS, _r as lobbyRecords, _s as handoffStreamKey, a as appStoreDecision, aa as formatFileSize, ac as REQUEST_LIFETIME_MS, ai as EDIT_CAPABILITY, al as inviteOwnership, an as assertWholeSats, ao as GROUP_ADMIN_OFF_ERROR, ar as groupSignalFrame, as as handoffCancelFrame, au as sanitizeAvatar, b as CommunitySession, ba as dhtEditId, bc as APP_ICON_PATH, bl as TURN_SETTLE_MS, bo as WATCH_PEER_MS, br as newerHead, bs as readHandoffAck, c as planAppUpdate, cc as knockSlotOf, ci as HOLD_CAPABILITY, cl as ENROLL_CAPABILITY, cn as walletNetworkOf, co as MEMBER_KEY, cr as mayBeHub, cs as handoffDataFrame, cu as fromBase64Url, da as fileMessageText, dc as makeStampPaced, di as HoldKeys, dl as deviceEchoNonce, dn as sparkAddressKind, do as rosterAdmin, dr as COMMUNITY_TOPOLOGY, ds as handoffHelloFrame, du as toBase64Url, ec as planKnocks, el as OwnInviteError, en as TEST_USDT_FAUCET_AMOUNT, eo as arrivalKey, er as CarriedTransport, es as filePartName, eu as identityFromSeed, f as readAppStoreSteps, fa as parseVoiceMeta, fc as mergeContactKnocks, fi as HoldRefusedError, fl as deviceKeyZ32, fn as sparkInvoiceDetails, fo as rosterHas, fr as beaconKeys, fs as handoffManifestFrames, fu as toZ32, g as groupTypingEpoch, ga as EDIT_RATE_WINDOW_MS, gc as requestRecords, gl as seedSigner, gr as lobbyKeys, gs as handoffRetryAfter, gt as normalizeAtprotoHandle, h as GroupTypingBoard, ha as EDIT_BUFFER_MS, hc as readLinkRecord, hi as readManifest, hl as newDeviceSetSecret, hn as isPubkyKey, ho as DirectPathWatch, hr as freshHubs, hs as handoffReleaseFrame, ht as isAtprotoDid, i as appRevocationFor, ia as dhtFileId, ic as ContactRequestError, ii as BUTTONS_CAPABILITY, il as inviteLink, in as assertTokenUnits, io as shownTime, is as handoffBusyFrame, j as mergeKnocks, ja as reactionIsNewer, ji as DHT_TEXT_CAPABILITY, jl as turnKeys, jn as isFederationId, js as readSetUpdate, k as knockIdentity, ka as queueReaction, kc as readAppBundleAsync, kl as signTurnRelease, kn as fedimintRequestPayload, kr as transferEnded, l as APP_STORE_LIMITS, lc as knockSlotRecords, li as HOLD_DATED_BACK_MS, ll as HANDOFF_CAPABILITY, ln as SPARK_NETWORKS, lo as commitHash, lr as meshHubs, ls as handoffDigest, ma as parseVideoMeta, mc as readKnockSlot, mi as newMailbox, ml as devicePingFrame, mo as edgeParams, mr as doorHubs, ms as handoffPakeFrame, mu as utf8Encode, n as readX401SdJwtVc, na as peekDhtMailbox, nc as takeRequest, ni as isAppVersion, nl as decodeInviteCode, nn as WALLET_NETWORKS, no as heardTime, ns as handoffAttemptFailed, nu as publicKeyFromZ32, o as appUpdateDecision, oa as sanitizeFileName, oc as contactDay, oi as STATUS_CARD_CAPABILITY, on as formatPaymentAmount, oo as GROUP_MEMBER_CAP, or as readGroupSignal, os as handoffContext, ou as sanitizeDisplayText, pc as openRequest, pi as isHoldUrl, pl as deviceLinkPairing, pn as isBitcoinAddress, po as verifyCommitSignature, pr as beaconRecords, ps as handoffOfferFrame, pu as utf8Decode, q as parseCommunityEdit, qc as readCanonicalJson, qi as PeerProofs, ql as PacketTooLargeError, qo as HANDOFF_HELLO, qr as parseWakeFrame, qs as readEnrollGrant, qt as signDidDhtPacket, r as sameX401HolderJwk, ra as DHT_FILE_CAPABILITY, rc as turnOff, ri as APPS_CAPABILITY, rl as encodeInviteCode, rn as arkAddressPrefix, ro as receivedTimestamp, rs as handoffAttemptSucceeded, ru as verify, s as checkAppBeforeRun, sa as sanitizeMime, sc as knockSlotIdentity, si as UPGRADE_CAPABILITY, sl as DEVICES_CAPABILITY, sn as validatePaymentTarget, sr as MESH_HUBS, ss as handoffContextProof, su as bytesEqual, t as newX401HolderKey, ta as DHT_MESSAGE_TTL, tc as settleRequest, ti as chatAppId, tl as createChatInvite, tn as USDT_PUBLIC_RPC, to as claimedTime, ts as handoffAttemptAllowed, tu as identityFromSeedB64, uc as linkRecords, ui as HOLD_LIMITS, ul as deviceEchoFrame, un as SPARK_PROVIDER, uo as parseGroupCommit, ur as pickMeshHubs, us as handoffEphemeral, uu as randomBytes, v as sealGroupTyping, va as REMOVED_TEXT, vc as APP_BUNDLE_LIMITS, vr as mergeBeacon, vs as handoffVersions, w as encodeCommunityLink, wa as COMMUNITY_REACTION_FRAME, wl as TURN_MAX, wo as parseLocalTarget, wr as readBeaconHead, ws as readHandoffHello, x as GROUP_READ_NOTE_COMMUNITY, xa as parseLinkPreview, xl as classifyTurnRead, xo as presenceSeenAt, xr as pickHubs, xs as readHandoffCancel, y as COMMUNITY_LIMITS, ya as RateWindow, yc as APP_BUNDLE_MAGIC, yl as TURN_RAISE_READ_TIMEOUT_MS, yo as RELAY_POLL_INTERVALS, yr as mergeLobby, ys as newHandoffId, zc as readAppRevocation, zn as pairedMessageFrame, zo as emptyLinkRecords, zr as nextPinNumber } from "./src-CwMTZ5Hj.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-CIlvpLT5.js";
6
- import { a as clearProfileStores, c as errorLine, d as openDb, f as profileOpenFailure, h as wrap, i as STORES$1, l as fileStore, m as transact, n as APP_STORAGE_SCOPE_INDEX, o as databaseName, p as store, r as CARD_INDEX, s as deleteDatabase, t as APP_STORAGE_CHAT_INDEX, u as newestWalletTx } from "./idb-CMVgtn2k.js";
7
- import { a as sealSeed, i as newDeviceKey, o as unsealSeed, r as intentRepository } from "./networkReason-ve6jyxIs.js";
8
- import { $ as setSingleWriterGate, A as LightningCards, B as breezDatabaseInUse, C as FileAppender, D as streamStored, E as storedSize, F as ProviderSources, G as ModeChanged, H as dropBreezDatabase, I as sourceKey, J as networkLabel, K as ModeGate, L as CASHU_MINT_SOURCE, M as isRecoveryPhrase, N as normalizePhrase, P as lightningPaying, Q as setAwayWallets, R as cashuMint, S as WALLET_TYPES, T as removeStored, U as iceServerProblem, V as breezDatabasesFor, W as iceServerSetting, X as refuseAway, Y as awayFrom, Z as requireTurn, _ as crossNetwork, a as storedGroupFiles, b as walletInstances, c as receivedPairedReply, d as paymentAlias, f as paymentWireId, g as createTiming, h as createFailure, i as groupOfFile, j as cardsKey, k as CASHU_CARD, l as replyRef, m as assertConfirmedReal, n as groupFileId, o as groupReply, p as WALLET_NAMES, q as WrongNetworkError, r as groupFileText, s as pairedWireReply, t as GroupFileDesk, u as replyTo, v as paymentNetwork, w as readStored$1, y as paymentNetworksOf, z as breezDatabase } from "./groupFiles-Dw0BA5-Z.js";
9
- import { i as fedimintDatabase, n as createIrohWebEndpoint, o as loadFedimintSdk, r as irohRelayProblem, t as DEFAULT_IROH_RELAYS } from "./irohWeb-4Q4EdaCa.js";
5
+ import { t as nwc } from "./nwcProvider-Dq647EAl.js";
6
+ import { a as clearProfileStores, c as errorLine, d as openDb, f as profileOpenFailure, h as wrap, i as STORES$1, l as fileStore, m as transact, n as APP_STORAGE_SCOPE_INDEX, o as databaseName, p as store, r as CARD_INDEX, s as deleteDatabase, t as APP_STORAGE_CHAT_INDEX, u as newestWalletTx } from "./idb-BJARz3Qi.js";
7
+ import { a as sealSeed, i as newDeviceKey, o as unsealSeed, r as intentRepository } from "./networkReason-BAnNO1Ji.js";
8
+ import { $ as setAwayWallets, A as LightningCards, B as breezDatabaseInUse, C as FileAppender, D as streamStored, E as storedSize, F as ProviderSources, G as relayOnlyProblem, H as dropBreezDatabase, I as sourceKey, J as WrongNetworkError, K as ModeChanged, L as CASHU_MINT_SOURCE, M as isRecoveryPhrase, N as normalizePhrase, P as lightningPaying, Q as requireTurn, R as cashuMint, S as WALLET_TYPES, T as removeStored, U as iceServerProblem, V as breezDatabasesFor, W as iceServerSetting, X as awayFrom, Y as networkLabel, Z as refuseAway, _ as crossNetwork, a as storedGroupFiles, b as walletInstances, c as receivedPairedReply, d as paymentAlias, et as setSingleWriterGate, f as paymentWireId, g as createTiming, h as createFailure, i as groupOfFile, j as cardsKey, k as CASHU_CARD, l as replyRef, m as assertConfirmedReal, n as groupFileId, o as groupReply, p as WALLET_NAMES, q as ModeGate, r as groupFileText, s as pairedWireReply, t as GroupFileDesk, u as replyTo, v as paymentNetwork, w as readStored$1, y as paymentNetworksOf, z as breezDatabase } from "./groupFiles-Cr4Gj9-R.js";
9
+ import { i as fedimintDatabase, n as createIrohWebEndpoint, o as loadFedimintSdk, r as irohRelayProblem, t as DEFAULT_IROH_RELAYS } from "./irohWeb-D2WaYPdN.js";
10
10
  import { c as isTestMint, d 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-BrlY773j.js";
11
- import { _ as reserveAdapterIds, b as testBuild, f as setOwnDidSource, g as registeredOnchainProviders, h as registeredLightningProviders, l as chosenResolver, n as resolveAtprotoDid, p as onAdaptersChanged, t as assertPublicServer, v as boundedIdentityFetch, y as verifyIdentity } from "./resolve-BDoQLkJR.js";
12
- import { c as fileSpace, f as FILE_BYTES_STEP, o as fileBytes, r as blobDigest, s as fileBytesOf, u as removeFileBytes } from "./fileBytes-B-fqGdEd.js";
13
- import { n as MAX_BACKUP_BYTES, t as BACKUP_MEDIA_TYPE } from "./envelope-BKSHUJnt.js";
11
+ import { _ as reserveAdapterIds, b as testBuild, f as setOwnDidSource, g as registeredOnchainProviders, h as registeredLightningProviders, l as chosenResolver, n as resolveAtprotoDid, p as onAdaptersChanged, t as assertPublicServer, v as boundedIdentityFetch, y as verifyIdentity } from "./resolve-C39pc4Kf.js";
12
+ import { i as fromBase64Url$1, n as MAX_BACKUP_BYTES, t as BACKUP_MEDIA_TYPE } from "./envelope-DEvU5FA9.js";
13
+ import { c as fileSpace, f as FILE_BYTES_STEP, o as fileBytes, r as blobDigest, s as fileBytesOf, u as removeFileBytes } from "./fileBytes-B8eTZfAT.js";
14
14
  import { t as hyperdhtRelayProblem } from "./hyperdhtRelay-BT_wRxab.js";
15
15
  import { sha256 } from "@noble/hashes/sha2.js";
16
16
  import { hkdf } from "@noble/hashes/hkdf.js";
@@ -198,7 +198,7 @@ function viewNews(before, after) {
198
198
  //#endregion
199
199
  //#region ../browser/src/engine/paymentAdapters/usdtWallet.ts
200
200
  /** The Ethereum libraries, a large part of the app: loaded once a USDT wallet is made, opened or restored, not with the engine. */
201
- var loadUsdt = () => import("./usdt-Byi5OFic.js");
201
+ var loadUsdt = () => import("./usdt-CxSyuXq4.js");
202
202
  /** Every new profile starts with this wallet: an address to receive on, nothing to set up. */
203
203
  var DEFAULT_USDT = {
204
204
  network: "ethereum",
@@ -647,7 +647,7 @@ async function restoreArkDatabase(walletId, snapshot) {
647
647
  //#endregion
648
648
  //#region ../browser/src/engine/paymentAdapters/arkWallet.ts
649
649
  /** The Ark SDK, a large part of the app: loaded once an Ark wallet is made, opened or restored, not with the engine. */
650
- var loadArkade = () => import("./arkade-DCovElLt.js");
650
+ var loadArkade = () => import("./arkade-GzJoov-w.js");
651
651
  /** How long a Testnet wallet about to make way for another waits for its server to say what it holds. */
652
652
  var RETIRE_READ_MS = 1e4;
653
653
  /** Every new profile starts with this wallet: nothing to set up before receiving. */
@@ -6713,6 +6713,96 @@ function defaultRegistry() {
6713
6713
  };
6714
6714
  }
6715
6715
  //#endregion
6716
+ //#region ../browser/src/shared/profileKey.ts
6717
+ /**
6718
+ * Only the record key can hold a newline: the other parts come from the code, so the joined binding still reads one
6719
+ * way (the first two lines, the last line, and the key between them).
6720
+ */
6721
+ function binding(b) {
6722
+ for (const part of [
6723
+ b.db,
6724
+ b.store,
6725
+ b.field
6726
+ ]) if (!part || part.includes("\n")) throw new Error("Invalid sealed field binding");
6727
+ return new TextEncoder().encode([
6728
+ "ghostly-field/2",
6729
+ b.db,
6730
+ b.store,
6731
+ b.key,
6732
+ b.field
6733
+ ].join("\n"));
6734
+ }
6735
+ function isSealedField(value) {
6736
+ const v = value;
6737
+ return !!v && typeof v === "object" && v.v === 2 && typeof v.iv === "string" && typeof v.ct === "string";
6738
+ }
6739
+ /** Seals one field under DK with a fresh random 96-bit nonce and no KDF per field. */
6740
+ async function sealField(key, where, value) {
6741
+ const iv = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(12));
6742
+ const ct = new Uint8Array(await crypto.subtle.encrypt({
6743
+ name: "AES-GCM",
6744
+ iv,
6745
+ additionalData: binding(where)
6746
+ }, key, new TextEncoder().encode(value)));
6747
+ return {
6748
+ v: 2,
6749
+ iv: toBase64Url(iv),
6750
+ ct: toBase64Url(ct)
6751
+ };
6752
+ }
6753
+ /** Opens a field sealed for exactly this place under this DK; anything else fails instead of opening wrong. */
6754
+ async function openField(key, where, sealed) {
6755
+ if (!isSealedField(sealed)) throw new Error("Unsupported sealed field version");
6756
+ const aad = binding(where);
6757
+ try {
6758
+ const iv = fromBase64Url$1(sealed.iv);
6759
+ if (iv.length !== 12) throw new Error("nonce");
6760
+ return new TextDecoder().decode(await crypto.subtle.decrypt({
6761
+ name: "AES-GCM",
6762
+ iv,
6763
+ additionalData: aad
6764
+ }, key, fromBase64Url$1(sealed.ct)));
6765
+ } catch {
6766
+ throw new Error("A sealed field could not be opened: it was changed, or it belongs to another record");
6767
+ }
6768
+ }
6769
+ //#endregion
6770
+ //#region ../browser/src/engine/dataKey.ts
6771
+ var PEER_DB = "ghostly";
6772
+ /**
6773
+ * The profile's data key (DK), when the profile is encrypted and unlocked: the one slot the engine owns. A
6774
+ * non-extractable key; nothing writes it anywhere. Empty, every secret is sealed as today (version 1).
6775
+ */
6776
+ var slot = null;
6777
+ var onDrop = /* @__PURE__ */ new Set();
6778
+ /** A cache of opened secrets empties itself when the key goes. Returns the way to stop listening. */
6779
+ function whenDataKeyDropped(drop) {
6780
+ onDrop.add(drop);
6781
+ return () => {
6782
+ onDrop.delete(drop);
6783
+ };
6784
+ }
6785
+ async function sealSecret(value, at) {
6786
+ if (slot) return sealField(slot, {
6787
+ db: PEER_DB,
6788
+ ...at
6789
+ }, value);
6790
+ const deviceKey = newDeviceKey();
6791
+ return {
6792
+ sealed: await sealSeed(value, deviceKey),
6793
+ deviceKey
6794
+ };
6795
+ }
6796
+ /** Reads both versions: a profile being encrypted holds some of each until its migration ends. */
6797
+ async function openSecret(secret, at) {
6798
+ if (!isSealedField(secret)) return unsealSeed(secret.sealed, secret.deviceKey);
6799
+ if (!slot) throw new Error("This profile is locked. Enter its passphrase first.");
6800
+ return openField(slot, {
6801
+ db: PEER_DB,
6802
+ ...at
6803
+ }, secret);
6804
+ }
6805
+ //#endregion
6716
6806
  //#region ../browser/src/proofs/load.ts
6717
6807
  /**
6718
6808
  * The identity proof providers, loaded on first need and not with the app: they and their libraries (OpenPGP, the
@@ -6723,7 +6813,7 @@ var registry;
6723
6813
  var loading$1;
6724
6814
  var listeners = /* @__PURE__ */ new Set();
6725
6815
  function loadIdentityProviders() {
6726
- return loading$1 ??= import("./registry-dG_Wm7fC.js").then((m) => {
6816
+ return loading$1 ??= import("./registry-DFiOxH5q.js").then((m) => {
6727
6817
  registry = m;
6728
6818
  for (const listener of listeners) listener();
6729
6819
  return m;
@@ -6736,6 +6826,12 @@ function loadIdentityProviders() {
6736
6826
  var loadedIdentityProviders = () => registry?.identityProviders() ?? [];
6737
6827
  //#endregion
6738
6828
  //#region ../browser/src/engine/identities.ts
6829
+ /** Where a proof key's seed belongs: by proof id, so it still opens once the proof moved to the revocations. */
6830
+ var proofKeyAt = (id) => ({
6831
+ store: STORES$1.settings,
6832
+ key: id,
6833
+ field: "identityProof.seed"
6834
+ });
6739
6835
  var KEY$2 = "identityProofs";
6740
6836
  var REVOCATIONS = "identityRevocations";
6741
6837
  /** Relays and the DHT forget a record within hours: republish revocations this often while the app runs. */
@@ -6769,6 +6865,7 @@ var IdentityProofs = class {
6769
6865
  /** Unsealed proof-key seeds, by proof id, for this run only. */
6770
6866
  seeds = /* @__PURE__ */ new Map();
6771
6867
  timers = [];
6868
+ unlisten;
6772
6869
  drafts = /* @__PURE__ */ new Map();
6773
6870
  exchanges = /* @__PURE__ */ new Map();
6774
6871
  errors = /* @__PURE__ */ new Map();
@@ -6799,10 +6896,16 @@ var IdentityProofs = class {
6799
6896
  };
6800
6897
  every(REPUBLISH_MS$1, 5e3, () => this.republish());
6801
6898
  every(REVOCATION_CHECK_MS, 6e4, () => this.checkRevocations());
6899
+ this.unlisten ??= whenDataKeyDropped(() => this.forgetSeeds());
6802
6900
  }
6803
6901
  stop() {
6804
6902
  for (const t of this.timers) clearTimeout(t);
6805
6903
  this.timers = [];
6904
+ this.unlisten?.();
6905
+ this.unlisten = void 0;
6906
+ this.forgetSeeds();
6907
+ }
6908
+ forgetSeeds() {
6806
6909
  for (const seed of this.seeds.values()) seed.fill(0);
6807
6910
  this.seeds.clear();
6808
6911
  }
@@ -6818,7 +6921,7 @@ var IdentityProofs = class {
6818
6921
  async seedOf(id, sealed) {
6819
6922
  let seed = this.seeds.get(id);
6820
6923
  if (!seed) {
6821
- seed = fromBase64Url(await unsealSeed(sealed.sealed, sealed.deviceKey));
6924
+ seed = fromBase64Url(await openSecret(sealed, proofKeyAt(id)));
6822
6925
  this.seeds.set(id, seed);
6823
6926
  }
6824
6927
  return seed;
@@ -6884,14 +6987,10 @@ var IdentityProofs = class {
6884
6987
  const verified = await this.verify(statement, JSON.parse(JSON.stringify(evidence ?? null)));
6885
6988
  if (this.proofs.length >= MAX_PROOFS) throw new Error("Remove an identity first");
6886
6989
  this.drafts.delete(draftId);
6887
- const deviceKey = newDeviceKey();
6888
6990
  const stored = {
6889
6991
  binding: draft.binding,
6890
6992
  evidence,
6891
- seed: {
6892
- sealed: await sealSeed(toBase64Url(draft.seed), deviceKey),
6893
- deviceKey
6894
- },
6993
+ seed: await sealSecret(toBase64Url(draft.seed), proofKeyAt(statement.id)),
6895
6994
  verified,
6896
6995
  createdAt: Date.now()
6897
6996
  };
@@ -7208,14 +7307,15 @@ var X401Credentials = class {
7208
7307
  */
7209
7308
  async newKey() {
7210
7309
  const { secret, jwk } = newX401HolderKey();
7211
- const deviceKey = newDeviceKey();
7310
+ const id = newId$1();
7212
7311
  const key = {
7213
- id: newId$1(),
7312
+ id,
7214
7313
  jwk,
7215
- secret: {
7216
- sealed: await sealSeed(toBase64Url(secret), deviceKey),
7217
- deviceKey
7218
- },
7314
+ secret: await sealSecret(toBase64Url(secret), {
7315
+ store: STORES$1.settings,
7316
+ key: id,
7317
+ field: "x401.holderKey"
7318
+ }),
7219
7319
  createdAt: Date.now()
7220
7320
  };
7221
7321
  secret.fill(0);
@@ -7314,6 +7414,11 @@ var X401Credentials = class {
7314
7414
  //#endregion
7315
7415
  //#region ../browser/src/engine/did.ts
7316
7416
  var KEY$1 = "profileDid";
7417
+ var SEED_AT = {
7418
+ store: STORES$1.settings,
7419
+ key: KEY$1,
7420
+ field: "did.seed"
7421
+ };
7317
7422
  /** Mainline keeps a mutable item about two hours: the same packet goes out again every hour. */
7318
7423
  var DID_REPUBLISH_MS = 36e5;
7319
7424
  /** After start, once the chats had their first go at the relays. */
@@ -7333,6 +7438,7 @@ var ProfileDid = class {
7333
7438
  running = false;
7334
7439
  inFlight = null;
7335
7440
  again = false;
7441
+ unlisten;
7336
7442
  constructor(host) {
7337
7443
  this.host = host;
7338
7444
  }
@@ -7344,12 +7450,8 @@ var ProfileDid = class {
7344
7450
  return;
7345
7451
  }
7346
7452
  const identity = createIdentity();
7347
- const deviceKey = newDeviceKey();
7348
7453
  const made = {
7349
- seed: {
7350
- sealed: await sealSeed(identity.seedB64, deviceKey),
7351
- deviceKey
7352
- },
7454
+ seed: await sealSecret(identity.seedB64, SEED_AT),
7353
7455
  publicKey: toBase64Url(identity.publicKey),
7354
7456
  createdAt: Date.now(),
7355
7457
  listed: []
@@ -7359,12 +7461,18 @@ var ProfileDid = class {
7359
7461
  }
7360
7462
  start() {
7361
7463
  this.running = true;
7464
+ this.unlisten ??= whenDataKeyDropped(() => this.forgetSeed());
7362
7465
  this.schedule(FIRST_PUBLISH_MS$1);
7363
7466
  }
7364
7467
  stop() {
7365
7468
  this.running = false;
7366
7469
  if (this.timer) clearTimeout(this.timer);
7367
7470
  this.timer = null;
7471
+ this.unlisten?.();
7472
+ this.unlisten = void 0;
7473
+ this.forgetSeed();
7474
+ }
7475
+ forgetSeed() {
7368
7476
  this.seed?.fill(0);
7369
7477
  this.seed = null;
7370
7478
  }
@@ -7487,7 +7595,7 @@ var ProfileDid = class {
7487
7595
  const previous = this.stored?.published;
7488
7596
  if (!this.stored || !previous) return;
7489
7597
  const seq = Math.max(Math.floor(Date.now() / 1e3), previous.seq + 1);
7490
- const identity = identityFromSeed(fromBase64Url(await unsealSeed(this.stored.seed.sealed, this.stored.seed.deviceKey)));
7598
+ const identity = identityFromSeed(fromBase64Url(await openSecret(this.stored.seed, SEED_AT)));
7491
7599
  await this.host.publish(toZ32(this.publicKey()), signDidDhtPacket(identity, encodeDidDhtDeactivated(this.publicKey()), seq));
7492
7600
  }
7493
7601
  listed() {
@@ -7518,7 +7626,7 @@ var ProfileDid = class {
7518
7626
  return new Uint8Array(await this.unsealed());
7519
7627
  }
7520
7628
  async unsealed() {
7521
- this.seed ??= fromBase64Url(await unsealSeed(this.stored.seed.sealed, this.stored.seed.deviceKey));
7629
+ this.seed ??= fromBase64Url(await openSecret(this.stored.seed, SEED_AT));
7522
7630
  return this.seed;
7523
7631
  }
7524
7632
  async save(next) {
@@ -7528,6 +7636,12 @@ var ProfileDid = class {
7528
7636
  };
7529
7637
  //#endregion
7530
7638
  //#region ../browser/src/engine/contactLinks.ts
7639
+ /** Where a link's seed belongs: by its key, so it still opens once the link is retired. */
7640
+ var seedAt = (linkKeyZ32) => ({
7641
+ store: STORES$1.settings,
7642
+ key: linkKeyZ32,
7643
+ field: "contactLink.seed"
7644
+ });
7531
7645
  var CONTACT_LINKS_KEY = "contactLinks";
7532
7646
  /** Mainline keeps a mutable item about two hours: the link record goes out again every hour. */
7533
7647
  var LINK_REPUBLISH_MS = 36e5;
@@ -7636,7 +7750,6 @@ var ContactLinks = class {
7636
7750
  }
7637
7751
  async make() {
7638
7752
  const made = createContactLink();
7639
- const deviceKey = newDeviceKey();
7640
7753
  const now = Date.now();
7641
7754
  const retired = this.retire(now);
7642
7755
  const waiting = this.stored.current?.inbox.waiting.filter((w) => w.expires > now) ?? [];
@@ -7648,10 +7761,7 @@ var ContactLinks = class {
7648
7761
  };
7649
7762
  await this.save({
7650
7763
  current: {
7651
- seed: {
7652
- sealed: await sealSeed(made.seedB64, deviceKey),
7653
- deviceKey
7654
- },
7764
+ seed: await sealSecret(made.seedB64, seedAt(made.linkKeyZ32)),
7655
7765
  linkKeyZ32: made.linkKeyZ32,
7656
7766
  createdAt: now,
7657
7767
  inbox,
@@ -7820,7 +7930,7 @@ var ContactLinks = class {
7820
7930
  this.host.emit();
7821
7931
  }
7822
7932
  async identity(link) {
7823
- return identityFromSeedB64(await unsealSeed(link.seed.sealed, link.seed.deviceKey));
7933
+ return identityFromSeedB64(await openSecret(link.seed, seedAt(link.linkKeyZ32)));
7824
7934
  }
7825
7935
  /**
7826
7936
  * The record is the one in memory from now on, and the writes go to the database in the order they were made: a
@@ -7940,7 +8050,7 @@ var ContactAsks = class {
7940
8050
  const ask = {
7941
8051
  link,
7942
8052
  key: asker.pubKeyZ32,
7943
- seed: known?.seed ?? await this.seal(asker),
8053
+ seed: known?.seed ?? await this.seal(asker, link),
7944
8054
  chatId: chat.linkId,
7945
8055
  invite: chat.inviteCode,
7946
8056
  name: sent.name,
@@ -8062,15 +8172,20 @@ var ContactAsks = class {
8062
8172
  this.queue = run.catch(() => {});
8063
8173
  return run;
8064
8174
  }
8065
- async seal(identity) {
8066
- const deviceKey = newDeviceKey();
8067
- return {
8068
- sealed: await sealSeed(identity.seedB64, deviceKey),
8069
- deviceKey
8070
- };
8175
+ /** An asker key's seed belongs to the link it asks: one ask per link. */
8176
+ seal(identity, link) {
8177
+ return sealSecret(identity.seedB64, {
8178
+ store: STORES$1.settings,
8179
+ key: link,
8180
+ field: "contactAsk.seed"
8181
+ });
8071
8182
  }
8072
8183
  async identity(ask) {
8073
- return identityFromSeedB64(await unsealSeed(ask.seed.sealed, ask.seed.deviceKey));
8184
+ return identityFromSeedB64(await openSecret(ask.seed, {
8185
+ store: STORES$1.settings,
8186
+ key: ask.link,
8187
+ field: "contactAsk.seed"
8188
+ }));
8074
8189
  }
8075
8190
  async put(ask) {
8076
8191
  const next = [...this.asks.filter((a) => a.link !== ask.link), ask];
@@ -10704,6 +10819,108 @@ var eachNetwork = (value) => "mainnet" in value && "testnet" in value ? value :
10704
10819
  testnet: value
10705
10820
  };
10706
10821
  //#endregion
10822
+ //#region ../browser/src/engine/saved.ts
10823
+ /**
10824
+ * Saved messages: marks the person puts on messages of any chat or group to find them again in one list. Kept for this
10825
+ * profile on this device only, in one settings record; nothing goes on the wire, so contacts and older apps never see
10826
+ * them. A mark names a row (`linkId`: a chat's link or `group:<id>`, `id`: the row here) and is read with the row, so an
10827
+ * edit shows its latest version and a deleted message, chat or group drops out of the list.
10828
+ */
10829
+ var SAVED_MESSAGES_KEY = "savedMessages";
10830
+ var isMark = (m) => {
10831
+ const v = m;
10832
+ return !!v && typeof v === "object" && typeof v.linkId === "string" && typeof v.id === "string" && Number.isSafeInteger(v.savedAt);
10833
+ };
10834
+ /** The marks a record holds; anything else reads as none (a record a newer version wrote keeps its readable marks). */
10835
+ function readSavedMarks(value) {
10836
+ const items = value?.items;
10837
+ return Array.isArray(items) ? items.filter(isMark) : [];
10838
+ }
10839
+ var sameRow = (a, b) => a.linkId === b.linkId && a.id === b.id;
10840
+ /** This profile's saved marks on this device, in one place: every change goes through one queue, so none is lost. */
10841
+ var SavedMessages = class {
10842
+ changed;
10843
+ queue = Promise.resolve();
10844
+ constructor(changed) {
10845
+ this.changed = changed;
10846
+ }
10847
+ serial(work) {
10848
+ const next = this.queue.then(work, work);
10849
+ this.queue = next.catch(() => {});
10850
+ return next;
10851
+ }
10852
+ async marks() {
10853
+ return readSavedMarks(await wrap((await store(STORES$1.settings, "readonly")).get(SAVED_MESSAGES_KEY)));
10854
+ }
10855
+ async write(items) {
10856
+ await wrap((await store(STORES$1.settings, "readwrite")).put({
10857
+ at: Date.now(),
10858
+ items
10859
+ }, SAVED_MESSAGES_KEY));
10860
+ }
10861
+ /** The row `messageId` names in the chat: its id here or, in a 1:1 chat, the id both sides know it by. */
10862
+ async row(linkId, messageId) {
10863
+ const messages = await store(STORES$1.messages, "readonly");
10864
+ const ids = linkId.startsWith("group:") ? [messageId] : [
10865
+ messageId,
10866
+ `peer_${messageId}`,
10867
+ `me_${messageId}`
10868
+ ];
10869
+ for (const id of ids) {
10870
+ const row = await wrap(messages.get([linkId, id]));
10871
+ if (row) return row;
10872
+ }
10873
+ }
10874
+ /** Saves a message, or unsaves it with `remove`. Saving one already saved keeps its first time. */
10875
+ save({ linkId, messageId, remove }) {
10876
+ return this.serial(async () => {
10877
+ if (typeof linkId !== "string" || !linkId) return { error: "No chat named" };
10878
+ if (typeof messageId !== "string" || !messageId) return { error: "No message named" };
10879
+ const marks = await this.marks();
10880
+ if (remove) {
10881
+ const row = await this.row(linkId, messageId);
10882
+ const next = marks.filter((m) => !sameRow(m, {
10883
+ linkId,
10884
+ id: messageId
10885
+ }) && !(row && sameRow(m, row)));
10886
+ if (next.length !== marks.length) {
10887
+ await this.write(next);
10888
+ this.changed();
10889
+ }
10890
+ return { error: null };
10891
+ }
10892
+ const row = await this.row(linkId, messageId);
10893
+ if (!row) return { error: "That message is not in this chat" };
10894
+ if (marks.some((m) => sameRow(m, row))) return { error: null };
10895
+ await this.write([...marks, {
10896
+ linkId,
10897
+ id: row.id,
10898
+ savedAt: Date.now()
10899
+ }]);
10900
+ this.changed();
10901
+ return { error: null };
10902
+ });
10903
+ }
10904
+ /**
10905
+ * The saved messages, the last saved first, each with its row as it is now. A mark whose row is gone (deleted here or
10906
+ * for everyone, or its chat or group deleted) is dropped from the record.
10907
+ */
10908
+ list() {
10909
+ return this.serial(async () => {
10910
+ const marks = await this.marks();
10911
+ if (!marks.length) return [];
10912
+ const messages = await store(STORES$1.messages, "readonly");
10913
+ const rows = await Promise.all(marks.map((m) => wrap(messages.get([m.linkId, m.id]))));
10914
+ const kept = marks.filter((_, i) => rows[i]);
10915
+ if (kept.length !== marks.length) await this.write(kept);
10916
+ return marks.flatMap((m, i) => rows[i] ? [{
10917
+ savedAt: m.savedAt,
10918
+ message: rows[i]
10919
+ }] : []).reverse();
10920
+ });
10921
+ }
10922
+ };
10923
+ //#endregion
10707
10924
  //#region ../browser/src/engine/appFetch.ts
10708
10925
  /** The hosts phase 1 reads from. A jsDelivr URL must also name a 40-character commit (`isAppUrl`). */
10709
10926
  var APP_FETCH_HOSTS = ["raw.githubusercontent.com", "cdn.jsdelivr.net"];
@@ -19509,8 +19726,15 @@ function fileWire(protocol, size) {
19509
19726
  var outgoingFileId = (linkId, wireId) => `${linkId}-out-${wireId}`;
19510
19727
  /** A file said on the DHT floor whose offer does not come within this long is shown as not coming (an offer's week). */
19511
19728
  var ANNOUNCED_FOR_MS = 6048e5;
19729
+ /**
19730
+ * Why this device refused the offer of a file said on the floor, as the bubble's error keeps it: no room, or too many
19731
+ * files waiting for the person, each with its own next step in the app (errorText.ts); else that it was refused.
19732
+ */
19733
+ var floorRefusal = (why) => why === "no-room" ? "No room on this device for this file" : why === "too-many" ? "Too many files are waiting here" : "It was refused here";
19512
19734
  /** Progress is written to the database at most this often; every change of state is written at once. */
19513
19735
  var SAVE_EVERY_MS = 2e3;
19736
+ /** The views of finished transfers the states carry, the newest (`FileDesk.finished`). */
19737
+ var DONE_VIEWS_KEPT = 16;
19514
19738
  /**
19515
19739
  * files/3 for every chat of this profile (WISP 501 rev 0.3): each chat's `ChatFiles`, the bytes in file
19516
19740
  * storage, the records in the files store (so a transfer resumes after a restart), the chat message a file
@@ -19537,13 +19761,17 @@ var FileDesk = class {
19537
19761
  local: /* @__PURE__ */ new Map(),
19538
19762
  places: /* @__PURE__ */ new Map(),
19539
19763
  announced: /* @__PURE__ */ new Map(),
19764
+ withdrawn: /* @__PURE__ */ new Map(),
19540
19765
  saving: Promise.resolve(),
19541
19766
  lastSaved: /* @__PURE__ */ new Map(),
19542
19767
  unsaved: /* @__PURE__ */ new Map(),
19543
19768
  files: void 0
19544
19769
  };
19545
19770
  made.files = new ChatFiles({
19546
- send: (frame) => this.deps.send(linkId, frame),
19771
+ send: (frame) => {
19772
+ this.refusedHere(made, frame);
19773
+ return this.deps.send(linkId, frame);
19774
+ },
19547
19775
  decide: (file, again) => this.decide(linkId, file, again),
19548
19776
  openTarget: (record) => this.openTarget(linkId, record),
19549
19777
  openSource: (record) => this.openSource(linkId, record),
@@ -19563,6 +19791,10 @@ var FileDesk = class {
19563
19791
  for (const file of files) {
19564
19792
  if (file.announced && !file.wire3 && file.direction === "in") {
19565
19793
  if (!file.transfer) this.announcedHere(chat, file.announced, file.id, file.metadata?.size ?? 0, file.createdAt);
19794
+ else {
19795
+ chat.local.set(file.announced, file.id);
19796
+ chat.withdrawn.set(file.announced, file.id);
19797
+ }
19566
19798
  continue;
19567
19799
  }
19568
19800
  if (!file.wire3) continue;
@@ -19590,6 +19822,11 @@ var FileDesk = class {
19590
19822
  return Promise.resolve();
19591
19823
  }
19592
19824
  const id = frame.t === "pf-offer" && typeof frame.id === "string" ? frame.id : void 0;
19825
+ const ended = id !== void 0 && !chat.files.get("in", id) ? chat.withdrawn.get(id) : void 0;
19826
+ if (ended !== void 0) {
19827
+ chat.withdrawn.delete(id);
19828
+ this.announcedHere(chat, id, ended, this.deps.transfers.get(ended)?.size ?? 0, Date.now());
19829
+ }
19593
19830
  if (id !== void 0 && chat.announced.has(id)) return chat.files.handle(frame).finally(() => {
19594
19831
  if (chat.announced.has(id) && !chat.files.get("in", id)) this.withdrawn(chat, id, "It was refused here");
19595
19832
  });
@@ -19633,11 +19870,16 @@ var FileDesk = class {
19633
19870
  size
19634
19871
  });
19635
19872
  }
19636
- /** A file said on the floor will not come (cancelled by its sender, or never offered within a week). */
19873
+ /** This device refuses the offer of a file said on the floor: its bubble ends, saying why (`floorRefusal`). */
19874
+ refusedHere(chat, frame) {
19875
+ if (frame.t === "pf-refuse" && typeof frame.id === "string") this.withdrawn(chat, frame.id, floorRefusal(frame.why));
19876
+ }
19877
+ /** A file said on the floor will not come (cancelled by its sender, refused here, or never offered within a week). */
19637
19878
  withdrawn(chat, wireId, error) {
19638
19879
  const said = chat.announced.get(wireId);
19639
19880
  if (!said) return;
19640
19881
  chat.announced.delete(wireId);
19882
+ chat.withdrawn.set(wireId, said.local);
19641
19883
  const transfer = {
19642
19884
  state: "failed",
19643
19885
  transferred: 0,
@@ -19770,6 +20012,7 @@ var FileDesk = class {
19770
20012
  if (!out) {
19771
20013
  chat.local.delete(wireId);
19772
20014
  chat.announced.delete(wireId);
20015
+ chat.withdrawn.delete(wireId);
19773
20016
  }
19774
20017
  this.speeds.delete(fileId);
19775
20018
  this.unwatch(fileId);
@@ -19999,7 +20242,8 @@ var FileDesk = class {
19999
20242
  clearTimeout(held.timer);
20000
20243
  chat.unsaved.delete(id);
20001
20244
  }
20002
- chat.lastSaved.set(id, Date.now());
20245
+ if (transferEnded(record)) chat.lastSaved.delete(id);
20246
+ else chat.lastSaved.set(id, Date.now());
20003
20247
  const transfer = this.deps.transfers.get(id);
20004
20248
  chat.saving = chat.saving.then(() => fileStore.patch(id, {
20005
20249
  wire3: record,
@@ -20037,7 +20281,10 @@ var FileDesk = class {
20037
20281
  view.room = this.deps.transfers.get(id)?.room;
20038
20282
  this.room(id);
20039
20283
  }
20040
- if (record.state !== "done" || this.underway.has(id) || this.deps.transfers.has(id)) this.deps.transfers.set(id, view);
20284
+ if (record.state !== "done" || this.underway.has(id) || this.deps.transfers.has(id)) {
20285
+ this.deps.transfers.set(id, view);
20286
+ if (record.state === "done") this.finished(id);
20287
+ }
20041
20288
  if (!transferEnded(record)) {
20042
20289
  this.underway.add(id);
20043
20290
  this.ended.delete(id);
@@ -20080,6 +20327,22 @@ var FileDesk = class {
20080
20327
  ended = /* @__PURE__ */ new Set();
20081
20328
  /** Transfers seen under way in this run, until they end. */
20082
20329
  underway = /* @__PURE__ */ new Set();
20330
+ /** The views of the transfers that finished last in this run, oldest first (`finished`). */
20331
+ done = /* @__PURE__ */ new Set();
20332
+ /**
20333
+ * A transfer finished: its view stays for the next states (its bubble, the CLI's `file.done`), then leaves them once
20334
+ * newer ones finished. A file with no transfer reads as finished, so the bubble needs none; a view kept for each would
20335
+ * go into every state the engine builds, so each would cost more with every file the chat had in this run.
20336
+ */
20337
+ finished(id) {
20338
+ this.done.delete(id);
20339
+ this.done.add(id);
20340
+ for (const oldest of this.done) {
20341
+ if (this.done.size <= DONE_VIEWS_KEPT) break;
20342
+ this.done.delete(oldest);
20343
+ if (this.deps.transfers.get(oldest)?.state === "done") this.deps.transfers.delete(oldest);
20344
+ }
20345
+ }
20083
20346
  /** The free space an offer is decided against, shown with it. */
20084
20347
  async room(id) {
20085
20348
  const room = await (await fileBytes()).room().catch(() => null);
@@ -20397,6 +20660,13 @@ function takesPeerEdit(message, text) {
20397
20660
  return message.sender === "peer" && !message.file && !message.paymentId && !message.event && !message.groupPay && !JOIN_NOTICE$1.test(message.text) && (text === void 0 || !JOIN_NOTICE$1.test(text));
20398
20661
  }
20399
20662
  /**
20663
+ * A message its author may delete for everyone (WISP 400 § Delete for everyone), either side: a text, a card, a file or
20664
+ * a voice message; never a payment or a request (a bearer token is not taken back), a notice or a group's line.
20665
+ */
20666
+ function canRemove(message) {
20667
+ return !message.paymentId && !message.event && !message.groupPay && !JOIN_NOTICE$1.test(message.text);
20668
+ }
20669
+ /**
20400
20670
  * The message after edit `seq`, made at `at`: the new text (and the preview and the status card that came with it, or
20401
20671
  * none: each belongs to its version), the version it replaces kept in the history. A text that did not change adds no
20402
20672
  * version. A status card's update adds none either (WISP 405 · Status Cards): it replaces the card in place, and its
@@ -21212,7 +21482,13 @@ var EditQueue = class {
21212
21482
  }
21213
21483
  if (!this.pace.take()) break;
21214
21484
  const receiptMs = typeof this.deps.receiptMs === "function" ? this.deps.receiptMs() : this.deps.receiptMs ?? 2e4;
21215
- if (await this.deps.send({
21485
+ if (await this.deps.send(message.removed ? {
21486
+ id: message.wireId,
21487
+ e: edit.seq,
21488
+ ts: edit.at,
21489
+ m: message.text,
21490
+ rm: true
21491
+ } : {
21216
21492
  id: message.wireId,
21217
21493
  e: edit.seq,
21218
21494
  ts: edit.at,
@@ -21326,6 +21602,58 @@ var EditBuffer = class {
21326
21602
  }
21327
21603
  };
21328
21604
  //#endregion
21605
+ //#region ../browser/src/engine/removals.ts
21606
+ /** The removal of a message after its last edit `seq`: one past it, at most `MAX_REMOVAL_NUMBER`. */
21607
+ var removalNumber = (seq) => Math.min((seq ?? 0) + 1, MAX_REMOVAL_NUMBER);
21608
+ /** The row a removal reads as to the edit queues: mine, its fallback text, its edit pending until said. */
21609
+ function removalRow(linkId, removal) {
21610
+ return {
21611
+ linkId,
21612
+ id: removal.id,
21613
+ ...removal.wireId && { wireId: removal.wireId },
21614
+ text: REMOVED_TEXT,
21615
+ sender: "me",
21616
+ timestamp: removal.at,
21617
+ via: "datalink",
21618
+ delivery: "delivered",
21619
+ removed: true,
21620
+ edit: {
21621
+ seq: removal.e,
21622
+ at: removal.at,
21623
+ history: [],
21624
+ ...removal.pending && { pending: true }
21625
+ }
21626
+ };
21627
+ }
21628
+ /** The list with this removal in it, in place of an older one of the same message; the newest `MAX_REMOVALS`. */
21629
+ function withRemoval(list, removal) {
21630
+ return [...(list ?? []).filter((r) => r.id !== removal.id), removal].slice(-500);
21631
+ }
21632
+ /**
21633
+ * A change an edit queue made to a removal's row (`patch`), on the list: the edit said or confirmed is no longer pending.
21634
+ * `drop`: confirmed in a 1:1 chat, nothing is left to say. Null when nothing changed.
21635
+ */
21636
+ function patchRemoval(list, id, change, linkId, drop = false) {
21637
+ const removal = list?.find((r) => r.id === id);
21638
+ if (!removal) return null;
21639
+ const row = removalRow(linkId, removal), patch = change(row);
21640
+ if (!patch) return null;
21641
+ const next = {
21642
+ ...row,
21643
+ ...patch
21644
+ };
21645
+ const left = list.filter((r) => r.id !== id);
21646
+ if (drop && !next.edit?.pending) return {
21647
+ list: left,
21648
+ row: next
21649
+ };
21650
+ const { pending: _said, ...said } = removal;
21651
+ return {
21652
+ list: [...left, next.edit?.pending ? removal : said],
21653
+ row: next
21654
+ };
21655
+ }
21656
+ //#endregion
21329
21657
  //#region ../browser/src/shared/walletRemoval.ts
21330
21658
  var UNFINISHED = /* @__PURE__ */ new Set([
21331
21659
  "pending",
@@ -23232,7 +23560,8 @@ var Communities = class {
23232
23560
  ts: edit.ts,
23233
23561
  text: edit.m,
23234
23562
  mentions: edit.k,
23235
- ...edit.sc && { card: edit.sc }
23563
+ ...edit.sc && { card: edit.sc },
23564
+ ...edit.rm && { remove: true }
23236
23565
  }, this.host.myNick?.(), this.now());
23237
23566
  if ("error" in result) return result.error;
23238
23567
  const key = editKey(edit.id, edit.e);
@@ -24490,6 +24819,7 @@ var Communities = class {
24490
24819
  const file = m.file && this.files ? await this.files.announced(id, {
24491
24820
  id: m.id,
24492
24821
  sender: m.sender,
24822
+ ts: m.timestamp,
24493
24823
  file: m.file
24494
24824
  }, session.myKey) : void 0;
24495
24825
  const placing = this.lineOrder.placing(MESSAGE_LINK$1(id), {
@@ -24715,6 +25045,7 @@ var MeshHubs = class {
24715
25045
  clocks,
24716
25046
  me: "",
24717
25047
  firstRead: false,
25048
+ epochRead: false,
24718
25049
  lastRead: 0,
24719
25050
  lastWrite: 0,
24720
25051
  lastTry: 0,
@@ -24915,6 +25246,7 @@ var MeshHubs = class {
24915
25246
  live.lastWrite = 0;
24916
25247
  live.lastTry = 0;
24917
25248
  live.beacon = [];
25249
+ live.epochRead = false;
24918
25250
  live.clocks.restart();
24919
25251
  }
24920
25252
  const policy = session.hubPolicy, me = session.myKey, inRoster = (key) => rosterHas(session.roster, key);
@@ -24924,16 +25256,16 @@ var MeshHubs = class {
24924
25256
  const others = this.listed(live, session, now);
24925
25257
  const fits = this.fits(groupId, session);
24926
25258
  if (live.hub) live.need = session.others.length;
24927
- if (!live.hub && may && fits && (policy.pin.includes(me) || others.length < MESH_HUBS.maxHubs)) {
25259
+ if (!live.hub && may && fits && (policy.pin.includes(me) || live.epochRead && others.length < MESH_HUBS.maxHubs)) {
24928
25260
  live.hub = true;
24929
25261
  live.hubSince = now;
24930
25262
  live.myHubs = [];
24931
25263
  live.need = session.others.length;
24932
25264
  await this.publish(groupId, session, live, now, true).catch(() => {});
24933
- } else if (live.hub && (!may || !fits)) {
25265
+ } else if (live.hub && (!may || !fits || this.full(live, session, now))) {
24934
25266
  live.hub = false;
24935
25267
  live.members.clear();
24936
- await this.publish(groupId, session, live, now, false).catch(() => {});
25268
+ if (!may || !fits) await this.publish(groupId, session, live, now, false).catch(() => {});
24937
25269
  } else if (live.hub && now - live.lastTry >= 5e3 && (now - live.lastWrite >= this.timings.beaconEveryMs || !live.beacon.some((h) => h.key === me))) await this.publish(groupId, session, live, now, true).catch(() => {});
24938
25270
  if (live.hub) {
24939
25271
  await this.serve(groupId, session, live, now, rv);
@@ -24945,6 +25277,14 @@ var MeshHubs = class {
24945
25277
  } else await this.pick(groupId, session, group, live, now, rv);
24946
25278
  return before !== this.shape(live);
24947
25279
  }
25280
+ /**
25281
+ * The beacon holds eight hubs, the newest: a hub that a reading of it no longer shows, beside eight others, is one too
25282
+ * many, and writing itself in again would only push another out (each would, in turn, and none ever step down). A
25283
+ * pinned hub lists itself whatever the beacon holds.
25284
+ */
25285
+ full(live, session, now) {
25286
+ return live.epochRead && !session.hubPolicy.pin.includes(session.myKey) && !live.beacon.some((h) => h.key === session.myKey) && this.listed(live, session, now).length >= MESH_HUBS.maxHubs;
25287
+ }
24948
25288
  shape(live) {
24949
25289
  return `${live.hub}|${live.myHubs.join(",")}|${[...live.members.keys()].sort().join(",")}|${live.beacon.map((h) => h.key).sort().join(",")}`;
24950
25290
  }
@@ -24959,6 +25299,7 @@ var MeshHubs = class {
24959
25299
  }
24960
25300
  live.beacon = live.clocks.inMyTime(readBeacon(keys, records ?? []), now);
24961
25301
  live.firstRead = true;
25302
+ live.epochRead = true;
24962
25303
  this.noteHubs(live, session, now);
24963
25304
  }
24964
25305
  noteHubs(live, session, now) {
@@ -24981,6 +25322,14 @@ var MeshHubs = class {
24981
25322
  return;
24982
25323
  }
24983
25324
  existing = live.clocks.inMyTime(readBeacon(keys, records ?? []), now);
25325
+ if (listed) {
25326
+ live.beacon = existing;
25327
+ live.lastRead = now;
25328
+ live.firstRead = true;
25329
+ live.epochRead = true;
25330
+ this.noteHubs(live, session, now);
25331
+ if (this.full(live, session, now)) return;
25332
+ }
24984
25333
  }
24985
25334
  const policy = session.hubPolicy;
24986
25335
  const hubs = mergeBeacon(existing, session.myKey, listed ? {
@@ -24994,6 +25343,7 @@ var MeshHubs = class {
24994
25343
  live.lastWrite = now;
24995
25344
  live.lastRead = now;
24996
25345
  live.firstRead = true;
25346
+ live.epochRead = true;
24997
25347
  this.noteHubs(live, session, now);
24998
25348
  }
24999
25349
  /** As a hub: who asked in my lobby, and which of my members are still around. */
@@ -25618,7 +25968,7 @@ var peerMessageAt = (map, groupId) => {
25618
25968
  var ENTRY_TIMINGS = {
25619
25969
  pollMs: 5e3,
25620
25970
  warmPollMs: 2e3,
25621
- warmMs: 6e5,
25971
+ warmMs: 6e4,
25622
25972
  knockMs: 5e3,
25623
25973
  slowKnockMs: 2e4,
25624
25974
  patienceMs: 12e4
@@ -26102,7 +26452,8 @@ var Groups = class {
26102
26452
  ts: edit.ts,
26103
26453
  text: edit.m,
26104
26454
  mentions: edit.k,
26105
- ...edit.sc && { card: edit.sc }
26455
+ ...edit.sc && { card: edit.sc },
26456
+ ...edit.rm && { remove: true }
26106
26457
  }, to);
26107
26458
  return "error" in result ? result.error : null;
26108
26459
  }
@@ -26368,7 +26719,7 @@ var Groups = class {
26368
26719
  me: session.myKey,
26369
26720
  community: false,
26370
26721
  inRoster: (key) => rosterHas(session.roster, key),
26371
- couldRead: (key, messageId) => session.couldRead(key, messageId)
26722
+ couldRead: (key, messageId, ts) => session.couldRead(key, messageId, ts)
26372
26723
  };
26373
26724
  }
26374
26725
  /**
@@ -26553,6 +26904,33 @@ var Groups = class {
26553
26904
  const commit = frame && typeof frame === "object" && frame.t === "group-commit" ? frame.commit : void 0;
26554
26905
  return typeof commit?.e === "number" && commit.e <= removalEpoch(session.state.chain, key);
26555
26906
  }
26907
+ /** My removals on their way in a group (`engine/removals.ts`). */
26908
+ removals(groupId) {
26909
+ return this.stored.get(groupId)?.removals ?? [];
26910
+ }
26911
+ async setRemovals(groupId, removals) {
26912
+ const group = this.stored.get(groupId);
26913
+ if (!group) return;
26914
+ group.removals = removals;
26915
+ await this.store.putGroup(group);
26916
+ }
26917
+ /** A member's message its author deleted for everyone (WISP 400 § Delete for everyone): a copy that comes again is not kept. */
26918
+ isRemoved(groupId, messageId) {
26919
+ return !!this.stored.get(groupId)?.removedIds?.includes(messageId);
26920
+ }
26921
+ /**
26922
+ * Its author deleted a message for everyone: noted so (the newest `MAX_REMOVED_IDS`, also when the message is not here
26923
+ * yet, so it is taken as gone when it comes), and its file goes from this device.
26924
+ */
26925
+ async removed(groupId, messageId) {
26926
+ const group = this.stored.get(groupId);
26927
+ if (!group) return;
26928
+ if (!group.removedIds?.includes(messageId)) {
26929
+ group.removedIds = [...group.removedIds ?? [], messageId].slice(-500);
26930
+ await this.store.putGroup(group);
26931
+ }
26932
+ await this.files?.forget(groupId, messageId);
26933
+ }
26556
26934
  /** The connection of an edge opened. One kept to tell a removed member closes a while after, whatever its app says or does not say. */
26557
26935
  edgeOpen(groupId, peerKey) {
26558
26936
  const group = this.stored.get(groupId), farewell = group?.farewells?.[peerKey];
@@ -28035,6 +28413,7 @@ var Groups = class {
28035
28413
  const file = m.file && this.files ? await this.files.announced(state.id, {
28036
28414
  id: m.id,
28037
28415
  sender: m.sender,
28416
+ ts: m.timestamp,
28038
28417
  file: m.file
28039
28418
  }, session.myKey) : void 0;
28040
28419
  const message = {
@@ -28388,13 +28767,24 @@ function mergeGroupPay(current, frame, author, members) {
28388
28767
  };
28389
28768
  return JSON.stringify(next) === JSON.stringify(current) ? void 0 : next;
28390
28769
  }
28391
- var railOf = (p) => p.target ? p.target.method === "cashu" ? "cashu" : p.target.method : p.invoice && !p.mints?.length && !p.mint ? "lightning" : "cashu";
28392
- var testOf = (p) => p.target ? p.target.method === "cashu" ? p.target.network === "cashu-test" : p.target.method === "usdt" ? p.unit === "testusdt" : p.target.network !== "bitcoin" : p.mint ? isWorthlessMint(p.mint) : p.mints?.length ? p.mints.every(isWorthlessMint) : false;
28770
+ var federationOf = (p) => p.federation ?? p.federations?.[0];
28771
+ var railOf = (p) => p.target ? p.target.method === "cashu" ? "cashu" : p.target.method : federationOf(p) ? "fedimint" : p.invoice && !p.mints?.length && !p.mint ? "lightning" : "cashu";
28772
+ /** Test money as the chat's bubble reads it (paymentIsTest): a target's chain, else the record's network, else a Fedimint federation's network, else its mints. */
28773
+ var testOf = (p, federationNetwork) => {
28774
+ if (p.target) return p.target.method === "cashu" ? p.target.network === "cashu-test" : p.target.method === "usdt" ? p.unit === "testusdt" : p.target.network !== "bitcoin";
28775
+ if (p.network) return p.network === "testnet";
28776
+ const federation = federationOf(p);
28777
+ if (federation) {
28778
+ const network = federationNetwork(federation);
28779
+ return !!network && network !== "bitcoin";
28780
+ }
28781
+ return p.mint ? isWorthlessMint(p.mint) : p.mints?.length ? p.mints.every(isWorthlessMint) : false;
28782
+ };
28393
28783
  /**
28394
28784
  * What this device says about one of its own payments in a group, or null when it says nothing (not a group's,
28395
28785
  * or nothing to say yet). `all` is every desk record, to find a request's payments and whether this device paid it.
28396
28786
  */
28397
- function authoredNote(p, at, all, current, memberOf = () => void 0) {
28787
+ function authoredNote(p, at, all, current, memberOf = () => void 0, federationNetwork = () => void 0) {
28398
28788
  const base = {
28399
28789
  t: "group-pay",
28400
28790
  g: at.groupId,
@@ -28403,7 +28793,7 @@ function authoredNote(p, at, all, current, memberOf = () => void 0) {
28403
28793
  u: p.unit,
28404
28794
  d: p.target?.method === "usdt" ? p.target.decimals ?? 6 : 0,
28405
28795
  r: railOf(p),
28406
- ...testOf(p) ? { x: 1 } : {},
28796
+ ...testOf(p, federationNetwork) ? { x: 1 } : {},
28407
28797
  ...p.memo ? { m: p.memo.slice(0, 140) } : {},
28408
28798
  ...p.ask ? { a: 1 } : {},
28409
28799
  ts: p.createdAt
@@ -28501,7 +28891,7 @@ var GroupPayments = class {
28501
28891
  const at = this.placement(p, membership);
28502
28892
  if (!at) continue;
28503
28893
  const current = (await this.load(at.groupId)).get(paymentWireId(p.id));
28504
- const frame = authoredNote(p, at, all, current, (linkId) => this.host.edgeOf(linkId)?.member);
28894
+ const frame = authoredNote(p, at, all, current, (linkId) => this.host.edgeOf(linkId)?.member, (federation) => this.host.federationNetwork?.(federation));
28505
28895
  if (!frame || JSON.stringify(frame) === JSON.stringify(current?.mine)) continue;
28506
28896
  const merged = mergeGroupPay(current, frame, at.me, membership(at.groupId).members) ?? current;
28507
28897
  if (!merged) continue;
@@ -28565,6 +28955,21 @@ var GROUP_EDIT_RESEND_WINDOW_MS = EDIT_RATE_WINDOW_MS + 1e3;
28565
28955
  /** An edit that could not go (no epoch key yet) is tried again after this long. */
28566
28956
  var RETRY_MS = 1e4;
28567
28957
  var chatOf = (groupId) => `group:${groupId}`;
28958
+ /** What a row of mine says to the group as its latest edit: a removal its fallback text alone (WISP 400 § Delete for everyone). */
28959
+ var said = (m) => m.removed ? {
28960
+ id: m.id,
28961
+ e: m.edit.seq,
28962
+ ts: m.edit.at,
28963
+ m: m.text,
28964
+ rm: true
28965
+ } : {
28966
+ id: m.id,
28967
+ e: m.edit.seq,
28968
+ ts: m.edit.at,
28969
+ m: m.text,
28970
+ ...m.mentions?.length && { k: m.mentions },
28971
+ ...m.card && { sc: m.card }
28972
+ };
28568
28973
  var resendKey = (groupId, member) => `${groupId}\n${member}`;
28569
28974
  var GroupEdits = class {
28570
28975
  host;
@@ -28655,6 +29060,34 @@ var GroupEdits = class {
28655
29060
  messageId
28656
29061
  };
28657
29062
  }
29063
+ /**
29064
+ * Deletes a message of mine for everyone (WISP 400 § Delete for everyone): gone here at once, and its removal said to
29065
+ * the group as the message's last edit, at the pace of edits. A text, a card, a file or a voice message; never a
29066
+ * payment, a note or an event line.
29067
+ */
29068
+ async removeMine(groupId, messageId) {
29069
+ const refuse = (error) => ({
29070
+ error,
29071
+ refused: true
29072
+ });
29073
+ if (!this.host.membership(groupId)) return refuse("You are not in this group");
29074
+ const chat = chatOf(groupId);
29075
+ const message = typeof messageId === "string" ? await this.find(chat, messageId) : void 0;
29076
+ if (!message || message.removed || message.sender !== "me" || !GROUP_MESSAGE_ID.test(message.id)) return refuse("Only your own messages can be deleted for everyone");
29077
+ if (!canRemove(message)) return refuse("A payment, a request or a notice cannot be deleted for everyone");
29078
+ await this.host.removeMine(chat, message, {
29079
+ id: message.id,
29080
+ e: removalNumber(message.edit?.seq),
29081
+ at: this.now(),
29082
+ pending: true
29083
+ });
29084
+ if (this.host.message) this.told(groupId).set(messageId, ++this.tick);
29085
+ await this.flush(groupId).catch(() => {});
29086
+ return {
29087
+ error: null,
29088
+ messageId
29089
+ };
29090
+ }
28658
29091
  /** Says my pending edits in a group, oldest first, at the pace allowed; what waits goes when the window has room. */
28659
29092
  flush(groupId) {
28660
29093
  const running = this.flushing.get(groupId);
@@ -28682,14 +29115,7 @@ var GroupEdits = class {
28682
29115
  retry = Math.min(retry, pace.wait());
28683
29116
  break;
28684
29117
  }
28685
- if (await this.host.send(groupId, {
28686
- id: message.id,
28687
- e: edit.seq,
28688
- ts: edit.at,
28689
- m: message.text,
28690
- ...message.mentions?.length && { k: message.mentions },
28691
- ...message.card && { sc: message.card }
28692
- })) {
29118
+ if (await this.host.send(groupId, said(message))) {
28693
29119
  retry = Math.min(retry, RETRY_MS);
28694
29120
  continue;
28695
29121
  }
@@ -28809,6 +29235,11 @@ var GroupEdits = class {
28809
29235
  async take(groupId, membership, sender, edit) {
28810
29236
  const chat = chatOf(groupId);
28811
29237
  const message = await this.find(chat, edit.id);
29238
+ if (edit.rm) {
29239
+ if (message && (message.sender !== "peer" || message.member !== sender || !canRemove(message))) return "dropped";
29240
+ await this.host.remove(chat, edit.id);
29241
+ return "applied";
29242
+ }
28812
29243
  if (!message) {
28813
29244
  this.buffer.hold(chat, {
28814
29245
  ...edit,
@@ -28895,14 +29326,7 @@ var GroupEdits = class {
28895
29326
  }, Math.max(50, pace.wait())));
28896
29327
  return;
28897
29328
  }
28898
- await this.host.send(groupId, {
28899
- id: m.id,
28900
- e: m.edit.seq,
28901
- ts: m.edit.at,
28902
- m: m.text,
28903
- ...m.mentions?.length && { k: m.mentions },
28904
- ...m.card && { sc: m.card }
28905
- }, to);
29329
+ await this.host.send(groupId, said(m), to);
28906
29330
  if (open() !== edge) return;
28907
29331
  if (after(m)) this.heard.set(key, {
28908
29332
  at: m.edit.at,
@@ -32817,6 +33241,8 @@ var UNIT = "sat";
32817
33241
  /** A contact's requests in one chat: the new ones taken per minute, and how many may wait to be paid. */
32818
33242
  var REQUESTS_PER_MINUTE = 20;
32819
33243
  var OPEN_REQUESTS = 50;
33244
+ var INVOICE_CLAIMS_KEY = "invoicePaidClaims";
33245
+ var sameClaim = (a, b) => a.linkId === b.linkId && a.invoice.toLowerCase() === b.invoice.toLowerCase();
32820
33246
  var satsWord = (n) => `${n} sat${n === 1 ? "" : "s"}`;
32821
33247
  /**
32822
33248
  * A refused send's review, once its ecash came back: why, and exactly what came back. Taking ecash back is a swap at
@@ -32979,6 +33405,8 @@ var PaymentDesk = class {
32979
33405
  async start() {
32980
33406
  const stored = await wrap((await store(STORES$1.payments, "readonly")).getAll());
32981
33407
  for (const payment of stored) this.payments.set(payment.id, payment);
33408
+ const claims = await wrap((await store(STORES$1.settings, "readonly")).get(INVOICE_CLAIMS_KEY));
33409
+ this.claims = [...(claims ?? []).filter((c) => !this.claims.some((d) => sameClaim(c, d))), ...this.claims];
32982
33410
  }
32983
33411
  /** Every payment as stored, tokens included: for the engine's own reading, never for a page. */
32984
33412
  records() {
@@ -32995,6 +33423,7 @@ var PaymentDesk = class {
32995
33423
  this.payments.delete(payment.id);
32996
33424
  wrap(paymentStore.delete(payment.id));
32997
33425
  }
33426
+ if (this.claims.some((c) => c.linkId === linkId)) this.keepClaims(this.claims.filter((c) => c.linkId !== linkId));
32998
33427
  this.requestsFrom.delete(linkId);
32999
33428
  }
33000
33429
  /** `confirmedReal`: the person confirmed a Mainnet send as real money; without it one is refused. */
@@ -33505,22 +33934,61 @@ var PaymentDesk = class {
33505
33934
  }
33506
33935
  /**
33507
33936
  * A Testnet invoice found in a chat message, paid from its card: the chat's contact is told as `sayPaid` does, with
33508
- * no request (it may be one from their Receive screen, held until a payer says it paid).
33937
+ * no request (it may be one from their Receive screen, held until a payer says it paid). Kept until it gets through
33938
+ * (`InvoiceClaim`); `pending`: the payment has not settled yet, and it is said once it does.
33509
33939
  */
33510
- sayInvoicePaid(linkId, invoice) {
33511
- const link = this.host.getLink(linkId);
33512
- const amount = decodeBolt11(invoice)?.amountSat;
33940
+ sayInvoicePaid(linkId, invoice, { pending } = {}) {
33941
+ const decoded = decodeBolt11(invoice);
33942
+ if (!decoded?.amountSat) return;
33943
+ const claim = {
33944
+ linkId,
33945
+ invoice: invoice.trim(),
33946
+ ...pending ? { pending } : {},
33947
+ expiresAt: (decoded.expiresAt + 60) * 1e3
33948
+ };
33949
+ this.keepClaims([...this.claims.filter((c) => !sameClaim(c, claim)), claim]).then(() => pending ? void 0 : this.tellClaim(claim));
33950
+ }
33951
+ claims = [];
33952
+ claimWrites = Promise.resolve();
33953
+ /** Says one `InvoiceClaim`, and forgets it once it went out; one that did not is said again when the chat is up. */
33954
+ async tellClaim(claim) {
33955
+ const link = this.host.getLink(claim.linkId);
33956
+ const amount = decodeBolt11(claim.invoice)?.amountSat;
33513
33957
  if (!link || !amount) return;
33514
- this.sendTo(link, {
33515
- id: newId(),
33516
- timestamp: Date.now(),
33517
- amount: {
33518
- value: String(amount),
33519
- asset: UNIT
33520
- },
33521
- endpoint: [ENDPOINT.bolt11, invoice.trim()]
33958
+ try {
33959
+ await this.sendTo(link, {
33960
+ id: newId(),
33961
+ timestamp: Date.now(),
33962
+ amount: {
33963
+ value: String(amount),
33964
+ asset: UNIT
33965
+ },
33966
+ endpoint: [ENDPOINT.bolt11, claim.invoice]
33967
+ });
33968
+ } catch {
33969
+ return;
33970
+ }
33971
+ await this.keepClaims(this.claims.filter((c) => c.pending || !sameClaim(c, claim)));
33972
+ }
33973
+ /** The claims from now on, expired ones left out, written in the order they were made. */
33974
+ keepClaims(next) {
33975
+ const now = Date.now();
33976
+ const kept = this.claims = next.filter((c) => c.expiresAt > now);
33977
+ return this.claimWrites = this.claimWrites.then(async () => {
33978
+ await wrap((await store(STORES$1.settings, "readwrite")).put(kept, INVOICE_CLAIMS_KEY));
33522
33979
  }).catch(() => {});
33523
33980
  }
33981
+ /** A payment left pending ended: the chats whose invoice it paid are told now, and none when it failed. */
33982
+ settleClaims(invoice, paid) {
33983
+ const wanted = invoice?.trim().toLowerCase();
33984
+ const settled = wanted ? this.claims.filter((c) => c.pending && c.invoice.toLowerCase() === wanted) : [];
33985
+ if (!settled.length) return;
33986
+ const told = settled.map(({ pending: _pending, ...claim }) => claim);
33987
+ const rest = this.claims.filter((c) => !settled.includes(c) && !(paid && told.some((t) => sameClaim(c, t))));
33988
+ this.keepClaims(paid ? [...rest, ...told] : rest).then(() => {
33989
+ if (paid) for (const claim of told) this.tellClaim(claim);
33990
+ });
33991
+ }
33524
33992
  /**
33525
33993
  * Takes back ecash the peer never redeemed. If they did redeem it, the mint says so and the payment is settled.
33526
33994
  * Resolves to what came back of Cashu ecash (and the mint's fee for it); undefined when nothing did, or not Cashu.
@@ -34113,6 +34581,8 @@ var PaymentDesk = class {
34113
34581
  }
34114
34582
  lastCheck = /* @__PURE__ */ new Map();
34115
34583
  lastCheckFrom = /* @__PURE__ */ new Map();
34584
+ /** `receiveInvoicePaid`'s last look, by `<link id>:<invoice>`: only the last 3 seconds' are kept. */
34585
+ lastInvoiceCheck = /* @__PURE__ */ new Map();
34116
34586
  /**
34117
34587
  * "I paid it from another wallet": the contact's app is asked to look at its wallet now. Nothing here
34118
34588
  * marks anything paid; the request settles when the payee's wallet sees the money, with or without this.
@@ -34171,21 +34641,25 @@ var PaymentDesk = class {
34171
34641
  /**
34172
34642
  * The contact says it paid an invoice of ours it found in the chat, with no request: a Receive-screen invoice is
34173
34643
  * held on a test mint until then (StoredQuote `held`), and that one alone is let go. A request's invoice is spoken
34174
- * for by its own contact only (`receiveCheck`). Bounded: one look every 3 seconds per chat.
34644
+ * for by its own contact only (`receiveCheck`). Bounded: one look every 3 seconds per invoice of a chat, so two
34645
+ * invoices paid one right after the other are both let go.
34175
34646
  */
34176
34647
  async receiveInvoicePaid(linkId, link, invoice) {
34177
34648
  if (!link.allowsPayment("lightning")) return;
34178
34649
  const now = Date.now();
34179
- if (now - (this.lastCheckFrom.get(`chat:${linkId}`) ?? 0) < 3e3) return;
34180
- this.lastCheckFrom.set(`chat:${linkId}`, now);
34181
34650
  const wanted = invoice.trim().toLowerCase();
34651
+ const key = `${linkId}:${wanted}`;
34652
+ if (now - (this.lastInvoiceCheck.get(key) ?? 0) < 3e3) return;
34653
+ for (const [seen, at] of this.lastInvoiceCheck) if (now - at >= 3e3) this.lastInvoiceCheck.delete(seen);
34654
+ this.lastInvoiceCheck.set(key, now);
34182
34655
  try {
34183
34656
  const quote = (await this.wallet.quotes()).find((q) => q.held && !q.paymentId && q.invoice.toLowerCase() === wanted);
34184
34657
  if (quote) await this.wallet.vouch(quote.invoice);
34185
34658
  } catch {}
34186
34659
  }
34187
- /** A Lightning payment of a contact's request that was left pending (or unknown) settled. */
34660
+ /** A Lightning payment of a contact's request, or of a chat's invoice, that was left pending (or unknown) settled. */
34188
34661
  async onLightningResolved(op, paid) {
34662
+ this.settleClaims(op.invoice, paid);
34189
34663
  const found = op.paymentId ? this.payments.get(op.paymentId) : void 0;
34190
34664
  if (found?.kind !== "request" || found.direction !== "in") return;
34191
34665
  const request = {
@@ -35302,6 +35776,7 @@ var PaymentDesk = class {
35302
35776
  async replay(linkId) {
35303
35777
  const link = this.host.getLink(linkId);
35304
35778
  if (!link?.supportsPayments) return;
35779
+ for (const claim of this.claims) if (claim.linkId === linkId && !claim.pending && claim.expiresAt > Date.now()) await this.tellClaim(claim);
35305
35780
  const group = this.host.groupOf?.(linkId);
35306
35781
  if (group) for (const request of this.payments.values()) {
35307
35782
  if (request.group !== group || request.kind !== "request" || request.direction !== "out") continue;
@@ -35812,6 +36287,10 @@ var CLEAR_WITHDRAW_MS = 6e3;
35812
36287
  * session): a dial to a contact that is not there ends within its 20 s timeout, and leaves its slot free until the next.
35813
36288
  */
35814
36289
  var ACTIVE_SLOT_RETRY_MS = 3e3;
36290
+ /** How long an edge passed over that way ranks after the others, before the group tries it again. */
36291
+ var GROUP_ANCHOR_PASSED_MS = 3e5;
36292
+ /** How often the edges groups keep are looked at for that (`groupAnchorsAnswered`). */
36293
+ var GROUP_ANCHOR_CHECK_MS = 5e3;
35815
36294
  /**
35816
36295
  * How long a chat live when the app last ran may take to be live again before that stretch counts as over
35817
36296
  * (`TransportLog.notBackAfterRestart`): past the contact's liveness bound (three pings missed), the session it held is
@@ -35846,6 +36325,8 @@ var CARD_RESTORE_EVERY_MS = 3e4;
35846
36325
  var RTT_SAVE_MS = 3e5;
35847
36326
  /** A reaction said on the live session and not confirmed is said again after this long. */
35848
36327
  var REACTION_RESEND_MS = 3e4;
36328
+ /** When the contact's newest message over the DHT in these was sent (`LiveLink.pkarrSeenAt`). */
36329
+ var pkarrSeenAt = (messages) => messages.reduce((max, m) => m.sender === "peer" && m.via === "pkarr" ? Math.max(max, m.sentAt ?? m.timestamp) : max, 0);
35849
36330
  /** A file or a payment request of mine that waits for the chat to be live (a text that waits is its outbox's). */
35850
36331
  var waitsForLive = (m) => m.sender === "me" && m.delivery === "waiting" && (!!m.file || !!m.paymentId);
35851
36332
  /** This side's participation key in a chat: derived from its seed once, not at every state built. */
@@ -36021,6 +36502,8 @@ var GhostlyNode = class GhostlyNode {
36021
36502
  settings = DEFAULT_SETTINGS;
36022
36503
  /** Limited mode (`NodeOptions.limited`): on from the start until `leaveLimited()`. */
36023
36504
  limitedMode = false;
36505
+ /** The read at start (`NodeOptions.startCheck`) is still out: limited mode until it answers, and the pages ask nothing. */
36506
+ startChecking = false;
36024
36507
  /** Whether this engine is in limited mode (WISP 06 § When a device checks). */
36025
36508
  get limited() {
36026
36509
  return this.limitedMode;
@@ -36063,7 +36546,10 @@ var GhostlyNode = class GhostlyNode {
36063
36546
  localFetch;
36064
36547
  links = /* @__PURE__ */ new Map();
36065
36548
  services = [];
36549
+ /** The chat (its link id) or the group (`group:<id>`) on screen. */
36066
36550
  activeLinkId = null;
36551
+ /** When each chat or group (`group:<id>`) was last on screen, for handing native listeners out least recently used first (`lastUsed`). */
36552
+ openedAt = /* @__PURE__ */ new Map();
36067
36553
  /**
36068
36554
  * Native listeners start one at a time per transport (`ensureNativeEndpoints`): their slots are counted per transport.
36069
36555
  * Not one queue for all: a transport slow to start held every other chat's listeners of every kind behind it.
@@ -37097,10 +37583,15 @@ var GhostlyNode = class GhostlyNode {
37097
37583
  * Never a new message: no sound, no unread.
37098
37584
  */
37099
37585
  groupEdits = new GroupEdits({
37100
- messages: (chat) => db.getMessages(chat),
37101
- history: (chat) => this.edgeOpenHistory(chat),
37102
- message: (chat, id) => db.getMessage(chat, id),
37103
- patch: (chat, id, change) => db.patchMessage(chat, id, change),
37586
+ messages: async (chat) => [...await db.getMessages(chat), ...this.groupRemovalRows(chat)],
37587
+ history: async (chat) => [...await this.edgeOpenHistory(chat), ...this.groupRemovalRows(chat)],
37588
+ message: async (chat, id) => this.groupRemovalRow(chat, id) ?? await db.getMessage(chat, id),
37589
+ patch: async (chat, id, change) => {
37590
+ const groupId = chat.slice(6), patched = patchRemoval(this.groups.removals(groupId), id, change, chat);
37591
+ if (!patched) return db.patchMessage(chat, id, change);
37592
+ await this.groups.setRemovals(groupId, patched.list);
37593
+ return patched.row;
37594
+ },
37104
37595
  changed: (chat, id) => this.messagesChanged(chat, [id]),
37105
37596
  membership: (groupId) => {
37106
37597
  const membership = this.membership(groupId);
@@ -37111,11 +37602,35 @@ var GhostlyNode = class GhostlyNode {
37111
37602
  };
37112
37603
  },
37113
37604
  send: (groupId, edit, to) => this.groups.sendEdit(groupId, edit, to),
37605
+ remove: (chat, id) => this.forgetGroupMessage(chat, id),
37606
+ removeMine: async (chat, message, removal) => {
37607
+ const groupId = chat.slice(6);
37608
+ await this.groups.setRemovals(groupId, withRemoval(this.groups.removals(groupId), removal));
37609
+ await this.forgetGroupMessage(chat, message.id);
37610
+ },
37114
37611
  edge: (groupId, member) => {
37115
37612
  const link = this.links.get(this.memberEdges(groupId).get(member) ?? "")?.link;
37116
37613
  return link?.supportsGroupVersion(1) ? link : void 0;
37117
37614
  }
37118
37615
  });
37616
+ /**
37617
+ * A group's message deleted for everyone, by its author or by me: gone from this device with its file, and noted so a
37618
+ * copy that comes again (a catch-up, a member handing it on) is not stored. The replies here that quote it lose its line.
37619
+ */
37620
+ async forgetGroupMessage(chat, id) {
37621
+ await this.groups.removed(chat.slice(6), id);
37622
+ await db.deleteMessage(chat, id);
37623
+ await this.messagesChanged(chat, [id, ...await this.forgetQuotes(chat, id, id)]);
37624
+ this.emitState();
37625
+ }
37626
+ groupRemovalRows(chat) {
37627
+ return this.groups.removals(chat.slice(6)).map((r) => removalRow(chat, r));
37628
+ }
37629
+ /** The row of one removal of mine in a group, by the message's id: none when it is not one. */
37630
+ groupRemovalRow(chat, id) {
37631
+ const removal = this.groups.removals(chat.slice(6)).find((r) => r.id === id);
37632
+ return removal && removalRow(chat, removal);
37633
+ }
37119
37634
  /** A community member's edit, signed by them: of their own message, and only while they are a member. */
37120
37635
  async receiveCommunityEdit(groupId, sender, frame) {
37121
37636
  const edit = parseCommunityEdit(frame, sender);
@@ -37172,7 +37687,8 @@ var GhostlyNode = class GhostlyNode {
37172
37687
  } : this.placed(message));
37173
37688
  await this.messagesChanged(message.linkId, [message.id]);
37174
37689
  this.emitState();
37175
- }
37690
+ },
37691
+ federationNetwork: (federation) => this.fedimintOf(federation)?.federation(federation)?.network
37176
37692
  });
37177
37693
  /**
37178
37694
  * Member key → edge link id, for the edges of a group that exist (open or not), whoever is at the other end: an edge
@@ -37219,6 +37735,7 @@ var GhostlyNode = class GhostlyNode {
37219
37735
  this.options = options;
37220
37736
  this.relays = options.transport ? null : new RelayTransport();
37221
37737
  this.limitedMode = options.limited === true;
37738
+ this.startChecking = options.startCheck !== void 0;
37222
37739
  this.turnGoodAt = options.turnReadAt ?? null;
37223
37740
  this.transport = this.limitedMode ? refusingWhileLimited(options.transport ?? this.relays, () => this.limitedMode) : options.transport ?? this.relays;
37224
37741
  this.groupTransport = withRequestOptions(this.transport, { group: true });
@@ -37294,14 +37811,15 @@ var GhostlyNode = class GhostlyNode {
37294
37811
  this.awaitingTimer = setTimeout(() => void this.readAwaiting().then((awaiting) => {
37295
37812
  const networks = this.walletView.networks;
37296
37813
  if (this.shuttingDown || !networks) return;
37297
- for (const network of WALLET_NETWORKS) networks[network] = {
37814
+ const next = { ...networks };
37815
+ for (const network of WALLET_NETWORKS) next[network] = {
37298
37816
  ...networks[network],
37299
37817
  mints: this.withWaits(networks[network].mints, awaiting.mints),
37300
37818
  awaiting: awaiting.networks[network]
37301
37819
  };
37302
37820
  this.walletView = {
37303
37821
  ...this.walletView,
37304
- networks: { ...networks }
37822
+ networks: next
37305
37823
  };
37306
37824
  this.emitState();
37307
37825
  }).catch(() => {}), 250);
@@ -37464,9 +37982,7 @@ var GhostlyNode = class GhostlyNode {
37464
37982
  await this.nostrSocial.load();
37465
37983
  await this.publicProfiles.load();
37466
37984
  if (!this.limitedMode) await this.startWallets();
37467
- const history = /* @__PURE__ */ new Map();
37468
37985
  const links = await db.getLinks();
37469
- for (const stored of links) history.set(stored.id, []);
37470
37986
  for (const stored of links) if (stored.group) this.links.set(stored.id, newLiveLink(stored, 0, linkFilesFrom(stored.id, [], [])));
37471
37987
  for (const group of await db.getGroups()) await this.settleHistory(`group:${group.id}`);
37472
37988
  await this.groups.load(this.limitedMode);
@@ -37488,7 +38004,7 @@ var GhostlyNode = class GhostlyNode {
37488
38004
  const files = linkFilesFrom(stored.id, storedFiles, messages);
37489
38005
  this.links.set(stored.id, newLiveLink(stored, messages[messages.length - 1]?.timestamp ?? 0, files));
37490
38006
  this.links.get(stored.id).waitingSends = Promise.resolve(new Set(messages.filter(waitsForLive).map((m) => m.id)));
37491
- history.set(stored.id, messages);
38007
+ this.links.get(stored.id).pkarrSeenAt = pkarrSeenAt(messages);
37492
38008
  for (const message of messages.slice(-20)) this.clockSample(message);
37493
38009
  const note = latestReaction(messages);
37494
38010
  if (note) this.reactionNotes.set(stored.id, note);
@@ -37500,15 +38016,9 @@ var GhostlyNode = class GhostlyNode {
37500
38016
  if (note) this.reactionNotes.set(`group:${group.id}`, note);
37501
38017
  }
37502
38018
  this.publicProfiles.start();
37503
- const pause = pacer(START_SLICE_MS);
37504
- if (this.networkOn) for (const linkId of this.nativeStartOrder([...history.keys()])) {
37505
- if (!this.networkOn || this.shuttingDown) break;
37506
- const messages = history.get(linkId);
37507
- if (!this.links.has(linkId)) continue;
37508
- this.startLink(linkId, messages);
38019
+ await this.startLinks(links.map((stored) => stored.id), (linkId) => {
37509
38020
  if (!this.links.get(linkId)?.stored.group) this.refreshPublicProfiles({ linkId }).catch(() => {});
37510
- await pause();
37511
- }
38021
+ });
37512
38022
  if (this.shuttingDown) return;
37513
38023
  this.emitState();
37514
38024
  if (this.networkOn) {
@@ -37519,7 +38029,8 @@ var GhostlyNode = class GhostlyNode {
37519
38029
  if (!this.limitedMode) this.openStartedWallets(fresh);
37520
38030
  if (this.appsOn && !this.appsWireOnly) this.appStore.start().catch(() => {});
37521
38031
  if (!this.options.singleDevice && this.networkOn && knownDeviceGate()?.state === "active") this.startDeviceSet().catch(() => {});
37522
- if (!this.options.singleDevice && this.limitedMode && knownDeviceGate()?.state === "active") this.readTurnWhileLimited();
38032
+ if (this.options.startCheck) this.afterStartCheck(this.options.startCheck);
38033
+ else if (!this.options.singleDevice && this.limitedMode && knownDeviceGate()?.state === "active") this.readTurnWhileLimited();
37523
38034
  if (this.restoreCheck === "checking" && this.limitedMode) this.checkRestoredTurn(0);
37524
38035
  }
37525
38036
  /** Where the check of a restored copy stands: reading every 30 seconds, or a tombstone found (the person decides). */
@@ -37642,6 +38153,31 @@ var GhostlyNode = class GhostlyNode {
37642
38153
  this.emitState();
37643
38154
  return false;
37644
38155
  }
38156
+ /**
38157
+ * The answer of the read at start (`NodeOptions.startCheck`), once the profile is loaded: another device took the turn,
38158
+ * and the engine stops having published nothing (the pages start again into the gate, where its device links run); no
38159
+ * good read, and it stays limited, reading every 30 seconds; else it starts properly, as it would have without the wait.
38160
+ */
38161
+ async afterStartCheck(check) {
38162
+ const start = await check.catch(() => ({ limited: true }));
38163
+ this.startChecking = false;
38164
+ if (this.shuttingDown) return;
38165
+ if (start.gated) {
38166
+ await this.stopReplaced({
38167
+ ...start.gated,
38168
+ reload: true
38169
+ });
38170
+ return;
38171
+ }
38172
+ if (start.limited) {
38173
+ this.emitState();
38174
+ this.readTurnWhileLimited();
38175
+ return;
38176
+ }
38177
+ await this.groups.files?.sweep((await db.getGroups()).map((group) => group.id)).catch(() => {});
38178
+ await this.leaveLimited(start.readAt ?? null).catch(() => {});
38179
+ if (!this.options.singleDevice && !this.limitedMode && this.networkOn && knownDeviceGate()?.state === "active") this.startDeviceSet().catch(() => {});
38180
+ }
37645
38181
  readTurnWhileLimited(after = 3e4) {
37646
38182
  if (this.limitedTimer) clearTimeout(this.limitedTimer);
37647
38183
  this.limitedTimer = setTimeout(() => {
@@ -37709,13 +38245,14 @@ var GhostlyNode = class GhostlyNode {
37709
38245
  * Leaves limited mode after the first good turn read that says this device is the active one (WISP 06 § When a
37710
38246
  * device checks: "the first good one either starts the engine properly or stops the device"). What `start()` left
37711
38247
  * out runs now: the wallets, then every chat, the hold storage and the group entries, as when the person goes online.
38248
+ * `readAt`: when that read was made; null when it said nothing of the turn (no device set), which notes no good read.
37712
38249
  */
37713
- async leaveLimited() {
38250
+ async leaveLimited(readAt = Date.now()) {
37714
38251
  if (!this.limitedMode) return;
37715
38252
  if (!this.starting || !await this.starting) throw new Error("The engine did not start");
37716
38253
  if (!this.limitedMode) return;
37717
38254
  this.limitedMode = false;
37718
- this.noteGoodTurn();
38255
+ if (readAt !== null) this.noteGoodTurn(readAt);
37719
38256
  let failure = null;
37720
38257
  try {
37721
38258
  if (!this.walletsStarted) {
@@ -37726,7 +38263,7 @@ var GhostlyNode = class GhostlyNode {
37726
38263
  failure = error ?? /* @__PURE__ */ new Error("The wallets did not start");
37727
38264
  }
37728
38265
  if (this.networkOn) {
37729
- for (const live of this.links.values()) this.startLink(live.stored.id, await db.getMessages(live.stored.id));
38266
+ await this.startLinks([...this.links.keys()]);
37730
38267
  this.hold.start();
37731
38268
  this.startGroupEntries();
37732
38269
  this.prepareSpare(STARTUP_QUIET_MS);
@@ -37781,8 +38318,8 @@ var GhostlyNode = class GhostlyNode {
37781
38318
  /** When the last good turn read said this device is the active one (ms); null before one. */
37782
38319
  turnGoodAt = null;
37783
38320
  /** A good read said this device is the active one: single-writer wallets that waited for one open now. */
37784
- noteGoodTurn() {
37785
- this.turnGoodAt = Date.now();
38321
+ noteGoodTurn(at = Date.now()) {
38322
+ this.turnGoodAt = at;
37786
38323
  if (this.singleWritersWaiting && this.walletsStarted && !this.limitedMode) this.openSingleWriters();
37787
38324
  }
37788
38325
  /**
@@ -38082,6 +38619,7 @@ var GhostlyNode = class GhostlyNode {
38082
38619
  settings: this.settings,
38083
38620
  ...this.limitedMode && { limited: true },
38084
38621
  ...this.limitedMode && this.restoreCheck && { restoreCheck: this.restoreCheck },
38622
+ ...this.limitedMode && this.startChecking && { startCheck: true },
38085
38623
  ...wakeOwnerOf(this.settings.wake, this.ownDeviceKey) && { wakeOwner: wakeOwnerOf(this.settings.wake, this.ownDeviceKey) },
38086
38624
  transport: {
38087
38625
  ...this.transport.describe(),
@@ -38202,6 +38740,14 @@ var GhostlyNode = class GhostlyNode {
38202
38740
  before: from
38203
38741
  });
38204
38742
  }
38743
+ /** Saves a message on this device, or unsaves it (`engine/saved.ts`): nothing is sent. */
38744
+ saveMessage(params) {
38745
+ return this.saved.save(params);
38746
+ }
38747
+ /** This profile's saved messages, the last saved first, each as it is now. */
38748
+ savedMessages() {
38749
+ return this.saved.list();
38750
+ }
38205
38751
  async statusCardIndex() {
38206
38752
  const rows = [];
38207
38753
  for (const m of await db.getCardMessages()) {
@@ -38267,11 +38813,12 @@ var GhostlyNode = class GhostlyNode {
38267
38813
  /**
38268
38814
  * One invite warmed and waiting (`after` ms from now), warmed again every so often while it waits (the relays forget).
38269
38815
  * Once too old for `takeInvite` to hand out, it is replaced by a new one, warmed at once: warming it on would spend
38270
- * two puts every few minutes on keys nobody will use, and leave the next invite on cold keys.
38816
+ * two puts every few minutes on keys nobody will use, and leave the next invite on cold keys. The timer set for its age
38817
+ * says so (`aged`): Node times it from the loop's cached clock, so it often fires a few ms before the age by `Date.now()`.
38271
38818
  */
38272
- prepareSpare(after = 0) {
38819
+ prepareSpare(after = 0, aged = false) {
38273
38820
  if (this.shuttingDown || !this.networkOn) return;
38274
- if (this.spare && after === 0 && Date.now() - this.spare.madeAt >= SPARE_INVITE_MAX_AGE_MS) {
38821
+ if (this.spare && after === 0 && (aged || Date.now() - this.spare.madeAt >= SPARE_INVITE_MAX_AGE_MS)) {
38275
38822
  for (const identity of [identityFromSeedB64(this.spare.mine.seedB64), this.spare.inviteKey]) this.warmedKeys.delete(identity.pubKeyZ32);
38276
38823
  this.spare = null;
38277
38824
  }
@@ -38290,11 +38837,12 @@ var GhostlyNode = class GhostlyNode {
38290
38837
  this.warmedKeys.set(identity.pubKeyZ32, Date.now());
38291
38838
  this.warmKey(identity);
38292
38839
  }
38293
- const untilAged = spare.madeAt + SPARE_INVITE_MAX_AGE_MS - Date.now();
38840
+ const untilAged = Math.max(0, spare.madeAt + SPARE_INVITE_MAX_AGE_MS - Date.now());
38841
+ const aging = untilAged <= SPARE_INVITE_WARM_EVERY_MS;
38294
38842
  this.spareTimer = setTimeout(() => {
38295
38843
  this.spareTimer = null;
38296
- if (this.spare === spare) this.prepareSpare();
38297
- }, Math.min(SPARE_INVITE_WARM_EVERY_MS, untilAged));
38844
+ if (this.spare === spare) this.prepareSpare(0, aging);
38845
+ }, aging ? untilAged : SPARE_INVITE_WARM_EVERY_MS);
38298
38846
  }
38299
38847
  async joinLink({ inviteCode }) {
38300
38848
  const decoded = decodeInviteCode(inviteCode);
@@ -38973,13 +39521,20 @@ var GhostlyNode = class GhostlyNode {
38973
39521
  db.patchLink(linkId, { label: live.stored.label });
38974
39522
  this.emitState();
38975
39523
  }
39524
+ /** `linkId`: a chat's, or `group:<id>` for a group on screen, whose edges then take native listeners as a chat on screen does. */
38976
39525
  setActiveLink({ linkId }) {
39526
+ const now = Date.now();
39527
+ if (this.activeLinkId) this.openedAt.set(this.activeLinkId, now);
39528
+ if (linkId) this.openedAt.set(linkId, now);
38977
39529
  this.activeLinkId = linkId;
38978
- if (linkId) this.ensureNativeEndpoints(linkId);
38979
- if (linkId && this.settings.nostr?.autoLoadProfiles) this.nostrSocial.ledgerChanged(linkId).catch(() => {});
38980
- if (linkId) this.hold.wake(linkId);
39530
+ const groupId = linkId?.startsWith("group:") ? linkId.slice(6) : void 0;
39531
+ const chat = groupId === void 0 ? linkId : null;
39532
+ if (groupId !== void 0) this.groupOnScreen(groupId);
39533
+ if (chat) this.ensureNativeEndpoints(chat);
39534
+ if (chat && this.settings.nostr?.autoLoadProfiles) this.nostrSocial.ledgerChanged(chat).catch(() => {});
39535
+ if (chat) this.hold.wake(chat);
38981
39536
  for (const [id, live] of this.links) live.link?.setChatActive(id === linkId);
38982
- if (linkId) this.links.get(linkId)?.link?.wake();
39537
+ if (chat) this.links.get(chat)?.link?.wake();
38983
39538
  this.emitState();
38984
39539
  }
38985
39540
  /**
@@ -39293,10 +39848,19 @@ var GhostlyNode = class GhostlyNode {
39293
39848
  static dhtByChoice(live) {
39294
39849
  return live?.stored.deliveryMode === "dht" || live?.link?.dhtDelivery?.peerMode === "dht";
39295
39850
  }
39296
- /** A status card a caller asks to send, by the sender's rule (WISP 405 · Status Cards), or why it cannot go. */
39297
- static cardToSend(raw) {
39851
+ /**
39852
+ * A status card a caller asks to send, by the sender's rule (WISP 405 · Status Cards), or why it cannot go. A removal
39853
+ * is only ever an edit of the card's own message (WISP 405 § Removing a card), never a message of its own.
39854
+ */
39855
+ static cardToSend(raw, edit = false) {
39298
39856
  const checked = checkStatusCard(raw);
39299
- return "error" in checked ? `Status card: ${checked.error}` : checked.card;
39857
+ if ("error" in checked) return `Status card: ${checked.error}`;
39858
+ if (checked.card.kind === "removed" && !edit) return "Status card: a removal is an edit of the card's message";
39859
+ return checked.card;
39860
+ }
39861
+ /** Whether a removal (WISP 405 § Removing a card) takes back the card this message of mine carries: its kind and id. */
39862
+ static removes(card, message) {
39863
+ return card.kind !== "removed" || message?.sender === "me" && message.card?.kind === card.of && message.card.id === card.id;
39300
39864
  }
39301
39865
  /**
39302
39866
  * A chat stopped by a security rejection (a stream authenticated a participation key other than the pinned one):
@@ -39317,13 +39881,15 @@ var GhostlyNode = class GhostlyNode {
39317
39881
  error,
39318
39882
  refused: true
39319
39883
  });
39320
- const card = params.card === void 0 ? void 0 : GhostlyNode.cardToSend(params.card);
39884
+ const card = params.card === void 0 ? void 0 : GhostlyNode.cardToSend(params.card, true);
39321
39885
  if (typeof card === "string") return refuse(card);
39322
39886
  if (card && !(typeof params.text === "string" && params.text.trim())) params = {
39323
39887
  ...params,
39324
39888
  text: statusCardText(card)
39325
39889
  };
39890
+ const notRemoved = "Status card: a removal takes back a task or routine of yours with that id, on its own message";
39326
39891
  if (typeof linkId === "string" && linkId.startsWith("group:")) {
39892
+ if (card && typeof params.messageId === "string" && !GhostlyNode.removes(card, await db.getMessage(linkId, params.messageId))) return refuse(notRemoved);
39327
39893
  const mentions = Array.isArray(params.mentions) ? params.mentions : [];
39328
39894
  return card ? this.groupEdits.edit(linkId.slice(6), params.messageId, params.text, mentions, card) : this.groupEdits.edit(linkId.slice(6), params.messageId, params.text, mentions);
39329
39895
  }
@@ -39334,6 +39900,7 @@ var GhostlyNode = class GhostlyNode {
39334
39900
  if (typeof params.messageId !== "string" || typeof params.text !== "string") return refuse("No message to edit");
39335
39901
  const message = await db.getMessage(linkId, params.messageId) ?? (await db.getMessages(linkId)).find((m) => m.sender === "me" && m.wireId === params.messageId);
39336
39902
  if (!message || !canEdit(message)) return refuse("Only your own text messages can be edited");
39903
+ if (card && !GhostlyNode.removes(card, message)) return refuse(notRemoved);
39337
39904
  const text = params.text.trim();
39338
39905
  if (!text) return refuse("An edit cannot be empty. Delete the message instead.");
39339
39906
  if (isJoinNotice(text)) return refuse("An edit cannot read as a join notice.");
@@ -39380,6 +39947,11 @@ var GhostlyNode = class GhostlyNode {
39380
39947
  if (!live?.stored.profile || live.stored.group) return false;
39381
39948
  const id = `peer_${edit.id}`;
39382
39949
  if (live.stored.deletedIds?.includes(id)) return true;
39950
+ if (edit.rm) {
39951
+ const message = await db.getMessage(linkId, id);
39952
+ if (!message || canRemove(message)) await this.forgetMessage(linkId, id, true);
39953
+ return true;
39954
+ }
39383
39955
  const message = await db.getMessage(linkId, id);
39384
39956
  if (!message) {
39385
39957
  this.editBuffer.hold(linkId, edit);
@@ -39532,9 +40104,15 @@ var GhostlyNode = class GhostlyNode {
39532
40104
  editsFor(linkId) {
39533
40105
  let queue = this.editQueues.get(linkId);
39534
40106
  if (!queue) {
40107
+ const removals = () => this.links.get(linkId)?.stored.removals ?? [];
39535
40108
  queue = new EditQueue({
39536
- read: () => db.getMessages(linkId),
39537
- rows: (ids) => db.getMessagesById(linkId, ids),
40109
+ read: async () => [...await db.getMessages(linkId), ...removals().map((r) => removalRow(linkId, r))],
40110
+ rows: async (ids) => {
40111
+ return (await db.getMessagesById(linkId, ids)).map((row, i) => {
40112
+ const removal = row ? void 0 : removals().find((r) => r.id === ids[i]);
40113
+ return row ?? (removal && removalRow(linkId, removal));
40114
+ });
40115
+ },
39538
40116
  ready: () => {
39539
40117
  const live = this.links.get(linkId), link = live?.link;
39540
40118
  return !!link && (link.supportsEdits || link.textDelivery === "dht" && this.takesDhtEdits(live));
@@ -39547,6 +40125,16 @@ var GhostlyNode = class GhostlyNode {
39547
40125
  },
39548
40126
  receiptMs: () => this.links.get(linkId)?.link?.isDataLinkOpen ? 2e4 : DHT_MESSAGE_TTL,
39549
40127
  settle: async (messageId, seq) => {
40128
+ const live = this.links.get(linkId), removal = live?.stored.removals?.find((r) => r.id === messageId);
40129
+ if (live && removal) {
40130
+ if (removal.e !== seq) return;
40131
+ live.stored = {
40132
+ ...live.stored,
40133
+ removals: live.stored.removals.filter((r) => r.id !== messageId)
40134
+ };
40135
+ await db.patchLink(linkId, { removals: live.stored.removals });
40136
+ return;
40137
+ }
39550
40138
  if (await db.patchMessage(linkId, messageId, (current) => {
39551
40139
  if (!current.edit?.pending || current.edit.seq !== seq) return null;
39552
40140
  const { pending: _done, ...edit } = current.edit;
@@ -39922,6 +40510,54 @@ var GhostlyNode = class GhostlyNode {
39922
40510
  }
39923
40511
  }
39924
40512
  deleteMessage({ linkId, messageId }) {
40513
+ this.forgetMessage(linkId, messageId);
40514
+ }
40515
+ /**
40516
+ * Deletes a message of mine for everyone (WISP 400 § Delete for everyone): it goes from this device at once, as a delete
40517
+ * here does, and its removal goes to the contact as the message's last edit, said again until confirmed, live only.
40518
+ * One that never left is only deleted. Never a payment, a request or a notice. A group's goes through `GroupEdits`.
40519
+ */
40520
+ async removeMessage({ linkId, messageId }) {
40521
+ const refuse = (error) => ({
40522
+ error,
40523
+ refused: true
40524
+ });
40525
+ if (linkId.startsWith("group:")) return this.groupEdits.removeMine(linkId.slice(6), messageId);
40526
+ const live = this.links.get(linkId);
40527
+ if (!live?.stored.profile || live.stored.group) return refuse("Only a chat with a contact deletes a message for everyone");
40528
+ const message = await db.getMessage(linkId, messageId);
40529
+ if (!message || message.sender !== "me") return refuse("Only your own messages can be deleted for everyone");
40530
+ if (!canRemove(message)) return refuse("A payment, a request or a notice cannot be deleted for everyone");
40531
+ const out = `${linkId}-out-`;
40532
+ const wireId = message.wireId ?? (message.file?.id.startsWith(out) ? message.file.id.slice(out.length) : void 0);
40533
+ if (!wireId || message.delivery === "waiting") {
40534
+ await this.forgetMessage(linkId, messageId, true);
40535
+ return { error: null };
40536
+ }
40537
+ const removal = {
40538
+ id: messageId,
40539
+ wireId,
40540
+ e: removalNumber(message.edit?.seq),
40541
+ at: Date.now(),
40542
+ pending: true
40543
+ };
40544
+ live.stored = {
40545
+ ...live.stored,
40546
+ removals: withRemoval(live.stored.removals, removal)
40547
+ };
40548
+ await db.patchLink(linkId, { removals: live.stored.removals });
40549
+ await this.forgetMessage(linkId, messageId, true);
40550
+ const edits = this.editsFor(linkId);
40551
+ edits.edited(messageId);
40552
+ edits.flush().catch(() => {});
40553
+ return { error: null };
40554
+ }
40555
+ /**
40556
+ * 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
40557
+ * copy that comes again is not stored: a delete here, or the contact's own removal (WISP 400 § Delete for everyone),
40558
+ * also of a message not here yet. `removed`: deleted for everyone, so the replies here that quote it lose its line too.
40559
+ */
40560
+ async forgetMessage(linkId, messageId, removed = false) {
39925
40561
  const live = this.links.get(linkId);
39926
40562
  if (!live) return;
39927
40563
  live.stored = {
@@ -39930,31 +40566,49 @@ var GhostlyNode = class GhostlyNode {
39930
40566
  };
39931
40567
  db.patchLink(linkId, { deletedIds: live.stored.deletedIds });
39932
40568
  this.hold.forget(linkId, messageId).catch(() => {});
39933
- (async () => {
39934
- const message = await db.getMessage(linkId, messageId);
39935
- if (message?.paymentId && message.delivery === "waiting") await this.desk.withdraw(message.paymentId).catch(() => {});
39936
- if (message?.paymentId && message.sender === "peer") await this.desk.dropReceipt(message.paymentId).catch(() => {});
39937
- if (message?.sender === "me" && message.file && message.delivery === "waiting" && (message.fileOnFloor === "sent" || message.fileOnFloor === "seen")) {
39938
- const wireId = message.file.id.slice(`${linkId}-out-`.length);
39939
- live.link?.settleDht(dhtFileId(wireId)).catch(() => {});
39940
- live.stored = {
39941
- ...live.stored,
39942
- withdrawnFiles: [...(live.stored.withdrawnFiles ?? []).filter((id) => id !== wireId), wireId].slice(-64)
39943
- };
39944
- await db.patchLink(linkId, { withdrawnFiles: live.stored.withdrawnFiles });
39945
- }
39946
- if (message?.file) {
39947
- const stored = await fileStore.get(message.file.id);
39948
- if (stored && !stored.wire3 && !stored.announced && (stored.direction === "in" || !stored.direction && message.sender === "peer")) live.files.receivedBytes = Math.max(0, live.files.receivedBytes - storedSize(stored));
39949
- this.fileDesk.forget(linkId, message.file.id);
39950
- await removeStored(message.file.id);
39951
- this.transfers.delete(message.file.id);
39952
- }
39953
- await db.deleteMessage(linkId, messageId);
39954
- live.lastMessageAt = (await db.getMessagePage(linkId, { limit: 1 })).messages[0]?.timestamp ?? 0;
39955
- await this.messagesChanged(linkId, [messageId]);
39956
- this.emitState();
39957
- })();
40569
+ const message = await db.getMessage(linkId, messageId);
40570
+ if (message?.paymentId && message.delivery === "waiting") await this.desk.withdraw(message.paymentId).catch(() => {});
40571
+ if (message?.paymentId && message.sender === "peer") await this.desk.dropReceipt(message.paymentId).catch(() => {});
40572
+ if (message?.sender === "me" && message.file && message.delivery === "waiting" && (message.fileOnFloor === "sent" || message.fileOnFloor === "seen")) {
40573
+ const wireId = message.file.id.slice(`${linkId}-out-`.length);
40574
+ live.link?.settleDht(dhtFileId(wireId)).catch(() => {});
40575
+ live.stored = {
40576
+ ...live.stored,
40577
+ withdrawnFiles: [...(live.stored.withdrawnFiles ?? []).filter((id) => id !== wireId), wireId].slice(-64)
40578
+ };
40579
+ await db.patchLink(linkId, { withdrawnFiles: live.stored.withdrawnFiles });
40580
+ }
40581
+ if (message?.file) {
40582
+ const stored = await fileStore.get(message.file.id);
40583
+ if (stored && !stored.wire3 && !stored.announced && (stored.direction === "in" || !stored.direction && message.sender === "peer")) live.files.receivedBytes = Math.max(0, live.files.receivedBytes - storedSize(stored));
40584
+ this.fileDesk.forget(linkId, message.file.id);
40585
+ await removeStored(message.file.id);
40586
+ this.transfers.delete(message.file.id);
40587
+ }
40588
+ await db.deleteMessage(linkId, messageId);
40589
+ live.lastMessageAt = (await db.getMessagePage(linkId, { limit: 1 })).messages[0]?.timestamp ?? 0;
40590
+ const quoting = removed ? await this.forgetQuotes(linkId, messageId, replyRef(message ?? {
40591
+ id: messageId,
40592
+ linkId
40593
+ })) : [];
40594
+ await this.messagesChanged(linkId, [messageId, ...quoting]);
40595
+ this.emitState();
40596
+ }
40597
+ /**
40598
+ * A message deleted for everyone leaves no line of it here (WISP 400 § Delete for everyone): the replies of the chat
40599
+ * that quote it keep the quote's id and who wrote it, which say it was deleted, and lose its snippet. The chat is
40600
+ * read whole: a removal is rare. The ids of the replies changed.
40601
+ */
40602
+ async forgetQuotes(linkId, messageId, ref) {
40603
+ const quotes = (reply) => !!reply && (reply.messageId === messageId || ref !== void 0 && reply.id === ref);
40604
+ const ids = (await db.getMessages(linkId)).filter((m) => quotes(m.replyTo) && (m.replyTo.snippet || m.replyTo.messageId !== messageId)).map((m) => m.id);
40605
+ if (!ids.length) return [];
40606
+ await db.patchMessages(linkId, ids, (m) => quotes(m.replyTo) ? { replyTo: {
40607
+ ...m.replyTo,
40608
+ snippet: "",
40609
+ messageId
40610
+ } } : null);
40611
+ return ids;
39958
40612
  }
39959
40613
  /** Local id of a file we send: the id on the wire is ours too, but lives in its own key space. */
39960
40614
  static outgoingFileId(linkId, wireId) {
@@ -41345,6 +41999,56 @@ var GhostlyNode = class GhostlyNode {
41345
41999
  await this.appChatRunnable(ref, digest);
41346
42000
  return { error: live.link ? live.link.sendAppData(app, data) : "offline" };
41347
42001
  }
42002
+ /** Ranges the contact's apps asked, by chat, app and request, until a page answers them. */
42003
+ appRanges = /* @__PURE__ */ new Map();
42004
+ /**
42005
+ * Every task stays until a page answers it, live or not: until the link settles it, it holds one of its app's places
42006
+ * (WISP 1200: at most 4 in flight), so the contact gets `busy` rather than more reads while a page is still reading.
42007
+ */
42008
+ appRangeAsked(linkId, task) {
42009
+ this.appRanges.set(`${linkId} ${task.app} ${task.request}`, task);
42010
+ const { app, request, serve, file, offset, length } = task;
42011
+ this.events.onAppRange?.(linkId, {
42012
+ app,
42013
+ request,
42014
+ serve,
42015
+ file,
42016
+ offset,
42017
+ length
42018
+ });
42019
+ }
42020
+ /** Lets the contact's app read `file`, one of this side's linked files, while both have the app open on this session. */
42021
+ appServe({ linkId, ref, file }) {
42022
+ const { live, app } = this.appChat(linkId, ref);
42023
+ if (typeof file !== "string" || !file) throw new Error("Not a file");
42024
+ return live.link ? live.link.serveAppFile(app, file) : { error: "offline" };
42025
+ }
42026
+ appUnserve({ linkId, serve }) {
42027
+ if (!this.appsOn) throw this.appsOff();
42028
+ this.links.get(linkId)?.link?.unserveAppFile(serve);
42029
+ }
42030
+ /** 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. */
42031
+ appRangeAnswer({ linkId, app, request, bytes, size, error }) {
42032
+ if (!this.appsOn) throw this.appsOff();
42033
+ const key = `${linkId} ${app} ${request}`, task = this.appRanges.get(key), link = this.links.get(linkId)?.link;
42034
+ this.appRanges.delete(key);
42035
+ if (!task || !link) return;
42036
+ if (error === "changed" || error === "gone") return link.failAppRange(task, error);
42037
+ if (!(bytes instanceof Uint8Array) || typeof size !== "number" || !Number.isSafeInteger(size) || size < 0) return link.failAppRange(task, "gone");
42038
+ link.sendAppRange(task, bytes, size);
42039
+ }
42040
+ /** Reads a range of what the contact's app serves in this chat, or why not. */
42041
+ async appRemoteRead({ linkId, ref, serve, offset, length }) {
42042
+ const { live, app } = this.appChat(linkId, ref);
42043
+ if (!live.link) return { error: "offline" };
42044
+ if (!isServeId(serve)) return { error: "not-served" };
42045
+ if (!Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(length) || length < 1 || length > APP_RANGE_LIMITS.requestBytes || !Number.isSafeInteger(offset + length)) throw new Error("Not a range");
42046
+ try {
42047
+ return await live.link.readAppRange(app, serve, offset, length);
42048
+ } catch (error) {
42049
+ return { error: error instanceof Error ? error.message : "failed" };
42050
+ }
42051
+ }
41348
42052
  /** Every page went away: no app runs here any more, so each open one is closed (`close` goes where it can). */
41349
42053
  appsCloseAll() {
41350
42054
  for (const live of this.links.values()) for (const app of [...live.appsOpen?.keys() ?? []]) if (live.link) live.link.closeApp(app);
@@ -41927,14 +42631,14 @@ var GhostlyNode = class GhostlyNode {
41927
42631
  /**
41928
42632
  * `confirmedReal`: the person confirmed a Mainnet payment as real money; without it one is refused. `linkId` +
41929
42633
  * `invoice`: the chat whose message held the invoice. Paid on Testnet, its contact is told (`sayInvoicePaid`): a test
41930
- * mint's invoice counts only on the payer's word.
42634
+ * mint's invoice counts only on the payer's word. Still pending, it is told once the payment settles.
41931
42635
  */
41932
42636
  async walletPayQuote({ quote, mint, note, confirmedReal, linkId, invoice }) {
41933
42637
  const network = WALLET_NETWORKS.find((n) => this.lightnings[n].withQuote(quote));
41934
42638
  const lightning = network && this.lightnings[network].withQuote(quote);
41935
42639
  assertConfirmedReal(network ?? mintNetwork(mint), confirmedReal);
41936
42640
  const paid = lightning ? await lightning.pay(quote, { note }) : await this.wallet.payQuote(quote, mint, note);
41937
- if (paid && linkId && invoice && (network ?? mintNetwork(mint)) === "testnet") this.desk.sayInvoicePaid(linkId, invoice);
42641
+ if (linkId && invoice && (network ?? mintNetwork(mint)) === "testnet") this.desk.sayInvoicePaid(linkId, invoice, { pending: !paid });
41938
42642
  return { paid };
41939
42643
  }
41940
42644
  /** A Lightning address or LNURL (LUD-16, LUD-06): resolved here, in the engine, so every platform fetches the same way. */
@@ -42504,6 +43208,9 @@ var GhostlyNode = class GhostlyNode {
42504
43208
  const problem = iceServerProblem(server);
42505
43209
  if (problem) throw new Error(problem);
42506
43210
  }
43211
+ if (settings.relayOnly !== void 0 && typeof settings.relayOnly !== "boolean") throw new Error("relayOnly is on or off");
43212
+ const relayOnlyBefore = this.settings.relayOnly === true;
43213
+ if ((settings.relayOnly ?? relayOnlyBefore) && relayOnlyProblem(settings.iceServers ?? this.settings.iceServers)) throw new Error(settings.relayOnly ? "Add a TURN server first" : "Hide my IP from contacts needs a TURN server. Turn it off first");
42507
43214
  if (settings.avatar !== void 0 && settings.avatar !== "" && typeof sanitizeAvatar(settings.avatar) !== "string") throw new Error("Use a small JPEG picture");
42508
43215
  if (settings.relays && (this.relays || this.transport.configure) && !settings.relays.some((relay) => normalizeRelayUrl(relay))) throw new Error("Enter at least one relay address (https://…)");
42509
43216
  if (settings.readRelays !== void 0 && typeof settings.readRelays !== "boolean") throw new Error("readRelays is on or off");
@@ -42547,6 +43254,8 @@ var GhostlyNode = class GhostlyNode {
42547
43254
  ...settings
42548
43255
  };
42549
43256
  if (!this.settings.irohRelays?.length) delete this.settings.irohRelays;
43257
+ if (this.settings.relayOnly !== true) delete this.settings.relayOnly;
43258
+ const relayOnlyChanged = this.settings.relayOnly === true !== relayOnlyBefore;
42550
43259
  if (irohRelaysChanged && !this.options.irohRelays?.length) this.rehomeIroh();
42551
43260
  if (settings.relays) {
42552
43261
  this.relays?.setRelays(settings.relays);
@@ -42622,12 +43331,12 @@ var GhostlyNode = class GhostlyNode {
42622
43331
  live.dataLink = "idle";
42623
43332
  }));
42624
43333
  else if (!wasOnline && this.networkOn && await this.turnBeforeOnline()) {
42625
- for (const live of this.links.values()) this.startLink(live.stored.id, await db.getMessages(live.stored.id));
43334
+ await this.startLinks([...this.links.keys()]);
42626
43335
  this.hold.start();
42627
43336
  this.startGroupEntries();
42628
43337
  this.prepareSpare(STARTUP_QUIET_MS);
42629
43338
  this.did.publishNow().catch(() => {});
42630
- }
43339
+ } else if (wasOnline && this.networkOn && relayOnlyChanged) await this.restartLinksForRelayOnly();
42631
43340
  if (wasOnline && !this.networkOn) this.stopGroupEntries();
42632
43341
  if (wasOnline && !this.networkOn) await this.hold.stop();
42633
43342
  const gate = knownDeviceGate();
@@ -42646,6 +43355,7 @@ var GhostlyNode = class GhostlyNode {
42646
43355
  counterFloor = 0;
42647
43356
  /** Groups whose admin work is off on this device since a forced takeover or a restore. */
42648
43357
  groupAdminOff = /* @__PURE__ */ new Set();
43358
+ saved = new SavedMessages(() => this.emitState());
42649
43359
  /**
42650
43360
  * Raises the counters a copy from older state must raise, once (`devices/raise.ts`): the raise a forced takeover wrote
42651
43361
  * into the device record with `active`, or the one a restore wrote into the profile's settings. Then reads the floor
@@ -42729,6 +43439,17 @@ var GhostlyNode = class GhostlyNode {
42729
43439
  ...transport.turnWarm ? { turnWarm: transport.turnWarm.bind(transport) } : {}
42730
43440
  };
42731
43441
  }
43442
+ /**
43443
+ * The WebRTC configuration of a connection to a contact (a chat's data link, a group's edge): the profile's ICE
43444
+ * servers, and only its TURN server while "Hide my IP from contacts" is on. The ICE servers a browser refuses are
43445
+ * left out, as they always were.
43446
+ */
43447
+ contactRtcConfig() {
43448
+ return contactRtcConfig({
43449
+ iceServers: this.settings.iceServers.filter((server) => !iceServerProblem(server)),
43450
+ relayOnly: this.settings.relayOnly
43451
+ });
43452
+ }
42732
43453
  /** WebRTC with the person's ICE servers, where this engine has WebRTC. */
42733
43454
  devicePeerConnection() {
42734
43455
  if (typeof RTCPeerConnection === "undefined") return void 0;
@@ -43406,7 +44127,7 @@ var GhostlyNode = class GhostlyNode {
43406
44127
  this.links.delete(stored.id);
43407
44128
  throw error;
43408
44129
  }
43409
- if (this.networkOn) this.startLink(stored.id, []);
44130
+ if (this.networkOn) this.startLink(stored.id);
43410
44131
  if (params.profile) this.links.get(stored.id)?.link?.expectPeer();
43411
44132
  if (params.profile && inviteCode && this.networkOn) this.warmInviteKey(inviteCode);
43412
44133
  this.emitState();
@@ -43470,6 +44191,7 @@ var GhostlyNode = class GhostlyNode {
43470
44191
  this.quietEdges.delete(linkId);
43471
44192
  this.groupNativeWaiting.delete(linkId);
43472
44193
  this.nativeFailed.delete(linkId);
44194
+ this.anchorPassedOver.delete(linkId);
43473
44195
  this.groupNativeRetryAt = 0;
43474
44196
  if (live.stored.wakeToken && this.meshEdge(live.stored)) {
43475
44197
  const group = live.stored.group, peer = live.stored.groupPeer;
@@ -43542,7 +44264,7 @@ var GhostlyNode = class GhostlyNode {
43542
44264
  this.links.delete(id);
43543
44265
  throw error;
43544
44266
  }
43545
- if (this.networkOn) this.startLink(id, []);
44267
+ if (this.networkOn) this.startLink(id);
43546
44268
  if (expectPeer) this.links.get(id)?.link?.expectPeer();
43547
44269
  return id;
43548
44270
  }
@@ -43577,7 +44299,7 @@ var GhostlyNode = class GhostlyNode {
43577
44299
  this.links.delete(id);
43578
44300
  throw error;
43579
44301
  }
43580
- if (this.networkOn) this.startLink(id, []);
44302
+ if (this.networkOn) this.startLink(id);
43581
44303
  this.links.get(id)?.link?.expectPeer();
43582
44304
  return id;
43583
44305
  }
@@ -43663,7 +44385,7 @@ var GhostlyNode = class GhostlyNode {
43663
44385
  oneShot: true,
43664
44386
  firstPublish: stored.groupEntry === "host" ? "after-first-poll" : "at-start"
43665
44387
  } : {},
43666
- createPeerConnection: () => new RTCPeerConnection({ iceServers: [...RTC_CONFIG.iceServers ?? [], ...this.settings.iceServers.filter((server) => !iceServerProblem(server))] }),
44388
+ createPeerConnection: () => new RTCPeerConnection(this.contactRtcConfig()),
43667
44389
  localFetch: this.localFetch,
43668
44390
  getServices: () => [{
43669
44391
  id: "chat",
@@ -43700,7 +44422,9 @@ var GhostlyNode = class GhostlyNode {
43700
44422
  ...live.stored,
43701
44423
  ...patch
43702
44424
  };
44425
+ live.peerSaidAt = Date.now();
43703
44426
  db.patchLink(linkId, patch).catch(() => {});
44427
+ if (this.chosenByPeer(live)) this.anchorPassedOver.delete(linkId);
43704
44428
  if (this.keepsGroupNative(live.stored)) this.ensureNativeEndpoints(linkId);
43705
44429
  else this.groupNativeWaiting.delete(linkId);
43706
44430
  },
@@ -43714,6 +44438,7 @@ var GhostlyNode = class GhostlyNode {
43714
44438
  ...live.stored,
43715
44439
  ...patch
43716
44440
  };
44441
+ live.peerSaidAt = void 0;
43717
44442
  db.patchLink(linkId, patch).catch(() => {});
43718
44443
  if (!this.keepsGroupNative(live.stored)) this.groupNativeWaiting.delete(linkId);
43719
44444
  this.emitState();
@@ -43760,6 +44485,7 @@ var GhostlyNode = class GhostlyNode {
43760
44485
  traceJoin(group, `link.${state}`, { role });
43761
44486
  if (state === "open" || live.dataLink === "open") live.lastSyncAt = Date.now();
43762
44487
  if (state === "open" && !entry) this.groups.edgeOpen(group, peer);
44488
+ if (state === "open") this.anchorPassedOver.delete(linkId);
43763
44489
  if (state === "open") {
43764
44490
  const off = this.edgeRtcOff.get(linkId);
43765
44491
  if (off) off.held = true;
@@ -43858,13 +44584,48 @@ var GhostlyNode = class GhostlyNode {
43858
44584
  this.startEdge(linkId);
43859
44585
  if (live.stored.groupEntry) this.links.get(linkId)?.link?.expectPeer();
43860
44586
  }
43861
- startLink(linkId, messages) {
44587
+ /**
44588
+ * "Hide my IP from contacts" was turned on or off: every chat and group edge starts over, so no connection made
44589
+ * before keeps a direct path (a WebRTC one gathered with STUN, an Iroh or HyperDHT endpoint of this app's own) and
44590
+ * the next ones follow the setting. No goodbye: the contacts see the chat back in a moment.
44591
+ */
44592
+ async restartLinksForRelayOnly() {
44593
+ await Promise.allSettled([...this.links.values()].map(async (live) => {
44594
+ const link = live.link;
44595
+ live.carried?.stop();
44596
+ live.link = null;
44597
+ await link?.stop(false);
44598
+ await live.caps?.stop();
44599
+ live.caps = void 0;
44600
+ live.status = "offline";
44601
+ live.dataLink = "idle";
44602
+ }));
44603
+ await this.startLinks([...this.links.keys()]);
44604
+ }
44605
+ /**
44606
+ * Starts these chats' and groups' links, the chats most recently live first (`nativeStartOrder`), in slices that let
44607
+ * the page go: each link derives its keys and seals its capability record as it starts, and 50 chats and 20 groups in
44608
+ * one task held the page for 575-762 ms at 4x CPU, right as the chat list appeared. A chat not started yet reads as
44609
+ * offline until its turn. `started`: after each link started. Gone offline or shut down meanwhile: the links left
44610
+ * start with the network, if ever.
44611
+ */
44612
+ async startLinks(linkIds, started) {
44613
+ const pause = pacer(START_SLICE_MS);
44614
+ for (const linkId of this.nativeStartOrder(linkIds)) {
44615
+ if (!this.networkOn || this.shuttingDown) break;
44616
+ if (!this.links.has(linkId)) continue;
44617
+ this.startLink(linkId);
44618
+ started?.(linkId);
44619
+ await pause();
44620
+ }
44621
+ }
44622
+ startLink(linkId) {
43862
44623
  const live = this.links.get(linkId);
43863
44624
  if (!live || live.link) return;
43864
44625
  const { stored } = live;
43865
44626
  if (stored.group) return this.startEdge(linkId);
43866
44627
  if (stored.profile) live.pairing = { status: "connecting" };
43867
- const lastSeenTimestamp = messages.reduce((max, m) => m.sender === "peer" && m.via === "pkarr" ? Math.max(max, m.sentAt ?? m.timestamp) : max, 0);
44628
+ const lastSeenTimestamp = live.pkarrSeenAt ?? 0;
43868
44629
  const credentials = stored.profile && stored.participationSeed ? {
43869
44630
  seedB64: stored.participationSeed,
43870
44631
  peerKey: stored.pairedPeerKey,
@@ -43898,6 +44659,7 @@ var GhostlyNode = class GhostlyNode {
43898
44659
  upgradeSupport: true,
43899
44660
  peerUpgrades: () => !!live.caps?.peer?.capabilities.includes(UPGRADE_CAPABILITY),
43900
44661
  appsSupport: this.appsOn,
44662
+ appRangesSupport: this.appsOn && !this.appsWireOnly,
43901
44663
  appsOpen: this.appsOn ? live.appsOpen ??= /* @__PURE__ */ new Map() : void 0,
43902
44664
  servicesSupport: this.options.servicesSupport ?? (this.options.platform ?? "web") !== "web",
43903
44665
  dht: stored.profile ? {
@@ -43981,7 +44743,7 @@ var GhostlyNode = class GhostlyNode {
43981
44743
  lastSeenTimestamp,
43982
44744
  pollIntervals: this.pollIntervals,
43983
44745
  autoConnect: true,
43984
- createPeerConnection: () => this.chatPeer(new RTCPeerConnection({ iceServers: [...RTC_CONFIG.iceServers ?? [], ...this.settings.iceServers.filter((server) => !iceServerProblem(server))] })),
44746
+ createPeerConnection: () => this.chatPeer(new RTCPeerConnection(this.contactRtcConfig())),
43985
44747
  localFetch: this.localFetch,
43986
44748
  getServices: () => stored.profile ? [{
43987
44749
  id: "chat",
@@ -44222,6 +44984,7 @@ var GhostlyNode = class GhostlyNode {
44222
44984
  if (supported) this.flushPin(linkId);
44223
44985
  },
44224
44986
  onAppFrame: this.appsOn ? (event) => this.events.onAppFrame?.(linkId, event) : void 0,
44987
+ onAppRangeTask: this.appsOn ? (task) => this.appRangeAsked(linkId, task) : void 0,
44225
44988
  onPaymentRequest: (request) => this.desk.onPaymentRequest(linkId, request),
44226
44989
  onPaymentAsk: (ask) => this.desk.onPaymentAsk(linkId, ask),
44227
44990
  onPayment: (payment) => this.desk.onPayment(linkId, payment),
@@ -44376,7 +45139,7 @@ var GhostlyNode = class GhostlyNode {
44376
45139
  get nativeFactories() {
44377
45140
  const relay = this.relaysHyperdht ? this.hyperdhtRelay : "";
44378
45141
  return {
44379
- ...relay ? { "hyperdht/1": async (seedB64) => (await import("./hyperdhtRelay-CmqjYDch.js")).createRelayedHyperEndpoint(seedB64, relay) } : {},
45142
+ ...relay ? { "hyperdht/1": async (seedB64) => (await import("./hyperdhtRelay-SBo4aoMk.js")).createRelayedHyperEndpoint(seedB64, relay) } : {},
44380
45143
  ...this.options.nativeTransports,
44381
45144
  ...this.ownIrohRelays ? { "iroh/1": (seedB64) => this.options.nativeTransports["iroh/1"](seedB64, this.settings.irohRelays?.length ? { relays: [...this.settings.irohRelays] } : {}) } : {},
44382
45145
  ...this.options.irohWeb ? { "iroh/1": (seedB64) => createIrohWebEndpoint(seedB64, { relays: this.irohRelays }) } : {}
@@ -44460,10 +45223,133 @@ var GhostlyNode = class GhostlyNode {
44460
45223
  /**
44461
45224
  * Whether the chat goes live only over a native transport: this app has no WebRTC, or its contact has none (its record
44462
45225
  * lists no `webrtc/1`). Not known yet (no record read) counts as only natively, as a chat before its first record must.
45226
+ * So does every chat while this device's own attempts say its network blocks direct connections (`directPath`, a VPN
45227
+ * that drops UDP): WebRTC carries none there, and a chat with a contact that has WebRTC was left with no listener
45228
+ * behind eight chats with contacts that have none, down for as long as the VPN was on.
44463
45229
  */
44464
45230
  reachedOnlyNatively(live) {
44465
45231
  const theirs = live.stored.capsState?.peer?.transports ?? live.stored.peerTransports;
44466
- return typeof RTCPeerConnection === "undefined" || !theirs || !theirs.includes("webrtc/1");
45232
+ return typeof RTCPeerConnection === "undefined" || !theirs || !theirs.includes("webrtc/1") || this.directPath.blocked;
45233
+ }
45234
+ /**
45235
+ * When a chat or a group (for one of its edges) was last in use, for handing native listeners out least recently used
45236
+ * first: now while on screen, else the later of when it was last on screen and its newest message.
45237
+ */
45238
+ lastUsed(live, viewOf) {
45239
+ const group = live.stored.group, key = group ? `group:${group}` : live.stored.id;
45240
+ if (key === this.activeLinkId) return Date.now();
45241
+ return Math.max(this.openedAt.get(key) ?? 0, group ? viewOf(group)?.lastMessageAt ?? 0 : live.lastMessageAt);
45242
+ }
45243
+ /**
45244
+ * A group's edges that run native transports (`keepsGroupNative`), the one it keeps while it is not on screen first
45245
+ * (WISP 902 § Transports): to a hub, then the admin, then one the member keeps itself (`chosenByPeer`), then one that
45246
+ * holds a listener already (so the one it keeps does not change hands each time another member is heard), then the
45247
+ * member seen last. One passed over lately (`groupAnchorsAnswered`: its member never answered) comes after all of
45248
+ * them. The mesh's catch-up brings the group's messages through any member.
45249
+ */
45250
+ groupEdgesByRank(groupId, view) {
45251
+ const native = Object.keys(this.nativeFactories), now = Date.now();
45252
+ const lead = new Map(view?.members.filter((member) => !member.me && (member.hub || member.role === "admin")).map((member) => [member.key, member.hub ? 2 : 1]));
45253
+ const rank = (live) => [
45254
+ Number(!this.anchorPassed(live, now)),
45255
+ lead.get(live.stored.groupPeer) ?? 0,
45256
+ Number(this.chosenByPeer(live)),
45257
+ Number(native.some((t) => live.link.availableTransports.includes(t))),
45258
+ live.link.groupsSupport ? now : Math.max(presenceSeenAt(live.presence), live.lastSyncAt)
45259
+ ];
45260
+ const edges = [...this.links.values()].filter((live) => live.stored.group === groupId && !live.stored.groupEntry && live.link && this.keepsGroupNative(live.stored));
45261
+ const ranks = new Map(edges.map((live) => [live, rank(live)]));
45262
+ return edges.sort((a, b) => {
45263
+ const x = ranks.get(a), y = ranks.get(b);
45264
+ for (let i = 0; i < x.length; i++) if (y[i] !== x[i]) return y[i] - x[i];
45265
+ return 0;
45266
+ });
45267
+ }
45268
+ /**
45269
+ * A group's edge the member keeps (WISP 902 § Transports): its packet, read in this run, says its app holds a native
45270
+ * listener there that this app runs too (`_tr`; an app publishes a native transport there only while it listens).
45271
+ * Each side picks the one edge it keeps on its own (`groupEdgesByRank`), and a member's pick is not this side's: this
45272
+ * side keeps that edge too, or the member's listener meets none here (ghostly-agents#1437: the admin, its four group
45273
+ * listeners taken by two other groups, answered "no slot" to the edge its third group's member kept to it).
45274
+ */
45275
+ chosenByPeer(live, key) {
45276
+ if (!live.stored.group || live.stored.groupEntry || live.peerSaidAt === void 0) return false;
45277
+ const theirs = live.stored.peerTransports ?? [];
45278
+ const common = TRANSPORTS.filter((t) => t !== "webrtc/1" && t in this.nativeFactories && theirs.includes(t));
45279
+ if (!key) return common.length > 0;
45280
+ const failed = this.nativeFailed.has(live.stored.id);
45281
+ return (common.find((t) => live.link?.availableTransports.includes(t)) ?? common.find((t) => !(failed && live.transportErrors?.[t])) ?? common[0]) === key;
45282
+ }
45283
+ /** Group edges passed over as the one their group keeps (`groupAnchorsAnswered`), by link id: when. */
45284
+ anchorPassedOver = /* @__PURE__ */ new Map();
45285
+ anchorPassed(live, now) {
45286
+ return now - (this.anchorPassedOver.get(live.stored.id) ?? -Infinity) < GROUP_ANCHOR_PASSED_MS;
45287
+ }
45288
+ anchorCheckAt = 0;
45289
+ /**
45290
+ * A group's edge whose native listener has been up `GROUP_ANCHOR_ANSWER_MS` with no session, and whose member's
45291
+ * packet says it holds none there (or it is away): nobody answers it.
45292
+ */
45293
+ unanswered(live, now) {
45294
+ const link = live.link;
45295
+ if (!link || link.isDataLinkOpen) return false;
45296
+ const up = Object.keys(this.nativeFactories).filter((t) => link.availableTransports.includes(t)).map((t) => live.nativeUpAt?.[t] ?? now);
45297
+ if (!up.length || now - Math.min(...up) < 2e4) return false;
45298
+ return !this.chosenByPeer(live) || !live.presence.online;
45299
+ }
45300
+ /**
45301
+ * Every few seconds, each group not on screen whose edges run native transports: the one edge it keeps has a
45302
+ * listener (or waits for one, `groupNativeWaiting`), and when its member has not answered it in
45303
+ * `GROUP_ANCHOR_ANSWER_MS` (it is away, or it has no listener for it: all its own taken), the group keeps the next
45304
+ * one instead (hub, then admin, then the member heard from last), whose member answers the edge it keeps
45305
+ * (`chosenByPeer`). Not while any edge of the group is live: the group is reachable through it. Every other one passed
45306
+ * over lately too: the one it keeps stays, without its listener going back and forth.
45307
+ */
45308
+ groupAnchorsAnswered() {
45309
+ const native = Object.keys(this.nativeFactories), now = Date.now();
45310
+ if (!native.length || now < this.anchorCheckAt) return;
45311
+ this.anchorCheckAt = now + GROUP_ANCHOR_CHECK_MS;
45312
+ const groups = /* @__PURE__ */ new Set();
45313
+ for (const live of this.links.values()) {
45314
+ const group = live.stored.group;
45315
+ if (group && !live.stored.groupEntry && live.link && `group:${group}` !== this.activeLinkId && this.keepsGroupNative(live.stored)) groups.add(group);
45316
+ }
45317
+ if (!groups.size) return;
45318
+ const views = new Map(this.groups.views().map((view) => [view.id, view]));
45319
+ for (const groupId of groups) {
45320
+ const edges = this.groupEdgesByRank(groupId, views.get(groupId));
45321
+ if (!edges.length || edges.some((live) => live.link.isDataLinkOpen)) continue;
45322
+ const [anchor, next] = edges;
45323
+ if (next && !this.anchorPassed(next, now) && this.unanswered(anchor, now)) {
45324
+ this.anchorPassedOver.set(anchor.stored.id, now);
45325
+ this.groupNativeWaiting.delete(anchor.stored.id);
45326
+ traceLink(anchor.myPubKeyZ32, "group-anchor-passed", { group: groupId });
45327
+ this.passAnchor(anchor, next.stored.id);
45328
+ continue;
45329
+ }
45330
+ const id = anchor.stored.id;
45331
+ if (!native.some((t) => anchor.link.availableTransports.includes(t)) && !this.groupNativeWaiting.has(id) && !this.nativeFailed.has(id)) this.ensureNativeEndpoints(id);
45332
+ }
45333
+ }
45334
+ /** The edge passed over gives its listeners up (its member holds none for it), and the next one takes one now. */
45335
+ async passAnchor(passed, nextId) {
45336
+ const link = passed.link;
45337
+ for (const key of Object.keys(this.nativeFactories)) {
45338
+ if (!link || !link.availableTransports.includes(key) || !link.canReleaseEndpoint(key)) continue;
45339
+ await link.releaseEndpoint(key).catch(() => {});
45340
+ }
45341
+ if (this.shuttingDown) return;
45342
+ this.groupNativeWaiting.add(nextId);
45343
+ await this.ensureNativeEndpoints(nextId);
45344
+ }
45345
+ /** A group opened on screen: its edges with no native listener take one as a chat on screen does, the one it keeps first. */
45346
+ groupOnScreen(groupId) {
45347
+ const native = Object.keys(this.nativeFactories);
45348
+ const view = this.groups.views().find((g) => g.id === groupId);
45349
+ for (const live of this.groupEdgesByRank(groupId, view)) {
45350
+ if (native.every((t) => live.link.availableTransports.includes(t))) continue;
45351
+ this.ensureNativeEndpoints(live.stored.id);
45352
+ }
44467
45353
  }
44468
45354
  /** `inUse`: a text is going or coming in the chat now, which counts as the chat on screen does for taking a listener. */
44469
45355
  ensureNativeEndpoints(linkId, inUse = false) {
@@ -44514,32 +45400,45 @@ var GhostlyNode = class GhostlyNode {
44514
45400
  try {
44515
45401
  const owners = [...this.links.values()].filter((other) => other.link?.availableTransports.includes(key));
44516
45402
  const slots = this.nativeSlots(key), groups = owners.filter((other) => other.stored.group).length;
44517
- if (group && (owners.length >= slots || groups >= this.groupNativeSlots(key))) return "no-slot";
44518
- const full = owners.length >= slots;
45403
+ const now = Date.now();
45404
+ let views;
45405
+ const viewOf = (groupId) => (views ??= new Map(this.groups.views().map((view) => [view.id, view]))).get(groupId);
45406
+ const anchors = /* @__PURE__ */ new Map();
45407
+ const anchorOf = (groupId) => {
45408
+ if (!anchors.has(groupId)) anchors.set(groupId, this.groupEdgesByRank(groupId, viewOf(groupId))[0]);
45409
+ return anchors.get(groupId);
45410
+ };
45411
+ const onScreen = (other) => (other.stored.group ? `group:${other.stored.group}` : other.stored.id) === this.activeLinkId;
45412
+ const used = (other) => this.lastUsed(other, viewOf);
45413
+ const extra = (other) => !!other.stored.group && !other.stored.groupEntry && !onScreen(other) && anchorOf(other.stored.group) !== other && !this.chosenByPeer(other, key);
45414
+ const full = owners.length >= slots, entry = !!live.stored.groupEntry;
45415
+ if (group && (entry || extra(live)) && (full || groups >= this.groupNativeSlots(key) || !entry && !anchorOf(live.stored.group)?.link?.availableTransports.includes(key))) return "no-slot";
44519
45416
  if (full || !group && owners.length - groups >= NATIVE_SLOTS) {
44520
- const now = Date.now();
44521
- const taking = !group && (this.activeLinkId === linkId || inUse);
44522
- const victim = (!full ? void 0 : owners.filter((other) => other.stored.group && other.link?.canReleaseEndpoint(key)).sort((a, b) => (a.link?.isDataLinkOpen ? 1 : 0) - (b.link?.isDataLinkOpen ? 1 : 0))[0]) ?? (taking ? owners.filter((other) => other !== live && other.stored.id !== this.activeLinkId && other.link?.canReleaseEndpoint(key) && now - (other.nativeTakenAt?.[key] ?? 0) >= 12e4).sort((a, b) => a.lastMessageAt - b.lastMessageAt)[0] : void 0);
44523
- const idle = victim || !taking || !this.reachedOnlyNatively(live) ? void 0 : owners.filter((other) => other !== live && !other.stored.group && other.stored.id !== this.activeLinkId && !this.fileDesk.moving(other.stored.id) && other.link?.canYieldEndpoint(key, 12e4)).sort((a, b) => a.link.lastActivityAt - b.link.lastActivityAt)[0];
45417
+ const taking = group || this.activeLinkId === linkId || inUse;
45418
+ const mine = taking && (inUse || onScreen(live)) ? now : used(live);
45419
+ const groupVictim = !full ? void 0 : owners.filter((other) => other !== live && extra(other) && other.link?.canReleaseEndpoint(key)).sort((a, b) => (a.link?.isDataLinkOpen ? 1 : 0) - (b.link?.isDataLinkOpen ? 1 : 0) || used(a) - used(b))[0];
45420
+ const quiet = (other) => other !== live && (full || !other.stored.group) && !other.stored.groupEntry && !onScreen(other) && now - (other.nativeTakenAt?.[key] ?? 0) >= 12e4 && used(other) <= now - 12e4 && used(other) < mine;
45421
+ const victim = groupVictim ?? (taking ? owners.filter((other) => quiet(other) && other.link?.canReleaseEndpoint(key)).sort((a, b) => used(a) - used(b))[0] : void 0);
45422
+ const idle = victim || !taking || !group && !this.reachedOnlyNatively(live) ? void 0 : owners.filter((other) => quiet(other) && !this.fileDesk.moving(other.stored.id) && other.link?.canYieldEndpoint(key, 12e4)).sort((a, b) => Number(extra(b)) - Number(extra(a)) || Math.max(used(a), a.link.lastActivityAt) - Math.max(used(b), b.link.lastActivityAt))[0];
44524
45423
  const idleFor = idle ? now - idle.link.lastActivityAt : 0;
44525
45424
  if (idle && await idle.link.yieldEndpoint(key, 12e4)) {
44526
45425
  traceLink(live.myPubKeyZ32, "native-take", {
44527
45426
  transport: key,
44528
45427
  idle: idleFor,
44529
- active: this.activeLinkId === linkId
45428
+ active: this.activeLinkId === linkId,
45429
+ group
44530
45430
  });
44531
- live.nativeTakenAt = {
44532
- ...live.nativeTakenAt,
44533
- [key]: Date.now()
44534
- };
44535
45431
  idle.transportErrors ??= {};
44536
45432
  idle.transportErrors[key] = "Listener given to a chat in use: this one was quiet. Open this chat to take one back; your messages and transport identity are saved.";
45433
+ if (idle.stored.group) this.groupNativeWaiting.add(idle.stored.id);
44537
45434
  } else if (!victim) {
44538
45435
  traceLink(live.myPubKeyZ32, "native-no-slot", {
44539
45436
  transport: key,
44540
- active: this.activeLinkId === linkId
45437
+ active: this.activeLinkId === linkId,
45438
+ group
44541
45439
  });
44542
- if (this.activeLinkId === linkId && !group) this.retryActiveSlot(linkId);
45440
+ if (group) return "no-slot";
45441
+ if (this.activeLinkId === linkId) this.retryActiveSlot(linkId);
44543
45442
  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.");
44544
45443
  } else {
44545
45444
  await victim.link.releaseEndpoint(key);
@@ -44547,6 +45446,10 @@ var GhostlyNode = class GhostlyNode {
44547
45446
  victim.transportErrors[key] = "Listener released for another chat. Open this chat to restore it; your messages and transport identity are saved.";
44548
45447
  if (victim.stored.group) this.groupNativeWaiting.add(victim.stored.id);
44549
45448
  }
45449
+ live.nativeTakenAt = {
45450
+ ...live.nativeTakenAt,
45451
+ [key]: Date.now()
45452
+ };
44550
45453
  }
44551
45454
  if (this.shuttingDown || live.link !== link) return false;
44552
45455
  const seed = live.stored.transportSeeds?.[key] ?? createIdentity().seedB64;
@@ -44570,6 +45473,10 @@ var GhostlyNode = class GhostlyNode {
44570
45473
  return false;
44571
45474
  }
44572
45475
  link.registerEndpoint(endpoint);
45476
+ if (group) live.nativeUpAt = {
45477
+ ...live.nativeUpAt,
45478
+ [key]: Date.now()
45479
+ };
44573
45480
  delete live.transportErrors[key];
44574
45481
  this.capsChanged(linkId);
44575
45482
  this.emitState();
@@ -44653,6 +45560,7 @@ var GhostlyNode = class GhostlyNode {
44653
45560
  * Chats and group links whose listener failed to start try again once their wait is over.
44654
45561
  */
44655
45562
  retryNative() {
45563
+ this.groupAnchorsAnswered();
44656
45564
  const now = Date.now();
44657
45565
  for (const [linkId, failed] of this.nativeFailed) {
44658
45566
  if (now < failed.at) continue;
@@ -44710,10 +45618,19 @@ var GhostlyNode = class GhostlyNode {
44710
45618
  const reacted = this.reactionNotes.get(linkId);
44711
45619
  if (reacted?.message && ids.includes(reacted.message)) {
44712
45620
  const row = await db.getMessage(linkId, reacted.message);
44713
- const fresh = row && noteAfterChange(reacted, row);
44714
- if (fresh) {
44715
- this.reactionNotes.set(linkId, fresh);
44716
- this.emitState();
45621
+ if (!row) {
45622
+ const before = await this.reactionNoteNow(linkId, reacted);
45623
+ if (this.reactionNotes.get(linkId) === reacted) {
45624
+ if (before) this.reactionNotes.set(linkId, before);
45625
+ else this.reactionNotes.delete(linkId);
45626
+ this.emitState();
45627
+ }
45628
+ } else {
45629
+ const fresh = noteAfterChange(reacted, row);
45630
+ if (fresh) {
45631
+ this.reactionNotes.set(linkId, fresh);
45632
+ this.emitState();
45633
+ }
44717
45634
  }
44718
45635
  }
44719
45636
  const onChanges = this.events.onMessageChanges;
@@ -44831,6 +45748,7 @@ var GhostlyNode = class GhostlyNode {
44831
45748
  message = this.placed(message, place);
44832
45749
  const live = this.links.get(message.linkId);
44833
45750
  if (live?.stored.deletedIds?.includes(message.id)) return false;
45751
+ if (message.linkId.startsWith("group:") && this.groups.isRemoved(message.linkId.slice(6), message.id)) return false;
44834
45752
  message = await this.resolveReply(message);
44835
45753
  if (message.sender === "peer" && live && !message.details?.received) message = {
44836
45754
  ...message,
@@ -44863,6 +45781,7 @@ var GhostlyNode = class GhostlyNode {
44863
45781
  if (!message.event) this.newestAt.set(message.linkId, Math.max(newest ?? 0, writtenAt(message, this.clockLeads.get(this.clockOf(message)))));
44864
45782
  if (message.sender === "peer") this.messageFeedback("message", message, newest);
44865
45783
  if (live) live.lastMessageAt = Math.max(live.lastMessageAt, message.timestamp);
45784
+ if (live && message.sender === "peer" && message.via === "pkarr") live.pkarrSeenAt = Math.max(live.pkarrSeenAt ?? 0, pkarrSeenAt([message]));
44866
45785
  const early = message.sender === "peer" && message.id.startsWith("peer_") ? this.editBuffer.take(message.linkId, message.id.slice(5)) : void 0;
44867
45786
  if (early) {
44868
45787
  await this.applyPeerEdit(message.linkId, message, early);
@@ -45066,6 +45985,11 @@ var EngineServer = class {
45066
45985
  linkId,
45067
45986
  event
45068
45987
  }),
45988
+ onAppRange: (linkId, range) => this.broadcast({
45989
+ kind: "app-range",
45990
+ linkId,
45991
+ range
45992
+ }),
45069
45993
  onAppsChecked: () => this.broadcast({ kind: "apps-checked" }),
45070
45994
  onDeviceGate: (gate) => this.broadcast({
45071
45995
  kind: "device-gate",
@@ -45086,8 +46010,10 @@ var EngineServer = class {
45086
46010
  /**
45087
46011
  * `read`: the chats and groups whose whole history the client read itself, after `mark` (`historyMark`). One that has
45088
46012
  * not changed since is not read and sent again: the client hears only what changes in it from now on.
46013
+ * `newest`: each chat's newest rows that many (`messagePage`), not its whole history, which the client asks for when
46014
+ * it needs it (`HistoryRequest`). What changes in the chat goes to it on top of that page.
45089
46015
  */
45090
- attach(client, read) {
46016
+ attach(client, read, scope = {}) {
45091
46017
  this.clients.add(client);
45092
46018
  const sent = /* @__PURE__ */ new Set();
45093
46019
  if (read) {
@@ -45110,7 +46036,7 @@ var EngineServer = class {
45110
46036
  if (sent.has(link.id)) continue;
45111
46037
  await this.inOrder(link.id, async () => {
45112
46038
  if (!this.clients.has(client)) return;
45113
- client.post({
46039
+ client.post(scope.newest ? await this.newestOf(link.id, scope.newest) : {
45114
46040
  kind: "messages",
45115
46041
  linkId: link.id,
45116
46042
  messages: await this.node.getMessages(link.id)
@@ -45179,6 +46105,38 @@ var EngineServer = class {
45179
46105
  return Promise.reject(error);
45180
46106
  }
45181
46107
  }
46108
+ /** A chat's newest page, as a `messages` event: `more` when older rows are left out. */
46109
+ async newestOf(linkId, limit) {
46110
+ const page = await this.node.messagePage({
46111
+ linkId,
46112
+ limit
46113
+ });
46114
+ return {
46115
+ kind: "messages",
46116
+ linkId,
46117
+ messages: page.messages,
46118
+ ...page.more ? { more: true } : {}
46119
+ };
46120
+ }
46121
+ /**
46122
+ * A chat's or group's whole history, to this client alone as a `messages` event, after what is still being sent for it
46123
+ * (a `HistoryRequest`, which the host hands here): what changes while it is read follows it.
46124
+ */
46125
+ async history(client, linkId) {
46126
+ if (typeof linkId !== "string" || !this.clients.has(client)) return;
46127
+ try {
46128
+ await this.ready;
46129
+ await this.inOrder(linkId, async () => {
46130
+ if (!this.clients.has(client)) return;
46131
+ const messages = await this.node.getMessages(linkId);
46132
+ if (this.clients.has(client) && this.post(client, {
46133
+ kind: "messages",
46134
+ linkId,
46135
+ messages
46136
+ })) this.histories.get(client)?.add(linkId);
46137
+ });
46138
+ } catch {}
46139
+ }
45182
46140
  changed(linkId) {
45183
46141
  this.changedAt.set(linkId, ++this.changes);
45184
46142
  }
@@ -45253,4 +46211,4 @@ function signalKind(signal) {
45253
46211
  //#endregion
45254
46212
  export { EngineServer };
45255
46213
 
45256
- //# sourceMappingURL=server-CYCzKx-R.js.map
46214
+ //# sourceMappingURL=server-DIICuvgy.js.map