chirkle 0.2.0 → 0.3.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 (64) hide show
  1. package/README.md +4 -1
  2. package/package.json +1 -1
  3. package/pb_hooks/federation/messages.js +48 -2
  4. package/pb_hooks/lib/anonymous.js +10 -6
  5. package/pb_hooks/lib/bulk.js +2 -0
  6. package/pb_hooks/lib/files.js +39 -47
  7. package/pb_hooks/lib/handles.js +337 -0
  8. package/pb_hooks/lib/http.js +35 -23
  9. package/pb_hooks/lib/inbox.js +383 -0
  10. package/pb_hooks/lib/lists.js +8 -2
  11. package/pb_hooks/lib/live.js +137 -0
  12. package/pb_hooks/lib/messages.js +4 -0
  13. package/pb_hooks/lib/reactions.js +2 -0
  14. package/pb_hooks/lib/reads.js +3 -1
  15. package/pb_hooks/lib/site.js +1 -1
  16. package/pb_hooks/lib/stats.js +252 -0
  17. package/pb_hooks/lib/users.js +6 -1
  18. package/pb_hooks/main.pb.js +103 -26
  19. package/pb_hooks/telegram/people.js +4 -0
  20. package/pb_hooks/telegram/reactions.js +67 -11
  21. package/pb_migrations/1760000044_stats.js +70 -0
  22. package/pb_migrations/1760000045_mentions.js +187 -0
  23. package/pb_migrations/1760000046_reserved_handles.js +29 -0
  24. package/pb_public/assets/access-GUDTDXIP.js +2 -0
  25. package/pb_public/assets/access-GUDTDXIP.js.map +7 -0
  26. package/pb_public/assets/app-3WX5JYL2.js +3 -0
  27. package/pb_public/assets/app-3WX5JYL2.js.map +7 -0
  28. package/pb_public/assets/app-WAFKVN2H.css +2 -0
  29. package/pb_public/assets/app-WAFKVN2H.css.map +7 -0
  30. package/pb_public/assets/{emoji-WSTVXAW5.css → emoji-VA2WCEAC.css} +2 -2
  31. package/pb_public/assets/{emoji-WSTVXAW5.css.map → emoji-VA2WCEAC.css.map} +2 -2
  32. package/pb_public/assets/{emoji-picker-QYRX6NYL.js → emoji-picker-65VVVGYW.js} +2 -2
  33. package/pb_public/assets/forward-66PELNWT.js +2 -0
  34. package/pb_public/assets/forward-66PELNWT.js.map +7 -0
  35. package/pb_public/assets/inbox-3FSOPY2T.css +2 -0
  36. package/pb_public/assets/inbox-3FSOPY2T.css.map +7 -0
  37. package/pb_public/assets/inbox-TZJWPRTG.js +2 -0
  38. package/pb_public/assets/inbox-TZJWPRTG.js.map +7 -0
  39. package/pb_public/assets/login-G7Y44CJ7.js +2 -0
  40. package/pb_public/assets/login-G7Y44CJ7.js.map +7 -0
  41. package/pb_public/assets/mention-suggest-R7MXUH6R.js +2 -0
  42. package/pb_public/assets/mention-suggest-R7MXUH6R.js.map +7 -0
  43. package/pb_public/assets/notify-RQ6ZLR46.js +2 -0
  44. package/pb_public/assets/notify-RQ6ZLR46.js.map +7 -0
  45. package/pb_public/assets/profile-2CNVT2KX.js +2 -0
  46. package/pb_public/assets/profile-2CNVT2KX.js.map +7 -0
  47. package/pb_public/assets/stats-A2TBRUI6.css +2 -0
  48. package/pb_public/assets/stats-A2TBRUI6.css.map +7 -0
  49. package/pb_public/assets/stats-JX52AQCO.js +2 -0
  50. package/pb_public/assets/stats-JX52AQCO.js.map +7 -0
  51. package/pb_public/assets/user-search-7GNEIXMN.js +2 -0
  52. package/pb_public/assets/user-search-7GNEIXMN.js.map +7 -0
  53. package/pb_public/index.html +2 -2
  54. package/pb_public/stats.html +25 -0
  55. package/pb_public/sw.js +1 -1
  56. package/pb_public/assets/access-ALBW2MT2.js +0 -2
  57. package/pb_public/assets/access-ALBW2MT2.js.map +0 -7
  58. package/pb_public/assets/app-A3SXD3FF.css +0 -2
  59. package/pb_public/assets/app-A3SXD3FF.css.map +0 -7
  60. package/pb_public/assets/app-NDSIQW4L.js +0 -3
  61. package/pb_public/assets/app-NDSIQW4L.js.map +0 -7
  62. package/pb_public/assets/notify-L6GERFNO.js +0 -2
  63. package/pb_public/assets/notify-L6GERFNO.js.map +0 -7
  64. /package/pb_public/assets/{emoji-picker-QYRX6NYL.js.map → emoji-picker-65VVVGYW.js.map} +0 -0
