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,413 @@
1
+ /// <reference path="../../types/pocketbase.d.ts" />
2
+ // The federation worker (DESIGN.md §33.8), as the Telegram bridge's (§26.7): a cron job starts it every minute and it
3
+ // runs for most of that minute, once a second. Per peer, in order: the queued events go in batches of up to 50, then
4
+ // files and avatars are fetched. A row being worked on is claimed (locked_until), so it is handled once. What failed
5
+ // for now (no answer, 5xx, 429) is tried again after 2, 4, 8… seconds, at most 10 minutes; rows are kept 3 days. A 4xx
6
+ // is dropped at once. fed_peers.last_ok and last_error show how a peer is doing. POST /api/fed/tick runs a pass now.
7
+
8
+ const { isActive, jsonOf, peerHost } = require(`${__hooks}/federation/config.js`);
9
+ const { call, errorOf, jsonBody } = require(`${__hooks}/federation/net.js`);
10
+ const { applyMessage, MAX_FILES } = require(`${__hooks}/federation/messages.js`);
11
+ const { setDown } = require(`${__hooks}/federation/rooms.js`);
12
+ const { isLost } = require(`${__hooks}/lib/worker.js`);
13
+
14
+ const LOCK = "federation.worker";
15
+ const STALE_MS = 90_000;
16
+ const CLAIM_MS = 10 * 60_000;
17
+ const BATCH = 50;
18
+ /** Fetches per peer in one pass: files can be big. */
19
+ const WORK_BATCH = 5;
20
+ const KEEP_MS = 3 * 24 * 60 * 60 * 1000;
21
+ const MAX_WAIT_S = 600;
22
+ /** A peer is shown as unreachable after this many failed tries in a row. */
23
+ const DOWN_AFTER = 3;
24
+ const MAX_FILE = 20 * 1024 * 1024;
25
+ const MAX_AVATAR = 5 * 1024 * 1024;
26
+
27
+ /**
28
+ * Claim queue row `id` unless another pass has it, or it isn't due yet.
29
+ * @param {core.App} app
30
+ * @param {string} id
31
+ */
32
+ function claim(app, id) {
33
+ let mine = false;
34
+ app.runInTransaction((tx) => {
35
+ let row;
36
+ try {
37
+ row = tx.findRecordById("fed_queue", id);
38
+ } catch {
39
+ return;
40
+ }
41
+ const now = Date.now();
42
+ const until = row.getDateTime("locked_until");
43
+ const due = row.getDateTime("next_at");
44
+ if (!until.isZero() && until.time().unixMilli() > now) return;
45
+ if (!due.isZero() && due.time().unixMilli() > now) return;
46
+ row.set("locked_until", new DateTime(new Date(now + CLAIM_MS).toISOString()));
47
+ tx.save(row);
48
+ mine = true;
49
+ });
50
+ return mine;
51
+ }
52
+
53
+ /**
54
+ * Try a row again later.
55
+ * @param {core.App} app
56
+ * @param {core.Record} row
57
+ * @param {string} error
58
+ * @returns {number} its tries so far
59
+ */
60
+ function retry(app, row, error) {
61
+ const tries = row.getInt("tries") + 1;
62
+ const wait = Math.min(2 ** tries, MAX_WAIT_S) * 1000;
63
+ row.set("tries", tries);
64
+ row.set("next_at", new DateTime(new Date(Date.now() + wait).toISOString()));
65
+ row.set("locked_until", "");
66
+ row.set("error", error.slice(0, 1000));
67
+ app.save(row);
68
+ return tries;
69
+ }
70
+
71
+ /**
72
+ * Note how the peer is doing (§33.8): last_ok, last_error, and its rooms shown as unreachable or not (§33.7).
73
+ * @param {core.App} app
74
+ * @param {core.Record} peer
75
+ * @param {string} error "" when it answered
76
+ * @param {number} [tries] of the item that failed
77
+ */
78
+ function note(app, peer, error, tries = 0) {
79
+ const key = `fed.down.${peer.id}`;
80
+ if (!error) {
81
+ const last = peer.getDateTime("last_ok");
82
+ if (peer.getString("last_error") || last.isZero() || Date.now() - last.time().unixMilli() > 60_000) {
83
+ peer.set("last_ok", new DateTime());
84
+ peer.set("last_error", "");
85
+ app.save(peer);
86
+ }
87
+ if (app.store().get(key)) {
88
+ app.store().remove(key);
89
+ setDown(app, peer.id, false);
90
+ }
91
+ return;
92
+ }
93
+ peer.set("last_error", error.slice(0, 1000));
94
+ app.save(peer);
95
+ if (tries >= DOWN_AFTER && !app.store().get(key)) {
96
+ app.store().set(key, true);
97
+ setDown(app, peer.id, true);
98
+ }
99
+ }
100
+
101
+ /**
102
+ * Send the peer's queued events, oldest first, up to BATCH at once (stopping at one that isn't due).
103
+ * @param {core.App} app
104
+ * @param {core.Record} peer
105
+ */
106
+ function sendEvents(app, peer) {
107
+ const rows = app.findRecordsByFilter("fed_queue", "peer = {:p} && op = 'event'", "seq", BATCH, 0, { p: peer.id });
108
+ /** @type {core.Record[]} */
109
+ const batch = [];
110
+ for (const row of rows) {
111
+ if (!row || !claim(app, row.id)) break;
112
+ batch.push(app.findRecordById("fed_queue", row.id));
113
+ }
114
+ if (!batch.length) return;
115
+ const events = batch.map((r) => jsonOf(r, "payload", {}));
116
+ /** @type {ReturnType<typeof call> | null} */
117
+ let answer = null;
118
+ let error = "";
119
+ try {
120
+ answer = call(peer, "POST", "/api/fed/inbox", { events });
121
+ } catch (err) {
122
+ error = String(err);
123
+ }
124
+ if (answer && answer.status === 200) {
125
+ const results = jsonBody(answer)?.results;
126
+ /** @type {Record<string, any>} */
127
+ const byId = {};
128
+ for (const r of Array.isArray(results) ? results : []) if (r && typeof r.id === "string") byId[r.id] = r;
129
+ let refused = "";
130
+ for (const row of batch) {
131
+ const r = byId[row.id];
132
+ const status = r ? Number(r.status) : 503;
133
+ if (status >= 500 || status === 429) {
134
+ retry(app, row, `${status} ${r?.error || "no result"}`);
135
+ continue;
136
+ }
137
+ if (status >= 400) {
138
+ refused = `${jsonOf(row, "payload", {}).type}: ${status} ${r?.error || ""}`;
139
+ app.logger().warn("federation: event refused by peer", "peer", peerHost(peer), "event", row.id, "result", refused);
140
+ }
141
+ app.delete(row);
142
+ }
143
+ note(app, peer, refused);
144
+ return;
145
+ }
146
+ if (answer && answer.status >= 400 && answer.status < 500 && answer.status !== 429) {
147
+ error = errorOf(answer);
148
+ app.logger().error("federation: events dropped", "peer", peerHost(peer), "count", batch.length, "error", error);
149
+ for (const row of batch) app.delete(row);
150
+ note(app, peer, error);
151
+ return;
152
+ }
153
+ if (answer) error = errorOf(answer);
154
+ let tries = 0;
155
+ for (const row of batch) tries = Math.max(tries, retry(app, row, error));
156
+ note(app, peer, error, tries);
157
+ }
158
+
159
+ /**
160
+ * A temp file for a download.
161
+ */
162
+ const tempPath = () => `${$os.tempDir()}/chirkle-fed-${$security.randomString(16)}`;
163
+
164
+ /**
165
+ * A name to store a fetched file under (PocketBase's style: safe characters, a random suffix).
166
+ * @param {string} original
167
+ */
168
+ function storedName(original) {
169
+ const dot = original.lastIndexOf(".");
170
+ const ext =
171
+ dot > 0
172
+ ? original
173
+ .slice(dot)
174
+ .toLowerCase()
175
+ .replace(/[^a-z0-9.]/g, "")
176
+ .slice(0, 10)
177
+ : "";
178
+ const stem =
179
+ (dot > 0 ? original.slice(0, dot) : original)
180
+ .toLowerCase()
181
+ .replace(/[^a-z0-9]+/g, "_")
182
+ .replace(/^_+|_+$/g, "")
183
+ .slice(0, 80) || "file";
184
+ return `${stem}_${$security.randomStringWithAlphabet(10, "abcdefghijklmnopqrstuvwxyz0123456789")}${ext}`;
185
+ }
186
+
187
+ /** Thrown for a fetch that may work later. */
188
+ class Later extends Error {}
189
+
190
+ /**
191
+ * Fetch a peer file to a temp file: its path, "" when the peer says it is gone (or too big). Throws Later otherwise.
192
+ * @param {core.Record} peer
193
+ * @param {string} path
194
+ * @param {number} max
195
+ */
196
+ function download(peer, path, max) {
197
+ const out = tempPath();
198
+ let answer;
199
+ try {
200
+ answer = call(peer, "GET", path, undefined, { out, max, seconds: 120 });
201
+ } catch (err) {
202
+ throw new Later(String(err));
203
+ }
204
+ const there = (() => {
205
+ try {
206
+ return $os.stat(out).size() > 0;
207
+ } catch {
208
+ return false;
209
+ }
210
+ })();
211
+ if (answer.status === 200 && there) return out;
212
+ try {
213
+ $os.remove(out);
214
+ } catch {
215
+ // never written
216
+ }
217
+ if (answer.status >= 500 || answer.status === 429) throw new Later(errorOf(answer));
218
+ return "";
219
+ }
220
+
221
+ /**
222
+ * A message that came with files (§33.5): fetch them from the peer that sent it, then save it.
223
+ * @param {core.App} app
224
+ * @param {core.Record} peer
225
+ * @param {any} payload
226
+ */
227
+ function fetchMessage(app, peer, payload) {
228
+ const ev = payload.event || {};
229
+ const listed = (Array.isArray(ev.message?.files) ? ev.message.files : []).slice(0, MAX_FILES);
230
+ /** @type {string[]} */
231
+ const temps = [];
232
+ try {
233
+ /** @type {any[]} */
234
+ const uploads = [];
235
+ for (const f of listed) {
236
+ const path = typeof f?.path === "string" && f.path.startsWith("/api/fed/files/") ? f.path : "";
237
+ if (!path) continue;
238
+ const tmp = download(peer, path, MAX_FILE);
239
+ if (!tmp) continue;
240
+ temps.push(tmp);
241
+ const up = $filesystem.fileFromPath(tmp);
242
+ const name = String(f.name || "file").slice(0, 200);
243
+ up.name = storedName(name);
244
+ up.originalName = name;
245
+ uploads.push(up);
246
+ }
247
+ app.runInTransaction((tx) => {
248
+ applyMessage(tx, peer, ev, uploads);
249
+ });
250
+ } finally {
251
+ for (const t of temps) {
252
+ try {
253
+ $os.remove(t);
254
+ } catch {
255
+ // gone
256
+ }
257
+ }
258
+ }
259
+ }
260
+
261
+ /**
262
+ * A stand-in's picture changed (§33.4): fetch it, unless a newer one was asked for meanwhile.
263
+ * @param {core.App} app
264
+ * @param {core.Record} peer
265
+ * @param {any} payload
266
+ */
267
+ function fetchAvatar(app, peer, payload) {
268
+ let row;
269
+ try {
270
+ row = app.findFirstRecordByFilter("fed_people", "user = {:u} && kind = 'standin'", { u: String(payload.user || "") });
271
+ } catch {
272
+ return;
273
+ }
274
+ if (row.getString("avatar") !== payload.key) return;
275
+ const path = String(payload.path || "");
276
+ if (!path.startsWith("/api/fed/avatars/")) return;
277
+ const tmp = download(peer, path, MAX_AVATAR);
278
+ if (!tmp) return;
279
+ try {
280
+ const user = app.findRecordById("users", row.getString("user"));
281
+ const up = $filesystem.fileFromPath(tmp);
282
+ up.name = storedName(String(payload.key));
283
+ up.originalName = String(payload.key);
284
+ user.set("avatar", up);
285
+ app.save(user);
286
+ } finally {
287
+ try {
288
+ $os.remove(tmp);
289
+ } catch {
290
+ // gone
291
+ }
292
+ }
293
+ }
294
+
295
+ /**
296
+ * Fetch what came from the peer and waits for its files, or avatars, oldest first.
297
+ * @param {core.App} app
298
+ * @param {core.Record} peer
299
+ * @param {() => void} renew
300
+ */
301
+ function doWork(app, peer, renew) {
302
+ const rows = app.findRecordsByFilter("fed_queue", "peer = {:p} && op != 'event'", "seq", WORK_BATCH, 0, { p: peer.id });
303
+ for (const r of rows) {
304
+ if (!r || !claim(app, r.id)) break;
305
+ const row = app.findRecordById("fed_queue", r.id);
306
+ const payload = jsonOf(row, "payload", {});
307
+ try {
308
+ if (row.getString("op") === "fetch") fetchMessage(app, peer, payload);
309
+ else fetchAvatar(app, peer, payload);
310
+ app.delete(row);
311
+ } catch (err) {
312
+ if (err instanceof Later) {
313
+ const tries = retry(app, row, String(err.message));
314
+ note(app, peer, String(err.message), tries);
315
+ break; // in order: the rest wait for it
316
+ }
317
+ app.logger().warn(`federation: ${row.getString("op")} dropped`, "peer", peerHost(peer), "error", String(err));
318
+ app.delete(row);
319
+ } finally {
320
+ renew();
321
+ }
322
+ }
323
+ }
324
+
325
+ /**
326
+ * Drop what is older than 3 days: queue rows (logged) and the ids of events taken.
327
+ * @param {core.App} app
328
+ */
329
+ function prune(app) {
330
+ const before = new Date(Date.now() - KEEP_MS).toISOString().replace("T", " ");
331
+ for (const row of app.findRecordsByFilter("fed_queue", "created < {:t}", "created", 100, 0, { t: before })) {
332
+ if (!row) continue;
333
+ app
334
+ .logger()
335
+ .error("federation: dropped after 3 days", "op", row.getString("op"), "peer", row.getString("peer"), "error", row.getString("error"));
336
+ app.delete(row);
337
+ }
338
+ app.db().newQuery("DELETE FROM fed_seen WHERE created < {:t}").bind({ t: before }).execute();
339
+ }
340
+
341
+ /**
342
+ * One pass over every active peer. `renew` (the worker's lock) after each item.
343
+ * @param {core.App} app
344
+ * @param {() => void} renew
345
+ */
346
+ function pass(app, renew) {
347
+ prune(app);
348
+ for (const peer of app.findRecordsByFilter("fed_peers", "status = 'active'", "created", 0, 0)) {
349
+ if (!peer || !isActive(peer)) continue;
350
+ try {
351
+ sendEvents(app, peer);
352
+ renew();
353
+ doWork(app, peer, renew);
354
+ } catch (err) {
355
+ if (isLost(err)) throw err;
356
+ app.logger().error("federation: worker", "peer", peerHost(peer), "error", String(err));
357
+ }
358
+ }
359
+ }
360
+
361
+ /**
362
+ * The cron job (lib/worker.js): passes, once a second, until the minute is nearly over; pending requests every 30 s.
363
+ * @param {core.App} app
364
+ */
365
+ function run(app) {
366
+ let pendingAt = 0;
367
+ require(`${__hooks}/lib/worker.js`).run(app, {
368
+ ...worker(app),
369
+ pass: (/** @type {() => void} */ renew) => {
370
+ if (Date.now() - pendingAt >= PENDING_MS) {
371
+ pending(app);
372
+ pendingAt = Date.now();
373
+ }
374
+ pass(app, renew);
375
+ },
376
+ });
377
+ }
378
+
379
+ /** @param {core.App} app */
380
+ const worker = (app) => ({
381
+ name: LOCK,
382
+ label: "federation",
383
+ staleMs: STALE_MS,
384
+ pass: (/** @type {() => void} */ renew) => pass(app, renew),
385
+ });
386
+
387
+ /** How often a run looks at pending pairing requests. */
388
+ const PENDING_MS = 30_000;
389
+
390
+ /**
391
+ * Pending pairing requests (§33.3), every 30 s of a run and on every tick: sent again until delivered, ended once
392
+ * expired.
393
+ * @param {core.App} app
394
+ */
395
+ function pending(app) {
396
+ try {
397
+ require(`${__hooks}/federation/peers.js`).pendingPass(app);
398
+ } catch (err) {
399
+ app.logger().error("federation: pending requests", "error", String(err));
400
+ }
401
+ }
402
+
403
+ /**
404
+ * POST /api/fed/tick (superusers): one pass now, unless a run is going (it does the work within a second).
405
+ * @param {core.RequestEvent} e
406
+ */
407
+ function tick(e) {
408
+ pending(e.app);
409
+ const ran = require(`${__hooks}/lib/worker.js`).once(e.app, worker(e.app));
410
+ return e.json(ran ? 200 : 202, { ran });
411
+ }
412
+
413
+ module.exports = { run, tick };
@@ -0,0 +1,141 @@
1
+ /// <reference path="../types/pocketbase.d.ts" />
2
+ // Linked instances (DESIGN.md §33): rooms and DMs shared with other servers running this app, paired by their admins.
3
+ // Self-contained like the Telegram bridge: this file, federation/ and the fed_* collections (pb_migrations/
4
+ // 1760000032_federation.js); the core only has the fields that migration adds.
5
+ //
6
+ // On while the site record's `federation` is ticked, with this server's address taken from the Application URL
7
+ // (federation/config.js). Off, the /api/fed/ routes answer 404 and the worker sends nothing. The record hooks are
8
+ // always registered but skip at once while there is no fed_peers row (`inUse`), so an instance that never linked pays
9
+ // one cached lookup.
10
+ //
11
+ // What it does on the core collections' saves (rooms, users, messages) main.pb.js calls, through lib/features.js, in the
12
+ // order stated there: it reads a record as it was, lets the save go on, then queues what a peer needs to hear, in the
13
+ // save's transaction. Here: its routes, its worker, and the hooks of its own collections.
14
+
15
+ routerAdd("POST", "/api/fed/request", (e) => {
16
+ require(`${__hooks}/federation/config.js`).requireOn(e.app);
17
+ return require(`${__hooks}/federation/peers.js`).request(e);
18
+ });
19
+ routerAdd("POST", "/api/fed/verify", (e) => {
20
+ require(`${__hooks}/federation/config.js`).requireOn(e.app);
21
+ return require(`${__hooks}/federation/peers.js`).verifyRequest(e);
22
+ });
23
+ routerAdd("POST", "/api/fed/cancel", (e) => {
24
+ require(`${__hooks}/federation/config.js`).requireOn(e.app);
25
+ return require(`${__hooks}/federation/peers.js`).cancel(e);
26
+ });
27
+ routerAdd("POST", "/api/fed/pair", (e) => {
28
+ require(`${__hooks}/federation/config.js`).requireOn(e.app);
29
+ return require(`${__hooks}/federation/peers.js`).pair(e);
30
+ });
31
+ routerAdd("POST", "/api/fed/inbox", (e) => {
32
+ require(`${__hooks}/federation/config.js`).requireOn(e.app);
33
+ return require(`${__hooks}/federation/inbox.js`).inbox(e);
34
+ });
35
+ routerAdd("GET", "/api/fed/files/{message}/{file}", (e) => {
36
+ require(`${__hooks}/federation/config.js`).requireOn(e.app);
37
+ return require(`${__hooks}/federation/inbox.js`).file(e);
38
+ });
39
+ routerAdd("GET", "/api/fed/avatars/{user}", (e) => {
40
+ require(`${__hooks}/federation/config.js`).requireOn(e.app);
41
+ return require(`${__hooks}/federation/inbox.js`).avatar(e);
42
+ });
43
+ routerAdd("GET", "/api/fed/users", (e) => {
44
+ require(`${__hooks}/federation/config.js`).requireOn(e.app);
45
+ return require(`${__hooks}/federation/inbox.js`).lookup(e);
46
+ });
47
+ routerAdd(
48
+ "POST",
49
+ "/api/fed/tick",
50
+ (e) => {
51
+ require(`${__hooks}/federation/config.js`).requireOn(e.app);
52
+ return require(`${__hooks}/federation/worker.js`).tick(e);
53
+ },
54
+ $apis.requireSuperuserAuth(),
55
+ );
56
+ routerAdd(
57
+ "POST",
58
+ "/api/chat/remote-users",
59
+ (e) => {
60
+ require(`${__hooks}/federation/config.js`).requireOn(e.app);
61
+ return require(`${__hooks}/federation/inbox.js`).remoteUser(e);
62
+ },
63
+ $apis.requireAuth("users"),
64
+ );
65
+
66
+ cronAdd("federation", "* * * * *", () => {
67
+ if (require(`${__hooks}/federation/config.js`).enabled($app)) require(`${__hooks}/federation/worker.js`).run($app);
68
+ });
69
+
70
+ // The switch (§33.2): on only with an Application URL that can be linked with; that URL's host is in every global id
71
+ // the peers keep, so it stays while any instance is listed.
72
+ onRecordUpdateRequest((e) => {
73
+ const rec = e.record;
74
+ if (rec?.getBool("federation") && !rec.original().getBool("federation")) {
75
+ const problem = require(`${__hooks}/federation/config.js`).originProblem();
76
+ if (problem) throw require(`${__hooks}/lib/records.js`).fieldError("federation", problem);
77
+ }
78
+ e.next();
79
+ }, "site");
80
+
81
+ onSettingsUpdateRequest((e) => {
82
+ const { hostOf, originProblem } = require(`${__hooks}/federation/config.js`);
83
+ const old = e.oldSettings?.meta.appURL || "";
84
+ const was = hostOf(old);
85
+ const now = hostOf(e.newSettings?.meta.appURL || "");
86
+ // An old URL that could never be linked with (PocketBase's default, say) is no one's global ids: set it freely.
87
+ if (was !== now && !originProblem(old) && e.app.findRecordsByFilter("fed_peers", "", "", 1, 0).length) {
88
+ const msg = `Linked instances know this server as ${was}: delete them in Collections → fed_peers before changing its address.`;
89
+ throw new BadRequestError(msg, { meta: { appURL: new ValidationError("validation_fed_paired", msg) } });
90
+ }
91
+ e.next();
92
+ });
93
+
94
+ // Whether any fed_peers row exists, for the record hooks' `inUse`: asked again after every create and delete.
95
+ onRecordAfterCreateSuccess((e) => {
96
+ require(`${__hooks}/federation/config.js`).forgetInUse(e.app);
97
+ e.next();
98
+ }, "fed_peers");
99
+
100
+ onRecordAfterDeleteSuccess((e) => {
101
+ require(`${__hooks}/federation/config.js`).forgetInUse(e.app);
102
+ e.next();
103
+ }, "fed_peers");
104
+
105
+ // Pairing (§33.3): superusers, in the admin UI.
106
+ onRecordCreateRequest((e) => {
107
+ require(`${__hooks}/federation/peers.js`).beforePeerCreate(e);
108
+ e.next();
109
+ }, "fed_peers");
110
+
111
+ onRecordUpdateRequest((e) => {
112
+ const peers = require(`${__hooks}/federation/peers.js`);
113
+ const changed = peers.beforePeerEdit(e);
114
+ e.next();
115
+ if (e.record) peers.afterPeerEdit(e.app, e.record, changed);
116
+ }, "fed_peers");
117
+
118
+ onRecordDeleteRequest((e) => {
119
+ if (e.record) require(`${__hooks}/federation/peers.js`).beforePeerDelete(e.app, e.record);
120
+ e.next();
121
+ }, "fed_peers");
122
+
123
+ // Sharing rooms (§33.5): superusers on both sides, in the admin UI.
124
+ onRecordCreateRequest((e) => {
125
+ const rooms = require(`${__hooks}/federation/rooms.js`);
126
+ rooms.beforeOffer(e);
127
+ e.next();
128
+ if (e.record) rooms.afterOffer(e.app, e.record);
129
+ }, "fed_shares");
130
+
131
+ onRecordUpdateRequest((e) => {
132
+ const rooms = require(`${__hooks}/federation/rooms.js`);
133
+ const what = rooms.beforeShareEdit(e);
134
+ e.next();
135
+ if (e.record) rooms.afterShareEdit(e.app, e.record, what);
136
+ }, "fed_shares");
137
+
138
+ onRecordDeleteRequest((e) => {
139
+ if (e.record) require(`${__hooks}/federation/rooms.js`).beforeShareDelete(e.app, e.record);
140
+ e.next();
141
+ }, "fed_shares");
@@ -0,0 +1,102 @@
1
+ /// <reference path="../../types/pocketbase.d.ts" />
2
+ // Room access (DESIGN.md §23): who can see a room, the way the rooms view rule says it (CAN_SEE in pb_migrations/
3
+ // 1760000014_room_access.js). For hooks and routes that check a room themselves, for SQL that lists rooms, and for
4
+ // telling realtime clients about a room they can no longer see. The rule, canSee and SEES_SQL must agree:
5
+ // tests/integration/access.matrix.test.ts checks every way in against one table.
6
+
7
+ /** Most members a private room can have (rooms.members maxSelect). */
8
+ const MAX_MEMBERS = 100;
9
+
10
+ /**
11
+ * What decides who can see a room, copied out of the record (so a hook can keep it from before a save).
12
+ * @typedef {{ id: string, visibility: string, archived: boolean, createdBy: string, members: string[] }} Access
13
+ */
14
+
15
+ /**
16
+ * @param {core.Record} room
17
+ * @returns {Access}
18
+ */
19
+ function accessOf(room) {
20
+ return {
21
+ id: room.id,
22
+ visibility: room.getString("visibility"),
23
+ archived: room.getBool("archived"),
24
+ createdBy: room.getString("created_by"),
25
+ members: room.getStringSlice("members"),
26
+ };
27
+ }
28
+
29
+ /**
30
+ * Can `userId` ("" for a guest) see the room? Open Air rooms that aren't archived: anyone. Otherwise only signed in:
31
+ * any public room, or a private one (DMs too) they are a member or the creator of.
32
+ * @param {Access} a
33
+ * @param {string} userId
34
+ */
35
+ function canSee(a, userId) {
36
+ if (a.visibility === "open" && !a.archived) return true;
37
+ if (!userId) return false;
38
+ return a.visibility !== "private" || a.createdBy === userId || a.members.includes(userId);
39
+ }
40
+
41
+ /**
42
+ * Can `userId` post in the room (§23.6)? They must see it, signed in, and the room let everyone post or list them as a
43
+ * writer (its creator always is). The messages create rule says the same.
44
+ * @param {core.Record} room
45
+ * @param {string} userId
46
+ */
47
+ function canWrite(room, userId) {
48
+ if (!userId || !canSee(accessOf(room), userId)) return false;
49
+ if (room.getString("posting") !== "selected") return true;
50
+ return room.getString("created_by") === userId || room.getStringSlice("writers").includes(userId);
51
+ }
52
+
53
+ /**
54
+ * canSee for a signed-in user, as an SQL condition on `rooms r`, with the user's id bound as {:me}. (Open Air rooms are
55
+ * not private, so no guest case is needed: guests never run these queries.)
56
+ */
57
+ const SEES_SQL = "(r.visibility != 'private' OR r.created_by = {:me} OR EXISTS (SELECT 1 FROM json_each(r.members) WHERE value = {:me}))";
58
+
59
+ /**
60
+ * The room if `userId` can see it, else null (also for a room that doesn't exist).
61
+ * @param {core.App} app
62
+ * @param {string} roomId
63
+ * @param {string} userId
64
+ */
65
+ function visibleRoom(app, roomId, userId) {
66
+ let room;
67
+ try {
68
+ room = app.findRecordById("rooms", roomId);
69
+ } catch {
70
+ return null;
71
+ }
72
+ return canSee(accessOf(room), userId) ? room : null;
73
+ }
74
+
75
+ /**
76
+ * After a room changed (§23.4): every realtime client that could see it before but can't now gets a `delete` event
77
+ * for it on its rooms subscriptions. PocketBase only sends a change to those who can see the result, so otherwise
78
+ * they would never hear of it: a member taken out of a private room would keep it in their list, and a guest an Open
79
+ * Air room that was archived or made private. Only the id goes out.
80
+ * @param {core.App} app
81
+ * @param {Access} before
82
+ * @param {core.Record} room
83
+ */
84
+ function dropLostAccess(app, before, room) {
85
+ const after = accessOf(room);
86
+ // Most saves don't touch access (every DM message saves its room): then there is no one to tell (QA BUG-63).
87
+ if (JSON.stringify(before) === JSON.stringify(after)) return;
88
+ const data = JSON.stringify({ action: "delete", record: { id: room.id } });
89
+ const clients = app.subscriptionsBroker().clients();
90
+ for (const id of Object.keys(clients)) {
91
+ const client = clients[id];
92
+ if (!client || client.isDiscarded()) continue;
93
+ /** @type {core.Record | null | undefined} */
94
+ const auth = client.get("auth");
95
+ if (auth?.isSuperuser()) continue;
96
+ const userId = auth ? auth.id : "";
97
+ if (!canSee(before, userId) || canSee(after, userId)) continue;
98
+ for (const name of Object.keys(client.subscriptions("rooms"))) client.send(new SubscriptionMessage({ name, data }));
99
+ }
100
+ }
101
+
102
+ module.exports = { MAX_MEMBERS, SEES_SQL, accessOf, canSee, canWrite, visibleRoom, dropLostAccess };
@@ -0,0 +1,31 @@
1
+ /// <reference path="../../types/pocketbase.d.ts" />
2
+ // POST /api/chat/password (DESIGN.md §22.2): change your password. Checks the current one, signs out every other
3
+ // session, and answers like a login (a fresh token and record), so the tab that changed it stays logged in.
4
+
5
+ /**
6
+ * @param {string} field
7
+ * @param {string} message
8
+ * @param {string} [code]
9
+ */
10
+ function fieldError(field, message, code = "validation_invalid_value") {
11
+ return new BadRequestError("Failed to change the password.", { [field]: new ValidationError(code, message) });
12
+ }
13
+
14
+ /** @param {core.RequestEvent} e */
15
+ function changePassword(e) {
16
+ if (!e.auth) throw new UnauthorizedError("The request requires a logged-in user.");
17
+ const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body);
18
+ const oldPassword = typeof body.oldPassword === "string" ? body.oldPassword : "";
19
+ const password = typeof body.password === "string" ? body.password : "";
20
+ if (!oldPassword) throw fieldError("oldPassword", "Enter your current password.", "validation_required");
21
+ if (!password) throw fieldError("password", "Enter a new password.", "validation_required");
22
+ const user = e.app.findRecordById("users", e.auth.id);
23
+ if (!user.validatePassword(oldPassword)) throw fieldError("oldPassword", "That isn't your current password.");
24
+ if (password === oldPassword) throw fieldError("password", "That is your current password. Choose a new one.");
25
+ user.setPassword(password); // the field's own rules (length) are checked by save()
26
+ user.refreshTokenKey(); // every token issued so far stops working: other devices are signed out
27
+ e.app.save(user);
28
+ return $apis.recordAuthResponse(e, user, "password");
29
+ }
30
+
31
+ module.exports = { changePassword };