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,420 @@
1
+ /// <reference path="../../types/pocketbase.d.ts" />
2
+ // Messages in shared rooms (DESIGN.md §33.5, §33.6). A message written on a mirror goes to the home, which saves it
3
+ // and passes it on to every other mirror; edits, deletes and reactions go the same way, the home deciding. A copy
4
+ // keeps the message's global id (`messages.remote_id`, unique per room), which replies, edits and reactions name it by.
5
+ // A message with files is saved once its files are fetched (the worker, §33.8); a forward goes as a snapshot of what it
6
+ // shows. Service messages, reads, previews and push stay on each instance.
7
+
8
+ const { reactionsOf, setReaction } = require(`${__hooks}/lib/reactions.js`);
9
+ /** @typedef {{ emoji: string, users: string[] }} Reaction */
10
+ const { isReactionEmoji } = require(`${__hooks}/lib/emoji.js`);
11
+ const { enqueue, enqueueWork, fromPeer, gid, isMine, jsonOf, newId, originOf, peerById, peerHost, splitGid } = require(
12
+ `${__hooks}/federation/config.js`,
13
+ );
14
+ const { gidOf, peopleFor, standInRow, userOf } = require(`${__hooks}/federation/people.js`);
15
+ const { isMirror, refusal, roomFor, roomGid, sharesOf } = require(`${__hooks}/federation/rooms.js`);
16
+
17
+ /** Files one message may have (§17.1). */
18
+ const MAX_FILES = 10;
19
+
20
+ /** A message's global id. @param {core.Record} rec */
21
+ const messageGid = (rec) => rec.getString("remote_id") || gid(rec.id);
22
+
23
+ /**
24
+ * The message of room `roomId` that global id `g` names: a copy (by remote_id), or one written here.
25
+ * @param {core.App} app
26
+ * @param {string} roomId
27
+ * @param {unknown} g
28
+ */
29
+ function messageIn(app, roomId, g) {
30
+ const s = splitGid(g);
31
+ if (!s) return null;
32
+ try {
33
+ return app.findFirstRecordByFilter("messages", "room = {:r} && remote_id = {:g}", { r: roomId, g: String(g) });
34
+ } catch {
35
+ // not a copy
36
+ }
37
+ try {
38
+ const rec = app.findRecordById("messages", s.id);
39
+ return rec.getString("room") === roomId && !rec.getString("remote_id") && gid(rec.id) === g ? rec : null;
40
+ } catch {
41
+ return null;
42
+ }
43
+ }
44
+
45
+ /**
46
+ * @param {core.App} app
47
+ * @param {string} id
48
+ */
49
+ function findMessage(app, id) {
50
+ try {
51
+ return app.findRecordById("messages", id);
52
+ } catch {
53
+ return null;
54
+ }
55
+ }
56
+
57
+ /**
58
+ * Reactions with people as global ids.
59
+ * @param {core.App} app
60
+ * @param {core.Record} rec
61
+ */
62
+ const reactionsOut = (app, rec) =>
63
+ reactionsOf(rec).map((/** @type {Reaction} */ r) => ({ emoji: r.emoji, users: r.users.map((u) => gidOf(app, u)) }));
64
+
65
+ /**
66
+ * A message as a `message` event to `peer` (§33.6): a forward as what it shows (its original's text and files, now).
67
+ * Null for one that shows nothing.
68
+ * @param {core.App} app
69
+ * @param {core.Record} rec
70
+ * @param {core.Record} peer
71
+ */
72
+ function messageEvent(app, rec, peer) {
73
+ const room = app.findRecordById("rooms", rec.getString("room"));
74
+ let src = rec;
75
+ if (rec.getString("forward_of")) {
76
+ const original = findMessage(app, rec.getString("forward_of"));
77
+ if (!original || original.getBool("deleted")) return null;
78
+ src = original;
79
+ }
80
+ const names = jsonOf(src, "file_names", {});
81
+ const files = src.getStringSlice("files").map((f) => ({ path: `/api/fed/files/${rec.id}/${f}`, name: String(names[f] || f) }));
82
+ const reply = rec.getString("reply_to") ? findMessage(app, rec.getString("reply_to")) : null;
83
+ const author = rec.getString("author");
84
+ const from = rec.getString("forwarded_from");
85
+ const reactions = reactionsOf(rec);
86
+ return {
87
+ type: "message",
88
+ room: roomGid(room),
89
+ message: {
90
+ id: messageGid(rec),
91
+ author: gidOf(app, author),
92
+ text: src.getString("text"),
93
+ reply_to: reply ? messageGid(reply) : "",
94
+ forwarded_from: from ? gidOf(app, from) : "",
95
+ created: rec.getString("created"),
96
+ files,
97
+ reactions: reactionsOut(app, rec),
98
+ },
99
+ people: peopleFor(app, peer, [author, from, ...reactions.flatMap((/** @type {Reaction} */ r) => r.users)]),
100
+ };
101
+ }
102
+
103
+ /**
104
+ * Who a change in this room goes to: the home, for a mirror's own change; every mirror but the one it came from, for
105
+ * the home's. `all`: the sender too (the home's word on reactions is final).
106
+ * @param {core.App} app
107
+ * @param {core.Record} room
108
+ * @param {string} recordId
109
+ * @param {boolean} [all]
110
+ * @returns {string[]} peer ids
111
+ */
112
+ function audience(app, room, recordId, all = false) {
113
+ const origin = originOf(app, recordId);
114
+ if (isMirror(room)) return origin ? [] : [room.getString("peer")];
115
+ return sharesOf(app, room.id)
116
+ .map((/** @type {core.Record} */ s) => s.getString("peer"))
117
+ .filter((/** @type {string} */ p) => all || p !== origin);
118
+ }
119
+
120
+ /**
121
+ * messages create (saved): a message by someone goes to where its room is shared (§33.5).
122
+ * @param {core.App} app
123
+ * @param {core.Record} rec
124
+ */
125
+ function messageCreated(app, rec) {
126
+ if (!rec.getString("author")) return; // a service message stays here
127
+ const room = app.findRecordById("rooms", rec.getString("room"));
128
+ for (const peerId of audience(app, room, rec.id)) {
129
+ const peer = peerById(app, peerId);
130
+ const ev = peer ? messageEvent(app, rec, peer) : null;
131
+ if (ev) enqueue(app, peerId, ev);
132
+ }
133
+ }
134
+
135
+ /**
136
+ * What a messages update changes for peers, read before it is saved.
137
+ * @param {core.Record} rec
138
+ */
139
+ function before(rec) {
140
+ const orig = rec.original();
141
+ return { text: orig.getString("text"), deleted: orig.getBool("deleted"), reactions: reactionsOf(orig) };
142
+ }
143
+
144
+ /**
145
+ * messages update request on a mirror: only its own people's messages are changed here; the home's word goes for the
146
+ * rest (§33.5). Reactions are anyone's.
147
+ * @param {core.App} app
148
+ * @param {core.Record} rec
149
+ */
150
+ function checkMirrorChange(app, rec) {
151
+ const orig = rec.original();
152
+ if (rec.getString("text") === orig.getString("text") && rec.getBool("deleted") === orig.getBool("deleted")) return;
153
+ if (originOf(app, rec.id)) return;
154
+ let room;
155
+ try {
156
+ room = app.findRecordById("rooms", rec.getString("room"));
157
+ } catch {
158
+ return;
159
+ }
160
+ if (isMirror(room) && standInRow(app, orig.getString("author"))) {
161
+ throw new BadRequestError("This message is from another instance; it is changed there.");
162
+ }
163
+ }
164
+
165
+ /**
166
+ * messages update (saved): an edit, delete or reaction goes where its room is shared.
167
+ * @param {core.App} app
168
+ * @param {core.Record} rec
169
+ * @param {ReturnType<typeof before>} was
170
+ */
171
+ function messageChanged(app, rec, was) {
172
+ if (!rec.getString("author")) return;
173
+ let room;
174
+ try {
175
+ room = app.findRecordById("rooms", rec.getString("room"));
176
+ } catch {
177
+ return;
178
+ }
179
+ if (!isMirror(room) && !sharesOf(app, room.id).length) return;
180
+ const g = messageGid(rec);
181
+ const rg = roomGid(room);
182
+ const deleted = rec.getBool("deleted") && !was.deleted;
183
+ const edited = !rec.getBool("deleted") && rec.getString("text") !== was.text;
184
+ if (deleted || edited) {
185
+ for (const peerId of audience(app, room, rec.id)) {
186
+ enqueue(
187
+ app,
188
+ peerId,
189
+ deleted ? { type: "delete", room: rg, message: g } : { type: "edit", room: rg, message: g, text: rec.getString("text") },
190
+ );
191
+ }
192
+ }
193
+ const now = reactionsOf(rec);
194
+ if (deleted || JSON.stringify(now) === JSON.stringify(was.reactions)) return;
195
+ if (isMirror(room)) {
196
+ if (originOf(app, rec.id)) return;
197
+ // This instance's own people's reactions, as add/remove requests.
198
+ const has = (/** @type {typeof now} */ list, /** @type {string} */ emoji, /** @type {string} */ u) =>
199
+ list.some((/** @type {Reaction} */ r) => r.emoji === emoji && r.users.includes(u));
200
+ const changes = [];
201
+ for (const r of now) for (const u of r.users) if (!has(was.reactions, r.emoji, u)) changes.push({ emoji: r.emoji, user: u, on: true });
202
+ for (const r of was.reactions) for (const u of r.users) if (!has(now, r.emoji, u)) changes.push({ emoji: r.emoji, user: u, on: false });
203
+ for (const c of changes) {
204
+ if (standInRow(app, c.user)) continue;
205
+ enqueue(app, room.getString("peer"), { type: "react", room: rg, message: g, emoji: c.emoji, on: c.on, user: gid(c.user) });
206
+ }
207
+ return;
208
+ }
209
+ for (const peerId of audience(app, room, rec.id, true)) {
210
+ const peer = peerById(app, peerId);
211
+ if (!peer) continue;
212
+ enqueue(app, peerId, {
213
+ type: "reactions",
214
+ room: rg,
215
+ message: g,
216
+ list: reactionsOut(app, rec),
217
+ people: peopleFor(
218
+ app,
219
+ peer,
220
+ now.flatMap((/** @type {Reaction} */ r) => r.users),
221
+ ),
222
+ });
223
+ }
224
+ }
225
+
226
+ // ---------------------------------------------------------------- events from a peer
227
+
228
+ /**
229
+ * Save a record for a peer's event: the hooks then don't send it back to it.
230
+ * @param {core.App} app
231
+ * @param {core.Record} rec
232
+ * @param {core.Record} sender
233
+ */
234
+ function saveFor(app, rec, sender) {
235
+ fromPeer(app, rec.id, sender.id, () => app.save(rec));
236
+ }
237
+
238
+ /**
239
+ * The room of a message event and whether this is its home; refused when the sender may not name it.
240
+ * @param {core.App} app
241
+ * @param {core.Record} sender
242
+ * @param {any} ev
243
+ */
244
+ function roomOf(app, sender, ev) {
245
+ const found = roomFor(app, sender, ev.room);
246
+ if (!found) throw refusal(403, "That room isn't shared with you.");
247
+ return found;
248
+ }
249
+
250
+ /**
251
+ * A `message` event (§33.6). On the home, only from the author's own instance; on a mirror, from its home. With
252
+ * files, it waits for the worker to fetch them (`files`: the fetched ones, then).
253
+ * @param {core.App} app
254
+ * @param {core.Record} sender
255
+ * @param {any} ev
256
+ * @param {any[]} [files] filesystem.File
257
+ */
258
+ function applyMessage(app, sender, ev, files) {
259
+ const { room, home } = roomOf(app, sender, ev);
260
+ const m = ev.message && typeof ev.message === "object" ? ev.message : {};
261
+ const g = String(m.id || "");
262
+ if (!splitGid(g)) throw refusal(400, "No message id.");
263
+ if (messageIn(app, room.id, g)) return; // had it
264
+ const people = ev.people && typeof ev.people === "object" ? ev.people : {};
265
+ // Our own people write here, never through a peer: a home naming one of them as the author would speak for them
266
+ // (QA BUG-173). What they wrote in its room it already has from us, and doesn't send back.
267
+ if (isMine(String(m.author || ""))) throw refusal(403, "People of this instance write here themselves.");
268
+ const author = userOf(app, sender, m.author, people, home);
269
+ if (!author) throw refusal(403, home ? "Only your own people write here." : "The author is unknown.");
270
+ const listed = (Array.isArray(m.files) ? m.files : []).slice(0, MAX_FILES);
271
+ if (listed.length && !files) {
272
+ enqueueWork(app, sender.id, "fetch", { event: ev });
273
+ return;
274
+ }
275
+ const rec = new Record(app.findCollectionByNameOrId("messages"));
276
+ rec.set("id", newId());
277
+ rec.set("room", room.id);
278
+ rec.set("author", author);
279
+ rec.set("text", String(m.text || "").slice(0, 2000));
280
+ rec.set("remote_id", g);
281
+ const reply = m.reply_to ? messageIn(app, room.id, m.reply_to) : null;
282
+ if (reply && !reply.getBool("deleted") && reply.getString("author")) rec.set("reply_to", reply.id);
283
+ if (m.forwarded_from) {
284
+ const from = userOf(app, sender, m.forwarded_from, people);
285
+ if (from) rec.set("forwarded_from", from);
286
+ }
287
+ if (files?.length) require(`${__hooks}/lib/files.js`).attachUploads(app, rec, files);
288
+ if (ev.backfill && typeof m.created === "string" && /^\d{4}-\d\d-\d\d[ T]\d\d:\d\d:\d\d/.test(m.created)) {
289
+ rec.setRaw("created", m.created);
290
+ rec.setRaw("updated", m.created);
291
+ }
292
+ if (!rec.getString("text") && !files?.length && !rec.getString("forwarded_from")) return; // nothing to show
293
+ saveFor(app, rec, sender);
294
+ const list = Array.isArray(m.reactions) ? m.reactions : [];
295
+ if (list.length) setReactions(app, sender, rec, list, people);
296
+ }
297
+
298
+ /**
299
+ * Set a message's reactions from a list naming people by global id.
300
+ * @param {core.App} app
301
+ * @param {core.Record} sender
302
+ * @param {core.Record} rec
303
+ * @param {any[]} list
304
+ * @param {Record<string, any>} people
305
+ */
306
+ function setReactions(app, sender, rec, list, people) {
307
+ const out = [];
308
+ for (const r of list.slice(0, 64)) {
309
+ if (!r || !isReactionEmoji(r.emoji) || !Array.isArray(r.users)) continue;
310
+ const users = [...new Set(r.users.map((/** @type {unknown} */ u) => userOf(app, sender, u, people)).filter(Boolean))];
311
+ if (users.length) out.push({ emoji: r.emoji, users });
312
+ }
313
+ if (JSON.stringify(out) === JSON.stringify(reactionsOf(rec))) return;
314
+ rec.set("reactions", out);
315
+ saveFor(app, rec, sender);
316
+ }
317
+
318
+ /**
319
+ * The message an edit, delete or reaction names; on the home, an edit or delete only of the sender's own people's.
320
+ * Null when it isn't here (not shared yet, or still being fetched).
321
+ * @param {core.App} app
322
+ * @param {core.Record} sender
323
+ * @param {any} ev
324
+ * @param {boolean} ownOnly
325
+ */
326
+ function target(app, sender, ev, ownOnly) {
327
+ const { room, home } = roomOf(app, sender, ev);
328
+ const rec = messageIn(app, room.id, ev.message);
329
+ if (!rec) return null;
330
+ if (home && ownOnly && splitGid(gidOf(app, rec.getString("author")))?.host !== peerHost(sender)) {
331
+ throw refusal(403, "Only your own people's messages are changed from there.");
332
+ }
333
+ return rec;
334
+ }
335
+
336
+ /**
337
+ * An `edit` event.
338
+ * @param {core.App} app
339
+ * @param {core.Record} sender
340
+ * @param {any} ev
341
+ */
342
+ function applyEdit(app, sender, ev) {
343
+ const rec = target(app, sender, ev, true);
344
+ if (!rec || rec.getBool("deleted")) return;
345
+ // On a mirror the home names any message, but our own people's words are edited only here (QA BUG-174). A delete
346
+ // still comes through: the home's superusers may take a message out of their room.
347
+ if (isMine(gidOf(app, rec.getString("author")))) throw refusal(403, "People of this instance edit their messages here.");
348
+ const text = String(ev.text || "").slice(0, 2000);
349
+ if (text === rec.getString("text")) return;
350
+ rec.set("text", text);
351
+ saveFor(app, rec, sender);
352
+ }
353
+
354
+ /**
355
+ * A `delete` event. A message still being fetched is dropped from the queue.
356
+ * @param {core.App} app
357
+ * @param {core.Record} sender
358
+ * @param {any} ev
359
+ */
360
+ function applyDelete(app, sender, ev) {
361
+ const rec = target(app, sender, ev, true);
362
+ if (!rec) {
363
+ for (const row of app.findRecordsByFilter("fed_queue", "peer = {:p} && op = 'fetch'", "", 0, 0, { p: sender.id })) {
364
+ if (row && jsonOf(row, "payload", {}).event?.message?.id === ev.message) app.delete(row);
365
+ }
366
+ return;
367
+ }
368
+ if (rec.getBool("deleted")) return;
369
+ rec.set("deleted", true);
370
+ saveFor(app, rec, sender);
371
+ }
372
+
373
+ /**
374
+ * A `react` event on the home: one of the sender's own people's reactions, on or off.
375
+ * @param {core.App} app
376
+ * @param {core.Record} sender
377
+ * @param {any} ev
378
+ */
379
+ function applyReact(app, sender, ev) {
380
+ const { home } = roomOf(app, sender, ev);
381
+ if (!home) throw refusal(403, "Reactions go to the room's home.");
382
+ if (!isReactionEmoji(ev.emoji) || typeof ev.on !== "boolean") throw refusal(400, "Not a reaction.");
383
+ const user = userOf(app, sender, ev.user, ev.people || {}, true);
384
+ if (!user) throw refusal(403, "Only your own people react from there.");
385
+ const rec = target(app, sender, ev, false);
386
+ if (!rec || rec.getBool("deleted") || !rec.getString("author")) return;
387
+ const next = setReaction(reactionsOf(rec), ev.emoji, user, ev.on);
388
+ if (!next) return;
389
+ rec.set("reactions", next);
390
+ saveFor(app, rec, sender);
391
+ }
392
+
393
+ /**
394
+ * A `reactions` event on a mirror: the home's whole list for a message.
395
+ * @param {core.App} app
396
+ * @param {core.Record} sender
397
+ * @param {any} ev
398
+ */
399
+ function applyReactions(app, sender, ev) {
400
+ const { home } = roomOf(app, sender, ev);
401
+ if (home) throw refusal(403, "Only a room's home sends its reactions.");
402
+ const rec = target(app, sender, ev, false);
403
+ if (!rec || rec.getBool("deleted")) return;
404
+ setReactions(app, sender, rec, Array.isArray(ev.list) ? ev.list : [], ev.people || {});
405
+ }
406
+
407
+ module.exports = {
408
+ MAX_FILES,
409
+ messageGid,
410
+ messageEvent,
411
+ messageCreated,
412
+ before,
413
+ checkMirrorChange,
414
+ messageChanged,
415
+ applyMessage,
416
+ applyEdit,
417
+ applyDelete,
418
+ applyReact,
419
+ applyReactions,
420
+ };
@@ -0,0 +1,277 @@
1
+ /// <reference path="../../types/pocketbase.d.ts" />
2
+ // Shared rooms on a mirror's side (DESIGN.md §33.5): the events a home sends about its rooms (share, unshare, room),
3
+ // and what a mirror's superusers may change themselves (its name; in a private room, their own people, which goes to
4
+ // the home as a `members` request). The home's side is federation/rooms.js.
5
+
6
+ const { MAX_MEMBERS } = require(`${__hooks}/lib/access.js`);
7
+ const { fieldError } = require(`${__hooks}/lib/records.js`);
8
+ const { nameKey, stripHashes, tidy } = require(`${__hooks}/lib/text.js`);
9
+ const { enqueue, gid, jsonOf, myHost, newId, peerById, peerHost, splitGid } = require(`${__hooks}/federation/config.js`);
10
+ const { peopleFor, standInRow, userOf } = require(`${__hooks}/federation/people.js`);
11
+ const {
12
+ ROOM_NAME_MAX,
13
+ backfill,
14
+ endShare,
15
+ fieldValue,
16
+ findRoom,
17
+ isMirror,
18
+ offerOf,
19
+ refreshShared,
20
+ refusal,
21
+ sendRoom,
22
+ shareOf,
23
+ tell,
24
+ } = require(`${__hooks}/federation/rooms.js`);
25
+
26
+ // ---------------------------------------------------------------- events from the peer
27
+
28
+ /**
29
+ * A `share` event: an offer from a home (§33.5, step 2), or the peer's answer to ours.
30
+ * @param {core.App} app
31
+ * @param {core.Record} sender
32
+ * @param {any} ev
33
+ */
34
+ function applyShare(app, sender, ev) {
35
+ const s = splitGid(ev.room);
36
+ if (!s) throw refusal(400, "No room.");
37
+ if (s.host === myHost()) {
38
+ // Our offer, taken.
39
+ const room = findRoom(app, s.id);
40
+ const share = room ? shareOf(app, room.id, sender.id) : null;
41
+ if (!room || !share) throw refusal(404, "That room isn't offered to you.");
42
+ if (!ev.accepted || share.getString("state") !== "offered") return;
43
+ share.set("state", "active");
44
+ share.set("accepted", true);
45
+ app.save(share);
46
+ if (!refreshShared(app, room)) sendRoom(app, room, sender.id);
47
+ tell(app, room, `This room is now shared with ${peerHost(sender)}.`);
48
+ backfill(app, room, sender);
49
+ return;
50
+ }
51
+ if (s.host !== peerHost(sender)) throw refusal(403, "Only a room's home offers it.");
52
+ const g = /** @type {string} */ (ev.room);
53
+ let share = offerOf(app, sender.id, g);
54
+ if (share?.getString("state") === "active") return;
55
+ if (!share) {
56
+ share = new Record(app.findCollectionByNameOrId("fed_shares"));
57
+ share.set("peer", sender.id);
58
+ share.set("remote_id", g);
59
+ share.set("state", "offered");
60
+ share.set("accepted", false);
61
+ }
62
+ share.set("name", tidy(String(ev.name || "")).slice(0, 255));
63
+ share.set("kind", ev.kind === "dm" ? "dm" : "public");
64
+ share.set("visibility", ["public", "private", "open"].includes(ev.visibility) ? ev.visibility : "public");
65
+ app.save(share);
66
+ }
67
+
68
+ /**
69
+ * An `unshare` event: the peer ended a share, or declined or withdrew an offer.
70
+ * @param {core.App} app
71
+ * @param {core.Record} sender
72
+ * @param {any} ev
73
+ */
74
+ function applyUnshare(app, sender, ev) {
75
+ const s = splitGid(ev.room);
76
+ if (!s) return;
77
+ /** @type {core.Record | null} */
78
+ let share = null;
79
+ if (s.host === myHost()) {
80
+ share = shareOf(app, s.id, sender.id);
81
+ } else if (s.host === peerHost(sender)) {
82
+ share = offerOf(app, sender.id, /** @type {string} */ (ev.room));
83
+ }
84
+ if (!share) return;
85
+ if (share.getString("state") === "offered") {
86
+ if (share.getString("remote_id"))
87
+ app.delete(share); // withdrawn
88
+ else {
89
+ share.set("state", "ended"); // declined
90
+ share.set("last_error", "Declined.");
91
+ app.save(share);
92
+ }
93
+ return;
94
+ }
95
+ endShare(app, share, false);
96
+ }
97
+
98
+ /**
99
+ * A mirror's name: the home's plus the label ("general (A)"), numbered when that is taken, within rooms.name's 48.
100
+ * @param {core.App} app
101
+ * @param {string} name
102
+ * @param {string} label
103
+ * @param {string} selfId
104
+ */
105
+ function mirrorName(app, name, label, selfId) {
106
+ for (let n = 1; n < 1000; n++) {
107
+ const tail = `${n > 1 ? ` ${n}` : ""} (${label})`;
108
+ const base =
109
+ [...stripHashes(tidy(name))]
110
+ .slice(0, ROOM_NAME_MAX - tail.length)
111
+ .join("")
112
+ .trim() || "room";
113
+ const candidate = `${base}${tail}`;
114
+ try {
115
+ app.findFirstRecordByFilter("rooms", "name_key = {:k} && id != {:id}", { k: nameKey(candidate), id: selfId });
116
+ } catch {
117
+ return candidate;
118
+ }
119
+ }
120
+ throw new Error("no free room name");
121
+ }
122
+
123
+ /**
124
+ * A `room` event from a home: make the mirror (once its share is accepted, or a DM is opened) or bring it up to date.
125
+ * @param {core.App} app
126
+ * @param {core.Record} sender
127
+ * @param {any} ev
128
+ */
129
+ function applyRoom(app, sender, ev) {
130
+ const g = String(ev.room || "");
131
+ if (splitGid(g)?.host !== peerHost(sender)) throw refusal(403, "Only a room's home sends it.");
132
+ const dm = ev.kind === "dm";
133
+ let share = offerOf(app, sender.id, g);
134
+ if (!share) {
135
+ if (!dm) return; // not offered, or ended here
136
+ if (!sender.getBool("dms")) throw refusal(403, "Direct messages with your people are off here.");
137
+ share = new Record(app.findCollectionByNameOrId("fed_shares"));
138
+ share.set("peer", sender.id);
139
+ share.set("remote_id", g);
140
+ share.set("state", "offered");
141
+ share.set("accepted", true);
142
+ share.set("kind", "dm");
143
+ share.set("visibility", "private");
144
+ }
145
+ if (!share.getBool("accepted")) return; // its admin hasn't taken it yet
146
+ const people = ev.people && typeof ev.people === "object" ? ev.people : {};
147
+ const map = (/** @type {unknown} */ list) =>
148
+ (Array.isArray(list) ? list : [])
149
+ .slice(0, MAX_MEMBERS)
150
+ .map((x) => userOf(app, sender, x, people))
151
+ .filter(Boolean);
152
+ // Its creator is one of the home's own people: one of ours would get a creator's rights over the copy.
153
+ const creator = userOf(app, sender, ev.created_by, people, true);
154
+ if (!creator) throw refusal(400, "The room's creator is unknown.");
155
+ const members = map(ev.members);
156
+ const writers = map(ev.writers);
157
+ const hosts = (Array.isArray(ev.shared_with) ? ev.shared_with : []).map(String).filter((/** @type {string} */ h) => h && h !== myHost());
158
+ const shared = { home: peerHost(sender), with: [...new Set([peerHost(sender), ...hosts])] };
159
+
160
+ let room = findRoom(app, share.getString("room"));
161
+ const name = tidy(String(ev.name || "")).slice(0, 255);
162
+ if (!room) {
163
+ room = new Record(app.findCollectionByNameOrId("rooms"));
164
+ room.set("id", newId());
165
+ room.set("kind", dm ? "dm" : "public");
166
+ room.set("created_by", creator);
167
+ room.set("peer", sender.id);
168
+ room.set("remote_id", g);
169
+ if (dm) {
170
+ const pair = [...members].sort();
171
+ // One of the home's people and one of ours: a home doesn't open DMs between two people here.
172
+ const own = (/** @type {unknown} */ g) => splitGid(g)?.host === peerHost(sender);
173
+ const gids = Array.isArray(ev.members) ? ev.members : [];
174
+ const ours = (/** @type {unknown} */ g) => splitGid(g)?.host === myHost();
175
+ if (pair.length !== 2 || gids.length !== 2 || !gids.some(own) || !gids.some(ours)) {
176
+ throw refusal(400, "A DM is between one of your people and one of ours.");
177
+ }
178
+ room.set("dm_key", pair.join(":"));
179
+ try {
180
+ app.findFirstRecordByFilter("rooms", "dm_key = {:k}", { k: pair.join(":") });
181
+ throw refusal(409, "These two already have a DM here.");
182
+ } catch (err) {
183
+ if (/** @type {any} */ (err)?.status === 409) throw err;
184
+ }
185
+ } else {
186
+ room.set("name", mirrorName(app, name, sender.getString("label"), room.id));
187
+ }
188
+ } else if (!dm && name && name !== share.getString("name")) {
189
+ room.set("name", mirrorName(app, name, sender.getString("label"), room.id));
190
+ }
191
+ share.set("name", name);
192
+ if (!dm) {
193
+ room.set("visibility", ["public", "private", "open"].includes(ev.visibility) ? ev.visibility : "public");
194
+ room.set("posting", ev.posting === "selected" ? "selected" : "everyone");
195
+ room.set("anonymous", ev.anonymous === true); // DESIGN.md §35; a home from before it sends none
196
+ room.set("archived", !!ev.archived);
197
+ room.set("writers", writers);
198
+ }
199
+ // A DM's two members are set once, when it is made: a home naming others later would let them read it (QA BUG-172).
200
+ if (!dm || room.isNew()) room.set("members", members);
201
+ const down = jsonOf(room, "shared", {}).down;
202
+ room.set("shared", down ? { ...shared, down: true } : shared);
203
+ app.save(room);
204
+ const wasActive = share.getString("state") === "active";
205
+ share.set("room", room.id);
206
+ share.set("state", "active");
207
+ share.set("last_error", ev.refused ? String(ev.refused).slice(0, 1000) : "");
208
+ app.save(share);
209
+ if (!wasActive && !dm) tell(app, room, `This room is shared from ${peerHost(sender)}.`);
210
+ }
211
+
212
+ // ---------------------------------------------------------------- a mirror's superuser and its members
213
+
214
+ /**
215
+ * rooms update request on a mirror (§33.5): its state is the home's. Its superusers may rename it here, and in a
216
+ * private room add or remove their own people, which goes to the home as a `members` request. Returns that request,
217
+ * to send once saved (null when there is none).
218
+ * @param {core.RecordRequestEvent} e
219
+ * @returns {{ add: string[], remove: string[] } | null}
220
+ */
221
+ function checkMirrorEdit(e) {
222
+ const rec = e.record;
223
+ if (!rec || !isMirror(rec)) return null;
224
+ const orig = rec.original();
225
+ const home = peerById(e.app, orig.getString("peer"));
226
+ const where = home ? peerHost(home) : "its home";
227
+ if (!e.hasSuperuserAuth()) throw new ForbiddenError(`This room is shared from ${where}; it is changed there.`);
228
+ for (const f of [
229
+ "kind",
230
+ "visibility",
231
+ "posting",
232
+ "anonymous",
233
+ "writers",
234
+ "archived",
235
+ "created_by",
236
+ "dm_key",
237
+ "peer",
238
+ "remote_id",
239
+ "shared",
240
+ ]) {
241
+ if (fieldValue(rec, f) !== fieldValue(orig, f)) throw fieldError(f, `This room is shared from ${where}; this is changed there.`);
242
+ }
243
+ const was = orig.getStringSlice("members");
244
+ const now = rec.getStringSlice("members");
245
+ if (was.join(",") === now.join(",")) return null;
246
+ if (orig.getString("kind") !== "public" || orig.getString("visibility") !== "private") {
247
+ throw fieldError("members", "Only a private room's members are listed.");
248
+ }
249
+ const add = now.filter((id) => !was.includes(id));
250
+ const remove = was.filter((id) => !now.includes(id));
251
+ for (const id of [...add, ...remove]) {
252
+ if (standInRow(e.app, id) || id === orig.getString("created_by")) {
253
+ throw fieldError("members", `People from other instances are added and removed on ${where}.`);
254
+ }
255
+ }
256
+ return { add, remove };
257
+ }
258
+
259
+ /**
260
+ * rooms update request on a mirror (saved): send its superuser's member change to the home.
261
+ * @param {core.App} app
262
+ * @param {core.Record} room
263
+ * @param {{ add: string[], remove: string[] }} change
264
+ */
265
+ function sendMembers(app, room, change) {
266
+ const peer = peerById(app, room.getString("peer"));
267
+ if (!peer) return;
268
+ enqueue(app, peer.id, {
269
+ type: "members",
270
+ room: room.getString("remote_id"),
271
+ add: change.add.map((id) => gid(id)),
272
+ remove: change.remove.map((id) => gid(id)),
273
+ people: peopleFor(app, peer, change.add),
274
+ });
275
+ }
276
+
277
+ module.exports = { applyShare, applyUnshare, applyRoom, checkMirrorEdit, sendMembers };