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,116 @@
1
+ /// <reference path="../../types/pocketbase.d.ts" />
2
+ // Where the server may go (DESIGN.md §28, §33): link previews (lib/previews.js) and linked instances (federation/net.js)
3
+ // fetch from addresses anyone can give, so only public web addresses: http(s) on the default port, a host name with a
4
+ // dot that isn't a local one, or a public IPv4 address; never userinfo or IPv6 literals. A name is looked up first
5
+ // (getent) and all its addresses must be public; the caller then connects to the one checked and no other. Hosts in
6
+ // LINK_PREVIEWS_ALLOW_HOSTS (comma-separated, host or host:port; tests) are let through without checks.
7
+
8
+ const LOOKUP_TIMEOUT = 3;
9
+
10
+ /**
11
+ * An http(s) URL split up, or null when it isn't one. Host lowercased, with its port unless it is the default one.
12
+ * @param {string} url
13
+ */
14
+ function parse(url) {
15
+ const m = /^(https?):\/\/([^/?#]*)([^#]*)/i.exec(url);
16
+ if (!m) return null;
17
+ const scheme = m[1].toLowerCase();
18
+ let host = m[2].toLowerCase();
19
+ const port = /:(\d*)$/.exec(host);
20
+ if (port) {
21
+ if (!port[1] || port[1] === (scheme === "https" ? "443" : "80")) host = host.slice(0, -port[0].length);
22
+ }
23
+ if (!host || /[@[\]\\%\s]/.test(host)) return null;
24
+ return { scheme, host, origin: `${scheme}://${host}`, path: m[3] || "/" };
25
+ }
26
+
27
+ const LOCAL = /(^|\.)(localhost|local|localdomain|internal|intranet|lan|home\.arpa)$/;
28
+ const IPV4 = /^\d+\.\d+\.\d+\.\d+$/;
29
+
30
+ /** LINK_PREVIEWS_ALLOW_HOSTS: fetched without checks (tests). */
31
+ const allowedHosts = () =>
32
+ $os
33
+ .getenv("LINK_PREVIEWS_ALLOW_HOSTS")
34
+ .split(",")
35
+ .map((h) => h.trim().toLowerCase())
36
+ .filter(Boolean);
37
+
38
+ /**
39
+ * May the server fetch from `host`? A public-looking name (its addresses are checked when it is fetched), or a
40
+ * public IPv4 address.
41
+ * @param {string} host
42
+ */
43
+ function publicHost(host) {
44
+ if (allowedHosts().includes(host)) return true;
45
+ if (/:\d+$/.test(host)) return false; // not the default port
46
+ const h = host.replace(/\.$/, "");
47
+ if (IPV4.test(h)) return publicIPv4(h);
48
+ // A name: ASCII labels that don't start with "-" (it goes to getent and curl as an argument), a dot, a last label of
49
+ // letters (not 0x7f.1 or 2130706433), and not a local one.
50
+ return (
51
+ h.length <= 253 &&
52
+ h.split(".").every((l) => /^[a-z0-9_][a-z0-9_-]*$/.test(l)) &&
53
+ /\.[a-z][a-z0-9-]*$|\.xn--[a-z0-9-]+$/.test(h) &&
54
+ !LOCAL.test(h)
55
+ );
56
+ }
57
+
58
+ /**
59
+ * A public IPv4 address, in plain decimal: "0177.0.0.1" is 127.0.0.1 to curl, so a leading zero is refused.
60
+ * @param {string} ip
61
+ */
62
+ function publicIPv4(ip) {
63
+ if (!IPV4.test(ip) || /(^|\.)0\d/.test(ip)) return false;
64
+ const [a, b, c, d] = ip.split(".").map(Number);
65
+ if ([a, b, c, d].some((n) => n > 255)) return false;
66
+ return !(
67
+ a === 0 ||
68
+ a === 10 ||
69
+ a === 127 ||
70
+ (a === 100 && b >= 64 && b < 128) ||
71
+ (a === 169 && b === 254) ||
72
+ (a === 172 && b >= 16 && b < 32) ||
73
+ (a === 192 && b === 168) ||
74
+ (a === 192 && b === 0 && (c === 0 || c === 2)) ||
75
+ (a === 198 && (b === 18 || b === 19)) ||
76
+ (a === 198 && b === 51 && c === 100) ||
77
+ (a === 203 && b === 0 && c === 113) ||
78
+ a >= 224
79
+ );
80
+ }
81
+
82
+ /**
83
+ * The address to connect to for a public host: an IPv4 address as is; a name's first address, looked up as the
84
+ * system does (getent), and "" when any of its addresses isn't public (a name may answer with an inward one among
85
+ * others). Throws when the lookup fails.
86
+ * @param {string} host
87
+ */
88
+ function addressOf(host) {
89
+ const h = host.replace(/\.$/, "");
90
+ if (IPV4.test(h)) return publicIPv4(h) ? h : "";
91
+ const out = toString($os.cmd("timeout", String(LOOKUP_TIMEOUT), "getent", "ahostsv4", h).output());
92
+ const ips = out
93
+ .split("\n")
94
+ .map((line) => line.split(/\s/)[0])
95
+ .filter((ip) => IPV4.test(ip));
96
+ return ips.length && ips.every(publicIPv4) ? ips[0] : "";
97
+ }
98
+
99
+ /**
100
+ * `ref` (an href from a page, a redirect's Location) against the page's URL.
101
+ * @param {string} ref
102
+ * @param {string} base
103
+ */
104
+ function resolve(ref, base) {
105
+ const r = ref.trim();
106
+ const b = parse(base);
107
+ if (!b || !r || /^data:/i.test(r)) return "";
108
+ if (/^https?:\/\//i.test(r)) return r;
109
+ if (/^[a-z][a-z0-9+.-]*:/i.test(r)) return "";
110
+ if (r.startsWith("//")) return `${b.scheme}:${r}`;
111
+ if (r.startsWith("/")) return b.origin + r;
112
+ const dir = b.path.replace(/[?].*$/, "").replace(/[^/]*$/, "");
113
+ return b.origin + (dir || "/") + r;
114
+ }
115
+
116
+ module.exports = { parse, allowedHosts, publicHost, publicIPv4, addressOf, resolve };
@@ -0,0 +1,171 @@
1
+ /// <reference path="../../types/pocketbase.d.ts" />
2
+ // Reading a fetched page for its link preview (DESIGN.md §28): its title, icon link and charset, and an icon as a data:
3
+ // URL. Pure: lib/previews.js fetches.
4
+
5
+ const { tidy } = require(`${__hooks}/lib/text.js`);
6
+
7
+ const MAX_TITLE = 200;
8
+ /** Of a title (or og:title) as written, only the start is cleaned: plenty for MAX_TITLE characters. */
9
+ const MAX_RAW_TITLE = 4096;
10
+
11
+ /** @typedef {{ headers: Record<string, string>, body: any }} Fetched What was fetched (lib/previews.js Response). */
12
+
13
+ /** @type {Record<string, string>} */
14
+ const ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " ", ndash: "–", mdash: "—", hellip: "…" };
15
+
16
+ /** @param {string} s */
17
+ function decode(s) {
18
+ return s.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (all, e) => {
19
+ if (e[0] !== "#") return ENTITIES[e.toLowerCase()] ?? all;
20
+ const n = e[1] === "x" || e[1] === "X" ? Number.parseInt(e.slice(2), 16) : Number(e.slice(1));
21
+ return n > 0 && n <= 0x10ffff ? String.fromCodePoint(n) : all;
22
+ });
23
+ }
24
+
25
+ /**
26
+ * A title as shown: entities decoded, no control or bidi characters (a page's title is anyone's text: "‮" would
27
+ * turn the rest of the line around, QA BUG-110), whitespace collapsed, cut at MAX_TITLE.
28
+ * @param {string} s
29
+ */
30
+ function clean(s) {
31
+ const t = tidy(decode(s.slice(0, MAX_RAW_TITLE)));
32
+ const chars = [...t];
33
+ return chars.length > MAX_TITLE
34
+ ? `${chars
35
+ .slice(0, MAX_TITLE - 1)
36
+ .join("")
37
+ .trimEnd()}…`
38
+ : t;
39
+ }
40
+
41
+ // A page is anyone's text, so it is read in one pass, never with a regex that can try again from every "<": a page of
42
+ // "<meta <meta …" kept the worker busy for minutes.
43
+
44
+ /**
45
+ * The page's <meta> and <link> tags, "<" to ">". A tag that never ends ends the search: no tag after it could.
46
+ * @param {string} html
47
+ */
48
+ function tags(html) {
49
+ /** @type {string[]} */
50
+ const out = [];
51
+ const start = /<(?:meta|link)\b/gi;
52
+ for (let m = start.exec(html); m; m = start.exec(html)) {
53
+ const end = html.indexOf(">", m.index);
54
+ if (end < 0) break;
55
+ out.push(html.slice(m.index, end + 1));
56
+ start.lastIndex = end + 1;
57
+ }
58
+ return out;
59
+ }
60
+
61
+ const SPACE = " \t\n\r\f";
62
+
63
+ /**
64
+ * A tag's attributes, names lowercased, the first of each.
65
+ * @param {string} tag
66
+ */
67
+ function attrs(tag) {
68
+ /** @type {Record<string, string>} */
69
+ const out = Object.create(null);
70
+ const n = tag.length;
71
+ let i = 1;
72
+ while (i < n && !`${SPACE}/>`.includes(tag[i])) i++; // the tag's name
73
+ while (i < n) {
74
+ while (i < n && `${SPACE}/`.includes(tag[i])) i++;
75
+ if (i >= n || tag[i] === ">") break;
76
+ const from = i;
77
+ while (i < n && !`${SPACE}=/>`.includes(tag[i])) i++;
78
+ if (i === from) {
79
+ i++; // a stray "="
80
+ continue;
81
+ }
82
+ const name = tag.slice(from, i).toLowerCase();
83
+ while (i < n && SPACE.includes(tag[i])) i++;
84
+ let value = "";
85
+ if (tag[i] === "=") {
86
+ i++;
87
+ while (i < n && SPACE.includes(tag[i])) i++;
88
+ const q = tag[i];
89
+ if (q === '"' || q === "'") {
90
+ const end = tag.indexOf(q, i + 1);
91
+ value = tag.slice(i + 1, end < 0 ? n : end);
92
+ i = end < 0 ? n : end + 1;
93
+ } else {
94
+ const at = i;
95
+ while (i < n && !`${SPACE}>`.includes(tag[i])) i++;
96
+ value = tag.slice(at, i);
97
+ }
98
+ }
99
+ if (!(name in out)) out[name] = value;
100
+ }
101
+ return out;
102
+ }
103
+
104
+ /**
105
+ * The text of the page's first <title>, "" when there is none.
106
+ * @param {string} html
107
+ */
108
+ function titleOf(html) {
109
+ const open = /<title\b/i.exec(html);
110
+ const start = open ? html.indexOf(">", open.index) : -1;
111
+ if (start < 0) return "";
112
+ const close = /<\/title\s*>/gi;
113
+ close.lastIndex = start + 1;
114
+ const end = close.exec(html);
115
+ return end ? html.slice(start + 1, end.index) : "";
116
+ }
117
+
118
+ /**
119
+ * A page's text: UTF-8, or Latin-1 (and Windows-1252, near enough) byte for byte. null for any other charset.
120
+ * @param {Fetched} res
121
+ */
122
+ function pageText(res) {
123
+ const body = res.body || [];
124
+ const text = toString(body); // at most PAGE_BYTES: all that was read
125
+ let charset = /charset=["']?([\w-]+)/i.exec(res.headers["content-type"] || "")?.[1];
126
+ if (!charset) {
127
+ for (const tag of tags(text.slice(0, 4096))) {
128
+ const a = attrs(tag);
129
+ charset = a.charset || /charset=([\w-]+)/i.exec(a.content || "")?.[1];
130
+ if (charset) break;
131
+ }
132
+ }
133
+ charset = (charset || "utf-8").toLowerCase();
134
+ if (charset === "utf-8" || charset === "utf8" || charset === "us-ascii") return text;
135
+ if (!/^(iso-8859-1|latin1|windows-1252|cp1252)$/.test(charset)) return null;
136
+ let s = "";
137
+ for (let i = 0; i < body.length; i++) s += String.fromCharCode(body[i]);
138
+ return s;
139
+ }
140
+
141
+ const B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
142
+
143
+ /** @param {ArrayLike<number>} bytes */
144
+ function base64(bytes) {
145
+ let out = "";
146
+ for (let i = 0; i < bytes.length; i += 3) {
147
+ const n = (bytes[i] << 16) | ((bytes[i + 1] ?? 0) << 8) | (bytes[i + 2] ?? 0);
148
+ out += B64[(n >> 18) & 63] + B64[(n >> 12) & 63];
149
+ out += i + 1 < bytes.length ? B64[(n >> 6) & 63] : "=";
150
+ out += i + 2 < bytes.length ? B64[n & 63] : "=";
151
+ }
152
+ return out;
153
+ }
154
+
155
+ /**
156
+ * An image's type: the one it is served as, else what its first bytes say.
157
+ * @param {Fetched} res
158
+ * @param {ArrayLike<number>} b
159
+ */
160
+ function imageType(res, b) {
161
+ const served = (res.headers["content-type"] || "").split(";")[0].trim().toLowerCase();
162
+ if (/^image\/[a-z0-9.+-]+$/.test(served)) return served;
163
+ if (b[0] === 0x89 && b[1] === 0x50) return "image/png";
164
+ if (b[0] === 0 && b[1] === 0 && b[2] === 1 && b[3] === 0) return "image/x-icon";
165
+ if (b[0] === 0x47 && b[1] === 0x49) return "image/gif";
166
+ if (b[0] === 0xff && b[1] === 0xd8) return "image/jpeg";
167
+ if (/^\s*<(\?xml|svg)/.test(toString(b).slice(0, 64))) return "image/svg+xml";
168
+ return "";
169
+ }
170
+
171
+ module.exports = { decode, clean, tags, attrs, titleOf, pageText, base64, imageType };
@@ -0,0 +1,346 @@
1
+ /// <reference path="../../types/pocketbase.d.ts" />
2
+ // Link previews (DESIGN.md §28): under a message, a line for each link in it, the page's favicon and title. A new
3
+ // message, or an edit of the text, queues it (link_queue, in the save's transaction); a worker started by a cron job
4
+ // fetches the pages and saves `previews` on the message, which reaches everyone live as an update. Off with
5
+ // LINK_PREVIEWS=off.
6
+ //
7
+ // The server fetches what anyone links to, so it only goes to public web addresses (lib/outbound.js says which); curl
8
+ // then connects to the address checked and no other, so a name that answers differently the second time can't send it
9
+ // inward. Redirects are followed here, not by curl, each checked the same way. The pages are read by lib/pages.js.
10
+ //
11
+ // curl, not $http.send: that follows redirects anywhere and reads a whole response into memory, however big (a page
12
+ // ignoring Range took 1.1 GB). Of a response only the start is read, from curl's output; then curl is stopped.
13
+
14
+ const { addressOf, allowedHosts, parse, publicHost, resolve } = require(`${__hooks}/lib/outbound.js`);
15
+ const { attrs, base64, clean, decode, imageType, pageText, tags, titleOf } = require(`${__hooks}/lib/pages.js`);
16
+
17
+ /** Links looked at in one message. */
18
+ const MAX_LINKS = 5;
19
+ /** Of a page, only the start is read for its title and icon: the rest is never asked for (Range), nor read. */
20
+ const PAGE_BYTES = 256 * 1024;
21
+ /** A bigger icon is left out: it is kept in the message, as a data: URL. */
22
+ const MAX_ICON = 16 * 1024;
23
+ /** Seconds for a page, or an icon, redirects included. */
24
+ const PAGE_TIMEOUT = 4;
25
+ const ICON_TIMEOUT = 3;
26
+ const MAX_REDIRECTS = 3;
27
+ /**
28
+ * A message's links are looked at for this long (ms) at most: links after it get no line. A message linking to sites
29
+ * that never answer would otherwise hold up everyone's previews behind it, for minutes.
30
+ */
31
+ const MESSAGE_MS = 12_000;
32
+ const UA = "Mozilla/5.0 (compatible; ChirkleLinkPreview/1.0)";
33
+
34
+ const LOCK = "previews.worker";
35
+ /** A lock not renewed for this long (ms) is a worker that died. Renewed after every message, which takes under 30 s. */
36
+ const STALE_MS = 120_000;
37
+ const BATCH = 10;
38
+
39
+ const enabled = () => $os.getenv("LINK_PREVIEWS").trim().toLowerCase() !== "off";
40
+
41
+ // ---------------------------------------------------------------- links (as web/src/lib/links.ts finds them)
42
+
43
+ const CANDIDATE = /\b(?:https?:\/\/|www\.)[^\s<>"]+/gi;
44
+ const TRAILING = /[.,:;!?'"*_…。“”‘’«»„‟‹›]$/;
45
+ /** @type {Record<string, string>} */
46
+ const OPENING = { ")": "(", "]": "[" };
47
+ /** @param {string} s @param {string} ch */
48
+ const count = (s, ch) => s.split(ch).length - 1;
49
+
50
+ /**
51
+ * The http(s) links in `text` (www. ones as https), each once, at most MAX_LINKS.
52
+ * @param {string} text
53
+ * @returns {string[]}
54
+ */
55
+ function linksOf(text) {
56
+ /** @type {string[]} */
57
+ const out = [];
58
+ CANDIDATE.lastIndex = 0;
59
+ for (let m = CANDIDATE.exec(text); m && out.length < MAX_LINKS; m = CANDIDATE.exec(text)) {
60
+ let url = m[0];
61
+ for (;;) {
62
+ const last = url.slice(-1);
63
+ const open = OPENING[last];
64
+ if (!TRAILING.test(last) && !(open && count(url, open) < count(url, last))) break;
65
+ url = url.slice(0, -1);
66
+ }
67
+ const www = /^www\./i.test(url);
68
+ if (www && /[@.-]/.test(text[m.index - 1] || "")) continue;
69
+ const href = www ? `https://${url}` : url;
70
+ if (parse(href) && !out.includes(href)) out.push(href);
71
+ }
72
+ return out;
73
+ }
74
+
75
+ // ---------------------------------------------------------------- fetching
76
+
77
+ /** Are curl, getent and timeout there? Looked up once: without them, links get no previews. */
78
+ function tools(/** @type {core.App} */ app) {
79
+ return /** @type {boolean} */ (
80
+ app.store().getOrSet("previews.tools", () => {
81
+ try {
82
+ $os.cmd("sh", "-c", "command -v curl && command -v getent && command -v timeout").output();
83
+ return true;
84
+ } catch {
85
+ app.logger().warn("previews: no curl, getent or timeout, links get no previews");
86
+ return false;
87
+ }
88
+ })
89
+ );
90
+ }
91
+
92
+ /**
93
+ * @typedef {{ status: number, headers: Record<string, string>, body: any, url?: string }} Response `headers` by
94
+ * lowercased name (the first of each); `body` the start of it, as bytes; `url` where it came from, after redirects.
95
+ */
96
+
97
+ /**
98
+ * One GET with curl, connecting to `ip` ("": as curl looks the host up, for allowed
99
+ * hosts), reading at most `max` bytes of the body. Throws when there is no response (a timeout, a refused connection).
100
+ * @param {{ origin: string, path: string, scheme: string }} u
101
+ * @param {string} ip
102
+ * @param {Record<string, string>} headers
103
+ * @param {number} seconds
104
+ * @param {number} max
105
+ * @returns {Response}
106
+ */
107
+ function request(u, ip, headers, seconds, max) {
108
+ const head = `${$os.tempDir()}/chirkle-preview-${$security.randomString(16)}`;
109
+ // No ~/.curlrc, no proxy (it would look the host up itself), no globbing of [] and {} in the URL; no redirects (get
110
+ // checks each). The headers go to a file, written as they come: there even when curl is stopped mid-body.
111
+ const args = ["-q", "--silent", "--globoff", "--noproxy", "*", "--proto", "=http,https", "--max-time", seconds.toFixed(1)];
112
+ // Whatever host curl makes of the URL, it connects here.
113
+ if (ip) args.push("--connect-to", `::${ip}:${u.scheme === "https" ? 443 : 80}`);
114
+ args.push("--user-agent", UA);
115
+ for (const [k, v] of Object.entries(headers)) args.push("--header", `${k}: ${v}`);
116
+ args.push("--dump-header", head, "--output", "-", "--url", u.origin + u.path);
117
+ try {
118
+ const cmd = $os.cmd("curl", ...args);
119
+ const out = cmd.stdoutPipe();
120
+ cmd.start();
121
+ let body;
122
+ try {
123
+ body = toBytes(out, max);
124
+ } finally {
125
+ // The rest of a big body is never read: curl stops at the next write.
126
+ try {
127
+ cmd.process?.kill();
128
+ } catch {
129
+ // done already
130
+ }
131
+ try {
132
+ cmd.wait();
133
+ } catch {
134
+ // killed, or failed: the headers tell
135
+ }
136
+ }
137
+ let status = 0;
138
+ /** @type {Record<string, string>} */
139
+ let fields = Object.create(null);
140
+ for (const line of toString($os.readFile(head)).split(/\r?\n/)) {
141
+ const s = /^HTTP\/[\d.]+\s+(\d{3})/.exec(line);
142
+ if (s) {
143
+ status = Number(s[1]);
144
+ fields = Object.create(null);
145
+ continue;
146
+ }
147
+ const colon = line.indexOf(":");
148
+ const name = line.slice(0, colon).trim().toLowerCase();
149
+ if (colon > 0 && !(name in fields)) fields[name] = line.slice(colon + 1).trim();
150
+ }
151
+ if (!status) throw new Error("no response");
152
+ return { status, headers: fields, body };
153
+ } finally {
154
+ try {
155
+ $os.remove(head);
156
+ } catch {
157
+ // never written: no response
158
+ }
159
+ }
160
+ }
161
+
162
+ const REDIRECT = [301, 302, 303, 307, 308];
163
+
164
+ /**
165
+ * GET `url` (following up to MAX_REDIRECTS redirects, each checked like the link), null on any failure or a final
166
+ * status other than 200/206. A host that didn't answer (a timeout, a refused connection, a failed lookup) goes in
167
+ * `dead` and isn't asked again for this message: its links to a site that never answers cost one timeout, not one
168
+ * each.
169
+ * @param {string} url
170
+ * @param {Record<string, string>} headers
171
+ * @param {number} timeout seconds, for all of it
172
+ * @param {number} max body bytes read
173
+ * @param {Set<string>} dead
174
+ */
175
+ function get(url, headers, timeout, max, dead) {
176
+ const until = Date.now() + timeout * 1000;
177
+ let at = url;
178
+ for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
179
+ const u = parse(at);
180
+ const left = (until - Date.now()) / 1000;
181
+ if (!u || !publicHost(u.host) || dead.has(u.host) || left < 0.1) return null;
182
+ /** @type {Response} */
183
+ let res;
184
+ try {
185
+ let ip = "";
186
+ if (!allowedHosts().includes(u.host)) {
187
+ ip = addressOf(u.host);
188
+ if (!ip) return null;
189
+ }
190
+ res = request(u, ip, headers, left, max);
191
+ } catch {
192
+ dead.add(u.host);
193
+ return null;
194
+ }
195
+ if (res.status === 200 || res.status === 206) return { ...res, url: at };
196
+ if (!REDIRECT.includes(res.status) || !res.headers.location) return null;
197
+ at = resolve(res.headers.location, at);
198
+ }
199
+ return null;
200
+ }
201
+
202
+ /**
203
+ * An icon as a data: URL, or "".
204
+ * @param {string} url
205
+ * @param {Set<string>} dead
206
+ */
207
+ function icon(url, dead) {
208
+ // One byte more than kept: a bigger icon shows by its length, and no more of it is read.
209
+ const res = url ? get(url, { Accept: "image/*" }, ICON_TIMEOUT, MAX_ICON + 1, dead) : null;
210
+ const b = res?.body;
211
+ if (!b?.length || b.length > MAX_ICON) return "";
212
+ const type = imageType(/** @type {Response} */ (res), b);
213
+ return type ? `data:${type};base64,${base64(b)}` : "";
214
+ }
215
+
216
+ /**
217
+ * What a link shows: the page's title (og:title, else <title>) and its icon. null when there is no title to show.
218
+ * @param {string} url
219
+ * @param {Set<string>} dead
220
+ * @returns {{ url: string, title: string, icon: string } | null}
221
+ */
222
+ function preview(url, dead) {
223
+ const accept = { Accept: "text/html,application/xhtml+xml", Range: `bytes=0-${PAGE_BYTES - 1}` };
224
+ const res = get(url, accept, PAGE_TIMEOUT, PAGE_BYTES, dead);
225
+ if (!res || !/html/i.test(res.headers["content-type"] || "")) return null;
226
+ const html = pageText(res);
227
+ if (html === null) return null;
228
+ let title = "";
229
+ let iconRef = "";
230
+ for (const tag of tags(html)) {
231
+ const a = attrs(tag);
232
+ if (!title && /^og:title$/i.test(a.property || a.name || "")) title = clean(a.content || "");
233
+ if (!iconRef && a.href && /^<link/i.test(tag) && (a.rel || "").toLowerCase().split(/\s+/).includes("icon")) iconRef = a.href;
234
+ }
235
+ if (!title) title = clean(titleOf(html));
236
+ if (!title) return null;
237
+ const at = res.url || url;
238
+ const page = parse(at);
239
+ const found = iconRef ? icon(resolve(decode(iconRef), at), dead) : "";
240
+ return { url, title, icon: found || (page ? icon(`${page.origin}/favicon.ico`, dead) : "") };
241
+ }
242
+
243
+ // ---------------------------------------------------------------- the queue and the worker
244
+
245
+ /**
246
+ * A message saved with new text: look at its links (none: nothing to do). In the save's transaction.
247
+ * @param {core.App} app
248
+ * @param {core.Record} rec
249
+ */
250
+ function queue(app, rec) {
251
+ if (!enabled() || rec.getBool("deleted") || !linksOf(rec.getString("text")).length) return;
252
+ const row = new Record(app.findCollectionByNameOrId("link_queue"));
253
+ row.set("message", rec.id);
254
+ app.save(row);
255
+ }
256
+
257
+ /**
258
+ * Previews for one queued message, saved unless its text changed meanwhile (the edit queued it again).
259
+ * @param {core.App} app
260
+ * @param {string} id
261
+ */
262
+ function fill(app, id) {
263
+ let msg;
264
+ try {
265
+ msg = app.findRecordById("messages", id);
266
+ } catch {
267
+ return;
268
+ }
269
+ if (msg.getBool("deleted") || !tools(app)) return;
270
+ const text = msg.getString("text");
271
+ const until = Date.now() + MESSAGE_MS;
272
+ /** @type {Set<string>} */
273
+ const dead = new Set();
274
+ /** @type {{ url: string, title: string, icon: string }[]} */
275
+ const previews = [];
276
+ for (const url of linksOf(text)) {
277
+ if (Date.now() > until) break;
278
+ const p = preview(url, dead);
279
+ if (p) previews.push(p);
280
+ }
281
+ if (!previews.length) return;
282
+ app.runInTransaction((tx) => {
283
+ const now = tx.findRecordById("messages", id);
284
+ if (now.getBool("deleted") || now.getString("text") !== text) return;
285
+ now.set("previews", previews);
286
+ tx.save(now);
287
+ });
288
+ }
289
+
290
+ /**
291
+ * One pass: the oldest queued messages. `beat`, if given, is called after each one (the worker renews its lock).
292
+ * @param {core.App} app
293
+ * @param {() => void} [beat]
294
+ */
295
+ function pass(app, beat) {
296
+ const rows = app.findRecordsByFilter("link_queue", "", "created,id", BATCH, 0);
297
+ for (const row of rows) {
298
+ if (!row) continue;
299
+ try {
300
+ fill(app, row.getString("message"));
301
+ } catch (err) {
302
+ app.logger().warn("previews: fill", "message", row.getString("message"), "error", String(err));
303
+ }
304
+ try {
305
+ app.delete(row);
306
+ } catch {
307
+ // gone with its message
308
+ }
309
+ beat?.();
310
+ }
311
+ return rows.length;
312
+ }
313
+
314
+ /**
315
+ * The cron job: passes until the minute is nearly over; with nothing to do, when a queued message wakes it (wake). One
316
+ * run at a time.
317
+ * @param {core.App} app
318
+ */
319
+ function run(app) {
320
+ require(`${__hooks}/lib/worker.js`).run(app, {
321
+ name: LOCK,
322
+ label: "previews",
323
+ staleMs: STALE_MS,
324
+ wakes: true,
325
+ pass: (/** @type {() => void} */ renew) => pass(app, renew),
326
+ });
327
+ }
328
+
329
+ /**
330
+ * A message was queued (committed): the worker looks at it now.
331
+ * @param {core.App} app
332
+ */
333
+ function wake(app) {
334
+ require(`${__hooks}/lib/worker.js`).wake(app, LOCK);
335
+ }
336
+
337
+ /**
338
+ * POST /api/previews/tick (superusers): one pass now.
339
+ * @param {core.RequestEvent} e
340
+ */
341
+ function tick(e) {
342
+ while (pass(e.app) === BATCH);
343
+ return e.noContent(204);
344
+ }
345
+
346
+ module.exports = { enabled, linksOf, queue, run, wake, tick };