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,192 @@
1
+ /// <reference path="../../types/pocketbase.d.ts" />
2
+ // Telegram rich messages (Bot API 10.1: Message.rich_message) as a chat message (DESIGN.md §26.4). A rich message has
3
+ // no text or caption: its content is a tree of blocks (headings, paragraphs, lists, tables, quotes, media…) holding
4
+ // rich text. The room shows plain text (§5), so the blocks become lines of it, and the media in them become files.
5
+
6
+ /** How deep blocks nest before the rest is left out: Telegram's own are shallow. */
7
+ const MAX_DEPTH = 16;
8
+
9
+ /**
10
+ * Rich text as plain text: a string, an array of rich texts, or a formatted piece (bold, a link…) around one. A link
11
+ * whose text isn't its address keeps the address after it.
12
+ * @param {any} t
13
+ * @returns {string}
14
+ */
15
+ function plain(t, depth = 0) {
16
+ if (t == null || depth > MAX_DEPTH) return "";
17
+ if (typeof t === "string") return t;
18
+ if (Array.isArray(t)) return t.map((x) => plain(x, depth + 1)).join("");
19
+ switch (t.type) {
20
+ case "custom_emoji":
21
+ return t.alternative_text || "";
22
+ case "mathematical_expression":
23
+ return t.expression || "";
24
+ case "anchor":
25
+ return "";
26
+ case "button":
27
+ return buttonText(t.button);
28
+ case "url": {
29
+ const text = plain(t.text, depth + 1);
30
+ return !t.url || text.trim() === t.url ? text || t.url || "" : `${text} (${t.url})`;
31
+ }
32
+ default:
33
+ return plain(t.text, depth + 1);
34
+ }
35
+ }
36
+
37
+ /**
38
+ * A button that opens a link, as its text and the link; other buttons (callbacks…) only work in Telegram.
39
+ * @param {any} b RichMessageButton
40
+ */
41
+ function buttonText(b) {
42
+ if (!b?.url) return "";
43
+ const text = plain(b.text).trim();
44
+ return text && text !== b.url ? `[${text}: ${b.url}]` : `[${b.url}]`;
45
+ }
46
+
47
+ /** @param {string} prefix @param {string[]} lines */
48
+ const prefixed = (prefix, lines) => lines.map((l) => `${prefix}${l}`);
49
+
50
+ /**
51
+ * A caption (RichBlockCaption) and its credit, as lines.
52
+ * @param {any} c
53
+ */
54
+ function captionLines(c) {
55
+ if (!c) return [];
56
+ return [plain(c.text), c.credit ? `— ${plain(c.credit)}` : ""].filter((l) => l.trim()).flatMap((l) => l.split("\n"));
57
+ }
58
+
59
+ /**
60
+ * A rich message's blocks as lines of text; the files in them go to `add` (a Telegram file, its name).
61
+ * @param {any[]} blocks
62
+ * @param {number} n the Telegram message's id, for the names of files that have none
63
+ * @param {(f: any, name: string) => void} add
64
+ * @param {string[]} notes what can't be shown as text or a file
65
+ * @returns {string[]}
66
+ */
67
+ function blockLines(blocks, n, add, notes, depth = 0) {
68
+ if (!Array.isArray(blocks) || depth > MAX_DEPTH) return [];
69
+ /** @type {string[]} */
70
+ const out = [];
71
+ for (const b of blocks) {
72
+ const lines = blockOf(b, n, add, notes, depth);
73
+ // A heading opens a section: a blank line above it, when something came before.
74
+ if (b?.type === "heading" && out.length && out[out.length - 1] !== "") out.push("");
75
+ out.push(...lines);
76
+ }
77
+ return out;
78
+ }
79
+
80
+ /**
81
+ * @param {any} b RichBlock
82
+ * @param {number} n
83
+ * @param {(f: any, name: string) => void} add
84
+ * @param {string[]} notes
85
+ * @param {number} depth
86
+ * @returns {string[]}
87
+ */
88
+ function blockOf(b, n, add, notes, depth) {
89
+ if (!b) return [];
90
+ const text = (/** @type {any} */ t) => plain(t).split("\n");
91
+ const inner = (/** @type {any[]} */ blocks) => blockLines(blocks, n, add, notes, depth + 1);
92
+ /** A file of the message: its name, numbered when it has none (a message can hold several). */
93
+ const file = (/** @type {any} */ f, /** @type {string} */ kind, /** @type {string} */ ext) => {
94
+ if (f) add(f, f.file_name || `${kind}_${n}_${seq++}.${ext}`);
95
+ return captionLines(b.caption);
96
+ };
97
+ switch (b.type) {
98
+ case "paragraph":
99
+ case "heading":
100
+ case "footer":
101
+ case "pre":
102
+ return text(b.text);
103
+ case "mathematical_expression":
104
+ return (b.expression || "").split("\n");
105
+ case "divider":
106
+ return ["———"];
107
+ case "anchor":
108
+ case "thinking":
109
+ return [];
110
+ case "list":
111
+ return (b.items || []).flatMap((/** @type {any} */ item) => {
112
+ const box = item.has_checkbox ? (item.is_checked ? "☑ " : "☐ ") : "";
113
+ const label = `${item.label || "•"} ${box}`;
114
+ const lines = inner(item.blocks);
115
+ if (!lines.length) return [label.trimEnd()];
116
+ const indent = " ".repeat([...label].length);
117
+ return [label + lines[0], ...lines.slice(1).map((l) => (l ? indent + l : l))];
118
+ });
119
+ case "blockquote":
120
+ return prefixed("> ", [...inner(b.blocks), ...(b.credit ? [`— ${plain(b.credit)}`] : [])]);
121
+ case "expandable_blockquote":
122
+ case "pullquote":
123
+ return prefixed("> ", [...text(b.text), ...(b.credit ? [`— ${plain(b.credit)}`] : [])]);
124
+ case "collage":
125
+ case "slideshow":
126
+ return [...inner(b.blocks), ...captionLines(b.caption)];
127
+ case "table":
128
+ return [
129
+ ...(b.caption ? text(b.caption) : []),
130
+ ...(b.cells || []).map((/** @type {any[]} */ row) =>
131
+ (row || [])
132
+ .filter((c) => c && c.text != null) // a cell without text is hidden (taken by another's span)
133
+ .map((c) =>
134
+ plain(c.text)
135
+ .replace(/\s*\n\s*/g, " ")
136
+ .trim(),
137
+ )
138
+ .join(" | "),
139
+ ),
140
+ ];
141
+ case "details":
142
+ return [...text(b.summary), ...inner(b.blocks)];
143
+ case "map": {
144
+ const loc = b.location;
145
+ const where = loc ? [`[location: https://www.openstreetmap.org/?mlat=${loc.latitude}&mlon=${loc.longitude}]`] : [];
146
+ return [...where, ...captionLines(b.caption)];
147
+ }
148
+ case "buttons":
149
+ return (b.buttons || []).map(buttonText).filter(Boolean);
150
+ case "photo":
151
+ return file(b.photo?.length ? b.photo[b.photo.length - 1] : null, "photo", "jpg");
152
+ case "video":
153
+ return file(b.video, "video", "mp4");
154
+ case "animation":
155
+ return file(b.animation, "animation", "mp4");
156
+ case "audio":
157
+ return file(b.audio, "audio", "mp3");
158
+ case "voice_note":
159
+ return file(b.voice_note, "voice", "ogg");
160
+ case "document":
161
+ return file(b.document, "file", "bin");
162
+ default:
163
+ // A kind of block newer than this: its text, or what it holds, else a line saying something was left out.
164
+ if (b.text != null) return text(b.text);
165
+ if (Array.isArray(b.blocks)) return inner(b.blocks);
166
+ notes.push(`[${String(b.type || "part").replace(/_/g, " ")}: can't be shown here]`);
167
+ return [];
168
+ }
169
+ }
170
+
171
+ /** Numbers the files without names of the message being read. */
172
+ let seq = 1;
173
+
174
+ /**
175
+ * A Telegram rich message as plain text; its files go to `add`, what can't come over to `notes`.
176
+ * @param {any} rich Message.rich_message
177
+ * @param {number} n the Telegram message's id
178
+ * @param {(f: any, name: string) => void} add
179
+ * @param {string[]} notes
180
+ */
181
+ function richText(rich, n, add, notes) {
182
+ seq = 1;
183
+ const lines = blockLines(rich?.blocks, n, add, notes);
184
+ // Runs of blank lines (empty paragraphs, a heading after a gap) as one.
185
+ return lines
186
+ .map((l) => l.trimEnd())
187
+ .filter((l, i, all) => l !== "" || (i > 0 && all[i - 1] !== ""))
188
+ .join("\n")
189
+ .trim();
190
+ }
191
+
192
+ module.exports = { richText };
@@ -0,0 +1,181 @@
1
+ /// <reference path="../../types/pocketbase.d.ts" />
2
+ // The bridge's worker (DESIGN.md §26.7). A cron job starts it every minute and it runs for most of that minute,
3
+ // once a second: it brings over albums that are complete and sends what is queued for Telegram, oldest first. In
4
+ // development (no webhook URL) it also polls Telegram for updates. One runs at a time (a lock in the app store);
5
+ // POST /api/telegram/tick runs one pass at once (tests, or an admin who doesn't want to wait).
6
+
7
+ const { asTelegram, call, config, UPDATES } = require(`${__hooks}/telegram/api.js`);
8
+ const { flushAlbums, handleUpdate } = require(`${__hooks}/telegram/inbound.js`);
9
+ const { edit, remove, send } = require(`${__hooks}/telegram/outbound.js`);
10
+
11
+ const LOCK = "telegram.worker";
12
+ const OFFSET = "telegram.offset";
13
+ /** A lock not renewed for this long was left by a run that died (lib/worker.js). Renewed after every item a pass handles. */
14
+ const STALE_MS = 90_000;
15
+ /**
16
+ * A queue row being sent is claimed (locked_until) for this long: no other pass sends it meanwhile, even one that took
17
+ * over the lock while this one was stuck on a slow upload (QA BUG-147). A row left claimed by a run that died is sent
18
+ * once it runs out.
19
+ */
20
+ const CLAIM_MS = 10 * 60_000;
21
+ /** How many times a send that failed for now is tried before it is dropped. */
22
+ const MAX_TRIES = 8;
23
+ /** Queue rows looked at in one pass. */
24
+ const BATCH = 50;
25
+
26
+ /**
27
+ * Claim queue row `id` for sending (locked_until), unless another pass has it. In a transaction: PocketBase's writes
28
+ * go one at a time, so two passes can't both claim it.
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("tg_queue", id);
38
+ } catch {
39
+ return; // done by another pass
40
+ }
41
+ const until = row.getDateTime("locked_until");
42
+ if (!until.isZero() && until.time().unixMilli() > Date.now()) return;
43
+ row.set("locked_until", new DateTime(new Date(Date.now() + CLAIM_MS).toISOString()));
44
+ tx.save(row);
45
+ mine = true;
46
+ });
47
+ return mine;
48
+ }
49
+
50
+ /**
51
+ * Updates from Telegram, when polling (no webhook URL), waiting at most `timeout` seconds for one.
52
+ * @param {core.App} app
53
+ * @param {number} timeout
54
+ */
55
+ function poll(app, timeout) {
56
+ const offset = Number(app.store().get(OFFSET) || 0);
57
+ const updates = call("getUpdates", { offset, timeout, allowed_updates: UPDATES }, undefined, timeout + 10) || [];
58
+ for (const u of updates) {
59
+ app.store().set(OFFSET, u.update_id + 1);
60
+ try {
61
+ handleUpdate(app, u);
62
+ } catch (err) {
63
+ app.logger().error("telegram: update", "update", u.update_id, "error", String(err));
64
+ }
65
+ }
66
+ }
67
+
68
+ /**
69
+ * Send what is queued for Telegram, oldest first. A group whose oldest item has to wait (a failure that may pass, or
70
+ * another pass sending it) gets nothing more this pass, so its messages arrive in order. `renew` after each one.
71
+ * @param {core.App} app
72
+ * @param {() => void} renew
73
+ */
74
+ function drain(app, renew) {
75
+ const rows = app.findRecordsByFilter("tg_queue", "op != 'album'", "created,id", BATCH, 0);
76
+ const blocked = new Set();
77
+ const now = Date.now();
78
+ for (const row of rows) {
79
+ if (!row) continue;
80
+ const chat = row.getString("chat_id");
81
+ if (blocked.has(chat)) continue;
82
+ const due = row.getDateTime("next_at");
83
+ if (!due.isZero() && due.time().unixMilli() > now) {
84
+ blocked.add(chat);
85
+ continue;
86
+ }
87
+ if (!claim(app, row.id)) {
88
+ blocked.add(chat);
89
+ continue;
90
+ }
91
+ const op = row.getString("op");
92
+ const message = row.getString("message");
93
+ try {
94
+ if (op === "send") send(app, message, chat);
95
+ else if (op === "edit") edit(app, message, chat);
96
+ else if (op === "delete") remove(app, message, chat);
97
+ app.delete(row);
98
+ } catch (err) {
99
+ const tries = row.getInt("tries") + 1;
100
+ const tg = asTelegram(err);
101
+ const transient = !tg || tg.transient;
102
+ app.logger().warn(`telegram: ${op}`, "message", message, "chat", chat, "try", tries, "error", String(err));
103
+ if (!transient || tries >= MAX_TRIES) {
104
+ app.delete(row);
105
+ continue;
106
+ }
107
+ const wait = Math.max(tg ? tg.retryAfter : 0, 2 ** tries) * 1000;
108
+ row.set("tries", tries);
109
+ row.set("next_at", new DateTime(new Date(Date.now() + wait).toISOString()));
110
+ row.set("locked_until", "");
111
+ row.set("error", String(err).slice(0, 1000));
112
+ app.save(row);
113
+ blocked.add(chat);
114
+ } finally {
115
+ renew();
116
+ }
117
+ }
118
+ }
119
+
120
+ /**
121
+ * One pass: poll (when polling), bring over complete albums, send what is queued. `renew` (the worker's lock) after
122
+ * each item. True when polling: the poll has already waited, so the next pass goes at once.
123
+ * @param {core.App} app
124
+ * @param {number} pollTimeout seconds
125
+ * @param {() => void} renew
126
+ */
127
+ function pass(app, pollTimeout, renew) {
128
+ if (!config().webhookUrl) {
129
+ try {
130
+ poll(app, pollTimeout);
131
+ } catch (err) {
132
+ app.logger().warn("telegram: getUpdates", "error", String(err));
133
+ sleep(1000);
134
+ }
135
+ }
136
+ flushAlbums(app, undefined, undefined, renew);
137
+ drain(app, renew);
138
+ return !config().webhookUrl;
139
+ }
140
+
141
+ /** The worker (lib/worker.js); a pass waits `pollTimeout` seconds at most for Telegram's updates. */
142
+ const worker = (/** @type {core.App} */ app, /** @type {number} */ pollTimeout) => ({
143
+ name: LOCK,
144
+ label: "telegram",
145
+ staleMs: STALE_MS,
146
+ pass: (/** @type {() => void} */ renew) => pass(app, pollTimeout, renew),
147
+ });
148
+
149
+ /**
150
+ * The cron job: passes until the minute is nearly over.
151
+ * @param {core.App} app
152
+ */
153
+ function run(app) {
154
+ require(`${__hooks}/lib/worker.js`).run(app, worker(app, 1));
155
+ }
156
+
157
+ /**
158
+ * POST /api/telegram/tick (superusers): one pass now, unless a run is going (it does the work within a second).
159
+ * @param {core.RequestEvent} e
160
+ */
161
+ function tick(e) {
162
+ const ran = require(`${__hooks}/lib/worker.js`).once(e.app, worker(e.app, 0));
163
+ return e.json(ran ? 200 : 202, { ran });
164
+ }
165
+
166
+ /**
167
+ * On start: tell Telegram where to send updates (one at a time, so they arrive in order), or, without a webhook
168
+ * URL, that the bridge polls.
169
+ * @param {core.App} app
170
+ */
171
+ function setup(app) {
172
+ const { webhookUrl, secret } = config();
173
+ try {
174
+ if (webhookUrl) call("setWebhook", { url: webhookUrl, secret_token: secret, allowed_updates: UPDATES, max_connections: 1 });
175
+ else call("deleteWebhook", {});
176
+ } catch (err) {
177
+ app.logger().error("telegram: setup", "error", String(err));
178
+ }
179
+ }
180
+
181
+ module.exports = { run, tick, setup };
@@ -0,0 +1,47 @@
1
+ /// <reference path="../types/pocketbase.d.ts" />
2
+ // Telegram bridge (DESIGN.md §26): messages go both ways between rooms and the Telegram groups they are linked to.
3
+ // This file, telegram/ and the tg_* collections (pb_migrations/1760000019_telegram.js); what it does on the core
4
+ // collections' saves (messages, users) main.pb.js calls through lib/features.js, which is off without
5
+ // TELEGRAM_BOT_TOKEN. Without it this file registers nothing either.
6
+
7
+ if ($os.getenv("TELEGRAM_BOT_TOKEN").trim()) {
8
+ // Only when serving: other commands (migrate, superuser…) bootstrap too.
9
+ onBootstrap((e) => {
10
+ e.next();
11
+ if ($os.args.includes("serve")) require(`${__hooks}/telegram/worker.js`).setup(e.app);
12
+ });
13
+
14
+ routerAdd("POST", "/api/telegram/webhook", (e) => require(`${__hooks}/telegram/inbound.js`).webhook(e));
15
+ routerAdd("POST", "/api/telegram/tick", (e) => require(`${__hooks}/telegram/worker.js`).tick(e), $apis.requireSuperuserAuth());
16
+
17
+ cronAdd("telegram", "* * * * *", () => require(`${__hooks}/telegram/worker.js`).run($app));
18
+
19
+ // A room says when a group is connected to it or disconnected from it (a service message, §26.5).
20
+ onRecordCreate((e) => {
21
+ const links = require(`${__hooks}/telegram/links.js`);
22
+ links.beforeLinkSave(e);
23
+ e.next();
24
+ if (e.record) links.tellLinkChange(e.app, e.record, "", links.linkedRoom(e.record));
25
+ }, "tg_links");
26
+
27
+ onRecordUpdate((e) => {
28
+ const links = require(`${__hooks}/telegram/links.js`);
29
+ links.beforeLinkSave(e);
30
+ const rec = e.record;
31
+ if (!rec) return e.next();
32
+ // What it was, as stored, read in the save's transaction: the same change saved twice at once tells the room once.
33
+ e.app.runInTransaction((tx) => {
34
+ e.app = tx;
35
+ const was = links.linkedRoom(tx.findRecordById("tg_links", rec.id));
36
+ e.next();
37
+ links.tellLinkChange(tx, rec, was, links.linkedRoom(rec));
38
+ });
39
+ }, "tg_links");
40
+
41
+ onRecordAfterDeleteSuccess((e) => {
42
+ const links = require(`${__hooks}/telegram/links.js`);
43
+ // Deleted with its room (cascade), there's no room left to tell.
44
+ if (e.record) links.tellLinkChange(e.app, e.record, links.linkedRoom(e.record), "");
45
+ e.next();
46
+ }, "tg_links");
47
+ }
@@ -0,0 +1,150 @@
1
+ /// <reference path="../types/pocketbase.d.ts" />
2
+ // Initial schema, API rules and rate limits — DESIGN.md §5.
3
+
4
+ const AUTH = '@request.auth.id != ""';
5
+ const NO_PUBLIC_EMAIL = "(@request.body.emailVisibility:isset = false || @request.body.emailVisibility = false)";
6
+
7
+ /**
8
+ * `new Collection({...})` from a plain object. The JSVM accepts this form (it is PocketBase's documented one), but the
9
+ * generated types describe the Go structs (fields with methods, JSONArray indexes, non-null rules), so cast here once.
10
+ * @param {Record<string, unknown>} data
11
+ */
12
+ const collection = (data) => new Collection(/** @type {any} */ (data));
13
+
14
+ migrate(
15
+ (app) => {
16
+ // users (built-in auth collection, §5.1)
17
+ const users = app.findCollectionByNameOrId("users");
18
+ const name = users.fields.getByName("name");
19
+ name.required = true;
20
+ name.min = 1;
21
+ name.max = 32;
22
+ users.listRule = AUTH;
23
+ users.viewRule = AUTH;
24
+ users.createRule = NO_PUBLIC_EMAIL;
25
+ users.updateRule = `id = @request.auth.id && ${NO_PUBLIC_EMAIL}`;
26
+ users.deleteRule = "id = @request.auth.id";
27
+ app.save(users);
28
+
29
+ // rooms (§5.2)
30
+ const rooms = collection({
31
+ type: "base",
32
+ name: "rooms",
33
+ listRule: AUTH,
34
+ viewRule: AUTH,
35
+ createRule: [
36
+ AUTH,
37
+ "@request.body.created_by = @request.auth.id",
38
+ "(@request.body.archived:isset = false || @request.body.archived = false)",
39
+ "@request.body.archived_at:isset = false",
40
+ ].join(" && "),
41
+ updateRule: [
42
+ "created_by = @request.auth.id",
43
+ "@request.body.created_by:isset = false",
44
+ "@request.body.archived_at:isset = false",
45
+ ].join(" && "),
46
+ deleteRule: null,
47
+ fields: [
48
+ { type: "text", name: "name", required: true, min: 1, max: 48 },
49
+ { type: "relation", name: "created_by", required: true, maxSelect: 1, collectionId: users.id, cascadeDelete: false },
50
+ { type: "bool", name: "archived" },
51
+ { type: "date", name: "archived_at" },
52
+ { type: "autodate", name: "created", onCreate: true, onUpdate: false },
53
+ { type: "autodate", name: "updated", onCreate: true, onUpdate: true },
54
+ ],
55
+ indexes: ["CREATE UNIQUE INDEX `idx_rooms_name` ON `rooms` (`name` COLLATE NOCASE)"],
56
+ });
57
+ app.save(rooms);
58
+
59
+ // messages (§5.3)
60
+ const messages = collection({
61
+ type: "base",
62
+ name: "messages",
63
+ listRule: AUTH,
64
+ viewRule: AUTH,
65
+ createRule: [
66
+ AUTH,
67
+ "@request.body.author = @request.auth.id",
68
+ "@request.body.room.archived = false",
69
+ "@request.body.deleted:isset = false",
70
+ "@request.body.deleted_at:isset = false",
71
+ "@request.body.edited_at:isset = false",
72
+ ].join(" && "),
73
+ updateRule: [
74
+ "author = @request.auth.id",
75
+ "room.archived = false",
76
+ "deleted = false",
77
+ "@request.body.author:isset = false",
78
+ "@request.body.room:isset = false",
79
+ "@request.body.edited_at:isset = false",
80
+ "@request.body.deleted_at:isset = false",
81
+ "(@request.body.deleted:isset = false || @request.body.deleted = true)",
82
+ ].join(" && "),
83
+ deleteRule: null,
84
+ fields: [
85
+ { type: "relation", name: "room", required: true, maxSelect: 1, collectionId: rooms.id, cascadeDelete: true },
86
+ { type: "relation", name: "author", required: true, maxSelect: 1, collectionId: users.id, cascadeDelete: false },
87
+ // Not `required`: a soft-deleted message has empty text. Non-empty is enforced by pb_hooks.
88
+ { type: "text", name: "text", max: 2000 },
89
+ { type: "date", name: "edited_at" },
90
+ { type: "bool", name: "deleted" },
91
+ { type: "date", name: "deleted_at" },
92
+ { type: "autodate", name: "created", onCreate: true, onUpdate: false },
93
+ { type: "autodate", name: "updated", onCreate: true, onUpdate: true },
94
+ ],
95
+ indexes: ["CREATE INDEX `idx_messages_room_created` ON `messages` (`room`, `created`, `id`)"],
96
+ });
97
+ app.save(messages);
98
+
99
+ // hidden_rooms (§5.4)
100
+ const hidden = collection({
101
+ type: "base",
102
+ name: "hidden_rooms",
103
+ listRule: "user = @request.auth.id",
104
+ viewRule: "user = @request.auth.id",
105
+ createRule: `${AUTH} && @request.body.user = @request.auth.id`,
106
+ updateRule: null,
107
+ deleteRule: "user = @request.auth.id",
108
+ fields: [
109
+ { type: "relation", name: "user", required: true, maxSelect: 1, collectionId: users.id, cascadeDelete: true },
110
+ { type: "relation", name: "room", required: true, maxSelect: 1, collectionId: rooms.id, cascadeDelete: true },
111
+ { type: "autodate", name: "created", onCreate: true, onUpdate: false },
112
+ ],
113
+ indexes: ["CREATE UNIQUE INDEX `idx_hidden_rooms_user_room` ON `hidden_rooms` (`user`, `room`)"],
114
+ });
115
+ app.save(hidden);
116
+
117
+ // rate limits (§5.6): keep PocketBase's defaults, add ours in front.
118
+ const settings = app.settings();
119
+ const ours = [
120
+ { label: "messages:create", audience: "", duration: 5, maxRequests: 10 },
121
+ { label: "users:create", audience: "@guest", duration: 60, maxRequests: 20 },
122
+ ];
123
+ const labels = ours.map((r) => r.label);
124
+ // Plain objects work here too; the generated RateLimitRule type is the Go struct (with methods).
125
+ settings.rateLimits.rules = [.../** @type {any[]} */ (ours), ...settings.rateLimits.rules.filter((r) => !labels.includes(r.label))];
126
+ settings.rateLimits.enabled = true;
127
+ app.save(settings);
128
+ },
129
+ (app) => {
130
+ for (const n of ["hidden_rooms", "messages", "rooms"]) {
131
+ app.delete(app.findCollectionByNameOrId(n));
132
+ }
133
+ const users = app.findCollectionByNameOrId("users");
134
+ const name = users.fields.getByName("name");
135
+ name.required = false;
136
+ name.min = 0;
137
+ name.max = 255;
138
+ users.listRule = "id = @request.auth.id";
139
+ users.viewRule = "id = @request.auth.id";
140
+ users.createRule = "";
141
+ users.updateRule = "id = @request.auth.id";
142
+ users.deleteRule = "id = @request.auth.id";
143
+ app.save(users);
144
+
145
+ const settings = app.settings();
146
+ settings.rateLimits.rules = settings.rateLimits.rules.filter((r) => !["messages:create", "users:create"].includes(r.label));
147
+ settings.rateLimits.enabled = false;
148
+ app.save(settings);
149
+ },
150
+ );
@@ -0,0 +1,69 @@
1
+ /// <reference path="../types/pocketbase.d.ts" />
2
+ // Fixes from the QA pass (DESIGN.md §5.2, §5.5, §5.6):
3
+ // - rooms.name_key: Unicode-aware unique room names ("Über" = "über", "Straße" = "STRASSE"), set by pb_hooks.
4
+ // - users can't delete their own account through the API: their messages and rooms reference them
5
+ // (required relations), so the delete always failed for anyone who had posted.
6
+ // - rate limits for message edits/deletes and for room creation.
7
+
8
+ const NEW_LIMITS = [
9
+ { label: "messages:update", audience: "", duration: 10, maxRequests: 20 },
10
+ { label: "rooms:create", audience: "", duration: 60, maxRequests: 5 },
11
+ ];
12
+
13
+ /**
14
+ * Same as nameKey() in pb_hooks/lib/text.js (migrations can't load the hooks' modules).
15
+ * @param {string} name
16
+ */
17
+ function roomKey(name) {
18
+ const s = name.replace(/[­᠎​-‏‪-‮⁠-⁤⁦-⁩]/g, "");
19
+ return (typeof s.normalize === "function" ? s.normalize("NFKC") : s).toUpperCase().toLowerCase();
20
+ }
21
+
22
+ migrate(
23
+ (app) => {
24
+ const rooms = app.findCollectionByNameOrId("rooms");
25
+ rooms.fields.add(new TextField({ name: "name_key", hidden: true, max: 400 }));
26
+ app.save(rooms);
27
+
28
+ // Backfill with raw SQL (no hooks). Names that already clash keep a key made unique by their id.
29
+ const seen = new Set();
30
+ for (const r of app.findAllRecords("rooms")) {
31
+ if (!r) continue;
32
+ let key = roomKey(r.getString("name"));
33
+ if (seen.has(key)) key = `${key}#${r.id}`;
34
+ seen.add(key);
35
+ app.db().newQuery("UPDATE rooms SET name_key = {:key} WHERE id = {:id}").bind({ key, id: r.id }).execute();
36
+ }
37
+
38
+ const withIndex = app.findCollectionByNameOrId("rooms");
39
+ withIndex.addIndex("idx_rooms_name_key", true, "`name_key`", "`name_key` != ''");
40
+ app.save(withIndex);
41
+
42
+ const users = app.findCollectionByNameOrId("users");
43
+ // null = superusers only. The generated type says string (a Go *string), so cast.
44
+ /** @type {any} */ (users).deleteRule = null;
45
+ app.save(users);
46
+
47
+ const settings = app.settings();
48
+ const labels = NEW_LIMITS.map((r) => r.label);
49
+ const rest = settings.rateLimits.rules.filter((r) => !labels.includes(r.label));
50
+ // Ours first, as in the init migration. Plain objects work here; the generated type is the Go struct.
51
+ settings.rateLimits.rules = [.../** @type {any[]} */ (NEW_LIMITS), ...rest];
52
+ app.save(settings);
53
+ },
54
+ (app) => {
55
+ const rooms = app.findCollectionByNameOrId("rooms");
56
+ rooms.removeIndex("idx_rooms_name_key");
57
+ rooms.fields.removeByName("name_key");
58
+ app.save(rooms);
59
+
60
+ const users = app.findCollectionByNameOrId("users");
61
+ users.deleteRule = "id = @request.auth.id";
62
+ app.save(users);
63
+
64
+ const settings = app.settings();
65
+ const labels = NEW_LIMITS.map((r) => r.label);
66
+ settings.rateLimits.rules = settings.rateLimits.rules.filter((r) => !labels.includes(r.label));
67
+ app.save(settings);
68
+ },
69
+ );
@@ -0,0 +1,39 @@
1
+ /// <reference path="../types/pocketbase.d.ts" />
2
+ // Avatars (DESIGN.md §15.1): configure the built-in users.avatar file field. Raster images only (no SVG),
3
+ // 2 MB, square thumbnails for 1× and 2× screens, public.
4
+
5
+ const AVATAR = {
6
+ maxSelect: 1,
7
+ maxSize: 2 * 1024 * 1024,
8
+ mimeTypes: ["image/jpeg", "image/png", "image/webp", "image/gif"],
9
+ thumbs: ["48x48", "96x96"],
10
+ protected: false,
11
+ };
12
+
13
+ /** PocketBase's defaults for the field, restored on down. */
14
+ const DEFAULTS = {
15
+ maxSelect: 1,
16
+ maxSize: 0,
17
+ mimeTypes: ["image/jpeg", "image/png", "image/svg+xml", "image/gif", "image/webp"],
18
+ thumbs: [],
19
+ protected: false,
20
+ };
21
+
22
+ /** @typedef {Parameters<Parameters<typeof migrate>[0]>[0]} AvatarMigrationApp */
23
+
24
+ /**
25
+ * @param {AvatarMigrationApp} app
26
+ * @param {typeof AVATAR} settings
27
+ */
28
+ function configure(app, settings) {
29
+ const users = app.findCollectionByNameOrId("users");
30
+ // The generated types model the Go field struct; the JSVM accepts plain property writes.
31
+ const avatar = /** @type {any} */ (users.fields.getByName("avatar"));
32
+ Object.assign(avatar, settings);
33
+ app.save(users);
34
+ }
35
+
36
+ migrate(
37
+ (app) => configure(app, AVATAR),
38
+ (app) => configure(app, DEFAULTS),
39
+ );