chirkle 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (229) hide show
  1. package/README.md +38 -196
  2. package/bin/release/darwin-amd64/chirkle-server +2 -2
  3. package/bin/release/darwin-arm64/chirkle-server +0 -0
  4. package/bin/release/linux-amd64/chirkle-server +0 -0
  5. package/bin/release/linux-arm64/chirkle-server +0 -0
  6. package/package.json +18 -5
  7. package/pb_hooks/lib/account.js +541 -6
  8. package/pb_hooks/lib/collections.js +9 -7
  9. package/pb_hooks/lib/dms.js +1 -1
  10. package/pb_hooks/lib/handles.js +24 -2
  11. package/pb_hooks/lib/http.js +2 -2
  12. package/pb_hooks/lib/inbox.js +7 -6
  13. package/pb_hooks/lib/invites.js +266 -0
  14. package/pb_hooks/lib/media.js +2 -2
  15. package/pb_hooks/lib/messages.js +11 -2
  16. package/pb_hooks/lib/moderation.js +1 -1
  17. package/pb_hooks/lib/retention.js +3 -0
  18. package/pb_hooks/lib/site.js +1 -1
  19. package/pb_hooks/lib/users.js +70 -11
  20. package/pb_hooks/main.pb.js +27 -1
  21. package/pb_hooks/telegram/api.js +64 -12
  22. package/pb_hooks/telegram/inbound.js +111 -15
  23. package/pb_hooks/telegram/links.js +12 -1
  24. package/pb_hooks/telegram/outbound.js +119 -39
  25. package/pb_hooks/telegram/worker.js +61 -16
  26. package/pb_migrations/1760000052_deleted_accounts.js +19 -0
  27. package/pb_migrations/1760000053_account_jobs.js +45 -0
  28. package/pb_migrations/1760000054_room_invites.js +39 -0
  29. package/pb_migrations/1760000055_invite_barred.js +16 -0
  30. package/pb_migrations/1760000056_telegram_fetch.js +21 -0
  31. package/pb_migrations/1760000057_reactions_seen.js +17 -0
  32. package/pb_migrations/1760000058_users_kind_public.js +20 -0
  33. package/pb_public/assets/access-KVSI7EFH.js +2 -0
  34. package/pb_public/assets/access-KVSI7EFH.js.br +0 -0
  35. package/pb_public/assets/access-KVSI7EFH.js.gz +0 -0
  36. package/pb_public/assets/access-KVSI7EFH.js.map +7 -0
  37. package/pb_public/assets/access-XGNXIUR5.css +2 -0
  38. package/pb_public/assets/access-XGNXIUR5.css.br +0 -0
  39. package/pb_public/assets/access-XGNXIUR5.css.gz +0 -0
  40. package/pb_public/assets/access-XGNXIUR5.css.map +7 -0
  41. package/pb_public/assets/account-EBCPOLWT.css +2 -0
  42. package/pb_public/assets/account-EBCPOLWT.css.br +0 -0
  43. package/pb_public/assets/account-EBCPOLWT.css.gz +0 -0
  44. package/pb_public/assets/account-EBCPOLWT.css.map +7 -0
  45. package/pb_public/assets/account-api-J6A6IYVX.js +2 -0
  46. package/pb_public/assets/account-api-J6A6IYVX.js.br +0 -0
  47. package/pb_public/assets/account-api-J6A6IYVX.js.gz +0 -0
  48. package/pb_public/assets/account-api-J6A6IYVX.js.map +7 -0
  49. package/pb_public/assets/app-5JOOV6JX.js +3 -0
  50. package/pb_public/assets/app-5JOOV6JX.js.br +0 -0
  51. package/pb_public/assets/app-5JOOV6JX.js.gz +0 -0
  52. package/pb_public/assets/app-5JOOV6JX.js.map +7 -0
  53. package/pb_public/assets/app-7OMYYLCI.css +2 -0
  54. package/pb_public/assets/app-7OMYYLCI.css.br +0 -0
  55. package/pb_public/assets/app-7OMYYLCI.css.gz +0 -0
  56. package/pb_public/assets/app-7OMYYLCI.css.map +7 -0
  57. package/pb_public/assets/chunk-5PKDEWJS.js +2 -0
  58. package/pb_public/assets/chunk-5PKDEWJS.js.br +0 -0
  59. package/pb_public/assets/chunk-5PKDEWJS.js.gz +0 -0
  60. package/pb_public/assets/chunk-5PKDEWJS.js.map +7 -0
  61. package/pb_public/assets/chunk-AG73QNUN.js +2 -0
  62. package/pb_public/assets/chunk-AG73QNUN.js.br +0 -0
  63. package/pb_public/assets/chunk-AG73QNUN.js.gz +0 -0
  64. package/pb_public/assets/chunk-AG73QNUN.js.map +7 -0
  65. package/pb_public/assets/chunk-DCLJRQ53.js +2 -0
  66. package/pb_public/assets/chunk-DCLJRQ53.js.br +0 -0
  67. package/pb_public/assets/chunk-DCLJRQ53.js.gz +0 -0
  68. package/pb_public/assets/chunk-DCLJRQ53.js.map +7 -0
  69. package/pb_public/assets/chunk-EO3AMXJN.js +2 -0
  70. package/pb_public/assets/chunk-EO3AMXJN.js.br +0 -0
  71. package/pb_public/assets/chunk-EO3AMXJN.js.gz +0 -0
  72. package/pb_public/assets/chunk-EO3AMXJN.js.map +7 -0
  73. package/pb_public/assets/chunk-LDZPNZ2E.js +2 -0
  74. package/pb_public/assets/chunk-LDZPNZ2E.js.br +0 -0
  75. package/pb_public/assets/chunk-LDZPNZ2E.js.gz +0 -0
  76. package/pb_public/assets/chunk-LDZPNZ2E.js.map +7 -0
  77. package/pb_public/assets/chunk-RPCBA7VF.js.br +0 -0
  78. package/pb_public/assets/chunk-RPCBA7VF.js.gz +0 -0
  79. package/pb_public/assets/chunk-RYZHXNLF.js +2 -0
  80. package/pb_public/assets/chunk-RYZHXNLF.js.br +0 -0
  81. package/pb_public/assets/chunk-RYZHXNLF.js.gz +0 -0
  82. package/pb_public/assets/chunk-RYZHXNLF.js.map +7 -0
  83. package/pb_public/assets/chunk-UZDXAORM.js +2 -0
  84. package/pb_public/assets/chunk-UZDXAORM.js.br +0 -0
  85. package/pb_public/assets/chunk-UZDXAORM.js.gz +0 -0
  86. package/pb_public/assets/chunk-UZDXAORM.js.map +7 -0
  87. package/pb_public/assets/chunk-VSHXXDW4.js +2 -0
  88. package/pb_public/assets/chunk-VSHXXDW4.js.br +0 -0
  89. package/pb_public/assets/chunk-VSHXXDW4.js.gz +0 -0
  90. package/pb_public/assets/chunk-VSHXXDW4.js.map +7 -0
  91. package/pb_public/assets/chunk-VTOUI25E.js.br +0 -0
  92. package/pb_public/assets/chunk-VTOUI25E.js.gz +0 -0
  93. package/pb_public/assets/{chunk-DZC4SY4M.js → chunk-Y5MCBN66.js} +2 -2
  94. package/pb_public/assets/chunk-Y5MCBN66.js.br +0 -0
  95. package/pb_public/assets/chunk-Y5MCBN66.js.gz +0 -0
  96. package/pb_public/assets/{chunk-DZC4SY4M.js.map → chunk-Y5MCBN66.js.map} +3 -3
  97. package/pb_public/assets/collections-FZB6G4W4.css +2 -0
  98. package/pb_public/assets/collections-FZB6G4W4.css.br +0 -0
  99. package/pb_public/assets/collections-FZB6G4W4.css.gz +0 -0
  100. package/pb_public/assets/collections-FZB6G4W4.css.map +7 -0
  101. package/pb_public/assets/emoji-IHRUMGCY.css +2 -0
  102. package/pb_public/assets/emoji-IHRUMGCY.css.br +0 -0
  103. package/pb_public/assets/emoji-IHRUMGCY.css.gz +0 -0
  104. package/pb_public/assets/emoji-IHRUMGCY.css.map +7 -0
  105. package/pb_public/assets/{emoji-picker-K6JTK2GV.js → emoji-picker-W27IJER2.js} +2 -2
  106. package/pb_public/assets/emoji-picker-W27IJER2.js.br +0 -0
  107. package/pb_public/assets/emoji-picker-W27IJER2.js.gz +0 -0
  108. package/pb_public/assets/{forward-267HRNPY.js → forward-5TJEYGEV.js} +2 -2
  109. package/pb_public/assets/forward-5TJEYGEV.js.br +0 -0
  110. package/pb_public/assets/forward-5TJEYGEV.js.gz +0 -0
  111. package/pb_public/assets/inbox-2AXY3INA.css +2 -0
  112. package/pb_public/assets/inbox-2AXY3INA.css.br +0 -0
  113. package/pb_public/assets/inbox-2AXY3INA.css.gz +0 -0
  114. package/pb_public/assets/inbox-2AXY3INA.css.map +7 -0
  115. package/pb_public/assets/{inbox-CLMYESNI.js → inbox-A46J7ZU2.js} +2 -2
  116. package/pb_public/assets/inbox-A46J7ZU2.js.br +0 -0
  117. package/pb_public/assets/inbox-A46J7ZU2.js.gz +0 -0
  118. package/pb_public/assets/{inbox-CLMYESNI.js.map → inbox-A46J7ZU2.js.map} +2 -2
  119. package/pb_public/assets/invite-6BCBF4KV.js +2 -0
  120. package/pb_public/assets/invite-6BCBF4KV.js.br +0 -0
  121. package/pb_public/assets/invite-6BCBF4KV.js.gz +0 -0
  122. package/pb_public/assets/invite-6BCBF4KV.js.map +7 -0
  123. package/pb_public/assets/invite-api-7G7XPXQW.js +2 -0
  124. package/pb_public/assets/invite-api-7G7XPXQW.js.br +0 -0
  125. package/pb_public/assets/invite-api-7G7XPXQW.js.gz +0 -0
  126. package/pb_public/assets/lazy-OVEJT5CP.js +2 -0
  127. package/pb_public/assets/lazy-OVEJT5CP.js.br +0 -0
  128. package/pb_public/assets/lazy-OVEJT5CP.js.gz +0 -0
  129. package/pb_public/assets/lazy-OVEJT5CP.js.map +7 -0
  130. package/pb_public/assets/login-FZY6GOMF.js +2 -0
  131. package/pb_public/assets/login-FZY6GOMF.js.br +0 -0
  132. package/pb_public/assets/login-FZY6GOMF.js.gz +0 -0
  133. package/pb_public/assets/{login-ECFBJP6Q.js.map → login-FZY6GOMF.js.map} +1 -1
  134. package/pb_public/assets/media-BCKZQR2R.css +2 -0
  135. package/pb_public/assets/media-BCKZQR2R.css.br +0 -0
  136. package/pb_public/assets/media-BCKZQR2R.css.gz +0 -0
  137. package/pb_public/assets/media-BCKZQR2R.css.map +7 -0
  138. package/pb_public/assets/{media-WZ4653L5.js → media-VCJWBQJZ.js} +2 -2
  139. package/pb_public/assets/media-VCJWBQJZ.js.br +0 -0
  140. package/pb_public/assets/media-VCJWBQJZ.js.gz +0 -0
  141. package/pb_public/assets/{mention-suggest-ODJD2IC5.js → mention-suggest-K3UUHR4D.js} +2 -2
  142. package/pb_public/assets/mention-suggest-K3UUHR4D.js.br +0 -0
  143. package/pb_public/assets/mention-suggest-K3UUHR4D.js.gz +0 -0
  144. package/pb_public/assets/notify-EPDM772N.js.br +0 -0
  145. package/pb_public/assets/notify-EPDM772N.js.gz +0 -0
  146. package/pb_public/assets/profile-7KMXLX5U.js +2 -0
  147. package/pb_public/assets/profile-7KMXLX5U.js.br +0 -0
  148. package/pb_public/assets/profile-7KMXLX5U.js.gz +0 -0
  149. package/pb_public/assets/profile-7KMXLX5U.js.map +7 -0
  150. package/pb_public/assets/rooms-forms-IADHTHBZ.js +2 -0
  151. package/pb_public/assets/rooms-forms-IADHTHBZ.js.br +0 -0
  152. package/pb_public/assets/rooms-forms-IADHTHBZ.js.gz +0 -0
  153. package/pb_public/assets/rooms-forms-IADHTHBZ.js.map +7 -0
  154. package/pb_public/assets/search-HOPAWIMQ.js +2 -0
  155. package/pb_public/assets/search-HOPAWIMQ.js.br +0 -0
  156. package/pb_public/assets/search-HOPAWIMQ.js.gz +0 -0
  157. package/pb_public/assets/search-HOPAWIMQ.js.map +7 -0
  158. package/pb_public/assets/sidebar-forms-ETSRVSPY.css +2 -0
  159. package/pb_public/assets/sidebar-forms-ETSRVSPY.css.br +0 -0
  160. package/pb_public/assets/sidebar-forms-ETSRVSPY.css.gz +0 -0
  161. package/pb_public/assets/sidebar-forms-ETSRVSPY.css.map +7 -0
  162. package/pb_public/assets/stats-5GSWDHZI.css +2 -0
  163. package/pb_public/assets/stats-5GSWDHZI.css.br +0 -0
  164. package/pb_public/assets/stats-5GSWDHZI.css.gz +0 -0
  165. package/pb_public/assets/stats-5GSWDHZI.css.map +7 -0
  166. package/pb_public/assets/stats-Y3LIXAZR.js +2 -0
  167. package/pb_public/assets/stats-Y3LIXAZR.js.br +0 -0
  168. package/pb_public/assets/stats-Y3LIXAZR.js.gz +0 -0
  169. package/pb_public/assets/stats-Y3LIXAZR.js.map +7 -0
  170. package/pb_public/assets/switcher-TFSO45KV.js.br +0 -0
  171. package/pb_public/assets/switcher-TFSO45KV.js.gz +0 -0
  172. package/pb_public/assets/user-search-GUNMIBSB.js +2 -0
  173. package/pb_public/assets/user-search-GUNMIBSB.js.br +0 -0
  174. package/pb_public/assets/user-search-GUNMIBSB.js.gz +0 -0
  175. package/pb_public/assets/user-search-GUNMIBSB.js.map +7 -0
  176. package/pb_public/assets/{viewer-2Y5FJBW4.js → viewer-BHKVAADP.js} +2 -2
  177. package/pb_public/assets/viewer-BHKVAADP.js.br +0 -0
  178. package/pb_public/assets/viewer-BHKVAADP.js.gz +0 -0
  179. package/pb_public/assets/viewer-JBZU46HP.css +2 -0
  180. package/pb_public/assets/viewer-JBZU46HP.css.br +0 -0
  181. package/pb_public/assets/viewer-JBZU46HP.css.gz +0 -0
  182. package/pb_public/assets/{viewer-P7GYCBYM.css.map → viewer-JBZU46HP.css.map} +2 -2
  183. package/pb_public/index.html +11 -8
  184. package/pb_public/stats.html +3 -3
  185. package/scripts/service.mjs +201 -0
  186. package/scripts/start.mjs +9 -2
  187. package/pb_public/assets/access-LHPD2EHG.js +0 -2
  188. package/pb_public/assets/access-LHPD2EHG.js.map +0 -7
  189. package/pb_public/assets/access-PB77EH4F.css +0 -2
  190. package/pb_public/assets/access-PB77EH4F.css.map +0 -7
  191. package/pb_public/assets/app-6ETOTHXQ.js +0 -3
  192. package/pb_public/assets/app-6ETOTHXQ.js.map +0 -7
  193. package/pb_public/assets/app-ZGHECF33.css +0 -2
  194. package/pb_public/assets/app-ZGHECF33.css.map +0 -7
  195. package/pb_public/assets/chunk-56ACD3V5.js +0 -2
  196. package/pb_public/assets/chunk-56ACD3V5.js.map +0 -7
  197. package/pb_public/assets/chunk-GXMWOXBX.js +0 -2
  198. package/pb_public/assets/chunk-GXMWOXBX.js.map +0 -7
  199. package/pb_public/assets/chunk-IFQGGTSP.js +0 -2
  200. package/pb_public/assets/chunk-IFQGGTSP.js.map +0 -7
  201. package/pb_public/assets/chunk-PWNJABVI.js +0 -2
  202. package/pb_public/assets/chunk-PWNJABVI.js.map +0 -7
  203. package/pb_public/assets/collections-DHJEOLHW.css +0 -2
  204. package/pb_public/assets/collections-DHJEOLHW.css.map +0 -7
  205. package/pb_public/assets/emoji-WWNPWCF3.css +0 -2
  206. package/pb_public/assets/emoji-WWNPWCF3.css.map +0 -7
  207. package/pb_public/assets/inbox-3FSOPY2T.css +0 -2
  208. package/pb_public/assets/inbox-3FSOPY2T.css.map +0 -7
  209. package/pb_public/assets/lazy-H3KIJVB5.js +0 -2
  210. package/pb_public/assets/lazy-H3KIJVB5.js.map +0 -7
  211. package/pb_public/assets/login-ECFBJP6Q.js +0 -2
  212. package/pb_public/assets/media-7TCBG7WM.css +0 -2
  213. package/pb_public/assets/media-7TCBG7WM.css.map +0 -7
  214. package/pb_public/assets/profile-NQQLAEDT.js +0 -2
  215. package/pb_public/assets/profile-NQQLAEDT.js.map +0 -7
  216. package/pb_public/assets/search-WCHOGAJQ.js +0 -2
  217. package/pb_public/assets/search-WCHOGAJQ.js.map +0 -7
  218. package/pb_public/assets/stats-A2TBRUI6.css +0 -2
  219. package/pb_public/assets/stats-A2TBRUI6.css.map +0 -7
  220. package/pb_public/assets/stats-ARDU576A.js +0 -2
  221. package/pb_public/assets/stats-ARDU576A.js.map +0 -7
  222. package/pb_public/assets/user-search-3HQOCQWL.js +0 -2
  223. package/pb_public/assets/viewer-P7GYCBYM.css +0 -2
  224. /package/pb_public/assets/{emoji-picker-K6JTK2GV.js.map → emoji-picker-W27IJER2.js.map} +0 -0
  225. /package/pb_public/assets/{forward-267HRNPY.js.map → forward-5TJEYGEV.js.map} +0 -0
  226. /package/pb_public/assets/{user-search-3HQOCQWL.js.map → invite-api-7G7XPXQW.js.map} +0 -0
  227. /package/pb_public/assets/{media-WZ4653L5.js.map → media-VCJWBQJZ.js.map} +0 -0
  228. /package/pb_public/assets/{mention-suggest-ODJD2IC5.js.map → mention-suggest-K3UUHR4D.js.map} +0 -0
  229. /package/pb_public/assets/{viewer-2Y5FJBW4.js.map → viewer-BHKVAADP.js.map} +0 -0
