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,247 @@
1
+ /// <reference path="../../types/pocketbase.d.ts" />
2
+ // Between servers (DESIGN.md §33.6): signed requests both ways. Every request carries X-Fed-Origin (who calls),
3
+ // X-Fed-Date (unix seconds, within 5 minutes of now) and X-Fed-Signature, an HMAC of the method, path, date and the
4
+ // body's hash with the pair's secret. Outgoing requests go out with curl as link previews do (lib/previews.js): to
5
+ // the peer's paired origin only, https on a public address (lib/outbound.js checks it, then it is connected to), no
6
+ // redirects, bodies capped, with timeouts. FEDERATION_ALLOW_PRIVATE=1 lets tests use http on 127.0.0.1.
7
+
8
+ const { addressOf, parse, publicHost } = require(`${__hooks}/lib/outbound.js`);
9
+ const { allowPrivate, isActive, origin, peerByOrigin } = require(`${__hooks}/federation/config.js`);
10
+
11
+ /** How far a request's date may be from now. */
12
+ const SKEW_S = 300;
13
+ /** Biggest inbox body (§33.6), and the most of an answer read. */
14
+ const MAX_BODY = 256 * 1024;
15
+ const MAX_ANSWER = 1 << 20;
16
+ const UA = "ChirkleFederation/1.0";
17
+
18
+ /**
19
+ * The signature of a request: hex HMAC-SHA256 of "method\npath\ndate\nsha256(body)".
20
+ * @param {string} secret
21
+ * @param {string} method
22
+ * @param {string} path with its query
23
+ * @param {string} date
24
+ * @param {string} body
25
+ */
26
+ const sign = (secret, method, path, date, body) => $security.hs256(`${method}\n${path}\n${date}\n${$security.sha256(body)}`, secret);
27
+
28
+ /**
29
+ * @param {number} status
30
+ * @param {string} message
31
+ */
32
+ function httpError(status, message) {
33
+ if (status === 401) return new UnauthorizedError(message);
34
+ if (status === 403) return new ForbiddenError(message);
35
+ if (status === 404) return new NotFoundError(message);
36
+ if (status === 429) return new TooManyRequestsError(message);
37
+ if (status === 503) return new ApiError(503, message);
38
+ return new BadRequestError(message);
39
+ }
40
+
41
+ /**
42
+ * Check a server request (§33.6) and return its peer and body. Throws 401 for a request that isn't signed right, 403
43
+ * for a peer that isn't paired, 503 for one suspended here (it keeps its queue and tries again later, §33.7).
44
+ * @param {core.RequestEvent} e
45
+ * @param {number} [max] body bytes
46
+ * @returns {{ peer: core.Record, body: string }}
47
+ */
48
+ function verify(e, max = MAX_BODY) {
49
+ const req = /** @type {any} */ (e.request);
50
+ const from = String(req.header.get("X-Fed-Origin") || "");
51
+ const date = String(req.header.get("X-Fed-Date") || "");
52
+ const got = String(req.header.get("X-Fed-Signature") || "");
53
+ if (!from || !date || !got) throw httpError(401, "Not a signed request.");
54
+ const peer = peerByOrigin(e.app, from);
55
+ const st = peer?.getString("status");
56
+ if (!peer?.getString("secret") || (st !== "active" && st !== "suspended")) throw httpError(403, "Not paired.");
57
+ const at = Number(date);
58
+ if (!Number.isFinite(at) || Math.abs(Date.now() / 1000 - at) > SKEW_S) throw httpError(401, "The request is too old.");
59
+ let body = "";
60
+ if (req.method !== "GET") {
61
+ const bytes = toBytes(req.body, max + 1);
62
+ if (bytes.length > max) throw new ApiError(413, "The request is too big.");
63
+ body = toString(bytes);
64
+ }
65
+ const path = req.url.path + (req.url.rawQuery ? `?${req.url.rawQuery}` : "");
66
+ if (!$security.equal(sign(peer.getString("secret"), req.method, path, date, body), got)) throw httpError(401, "Wrong signature.");
67
+ if (!isActive(peer)) throw httpError(503, "Suspended.");
68
+ return { peer, body };
69
+ }
70
+
71
+ /**
72
+ * Where to connect for an origin: { url parts, ip }. Throws when the server may not go there.
73
+ * @param {string} o
74
+ */
75
+ function target(o) {
76
+ const u = parse(o);
77
+ if (!u) throw new Error("not an http(s) origin");
78
+ if (allowPrivate()) return { u, ip: "" };
79
+ if (u.scheme !== "https") throw new Error("peers are reached over https only");
80
+ if (!publicHost(u.host)) throw new Error("not a public host");
81
+ const ip = addressOf(u.host);
82
+ if (!ip) throw new Error("not a public address");
83
+ return { u, ip };
84
+ }
85
+
86
+ /**
87
+ * @typedef {{ status: number, headers: Record<string, string>, body: string }} Answer
88
+ */
89
+
90
+ /**
91
+ * One request with curl. `out`: a file the body goes to (at most `max` bytes, else it fails); without it the body is
92
+ * read, `max` bytes at most. Throws when there is no answer.
93
+ * @param {string} url
94
+ * @param {string} ip "" to let curl look the host up (FEDERATION_ALLOW_PRIVATE)
95
+ * @param {{ method: string, headers: Record<string, string>, body?: string, out?: string, max: number, seconds: number }} o
96
+ * @returns {Answer}
97
+ */
98
+ function curl(url, ip, o) {
99
+ const tmp = `${$os.tempDir()}/chirkle-fed-${$security.randomString(16)}`;
100
+ const head = `${tmp}.head`;
101
+ const data = `${tmp}.body`;
102
+ const u = /** @type {NonNullable<ReturnType<typeof parse>>} */ (parse(url));
103
+ const args = ["-q", "--silent", "--globoff", "--noproxy", "*", "--proto", "=http,https", "--max-time", o.seconds.toFixed(1)];
104
+ if (ip) args.push("--connect-to", `::${ip}:${u.scheme === "https" ? 443 : 80}`);
105
+ args.push("--user-agent", UA, "--request", o.method);
106
+ for (const [k, v] of Object.entries(o.headers)) args.push("--header", `${k}: ${v}`);
107
+ if (o.body !== undefined) {
108
+ $os.writeFile(data, o.body, /** @type {any} */ (0o600));
109
+ args.push("--data-binary", `@${data}`);
110
+ }
111
+ args.push("--dump-header", head);
112
+ if (o.out) args.push("--max-filesize", String(o.max), "--output", o.out);
113
+ else args.push("--output", "-");
114
+ args.push("--url", url);
115
+ try {
116
+ const cmd = $os.cmd("curl", ...args);
117
+ let body = "";
118
+ if (o.out) {
119
+ try {
120
+ cmd.run();
121
+ } catch {
122
+ // the headers tell (a body over the limit has a status but no file)
123
+ }
124
+ } else {
125
+ const pipe = cmd.stdoutPipe();
126
+ cmd.start();
127
+ try {
128
+ body = toString(toBytes(pipe, o.max));
129
+ } finally {
130
+ try {
131
+ cmd.process?.kill();
132
+ } catch {
133
+ // done already
134
+ }
135
+ try {
136
+ cmd.wait();
137
+ } catch {
138
+ // killed, or failed: the headers tell
139
+ }
140
+ }
141
+ }
142
+ let status = 0;
143
+ /** @type {Record<string, string>} */
144
+ let headers = Object.create(null);
145
+ let raw = "";
146
+ try {
147
+ raw = toString($os.readFile(head));
148
+ } catch {
149
+ raw = "";
150
+ }
151
+ for (const line of raw.split(/\r?\n/)) {
152
+ const s = /^HTTP\/[\d.]+\s+(\d{3})/.exec(line);
153
+ if (s) {
154
+ status = Number(s[1]);
155
+ headers = Object.create(null);
156
+ continue;
157
+ }
158
+ const colon = line.indexOf(":");
159
+ const name = line.slice(0, colon).trim().toLowerCase();
160
+ if (colon > 0 && !(name in headers)) headers[name] = line.slice(colon + 1).trim();
161
+ }
162
+ if (!status) throw new Error("no answer");
163
+ return { status, headers, body };
164
+ } finally {
165
+ for (const f of [head, data]) {
166
+ try {
167
+ $os.remove(f);
168
+ } catch {
169
+ // never written
170
+ }
171
+ }
172
+ }
173
+ }
174
+
175
+ /**
176
+ * A signed request to a peer: path ("/api/fed/inbox"), body (JSON, for POST). Returns the answer; throws when there
177
+ * is none (the peer is down, or can't be reached from here).
178
+ * @param {core.Record} peer
179
+ * @param {string} method
180
+ * @param {string} path with its query
181
+ * @param {unknown} [json]
182
+ * @param {{ out?: string, max?: number, seconds?: number }} [opts]
183
+ * @returns {Answer}
184
+ */
185
+ function call(peer, method, path, json, opts = {}) {
186
+ const { u, ip } = target(peer.getString("origin"));
187
+ const body = json === undefined ? "" : JSON.stringify(json);
188
+ const date = String(Math.floor(Date.now() / 1000));
189
+ /** @type {Record<string, string>} */
190
+ const headers = {
191
+ "X-Fed-Origin": origin(),
192
+ "X-Fed-Date": date,
193
+ "X-Fed-Signature": sign(peer.getString("secret"), method, path, date, body),
194
+ };
195
+ if (json !== undefined) headers["Content-Type"] = "application/json";
196
+ return curl(u.origin + path, ip, {
197
+ method,
198
+ headers,
199
+ body: json === undefined ? undefined : body,
200
+ out: opts.out,
201
+ max: opts.max ?? MAX_ANSWER,
202
+ seconds: opts.seconds ?? 20,
203
+ });
204
+ }
205
+
206
+ /**
207
+ * An unsigned POST for pairing (§33.3): there is no secret yet, the code says who it is. To `o` only, which is where
208
+ * the code may go: it is the address its admin typed in (or the one that asked, checked by asking it back).
209
+ * @param {string} o its origin
210
+ * @param {"/api/fed/request" | "/api/fed/verify" | "/api/fed/pair" | "/api/fed/cancel"} path
211
+ * @param {Record<string, unknown>} json
212
+ * @param {number} [seconds]
213
+ * @returns {Answer}
214
+ */
215
+ function pairing(o, path, json, seconds = 20) {
216
+ const { u, ip } = target(o);
217
+ return curl(`${u.origin}${path}`, ip, {
218
+ method: "POST",
219
+ headers: { "Content-Type": "application/json" },
220
+ body: JSON.stringify(json),
221
+ max: MAX_ANSWER,
222
+ seconds,
223
+ });
224
+ }
225
+
226
+ /**
227
+ * An answer's JSON body, or null.
228
+ * @param {Answer} a
229
+ */
230
+ function jsonBody(a) {
231
+ try {
232
+ return JSON.parse(a.body);
233
+ } catch {
234
+ return null;
235
+ }
236
+ }
237
+
238
+ /**
239
+ * The error message of an answer that isn't 2xx: PocketBase's "message", else the status.
240
+ * @param {Answer} a
241
+ */
242
+ function errorOf(a) {
243
+ const j = jsonBody(a);
244
+ return `${a.status}${j && typeof j.message === "string" ? ` ${j.message.slice(0, 300)}` : ""}`;
245
+ }
246
+
247
+ module.exports = { MAX_BODY, sign, verify, target, call, pairing, jsonBody, errorOf, httpError };