fedipod-server 0.10.0 → 0.12.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 (416) hide show
  1. package/README.md +15 -6
  2. package/dist/claims.js +1 -1
  3. package/dist/handler.d.ts +7 -1
  4. package/dist/handler.js +58 -12
  5. package/dist/handler.jsonld +5 -1
  6. package/dist/store-pod.js +18 -4
  7. package/lib/{c2s.mjs → client/c2s.mjs} +8 -3
  8. package/lib/{localapi.mjs → client/localapi.mjs} +2 -2
  9. package/lib/client/masto/accounts.mjs +264 -0
  10. package/lib/client/masto/body.mjs +69 -0
  11. package/lib/client/masto/index.mjs +183 -0
  12. package/lib/client/masto/instance.mjs +104 -0
  13. package/lib/client/masto/media.mjs +133 -0
  14. package/lib/client/masto/oauth.mjs +599 -0
  15. package/lib/client/masto/render.mjs +459 -0
  16. package/lib/client/masto/statuses.mjs +331 -0
  17. package/lib/client/masto/timelines.mjs +316 -0
  18. package/lib/{streaming.mjs → client/streaming.mjs} +1 -1
  19. package/lib/{acctfeed.mjs → connections/acctfeed.mjs} +1 -1
  20. package/lib/{atproto.mjs → connections/atproto.mjs} +15 -16
  21. package/lib/{bskygroup.mjs → connections/bskygroup.mjs} +1 -1
  22. package/lib/{fediacct.mjs → connections/fediacct.mjs} +31 -35
  23. package/lib/{import.mjs → connections/import.mjs} +2 -2
  24. package/lib/{tagfeed.mjs → connections/tagfeed.mjs} +21 -4
  25. package/lib/connections/vault.mjs +114 -0
  26. package/lib/core/as2.mjs +124 -0
  27. package/lib/core/contexts/activitystreams.json +379 -0
  28. package/lib/core/contexts/did-v1.json +57 -0
  29. package/lib/core/contexts/fep-5711.json +36 -0
  30. package/lib/core/contexts/gotosocial.json +86 -0
  31. package/lib/core/contexts/identity-v1.json +152 -0
  32. package/lib/core/contexts/index.mjs +45 -0
  33. package/lib/core/contexts/join-lemmy.json +33 -0
  34. package/lib/core/contexts/joinmastodon.json +28 -0
  35. package/lib/core/contexts/map.json +16 -0
  36. package/lib/core/contexts/miscellany.json +19 -0
  37. package/lib/core/contexts/schemaorg.json +8845 -0
  38. package/lib/core/contexts/security-data-integrity-v1.json +78 -0
  39. package/lib/core/contexts/security-data-integrity-v2.json +81 -0
  40. package/lib/core/contexts/security-multikey-v1.json +35 -0
  41. package/lib/core/contexts/security-v1.json +74 -0
  42. package/lib/core/contexts/webfinger.json +10 -0
  43. package/lib/{deliver.mjs → core/deliver.mjs} +8 -2
  44. package/lib/core/intake/activities.mjs +437 -0
  45. package/lib/core/intake/activity.mjs +240 -0
  46. package/lib/core/intake/channel.mjs +144 -0
  47. package/lib/core/intake/group.mjs +222 -0
  48. package/lib/core/intake/index.mjs +629 -0
  49. package/lib/core/intake/notes.mjs +288 -0
  50. package/lib/core/intake/verify.mjs +141 -0
  51. package/lib/{keys.mjs → core/keys.mjs} +1 -1
  52. package/lib/core/publisher/collections.mjs +229 -0
  53. package/lib/core/publisher/index.mjs +421 -0
  54. package/lib/core/publisher/notes.mjs +188 -0
  55. package/lib/core/publisher/questions.mjs +233 -0
  56. package/lib/core/publisher/restore.mjs +196 -0
  57. package/lib/core/shapes/activitystreams.ttl +129 -0
  58. package/lib/core/shapes/index.mjs +107 -0
  59. package/lib/core/shapes/shapes-text.mjs +13 -0
  60. package/lib/{social.mjs → core/social.mjs} +19 -10
  61. package/lib/{storage.mjs → core/storage.mjs} +2 -2
  62. package/lib/{store.mjs → core/store.mjs} +12 -1
  63. package/lib/{wire.mjs → core/wire.mjs} +48 -67
  64. package/lib/device/admin/index.mjs +13 -0
  65. package/lib/device/admin/origins.mjs +35 -0
  66. package/lib/device/admin/routes/connections.mjs +144 -0
  67. package/lib/device/admin/routes/gateway.mjs +199 -0
  68. package/lib/device/admin/routes/lifecycle.mjs +191 -0
  69. package/lib/device/admin/routes/owner.mjs +322 -0
  70. package/lib/device/admin/routes/setup.mjs +393 -0
  71. package/lib/device/admin/routes/social.mjs +188 -0
  72. package/lib/device/admin/server.mjs +95 -0
  73. package/lib/device/admin/static.mjs +244 -0
  74. package/lib/device/admin/surface.mjs +274 -0
  75. package/lib/device/cli/commands/account.mjs +586 -0
  76. package/lib/device/cli/commands/run.mjs +278 -0
  77. package/lib/device/cli/commands/service.mjs +221 -0
  78. package/lib/device/cli/commands/setup.mjs +410 -0
  79. package/lib/device/cli/commands/state.mjs +559 -0
  80. package/lib/device/cli/context.mjs +288 -0
  81. package/lib/{export-collections.mjs → device/export-collections.mjs} +1 -1
  82. package/lib/{migrate.mjs → device/migrate.mjs} +5 -19
  83. package/lib/device/remote.mjs +54 -0
  84. package/lib/{setup.mjs → device/setup.mjs} +3 -3
  85. package/lib/{update.mjs → device/update.mjs} +1 -1
  86. package/lib/{directory.mjs → gateway/directory.mjs} +1 -1
  87. package/lib/{front-core.mjs → gateway/front-core.mjs} +272 -49
  88. package/lib/{gateway-core.mjs → gateway/gateway-core.mjs} +3 -7
  89. package/lib/{httpsig.mjs → gateway/httpsig.mjs} +34 -3
  90. package/lib/pod/README.md +61 -0
  91. package/lib/pod/actor.mjs +96 -0
  92. package/lib/pod/collection.mjs +77 -0
  93. package/lib/pod/containers.mjs +136 -0
  94. package/lib/pod/discovery.mjs +46 -0
  95. package/lib/pod/featured.mjs +18 -0
  96. package/lib/pod/followers.mjs +24 -0
  97. package/lib/pod/following.mjs +10 -0
  98. package/lib/pod/http.mjs +74 -0
  99. package/lib/pod/inbox.mjs +144 -0
  100. package/lib/{links.mjs → pod/links.mjs} +1 -1
  101. package/lib/pod/media.mjs +27 -0
  102. package/lib/pod/notes.mjs +80 -0
  103. package/lib/pod/notifications.mjs +89 -0
  104. package/lib/pod/outbox.mjs +18 -0
  105. package/lib/pod/package.json +19 -0
  106. package/lib/pod/policy.mjs +58 -0
  107. package/lib/pod/private.mjs +19 -0
  108. package/lib/pod/root.mjs +63 -0
  109. package/lib/pod/state.mjs +39 -0
  110. package/lib/{remote.mjs → pod/transport.mjs} +217 -159
  111. package/lib/pod/urls.mjs +71 -0
  112. package/lib/{embed.mjs → server/embed.mjs} +149 -22
  113. package/lib/shared/links.mjs +9 -0
  114. package/lib/{ua.mjs → shared/ua.mjs} +1 -1
  115. package/package.json +1 -1
  116. package/run-agent.mjs +47 -64
  117. package/web/admin/actors.js +145 -0
  118. package/web/admin/bar.css +9 -13
  119. package/web/admin/bar.js +2 -2
  120. package/web/admin/client/client.js +1 -1
  121. package/web/admin/client/index.html +5 -6
  122. package/web/admin/common.js +23 -0
  123. package/web/admin/connections.js +112 -0
  124. package/web/admin/gateway.js +111 -0
  125. package/web/admin/group.js +258 -0
  126. package/web/admin/index.html +60 -66
  127. package/web/admin/record.js +378 -0
  128. package/web/admin/setup/index.html +3 -1
  129. package/web/admin/setup/setup.js +2 -13
  130. package/web/admin/tokens.css +56 -0
  131. package/web/admin/upkeep.js +170 -0
  132. package/web/app/README.md +77 -0
  133. package/web/app/admin-facade.mjs +549 -0
  134. package/web/app/agent.mjs +490 -0
  135. package/web/app/atproto-browser.mjs +86 -0
  136. package/web/app/boot.mjs +340 -0
  137. package/web/app/deliver-relay.mjs +72 -0
  138. package/web/app/dist/boot.js +34067 -0
  139. package/web/app/dist/boot.js.map +7 -0
  140. package/web/app/dist/sw.js +70014 -0
  141. package/web/app/dist/sw.js.map +7 -0
  142. package/web/app/fediacct-browser.mjs +146 -0
  143. package/web/app/idb-kv.mjs +35 -0
  144. package/web/app/index.html +203 -0
  145. package/web/app/index.html~ +152 -0
  146. package/web/app/keys-browser.mjs +46 -0
  147. package/web/app/keystore.mjs +99 -0
  148. package/web/app/oidc-session.mjs +189 -0
  149. package/web/app/pod-auth.mjs +248 -0
  150. package/web/app/pod-remote.mjs +84 -0
  151. package/web/app/shims/_globals.mjs +2 -0
  152. package/web/app/shims/fedify-sig.mjs +77 -0
  153. package/web/app/shims/node-crypto.mjs +113 -0
  154. package/web/app/shims/node-fs.mjs +17 -0
  155. package/web/app/shims/node-path.mjs +19 -0
  156. package/web/app/shims/node-url.mjs +7 -0
  157. package/web/app/shims/prelude.js +58 -0
  158. package/web/app/shims/safefetch.mjs +58 -0
  159. package/web/app/shims/shapes-text.mjs +8 -0
  160. package/web/app/shims/web-push.mjs +14 -0
  161. package/web/app/signup.mjs +248 -0
  162. package/web/app/site/_headers +9 -0
  163. package/web/app/site/_redirects +21 -0
  164. package/web/app/site/admin/actors.js +145 -0
  165. package/web/app/site/admin/bar.css +60 -0
  166. package/web/app/site/admin/bar.js +61 -0
  167. package/web/app/site/admin/client/client.js +66 -0
  168. package/web/app/site/admin/client/index.html +43 -0
  169. package/web/app/site/admin/common.js +23 -0
  170. package/web/app/site/admin/connections.js +112 -0
  171. package/web/app/site/admin/gateway.js +111 -0
  172. package/web/app/site/admin/group.js +258 -0
  173. package/web/app/site/admin/index.html +562 -0
  174. package/web/app/site/admin/record.js +378 -0
  175. package/web/app/site/admin/setup/index.html +192 -0
  176. package/web/app/site/admin/setup/setup.js +297 -0
  177. package/web/app/site/admin/tokens.css +56 -0
  178. package/web/app/site/admin/upkeep.js +170 -0
  179. package/web/app/site/admin/window.css +55 -0
  180. package/web/app/site/admin/window.js +136 -0
  181. package/web/app/site/app/404.html +40 -0
  182. package/web/app/site/app/_headers +2 -0
  183. package/web/app/site/app/apple-touch-icon.png +0 -0
  184. package/web/app/site/app/assets/ICONS-DIPJeU0C.js +2 -0
  185. package/web/app/site/app/assets/ICONS-DIPJeU0C.js.map +1 -0
  186. package/web/app/site/app/assets/ScheduledAtField-D-Abfo4J.js +183 -0
  187. package/web/app/site/app/assets/ScheduledAtField-D-Abfo4J.js.map +1 -0
  188. package/web/app/site/app/assets/Temml-CCjoacWt.woff2 +0 -0
  189. package/web/app/site/app/assets/__vite-browser-external-C7iut881.js +2 -0
  190. package/web/app/site/app/assets/__vite-browser-external-C7iut881.js.map +1 -0
  191. package/web/app/site/app/assets/boosts-carousel-BiOaNdMT.jpg +0 -0
  192. package/web/app/site/app/assets/catch-up-O5q5C75Z.png +0 -0
  193. package/web/app/site/app/assets/chunk-aKtaBQYM.js +1 -0
  194. package/web/app/site/app/assets/compose-CFEx7wb4.js +2 -0
  195. package/web/app/site/app/assets/compose-CFEx7wb4.js.map +1 -0
  196. package/web/app/site/app/assets/compose-ZJN5xSb4.js +35 -0
  197. package/web/app/site/app/assets/compose-ZJN5xSb4.js.map +1 -0
  198. package/web/app/site/app/assets/debug.module-YFQgwnIr.js +52 -0
  199. package/web/app/site/app/assets/debug.module-YFQgwnIr.js.map +1 -0
  200. package/web/app/site/app/assets/dom-p1YcJ5Rw.js +2 -0
  201. package/web/app/site/app/assets/dom-p1YcJ5Rw.js.map +1 -0
  202. package/web/app/site/app/assets/home-mobile-dark@2x-Dc-J8-SM.png +0 -0
  203. package/web/app/site/app/assets/home-mobile-light@2x-Bd3fod8m.png +0 -0
  204. package/web/app/site/app/assets/home-tablet-dark@2x-BgcNI8le.png +0 -0
  205. package/web/app/site/app/assets/home-tablet-light@2x-BW2RV9T6.png +0 -0
  206. package/web/app/site/app/assets/icons/add-circle-line-WD0mwORD.js +1 -0
  207. package/web/app/site/app/assets/icons/alert-line-CpFUMf9s.js +1 -0
  208. package/web/app/site/app/assets/icons/android-2-line-Bzxnrd3S.js +1 -0
  209. package/web/app/site/app/assets/icons/announcement-line-5nwaJFJm.js +1 -0
  210. package/web/app/site/app/assets/icons/arrow-down-circle-line-a7Id9-Iv.js +1 -0
  211. package/web/app/site/app/assets/icons/arrow-down-line-B8uzXzq6.js +1 -0
  212. package/web/app/site/app/assets/icons/arrow-left-line-CGrGT9C-.js +1 -0
  213. package/web/app/site/app/assets/icons/arrow-right-line-CE-HERfX.js +1 -0
  214. package/web/app/site/app/assets/icons/arrow-to-up-line-CvdQjmcy.js +1 -0
  215. package/web/app/site/app/assets/icons/arrow-up-circle-line-DEparSNF.js +1 -0
  216. package/web/app/site/app/assets/icons/arrow-up-line-C7yBeugc.js +1 -0
  217. package/web/app/site/app/assets/icons/arrows-right-line-BtbXmJGP.js +1 -0
  218. package/web/app/site/app/assets/icons/at-line-CF66Bznk.js +1 -0
  219. package/web/app/site/app/assets/icons/attachment-line-BY8It-l9.js +1 -0
  220. package/web/app/site/app/assets/icons/blockquote-line-BS6pU_hm.js +1 -0
  221. package/web/app/site/app/assets/icons/board-line-C0UWXyA6.js +1 -0
  222. package/web/app/site/app/assets/icons/bookmark-line-1CtX5JLF.js +1 -0
  223. package/web/app/site/app/assets/icons/building-5-line-Dd59MzbO.js +1 -0
  224. package/web/app/site/app/assets/icons/bus-2-line-6_dvA0GG.js +1 -0
  225. package/web/app/site/app/assets/icons/calendar-day-line-Crpl_fmu.js +1 -0
  226. package/web/app/site/app/assets/icons/calendar-month-line-vommts2C.js +1 -0
  227. package/web/app/site/app/assets/icons/calendar-time-add-line-BU_DTlQk.js +1 -0
  228. package/web/app/site/app/assets/icons/camera-line-Cv69MEei.js +1 -0
  229. package/web/app/site/app/assets/icons/celebrate-line-B8DvIoi0.js +1 -0
  230. package/web/app/site/app/assets/icons/chart-bar-line-FK-QOmtF.js +1 -0
  231. package/web/app/site/app/assets/icons/chart-line-line-BGcJAFWw.js +1 -0
  232. package/web/app/site/app/assets/icons/chat-3-line-YFK2-hwz.js +1 -0
  233. package/web/app/site/app/assets/icons/check-circle-line-DsAxFr5-.js +1 -0
  234. package/web/app/site/app/assets/icons/clipboard-line-BBp364gJ.js +1 -0
  235. package/web/app/site/app/assets/icons/close-circle-line-CICdiuGz.js +1 -0
  236. package/web/app/site/app/assets/icons/close-line-DYrFWcjv.js +1 -0
  237. package/web/app/site/app/assets/icons/cloud-line-tiQAbah8.js +1 -0
  238. package/web/app/site/app/assets/icons/code-line-fAl8iiV3.js +1 -0
  239. package/web/app/site/app/assets/icons/comment-2-line-CR3g7WeB.js +1 -0
  240. package/web/app/site/app/assets/icons/copy-2-line-CLW69yF5.js +1 -0
  241. package/web/app/site/app/assets/icons/delete-2-line-B8xmbr4n.js +1 -0
  242. package/web/app/site/app/assets/icons/document-3-line-DBGNhAg2.js +1 -0
  243. package/web/app/site/app/assets/icons/document-line-C7mb9sb7.js +1 -0
  244. package/web/app/site/app/assets/icons/down-line-BGqSSThd.js +1 -0
  245. package/web/app/site/app/assets/icons/edit-4-line-DcgGaEhx.js +1 -0
  246. package/web/app/site/app/assets/icons/emoji-2-line-D8YgnM-y.js +1 -0
  247. package/web/app/site/app/assets/icons/exit-line-Dc07BS-x.js +1 -0
  248. package/web/app/site/app/assets/icons/external-link-line-BvpSkmjO.js +1 -0
  249. package/web/app/site/app/assets/icons/eye-2-line-CiWXx-f_.js +1 -0
  250. package/web/app/site/app/assets/icons/eye-close-line-BgTaSJ4P.js +1 -0
  251. package/web/app/site/app/assets/icons/filter-2-line-B_mR2usy.js +1 -0
  252. package/web/app/site/app/assets/icons/filter-line-C_nm-3cU.js +1 -0
  253. package/web/app/site/app/assets/icons/flag-1-line-C2HB05I0.js +1 -0
  254. package/web/app/site/app/assets/icons/forbid-circle-line-D3LTT9yd.js +1 -0
  255. package/web/app/site/app/assets/icons/formula-line-DLrt2d6j.js +1 -0
  256. package/web/app/site/app/assets/icons/grid-line-CgUmEikf.js +1 -0
  257. package/web/app/site/app/assets/icons/group-line-C5fnX0wU.js +1 -0
  258. package/web/app/site/app/assets/icons/hand-finger-2-line-BGgxbuL9.js +1 -0
  259. package/web/app/site/app/assets/icons/hashtag-line-CyTEEXBb.js +1 -0
  260. package/web/app/site/app/assets/icons/heart-crack-line-BZddbO2C.js +1 -0
  261. package/web/app/site/app/assets/icons/heart-line-CJ7K47J4.js +1 -0
  262. package/web/app/site/app/assets/icons/history-2-line-kWWvFzqv.js +1 -0
  263. package/web/app/site/app/assets/icons/history-line-bGQiwbTH.js +1 -0
  264. package/web/app/site/app/assets/icons/home-3-line-fRU1zeLG.js +1 -0
  265. package/web/app/site/app/assets/icons/information-line-iNk6-sOY.js +1 -0
  266. package/web/app/site/app/assets/icons/keyboard-line-DsCyuQNz.js +1 -0
  267. package/web/app/site/app/assets/icons/layout-4-line-CZkOX52Z.js +1 -0
  268. package/web/app/site/app/assets/icons/layout-5-line-B_znt5wO.js +1 -0
  269. package/web/app/site/app/assets/icons/left-line-eUw0tya4.js +1 -0
  270. package/web/app/site/app/assets/icons/lightning-line-DaKoDdix.js +1 -0
  271. package/web/app/site/app/assets/icons/link-2-line-DCqLmMA7.js +1 -0
  272. package/web/app/site/app/assets/icons/list-check-line-BAxosBh9.js +1 -0
  273. package/web/app/site/app/assets/icons/lock-line-CPoaXeUW.js +1 -0
  274. package/web/app/site/app/assets/icons/mail-line-B0P8aa1L.js +1 -0
  275. package/web/app/site/app/assets/icons/moon-line-CEqNAToP.js +1 -0
  276. package/web/app/site/app/assets/icons/more-1-fill-Dw2e5xab.js +1 -0
  277. package/web/app/site/app/assets/icons/more-3-line-BIiVjYTz.js +1 -0
  278. package/web/app/site/app/assets/icons/notification-line-BZZq2Gtu.js +1 -0
  279. package/web/app/site/app/assets/icons/pencil-line-CKh8-A1v.js +1 -0
  280. package/web/app/site/app/assets/icons/photo-album-line-Bnfg2u40.js +1 -0
  281. package/web/app/site/app/assets/icons/pin-line-DpTolyhs.js +1 -0
  282. package/web/app/site/app/assets/icons/play-fill-B0-G_8lX.js +1 -0
  283. package/web/app/site/app/assets/icons/qrcode-2-line-B6SPCaHn.js +1 -0
  284. package/web/app/site/app/assets/icons/quill-pen-line-B6LUrnCP.js +1 -0
  285. package/web/app/site/app/assets/icons/quote-left-fill-hQZ1cj_6.js +1 -0
  286. package/web/app/site/app/assets/icons/radar-line-CKyroTth.js +1 -0
  287. package/web/app/site/app/assets/icons/react-line-CoIKhhtK.js +1 -0
  288. package/web/app/site/app/assets/icons/refresh-2-line-D0mTF97S.js +1 -0
  289. package/web/app/site/app/assets/icons/right-line-B3KWJaqc.js +1 -0
  290. package/web/app/site/app/assets/icons/rocket-line-4KZl537D.js +1 -0
  291. package/web/app/site/app/assets/icons/round-fill-C69NTrZ0.js +1 -0
  292. package/web/app/site/app/assets/icons/round-line-B9k_1uo-.js +1 -0
  293. package/web/app/site/app/assets/icons/route-line-B28ReHcE.js +1 -0
  294. package/web/app/site/app/assets/icons/rows-4-line-CrBniagM.js +1 -0
  295. package/web/app/site/app/assets/icons/scan-line-DSf74YdP.js +1 -0
  296. package/web/app/site/app/assets/icons/search-2-line-B6geIU1z.js +1 -0
  297. package/web/app/site/app/assets/icons/settings-3-line-azJwK47w.js +1 -0
  298. package/web/app/site/app/assets/icons/settings-6-line-C_5zc5YR.js +1 -0
  299. package/web/app/site/app/assets/icons/share-2-line-D5MxWjrm.js +1 -0
  300. package/web/app/site/app/assets/icons/share-forward-line-Cp61fZzZ.js +1 -0
  301. package/web/app/site/app/assets/icons/sparkles-2-line-DYYyXTaW.js +1 -0
  302. package/web/app/site/app/assets/icons/sparkles-line-C2hY1s6I.js +1 -0
  303. package/web/app/site/app/assets/icons/time-line-BF3eet1v.js +1 -0
  304. package/web/app/site/app/assets/icons/transfer-4-line-oisfvTBw.js +1 -0
  305. package/web/app/site/app/assets/icons/translate-line-BFWol2Ce.js +1 -0
  306. package/web/app/site/app/assets/icons/unlock-line-X_x5vwv3.js +1 -0
  307. package/web/app/site/app/assets/icons/upload-3-line-DgzwUJeW.js +1 -0
  308. package/web/app/site/app/assets/icons/user-4-line-BVSynZCp.js +1 -0
  309. package/web/app/site/app/assets/icons/user-add-2-line-BlGS5Q8q.js +1 -0
  310. package/web/app/site/app/assets/icons/user-add-line-BbXdHG4z.js +1 -0
  311. package/web/app/site/app/assets/icons/user-edit-line-BFAHOV0X.js +1 -0
  312. package/web/app/site/app/assets/icons/user-follow-line-BXux0wSd.js +1 -0
  313. package/web/app/site/app/assets/icons/user-star-line-DdYlpHLU.js +1 -0
  314. package/web/app/site/app/assets/icons/user-warning-line-Cj43j0_E.js +1 -0
  315. package/web/app/site/app/assets/icons/user-x-line-DIDgNlPH.js +1 -0
  316. package/web/app/site/app/assets/icons/volume-line-Bs390KQt.js +1 -0
  317. package/web/app/site/app/assets/icons/volume-mute-line-DzlzIqFZ.js +1 -0
  318. package/web/app/site/app/assets/icons/walk-line-yNXfB-md.js +1 -0
  319. package/web/app/site/app/assets/icons/world-2-line-CenkGIwj.js +1 -0
  320. package/web/app/site/app/assets/icons/zoom-in-line-CaENUphf.js +1 -0
  321. package/web/app/site/app/assets/icons/zoom-out-line-BDNk0EWo.js +1 -0
  322. package/web/app/site/app/assets/instances-BNPptnn-.json +333 -0
  323. package/web/app/site/app/assets/locales/ar-SA-CfheRbCu.js +1 -0
  324. package/web/app/site/app/assets/locales/ca-ES-DHRW86Tz.js +1 -0
  325. package/web/app/site/app/assets/locales/cs-CZ-CKoqEuA1.js +1 -0
  326. package/web/app/site/app/assets/locales/de-DE-ByRPMRFy.js +1 -0
  327. package/web/app/site/app/assets/locales/eo-UY-CPC7wLCS.js +1 -0
  328. package/web/app/site/app/assets/locales/es-ES-dJa0Fd9t.js +1 -0
  329. package/web/app/site/app/assets/locales/eu-ES-C3djlPR2.js +1 -0
  330. package/web/app/site/app/assets/locales/fa-IR-DTT490Ck.js +1 -0
  331. package/web/app/site/app/assets/locales/fi-FI-B23MCPuz.js +1 -0
  332. package/web/app/site/app/assets/locales/fr-FR-BcaQsO5C.js +1 -0
  333. package/web/app/site/app/assets/locales/gl-ES-BR-CVKBN.js +1 -0
  334. package/web/app/site/app/assets/locales/he-IL-CfheRbCu.js +1 -0
  335. package/web/app/site/app/assets/locales/hu-HU-CfheRbCu.js +1 -0
  336. package/web/app/site/app/assets/locales/it-IT-C1136UFV.js +1 -0
  337. package/web/app/site/app/assets/locales/ja-JP-CRZmRAhD.js +1 -0
  338. package/web/app/site/app/assets/locales/kab-Cz8xH_TT.js +1 -0
  339. package/web/app/site/app/assets/locales/ko-KR-CG9UiY4o.js +1 -0
  340. package/web/app/site/app/assets/locales/lt-LT-CJcI6sHZ.js +1 -0
  341. package/web/app/site/app/assets/locales/nb-NO-CfheRbCu.js +1 -0
  342. package/web/app/site/app/assets/locales/nl-NL-DxN4Yc1t.js +1 -0
  343. package/web/app/site/app/assets/locales/oc-FR-CfheRbCu.js +1 -0
  344. package/web/app/site/app/assets/locales/pl-PL-DkwGXf6P.js +1 -0
  345. package/web/app/site/app/assets/locales/pseudo-LOCALE-CQ4XxkQ0.js +1 -0
  346. package/web/app/site/app/assets/locales/pt-BR-nGL0HdFS.js +1 -0
  347. package/web/app/site/app/assets/locales/pt-PT-Cp17aj2z.js +1 -0
  348. package/web/app/site/app/assets/locales/ru-RU-0Y8cIoaK.js +1 -0
  349. package/web/app/site/app/assets/locales/th-TH-CfheRbCu.js +1 -0
  350. package/web/app/site/app/assets/locales/tok-CfheRbCu.js +1 -0
  351. package/web/app/site/app/assets/locales/tr-TR-CfheRbCu.js +1 -0
  352. package/web/app/site/app/assets/locales/uk-UA-C5E3dFBf.js +1 -0
  353. package/web/app/site/app/assets/locales/zh-CN-BHJi7_et.js +1 -0
  354. package/web/app/site/app/assets/locales/zh-TW-CfheRbCu.js +1 -0
  355. package/web/app/site/app/assets/main-BdqNbG-a.js +26 -0
  356. package/web/app/site/app/assets/main-BdqNbG-a.js.map +1 -0
  357. package/web/app/site/app/assets/mock-home-DGhR__He.js +2 -0
  358. package/web/app/site/app/assets/mock-home-DGhR__He.js.map +1 -0
  359. package/web/app/site/app/assets/multi-column-ROck0NVt.jpg +0 -0
  360. package/web/app/site/app/assets/multi-hashtag-timeline-DH5INVHi.jpg +0 -0
  361. package/web/app/site/app/assets/nested-comments-thread-hv59kZLc.jpg +0 -0
  362. package/web/app/site/app/assets/polyfill-force-H8sUkLGp.js +2 -0
  363. package/web/app/site/app/assets/polyfill-force-H8sUkLGp.js.map +1 -0
  364. package/web/app/site/app/assets/pwa-viewport-ogKbF51K.js +20 -0
  365. package/web/app/site/app/assets/pwa-viewport-ogKbF51K.js.map +1 -0
  366. package/web/app/site/app/assets/style-B1iLPTPR.css +2 -0
  367. package/web/app/site/app/assets/temml-DuyIQMei.js +97 -0
  368. package/web/app/site/app/assets/temml-DuyIQMei.js.map +1 -0
  369. package/web/app/site/app/assets/tinyld.light.node-DtbBhLYC.js +2 -0
  370. package/web/app/site/app/assets/tinyld.light.node-DtbBhLYC.js.map +1 -0
  371. package/web/app/site/app/assets/year-in-posts-B2lywqdx.png +0 -0
  372. package/web/app/site/app/assets/year-in-posts-DJv_star.js +3 -0
  373. package/web/app/site/app/assets/year-in-posts-DJv_star.js.map +1 -0
  374. package/web/app/site/app/compose/index.html +20 -0
  375. package/web/app/site/app/favicon.ico +0 -0
  376. package/web/app/site/app/index.html +73 -0
  377. package/web/app/site/app/logo-192.png +0 -0
  378. package/web/app/site/app/logo-512.png +0 -0
  379. package/web/app/site/app/logo-badge-72.png +0 -0
  380. package/web/app/site/app/logo-maskable-512.png +0 -0
  381. package/web/app/site/app/logo-monochrome-512.png +0 -0
  382. package/web/app/site/app/logo-monochrome-maskable-512.png +0 -0
  383. package/web/app/site/app/manifest.webmanifest +1 -0
  384. package/web/app/site/app/og-image-2.jpg +0 -0
  385. package/web/app/site/app/og-image.png +0 -0
  386. package/web/app/site/app/robots.txt +2 -0
  387. package/web/app/site/app/version.json +1 -0
  388. package/web/app/site/boot.js +34067 -0
  389. package/web/app/site/index.html +203 -0
  390. package/web/app/site/sw.js +70014 -0
  391. package/web/app/sw-src.mjs +220 -0
  392. package/web/front/#new-account.html# +43 -0
  393. package/web/front/admin.html +1 -81
  394. package/web/front/admin.js +85 -0
  395. package/web/front/new-account.html +1 -9
  396. package/web/front/new-account.js +13 -0
  397. package/web/front/run.html +1 -92
  398. package/web/front/run.js +107 -0
  399. package/lib/admin.mjs +0 -1913
  400. package/lib/intake.mjs +0 -1764
  401. package/lib/mastoapi.mjs +0 -1947
  402. package/lib/podrdf.mjs +0 -132
  403. package/lib/publisher.mjs +0 -1263
  404. package/web/admin/admin.js +0 -1114
  405. /package/lib/{oidc-auth.mjs → client/oidc-auth.mjs} +0 -0
  406. /package/lib/{webpush.mjs → client/webpush.mjs} +0 -0
  407. /package/lib/{bskyfeed.mjs → connections/bskyfeed.mjs} +0 -0
  408. /package/lib/{lease.mjs → core/lease.mjs} +0 -0
  409. /package/lib/{polls.mjs → core/polls.mjs} +0 -0
  410. /package/lib/{proof.mjs → core/proof.mjs} +0 -0
  411. /package/lib/{account.mjs → device/account.mjs} +0 -0
  412. /package/lib/{certs.mjs → device/certs.mjs} +0 -0
  413. /package/lib/{home.mjs → device/home.mjs} +0 -0
  414. /package/lib/{ports.mjs → device/ports.mjs} +0 -0
  415. /package/lib/{guard.mjs → shared/guard.mjs} +0 -0
  416. /package/lib/{safefetch.mjs → shared/safefetch.mjs} +0 -0