@@ -1,20 +1,28 @@
1
1
  /// <reference path="../../types/pocketbase.d.ts" />
2
- // POST /api/chat/password (DESIGN.md §22.2): change your password. Checks the current one, signs out every other
3
- // session, and answers like a login (a fresh token and record), so the tab that changed it stays logged in.
2
+ // Your account (DESIGN.md §22.2, §43):
3
+ // - POST /api/chat/password: change your password. Checks the current one, signs out every other session, and
4
+ // answers like a login (a fresh token and record), so the tab that changed it stays logged in.
5
+ // - POST /api/chat/export, GET /api/chat/export, GET /api/chat/export/file: everything you wrote and keep here, as a
6
+ // JSON file. Asked for, it is made by a worker (an account job), and is then there to download for 7 days.
7
+ // - POST /api/chat/account/delete: delete your account. Its personal data goes at once; its collections, and its
8
+ // messages if its person chooses so, go after, by the same worker, a batch at a time.
9
+ //
10
+ // The worker (a cron job, lib/worker.js) does the work that grows with the account, so a big account or a busy
11
+ // server never holds a request, or the database's write lock, for long (§43.5).
4
12
 
5
13
  /**
6
14
  * @param {string} field
7
15
  * @param {string} message
8
16
  * @param {string} [code]
9
17
  */
