chirkle 0.3.0 → 0.4.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 (156) hide show
  1. package/README.md +99 -47
  2. package/bin/release/darwin-amd64/chirkle-server +4 -0
  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 +9 -6
  7. package/pb_hooks/federation/inbox.js +2 -69
  8. package/pb_hooks/federation/messages.js +5 -3
  9. package/pb_hooks/federation/net.js +1 -0
  10. package/pb_hooks/federation/people.js +1 -0
  11. package/pb_hooks/federation.pb.js +1 -8
  12. package/pb_hooks/lib/access.js +33 -10
  13. package/pb_hooks/lib/account.js +542 -6
  14. package/pb_hooks/lib/anonymous.js +2 -129
  15. package/pb_hooks/lib/bulk.js +1 -2
  16. package/pb_hooks/lib/collections.js +4 -4
  17. package/pb_hooks/lib/dms.js +1 -1
  18. package/pb_hooks/lib/files.js +82 -120
  19. package/pb_hooks/lib/handles.js +2 -2
  20. package/pb_hooks/lib/inbox.js +40 -54
  21. package/pb_hooks/lib/invites.js +266 -0
  22. package/pb_hooks/lib/media.js +5 -43
  23. package/pb_hooks/lib/messages.js +72 -117
  24. package/pb_hooks/lib/moderation.js +2 -16
  25. package/pb_hooks/lib/reactions.js +28 -4
  26. package/pb_hooks/lib/retention.js +88 -0
  27. package/pb_hooks/lib/site.js +13 -2
  28. package/pb_hooks/lib/stats.js +6 -34
  29. package/pb_hooks/lib/users.js +88 -7
  30. package/pb_hooks/lib/worker.js +22 -1
  31. package/pb_hooks/main.pb.js +85 -94
  32. package/pb_hooks/telegram/api.js +64 -12
  33. package/pb_hooks/telegram/inbound.js +158 -31
  34. package/pb_hooks/telegram/links.js +4 -3
  35. package/pb_hooks/telegram/outbound.js +86 -45
  36. package/pb_hooks/telegram/people.js +3 -3
  37. package/pb_hooks/telegram/worker.js +59 -15
  38. package/pb_migrations/1760000045_password_reset.js +38 -0
  39. package/pb_migrations/1760000047_telegram_supergroup_ids.js +51 -0
  40. package/pb_migrations/1760000048_inbox_reactions_merged.js +24 -0
  41. package/pb_migrations/1760000049_inbox_room_index.js +22 -0
  42. package/pb_migrations/1760000050_messages_unread_index.js +22 -0
  43. package/pb_migrations/1760000051_users_kind.js +31 -0
  44. package/pb_migrations/1760000052_deleted_accounts.js +19 -0
  45. package/pb_migrations/1760000053_account_jobs.js +45 -0
  46. package/pb_migrations/1760000054_room_invites.js +39 -0
  47. package/pb_migrations/1760000055_invite_barred.js +16 -0
  48. package/pb_migrations/1760000056_telegram_fetch.js +21 -0
  49. package/pb_public/assets/{access-PB77EH4F.css → access-GPRLOZOO.css} +2 -2
  50. package/pb_public/assets/{access-PB77EH4F.css.map → access-GPRLOZOO.css.map} +2 -2
  51. package/pb_public/assets/access-UK3L54NR.js +2 -0
  52. package/pb_public/assets/access-UK3L54NR.js.map +7 -0
  53. package/pb_public/assets/account-CT2BVMAX.css +2 -0
  54. package/pb_public/assets/account-CT2BVMAX.css.map +7 -0
  55. package/pb_public/assets/account-api-J6A6IYVX.js +2 -0
  56. package/pb_public/assets/account-api-J6A6IYVX.js.map +7 -0
  57. package/pb_public/assets/app-HB3NZHQ2.js +3 -0
  58. package/pb_public/assets/app-HB3NZHQ2.js.map +7 -0
  59. package/pb_public/assets/app-XJ73EU5O.css +2 -0
  60. package/pb_public/assets/app-XJ73EU5O.css.map +7 -0
  61. package/pb_public/assets/chunk-56ACD3V5.js +2 -0
  62. package/pb_public/assets/chunk-56ACD3V5.js.map +7 -0
  63. package/pb_public/assets/chunk-AG73QNUN.js +2 -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.map +7 -0
  67. package/pb_public/assets/chunk-DZC4SY4M.js +2 -0
  68. package/pb_public/assets/chunk-DZC4SY4M.js.map +7 -0
  69. package/pb_public/assets/chunk-N2OFGBCZ.js +2 -0
  70. package/pb_public/assets/chunk-N2OFGBCZ.js.map +7 -0
  71. package/pb_public/assets/chunk-OKIIBH7O.js +2 -0
  72. package/pb_public/assets/chunk-OKIIBH7O.js.map +7 -0
  73. package/pb_public/assets/chunk-RPCBA7VF.js +2 -0
  74. package/pb_public/assets/chunk-RPCBA7VF.js.map +7 -0
  75. package/pb_public/assets/chunk-UZDXAORM.js +2 -0
  76. package/pb_public/assets/chunk-UZDXAORM.js.map +7 -0
  77. package/pb_public/assets/chunk-VTOUI25E.js +4 -0
  78. package/pb_public/assets/chunk-VTOUI25E.js.map +7 -0
  79. package/pb_public/assets/chunk-WR25F7FU.js +2 -0
  80. package/pb_public/assets/chunk-WR25F7FU.js.map +7 -0
  81. package/pb_public/assets/{emoji-VA2WCEAC.css → emoji-WWNPWCF3.css} +2 -2
  82. package/pb_public/assets/{emoji-VA2WCEAC.css.map → emoji-WWNPWCF3.css.map} +2 -2
  83. package/pb_public/assets/{emoji-picker-65VVVGYW.js → emoji-picker-K6JTK2GV.js} +4 -4
  84. package/pb_public/assets/emoji-picker-K6JTK2GV.js.map +7 -0
  85. package/pb_public/assets/forward-267HRNPY.js +2 -0
  86. package/pb_public/assets/forward-267HRNPY.js.map +7 -0
  87. package/pb_public/assets/inbox-CLMYESNI.js +2 -0
  88. package/pb_public/assets/inbox-CLMYESNI.js.map +7 -0
  89. package/pb_public/assets/invite-OGT5E2MZ.js +2 -0
  90. package/pb_public/assets/invite-OGT5E2MZ.js.map +7 -0
  91. package/pb_public/assets/invite-api-7G7XPXQW.js +2 -0
  92. package/pb_public/assets/invite-api-7G7XPXQW.js.map +7 -0
  93. package/pb_public/assets/lazy-H3KIJVB5.js +2 -0
  94. package/pb_public/assets/lazy-H3KIJVB5.js.map +7 -0
  95. package/pb_public/assets/login-TK6K4WGB.js +2 -0
  96. package/pb_public/assets/login-TK6K4WGB.js.map +7 -0
  97. package/pb_public/assets/media-WZ4653L5.js +2 -0
  98. package/pb_public/assets/media-WZ4653L5.js.map +7 -0
  99. package/pb_public/assets/mention-suggest-ODJD2IC5.js +2 -0
  100. package/pb_public/assets/mention-suggest-ODJD2IC5.js.map +7 -0
  101. package/pb_public/assets/notify-EPDM772N.js +2 -0
  102. package/pb_public/assets/notify-EPDM772N.js.map +7 -0
  103. package/pb_public/assets/profile-3R6S5QYS.js +2 -0
  104. package/pb_public/assets/profile-3R6S5QYS.js.map +7 -0
  105. package/pb_public/assets/search-WCHOGAJQ.js +2 -0
  106. package/pb_public/assets/search-WCHOGAJQ.js.map +7 -0
  107. package/pb_public/assets/stats-GTO2H6PG.js +2 -0
  108. package/pb_public/assets/stats-GTO2H6PG.js.map +7 -0
  109. package/pb_public/assets/switcher-TFSO45KV.js +2 -0
  110. package/pb_public/assets/switcher-TFSO45KV.js.map +7 -0
  111. package/pb_public/assets/user-search-3HQOCQWL.js +2 -0
  112. package/pb_public/assets/user-search-3HQOCQWL.js.map +7 -0
  113. package/pb_public/assets/viewer-2Y5FJBW4.js +2 -0
  114. package/pb_public/assets/viewer-2Y5FJBW4.js.map +7 -0
  115. package/pb_public/index.html +10 -2
  116. package/pb_public/stats.html +1 -1
  117. package/scripts/service.mjs +201 -0
  118. package/scripts/start.mjs +21 -17
  119. package/pb_hooks/lib/enrich.js +0 -75
  120. package/pb_hooks/lib/lists.js +0 -179
  121. package/pb_hooks/lib/live.js +0 -137
  122. package/pb_hooks/lib/reads.js +0 -183
  123. package/pb_public/assets/access-GUDTDXIP.js +0 -2
  124. package/pb_public/assets/access-GUDTDXIP.js.map +0 -7
  125. package/pb_public/assets/app-3WX5JYL2.js +0 -3
  126. package/pb_public/assets/app-3WX5JYL2.js.map +0 -7
  127. package/pb_public/assets/app-WAFKVN2H.css +0 -2
  128. package/pb_public/assets/app-WAFKVN2H.css.map +0 -7
  129. package/pb_public/assets/emoji-picker-65VVVGYW.js.map +0 -7
  130. package/pb_public/assets/forward-66PELNWT.js +0 -2
  131. package/pb_public/assets/forward-66PELNWT.js.map +0 -7
  132. package/pb_public/assets/inbox-TZJWPRTG.js +0 -2
  133. package/pb_public/assets/inbox-TZJWPRTG.js.map +0 -7
  134. package/pb_public/assets/lazy-4CXRBHHM.js +0 -2
  135. package/pb_public/assets/lazy-4CXRBHHM.js.map +0 -7
  136. package/pb_public/assets/login-G7Y44CJ7.js +0 -2
  137. package/pb_public/assets/login-G7Y44CJ7.js.map +0 -7
  138. package/pb_public/assets/media-FPRU2QH5.js +0 -2
  139. package/pb_public/assets/media-FPRU2QH5.js.map +0 -7
  140. package/pb_public/assets/mention-suggest-R7MXUH6R.js +0 -2
  141. package/pb_public/assets/mention-suggest-R7MXUH6R.js.map +0 -7
  142. package/pb_public/assets/notify-RQ6ZLR46.js +0 -2
  143. package/pb_public/assets/notify-RQ6ZLR46.js.map +0 -7
  144. package/pb_public/assets/profile-2CNVT2KX.js +0 -2
  145. package/pb_public/assets/profile-2CNVT2KX.js.map +0 -7
  146. package/pb_public/assets/search-3UT4HMES.js +0 -2
  147. package/pb_public/assets/search-3UT4HMES.js.map +0 -7
  148. package/pb_public/assets/stats-JX52AQCO.js +0 -2
  149. package/pb_public/assets/stats-JX52AQCO.js.map +0 -7
  150. package/pb_public/assets/switcher-CEUKRLEY.js +0 -2
  151. package/pb_public/assets/switcher-CEUKRLEY.js.map +0 -7
  152. package/pb_public/assets/user-search-7GNEIXMN.js +0 -2
  153. package/pb_public/assets/user-search-7GNEIXMN.js.map +0 -7
  154. package/pb_public/assets/viewer-DXT7SKOU.js +0 -2
  155. package/pb_public/assets/viewer-DXT7SKOU.js.map +0 -7
  156. package/scripts/fetch-pocketbase.sh +0 -63
