chirkle 0.1.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 (82) hide show
  1. package/README.md +23 -4
  2. package/package.json +2 -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 +104 -27
  19. package/pb_hooks/telegram/api.js +3 -2
  20. package/pb_hooks/telegram/inbound.js +6 -1
  21. package/pb_hooks/telegram/outbound.js +35 -6
  22. package/pb_hooks/telegram/people.js +4 -0
  23. package/pb_hooks/telegram/reactions.js +193 -0
  24. package/pb_hooks/telegram/worker.js +1 -0
  25. package/pb_migrations/1760000043_telegram_reactions.js +21 -0
  26. package/pb_migrations/1760000044_stats.js +70 -0
  27. package/pb_migrations/1760000045_mentions.js +187 -0
  28. package/pb_migrations/1760000046_reserved_handles.js +29 -0
  29. package/pb_public/assets/access-GUDTDXIP.js +2 -0
  30. package/pb_public/assets/access-GUDTDXIP.js.map +7 -0
  31. package/pb_public/assets/app-3WX5JYL2.js +3 -0
  32. package/pb_public/assets/app-3WX5JYL2.js.map +7 -0
  33. package/pb_public/assets/app-WAFKVN2H.css +2 -0
  34. package/pb_public/assets/app-WAFKVN2H.css.map +7 -0
  35. package/pb_public/assets/collections-DHJEOLHW.css +2 -0
  36. package/pb_public/assets/collections-DHJEOLHW.css.map +7 -0
  37. package/pb_public/assets/{emoji-WSTVXAW5.css → emoji-VA2WCEAC.css} +2 -2
  38. package/pb_public/assets/{emoji-WSTVXAW5.css.map → emoji-VA2WCEAC.css.map} +2 -2
  39. package/pb_public/assets/{emoji-picker-QYRX6NYL.js → emoji-picker-65VVVGYW.js} +2 -2
  40. package/pb_public/assets/forward-66PELNWT.js +2 -0
  41. package/pb_public/assets/forward-66PELNWT.js.map +7 -0
  42. package/pb_public/assets/inbox-3FSOPY2T.css +2 -0
  43. package/pb_public/assets/inbox-3FSOPY2T.css.map +7 -0
  44. package/pb_public/assets/inbox-TZJWPRTG.js +2 -0
  45. package/pb_public/assets/inbox-TZJWPRTG.js.map +7 -0
  46. package/pb_public/assets/{lazy-SCCVSUZO.js → lazy-4CXRBHHM.js} +2 -2
  47. package/pb_public/assets/lazy-4CXRBHHM.js.map +7 -0
  48. package/pb_public/assets/login-G7Y44CJ7.js +2 -0
  49. package/pb_public/assets/login-G7Y44CJ7.js.map +7 -0
  50. package/pb_public/assets/{media-L3EYTHKT.css → media-7TCBG7WM.css} +2 -2
  51. package/pb_public/assets/{media-L3EYTHKT.css.map → media-7TCBG7WM.css.map} +2 -2
  52. package/pb_public/assets/media-FPRU2QH5.js +2 -0
  53. package/pb_public/assets/media-FPRU2QH5.js.map +7 -0
  54. package/pb_public/assets/mention-suggest-R7MXUH6R.js +2 -0
  55. package/pb_public/assets/mention-suggest-R7MXUH6R.js.map +7 -0
  56. package/pb_public/assets/notify-RQ6ZLR46.js +2 -0
  57. package/pb_public/assets/notify-RQ6ZLR46.js.map +7 -0
  58. package/pb_public/assets/profile-2CNVT2KX.js +2 -0
  59. package/pb_public/assets/profile-2CNVT2KX.js.map +7 -0
  60. package/pb_public/assets/stats-A2TBRUI6.css +2 -0
  61. package/pb_public/assets/stats-A2TBRUI6.css.map +7 -0
  62. package/pb_public/assets/stats-JX52AQCO.js +2 -0
  63. package/pb_public/assets/stats-JX52AQCO.js.map +7 -0
  64. package/pb_public/assets/user-search-7GNEIXMN.js +2 -0
  65. package/pb_public/assets/user-search-7GNEIXMN.js.map +7 -0
  66. package/pb_public/index.html +3 -3
  67. package/pb_public/stats.html +25 -0
  68. package/pb_public/sw.js +1 -1
  69. package/pb_public/assets/access-ALBW2MT2.js +0 -2
  70. package/pb_public/assets/access-ALBW2MT2.js.map +0 -7
  71. package/pb_public/assets/app-ECR34OBK.css +0 -2
  72. package/pb_public/assets/app-ECR34OBK.css.map +0 -7
  73. package/pb_public/assets/app-SILEBEXB.js +0 -3
  74. package/pb_public/assets/app-SILEBEXB.js.map +0 -7
  75. package/pb_public/assets/collections-VEOIOCAW.css +0 -2
  76. package/pb_public/assets/collections-VEOIOCAW.css.map +0 -7
  77. package/pb_public/assets/lazy-SCCVSUZO.js.map +0 -7
  78. package/pb_public/assets/media-DH7ECZSF.js +0 -2
  79. package/pb_public/assets/media-DH7ECZSF.js.map +0 -7
  80. package/pb_public/assets/notify-L6GERFNO.js +0 -2
  81. package/pb_public/assets/notify-L6GERFNO.js.map +0 -7
  82. /package/pb_public/assets/{emoji-picker-QYRX6NYL.js.map → emoji-picker-65VVVGYW.js.map} +0 -0
