chirkle 0.3.0 → 0.4.1

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 (156) hide show
  1. package/README.md +99 -47
  2. package/bin/release/darwin-amd64/chirkle-server +4 -0
  3. package/bin/release/darwin-arm64/chirkle-server +0 -0
  4. package/bin/release/linux-amd64/chirkle-server +0 -0
  5. package/bin/release/linux-arm64/chirkle-server +0 -0
  6. package/package.json +9 -6
  7. package/pb_hooks/federation/inbox.js +2 -69
  8. package/pb_hooks/federation/messages.js +5 -3
  9. package/pb_hooks/federation/net.js +1 -0
  10. package/pb_hooks/federation/people.js +1 -0
  11. package/pb_hooks/federation.pb.js +1 -8
  12. package/pb_hooks/lib/access.js +33 -10
  13. package/pb_hooks/lib/account.js +542 -6
  14. package/pb_hooks/lib/anonymous.js +2 -129
  15. package/pb_hooks/lib/bulk.js +1 -2
  16. package/pb_hooks/lib/collections.js +4 -4
  17. package/pb_hooks/lib/dms.js +1 -1
  18. package/pb_hooks/lib/files.js +82 -120
  19. package/pb_hooks/lib/handles.js +2 -2
  20. package/pb_hooks/lib/inbox.js +40 -54
  21. package/pb_hooks/lib/invites.js +266 -0
  22. package/pb_hooks/lib/media.js +5 -43
  23. package/pb_hooks/lib/messages.js +72 -117
  24. package/pb_hooks/lib/moderation.js +2 -16
  25. package/pb_hooks/lib/reactions.js +28 -4
  26. package/pb_hooks/lib/retention.js +88 -0
  27. package/pb_hooks/lib/site.js +13 -2
  28. package/pb_hooks/lib/stats.js +6 -34
  29. package/pb_hooks/lib/users.js +88 -7
  30. package/pb_hooks/lib/worker.js +22 -1
  31. package/pb_hooks/main.pb.js +85 -94
  32. package/pb_hooks/telegram/api.js +64 -12
  33. package/pb_hooks/telegram/inbound.js +158 -31
  34. package/pb_hooks/telegram/links.js +4 -3
  35. package/pb_hooks/telegram/outbound.js +86 -45
  36. package/pb_hooks/telegram/people.js +3 -3
  37. package/pb_hooks/telegram/worker.js +59 -15
  38. package/pb_migrations/1760000045_password_reset.js +38 -0
  39. package/pb_migrations/1760000047_telegram_supergroup_ids.js +51 -0
  40. package/pb_migrations/1760000048_inbox_reactions_merged.js +24 -0
  41. package/pb_migrations/1760000049_inbox_room_index.js +22 -0
  42. package/pb_migrations/1760000050_messages_unread_index.js +22 -0
  43. package/pb_migrations/1760000051_users_kind.js +31 -0
  44. package/pb_migrations/1760000052_deleted_accounts.js +19 -0
  45. package/pb_migrations/1760000053_account_jobs.js +45 -0
  46. package/pb_migrations/1760000054_room_invites.js +39 -0
  47. package/pb_migrations/1760000055_invite_barred.js +16 -0
  48. package/pb_migrations/1760000056_telegram_fetch.js +21 -0
  49. package/pb_public/assets/{access-PB77EH4F.css → access-GPRLOZOO.css} +2 -2
  50. package/pb_public/assets/{access-PB77EH4F.css.map → access-GPRLOZOO.css.map} +2 -2
  51. package/pb_public/assets/access-UK3L54NR.js +2 -0
  52. package/pb_public/assets/access-UK3L54NR.js.map +7 -0
  53. package/pb_public/assets/account-CT2BVMAX.css +2 -0
  54. package/pb_public/assets/account-CT2BVMAX.css.map +7 -0
  55. package/pb_public/assets/account-api-J6A6IYVX.js +2 -0
  56. package/pb_public/assets/account-api-J6A6IYVX.js.map +7 -0
  57. package/pb_public/assets/app-HB3NZHQ2.js +3 -0
  58. package/pb_public/assets/app-HB3NZHQ2.js.map +7 -0
  59. package/pb_public/assets/app-XJ73EU5O.css +2 -0
  60. package/pb_public/assets/app-XJ73EU5O.css.map +7 -0
  61. package/pb_public/assets/chunk-56ACD3V5.js +2 -0
  62. package/pb_public/assets/chunk-56ACD3V5.js.map +7 -0
  63. package/pb_public/assets/chunk-AG73QNUN.js +2 -0
  64. package/pb_public/assets/chunk-AG73QNUN.js.map +7 -0
  65. package/pb_public/assets/chunk-DCLJRQ53.js +2 -0
  66. package/pb_public/assets/chunk-DCLJRQ53.js.map +7 -0
  67. package/pb_public/assets/chunk-DZC4SY4M.js +2 -0
  68. package/pb_public/assets/chunk-DZC4SY4M.js.map +7 -0
  69. package/pb_public/assets/chunk-N2OFGBCZ.js +2 -0
  70. package/pb_public/assets/chunk-N2OFGBCZ.js.map +7 -0
  71. package/pb_public/assets/chunk-OKIIBH7O.js +2 -0
  72. package/pb_public/assets/chunk-OKIIBH7O.js.map +7 -0
  73. package/pb_public/assets/chunk-RPCBA7VF.js +2 -0
  74. package/pb_public/assets/chunk-RPCBA7VF.js.map +7 -0
  75. package/pb_public/assets/chunk-UZDXAORM.js +2 -0
  76. package/pb_public/assets/chunk-UZDXAORM.js.map +7 -0
  77. package/pb_public/assets/chunk-VTOUI25E.js +4 -0
  78. package/pb_public/assets/chunk-VTOUI25E.js.map +7 -0
  79. package/pb_public/assets/chunk-WR25F7FU.js +2 -0
  80. package/pb_public/assets/chunk-WR25F7FU.js.map +7 -0
  81. package/pb_public/assets/{emoji-VA2WCEAC.css → emoji-WWNPWCF3.css} +2 -2
  82. package/pb_public/assets/{emoji-VA2WCEAC.css.map → emoji-WWNPWCF3.css.map} +2 -2
  83. package/pb_public/assets/{emoji-picker-65VVVGYW.js → emoji-picker-K6JTK2GV.js} +4 -4
  84. package/pb_public/assets/emoji-picker-K6JTK2GV.js.map +7 -0
  85. package/pb_public/assets/forward-267HRNPY.js +2 -0
  86. package/pb_public/assets/forward-267HRNPY.js.map +7 -0
  87. package/pb_public/assets/inbox-CLMYESNI.js +2 -0
  88. package/pb_public/assets/inbox-CLMYESNI.js.map +7 -0
  89. package/pb_public/assets/invite-OGT5E2MZ.js +2 -0
  90. package/pb_public/assets/invite-OGT5E2MZ.js.map +7 -0
  91. package/pb_public/assets/invite-api-7G7XPXQW.js +2 -0
  92. package/pb_public/assets/invite-api-7G7XPXQW.js.map +7 -0
  93. package/pb_public/assets/lazy-H3KIJVB5.js +2 -0
  94. package/pb_public/assets/lazy-H3KIJVB5.js.map +7 -0
  95. package/pb_public/assets/login-TK6K4WGB.js +2 -0
  96. package/pb_public/assets/login-TK6K4WGB.js.map +7 -0
  97. package/pb_public/assets/media-WZ4653L5.js +2 -0
  98. package/pb_public/assets/media-WZ4653L5.js.map +7 -0
  99. package/pb_public/assets/mention-suggest-ODJD2IC5.js +2 -0
  100. package/pb_public/assets/mention-suggest-ODJD2IC5.js.map +7 -0
  101. package/pb_public/assets/notify-EPDM772N.js +2 -0
  102. package/pb_public/assets/notify-EPDM772N.js.map +7 -0
  103. package/pb_public/assets/profile-3R6S5QYS.js +2 -0
  104. package/pb_public/assets/profile-3R6S5QYS.js.map +7 -0
  105. package/pb_public/assets/search-WCHOGAJQ.js +2 -0
  106. package/pb_public/assets/search-WCHOGAJQ.js.map +7 -0
  107. package/pb_public/assets/stats-GTO2H6PG.js +2 -0
  108. package/pb_public/assets/stats-GTO2H6PG.js.map +7 -0
  109. package/pb_public/assets/switcher-TFSO45KV.js +2 -0
  110. package/pb_public/assets/switcher-TFSO45KV.js.map +7 -0
  111. package/pb_public/assets/user-search-3HQOCQWL.js +2 -0
  112. package/pb_public/assets/user-search-3HQOCQWL.js.map +7 -0
  113. package/pb_public/assets/viewer-2Y5FJBW4.js +2 -0
  114. package/pb_public/assets/viewer-2Y5FJBW4.js.map +7 -0
  115. package/pb_public/index.html +10 -2
  116. package/pb_public/stats.html +1 -1
  117. package/scripts/service.mjs +201 -0
  118. package/scripts/start.mjs +21 -17
  119. package/pb_hooks/lib/enrich.js +0 -75
  120. package/pb_hooks/lib/lists.js +0 -179
  121. package/pb_hooks/lib/live.js +0 -137
  122. package/pb_hooks/lib/reads.js +0 -183
  123. package/pb_public/assets/access-GUDTDXIP.js +0 -2
  124. package/pb_public/assets/access-GUDTDXIP.js.map +0 -7
  125. package/pb_public/assets/app-3WX5JYL2.js +0 -3
  126. package/pb_public/assets/app-3WX5JYL2.js.map +0 -7
  127. package/pb_public/assets/app-WAFKVN2H.css +0 -2
  128. package/pb_public/assets/app-WAFKVN2H.css.map +0 -7
  129. package/pb_public/assets/emoji-picker-65VVVGYW.js.map +0 -7
  130. package/pb_public/assets/forward-66PELNWT.js +0 -2
  131. package/pb_public/assets/forward-66PELNWT.js.map +0 -7
  132. package/pb_public/assets/inbox-TZJWPRTG.js +0 -2
  133. package/pb_public/assets/inbox-TZJWPRTG.js.map +0 -7
  134. package/pb_public/assets/lazy-4CXRBHHM.js +0 -2
  135. package/pb_public/assets/lazy-4CXRBHHM.js.map +0 -7
  136. package/pb_public/assets/login-G7Y44CJ7.js +0 -2
  137. package/pb_public/assets/login-G7Y44CJ7.js.map +0 -7
  138. package/pb_public/assets/media-FPRU2QH5.js +0 -2
  139. package/pb_public/assets/media-FPRU2QH5.js.map +0 -7
  140. package/pb_public/assets/mention-suggest-R7MXUH6R.js +0 -2
  141. package/pb_public/assets/mention-suggest-R7MXUH6R.js.map +0 -7
  142. package/pb_public/assets/notify-RQ6ZLR46.js +0 -2
  143. package/pb_public/assets/notify-RQ6ZLR46.js.map +0 -7
  144. package/pb_public/assets/profile-2CNVT2KX.js +0 -2
  145. package/pb_public/assets/profile-2CNVT2KX.js.map +0 -7
  146. package/pb_public/assets/search-3UT4HMES.js +0 -2
  147. package/pb_public/assets/search-3UT4HMES.js.map +0 -7
  148. package/pb_public/assets/stats-JX52AQCO.js +0 -2
  149. package/pb_public/assets/stats-JX52AQCO.js.map +0 -7
  150. package/pb_public/assets/switcher-CEUKRLEY.js +0 -2
  151. package/pb_public/assets/switcher-CEUKRLEY.js.map +0 -7
  152. package/pb_public/assets/user-search-7GNEIXMN.js +0 -2
  153. package/pb_public/assets/user-search-7GNEIXMN.js.map +0 -7
  154. package/pb_public/assets/viewer-DXT7SKOU.js +0 -2
  155. package/pb_public/assets/viewer-DXT7SKOU.js.map +0 -7
  156. package/scripts/fetch-pocketbase.sh +0 -63
