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.
- package/LICENSE +674 -0
- package/README.md +326 -2
- package/package.json +76 -4
- package/pb_hooks/federation/config.js +276 -0
- package/pb_hooks/federation/inbox.js +316 -0
- package/pb_hooks/federation/messages.js +420 -0
- package/pb_hooks/federation/mirror.js +277 -0
- package/pb_hooks/federation/net.js +247 -0
- package/pb_hooks/federation/peers.js +490 -0
- package/pb_hooks/federation/people.js +376 -0
- package/pb_hooks/federation/rooms.js +552 -0
- package/pb_hooks/federation/worker.js +413 -0
- package/pb_hooks/federation.pb.js +141 -0
- package/pb_hooks/lib/access.js +102 -0
- package/pb_hooks/lib/account.js +31 -0
- package/pb_hooks/lib/anonymous.js +189 -0
- package/pb_hooks/lib/bulk.js +187 -0
- package/pb_hooks/lib/collections.js +587 -0
- package/pb_hooks/lib/dms.js +123 -0
- package/pb_hooks/lib/emoji.js +28 -0
- package/pb_hooks/lib/enrich.js +75 -0
- package/pb_hooks/lib/features.js +31 -0
- package/pb_hooks/lib/files.js +375 -0
- package/pb_hooks/lib/http.js +146 -0
- package/pb_hooks/lib/images.js +160 -0
- package/pb_hooks/lib/keepalive.js +31 -0
- package/pb_hooks/lib/lists.js +173 -0
- package/pb_hooks/lib/media.js +635 -0
- package/pb_hooks/lib/messages.js +519 -0
- package/pb_hooks/lib/moderation.js +128 -0
- package/pb_hooks/lib/outbound.js +116 -0
- package/pb_hooks/lib/pages.js +171 -0
- package/pb_hooks/lib/previews.js +346 -0
- package/pb_hooks/lib/reactions.js +110 -0
- package/pb_hooks/lib/reads.js +181 -0
- package/pb_hooks/lib/records.js +77 -0
- package/pb_hooks/lib/rooms.js +148 -0
- package/pb_hooks/lib/site.js +102 -0
- package/pb_hooks/lib/text.js +110 -0
- package/pb_hooks/lib/users.js +81 -0
- package/pb_hooks/lib/worker.js +159 -0
- package/pb_hooks/main.pb.js +324 -0
- package/pb_hooks/telegram/api.js +129 -0
- package/pb_hooks/telegram/inbound.js +553 -0
- package/pb_hooks/telegram/links.js +157 -0
- package/pb_hooks/telegram/outbound.js +352 -0
- package/pb_hooks/telegram/people.js +166 -0
- package/pb_hooks/telegram/reactions.js +137 -0
- package/pb_hooks/telegram/rich.js +192 -0
- package/pb_hooks/telegram/worker.js +182 -0
- package/pb_hooks/telegram.pb.js +47 -0
- package/pb_migrations/1760000000_init.js +150 -0
- package/pb_migrations/1760000001_qa_fixes.js +69 -0
- package/pb_migrations/1760000002_avatars.js +39 -0
- package/pb_migrations/1760000003_direct_messages.js +142 -0
- package/pb_migrations/1760000004_attachments.js +28 -0
- package/pb_migrations/1760000005_file_names.js +16 -0
- package/pb_migrations/1760000006_room_reads.js +41 -0
- package/pb_migrations/1760000007_replies.js +23 -0
- package/pb_migrations/1760000008_lowercase_emails.js +24 -0
- package/pb_migrations/1760000009_reactions.js +32 -0
- package/pb_migrations/1760000010_fit_thumbs.js +18 -0
- package/pb_migrations/1760000011_forwarding.js +39 -0
- package/pb_migrations/1760000012_accounts.js +55 -0
- package/pb_migrations/1760000013_qa_pass5.js +19 -0
- package/pb_migrations/1760000014_room_access.js +96 -0
- package/pb_migrations/1760000015_site.js +46 -0
- package/pb_migrations/1760000016_forward_refs.js +43 -0
- package/pb_migrations/1760000017_no_dms.js +18 -0
- package/pb_migrations/1760000018_attachment_limits.js +24 -0
- package/pb_migrations/1760000019_telegram.js +109 -0
- package/pb_migrations/1760000020_service_messages.js +21 -0
- package/pb_migrations/1760000021_forward_view_index.js +41 -0
- package/pb_migrations/1760000022_link_previews.js +43 -0
- package/pb_migrations/1760000023_room_writers.js +49 -0
- package/pb_migrations/1760000024_message_search.js +51 -0
- package/pb_migrations/1760000025_search_dotted_i.js +16 -0
- package/pb_migrations/1760000026_push.js +67 -0
- package/pb_migrations/1760000027_push_tokens_per_user.js +31 -0
- package/pb_migrations/1760000028_media_grid_thumbs.js +18 -0
- package/pb_migrations/1760000029_media.js +71 -0
- package/pb_migrations/1760000030_collections.js +140 -0
- package/pb_migrations/1760000031_unread_limit.js +20 -0
- package/pb_migrations/1760000032_federation.js +227 -0
- package/pb_migrations/1760000033_federation_requests.js +44 -0
- package/pb_migrations/1760000034_telegram_parts.js +26 -0
- package/pb_migrations/1760000035_telegram_anonymous.js +16 -0
- package/pb_migrations/1760000036_chirkle.js +20 -0
- package/pb_migrations/1760000037_file_dims.js +35 -0
- package/pb_migrations/1760000038_drop_push.js +64 -0
- package/pb_migrations/1760000039_anonymous_rooms.js +40 -0
- package/pb_migrations/1760000040_moderators.js +42 -0
- package/pb_migrations/1760000041_shared_files.js +500 -0
- package/pb_migrations/1760000042_files_src.js +17 -0
- package/pb_migrations/1760000043_telegram_reactions.js +21 -0
- package/pb_public/assets/access-ALBW2MT2.js +2 -0
- package/pb_public/assets/access-ALBW2MT2.js.map +7 -0
- package/pb_public/assets/access-PB77EH4F.css +2 -0
- package/pb_public/assets/access-PB77EH4F.css.map +7 -0
- package/pb_public/assets/app-A3SXD3FF.css +2 -0
- package/pb_public/assets/app-A3SXD3FF.css.map +7 -0
- package/pb_public/assets/app-NDSIQW4L.js +3 -0
- package/pb_public/assets/app-NDSIQW4L.js.map +7 -0
- package/pb_public/assets/collections-DHJEOLHW.css +2 -0
- package/pb_public/assets/collections-DHJEOLHW.css.map +7 -0
- package/pb_public/assets/emoji-WSTVXAW5.css +2 -0
- package/pb_public/assets/emoji-WSTVXAW5.css.map +7 -0
- package/pb_public/assets/emoji-picker-QYRX6NYL.js +609 -0
- package/pb_public/assets/emoji-picker-QYRX6NYL.js.map +7 -0
- package/pb_public/assets/inter-cyrillic-JEOLYBOO.woff2 +0 -0
- package/pb_public/assets/inter-cyrillic-ext-IYF56FF6.woff2 +0 -0
- package/pb_public/assets/inter-greek-IRE366VL.woff2 +0 -0
- package/pb_public/assets/inter-latin-NRMW37G5.woff2 +0 -0
- package/pb_public/assets/inter-latin-ext-HA22NDSG.woff2 +0 -0
- package/pb_public/assets/lazy-4CXRBHHM.js +2 -0
- package/pb_public/assets/lazy-4CXRBHHM.js.map +7 -0
- package/pb_public/assets/media-7TCBG7WM.css +2 -0
- package/pb_public/assets/media-7TCBG7WM.css.map +7 -0
- package/pb_public/assets/media-FPRU2QH5.js +2 -0
- package/pb_public/assets/media-FPRU2QH5.js.map +7 -0
- package/pb_public/assets/notify-L6GERFNO.js +2 -0
- package/pb_public/assets/notify-L6GERFNO.js.map +7 -0
- package/pb_public/assets/search-3UT4HMES.js +2 -0
- package/pb_public/assets/search-3UT4HMES.js.map +7 -0
- package/pb_public/assets/switcher-CEUKRLEY.js +2 -0
- package/pb_public/assets/switcher-CEUKRLEY.js.map +7 -0
- package/pb_public/assets/viewer-DXT7SKOU.js +2 -0
- package/pb_public/assets/viewer-DXT7SKOU.js.map +7 -0
- package/pb_public/assets/viewer-P7GYCBYM.css +2 -0
- package/pb_public/assets/viewer-P7GYCBYM.css.map +7 -0
- package/pb_public/icons/apple-touch-icon.png +0 -0
- package/pb_public/icons/icon-192.png +0 -0
- package/pb_public/icons/icon-512.png +0 -0
- package/pb_public/icons/icon.svg +1 -0
- package/pb_public/icons/maskable-512.png +0 -0
- package/pb_public/index.html +21 -0
- package/pb_public/sw.js +1 -0
- package/scripts/fetch-pocketbase.sh +63 -0
- package/scripts/start.mjs +93 -0
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
/// <reference path="../../types/pocketbase.d.ts" />
|
|
2
|
+
// Every response's security and cache headers, the built assets, and the client IP behind a proxy (DESIGN.md §5.6, §8.2).
|
|
3
|
+
|
|
4
|
+
const CSP = [
|
|
5
|
+
"default-src 'self'",
|
|
6
|
+
// The hash is index.html's inline theme script (web/src/theme.ts); tests/unit/build/csp.test.ts checks it.
|
|
7
|
+
"script-src 'self' 'sha256-lMI93IRRLFIlto6GZfZdfPFeIgbs3CJfe2ncDiU/aWw='",
|
|
8
|
+
"style-src 'self'",
|
|
9
|
+
"connect-src 'self'",
|
|
10
|
+
"img-src 'self' data: blob:",
|
|
11
|
+
"media-src 'self' blob:",
|
|
12
|
+
"base-uri 'none'",
|
|
13
|
+
"form-action 'self'",
|
|
14
|
+
"frame-ancestors 'none'",
|
|
15
|
+
].join("; ");
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Security + cache headers for every response (§5.6).
|
|
19
|
+
* @param {core.RequestEvent} e
|
|
20
|
+
*/
|
|
21
|
+
function headers(e) {
|
|
22
|
+
const path = e.request?.url?.path ?? ""; // always set for a real request; optional in the generated types
|
|
23
|
+
const h = e.response.header();
|
|
24
|
+
h.set("X-Content-Type-Options", "nosniff");
|
|
25
|
+
h.set("Referrer-Policy", "same-origin");
|
|
26
|
+
// The admin UI (/_/) relies on inline scripts/styles; the API serves JSON.
|
|
27
|
+
if (!path.startsWith("/_/") && !path.startsWith("/api/")) {
|
|
28
|
+
h.set("Content-Security-Policy", CSP);
|
|
29
|
+
// Only content-hashed names (esbuild "[name]-[hash]", 8 chars) are immutable; dev builds are unhashed.
|
|
30
|
+
if (/^\/assets\/.+-[A-Z0-9]{8}\.(js|css|woff2)(\.map)?$/.test(path)) h.set("Cache-Control", "public, max-age=31536000, immutable");
|
|
31
|
+
else h.set("Cache-Control", "no-cache");
|
|
32
|
+
// A page (the app's index.html, at any path without a file name): what it loads first.
|
|
33
|
+
if (e.request?.method === "GET" && !path.startsWith("/assets/") && !/\.[a-z0-9]+$/i.test(path)) {
|
|
34
|
+
const link = preloads();
|
|
35
|
+
if (link) h.set("Link", link);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* index.html's assets as a Link header, read again by each JS runtime when index.html changes: a deploy may replace
|
|
42
|
+
* pb_public/ while the server runs, and the last build's assets must not be preloaded (QA BUG-206).
|
|
43
|
+
*/
|
|
44
|
+
/** @type {string} */
|
|
45
|
+
let links = "";
|
|
46
|
+
/** index.html's modification time when `links` was read. */
|
|
47
|
+
let linksOf = "";
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* What a page loads first (index.html's stylesheet, script and preloaded font), as a Link header: a proxy in front can
|
|
51
|
+
* send it ahead of the page as 103 Early Hints, so the browser asks for them while the page is still on its way
|
|
52
|
+
* (PERF.md §5). None while there is no index.html (not built yet).
|
|
53
|
+
*/
|
|
54
|
+
function preloads() {
|
|
55
|
+
try {
|
|
56
|
+
const file = $filepath.join(publicDir(), "index.html");
|
|
57
|
+
const at = String($os.stat(file).modTime().unixNano());
|
|
58
|
+
if (at === linksOf) return links;
|
|
59
|
+
const html = toString($os.readFile(file));
|
|
60
|
+
const out = [];
|
|
61
|
+
for (const m of html.matchAll(/<(link|script)\b[^>]*?(?:href|src)="(\/assets\/[^"]+)"/g)) {
|
|
62
|
+
const url = m[2];
|
|
63
|
+
if (url.endsWith(".css")) out.push(`<${url}>; rel=preload; as=style`);
|
|
64
|
+
else if (url.endsWith(".js")) out.push(`<${url}>; rel=modulepreload`);
|
|
65
|
+
else if (url.endsWith(".woff2")) out.push(`<${url}>; rel=preload; as=font; type="font/woff2"; crossorigin`);
|
|
66
|
+
}
|
|
67
|
+
links = out.join(", ");
|
|
68
|
+
linksOf = at;
|
|
69
|
+
} catch {
|
|
70
|
+
links = "";
|
|
71
|
+
linksOf = "";
|
|
72
|
+
}
|
|
73
|
+
return links;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** PocketBase's own request body limit, which every request but a message create keeps. */
|
|
77
|
+
const DEFAULT_BODY_LIMIT = 32 << 20;
|
|
78
|
+
|
|
79
|
+
/** A message create: 10 attachments of 20 MB (DESIGN.md §17.1), and room for the rest of the form. */
|
|
80
|
+
const MESSAGE_BODY_LIMIT = 10 * 20 * 1024 * 1024 + (1 << 20);
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* The body limit is MESSAGE_BODY_LIMIT for every route (main.pb.js replaces PocketBase's default, as one route can't
|
|
84
|
+
* have its own: the records API is PocketBase's): hold a body to the default anywhere but a message create, as
|
|
85
|
+
* PocketBase's limiter does, counting what is read. Not by Content-Length alone: a chunked body has none (-1), and was
|
|
86
|
+
* let through to MESSAGE_BODY_LIMIT, signups and logins too (QA BUG-143). The Android app sends chunked uploads when a
|
|
87
|
+
* file's size is unknown, so those are limited, not refused. Goes on with the request (e.next) when within it.
|
|
88
|
+
* @param {core.RequestEvent} e
|
|
89
|
+
*/
|
|
90
|
+
function bodyLimit(e) {
|
|
91
|
+
const req = e.request;
|
|
92
|
+
if (req?.method === "POST" && req.url?.path === "/api/collections/messages/records") return e.next();
|
|
93
|
+
return $apis.bodyLimit(DEFAULT_BODY_LIMIT).func(e);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** The directory the app is served from: `--publicDir`, else PocketBase's default, pb_public beside the executable. */
|
|
97
|
+
function publicDir() {
|
|
98
|
+
const args = $os.args;
|
|
99
|
+
for (let i = 1; i < args.length; i++) {
|
|
100
|
+
if (args[i].startsWith("--publicDir=")) return args[i].slice("--publicDir=".length);
|
|
101
|
+
if (args[i] === "--publicDir") return args[i + 1];
|
|
102
|
+
}
|
|
103
|
+
return $filepath.join($filepath.dir(args[0]), "pb_public");
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* GET /assets/{path...}: the built JS and CSS (§8.2). A missing file is a 404, not the app's index.html, which
|
|
108
|
+
* PocketBase serves for any other path (§7.1). As index.html, an old build's lazy chunk (a tab still open across a
|
|
109
|
+
* deploy) would fail as a script anyway, and its content-hashed URL would keep that HTML cached for a year.
|
|
110
|
+
* @param {core.RequestEvent} e
|
|
111
|
+
*/
|
|
112
|
+
function asset(e) {
|
|
113
|
+
const dir = $filepath.join(publicDir(), "assets");
|
|
114
|
+
const path = e.request?.pathValue("path") ?? "";
|
|
115
|
+
try {
|
|
116
|
+
if (path.split("/").includes("..")) throw new Error("outside assets/");
|
|
117
|
+
if ($os.stat($filepath.join(dir, path)).isDir()) throw new Error("a directory");
|
|
118
|
+
} catch {
|
|
119
|
+
e.response.header().set("Cache-Control", "no-store");
|
|
120
|
+
throw new NotFoundError();
|
|
121
|
+
}
|
|
122
|
+
return $apis.static(dir, false)(e);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Who the client is behind a reverse proxy (Dokku, nginx, Caddy…). PocketBase rate limits per client IP, and without a
|
|
127
|
+
* trusted header every request comes from the proxy: each per-IP limit would be one limit for the whole site (a script
|
|
128
|
+
* failing a login every 1.5 s would lock everyone out). `TRUSTED_PROXY` names the header the proxy sets, usually
|
|
129
|
+
* X-Forwarded-For. Its rightmost address is used, the one the proxy itself added, so a client can't choose its own.
|
|
130
|
+
* "off" clears it; unset leaves what the admin chose (Settings → Application). Only set it with a proxy in front:
|
|
131
|
+
* otherwise clients send that header themselves and pick their IP.
|
|
132
|
+
* @param {core.App} app
|
|
133
|
+
*/
|
|
134
|
+
function trustProxy(app) {
|
|
135
|
+
const value = $os.getenv("TRUSTED_PROXY").trim();
|
|
136
|
+
if (!value) return;
|
|
137
|
+
const headers = value.toLowerCase() === "off" ? [] : [value];
|
|
138
|
+
const settings = app.settings();
|
|
139
|
+
const now = settings.trustedProxy;
|
|
140
|
+
if (now.headers.join(",") === headers.join(",") && !now.useLeftmostIP) return;
|
|
141
|
+
now.headers = headers;
|
|
142
|
+
now.useLeftmostIP = false;
|
|
143
|
+
app.save(settings);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
module.exports = { headers, bodyLimit, asset, trustProxy, MESSAGE_BODY_LIMIT };
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
/// <reference path="../../types/pocketbase.d.ts" />
|
|
2
|
+
// Image dimension limit for uploads (QA BUG-24). PocketBase decodes a whole image to thumbnail it, so a small,
|
|
3
|
+
// highly compressed file declaring huge dimensions can exhaust memory. Read the header of every upload in a format
|
|
4
|
+
// PocketBase thumbnails and refuse more than MAX_PIXELS. Pure byte parsing; no decoding.
|
|
5
|
+
// The same header gives the shape the image is shown in (a JPEG's EXIF orientation applied), which messages keep in
|
|
6
|
+
// `file_dims` so a tile has its size before the image loads (DESIGN.md §17.5).
|
|
7
|
+
|
|
8
|
+
/** 25 megapixels: about 125 MB to decode. The app's own uploads are at most 2048 px on a side (§15.3). */
|
|
9
|
+
const MAX_PIXELS = 25_000_000;
|
|
10
|
+
|
|
11
|
+
/** How much of a file to read looking for its dimensions (a JPEG's frame header can follow metadata segments). */
|
|
12
|
+
const HEADER_BYTES = 256 * 1024;
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* @param {number[]} b
|
|
16
|
+
* @param {number} i
|
|
17
|
+
*/
|
|
18
|
+
const u16be = (b, i) => ((b[i] ?? 0) << 8) | (b[i + 1] ?? 0);
|
|
19
|
+
/**
|
|
20
|
+
* @param {number[]} b
|
|
21
|
+
* @param {number} i
|
|
22
|
+
*/
|
|
23
|
+
const u16le = (b, i) => (b[i] ?? 0) | ((b[i + 1] ?? 0) << 8);
|
|
24
|
+
/**
|
|
25
|
+
* @param {number[]} b
|
|
26
|
+
* @param {number} i
|
|
27
|
+
*/
|
|
28
|
+
const u32le = (b, i) => u16le(b, i) + u16le(b, i + 2) * 65536;
|
|
29
|
+
/**
|
|
30
|
+
* @param {number[]} b
|
|
31
|
+
* @param {number} i
|
|
32
|
+
*/
|
|
33
|
+
const u24le = (b, i) => (b[i] ?? 0) | ((b[i + 1] ?? 0) << 8) | ((b[i + 2] ?? 0) << 16);
|
|
34
|
+
/**
|
|
35
|
+
* @param {number[]} b
|
|
36
|
+
* @param {number} i
|
|
37
|
+
*/
|
|
38
|
+
const u32be = (b, i) => (((b[i] ?? 0) << 24) >>> 0) + (((b[i + 1] ?? 0) << 16) | ((b[i + 2] ?? 0) << 8) | (b[i + 3] ?? 0));
|
|
39
|
+
/**
|
|
40
|
+
* @param {number[]} b
|
|
41
|
+
* @param {number} i
|
|
42
|
+
* @param {string} s
|
|
43
|
+
*/
|
|
44
|
+
const ascii = (b, i, s) => [...s].every((c, k) => b[i + k] === c.charCodeAt(0));
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Is the JPEG APP1 segment at `i` EXIF that turns the image a quarter turn (orientation 5–8)? Browsers and
|
|
48
|
+
* PocketBase's thumbnails both show it turned, so its width and height swap.
|
|
49
|
+
* @param {number[]} b
|
|
50
|
+
* @param {number} i
|
|
51
|
+
*/
|
|
52
|
+
function exifTurned(b, i) {
|
|
53
|
+
if (!ascii(b, i + 4, "Exif") || b[i + 8] !== 0 || b[i + 9] !== 0) return false;
|
|
54
|
+
const t = i + 10; // the TIFF header
|
|
55
|
+
const le = ascii(b, t, "II");
|
|
56
|
+
if (!le && !ascii(b, t, "MM")) return false;
|
|
57
|
+
const u16 = le ? u16le : u16be;
|
|
58
|
+
const u32 = le ? u32le : u32be;
|
|
59
|
+
const ifd = t + u32(b, t + 4);
|
|
60
|
+
const count = u16(b, ifd);
|
|
61
|
+
for (let k = 0; k < count && ifd + 2 + 12 * (k + 1) <= b.length; k++) {
|
|
62
|
+
const entry = ifd + 2 + 12 * k;
|
|
63
|
+
if (u16(b, entry) === 0x0112) return u16(b, entry + 8) >= 5 && u16(b, entry + 8) <= 8;
|
|
64
|
+
}
|
|
65
|
+
return false;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Dimensions declared by a PNG, GIF, JPEG or WebP header; null for anything else.
|
|
70
|
+
* `{ unreadable: true }` for an image whose dimensions couldn't be found in the bytes read.
|
|
71
|
+
* `turned`: a JPEG whose EXIF says it is shown a quarter turn round (width and height swap on screen).
|
|
72
|
+
* @param {number[]} b
|
|
73
|
+
* @returns {{ width: number, height: number, turned?: boolean } | { unreadable: true } | null}
|
|
74
|
+
*/
|
|
75
|
+
function imageSize(b) {
|
|
76
|
+
if (ascii(b, 1, "PNG") && b[0] === 0x89) return { width: u32be(b, 16), height: u32be(b, 20) };
|
|
77
|
+
if (ascii(b, 0, "GIF8")) return { width: u16le(b, 6), height: u16le(b, 8) };
|
|
78
|
+
if (ascii(b, 0, "RIFF") && ascii(b, 8, "WEBP")) {
|
|
79
|
+
if (ascii(b, 12, "VP8X")) return { width: 1 + u24le(b, 24), height: 1 + u24le(b, 27) };
|
|
80
|
+
if (ascii(b, 12, "VP8L")) {
|
|
81
|
+
const b1 = b[21] ?? 0;
|
|
82
|
+
const b2 = b[22] ?? 0;
|
|
83
|
+
const b3 = b[23] ?? 0;
|
|
84
|
+
const b4 = b[24] ?? 0;
|
|
85
|
+
return { width: 1 + (((b2 & 0x3f) << 8) | b1), height: 1 + (((b4 & 0x0f) << 10) | (b3 << 2) | ((b2 & 0xc0) >> 6)) };
|
|
86
|
+
}
|
|
87
|
+
if (ascii(b, 12, "VP8 ")) return { width: u16le(b, 26) & 0x3fff, height: u16le(b, 28) & 0x3fff };
|
|
88
|
+
return { unreadable: true };
|
|
89
|
+
}
|
|
90
|
+
if (b[0] === 0xff && b[1] === 0xd8) {
|
|
91
|
+
// Walk the segments to the frame header (SOF0–SOF15, except DHT C4, JPG C8 and DAC CC). EXIF comes before it.
|
|
92
|
+
let i = 2;
|
|
93
|
+
let turned = false;
|
|
94
|
+
while (i + 9 < b.length) {
|
|
95
|
+
if (b[i] !== 0xff) return { unreadable: true };
|
|
96
|
+
const marker = b[i + 1] ?? 0;
|
|
97
|
+
if (marker === 0xff) {
|
|
98
|
+
i++; // fill byte
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
101
|
+
if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc) {
|
|
102
|
+
return { width: u16be(b, i + 7), height: u16be(b, i + 5), turned };
|
|
103
|
+
}
|
|
104
|
+
if (marker === 0xd9 || marker === 0xda) return { unreadable: true }; // end of image / scan data before a frame
|
|
105
|
+
if (marker === 0xe1 && !turned) turned = exifTurned(b, i);
|
|
106
|
+
i += 2 + u16be(b, i + 2);
|
|
107
|
+
}
|
|
108
|
+
return { unreadable: true };
|
|
109
|
+
}
|
|
110
|
+
return null;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* The shape an image is shown in, [width, height], from its header; null for anything else (or a size of 0).
|
|
115
|
+
* @param {number[]} b
|
|
116
|
+
* @returns {[number, number] | null}
|
|
117
|
+
*/
|
|
118
|
+
function shownSize(b) {
|
|
119
|
+
const size = imageSize(b);
|
|
120
|
+
if (!size || "unreadable" in size || !size.width || !size.height) return null;
|
|
121
|
+
return size.turned ? [size.height, size.width] : [size.width, size.height];
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Refuse uploads in `field` that are images over the size limit (or whose dimensions can't be read). Returns the
|
|
126
|
+
* shape each image upload is shown in (shownSize), by its stored name.
|
|
127
|
+
* @param {core.Record} record
|
|
128
|
+
* @param {string} field
|
|
129
|
+
* @param {string} [key] the field errors name (default `field`)
|
|
130
|
+
* @returns {Record<string, [number, number]>}
|
|
131
|
+
*/
|
|
132
|
+
function assertImagesFit(record, field, key = field) {
|
|
133
|
+
/** @type {Record<string, [number, number]>} */
|
|
134
|
+
const dims = {};
|
|
135
|
+
for (const f of record.getUnsavedFiles(field)) {
|
|
136
|
+
if (!f) continue;
|
|
137
|
+
// A copy of a stored file (a forward, §21.3) has a Go func type as its reader, which reaches JS as a plain
|
|
138
|
+
// function: calling it is its Open().
|
|
139
|
+
const r = /** @type {any} */ (f.reader);
|
|
140
|
+
const reader = typeof r === "function" ? r() : r.open();
|
|
141
|
+
let bytes;
|
|
142
|
+
try {
|
|
143
|
+
bytes = toBytes(reader, HEADER_BYTES);
|
|
144
|
+
} finally {
|
|
145
|
+
reader.close();
|
|
146
|
+
}
|
|
147
|
+
const size = imageSize(bytes);
|
|
148
|
+
if (!size) continue;
|
|
149
|
+
if ("unreadable" in size || size.width * size.height > MAX_PIXELS) {
|
|
150
|
+
throw new BadRequestError("Failed to save record.", {
|
|
151
|
+
[key]: new ValidationError("validation_image_too_large", `Images can be at most ${MAX_PIXELS / 1_000_000} megapixels.`),
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
const shown = shownSize(bytes);
|
|
155
|
+
if (shown) dims[f.name] = shown;
|
|
156
|
+
}
|
|
157
|
+
return dims;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
module.exports = { assertImagesFit, imageSize, shownSize, HEADER_BYTES, MAX_PIXELS };
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/// <reference path="../../types/pocketbase.d.ts" />
|
|
2
|
+
// PocketBase closes a realtime connection that has sent nothing for 5 minutes, and the clients take every reconnect for
|
|
3
|
+
// one that may have missed events: they load their rooms, unread counts, collections and open room again
|
|
4
|
+
// (docs/PERF.md §2.4). An event every 3 minutes keeps quiet connections open. No client listens for it, so it is
|
|
5
|
+
// dropped on arrival (old apps too).
|
|
6
|
+
|
|
7
|
+
const NAME = "chat/keepalive";
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Send the keepalive to every connected client.
|
|
11
|
+
* @param {core.App} app
|
|
12
|
+
*/
|
|
13
|
+
function run(app) {
|
|
14
|
+
const message = new SubscriptionMessage({ name: NAME, data: "{}" });
|
|
15
|
+
const clients = app.subscriptionsBroker().clients();
|
|
16
|
+
for (const id of Object.keys(clients)) {
|
|
17
|
+
const client = clients[id];
|
|
18
|
+
if (client && !client.isDiscarded()) client.send(message);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* POST /api/keepalive/tick (superusers): a run now, for tests.
|
|
24
|
+
* @param {core.RequestEvent} e
|
|
25
|
+
*/
|
|
26
|
+
function tick(e) {
|
|
27
|
+
run(e.app);
|
|
28
|
+
return e.noContent(204);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
module.exports = { run, tick };
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
/// <reference path="../../types/pocketbase.d.ts" />
|
|
2
|
+
// The room list and a room's message pages, as routes (docs/API.md): the clients say which page they want and the
|
|
3
|
+
// server writes the filter, so the schema can change under them. Both answer as the records API does (the same
|
|
4
|
+
// ?expand and ?fields, applied to each record; the enrich hooks), as a plain array, and see what the API rules let
|
|
5
|
+
// the caller see (lib/access.js). Apps from before these routes still list `rooms` and `messages` through the records
|
|
6
|
+
// API, which stays as it was.
|
|
7
|
+
|
|
8
|
+
const { SEES_SQL, visibleRoom } = require(`${__hooks}/lib/access.js`);
|
|
9
|
+
const { enrichInRooms } = require(`${__hooks}/lib/messages.js`);
|
|
10
|
+
const { searchKey } = require(`${__hooks}/lib/text.js`);
|
|
11
|
+
|
|
12
|
+
/** Messages in a page unless `limit` says otherwise (web/src/lib/cursor.ts PAGE_SIZE). */
|
|
13
|
+
const PAGE_SIZE = 50;
|
|
14
|
+
const MAX_LIMIT = 200;
|
|
15
|
+
/** Words of a search that count (web/src/views/room/search.ts MAX_WORDS). */
|
|
16
|
+
const MAX_WORDS = 5;
|
|
17
|
+
/** Rooms in one notification check, at most (ANDROID.md §21.2 asks for 40). */
|
|
18
|
+
const MAX_ROOMS = 50;
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* A room's pages (DESIGN.md §7.5), keyset by (created, id), and the edits and deletes missed while offline (`changed`).
|
|
22
|
+
* `latest` and `older` come newest first, the others oldest first.
|
|
23
|
+
* @type {Record<string, { where: string, params: string[], sort: string }>}
|
|
24
|
+
*/
|
|
25
|
+
const KINDS = {
|
|
26
|
+
latest: { where: "", params: [], sort: "-created,-id" },
|
|
27
|
+
first: { where: "", params: [], sort: "created,id" },
|
|
28
|
+
older: { where: "(created < {:created} || (created = {:created} && id < {:id}))", params: ["created", "id"], sort: "-created,-id" },
|
|
29
|
+
newer: { where: "(created > {:created} || (created = {:created} && id > {:id}))", params: ["created", "id"], sort: "created,id" },
|
|
30
|
+
changed: { where: "updated > {:since} && created >= {:from} && created <= {:to}", params: ["since", "from", "to"], sort: "updated,id" },
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* GET /api/chat/rooms → the rooms: every room the caller can see, by name. Guests: the Open Air rooms (§23.3).
|
|
35
|
+
* @param {core.RequestEvent} e
|
|
36
|
+
*/
|
|
37
|
+
function rooms(e) {
|
|
38
|
+
const me = e.auth && !e.auth.isSuperuser() ? e.auth.id : "";
|
|
39
|
+
const where = e.hasSuperuserAuth() ? "1" : me ? SEES_SQL : "r.visibility = 'open' AND NOT r.archived";
|
|
40
|
+
const rows = arrayOf(new DynamicModel({ id: "" }));
|
|
41
|
+
e.app.db().newQuery(`SELECT r.id FROM rooms r WHERE ${where} ORDER BY r.name, r.id`).bind({ me }).all(rows);
|
|
42
|
+
const found = e.app.findRecordsByIds(
|
|
43
|
+
"rooms",
|
|
44
|
+
rows.map((r) => r.id),
|
|
45
|
+
);
|
|
46
|
+
const byId = new Map(found.map((r) => [r?.id, r]));
|
|
47
|
+
const items = /** @type {core.Record[]} */ (rows.map((r) => byId.get(r.id)).filter(Boolean));
|
|
48
|
+
$apis.enrichRecords(e, items);
|
|
49
|
+
return e.json(200, items);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* GET /api/chat/rooms/{room}/messages?kind=latest|first|older|newer|changed → the messages. `older` and `newer` take the
|
|
54
|
+
* cursor (`created`, `id`); `changed` takes `since` (an `updated` value) and `from`, `to` (`created` values). `files=1`:
|
|
55
|
+
* only messages that may have attachments (theirs, or a forward's original's, §17.7). `q`: only messages with every
|
|
56
|
+
* word of it (search, §29; with `latest` and `older`). `limit` (at most 200) and `page` (from 1) as the records API has
|
|
57
|
+
* them. A room the caller can't see has no messages, as the records API says. Answered with an ETag: asked again with it
|
|
58
|
+
* (If-None-Match), an unchanged page is a 304 without a body (PERF.md §5).
|
|
59
|
+
* @param {core.RequestEvent} e
|
|
60
|
+
*/
|
|
61
|
+
function messages(e) {
|
|
62
|
+
const roomId = e.request?.pathValue("room") ?? "";
|
|
63
|
+
const q = e.requestInfo().query;
|
|
64
|
+
// Own keys only: "toString" and the like are the object's too (QA BUG-171).
|
|
65
|
+
const name = q.kind || "latest";
|
|
66
|
+
const kind = Object.keys(KINDS).includes(name) ? KINDS[name] : null;
|
|
67
|
+
if (!kind) throw new BadRequestError("Unknown page kind.");
|
|
68
|
+
const me = e.auth && !e.auth.isSuperuser() ? e.auth.id : "";
|
|
69
|
+
if (!e.hasSuperuserAuth() && !visibleRoom(e.app, roomId, me)) return e.json(200, []);
|
|
70
|
+
/** @type {Record<string, string>} */
|
|
71
|
+
const params = { room: roomId };
|
|
72
|
+
for (const p of kind.params) {
|
|
73
|
+
// An empty id is a cursor too: `newer` than (created, "") starts at `created` itself (around a message, §7.5).
|
|
74
|
+
if (typeof q[p] !== "string" || (p !== "id" && !q[p])) throw new BadRequestError(`Missing ${p}.`);
|
|
75
|
+
params[p] = q[p];
|
|
76
|
+
}
|
|
77
|
+
const where = [
|
|
78
|
+
"room = {:room}",
|
|
79
|
+
...searchWhere(q.q ?? "", params),
|
|
80
|
+
kind.where,
|
|
81
|
+
// `files` is JSON (§37): `:length` means nothing on it, and every message has at least [].
|
|
82
|
+
q.files === "1" ? `(files != "[]" || forward_of != "")` : "",
|
|
83
|
+
];
|
|
84
|
+
return tagged(e, list(e, where, kind.sort, q, params, [roomId]));
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Answer with `body` and an ETag of it, or 304 when the client has that one already. The tag is a hash of the records as
|
|
89
|
+
* they serialize with their expands and what the enrich hooks added, so anything a page shows changes it. `no-store`:
|
|
90
|
+
* nothing keeps a page but the app itself (cache.ts, which a logout clears), and it sends the tag it kept.
|
|
91
|
+
* @param {core.RequestEvent} e
|
|
92
|
+
* @param {(core.Record | undefined)[]} body
|
|
93
|
+
*/
|
|
94
|
+
function tagged(e, body) {
|
|
95
|
+
const tag = `"${$security.sha256(JSON.stringify([e.requestInfo().query.fields ?? "", e.requestInfo().query.expand ?? "", body])).slice(0, 32)}"`;
|
|
96
|
+
const h = e.response.header();
|
|
97
|
+
h.set("ETag", tag);
|
|
98
|
+
h.set("Cache-Control", "no-store");
|
|
99
|
+
const asked = e.request?.header.get("If-None-Match") ?? "";
|
|
100
|
+
if (asked.split(",").some((t) => t.trim() === tag)) return e.noContent(304);
|
|
101
|
+
return e.json(200, body);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* The conditions for a search's words (§29), matched on `text_key`, folded as the server stores it: each word once, the
|
|
106
|
+
* first MAX_WORDS. `~` treats a % in the value as a wildcard (and then stops adding its own), so it is escaped (QA
|
|
107
|
+
* BUG-34); `_` already is. So is the escape character itself (QA BUG-112).
|
|
108
|
+
* @param {string} text
|
|
109
|
+
* @param {Record<string, string>} params the words' values go in here
|
|
110
|
+
*/
|
|
111
|
+
function searchWhere(text, params) {
|
|
112
|
+
const words = [...new Set(searchKey(text).split(/\s+/).filter(Boolean))].slice(0, MAX_WORDS);
|
|
113
|
+
return words.map((w, i) => {
|
|
114
|
+
params[`w${i}`] = w.replace(/[\\%]/g, "\\$&");
|
|
115
|
+
return `text_key ~ {:w${i}}`;
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* GET /api/chat/notifiable?rooms=a,b&since=…[&every=a] → other people's messages in `rooms` since `since` that are
|
|
121
|
+
* DMs or replies to you, or any message in an `every` room (ANDROID.md §21.2, §24): newest first, `limit` of them. The
|
|
122
|
+
* rooms you can't see are left out.
|
|
123
|
+
* @param {core.RequestEvent} e
|
|
124
|
+
*/
|
|
125
|
+
function notifiable(e) {
|
|
126
|
+
const q = e.requestInfo().query;
|
|
127
|
+
if (!q.since) throw new BadRequestError("Missing since.");
|
|
128
|
+
const me = e.auth?.id ?? "";
|
|
129
|
+
const ids = (/** @type {string} */ s) => (s ?? "").split(",").filter(Boolean);
|
|
130
|
+
const rooms = ids(q.rooms)
|
|
131
|
+
.slice(0, MAX_ROOMS)
|
|
132
|
+
.filter((r) => visibleRoom(e.app, r, me));
|
|
133
|
+
if (!rooms.length) return e.json(200, []);
|
|
134
|
+
const every = new Set(ids(q.every));
|
|
135
|
+
/** @type {Record<string, string>} */
|
|
136
|
+
const params = { me, since: q.since };
|
|
137
|
+
rooms.forEach((r, i) => {
|
|
138
|
+
params[`r${i}`] = r;
|
|
139
|
+
});
|
|
140
|
+
const inRooms = rooms.map((_, i) => `room = {:r${i}}`).join(" || ");
|
|
141
|
+
const all = rooms.map((r, i) => (every.has(r) ? ` || room = {:r${i}}` : "")).join("");
|
|
142
|
+
const where = [
|
|
143
|
+
`(${inRooms})`,
|
|
144
|
+
"created > {:since}",
|
|
145
|
+
"author != {:me}",
|
|
146
|
+
"deleted = false",
|
|
147
|
+
`(room.kind = "dm" || reply_to.author = {:me}${all})`,
|
|
148
|
+
];
|
|
149
|
+
return e.json(200, list(e, where, "-created,-id", q, params, rooms));
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* The messages matching every condition in `where`, a page of them as `q`'s `limit` and `page` say, enriched. They
|
|
154
|
+
* are all in `rooms`, which the caller can see.
|
|
155
|
+
* @param {core.RequestEvent} e
|
|
156
|
+
* @param {string[]} where
|
|
157
|
+
* @param {string} sort
|
|
158
|
+
* @param {Record<string, any>} q
|
|
159
|
+
* @param {Record<string, string>} params
|
|
160
|
+
* @param {string[]} rooms
|
|
161
|
+
*/
|
|
162
|
+
function list(e, where, sort, q, params, rooms) {
|
|
163
|
+
const limit = Math.min(Math.max(Number.parseInt(q.limit, 10) || PAGE_SIZE, 1), MAX_LIMIT);
|
|
164
|
+
const page = Math.max(Number.parseInt(q.page, 10) || 1, 1);
|
|
165
|
+
const items = e.app.findRecordsByFilter("messages", where.filter(Boolean).join(" && "), sort, limit, (page - 1) * limit, params);
|
|
166
|
+
enrichInRooms(e, rooms, () => {
|
|
167
|
+
$apis.enrichRecords(e, items);
|
|
168
|
+
return items;
|
|
169
|
+
});
|
|
170
|
+
return items;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
module.exports = { rooms, messages, notifiable };
|