chirkle 0.3.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 (156) hide show
  1. package/README.md +99 -47
  2. package/bin/release/darwin-amd64/chirkle-server +4 -0
  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 +9 -6
  7. package/pb_hooks/federation/inbox.js +2 -69
  8. package/pb_hooks/federation/messages.js +5 -3
  9. package/pb_hooks/federation/net.js +1 -0
  10. package/pb_hooks/federation/people.js +1 -0
  11. package/pb_hooks/federation.pb.js +1 -8
  12. package/pb_hooks/lib/access.js +33 -10
  13. package/pb_hooks/lib/account.js +542 -6
  14. package/pb_hooks/lib/anonymous.js +2 -129
  15. package/pb_hooks/lib/bulk.js +1 -2
  16. package/pb_hooks/lib/collections.js +4 -4
  17. package/pb_hooks/lib/dms.js +1 -1
  18. package/pb_hooks/lib/files.js +82 -120
  19. package/pb_hooks/lib/handles.js +2 -2
  20. package/pb_hooks/lib/inbox.js +40 -54
  21. package/pb_hooks/lib/invites.js +266 -0
  22. package/pb_hooks/lib/media.js +5 -43
  23. package/pb_hooks/lib/messages.js +72 -117
  24. package/pb_hooks/lib/moderation.js +2 -16
  25. package/pb_hooks/lib/reactions.js +28 -4
  26. package/pb_hooks/lib/retention.js +88 -0
  27. package/pb_hooks/lib/site.js +13 -2
  28. package/pb_hooks/lib/stats.js +6 -34
  29. package/pb_hooks/lib/users.js +88 -7
  30. package/pb_hooks/lib/worker.js +22 -1
  31. package/pb_hooks/main.pb.js +85 -94
  32. package/pb_hooks/telegram/api.js +64 -12
  33. package/pb_hooks/telegram/inbound.js +158 -31
  34. package/pb_hooks/telegram/links.js +4 -3
  35. package/pb_hooks/telegram/outbound.js +86 -45
  36. package/pb_hooks/telegram/people.js +3 -3
  37. package/pb_hooks/telegram/worker.js +59 -15
  38. package/pb_migrations/1760000045_password_reset.js +38 -0
  39. package/pb_migrations/1760000047_telegram_supergroup_ids.js +51 -0
  40. package/pb_migrations/1760000048_inbox_reactions_merged.js +24 -0
  41. package/pb_migrations/1760000049_inbox_room_index.js +22 -0
  42. package/pb_migrations/1760000050_messages_unread_index.js +22 -0
  43. package/pb_migrations/1760000051_users_kind.js +31 -0
  44. package/pb_migrations/1760000052_deleted_accounts.js +19 -0
  45. package/pb_migrations/1760000053_account_jobs.js +45 -0
  46. package/pb_migrations/1760000054_room_invites.js +39 -0
  47. package/pb_migrations/1760000055_invite_barred.js +16 -0
  48. package/pb_migrations/1760000056_telegram_fetch.js +21 -0
  49. package/pb_public/assets/{access-PB77EH4F.css → access-GPRLOZOO.css} +2 -2
  50. package/pb_public/assets/{access-PB77EH4F.css.map → access-GPRLOZOO.css.map} +2 -2
  51. package/pb_public/assets/access-UK3L54NR.js +2 -0
  52. package/pb_public/assets/access-UK3L54NR.js.map +7 -0
  53. package/pb_public/assets/account-CT2BVMAX.css +2 -0
  54. package/pb_public/assets/account-CT2BVMAX.css.map +7 -0
  55. package/pb_public/assets/account-api-J6A6IYVX.js +2 -0
  56. package/pb_public/assets/account-api-J6A6IYVX.js.map +7 -0
  57. package/pb_public/assets/app-HB3NZHQ2.js +3 -0
  58. package/pb_public/assets/app-HB3NZHQ2.js.map +7 -0
  59. package/pb_public/assets/app-XJ73EU5O.css +2 -0
  60. package/pb_public/assets/app-XJ73EU5O.css.map +7 -0
  61. package/pb_public/assets/chunk-56ACD3V5.js +2 -0
  62. package/pb_public/assets/chunk-56ACD3V5.js.map +7 -0
  63. package/pb_public/assets/chunk-AG73QNUN.js +2 -0
  64. package/pb_public/assets/chunk-AG73QNUN.js.map +7 -0
  65. package/pb_public/assets/chunk-DCLJRQ53.js +2 -0
  66. package/pb_public/assets/chunk-DCLJRQ53.js.map +7 -0
  67. package/pb_public/assets/chunk-DZC4SY4M.js +2 -0
  68. package/pb_public/assets/chunk-DZC4SY4M.js.map +7 -0
  69. package/pb_public/assets/chunk-N2OFGBCZ.js +2 -0
  70. package/pb_public/assets/chunk-N2OFGBCZ.js.map +7 -0
  71. package/pb_public/assets/chunk-OKIIBH7O.js +2 -0
  72. package/pb_public/assets/chunk-OKIIBH7O.js.map +7 -0
  73. package/pb_public/assets/chunk-RPCBA7VF.js +2 -0
  74. package/pb_public/assets/chunk-RPCBA7VF.js.map +7 -0
  75. package/pb_public/assets/chunk-UZDXAORM.js +2 -0
  76. package/pb_public/assets/chunk-UZDXAORM.js.map +7 -0
  77. package/pb_public/assets/chunk-VTOUI25E.js +4 -0
  78. package/pb_public/assets/chunk-VTOUI25E.js.map +7 -0
  79. package/pb_public/assets/chunk-WR25F7FU.js +2 -0
  80. package/pb_public/assets/chunk-WR25F7FU.js.map +7 -0
  81. package/pb_public/assets/{emoji-VA2WCEAC.css → emoji-WWNPWCF3.css} +2 -2
  82. package/pb_public/assets/{emoji-VA2WCEAC.css.map → emoji-WWNPWCF3.css.map} +2 -2
  83. package/pb_public/assets/{emoji-picker-65VVVGYW.js → emoji-picker-K6JTK2GV.js} +4 -4
  84. package/pb_public/assets/emoji-picker-K6JTK2GV.js.map +7 -0
  85. package/pb_public/assets/forward-267HRNPY.js +2 -0
  86. package/pb_public/assets/forward-267HRNPY.js.map +7 -0
  87. package/pb_public/assets/inbox-CLMYESNI.js +2 -0
  88. package/pb_public/assets/inbox-CLMYESNI.js.map +7 -0
  89. package/pb_public/assets/invite-OGT5E2MZ.js +2 -0
  90. package/pb_public/assets/invite-OGT5E2MZ.js.map +7 -0
  91. package/pb_public/assets/invite-api-7G7XPXQW.js +2 -0
  92. package/pb_public/assets/invite-api-7G7XPXQW.js.map +7 -0
  93. package/pb_public/assets/lazy-H3KIJVB5.js +2 -0
  94. package/pb_public/assets/lazy-H3KIJVB5.js.map +7 -0
  95. package/pb_public/assets/login-TK6K4WGB.js +2 -0
  96. package/pb_public/assets/login-TK6K4WGB.js.map +7 -0
  97. package/pb_public/assets/media-WZ4653L5.js +2 -0
  98. package/pb_public/assets/media-WZ4653L5.js.map +7 -0
  99. package/pb_public/assets/mention-suggest-ODJD2IC5.js +2 -0
  100. package/pb_public/assets/mention-suggest-ODJD2IC5.js.map +7 -0
  101. package/pb_public/assets/notify-EPDM772N.js +2 -0
  102. package/pb_public/assets/notify-EPDM772N.js.map +7 -0
  103. package/pb_public/assets/profile-3R6S5QYS.js +2 -0
  104. package/pb_public/assets/profile-3R6S5QYS.js.map +7 -0
  105. package/pb_public/assets/search-WCHOGAJQ.js +2 -0
  106. package/pb_public/assets/search-WCHOGAJQ.js.map +7 -0
  107. package/pb_public/assets/stats-GTO2H6PG.js +2 -0
  108. package/pb_public/assets/stats-GTO2H6PG.js.map +7 -0
  109. package/pb_public/assets/switcher-TFSO45KV.js +2 -0
  110. package/pb_public/assets/switcher-TFSO45KV.js.map +7 -0
  111. package/pb_public/assets/user-search-3HQOCQWL.js +2 -0
  112. package/pb_public/assets/user-search-3HQOCQWL.js.map +7 -0
  113. package/pb_public/assets/viewer-2Y5FJBW4.js +2 -0
  114. package/pb_public/assets/viewer-2Y5FJBW4.js.map +7 -0
  115. package/pb_public/index.html +10 -2
  116. package/pb_public/stats.html +1 -1
  117. package/scripts/service.mjs +201 -0
  118. package/scripts/start.mjs +21 -17
  119. package/pb_hooks/lib/enrich.js +0 -75
  120. package/pb_hooks/lib/lists.js +0 -179
  121. package/pb_hooks/lib/live.js +0 -137
  122. package/pb_hooks/lib/reads.js +0 -183
  123. package/pb_public/assets/access-GUDTDXIP.js +0 -2
  124. package/pb_public/assets/access-GUDTDXIP.js.map +0 -7
  125. package/pb_public/assets/app-3WX5JYL2.js +0 -3
  126. package/pb_public/assets/app-3WX5JYL2.js.map +0 -7
  127. package/pb_public/assets/app-WAFKVN2H.css +0 -2
  128. package/pb_public/assets/app-WAFKVN2H.css.map +0 -7
  129. package/pb_public/assets/emoji-picker-65VVVGYW.js.map +0 -7
  130. package/pb_public/assets/forward-66PELNWT.js +0 -2
  131. package/pb_public/assets/forward-66PELNWT.js.map +0 -7
  132. package/pb_public/assets/inbox-TZJWPRTG.js +0 -2
  133. package/pb_public/assets/inbox-TZJWPRTG.js.map +0 -7
  134. package/pb_public/assets/lazy-4CXRBHHM.js +0 -2
  135. package/pb_public/assets/lazy-4CXRBHHM.js.map +0 -7
  136. package/pb_public/assets/login-G7Y44CJ7.js +0 -2
  137. package/pb_public/assets/login-G7Y44CJ7.js.map +0 -7
  138. package/pb_public/assets/media-FPRU2QH5.js +0 -2
  139. package/pb_public/assets/media-FPRU2QH5.js.map +0 -7
  140. package/pb_public/assets/mention-suggest-R7MXUH6R.js +0 -2
  141. package/pb_public/assets/mention-suggest-R7MXUH6R.js.map +0 -7
  142. package/pb_public/assets/notify-RQ6ZLR46.js +0 -2
  143. package/pb_public/assets/notify-RQ6ZLR46.js.map +0 -7
  144. package/pb_public/assets/profile-2CNVT2KX.js +0 -2
  145. package/pb_public/assets/profile-2CNVT2KX.js.map +0 -7
  146. package/pb_public/assets/search-3UT4HMES.js +0 -2
  147. package/pb_public/assets/search-3UT4HMES.js.map +0 -7
  148. package/pb_public/assets/stats-JX52AQCO.js +0 -2
  149. package/pb_public/assets/stats-JX52AQCO.js.map +0 -7
  150. package/pb_public/assets/switcher-CEUKRLEY.js +0 -2
  151. package/pb_public/assets/switcher-CEUKRLEY.js.map +0 -7
  152. package/pb_public/assets/user-search-7GNEIXMN.js +0 -2
  153. package/pb_public/assets/user-search-7GNEIXMN.js.map +0 -7
  154. package/pb_public/assets/viewer-DXT7SKOU.js +0 -2
  155. package/pb_public/assets/viewer-DXT7SKOU.js.map +0 -7
  156. package/scripts/fetch-pocketbase.sh +0 -63