@@ -0,0 +1,266 @@
1
+ /// <reference path="../../types/pocketbase.d.ts" />
2
+ // Room invite links (DESIGN.md §44, REFACTOR P9): whoever may change a private room's members (its creator, or a
3
+ // moderator who is in it, §36) shares a link, /invite/<token>, that adds whoever opens it, signed in, to the members.
4
+ // One link per room at a time, kept in `room_invites` (migration 54, no API rules): made again, the old one stops
5
+ // working; revoked, it is deleted. It expires after 1, 7 or 30 days, and stops working once the room is no longer
6
+ // private (the rooms update hook deletes it, dropInvites) or while it is archived.
7
+ //
8
+ // The token is 24 random letters and digits (about 143 bits): it is the whole secret, so no rate limit guards it.
9
+
10
+ const { MAX_MEMBERS, accessOf, sees, viewerOf } = require(`${__hooks}/lib/access.js`);
11
+ const { isDm } = require(`${__hooks}/lib/rooms.js`);
12
+
13
+ /** How long a new link works, in days: the choices the clients offer. */
14
+ const DAYS = [1, 7, 30];
15
+ /** When none is given. */
16
+ const DEFAULT_DAYS = 7;
17
+ const TOKEN_LENGTH = 24;
18
+ /** What a link that doesn't work (any more) says: never which of the reasons, so a token tells nothing. */
19
+ const GONE = "This invite link has expired or was revoked.";
20
+
21
+ /** PocketBase's date text for `ms`. @param {number} ms */
22
+ const dbDate = (ms) => new Date(ms).toISOString().replace("T", " ");
23
+ /** @param {string} s PocketBase's date text */
24
+ const msOf = (s) => Date.parse(s.replace(" ", "T"));
25
+
26
+ /**
27
+ * The room's invite row, or null.
28
+ * @param {core.App} app
29
+ * @param {string} roomId
30
+ */
31
+ function inviteOf(app, roomId) {
32
+ try {
33
+ return app.findFirstRecordByFilter("room_invites", "room = {:r}", { r: roomId });
34
+ } catch {
35
+ return null;
36
+ }
37
+ }
38
+
39
+ /**
40
+ * Those the room's managers took out of its members while this link worked (QA BUG-280): it doesn't let them back in.
41
+ * @param {core.Record} inv
42
+ */
43
+ function barredOf(inv) {
44
+ // A JSON field reads as its raw text.
45
+ let v;
46
+ try {
47
+ v = JSON.parse(inv.getString("barred") || "[]");
48
+ } catch {
49
+ return [];
50
+ }
51
+ return Array.isArray(v) ? v.filter((x) => typeof x === "string") : [];
52
+ }
53
+
54
+ /** Has the link run out? @param {core.Record} inv @param {number} [now] */
55
+ const expired = (inv, now = Date.now()) => msOf(inv.getString("expires")) <= now;
56
+
57
+ /**
58
+ * What the managing routes answer: the room's working link, or null.
59
+ * @param {core.Record | null} inv
60
+ */
61
+ function answer(inv) {
62
+ if (!inv || expired(inv)) return { invite: null };
63
+ return {
64
+ invite: {
65
+ token: inv.getString("token"),
66
+ created: inv.getString("created"),
67
+ expires: inv.getString("expires"),
68
+ uses: inv.getInt("uses"),
69
+ },
70
+ };
71
+ }
72
+
73
+ /**
74
+ * The room in the path, for someone who may manage its link: signed in, sees it, its creator or a moderator, not a DM,
75
+ * not a copy of another instance's room (§33.5: its members are changed there). Throws what to answer otherwise.
76
+ * @param {core.RequestEvent} e
77
+ */
78
+ function managedRoom(e) {
79
+ if (!e.auth) throw new UnauthorizedError("The request requires a logged-in user.");
80
+ const id = e.request?.pathValue("room") ?? "";
81
+ let room;
82
+ try {
83
+ room = e.app.findRecordById("rooms", id);
84
+ } catch {
85
+ throw new NotFoundError("This room doesn't exist.");
86
+ }
87
+ if (!sees(viewerOf(e.auth), accessOf(room))) throw new NotFoundError("This room doesn't exist.");
88
+ const { canManage } = require(`${__hooks}/lib/moderation.js`);
89
+ if (isDm(room) || !canManage(room, e.auth)) {
90
+ throw new ForbiddenError("Only the room's creator or a moderator can share an invite link.");
91
+ }
92
+ if (room.getString("peer")) throw new BadRequestError("This room's home is another instance: invite people there.");
93
+ return room;
94
+ }
95
+
96
+ /**
97
+ * GET /api/chat/rooms/{room}/invite → { invite: { token, created, expires, uses } | null }: the room's working link.
98
+ * @param {core.RequestEvent} e
99
+ */
100
+ function get(e) {
101
+ const room = managedRoom(e);
102
+ if (room.getString("visibility") !== "private") return e.json(200, { invite: null });
103
+ return e.json(200, answer(inviteOf(e.app, room.id)));
104
+ }
105
+
106
+ /**
107
+ * POST /api/chat/rooms/{room}/invite { days: 1 | 7 | 30 } → a new link (as GET answers), replacing the room's last one.
108
+ * Private rooms only, and not archived ones.
109
+ * @param {core.RequestEvent} e
110
+ */
111
+ function create(e) {
112
+ const room = managedRoom(e);
113
+ if (room.getString("visibility") !== "private") throw new BadRequestError("Only a private room has an invite link.");
114
+ if (room.getBool("archived")) throw new BadRequestError("This room is archived.");
115
+ const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body ?? {});
116
+ const days = body.days === undefined || body.days === null ? DEFAULT_DAYS : body.days;
117
+ if (typeof days !== "number" || !DAYS.includes(days)) {
118
+ throw new BadRequestError("Failed to make the invite link.", {
119
+ days: new ValidationError("validation_invalid_value", `A link works for ${DAYS.join(", ")} days.`),
120
+ });
121
+ }
122
+ /** @type {core.Record | null} */
123
+ let made = null;
124
+ e.app.runInTransaction((tx) => {
125
+ const old = inviteOf(tx, room.id);
126
+ if (old) tx.delete(old);
127
+ const inv = new Record(tx.findCollectionByNameOrId("room_invites"));
128
+ inv.set("room", room.id);
129
+ inv.set("token", $security.randomString(TOKEN_LENGTH));
130
+ inv.set("created_by", e.auth?.id ?? "");
131
+ inv.set("expires", dbDate(Date.now() + days * 24 * 3600_000));
132
+ inv.set("uses", 0);
133
+ tx.save(inv);
134
+ made = inv;
135
+ });
136
+ return e.json(200, answer(made));
137
+ }
138
+
139
+ /**
140
+ * DELETE /api/chat/rooms/{room}/invite → 204: the link stops working. Nothing to revoke is fine too.
141
+ * @param {core.RequestEvent} e
142
+ */
143
+ function revoke(e) {
144
+ const room = managedRoom(e);
145
+ const inv = inviteOf(e.app, room.id);
146
+ if (inv) e.app.delete(inv);
147
+ return e.noContent(204);
148
+ }
149
+
150
+ /**
151
+ * The working invite the path's token names, with its room; null when there is none (unknown, expired, revoked, the
152
+ * room no longer private or archived, a DM).
153
+ * @param {core.App} app
154
+ * @param {string} token
155
+ */
156
+ function working(app, token) {
157
+ if (typeof token !== "string" || token.length !== TOKEN_LENGTH) return null;
158
+ let inv;
159
+ try {
160
+ inv = app.findFirstRecordByFilter("room_invites", "token = {:t}", { t: token });
161
+ } catch {
162
+ return null;
163
+ }
164
+ if (expired(inv)) return null;
165
+ let room;
166
+ try {
167
+ room = app.findRecordById("rooms", inv.getString("room"));
168
+ } catch {
169
+ return null;
170
+ }
171
+ if (isDm(room) || room.getString("visibility") !== "private" || room.getBool("archived")) return null;
172
+ return { inv, room };
173
+ }
174
+
175
+ /**
176
+ * GET /api/chat/invites/{token} → { room: { id, name, members }, by, expires, member }: what the link is to, for its
177
+ * page (guests too: the link is the secret, and they are asked to log in or sign up to join). `members` counts its
178
+ * members; `by` is who made the link; `member` says whether you are in already.
179
+ * 404 when it doesn't work.
180
+ * @param {core.RequestEvent} e
181
+ */
182
+ function preview(e) {
183
+ const found = working(e.app, e.request?.pathValue("token") ?? "");
184
+ if (!found) throw new NotFoundError(GONE);
185
+ const { inv, room } = found;
186
+ const members = room.getStringSlice("members");
187
+ let by = "";
188
+ try {
189
+ by = e.app.findRecordById("users", inv.getString("created_by")).getString("name");
190
+ } catch {}
191
+ const me = e.auth && !e.auth.isSuperuser() ? e.auth.id : "";
192
+ // Taken out of the room by its managers: for them the link doesn't work (the same answer as any dead link).
193
+ if (me && barredOf(inv).includes(me)) throw new NotFoundError(GONE);
194
+ return e.json(200, {
195
+ room: { id: room.id, name: room.getString("name"), members: members.length },
196
+ by,
197
+ expires: inv.getString("expires"),
198
+ member: !!me && (members.includes(me) || room.getString("created_by") === me),
199
+ });
200
+ }
201
+
202
+ /**
203
+ * POST /api/chat/invites/{token} → { room }: join the room as a member (signed in). Already in, nothing changes. 404
204
+ * when the link doesn't work; 400 when the room is full. The room's save goes through its hooks, so whoever is in it
205
+ * (the new member too) hears of it live (§23.4), and a shared room's peers are told (§33).
206
+ * @param {core.RequestEvent} e
207
+ */
208
+ function join(e) {
209
+ if (!e.auth || e.auth.isSuperuser()) throw new UnauthorizedError("Log in to join the room.");
210
+ const me = e.auth.id;
211
+ const token = e.request?.pathValue("token") ?? "";
212
+ /** @type {string} */
213
+ let roomId = "";
214
+ e.app.runInTransaction((tx) => {
215
+ const found = working(tx, token);
216
+ if (!found) throw new NotFoundError(GONE);
217
+ const { inv, room } = found;
218
+ if (barredOf(inv).includes(me)) throw new NotFoundError(GONE);
219
+ roomId = room.id;
220
+ const members = room.getStringSlice("members");
221
+ if (members.includes(me) || room.getString("created_by") === me) return;
222
+ if (members.length >= MAX_MEMBERS) throw new BadRequestError(`This room is full: it has ${MAX_MEMBERS} members.`);
223
+ room.set("members", [...members, me]);
224
+ tx.save(room);
225
+ inv.set("uses", inv.getInt("uses") + 1);
226
+ tx.save(inv);
227
+ });
228
+ return e.json(200, { room: roomId });
229
+ }
230
+
231
+ /**
232
+ * rooms update (saved): a room that stopped being private has no invite link. Made private again, it needs a new one,
233
+ * so an old link doesn't come back to life. Only on that change: every DM message saves its room.
234
+ * @param {core.App} app
235
+ * @param {string} wasVisibility
236
+ * @param {core.Record} room
237
+ */
238
+ function dropInvites(app, wasVisibility, room) {
239
+ if (wasVisibility !== "private" || room.getString("visibility") === "private") return;
240
+ const inv = inviteOf(app, room.id);
241
+ if (inv) app.delete(inv);
242
+ }
243
+
244
+ /**
245
+ * rooms update request (saved): whoever the request took out of a private room's members can't come back with its
246
+ * working link (QA BUG-280); its managers make a new link to let everyone in again, or add them back. Not the joins
247
+ * themselves, nor an account's delete (§43.3): those are saved by the server, not by a request.
248
+ * @param {core.App} app
249
+ * @param {string[]} wasMembers
250
+ * @param {core.Record} room
251
+ */
252
+ function barRemoved(app, wasMembers, room) {
253
+ if (room.getString("visibility") !== "private") return;
254
+ const now = new Set(room.getStringSlice("members"));
255
+ const gone = wasMembers.filter((u) => !now.has(u));
256
+ const inv = inviteOf(app, room.id);
257
+ if (!inv) return;
258
+ const was = barredOf(inv);
259
+ // Added back by hand: barred no more.
260
+ const barred = [...new Set([...was, ...gone])].filter((u) => !now.has(u));
261
+ if (barred.length === was.length && barred.every((u) => was.includes(u))) return;
262
+ inv.set("barred", barred);
263
+ app.save(inv);
264
+ }
265
+
266
+ module.exports = { DAYS, DEFAULT_DAYS, GONE, get, create, revoke, preview, join, dropInvites, barRemoved };
@@ -17,9 +17,9 @@
17
17
  // - GET /api/chat/posters/{message}/{file}: a video's poster, for whoever has the video's URL (§37.3).
