chirkle 0.4.0 → 0.4.1

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 (80) hide show
  1. package/README.md +32 -24
  2. package/bin/release/darwin-amd64/chirkle-server +2 -2
  3. package/bin/release/darwin-arm64/chirkle-server +0 -0
  4. package/bin/release/linux-amd64/chirkle-server +0 -0
  5. package/bin/release/linux-arm64/chirkle-server +0 -0
  6. package/package.json +2 -1
  7. package/pb_hooks/lib/account.js +541 -6
  8. package/pb_hooks/lib/collections.js +4 -4
  9. package/pb_hooks/lib/dms.js +1 -1
  10. package/pb_hooks/lib/inbox.js +1 -1
  11. package/pb_hooks/lib/invites.js +266 -0
  12. package/pb_hooks/lib/messages.js +11 -2
  13. package/pb_hooks/lib/moderation.js +1 -1
  14. package/pb_hooks/lib/retention.js +3 -0
  15. package/pb_hooks/lib/site.js +1 -1
  16. package/pb_hooks/lib/users.js +38 -10
  17. package/pb_hooks/main.pb.js +26 -1
  18. package/pb_hooks/telegram/api.js +64 -12
  19. package/pb_hooks/telegram/inbound.js +106 -15
  20. package/pb_hooks/telegram/outbound.js +63 -37
  21. package/pb_hooks/telegram/worker.js +59 -15
  22. package/pb_migrations/1760000052_deleted_accounts.js +19 -0
  23. package/pb_migrations/1760000053_account_jobs.js +45 -0
  24. package/pb_migrations/1760000054_room_invites.js +39 -0
  25. package/pb_migrations/1760000055_invite_barred.js +16 -0
  26. package/pb_migrations/1760000056_telegram_fetch.js +21 -0
  27. package/pb_public/assets/{access-PB77EH4F.css → access-GPRLOZOO.css} +2 -2
  28. package/pb_public/assets/{access-PB77EH4F.css.map → access-GPRLOZOO.css.map} +2 -2
  29. package/pb_public/assets/access-UK3L54NR.js +2 -0
  30. package/pb_public/assets/access-UK3L54NR.js.map +7 -0
  31. package/pb_public/assets/account-CT2BVMAX.css +2 -0
  32. package/pb_public/assets/account-CT2BVMAX.css.map +7 -0
  33. package/pb_public/assets/account-api-J6A6IYVX.js +2 -0
  34. package/pb_public/assets/account-api-J6A6IYVX.js.map +7 -0
  35. package/pb_public/assets/app-HB3NZHQ2.js +3 -0
  36. package/pb_public/assets/app-HB3NZHQ2.js.map +7 -0
  37. package/pb_public/assets/app-XJ73EU5O.css +2 -0
  38. package/pb_public/assets/app-XJ73EU5O.css.map +7 -0
  39. package/pb_public/assets/chunk-AG73QNUN.js +2 -0
  40. package/pb_public/assets/chunk-AG73QNUN.js.map +7 -0
  41. package/pb_public/assets/chunk-DCLJRQ53.js +2 -0
  42. package/pb_public/assets/chunk-DCLJRQ53.js.map +7 -0
  43. package/pb_public/assets/chunk-N2OFGBCZ.js +2 -0
  44. package/pb_public/assets/{chunk-PWNJABVI.js.map → chunk-N2OFGBCZ.js.map} +4 -4
  45. package/pb_public/assets/chunk-OKIIBH7O.js +2 -0
  46. package/pb_public/assets/chunk-OKIIBH7O.js.map +7 -0
  47. package/pb_public/assets/chunk-UZDXAORM.js +2 -0
  48. package/pb_public/assets/chunk-UZDXAORM.js.map +7 -0
  49. package/pb_public/assets/chunk-WR25F7FU.js +2 -0
  50. package/pb_public/assets/chunk-WR25F7FU.js.map +7 -0
  51. package/pb_public/assets/invite-OGT5E2MZ.js +2 -0
  52. package/pb_public/assets/invite-OGT5E2MZ.js.map +7 -0
  53. package/pb_public/assets/invite-api-7G7XPXQW.js +2 -0
  54. package/pb_public/assets/invite-api-7G7XPXQW.js.map +7 -0
  55. package/pb_public/assets/login-TK6K4WGB.js +2 -0
  56. package/pb_public/assets/{login-ECFBJP6Q.js.map → login-TK6K4WGB.js.map} +1 -1
  57. package/pb_public/assets/profile-3R6S5QYS.js +2 -0
  58. package/pb_public/assets/profile-3R6S5QYS.js.map +7 -0
  59. package/pb_public/assets/stats-GTO2H6PG.js +2 -0
  60. package/pb_public/assets/stats-GTO2H6PG.js.map +7 -0
  61. package/pb_public/index.html +7 -5
  62. package/pb_public/stats.html +1 -1
  63. package/scripts/service.mjs +201 -0
  64. package/scripts/start.mjs +7 -1
  65. package/pb_public/assets/access-LHPD2EHG.js +0 -2
  66. package/pb_public/assets/access-LHPD2EHG.js.map +0 -7
  67. package/pb_public/assets/app-6ETOTHXQ.js +0 -3
  68. package/pb_public/assets/app-6ETOTHXQ.js.map +0 -7
  69. package/pb_public/assets/app-ZGHECF33.css +0 -2
  70. package/pb_public/assets/app-ZGHECF33.css.map +0 -7
  71. package/pb_public/assets/chunk-GXMWOXBX.js +0 -2
  72. package/pb_public/assets/chunk-GXMWOXBX.js.map +0 -7
  73. package/pb_public/assets/chunk-IFQGGTSP.js +0 -2
  74. package/pb_public/assets/chunk-IFQGGTSP.js.map +0 -7
  75. package/pb_public/assets/chunk-PWNJABVI.js +0 -2
  76. package/pb_public/assets/login-ECFBJP6Q.js +0 -2
  77. package/pb_public/assets/profile-NQQLAEDT.js +0 -2
  78. package/pb_public/assets/profile-NQQLAEDT.js.map +0 -7
  79. package/pb_public/assets/stats-ARDU576A.js +0 -2
  80. package/pb_public/assets/stats-ARDU576A.js.map +0 -7