@@ -12,10 +12,18 @@
12
12
  <link rel="apple-touch-icon" href="/icons/apple-touch-icon.png">
13
13
  <link rel="icon" type="image/svg+xml" href="/icons/icon.svg">
14
14
  <link rel="preload" href="/assets/inter-latin-NRMW37G5.woff2" as="font" type="font/woff2" crossorigin>
15
- <link rel="stylesheet" href="/assets/app-WAFKVN2H.css">
15
+ <link rel="stylesheet" href="/assets/app-XJ73EU5O.css">
16
16
  </head>
17
17
  <body>
18
18
  <div id="app"><header class="app-bar"><span class="brand">Chirkle</span></header><main class="app-main"></main></div>
19
- <script type="module" src="/assets/app-3WX5JYL2.js"></script>
19
+ <script type="module" src="/assets/app-HB3NZHQ2.js"></script>
20
+ <link rel="modulepreload" href="/assets/chunk-AG73QNUN.js">
21
+ <link rel="modulepreload" href="/assets/chunk-DZC4SY4M.js">
22
+ <link rel="modulepreload" href="/assets/chunk-N2OFGBCZ.js">
23
+ <link rel="modulepreload" href="/assets/chunk-OKIIBH7O.js">
24
+ <link rel="modulepreload" href="/assets/chunk-RPCBA7VF.js">
25
+ <link rel="modulepreload" href="/assets/chunk-UZDXAORM.js">
26
+ <link rel="modulepreload" href="/assets/chunk-VTOUI25E.js">
27
+ <link rel="modulepreload" href="/assets/chunk-WR25F7FU.js">
20
28
  </body>
