chirkle 0.0.0-stage → 0.1.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 (137) hide show
  1. package/LICENSE +674 -0
  2. package/README.md +310 -2
  3. package/package.json +75 -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 +128 -0
  44. package/pb_hooks/telegram/inbound.js +548 -0
  45. package/pb_hooks/telegram/links.js +157 -0
  46. package/pb_hooks/telegram/outbound.js +323 -0
  47. package/pb_hooks/telegram/people.js +166 -0
  48. package/pb_hooks/telegram/rich.js +192 -0
  49. package/pb_hooks/telegram/worker.js +181 -0
  50. package/pb_hooks/telegram.pb.js +47 -0
  51. package/pb_migrations/1760000000_init.js +150 -0
  52. package/pb_migrations/1760000001_qa_fixes.js +69 -0
  53. package/pb_migrations/1760000002_avatars.js +39 -0
  54. package/pb_migrations/1760000003_direct_messages.js +142 -0
  55. package/pb_migrations/1760000004_attachments.js +28 -0
  56. package/pb_migrations/1760000005_file_names.js +16 -0
  57. package/pb_migrations/1760000006_room_reads.js +41 -0
  58. package/pb_migrations/1760000007_replies.js +23 -0
  59. package/pb_migrations/1760000008_lowercase_emails.js +24 -0
  60. package/pb_migrations/1760000009_reactions.js +32 -0
  61. package/pb_migrations/1760000010_fit_thumbs.js +18 -0
  62. package/pb_migrations/1760000011_forwarding.js +39 -0
  63. package/pb_migrations/1760000012_accounts.js +55 -0
  64. package/pb_migrations/1760000013_qa_pass5.js +19 -0
  65. package/pb_migrations/1760000014_room_access.js +96 -0
  66. package/pb_migrations/1760000015_site.js +46 -0
  67. package/pb_migrations/1760000016_forward_refs.js +43 -0
  68. package/pb_migrations/1760000017_no_dms.js +18 -0
  69. package/pb_migrations/1760000018_attachment_limits.js +24 -0
  70. package/pb_migrations/1760000019_telegram.js +109 -0
  71. package/pb_migrations/1760000020_service_messages.js +21 -0
  72. package/pb_migrations/1760000021_forward_view_index.js +41 -0
  73. package/pb_migrations/1760000022_link_previews.js +43 -0
  74. package/pb_migrations/1760000023_room_writers.js +49 -0
  75. package/pb_migrations/1760000024_message_search.js +51 -0
  76. package/pb_migrations/1760000025_search_dotted_i.js +16 -0
  77. package/pb_migrations/1760000026_push.js +67 -0
  78. package/pb_migrations/1760000027_push_tokens_per_user.js +31 -0
  79. package/pb_migrations/1760000028_media_grid_thumbs.js +18 -0
  80. package/pb_migrations/1760000029_media.js +71 -0
  81. package/pb_migrations/1760000030_collections.js +140 -0
  82. package/pb_migrations/1760000031_unread_limit.js +20 -0
  83. package/pb_migrations/1760000032_federation.js +227 -0
  84. package/pb_migrations/1760000033_federation_requests.js +44 -0
  85. package/pb_migrations/1760000034_telegram_parts.js +26 -0
  86. package/pb_migrations/1760000035_telegram_anonymous.js +16 -0
  87. package/pb_migrations/1760000036_chirkle.js +20 -0
  88. package/pb_migrations/1760000037_file_dims.js +35 -0
  89. package/pb_migrations/1760000038_drop_push.js +64 -0
  90. package/pb_migrations/1760000039_anonymous_rooms.js +40 -0
  91. package/pb_migrations/1760000040_moderators.js +42 -0
  92. package/pb_migrations/1760000041_shared_files.js +500 -0
  93. package/pb_migrations/1760000042_files_src.js +17 -0
  94. package/pb_public/assets/access-ALBW2MT2.js +2 -0
  95. package/pb_public/assets/access-ALBW2MT2.js.map +7 -0
  96. package/pb_public/assets/access-PB77EH4F.css +2 -0
  97. package/pb_public/assets/access-PB77EH4F.css.map +7 -0
  98. package/pb_public/assets/app-ECR34OBK.css +2 -0
  99. package/pb_public/assets/app-ECR34OBK.css.map +7 -0
  100. package/pb_public/assets/app-SILEBEXB.js +3 -0
  101. package/pb_public/assets/app-SILEBEXB.js.map +7 -0
  102. package/pb_public/assets/collections-VEOIOCAW.css +2 -0
  103. package/pb_public/assets/collections-VEOIOCAW.css.map +7 -0
  104. package/pb_public/assets/emoji-WSTVXAW5.css +2 -0
  105. package/pb_public/assets/emoji-WSTVXAW5.css.map +7 -0
  106. package/pb_public/assets/emoji-picker-QYRX6NYL.js +609 -0
  107. package/pb_public/assets/emoji-picker-QYRX6NYL.js.map +7 -0
  108. package/pb_public/assets/inter-cyrillic-JEOLYBOO.woff2 +0 -0
  109. package/pb_public/assets/inter-cyrillic-ext-IYF56FF6.woff2 +0 -0
  110. package/pb_public/assets/inter-greek-IRE366VL.woff2 +0 -0
  111. package/pb_public/assets/inter-latin-NRMW37G5.woff2 +0 -0
  112. package/pb_public/assets/inter-latin-ext-HA22NDSG.woff2 +0 -0
  113. package/pb_public/assets/lazy-SCCVSUZO.js +2 -0
  114. package/pb_public/assets/lazy-SCCVSUZO.js.map +7 -0
  115. package/pb_public/assets/media-DH7ECZSF.js +2 -0
  116. package/pb_public/assets/media-DH7ECZSF.js.map +7 -0
  117. package/pb_public/assets/media-L3EYTHKT.css +2 -0
  118. package/pb_public/assets/media-L3EYTHKT.css.map +7 -0
  119. package/pb_public/assets/notify-L6GERFNO.js +2 -0
  120. package/pb_public/assets/notify-L6GERFNO.js.map +7 -0
  121. package/pb_public/assets/search-3UT4HMES.js +2 -0
  122. package/pb_public/assets/search-3UT4HMES.js.map +7 -0
  123. package/pb_public/assets/switcher-CEUKRLEY.js +2 -0
  124. package/pb_public/assets/switcher-CEUKRLEY.js.map +7 -0
  125. package/pb_public/assets/viewer-DXT7SKOU.js +2 -0
  126. package/pb_public/assets/viewer-DXT7SKOU.js.map +7 -0
  127. package/pb_public/assets/viewer-P7GYCBYM.css +2 -0
  128. package/pb_public/assets/viewer-P7GYCBYM.css.map +7 -0
  129. package/pb_public/icons/apple-touch-icon.png +0 -0
  130. package/pb_public/icons/icon-192.png +0 -0
  131. package/pb_public/icons/icon-512.png +0 -0
  132. package/pb_public/icons/icon.svg +1 -0
  133. package/pb_public/icons/maskable-512.png +0 -0
  134. package/pb_public/index.html +21 -0
  135. package/pb_public/sw.js +1 -0
  136. package/scripts/fetch-pocketbase.sh +63 -0
  137. package/scripts/start.mjs +93 -0
