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,110 @@
1
+ /// <reference path="../../types/pocketbase.d.ts" />
2
+ // Reactions (DESIGN.md §20): POST /api/chat/reactions adds or removes one of the caller's reactions on a message.
3
+ // They live on the message itself (`messages.reactions`), so they reach clients with it: pages, realtime updates and
4
+ // the reconnect refetch (§7.5) need nothing new.
5
+
6
+ const { isReactionEmoji } = require(`${__hooks}/lib/emoji.js`);
7
+ const { isService } = require(`${__hooks}/lib/messages.js`);
8
+
9
+ /**
10
+ * @typedef {{ emoji: string, users: string[] }} Reaction
11
+ */
12
+
13
+ /**
14
+ * @param {string} field
15
+ * @param {string} message
16
+ */
17
+ const badRequest = (field, message) =>
18
+ new BadRequestError("Failed to update the reaction.", { [field]: new ValidationError("validation_invalid_value", message) });
19
+
20
+ /**
21
+ * A message's reactions, in the order they were first added. Anything malformed is dropped.
22
+ * @param {core.Record} rec
23
+ * @returns {Reaction[]}
24
+ */
25
+ function reactionsOf(rec) {
26
+ /** @type {unknown} */
27
+ let raw;
28
+ try {
29
+ raw = JSON.parse(rec.getString("reactions") || "[]");
30
+ } catch {
31
+ return [];
32
+ }
33
+ if (!Array.isArray(raw)) return [];
34
+ return raw
35
+ .filter((r) => r && typeof r.emoji === "string" && Array.isArray(r.users))
36
+ .map((r) => ({ emoji: r.emoji, users: r.users.filter((/** @type {unknown} */ u) => typeof u === "string") }))
37
+ .filter((r) => r.users.length > 0);
38
+ }
39
+
40
+ /**
41
+ * `list` with `user`'s `emoji` reaction added (`on`) or removed; null when that changes nothing. A new emoji goes
42
+ * last, and an emoji nobody uses any more goes away.
43
+ * @param {Reaction[]} list
44
+ * @param {string} emoji
45
+ * @param {string} user
46
+ * @param {boolean} on
47
+ * @returns {Reaction[] | null}
48
+ */
49
+ function setReaction(list, emoji, user, on) {
50
+ const r = list.find((x) => x.emoji === emoji);
51
+ const has = !!r && r.users.includes(user);
52
+ if (has === on) return null;
53
+ if (on) return r ? list.map((x) => (x === r ? { emoji, users: [...x.users, user] } : x)) : [...list, { emoji, users: [user] }];
54
+ return list.map((x) => (x === r ? { emoji, users: x.users.filter((u) => u !== user) } : x)).filter((x) => x.users.length > 0);
55
+ }
56
+
57
+ /**
58
+ * POST /api/chat/reactions { message, emoji, on } → the message, as GET /api/collections/messages/records/:id
59
+ * answers it (the same ?expand and ?fields apply): the caller's `emoji` reaction on
60
+ * `message` is there (`on: true`) or not (`on: false`). Idempotent, so a retry or a double click can't flip it back.
61
+ * Only on messages the caller can see, that aren't deleted, in rooms that aren't archived.
62
+ * @param {core.RequestEvent} e
63
+ */
64
+ function react(e) {
65
+ const me = e.auth;
66
+ if (!me) throw new UnauthorizedError("The request requires a logged-in user.");
67
+ const info = e.requestInfo();
68
+ const body = /** @type {Record<string, unknown>} */ (info.body);
69
+ const id = typeof body.message === "string" ? body.message : "";
70
+ const emoji = body.emoji;
71
+ const on = body.on;
72
+ if (!isReactionEmoji(emoji)) throw badRequest("emoji", "Choose one of the offered emoji.");
73
+ if (typeof on !== "boolean") throw badRequest("on", "Must be true or false.");
74
+
75
+ // Someone else's DM gets the same answer as a message that doesn't exist.
76
+ const notFound = () => new NotFoundError("The message doesn't exist.");
77
+ let msg;
78
+ try {
79
+ msg = e.app.findRecordById("messages", id);
80
+ } catch {
81
+ throw notFound();
82
+ }
83
+ // The list rule: seen in its room. The view rule would also let the readers of a forward react to its original (§21.3).
84
+ const rule = e.app.findCollectionByNameOrId("messages").listRule;
85
+ if (rule === null || rule === undefined || !e.app.canAccessRecord(msg, info, rule)) throw notFound();
86
+ if (isService(msg)) throw badRequest("message", "Service messages take no reactions.");
87
+
88
+ // Read and write in one transaction: two people reacting at once both count. (Errors are thrown after it, so
89
+ // they keep their status.)
90
+ let problem = "";
91
+ e.app.runInTransaction((tx) => {
92
+ const rec = tx.findRecordById("messages", id);
93
+ msg = rec;
94
+ if (rec.getBool("deleted")) problem = "That message was deleted.";
95
+ else if (tx.findRecordById("rooms", rec.getString("room")).getBool("archived")) problem = "This room is archived and read-only.";
96
+ if (problem) return;
97
+ const next = setReaction(reactionsOf(rec), /** @type {string} */ (emoji), me.id, on);
98
+ if (!next) return;
99
+ rec.set("reactions", next);
100
+ tx.save(rec);
101
+ });
102
+ if (problem) throw badRequest("message", problem);
103
+ // The whole message, not just its reactions: a copy the client patched with a newer `updated` would hide
104
+ // changes it hasn't heard of yet (an edit while its realtime connection was down).
105
+ msg.set("reactions", reactionsOf(msg));
106
+ $apis.enrichRecord(e, msg);
107
+ return e.json(200, msg);
108
+ }
109
+
110
+ module.exports = { react, reactionsOf, setReaction };
@@ -0,0 +1,181 @@
1
+ /// <reference path="../../types/pocketbase.d.ts" />
2
+ // Unread counts (DESIGN.md §18): GET /api/chat/unread and POST /api/chat/reads.
3
+
4
+ const { SEES_SQL, visibleRoom } = require(`${__hooks}/lib/access.js`);
5
+
6
+ /**
7
+ * Unread messages per room the caller can see (§23.1): other people's, not deleted, newer than the caller's read position
8
+ * (or their signup, for a room they never opened). One correlated count per room, so each one is a range scan on
9
+ * idx_messages_room_created, stopped at UNREAD_CAP (the badge shows "99+" past 99, so more is never needed).
10
+ * Hidden and archived rooms are counted too; the client doesn't show those (§18.4).
11
+ */
12
+ const UNREAD_CAP = 100;
13
+ const UNREAD_SQL = `
14
+ SELECT room, n FROM (
15
+ SELECT r.id AS room, (
16
+ SELECT COUNT(*) FROM (
17
+ SELECT 1 FROM messages m
18
+ WHERE m.room = r.id
19
+ AND m.created > MAX(COALESCE((SELECT rr.last_read_at FROM room_reads rr WHERE rr.user = {:me} AND rr.room = r.id), ''), {:since})
20
+ AND m.author != {:me}
21
+ AND m.deleted = FALSE
22
+ LIMIT ${UNREAD_CAP}
23
+ )
24
+ ) AS n
25
+ FROM rooms r
26
+ WHERE ${SEES_SQL}
27
+ ) WHERE n > 0`;
28
+
29
+ /** How far back GET /api/chat/unread lists the messages its counts already account for (QA BUG-106). */
30
+ const ACCOUNTED_MS = 30_000;
31
+
32
+ /**
33
+ * UNREAD_SQL's rows (`id` "") and, in the same statement so from the same snapshot, the ids of other people's
34
+ * messages in the rooms the caller sees created since {:from} (`room` ""): whatever its read position, the counts
35
+ * account for each of them. Their live events arrive late (or during the request), so the client skips those instead
36
+ * of guessing from `created`, which says nothing about when a message was committed (QA BUG-106). CROSS JOIN keeps
37
+ * rooms the outer loop (SQLite doesn't reorder it), so each room is a range scan on idx_messages_room_created, not a
38
+ * scan of every message (an integration test pins the plan).
39
+ */
40
+ const COUNTS_SQL = `
41
+ SELECT room, n, '' AS id FROM (${UNREAD_SQL})
42
+ UNION ALL
43
+ SELECT * FROM (
44
+ SELECT '' AS room, 0 AS n, m.id AS id FROM rooms r CROSS JOIN messages m ON m.room = r.id
45
+ WHERE ${SEES_SQL}
46
+ AND m.created > {:from}
47
+ AND m.author != {:me}
48
+ LIMIT 1000
49
+ )`;
50
+
51
+ /** The oldest unread message in one room, by the same rule as UNREAD_SQL (§18.2). */
52
+ const FIRST_UNREAD_SQL = `
53
+ SELECT m.id, m.created FROM messages m
54
+ WHERE m.room = {:room}
55
+ AND m.created > MAX(COALESCE((SELECT rr.last_read_at FROM room_reads rr WHERE rr.user = {:me} AND rr.room = {:room}), ''), {:since})
56
+ AND m.author != {:me}
57
+ AND m.deleted = FALSE
58
+ ORDER BY m.created, m.id
59
+ LIMIT 1`;
60
+
61
+ /** @param {core.RequestEvent} e */
62
+ function me(e) {
63
+ if (!e.auth) throw new UnauthorizedError("The request requires a logged-in user.");
64
+ return e.auth;
65
+ }
66
+
67
+ /** @param {string} message */
68
+ const badRequest = (message) =>
69
+ new BadRequestError("Failed to mark the room as read.", { at: new ValidationError("validation_invalid_value", message) });
70
+
71
+ /**
72
+ * GET /api/chat/unread → { at, rooms: { "<roomId>": count }, ids } for every room with unread messages (at most
73
+ * UNREAD_CAP each). `at` is when the counts were taken. `ids` are the recent messages (ACCOUNTED_SQL) the counts
74
+ * account for: the client adds the live ones it gets that aren't among them, and only those (§18.3, QA BUG-106).
75
+ * @param {core.RequestEvent} e
76
+ */
77
+ function unread(e) {
78
+ const user = me(e);
79
+ const at = new DateTime().string();
80
+ const rows = arrayOf(new DynamicModel({ room: "", n: 0, id: "" }));
81
+ e.app
82
+ .db()
83
+ .newQuery(COUNTS_SQL)
84
+ // {:from} in PocketBase's format, "2006-01-02 15:04:05.000Z".
85
+ .bind({ me: user.id, since: user.getString("created"), from: new Date(Date.now() - ACCOUNTED_MS).toISOString().replace("T", " ") })
86
+ .all(rows);
87
+ /** @type {Record<string, number>} */
88
+ const out = {};
89
+ /** @type {string[]} */
90
+ const ids = [];
91
+ for (const row of rows) {
92
+ if (row.id) ids.push(row.id);
93
+ else out[row.room] = row.n;
94
+ }
95
+ return e.json(200, { at, rooms: out, ids });
96
+ }
97
+
98
+ /**
99
+ * GET /api/chat/unread/{room} → { id, created } of the oldest message in `room` that is unread for the caller, or
100
+ * { id: "", created: "" } when there is none. The room view opens there (§18.5).
101
+ * @param {core.RequestEvent} e
102
+ */
103
+ function firstUnread(e) {
104
+ const user = me(e);
105
+ const roomId = e.request?.pathValue("room") ?? "";
106
+ if (!visibleRoom(e.app, roomId, user.id)) throw new NotFoundError("The room doesn't exist.");
107
+ const row = new DynamicModel({ id: "", created: "" });
108
+ try {
109
+ e.app
110
+ .db()
111
+ .newQuery(FIRST_UNREAD_SQL)
112
+ .bind({ me: user.id, room: roomId, since: user.getString("created") })
113
+ .one(row);
114
+ } catch {
115
+ // No rows: nothing unread.
116
+ }
117
+ return e.json(200, { id: row.id, created: row.created });
118
+ }
119
+
120
+ /**
121
+ * @param {core.App} app
122
+ * @param {string} user
123
+ * @param {string} room
124
+ */
125
+ function findRead(app, user, room) {
126
+ try {
127
+ return app.findFirstRecordByFilter("room_reads", "user = {:user} && room = {:room}", { user, room });
128
+ } catch {
129
+ return null;
130
+ }
131
+ }
132
+
133
+ /**
134
+ * POST /api/chat/reads { room, at? }: the caller has read `room` up to `at` (a message's `created`; default now).
135
+ * Never moves the read position back, and never past now. Idempotent.
136
+ * @param {core.RequestEvent} e
137
+ */
138
+ function markRead(e) {
139
+ const user = me(e);
140
+ const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body);
141
+ const roomId = typeof body.room === "string" ? body.room : "";
142
+ // Someone else's DM (or private room) gets the same answer as a room that doesn't exist.
143
+ if (!roomId || !visibleRoom(e.app, roomId, user.id)) throw new NotFoundError("The room doesn't exist.");
144
+
145
+ const now = new DateTime();
146
+ let at = now;
147
+ if (body.at !== undefined) {
148
+ // "" too: DateTime("") would be now, which a client sending a message's `created` never means.
149
+ if (typeof body.at !== "string" || body.at === "") throw badRequest("Must be a date.");
150
+ try {
151
+ at = new DateTime(body.at);
152
+ } catch {
153
+ throw badRequest("Must be a date.");
154
+ }
155
+ if (at.isZero()) throw badRequest("Must be a date.");
156
+ if (at.after(now)) at = now;
157
+ }
158
+
159
+ let row = findRead(e.app, user.id, roomId);
160
+ if (!row) {
161
+ const created = new Record(e.app.findCollectionByNameOrId("room_reads"));
162
+ created.set("user", user.id);
163
+ created.set("room", roomId);
164
+ created.set("last_read_at", at);
165
+ try {
166
+ e.app.save(created);
167
+ return e.json(200, { room: roomId, last_read_at: created.getString("last_read_at") });
168
+ } catch (err) {
169
+ // Lost a race with another tab: the unique (user, room) index kept it to one row. Update that one.
170
+ row = findRead(e.app, user.id, roomId);
171
+ if (!row) throw err;
172
+ }
173
+ }
174
+ if (at.after(row.getDateTime("last_read_at"))) {
175
+ row.set("last_read_at", at);
176
+ e.app.save(row);
177
+ }
178
+ return e.json(200, { room: roomId, last_read_at: row.getString("last_read_at") });
179
+ }
180
+
181
+ module.exports = { unread, firstUnread, markRead };
@@ -0,0 +1,77 @@
1
+ /// <reference path="../../types/pocketbase.d.ts" />
2
+ // Record helpers shared by the users, rooms and messages hooks: validation errors, names, uploaded file names.
3
+
4
+ const { clipFileName, isBlank, nameKey, tidy, unescapeUploadName } = require(`${__hooks}/lib/text.js`);
5
+
6
+ /**
7
+ * @param {string} field
8
+ * @param {string} message
9
+ * @param {string} [code]
10
+ */
11
+ function fieldError(field, message, code = "validation_invalid_value") {
12
+ return new BadRequestError("Failed to save record.", {
13
+ [field]: new ValidationError(code, message),
14
+ });
15
+ }
16
+
17
+ /**
18
+ * The event's record. PocketBase always sets it in record hooks; the generated types mark it optional (a Go pointer).
19
+ * @param {{ record?: core.Record | undefined }} e
20
+ */
21
+ function recordOf(e) {
22
+ if (!e.record) throw new Error("record hook called without a record");
23
+ return e.record;
24
+ }
25
+
26
+ /**
27
+ * Clean a display name or room name in place: drop invisible/bidi characters, trim, reject if nothing visible.
28
+ * @param {core.Record} record
29
+ */
30
+ function cleanName(record) {
31
+ const name = tidy(record.getString("name"));
32
+ record.set("name", name);
33
+ // Empty is left to the field's `required` rule (same message as before); only-invisible is caught here.
34
+ if (name !== "" && isBlank(name)) throw fieldError("name", "Cannot be blank.");
35
+ }
36
+
37
+ /**
38
+ * Set `name_key` from the (cleaned) name and enforce case-insensitive (Unicode) uniqueness within `collection`.
39
+ * The unique index on name_key backs this up against races.
40
+ * @param {core.App} app
41
+ * @param {string} collection
42
+ * @param {core.Record} rec
43
+ * @param {string} taken the error message when another record has the name
44
+ */
45
+ function setNameKey(app, collection, rec, taken) {
46
+ const key = nameKey(rec.getString("name"));
47
+ rec.set("name_key", key);
48
+ if (key === "") return; // `required` on name reports it
49
+ let clash = null;
50
+ try {
51
+ clash = app.findFirstRecordByFilter(collection, "name_key = {:key} && id != {:id}", { key, id: rec.id });
52
+ } catch {
53
+ clash = null; // no such record
54
+ }
55
+ if (clash) throw fieldError("name", taken, "validation_not_unique");
56
+ }
57
+
58
+ /**
59
+ * Original names of this request's uploads in `field`, keyed by stored name (QA BUG-28). Cleaned like display
60
+ * names, so bidi overrides can't disguise a file ("invoice‮fdp.exe"), and capped in length with the extension
61
+ * kept. The upload itself gets the same name, so PocketBase never has to cut it (QA BUG-35).
62
+ * @param {core.Record} record
63
+ * @param {string} field
64
+ */
65
+ function originalNames(record, field) {
66
+ /** @type {Record<string, string>} */
67
+ const names = {};
68
+ for (const f of record.getUnsavedFiles(field)) {
69
+ if (!f) continue;
70
+ const original = clipFileName(tidy(unescapeUploadName(f.originalName)));
71
+ f.originalName = original || f.name;
72
+ if (original) names[f.name] = original;
73
+ }
74
+ return names;
75
+ }
76
+
77
+ module.exports = { fieldError, recordOf, cleanName, setNameKey, originalNames };
@@ -0,0 +1,148 @@
1
+ /// <reference path="../../types/pocketbase.d.ts" />
2
+ // rooms hooks (DESIGN.md §5.2, §16, §23): names, DM fields, members, archive stamps.
3
+
4
+ const { cleanName, fieldError, recordOf, setNameKey } = require(`${__hooks}/lib/records.js`);
5
+ const { stripHashes } = require(`${__hooks}/lib/text.js`);
6
+
7
+ /** @param {core.Record} room */
8
+ const isDm = (room) => room.getString("kind") === "dm";
9
+
10
+ /**
11
+ * rooms create/update: clean the name and check it is unique.
12
+ * @param {core.App} app
13
+ * @param {core.Record} rec
14
+ */
15
+ function setRoomKey(app, rec) {
16
+ cleanName(rec);
17
+ rec.set("name", stripHashes(rec.getString("name")));
18
+ setNameKey(app, "rooms", rec, "Value must be unique.");
19
+ }
20
+
21
+ /**
22
+ * A public room needs a (unique) name; a DM has none (its title is the other member's name, §16.1).
23
+ * @param {core.App} app
24
+ * @param {core.Record} rec
25
+ */
26
+ function setRoomName(app, rec) {
27
+ if (isDm(rec)) {
28
+ rec.set("name", "");
29
+ rec.set("name_key", "");
30
+ return;
31
+ }
32
+ setRoomKey(app, rec);
33
+ if (rec.getString("name") === "") throw fieldError("name", "Cannot be blank.", "validation_required");
34
+ }
35
+
36
+ /**
37
+ * Who is in the room (§23.1): a DM's two members never change. A private room lists its creator and the people they
38
+ * added, each once; other rooms list nobody (their members were only for while they were private).
39
+ * @param {core.Record} rec
40
+ */
41
+ function setMembers(rec) {
42
+ if (isDm(rec)) {
43
+ rec.set("visibility", "private");
44
+ return;
45
+ }
46
+ if (!rec.getString("visibility")) rec.set("visibility", "public");
47
+ if (rec.getString("visibility") !== "private") {
48
+ rec.set("members", []);
49
+ return;
50
+ }
51
+ const creator = rec.getString("created_by");
52
+ rec.set("members", [...new Set([creator, ...rec.getStringSlice("members")])].filter(Boolean));
53
+ }
54
+
55
+ /**
56
+ * Who can post (§23.6): everyone who can read the room, or only its writers. A DM is always everyone. Writers are
57
+ * listed only while posting is "selected": the creator first, each once, and in a private room only its members (a
58
+ * member taken out stops being a writer too).
59
+ * @param {core.Record} rec
60
+ */
61
+ function setWriters(rec) {
62
+ if (isDm(rec) || !rec.getString("posting")) rec.set("posting", "everyone");
63
+ if (rec.getString("posting") !== "selected") {
64
+ rec.set("writers", []);
65
+ return;
66
+ }
67
+ const creator = rec.getString("created_by");
68
+ let writers = [...new Set([creator, ...rec.getStringSlice("writers")])].filter(Boolean);
69
+ if (rec.getString("visibility") === "private") {
70
+ const members = new Set(rec.getStringSlice("members"));
71
+ writers = writers.filter((id) => members.has(id));
72
+ }
73
+ rec.set("writers", writers);
74
+ }
75
+
76
+ /**
77
+ * rooms create: public unless said otherwise; clean the name and check it is unique (§5.2, §16.1).
78
+ * @param {core.RecordEvent} e
79
+ */
80
+ function beforeRoomCreate(e) {
81
+ const rec = recordOf(e);
82
+ if (!rec.getString("kind")) rec.set("kind", "public");
83
+ setRoomName(e.app, rec);
84
+ setMembers(rec);
85
+ setWriters(rec);
86
+ }
87
+
88
+ /** Fields only the DM route and hooks may set (§16.3). A room's creator may change a private room's members (§23.2). */
89
+ const DM_FIELDS = ["kind", "members", "dm_key", "last_message_at"];
90
+
91
+ /**
92
+ * A DM field's value, comparable with ===.
93
+ * @param {core.Record} rec
94
+ * @param {string} field
95
+ */
96
+ const dmValue = (rec, field) => (field === "members" ? rec.getStringSlice(field).join(",") : rec.getString(field));
97
+
98
+ /**
99
+ * rooms create through the API: only public rooms (DMs come from POST /api/chat/dms). Backs up the create rule,
100
+ * field modifiers such as `members+` included (PocketBase 0.40.4's `:isset` sees them too, QA BUG-150).
101
+ * @param {core.RecordRequestEvent} e
102
+ */
103
+ function beforeRoomCreateRequest(e) {
104
+ const rec = recordOf(e);
105
+ const kind = rec.getString("kind");
106
+ if (kind && kind !== "public") throw fieldError("kind", "Rooms created here are public.");
107
+ for (const f of DM_FIELDS.slice(1)) {
108
+ if (dmValue(rec, f) !== "") throw fieldError(f, "This field can't be set.");
109
+ }
110
+ }
111
+
112
+ /**
113
+ * rooms update through the API: the DM fields never change (backs up the update rule, §16.3).
114
+ * @param {core.RecordRequestEvent} e
115
+ */
116
+ function beforeRoomUpdateRequest(e) {
117
+ const rec = recordOf(e);
118
+ const orig = rec.original();
119
+ for (const f of DM_FIELDS) {
120
+ if (f === "members" && !isDm(orig)) continue;
121
+ if (dmValue(rec, f) !== dmValue(orig, f)) throw fieldError(f, "This field can't be changed.");
122
+ }
123
+ }
124
+
125
+ /**
126
+ * rooms update: clean + unique name, stamp/clear archived_at when `archived` flips (§5.6).
127
+ * @param {core.RecordEvent} e
128
+ */
129
+ function beforeRoomUpdate(e) {
130
+ const rec = recordOf(e);
131
+ const orig = rec.original();
132
+ if (!isDm(rec) && rec.getString("name") === orig.getString("name")) {
133
+ // Name unchanged: keep its key and don't check it again. Rooms named before name_key existed may share a key
134
+ // (the migration made those unique), and must still be archivable (QA BUG-41).
135
+ rec.set("name_key", orig.getString("name_key"));
136
+ } else {
137
+ setRoomName(e.app, rec);
138
+ }
139
+ setMembers(rec);
140
+ setWriters(rec);
141
+ if (isDm(rec)) return;
142
+ const was = orig.getBool("archived");
143
+ const now = rec.getBool("archived");
144
+ if (!was && now) rec.set("archived_at", new DateTime());
145
+ if (was && !now) rec.set("archived_at", "");
146
+ }
147
+
148
+ module.exports = { isDm, beforeRoomCreate, beforeRoomCreateRequest, beforeRoomUpdate, beforeRoomUpdateRequest };
@@ -0,0 +1,102 @@
1
+ /// <reference path="../../types/pocketbase.d.ts" />
2
+ // Invite-only signups (DESIGN.md §24): while the `site` record says invite_only, a new account needs its invite_code
3
+ // (sent as `invite_code` with the signup). Superusers create accounts as they like.
4
+
5
+ /**
6
+ * The site record (the oldest, should a second one be added), or null without one.
7
+ * @param {core.App} app
8
+ */
9
+ function siteOf(app) {
10
+ const found = app.findRecordsByFilter("site", "", "created", 1, 0);
11
+ return found.length ? found[0] : null;
12
+ }
13
+
14
+ /**
15
+ * users create request: refuse a signup without the invite code while the site is invite-only.
16
+ * @param {core.RecordRequestEvent} e
17
+ */
18
+ function checkInvite(e) {
19
+ if (e.hasSuperuserAuth()) return;
20
+ const site = siteOf(e.app);
21
+ if (!site?.getBool("invite_only")) return;
22
+ const want = site.getString("invite_code").trim();
23
+ const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body);
24
+ const got = typeof body.invite_code === "string" ? body.invite_code.trim() : "";
25
+ if (want !== "" && got !== "" && $security.equal(got, want)) return;
26
+ const [code, message] =
27
+ want === ""
28
+ ? ["validation_signups_closed", "Signing up is closed."]
29
+ : got === ""
30
+ ? ["validation_required", "Enter your invite code."]
31
+ : ["validation_invalid_invite", "This invite code isn't valid."];
32
+ throw new BadRequestError("Failed to create record.", { invite_code: new ValidationError(code, message) });
33
+ }
34
+
35
+ /**
36
+ * users OAuth2 login: no new accounts this way while the site is invite-only (there is no code to check).
37
+ * @param {core.RecordAuthWithOAuth2RequestEvent} e
38
+ */
39
+ function checkOAuth2Signup(e) {
40
+ if (e.isNewRecord && siteOf(e.app)?.getBool("invite_only")) throw new ForbiddenError("Signing up is by invitation only.");
41
+ }
42
+
43
+ /**
44
+ * GET /manifest.webmanifest: the web app manifest (§27), named after the site's title. The icons stay the app's own:
45
+ * the logo may be any image (an SVG or a small one), and an installed app needs square PNGs.
46
+ * @param {core.RequestEvent} e
47
+ */
48
+ function manifest(e) {
49
+ const name = siteOf(e.app)?.getString("title") || "Chirkle";
50
+ const icon = (/** @type {string} */ src, /** @type {string} */ sizes, purpose = "any") => ({
51
+ src: `/icons/${src}`,
52
+ sizes,
53
+ type: src.endsWith(".svg") ? "image/svg+xml" : "image/png",
54
+ purpose,
55
+ });
56
+ e.response.header().set("Content-Type", "application/manifest+json");
57
+ return e.string(
58
+ 200,
59
+ JSON.stringify({
60
+ id: "/",
61
+ name,
62
+ short_name: name,
63
+ start_url: "/",
64
+ scope: "/",
65
+ display: "standalone",
66
+ // The app bar's color (--surface) and the page's (--bg), light theme: a manifest can't follow the system's.
67
+ theme_color: "#f1eefc",
68
+ background_color: "#fbfaff",
69
+ icons: [
70
+ icon("icon.svg", "any"),
71
+ icon("icon-192.png", "192x192"),
72
+ icon("icon-512.png", "512x512"),
73
+ icon("maskable-512.png", "512x512", "maskable"),
74
+ ],
75
+ }),
76
+ );
77
+ }
78
+
79
+ /**
80
+ * GET /.well-known/assetlinks.json: lets the Android app open links to rooms and messages (docs/ANDROID.md §9.4). From ANDROID_APP_ID
81
+ * (the app's own id, com.chirkle.android, when unset) and ANDROID_CERT_SHA256 (comma-separated fingerprints); 404
82
+ * without fingerprints.
83
+ * @param {core.RequestEvent} e
84
+ */
85
+ function assetLinks(e) {
86
+ const app = $os.getenv("ANDROID_APP_ID").trim() || "com.chirkle.android";
87
+ const certs = $os
88
+ .getenv("ANDROID_CERT_SHA256")
89
+ .split(",")
90
+ .map((c) => c.trim().toUpperCase())
91
+ .filter(Boolean);
92
+ if (!certs.length) throw new NotFoundError();
93
+ e.response.header().set("Cache-Control", "public, max-age=3600");
94
+ return e.json(200, [
95
+ {
96
+ relation: ["delegate_permission/common.handle_all_urls"],
97
+ target: { namespace: "android_app", package_name: app, sha256_cert_fingerprints: certs },
98
+ },
99
+ ]);
100
+ }
101
+
102
+ module.exports = { checkInvite, checkOAuth2Signup, manifest, assetLinks };