chirkle 0.0.0-stage → 0.1.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 (137) hide show
  1. package/LICENSE +674 -0
  2. package/README.md +310 -2
  3. package/package.json +75 -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 +128 -0
  44. package/pb_hooks/telegram/inbound.js +548 -0
  45. package/pb_hooks/telegram/links.js +157 -0
  46. package/pb_hooks/telegram/outbound.js +323 -0
  47. package/pb_hooks/telegram/people.js +166 -0
  48. package/pb_hooks/telegram/rich.js +192 -0
  49. package/pb_hooks/telegram/worker.js +181 -0
  50. package/pb_hooks/telegram.pb.js +47 -0
  51. package/pb_migrations/1760000000_init.js +150 -0
  52. package/pb_migrations/1760000001_qa_fixes.js +69 -0
  53. package/pb_migrations/1760000002_avatars.js +39 -0
  54. package/pb_migrations/1760000003_direct_messages.js +142 -0
  55. package/pb_migrations/1760000004_attachments.js +28 -0
  56. package/pb_migrations/1760000005_file_names.js +16 -0
  57. package/pb_migrations/1760000006_room_reads.js +41 -0
  58. package/pb_migrations/1760000007_replies.js +23 -0
  59. package/pb_migrations/1760000008_lowercase_emails.js +24 -0
  60. package/pb_migrations/1760000009_reactions.js +32 -0
  61. package/pb_migrations/1760000010_fit_thumbs.js +18 -0
  62. package/pb_migrations/1760000011_forwarding.js +39 -0
  63. package/pb_migrations/1760000012_accounts.js +55 -0
  64. package/pb_migrations/1760000013_qa_pass5.js +19 -0
  65. package/pb_migrations/1760000014_room_access.js +96 -0
  66. package/pb_migrations/1760000015_site.js +46 -0
  67. package/pb_migrations/1760000016_forward_refs.js +43 -0
  68. package/pb_migrations/1760000017_no_dms.js +18 -0
  69. package/pb_migrations/1760000018_attachment_limits.js +24 -0
  70. package/pb_migrations/1760000019_telegram.js +109 -0
  71. package/pb_migrations/1760000020_service_messages.js +21 -0
  72. package/pb_migrations/1760000021_forward_view_index.js +41 -0
  73. package/pb_migrations/1760000022_link_previews.js +43 -0
  74. package/pb_migrations/1760000023_room_writers.js +49 -0
  75. package/pb_migrations/1760000024_message_search.js +51 -0
  76. package/pb_migrations/1760000025_search_dotted_i.js +16 -0
  77. package/pb_migrations/1760000026_push.js +67 -0
  78. package/pb_migrations/1760000027_push_tokens_per_user.js +31 -0
  79. package/pb_migrations/1760000028_media_grid_thumbs.js +18 -0
  80. package/pb_migrations/1760000029_media.js +71 -0
  81. package/pb_migrations/1760000030_collections.js +140 -0
  82. package/pb_migrations/1760000031_unread_limit.js +20 -0
  83. package/pb_migrations/1760000032_federation.js +227 -0
  84. package/pb_migrations/1760000033_federation_requests.js +44 -0
  85. package/pb_migrations/1760000034_telegram_parts.js +26 -0
  86. package/pb_migrations/1760000035_telegram_anonymous.js +16 -0
  87. package/pb_migrations/1760000036_chirkle.js +20 -0
  88. package/pb_migrations/1760000037_file_dims.js +35 -0
  89. package/pb_migrations/1760000038_drop_push.js +64 -0
  90. package/pb_migrations/1760000039_anonymous_rooms.js +40 -0
  91. package/pb_migrations/1760000040_moderators.js +42 -0
  92. package/pb_migrations/1760000041_shared_files.js +500 -0
  93. package/pb_migrations/1760000042_files_src.js +17 -0
  94. package/pb_public/assets/access-ALBW2MT2.js +2 -0
  95. package/pb_public/assets/access-ALBW2MT2.js.map +7 -0
  96. package/pb_public/assets/access-PB77EH4F.css +2 -0
  97. package/pb_public/assets/access-PB77EH4F.css.map +7 -0
  98. package/pb_public/assets/app-ECR34OBK.css +2 -0
  99. package/pb_public/assets/app-ECR34OBK.css.map +7 -0
  100. package/pb_public/assets/app-SILEBEXB.js +3 -0
  101. package/pb_public/assets/app-SILEBEXB.js.map +7 -0
  102. package/pb_public/assets/collections-VEOIOCAW.css +2 -0
  103. package/pb_public/assets/collections-VEOIOCAW.css.map +7 -0
  104. package/pb_public/assets/emoji-WSTVXAW5.css +2 -0
  105. package/pb_public/assets/emoji-WSTVXAW5.css.map +7 -0
  106. package/pb_public/assets/emoji-picker-QYRX6NYL.js +609 -0
  107. package/pb_public/assets/emoji-picker-QYRX6NYL.js.map +7 -0
  108. package/pb_public/assets/inter-cyrillic-JEOLYBOO.woff2 +0 -0
  109. package/pb_public/assets/inter-cyrillic-ext-IYF56FF6.woff2 +0 -0
  110. package/pb_public/assets/inter-greek-IRE366VL.woff2 +0 -0
  111. package/pb_public/assets/inter-latin-NRMW37G5.woff2 +0 -0
  112. package/pb_public/assets/inter-latin-ext-HA22NDSG.woff2 +0 -0
  113. package/pb_public/assets/lazy-SCCVSUZO.js +2 -0
  114. package/pb_public/assets/lazy-SCCVSUZO.js.map +7 -0
  115. package/pb_public/assets/media-DH7ECZSF.js +2 -0
  116. package/pb_public/assets/media-DH7ECZSF.js.map +7 -0
  117. package/pb_public/assets/media-L3EYTHKT.css +2 -0
  118. package/pb_public/assets/media-L3EYTHKT.css.map +7 -0
  119. package/pb_public/assets/notify-L6GERFNO.js +2 -0
  120. package/pb_public/assets/notify-L6GERFNO.js.map +7 -0
  121. package/pb_public/assets/search-3UT4HMES.js +2 -0
  122. package/pb_public/assets/search-3UT4HMES.js.map +7 -0
  123. package/pb_public/assets/switcher-CEUKRLEY.js +2 -0
  124. package/pb_public/assets/switcher-CEUKRLEY.js.map +7 -0
  125. package/pb_public/assets/viewer-DXT7SKOU.js +2 -0
  126. package/pb_public/assets/viewer-DXT7SKOU.js.map +7 -0
  127. package/pb_public/assets/viewer-P7GYCBYM.css +2 -0
  128. package/pb_public/assets/viewer-P7GYCBYM.css.map +7 -0
  129. package/pb_public/icons/apple-touch-icon.png +0 -0
  130. package/pb_public/icons/icon-192.png +0 -0
  131. package/pb_public/icons/icon-512.png +0 -0
  132. package/pb_public/icons/icon.svg +1 -0
  133. package/pb_public/icons/maskable-512.png +0 -0
  134. package/pb_public/index.html +21 -0
  135. package/pb_public/sw.js +1 -0
  136. package/scripts/fetch-pocketbase.sh +63 -0
  137. package/scripts/start.mjs +93 -0