21
29
  </html>
@@ -20,6 +20,6 @@
20
20
  <span id="stats-updated" class="stats-updated" aria-live="polite"></span>
21
21
  </header>
22
22
  <main id="stats" class="stats"><p class="loading">Loading…</p></main>
23
- <script type="module" src="/assets/stats-JX52AQCO.js"></script>
23
+ <script type="module" src="/assets/stats-GTO2H6PG.js"></script>
24
24
  </body>
25
25
  </html>
@@ -0,0 +1,201 @@
1
+ // `chirkle install-service` / `chirkle uninstall-service` (scripts/start.mjs): run Chirkle under systemd in one command.
2
+ //
3
+ // sudo npx chirkle install-service chat.example.com HTTPS (Let's Encrypt) on :80/:443
4
+ // sudo npx chirkle install-service --http=127.0.0.1:8090 behind a reverse proxy (TRUSTED_PROXY=X-Forwarded-For)
5
+ // npx chirkle install-service ... --dry-run print what it would do, change nothing
6
+ // sudo npx chirkle uninstall-service stop, disable and remove the unit (the data stays)
7
+ //
8
+ // It copies this version of the server, pb_public/, pb_migrations/ and pb_hooks/ to --prefix (/opt/chirkle), creates
9
+ // the system user --user (chirkle) that owns the data directory (<prefix>/pb_data, or --data), writes
10
+ // /etc/systemd/system/<--name>.service, and enables and (re)starts it. Running it again with a newer version upgrades
11
+ // in place: the files are replaced and the service restarted, the data is kept. Any other flags go to `serve`.
12
+
13
+ import { spawnSync } from "node:child_process";
14
+ import { chownSync, cpSync, existsSync, mkdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
15
+ import { isAbsolute, join, resolve } from "node:path";
16
+
17
+ const UNIT_DIR = "/etc/systemd/system";
18
+
19
+ /** @param {string} message @returns {never} */
20
+ function fail(message) {
21
+ console.error(`chirkle: ${message}`);
22
+ process.exit(1);
23
+ }
24
+
25
+ /**
26
+ * Split `args` into our options and the flags passed through to `serve`.
27
+ * @param {string[]} args
28
+ */
29
+ export function parseArgs(args) {
30
+ /** @type {{ prefix: string, user: string, name: string, data: string | undefined, dryRun: boolean, serve: string[] }} */
31
+ const opts = { prefix: "/opt/chirkle", user: "chirkle", name: "chirkle", data: undefined, dryRun: false, serve: [] };
32
+ for (let i = 0; i < args.length; i++) {
33
+ const arg = /** @type {string} */ (args[i]);
34
+ const m = /^--(prefix|user|name|data)(?:=(.*))?$/.exec(arg);
35
+ if (m) {
36
+ const value = m[2] ?? args[++i];
37
+ if (!value) fail(`--${m[1]} needs a value`);
38
+ opts[/** @type {"prefix" | "user" | "name" | "data"} */ (m[1])] = value;
39
+ } else if (arg === "--dry-run" || arg === "-n") {
40
+ opts.dryRun = true;
41
+ } else {
42
+ opts.serve.push(arg);
43
+ }
44
+ }
45
+ if (!isAbsolute(opts.prefix)) opts.prefix = resolve(opts.prefix);
46
+ opts.data = opts.data ? resolve(opts.data) : join(opts.prefix, "pb_data");
47
+ if (!/^[a-z_][a-z0-9_-]*$/.test(opts.user)) fail(`not a valid user name: ${opts.user}`);
48
+ if (!/^[A-Za-z0-9_.@-]+$/.test(opts.name)) fail(`not a valid unit name: ${opts.name}`);
49
+ return /** @type {typeof opts & { data: string }} */ (opts);
50
+ }
51
+
52
+ /** systemd's quoting for one ExecStart word. @param {string} s */
53
+ const quote = (s) => (/^[A-Za-z0-9_@%+=:,./-]+$/.test(s) ? s : `"${s.replace(/[\\"]/g, "\\$&").replace(/%/g, "%%")}"`);
54
+
55
+ /**
56
+ * The unit file.
57
+ * @param {ReturnType<typeof parseArgs>} opts
58
+ */
59
+ export function unitFile(opts) {
60
+ const { prefix, data, user, serve } = opts;
61
+ /** @param {string} flag */
62
+ const has = (flag) => serve.some((a) => a === flag || a.startsWith(`${flag}=`));
63
+ const domain = serve.find((a) => !a.startsWith("-"));
64
+ const flags = [];
65
+ if (!domain && !has("--https") && !has("--http")) flags.push("--http=127.0.0.1:8090");
66
+ const defaults = {
67
+ "--dir": data,
68
+ "--publicDir": join(prefix, "pb_public"),
69
+ "--migrationsDir": join(prefix, "pb_migrations"),
70
+ "--hooksDir": join(prefix, "pb_hooks"),
71
+ "--hooksPool": "100",
72
+ // Upgrades replace pb_hooks/ and then restart: no reload in between against the old binary.
73
+ "--hooksWatch": "false",
74
+ };
75
+ for (const [flag, value] of Object.entries(defaults)) if (!has(flag)) flags.push(`${flag}=${value}`);
76
+ const argv = [join(prefix, "chirkle-server"), "serve", ...serve, ...flags];
77
+
78
+ // On loopback only a proxy on this machine can reach it, so trust the client IP it forwards (README "Deploying").
79
+ const http = [...serve, ...flags].find((a) => a.startsWith("--http="))?.slice("--http=".length) ?? "";
80
+ const loopback = !domain && /^(127\.|localhost:|\[::1\]:)/.test(http);
81
+ const port = Number(/:(\d+)$/.exec(http)?.[1] ?? 0);
82
+ const lowPorts = Boolean(domain) || has("--https") || (port > 0 && port < 1024);
83
+
84
+ return `# Written by \`chirkle install-service\`; running it again rewrites this file.
85
+ [Unit]
86
+ Description=Chirkle chat
87
+ After=network-online.target
88
+ Wants=network-online.target
89
+
90
+ [Service]
91
+ User=${user}
92
+ Group=${user}
93
+ WorkingDirectory=${prefix}
94
+ ExecStart=${argv.map(quote).join(" ")}
95
+ ${loopback ? "Environment=TRUSTED_PROXY=X-Forwarded-For\n" : ""}Restart=on-failure
96
+ RestartSec=2
97
+ LimitNOFILE=65536
98
+ ${lowPorts ? "AmbientCapabilities=CAP_NET_BIND_SERVICE\nCapabilityBoundingSet=CAP_NET_BIND_SERVICE\n" : "CapabilityBoundingSet=\n"}NoNewPrivileges=true
99
+ PrivateTmp=true
100
+ ProtectSystem=full
101
+ ProtectHome=true
102
+ ReadWritePaths=${quote(data)}
103
+
104
+ [Install]
105
+ WantedBy=multi-user.target
106
+ `;
107
+ }
108
+
109
+ /**
110
+ * @param {string[]} args what followed `install-service`
111
+ * @param {{ root: string, bin: string }} app where this version's files are
112
+ */
113
+ export function install(args, { root, bin }) {
114
+ const opts = parseArgs(args);
115
+ const { prefix, data, user, name, dryRun } = opts;
116
+ const unitPath = join(UNIT_DIR, `${name}.service`);
117
+ const unit = unitFile(opts);
118
+ const server = join(prefix, "chirkle-server");
119
+
120
+ if (dryRun) {
121
+ console.log(`would copy ${bin} and ${root}/{pb_public,pb_migrations,pb_hooks} to ${prefix}/`);
122
+ console.log(`would create the system user ${user} (if missing) and the data directory ${data}, owned by it`);
123
+ console.log(`would write ${unitPath}, then: systemctl daemon-reload && systemctl enable ${name} && systemctl restart ${name}\n`);
124
+ process.stdout.write(unit);
125
+ return;
126
+ }
127
+ preflight();
128
+
129
+ // ---- the user ----
130
+ if (spawnSync("id", ["-u", user], { stdio: "ignore" }).status !== 0) {
131
+ const shell = ["/usr/sbin/nologin", "/sbin/nologin", "/bin/false"].find((s) => existsSync(s)) ?? "/bin/false";
132
+ sh("useradd", ["--system", "--user-group", "--home-dir", data, "--no-create-home", "--shell", shell, user]);
133
+ }
134
+
135
+ // ---- the files: each staged next to its place and renamed over it, so a running server keeps its old binary ----
136
+ mkdirSync(prefix, { recursive: true });
137
+ const staged = `${server}.new`;
138
+ cpSync(bin, staged);
139
+ renameSync(staged, server);
140
+ for (const dir of ["pb_public", "pb_migrations", "pb_hooks"]) {
141
+ const dest = join(prefix, dir);
142
+ const next = `${dest}.new`;
143
+ const old = `${dest}.old`;
144
+ rmSync(next, { recursive: true, force: true });
145
+ rmSync(old, { recursive: true, force: true });
146
+ cpSync(join(root, dir), next, { recursive: true });
147
+ if (existsSync(dest)) renameSync(dest, old);
148
+ renameSync(next, dest);
149
+ rmSync(old, { recursive: true, force: true });
150
+ }
151
+ if (!existsSync(data)) {
152
+ mkdirSync(data, { recursive: true, mode: 0o750 });
153
+ const ids = (/** @type {string} */ flag) => Number(spawnSync("id", [flag, user], { encoding: "utf8" }).stdout.trim());
154
+ chownSync(data, ids("-u"), ids("-g"));
155
+ }
156
+
157
+ // ---- the unit ----
158
+ const upgrade = existsSync(unitPath);
159
+ writeFileSync(unitPath, unit);
160
+ sh("systemctl", ["daemon-reload"]);
161
+ sh("systemctl", ["enable", "--quiet", name]);
162
+ sh("systemctl", ["restart", name]);
163
+
164
+ const active = spawnSync("systemctl", ["is-active", "--quiet", name]).status === 0;
165
+ console.log(`
166
+ ${upgrade ? "Upgraded" : "Installed"} ${name}.service (${prefix}, data in ${data}): ${active ? "running" : "NOT running"}.
167
+ ${active ? "" : ` See why: journalctl -u ${name} -e\n`} Logs: journalctl -u ${name} -f
168
+ Admin account: sudo -u ${user} ${server} superuser upsert you@example.com <password> --dir=${data}
169
+ Upgrade: sudo npx chirkle@latest install-service ${args.join(" ")}
170
+ Remove: sudo npx chirkle uninstall-service${name === "chirkle" ? "" : ` --name=${name}`}`);
171
+ if (!active) process.exit(1);
172
+ }
173
+
174
+ /** @param {string[]} args */
175
+ export function uninstall(args) {
176
+ const { name, prefix, data, dryRun } = parseArgs(args);
177
+ const unitPath = join(UNIT_DIR, `${name}.service`);
178
+ if (dryRun) {
179
+ console.log(`would stop and disable ${name}, then remove ${unitPath}`);
180
+ return;
181
+ }
182
+ preflight();
183
+ if (!existsSync(unitPath)) fail(`${unitPath} does not exist`);
184
+ sh("systemctl", ["disable", "--now", "--quiet", name]);
185
+ rmSync(unitPath);
186
+ sh("systemctl", ["daemon-reload"]);
187
+ console.log(`Removed ${name}.service. The files are still in ${prefix} and the data in ${data}: delete them yourself.`);
188
+ }
189
+
190
+ function preflight() {
191
+ if (process.platform !== "linux") fail("install-service needs Linux with systemd");
192
+ if (spawnSync("systemctl", ["--version"], { stdio: "ignore" }).status !== 0) fail("systemctl not found: is this a systemd system?");
193
+ if (process.getuid?.() !== 0) fail("run it as root: sudo npx chirkle install-service ... (or --dry-run to see what it does)");
194
+ }
195
+
196
+ /** @param {string} cmd @param {string[]} argv */
197
+ function sh(cmd, argv) {
198
+ const r = spawnSync(cmd, argv, { stdio: "inherit" });
199
+ if (r.error) fail(`${cmd}: ${r.error.message}`);
200
+ if (r.status !== 0) fail(`${cmd} ${argv.join(" ")} failed (exit ${r.status})`);
201
+ }
package/scripts/start.mjs CHANGED
@@ -1,15 +1,17 @@
1
1
  #!/usr/bin/env node
2
2
  // `npm start` / `npx chirkle`: run the production server. In a source checkout it builds web/ → pb_public/ first;
3
- // the npm package ships pb_public/ built. PocketBase (pinned, checksum-verified) is downloaded on the first run.
3
+ // the npm package ships pb_public/ built. The server (server/: PocketBase with the hot paths in Go) is built with Go in a
4
+ // checkout (`npm run setup`), and ships built for each platform in the npm package (bin/release/).
4
5
  //
5
6
  // chirkle serve on http://127.0.0.1:8090 (HOST, PORT), data in ./pb_data (CHIRKLE_DATA)
6
7
  // chirkle chat.example.com serve with HTTPS (Let's Encrypt) on :80/:443; any other `pocketbase serve` flags
7
8
  // chirkle superuser upsert <email> <password>
8
9
  // the other PocketBase commands, on the same data directory
10
+ // sudo chirkle install-service chat.example.com
11
+ // install it under systemd (scripts/service.mjs); uninstall-service removes it
9
12
 
10
13
  import { spawn, spawnSync } from "node:child_process";
11
- import { accessSync, constants, existsSync, mkdirSync } from "node:fs";
12
- import { homedir } from "node:os";
14
+ import { existsSync } from "node:fs";
13
15
  import { dirname, join, resolve } from "node:path";
14
16
  import { fileURLToPath } from "node:url";
15
17
 
@@ -38,28 +40,30 @@ if (existsSync(join(ROOT, "web")) && existsSync(join(ROOT, "node_modules/esbuild
38
40
  fail("pb_public/ is not built: run `npm install` (with dev dependencies) first");
39
41
  }
40
42
 
41
- // ---- PocketBase: next to the package when it can write there (a checkout, a local install), else in the cache ----
42
- let binDir = join(ROOT, "bin");
43
- try {
44
- mkdirSync(binDir, { recursive: true });
45
- accessSync(binDir, constants.W_OK);
46
- } catch {
47
- binDir = join(process.env.XDG_CACHE_HOME || join(homedir(), ".cache"), "chirkle");
43
+ // ---- the server: built from server/ in a checkout, else the package's own for this platform ----
44
+ let bin = join(ROOT, "bin/chirkle-server");
45
+ if (existsSync(join(ROOT, "server/go.mod"))) {
46
+ run(process.execPath, [join(ROOT, "scripts/build-server.mjs")], { stdio: ["inherit", "ignore", "inherit"] });
47
+ } else {
48
+ const os = { linux: "linux", darwin: "darwin" }[/** @type {string} */ (process.platform)];
49
+ const arch = { x64: "amd64", arm64: "arm64" }[/** @type {string} */ (process.arch)];
50
+ bin = join(ROOT, "bin/release", `${os}-${arch}`, "chirkle-server");
51
+ if (!os || !arch || !existsSync(bin)) fail(`no server built for ${process.platform}-${process.arch} in this package`);
48
52
  }
49
- run("sh", [join(ROOT, "scripts/fetch-pocketbase.sh")], {
50
- env: { ...process.env, PB_BIN_DIR: binDir },
51
- stdio: ["inherit", "ignore", "inherit"],
52
- });
53
53
 
54
54
  // ---- run it ----
55
55
  /** @param {string[]} argv */
56
56
  const exec = (argv) => {
57
- const pb = spawn(join(binDir, "pocketbase"), argv, { stdio: "inherit" });
57
+ const pb = spawn(bin, argv, { stdio: "inherit" });
58
58
  for (const signal of /** @type {const} */ (["SIGINT", "SIGTERM", "SIGHUP"])) process.on(signal, () => pb.kill(signal));
59
59
  pb.on("error", (err) => fail(err.message));
60
60
  pb.on("exit", (code, signal) => process.exit(code ?? (signal ? 1 : 0)));
61
61
  };
62
- if (["--version", "-v", "--help", "-h", "help"].includes(args[0] ?? "")) {
62
+ if (args[0] === "install-service" || args[0] === "uninstall-service") {
63
+ const service = await import("./service.mjs");
64
+ if (args[0] === "install-service") service.install(args.slice(1), { root: ROOT, bin });
65
+ else service.uninstall(args.slice(1));
66
+ } else if (["--version", "-v", "--help", "-h", "help"].includes(args[0] ?? "")) {
63
67
  exec(args);
64
68
  } else {
65
69
  serve();
@@ -83,7 +87,7 @@ function serve() {
83
87
  defaults["--http"] = `${process.env.HOST || "127.0.0.1"}:${process.env.PORT || "8090"}`;
84
88
  }
85
89
  defaults["--publicDir"] = join(ROOT, "pb_public");
86
- // PocketBase enriches a page of messages in parallel, one JS hook call each (as in the Dockerfile).
90
+ // JS hook runtimes kept warm (as in the Dockerfile): the records API's hooks run in them.
87
91
  defaults["--hooksPool"] = "100";
88
92
  }
89
93
  const flags = Object.entries(defaults)
@@ -1,75 +0,0 @@
1
- /// <reference path="../../types/pocketbase.d.ts" />
2
- // What the messages enrich hook (main.pb.js) needs before it loads lib/messages.js: whether a message needs anything
3
- // at all, and the list routes' mark on the rooms they checked. No require here: under load PocketBase runs a hook
4
- // beyond --hooksPool in a JS runtime made for that one call, which loads every module it requires from scratch, and
5
- // lib/messages.js with what it requires made a room page several times slower (docs/PERF.md).
6
-
7
- /**
8
- * The query parameter a list route (lib/lists.js) adds while it enriches its page: the rooms it has checked the caller
9
- * can see, every listed message being in one of them. The hooks then leave those messages to the route (lib/messages.js
10
- * showOriginals), and a page costs no query per message. The hooks see a copy of the request's info, but its query is
11
- * the same map. A client can send the parameter too, so its value starts with a secret of this process.
12
- */
13
- const CHECKED = "__chirkle_checked";
14
- const SECRET_KEY = "enrich.checkedSecret";
15
-
16
- /** @param {core.App} app */
17
- const secret = (app) => String(app.store().getOrSet(SECRET_KEY, () => $security.randomString(32)));
18
-
19
- /**
20
- * Run `enrich` (a call of $apis.enrichRecords) with the mark that rooms `rooms` were checked.
21
- * @template T
22
- * @param {core.RequestEvent} e
23
- * @param {string[]} rooms
24
- * @param {() => T} enrich
25
- * @returns {T}
26
- */
27
- function markChecked(e, rooms, enrich) {
28
- const query = e.requestInfo().query;
29
- query[CHECKED] = `${secret(e.app)} ${rooms.join(",")}`;
30
- try {
31
- return enrich();
32
- } finally {
33
- delete query[CHECKED];
34
- }
35
- }
36
-
37
- /**
38
- * Did a list route check this message's room?
39
- * @param {core.RecordEnrichEvent} e
40
- */
41
- function inCheckedRoom(e) {
42
- const mark = String(e.requestInfo?.query?.[CHECKED] ?? "");
43
- if (!mark) return false;
44
- const s = secret(e.app);
45
- return (
46
- mark.startsWith(`${s} `) &&
47
- mark
48
- .slice(s.length + 1)
49
- .split(",")
50
- .includes(e.record?.getString("room") ?? "")
51
- );
52
- }
53
-
54
- /**
55
- * Has lib/messages.js anything to do for this message (showOriginal: a forward; keepToRoom: a reply or reactions)?
56
- * Most messages have neither.
57
- * @param {core.RecordEnrichEvent} e
58
- */
59
- function needsWork(e) {
60
- const rec = e.record;
61
- if (!rec || inCheckedRoom(e)) return false;
62
- if (rec.getString("forward_of") && !rec.getBool("deleted")) return true;
63
- const reactions = rec.getString("reactions");
64
- return !!rec.getString("reply_to") || !(reactions === "" || reactions === "[]" || reactions === "null");
65
- }
66
-
67
- /**
68
- * Is anything about this message's author kept to themselves (lib/anonymous.js, DESIGN.md §35), or the author of the
69
- * message it replies to? Checked for every message, the list routes' too.
70
- * @param {core.RecordEnrichEvent} e
71
- */
72
- const isAnonymous = (e) =>
73
- !!e.record && (e.record.getBool("anonymous") || e.record.getBool("forwarded_anonymous") || !!e.record.expand()?.reply_to);
74
-
75
- module.exports = { markChecked, inCheckedRoom, needsWork, isAnonymous };
@@ -1,179 +0,0 @@
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
- // As the records API's (main.pb.js): this page's ?expand mustn't group messages by author (§35).
39
- require(`${__hooks}/lib/anonymous.js`).refuseProbes(e);
40
- const me = e.auth && !e.auth.isSuperuser() ? e.auth.id : "";
41
- const where = e.hasSuperuserAuth() ? "1" : me ? SEES_SQL : "r.visibility = 'open' AND NOT r.archived";
42
- const rows = arrayOf(new DynamicModel({ id: "" }));
43
- e.app.db().newQuery(`SELECT r.id FROM rooms r WHERE ${where} ORDER BY r.name, r.id`).bind({ me }).all(rows);
44
- const found = e.app.findRecordsByIds(
45
- "rooms",
46
- rows.map((r) => r.id),
47
- );
48
- const byId = new Map(found.map((r) => [r?.id, r]));
49
- const items = /** @type {core.Record[]} */ (rows.map((r) => byId.get(r.id)).filter(Boolean));
50
- $apis.enrichRecords(e, items);
51
- return e.json(200, items);
52
- }
53
-
54
- /**
55
- * GET /api/chat/rooms/{room}/messages?kind=latest|first|older|newer|changed → the messages. `older` and `newer` take the
56
- * cursor (`created`, `id`); `changed` takes `since` (an `updated` value) and `from`, `to` (`created` values). `files=1`:
57
- * only messages that may have attachments (theirs, or a forward's original's, §17.7). `q`: only messages with every
58
- * word of it (search, §29; with `latest` and `older`). `limit` (at most 200) and `page` (from 1) as the records API has
59
- * them. A room the caller can't see has no messages, as the records API says. Answered with an ETag: asked again with it
60
- * (If-None-Match), an unchanged page is a 304 without a body (PERF.md §5).
61
- * @param {core.RequestEvent} e
62
- */
63
- function messages(e) {
64
- // As the records API's (main.pb.js): this page's ?expand mustn't group messages by author (§35).
65
- require(`${__hooks}/lib/anonymous.js`).refuseProbes(e);
66
- const roomId = e.request?.pathValue("room") ?? "";
67
- const q = e.requestInfo().query;
68
- // Own keys only: "toString" and the like are the object's too (QA BUG-171).
69
- const name = q.kind || "latest";
70
- const kind = Object.keys(KINDS).includes(name) ? KINDS[name] : null;
71
- if (!kind) throw new BadRequestError("Unknown page kind.");
72
- const me = e.auth && !e.auth.isSuperuser() ? e.auth.id : "";
73
- if (!e.hasSuperuserAuth() && !visibleRoom(e.app, roomId, me)) return e.json(200, []);
74
- /** @type {Record<string, string>} */
75
- const params = { room: roomId };
76
- for (const p of kind.params) {
77
- // An empty id is a cursor too: `newer` than (created, "") starts at `created` itself (around a message, §7.5).
78
- if (typeof q[p] !== "string" || (p !== "id" && !q[p])) throw new BadRequestError(`Missing ${p}.`);
79
- params[p] = q[p];
80
- }
81
- const where = [
82
- "room = {:room}",
83
- ...searchWhere(q.q ?? "", params),
84
- kind.where,
85
- // `files` is JSON (§37): `:length` means nothing on it, and every message has at least [].
86
- q.files === "1" ? `(files != "[]" || forward_of != "")` : "",
87
- ];
88
- return tagged(e, list(e, where, kind.sort, q, params, [roomId]));
89
- }
90
-
91
- /**
92
- * 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
93
- * they serialize with their expands and what the enrich hooks added, so anything a page shows changes it. `no-store`:
94
- * nothing keeps a page but the app itself (cache.ts, which a logout clears), and it sends the tag it kept.
95
- * @param {core.RequestEvent} e
96
- * @param {(core.Record | undefined)[]} body
97
- */
98
- function tagged(e, body) {
99
- const tag = `"${$security.sha256(JSON.stringify([e.requestInfo().query.fields ?? "", e.requestInfo().query.expand ?? "", body])).slice(0, 32)}"`;
100
- const h = e.response.header();
101
- h.set("ETag", tag);
102
- h.set("Cache-Control", "no-store");
103
- const asked = e.request?.header.get("If-None-Match") ?? "";
104
- if (asked.split(",").some((t) => t.trim() === tag)) return e.noContent(304);
105
- return e.json(200, body);
106
- }
107
-
108
- /**
109
- * The conditions for a search's words (§29), matched on `text_key`, folded as the server stores it: each word once, the
110
- * first MAX_WORDS. `~` treats a % in the value as a wildcard (and then stops adding its own), so it is escaped (QA
111
- * BUG-34); `_` already is. So is the escape character itself (QA BUG-112).
112
- * @param {string} text
113
- * @param {Record<string, string>} params the words' values go in here
114
- */
115
- function searchWhere(text, params) {
116
- const words = [...new Set(searchKey(text).split(/\s+/).filter(Boolean))].slice(0, MAX_WORDS);
117
- return words.map((w, i) => {
118
- params[`w${i}`] = w.replace(/[\\%]/g, "\\$&");
119
- return `text_key ~ {:w${i}}`;
120
- });
121
- }
122
-
123
- /**
124
- * GET /api/chat/notifiable?rooms=a,b&since=…[&every=a] → other people's messages in `rooms` since `since` that are
125
- * DMs, replies to you or mentions of you (DESIGN.md §41), or any message in an `every` room (ANDROID.md §21.2, §24): newest first, `limit` of them. The
126
- * rooms you can't see are left out.
127
- * @param {core.RequestEvent} e
128
- */
129
- function notifiable(e) {
130
- // As the records API's (main.pb.js): this page's ?expand mustn't group messages by author (§35).
131
- require(`${__hooks}/lib/anonymous.js`).refuseProbes(e);
132
- const q = e.requestInfo().query;
133
- if (!q.since) throw new BadRequestError("Missing since.");
134
- const me = e.auth?.id ?? "";
135
- const ids = (/** @type {string} */ s) => (s ?? "").split(",").filter(Boolean);
136
- const rooms = ids(q.rooms)
137
- .slice(0, MAX_ROOMS)
138
- .filter((r) => visibleRoom(e.app, r, me));
139
- if (!rooms.length) return e.json(200, []);
140
- const every = new Set(ids(q.every));
141
- /** @type {Record<string, string>} */
142
- const params = { me, since: q.since };
143
- rooms.forEach((r, i) => {
144
- params[`r${i}`] = r;
145
- });
146
- const inRooms = rooms.map((_, i) => `room = {:r${i}}`).join(" || ");
147
- const all = rooms.map((r, i) => (every.has(r) ? ` || room = {:r${i}}` : "")).join("");
148
- const where = [
149
- `(${inRooms})`,
150
- "created > {:since}",
151
- "author != {:me}",
152
- "deleted = false",
153
- `(room.kind = "dm" || reply_to.author = {:me} || mentions.id ?= {:me}${all})`,
154
- ];
155
- return e.json(200, list(e, where, "-created,-id", q, params, rooms));
156
- }
157
-
158
- /**
159
- * The messages matching every condition in `where`, a page of them as `q`'s `limit` and `page` say, enriched. They
160
- * are all in `rooms`, which the caller can see.
161
- * @param {core.RequestEvent} e
162
- * @param {string[]} where
163
- * @param {string} sort
164
- * @param {Record<string, any>} q
165
- * @param {Record<string, string>} params
166
- * @param {string[]} rooms
167
- */
168
- function list(e, where, sort, q, params, rooms) {
169
- const limit = Math.min(Math.max(Number.parseInt(q.limit, 10) || PAGE_SIZE, 1), MAX_LIMIT);
170
- const page = Math.max(Number.parseInt(q.page, 10) || 1, 1);
171
- const items = e.app.findRecordsByFilter("messages", where.filter(Boolean).join(" && "), sort, limit, (page - 1) * limit, params);
172
- enrichInRooms(e, rooms, () => {
173
- $apis.enrichRecords(e, items);
174
- return items;
175
- });
176
- return items;
177
- }
178
-
179
- module.exports = { rooms, messages, notifiable };