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,276 @@
1
+ /// <reference path="../../types/pocketbase.d.ts" />
2
+ // Linked instances (DESIGN.md §33): this server's origin, global ids, peers, and the queue every part writes to.
3
+
4
+ /** Tests and development only: peers on private addresses and plain http (§33.6). */
5
+ const allowPrivate = () => $os.getenv("FEDERATION_ALLOW_PRIVATE").trim() === "1";
6
+
7
+ /**
8
+ * An origin as stored: scheme and host (and port), lowercased, no path. "" for anything else.
9
+ * @param {string} raw
10
+ */
11
+ function cleanOrigin(raw) {
12
+ const m = /^(https?):\/\/([a-z0-9.-]+(?::\d+)?)\/?$/i.exec(String(raw || "").trim());
13
+ if (!m) return "";
14
+ return `${m[1].toLowerCase()}://${m[2].toLowerCase()}`;
15
+ }
16
+
17
+ /** This server's public origin: the Application URL (Settings → Application), as stored. "" when it isn't one. */
18
+ const origin = () => cleanOrigin($app.settings().meta.appURL);
19
+
20
+ /**
21
+ * Why this server can't link with others, or "" when it can: the Application URL must be its public https address
22
+ * (http and localhost only with FEDERATION_ALLOW_PRIVATE).
23
+ * @param {string} [o] an Application URL to check instead of the current one
24
+ */
25
+ function originProblem(o = origin()) {
26
+ const c = cleanOrigin(o);
27
+ if (!c) return "Set the Application URL (Settings → Application) to this server's public address, like https://chat.example.org.";
28
+ if (allowPrivate()) return "";
29
+ if (!c.startsWith("https://")) return "The Application URL must be this server's public https:// address.";
30
+ if (/^https:\/\/(localhost|127\.|\[?::1)/.test(c)) return "The Application URL must be this server's public address, not localhost.";
31
+ return "";
32
+ }
33
+
34
+ /**
35
+ * Is the module on (§33.2): the site record's `federation` ticked, and an Application URL that can be linked with.
36
+ * Off, the /api/fed/ routes answer 404 and the worker sends nothing.
37
+ * @param {core.App} app
38
+ */
39
+ function enabled(app) {
40
+ if (originProblem()) return false;
41
+ const found = app.findRecordsByFilter("site", "", "created", 1, 0);
42
+ return !!found[0]?.getBool("federation");
43
+ }
44
+
45
+ /**
46
+ * The /api/fed/ routes (and remote-users) while the module is off: 404, as on a server without it.
47
+ * @param {core.App} app
48
+ */
49
+ function requireOn(app) {
50
+ if (!enabled(app)) throw new NotFoundError("Linking with other instances is off here.");
51
+ }
52
+
53
+ const IN_USE_KEY = "fed.inUse";
54
+
55
+ /**
56
+ * Has this instance any fed_peers row at all: the record hooks have nothing to do without one, and skip their queries.
57
+ * Kept in the app store, dropped whenever a row is created or deleted.
58
+ * @param {core.App} app
59
+ */
60
+ function inUse(app) {
61
+ const known = app.store().get(IN_USE_KEY);
62
+ if (known !== undefined && known !== null) return !!known;
63
+ const any = app.findRecordsByFilter("fed_peers", "", "", 1, 0).length > 0;
64
+ app.store().set(IN_USE_KEY, any);
65
+ return any;
66
+ }
67
+
68
+ /** @param {core.App} app */
69
+ const forgetInUse = (app) => app.store().remove(IN_USE_KEY);
70
+
71
+ /**
72
+ * The host of an origin, lowercased, with its port if it has one: "https://B.example" → "b.example".
73
+ * @param {string} o
74
+ */
75
+ const hostOf = (o) =>
76
+ o
77
+ .replace(/^[a-z]+:\/\//i, "")
78
+ .replace(/\/.*$/, "")
79
+ .toLowerCase();
80
+
81
+ /** This server's host, as global ids end in. Changing the Application URL's host is refused while paired (§33.2). */
82
+ const myHost = () => hostOf(origin());
83
+
84
+ /**
85
+ * A thing's global id (§33.6): its id on the instance it was made on, and that instance's host.
86
+ * @param {string} id
87
+ * @param {string} [host]
88
+ */
89
+ const gid = (id, host = myHost()) => `${id}@${host}`;
90
+
91
+ /**
92
+ * A global id split at its last "@": { id, host }. Null for anything else.
93
+ * @param {unknown} g
94
+ */
95
+ function splitGid(g) {
96
+ if (typeof g !== "string") return null;
97
+ const at = g.lastIndexOf("@");
98
+ if (at < 1 || at === g.length - 1 || g.length > 300) return null;
99
+ const id = g.slice(0, at);
100
+ if (!/^[a-z0-9]{1,64}$/i.test(id)) return null;
101
+ return { id, host: g.slice(at + 1).toLowerCase() };
102
+ }
103
+
104
+ /** Is this global id one of this instance's own? @param {string} g */
105
+ const isMine = (g) => splitGid(g)?.host === myHost();
106
+
107
+ /** A new record id, as PocketBase makes them. */
108
+ const newId = () => $security.randomStringWithAlphabet(15, "abcdefghijklmnopqrstuvwxyz0123456789");
109
+
110
+ /**
111
+ * @param {core.App} app
112
+ * @param {string} id
113
+ */
114
+ function peerById(app, id) {
115
+ if (!id) return null;
116
+ try {
117
+ return app.findRecordById("fed_peers", id);
118
+ } catch {
119
+ return null;
120
+ }
121
+ }
122
+
123
+ /**
124
+ * @param {core.App} app
125
+ * @param {string} o
126
+ */
127
+ function peerByOrigin(app, o) {
128
+ try {
129
+ return app.findFirstRecordByFilter("fed_peers", "origin = {:o}", { o: o.replace(/\/+$/, "") });
130
+ } catch {
131
+ return null;
132
+ }
133
+ }
134
+
135
+ /**
136
+ * The peer whose host this is, or null.
137
+ * @param {core.App} app
138
+ * @param {string} host
139
+ */
140
+ function peerByHost(app, host) {
141
+ for (const p of app.findRecordsByFilter("fed_peers", "", "created", 0, 0)) {
142
+ if (p && hostOf(p.getString("origin")) === host) return p;
143
+ }
144
+ return null;
145
+ }
146
+
147
+ /** @param {core.Record} peer */
148
+ const peerHost = (peer) => hostOf(peer.getString("origin"));
149
+
150
+ /** @param {core.Record | null} peer */
151
+ const isActive = (peer) => !!peer && peer.getString("status") === "active";
152
+
153
+ /**
154
+ * The next queue position: microseconds since 1970, one more than the last at least, so rows queued in the same
155
+ * millisecond keep their order.
156
+ * @param {core.App} app
157
+ */
158
+ function nextSeq(app) {
159
+ let seq = 0;
160
+ app.store().setFunc("fed.seq", (old) => {
161
+ seq = Math.max(Number(old || 0) + 1, Date.now() * 1000);
162
+ return seq;
163
+ });
164
+ return seq;
165
+ }
166
+
167
+ /**
168
+ * Queue an event for a peer (§33.8). It goes in the caller's transaction, so it is sent only if what it tells of is
169
+ * saved. Its id is the queue row's: unique here, which is what the peer drops repeats by.
170
+ * @param {core.App} app
171
+ * @param {string} peerId
172
+ * @param {Record<string, unknown>} event
173
+ */
174
+ function enqueue(app, peerId, event) {
175
+ const row = new Record(app.findCollectionByNameOrId("fed_queue"));
176
+ const id = newId();
177
+ row.set("id", id);
178
+ row.set("peer", peerId);
179
+ row.set("op", "event");
180
+ row.set("seq", nextSeq(app));
181
+ row.set("payload", { ...event, id });
182
+ app.save(row);
183
+ }
184
+
185
+ /**
186
+ * Queue other work for the worker: files ("fetch") or an avatar ("avatar") to fetch from a peer.
187
+ * @param {core.App} app
188
+ * @param {string} peerId
189
+ * @param {"fetch" | "avatar"} op
190
+ * @param {Record<string, unknown>} payload
191
+ */
192
+ function enqueueWork(app, peerId, op, payload) {
193
+ const row = new Record(app.findCollectionByNameOrId("fed_queue"));
194
+ row.set("peer", peerId);
195
+ row.set("op", op);
196
+ row.set("seq", nextSeq(app));
197
+ row.set("payload", payload);
198
+ app.save(row);
199
+ }
200
+
201
+ // ---------------------------------------------------------------- what came from a peer
202
+
203
+ /**
204
+ * Saves made for a peer's event say so here, by record id, while they run: the hooks then don't send the change back
205
+ * where it came from (a mirror's own people's changes go to the home; the home's to every mirror but the sender).
206
+ * In the app store, which every hook sees, whichever JS runtime it runs in.
207
+ * @param {string} id
208
+ */
209
+ const ORIGIN_KEY = (id) => `fed.origin.${id}`;
210
+
211
+ /**
212
+ * Run `fn` with record `id`'s saves marked as coming from `peerId`.
213
+ * @template T
214
+ * @param {core.App} app
215
+ * @param {string} id
216
+ * @param {string} peerId
217
+ * @param {() => T} fn
218
+ * @returns {T}
219
+ */
220
+ function fromPeer(app, id, peerId, fn) {
221
+ app.store().set(ORIGIN_KEY(id), peerId);
222
+ try {
223
+ return fn();
224
+ } finally {
225
+ app.store().remove(ORIGIN_KEY(id));
226
+ }
227
+ }
228
+
229
+ /**
230
+ * The peer a save of record `id` is being made for, "" when it is this instance's own.
231
+ * @param {core.App} app
232
+ * @param {string} id
233
+ */
234
+ const originOf = (app, id) => String(app.store().get(ORIGIN_KEY(id)) || "");
235
+
236
+ /**
237
+ * Read a JSON field as a value ({} or [] when empty or bad).
238
+ * @param {core.Record} rec
239
+ * @param {string} field
240
+ * @param {any} fallback
241
+ */
242
+ function jsonOf(rec, field, fallback) {
243
+ try {
244
+ const v = JSON.parse(rec.getString(field) || "null");
245
+ return v === null || v === undefined ? fallback : v;
246
+ } catch {
247
+ return fallback;
248
+ }
249
+ }
250
+
251
+ module.exports = {
252
+ origin,
253
+ allowPrivate,
254
+ cleanOrigin,
255
+ originProblem,
256
+ enabled,
257
+ requireOn,
258
+ inUse,
259
+ forgetInUse,
260
+ hostOf,
261
+ myHost,
262
+ gid,
263
+ splitGid,
264
+ isMine,
265
+ newId,
266
+ peerById,
267
+ peerByOrigin,
268
+ peerByHost,
269
+ peerHost,
270
+ isActive,
271
+ enqueue,
272
+ enqueueWork,
273
+ fromPeer,
274
+ originOf,
275
+ jsonOf,
276
+ };
@@ -0,0 +1,316 @@
1
+ /// <reference path="../../types/pocketbase.d.ts" />
2
+ // The routes peers call (DESIGN.md §33.6), all signed (net.js verify), and the one people call to find someone on a
3
+ // peer (POST /api/chat/remote-users).
4
+ // - POST /api/fed/inbox { events: [...] }: up to 50 events, each applied in a transaction of its own, in order. The
5
+ // answer gives each one's status: 200 (applied, or a repeat), 4xx (refused: the sender drops it and logs why), 5xx
6
+ // (failed for now: the sender tries it again).
7
+ // - GET /api/fed/files/{message}/{file}: a message file, to a peer the message's room is shared with.
8
+ // - GET /api/fed/avatars/{user}: the picture of someone the peer was told of.
9
+ // - GET /api/fed/users?name=&for=dm|member: one person by exact name, for a DM or to add to a shared private room.
10
+
11
+ const { canSee, accessOf } = require(`${__hooks}/lib/access.js`);
12
+ const { canManage } = require(`${__hooks}/lib/moderation.js`);
13
+ const { nameKey } = require(`${__hooks}/lib/text.js`);
14
+ const { gid, isActive, myHost, peerByHost, peerHost, splitGid } = require(`${__hooks}/federation/config.js`);
15
+ const { call, errorOf, jsonBody, verify } = require(`${__hooks}/federation/net.js`);
16
+ const fedMessages = require(`${__hooks}/federation/messages.js`);
17
+ const { applyUnpair } = require(`${__hooks}/federation/peers.js`);
18
+ const { applyUser, peopleFor, profileOf, standInRow, userOf } = require(`${__hooks}/federation/people.js`);
19
+ const fedRooms = require(`${__hooks}/federation/rooms.js`);
20
+ const fedMirror = require(`${__hooks}/federation/mirror.js`);
21
+
22
+ /** Events in one request, and from one peer in a minute (§33.6). */
23
+ const MAX_EVENTS = 50;
24
+ const PER_MINUTE = 600;
25
+
26
+ /**
27
+ * The status to answer a failed event with: a refusal's own, 503 for a busy database (tried again), else 400 (the
28
+ * hooks refused the save: trying again won't help).
29
+ * @param {any} err
30
+ */
31
+ function statusOf(err) {
32
+ const s = Number(err?.status);
33
+ if (s >= 400 && s < 600) return s;
34
+ return /database is locked|busy/i.test(String(err)) ? 503 : 400;
35
+ }
36
+
37
+ /**
38
+ * Apply one event.
39
+ * @param {core.App} app
40
+ * @param {core.Record} peer
41
+ * @param {any} ev
42
+ * @returns {{ status: number, error: string } | void}
43
+ */
44
+ function apply(app, peer, ev) {
45
+ switch (ev.type) {
46
+ case "room":
47
+ return fedMirror.applyRoom(app, peer, ev);
48
+ case "share":
49
+ return fedMirror.applyShare(app, peer, ev);
50
+ case "unshare":
51
+ return fedMirror.applyUnshare(app, peer, ev);
52
+ case "members":
53
+ return fedRooms.applyMembers(app, peer, ev);
54
+ case "message":
55
+ return fedMessages.applyMessage(app, peer, ev);
56
+ case "edit":
57
+ return fedMessages.applyEdit(app, peer, ev);
58
+ case "delete":
59
+ return fedMessages.applyDelete(app, peer, ev);
60
+ case "react":
61
+ return fedMessages.applyReact(app, peer, ev);
62
+ case "reactions":
63
+ return fedMessages.applyReactions(app, peer, ev);
64
+ case "user":
65
+ return applyUser(app, peer, ev);
66
+ default:
67
+ return { status: 400, error: "Unknown event." };
68
+ }
69
+ }
70
+
71
+ /**
72
+ * Count `n` more events from the peer this minute; false when that is over the limit.
73
+ * @param {core.App} app
74
+ * @param {string} peerId
75
+ * @param {number} n
76
+ */
77
+ function withinRate(app, peerId, n) {
78
+ const minute = Math.floor(Date.now() / 60_000);
79
+ let ok = true;
80
+ app.store().setFunc(`fed.rate.${peerId}`, (old) => {
81
+ const [m, count] = String(old || "0 0")
82
+ .split(" ")
83
+ .map(Number);
84
+ const used = m === minute ? count : 0;
85
+ if (used + n > PER_MINUTE) {
86
+ ok = false;
87
+ return old;
88
+ }
89
+ return `${minute} ${used + n}`;
90
+ });
91
+ return ok;
92
+ }
93
+
94
+ /** @param {core.RequestEvent} e */
95
+ function inbox(e) {
96
+ const { peer, body } = verify(e);
97
+ /** @type {any} */
98
+ let parsed;
99
+ try {
100
+ parsed = JSON.parse(body);
101
+ } catch {
102
+ throw new BadRequestError("Not JSON.");
103
+ }
104
+ const events = parsed && Array.isArray(parsed.events) ? parsed.events : null;
105
+ if (!events || events.length > MAX_EVENTS) throw new BadRequestError(`A list of at most ${MAX_EVENTS} events.`);
106
+ if (!withinRate(e.app, peer.id, events.length)) throw new TooManyRequestsError("Too many events; try again in a minute.");
107
+ /** @type {{ id: string, status: number, error?: string }[]} */
108
+ const results = [];
109
+ let unpair = false;
110
+ for (const ev of events) {
111
+ const id = ev && typeof ev.id === "string" ? ev.id.slice(0, 64) : "";
112
+ if (!id || typeof ev.type !== "string") {
113
+ results.push({ id, status: 400, error: "An event has an id and a type." });
114
+ continue;
115
+ }
116
+ if (ev.type === "unpair") {
117
+ unpair = true;
118
+ results.push({ id, status: 200 });
119
+ continue;
120
+ }
121
+ try {
122
+ /** @type {any} */
123
+ let answer = null;
124
+ e.app.runInTransaction((tx) => {
125
+ try {
126
+ tx.findFirstRecordByFilter("fed_seen", "peer = {:p} && event = {:e}", { p: peer.id, e: id });
127
+ return; // a repeat
128
+ } catch {
129
+ // new
130
+ }
131
+ const seen = new Record(tx.findCollectionByNameOrId("fed_seen"));
132
+ seen.set("peer", peer.id);
133
+ seen.set("event", id);
134
+ tx.save(seen);
135
+ answer = apply(tx, peer, ev);
136
+ });
137
+ results.push(answer ? { id, ...answer } : { id, status: 200 });
138
+ } catch (err) {
139
+ const status = statusOf(err);
140
+ const error = String(/** @type {any} */ (err)?.message || err).slice(0, 300);
141
+ e.app.logger().warn("federation: event refused", "peer", peerHost(peer), "type", ev.type, "status", status, "error", error);
142
+ results.push({ id, status, error });
143
+ }
144
+ }
145
+ if (unpair) applyUnpair(e.app, peer);
146
+ return e.json(200, { results });
147
+ }
148
+
149
+ /**
150
+ * GET /api/fed/files/{message}/{file}: a file of a message in a room shared with the peer (as the home, or as its
151
+ * mirror's home). A forward's are its original's (§33.5).
152
+ * @param {core.RequestEvent} e
153
+ */
154
+ function file(e) {
155
+ const { peer } = verify(e);
156
+ const id = e.request?.pathValue("message") ?? "";
157
+ const name = e.request?.pathValue("file") ?? "";
158
+ let msg;
159
+ try {
160
+ msg = e.app.findRecordById("messages", id);
161
+ } catch {
162
+ throw new NotFoundError();
163
+ }
164
+ const room = e.app.findRecordById("rooms", msg.getString("room"));
165
+ const shared =
166
+ room.getString("peer") === peer.id ||
167
+ e.app.findRecordsByFilter("fed_shares", "room = {:r} && peer = {:p} && state = 'active'", "", 1, 0, { r: room.id, p: peer.id }).length >
168
+ 0;
169
+ if (!shared || msg.getBool("deleted")) throw new NotFoundError();
170
+ let src = msg;
171
+ if (msg.getString("forward_of")) {
172
+ try {
173
+ src = e.app.findRecordById("messages", msg.getString("forward_of"));
174
+ } catch {
175
+ throw new NotFoundError();
176
+ }
177
+ }
178
+ if (!src.getStringSlice("files").includes(name)) throw new NotFoundError();
179
+ // Its shared file (§37).
180
+ const files = require(`${__hooks}/lib/files.js`);
181
+ const row = files.byName(e.app, name);
182
+ if (!row) throw new NotFoundError();
183
+ const fs = e.app.newFilesystem();
184
+ try {
185
+ fs.serve(e.response, /** @type {any} */ (e.request), files.keyOf(row), name);
186
+ } finally {
187
+ fs.close();
188
+ }
189
+ }
190
+
191
+ /**
192
+ * GET /api/fed/avatars/{user}: the picture of someone the peer was told of.
193
+ * @param {core.RequestEvent} e
194
+ */
195
+ function avatar(e) {
196
+ const { peer } = verify(e);
197
+ const id = e.request?.pathValue("user") ?? "";
198
+ let user;
199
+ try {
200
+ user = e.app.findRecordById("users", id);
201
+ e.app.findFirstRecordByFilter("fed_people", "peer = {:p} && user = {:u} && kind = 'known'", { p: peer.id, u: id });
202
+ } catch {
203
+ throw new NotFoundError();
204
+ }
205
+ const name = user.getString("avatar");
206
+ if (!name) throw new NotFoundError();
207
+ const fs = e.app.newFilesystem();
208
+ try {
209
+ fs.serve(e.response, /** @type {any} */ (e.request), `${user.baseFilesPath()}/${name}`, name);
210
+ } finally {
211
+ fs.close();
212
+ }
213
+ }
214
+
215
+ /**
216
+ * GET /api/fed/users?name=&for=dm|member: one of this instance's own people by their exact name (never a list, so
217
+ * nobody can go through another instance's people, §33.5). For a DM, only while DMs with the peer are on and they take
218
+ * DMs; to add to a room, only while a room is shared with the peer.
219
+ * @param {core.RequestEvent} e
220
+ */
221
+ function lookup(e) {
222
+ const { peer } = verify(e);
223
+ const q = e.requestInfo().query;
224
+ const key = nameKey(String(q.name || "").trim());
225
+ const forDm = q.for !== "member";
226
+ if (!key) throw new NotFoundError();
227
+ let user;
228
+ try {
229
+ user = e.app.findFirstRecordByFilter("users", "name_key = {:k}", { k: key });
230
+ } catch {
231
+ throw new NotFoundError();
232
+ }
233
+ if (standInRow(e.app, user.id)) throw new NotFoundError();
234
+ if (forDm && (!peer.getBool("dms") || user.getBool("no_dms"))) throw new NotFoundError();
235
+ if (!forDm && !e.app.findRecordsByFilter("fed_shares", "peer = {:p} && state = 'active'", "", 1, 0, { p: peer.id }).length) {
236
+ throw new NotFoundError();
237
+ }
238
+ peopleFor(e.app, peer, [user.id]); // noted as known
239
+ return e.json(200, { id: gid(user.id), profile: profileOf(e.app, user.id) });
240
+ }
241
+
242
+ /**
243
+ * POST /api/chat/remote-users { address, room? } → a person on a linked instance, as a user here (their stand-in):
244
+ * `name@host`, looked up there by exact name (§33.5). With `room`, to add them to that private room, which must be
245
+ * the caller's, here, and shared with their instance; without, to message them.
246
+ * @param {core.RequestEvent} e
247
+ */
248
+ function remoteUser(e) {
249
+ const me = e.auth;
250
+ if (!me) throw new UnauthorizedError("The request requires a logged-in user.");
251
+ const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body);
252
+ const address = typeof body.address === "string" ? body.address.trim() : "";
253
+ const at = address.lastIndexOf("@");
254
+ const name = at > 0 ? address.slice(0, at).trim() : "";
255
+ const host =
256
+ at > 0
257
+ ? address
258
+ .slice(at + 1)
259
+ .trim()
260
+ .toLowerCase()
261
+ : "";
262
+ const bad = (/** @type {string} */ msg) =>
263
+ new BadRequestError("Failed to find them.", { address: new ValidationError("validation_invalid_value", msg) });
264
+ if (!name || !host) throw bad("Write it as name@instance, like ann@chat.example.org.");
265
+ if (host === myHost()) throw bad("They are on this instance: find them by name.");
266
+ const peer = peerByHost(e.app, host);
267
+ if (!peer || !isActive(peer)) throw bad(`This instance isn't linked to ${host}.`);
268
+ const roomId = typeof body.room === "string" ? body.room : "";
269
+ if (roomId) {
270
+ let room;
271
+ try {
272
+ room = e.app.findRecordById("rooms", roomId);
273
+ } catch {
274
+ throw new NotFoundError("The room doesn't exist.");
275
+ }
276
+ if (!canSee(accessOf(room), me.id)) throw new NotFoundError("The room doesn't exist.");
277
+ if (!canManage(room, me) || room.getString("peer"))
278
+ throw new ForbiddenError("Only the room's creator or a moderator adds people to it.");
279
+ const shared = e.app.findRecordsByFilter("fed_shares", "room = {:r} && peer = {:p} && state = 'active'", "", 1, 0, {
280
+ r: room.id,
281
+ p: peer.id,
282
+ });
283
+ if (!shared.length) throw bad(`This room isn't shared with ${host}.`);
284
+ } else if (!peer.getBool("dms")) {
285
+ throw bad(`Direct messages with people on ${host} are off.`);
286
+ }
287
+ /** @type {ReturnType<typeof call>} */
288
+ let answer;
289
+ try {
290
+ answer = call(peer, "GET", `/api/fed/users?name=${encodeURIComponent(name)}&for=${roomId ? "member" : "dm"}`, undefined, {
291
+ seconds: 10,
292
+ });
293
+ } catch {
294
+ throw bad(`Can't reach ${host} right now.`);
295
+ }
296
+ if (answer.status === 404)
297
+ throw bad(roomId ? `There's nobody called ${name} on ${host}.` : `There's nobody called ${name} on ${host} who takes direct messages.`);
298
+ if (answer.status !== 200) {
299
+ e.app.logger().warn("federation: lookup failed", "peer", host, "error", errorOf(answer));
300
+ throw bad(`Can't reach ${host} right now.`);
301
+ }
302
+ const found = jsonBody(answer) || {};
303
+ if (splitGid(found.id)?.host !== peerHost(peer)) throw bad(`Got an unexpected answer from ${host}.`);
304
+ const id = userOf(e.app, peer, found.id, { [found.id]: found.profile || {} });
305
+ if (!id) throw bad(`Got an unexpected answer from ${host}.`);
306
+ const u = e.app.findRecordById("users", id);
307
+ return e.json(200, {
308
+ id: u.id,
309
+ name: u.getString("name"),
310
+ avatar: u.getString("avatar"),
311
+ no_dms: u.getBool("no_dms"),
312
+ instance: u.getString("instance"),
313
+ });
314
+ }
315
+
316
+ module.exports = { inbox, file, avatar, lookup, remoteUser };