10
- function fieldError(field, message, code = "validation_invalid_value") {
11
- return new BadRequestError("Failed to change the password.", { [field]: new ValidationError(code, message) });
18
+ function fieldError(field, message, code = "validation_invalid_value", what = "Failed to change the password.") {
19
+ return new BadRequestError(what, { [field]: new ValidationError(code, message) });
12
20
  }
13
21
 
14
22
  /** @param {core.RequestEvent} e */
15
23
  function changePassword(e) {
16
24
  if (!e.auth) throw new UnauthorizedError("The request requires a logged-in user.");
17
- const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body);
25
+ const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body ?? {});
18
26
  const oldPassword = typeof body.oldPassword === "string" ? body.oldPassword : "";
19
27
  const password = typeof body.password === "string" ? body.password : "";
20
28
  if (!oldPassword) throw fieldError("oldPassword", "Enter your current password.", "validation_required");
@@ -29,4 +37,531 @@ function changePassword(e) {
29
37
  return $apis.recordAuthResponse(e, user, "password");
30
38
  }
31
39
 
32
- module.exports = { changePassword };
40
+ /** Rows read at a time by the export and the delete. */
41
+ const PAGE = 500;
42
+
43
+ /** Items or messages deleted in one transaction by an erase job. */
44
+ const ERASE_BATCH = 200;
45
+
46
+ /** What an export says it is (§43.2); `version` changes when its shape does. */
47
+ const FORMAT = "chirkle-export";
48
+ const VERSION = 1;
49
+
50
+ /** How long a made export is kept to download. */
51
+ const KEEP_MS = 7 * 24 * 3600_000;
52
+
53
+ /** A made export asked for again within this long is the same one: no new job. */
54
+ const FRESH_MS = 10 * 60_000;
55
+
56
+ /** A job that failed this many times is given up ("failed"). */
57
+ const MAX_TRIES = 5;
58
+
59
+ /** The worker's lock (lib/worker.js), and how long before a run that stopped renewing it is taken over. */
60
+ const LOCK = "account.worker";
61
+ const STALE_MS = 5 * 60_000;
62
+
63
+ /** A time as the database stores it. @param {number} ms */
64
+ const dbDate = (ms) => new Date(ms).toISOString().replace("T", " ");
65
+
66
+ /** A stored time in ms, or 0. @param {string} t */
67
+ const msOf = (t) => (t ? Date.parse(t.replace(" ", "T")) || 0 : 0);
68
+
69
+ /**
70
+ * What a file is called: its upload's name when recorded, else its stored name without the "_" and 10 characters
71
+ * PocketBase adds (web/src/lib/files.ts attachmentName).
72
+ * @param {Record<string, string>} names
73
+ * @param {string} stored
74
+ */
75
+ const fileName = (names, stored) => names[stored] || stored.replace(/_[a-z0-9]{10}(\.[^.]*)?$/i, "$1");
76
+
77
+ /**
78
+ * Every record of `collection` matching `filter`, a page at a time, oldest first, by (created, id): a page costs the
79
+ * same however far in it is. `renew` (the worker's) after each page.
80
+ * @param {core.App} app
81
+ * @param {string} collection
82
+ * @param {string} filter
83
+ * @param {Record<string, unknown>} params
84
+ * @param {(rec: core.Record) => void} each
85
+ * @param {() => void} [renew]
86
+ */
87
+ function eachRecord(app, collection, filter, params, each, renew) {
88
+ /** @type {{ c: string, i: string } | null} */
89
+ let after = null;
90
+ for (;;) {
91
+ /** @type {(core.Record | undefined)[]} */
92
+ const page = after
93
+ ? app.findRecordsByFilter(collection, `(${filter}) && (created > {:_c} || (created = {:_c} && id > {:_i}))`, "created,id", PAGE, 0, {
94
+ ...params,
95
+ _c: after.c,
96
+ _i: after.i,
97
+ })
98
+ : app.findRecordsByFilter(collection, filter, "created,id", PAGE, 0, params);
99
+ for (const rec of page) if (rec) each(rec);
100
+ if (renew) renew();
101
+ /** @type {core.Record | undefined} */
102
+ const last = page[page.length - 1];
103
+ if (page.length < PAGE || !last) return;
104
+ after = { c: last.getString("created"), i: last.id };
105
+ }
106
+ }
107
+
108
+ // ---------------------------------------------------------------- your data (§43.2)
109
+
110
+ /**
111
+ * A user's newest job of `kind`, or null.
112
+ * @param {core.App} app
113
+ * @param {string} userId
114
+ * @param {"export" | "erase"} kind
115
+ */
116
+ function latestJob(app, userId, kind) {
117
+ const rows = app.findRecordsByFilter("account_jobs", "user = {:u} && kind = {:k}", "-created,-id", 1, 0, { u: userId, k: kind });
118
+ return rows[0] ?? null;
119
+ }
120
+
121
+ /**
122
+ * What GET and POST /api/chat/export answer: where the newest export is. `state` "none" (never asked, or gone after 7
123
+ * days), "queued" (being made), "done" (to download until `expires`) or "failed".
124
+ * @param {core.Record | null} job
125
+ */
126
+ function exportStatus(job) {
127
+ if (!job) return { id: "", state: "none", created: "", finished: "", expires: "", size: 0 };
128
+ const state = job.getString("state");
129
+ return {
130
+ id: job.id,
131
+ state,
132
+ created: job.getString("created"),
133
+ finished: job.getString("finished"),
134
+ expires: state === "done" ? dbDate(msOf(job.getString("created")) + KEEP_MS) : "",
135
+ size: job.getInt("size"),
136
+ };
137
+ }
138
+
139
+ /**
140
+ * GET /api/chat/export: where your newest export is (exportStatus).
141
+ * @param {core.RequestEvent} e
142
+ */
143
+ function exportState(e) {
144
+ if (!e.auth) throw new UnauthorizedError("The request requires a logged-in user.");
145
+ return e.json(200, exportStatus(latestJob(e.app, e.auth.id, "export")));
146
+ }
147
+
148
+ /**
149
+ * POST /api/chat/export: make your data into a file (§43.2). Queued for the worker; asked again while it is being made,
150
+ * or within 10 minutes of it being made, the same one. Answers as GET does.
151
+ * @param {core.RequestEvent} e
152
+ */
153
+ function startExport(e) {
154
+ if (!e.auth) throw new UnauthorizedError("The request requires a logged-in user.");
155
+ const last = latestJob(e.app, e.auth.id, "export");
156
+ const state = last?.getString("state");
157
+ if (last && (state === "queued" || (state === "done" && Date.now() - msOf(last.getString("created")) < FRESH_MS))) {
158
+ return e.json(200, exportStatus(last));
159
+ }
160
+ const job = new Record(e.app.findCollectionByNameOrId("account_jobs"));
161
+ job.set("user", e.auth.id);
162
+ job.set("kind", "export");
163
+ job.set("state", "queued");
164
+ e.app.save(job);
165
+ wake(e.app);
166
+ return e.json(200, exportStatus(job));
167
+ }
168
+
169
+ /**
170
+ * GET /api/chat/export/file: your newest made export, as a download. Signed in, or with a file token
171
+ * (`?token=`, POST /api/files/token) so that a plain link (the web's, the app's download manager) can fetch it.
172
+ * @param {core.RequestEvent} e
173
+ */
174
+ function exportFile(e) {
175
+ /** @type {core.Record | undefined} */
176
+ let user = e.auth;
177
+ const token = e.request?.url?.query().get("token") ?? "";
178
+ if (!user && token) {
179
+ try {
180
+ user = e.app.findAuthRecordByToken(token, "file");
181
+ } catch {
182
+ user = undefined;
183
+ }
184
+ }
185
+ if (!e.request) throw new BadRequestError("No request.");
186
+ if (user?.collection().name !== "users") throw new UnauthorizedError("The request requires a logged-in user.");
187
+ const job = latestJob(e.app, user.id, "export");
188
+ const file = job?.getString("state") === "done" ? job.getString("file") : "";
189
+ if (!job || !file) throw new NotFoundError("There is no export to download. Ask for one first.");
190
+ const name = `chirkle-export-${job.getString("created").slice(0, 10)}.json`;
191
+ const fsys = e.app.newFilesystem();
192
+ try {
193
+ e.response.header().set("Cache-Control", "no-store");
194
+ e.response.header().set("Content-Disposition", `attachment; filename="${name}"`);
195
+ fsys.serve(e.response, e.request, `${job.baseFilesPath()}/${file}`, name);
196
+ } finally {
197
+ fsys.close();
198
+ }
199
+ }
200
+
201
+ /**
202
+ * Write export job `job`'s file (§43.2): the user's profile (with their e-mail); the messages they wrote and haven't
203
+ * deleted, with their files; the rooms those are in and the rooms they made; their collections with their items; the
204
+ * collections they follow; the rooms they hid. Written a record at a time into a temporary file, which is then the
205
+ * job's (protected) `file`: what is held in memory is the room list, not the messages. Files are paths on this server
206
+ * (`/api/files/…`), which whoever has them can open (§37.3). Other people's words aren't in it: a forward names the
207
+ * message it shows, not its text.
208
+ * @param {core.App} app
209
+ * @param {core.Record} job
210
+ * @param {() => void} [renew]
211
+ */
212
+ function writeExport(app, job, renew) {
213
+ const id = job.getString("user");
214
+ const me = app.findRecordById("users", id);
215
+ const at = new Date().toISOString();
216
+ const dir = $os.tempDir();
217
+ const tmp = `chirkle-export-${job.id}-${$security.randomString(8)}.json`;
218
+ const root = $os.openRoot(dir);
219
+ const out = root.create(tmp);
220
+ const w = (/** @type {string} */ s) => out.writeString(s);
221
+ try {
222
+ const account = {
223
+ id,
224
+ name: me.getString("name"),
225
+ handle: me.getString("handle"),
226
+ email: me.getString("email"),
227
+ created: me.getString("created"),
228
+ avatar: me.getString("avatar") ? `/api/files/users/${id}/${me.getString("avatar")}` : "",
229
+ no_dms: me.getBool("no_dms"),
230
+ };
231
+ w(`{"format":${JSON.stringify(FORMAT)},"version":${VERSION},"exported":${JSON.stringify(at)},"account":${JSON.stringify(account)}`);
232
+
233
+ /** The rooms its messages are in. @type {Set<string>} */
234
+ const roomIds = new Set();
235
+ let first = true;
236
+ w(`,"messages":[`);
237
+ eachRecord(
238
+ app,
239
+ "messages",
240
+ "author = {:id} && deleted = false",
241
+ { id },
242
+ (m) => {
243
+ roomIds.add(m.getString("room"));
244
+ const names = /** @type {Record<string, string>} */ (m.get("file_names") ?? {});
245
+ const row = {
246
+ id: m.id,
247
+ room: m.getString("room"),
248
+ created: m.getString("created"),
249
+ edited: m.getString("edited_at"),
250
+ text: m.getString("text"),
251
+ reply_to: m.getString("reply_to"),
252
+ forward_of: m.getString("forward_of"),
253
+ files: m.getStringSlice("files").map((f) => ({ name: fileName(names, f), url: `/api/files/messages/${m.id}/${f}` })),
254
+ };
255
+ w(`${first ? "" : ","}${JSON.stringify(row)}`);
256
+ first = false;
257
+ },
258
+ renew,
259
+ );
260
+
261
+ /** A DM is named for whoever else is in it. @param {core.Record} r */
262
+ const roomRow = (r) => {
263
+ let name = r.getString("name");
264
+ if (r.getString("kind") === "dm") {
265
+ const others = r.getStringSlice("members").filter((u) => u !== id);
266
+ name = (others.length ? app.findRecordsByIds("users", others) : []).map((u) => (u ? u.getString("name") : "")).join(", ");
267
+ }
268
+ return { id: r.id, name, kind: r.getString("kind") === "dm" ? "dm" : "room", mine: r.getString("created_by") === id };
269
+ };
270
+ first = true;
271
+ w(`],"rooms":[`);
272
+ const room = (/** @type {core.Record} */ r) => {
273
+ w(`${first ? "" : ","}${JSON.stringify(roomRow(r))}`);
274
+ first = false;
275
+ };
276
+ eachRecord(app, "rooms", "created_by = {:id}", { id }, (r) => {
277
+ roomIds.delete(r.id);
278
+ room(r);
279
+ });
280
+ const rest = [...roomIds];
281
+ for (let i = 0; i < rest.length; i += PAGE) {
282
+ for (const r of app.findRecordsByIds("rooms", rest.slice(i, i + PAGE))) if (r) room(r);
283
+ if (renew) renew();
284
+ }
285
+
286
+ first = true;
287
+ w(`],"collections":[`);
288
+ eachRecord(app, "collections", "owner = {:id}", { id }, (c) => {
289
+ w(
290
+ `${first ? "" : ","}{"id":${JSON.stringify(c.id)},"name":${JSON.stringify(c.getString("name"))},"public":${c.getBool("public")},"created":${JSON.stringify(c.getString("created"))},"items":[`,
291
+ );
292
+ first = false;
293
+ let firstItem = true;
294
+ eachRecord(
295
+ app,
296
+ "collection_items",
297
+ "collection = {:c}",
298
+ { c: c.id },
299
+ (it) => {
300
+ const file = it.getString("file");
301
+ const row = {
302
+ id: it.id,
303
+ name: it.getString("name") || fileName({}, file),
304
+ created: it.getString("created"),
305
+ url: file ? `/api/files/collection_items/${it.id}/${file}` : "",
306
+ };
307
+ w(`${firstItem ? "" : ","}${JSON.stringify(row)}`);
308
+ firstItem = false;
309
+ },
310
+ renew,
311
+ );
312
+ w("]}");
313
+ });
314
+
315
+ first = true;
316
+ w(`],"following":[`);
317
+ eachRecord(app, "collection_subs", "user = {:id}", { id }, (sub) => {
318
+ try {
319
+ const c = app.findRecordById("collections", sub.getString("collection"));
320
+ w(`${first ? "" : ","}${JSON.stringify({ id: c.id, name: c.getString("name") })}`);
321
+ first = false;
322
+ } catch {
323
+ // gone
324
+ }
325
+ });
326
+
327
+ first = true;
328
+ w(`],"hidden_rooms":[`);
329
+ eachRecord(app, "hidden_rooms", "user = {:id}", { id }, (row) => {
330
+ w(`${first ? "" : ","}${JSON.stringify(row.getString("room"))}`);
331
+ first = false;
332
+ });
333
+ w("]}\n");
334
+ } finally {
335
+ out.close();
336
+ root.close();
337
+ }
338
+ const path = `${dir}/${tmp}`;
339
+ try {
340
+ const file = $filesystem.fileFromPath(path);
341
+ file.originalName = `chirkle-export-${at.slice(0, 10)}.json`;
342
+ job.set("file", file);
343
+ job.set("size", $os.stat(path).size());
344
+ app.save(job);
345
+ } finally {
346
+ $os.remove(path);
347
+ }
348
+ }
349
+
350
+ // ---------------------------------------------------------------- deleting the account (§43.3)
351
+
352
+ /**
353
+ * POST /api/chat/account/delete { password, messages: "keep" | "delete" } → 204 (§43.3). The caller's password says
354
+ * it is them. The account is a deleted one at once (erase); what grows with it (its collections' items, and with
355
+ * "delete" its messages) goes after, by the worker (an erase job).
356
+ * @param {core.RequestEvent} e
357
+ */
358
+ function deleteAccount(e) {
359
+ if (!e.auth) throw new UnauthorizedError("The request requires a logged-in user.");
360
+ const what = "Failed to delete the account.";
361
+ const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body ?? {});
362
+ const password = typeof body.password === "string" ? body.password : "";
363
+ const choice = body.messages;
364
+ if (!password) throw fieldError("password", "Enter your password.", "validation_required", what);
365
+ if (choice !== "keep" && choice !== "delete") {
366
+ throw fieldError("messages", "Choose whether your messages stay or go.", "validation_required", what);
367
+ }
368
+ const user = e.app.findRecordById("users", e.auth.id);
369
+ if (!user.validatePassword(password)) throw fieldError("password", "That isn't your password.", undefined, what);
370
+ erase(e.app, user.id, choice === "delete");
371
+ wake(e.app);
372
+ return e.noContent(204);
373
+ }
374
+
375
+ /**
376
+ * Make `userId` a deleted account (§43.3), in one transaction, and queue the rest. Its name becomes "Deleted account"
377
+ * (lib/users.js beforeUserSave), its handle, picture and e-mail go, it takes no DMs, it is no moderator. Every session
378
+ * ends and no sign-in works again: a random password, its OAuth2 links, one-time codes and sign-in origins gone. What
379
+ * only it had and is small goes now: whom and what it follows, hid and read, its inbox, its exports, the invite links it
380
+ * made. Its collections
381
+ * stop being public, and go with their items by the erase job. It leaves the private rooms it was in and the lists of
382
+ * who may post. The row stays, so the messages (kept, or deleted) and rooms that name it still have an author; a room
383
+ * it made keeps it as its creator, and moderators look after it.
384
+ * @param {core.App} app
385
+ * @param {string} userId
386
+ * @param {boolean} messages its messages go too (by the erase job)
387
+ */
388
+ function erase(app, userId, messages) {
389
+ app.runInTransaction((tx) => {
390
+ const user = tx.findRecordById("users", userId);
391
+ user.set("kind", "deleted");
392
+ user.set("email", `${userId}@deleted.invalid`);
393
+ user.set("emailVisibility", false);
394
+ user.set("verified", false);
395
+ user.set("avatar", null);
396
+ user.set("no_dms", true);
397
+ user.set("moderator", false);
398
+ user.set("banned", false);
399
+ user.setPassword($security.randomString(48));
400
+ user.refreshTokenKey();
401
+ tx.save(user);
402
+ tx.deleteAllExternalAuthsByRecord(user);
403
+ tx.deleteAllMFAsByRecord(user);
404
+ tx.deleteAllOTPsByRecord(user);
405
+ tx.deleteAllAuthOriginsByRecord(user);
406
+
407
+ for (const [collection, field] of [
408
+ ["collection_subs", "user"],
409
+ ["hidden_rooms", "user"],
410
+ ["room_reads", "user"],
411
+ ["inbox", "user"],
412
+ ["inbox_reads", "user"],
413
+ ["stats_activity", "user"],
414
+ ["account_jobs", "user"],
415
+ // The invite links it made (§44): a room it no longer manages takes no one in by its hand (QA BUG-281).
416
+ ["room_invites", "created_by"],
417
+ ]) {
418
+ for (;;) {
419
+ const rows = tx.findRecordsByFilter(collection, `${field} = {:id}`, "", PAGE, 0, { id: userId });
420
+ for (const row of rows) if (row) tx.delete(row);
421
+ if (rows.length < PAGE) break;
422
+ }
423
+ }
424
+ // Read all first, as below: saved, a record no longer matches, and the pages would skip some.
425
+ /** @type {core.Record[]} */
426
+ const shown = [];
427
+ eachRecord(tx, "collections", "owner = {:id} && public = true", { id: userId }, (c) => shown.push(c));
428
+ for (const c of shown) {
429
+ c.set("public", false);
430
+ tx.save(c);
431
+ }
432
+
433
+ // Private rooms' members and who may post (§23): not a DM's two, which name the DM.
434
+ /** @type {core.Record[]} */
435
+ const rooms = [];
436
+ eachRecord(tx, "rooms", "kind != 'dm' && (members.id ?= {:id} || writers.id ?= {:id})", { id: userId }, (r) => rooms.push(r));
437
+ for (const room of rooms) {
438
+ room.set(
439
+ "members",
440
+ room.getStringSlice("members").filter((u) => u !== userId),
441
+ );
442
+ room.set(
443
+ "writers",
444
+ room.getStringSlice("writers").filter((u) => u !== userId),
445
+ );
446
+ tx.save(room);
447
+ }
448
+
449
+ const job = new Record(tx.findCollectionByNameOrId("account_jobs"));
450
+ job.set("user", userId);
451
+ job.set("kind", "erase");
452
+ job.set("state", "queued");
453
+ job.set("messages", messages);
454
+ tx.save(job);
455
+ });
456
+ }
457
+
458
+ /**
459
+ * One step of erase job `job`: a batch of a collection's items (the collection itself after its last), else with
460
+ * `messages` a batch of its messages soft-deleted (§21.2) through the messages hooks, so files, previews, the media
461
+ * grid, the inbox, forwards and the bridges follow as for any delete, archived rooms too (`@erasing`). Each batch in a
462
+ * transaction. True while there is more.
463
+ * @param {core.App} app
464
+ * @param {core.Record} job
465
+ */
466
+ function eraseStep(app, job) {
467
+ const userId = job.getString("user");
468
+ const coll = app.findRecordsByFilter("collections", "owner = {:u}", "created,id", 1, 0, { u: userId })[0];
469
+ if (coll) {
470
+ const items = app.findRecordsByFilter("collection_items", "collection = {:c}", "", ERASE_BATCH, 0, { c: coll.id });
471
+ app.runInTransaction((tx) => {
472
+ for (const it of items) if (it) tx.delete(it);
473
+ if (items.length < ERASE_BATCH) tx.delete(tx.findRecordById("collections", coll.id));
474
+ });
475
+ return true;
476
+ }
477
+ if (!job.getBool("messages")) return false;
478
+ const batch = app.findRecordsByFilter("messages", "author = {:id} && deleted = false", "created,id", ERASE_BATCH, 0, { id: userId });
479
+ if (!batch.length) return false;
480
+ const { ERASING } = require(`${__hooks}/lib/messages.js`);
481
+ app.runInTransaction((tx) => {
482
+ for (const m of batch) {
483
+ if (!m) continue;
484
+ const rec = tx.findRecordById("messages", m.id);
485
+ if (rec.getBool("deleted")) continue;
486
+ rec.set(ERASING, true);
487
+ rec.set("deleted", true);
488
+ tx.save(rec);
489
+ }
490
+ });
491
+ return true;
492
+ }
493
+
494
+ // ---------------------------------------------------------------- the worker (§43.5)
495
+
496
+ /**
497
+ * One pass: exports older than 7 days deleted (their files with them), then one step of the queued job touched
498
+ * longest ago: an export written whole, or a batch of an erase. Saving the job touches it, so jobs take turns: a
499
+ * large erase doesn't keep an export waiting. A step that fails is tried again on a later pass, at most MAX_TRIES
500
+ * times. Returns whether there may be more to do now.
501
+ * @param {core.App} app
502
+ * @param {() => void} [renew]
503
+ */
504
+ function pass(app, renew) {
505
+ const old = app.findRecordsByFilter("account_jobs", "kind = 'export' && created < {:t}", "", 50, 0, { t: dbDate(Date.now() - KEEP_MS) });
506
+ for (const j of old) if (j) app.delete(j);
507
+ const job = app.findRecordsByFilter("account_jobs", "state = 'queued'", "updated,id", 1, 0)[0];
508
+ if (!job) return old.length === 50;
509
+ try {
510
+ let more = false;
511
+ if (job.getString("kind") === "export") writeExport(app, job, renew);
512
+ else more = eraseStep(app, job);
513
+ if (!more) {
514
+ job.set("state", "done");
515
+ job.set("finished", new DateTime());
516
+ }
517
+ app.save(job);
518
+ } catch (err) {
519
+ if (require(`${__hooks}/lib/worker.js`).isLost(err)) throw err;
520
+ app.logger().error("account: job failed", "job", job.id, "kind", job.getString("kind"), "error", String(err));
521
+ try {
522
+ const fresh = app.findRecordById("account_jobs", job.id);
523
+ const tries = fresh.getInt("tries") + 1;
524
+ fresh.set("tries", tries);
525
+ fresh.set("error", String(err).slice(0, 500));
526
+ if (tries >= MAX_TRIES) {
527
+ fresh.set("state", "failed");
528
+ fresh.set("finished", new DateTime());
529
+ }
530
+ app.save(fresh);
531
+ } catch {
532
+ // gone meanwhile (its account deleted)
533
+ }
534
+ }
535
+ if (renew) renew();
536
+ return true;
537
+ }
538
+
539
+ /**
540
+ * The cron job: passes until the minute is nearly over; with nothing to do, when a request wakes it. One run at a time.
541
+ * @param {core.App} app
542
+ */
543
+ function run(app) {
544
+ require(`${__hooks}/lib/worker.js`).run(app, {
545
+ name: LOCK,
546
+ label: "account",
547
+ staleMs: STALE_MS,
548
+ wakes: true,
549
+ pass: (/** @type {() => void} */ renew) => pass(app, renew),
550
+ });
551
+ }
552
+
553
+ /** A job was queued (committed): the worker looks now. @param {core.App} app */
554
+ function wake(app) {
555
+ require(`${__hooks}/lib/worker.js`).wake(app, LOCK);
556
+ }
557
+
558
+ /**
559
+ * POST /api/account/tick (superusers): every queued job done now (tests; ACCOUNT_CRON=off).
560
+ * @param {core.RequestEvent} e
561
+ */
562
+ function tick(e) {
563
+ for (let i = 0; i < 10_000 && pass(e.app); i++);
564
+ return e.noContent(204);
565
+ }
566
+
567
+ module.exports = { changePassword, deleteAccount, erase, exportFile, exportState, run, startExport, tick };
@@ -162,11 +162,13 @@ function list(e) {
162
162
  .newQuery("SELECT id, name, public, items, last_added FROM collections WHERE owner = {:me} ORDER BY name_key, id")
163
163
  .bind({ me: user.id })
164
164
  .all(mine);
165
- const subs = arrayOf(new DynamicModel({ id: "", name: "", items: 0, last_added: "", owner: "", owner_name: "", seen_at: "", n: 0 }));
165
+ const subs = arrayOf(
166
+ new DynamicModel({ id: "", name: "", items: 0, last_added: "", owner: "", owner_name: "", owner_avatar: "", seen_at: "", n: 0 }),
167
+ );
166
168
  e.app
167
169
  .db()
168
170
  .newQuery(
169
- `SELECT c.id, c.name, c.items, c.last_added, c.owner, COALESCE(u.name, '') AS owner_name, s.seen_at, (
171
+ `SELECT c.id, c.name, c.items, c.last_added, c.owner, COALESCE(u.name, '') AS owner_name, COALESCE(u.avatar, '') AS owner_avatar, s.seen_at, (
170
172
  SELECT COUNT(*) FROM (
171
173
  SELECT 1 FROM collection_items i WHERE i.collection = c.id AND i.created > s.seen_at LIMIT ${NEW_CAP}
172
174
  )
@@ -195,7 +197,7 @@ function list(e) {
195
197
  public: true,
196
198
  items: c.items,
197
199
  last_added: c.last_added,
198
- owner: { id: c.owner, name: c.owner_name },
200
+ owner: { id: c.owner, name: c.owner_name, avatar: c.owner_avatar },
199
201
  seen_at: c.seen_at,
200
202
  new: c.n,
201
203
  preview: previews[c.id] ?? [],
@@ -281,7 +283,7 @@ const itemOut = (item) => ({
281
283
  */
282
284
  function saveItem(e) {
283
285
  const user = me(e);
284
- const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body);
286
+ const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body ?? {});
285
287
  const str = (/** @type {string} */ k) => (typeof body[k] === "string" ? /** @type {string} */ (body[k]) : "");
286
288
  const coll = find(e.app, "collections", str("collection"));
287
289
  if (!coll || !canView(e, coll)) throw new NotFoundError("The collection doesn't exist.");
@@ -447,7 +449,7 @@ function removeItem(e) {
447
449
  * @returns {{ rows: core.Record[], sources: Record<string, string> }}
448
450
  */
449
451
  function itemsToAttach(e, uploads) {
450
- const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body);
452
+ const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body ?? {});
451
453
  let ids = body.items;
452
454
  if (ids === undefined || ids === "" || ids === null) return { rows: [], sources: {} };
453
455
  if (typeof ids === "string") {
@@ -502,7 +504,7 @@ function findSub(app, user, collection) {
502
504
  */
503
505
  function subscribe(e) {
504
506
  const user = me(e);
505
- const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body);
507
+ const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body ?? {});
506
508
  const id = typeof body.collection === "string" ? body.collection : "";
507
509
  const what = "Failed to subscribe.";
508
510
  // Not "false" or 0 taken for true.
@@ -545,7 +547,7 @@ function subscribe(e) {
545
547
  */
546
548
  function markSeen(e) {
547
549
  const user = me(e);
548
- const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body);
550
+ const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body ?? {});
549
551
  const id = typeof body.collection === "string" ? body.collection : "";
550
552
  const row = id ? findSub(e.app, user.id, id) : null;
551
553
  if (!row) throw new NotFoundError("You don't follow this collection.");
@@ -82,7 +82,7 @@ function dmRefusal(app, me, members) {
82
82
  function openDm(e) {
83
83
  const me = e.auth;
84
84
  if (!me) throw new UnauthorizedError("The request requires a logged-in user.");
85
- const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body);
85
+ const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body ?? {});
86
86
  const other = typeof body.user === "string" ? body.user : "";
87
87
  if (!other) throw userError("Choose who to message.", "validation_required");
88
88
  if (other === me.id) throw userError("You can't message yourself.");
@@ -10,8 +10,30 @@ const { nameKey } = require(`${__hooks}/lib/text.js`);
10
10
  const HANDLE_MIN = 3;
11
11
  const HANDLE_MAX = 24;
12
12
  const HANDLE = /^[a-z0-9_]{3,24}$/;
13
- /** Kept for what may one day mean everyone in a room. */
14
- const RESERVED = new Set(["all", "everyone", "here", "room", "channel"]);
13
+ /** Kept for what may one day mean everyone in a room: nobody has these (migration 46 took them back). */
14
+ const GROUP = ["all", "everyone", "here", "room", "channel"];
15
+ /**
16
+ * Words that would lend a stranger the site's authority in a mention ("@admin says…", QA SEC-2): not given to a new
17
+ * handle, nor taken in a change. Whoever has one already keeps it (and is still mentioned by it).
18
+ */
19
+ const STAFF = [
20
+ "admin",
21
+ "admins",
22
+ "administrator",
23
+ "chirkle",
24
+ "help",
25
+ "mod",
26
+ "moderator",
27
+ "moderators",
28
+ "mods",
29
+ "official",
30
+ "root",
31
+ "security",
32
+ "staff",
33
+ "support",
34
+ "system",
35
+ ];
36
+ const RESERVED = new Set([...GROUP, ...STAFF]);
15
37
  /** Most people one message mentions. */
16
38
  const MAX_MENTIONS = 20;
17
39
  /** Most people GET /api/chat/mentionable suggests. */
@@ -3,8 +3,8 @@
3
3
 
4
4
  const CSP = [
5
5
  "default-src 'self'",
6
- // The hash is index.html's inline theme script (web/src/theme.ts); tests/unit/build/csp.test.ts checks it.
7
- "script-src 'self' 'sha256-lMI93IRRLFIlto6GZfZdfPFeIgbs3CJfe2ncDiU/aWw='",
6
+ // The hash is index.html's inline theme and text size script (web/src/theme.ts); tests/unit/build/csp.test.ts checks it.
7
+ "script-src 'self' 'sha256-mOQF+ckehOwPXg3QQaTKo5nz/mkpPjspccYc517TGsE='",
8
8
  "style-src 'self'",
9
9
  "connect-src 'self'",
10
10
  "img-src 'self' data: blob:",