@@ -0,0 +1,337 @@
1
+ /// <reference path="../../types/pocketbase.d.ts" />
2
+ // Handles and mentions (DESIGN.md §41): every account has a handle (`users.handle`, a–z 0–9 _, 3–24, unique), which
3
+ // "@handle" in a message names. The hooks resolve a message's mentions from its text (`messages.mentions`: those named
4
+ // who can see its room); GET /api/chat/mentionable suggests people as "@" is typed.
5
+
6
+ const { accessOf, canSee, visibleRoom } = require(`${__hooks}/lib/access.js`);
7
+ const { fieldError } = require(`${__hooks}/lib/records.js`);
8
+ const { nameKey } = require(`${__hooks}/lib/text.js`);
9
+
10
+ const HANDLE_MIN = 3;
11
+ const HANDLE_MAX = 24;
12
+ const HANDLE = /^[a-z0-9_]{3,24}$/;
13
+ /** Kept for what may one day mean everyone in a room. */
14
+ const RESERVED = new Set(["all", "everyone", "here", "room", "channel"]);
15
+ /** Most people one message mentions. */
16
+ const MAX_MENTIONS = 20;
17
+ /** Most people GET /api/chat/mentionable suggests. */
18
+ const SUGGESTIONS = 8;
19
+
20
+ /**
21
+ * "@handle" in a message: after the start or anything but a letter, digit, "_", "@", "." or "/" (an email, a path, a
22
+ * linked instance's "ann@b.example"), and not followed by one of those. Keep in sync with web/src/lib/mentions.ts and
23
+ * the app's lib/Mentions.kt (shared/vectors/mentions.json).
24
+ */
25
+ const MENTION = /(^|[^A-Za-z0-9_@./])@([A-Za-z0-9_]{3,24})(?![A-Za-z0-9_@])/g;
26
+
27
+ /** @type {Record<string, string>} */
28
+ const CYRILLIC = {
29
+ а: "a",
30
+ б: "b",
31
+ в: "v",
32
+ г: "g",
33
+ д: "d",
34
+ е: "e",
35
+ ё: "e",
36
+ ж: "zh",
37
+ з: "z",
38
+ и: "i",
39
+ й: "y",
40
+ к: "k",
41
+ л: "l",
42
+ м: "m",
43
+ н: "n",
44
+ о: "o",
45
+ п: "p",
46
+ р: "r",
47
+ с: "s",
48
+ т: "t",
49
+ у: "u",
50
+ ф: "f",
51
+ х: "kh",
52
+ ц: "ts",
53
+ ч: "ch",
54
+ ш: "sh",
55
+ щ: "shch",
56
+ ъ: "",
57
+ ы: "y",
58
+ ь: "",
59
+ э: "e",
60
+ ю: "yu",
61
+ я: "ya",
62
+ і: "i",
63
+ ї: "yi",
64
+ є: "ye",
65
+ ґ: "g",
66
+ ў: "u",
67
+ };
68
+
69
+ /**
70
+ * Letters NFKD leaves whole (Ł, Ø, Æ, Þ…) and Greek, spelled in Latin: "Łukasz" was "ukasz", "Ørjan" "rjan" (QA BUG-255).
71
+ * @type {Record<string, string>}
72
+ */
73
+ const LATIN = {
74
+ ł: "l",
75
+ ø: "o",
76
+ æ: "ae",
77
+ œ: "oe",
78
+ đ: "d",
79
+ ð: "d",
80
+ þ: "th",
81
+ ı: "i",
82
+ ħ: "h",
83
+ ŧ: "t",
84
+ ŋ: "ng",
85
+ α: "a",
86
+ β: "v",
87
+ γ: "g",
88
+ δ: "d",
89
+ ε: "e",
90
+ ζ: "z",
91
+ η: "i",
92
+ θ: "th",
93
+ ι: "i",
94
+ κ: "k",
95
+ λ: "l",
96
+ μ: "m",
97
+ ν: "n",
98
+ ξ: "x",
99
+ ο: "o",
100
+ π: "p",
101
+ ρ: "r",
102
+ σ: "s",
103
+ ς: "s",
104
+ τ: "t",
105
+ υ: "y",
106
+ φ: "f",
107
+ χ: "ch",
108
+ ψ: "ps",
109
+ ω: "o",
110
+ };
111
+
112
+ /**
113
+ * A handle made from a display name: Latin letters without their accents, Cyrillic spelled in Latin, anything else
114
+ * an "_" (at most 20, so a number fits after it). Keep in sync with pb_migrations/1760000045_mentions.js.
115
+ * @param {string} name
116
+ */
117
+ function handleFrom(name) {
118
+ let s = [...name.toLowerCase()].map((c) => CYRILLIC[c] ?? c).join("");
119
+ if (typeof s.normalize === "function") s = s.normalize("NFKD").replace(/[̀-ͯ]/g, "");
120
+ s = s
121
+ .replace(/ß/g, "ss")
122
+ .replace(/[\u0080-\uffff]/g, (c) => LATIN[c] ?? c)
123
+ .replace(/[^a-z0-9]+/g, "_")
124
+ .replace(/^_+|_+$/g, "")
125
+ .slice(0, 20)
126
+ .replace(/_+$/, "");
127
+ if (s.length < HANDLE_MIN) s = s ? `${s}_user` : "user";
128
+ return s;
129
+ }
130
+
131
+ /**
132
+ * Is `handle` someone else's than user `id`'s?
133
+ * @param {core.App} app
134
+ * @param {string} handle
135
+ * @param {string} id
136
+ */
137
+ function taken(app, handle, id) {
138
+ if (RESERVED.has(handle)) return true;
139
+ try {
140
+ app.findFirstRecordByFilter("users", "handle = {:h} && id != {:id}", { h: handle, id });
141
+ return true;
142
+ } catch {
143
+ return false;
144
+ }
145
+ }
146
+
147
+ /**
148
+ * The first free handle for `base` ("ann", then "ann2", "ann3"…).
149
+ * @param {core.App} app
150
+ * @param {string} base
151
+ * @param {string} id the user's own (their handle isn't taken from them)
152
+ */
153
+ function freeHandle(app, base, id) {
154
+ for (let n = 1; n < 10000; n++) {
155
+ const tail = n > 1 ? String(n) : "";
156
+ const candidate = `${base.slice(0, HANDLE_MAX - tail.length)}${tail}`;
157
+ if (!taken(app, candidate, id)) return candidate;
158
+ }
159
+ return `${base.slice(0, HANDLE_MAX - 10)}_${$security.randomStringWithAlphabet(9, "abcdefghijklmnopqrstuvwxyz0123456789")}`;
160
+ }
161
+
162
+ /**
163
+ * A handle as typed: no leading "@", in lower case, trimmed.
164
+ * @param {string} raw
165
+ */
166
+ const normalHandle = (raw) => raw.trim().replace(/^@/, "").toLowerCase();
167
+
168
+ /**
169
+ * users create/update (lib/users.js beforeUserSave): a new account without a handle gets one from its name; one typed
170
+ * is checked (allowed characters, length, not someone else's). An update that keeps it keeps it unchecked.
171
+ * @param {core.App} app
172
+ * @param {core.Record} rec
173
+ */
174
+ function setHandle(app, rec) {
175
+ const typed = normalHandle(rec.getString("handle"));
176
+ if (!rec.isNew() && typed === rec.original().getString("handle")) {
177
+ rec.set("handle", typed);
178
+ return;
179
+ }
180
+ if (typed === "") {
181
+ if (!rec.isNew() && rec.original().getString("handle") !== "") throw fieldError("handle", "Cannot be blank.", "validation_required");
182
+ rec.set("handle", freeHandle(app, handleFrom(rec.getString("name")), rec.id));
183
+ return;
184
+ }
185
+ if (!HANDLE.test(typed)) {
186
+ throw fieldError("handle", `Use ${HANDLE_MIN} to ${HANDLE_MAX} letters a–z, digits or underscores.`);
187
+ }
188
+ if (taken(app, typed, rec.id)) throw fieldError("handle", "This handle is taken. Choose another one.", "validation_not_unique");
189
+ rec.set("handle", typed);
190
+ }
191
+
192
+ /**
193
+ * The handles "@"-named in `text`, in lower case, each once, at most MAX_MENTIONS.
194
+ * @param {string} text
195
+ */
196
+ function handlesIn(text) {
197
+ const out = new Set();
198
+ for (const m of text.matchAll(MENTION)) {
199
+ out.add(m[2].toLowerCase());
200
+ if (out.size >= MAX_MENTIONS) break;
201
+ }
202
+ return [...out];
203
+ }
204
+
205
+ /**
206
+ * Who message `rec` mentions: the people its text names who can see its room, but not its author.
207
+ * @param {core.App} app
208
+ * @param {core.Record} rec
209
+ * @returns {string[]} user ids
210
+ */
211
+ function mentionsOf(app, rec) {
212
+ const handles = handlesIn(rec.getString("text"));
213
+ if (!handles.length) return [];
214
+ let room;
215
+ try {
216
+ room = app.findRecordById("rooms", rec.getString("room"));
217
+ } catch {
218
+ return [];
219
+ }
220
+ const access = accessOf(room);
221
+ const params = Object.fromEntries(handles.map((h, i) => [`h${i}`, h]));
222
+ const found = app.findRecordsByFilter("users", handles.map((_, i) => `handle = {:h${i}}`).join(" || "), "", MAX_MENTIONS, 0, params);
223
+ const author = rec.getString("author");
224
+ const byHandle = new Map(found.flatMap((u) => (u ? [[u.getString("handle"), u.id]] : [])));
225
+ return handles.flatMap((h) => {
226
+ const id = byHandle.get(h);
227
+ return id && id !== author && canSee(access, id) ? [id] : [];
228
+ });
229
+ }
230
+
231
+ /**
232
+ * messages create and update (main.pb.js): `mentions` from the text, unless the save is a linked instance's (§33),
233
+ * which names the people itself (federation/messages.js). A forward mentions no one: its words are the original's.
234
+ * @param {core.App} app
235
+ * @param {core.Record} rec
236
+ * @param {boolean} fromPeer
237
+ */
238
+ function setMentions(app, rec, fromPeer) {
239
+ if (fromPeer) return;
240
+ if (rec.getString("forwarded_from") !== "" || rec.getBool("deleted") || rec.getString("author") === "") {
241
+ rec.set("mentions", []);
242
+ return;
243
+ }
244
+ // Unchanged text keeps them (or what PocketBase left of them, a mentioned account deleted for good). The update
245
+ // request hook refuses any other change.
246
+ if (!rec.isNew() && rec.getString("text") === rec.original().getString("text")) return;
247
+ rec.set("mentions", mentionsOf(app, rec));
248
+ }
249
+
250
+ /** Messages looked at for who has written in a room lately. */
251
+ const RECENT = 300;
252
+
253
+ /**
254
+ * GET /api/chat/mentionable?room=&q= → up to SUGGESTIONS people who can see `room` whose handle or name starts with
255
+ * (or, failing enough of those, contains) `q`, as the composer's "@" suggestions: [{ id, name, handle, avatar,
256
+ * instance }]. Those who wrote there lately first (not in an anonymous room, where that would say who they are), the
257
+ * caller never. An empty `q` lists those recent writers, or a private room's members.
258
+ * @param {core.RequestEvent} e
259
+ */
260
+ function mentionable(e) {
261
+ const me = e.auth;
262
+ if (!me) throw new UnauthorizedError("The request requires a logged-in user.");
263
+ const q = e.requestInfo().query;
264
+ const room = visibleRoom(e.app, typeof q.room === "string" ? q.room : "", me.id);
265
+ if (!room) throw new NotFoundError("The room doesn't exist.");
266
+ const typed = normalHandle(typeof q.q === "string" ? q.q : "").slice(0, 32);
267
+ const key = nameKey(typed);
268
+ const access = accessOf(room);
269
+
270
+ /** @type {string[]} */
271
+ let recent = [];
272
+ if (!room.getBool("anonymous")) {
273
+ const rows = arrayOf(new DynamicModel({ author: "" }));
274
+ e.app
275
+ .db()
276
+ .newQuery(
277
+ `SELECT author FROM (SELECT author, created FROM messages WHERE room = {:room} AND author != '' AND deleted = FALSE ORDER BY created DESC LIMIT ${RECENT}) GROUP BY author ORDER BY MAX(created) DESC LIMIT 50`,
278
+ )
279
+ .bind({ room: room.id })
280
+ .all(rows);
281
+ recent = rows.map((r) => r.author);
282
+ }
283
+ const rank = new Map(recent.map((id, i) => [id, i]));
284
+
285
+ /** @type {core.Record[]} */
286
+ let pool = [];
287
+ const members = access.visibility === "private" ? [...new Set([access.createdBy, ...access.members])].filter(Boolean) : [];
288
+ if (members.length) {
289
+ pool = e.app.findRecordsByIds("users", members).filter((u) => !!u);
290
+ } else if (typed) {
291
+ const like = { h: `${typed.replace(/[%_\\]/g, "\\$&")}%`, k: `%${key.replace(/[%_\\]/g, "\\$&")}%` };
292
+ const rows = arrayOf(new DynamicModel({ id: "" }));
293
+ e.app
294
+ .db()
295
+ .newQuery(
296
+ "SELECT id FROM users WHERE banned = FALSE AND (handle LIKE {:h} ESCAPE '\\' OR name_key LIKE {:k} ESCAPE '\\') ORDER BY handle LIMIT 200",
297
+ )
298
+ .bind(like)
299
+ .all(rows);
300
+ // With those who wrote lately, whom a short query may match among many more.
301
+ pool = e.app.findRecordsByIds("users", [...new Set([...recent, ...rows.map((r) => r.id)])]).filter((u) => !!u);
302
+ } else if (recent.length) {
303
+ pool = e.app.findRecordsByIds("users", recent).filter((u) => !!u);
304
+ }
305
+
306
+ /** @param {core.Record} u */
307
+ const score = (u) => {
308
+ const handle = u.getString("handle");
309
+ const name = nameKey(u.getString("name"));
310
+ if (!typed) return 0;
311
+ if (handle.startsWith(typed)) return 0;
312
+ if (name.startsWith(key) || name.split(/[\s_\-.]+/).some((/** @type {string} */ w) => w.startsWith(key))) return 1;
313
+ if (handle.includes(typed) || name.includes(key)) return 2;
314
+ return 3;
315
+ };
316
+ const found = pool
317
+ .filter((u) => u.id !== me.id && u.getString("handle") !== "" && !u.getBool("banned") && canSee(access, u.id) && score(u) < 3)
318
+ .sort(
319
+ (a, b) =>
320
+ score(a) - score(b) ||
321
+ (rank.get(a.id) ?? 1e9) - (rank.get(b.id) ?? 1e9) ||
322
+ a.getString("handle").localeCompare(b.getString("handle")),
323
+ )
324
+ .slice(0, SUGGESTIONS);
325
+ return e.json(
326
+ 200,
327
+ found.map((u) => ({
328
+ id: u.id,
329
+ name: u.getString("name"),
330
+ handle: u.getString("handle"),
331
+ avatar: u.getString("avatar"),
332
+ instance: u.getString("instance"),
333
+ })),
334
+ );
335
+ }
336
+
337
+ module.exports = { HANDLE, MENTION, handleFrom, freeHandle, setHandle, handlesIn, mentionsOf, setMentions, mentionable, normalHandle };
@@ -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 };