@@ -50,134 +50,7 @@ function forget(app, roomId) {
50
50
  app.store().remove(`anonymous.${roomId}`);
51
51
  }
52
52
 
53
- /**
54
- * Who an anonymous message shows as: a users record that is never saved, with the room's id and `name`. It takes no DMs,
55
- * so the clients offer none.
56
- * @param {core.App} app
57
- * @param {string} id
58
- * @param {string} name
59
- */
60
- function standIn(app, id, name) {
61
- const user = new Record(app.findCollectionByNameOrId("users"));
62
- user.set("id", id);
63
- user.set("name", name);
64
- user.set("no_dms", true);
65
- return user;
66
- }
67
-
68
- /**
69
- * Put `user` in the message's expand under `field`, in place of what is there (or also when nothing is, `add`): a new
70
- * map, as the expanded record of the real author may be the one other messages of theirs show too.
71
- * @param {core.Record} rec
72
- * @param {string} field
73
- * @param {core.Record} user
74
- * @param {boolean} [add]
75
- */
76
- function setExpanded(rec, field, user, add = false) {
77
- const expand = rec.expand() ?? {};
78
- if (expand[field] == null && !add) return;
79
- /** @type {Record<string, any>} */
80
- const next = {};
81
- for (const k of Object.keys(expand)) next[k] = expand[k];
82
- next[field] = user;
83
- rec.setExpand(next);
84
- }
85
-
86
- /**
87
- * messages enrich, once expanded, for one stamped `anonymous` or `forwarded_anonymous` or quoting one (lib/enrich.js
88
- * isAnonymous): to anyone but its author and superusers, the author is its room, and a forward is from the original's
89
- * room. Only in the answer.
90
- * @param {core.RecordEnrichEvent} e
91
- */
92
- function hide(e) {
93
- const rec = e.record;
94
- const auth = e.requestInfo?.auth;
95
- if (!rec || auth?.isSuperuser()) return;
96
- // The quoted message hid its author when it was fetched, before its own expand (reply_to.author) looked for them.
97
- const quoted = rec.expand()?.reply_to;
98
- if (quoted?.getBool?.("anonymous") && quoted.getString("author") === quoted.getString("room")) {
99
- setExpanded(quoted, "author", standIn(e.app, quoted.getString("room"), roomName(e.app, quoted.getString("room"))), true);
100
- }
101
- const me = auth?.id ?? "";
102
- const author = rec.getString("author");
103
- if (rec.getBool("anonymous") && author && author !== me) {
104
- const room = rec.getString("room");
105
- rec.set("author", room);
106
- setExpanded(rec, "author", standIn(e.app, room, roomName(e.app, room)));
107
- }
108
- const from = rec.getString("forwarded_from");
109
- if (rec.getBool("forwarded_anonymous") && from && from !== me) {
110
- let room = "";
111
- try {
112
- room = rec.getString("forward_of") ? e.app.findRecordById("messages", rec.getString("forward_of")).getString("room") : "";
113
- } catch {
114
- room = ""; // the original is being removed for good
115
- }
116
- const id = room || rec.id;
117
- rec.set("forwarded_from", id);
118
- setExpanded(rec, "forwarded_from", standIn(e.app, id, room ? sourceName(e.app, room) : "Anonymous"));
119
- }
120
- }
121
-
122
- /** Fields whose value says who wrote a message: no one but a superuser filters or sorts on them. */
123
- const AUTHOR_FIELD = /(^|[^a-z0-9])(author|forwarded_from)(?![a-z0-9])/i;
124
- /** A back-relation from users to the messages they wrote: expanded, it would group them by author. */
125
- const AUTHOR_BACK_RELATION = /_via_(author|forwarded_from)(?![a-z0-9_])/i;
126
-
127
- /**
128
- * An author compared with the caller (`author != {:me}`, `reply_to.author = {:me}`): says only which messages are
129
- * the caller's own. Apps from before 2026-10-29 filter so (docs/API.md); `ME` stands for the caller's id.
130
- */
131
- const OWN_AUTHOR = String.raw`\b(author|forwarded_from)\s*(=|!=|\?=|\?!=)\s*(@request\.auth\.id\b|"ME"|'ME')`;
132
-
133
- /**
134
- * Does a filter, sort or expand (as a client sends it) say who wrote a message? Quoted text is a value, not a field.
135
- * @param {{ filter?: unknown, sort?: unknown, expand?: unknown }} q
136
- * @param {string} me the caller's id ("" for guests)
137
- */
138
- function probes(q, me) {
139
- const own = new RegExp(OWN_AUTHOR.replace(/ME/g, me.replace(/[^a-z0-9]/gi, "") || "@"), "gi");
140
- const fields = `${q.filter ?? ""} ${q.sort ?? ""}`.replace(own, "").replace(/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'/g, "''");
141
- return AUTHOR_FIELD.test(fields) || AUTHOR_BACK_RELATION.test(String(q.expand ?? ""));
142
- }
143
-
144
- const REFUSAL = "Messages can't be filtered, sorted or grouped by who wrote them.";
145
-
146
- /**
147
- * A request refused when its query filters, sorts or groups by author (the records API's ?filter, ?sort, ?expand, on any
148
- * collection, as a relation or back-relation can reach messages from any of them; our routes' ?expand). Called by the
149
- * record request hooks (main.pb.js) and by each route that enriches records. Superusers may.
150
- * @param {core.RequestEvent} e
151
- */
152
- function refuseProbes(e) {
153
- // requestInfo, not e.request: the record request hooks' events have no `request` in JS. Its values are decoded
154
- // (%61uthor is "author").
155
- const info = e.requestInfo();
156
- const q = { filter: info.query.filter ?? "", sort: info.query.sort ?? "", expand: info.query.expand ?? "" };
157
- if (!/author|forwarded_from/i.test(`${q.filter} ${q.sort} ${q.expand}`)) return;
158
- if (!probes(q, info.auth?.id ?? "")) return;
159
- if (info.auth?.isSuperuser()) return;
160
- throw new BadRequestError(REFUSAL);
161
- }
162
-
163
- /**
164
- * Realtime subscriptions: the same, for the filter, sort and expand in a subscription's options.
165
- * @param {core.RealtimeSubscribeRequestEvent} e
166
- */
167
- function refuseSubscriptionProbes(e) {
168
- if (e.hasSuperuserAuth()) return;
169
- for (const topic of e.subscriptions ?? []) {
170
- const at = topic.indexOf("?options=");
171
- if (at < 0) continue;
172
- let query = {};
173
- try {
174
- query = JSON.parse(decodeURIComponent(topic.slice(at + "?options=".length)))?.query ?? {};
175
- } catch {
176
- query = {}; // PocketBase ignores options it can't read
177
- }
178
- if (probes(query, e.auth?.id ?? "")) throw new BadRequestError(REFUSAL);
179
- }
180
- }
53
+ // Filters, sorts and expands that would say who wrote a message are refused in Go (server/anonymous.go bindProbes).
181
54
 
182
55
  /**
183
56
  * The media grid's author of an item (lib/media.js list): the room for an anonymous message, as hide does.
@@ -190,4 +63,4 @@ function gridAuthor(e, row) {
190
63
  return { id: row.author, name: row.name };
191
64
  }
192
65
 
193
- module.exports = { hide, forget, roomName, sourceName, refuseProbes, refuseSubscriptionProbes, gridAuthor };
66
+ module.exports = { forget, roomName, sourceName, gridAuthor };
@@ -148,8 +148,7 @@ function originalOf(app, m) {
148
148
  * @param {core.RequestEvent} e
149
149
  */
150
150
  function forward(e) {
151
- // As the records API's (main.pb.js): this page's ?expand mustn't group messages by author (§35).
152
- require(`${__hooks}/lib/anonymous.js`).refuseProbes(e);
151
+ // Its ?expand can't group messages by author: refused before this runs (server/anonymous.go bindProbes, §35).
153
152
  const me = e.auth;
154
153
  if (!me) throw new UnauthorizedError("The request requires a logged-in user.");
155
154
  const what = "Failed to forward the messages.";
@@ -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.");
@@ -91,26 +91,61 @@ function byNames(app, names) {
91
91
  function fromUploads(app, uploads, field = "files") {
92
92
  const { assertImagesFit } = require(`${__hooks}/lib/images.js`);
93
93
  const collection = app.findCollectionByNameOrId("files");
94
- return uploads.map((upload) => {
95
- const original = clipFileName(tidy(unescapeUploadName(upload.originalName)));
96
- upload.originalName = original || upload.name;
97
- const row = new Record(collection);
98
- row.set("file", upload);
99
- const name = upload.name;
100
- row.set("name", (original || name).slice(0, 200));
101
- row.set("video", isVideo(name));
102
- row.set("refs", 0);
103
- if (upload.size > MAX_SIZE) {
104
- throw fieldError(field, `Files can be at most ${MAX_SIZE / 1024 / 1024} MB.`, "validation_file_size_limit");
94
+ /** @type {core.Record[]} */
95
+ const saved = [];
96
+ try {
97
+ for (const upload of uploads) saved.push(fromUpload(app, collection, upload, field, assertImagesFit));
98
+ } catch (err) {
99
+ // Outside a transaction (a message's create request, lib/messages.js prepareCreate): the ones already stored go.
100
+ discard(app, saved);
101
+ throw err;
102
+ }
103
+ return saved;
104
+ }
105
+
106
+ /**
107
+ * fromUploads' one row.
108
+ * @param {core.App} app
109
+ * @param {core.Collection} collection
110
+ * @param {filesystem.File} upload
111
+ * @param {string} field
112
+ * @param {(row: core.Record, key: string, field: string) => Record<string, unknown>} assertImagesFit
113
+ */
114
+ function fromUpload(app, collection, upload, field, assertImagesFit) {
115
+ const original = clipFileName(tidy(unescapeUploadName(upload.originalName)));
116
+ upload.originalName = original || upload.name;
117
+ const row = new Record(collection);
118
+ row.set("file", upload);
119
+ const name = upload.name;
120
+ row.set("name", (original || name).slice(0, 200));
121
+ row.set("video", isVideo(name));
122
+ row.set("refs", 0);
123
+ if (upload.size > MAX_SIZE) {
124
+ throw fieldError(field, `Files can be at most ${MAX_SIZE / 1024 / 1024} MB.`, "validation_file_size_limit");
125
+ }
126
+ const dims = assertImagesFit(row, "file", field);
127
+ if (dims[name]) row.set("dims", dims[name]);
128
+ // The worker makes thumbnails of images and a video's poster; its shape it reads once the poster is there.
129
+ row.set("ready", !isMedia(name));
130
+ row.set("sized", !isVideo(name) && (!isImage(name) || !!dims[name]));
131
+ app.save(row);
132
+ return row;
133
+ }
134
+
135
+ /**
136
+ * Drop new `files` rows nothing came to name (a message's create that failed after its uploads were stored), with
137
+ * what is stored. Best effort: a row left behind is named by nothing, as rows of failed uploads were before.
138
+ * @param {core.App} app
139
+ * @param {core.Record[]} rows
140
+ */
141
+ function discard(app, rows) {
142
+ for (const row of rows) {
143
+ try {
144
+ app.delete(row);
145
+ } catch (err) {
146
+ app.logger().warn("files: an unused upload wasn't deleted", "id", row.id, "error", String(err));
105
147
  }
106
- const dims = assertImagesFit(row, "file", field);
107
- if (dims[name]) row.set("dims", dims[name]);
108
- // The worker makes thumbnails of images and a video's poster; its shape it reads once the poster is there.
109
- row.set("ready", !isMedia(name));
110
- row.set("sized", !isVideo(name) && (!isImage(name) || !!dims[name]));
111
- app.save(row);
112
- return row;
113
- });
148
+ }
114
149
  }
115
150
 
116
151
  /**
@@ -120,11 +155,14 @@ function fromUploads(app, uploads, field = "files") {
120
155
  */
121
156
  function link(app, ids) {
122
157
  if (!ids.length) return;
123
- app
158
+ const res = app
124
159
  .db()
125
160
  .newQuery("UPDATE files SET refs = refs + 1 WHERE id IN (SELECT value FROM json_each({:ids}))")
126
161
  .bind({ ids: JSON.stringify(ids) })
127
162
  .execute();
163
+ // Looked up before the transaction (a create request's collection items, lib/messages.js prepareCreate): one may
164
+ // have gone since.
165
+ if (Number(res.rowsAffected()) !== ids.length) throw fieldError("items", "A collection item is no longer available.");
128
166
  }
129
167
 
130
168
  /**
@@ -190,8 +228,10 @@ function namedBy(app, collection, id) {
190
228
  * @param {core.Record} rec
191
229
  * @param {core.Record[]} rows
192
230
  * @param {Record<string, string>} [sources] stored name → collection id
231
+ * @param {boolean} [later] link them in the message's save (linkPending), not now: a create request sets them
232
+ * before the save's transaction (lib/messages.js setRequestFiles)
193
233
  */
194
- function setMessageFiles(app, rec, rows, sources = {}) {
234
+ function setMessageFiles(app, rec, rows, sources = {}, later = false) {
195
235
  /** @type {core.Record[]} */
196
236
  const list = [];
197
237
  const seen = new Set();
@@ -222,10 +262,24 @@ function setMessageFiles(app, rec, rows, sources = {}) {
222
262
  rec.set("file_names", names);
223
263
  rec.set("file_dims", dims);
224
264
  rec.set("file_sources", from);
225
- link(
226
- app,
227
- list.map((r) => r.id),
228
- );
265
+ const ids = list.map((r) => r.id);
266
+ if (later) rec.set(PENDING, ids);
267
+ else link(app, ids);
268
+ }
269
+
270
+ /** A custom key (neither stored nor sent): the `files` rows a message's save is to link (setMessageFiles `later`). */
271
+ const PENDING = "@link";
272
+
273
+ /**
274
+ * Link what setMessageFiles left to the save of `rec` (main.pb.js, in the save's transaction).
275
+ * @param {core.App} app
276
+ * @param {core.Record} rec
277
+ */
278
+ function linkPending(app, rec) {
279
+ const ids = rec.get(PENDING);
280
+ if (!Array.isArray(ids) || !ids.length) return;
281
+ rec.set(PENDING, null);
282
+ link(app, /** @type {string[]} */ (ids));
229
283
  }
230
284
 
231
285
  /** @param {string} s */
@@ -247,101 +301,11 @@ function attachUploads(app, rec, uploads) {
247
301
  setMessageFiles(app, rec, fromUploads(app, uploads));
248
302
  }
249
303
 
250
- /**
251
- * Does message `msg` (as stored) show stored name `name`: its own, or as a forward, its original's (§21.3)? Never
252
- * once deleted.
253
- * @param {core.App} app
254
- * @param {core.Record} msg
255
- * @param {string} name
256
- */
257
- function messageShows(app, msg, name) {
258
- if (msg.getBool("deleted")) return false;
259
- if (msg.getStringSlice("files").includes(name)) return true;
260
- const id = msg.getString("forward_of");
261
- if (!id) return false;
262
- try {
263
- const original = app.findRecordById("messages", id);
264
- return !original.getBool("deleted") && original.getStringSlice("files").includes(name);
265
- } catch {
266
- return false;
267
- }
268
- }
269
-
270
- /**
271
- * The `files` row that `collection`'s record `id` shows as `name` (a message's attachment, a collection item's file),
272
- * or null when it doesn't show it (any more).
273
- * @param {core.App} app
274
- * @param {string} collection "messages" or "collection_items"
275
- * @param {string} id
276
- * @param {string} name
277
- */
278
- function shownBy(app, collection, id, name) {
279
- let rec;
280
- try {
281
- rec = app.findRecordById(collection, id);
282
- } catch {
283
- return null;
284
- }
285
- const shows = collection === "messages" ? messageShows(app, rec, name) : rec.getString("file") === name;
286
- return shows ? byName(app, name) : null;
287
- }
288
-
289
- /** The images PocketBase makes thumbnails of, and the size it makes for any file field besides the field's own. */
290
- const THUMB_EXT = ["jpg", "jpeg", "png", "gif", "webp"];
291
- const DEFAULT_THUMB = "100x100";
292
-
293
- /**
294
- * GET /api/files/messages/{recordId}/{filename} and /api/files/collection_items/{recordId}/{filename}: a message's or
295
- * a collection item's file, served from its `files` row (§37). Routes of their own, more specific than PocketBase's
296
- * /api/files/{collection}/…, so no other request runs JS for this: a router middleware would hold a JS runtime for every
297
- * request, realtime connections and file downloads too (docs/PERF.md §6). As PocketBase's handler does: `thumb` (one of
298
- * the field's sizes, or 100x100) serves that thumbnail of an image, made when first asked for; `download` makes it an
299
- * attachment; ranges, and the headers that keep a file from running as a page (fs.serve). The token clients still
300
- * send is ignored. 404 when the message or item doesn't show it (deleted, taken out). A file not moved to its row's
301
- * folder yet is served from its old place (`src`), with a thumbnail only if one is there already: those folders have
302
- * the ones that were ever asked for. The `files` rows themselves are served only through these (main.pb.js).
303
- * @param {core.RequestEvent} e
304
- * @param {"messages" | "collection_items"} collection
305
- */
306
- function serve(e, collection) {
307
- const req = e.request;
308
- const id = req?.pathValue("recordId") ?? "";
309
- const name = req?.pathValue("filename") ?? "";
310
- const row = shownBy(e.app, collection, id, name);
311
- if (!row) throw new NotFoundError();
312
- const moved = !row.getString("src");
313
- const key = keyOf(row);
314
- const file = row.getString("file");
315
- const q = req?.url?.query();
316
- const thumb = q?.get("thumb") ?? "";
317
- const sizes = /** @type {any} */ (row.collection().fields.getByName("file")).thumbs ?? [];
318
- const fs = e.app.newFilesystem();
319
- try {
320
- let served = key;
321
- if (thumb && (thumb === DEFAULT_THUMB || sizes.includes(thumb)) && THUMB_EXT.includes(ext(file))) {
322
- const at = thumbKeyOf(key, thumb);
323
- if (fs.exists(at)) served = at;
324
- else if (moved && fs.exists(key)) {
325
- try {
326
- fs.createThumb(key, at, thumb);
327
- served = at;
328
- } catch {
329
- served = key; // as PocketBase does: the file itself when it can't make one
330
- }
331
- }
332
- }
333
- if (served === key && !fs.exists(key)) throw new NotFoundError();
334
- const download = q?.get("download") ?? "";
335
- if (download && download !== "0" && download !== "false") {
336
- e.response.header().set("Content-Disposition", `attachment; filename=${file}`);
337
- }
338
- fs.serve(e.response, /** @type {any} */ (req), served, file);
339
- } finally {
340
- fs.close();
341
- }
342
- }
304
+ // Serving a message's or collection item's file (only while it shows it) is in Go: server/files.go (§37).
343
305
 
344
306
  module.exports = {
307
+ discard,
308
+ linkPending,
345
309
  MAX_FILES,
346
310
  isImage,
347
311
  isVideo,
@@ -362,6 +326,4 @@ module.exports = {
362
326
  namedBy,
363
327
  setMessageFiles,
364
328
  attachUploads,
365
- shownBy,
366
- serve,
367
329
  };
@@ -3,7 +3,7 @@
3
3
  // "@handle" in a message names. The hooks resolve a message's mentions from its text (`messages.mentions`: those named
4
4
  // who can see its room); GET /api/chat/mentionable suggests people as "@" is typed.
5
5
 
6
- const { accessOf, canSee, visibleRoom } = require(`${__hooks}/lib/access.js`);
6
+ const { accessOf, canSee, viewerOf, visibleRoom } = require(`${__hooks}/lib/access.js`);
7
7
  const { fieldError } = require(`${__hooks}/lib/records.js`);
8
8
  const { nameKey } = require(`${__hooks}/lib/text.js`);
9
9
 
@@ -261,7 +261,7 @@ function mentionable(e) {
261
261
  const me = e.auth;
262
262
  if (!me) throw new UnauthorizedError("The request requires a logged-in user.");
263
263
  const q = e.requestInfo().query;
264
- const room = visibleRoom(e.app, typeof q.room === "string" ? q.room : "", me.id);
264
+ const room = visibleRoom(e.app, typeof q.room === "string" ? q.room : "", viewerOf(me));
265
265
  if (!room) throw new NotFoundError("The room doesn't exist.");
266
266
  const typed = normalHandle(typeof q.q === "string" ? q.q : "").slice(0, 32);
267
267
  const key = nameKey(typed);
@@ -1,10 +1,11 @@
1
1
  /// <reference path="../../types/pocketbase.d.ts" />
2
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
3
+ // mentions them, a reply to one of their messages, someone's reactions to one (one row however many emoji they add:
4
+ // its `emoji` is "", the list shows the ones they have on the message now). The messages hooks keep the rows as messages are
4
5
  // made, edited, deleted and reacted to, whichever way (the apps, a linked instance, the Telegram bridge); they go with a
5
6
  // 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
7
  // 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
+ // far they have been looked at, and GET /api/chat/unread (server/unread.go) counts the rest (`inbox`) and the unread mentions and replies
8
9
  // of each room (`mentions`).
9
10
 
10
11
  const { SEES_SQL } = require(`${__hooks}/lib/access.js`);
@@ -13,10 +14,10 @@ const { reactionsOf } = require(`${__hooks}/lib/reactions.js`);
13
14
  const TOPIC = "chat/inbox";
14
15
  /** Most rows one page lists. */
15
16
  const PAGE = 30;
16
- /** The "unseen" count stops here (shown as "99+"). */
17
- const CAP = 100;
18
17
  /** How much of a message's text a row shows. */
19
18
  const SNIPPET = 200;
19
+ /** Most of one person's emoji a reaction row names in `emoji` ("👍🎉❤️😂🔥 +3"); `emojis` has them all. */
20
+ const EMOJI_SHOWN = 5;
20
21
 
21
22
  /**
22
23
  * Does `user` have an inbox? Not a stand-in (a Telegram sender's, §26.3, or another instance's person's, §33.4): they
@@ -27,8 +28,7 @@ const SNIPPET = 200;
27
28
  function hasInbox(app, userId) {
28
29
  if (!userId) return false;
29
30
  try {
30
- const u = app.findRecordById("users", userId);
31
- return !/@(telegram|federation)\.invalid$/.test(u.getString("email"));
31
+ return !require(`${__hooks}/lib/users.js`).isStandIn(app.findRecordById("users", userId));
32
32
  } catch {
33
33
  return false;
34
34
  }
@@ -121,7 +121,8 @@ const before = (rec) => {
121
121
 
122
122
  /**
123
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.
124
+ * theirs; someone's first reaction to a message tells its author (one row for all their reactions to it), and the
125
+ * last of them taken back, no longer does.
125
126
  * @param {core.App} app
126
127
  * @param {core.Record} rec
127
128
  * @param {ReturnType<typeof before>} was
@@ -143,20 +144,12 @@ function messageChanged(app, rec, was) {
143
144
  if (!was.mentions.includes(user) && user !== parent) add(app, { user, kind: "mention", message: rec, actor: author });
144
145
  }
145
146
  }
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
- }
147
+ /** @param {{ emoji: string, users: string[] }[]} list */
148
+ const people = (list) => new Set(list.flatMap((r) => r.users));
149
+ const nowBy = people(reactionsOf(rec));
150
+ const wasBy = people(was.reactions);
151
+ for (const u of nowBy) if (!wasBy.has(u)) add(app, { user: author, kind: "reaction", message: rec, actor: u });
152
+ for (const u of wasBy) if (!nowBy.has(u)) remove(app, rec.id, "kind = 'reaction' && actor = {:a}", { a: u });
160
153
  }
161
154
 
162
155
  /**
@@ -214,38 +207,17 @@ function seenAt(app, user) {
214
207
  }
215
208
  }
216
209
 
217
- /** The rows a person is shown: their room still visible to them, the message not deleted. */
210
+ /** The rows a person is shown: their room still visible to them, the message not deleted. server/unread.go counts by the same. */
218
211
  const VISIBLE_SQL = `FROM inbox i JOIN messages m ON m.id = i.message JOIN rooms r ON r.id = i.room
219
212
  WHERE i.user = {:me} AND m.deleted = FALSE AND ${SEES_SQL}`;
220
213
 
221
214
  /**
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
215
+ * A mention or reply whose message you have read in its room: seen there, so not new in the inbox either (2026-11-10,
216
+ * user: no reading it twice). A reaction is only seen in the inbox: it comes after the message it is on. server/unread.go
217
+ * counts by the same.
226
218
  */
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
- }
219
+ const READ_IN_ROOM_SQL = `(i.kind != 'reaction' AND m.created <= COALESCE((SELECT rr.last_read_at FROM room_reads rr
220
+ WHERE rr.user = {:me} AND rr.room = i.room), ''))`;
249
221
 
250
222
  /** @param {string} s */
251
223
  const snippet = (s) => {
@@ -273,7 +245,9 @@ function shown(app, msg) {
273
245
 
274
246
  /**
275
247
  * 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,
248
+ * (`before`: the last item's `cursor`). Each item: { id, cursor, kind, emoji (a reaction row's: the actor's emoji on
249
+ * the message now, at most EMOJI_SHOWN then " +n"; "" otherwise), emojis (all of them, in the message's order), created, read (a mention or reply read in
250
+ * its room: not new, whatever seen_at says), room, message: { id, text, files,
277
251
  * created }, quote (a reply's: the caller's message it answers, { id, text, files }), actor: { id, name, avatar,
278
252
  * instance } }. In an anonymous room (§35) a mention or reply shows the room, not who wrote it.
279
253
  * @param {core.RequestEvent} e
@@ -285,11 +259,12 @@ function list(e) {
285
259
  const limit = Math.max(1, Math.min(PAGE, Number.parseInt(String(q.limit ?? PAGE), 10) || PAGE));
286
260
  const before = typeof q.before === "string" ? q.before : "";
287
261
  const [bCreated, bId] = before.includes("|") ? before.split("|") : ["", ""];
288
- const rows = arrayOf(new DynamicModel({ id: "", kind: "", emoji: "", created: "", room: "", message: "", actor: "" }));
262
+ const rows = arrayOf(new DynamicModel({ id: "", kind: "", emoji: "", created: "", room: "", message: "", actor: "", read: false }));
289
263
  e.app
290
264
  .db()
291
265
  .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
266
+ `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,
267
+ ${READ_IN_ROOM_SQL} AS read
293
268
  ${VISIBLE_SQL} ${bCreated ? "AND (i.created < {:bc} OR (i.created = {:bc} AND i.id < {:bi}))" : ""}
294
269
  ORDER BY i.created DESC, i.id DESC LIMIT ${limit + 1}`,
295
270
  )
@@ -303,6 +278,15 @@ function list(e) {
303
278
  const items = page.flatMap((row) => {
304
279
  const msg = messages.get(row.message);
305
280
  if (!msg) return [];
281
+ const emojis =
282
+ row.kind === "reaction"
283
+ ? reactionsOf(msg)
284
+ .filter((/** @type {{ emoji: string, users: string[] }} */ r) => r.users.includes(row.actor))
285
+ .map((/** @type {{ emoji: string }} */ r) => r.emoji)
286
+ : [];
287
+ if (row.kind === "reaction" && !emojis.length) return []; // taken back meanwhile: its row goes in the same save
288
+ const extra = emojis.length - EMOJI_SHOWN;
289
+ const emoji = row.kind === "reaction" ? `${emojis.slice(0, EMOJI_SHOWN).join("")}${extra > 0 ? ` +${extra}` : ""}` : row.emoji;
306
290
  const u = actors.get(row.actor);
307
291
  const hidden = row.kind !== "reaction" && msg.getBool("anonymous") && !e.hasSuperuserAuth();
308
292
  const actor = hidden
@@ -323,8 +307,10 @@ function list(e) {
323
307
  id: row.id,
324
308
  cursor: `${row.created}|${row.id}`,
325
309
  kind: row.kind,
326
- emoji: row.emoji,
310
+ emoji,
311
+ emojis,
327
312
  created: row.created,
313
+ read: !!row.read,
328
314
  room: row.room,
329
315
  message: { id: msg.id, created: msg.getString("created"), ...shown(e.app, msg) },
330
316
  quote,
@@ -343,7 +329,7 @@ function list(e) {
343
329
  function markSeen(e) {
344
330
  const me = e.auth;
345
331
  if (!me) throw new UnauthorizedError("The request requires a logged-in user.");
346
- const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body);
332
+ const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body ?? {});
347
333
  const now = new DateTime();
348
334
  let at = now;
349
335
  if (body.at !== undefined) {
@@ -380,4 +366,4 @@ function markSeen(e) {
380
366
  return e.json(200, { seen_at: row.getString("seen_at") });
381
367
  }
382
368
 
383
- module.exports = { TOPIC, before, messageCreated, messageChanged, tell, counts, list, markSeen };
369
+ module.exports = { TOPIC, before, messageCreated, messageChanged, tell, list, markSeen };