chirkle 0.0.0-stage → 0.2.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 (139) hide show
  1. package/LICENSE +674 -0
  2. package/README.md +326 -2
  3. package/package.json +76 -4
  4. package/pb_hooks/federation/config.js +276 -0
  5. package/pb_hooks/federation/inbox.js +316 -0
  6. package/pb_hooks/federation/messages.js +420 -0
  7. package/pb_hooks/federation/mirror.js +277 -0
  8. package/pb_hooks/federation/net.js +247 -0
  9. package/pb_hooks/federation/peers.js +490 -0
  10. package/pb_hooks/federation/people.js +376 -0
  11. package/pb_hooks/federation/rooms.js +552 -0
  12. package/pb_hooks/federation/worker.js +413 -0
  13. package/pb_hooks/federation.pb.js +141 -0
  14. package/pb_hooks/lib/access.js +102 -0
  15. package/pb_hooks/lib/account.js +31 -0
  16. package/pb_hooks/lib/anonymous.js +189 -0
  17. package/pb_hooks/lib/bulk.js +187 -0
  18. package/pb_hooks/lib/collections.js +587 -0
  19. package/pb_hooks/lib/dms.js +123 -0
  20. package/pb_hooks/lib/emoji.js +28 -0
  21. package/pb_hooks/lib/enrich.js +75 -0
  22. package/pb_hooks/lib/features.js +31 -0
  23. package/pb_hooks/lib/files.js +375 -0
  24. package/pb_hooks/lib/http.js +146 -0
  25. package/pb_hooks/lib/images.js +160 -0
  26. package/pb_hooks/lib/keepalive.js +31 -0
  27. package/pb_hooks/lib/lists.js +173 -0
  28. package/pb_hooks/lib/media.js +635 -0
  29. package/pb_hooks/lib/messages.js +519 -0
  30. package/pb_hooks/lib/moderation.js +128 -0
  31. package/pb_hooks/lib/outbound.js +116 -0
  32. package/pb_hooks/lib/pages.js +171 -0
  33. package/pb_hooks/lib/previews.js +346 -0
  34. package/pb_hooks/lib/reactions.js +110 -0
  35. package/pb_hooks/lib/reads.js +181 -0
  36. package/pb_hooks/lib/records.js +77 -0
  37. package/pb_hooks/lib/rooms.js +148 -0
  38. package/pb_hooks/lib/site.js +102 -0
  39. package/pb_hooks/lib/text.js +110 -0
  40. package/pb_hooks/lib/users.js +81 -0
  41. package/pb_hooks/lib/worker.js +159 -0
  42. package/pb_hooks/main.pb.js +324 -0
  43. package/pb_hooks/telegram/api.js +129 -0
  44. package/pb_hooks/telegram/inbound.js +553 -0
  45. package/pb_hooks/telegram/links.js +157 -0
  46. package/pb_hooks/telegram/outbound.js +352 -0
  47. package/pb_hooks/telegram/people.js +166 -0
  48. package/pb_hooks/telegram/reactions.js +137 -0
  49. package/pb_hooks/telegram/rich.js +192 -0
  50. package/pb_hooks/telegram/worker.js +182 -0
  51. package/pb_hooks/telegram.pb.js +47 -0
  52. package/pb_migrations/1760000000_init.js +150 -0
  53. package/pb_migrations/1760000001_qa_fixes.js +69 -0
  54. package/pb_migrations/1760000002_avatars.js +39 -0
  55. package/pb_migrations/1760000003_direct_messages.js +142 -0
  56. package/pb_migrations/1760000004_attachments.js +28 -0
  57. package/pb_migrations/1760000005_file_names.js +16 -0
  58. package/pb_migrations/1760000006_room_reads.js +41 -0
  59. package/pb_migrations/1760000007_replies.js +23 -0
  60. package/pb_migrations/1760000008_lowercase_emails.js +24 -0
  61. package/pb_migrations/1760000009_reactions.js +32 -0
  62. package/pb_migrations/1760000010_fit_thumbs.js +18 -0
  63. package/pb_migrations/1760000011_forwarding.js +39 -0
  64. package/pb_migrations/1760000012_accounts.js +55 -0
  65. package/pb_migrations/1760000013_qa_pass5.js +19 -0
  66. package/pb_migrations/1760000014_room_access.js +96 -0
  67. package/pb_migrations/1760000015_site.js +46 -0
  68. package/pb_migrations/1760000016_forward_refs.js +43 -0
  69. package/pb_migrations/1760000017_no_dms.js +18 -0
  70. package/pb_migrations/1760000018_attachment_limits.js +24 -0
  71. package/pb_migrations/1760000019_telegram.js +109 -0
  72. package/pb_migrations/1760000020_service_messages.js +21 -0
  73. package/pb_migrations/1760000021_forward_view_index.js +41 -0
  74. package/pb_migrations/1760000022_link_previews.js +43 -0
  75. package/pb_migrations/1760000023_room_writers.js +49 -0
  76. package/pb_migrations/1760000024_message_search.js +51 -0
  77. package/pb_migrations/1760000025_search_dotted_i.js +16 -0
  78. package/pb_migrations/1760000026_push.js +67 -0
  79. package/pb_migrations/1760000027_push_tokens_per_user.js +31 -0
  80. package/pb_migrations/1760000028_media_grid_thumbs.js +18 -0
  81. package/pb_migrations/1760000029_media.js +71 -0
  82. package/pb_migrations/1760000030_collections.js +140 -0
  83. package/pb_migrations/1760000031_unread_limit.js +20 -0
  84. package/pb_migrations/1760000032_federation.js +227 -0
  85. package/pb_migrations/1760000033_federation_requests.js +44 -0
  86. package/pb_migrations/1760000034_telegram_parts.js +26 -0
  87. package/pb_migrations/1760000035_telegram_anonymous.js +16 -0
  88. package/pb_migrations/1760000036_chirkle.js +20 -0
  89. package/pb_migrations/1760000037_file_dims.js +35 -0
  90. package/pb_migrations/1760000038_drop_push.js +64 -0
  91. package/pb_migrations/1760000039_anonymous_rooms.js +40 -0
  92. package/pb_migrations/1760000040_moderators.js +42 -0
  93. package/pb_migrations/1760000041_shared_files.js +500 -0
  94. package/pb_migrations/1760000042_files_src.js +17 -0
  95. package/pb_migrations/1760000043_telegram_reactions.js +21 -0
  96. package/pb_public/assets/access-ALBW2MT2.js +2 -0
  97. package/pb_public/assets/access-ALBW2MT2.js.map +7 -0
  98. package/pb_public/assets/access-PB77EH4F.css +2 -0
  99. package/pb_public/assets/access-PB77EH4F.css.map +7 -0
  100. package/pb_public/assets/app-A3SXD3FF.css +2 -0
  101. package/pb_public/assets/app-A3SXD3FF.css.map +7 -0
  102. package/pb_public/assets/app-NDSIQW4L.js +3 -0
  103. package/pb_public/assets/app-NDSIQW4L.js.map +7 -0
  104. package/pb_public/assets/collections-DHJEOLHW.css +2 -0
  105. package/pb_public/assets/collections-DHJEOLHW.css.map +7 -0
  106. package/pb_public/assets/emoji-WSTVXAW5.css +2 -0
  107. package/pb_public/assets/emoji-WSTVXAW5.css.map +7 -0
  108. package/pb_public/assets/emoji-picker-QYRX6NYL.js +609 -0
  109. package/pb_public/assets/emoji-picker-QYRX6NYL.js.map +7 -0
  110. package/pb_public/assets/inter-cyrillic-JEOLYBOO.woff2 +0 -0
  111. package/pb_public/assets/inter-cyrillic-ext-IYF56FF6.woff2 +0 -0
  112. package/pb_public/assets/inter-greek-IRE366VL.woff2 +0 -0
  113. package/pb_public/assets/inter-latin-NRMW37G5.woff2 +0 -0
  114. package/pb_public/assets/inter-latin-ext-HA22NDSG.woff2 +0 -0
  115. package/pb_public/assets/lazy-4CXRBHHM.js +2 -0
  116. package/pb_public/assets/lazy-4CXRBHHM.js.map +7 -0
  117. package/pb_public/assets/media-7TCBG7WM.css +2 -0
  118. package/pb_public/assets/media-7TCBG7WM.css.map +7 -0
  119. package/pb_public/assets/media-FPRU2QH5.js +2 -0
  120. package/pb_public/assets/media-FPRU2QH5.js.map +7 -0
  121. package/pb_public/assets/notify-L6GERFNO.js +2 -0
  122. package/pb_public/assets/notify-L6GERFNO.js.map +7 -0
  123. package/pb_public/assets/search-3UT4HMES.js +2 -0
  124. package/pb_public/assets/search-3UT4HMES.js.map +7 -0
  125. package/pb_public/assets/switcher-CEUKRLEY.js +2 -0
  126. package/pb_public/assets/switcher-CEUKRLEY.js.map +7 -0
  127. package/pb_public/assets/viewer-DXT7SKOU.js +2 -0
  128. package/pb_public/assets/viewer-DXT7SKOU.js.map +7 -0
  129. package/pb_public/assets/viewer-P7GYCBYM.css +2 -0
  130. package/pb_public/assets/viewer-P7GYCBYM.css.map +7 -0
  131. package/pb_public/icons/apple-touch-icon.png +0 -0
  132. package/pb_public/icons/icon-192.png +0 -0
  133. package/pb_public/icons/icon-512.png +0 -0
  134. package/pb_public/icons/icon.svg +1 -0
  135. package/pb_public/icons/maskable-512.png +0 -0
  136. package/pb_public/index.html +21 -0
  137. package/pb_public/sw.js +1 -0
  138. package/scripts/fetch-pocketbase.sh +63 -0
  139. package/scripts/start.mjs +93 -0
