@ghostlytools/cli 1.4.5 → 1.5.1

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 (89) hide show
  1. package/README.md +14 -7
  2. package/dist/assets/{api-D70he3-A.js → api-Dy_05gaq.js} +93 -62
  3. package/dist/assets/api-Dy_05gaq.js.map +1 -0
  4. package/dist/assets/{api-XX7bbtTZ.js → api-oUpBfryK.js} +2 -2
  5. package/dist/assets/{apiKit-CpsEqF-1.js → apiKit-B-PUYkXH.js} +2 -2
  6. package/dist/assets/{apiKit-CpsEqF-1.js.map → apiKit-B-PUYkXH.js.map} +1 -1
  7. package/dist/assets/{apps-DVMnlwGF.js → apps-C6MBfO-I.js} +1 -1
  8. package/dist/assets/{apps-VA8W_YCQ.js → apps-ejb6H1lT.js} +2 -2
  9. package/dist/assets/{apps-VA8W_YCQ.js.map → apps-ejb6H1lT.js.map} +1 -1
  10. package/dist/assets/{arkade-DxgW4-dK.js → arkade-DXyOeKEI.js} +2 -2
  11. package/dist/assets/{arkade-DxgW4-dK.js.map → arkade-DXyOeKEI.js.map} +1 -1
  12. package/dist/assets/{backup-BRTH1y3-.js → backup-Bt6UjCiM.js} +1 -1
  13. package/dist/assets/{backup-c9xvXgCS.js → backup-DRIIguzE.js} +6 -6
  14. package/dist/assets/{backup-c9xvXgCS.js.map → backup-DRIIguzE.js.map} +1 -1
  15. package/dist/assets/bark_ffi_wasm_bg-EY2uc0Bx.js.map +1 -1
  16. package/dist/assets/{blobFiles-B0rNnHlO.js → blobFiles-1wUBd8ZD.js} +3 -3
  17. package/dist/assets/{blobFiles-B0rNnHlO.js.map → blobFiles-1wUBd8ZD.js.map} +1 -1
  18. package/dist/assets/buttons-B3bi6p_d.js +2 -0
  19. package/dist/assets/{buttons-D31LBftz.js → buttons-DoccJ_cK.js} +3 -3
  20. package/dist/assets/{buttons-D31LBftz.js.map → buttons-DoccJ_cK.js.map} +1 -1
  21. package/dist/assets/daemonProof-CWTVNUmr.js +254 -0
  22. package/dist/assets/daemonProof-CWTVNUmr.js.map +1 -0
  23. package/dist/assets/{envelope-hAl4pblf.js → envelope-hJ0SfbAh.js} +2 -2
  24. package/dist/assets/{envelope-hAl4pblf.js.map → envelope-hJ0SfbAh.js.map} +1 -1
  25. package/dist/assets/fedimint_client_wasm_bg-BtHHlFpp.js.map +1 -1
  26. package/dist/assets/{fileBytes-B-fqGdEd.js → fileBytes-B8eTZfAT.js} +3 -3
  27. package/dist/assets/{fileBytes-B-fqGdEd.js.map → fileBytes-B8eTZfAT.js.map} +1 -1
  28. package/dist/assets/{fileBytes-C2jycN_7.js → fileBytes-gTd_8l-P.js} +1 -1
  29. package/dist/assets/{fileBytes-D6fqFQEX.js → fileBytes-uRqLyxa0.js} +2 -2
  30. package/dist/assets/{fileBytes-D6fqFQEX.js.map → fileBytes-uRqLyxa0.js.map} +1 -1
  31. package/dist/assets/{fileBytesIdb-_HnxdacI.js → fileBytesIdb-BIFKtgln.js} +3 -3
  32. package/dist/assets/{fileBytesIdb-_HnxdacI.js.map → fileBytesIdb-BIFKtgln.js.map} +1 -1
  33. package/dist/assets/fileBytesIdb-BVVr_rWX.js +2 -0
  34. package/dist/assets/{fileBytesOpfs-p_CANncD.js → fileBytesOpfs-ChrHcCVV.js} +3 -3
  35. package/dist/assets/{fileBytesOpfs-p_CANncD.js.map → fileBytesOpfs-ChrHcCVV.js.map} +1 -1
  36. package/dist/assets/{groupFiles-gQ8_792r.js → groupFiles-BXPINkVJ.js} +60 -14
  37. package/dist/assets/groupFiles-BXPINkVJ.js.map +1 -0
  38. package/dist/assets/{host-Dmo6m7So.js → host-CzgYwupN.js} +15 -122
  39. package/dist/assets/host-CzgYwupN.js.map +1 -0
  40. package/dist/assets/{hyperdhtRelay-DwkZ8vpt.js → hyperdhtRelay-CJBqsS_e.js} +2 -2
  41. package/dist/assets/{hyperdhtRelay-DwkZ8vpt.js.map → hyperdhtRelay-CJBqsS_e.js.map} +1 -1
  42. package/dist/assets/{idb-CMVgtn2k.js → idb-BJARz3Qi.js} +5 -3
  43. package/dist/assets/idb-BJARz3Qi.js.map +1 -0
  44. package/dist/assets/{irohWeb-DKJhESuV.js → irohWeb-CrGOD-OD.js} +2 -2
  45. package/dist/assets/{irohWeb-DKJhESuV.js.map → irohWeb-CrGOD-OD.js.map} +1 -1
  46. package/dist/assets/{main-DgXvK9Cr.js → main-BDOIJ_ls.js} +240 -53
  47. package/dist/assets/main-BDOIJ_ls.js.map +1 -0
  48. package/dist/assets/{mainline-9j_FqcJe.js → mainline-Cw7rnEWM.js} +2 -2
  49. package/dist/assets/{mainline-9j_FqcJe.js.map → mainline-Cw7rnEWM.js.map} +1 -1
  50. package/dist/assets/{networkReason-Bp8Huk9Z.js → networkReason-C0VY94cG.js} +3 -3
  51. package/dist/assets/{networkReason-Bp8Huk9Z.js.map → networkReason-C0VY94cG.js.map} +1 -1
  52. package/dist/assets/{nwc-DxIjNmYz.js → nwc-lpGWvzYU.js} +3 -3
  53. package/dist/assets/{nwc-DxIjNmYz.js.map → nwc-lpGWvzYU.js.map} +1 -1
  54. package/dist/assets/{nwcProvider-CyGVe35t.js → nwcProvider-CAGRn2ly.js} +2 -2
  55. package/dist/assets/{nwcProvider-CyGVe35t.js.map → nwcProvider-CAGRn2ly.js.map} +1 -1
  56. package/dist/assets/{profiles-ClRPr6y8.js → profiles-BehWURA9.js} +7 -3
  57. package/dist/assets/profiles-BehWURA9.js.map +1 -0
  58. package/dist/assets/{registry-siqMiD8L.js → registry-D2bK-k1T.js} +1 -1
  59. package/dist/assets/{registry-BTIRr7gH.js → registry-DWkkBN57.js} +3 -3
  60. package/dist/assets/registry-DWkkBN57.js.map +1 -0
  61. package/dist/assets/{resolve-CZ4yb7wp.js → resolve-CvYK0Lbt.js} +2 -2
  62. package/dist/assets/{resolve-CZ4yb7wp.js.map → resolve-CvYK0Lbt.js.map} +1 -1
  63. package/dist/assets/{restoredRows-DeBImGRd.js → restoredRows-DGuKtIBz.js} +2 -2
  64. package/dist/assets/{restoredRows-DeBImGRd.js.map → restoredRows-DGuKtIBz.js.map} +1 -1
  65. package/dist/assets/{server-ZrkwMbFo.js → server-BktMmp7L.js} +1141 -310
  66. package/dist/assets/server-BktMmp7L.js.map +1 -0
  67. package/dist/assets/{src-CxEO33Hb.js → src-Bpy99Z2K.js} +828 -57
  68. package/dist/assets/src-Bpy99Z2K.js.map +1 -0
  69. package/dist/assets/{usdt-exH8dIZK.js → usdt-DFusiw8x.js} +3 -3
  70. package/dist/assets/{usdt-exH8dIZK.js.map → usdt-DFusiw8x.js.map} +1 -1
  71. package/dist/assets/{turnRefs-Dndxqyxk.js → words-Z-izzDBN.js} +61 -3
  72. package/dist/assets/words-Z-izzDBN.js.map +1 -0
  73. package/dist/ghostly.mjs +1 -1
  74. package/package.json +1 -1
  75. package/skills/ghostly/scripts/status +3 -2
  76. package/dist/assets/api-D70he3-A.js.map +0 -1
  77. package/dist/assets/buttons-CtGCix-8.js +0 -2
  78. package/dist/assets/daemonProof-B53VnZ1Z.js +0 -100
  79. package/dist/assets/daemonProof-B53VnZ1Z.js.map +0 -1
  80. package/dist/assets/fileBytesIdb-DOxm_BKt.js +0 -2
  81. package/dist/assets/groupFiles-gQ8_792r.js.map +0 -1
  82. package/dist/assets/host-Dmo6m7So.js.map +0 -1
  83. package/dist/assets/idb-CMVgtn2k.js.map +0 -1
  84. package/dist/assets/main-DgXvK9Cr.js.map +0 -1
  85. package/dist/assets/profiles-ClRPr6y8.js.map +0 -1
  86. package/dist/assets/registry-BTIRr7gH.js.map +0 -1
  87. package/dist/assets/server-ZrkwMbFo.js.map +0 -1
  88. package/dist/assets/src-CxEO33Hb.js.map +0 -1
  89. package/dist/assets/turnRefs-Dndxqyxk.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 bytesEqual, $o as handoffContextProof, $r as chatAppId, $s as knockSlotIdentity, A as knockRecords, Aa as wireReaction, Ac as isAppRef, Ai as capsDescriptors, 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 traceLink, 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 createIdentity, Go as HANDOFF_VERIFIED, Gr as deviceWakeRequest, Gs as newInbox, Gt as encodeDidDhtPacket, H as frameBytes, Hc as readContactLink, Hi as receivedIdentityStatus, 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 budgetRetryMs, 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 publicKeyFromZ32, 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 identityFromSeed, Ko as filePartName, Kr as newWakeToken, Ks as planKnocks, L as parseGroupWakeFrame, Lc as canonicalJson, Ll as isDiscoveryBudgetError, 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 currentRelays, Mn as parseCashuRequestPayload, Mo as HTTP_SERVICE_PROTO, Ms as enrollCancelFrame, Na as replySnippet, Nl as normalizeRelayUrl, 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, On as cashuRequestPayload, Or as FILE_LIMITS, P as GroupWakeLimiter, Pa as BUTTON_ID, Pi as IDENTITY_REVOCATION_LABEL, Pn as GhostLink, Po as serviceIdFromName, Ps as enrollDigits, Qa as GROUP_ADMIN_OFF_ERROR, Ql as sanitizeDisplayText, Qo as handoffContext, Qs as contactDay, Qt as SEPOLIA_TEST_USDT, R as GROUP_LIMITS, Ri as emptyIdentityLedger, Rl as withRequestOptions, 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, 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, Vl as createRelayPayload, Vn as engineText, Vo as HANDOFF_PAKE, Vr as pinNumberHolds, Vs as verifyEnrollProof, Wa as checkStatusCard, Wc as deviceInviteJoinerParams, Wi as lastSharedWithMe, Wo as HANDOFF_TIMINGS, Wr as WakeLimiter, Ws as inboxRecord, Wt as encodeDidDhtDeactivated, Xa as receivedTimestamp, Xc as inviteLink, 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 verify, Yo as handoffAttemptSucceeded, Yr as wakeRequest, Ys as turnOff, Yt as EVM_TEST_CHAINS, Za as shownTime, Zc as inviteOwnership, Zl as sanitizeAvatar, 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, au as utf8Decode, 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 fromBase64Url, 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, iu as toZ32, 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 RelayTransport, 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 randomBytes, 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, ou as utf8Encode, 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, ql as identityFromSeedB64, 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 toBase64Url, 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, 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, zl as PacketTooLargeError, zn as pairedMessageFrame, zo as HANDOFF_HELLO, zr as nextPinNumber, zs as readEnrollGrant } from "./src-CxEO33Hb.js";
