@ghostlytools/cli 1.12.1 → 1.13.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 (91) hide show
  1. package/README.md +8 -7
  2. package/dist/assets/{api-jRUXnBdX.js → api-DF36rBJK.js} +2 -2
  3. package/dist/assets/{api-BwEgbvvK.js → api-Dnq86JAA.js} +139 -41
  4. package/dist/assets/api-Dnq86JAA.js.map +1 -0
  5. package/dist/assets/{apiKit-BlsNk-Cx.js → apiKit-nLK4jeTq.js} +3 -3
  6. package/dist/assets/{apiKit-BlsNk-Cx.js.map → apiKit-nLK4jeTq.js.map} +1 -1
  7. package/dist/assets/{appFetch-CW9fJPHh.js → appFetch-wqBWi3Ry.js} +2 -2
  8. package/dist/assets/{appFetch-CW9fJPHh.js.map → appFetch-wqBWi3Ry.js.map} +1 -1
  9. package/dist/assets/{apps-CL8TXHhu.js → apps-DBVhKpfe.js} +10 -10
  10. package/dist/assets/apps-DBVhKpfe.js.map +1 -0
  11. package/dist/assets/{apps-BcG4u6SM.js → apps-nLtyhC2f.js} +1 -1
  12. package/dist/assets/{backup-BA41EDvh.js → backup-Bczllmzf.js} +4 -4
  13. package/dist/assets/{backup-BA41EDvh.js.map → backup-Bczllmzf.js.map} +1 -1
  14. package/dist/assets/{backup-xZfV-ytw.js → backup-D6s0LQdg.js} +1 -1
  15. package/dist/assets/{bitcoind-Dh7n9amb.js → bitcoind-DML_-Xbv.js} +2 -2
  16. package/dist/assets/{bitcoind-Dh7n9amb.js.map → bitcoind-DML_-Xbv.js.map} +1 -1
  17. package/dist/assets/{buttons-SH1tNRh7.js → buttons-B3C3vdhH.js} +30 -9
  18. package/dist/assets/buttons-B3C3vdhH.js.map +1 -0
  19. package/dist/assets/buttons-DaY5FYlV.js +1 -0
  20. package/dist/assets/{client-DGS-atRu.js → client-B7jRrSnb.js} +3 -3
  21. package/dist/assets/{client-DGS-atRu.js.map → client-B7jRrSnb.js.map} +1 -1
  22. package/dist/assets/{domainProofs-BDNP1dIy.js → domainProofs-b3Y1Gj9g.js} +6 -2
  23. package/dist/assets/{domainProofs-BDNP1dIy.js.map → domainProofs-b3Y1Gj9g.js.map} +1 -1
  24. package/dist/assets/{errors-DDLFO4Gf.js → errors-JVJsO8Iu.js} +18 -2
  25. package/dist/assets/errors-JVJsO8Iu.js.map +1 -0
  26. package/dist/assets/{fixedHosts-CPSsGOI2.js → fixedHosts-H3i6o9Iy.js} +2 -2
  27. package/dist/assets/{fixedHosts-CPSsGOI2.js.map → fixedHosts-H3i6o9Iy.js.map} +1 -1
  28. package/dist/assets/{ghostly_iroh_web-DIj5xGmR.js → ghostly_iroh_web-9VOwZcJQ.js} +30 -35
  29. package/dist/assets/ghostly_iroh_web-9VOwZcJQ.js.map +1 -0
  30. package/dist/assets/ghostly_iroh_web_bg.wasm +0 -0
  31. package/dist/assets/{groupMeta-DxuJzko_.js → groupMeta--fxSh792.js} +165 -20
  32. package/dist/assets/groupMeta--fxSh792.js.map +1 -0
  33. package/dist/assets/{host-BxM-HMr0.js → host-CGzVFfMz.js} +211 -58
  34. package/dist/assets/host-CGzVFfMz.js.map +1 -0
  35. package/dist/assets/{hyperdhtRelay-bjNGacf5.js → hyperdhtRelay-B4_wdCtx.js} +2 -2
  36. package/dist/assets/{hyperdhtRelay-bjNGacf5.js.map → hyperdhtRelay-B4_wdCtx.js.map} +1 -1
  37. package/dist/assets/{hyperdhtRelay-DLUiwfnt.js → hyperdhtRelay-Ce-gWsRY.js} +2 -2
  38. package/dist/assets/{hyperdhtRelay-DLUiwfnt.js.map → hyperdhtRelay-Ce-gWsRY.js.map} +1 -1
  39. package/dist/assets/{irohWeb-CbnGtUo6.js → irohWeb-Dp1i8v6n.js} +13 -12
  40. package/dist/assets/irohWeb-Dp1i8v6n.js.map +1 -0
  41. package/dist/assets/{main-CwTaepxR.js → main-C8J53SwH.js} +68 -63
  42. package/dist/assets/main-C8J53SwH.js.map +1 -0
  43. package/dist/assets/{mainline-CVrd0C1n.js → mainline-DY95WbuK.js} +2 -2
  44. package/dist/assets/{mainline-CVrd0C1n.js.map → mainline-DY95WbuK.js.map} +1 -1
  45. package/dist/assets/{ownDid-DY3rYqDI.js → ownDid-oa-T2vmZ.js} +9 -5
  46. package/dist/assets/ownDid-oa-T2vmZ.js.map +1 -0
  47. package/dist/assets/{ownStatus-DtzIllg2.js → ownStatus-Bc08eNJY.js} +7 -6
  48. package/dist/assets/ownStatus-Bc08eNJY.js.map +1 -0
  49. package/dist/assets/{pairedTransports-BKmvlKz1.js → pairedTransports-Dppn8lUN.js} +3 -3
  50. package/dist/assets/pairedTransports-Dppn8lUN.js.map +1 -0
  51. package/dist/assets/{profiles-BOYGlmu2.js → profiles-B2uy04ph.js} +3 -3
  52. package/dist/assets/{profiles-BOYGlmu2.js.map → profiles-B2uy04ph.js.map} +1 -1
  53. package/dist/assets/{registry-Bep4umOM.js → registry-DbTLLs3y.js} +9 -5
  54. package/dist/assets/registry-DbTLLs3y.js.map +1 -0
  55. package/dist/assets/{registry-4W1LGlCF.js → registry-bLIfG619.js} +1 -1
  56. package/dist/assets/{relay-Cjfmdec0.js → relay-CHWg5hpZ.js} +73 -11
  57. package/dist/assets/relay-CHWg5hpZ.js.map +1 -0
  58. package/dist/assets/{resolve-CIc3KZMV.js → resolve-DNX-eecG.js} +9 -4
  59. package/dist/assets/resolve-DNX-eecG.js.map +1 -0
  60. package/dist/assets/secretGuard-Bh11MPdI.js +1 -0
  61. package/dist/assets/{secretGuard-BrATm_gl.js → secretGuard-oz_3hBfW.js} +19 -2
  62. package/dist/assets/{secretGuard-BrATm_gl.js.map → secretGuard-oz_3hBfW.js.map} +1 -1
  63. package/dist/assets/{server-D4gf-LnD.js → server-DWJ4RzJn.js} +748 -222
  64. package/dist/assets/server-DWJ4RzJn.js.map +1 -0
  65. package/dist/assets/{translate-BcbSWkuq.js → translate-CHj_PdLg.js} +13 -8
  66. package/dist/assets/translate-CHj_PdLg.js.map +1 -0
  67. package/dist/assets/{waitNotice-DQvZgz2T.js → waitNotice-Cvz5CiKR.js} +57 -3
  68. package/dist/assets/waitNotice-Cvz5CiKR.js.map +1 -0
  69. package/dist/ghostly.mjs +1 -1
  70. package/npm-shrinkwrap.json +2 -2
  71. package/package.json +1 -1
  72. package/dist/assets/api-BwEgbvvK.js.map +0 -1
  73. package/dist/assets/apps-CL8TXHhu.js.map +0 -1
  74. package/dist/assets/buttons-CsGdQNnR.js +0 -1
  75. package/dist/assets/buttons-SH1tNRh7.js.map +0 -1
  76. package/dist/assets/errors-DDLFO4Gf.js.map +0 -1
  77. package/dist/assets/ghostly_iroh_web-DIj5xGmR.js.map +0 -1
  78. package/dist/assets/groupMeta-DxuJzko_.js.map +0 -1
  79. package/dist/assets/host-BxM-HMr0.js.map +0 -1
  80. package/dist/assets/irohWeb-CbnGtUo6.js.map +0 -1
  81. package/dist/assets/main-CwTaepxR.js.map +0 -1
  82. package/dist/assets/ownDid-DY3rYqDI.js.map +0 -1
  83. package/dist/assets/ownStatus-DtzIllg2.js.map +0 -1
  84. package/dist/assets/pairedTransports-BKmvlKz1.js.map +0 -1
  85. package/dist/assets/registry-Bep4umOM.js.map +0 -1
  86. package/dist/assets/relay-Cjfmdec0.js.map +0 -1
  87. package/dist/assets/resolve-CIc3KZMV.js.map +0 -1
  88. package/dist/assets/secretGuard-Bm6nci0I.js +0 -1
  89. package/dist/assets/server-D4gf-LnD.js.map +0 -1
  90. package/dist/assets/translate-BcbSWkuq.js.map +0 -1
  91. package/dist/assets/waitNotice-DQvZgz2T.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ownStatus-Bc08eNJY.js","names":[],"sources":["../../src/engineMethods.ts","../../src/turnRefs.ts","../../src/words.ts","../../src/ownStatus.ts"],"sourcesContent":["/**\n * What each call of the app's `EngineApi` (packages/browser/src/shared/rpc.ts) takes, as `engine --list --verbose`\n * shows it: `{ linkId, label }` an object with these keys (`?` an optional one), a type's name for an object of that\n * type, \"\" nothing; a trailing `?` when the object may be left out. `engineMethods.test.ts` reads it out of rpc.ts and\n * keeps the two equal. The device calls (WISP 06): a CLI profile is always on one device, so they answer `single` or refuse.\n */\nexport const ENGINE_PARAMS: Readonly<Record<string, string>> = {\n usdtCreate: \"UsdtCreate\",\n usdtUnlock: \"{ password, network? }\",\n usdtReveal: \"{ password?, network? }\",\n usdtLock: \"{ network? }?\",\n usdtRefresh: \"{ network? }?\",\n usdtExportBackup: \"{ password, network? }\",\n usdtRestoreBackup: \"{ text, password, network? }\",\n arkCreate: \"ArkCreate\",\n arkUnlock: \"{ password, network? }\",\n arkLock: \"{ network? }?\",\n arkBackup: \"{ password?, network? }\",\n arkExportBackup: \"{ password, network? }\",\n arkRestoreBackup: \"{ text, password, network? }\",\n arkRefresh: \"{ network? }?\",\n arkRecover: \"{ network? }?\",\n barkCreate: \"BarkCreate\",\n barkBackup: \"{ network? }?\",\n barkExportBackup: \"{ password, network? }\",\n barkRestoreBackup: \"{ text, password, network? }\",\n barkRefresh: \"{ network? }?\",\n barkBoard: \"{ network? }?\",\n fedimintPreview: \"{ invite, network? }\",\n fedimintJoin: \"{ invite, recover?, network? }\",\n fedimintLeave: \"{ federation }\",\n fedimintRefresh: \"{ network? }?\",\n fedimintSpendNotes: \"{ federation, amount, confirmedReal? }\",\n fedimintReceiveNotes: \"{ notes, network? }\",\n fedimintInvoice: \"{ federation, amount, memo? }\",\n fedimintTakeBack: \"{ federation, operation }\",\n fedimintBackup: \"{ network? }?\",\n fedimintExportBackup: \"{ password, network? }\",\n fedimintRestoreBackup: \"{ text, password, network? }\",\n fedimintRestorePhrase: \"{ mnemonic, invites, network? }\",\n sparkCreate: \"SparkCreate\",\n sparkBackup: \"{ network? }?\",\n sparkExportBackup: \"{ password, network? }\",\n sparkRestoreBackup: \"{ text, password, apiKey?, network? }\",\n sparkRefresh: \"{ network? }?\",\n sparkUseForLightning: \"{ network? }?\",\n preparePayment: \"{ target, amount, feeCap, payee, linkId?, requestId?, memo?, network? }\",\n approvePayment: \"{ id, confirmedReal? }\",\n reconcilePayment: \"{ id }\",\n cancelPayment: \"{ id }\",\n refreshPublicProfiles: \"{ linkId, force? }\",\n choosePublicProfile: \"{ linkId, choice }\",\n preparePeerProof: \"{ linkId, externalKey, adapter? }\",\n submitPeerProof: \"{ linkId, challenge, event }\",\n withdrawPeerProof: \"{ linkId, adapter? }\",\n beginIdentityProof: \"{ provider, subject, validityDays? }\",\n completeIdentityProof: \"{ draftId, evidence }\",\n cancelIdentityProof: \"{ draftId }\",\n removeIdentityProof: \"{ id }\",\n shareIdentityProof: \"{ linkId, id }\",\n withdrawIdentityProof: \"{ linkId, id }\",\n recheckIdentityProof: \"{ linkId, id }\",\n lookupIdentityDisplay: \"{ linkId, id }\",\n loadPublicProfile: \"{ provider, subject, force? }\",\n loadPublicPosts: \"{ provider, subject, more?, force? }\",\n loadPublicGraph: \"{ provider, subject, force? }\",\n loadPublicPostImage: \"{ provider, subject, postId, index }\",\n clearProfileData: \"\",\n setDidListed: \"{ id, listed }\",\n nostrLoadContact: \"{ linkId, subject, what, more? }\",\n nostrForgetContact: \"{ linkId, subject }\",\n nostrLoadOwn: \"{ subject }\",\n nostrOwnFollows: \"{ subject }\",\n nostrContactNotes: \"{ linkId, subject }\",\n nostrLookup: \"NostrLookupRequest\",\n nostrDraft: \"NostrDraftRequest\",\n nostrPublish: \"{ draftId, event }\",\n createLink: \"\",\n takeInvite: \"\",\n joinLink: \"{ inviteCode }\",\n ensureLink: \"LinkParams & { inviteCode?: string }\",\n confirmPair: \"{ linkId, code }\",\n pollNow: \"{ linkId }\",\n removeLink: \"{ linkId }\",\n renameLink: \"{ linkId, label }\",\n setActiveLink: \"{ linkId }\",\n sendMessage: \"{ linkId, text, timestamp?, preview?, replyTo?, card? }\",\n editMessage: \"{ linkId, messageId, text, preview?, mentions?, card? }\",\n retryMessage: \"{ linkId, messageId }\",\n react: \"{ linkId, messageId, emoji }\",\n pinMessage: \"{ linkId, messageId?, remove? }\",\n appId: \"{ linkId, ref }\",\n appOpen: \"{ linkId, ref, version, digest? }\",\n appClose: \"{ linkId, ref }\",\n appSend: \"{ linkId, ref, data, digest? }\",\n appServe: \"{ linkId, ref, file, digest? }\",\n appUnserve: \"{ linkId, serve }\",\n appRangeAnswer: \"{ linkId, app, request, bytes?, size?, error? }\",\n appRemoteRead: \"{ linkId, ref, serve, offset, length, digest? }\",\n messageDetails: \"{ linkId, messageId }\",\n deleteMessage: \"{ linkId, messageId }\",\n removeMessage: \"{ linkId, messageId }\",\n exportLinks: \"\",\n sendFile: \"{ linkId, file, timestamp, replyTo?, forwarded? }\",\n sendGroupFile: \"{ groupId, file, caption?, replyTo?, forwarded? }\",\n groupFileCheck: \"{ groupId }\",\n forwardMessages: \"{ linkId, messageIds, to }\",\n fileAction: \"{ linkId, fileId, action }\",\n setDeliveryMode: \"{ linkId, mode }\",\n setTransportPreference: \"{ linkId, preferred, fallback }\",\n setChatTransport: \"{ linkId, transport }\",\n setChatPaymentMethods: \"{ linkId, methods, networks? }\",\n setChatHold: \"{ linkId, enabled }\",\n connect: \"{ linkId }\",\n walletAddMint: \"{ url, primary?, network? }\",\n walletCreate: \"WalletCreate\",\n walletRemove: \"WalletRemove\",\n walletTestCoins: \"WalletTestCoins\",\n walletSetupRetry: \"{ type }\",\n walletSetupDismiss: \"{ type }\",\n wake: \"{ network? }?\",\n peekProfile: \"{ profile, dbName }\",\n walletSetPrimaryMint: \"{ url }\",\n walletRemoveMint: \"{ url, acceptLoss? }\",\n walletReceiveLightning: \"{ amount, via?, network?, card? }\",\n walletWatchInvoice: \"{ invoice, network? }\",\n walletQuoteInvoice: \"{ invoice, via?, network?, card?, amount? }\",\n walletPayQuote: \"{ quote, mint, note?, confirmedReal?, linkId?, invoice? }\",\n lnurlResolve: \"{ text, network? }\",\n lnurlInvoice: \"{ id, amount, comment?, network? }\",\n checkPayment: \"{ linkId, paymentId }\",\n lightningSetSource: \"{ providerId, values, network?, card? }\",\n lightningClearSource: \"{ network?, card? }?\",\n lightningRetrySource: \"{ network?, card? }?\",\n lightningReconfigureSource: \"{ values, network?, card? }\",\n lightningRefresh: \"{ network?, card? }?\",\n lightningSetReceive: \"{ network, card }\",\n lightningRename: \"{ network, card, name }\",\n bitcoinSetSource: \"{ providerId, values, network? }\",\n bitcoinClearSource: \"{ network? }?\",\n bitcoinRetrySource: \"{ network? }?\",\n bitcoinReconfigureSource: \"{ values, network? }\",\n bitcoinReceiveAddress: \"{ network? }?\",\n bitcoinRefresh: \"{ network? }?\",\n walletReceiveToken: \"{ token }\",\n walletInspectCashu: \"{ text }\",\n walletExport: \"{ network? }?\",\n walletBackupReminder: \"{ event: \\\"later\\\"; wallet: string } | { event: \\\"profile\\\" }\",\n sendPayment: \"{ linkId, amount, memo?, timestamp, network?, confirmedReal? }\",\n requestPayment: \"{ linkId, amount, memo?, timestamp, method?, rail?, network?, card? }\",\n requestGroupPayment: \"{ groupId, amount, memo?, timestamp, rail, network?, card? }\",\n groupPaymentHello: \"{ groupId, member }\",\n askToPay: \"{ linkId, amount, method, memo?, timestamp, network? }\",\n payRequest: \"{ linkId, paymentId, via?, maxFee?, network?, confirmedReal?, card? }\",\n reclaimPayment: \"{ paymentId }\",\n disconnect: \"{ linkId }\",\n addService: \"{ name, target }\",\n removeService: \"{ serviceId }\",\n setServiceEnabled: \"{ serviceId, enabled }\",\n setServiceShared: \"{ serviceId, peerPubKeyZ32, shared }\",\n updateSettings: \"{ settings }\",\n setCallSignal: \"{ linkId, signal }\",\n callOfferHeld: \"{ linkId, ts }\",\n setTyping: \"{ linkId, typing, kind?, status? }\",\n setGroupTyping: \"{ groupId, typing, kind?, status? }\",\n setPresence: \"{ presence }\",\n setOwnStatus: \"{ status }\",\n clearOwnStatus: \"\",\n getOwnStatus: \"\",\n setWakeSubscription: \"{ subscription }\",\n wakeConfirm: \"{ endpoint }\",\n setWakeMuted: \"{ linkId, muted }\",\n setWakeOnline: \"{ on }\",\n wakeForCall: \"{ linkId }\",\n setCallOn: \"{ on }\",\n setFastPoll: \"{ linkId, fast }\",\n createGroup: \"{ name, profile? }\",\n inviteToGroup: \"{ groupId, linkId }\",\n acceptGroupInvitation: \"{ groupId }\",\n declineGroupInvitation: \"{ groupId }\",\n keepGroup: \"{ groupId }\",\n switchGroup: \"{ groupId, to }\",\n enableGroupLink: \"{ groupId, reset? }\",\n disableGroupLink: \"{ groupId }\",\n joinGroupByLink: \"{ link }\",\n sendGroupMessage: \"{ groupId, text, mentions?, replyTo?, card? }\",\n pressButton: \"{ linkId, messageId, buttonId }\",\n groupTaken: \"{ groupId, messageId, edit?, reaction?, pin? }\",\n chatUnconfirmed: \"{ linkId }\",\n groupMessages: \"{ groupId }\",\n messagePage: \"{ linkId, limit?, before?, after? }\",\n chatsFound: \"{ query, linkIds }\",\n statusCardIndex: \"\",\n saveMessage: \"{ linkId, messageId, remove? }\",\n savedMessages: \"\",\n leaveGroup: \"{ groupId }\",\n removeGroupMember: \"{ groupId, key }\",\n makeGroupAdmin: \"{ groupId, key }\",\n setGroupHub: \"{ groupId, key, role }\",\n rotateGroup: \"{ groupId }\",\n setGroupPicture: \"{ groupId, picture }\",\n renameGroup: \"{ groupId, name }\",\n setGroupCall: \"{ groupId, sfu, e2ee? }\",\n groupCallToken: \"{ groupId }\",\n groupCallKey: \"{ groupId }\",\n groupCallModerate: \"{ groupId, act, target?, src? }\",\n forgetGroup: \"{ groupId }\",\n setGroupManage: \"{ groupId, on }\",\n deviceEnrollInvite: \"{ name }\",\n deviceEnrollConfirm: \"{ match }\",\n deviceEnrollCancel: \"\",\n deviceEnrollView: \"\",\n deviceEnrollJoin: \"{ code, name, kind?, app? }\",\n deviceEnrollReady: \"\",\n deviceEnrollFinish: \"\",\n deviceEnrollRemove: \"\",\n deviceSet: \"\",\n devicePing: \"{ key }\",\n devicePushState: \"\",\n devicePushSet: \"{ subscription }\",\n deviceHandoffVerifier: \"{ password, current? }\",\n deviceHandoffPush: \"{ key }\",\n deviceHandoffPull: \"{ password, later? }\",\n deviceHandoffAccept: \"{ later? }\",\n deviceHandoffSettle: \"\",\n deviceHandoffCancel: \"\",\n deviceHandoffView: \"\",\n deviceHandoffAllow: \"{ key }\",\n deviceTakeoverInfo: \"\",\n deviceTakeover: \"{ password, name, lost? }\",\n deviceTurnPeek: \"{ d }\",\n deviceForkDiscard: \"{ database }\",\n deviceRestoreStartOwn: \"\",\n deviceRemove: \"{ key }\",\n deviceRename: \"{ key, name }\",\n deviceNewSecret: \"\",\n deviceSecretOfferDismiss: \"\",\n deviceTurnCheck: \"\",\n deviceSetNoticeSeen: \"{ wrong? }\",\n appList: \"\",\n appBuiltIns: \"\",\n appStoreList: \"\",\n appStorePreview: \"{ url }\",\n appStoreAdd: \"{ url, key? }\",\n appStoreRemove: \"{ key }\",\n appStoreRefresh: \"{ key? }?\",\n appPreview: \"AppSource\",\n appInstall: \"{ stage?, digest, grant, asks? }\",\n appUpdateAccept: \"{ ref, sequence?, added? }\",\n appCheckUpdates: \"\",\n appUninstall: \"{ ref }\",\n appRunCheck: \"{ ref }\",\n appFetchFiles: \"{ ref }\",\n appEntry: \"{ ref, runAnyway? }\",\n appFile: \"{ ref, path, digest? }\",\n appFileAt: \"{ ref, path, digest? }\",\n appStorageGet: \"{ ref, scope, key, digest? }\",\n appStorageSet: \"{ ref, scope, key, value, digest? }\",\n appStorageDelete: \"{ ref, scope, key, digest? }\",\n appStorageKeys: \"{ ref, scope, digest? }\",\n appDataExport: \"{ ref }\",\n appDataExportText: \"{ ref }\",\n};\n\n/**\n * The engine's calls the daemon passes through as `engine.<method>` (WISP 1100 § Local control API): exactly the\n * app's `EngineApi`, plus two reads every host has. Nothing else on the engine object is reachable.\n */\nexport const ENGINE_METHODS: readonly string[] = Object.keys(ENGINE_PARAMS);\n\n/** Reads the hosts use outside `EngineApi`: the whole state, and one chat's stored messages. */\nexport const ENGINE_READS: readonly string[] = [\"getState\", \"getMessages\"];\n\n/** What the two reads take, in `ENGINE_PARAMS`' words. */\nexport const READ_PARAMS: Readonly<Record<string, string>> = { getState: \"\", getMessages: \"{ linkId }\" };\n\n/**\n * Why `params` is not what `method` takes: missing when it takes some, or a key it needs not there (a key holding\n * null is there: `setActiveLink { linkId: null }`). Undefined when it is, or when the shape names a type, which is not\n * looked into here.\n */\nexport function engineParamsProblem(method: string, params: Record<string, unknown> | undefined): string | undefined {\n const takes = ENGINE_PARAMS[method] ?? READ_PARAMS[method];\n if (!takes) return undefined;\n if (params === undefined) return takes.endsWith(\"?\") ? undefined : \"no parameters given\";\n const keys = /^\\{ ([\\w?, ]*) \\}\\??$/.exec(takes)?.[1].split(\", \") ?? [];\n const missing = keys.filter((key) => !key.endsWith(\"?\") && params[key] === undefined);\n return missing.length ? `${missing.join(\", \")} missing` : undefined;\n}\n\n/**\n * Calls that delete what this device holds, by what they delete: they go only with `--yes` (`yes: true` over the\n * socket), as `chat remove`, `group leave` and `group forget` ask for it.\n */\nexport const DESTRUCTIVE_CALLS: ReadonlyMap<string, string> = new Map([\n [\"clearProfileData\", \"deletes every chat and group on this device (the wallets stay)\"],\n [\"removeLink\", \"deletes a chat's keys and history on this device\"],\n [\"leaveGroup\", \"deletes a group's history and files on this device\"],\n [\"forgetGroup\", \"deletes a group's history on this device\"],\n [\"switchGroup\", \"leaves the group held under this id and deletes its history on this device\"],\n [\"deviceRemove\", \"takes a device off this profile\"],\n]);\n\n/**\n * Calls whose answer holds a secret (chat seeds, wallet phrases and keys, ecash, backups): the CLI prints their\n * result only with `--show-secret`.\n */\nexport const SECRET_RESULTS: ReadonlySet<string> = new Set([\n \"exportLinks\", \"takeInvite\", \"walletExport\", \"usdtReveal\",\n \"arkBackup\", \"barkBackup\", \"sparkBackup\", \"fedimintBackup\",\n \"usdtExportBackup\", \"arkExportBackup\", \"barkExportBackup\", \"sparkExportBackup\", \"fedimintExportBackup\",\n \"fedimintSpendNotes\",\n]);\n\n/**\n * Calls whose answer holds one secret among what a script needs: the CLI prints it `<hidden>` unless `--show-secret`,\n * as `wallet receive` leaves it out. A Cashu mint quote's id is not locked to a key: whoever holds it can mint the\n * ecash its invoice pays for. A group call's pass (`token`) lets whoever holds it into the call as this member until\n * it expires, and the node's TURN servers come with their passwords, as `settings get` hides them. A group's call key\n * (`groupCallKey`) opens the group's sealed call media. `a[].b` is the `b` of each entry in the list `a`.\n */\nconst SECRET_FIELDS: Readonly<Record<string, readonly string[]>> = {\n walletReceiveLightning: [\"quote\"],\n groupCallToken: [\"token\", \"iceServers[].credential\"],\n groupCallKey: [\"key\"],\n};\n\nexport function hideSecretFields(method: string, result: unknown, showSecret = false): unknown {\n const fields = SECRET_FIELDS[method];\n if (!fields || showSecret || !result || typeof result !== \"object\") return result;\n const shown = { ...(result as Record<string, unknown>) };\n for (const field of fields) {\n const [list, inner] = field.split(\"[].\");\n if (inner === undefined) { if (shown[field] !== undefined) shown[field] = \"<hidden>\"; continue; }\n const entries = shown[list];\n if (Array.isArray(entries)) shown[list] = entries.map((entry: unknown) => entry && typeof entry === \"object\" && (entry as Record<string, unknown>)[inner] !== undefined ? { ...entry, [inner]: \"<hidden>\" } : entry);\n }\n return shown;\n}\n","import { createHash } from \"node:crypto\";\nimport { chatOrGroup, groupOf, node, type ApiContext, type Params } from \"./apiKit\";\n\n/**\n * The id an agent turn names its message by (docs/CLI.md § Agent turns). A message is stored under an id its sender\n * chose most of (`peer_<the id they sent>`), so a turn carries this one instead, made here from the chat (or group) and\n * that id: `t_` and 32 hex digits, in which nobody can write a word. Every command that takes a message's id takes it.\n */\nexport function turnRef(where: string, messageId: string): string {\n return \"t_\" + createHash(\"sha256\").update(`${where}\\n${messageId}`).digest(\"hex\").slice(0, 32);\n}\n\nconst TURN_REF = /^t_[0-9a-f]{32}$/;\nconst isRef = (value: unknown): value is string => typeof value === \"string\" && TURN_REF.test(value);\n\n/** How many turns' ids, older than the newest page, a profile's daemon keeps the answer for. */\nconst REMEMBERED = 1000;\n/**\n * Per node, `<chat or group>\\n<turn's id>` → the id its message is stored under, or null for none: what reading a whole\n * history found, so the reply, reaction and pin of one old turn read it once, and a turn whose message was deleted for\n * everyone (never stored again) once at all. Oldest asked first out.\n */\nconst remembered = new WeakMap<object, Map<string, string | null>>();\n\n/**\n * `params` with each turn's id in `message`, `reply`, `messages`, `before` and `after` as the id its message is stored\n * under: looked for among the chat's (or group's) newest messages first, where a turn's almost always is, then in what an\n * earlier read of all of them found, then in all of them. One that names no message stays as given, and its command says\n * so as for any unknown id. A timestamp in `before` or `after` is no turn's id and stays as it is.\n */\nexport async function withStoredIds(ctx: ApiContext, params: Params): Promise<Params> {\n const wanted = new Set([params.message, params.reply, params.before, params.after, ...(Array.isArray(params.messages) ? params.messages : [])].filter(isRef));\n if (!wanted.size) return params;\n let target: { id: string; linkId: string; group: boolean } | null = null;\n try {\n if (typeof params.group === \"string\") { const group = groupOf(ctx, { group: params.group }); target = { id: group.id, linkId: `group:${group.id}`, group: true }; }\n else if (typeof params.chat === \"string\") target = chatOrGroup(ctx, params.chat);\n } catch { /* the command says what is wrong with its chat or group */ }\n if (!target) return params;\n const { id, linkId, group } = target;\n const found = new Map<string, string>();\n const look = (messages: readonly { id: string }[]) => {\n for (const message of messages) { const ref = turnRef(id, message.id); if (wanted.has(ref)) found.set(ref, message.id); }\n return found.size === wanted.size;\n };\n if (!look((await node(ctx).messagePage({ linkId, limit: 200 })).messages)) {\n let known = remembered.get(node(ctx));\n if (!known) remembered.set(node(ctx), known = new Map());\n const unknown = new Set<string>();\n for (const ref of wanted) {\n if (found.has(ref)) continue;\n const key = `${id}\\n${ref}`, kept = known.get(key);\n if (kept === undefined) { unknown.add(ref); continue; }\n known.delete(key);\n // Deleted since: it names none now (and its refusal names the turn's id, not the one its sender chose).\n const now = kept !== null && await node(ctx).getMessage(linkId, kept) ? kept : null;\n known.set(key, now);\n if (now !== null) found.set(ref, now);\n }\n if (unknown.size) {\n look(group ? await node(ctx).groupMessages({ groupId: id }) : await node(ctx).getMessages(linkId));\n for (const ref of unknown) {\n known.set(`${id}\\n${ref}`, found.get(ref) ?? null);\n if (known.size > REMEMBERED) known.delete(known.keys().next().value!);\n }\n }\n }\n const stored = (value: unknown) => (isRef(value) ? found.get(value) ?? value : value);\n return {\n ...params,\n ...(params.message !== undefined && { message: stored(params.message) }),\n ...(params.reply !== undefined && { reply: stored(params.reply) }),\n ...(params.before !== undefined && { before: stored(params.before) }),\n ...(params.after !== undefined && { after: stored(params.after) }),\n ...(Array.isArray(params.messages) && { messages: params.messages.map(stored) }),\n };\n}\n","import type { PairedTransport } from \"@ghostly/core\";\n\n/**\n * The words an argument takes, for the API's methods and the command table both: the command line refuses any other\n * before the profile opens (`commands/index.ts` positionals), and the socket keeps its own refusal for its callers.\n * Its own module, with no code from the package: the command table is read by every command.\n */\n\nexport const WALLET_TYPES = [\"cashu\", \"lightning\", \"arkade\", \"bark\", \"spark\", \"bitcoin\", \"fedimint\", \"usdt\"] as const;\n/** The wallets that have an address to be paid on (`wallet address`). */\nexport const ADDRESS_TYPES = [\"bitcoin\", \"arkade\", \"spark\", \"usdt\"] as const;\n/** What a payment request may name as its way of paying (`chat request --method`). */\nexport const PAY_METHODS = [\"cashu\", \"arkade\", \"usdt\", \"bark\", \"bitcoin\", \"fedimint\", \"spark\"] as const;\n/** The ways of paying a chat takes (`chat accept`). */\nexport const CHAT_METHODS = [\"cashu\", \"lightning\", ...PAY_METHODS.filter((m) => m !== \"cashu\")] as const;\n\n/** A chat's transport by the name the command line gives it (`chat transport`). */\nexport const TRANSPORT_NAMES: Record<string, PairedTransport | \"auto\" | \"dht\"> = {\n auto: \"auto\", dht: \"dht\", webrtc: \"webrtc/1\", iroh: \"iroh/1\", hyperdht: \"hyperdht/1\",\n \"webrtc/1\": \"webrtc/1\", \"iroh/1\": \"iroh/1\", \"hyperdht/1\": \"hyperdht/1\",\n};\n","import { reactionEmoji, sanitizeDisplayText, sanitizeStatusText, STATUS_AVAILABILITIES, STATUS_TEXT_MAX, type PersonStatus, type StatusAvailability } from \"@ghostly/core\";\nimport { STATUS_CARD_LIMITS } from \"@ghostly/core/statusCards\";\nimport { CliError, type ErrorCode, shownValue } from \"./errors\";\n\n/**\n * This profile's status (WISP 401 § Presence and status): a text, one emoji, an availability and when it ends, said to\n * every paired contact whose app offers `status/1`: `status set|clear|show`, and the socket's `status.set|clear|get`.\n * These never say presence (active or idle): only a daemon does, and only with `settings set daemonPresence true`\n * (daemonPresence.ts); otherwise a headless profile never reads as online.\n */\n\n/** What `status set` was given, before it is checked. */\nexport interface StatusInput { text?: string; emoji?: string; availability?: string; until?: number }\n\n/**\n * The status as the engine keeps it (`personStatus`), checked first: the engine drops a field that does not hold\n * without a word (a long text cut, a word that is not one emoji left out, an end already past clearing the whole\n * status), so here each is refused instead, named by `name` (the command's option, or the socket's parameter).\n */\nexport function checkOwnStatus(input: StatusInput, name: (field: keyof StatusInput) => string, code: ErrorCode, now = Date.now()): PersonStatus {\n const fail = (field: keyof StatusInput, rule: string) => new CliError(code, `${name(field)} ${rule}`);\n const status: PersonStatus = {};\n if (input.availability !== undefined) {\n if (!(STATUS_AVAILABILITIES as readonly string[]).includes(input.availability)) throw fail(\"availability\", `takes ${STATUS_AVAILABILITIES.join(\", \")}, not ${shownValue(input.availability)}`);\n status.availability = input.availability as StatusAvailability;\n }\n if (input.emoji !== undefined) {\n const emoji = reactionEmoji(input.emoji);\n if (!emoji) throw fail(\"emoji\", `takes one emoji, not ${shownValue(input.emoji)}`);\n status.emoji = emoji;\n }\n // One line, as contacts see it: a line break or a run of spaces is one space; invisible characters are not counted.\n const oneLine = input.text?.replace(/\\s+/g, \" \").trim();\n if (oneLine) {\n const shown = sanitizeDisplayText(oneLine, Infinity) ?? \"\";\n const length = [...shown].length;\n if (length > STATUS_TEXT_MAX) throw fail(\"text\", `is up to ${STATUS_TEXT_MAX} characters, not ${length} characters`);\n if (!shown) throw fail(\"text\", \"needs a character that shows\");\n // The text as counted: the raw one could lose characters that fit to the engine's cut of invisible padding.\n const text = sanitizeStatusText(shown);\n if (!text) throw fail(\"text\", \"is plain text: no link or markup\");\n status.text = text;\n }\n if (!status.text && !status.emoji && !status.availability) {\n throw new CliError(code, `Nothing to set: give a ${name(\"text\")}, ${name(\"emoji\")} or ${name(\"availability\")}`);\n }\n if (input.until !== undefined) {\n if (!Number.isSafeInteger(input.until) || input.until <= now) throw fail(\"until\", \"is a time to come: a status that ended is none\");\n // As the command line's --until, so the socket cannot keep an end past the last time a Date holds.\n if (input.until > now + STATUS_CARD_LIMITS.nextRunMs) throw fail(\"until\", \"is a time within a year from now\");\n status.until = input.until;\n }\n return status;\n}\n\n/** What `status set|clear|show` answer: the status with every field (null when not set), or null when there is none. */\nexport function statusJson(status: PersonStatus | undefined): { status: { text: string | null; emoji: string | null; availability: StatusAvailability | null; until: number | null } | null } {\n return { status: status ? { text: status.text ?? null, emoji: status.emoji ?? null, availability: status.availability ?? null, until: status.until ?? null } : null };\n}\n"],"mappings":";;;;;;;;;;;;AAMA,IAAa,gBAAkD;CAC7D,YAAY;CACZ,YAAY;CACZ,YAAY;CACZ,UAAU;CACV,aAAa;CACb,kBAAkB;CAClB,mBAAmB;CACnB,WAAW;CACX,WAAW;CACX,SAAS;CACT,WAAW;CACX,iBAAiB;CACjB,kBAAkB;CAClB,YAAY;CACZ,YAAY;CACZ,YAAY;CACZ,YAAY;CACZ,kBAAkB;CAClB,mBAAmB;CACnB,aAAa;CACb,WAAW;CACX,iBAAiB;CACjB,cAAc;CACd,eAAe;CACf,iBAAiB;CACjB,oBAAoB;CACpB,sBAAsB;CACtB,iBAAiB;CACjB,kBAAkB;CAClB,gBAAgB;CAChB,sBAAsB;CACtB,uBAAuB;CACvB,uBAAuB;CACvB,aAAa;CACb,aAAa;CACb,mBAAmB;CACnB,oBAAoB;CACpB,cAAc;CACd,sBAAsB;CACtB,gBAAgB;CAChB,gBAAgB;CAChB,kBAAkB;CAClB,eAAe;CACf,uBAAuB;CACvB,qBAAqB;CACrB,kBAAkB;CAClB,iBAAiB;CACjB,mBAAmB;CACnB,oBAAoB;CACpB,uBAAuB;CACvB,qBAAqB;CACrB,qBAAqB;CACrB,o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M,QAAQ,MAAM,mBAAmB,WAAW,MAAM,KAAK,SAAS,kCAAkC;EAC5G,OAAO,QAAQ,MAAM;CACvB;CACA,OAAO;AACT;;AAGA,SAAgB,WAAW,QAAmK;CAC5L,OAAO,EAAE,QAAQ,SAAS;EAAE,MAAM,OAAO,QAAQ;EAAM,OAAO,OAAO,SAAS;EAAM,cAAc,OAAO,gBAAgB;EAAM,OAAO,OAAO,SAAS;CAAK,IAAI,KAAK;AACtK"}