@@ -0,0 +1,519 @@
1
+ /// <reference path="../../types/pocketbase.d.ts" />
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).
4
+
5
+ const { accessOf, canSee, canWrite, visibleRoom } = require(`${__hooks}/lib/access.js`);
6
+ const { inCheckedRoom, markChecked } = require(`${__hooks}/lib/enrich.js`);
7
+ const { fieldError, recordOf } = require(`${__hooks}/lib/records.js`);
8
+ const { dmRefusal } = require(`${__hooks}/lib/dms.js`);
9
+ const { isDm } = require(`${__hooks}/lib/rooms.js`);
10
+ const { cleanText, isBlank, searchKey } = require(`${__hooks}/lib/text.js`);
11
+
12
+ /**
13
+ * Trim a text field in place (required/min validation then rejects blanks).
14
+ * @param {core.Record} record
15
+ * @param {string} field
16
+ */
17
+ function trim(record, field) {
18
+ record.set(field, record.getString(field).trim());
19
+ }
20
+
21
+ /**
22
+ * The message's room, which must be active (not archived). Null when no room is set.
23
+ * @param {core.App} app
24
+ * @param {string} roomId
25
+ */
26
+ function activeRoom(app, roomId) {
27
+ if (!roomId) return null; // the relation's own `required` validation reports this
28
+ const room = app.findRecordById("rooms", roomId);
29
+ if (room.getBool("archived")) throw fieldError("room", "This room is archived and read-only.");
30
+ return room;
31
+ }
32
+
33
+ /**
34
+ * Clean (no control characters, QA BUG-105), trimmed text that isn't blank, unless `blankOk` (a message with
35
+ * attachments may have no text, §17.1).
36
+ * @param {core.Record} record
37
+ * @param {boolean} [blankOk]
38
+ */
39
+ function assertText(record, blankOk = false) {
40
+ record.set("text", cleanText(record.getString("text")));
41
+ trim(record, "text");
42
+ const text = record.getString("text");
43
+ if (!isBlank(text)) return;
44
+ if (!blankOk) throw fieldError("text", "Cannot be blank.");
45
+ record.set("text", ""); // e.g. only zero-width characters next to an attachment
46
+ }
47
+
48
+ /**
49
+ * What message search matches (§29): the text case folded (`searchKey`), whatever the client sent. Set after
50
+ * every other change to the text, on every save.
51
+ * @param {core.Record} record
52
+ */
53
+ function setTextKey(record) {
54
+ record.set("text_key", searchKey(record.getString("text")));
55
+ }
56
+
57
+ /**
58
+ * Attachment names: the stored names of its `files` rows (§37).
59
+ * @param {core.Record} record
60
+ */
61
+ const fileNames = (record) => record.getStringSlice("files");
62
+
63
+ /**
64
+ * Is this message a forward (§21.3)? A forward's text may be blank: it shows the original's, or nothing once that is gone.
65
+ * @param {core.Record} rec
66
+ */
67
+ const isForward = (rec) => rec.getString("forwarded_from") !== "";
68
+
69
+ /**
70
+ * Is this a service message (§5.3): the app's own notice in a room, with no author?
71
+ * @param {core.Record} rec
72
+ */
73
+ const isService = (rec) => rec.getString("author") === "";
74
+
75
+ /**
76
+ * Post a service message (§5.3) in a room that isn't archived: one line of the app's own, no author. It goes through
77
+ * the same hooks as any message, so unread counts and realtime see it.
78
+ * @param {core.App} app
79
+ * @param {string} roomId
80
+ * @param {string} text
81
+ */
82
+ function postService(app, roomId, text) {
83
+ const rec = new Record(app.findCollectionByNameOrId("messages"));
84
+ rec.set("room", roomId);
85
+ rec.set("text", text);
86
+ app.save(rec);
87
+ }
88
+
89
+ /**
90
+ * messages create: trim + non-empty text, room must be active (§5.6).
91
+ * @param {core.RecordEvent} e
92
+ */
93
+ function beforeMessageCreate(e) {
94
+ const rec = recordOf(e);
95
+ // Set with their rows (setRequestFiles, lib/files.js setMessageFiles); a message without files says so, never null.
96
+ if (!fileNames(rec).length) {
97
+ rec.set("files", []);
98
+ rec.set("file_names", {});
99
+ rec.set("file_dims", {});
100
+ }
101
+ if (isService(rec)) {
102
+ // Made only by postService (no request can leave out the author): text alone, in any room that isn't archived.
103
+ assertText(rec);
104
+ rec.set("reactions", []);
105
+ rec.set("previews", []);
106
+ activeRoom(e.app, rec.getString("room"));
107
+ return;
108
+ }
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"));
113
+ // Defense in depth for the members-only create rule (§16.3, §23.1): DMs and private rooms.
114
+ if (room && !canSee(accessOf(room), rec.getString("author"))) {
115
+ throw fieldError("room", isDm(room) ? "You are not a member of this conversation." : "You are not a member of this room.");
116
+ }
117
+ // ... and for who may post in it (§23.6): forwards and the Telegram bridge come through here too.
118
+ if (room && !canWrite(room, rec.getString("author"))) throw fieldError("room", "Only some people can post in this room.");
119
+ if (room && isDm(room)) {
120
+ const refused = dmRefusal(e.app, rec.getString("author"), room.getStringSlice("members"));
121
+ if (refused) throw fieldError("room", refused);
122
+ }
123
+ // Posted in an anonymous room (§35): its author is kept to themselves for good. DMs never are.
124
+ rec.set("anonymous", !!room && !isDm(room) && room.getBool("anonymous"));
125
+ assertReplyTarget(e.app, rec);
126
+ rec.set("forwarded_anonymous", assertForwardTarget(e.app, rec));
127
+ }
128
+
129
+ /**
130
+ * A forward (§21.3) shows an original that is still there: not deleted, and not a forward itself (POST
131
+ * /api/chat/forward points a forward of a forward at its original), so a chain is never more than one step. Returns
132
+ * whether the original's author is kept to themselves (§35).
133
+ * @param {core.App} app
134
+ * @param {core.Record} rec
135
+ */
136
+ function assertForwardTarget(app, rec) {
137
+ const id = rec.getString("forward_of");
138
+ if (!id) return false;
139
+ let original = null;
140
+ try {
141
+ original = app.findRecordById("messages", id);
142
+ } catch {
143
+ original = null;
144
+ }
145
+ if (!original || original.getBool("deleted")) throw fieldError("forward_of", "That message was deleted.");
146
+ if (original.getString("forward_of") !== "") throw fieldError("forward_of", "That message is a forward.");
147
+ return original.getBool("anonymous");
148
+ }
149
+
150
+ /**
151
+ * A reply (§19) answers a message of the same room that is still there. Without this check a reply could
152
+ * point into a DM you're not in, and its expanded preview would show you that message.
153
+ * @param {core.App} app
154
+ * @param {core.Record} rec
155
+ */
156
+ function assertReplyTarget(app, rec) {
157
+ const id = rec.getString("reply_to");
158
+ if (!id) return;
159
+ let parent = null;
160
+ try {
161
+ parent = app.findRecordById("messages", id);
162
+ } catch {
163
+ parent = null;
164
+ }
165
+ if (!parent || parent.getString("room") !== rec.getString("room")) {
166
+ throw fieldError("reply_to", "That message isn't in this room.");
167
+ }
168
+ if (parent.getBool("deleted")) throw fieldError("reply_to", "That message was deleted.");
169
+ if (isService(parent)) throw fieldError("reply_to", "Service messages can't be replied to.");
170
+ }
171
+
172
+ /**
173
+ * Is this update PocketBase clearing `reply_to` because the message it pointed at no longer exists? Users can't
174
+ * remove messages (only soft-delete them), and the update rule refuses any `reply_to` in a request body.
175
+ * @param {core.App} app
176
+ * @param {core.Record} rec
177
+ * @param {core.Record} orig
178
+ */
179
+ function replyTargetRemoved(app, rec, orig) {
180
+ const id = orig.getString("reply_to");
181
+ if (!id || rec.getString("reply_to") !== "") return false;
182
+ try {
183
+ app.findRecordById("messages", id);
184
+ return false;
185
+ } catch {
186
+ return true;
187
+ }
188
+ }
189
+
190
+ /**
191
+ * Is this update PocketBase clearing `forward_of` because the original was deleted for good (by a superuser, or with
192
+ * its room)? The forward then shows nothing (§21.3). The update rule refuses any `forward_of` in a request body.
193
+ * @param {core.App} app
194
+ * @param {core.Record} rec
195
+ * @param {core.Record} orig
196
+ */
197
+ function originalRemoved(app, rec, orig) {
198
+ const id = orig.getString("forward_of");
199
+ if (!id || rec.getString("forward_of") !== "") return false;
200
+ try {
201
+ app.findRecordById("messages", id);
202
+ return false;
203
+ } catch {
204
+ return true;
205
+ }
206
+ }
207
+
208
+ /**
209
+ * Is this update PocketBase clearing `forwarded_from` because the user it named was deleted (by a superuser)? The
210
+ * update rule refuses any `forwarded_from` in a request body.
211
+ * @param {core.App} app
212
+ * @param {core.Record} rec
213
+ * @param {core.Record} orig
214
+ */
215
+ function forwardSourceRemoved(app, rec, orig) {
216
+ const id = orig.getString("forwarded_from");
217
+ if (!id || rec.getString("forwarded_from") !== "") return false;
218
+ try {
219
+ app.findRecordById("users", id);
220
+ return false;
221
+ } catch {
222
+ return true;
223
+ }
224
+ }
225
+
226
+ /**
227
+ * messages create through the API: only POST /api/chat/forward, whose own saves don't come through here, makes a
228
+ * forward (§21.3). Backs up the create rule against field modifiers.
229
+ * @param {core.RecordRequestEvent} e
230
+ */
231
+ function beforeMessageCreateRequest(e) {
232
+ const rec = recordOf(e);
233
+ for (const f of ["forwarded_from", "forward_of"]) if (rec.getString(f) !== "") throw fieldError(f, "This field can't be set.");
234
+ // Only attachItems sets file_sources, from the items named (§31); only the hooks set file_dims (§17.5).
235
+ for (const f of ["file_sources", "file_dims"]) {
236
+ const v = rec.getString(f);
237
+ if (v !== "" && v !== "null" && v !== "{}") throw fieldError(f, "This field can't be set.");
238
+ }
239
+ }
240
+
241
+ /**
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.
245
+ * @param {core.RecordRequestEvent} e
246
+ */
247
+ function setRequestFiles(e) {
248
+ const rec = recordOf(e);
249
+ /** @type {filesystem.File[]} */
250
+ const uploads = [];
251
+ for (const key of ["files", "files+"]) {
252
+ try {
253
+ for (const f of e.findUploadedFiles(key)) if (f) uploads.push(f);
254
+ } catch {
255
+ // none under this key
256
+ }
257
+ }
258
+ const files = require(`${__hooks}/lib/files.js`);
259
+ const { rows: items, sources } = require(`${__hooks}/lib/collections.js`).itemsToAttach(e, uploads.length);
260
+ if (uploads.length + items.length > files.MAX_FILES) throw fieldError("files", `At most ${files.MAX_FILES} files.`);
261
+ // The create rule would refuse it anyway: store nothing first.
262
+ 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);
264
+ }
265
+
266
+ /**
267
+ * messages, after a create is committed: a DM records its latest activity (sorts the DM list) and reopens
268
+ * itself for members who had closed it (§16.4).
269
+ * @param {core.RecordEvent} e
270
+ */
271
+ function afterMessageCreate(e) {
272
+ const rec = recordOf(e);
273
+ const room = e.app.findRecordById("rooms", rec.getString("room"));
274
+ if (!isDm(room)) return;
275
+ room.set("last_message_at", rec.get("created"));
276
+ e.app.save(room);
277
+ const author = rec.getString("author");
278
+ for (const member of room.getStringSlice("members")) {
279
+ if (member === author) continue;
280
+ const rows = e.app.findRecordsByFilter("hidden_rooms", "user = {:user} && room = {:room}", "", 1, 0, { user: member, room: room.id });
281
+ for (const row of rows) if (row) e.app.delete(row);
282
+ }
283
+ }
284
+
285
+ /**
286
+ * messages update: soft delete, edit stamp, archived guard (§5.6).
287
+ * @param {core.RecordEvent} e
288
+ */
289
+ function beforeMessageUpdate(e) {
290
+ const rec = recordOf(e);
291
+ const orig = rec.original();
292
+ // A message deleted for good (by a superuser, or with its room) is already gone when PocketBase unsets the
293
+ // reply_to of its replies (§19.1). Let that save through: the guards below would refuse it, and with it the delete.
294
+ if (replyTargetRemoved(e.app, rec, orig) || forwardSourceRemoved(e.app, rec, orig) || originalRemoved(e.app, rec, orig)) return;
295
+ activeRoom(e.app, orig.getString("room"));
296
+
297
+ if (orig.getBool("deleted")) {
298
+ // Deletion is final; API rules already refuse this, so this only guards superuser edits.
299
+ throw fieldError("deleted", "Deleted messages cannot be changed.");
300
+ }
301
+ // Backs up the update rule (§19), superusers included. PocketBase 0.40.4 counts field modifiers (`author+`) as set
302
+ // for `:isset`, so the rule refuses them (QA BUG-150), but nothing else would if a version stopped doing so.
303
+ if (rec.getString("reply_to") !== orig.getString("reply_to")) throw fieldError("reply_to", "This field can't be changed.");
304
+ for (const f of ["author", "room", "forwarded_from", "forward_of"]) {
305
+ if (rec.getString(f) !== orig.getString(f)) throw fieldError(f, "This field can't be changed.");
306
+ }
307
+
308
+ if (rec.getBool("deleted")) {
309
+ rec.set("text", "");
310
+ rec.set("files", []); // unlinked once saved: a file nothing else names is deleted (§17.1, §37)
311
+ rec.set("file_names", {});
312
+ rec.set("file_sources", {});
313
+ rec.set("file_dims", {});
314
+ rec.set("reactions", []);
315
+ rec.set("previews", []);
316
+ rec.set("deleted_at", new DateTime());
317
+ rec.set("edited_at", orig.get("edited_at"));
318
+ return;
319
+ }
320
+
321
+ rec.set("file_names", orig.get("file_names")); // never changed by an edit
322
+ rec.set("file_sources", orig.get("file_sources")); // nor this (§31)
323
+ // Only the create hook and the media worker set these; the worker's may be newer than the loaded record's.
324
+ rec.set("file_dims", e.app.findRecordById("messages", rec.id).get("file_dims"));
325
+ // Reactions only change through POST /api/chat/reactions (§20.2). Any other save (an edit) keeps the ones stored
326
+ // now, not the ones loaded with the record: a reaction added meanwhile would be lost. (Edits save in a transaction.)
327
+ if (rec.getString("reactions") === orig.getString("reactions")) {
328
+ rec.set("reactions", e.app.findRecordById("messages", rec.id).get("reactions"));
329
+ }
330
+ // Attachments are immutable after sending (backs up the update rule, as above).
331
+ const files = fileNames(rec);
332
+ if (files.join("/") !== orig.getStringSlice("files").join("/")) throw fieldError("files", "Attachments can't be changed.");
333
+ assertText(rec, files.length > 0 || isForward(rec));
334
+ if (rec.getString("text") !== orig.getString("text")) {
335
+ rec.set("previews", []); // the worker looks at the new text's links (§28)
336
+ } else if (rec.getString("previews") === orig.getString("previews")) {
337
+ // As for reactions: the ones stored now, not those loaded with the record (the worker may have saved meanwhile).
338
+ rec.set("previews", e.app.findRecordById("messages", rec.id).get("previews"));
339
+ }
340
+ if (rec.getString("text") !== orig.getString("text")) {
341
+ // A forward's words are someone else's: "Forwarded from Bob" must stay true (§21.3). It can still be deleted.
342
+ if (orig.getString("forwarded_from") !== "") throw fieldError("text", "Forwarded messages can't be edited.");
343
+ rec.set("edited_at", new DateTime());
344
+ }
345
+ }
346
+
347
+ /**
348
+ * messages update through the API: reactions only change through POST /api/chat/reactions, whose own saves don't
349
+ * come through here (§20.2); previews and file_dims only through the workers (§28, §17.5). Backs up the update rule.
350
+ * @param {core.RecordRequestEvent} e
351
+ */
352
+ function beforeMessageUpdateRequest(e) {
353
+ const rec = recordOf(e);
354
+ // Uploads and modifiers aren't a file field's any more (§37), so the update rule doesn't see them all: refused
355
+ // here, not dropped.
356
+ const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body);
357
+ for (const key of ["files", "+files", "files+", "files-"]) {
358
+ let n = 0;
359
+ try {
360
+ n = e.findUploadedFiles(key).length;
361
+ } catch {
362
+ n = 0;
363
+ }
364
+ if (n || key in body) throw fieldError("files", "Attachments can't be changed.");
365
+ }
366
+ for (const f of ["reactions", "previews", "file_dims"]) {
367
+ if (rec.getString(f) !== rec.original().getString(f)) throw fieldError(f, "This field can't be changed.");
368
+ }
369
+ }
370
+
371
+ /**
372
+ * Will this update change what forwards of the message show (§21.3)? Called with the update about to be saved.
373
+ * @param {core.Record} rec
374
+ */
375
+ function changesForwards(rec) {
376
+ const orig = rec.original();
377
+ return (
378
+ rec.getString("text") !== orig.getString("text") ||
379
+ rec.getBool("deleted") !== orig.getBool("deleted") ||
380
+ rec.getString("previews") !== orig.getString("previews")
381
+ );
382
+ }
383
+
384
+ /**
385
+ * After an edit or delete of a message: its forwards are saved again (nothing in them changes), so everyone who sees
386
+ * one hears of it live, with the original as it is now (showOriginal). They can't hear of the original itself: it is
387
+ * in a room they may not see. Forwards in archived rooms are left alone: they can't be saved, and show it once loaded.
388
+ * @param {core.App} app
389
+ * @param {core.Record} rec
390
+ */
391
+ function touchForwards(app, rec) {
392
+ const forwards = app.findRecordsByFilter("messages", "forward_of = {:id} && deleted = false", "", 0, 0, { id: rec.id });
393
+ for (const fwd of forwards) {
394
+ if (!fwd || app.findRecordById("rooms", fwd.getString("room")).getBool("archived")) continue;
395
+ app.save(fwd);
396
+ }
397
+ }
398
+
399
+ /**
400
+ * Every message the API answers with or sends live (lists, reads, expanded replies, realtime): a forward that isn't
401
+ * deleted shows its original's text, attachments and edit stamp (§21.3), or nothing once that is deleted. Whoever
402
+ * sees the forward may see those: the view rule grants it, as for the attachments' URLs (the original's).
403
+ * Only in the answer: nothing is saved.
404
+ * @param {core.RecordEnrichEvent} e
405
+ */
406
+ function showOriginal(e) {
407
+ const rec = e.record;
408
+ const id = rec ? rec.getString("forward_of") : "";
409
+ if (!rec || !id || rec.getBool("deleted") || inCheckedRoom(e)) return;
410
+ let original = null;
411
+ try {
412
+ original = e.app.findRecordById("messages", id);
413
+ } catch {
414
+ return; // being removed for good: PocketBase is about to clear forward_of
415
+ }
416
+ setOriginal(rec, original);
417
+ }
418
+
419
+ /**
420
+ * The forward `rec` shows `original` (showOriginal).
421
+ * @param {core.Record} rec
422
+ * @param {core.Record} original
423
+ */
424
+ function setOriginal(rec, original) {
425
+ const gone = original.getBool("deleted");
426
+ rec.set("text", gone ? "" : original.getString("text"));
427
+ rec.set("files", gone ? [] : original.getStringSlice("files"));
428
+ rec.set("file_names", gone ? {} : original.get("file_names"));
429
+ rec.set("file_sources", gone ? {} : original.get("file_sources"));
430
+ rec.set("file_dims", gone ? {} : original.get("file_dims"));
431
+ rec.set("previews", gone ? [] : original.get("previews"));
432
+ rec.set("edited_at", gone ? "" : original.get("edited_at"));
433
+ }
434
+
435
+ /**
436
+ * A message read only through a forward of it (the view rule grants that, §21.3) keeps to itself what would say who
437
+ * is in its room: its reactions (who reacted) and the message it replies to. Only in the answer: nothing is saved.
438
+ * Most messages have neither, and cost nothing here.
439
+ * @param {core.RecordEnrichEvent} e
440
+ */
441
+ function keepToRoom(e) {
442
+ const rec = e.record;
443
+ const info = e.requestInfo;
444
+ if (!rec || !info || info.auth?.isSuperuser() || inCheckedRoom(e)) return;
445
+ const reactions = rec.getString("reactions");
446
+ if (!rec.getString("reply_to") && (reactions === "" || reactions === "[]" || reactions === "null")) return;
447
+ if (visibleRoom(e.app, rec.getString("room"), info.auth?.id ?? "")) return;
448
+ rec.set("reactions", []);
449
+ rec.set("reply_to", "");
450
+ }
451
+
452
+ /**
453
+ * users delete (a superuser): refused while they have messages. `author` isn't required (service messages have none,
454
+ * §5.3), so PocketBase would otherwise clear it on their messages, which would then read as the app's own notices.
455
+ * @param {core.RecordEvent} e
456
+ */
457
+ function beforeUserDelete(e) {
458
+ const id = recordOf(e).id;
459
+ if (e.app.findRecordsByFilter("messages", "author = {:id}", "", 1, 0, { id }).length) {
460
+ throw new BadRequestError("This user wrote messages, so their account can't be deleted.");
461
+ }
462
+ }
463
+
464
+ /**
465
+ * Enrich the messages of rooms `rooms` (which the caller can see) in `enrich`, a call of $apis.enrichRecords, as the
466
+ * hooks would, with one query for every forward's original instead of one each (lib/enrich.js).
467
+ * @param {core.RequestEvent} e
468
+ * @param {string[]} rooms
469
+ * @param {() => core.Record[]} enrich
470
+ */
471
+ function enrichInRooms(e, rooms, enrich) {
472
+ showOriginals(e.app, markChecked(e, rooms, enrich), new Set(rooms));
473
+ }
474
+
475
+ /**
476
+ * showOriginal for every message in `rooms` among `records` and what they expand (an expanded reply, to any depth).
477
+ * @param {core.App} app
478
+ * @param {core.Record[]} records
479
+ * @param {Set<string>} rooms
480
+ */
481
+ function showOriginals(app, records, rooms) {
482
+ /** @type {core.Record[]} */
483
+ const forwards = [];
484
+ const seen = new Set();
485
+ const visit = (/** @type {any} */ rec) => {
486
+ if (!rec || seen.has(rec)) return;
487
+ seen.add(rec);
488
+ for (const v of Object.values(rec.expand() ?? {})) for (const r of Array.isArray(v) ? v : [v]) visit(r);
489
+ if (rec.collection().name !== "messages" || !rooms.has(rec.getString("room"))) return;
490
+ if (rec.getString("forward_of") && !rec.getBool("deleted")) forwards.push(rec);
491
+ };
492
+ for (const rec of records) visit(rec);
493
+ if (!forwards.length) return;
494
+ const originals = new Map(
495
+ app.findRecordsByIds("messages", [...new Set(forwards.map((f) => f.getString("forward_of")))]).map((o) => [o?.id, o]),
496
+ );
497
+ for (const fwd of forwards) {
498
+ const original = originals.get(fwd.getString("forward_of"));
499
+ if (original) setOriginal(fwd, original);
500
+ }
501
+ }
502
+
503
+ module.exports = {
504
+ enrichInRooms,
505
+ isService,
506
+ setTextKey,
507
+ setRequestFiles,
508
+ beforeUserDelete,
509
+ postService,
510
+ beforeMessageCreate,
511
+ beforeMessageCreateRequest,
512
+ afterMessageCreate,
513
+ beforeMessageUpdate,
514
+ beforeMessageUpdateRequest,
515
+ changesForwards,
516
+ touchForwards,
517
+ showOriginal,
518
+ keepToRoom,
519
+ };
@@ -0,0 +1,128 @@
1
+ /// <reference path="../../types/pocketbase.d.ts" />
2
+ // Moderators (DESIGN.md §36): people a superuser ticked `moderator` for in the admin UI. They delete anyone's messages
3
+ // (POST /api/chat/delete), change any public room's access and archive it (the rooms update rule), and ban and unban
4
+ // people (POST /api/chat/ban). A banned account can't sign in (the users authRule), its sessions end and its live
5
+ // connections close.
6
+
7
+ const { isDm } = require(`${__hooks}/lib/rooms.js`);
8
+
9
+ /**
10
+ * Is `user` (e.auth) a moderator? Superusers aren't users, and act through the admin UI.
11
+ * @param {core.Record | null | undefined} user
12
+ */
13
+ function isModerator(user) {
14
+ return !!user && user.collection().name === "users" && user.getBool("moderator") && !user.getBool("banned");
15
+ }
16
+
17
+ /**
18
+ * May `user` change the room's access and archive it? Its creator, or a moderator; never a DM.
19
+ * @param {core.Record} room
20
+ * @param {core.Record | null | undefined} user
21
+ */
22
+ function canManage(room, user) {
23
+ if (!user || isDm(room)) return false;
24
+ return room.getString("created_by") === user.id || isModerator(user);
25
+ }
26
+
27
+ /**
28
+ * May `user` delete someone else's message in this room? A moderator, outside DMs.
29
+ * @param {core.Record} room
30
+ * @param {core.Record | null | undefined} user
31
+ */
32
+ const canModerate = (room, user) => isModerator(user) && !isDm(room);
33
+
34
+ /**
35
+ * users update: a ban ends the account's sessions (its tokens no longer check out). Returns whether it was banned now,
36
+ * for afterBan once saved.
37
+ * @param {core.Record} rec
38
+ */
39
+ function beforeBan(rec) {
40
+ if (rec.isNew() || !rec.getBool("banned") || rec.original().getBool("banned")) return false;
41
+ rec.refreshTokenKey();
42
+ return true;
43
+ }
44
+
45
+ /**
46
+ * users update (saved) that banned someone: close their live connections, which outlive the token.
47
+ * @param {core.App} app
48
+ * @param {string} userId
49
+ */
50
+ function afterBan(app, userId) {
51
+ const broker = app.subscriptionsBroker();
52
+ const clients = broker.clients();
53
+ for (const id of Object.keys(clients)) {
54
+ const client = clients[id];
55
+ /** @type {core.Record | null | undefined} */
56
+ const auth = client?.get("auth");
57
+ if (!client || !auth || auth.isSuperuser() || auth.id !== userId) continue;
58
+ client.discard();
59
+ broker.unregister(id);
60
+ }
61
+ }
62
+
63
+ /**
64
+ * users auth-with-password / OAuth2: a banned account is told so (the authRule alone answers "doesn't satisfy the
65
+ * collection requirements"). Only once the password checks out, so a stranger learns nothing.
66
+ * @param {core.Record | null | undefined} rec
67
+ * @param {string | null} password the password tried; null for OAuth2, whose provider vouched for them
68
+ */
69
+ function refuseBanned(rec, password) {
70
+ if (!rec?.getBool("banned")) return;
71
+ if (password !== null && !rec.validatePassword(password)) return;
72
+ throw new ForbiddenError("This account is banned.");
73
+ }
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
+ /**
90
+ * POST /api/chat/ban { user, banned } → the user's public profile with `banned`. Moderators only. Not themselves,
91
+ * another moderator, or someone who doesn't sign in here (a linked instance's people, a Telegram stand-in); anyone
92
+ * banned can be unbanned (a superuser may have banned them).
93
+ * @param {core.RequestEvent} e
94
+ */
95
+ function ban(e) {
96
+ const me = e.auth;
97
+ if (!isModerator(me)) throw new ForbiddenError("Only moderators can ban people.");
98
+ const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body);
99
+ const what = body.banned === false ? "Failed to unban them." : "Failed to ban them.";
100
+ const bad = (/** @type {string} */ field, /** @type {string} */ msg) =>
101
+ new BadRequestError(what, { [field]: new ValidationError("validation_invalid_value", msg) });
102
+ if (typeof body.banned !== "boolean") throw bad("banned", "Say whether they are banned.");
103
+ let user;
104
+ try {
105
+ user = e.app.findRecordById("users", typeof body.user === "string" ? body.user : "");
106
+ } catch {
107
+ throw new NotFoundError("They don't exist.");
108
+ }
109
+ if (user.id === me?.id) throw bad("user", "You can't ban yourself.");
110
+ 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))) {
112
+ throw bad("user", "Only people who sign in here can be banned.");
113
+ }
114
+ if (user.getBool("banned") !== body.banned) {
115
+ user.set("banned", body.banned);
116
+ e.app.save(user);
117
+ }
118
+ return e.json(200, {
119
+ id: user.id,
120
+ name: user.getString("name"),
121
+ avatar: user.getString("avatar"),
122
+ no_dms: user.getBool("no_dms"),
123
+ instance: user.getString("instance"),
124
+ banned: user.getBool("banned"),
125
+ });
126
+ }
127
+
128
+ module.exports = { isModerator, canManage, canModerate, beforeBan, afterBan, refuseBanned, ban };