2
+ import { $a as sameButtonText, $c as deviceInviteJoinerParams, $o as HANDOFF_TIMINGS, $r as isServeId, $s as inboxRecord, A as knockRecords, Aa as queueReaction, Ac as readAppBundleAsync, Ai as CapsExchange, Al as signTurnRelease, An as findEndpoint, Ar as transferStalled, B as GROUP_READ_NOTE, Bc as readAppRevocation, Bi as emptyIdentityLedger, Bn as engineError, Bo as emptyLinkRecords, Br as pinIsNewer, C as decodeCommunityLink, Ca as forwardedAgain, Cc as appDigest, Cl as turnPutSummary, Co as GhostlyHttpError, Cr as readBeacon, Cs as readHandoffDone, D as encodeGroupEntryLink, Da as REACTION_LIMITS, Dc as isAppUrl, Dl as nextTurnPosition, Dn as ENDPOINT, Do as LIMITS, Dr as ChatFiles, Ds as readHandoffTurnFrame, E as decodeGroupEntryLink, Ea as GROUP_REACTION_FRAME, El as firstDeviceSetSecret, En as decodeBolt11, Eo as webLocalFetch, Er as shouldBeHub, Es as readHandoffPake, F as groupWakeFrame, Fa as wireReaction, Fc as appRef, Fl as turnVerifierMark, Fn as INVITE_TAKEN, Fr as typingActivity, Fs as signTombstone, G as GROUP_EDIT_TEXT_BYTES, Gi as revokesIdentity, Gl as budgetRetryMs, Go as HANDOFF_CANCEL, Gr as deviceWakeRequest, Gs as enrollGrantFrame, Gt as encodeDidDhtPacket, H as frameBytes, Hi as identityStatement, Hl as normalizeRelayUrl, Hn as parseEngineError, Ho as LEGACY_SERVICES, Hr as readPin, Hs as enrollCancelReason, Ht as didDhtDocument, I as groupWakes, Ia as pairedReplyAuthor, Ii as IDENTITY_REVOCATION_LABEL, Il as DEFAULT_RELAYS, In as LIVENESS_PING_MS, Io as contactRtcConfig, Is as verifySetUpdate, J as mentionsMember, Jc as readCanonicalJson, Ji as emptyProofLedger, Jl as PacketTooLargeError, Jn as groupFileFallback, Jo as HANDOFF_HELLO, Jr as relayRequest, Js as readEnrollGrant, Jt as ETHEREUM_USDT, K as carryMentions, Ka as STATUS_CARD_LIMITS, Kc as canonicalJson, Ki as lastSharedWithMe, Kl as isDiscoveryBudgetError, Ko as HANDOFF_DONE, Kr as newWakeToken, Ks as enrollHelloFrame, L as parseGroupWakeFrame, La as readReply, Lc as isAppHash, Ln as PAIRED_FRAME_TOO_LARGE, Lr as PIN_LIMITS, M as readKnocks, Ma as reactionIsNewer, Mi as capsDescriptors, Ml as turnKeys, Mn as parseCashuRequestPayload, Ms as readSetUpdate, Na as readReaction, Nc as APP_STATEMENT_LIMITS, Ni as dialDescriptors, Nl as turnName, Nn as parseFedimintRequestPayload, Nr as TypingSender, Ns as setAckFrame, O as entryParams, Oa as ReactionWindow, Oc as pacer, Ol as readTurnPacket, On as cashuRequestPayload, Oo as decodeControl, Or as FILE_LIMITS, Os as readHandoffVerified, P as GroupWakeLimiter, Pa as validReactionNumber, Pc as appFingerprint, Pl as turnStatedVerifier, Pn as GhostLink, Ps as setUpdateFrame, Qa as checkStatusCard, Qc as createDeviceInvite, Qo as HANDOFF_REQUEST, Qr as APP_RANGE_LIMITS, Qs as endedRequests, Qt as SEPOLIA_TEST_USDT, R as GROUP_LIMITS, Ra as replySnippet, Rc as isAppKey, Ri as IdentityExchange, Rl as RelayTransport, Rn as pairedMessageFits, Ro as parseCallSignal, Rr as mayPin, S as communityHasFrame, Sa as parseLinkPreview, Sl as classifyTurnRead, So as presenceSeenAt, Sr as rankHubs, Ss as readHandoffCancel, Ta as COMMUNITY_REACTION_FRAME, Tl as TURN_MAX, To as parseLocalTarget, Tr as readLobby, Ts as readHandoffHello, Ui as newIdentityBinding, Un as GROUP_FILE_LIMITS, Uo as serviceIdFromName, Ur as WAKE_CALL_INTERVAL_MS, Us as enrollDigits, Ut as didDhtFromPublicKey, V as GroupSession, Vi as identityRevocationValue, Vl as currentRelays, Vn as engineText, Vo as HTTP_SERVICE_PROTO, Vr as pinNumberHolds, Vs as enrollCancelFrame, Wc as parseImageMeta, Wi as receivedIdentityStatus, Wl as traceLink, Wo as HANDOFF_ACK, Wr as WakeLimiter, Ws as enrollDoneFrame, Wt as encodeDidDhtDeactivated, Xc as encodeContactLink, Xi as TRANSPORTS, Xl as createRelayPayload, Xn as readGroupFileMeta, Xo as HANDOFF_PAKE, Xr as checkPushEndpoint, Xs as verifyEnrollProof, Xt as ONCHAIN_PROVIDER, Y as groupName, Yc as createContactLink, Yi as validExternalKey, Yo as HANDOFF_OFFER, Yr as wakeRequest, Ys as readEnrollHello, Yt as EVM_TEST_CHAINS, Zc as readContactLink, Zi as automaticTransport, Zo as HANDOFF_PIECE_BYTES, Zr as vapidKeysMatch, Zs as clearMissed, Zt as PaymentPreflightError, _ as openGroupTyping, _a as EDIT_RATE_WINDOW_MS, _c as requestRecords, _l as seedSigner, _r as lobbyRecords, _s as handoffRetryAfter, a as appStoreDecision, aa as formatFileSize, ac as ContactRequestError, ai as EDIT_CAPABILITY, al as inviteLink, an as assertWholeSats, ao as shownTime, ar as groupSignalFrame, as as handoffBusyFrame, b as CommunitySession, ba as RateWindow, bc as APP_BUNDLE_MAGIC, bl as TURN_RAISE_READ_TIMEOUT_MS, bo as RELAY_POLL_INTERVALS, br as newerHead, bs as newHandoffId, c as planAppUpdate, cc as knockSlotIdentity, ci as HOLD_CAPABILITY, cl as DEVICES_CAPABILITY, cn as walletNetworkOf, cr as mayBeHub, cs as handoffContextProof, cu as bytesEqual, da as fileMessageText, dc as linkRecords, di as HoldKeys, dl as deviceEchoFrame, dn as sparkAddressKind, do as parseGroupCommit, dr as COMMUNITY_TOPOLOGY, ds as handoffEphemeral, du as randomBytes, ec as newInbox, el as readDeviceInvite, en as TEST_USDT_FAUCET_AMOUNT, eo as statusCardText, er as CarriedTransport, es as HANDOFF_VERIFIED, eu as createIdentity, f as readAppStoreSteps, fa as parseVoiceMeta, fc as makeStampPaced, fi as HoldRefusedError, fl as deviceEchoNonce, fn as sparkInvoiceDetails, fo as rosterAdmin, fr as beaconKeys, fs as handoffHelloFrame, fu as toBase64Url, g as groupTypingEpoch, ga as EDIT_BUFFER_MS, gc as readLinkRecord, gl as newDeviceSetSecret, go as DirectPathWatch, gr as lobbyKeys, gs as handoffReleaseFrame, gt as normalizeAtprotoHandle, h as GroupTypingBoard, ha as parseVideoMeta, hc as readKnockSlot, hi as readManifest, hl as devicePingFrame, hn as isPubkyKey, ho as edgeParams, hr as freshHubs, hs as handoffPakeFrame, ht as isAtprotoDid, hu as utf8Encode, i as appRevocationFor, ia as dhtFileId, ic as turnOff, ii as BUTTONS_CAPABILITY, il as encodeInviteCode, in as assertTokenUnits, io as receivedTimestamp, is as handoffAttemptSucceeded, iu as verify, j as mergeKnocks, ja as reactionEmoji, jc as sha256Paced, ji as DHT_TEXT_CAPABILITY, jl as turnInstance, jn as isFederationId, jo as RTC_CONFIG, k as knockIdentity, ka as nextReactionNumber, kl as signTurnPacket, kn as fedimintRequestPayload, ko as encodeControl, kr as transferEnded, ks as sealHandoffPiece, l as APP_STORE_LIMITS, lc as knockSlotOf, li as HOLD_DATED_BACK_MS, ll as ENROLL_CAPABILITY, ln as SPARK_NETWORKS, lo as MEMBER_KEY, lr as meshHubs, ls as handoffDataFrame, lu as fromBase64Url, mc as openRequest, mi as newMailbox, ml as deviceLinkPairing, mo as verifyCommitSignature, mr as doorHubs, ms as handoffOfferFrame, mu as utf8Decode, n as readX401SdJwtVc, na as peekDhtMailbox, nc as settleRequest, ni as isAppVersion, nl as createChatInvite, nn as WALLET_NETWORKS, no as claimedTime, ns as handoffAttemptAllowed, nu as identityFromSeedB64, o as appUpdateDecision, oa as sanitizeFileName, oc as REQUEST_LIFETIME_MS, oi as STATUS_CARD_CAPABILITY, ol as inviteOwnership, on as formatPaymentAmount, oo as GROUP_ADMIN_OFF_ERROR, or as readGroupSignal, os as handoffCancelFrame, ou as sanitizeAvatar, pc as mergeContactKnocks, pi as isHoldUrl, pl as deviceKeyZ32, pn as isBitcoinAddress, po as rosterHas, pr as beaconRecords, ps as handoffManifestFrames, pu as toZ32, q as parseCommunityEdit, qi as PeerProofs, ql as withRequestOptions, qo as HANDOFF_HAVE, qr as parseWakeFrame, qs as enrollProofFrame, qt as signDidDhtPacket, r as sameX401HolderJwk, ra as DHT_FILE_CAPABILITY, rc as takeRequest, ri as APPS_CAPABILITY, rl as decodeInviteCode, rn as arkAddressPrefix, ro as heardTime, rs as handoffAttemptFailed, ru as publicKeyFromZ32, s as checkAppBeforeRun, sa as sanitizeMime, sc as contactDay, si as UPGRADE_CAPABILITY, sn as validatePaymentTarget, so as GROUP_MEMBER_CAP, sr as MESH_HUBS, ss as handoffContext, su as sanitizeDisplayText, t as newX401HolderKey, ta as DHT_MESSAGE_TTL, tc as planKnocks, ti as chatAppId, tl as OwnInviteError, tn as USDT_PUBLIC_RPC, to as arrivalKey, ts as filePartName, tu as identityFromSeed, uc as knockSlotRecords, ui as HOLD_LIMITS, ul as HANDOFF_CAPABILITY, un as SPARK_PROVIDER, uo as commitHash, ur as pickMeshHubs, us as handoffDigest, v as sealGroupTyping, va as MAX_REMOVAL_NUMBER, vc as seenEntry, vl as webCryptoSigner, vo as DHT_POLL_INTERVALS, vr as mergeBeacon, vs as handoffStreamKey, w as encodeCommunityLink, wa as readForwarded, wc as appViewOf, wl as TURN_LAST_SEQUENCE, wo as formatLocalTarget, wr as readBeaconHead, ws as readHandoffHave, x as GROUP_READ_NOTE_COMMUNITY, xa as dhtEditId, xc as APP_ICON_PATH, xl as TURN_SETTLE_MS, xo as WATCH_PEER_MS, xr as pickHubs, xs as readHandoffAck, y as COMMUNITY_LIMITS, ya as REMOVED_TEXT, yc as APP_BUNDLE_LIMITS, yr as mergeLobby, ys as handoffVersions, za as BUTTON_ID, zc as isAppRef, zn as pairedMessageFrame, zr as nextPinNumber } from "./src-Bpy99Z2K.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-CyGVe35t.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-Bp8Huk9Z.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-gQ8_792r.js";
9
- import { i as fedimintDatabase, n as createIrohWebEndpoint, o as loadFedimintSdk, r as irohRelayProblem, t as DEFAULT_IROH_RELAYS } from "./irohWeb-DKJhESuV.js";
5
+ import { t as nwc } from "./nwcProvider-CAGRn2ly.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-C0VY94cG.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-BXPINkVJ.js";
9
+ import { i as fedimintDatabase, n as createIrohWebEndpoint, o as loadFedimintSdk, r as irohRelayProblem, t as DEFAULT_IROH_RELAYS } from "./irohWeb-CrGOD-OD.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-CZ4yb7wp.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-hAl4pblf.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-CvYK0Lbt.js";
12
+ import { i as fromBase64Url$1, n as MAX_BACKUP_BYTES, t as BACKUP_MEDIA_TYPE } from "./envelope-hJ0SfbAh.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-exH8dIZK.js");
201
+ var loadUsdt = () => import("./usdt-DFusiw8x.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-DxgW4-dK.js");
650
+ var loadArkade = () => import("./arkade-DXyOeKEI.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-siqMiD8L.js").then((m) => {
6816
+ return loading$1 ??= import("./registry-D2bK-k1T.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"];
@@ -20443,6 +20660,13 @@ function takesPeerEdit(message, text) {
20443
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));
20444
20661
  }
20445
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
+ /**
20446
20670
  * The message after edit `seq`, made at `at`: the new text (and the preview and the status card that came with it, or
20447
20671
  * none: each belongs to its version), the version it replaces kept in the history. A text that did not change adds no
20448
20672
  * version. A status card's update adds none either (WISP 405 · Status Cards): it replaces the card in place, and its
@@ -21258,7 +21482,13 @@ var EditQueue = class {
21258
21482
  }
21259
21483
  if (!this.pace.take()) break;
21260
21484
  const receiptMs = typeof this.deps.receiptMs === "function" ? this.deps.receiptMs() : this.deps.receiptMs ?? 2e4;
21261
- 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
+ } : {
21262
21492
  id: message.wireId,
21263
21493
  e: edit.seq,
21264
21494
  ts: edit.at,
@@ -21372,6 +21602,114 @@ var EditBuffer = class {
21372
21602
  }
21373
21603
  };
21374
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
+ /** How often a chat is read whole for the quotes of removed messages (`QuoteSweeps`). */
21609
+ var QUOTE_SWEEP_MS = 1e4;
21610
+ /**
21611
+ * The quotes of removed messages, here or not (never came, or deleted here first). The replies that quote one are found
21612
+ * by reading the chat whole, and a contact or a member can send and remove, or remove ids that never were, at its edit
21613
+ * pace. So a chat is read for them at most once a `QUOTE_SWEEP_MS`: the first at once, the ones that come meanwhile
21614
+ * together when the time is up.
21615
+ */
21616
+ var QuoteSweeps = class {
21617
+ sweep;
21618
+ now;
21619
+ chats = /* @__PURE__ */ new Map();
21620
+ constructor(sweep, now = Date.now) {
21621
+ this.sweep = sweep;
21622
+ this.now = now;
21623
+ }
21624
+ add(chat, id, ref) {
21625
+ let state = this.chats.get(chat);
21626
+ if (!state) this.chats.set(chat, state = {
21627
+ due: /* @__PURE__ */ new Map(),
21628
+ at: -Infinity,
21629
+ busy: false
21630
+ });
21631
+ state.due.set(id, ref);
21632
+ this.next(chat);
21633
+ }
21634
+ /** The chat is gone: what waits for it is dropped. */
21635
+ forget(chat) {
21636
+ clearTimeout(this.chats.get(chat)?.timer);
21637
+ this.chats.delete(chat);
21638
+ }
21639
+ stop() {
21640
+ for (const state of this.chats.values()) clearTimeout(state.timer);
21641
+ this.chats.clear();
21642
+ }
21643
+ next(chat) {
21644
+ const state = this.chats.get(chat);
21645
+ if (!state?.due.size || state.busy || state.timer) return;
21646
+ const wait = state.at + QUOTE_SWEEP_MS - this.now();
21647
+ if (wait > 0) {
21648
+ state.timer = setTimeout(() => {
21649
+ state.timer = void 0;
21650
+ this.next(chat);
21651
+ }, wait);
21652
+ return;
21653
+ }
21654
+ const removed = state.due;
21655
+ state.due = /* @__PURE__ */ new Map();
21656
+ state.busy = true;
21657
+ state.at = this.now();
21658
+ this.sweep(chat, removed).catch(() => {}).finally(() => {
21659
+ state.busy = false;
21660
+ if (this.chats.get(chat) === state) this.next(chat);
21661
+ });
21662
+ }
21663
+ };
21664
+ /** The row a removal reads as to the edit queues: mine, its fallback text, its edit pending until said. */
21665
+ function removalRow(linkId, removal) {
21666
+ return {
21667
+ linkId,
21668
+ id: removal.id,
21669
+ ...removal.wireId && { wireId: removal.wireId },
21670
+ text: REMOVED_TEXT,
21671
+ sender: "me",
21672
+ timestamp: removal.at,
21673
+ via: "datalink",
21674
+ delivery: "delivered",
21675
+ removed: true,
21676
+ edit: {
21677
+ seq: removal.e,
21678
+ at: removal.at,
21679
+ history: [],
21680
+ ...removal.pending && { pending: true }
21681
+ }
21682
+ };
21683
+ }
21684
+ /** The list with this removal in it, in place of an older one of the same message; the newest `MAX_REMOVALS`. */
21685
+ function withRemoval(list, removal) {
21686
+ return [...(list ?? []).filter((r) => r.id !== removal.id), removal].slice(-500);
21687
+ }
21688
+ /**
21689
+ * A change an edit queue made to a removal's row (`patch`), on the list: the edit said or confirmed is no longer pending.
21690
+ * `drop`: confirmed in a 1:1 chat, nothing is left to say. Null when nothing changed.
21691
+ */
21692
+ function patchRemoval(list, id, change, linkId, drop = false) {
21693
+ const removal = list?.find((r) => r.id === id);
21694
+ if (!removal) return null;
21695
+ const row = removalRow(linkId, removal), patch = change(row);
21696
+ if (!patch) return null;
21697
+ const next = {
21698
+ ...row,
21699
+ ...patch
21700
+ };
21701
+ const left = list.filter((r) => r.id !== id);
21702
+ if (drop && !next.edit?.pending) return {
21703
+ list: left,
21704
+ row: next
21705
+ };
21706
+ const { pending: _said, ...said } = removal;
21707
+ return {
21708
+ list: [...left, next.edit?.pending ? removal : said],
21709
+ row: next
21710
+ };
21711
+ }
21712
+ //#endregion
21375
21713
  //#region ../browser/src/shared/walletRemoval.ts
