fedipod 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +123 -0
- package/architecture.svg +89 -0
- package/bin/fedipod.mjs +2303 -0
- package/cli.md +243 -0
- package/groups.md +85 -0
- package/gui.md +99 -0
- package/lib/account.mjs +87 -0
- package/lib/admin.mjs +1606 -0
- package/lib/atproto.mjs +310 -0
- package/lib/bskyfeed.mjs +166 -0
- package/lib/bskygroup.mjs +162 -0
- package/lib/c2s.mjs +305 -0
- package/lib/certs.mjs +265 -0
- package/lib/deliver.mjs +249 -0
- package/lib/directory.mjs +90 -0
- package/lib/embed.mjs +214 -0
- package/lib/export-collections.mjs +161 -0
- package/lib/front-core.mjs +322 -0
- package/lib/gateway-core.mjs +115 -0
- package/lib/guard.mjs +213 -0
- package/lib/home.mjs +161 -0
- package/lib/httpsig.mjs +109 -0
- package/lib/import.mjs +357 -0
- package/lib/intake.mjs +1710 -0
- package/lib/keys.mjs +139 -0
- package/lib/lease.mjs +190 -0
- package/lib/localapi.mjs +87 -0
- package/lib/mastoapi.mjs +1588 -0
- package/lib/migrate.mjs +127 -0
- package/lib/oidc-auth.mjs +53 -0
- package/lib/podrdf.mjs +132 -0
- package/lib/ports.mjs +27 -0
- package/lib/publisher.mjs +1003 -0
- package/lib/remote.mjs +303 -0
- package/lib/safefetch.mjs +235 -0
- package/lib/setup.mjs +262 -0
- package/lib/social.mjs +505 -0
- package/lib/storage.mjs +170 -0
- package/lib/store.mjs +470 -0
- package/lib/streaming.mjs +154 -0
- package/lib/tagfeed.mjs +158 -0
- package/lib/ua.mjs +29 -0
- package/lib/update.mjs +91 -0
- package/lib/webpush.mjs +98 -0
- package/lib/wire.mjs +762 -0
- package/package.json +60 -0
- package/phanpy/dist/404.html +40 -0
- package/phanpy/dist/_headers +2 -0
- package/phanpy/dist/apple-touch-icon.png +0 -0
- package/phanpy/dist/assets/ICONS-DIPJeU0C.js +2 -0
- package/phanpy/dist/assets/ICONS-DIPJeU0C.js.map +1 -0
- package/phanpy/dist/assets/ScheduledAtField-D-Abfo4J.js +183 -0
- package/phanpy/dist/assets/ScheduledAtField-D-Abfo4J.js.map +1 -0
- package/phanpy/dist/assets/Temml-CCjoacWt.woff2 +0 -0
- package/phanpy/dist/assets/__vite-browser-external-C7iut881.js +2 -0
- package/phanpy/dist/assets/__vite-browser-external-C7iut881.js.map +1 -0
- package/phanpy/dist/assets/boosts-carousel-BiOaNdMT.jpg +0 -0
- package/phanpy/dist/assets/catch-up-O5q5C75Z.png +0 -0
- package/phanpy/dist/assets/chunk-aKtaBQYM.js +1 -0
- package/phanpy/dist/assets/compose-CFEx7wb4.js +2 -0
- package/phanpy/dist/assets/compose-CFEx7wb4.js.map +1 -0
- package/phanpy/dist/assets/compose-ZJN5xSb4.js +35 -0
- package/phanpy/dist/assets/compose-ZJN5xSb4.js.map +1 -0
- package/phanpy/dist/assets/debug.module-YFQgwnIr.js +52 -0
- package/phanpy/dist/assets/debug.module-YFQgwnIr.js.map +1 -0
- package/phanpy/dist/assets/dom-p1YcJ5Rw.js +2 -0
- package/phanpy/dist/assets/dom-p1YcJ5Rw.js.map +1 -0
- package/phanpy/dist/assets/home-mobile-dark@2x-Dc-J8-SM.png +0 -0
- package/phanpy/dist/assets/home-mobile-light@2x-Bd3fod8m.png +0 -0
- package/phanpy/dist/assets/home-tablet-dark@2x-BgcNI8le.png +0 -0
- package/phanpy/dist/assets/home-tablet-light@2x-BW2RV9T6.png +0 -0
- package/phanpy/dist/assets/icons/add-circle-line-WD0mwORD.js +1 -0
- package/phanpy/dist/assets/icons/alert-line-CpFUMf9s.js +1 -0
- package/phanpy/dist/assets/icons/android-2-line-Bzxnrd3S.js +1 -0
- package/phanpy/dist/assets/icons/announcement-line-5nwaJFJm.js +1 -0
- package/phanpy/dist/assets/icons/arrow-down-circle-line-a7Id9-Iv.js +1 -0
- package/phanpy/dist/assets/icons/arrow-down-line-B8uzXzq6.js +1 -0
- package/phanpy/dist/assets/icons/arrow-left-line-CGrGT9C-.js +1 -0
- package/phanpy/dist/assets/icons/arrow-right-line-CE-HERfX.js +1 -0
- package/phanpy/dist/assets/icons/arrow-to-up-line-CvdQjmcy.js +1 -0
- package/phanpy/dist/assets/icons/arrow-up-circle-line-DEparSNF.js +1 -0
- package/phanpy/dist/assets/icons/arrow-up-line-C7yBeugc.js +1 -0
- package/phanpy/dist/assets/icons/arrows-right-line-BtbXmJGP.js +1 -0
- package/phanpy/dist/assets/icons/at-line-CF66Bznk.js +1 -0
- package/phanpy/dist/assets/icons/attachment-line-BY8It-l9.js +1 -0
- package/phanpy/dist/assets/icons/blockquote-line-BS6pU_hm.js +1 -0
- package/phanpy/dist/assets/icons/board-line-C0UWXyA6.js +1 -0
- package/phanpy/dist/assets/icons/bookmark-line-1CtX5JLF.js +1 -0
- package/phanpy/dist/assets/icons/building-5-line-Dd59MzbO.js +1 -0
- package/phanpy/dist/assets/icons/bus-2-line-6_dvA0GG.js +1 -0
- package/phanpy/dist/assets/icons/calendar-day-line-Crpl_fmu.js +1 -0
- package/phanpy/dist/assets/icons/calendar-month-line-vommts2C.js +1 -0
- package/phanpy/dist/assets/icons/calendar-time-add-line-BU_DTlQk.js +1 -0
- package/phanpy/dist/assets/icons/camera-line-Cv69MEei.js +1 -0
- package/phanpy/dist/assets/icons/celebrate-line-B8DvIoi0.js +1 -0
- package/phanpy/dist/assets/icons/chart-bar-line-FK-QOmtF.js +1 -0
- package/phanpy/dist/assets/icons/chart-line-line-BGcJAFWw.js +1 -0
- package/phanpy/dist/assets/icons/chat-3-line-YFK2-hwz.js +1 -0
- package/phanpy/dist/assets/icons/check-circle-line-DsAxFr5-.js +1 -0
- package/phanpy/dist/assets/icons/clipboard-line-BBp364gJ.js +1 -0
- package/phanpy/dist/assets/icons/close-circle-line-CICdiuGz.js +1 -0
- package/phanpy/dist/assets/icons/close-line-DYrFWcjv.js +1 -0
- package/phanpy/dist/assets/icons/cloud-line-tiQAbah8.js +1 -0
- package/phanpy/dist/assets/icons/code-line-fAl8iiV3.js +1 -0
- package/phanpy/dist/assets/icons/comment-2-line-CR3g7WeB.js +1 -0
- package/phanpy/dist/assets/icons/copy-2-line-CLW69yF5.js +1 -0
- package/phanpy/dist/assets/icons/delete-2-line-B8xmbr4n.js +1 -0
- package/phanpy/dist/assets/icons/document-3-line-DBGNhAg2.js +1 -0
- package/phanpy/dist/assets/icons/document-line-C7mb9sb7.js +1 -0
- package/phanpy/dist/assets/icons/down-line-BGqSSThd.js +1 -0
- package/phanpy/dist/assets/icons/edit-4-line-DcgGaEhx.js +1 -0
- package/phanpy/dist/assets/icons/emoji-2-line-D8YgnM-y.js +1 -0
- package/phanpy/dist/assets/icons/exit-line-Dc07BS-x.js +1 -0
- package/phanpy/dist/assets/icons/external-link-line-BvpSkmjO.js +1 -0
- package/phanpy/dist/assets/icons/eye-2-line-CiWXx-f_.js +1 -0
- package/phanpy/dist/assets/icons/eye-close-line-BgTaSJ4P.js +1 -0
- package/phanpy/dist/assets/icons/filter-2-line-B_mR2usy.js +1 -0
- package/phanpy/dist/assets/icons/filter-line-C_nm-3cU.js +1 -0
- package/phanpy/dist/assets/icons/flag-1-line-C2HB05I0.js +1 -0
- package/phanpy/dist/assets/icons/forbid-circle-line-D3LTT9yd.js +1 -0
- package/phanpy/dist/assets/icons/formula-line-DLrt2d6j.js +1 -0
- package/phanpy/dist/assets/icons/grid-line-CgUmEikf.js +1 -0
- package/phanpy/dist/assets/icons/group-line-C5fnX0wU.js +1 -0
- package/phanpy/dist/assets/icons/hand-finger-2-line-BGgxbuL9.js +1 -0
- package/phanpy/dist/assets/icons/hashtag-line-CyTEEXBb.js +1 -0
- package/phanpy/dist/assets/icons/heart-crack-line-BZddbO2C.js +1 -0
- package/phanpy/dist/assets/icons/heart-line-CJ7K47J4.js +1 -0
- package/phanpy/dist/assets/icons/history-2-line-kWWvFzqv.js +1 -0
- package/phanpy/dist/assets/icons/history-line-bGQiwbTH.js +1 -0
- package/phanpy/dist/assets/icons/home-3-line-fRU1zeLG.js +1 -0
- package/phanpy/dist/assets/icons/information-line-iNk6-sOY.js +1 -0
- package/phanpy/dist/assets/icons/keyboard-line-DsCyuQNz.js +1 -0
- package/phanpy/dist/assets/icons/layout-4-line-CZkOX52Z.js +1 -0
- package/phanpy/dist/assets/icons/layout-5-line-B_znt5wO.js +1 -0
- package/phanpy/dist/assets/icons/left-line-eUw0tya4.js +1 -0
- package/phanpy/dist/assets/icons/lightning-line-DaKoDdix.js +1 -0
- package/phanpy/dist/assets/icons/link-2-line-DCqLmMA7.js +1 -0
- package/phanpy/dist/assets/icons/list-check-line-BAxosBh9.js +1 -0
- package/phanpy/dist/assets/icons/lock-line-CPoaXeUW.js +1 -0
- package/phanpy/dist/assets/icons/mail-line-B0P8aa1L.js +1 -0
- package/phanpy/dist/assets/icons/moon-line-CEqNAToP.js +1 -0
- package/phanpy/dist/assets/icons/more-1-fill-Dw2e5xab.js +1 -0
- package/phanpy/dist/assets/icons/more-3-line-BIiVjYTz.js +1 -0
- package/phanpy/dist/assets/icons/notification-line-BZZq2Gtu.js +1 -0
- package/phanpy/dist/assets/icons/pencil-line-CKh8-A1v.js +1 -0
- package/phanpy/dist/assets/icons/photo-album-line-Bnfg2u40.js +1 -0
- package/phanpy/dist/assets/icons/pin-line-DpTolyhs.js +1 -0
- package/phanpy/dist/assets/icons/play-fill-B0-G_8lX.js +1 -0
- package/phanpy/dist/assets/icons/qrcode-2-line-B6SPCaHn.js +1 -0
- package/phanpy/dist/assets/icons/quill-pen-line-B6LUrnCP.js +1 -0
- package/phanpy/dist/assets/icons/quote-left-fill-hQZ1cj_6.js +1 -0
- package/phanpy/dist/assets/icons/radar-line-CKyroTth.js +1 -0
- package/phanpy/dist/assets/icons/react-line-CoIKhhtK.js +1 -0
- package/phanpy/dist/assets/icons/refresh-2-line-D0mTF97S.js +1 -0
- package/phanpy/dist/assets/icons/right-line-B3KWJaqc.js +1 -0
- package/phanpy/dist/assets/icons/rocket-line-4KZl537D.js +1 -0
- package/phanpy/dist/assets/icons/round-fill-C69NTrZ0.js +1 -0
- package/phanpy/dist/assets/icons/round-line-B9k_1uo-.js +1 -0
- package/phanpy/dist/assets/icons/route-line-B28ReHcE.js +1 -0
- package/phanpy/dist/assets/icons/rows-4-line-CrBniagM.js +1 -0
- package/phanpy/dist/assets/icons/scan-line-DSf74YdP.js +1 -0
- package/phanpy/dist/assets/icons/search-2-line-B6geIU1z.js +1 -0
- package/phanpy/dist/assets/icons/settings-3-line-azJwK47w.js +1 -0
- package/phanpy/dist/assets/icons/settings-6-line-C_5zc5YR.js +1 -0
- package/phanpy/dist/assets/icons/share-2-line-D5MxWjrm.js +1 -0
- package/phanpy/dist/assets/icons/share-forward-line-Cp61fZzZ.js +1 -0
- package/phanpy/dist/assets/icons/sparkles-2-line-DYYyXTaW.js +1 -0
- package/phanpy/dist/assets/icons/sparkles-line-C2hY1s6I.js +1 -0
- package/phanpy/dist/assets/icons/time-line-BF3eet1v.js +1 -0
- package/phanpy/dist/assets/icons/transfer-4-line-oisfvTBw.js +1 -0
- package/phanpy/dist/assets/icons/translate-line-BFWol2Ce.js +1 -0
- package/phanpy/dist/assets/icons/unlock-line-X_x5vwv3.js +1 -0
- package/phanpy/dist/assets/icons/upload-3-line-DgzwUJeW.js +1 -0
- package/phanpy/dist/assets/icons/user-4-line-BVSynZCp.js +1 -0
- package/phanpy/dist/assets/icons/user-add-2-line-BlGS5Q8q.js +1 -0
- package/phanpy/dist/assets/icons/user-add-line-BbXdHG4z.js +1 -0
- package/phanpy/dist/assets/icons/user-edit-line-BFAHOV0X.js +1 -0
- package/phanpy/dist/assets/icons/user-follow-line-BXux0wSd.js +1 -0
- package/phanpy/dist/assets/icons/user-star-line-DdYlpHLU.js +1 -0
- package/phanpy/dist/assets/icons/user-warning-line-Cj43j0_E.js +1 -0
- package/phanpy/dist/assets/icons/user-x-line-DIDgNlPH.js +1 -0
- package/phanpy/dist/assets/icons/volume-line-Bs390KQt.js +1 -0
- package/phanpy/dist/assets/icons/volume-mute-line-DzlzIqFZ.js +1 -0
- package/phanpy/dist/assets/icons/walk-line-yNXfB-md.js +1 -0
- package/phanpy/dist/assets/icons/world-2-line-CenkGIwj.js +1 -0
- package/phanpy/dist/assets/icons/zoom-in-line-CaENUphf.js +1 -0
- package/phanpy/dist/assets/icons/zoom-out-line-BDNk0EWo.js +1 -0
- package/phanpy/dist/assets/instances-BNPptnn-.json +333 -0
- package/phanpy/dist/assets/locales/ar-SA-CfheRbCu.js +1 -0
- package/phanpy/dist/assets/locales/ca-ES-DHRW86Tz.js +1 -0
- package/phanpy/dist/assets/locales/cs-CZ-CKoqEuA1.js +1 -0
- package/phanpy/dist/assets/locales/de-DE-ByRPMRFy.js +1 -0
- package/phanpy/dist/assets/locales/eo-UY-CPC7wLCS.js +1 -0
- package/phanpy/dist/assets/locales/es-ES-dJa0Fd9t.js +1 -0
- package/phanpy/dist/assets/locales/eu-ES-C3djlPR2.js +1 -0
- package/phanpy/dist/assets/locales/fa-IR-DTT490Ck.js +1 -0
- package/phanpy/dist/assets/locales/fi-FI-B23MCPuz.js +1 -0
- package/phanpy/dist/assets/locales/fr-FR-BcaQsO5C.js +1 -0
- package/phanpy/dist/assets/locales/gl-ES-BR-CVKBN.js +1 -0
- package/phanpy/dist/assets/locales/he-IL-CfheRbCu.js +1 -0
- package/phanpy/dist/assets/locales/hu-HU-CfheRbCu.js +1 -0
- package/phanpy/dist/assets/locales/it-IT-C1136UFV.js +1 -0
- package/phanpy/dist/assets/locales/ja-JP-CRZmRAhD.js +1 -0
- package/phanpy/dist/assets/locales/kab-Cz8xH_TT.js +1 -0
- package/phanpy/dist/assets/locales/ko-KR-CG9UiY4o.js +1 -0
- package/phanpy/dist/assets/locales/lt-LT-CJcI6sHZ.js +1 -0
- package/phanpy/dist/assets/locales/nb-NO-CfheRbCu.js +1 -0
- package/phanpy/dist/assets/locales/nl-NL-DxN4Yc1t.js +1 -0
- package/phanpy/dist/assets/locales/oc-FR-CfheRbCu.js +1 -0
- package/phanpy/dist/assets/locales/pl-PL-DkwGXf6P.js +1 -0
- package/phanpy/dist/assets/locales/pseudo-LOCALE-CQ4XxkQ0.js +1 -0
- package/phanpy/dist/assets/locales/pt-BR-nGL0HdFS.js +1 -0
- package/phanpy/dist/assets/locales/pt-PT-Cp17aj2z.js +1 -0
- package/phanpy/dist/assets/locales/ru-RU-0Y8cIoaK.js +1 -0
- package/phanpy/dist/assets/locales/th-TH-CfheRbCu.js +1 -0
- package/phanpy/dist/assets/locales/tok-CfheRbCu.js +1 -0
- package/phanpy/dist/assets/locales/tr-TR-CfheRbCu.js +1 -0
- package/phanpy/dist/assets/locales/uk-UA-C5E3dFBf.js +1 -0
- package/phanpy/dist/assets/locales/zh-CN-BHJi7_et.js +1 -0
- package/phanpy/dist/assets/locales/zh-TW-CfheRbCu.js +1 -0
- package/phanpy/dist/assets/main-BdqNbG-a.js +26 -0
- package/phanpy/dist/assets/main-BdqNbG-a.js.map +1 -0
- package/phanpy/dist/assets/mock-home-DGhR__He.js +2 -0
- package/phanpy/dist/assets/mock-home-DGhR__He.js.map +1 -0
- package/phanpy/dist/assets/multi-column-ROck0NVt.jpg +0 -0
- package/phanpy/dist/assets/multi-hashtag-timeline-DH5INVHi.jpg +0 -0
- package/phanpy/dist/assets/nested-comments-thread-hv59kZLc.jpg +0 -0
- package/phanpy/dist/assets/polyfill-force-H8sUkLGp.js +2 -0
- package/phanpy/dist/assets/polyfill-force-H8sUkLGp.js.map +1 -0
- package/phanpy/dist/assets/pwa-viewport-ogKbF51K.js +20 -0
- package/phanpy/dist/assets/pwa-viewport-ogKbF51K.js.map +1 -0
- package/phanpy/dist/assets/style-B1iLPTPR.css +2 -0
- package/phanpy/dist/assets/temml-DuyIQMei.js +97 -0
- package/phanpy/dist/assets/temml-DuyIQMei.js.map +1 -0
- package/phanpy/dist/assets/tinyld.light.node-DtbBhLYC.js +2 -0
- package/phanpy/dist/assets/tinyld.light.node-DtbBhLYC.js.map +1 -0
- package/phanpy/dist/assets/year-in-posts-B2lywqdx.png +0 -0
- package/phanpy/dist/assets/year-in-posts-DJv_star.js +3 -0
- package/phanpy/dist/assets/year-in-posts-DJv_star.js.map +1 -0
- package/phanpy/dist/compose/index.html +20 -0
- package/phanpy/dist/favicon.ico +0 -0
- package/phanpy/dist/index.html +73 -0
- package/phanpy/dist/logo-192.png +0 -0
- package/phanpy/dist/logo-512.png +0 -0
- package/phanpy/dist/logo-badge-72.png +0 -0
- package/phanpy/dist/logo-maskable-512.png +0 -0
- package/phanpy/dist/logo-monochrome-512.png +0 -0
- package/phanpy/dist/logo-monochrome-maskable-512.png +0 -0
- package/phanpy/dist/manifest.webmanifest +1 -0
- package/phanpy/dist/og-image-2.jpg +0 -0
- package/phanpy/dist/og-image.png +0 -0
- package/phanpy/dist/robots.txt +2 -0
- package/phanpy/dist/sw.js +25 -0
- package/phanpy/dist/version.json +1 -0
- package/run-agent.mjs +805 -0
- package/scripts/build-dist.mjs +37 -0
- package/scripts/verify-ui.mjs +60 -0
- package/ui/README.md +23 -0
- package/vendor/gate.cjs +132 -0
- package/vendor/idp-grant.cjs +394 -0
- package/vendor/jfetch.cjs +16 -0
- package/web/admin/admin.js +958 -0
- package/web/admin/bar.css +64 -0
- package/web/admin/bar.js +61 -0
- package/web/admin/client/client.js +66 -0
- package/web/admin/client/index.html +42 -0
- package/web/admin/index.html +493 -0
- package/web/admin/setup/index.html +172 -0
- package/web/admin/setup/setup.js +268 -0
- package/web/admin/window.css +55 -0
- package/web/admin/window.js +136 -0
- package/web/front/install.sh +69 -0
- package/web/front/new-account.html +424 -0
- package/web/front/run.html +138 -0
- package/web/front/solid-client-authn.bundle.js +2 -0
package/run-agent.mjs
ADDED
|
@@ -0,0 +1,805 @@
|
|
|
1
|
+
// run-agent.mjs — fedipod: a standalone single-actor ActivityPub
|
|
2
|
+
// agent. The remote pod is a RELAY: it serves the public wire face
|
|
3
|
+
// (/activitypods-js/ap/) and buffers inbound mail in a public-append inbox
|
|
4
|
+
// while this process is off, and it keeps one private document, the lease,
|
|
5
|
+
// because a lock only one machine can reach coordinates nothing.
|
|
6
|
+
//
|
|
7
|
+
// Everything else private is on THIS machine — the RDF truth and the
|
|
8
|
+
// operational state, in a directory beside the credential and the signing key.
|
|
9
|
+
// So a machine holding only the credential file does NOT resume the actor: it
|
|
10
|
+
// resumes the identity with an empty timeline, contacts, blocklist and
|
|
11
|
+
// notifications, and `fedipod rebuild` recovers the posts the pod still
|
|
12
|
+
// carries. `privateRoot` absent in credential.json is the pre-2026-08-03
|
|
13
|
+
// layout and still means both trees are on the pod; `fedipod upgrade`
|
|
14
|
+
// says so and `state --all` moves them.
|
|
15
|
+
//
|
|
16
|
+
// node run-agent.mjs # or: bin/fedipod.mjs run
|
|
17
|
+
//
|
|
18
|
+
// Env: AP_HOME (credential dir + local log, default ~/.fedipod, or
|
|
19
|
+
// ~/.activitypod on an install that predates the rename — see lib/home.mjs),
|
|
20
|
+
// AP_PORT (UI/API/admin, default 8030),
|
|
21
|
+
// AP_GATE_TOKEN (optional loopback gate; absent → open, loopback-only).
|
|
22
|
+
//
|
|
23
|
+
// Until `bin/fedipod.mjs setup` has minted a credential the agent idles:
|
|
24
|
+
// UI + admin up, no federation.
|
|
25
|
+
|
|
26
|
+
import fs from 'node:fs';
|
|
27
|
+
import os from 'node:os';
|
|
28
|
+
import path from 'node:path';
|
|
29
|
+
import { pathToFileURL } from 'node:url';
|
|
30
|
+
|
|
31
|
+
import { PodStore } from './lib/store.mjs';
|
|
32
|
+
import { apRoot, rootOf, writeJsonAtomic } from './lib/home.mjs';
|
|
33
|
+
import { ensureTrustedTls } from './lib/certs.mjs';
|
|
34
|
+
import { storageFor } from './lib/storage.mjs';
|
|
35
|
+
import { resolveKeys } from './lib/keys.mjs';
|
|
36
|
+
import { RemotePod } from './lib/remote.mjs';
|
|
37
|
+
import { PodRdf } from './lib/podrdf.mjs';
|
|
38
|
+
import { Deliverer } from './lib/deliver.mjs';
|
|
39
|
+
import { Publisher } from './lib/publisher.mjs';
|
|
40
|
+
import { Intake } from './lib/intake.mjs';
|
|
41
|
+
import { TagFeed } from './lib/tagfeed.mjs';
|
|
42
|
+
import { ImportWorker } from './lib/import.mjs';
|
|
43
|
+
import { Atproto } from './lib/atproto.mjs';
|
|
44
|
+
import { BskyFeed } from './lib/bskyfeed.mjs';
|
|
45
|
+
import { BskyGroup } from './lib/bskygroup.mjs';
|
|
46
|
+
import { Lease } from './lib/lease.mjs';
|
|
47
|
+
import { startAdmin } from './lib/admin.mjs';
|
|
48
|
+
import { exposureProblem, hostLabel } from './lib/guard.mjs';
|
|
49
|
+
import { pendingSteps } from './lib/migrate.mjs';
|
|
50
|
+
import { apUrls } from './lib/wire.mjs';
|
|
51
|
+
import { followActor, unfollowActor, resolveHandle } from './lib/social.mjs';
|
|
52
|
+
|
|
53
|
+
export class Agent {
|
|
54
|
+
constructor({ home, log }) {
|
|
55
|
+
this.home = home;
|
|
56
|
+
this.log = log;
|
|
57
|
+
this.logRing = [];
|
|
58
|
+
this.store = new PodStore({ log });
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
readCredential() {
|
|
62
|
+
try { return JSON.parse(fs.readFileSync(path.join(this.home, 'credential.json'), 'utf8')); }
|
|
63
|
+
catch { return null; }
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
configured() { return !!this.remote && !!this.store.getConfig(); }
|
|
67
|
+
|
|
68
|
+
// Where the private half lives. `privateRoot` in the credential file names a
|
|
69
|
+
// container — by default a plain directory beside the credential, and a pod
|
|
70
|
+
// on this machine if you move it there — under which the same two trees are
|
|
71
|
+
// laid out as on the pod. Absent means on the pod, exactly as before, so an
|
|
72
|
+
// existing install is untouched.
|
|
73
|
+
privateUrls(cred, urls = this.urls) {
|
|
74
|
+
if (!cred.privateRoot) {
|
|
75
|
+
return { state: urls.state, fediverse: urls.fediverse, archive: urls.home + 'inbox-archive/', elsewhere: false };
|
|
76
|
+
}
|
|
77
|
+
const base = cred.privateRoot.endsWith('/') ? cred.privateRoot : cred.privateRoot + '/';
|
|
78
|
+
return { state: base + 'ap-state/', fediverse: base + 'fediverse/', archive: base + 'inbox-archive/', elsewhere: true };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// A container to keep the private half in. On the pod it is reached with the
|
|
82
|
+
// credential; a local pod plainly, with a token header when it is gated
|
|
83
|
+
// (dk's is); a directory is not reached over anything at all.
|
|
84
|
+
privateStorage(cred, which, urls = this.urls) {
|
|
85
|
+
const url = this.privateUrls(cred, urls)[which];
|
|
86
|
+
if (!cred.privateRoot) return storageFor(url, (u, i) => this.remote.fetch(u, i));
|
|
87
|
+
const token = process.env.AP_STATE_TOKEN || '';
|
|
88
|
+
return storageFor(url, (u, i) => fetch(u, token
|
|
89
|
+
? { ...i, headers: { ...(i?.headers || {}), 'x-dk-token': token } }
|
|
90
|
+
: i));
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
logLines(n = 100) { return this.logRing.slice(-n); }
|
|
94
|
+
|
|
95
|
+
status() {
|
|
96
|
+
const cfg = this.store.getConfig();
|
|
97
|
+
const contacts = this.store.getContacts();
|
|
98
|
+
return {
|
|
99
|
+
configured: this.configured(),
|
|
100
|
+
mode: !this.configured() ? 'unconfigured' : this.viewer ? 'viewer' : 'active',
|
|
101
|
+
kind: cfg?.kind || 'person',
|
|
102
|
+
handle: cfg?.handle || null,
|
|
103
|
+
actor: this.urls?.actor || null,
|
|
104
|
+
followers: contacts.followers.length,
|
|
105
|
+
following: contacts.following.length,
|
|
106
|
+
queue: this.store.getQueue().length,
|
|
107
|
+
deadLetters: this.store.getDeadLetters().length,
|
|
108
|
+
blockedDomains: this.store.getBlocklist().domains.length,
|
|
109
|
+
push: this.intake?.wsState || 'n/a',
|
|
110
|
+
// Measured by the last sweep from the listing it already fetched, so
|
|
111
|
+
// asking costs nothing. What the admin page prompts on.
|
|
112
|
+
inbox: this.intake?.inboxStats || null,
|
|
113
|
+
lastDrain: this.intake?.lastDrain || null,
|
|
114
|
+
tagfeed: this.tagfeed
|
|
115
|
+
? { ...this.tagfeed.config(), lastSweep: this.tagfeed.lastSweep, lastAdded: this.tagfeed.lastAdded }
|
|
116
|
+
: null,
|
|
117
|
+
atproto: this.atproto?.status() || null,
|
|
118
|
+
// Anyone asking whether this agent is hammering their server can read the
|
|
119
|
+
// answer here instead of in their access log.
|
|
120
|
+
podRequests: this.remote?.stats?.() || null,
|
|
121
|
+
update: this.updateInfo || null,
|
|
122
|
+
inboxCooldownFor: this.intake?.drainCooldownUntil
|
|
123
|
+
? Math.max(0, Math.round((this.intake.drainCooldownUntil - Date.now()) / 1000)) : 0,
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// First-run provisioning, called by the setup CLI after the credential file
|
|
128
|
+
// is written: containers, owner-only ACLs on the private trees, config into
|
|
129
|
+
// pod state. publishProfile (via connect) handles the public wire ACLs.
|
|
130
|
+
async bootstrap({ handle, name, root, kind, approveJoins = false, summary, icon, gateway }) {
|
|
131
|
+
const cred = this.readCredential();
|
|
132
|
+
if (!cred) throw new Error('no credential — run setup first');
|
|
133
|
+
if (!this.remote) {
|
|
134
|
+
this.remote = new RemotePod(cred, { log: this.log, home: this.home });
|
|
135
|
+
await this.remote.warmup();
|
|
136
|
+
}
|
|
137
|
+
this.urls = apUrls(cred.remotePod, root);
|
|
138
|
+
const priv = this.privateUrls(cred);
|
|
139
|
+
const stateStore = this.privateStorage(cred, 'state');
|
|
140
|
+
// The pod's own ap-state/ is provisioned either way: even when the rest of
|
|
141
|
+
// the private half lives elsewhere, lease.json stays here, because a lease
|
|
142
|
+
// in a pod only one machine can reach coordinates nothing.
|
|
143
|
+
await this.remote.putJson(this.urls.state + '.keep', { keep: true }, 'application/json');
|
|
144
|
+
await this.remote.setAcl(this.urls.home, []);
|
|
145
|
+
await this.remote.setAcl(this.urls.state, []);
|
|
146
|
+
if (priv.elsewhere) {
|
|
147
|
+
for (const s of [stateStore, this.privateStorage(cred, 'fediverse')]) {
|
|
148
|
+
const r = await s.write('.keep', '{"keep":true}\n', 'application/json');
|
|
149
|
+
if (!r.ok) throw new Error(`private store ${s.base}.keep → ${r.why}`);
|
|
150
|
+
}
|
|
151
|
+
this.log(`private state lives at ${cred.privateRoot} (${stateStore.kind})`);
|
|
152
|
+
} else {
|
|
153
|
+
await this.remote.putJson(this.urls.fediverse + '.keep', { keep: true }, 'application/json');
|
|
154
|
+
await this.remote.setAcl(this.urls.fediverse, []);
|
|
155
|
+
}
|
|
156
|
+
this.store.attach(stateStore);
|
|
157
|
+
// Re-running setup must not destroy state set afterwards (the UI
|
|
158
|
+
// password, above all), so load what is there and merge into it.
|
|
159
|
+
await this.store.load().catch(() => {});
|
|
160
|
+
const existing = this.store.getConfig() || {};
|
|
161
|
+
this.store.setConfig({
|
|
162
|
+
...existing,
|
|
163
|
+
remotePod: cred.remotePod, handle, name: name || existing.name || handle,
|
|
164
|
+
issuer: cred.issuerOrigin, ...(root ? { root } : {}),
|
|
165
|
+
...(kind ? { kind } : {}),
|
|
166
|
+
...(approveJoins ? { approveJoins: true } : {}),
|
|
167
|
+
...(summary ? { summary } : {}), ...(icon ? { icon } : {}),
|
|
168
|
+
// Set before the first publish, so the actor never advertises the pod
|
|
169
|
+
// inbox only to rename it a moment later.
|
|
170
|
+
...(gateway ? { gateway } : {}),
|
|
171
|
+
});
|
|
172
|
+
await this.store.flush();
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// Cache the handle in agent.json, merging so the port survives. Nothing
|
|
176
|
+
// outside this process can read pod state, so this file is the only place a
|
|
177
|
+
// sibling — or the next start, before it connects — can learn the name to
|
|
178
|
+
// build this identity's origin from.
|
|
179
|
+
recordHandle(handle) {
|
|
180
|
+
if (!handle || !this.home) return;
|
|
181
|
+
const file = path.join(this.home, 'agent.json');
|
|
182
|
+
let rec = {};
|
|
183
|
+
try { rec = JSON.parse(fs.readFileSync(file, 'utf8')) || {}; } catch { /* first run */ }
|
|
184
|
+
if (rec.handle === handle) return;
|
|
185
|
+
try { writeJsonAtomic(file, { ...rec, handle }, { mode: 0o644 }); }
|
|
186
|
+
catch { /* the agent still runs; its links are just bare */ }
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// Bring federation up from the credential file + pod state. `name` (from
|
|
190
|
+
// `run --name "…"`) updates the display name other servers show, without
|
|
191
|
+
// the collateral of re-running setup.
|
|
192
|
+
// `act: false` reads the identity and stops. Everything a confirmation prompt
|
|
193
|
+
// needs — the handle, the host, the follow counts — is in pod state that is
|
|
194
|
+
// loaded by then, while acquiring the lease, draining the inbox, subscribing a
|
|
195
|
+
// notification channel, probing the ACLs and sweeping the tag feed are all
|
|
196
|
+
// things a command you are about to decline should never have spent. The
|
|
197
|
+
// command calls connect() again, without the flag, if you say yes.
|
|
198
|
+
async connect({ name = null, repair = true, act = true } = {}) {
|
|
199
|
+
const cred = this.readCredential();
|
|
200
|
+
if (!cred) return false;
|
|
201
|
+
if (!this.remote) {
|
|
202
|
+
this.remote = new RemotePod(cred, { log: this.log, home: this.home });
|
|
203
|
+
await this.remote.warmup();
|
|
204
|
+
}
|
|
205
|
+
const probeUrls = apUrls(cred.remotePod, cred.root);
|
|
206
|
+
// Load until it actually succeeds: attaching is not the same as having
|
|
207
|
+
// read the state, and a retry that skipped the load would see an empty
|
|
208
|
+
// cache and wrongly conclude the agent was never set up.
|
|
209
|
+
if (!this.store.storage) this.store.attach(this.privateStorage(cred, 'state', probeUrls));
|
|
210
|
+
if (!this.stateLoaded) {
|
|
211
|
+
await this.store.load();
|
|
212
|
+
this.stateLoaded = true;
|
|
213
|
+
}
|
|
214
|
+
let config = this.store.getConfig();
|
|
215
|
+
if (!config) { this.log('credential present but pod state empty — run setup'); return false; }
|
|
216
|
+
// The store had to be attached from the credential, because only the config
|
|
217
|
+
// it holds says where the state really lives. If the two disagree,
|
|
218
|
+
// everything past here reads one tree and writes another.
|
|
219
|
+
// Only meaningful when the state follows the pod. With privateRoot set it
|
|
220
|
+
// is pinned by configuration and a moved pod does not move it.
|
|
221
|
+
if (!cred.privateRoot && apUrls(config.remotePod, config.root).state !== probeUrls.state) {
|
|
222
|
+
const moved = apUrls(config.remotePod, config.root).state;
|
|
223
|
+
this.log(`state tree moved (${probeUrls.state} → ${moved}) — reattaching`);
|
|
224
|
+
this.store.attach(storageFor(moved, (u, i) => this.remote.fetch(u, i)));
|
|
225
|
+
await this.store.load();
|
|
226
|
+
config = this.store.getConfig();
|
|
227
|
+
if (!config) { this.log('no state at the pod its own config names — run setup'); return false; }
|
|
228
|
+
}
|
|
229
|
+
// Resurrecting a tombstoned actor would contradict the Delete every server
|
|
230
|
+
// has already acted on, so a retired identity stays retired.
|
|
231
|
+
if (config.retiredAt) {
|
|
232
|
+
this.log(`this actor was retired on ${config.retiredAt} — run setup for a new identity`);
|
|
233
|
+
return false;
|
|
234
|
+
}
|
|
235
|
+
// A rename is a merge into the existing config, never a rewrite — the
|
|
236
|
+
// UI password and anything else set later must survive it.
|
|
237
|
+
if (name && name !== config.name) {
|
|
238
|
+
this.store.setConfig({ ...config, name });
|
|
239
|
+
config = this.store.getConfig();
|
|
240
|
+
this.renamed = true; // republish the actor once connected
|
|
241
|
+
this.log(`display name set to "${name}"`);
|
|
242
|
+
}
|
|
243
|
+
// A fronted identity (config.gateway.frontActor) advertises its ids on a
|
|
244
|
+
// shared domain; RemotePod gets the map so writes still land on the pod.
|
|
245
|
+
const publicBase = config.gateway?.frontActor
|
|
246
|
+
? config.gateway.frontActor.replace(/ap\/actor\/?$/, '') : null;
|
|
247
|
+
this.urls = apUrls(config.remotePod, config.root, { publicBase });
|
|
248
|
+
if (this.urls.toPod) this.remote.setUrlMap(this.urls.toPod);
|
|
249
|
+
// The agent answers at <handle>.localhost too, so each identity on a
|
|
250
|
+
// machine gets a browser origin of its own. Known only now: the admin
|
|
251
|
+
// server was listening before any of this was read.
|
|
252
|
+
this.authorities?.setHandle(config.handle);
|
|
253
|
+
// And write it down beside the port. Everything that links to this identity
|
|
254
|
+
// from OUTSIDE the process builds the origin from agent.json — the Actors
|
|
255
|
+
// list, a sibling's page, the next start — and an identity set up before the
|
|
256
|
+
// handle was recorded has only a port there, so every one of those links
|
|
257
|
+
// came out bare. Pod state is the authority; this is the cache of it.
|
|
258
|
+
this.recordHandle(config.handle);
|
|
259
|
+
|
|
260
|
+
// Said once, where the config is finally known. Exposure without a gate
|
|
261
|
+
// token is refused before the socket opens (startAgent), so reaching here
|
|
262
|
+
// means the token is set and the whole surface is behind it. A UI password
|
|
263
|
+
// is the second, per-person half: without one, anyone who has the token
|
|
264
|
+
// gets a client bearer for the asking.
|
|
265
|
+
// An install made before the shape changed goes on working, which is why
|
|
266
|
+
// nothing here refuses — but it should not go on SILENTLY. The whole reason
|
|
267
|
+
// this is said out loud is that bbba587 changed a default and every install
|
|
268
|
+
// that already existed kept the old layout with nothing to show for it.
|
|
269
|
+
const pending = pendingSteps(cred);
|
|
270
|
+
for (const step of pending) {
|
|
271
|
+
this.log(`this identity is on an older layout: ${step.what} (${step.why}). `
|
|
272
|
+
+ 'Run `fedipod upgrade` to see what is pending.');
|
|
273
|
+
}
|
|
274
|
+
// The record page says the same thing on its software row — the log is
|
|
275
|
+
// read by nobody who lives in the GUI.
|
|
276
|
+
this.pendingUpgrade = pending.map(s => s.what);
|
|
277
|
+
|
|
278
|
+
if (process.env.AP_ALLOWED_HOSTS && !config.uiPassword) {
|
|
279
|
+
this.log('WARNING: AP_ALLOWED_HOSTS is set and no UI password is — anyone holding '
|
|
280
|
+
+ 'AP_GATE_TOKEN can mint a client token. Run `fedipod passwd`.');
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
if (!act) return true; // reading only — see the note above
|
|
284
|
+
|
|
285
|
+
// Exactly one agent may act on a pod (inbox drains are destructive
|
|
286
|
+
// reads); later arrivals become read-only viewers of the same state.
|
|
287
|
+
// Deliberately the REMOTE pod's ap-state/, never privateRoot's: a lease
|
|
288
|
+
// that only one machine can reach is not a lease.
|
|
289
|
+
this.lease = new Lease({
|
|
290
|
+
url: this.urls.state + 'lease.json',
|
|
291
|
+
fetchImpl: (u, i) => this.remote.fetch(u, i), log: this.log,
|
|
292
|
+
});
|
|
293
|
+
this.viewer = !(await this.lease.acquire());
|
|
294
|
+
|
|
295
|
+
// Keys are LOCAL by default (the pod host never holds them); `setup
|
|
296
|
+
// --keys pod` opts into sharing them through the pod so several devices
|
|
297
|
+
// can sign as the same actor. Per-machine choice, so it rides in the
|
|
298
|
+
// credential file rather than pod state.
|
|
299
|
+
const keys = await resolveKeys(this.store, {
|
|
300
|
+
localDir: cred.keysMode === 'pod' ? null : this.home,
|
|
301
|
+
rotate: !!cred.rotateKeyOnce,
|
|
302
|
+
actorId: this.urls.actor,
|
|
303
|
+
log: this.log,
|
|
304
|
+
// Consulted only when no key material exists anywhere: if the actor
|
|
305
|
+
// already publishes a key, minting a new one would break federation.
|
|
306
|
+
actorHasKey: async () => {
|
|
307
|
+
const doc = await this.remote.getJson(this.urls.actor).catch(() => null);
|
|
308
|
+
return !!doc?.publicKey?.publicKeyPem;
|
|
309
|
+
},
|
|
310
|
+
});
|
|
311
|
+
if (cred.rotateKeyOnce) { // one-shot flag
|
|
312
|
+
const { rotateKeyOnce, ...rest } = cred;
|
|
313
|
+
writeJsonAtomic(path.join(this.home, 'credential.json'), rest);
|
|
314
|
+
}
|
|
315
|
+
this.local = new PodRdf({ storage: this.privateStorage(cred, 'fediverse') });
|
|
316
|
+
// connect() can run more than once — connectWithRetry retries after a throw,
|
|
317
|
+
// and the CLI connects for real after its confirmation. Deliverer arms a
|
|
318
|
+
// 60s queue timer in its constructor and Intake owns a poll timer and a
|
|
319
|
+
// websocket, so replacing them without stopping the old ones leaves both
|
|
320
|
+
// ticking for the life of the process.
|
|
321
|
+
this.intake?.stop();
|
|
322
|
+
this.deliverer?.stop();
|
|
323
|
+
this.tagfeed?.stop();
|
|
324
|
+
clearInterval(this.schedTimer);
|
|
325
|
+
this.deliverer = new Deliverer({
|
|
326
|
+
store: this.store, rsaPrivate: keys.rsaPrivate, keyId: this.urls.actor + '#main-key',
|
|
327
|
+
log: this.log, passive: this.viewer,
|
|
328
|
+
});
|
|
329
|
+
this.publisher = new Publisher({
|
|
330
|
+
config, remote: this.remote, local: this.local, store: this.store,
|
|
331
|
+
deliverer: this.deliverer, publicKeyPem: keys.rsaPublicPem, log: this.log,
|
|
332
|
+
resolveMention: (h) => resolveHandle(this, h),
|
|
333
|
+
// Whether the fediverse tree is on the pod at all, so the ACL check does
|
|
334
|
+
// not probe for something the default layout keeps on local disk.
|
|
335
|
+
privateOnPod: !cred.privateRoot,
|
|
336
|
+
});
|
|
337
|
+
// Intake is constructed even for viewers — its signed fetchAP powers
|
|
338
|
+
// search/deref; start() (draining) is active-only.
|
|
339
|
+
this.intake = new Intake({
|
|
340
|
+
config, urls: this.urls, remote: this.remote, local: this.local, store: this.store,
|
|
341
|
+
deliverer: this.deliverer, publisher: this.publisher, log: this.log, lease: this.lease,
|
|
342
|
+
archive: this.privateStorage(cred, 'archive'),
|
|
343
|
+
push: !this.embedded, pollSeconds: this.pollSeconds || null,
|
|
344
|
+
});
|
|
345
|
+
// The CSV-import worker: paced, resumable, armed only while active.
|
|
346
|
+
this.importer?.stop();
|
|
347
|
+
this.importer = new ImportWorker({ agent: this, log: this.log });
|
|
348
|
+
// The Bluesky connection, when one exists. Stamped to this actor; a
|
|
349
|
+
// credential connected for another identity is treated as absent.
|
|
350
|
+
this.atproto = new Atproto({ localDir: this.home, actorId: this.urls.actor, log: this.log });
|
|
351
|
+
this.publisher.atproto = this.atproto;
|
|
352
|
+
this.bskyfeed?.stop();
|
|
353
|
+
this.bskyfeed = null;
|
|
354
|
+
this.bskygroup = null;
|
|
355
|
+
this.intake.bskyGroup = null;
|
|
356
|
+
if (this.viewer) {
|
|
357
|
+
this.startViewer();
|
|
358
|
+
this.log(`another agent is active for this pod — viewing as @${config.handle} (read-only)`);
|
|
359
|
+
return true;
|
|
360
|
+
}
|
|
361
|
+
await this.startActive({ repair });
|
|
362
|
+
return true;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
// Claim the lease from whoever holds it and start acting. For the case where
|
|
366
|
+
// the holder is gone but its lease has not expired — a crash, or a one-shot
|
|
367
|
+
// command that exited without releasing — the only alternative is waiting out
|
|
368
|
+
// the TTL, which is five minutes.
|
|
369
|
+
async takeOver() {
|
|
370
|
+
if (!this.viewer) return false;
|
|
371
|
+
if (!await this.lease.takeover()) return false;
|
|
372
|
+
this.log('took the lease over');
|
|
373
|
+
await this.startActive({ promoted: true });
|
|
374
|
+
return true;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
// Mint a replacement signing key and republish the actor that advertises it.
|
|
378
|
+
// These are one operation: a rotation without the republish leaves remote
|
|
379
|
+
// servers verifying against a key we no longer hold, which fails every
|
|
380
|
+
// delivery silently. The live deliverer and publisher are updated too, so the
|
|
381
|
+
// running agent signs with the new key from here on.
|
|
382
|
+
async rotateKey() {
|
|
383
|
+
const cred = this.readCredential();
|
|
384
|
+
const before = this.publisher.publicKeyPem;
|
|
385
|
+
const keys = await resolveKeys(this.store, {
|
|
386
|
+
localDir: cred.keysMode === 'pod' ? null : this.home,
|
|
387
|
+
rotate: true,
|
|
388
|
+
actorId: this.urls.actor,
|
|
389
|
+
log: this.log,
|
|
390
|
+
});
|
|
391
|
+
this.publisher.publicKeyPem = keys.rsaPublicPem;
|
|
392
|
+
this.deliverer.rsaPrivate = keys.rsaPrivate;
|
|
393
|
+
await this.publisher.publishProfile();
|
|
394
|
+
return { changed: before !== keys.rsaPublicPem, publicKeyPem: keys.rsaPublicPem };
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
// Park: as quiet as a pod can be while keeping its name, and revivable.
|
|
398
|
+
// The following list is snapshotted FIRST — unfollowing is what stops the
|
|
399
|
+
// traffic at source, but it also destroys the only record of who was being
|
|
400
|
+
// followed, and "until I want to revive it" needs that record.
|
|
401
|
+
async park({ unfollow = unfollowActor } = {}) {
|
|
402
|
+
const following = await this._snapshotFollowing();
|
|
403
|
+
const r = await this.quiesce({ unfollow });
|
|
404
|
+
this.log(`parked: ${r.unfollowed} unfollow(s) recorded for revival, inbox closed`);
|
|
405
|
+
return { ...r, snapshot: following.length };
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
// Undo a park: re-open the inbox, then re-follow everyone from the snapshot.
|
|
409
|
+
// Each Follow needs the far end to Accept, so this is a request, not a
|
|
410
|
+
// restoration — some will not come back, which is the nature of the thing.
|
|
411
|
+
async revive({ follow = followActor } = {}) {
|
|
412
|
+
const parked = this.store.read('parked.json', null);
|
|
413
|
+
await this.publisher.openInbox();
|
|
414
|
+
let refollowed = 0;
|
|
415
|
+
for (const f of parked?.following || []) {
|
|
416
|
+
try { await follow(this, f.actor); refollowed++; }
|
|
417
|
+
catch (e) { this.log(`re-follow ${f.actor} failed: ${e.message}`); }
|
|
418
|
+
}
|
|
419
|
+
if (parked) this.store.remove('parked.json').catch(() => {});
|
|
420
|
+
await this.store.flush();
|
|
421
|
+
this.log(`revived: inbox open, ${refollowed}/${parked?.following?.length || 0} follow(s) re-sent`);
|
|
422
|
+
return { refollowed, of: parked?.following?.length || 0, parkedAt: parked?.parkedAt || null };
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
// The follow graph, written down before it is torn down. Both going quiet
|
|
426
|
+
// and moving away unfollow everyone, and the record page offers "active"
|
|
427
|
+
// afterwards for either — so both have to leave something to come back from,
|
|
428
|
+
// or setting it back re-follows nobody and says so only in a count.
|
|
429
|
+
async _snapshotFollowing() {
|
|
430
|
+
const following = this.store.getContacts().following;
|
|
431
|
+
this.store.write('parked.json', {
|
|
432
|
+
parkedAt: new Date().toISOString(),
|
|
433
|
+
following: following.map(f => ({ actor: f.actor, handle: f.handle || null })),
|
|
434
|
+
});
|
|
435
|
+
await this.store.flush();
|
|
436
|
+
return following;
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
// Keep the handle, take no more mail. Unfollowing is what actually stops the
|
|
440
|
+
// volume — every account you follow pushes its posts into your inbox — and
|
|
441
|
+
// closing the inbox handles the rest, which no follow graph can gate:
|
|
442
|
+
// stranger mentions, new follow requests, outright spam.
|
|
443
|
+
// `unfollow` is injectable so this is testable without a live pod.
|
|
444
|
+
async quiesce({ unfollow = unfollowActor } = {}) {
|
|
445
|
+
const following = this.store.getContacts().following.map(f => f.actor);
|
|
446
|
+
let unfollowed = 0;
|
|
447
|
+
for (const actor of following) {
|
|
448
|
+
try { await unfollow(this, actor); unfollowed++; }
|
|
449
|
+
catch (e) { this.log(`unfollow ${actor} failed: ${e.message}`); }
|
|
450
|
+
}
|
|
451
|
+
const quiescedAt = await this.publisher.closeInbox();
|
|
452
|
+
this.log(`quiesced: unfollowed ${unfollowed}/${following.length}, inbox closed`);
|
|
453
|
+
return { unfollowed, following: following.length, quiescedAt };
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
// Same, plus the fediverse-native redirect: followers are migrated to the
|
|
457
|
+
// target by their own servers, and the old handle keeps resolving.
|
|
458
|
+
async moveTo(target, { unfollow = unfollowActor } = {}) {
|
|
459
|
+
const moved = await this.publisher.publishMove(target);
|
|
460
|
+
const snapshot = await this._snapshotFollowing();
|
|
461
|
+
const quiesced = await this.quiesce({ unfollow });
|
|
462
|
+
return { ...moved, ...quiesced, snapshot: snapshot.length };
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
// True when it had to republish. Authenticated read: the question here is
|
|
466
|
+
// whether the document EXISTS, not whether the world can see it —
|
|
467
|
+
// verifyPublicSurface answers that one.
|
|
468
|
+
async ensureActorPublished() {
|
|
469
|
+
const doc = await this.remote.getJson(this.urls.actor);
|
|
470
|
+
if (doc?.id) return false;
|
|
471
|
+
this.log('actor document missing from the pod — republishing');
|
|
472
|
+
await this.publisher.publishProfile({ force: true }); // the digest cannot know this
|
|
473
|
+
return true;
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
// Read-only mode: refresh the state cache periodically, and take over the
|
|
477
|
+
// moment the active agent's lease frees.
|
|
478
|
+
startViewer() {
|
|
479
|
+
this.viewer = true;
|
|
480
|
+
// Five minutes, not one: with revalidation a quiet refresh is a single 304,
|
|
481
|
+
// but a viewer still has no reason to ask twelve times an hour.
|
|
482
|
+
this.refreshTimer = setInterval(async () => {
|
|
483
|
+
try {
|
|
484
|
+
if (this.viewer && await this.lease.acquire()) {
|
|
485
|
+
this.log('lease freed — promoting to ACTIVE');
|
|
486
|
+
await this.startActive({ promoted: true });
|
|
487
|
+
return;
|
|
488
|
+
}
|
|
489
|
+
if (this.viewer) await this.store.load();
|
|
490
|
+
} catch (e) { this.log(`viewer refresh: ${e.message}`); }
|
|
491
|
+
}, Math.round(5 * 60_000 * (0.85 + Math.random() * 0.3)));
|
|
492
|
+
this.refreshTimer.unref?.();
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
// The acting half: lease renewal, inbox drain, tag feed, delivery queue.
|
|
496
|
+
// Called at connect when the lease is ours, or on viewer promotion.
|
|
497
|
+
async startActive({ repair = true, promoted = false } = {}) {
|
|
498
|
+
this.viewer = false;
|
|
499
|
+
clearInterval(this.refreshTimer);
|
|
500
|
+
if (promoted) await this.refreshBeforeActing();
|
|
501
|
+
this.lease.onLost = () => this.demote();
|
|
502
|
+
this.lease.startRenewal();
|
|
503
|
+
this.deliverer.startQueue();
|
|
504
|
+
// Parked: no draining (the inbox is closed anyway) and no tag feed, so
|
|
505
|
+
// starting the agent by accident does not undo the quiet.
|
|
506
|
+
if (this.store.getConfig()?.quiescedAt) {
|
|
507
|
+
this.log('parked — not draining or polling; run `fedipod revive` to resume');
|
|
508
|
+
return; // renewal is already running, above
|
|
509
|
+
}
|
|
510
|
+
await this.intake.start();
|
|
511
|
+
// Reused, not replaced: demote() stops this instance but does not clear it,
|
|
512
|
+
// so constructing a new one over the top orphaned the old chain beyond the
|
|
513
|
+
// reach of any later stop().
|
|
514
|
+
this.tagfeed ||= new TagFeed({ store: this.store, intake: this.intake, log: this.log });
|
|
515
|
+
this.tagfeed.start();
|
|
516
|
+
this.startBsky();
|
|
517
|
+
// Scheduled posts: a 30s sweep publishes what has come due. The entry is
|
|
518
|
+
// removed before publishing, so a slow publish cannot double-post; a
|
|
519
|
+
// failed one is dropped with its reason in the log.
|
|
520
|
+
clearInterval(this.schedTimer);
|
|
521
|
+
this.schedTimer = setInterval(() => {
|
|
522
|
+
const due = this.store.getScheduled().filter(e => Date.parse(e.scheduledAt) <= Date.now());
|
|
523
|
+
for (const e of due) {
|
|
524
|
+
this.store.setScheduled(this.store.getScheduled().filter(x => x.id !== e.id));
|
|
525
|
+
this.publisher.publishNote(e.params.status, {
|
|
526
|
+
inReplyTo: e.params.inReplyTo, attachments: e.params.attachments,
|
|
527
|
+
visibility: e.params.visibility, spoilerText: e.params.spoilerText,
|
|
528
|
+
}).then(() => this.log(`scheduled post published (${e.id})`))
|
|
529
|
+
.catch(err => this.log(`scheduled post ${e.id} failed: ${err.message} — dropped`));
|
|
530
|
+
}
|
|
531
|
+
}, 30_000);
|
|
532
|
+
this.schedTimer.unref();
|
|
533
|
+
// A CSV import interrupted by a restart or a handoff picks back up here.
|
|
534
|
+
this.importer?.resume();
|
|
535
|
+
this.log(`federating as @${this.store.getConfig()?.handle}@${new URL(this.urls.base).host}`);
|
|
536
|
+
if (this.renamed) {
|
|
537
|
+
// The display name lives in the actor document, so a rename only
|
|
538
|
+
// reaches other servers once that is republished.
|
|
539
|
+
this.renamed = false;
|
|
540
|
+
this.publisher.publishProfile()
|
|
541
|
+
.then(() => this.log('actor document republished with the new display name'))
|
|
542
|
+
.catch(e => this.log(`republish after rename failed: ${e.message}`));
|
|
543
|
+
}
|
|
544
|
+
// bootstrap writes the owner-only ACLs once, at setup, and nothing else
|
|
545
|
+
// ever returns to them — so check on every start that the private trees
|
|
546
|
+
// really are private, and repair them if not. Off the critical path.
|
|
547
|
+
this.publisher.ensurePrivateAcls()
|
|
548
|
+
.catch(e => this.log(`private-ACL check failed: ${e.message}`));
|
|
549
|
+
// A publish that died half-way leaves an actor nobody can fetch while
|
|
550
|
+
// everything here looks healthy — one GET to find out, and republishing
|
|
551
|
+
// is idempotent.
|
|
552
|
+
// Skipped during setup, which publishes the profile itself a moment later:
|
|
553
|
+
// running both meant every first run wrote the whole wire face twice.
|
|
554
|
+
if (repair) {
|
|
555
|
+
this.ensureActorPublished()
|
|
556
|
+
.catch(e => this.log(`actor check failed: ${e.message}`));
|
|
557
|
+
}
|
|
558
|
+
this.backfillStatuses().catch(e => this.log(`statuses backfill failed: ${e.message}`));
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
// Re-read state before acting on what we hold. A viewer's cache is kept
|
|
562
|
+
// current by revalidation against the CONTAINER, whose ETag vouches for its
|
|
563
|
+
// children existing rather than for their contents — so a peer rewriting
|
|
564
|
+
// contacts.json or statuses.json in place moves nothing this agent would
|
|
565
|
+
// notice. Only on promotion, never on a timer, and only documents that really
|
|
566
|
+
// changed come back with a body.
|
|
567
|
+
async refreshBeforeActing() {
|
|
568
|
+
if (!this.store.storage) return;
|
|
569
|
+
await this.store.load({ force: true })
|
|
570
|
+
.catch(e => this.log(`state refresh on promotion: ${e.message}`));
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
// Another device claimed the lease (its user acted there) — stand down to
|
|
574
|
+
// viewer so exactly one agent keeps draining.
|
|
575
|
+
// The Bluesky mirror poll, only ever running when an account is connected.
|
|
576
|
+
// Reused, not replaced, for the same orphaned-timer reason as tagfeed.
|
|
577
|
+
startBsky() {
|
|
578
|
+
if (this.viewer || !this.atproto?.connected()) return;
|
|
579
|
+
if (this.store.getConfig()?.quiescedAt) return;
|
|
580
|
+
// A group's account is the group's presence on Bluesky: follows are joins,
|
|
581
|
+
// mentions are submissions, and both ride the notification hook.
|
|
582
|
+
if (this.store.getConfig()?.kind === 'group') {
|
|
583
|
+
this.bskygroup ||= new BskyGroup({
|
|
584
|
+
store: this.store, atproto: this.atproto, intake: this.intake,
|
|
585
|
+
publisher: this.publisher, log: this.log,
|
|
586
|
+
});
|
|
587
|
+
this.intake.bskyGroup = this.bskygroup;
|
|
588
|
+
}
|
|
589
|
+
this.bskyfeed ||= new BskyFeed({
|
|
590
|
+
store: this.store, atproto: this.atproto, log: this.log,
|
|
591
|
+
onNotification: async (n) => {
|
|
592
|
+
if (!this.bskygroup) return;
|
|
593
|
+
if (n.reason === 'follow') await this.bskygroup.onFollow(n.author);
|
|
594
|
+
else await this.bskygroup.onMention(n);
|
|
595
|
+
},
|
|
596
|
+
});
|
|
597
|
+
this.bskyfeed.start();
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
stopBsky() { this.bskyfeed?.stop(); }
|
|
601
|
+
|
|
602
|
+
demote() {
|
|
603
|
+
if (this.viewer) return;
|
|
604
|
+
this.log('another device took over — demoting to viewer');
|
|
605
|
+
this.intake?.stop();
|
|
606
|
+
this.tagfeed?.stop();
|
|
607
|
+
this.bskyfeed?.stop();
|
|
608
|
+
this.deliverer?.stop();
|
|
609
|
+
this.importer?.stop();
|
|
610
|
+
clearInterval(this.schedTimer);
|
|
611
|
+
// The lease too: standing down means standing down. Left renewing, a viewer
|
|
612
|
+
// keeps writing to the pod on the active agent's behalf and can win the
|
|
613
|
+
// lease back on a conditional PUT it had no business making.
|
|
614
|
+
this.lease?.stopRenewal();
|
|
615
|
+
this.startViewer();
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
// A user acting on this viewer outranks the idle active agent elsewhere:
|
|
619
|
+
// claim the lease now (writes are safe immediately — publishing never
|
|
620
|
+
// touches the inbox), but hold the destructive inbox drain until the old
|
|
621
|
+
// active has seen the loss at its next renewal and demoted.
|
|
622
|
+
async requestTakeover() {
|
|
623
|
+
if (!this.viewer) return true;
|
|
624
|
+
if (!(await this.lease.takeover())) return false;
|
|
625
|
+
this.log('taking over from the other device (user action here)');
|
|
626
|
+
this.viewer = false;
|
|
627
|
+
clearInterval(this.refreshTimer);
|
|
628
|
+
this.lease.onLost = () => this.demote();
|
|
629
|
+
this.lease.startRenewal();
|
|
630
|
+
this.deliverer.startQueue();
|
|
631
|
+
setTimeout(async () => {
|
|
632
|
+
if (this.viewer) return; // lost it again in the meantime
|
|
633
|
+
try {
|
|
634
|
+
await this.refreshBeforeActing();
|
|
635
|
+
await this.intake.start();
|
|
636
|
+
this.tagfeed ||= new TagFeed({ store: this.store, intake: this.intake, log: this.log });
|
|
637
|
+
this.tagfeed.start();
|
|
638
|
+
this.startBsky();
|
|
639
|
+
// A stranded CSV import resumes here too — startActive is not on the
|
|
640
|
+
// takeover path, so without this the rows sat pending until a restart.
|
|
641
|
+
this.importer?.resume();
|
|
642
|
+
this.log('takeover complete — draining resumed on this device');
|
|
643
|
+
} catch (e) { this.log(`takeover drain start: ${e.message}`); }
|
|
644
|
+
}, 35_000).unref?.(); // > one renewal interval: old agent has demoted
|
|
645
|
+
return true;
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
// The statuses index is an operational mirror of the pod's RDF — rebuild it
|
|
649
|
+
// from /fediverse/ when absent (fresh state, or state loss).
|
|
650
|
+
async backfillStatuses() {
|
|
651
|
+
if (!this.store.has('notifications.json')) {
|
|
652
|
+
for (const f of this.store.getContacts().followers) {
|
|
653
|
+
this.store.addNotification({ type: 'follow', actor: f.actor });
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
if (this.store.has('statuses.json')) return;
|
|
657
|
+
const entries = [];
|
|
658
|
+
for (const [container, kind] of [['timeline', 'timeline'], ['posts', 'post']]) {
|
|
659
|
+
for (const url of await this.local.listNotes(container)) {
|
|
660
|
+
try {
|
|
661
|
+
const n = await this.local.readNote(url);
|
|
662
|
+
if (n.noteId) entries.push({ ...n, kind, slug: url.split('/').pop() });
|
|
663
|
+
} catch (e) { this.log(`backfill: skipped ${url}: ${e.message}`); }
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
entries.sort((a, b) => String(b.published || '').localeCompare(String(a.published || '')));
|
|
667
|
+
this.store.write('statuses.json', entries.slice(0, 1000));
|
|
668
|
+
this.log(`backfilled ${entries.length} statuses from pod RDF`);
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
// Two megabytes is a few weeks of an ordinary agent's chatter, and small
|
|
673
|
+
// enough that reading the whole thing is still reasonable.
|
|
674
|
+
const LOG_MAX_BYTES = 2 * 1024 * 1024;
|
|
675
|
+
|
|
676
|
+
export async function startAgent({
|
|
677
|
+
home = process.env.AP_HOME || apRoot(),
|
|
678
|
+
port = Number(process.env.AP_PORT) || 8030,
|
|
679
|
+
gateToken = process.env.AP_GATE_TOKEN || '',
|
|
680
|
+
name = null,
|
|
681
|
+
takeover = false,
|
|
682
|
+
handle = null,
|
|
683
|
+
} = {}) {
|
|
684
|
+
fs.mkdirSync(home, { recursive: true, mode: 0o700 });
|
|
685
|
+
// connect() sets this from pod state a moment later, but the browser may
|
|
686
|
+
// already be opening — seed it from what setup recorded so the named origin
|
|
687
|
+
// works from the first request.
|
|
688
|
+
// agent.json is how everything else finds this agent afterwards — `profiles`,
|
|
689
|
+
// `stop`, the Actors list. The CLI used to be the only thing that wrote it, so
|
|
690
|
+
// an agent spawned any other way (the admin page starts them now) ran
|
|
691
|
+
// invisibly on a port nobody could look up. Merge, so `handle` survives.
|
|
692
|
+
const agentJson = path.join(home, 'agent.json');
|
|
693
|
+
let recorded = {};
|
|
694
|
+
try { recorded = JSON.parse(fs.readFileSync(agentJson, 'utf8')) || {}; } catch { /* first run */ }
|
|
695
|
+
if (!handle) handle = recorded.handle || null;
|
|
696
|
+
if (recorded.port !== port) {
|
|
697
|
+
try {
|
|
698
|
+
fs.mkdirSync(home, { recursive: true, mode: 0o700 });
|
|
699
|
+
writeJsonAtomic(agentJson, { ...recorded, port }, { mode: 0o644 });
|
|
700
|
+
} catch { /* the agent still runs; it is just harder to find */ }
|
|
701
|
+
}
|
|
702
|
+
const logFile = path.join(home, 'agent.log');
|
|
703
|
+
const agent = new Agent({ home, log: () => {} });
|
|
704
|
+
// The port on every line. Agents sharing a home share agent.log, and without
|
|
705
|
+
// it there is no way to tell which one wrote what — a viewer's startup reads
|
|
706
|
+
// as the active one's work.
|
|
707
|
+
const log = (...a) => {
|
|
708
|
+
const line = `${new Date().toISOString()} :${port} ${a.join(' ')}`;
|
|
709
|
+
console.log(`[ap:${port}]`, ...a);
|
|
710
|
+
agent.logRing.push(line);
|
|
711
|
+
if (agent.logRing.length > 500) agent.logRing.shift();
|
|
712
|
+
try {
|
|
713
|
+
// Rotated, because nothing else was ever going to. This file is appended
|
|
714
|
+
// to on every drain, every delivery and every lease event, for the life
|
|
715
|
+
// of an agent that is meant to run for months — on a phone under Termux
|
|
716
|
+
// especially, an unbounded log is the thing that fills the disk. One
|
|
717
|
+
// previous generation is kept; a crash investigation rarely wants two.
|
|
718
|
+
if (fs.statSync(logFile).size > LOG_MAX_BYTES) fs.renameSync(logFile, logFile + '.1');
|
|
719
|
+
} catch { /* no log yet, or a rename we cannot do — appending still works */ }
|
|
720
|
+
try { fs.appendFileSync(logFile, line + '\n'); } catch { /* logging must never throw */ }
|
|
721
|
+
};
|
|
722
|
+
agent.log = log;
|
|
723
|
+
agent.store.log = log;
|
|
724
|
+
// Before the socket, not after: an agent that must not be reachable at that
|
|
725
|
+
// address must never have answered there. This used to be a warning said at
|
|
726
|
+
// connect time, which is both too late (the server has been listening for
|
|
727
|
+
// seconds) and too narrow (it only ever described the OAuth login).
|
|
728
|
+
const exposure = exposureProblem({ allowedHosts: process.env.AP_ALLOWED_HOSTS, gateToken });
|
|
729
|
+
if (exposure) {
|
|
730
|
+
log(`refusing to start:\n${exposure}`);
|
|
731
|
+
process.exit(2);
|
|
732
|
+
}
|
|
733
|
+
// https and nothing else, on the one port this agent was given: a
|
|
734
|
+
// per-machine certificate (never packaged — see lib/certs.mjs), covering
|
|
735
|
+
// every identity on this root. A certificate problem stops the start rather
|
|
736
|
+
// than quietly serving the UI and the API in the clear.
|
|
737
|
+
let tls = null;
|
|
738
|
+
try {
|
|
739
|
+
tls = ensureTrustedTls(path.join(rootOf(agent.home), 'certs'),
|
|
740
|
+
{ log, names: hostLabel(handle) ? [`${hostLabel(handle)}.localhost`] : [] });
|
|
741
|
+
} catch (e) {
|
|
742
|
+
log(`refusing to start: certificate setup failed (${e.message})`);
|
|
743
|
+
log('the agent serves https only — fix the certificate, or run `fedipod https --trust`');
|
|
744
|
+
process.exit(2);
|
|
745
|
+
}
|
|
746
|
+
startAdmin({ port, gateToken, agent, log, handle, tls });
|
|
747
|
+
|
|
748
|
+
// Is a newer FediPod published? Once at boot and daily after; the answer
|
|
749
|
+
// rides /status and the record page offers the update.
|
|
750
|
+
const updateTick = async () => {
|
|
751
|
+
const { checkLatest } = await import('./lib/update.mjs');
|
|
752
|
+
const u = await checkLatest();
|
|
753
|
+
if (u) {
|
|
754
|
+
agent.updateInfo = u;
|
|
755
|
+
if (u.available) log(`FediPod ${u.latest} is available (running ${u.current}) — update from the record page or \`fedipod update\``);
|
|
756
|
+
}
|
|
757
|
+
};
|
|
758
|
+
void updateTick();
|
|
759
|
+
setInterval(updateTick, 24 * 3600e3).unref?.();
|
|
760
|
+
|
|
761
|
+
// The pod (or its issuer) can be briefly unreachable — a 504 from the
|
|
762
|
+
// token endpoint, or no network yet at boot under install-service. Keep
|
|
763
|
+
// retrying with backoff instead of sitting unconfigured until someone
|
|
764
|
+
// notices; the UI stays up throughout.
|
|
765
|
+
const connectWithRetry = async () => {
|
|
766
|
+
for (let attempt = 1; ; attempt++) {
|
|
767
|
+
try {
|
|
768
|
+
const up = await agent.connect({ name });
|
|
769
|
+
if (up) {
|
|
770
|
+
// A lease whose holder is gone but not expired would otherwise leave
|
|
771
|
+
// us read-only for the whole TTL.
|
|
772
|
+
if (takeover && agent.viewer) await agent.takeOver();
|
|
773
|
+
return;
|
|
774
|
+
}
|
|
775
|
+
log('unconfigured — run `bin/fedipod.mjs setup` to begin');
|
|
776
|
+
return; // no credential: retrying won't help
|
|
777
|
+
} catch (e) {
|
|
778
|
+
// Caps at an hour, not ten minutes: a pod that has refused for an hour
|
|
779
|
+
// is not going to be helped by asking six times more per hour, and an
|
|
780
|
+
// agent left running for days should not be a fixture in its logs.
|
|
781
|
+
// Jittered so restarts of several agents do not line up.
|
|
782
|
+
const base = Math.min(30 * 2 ** (attempt - 1), 3600);
|
|
783
|
+
const wait = Math.round(base * (0.8 + Math.random() * 0.4));
|
|
784
|
+
log(`connect failed (attempt ${attempt}): ${e.message} — retrying in ${wait}s`);
|
|
785
|
+
await new Promise(r => setTimeout(r, wait * 1000));
|
|
786
|
+
}
|
|
787
|
+
}
|
|
788
|
+
};
|
|
789
|
+
connectWithRetry();
|
|
790
|
+
const shutdown = () => {
|
|
791
|
+
setTimeout(() => process.exit(0), 1500).unref(); // never hang a stop on a slow pod
|
|
792
|
+
try { fs.rmSync(path.join(home, 'agent.pid'), { force: true }); } catch {}
|
|
793
|
+
Promise.allSettled([
|
|
794
|
+
agent.store.flush(),
|
|
795
|
+
agent.viewer ? Promise.resolve() : agent.lease?.release(),
|
|
796
|
+
]).finally(() => process.exit(0));
|
|
797
|
+
};
|
|
798
|
+
process.on('SIGTERM', shutdown);
|
|
799
|
+
process.on('SIGINT', shutdown);
|
|
800
|
+
return agent;
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
|
804
|
+
startAgent();
|
|
805
|
+
}
|