@@ -15,7 +15,8 @@ const CSP = [
15
15
  ].join("; ");
16
16
 
17
17
  /**
18
- * Security + cache headers for every response (§5.6).
18
+ * Security + cache headers (§5.6), set by the routes that serve the app (page, asset, the manifest). Not by a router
19
+ * middleware for every request (main.pb.js): PocketBase's own already sends nosniff with every API answer.
19
20
  * @param {core.RequestEvent} e
20
21
  */
21
22
  function headers(e) {
@@ -30,7 +31,7 @@ function headers(e) {
30
31
  if (/^\/assets\/.+-[A-Z0-9]{8}\.(js|css|woff2)(\.map)?$/.test(path)) h.set("Cache-Control", "public, max-age=31536000, immutable");
31
32
  else h.set("Cache-Control", "no-cache");
32
33
  // A page (the app's index.html, at any path without a file name): what it loads first.
33
- if (e.request?.method === "GET" && !path.startsWith("/assets/") && !/\.[a-z0-9]+$/i.test(path)) {
34
+ if (e.request?.method === "GET" && path !== STATS_PATH && !path.startsWith("/assets/") && !/\.[a-z0-9]+$/i.test(path)) {
34
35
  const link = preloads();
35
36
  if (link) h.set("Link", link);
36
37
  }
@@ -73,26 +74,6 @@ function preloads() {
73
74
  return links;
74
75
  }
75
76
 
76
- /** PocketBase's own request body limit, which every request but a message create keeps. */
77
- const DEFAULT_BODY_LIMIT = 32 << 20;
78
-
79
- /** A message create: 10 attachments of 20 MB (DESIGN.md §17.1), and room for the rest of the form. */
80
- const MESSAGE_BODY_LIMIT = 10 * 20 * 1024 * 1024 + (1 << 20);
81
-
82
- /**
83
- * The body limit is MESSAGE_BODY_LIMIT for every route (main.pb.js replaces PocketBase's default, as one route can't
84
- * have its own: the records API is PocketBase's): hold a body to the default anywhere but a message create, as
85
- * PocketBase's limiter does, counting what is read. Not by Content-Length alone: a chunked body has none (-1), and was
86
- * let through to MESSAGE_BODY_LIMIT, signups and logins too (QA BUG-143). The Android app sends chunked uploads when a
87
- * file's size is unknown, so those are limited, not refused. Goes on with the request (e.next) when within it.
88
- * @param {core.RequestEvent} e
89
- */
90
- function bodyLimit(e) {
91
- const req = e.request;
92
- if (req?.method === "POST" && req.url?.path === "/api/collections/messages/records") return e.next();
93
- return $apis.bodyLimit(DEFAULT_BODY_LIMIT).func(e);
94
- }
95
-
96
77
  /** The directory the app is served from: `--publicDir`, else PocketBase's default, pb_public beside the executable. */
97
78
  function publicDir() {
98
79
  const args = $os.args;
@@ -110,6 +91,7 @@ function publicDir() {
110
91
  * @param {core.RequestEvent} e
111
92
  */
112
93
  function asset(e) {
94
+ headers(e);
113
95
  const dir = $filepath.join(publicDir(), "assets");
114
96
  const path = e.request?.pathValue("path") ?? "";
115
97
  try {
@@ -122,6 +104,16 @@ function asset(e) {
122
104
  return $apis.static(dir, false)(e);
123
105
  }
124
106
 
107
+ /**
108
+ * GET /{path...}: the app's files in the public directory, and index.html at any path that isn't one (§7.1), as
109
+ * PocketBase serves them when no route of ours does, with the headers.
110
+ * @param {core.RequestEvent} e
111
+ */
112
+ function page(e) {
113
+ headers(e);
114
+ return $apis.static(publicDir(), true)(e);
115
+ }
116
+
125
117
  /**
126
118
  * Who the client is behind a reverse proxy (Dokku, nginx, Caddy…). PocketBase rate limits per client IP, and without a
127
119
  * trusted header every request comes from the proxy: each per-IP limit would be one limit for the whole site (a script
@@ -143,4 +135,24 @@ function trustProxy(app) {
143
135
  app.save(settings);
144
136
  }
145
137
 
146
- module.exports = { headers, bodyLimit, asset, trustProxy, MESSAGE_BODY_LIMIT };
138
+ /** The usage statistics page (§40): a page of its own, not the app's. */
139
+ const STATS_PATH = "/stats";
140
+
141
+ /**
142
+ * GET /stats: the statistics page (stats.html, built from web/stats.html), to anyone: it asks GET /api/chat/stats, which
143
+ * only moderators and superusers get. Not built yet (the dev build has it too): a 404.
144
+ * @param {core.RequestEvent} e
145
+ */
146
+ function statsPage(e) {
147
+ headers(e);
148
+ /** @type {string} */
149
+ let html;
150
+ try {
151
+ html = toString($os.readFile($filepath.join(publicDir(), "stats.html")));
152
+ } catch {
153
+ throw new NotFoundError();
154
+ }
155
+ return e.html(200, html);
156
+ }
157
+
158
+ module.exports = { headers, page, asset, statsPage, trustProxy };
@@ -0,0 +1,383 @@
1
+ /// <reference path="../../types/pocketbase.d.ts" />
2
+ // The "Mentions & replies" inbox (DESIGN.md §41): a row (`inbox`) for each thing to tell someone of: a message that
3
+ // mentions them, a reply to one of their messages, a reaction to one. The messages hooks keep the rows as messages are
4
+ // made, edited, deleted and reacted to, whichever way (the apps, a linked instance, the Telegram bridge); they go with a
5
+ // deleted message, and a room you can't see any more keeps its rows out of the list. Each new or removed row is told
6
+ // live to its person's apps (TOPIC). GET /api/chat/inbox lists them, newest first; POST /api/chat/inbox/seen notes how
7
+ // far they have been looked at, and GET /api/chat/unread counts the rest (`inbox`) and the unread mentions and replies
8
+ // of each room (`mentions`).
9
+
10
+ const { SEES_SQL } = require(`${__hooks}/lib/access.js`);
11
+ const { reactionsOf } = require(`${__hooks}/lib/reactions.js`);
12
+
13
+ const TOPIC = "chat/inbox";
14
+ /** Most rows one page lists. */
15
+ const PAGE = 30;
16
+ /** The "unseen" count stops here (shown as "99+"). */
17
+ const CAP = 100;
18
+ /** How much of a message's text a row shows. */
19
+ const SNIPPET = 200;
20
+
21
+ /**
22
+ * Does `user` have an inbox? Not a stand-in (a Telegram sender's, §26.3, or another instance's person's, §33.4): they
23
+ * never sign in here.
24
+ * @param {core.App} app
25
+ * @param {string} userId
26
+ */
27
+ function hasInbox(app, userId) {
28
+ if (!userId) return false;
29
+ try {
30
+ const u = app.findRecordById("users", userId);
31
+ return !/@(telegram|federation)\.invalid$/.test(u.getString("email"));
32
+ } catch {
33
+ return false;
34
+ }
35
+ }
36
+
37
+ /**
38
+ * Add a row, unless it is the actor's own or there already.
39
+ * @param {core.App} app
40
+ * @param {{ user: string, kind: string, message: core.Record, actor: string, emoji?: string }} row
41
+ */
42
+ function add(app, { user, kind, message, actor, emoji = "" }) {
43
+ if (!user || !actor || user === actor || !hasInbox(app, user)) return;
44
+ try {
45
+ app.findFirstRecordByFilter("inbox", "user = {:u} && message = {:m} && kind = {:k} && actor = {:a} && emoji = {:e}", {
46
+ u: user,
47
+ m: message.id,
48
+ k: kind,
49
+ a: actor,
50
+ e: emoji,
51
+ });
52
+ return; // there already
53
+ } catch {
54
+ // not yet
55
+ }
56
+ const rec = new Record(app.findCollectionByNameOrId("inbox"));
57
+ rec.set("user", user);
58
+ rec.set("kind", kind);
59
+ rec.set("message", message.id);
60
+ rec.set("room", message.getString("room"));
61
+ rec.set("actor", actor);
62
+ rec.set("emoji", emoji);
63
+ try {
64
+ app.save(rec);
65
+ } catch {
66
+ // already there (the unique index)
67
+ }
68
+ }
69
+
70
+ /**
71
+ * Remove the rows of `messageId` that match `where` (a filter on inbox, with its own params).
72
+ * @param {core.App} app
73
+ * @param {string} messageId
74
+ * @param {string} [where]
75
+ * @param {Record<string, string>} [params]
76
+ */
77
+ function remove(app, messageId, where = "", params = {}) {
78
+ const filter = `message = {:m}${where ? ` && (${where})` : ""}`;
79
+ for (const row of app.findRecordsByFilter("inbox", filter, "", 0, 0, { ...params, m: messageId })) if (row) app.delete(row);
80
+ }
81
+
82
+ /**
83
+ * The author of the message `rec` replies to, "" when none (or a service message's).
84
+ * @param {core.App} app
85
+ * @param {core.Record} rec
86
+ */
87
+ function repliedTo(app, rec) {
88
+ const id = rec.getString("reply_to");
89
+ if (!id) return "";
90
+ try {
91
+ return app.findRecordById("messages", id).getString("author");
92
+ } catch {
93
+ return "";
94
+ }
95
+ }
96
+
97
+ /**
98
+ * messages create (saved, in its transaction): a reply tells the author of what it answers; a mention, whoever it
99
+ * names (but not that author again: the reply says it).
100
+ * @param {core.App} app
101
+ * @param {core.Record} rec
102
+ */
103
+ function messageCreated(app, rec) {
104
+ const author = rec.getString("author");
105
+ if (!author || rec.getBool("deleted")) return;
106
+ const parent = repliedTo(app, rec);
107
+ if (parent) add(app, { user: parent, kind: "reply", message: rec, actor: author });
108
+ for (const user of rec.getStringSlice("mentions")) {
109
+ if (user !== parent) add(app, { user, kind: "mention", message: rec, actor: author });
110
+ }
111
+ }
112
+
113
+ /**
114
+ * What messageChanged compares with: the message's mentions and reactions before the save.
115
+ * @param {core.Record} rec the record about to be saved
116
+ */
117
+ const before = (rec) => {
118
+ const orig = rec.original();
119
+ return { mentions: orig.getStringSlice("mentions"), reactions: reactionsOf(orig), deleted: orig.getBool("deleted") };
120
+ };
121
+
122
+ /**
123
+ * messages update (saved, in its transaction): a deleted message takes its rows; changed mentions add and remove
124
+ * theirs; a reaction added to someone's message tells them, and taken back, no longer does.
125
+ * @param {core.App} app
126
+ * @param {core.Record} rec
127
+ * @param {ReturnType<typeof before>} was
128
+ */
129
+ function messageChanged(app, rec, was) {
130
+ if (rec.getBool("deleted")) {
131
+ if (!was.deleted) remove(app, rec.id);
132
+ return;
133
+ }
134
+ const author = rec.getString("author");
135
+ if (!author) return;
136
+ const now = rec.getStringSlice("mentions");
137
+ if (now.join(",") !== was.mentions.join(",")) {
138
+ const parent = repliedTo(app, rec);
139
+ for (const user of was.mentions) {
140
+ if (!now.includes(user)) remove(app, rec.id, "kind = 'mention' && user = {:u}", { u: user });
141
+ }
142
+ for (const user of now) {
143
+ if (!was.mentions.includes(user) && user !== parent) add(app, { user, kind: "mention", message: rec, actor: author });
144
+ }
145
+ }
146
+ const reactions = reactionsOf(rec);
147
+ /** @param {{ emoji: string, users: string[] }[]} list @param {string} emoji @param {string} user */
148
+ const has = (list, emoji, user) => list.some((r) => r.emoji === emoji && r.users.includes(user));
149
+ for (const r of reactions) {
150
+ for (const u of r.users)
151
+ if (!has(was.reactions, r.emoji, u)) add(app, { user: author, kind: "reaction", message: rec, actor: u, emoji: r.emoji });
152
+ }
153
+ for (const r of was.reactions) {
154
+ for (const u of r.users) {
155
+ if (!has(reactions, r.emoji, u)) {
156
+ remove(app, rec.id, "kind = 'reaction' && actor = {:a} && emoji = {:e}", { a: u, e: r.emoji });
157
+ }
158
+ }
159
+ }
160
+ }
161
+
162
+ /**
163
+ * An inbox row added or removed (committed): its person's apps hear of it on TOPIC, as { action, id, kind, room,
164
+ * message, created }. A failure is logged: the apps count again when they reconnect.
165
+ * @param {core.App} app
166
+ * @param {core.Record | undefined} row
167
+ * @param {"create" | "delete"} action
168
+ */
169
+ function tell(app, row, action) {
170
+ if (!row) return;
171
+ try {
172
+ const user = row.getString("user");
173
+ const clients = app.subscriptionsBroker().clients();
174
+ let data = "";
175
+ for (const id of Object.keys(clients)) {
176
+ const client = clients[id];
177
+ if (!client || client.isDiscarded() || !client.hasSubscription(TOPIC)) continue;
178
+ /** @type {core.Record | null | undefined} */
179
+ const auth = client.get("auth");
180
+ if (!auth || auth.isSuperuser() || auth.id !== user) continue;
181
+ if (!data) {
182
+ let created = "";
183
+ try {
184
+ created = app.findRecordById("messages", row.getString("message")).getString("created");
185
+ } catch {
186
+ created = ""; // deleted for good with it
187
+ }
188
+ data = JSON.stringify({
189
+ action,
190
+ id: row.id,
191
+ kind: row.getString("kind"),
192
+ room: row.getString("room"),
193
+ message: row.getString("message"),
194
+ created,
195
+ });
196
+ }
197
+ client.send(new SubscriptionMessage({ name: TOPIC, data }));
198
+ }
199
+ } catch (err) {
200
+ app.logger().error("inbox: a row wasn't told", "row", row.id, "error", String(err));
201
+ }
202
+ }
203
+
204
+ /**
205
+ * When `user` last looked at their inbox ("" for never).
206
+ * @param {core.App} app
207
+ * @param {string} user
208
+ */
209
+ function seenAt(app, user) {
210
+ try {
211
+ return app.findFirstRecordByFilter("inbox_reads", "user = {:u}", { u: user }).getString("seen_at");
212
+ } catch {
213
+ return "";
214
+ }
215
+ }
216
+
217
+ /** The rows a person is shown: their room still visible to them, the message not deleted. */
218
+ const VISIBLE_SQL = `FROM inbox i JOIN messages m ON m.id = i.message JOIN rooms r ON r.id = i.room
219
+ WHERE i.user = {:me} AND m.deleted = FALSE AND ${SEES_SQL}`;
220
+
221
+ /**
222
+ * For GET /api/chat/unread: how many rows `user` hasn't seen (at most CAP), and per room the mentions of them and
223
+ * replies to them that are still unread there (newer than their read position, or signup).
224
+ * @param {core.App} app
225
+ * @param {core.Record} user
226
+ */
227
+ function counts(app, user) {
228
+ const unseen = new DynamicModel({ n: 0 });
229
+ app
230
+ .db()
231
+ .newQuery(`SELECT COUNT(*) AS n FROM (SELECT 1 ${VISIBLE_SQL} AND i.created > {:seen} LIMIT ${CAP})`)
232
+ .bind({ me: user.id, seen: seenAt(app, user.id) })
233
+ .one(unseen);
234
+ const rows = arrayOf(new DynamicModel({ room: "", n: 0 }));
235
+ app
236
+ .db()
237
+ .newQuery(
238
+ `SELECT i.room AS room, COUNT(DISTINCT i.message) AS n ${VISIBLE_SQL} AND i.kind != 'reaction'
239
+ AND m.created > MAX(COALESCE((SELECT rr.last_read_at FROM room_reads rr WHERE rr.user = {:me} AND rr.room = i.room), ''), {:since})
240
+ GROUP BY i.room`,
241
+ )
242
+ .bind({ me: user.id, since: user.getString("created") })
243
+ .all(rows);
244
+ /** @type {Record<string, number>} */
245
+ const mentions = {};
246
+ for (const row of rows) mentions[row.room] = row.n;
247
+ return { inbox: unseen.n, mentions };
248
+ }
249
+
250
+ /** @param {string} s */
251
+ const snippet = (s) => {
252
+ const line = s.replace(/\s+/g, " ").trim();
253
+ return [...line].length > SNIPPET ? `${[...line].slice(0, SNIPPET).join("")}…` : line;
254
+ };
255
+
256
+ /**
257
+ * What a message shows in a row: its text (a forward's, its original's) cut short, and how many files it has.
258
+ * @param {core.App} app
259
+ * @param {core.Record} msg
260
+ */
261
+ function shown(app, msg) {
262
+ let src = msg;
263
+ if (msg.getString("forward_of")) {
264
+ try {
265
+ src = app.findRecordById("messages", msg.getString("forward_of"));
266
+ if (src.getBool("deleted")) return { text: "", files: 0 };
267
+ } catch {
268
+ return { text: "", files: 0 };
269
+ }
270
+ }
271
+ return { text: snippet(src.getString("text")), files: src.getStringSlice("files").length };
272
+ }
273
+
274
+ /**
275
+ * GET /api/chat/inbox?before=&limit= → { items, more, seen_at }: the caller's rows, newest first, PAGE at a time
276
+ * (`before`: the last item's `cursor`). Each item: { id, cursor, kind, emoji, created, room, message: { id, text, files,
277
+ * created }, quote (a reply's: the caller's message it answers, { id, text, files }), actor: { id, name, avatar,
278
+ * instance } }. In an anonymous room (§35) a mention or reply shows the room, not who wrote it.
279
+ * @param {core.RequestEvent} e
280
+ */
281
+ function list(e) {
282
+ const me = e.auth;
283
+ if (!me) throw new UnauthorizedError("The request requires a logged-in user.");
284
+ const q = e.requestInfo().query;
285
+ const limit = Math.max(1, Math.min(PAGE, Number.parseInt(String(q.limit ?? PAGE), 10) || PAGE));
286
+ const before = typeof q.before === "string" ? q.before : "";
287
+ const [bCreated, bId] = before.includes("|") ? before.split("|") : ["", ""];
288
+ const rows = arrayOf(new DynamicModel({ id: "", kind: "", emoji: "", created: "", room: "", message: "", actor: "" }));
289
+ e.app
290
+ .db()
291
+ .newQuery(
292
+ `SELECT i.id AS id, i.kind AS kind, i.emoji AS emoji, i.created AS created, i.room AS room, i.message AS message, i.actor AS actor
293
+ ${VISIBLE_SQL} ${bCreated ? "AND (i.created < {:bc} OR (i.created = {:bc} AND i.id < {:bi}))" : ""}
294
+ ORDER BY i.created DESC, i.id DESC LIMIT ${limit + 1}`,
295
+ )
296
+ .bind({ me: me.id, bc: bCreated, bi: bId })
297
+ .all(rows);
298
+ const more = rows.length > limit;
299
+ const page = rows.slice(0, limit);
300
+ const messages = new Map(e.app.findRecordsByIds("messages", [...new Set(page.map((r) => r.message))]).map((m) => [m?.id, m]));
301
+ const actors = new Map(e.app.findRecordsByIds("users", [...new Set(page.map((r) => r.actor))]).map((u) => [u?.id, u]));
302
+ const { roomName } = require(`${__hooks}/lib/anonymous.js`);
303
+ const items = page.flatMap((row) => {
304
+ const msg = messages.get(row.message);
305
+ if (!msg) return [];
306
+ const u = actors.get(row.actor);
307
+ const hidden = row.kind !== "reaction" && msg.getBool("anonymous") && !e.hasSuperuserAuth();
308
+ const actor = hidden
309
+ ? { id: row.room, name: roomName(e.app, row.room), avatar: "", instance: "" }
310
+ : { id: row.actor, name: u?.getString("name") ?? "", avatar: u?.getString("avatar") ?? "", instance: u?.getString("instance") ?? "" };
311
+ /** @type {{ id: string, text: string, files: number } | null} */
312
+ let quote = null;
313
+ if (row.kind === "reply" && msg.getString("reply_to")) {
314
+ try {
315
+ const original = e.app.findRecordById("messages", msg.getString("reply_to"));
316
+ quote = original.getBool("deleted") ? { id: original.id, text: "", files: 0 } : { id: original.id, ...shown(e.app, original) };
317
+ } catch {
318
+ quote = null;
319
+ }
320
+ }
321
+ return [
322
+ {
323
+ id: row.id,
324
+ cursor: `${row.created}|${row.id}`,
325
+ kind: row.kind,
326
+ emoji: row.emoji,
327
+ created: row.created,
328
+ room: row.room,
329
+ message: { id: msg.id, created: msg.getString("created"), ...shown(e.app, msg) },
330
+ quote,
331
+ actor,
332
+ },
333
+ ];
334
+ });
335
+ return e.json(200, { items, more, seen_at: seenAt(e.app, me.id) });
336
+ }
337
+
338
+ /**
339
+ * POST /api/chat/inbox/seen { at? }: the caller has looked at their inbox up to `at` (a row's `created`; default now).
340
+ * Never moves back, nor past now.
341
+ * @param {core.RequestEvent} e
342
+ */
343
+ function markSeen(e) {
344
+ const me = e.auth;
345
+ if (!me) throw new UnauthorizedError("The request requires a logged-in user.");
346
+ const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body);
347
+ const now = new DateTime();
348
+ let at = now;
349
+ if (body.at !== undefined) {
350
+ try {
351
+ at = typeof body.at === "string" && body.at ? new DateTime(body.at) : now;
352
+ } catch {
353
+ throw new BadRequestError("Failed to mark the inbox as seen.", {
354
+ at: new ValidationError("validation_invalid_value", "Must be a date."),
355
+ });
356
+ }
357
+ if (at.isZero() || at.after(now)) at = now;
358
+ }
359
+ let row = null;
360
+ try {
361
+ row = e.app.findFirstRecordByFilter("inbox_reads", "user = {:u}", { u: me.id });
362
+ } catch {
363
+ row = null;
364
+ }
365
+ if (!row) {
366
+ row = new Record(e.app.findCollectionByNameOrId("inbox_reads"));
367
+ row.set("user", me.id);
368
+ row.set("seen_at", at);
369
+ try {
370
+ e.app.save(row);
371
+ } catch {
372
+ // another tab made it meanwhile
373
+ row = e.app.findFirstRecordByFilter("inbox_reads", "user = {:u}", { u: me.id });
374
+ }
375
+ }
376
+ if (at.after(row.getDateTime("seen_at"))) {
377
+ row.set("seen_at", at);
378
+ e.app.save(row);
379
+ }
380
+ return e.json(200, { seen_at: row.getString("seen_at") });
381
+ }
382
+
383
+ module.exports = { TOPIC, before, messageCreated, messageChanged, tell, counts, list, markSeen };
@@ -35,6 +35,8 @@ const KINDS = {
35
35
  * @param {core.RequestEvent} e
36
36
  */
37
37
  function rooms(e) {
38
+ // As the records API's (main.pb.js): this page's ?expand mustn't group messages by author (§35).
39
+ require(`${__hooks}/lib/anonymous.js`).refuseProbes(e);
38
40
  const me = e.auth && !e.auth.isSuperuser() ? e.auth.id : "";
39
41
  const where = e.hasSuperuserAuth() ? "1" : me ? SEES_SQL : "r.visibility = 'open' AND NOT r.archived";
40
42
  const rows = arrayOf(new DynamicModel({ id: "" }));
@@ -59,6 +61,8 @@ function rooms(e) {
59
61
  * @param {core.RequestEvent} e
60
62
  */
61
63
  function messages(e) {
64
+ // As the records API's (main.pb.js): this page's ?expand mustn't group messages by author (§35).
65
+ require(`${__hooks}/lib/anonymous.js`).refuseProbes(e);
62
66
  const roomId = e.request?.pathValue("room") ?? "";
63
67
  const q = e.requestInfo().query;
64
68
  // Own keys only: "toString" and the like are the object's too (QA BUG-171).
@@ -118,11 +122,13 @@ function searchWhere(text, params) {
118
122
 
119
123
  /**
120
124
  * GET /api/chat/notifiable?rooms=a,b&since=…[&every=a] → other people's messages in `rooms` since `since` that are
121
- * DMs or replies to you, or any message in an `every` room (ANDROID.md §21.2, §24): newest first, `limit` of them. The
125
+ * DMs, replies to you or mentions of you (DESIGN.md §41), or any message in an `every` room (ANDROID.md §21.2, §24): newest first, `limit` of them. The
122
126
  * rooms you can't see are left out.
123
127
  * @param {core.RequestEvent} e
124
128
  */
125
129
  function notifiable(e) {
130
+ // As the records API's (main.pb.js): this page's ?expand mustn't group messages by author (§35).
131
+ require(`${__hooks}/lib/anonymous.js`).refuseProbes(e);
126
132
  const q = e.requestInfo().query;
127
133
  if (!q.since) throw new BadRequestError("Missing since.");
128
134
  const me = e.auth?.id ?? "";
@@ -144,7 +150,7 @@ function notifiable(e) {
144
150
  "created > {:since}",
145
151
  "author != {:me}",
146
152
  "deleted = false",
147
- `(room.kind = "dm" || reply_to.author = {:me}${all})`,
153
+ `(room.kind = "dm" || reply_to.author = {:me} || mentions.id ?= {:me}${all})`,
148
154
  ];
149
155
  return e.json(200, list(e, where, "-created,-id", q, params, rooms));
150
156
  }
@@ -0,0 +1,137 @@
1
+ /// <reference path="../../types/pocketbase.d.ts" />
2
+ // Live messages (docs/PERF.md §7): each message saved or deleted is sent once, by one hook call, to every realtime
3
+ // client subscribed to TOPIC that can see its room, as the clients' rooms and activity need it. Not by PocketBase's
4
+ // own `messages/*` subscriptions: for those it checks the list rule and runs the messages enrich hook (JS, lib/enrich.js)
5
+ // once for each subscriber, and with a hundred people listening every message and reaction cost seconds (PERF.md
6
+ // §6.1). Here the message is expanded once, a forward shows its original once (lib/messages.js showOriginal), and an
7
+ // anonymous room's message is hidden once (lib/anonymous.js hide), with its author's own view beside it.
8
+ //
9
+ // The event is what a `messages/*` subscription with the apps' live options sent: { action, record }, the record with the
10
+ // contract's message fields, expanded with `author` and `forwarded_from`. Who gets it is who that subscription's list rule lets see the message: anyone who can
11
+ // see its room (lib/access.js canSee; tests/integration/access.matrix.test.ts checks they agree). The view rule's
12
+ // other way in, a forward of it in a room you see, isn't one here: such a reader is told of the forward instead
13
+ // (lib/messages.js touches forwards when their original changes), as the apps' list subscriptions always were.
14
+ //
15
+ // Apps ask GET /api/chat/live first; a server from before has no such route (404), and they subscribe as before.
16
+
17
+ const { accessOf, canSee } = require(`${__hooks}/lib/access.js`);
18
+
19
+ const TOPIC = "chat/messages";
20
+ const EXPAND = ["author", "forwarded_from"];
21
+ /** What an event carries: the fields the apps ask the records API for (shared/contract.json, tests/unit/contract.test.ts). */
22
+ const FIELDS =
23
+ "id,room,text,created,updated,edited_at,deleted,files,file_names,file_sources,file_dims,reactions,previews,author,expand.author.id,expand.author.name,expand.author.avatar,expand.author.no_dms,expand.author.instance,reply_to,expand.reply_to.id,expand.reply_to.author,expand.reply_to.text,expand.reply_to.deleted,expand.reply_to.files,expand.reply_to.expand.author.id,expand.reply_to.expand.author.name,forwarded_from,forward_of,expand.forwarded_from.id,expand.forwarded_from.name,mentions";
24
+
25
+ /**
26
+ * `value` (a record as JSON) with only `fields` (PocketBase's `fields` syntax, dotted paths), as the API's `fields` gives it.
27
+ * @param {any} value
28
+ * @param {string} fields
29
+ */
30
+ function pick(value, fields) {
31
+ /** @type {Record<string, any>} */
32
+ const tree = {};
33
+ for (const path of fields.split(",")) {
34
+ let node = tree;
35
+ for (const key of path.split(".")) node = node[key] ??= {};
36
+ }
37
+ /** @param {any} v @param {Record<string, any>} t @returns {any} */
38
+ const walk = (v, t) => {
39
+ if (Array.isArray(v)) return v.map((x) => walk(x, t));
40
+ if (!v || typeof v !== "object" || !Object.keys(t).length) return v;
41
+ /** @type {Record<string, any>} */
42
+ const out = {};
43
+ for (const k of Object.keys(t)) if (k in v) out[k] = walk(v[k], t[k]);
44
+ return out;
45
+ };
46
+ return walk(value, tree);
47
+ }
48
+
49
+ /**
50
+ * Send `record` (a message just saved, or deleted) to the clients listening that can see its room.
51
+ * @param {core.App} app
52
+ * @param {core.Record} record
53
+ * @param {"create" | "update" | "delete"} action
54
+ */
55
+ function send(app, record, action) {
56
+ const clients = app.subscriptionsBroker().clients();
57
+ /** @type {any[]} */
58
+ const listening = [];
59
+ for (const id of Object.keys(clients)) {
60
+ const client = clients[id];
61
+ if (client && !client.isDiscarded() && client.hasSubscription(TOPIC)) listening.push(client);
62
+ }
63
+ if (!listening.length) return;
64
+ let room;
65
+ try {
66
+ room = app.findRecordById("rooms", record.getString("room"));
67
+ } catch {
68
+ return; // the room is gone, and with it everyone's right to see the message
69
+ }
70
+ const access = accessOf(room);
71
+ const base = record.fresh();
72
+ app.expandRecord(base, EXPAND, /** @type {any} */ (null));
73
+ if (action !== "delete") require(`${__hooks}/lib/messages.js`).showOriginal(/** @type {any} */ ({ app, record: base }));
74
+ const anonymous = base.getBool("anonymous");
75
+ const forwardedAnonymous = base.getBool("forwarded_anonymous");
76
+ const author = base.getString("author");
77
+ const from = base.getString("forwarded_from");
78
+
79
+ /** @type {Record<string, string>} */
80
+ const payloads = {};
81
+ /**
82
+ * The event as `userId` sees it: the real author only to the author (and the forward's source only to its writer),
83
+ * as the enrich hook's hide would show it to them.
84
+ * @param {string} key
85
+ * @param {string} userId
86
+ */
87
+ const payload = (key, userId) => {
88
+ if (payloads[key] === undefined) {
89
+ let rec = base;
90
+ if (key !== "real") {
91
+ rec = base.fresh();
92
+ rec.setExpand(base.expand());
93
+ const auth = { id: userId, isSuperuser: () => false };
94
+ require(`${__hooks}/lib/anonymous.js`).hide(/** @type {any} */ ({ app, record: rec, requestInfo: { auth } }));
95
+ }
96
+ payloads[key] = JSON.stringify({ action, record: pick(JSON.parse(JSON.stringify(rec)), FIELDS) });
97
+ }
98
+ return payloads[key];
99
+ };
100
+
101
+ for (const client of listening) {
102
+ /** @type {core.Record | null | undefined} */
103
+ const auth = client.get("auth");
104
+ const superuser = !!auth?.isSuperuser();
105
+ const userId = auth && !superuser ? auth.id : "";
106
+ if (!superuser && !canSee(access, userId)) continue;
107
+ const hidesAuthor = anonymous && author !== "" && author !== userId;
108
+ const hidesFrom = forwardedAnonymous && from !== "" && from !== userId;
109
+ const key = superuser || (!hidesAuthor && !hidesFrom) ? "real" : `${hidesAuthor ? "a" : ""}${hidesFrom ? "f" : ""}`;
110
+ client.send(new SubscriptionMessage({ name: TOPIC, data: payload(key, userId) }));
111
+ }
112
+ }
113
+
114
+ /**
115
+ * send, with a failure logged instead of thrown: the save is committed already.
116
+ * @param {core.App} app
117
+ * @param {core.Record | undefined} record
118
+ * @param {"create" | "update" | "delete"} action
119
+ */
120
+ function sendSafely(app, record, action) {
121
+ if (!record) return;
122
+ try {
123
+ send(app, record, action);
124
+ } catch (err) {
125
+ app.logger().error("live: a message event wasn't sent", "message", record.id, "action", action, "error", String(err));
126
+ }
127
+ }
128
+
129
+ /**
130
+ * GET /api/chat/live: that this server sends messages on TOPIC (apps from before subscribe to `messages/*`).
131
+ * @param {core.RequestEvent} e
132
+ */
133
+ function info(e) {
134
+ return e.json(200, { topic: TOPIC });
135
+ }
136
+
137
+ module.exports = { TOPIC, send, sendSafely, info };
@@ -366,6 +366,10 @@ function beforeMessageUpdateRequest(e) {
366
366
  for (const f of ["reactions", "previews", "file_dims"]) {
367
367
  if (rec.getString(f) !== rec.original().getString(f)) throw fieldError(f, "This field can't be changed.");
368
368
  }
369
+ // Only the hooks set who a message mentions, from its text (§41).
370
+ if (rec.getStringSlice("mentions").join(",") !== rec.original().getStringSlice("mentions").join(",")) {
371
+ throw fieldError("mentions", "This field can't be changed.");
372
+ }
369
373
  }
370
374
 
371
375
  /**
@@ -62,6 +62,8 @@ function setReaction(list, emoji, user, on) {
62
62
  * @param {core.RequestEvent} e
63
63
  */
64
64
  function react(e) {
65
+ // As the records API's (main.pb.js): this page's ?expand mustn't group messages by author (§35).
66
+ require(`${__hooks}/lib/anonymous.js`).refuseProbes(e);
65
67
  const me = e.auth;
66
68
  if (!me) throw new UnauthorizedError("The request requires a logged-in user.");
67
69
  const info = e.requestInfo();