chirkle 0.4.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.
- package/README.md +32 -24
- package/bin/release/darwin-amd64/chirkle-server +2 -2
- package/bin/release/darwin-arm64/chirkle-server +0 -0
- package/bin/release/linux-amd64/chirkle-server +0 -0
- package/bin/release/linux-arm64/chirkle-server +0 -0
- package/package.json +2 -1
- package/pb_hooks/lib/account.js +541 -6
- package/pb_hooks/lib/collections.js +4 -4
- package/pb_hooks/lib/dms.js +1 -1
- package/pb_hooks/lib/inbox.js +1 -1
- package/pb_hooks/lib/invites.js +266 -0
- package/pb_hooks/lib/messages.js +11 -2
- package/pb_hooks/lib/moderation.js +1 -1
- package/pb_hooks/lib/retention.js +3 -0
- package/pb_hooks/lib/site.js +1 -1
- package/pb_hooks/lib/users.js +38 -10
- package/pb_hooks/main.pb.js +26 -1
- package/pb_hooks/telegram/api.js +64 -12
- package/pb_hooks/telegram/inbound.js +106 -15
- package/pb_hooks/telegram/outbound.js +63 -37
- package/pb_hooks/telegram/worker.js +59 -15
- package/pb_migrations/1760000052_deleted_accounts.js +19 -0
- package/pb_migrations/1760000053_account_jobs.js +45 -0
- package/pb_migrations/1760000054_room_invites.js +39 -0
- package/pb_migrations/1760000055_invite_barred.js +16 -0
- package/pb_migrations/1760000056_telegram_fetch.js +21 -0
- package/pb_public/assets/{access-PB77EH4F.css → access-GPRLOZOO.css} +2 -2
- package/pb_public/assets/{access-PB77EH4F.css.map → access-GPRLOZOO.css.map} +2 -2
- package/pb_public/assets/access-UK3L54NR.js +2 -0
- package/pb_public/assets/access-UK3L54NR.js.map +7 -0
- package/pb_public/assets/account-CT2BVMAX.css +2 -0
- package/pb_public/assets/account-CT2BVMAX.css.map +7 -0
- package/pb_public/assets/account-api-J6A6IYVX.js +2 -0
- package/pb_public/assets/account-api-J6A6IYVX.js.map +7 -0
- package/pb_public/assets/app-HB3NZHQ2.js +3 -0
- package/pb_public/assets/app-HB3NZHQ2.js.map +7 -0
- package/pb_public/assets/app-XJ73EU5O.css +2 -0
- package/pb_public/assets/app-XJ73EU5O.css.map +7 -0
- package/pb_public/assets/chunk-AG73QNUN.js +2 -0
- package/pb_public/assets/chunk-AG73QNUN.js.map +7 -0
- package/pb_public/assets/chunk-DCLJRQ53.js +2 -0
- package/pb_public/assets/chunk-DCLJRQ53.js.map +7 -0
- package/pb_public/assets/chunk-N2OFGBCZ.js +2 -0
- package/pb_public/assets/{chunk-PWNJABVI.js.map → chunk-N2OFGBCZ.js.map} +4 -4
- package/pb_public/assets/chunk-OKIIBH7O.js +2 -0
- package/pb_public/assets/chunk-OKIIBH7O.js.map +7 -0
- package/pb_public/assets/chunk-UZDXAORM.js +2 -0
- package/pb_public/assets/chunk-UZDXAORM.js.map +7 -0
- package/pb_public/assets/chunk-WR25F7FU.js +2 -0
- package/pb_public/assets/chunk-WR25F7FU.js.map +7 -0
- package/pb_public/assets/invite-OGT5E2MZ.js +2 -0
- package/pb_public/assets/invite-OGT5E2MZ.js.map +7 -0
- package/pb_public/assets/invite-api-7G7XPXQW.js +2 -0
- package/pb_public/assets/invite-api-7G7XPXQW.js.map +7 -0
- package/pb_public/assets/login-TK6K4WGB.js +2 -0
- package/pb_public/assets/{login-ECFBJP6Q.js.map → login-TK6K4WGB.js.map} +1 -1
- package/pb_public/assets/profile-3R6S5QYS.js +2 -0
- package/pb_public/assets/profile-3R6S5QYS.js.map +7 -0
- package/pb_public/assets/stats-GTO2H6PG.js +2 -0
- package/pb_public/assets/stats-GTO2H6PG.js.map +7 -0
- package/pb_public/index.html +7 -5
- package/pb_public/stats.html +1 -1
- package/scripts/service.mjs +201 -0
- package/scripts/start.mjs +7 -1
- package/pb_public/assets/access-LHPD2EHG.js +0 -2
- package/pb_public/assets/access-LHPD2EHG.js.map +0 -7
- package/pb_public/assets/app-6ETOTHXQ.js +0 -3
- package/pb_public/assets/app-6ETOTHXQ.js.map +0 -7
- package/pb_public/assets/app-ZGHECF33.css +0 -2
- package/pb_public/assets/app-ZGHECF33.css.map +0 -7
- package/pb_public/assets/chunk-GXMWOXBX.js +0 -2
- package/pb_public/assets/chunk-GXMWOXBX.js.map +0 -7
- package/pb_public/assets/chunk-IFQGGTSP.js +0 -2
- package/pb_public/assets/chunk-IFQGGTSP.js.map +0 -7
- package/pb_public/assets/chunk-PWNJABVI.js +0 -2
- package/pb_public/assets/login-ECFBJP6Q.js +0 -2
- package/pb_public/assets/profile-NQQLAEDT.js +0 -2
- package/pb_public/assets/profile-NQQLAEDT.js.map +0 -7
- package/pb_public/assets/stats-ARDU576A.js +0 -2
- package/pb_public/assets/stats-ARDU576A.js.map +0 -7
package/README.md
CHANGED
|
@@ -39,6 +39,8 @@ Mentions & replies, which load on first use).
|
|
|
39
39
|
- Unread counts on every room and DM, live, and in sync across your tabs and devices; the total shows in the tab's favicon and title;
|
|
40
40
|
a room with unread messages opens at the first of them, under a "New" line
|
|
41
41
|
- What you were typing is kept per room, even across a reload; "Jump to latest" whenever you are scrolled up
|
|
42
|
+
- Invite links for private rooms: share one link that adds whoever opens it (after logging in or signing up) as a
|
|
43
|
+
member; it works for 1, 7 or 30 days and can be revoked or replaced at any time (web and Android)
|
|
42
44
|
- Moderators, chosen by the admin: they delete anyone's messages, change any room's access, archive rooms, and ban or
|
|
43
45
|
unban people (a banned account can't log in); DMs and private rooms they aren't in stay out of their reach
|
|
44
46
|
- Usage statistics at `/stats` for moderators and the admin: people online now, messages and active people over
|
|
@@ -149,6 +151,32 @@ android/ the Android app (docs/ANDROID.md): core/data (API, realtime, da
|
|
|
149
151
|
|
|
150
152
|
## Deploying
|
|
151
153
|
|
|
154
|
+
### systemd, in one command
|
|
155
|
+
|
|
156
|
+
On a Linux server with Node 22+, with a domain pointing at it, this installs Chirkle as a systemd service that serves
|
|
157
|
+
HTTPS itself (Let's Encrypt, on :80/:443):
|
|
158
|
+
|
|
159
|
+
```sh
|
|
160
|
+
sudo npx chirkle install-service chat.example.com
|
|
161
|
+
sudo -u chirkle /opt/chirkle/chirkle-server superuser upsert you@example.com <password> --dir=/opt/chirkle/pb_data
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
It copies the server, `pb_public/`, `pb_migrations/` and `pb_hooks/` to `/opt/chirkle`, creates the system user
|
|
165
|
+
`chirkle`, which owns the data directory `/opt/chirkle/pb_data` (and nothing else), writes
|
|
166
|
+
`/etc/systemd/system/chirkle.service` (sandboxed: `ProtectSystem`, `ProtectHome`, `NoNewPrivileges`), and enables and
|
|
167
|
+
starts it. Run it again — `sudo npx chirkle@latest install-service chat.example.com` — to upgrade: the files are
|
|
168
|
+
replaced and the service restarted, the data stays. `sudo npx chirkle uninstall-service` stops and removes the unit
|
|
169
|
+
(files and data are left for you to delete).
|
|
170
|
+
|
|
171
|
+
- Without a domain it listens on `127.0.0.1:8090` for a reverse proxy on the same machine, and sets
|
|
172
|
+
`TRUSTED_PROXY=X-Forwarded-For` (see below); `--http=<addr>` picks another address (trusted only on loopback).
|
|
173
|
+
- `--prefix=<dir>`, `--data=<dir>`, `--user=<name>`, `--name=<unit>` (several instances side by side) change the
|
|
174
|
+
defaults; any other flag goes to `serve`.
|
|
175
|
+
- `--dry-run` prints the unit file and what it would do, and changes nothing; use it to write the unit yourself.
|
|
176
|
+
- More settings (`FFMPEG=`, other environment): `sudo systemctl edit chirkle`, which survives reinstalls.
|
|
177
|
+
|
|
178
|
+
### By hand
|
|
179
|
+
|
|
152
180
|
Build once, then copy `bin/chirkle-server`, `pb_public/`, `pb_migrations/` and `pb_hooks/` to the server. It is PocketBase
|
|
153
181
|
with the hot paths in Go (`server/`): the same commands and flags as the `pocketbase` binary. Go builds it for another
|
|
154
182
|
platform with `GOOS`/`GOARCH` (`node scripts/build-server.mjs --all` builds them all into `bin/release/`).
|
|
@@ -161,30 +189,10 @@ npm ci && npm run setup && npm run build
|
|
|
161
189
|
rsync -a bin/chirkle-server pb_public pb_migrations pb_hooks server:/opt/chirkle/
|
|
162
190
|
```
|
|
163
191
|
|
|
164
|
-
With a domain pointing at the server, PocketBase serves HTTPS itself (Let's Encrypt):
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
[Unit]
|
|
169
|
-
Description=Chirkle (PocketBase)
|
|
170
|
-
After=network-online.target
|
|
171
|
-
|
|
172
|
-
[Service]
|
|
173
|
-
User=chirkle
|
|
174
|
-
WorkingDirectory=/opt/chirkle
|
|
175
|
-
ExecStart=/opt/chirkle/chirkle-server serve chat.example.com --hooksPool=100 --dir=/opt/chirkle/pb_data --publicDir=/opt/chirkle/pb_public --migrationsDir=/opt/chirkle/pb_migrations --hooksDir=/opt/chirkle/pb_hooks
|
|
176
|
-
Restart=on-failure
|
|
177
|
-
AmbientCapabilities=CAP_NET_BIND_SERVICE
|
|
178
|
-
LimitNOFILE=65536
|
|
179
|
-
|
|
180
|
-
[Install]
|
|
181
|
-
WantedBy=multi-user.target
|
|
182
|
-
```
|
|
183
|
-
|
|
184
|
-
```sh
|
|
185
|
-
sudo systemctl enable --now chirkle
|
|
186
|
-
sudo -u chirkle /opt/chirkle/chirkle-server superuser upsert you@example.com <password> --dir=/opt/chirkle/pb_data
|
|
187
|
-
```
|
|
192
|
+
With a domain pointing at the server, PocketBase serves HTTPS itself (Let's Encrypt): run
|
|
193
|
+
`chirkle-server serve chat.example.com --hooksPool=100 --dir=… --publicDir=… --migrationsDir=… --hooksDir=…` under your
|
|
194
|
+
init system with `CAP_NET_BIND_SERVICE` (`npx chirkle install-service chat.example.com --dry-run` prints a systemd unit
|
|
195
|
+
for it).
|
|
188
196
|
|
|
189
197
|
Behind an existing reverse proxy instead, use `serve --http=127.0.0.1:8090` and proxy to it (keep
|
|
190
198
|
`/api/realtime` unbuffered — it is a Server-Sent Events stream — and let request bodies through up to 210 MB, since a
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
[diffend] Oversized file quarantined before diffing.
|
|
2
2
|
name: package/bin/release/darwin-amd64/chirkle-server
|
|
3
|
-
size:
|
|
4
|
-
sha256:
|
|
3
|
+
size: 33843680 bytes
|
|
4
|
+
sha256: d3cb6ef1f9413c1584e9875fc55dadbb38534dc3b3f24b6e36d05b39d78d5cf1
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "chirkle",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.1",
|
|
4
4
|
"description": "A small, fast, real-time group chat: one PocketBase server, a vanilla TypeScript web app",
|
|
5
5
|
"license": "GPL-3.0-or-later",
|
|
6
6
|
"repository": {
|
|
@@ -23,6 +23,7 @@
|
|
|
23
23
|
"pb_hooks/",
|
|
24
24
|
"pb_migrations/",
|
|
25
25
|
"scripts/start.mjs",
|
|
26
|
+
"scripts/service.mjs",
|
|
26
27
|
"bin/release/"
|
|
27
28
|
],
|
|
28
29
|
"engines": {
|
package/pb_hooks/lib/account.js
CHANGED
|
@@ -1,20 +1,28 @@
|
|
|
1
1
|
/// <reference path="../../types/pocketbase.d.ts" />
|
|
2
|
-
//
|
|
3
|
-
//
|
|
2
|
+
// Your account (DESIGN.md §22.2, §43):
|
|
3
|
+
// - POST /api/chat/password: change your password. Checks the current one, signs out every other session, and
|
|
4
|
+
// answers like a login (a fresh token and record), so the tab that changed it stays logged in.
|
|
5
|
+
// - POST /api/chat/export, GET /api/chat/export, GET /api/chat/export/file: everything you wrote and keep here, as a
|
|
6
|
+
// JSON file. Asked for, it is made by a worker (an account job), and is then there to download for 7 days.
|
|
7
|
+
// - POST /api/chat/account/delete: delete your account. Its personal data goes at once; its collections, and its
|
|
8
|
+
// messages if its person chooses so, go after, by the same worker, a batch at a time.
|
|
9
|
+
//
|
|
10
|
+
// The worker (a cron job, lib/worker.js) does the work that grows with the account, so a big account or a busy
|
|
11
|
+
// server never holds a request, or the database's write lock, for long (§43.5).
|
|
4
12
|
|
|
5
13
|
/**
|
|
6
14
|
* @param {string} field
|
|
7
15
|
* @param {string} message
|
|
8
16
|
* @param {string} [code]
|
|
9
17
|
*/
|
|
10
|
-
function fieldError(field, message, code = "validation_invalid_value") {
|
|
11
|
-
return new BadRequestError(
|
|
18
|
+
function fieldError(field, message, code = "validation_invalid_value", what = "Failed to change the password.") {
|
|
19
|
+
return new BadRequestError(what, { [field]: new ValidationError(code, message) });
|
|
12
20
|
}
|
|
13
21
|
|
|
14
22
|
/** @param {core.RequestEvent} e */
|
|
15
23
|
function changePassword(e) {
|
|
16
24
|
if (!e.auth) throw new UnauthorizedError("The request requires a logged-in user.");
|
|
17
|
-
const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body);
|
|
25
|
+
const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body ?? {});
|
|
18
26
|
const oldPassword = typeof body.oldPassword === "string" ? body.oldPassword : "";
|
|
19
27
|
const password = typeof body.password === "string" ? body.password : "";
|
|
20
28
|
if (!oldPassword) throw fieldError("oldPassword", "Enter your current password.", "validation_required");
|
|
@@ -29,4 +37,531 @@ function changePassword(e) {
|
|
|
29
37
|
return $apis.recordAuthResponse(e, user, "password");
|
|
30
38
|
}
|
|
31
39
|
|
|
32
|
-
|
|
40
|
+
/** Rows read at a time by the export and the delete. */
|
|
41
|
+
const PAGE = 500;
|
|
42
|
+
|
|
43
|
+
/** Items or messages deleted in one transaction by an erase job. */
|
|
44
|
+
const ERASE_BATCH = 200;
|
|
45
|
+
|
|
46
|
+
/** What an export says it is (§43.2); `version` changes when its shape does. */
|
|
47
|
+
const FORMAT = "chirkle-export";
|
|
48
|
+
const VERSION = 1;
|
|
49
|
+
|
|
50
|
+
/** How long a made export is kept to download. */
|
|
51
|
+
const KEEP_MS = 7 * 24 * 3600_000;
|
|
52
|
+
|
|
53
|
+
/** A made export asked for again within this long is the same one: no new job. */
|
|
54
|
+
const FRESH_MS = 10 * 60_000;
|
|
55
|
+
|
|
56
|
+
/** A job that failed this many times is given up ("failed"). */
|
|
57
|
+
const MAX_TRIES = 5;
|
|
58
|
+
|
|
59
|
+
/** The worker's lock (lib/worker.js), and how long before a run that stopped renewing it is taken over. */
|
|
60
|
+
const LOCK = "account.worker";
|
|
61
|
+
const STALE_MS = 5 * 60_000;
|
|
62
|
+
|
|
63
|
+
/** A time as the database stores it. @param {number} ms */
|
|
64
|
+
const dbDate = (ms) => new Date(ms).toISOString().replace("T", " ");
|
|
65
|
+
|
|
66
|
+
/** A stored time in ms, or 0. @param {string} t */
|
|
67
|
+
const msOf = (t) => (t ? Date.parse(t.replace(" ", "T")) || 0 : 0);
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* What a file is called: its upload's name when recorded, else its stored name without the "_" and 10 characters
|
|
71
|
+
* PocketBase adds (web/src/lib/files.ts attachmentName).
|
|
72
|
+
* @param {Record<string, string>} names
|
|
73
|
+
* @param {string} stored
|
|
74
|
+
*/
|
|
75
|
+
const fileName = (names, stored) => names[stored] || stored.replace(/_[a-z0-9]{10}(\.[^.]*)?$/i, "$1");
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Every record of `collection` matching `filter`, a page at a time, oldest first, by (created, id): a page costs the
|
|
79
|
+
* same however far in it is. `renew` (the worker's) after each page.
|
|
80
|
+
* @param {core.App} app
|
|
81
|
+
* @param {string} collection
|
|
82
|
+
* @param {string} filter
|
|
83
|
+
* @param {Record<string, unknown>} params
|
|
84
|
+
* @param {(rec: core.Record) => void} each
|
|
85
|
+
* @param {() => void} [renew]
|
|
86
|
+
*/
|
|
87
|
+
function eachRecord(app, collection, filter, params, each, renew) {
|
|
88
|
+
/** @type {{ c: string, i: string } | null} */
|
|
89
|
+
let after = null;
|
|
90
|
+
for (;;) {
|
|
91
|
+
/** @type {(core.Record | undefined)[]} */
|
|
92
|
+
const page = after
|
|
93
|
+
? app.findRecordsByFilter(collection, `(${filter}) && (created > {:_c} || (created = {:_c} && id > {:_i}))`, "created,id", PAGE, 0, {
|
|
94
|
+
...params,
|
|
95
|
+
_c: after.c,
|
|
96
|
+
_i: after.i,
|
|
97
|
+
})
|
|
98
|
+
: app.findRecordsByFilter(collection, filter, "created,id", PAGE, 0, params);
|
|
99
|
+
for (const rec of page) if (rec) each(rec);
|
|
100
|
+
if (renew) renew();
|
|
101
|
+
/** @type {core.Record | undefined} */
|
|
102
|
+
const last = page[page.length - 1];
|
|
103
|
+
if (page.length < PAGE || !last) return;
|
|
104
|
+
after = { c: last.getString("created"), i: last.id };
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// ---------------------------------------------------------------- your data (§43.2)
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* A user's newest job of `kind`, or null.
|
|
112
|
+
* @param {core.App} app
|
|
113
|
+
* @param {string} userId
|
|
114
|
+
* @param {"export" | "erase"} kind
|
|
115
|
+
*/
|
|
116
|
+
function latestJob(app, userId, kind) {
|
|
117
|
+
const rows = app.findRecordsByFilter("account_jobs", "user = {:u} && kind = {:k}", "-created,-id", 1, 0, { u: userId, k: kind });
|
|
118
|
+
return rows[0] ?? null;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* What GET and POST /api/chat/export answer: where the newest export is. `state` "none" (never asked, or gone after 7
|
|
123
|
+
* days), "queued" (being made), "done" (to download until `expires`) or "failed".
|
|
124
|
+
* @param {core.Record | null} job
|
|
125
|
+
*/
|
|
126
|
+
function exportStatus(job) {
|
|
127
|
+
if (!job) return { id: "", state: "none", created: "", finished: "", expires: "", size: 0 };
|
|
128
|
+
const state = job.getString("state");
|
|
129
|
+
return {
|
|
130
|
+
id: job.id,
|
|
131
|
+
state,
|
|
132
|
+
created: job.getString("created"),
|
|
133
|
+
finished: job.getString("finished"),
|
|
134
|
+
expires: state === "done" ? dbDate(msOf(job.getString("created")) + KEEP_MS) : "",
|
|
135
|
+
size: job.getInt("size"),
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* GET /api/chat/export: where your newest export is (exportStatus).
|
|
141
|
+
* @param {core.RequestEvent} e
|
|
142
|
+
*/
|
|
143
|
+
function exportState(e) {
|
|
144
|
+
if (!e.auth) throw new UnauthorizedError("The request requires a logged-in user.");
|
|
145
|
+
return e.json(200, exportStatus(latestJob(e.app, e.auth.id, "export")));
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* POST /api/chat/export: make your data into a file (§43.2). Queued for the worker; asked again while it is being made,
|
|
150
|
+
* or within 10 minutes of it being made, the same one. Answers as GET does.
|
|
151
|
+
* @param {core.RequestEvent} e
|
|
152
|
+
*/
|
|
153
|
+
function startExport(e) {
|
|
154
|
+
if (!e.auth) throw new UnauthorizedError("The request requires a logged-in user.");
|
|
155
|
+
const last = latestJob(e.app, e.auth.id, "export");
|
|
156
|
+
const state = last?.getString("state");
|
|
157
|
+
if (last && (state === "queued" || (state === "done" && Date.now() - msOf(last.getString("created")) < FRESH_MS))) {
|
|
158
|
+
return e.json(200, exportStatus(last));
|
|
159
|
+
}
|
|
160
|
+
const job = new Record(e.app.findCollectionByNameOrId("account_jobs"));
|
|
161
|
+
job.set("user", e.auth.id);
|
|
162
|
+
job.set("kind", "export");
|
|
163
|
+
job.set("state", "queued");
|
|
164
|
+
e.app.save(job);
|
|
165
|
+
wake(e.app);
|
|
166
|
+
return e.json(200, exportStatus(job));
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* GET /api/chat/export/file: your newest made export, as a download. Signed in, or with a file token
|
|
171
|
+
* (`?token=`, POST /api/files/token) so that a plain link (the web's, the app's download manager) can fetch it.
|
|
172
|
+
* @param {core.RequestEvent} e
|
|
173
|
+
*/
|
|
174
|
+
function exportFile(e) {
|
|
175
|
+
/** @type {core.Record | undefined} */
|
|
176
|
+
let user = e.auth;
|
|
177
|
+
const token = e.request?.url?.query().get("token") ?? "";
|
|
178
|
+
if (!user && token) {
|
|
179
|
+
try {
|
|
180
|
+
user = e.app.findAuthRecordByToken(token, "file");
|
|
181
|
+
} catch {
|
|
182
|
+
user = undefined;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
if (!e.request) throw new BadRequestError("No request.");
|
|
186
|
+
if (user?.collection().name !== "users") throw new UnauthorizedError("The request requires a logged-in user.");
|
|
187
|
+
const job = latestJob(e.app, user.id, "export");
|
|
188
|
+
const file = job?.getString("state") === "done" ? job.getString("file") : "";
|
|
189
|
+
if (!job || !file) throw new NotFoundError("There is no export to download. Ask for one first.");
|
|
190
|
+
const name = `chirkle-export-${job.getString("created").slice(0, 10)}.json`;
|
|
191
|
+
const fsys = e.app.newFilesystem();
|
|
192
|
+
try {
|
|
193
|
+
e.response.header().set("Cache-Control", "no-store");
|
|
194
|
+
e.response.header().set("Content-Disposition", `attachment; filename="${name}"`);
|
|
195
|
+
fsys.serve(e.response, e.request, `${job.baseFilesPath()}/${file}`, name);
|
|
196
|
+
} finally {
|
|
197
|
+
fsys.close();
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* Write export job `job`'s file (§43.2): the user's profile (with their e-mail); the messages they wrote and haven't
|
|
203
|
+
* deleted, with their files; the rooms those are in and the rooms they made; their collections with their items; the
|
|
204
|
+
* collections they follow; the rooms they hid. Written a record at a time into a temporary file, which is then the
|
|
205
|
+
* job's (protected) `file`: what is held in memory is the room list, not the messages. Files are paths on this server
|
|
206
|
+
* (`/api/files/…`), which whoever has them can open (§37.3). Other people's words aren't in it: a forward names the
|
|
207
|
+
* message it shows, not its text.
|
|
208
|
+
* @param {core.App} app
|
|
209
|
+
* @param {core.Record} job
|
|
210
|
+
* @param {() => void} [renew]
|
|
211
|
+
*/
|
|
212
|
+
function writeExport(app, job, renew) {
|
|
213
|
+
const id = job.getString("user");
|
|
214
|
+
const me = app.findRecordById("users", id);
|
|
215
|
+
const at = new Date().toISOString();
|
|
216
|
+
const dir = $os.tempDir();
|
|
217
|
+
const tmp = `chirkle-export-${job.id}-${$security.randomString(8)}.json`;
|
|
218
|
+
const root = $os.openRoot(dir);
|
|
219
|
+
const out = root.create(tmp);
|
|
220
|
+
const w = (/** @type {string} */ s) => out.writeString(s);
|
|
221
|
+
try {
|
|
222
|
+
const account = {
|
|
223
|
+
id,
|
|
224
|
+
name: me.getString("name"),
|
|
225
|
+
handle: me.getString("handle"),
|
|
226
|
+
email: me.getString("email"),
|
|
227
|
+
created: me.getString("created"),
|
|
228
|
+
avatar: me.getString("avatar") ? `/api/files/users/${id}/${me.getString("avatar")}` : "",
|
|
229
|
+
no_dms: me.getBool("no_dms"),
|
|
230
|
+
};
|
|
231
|
+
w(`{"format":${JSON.stringify(FORMAT)},"version":${VERSION},"exported":${JSON.stringify(at)},"account":${JSON.stringify(account)}`);
|
|
232
|
+
|
|
233
|
+
/** The rooms its messages are in. @type {Set<string>} */
|
|
234
|
+
const roomIds = new Set();
|
|
235
|
+
let first = true;
|
|
236
|
+
w(`,"messages":[`);
|
|
237
|
+
eachRecord(
|
|
238
|
+
app,
|
|
239
|
+
"messages",
|
|
240
|
+
"author = {:id} && deleted = false",
|
|
241
|
+
{ id },
|
|
242
|
+
(m) => {
|
|
243
|
+
roomIds.add(m.getString("room"));
|
|
244
|
+
const names = /** @type {Record<string, string>} */ (m.get("file_names") ?? {});
|
|
245
|
+
const row = {
|
|
246
|
+
id: m.id,
|
|
247
|
+
room: m.getString("room"),
|
|
248
|
+
created: m.getString("created"),
|
|
249
|
+
edited: m.getString("edited_at"),
|
|
250
|
+
text: m.getString("text"),
|
|
251
|
+
reply_to: m.getString("reply_to"),
|
|
252
|
+
forward_of: m.getString("forward_of"),
|
|
253
|
+
files: m.getStringSlice("files").map((f) => ({ name: fileName(names, f), url: `/api/files/messages/${m.id}/${f}` })),
|
|
254
|
+
};
|
|
255
|
+
w(`${first ? "" : ","}${JSON.stringify(row)}`);
|
|
256
|
+
first = false;
|
|
257
|
+
},
|
|
258
|
+
renew,
|
|
259
|
+
);
|
|
260
|
+
|
|
261
|
+
/** A DM is named for whoever else is in it. @param {core.Record} r */
|
|
262
|
+
const roomRow = (r) => {
|
|
263
|
+
let name = r.getString("name");
|
|
264
|
+
if (r.getString("kind") === "dm") {
|
|
265
|
+
const others = r.getStringSlice("members").filter((u) => u !== id);
|
|
266
|
+
name = (others.length ? app.findRecordsByIds("users", others) : []).map((u) => (u ? u.getString("name") : "")).join(", ");
|
|
267
|
+
}
|
|
268
|
+
return { id: r.id, name, kind: r.getString("kind") === "dm" ? "dm" : "room", mine: r.getString("created_by") === id };
|
|
269
|
+
};
|
|
270
|
+
first = true;
|
|
271
|
+
w(`],"rooms":[`);
|
|
272
|
+
const room = (/** @type {core.Record} */ r) => {
|
|
273
|
+
w(`${first ? "" : ","}${JSON.stringify(roomRow(r))}`);
|
|
274
|
+
first = false;
|
|
275
|
+
};
|
|
276
|
+
eachRecord(app, "rooms", "created_by = {:id}", { id }, (r) => {
|
|
277
|
+
roomIds.delete(r.id);
|
|
278
|
+
room(r);
|
|
279
|
+
});
|
|
280
|
+
const rest = [...roomIds];
|
|
281
|
+
for (let i = 0; i < rest.length; i += PAGE) {
|
|
282
|
+
for (const r of app.findRecordsByIds("rooms", rest.slice(i, i + PAGE))) if (r) room(r);
|
|
283
|
+
if (renew) renew();
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
first = true;
|
|
287
|
+
w(`],"collections":[`);
|
|
288
|
+
eachRecord(app, "collections", "owner = {:id}", { id }, (c) => {
|
|
289
|
+
w(
|
|
290
|
+
`${first ? "" : ","}{"id":${JSON.stringify(c.id)},"name":${JSON.stringify(c.getString("name"))},"public":${c.getBool("public")},"created":${JSON.stringify(c.getString("created"))},"items":[`,
|
|
291
|
+
);
|
|
292
|
+
first = false;
|
|
293
|
+
let firstItem = true;
|
|
294
|
+
eachRecord(
|
|
295
|
+
app,
|
|
296
|
+
"collection_items",
|
|
297
|
+
"collection = {:c}",
|
|
298
|
+
{ c: c.id },
|
|
299
|
+
(it) => {
|
|
300
|
+
const file = it.getString("file");
|
|
301
|
+
const row = {
|
|
302
|
+
id: it.id,
|
|
303
|
+
name: it.getString("name") || fileName({}, file),
|
|
304
|
+
created: it.getString("created"),
|
|
305
|
+
url: file ? `/api/files/collection_items/${it.id}/${file}` : "",
|
|
306
|
+
};
|
|
307
|
+
w(`${firstItem ? "" : ","}${JSON.stringify(row)}`);
|
|
308
|
+
firstItem = false;
|
|
309
|
+
},
|
|
310
|
+
renew,
|
|
311
|
+
);
|
|
312
|
+
w("]}");
|
|
313
|
+
});
|
|
314
|
+
|
|
315
|
+
first = true;
|
|
316
|
+
w(`],"following":[`);
|
|
317
|
+
eachRecord(app, "collection_subs", "user = {:id}", { id }, (sub) => {
|
|
318
|
+
try {
|
|
319
|
+
const c = app.findRecordById("collections", sub.getString("collection"));
|
|
320
|
+
w(`${first ? "" : ","}${JSON.stringify({ id: c.id, name: c.getString("name") })}`);
|
|
321
|
+
first = false;
|
|
322
|
+
} catch {
|
|
323
|
+
// gone
|
|
324
|
+
}
|
|
325
|
+
});
|
|
326
|
+
|
|
327
|
+
first = true;
|
|
328
|
+
w(`],"hidden_rooms":[`);
|
|
329
|
+
eachRecord(app, "hidden_rooms", "user = {:id}", { id }, (row) => {
|
|
330
|
+
w(`${first ? "" : ","}${JSON.stringify(row.getString("room"))}`);
|
|
331
|
+
first = false;
|
|
332
|
+
});
|
|
333
|
+
w("]}\n");
|
|
334
|
+
} finally {
|
|
335
|
+
out.close();
|
|
336
|
+
root.close();
|
|
337
|
+
}
|
|
338
|
+
const path = `${dir}/${tmp}`;
|
|
339
|
+
try {
|
|
340
|
+
const file = $filesystem.fileFromPath(path);
|
|
341
|
+
file.originalName = `chirkle-export-${at.slice(0, 10)}.json`;
|
|
342
|
+
job.set("file", file);
|
|
343
|
+
job.set("size", $os.stat(path).size());
|
|
344
|
+
app.save(job);
|
|
345
|
+
} finally {
|
|
346
|
+
$os.remove(path);
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
// ---------------------------------------------------------------- deleting the account (§43.3)
|
|
351
|
+
|
|
352
|
+
/**
|
|
353
|
+
* POST /api/chat/account/delete { password, messages: "keep" | "delete" } → 204 (§43.3). The caller's password says
|
|
354
|
+
* it is them. The account is a deleted one at once (erase); what grows with it (its collections' items, and with
|
|
355
|
+
* "delete" its messages) goes after, by the worker (an erase job).
|
|
356
|
+
* @param {core.RequestEvent} e
|
|
357
|
+
*/
|
|
358
|
+
function deleteAccount(e) {
|
|
359
|
+
if (!e.auth) throw new UnauthorizedError("The request requires a logged-in user.");
|
|
360
|
+
const what = "Failed to delete the account.";
|
|
361
|
+
const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body ?? {});
|
|
362
|
+
const password = typeof body.password === "string" ? body.password : "";
|
|
363
|
+
const choice = body.messages;
|
|
364
|
+
if (!password) throw fieldError("password", "Enter your password.", "validation_required", what);
|
|
365
|
+
if (choice !== "keep" && choice !== "delete") {
|
|
366
|
+
throw fieldError("messages", "Choose whether your messages stay or go.", "validation_required", what);
|
|
367
|
+
}
|
|
368
|
+
const user = e.app.findRecordById("users", e.auth.id);
|
|
369
|
+
if (!user.validatePassword(password)) throw fieldError("password", "That isn't your password.", undefined, what);
|
|
370
|
+
erase(e.app, user.id, choice === "delete");
|
|
371
|
+
wake(e.app);
|
|
372
|
+
return e.noContent(204);
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
/**
|
|
376
|
+
* Make `userId` a deleted account (§43.3), in one transaction, and queue the rest. Its name becomes "Deleted account"
|
|
377
|
+
* (lib/users.js beforeUserSave), its handle, picture and e-mail go, it takes no DMs, it is no moderator. Every session
|
|
378
|
+
* ends and no sign-in works again: a random password, its OAuth2 links, one-time codes and sign-in origins gone. What
|
|
379
|
+
* only it had and is small goes now: whom and what it follows, hid and read, its inbox, its exports, the invite links it
|
|
380
|
+
* made. Its collections
|
|
381
|
+
* stop being public, and go with their items by the erase job. It leaves the private rooms it was in and the lists of
|
|
382
|
+
* who may post. The row stays, so the messages (kept, or deleted) and rooms that name it still have an author; a room
|
|
383
|
+
* it made keeps it as its creator, and moderators look after it.
|
|
384
|
+
* @param {core.App} app
|
|
385
|
+
* @param {string} userId
|
|
386
|
+
* @param {boolean} messages its messages go too (by the erase job)
|
|
387
|
+
*/
|
|
388
|
+
function erase(app, userId, messages) {
|
|
389
|
+
app.runInTransaction((tx) => {
|
|
390
|
+
const user = tx.findRecordById("users", userId);
|
|
391
|
+
user.set("kind", "deleted");
|
|
392
|
+
user.set("email", `${userId}@deleted.invalid`);
|
|
393
|
+
user.set("emailVisibility", false);
|
|
394
|
+
user.set("verified", false);
|
|
395
|
+
user.set("avatar", null);
|
|
396
|
+
user.set("no_dms", true);
|
|
397
|
+
user.set("moderator", false);
|
|
398
|
+
user.set("banned", false);
|
|
399
|
+
user.setPassword($security.randomString(48));
|
|
400
|
+
user.refreshTokenKey();
|
|
401
|
+
tx.save(user);
|
|
402
|
+
tx.deleteAllExternalAuthsByRecord(user);
|
|
403
|
+
tx.deleteAllMFAsByRecord(user);
|
|
404
|
+
tx.deleteAllOTPsByRecord(user);
|
|
405
|
+
tx.deleteAllAuthOriginsByRecord(user);
|
|
406
|
+
|
|
407
|
+
for (const [collection, field] of [
|
|
408
|
+
["collection_subs", "user"],
|
|
409
|
+
["hidden_rooms", "user"],
|
|
410
|
+
["room_reads", "user"],
|
|
411
|
+
["inbox", "user"],
|
|
412
|
+
["inbox_reads", "user"],
|
|
413
|
+
["stats_activity", "user"],
|
|
414
|
+
["account_jobs", "user"],
|
|
415
|
+
// The invite links it made (§44): a room it no longer manages takes no one in by its hand (QA BUG-281).
|
|
416
|
+
["room_invites", "created_by"],
|
|
417
|
+
]) {
|
|
418
|
+
for (;;) {
|
|
419
|
+
const rows = tx.findRecordsByFilter(collection, `${field} = {:id}`, "", PAGE, 0, { id: userId });
|
|
420
|
+
for (const row of rows) if (row) tx.delete(row);
|
|
421
|
+
if (rows.length < PAGE) break;
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
// Read all first, as below: saved, a record no longer matches, and the pages would skip some.
|
|
425
|
+
/** @type {core.Record[]} */
|
|
426
|
+
const shown = [];
|
|
427
|
+
eachRecord(tx, "collections", "owner = {:id} && public = true", { id: userId }, (c) => shown.push(c));
|
|
428
|
+
for (const c of shown) {
|
|
429
|
+
c.set("public", false);
|
|
430
|
+
tx.save(c);
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
// Private rooms' members and who may post (§23): not a DM's two, which name the DM.
|
|
434
|
+
/** @type {core.Record[]} */
|
|
435
|
+
const rooms = [];
|
|
436
|
+
eachRecord(tx, "rooms", "kind != 'dm' && (members.id ?= {:id} || writers.id ?= {:id})", { id: userId }, (r) => rooms.push(r));
|
|
437
|
+
for (const room of rooms) {
|
|
438
|
+
room.set(
|
|
439
|
+
"members",
|
|
440
|
+
room.getStringSlice("members").filter((u) => u !== userId),
|
|
441
|
+
);
|
|
442
|
+
room.set(
|
|
443
|
+
"writers",
|
|
444
|
+
room.getStringSlice("writers").filter((u) => u !== userId),
|
|
445
|
+
);
|
|
446
|
+
tx.save(room);
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
const job = new Record(tx.findCollectionByNameOrId("account_jobs"));
|
|
450
|
+
job.set("user", userId);
|
|
451
|
+
job.set("kind", "erase");
|
|
452
|
+
job.set("state", "queued");
|
|
453
|
+
job.set("messages", messages);
|
|
454
|
+
tx.save(job);
|
|
455
|
+
});
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
/**
|
|
459
|
+
* One step of erase job `job`: a batch of a collection's items (the collection itself after its last), else with
|
|
460
|
+
* `messages` a batch of its messages soft-deleted (§21.2) through the messages hooks, so files, previews, the media
|
|
461
|
+
* grid, the inbox, forwards and the bridges follow as for any delete, archived rooms too (`@erasing`). Each batch in a
|
|
462
|
+
* transaction. True while there is more.
|
|
463
|
+
* @param {core.App} app
|
|
464
|
+
* @param {core.Record} job
|
|
465
|
+
*/
|
|
466
|
+
function eraseStep(app, job) {
|
|
467
|
+
const userId = job.getString("user");
|
|
468
|
+
const coll = app.findRecordsByFilter("collections", "owner = {:u}", "created,id", 1, 0, { u: userId })[0];
|
|
469
|
+
if (coll) {
|
|
470
|
+
const items = app.findRecordsByFilter("collection_items", "collection = {:c}", "", ERASE_BATCH, 0, { c: coll.id });
|
|
471
|
+
app.runInTransaction((tx) => {
|
|
472
|
+
for (const it of items) if (it) tx.delete(it);
|
|
473
|
+
if (items.length < ERASE_BATCH) tx.delete(tx.findRecordById("collections", coll.id));
|
|
474
|
+
});
|
|
475
|
+
return true;
|
|
476
|
+
}
|
|
477
|
+
if (!job.getBool("messages")) return false;
|
|
478
|
+
const batch = app.findRecordsByFilter("messages", "author = {:id} && deleted = false", "created,id", ERASE_BATCH, 0, { id: userId });
|
|
479
|
+
if (!batch.length) return false;
|
|
480
|
+
const { ERASING } = require(`${__hooks}/lib/messages.js`);
|
|
481
|
+
app.runInTransaction((tx) => {
|
|
482
|
+
for (const m of batch) {
|
|
483
|
+
if (!m) continue;
|
|
484
|
+
const rec = tx.findRecordById("messages", m.id);
|
|
485
|
+
if (rec.getBool("deleted")) continue;
|
|
486
|
+
rec.set(ERASING, true);
|
|
487
|
+
rec.set("deleted", true);
|
|
488
|
+
tx.save(rec);
|
|
489
|
+
}
|
|
490
|
+
});
|
|
491
|
+
return true;
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
// ---------------------------------------------------------------- the worker (§43.5)
|
|
495
|
+
|
|
496
|
+
/**
|
|
497
|
+
* One pass: exports older than 7 days deleted (their files with them), then one step of the queued job touched
|
|
498
|
+
* longest ago: an export written whole, or a batch of an erase. Saving the job touches it, so jobs take turns: a
|
|
499
|
+
* large erase doesn't keep an export waiting. A step that fails is tried again on a later pass, at most MAX_TRIES
|
|
500
|
+
* times. Returns whether there may be more to do now.
|
|
501
|
+
* @param {core.App} app
|
|
502
|
+
* @param {() => void} [renew]
|
|
503
|
+
*/
|
|
504
|
+
function pass(app, renew) {
|
|
505
|
+
const old = app.findRecordsByFilter("account_jobs", "kind = 'export' && created < {:t}", "", 50, 0, { t: dbDate(Date.now() - KEEP_MS) });
|
|
506
|
+
for (const j of old) if (j) app.delete(j);
|
|
507
|
+
const job = app.findRecordsByFilter("account_jobs", "state = 'queued'", "updated,id", 1, 0)[0];
|
|
508
|
+
if (!job) return old.length === 50;
|
|
509
|
+
try {
|
|
510
|
+
let more = false;
|
|
511
|
+
if (job.getString("kind") === "export") writeExport(app, job, renew);
|
|
512
|
+
else more = eraseStep(app, job);
|
|
513
|
+
if (!more) {
|
|
514
|
+
job.set("state", "done");
|
|
515
|
+
job.set("finished", new DateTime());
|
|
516
|
+
}
|
|
517
|
+
app.save(job);
|
|
518
|
+
} catch (err) {
|
|
519
|
+
if (require(`${__hooks}/lib/worker.js`).isLost(err)) throw err;
|
|
520
|
+
app.logger().error("account: job failed", "job", job.id, "kind", job.getString("kind"), "error", String(err));
|
|
521
|
+
try {
|
|
522
|
+
const fresh = app.findRecordById("account_jobs", job.id);
|
|
523
|
+
const tries = fresh.getInt("tries") + 1;
|
|
524
|
+
fresh.set("tries", tries);
|
|
525
|
+
fresh.set("error", String(err).slice(0, 500));
|
|
526
|
+
if (tries >= MAX_TRIES) {
|
|
527
|
+
fresh.set("state", "failed");
|
|
528
|
+
fresh.set("finished", new DateTime());
|
|
529
|
+
}
|
|
530
|
+
app.save(fresh);
|
|
531
|
+
} catch {
|
|
532
|
+
// gone meanwhile (its account deleted)
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
if (renew) renew();
|
|
536
|
+
return true;
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
/**
|
|
540
|
+
* The cron job: passes until the minute is nearly over; with nothing to do, when a request wakes it. One run at a time.
|
|
541
|
+
* @param {core.App} app
|
|
542
|
+
*/
|
|
543
|
+
function run(app) {
|
|
544
|
+
require(`${__hooks}/lib/worker.js`).run(app, {
|
|
545
|
+
name: LOCK,
|
|
546
|
+
label: "account",
|
|
547
|
+
staleMs: STALE_MS,
|
|
548
|
+
wakes: true,
|
|
549
|
+
pass: (/** @type {() => void} */ renew) => pass(app, renew),
|
|
550
|
+
});
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
/** A job was queued (committed): the worker looks now. @param {core.App} app */
|
|
554
|
+
function wake(app) {
|
|
555
|
+
require(`${__hooks}/lib/worker.js`).wake(app, LOCK);
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
/**
|
|
559
|
+
* POST /api/account/tick (superusers): every queued job done now (tests; ACCOUNT_CRON=off).
|
|
560
|
+
* @param {core.RequestEvent} e
|
|
561
|
+
*/
|
|
562
|
+
function tick(e) {
|
|
563
|
+
for (let i = 0; i < 10_000 && pass(e.app); i++);
|
|
564
|
+
return e.noContent(204);
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
module.exports = { changePassword, deleteAccount, erase, exportFile, exportState, run, startExport, tick };
|