18
18
 
19
19
  const { gridAuthor } = require(`${__hooks}/lib/anonymous.js`);
20
- const { visibleRoom } = require(`${__hooks}/lib/access.js`);
20
+ const { viewerOf, visibleRoom } = require(`${__hooks}/lib/access.js`);
21
21
  const { HEADER_BYTES, shownSize } = require(`${__hooks}/lib/images.js`);
22
- const { cleanupLater, ext, homeKeyOf, isMedia, isVideo, keyOf, posterKeyOf, shownBy, thumbsDirOf } = require(`${__hooks}/lib/files.js`);
22
+ const { cleanupLater, ext, homeKeyOf, isMedia, isVideo, keyOf, posterKeyOf, thumbsDirOf } = require(`${__hooks}/lib/files.js`);
23
23
 
24
24
  /** The images PocketBase makes thumbnails of (avif it serves as it is). */
25
25
  const THUMB_EXT = ["jpg", "jpeg", "png", "gif", "webp"];
@@ -103,7 +103,7 @@ function drop(app, id) {
103
103
  */
104
104
  function list(e) {
105
105
  const room = e.request?.pathValue("room") ?? "";
106
- if (!visibleRoom(e.app, room, e.auth?.id ?? "")) throw new NotFoundError();
106
+ if (!visibleRoom(e.app, room, viewerOf(e.auth))) throw new NotFoundError();
107
107
  const q = e.request?.url?.query();
108
108
  const sent = q?.get("sent") ?? "";
109
109
  const limit = Math.min(MAX_PAGE, Math.max(1, Number.parseInt(q?.get("limit") ?? "", 10) || PAGE));
@@ -166,45 +166,7 @@ function list(e) {
166
166
 
167
167
  // ---------------------------------------------------------------- posters
168
168
 
169
- /**
170
- * GET /api/chat/posters/{message}/{file}: a video's poster frame, for whoever has the video's URL (§37.3): the message
171
- * (or as a forward, its original) shows the file. A `token` is ignored. 404 for anything else, and until the worker
172
- * has made it.
173
- * @param {core.RequestEvent} e
174
- */
175
- function poster(e) {
176
- servePoster(e, "messages", e.request?.pathValue("message") ?? "");
177
- }
178
-
179
- /**
180
- * GET /api/chat/posters/items/{item}/{file}: a collection item's poster (§31), as the item's file is served.
181
- * @param {core.RequestEvent} e
182
- */
183
- function itemPoster(e) {
184
- servePoster(e, "collection_items", e.request?.pathValue("item") ?? "");
185
- }
186
-
187
- /**
188
- * The poster of the video `file` that record `id` of `collection` shows.
189
- * @param {core.RequestEvent} e
190
- * @param {string} collection
191
- * @param {string} id
192
- */
193
- function servePoster(e, collection, id) {
194
- const file = e.request?.pathValue("file") ?? "";
195
- const row = isVideo(file) ? shownBy(e.app, collection, id, file) : null;
196
- if (!row) throw new NotFoundError();
197
- const fs = e.app.newFilesystem();
198
- try {
199
- const key = posterKeyOf(row);
200
- if (!fs.exists(key)) throw new NotFoundError();
201
- // Never changes under one name: a new upload gets a new file name.
202
- e.response.header().set("Cache-Control", "private, max-age=2592000");
203
- fs.serve(e.response, /** @type {any} */ (e.request), key, POSTER);
204
- } finally {
205
- fs.close();
206
- }
207
- }
169
+ // GET /api/chat/posters/… (a video's poster, for whoever has the video's URL) is served in Go: server/files.go.
208
170
 
209
171
  // ---------------------------------------------------------------- the worker
210
172
 
@@ -632,4 +594,4 @@ function tick(e) {
632
594
  return e.noContent(204);
633
595
  }
634
596
 
635
- module.exports = { add, drop, list, poster, itemPoster, run, wake, tick };
597
+ module.exports = { add, drop, list, run, wake, tick };
@@ -1,9 +1,9 @@
1
1
  /// <reference path="../../types/pocketbase.d.ts" />
2
2
  // messages hooks (DESIGN.md §5.6, §17, §19, §20, §21, §28): text, attachments, replies, forwards, soft delete, edit stamps.
3
- // A forward (§21.3) has no text or files of its own: it shows those of the message in `forward_of` (showOriginal).
3
+ // A forward (§21.3) has no text or files of its own: it shows those of the message in `forward_of` (server/enrich.go
4
+ // showOriginal, in every answer and live event).
4
5
 
5
- const { accessOf, canSee, canWrite, visibleRoom } = require(`${__hooks}/lib/access.js`);
6
- const { inCheckedRoom, markChecked } = require(`${__hooks}/lib/enrich.js`);
6
+ const { accessOf, canSee, canWrite } = require(`${__hooks}/lib/access.js`);
7
7
  const { fieldError, recordOf } = require(`${__hooks}/lib/records.js`);
8
8
  const { dmRefusal } = require(`${__hooks}/lib/dms.js`);
9
9
  const { isDm } = require(`${__hooks}/lib/rooms.js`);
@@ -87,7 +87,23 @@ function postService(app, roomId, text) {
87
87
  }
88
88
 
89
89
  /**
90
- * messages create: trim + non-empty text, room must be active (§5.6).
90
+ * Set on a message by prepareCreate, a custom key (neither stored nor sent): the create request checked it, its
91
+ * mentions included, before the save's transaction, which doesn't do it again.
92
+ */
93
+ const CHECKED = "@checked";
94
+
95
+ /**
96
+ * Set on a message by lib/account.js erase (a custom key, neither stored nor sent): deleted because its author deleted
97
+ * their account and its messages (§43), which archived rooms don't refuse.
98
+ */
99
+ const ERASING = "@erasing";
100
+
101
+ /** Was this message checked by its create request already (prepareCreate)? @param {core.Record} rec */
102
+ const checked = (rec) => rec.get(CHECKED) === true;
103
+
104
+ /**
105
+ * messages create: trim + non-empty text, room must be active (§5.6). A create request's message was checked before
106
+ * the transaction (prepareCreate); every other create (service messages, forwards, the bridges) is checked here.
91
107
  * @param {core.RecordEvent} e
92
108
  */
93
109
  function beforeMessageCreate(e) {
@@ -98,18 +114,27 @@ function beforeMessageCreate(e) {
98
114
  rec.set("file_names", {});
99
115
  rec.set("file_dims", {});
100
116
  }
117
+ rec.set("reactions", []); // only POST /api/chat/reactions adds them (§20.2)
118
+ rec.set("previews", []); // only the previews worker sets them (§28)
119
+ if (!checked(rec)) checkCreate(e.app, rec, fileNames(rec).length > 0);
120
+ }
121
+
122
+ /**
123
+ * What a new message must be: text that isn't blank unless it has files (`hasFiles`) or is a forward, in a room that
124
+ * is active and that its author can see and post in; a reply or forward of a message that is still there.
125
+ * @param {core.App} app
126
+ * @param {core.Record} rec
127
+ * @param {boolean} hasFiles
128
+ */
129
+ function checkCreate(app, rec, hasFiles) {
101
130
  if (isService(rec)) {
102
131
  // Made only by postService (no request can leave out the author): text alone, in any room that isn't archived.
103
132
  assertText(rec);
104
- rec.set("reactions", []);
105
- rec.set("previews", []);
106
- activeRoom(e.app, rec.getString("room"));
133
+ activeRoom(app, rec.getString("room"));
107
134
  return;
108
135
  }
109
- assertText(rec, fileNames(rec).length > 0 || isForward(rec));
110
- rec.set("reactions", []); // only POST /api/chat/reactions adds them (§20.2)
111
- rec.set("previews", []); // only the previews worker sets them (§28)
112
- const room = activeRoom(e.app, rec.getString("room"));
136
+ assertText(rec, hasFiles || isForward(rec));
137
+ const room = activeRoom(app, rec.getString("room"));
113
138
  // Defense in depth for the members-only create rule (§16.3, §23.1): DMs and private rooms.
114
139
  if (room && !canSee(accessOf(room), rec.getString("author"))) {
115
140
  throw fieldError("room", isDm(room) ? "You are not a member of this conversation." : "You are not a member of this room.");
@@ -117,13 +142,13 @@ function beforeMessageCreate(e) {
117
142
  // ... and for who may post in it (§23.6): forwards and the Telegram bridge come through here too.
118
143
  if (room && !canWrite(room, rec.getString("author"))) throw fieldError("room", "Only some people can post in this room.");
119
144
  if (room && isDm(room)) {
120
- const refused = dmRefusal(e.app, rec.getString("author"), room.getStringSlice("members"));
145
+ const refused = dmRefusal(app, rec.getString("author"), room.getStringSlice("members"));
121
146
  if (refused) throw fieldError("room", refused);
122
147
  }
123
148
  // Posted in an anonymous room (§35): its author is kept to themselves for good. DMs never are.
124
149
  rec.set("anonymous", !!room && !isDm(room) && room.getBool("anonymous"));
125
- assertReplyTarget(e.app, rec);
126
- rec.set("forwarded_anonymous", assertForwardTarget(e.app, rec));
150
+ assertReplyTarget(app, rec);
151
+ rec.set("forwarded_anonymous", assertForwardTarget(app, rec));
127
152
  }
128
153
 
129
154
  /**
@@ -239,12 +264,16 @@ function beforeMessageCreateRequest(e) {
239
264
  }
240
265
 
241
266
  /**
242
- * messages create through the API, in the request's transaction: the attachments are this request's uploads
243
- * (`files`) and the collection items it names (`items`, §31), each a `files` row (§37), in that order. Names in
244
- * the body are never taken: whatever it says of `files`, `file_names`, `file_dims` or `file_sources` is replaced.
267
+ * messages create through the API, before its transaction (docs/PERF.md §12): what beforeMessageCreate and the
268
+ * mentions would check and read inside it, and the uploads, each stored with its `files` row (§37) on its own. The
269
+ * write connection is then held only for the inserts, not for the reads, the JS or the uploads' round trips to S3.
270
+ * The attachments are this request's uploads (`files`) and the collection items it names (`items`, §31), in that
271
+ * order; names in the body are never taken (setRequestFiles replaces them). The create rule was checked before this,
272
+ * outside any transaction too. If the save then fails, `uploaded` are to be dropped (lib/files.js discard).
245
273
  * @param {core.RecordRequestEvent} e
274
+ * @returns {{ rows: core.Record[], uploaded: core.Record[], sources: Record<string, string> }}
246
275
  */
247
- function setRequestFiles(e) {
276
+ function prepareCreate(e) {
248
277
  const rec = recordOf(e);
249
278
  /** @type {filesystem.File[]} */
250
279
  const uploads = [];
@@ -260,7 +289,23 @@ function setRequestFiles(e) {
260
289
  if (uploads.length + items.length > files.MAX_FILES) throw fieldError("files", `At most ${files.MAX_FILES} files.`);
261
290
  // The create rule would refuse it anyway: store nothing first.
262
291
  if (uploads.length && !e.auth) throw new ForbiddenError("Only signed-in users can post.");
263
- files.setMessageFiles(e.app, rec, [...files.fromUploads(e.app, uploads), ...items], sources);
292
+ checkCreate(e.app, rec, uploads.length + items.length > 0);
293
+ const fed = require(`${__hooks}/lib/features.js`).federation(e.app);
294
+ require(`${__hooks}/lib/handles.js`).setMentions(e.app, rec, !!fed && fed.messages.isFromPeer(e.app, rec));
295
+ rec.set(CHECKED, true);
296
+ const uploaded = files.fromUploads(e.app, uploads);
297
+ return { rows: [...uploaded, ...items], uploaded, sources };
298
+ }
299
+
300
+ /**
301
+ * messages create through the API: its attachments (prepareCreate's rows) set on it, linked by its save, in the
302
+ * save's transaction (main.pb.js). Whatever the body said of `files`, `file_names`, `file_dims` or `file_sources`
303
+ * is replaced.
304
+ * @param {core.RecordRequestEvent} e
305
+ * @param {{ rows: core.Record[], sources: Record<string, string> }} prepared
306
+ */
307
+ function setRequestFiles(e, prepared) {
308
+ require(`${__hooks}/lib/files.js`).setMessageFiles(e.app, recordOf(e), prepared.rows, prepared.sources, true);
264
309
  }
265
310
 
266
311
  /**
@@ -292,7 +337,9 @@ function beforeMessageUpdate(e) {
292
337
  // A message deleted for good (by a superuser, or with its room) is already gone when PocketBase unsets the
293
338
  // reply_to of its replies (§19.1). Let that save through: the guards below would refuse it, and with it the delete.
294
339
  if (replyTargetRemoved(e.app, rec, orig) || forwardSourceRemoved(e.app, rec, orig) || originalRemoved(e.app, rec, orig)) return;
295
- activeRoom(e.app, orig.getString("room"));
340
+ // A deleted account's messages, deleted with it at its person's wish (§43), go from archived rooms too.
341
+ const erasing = rec.get(ERASING) === true && rec.getBool("deleted");
342
+ if (!erasing) activeRoom(e.app, orig.getString("room"));
296
343
 
297
344
  if (orig.getBool("deleted")) {
298
345
  // Deletion is final; API rules already refuse this, so this only guards superuser edits.
@@ -353,7 +400,7 @@ function beforeMessageUpdateRequest(e) {
353
400
  const rec = recordOf(e);
354
401
  // Uploads and modifiers aren't a file field's any more (§37), so the update rule doesn't see them all: refused
355
402
  // here, not dropped.
356
- const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body);
403
+ const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body ?? {});
357
404
  for (const key of ["files", "+files", "files+", "files-"]) {
358
405
  let n = 0;
359
406
  try {
@@ -387,7 +434,7 @@ function changesForwards(rec) {
387
434
 
388
435
  /**
389
436
  * After an edit or delete of a message: its forwards are saved again (nothing in them changes), so everyone who sees
390
- * one hears of it live, with the original as it is now (showOriginal). They can't hear of the original itself: it is
437
+ * one hears of it live, with the original as it is now (server/enrich.go showOriginal). They can't hear of the original itself: it is
391
438
  * in a room they may not see. Forwards in archived rooms are left alone: they can't be saved, and show it once loaded.
392
439
  * @param {core.App} app
393
440
  * @param {core.Record} rec
@@ -400,59 +447,6 @@ function touchForwards(app, rec) {
400
447
  }
401
448
  }
402
449
 
403
- /**
404
- * Every message the API answers with or sends live (lists, reads, expanded replies, realtime): a forward that isn't
405
- * deleted shows its original's text, attachments and edit stamp (§21.3), or nothing once that is deleted. Whoever
406
- * sees the forward may see those: the view rule grants it, as for the attachments' URLs (the original's).
407
- * Only in the answer: nothing is saved.
408
- * @param {core.RecordEnrichEvent} e
409
- */
410
- function showOriginal(e) {
411
- const rec = e.record;
412
- const id = rec ? rec.getString("forward_of") : "";
413
- if (!rec || !id || rec.getBool("deleted") || inCheckedRoom(e)) return;
414
- let original = null;
415
- try {
416
- original = e.app.findRecordById("messages", id);
417
- } catch {
418
- return; // being removed for good: PocketBase is about to clear forward_of
419
- }
420
- setOriginal(rec, original);
421
- }
422
-
423
- /**
424
- * The forward `rec` shows `original` (showOriginal).
425
- * @param {core.Record} rec
426
- * @param {core.Record} original
427
- */
428
- function setOriginal(rec, original) {
429
- const gone = original.getBool("deleted");
430
- rec.set("text", gone ? "" : original.getString("text"));
431
- rec.set("files", gone ? [] : original.getStringSlice("files"));
432
- rec.set("file_names", gone ? {} : original.get("file_names"));
433
- rec.set("file_sources", gone ? {} : original.get("file_sources"));
434
- rec.set("file_dims", gone ? {} : original.get("file_dims"));
435
- rec.set("previews", gone ? [] : original.get("previews"));
436
- rec.set("edited_at", gone ? "" : original.get("edited_at"));
437
- }
438
-
439
- /**
440
- * A message read only through a forward of it (the view rule grants that, §21.3) keeps to itself what would say who
441
- * is in its room: its reactions (who reacted) and the message it replies to. Only in the answer: nothing is saved.
442
- * Most messages have neither, and cost nothing here.
443
- * @param {core.RecordEnrichEvent} e
444
- */
445
- function keepToRoom(e) {
446
- const rec = e.record;
447
- const info = e.requestInfo;
448
- if (!rec || !info || info.auth?.isSuperuser() || inCheckedRoom(e)) return;
449
- const reactions = rec.getString("reactions");
450
- if (!rec.getString("reply_to") && (reactions === "" || reactions === "[]" || reactions === "null")) return;
451
- if (visibleRoom(e.app, rec.getString("room"), info.auth?.id ?? "")) return;
452
- rec.set("reactions", []);
453
- rec.set("reply_to", "");
454
- }
455
-
456
450
  /**
457
451
  * users delete (a superuser): refused while they have messages. `author` isn't required (service messages have none,
458
452
  * §5.3), so PocketBase would otherwise clear it on their messages, which would then read as the app's own notices.
@@ -465,47 +459,10 @@ function beforeUserDelete(e) {
465
459
  }
466
460
  }
467
461
 
468
- /**
469
- * Enrich the messages of rooms `rooms` (which the caller can see) in `enrich`, a call of $apis.enrichRecords, as the
470
- * hooks would, with one query for every forward's original instead of one each (lib/enrich.js).
471
- * @param {core.RequestEvent} e
472
- * @param {string[]} rooms
473
- * @param {() => core.Record[]} enrich
474
- */
475
- function enrichInRooms(e, rooms, enrich) {
476
- showOriginals(e.app, markChecked(e, rooms, enrich), new Set(rooms));
477
- }
478
-
479
- /**
480
- * showOriginal for every message in `rooms` among `records` and what they expand (an expanded reply, to any depth).
481
- * @param {core.App} app
482
- * @param {core.Record[]} records
483
- * @param {Set<string>} rooms
484
- */
485
- function showOriginals(app, records, rooms) {
486
- /** @type {core.Record[]} */
487
- const forwards = [];
488
- const seen = new Set();
489
- const visit = (/** @type {any} */ rec) => {
490
- if (!rec || seen.has(rec)) return;
491
- seen.add(rec);
492
- for (const v of Object.values(rec.expand() ?? {})) for (const r of Array.isArray(v) ? v : [v]) visit(r);
493
- if (rec.collection().name !== "messages" || !rooms.has(rec.getString("room"))) return;
494
- if (rec.getString("forward_of") && !rec.getBool("deleted")) forwards.push(rec);
495
- };
496
- for (const rec of records) visit(rec);
497
- if (!forwards.length) return;
498
- const originals = new Map(
499
- app.findRecordsByIds("messages", [...new Set(forwards.map((f) => f.getString("forward_of")))]).map((o) => [o?.id, o]),
500
- );
501
- for (const fwd of forwards) {
502
- const original = originals.get(fwd.getString("forward_of"));
503
- if (original) setOriginal(fwd, original);
504
- }
505
- }
506
-
507
462
  module.exports = {
508
- enrichInRooms,
463
+ ERASING,
464
+ checked,
465
+ prepareCreate,
509
466
  isService,
510
467
  setTextKey,
511
468
  setRequestFiles,
@@ -518,6 +475,4 @@ module.exports = {
518
475
  beforeMessageUpdateRequest,
519
476
  changesForwards,
520
477
  touchForwards,
521
- showOriginal,
522
- keepToRoom,
523
478
  };
@@ -72,20 +72,6 @@ function refuseBanned(rec, password) {
72
72
  throw new ForbiddenError("This account is banned.");
73
73
  }
74
74
 
75
- /**
76
- * Is this user a Telegram stand-in (§26.3)? Asked of tg_people whether or not the bridge is on now.
77
- * @param {core.App} app
78
- * @param {string} userId
79
- */
80
- function isStandIn(app, userId) {
81
- try {
82
- app.findFirstRecordByFilter("tg_people", "user = {:user}", { user: userId });
83
- return true;
84
- } catch {
85
- return false;
86
- }
87
- }
88
-
89
75
  /**
90
76
  * POST /api/chat/ban { user, banned } → the user's public profile with `banned`. Moderators only. Not themselves,
91
77
  * another moderator, or someone who doesn't sign in here (a linked instance's people, a Telegram stand-in); anyone
@@ -95,7 +81,7 @@ function isStandIn(app, userId) {
95
81
  function ban(e) {
96
82
  const me = e.auth;
97
83
  if (!isModerator(me)) throw new ForbiddenError("Only moderators can ban people.");
98
- const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body);
84
+ const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body ?? {});
99
85
  const what = body.banned === false ? "Failed to unban them." : "Failed to ban them.";
100
86
  const bad = (/** @type {string} */ field, /** @type {string} */ msg) =>
101
87
  new BadRequestError(what, { [field]: new ValidationError("validation_invalid_value", msg) });
@@ -108,7 +94,7 @@ function ban(e) {
108
94
  }
109
95
  if (user.id === me?.id) throw bad("user", "You can't ban yourself.");
110
96
  if (body.banned && user.getBool("moderator")) throw bad("user", "Moderators can't be banned here; an admin can.");
111
- if (body.banned && (user.getString("instance") || isStandIn(e.app, user.id))) {
97
+ if (body.banned && require(`${__hooks}/lib/users.js`).isStandIn(user)) {
112
98
  throw bad("user", "Only people who sign in here can be banned.");
113
99
  }
114
100
  if (user.getBool("banned") !== body.banned) {