21376
21714
  var UNFINISHED = /* @__PURE__ */ new Set([
21377
21715
  "pending",
@@ -22112,6 +22450,8 @@ function settleAhead(history, now) {
22112
22450
  //#endregion
22113
22451
  //#region ../browser/src/engine/reactions.ts
22114
22452
  var isGroup$1 = (chat) => chat.startsWith("group:");
22453
+ /** How often a 1:1 chat is read whole for received reactions its rows' ids did not find (`Reactions.find`). */
22454
+ var REACTION_LOOKUP_MS = 1e4;
22115
22455
  /** The row a reaction names in a chat: the id both sides know it by (`replyRef`). */
22116
22456
  function reactionTarget(messages, id, group) {
22117
22457
  return messages.find((m) => replyRef(m, group) === id);
@@ -22186,6 +22526,8 @@ var Reactions = class {
22186
22526
  * out. It only has to grow, so a row deleted since leaves it too high and nothing is wrong.
22187
22527
  */
22188
22528
  last = /* @__PURE__ */ new Map();
22529
+ /** Per 1:1 chat: when it was last read whole for a received reaction, and the read of those that waited meanwhile. */
22530
+ lookups = /* @__PURE__ */ new Map();
22189
22531
  constructor(host) {
22190
22532
  this.host = host;
22191
22533
  }
@@ -22243,7 +22585,7 @@ var Reactions = class {
22243
22585
  }
22244
22586
  take(chat, by, reaction) {
22245
22587
  return this.run(async () => {
22246
- const target = await this.find(chat, reaction.id);
22588
+ const target = await this.find(chat, reaction.id, true);
22247
22589
  if (!target) return this.wait(chat, by, reaction);
22248
22590
  if (!reactionIsNewer(target.reactions?.[by], reaction.n)) return "stale";
22249
22591
  await this.write(chat, target, by, reaction);
@@ -22310,6 +22652,8 @@ var Reactions = class {
22310
22652
  stop() {
22311
22653
  this.stopped = true;
22312
22654
  this.dropHeld();
22655
+ for (const state of this.lookups.values()) clearTimeout(state.timer);
22656
+ this.lookups.clear();
22313
22657
  }
22314
22658
  dropHeld(chat) {
22315
22659
  for (const [key, timer] of this.heldTimers) if (chat === void 0 || key.startsWith(`${chat}\n`)) {
@@ -22341,9 +22685,11 @@ var Reactions = class {
22341
22685
  /**
22342
22686
  * The row a received reaction names. Most often the row of that id (a group's), or of `peer_` or `me_` and that id (a
22343
22687
  * chat's): those are read alone. Any other (a file's, a payment's, one not here yet) is looked for in the whole chat;
22344
- * in a group there is no other, since a row that takes a reaction goes by its own id there.
22688
+ * in a group there is no other, since a row that takes a reaction goes by its own id there. A `received` one is looked
22689
+ * for so at most once a `REACTION_LOOKUP_MS` per chat, since the contact can name ids that never were: one that comes
22690
+ * meanwhile waits, and the next read finds what waited (`lookUpWaiting`).
22345
22691
  */
22346
- async find(chat, id) {
22692
+ async find(chat, id, received = false) {
22347
22693
  const group = isGroup$1(chat);
22348
22694
  if (this.host.message) {
22349
22695
  for (const rowId of group ? [id] : [`peer_${id}`, `me_${id}`]) {
@@ -22351,14 +22697,54 @@ var Reactions = class {
22351
22697
  if (row && replyRef(row, group) === id) return row;
22352
22698
  }
22353
22699
  if (group) return void 0;
22700
+ if (received && !this.lookupDue(chat)) return void 0;
22354
22701
  }
22355
22702
  return reactionTarget(await this.host.messages(chat), id, group);
22356
22703
  }
22704
+ /** Whether a received reaction may read the chat whole now; if not, a read of those that wait is due when it may. */
22705
+ lookupDue(chat) {
22706
+ const now = this.now();
22707
+ let state = this.lookups.get(chat);
22708
+ if (!state) this.lookups.set(chat, state = { at: -Infinity });
22709
+ if (now - state.at >= 1e4) {
22710
+ state.at = now;
22711
+ return true;
22712
+ }
22713
+ if (!state.timer && !this.stopped) {
22714
+ const due = state;
22715
+ due.timer = setTimeout(() => {
22716
+ due.timer = void 0;
22717
+ this.lookUpWaiting(chat, due).catch(() => {});
22718
+ }, due.at + REACTION_LOOKUP_MS - now);
22719
+ }
22720
+ return false;
22721
+ }
22722
+ /** The chat read whole once for the reactions that wait in it: those whose row it has land, newest last. */
22723
+ lookUpWaiting(chat, due) {
22724
+ return this.run(async () => {
22725
+ const now = this.now(), list = (this.waiting.get(chat) ?? []).filter((w) => w.until > now);
22726
+ if (this.stopped || this.lookups.get(chat) !== due || !list.length) return;
22727
+ due.at = now;
22728
+ const messages = await this.host.messages(chat);
22729
+ const found = list.flatMap((w) => {
22730
+ const target = reactionTarget(messages, w.reaction.id, false);
22731
+ return target ? [{
22732
+ ...w,
22733
+ target
22734
+ }] : [];
22735
+ });
22736
+ if (!found.length) return;
22737
+ this.waiting.set(chat, list.filter((w) => !found.some((f) => f.by === w.by && f.reaction === w.reaction)));
22738
+ for (const { target, by, reaction } of found.sort((a, b) => a.reaction.n - b.reaction.n)) await this.write(chat, target, by, reaction);
22739
+ });
22740
+ }
22357
22741
  /** A chat is gone: nothing waits for it any more, and my highest number in it is read again if it comes back. */
22358
22742
  forget(chat) {
22359
22743
  this.dropHeld(chat);
22360
22744
  this.waiting.delete(chat);
22361
22745
  this.last.delete(chat);
22746
+ clearTimeout(this.lookups.get(chat)?.timer);
22747
+ this.lookups.delete(chat);
22362
22748
  }
22363
22749
  wait(chat, by, reaction) {
22364
22750
  const now = this.now();
@@ -23063,76 +23449,82 @@ var Communities = class {
23063
23449
  return this.stored.get(groupId);
23064
23450
  }
23065
23451
  views() {
23066
- return [...this.stored.values()].flatMap((group) => {
23067
- const live = this.live.get(group.id);
23068
- const base = {
23069
- id: group.id,
23070
- profile: "community",
23071
- createdAt: group.createdAt,
23072
- lastMessageAt: this.lastMessageAt.get(group.id) ?? 0,
23073
- ...peerMessageAt(this.lastPeerMessageAt, group.id),
23074
- ...mentionAt(this.lastMentionAt, group.id),
23075
- invited: [],
23076
- memberLinks: {}
23077
- };
23078
- const invitation = this.knocking(group, live) ? {
23079
- linkId: group.joining.linkId,
23080
- contact: "",
23081
- admin: group.joining.inviter,
23082
- members: 0,
23083
- accepted: true,
23084
- viaLink: true,
23085
- stage: this.joinStage(group),
23086
- since: group.joining.since,
23087
- ...this.knockingWith.get(group.id) ? { waiting: this.knockingWith.get(group.id) } : {}
23088
- } : void 0;
23089
- if (invitation && !this.keptWhileKnocking(live)) return [{
23090
- ...base,
23091
- name: groupName(group.joining.name) ?? live?.session.name ?? "",
23092
- isAdmin: false,
23093
- members: [],
23094
- canSend: false,
23095
- invitation
23096
- }];
23097
- if (!live) return [];
23098
- const s = live.session, edges = this.host.edges(group.id);
23099
- const ready = (key) => {
23100
- const id = edges.get(key);
23101
- return !!id && this.host.linkReady(id, 2);
23102
- };
23103
- const hubs = freshHubs(this.hubs(live), this.now()).map((h) => h.key);
23104
- const former = Object.entries(s.state.nicks).filter(([key]) => !rosterHas(s.roster, key));
23105
- return [{
23106
- ...base,
23107
- name: s.name,
23108
- ...former.length ? { formerNames: Object.fromEntries(former) } : {},
23109
- status: s.status,
23110
- statusReason: s.state.statusReason,
23111
- epoch: s.epoch,
23112
- myKey: s.myKey,
23113
- isAdmin: s.isAdmin,
23114
- ...s.isMember && s.entryKey ? { entryLink: encodeCommunityLink({
23115
- g: s.id,
23116
- host: s.entryKey
23117
- }) } : {},
23118
- canSend: s.canSend,
23119
- ...s.picture ? { picture: s.picture } : {},
23120
- ...invitation ? { invitation } : {},
23121
- community: {
23122
- hub: live.hub,
23123
- hubs: hubs.length,
23124
- connected: [...edges.keys()].filter(ready).length
23125
- },
23126
- members: s.roster.map(([key, role]) => ({
23127
- key,
23128
- role,
23129
- me: key === s.myKey,
23130
- nick: key === s.myKey ? void 0 : edges.get(key) && this.host.edgeNick(edges.get(key)) || s.state.nicks[key],
23131
- online: key === s.myKey || ready(key),
23132
- missing: s.missing(key)
23133
- }))
23134
- }];
23135
- });
23452
+ return [...this.stored.values()].flatMap((group) => this.viewOf(group));
23453
+ }
23454
+ /** One community's view, as `views()` makes it, without building the others' (`Groups.view`). */
23455
+ view(groupId) {
23456
+ const group = this.stored.get(groupId);
23457
+ return group && this.viewOf(group)[0];
23458
+ }
23459
+ viewOf(group) {
23460
+ const live = this.live.get(group.id);
23461
+ const base = {
23462
+ id: group.id,
23463
+ profile: "community",
23464
+ createdAt: group.createdAt,
23465
+ lastMessageAt: this.lastMessageAt.get(group.id) ?? 0,
23466
+ ...peerMessageAt(this.lastPeerMessageAt, group.id),
23467
+ ...mentionAt(this.lastMentionAt, group.id),
23468
+ invited: [],
23469
+ memberLinks: {}
23470
+ };
23471
+ const invitation = this.knocking(group, live) ? {
23472
+ linkId: group.joining.linkId,
23473
+ contact: "",
23474
+ admin: group.joining.inviter,
23475
+ members: 0,
23476
+ accepted: true,
23477
+ viaLink: true,
23478
+ stage: this.joinStage(group),
23479
+ since: group.joining.since,
23480
+ ...this.knockingWith.get(group.id) ? { waiting: this.knockingWith.get(group.id) } : {}
23481
+ } : void 0;
23482
+ if (invitation && !this.keptWhileKnocking(live)) return [{
23483
+ ...base,
23484
+ name: groupName(group.joining.name) ?? live?.session.name ?? "",
23485
+ isAdmin: false,
23486
+ members: [],
23487
+ canSend: false,
23488
+ invitation
23489
+ }];
23490
+ if (!live) return [];
23491
+ const s = live.session, edges = this.host.edges(group.id);
23492
+ const ready = (key) => {
23493
+ const id = edges.get(key);
23494
+ return !!id && this.host.linkReady(id, 2);
23495
+ };
23496
+ const hubs = freshHubs(this.hubs(live), this.now()).map((h) => h.key);
23497
+ const former = Object.entries(s.state.nicks).filter(([key]) => !rosterHas(s.roster, key));
23498
+ return [{
23499
+ ...base,
23500
+ name: s.name,
23501
+ ...former.length ? { formerNames: Object.fromEntries(former) } : {},
23502
+ status: s.status,
23503
+ statusReason: s.state.statusReason,
23504
+ epoch: s.epoch,
23505
+ myKey: s.myKey,
23506
+ isAdmin: s.isAdmin,
23507
+ ...s.isMember && s.entryKey ? { entryLink: encodeCommunityLink({
23508
+ g: s.id,
23509
+ host: s.entryKey
23510
+ }) } : {},
23511
+ canSend: s.canSend,
23512
+ ...s.picture ? { picture: s.picture } : {},
23513
+ ...invitation ? { invitation } : {},
23514
+ community: {
23515
+ hub: live.hub,
23516
+ hubs: hubs.length,
23517
+ connected: [...edges.keys()].filter(ready).length
23518
+ },
23519
+ members: s.roster.map(([key, role]) => ({
23520
+ key,
23521
+ role,
23522
+ me: key === s.myKey,
23523
+ nick: key === s.myKey ? void 0 : edges.get(key) && this.host.edgeNick(edges.get(key)) || s.state.nicks[key],
23524
+ online: key === s.myKey || ready(key),
23525
+ missing: s.missing(key)
23526
+ }))
23527
+ }];
23136
23528
  }
23137
23529
  messages(groupId) {
23138
23530
  return this.store.getMessages(MESSAGE_LINK$1(groupId));
@@ -23278,7 +23670,8 @@ var Communities = class {
23278
23670
  ts: edit.ts,
23279
23671
  text: edit.m,
23280
23672
  mentions: edit.k,
23281
- ...edit.sc && { card: edit.sc }
23673
+ ...edit.sc && { card: edit.sc },
23674
+ ...edit.rm && { remove: true }
23282
23675
  }, this.host.myNick?.(), this.now());
23283
23676
  if ("error" in result) return result.error;
23284
23677
  const key = editKey(edit.id, edit.e);
@@ -24536,6 +24929,7 @@ var Communities = class {
24536
24929
  const file = m.file && this.files ? await this.files.announced(id, {
24537
24930
  id: m.id,
24538
24931
  sender: m.sender,
24932
+ ts: m.timestamp,
24539
24933
  file: m.file
24540
24934
  }, session.myKey) : void 0;
24541
24935
  const placing = this.lineOrder.placing(MESSAGE_LINK$1(id), {
@@ -26028,92 +26422,103 @@ var Groups = class {
26028
26422
  return this.isCommunity(groupId) ? this.communities.record(groupId) : this.stored.get(groupId);
26029
26423
  }
26030
26424
  views() {
26031
- return [...this.meshViews(), ...this.communities.views()].map((view) => {
26032
- const pin = pinView(this.record(view.id)?.pin);
26033
- return pin ? {
26034
- ...view,
26035
- pin
26036
- } : view;
26037
- }).sort((a, b) => Math.max(b.lastMessageAt, b.createdAt) - Math.max(a.lastMessageAt, a.createdAt));
26425
+ return [...this.meshViews(), ...this.communities.views()].map((view) => this.pinned(view)).sort((a, b) => Math.max(b.lastMessageAt, b.createdAt) - Math.max(a.lastMessageAt, a.createdAt));
26426
+ }
26427
+ /**
26428
+ * One group's view, as `views()` makes it, without building every other group's: the engine's native-listener
26429
+ * decisions read it per edge, and all groups' views per edge grew with groups × members squared.
26430
+ */
26431
+ view(groupId) {
26432
+ const view = this.isCommunity(groupId) ? this.communities.view(groupId) : this.meshView(this.stored.get(groupId));
26433
+ return view && this.pinned(view);
26434
+ }
26435
+ pinned(view) {
26436
+ const pin = pinView(this.record(view.id)?.pin);
26437
+ return pin ? {
26438
+ ...view,
26439
+ pin
26440
+ } : view;
26038
26441
  }
26039
26442
  meshViews() {
26040
- return [...this.stored.values()].filter((group) => !group.left && (group.invitation || this.sessions.has(group.id))).map((group) => {
26041
- const session = this.sessions.get(group.id);
26042
- const edges = this.host.edges(group.id);
26043
- const contacts = Object.entries(group.contacts ?? {}).filter(([key]) => !session || rosterHas(session.roster, key));
26044
- const base = {
26045
- id: group.id,
26046
- profile: "mesh",
26047
- createdAt: group.createdAt,
26048
- lastMessageAt: this.lastMessageAt.get(group.id) ?? 0,
26049
- ...peerMessageAt(this.lastPeerMessageAt, group.id),
26050
- ...mentionAt(this.lastMentionAt, group.id),
26051
- invited: [...this.invited.get(group.id) ?? []],
26052
- memberLinks: Object.fromEntries(contacts.map(([key, linkId]) => [linkId, key]))
26053
- };
26054
- if (!session) {
26055
- const invitation = group.invitation;
26056
- return {
26057
- ...base,
26058
- name: groupName(invitation.name) ?? "",
26059
- isAdmin: false,
26060
- members: [],
26061
- canSend: false,
26062
- ...group.formerNames ? { formerNames: group.formerNames } : {},
26063
- invitation: {
26064
- linkId: invitation.linkId,
26065
- contact: this.host.contactName(invitation.linkId) ?? "",
26066
- admin: invitation.admin,
26067
- members: Math.min(Math.max(invitation.n, 0), GROUP_MEMBER_CAP.max),
26068
- accepted: !!invitation.seedB64,
26069
- ...this.acceptSaid.get(group.id)?.unanswered ? { unanswered: true } : {},
26070
- ...invitation.takenBack ? { takenBack: true } : {},
26071
- ...invitation.entry ? {
26072
- viaLink: true,
26073
- stage: this.joinStage(group)
26074
- } : {}
26075
- }
26076
- };
26077
- }
26078
- const nicks = session.state.nicks;
26079
- const entry = session.isAdmin ? this.entryOf(group) : void 0;
26080
- const now = this.now(), onHubs = this.hubs.active(group.id, session, now);
26081
- const hubKeys = new Set(onHubs ? this.hubs.hubs(group.id, session, now) : []), policy = session.hubPolicy;
26082
- if (onHubs && this.hubs.isHub(group.id)) hubKeys.add(session.myKey);
26083
- const typing = this.typings.view(session);
26084
- const former = Object.entries(nicks).filter(([key]) => !rosterHas(session.roster, key));
26443
+ return [...this.stored.values()].flatMap((group) => this.meshView(group) ?? []);
26444
+ }
26445
+ meshView(group) {
26446
+ if (!group || group.left || !(group.invitation || this.sessions.has(group.id))) return void 0;
26447
+ const session = this.sessions.get(group.id);
26448
+ const edges = this.host.edges(group.id);
26449
+ const contacts = Object.entries(group.contacts ?? {}).filter(([key]) => !session || rosterHas(session.roster, key));
26450
+ const base = {
26451
+ id: group.id,
26452
+ profile: "mesh",
26453
+ createdAt: group.createdAt,
26454
+ lastMessageAt: this.lastMessageAt.get(group.id) ?? 0,
26455
+ ...peerMessageAt(this.lastPeerMessageAt, group.id),
26456
+ ...mentionAt(this.lastMentionAt, group.id),
26457
+ invited: [...this.invited.get(group.id) ?? []],
26458
+ memberLinks: Object.fromEntries(contacts.map(([key, linkId]) => [linkId, key]))
26459
+ };
26460
+ if (!session) {
26461
+ const invitation = group.invitation;
26085
26462
  return {
26086
26463
  ...base,
26087
- name: session.name,
26088
- ...former.length ? { formerNames: Object.fromEntries(former) } : {},
26089
- status: session.status,
26090
- statusReason: session.state.statusReason,
26091
- epoch: session.epoch,
26092
- myKey: session.myKey,
26093
- isAdmin: session.isAdmin,
26094
- ...entry ? { entryLink: encodeGroupEntryLink(entry.link) } : {},
26095
- ...session.picture ? { picture: session.picture } : {},
26096
- canSend: session.status === "active" && session.readableEpochs.includes(session.epoch),
26097
- ...onHubs ? { hubs: { hub: this.hubs.isHub(group.id) } } : {},
26098
- ...typing ? { typing } : {},
26099
- members: session.roster.map(([key, role]) => {
26100
- const edge = edges.get(key);
26101
- const direct = key === session.myKey || !!edge && this.host.linkReady(edge), viaHub = !direct && onHubs && this.hubs.viaHub(group.id, session, key, now);
26102
- const hubRole = policy.pin.includes(key) ? "pin" : policy.no.includes(key) ? "exclude" : void 0;
26103
- return {
26104
- key,
26105
- role,
26106
- me: key === session.myKey,
26107
- nick: key === session.myKey ? void 0 : edge && this.host.edgeNick(edge) || nicks[key],
26108
- online: direct || viaHub,
26109
- ...viaHub ? { viaHub } : {},
26110
- ...hubKeys.has(key) ? { hub: true } : {},
26111
- ...hubRole ? { hubRole } : {},
26112
- missing: session.missing(key, this.gapsGone.get(group.id)?.get(key)?.[session.epoch])
26113
- };
26114
- })
26464
+ name: groupName(invitation.name) ?? "",
26465
+ isAdmin: false,
26466
+ members: [],
26467
+ canSend: false,
26468
+ ...group.formerNames ? { formerNames: group.formerNames } : {},
26469
+ invitation: {
26470
+ linkId: invitation.linkId,
26471
+ contact: this.host.contactName(invitation.linkId) ?? "",
26472
+ admin: invitation.admin,
26473
+ members: Math.min(Math.max(invitation.n, 0), GROUP_MEMBER_CAP.max),
26474
+ accepted: !!invitation.seedB64,
26475
+ ...this.acceptSaid.get(group.id)?.unanswered ? { unanswered: true } : {},
26476
+ ...invitation.takenBack ? { takenBack: true } : {},
26477
+ ...invitation.entry ? {
26478
+ viaLink: true,
26479
+ stage: this.joinStage(group)
26480
+ } : {}
26481
+ }
26115
26482
  };
26116
- }).sort((a, b) => Math.max(b.lastMessageAt, b.createdAt) - Math.max(a.lastMessageAt, a.createdAt));
26483
+ }
26484
+ const nicks = session.state.nicks;
26485
+ const entry = session.isAdmin ? this.entryOf(group) : void 0;
26486
+ const now = this.now(), onHubs = this.hubs.active(group.id, session, now);
26487
+ const hubKeys = new Set(onHubs ? this.hubs.hubs(group.id, session, now) : []), policy = session.hubPolicy;
26488
+ if (onHubs && this.hubs.isHub(group.id)) hubKeys.add(session.myKey);
26489
+ const typing = this.typings.view(session);
26490
+ const former = Object.entries(nicks).filter(([key]) => !rosterHas(session.roster, key));
26491
+ return {
26492
+ ...base,
26493
+ name: session.name,
26494
+ ...former.length ? { formerNames: Object.fromEntries(former) } : {},
26495
+ status: session.status,
26496
+ statusReason: session.state.statusReason,
26497
+ epoch: session.epoch,
26498
+ myKey: session.myKey,
26499
+ isAdmin: session.isAdmin,
26500
+ ...entry ? { entryLink: encodeGroupEntryLink(entry.link) } : {},
26501
+ ...session.picture ? { picture: session.picture } : {},
26502
+ canSend: session.status === "active" && session.readableEpochs.includes(session.epoch),
26503
+ ...onHubs ? { hubs: { hub: this.hubs.isHub(group.id) } } : {},
26504
+ ...typing ? { typing } : {},
26505
+ members: session.roster.map(([key, role]) => {
26506
+ const edge = edges.get(key);
26507
+ const direct = key === session.myKey || !!edge && this.host.linkReady(edge), viaHub = !direct && onHubs && this.hubs.viaHub(group.id, session, key, now);
26508
+ const hubRole = policy.pin.includes(key) ? "pin" : policy.no.includes(key) ? "exclude" : void 0;
26509
+ return {
26510
+ key,
26511
+ role,
26512
+ me: key === session.myKey,
26513
+ nick: key === session.myKey ? void 0 : edge && this.host.edgeNick(edge) || nicks[key],
26514
+ online: direct || viaHub,
26515
+ ...viaHub ? { viaHub } : {},
26516
+ ...hubKeys.has(key) ? { hub: true } : {},
26517
+ ...hubRole ? { hubRole } : {},
26518
+ missing: session.missing(key, this.gapsGone.get(group.id)?.get(key)?.[session.epoch])
26519
+ };
26520
+ })
26521
+ };
26117
26522
  }
26118
26523
  messages(groupId) {
26119
26524
  return this.store.getMessages(MESSAGE_LINK(groupId));
@@ -26168,7 +26573,8 @@ var Groups = class {
26168
26573
  ts: edit.ts,
26169
26574
  text: edit.m,
26170
26575
  mentions: edit.k,
26171
- ...edit.sc && { card: edit.sc }
26576
+ ...edit.sc && { card: edit.sc },
26577
+ ...edit.rm && { remove: true }
26172
26578
  }, to);
26173
26579
  return "error" in result ? result.error : null;
26174
26580
  }
@@ -26434,7 +26840,7 @@ var Groups = class {
26434
26840
  me: session.myKey,
26435
26841
  community: false,
26436
26842
  inRoster: (key) => rosterHas(session.roster, key),
26437
- couldRead: (key, messageId) => session.couldRead(key, messageId)
26843
+ couldRead: (key, messageId, ts) => session.couldRead(key, messageId, ts)
26438
26844
  };
26439
26845
  }
26440
26846
  /**
@@ -26619,6 +27025,33 @@ var Groups = class {
26619
27025
  const commit = frame && typeof frame === "object" && frame.t === "group-commit" ? frame.commit : void 0;
26620
27026
  return typeof commit?.e === "number" && commit.e <= removalEpoch(session.state.chain, key);
26621
27027
  }
27028
+ /** My removals on their way in a group (`engine/removals.ts`), a private group's or a community's. */
27029
+ removals(groupId) {
27030
+ return this.record(groupId)?.removals ?? [];
27031
+ }
27032
+ async setRemovals(groupId, removals) {
27033
+ const group = this.record(groupId);
27034
+ if (!group) return;
27035
+ group.removals = removals;
27036
+ await this.store.putGroup(group);
27037
+ }
27038
+ /** A member's message its author deleted for everyone (WISP 400 § Delete for everyone): a copy that comes again is not kept. */
27039
+ isRemoved(groupId, messageId) {
27040
+ return !!this.record(groupId)?.removedIds?.includes(messageId);
27041
+ }
27042
+ /**
27043
+ * Its author deleted a message for everyone: noted so (the newest `MAX_REMOVED_IDS`, also when the message is not here
27044
+ * yet, so it is taken as gone when it comes), and its file goes from this device.
27045
+ */
27046
+ async removed(groupId, messageId) {
27047
+ const group = this.record(groupId);
27048
+ if (!group) return;
27049
+ if (!group.removedIds?.includes(messageId)) {
27050
+ group.removedIds = [...group.removedIds ?? [], messageId].slice(-500);
27051
+ await this.store.putGroup(group);
27052
+ }
27053
+ await this.files?.forget(groupId, messageId);
27054
+ }
26622
27055
  /** 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. */
26623
27056
  edgeOpen(groupId, peerKey) {
26624
27057
  const group = this.stored.get(groupId), farewell = group?.farewells?.[peerKey];
@@ -28101,6 +28534,7 @@ var Groups = class {
28101
28534
  const file = m.file && this.files ? await this.files.announced(state.id, {
28102
28535
  id: m.id,
28103
28536
  sender: m.sender,
28537
+ ts: m.timestamp,
28104
28538
  file: m.file
28105
28539
  }, session.myKey) : void 0;
28106
28540
  const message = {
@@ -28642,6 +29076,21 @@ var GROUP_EDIT_RESEND_WINDOW_MS = EDIT_RATE_WINDOW_MS + 1e3;
28642
29076
  /** An edit that could not go (no epoch key yet) is tried again after this long. */
28643
29077
  var RETRY_MS = 1e4;
28644
29078
  var chatOf = (groupId) => `group:${groupId}`;
29079
+ /** What a row of mine says to the group as its latest edit: a removal its fallback text alone (WISP 400 § Delete for everyone). */
29080
+ var said = (m) => m.removed ? {
29081
+ id: m.id,
29082
+ e: m.edit.seq,
29083
+ ts: m.edit.at,
29084
+ m: m.text,
29085
+ rm: true
29086
+ } : {
29087
+ id: m.id,
29088
+ e: m.edit.seq,
29089
+ ts: m.edit.at,
29090
+ m: m.text,
29091
+ ...m.mentions?.length && { k: m.mentions },
29092
+ ...m.card && { sc: m.card }
29093
+ };
28645
29094
  var resendKey = (groupId, member) => `${groupId}\n${member}`;
28646
29095
  var GroupEdits = class {
28647
29096
  host;
@@ -28732,6 +29181,34 @@ var GroupEdits = class {
28732
29181
  messageId
28733
29182
  };
28734
29183
  }
29184
+ /**
29185
+ * Deletes a message of mine for everyone (WISP 400 § Delete for everyone): gone here at once, and its removal said to
29186
+ * 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
29187
+ * payment, a note or an event line.
29188
+ */
29189
+ async removeMine(groupId, messageId) {
29190
+ const refuse = (error) => ({
29191
+ error,
29192
+ refused: true
29193
+ });
29194
+ if (!this.host.membership(groupId)) return refuse("You are not in this group");
29195
+ const chat = chatOf(groupId);
29196
+ const message = typeof messageId === "string" ? await this.find(chat, messageId) : void 0;
29197
+ if (!message || message.removed || message.sender !== "me" || !GROUP_MESSAGE_ID.test(message.id)) return refuse("Only your own messages can be deleted for everyone");
29198
+ if (!canRemove(message)) return refuse("A payment, a request or a notice cannot be deleted for everyone");
29199
+ await this.host.removeMine(chat, message, {
29200
+ id: message.id,
29201
+ e: removalNumber(message.edit?.seq),
29202
+ at: this.now(),
29203
+ pending: true
29204
+ });
29205
+ if (this.host.message) this.told(groupId).set(messageId, ++this.tick);
29206
+ await this.flush(groupId).catch(() => {});
29207
+ return {
29208
+ error: null,
29209
+ messageId
29210
+ };
29211
+ }
28735
29212
  /** Says my pending edits in a group, oldest first, at the pace allowed; what waits goes when the window has room. */
28736
29213
  flush(groupId) {
28737
29214
  const running = this.flushing.get(groupId);
@@ -28759,14 +29236,7 @@ var GroupEdits = class {
28759
29236
  retry = Math.min(retry, pace.wait());
28760
29237
  break;
28761
29238
  }
28762
- if (await this.host.send(groupId, {
28763
- id: message.id,
28764
- e: edit.seq,
28765
- ts: edit.at,
28766
- m: message.text,
28767
- ...message.mentions?.length && { k: message.mentions },
28768
- ...message.card && { sc: message.card }
28769
- })) {
29239
+ if (await this.host.send(groupId, said(message))) {
28770
29240
  retry = Math.min(retry, RETRY_MS);
28771
29241
  continue;
28772
29242
  }
@@ -28886,6 +29356,11 @@ var GroupEdits = class {
28886
29356
  async take(groupId, membership, sender, edit) {
28887
29357
  const chat = chatOf(groupId);
28888
29358
  const message = await this.find(chat, edit.id);
29359
+ if (edit.rm) {
29360
+ if (message && (message.sender !== "peer" || message.member !== sender || !canRemove(message))) return "dropped";
29361
+ await this.host.remove(chat, edit.id);
29362
+ return "applied";
29363
+ }
28889
29364
  if (!message) {
28890
29365
  this.buffer.hold(chat, {
28891
29366
  ...edit,
@@ -28972,14 +29447,7 @@ var GroupEdits = class {
28972
29447
  }, Math.max(50, pace.wait())));
28973
29448
  return;
28974
29449
  }
28975
- await this.host.send(groupId, {
28976
- id: m.id,
28977
- e: m.edit.seq,
28978
- ts: m.edit.at,
28979
- m: m.text,
28980
- ...m.mentions?.length && { k: m.mentions },
28981
- ...m.card && { sc: m.card }
28982
- }, to);
29450
+ await this.host.send(groupId, said(m), to);
28983
29451
  if (open() !== edge) return;
28984
29452
  if (after(m)) this.heard.set(key, {
28985
29453
  at: m.edit.at,
@@ -32894,6 +33362,8 @@ var UNIT = "sat";
32894
33362
  /** A contact's requests in one chat: the new ones taken per minute, and how many may wait to be paid. */
32895
33363
  var REQUESTS_PER_MINUTE = 20;
32896
33364
  var OPEN_REQUESTS = 50;
33365
+ var INVOICE_CLAIMS_KEY = "invoicePaidClaims";
33366
+ var sameClaim = (a, b) => a.linkId === b.linkId && a.invoice.toLowerCase() === b.invoice.toLowerCase();
32897
33367
  var satsWord = (n) => `${n} sat${n === 1 ? "" : "s"}`;
32898
33368
  /**
32899
33369
  * A refused send's review, once its ecash came back: why, and exactly what came back. Taking ecash back is a swap at
@@ -33056,6 +33526,8 @@ var PaymentDesk = class {
33056
33526
  async start() {
33057
33527
  const stored = await wrap((await store(STORES$1.payments, "readonly")).getAll());
33058
33528
  for (const payment of stored) this.payments.set(payment.id, payment);
33529
+ const claims = await wrap((await store(STORES$1.settings, "readonly")).get(INVOICE_CLAIMS_KEY));
33530
+ this.claims = [...(claims ?? []).filter((c) => !this.claims.some((d) => sameClaim(c, d))), ...this.claims];
33059
33531
  }
33060
33532
  /** Every payment as stored, tokens included: for the engine's own reading, never for a page. */
33061
33533
  records() {
@@ -33072,6 +33544,7 @@ var PaymentDesk = class {
33072
33544
  this.payments.delete(payment.id);
33073
33545
  wrap(paymentStore.delete(payment.id));
33074
33546
  }
33547
+ if (this.claims.some((c) => c.linkId === linkId)) this.keepClaims(this.claims.filter((c) => c.linkId !== linkId));
33075
33548
  this.requestsFrom.delete(linkId);
33076
33549
  }
33077
33550
  /** `confirmedReal`: the person confirmed a Mainnet send as real money; without it one is refused. */
@@ -33582,22 +34055,61 @@ var PaymentDesk = class {
33582
34055
  }
33583
34056
  /**
33584
34057
  * A Testnet invoice found in a chat message, paid from its card: the chat's contact is told as `sayPaid` does, with
33585
- * no request (it may be one from their Receive screen, held until a payer says it paid).
34058
+ * no request (it may be one from their Receive screen, held until a payer says it paid). Kept until it gets through
34059
+ * (`InvoiceClaim`); `pending`: the payment has not settled yet, and it is said once it does.
33586
34060
  */
33587
- sayInvoicePaid(linkId, invoice) {
33588
- const link = this.host.getLink(linkId);
33589
- const amount = decodeBolt11(invoice)?.amountSat;
34061
+ sayInvoicePaid(linkId, invoice, { pending } = {}) {
34062
+ const decoded = decodeBolt11(invoice);
34063
+ if (!decoded?.amountSat) return;
34064
+ const claim = {
34065
+ linkId,
34066
+ invoice: invoice.trim(),
34067
+ ...pending ? { pending } : {},
34068
+ expiresAt: (decoded.expiresAt + 60) * 1e3
34069
+ };
34070
+ this.keepClaims([...this.claims.filter((c) => !sameClaim(c, claim)), claim]).then(() => pending ? void 0 : this.tellClaim(claim));
34071
+ }
34072
+ claims = [];
34073
+ claimWrites = Promise.resolve();
34074
+ /** Says one `InvoiceClaim`, and forgets it once it went out; one that did not is said again when the chat is up. */
34075
+ async tellClaim(claim) {
34076
+ const link = this.host.getLink(claim.linkId);
34077
+ const amount = decodeBolt11(claim.invoice)?.amountSat;
33590
34078
  if (!link || !amount) return;
33591
- this.sendTo(link, {
33592
- id: newId(),
33593
- timestamp: Date.now(),
33594
- amount: {
33595
- value: String(amount),
33596
- asset: UNIT
33597
- },
33598
- endpoint: [ENDPOINT.bolt11, invoice.trim()]
34079
+ try {
34080
+ await this.sendTo(link, {
34081
+ id: newId(),
34082
+ timestamp: Date.now(),
34083
+ amount: {
34084
+ value: String(amount),
34085
+ asset: UNIT
34086
+ },
34087
+ endpoint: [ENDPOINT.bolt11, claim.invoice]
34088
+ });
34089
+ } catch {
34090
+ return;
34091
+ }
34092
+ await this.keepClaims(this.claims.filter((c) => c.pending || !sameClaim(c, claim)));
34093
+ }
34094
+ /** The claims from now on, expired ones left out, written in the order they were made. */
34095
+ keepClaims(next) {
34096
+ const now = Date.now();
34097
+ const kept = this.claims = next.filter((c) => c.expiresAt > now);
34098
+ return this.claimWrites = this.claimWrites.then(async () => {
34099
+ await wrap((await store(STORES$1.settings, "readwrite")).put(kept, INVOICE_CLAIMS_KEY));
33599
34100
  }).catch(() => {});
33600
34101
  }
34102
+ /** A payment left pending ended: the chats whose invoice it paid are told now, and none when it failed. */
34103
+ settleClaims(invoice, paid) {
34104
+ const wanted = invoice?.trim().toLowerCase();
34105
+ const settled = wanted ? this.claims.filter((c) => c.pending && c.invoice.toLowerCase() === wanted) : [];
34106
+ if (!settled.length) return;
34107
+ const told = settled.map(({ pending: _pending, ...claim }) => claim);
34108
+ const rest = this.claims.filter((c) => !settled.includes(c) && !(paid && told.some((t) => sameClaim(c, t))));
34109
+ this.keepClaims(paid ? [...rest, ...told] : rest).then(() => {
34110
+ if (paid) for (const claim of told) this.tellClaim(claim);
34111
+ });
34112
+ }
33601
34113
  /**
33602
34114
  * Takes back ecash the peer never redeemed. If they did redeem it, the mint says so and the payment is settled.
33603
34115
  * Resolves to what came back of Cashu ecash (and the mint's fee for it); undefined when nothing did, or not Cashu.
@@ -34190,6 +34702,8 @@ var PaymentDesk = class {
34190
34702
  }
34191
34703
  lastCheck = /* @__PURE__ */ new Map();
34192
34704
  lastCheckFrom = /* @__PURE__ */ new Map();
34705
+ /** `receiveInvoicePaid`'s last look, by `<link id>:<invoice>`: only the last 3 seconds' are kept. */
34706
+ lastInvoiceCheck = /* @__PURE__ */ new Map();
34193
34707
  /**
34194
34708
  * "I paid it from another wallet": the contact's app is asked to look at its wallet now. Nothing here
34195
34709
  * marks anything paid; the request settles when the payee's wallet sees the money, with or without this.
@@ -34248,21 +34762,25 @@ var PaymentDesk = class {
34248
34762
  /**
34249
34763
  * The contact says it paid an invoice of ours it found in the chat, with no request: a Receive-screen invoice is
34250
34764
  * held on a test mint until then (StoredQuote `held`), and that one alone is let go. A request's invoice is spoken
34251
- * for by its own contact only (`receiveCheck`). Bounded: one look every 3 seconds per chat.
34765
+ * for by its own contact only (`receiveCheck`). Bounded: one look every 3 seconds per invoice of a chat, so two
34766
+ * invoices paid one right after the other are both let go.
34252
34767
  */
34253
34768
  async receiveInvoicePaid(linkId, link, invoice) {
34254
34769
  if (!link.allowsPayment("lightning")) return;
34255
34770
  const now = Date.now();
34256
- if (now - (this.lastCheckFrom.get(`chat:${linkId}`) ?? 0) < 3e3) return;
34257
- this.lastCheckFrom.set(`chat:${linkId}`, now);
34258
34771
  const wanted = invoice.trim().toLowerCase();
34772
+ const key = `${linkId}:${wanted}`;
34773
+ if (now - (this.lastInvoiceCheck.get(key) ?? 0) < 3e3) return;
34774
+ for (const [seen, at] of this.lastInvoiceCheck) if (now - at >= 3e3) this.lastInvoiceCheck.delete(seen);
34775
+ this.lastInvoiceCheck.set(key, now);
34259
34776
  try {
34260
34777
  const quote = (await this.wallet.quotes()).find((q) => q.held && !q.paymentId && q.invoice.toLowerCase() === wanted);
34261
34778
  if (quote) await this.wallet.vouch(quote.invoice);
34262
34779
  } catch {}
34263
34780
  }
34264
- /** A Lightning payment of a contact's request that was left pending (or unknown) settled. */
34781
+ /** A Lightning payment of a contact's request, or of a chat's invoice, that was left pending (or unknown) settled. */
34265
34782
  async onLightningResolved(op, paid) {
34783
+ this.settleClaims(op.invoice, paid);
34266
34784
  const found = op.paymentId ? this.payments.get(op.paymentId) : void 0;
34267
34785
  if (found?.kind !== "request" || found.direction !== "in") return;
34268
34786
  const request = {
@@ -35379,6 +35897,7 @@ var PaymentDesk = class {
35379
35897
  async replay(linkId) {
35380
35898
  const link = this.host.getLink(linkId);
35381
35899
  if (!link?.supportsPayments) return;
35900
+ for (const claim of this.claims) if (claim.linkId === linkId && !claim.pending && claim.expiresAt > Date.now()) await this.tellClaim(claim);
35382
35901
  const group = this.host.groupOf?.(linkId);
35383
35902
  if (group) for (const request of this.payments.values()) {
35384
35903
  if (request.group !== group || request.kind !== "request" || request.direction !== "out") continue;
@@ -35927,6 +36446,8 @@ var CARD_RESTORE_EVERY_MS = 3e4;
35927
36446
  var RTT_SAVE_MS = 3e5;
35928
36447
  /** A reaction said on the live session and not confirmed is said again after this long. */
35929
36448
  var REACTION_RESEND_MS = 3e4;
36449
+ /** When the contact's newest message over the DHT in these was sent (`LiveLink.pkarrSeenAt`). */
36450
+ var pkarrSeenAt = (messages) => messages.reduce((max, m) => m.sender === "peer" && m.via === "pkarr" ? Math.max(max, m.sentAt ?? m.timestamp) : max, 0);
35930
36451
  /** A file or a payment request of mine that waits for the chat to be live (a text that waits is its outbox's). */
35931
36452
  var waitsForLive = (m) => m.sender === "me" && m.delivery === "waiting" && (!!m.file || !!m.paymentId);
35932
36453
  /** This side's participation key in a chat: derived from its seed once, not at every state built. */
@@ -36260,6 +36781,11 @@ var GhostlyNode = class GhostlyNode {
36260
36781
  cardRestores = /* @__PURE__ */ new Map();
36261
36782
  /** The contacts' edits of messages not here yet. */
36262
36783
  editBuffer = new EditBuffer();
36784
+ /** Removals of messages, whose quotes are looked for at most once a while per chat (`forgetQuotes`). */
36785
+ quoteSweeps = new QuoteSweeps(async (chat, removed) => {
36786
+ const ids = await this.forgetQuotes(chat, removed);
36787
+ if (ids.length) await this.messagesChanged(chat, ids);
36788
+ });
36263
36789
  /** Received status card updates, applied at most once a second per message (WISP 405 · Status Cards). */
36264
36790
  cardEdits = new CardEditPacer();
36265
36791
  /** When each message's buttons were last pressed here (`pressButton`). */
@@ -37183,10 +37709,15 @@ var GhostlyNode = class GhostlyNode {
37183
37709
  * Never a new message: no sound, no unread.
37184
37710
  */
37185
37711
  groupEdits = new GroupEdits({
37186
- messages: (chat) => db.getMessages(chat),
37187
- history: (chat) => this.edgeOpenHistory(chat),
37188
- message: (chat, id) => db.getMessage(chat, id),
37189
- patch: (chat, id, change) => db.patchMessage(chat, id, change),
37712
+ messages: async (chat) => [...await db.getMessages(chat), ...this.groupRemovalRows(chat)],
37713
+ history: async (chat) => [...await this.edgeOpenHistory(chat), ...this.groupRemovalRows(chat)],
37714
+ message: async (chat, id) => this.groupRemovalRow(chat, id) ?? await db.getMessage(chat, id),
37715
+ patch: async (chat, id, change) => {
37716
+ const groupId = chat.slice(6), patched = patchRemoval(this.groups.removals(groupId), id, change, chat);
37717
+ if (!patched) return db.patchMessage(chat, id, change);
37718
+ await this.groups.setRemovals(groupId, patched.list);
37719
+ return patched.row;
37720
+ },
37190
37721
  changed: (chat, id) => this.messagesChanged(chat, [id]),
37191
37722
  membership: (groupId) => {
37192
37723
  const membership = this.membership(groupId);
@@ -37197,11 +37728,36 @@ var GhostlyNode = class GhostlyNode {
37197
37728
  };
37198
37729
  },
37199
37730
  send: (groupId, edit, to) => this.groups.sendEdit(groupId, edit, to),
37731
+ remove: (chat, id) => this.forgetGroupMessage(chat, id),
37732
+ removeMine: async (chat, message, removal) => {
37733
+ const groupId = chat.slice(6);
37734
+ await this.groups.setRemovals(groupId, withRemoval(this.groups.removals(groupId), removal));
37735
+ await this.forgetGroupMessage(chat, message.id);
37736
+ },
37200
37737
  edge: (groupId, member) => {
37201
37738
  const link = this.links.get(this.memberEdges(groupId).get(member) ?? "")?.link;
37202
37739
  return link?.supportsGroupVersion(1) ? link : void 0;
37203
37740
  }
37204
37741
  });
37742
+ /**
37743
+ * A group's message deleted for everyone, by its author or by me: gone from this device with its file, and noted so a
37744
+ * copy that comes again (a catch-up, a member handing it on) is not stored. The replies here that quote it lose its line.
37745
+ */
37746
+ async forgetGroupMessage(chat, id) {
37747
+ await this.groups.removed(chat.slice(6), id);
37748
+ await db.deleteMessage(chat, id);
37749
+ this.quoteSweeps.add(chat, id, id);
37750
+ await this.messagesChanged(chat, [id]);
37751
+ this.emitState();
37752
+ }
37753
+ groupRemovalRows(chat) {
37754
+ return this.groups.removals(chat.slice(6)).map((r) => removalRow(chat, r));
37755
+ }
37756
+ /** The row of one removal of mine in a group, by the message's id: none when it is not one. */
37757
+ groupRemovalRow(chat, id) {
37758
+ const removal = this.groups.removals(chat.slice(6)).find((r) => r.id === id);
37759
+ return removal && removalRow(chat, removal);
37760
+ }
37205
37761
  /** A community member's edit, signed by them: of their own message, and only while they are a member. */
37206
37762
  async receiveCommunityEdit(groupId, sender, frame) {
37207
37763
  const edit = parseCommunityEdit(frame, sender);
@@ -37382,14 +37938,15 @@ var GhostlyNode = class GhostlyNode {
37382
37938
  this.awaitingTimer = setTimeout(() => void this.readAwaiting().then((awaiting) => {
37383
37939
  const networks = this.walletView.networks;
37384
37940
  if (this.shuttingDown || !networks) return;
37385
- for (const network of WALLET_NETWORKS) networks[network] = {
37941
+ const next = { ...networks };
37942
+ for (const network of WALLET_NETWORKS) next[network] = {
37386
37943
  ...networks[network],
37387
37944
  mints: this.withWaits(networks[network].mints, awaiting.mints),
37388
37945
  awaiting: awaiting.networks[network]
37389
37946
  };
37390
37947
  this.walletView = {
37391
37948
  ...this.walletView,
37392
- networks: { ...networks }
37949
+ networks: next
37393
37950
  };
37394
37951
  this.emitState();
37395
37952
  }).catch(() => {}), 250);
@@ -37552,9 +38109,7 @@ var GhostlyNode = class GhostlyNode {
37552
38109
  await this.nostrSocial.load();
37553
38110
  await this.publicProfiles.load();
37554
38111
  if (!this.limitedMode) await this.startWallets();
37555
- const history = /* @__PURE__ */ new Map();
37556
38112
  const links = await db.getLinks();
37557
- for (const stored of links) history.set(stored.id, []);
37558
38113
  for (const stored of links) if (stored.group) this.links.set(stored.id, newLiveLink(stored, 0, linkFilesFrom(stored.id, [], [])));
37559
38114
  for (const group of await db.getGroups()) await this.settleHistory(`group:${group.id}`);
37560
38115
  await this.groups.load(this.limitedMode);
@@ -37576,7 +38131,7 @@ var GhostlyNode = class GhostlyNode {
37576
38131
  const files = linkFilesFrom(stored.id, storedFiles, messages);
37577
38132
  this.links.set(stored.id, newLiveLink(stored, messages[messages.length - 1]?.timestamp ?? 0, files));
37578
38133
  this.links.get(stored.id).waitingSends = Promise.resolve(new Set(messages.filter(waitsForLive).map((m) => m.id)));
37579
- history.set(stored.id, messages);
38134
+ this.links.get(stored.id).pkarrSeenAt = pkarrSeenAt(messages);
37580
38135
  for (const message of messages.slice(-20)) this.clockSample(message);
37581
38136
  const note = latestReaction(messages);
37582
38137
  if (note) this.reactionNotes.set(stored.id, note);
@@ -37588,15 +38143,9 @@ var GhostlyNode = class GhostlyNode {
37588
38143
  if (note) this.reactionNotes.set(`group:${group.id}`, note);
37589
38144
  }
37590
38145
  this.publicProfiles.start();
37591
- const pause = pacer(START_SLICE_MS);
37592
- if (this.networkOn) for (const linkId of this.nativeStartOrder([...history.keys()])) {
37593
- if (!this.networkOn || this.shuttingDown) break;
37594
- const messages = history.get(linkId);
37595
- if (!this.links.has(linkId)) continue;
37596
- this.startLink(linkId, messages);
38146
+ await this.startLinks(links.map((stored) => stored.id), (linkId) => {
37597
38147
  if (!this.links.get(linkId)?.stored.group) this.refreshPublicProfiles({ linkId }).catch(() => {});
37598
- await pause();
37599
- }
38148
+ });
37600
38149
  if (this.shuttingDown) return;
37601
38150
  this.emitState();
37602
38151
  if (this.networkOn) {
@@ -37841,7 +38390,7 @@ var GhostlyNode = class GhostlyNode {
37841
38390
  failure = error ?? /* @__PURE__ */ new Error("The wallets did not start");
37842
38391
  }
37843
38392
  if (this.networkOn) {
37844
- for (const live of this.links.values()) this.startLink(live.stored.id, await db.getMessages(live.stored.id));
38393
+ await this.startLinks([...this.links.keys()]);
37845
38394
  this.hold.start();
37846
38395
  this.startGroupEntries();
37847
38396
  this.prepareSpare(STARTUP_QUIET_MS);
@@ -38063,6 +38612,7 @@ var GhostlyNode = class GhostlyNode {
38063
38612
  for (const queue of this.editQueues.values()) queue.stop();
38064
38613
  for (const restore of this.cardRestores.values()) clearTimeout(restore.timer);
38065
38614
  this.cardRestores.clear();
38615
+ this.quoteSweeps.stop();
38066
38616
  this.groupEdits.stop();
38067
38617
  this.reactions.stop();
38068
38618
  this.cardEdits.stop();
@@ -38318,6 +38868,14 @@ var GhostlyNode = class GhostlyNode {
38318
38868
  before: from
38319
38869
  });
38320
38870
  }
38871
+ /** Saves a message on this device, or unsaves it (`engine/saved.ts`): nothing is sent. */
38872
+ saveMessage(params) {
38873
+ return this.saved.save(params);
38874
+ }
38875
+ /** This profile's saved messages, the last saved first, each as it is now. */
38876
+ savedMessages() {
38877
+ return this.saved.list();
38878
+ }
38321
38879
  async statusCardIndex() {
38322
38880
  const rows = [];
38323
38881
  for (const m of await db.getCardMessages()) {
@@ -39063,6 +39621,7 @@ var GhostlyNode = class GhostlyNode {
39063
39621
  this.editQueues.delete(linkId);
39064
39622
  clearTimeout(this.cardRestores.get(linkId)?.timer);
39065
39623
  this.cardRestores.delete(linkId);
39624
+ this.quoteSweeps.forget(linkId);
39066
39625
  this.editBuffer.forget(linkId);
39067
39626
  live.carried?.stop();
39068
39627
  this.links.delete(linkId);
@@ -39418,10 +39977,19 @@ var GhostlyNode = class GhostlyNode {
39418
39977
  static dhtByChoice(live) {
39419
39978
  return live?.stored.deliveryMode === "dht" || live?.link?.dhtDelivery?.peerMode === "dht";
39420
39979
  }
39421
- /** A status card a caller asks to send, by the sender's rule (WISP 405 · Status Cards), or why it cannot go. */
39422
- static cardToSend(raw) {
39980
+ /**
39981
+ * A status card a caller asks to send, by the sender's rule (WISP 405 · Status Cards), or why it cannot go. A removal
39982
+ * is only ever an edit of the card's own message (WISP 405 § Removing a card), never a message of its own.
39983
+ */
39984
+ static cardToSend(raw, edit = false) {
39423
39985
  const checked = checkStatusCard(raw);
39424
- return "error" in checked ? `Status card: ${checked.error}` : checked.card;
39986
+ if ("error" in checked) return `Status card: ${checked.error}`;
39987
+ if (checked.card.kind === "removed" && !edit) return "Status card: a removal is an edit of the card's message";
39988
+ return checked.card;
39989
+ }
39990
+ /** Whether a removal (WISP 405 § Removing a card) takes back the card this message of mine carries: its kind and id. */
39991
+ static removes(card, message) {
39992
+ return card.kind !== "removed" || message?.sender === "me" && message.card?.kind === card.of && message.card.id === card.id;
39425
39993
  }
39426
39994
  /**
39427
39995
  * A chat stopped by a security rejection (a stream authenticated a participation key other than the pinned one):
@@ -39442,13 +40010,15 @@ var GhostlyNode = class GhostlyNode {
39442
40010
  error,
39443
40011
  refused: true
39444
40012
  });
39445
- const card = params.card === void 0 ? void 0 : GhostlyNode.cardToSend(params.card);
40013
+ const card = params.card === void 0 ? void 0 : GhostlyNode.cardToSend(params.card, true);
39446
40014
  if (typeof card === "string") return refuse(card);
39447
40015
  if (card && !(typeof params.text === "string" && params.text.trim())) params = {
39448
40016
  ...params,
39449
40017
  text: statusCardText(card)
39450
40018
  };
40019
+ const notRemoved = "Status card: a removal takes back a task or routine of yours with that id, on its own message";
39451
40020
  if (typeof linkId === "string" && linkId.startsWith("group:")) {
40021
+ if (card && typeof params.messageId === "string" && !GhostlyNode.removes(card, await db.getMessage(linkId, params.messageId))) return refuse(notRemoved);
39452
40022
  const mentions = Array.isArray(params.mentions) ? params.mentions : [];
39453
40023
  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);
39454
40024
  }
@@ -39459,6 +40029,7 @@ var GhostlyNode = class GhostlyNode {
39459
40029
  if (typeof params.messageId !== "string" || typeof params.text !== "string") return refuse("No message to edit");
39460
40030
  const message = await db.getMessage(linkId, params.messageId) ?? (await db.getMessages(linkId)).find((m) => m.sender === "me" && m.wireId === params.messageId);
39461
40031
  if (!message || !canEdit(message)) return refuse("Only your own text messages can be edited");
40032
+ if (card && !GhostlyNode.removes(card, message)) return refuse(notRemoved);
39462
40033
  const text = params.text.trim();
39463
40034
  if (!text) return refuse("An edit cannot be empty. Delete the message instead.");
39464
40035
  if (isJoinNotice(text)) return refuse("An edit cannot read as a join notice.");
@@ -39504,7 +40075,18 @@ var GhostlyNode = class GhostlyNode {
39504
40075
  const live = this.links.get(linkId);
39505
40076
  if (!live?.stored.profile || live.stored.group) return false;
39506
40077
  const id = `peer_${edit.id}`;
39507
- if (live.stored.deletedIds?.includes(id)) return true;
40078
+ if (live.stored.deletedIds?.includes(id)) {
40079
+ if (edit.rm) this.quoteSweeps.add(linkId, id, replyRef({
40080
+ id,
40081
+ linkId
40082
+ }));
40083
+ return true;
40084
+ }
40085
+ if (edit.rm) {
40086
+ const message = await db.getMessage(linkId, id);
40087
+ if (!message || canRemove(message)) await this.forgetMessage(linkId, id, true);
40088
+ return true;
40089
+ }
39508
40090
  const message = await db.getMessage(linkId, id);
39509
40091
  if (!message) {
39510
40092
  this.editBuffer.hold(linkId, edit);
@@ -39657,9 +40239,15 @@ var GhostlyNode = class GhostlyNode {
39657
40239
  editsFor(linkId) {
39658
40240
  let queue = this.editQueues.get(linkId);
39659
40241
  if (!queue) {
40242
+ const removals = () => this.links.get(linkId)?.stored.removals ?? [];
39660
40243
  queue = new EditQueue({
39661
- read: () => db.getMessages(linkId),
39662
- rows: (ids) => db.getMessagesById(linkId, ids),
40244
+ read: async () => [...await db.getMessages(linkId), ...removals().map((r) => removalRow(linkId, r))],
40245
+ rows: async (ids) => {
40246
+ return (await db.getMessagesById(linkId, ids)).map((row, i) => {
40247
+ const removal = row ? void 0 : removals().find((r) => r.id === ids[i]);
40248
+ return row ?? (removal && removalRow(linkId, removal));
40249
+ });
40250
+ },
39663
40251
  ready: () => {
39664
40252
  const live = this.links.get(linkId), link = live?.link;
39665
40253
  return !!link && (link.supportsEdits || link.textDelivery === "dht" && this.takesDhtEdits(live));
@@ -39672,6 +40260,16 @@ var GhostlyNode = class GhostlyNode {
39672
40260
  },
39673
40261
  receiptMs: () => this.links.get(linkId)?.link?.isDataLinkOpen ? 2e4 : DHT_MESSAGE_TTL,
39674
40262
  settle: async (messageId, seq) => {
40263
+ const live = this.links.get(linkId), removal = live?.stored.removals?.find((r) => r.id === messageId);
40264
+ if (live && removal) {
40265
+ if (removal.e !== seq) return;
40266
+ live.stored = {
40267
+ ...live.stored,
40268
+ removals: live.stored.removals.filter((r) => r.id !== messageId)
40269
+ };
40270
+ await db.patchLink(linkId, { removals: live.stored.removals });
40271
+ return;
40272
+ }
39675
40273
  if (await db.patchMessage(linkId, messageId, (current) => {
39676
40274
  if (!current.edit?.pending || current.edit.seq !== seq) return null;
39677
40275
  const { pending: _done, ...edit } = current.edit;
@@ -40047,6 +40645,54 @@ var GhostlyNode = class GhostlyNode {
40047
40645
  }
40048
40646
  }
40049
40647
  deleteMessage({ linkId, messageId }) {
40648
+ this.forgetMessage(linkId, messageId);
40649
+ }
40650
+ /**
40651
+ * Deletes a message of mine for everyone (WISP 400 § Delete for everyone): it goes from this device at once, as a delete
40652
+ * here does, and its removal goes to the contact as the message's last edit, said again until confirmed, live only.
40653
+ * One that never left is only deleted. Never a payment, a request or a notice. A group's goes through `GroupEdits`.
40654
+ */
40655
+ async removeMessage({ linkId, messageId }) {
40656
+ const refuse = (error) => ({
40657
+ error,
40658
+ refused: true
40659
+ });
40660
+ if (linkId.startsWith("group:")) return this.groupEdits.removeMine(linkId.slice(6), messageId);
40661
+ const live = this.links.get(linkId);
40662
+ if (!live?.stored.profile || live.stored.group) return refuse("Only a chat with a contact deletes a message for everyone");
40663
+ const message = await db.getMessage(linkId, messageId);
40664
+ if (!message || message.sender !== "me") return refuse("Only your own messages can be deleted for everyone");
40665
+ if (!canRemove(message)) return refuse("A payment, a request or a notice cannot be deleted for everyone");
40666
+ const out = `${linkId}-out-`;
40667
+ const wireId = message.wireId ?? (message.file?.id.startsWith(out) ? message.file.id.slice(out.length) : void 0);
40668
+ if (!wireId || message.delivery === "waiting") {
40669
+ await this.forgetMessage(linkId, messageId, true);
40670
+ return { error: null };
40671
+ }
40672
+ const removal = {
40673
+ id: messageId,
40674
+ wireId,
40675
+ e: removalNumber(message.edit?.seq),
40676
+ at: Date.now(),
40677
+ pending: true
40678
+ };
40679
+ live.stored = {
40680
+ ...live.stored,
40681
+ removals: withRemoval(live.stored.removals, removal)
40682
+ };
40683
+ await db.patchLink(linkId, { removals: live.stored.removals });
40684
+ await this.forgetMessage(linkId, messageId, true);
40685
+ const edits = this.editsFor(linkId);
40686
+ edits.edited(messageId);
40687
+ edits.flush().catch(() => {});
40688
+ return { error: null };
40689
+ }
40690
+ /**
40691
+ * 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
40692
+ * copy that comes again is not stored: a delete here, or the contact's own removal (WISP 400 § Delete for everyone),
40693
+ * also of a message not here yet. `removed`: deleted for everyone, so the replies here that quote it lose its line too.
40694
+ */
40695
+ async forgetMessage(linkId, messageId, removed = false) {
40050
40696
  const live = this.links.get(linkId);
40051
40697
  if (!live) return;
40052
40698
  live.stored = {
@@ -40055,31 +40701,57 @@ var GhostlyNode = class GhostlyNode {
40055
40701
  };
40056
40702
  db.patchLink(linkId, { deletedIds: live.stored.deletedIds });
40057
40703
  this.hold.forget(linkId, messageId).catch(() => {});
40058
- (async () => {
40059
- const message = await db.getMessage(linkId, messageId);
40060
- if (message?.paymentId && message.delivery === "waiting") await this.desk.withdraw(message.paymentId).catch(() => {});
40061
- if (message?.paymentId && message.sender === "peer") await this.desk.dropReceipt(message.paymentId).catch(() => {});
40062
- if (message?.sender === "me" && message.file && message.delivery === "waiting" && (message.fileOnFloor === "sent" || message.fileOnFloor === "seen")) {
40063
- const wireId = message.file.id.slice(`${linkId}-out-`.length);
40064
- live.link?.settleDht(dhtFileId(wireId)).catch(() => {});
40065
- live.stored = {
40066
- ...live.stored,
40067
- withdrawnFiles: [...(live.stored.withdrawnFiles ?? []).filter((id) => id !== wireId), wireId].slice(-64)
40068
- };
40069
- await db.patchLink(linkId, { withdrawnFiles: live.stored.withdrawnFiles });
40070
- }
40071
- if (message?.file) {
40072
- const stored = await fileStore.get(message.file.id);
40073
- 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));
40074
- this.fileDesk.forget(linkId, message.file.id);
40075
- await removeStored(message.file.id);
40076
- this.transfers.delete(message.file.id);
40077
- }
40078
- await db.deleteMessage(linkId, messageId);
40079
- live.lastMessageAt = (await db.getMessagePage(linkId, { limit: 1 })).messages[0]?.timestamp ?? 0;
40080
- await this.messagesChanged(linkId, [messageId]);
40081
- this.emitState();
40082
- })();
40704
+ const message = await db.getMessage(linkId, messageId);
40705
+ if (message?.paymentId && message.delivery === "waiting") await this.desk.withdraw(message.paymentId).catch(() => {});
40706
+ if (message?.paymentId && message.sender === "peer") await this.desk.dropReceipt(message.paymentId).catch(() => {});
40707
+ if (message?.sender === "me" && message.file && message.delivery === "waiting" && (message.fileOnFloor === "sent" || message.fileOnFloor === "seen")) {
40708
+ const wireId = message.file.id.slice(`${linkId}-out-`.length);
40709
+ live.link?.settleDht(dhtFileId(wireId)).catch(() => {});
40710
+ live.stored = {
40711
+ ...live.stored,
40712
+ withdrawnFiles: [...(live.stored.withdrawnFiles ?? []).filter((id) => id !== wireId), wireId].slice(-64)
40713
+ };
40714
+ await db.patchLink(linkId, { withdrawnFiles: live.stored.withdrawnFiles });
40715
+ }
40716
+ if (message?.file) {
40717
+ const stored = await fileStore.get(message.file.id);
40718
+ 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));
40719
+ this.fileDesk.forget(linkId, message.file.id);
40720
+ await removeStored(message.file.id);
40721
+ this.transfers.delete(message.file.id);
40722
+ }
40723
+ await db.deleteMessage(linkId, messageId);
40724
+ live.lastMessageAt = (await db.getMessagePage(linkId, { limit: 1 })).messages[0]?.timestamp ?? 0;
40725
+ if (removed) this.quoteSweeps.add(linkId, messageId, replyRef(message ?? {
40726
+ id: messageId,
40727
+ linkId
40728
+ }));
40729
+ await this.messagesChanged(linkId, [messageId]);
40730
+ this.emitState();
40731
+ }
40732
+ /**
40733
+ * Messages deleted for everyone leave no line of them here (WISP 400 § Delete for everyone): the replies of the chat
40734
+ * that quote one keep the quote's id and who wrote it, which say it was deleted, and lose its snippet. The chat is
40735
+ * read whole, so removals are gathered (`QuoteSweeps`). The ids of the replies changed.
40736
+ */
40737
+ async forgetQuotes(linkId, removed) {
40738
+ const byRef = /* @__PURE__ */ new Map();
40739
+ for (const [id, ref] of removed) if (ref !== void 0) byRef.set(ref, id);
40740
+ const quoted = (reply) => !reply ? void 0 : reply.messageId !== void 0 && removed.has(reply.messageId) ? reply.messageId : byRef.get(reply.id);
40741
+ const ids = (await db.getMessages(linkId)).filter((m) => {
40742
+ const id = quoted(m.replyTo);
40743
+ return id !== void 0 && (m.replyTo.snippet || m.replyTo.messageId !== id);
40744
+ }).map((m) => m.id);
40745
+ if (!ids.length) return [];
40746
+ await db.patchMessages(linkId, ids, (m) => {
40747
+ const id = quoted(m.replyTo);
40748
+ return id === void 0 ? null : { replyTo: {
40749
+ ...m.replyTo,
40750
+ snippet: "",
40751
+ messageId: id
40752
+ } };
40753
+ });
40754
+ return ids;
40083
40755
  }
40084
40756
  /** Local id of a file we send: the id on the wire is ours too, but lives in its own key space. */
40085
40757
  static outgoingFileId(linkId, wireId) {
@@ -41470,6 +42142,60 @@ var GhostlyNode = class GhostlyNode {
41470
42142
  await this.appChatRunnable(ref, digest);
41471
42143
  return { error: live.link ? live.link.sendAppData(app, data) : "offline" };
41472
42144
  }
42145
+ /** Ranges the contact's apps asked, by chat, app and this engine's number for the ask, until a page answers them. */
42146
+ appRanges = /* @__PURE__ */ new Map();
42147
+ nextAppRangeAsk = 0;
42148
+ /**
42149
+ * Every task stays until a page answers it, live or not: until the link settles it, it holds one of its app's places
42150
+ * (WISP 1200: at most 4 in flight), so the contact gets `busy` rather than more reads while a page is still reading.
42151
+ * The page answers under a number of the engine's, not the contact's: a number the contact cancelled is free for it to
42152
+ * ask again while the page still reads the first ask, whose answer must not go out as the second's.
42153
+ */
42154
+ appRangeAsked(linkId, task) {
42155
+ const request = ++this.nextAppRangeAsk;
42156
+ this.appRanges.set(`${linkId} ${task.app} ${request}`, task);
42157
+ const { app, serve, file, offset, length } = task;
42158
+ this.events.onAppRange?.(linkId, {
42159
+ app,
42160
+ request,
42161
+ serve,
42162
+ file,
42163
+ offset,
42164
+ length
42165
+ });
42166
+ }
42167
+ /** Lets the contact's app read `file`, one of this side's linked files, while both have the app open on this session. */
42168
+ appServe({ linkId, ref, file }) {
42169
+ const { live, app } = this.appChat(linkId, ref);
42170
+ if (typeof file !== "string" || !file) throw new Error("Not a file");
42171
+ return live.link ? live.link.serveAppFile(app, file) : { error: "offline" };
42172
+ }
42173
+ appUnserve({ linkId, serve }) {
42174
+ if (!this.appsOn) throw this.appsOff();
42175
+ this.links.get(linkId)?.link?.unserveAppFile(serve);
42176
+ }
42177
+ /** 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. */
42178
+ appRangeAnswer({ linkId, app, request, bytes, size, error }) {
42179
+ if (!this.appsOn) throw this.appsOff();
42180
+ const key = `${linkId} ${app} ${request}`, task = this.appRanges.get(key), link = this.links.get(linkId)?.link;
42181
+ this.appRanges.delete(key);
42182
+ if (!task || !link) return;
42183
+ if (error === "changed" || error === "gone") return link.failAppRange(task, error);
42184
+ if (!(bytes instanceof Uint8Array) || typeof size !== "number" || !Number.isSafeInteger(size) || size < 0) return link.failAppRange(task, "gone");
42185
+ link.sendAppRange(task, bytes, size);
42186
+ }
42187
+ /** Reads a range of what the contact's app serves in this chat, or why not. */
42188
+ async appRemoteRead({ linkId, ref, serve, offset, length }) {
42189
+ const { live, app } = this.appChat(linkId, ref);
42190
+ if (!live.link) return { error: "offline" };
42191
+ if (!isServeId(serve)) return { error: "not-served" };
42192
+ 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");
42193
+ try {
42194
+ return await live.link.readAppRange(app, serve, offset, length);
42195
+ } catch (error) {
42196
+ return { error: error instanceof Error ? error.message : "failed" };
42197
+ }
42198
+ }
41473
42199
  /** Every page went away: no app runs here any more, so each open one is closed (`close` goes where it can). */
41474
42200
  appsCloseAll() {
41475
42201
  for (const live of this.links.values()) for (const app of [...live.appsOpen?.keys() ?? []]) if (live.link) live.link.closeApp(app);
@@ -42052,14 +42778,14 @@ var GhostlyNode = class GhostlyNode {
42052
42778
  /**
42053
42779
  * `confirmedReal`: the person confirmed a Mainnet payment as real money; without it one is refused. `linkId` +
42054
42780
  * `invoice`: the chat whose message held the invoice. Paid on Testnet, its contact is told (`sayInvoicePaid`): a test
42055
- * mint's invoice counts only on the payer's word.
42781
+ * mint's invoice counts only on the payer's word. Still pending, it is told once the payment settles.
42056
42782
  */
42057
42783
  async walletPayQuote({ quote, mint, note, confirmedReal, linkId, invoice }) {
42058
42784
  const network = WALLET_NETWORKS.find((n) => this.lightnings[n].withQuote(quote));
42059
42785
  const lightning = network && this.lightnings[network].withQuote(quote);
42060
42786
  assertConfirmedReal(network ?? mintNetwork(mint), confirmedReal);
42061
42787
  const paid = lightning ? await lightning.pay(quote, { note }) : await this.wallet.payQuote(quote, mint, note);
42062
- if (paid && linkId && invoice && (network ?? mintNetwork(mint)) === "testnet") this.desk.sayInvoicePaid(linkId, invoice);
42788
+ if (linkId && invoice && (network ?? mintNetwork(mint)) === "testnet") this.desk.sayInvoicePaid(linkId, invoice, { pending: !paid });
42063
42789
  return { paid };
42064
42790
  }
42065
42791
  /** A Lightning address or LNURL (LUD-16, LUD-06): resolved here, in the engine, so every platform fetches the same way. */
@@ -42629,6 +43355,9 @@ var GhostlyNode = class GhostlyNode {
42629
43355
  const problem = iceServerProblem(server);
42630
43356
  if (problem) throw new Error(problem);
42631
43357
  }
43358
+ if (settings.relayOnly !== void 0 && typeof settings.relayOnly !== "boolean") throw new Error("relayOnly is on or off");
43359
+ const relayOnlyBefore = this.settings.relayOnly === true;
43360
+ 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");
42632
43361
  if (settings.avatar !== void 0 && settings.avatar !== "" && typeof sanitizeAvatar(settings.avatar) !== "string") throw new Error("Use a small JPEG picture");
42633
43362
  if (settings.relays && (this.relays || this.transport.configure) && !settings.relays.some((relay) => normalizeRelayUrl(relay))) throw new Error("Enter at least one relay address (https://…)");
42634
43363
  if (settings.readRelays !== void 0 && typeof settings.readRelays !== "boolean") throw new Error("readRelays is on or off");
@@ -42672,6 +43401,8 @@ var GhostlyNode = class GhostlyNode {
42672
43401
  ...settings
42673
43402
  };
42674
43403
  if (!this.settings.irohRelays?.length) delete this.settings.irohRelays;
43404
+ if (this.settings.relayOnly !== true) delete this.settings.relayOnly;
43405
+ const relayOnlyChanged = this.settings.relayOnly === true !== relayOnlyBefore;
42675
43406
  if (irohRelaysChanged && !this.options.irohRelays?.length) this.rehomeIroh();
42676
43407
  if (settings.relays) {
42677
43408
  this.relays?.setRelays(settings.relays);
@@ -42747,12 +43478,12 @@ var GhostlyNode = class GhostlyNode {
42747
43478
  live.dataLink = "idle";
42748
43479
  }));
42749
43480
  else if (!wasOnline && this.networkOn && await this.turnBeforeOnline()) {
42750
- for (const live of this.links.values()) this.startLink(live.stored.id, await db.getMessages(live.stored.id));
43481
+ await this.startLinks([...this.links.keys()]);
42751
43482
  this.hold.start();
42752
43483
  this.startGroupEntries();
42753
43484
  this.prepareSpare(STARTUP_QUIET_MS);
42754
43485
  this.did.publishNow().catch(() => {});
42755
- }
43486
+ } else if (wasOnline && this.networkOn && relayOnlyChanged) await this.restartLinksForRelayOnly();
42756
43487
  if (wasOnline && !this.networkOn) this.stopGroupEntries();
42757
43488
  if (wasOnline && !this.networkOn) await this.hold.stop();
42758
43489
  const gate = knownDeviceGate();
@@ -42771,6 +43502,7 @@ var GhostlyNode = class GhostlyNode {
42771
43502
  counterFloor = 0;
42772
43503
  /** Groups whose admin work is off on this device since a forced takeover or a restore. */
42773
43504
  groupAdminOff = /* @__PURE__ */ new Set();
43505
+ saved = new SavedMessages(() => this.emitState());
42774
43506
  /**
42775
43507
  * Raises the counters a copy from older state must raise, once (`devices/raise.ts`): the raise a forced takeover wrote
42776
43508
  * into the device record with `active`, or the one a restore wrote into the profile's settings. Then reads the floor
@@ -42854,6 +43586,17 @@ var GhostlyNode = class GhostlyNode {
42854
43586
  ...transport.turnWarm ? { turnWarm: transport.turnWarm.bind(transport) } : {}
42855
43587
  };
42856
43588
  }
43589
+ /**
43590
+ * The WebRTC configuration of a connection to a contact (a chat's data link, a group's edge): the profile's ICE
43591
+ * servers, and only its TURN server while "Hide my IP from contacts" is on. The ICE servers a browser refuses are
43592
+ * left out, as they always were.
43593
+ */
43594
+ contactRtcConfig() {
43595
+ return contactRtcConfig({
43596
+ iceServers: this.settings.iceServers.filter((server) => !iceServerProblem(server)),
43597
+ relayOnly: this.settings.relayOnly
43598
+ });
43599
+ }
42857
43600
  /** WebRTC with the person's ICE servers, where this engine has WebRTC. */
42858
43601
  devicePeerConnection() {
42859
43602
  if (typeof RTCPeerConnection === "undefined") return void 0;
@@ -43531,7 +44274,7 @@ var GhostlyNode = class GhostlyNode {
43531
44274
  this.links.delete(stored.id);
43532
44275
  throw error;
43533
44276
  }
43534
- if (this.networkOn) this.startLink(stored.id, []);
44277
+ if (this.networkOn) this.startLink(stored.id);
43535
44278
  if (params.profile) this.links.get(stored.id)?.link?.expectPeer();
43536
44279
  if (params.profile && inviteCode && this.networkOn) this.warmInviteKey(inviteCode);
43537
44280
  this.emitState();
@@ -43668,7 +44411,7 @@ var GhostlyNode = class GhostlyNode {
43668
44411
  this.links.delete(id);
43669
44412
  throw error;
43670
44413
  }
43671
- if (this.networkOn) this.startLink(id, []);
44414
+ if (this.networkOn) this.startLink(id);
43672
44415
  if (expectPeer) this.links.get(id)?.link?.expectPeer();
43673
44416
  return id;
43674
44417
  }
@@ -43703,7 +44446,7 @@ var GhostlyNode = class GhostlyNode {
43703
44446
  this.links.delete(id);
43704
44447
  throw error;
43705
44448
  }
43706
- if (this.networkOn) this.startLink(id, []);
44449
+ if (this.networkOn) this.startLink(id);
43707
44450
  this.links.get(id)?.link?.expectPeer();
43708
44451
  return id;
43709
44452
  }
@@ -43789,7 +44532,7 @@ var GhostlyNode = class GhostlyNode {
43789
44532
  oneShot: true,
43790
44533
  firstPublish: stored.groupEntry === "host" ? "after-first-poll" : "at-start"
43791
44534
  } : {},
43792
- createPeerConnection: () => new RTCPeerConnection({ iceServers: [...RTC_CONFIG.iceServers ?? [], ...this.settings.iceServers.filter((server) => !iceServerProblem(server))] }),
44535
+ createPeerConnection: () => new RTCPeerConnection(this.contactRtcConfig()),
43793
44536
  localFetch: this.localFetch,
43794
44537
  getServices: () => [{
43795
44538
  id: "chat",
@@ -43988,13 +44731,48 @@ var GhostlyNode = class GhostlyNode {
43988
44731
  this.startEdge(linkId);
43989
44732
  if (live.stored.groupEntry) this.links.get(linkId)?.link?.expectPeer();
43990
44733
  }
43991
- startLink(linkId, messages) {
44734
+ /**
44735
+ * "Hide my IP from contacts" was turned on or off: every chat and group edge starts over, so no connection made
44736
+ * before keeps a direct path (a WebRTC one gathered with STUN, an Iroh or HyperDHT endpoint of this app's own) and
44737
+ * the next ones follow the setting. No goodbye: the contacts see the chat back in a moment.
44738
+ */
44739
+ async restartLinksForRelayOnly() {
44740
+ await Promise.allSettled([...this.links.values()].map(async (live) => {
44741
+ const link = live.link;
44742
+ live.carried?.stop();
44743
+ live.link = null;
44744
+ await link?.stop(false);
44745
+ await live.caps?.stop();
44746
+ live.caps = void 0;
44747
+ live.status = "offline";
44748
+ live.dataLink = "idle";
44749
+ }));
44750
+ await this.startLinks([...this.links.keys()]);
44751
+ }
44752
+ /**
44753
+ * Starts these chats' and groups' links, the chats most recently live first (`nativeStartOrder`), in slices that let
44754
+ * the page go: each link derives its keys and seals its capability record as it starts, and 50 chats and 20 groups in
44755
+ * 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
44756
+ * offline until its turn. `started`: after each link started. Gone offline or shut down meanwhile: the links left
44757
+ * start with the network, if ever.
44758
+ */
44759
+ async startLinks(linkIds, started) {
44760
+ const pause = pacer(START_SLICE_MS);
44761
+ for (const linkId of this.nativeStartOrder(linkIds)) {
44762
+ if (!this.networkOn || this.shuttingDown) break;
44763
+ if (!this.links.has(linkId)) continue;
44764
+ this.startLink(linkId);
44765
+ started?.(linkId);
44766
+ await pause();
44767
+ }
44768
+ }
44769
+ startLink(linkId) {
43992
44770
  const live = this.links.get(linkId);
43993
44771
  if (!live || live.link) return;
43994
44772
  const { stored } = live;
43995
44773
  if (stored.group) return this.startEdge(linkId);
43996
44774
  if (stored.profile) live.pairing = { status: "connecting" };
43997
- const lastSeenTimestamp = messages.reduce((max, m) => m.sender === "peer" && m.via === "pkarr" ? Math.max(max, m.sentAt ?? m.timestamp) : max, 0);
44775
+ const lastSeenTimestamp = live.pkarrSeenAt ?? 0;
43998
44776
  const credentials = stored.profile && stored.participationSeed ? {
43999
44777
  seedB64: stored.participationSeed,
44000
44778
  peerKey: stored.pairedPeerKey,
@@ -44028,6 +44806,7 @@ var GhostlyNode = class GhostlyNode {
44028
44806
  upgradeSupport: true,
44029
44807
  peerUpgrades: () => !!live.caps?.peer?.capabilities.includes(UPGRADE_CAPABILITY),
44030
44808
  appsSupport: this.appsOn,
44809
+ appRangesSupport: this.appsOn && !this.appsWireOnly,
44031
44810
  appsOpen: this.appsOn ? live.appsOpen ??= /* @__PURE__ */ new Map() : void 0,
44032
44811
  servicesSupport: this.options.servicesSupport ?? (this.options.platform ?? "web") !== "web",
44033
44812
  dht: stored.profile ? {
@@ -44111,7 +44890,7 @@ var GhostlyNode = class GhostlyNode {
44111
44890
  lastSeenTimestamp,
44112
44891
  pollIntervals: this.pollIntervals,
44113
44892
  autoConnect: true,
44114
- createPeerConnection: () => this.chatPeer(new RTCPeerConnection({ iceServers: [...RTC_CONFIG.iceServers ?? [], ...this.settings.iceServers.filter((server) => !iceServerProblem(server))] })),
44893
+ createPeerConnection: () => this.chatPeer(new RTCPeerConnection(this.contactRtcConfig())),
44115
44894
  localFetch: this.localFetch,
44116
44895
  getServices: () => stored.profile ? [{
44117
44896
  id: "chat",
@@ -44352,6 +45131,7 @@ var GhostlyNode = class GhostlyNode {
44352
45131
  if (supported) this.flushPin(linkId);
44353
45132
  },
44354
45133
  onAppFrame: this.appsOn ? (event) => this.events.onAppFrame?.(linkId, event) : void 0,
45134
+ onAppRangeTask: this.appsOn ? (task) => this.appRangeAsked(linkId, task) : void 0,
44355
45135
  onPaymentRequest: (request) => this.desk.onPaymentRequest(linkId, request),
44356
45136
  onPaymentAsk: (ask) => this.desk.onPaymentAsk(linkId, ask),
44357
45137
  onPayment: (payment) => this.desk.onPayment(linkId, payment),
@@ -44506,7 +45286,7 @@ var GhostlyNode = class GhostlyNode {
44506
45286
  get nativeFactories() {
44507
45287
  const relay = this.relaysHyperdht ? this.hyperdhtRelay : "";
44508
45288
  return {
44509
- ...relay ? { "hyperdht/1": async (seedB64) => (await import("./hyperdhtRelay-DwkZ8vpt.js")).createRelayedHyperEndpoint(seedB64, relay) } : {},
45289
+ ...relay ? { "hyperdht/1": async (seedB64) => (await import("./hyperdhtRelay-CJBqsS_e.js")).createRelayedHyperEndpoint(seedB64, relay) } : {},
44510
45290
  ...this.options.nativeTransports,
44511
45291
  ...this.ownIrohRelays ? { "iroh/1": (seedB64) => this.options.nativeTransports["iroh/1"](seedB64, this.settings.irohRelays?.length ? { relays: [...this.settings.irohRelays] } : {}) } : {},
44512
45292
  ...this.options.irohWeb ? { "iroh/1": (seedB64) => createIrohWebEndpoint(seedB64, { relays: this.irohRelays }) } : {}
@@ -44682,9 +45462,8 @@ var GhostlyNode = class GhostlyNode {
44682
45462
  if (group && !live.stored.groupEntry && live.link && `group:${group}` !== this.activeLinkId && this.keepsGroupNative(live.stored)) groups.add(group);
44683
45463
  }
44684
45464
  if (!groups.size) return;
44685
- const views = new Map(this.groups.views().map((view) => [view.id, view]));
44686
45465
  for (const groupId of groups) {
44687
- const edges = this.groupEdgesByRank(groupId, views.get(groupId));
45466
+ const edges = this.groupEdgesByRank(groupId, this.groups.view(groupId));
44688
45467
  if (!edges.length || edges.some((live) => live.link.isDataLinkOpen)) continue;
44689
45468
  const [anchor, next] = edges;
44690
45469
  if (next && !this.anchorPassed(next, now) && this.unanswered(anchor, now)) {
@@ -44712,8 +45491,7 @@ var GhostlyNode = class GhostlyNode {
44712
45491
  /** A group opened on screen: its edges with no native listener take one as a chat on screen does, the one it keeps first. */
44713
45492
  groupOnScreen(groupId) {
44714
45493
  const native = Object.keys(this.nativeFactories);
44715
- const view = this.groups.views().find((g) => g.id === groupId);
44716
- for (const live of this.groupEdgesByRank(groupId, view)) {
45494
+ for (const live of this.groupEdgesByRank(groupId, this.groups.view(groupId))) {
44717
45495
  if (native.every((t) => live.link.availableTransports.includes(t))) continue;
44718
45496
  this.ensureNativeEndpoints(live.stored.id);
44719
45497
  }
@@ -44768,8 +45546,11 @@ var GhostlyNode = class GhostlyNode {
44768
45546
  const owners = [...this.links.values()].filter((other) => other.link?.availableTransports.includes(key));
44769
45547
  const slots = this.nativeSlots(key), groups = owners.filter((other) => other.stored.group).length;
44770
45548
  const now = Date.now();
44771
- let views;
44772
- const viewOf = (groupId) => (views ??= new Map(this.groups.views().map((view) => [view.id, view]))).get(groupId);
45549
+ const views = /* @__PURE__ */ new Map();
45550
+ const viewOf = (groupId) => {
45551
+ if (!views.has(groupId)) views.set(groupId, this.groups.view(groupId));
45552
+ return views.get(groupId);
45553
+ };
44773
45554
  const anchors = /* @__PURE__ */ new Map();
44774
45555
  const anchorOf = (groupId) => {
44775
45556
  if (!anchors.has(groupId)) anchors.set(groupId, this.groupEdgesByRank(groupId, viewOf(groupId))[0]);
@@ -44985,10 +45766,19 @@ var GhostlyNode = class GhostlyNode {
44985
45766
  const reacted = this.reactionNotes.get(linkId);
44986
45767
  if (reacted?.message && ids.includes(reacted.message)) {
44987
45768
  const row = await db.getMessage(linkId, reacted.message);
44988
- const fresh = row && noteAfterChange(reacted, row);
44989
- if (fresh) {
44990
- this.reactionNotes.set(linkId, fresh);
44991
- this.emitState();
45769
+ if (!row) {
45770
+ const before = await this.reactionNoteNow(linkId, reacted);
45771
+ if (this.reactionNotes.get(linkId) === reacted) {
45772
+ if (before) this.reactionNotes.set(linkId, before);
45773
+ else this.reactionNotes.delete(linkId);
45774
+ this.emitState();
45775
+ }
45776
+ } else {
45777
+ const fresh = noteAfterChange(reacted, row);
45778
+ if (fresh) {
45779
+ this.reactionNotes.set(linkId, fresh);
45780
+ this.emitState();
45781
+ }
44992
45782
  }
44993
45783
  }
44994
45784
  const onChanges = this.events.onMessageChanges;
@@ -45106,6 +45896,7 @@ var GhostlyNode = class GhostlyNode {
45106
45896
  message = this.placed(message, place);
45107
45897
  const live = this.links.get(message.linkId);
45108
45898
  if (live?.stored.deletedIds?.includes(message.id)) return false;
45899
+ if (message.linkId.startsWith("group:") && this.groups.isRemoved(message.linkId.slice(6), message.id)) return false;
45109
45900
  message = await this.resolveReply(message);
45110
45901
  if (message.sender === "peer" && live && !message.details?.received) message = {
45111
45902
  ...message,
@@ -45138,6 +45929,7 @@ var GhostlyNode = class GhostlyNode {
45138
45929
  if (!message.event) this.newestAt.set(message.linkId, Math.max(newest ?? 0, writtenAt(message, this.clockLeads.get(this.clockOf(message)))));
45139
45930
  if (message.sender === "peer") this.messageFeedback("message", message, newest);
45140
45931
  if (live) live.lastMessageAt = Math.max(live.lastMessageAt, message.timestamp);
45932
+ if (live && message.sender === "peer" && message.via === "pkarr") live.pkarrSeenAt = Math.max(live.pkarrSeenAt ?? 0, pkarrSeenAt([message]));
45141
45933
  const early = message.sender === "peer" && message.id.startsWith("peer_") ? this.editBuffer.take(message.linkId, message.id.slice(5)) : void 0;
45142
45934
  if (early) {
45143
45935
  await this.applyPeerEdit(message.linkId, message, early);
@@ -45341,6 +46133,11 @@ var EngineServer = class {
45341
46133
  linkId,
45342
46134
  event
45343
46135
  }),
46136
+ onAppRange: (linkId, range) => this.broadcast({
46137
+ kind: "app-range",
46138
+ linkId,
46139
+ range
46140
+ }),
45344
46141
  onAppsChecked: () => this.broadcast({ kind: "apps-checked" }),
45345
46142
  onDeviceGate: (gate) => this.broadcast({
45346
46143
  kind: "device-gate",
@@ -45361,8 +46158,10 @@ var EngineServer = class {
45361
46158
  /**
45362
46159
  * `read`: the chats and groups whose whole history the client read itself, after `mark` (`historyMark`). One that has
45363
46160
  * not changed since is not read and sent again: the client hears only what changes in it from now on.
46161
+ * `newest`: each chat's newest rows that many (`messagePage`), not its whole history, which the client asks for when
46162
+ * it needs it (`HistoryRequest`). What changes in the chat goes to it on top of that page.
45364
46163
  */
45365
- attach(client, read) {
46164
+ attach(client, read, scope = {}) {
45366
46165
  this.clients.add(client);
45367
46166
  const sent = /* @__PURE__ */ new Set();
45368
46167
  if (read) {
@@ -45385,7 +46184,7 @@ var EngineServer = class {
45385
46184
  if (sent.has(link.id)) continue;
45386
46185
  await this.inOrder(link.id, async () => {
45387
46186
  if (!this.clients.has(client)) return;
45388
- client.post({
46187
+ client.post(scope.newest ? await this.newestOf(link.id, scope.newest) : {
45389
46188
  kind: "messages",
45390
46189
  linkId: link.id,
45391
46190
  messages: await this.node.getMessages(link.id)
@@ -45454,6 +46253,38 @@ var EngineServer = class {
45454
46253
  return Promise.reject(error);
45455
46254
  }
45456
46255
  }
46256
+ /** A chat's newest page, as a `messages` event: `more` when older rows are left out. */
46257
+ async newestOf(linkId, limit) {
46258
+ const page = await this.node.messagePage({
46259
+ linkId,
46260
+ limit
46261
+ });
46262
+ return {
46263
+ kind: "messages",
46264
+ linkId,
46265
+ messages: page.messages,
46266
+ ...page.more ? { more: true } : {}
46267
+ };
46268
+ }
46269
+ /**
46270
+ * A chat's or group's whole history, to this client alone as a `messages` event, after what is still being sent for it
46271
+ * (a `HistoryRequest`, which the host hands here): what changes while it is read follows it.
46272
+ */
46273
+ async history(client, linkId) {
46274
+ if (typeof linkId !== "string" || !this.clients.has(client)) return;
46275
+ try {
46276
+ await this.ready;
46277
+ await this.inOrder(linkId, async () => {
46278
+ if (!this.clients.has(client)) return;
46279
+ const messages = await this.node.getMessages(linkId);
46280
+ if (this.clients.has(client) && this.post(client, {
46281
+ kind: "messages",
46282
+ linkId,
46283
+ messages
46284
+ })) this.histories.get(client)?.add(linkId);
46285
+ });
46286
+ } catch {}
46287
+ }
45457
46288
  changed(linkId) {
45458
46289
  this.changedAt.set(linkId, ++this.changes);
45459
46290
  }
@@ -45528,4 +46359,4 @@ function signalKind(signal) {
45528
46359
  //#endregion
45529
46360
  export { EngineServer };
45530
46361
 
45531
- //# sourceMappingURL=server-ZrkwMbFo.js.map
46362
+ //# sourceMappingURL=server-BktMmp7L.js.map