@@ -0,0 +1,189 @@
1
+ /// <reference path="../../types/pocketbase.d.ts" />
2
+ // Anonymous rooms (DESIGN.md §35): a room a superuser marks `anonymous` shows its messages as the room's, not their
3
+ // authors'. Each message is stamped when it is made (`anonymous`, `forwarded_anonymous`), so turning the flag on later
4
+ // hides nothing already seen, and turning it off shows nothing that was posted unseen. The real author stays stored:
5
+ // they still edit and delete their messages, and see them as their own. Everyone else gets, in every answer and live
6
+ // event, the room in place of the author, and can't find out who it is by filtering, sorting or expanding on it.
7
+
8
+ /**
9
+ * What the messages of anonymous room `roomId` show as: its name, and whether it is private. Kept by the app until the
10
+ * room is saved again (forget).
11
+ * @param {core.App} app
12
+ * @param {string} roomId
13
+ * @returns {{ name: string, private: boolean }}
14
+ */
15
+ function roomOf(app, roomId) {
16
+ const key = `anonymous.${roomId}`;
17
+ const kept = app.store().get(key);
18
+ if (kept) return { name: String(kept.name), private: !!kept.private };
19
+ // Not with getOrSet: it holds the store while it looks, and finding a record reads PocketBase's collections there.
20
+ let room = { name: "Anonymous", private: true };
21
+ try {
22
+ const rec = app.findRecordById("rooms", roomId);
23
+ room = { name: rec.getString("name") || "Anonymous", private: rec.getString("visibility") === "private" };
24
+ } catch {
25
+ return room; // being removed
26
+ }
27
+ app.store().set(key, room);
28
+ return room;
29
+ }
30
+
31
+ /** @param {core.App} app @param {string} roomId */
32
+ const roomName = (app, roomId) => roomOf(app, roomId).name;
33
+
34
+ /**
35
+ * A forward's "from": the room's name, but not a private room's to readers elsewhere, who may not know it.
36
+ * @param {core.App} app
37
+ * @param {string} roomId
38
+ */
39
+ function sourceName(app, roomId) {
40
+ const room = roomOf(app, roomId);
41
+ return room.private ? "Anonymous" : room.name;
42
+ }
43
+
44
+ /**
45
+ * rooms saved or deleted: its name is read again when next needed.
46
+ * @param {core.App} app
47
+ * @param {string} roomId
48
+ */
49
+ function forget(app, roomId) {
50
+ app.store().remove(`anonymous.${roomId}`);
51
+ }
52
+
53
+ /**
54
+ * Who an anonymous message shows as: a users record that is never saved, with the room's id and `name`. It takes no DMs,
55
+ * so the clients offer none.
56
+ * @param {core.App} app
57
+ * @param {string} id
58
+ * @param {string} name
59
+ */
60
+ function standIn(app, id, name) {
61
+ const user = new Record(app.findCollectionByNameOrId("users"));
62
+ user.set("id", id);
63
+ user.set("name", name);
64
+ user.set("no_dms", true);
65
+ return user;
66
+ }
67
+
68
+ /**
69
+ * Put `user` in the message's expand under `field`, in place of what is there (or also when nothing is, `add`): a new
70
+ * map, as the expanded record of the real author may be the one other messages of theirs show too.
71
+ * @param {core.Record} rec
72
+ * @param {string} field
73
+ * @param {core.Record} user
74
+ * @param {boolean} [add]
75
+ */
76
+ function setExpanded(rec, field, user, add = false) {
77
+ const expand = rec.expand() ?? {};
78
+ if (expand[field] == null && !add) return;
79
+ /** @type {Record<string, any>} */
80
+ const next = {};
81
+ for (const k of Object.keys(expand)) next[k] = expand[k];
82
+ next[field] = user;
83
+ rec.setExpand(next);
84
+ }
85
+
86
+ /**
87
+ * messages enrich, once expanded, for one stamped `anonymous` or `forwarded_anonymous` or quoting one (lib/enrich.js
88
+ * isAnonymous): to anyone but its author and superusers, the author is its room, and a forward is from the original's
89
+ * room. Only in the answer.
90
+ * @param {core.RecordEnrichEvent} e
91
+ */
92
+ function hide(e) {
93
+ const rec = e.record;
94
+ const auth = e.requestInfo?.auth;
95
+ if (!rec || auth?.isSuperuser()) return;
96
+ // The quoted message hid its author when it was fetched, before its own expand (reply_to.author) looked for them.
97
+ const quoted = rec.expand()?.reply_to;
98
+ if (quoted?.getBool?.("anonymous") && quoted.getString("author") === quoted.getString("room")) {
99
+ setExpanded(quoted, "author", standIn(e.app, quoted.getString("room"), roomName(e.app, quoted.getString("room"))), true);
100
+ }
101
+ const me = auth?.id ?? "";
102
+ const author = rec.getString("author");
103
+ if (rec.getBool("anonymous") && author && author !== me) {
104
+ const room = rec.getString("room");
105
+ rec.set("author", room);
106
+ setExpanded(rec, "author", standIn(e.app, room, roomName(e.app, room)));
107
+ }
108
+ const from = rec.getString("forwarded_from");
109
+ if (rec.getBool("forwarded_anonymous") && from && from !== me) {
110
+ let room = "";
111
+ try {
112
+ room = rec.getString("forward_of") ? e.app.findRecordById("messages", rec.getString("forward_of")).getString("room") : "";
113
+ } catch {
114
+ room = ""; // the original is being removed for good
115
+ }
116
+ const id = room || rec.id;
117
+ rec.set("forwarded_from", id);
118
+ setExpanded(rec, "forwarded_from", standIn(e.app, id, room ? sourceName(e.app, room) : "Anonymous"));
119
+ }
120
+ }
121
+
122
+ /** Fields whose value says who wrote a message: no one but a superuser filters or sorts on them. */
123
+ const AUTHOR_FIELD = /(^|[^a-z0-9])(author|forwarded_from)(?![a-z0-9])/i;
124
+ /** A back-relation from users to the messages they wrote: expanded, it would group them by author. */
125
+ const AUTHOR_BACK_RELATION = /_via_(author|forwarded_from)(?![a-z0-9_])/i;
126
+
127
+ /**
128
+ * An author compared with the caller (`author != {:me}`, `reply_to.author = {:me}`): says only which messages are
129
+ * the caller's own. Apps from before 2026-10-29 filter so (docs/API.md); `ME` stands for the caller's id.
130
+ */
131
+ const OWN_AUTHOR = String.raw`\b(author|forwarded_from)\s*(=|!=|\?=|\?!=)\s*(@request\.auth\.id\b|"ME"|'ME')`;
132
+
133
+ /**
134
+ * Does a filter, sort or expand (as a client sends it) say who wrote a message? Quoted text is a value, not a field.
135
+ * @param {{ filter?: unknown, sort?: unknown, expand?: unknown }} q
136
+ * @param {string} me the caller's id ("" for guests)
137
+ */
138
+ function probes(q, me) {
139
+ const own = new RegExp(OWN_AUTHOR.replace(/ME/g, me.replace(/[^a-z0-9]/gi, "") || "@"), "gi");
140
+ const fields = `${q.filter ?? ""} ${q.sort ?? ""}`.replace(own, "").replace(/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'/g, "''");
141
+ return AUTHOR_FIELD.test(fields) || AUTHOR_BACK_RELATION.test(String(q.expand ?? ""));
142
+ }
143
+
144
+ const REFUSAL = "Messages can't be filtered, sorted or grouped by who wrote them.";
145
+
146
+ /**
147
+ * Every request: refused when its query filters, sorts or groups by author (the records API's ?filter, ?sort, ?expand,
148
+ * on any collection, as a relation or back-relation can reach messages from any of them). Superusers may.
149
+ * @param {core.RequestEvent} e
150
+ */
151
+ function refuseProbes(e) {
152
+ const q = e.request?.url?.query();
153
+ if (!q || (!q.has("filter") && !q.has("sort") && !q.has("expand"))) return;
154
+ if (!probes({ filter: q.get("filter"), sort: q.get("sort"), expand: q.get("expand") }, e.auth?.id ?? "")) return;
155
+ if (e.hasSuperuserAuth()) return;
156
+ throw new BadRequestError(REFUSAL);
157
+ }
158
+
159
+ /**
160
+ * Realtime subscriptions: the same, for the filter, sort and expand in a subscription's options.
161
+ * @param {core.RealtimeSubscribeRequestEvent} e
162
+ */
163
+ function refuseSubscriptionProbes(e) {
164
+ if (e.hasSuperuserAuth()) return;
165
+ for (const topic of e.subscriptions ?? []) {
166
+ const at = topic.indexOf("?options=");
167
+ if (at < 0) continue;
168
+ let query = {};
169
+ try {
170
+ query = JSON.parse(decodeURIComponent(topic.slice(at + "?options=".length)))?.query ?? {};
171
+ } catch {
172
+ query = {}; // PocketBase ignores options it can't read
173
+ }
174
+ if (probes(query, e.auth?.id ?? "")) throw new BadRequestError(REFUSAL);
175
+ }
176
+ }
177
+
178
+ /**
179
+ * The media grid's author of an item (lib/media.js list): the room for an anonymous message, as hide does.
180
+ * @param {core.RequestEvent} e the caller's request (superusers see the author)
181
+ * @param {{ author: string, name: string, anonymous: boolean, room: string }} row
182
+ */
183
+ function gridAuthor(e, row) {
184
+ if (!row.author) return null;
185
+ if (row.anonymous && row.author !== (e.auth?.id ?? "") && !e.hasSuperuserAuth()) return { id: row.room, name: roomName(e.app, row.room) };
186
+ return { id: row.author, name: row.name };
187
+ }
188
+
189
+ module.exports = { hide, forget, roomName, sourceName, refuseProbes, refuseSubscriptionProbes, gridAuthor };
@@ -0,0 +1,187 @@
1
+ /// <reference path="../../types/pocketbase.d.ts" />
2
+ // Acting on several messages at once (DESIGN.md §21): POST /api/chat/delete soft-deletes the caller's own messages,
3
+ // POST /api/chat/forward forwards messages the caller can see into another room or DM, pointing at them (nothing is copied). All or nothing: each runs in one
4
+ // transaction. The saves go through the messages hooks (messages.js) like any other, so the soft delete wipes what it
5
+ // should, a forward is checked like a new message, and realtime tells everyone.
6
+
7
+ const { canWrite } = require(`${__hooks}/lib/access.js`);
8
+ const { isService } = require(`${__hooks}/lib/messages.js`);
9
+ const { canModerate } = require(`${__hooks}/lib/moderation.js`);
10
+
11
+ /** Most messages one request may act on (MAX_SELECTED in web/src/lib/limits.ts). */
12
+ const MAX_MESSAGES = 50;
13
+
14
+ /**
15
+ * @param {string} field
16
+ * @param {string} message
17
+ * @param {string} [what]
18
+ */
19
+ const badRequest = (field, message, what = "Failed to update the messages.") =>
20
+ new BadRequestError(what, { [field]: new ValidationError("validation_invalid_value", message) });
21
+
22
+ /**
23
+ * The message ids of the request body: distinct, 1 to MAX_MESSAGES of them.
24
+ * @param {Record<string, unknown>} body
25
+ * @param {string} what
26
+ */
27
+ function messageIds(body, what) {
28
+ const raw = body.messages;
29
+ if (!Array.isArray(raw) || !raw.length || raw.some((id) => typeof id !== "string" || !id)) {
30
+ throw badRequest("messages", "Choose at least one message.", what);
31
+ }
32
+ const ids = [.../** @type {Set<string>} */ (new Set(raw))];
33
+ if (ids.length > MAX_MESSAGES) throw badRequest("messages", `At most ${MAX_MESSAGES} messages at a time.`, what);
34
+ return ids;
35
+ }
36
+
37
+ /**
38
+ * Can the caller see `rec` where it is (its collection's list rule)? Not the messages view rule, which also lets the
39
+ * readers of a forward view its original (§21.3), in a room they can't see. Someone else's DM gets the same answer
40
+ * as a record that doesn't exist.
41
+ * @param {core.RequestEvent} e
42
+ * @param {core.RequestInfo} info
43
+ * @param {string} collection
44
+ * @param {string} id
45
+ * @returns {core.Record | null}
46
+ */
47
+ function visible(e, info, collection, id) {
48
+ let rec;
49
+ try {
50
+ rec = e.app.findRecordById(collection, id);
51
+ } catch {
52
+ return null;
53
+ }
54
+ const rule = e.app.findCollectionByNameOrId(collection).listRule;
55
+ return rule !== null && rule !== undefined && e.app.canAccessRecord(rec, info, rule) ? rec : null;
56
+ }
57
+
58
+ /**
59
+ * The messages with these ids, oldest first (as they are shown), all visible to the caller; else a 404.
60
+ * @param {core.RequestEvent} e
61
+ * @param {core.RequestInfo} info
62
+ * @param {string[]} ids
63
+ */
64
+ function visibleMessages(e, info, ids) {
65
+ const found = ids.map((id) => visible(e, info, "messages", id));
66
+ if (found.some((m) => !m)) throw new NotFoundError("A message doesn't exist.");
67
+ const msgs = /** @type {core.Record[]} */ (found);
68
+ const key = (/** @type {core.Record} */ m) => `${m.getString("created")}|${m.id}`;
69
+ return msgs.sort((a, b) => (key(a) < key(b) ? -1 : key(a) > key(b) ? 1 : 0));
70
+ }
71
+
72
+ /**
73
+ * The saved messages as GET /api/collections/messages/records/:id answers them (the same ?expand and ?fields apply).
74
+ * @param {core.RequestEvent} e
75
+ * @param {core.Record[]} recs
76
+ */
77
+ function answer(e, recs) {
78
+ $apis.enrichRecords(e, recs);
79
+ return e.json(200, recs);
80
+ }
81
+
82
+ /**
83
+ * POST /api/chat/delete { messages: [ids] } → the messages, soft-deleted (§21.2). Only the caller's own, in rooms that
84
+ * aren't archived and they may still post in; a moderator's, anyone's outside DMs (§36). Already deleted ones are left
85
+ * as they are, so a retry succeeds.
86
+ * @param {core.RequestEvent} e
87
+ */
88
+ function deleteMessages(e) {
89
+ const me = e.auth;
90
+ if (!me) throw new UnauthorizedError("The request requires a logged-in user.");
91
+ const what = "Failed to delete the messages.";
92
+ const info = e.requestInfo();
93
+ const msgs = visibleMessages(e, info, messageIds(/** @type {Record<string, unknown>} */ (info.body), what));
94
+ const rooms = msgs.map((m) => e.app.findRecordById("rooms", m.getString("room")));
95
+ const moderating = rooms.map((r) => canModerate(r, me));
96
+ if (msgs.some((m, i) => m.getString("author") !== me.id && !moderating[i])) {
97
+ throw new ForbiddenError("You can only delete your own messages.");
98
+ }
99
+ // The app's own lines stay (no author has them; only a moderator gets this far).
100
+ if (msgs.some(isService)) throw badRequest("messages", "Service messages can't be deleted.", what);
101
+ // (Archived meanwhile: beforeMessageUpdate refuses the save, and the transaction rolls back.)
102
+ if (rooms.some((r) => r.getBool("archived"))) throw badRequest("messages", "This room is archived and read-only.", what);
103
+ // As the update rule says: no longer allowed to post there, no deleting either (§23.6). Moderators still can.
104
+ if (rooms.some((r, i) => !moderating[i] && !canWrite(r, me.id))) {
105
+ throw badRequest("messages", "Only some people can post in this room.", what);
106
+ }
107
+
108
+ /** @type {core.Record[]} */
109
+ const saved = [];
110
+ e.app.runInTransaction((tx) => {
111
+ for (const m of msgs) {
112
+ const rec = tx.findRecordById("messages", m.id);
113
+ saved.push(rec);
114
+ if (rec.getBool("deleted")) continue;
115
+ rec.set("deleted", true);
116
+ tx.save(rec);
117
+ }
118
+ });
119
+ return answer(e, saved);
120
+ }
121
+
122
+ /**
123
+ * What a message shows when forwarded (§21.3): itself, or for a forward, the message it shows. Null when that is
124
+ * deleted, or gone (a forward whose original was removed for good shows nothing).
125
+ * @param {core.App} app
126
+ * @param {core.Record} m
127
+ */
128
+ function originalOf(app, m) {
129
+ if (m.getBool("deleted")) return null;
130
+ const id = m.getString("forward_of");
131
+ if (!id) {
132
+ const empty = m.getString("text") === "" && m.getStringSlice("files").length === 0;
133
+ return m.getString("forwarded_from") !== "" && empty ? null : m;
134
+ }
135
+ try {
136
+ const original = app.findRecordById("messages", id);
137
+ return original.getBool("deleted") ? null : original;
138
+ } catch {
139
+ return null;
140
+ }
141
+ }
142
+
143
+ /**
144
+ * POST /api/chat/forward { messages: [ids], room } → the new messages in `room` (§21.3), oldest first, by the caller:
145
+ * forwards pointing at the given messages (`forward_of`; a forward of a forward points at its original), showing their
146
+ * text and attachments as they are now, and saying who first wrote them (`forwarded_from`). Nothing is copied, so a
147
+ * forward costs a row however big its attachments are. Replies, reactions and edit stamps aren't forwarded.
148
+ * @param {core.RequestEvent} e
149
+ */
150
+ function forward(e) {
151
+ const me = e.auth;
152
+ if (!me) throw new UnauthorizedError("The request requires a logged-in user.");
153
+ const what = "Failed to forward the messages.";
154
+ const info = e.requestInfo();
155
+ const body = /** @type {Record<string, unknown>} */ (info.body);
156
+ const ids = messageIds(body, what);
157
+ const room = visible(e, info, "rooms", typeof body.room === "string" ? body.room : "");
158
+ if (!room) throw new NotFoundError("The room doesn't exist.");
159
+ if (room.getBool("archived")) throw badRequest("room", "This room is archived and read-only.", what);
160
+ const originals = visibleMessages(e, info, ids).map((m) => originalOf(e.app, m));
161
+ if (originals.some((m) => !m)) throw badRequest("messages", "A message was deleted.", what);
162
+ if (originals.some((m) => m && isService(m))) throw badRequest("messages", "Service messages can't be forwarded.", what);
163
+
164
+ const collection = e.app.findCollectionByNameOrId("messages");
165
+ /** @type {core.Record[]} */
166
+ const saved = [];
167
+ e.app.runInTransaction((tx) => {
168
+ // One millisecond apart, so they keep their order: messages sort by (created, id), and ids are random.
169
+ const now = Date.now();
170
+ /** @type {core.Record[]} */ (originals).forEach((src, i) => {
171
+ const rec = new Record(collection);
172
+ const at = new Date(now + i).toISOString().replace("T", " ");
173
+ rec.setRaw("created", at);
174
+ rec.setRaw("updated", at);
175
+ rec.set("room", room.id);
176
+ rec.set("author", me.id);
177
+ rec.set("text", "");
178
+ rec.set("forward_of", src.id);
179
+ rec.set("forwarded_from", src.getString("forwarded_from") || src.getString("author"));
180
+ tx.save(rec);
181
+ saved.push(rec);
182
+ });
183
+ });
184
+ return answer(e, saved);
185
+ }
186
+
187
+ module.exports = { deleteMessages, forward, MAX_MESSAGES };