package/lib/intake.mjs DELETED
@@ -1,1764 +0,0 @@
1
- // intake.mjs — drains the remote pod's public-append inbox and applies side
2
- // effects. Inbound authenticity: LDN bodies don't carry the delivery's
3
- // HTTP-Signature headers, so instead of verifying signatures we VERIFY BY
4
- // DEREFERENCING — re-fetch the claimed object/actor from its origin (signed
5
- // GET, so authorized-fetch instances answer) and trust only what the origin
6
- // itself serves.
7
- //
8
- // Failure policy: a REJECTED item (verification says no) goes to the
9
- // dead-letter store and leaves the inbox; a FAILING item (exception —
10
- // network, remote 5xx) stays in the inbox for the next drain, and moves to
11
- // the dead-letter store after MAX_ITEM_ATTEMPTS. Nothing is silently
12
- // destroyed.
13
- //
14
- // Wake-up: WebSocketChannel2023 push on the inbox container (probe P4), plus
15
- // a poll every POLL_MS as fallback, plus a drain at startup.
16
-
17
- import * as $rdf from 'rdflib';
18
- import { USER_AGENT } from './ua.mjs';
19
- import { PUBLIC } from './wire.mjs';
20
- import { HTTP_TIMEOUT_MS, readCapped } from './safefetch.mjs';
21
- import { linkTargets, REL } from './links.mjs';
22
- import * as polls from './polls.mjs';
23
- import { dropFollower } from './store.mjs';
24
-
25
- const RDF = $rdf.Namespace('http://www.w3.org/1999/02/22-rdf-syntax-ns#');
26
- const NOTIFY = $rdf.Namespace('http://www.w3.org/ns/solid/notifications#');
27
-
28
- const POLL_MS = 2 * 60_000; // fallback cadence when there is no push
29
- // With a live socket the poll is pure redundancy: it exists for the case where
30
- // push is down, so it slows right down while push is up.
31
- const POLL_PUSH_OK_MS = 10 * 60_000;
32
- // The channel a subscription returns outlives a dropped socket, so reconnecting
33
- // reuses it. Creating a new one per reconnect is what buried solidcommunity.net
34
- // in channel records they then had to sweep.
35
- const CHANNEL_DOC = 'inbox-channel.json';
36
- // A flapping socket used to POST a NEW WebSocketChannel2023 channel every two
37
- // seconds — hundreds an hour against a server that is already struggling, and
38
- // channel churn its operators have to sweep up. Backs off instead, and an open
39
- // only triggers a sweep if we have not just swept.
40
- const RECONNECT_MIN_MS = 2_000;
41
- const RECONNECT_MAX_MS = 5 * 60_000;
42
- // How long a socket must stay up before the backoff counts it as a success and
43
- // resets. Shorter than that is a flap, not a connection.
44
- const RECONNECT_STABLE_MS = 60_000;
45
- const OPEN_DRAIN_MIN_GAP_MS = 30_000;
46
- // A container that times out will time out again in two minutes, and each
47
- // attempt holds one of the pod's workers for the full timeout. Sweeping stops
48
- // for a while instead, doubling up to half an hour.
49
- const DRAIN_COOLDOWN_MIN_MS = 2 * 60_000;
50
- const DRAIN_COOLDOWN_MAX_MS = 30 * 60_000;
51
- // Our DELETEs take the same container write lock as the deliveries arriving
52
- // into it — a gap between them keeps a sweep from convoying against inbound.
53
- const DELETE_GAP_MS = 150;
54
- const CHAIN_GAP_MS = 5_000; // pause between chained backlog sweeps
55
- // How many handled items ride on one commit before they are deleted. Small
56
- // enough that a crash re-does little, large enough that a flood of fast
57
- // rejections does not become a pod write per item.
58
- const DELETE_BATCH = 10;
59
- // Attempt counts live in pod state, not in memory: a restart used to hand every
60
- // poison item five fresh tries, and under a crash loop that is unbounded.
61
- const ATTEMPTS_DOC = 'intake-attempts.json';
62
- const ATTEMPTS_TTL_MS = 7 * 24 * 60 * 60_000;
63
- const MAX_ITEM_ATTEMPTS = 5;
64
- const MAX_ITEMS_PER_DRAIN = 50;
65
- // A note's replies collection is rewritten WHOLE every time one is added, so
66
- // without a cap the bytes are quadratic in a number a stranger chooses.
67
- const MAX_REPLIES_RECORDED = 500;
68
- // Ids of activities already forwarded to our followers (§7.1.2), so a re-drain
69
- // never re-broadcasts one. A ceiling on the record, not on forwarding.
70
- const MAX_FORWARDED = 2000;
71
- // How many posts may wait for a group operator's decision. A ceiling, not a
72
- // window: full refuses the newest rather than dropping the oldest.
73
- const MAX_PENDING_REVIEW = 500;
74
- // A group's membership, cached: it changes when someone joins or leaves, and
75
- // re-reading it on every arriving post would spend one stranger's fetch per
76
- // message on a list that moves in days.
77
- const CO_MEMBER_TTL_MS = 24 * 60 * 60_000;
78
- const CO_MEMBER_MAX = 5000;
79
- // An activity is a few kB. This is generous by two orders of magnitude and
80
- // still bounds what one Append can make us hold in memory.
81
- const MAX_ITEM_BYTES = 512 * 1024;
82
- // The AS2 actor types. A group is as much an actor as a person is.
83
- const ACTOR_TYPES = new Set(['Person', 'Group', 'Service', 'Application', 'Organization']);
84
- // The AS2 types the fediverse actually posts. `Note` alone is Mastodon's world
85
- // and not the fediverse's: an Article is a Plume or WriteFreely post, a
86
- // Question is a poll, a Video is PeerTube, a Page is Lemmy, an Audio is
87
- // Funkwhale. Insisting on Note dead-lettered every one of them as "not a
88
- // verifiable Note" — from people the owner had chosen to follow, silently.
89
- //
90
- // They share the shape this code reads: attributedTo, content, published,
91
- // inReplyTo, tag, attachment. A poll's options are dropped, which is a
92
- // degraded rendering rather than a lost post.
93
- const CONTENT_TYPES = new Set(['Note', 'Article', 'Question', 'Page', 'Video', 'Audio', 'Image', 'Event']);
94
-
95
- // A Question is a poll: its options live in oneOf (pick one) or anyOf (pick
96
- // several), each carrying the tally its author's server maintains.
97
- // Custom emojis ride the tag list; the images live at the author's server and
98
- // the client fetches them from there.
99
- function emojisOf(note) {
100
- return [].concat(note?.tag || [])
101
- .filter(t => t?.type === 'Emoji' && t.icon?.url && t.name)
102
- .map(t => ({ shortcode: String(t.name).replace(/^:|:$/g, ''), url: String(t.icon.url) }));
103
- }
104
-
105
- function pollOf(note) {
106
- const opts = note?.oneOf || note?.anyOf;
107
- if (!Array.isArray(opts) || !opts.length) return null;
108
- return {
109
- multiple: !!note.anyOf,
110
- expiresAt: note.endTime || null,
111
- closed: !!note.closed,
112
- options: opts.map(o => ({
113
- title: String(o?.name ?? ''),
114
- votes: Number(o?.replies?.totalItems) || 0,
115
- })),
116
- };
117
- }
118
- // AS2 lets `type` be one string or a list, and implementations use both —
119
- // `["Person","Service"]` is an ordinary actor. Read either form.
120
- const typesOf = (t) => (Array.isArray(t) ? t : [t]).filter(x => typeof x === 'string');
121
- export const isContentType = (t) => typesOf(t).some(x => CONTENT_TYPES.has(x));
122
- const isActorType = (t) => typesOf(t).some(x => ACTOR_TYPES.has(x));
123
-
124
- // What we will carry to our followers on someone else's behalf (§7.1.2): the
125
- // activities a conversation is made of, and nothing else. A type this file
126
- // does not handle falls out of handle() with no rejection, and "no rejection"
127
- // is what qualifies an activity for forwarding — so without this gate a
128
- // stranger could have anything at all, of a type nothing here reads,
129
- // re-delivered to every follower over our signature.
130
- const FORWARDABLE = new Set(['Create', 'Update', 'Delete', 'Like', 'Announce', 'Undo']);
131
- const ACCEPT_AP = 'application/activity+json, application/ld+json; profile="https://www.w3.org/ns/activitystreams"';
132
-
133
- export function sameOrigin(a, b) {
134
- try { return new URL(a).origin === new URL(b).origin; } catch { return false; }
135
- }
136
-
137
- // Is this socket URL the pod's own? The scheme has to be the socket form of the
138
- // pod's — wss for https, ws for http — so a downgrade to plaintext from an https
139
- // pod is somewhere else, not the same place unencrypted.
140
- //
141
- // The host may be the pod's, or a PARENT of it. Not a loosening for
142
- // convenience: a CSS server that gives every pod a subdomain answers
143
- // notifications from the server root, so jeff-zucker.teamid.live is served by
144
- // wss://teamid.live/.notifications/… — which is the deployment this project
145
- // actually runs on. Requiring an exact match dropped it to polling, and the
146
- // live agents are how that was found rather than the suite.
147
- //
148
- // A sibling subdomain is still refused: only a suffix of our own host passes,
149
- // and two labels minimum so `.live` cannot pose as everyone's parent. Not a
150
- // public-suffix list — that is a dependency and a data file to keep current,
151
- // and the party this guards against is the pod you already chose to trust.
152
- export function sameSocketOrigin(socketUrl, podBase) {
153
- let s, p;
154
- try { s = new URL(socketUrl); p = new URL(podBase); } catch { return false; }
155
- if (s.protocol !== (p.protocol === 'https:' ? 'wss:' : 'ws:')) return false;
156
- if (s.host === p.host) return true;
157
- const parent = s.hostname.toLowerCase();
158
- return parent.split('.').length >= 2
159
- && s.port === p.port
160
- && p.hostname.toLowerCase().endsWith('.' + parent);
161
- }
162
-
163
- export function httpUrl(u) {
164
- try {
165
- const p = new URL(String(u)).protocol;
166
- return p === 'https:' || p === 'http:';
167
- } catch { return false; }
168
- }
169
-
170
- // Who a note is BY. A document may only speak for an actor at its own origin.
171
- // `attributedTo` used to be taken at face value, so a note served anywhere
172
- // could name anyone: one at a host the attacker controls, claiming to be by
173
- // someone the owner follows, passed every check we had — the envelope's
174
- // sameOrigin compares the ACTIVITY to its object, never the object to its
175
- // author — and landed in the home timeline and in the pod as them. For a group
176
- // it went further still, because amplify() gates on the author's membership,
177
- // so the group signed an Announce of it and delivered it to every member.
178
- //
179
- // `delivered` is the actor that brought it, used only when the note names no
180
- // author of its own; it has to clear the same test, which is why a boost of an
181
- // unattributed note is refused rather than credited to the booster.
182
- //
183
- // Returns the author, or null when nothing at the note's origin vouches for one.
184
- export function authorOf(note, delivered = null) {
185
- const claimed = [].concat(note?.attributedTo || [])
186
- .map(a => (typeof a === 'string' ? a : a?.id)).find(Boolean) || null;
187
- const author = claimed || delivered;
188
- if (!author) return null;
189
- return sameOrigin(note?.id, author) ? author : null;
190
- }
191
-
192
- export class Intake {
193
- constructor({ config, urls, remote, local, store, deliverer, publisher, log = console.log, lease = null, archive = null, push = true, pollSeconds = null }) {
194
- Object.assign(this, { config, urls, remote, local, store, deliverer, publisher, log, lease, archive, push, pollSeconds });
195
- this.serial = Date.now();
196
- this.stopped = false;
197
- // (attempt counts are kept in pod state — see _bumpAttempt)
198
- this.lastDrain = null;
199
- this.lastDrainAtMs = 0;
200
- this.reconnectTries = 0;
201
- this.drainCooldownUntil = 0;
202
- this.drainFailures = 0;
203
- this.wsState = 'never-connected';
204
- }
205
-
206
- // Draining is a destructive read — an item is gone from the pod once we
207
- // DELETE it — so the result of handling it must be on disk first.
208
- //
209
- // This used to be skipped whenever the state and the inbox shared an origin,
210
- // on the reasoning that a pod we cannot write to is a pod we cannot list
211
- // either, so the drain never starts. That covers the pod being unreachable
212
- // and nothing else: it does not cover a crash inside the 300ms debounce
213
- // window, and it does not cover a pod that refuses a write while still
214
- // serving reads and deletes — a quota, a 507, a 403 on one document. In
215
- // either case every item drained since the last successful write is gone,
216
- // and what goes is the mentions, replies, join requests and dead-letter
217
- // records that nothing else can rebuild.
218
- async _persisted() {
219
- return this.store.commit();
220
- }
221
-
222
- _backOff(why) {
223
- this.drainFailures++;
224
- const capped = Math.min(DRAIN_COOLDOWN_MIN_MS * 2 ** (this.drainFailures - 1), DRAIN_COOLDOWN_MAX_MS);
225
- this.drainCooldownUntil = Date.now() + Math.round(capped * (0.85 + Math.random() * 0.3));
226
- this.log(`${why} — next sweep in ${Math.round(capped / 1000)}s`);
227
- }
228
-
229
- // Sweep cadence: a configured interval wins, otherwise a live push channel —
230
- // a notification socket, or the store's own change events in-process — is
231
- // what makes the fallback poll a slow one.
232
- _pollMs() {
233
- if (this.pollSeconds) return this.pollSeconds * 1000;
234
- return this.wsState === 'open' || this.wsState === 'in-process' ? POLL_PUSH_OK_MS : POLL_MS;
235
- }
236
-
237
- async start() {
238
- this.stopped = false; // restartable across demote/takeover cycles
239
- await this.drain().catch(e => this.log(`drain: ${e.message}`));
240
- const tick = () => {
241
- this.pollTimer = setTimeout(() => {
242
- this.drain().catch(e => this.log(`drain: ${e.message}`)).finally(() => { if (!this.stopped) tick(); });
243
- }, Math.round(this._pollMs() * (0.85 + Math.random() * 0.3)));
244
- this.pollTimer.unref?.();
245
- };
246
- tick();
247
- // Embedded in the pod server, a notification socket back to that same
248
- // server buys nothing — the store's own change events wake the drain.
249
- if (this.push) this.subscribe().catch(e => this.log(`subscribe: ${e.message}`));
250
- else this.wsState = 'in-process';
251
- }
252
-
253
- stop() { this.stopped = true; clearTimeout(this.pollTimer); clearTimeout(this.resubTimer); this.ws?.close(); }
254
-
255
- // Attempt bookkeeping, persisted. Written only when an item fails, so a
256
- // healthy inbox never touches this document.
257
- _bumpAttempt(url, message) {
258
- const all = this.store.read(ATTEMPTS_DOC, {});
259
- const rec = all[url] || { n: 0 };
260
- rec.n += 1;
261
- rec.at = new Date().toISOString();
262
- rec.last = String(message || '').slice(0, 200);
263
- all[url] = rec;
264
- this.store.write(ATTEMPTS_DOC, all);
265
- return rec.n;
266
- }
267
-
268
- _clearAttempt(url) {
269
- const all = this.store.read(ATTEMPTS_DOC, {});
270
- if (!all[url]) return;
271
- delete all[url];
272
- this.store.write(ATTEMPTS_DOC, all);
273
- }
274
-
275
- // Items deleted long ago would otherwise accumulate here forever.
276
- _pruneAttempts() {
277
- const all = this.store.read(ATTEMPTS_DOC, {});
278
- const cutoff = Date.now() - ATTEMPTS_TTL_MS;
279
- let dropped = 0;
280
- for (const [url, rec] of Object.entries(all)) {
281
- if (!rec?.at || Date.parse(rec.at) < cutoff) { delete all[url]; dropped++; }
282
- }
283
- if (dropped) { this.store.write(ATTEMPTS_DOC, all); this.log(`pruned ${dropped} stale inbox attempt record(s)`); }
284
- }
285
-
286
- // Jittered exponential, floor to ceiling, reset by a successful open.
287
- _reconnectDelay() {
288
- const capped = Math.min(RECONNECT_MIN_MS * 2 ** this.reconnectTries, RECONNECT_MAX_MS);
289
- this.reconnectTries++;
290
- return Math.round(capped * (0.8 + Math.random() * 0.4));
291
- }
292
-
293
- // --- push ---
294
- // Any failure in here used to end push for the life of the process: the
295
- // retry lived only in the "server refused the subscription" branch, so a
296
- // network blip left wsState at never-connected and the agent silently on
297
- // polling. Every path now schedules a retry on the same backoff.
298
- async subscribe() {
299
- try {
300
- await this._subscribeOnce();
301
- } catch (e) {
302
- this.wsState = 'subscribe-error';
303
- const wait = this._reconnectDelay();
304
- this.log(`subscribe failed (${e.message}) — retrying in ${Math.round(wait / 1000)}s (polling meanwhile)`);
305
- if (!this.stopped) {
306
- this.resubTimer = setTimeout(() => this.subscribe().catch(() => {}), wait);
307
- this.resubTimer.unref?.();
308
- }
309
- }
310
- }
311
-
312
- /**
313
- * Where this pod describes the services it offers. The pod says so on any
314
- * response about one of its resources; the well-known path is only what a
315
- * pod that says nothing has always used.
316
- */
317
- async _storageDescriptionUrl() {
318
- try {
319
- const head = await fetch(this.urls.base, {
320
- method: 'HEAD',
321
- headers: { 'user-agent': USER_AGENT },
322
- signal: AbortSignal.timeout(HTTP_TIMEOUT_MS),
323
- });
324
- const [found] = linkTargets(head.headers.get('link'), REL.storageDescription, this.urls.base);
325
- if (found) return found;
326
- } catch { /* the well-known path below */ }
327
- return this.urls.base + '.well-known/solid';
328
- }
329
-
330
- async _subscribeOnce() {
331
- // Reuse a channel we already have rather than asking for another one.
332
- const saved = this.store.read(CHANNEL_DOC, null);
333
- if (saved?.receiveFrom && (!saved.endAt || Date.parse(saved.endAt) - Date.now() > 60_000)) {
334
- this._openSocket(saved.receiveFrom, true);
335
- return;
336
- }
337
- const descUrl = await this._storageDescriptionUrl();
338
- const descRes = await fetch(descUrl, {
339
- headers: { accept: 'text/turtle', 'user-agent': USER_AGENT },
340
- signal: AbortSignal.timeout(HTTP_TIMEOUT_MS),
341
- });
342
- // The service description is RDF; ask rdflib which subject is the
343
- // WebSocketChannel2023 service rather than pattern-matching the document.
344
- const g = $rdf.graph();
345
- try { $rdf.parse(await readCapped(descRes), g, descUrl, 'text/turtle'); }
346
- catch (e) { this.wsState = 'unavailable'; this.log(`service description unparsable (${e.message}) — polling only`); return; }
347
- const channel = g.each(null, RDF('type'), NOTIFY('WebSocketChannel2023'), null)
348
- .map(n => n.value)
349
- .find(Boolean)
350
- || g.each(null, NOTIFY('channelType'), NOTIFY('WebSocketChannel2023'), null)
351
- .map(n => n.value).find(Boolean);
352
- if (!channel) { this.wsState = 'unavailable'; this.log('no WebSocketChannel2023 service — polling only'); return; }
353
- // The topic is a POD resource, and it travels in the BODY — so the url map
354
- // RemotePod applies to the request line never reaches it. A fronted
355
- // identity's inbox url names the front, which the pod cannot grant read on,
356
- // and the subscription came back 403. A no-op when unfronted.
357
- const topic = this.urls.toPod ? this.urls.toPod(this.urls.inbox) : this.urls.inbox;
358
- const sub = await this.remote.fetch(channel, {
359
- method: 'POST',
360
- headers: { 'content-type': 'application/ld+json' },
361
- body: JSON.stringify({
362
- '@context': ['https://www.w3.org/ns/solid/notification/v1'],
363
- type: 'http://www.w3.org/ns/solid/notifications#WebSocketChannel2023',
364
- topic,
365
- }),
366
- });
367
- const body = await readCapped(sub).then(JSON.parse).catch(() => null);
368
- if (!body?.receiveFrom) {
369
- this.wsState = `subscribe-failed-${sub.status}`;
370
- const wait = this._reconnectDelay();
371
- this.log(`subscription failed (${sub.status}) — retrying in ${Math.round(wait / 1000)}s (polling meanwhile)`);
372
- if (!this.stopped) {
373
- this.resubTimer = setTimeout(() => this.subscribe().catch(e => this.log(`resubscribe: ${e.message}`)), wait);
374
- this.resubTimer.unref?.();
375
- }
376
- return;
377
- }
378
- this.store.write(CHANNEL_DOC, { receiveFrom: body.receiveFrom, endAt: body.endAt || null });
379
- this._openSocket(body.receiveFrom, false);
380
- }
381
-
382
- // The socket URL arrives in the pod's own subscription response, and it was
383
- // the one outbound address in the project that reached the network without
384
- // passing anything — safefetch guards every fetch, and `new WebSocket()` is
385
- // not a fetch. A pod that answered with somebody else's address had us open a
386
- // long-lived connection there and treat what came back as our inbox waking up.
387
- //
388
- // Same origin as the pod, not assertPublicUrl: a pod on this machine is a
389
- // documented setup and its socket is legitimately ws://localhost:3000, which
390
- // a public-address check would refuse.
391
- _openSocket(receiveFrom, reused) {
392
- if (!sameSocketOrigin(receiveFrom, this.urls.base)) {
393
- this.wsState = 'refused';
394
- this.log(`subscription named ${receiveFrom}, which is not this pod — polling only`);
395
- if (reused) this.store.write(CHANNEL_DOC, null);
396
- return;
397
- }
398
- this.ws = new WebSocket(receiveFrom);
399
- this.ws.onopen = () => {
400
- this.wsState = 'open';
401
- if (!this._announcedPush) { this.log('inbox push subscription active'); this._announcedPush = true; }
402
- this._openedAt = Date.now();
403
- // Anything that arrived while the socket was down is waiting — sweep it,
404
- // unless a sweep just ran: a flapping socket must not re-list the inbox
405
- // on every open.
406
- if (Date.now() - this.lastDrainAtMs > OPEN_DRAIN_MIN_GAP_MS) {
407
- this.drain().catch(e => this.log(`drain: ${e.message}`));
408
- }
409
- };
410
- this.ws.onmessage = () => this.drain().catch(e => this.log(`drain: ${e.message}`));
411
- this.ws.onclose = () => {
412
- this.wsState = 'closed';
413
- // Only a connection that STAYED up counts as a success. Resetting on open
414
- // alone meant the 2026-07-29 failure — a server that accepts the upgrade
415
- // and then drops the socket on a crash cycle — reconnected at the 2s
416
- // floor indefinitely: every cycle "succeeded", so the exponential cap was
417
- // never reached, and each open also drained the inbox.
418
- if (this._openedAt && Date.now() - this._openedAt >= RECONNECT_STABLE_MS) this.reconnectTries = 0;
419
- this._openedAt = 0;
420
- if (!this.stopped) {
421
- this.resubTimer = setTimeout(() => this.subscribe().catch(e => this.log(`resubscribe: ${e.message}`)), this._reconnectDelay());
422
- this.resubTimer.unref?.();
423
- }
424
- };
425
- this.ws.onerror = () => {
426
- this.wsState = 'error';
427
- // A channel we reused may simply be gone: forget it so the next attempt
428
- // asks for a fresh one instead of retrying a dead URL forever.
429
- if (reused) this.store.write(CHANNEL_DOC, null);
430
- };
431
- }
432
-
433
- // --- drain + dispatch ---
434
- // Serialized: push events, polls, and manual /drain calls can fire
435
- // concurrently, and overlapping sweeps double-process items (observed as
436
- // duplicate Accepts/timeline writes). One sweep at a time; callers that
437
- // arrive mid-sweep get one follow-up sweep.
438
- async drain() {
439
- if (this._draining) { this._drainAgain = true; return this._draining; }
440
- // Held for the whole sweep, released however it ends. The debounce cannot
441
- // coalesce a drain — every handler awaits somebody else's server first — so
442
- // the writes are left to the commit boundaries the drain already has. See
443
- // PodStore.hold.
444
- // Optional: this is a throughput hint, not part of the commit-before-delete
445
- // invariant — commit() flushes whatever is pending either way — so a store
446
- // that does not implement it behaves exactly as before.
447
- this._inSweep = true;
448
- this.store.hold?.();
449
- this._draining = this._drainOnce().finally(async () => {
450
- this._inSweep = false;
451
- await this._publishPending();
452
- this.store.release?.();
453
- this._draining = null;
454
- if (this._drainAgain) {
455
- this._drainAgain = false;
456
- // Paced, not immediate: chained sweeps put a ceiling on work per unit
457
- // time, so a delivery flood cannot run the drain back-to-back.
458
- const t = setTimeout(() => this.drain().catch(e => this.log(`drain: ${e.message}`)), CHAIN_GAP_MS);
459
- t.unref?.();
460
- }
461
- });
462
- return this._draining;
463
- }
464
-
465
- // Discard the content waiting in the inbox from before `before`, on the
466
- // owner's say-so — the admin page asks, this does it. NOT a blind sweep:
467
- // every item is read, because the type is the only thing that decides its
468
- // fate and size does not predict it. A Follow, Undo, Accept or Delete is
469
- // APPLIED whatever it weighs, so the follow graph stays correct and a post
470
- // its author retracted still goes; only a Create is dropped. Judging by size
471
- // instead saved one request per item and lost any control activity that
472
- // happened to be large, silently and permanently.
473
- //
474
- // An item past the drain's own byte cap is deleted unread: it could not be
475
- // handled if it were read, so there is nothing to lose by not reading it.
476
- //
477
- // `keepConcerning` narrows the discard to noise: every item is passed to
478
- // handle(), which ingests a Create only when concernsUs passes — addressed to
479
- // us, a mention, a reply to ours, or from someone we follow — and drops the
480
- // rest.
481
- async prune({ before, keepConcerning = false } = {}) {
482
- const cutoff = Date.parse(before);
483
- if (!Number.isFinite(cutoff)) throw new Error(`"${before}" is not a date`);
484
- const all = await this.remote.listContainer(this.urls.inbox);
485
- const older = all.filter(e => !e.url.endsWith('.keep')
486
- && e.modified && Date.parse(e.modified) < cutoff);
487
- const out = { considered: older.length, applied: 0, dropped: 0, discarded: 0, failed: 0 };
488
-
489
- for (const item of older) {
490
- try {
491
- if (item.size > MAX_ITEM_BYTES) {
492
- await this.remote.delete(item.url); // unreadable by the drain either way
493
- out.discarded++;
494
- } else {
495
- const res = await this.remote.fetch(item.url, { headers: { accept: '*/*' } });
496
- // Same rule as the drain: a read we could not make is not a Create to
497
- // be dropped. Let it count as failed and stay for the next pass.
498
- if (res.status >= 400 && res.status !== 404) throw new Error(`inbox item GET → ${res.status}`);
499
- const activity = res.status < 400 ? await res.json().catch(() => null) : null;
500
- // A Create is the content the owner just asked to be rid of. Anything
501
- // else changes state and is applied exactly as a drain would.
502
- if (keepConcerning) {
503
- const rejection = activity ? await this.handle(activity) : 'unparsable JSON';
504
- if (rejection) out.dropped++; else out.applied++;
505
- } else if (activity && activity.type !== 'Create') {
506
- await this.handle(activity);
507
- out.applied++;
508
- } else {
509
- out.dropped++;
510
- }
511
- if (!await this._persisted()) {
512
- this.log(`state not written — stopping the prune with ${older.length - out.applied - out.dropped - out.discarded} left`);
513
- break;
514
- }
515
- await this.remote.delete(item.url);
516
- }
517
- this._clearAttempt(item.url);
518
- await new Promise(r => setTimeout(r, DELETE_GAP_MS));
519
- } catch (e) {
520
- out.failed++;
521
- this.log(`prune ${item.url}: ${e.message}`);
522
- }
523
- }
524
- this.log(`pruned before ${before}: applied ${out.applied}, dropped ${out.dropped} `
525
- + `small Create(s), discarded ${out.discarded} unread${out.failed ? `, ${out.failed} failed` : ''}`);
526
- await this.store.flush();
527
- // Adjust the measurement in place rather than kicking a drain to re-take
528
- // it: an un-awaited drain would still be running when this returns, which
529
- // races whoever called us. The poll picks the rest up soon enough.
530
- const removed = out.applied + out.dropped + out.discarded;
531
- if (this.inboxStats && removed) {
532
- this.inboxStats = { ...this.inboxStats, count: Math.max(0, this.inboxStats.count - removed) };
533
- }
534
- return out;
535
- }
536
-
537
- // The sender's original bytes, kept after the activity was verified and
538
- // applied and before the pod DELETE erases the only other copy. The filename
539
- // is the content's own hash, so a re-delivered activity lands on the same
540
- // file instead of duplicating. Best-effort history: a failed write logs and
541
- // the drain goes on — mail must never stall on its own receipt. This is the
542
- // one category of account data that lives only in the private half; the pod
543
- // cannot rebuild it because the pod never kept it.
544
- //
545
- // The record is JSON-LD: a cnt:ContentAsText whose cnt:chars are the raw
546
- // bytes, stamped prov:generatedAtTime / prov:wasDerivedFrom / as:actor —
547
- // plain JSON to everything here, a graph to any RDF reader.
548
- async _archive(sourceUrl, raw, activity) {
549
- try {
550
- if (!this.archive || this.store.getConfig()?.archiveInbox === false) return;
551
- const { createHash } = await import('node:crypto');
552
- const hash = createHash('sha256').update(raw).digest('hex').slice(0, 16);
553
- const receivedAt = new Date().toISOString();
554
- const rec = {
555
- '@context': {
556
- prov: 'http://www.w3.org/ns/prov#',
557
- cnt: 'http://www.w3.org/2011/content#',
558
- as: 'https://www.w3.org/ns/activitystreams#',
559
- xsd: 'http://www.w3.org/2001/XMLSchema#',
560
- receivedAt: { '@id': 'prov:generatedAtTime', '@type': 'xsd:dateTime' },
561
- source: { '@id': 'prov:wasDerivedFrom', '@type': '@id' },
562
- actor: { '@id': 'as:actor', '@type': '@id' },
563
- raw: 'cnt:chars',
564
- },
565
- '@id': '',
566
- '@type': 'cnt:ContentAsText',
567
- receivedAt,
568
- actor: typeof activity?.actor === 'string' ? activity.actor : activity?.actor?.id || null,
569
- source: sourceUrl,
570
- raw,
571
- };
572
- const w = await this.archive.write(`${receivedAt.slice(0, 7)}/${hash}.json`,
573
- JSON.stringify(rec, null, 2), 'application/ld+json');
574
- if (!w.ok) this.log(`inbox archive: ${w.why || 'write failed'}`);
575
- } catch (e) {
576
- this.log(`inbox archive: ${e.message}`);
577
- }
578
- }
579
-
580
- async _drainOnce() {
581
- const cooling = this.drainCooldownUntil - Date.now();
582
- if (cooling > 0) {
583
- this.log(`inbox sweep skipped — backing off for another ${Math.ceil(cooling / 1000)}s`);
584
- return;
585
- }
586
- // Draining DELETES from the pod, so it must not run on a lease that has
587
- // quietly expired. renewOnce notices at its own cadence — up to ~117s — and
588
- // after the TTL another agent is entitled to start draining the same inbox.
589
- if (this.lease && !this.lease.stillHeld()) {
590
- this.log('lease is no longer held — not draining');
591
- return;
592
- }
593
- this.lastDrain = new Date().toISOString();
594
- this.lastDrainAtMs = Date.now();
595
- this._pruneAttempts();
596
- let all;
597
- try {
598
- all = await this.remote.listContainer(this.urls.inbox);
599
- this.drainFailures = 0;
600
- } catch (e) {
601
- this._backOff(`inbox unreadable (${e.message})`);
602
- return;
603
- }
604
- // What is waiting, measured from the listing we already fetched: no extra
605
- // request, and it is what /status reports and what the admin page prompts
606
- // on. The listing arrives oldest-first (lib/remote.mjs).
607
- const real = all.filter(e => !e.url.endsWith('.keep'));
608
- this.inboxStats = {
609
- count: real.length,
610
- bytes: real.reduce((n, e) => n + e.size, 0),
611
- oldest: real[0]?.modified || null,
612
- newest: real[real.length - 1]?.modified || null,
613
- at: new Date().toISOString(),
614
- };
615
- // The inbox is public-Append: a flood must not turn one sweep into an
616
- // unbounded run. But stopping there is why a backlog never cleared — 50
617
- // items every two minutes does not converge on an agent that is only
618
- // running while a laptop is open. So a sweep that made progress and left
619
- // work behind goes straight round again.
620
- const items = all.slice(0, MAX_ITEMS_PER_DRAIN);
621
- if (all.length > items.length) this.log(`inbox has ${all.length} items — processing ${items.length} this sweep`);
622
- let handled = 0;
623
- // Deletes are batched behind ONE commit rather than a commit per item.
624
- // Per-item, the 300ms debounce that coalesces a sweep's writes never gets
625
- // to do its job: on a flood of fast rejections that is fifty writes of
626
- // deadletter.json where one would do, and a flood is exactly when the pod
627
- // should be asked for less rather than more.
628
- const pending = [];
629
- const flush = async () => {
630
- if (!pending.length) return true;
631
- // Written down before any of them leaves the mailbox. A failure here
632
- // leaves them where they are: the next sweep sees them again, and a
633
- // re-delivered activity is handled idempotently.
634
- if (!await this._persisted()) {
635
- this._backOff(`state not written — ${pending.length} item(s) left in the inbox`);
636
- pending.length = 0;
637
- return false;
638
- }
639
- for (const url of pending.splice(0)) {
640
- if (!await this.remote.delete(url)) {
641
- // Still in the mailbox. Handling is idempotent so seeing it again is
642
- // harmless, but counting it would clear the attempt record and report
643
- // progress that did not happen.
644
- this.log(`inbox item ${url} was handled but NOT removed — it will be seen again`);
645
- continue;
646
- }
647
- this._clearAttempt(url);
648
- handled++;
649
- await new Promise(r => setTimeout(r, DELETE_GAP_MS));
650
- }
651
- return true;
652
- };
653
-
654
- for (const { url, size } of items) {
655
- if (url.endsWith('.keep')) continue;
656
- // The listing already carries every child's size, so this costs nothing
657
- // to ask. An activity is a few kB; anything of this order is not one, and
658
- // reading it with an unbounded res.text() buffers whatever a stranger
659
- // chose to Append into memory.
660
- // A cheap pre-filter only: listContainer coerces a missing posix:size to
661
- // 0, so a pod that does not publish sizes would wave everything through.
662
- // The real bound is readCapped on the body below.
663
- if (size > MAX_ITEM_BYTES) {
664
- this.store.addDeadLetter({ inboxUrl: url, reason: `oversized (${size} bytes)`, activity: null });
665
- pending.push(url);
666
- continue;
667
- }
668
- let activity = null;
669
- try {
670
- const res = await this.remote.fetch(url, { headers: { accept: '*/*' } });
671
- // A pod that would not GIVE us the item has told us nothing about it.
672
- // Reading a 500 as an empty body made it "unparsable JSON", which is a
673
- // REJECTION: dead-lettered with both `activity` and `raw` null, and then
674
- // DELETEd — a delivery destroyed by a transient fault, with no record of
675
- // what it was. Throwing puts it on the retry path the header promises.
676
- // 404 is the exception: the item is already gone, so deleting is right.
677
- if (res.status >= 400 && res.status !== 404) throw new Error(`inbox item GET → ${res.status}`);
678
- // Capped rather than res.text(): the listing's size is advisory, and the
679
- // inbox is public-Append, so the body is whatever a stranger chose.
680
- const raw = res.status < 400 ? await readCapped(res, MAX_ITEM_BYTES) : null;
681
- try { activity = raw ? JSON.parse(raw) : null; } catch { /* kept raw for the dead letter */ }
682
- // A gateway that verified this delivery left a receipt beside it. Read
683
- // it only when a gateway is configured (no config → no fetch, so an
684
- // install with no gateway pays nothing); a missing or HMAC-invalid
685
- // receipt reads as null, which is exactly today's unverified behavior.
686
- const receipt = activity ? await this._readReceipt(url) : null;
687
- if (activity && this.gatewaySecret()) this._bumpGatewayStat(!!receipt?.verified);
688
- const rejection = activity ? await this.handle(activity, receipt) : 'unparsable JSON';
689
- if (!rejection && raw) await this._archive(url, raw, activity);
690
- if (!rejection) await this._maybeForward(activity); // §7.1.2, only what we accepted
691
- if (rejection) {
692
- this.store.addDeadLetter({
693
- inboxUrl: url, reason: rejection, activity,
694
- ...(activity ? {} : { raw: raw?.slice(0, 2000) ?? null }),
695
- });
696
- this.log(`rejected (${rejection}) — dead-lettered: ${url}`);
697
- }
698
- pending.push(url);
699
- } catch (e) {
700
- const n = this._bumpAttempt(url, e.message);
701
- this.log(`inbox item ${url} attempt ${n}/${MAX_ITEM_ATTEMPTS}: ${e.message}`);
702
- if (n >= MAX_ITEM_ATTEMPTS) {
703
- this.store.addDeadLetter({ inboxUrl: url, reason: `failed ${n}x: ${e.message}`, activity });
704
- // The dead letter IS the record of this item — deleting before it is
705
- // written down would lose the only evidence it ever arrived, so it
706
- // goes through the same commit-then-delete batch as everything else.
707
- pending.push(url);
708
- }
709
- }
710
- if (pending.length >= DELETE_BATCH && !await flush()) return;
711
- }
712
- if (!await this._finishSweep(flush)) return;
713
- // Made progress and there is more waiting: go straight round rather than
714
- // sleeping. Gated on progress so a sweep that achieved nothing — a
715
- // cooldown, an unwritable store, poison at the head — cannot spin.
716
- if (handled > 0 && all.length > items.length && !this.stopped) this._drainAgain = true;
717
- }
718
-
719
- // The end of a sweep: publish whatever the follow graph did ONCE, then flush.
720
- //
721
- // publishCollections used to run per handled item — every Follow, Undo,
722
- // Accept, Reject, admit and eject — and each one is a full GET of the pod's
723
- // followers collection plus a PUT of it. Fifty follows in a sweep were a
724
- // hundred requests where two would do, and the answer they arrive at is the
725
- // same either way, because it is built from contacts.json in memory.
726
- async _finishSweep(flush) {
727
- await this._publishPending();
728
- return flush();
729
- }
730
-
731
- // Idempotent: it clears what it takes, so the drain's own exit path calling
732
- // it again after a sweep that bailed early — an unwritable store, a delete
733
- // that failed — is a no-op in the ordinary case and the difference between
734
- // "published" and "waiting for a sweep that may never come" in the other.
735
- async _publishPending() {
736
- const want = this._republish;
737
- this._republish = null;
738
- if (!want) return;
739
- try { await this.publisher.publishCollections(want); }
740
- catch (e) { this.log(`publishing collections: ${e.message}`); }
741
- }
742
-
743
- // Ask for a collection to be republished at the end of this sweep. Outside a
744
- // sweep there is no boundary to wait for, so it happens now.
745
- async republish(which) {
746
- if (!this._inSweep) return this.publisher.publishCollections(which);
747
- this._republish = { ...(this._republish || {}), ...which };
748
- }
749
-
750
- async fetchAP(url) {
751
- const res = await this.deliverer.signedFetch(url, { headers: { accept: ACCEPT_AP } });
752
- if (res.status >= 400) return null;
753
- // Remote servers are untrusted: read with a byte budget rather than
754
- // letting res.json() buffer whatever they choose to send.
755
- const { readCapped } = await import('./safefetch.mjs');
756
- // Plenty of servers answer 200 text/html however politely we ask for AS2 —
757
- // people reply to ordinary web pages, and their id is that page. Say so,
758
- // rather than handing the HTML to JSON.parse and logging the parser's
759
- // complaint about an unexpected `<`.
760
- // Not logged: people reply to ordinary web pages, so the reply's object id
761
- // is that page and this is the expected answer, not a fault. Only a server
762
- // that CLAIMS to be sending JSON and then does not is worth a line.
763
- const ct = (res.headers.get('content-type') || '').split(';')[0].trim().toLowerCase();
764
- if (ct && !ct.endsWith('json')) return null;
765
- let doc = null;
766
- try { doc = JSON.parse(await readCapped(res)); }
767
- catch (e) { this.log(`fetch ${url}: unreadable as JSON — ${e.message}`); return null; }
768
- // Every actor type, not just Person. A Group was fetched, used and thrown
769
- // away, so nothing knew its preferredUsername — and a client rendering it
770
- // fell back to the last path segment of the actor URL, which is the literal
771
- // word `actor`. That is where @actor@host came from.
772
- // Under the id the document CLAIMS, but only when its own origin vouches
773
- // for that id. A stranger's actor document naming someone else's id used to
774
- // overwrite that actor's cached name, bio, avatar and Person/Group flag —
775
- // one appended Follow was enough, and the id-mismatch checks in onFollow
776
- // and ingestNote both run after this line and never undid it.
777
- //
778
- // Same origin rather than exact equality: signedFetch follows redirects
779
- // without reporting where it landed, so a server that redirects its own
780
- // canonical actor URL would otherwise stop being cached at all.
781
- if (isActorType(doc?.type) && doc.id && sameOrigin(doc.id, url)) {
782
- this.store.cacheActor(doc.id, doc);
783
- }
784
- return doc;
785
- }
786
-
787
- sameOrigin(a, b) { return sameOrigin(a, b); }
788
-
789
- // Have we ever heard of this actor or object? Answered entirely from local
790
- // state, so asking costs nothing. It is what stops a stranger's Delete or
791
- // Update — of which Mastodon broadcasts a great many, and of which anyone at
792
- // all can Append one — turning into a signed request to a host they chose.
793
- known(id) {
794
- const c = this.store.getContacts();
795
- return c.followers.some(f => f.actor === id)
796
- || c.following.some(f => f.actor === id)
797
- || this.store.getStatuses().some(s => s.noteId === id || s.actor === id)
798
- || !!this.store.getActors()[id];
799
- }
800
-
801
- // Returns a rejection reason string, or undefined when handled.
802
- // The gateway's shared HMAC secret, or null when no gateway is configured.
803
- // Its absence is what makes the whole receipt path dormant by default.
804
- gatewaySecret() {
805
- return this.store.getConfig()?.gateway?.hmacSecret || null;
806
- }
807
-
808
- // Shadow-mode measurement: how much real traffic actually verified. The one
809
- // number an operator needs before trusting receipts. Only touched while a
810
- // gateway is configured, so it costs a non-gateway install nothing.
811
- _bumpGatewayStat(verified) {
812
- const s = this.store.read('gateway-stats.json', { verified: 0, unverified: 0 });
813
- if (verified) s.verified++; else s.unverified++;
814
- s.lastAt = new Date().toISOString();
815
- this.store.write('gateway-stats.json', s);
816
- }
817
-
818
- // Read and authenticate the receipt a gateway wrote beside an inbox item.
819
- // Returns the receipt object only when its HMAC verifies against our secret;
820
- // null otherwise (no gateway, no receipt, a stranger's forged one, or a read
821
- // failure) — and null means "unverified", the pre-gateway behavior.
822
- async _readReceipt(itemUrl) {
823
- const secret = this.gatewaySecret();
824
- if (!secret) return null;
825
- try {
826
- const res = await this.remote.fetch(itemUrl + '.receipt.json', { headers: { accept: 'application/json' } });
827
- if (res.status >= 400) return null;
828
- const { readCapped } = await import('./safefetch.mjs');
829
- const receipt = JSON.parse(await readCapped(res, 64 * 1024));
830
- const { verifyReceipt } = await import('./httpsig.mjs');
831
- return verifyReceipt(receipt, secret) ? receipt : null;
832
- } catch { return null; }
833
- }
834
-
835
- async handle(activity, receipt = null) { // eslint-disable-line no-unused-vars
836
- const actor = typeof activity.actor === 'string' ? activity.actor : activity.actor?.id;
837
- if (!actor) return 'no actor';
838
- // An actor is a URL that can be dereferenced. Most arms here go on to fetch
839
- // it, and safefetch refuses a bad scheme there — but Like and Announce on
840
- // one of our own notes record a notification without dereferencing
841
- // anything, so `javascript:` and `data:` reached the client as an account
842
- // url. The store already guards avatars this way (safeUrl); actors were
843
- // simply never put through it.
844
- if (!httpUrl(actor)) return `actor is not an http(s) URL (${actor})`;
845
- if (this.store.isBlocked(actor)) return `blocked sender (${actor})`;
846
-
847
- // FEP-1b12 moderation from a LISTED moderator. A delivery proves nothing
848
- // about its sender, which is why these are QUEUED for the operator rather
849
- // than run on arrival — the queue is where a claimed moderator's word
850
- // waits for the one person who can vouch for it. Everything else about
851
- // the activity falls through to the ordinary arms.
852
- if (this.config.kind === 'group'
853
- && (this.config.moderators || []).includes(actor)
854
- && this.isModerationAsk(activity)) {
855
- return this.queueModeration(activity, actor);
856
- }
857
-
858
- // A gateway receipt is trusted only in `trust` mode — in `shadow` it is
859
- // measured but never acted on, which is what makes the shadow phase safe.
860
- const trusted = !!receipt?.verified && this.store.getConfig()?.gateway?.mode === 'trust';
861
-
862
- switch (activity.type) {
863
- case 'Follow': return this.onFollow(activity, actor, { trusted });
864
- case 'Undo': return this.onUndo(activity, actor, { trusted });
865
- case 'Create': return this.onCreate(activity, actor);
866
- case 'Accept': return this.onAccept(activity, actor);
867
- case 'Like': case 'Announce': {
868
- // FEP-1b12: a group Announces the member's whole Create, not the note.
869
- // Without unwrapping we try to ingest a Create as if it were a Note and
870
- // dead-letter every post a group ever carries — including our own.
871
- const wrapped = activity.object;
872
- // FEP-1b12: a group announces its moderation too. The one act a
873
- // follower can honor without trusting anyone new is a Delete of a
874
- // post that same group carried to us — the carrier unsaying its carry.
875
- if (activity.type === 'Announce' && wrapped && typeof wrapped === 'object'
876
- && wrapped.type === 'Delete') {
877
- return this.onAnnouncedDelete(actor, wrapped);
878
- }
879
- const inner = (wrapped && typeof wrapped === 'object'
880
- && (wrapped.type === 'Create' || wrapped.type === 'Update')) ? wrapped.object : wrapped;
881
- const objectId = typeof inner === 'string' ? inner : inner?.id;
882
- this.log(`${activity.type} from ${actor} on ${objectId}`);
883
- if (objectId && objectId.startsWith(this.urls.notes)) {
884
- // Nothing vouches for this actor: a Like carries no signature and,
885
- // unlike a Create, has no object at the sender's origin to re-read.
886
- // `known()` is answered from local state and costs nothing — a
887
- // stranger's favourite is still recorded, it is just the first thing
888
- // the cap evicts, so a flood cannot push out real history.
889
- this.store.addNotification({
890
- type: activity.type === 'Like' ? 'favourite' : 'reblog', actor, noteId: objectId,
891
- ...(this.known(actor) ? {} : { unverified: true }),
892
- });
893
- return;
894
- }
895
- if (activity.type === 'Announce') return this.onAnnounce(activity, actor, objectId);
896
- return;
897
- }
898
- case 'Delete': return this.onDelete(activity, actor);
899
- case 'Update': return this.onUpdate(activity, actor);
900
- case 'Reject': return this.onReject(activity, actor);
901
- case 'Move': return this.onMove(activity, actor);
902
- case 'Add': case 'Remove': return this.onAddRemove(activity, actor);
903
- default: this.log(`ignored ${activity.type} from ${actor}`);
904
- }
905
- }
906
-
907
- // Which inbound activities count as a moderator's ask: a ban, an unban, a
908
- // post removal, or a roster change naming OUR moderators collection. A
909
- // moderator's ordinary traffic (their posts, likes, follows) is not
910
- // moderation and takes the normal arms.
911
- isModerationAsk(activity) {
912
- if (activity.type === 'Block') return true;
913
- if (activity.type === 'Undo') {
914
- return typeof activity.object === 'object' && activity.object?.type === 'Block';
915
- }
916
- if (activity.type === 'Delete') {
917
- const id = typeof activity.object === 'string' ? activity.object : activity.object?.id;
918
- const s = id && this.store.getStatuses().find(x => x.noteId === id);
919
- // Only a post the group holds and did not author — removing those is
920
- // moderation; everything else is the author's own Delete.
921
- return !!s && s.kind !== 'post';
922
- }
923
- if (activity.type === 'Add' || activity.type === 'Remove') {
924
- const target = typeof activity.target === 'string' ? activity.target : activity.target?.id;
925
- return target === this.urls.moderators;
926
- }
927
- return false;
928
- }
929
-
930
- // Held, not run: one entry per distinct ask, capped, waiting for the
931
- // operator to apply or dismiss it (social.applyModeration).
932
- queueModeration(activity, actor) {
933
- const q = this.store.read('modqueue.json', []);
934
- const objectId = typeof activity.object === 'string' ? activity.object : activity.object?.id;
935
- const key = [activity.type, actor, objectId || JSON.stringify(activity.object || null)].join(' ');
936
- if (q.some(e => e.key === key)) return;
937
- q.unshift({
938
- key, id: (this.serial++).toString(36) + '-' + q.length,
939
- type: activity.type, moderator: actor, activity, at: new Date().toISOString(),
940
- });
941
- this.store.write('modqueue.json', q.slice(0, 200));
942
- this.log(`moderation queued from ${actor}: ${activity.type} ${objectId || ''}`);
943
- }
944
-
945
- // §7.6 Add / §7.9 Remove. The side effect would be to add or remove the object
946
- // to/from the collection named in `target` — but only a collection we own AND
947
- // that the sender is authorised to modify. No remote is granted write to our
948
- // collections (membership is Follow/Undo, pins are ours to set), so there is
949
- // nothing an inbound Add or Remove may change here. It is a valid activity,
950
- // not garbage: acknowledge it, make no change, and never dead-letter it.
951
- onAddRemove(activity, actor) {
952
- const target = typeof activity.target === 'string' ? activity.target : activity.target?.id;
953
- const ours = target && [this.urls.followers, this.urls.following, this.urls.featured]
954
- .filter(Boolean).includes(target);
955
- this.log(ours
956
- ? `${activity.type} from ${actor} targets our ${target} — no remote may modify it; acknowledged`
957
- : `${activity.type} from ${actor} targets ${target || 'no collection of ours'}; nothing here to change`);
958
- return; // accepted, no side effect
959
- }
960
-
961
- async onFollow(activity, actor, { trusted = false } = {}) {
962
- const doc = await this.fetchAP(actor); // origin must vouch for the actor
963
- if (!doc) return `actor fetch failed (${actor})`;
964
- if (doc.id !== actor) return `actor id mismatch (${actor} vs ${doc.id})`;
965
- if (!doc.inbox) return `actor has no inbox (${actor})`;
966
- const contacts = this.store.getContacts();
967
- const existing = contacts.followers.find(f => f.actor === actor);
968
- // NOTHING binds a delivered Follow to the actor it names. LDN bodies carry
969
- // no signature, and unlike Create, Delete and Update there is no object at
970
- // the origin to re-fetch and compare — dereferencing the actor proves only
971
- // that the actor EXISTS. So anyone at all could Append a Follow naming
972
- // anyone at all, and we would sign an Accept, deliver it to that person,
973
- // and send them everything published from then on.
974
- //
975
- // Until deliveries terminate somewhere their signature survives, a follow
976
- // we cannot verify is a REQUEST, waiting in the same queue a gated group
977
- // uses. The requester's client shows "Requested", which is the ordinary
978
- // locked-account state that manuallyApprovesFollowers tells it to expect.
979
- // `autoAcceptFollows: true` in config restores the old behaviour.
980
- // A GROUP is left alone: `approveJoins: false` is its operator saying, in
981
- // as many words, that anyone may join, and mute/eject are the remedy there.
982
- // A person has no such setting, so this is their default.
983
- //
984
- // A gateway-verified Follow (trust mode) is no longer unverifiable — the
985
- // door proved the sender — so it does not need the OK that unverifiability
986
- // alone demanded. An explicit `approveJoins` still holds: verified or not,
987
- // the operator asked to see joins.
988
- const unverifiedNeedsOk = this.config.kind !== 'group' && !this.config.autoAcceptFollows && !trusted;
989
- const mustApprove = this.config.approveJoins || unverifiedNeedsOk;
990
- if (mustApprove && !existing) {
991
- const reqs = this.store.getRequests();
992
- if (!reqs.some(r => r.actor === actor)) {
993
- reqs.unshift({
994
- actor, inbox: doc.inbox, sharedInbox: doc.endpoints?.sharedInbox,
995
- activity, at: new Date().toISOString(),
996
- });
997
- this.store.setRequests(reqs.slice(0, 500));
998
- this.store.addNotification({ type: 'follow-request', actor });
999
- await this.republish({ pending: true });
1000
- }
1001
- this.log(`join requested: ${actor}`);
1002
- return;
1003
- }
1004
- if (existing) {
1005
- // Deliberately NOT updating followId. An inbound Follow is unverifiable —
1006
- // that is what the queue above exists for — so letting one rewrite the id
1007
- // of a follower we already hold hands an attacker the exact value onUndo
1008
- // matches on: POST a Follow naming any follower in the published
1009
- // collection, then POST an Undo naming the id you just chose, and they are
1010
- // gone permanently. A genuine refollow needs nothing from us but the
1011
- // Accept below, which is idempotent.
1012
- } else {
1013
- // A Bluesky member who bridges later arrives here as a second, different
1014
- // actor: the bridge follows on their behalf from bsky.brid.gy/ap/<did>,
1015
- // while the native join is recorded under bsky.app/profile/<did>. Left
1016
- // alone that is one person listed twice, carried twice, and ejectable
1017
- // only half at a time. The bridged record supersedes the native one —
1018
- // it reaches the fediverse side, which the native one never could.
1019
- const bridgedDid = /^https:\/\/bsky\.brid\.gy\/ap\/(did:[^/]+)$/.exec(actor)?.[1];
1020
- if (bridgedDid) {
1021
- const before = contacts.followers.length;
1022
- contacts.followers = contacts.followers.filter(f => f.bsky?.did !== bridgedDid);
1023
- if (contacts.followers.length < before) {
1024
- this.log(`bluesky member ${bridgedDid} is bridged now — the native record gives way to it`);
1025
- }
1026
- }
1027
- contacts.followers.push({
1028
- actor, inbox: doc.inbox, sharedInbox: doc.endpoints?.sharedInbox, followId: activity.id,
1029
- ...(bridgedDid ? { bsky: { did: bridgedDid, bridged: true } } : {}),
1030
- });
1031
- this.store.setContacts(contacts);
1032
- this.store.addNotification({ type: 'follow', actor });
1033
- await this.republish({ followers: true });
1034
- this.log(`new follower: ${actor}`);
1035
- }
1036
- const { acceptActivity } = await import('./wire.mjs');
1037
- await this.deliverer.deliver(doc.inbox,
1038
- acceptActivity({ urls: this.urls, followActivity: activity, serial: this.serial++ }));
1039
- this.log(`Accept sent → ${doc.inbox}`);
1040
- }
1041
-
1042
- async onUndo(activity, actor, { trusted = false } = {}) {
1043
- // AS2 allows `object` to be a bare IRI, and that IRI is exactly the Follow
1044
- // id we stored. Reading `.type` off a string gives undefined, so the whole
1045
- // Undo was dropped — silently, since handle() reads that as handled, so no
1046
- // dead letter was kept and the item was DELETEd. The follower stayed, we
1047
- // kept delivering to them, and their server had recorded the unfollow as
1048
- // done and would never resend. Only a TYPED non-Follow is not ours.
1049
- if (typeof activity.object === 'object' && activity.object?.type
1050
- && activity.object.type !== 'Follow') return;
1051
- // And it must NAME something. Widening the type test to admit a bare IRI
1052
- // also admitted `object: undefined`, `null` and `{}` — which land on the
1053
- // no-followId carve-out below and evict, which is the very hole the
1054
- // followId check was added to close. An Undo that identifies nothing is
1055
- // not an Undo of ours.
1056
- const named = typeof activity.object === 'string' ? activity.object : activity.object?.id;
1057
- // A gateway-verified Undo need not name a stored id — the door proved the
1058
- // sender, so an Undo{Follow} that names us as its object is enough. An
1059
- // unverified one must still identify something (the eviction-hole guard).
1060
- if (!named && !trusted) return;
1061
- // Deliveries arrive unordered: an Undo may land AFTER the refollow it
1062
- // predates. It names the Follow id it revokes — only honor it when it
1063
- // matches the follow we currently hold for that actor.
1064
- const undoneId = typeof activity.object === 'string' ? activity.object : activity.object?.id;
1065
- const contacts = this.store.getContacts();
1066
- const rec = contacts.followers.find(f => f.actor === actor);
1067
- // Withdrawing a request that was never answered: drop it, or it sits in the
1068
- // operator's queue forever asking about someone who left.
1069
- if (!rec) {
1070
- const reqs = this.store.getRequests();
1071
- if (reqs.some(r => r.actor === actor)) {
1072
- this.store.setRequests(reqs.filter(r => r.actor !== actor));
1073
- await this.republish({ pending: true });
1074
- this.log(`join request withdrawn: ${actor}`);
1075
- }
1076
- return;
1077
- }
1078
- // An Undo must NAME the Follow it revokes, and name the one we hold.
1079
- //
1080
- // The follow id is the ONLY thing binding an Undo to the follower. LDN
1081
- // bodies carry no signature, and unlike every other inbound type this path
1082
- // dereferences nothing, so there is no origin to disagree. Matching works
1083
- // because the id was chosen by their server and delivered in a Follow we
1084
- // accepted: we publish the followers collection, but never the ids.
1085
- //
1086
- // Which means a record with NO id cannot be matched at all — and the
1087
- // carve-out that used to let those through turned "we cannot tell" into
1088
- // "anyone may evict". reconcileFollowers writes exactly such records when a
1089
- // restored machine recovers its followers from the pod, so after a restore
1090
- // every follower could be removed by one unauthenticated POST, permanently:
1091
- // dropFollower leaves a mark and the next reconcile will not bring them
1092
- // back, their server recorded no unfollow so it never resends, and neither
1093
- // side has anything to notice.
1094
- //
1095
- // Unmatchable is refused now. The cost is a follower who really did leave
1096
- // staying on the list until the operator ejects them, which is the right way
1097
- // round: `eject` is one command, and the alternative was silent, permanent,
1098
- // and available to anyone.
1099
- // A gateway-verified Undo carries the sender's proof, so it is honored on
1100
- // its own — the followId match below exists only because an UNVERIFIED Undo
1101
- // is otherwise unbindable. A verified one needs no such crutch.
1102
- if (trusted) {
1103
- dropFollower(contacts, actor, 'undo-follow');
1104
- this.store.setContacts(contacts);
1105
- await this.republish({ followers: true });
1106
- this.log(`unfollowed by ${actor} (gateway-verified)`);
1107
- return;
1108
- }
1109
- if (!rec.followId) {
1110
- this.log(`Undo from ${actor} cannot be matched — this follower was `
1111
- + `${rec.recovered ? 'recovered from the pod' : 'recorded before follow ids were kept'}, `
1112
- + `so its follow id is unknown. Ignored; \`fedipod eject ${actor}\` if they did leave.`);
1113
- return;
1114
- }
1115
- if (undoneId !== rec.followId) {
1116
- this.log(`Undo from ${actor} does not name the follow we hold `
1117
- + `(revokes ${undoneId || 'nothing'}, current is ${rec.followId}) — ignored`);
1118
- return;
1119
- }
1120
- dropFollower(contacts, actor, 'undo-follow');
1121
- this.store.setContacts(contacts);
1122
- await this.republish({ followers: true });
1123
- this.log(`unfollowed by ${actor}`);
1124
- }
1125
-
1126
- // Does this activity/note concern us at all? Either it comes from someone
1127
- // we follow, or it names us (to/cc, mention tag) or replies to one of our
1128
- // notes. Anything else is a stranger blasting inboxes — refuse it before
1129
- // spending a dereference on it.
1130
- concernsUs(doc, actor) {
1131
- if (this.store.getContacts().following.some(f => f.actor === actor && f.accepted)) return true;
1132
- const audience = []
1133
- .concat(doc?.to || [], doc?.cc || [], doc?.bto || [], doc?.bcc || [], doc?.audience || [])
1134
- .map(v => (typeof v === 'string' ? v : v?.id)).filter(Boolean);
1135
- if (audience.includes(this.urls.actor) || audience.includes(this.urls.followers)) return true;
1136
- const tagged = [].concat(doc?.tag || [])
1137
- .some(t => t?.type === 'Mention' && (t.href === this.urls.actor || t.name?.includes(this.urls.actor)));
1138
- if (tagged) return true;
1139
- const inReplyTo = typeof doc?.inReplyTo === 'string' ? doc.inReplyTo : doc?.inReplyTo?.id;
1140
- if (!inReplyTo) return false;
1141
- if (String(inReplyTo).startsWith(this.urls.notes)) return true;
1142
- // A group also owns the conversation under anything it carried. Without
1143
- // this, a reply that lost the group's mention on its way round the
1144
- // fediverse is refused, and the thread breaks for everyone who was only
1145
- // ever following the group.
1146
- return this.config.kind === 'group'
1147
- && this.store.getStatuses().some(s => s.noteId === String(inReplyTo));
1148
- }
1149
-
1150
- // §7.1.2 Forwarding from the inbox. A reply into one of our threads reaches
1151
- // only the servers the replier's server chose to deliver to — never our
1152
- // followers on servers it has never heard of. As the actor those followers
1153
- // follow, WE close that gap: an activity addressed to our followers collection
1154
- // that names one of our objects is re-delivered to our followers' inboxes.
1155
- //
1156
- // Only what was addressed to the followers COLLECTION is carried — bto/bcc are
1157
- // never read here, so a direct message (addressed to a person) never qualifies
1158
- // and is never rebroadcast. And this runs only after handle() accepted the
1159
- // activity, so anything blocked or muted was already refused upstream and is
1160
- // never forwarded.
1161
- async _maybeForward(activity) {
1162
- if (!activity || typeof activity !== 'object') return;
1163
- if (!FORWARDABLE.has(activity.type)) return; // see FORWARDABLE
1164
- try {
1165
- const audience = []
1166
- .concat(activity.to || [], activity.cc || [], activity.audience || [])
1167
- .map(v => (typeof v === 'string' ? v : v?.id)).filter(Boolean);
1168
- if (!audience.includes(this.urls.followers)) return; // not for our followers
1169
- if (!this._referencesOurObject(activity)) return; // not into a thread of ours
1170
- const actor = typeof activity.actor === 'string' ? activity.actor : activity.actor?.id;
1171
- if (actor === this.urls.actor) return; // our own; nothing to forward
1172
- const id = typeof activity.id === 'string' ? activity.id : null;
1173
- if (!id) return;
1174
- const forwarded = this.store.read('forwarded.json', []);
1175
- if (forwarded.includes(id)) return; // already done
1176
-
1177
- const inboxes = [...new Set(this.store.getContacts().followers
1178
- .filter(f => !f.bsky) // Bluesky members are not AP inboxes
1179
- .map(f => f.sharedInbox || f.inbox)
1180
- .filter(Boolean))];
1181
- if (!inboxes.length) return;
1182
- await this.deliverer.deliverToAll(inboxes, activity);
1183
- this.store.write('forwarded.json', [...forwarded, id].slice(-MAX_FORWARDED));
1184
- this.log(`forwarded ${activity.type} ${id} to ${inboxes.length} follower inbox(es)`);
1185
- } catch (e) {
1186
- this.log(`inbox forwarding: ${e.message}`); // never stalls the drain
1187
- }
1188
- }
1189
-
1190
- // The "objects owned by the server" half of §7.1.2: does the activity reply
1191
- // to, like, boost or otherwise name one of our own objects?
1192
- _referencesOurObject(activity) {
1193
- const refs = [];
1194
- const add = (v) => { const id = typeof v === 'string' ? v : v?.id; if (id) refs.push(String(id)); };
1195
- const obj = activity.object;
1196
- if (obj && typeof obj === 'object') add(obj.inReplyTo); // a reply's parent
1197
- add(activity.inReplyTo);
1198
- add(activity.object); // a Like/Announce of our note
1199
- add(activity.target);
1200
- if (refs.some(r => r.startsWith(this.urls.notes))) return true;
1201
- return this.config.kind === 'group'
1202
- && refs.some(r => this.store.getStatuses().some(s => s.noteId === r));
1203
- }
1204
-
1205
- async onCreate(activity, actor) {
1206
- const objectId = typeof activity.object === 'string' ? activity.object : activity.object?.id;
1207
- if (!objectId) return 'Create without object id';
1208
- if (this.store.isBlocked(objectId)) return `blocked domain (${objectId})`;
1209
- if (!this.sameOrigin(objectId, actor)) return `object/actor origin mismatch (${objectId})`;
1210
- // The delivered copy is untrusted for CONTENT, but its addressing is
1211
- // enough to decide whether to bother fetching the origin's copy.
1212
- const envelope = typeof activity.object === 'object' ? { ...activity, ...activity.object } : activity;
1213
- if (!this.concernsUs(envelope, actor)) return `not addressed to us (${objectId})`;
1214
- // The check onAnnounce has had all along. A re-delivered Create — a remote
1215
- // retry, a group fan-out, or our own sweep seeing an item whose DELETE was
1216
- // refused — cost a fresh signed GET to the origin and rewrote the private
1217
- // RDF note every time, because addStatus only dedupes AFTER the deref.
1218
- // Gated around the INGEST alone: a group must still reach amplify below,
1219
- // which is separately idempotent on announcedAt.
1220
- // Only a status that came from an INGEST counts as already done. TagFeed
1221
- // writes a bare `kind:'tag'` row straight into the index — no pod RDF note,
1222
- // no mention notification, no replies-collection entry — so treating that
1223
- // as ingested loses all three when the same note is then delivered to us.
1224
- const ingested = this.store.getStatuses()
1225
- .some(x => x.noteId === objectId && (x.kind === 'timeline' || x.kind === 'mention'));
1226
- if (!ingested) {
1227
- const rejected = await this.ingestNote(objectId, actor);
1228
- if (rejected) return rejected;
1229
- }
1230
- // A group carries its members' posts onward. Only reached from Create, so an
1231
- // inbound Announce is never re-announced. The activity is passed through
1232
- // untouched — FEP-1b12 wants the original wrapped, not a summary of it.
1233
- if (this.config.kind === 'group') await this.amplify(objectId, { activity });
1234
- }
1235
-
1236
- // Anyone can Append to a public inbox, so arriving is not the same as being
1237
- // carried to every follower. Membership is the gate: you cannot post to a
1238
- // group you have not joined, and declining to carry a member is the only
1239
- // moderation a group can actually enforce.
1240
- async amplify(noteId, { approved = false, activity = null } = {}) {
1241
- const s = this.store.getStatuses().find(x => x.noteId === noteId);
1242
- if (!s) return;
1243
- if (s.announcedAt) return; // a re-delivered Create announces once
1244
- // A DM to the group, or a followers-only post it happened to receive, was
1245
- // addressed to less than the world — carrying it would widen the author's
1246
- // audience for them. A group only ever amplifies public posts.
1247
- if (s.direct || s.nonPublic) {
1248
- this.log(`not amplified — ${noteId} was not addressed publicly, and a group never widens a post's audience`);
1249
- return;
1250
- }
1251
- const contacts = this.store.getContacts();
1252
- if (!contacts.followers.some(f => f.actor === s.actor)) {
1253
- this.log(`not amplified — ${s.actor} is not a member`);
1254
- return;
1255
- }
1256
- if (this.store.getMuted().actors.includes(s.actor)) {
1257
- this.log(`not amplified — ${s.actor} is muted`);
1258
- return;
1259
- }
1260
- // A reviewed group carries nothing until its operator says so.
1261
- if (this.config.review && !approved) {
1262
- const pending = this.store.getPending();
1263
- if (!pending.some(p => p.noteId === noteId)) {
1264
- // Full means refuse the new one, not evict the oldest. `slice(0, 500)`
1265
- // dropped from the tail, so one member posting 500 notes silently
1266
- // discarded everything the operator was still deciding about — the
1267
- // posts were never carried, never refused, and left no record that they
1268
- // had ever arrived. Becoming a member costs one Follow when joins are
1269
- // unmoderated, which is the default.
1270
- //
1271
- // Not carrying it is what a reviewed group does with anything it has
1272
- // not approved, so refusing is the same outcome the queue was for.
1273
- if (pending.length >= MAX_PENDING_REVIEW) {
1274
- this.log(`review queue is full (${MAX_PENDING_REVIEW}) — ${noteId} not held. `
1275
- + 'Approve or decline what is waiting and it will be carried on redelivery.');
1276
- return;
1277
- }
1278
- // The activity rides along: approving later still has to wrap the one
1279
- // the member actually sent, not a reconstruction of it.
1280
- pending.unshift({ noteId, actor: s.actor, activity, at: new Date().toISOString() });
1281
- this.store.setPending(pending);
1282
- }
1283
- this.log(`held for review: ${noteId}`);
1284
- return;
1285
- }
1286
- // A member's Bluesky post: the carry is a native repost by the group's
1287
- // account. It reaches AP followers only through the author's own bridge —
1288
- // the group never fabricates an AP object for someone else's words.
1289
- if (s.kind === 'bsky') {
1290
- if (!this.bskyGroup) { this.log(`not amplified — ${noteId} is a bluesky post and no account is connected`); return; }
1291
- return this.bskyGroup.carry(s);
1292
- }
1293
- const held = this.store.getPending().find(p => p.noteId === noteId);
1294
- const inboxes = this.announceTargets(s.actor);
1295
- const { announceActivity } = await import('./wire.mjs');
1296
- // Wrap the member's own activity when we have it; a bare note URL is the
1297
- // fallback, and renders as a plain boost rather than a group carry. The
1298
- // group names itself as the audience (FEP-1b12).
1299
- const act = announceActivity({
1300
- urls: this.urls, object: activity || held?.activity || noteId, serial: this.serial++,
1301
- audience: this.urls.actor,
1302
- });
1303
- await this.deliverer.deliverToAll(inboxes, act);
1304
- // Marked carried before recorded: a failed outbox write costs one missing
1305
- // entry, a failed status write would carry the same post twice.
1306
- this.store.updateStatus(noteId, { announcedAt: new Date().toISOString(), announceActivity: act });
1307
- await this.publisher.recordOutbox(act);
1308
- this.store.setPending(this.store.getPending().filter(p => p.noteId !== noteId));
1309
- this.log(`amplified ${noteId} → ${inboxes.length} inbox(es)`);
1310
- // The same carry, shown natively to the group's Bluesky followers.
1311
- await this.bskyGroup?.mirrorCarry(s)
1312
- .catch(e => this.log(`bluesky mirror of the carry failed: ${e.message}`));
1313
- }
1314
-
1315
- // Is this actor in a group we are in? Each followed Group's membership is a
1316
- // public collection, read at most once a day and cached — a membership list
1317
- // is slow-moving, and this runs on arriving mail.
1318
- async isCoMember(actor) {
1319
- if (this.config.kind === 'group') return false; // a group has members, not peers
1320
- const groups = this.store.getContacts().following
1321
- .filter(f => f.accepted && this.store.getActors()[f.actor]?.type === 'Group')
1322
- .map(f => f.actor);
1323
- if (!groups.length) return false;
1324
- const cache = this.store.read('comembers.json', {});
1325
- const fresh = Date.now() - CO_MEMBER_TTL_MS;
1326
- let changed = false;
1327
- for (const g of groups) {
1328
- const held = cache[g];
1329
- if (held && Date.parse(held.at || 0) > fresh) continue;
1330
- const doc = await this.fetchAP(g).catch(() => null);
1331
- const list = doc?.followers ? await this.collectionMembers(doc.followers) : null;
1332
- // A list we could not read keeps whatever we had: losing it would demote
1333
- // every co-member to a stranger for a day because one fetch failed.
1334
- if (!list) continue;
1335
- cache[g] = { at: new Date().toISOString(), members: list };
1336
- changed = true;
1337
- }
1338
- if (changed) this.store.write('comembers.json', cache);
1339
- return groups.some(g => cache[g]?.members?.includes(actor));
1340
- }
1341
-
1342
- // The actor ids in a (possibly paged) public collection, capped.
1343
- async collectionMembers(url) {
1344
- const out = [];
1345
- let next = url;
1346
- for (let page = 0; next && page < 10 && out.length < CO_MEMBER_MAX; page++) {
1347
- const doc = await this.fetchAP(next).catch(() => null);
1348
- if (!doc) return out.length ? out : null;
1349
- for (const item of doc.orderedItems || doc.items || []) {
1350
- if (typeof item === 'string') out.push(item);
1351
- }
1352
- next = doc.first && page === 0 ? doc.first : doc.next;
1353
- if (typeof next === 'object') next = next?.id;
1354
- }
1355
- return out;
1356
- }
1357
-
1358
- // Who an Announce for `author` goes to. Shared with the retract path: an Undo
1359
- // that reached a different set than the Announce did would leave the post
1360
- // standing for whoever the two sets disagreed about.
1361
- // The author's own target is dropped only when it serves nobody else — a
1362
- // shared inbox carries the whole server's members.
1363
- announceTargets(author) {
1364
- const byTarget = new Map();
1365
- for (const f of this.store.getContacts().followers) {
1366
- const t = f.sharedInbox || f.inbox;
1367
- if (!t) continue;
1368
- if (!byTarget.has(t)) byTarget.set(t, new Set());
1369
- byTarget.get(t).add(f.actor);
1370
- }
1371
- return [...byTarget]
1372
- .filter(([, who]) => !(who.size === 1 && who.has(author)))
1373
- .map(([t]) => t);
1374
- }
1375
-
1376
- // A boost: ingest the boosted note when the booster is someone we follow —
1377
- // that's what following means, their boosts widen the timeline. Anything
1378
- // else is unsolicited and only logged.
1379
- // A group we follow announces a Delete: the carrier moderating away a post
1380
- // it carried. Honored only within what the carry itself established — the
1381
- // announcer is a group we follow AND the post reached us via that same
1382
- // group — so no new party is trusted and nothing is dereferenced. Our own
1383
- // posts are never removed by anyone's moderation.
1384
- async onAnnouncedDelete(actor, del) {
1385
- const followed = this.store.getContacts().following.some(f => f.actor === actor && f.accepted);
1386
- if (!followed) { this.log(`announced Delete from unfollowed ${actor} — ignored`); return; }
1387
- const targetId = typeof del.object === 'string' ? del.object : del.object?.id;
1388
- if (!targetId) return 'announced Delete without an object';
1389
- const s = this.store.getStatuses().find(x => x.noteId === targetId);
1390
- if (!s || s.kind === 'post' || s.via !== actor) return;
1391
- await this.forget(s);
1392
- this.log(`moderated away by ${actor}: ${targetId}`);
1393
- }
1394
-
1395
- async onAnnounce(activity, actor, objectId) {
1396
- if (!objectId) return 'Announce without object id';
1397
- const followed = this.store.getContacts().following.some(f => f.actor === actor && f.accepted);
1398
- if (!followed) { this.log(`Announce from unfollowed ${actor} — ignored`); return; }
1399
- if (this.store.isBlocked(objectId)) return `blocked domain (${objectId})`;
1400
- const existing = this.store.getStatuses().find(s => s.noteId === objectId);
1401
- if (existing) {
1402
- // Known, but possibly as a lesser kind — a stranger's mention, a tag or
1403
- // search mirror — none of which the home timeline shows. A carry from
1404
- // someone we follow is exactly what promotes it there.
1405
- if (!['timeline', 'post'].includes(existing.kind)) {
1406
- this.store.updateStatus(objectId, { kind: 'timeline', via: actor });
1407
- this.log(`promoted to timeline (carried by ${actor}): ${objectId}`);
1408
- }
1409
- return;
1410
- }
1411
- return this.ingestNote(objectId, actor, { via: actor });
1412
- }
1413
-
1414
- // Shared tail of Create/Announce: deref the note at its origin (never trust
1415
- // the delivered copy), mirror it into pod RDF + statuses, notify on replies
1416
- // to our own notes. Returns a rejection reason string, or undefined.
1417
- async ingestNote(objectId, actor, { via } = {}) {
1418
- const note = await this.fetchAP(objectId);
1419
- if (!note) return `object fetch failed (${objectId})`;
1420
- if (note.id !== objectId || !isContentType(note.type)) return `object not verifiable content (${objectId}, ${note.type})`;
1421
- const { attachmentsOf, titledContent } = await import('./wire.mjs');
1422
- const attachments = attachmentsOf(note);
1423
- const content = titledContent(note); // hostile markup never reaches pod or client
1424
- // The delivering actor was checked on arrival; the author is only known once
1425
- // the note is dereferenced. authorOf refuses an author the note's own origin
1426
- // does not vouch for — see its comment; this is where a forged attribution
1427
- // would otherwise become a timeline entry, a pod document, and for a group a
1428
- // signed Announce to every member.
1429
- const author = authorOf(note, actor);
1430
- if (!author) return `object names an author its origin does not vouch for (${objectId})`;
1431
- // This is the check that catches a blocked actor reaching us through
1432
- // somebody else's boost, or through a hashtag feed.
1433
- if (this.store.isBlocked(author)) return `blocked author (${author})`;
1434
-
1435
- // An answer to one of our polls is a number on a document, not a post. It
1436
- // arrives as an ordinary reply naming an option and carrying nothing else,
1437
- // so filing it as one would put a blank entry in the thread and ring the
1438
- // owner once per voter. Counted or refused — a second answer, an option we
1439
- // do not offer, a poll already shut — it stops here either way.
1440
- const asked = note.inReplyTo && this.store.getStatuses()
1441
- .find(x => x.noteId === String(note.inReplyTo) && x.kind === 'post' && x.poll);
1442
- if (asked && polls.isVoteShape(note)) {
1443
- const counted = await this.publisher.recordVote(asked.noteId, author, note.name)
1444
- .catch(e => { this.log(`vote on ${asked.noteId}: ${e.message}`); return false; });
1445
- this.log(counted
1446
- ? `vote counted (${note.name}): ${asked.noteId}`
1447
- : `vote not counted (${note.name}) from ${author}: ${asked.noteId}`);
1448
- return;
1449
- }
1450
-
1451
- // Anyone can Append to a public inbox, so arriving is not the same as
1452
- // belonging in the home timeline. Follow Mastodon's split: people you
1453
- // follow (and their boosts) are HOME; anyone else is a MENTION — kept,
1454
- // notified, readable in the Mentions view, but out of the timeline, and
1455
- // mirror-only so unsolicited content never accumulates in the pod.
1456
- // A group's people are its FOLLOWERS — it follows nobody. Reading the
1457
- // following list for one filed every member's post as a stranger's mention,
1458
- // so nothing reached the pod RDF and each post raised a notification.
1459
- const contacts = this.store.getContacts();
1460
- const known = this.config.kind === 'group'
1461
- ? contacts.followers.some(f => f.actor === author)
1462
- : contacts.following.some(f => f.actor === author && f.accepted);
1463
- // Someone in a group you are in is not a stranger: their reply belongs in
1464
- // the room, not in the drawer of unsolicited mail. Whose word this is on
1465
- // is the group's — its published membership — so the group's own door
1466
- // decides who gets in.
1467
- const followed = via || known || (!known && await this.isCoMember(author));
1468
- const kind = followed ? 'timeline' : 'mention';
1469
-
1470
- // `published` comes from a document at someone else's origin, and its first
1471
- // ten characters become the leading component of a storage path. A date is
1472
- // a date or it is not used: a value carrying `../` would otherwise be a
1473
- // remote party choosing where we write.
1474
- const day = String(note.published || '').slice(0, 10);
1475
- const slug = (/^\d{4}-\d{2}-\d{2}$/.test(day) ? day : new Date().toISOString().slice(0, 10)) + '-' +
1476
- (await import('node:crypto')).createHash('sha256').update(note.id).digest('hex').slice(0, 8);
1477
- if (kind === 'timeline') {
1478
- await this.local.writeNote('timeline', slug, {
1479
- noteId: note.id, actor: author, published: note.published, content,
1480
- inReplyTo: note.inReplyTo, attachments,
1481
- });
1482
- }
1483
- // Mastodon carries a thread's mentions into every reply, which is the only
1484
- // reason a reply ever reaches a group. Keep them so our composer can too.
1485
- const mentions = [].concat(note.tag || [])
1486
- .filter(t => t?.type === 'Mention' && t.href && t.name)
1487
- .map(t => ({ href: t.href, name: t.name }));
1488
- const emojis = emojisOf(note);
1489
- const poll = pollOf(note);
1490
- // Explicitly addressed, but to nobody public and to no followers
1491
- // collection: a direct message, which belongs to the conversations view
1492
- // rather than a timeline. A note with no addressing at all is NOT direct —
1493
- // some servers omit to/cc, and vanishing from home is the wrong reading.
1494
- const audience = [].concat(note.to || [], note.cc || []).map(String);
1495
- const direct = audience.length > 0
1496
- && !audience.includes(PUBLIC) && !audience.some(a => a.endsWith('/followers'));
1497
- // Addressed to less than the world: whatever else happens to it, a group
1498
- // must never widen its audience by carrying it.
1499
- const nonPublic = audience.length > 0 && !audience.includes(PUBLIC);
1500
- this.store.addStatus({
1501
- noteId: note.id, actor: author, content,
1502
- published: note.published, inReplyTo: note.inReplyTo, kind,
1503
- ...(direct ? { direct: true } : {}),
1504
- ...(nonPublic ? { nonPublic: true } : {}),
1505
- // The author's content warning, shown as one: plain text only.
1506
- ...(note.summary ? { spoiler: String(note.summary).replace(/<[^>]*>/g, '') } : {}),
1507
- ...(poll ? { poll } : {}),
1508
- ...(emojis.length ? { emojis } : {}),
1509
- ...(mentions.length ? { mentions } : {}),
1510
- ...(kind === 'timeline' ? { slug } : {}),
1511
- ...(attachments.length ? { attachments } : {}),
1512
- ...(via ? { via } : {}),
1513
- });
1514
- if (!followed || (note.inReplyTo && String(note.inReplyTo).startsWith(this.urls.notes))) {
1515
- this.store.addNotification({ type: 'mention', actor: author, noteId: note.id });
1516
- }
1517
- if (note.inReplyTo && String(note.inReplyTo).startsWith(this.urls.notes)) {
1518
- await this.addReply(String(note.inReplyTo), note.id)
1519
- .catch(e => this.log(`replies collection: ${e.message}`));
1520
- }
1521
- this.log(`${kind}: ${note.id}${via ? ` (boosted by ${via})` : ''}`);
1522
- }
1523
-
1524
- // Is this really gone at its origin? true / false / null when the origin
1525
- // could not be asked. Delivered bodies carry no signature, so this is how a
1526
- // Delete is verified — the same verify-by-dereference the rest of intake uses.
1527
- async isGone(url) {
1528
- let res;
1529
- try { res = await this.deliverer.signedFetch(url, { headers: { accept: ACCEPT_AP } }); }
1530
- catch { return null; }
1531
- if (res.status === 404 || res.status === 410) return true;
1532
- if (res.status < 400) {
1533
- // A Tombstone answers 200 and still means deleted.
1534
- try {
1535
- const { readCapped } = await import('./safefetch.mjs');
1536
- return JSON.parse(await readCapped(res))?.type === 'Tombstone';
1537
- } catch { return false; }
1538
- }
1539
- return null; // 401/403/5xx — no answer, not a denial
1540
- }
1541
-
1542
- // Mastodon sends these constantly; ignoring them left deleted posts standing
1543
- // for good. Two guards, because a forged Delete would otherwise erase anyone's
1544
- // content: it must come from the object's own origin, and the object must
1545
- // really be gone there. An origin we cannot reach is a retry, never a delete.
1546
- async onDelete(activity, actor) {
1547
- const objectId = typeof activity.object === 'string' ? activity.object : activity.object?.id;
1548
- if (!objectId) return 'Delete without object id';
1549
- if (!this.sameOrigin(objectId, actor)) return `Delete crosses origins (${objectId})`;
1550
- // `objectId === actor` is NOT evidence we care: it is true of EVERY account
1551
- // deletion, and Mastodon broadcasts those constantly. Taking it as known
1552
- // meant a signed dereference to a stranger's server for each one.
1553
- if (!this.known(objectId)) return; // nothing of ours to remove
1554
- const gone = await this.isGone(objectId);
1555
- if (gone === null) throw new Error(`cannot confirm ${objectId} is gone — will retry`);
1556
- if (!gone) return `Delete for something still published (${objectId})`;
1557
-
1558
- if (objectId === actor) { // the account itself
1559
- const contacts = this.store.getContacts();
1560
- dropFollower(contacts, actor, 'account-deleted');
1561
- contacts.following = contacts.following.filter(f => f.actor !== actor);
1562
- this.store.setContacts(contacts);
1563
- // One publish for the lot. Each forget() used to run its own
1564
- // unrecordOutbox, and each of those republished the outbox — so a group
1565
- // that had carried M of this actor's posts paid M full page sweeps for a
1566
- // single inbox item. The Undo deliveries stay per-Announce, because each
1567
- // Announce needs its own; only the pod write is collected.
1568
- const retracted = [];
1569
- for (const s of this.store.getStatuses().filter(s => s.actor === actor)) {
1570
- await this.forget(s, { collect: retracted });
1571
- }
1572
- if (retracted.length) {
1573
- const gone = new Set(retracted);
1574
- await this.publisher.unrecordOutbox(i => gone.has(i?.id));
1575
- }
1576
- // Both: an account deletion drops them from followers AND following.
1577
- await this.republish({ followers: true, following: true });
1578
- this.log(`account deleted upstream: ${actor}`);
1579
- return;
1580
- }
1581
- const s = this.store.getStatuses().find(x => x.noteId === objectId);
1582
- if (s) await this.forget(s);
1583
- this.log(`deleted upstream: ${objectId}`);
1584
- }
1585
-
1586
- // Drop a post we were holding. A group that carried it also unsays its own
1587
- // Announce — forwarding the author's Delete would be signed by us and not by
1588
- // them, which receivers are right to refuse.
1589
- // `collect` batches the outbox side: retract pushes the Announce id onto it
1590
- // instead of republishing, and the caller writes once for all of them.
1591
- async forget(s, { collect = null } = {}) {
1592
- if (s.announceActivity) {
1593
- await this.retract(s.noteId, { collect }).catch(e => this.log(`retract: ${e.message}`));
1594
- }
1595
- if (s.slug) {
1596
- // Said out loud rather than swallowed: the status row is about to go, so
1597
- // a failure here leaves the note document in the private tree with
1598
- // nothing indexing it, and no other record that it is there.
1599
- await this.local.delete(this.local.fedi + 'timeline/' + s.slug)
1600
- .catch(e => this.log(`forget ${s.noteId}: its RDF note could NOT be removed (${e.message})`));
1601
- }
1602
- this.store.removeStatus(s.noteId);
1603
- }
1604
-
1605
- // Undo an Announce this group made. Shared with the operator's `retract`.
1606
- async retract(noteId, { collect = null } = {}) {
1607
- const s = this.store.getStatuses().find(x => x.noteId === noteId);
1608
- if (!s) throw new Error('no such post');
1609
- // A Bluesky carry is a repost, and unsaying it is deleting the repost.
1610
- if (s.repostUri) {
1611
- if (!this.bskyGroup) throw new Error('no bluesky account connected');
1612
- return this.bskyGroup.retract(s);
1613
- }
1614
- if (!s.announceActivity) throw new Error('that post was never carried');
1615
- const { undoActivity } = await import('./wire.mjs');
1616
- const inboxes = this.announceTargets(s.actor);
1617
- await this.deliverer.deliverToAll(inboxes,
1618
- undoActivity({ urls: this.urls, activity: s.announceActivity, serial: this.serial++ }));
1619
- if (collect) collect.push(s.announceActivity.id);
1620
- else await this.publisher.unrecordOutbox(i => i?.id === s.announceActivity.id);
1621
- this.store.updateStatus(noteId, {
1622
- announcedAt: undefined, announceActivity: undefined, retractedAt: new Date().toISOString(),
1623
- });
1624
- return { ok: true, noteId, inboxes: inboxes.length };
1625
- }
1626
-
1627
- // An edited post, or a changed profile. Verified the only way we can: by
1628
- // refetching at the origin and believing that, not the delivered copy.
1629
- async onUpdate(activity, actor) {
1630
- const objectId = typeof activity.object === 'string' ? activity.object : activity.object?.id;
1631
- if (!objectId) return 'Update without object id';
1632
- if (!this.sameOrigin(objectId, actor)) return `Update crosses origins (${objectId})`;
1633
- if (objectId === actor) { // display name, avatar, bio
1634
- // The same guard onDelete has, for the same reason: the inbox is
1635
- // public-Append, so without it anyone can name any host and make us spend
1636
- // a signed GET on it — and because the failure below THROWS rather than
1637
- // returning a rejection, one planted item buys five of them, plus five
1638
- // pod reads and the head of the inbox held for five sweeps.
1639
- if (!this.known(actor)) return; // nothing of ours to update
1640
- const doc = await this.fetchAP(actor);
1641
- if (!doc) throw new Error(`cannot refetch ${actor} — will retry`);
1642
- this.store.cacheActor(actor, doc); // fetchAP caches Persons; Groups too
1643
- this.log(`profile updated: ${actor}`);
1644
- return;
1645
- }
1646
- const s = this.store.getStatuses().find(x => x.noteId === objectId);
1647
- if (!s) return; // not one we hold
1648
- const note = await this.fetchAP(objectId);
1649
- if (!note) throw new Error(`cannot refetch ${objectId} — will retry`);
1650
- if (note.id !== objectId || !isContentType(note.type)) return `object not verifiable content (${objectId}, ${note.type})`;
1651
- const { attachmentsOf, titledContent } = await import('./wire.mjs');
1652
- const content = titledContent(note);
1653
- const attachments = attachmentsOf(note);
1654
- const freshPoll = pollOf(note);
1655
- const freshEmojis = emojisOf(note);
1656
- this.store.updateStatus(objectId, {
1657
- content, ...(attachments.length ? { attachments } : {}),
1658
- emojis: freshEmojis.length ? freshEmojis : undefined,
1659
- // The edit's own stamp when the note carries one; tallies and the
1660
- // content warning follow the edit too. A poll refresh keeps our vote.
1661
- editedAt: note.updated || new Date().toISOString(),
1662
- spoiler: note.summary ? String(note.summary).replace(/<[^>]*>/g, '') : undefined,
1663
- ...(freshPoll ? {
1664
- poll: { ...freshPoll, voted: !!s.poll?.voted, ownVotes: s.poll?.ownVotes || [] },
1665
- } : {}),
1666
- });
1667
- if (s.slug) {
1668
- await this.local.writeNote('timeline', s.slug, {
1669
- noteId: note.id, actor: s.actor, published: note.published, content,
1670
- inReplyTo: note.inReplyTo, attachments,
1671
- }).catch(e => this.log(`rewrite ${s.slug}: ${e.message}`));
1672
- }
1673
- this.log(`edited upstream: ${objectId}`);
1674
- }
1675
-
1676
- // Read-modify-write, and the drain is serialized, so two replies in one sweep
1677
- // do not race. Nothing else writes this document.
1678
- // MAX_REPLIES_RECORDED caps the collection. It is a discovery aid — a client
1679
- // reading a thread — and the statuses index is what actually holds the
1680
- // replies, so dropping the oldest costs a hop, not a record.
1681
- async addReply(parentId, replyId) {
1682
- // The parent has to be a post we actually made. The only check used to be
1683
- // that the id started with our notes prefix, and `inReplyTo` is read off a
1684
- // document at the sender's own origin — so a stranger could name a note we
1685
- // never wrote, and we would CREATE a document on the pod at a URL of their
1686
- // choosing and then grow it, one whole re-PUT per reply, with no cap. Four
1687
- // pod requests each and bytes quadratic in the number of replies.
1688
- if (!this.store.getStatuses().some(s => s.noteId === parentId && s.kind === 'post')) {
1689
- this.log(`reply names ${parentId}, which is not a post of ours — not recorded`);
1690
- return;
1691
- }
1692
- const { repliesId, collection } = await import('./wire.mjs');
1693
- const url = repliesId(parentId);
1694
- // Deliberately NOT caught: a read we could not make is not an empty
1695
- // collection, and rewriting on top of one erases every reply already
1696
- // recorded. getJson returns null only for a genuine 404 — the document does
1697
- // not exist yet — and throws otherwise, which the caller logs and retries.
1698
- const cur = await this.remote.getJson(url);
1699
- const items = Array.isArray(cur?.items) ? cur.items : [];
1700
- if (items.includes(replyId)) return;
1701
- items.push(replyId);
1702
- await this.remote.putJson(url, collection(url, items.slice(-MAX_REPLIES_RECORDED)));
1703
- this.log(`reply recorded on ${parentId}`);
1704
- }
1705
-
1706
- // The other answer to a Follow, and it was dropped on the floor. Their server
1707
- // has recorded that we do not follow them; ours went on saying we did, and
1708
- // published it — so the two disagreed permanently, and a retry would never
1709
- // come because as far as they are concerned the question was answered.
1710
- async onReject(activity, actor) {
1711
- if (activity.object?.type && activity.object.type !== 'Follow') return;
1712
- const contacts = this.store.getContacts();
1713
- const rec = contacts.following.find(f => f.actor === actor);
1714
- if (!rec) return; // nothing of ours to undo
1715
- contacts.following = contacts.following.filter(f => f.actor !== actor);
1716
- this.store.setContacts(contacts);
1717
- await this.republish({ following: true, pending: true });
1718
- this.log(`follow rejected by ${actor}`);
1719
- }
1720
-
1721
- // Someone we follow has moved. Their server will stop delivering from the old
1722
- // actor, so without this we keep an entry that can never produce another post
1723
- // and never learn where they went. The new account is not followed
1724
- // automatically — that is a Follow only the owner should send — but it is
1725
- // recorded and raised, so it can be acted on.
1726
- async onMove(activity, actor) {
1727
- const target = typeof activity.target === 'string' ? activity.target : activity.target?.id;
1728
- if (!target) return 'Move without a target';
1729
- const contacts = this.store.getContacts();
1730
- const rec = contacts.following.find(f => f.actor === actor);
1731
- if (!rec) return; // not someone we follow
1732
- // Believed only if the actor we follow says so at its OWN origin: a Move is
1733
- // otherwise a redirect anyone could Append.
1734
- const doc = await this.fetchAP(actor);
1735
- if (!doc) throw new Error(`cannot confirm ${actor} moved — will retry`);
1736
- const movedTo = typeof doc.movedTo === 'string' ? doc.movedTo : doc.movedTo?.id;
1737
- if (movedTo !== target) return `Move not corroborated by ${actor} (says ${movedTo || 'nothing'})`;
1738
- rec.movedTo = target;
1739
- this.store.setContacts(contacts);
1740
- this.store.addNotification({ type: 'move', actor, target });
1741
- this.log(`${actor} moved to ${target} — follow the new account to keep seeing them`);
1742
- }
1743
-
1744
- async onAccept(activity, actor) {
1745
- const contacts = this.store.getContacts();
1746
- const rec = contacts.following.find(f => f.actor === actor);
1747
- // It has to answer the Follow we actually sent. followActor stores that
1748
- // activity for the later Undo, so the id is here to compare against; without
1749
- // the check any Accept from an actor we happen to follow flips the flag,
1750
- // including one answering a Follow we never made.
1751
- const named = typeof activity.object === 'string' ? activity.object : activity.object?.id;
1752
- const ours = rec?.followActivity?.id;
1753
- if (ours && named && named !== ours) {
1754
- this.log(`Accept from ${actor} answers ${named}, not the follow we sent — ignored`);
1755
- return;
1756
- }
1757
- if (rec && !rec.accepted) {
1758
- rec.accepted = true;
1759
- this.store.setContacts(contacts);
1760
- await this.republish({ following: true, pending: true });
1761
- this.log(`follow accepted by ${actor}`);
1762
- }
1763
- }
1764
- }