@@ -1,5 +1,5 @@
1
1
  import { c as toBase64, d as utf8Decode, f as utf8Encode, i as fromBase64Url, l as toBase64Url, n as concatBytes, r as fromBase64, s as randomBytes } from "./bytes-C1DNGY18.js";
2
- import { s as isPublicAddress } from "./domainProofs-BDNP1dIy.js";
2
+ import { s as isPublicAddress } from "./domainProofs-b3Y1Gj9g.js";
3
3
  import { S as verify, _ as identityFromSeed, o as measureRecords, v as identityFromSeedB64, x as sign, y as publicKeyFromZ32 } from "./pkarr-BQo4PcCg.js";
4
4
  import { xsalsa20poly1305 } from "@noble/ciphers/salsa.js";
5
5
  import { ed25519, x25519 } from "@noble/curves/ed25519.js";
@@ -371,7 +371,7 @@ function isHoldUrl(value, loopback = false) {
371
371
  return false;
372
372
  }
373
373
  if (url.username || url.password) return false;
374
- const host = url.hostname.toLowerCase().replace(/\.$/, "");
374
+ const host = url.hostname.toLowerCase().replace(/\.+$/, "");
375
375
  if (loopback && url.protocol === "http:" && [
376
376
  "localhost",
377
377
  "127.0.0.1",
@@ -578,4 +578,4 @@ function transportOrder(available, preferred, fallback) {
578
578
  }
579
579
  export { generateEncryptionKey as C, encrypt as S, tryDecrypt as T, HoldKeys as _, checkedDescriptors as a, newMailbox as b, irohRelayUrl as c, relayUrlTooLong as d, relayedTransports as f, HOLD_LIMITS as g, HOLD_DATED_BACK_MS as h, automaticTransport as i, rankTransports as l, HOLD_CAPABILITY as m, RELAY_WITH_SECRETS as n, dialableIrohRelay as o, transportOrder as p, TRANSPORTS as r, irohDescriptor as s, RELAY_URL as t, relayUrl as u, HoldRefusedError as v, sealedLength as w, readManifest as x, isHoldUrl as y };
580
580
 
581
- //# sourceMappingURL=pairedTransports-BKmvlKz1.js.map
581
+ //# sourceMappingURL=pairedTransports-Dppn8lUN.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pairedTransports-Dppn8lUN.js","names":[],"sources":["../../../core/src/crypto.ts","../../../core/src/storeForward.ts","../../../core/src/pairedTransports.ts"],"sourcesContent":["import { xsalsa20poly1305 } from \"@noble/ciphers/salsa.js\";\nimport { concatBytes, fromBase64, randomBytes, toBase64, utf8Decode, utf8Encode } from \"./bytes\";\n\nconst NONCE_LENGTH = 24;\nconst KEY_LENGTH = 32;\n\nexport function generateEncryptionKey(): Uint8Array {\n return randomBytes(KEY_LENGTH);\n}\n\n/**\n * NaCl secretbox (XSalsa20-Poly1305). Wire format matches the Rust\n * implementation in `apps/desktop/src/crypto.rs`: base64(nonce || box).\n */\nexport function encrypt(plaintext: string, key: Uint8Array): string {\n if (key.length !== KEY_LENGTH) throw new Error(\"Invalid key length: expected 32 bytes\");\n const nonce = randomBytes(NONCE_LENGTH);\n const box = xsalsa20poly1305(key, nonce).encrypt(utf8Encode(plaintext));\n return toBase64(concatBytes(nonce, box));\n}\n\n/** The length of what `encrypt` returns for a plaintext of this many UTF-8 bytes: base64 of nonce, box and 16-byte tag. */\nexport function sealedLength(plaintextBytes: number): number {\n return 4 * Math.ceil((NONCE_LENGTH + 16 + plaintextBytes) / 3);\n}\n\nexport function decrypt(encoded: string, key: Uint8Array): string {\n if (key.length !== KEY_LENGTH) throw new Error(\"Invalid key length: expected 32 bytes\");\n const combined = fromBase64(encoded);\n if (combined.length < NONCE_LENGTH + 1) throw new Error(\"Invalid ciphertext: too short\");\n const nonce = combined.subarray(0, NONCE_LENGTH);\n const box = combined.subarray(NONCE_LENGTH);\n return utf8Decode(xsalsa20poly1305(key, nonce).decrypt(box));\n}\n\nexport function tryDecrypt(encoded: string, key: Uint8Array): string | null {\n try {\n return decrypt(encoded, key);\n } catch {\n return null;\n }\n}\n","import { ed25519, x25519 } from \"@noble/curves/ed25519.js\";\nimport { xsalsa20poly1305 } from \"@noble/ciphers/salsa.js\";\nimport { hkdf } from \"@noble/hashes/hkdf.js\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { concatBytes, fromBase64Url, randomBytes, toBase64Url, utf8Decode, utf8Encode } from \"./bytes\";\nimport { encrypt, tryDecrypt } from \"./crypto\";\nimport { isPublicAddress } from \"./domainProofs\";\nimport { identityFromSeed, identityFromSeedB64, publicKeyFromZ32, sign, verify, type Identity } from \"./identity\";\nimport type { LinkParams } from \"./invite\";\nimport { measureRecords, MAX_DNS_PACKET_BYTES, type GhostRecord, type SignedPacket } from \"./pkarr\";\n\n/**\n * Store-and-forward for an away contact (WISP 404 draft, `hold/1`).\n *\n * What a person sends while the contact is away is sealed into a *bundle* (signed by the sender's\n * participation key, then encrypted to a key only the two of them can derive), put in the sender's\n * own storage (WISP 1000), and named in a *manifest* the storage also holds. A small signed, encrypted\n * *pointer* record on a per-link Pkarr key tells the contact where the manifest is (a URL that expires)\n * and which of the contact's own bundles have been received. Storage and relays see ciphertext, sizes\n * and timing only. Nothing here promises forward secrecy or retention beyond the bounds below.\n */\nexport const HOLD_CAPABILITY = \"hold/1\" as const;\nexport const HOLD_LIMITS = {\n /** One bundle, ciphertext and header included: a picture, not a video. */\n maxBundleBytes: 8 * 1024 * 1024,\n /** All bundles held for one contact at once. */\n maxMailboxBytes: 64 * 1024 * 1024,\n maxMailboxBundles: 64,\n /** A bundle not picked up by then is dropped by its sender. The longest a presigned URL lives, too. */\n ttlMs: 7 * 24 * 60 * 60_000,\n maxTextBytes: 16 * 1024,\n maxPaymentRequestBytes: 64 * 1024,\n maxManifestBytes: 64 * 1024,\n /**\n * How far past one lifetime from now an expiry may reach by the reader's clock: the sender's clock may be ahead, and\n * a day covers any clock that is merely wrong. Nothing else about a pointer or a bundle is held against this clock.\n */\n clockSkewMs: 24 * 60 * 60_000,\n} as const;\n/**\n * How far before its own clock a sender dates its pointer and its manifest, and ends the lifetimes it gives. A reader\n * refuses nothing for those dates: `rev` orders pointers and `seq` orders items, both kept by the reader. Apps up to\n * 1.0.2 refuse a pointer or a manifest dated more than a minute past their clock, and an expiry more than a minute\n * past one lifetime from now, each without a word: the items of a sender whose clock ran two minutes fast were never\n * fetched. Dated back, a sender up to about eleven minutes ahead is read by them.\n */\nexport const HOLD_DATED_BACK_MS = 10 * 60_000;\n\nexport type HoldKind = \"text\" | \"file\" | \"pay-req\" | \"manifest\";\nconst KINDS: readonly string[] = [\"text\", \"file\", \"pay-req\", \"manifest\"];\nconst WIRE_ID = /^[A-Za-z0-9_-]{8,64}$/;\nconst MAILBOX = /^[A-Za-z0-9_-]{22}$/;\nconst SIG = /^[A-Za-z0-9_-]{86}$/;\nconst MAGIC = utf8Encode(\"GHLD\");\nconst VERSION = 1;\nconst NONCE = 24;\n/** A bundle sealed by the chat's ratchet (WISP 4xx § Held items). */\nconst RATCHETED = 2;\ntype HoldItem = { mailbox: string; seq: number; id: string; ts: number; kind: HoldKind; meta?: unknown; expires: number };\n\nexport interface HoldFileMeta { name: string; size: number; mime: string }\n/** One held bundle as the manifest lists it: where to get it, and what to expect. */\nexport type HoldManifestEntry = [seq: number, id: string, kind: Exclude<HoldKind, \"manifest\">, bytes: number, url: string, expires: number];\nexport interface HoldHeader {\n v: 1;\n /** Rendezvous keys, as the sender sees the link. */\n from: string;\n to: string;\n /** Participation keys: who signed, who may open. */\n author: string;\n recipient: string;\n mailbox: string;\n seq: number;\n id: string;\n ts: number;\n kind: HoldKind;\n meta: unknown;\n /** base64url SHA-256 of the body. */\n digest: string;\n expires: number;\n}\nexport interface HoldPointer {\n rev: number;\n issued: number;\n /** When the manifest URL stops working. */\n expires: number;\n manifestUrl: string | null;\n /** Highest sequence the publisher has held for the reader. */\n top: number;\n /** Highest sequence the publisher received from the reader. */\n ack: number;\n count: number;\n bytes: number;\n /** Sequences of the reader's items this publisher refused (changed, oversized, not for it): at most the last 32. */\n refused: number[];\n}\n\n/** Why a bundle, manifest or pointer was refused. Never a reason to trust it a little. */\nexport class HoldRefusedError extends Error {\n /** The bytes the chat's ratchet opened, when it opened them before the item was refused: the caller commits them. */\n ratcheted?: Uint8Array;\n constructor(readonly reason: \"size\" | \"format\" | \"tampered\" | \"not-for-me\" | \"author\" | \"signature\" | \"digest\" | \"limits\" | \"expired\" | \"plain\", message: string) {\n super(message);\n }\n}\n\nconst bodyDigest = (body: Uint8Array) => toBase64Url(sha256(body));\nconst newMailbox = () => toBase64Url(randomBytes(16)).slice(0, 22);\nexport { newMailbox as newHoldMailbox };\n\n/**\n * Everything derived once per link for this feature: my pointer key, the contact's pointer address and\n * the key that seals bundles and pointers between the two participation keys. Needs a pinned contact.\n */\nexport class HoldKeys {\n readonly from: string;\n readonly to: string;\n readonly me: string;\n readonly peer: string;\n /** Publishes my pointer. */\n readonly identity: Identity;\n /** Where the contact publishes its pointer. */\n readonly peerAddress: string;\n private readonly seed: Uint8Array;\n private readonly sealKey: Uint8Array;\n\n constructor(params: LinkParams, participationSeedB64: string, peerKey: string) {\n this.from = identityFromSeedB64(params.seedB64).pubKeyZ32;\n this.to = params.peerPubKeyZ32;\n const mine = identityFromSeedB64(participationSeedB64);\n this.seed = mine.seed;\n this.me = mine.pubKeyZ32;\n this.peer = peerKey;\n const secret = fromBase64Url(params.encKeyB64);\n const context = JSON.stringify([\"ghostly-hold/1\", [this.from, this.to].sort()]);\n const derive = (label: string) => hkdf(sha256, secret, utf8Encode(context), utf8Encode(label), 32);\n this.identity = identityFromSeed(derive(`pointer:${this.from}`));\n this.peerAddress = identityFromSeed(derive(`pointer:${this.to}`)).pubKeyZ32;\n const shared = x25519.getSharedSecret(ed25519.utils.toMontgomerySecret(this.seed), ed25519.utils.toMontgomery(publicKeyFromZ32(peerKey)));\n this.sealKey = hkdf(sha256, shared, derive(\"envelope\"), utf8Encode(\"ghostly-hold-envelope/1\"), 32);\n }\n\n /** Seals one item for the contact: signed with my participation key, encrypted to our shared key. */\n seal(item: HoldItem, body: Uint8Array): Uint8Array {\n const nonce = randomBytes(NONCE);\n const box = xsalsa20poly1305(this.sealKey, nonce).encrypt(this.inner(item, body));\n return concatBytes(MAGIC, new Uint8Array([VERSION]), nonce, box);\n }\n /**\n * The same item as a version-2 bundle (WISP 4xx § Held items): the same plaintext, sealed by the chat's ratchet\n * (`seal`, which saves the ratchet's state before it returns), so the bundle can be uploaded once this returns.\n */\n async sealRatcheted(item: HoldItem, body: Uint8Array, seal: (plaintext: Uint8Array) => Promise<Uint8Array>): Promise<Uint8Array> {\n return concatBytes(MAGIC, new Uint8Array([RATCHETED]), await seal(this.inner(item, body)));\n }\n /** What a bundle seals: the header's length, the signed header, the body. */\n private inner(item: HoldItem, body: Uint8Array): Uint8Array {\n const fields = [VERSION, this.from, this.to, this.me, this.peer, item.mailbox, item.seq, item.id, item.ts, item.kind, item.meta ?? null, bodyDigest(body), item.expires];\n const signature = toBase64Url(sign(utf8Encode(JSON.stringify([\"ghostly-hold-bundle\", fields])), this.seed));\n const header = utf8Encode(JSON.stringify([fields, signature]));\n const length = new Uint8Array(4);\n new DataView(length.buffer).setUint32(0, header.length);\n return concatBytes(length, header, body);\n }\n\n /**\n * Opens a bundle the contact sealed for me. Everything is checked before anything is returned: the\n * authenticated encryption, the header's shape, that it names this link, this contact and me, the\n * signature, the body digest and the limits of its kind. `loopback`: see `isHoldUrl`.\n */\n /**\n * `ratchet`: opens a version-2 bundle's sealed bytes (WISP 4xx), without keeping anything; absent, one is from a newer\n * Ghostly. `refusePlain`: a ratcheted item from this contact opened here, so a version-1 item other than the manifest is\n * refused (WISP 4xx § Downgrade). `ratcheted` in the result: the bytes the ratchet opened, for the caller to commit once\n * the item is stored.\n */\n open(bytes: Uint8Array, expect: { maxBytes?: number; mailbox?: string; now?: number; loopback?: boolean; ratchet?: (sealed: Uint8Array) => Uint8Array | null; refusePlain?: boolean } = {}): { header: HoldHeader; body: Uint8Array; ratcheted?: Uint8Array } {\n const now = expect.now ?? Date.now();\n if (bytes.length > (expect.maxBytes ?? HOLD_LIMITS.maxBundleBytes)) throw new HoldRefusedError(\"size\", \"The held item is larger than allowed\");\n if (bytes.length < MAGIC.length + 1 + 16 + 4 || !MAGIC.every((b, i) => bytes[i] === b)) throw new HoldRefusedError(\"format\", \"Not a held item\");\n const version = bytes[MAGIC.length];\n if (version !== VERSION && (version !== RATCHETED || !expect.ratchet)) throw new HoldRefusedError(\"format\", \"Held item from a newer Ghostly\");\n let plain: Uint8Array | null, ratcheted: Uint8Array | undefined;\n if (version === RATCHETED) {\n ratcheted = bytes.subarray(MAGIC.length + 1);\n try { plain = expect.ratchet!(ratcheted); } catch { plain = null; }\n if (!plain) throw new HoldRefusedError(\"tampered\", \"The held item was changed, is not for this chat, or was opened already\");\n } else {\n if (bytes.length < MAGIC.length + 1 + NONCE + 16 + 4) throw new HoldRefusedError(\"format\", \"Not a held item\");\n try { plain = xsalsa20poly1305(this.sealKey, bytes.subarray(MAGIC.length + 1, MAGIC.length + 1 + NONCE)).decrypt(bytes.subarray(MAGIC.length + 1 + NONCE)); }\n catch { throw new HoldRefusedError(\"tampered\", \"The held item was changed or is not for this chat\"); }\n }\n try { return this.read(plain, ratcheted, expect, now); }\n catch (error) {\n // Opened, then refused: the ratchet's bytes go with the refusal, so the key is used up and the lane heard all the same.\n if (error instanceof HoldRefusedError && ratcheted) error.ratcheted = ratcheted;\n throw error;\n }\n }\n /** The checks of `open` once the bundle is decrypted. */\n private read(plain: Uint8Array, ratcheted: Uint8Array | undefined, expect: { mailbox?: string; loopback?: boolean; refusePlain?: boolean }, now: number): { header: HoldHeader; body: Uint8Array; ratcheted?: Uint8Array } {\n if (plain.length < 4) throw new HoldRefusedError(\"format\", \"Not a held item\");\n const headerLength = new DataView(plain.buffer, plain.byteOffset, 4).getUint32(0);\n if (headerLength > 128 * 1024 || 4 + headerLength > plain.length) throw new HoldRefusedError(\"format\", \"Not a held item\");\n let parsed: unknown;\n try { parsed = JSON.parse(utf8Decode(plain.subarray(4, 4 + headerLength))); } catch { throw new HoldRefusedError(\"format\", \"Not a held item\"); }\n if (!Array.isArray(parsed) || parsed.length !== 2 || !Array.isArray(parsed[0]) || parsed[0].length !== 13 || typeof parsed[1] !== \"string\" || !SIG.test(parsed[1])) throw new HoldRefusedError(\"format\", \"Not a held item\");\n const [fields, signature] = parsed as [unknown[], string];\n const [v, from, to, author, recipient, mailbox, seq, id, ts, kind, meta, digest, expires] = fields;\n if (v !== VERSION || typeof from !== \"string\" || typeof to !== \"string\" || typeof author !== \"string\" || typeof recipient !== \"string\" || typeof mailbox !== \"string\" || !MAILBOX.test(mailbox) ||\n !Number.isSafeInteger(seq) || (seq as number) < 0 || typeof id !== \"string\" || !WIRE_ID.test(id) || !Number.isSafeInteger(ts) || (ts as number) <= 0 ||\n typeof kind !== \"string\" || !KINDS.includes(kind) || typeof digest !== \"string\" || !Number.isSafeInteger(expires)) throw new HoldRefusedError(\"format\", \"Not a held item\");\n // Both directions of this link are sealed with the same key: the header says which one this is.\n if (from !== this.to || to !== this.from || recipient !== this.me) throw new HoldRefusedError(\"not-for-me\", \"The held item is for another chat\");\n if (author !== this.peer) throw new HoldRefusedError(\"author\", \"The held item was not signed by this contact\");\n if (expect.mailbox && mailbox !== expect.mailbox) throw new HoldRefusedError(\"not-for-me\", \"The held item is from another mailbox\");\n let valid: boolean;\n try { valid = verify(fromBase64Url(signature), utf8Encode(JSON.stringify([\"ghostly-hold-bundle\", fields])), publicKeyFromZ32(author)); } catch { valid = false; }\n if (!valid) throw new HoldRefusedError(\"signature\", \"The held item's signature does not check out\");\n const body = plain.subarray(4 + headerLength);\n if (bodyDigest(body) !== digest) throw new HoldRefusedError(\"digest\", \"The held item's content does not match its header\");\n // Its `ts` is its sender's clock, often minutes from this one: nothing is refused for it. It was, past a minute\n // ahead, and for good: the item's sequence was passed, and its sender told \"could not be verified as yours, or was\n // too large\". What stops an item from being taken twice is its sequence (the manifest's, the pointer's `rev`).\n // The item may be older than its upload (a retry, a message written offline); its expiry may not reach past one\n // lifetime from now, give or take what the sender's clock is ahead.\n if ((expires as number) <= (ts as number) || (expires as number) > now + HOLD_LIMITS.ttlMs + HOLD_LIMITS.clockSkewMs) throw new HoldRefusedError(\"limits\", \"The held item's lifetime is out of bounds\");\n const header: HoldHeader = { v: 1, from, to, author, recipient, mailbox, seq: seq as number, id, ts: ts as number, kind: kind as HoldKind, meta, digest, expires: expires as number };\n // The manifest is always sealed as before; anything else from a contact whose items come ratcheted must be ratcheted.\n if (!ratcheted && expect.refusePlain && kind !== \"manifest\") throw new HoldRefusedError(\"plain\", \"The held item was sealed without forward secrecy, which this chat no longer takes\");\n checkKind(header, body, expect.loopback);\n return { header, body, ...(ratcheted && { ratcheted }) };\n }\n\n /** My pointer, as records to publish under `identity`. Throws when it cannot fit a packet. */\n pointerRecords(pointer: HoldPointer, now = Date.now()): GhostRecord[] {\n const body = [VERSION, pointer.rev, pointer.issued, pointer.expires, pointer.manifestUrl, pointer.top, pointer.ack, pointer.count, pointer.bytes, pointer.refused.slice(-32)];\n const signature = toBase64Url(sign(utf8Encode(JSON.stringify([\"ghostly-hold-pointer\", this.from, this.to, body])), this.seed));\n const ttl = Math.min(24 * 3600, Math.max(60, Math.ceil((pointer.expires - now) / 1000)));\n const records = [{ label: \"_hold\", value: encrypt(JSON.stringify([body, signature]), this.sealKey), ttl }];\n if (measureRecords(this.identity.pubKeyZ32, records) > MAX_DNS_PACKET_BYTES) throw new Error(\"The storage address is too long for a DHT packet. Use a shorter endpoint or prefix.\");\n return records;\n }\n\n /**\n * The contact's pointer out of its packet, or null when the packet is not one of its pointers. Its `issued` is the\n * contact's clock and refuses nothing: an older pointer cannot take a newer one's place because of `rev`. The\n * manifest's address is held to what an item's is (`isHoldUrl`): it is fetched as soon as the pointer is read.\n */\n readPointer(packet: SignedPacket, loopback = false): HoldPointer | null {\n if (packet.pubKeyZ32 !== this.peerAddress || measureRecords(packet.pubKeyZ32, packet.records) > MAX_DNS_PACKET_BYTES) return null;\n const records = packet.records.filter(r => r.label === \"_hold\");\n if (records.length !== 1) return null;\n const plain = tryDecrypt(records[0].value, this.sealKey);\n if (!plain) return null;\n let parsed: unknown;\n try { parsed = JSON.parse(plain); } catch { return null; }\n if (!Array.isArray(parsed) || parsed.length !== 2 || !Array.isArray(parsed[0]) || (parsed[0].length !== 9 && parsed[0].length !== 10) || typeof parsed[1] !== \"string\" || !SIG.test(parsed[1])) return null;\n const [body, signature] = parsed as [unknown[], string];\n const [v, rev, issued, expires, manifestUrl, top, ack, count, bytes, refused = []] = body;\n if (v !== VERSION || ![rev, issued, expires, top, ack, count, bytes].every(n => Number.isSafeInteger(n) && (n as number) >= 0) ||\n (manifestUrl !== null && !isHoldUrl(manifestUrl, loopback)) ||\n !Array.isArray(refused) || refused.length > 32 || !refused.every(n => Number.isSafeInteger(n) && (n as number) > 0)) return null;\n try {\n if (!verify(fromBase64Url(signature), utf8Encode(JSON.stringify([\"ghostly-hold-pointer\", this.to, this.from, body])), publicKeyFromZ32(this.peer))) return null;\n } catch { return null; }\n return { rev: rev as number, issued: issued as number, expires: expires as number, manifestUrl: manifestUrl as string | null, top: top as number, ack: ack as number, count: count as number, bytes: bytes as number, refused: refused as number[] };\n }\n}\n\n/** Names only a local network answers (RFC 6762, RFC 8375, ICANN's .internal, and the usual router ones). */\nconst LOCAL_SUFFIXES = [\"localhost\", \"local\", \"internal\", \"lan\", \"home\", \"home.arpa\", \"localdomain\", \"intranet\", \"corp\"];\n\n/**\n * A URL a bundle or manifest may be fetched from. The contact chose it and this device fetches it on its own, so it\n * is HTTPS, without a user or password, at a public name or a public IPv4 address: never this machine or its network.\n * A name with no dot or under a local suffix is a local one. A public name may still resolve to a local address:\n * where the host can resolve, its `fetch` refuses that too (the CLI's, packages/cli/src/runtime/holdFetch.ts, and\n * Desktop's, apps/desktop/src/hold_fetch.rs).\n * `loopback` adds plain HTTP to this machine, for a test against a local server; no shipped app passes it.\n */\nexport function isHoldUrl(value: unknown, loopback = false): value is string {\n if (typeof value !== \"string\" || value.length > 2048) return false;\n let url: URL;\n try { url = new URL(value); } catch { return false; }\n if (url.username || url.password) return false;\n const host = url.hostname.toLowerCase().replace(/\\.+$/, \"\");\n if (loopback && url.protocol === \"http:\" && [\"localhost\", \"127.0.0.1\", \"[::1]\"].includes(host)) return true;\n if (url.protocol !== \"https:\" || !host.includes(\".\") || host.startsWith(\"[\") || LOCAL_SUFFIXES.some(s => host === s || host.endsWith(`.${s}`))) return false;\n // A URL's IPv4 host is always written as four decimal numbers, whatever form it was given in.\n return !/^\\d+\\.\\d+\\.\\d+\\.\\d+$/.test(host) || isPublicAddress(Uint8Array.from(host.split(\".\"), Number));\n}\n\n/** The limits of each kind, on the way in. */\nfunction checkKind(header: HoldHeader, body: Uint8Array, loopback = false): void {\n const bad = (message: string) => new HoldRefusedError(\"limits\", message);\n switch (header.kind) {\n case \"text\":\n if (body.length > HOLD_LIMITS.maxTextBytes) throw bad(\"The held text is too long\");\n try { utf8Decode(body); } catch { throw bad(\"The held text is not text\"); }\n return;\n case \"pay-req\":\n if (body.length > HOLD_LIMITS.maxPaymentRequestBytes) throw bad(\"The held payment request is too large\");\n return;\n case \"file\": {\n const meta = header.meta as Partial<HoldFileMeta> | null;\n if (!meta || typeof meta !== \"object\" || typeof meta.name !== \"string\" || meta.name.length > 255 || typeof meta.mime !== \"string\" || meta.mime.length > 255 || meta.size !== body.length) throw bad(\"The held file does not match its description\");\n return;\n }\n case \"manifest\": {\n if (body.length !== 0) throw bad(\"A manifest carries no body\");\n readManifest(header.meta, loopback);\n return;\n }\n }\n}\n\n/** The entries of a manifest, checked: strictly increasing sequences, bounded sizes, fetchable URLs. */\nexport function readManifest(meta: unknown, loopback = false): HoldManifestEntry[] {\n const bad = (message: string) => new HoldRefusedError(\"limits\", message);\n const entries = (meta as { entries?: unknown } | null)?.entries;\n if (!Array.isArray(entries) || entries.length > HOLD_LIMITS.maxMailboxBundles) throw bad(\"The manifest lists too many items\");\n let last = 0, total = 0;\n const out: HoldManifestEntry[] = [];\n for (const entry of entries) {\n if (!Array.isArray(entry) || entry.length !== 6) throw bad(\"The manifest is malformed\");\n const [seq, id, kind, bytes, url, expires] = entry;\n if (!Number.isSafeInteger(seq) || seq <= last || typeof id !== \"string\" || !WIRE_ID.test(id) || typeof kind !== \"string\" || !KINDS.includes(kind) || kind === \"manifest\" ||\n !Number.isSafeInteger(bytes) || bytes < 0 || bytes > HOLD_LIMITS.maxBundleBytes || !isHoldUrl(url, loopback) || !Number.isSafeInteger(expires)) throw bad(\"The manifest is malformed\");\n last = seq; total += bytes;\n if (total > HOLD_LIMITS.maxMailboxBytes) throw bad(\"The manifest lists more than a mailbox may hold\");\n out.push([seq, id, kind as HoldManifestEntry[2], bytes, url, expires]);\n }\n return out;\n}\n","import type { FrameChannel } from \"./frames\";\nimport { isHoldUrl } from \"./storeForward\";\n\nexport const TRANSPORTS = [\"iroh/1\", \"hyperdht/1\", \"webrtc/1\"] as const;\nexport type PairedTransport = typeof TRANSPORTS[number];\nexport type NativeTransport = Exclude<PairedTransport, \"webrtc/1\">;\n\n/** Supplied only by the local adapter after its real cryptographic handshake.\n * Iroh uses a TLS exporter; HyperDHT uses its Noise handshake hash. */\nexport interface NativeBinding {\n transport: NativeTransport;\n context: string;\n identities: [string, string];\n}\nexport interface BoundChannel { channel: FrameChannel; binding: NativeBinding }\nexport interface NativeEndpoint {\n transport: NativeTransport;\n descriptor: unknown;\n connect(descriptor: unknown): Promise<BoundChannel>;\n close(): Promise<void>;\n onConnection: ((connection: BoundChannel) => void) | null;\n onDescriptor: (() => void) | null;\n onUnavailable?: (() => void) | null;\n /** The endpoint is connected to its relay again after it lost it (the native Iroh's home relay; nothing else says it). */\n onRelayBack?: (() => void) | null;\n}\nexport type TransportDescriptors = Partial<Record<NativeTransport, unknown>>;\n\n/**\n * One spelling per Iroh relay. Iroh compares relay URLs as text, and its own relays are named with the trailing dot\n * of a fully qualified name (`https://use1-1.relay.n0.iroh.link./`): the same server written without the dot is\n * another relay to it, and an endpoint dialling a contact there opens a second connection to the server it is already\n * homed on, which the server answers by setting the first one aside.\n *\n * So every relay URL is put in one spelling before it goes into an Iroh endpoint (the relays it homes on, a contact's\n * descriptor before a dial), and which one depends on the endpoint:\n * - `\"dotted\"`, n0's relays with their trailing dot: what native Iroh homes on by default (the Desktop), and the form\n * to compare two relays in. Any other relay keeps its plain name here too: a relay behind a proxy (a Cloudflare\n * tunnel) is found by its Host header, and the proxy answers the dotted name with 404.\n * - `\"plain\"`, the name without it: the only one every browser opens. WebKit (Safari, the iPhone app) refuses a\n * host name that ends in a dot, for `fetch` and for a WebSocket alike, so nothing a browser's Iroh is given has one.\n *\n * An IP address and a single-label name (a search domain may complete it) stay as written; `localhost.` loses its dot\n * in both, the form the relay settings accept. What does not parse comes back untouched, for the caller's own check.\n */\nexport type IrohRelaySpelling = \"dotted\" | \"plain\";\nexport function irohRelayUrl(value: string, spelling: IrohRelaySpelling = \"dotted\"): string {\n let url: URL;\n try { url = new URL(value); } catch { return value; }\n const host = url.hostname, name = host.replace(/\\.$/, \"\");\n if (!name.includes(\".\") && name !== \"localhost\") return value;\n if (name.startsWith(\"[\") || /^\\d+(\\.\\d+){3}$/.test(name)) return value;\n const wanted = spelling === \"dotted\" && /(^|\\.)iroh\\.link$/.test(name) ? `${name}.` : name;\n if (wanted === host) return value;\n url.hostname = wanted;\n return url.href;\n}\n\n/** An Iroh descriptor with its relay in one spelling (`irohRelayUrl`); anything else as it is. */\nexport function irohDescriptor<T>(descriptor: T, spelling: IrohRelaySpelling = \"dotted\"): T {\n const relay = (descriptor as { relay?: unknown } | null | undefined)?.relay;\n if (typeof relay !== \"string\") return descriptor;\n const canonical = irohRelayUrl(relay, spelling);\n return canonical === relay ? descriptor : { ...descriptor, relay: canonical };\n}\n\n/**\n * A relay server's URL, short: https, or wss for a browser's relay; plain http or ws only on this machine's loopback,\n * as a test relay is (the same rule as the relay settings).\n */\nexport const RELAY_URL = /^((https|wss):\\/\\/[^\\s]{1,120}|(http|ws):\\/\\/(127\\.0\\.0\\.1|localhost|\\[::1\\])(:\\d{1,5})?(\\/[^\\s]{0,100})?)$/;\n/**\n * A relay URL with more than its server's address in it: a login, a query or a fragment, which no relay setting takes\n * (irohWeb.ts `irohRelayProblem`, hyperdhtRelay.ts `hyperdhtRelayProblem`). An older app named its HyperDHT relay as\n * set, with them; such a descriptor is not dialed or kept, and the rest of what the contact told still is.\n */\nexport const RELAY_WITH_SECRETS = /^[a-z]+:\\/\\/[^/?#]*@|[?#]/i;\n/** A relay URL a descriptor may name: `RELAY_URL`, with nothing but the server's address in it. */\nexport const relayUrl = (value: unknown): value is string => typeof value === \"string\" && RELAY_URL.test(value) && !RELAY_WITH_SECRETS.test(value);\n/** `RELAY_URL` at any length. */\nconst RELAY_URL_ANY_LENGTH = /^((https|wss):\\/\\/[^\\s]+|(http|ws):\\/\\/(127\\.0\\.0\\.1|localhost|\\[::1\\])(:\\d{1,5})?(\\/[^\\s]*)?)$/;\n/**\n * A relay URL `relayUrl` refuses for its length alone (past 120 characters, a loopback path past 100): a relay setting\n * asks for a shorter one, where \"not a relay address\" sent the person looking for a typo in it.\n */\nexport const relayUrlTooLong = (value: string): boolean => !relayUrl(value) && !RELAY_WITH_SECRETS.test(value) && RELAY_URL_ANY_LENGTH.test(value);\n/**\n * Whether an Iroh endpoint may dial a contact through the relay its descriptor names (none: a direct address alone).\n * The contact chose that relay and this device opens it on its own, again on each redial, so it is held to what a held\n * item's address is (`isHoldUrl`): https at a public name or a public address, never this machine or its network.\n * One of the endpoint's own relays (`own`: the person's settings, a private network's or a test's) is dialled as well,\n * in either spelling: this device opens it anyway.\n */\nexport function dialableIrohRelay(relay: unknown, own: readonly string[]): boolean {\n if (relay === null || relay === undefined) return true;\n if (!relayUrl(relay)) return false;\n const same = (a: string, b: string) => { try { return new URL(irohRelayUrl(a, \"plain\")).href === new URL(irohRelayUrl(b, \"plain\")).href; } catch { return false; } };\n return own.some(mine => same(mine, relay)) || isHoldUrl(relay);\n}\nconst HEX_KEY = /^[0-9a-f]{64}$/;\n/** An Iroh direct address as the adapters parse it: an IPv4 or bracketed IPv6 address and its port. */\nconst SOCKET_ADDRESS = /^(\\d{1,3}(\\.\\d{1,3}){3}|\\[[0-9A-Fa-f:.]{2,45}(%[A-Za-z0-9._-]{1,16})?\\]):\\d{1,5}$/;\nconst MAX_ADDRESSES = 8;\n\n/**\n * A contact's native descriptors as it tells them on a session (`paired-policy`, `paired-adapters`) or as this app\n * kept them: only what the adapters dial, each field in the shape its adapter makes. The keys are 64 hex characters,\n * a relay passes `relayUrl` (the rule its capability record is read by), an Iroh descriptor lists at most eight\n * socket addresses. A descriptor that is anything else is left out, as one the contact never told; a field this app\n * does not know is not kept.\n */\nexport function checkedDescriptors(value: unknown): TransportDescriptors {\n const out: TransportDescriptors = {};\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return out;\n const raw = value as Record<string, unknown>;\n const relayed = (v: unknown) => v === undefined || typeof v === \"boolean\";\n const iroh = raw[\"iroh/1\"] as { id?: unknown; relay?: unknown; addresses?: unknown; relayed?: unknown } | null | undefined;\n if (iroh && typeof iroh === \"object\" && typeof iroh.id === \"string\" && HEX_KEY.test(iroh.id) &&\n (iroh.relay === undefined || iroh.relay === null || relayUrl(iroh.relay)) && relayed(iroh.relayed) &&\n Array.isArray(iroh.addresses) && iroh.addresses.length <= MAX_ADDRESSES &&\n iroh.addresses.every(a => typeof a === \"string\" && SOCKET_ADDRESS.test(a)))\n out[\"iroh/1\"] = { id: iroh.id, relay: (iroh.relay as string | null | undefined) ?? null, addresses: [...iroh.addresses] as string[],\n ...(iroh.relayed !== undefined ? { relayed: iroh.relayed } : {}) };\n const hyper = raw[\"hyperdht/1\"] as { publicKey?: unknown; relay?: unknown; relayed?: unknown } | null | undefined;\n if (hyper && typeof hyper === \"object\" && typeof hyper.publicKey === \"string\" && HEX_KEY.test(hyper.publicKey) &&\n (hyper.relay === undefined || relayUrl(hyper.relay)) && relayed(hyper.relayed))\n out[\"hyperdht/1\"] = { publicKey: hyper.publicKey, ...(hyper.relay !== undefined ? { relay: hyper.relay } : {}),\n ...(hyper.relayed !== undefined ? { relayed: hyper.relayed } : {}) };\n return out;\n}\n\n/**\n * Relay only (WISP 100, \"Relayed\"): the transport reaches this contact only through a relay server, never\n * directly. A descriptor says so with `relayed: true`, and an Iroh descriptor with no direct address is relayed\n * too (a browser's, WISP 102). Either side being relay only makes the whole path relayed. Both sides hold both\n * descriptors after the exchange, so they agree, and the rank stays symmetric.\n */\nexport function relayedTransports(local: TransportDescriptors, remote: TransportDescriptors): NativeTransport[] {\n const relayOnly = (transport: NativeTransport, descriptor: unknown): boolean => {\n if (!descriptor || typeof descriptor !== \"object\") return false;\n const d = descriptor as { relayed?: unknown; addresses?: unknown };\n return d.relayed === true || (transport === \"iroh/1\" && Array.isArray(d.addresses) && d.addresses.length === 0);\n };\n return ([\"iroh/1\", \"hyperdht/1\"] as const).filter(t => relayOnly(t, local[t]) || relayOnly(t, remote[t]));\n}\n\n/** Symmetric rank sum; the fixed order breaks ties deterministically. Neither\n * a remote list nor a preference can add an unavailable local adapter. A\n * relayed transport ranks after every direct one: it is where a failed direct\n * path goes, never ahead of one that works. Iroh through its relay is the\n * exception (WISP 100, revision 2026-11-08): it comes back almost at once after\n * the app was away, and a browser's Iroh is never anything else. */\nexport function rankTransports(local: readonly string[], remote: readonly string[], relayed: readonly string[] = []): PairedTransport[] {\n const penalty = (t: PairedTransport) => t !== \"iroh/1\" && relayed.includes(t) ? 1 : 0;\n return TRANSPORTS.filter(t => local.includes(t) && remote.includes(t))\n .sort((a, b) => penalty(a) - penalty(b)\n || (local.indexOf(a) + remote.indexOf(a)) - (local.indexOf(b) + remote.indexOf(b))\n || TRANSPORTS.indexOf(a) - TRANSPORTS.indexOf(b));\n}\n\n/**\n * What a chat prefers when nobody chose (Automatic): Iroh where the app has it, then WebRTC, then HyperDHT (WISP 100,\n * revision 2026-11-08). Every app puts Iroh first, so the rank sum of two apps that both run it puts it first on both\n * sides. With nothing at all, WebRTC, which the offer then leaves out.\n * With Fallback off the chat may use only that one transport, and nothing moves it off a relayed Iroh then: WebRTC\n * where the app has it, else the first transport it has (a Linux Desktop: WebKitGTK has no WebRTC), as before.\n */\nexport const AUTOMATIC_ORDER: readonly PairedTransport[] = [\"iroh/1\", \"webrtc/1\", \"hyperdht/1\"];\nexport function automaticTransport(available: readonly PairedTransport[], fallback = true): PairedTransport {\n if (!fallback) return available.includes(\"webrtc/1\") ? \"webrtc/1\" : TRANSPORTS.find(t => available.includes(t)) ?? \"webrtc/1\";\n return AUTOMATIC_ORDER.find(t => available.includes(t)) ?? \"webrtc/1\";\n}\n\nexport function transportOrder(available: readonly PairedTransport[], preferred: PairedTransport,\n fallback: boolean): PairedTransport[] {\n const rest = TRANSPORTS.filter(t => available.includes(t) && t !== preferred);\n return [...(available.includes(preferred) ? [preferred] : []), ...(fallback ? rest : [])];\n}\n"],"mappings":";;;;;;;;AAGA,IAAM,eAAe;AACrB,IAAM,aAAa;AAEnB,SAAgB,wBAAoC;CAClD,OAAO,YAAY,UAAU;AAC/B;;;;;AAMA,SAAgB,QAAQ,WAAmB,KAAyB;CAClE,IAAI,IAAI,WAAW,YAAY,MAAM,IAAI,MAAM,uCAAuC;CACtF,MAAM,QAAQ,YAAY,YAAY;CACtC,MAAM,MAAM,iBAAiB,KAAK,KAAK,CAAC,CAAC,QAAQ,WAAW,SAAS,CAAC;CACtE,OAAO,SAAS,YAAY,OAAO,GAAG,CAAC;AACzC;;AAGA,SAAgB,aAAa,gBAAgC;CAC3D,OAAO,IAAI,KAAK,MAAM,KAAoB,kBAAkB,CAAC;AAC/D;AAEA,SAAgB,QAAQ,SAAiB,KAAyB;CAChE,IAAI,IAAI,WAAW,YAAY,MAAM,IAAI,MAAM,uCAAuC;CACtF,MAAM,WAAW,WAAW,OAAO;CACnC,IAAI,SAAS,SAAS,IAAkB,MAAM,IAAI,MAAM,+BAA+B;CACvF,MAAM,QAAQ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AO,WAAW,QAAO,MAAK,MAAM,SAAS,CAAC,KAAK,OAAO,SAAS,CAAC,CAAC,CAAC,CACnE,MAAM,GAAG,MAAM,QAAQ,CAAC,IAAI,QAAQ,CAAC,KAChC,MAAM,QAAQ,CAAC,IAAI,OAAO,QAAQ,CAAC,KAAM,MAAM,QAAQ,CAAC,IAAI,OAAO,QAAQ,CAAC,MAC7E,WAAW,QAAQ,CAAC,IAAI,WAAW,QAAQ,CAAC,CAAC;AACtD;;;;;;;;AASA,IAAa,kBAA8C;CAAC;CAAU;CAAY;AAAY;AAC9F,SAAgB,mBAAmB,WAAuC,WAAW,MAAuB;CAC1G,IAAI,CAAC,UAAU,OAAO,UAAU,SAAS,UAAU,IAAI,aAAa,WAAW,MAAK,MAAK,UAAU,SAAS,CAAC,CAAC,KAAK;CACnH,OAAO,gBAAgB,MAAK,MAAK,UAAU,SAAS,CAAC,CAAC,KAAK;AAC7D;AAEA,SAAgB,eAAe,WAAuC,WACpE,UAAsC;CACtC,MAAM,OAAO,WAAW,QAAO,MAAK,UAAU,SAAS,CAAC,KAAK,MAAM,SAAS;CAC5E,OAAO,CAAC,GAAI,UAAU,SAAS,SAAS,IAAI,CAAC,SAAS,IAAI,CAAC,GAAI,GAAI,WAAW,OAAO,CAAC,CAAE;AAC1F"}
@@ -1,6 +1,6 @@
1
- import { M as shownName, i as cleanName } from "./apiKit-BlsNk-Cx.js";
1
+ import { M as shownName, i as cleanName } from "./apiKit-nLK4jeTq.js";
2
2
  import { t as childEnv } from "./childEnv-C-99hdbL.js";
3
- import { t as CliError } from "./errors-DDLFO4Gf.js";
3
+ import { t as CliError } from "./errors-JVJsO8Iu.js";
4
4
  import { execFileSync } from "node:child_process";
5
5
  import { chmodSync, closeSync, existsSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, statSync, utimesSync, writeFileSync, writeSync } from "node:fs";
6
6
  import { dirname, isAbsolute, join, resolve } from "node:path";
@@ -539,4 +539,4 @@ function holder(file, lock) {
539
539
  }
540
540
  export { ownFolder as C, runtimePath as D, privateFolder as E, userPath as S, ownSocket as T, profileExists as _, checkShownName as a, startingDaemon as b, createProfile as c, daemonClaim as d, ghostlyHome as f, noProfile as g, lockPath as h, checkProfileName as i, currentProfile as l, lockOwner as m, RESTORED_MARK as n, checkShownNameOption as o, listProfiles as p, acquireLock as r, claimForDaemon as s, DEFAULT_PROFILE as t, currentProfileOrNone as u, profilePaths as v, ownProfile as w, startingPath as x, selectProfile as y };
541
541
 
542
- //# sourceMappingURL=profiles-BOYGlmu2.js.map
542
+ //# sourceMappingURL=profiles-B2uy04ph.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"profiles-BOYGlmu2.js","names":[],"sources":["../../src/privateFolder.ts","../../src/profiles.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { chmodSync, lstatSync, mkdirSync, readdirSync, statSync, type Stats } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, isAbsolute, join } from \"node:path\";\nimport { CliError } from \"./errors\";\n\n/**\n * Where a socket goes when its path in the profile is longer than a Unix socket may be: `<base>/<prefix>-<hash of the\n * profile>/<leaf>`, in `$XDG_RUNTIME_DIR` or else the temp folder (macOS gives each user one) when that folder is the\n * user's alone, so no other user can make the folder first. When neither is, or the path would still be too long:\n * `/tmp/<prefix>-<uid>-<hash>/<leaf>`. Either way `privateFolder` checks the folder before use.\n */\nexport function runtimePath(prefix: string, profileDir: string, leaf: string): string {\n const hash = createHash(\"sha256\").update(profileDir).digest(\"hex\").slice(0, 24);\n for (const base of [process.env.XDG_RUNTIME_DIR, tmpdir()]) {\n if (!base || !isAbsolute(base) || !usersAlone(base)) continue;\n const path = join(base, `${prefix}-${hash}`, leaf);\n if (Buffer.byteLength(path) <= 100) return path;\n }\n return join(\"/tmp\", `${prefix}-${process.getuid?.() ?? 0}-${hash}`, leaf);\n}\n\nfunction usersAlone(path: string): boolean {\n try {\n const info = statSync(path);\n return info.isDirectory() && (!process.getuid || info.uid === process.getuid()) && (info.mode & 0o077) === 0;\n } catch {\n return false;\n }\n}\n\n/**\n * A folder for a socket outside the profile (when the profile's path is too long for one): made owner-only, and\n * refused when it is a link, someone else made it, or anyone else may enter it: `refused`, as the profile's own checks\n * (`ownProfile`), with the way out. It holds only sockets, so removing it loses nothing; it is made again.\n */\nexport function privateFolder(path: string, what: string): void {\n mkdirSync(path, { recursive: true, mode: 0o700 });\n const info = lstatSync(path);\n if (!info.isDirectory() || (process.getuid && info.uid !== process.getuid()) || (info.mode & 0o077) !== 0) {\n throw new CliError(\"refused\", `${path} is not a folder of this user's alone: ${what}. Run \\`rm -r ${path}\\` (ghostly makes it again), or if it is this user's folder, \\`chmod 700 ${path}\\`, then try again`);\n }\n}\n\n/**\n * The profile's own folder, made owner-only again before the daemon's socket goes in it: a folder made by an older\n * release, or opened up by hand, is closed rather than trusted. Refused when it is a link or someone else's.\n */\nexport function ownFolder(path: string, what: string): void {\n const info = lstatSync(path);\n if (!info.isDirectory() || (process.getuid && info.uid !== process.getuid())) throw new CliError(\"refused\", `${path} is not a folder of this user's: ${what}`);\n if ((info.mode & 0o077) !== 0) chmodSync(path, 0o700);\n}\n\n/**\n * A profile's folders and files, checked before a command (a one-shot as much as the daemon) takes its lock or opens\n * its store, which append to the files in place and follow a link: the home and its `profiles/` must be this user's\n * (a link to a folder of this user's is one); the home is closed to others' writes, `profiles/` to 0700. The profile's\n * folder and its `db/` must be this user's and not links, and are closed to 0700; what is in them must be this user's\n * and not a link, and a file is closed to 0600. A home, profile or journal opened up by hand, or made by another\n * account in a folder it could write, was used as it was: the events journal (message texts) stayed readable by others.\n */\nexport function ownProfile(dir: string): void {\n if (process.platform === \"win32\") return;\n const what = \"ghostly will not open the profile there\";\n const profiles = dirname(dir), home = dirname(profiles);\n const mine = (info: Stats) => !process.getuid || info.uid === process.getuid();\n for (const folder of [home, profiles]) {\n const info = statSync(folder);\n if (!info.isDirectory() || !mine(info)) throw new CliError(\"refused\", `${folder} is not a folder of this user's: ${what}`);\n const open = folder === home ? 0o022 : 0o077;\n if ((info.mode & open) !== 0) chmodSync(folder, info.mode & 0o777 & ~open);\n }\n const db = join(dir, \"db\");\n for (const folder of [dir, db]) {\n let info;\n try { info = lstatSync(folder); } catch (error) { if (folder === db && (error as NodeJS.ErrnoException).code === \"ENOENT\") continue; throw error; }\n if (!info.isDirectory() || !mine(info)) throw new CliError(\"refused\", `${folder} is not a folder of this user's: ${what}`);\n if ((info.mode & 0o077) !== 0) chmodSync(folder, 0o700);\n for (const name of readdirSync(folder)) {\n // Another command at once on the profile removes its lock's draft, start and stale files as it goes: one gone\n // since the listing is passed over, not the command's error.\n const path = join(folder, name), entry = lstatSync(path, { throwIfNoEntry: false });\n if (!entry) continue;\n if (entry.isSymbolicLink() || !mine(entry)) throw new CliError(\"refused\", `${path} is a link or another user's: ${what}`);\n if (entry.isFile() && (entry.mode & 0o077) !== 0) {\n try { chmodSync(path, 0o600); } catch (error) { if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error; }\n }\n }\n }\n}\n\n/** False when `path` is there but is not a socket of this user's: nothing to connect to. */\nexport function ownSocket(path: string): boolean {\n if (process.platform === \"win32\") return true;\n let info;\n try { info = lstatSync(path); } catch { return true; }\n return info.isSocket() && (!process.getuid || info.uid === process.getuid());\n}\n","import { execFileSync } from \"node:child_process\";\nimport { closeSync, existsSync, linkSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, rmSync, statSync, utimesSync, writeFileSync, writeSync, type Stats } from \"node:fs\";\nimport { createHash } from \"node:crypto\";\nimport { homedir } from \"node:os\";\nimport { join, resolve } from \"node:path\";\nimport { MAX_NICK_LENGTH } from \"@ghostly/core\";\nimport { cleanName, shownName } from \"./apiKit\";\nimport { childEnv } from \"./childEnv\";\nimport { CliError } from \"./errors\";\nimport { runtimePath } from \"./privateFolder\";\n\n/**\n * Profiles on disk (WISP 1100 § Profiles and files): `<home>/profiles/<name>/`, 0700, one engine store each.\n * `<home>/current` names the profile commands use when none is given.\n */\nexport const DEFAULT_PROFILE = \"default\";\nconst NAME = /^[a-z0-9][a-z0-9._-]{0,63}$/i;\n\n/**\n * An empty `--home` or `--profile` (an unset variable in a script) is a usage error: taken as not given, it ran the\n * command in the current folder, or as the current profile. An empty variable of the environment counts as unset.\n */\nexport function ghostlyHome(option?: string): string {\n if (option === \"\") throw new CliError(\"usage\", \"--home needs a folder\");\n return userPath(option ?? (process.env.GHOSTLY_HOME || join(homedir(), \".ghostly\")), true);\n}\n\n/**\n * A path the CLI was given, made absolute. A `~` the shell left alone (`--home=~/bots`, a quoted variable, a unit\n * file's `Environment=` line) is the user's home, as the shell reads it: it was a folder named `~` in the current one.\n * `~user/…` is a usage error, not a guess at another user's home, unless it is there under this folder. Any other name\n * that starts with `~` is a file here, as the shell and every other tool read it (`~notes.txt`, Office's\n * `~$report.docx`, a new `~cursor`): all of them were refused (agents#1604). `home`: the profiles' folder, where a bare\n * `~bob` that is not there is refused too, as a new profile would be made in a folder of that name.\n */\nexport function userPath(path: string, home = false): string {\n if (path === \"~\" || path.startsWith(\"~/\")) return join(homedir(), path.slice(1));\n if (path.startsWith(\"~\") && (home || path.includes(\"/\")) && !existsSync(resolve(path))) {\n throw new CliError(\"usage\", `${path}: ~user is not read here: write the ${home || path.endsWith(\"/\") ? \"folder\" : \"path\"} in full`);\n }\n return resolve(path);\n}\n\nconst isProfileName = (name: string): boolean => NAME.test(name) && !name.includes(\"..\");\n\nexport function checkProfileName(name: string): string {\n if (!isProfileName(name)) throw new CliError(\"usage\", `Not a profile name: ${JSON.stringify(name)} (letters, digits, \".\", \"_\" and \"-\", up to 64)`);\n return name;\n}\n\n/**\n * The name a profile shows its contacts, whichever command sets it (`--name`, `profile.set`, `settings set nick`):\n * cleaned as a group's name is (`shownName`: a tab or a line break is a space, invisible characters go), then up to 64\n * characters as stored; empty (or spaces) is no name. `settings set nick` took any length and every one took a line\n * break, printed whole by `status`; a name with nothing that shows was kept as given, and contacts saw no name. `field`\n * names it in the refusal.\n */\nexport function checkShownName(name: unknown, field = \"name\"): string {\n if (typeof name !== \"string\") throw new CliError(\"bad_request\", `${field} must be up to ${MAX_NICK_LENGTH} characters on one line`);\n if (!name.trim()) return \"\";\n return shownName(name, MAX_NICK_LENGTH, field, \" (an empty one is no name)\");\n}\n\n/**\n * `--name` of `profile create` and `profile set`, checked before the profile opens: `checkShownName`'s rule, counted as\n * it counts (code points once cleaned, so a line break is a space and e + a combining accent is one), refused as a\n * usage error (exit 2) that names the option, as `app init --title` is. It was the engine's `bad_request` (exit 1),\n * \"name must be up to 64 characters on one line\", which named neither the option nor the length given.\n */\nexport function checkShownNameOption(name: string): string {\n const shown = cleanName(name, Infinity) ?? \"\";\n const length = [...shown].length;\n if (length > MAX_NICK_LENGTH) throw new CliError(\"usage\", `--name is up to ${MAX_NICK_LENGTH} characters, not ${length} characters`);\n if (name.trim() && !shown) throw new CliError(\"usage\", \"--name needs a character that shows (an empty one is no name)\");\n return checkShownName(name);\n}\n\nexport function currentProfile(home: string, option?: string): string {\n if (option === \"\") throw new CliError(\"usage\", \"--profile needs a profile name\");\n if (option !== undefined) return checkProfileName(option);\n const env = process.env.GHOSTLY_PROFILE;\n // Nobody typed it on this line: refused naming the variable and the way out, not as a `--profile` given here.\n if (env && !isProfileName(env)) {\n throw new CliError(\"usage\", `GHOSTLY_PROFILE names no profile (${JSON.stringify(env)}): set it to a profile's name (letters, digits, \".\", \"_\" and \"-\", up to 64), or unset it`);\n }\n if (env) return env;\n const file = join(home, \"current\");\n if (existsSync(file)) {\n const name = readFileSync(file, \"utf8\").trim();\n // Nobody typed it: refused naming the file and the way out, not a usage error of a name the command never had.\n if (name && !isProfileName(name)) {\n throw new CliError(\"refused\", `${file} names no profile (${JSON.stringify(name)}): ghostly profile use <name> or ghostly profile create <name> --use replaces it, or delete the file`, { file });\n }\n if (name) return name;\n }\n return DEFAULT_PROFILE;\n}\n\n/**\n * The current profile, or null when `<home>/current` names none: for the commands that list profiles or replace that\n * file (`profile list`, `use`, `create`, `restore`), which a bad name there would otherwise block.\n */\nexport function currentProfileOrNone(home: string, option?: string): string | null {\n try {\n return currentProfile(home, option);\n } catch (error) {\n if (error instanceof CliError && error.details?.file) return null;\n throw error;\n }\n}\n\nexport function profileDir(home: string, name: string): string {\n return join(home, \"profiles\", checkProfileName(name));\n}\n\nexport interface ProfilePaths { name: string; dir: string; db: string; socket: string; lock: string; events: string; files: string; log: string }\nexport function profilePaths(home: string, name: string): ProfilePaths {\n const dir = profileDir(home, name);\n return {\n name, dir, db: join(dir, \"db\"), socket: socketPath(dir), lock: lockPath(dir),\n events: join(dir, \"events.jsonl\"), files: join(dir, \"files\"), log: join(dir, \"daemon.log\"),\n };\n}\n\n/** The file that says which process holds the profile (`acquireLock`). */\nexport function lockPath(dir: string): string {\n return join(dir, \"daemon.lock\");\n}\n\n/** The file in which a daemon says it is starting: its pid, from the lock it took until its socket listens. */\nexport function startingPath(dir: string): string {\n return join(dir, \"daemon.starting\");\n}\n\n/**\n * The pid of the profile's daemon while it starts (its engine, before its socket listens): the lock's holder, when it\n * marked its start. Null otherwise: nobody holds the profile, a one-shot command does, or the mark is a dead daemon's.\n */\nexport function startingDaemon(paths: ProfilePaths): number | null {\n let pid: number;\n try { pid = Number(readFileSync(startingPath(paths.dir), \"utf8\").trim()); } catch { return null; }\n // Alive, and this profile's: the lock's holder is.\n return Number.isInteger(pid) && pid > 0 && pid === lockOwner(paths) ? pid : null;\n}\n\n/**\n * The file in which `daemon restart` or `daemon --detach` keeps the profile for the daemon it starts (`claimForDaemon`):\n * its pid, the file touched every CLAIM_TOUCH_MS while it waits.\n */\nexport function claimPath(dir: string): string {\n return join(dir, \"daemon.claim\");\n}\n\nconst CLAIM_TOUCH_MS = 1_000;\n/** A claim not touched for that long is a start that ended without removing it (killed): none. */\nconst CLAIM_FRESH_MS = 10_000;\n\n/**\n * The pid of the `daemon restart` or `daemon --detach` that keeps the profile for the daemon it starts, from the stop\n * of the old one until the new one holds the profile: the lock is free in between, and one-shot commands that kept\n * taking it in turn (a bot's typing indicator every few seconds) left the new daemon, seconds to boot, never finding\n * it free. Null when no live start claims it.\n */\nexport function daemonClaim(paths: ProfilePaths): number | null {\n const file = claimPath(paths.dir);\n let pid: number;\n try {\n if (Date.now() - statSync(file).mtimeMs > CLAIM_FRESH_MS) return null;\n pid = Number(readFileSync(file, \"utf8\").trim());\n } catch { return null; }\n if (!Number.isInteger(pid) || pid <= 0) return null;\n try { process.kill(pid, 0); } catch (error) { if ((error as NodeJS.ErrnoException).code !== \"EPERM\") return null; }\n return pid;\n}\n\n/**\n * Keeps the profile for the daemon this process starts (`daemonClaim`): until the function it returns is called, only\n * this process and its children take the profile's lock; any other command waits for the daemon's socket instead.\n * Another live start's claim stands (its daemon is the one that comes up); a claim that cannot be written is none.\n */\nexport function claimForDaemon(paths: ProfilePaths): () => void {\n if (daemonClaim(paths) !== null) return () => {};\n const mine = String(process.pid), file = claimPath(paths.dir), draft = `${file}.${mine}`;\n try {\n writeFileSync(draft, mine, { mode: 0o600 });\n renameSync(draft, file);\n } catch {\n rmSync(draft, { force: true });\n return () => {};\n }\n const ours = () => { try { return readFileSync(file, \"utf8\").trim() === mine; } catch { return false; } };\n const touch = setInterval(() => {\n if (!ours()) return;\n const now = new Date();\n try { utimesSync(file, now, now); } catch { /* removed meanwhile */ }\n }, CLAIM_TOUCH_MS);\n touch.unref();\n let released = false;\n return () => {\n if (released) return;\n released = true;\n clearInterval(touch);\n if (ours()) rmSync(file, { force: true });\n };\n}\n\n/**\n * The daemon's socket: in the profile's folder, unless that path is longer than a Unix socket may be (104 bytes on\n * macOS); then in a folder of the user's runtime folder named after the profile's (`runtimePath`), which the daemon\n * makes owner-only and checks before use (`privateFolder`), and whose socket a client connects to only when it is this\n * user's (`ownSocket`).\n */\nfunction socketPath(dir: string): string {\n const inside = join(dir, \"daemon.sock\");\n if (process.platform === \"win32\") return `\\\\\\\\.\\\\pipe\\\\ghostly-${createHash(\"sha256\").update(dir).digest(\"hex\").slice(0, 24)}`;\n if (Buffer.byteLength(inside) <= 100) return inside;\n return runtimePath(\"ghostly\", dir, \"daemon.sock\");\n}\n\nfunction ensureFolder(path: string): void {\n mkdirSync(path, { recursive: true, mode: 0o700 });\n}\n\n/** Makes the profile's folder; refused when it exists and `existing` is not allowed. */\nexport function createProfile(home: string, name: string, { existing = false } = {}): ProfilePaths {\n const paths = profilePaths(home, name);\n if (existsSync(paths.dir) && !existing) throw new CliError(\"refused\", `Profile ${name} exists`);\n ensureFolder(join(home, \"profiles\"));\n ensureFolder(paths.dir);\n return paths;\n}\n\n/**\n * A file in the folder of a profile a restore made, until its engine starts for the first time: the store came back\n * whole, as the backup held it, and the money in it is then treated as every restore treats it (WISP 05 § Restoring).\n */\nexport const RESTORED_MARK = \"restored\";\n\nexport function profileExists(home: string, name: string): boolean {\n return existsSync(profileDir(home, name));\n}\n\nexport function listProfiles(home: string): string[] {\n const root = join(home, \"profiles\");\n if (!existsSync(root)) return [];\n return readdirSync(root).filter((name) => NAME.test(name) && statSync(join(root, name)).isDirectory()).sort();\n}\n\n/** A profile this home lacks, as `profile use` and `--profile` both say it: quoted, with how to list or make one. */\nexport const noProfile = (name: string): CliError =>\n new CliError(\"not_found\", `No profile ${JSON.stringify(name)} (ghostly profile list, or ghostly profile create ${name})`);\n\nexport function selectProfile(home: string, name: string): void {\n if (!profileExists(home, name)) throw noProfile(name);\n ensureFolder(home);\n writeFileSync(join(home, \"current\"), name + \"\\n\", { mode: 0o600 });\n}\n\n/**\n * One process per profile: the daemon or a one-shot command. The lock holds the owner's pid; a lock whose\n * process is gone is taken over.\n *\n * The lock is a link to a file that already holds the pid, so it never exists empty (agents#1642): one made by\n * `openSync` + `writeSync` was empty for a moment, and another process read that as nobody's and removed it under its\n * owner. An empty lock younger than `EMPTY_LOCK_GRACE_MS` is still an older release's being written: busy. A stale\n * lock is moved aside before it is removed, and only when what was moved is the file judged stale: one that vanished,\n * or that another process made since, is no longer removed.\n *\n * The lock stays the bare pid, as older releases read it; beside it, `<lock>.<pid>.start` holds when that process\n * started (`processStart`). A lock left by a process that died without releasing it (kill -9, Ctrl-C of a one-shot, a\n * reboot) whose pid now belongs to another process is then stale too: it held the profile for good, every command busy\n * until someone found the file. It is written before the lock is placed, so a lock of this release never lacks it for\n * a moment; one without it (an older release's) is held while its pid is alive, as before.\n *\n * While a `daemon restart` or `daemon --detach` keeps the profile for the daemon it starts (`daemonClaim`), it is busy\n * for every other process: a one-shot then waits for that daemon's socket (`openOneShot`).\n */\nexport function acquireLock(paths: ProfilePaths): () => void {\n // Kept for the daemon a start brings up (`daemonClaim`): its own process and the daemon it spawns take it, no other.\n const claim = daemonClaim(paths);\n if (claim !== null && claim !== process.pid && claim !== process.ppid) throw new CliError(\"busy\", `Profile ${paths.name} is kept for the daemon that process ${claim} starts`, { pid: claim });\n const mine = String(process.pid);\n const draft = `${paths.lock}.${mine}`;\n const start = startPath(paths.lock, process.pid);\n const started = processStart(process.pid);\n let placed = false;\n writeFileSync(draft, mine, { mode: 0o600 });\n if (started !== null) writeFileSync(start, started, { mode: 0o600 });\n try {\n for (let attempt = 0; attempt < 3; attempt++) {\n if (placeLock(draft, paths.lock, mine)) {\n placed = true;\n heldHere.add(paths.lock);\n let released = false;\n return () => {\n if (released) return;\n released = true;\n heldHere.delete(paths.lock);\n try { if (readFileSync(paths.lock, \"utf8\").trim() === mine) rmSync(paths.lock, { force: true }); } catch { /* gone already */ }\n rmSync(start, { force: true });\n };\n }\n let seen: Stats;\n try { seen = lstatSync(paths.lock); } catch { continue; }\n const owner = lockOwner(paths);\n if (owner !== null) throw new CliError(\"busy\", `Profile ${paths.name} is in use by process ${owner}`, { pid: owner });\n if (seen.size === 0 && Date.now() - seen.mtimeMs < EMPTY_LOCK_GRACE_MS) break;\n removeStaleLock(paths.lock, seen);\n }\n } finally {\n rmSync(draft, { force: true });\n if (!placed) rmSync(start, { force: true });\n }\n throw new CliError(\"busy\", `Profile ${paths.name} is in use`);\n}\n\n/** The locks this process holds: a lock naming this pid that is not one of them is a dead holder's whose pid it has now. */\nconst heldHere = new Set<string>();\n\nfunction startPath(lock: string, pid: number): string {\n return `${lock}.${pid}.start`;\n}\n\n/**\n * When the process `pid` started, as a text that is the same for as long as it runs and another for the next process\n * given that pid; null where it cannot be read (Windows, a `/proc` that hides others' processes, no `ps`). On Linux the\n * boot's id and `/proc/<pid>/stat`'s start time (clock ticks since boot); elsewhere `ps -o lstart=`.\n */\nexport function processStart(pid: number): string | null {\n try {\n if (process.platform === \"linux\") {\n const stat = readFileSync(`/proc/${pid}/stat`, \"utf8\");\n // Fields after the command, which may hold spaces and parentheses: the start time is field 22.\n const ticks = stat.slice(stat.lastIndexOf(\")\") + 2).split(\" \")[19];\n if (!ticks || !/^\\d+$/.test(ticks)) return null;\n return `${readFileSync(\"/proc/sys/kernel/random/boot_id\", \"utf8\").trim()} ${ticks}`;\n }\n if (process.platform === \"win32\") return null;\n const lstart = execFileSync(\"ps\", [\"-o\", \"lstart=\", \"-p\", String(pid)], {\n encoding: \"utf8\", stdio: [\"ignore\", \"pipe\", \"ignore\"], timeout: 2_000, env: { ...childEnv(), LC_ALL: \"C\" },\n }).trim();\n return lstart || null;\n } catch {\n return null;\n }\n}\n\n/** How long an empty lock is taken for one an older release is still writing its pid into. */\nconst EMPTY_LOCK_GRACE_MS = 1_000;\n\n/**\n * Links `draft` (which holds `mine`) as the lock; false when there is a lock already. Where the file system has no\n * hard links, the lock is made in place, as before.\n */\nfunction placeLock(draft: string, lock: string, mine: string): boolean {\n try {\n linkSync(draft, lock);\n return true;\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code === \"EEXIST\") return false;\n if (![\"EPERM\", \"ENOTSUP\", \"EOPNOTSUPP\", \"ENOSYS\"].includes(code ?? \"\")) throw error;\n }\n let fd: number;\n try { fd = openSync(lock, \"wx\", 0o600); } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"EEXIST\") return false;\n throw error;\n }\n writeSync(fd, mine);\n closeSync(fd);\n return true;\n}\n\n/**\n * Removes the lock judged stale (`seen`): it is moved aside first, and removed only when what was moved is that same\n * file and holds no live pid (a freed inode is soon reused). A lock another process made in the meantime is put back.\n */\nfunction removeStaleLock(lock: string, seen: Stats): void {\n const aside = `${lock}.stale.${process.pid}`;\n try { renameSync(lock, aside); } catch { return; }\n try {\n const moved = lstatSync(aside);\n if (moved.ino === seen.ino && moved.dev === seen.dev && holder(aside, lock) === null && moved.size === seen.size) {\n const pid = lockPid(aside);\n if (pid !== null && pid !== process.pid) rmSync(startPath(lock, pid), { force: true });\n return;\n }\n try { linkSync(aside, lock); } catch { /* another lock is there already */ }\n } finally {\n rmSync(aside, { force: true });\n }\n}\n\n/**\n * The pid holding the profile, or null when nobody does: the lock's process is gone, or its pid is another process's\n * now (it started at another time than the lock's holder, or it is this process, which does not hold the lock).\n */\nexport function lockOwner(paths: ProfilePaths): number | null {\n return holder(paths.lock, paths.lock);\n}\n\nfunction lockPid(file: string): number | null {\n let pid: number;\n try { pid = Number(readFileSync(file, \"utf8\").trim()); } catch { return null; }\n return Number.isInteger(pid) && pid > 0 ? pid : null;\n}\n\n/** `file`: the lock, or the stale one moved aside; `lock`: the lock's own path, beside which its start is. */\nfunction holder(file: string, lock: string): number | null {\n const pid = lockPid(file);\n if (pid === null) return null;\n if (pid === process.pid) return heldHere.has(lock) ? pid : null;\n try { process.kill(pid, 0); } catch (error) { if ((error as NodeJS.ErrnoException).code !== \"EPERM\") return null; }\n let recorded: string;\n try { recorded = readFileSync(startPath(lock, pid), \"utf8\").trim(); } catch { return pid; }\n const now = processStart(pid);\n return recorded && now !== null && now !== recorded ? null : pid;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAYA,SAAgB,YAAY,QAAgB,YAAoB,MAAsB;CACpF,MAAM,OAAO,WAAW,QAAQ,CAAC,CAAC,OAAO,UAAU,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,MAAM,GAAG,EAAE;CAC9E,KAAK,MAAM,QAAQ,CAAC,QAAQ,IAAI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sources":["../../src/privateFolder.ts","../../src/profiles.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { chmodSync, lstatSync, mkdirSync, readdirSync, statSync, type Stats } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, isAbsolute, join } from \"node:path\";\nimport { CliError } from \"./errors\";\n\n/**\n * Where a socket goes when its path in the profile is longer than a Unix socket may be: `<base>/<prefix>-<hash of the\n * profile>/<leaf>`, in `$XDG_RUNTIME_DIR` or else the temp folder (macOS gives each user one) when that folder is the\n * user's alone, so no other user can make the folder first. When neither is, or the path would still be too long:\n * `/tmp/<prefix>-<uid>-<hash>/<leaf>`. Either way `privateFolder` checks the folder before use.\n */\nexport function runtimePath(prefix: string, profileDir: string, leaf: string): string {\n const hash = createHash(\"sha256\").update(profileDir).digest(\"hex\").slice(0, 24);\n for (const base of [process.env.XDG_RUNTIME_DIR, tmpdir()]) {\n if (!base || !isAbsolute(base) || !usersAlone(base)) continue;\n const path = join(base, `${prefix}-${hash}`, leaf);\n if (Buffer.byteLength(path) <= 100) return path;\n }\n return join(\"/tmp\", `${prefix}-${process.getuid?.() ?? 0}-${hash}`, leaf);\n}\n\nfunction usersAlone(path: string): boolean {\n try {\n const info = statSync(path);\n return info.isDirectory() && (!process.getuid || info.uid === process.getuid()) && (info.mode & 0o077) === 0;\n } catch {\n return false;\n }\n}\n\n/**\n * A folder for a socket outside the profile (when the profile's path is too long for one): made owner-only, and\n * refused when it is a link, someone else made it, or anyone else may enter it: `refused`, as the profile's own checks\n * (`ownProfile`), with the way out. It holds only sockets, so removing it loses nothing; it is made again.\n */\nexport function privateFolder(path: string, what: string): void {\n mkdirSync(path, { recursive: true, mode: 0o700 });\n const info = lstatSync(path);\n if (!info.isDirectory() || (process.getuid && info.uid !== process.getuid()) || (info.mode & 0o077) !== 0) {\n throw new CliError(\"refused\", `${path} is not a folder of this user's alone: ${what}. Run \\`rm -r ${path}\\` (ghostly makes it again), or if it is this user's folder, \\`chmod 700 ${path}\\`, then try again`);\n }\n}\n\n/**\n * The profile's own folder, made owner-only again before the daemon's socket goes in it: a folder made by an older\n * release, or opened up by hand, is closed rather than trusted. Refused when it is a link or someone else's.\n */\nexport function ownFolder(path: string, what: string): void {\n const info = lstatSync(path);\n if (!info.isDirectory() || (process.getuid && info.uid !== process.getuid())) throw new CliError(\"refused\", `${path} is not a folder of this user's: ${what}`);\n if ((info.mode & 0o077) !== 0) chmodSync(path, 0o700);\n}\n\n/**\n * A profile's folders and files, checked before a command (a one-shot as much as the daemon) takes its lock or opens\n * its store, which append to the files in place and follow a link: the home and its `profiles/` must be this user's\n * (a link to a folder of this user's is one); the home is closed to others' writes, `profiles/` to 0700. The profile's\n * folder and its `db/` must be this user's and not links, and are closed to 0700; what is in them must be this user's\n * and not a link, and a file is closed to 0600. A home, profile or journal opened up by hand, or made by another\n * account in a folder it could write, was used as it was: the events journal (message texts) stayed readable by others.\n */\nexport function ownProfile(dir: string): void {\n if (process.platform === \"win32\") return;\n const what = \"ghostly will not open the profile there\";\n const profiles = dirname(dir), home = dirname(profiles);\n const mine = (info: Stats) => !process.getuid || info.uid === process.getuid();\n for (const folder of [home, profiles]) {\n const info = statSync(folder);\n if (!info.isDirectory() || !mine(info)) throw new CliError(\"refused\", `${folder} is not a folder of this user's: ${what}`);\n const open = folder === home ? 0o022 : 0o077;\n if ((info.mode & open) !== 0) chmodSync(folder, info.mode & 0o777 & ~open);\n }\n const db = join(dir, \"db\");\n for (const folder of [dir, db]) {\n let info;\n try { info = lstatSync(folder); } catch (error) { if (folder === db && (error as NodeJS.ErrnoException).code === \"ENOENT\") continue; throw error; }\n if (!info.isDirectory() || !mine(info)) throw new CliError(\"refused\", `${folder} is not a folder of this user's: ${what}`);\n if ((info.mode & 0o077) !== 0) chmodSync(folder, 0o700);\n for (const name of readdirSync(folder)) {\n // Another command at once on the profile removes its lock's draft, start and stale files as it goes: one gone\n // since the listing is passed over, not the command's error.\n const path = join(folder, name), entry = lstatSync(path, { throwIfNoEntry: false });\n if (!entry) continue;\n if (entry.isSymbolicLink() || !mine(entry)) throw new CliError(\"refused\", `${path} is a link or another user's: ${what}`);\n if (entry.isFile() && (entry.mode & 0o077) !== 0) {\n try { chmodSync(path, 0o600); } catch (error) { if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error; }\n }\n }\n }\n}\n\n/** False when `path` is there but is not a socket of this user's: nothing to connect to. */\nexport function ownSocket(path: string): boolean {\n if (process.platform === \"win32\") return true;\n let info;\n try { info = lstatSync(path); } catch { return true; }\n return info.isSocket() && (!process.getuid || info.uid === process.getuid());\n}\n","import { execFileSync } from \"node:child_process\";\nimport { closeSync, existsSync, linkSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, rmSync, statSync, utimesSync, writeFileSync, writeSync, type Stats } from \"node:fs\";\nimport { createHash } from \"node:crypto\";\nimport { homedir } from \"node:os\";\nimport { join, resolve } from \"node:path\";\nimport { MAX_NICK_LENGTH } from \"@ghostly/core\";\nimport { cleanName, shownName } from \"./apiKit\";\nimport { childEnv } from \"./childEnv\";\nimport { CliError } from \"./errors\";\nimport { runtimePath } from \"./privateFolder\";\n\n/**\n * Profiles on disk (WISP 1100 § Profiles and files): `<home>/profiles/<name>/`, 0700, one engine store each.\n * `<home>/current` names the profile commands use when none is given.\n */\nexport const DEFAULT_PROFILE = \"default\";\nconst NAME = /^[a-z0-9][a-z0-9._-]{0,63}$/i;\n\n/**\n * An empty `--home` or `--profile` (an unset variable in a script) is a usage error: taken as not given, it ran the\n * command in the current folder, or as the current profile. An empty variable of the environment counts as unset.\n */\nexport function ghostlyHome(option?: string): string {\n if (option === \"\") throw new CliError(\"usage\", \"--home needs a folder\");\n return userPath(option ?? (process.env.GHOSTLY_HOME || join(homedir(), \".ghostly\")), true);\n}\n\n/**\n * A path the CLI was given, made absolute. A `~` the shell left alone (`--home=~/bots`, a quoted variable, a unit\n * file's `Environment=` line) is the user's home, as the shell reads it: it was a folder named `~` in the current one.\n * `~user/…` is a usage error, not a guess at another user's home, unless it is there under this folder. Any other name\n * that starts with `~` is a file here, as the shell and every other tool read it (`~notes.txt`, Office's\n * `~$report.docx`, a new `~cursor`): all of them were refused (agents#1604). `home`: the profiles' folder, where a bare\n * `~bob` that is not there is refused too, as a new profile would be made in a folder of that name.\n */\nexport function userPath(path: string, home = false): string {\n if (path === \"~\" || path.startsWith(\"~/\")) return join(homedir(), path.slice(1));\n if (path.startsWith(\"~\") && (home || path.includes(\"/\")) && !existsSync(resolve(path))) {\n throw new CliError(\"usage\", `${path}: ~user is not read here: write the ${home || path.endsWith(\"/\") ? \"folder\" : \"path\"} in full`);\n }\n return resolve(path);\n}\n\nconst isProfileName = (name: string): boolean => NAME.test(name) && !name.includes(\"..\");\n\nexport function checkProfileName(name: string): string {\n if (!isProfileName(name)) throw new CliError(\"usage\", `Not a profile name: ${JSON.stringify(name)} (letters, digits, \".\", \"_\" and \"-\", up to 64)`);\n return name;\n}\n\n/**\n * The name a profile shows its contacts, whichever command sets it (`--name`, `profile.set`, `settings set nick`):\n * cleaned as a group's name is (`shownName`: a tab or a line break is a space, invisible characters go), then up to 64\n * characters as stored; empty (or spaces) is no name. `settings set nick` took any length and every one took a line\n * break, printed whole by `status`; a name with nothing that shows was kept as given, and contacts saw no name. `field`\n * names it in the refusal.\n */\nexport function checkShownName(name: unknown, field = \"name\"): string {\n if (typeof name !== \"string\") throw new CliError(\"bad_request\", `${field} must be up to ${MAX_NICK_LENGTH} characters on one line`);\n if (!name.trim()) return \"\";\n return shownName(name, MAX_NICK_LENGTH, field, \" (an empty one is no name)\");\n}\n\n/**\n * `--name` of `profile create` and `profile set`, checked before the profile opens: `checkShownName`'s rule, counted as\n * it counts (code points once cleaned, so a line break is a space and e + a combining accent is one), refused as a\n * usage error (exit 2) that names the option, as `app init --title` is. It was the engine's `bad_request` (exit 1),\n * \"name must be up to 64 characters on one line\", which named neither the option nor the length given.\n */\nexport function checkShownNameOption(name: string): string {\n const shown = cleanName(name, Infinity) ?? \"\";\n const length = [...shown].length;\n if (length > MAX_NICK_LENGTH) throw new CliError(\"usage\", `--name is up to ${MAX_NICK_LENGTH} characters, not ${length} characters`);\n if (name.trim() && !shown) throw new CliError(\"usage\", \"--name needs a character that shows (an empty one is no name)\");\n return checkShownName(name);\n}\n\nexport function currentProfile(home: string, option?: string): string {\n if (option === \"\") throw new CliError(\"usage\", \"--profile needs a profile name\");\n if (option !== undefined) return checkProfileName(option);\n const env = process.env.GHOSTLY_PROFILE;\n // Nobody typed it on this line: refused naming the variable and the way out, not as a `--profile` given here.\n if (env && !isProfileName(env)) {\n throw new CliError(\"usage\", `GHOSTLY_PROFILE names no profile (${JSON.stringify(env)}): set it to a profile's name (letters, digits, \".\", \"_\" and \"-\", up to 64), or unset it`);\n }\n if (env) return env;\n const file = join(home, \"current\");\n if (existsSync(file)) {\n const name = readFileSync(file, \"utf8\").trim();\n // Nobody typed it: refused naming the file and the way out, not a usage error of a name the command never had.\n if (name && !isProfileName(name)) {\n throw new CliError(\"refused\", `${file} names no profile (${JSON.stringify(name)}): ghostly profile use <name> or ghostly profile create <name> --use replaces it, or delete the file`, { file });\n }\n if (name) return name;\n }\n return DEFAULT_PROFILE;\n}\n\n/**\n * The current profile, or null when `<home>/current` names none: for the commands that list profiles or replace that\n * file (`profile list`, `use`, `create`, `restore`), which a bad name there would otherwise block.\n */\nexport function currentProfileOrNone(home: string, option?: string): string | null {\n try {\n return currentProfile(home, option);\n } catch (error) {\n if (error instanceof CliError && error.details?.file) return null;\n throw error;\n }\n}\n\nexport function profileDir(home: string, name: string): string {\n return join(home, \"profiles\", checkProfileName(name));\n}\n\nexport interface ProfilePaths { name: string; dir: string; db: string; socket: string; lock: string; events: string; files: string; log: string }\nexport function profilePaths(home: string, name: string): ProfilePaths {\n const dir = profileDir(home, name);\n return {\n name, dir, db: join(dir, \"db\"), socket: socketPath(dir), lock: lockPath(dir),\n events: join(dir, \"events.jsonl\"), files: join(dir, \"files\"), log: join(dir, \"daemon.log\"),\n };\n}\n\n/** The file that says which process holds the profile (`acquireLock`). */\nexport function lockPath(dir: string): string {\n return join(dir, \"daemon.lock\");\n}\n\n/** The file in which a daemon says it is starting: its pid, from the lock it took until its socket listens. */\nexport function startingPath(dir: string): string {\n return join(dir, \"daemon.starting\");\n}\n\n/**\n * The pid of the profile's daemon while it starts (its engine, before its socket listens): the lock's holder, when it\n * marked its start. Null otherwise: nobody holds the profile, a one-shot command does, or the mark is a dead daemon's.\n */\nexport function startingDaemon(paths: ProfilePaths): number | null {\n let pid: number;\n try { pid = Number(readFileSync(startingPath(paths.dir), \"utf8\").trim()); } catch { return null; }\n // Alive, and this profile's: the lock's holder is.\n return Number.isInteger(pid) && pid > 0 && pid === lockOwner(paths) ? pid : null;\n}\n\n/**\n * The file in which `daemon restart` or `daemon --detach` keeps the profile for the daemon it starts (`claimForDaemon`):\n * its pid, the file touched every CLAIM_TOUCH_MS while it waits.\n */\nexport function claimPath(dir: string): string {\n return join(dir, \"daemon.claim\");\n}\n\nconst CLAIM_TOUCH_MS = 1_000;\n/** A claim not touched for that long is a start that ended without removing it (killed): none. */\nconst CLAIM_FRESH_MS = 10_000;\n\n/**\n * The pid of the `daemon restart` or `daemon --detach` that keeps the profile for the daemon it starts, from the stop\n * of the old one until the new one holds the profile: the lock is free in between, and one-shot commands that kept\n * taking it in turn (a bot's typing indicator every few seconds) left the new daemon, seconds to boot, never finding\n * it free. Null when no live start claims it.\n */\nexport function daemonClaim(paths: ProfilePaths): number | null {\n const file = claimPath(paths.dir);\n let pid: number;\n try {\n if (Date.now() - statSync(file).mtimeMs > CLAIM_FRESH_MS) return null;\n pid = Number(readFileSync(file, \"utf8\").trim());\n } catch { return null; }\n if (!Number.isInteger(pid) || pid <= 0) return null;\n try { process.kill(pid, 0); } catch (error) { if ((error as NodeJS.ErrnoException).code !== \"EPERM\") return null; }\n return pid;\n}\n\n/**\n * Keeps the profile for the daemon this process starts (`daemonClaim`): until the function it returns is called, only\n * this process and its children take the profile's lock; any other command waits for the daemon's socket instead.\n * Another live start's claim stands (its daemon is the one that comes up); a claim that cannot be written is none.\n */\nexport function claimForDaemon(paths: ProfilePaths): () => void {\n if (daemonClaim(paths) !== null) return () => {};\n const mine = String(process.pid), file = claimPath(paths.dir), draft = `${file}.${mine}`;\n try {\n writeFileSync(draft, mine, { mode: 0o600 });\n renameSync(draft, file);\n } catch {\n rmSync(draft, { force: true });\n return () => {};\n }\n const ours = () => { try { return readFileSync(file, \"utf8\").trim() === mine; } catch { return false; } };\n const touch = setInterval(() => {\n if (!ours()) return;\n const now = new Date();\n try { utimesSync(file, now, now); } catch { /* removed meanwhile */ }\n }, CLAIM_TOUCH_MS);\n touch.unref();\n let released = false;\n return () => {\n if (released) return;\n released = true;\n clearInterval(touch);\n if (ours()) rmSync(file, { force: true });\n };\n}\n\n/**\n * The daemon's socket: in the profile's folder, unless that path is longer than a Unix socket may be (104 bytes on\n * macOS); then in a folder of the user's runtime folder named after the profile's (`runtimePath`), which the daemon\n * makes owner-only and checks before use (`privateFolder`), and whose socket a client connects to only when it is this\n * user's (`ownSocket`).\n */\nfunction socketPath(dir: string): string {\n const inside = join(dir, \"daemon.sock\");\n if (process.platform === \"win32\") return `\\\\\\\\.\\\\pipe\\\\ghostly-${createHash(\"sha256\").update(dir).digest(\"hex\").slice(0, 24)}`;\n if (Buffer.byteLength(inside) <= 100) return inside;\n return runtimePath(\"ghostly\", dir, \"daemon.sock\");\n}\n\nfunction ensureFolder(path: string): void {\n mkdirSync(path, { recursive: true, mode: 0o700 });\n}\n\n/** Makes the profile's folder; refused when it exists and `existing` is not allowed. */\nexport function createProfile(home: string, name: string, { existing = false } = {}): ProfilePaths {\n const paths = profilePaths(home, name);\n if (existsSync(paths.dir) && !existing) throw new CliError(\"refused\", `Profile ${name} exists`);\n ensureFolder(join(home, \"profiles\"));\n ensureFolder(paths.dir);\n return paths;\n}\n\n/**\n * A file in the folder of a profile a restore made, until its engine starts for the first time: the store came back\n * whole, as the backup held it, and the money in it is then treated as every restore treats it (WISP 05 § Restoring).\n */\nexport const RESTORED_MARK = \"restored\";\n\nexport function profileExists(home: string, name: string): boolean {\n return existsSync(profileDir(home, name));\n}\n\nexport function listProfiles(home: string): string[] {\n const root = join(home, \"profiles\");\n if (!existsSync(root)) return [];\n return readdirSync(root).filter((name) => NAME.test(name) && statSync(join(root, name)).isDirectory()).sort();\n}\n\n/** A profile this home lacks, as `profile use` and `--profile` both say it: quoted, with how to list or make one. */\nexport const noProfile = (name: string): CliError =>\n new CliError(\"not_found\", `No profile ${JSON.stringify(name)} (ghostly profile list, or ghostly profile create ${name})`);\n\nexport function selectProfile(home: string, name: string): void {\n if (!profileExists(home, name)) throw noProfile(name);\n ensureFolder(home);\n writeFileSync(join(home, \"current\"), name + \"\\n\", { mode: 0o600 });\n}\n\n/**\n * One process per profile: the daemon or a one-shot command. The lock holds the owner's pid; a lock whose\n * process is gone is taken over.\n *\n * The lock is a link to a file that already holds the pid, so it never exists empty (agents#1642): one made by\n * `openSync` + `writeSync` was empty for a moment, and another process read that as nobody's and removed it under its\n * owner. An empty lock younger than `EMPTY_LOCK_GRACE_MS` is still an older release's being written: busy. A stale\n * lock is moved aside before it is removed, and only when what was moved is the file judged stale: one that vanished,\n * or that another process made since, is no longer removed.\n *\n * The lock stays the bare pid, as older releases read it; beside it, `<lock>.<pid>.start` holds when that process\n * started (`processStart`). A lock left by a process that died without releasing it (kill -9, Ctrl-C of a one-shot, a\n * reboot) whose pid now belongs to another process is then stale too: it held the profile for good, every command busy\n * until someone found the file. It is written before the lock is placed, so a lock of this release never lacks it for\n * a moment; one without it (an older release's) is held while its pid is alive, as before.\n *\n * While a `daemon restart` or `daemon --detach` keeps the profile for the daemon it starts (`daemonClaim`), it is busy\n * for every other process: a one-shot then waits for that daemon's socket (`openOneShot`).\n */\nexport function acquireLock(paths: ProfilePaths): () => void {\n // Kept for the daemon a start brings up (`daemonClaim`): its own process and the daemon it spawns take it, no other.\n const claim = daemonClaim(paths);\n if (claim !== null && claim !== process.pid && claim !== process.ppid) throw new CliError(\"busy\", `Profile ${paths.name} is kept for the daemon that process ${claim} starts`, { pid: claim });\n const mine = String(process.pid);\n const draft = `${paths.lock}.${mine}`;\n const start = startPath(paths.lock, process.pid);\n const started = processStart(process.pid);\n let placed = false;\n writeFileSync(draft, mine, { mode: 0o600 });\n if (started !== null) writeFileSync(start, started, { mode: 0o600 });\n try {\n for (let attempt = 0; attempt < 3; attempt++) {\n if (placeLock(draft, paths.lock, mine)) {\n placed = true;\n heldHere.add(paths.lock);\n let released = false;\n return () => {\n if (released) return;\n released = true;\n heldHere.delete(paths.lock);\n try { if (readFileSync(paths.lock, \"utf8\").trim() === mine) rmSync(paths.lock, { force: true }); } catch { /* gone already */ }\n rmSync(start, { force: true });\n };\n }\n let seen: Stats;\n try { seen = lstatSync(paths.lock); } catch { continue; }\n const owner = lockOwner(paths);\n if (owner !== null) throw new CliError(\"busy\", `Profile ${paths.name} is in use by process ${owner}`, { pid: owner });\n if (seen.size === 0 && Date.now() - seen.mtimeMs < EMPTY_LOCK_GRACE_MS) break;\n removeStaleLock(paths.lock, seen);\n }\n } finally {\n rmSync(draft, { force: true });\n if (!placed) rmSync(start, { force: true });\n }\n throw new CliError(\"busy\", `Profile ${paths.name} is in use`);\n}\n\n/** The locks this process holds: a lock naming this pid that is not one of them is a dead holder's whose pid it has now. */\nconst heldHere = new Set<string>();\n\nfunction startPath(lock: string, pid: number): string {\n return `${lock}.${pid}.start`;\n}\n\n/**\n * When the process `pid` started, as a text that is the same for as long as it runs and another for the next process\n * given that pid; null where it cannot be read (Windows, a `/proc` that hides others' processes, no `ps`). On Linux the\n * boot's id and `/proc/<pid>/stat`'s start time (clock ticks since boot); elsewhere `ps -o lstart=`.\n */\nexport function processStart(pid: number): string | null {\n try {\n if (process.platform === \"linux\") {\n const stat = readFileSync(`/proc/${pid}/stat`, \"utf8\");\n // Fields after the command, which may hold spaces and parentheses: the start time is field 22.\n const ticks = stat.slice(stat.lastIndexOf(\")\") + 2).split(\" \")[19];\n if (!ticks || !/^\\d+$/.test(ticks)) return null;\n return `${readFileSync(\"/proc/sys/kernel/random/boot_id\", \"utf8\").trim()} ${ticks}`;\n }\n if (process.platform === \"win32\") return null;\n const lstart = execFileSync(\"ps\", [\"-o\", \"lstart=\", \"-p\", String(pid)], {\n encoding: \"utf8\", stdio: [\"ignore\", \"pipe\", \"ignore\"], timeout: 2_000, env: { ...childEnv(), LC_ALL: \"C\" },\n }).trim();\n return lstart || null;\n } catch {\n return null;\n }\n}\n\n/** How long an empty lock is taken for one an older release is still writing its pid into. */\nconst EMPTY_LOCK_GRACE_MS = 1_000;\n\n/**\n * Links `draft` (which holds `mine`) as the lock; false when there is a lock already. Where the file system has no\n * hard links, the lock is made in place, as before.\n */\nfunction placeLock(draft: string, lock: string, mine: string): boolean {\n try {\n linkSync(draft, lock);\n return true;\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code === \"EEXIST\") return false;\n if (![\"EPERM\", \"ENOTSUP\", \"EOPNOTSUPP\", \"ENOSYS\"].includes(code ?? \"\")) throw error;\n }\n let fd: number;\n try { fd = openSync(lock, \"wx\", 0o600); } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"EEXIST\") return false;\n throw error;\n }\n writeSync(fd, mine);\n closeSync(fd);\n return true;\n}\n\n/**\n * Removes the lock judged stale (`seen`): it is moved aside first, and removed only when what was moved is that same\n * file and holds no live pid (a freed inode is soon reused). A lock another process made in the meantime is put back.\n */\nfunction removeStaleLock(lock: string, seen: Stats): void {\n const aside = `${lock}.stale.${process.pid}`;\n try { renameSync(lock, aside); } catch { return; }\n try {\n const moved = lstatSync(aside);\n if (moved.ino === seen.ino && moved.dev === seen.dev && holder(aside, lock) === null && moved.size === seen.size) {\n const pid = lockPid(aside);\n if (pid !== null && pid !== process.pid) rmSync(startPath(lock, pid), { force: true });\n return;\n }\n try { linkSync(aside, lock); } catch { /* another lock is there already */ }\n } finally {\n rmSync(aside, { force: true });\n }\n}\n\n/**\n * The pid holding the profile, or null when nobody does: the lock's process is gone, or its pid is another process's\n * now (it started at another time than the lock's holder, or it is this process, which does not hold the lock).\n */\nexport function lockOwner(paths: ProfilePaths): number | null {\n return holder(paths.lock, paths.lock);\n}\n\nfunction lockPid(file: string): number | null {\n let pid: number;\n try { pid = Number(readFileSync(file, \"utf8\").trim()); } catch { return null; }\n return Number.isInteger(pid) && pid > 0 ? pid : null;\n}\n\n/** `file`: the lock, or the stale one moved aside; `lock`: the lock's own path, beside which its start is. */\nfunction holder(file: string, lock: string): number | null {\n const pid = lockPid(file);\n if (pid === null) return null;\n if (pid === process.pid) return heldHere.has(lock) ? pid : null;\n try { process.kill(pid, 0); } catch (error) { if ((error as NodeJS.ErrnoException).code !== \"EPERM\") return null; }\n let recorded: string;\n try { recorded = readFileSync(startPath(lock, pid), \"utf8\").trim(); } catch { return pid; }\n const now = processStart(pid);\n return recorded && now !== null && now !== recorded ? null : pid;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAYA,SAAgB,YAAY,QAAgB,YAAoB,MAAsB;CACpF,MAAM,OAAO,WAAW,QAAQ,CAAC,CAAC,OAAO,UAAU,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,MAAM,GAAG,EAAE;CAC9E,KAAK,MAAM,QAAQ,CAAC,QAAQ,IAAI,iBAAiB,OAAO,CAAC,GAAG;EAC1D,IAAI,CAAC,QAAQ,CAAC,WAAW,IAAI,KAAK,CAAC,WAAW,IAAI,GAAG;EACrD,MAAM,OAAO,KAAK,MAAM,GAAG,OAAO,GAAG,QAAQ,IAAI;EACjD,IAAI,OAAO,WAAW,IAAI,KAAK,KAAK,OAAO;CAC7C;CACA,OAAO,KAAK,QAAQ,GAAG,OAAO,GAAG,QAAQ,SAAS,KAAK,EAAE,GAAG,QAAQ,IAAI;AAC1E;AAEA,SAAS,WAAW,MAAuB;CACzC,IAAI;EACF,MAAM,OAAO,SAAS,IAAI;EAC1B,OAAO,KAAK,YAAY,MAAM,CAAC,QAAQ,UAAU,KAAK,QAAQ,QA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,OAAoC;CAC5D,OAAO,OAAO,MAAM,MAAM,MAAM,IAAI;AACtC;AAEA,SAAS,QAAQ,MAA6B;CAC5C,IAAI;CACJ,IAAI;EAAE,MAAM,OAAO,aAAa,MAAM,MAAM,CAAC,CAAC,KAAK,CAAC;CAAG,QAAQ;EAAE,OAAO;CAAM;CAC9E,OAAO,OAAO,UAAU,GAAG,KAAK,MAAM,IAAI,MAAM;AAClD;;AAGA,SAAS,OAAO,MAAc,MAA6B;CACzD,MAAM,MAAM,QAAQ,IAAI;CACxB,IAAI,QAAQ,MAAM,OAAO;CACzB,IAAI,QAAQ,QAAQ,KAAK,OAAO,SAAS,IAAI,IAAI,IAAI,MAAM;CAC3D,IAAI;EAAE,QAAQ,KAAK,KAAK,CAAC;CAAG,SAAS,OAAO;EAAE,IAAK,MAAgC,SAAS,SAAS,OAAO;CAAM;CAClH,IAAI;CACJ,IAAI;EAAE,WAAW,aAAa,UAAU,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,KAAK;CAAG,QAAQ;EAAE,OAAO;CAAK;CAC1F,MAAM,MAAM,aAAa,GAAG;CAC5B,OAAO,YAAY,QAAQ,QAAQ,QAAQ,WAAW,OAAO;AAC/D"}
@@ -1,9 +1,9 @@
1
1
  import { a as fromZ32, d as utf8Decode, f as utf8Encode, i as fromBase64Url, l as toBase64Url, n as concatBytes, o as isZ32Key, s as randomBytes, t as bytesEqual, u as toZ32 } from "./bytes-C1DNGY18.js";
2
- import { a as domainWellKnownFile, i as domainTxtRecord, l as normalizeDomain, m as wellKnownUrl, r as dnsProofName } from "./domainProofs-BDNP1dIy.js";
3
- import { C as normalizeAtprotoHandle, E as verifyAtprotoRecordProof, S as isAtprotoDid, T as AtprotoProofError, _ as ATPROTO_PROOF_COLLECTION, a as verifiedAtprotoHandle, b as atprotoProofRkey, c as assertDomainRecord, d as chosenResolver, f as resolverById, g as ATPROTO_FULL_SCOPE, h as ATPROTO_DECLARED_SCOPE, i as resolveAtprotoHandle, l as assertNip05, p as pkarrRelays, r as resolveAtprotoDid, s as DomainCheckError, t as assertPublicServer, u as assertPublicHost, v as ATPROTO_PROOF_SCOPE, w as shortAtprotoDid, x as checkAtprotoProofRecord, y as atprotoProofRecord } from "./resolve-CIc3KZMV.js";
2
+ import { a as domainWellKnownFile, i as domainTxtRecord, l as normalizeDomain, m as wellKnownUrl, r as dnsProofName } from "./domainProofs-b3Y1Gj9g.js";
3
+ import { C as isAtprotoDid, D as verifyAtprotoRecordProof, E as AtprotoProofError, S as checkAtprotoProofRecord, T as shortAtprotoDid, _ as ATPROTO_FULL_SCOPE, a as verifiedAtprotoHandle, b as atprotoProofRecord, c as assertDomainRecord, d as chosenResolver, f as resolverById, g as ATPROTO_DECLARED_SCOPE, i as resolveAtprotoHandle, l as assertNip05, m as pkarrRelays, r as resolveAtprotoDid, s as DomainCheckError, t as assertPublicServer, u as assertPublicHost, v as ATPROTO_PROOF_COLLECTION, w as normalizeAtprotoHandle, x as atprotoProofRkey, y as ATPROTO_PROOF_SCOPE } from "./resolve-DNX-eecG.js";
4
4
  import { _ as sshSignCommand, a as PUBKY_RELAYS, c as isConfigured, d as providerForIssuer, g as parseSshSignature, h as parseSshPublicKey, i as validForgeLogin, l as issuerFor, m as SshSigError, n as SSH_FORGE_LABEL, o as audiences, p as SSHSIG_NAMESPACE, r as checkSshForge, s as clientIdFor, t as SSH_FORGE_HOST, u as oidcProviders, v as verifySshSignature } from "./sshForges-BnvwmNj-.js";
5
5
  import { s as IdentityCheckUnavailable } from "./identityProofs-Cksc_K7_.js";
6
- import { C as normalizePubkyKey, E as pubkyProofPath, S as newPubkyProofFolder, T as pubkyProofFile, _ as resolveDidDht, b as isPubkyKey, c as boundedIdentityFetch, f as DidDhtError, i as registeredIdentityProviders, s as reserveAdapterIds, t as ownDid, u as testBuild, w as pubkyProofCapability, x as isPubkyProofFolder, y as PUBKY_PROOF_MAX_BYTES } from "./ownDid-DY3rYqDI.js";
6
+ import { C as normalizePubkyKey, E as pubkyProofPath, S as newPubkyProofFolder, T as pubkyProofFile, _ as resolveDidDht, b as isPubkyKey, c as boundedIdentityFetch, f as DidDhtError, i as registeredIdentityProviders, s as reserveAdapterIds, t as ownDid, u as testBuild, w as pubkyProofCapability, x as isPubkyProofFolder, y as PUBKY_PROOF_MAX_BYTES } from "./ownDid-oa-T2vmZ.js";
7
7
  import { c as openRelayPayload, f as decodeDnsAnswers, h as readDnsName, i as RELAY_PAYLOAD_MAX_BYTES } from "./pkarr-BQo4PcCg.js";
8
8
  import { ed25519 } from "@noble/curves/ed25519.js";
9
9
  import { sha256 } from "@noble/hashes/sha2.js";
@@ -3468,8 +3468,12 @@ async function resolve(did, method, options) {
3468
3468
  documentUrl
3469
3469
  };
3470
3470
  }
3471
+ const fetch = (url, init) => options.fetch(url, {
3472
+ ...init,
3473
+ ownPkarrRelay: true
3474
+ });
3471
3475
  const found = await (options.dht ?? resolveDidDht)(did, {
3472
- fetch: options.fetch,
3476
+ fetch,
3473
3477
  signal: options.signal,
3474
3478
  relays: pkarrRelays()
3475
3479
  }).catch((e) => {
@@ -5023,4 +5027,4 @@ function identityProvider(id, providers = identityProviders()) {
5023
5027
  }
5024
5028
  export { SignerTimeout as a, parseProofBunker as i, identityProvider as n, identityProviders as r, IDENTITY_PROVIDERS as t };
5025
5029
 
5026
- //# sourceMappingURL=registry-Bep4umOM.js.map
5030
+ //# sourceMappingURL=registry-DbTLLs3y.js.map