@@ -281,7 +281,7 @@ const itemOut = (item) => ({
281
281
  */
282
282
  function saveItem(e) {
283
283
  const user = me(e);
284
- const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body);
284
+ const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body ?? {});
285
285
  const str = (/** @type {string} */ k) => (typeof body[k] === "string" ? /** @type {string} */ (body[k]) : "");
286
286
  const coll = find(e.app, "collections", str("collection"));
287
287
  if (!coll || !canView(e, coll)) throw new NotFoundError("The collection doesn't exist.");
@@ -447,7 +447,7 @@ function removeItem(e) {
447
447
  * @returns {{ rows: core.Record[], sources: Record<string, string> }}
448
448
  */
449
449
  function itemsToAttach(e, uploads) {
450
- const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body);
450
+ const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body ?? {});
451
451
  let ids = body.items;
452
452
  if (ids === undefined || ids === "" || ids === null) return { rows: [], sources: {} };
453
453
  if (typeof ids === "string") {
@@ -502,7 +502,7 @@ function findSub(app, user, collection) {
502
502
  */
503
503
  function subscribe(e) {
504
504
  const user = me(e);
505
- const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body);
505
+ const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body ?? {});
506
506
  const id = typeof body.collection === "string" ? body.collection : "";
507
507
  const what = "Failed to subscribe.";
508
508
  // Not "false" or 0 taken for true.
@@ -545,7 +545,7 @@ function subscribe(e) {
545
545
  */
546
546
  function markSeen(e) {
547
547
  const user = me(e);
548
- const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body);
548
+ const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body ?? {});
549
549
  const id = typeof body.collection === "string" ? body.collection : "";
550
550
  const row = id ? findSub(e.app, user.id, id) : null;
551
551
  if (!row) throw new NotFoundError("You don't follow this collection.");
@@ -82,7 +82,7 @@ function dmRefusal(app, me, members) {
82
82
  function openDm(e) {
83
83
  const me = e.auth;
84
84
  if (!me) throw new UnauthorizedError("The request requires a logged-in user.");
85
- const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body);
85
+ const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body ?? {});
86
86
  const other = typeof body.user === "string" ? body.user : "";
87
87
  if (!other) throw userError("Choose who to message.", "validation_required");
88
88
  if (other === me.id) throw userError("You can't message yourself.");
@@ -329,7 +329,7 @@ function list(e) {
329
329
  function markSeen(e) {
330
330
  const me = e.auth;
331
331
  if (!me) throw new UnauthorizedError("The request requires a logged-in user.");
332
- const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body);
332
+ const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body ?? {});
333
333
  const now = new DateTime();
334
334
  let at = now;
335
335
  if (body.at !== undefined) {
@@ -0,0 +1,266 @@
1
+ /// <reference path="../../types/pocketbase.d.ts" />
2
+ // Room invite links (DESIGN.md §44, REFACTOR P9): whoever may change a private room's members (its creator, or a
3
+ // moderator who is in it, §36) shares a link, /invite/<token>, that adds whoever opens it, signed in, to the members.
4
+ // One link per room at a time, kept in `room_invites` (migration 54, no API rules): made again, the old one stops
5
+ // working; revoked, it is deleted. It expires after 1, 7 or 30 days, and stops working once the room is no longer
6
+ // private (the rooms update hook deletes it, dropInvites) or while it is archived.
7
+ //
8
+ // The token is 24 random letters and digits (about 143 bits): it is the whole secret, so no rate limit guards it.
9
+
10
+ const { MAX_MEMBERS, accessOf, sees, viewerOf } = require(`${__hooks}/lib/access.js`);
11
+ const { isDm } = require(`${__hooks}/lib/rooms.js`);
12
+
13
+ /** How long a new link works, in days: the choices the clients offer. */
14
+ const DAYS = [1, 7, 30];
15
+ /** When none is given. */
16
+ const DEFAULT_DAYS = 7;
17
+ const TOKEN_LENGTH = 24;
18
+ /** What a link that doesn't work (any more) says: never which of the reasons, so a token tells nothing. */
19
+ const GONE = "This invite link has expired or was revoked.";
20
+
21
+ /** PocketBase's date text for `ms`. @param {number} ms */
22
+ const dbDate = (ms) => new Date(ms).toISOString().replace("T", " ");
23
+ /** @param {string} s PocketBase's date text */
24
+ const msOf = (s) => Date.parse(s.replace(" ", "T"));
25
+
26
+ /**
27
+ * The room's invite row, or null.
28
+ * @param {core.App} app
29
+ * @param {string} roomId
30
+ */
31
+ function inviteOf(app, roomId) {
32
+ try {
33
+ return app.findFirstRecordByFilter("room_invites", "room = {:r}", { r: roomId });
34
+ } catch {
35
+ return null;
36
+ }
37
+ }
38
+
39
+ /**
40
+ * Those the room's managers took out of its members while this link worked (QA BUG-280): it doesn't let them back in.
41
+ * @param {core.Record} inv
42
+ */
43
+ function barredOf(inv) {
44
+ // A JSON field reads as its raw text.
45
+ let v;
46
+ try {
47
+ v = JSON.parse(inv.getString("barred") || "[]");
48
+ } catch {
49
+ return [];
50
+ }
51
+ return Array.isArray(v) ? v.filter((x) => typeof x === "string") : [];
52
+ }
53
+
54
+ /** Has the link run out? @param {core.Record} inv @param {number} [now] */
55
+ const expired = (inv, now = Date.now()) => msOf(inv.getString("expires")) <= now;
56
+
57
+ /**
58
+ * What the managing routes answer: the room's working link, or null.
59
+ * @param {core.Record | null} inv
60
+ */
61
+ function answer(inv) {
62
+ if (!inv || expired(inv)) return { invite: null };
63
+ return {
64
+ invite: {
65
+ token: inv.getString("token"),
66
+ created: inv.getString("created"),
67
+ expires: inv.getString("expires"),
68
+ uses: inv.getInt("uses"),
69
+ },
70
+ };
71
+ }
72
+
73
+ /**
74
+ * The room in the path, for someone who may manage its link: signed in, sees it, its creator or a moderator, not a DM,
75
+ * not a copy of another instance's room (§33.5: its members are changed there). Throws what to answer otherwise.
76
+ * @param {core.RequestEvent} e
77
+ */
78
+ function managedRoom(e) {
79
+ if (!e.auth) throw new UnauthorizedError("The request requires a logged-in user.");
80
+ const id = e.request?.pathValue("room") ?? "";
81
+ let room;
82
+ try {
83
+ room = e.app.findRecordById("rooms", id);
84
+ } catch {
85
+ throw new NotFoundError("This room doesn't exist.");
86
+ }
87
+ if (!sees(viewerOf(e.auth), accessOf(room))) throw new NotFoundError("This room doesn't exist.");
88
+ const { canManage } = require(`${__hooks}/lib/moderation.js`);
89
+ if (isDm(room) || !canManage(room, e.auth)) {
90
+ throw new ForbiddenError("Only the room's creator or a moderator can share an invite link.");
91
+ }
92
+ if (room.getString("peer")) throw new BadRequestError("This room's home is another instance: invite people there.");
93
+ return room;
94
+ }
95
+
96
+ /**
97
+ * GET /api/chat/rooms/{room}/invite → { invite: { token, created, expires, uses } | null }: the room's working link.
98
+ * @param {core.RequestEvent} e
99
+ */
100
+ function get(e) {
101
+ const room = managedRoom(e);
102
+ if (room.getString("visibility") !== "private") return e.json(200, { invite: null });
103
+ return e.json(200, answer(inviteOf(e.app, room.id)));
104
+ }
105
+
106
+ /**
107
+ * POST /api/chat/rooms/{room}/invite { days: 1 | 7 | 30 } → a new link (as GET answers), replacing the room's last one.
108
+ * Private rooms only, and not archived ones.
109
+ * @param {core.RequestEvent} e
110
+ */
111
+ function create(e) {
112
+ const room = managedRoom(e);
113
+ if (room.getString("visibility") !== "private") throw new BadRequestError("Only a private room has an invite link.");
114
+ if (room.getBool("archived")) throw new BadRequestError("This room is archived.");
115
+ const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body ?? {});
116
+ const days = body.days === undefined || body.days === null ? DEFAULT_DAYS : body.days;
117
+ if (typeof days !== "number" || !DAYS.includes(days)) {
118
+ throw new BadRequestError("Failed to make the invite link.", {
119
+ days: new ValidationError("validation_invalid_value", `A link works for ${DAYS.join(", ")} days.`),
120
+ });
121
+ }
122
+ /** @type {core.Record | null} */
123
+ let made = null;
124
+ e.app.runInTransaction((tx) => {
125
+ const old = inviteOf(tx, room.id);
126
+ if (old) tx.delete(old);
127
+ const inv = new Record(tx.findCollectionByNameOrId("room_invites"));
128
+ inv.set("room", room.id);
129
+ inv.set("token", $security.randomString(TOKEN_LENGTH));
130
+ inv.set("created_by", e.auth?.id ?? "");
131
+ inv.set("expires", dbDate(Date.now() + days * 24 * 3600_000));
132
+ inv.set("uses", 0);
133
+ tx.save(inv);
134
+ made = inv;
135
+ });
136
+ return e.json(200, answer(made));
137
+ }
138
+
139
+ /**
140
+ * DELETE /api/chat/rooms/{room}/invite → 204: the link stops working. Nothing to revoke is fine too.
141
+ * @param {core.RequestEvent} e
142
+ */
143
+ function revoke(e) {
144
+ const room = managedRoom(e);
145
+ const inv = inviteOf(e.app, room.id);
146
+ if (inv) e.app.delete(inv);
147
+ return e.noContent(204);
148
+ }
149
+
150
+ /**
151
+ * The working invite the path's token names, with its room; null when there is none (unknown, expired, revoked, the
152
+ * room no longer private or archived, a DM).
153
+ * @param {core.App} app
154
+ * @param {string} token
155
+ */
156
+ function working(app, token) {
157
+ if (typeof token !== "string" || token.length !== TOKEN_LENGTH) return null;
158
+ let inv;
159
+ try {
160
+ inv = app.findFirstRecordByFilter("room_invites", "token = {:t}", { t: token });
161
+ } catch {
162
+ return null;
163
+ }
164
+ if (expired(inv)) return null;
165
+ let room;
166
+ try {
167
+ room = app.findRecordById("rooms", inv.getString("room"));
168
+ } catch {
169
+ return null;
170
+ }
171
+ if (isDm(room) || room.getString("visibility") !== "private" || room.getBool("archived")) return null;
172
+ return { inv, room };
173
+ }
174
+
175
+ /**
176
+ * GET /api/chat/invites/{token} → { room: { id, name, members }, by, expires, member }: what the link is to, for its
177
+ * page (guests too: the link is the secret, and they are asked to log in or sign up to join). `members` counts its
178
+ * members; `by` is who made the link; `member` says whether you are in already.
179
+ * 404 when it doesn't work.
180
+ * @param {core.RequestEvent} e
181
+ */
182
+ function preview(e) {
183
+ const found = working(e.app, e.request?.pathValue("token") ?? "");
184
+ if (!found) throw new NotFoundError(GONE);
185
+ const { inv, room } = found;
186
+ const members = room.getStringSlice("members");
187
+ let by = "";
188
+ try {
189
+ by = e.app.findRecordById("users", inv.getString("created_by")).getString("name");
190
+ } catch {}
191
+ const me = e.auth && !e.auth.isSuperuser() ? e.auth.id : "";
192
+ // Taken out of the room by its managers: for them the link doesn't work (the same answer as any dead link).
193
+ if (me && barredOf(inv).includes(me)) throw new NotFoundError(GONE);
194
+ return e.json(200, {
195
+ room: { id: room.id, name: room.getString("name"), members: members.length },
196
+ by,
197
+ expires: inv.getString("expires"),
198
+ member: !!me && (members.includes(me) || room.getString("created_by") === me),
199
+ });
200
+ }
201
+
202
+ /**
203
+ * POST /api/chat/invites/{token} → { room }: join the room as a member (signed in). Already in, nothing changes. 404
204
+ * when the link doesn't work; 400 when the room is full. The room's save goes through its hooks, so whoever is in it
205
+ * (the new member too) hears of it live (§23.4), and a shared room's peers are told (§33).
206
+ * @param {core.RequestEvent} e
207
+ */
208
+ function join(e) {
209
+ if (!e.auth || e.auth.isSuperuser()) throw new UnauthorizedError("Log in to join the room.");
210
+ const me = e.auth.id;
211
+ const token = e.request?.pathValue("token") ?? "";
212
+ /** @type {string} */
213
+ let roomId = "";
214
+ e.app.runInTransaction((tx) => {
215
+ const found = working(tx, token);
216
+ if (!found) throw new NotFoundError(GONE);
217
+ const { inv, room } = found;
218
+ if (barredOf(inv).includes(me)) throw new NotFoundError(GONE);
219
+ roomId = room.id;
220
+ const members = room.getStringSlice("members");
221
+ if (members.includes(me) || room.getString("created_by") === me) return;
222
+ if (members.length >= MAX_MEMBERS) throw new BadRequestError(`This room is full: it has ${MAX_MEMBERS} members.`);
223
+ room.set("members", [...members, me]);
224
+ tx.save(room);
225
+ inv.set("uses", inv.getInt("uses") + 1);
226
+ tx.save(inv);
227
+ });
228
+ return e.json(200, { room: roomId });
229
+ }
230
+
231
+ /**
232
+ * rooms update (saved): a room that stopped being private has no invite link. Made private again, it needs a new one,
233
+ * so an old link doesn't come back to life. Only on that change: every DM message saves its room.
234
+ * @param {core.App} app
235
+ * @param {string} wasVisibility
236
+ * @param {core.Record} room
237
+ */
238
+ function dropInvites(app, wasVisibility, room) {
239
+ if (wasVisibility !== "private" || room.getString("visibility") === "private") return;
240
+ const inv = inviteOf(app, room.id);
241
+ if (inv) app.delete(inv);
242
+ }
243
+
244
+ /**
245
+ * rooms update request (saved): whoever the request took out of a private room's members can't come back with its
246
+ * working link (QA BUG-280); its managers make a new link to let everyone in again, or add them back. Not the joins
247
+ * themselves, nor an account's delete (§43.3): those are saved by the server, not by a request.
248
+ * @param {core.App} app
249
+ * @param {string[]} wasMembers
250
+ * @param {core.Record} room
251
+ */
252
+ function barRemoved(app, wasMembers, room) {
253
+ if (room.getString("visibility") !== "private") return;
254
+ const now = new Set(room.getStringSlice("members"));
255
+ const gone = wasMembers.filter((u) => !now.has(u));
256
+ const inv = inviteOf(app, room.id);
257
+ if (!inv) return;
258
+ const was = barredOf(inv);
259
+ // Added back by hand: barred no more.
260
+ const barred = [...new Set([...was, ...gone])].filter((u) => !now.has(u));
261
+ if (barred.length === was.length && barred.every((u) => was.includes(u))) return;
262
+ inv.set("barred", barred);
263
+ app.save(inv);
264
+ }
265
+
266
+ module.exports = { DAYS, DEFAULT_DAYS, GONE, get, create, revoke, preview, join, dropInvites, barRemoved };
@@ -92,6 +92,12 @@ function postService(app, roomId, text) {
92
92
  */
93
93
  const CHECKED = "@checked";
94
94
 
95
+ /**
96
+ * Set on a message by lib/account.js erase (a custom key, neither stored nor sent): deleted because its author deleted
97
+ * their account and its messages (§43), which archived rooms don't refuse.
98
+ */
99
+ const ERASING = "@erasing";
100
+
95
101
  /** Was this message checked by its create request already (prepareCreate)? @param {core.Record} rec */
96
102
  const checked = (rec) => rec.get(CHECKED) === true;
97
103
 
@@ -331,7 +337,9 @@ function beforeMessageUpdate(e) {
331
337
  // A message deleted for good (by a superuser, or with its room) is already gone when PocketBase unsets the
332
338
  // reply_to of its replies (§19.1). Let that save through: the guards below would refuse it, and with it the delete.
333
339
  if (replyTargetRemoved(e.app, rec, orig) || forwardSourceRemoved(e.app, rec, orig) || originalRemoved(e.app, rec, orig)) return;
334
- activeRoom(e.app, orig.getString("room"));
340
+ // A deleted account's messages, deleted with it at its person's wish (§43), go from archived rooms too.
341
+ const erasing = rec.get(ERASING) === true && rec.getBool("deleted");
342
+ if (!erasing) activeRoom(e.app, orig.getString("room"));
335
343
 
336
344
  if (orig.getBool("deleted")) {
337
345
  // Deletion is final; API rules already refuse this, so this only guards superuser edits.
@@ -392,7 +400,7 @@ function beforeMessageUpdateRequest(e) {
392
400
  const rec = recordOf(e);
393
401
  // Uploads and modifiers aren't a file field's any more (§37), so the update rule doesn't see them all: refused
394
402
  // here, not dropped.
395
- const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body);
403
+ const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body ?? {});
396
404
  for (const key of ["files", "+files", "files+", "files-"]) {
397
405
  let n = 0;
398
406
  try {
@@ -452,6 +460,7 @@ function beforeUserDelete(e) {
452
460
  }
453
461
 
454
462
  module.exports = {
463
+ ERASING,
455
464
  checked,
456
465
  prepareCreate,
457
466
  isService,
@@ -81,7 +81,7 @@ function refuseBanned(rec, password) {
81
81
  function ban(e) {
82
82
  const me = e.auth;
83
83
  if (!isModerator(me)) throw new ForbiddenError("Only moderators can ban people.");
84
- const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body);
84
+ const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body ?? {});
85
85
  const what = body.banned === false ? "Failed to unban them." : "Failed to ban them.";
86
86
  const bad = (/** @type {string} */ field, /** @type {string} */ msg) =>
87
87
  new BadRequestError(what, { [field]: new ValidationError("validation_invalid_value", msg) });
@@ -9,6 +9,7 @@
9
9
  // person or room that is gone; media rows (§30) and link preview jobs (§28) of a soft-deleted or gone message (a
10
10
  // forward's media rows go with its original, as lib/media.js drop() does). PocketBase's cascades only run for
11
11
  // deletes it makes itself.
12
+ // - `room_invites` (DESIGN.md §44): links that expired a day or more ago.
12
13
  //
13
14
  // Messages are never pruned: history is kept (DESIGN.md §2). A retention period for them would be the owner's choice.
14
15
 
@@ -47,6 +48,8 @@ const STEPS = [
47
48
  ],
48
49
  ["media_orphans", `DELETE FROM media WHERE NOT ${live("media.message")} OR (media.source != '' AND NOT ${live("media.source")})`],
49
50
  ["link_queue_orphans", `DELETE FROM link_queue WHERE NOT ${live("link_queue.message")}`],
51
+ // Invite links that ran out a day or more ago (DESIGN.md §44): they no longer work, and the room's managers see none.
52
+ ["room_invites_expired", "DELETE FROM room_invites WHERE expires < strftime('%Y-%m-%d %H:%M:%fZ', 'now', '-1 day')"],
50
53
  ];
51
54
 
52
55
  /** PocketBase's date text for `ms`. @param {number} ms */
@@ -20,7 +20,7 @@ function checkInvite(e) {
20
20
  const site = siteOf(e.app);
21
21
  if (!site?.getBool("invite_only")) return;
22
22
  const want = site.getString("invite_code").trim();
23
- const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body);
23
+ const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body ?? {});
24
24
  const got = typeof body.invite_code === "string" ? body.invite_code.trim() : "";
25
25
  if (want !== "" && got !== "" && $security.equal(got, want)) return;
26
26
  const [code, message] =
@@ -36,18 +36,25 @@ function checkPasswordLength(password) {
36
36
  }
37
37
  }
38
38
 
39
+ /** What a deleted account is called (§43). Nobody else may take the name. */
40
+ const DELETED_NAME = "Deleted account";
41
+
39
42
  /**
40
43
  * What kind of account `user` is (§5.1, `users.kind`): "person" (signs in here), "telegram" (a Telegram sender's
41
- * stand-in, §26.3) or "peer" (a linked instance's person, §33.4). Never set: a person.
44
+ * stand-in, §26.3), "peer" (a linked instance's person, §33.4) or "deleted" (its person deleted it, §43). Never set: a
45
+ * person.
42
46
  * @param {core.Record} user
43
- * @returns {"person" | "telegram" | "peer"}
47
+ * @returns {"person" | "telegram" | "peer" | "deleted"}
44
48
  */
45
49
  function kindOf(user) {
46
50
  const kind = user.getString("kind");
47
- return kind === "telegram" || kind === "peer" ? kind : "person";
51
+ return kind === "telegram" || kind === "peer" || kind === "deleted" ? kind : "person";
48
52
  }
49
53
 
50
- /** A stand-in: an account nobody signs in to here (a Telegram sender's, another instance's person's). @param {core.Record} user */
54
+ /**
55
+ * A stand-in: an account nobody signs in to here (a Telegram sender's, another instance's person's, a deleted one).
56
+ * @param {core.Record} user
57
+ */
51
58
  const isStandIn = (user) => kindOf(user) !== "person";
52
59
 
53
60
  /** @param {core.RequestEvent} e */
@@ -60,11 +67,19 @@ function searchUsers(e) {
60
67
  // `~` treats a % in the value as a wildcard (and then stops adding its own): escape it (QA BUG-34). `_` is escaped.
61
68
  // "@ann" finds Ann by her handle (§41) as well as by name.
62
69
  const handle = key.replace(/^@/, "");
63
- const found = e.app.findRecordsByFilter("users", "(name_key ~ {:q} || handle ~ {:h}) && id != {:me}", "name", LIMIT, 0, {
64
- q: key.replace(/%/g, "\\%"),
65
- h: handle.replace(/%/g, "\\%"),
66
- me: me.id,
67
- });
70
+ // Not a deleted account (§43): there is nobody to message.
71
+ const found = e.app.findRecordsByFilter(
72
+ "users",
73
+ "(name_key ~ {:q} || handle ~ {:h}) && id != {:me} && kind != 'deleted'",
74
+ "name",
75
+ LIMIT,
76
+ 0,
77
+ {
78
+ q: key.replace(/%/g, "\\%"),
79
+ h: handle.replace(/%/g, "\\%"),
80
+ me: me.id,
81
+ },
82
+ );
68
83
  // Only the public profile, never the email (§6).
69
84
  return e.json(
70
85
  200,
@@ -97,7 +112,20 @@ function beforeUserSave(e) {
97
112
  if (rec.isNew() || email !== rec.original().getString("email")) rec.set("email", email.trim().toLowerCase());
98
113
  // Signups and accounts a superuser makes are people; the bridges set their stand-ins' kind before saving.
99
114
  if (rec.isNew() && !rec.getString("kind")) rec.set("kind", "person");
115
+ if (kindOf(rec) === "deleted") {
116
+ // A deleted account (§43, lib/account.js erase): one name for all of them, each with a key of its own (no name
117
+ // is cleaned to a control character, so no one else's key is ever this), and no handle.
118
+ rec.set("name", DELETED_NAME);
119
+ rec.set("name_key", `\u0001deleted ${rec.id}`);
120
+ rec.set("handle", "");
121
+ return;
122
+ }
100
123
  cleanName(rec);
124
+ // "Deleted account" is what deleted accounts are called (§43): taken, by them.
125
+ const renamed = rec.isNew() || rec.getString("name") !== rec.original().getString("name");
126
+ if (renamed && nameKey(rec.getString("name")) === nameKey(DELETED_NAME)) {
127
+ throw fieldError("name", "This display name is taken. Choose another one.", "validation_not_unique");
128
+ }
101
129
  if (!rec.isNew() && rec.getString("name") === rec.original().getString("name")) {
102
130
  // Name unchanged: keep its key. Accounts named before name_key existed may share a name (the migration made
103
131
  // their keys unique), and must still be able to change their picture or password.
@@ -136,4 +164,4 @@ function skipStandInReset(e) {
136
164
  return e.next();
137
165
  }
138
166
 
139
- module.exports = { beforeUserSave, checkPasswordLength, findLoginByEmail, isStandIn, kindOf, searchUsers, skipStandInReset };
167
+ module.exports = { DELETED_NAME, beforeUserSave, checkPasswordLength, findLoginByEmail, isStandIn, kindOf, searchUsers, skipStandInReset };
@@ -1,5 +1,5 @@
1
1
  /// <reference path="../types/pocketbase.d.ts" />
2
- // Server-side hooks (DESIGN.md §5.6, §16, §18, §20, §21, §22, §23, §24, §28, §30, §31, §36, §37, §40; docs/ANDROID.md §9.4). Logic lives in lib/, one module per collection
2
+ // Server-side hooks (DESIGN.md §5.6, §16, §18, §20, §21, §22, §23, §24, §28, §30, §31, §36, §37, §40, §43, §44; docs/ANDROID.md §9.4). Logic lives in lib/, one module per collection
3
3
  // or route: PocketBase hook handlers can't see top-level variables, so each handler require()s its module.
4
4
 
5
5
  onBootstrap((e) => {
@@ -58,6 +58,20 @@ routerAdd("GET", "/api/chat/mentionable", (e) => require(`${__hooks}/lib/handles
58
58
  routerAdd("GET", "/api/chat/inbox", (e) => require(`${__hooks}/lib/inbox.js`).list(e), $apis.requireAuth("users"));
59
59
  routerAdd("POST", "/api/chat/inbox/seen", (e) => require(`${__hooks}/lib/inbox.js`).markSeen(e), $apis.requireAuth("users"));
60
60
  routerAdd("POST", "/api/chat/password", (e) => require(`${__hooks}/lib/account.js`).changePassword(e), $apis.requireAuth("users"));
61
+ // Your data, and deleting your account (§43).
62
+ routerAdd("GET", "/api/chat/export", (e) => require(`${__hooks}/lib/account.js`).exportState(e), $apis.requireAuth("users"));
63
+ routerAdd("POST", "/api/chat/export", (e) => require(`${__hooks}/lib/account.js`).startExport(e), $apis.requireAuth("users"));
64
+ // Signed in or with a file token (a plain link), checked by the route.
65
+ routerAdd("GET", "/api/chat/export/file", (e) => require(`${__hooks}/lib/account.js`).exportFile(e));
66
+ routerAdd("POST", "/api/account/tick", (e) => require(`${__hooks}/lib/account.js`).tick(e), $apis.requireSuperuserAuth());
67
+ routerAdd("POST", "/api/chat/account/delete", (e) => require(`${__hooks}/lib/account.js`).deleteAccount(e), $apis.requireAuth("users"));
68
+ // Room invite links (§44): a private room's managers make and revoke its link; anyone reads where a link goes, and
69
+ // joins by it signed in.
70
+ routerAdd("GET", "/api/chat/rooms/{room}/invite", (e) => require(`${__hooks}/lib/invites.js`).get(e), $apis.requireAuth("users"));
71
+ routerAdd("POST", "/api/chat/rooms/{room}/invite", (e) => require(`${__hooks}/lib/invites.js`).create(e), $apis.requireAuth("users"));
72
+ routerAdd("DELETE", "/api/chat/rooms/{room}/invite", (e) => require(`${__hooks}/lib/invites.js`).revoke(e), $apis.requireAuth("users"));
73
+ routerAdd("GET", "/api/chat/invites/{token}", (e) => require(`${__hooks}/lib/invites.js`).preview(e));
74
+ routerAdd("POST", "/api/chat/invites/{token}", (e) => require(`${__hooks}/lib/invites.js`).join(e), $apis.requireAuth("users"));
61
75
 
62
76
  // The core collections' hooks (messages, rooms, users) are all here, with the optional features' parts (lib/features.js)
63
77
  // called in order: the federation's first, then the core's, then the Telegram bridge's; after the save, the other way
@@ -138,8 +152,11 @@ onRecordUpdateRequest((e) => {
138
152
  if (fed) fed.rooms.checkHomeMembers(e);
139
153
  const members = fed ? fed.mirror.checkMirrorEdit(e) : null;
140
154
  require(`${__hooks}/lib/rooms.js`).beforeRoomUpdateRequest(e);
155
+ const wasMembers = e.record?.original().getStringSlice("members") ?? [];
141
156
  e.next();
142
157
  if (fed && members && e.record) fed.mirror.sendMembers(e.app, e.record, members);
158
+ // Taken out of a private room: its invite link doesn't let them back in (§44.2, QA BUG-280).
159
+ if (e.record) require(`${__hooks}/lib/invites.js`).barRemoved(e.app, wasMembers, e.record);
143
160
  }, "rooms");
144
161
 
145
162
  onRecordCreate((e) => {
@@ -159,6 +176,8 @@ onRecordUpdate((e) => {
159
176
  e.next();
160
177
  // Saved: whoever can't see it any more is told (§23.4).
161
178
  if (e.record) access.dropLostAccess(e.app, before, e.record);
179
+ // No longer private: its invite link goes (§44).
180
+ if (e.record) require(`${__hooks}/lib/invites.js`).dropInvites(e.app, before.visibility, e.record);
162
181
  // Its anonymous messages show its new name (§35).
163
182
  if (e.record) require(`${__hooks}/lib/anonymous.js`).forget(e.app, e.record.id);
164
183
  // A home room's changes go to its mirrors (§33).
@@ -360,6 +379,12 @@ if ($os.getenv("STATS_CRON").trim().toLowerCase() !== "off") {
360
379
  // Retention (REFACTOR item 49): old inbox rows and rows left behind by raw deletes, daily (lib/retention.js).
361
380
  cronAdd("retention", "41 3 * * *", () => require(`${__hooks}/lib/retention.js`).prune($app));
362
381
 
382
+ // Account jobs (§43.5): exports made and deleted accounts' collections and messages deleted, by a worker, a minute's run
383
+ // at a time. ACCOUNT_CRON=off leaves them to POST /api/account/tick (tests).
384
+ if ($os.getenv("ACCOUNT_CRON").trim().toLowerCase() !== "off") {
385
+ cronAdd("account", "* * * * *", () => require(`${__hooks}/lib/account.js`).run($app));
386
+ }
387
+
363
388
  // The media grid's thumbnails and video posters (§30.1): made by a worker, a minute's run at a time. MEDIA_CRON=off
364
389
  // leaves them to POST /api/media/tick (tests).
365
390
  if ($os.getenv("MEDIA_CRON").trim().toLowerCase() !== "off") {