@@ -0,0 +1,490 @@
1
+ /// <reference path="../../types/pocketbase.d.ts" />
2
+ // Pairing (DESIGN.md §33.3) and unpairing (§33.7), by superusers in the admin UI (Collections → fed_peers).
3
+ // - Asking: a row with the other instance's origin and a label. It is saved `invited` with a one-time code, and the
4
+ // code goes to that origin (POST /api/fed/request), so only the instance the admin named learns it.
5
+ // - Being asked: the other side checks the request by asking back (POST /api/fed/verify on the asking origin), so a
6
+ // request claiming to be from someone else never shows. It then shows as a `requested` row, with a label suggested
7
+ // from the host.
8
+ // - Accepting: that row's admin sets it active (and the label as they like). This side makes the secret and sends it
9
+ // with the code to POST /api/fed/pair over https; both rows are then active. Deleting a pending row declines (or
10
+ // withdraws) it, and tells the other side.
11
+ // - Both sides asking each other: the second request pairs at once.
12
+ // - Suspending (status → suspended) holds everything until it is active again; deleting the row unpairs.
13
+
14
+ const { fieldError } = require(`${__hooks}/lib/records.js`);
15
+ const { allowPrivate, cleanOrigin, enabled, hostOf, isActive, myHost, newId, origin, originProblem, peerByOrigin, peerHost } = require(
16
+ `${__hooks}/federation/config.js`,
17
+ );
18
+ const { call, errorOf, jsonBody, pairing, target } = require(`${__hooks}/federation/net.js`);
19
+ const { refreshDms } = require(`${__hooks}/federation/people.js`);
20
+ const { endShare, setDown } = require(`${__hooks}/federation/rooms.js`);
21
+
22
+ /** How an invited row's `last_error` starts while its request is to be sent again. */
23
+ const EXPIRED = "Expired: no answer in 7 days. Delete the row and add it again to ask again.";
24
+ const UNREACHED = "Can't be reached yet: ";
25
+ /** How long a request may wait for the other side's admin. */
26
+ const INVITE_MS = 7 * 24 * 60 * 60 * 1000;
27
+ /** The most requests waiting here at once: more are refused (429) until some are accepted or declined. */
28
+ const MAX_REQUESTED = 20;
29
+ const CODE_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789";
30
+ const HEX = "0123456789abcdef";
31
+ /** Host names' first parts that say nothing about which instance it is: "chat.acme.org" is suggested as "acme". */
32
+ const GENERIC = new Set(["chat", "www", "app", "im", "talk", "m", "web"]);
33
+
34
+ /** @param {core.App} app */
35
+ function siteName(app) {
36
+ const found = app.findRecordsByFilter("site", "", "created", 1, 0);
37
+ return found[0]?.getString("title") || "Chirkle";
38
+ }
39
+
40
+ /** Why this instance can't pair now, or "". */
41
+ const offProblem = (/** @type {core.App} */ app) =>
42
+ originProblem() || (enabled(app) ? "" : "Linking is off here: tick `federation` in Collections → site first.");
43
+
44
+ /**
45
+ * fed_peers create and update requests: a clean origin (not this server's), a label as names show it ("Ann (B)").
46
+ * @param {core.RecordRequestEvent} e
47
+ */
48
+ function checkPeer(e) {
49
+ const rec = /** @type {core.Record} */ (e.record);
50
+ const o = cleanOrigin(rec.getString("origin"));
51
+ if (!o) throw fieldError("origin", "The other instance's address, like https://chat.example.org.");
52
+ if (!o.startsWith("https://") && !allowPrivate()) throw fieldError("origin", "Instances are linked over https only.");
53
+ if (hostOf(o) === myHost()) throw fieldError("origin", "That is this instance.");
54
+ rec.set("origin", o);
55
+ const label = rec.getString("label").trim();
56
+ if (!/^[^\s()@]{1,8}$/u.test(label))
57
+ throw fieldError("label", '1 to 8 characters, no spaces or brackets: its people show as "Ann (label)".');
58
+ rec.set("label", label);
59
+ }
60
+
61
+ /**
62
+ * A label for a requested row, until its admin picks one: the host's telling part, cut to 8, made unique.
63
+ * @param {core.App} app
64
+ * @param {string} host
65
+ */
66
+ function suggestLabel(app, host) {
67
+ const parts = host.replace(/:\d+$/, "").split(".");
68
+ const part = parts.find((p, i) => i < parts.length - 1 && !GENERIC.has(p)) || parts[0] || "";
69
+ const base = part.replace(/[^a-z0-9_-]/g, "").slice(0, 8) || "peer";
70
+ const taken = (/** @type {string} */ l) => app.findRecordsByFilter("fed_peers", "label = {:l}", "", 1, 0, { l }).length > 0;
71
+ if (!taken(base)) return base;
72
+ for (let n = 2; n < 10; n++) {
73
+ const l = `${base.slice(0, 7)}${n}`;
74
+ if (!taken(l)) return l;
75
+ }
76
+ return $security.randomStringWithAlphabet(6, "abcdefghijkmnpqrstuvwxyz23456789");
77
+ }
78
+
79
+ /**
80
+ * fed_peers create request: ask the other instance to link (§33.3, step 1), before the row is saved, so the admin hears
81
+ * at once if it refuses (it doesn't link, or lists this instance already). One that can't be reached is saved with
82
+ * `last_error` and asked again by the worker. One that asked this instance too pairs at once.
83
+ * @param {core.RecordRequestEvent} e
84
+ */
85
+ function beforePeerCreate(e) {
86
+ const off = offProblem(e.app);
87
+ if (off) throw fieldError("origin", off);
88
+ checkPeer(e);
89
+ const rec = /** @type {core.Record} */ (e.record);
90
+ const there = peerByOrigin(e.app, rec.getString("origin"));
91
+ if (there?.getString("status") === "requested")
92
+ throw fieldError("origin", "This instance asked to link already: set its row's status to active to accept.");
93
+ if (there) throw fieldError("origin", "This instance is listed already.");
94
+ rec.set("secret", "");
95
+ rec.set("status", "invited");
96
+ rec.set("invite", $security.randomStringWithAlphabet(32, CODE_ALPHABET));
97
+ rec.set("invite_expires", new DateTime(new Date(Date.now() + INVITE_MS).toISOString()));
98
+ rec.set("name", "");
99
+ rec.set("last_ok", "");
100
+ rec.set("last_error", "");
101
+ const r = ask(e.app, rec);
102
+ if (r.outcome === "refused") throw fieldError("origin", r.error.slice(0, 300));
103
+ noteAsked(e.app, rec, r, "origin");
104
+ }
105
+
106
+ /**
107
+ * The app store key an invited row's code is under while its request is out: the other side checks it by asking back
108
+ * (POST /api/fed/verify) before the row is saved.
109
+ * @param {string} o the asked origin
110
+ */
111
+ const ASKING_KEY = (o) => `fed.asking.${o}`;
112
+
113
+ /**
114
+ * @typedef {{ outcome: "sent" | "retry" | "refused", error: string, name: string, code: string }} Asked
115
+ * code: the other side's own code, when it had asked this instance too.
116
+ */
117
+
118
+ /**
119
+ * Send an invited row's code to its origin (POST /api/fed/request), which only the instance at that address can read.
120
+ * @param {core.App} app
121
+ * @param {core.Record} rec
122
+ * @returns {Asked}
123
+ */
124
+ function ask(app, rec) {
125
+ const o = rec.getString("origin");
126
+ try {
127
+ target(o);
128
+ } catch (err) {
129
+ return { outcome: "refused", error: `That address can't be linked with: ${String(err).slice(0, 200)}`, name: "", code: "" };
130
+ }
131
+ /** @type {ReturnType<typeof pairing>} */
132
+ let answer;
133
+ app.store().set(ASKING_KEY(o), rec.getString("invite"));
134
+ try {
135
+ answer = pairing(o, "/api/fed/request", { origin: origin(), code: rec.getString("invite"), name: siteName(app) });
136
+ } catch (err) {
137
+ return { outcome: "retry", error: `${UNREACHED}${String(err).slice(0, 200)}`, name: "", code: "" };
138
+ } finally {
139
+ app.store().remove(ASKING_KEY(o));
140
+ }
141
+ if (answer.status === 200) {
142
+ const body = jsonBody(answer) || {};
143
+ const code = typeof body.code === "string" && /^[A-Za-z0-9]{32}$/.test(body.code) ? body.code : "";
144
+ return { outcome: "sent", error: "", name: String(body.name || "").slice(0, 255), code };
145
+ }
146
+ if (answer.status >= 500 || answer.status === 429)
147
+ return { outcome: "retry", error: `${UNREACHED}${errorOf(answer)}`, name: "", code: "" };
148
+ const error = answer.status === 404 ? "It doesn't take links (not this app, or linking is off there)." : `It refused: ${errorOf(answer)}`;
149
+ return { outcome: "refused", error, name: "", code: "" };
150
+ }
151
+
152
+ /**
153
+ * Note on an invited row how its request went: `last_ok` once delivered, `last_error` else. When the other side had
154
+ * asked too, pair now with its code.
155
+ * @param {core.App} app
156
+ * @param {core.Record} rec
157
+ * @param {Asked} r
158
+ * @param {string} field the field to show a pairing refusal on
159
+ */
160
+ function noteAsked(app, rec, r, field) {
161
+ if (r.code) {
162
+ rec.set("invite", r.code);
163
+ pairNow(app, rec, field);
164
+ return;
165
+ }
166
+ if (r.outcome === "sent") {
167
+ rec.set("last_ok", new DateTime());
168
+ rec.set("last_error", "");
169
+ rec.set("name", r.name);
170
+ } else {
171
+ rec.set("last_error", r.error.slice(0, 1000));
172
+ }
173
+ }
174
+
175
+ /**
176
+ * Accept a requested row (§33.3, step 3): make the secret and send it with the asking side's code. Sets the record
177
+ * active; throws when the other side refuses.
178
+ * @param {core.App} app
179
+ * @param {core.Record} rec
180
+ * @param {string} field the field to show a refusal on
181
+ */
182
+ function pairNow(app, rec, field) {
183
+ const secret = $security.randomStringWithAlphabet(64, HEX);
184
+ /** @type {ReturnType<typeof pairing>} */
185
+ let answer;
186
+ try {
187
+ answer = pairing(rec.getString("origin"), "/api/fed/pair", {
188
+ origin: origin(),
189
+ code: rec.getString("invite"),
190
+ secret,
191
+ name: siteName(app),
192
+ });
193
+ } catch (err) {
194
+ throw fieldError(field, `That instance can't be reached: ${String(err).slice(0, 200)}`);
195
+ }
196
+ if (answer.status !== 200)
197
+ throw fieldError(
198
+ field,
199
+ answer.status === 403
200
+ ? "The request has expired or was withdrawn: ask that instance to send it again."
201
+ : `Pairing failed: ${errorOf(answer)}`,
202
+ );
203
+ const body = jsonBody(answer) || {};
204
+ rec.set("secret", secret);
205
+ rec.set("status", "active");
206
+ rec.set("invite", "");
207
+ rec.set("invite_expires", "");
208
+ if (body.name) rec.set("name", String(body.name).slice(0, 255));
209
+ rec.set("last_ok", new DateTime());
210
+ rec.set("last_error", "");
211
+ }
212
+
213
+ /**
214
+ * fed_peers update request: the origin, secret and code stay as they are. A requested row becomes active by its admin
215
+ * setting it so (which pairs); an invited one only by the other side accepting. Returns what changed, to act on once
216
+ * saved.
217
+ * @param {core.RecordRequestEvent} e
218
+ */
219
+ function beforePeerEdit(e) {
220
+ checkPeer(e);
221
+ const rec = /** @type {core.Record} */ (e.record);
222
+ const orig = rec.original();
223
+ for (const f of ["origin", "secret", "invite", "invite_expires", "name"]) {
224
+ if (rec.getString(f) !== orig.getString(f)) throw fieldError(f, "This field can't be changed.");
225
+ }
226
+ const was = orig.getString("status");
227
+ const now = rec.getString("status");
228
+ if (was !== now) {
229
+ if (was === "invited") throw fieldError("status", "It becomes active once the other instance's admin accepts.");
230
+ if (was === "requested" && now !== "active") throw fieldError("status", "Set it active to accept, or delete the row to decline.");
231
+ if (now === "invited" || now === "requested") throw fieldError("status", "A paired instance is active or suspended.");
232
+ if (was === "requested") {
233
+ const off = offProblem(e.app);
234
+ if (off) throw fieldError("status", off);
235
+ pairNow(e.app, rec, "status");
236
+ }
237
+ }
238
+ return { status: was !== now, dms: rec.getBool("dms") !== orig.getBool("dms") };
239
+ }
240
+
241
+ /**
242
+ * fed_peers update request (saved): suspending holds its queue and shows its rooms as unreachable (§33.7); `dms`
243
+ * opens or closes DMs with its people (§33.5).
244
+ * @param {core.App} app
245
+ * @param {core.Record} peer
246
+ * @param {{ status: boolean, dms: boolean }} changed
247
+ */
248
+ function afterPeerEdit(app, peer, changed) {
249
+ if (changed.status) setDown(app, peer.id, !isActive(peer));
250
+ if (changed.status || changed.dms) refreshDms(app, peer);
251
+ }
252
+
253
+ /**
254
+ * Unpair here (§33.7): every share with the peer ends (mirrors archived, its people out of our rooms), and DMs with its
255
+ * people become read-only. Stand-ins and their messages stay.
256
+ * @param {core.App} app
257
+ * @param {core.Record} peer
258
+ */
259
+ function unpairHere(app, peer) {
260
+ for (const share of app.findRecordsByFilter("fed_shares", "peer = {:p} && state != 'ended'", "created", 0, 0, { p: peer.id })) {
261
+ if (share) endShare(app, share, false);
262
+ }
263
+ peer.set("status", "suspended");
264
+ refreshDms(app, peer); // not active: no DMs
265
+ }
266
+
267
+ /**
268
+ * fed_peers delete request: tell the peer (once, now: its queue goes with the row), then unpair here. A pending row
269
+ * (asked or asking) tells the other side it is withdrawn or declined.
270
+ * @param {core.App} app
271
+ * @param {core.Record} peer
272
+ */
273
+ function beforePeerDelete(app, peer) {
274
+ const st = peer.getString("status");
275
+ if (st === "invited" || st === "requested") {
276
+ try {
277
+ pairing(peer.getString("origin"), "/api/fed/cancel", { origin: origin(), code: peer.getString("invite") }, 5);
278
+ } catch (err) {
279
+ app.logger().warn("federation: cancel not delivered", "peer", peerHost(peer), "error", String(err));
280
+ }
281
+ return;
282
+ }
283
+ if (isActive(peer)) {
284
+ try {
285
+ call(peer, "POST", "/api/fed/inbox", { events: [{ id: newId(), type: "unpair" }] }, { seconds: 5 });
286
+ } catch (err) {
287
+ app.logger().warn("federation: unpair not delivered", "peer", peerHost(peer), "error", String(err));
288
+ }
289
+ }
290
+ unpairHere(app, peer);
291
+ }
292
+
293
+ /**
294
+ * An `unpair` event: the peer's admin unpaired. Unpair here and drop the row.
295
+ * @param {core.App} app
296
+ * @param {core.Record} peer
297
+ */
298
+ function applyUnpair(app, peer) {
299
+ app.runInTransaction((tx) => {
300
+ const fresh = tx.findRecordById("fed_peers", peer.id);
301
+ unpairHere(tx, fresh);
302
+ tx.delete(fresh);
303
+ });
304
+ app.logger().info("federation: unpaired by the peer", "peer", peerHost(peer));
305
+ }
306
+
307
+ /**
308
+ * A pairing request's { origin, code } (unsigned: the code says who it is). Throws 400 for a malformed one.
309
+ * @param {core.RequestEvent} e
310
+ */
311
+ function pairingBody(e) {
312
+ const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body);
313
+ const from = typeof body.origin === "string" ? cleanOrigin(body.origin) : "";
314
+ const code = typeof body.code === "string" ? body.code : "";
315
+ if (!from || !/^[A-Za-z0-9]{32}$/.test(code)) throw new BadRequestError("Missing origin or code.");
316
+ return { from, code, body };
317
+ }
318
+
319
+ /**
320
+ * Is `code` this row's open invite?
321
+ * @param {core.Record | null} peer
322
+ * @param {string} code
323
+ */
324
+ function invites(peer, code) {
325
+ if (peer?.getString("status") !== "invited") return false;
326
+ const want = peer.getString("invite");
327
+ const expires = peer.getDateTime("invite_expires");
328
+ if (!want || !$security.equal(code, want)) return false;
329
+ return !expires.isZero() && expires.time().unixMilli() >= Date.now();
330
+ }
331
+
332
+ /**
333
+ * POST /api/fed/request { origin, code, name }: an instance asking to link (§33.3, step 1). Checked by asking it back
334
+ * (POST /api/fed/verify there) before anything is saved, so only a real request shows. Shows as a requested row; if
335
+ * this side asked that instance already, they pair at once.
336
+ * @param {core.RequestEvent} e
337
+ */
338
+ function request(e) {
339
+ const { from, code, body } = pairingBody(e);
340
+ if (!from.startsWith("https://") && !allowPrivate()) throw new BadRequestError("Instances are linked over https only.");
341
+ if (hostOf(from) === myHost()) throw new BadRequestError("That is this instance.");
342
+ const there = peerByOrigin(e.app, from);
343
+ const st = there?.getString("status") || "";
344
+ if (st === "active" || st === "suspended")
345
+ throw new ApiError(409, `${hostOf(origin())} is paired with it already: its admin can delete the row there to pair again.`);
346
+ if (!there && e.app.findRecordsByFilter("fed_peers", "status = 'requested'", "", MAX_REQUESTED, 0).length >= MAX_REQUESTED)
347
+ throw new TooManyRequestsError("Too many requests are waiting here.");
348
+ /** @type {ReturnType<typeof pairing>} */
349
+ let check;
350
+ try {
351
+ check = pairing(from, "/api/fed/verify", { origin: origin(), code }, 10);
352
+ } catch (err) {
353
+ throw new BadRequestError(`It can't be reached to check the request: ${String(err).slice(0, 200)}`);
354
+ }
355
+ if (check.status !== 200) {
356
+ e.app.logger().warn("federation: a request not confirmed by its origin", "origin", from, "status", check.status);
357
+ throw new ForbiddenError("That instance didn't confirm the request.");
358
+ }
359
+ const name = String(jsonBody(check)?.name || body.name || "").slice(0, 255);
360
+ if (st === "invited" && invites(there, there?.getString("invite") || "")) {
361
+ // Both asked: give it this side's code, and it pairs with it at once (as an admin accepting would).
362
+ e.app.logger().info("federation: both asked", "peer", hostOf(from));
363
+ return e.json(200, { name: siteName(e.app), code: /** @type {core.Record} */ (there).getString("invite") });
364
+ }
365
+ // A request this side sent that expired becomes theirs.
366
+ const rec = there || new Record(e.app.findCollectionByNameOrId("fed_peers"));
367
+ if (!there) {
368
+ rec.set("origin", from);
369
+ rec.set("label", suggestLabel(e.app, hostOf(from)));
370
+ rec.set("dms", false);
371
+ }
372
+ rec.set("status", "requested");
373
+ rec.set("last_ok", "");
374
+ rec.set("invite", code);
375
+ rec.set("invite_expires", new DateTime(new Date(Date.now() + INVITE_MS).toISOString()));
376
+ rec.set("name", name);
377
+ rec.set("last_error", "");
378
+ e.app.save(rec);
379
+ e.app.logger().info("federation: link requested", "origin", from);
380
+ return e.json(200, { name: siteName(e.app) });
381
+ }
382
+
383
+ /**
384
+ * POST /api/fed/verify { origin, code }: did this instance ask `origin` to link, with this code? The asked side's check
385
+ * (§33.3), answered with the site name.
386
+ * @param {core.RequestEvent} e
387
+ */
388
+ function verifyRequest(e) {
389
+ const { from, code } = pairingBody(e);
390
+ const asking = String(e.app.store().get(ASKING_KEY(from)) || "");
391
+ if (!(asking && $security.equal(code, asking)) && !invites(peerByOrigin(e.app, from), code)) throw new ForbiddenError("No such request.");
392
+ return e.json(200, { name: siteName(e.app) });
393
+ }
394
+
395
+ /**
396
+ * POST /api/fed/pair { origin, code, secret, name }: the asked instance accepting the request this one sent (§33.3,
397
+ * step 3). Not signed (there is no secret yet): the code, used once and compared in constant time, says who it is.
398
+ * @param {core.RequestEvent} e
399
+ */
400
+ function pair(e) {
401
+ const { from, code, body } = pairingBody(e);
402
+ const secret = typeof body.secret === "string" ? body.secret : "";
403
+ if (!/^[0-9a-f]{64}$/.test(secret)) throw new BadRequestError("Missing origin, code or secret.");
404
+ let ok = false;
405
+ e.app.runInTransaction((tx) => {
406
+ const peer = peerByOrigin(tx, from);
407
+ if (!peer || !invites(peer, code)) return;
408
+ peer.set("secret", secret);
409
+ peer.set("status", "active");
410
+ peer.set("invite", "");
411
+ peer.set("invite_expires", "");
412
+ peer.set("name", String(body.name || "").slice(0, 255));
413
+ peer.set("last_ok", new DateTime());
414
+ peer.set("last_error", "");
415
+ tx.save(peer);
416
+ ok = true;
417
+ });
418
+ if (!ok) {
419
+ e.app.logger().warn("federation: pairing refused", "origin", from);
420
+ throw new ForbiddenError("This code isn't valid.");
421
+ }
422
+ return e.json(200, { name: siteName(e.app), origin: origin() });
423
+ }
424
+
425
+ /**
426
+ * POST /api/fed/cancel { origin, code }: the other side deleted its pending row. A request it sent is withdrawn (the
427
+ * row goes); one this side sent was declined (noted on the row, for its admin to delete).
428
+ * @param {core.RequestEvent} e
429
+ */
430
+ function cancel(e) {
431
+ const { from, code } = pairingBody(e);
432
+ const peer = peerByOrigin(e.app, from);
433
+ const st = peer?.getString("status");
434
+ if (!peer || (st !== "invited" && st !== "requested") || !$security.equal(code, peer.getString("invite")))
435
+ throw new ForbiddenError("No such request.");
436
+ if (st === "requested") {
437
+ e.app.delete(peer);
438
+ } else {
439
+ peer.set("last_error", `${hostOf(from)} declined.`);
440
+ e.app.save(peer);
441
+ }
442
+ return e.json(200, {});
443
+ }
444
+
445
+ /**
446
+ * The worker's look at pending rows, once a run: requests not delivered yet are sent again, expired ones end (a
447
+ * requested row goes, an invited one says so).
448
+ * @param {core.App} app
449
+ */
450
+ function pendingPass(app) {
451
+ for (const p of app.findRecordsByFilter("fed_peers", "status = 'invited' || status = 'requested'", "created", 0, 0)) {
452
+ if (!p) continue;
453
+ const expires = p.getDateTime("invite_expires");
454
+ const expired = expires.isZero() || expires.time().unixMilli() < Date.now();
455
+ if (p.getString("status") === "requested") {
456
+ if (expired) app.delete(p);
457
+ continue;
458
+ }
459
+ if (expired) {
460
+ if (p.getString("last_error") !== EXPIRED) {
461
+ p.set("last_error", EXPIRED);
462
+ app.save(p);
463
+ }
464
+ } else if (p.getDateTime("last_ok").isZero() && (!p.getString("last_error") || p.getString("last_error").startsWith(UNREACHED))) {
465
+ const r = ask(app, p);
466
+ const code = p.getString("invite");
467
+ try {
468
+ noteAsked(app, p, r, "origin");
469
+ } catch (err) {
470
+ p.set("invite", code);
471
+ p.set("last_error", `Pairing failed: ${String(err).slice(0, 300)}`);
472
+ }
473
+ app.save(p);
474
+ }
475
+ }
476
+ }
477
+
478
+ module.exports = {
479
+ beforePeerCreate,
480
+ beforePeerEdit,
481
+ afterPeerEdit,
482
+ beforePeerDelete,
483
+ applyUnpair,
484
+ request,
485
+ verifyRequest,
486
+ pair,
487
+ cancel,
488
+ pendingPass,
489
+ siteName,
490
+ };