Initial commit - v0.6.0
This commit is contained in:
commit
f3e6c63368
264 files changed
+51460
No files matched your search
@@ -0,0 +1,16 @@
|
||||
# Build context = repo root (or the unzipped release folder). Keep it small and secret-free.
|
||||
**/node_modules
|
||||
**/dist
|
||||
**/coverage
|
||||
**/.env
|
||||
deploy/data
|
||||
deploy/.env
|
||||
data
|
||||
test-results
|
||||
playwright-report
|
||||
qa
|
||||
e2e
|
||||
.git
|
||||
*.db
|
||||
*.db-wal
|
||||
*.db-shm
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
node_modules/
|
||||
dist/
|
||||
coverage/
|
||||
data/
|
||||
*.db
|
||||
*.db-wal
|
||||
*.db-shm
|
||||
.env
|
||||
test-results/
|
||||
playwright-report/
|
||||
# Deployment secrets and data (also in the release zip)
|
||||
deploy/.env
|
||||
deploy/data/
|
||||
test-results/
|
||||
vapid.json
|
||||
@@ -0,0 +1,61 @@
|
||||
# Doghouse 0.1.1
|
||||
|
||||
Patch release on top of 0.1.0 (`45cd711`, tag `v0.1.0`). It contains one UI fix, QA-8, which was
|
||||
developed on `fix/qa-8-composer-focus-bar` (`99ce00e`) and fast-forwarded into `main`. Package:
|
||||
`dist/doghouse-0.1.1.zip`.
|
||||
|
||||
**Upgrading from 0.1.0:** there are no database changes, no new settings and no changes to
|
||||
`docker-compose.yml`, `livekit.yaml` or `npm-advanced.conf`. Follow "Upgrading 0.1.0 -> 0.1.1" in
|
||||
the README: back up `./data`, keep your `.env` (and `livekit.yaml` if you edited it), replace the
|
||||
source files from the new zip, then run `docker compose up -d --build` from `deploy/`.
|
||||
|
||||
## QA-8 (Low): thin dark bar above the message box
|
||||
|
||||
**Seen:** the reported screenshot `/workspace/shots/doghouse-phone.png` (script
|
||||
`/workspace/shots/tests/shots.spec.ts`, 375 px). A 2 px dark strip about 215 px wide sits just above
|
||||
the composer's focus ring, and a matching one sits just below it.
|
||||
|
||||
**Root cause:** the strip is not the typing row, the voice bar or the safe-area padding. The global
|
||||
keyboard-focus style in `app.css` is `:focus-visible { outline …; box-shadow: 0 0 0 4px
|
||||
var(--bg-tertiary) }`. The composer textarea suppresses its own outline (`outline: none`), because
|
||||
the ring is drawn on `.composer:focus-within`, but it never reset the box-shadow. A focused textarea
|
||||
always matches `:focus-visible`, so its 4 px halo stuck out above and below the composer. The 2 px
|
||||
outline covered half of it, and the other 2 px showed as a bar in `--bg-tertiary`: (30,31,34) dark,
|
||||
(227,229,232) light, (21,22,24) amoled. It only shows while the message box is focused. That's the
|
||||
normal state on a phone after sending, and why the screenshot caught it. It happened at every width,
|
||||
1440 included, and the bar spanned the textarea's width (x 55–270 at 375 px).
|
||||
|
||||
**Fix:** `.composer-input` now also sets `box-shadow: none`, so the composer keeps its 2 px accent
|
||||
ring and nothing else. The other elements that set `outline: none` under the same global rule got
|
||||
the same reset: menu items, which show focus with an accent fill; the members, main and message
|
||||
scroller panes, which are focused by script. `app.css` now notes that suppressing the outline means
|
||||
suppressing the halo too. The typing row (`.below` / `.typing`) is unchanged.
|
||||
|
||||
**Regression test:** `e2e/tests/composer-layout.spec.ts` covers 1440 (desktop project) and 375 +
|
||||
320 (phone project), in dark, light and amoled. In each case the composer is focused while another
|
||||
user is typing. The test asserts that:
|
||||
- the "… is typing" row is visible;
|
||||
- the textarea's box-shadow is `none` and the composer's ring is still drawn;
|
||||
- the 8 px strip just outside the ring is plain background, using a pixel check on a screenshot clip.
|
||||
|
||||
I confirmed it fails against the unfixed build: the box-shadow is `rgb(30, 31, 34) 0px 0px 0px 4px`,
|
||||
and 1424 px (1440) / 430 px (375) break the background.
|
||||
|
||||
**Screenshots** (`/workspace/shots/repro/`, 27 before + 27 after):
|
||||
`{before,after}-{320,375,1440}-{dark,light,amoled}-{idle,focus,typing}.png`. In all 18 focus and
|
||||
typing pairs, rows 740–741 (phone) / 828–829 (1440) change from the bg-tertiary bar to the plain
|
||||
chat background. The typing indicator shows in every typing shot.
|
||||
|
||||
**Tests (10 Oct 2026, 03:36–03:47 AEDT):**
|
||||
- `REQUIRE_LIVEKIT=1 npm run check`: passed. shared 22, server 187, web 205, 0 failed, "Skipped
|
||||
tests: 0", "Server coverage: statements 98.12%, branches 92.35%, functions 99.29%, lines 99.19%".
|
||||
- `REQUIRE_LIVEKIT=1 npm run e2e`: "12 passed (41.2s)", "4 skipped". The 4 skips are the existing
|
||||
two-user specs that run once in the desktop project (`one run covers both sizes`), not LiveKit
|
||||
skips. The voice spec passed.
|
||||
|
||||
**Release gate for 0.1.1** (version bumped, run on `main`, 10 Oct 2026, 03:49–03:51 AEDT):
|
||||
- `REQUIRE_LIVEKIT=1 npm run check`: passed. "Skipped tests: 0", "Server coverage: statements
|
||||
98.12%, branches 92.35%, functions 99.29%, lines 99.19%" (shared 22, server 187, web 205 passed,
|
||||
0 failed).
|
||||
- `REQUIRE_LIVEKIT=1 npm run e2e`: "12 passed (41.1s)", "4 skipped" (the same desktop-only two-user
|
||||
specs as above).
|
||||
@@ -0,0 +1,143 @@
|
||||
# Doghouse 0.1.2
|
||||
|
||||
Patch release on top of 0.1.1 (`d01ed0b`, tag `v0.1.1`). It fixes a LiveKit startup crash loop
|
||||
seen on Justin's server, moves LiveKit's media ports out of Linux's ephemeral range, and makes the
|
||||
Docker network configurable. There are no database or app
|
||||
changes. Branch `release/0.1.2`; no zip or tag yet (QA reviews first).
|
||||
|
||||
## Upgrading from 0.1.1
|
||||
|
||||
Keep your existing `deploy/.env` and **add** the two new settings (see `.env.example`):
|
||||
|
||||
```
|
||||
LIVEKIT_NODE_IP=<your public IP, from: curl -4 ifconfig.me>
|
||||
DOGHOUSE_NETWORK=doghouse_net
|
||||
```
|
||||
|
||||
- If you edited `docker-compose.yml` to use your own network (e.g. `homelab`), set
|
||||
`DOGHOUSE_NETWORK=homelab` instead and use the new `docker-compose.yml` unedited. Never use
|
||||
`network_mode:`.
|
||||
- Then follow README "Upgrading 0.1.1 -> 0.1.2": back up `./data`, replace the source files from
|
||||
the zip, and run `docker compose up -d --build` from `deploy/`.
|
||||
- **Router and ufw:** voice media moved to **UDP 20000-20100**. Forward UDP 20000-20100 to the
|
||||
server and **remove the old UDP 50000-50100 forward**. For ufw:
|
||||
`sudo ufw allow 20000:20100/udp` and `sudo ufw delete allow 50000:50100/udp`. TCP 7881 and
|
||||
UDP 3478 are unchanged.
|
||||
- Use the new `docker-compose.yml` and `livekit.yaml`; they must agree on the range. If you had
|
||||
edited `livekit.yaml`, re-apply your edits to the new file. `npm-advanced.conf` is unchanged.
|
||||
- If your home IP is dynamic, update `LIVEKIT_NODE_IP` when it changes, then run
|
||||
`docker compose up -d livekit`.
|
||||
|
||||
## LiveKit crash loop: "could not resolve external IP"
|
||||
|
||||
**Seen:** on 0.1.1, `doghouse-livekit` restarts forever with
|
||||
`could not validate RTC config: could not resolve external IP: dial udp: lookup stun1.l.google.com
|
||||
on 127.0.0.53:53: … connection refused` and `exited with code 0 (restarting)`. `livekit.yaml` has
|
||||
`use_external_ip: true`, so LiveKit must reach a STUN server at startup, and that container
|
||||
couldn't resolve DNS. `127.0.0.53` is the host's systemd-resolved, which points to host networking
|
||||
(`network_mode: host`) rather than our `doghouse_net`, where Docker's DNS is `127.0.0.11`.
|
||||
|
||||
**Fix:** a new optional `.env` setting, `LIVEKIT_NODE_IP`. When it is set, LiveKit advertises that
|
||||
IP and **skips STUN entirely**. When it is empty, LiveKit behaves exactly as before. No `dns:` lines
|
||||
are hard-coded (decisions log).
|
||||
|
||||
**How it works in livekit-server v1.13.9** (checked against the source at tag `v1.13.9` and its
|
||||
`mediatransportutil` dependency `f234b534b095`, and on the v1.13.9 binary):
|
||||
- `--node-ip` / env `NODE_IP` sets `rtc.node_ip` (`pkg/config/config.go`, `updateFromCLI`).
|
||||
- A node IP alone is **not** enough. `RTCConfig.Validate` runs STUN when
|
||||
`conf.NodeIP.IsEmpty() || conf.UseExternalIP`, so with `use_external_ip: true` STUN still runs.
|
||||
Binary test with `NODE_IP=203.0.113.10` and a broken resolver: same error, exit 0.
|
||||
- So when a node IP is set, `use_external_ip` must also be false. Then LiveKit logs
|
||||
`using explicit node IP for NAT1To1Ips` and starts.
|
||||
- Passing `LIVEKIT_RTC_USE_EXTERNAL_IP` from compose as `${LIVEKIT_NODE_IP:+false}` doesn't work.
|
||||
When the IP is empty the variable is set but empty, and livekit-server reads that as **false**.
|
||||
The binary then started with the container's private IP (`nodeIP: 172.30.0.2`) and no STUN,
|
||||
which would silently break voice for everyone not using the new setting.
|
||||
|
||||
**Implementation:** `docker-compose.yml` passes `NODE_IP: '${LIVEKIT_NODE_IP:-}'` and starts the
|
||||
container (alpine, so `/bin/sh` exists) with a small `sh -c`:
|
||||
- if `NODE_IP` is non-empty, it runs
|
||||
`exec /livekit-server --config /etc/livekit.yaml --rtc.use_external_ip=false` and logs
|
||||
`doghouse: LIVEKIT_NODE_IP=…, skipping STUN`;
|
||||
- otherwise it runs `exec /livekit-server --config /etc/livekit.yaml` as before.
|
||||
|
||||
The setting lives in `.env`, so upgrades never overwrite it, and `livekit.yaml` is unchanged.
|
||||
|
||||
**Tested with the v1.13.9 binary.** The compose command and environment were extracted from
|
||||
`docker-compose.yml` and run in a mount namespace whose `/etc/resolv.conf` is
|
||||
`nameserver 127.0.0.53`, so STUN is unreachable, as on Justin's server:
|
||||
- `LIVEKIT_NODE_IP` empty: exits with code 0 after 1.5 s with the exact error,
|
||||
`could not validate RTC config: could not resolve external IP: dial udp: lookup
|
||||
stun1.l.google.com on 127.0.0.53:53: read udp 127.0.0.1:43433->127.0.0.53:53: read: connection
|
||||
refused`.
|
||||
- `LIVEKIT_NODE_IP=203.0.113.10`: listening on 7880 after 0.3 s, logging
|
||||
`doghouse: LIVEKIT_NODE_IP=203.0.113.10, skipping STUN`, `using explicit node IP for NAT1To1Ips`
|
||||
and `starting LiveKit server … "nodeIP": "203.0.113.10"`.
|
||||
- With the box's normal resolver, where STUN gets no reply, the old default hangs: still not
|
||||
listening after 30 s.
|
||||
|
||||
## LiveKit media ports: UDP 20000-20100 (was 50000-50100)
|
||||
|
||||
**Seen:** Justin's `docker compose up -d livekit` failed with
|
||||
`failed to bind host port [::]:50028/udp: address already in use`. 50000-50100 sits inside Linux's
|
||||
ephemeral port range (32768-60999), which the kernel hands out for outgoing connections, so any
|
||||
port in it can already be taken.
|
||||
|
||||
**Fix (decisions log):** the default RTC UDP range is now 20000-20100: `livekit.yaml`
|
||||
`rtc.port_range_start/end`, the compose port mapping, README (router table, ufw example,
|
||||
troubleshooting) and DESIGN/PLAN. The e2e LiveKit config moved from 51000-51100 to 21000-21100 for
|
||||
the same reason. `validate:deploy` enforces that the range is valid, below 32768, doesn't overlap
|
||||
TURN's relay range (`turn.relay_range_start/end`, default 30000-40000), and matches the published
|
||||
compose range. Each rule fails when broken: 50000-50100, 29950-30050, and a compose/yaml mismatch.
|
||||
The README has a troubleshooting entry quoting the exact error. With the new config, the v1.13.9
|
||||
binary logs `"rtc.portICERange": [20000, 20100]`.
|
||||
|
||||
## Configurable Docker network
|
||||
|
||||
Justin's NPM is on his existing network `homelab`. The compose network key stays `doghouse_net`,
|
||||
but its Docker name is now `name: ${DOGHOUSE_NETWORK:-doghouse_net}` (still `external: true`).
|
||||
`DOGHOUSE_NETWORK=doghouse_net` is in `.env.example`, with a comment: set it to a network your proxy
|
||||
is already on, e.g. `homelab`. The README explains the option, warns that `network_mode: <name>`
|
||||
and `network_mode: host` are wrong (use `networks:`), and notes that containers on a user-defined
|
||||
network show `nameserver 127.0.0.11` in `/etc/resolv.conf`.
|
||||
|
||||
## Other changes
|
||||
|
||||
**`npm run validate:deploy`** (part of `npm run check`) now checks:
|
||||
- `LIVEKIT_NODE_IP` is in `.env.example`, empty, and explained with `curl -4 ifconfig.me`; and
|
||||
`DOGHOUSE_NETWORK` is there with default `doghouse_net`.
|
||||
- Compose with `LIVEKIT_NODE_IP` set gives `NODE_IP=<ip>` and the
|
||||
`--rtc.use_external_ip=false` start; with it empty, `NODE_IP=''` and the plain start.
|
||||
`LIVEKIT_RTC_USE_EXTERNAL_IP` must not be set (the empty-means-false trap).
|
||||
- The network name comes from `${DOGHOUSE_NETWORK:-doghouse_net}`, and
|
||||
`DOGHOUSE_NETWORK=homelab` gives external network `homelab`. `doghouse_net` is the only network,
|
||||
both services are on it, and no service uses `network_mode:` or `dns:`.
|
||||
- The interpolation now handles `${VAR:+alt}` and `$$` like Compose does.
|
||||
- Each new rule was confirmed to fail when broken: `network_mode: homelab` added, network name
|
||||
hard-coded, `NODE_IP` removed, the flag removed, and the empty-bool env approach.
|
||||
|
||||
**README:**
|
||||
- A troubleshooting entry quotes the exact error. It covers setting `LIVEKIT_NODE_IP` and running
|
||||
`docker compose up -d livekit`, and checking that
|
||||
`docker inspect doghouse-livekit --format '{{.HostConfig.NetworkMode}}'` says `doghouse_net`,
|
||||
not `host` (host mode breaks NPM -> LiveKit and LiveKit -> app webhooks).
|
||||
- A new entry covers dynamic home IPs.
|
||||
- The old "set `node_ip` in `livekit.yaml`" advice now points at `LIVEKIT_NODE_IP`.
|
||||
- Step 4 lists the two new settings, and step 5 covers `DOGHOUSE_NETWORK`.
|
||||
|
||||
**Packaging:**
|
||||
- The zip now includes the repo `.gitignore`, which gained explicit `deploy/.env` and
|
||||
`deploy/data/` lines, plus `CHANGES-0.1.2.md`.
|
||||
- `npm run package` refuses to build if `.gitignore` lacks those lines or `CHANGES-<version>.md`
|
||||
is missing.
|
||||
|
||||
**Version:** 0.1.2 in the root and workspace `package.json` files and in `package-lock.json`.
|
||||
|
||||
## Tests (branch `release/0.1.2`, 10 Oct 2026, 07:17–07:24 AEDT)
|
||||
|
||||
- `REQUIRE_LIVEKIT=1 npm run check`: passed (exit 0). The output includes `deploy/ OK: …`,
|
||||
"Skipped tests: 0" and "Server coverage: statements 98.12%, branches 92.35%, functions 99.29%,
|
||||
lines 99.19%". Counts: shared 22, server 187, web 205 passed, 0 failed.
|
||||
- `REQUIRE_LIVEKIT=1 npm run e2e`: passed (exit 0), "12 passed (44.7s)", "4 skipped". The skips are
|
||||
the usual desktop-only two-user specs. The voice spec passed on the new 21000-21100 e2e range.
|
||||
- No zip was built (`npm run package` not run); QA reviews first.
|
||||
@@ -0,0 +1,163 @@
|
||||
# Doghouse 0.2.0
|
||||
|
||||
The second feature release, on top of 0.1.2. It brings profile pictures, server icons and
|
||||
banners, group chats, and voice/video calls in DMs and groups. QA passed it at `f886ee6`.
|
||||
The detailed engineering notes are in the repository (`CHANGES-M7.md` to `CHANGES-M10.md`);
|
||||
this file is the short version.
|
||||
|
||||
## What's new
|
||||
|
||||
**Profiles (M7)**
|
||||
- Everyone can set a profile picture and a banner. Pictures are cropped in the browser before
|
||||
uploading, and animated GIFs stay animated. Photo location data (EXIF) is removed.
|
||||
- New "About me" (with simple formatting) and pronouns fields, plus a banner colour.
|
||||
- Click anyone's name or picture (in messages, the member list, DMs or voice) to see their
|
||||
profile card. It also works with the keyboard and screen readers.
|
||||
- Pictures are only visible to people who share a server or a DM with that person.
|
||||
|
||||
**Server icons and banners (M8)**
|
||||
- Server owners and admins can set a server icon and a banner, cropped the same way.
|
||||
- Icons uploaded in 0.1 are converted automatically on the first start; nothing to do.
|
||||
- Invite links show the server's icon and name before you join.
|
||||
|
||||
**Group chats (M9)**
|
||||
- Group DMs with up to 10 people. You can start one from Home ("New message", pick several
|
||||
people), or add people to an existing 1:1 (that creates a new group; the 1:1 stays private).
|
||||
- Groups can have a name and an icon. Anyone in the group can change them, the owner can remove
|
||||
people, and anyone can leave. If the owner leaves, the longest-standing member takes over.
|
||||
- Short messages in the chat say who joined, left, was removed, or renamed the group.
|
||||
- People who are added can see the group's earlier messages (the add dialog says so). People
|
||||
who leave or are removed lose access straight away, including to pictures and files they had
|
||||
already opened (their browser has to re-check with the server every time).
|
||||
|
||||
**Calls and video (M10)**
|
||||
- Call anyone you have a DM with, or call a whole group, with the phone button at the top of the
|
||||
conversation. It rings in every open Doghouse tab of the people you call, on all their devices,
|
||||
with Accept and Decline buttons. Answering on one device stops the ringing on the others.
|
||||
- If nobody answers within 30 seconds, the call stops and "Missed call" appears in the chat.
|
||||
Finished calls show how long they lasted.
|
||||
- In a group, people can join a call that's already going ("Join call" bar at the top).
|
||||
- Screen sharing works in calls the same way as in voice channels (desktop browsers).
|
||||
- Cameras (webcam) in calls and voice channels. Your camera is always off when you join, and you
|
||||
see a private preview before anyone else sees you. Turning it off really switches the camera
|
||||
off (the light goes out). On phones you can switch between front and back camera; on desktop
|
||||
you can pick which camera.
|
||||
- You're in one call or voice channel at a time. Joining another asks first.
|
||||
- **Limits:** ringing only reaches Doghouse tabs that are open. There are no push
|
||||
notifications, so a phone with the screen locked or the browser closed will not ring.
|
||||
|
||||
**Smaller fixes**
|
||||
- QA-9: on phones, a long group or channel name no longer makes the message box six lines tall.
|
||||
|
||||
## Upgrading from 0.1.2
|
||||
|
||||
The upgrade changes the database (new tables for profiles, groups and calls). The changes are
|
||||
applied automatically when the app starts. **You can't go back to 0.1.2 without your backup**,
|
||||
so step 1 matters.
|
||||
|
||||
1. **Back up first.** In your current `doghouse-0.1.2/deploy` folder:
|
||||
```bash
|
||||
docker compose down
|
||||
sudo tar czf ~/doghouse-backup-$(date +%F).tgz data .env
|
||||
```
|
||||
2. **Unzip 0.2.0 into a fresh folder** next to the old one (don't unzip over it):
|
||||
```bash
|
||||
cd ~ # wherever doghouse-0.1.2 lives
|
||||
unzip doghouse-0.2.0.zip
|
||||
```
|
||||
3. **Keep your settings and data:** copy `.env` and move `data` into the new folder.
|
||||
```bash
|
||||
cp doghouse-0.1.2/deploy/.env doghouse-0.2.0/deploy/
|
||||
sudo mv doghouse-0.1.2/deploy/data doghouse-0.2.0/deploy/
|
||||
```
|
||||
If you had edited `deploy/livekit.yaml`, copy your edits into the new file (it's unchanged
|
||||
from 0.1.2 otherwise).
|
||||
4. **Add the new setting** to `doghouse-0.2.0/deploy/.env` (see `.env.example`):
|
||||
```
|
||||
VIDEO_ENABLED=true
|
||||
```
|
||||
This turns webcams on (the default even if you leave it out). Set it to `false` if your home
|
||||
internet upload is slow. Every camera in a call is sent out from your server to each viewer;
|
||||
five people on camera need roughly 5-10 Mbps of upload. Voice and screen share keep working
|
||||
either way.
|
||||
|
||||
Optional settings, only if you want to change them (the defaults are fine):
|
||||
- `CALL_RING_TIMEOUT_MS=30000`: how long a call rings before it counts as missed (1000-300000).
|
||||
- `MEDIA_DIR`: where profile pictures, icons and banners are stored. The default is
|
||||
`data/media`, inside your `data` folder, so the backup in step 1 already covers it. Don't
|
||||
set it unless you want them elsewhere.
|
||||
5. **Start it:**
|
||||
```bash
|
||||
cd doghouse-0.2.0/deploy
|
||||
docker compose up -d --build
|
||||
docker compose ps # both containers should be "healthy" after a minute
|
||||
docker compose logs app # the database update runs on start (migrations 004-007)
|
||||
```
|
||||
6. **Nothing else changes.** The router ports (TCP 7881, UDP 3478, UDP 20000-20100), the
|
||||
Nginx Proxy Manager settings (`npm-advanced.conf`), `docker-compose.yml` and `livekit.yaml`
|
||||
are the same as 0.1.2.
|
||||
7. Open the site and log in. Then work through the checklist below.
|
||||
|
||||
**Rolling back:** stop 0.2.0 (`docker compose down` in `doghouse-0.2.0/deploy`). Restore the
|
||||
backup from step 1 into the old folder: in `doghouse-0.1.2/deploy`, run
|
||||
`sudo rm -rf data && sudo tar xzf ~/doghouse-backup-<date>.tgz`. Then start 0.1.2 again with
|
||||
`docker compose up -d` in `doghouse-0.1.2/deploy`. Don't point 0.1.2 at the upgraded `data`
|
||||
folder; always use the backup. Anything posted after the upgrade is lost on rollback.
|
||||
|
||||
## Justin's real-device checklist
|
||||
|
||||
Please try these on real phones. Our automated tests use desktop Chrome with fake cameras and
|
||||
microphones, so they can't cover these.
|
||||
|
||||
**Calls and video (M10)**
|
||||
1. Call from a phone on mobile data (not Wi-Fi) to a desktop, and the other way round, on
|
||||
iPhone Safari and Android Chrome. Check ringing, Accept, sound both ways, Leave, and the
|
||||
"call ended after …" line in the chat.
|
||||
2. Ringing on a phone with the screen locked: it's expected **not** to ring (no push
|
||||
notifications). With Doghouse open in a background tab, check that the incoming-call card and
|
||||
the flashing tab title are there when you switch back, and the sound if the browser allows it.
|
||||
On Android, check the vibration.
|
||||
3. The ringtone before you've tapped anything on the page: iPhone blocks the sound, but the
|
||||
incoming-call card must still show.
|
||||
4. Camera permission prompts on iPhone Safari and Android Chrome. Deny once, then allow it in
|
||||
the browser settings and try again. The message should be clear, and the call should keep
|
||||
going on audio.
|
||||
5. Switch between front and back camera during a call on both phones. The other side should see
|
||||
the switch without anyone rejoining. Also rotate the phone during a call.
|
||||
6. Lock the screen or switch apps with the camera on. The camera light should go out, and the
|
||||
others should see your camera go off. When you come back, it stays off until you turn it on.
|
||||
7. Desktop: unplug a USB camera during a call. A message should appear, the sound should keep
|
||||
going, and you should be able to pick another camera in the preview.
|
||||
8. Bandwidth: a call with 5 cameras on. On a desktop viewer, `chrome://webrtc-internals` should
|
||||
show small tiles receiving about 320x180 and an enlarged or fullscreen tile 720p. Tiles
|
||||
scrolled out of view should be paused. Note the server's total upload (router stats or
|
||||
`docker stats`) and compare it with the 5-10 Mbps estimate.
|
||||
9. Layout with 1, 2, 5 and 10 cameras on a small phone, a normal phone, a tablet and a desktop,
|
||||
plus a screen share. Nothing should scroll sideways, and enlarge/fullscreen should work by
|
||||
touch and keyboard.
|
||||
10. Set `VIDEO_ENABLED=false` in `.env` and run `docker compose up -d`. There should be no camera
|
||||
button. Do it while someone has their camera on: their camera should be turned off.
|
||||
|
||||
**Profiles, icons and groups (M7-M9)**
|
||||
|
||||
11. Set a profile picture from a phone photo (iPhone and Android), including a photo taken in
|
||||
portrait. The crop should be easy by touch, and the picture should come out the right way up.
|
||||
12. Upload an animated GIF as a profile picture from a phone. It should stay animated for others.
|
||||
13. Open someone's profile card from a message, the member list and a voice channel on a phone.
|
||||
It should fit the screen and close with its close button.
|
||||
14. Set a server icon and banner from a phone. Check the server header with a long server name
|
||||
on a small phone.
|
||||
15. Create a group from a phone, add someone, rename it, set an icon, then have someone leave.
|
||||
They should lose the group straight away on their own phone too.
|
||||
16. On a small phone, a group with a very long name: the message box stays one line until you
|
||||
type.
|
||||
17. After the upgrade, check that existing DMs, their history and attachments, and server icons
|
||||
from 0.1 are all still there.
|
||||
|
||||
## For reference
|
||||
- Version 0.2.0, tag `v0.2.0`. Database migrations 004-007 are applied automatically and are
|
||||
safe to re-run.
|
||||
- New setting: `VIDEO_ENABLED` (default `true`). Optional: `CALL_RING_TIMEOUT_MS`,
|
||||
`MEDIA_DIR`.
|
||||
- Engineering notes: `CHANGES-M7.md`, `CHANGES-M8.md`, `CHANGES-M9.md`, `CHANGES-M10.md` (in the
|
||||
repository, not in the zip).
|
||||
@@ -0,0 +1,204 @@
|
||||
# Doghouse 0.3.0
|
||||
|
||||
Release notes, filled in as milestones land. The detailed engineering notes per milestone
|
||||
(`CHANGES-M11.md` to `CHANGES-M13.md`) are in the repository, not in the zip.
|
||||
|
||||
## M11: install it as an app
|
||||
- Doghouse can be installed to the home screen or desktop (manifest, icons, install button in
|
||||
Settings > App and notifications; iPhone steps shown there).
|
||||
- A service worker shows a friendly offline page when the server can't be reached. It caches
|
||||
no app files, so an upgrade can't leave you on a mix of old and new.
|
||||
- Upgrades: a new version takes over when you have only one Doghouse window open and aren't in a
|
||||
call or voice channel. Otherwise it waits until you close the other windows or leave the call.
|
||||
- Nothing to configure. Your reverse proxy must not cache `/sw.js` or `/manifest.webmanifest`.
|
||||
|
||||
## M12: push notifications
|
||||
- Switch notifications on per device in Settings > App and notifications (asked only then), with a
|
||||
Send test button. DMs and group chats notify for every message; servers for @mentions and replies.
|
||||
Levels per server, channel and DM; Do Not Disturb; quiet hours in your own time zone.
|
||||
- "Show message content" off: the notification says only who wrote, and the push carries no text.
|
||||
- No notification for what you are looking at in a focused tab; a burst of messages folds into one
|
||||
"N new messages" notification; tapping opens the right conversation.
|
||||
- Self-hosted Web Push: a key pair is made on first start in `data/vapid.json` (in your backup). Your
|
||||
server needs outbound HTTPS to Google/Apple/Mozilla push services.
|
||||
- Database migration 008 (automatic). Roll back only from a backup.
|
||||
- @mentions are highlighted in messages.
|
||||
|
||||
## M13: ringing calls and ringtones
|
||||
- A DM or group call rings: the other people get a card with Accept and Decline, a looping tone
|
||||
(three built-in tones, or your own), and a vibration on phones. The caller hears a soft ringback.
|
||||
With the app closed, a push rings the phone: Accept opens the app on the call (the browser needs
|
||||
a tap before it will open the microphone), Decline declines. A ring push lives 30 s at most; a
|
||||
`call-end` push clears it when the caller hangs up or someone answers.
|
||||
- No loud ring (the card still shows) with Do Not Disturb, in quiet hours, or while you are already
|
||||
in a call. Two tabs of one browser: only the visible tab rings aloud; both show the card.
|
||||
- Settings > App and notifications: choose a tone, preview it, set the volume, or "Use my own
|
||||
ringtone" (mp3, ogg Vorbis/Opus or wav, up to 1 MB and 30 s). Your file is checked in the page
|
||||
and stays on that device (never uploaded); it survives logout, another account on the same
|
||||
browser gets the default, and Remove deletes it.
|
||||
- Pushes go through two queue lanes so a slow message push can't delay a ring: calls 16 at a
|
||||
time with a 4 s timeout (dropped if they waited over 20 s), messages 8 at a time with a 10 s
|
||||
timeout. A message push to an endpoint that timed out is skipped for 60 s; rings never are.
|
||||
- Push housekeeping: 408 and 413 are treated as temporary; five other client errors within 24 h
|
||||
switch a device off ("Not working" in Settings); a success resets the count; duplicate device
|
||||
rows are merged at start-up.
|
||||
- Details and review fixes: `CHANGES-M13.md` (in the repository, not in the zip).
|
||||
|
||||
## M14: clean-up
|
||||
- Two tabs, one ring (QA-39): a BroadcastChannel claim, visible tab first. It fails open: a hidden
|
||||
tab waits about 300 ms for a visible tab and rings if none answers; a visible tab that freezes
|
||||
can't leave the ring silent (the other tab rings again within about 4 to 5 s). No Web Lock is used.
|
||||
- A tab in a call tells the other tabs of the browser (QA-50), which then don't ring aloud (the card
|
||||
still shows). A tab that crashes or freezes is forgotten after about 4 s, so it can't silence them for good.
|
||||
- A late LiveKit `room_finished` of an earlier call in the same DM can no longer end the new call
|
||||
(QA-54): the call remembers its LiveKit room session id and ignores a `room_finished` for another
|
||||
session or from before the call started; as a backstop the server asks LiveKit whether anyone is
|
||||
still in the room first (and ends the call as before if LiveKit can't be asked).
|
||||
- The call room name is reused for every call in a DM, so the server no longer removes people or
|
||||
deletes the room by name on a normal path: a normal leave, and a call ending with nobody in it,
|
||||
make no LiveKit change at all (the client has already disconnected; LiveKit closes an empty room
|
||||
itself). When someone must be forced out (a declined 1:1 whose caller is still connected, a
|
||||
member removed from a group, joining a voice channel, an outsider in the room) the server first
|
||||
looks that session up and removes only that session, and does nothing if LiveKit can't be asked
|
||||
(the app's own `call:state` also makes the client leave). The only `deleteRoom` left is the
|
||||
start-up cleanup of rooms that have no call and the deletion of a group's room when the group
|
||||
itself is gone.
|
||||
- LiveKit's own room timeouts are already set, with no action needed and nothing new in 0.3.0:
|
||||
`deploy/livekit.yaml` has had `room.empty_timeout: 300` (an empty room is closed after 5
|
||||
minutes) and `departure_timeout: 20` since 0.1.x, and it and `docker-compose.yml` are identical to
|
||||
0.2.0. Only the e2e LiveKit config uses 10 and 5.
|
||||
There is no other LiveKit config in the repo (no separate dev one). Nothing needs changing: a
|
||||
room that is still open when the next call in the DM starts is simply reused, which the session
|
||||
checks above allow for.
|
||||
- Built-in tone format (QA-42): if the first format (ogg or m4a) won't decode, the other is tried
|
||||
once, then silence without an error loop.
|
||||
- Custom ringtone checks (QA-41, rest): the WAV duration is read by walking the RIFF chunks (a big
|
||||
chunk before `data` no longer hides it); an mp3 with some junk before its first frame is
|
||||
accepted (two real frames in the first 4 KB), ADTS AAC is refused; an Ogg must carry Vorbis or
|
||||
Opus (Ogg-FLAC, Speex and Theora are refused before decoding). Size is still checked first,
|
||||
then the format.
|
||||
- e2e skip audit (below).
|
||||
|
||||
## Environment variables new in 0.3
|
||||
| Var | Default | Notes |
|
||||
|---|---|---|
|
||||
| `VAPID_PUBLIC_KEY`, `VAPID_PRIVATE_KEY` | generated into `data/vapid.json` | Set both or neither. Changing keys makes every device switch notifications on again |
|
||||
| `PUSH_ENDPOINT_ALLOW` | empty | Extra push-service hosts (`host` or `*.suffix`, https only). Needed only if your browser's push service isn't Google, Apple, Mozilla or Windows |
|
||||
| `PUSH_TEST_ORIGINS` | empty | Tests only (read only when `NODE_ENV=test`): lets the e2e suite point pushes at a local mock. Ignored in production |
|
||||
| `CALL_RING_TIMEOUT_MS` | `30000` | Existing since 0.2.0; the ring push TTL is capped at 30 s whatever this says |
|
||||
|
||||
Limits: 10 devices per account (an 11th replaces the one that last received a push longest ago).
|
||||
|
||||
## Upgrading from 0.2.0 and rolling back
|
||||
- Upgrade as in the README ("Upgrading 0.2.0 -> 0.3.0"). Migration `008_push.sql` runs on start
|
||||
(additive: push devices, notification settings, user columns). A new `data/vapid.json` appears;
|
||||
it is part of your backup.
|
||||
- No new ports. Your reverse proxy must not cache `/sw.js` or `/manifest.webmanifest`.
|
||||
- Rollback: stop 0.3.0, restore the backup taken before the upgrade into the 0.2.0 folder, start
|
||||
0.2.0. Do not run 0.2.0 on upgraded data.
|
||||
- Custom ringtones live in each browser (IndexedDB) and are not in your backup.
|
||||
|
||||
## Developers: the e2e skip audit (M14)
|
||||
A full e2e run (`REQUIRE_LIVEKIT=1`) is 52 passed, 44 skipped, 0 failed. All 44 skips were checked
|
||||
and are intentional; none was stale or accidental (no test is skipped for a missing LiveKit when
|
||||
`REQUIRE_LIVEKIT=1`, which fails instead). Each skip now says why in its own message.
|
||||
- **Desktop-only tests (42 skipped in the phone project):** the test builds its own browsers or
|
||||
viewports, or the thing it checks isn't viewport dependent, so a second run adds nothing.
|
||||
`call-recall.spec` (1), `call-restart.spec` (1), `calls.spec` (7), `dm-presence.spec` (2), `groups.spec` (1), `profiles.spec` (1),
|
||||
`push.spec` (4), `pwa.spec` (14: worker, offline, install and upgrade lifecycle), `realtime.spec`
|
||||
(1), `ringing.spec` (3), `ringtone.spec` (4), `server-media.spec` (1), `voice.spec` (1),
|
||||
`xss.spec` (1).
|
||||
- **Phone-only tests (2 skipped in the desktop project):** the 320 px composer layout
|
||||
(`composer-layout.spec`) and the phone layout check in `pwa.spec`.
|
||||
- **Missing LiveKit:** skips only when `REQUIRE_LIVEKIT` is not 1 (no `livekit-server` binary); with
|
||||
it set the suite fails instead of hiding the voice tests.
|
||||
- **Skip policy** (also at the top of `e2e/playwright.config.ts`): the suite runs in a desktop and a
|
||||
phone project. A test that builds its own browsers or viewports, or isn't viewport dependent,
|
||||
runs once, in the desktop project, and skips in the phone project with a reason starting
|
||||
`desktop only:`. A layout check that only makes sense on a phone runs only in the phone project
|
||||
and starts its reason with `phone only:`. The only other skip is a missing LiveKit binary, and
|
||||
`REQUIRE_LIVEKIT=1` turns that into a failure. Every new skip needs a reason of one of these
|
||||
kinds; a bare `test.skip` or a skip without a reason is not allowed. A full run reports 44 skipped
|
||||
(42 desktop-only skips in the phone project, 2 phone-only skips in the desktop project) today.
|
||||
|
||||
## Fixes found in review
|
||||
- Upgrades could occasionally stay on the old service worker when the page reloaded right as the
|
||||
new worker was waiting; the page now waits for the page to settle before asking it to take over.
|
||||
- A call or voice channel is now protected from worker upgrades from the moment you click Join
|
||||
until you leave, including the short automatic reconnect.
|
||||
|
||||
## Developers
|
||||
- e2e ports, screenshot and artifact folders are env vars (`e2e/ports.mjs`), so suites can run
|
||||
side by side.
|
||||
- `E2E_UNIQUE_OUTPUT=1` gives each e2e run its own output folder (`test-results/e2e-<time>`), so loops
|
||||
don't overwrite earlier failures. `ringing.spec` saves each page's console and the `call:*` events the
|
||||
server sent it into the test's output folder (and attaches them).
|
||||
- `call-restart.spec.ts` (real LiveKit): ends a call and at once starts a new one in the same DM
|
||||
(people take turns, since one person may start 10 calls per 10 minutes) and checks that each new
|
||||
call is still the DM's active call, with its caller connected, 6 s later. It runs 3 restarts by
|
||||
default; `E2E_RAPID_RESTARTS=20 npm run e2e:only -- call-restart.spec.ts` runs a longer one
|
||||
(about 7 s per restart). Checked against the code before the QA-54 fixes (ae56d85): it did not fail
|
||||
there (20 of 20 restarts survived, idle and under load), so it is a regression guard for the
|
||||
race rather than a reproduction of it; the server tests are what pin the fix.
|
||||
- `E2E_SERVER_LOG=<file>` keeps the e2e app server's log, and `E2E_LOG_LEVEL=info` makes it include
|
||||
every LiveKit kick, removal, room delete and call-end decision (reason, identity, room, sid, call
|
||||
id; QA-58). `E2E_LIVEKIT_LOG=info` (default `warn`) sets the e2e LiveKit server's log level; its
|
||||
log is `livekit.log` in the run's data folder.
|
||||
- `call-recall.spec.ts` (real LiveKit): cancel a call and call again at once, with the hang-up
|
||||
slowed down (`E2E_LEAVE_DELAY_MS`, default 400; `E2E_RECALL_CYCLES=N`).
|
||||
- e2e fails early with a clear message if its ports are busy, and kills leftover servers when it
|
||||
finishes.
|
||||
|
||||
## Known issues
|
||||
- Starting a call within a second or two of cancelling or timing out another call in the same chat
|
||||
can, rarely, drop the new call at connect. Calling again works. Seen about 2 times in roughly 400
|
||||
related test runs, and once only under heavy CPU load. The suspected cause (the hang-up request
|
||||
being overtaken by the next start) is fixed on the client and covered by a server test, but it
|
||||
was never reproduced in a browser, so the cause is not proven. With `E2E_LOG_LEVEL=info` the
|
||||
server logs who removed a call participant and why.
|
||||
**Fixed in 0.3.1** (see `CHANGES-0.3.1.md`): the cause was found and each call now has its own
|
||||
LiveKit room.
|
||||
|
||||
## Real-device checklist (phone and desktop)
|
||||
Nothing here can be proven by the automated tests; do it once on real hardware before shipping.
|
||||
- **Real push round trip:** on Android Chrome, switch notifications on, close the app completely,
|
||||
have someone DM you: the notification appears and tapping opens that DM. Repeat with the phone
|
||||
locked. Turn "Show message content" off and check it only says who wrote. Log out and check the
|
||||
phone stops getting them.
|
||||
- **iPhone:** iOS 16.4 or later, Safari, Add to Home Screen, then switch notifications on from the
|
||||
installed app (not from Safari). Check a DM push and a call ring push arrive with the app closed,
|
||||
the status bar and notch / home-indicator insets in the installed app, and that the call card
|
||||
fits. Settings shows the steps if you try from a Safari tab.
|
||||
- **Install:** Android Chrome Install; desktop Chrome or Edge Install.
|
||||
- **Ringing, with the app closed:** call the phone; it rings (system notification sound, plus the
|
||||
notification with Accept and Decline). Accept opens the app on the call and you tap Accept there;
|
||||
Decline from the notification declines. Put the phone offline for over 30 s while it's called, then bring it back online: no late ring.
|
||||
- **Android notification buttons:** Accept and Decline on the call notification, and a missed call
|
||||
shows "Missed call from X" afterwards.
|
||||
- **Loud-ring suppression in a call:** while on a call (or in a voice channel), have a second person
|
||||
call you: the card shows but there is no loud ring; the same with Do Not Disturb on.
|
||||
- **DND and quiet hours, by ear:** with DND on, a call card is silent and there is no vibration or
|
||||
push sound; set quiet hours that include now (in your own time zone) and check the same; turn
|
||||
both off and check it rings again. The caller's ringback is silent too in DND and quiet hours.
|
||||
- **Safari AAC decode:** on iPhone/Mac Safari, the three built-in tones play (they are `.m4a` there),
|
||||
loop with no gap or click, and the preview works. Try a custom mp3 and a custom wav (and an ogg on
|
||||
recent Safari): accepted ones play, an undecodable one gets a clear message.
|
||||
- **Tone quality by ear:** listen to Classic phone, Soft marimba and Doghouse jazz on the phone
|
||||
speaker and on headphones: loop seam, loudness at 70% (default), at 100% (capped), and the
|
||||
ringback pulse.
|
||||
- **10-device cap:** register notifications on 11 devices or browsers for one account (a few
|
||||
browser profiles will do): the 11th works and the one that received a push longest ago stops
|
||||
getting them. Server tests cover the rule; this only confirms it with real devices.
|
||||
- **Push lanes:** with a push endpoint that hangs, ring pushes to your other devices still arrive
|
||||
within a couple of seconds and a message push to the blocked one backs off. Blocking is per push-service
|
||||
host (Chrome and Android use Google's FCM, Safari/iPhone use Apple's, Firefox uses Mozilla's), so
|
||||
use a Firefox or Apple device alongside a Chrome device: block only one host with the firewall (for
|
||||
example `fcm.googleapis.com`) and check the other device still gets its ring. Two Chrome/FCM
|
||||
devices would be blocked together and prove nothing. Server tests (`push-lanes.test.ts`) cover this
|
||||
with fake endpoints; the real check is only that nothing in front of your server changes it.
|
||||
- **Two tabs:** on desktop, open Doghouse in two tabs and ring yourself from another account: only
|
||||
the tab you are looking at rings aloud; switching tabs moves the sound; both show the card.
|
||||
- **Rejoin gap with a forced network drop:** drop the connection mid-call (airplane mode for a few
|
||||
seconds, or switch Wi-Fi off), let the call rejoin on its own, and with a new version deployed,
|
||||
confirm the upgrade does not swap the worker during the rejoin gap (the call keeps going and the
|
||||
tab is not reloaded). It should only swap after you leave the call.
|
||||
@@ -0,0 +1,32 @@
|
||||
# Doghouse 0.3.1
|
||||
|
||||
A small fix release on top of 0.3.0. No database changes, no new settings, no new ports.
|
||||
|
||||
## Fixes
|
||||
- Fixed: a call started right after an earlier one ended (for example after the ring timed out or
|
||||
you cancelled) could, rarely, drop as it connected (QA-58). When a call ends with someone still
|
||||
connected, the server asks LiveKit to remove them. LiveKit removes people by user, not by
|
||||
connection, and could carry that out up to about a second late, by which time the same person
|
||||
was already in their next call in the same room. Every call now gets its own LiveKit room, so a
|
||||
removal can only ever reach the call it was meant for. The 0.3.0 known issue is gone.
|
||||
- Quick call-again is snappier when the network is slow: if the hang-up of the previous call is
|
||||
slow to answer, starting or accepting the next call waits at most 3 s in total (it could add up
|
||||
to 6 s before). Decline never waits.
|
||||
- README: the file list names the right release notes, and the release notes it points to
|
||||
(0.2.0 and 0.3.0) are now in the zip. The upgrade steps say to check that the app starts healthy
|
||||
(the database changes are applied quietly and don't print a log line).
|
||||
- e2e skip count in `CHANGES-0.3.0.md` corrected to 44.
|
||||
|
||||
## Upgrading from 0.3.0 and rolling back
|
||||
- Upgrade as in the README ("Upgrading 0.3.0 -> 0.3.1"): replace the files, keep `deploy/.env`
|
||||
and `deploy/data`, then `docker compose up -d --build`.
|
||||
- Calls going on during the upgrade end when the app restarts (as with any restart), with the
|
||||
usual "call ended" message in the chat. Calling again works straight away.
|
||||
- The first start of 0.3.1 closes any LiveKit call rooms left over from 0.3.0 (they were named
|
||||
after the conversation; 0.3.1 names them after each call). This is automatic.
|
||||
- Rollback: start 0.3.0 again on the same data. Nothing in the database changed. Calls going on at
|
||||
the time end, and 0.3.0 cleans up the 0.3.1 call rooms on its own.
|
||||
|
||||
## Phone checklist
|
||||
The 0.3.0 real-device checklist (`CHANGES-0.3.0.md`) still applies. Anything Justin finds on his
|
||||
phones goes here.
|
||||
@@ -0,0 +1,164 @@
|
||||
# Doghouse 0.4.0
|
||||
|
||||
Pinned messages, blocking and theme presets, on top of 0.3.1. One additive database migration,
|
||||
`009_pins_blocks.sql`, applied automatically on start. No new settings and no new ports.
|
||||
|
||||
## What's new
|
||||
- **Pinned messages:** pin or unpin a message from its menu in channels, DMs and group DMs (anyone
|
||||
in the conversation can). The pin button in the chat header lists the pins with author, who
|
||||
pinned it and when, and jumps to the message. Up to 50 pins per conversation; "X pinned a
|
||||
message" appears in the chat; deleting a message removes its pin.
|
||||
- **Blocking:** block or unblock someone from their profile card or your DM with them; Settings
|
||||
lists the people you blocked. They can't DM you, call or ring you, or add you to a group, and
|
||||
they aren't told. Your DM with them stays, read-only; their messages in shared servers are
|
||||
hidden, and so are their typing, mentions, unread counts and pushes. Blocking ends a 1:1 call
|
||||
with them; group calls carry on. Server moderation is unaffected.
|
||||
- **Themes:** ten new presets (Doghouse, Neon, Synthwave, Nord, Solarized light, Solarized dark,
|
||||
Forest, Ocean, Sepia, High contrast) next to Dark, Light and AMOLED, plus Auto, which follows
|
||||
each device's light or dark setting. Your theme, accent, text size and compact mode follow your
|
||||
account to every device. Every preset reads at 4.5:1 or better (7:1 in High contrast).
|
||||
- Settings and `/api/health` show the running version.
|
||||
- Dependencies updated (zod, fastify, fast-uri) for the advisories found in 0.3.1's review, and
|
||||
oversized lists in requests are refused before they are checked item by item.
|
||||
|
||||
## Behaviour changes to know about
|
||||
- Pins: pinning and unpinning together are limited to 10 a minute per person, across all chats.
|
||||
Beyond that the server answers `429 too_many_pins` with a `Retry-After` header, like the other
|
||||
limits. The limit follows the global `RATE_LIMIT`
|
||||
switch, which is on by default. Re-pinning a message whose "pinned a message" line is under 10
|
||||
minutes old posts no new line.
|
||||
- Read-only DMs: a DM you can't post in (you no longer share a server, or a block either way) now
|
||||
refuses with `403 cant_send` ("Couldn't send") instead of `dm_closed`. The two cases look
|
||||
identical on purpose, so a blocked person can't tell. A 0.3 tab still open after the upgrade
|
||||
shows a generic error for that refusal until it is reloaded.
|
||||
- Push and blocks: a message's push is checked against blocks when it is delivered, not when it
|
||||
is sent. A notification already on its way when you block someone may still arrive; nothing
|
||||
sent after the block notifies you.
|
||||
- High contrast: links, mentions and other accent-coloured text always use the theme's own yellow
|
||||
(7:1), whatever accent you pick; your accent still colours buttons and highlights. Settings says
|
||||
so under the accent picker.
|
||||
- Theme changes made just before a reload, tab switch or close are kept: they are sent as the page
|
||||
goes away and, if that is lost, sent again on the next load. That retry only happens if the
|
||||
theme wasn't changed on another device in the meantime; if it was, the other device's newer
|
||||
choice wins and the older one is dropped. A change you make and then leave in the same tab is
|
||||
always your latest choice: it is kept even if you change themes quickly on a slow connection,
|
||||
and even if another device changed the theme while that tab was open.
|
||||
- A theme change now shows straight away in your other open tabs and on your other signed-in
|
||||
devices, without a reload. A tab where you have just changed the theme yourself keeps your
|
||||
change until it is saved. Nobody else is told about your theme.
|
||||
- Call screen: the name, muted/deafened icon and volume slider over someone's video now sit on a
|
||||
solid dark chip, the speaking outline is a two-colour ring, and the incoming call's Decline
|
||||
button has fixed colours with a white ring, so all of them stay visible over any video and in
|
||||
every theme.
|
||||
- A saved theme with one damaged setting (for example a text size outside the allowed range) now
|
||||
keeps the theme and its other settings, using the default only for the damaged one, and is not
|
||||
overwritten by the device you open it on. Before, the whole theme was treated as never saved.
|
||||
Settings > Appearance keeps that theme ticked and says some settings couldn't be read; changing
|
||||
the damaged setting or picking a theme fixes it.
|
||||
|
||||
## Upgrading from 0.3.x and rolling back
|
||||
- Upgrade as in the README ("Upgrading 0.3.1 -> 0.4.0"): back up `data` and `.env`, unzip
|
||||
`doghouse-0.4.0.zip` into a **fresh folder** next to the 0.3.1 one (not over it), copy
|
||||
`deploy/.env` and move `deploy/data` across, then `docker compose up -d --build`. Keep the 0.3.1
|
||||
folder: a rollback uses it. Migration `009_pins_blocks.sql` (pins and blocks tables, additive)
|
||||
runs on start without a log line. Calls going on during the upgrade end, as with any restart.
|
||||
- Rollback to 0.3.1, if you need it (the same steps as in the README):
|
||||
1. In `doghouse-0.4.0/deploy`: `docker compose down`.
|
||||
2. Move `data` back into the 0.3.1 folder: `mv data ../../doghouse-0.3.1/deploy/`. That folder
|
||||
still has its `.env`. If you deleted it, unzip `doghouse-0.3.1.zip` into a fresh folder first
|
||||
and copy `deploy/.env` into it.
|
||||
3. Optional, instead of step 2: restore the backup you made before the upgrade. In
|
||||
`doghouse-0.3.1/deploy`: `tar xzf ~/doghouse-backup-<date>.tgz` (it puts back `data` and
|
||||
`.env`). **This loses everything since the upgrade: messages, pins, blocks and theme
|
||||
changes.** Only do this if the data itself is the problem.
|
||||
Then, still in `doghouse-0.3.1/deploy`, rename the old 0.4 data so it is never used by mistake:
|
||||
`mv ../../doghouse-0.4.0/deploy/data ../../doghouse-0.4.0/deploy/data-before-rollback`. A later
|
||||
upgrade then moves the restored `data` in as usual.
|
||||
4. In `doghouse-0.3.1/deploy`: `docker compose up -d --build`. 0.3.1 runs on the moved data and
|
||||
ignores the pins and blocks tables; messages sent on 0.4.0 are kept.
|
||||
|
||||
What a rollback changes for themes, blocks and pins is listed below.
|
||||
- 0.3.x tabs still open after the upgrade keep working until they are reloaded; the differences
|
||||
are listed below.
|
||||
|
||||
## Known limits
|
||||
- Blocking can sometimes be inferred (accepted under D5, QA-73). "Couldn't add" (adding someone
|
||||
to a group) and "Couldn't send" when opening a *new* 1:1 DM only ever come from a block; the
|
||||
ordinary failures there are "User not found". Sending in an existing DM is ambiguous on purpose:
|
||||
a DM where you no longer share a server gives exactly the same "Couldn't send".
|
||||
- Blocking hides what is broadcast to a room (live messages, edits, reactions, typing) in the app,
|
||||
not on the wire: it still reaches the blocker's browser and is visible in developer tools (D3).
|
||||
History, pins, unread counts, pushes, reply quotes and reaction counts are filtered by the server.
|
||||
- A 0.3.x tab left open after the upgrade shows live messages, quotes and reactions from people
|
||||
you blocked until it is reloaded, and if it reconnects while a group call involving a blocked
|
||||
person is ringing it can show that call's incoming card (0.4 rings only on the server's
|
||||
per-person answer).
|
||||
- Rolling back to 0.3.x turns blocking off completely: DMs, calls, unread counts, pushes and
|
||||
history from blocked people all come back, and 0.3.1 words a blocked DM as "you no longer share a
|
||||
server". Upgrading to 0.4 again turns the blocks back on (they are kept in the database) and
|
||||
hides what was sent in the meantime.
|
||||
- Rollback to 0.3.x: the 0.4 tables are ignored, but the "X pinned a message" lines already in
|
||||
chats are shown by 0.3 as "X updated the group" (QA-68). They read correctly again after
|
||||
upgrading back to 0.4.
|
||||
- Themes: 0.4 adds ten colour presets and Auto. After a rollback to 0.3.x an account whose theme
|
||||
is one of them shows the default (Dark) theme, and the 0.3 app then saves that default to the
|
||||
account, so upgrading to 0.4 again keeps Dark until the person picks their theme again. Accent,
|
||||
text size and compact mode on such an account also go back to the defaults. Accounts on Dark,
|
||||
Light or AMOLED are unaffected. 0.4 itself is safe for the next rollback (D19): given a theme it
|
||||
does not know (saved by a later version) it shows Dark with the saved accent, size and compact
|
||||
setting but writes nothing back. Changing the accent, size or compact saves only that setting and
|
||||
keeps the saved theme; picking a theme replaces it.
|
||||
A theme change a 0.4 device made but never managed to save before a rollback is not sent again
|
||||
after the re-upgrade if the theme was changed under 0.3 in the meantime: the later 0.3 choice
|
||||
wins. A 0.4 tab left open against a server rolled back to 0.3.x can't save theme
|
||||
changes until it is reloaded.
|
||||
- Solarized light and Solarized dark keep the published Solarized background colours (or very
|
||||
close to them), but their text, muted text, danger, success and accent colours are adjusted so
|
||||
everything reads at 4.5:1 or better. The published body-text colours fall short of that, so
|
||||
these themes look slightly higher-contrast than the original palette (D19).
|
||||
- Themes: if you change the theme twice in quick succession and reload straight away, the first
|
||||
change's save can be held up on a slow or flaky connection and reach the server only after the
|
||||
reloaded page has saved your second change. It then replaces it, and every open page shows the
|
||||
first choice again; pick the theme again (D21, QA-87). If those saves are lost altogether
|
||||
instead, the next load re-sends your last choice and nothing is lost.
|
||||
- Known issue, for 0.5 (QA-80): links and muted text on a hovered or selected row, and the mention
|
||||
in the Settings preview, can fall to about 3.2-4.4:1 in several themes (Dark included, as in
|
||||
0.3). Ordinary text on every surface reaches 4.5:1 (7:1 in High contrast).
|
||||
- Known issue, for 0.5 (QA-88): if another device changes the theme while this device's own
|
||||
theme change is still being saved, this device can miss the update and keep showing its own,
|
||||
older choice until it is reloaded or the theme is changed again. The saved theme is right; only
|
||||
that screen is behind.
|
||||
- Known issue, for 0.5 (QA-90): in Settings > Appearance on a device in dark mode, the small "Follows
|
||||
your device" line under Auto is a little low in contrast (3.87:1) while Auto is the selected
|
||||
theme.
|
||||
|
||||
## Developers
|
||||
- `REQUIRE_LIVEKIT=1 npm run check` runs typecheck, lint and all unit tests with nothing skipped.
|
||||
- A full e2e run (`REQUIRE_LIVEKIT=1 npm run e2e`) is 77 passed, 67 skipped, 0 failed. All skips
|
||||
follow the skip policy in `CHANGES-0.3.0.md`: 65 desktop-only tests skipped in the phone
|
||||
project and 2 phone-only layout checks skipped in the desktop project.
|
||||
- The release zip carries the notes of every release (`CHANGES-0.1.1.md` to this file and
|
||||
`CHANGES-M6.md`) and `THIRD-PARTY-NOTICES.md`.
|
||||
|
||||
## Real-device checklist
|
||||
The 0.3.0 checklist (`CHANGES-0.3.0.md`) still applies. New in 0.4, once on real phones:
|
||||
- Pins: pin from a message's menu on a phone, open the pins list at 320 px, jump to an old pin.
|
||||
- Blocking: block someone from their profile card on a phone; their calls don't ring and their
|
||||
pushes don't arrive while the app is closed; unblock from Settings and both work again.
|
||||
- Themes: pick a few presets on the phone and check they follow to the desktop; set Auto and
|
||||
switch the phone between light and dark mode; check the installed app's status bar colour
|
||||
follows the theme.
|
||||
- Themes on a slow connection: on a phone and on a desktop, with a weak signal or a slow network,
|
||||
change the theme and straight away reload, switch to another app or close the tab. When you come
|
||||
back, your last choice is shown.
|
||||
- Hiding the app for real: change the theme, then switch apps, lock the phone or switch browser
|
||||
tabs, and come back. The theme you picked is still there.
|
||||
- Chrome's Duplicate tab: right-click a Doghouse tab and choose Duplicate. Pick a different theme
|
||||
in each tab, then reload both. Both show your last pick; neither tab undoes the other.
|
||||
- Live theme changes: with Doghouse open in two tabs and on a second device, change the theme in
|
||||
one tab. The other tab and the other device switch without a reload.
|
||||
- Calls with a real camera: in a video call, the name labels, the speaking ring and the Decline
|
||||
button are easy to read over real camera video.
|
||||
- After the real upgrade, on your own data: Settings > App and notifications > About shows 0.4.0,
|
||||
old messages and everyone's themes are still there, and a call connects. If you ever roll back,
|
||||
check the same on 0.3.1.
|
||||
@@ -0,0 +1,45 @@
|
||||
# Doghouse 0.4.1
|
||||
|
||||
A small fix release on top of 0.4.0. No database changes, no new settings, no new ports.
|
||||
|
||||
## Fixes
|
||||
- Fixed: in a direct message or group DM, what you were typing was wiped when the other person
|
||||
sent a message before you sent yours (QA-102). Every new message (and a pin, which posts "pinned
|
||||
a message", or a block or unblock from any of your devices) refreshes the conversation, and the
|
||||
message box treated that as switching conversations and put back the saved draft, usually
|
||||
nothing. It now swaps drafts only when you really move to another conversation, so your text,
|
||||
cursor position and focus stay put. This was not new in 0.4.0 (0.3.1 does the same).
|
||||
- The same change also keeps a draft in a server channel when that channel is renamed, its topic
|
||||
is edited or the channels are reordered while you type (QA-104).
|
||||
- The regression test now types new text after switching away and back, so it can't pass on the
|
||||
old saved draft (QA-103).
|
||||
|
||||
## Tested
|
||||
- QA-102 is fixed in 1:1 DMs and group DMs, at desktop and phone size: about 730 tries (incoming
|
||||
messages, pins, blocks and unblocks from another device, replies, switching away and back) with
|
||||
no draft lost. QA-103 and QA-104 are fixed.
|
||||
|
||||
## Known limits (planned for 0.5)
|
||||
- Drafts are kept per tab and in memory only. Moving between a server and Home, or reloading the
|
||||
page, still loses them.
|
||||
|
||||
## Upgrading from 0.4.0 and rolling back
|
||||
- A drop-in: only the web app changed. No database migration, no new settings, and
|
||||
`docker-compose.yml`, `Dockerfile`, `livekit.yaml`, `npm-advanced.conf` and `.env.example` are
|
||||
unchanged. Follow "Upgrading 0.4.0 -> 0.4.1" in the README: unzip into a fresh folder, copy
|
||||
`deploy/.env` across, move `deploy/data` across and `docker compose up -d --build`. Settings and
|
||||
`/api/health` then show `0.4.1`.
|
||||
- Rollback: stop 0.4.1, move `data` back into the 0.4.0 folder and start 0.4.0 on the same data.
|
||||
|
||||
## Developers
|
||||
- The draft swap is `swapDraft` in `apps/web/src/lib/draft.ts` (unit test `draft.test.ts`), used
|
||||
by `Composer.svelte` from an effect that only depends on the conversation id.
|
||||
- New e2e `e2e/tests/drafts.spec.ts` (desktop project, covers desktop and phone sizes): a 1:1 DM
|
||||
and a group DM keep a draft, with the caret mid-text and focus, through the other person
|
||||
sending, a pin, a block and unblock from another device, and switching away and back then
|
||||
typing new text. It is desktop-only, so a full e2e run has one more skip in the phone project
|
||||
than 0.4.0.
|
||||
- `REQUIRE_LIVEKIT=1 npm run check` runs typecheck, lint and all unit tests with nothing skipped.
|
||||
- A full e2e run (`REQUIRE_LIVEKIT=1 npm run e2e`) is 78 passed, 68 skipped, 0 failed. All skips
|
||||
follow the skip policy in `CHANGES-0.3.0.md`: 66 desktop-only tests skipped in the phone
|
||||
project and 2 phone-only layout checks skipped in the desktop project.
|
||||
@@ -0,0 +1,444 @@
|
||||
# Doghouse 0.5.0
|
||||
|
||||
Message search, custom server emoji and threads, on top of 0.4.1, plus the 0.5 fixes (drafts kept
|
||||
across a reload and between a server and Home, the build number, and the items listed under
|
||||
Fixes). One additive database migration, `010_search_emoji_threads.sql`, applied automatically on
|
||||
start. No new settings and no new ports.
|
||||
|
||||
## New: message search (M23)
|
||||
- A search field in the chat header searches the server you're in (every text channel you can
|
||||
see) or the DM or group DM you're in, never anywhere else. On a phone it's a magnifier icon that
|
||||
opens a full-width bar over the header.
|
||||
- Results open in the right-hand panel (full screen on a phone), newest first: who wrote it, where
|
||||
(#channel or the DM), when, and a short extract with the words you searched for highlighted.
|
||||
Jump takes you to the message, even if it's far back or in another channel. "Show older
|
||||
results" loads 25 more at a time.
|
||||
- Every word you type must appear (in any order), and the last word also matches longer words
|
||||
that start with it (`part` finds "party"). Accents don't matter (`cafe` finds "café").
|
||||
Punctuation-only input finds nothing and says so; quotes and words like AND, OR or NEAR are just
|
||||
searched as words.
|
||||
- Filters: type `from:` or `in:` and pick a person or channel from the list, or type
|
||||
`has:file`, `has:link`, `before:2026-11-01` or `after:2026-11-01` (dates are days in your own
|
||||
time zone; `after:` starts the day after). Filters show as chips; click a chip to remove it.
|
||||
You can search with only filters.
|
||||
- You never see messages from people you've blocked, from channels or DMs you can't see, or
|
||||
messages that were deleted. An edited message is found by its new text, not its old text.
|
||||
- Limit: 30 searches a minute per person (off when `RATE_LIMIT=false`).
|
||||
- Known limit: Chinese, Japanese and Korean text is matched by whole runs of characters between
|
||||
spaces or punctuation, so searching for part of a run may not find it.
|
||||
- On a 320 px wide screen, a DM's header puts Add people and Pinned messages in one "More
|
||||
options" menu, so the search icon fits (Add people starts a group from a 1:1 there too,
|
||||
QA-113).
|
||||
- On phones 361 to 400 px wide (375 and 390 px), a group's header no longer runs off the
|
||||
screen and cuts off Notifications: the Group settings button stands in for the group picture
|
||||
there, as it already did at 320 px (QA-112).
|
||||
- Picking a person or channel from the `from:` / `in:` suggestions no longer throws an error in
|
||||
the background; the caret now goes back to where the filter was (QA-114).
|
||||
- Search has its own index inside the database. Some database tools (a hand-run `VACUUM`, a
|
||||
`.dump` and restore, `.recover`) can renumber the rows it points at; Doghouse checks for that
|
||||
every time it starts and rebuilds the index by itself if needed (one line in the log), so a
|
||||
restart puts search right. You can also rebuild it by hand with
|
||||
`node apps/server/dist/scripts/rebuild-search.js` (in Docker:
|
||||
`docker compose exec -u node app node apps/server/dist/scripts/rebuild-search.js`). See the README.
|
||||
- Deleting a big channel no longer stalls the server (QA-116, there since 0.1): a 7,500-message
|
||||
channel in a 100,000-message database now goes in well under a second (before, every deleted
|
||||
message scanned the whole table: 1,500 messages among 11,500 already took close to a second).
|
||||
|
||||
## New: custom server emoji (M24)
|
||||
- Every server can have up to 50 of its own emoji. Anyone in the server can add one in Server
|
||||
settings > Emoji: give it a name (2 to 32 letters, numbers or underscores; `party` and `Party`
|
||||
count as the same name), pick a PNG, JPEG, GIF or WebP image of up to 256 KB and crop it
|
||||
square. Animated GIFs stay animated. The page shows each emoji, its name, who added it and how
|
||||
many of the 50 are used. The person who added an emoji, the owner and admins can rename or
|
||||
delete it.
|
||||
- Use them anywhere: type `:name:` or pick one in the emoji picker, which now has a tab for each
|
||||
of your servers (with the server's icon) before the standard emoji, and searches both. You can
|
||||
use an emoji from any server you're in, in any server, DM or group.
|
||||
- People who aren't in that emoji's server, and messages whose emoji was deleted, show `:name:`
|
||||
as text instead of the picture, never a broken image. Inside `code` it's always plain text.
|
||||
- React with them too. A message can still have at most 20 different reactions, custom and
|
||||
standard together. Deleting an emoji removes its reactions everywhere; old messages show
|
||||
`:name:`.
|
||||
- Limit: 10 emoji uploads a minute per person (off when `RATE_LIMIT=false`).
|
||||
|
||||
## New: threads (M25)
|
||||
- Start a thread on any message in a server text channel: hover it (tap it on a phone) and pick
|
||||
Start thread, or press T with the message focused. The thread is named after the first 60
|
||||
characters of the message. It opens beside the channel on a wide screen and full screen on a
|
||||
phone or tablet, with a Back button to the channel. Esc closes it on a wide screen; focus goes
|
||||
back to where you were.
|
||||
- Replies stay in the thread. The channel shows the message that started it with a badge ("Picnic
|
||||
plans, 3 replies"); the badge opens the thread. The channel header has a Threads button that
|
||||
lists the channel's threads, newest activity first (in More options when the chat is under
|
||||
360 px wide).
|
||||
- Starting or replying follows a thread; the Following button unfollows it, and replying again
|
||||
follows it again. Being mentioned doesn't follow you. Only threads you follow count as unread:
|
||||
the channel gets a small dot, and mentions in a thread count toward the server's mention badge
|
||||
as channel mentions do. Notifications: a reply notifies the people following the thread whose
|
||||
notification level for the channel or server is All; a mention notifies the person mentioned
|
||||
unless their level is None. The title says "#channel › Thread name" and opens the thread.
|
||||
Blocks, quiet hours and Do not disturb work as for channel messages.
|
||||
- If you block someone, a thread they started, or one started on their message, is still listed
|
||||
but its name shows as "Thread" to you, in the list, the thread's title, search and
|
||||
notifications (QA-128). Replies from other people show as normal. If a thread on their message
|
||||
is open when you block them, its parent switches to "Blocked message" at once (QA-133).
|
||||
- Inside a thread everything works as in a channel: edit, delete, reactions, custom emoji, files,
|
||||
pins (up to 50 per thread), drafts (kept per thread) and blocking. Search finds replies in
|
||||
threads too and Jump opens the thread first.
|
||||
- Not in DMs or group DMs, not on system messages, and no threads inside threads. Deleting the
|
||||
message that started a thread leaves the thread ("Original message was deleted"); server admins
|
||||
and the owner can delete a whole thread, with all its replies, from its menu; deleting the
|
||||
channel deletes its threads.
|
||||
- On a wide screen an open thread takes the member list's place; Show member list closes the
|
||||
thread and brings the list back.
|
||||
- Limit: 10 new threads a minute per person (off when `RATE_LIMIT=false`). Replies count as
|
||||
ordinary messages.
|
||||
|
||||
## Fixes
|
||||
- Drafts are kept everywhere: what you type in a channel, DM or group DM is still there after you
|
||||
move between a server and Home and back, and after a reload of the page (D23). Drafts belong to
|
||||
the tab: a new tab or a tab you closed and reopened starts empty, and a second tab doesn't share
|
||||
them (a duplicated tab starts with a copy). Logging out clears every draft in that tab, so the
|
||||
next person to log in there never sees what you were typing, and so does the session ending
|
||||
without a Log out (it expired, or was signed out elsewhere): the app then goes back to the login
|
||||
screen and says "Your session has ended" (QA-108), also when the session ran out while the
|
||||
page was closed or in the background and you then reload it (QA-115). Only the server saying the session is
|
||||
missing or expired, and confirming it when asked again, does that: a wrong password, or any other refused request, is shown as an
|
||||
error and you stay logged in with your drafts. Only the text is kept: a reply you had
|
||||
started or a file you had attached is not. A draft longer than the message limit is kept in
|
||||
full too; it can't be sent until it's shortened (QA-106).
|
||||
- Security (QA-105): `npm audit --omit=dev` is clean again. The three moderate reports published
|
||||
after 0.4.0 shipped (glob GHSA-3g3m-2fjr-6pw4, reached through `@fastify/static`, and minimatch
|
||||
GHSA-g3hv-75wg-m249) are gone: `@fastify/static` goes from 10.1.5 to 10.1.10, a patch release
|
||||
that asks for glob 14.0.5, which brings minimatch 11.0.8. No override was needed.
|
||||
- Themes (QA-88): if another device changes the theme while this device's own change is still
|
||||
being saved, this device now switches to the other device's newer choice as soon as its own
|
||||
save is confirmed, instead of staying on its older choice until a reload. Nothing flickers in
|
||||
between, and a change you make on this device after the other one still wins, as before.
|
||||
- `RATE_LIMIT=false` now also switches off the call-start limit (10 new calls per 10 minutes per
|
||||
person), like every other limit; it is listed in the README settings table, and a refusal now
|
||||
says when to try again (`Retry-After`) (QA-101).
|
||||
- Calls: joining a call always names the call it means (D10, planned in 0.4). 0.4.x pages
|
||||
already do, so they join as before; only a 0.3 page still open after the upgrade gets "Reload
|
||||
the page to join this call" until it is reloaded (QA-107).
|
||||
- Readability (QA-80, QA-90): links, mentions and muted text on a hovered or selected row (a
|
||||
message under the pointer, the open channel or DM, a picked theme card) and the mention in the
|
||||
Settings preview now read at 4.5:1 or better in every theme, 7:1 in High contrast. Before, they
|
||||
could drop to about 3.2-4.4:1, and Auto's "Follows your device" line was 3.87:1 when Auto was
|
||||
picked on a dark device.
|
||||
- High contrast with your own accent colour: accent-filled buttons, pills and highlights keep your
|
||||
colour's hue but are lightened when needed, so their labels read at 7:1 and they stand out on
|
||||
the black background (a black accent used to give black buttons on black). In High contrast a
|
||||
custom accent is lightened until its label reaches 7:1, and Settings > Appearance then shows
|
||||
"Adjusted for readability" with the colour used. The keyboard focus ring in High contrast also
|
||||
reaches 7:1 with any accent (QA-110).
|
||||
- Docs (QA-96, QA-98): the backup command now names each file with the date **and time**
|
||||
(`doghouse-backup-$(date +%F-%H%M%S).tgz`), so a second backup on the same day no longer
|
||||
replaces the first, and the restore-rollback renames the old data to
|
||||
`data-before-rollback-$(date +%F-%H%M%S)`, so a second rollback no longer puts the newer data
|
||||
inside the older folder.
|
||||
- Docs (QA-97, QA-99, QA-100): the 0.3.1 -> 0.4.0 notes in the README now say that 0.3.0 can go
|
||||
straight to 0.4.0 (reading `doghouse-0.3.0` for `doghouse-0.3.1`), that a 0.3.0 user rolls back
|
||||
to 0.3.1 rather than 0.3.0 (unzip 0.3.1 into a fresh folder and copy `.env` from
|
||||
`doghouse-0.4.0/deploy`), and the last rollback step no longer says the 0.4.0 messages are kept
|
||||
after you restored the backup.
|
||||
- Build number (story 26): Settings > About now shows which build the server runs, e.g.
|
||||
`0.5.0 (build 1a2b3c4d5e, 2026-11-20)`, with a Copy version button for bug reports (it copies the same name as the screen, e.g.
|
||||
`Doghouse 0.5.0 build 1a2b3c4d5e (2026-11-20T03:14:00Z)`, using your `APP_NAME`). The same
|
||||
`build` object (`version`, `commit`, `commitDate`) is on `/api/health` and `/api/instance`.
|
||||
- QA-94: the package is now the same, byte for byte, whatever time zone it is built in (the zip's
|
||||
file times are the commit time in UTC).
|
||||
- Rolling back to 0.4.1 no longer deletes custom emoji pictures (QA-120). They are now stored in
|
||||
their own `emoji` folder inside the media folder, which 0.4.1's clean-up of unused pictures
|
||||
leaves alone, so upgrading again shows them.
|
||||
- A chat whose messages fail to load (the server or a proxy answers with an error) now says so
|
||||
with a Retry button, instead of asking again hundreds of times a second in every open tab
|
||||
(QA-121, at least since 0.4.1).
|
||||
- Chat headers fit at every width (QA-112): on a group DM at 401-427 px (common Android phones)
|
||||
and in a 640-663 px window, Notifications was cut off. The header now arranges its buttons by
|
||||
the chat's own width, so the search field becomes an icon and the group picture button steps
|
||||
aside whenever space is short.
|
||||
- The emoji picker lists the server you're in first, and search results say which server each
|
||||
custom emoji is from ("`:party:` from Gaming"), so Enter picks this server's emoji when two
|
||||
servers have one with the same name (QA-119).
|
||||
- The search rebuild command refuses to run when it can't find the database (a wrong `DATA_DIR`
|
||||
or `DB_PATH`) instead of creating an empty one and reporting success, and waits for the server
|
||||
to finish a write instead of failing with "database is locked" (QA-122, QA-123).
|
||||
|
||||
## Upgrading to 0.5.0 and rolling back
|
||||
- From 0.4.1 or 0.4.0: follow "Upgrading 0.4.1 -> 0.5.0" in the README (back up the data folder
|
||||
and `.env`, unzip into a fresh folder, copy `deploy/.env` across, move `deploy/data` across,
|
||||
`docker compose up -d --build`). Settings and `/api/health` then show `0.5.0`.
|
||||
- From 0.3.0 or 0.3.1: the same steps, reading your folder name for `doghouse-0.4.1`. 0.5.0
|
||||
includes every earlier fix, and the migrations in between run on start, in order.
|
||||
- Rollback: to 0.4.1 (not straight to 0.3.x), by moving `data` back into the
|
||||
0.4.1 folder. If you no longer have it, unzip `doghouse-0.4.1.zip` into a fresh folder and copy
|
||||
`.env` into its `deploy` folder from `doghouse-0.5.0/deploy`. If you restore the pre-upgrade
|
||||
backup instead, rename the 0.5 data to `data-before-rollback-$(date +%F-%H%M%S)` first, and note
|
||||
that messages sent on 0.5.0 are then not kept.
|
||||
- The database (migration `010_search_emoji_threads.sql`, the only one in 0.5): it only adds
|
||||
things (a search index, tables for custom emoji and threads, and one empty column on
|
||||
messages); no table is rebuilt. The first start builds the search index from your existing
|
||||
messages inside the migration: about 0.5 s for 118,000 messages on a test machine, and the
|
||||
server is healthy about a second after start. The database file grows by about a third more in
|
||||
that test (+37%). After that, a start-up check confirms the search index is in step (a few tens
|
||||
of milliseconds per 100,000 messages) and, if needed, moves custom emoji pictures into
|
||||
`media/emoji` and moves any thread-reply pins made under 0.4.1 into their thread.
|
||||
- Rolling back to 0.4.1 on the same data works: 0.4.1 doesn't use the new tables. The search index
|
||||
keeps itself up to date under 0.4.1 too, so upgrading again needs no rebuild.
|
||||
- Custom emoji under 0.4.1 after a rollback (Q20): messages show the raw `<:name:...>` text and
|
||||
custom reactions show as a `c:<id>` pill, which 0.4.1 can't remove (its reaction check refuses
|
||||
that value; adding the same `c:<id>` is refused too). Nothing else breaks, and upgrading again
|
||||
shows the pictures and makes them removable. The emoji pictures are kept through the rollback:
|
||||
0.5 stores them in their own `media/emoji` folder inside the data folder (QA-120, D34), which
|
||||
0.4.1's hourly clean-up of unused pictures doesn't touch, and they are in your backups as
|
||||
before.
|
||||
- Threads under 0.4.1 after a rollback (D25): replies keep their channel, so 0.4.1 shows them
|
||||
inline in the channel as normal messages, in time order, without the thread around them. Pins
|
||||
made inside a thread aren't listed, and the channel's unread count includes the replies.
|
||||
Upgrading again puts them back in their threads; replies posted in that channel under 0.4.1 stay
|
||||
in the channel. A thread reply pinned under 0.4.1 moves to its thread's pins on the next start
|
||||
(QA-127); nothing is unpinned, even if that takes the thread past 50 pins.
|
||||
|
||||
## Real-device checklist
|
||||
The 0.3.0 and 0.4.0 checklists still apply. New in 0.5:
|
||||
- Docker build on the server (M21-22): unzip the 0.5.0 package, run `docker compose up -d --build`
|
||||
in its `deploy` folder and wait until `docker compose ps` says healthy. The build must finish
|
||||
with no error about `build.json`. Then Settings > App and notifications > About and
|
||||
`/api/health` both show `0.5.0 (build <10 characters>, <date>)` with the same build as the
|
||||
`build.json` in the zip, and Copy version copies it.
|
||||
- Drafts on a phone: type something in a channel, switch to another app (or lock the phone) for a
|
||||
minute, come back and reload. The draft is still there. Log out and in as someone else in that
|
||||
tab: no drafts.
|
||||
- Duplicate tab: duplicate a tab that has a draft. The new tab starts with it; after that, typing
|
||||
in one tab doesn't change the other.
|
||||
- Custom emoji on a phone: in Server settings > Emoji, add one from the photo library (crop it
|
||||
square) and one animated GIF; both show in the picker's server tab, in a message and as a
|
||||
reaction, and the GIF moves.
|
||||
- Threads on a phone: start one from a message, reply, go Back to the channel and see the badge
|
||||
and the count; tap a thread notification and it opens that thread.
|
||||
- High contrast with your own accent (try black): buttons are a lighter shade of it with readable
|
||||
labels, and Settings > Appearance says "Adjusted for readability".
|
||||
|
||||
## Developers
|
||||
- `REQUIRE_LIVEKIT=1 npm run check` runs typecheck, lint and all unit tests with nothing skipped:
|
||||
shared 49, server 690, web 1701, 0 failed.
|
||||
- A full e2e run (`REQUIRE_LIVEKIT=1 npm run e2e`) is 114 passed, 100 skipped, 0 failed. All skips
|
||||
follow the skip policy in `CHANGES-0.3.0.md`: desktop-only tests skipped in the phone project
|
||||
and phone-only layout checks skipped in the desktop project.
|
||||
- The release zip carries the notes of every release (`CHANGES-0.1.1.md` to this file and
|
||||
`CHANGES-M6.md`) and `THIRD-PARTY-NOTICES.md`.
|
||||
- M25 threads UI (DESIGN-0.5 section 4e): `ThreadPanel.svelte` (the thread conv in
|
||||
`MessageList`/`Composer`, title, Following, menu, Back/Close), `ThreadsPanel.svelte` (the
|
||||
channel's list), routes `/channels/:server/:channel/threads/:thread` (the app's existing
|
||||
`/channels/...` scheme; the design text says `/servers/...`). `AppShell` docks the panel on
|
||||
desktop (`clamp(20rem, 40%, 26rem)`, in the member list's slot) and puts it full screen with
|
||||
the channel `inert` below 1024 px. `MessageItem` has the badge, the Start/Open thread tool and
|
||||
the T key; `MessageList` takes an `intro` (the thread's parent) and `onThread`; `Composer`
|
||||
takes `inputId` (`thread-composer-input`); `ChannelList` shows the followed-thread dot.
|
||||
E2E: `e2e/tests/threads.spec.ts` (M25-01..06, including the M25-05 seeded-thread regression
|
||||
across every channel endpoint, the 0.4.1 history query on the e2e data, and the start limit
|
||||
on the RATE_LIMIT and `RATE_LIMIT=false` instances) and an M25-02 case in `push.spec.ts`.
|
||||
QA-133: the open thread's parent uses the same `blocks.has` check as a channel quote, so it
|
||||
reads "Blocked message" as soon as you block its author (after a reload the server omits the
|
||||
parent, so it reads as deleted). QA-134: M25-02 waits for `push-devices` to show
|
||||
"(this device)" after the checkbox, the same wait M12 already uses, so the subscription is
|
||||
saved before the test triggers a push.
|
||||
- M24 custom emoji (D27, D28): `packages/shared/src/custom-emoji.ts` (limits, name rule, token
|
||||
and `c:<id>` helpers), media kind `emoji` (`aspect 1`, sizes 64 and 128, `maxMb 0.25`; a size
|
||||
under 1 MB is reported in KB). Server: `services/emoji.ts` and `routes/emoji.ts`
|
||||
(`GET/POST /api/servers/:id/emoji`, `PATCH/DELETE /api/emoji/:id`); the upload is the shared
|
||||
multipart pipeline with one extra `name` field (`receiveCroppedImage(..., ['name'])`), checked
|
||||
for membership, the rate limit and the cap before the body is read and again in the insert
|
||||
transaction. Reactions: `emojiSchema` takes `c:<ULID>`; `MessageService.react` checks the emoji
|
||||
exists and the reactor is a member of its server (`400 unknown_emoji`); `ReactionDto` carries
|
||||
the emoji's `name` while it exists; `dropReactionsIn` deletes and announces. Deleting a server
|
||||
removes its emoji images and the reactions that used them. Push notifications show `:name:`.
|
||||
Uses migration 010's `custom_emoji` table as it is. Client: `stores/emoji.svelte.ts`,
|
||||
`lib/custom-emoji.ts` (`:name:` <-> token outside code), `Inline` type `emoji` in
|
||||
`markdown.ts`, `EmojiPicker.svelte` (category bar, `onPick(emoji, custom?)`),
|
||||
`ServerEmojiSettings.svelte`. Tests: `apps/server/test/emoji.routes.test.ts`,
|
||||
`packages/shared/src/custom-emoji.test.ts`, `apps/web/src/lib/custom-emoji.test.ts`; e2e
|
||||
`emoji.spec.ts` (M24-01 to M24-07).
|
||||
- Drafts live in the module-level `apps/web/src/lib/stores/drafts.ts` (a `Map` keyed by
|
||||
conversation id, with `get`, `set` and `clear()`), not in `Composer.svelte`. It is backed by
|
||||
`sessionStorage` under one key per user, `doghouse:drafts:<userId>`: loaded once at login,
|
||||
written at most every 500 ms while typing and whenever the page is hidden (`visibilitychange` to hidden, which phones send when an app is backgrounded, and `pagehide`), never synced between tabs (nothing listens for `storage` events), every draft stored in full, never cut down, even one over the message limit (`MAX_MESSAGE_LENGTH`, 4,000; QA-106: the composer still blocks sending it). An unreadable value is dropped and a write over the quota is skipped (the draft
|
||||
stays in memory). The composer reads its draft when it mounts and when `conv.id` changes (the
|
||||
0.4.1 `swapDraft` guard, QA-102, stays) and writes it back as you type, when the id changes and
|
||||
when it is destroyed. `auth.logout()` calls `drafts.clear()`, which removes every
|
||||
`doghouse:drafts:*` key and ends the composer's session, so a composer torn down after the
|
||||
logout can't write its text back. QA-108: the session ending on the server does the same:
|
||||
`api()` reports a 401 whose body code is `SESSION_REQUIRED` (`'unauthorized'`, from
|
||||
`@chat/shared`; the only code `requireAuth` sends) from any call except login, register and
|
||||
logout (`onSessionLost` in `lib/api.ts`), and the socket reports a refused connection
|
||||
(`connect_error` with that message). D31: either report then makes one `GET /api/auth/me`, and
|
||||
only `{ user: null }` ends the session and wipes the drafts; a network error, a 5xx, a user, or
|
||||
any other answer leaves both alone, and 401s that arrive together share one pending check
|
||||
(`reportSessionLost` in `lib/api.ts`). Every other 401 has its own code and is an ordinary error:
|
||||
a wrong password at login is now `401 invalid_credentials` (it was `unauthorized`; a 0.4.1
|
||||
page only shows the message, which is unchanged), and the LiveKit webhook's `401 bad_signature`
|
||||
only ever goes to LiveKit. Tests: `api.test.ts` (each non-session 401 keeps the session; each `/me` answer; one shared check),
|
||||
`apps/server/test/session-401.test.ts` (every protected route's 401 code, the login and webhook
|
||||
codes), and e2e `drafts.spec.ts` "QA-108 follow-up" (a 401 `invalid_credentials` from Settings
|
||||
keeps you logged in with your drafts; the same call with the session code keeps you logged in while
|
||||
`/me` still returns you, with one check, and logs out once `/me` answers `{ user: null }`). There is no
|
||||
change-password form in 0.5, so that e2e answers the account Save with the wrong-password 401.
|
||||
- Search rebuild and the start-up check (D30, D32, QA-111): `apps/server/src/db/search-index.ts`.
|
||||
`messages.id` is a TEXT primary key (ULIDs), so the FTS index joins on the implicit rowid, which
|
||||
a dump and restore, `.recover`, a table rebuild or VACUUM on another SQLite build can renumber.
|
||||
Migration 010 adds `search_rowids(rowid INTEGER PRIMARY KEY, message_id)`, kept in step by the
|
||||
same three triggers as `messages_fts` and filled by the same backfill. At every start
|
||||
(`buildApp`, after migrations) `checkSearchIndex` looks for any `search_rowids` row whose
|
||||
`messages` row (by rowid) is missing, has another id or is no longer searchable, then compares
|
||||
the counts of searchable messages, `search_rowids` and `messages_fts_docsize`; on any
|
||||
difference `rebuildSearchIndex` (the same `delete-all` plus `INSERT ... SELECT` as the backfill,
|
||||
for both tables, one transaction) runs and one warning line is logged. The check is about 20 ms
|
||||
for 100,000 messages. The script `apps/server/src/scripts/rebuild-search.ts`, built to
|
||||
`dist/scripts/rebuild-search.js` (in the image and the zip), runs the rebuild by hand; it opens
|
||||
`DB_PATH`, or `DATA_DIR/chat.db`, like the server. Every search filter (scope, membership,
|
||||
blocks, type, deleted) still reads the joined `messages` row. Tests:
|
||||
`apps/server/test/search-startup-check.test.ts` (a channel deleted and the rows renumbered as a
|
||||
dump and restore would; a rowid swap plus a reordered rebuild that keep count, sum and max; a
|
||||
missing pair; the triggers through edit, delete and cascades; the 100,000-row timing),
|
||||
`search-index-check.test.ts` (the same through a real restart on a database file: words only in
|
||||
a DM the reader isn't in give 0 results, real results are exact; the 0.4.1 upgrade fills
|
||||
`search_rowids`; the timings below), `search-rebuild.test.ts` (the command, and the worst-case
|
||||
shift without a restart), and
|
||||
`search.test.ts` (snippets are text, the `<mark>`s come only from the markers).
|
||||
- 0.5-dev databases (QA-126): delete any database made by a 0.5 development build before this
|
||||
release (for example before commit 1211228 it has no `search_rowids` and won't start); only
|
||||
databases from released versions are upgraded.
|
||||
- D36 (QA-127, QA-128): `apps/server/src/db/thread-pins.ts` `relocateThreadPins()` runs at every
|
||||
start (`buildApp`, next to `relocateEmoji()`): one `UPDATE pins` moves pins whose message is a
|
||||
thread reply to the thread's `conv_id` and logs one line when it moved any; moved pins don't
|
||||
count against the 50 (the cap only applies to new pins). `threadNameFor()` in
|
||||
`packages/shared` gives `THREAD_NAME_HIDDEN` ("Thread") for a reader who blocked the thread's
|
||||
starter or its parent's author; the server applies it in `ThreadService` (list, get, follow),
|
||||
the parent badge (`threadSummaries`), search `threadName` and push titles, and the web applies
|
||||
it to room events (`createdBy`, `parentAuthorId`) and on a live block. Tests:
|
||||
`thread-pins.test.ts`, `threads.blocked-names.test.ts`, `threads.push.test.ts`, threads.spec
|
||||
M25-03.
|
||||
- D34 fix pass (QA-119 to QA-123):
|
||||
- QA-120: `MediaService` writes kind `emoji` to `MEDIA_DIR/emoji/<mediaId>/<size>.webp`;
|
||||
`filePath()` looks in `MEDIA_DIR/<id>` then `MEDIA_DIR/emoji/<id>`, `remove()` and `exists()`
|
||||
cover both, and `sweep()` sweeps top-level media ids and `emoji/<id>` (the `emoji` folder
|
||||
itself is not a media id, so neither 0.5's nor 0.4.1's sweep removes it). `relocateEmoji()`
|
||||
moves emoji folders a pre-release 0.5 build left at the top level, once, at start. Tests:
|
||||
`media.test.ts` (layout, lookup order, remove, sweep, a copy of 0.4.1's sweep on 2-hour-old
|
||||
emoji, relocation) and `emoji.routes.test.ts` (served from the new place, emoji and server
|
||||
delete remove the folder, 0.4.1's sweep then re-upgrade serves the same bytes).
|
||||
- QA-121: `MessageList`'s load effect tracks only `conv.id` (`untrack()` around the loads); a
|
||||
failed first page shows "Couldn't load messages" with a Retry button (44 px). Tests:
|
||||
`stores/messages-load-retry.test.ts`, e2e `history-retry.spec.ts` (500 and 401, desktop and
|
||||
phone: one request in 2.5 s, Retry once more, then loads).
|
||||
- QA-112: `ChatPane`'s `.chat` is a size container (`chathead`); the header tiers (under 600 px:
|
||||
search icon, no gaps, no topic; under 480 px: no group avatar button; under 360 px: DM menu)
|
||||
and SearchBar's icon mode follow the chat's width instead of the window's. The search field
|
||||
keeps at least 8rem. e2e `header-fit.spec.ts` checks 21 widths from 320 to 1024 px.
|
||||
- QA-119: `lib/emoji-picker.ts` (`currentServerFirst`, `matchCustom`, `customResultLabel`);
|
||||
`EmojiPicker` takes `serverId`. Tests: `emoji-picker.test.ts`, e2e `emoji.spec.ts` "QA-119".
|
||||
- QA-122/123: `openExistingDb()` (`fileMustExist`, needs a `messages` table, no `mkdir`) and
|
||||
`rebuildSearchCommand()` in `db/rebuild-command.ts`; `rebuildSearchIndex` uses
|
||||
`.immediate()`. Tests: `search-rebuild-command.test.ts` (missing file, foreign file, another
|
||||
writer holding the lock in a worker thread) and `search-rebuild.test.ts` (the built script
|
||||
with a wrong `DATA_DIR`: exit 1, nothing created).
|
||||
- QA-116: migration 010 also adds `idx_messages_reply_to` (partial, `reply_to_id IS NOT NULL`).
|
||||
Deleting a message nulls `reply_to_id` on its replies (`ON DELETE SET NULL`), which was a full
|
||||
scan of `messages` per deleted message; deleting a 7,500-message channel among 100,000 messages
|
||||
now takes about 80 to 150 ms (`search-startup-check.test.ts`, `search-index-check.test.ts`; the
|
||||
same delete without the index is shown for comparison).
|
||||
- QA-108 (continued): after the `/me` check confirms it, the auth store runs the same teardown as Log out (`endSession()`) and shows a notice on the
|
||||
login screen. A page load with no session also clears the stored drafts. Unit tests
|
||||
`stores/drafts.test.ts`, `draft.test.ts` and `api.test.ts`; e2e `drafts.spec.ts` (the two "0.5
|
||||
drafts" tests: server and Home at desktop and phone size, several chats, reload, new tab, logout
|
||||
and the next account; and QA-106/QA-108: an over-long draft after a reload, and an expired
|
||||
session both while the page is open and across a reload).
|
||||
- QA-105: `apps/server/test/deps-floors.test.ts` checks the `@fastify/static` floor and that the
|
||||
lockfile installs no production glob or minimatch inside the advisory ranges. The bump also
|
||||
moves glob 13 -> 14, minimatch 10 -> 11, path-scurry 2 -> 3 and @fastify/send 4.1 -> 4.2 inside
|
||||
`@fastify/static`'s own tree, and adds `@isaacs/nonrecursive-glob-match` (BlueOak-1.0.0, the
|
||||
same licence as glob); all of them need Node 20 or 22+, which the Docker image (node:22) and
|
||||
`engines` (>=20.19) already meet.
|
||||
- QA-88 (D24): `themeStore.applyRemote` keeps the newest `theme:update` it skips while the tab
|
||||
holds an unconfirmed change, and `saved()` shows it when its `themeUpdatedAt` is later than the
|
||||
reply's (both server-stamped; `isLater`). That is the only theme-saving change in 0.5. Unit tests
|
||||
in `theme-store.test.ts`; e2e `themes.spec.ts` "QA-88 (D24)" (5 rounds with the reply held,
|
||||
checking every painted theme; it fails on the 0.4.1 store).
|
||||
- QA-101: `CallService` takes the limit flag from `config.rateLimit.enabled` (`starts` is null when
|
||||
off), and the 429 carries `Retry-After`. Unit tests in `calls.test.ts`; e2e
|
||||
`call-limits.spec.ts`. The e2e's second instance (`NOVIDEO_URL`) now runs with
|
||||
`RATE_LIMIT=false` (`E2E_RATE_LIMIT` in `e2e/server.mjs`) for that check.
|
||||
- D10: `POST /api/dms/:dmId/call/token` without `callId` is `400 call_id_required` (after the
|
||||
membership check, so a non-member still gets 404); the current-call fallback and its debug line
|
||||
are gone. Unit tests in `calls.test.ts` and `blocks.test.ts`; e2e `call-limits.spec.ts`.
|
||||
- QA-80, QA-90: two new per-user CSS variables from `themeVariables` (`lib/theme/theme.ts`):
|
||||
`--selected-text` (the accent as text, moved only as far as needed to reach the target on the
|
||||
surfaces, on `--hover` and `--selected` over them, and on the 22% accent mention chip) and
|
||||
`--selected-muted` (muted text on those rows). Every rule that paints `--hover` or `--selected`
|
||||
sets `--accent-text: var(--selected-text)` and `--text-muted: var(--selected-muted)` for its
|
||||
contents, and the preview mention uses `--selected-text`. Helpers `compositeOver`,
|
||||
`rowBackgrounds` and `readableOn` in `contrast.ts`. Unit tests in `contrast.test.ts` (every
|
||||
preset, 16 accents) and `theme.test.ts`; e2e `themes.spec.ts` "QA-80 and QA-90 in Chrome"
|
||||
measures the rendered colours.
|
||||
- High contrast buttons: `--accent` (the fill) is lightened in OKLCH until black text on it reaches
|
||||
7:1 (`palette.buttonAdjusted`), `--on-accent` follows; accent text stays the preset's yellow.
|
||||
QA-110: `--focus-ring` in High contrast is lightened the same way to 7:1 against black, the
|
||||
surfaces and hovered or selected rows (other presets keep 3:1, QA-3); `theme.test.ts` and the
|
||||
QA-80/QA-90 test in `themes.spec.ts` check it.
|
||||
- QA-96, QA-98: `apps/server/test/docs-commands.test.ts` runs the README's backup and rename
|
||||
commands as written, twice on the same day (a stand-in `date`), and checks that both backups and
|
||||
both rollback folders exist, nothing is nested and `data` is cleared. It also checks the QA-97,
|
||||
QA-99 and QA-100 wording.
|
||||
- D22: `npm run package` writes `build.json` at the zip root from git only: `commit` is the first
|
||||
10 characters of `git rev-parse HEAD` (fixed, never `--short`), `commitDate` is `%ct` as UTC
|
||||
with a Z. It is built in memory after the dirty-tree check, so a refused run leaves nothing
|
||||
behind. The server reads it once at start (`apps/server/src/lib/build-info.ts`), else asks git
|
||||
with the same rules, else reports `commit: "dev"`. `deploy/Dockerfile` copies it into the image
|
||||
(optional, so a checkout still builds). Tests: `build-info.test.ts` (both copies of the rules
|
||||
agree, TZ makes no difference, DOS times are UTC, fallbacks), `build-info.test.ts` in the web
|
||||
app, and the M21-11 e2e in `pwa.spec.ts`.
|
||||
- D22: development zip names use the same 10-character build hash as `build.json`
|
||||
(`doghouse-<version>.<hash>.zip`), not `git rev-parse --short=7`, which can grow;
|
||||
`scripts/package-name.mjs` takes it from `scripts/build-info.mjs` and `package-name.test.ts`
|
||||
checks it matches `build.json`'s `commit`.
|
||||
- Migration `010_search_emoji_threads.sql` (DESIGN-0.5 sections 0, 2a, 3a, 4a; D25, D26, D27):
|
||||
`threads` (+ `idx_threads_channel`, not in the design text, for "a channel's threads" and the
|
||||
cascade), `thread_follows`, `messages.thread_id` with `idx_messages_thread` and
|
||||
`idx_messages_channel_main`, `custom_emoji`, and the external-content FTS5 table
|
||||
`messages_fts` (`unicode61 remove_diacritics 2`) with insert, update-of-content-or-deleted_at
|
||||
and delete triggers that share one condition (`type = 'default' AND deleted_at IS NULL`). The
|
||||
backfill is an `INSERT ... SELECT` with that condition, after a `'delete-all'` so a re-applied
|
||||
migration doesn't index twice. Tests: `upgrade.test.ts` (010 on the 0.1.2 fixture: no old row
|
||||
changes, backfill exact, re-apply harmless, the 0.4.1 migration set has nothing to do and
|
||||
0.4.1-style inserts, edits and soft deletes keep the index in step) and
|
||||
`search-backfill.test.ts` (M23-08: 100,000 mixed rows, timed, deleted and system rows left
|
||||
out). Note: FTS5's `integrity-check` must be run with rank 0 here, because a partial
|
||||
external-content index never matches the whole `messages` table.
|
||||
- Search API (M23, DESIGN-0.5 2b, D26): `GET /api/search` in `routes/search.ts` and
|
||||
`services/search.ts`. The scope is checked first (server: member and not banned; DM: a current
|
||||
member; `in`: a text channel of that server); every failure is one neutral 404 `Nothing to
|
||||
search here`, so the body never says what exists. The FTS5 query comes from
|
||||
`lib/search-query.ts` (`ftsQuery`): each word with a letter or digit becomes one quoted string
|
||||
(quotes doubled), ANDed, `*` on the last; words with no letter or digit are dropped, and nothing
|
||||
left is `400 empty_query`. Filters `from`, `in`, `before`/`after` (instants via `ulidFloor`;
|
||||
`after` inclusive), `has=file` (`EXISTS` on attachments), `has=link` (`LIKE '%://%'`); empty
|
||||
`q` needs a filter. `notBlockedAuthor()` before the LIMIT; newest first, 25 a page, cursor =
|
||||
last id. Each result is `{ message, convId, convName, snippet, threadId?, threadName? }`;
|
||||
`snippet` is `snippet(…, U+0002, U+0003, '…', 12)` text, null without search text. 30 a minute
|
||||
per person (`429 too_many_searches` with Retry-After, off with `RATE_LIMIT=false`); a 400 or
|
||||
404 doesn't count. Tests: `search-query.test.ts` and `search.routes.test.ts` (M23-01 to
|
||||
M23-07, M23-09). The markers are C0 controls on purpose: `cleanMessageText` strips them on
|
||||
every write, so a message can't fake a highlight.
|
||||
- Search UI (M23, DESIGN-0.5 2c): `lib/search.ts` (pure: filter tokens, `from:`/`in:`
|
||||
suggestions, `extractFilters`, `searchParams` with local days as UTC instants, and
|
||||
`highlightSegments`, which splits the snippet into text segments, rendered as text with
|
||||
`<mark>`, never `{@html}`), `lib/stores/search.svelte.ts` (scope, text, chips, results, a
|
||||
sequence guard against stale responses; cleared on logout and when the scope changes),
|
||||
`SearchBar.svelte` (combobox field with a listbox; Enter/Tab pick, Esc closes suggestions then
|
||||
the phone bar, Backspace on an empty field removes the last chip) and `SearchPanel.svelte` (in
|
||||
the `Modal` slot Pins uses, with the new `fullOnPhone`). Jump in the same conversation calls
|
||||
`MessageList.jumpTo`; to another channel it leaves the id in `lib/stores/jump.ts` and navigates,
|
||||
and `MessageList` takes it instead of loading the latest page. `.chat-header` is now
|
||||
`position: relative` (the phone bar covers it). Tests: `search.test.ts` (unit) and
|
||||
`e2e/tests/search.spec.ts` (M23-01 to M23-07, M23-09, M23-10, screenshots in `shots/m23`).
|
||||
@@ -0,0 +1,201 @@
|
||||
# Doghouse 0.6.0
|
||||
|
||||
Custom roles and channel permissions (with private and read-only channels) and statuses (Online,
|
||||
Idle, Do not disturb, Invisible, custom text that can clear itself), on top of 0.5.0, plus
|
||||
housekeeping (the app image is tagged with the version), a security fix for 0.5.0 and earlier,
|
||||
and the fixes listed below. One additive database migration, `011_roles_status.sql`, applied
|
||||
automatically on start. No new settings and no new ports.
|
||||
|
||||
**Right before you upgrade, back up the data folder (`deploy/data`) and `.env`. Database
|
||||
migrations can't be undone: going back to 0.5.0 needs that backup, and restoring it loses anything
|
||||
posted after the backup was made.** See "Upgrading to 0.6.0 and rolling
|
||||
back" below.
|
||||
|
||||
## New: custom roles and channel permissions (M28, M29)
|
||||
- Server settings has a **Roles** tab for owners, admins and anyone with Manage roles: create a
|
||||
role, name it (up to 32 characters), give it a colour and pick what it allows (view channels,
|
||||
send messages, send in threads, add reactions, pin messages, manage messages, add emoji,
|
||||
manage emoji, manage channels, manage roles). Up to 50 roles per server, plus `@everyone`.
|
||||
- Every server has `@everyone`, the role all members have. On upgrade it gets exactly what
|
||||
members could do in 0.5.0 (view, send, threads, reactions, pins, adding emoji), so nothing
|
||||
changes for anyone until you change it. `@everyone` can't be renamed or deleted.
|
||||
- Roles are ordered; reorder them with the up and down buttons (keyboard friendly). The
|
||||
owner and admins sit above every role and keep every permission, so nobody can lock out the
|
||||
owner. Someone with Manage roles can only edit, assign or reorder roles below their own top
|
||||
role, and only hand out permissions they have themselves.
|
||||
- Members: Server settings > Members assigns roles. A member's name takes the colour of their
|
||||
highest coloured role in chat, the member list and mentions (High contrast keeps names in the
|
||||
normal text colour; a colour too dark for the theme falls back to the text colour). The member
|
||||
list groups online members under their highest role.
|
||||
- **Channel permissions** tab: for each channel, allow or deny bits for `@everyone` and for
|
||||
roles, on top of the server-wide role permissions. Saving a change that would take a
|
||||
permission away from you asks first ("You won't be able to undo this yourself; an owner or
|
||||
admin would have to"); a change that would give you a permission you don't have is refused.
|
||||
The Roles tab asks the same before a save or delete that lowers your own permissions.
|
||||
- Kick, ban, promoting to admin and transferring ownership work exactly as before (by rank).
|
||||
|
||||
## New: private and read-only channels (M29)
|
||||
- Deny View channels to `@everyone` (and allow it to a role) and the channel is private: people
|
||||
who can't see it don't get it in the channel list, its history, pins, threads, search results,
|
||||
unread counts, notifications, voice participants or member list, and it doesn't leak through
|
||||
live updates either. Taking someone's access away drops the channel (and a voice call in it)
|
||||
for them at once, without a reload.
|
||||
- **Admins and the owner see every private channel** (as Discord's Administrator does). A
|
||||
private channel hides from members, not from admins.
|
||||
- Deny Send messages and the channel is read-only for those people: the composer says "You can't
|
||||
send messages here." instead of offering a text box.
|
||||
|
||||
## New: statuses (M30)
|
||||
- Open the status menu in the user panel (bottom left, "Set status") to pick Online, Idle, Do
|
||||
not disturb or Invisible.
|
||||
- **Auto-idle:** after 10 minutes with no input in any of your tabs (a hidden tab counts as idle
|
||||
10 minutes after its last input), others see you as Idle; you're Online again as soon as you're
|
||||
back. A status you picked yourself is never changed for you.
|
||||
- **Do not disturb:** no push notifications for messages, mentions or incoming calls and no ring
|
||||
sound (incoming calls still show the ring card), on top of the existing notification settings
|
||||
and quiet hours.
|
||||
- **Invisible:** everyone else sees you exactly as offline (member list, online count, profile,
|
||||
typing), while you can carry on as normal.
|
||||
- **Custom status:** "Set custom status…" in the same menu: up to 128 characters (a live
|
||||
counter shows how many; the app and the server count them the same way) and an optional emoji, cleared after 30 minutes, 1 hour,
|
||||
4 hours, at the end of today, or never. It shows in the user panel, the member list and the
|
||||
profile card, to people who share a server or DM with you, not while you're offline or
|
||||
Invisible, and never between people who have blocked each other. Text that has expired goes
|
||||
away by itself, also if the server was off when it expired.
|
||||
|
||||
## Housekeeping
|
||||
|
||||
### Docker image is tagged with the version
|
||||
- `deploy/docker-compose.yml` now uses `image: doghouse-app:<version>` (`doghouse-app:0.6.0` in
|
||||
the release) instead of `doghouse-app:local`. A plain `docker compose up -d` builds the image the first time (the
|
||||
compose file has a `build:` section) and reuses it after that, so a new release can't start on
|
||||
the previous release's image because `--build` was forgotten. That is what made Settings show
|
||||
0.4.0 after a 0.5.0 upgrade done without `--build`. `up -d --build` still works and rebuilds.
|
||||
- A release check keeps the tag honest: `npm run check` (through `validate:deploy`), the
|
||||
packager and the package-files test all fail if the compose image isn't exactly
|
||||
`doghouse-app:<package.json version>`. When you bump the version in package.json, also bump
|
||||
the compose image tag to `doghouse-app:<version>` in the same change.
|
||||
- The app service has `pull_policy: never`: a missing image is built straight away, with no
|
||||
attempt to pull `doghouse-app` from a registry and no "pull access denied" warning (QA-140).
|
||||
- Development zips (`doghouse-<version>.<hash>.zip`) tag their image
|
||||
`doghouse-app:<version>-<hash>`, written into the zip's compose file by the packager, so each
|
||||
milestone zip builds its own image on a plain `up -d` even though the version hasn't changed
|
||||
(QA-141). Release zips keep `doghouse-app:<version>`.
|
||||
- Older images stay on the machine under their own tag until you remove them
|
||||
(`docker image rm doghouse-app:<version>`).
|
||||
- Tested on a real Docker daemon: a plain `up -d` built the missing tag, a second `up -d` rebuilt
|
||||
nothing, and a version bump built and started the new tag while the old tag stayed.
|
||||
|
||||
## Security
|
||||
- **0.5.0 and earlier:** the cross-origin check on state-changing requests (and, in 0.6 builds
|
||||
before this fix, the "don't cache" header on API answers) could be skipped by writing the path
|
||||
with percent-escapes, for example `/%61pi/...` for `/api/...` (QA-163, Medium). A page on a
|
||||
sibling subdomain could, for example, make a logged-in user join a server. SameSite cookies
|
||||
already stopped other sites. Now every POST, PUT, PATCH and DELETE is checked whatever its
|
||||
path, a request with no Origin header is accepted only from the page itself or from
|
||||
non-browser clients (a sibling subdomain is refused), and every JSON answer is marked
|
||||
`Cache-Control: no-store` unless it is a static file.
|
||||
|
||||
## Fixes
|
||||
- After you unblock someone, thread names (and the parent message in an open thread) come back
|
||||
without a reload. Before, a thread you had loaded while they were blocked kept the neutral
|
||||
name "Thread" until you reloaded (a 0.5.0 leftover).
|
||||
- The old 0.4.1 "pinned a message" line, for a reply that has since moved into a thread, now
|
||||
opens that thread at the reply instead of saying "That message isn't available any more"
|
||||
(QA-135). A deleted message still says so.
|
||||
- `GET /api/messages/:id` now answers "not found" for a message by someone you blocked, like the
|
||||
history, jump and pins routes do (QA-137). Nothing in the app showed it before.
|
||||
- A tab that gets a "session needed" answer and finds another account logged in (another tab
|
||||
switched accounts) now ends its session and shows the login screen, instead of carrying on as
|
||||
that account (QA-124). The same check runs when the tab is focused or becomes visible again,
|
||||
so a cookie swapped to another valid account is caught without waiting for a 401.
|
||||
- The emoji picker is one Tab stop; the arrow keys move between emoji, and Tab leaves the grid
|
||||
in one press instead of walking through all of them (QA-125).
|
||||
- The server rail's divider no longer trips the accessibility checker's "list" rule (QA-125).
|
||||
- Every name (display names, custom status, server, channel, role and device names) refuses text
|
||||
that shows nothing, such as only zero-width spaces, a Braille blank or Hangul fillers (QA-162),
|
||||
while emoji keep every part, for example ❤️ at the end, 🏳️⚧️, keycaps and the Scotland, England
|
||||
and Wales flags (QA-168).
|
||||
- Text channel names keep accents and vowel signs: "नमस्ते" and "สวัสดี" are no longer cut down
|
||||
(QA-170, a bug since 0.5.0 or earlier). Existing channel names are not changed.
|
||||
- Display-name changes are rate limited like custom status (10 in 10 seconds per person); theme
|
||||
saves are not (QA-166, QA-167).
|
||||
- Accessibility: confirmations describe themselves to screen readers and start on Cancel when
|
||||
they delete or can't be undone (QA-159); after a role save focus returns to Save, and after
|
||||
revoking an invite it moves to the next one (QA-165); the custom status dialog starts in its
|
||||
text field; danger buttons on hovered rows (QA-160) and the hovered thread badge (QA-169) reach
|
||||
4.5:1 in every theme.
|
||||
- Every API answer that is JSON is marked `Cache-Control: no-store`, so a shared browser or proxy
|
||||
never keeps a copy (QA-161).
|
||||
|
||||
## Upgrading to 0.6.0 and rolling back
|
||||
**Back up the data folder and `.env` right before you upgrade, not the night before. Migration 011 can't be undone, so the
|
||||
way back to 0.5.0 is that backup: anything done on 0.6.0 after the upgrade is lost.**
|
||||
- From 0.5.0: follow "Upgrading 0.5.0 -> 0.6.0" in the README (back up, unzip
|
||||
`doghouse-0.6.0.zip`, copy `.env` and move `data` across, `docker compose up -d --build`).
|
||||
Settings > App and notifications > About and `/api/health` then show `0.6.0`.
|
||||
- From 0.4.x or 0.3.x: the same steps, reading your folder name for `doghouse-0.5.0`. 0.6.0
|
||||
includes every earlier fix, and the migrations in between run on start, in order. The way back
|
||||
is the backup you made, as below.
|
||||
- The database (migration `011_roles_status.sql`, the only one in 0.6): it adds roles, member
|
||||
roles and channel permission overrides, plus three columns on users for custom status text.
|
||||
Nothing is rebuilt. Every existing server gets an `@everyone` role with exactly the 0.5.0
|
||||
member rights, so nothing changes for anyone on upgrade. Owners and admins keep every
|
||||
permission through their rank and need no roles. A check at start-up creates `@everyone` for
|
||||
any server that is missing one.
|
||||
- **Rolling back to 0.5.0: restore the backup.** 0.5.0 would start on 0.6 data (it ignores the
|
||||
new tables), **but it has no private channels: every member would see every private channel's
|
||||
history**, read-only channels become writable again, and roles and custom text vanish. So go
|
||||
back with the backup you made before the upgrade (README, step 5), not by moving the 0.6 data
|
||||
back.
|
||||
|
||||
## Real-device checklist
|
||||
The 0.3.0, 0.4.0 and 0.5.0 checklists still apply. New in 0.6:
|
||||
- Docker build on the server: unzip the 0.6.0 package, run `docker compose up -d --build` in its
|
||||
`deploy` folder and wait until `docker compose ps` says healthy. Settings > App and
|
||||
notifications > About and `/api/health` show `0.6.0 (build <10 characters>, <date>)`, and
|
||||
`docker images doghouse-app` lists a `0.6.0` tag.
|
||||
- Voice and TURN: a voice channel call and a screen share between a phone on mobile data and a
|
||||
computer at home (so the media goes through the router's forwarded ports, and TURN on UDP 3478
|
||||
for the phone if its network is strict); both hear each other and see the share.
|
||||
- Push on a phone: with the app installed on the phone and the tab closed, a mention and a DM
|
||||
arrive as notifications; set Do not disturb and they don't; back to Online and they do.
|
||||
- Statuses on two devices: on the phone pick Idle, then Invisible, then set a custom status that
|
||||
clears in 30 minutes; the computer (logged in as someone else) shows Idle, then you as offline
|
||||
with no custom text, then Online again with the text; leave a tab alone for 10 minutes and it
|
||||
shows Idle.
|
||||
- Private channels and role edits: make a role, give it to a second account, make a channel
|
||||
private to that role (deny View for `@everyone`, allow it for the role). The second account
|
||||
sees the channel at once; take the role away and it disappears for them without a reload. A
|
||||
third account never sees it, nor in search. Deny Send for `@everyone` somewhere: the
|
||||
third account sees "You can't send messages here."
|
||||
- Admin view: an admin account sees every private channel (D37), including ones no role allows;
|
||||
the owner sees everything.
|
||||
- **Admin policy (D61):** 0.6.0 ships with `ADMIN_CHANNEL_POLICY = 'all'` (admins see every
|
||||
private channel). The other choice, `'roles'` (admins see only channels their roles allow, but
|
||||
can still fix access because the Channel permissions page lists every channel's name), is
|
||||
built and tested but needs a one-line change in `packages/shared/src/permissions.ts` and a
|
||||
rebuild. Say if you want it.
|
||||
|
||||
## Known limitations (0.7 list)
|
||||
- Custom status text isn't shown in DM list rows (it is in the member list, user panel and
|
||||
profile card).
|
||||
- The custom status dialog loses what you've typed (text, emoji and "Clear after") if your status
|
||||
changes from another tab or device while it's open.
|
||||
- No general per-user write limit: theme saves and some other own-account writes aren't rate
|
||||
limited (as in 0.5.0).
|
||||
- Every custom role is its own group in the member list; a "display separately" option per role
|
||||
comes later.
|
||||
- No category-level permissions: a private category is several private channels.
|
||||
|
||||
## Not fixed in 0.6 (decided)
|
||||
QA-117 (search time cap), the other three QA-125 items (cosmetic), QA-129, QA-130 and QA-136.
|
||||
|
||||
## Developers
|
||||
- `REQUIRE_LIVEKIT=1 npm run check` runs typecheck, lint and all unit tests with nothing skipped:
|
||||
shared 340, server 834, web 1792, 0 failed.
|
||||
- A full e2e run (`REQUIRE_LIVEKIT=1 npm run e2e`) is 136 passed, 122 skipped, 0 failed. All skips
|
||||
follow the skip policy in `CHANGES-0.3.0.md`: desktop-only tests skipped in the phone project
|
||||
and phone-only layout checks skipped in the desktop project.
|
||||
- The release zip carries the notes of every release (`CHANGES-0.1.1.md` to this file and
|
||||
`CHANGES-M6.md`) and `THIRD-PARTY-NOTICES.md`.
|
||||
+209
@@ -0,0 +1,209 @@
|
||||
# Milestone 6 change note (for QA)
|
||||
Author: the developer. Scope: PLAN story 10 (self-hosting), DESIGN build-order step 6, and the
|
||||
decisions-log entries for Nginx Proxy Manager, security headers and invisible users in voice.
|
||||
Also adds the "no silent skips" rule from the decisions log (`REQUIRE_LIVEKIT`) and a 320/375 px pass over the
|
||||
voice UI.
|
||||
|
||||
## Deliverable
|
||||
- **`npm run package`** builds `dist/doghouse-<version>.zip` and a `.sha256` file next to it.
|
||||
The zip's single top folder is `doghouse-<version>/`. It holds:
|
||||
- `README.md`, `CHANGES-M6.md` and `deploy/`.
|
||||
- The source the image is built from: root `package.json`, `package-lock.json`,
|
||||
`tsconfig.base.json`, `.dockerignore`, `packages/shared`, `apps/server`, `apps/web`
|
||||
(sources, configs and `public/`).
|
||||
- Never included: `node_modules`, `dist`, `coverage`, `*.test.ts`, `e2e/`, `qa/`, data,
|
||||
`.env`, `.git`.
|
||||
- **Building on the server:** Justin runs `docker compose up -d --build` in `deploy/`. No
|
||||
prebuilt image and no registry.
|
||||
- **Zip writer:** written in Node, so packaging needs no zip tool. Unix permissions are kept, so
|
||||
`docker-entrypoint.sh` stays executable.
|
||||
|
||||
## deploy/
|
||||
| File | What |
|
||||
|---|---|
|
||||
| `Dockerfile` | Three stages on `node:22-alpine`. **build:** `npm ci` + `npm run build`. **deps:** `npm ci --omit=dev --workspace=apps/server`, so only the server's production deps are installed, as musl binaries. **runtime:** the compiled server, shared and web `dist`, and the prod `node_modules`. Runs as the `node` user, uses `tini`, and has a `HEALTHCHECK` (wget `/api/health`) |
|
||||
| `docker-entrypoint.sh` | Starts as root only to `chown` a fresh `./data` bind mount (Docker creates it root-owned), then `su-exec node`. The app never runs as root |
|
||||
| `docker-compose.yml` | Project `doghouse`. **`doghouse-app`** is built from `..`, takes `env_file: .env`, mounts `./data:/data`, and **publishes no ports**. **`doghouse-livekit`** uses the pinned `livekit/livekit-server:v1.13.9` image (the version e2e tests against), mounts `./livekit.yaml` read-only and publishes `7881/tcp`, `50000-50100/udp` and `3478/udp`. Both containers are on the external network `doghouse_net` with `restart: unless-stopped` |
|
||||
| `livekit.yaml` | Signal port 7880. RTC: TCP 7881, UDP 50000-50100, `use_external_ip: true`. TURN: enabled on UDP 3478, TLS off. Webhook to `http://doghouse-app:3000/api/livekit/webhook`. **No keys in the file** |
|
||||
| `.env.example` | `APP_NAME`, `PUBLIC_URL`, `LIVEKIT_PUBLIC_URL`, `LIVEKIT_TURN_DOMAIN`, `NODE_ENV=production`, `TRUST_PROXY_HOPS=1`, `MAX_UPLOAD_MB=25`, `PRESENCE_GRACE_MS`, `SESSION_TTL_DAYS`, `AUTH_RATE_LIMIT_MAX`, `LOG_LEVEL`. **LiveKit key and secret are empty**, with the command to generate them |
|
||||
| `npm-advanced.conf` | Pasted into NPM's Advanced tab: `client_max_body_size 30m`, and `location /livekit/` to `doghouse-livekit:7880` (prefix stripped, Upgrade/Connection headers, 86400 s timeouts) |
|
||||
| `nginx-raw.conf` | Appendix for plain nginx. A full server block that **overwrites** `X-Forwarded-For`/`X-Real-IP` with `$remote_addr` and covers `/`, `/ws` and `/livekit/` |
|
||||
|
||||
**How keys reach LiveKit:**
|
||||
- `livekit.yaml` can't read env vars, but LiveKit takes every config field from `LIVEKIT_*`
|
||||
env vars.
|
||||
- Compose sets `LIVEKIT_KEYS="${LIVEKIT_API_KEY}: ${LIVEKIT_API_SECRET}"`,
|
||||
`LIVEKIT_WEBHOOK_API_KEY=${LIVEKIT_API_KEY}` and `LIVEKIT_TURN_DOMAIN` from `.env`.
|
||||
- With an empty key, compose refuses to start (`${LIVEKIT_API_SECRET:?…}`), so there are no
|
||||
default keys (TESTPLAN 10).
|
||||
|
||||
**NPM resolves LiveKit per request:** the Advanced block proxies through a variable plus Docker's
|
||||
resolver `127.0.0.11`. So NPM still loads its config when `doghouse-livekit` doesn't exist yet,
|
||||
and that route returns 502 until it does. A literal hostname would make nginx refuse to start.
|
||||
|
||||
**X-Forwarded-For with NPM:** NPM appends to it. With `TRUST_PROXY_HOPS=1` the app uses the
|
||||
rightmost entry, which NPM sets from the real connection. Verified (see "Verified here").
|
||||
|
||||
## App changes
|
||||
- **Security headers come from the app** (`apps/server/src/lib/security.ts`) and are sent on
|
||||
every response; attachments keep their stricter sandbox CSP. The policy:
|
||||
- `default-src 'self'; script-src 'self'` (no inline, no eval).
|
||||
- `style-src 'self' 'unsafe-inline'`: Svelte style attributes and transitions. Styles can't run
|
||||
code.
|
||||
- `img-src 'self' data: blob:; media-src 'self' blob:; font-src 'self'`.
|
||||
- `connect-src 'self'` plus the `wss://` and `https://` origins of `PUBLIC_URL` and
|
||||
`LIVEKIT_PUBLIC_URL`.
|
||||
- `worker-src 'self' blob:; object-src 'none'; base-uri 'self'; form-action 'self';
|
||||
frame-ancestors 'none'`.
|
||||
|
||||
Other headers:
|
||||
- `X-Content-Type-Options: nosniff`.
|
||||
- `Referrer-Policy: same-origin`.
|
||||
- `Permissions-Policy: microphone=(self), display-capture=(self), fullscreen=(self),
|
||||
autoplay=(self), camera=(), geolocation=(), payment=(), usb=()`.
|
||||
- `X-Frame-Options: DENY`.
|
||||
- `Cross-Origin-Opener-Policy: same-origin`.
|
||||
- **CSP fix: zod probed `new Function`.** Zod 4's JIT does this, and the browser logged it as a
|
||||
CSP violation (`script-src blocked eval`) on every page load. The e2e CSP guard caught it.
|
||||
`packages/shared` now sets `z.config({ jitless: true })`. Theme boot was already an external
|
||||
file (`/theme-boot.js`), and a test asserts `index.html` has no inline scripts or handlers.
|
||||
- **`MAX_UPLOAD_MB`** (new, default 25, range 1-1024) is both the default and the **ceiling** for
|
||||
the upload limit, so the proxy's `client_max_body_size` always fits.
|
||||
- Admins can lower it with `PATCH /api/admin/settings`. A value above the ceiling gets 400
|
||||
"at most N MB (MAX_UPLOAD_MB in .env)".
|
||||
- Migration `003` drops the old seeded `max_upload_mb=25` row so the env value applies.
|
||||
- There's no admin UI for this setting; there wasn't one before either.
|
||||
- **Invisible users in voice** (decisions log):
|
||||
- They show in that voice channel's participant list (channel list and voice view), which
|
||||
never had presence dots.
|
||||
- The member list now keeps them in **Offline**, not in the "In voice" group. DMs and presence
|
||||
still show them as offline.
|
||||
- They disappear from voice as soon as they leave.
|
||||
- New test, `socket.test.ts`, "invisible in voice": a server-mate gets `voice:state` with them
|
||||
and still no presence. A user in a different server with no DM gets **no socket event
|
||||
mentioning them at all** (`onAny` capture), nothing in `/api/presence`, and 404 on that
|
||||
server's `/voice`. Leaving empties the channel at once.
|
||||
- **Responsive fix (320 px):** in the channel drawer, a long name next to the LIVE badge pushed
|
||||
the badge past the drawer edge, where it was clipped. The voice-people list now stays inside
|
||||
its row, the name truncates and the flags never shrink.
|
||||
- Checked at 320×640 and 375×812 with 3 people in a call and a screen share: voice view,
|
||||
focused share, and the drawer with the voice bar.
|
||||
- `scrollWidth` equals the viewport width and no element extends past the right edge in any
|
||||
of them. Screenshots were reviewed.
|
||||
|
||||
## Tests and "no silent skips" (decisions log)
|
||||
- **`npm test` = `scripts/test.mjs`:**
|
||||
- Runs Vitest per workspace, then prints a summary table (files, passed, failed, skipped per
|
||||
suite) and **lists every skipped test by name**.
|
||||
- Prints whether `REQUIRE_LIVEKIT` was set, and the server coverage figures.
|
||||
- **New `apps/server/test/livekit.integration.test.ts`:**
|
||||
- Starts the real `livekit-server` binary.
|
||||
- Checks the app's real `RoomServiceClient` calls: the startup rebuild deletes rooms of unknown
|
||||
channels and keeps ours, and a stranger's join leads to a `removeParticipant` whose 404 is
|
||||
ignored.
|
||||
- Deleting a voice channel deletes its room.
|
||||
- **Without the binary**, it is skipped with a warning and listed in the summary.
|
||||
- **With `REQUIRE_LIVEKIT=1`**, it fails with "REQUIRE_LIVEKIT=1 but no livekit-server binary was
|
||||
found…".
|
||||
- **e2e:** with `REQUIRE_LIVEKIT=1` and no binary, `e2e/server.mjs` exits with a clear error and
|
||||
the run fails. The voice spec also throws instead of skipping if voice turns out to be disabled.
|
||||
- **`LIVEKIT_BIN`, if set, is the only path tried.** This makes "missing" testable.
|
||||
- **e2e now runs the production configuration:** `NODE_ENV=production` (strict Origin check)
|
||||
with the full CSP. Every e2e page records `securitypolicyviolation` events and fails on any.
|
||||
This covers the smoke specs, the realtime spec, and voice with a screen share.
|
||||
- **`npm run validate:deploy`** (part of `npm run check`):
|
||||
- Parses all the YAML.
|
||||
- Validates `docker-compose.yml` against the official compose-spec JSON schema (vendored as
|
||||
`scripts/compose-spec.json`) after interpolating `.env.example`.
|
||||
- Enforces the decisions-log rules: container names, no app ports, pinned LiveKit image, exact
|
||||
published ports, external network, volumes, restart policy, no keys in `livekit.yaml` and
|
||||
empty keys in `.env.example`, `client_max_body_size` above `MAX_UPLOAD_MB`, `/livekit/`
|
||||
rewrite plus upgrade headers, XFF overwrite in the raw appendix, and the Dockerfile basics.
|
||||
- Checked that it fails when the app publishes a port or the compose file has an unknown key.
|
||||
|
||||
### Results (all on Node v20.19.2)
|
||||
**`REQUIRE_LIVEKIT=1 npm run check`** at the M6 commit, copied from its summary:
|
||||
```
|
||||
┌─────────┬───────────────────┬───────┬────────┬────────┬─────────┐
|
||||
│ (index) │ suite │ files │ passed │ failed │ skipped │
|
||||
├─────────┼───────────────────┼───────┼────────┼────────┼─────────┤
|
||||
│ 0 │ 'packages/shared' │ 3 │ 22 │ 0 │ 0 │
|
||||
│ 1 │ 'apps/server' │ 14 │ 187 │ 0 │ 0 │
|
||||
│ 2 │ 'apps/web' │ 7 │ 205 │ 0 │ 0 │
|
||||
└─────────┴───────────────────┴───────┴────────┴────────┴─────────┘
|
||||
Skipped tests: 0
|
||||
REQUIRE_LIVEKIT=1
|
||||
Server coverage: statements 98.12%, branches 92.35%, functions 99.29%, lines 99.19%
|
||||
```
|
||||
(The coverage line is Vitest's `coverage-summary.json` for `apps/server`, which is the same as
|
||||
the "All files" row.)
|
||||
|
||||
**About the M5 coverage figure** (QA measured 96.6% statements, my M5 report said 97.6%):
|
||||
- A fresh `cd apps/server && npx vitest run --coverage` on a clean checkout of `5c8f45b` gives
|
||||
`All files | 97.62 | 91.76 | 98.09 | 98.62` (180 tests, 0 skipped).
|
||||
- At M5 no server test depended on LiveKit (they all used a fake), so skipping can't explain a
|
||||
1-point gap then. I couldn't reproduce 96.6%. QA-REPORT records **181** server tests for
|
||||
the QA run against 180 at `5c8f45b`, so that tree had something extra (perhaps a local probe
|
||||
test), and that's the likeliest cause. A different Node version (V8 counts coverage slightly
|
||||
differently) is the other candidate.
|
||||
- From M6 on, skipping **does** matter. Without the binary
|
||||
(`LIVEKIT_BIN=/nope npx vitest run --coverage`) the run shows 186 passed, 1 skipped, and
|
||||
`All files | 97.66 | 91.84 | 98.12 | 98.65`, because `defaultLivekitApi` in `app.ts`
|
||||
(lines 65-72) is then never exercised. So quote coverage from `REQUIRE_LIVEKIT=1` runs.
|
||||
|
||||
**e2e:** `REQUIRE_LIVEKIT=1 npm run e2e`, run twice in full: both times 10 passed, 4 skipped (the multi-user specs only run in the desktop project, by design, including voice), 0 failed.
|
||||
`LIVEKIT_BIN=/nope REQUIRE_LIVEKIT=1` fails as intended: `[WebServer] e2e: REQUIRE_LIVEKIT=1 but no livekit-server binary was found …`, then `Process from config.webServer was not able to start. Exit code: 1`.
|
||||
|
||||
## Verified here (no Docker on this machine)
|
||||
- **Alpine/musl runtime, built from the zip.** The zip was unpacked into an **Alpine 3.22
|
||||
root filesystem with Node 22.23.2 and npm 11** (the same musl/Node base as `node:22-alpine`),
|
||||
run with `bwrap`. Inside it:
|
||||
- The Dockerfile's commands were repeated by hand: `npm ci` + `npm run build`, then
|
||||
`npm ci --omit=dev --workspace=apps/server`, giving 157 packages.
|
||||
- `sharp` loads its musl build (libvips 8.18.7), `better-sqlite3` uses its musl prebuild
|
||||
(SQLite 3.53.0) and `@node-rs/argon2` hashes with its musl binary. This closes QA's
|
||||
"sharp Alpine build" item, short of the real image.
|
||||
- **Production stack behind an NPM-like nginx.** The production app from that tree (as a
|
||||
non-root uid, `NODE_ENV=production`) ran behind **nginx 1.28 configured like an NPM proxy
|
||||
host** (Websockets on, XFF appended, our `npm-advanced.conf` included). LiveKit 1.13.9 ran
|
||||
with **`deploy/livekit.yaml`**, with keys, webhook key and TURN domain passed **only through
|
||||
the env vars compose sets**. Results:
|
||||
- The **e2e realtime and voice specs pass through nginx**: join, speaking, mute and deafen,
|
||||
screen share received, kick. Webhooks arrive signed with the env-provided key, and there
|
||||
were no CSP violations.
|
||||
- Headers are present on every response.
|
||||
- The QA-1 spoof check passes: 12 logins with forged `X-Forwarded-For` values still hit the
|
||||
per-IP limit (10 × 401, then 429).
|
||||
- A cross-origin POST gets 403.
|
||||
- A 31 MB upload is rejected by nginx with 413 (`client_max_body_size 30m`).
|
||||
- `/livekit/` answers `OK` through the proxy, and 502 (nginx still running) while LiveKit is
|
||||
down.
|
||||
- `nginx -t` passes for `nginx-raw.conf` (syntax OK; binding to 80/443 isn't possible here
|
||||
without root).
|
||||
- The zip passes `unzip -t`. Its listing contains no `node_modules`, `dist`, tests, `.env`, data
|
||||
or `.git`, and `docker-entrypoint.sh` keeps mode 755.
|
||||
|
||||
## Not verified (needs a machine with Docker; for QA's step 6)
|
||||
- `docker compose config` and a real `docker compose build` / `up`. Checks to make there:
|
||||
- The image's `HEALTHCHECK` turns healthy.
|
||||
- The entrypoint's `chown` + `su-exec` on a fresh `./data`.
|
||||
- `tini` signal handling (`docker compose stop` should be quick).
|
||||
- Data survives `down && up`.
|
||||
- The real `livekit/livekit-server:v1.13.9` image. It was tested only as the same-version
|
||||
binary. Two things to confirm: its entrypoint accepts `--config` and `generate-keys` (README
|
||||
step 4), and `use_external_ip: true` finds the public IP. **On this machine STUN is blocked,
|
||||
and LiveKit then hangs at startup without logging anything.** The README's troubleshooting
|
||||
covers this: set `node_ip` instead.
|
||||
- Nginx Proxy Manager itself (only an equivalent nginx config was tested): the Advanced-tab
|
||||
`location` merging, Let's Encrypt, Force SSL, HTTP/2 and HSTS.
|
||||
- TURN relaying from outside, router forwards, and real phones (iOS audio after tapping Join is
|
||||
still a manual item from M5).
|
||||
- arm64 (e.g. a Raspberry Pi). Prebuilt musl arm64 packages exist for sharp and argon2, and the
|
||||
Dockerfile includes `g++` as a fallback for better-sqlite3, but none of this was tried.
|
||||
|
||||
## Known gaps / notes
|
||||
- The root `package.json` version is still `0.1.0`, so the zip is `doghouse-0.1.0.zip`. Bump the
|
||||
version before the real release if wanted.
|
||||
- npm installs the glibc variants of sharp and argon2 alongside the musl ones. The deps stage
|
||||
deletes them, saving about 19 MB. After that, sharp still encoded a JPEG and argon2 still
|
||||
hashed in the Alpine root filesystem. The runtime `node_modules` is about 95 MB.
|
||||
@@ -0,0 +1,768 @@
|
||||
# Doghouse
|
||||
|
||||
A self-hostable, Discord-style chat app: servers, text channels, DMs, voice and screen share.
|
||||
Runs as two Docker containers (the app and LiveKit) behind your existing **Nginx Proxy Manager**
|
||||
at **https://doghouse.snoooopy.online**.
|
||||
|
||||
- **Deploying it:** follow [Deploy](#deploy-step-by-step) from top to bottom. You don't need
|
||||
Node.js on the server; the image is built there by Docker.
|
||||
- **Upgrading or rolling back:** see [Upgrades](#upgrades) (0.5.0 -> 0.6.0:
|
||||
[Upgrading 0.5.0 -> 0.6.0](#upgrading-050---060); 0.4.1 -> 0.5.0:
|
||||
[Upgrading 0.4.1 -> 0.5.0](#upgrading-041---050); 0.4.0 -> 0.4.1:
|
||||
[Upgrading 0.4.0 -> 0.4.1](#upgrading-040---041); 0.3.1 -> 0.4.0:
|
||||
[Upgrading 0.3.1 -> 0.4.0](#upgrading-031---040)).
|
||||
- **Working on it:** see [Development](#development).
|
||||
|
||||
## What you get in the zip
|
||||
```
|
||||
doghouse-<version>/
|
||||
README.md this guide
|
||||
THIRD-PARTY-NOTICES.md credits and licences (Nord and Solarized colour palettes)
|
||||
CHANGES-0.6.0.md what changed in this release, upgrade steps
|
||||
(CHANGES-0.5.0.md, CHANGES-0.4.1.md, CHANGES-0.4.0.md, CHANGES-0.3.1.md,
|
||||
CHANGES-0.3.0.md, CHANGES-0.2.0.md, CHANGES-0.1.2.md,
|
||||
CHANGES-0.1.1.md, CHANGES-M6.md: older releases)
|
||||
.gitignore keeps deploy/.env and deploy/data/ out of git if you version the folder
|
||||
deploy/
|
||||
docker-compose.yml project "doghouse": doghouse-app + doghouse-livekit
|
||||
Dockerfile builds the app image (node 22 -> node:22-alpine, non-root)
|
||||
docker-entrypoint.sh makes ./data writable, then runs the app as user "node"
|
||||
.env.example settings template -> copy to .env
|
||||
livekit.yaml LiveKit config (no secrets in it)
|
||||
npm-advanced.conf paste into NPM's "Advanced" tab
|
||||
nginx-raw.conf appendix: plain nginx instead of NPM
|
||||
apps/ packages/ ... source code the image is built from
|
||||
```
|
||||
|
||||
## Deploy step by step
|
||||
|
||||
### 0. What you need
|
||||
- A Linux server with **Docker Engine 24+ and the Compose plugin** (`docker compose version`
|
||||
prints v2.x).
|
||||
- **Nginx Proxy Manager** already running in Docker on that server, with ports 80 and 443 reaching
|
||||
it from the internet.
|
||||
- The domain `snoooopy.online` in a DNS provider you can edit.
|
||||
- Access to your router (to forward the voice ports).
|
||||
- About 1 GB of disk for the images. The first build takes a few minutes.
|
||||
|
||||
### 1. DNS record
|
||||
At your DNS provider add:
|
||||
|
||||
| Type | Name | Value |
|
||||
|---|---|---|
|
||||
| `A` | `doghouse` | your public IPv4 address |
|
||||
|
||||
(Or a `CNAME` `doghouse` -> your existing dynamic-DNS name.) If you use Cloudflare, set it to
|
||||
**DNS only** (grey cloud): voice traffic can't go through Cloudflare's proxy. Check it with
|
||||
`nslookup doghouse.snoooopy.online`.
|
||||
|
||||
### 2. Router port forwards (voice)
|
||||
Web traffic (80/443) already goes to NPM. Voice and screen share need these extra forwards to the
|
||||
server's LAN IP:
|
||||
|
||||
| Protocol | Port(s) | What |
|
||||
|---|---|---|
|
||||
| UDP | 20000-20100 | voice/screen-share media |
|
||||
| TCP | 7881 | media fallback for networks that block UDP |
|
||||
| UDP | 3478 | TURN (relays media for people behind strict firewalls) |
|
||||
|
||||
**Firewall note:** Docker publishes these ports with its own iptables rules, which **bypass ufw**.
|
||||
`ufw allow` alone neither opens nor closes them; the router forwards are what matter. (If you
|
||||
also want ufw rules for documentation, `sudo ufw allow 20000:20100/udp`, `sudo ufw allow 7881/tcp`,
|
||||
`sudo ufw allow 3478/udp` are harmless.) Port 3000 (the app) and 7880 (LiveKit signalling) are
|
||||
never published; NPM reaches them over the Docker network.
|
||||
|
||||
### 3. Upload and unzip
|
||||
```bash
|
||||
scp doghouse-<version>.zip you@server:~
|
||||
ssh you@server
|
||||
unzip doghouse-<version>.zip
|
||||
cd doghouse-<version>/deploy
|
||||
```
|
||||
Everything below runs in this `deploy` folder.
|
||||
|
||||
### 4. Settings (`.env`)
|
||||
```bash
|
||||
cp .env.example .env
|
||||
docker run --rm livekit/livekit-server:v1.13.9 generate-keys
|
||||
```
|
||||
`generate-keys` prints an `API Key` and an `API Secret`. Put them into `.env`:
|
||||
```
|
||||
LIVEKIT_API_KEY=APIxxxxxxxxxxxx
|
||||
LIVEKIT_API_SECRET=<the long secret, at least 32 characters>
|
||||
```
|
||||
Check the other values (they're already right for doghouse.snoooopy.online):
|
||||
`APP_NAME`, `PUBLIC_URL=https://doghouse.snoooopy.online`,
|
||||
`LIVEKIT_PUBLIC_URL=wss://doghouse.snoooopy.online/livekit`, `NODE_ENV=production`,
|
||||
`TRUST_PROXY_HOPS=1`, `MAX_UPLOAD_MB=25`, `VIDEO_ENABLED=true` (webcams; `false` turns them off).
|
||||
Keep `.env` private (`chmod 600 .env`).
|
||||
|
||||
Two more settings live in `.env`, so upgrades never overwrite them:
|
||||
- `LIVEKIT_NODE_IP`: your public IP (`curl -4 ifconfig.me`). Recommended: LiveKit then advertises
|
||||
it directly instead of looking it up via STUN at every start. Leave it empty to use STUN.
|
||||
- `DOGHOUSE_NETWORK`: the Docker network to join (step 5). Default `doghouse_net`.
|
||||
|
||||
### 5. Docker network, and connect NPM to it
|
||||
The app, LiveKit and NPM talk over one shared network called `doghouse_net`:
|
||||
```bash
|
||||
docker network create doghouse_net
|
||||
docker ps --format '{{.Names}}' # find your NPM container's name
|
||||
docker network connect doghouse_net <npm-container-name>
|
||||
```
|
||||
If NPM was started with its own compose file, add the network there instead so it survives NPM
|
||||
re-creates:
|
||||
```yaml
|
||||
services:
|
||||
app: # the NPM service
|
||||
networks: [default, doghouse_net]
|
||||
networks:
|
||||
doghouse_net:
|
||||
external: true
|
||||
```
|
||||
then `docker compose up -d` in NPM's folder.
|
||||
|
||||
**Already have a network NPM is on** (e.g. `homelab`)? Skip the commands above and set
|
||||
`DOGHOUSE_NETWORK=homelab` in `.env` instead. Don't edit `docker-compose.yml` for this (an upgrade
|
||||
would overwrite it), and don't use `network_mode:`. `network_mode: host` or `network_mode: homelab`
|
||||
is wrong; joining a network is done with `networks:`, which the compose file already does. In host
|
||||
mode NPM can no longer reach `doghouse-livekit:7880`, LiveKit can't send webhooks to
|
||||
`doghouse-app:3000`, and DNS inside the container can break (see Troubleshooting). Check:
|
||||
```bash
|
||||
docker inspect doghouse-livekit --format '{{.HostConfig.NetworkMode}}' # doghouse_net (or your DOGHOUSE_NETWORK), never "host"
|
||||
docker exec doghouse-app cat /etc/resolv.conf # nameserver 127.0.0.11
|
||||
```
|
||||
Containers on a user-defined network use Docker's embedded DNS, `nameserver 127.0.0.11`.
|
||||
|
||||
### 6. Start Doghouse
|
||||
```bash
|
||||
docker compose up -d
|
||||
docker compose ps # both "running"; doghouse-app becomes "healthy" within ~30 s
|
||||
docker compose logs -f app # Ctrl+C to stop following
|
||||
```
|
||||
The first run builds the app image (a few minutes). Since 0.6 the image is tagged with the version
|
||||
(`doghouse-app:<version>`), so a new release always builds its own image the first time and a
|
||||
plain `up -d` is enough; `docker compose up -d --build` still works and forces a rebuild (see
|
||||
[Upgrades](#upgrades)). `./data` is created next to the compose file and holds the database and
|
||||
uploads.
|
||||
|
||||
### 7. Nginx Proxy Manager: proxy host
|
||||
In NPM's web UI: **Hosts > Proxy Hosts > Add Proxy Host**.
|
||||
|
||||
**Details tab**
|
||||
| Field | Value |
|
||||
|---|---|
|
||||
| Domain Names | `doghouse.snoooopy.online` |
|
||||
| Scheme | `http` |
|
||||
| Forward Hostname / IP | `doghouse-app` |
|
||||
| Forward Port | `3000` |
|
||||
| Cache Assets | off |
|
||||
| Block Common Exploits | **on** |
|
||||
| Websockets Support | **on** (chat uses a WebSocket at `/ws`) |
|
||||
| Access List | Publicly Accessible |
|
||||
|
||||
**SSL tab**
|
||||
| Field | Value |
|
||||
|---|---|
|
||||
| SSL Certificate | **Request a new SSL Certificate** (Let's Encrypt) |
|
||||
| Force SSL | **on** |
|
||||
| HTTP/2 Support | **on** |
|
||||
| HSTS Enabled | **on** (leave HSTS Subdomains off) |
|
||||
| Email / Agree to ToS | your email, tick the box |
|
||||
|
||||
**Advanced tab:** paste the whole content of `deploy/npm-advanced.conf` into **Custom Nginx
|
||||
Configuration**. It adds the LiveKit signalling route `/livekit/` (forwarded to
|
||||
`doghouse-livekit:7880` with the prefix stripped, WebSocket upgrade, 24 h timeouts) and the upload
|
||||
limit `client_max_body_size 30m`. If you change `MAX_UPLOAD_MB`, set `client_max_body_size` a few
|
||||
MB above it.
|
||||
|
||||
Save. The certificate request needs DNS (step 1) to point at you already.
|
||||
|
||||
*About X-Forwarded-For:* NPM **appends** the client address to any `X-Forwarded-For` header the
|
||||
client sent, and this can't be reliably changed from the Advanced tab. That's safe here: with
|
||||
`TRUST_PROXY_HOPS=1` the app only trusts the last (rightmost) address, which NPM writes from the
|
||||
real connection, so a forged header can't change the IP used for rate limiting.
|
||||
|
||||
### 8. First run
|
||||
1. Open https://doghouse.snoooopy.online. The **first account you register becomes the instance
|
||||
admin**, so do it straight away.
|
||||
2. Close open sign-ups: **User settings (gear, bottom left) > Registration**, turn off
|
||||
**Open registration**. New people then need an invite (create one there, or use a server's
|
||||
invite link).
|
||||
3. Create a server; it comes with a text and a voice channel. Join the voice channel from two
|
||||
devices (one on mobile data) to check voice works. Turn a camera on to check video (or set
|
||||
`VIDEO_ENABLED=false` in `.env` if your upload is slow; see "Bandwidth" under Development).
|
||||
|
||||
### Backups
|
||||
Everything lives in `deploy/data/` (SQLite database `chat.db` + `uploads/`) and `deploy/.env`.
|
||||
```bash
|
||||
cd ~/doghouse-<version>/deploy
|
||||
docker compose stop app # consistent copy of the database
|
||||
tar czf ~/doghouse-backup-$(date +%F-%H%M%S).tgz data .env
|
||||
docker compose start app
|
||||
```
|
||||
Each backup gets the date and time in its name, so a second backup on the same day never replaces
|
||||
the first (QA-96). Keep the one from before an upgrade until you're happy with the new version.
|
||||
Restore: stop, put `data/` and `.env` back, `docker compose up -d`. Voice has no state to back up.
|
||||
`data/vapid.json` holds the push notification key (see "Push notifications"); it is in the backup, and a
|
||||
restore keeps every device's notifications working. It is a secret: it is never in the release zip.
|
||||
|
||||
### Search index
|
||||
Message search (0.5) keeps its index in the database and updates it by itself; there is nothing to
|
||||
maintain. The index points at SQLite's internal row numbers, and some database tools can renumber
|
||||
those: a hand-run `VACUUM`, a `.dump` and restore, or `.recover`. **A stale index is detected and
|
||||
rebuilt at start**: every time Doghouse starts it checks that each indexed row is still the
|
||||
message it was (a few tens of milliseconds per 100,000 messages), and if not it rebuilds the index
|
||||
and logs one line, `Search index was out of step with messages (...); rebuilt <n> messages in <ms> ms`.
|
||||
So after any such tool, just restart Doghouse. You can also rebuild by hand at any time (safe while
|
||||
Doghouse runs; well under a second per 100,000 messages):
|
||||
```bash
|
||||
cd ~/doghouse-<version>/deploy
|
||||
docker compose exec -u node app node apps/server/dist/scripts/rebuild-search.js
|
||||
```
|
||||
From the release zip or from source (`npm start`, see Development): from the folder you run it in,
|
||||
with the same `DATA_DIR` or `DB_PATH` as the server, run `node apps/server/dist/scripts/rebuild-search.js`.
|
||||
It prints `Search index rebuilt: <n> messages in <ms> ms (<database path>)`. If it says
|
||||
`No database at <path>`, it was pointed at the wrong folder: it never creates a database, so check
|
||||
`DATA_DIR` or `DB_PATH` and run it again. While Doghouse is writing it waits its turn (up to 5
|
||||
seconds) rather than failing.
|
||||
|
||||
### Install as an app (PWA)
|
||||
Doghouse can be installed to the home screen / desktop (Chrome, Edge, Android: **Install** in
|
||||
*Settings → App and notifications*, or the browser menu; iPhone/iPad: Safari **Share → Add to Home
|
||||
Screen**, and the same settings page shows the steps). It needs HTTPS (your NPM proxy host
|
||||
already provides it).
|
||||
- `/manifest.webmanifest` is built from `APP_NAME` (name, short name, icons); `/sw.js` is the
|
||||
service worker, served `no-cache` with the app version filled in. Both are served by the app, not
|
||||
files in `dist`.
|
||||
- The service worker caches **no app files**: only a small offline page (`/offline.html`) shown
|
||||
when the server can't be reached. An upgrade installs a new worker, which never takes over by
|
||||
itself: an open page asks it to, and the worker agrees only when that is the only open window
|
||||
and nobody is in a call or voice channel (a tab in a call holds the Web Lock
|
||||
`doghouse-active-call`). Otherwise it waits until the other tabs close or the call ends, so
|
||||
people never run a mix of old and new files and a call is never interrupted.
|
||||
- Icons are generated (`node scripts/make-icons.mjs`, from `scripts/icons/*.svg`) and committed in
|
||||
`apps/web/public/icons/`; rerun the script only if you change the artwork.
|
||||
- If your reverse proxy rewrites headers, don't add caching to `/sw.js` or `/manifest.webmanifest`.
|
||||
|
||||
### Push notifications
|
||||
Settings > App and notifications switches notifications on **per device** (the browser asks for
|
||||
permission only then). Notified: direct and group messages, @mentions and replies to you; per-server,
|
||||
per-channel and per-DM levels (all / mentions only / nothing), Do Not Disturb and quiet hours (in your own
|
||||
time zone). Nothing is sent for a conversation you are looking at in a focused tab. On iPhone it works
|
||||
only after "Add to Home Screen" (iOS 16.4+).
|
||||
|
||||
Privacy: the browser's own push service (Google, Apple or Mozilla) carries the message, encrypted for your
|
||||
browser, so they can't read it. They do see that a notification was sent and when. "Show message content in
|
||||
notifications" off means the push contains no message text at all.
|
||||
|
||||
Your server must reach the push services over HTTPS (`fcm.googleapis.com`, `*.push.apple.com`,
|
||||
`updates.push.services.mozilla.com`, `*.notify.windows.com`). Restricted egress or broken DNS looks like
|
||||
"pushes never arrive". Don't rotate the VAPID key unless you must (see `VAPID_*` below).
|
||||
|
||||
Each account can have up to 10 devices (the push queue and its limits: see "Calls ring" below); adding an 11th replaces the one that last received a push longest
|
||||
ago. A device whose push service rejects it five times within 24 hours (403, 401, 400, a redirect, and so on;
|
||||
a success resets the count, and timeouts, 408, 413, 429 and 5xx never count) is
|
||||
switched off and shown as "Not working" in Settings: switch notifications on again on that device. If the
|
||||
Google, Apple or Mozilla host you use isn't on the list above, add it with `PUSH_ENDPOINT_ALLOW`.
|
||||
|
||||
### Calls ring, and ringtones
|
||||
A DM or group call rings the other people: a card with Accept and Decline, a looping tone and (on phones) a
|
||||
vibration, and a push that rings a closed app (the ring push expires after 30 s; a `call-end` push clears
|
||||
it). The caller hears a soft ringback. There is no loud ring with Do Not Disturb, in quiet hours or while
|
||||
you are already in a call (the card still shows), and with two tabs open only the visible one rings aloud.
|
||||
Settings > App and notifications has three built-in tones, a volume slider, Preview, and "Use my own
|
||||
ringtone" (mp3, ogg Vorbis/Opus or wav, up to 1 MB and 30 s): the file is checked and kept in that browser
|
||||
only, never uploaded, and isn't in your backup. How long a call rings: `CALL_RING_TIMEOUT_MS`.
|
||||
Pushes use two queues so a slow message push never delays a ring (calls: 16 at a time, 4 s timeout;
|
||||
messages: 8 at a time, 10 s; an endpoint that timed out is skipped for message pushes for 60 s).
|
||||
|
||||
### Upgrades
|
||||
**Going from 0.5.0 to 0.6.0?** Back up first, then follow
|
||||
[Upgrading 0.5.0 -> 0.6.0](#upgrading-050---060) below, with `docker compose up -d --build`. Its
|
||||
step 5 is the rollback to 0.5.0, which needs that backup.
|
||||
**Going from 0.4.1 to 0.5.0?** Follow [Upgrading 0.4.1 -> 0.5.0](#upgrading-041---050) below. Its
|
||||
step 4 is the rollback to 0.4.1.
|
||||
**Going from 0.4.0 to 0.4.1?** It's a drop-in: see [Upgrading 0.4.0 -> 0.4.1](#upgrading-040---041).
|
||||
**Going from 0.3.1 to 0.4.0?** Follow [Upgrading 0.3.1 -> 0.4.0](#upgrading-031---040) below. Its
|
||||
step 4 is the rollback to 0.3.1. **Still on 0.3.0?** You can go straight to 0.4.0 with the same
|
||||
steps, reading `doghouse-0.3.0` for `doghouse-0.3.1` (0.4.0 includes 0.3.1's call fix), and roll
|
||||
back to 0.3.1, not 0.3.0 (see step 4). Each version's own steps are below, oldest first; these general
|
||||
steps apply to all of them:
|
||||
1. Back up (above).
|
||||
2. Unzip the new version next to the old one and copy your settings and data over:
|
||||
```bash
|
||||
unzip doghouse-<new>.zip
|
||||
cp doghouse-<old>/deploy/.env doghouse-<new>/deploy/
|
||||
cd doghouse-<old>/deploy && docker compose down
|
||||
mv data ../../doghouse-<new>/deploy/
|
||||
cd ../../doghouse-<new>/deploy && docker compose up -d
|
||||
```
|
||||
From 0.6.0 on, the app image is named `doghouse-app:<version>`, and Compose builds it when it
|
||||
isn't there yet, so `up -d` is enough and you can't start a new release on an old image by
|
||||
forgetting `--build`. (Releases up to 0.5.0 name it `doghouse-app:local` and need
|
||||
`up -d --build`; their steps below keep it.) `up -d --build` is still fine: it just rebuilds.
|
||||
The compose file also says `pull_policy: never`, so Compose builds a missing image instead of
|
||||
first trying to pull `doghouse-app` from Docker Hub. A development zip (one with a commit
|
||||
hash in its name, `doghouse-<version>.<hash>.zip`) tags its image
|
||||
`doghouse-app:<version>-<hash>`, so each test zip builds its own image on a plain `up -d` too.
|
||||
3. Database migrations run automatically on start. Check `docker compose logs app`.
|
||||
4. Compare `.env.example` with your `.env` for new settings, and re-paste
|
||||
`npm-advanced.conf` into NPM if the changes notes say it changed.
|
||||
|
||||
Data survives `docker compose down` / `up` because it's in `./data` on the host.
|
||||
|
||||
#### Upgrading 0.1.0 -> 0.1.1
|
||||
0.1.1 fixes one display bug (QA-8, see `CHANGES-0.1.1.md`). It has **no database changes**, no new
|
||||
`.env` settings, and `docker-compose.yml`, `livekit.yaml` and `npm-advanced.conf` are unchanged.
|
||||
1. Back up `./data` (and `.env`), as in [Backups](#backups).
|
||||
2. Keep your existing `deploy/.env`, and your `deploy/livekit.yaml` if you edited it.
|
||||
3. Replace the source files with the ones from `doghouse-0.1.1.zip`: either unzip it next to the
|
||||
old folder and move `data/` and `.env` across as in the steps above, or unzip it over the old
|
||||
folder, taking care not to overwrite your `.env` (the zip has none) or an edited `livekit.yaml`.
|
||||
4. From `deploy/`, run `docker compose up -d --build`, then check `docker compose ps` shows both
|
||||
containers healthy.
|
||||
|
||||
#### Upgrading 0.1.1 -> 0.1.2
|
||||
0.1.2 fixes the LiveKit startup crash loop ("could not resolve external IP"), moves voice media
|
||||
to UDP **20000-20100** (from 50000-50100, which could fail with "address already in use") and
|
||||
makes the Docker network configurable. It has **no database changes**; `npm-advanced.conf` is
|
||||
unchanged. `docker-compose.yml` and `livekit.yaml` changed: use the new ones, and if you had edited
|
||||
`livekit.yaml`, re-apply your edits to the new file (keep its port range).
|
||||
1. Back up `./data` and `.env` ([Backups](#backups)). Keep your existing `.env`.
|
||||
2. Add the two new settings to your existing `deploy/.env` (see `.env.example`):
|
||||
```
|
||||
LIVEKIT_NODE_IP=<your public IP, from: curl -4 ifconfig.me>
|
||||
DOGHOUSE_NETWORK=doghouse_net
|
||||
```
|
||||
If you edited `docker-compose.yml` to use your own network (e.g. `homelab`), set
|
||||
`DOGHOUSE_NETWORK=homelab` instead and use the new compose file unedited. Remove any
|
||||
`network_mode:` line.
|
||||
3. Router and firewall: forward **UDP 20000-20100** to the server and remove the old
|
||||
UDP 50000-50100 forward. Same for ufw if you added rules:
|
||||
`sudo ufw allow 20000:20100/udp` and `sudo ufw delete allow 50000:50100/udp`.
|
||||
4. Replace the source files from `doghouse-0.1.2.zip`, as for 0.1.1 above, then from `deploy/`:
|
||||
`docker compose up -d --build`. Check `docker compose ps` and `docker compose logs livekit`.
|
||||
|
||||
#### Upgrading 0.1.2 -> 0.2.0
|
||||
0.2.0 adds profiles, server icons and banners, group DMs, and DM/group calls with webcams (see
|
||||
`CHANGES-0.2.0.md`). It **changes the database** (migrations 004-007, applied automatically on
|
||||
start), so a rollback needs the backup. `docker-compose.yml`, `livekit.yaml`,
|
||||
`npm-advanced.conf` and the router ports are unchanged.
|
||||
1. In `doghouse-0.1.2/deploy`: `docker compose down`, then back up `data` and `.env`
|
||||
([Backups](#backups)).
|
||||
2. Unzip `doghouse-0.2.0.zip` into a **fresh folder** next to the old one (not over it). Copy
|
||||
`deploy/.env` across and move `deploy/data` across, as in the general steps above. If you had
|
||||
edited `livekit.yaml`, re-apply your edits to the new file.
|
||||
3. Add the new setting to `deploy/.env`: `VIDEO_ENABLED=true` (webcams; `false` turns them
|
||||
off if your upload is slow. About 5-10 Mbps of server upload for five people on camera).
|
||||
Optional, defaults are fine: `CALL_RING_TIMEOUT_MS` (30000) and `MEDIA_DIR` (`data/media`,
|
||||
inside `./data`, so it's in your backup).
|
||||
4. From `doghouse-0.2.0/deploy`: `docker compose up -d --build`. Check `docker compose ps`
|
||||
(both healthy) and `docker compose logs app` (the app starts with no errors; the database
|
||||
changes are applied quietly on start).
|
||||
5. Rollback: stop 0.2.0, restore the backup into the 0.1.2 folder, and start 0.1.2. Never run
|
||||
0.1.2 on the upgraded `data`.
|
||||
6. Go through the real-device checklist in `CHANGES-0.2.0.md`.
|
||||
|
||||
#### Upgrading 0.2.0 -> 0.3.0
|
||||
0.3.0 adds installing Doghouse as an app, push notifications, and ringing calls with ringtones (see
|
||||
`CHANGES-0.3.0.md`). It **changes the database** (migration 008, additive, applied automatically on
|
||||
start), so a rollback needs the backup. No new ports; `docker-compose.yml`, `livekit.yaml` and
|
||||
`npm-advanced.conf` are unchanged.
|
||||
1. In `doghouse-0.2.0/deploy`: `docker compose down`, then back up `data` and `.env`
|
||||
([Backups](#backups)). From this version `data/vapid.json` (the push key pair, made on first
|
||||
start) is part of the backup too.
|
||||
2. Unzip `doghouse-0.3.0.zip` into a **fresh folder**, copy `deploy/.env` across and move
|
||||
`deploy/data` across, as in the general steps above.
|
||||
3. Nothing new is required in `.env`. Optional: `PUSH_ENDPOINT_ALLOW` (extra push-service hosts;
|
||||
only if your browsers' push service isn't Google, Apple, Mozilla or Windows) and the
|
||||
`VAPID_*` pair if you want your own keys. Your server needs outbound HTTPS to the push services
|
||||
(see [Push notifications](#push-notifications)).
|
||||
4. Your reverse proxy must not cache `/sw.js` or `/manifest.webmanifest`.
|
||||
5. From `doghouse-0.3.0/deploy`: `docker compose up -d --build`. Check `docker compose ps`: the
|
||||
app starts healthy (both containers `healthy`), and `docker compose logs app` shows no errors.
|
||||
Migration 008 is applied quietly on start; it doesn't print a log line.
|
||||
6. Rollback: stop 0.3.0, restore the backup into the 0.2.0 folder, and start 0.2.0. Never run
|
||||
0.2.0 on the upgraded `data`. Custom ringtones live in each person's browser, not on the server.
|
||||
7. Go through the real-device checklist in `CHANGES-0.3.0.md` (real push, iPhone, ringing).
|
||||
8. Known issue in 0.3.0, fixed in 0.3.1: starting a call within a second or two of the previous
|
||||
one ending could, rarely, drop the new call at connect. Upgrade on to 0.3.1 (below).
|
||||
|
||||
#### Upgrading 0.3.0 -> 0.3.1
|
||||
0.3.1 is a small fix release (see `CHANGES-0.3.1.md`). It has **no database changes**, no new
|
||||
settings and no new ports; `docker-compose.yml`, `livekit.yaml` and `npm-advanced.conf` are
|
||||
unchanged.
|
||||
1. In `doghouse-0.3.0/deploy`: `docker compose down`, then back up `data` and `.env`
|
||||
([Backups](#backups)).
|
||||
2. Unzip `doghouse-0.3.1.zip` into a **fresh folder**, copy `deploy/.env` across and move
|
||||
`deploy/data` across, as in the general steps above.
|
||||
3. From `doghouse-0.3.1/deploy`: `docker compose up -d --build`. Check `docker compose ps` (both
|
||||
healthy) and `docker compose logs app` (no errors). Calls going on during the upgrade end, as
|
||||
with any restart. On its first start 0.3.1 closes the LiveKit call rooms left over from 0.3.0
|
||||
(each call now gets its own room); nothing to do.
|
||||
4. Rollback: stop 0.3.1, move `data` back into the 0.3.0 folder and start 0.3.0. With no database
|
||||
changes, 0.3.0 runs on the same data.
|
||||
|
||||
#### Upgrading 0.3.1 -> 0.4.0
|
||||
0.4.0 adds pinned messages, blocking and theme presets (see `CHANGES-0.4.0.md`). It **changes the
|
||||
database** (migration 009, additive, applied automatically on start). No new settings and no new
|
||||
ports; `docker-compose.yml`, `livekit.yaml` and `npm-advanced.conf` are unchanged.
|
||||
|
||||
**On 0.3.0?** Go straight to 0.4.0 with these steps, reading `doghouse-0.3.0` for `doghouse-0.3.1`
|
||||
(QA-99). 0.4.0 includes everything in 0.3.1 (its call fix and its start-up clean-up of old call
|
||||
rooms, see `CHANGES-0.3.1.md`), and 0.3.1 has no database or deploy changes of its own. For a
|
||||
rollback, see step 4: roll back to 0.3.1, not 0.3.0.
|
||||
1. In `doghouse-0.3.1/deploy`: `docker compose down`, then back up `data` and `.env`
|
||||
([Backups](#backups)).
|
||||
2. Unzip `doghouse-0.4.0.zip` into a **fresh folder**, copy `deploy/.env` across and move
|
||||
`deploy/data` across, as in the general steps above.
|
||||
3. From `doghouse-0.4.0/deploy`: `docker compose up -d --build`. Check `docker compose ps` (both
|
||||
healthy) and `docker compose logs app` (no errors). Migration 009 is applied quietly on start;
|
||||
Settings and `/api/health` now show `0.4.0`. Calls going on during the upgrade end, as with any
|
||||
restart.
|
||||
4. Rollback to 0.3.1, if you need it:
|
||||
1. In `doghouse-0.4.0/deploy`: `docker compose down`.
|
||||
2. Move `data` back into the 0.3.1 folder: `mv data ../../doghouse-0.3.1/deploy/`. That folder
|
||||
still has its `.env`. If you deleted it, unzip `doghouse-0.3.1.zip` into a fresh folder first
|
||||
and copy `.env` into its `deploy` folder from `doghouse-0.4.0/deploy` (QA-100).
|
||||
**Coming from 0.3.0?** Roll back to 0.3.1, not 0.3.0: you have no 0.3.1 folder, so unzip
|
||||
`doghouse-0.3.1.zip` into a fresh folder, copy `.env` from `doghouse-0.4.0/deploy` into its
|
||||
`deploy` folder, then do this step or step 3 there. 0.3.0 also runs on the data, but it
|
||||
still has the rare call drop that 0.3.1 fixed.
|
||||
3. Optional, instead of step 2: restore the backup you made before the upgrade. In
|
||||
`doghouse-0.3.1/deploy`: `tar xzf ~/doghouse-backup-<date>.tgz` (it puts back `data` and
|
||||
`.env`). **This loses everything since the upgrade: messages, pins, blocks and theme
|
||||
changes.** Only do this if the data itself is the problem.
|
||||
Then, still in `doghouse-0.3.1/deploy`, rename the old 0.4 data so it is never used by mistake:
|
||||
`mv ../../doghouse-0.4.0/deploy/data ../../doghouse-0.4.0/deploy/data-before-rollback-$(date +%F-%H%M%S)`.
|
||||
The date and time in the name mean a second rollback never puts the newer data inside an
|
||||
older `data-before-rollback` folder (QA-98). A later upgrade then moves the restored `data`
|
||||
in as usual.
|
||||
4. In `doghouse-0.3.1/deploy`: `docker compose up -d --build`. 0.3.1 runs on the moved data (or
|
||||
the restored backup) and ignores the pins and blocks tables. Messages sent on 0.4.0 are kept,
|
||||
unless you restored the backup in step 3 (QA-97).
|
||||
|
||||
While rolled back, blocking is off and the new themes show as Dark; `CHANGES-0.4.0.md` lists
|
||||
what changes and what comes back when you upgrade again.
|
||||
5. Go through the real-device checklist in `CHANGES-0.4.0.md`.
|
||||
|
||||
#### Upgrading 0.4.0 -> 0.4.1
|
||||
0.4.1 is a small fix release (see `CHANGES-0.4.1.md`): a draft in a DM or group DM is no longer
|
||||
wiped when the other person sends. It is a drop-in: **no database changes**, no new settings and no
|
||||
new ports; `docker-compose.yml`, `Dockerfile`, `livekit.yaml` and `npm-advanced.conf` are
|
||||
unchanged.
|
||||
1. In `doghouse-0.4.0/deploy`: `docker compose down`, then back up `data` and `.env`
|
||||
([Backups](#backups)).
|
||||
2. Unzip `doghouse-0.4.1.zip` into a **fresh folder**, copy `deploy/.env` across and move
|
||||
`deploy/data` across, as in the general steps above.
|
||||
3. From `doghouse-0.4.1/deploy`: `docker compose up -d --build`. Check `docker compose ps` (both
|
||||
healthy) and `docker compose logs app` (no errors). Settings and `/api/health` now show
|
||||
`0.4.1`.
|
||||
4. Rollback: stop 0.4.1, move `data` back into the 0.4.0 folder and start 0.4.0. With no database
|
||||
changes, 0.4.0 runs on the same data.
|
||||
|
||||
#### Upgrading 0.4.1 -> 0.5.0
|
||||
0.5.0 adds message search, custom server emoji and threads (see `CHANGES-0.5.0.md`). It **changes
|
||||
the database** (migration 010, additive, applied automatically on start). No new settings and no
|
||||
new ports; `docker-compose.yml`, `livekit.yaml` and `npm-advanced.conf` are unchanged.
|
||||
|
||||
**On 0.4.0 or 0.3.x?** You can go straight to 0.5.0 with these steps, reading your folder name for
|
||||
`doghouse-0.4.1`. 0.5.0 includes every earlier fix, and the migrations in between run on start, in
|
||||
order. For a rollback, see step 4: roll back to 0.4.1, not to an earlier version.
|
||||
1. In `doghouse-0.4.1/deploy`: `docker compose down`, then back up `data` and `.env`
|
||||
([Backups](#backups)).
|
||||
2. Unzip `doghouse-0.5.0.zip` into a **fresh folder**, copy `deploy/.env` across and move
|
||||
`deploy/data` across, as in the general steps above.
|
||||
3. From `doghouse-0.5.0/deploy`: `docker compose up -d --build`. Check `docker compose ps` (both
|
||||
healthy) and `docker compose logs app` (no errors). Migration 010 runs on the first start: it
|
||||
builds the search index from your existing messages (about 0.5 s for 118,000 messages on a
|
||||
test machine) and the server is healthy about a second after start. The database grows by
|
||||
about a third (+37% on that 118,000-message set). Settings and `/api/health` now show
|
||||
`0.5.0`. A start-up check then confirms the search index is in step (a few tens of
|
||||
milliseconds per 100,000 messages) and, if needed, moves custom emoji pictures into
|
||||
`media/emoji` and moves any thread-reply pins made under 0.4.1 into their thread. You can also
|
||||
rebuild the search index by hand (see [Search index](#search-index)).
|
||||
4. Rollback to 0.4.1, if you need it:
|
||||
1. In `doghouse-0.5.0/deploy`: `docker compose down`.
|
||||
2. Move `data` back into the 0.4.1 folder: `mv data ../../doghouse-0.4.1/deploy/`. That folder
|
||||
still has its `.env`. If you deleted it, unzip `doghouse-0.4.1.zip` into a fresh folder first
|
||||
and copy `.env` into its `deploy` folder from `doghouse-0.5.0/deploy`.
|
||||
3. Optional, instead of step 2: restore the backup you made before the upgrade. In
|
||||
`doghouse-0.4.1/deploy`: `tar xzf ~/doghouse-backup-<date>.tgz` (it puts back `data` and
|
||||
`.env`). **This loses everything since the upgrade: messages, custom emoji and threads.**
|
||||
Only do this if the data itself is the problem.
|
||||
Then, still in `doghouse-0.4.1/deploy`, rename the old 0.5 data so it is never used by mistake:
|
||||
`mv ../../doghouse-0.5.0/deploy/data ../../doghouse-0.5.0/deploy/data-before-rollback-$(date +%F-%H%M%S)`.
|
||||
4. In `doghouse-0.4.1/deploy`: `docker compose up -d --build`. 0.4.1 runs on the moved data (or
|
||||
the restored backup) and ignores the new 0.5 tables. Messages sent on 0.5.0 are kept,
|
||||
unless you restored the backup in step 3.
|
||||
|
||||
While rolled back:
|
||||
- Custom emoji in messages show as raw `<:name:...>` text, and custom reactions show as a
|
||||
`c:<id>` pill that 0.4.1 can't remove. The pictures stay in `media/emoji` (0.4.1's clean-up
|
||||
doesn't touch them) and come back when you upgrade again.
|
||||
- Thread replies show inline in the channel as ordinary messages. Pins made inside a thread
|
||||
aren't listed, and the channel's unread count includes the replies. Upgrading again puts
|
||||
them back in their threads; a thread reply pinned under 0.4.1 moves to its thread at the
|
||||
next start, and nothing is unpinned.
|
||||
5. Go through the real-device checklist in `CHANGES-0.5.0.md`.
|
||||
|
||||
Tested: `REQUIRE_LIVEKIT=1 npm run check` is shared 49, server 690, web 1701, 0 failed. A full
|
||||
e2e run (`REQUIRE_LIVEKIT=1 npm run e2e`) is 114 passed, 100 skipped, 0 failed.
|
||||
|
||||
#### Upgrading 0.5.0 -> 0.6.0
|
||||
0.6.0 adds custom roles and channel permissions (with private and read-only channels) and
|
||||
statuses (Online, Idle, Do not disturb, Invisible, custom text); see `CHANGES-0.6.0.md`. It
|
||||
**changes the database** (migration 011, additive, applied automatically on start) and fixes a
|
||||
security issue in 0.5.0 and earlier. No new settings and no new ports. The app image is now
|
||||
tagged with the version: `deploy/docker-compose.yml` uses `doghouse-app:0.6.0` instead of
|
||||
`doghouse-app:local`.
|
||||
|
||||
**Back up first. Migration 011 can't be undone, so the only safe way back to 0.5.0 is the backup
|
||||
you make in step 1.**
|
||||
|
||||
**On 0.4.x or 0.3.x?** You can go straight to 0.6.0 with these steps, reading your folder name for
|
||||
`doghouse-0.5.0`; the migrations in between run on start, in order.
|
||||
1. In `doghouse-0.5.0/deploy`: `docker compose down`, then back up `data` and `.env`
|
||||
([Backups](#backups)). Keep that `.tgz` until you're happy with 0.6.0.
|
||||
2. Unzip `doghouse-0.6.0.zip` next to the old folder (it unpacks into `doghouse-0.6.0/`), copy
|
||||
`deploy/.env` across and move `deploy/data` across, as in the general steps above.
|
||||
3. From `doghouse-0.6.0/deploy`: **`docker compose up -d --build`**. Use `--build` for this
|
||||
upgrade: it always builds the 0.6.0 image from the files you just unzipped (the first build
|
||||
takes a few minutes). A plain `up -d` would also build the missing `doghouse-app:0.6.0` tag,
|
||||
but `--build` leaves no doubt. Check `docker compose ps` (both healthy) and
|
||||
`docker compose logs app` (no errors). Migration 011 runs on the first start and gives every
|
||||
server an `@everyone` role with exactly the 0.5.0 member rights, so nothing changes for anyone
|
||||
until you set up roles.
|
||||
4. Confirm the version: **Settings > App and notifications > About** shows `0.6.0 (build ...)`,
|
||||
and so does `/api/health`. `docker images doghouse-app` lists a `0.6.0` tag. If About still
|
||||
says 0.5.0, run step 3 again (with `--build`) in the 0.6.0 folder.
|
||||
5. Rollback to 0.5.0, if you need it: **restore the backup from step 1. This loses everything
|
||||
done since the upgrade (messages, roles, private channels, custom status).** Don't move the
|
||||
0.6 data back instead: 0.5.0 would start on it, **but 0.5.0 has no private channels, so every
|
||||
member could read every private channel's history**, and read-only channels would be writable.
|
||||
1. In `doghouse-0.6.0/deploy`: `docker compose down`, then rename the 0.6 data so it is never
|
||||
used by mistake: `mv data data-before-rollback-$(date +%F-%H%M%S)`.
|
||||
2. In `doghouse-0.5.0/deploy`: `tar xzf ~/doghouse-backup-<date>.tgz` (it puts back `data` and
|
||||
`.env` as they were before the upgrade). If you deleted that folder, unzip
|
||||
`doghouse-0.5.0.zip` into a fresh folder first and restore the backup in its `deploy`
|
||||
folder.
|
||||
3. In `doghouse-0.5.0/deploy`: `docker compose up -d --build`. Keep `--build` here: 0.5.0's
|
||||
compose file names its image `doghouse-app:local`, which is whatever you last built under
|
||||
that name, so only a rebuild makes sure it is 0.5.0. Settings then shows `0.5.0`. (The
|
||||
0.6.0 image stays under its own tag, so going forward to 0.6.0 again needs no rebuild.)
|
||||
6. Go through the real-device checklist in `CHANGES-0.6.0.md`.
|
||||
7. Old images pile up under their own tags. To free the disk once you're happy with 0.6.0:
|
||||
`docker image rm doghouse-app:local` (the 0.5.0 image; a rollback would rebuild it).
|
||||
|
||||
Tested: `REQUIRE_LIVEKIT=1 npm run check` is shared 340, server 834, web 1792, 0 failed. A full
|
||||
e2e run (`REQUIRE_LIVEKIT=1 npm run e2e`) is 136 passed, 122 skipped, 0 failed.
|
||||
|
||||
### Troubleshooting
|
||||
**Notifications never arrive**
|
||||
- The container needs outbound HTTPS to the push services (see "Push notifications"). Try
|
||||
`docker compose exec app node -e "fetch('https://fcm.googleapis.com').then(r=>console.log(r.status),e=>console.log(String(e)))"`.
|
||||
- Settings > App and notifications > "Send test notification". Nothing there means no device is switched on.
|
||||
- A subscription the push service reports as gone (404/410) is deleted; switch the device on again.
|
||||
- The app's logs show `push: rejected` or `push: no answer` with the host (never keys or message text).
|
||||
|
||||
**Voice doesn't connect** ("Connecting…" forever, or drops after a few seconds)
|
||||
- Router forwards from step 2 present (UDP 20000-20100, TCP 7881, UDP 3478) and pointing at
|
||||
the right LAN IP.
|
||||
- `docker compose logs livekit` should show `starting LiveKit server` with your **public** IP as
|
||||
`nodeIP`. Without `LIVEKIT_NODE_IP`, LiveKit finds it with STUN (`use_external_ip: true`). If
|
||||
the log stops before that line (LiveKit can hang at startup while STUN times out), or shows a
|
||||
private IP, set `LIVEKIT_NODE_IP=<your public IP>` in `.env` (`curl -4 ifconfig.me`), then
|
||||
`docker compose up -d livekit`. Don't edit `livekit.yaml` for this.
|
||||
- `https://doghouse.snoooopy.online/livekit/` in a browser should show `OK`. A 502 means NPM can't
|
||||
reach `doghouse-livekit` (check step 5: is NPM on `doghouse_net`?). A 404 means the Advanced
|
||||
block wasn't saved.
|
||||
- Voice needs HTTPS; it never works on `http://`.
|
||||
- "Voice isn't set up on this server yet" in the app = `LIVEKIT_API_KEY`/`LIVEKIT_API_SECRET` missing
|
||||
from `.env`.
|
||||
|
||||
**LiveKit restarts over and over** with:
|
||||
```
|
||||
could not validate RTC config: could not resolve external IP: dial udp: lookup stun1.l.google.com on 127.0.0.53:53: read udp 127.0.0.1:33500->127.0.0.53:53: read: connection refused
|
||||
doghouse-livekit exited with code 0 (restarting)
|
||||
```
|
||||
LiveKit looks up your public IP with STUN at startup, and that DNS lookup failed. The fix:
|
||||
1. Put your public IP in `.env`: `LIVEKIT_NODE_IP=203.0.113.10` (yours, from `curl -4 ifconfig.me`).
|
||||
2. `docker compose up -d livekit`. The log should now say
|
||||
`doghouse: LIVEKIT_NODE_IP=…, skipping STUN` and then `starting LiveKit server` with that `nodeIP`.
|
||||
|
||||
Then find out why DNS failed. `127.0.0.53` is the host's own resolver (systemd-resolved), which
|
||||
a container only sees when it runs in the host's network:
|
||||
```bash
|
||||
docker inspect doghouse-livekit --format '{{.HostConfig.NetworkMode}}'
|
||||
```
|
||||
This must say `doghouse_net` (or your `DOGHOUSE_NETWORK`), **not** `host`. Host mode also breaks
|
||||
NPM -> LiveKit (`/livekit/` gives 502) and LiveKit -> app webhooks (voice participant lists go
|
||||
stale). Remove any `network_mode:` you added to `docker-compose.yml` and use `DOGHOUSE_NETWORK`
|
||||
in `.env` instead (step 5), then `docker compose up -d`.
|
||||
|
||||
**`docker compose up` fails with "address already in use"** on a UDP port, e.g.:
|
||||
```
|
||||
failed to bind host port [::]:50028/udp: address already in use
|
||||
```
|
||||
That port is inside Linux's ephemeral range (32768-60999), which the host hands out to outgoing
|
||||
connections, so something else already holds it. 0.1.1 used UDP 50000-50100 for voice media;
|
||||
since 0.1.2 it's **20000-20100**, below that range. Use the shipped `livekit.yaml` and
|
||||
`docker-compose.yml` (the range is in both and they must match), move your router forwards and
|
||||
ufw rules to UDP 20000-20100 (step 2), then `docker compose up -d livekit`. Check what holds a
|
||||
port with `sudo ss -ulpn | grep 20000`.
|
||||
|
||||
**Home IP changed** (dynamic IP from your ISP): voice stops connecting while the site still works.
|
||||
Update `LIVEKIT_NODE_IP` in `.env` and run `docker compose up -d livekit`.
|
||||
|
||||
**"413 Request Entity Too Large" when uploading** - NPM's limit is lower than the file. Make sure
|
||||
the Advanced tab contains `client_max_body_size 30m;` (or more, matching `MAX_UPLOAD_MB`). Files
|
||||
over `MAX_UPLOAD_MB` get the app's own "too large" message instead.
|
||||
|
||||
**Messages from others only appear after a reload** - the WebSocket at `/ws` isn't
|
||||
getting through: turn on **Websockets Support** in the Details tab and save again.
|
||||
|
||||
**502 Bad Gateway on the whole site** - the app isn't running or NPM isn't on `doghouse_net`
|
||||
(or your `DOGHOUSE_NETWORK`): `docker compose ps`, `docker compose logs app`,
|
||||
`docker network inspect doghouse_net` (should list NPM, doghouse-app and doghouse-livekit).
|
||||
|
||||
**App keeps restarting** - `docker compose logs app` names the problem, e.g. a LiveKit secret
|
||||
shorter than 32 characters or a malformed `PUBLIC_URL`.
|
||||
|
||||
**`docker compose up` says "set LIVEKIT_API_KEY in .env"** - step 4 isn't done.
|
||||
|
||||
**Login says "Cross-origin request blocked"** - `PUBLIC_URL` in `.env` must exactly match the
|
||||
address in the browser (`https://doghouse.snoooopy.online`, no trailing slash).
|
||||
|
||||
### Appendix: plain nginx instead of NPM
|
||||
`deploy/nginx-raw.conf` is a complete `server` block for a self-managed nginx container on
|
||||
`doghouse_net` (certificates from certbot or similar). Unlike NPM it **overwrites**
|
||||
`X-Forwarded-For` and `X-Real-IP` with `$remote_addr`, proxies `/` and `/ws` to `doghouse-app:3000`
|
||||
with WebSocket upgrade, `/livekit/` to `doghouse-livekit:7880` (prefix stripped), and sets
|
||||
`client_max_body_size 30m`. Skip step 7 when you use it.
|
||||
|
||||
### Security notes
|
||||
- The app sends its own Content-Security-Policy (`script-src 'self'`, `connect-src` limited to
|
||||
the site and `LIVEKIT_PUBLIC_URL`, `frame-ancestors 'none'`), `X-Content-Type-Options`,
|
||||
`Referrer-Policy`, `Permissions-Policy` (microphone, screen capture and, with `VIDEO_ENABLED`,
|
||||
camera for the site only; `camera=()` when video is off) and
|
||||
`X-Frame-Options`. Don't add a second CSP in NPM.
|
||||
- The app runs as an unprivileged user inside the container and isn't reachable except through
|
||||
NPM.
|
||||
|
||||
## Development
|
||||
### Requirements
|
||||
- Node.js 20.19+ or 22 (production image will be `node:22-alpine`).
|
||||
- npm. `npm install` works with the committed `package-lock.json`. When *adding or upgrading*
|
||||
packages on the dev box, use `npx -y npm@10 install ...`: the Debian-packaged npm 9.2 crashes
|
||||
resolving new peer dependencies (arborist `edgesOut` bug).
|
||||
|
||||
### Commands (from the repo root)
|
||||
| Command | What it does |
|
||||
|---|---|
|
||||
| `npm install` | Install all workspaces |
|
||||
| `npm run dev` | API on :3000 (tsx watch) + Vite on :5173 proxying `/api` and `/ws` |
|
||||
| `npm run check` | Typecheck (tsc + svelte-check) → ESLint + Prettier → Vitest (server with coverage, 80% gate), then a summary of passed/failed/**skipped** tests per suite and the coverage figures |
|
||||
| `npm run build` | Build `packages/shared`, `apps/server/dist`, `apps/web/dist` |
|
||||
| `npm start` | Run the built server; serves `apps/web/dist` (or `./public`) with SPA fallback |
|
||||
| `npm run format` | Prettier write |
|
||||
| `npm run validate:deploy` | Static checks of `deploy/` (YAML + compose-spec schema + the rules above); part of `check` |
|
||||
| `npm run package` | Build the server zip (+ `.sha256`) in `dist/`, from a clean `git archive` of HEAD; refuses to run if the working tree has any change. Named `doghouse-<version>.zip` only when HEAD is exactly on the tag `v<version>` (the version in `package.json`); any other commit gives `doghouse-<version>.<hash>.zip`, e.g. `doghouse-0.2.0-dev.d95a1a1b2c.zip`, where `<hash>` is the same 10-character build hash as in `build.json`. Never overwrites an existing zip in `dist/` (it refuses; move the old one away first). Release builds also need `CHANGES-<version>.md`. The zip also gets `build.json` at its root (the one file not from `git archive`): the version, the first 10 characters of the commit hash and the commit time in UTC, so the same commit always gives the same zip, in any time zone. Settings > About, `/api/health` and `/api/instance` show it; a git checkout with no `build.json` uses git, and with neither the build is `dev` |
|
||||
| `npm run e2e` | Build, then run the Playwright smoke suite in `e2e/` (desktop 1440×900 + phone 375×812) against a fresh data dir. Ports, screenshot and artifact folders come from env vars (`E2E_PORT_BASE`, `E2E_LK_BASE`, `E2E_RTC_BASE`, `E2E_SHOTS_DIR`, `E2E_OUTPUT_DIR`; see `e2e/ports.mjs`), so two runs can go at once on different values (use `npm run e2e:only` for the second: `npm run e2e` rebuilds `dist`). Uses `CHROME_PATH`, else system Chrome/Chromium, else `npx playwright install chromium` |
|
||||
|
||||
### Releasing
|
||||
When you bump the version in the four workspace `package.json` files (and the lockfile), also bump
|
||||
the compose image tag in `deploy/docker-compose.yml` to `doghouse-app:<version>` in the same
|
||||
change. `npm run check` and `npm run package` fail if they don't match.
|
||||
|
||||
### Layout
|
||||
```
|
||||
apps/server Fastify + Socket.IO (/ws) + SQLite (better-sqlite3, WAL)
|
||||
src/db/migrations/*.sql plain SQL migrations (full v1 data model)
|
||||
src/auth/permissions.ts server-side authorization helpers (use these in every route)
|
||||
apps/web Svelte 5 + Vite, plain CSS; theme code in src/lib/theme
|
||||
packages/shared zod schemas + DTO types shared by server and web
|
||||
```
|
||||
|
||||
### Server environment variables
|
||||
| Var | Default | Notes |
|
||||
|---|---|---|
|
||||
| `APP_NAME` | `Doghouse` | Shown in the page title and auth screens (served by `/api/instance`) |
|
||||
| `PUBLIC_URL` | `https://doghouse.snoooopy.online` | The one origin users reach the app on |
|
||||
| `LIVEKIT_API_KEY` / `LIVEKIT_API_SECRET` | (empty) | Must match LiveKit's keys. Set both or neither; the secret must be at least 32 characters. Empty = voice disabled (the voice view says so, `/api/instance` reports `voiceEnabled: false`) |
|
||||
| `LIVEKIT_URL` | `http://doghouse-livekit:7880` | Internal LiveKit address the app uses for the server API (list/remove participants, delete rooms) |
|
||||
| `LIVEKIT_PUBLIC_URL` | `wss://doghouse.snoooopy.online/livekit` | LiveKit signalling URL handed to browsers, proxied under `/livekit/` with the prefix stripped. Outside production, if unset, browsers use same-origin `/livekit` (the Vite proxy) |
|
||||
| `NODE_ENV` | (unset) | `production` = strict Origin check: only `PUBLIC_URL` is accepted for POST/PATCH/PUT/DELETE and socket handshakes |
|
||||
| `PORT` / `HOST` | `3000` / `0.0.0.0` | |
|
||||
| `DATA_DIR` | `./data` | SQLite file `chat.db` and `uploads/` live here |
|
||||
| `UPLOADS_DIR` | `$DATA_DIR/uploads` | Uploaded files (random names, served only through the API) |
|
||||
| `MEDIA_DIR` | `$DATA_DIR/media` | Avatars and banners (0.2+): one folder of WebP sizes per image, random ids, served only to logged-in users |
|
||||
| `DB_PATH` | `$DATA_DIR/chat.db` | Override the DB file directly |
|
||||
| `STATIC_DIR` | auto | `./public`, then `apps/web/dist` |
|
||||
| `COOKIE_SECURE` | `auto` | `auto` = Secure when the request came in over HTTPS (uses `X-Forwarded-Proto`); `true`/`false` to force |
|
||||
| `TRUST_PROXY_HOPS` | `1` | Whole number of reverse-proxy hops to trust for `X-Forwarded-*` (QA-1). `1` = nginx, `0` = app reached directly, `2` = CDN in front of nginx. Never "true" |
|
||||
| `ALLOWED_ORIGINS` | (empty) | Development only: extra origins allowed besides `PUBLIC_URL` and same-host. Ignored when `NODE_ENV=production` |
|
||||
| `SESSION_TTL_DAYS` | `30` | |
|
||||
| `RATE_LIMIT` | `true` | Switches all the limits below on or off, including the pin, call-start and search limits. `AUTH_RATE_LIMIT_MAX` (10) per `AUTH_RATE_LIMIT_WINDOW_MS` (60000) per IP on login/register; it also covers the message, pin and unpin limits |
|
||||
| `MESSAGE_RATE_LIMIT_MAX` / `_WINDOW_MS` | `10` / `10000` | Messages per user per window (edits/deletes ×2, reactions ×3, uploads ×1, separate buckets) |
|
||||
| (fixed, follows `RATE_LIMIT`) | `10` per minute | Pin and unpin together, per person, across all chats; beyond that `429 too_many_pins` ("You can pin or unpin at most 10 messages a minute") with `Retry-After` |
|
||||
| (fixed, follows `RATE_LIMIT`) | `10` per 10 minutes | New DM and group calls started, per person (joining a call that is already going doesn't count); beyond that `429 too_many_calls` with `Retry-After`. Before 0.5 this one stayed on with `RATE_LIMIT=false` (QA-101) |
|
||||
| (fixed, follows `RATE_LIMIT`) | `30` per minute | Message searches, per person; beyond that `429 too_many_searches` ("You can search at most 30 times a minute") with `Retry-After` |
|
||||
| `MAX_UPLOAD_MB` | `25` | Upload limit in MB, 1-1024. Default **and ceiling**: admins can lower it via the API but not raise it above this, so the proxy's `client_max_body_size` (set a few MB higher) always fits |
|
||||
| `VIDEO_ENABLED` | `true` | Webcams in voice channels and DM/group calls. `false` = no camera button, LiveKit tokens can't publish a camera (LiveKit refuses it), and `Permissions-Policy: camera=()`. One flag drives all three. See "Bandwidth" below |
|
||||
| `VAPID_PUBLIC_KEY`, `VAPID_PRIVATE_KEY` | generated | Push notification key pair. Empty = generated on first start into `$DATA_DIR/vapid.json` (mode 0600). Set both or neither. Changing keys makes every device switch notifications on again |
|
||||
| `PUSH_ENDPOINT_ALLOW` | empty | Extra push-service hosts (comma separated, `host` or `*.suffix`). Defaults: `fcm.googleapis.com`, `*.push.apple.com`, `updates.push.services.mozilla.com`, `*.push.services.mozilla.com`, `*.notify.windows.com`. Only `https`, no port, never an IP or internal name |
|
||||
| `PUSH_TEST_ORIGINS` | empty | Tests only: read only when `NODE_ENV=test` (the e2e suite points pushes at a local mock). Ignored in production; leave it out of `.env` |
|
||||
| `CALL_RING_TIMEOUT_MS` | `30000` | How long a DM/group call rings before it ends as a missed call (1000-300000; tests shorten it) |
|
||||
| `PRESENCE_GRACE_MS` | `10000` | How long after a user's last socket disconnects before they show as offline (a reload or brief network drop doesn't flicker). Dead connections are noticed within ~20 s by Socket.IO pings |
|
||||
| `LOG_LEVEL` | `info` | |
|
||||
|
||||
Uploaded JPEG/PNG/GIF/WebP images are re-encoded with `sharp` (orientation applied, EXIF/GPS/XMP
|
||||
removed, animations kept, 50 MP limit); images that don't decode are rejected with 400. Other files
|
||||
are stored byte-for-byte. `sharp` ships prebuilt binaries for glibc and musl (`node:22-alpine`), so no
|
||||
build tools are needed.
|
||||
|
||||
### Voice and screen share (LiveKit)
|
||||
- `POST /api/voice/:channelId/token` issues a 10-minute token for room `voice_<channelId>` (identity =
|
||||
user id): mic + screen share (+ its audio), plus camera only when `VIDEO_ENABLED` is on; no data
|
||||
channel, no room admin. 404 if you can't see the channel, 400 for a text channel.
|
||||
- DM and group calls (0.2): `POST /api/dms/:dmId/call` starts the DM's call (or returns the one
|
||||
already going: one active call per DM, enforced by a unique index) and rings every open tab of
|
||||
every other member (`call:ring`; no push notifications). `POST /api/dms/:dmId/call/token` gives
|
||||
a token for room `call_<dmId>` to current members only (404 otherwise, like voice).
|
||||
`POST /api/calls/:id/accept|decline|leave` and `GET /api/calls` (what's active / ringing for
|
||||
you). Unanswered after `CALL_RING_TIMEOUT_MS` (30 s) = "Missed call" system message; an
|
||||
answered call ends with "…'s call ended after N minutes". Removing someone from a group drops
|
||||
them from its call at once. One call or voice channel per person at a time.
|
||||
- **Bandwidth (webcams):** LiveKit forwards a copy of every camera to every viewer, so your home
|
||||
connection's *upload* is the limit. The app uses simulcast (180p/360p/full layers), adaptive
|
||||
stream and dynacast, so small tiles get the small layer and hidden tiles get nothing. Rough
|
||||
guide: five people on camera in a grid need about **5-10 Mbps of server upload**; screen share
|
||||
adds 1-3 Mbps per viewer. If calls stutter, set `VIDEO_ENABLED=false` (voice and screen share
|
||||
keep working) and `docker compose up -d`.
|
||||
- `POST /api/livekit/webhook` (LiveKit signs it with the API key/secret; unsigned or forged = 401)
|
||||
keeps the in-memory "who's in voice" state that is pushed as `voice:state`. On startup the app
|
||||
rebuilds that state from LiveKit (`listRooms`/`listParticipants`). Kick, ban or losing access
|
||||
removes the person from the call; deleting a voice channel deletes its room.
|
||||
- Local dev: download `livekit-server` (GitHub releases; tested with v1.13.9) and run
|
||||
`livekit-server --dev --keys "devkey: <32+ character secret>" --node-ip <your LAN IP>` (the
|
||||
built-in dev secret `secret` is shorter than the app's 32-character minimum). Set `LIVEKIT_API_KEY`,
|
||||
`LIVEKIT_API_SECRET`, `LIVEKIT_URL=http://localhost:7880` for the API; Vite proxies `/livekit` to
|
||||
`LIVEKIT_DEV_URL` (default `http://localhost:7880`) with the prefix stripped. Chrome won't connect
|
||||
over loopback-only ICE candidates, hence `--node-ip`/`rtc.node_ip`. `--dev` sends no webhooks, so
|
||||
the voice roster stays empty unless you use a config file with `webhook.urls:
|
||||
[http://localhost:3000/api/livekit/webhook]` (as `e2e/livekit.mjs` does).
|
||||
- e2e: `e2e/tests/voice.spec.ts` and `e2e/tests/calls.spec.ts` run Chromes with fake mic, camera and
|
||||
screen against a real LiveKit when the binary is found. The e2e suite starts two app instances:
|
||||
:3199 (ring timeout 10 s) and :3197 with `VIDEO_ENABLED=false` and its own LiveKit (7895/7896,
|
||||
proxy :3196, media UDP 21200-21300) to check that LiveKit itself refuses a camera. The binary is
|
||||
found (`LIVEKIT_BIN`, `/workspace/tools/livekit-server` or `PATH`); otherwise it skips.
|
||||
`E2E_LIVEKIT=0` forces the skip; `E2E_LIVEKIT_NODE_IP` overrides the advertised IP. If
|
||||
`LIVEKIT_BIN` is set, only that path is used.
|
||||
- `apps/server/test/livekit.integration.test.ts` (part of `npm run check`) starts the same binary
|
||||
and checks the app's real LiveKit API calls (startup rebuild, `deleteRoom`, `removeParticipant`).
|
||||
- **`REQUIRE_LIVEKIT=1`**: nothing LiveKit-related may skip. `npm run check` fails (the integration
|
||||
test throws "REQUIRE_LIVEKIT=1 but no livekit-server binary was found…") and `npm run e2e` fails
|
||||
(the e2e server exits, and the voice spec errors if voice is disabled) when the binary isn't
|
||||
available. Use it in CI and for release sign-off: `REQUIRE_LIVEKIT=1 npm run check && REQUIRE_LIVEKIT=1 npm run e2e`.
|
||||
Without it, skipped tests are still listed by name in the check summary.
|
||||
@@ -0,0 +1,64 @@
|
||||
# Third-party notices
|
||||
|
||||
Doghouse's own code is not covered by this file. This lists third-party work that Doghouse
|
||||
includes or is based on, with its licence. The npm packages the app is built from are installed
|
||||
when the Docker image is built and carry their own licence files in `node_modules`.
|
||||
|
||||
## Nord colour palette
|
||||
|
||||
The "Nord" theme uses colours from the Nord palette by Arctic Ice Studio and Sven Greb
|
||||
(<https://www.nordtheme.com>), adapted where needed so text reads at 4.5:1.
|
||||
|
||||
```
|
||||
MIT License (MIT)
|
||||
|
||||
Copyright (c) 2016-present Sven Greb <development@svengreb.de> (https://www.svengreb.de)
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
```
|
||||
|
||||
## Solarized colour palette
|
||||
|
||||
The "Solarized light" and "Solarized dark" themes use the Solarized palette by Ethan Schoonover
|
||||
(<https://ethanschoonover.com/solarized/>). The background colours are kept; text and accent
|
||||
colours are adjusted so everything reads at 4.5:1 (see CHANGES-0.4.0.md).
|
||||
|
||||
```
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2011 Ethan Schoonover
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
```
|
||||
@@ -0,0 +1,39 @@
|
||||
{
|
||||
"name": "@chat/server",
|
||||
"version": "0.6.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "dist/index.js",
|
||||
"engines": {
|
||||
"node": ">=20.19"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc -p tsconfig.json && node scripts/copy-migrations.mjs",
|
||||
"dev": "tsx watch --clear-screen=false src/index.ts",
|
||||
"start": "node dist/index.js",
|
||||
"typecheck": "tsc -p tsconfig.check.json",
|
||||
"test": "vitest run --coverage",
|
||||
"coverage": "vitest run --coverage"
|
||||
},
|
||||
"dependencies": {
|
||||
"@chat/shared": "*",
|
||||
"@fastify/cookie": "^11.0.2",
|
||||
"@fastify/multipart": "^9.4.0",
|
||||
"@fastify/rate-limit": "^10.3.0",
|
||||
"@fastify/static": "^10.1.10",
|
||||
"@node-rs/argon2": "^2.0.2",
|
||||
"better-sqlite3": "12.9.0",
|
||||
"fastify": "^5.12.7",
|
||||
"livekit-server-sdk": "^2.19.1",
|
||||
"sharp": "^0.35.5",
|
||||
"socket.io": "^4.8.1",
|
||||
"ulid": "^3.0.1",
|
||||
"web-push": "^3.6.7",
|
||||
"zod": "^4.6.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/better-sqlite3": "^7.6.13",
|
||||
"socket.io-client": "^4.8.4",
|
||||
"tsx": "^4.20.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import { cpSync } from 'node:fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const src = fileURLToPath(new URL('../src/db/migrations', import.meta.url));
|
||||
const dest = fileURLToPath(new URL('../dist/db/migrations', import.meta.url));
|
||||
cpSync(src, dest, { recursive: true });
|
||||
@@ -0,0 +1,410 @@
|
||||
import type { HealthDto } from '@chat/shared';
|
||||
import { blockRoutes } from './routes/blocks.js';
|
||||
import { BlockService } from './services/blocks.js';
|
||||
import fastifyCookie from '@fastify/cookie';
|
||||
import fastifyMultipart from '@fastify/multipart';
|
||||
import fastifyRateLimit from '@fastify/rate-limit';
|
||||
import fastifyStatic from '@fastify/static';
|
||||
import Fastify, { type FastifyInstance, type FastifyReply } from 'fastify';
|
||||
import { existsSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { SESSION_COOKIE } from './auth/plugin.js';
|
||||
import type { AppConfig } from './config.js';
|
||||
import { openDb, type DB } from './db/index.js';
|
||||
import { checkSearchIndex, type SearchIndexCheck } from './db/search-index.js';
|
||||
import { relocateThreadPins } from './db/thread-pins.js';
|
||||
import { ensureEveryoneRoles } from './db/everyone.js';
|
||||
import { HttpError } from './lib/errors.js';
|
||||
import { readAppVersion } from './lib/pwa.js';
|
||||
import { readBuildInfo } from './lib/build-info.js';
|
||||
import { securityHeaders } from './lib/security.js';
|
||||
import { pwaRoutes } from './routes/pwa.js';
|
||||
import { requestIsAllowed } from './lib/origin.js';
|
||||
import { normalisedPath, routeOf } from './lib/paths.js';
|
||||
import { authRoutes } from './routes/auth.js';
|
||||
import { dmRoutes } from './routes/dms.js';
|
||||
import { voiceRoutes } from './routes/voice.js';
|
||||
import { callRoutes } from './routes/calls.js';
|
||||
import { instanceRoutes } from './routes/instance.js';
|
||||
import { searchRoutes } from './routes/search.js';
|
||||
import { threadRoutes } from './routes/threads.js';
|
||||
import { roleRoutes } from './routes/roles.js';
|
||||
import { RoleService } from './services/roles.js';
|
||||
import { emojiRoutes } from './routes/emoji.js';
|
||||
import { EmojiService } from './services/emoji.js';
|
||||
import { SearchService } from './services/search.js';
|
||||
import { ThreadService } from './services/threads.js';
|
||||
import { meRoutes } from './routes/me.js';
|
||||
import { profileRoutes } from './routes/profiles.js';
|
||||
import { serverMediaRoutes } from './routes/server-media.js';
|
||||
import { messageRoutes } from './routes/messages.js';
|
||||
import { serverRoutes } from './routes/servers.js';
|
||||
import { RecordingHub, type RealtimeHub } from './realtime/hub.js';
|
||||
import { AuthService } from './services/auth.js';
|
||||
import { ChannelService } from './services/channels.js';
|
||||
import { DmService } from './services/dms.js';
|
||||
import { PresenceService, visibleTo } from './services/presence.js';
|
||||
import { InviteService } from './services/invites.js';
|
||||
import { MessageService } from './services/messages.js';
|
||||
import { ServerService } from './services/servers.js';
|
||||
import { convertLegacyServerIcons } from './services/server-media.js';
|
||||
import { SettingsService } from './services/settings.js';
|
||||
import { UploadService } from './services/uploads.js';
|
||||
import { MediaService } from './services/media.js';
|
||||
import { UserService } from './services/users.js';
|
||||
import type { Lifecycle } from './services/lifecycle.js';
|
||||
import { AccessSync } from './services/access-sync.js';
|
||||
import { VoiceService, type LivekitApi } from './services/voice.js';
|
||||
import { CallService } from './services/calls.js';
|
||||
import { PushService, type FetchLike } from './services/push.js';
|
||||
import { pushRoutes } from './routes/push.js';
|
||||
import { RoomServiceClient } from 'livekit-server-sdk';
|
||||
|
||||
export interface AppServices {
|
||||
db: DB;
|
||||
auth: AuthService;
|
||||
settings: SettingsService;
|
||||
users: UserService;
|
||||
servers: ServerService;
|
||||
channels: ChannelService;
|
||||
invites: InviteService;
|
||||
uploads: UploadService;
|
||||
/** The shared image pipeline (M7+): avatars, banners, later server and group images. */
|
||||
media: MediaService;
|
||||
messages: MessageService;
|
||||
dms: DmService;
|
||||
presence: PresenceService;
|
||||
voice: VoiceService;
|
||||
/** DM and group calls (M10): ringing, the calls table, call rooms in LiveKit. */
|
||||
calls: CallService;
|
||||
/** Web push (M12): subscriptions, preferences, sending. */
|
||||
push: PushService;
|
||||
/** M18 blocking: your list, block and unblock (enforcement lives in auth/blocks.ts). */
|
||||
blocks: BlockService;
|
||||
/** M23 message search (D26): one server or DM, FTS5 index kept by migration 010's triggers. */
|
||||
search: SearchService;
|
||||
/** M24 custom server emoji (D27): 50 per server, 10 uploads a minute per user. */
|
||||
emoji: EmojiService;
|
||||
/** M25 threads (D25, D29): start, list, follow, delete; 10 starts a minute per user. */
|
||||
threads: ThreadService;
|
||||
/** M29 (D46): keeps sockets' `chan:` rooms equal to what their user can VIEW. */
|
||||
accessSync: AccessSync;
|
||||
/** M29 roles and channel permissions (D40 hierarchy, D57 30 writes a minute per user). */
|
||||
roles: RoleService;
|
||||
/** D32: what the start-up search index check found (and rebuilt). */
|
||||
searchIndex: SearchIndexCheck;
|
||||
/** Replaced by a Socket.IO-backed hub in attachSocket(); records events otherwise (tests). */
|
||||
realtime: RealtimeHub;
|
||||
}
|
||||
|
||||
declare module 'fastify' {
|
||||
interface FastifyInstance {
|
||||
services: AppServices;
|
||||
}
|
||||
}
|
||||
|
||||
export interface BuildOptions {
|
||||
/** LiveKit server API. Default: RoomServiceClient on LIVEKIT_URL when voice is configured. */
|
||||
livekitApi?: LivekitApi | null;
|
||||
/** Tests: how pushes are delivered (a mock push service). Default: global fetch. */
|
||||
pushFetch?: FetchLike;
|
||||
/** Tests: the clock the push service uses (throttle, quiet hours, grace). */
|
||||
pushNow?: () => number;
|
||||
}
|
||||
|
||||
function defaultLivekitApi(config: AppConfig): LivekitApi | null {
|
||||
const { apiKey, apiSecret, url } = config.livekit;
|
||||
if (!apiKey || !apiSecret) return null;
|
||||
const client = new RoomServiceClient(url, apiKey, apiSecret);
|
||||
return {
|
||||
listRooms: () => client.listRooms(),
|
||||
listParticipants: (room) => client.listParticipants(room),
|
||||
removeParticipant: (room, identity) => client.removeParticipant(room, identity),
|
||||
deleteRoom: (room) => client.deleteRoom(room),
|
||||
setPublishSources: async (room, identity, sources) => {
|
||||
const p = await client.getParticipant(room, identity);
|
||||
await client.updateParticipant(room, identity, {
|
||||
permission: { ...p.permission, canPublishSources: sources },
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function buildApp(
|
||||
config: AppConfig,
|
||||
db: DB = openDb(config.dbPath),
|
||||
options: BuildOptions = {},
|
||||
): Promise<FastifyInstance> {
|
||||
const app = Fastify({
|
||||
logger: config.logLevel === 'silent' ? false : { level: config.logLevel },
|
||||
// Trust exactly N proxy hops (QA-1): same semantics as proxy-addr's numeric trust, written as a
|
||||
// function because Fastify's types don't accept a number.
|
||||
trustProxy:
|
||||
config.trustProxy > 0 ? (_addr: string, hop: number) => hop < config.trustProxy : false,
|
||||
bodyLimit: 1024 * 1024,
|
||||
// D67 (QA-163): a URL Fastify can't decode (`/%zz`) is answered before any hook runs; give it
|
||||
// the same JSON 400 with no-store and the security headers.
|
||||
frameworkErrors: (err, _req, res) => {
|
||||
const reply = res as unknown as FastifyReply;
|
||||
void reply
|
||||
.code(400)
|
||||
.headers(securityHeaders(config))
|
||||
.header('Cache-Control', 'no-store')
|
||||
.send({ error: 'bad_request', message: err.message });
|
||||
},
|
||||
});
|
||||
|
||||
// D32 (QA-111): after migrations, make sure the search index still points at the right rows.
|
||||
const searchCheck = checkSearchIndex(db);
|
||||
if (searchCheck.problem) {
|
||||
app.log.warn(
|
||||
`Search index was out of step with messages (${searchCheck.problem}); rebuilt ${searchCheck.rebuilt} messages in ${Math.round(searchCheck.rebuildMs)} ms`,
|
||||
);
|
||||
}
|
||||
|
||||
// D42: belt and braces after migration 011's backfill: every server has an @everyone role.
|
||||
const madeEveryone = ensureEveryoneRoles(db);
|
||||
if (madeEveryone > 0)
|
||||
app.log.warn(`Created a missing @everyone role for ${madeEveryone} servers`);
|
||||
|
||||
// D36 (QA-127): pins put on thread replies by 0.4.1 after a rollback move to their thread.
|
||||
const movedPins = relocateThreadPins(db);
|
||||
if (movedPins > 0) {
|
||||
app.log.info(`Moved ${movedPins} pinned thread replies from their channel to their thread`);
|
||||
}
|
||||
|
||||
const hub = () => services.realtime;
|
||||
const lifecycle: Lifecycle = {};
|
||||
const servers = new ServerService(db, hub, lifecycle);
|
||||
const uploads = new UploadService(db, config.uploadsDir);
|
||||
const media = new MediaService(db, config.mediaDir);
|
||||
media.addReferences('SELECT avatar_media AS id FROM users WHERE avatar_media IS NOT NULL');
|
||||
media.addReferences('SELECT banner_media AS id FROM users WHERE banner_media IS NOT NULL');
|
||||
media.addReferences('SELECT icon_media AS id FROM servers WHERE icon_media IS NOT NULL');
|
||||
media.addReferences('SELECT banner_media AS id FROM servers WHERE banner_media IS NOT NULL');
|
||||
media.addReferences('SELECT icon_media AS id FROM dm_channels WHERE icon_media IS NOT NULL');
|
||||
media.addReferences('SELECT media_id AS id FROM custom_emoji');
|
||||
// D34: emoji images a pre-release 0.5 build stored at the top level move under emoji/.
|
||||
media.relocateEmoji(
|
||||
(db.prepare('SELECT media_id AS id FROM custom_emoji').all() as { id: string }[]).map(
|
||||
(r) => r.id,
|
||||
),
|
||||
);
|
||||
const messages = new MessageService(
|
||||
db,
|
||||
hub,
|
||||
uploads,
|
||||
config.rateLimit.enabled ? undefined : null, // D14 pin limit follows RATE_LIMIT
|
||||
);
|
||||
const dms = new DmService(db, hub, messages, media, uploads);
|
||||
const presence = new PresenceService(
|
||||
db,
|
||||
hub,
|
||||
(userId) => visibleTo(db, userId),
|
||||
config.presenceGraceMs,
|
||||
);
|
||||
const livekitApi =
|
||||
options.livekitApi === undefined ? defaultLivekitApi(config) : options.livekitApi;
|
||||
const grants = { ...config.livekit, videoEnabled: config.videoEnabled };
|
||||
const services: AppServices = {
|
||||
db,
|
||||
searchIndex: searchCheck,
|
||||
auth: new AuthService(db, config.sessionTtlDays),
|
||||
settings: new SettingsService(db, config.maxUploadMb),
|
||||
users: new UserService(db, hub),
|
||||
servers,
|
||||
channels: new ChannelService(db, hub, lifecycle),
|
||||
invites: new InviteService(db, servers),
|
||||
uploads,
|
||||
media,
|
||||
messages,
|
||||
dms,
|
||||
presence,
|
||||
voice: new VoiceService(db, hub, grants, livekitApi, app.log),
|
||||
calls: new CallService(
|
||||
db,
|
||||
hub,
|
||||
messages,
|
||||
{ ...grants, callRingMs: config.callRingMs },
|
||||
livekitApi,
|
||||
app.log,
|
||||
config.rateLimit.enabled, // QA-101: the call-start limit follows RATE_LIMIT
|
||||
),
|
||||
push: new PushService(
|
||||
db,
|
||||
config.push,
|
||||
config.publicUrl,
|
||||
app.log,
|
||||
options.pushFetch,
|
||||
options.pushNow,
|
||||
),
|
||||
blocks: new BlockService(db, hub),
|
||||
// D26: 30 searches a minute per person, off with RATE_LIMIT=false.
|
||||
search: new SearchService(db, messages, config.rateLimit.enabled ? undefined : null),
|
||||
// D27: 10 emoji uploads a minute per person, off with RATE_LIMIT=false.
|
||||
emoji: new EmojiService(db, hub, messages, config.rateLimit.enabled ? undefined : null),
|
||||
// M25: 10 thread starts a minute per person, off with RATE_LIMIT=false.
|
||||
threads: new ThreadService(db, hub, messages, config.rateLimit.enabled ? undefined : null),
|
||||
realtime: new RecordingHub(),
|
||||
accessSync: new AccessSync(db, hub, lifecycle),
|
||||
// D57: 30 role and permission writes a minute per person, off with RATE_LIMIT=false.
|
||||
roles: new RoleService(db, hub, lifecycle, config.rateLimit.enabled ? undefined : null),
|
||||
};
|
||||
messages.onCreated = (id) => services.push.notifyMessage(id);
|
||||
lifecycle.memberRemoved = (serverId, userId) => services.voice.memberRemoved(serverId, userId);
|
||||
lifecycle.voiceChannelDeleted = (channelId, serverId) =>
|
||||
services.voice.channelDeleted(channelId, serverId);
|
||||
lifecycle.voiceAccessChanged = (serverId, userId, visible) =>
|
||||
services.voice.accessChanged(serverId, userId, visible);
|
||||
lifecycle.accessChanged = (serverId, userIds) => services.accessSync.apply(serverId, userIds);
|
||||
// One call at a time per user: joining a voice channel leaves a DM call and the other way round.
|
||||
services.voice.onConnected = (userId) => services.calls.disconnectUser(userId);
|
||||
services.calls.onConnected = (userId) => services.voice.disconnectUser(userId);
|
||||
services.calls.push = services.push;
|
||||
services.blocks.onBlocked = (a, b) => services.calls.blocked(a, b);
|
||||
// D50: custom text stops (or comes back) between the two at once.
|
||||
services.blocks.onChanged = (a, b) => services.presence.blockChanged(a, b);
|
||||
dms.onMemberGone = (dmId, userId) => services.calls.memberGone(dmId, userId);
|
||||
// D49 expiry sweep; D67: it also runs once now, so it needs the services (the hub) in place.
|
||||
presence.startSweep(config.statusSweepMs);
|
||||
app.decorate('services', services);
|
||||
app.decorateRequest('user', null);
|
||||
// Migration 005's data step: 0.1 server icons onto the media pipeline (idempotent).
|
||||
await convertLegacyServerIcons(db, uploads, media, app.log);
|
||||
app.addHook('onClose', async () => {
|
||||
presence.close();
|
||||
services.calls.close();
|
||||
if (db.open) db.close();
|
||||
});
|
||||
|
||||
await app.register(fastifyCookie);
|
||||
// Per-request size limits come from instance settings (routes/messages.ts); this is a ceiling.
|
||||
await app.register(fastifyMultipart, {
|
||||
limits: { fileSize: 1024 * 1024 * 1024, files: 1, fields: 0, parts: 1, headerPairs: 50 },
|
||||
});
|
||||
if (config.rateLimit.enabled) {
|
||||
// global: false -> only routes with config.rateLimit are limited (auth now, messages later).
|
||||
await app.register(fastifyRateLimit, { global: false });
|
||||
}
|
||||
|
||||
const headers = securityHeaders(config);
|
||||
app.addHook('onRequest', async (req, reply) => {
|
||||
reply.headers(headers);
|
||||
// D67 (QA-163): every state-changing request, whatever its path (`/%61pi/...` is routed as
|
||||
// `/api/...`), must come from our origin. Safe methods pass; Socket.IO has its own check.
|
||||
if (!requestIsAllowed(req, config.allowedOrigins, !config.production)) {
|
||||
throw new HttpError(403, 'bad_origin', 'Cross-origin request blocked');
|
||||
}
|
||||
req.user = services.auth.getSessionUser(req.cookies[SESSION_COOKIE]);
|
||||
});
|
||||
|
||||
// D65 (QA-161), D67 (QA-163): JSON can carry private content (messages, pins, member lists),
|
||||
// so by default it never goes into the browser's HTTP cache, where it would outlive a logout or
|
||||
// lost access. This keys on nothing path-based: every JSON response, matched or not (404s for
|
||||
// unknown or oddly encoded paths included). Only static files opt out (tones.json keeps
|
||||
// @fastify/static's caching; its routes carry `rootPath`). File routes (D58 attachments, media
|
||||
// and emoji) never send JSON bodies except their errors, which are no-store anyway.
|
||||
app.addHook('onSend', async (req, reply, payload) => {
|
||||
const cfg = req.routeOptions.config as { rootPath?: unknown } | undefined;
|
||||
const type = String(reply.getHeader('content-type') ?? '');
|
||||
if (typeof cfg?.rootPath !== 'string' && type.startsWith('application/json')) {
|
||||
reply.header('Cache-Control', 'no-store');
|
||||
}
|
||||
return payload;
|
||||
});
|
||||
|
||||
app.setErrorHandler((err, req, reply) => {
|
||||
if (err instanceof HttpError) {
|
||||
if (err.headers) reply.headers(err.headers);
|
||||
return reply
|
||||
.code(err.statusCode)
|
||||
.send({ error: err.code, message: err.message, details: err.details });
|
||||
}
|
||||
const e = err as { statusCode?: number; code?: string; message?: string };
|
||||
if (e.statusCode === 429) {
|
||||
return reply.code(429).send({
|
||||
error: 'rate_limited',
|
||||
message: routeOf(req).startsWith('/api/auth/')
|
||||
? 'Too many attempts. Please wait a minute and try again.'
|
||||
: "You're doing that too fast. Please wait a moment.",
|
||||
});
|
||||
}
|
||||
if (e.statusCode && e.statusCode >= 400 && e.statusCode < 500) {
|
||||
return reply.code(e.statusCode).send({ error: e.code ?? 'bad_request', message: e.message });
|
||||
}
|
||||
req.log.error(err);
|
||||
return reply.code(500).send({ error: 'internal', message: 'Something went wrong' });
|
||||
});
|
||||
|
||||
await app.register(authRoutes, { auth: services.auth, servers: services.servers, config });
|
||||
await app.register(meRoutes, { users: services.users, config });
|
||||
await app.register(profileRoutes, { services, config });
|
||||
await app.register(serverMediaRoutes, { services, config });
|
||||
// QA-62: the release version, so a deploy can be confirmed from /api/health and Settings.
|
||||
const appVersion = readAppVersion();
|
||||
// D22: read once at start (build.json in a release, else git, else "dev").
|
||||
const build = readBuildInfo({ version: appVersion, log: (m) => app.log.warn(m) });
|
||||
await app.register(instanceRoutes, {
|
||||
...services,
|
||||
appName: config.appName,
|
||||
voiceEnabled: services.voice.enabled,
|
||||
videoEnabled: config.videoEnabled,
|
||||
callRingMs: config.callRingMs,
|
||||
version: appVersion,
|
||||
build,
|
||||
});
|
||||
await app.register(serverRoutes, { services, config });
|
||||
await app.register(messageRoutes, { services, config });
|
||||
await app.register(dmRoutes, { services, config });
|
||||
await app.register(voiceRoutes, { services, config });
|
||||
await app.register(callRoutes, { services, config });
|
||||
await app.register(pushRoutes, { services, config });
|
||||
await app.register(blockRoutes, { services, config });
|
||||
await app.register(searchRoutes, { services });
|
||||
await app.register(threadRoutes, { services });
|
||||
await app.register(roleRoutes, { services });
|
||||
await app.register(emojiRoutes, { services });
|
||||
// Who is in voice right now: LiveKit is the source of truth after a restart (decisions log).
|
||||
app.addHook('onReady', async () => {
|
||||
services.voice.rebuild().catch((err: unknown) => {
|
||||
app.log.warn({ err }, 'Could not load voice state from LiveKit');
|
||||
});
|
||||
services.calls.rebuild().catch((err: unknown) => {
|
||||
app.log.warn({ err }, 'Could not load call state from LiveKit');
|
||||
});
|
||||
});
|
||||
app.get('/api/health', async (): Promise<HealthDto> => ({
|
||||
ok: true,
|
||||
version: appVersion,
|
||||
build,
|
||||
}));
|
||||
await app.register(pwaRoutes, {
|
||||
appName: config.appName,
|
||||
appVersion,
|
||||
staticDir: config.staticDir,
|
||||
});
|
||||
|
||||
const staticDir = config.staticDir;
|
||||
if (staticDir && existsSync(path.join(staticDir, 'index.html'))) {
|
||||
await app.register(fastifyStatic, {
|
||||
root: staticDir,
|
||||
wildcard: false,
|
||||
index: ['index.html'],
|
||||
// /sw.js is served by routes/pwa.ts (version filled in, no-cache).
|
||||
globIgnore: ['sw.js'],
|
||||
});
|
||||
}
|
||||
|
||||
// SPA fallback: unknown GETs that want HTML get index.html; API/socket paths get JSON 404.
|
||||
app.setNotFoundHandler((req, reply) => {
|
||||
const path = normalisedPath(req.url);
|
||||
const isApi = path.startsWith('/api/') || path === '/api' || path.startsWith('/ws');
|
||||
const wantsHtml = (req.headers.accept ?? '').includes('text/html');
|
||||
if (!isApi && staticDir && req.method === 'GET' && wantsHtml) {
|
||||
return reply.type('text/html').sendFile('index.html');
|
||||
}
|
||||
return reply.code(404).send({ error: 'not_found', message: 'Not found' });
|
||||
});
|
||||
|
||||
return app;
|
||||
}
|
||||
@@ -0,0 +1,296 @@
|
||||
/**
|
||||
* D44 (DESIGN-0.6 §3.1): the only place that computes permissions on the server. Every check
|
||||
* reads the database right now (no cache: SQLite is in-process and these are indexed lookups; a
|
||||
* cache would add invalidation bugs exactly where the leak tests live). The bits themselves come
|
||||
* from the one shared function, `computePerms` in @chat/shared, so the client agrees.
|
||||
*
|
||||
* - 404 when the user can't VIEW the channel (or isn't a member, or it doesn't exist), with the
|
||||
* same body as a missing id, so hidden ids can't be probed.
|
||||
* - 403 when they can VIEW it but lack the bit.
|
||||
*/
|
||||
import {
|
||||
ADMIN_CHANNEL_POLICY,
|
||||
Perm,
|
||||
computePerms,
|
||||
hasPerm,
|
||||
topPosition,
|
||||
type AdminChannelPolicy,
|
||||
type OverrideLike,
|
||||
type RoleLike,
|
||||
type ServerRole,
|
||||
} from '@chat/shared';
|
||||
import type { DB } from '../db/index.js';
|
||||
import { forbidden, notFound } from '../lib/errors.js';
|
||||
import type { ChannelRow } from './permissions.js';
|
||||
|
||||
export interface RoleRow {
|
||||
id: string;
|
||||
server_id: string;
|
||||
name: string;
|
||||
color: string | null;
|
||||
position: number;
|
||||
permissions: number;
|
||||
is_everyone: number;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
type Role = RoleLike & { position: number };
|
||||
|
||||
/** Everything needed to compute permissions for many people in one server, from one load. */
|
||||
export interface ServerAccessData {
|
||||
serverId: string;
|
||||
roles: Role[];
|
||||
/** Non-banned members: rank and custom role ids. */
|
||||
members: Map<string, { rank: ServerRole; roleIds: string[] }>;
|
||||
channels: ChannelRow[];
|
||||
overrides: Map<string, OverrideLike[]>;
|
||||
}
|
||||
|
||||
const toRole = (r: RoleRow): Role => ({
|
||||
id: r.id,
|
||||
permissions: r.permissions,
|
||||
isEveryone: r.is_everyone === 1,
|
||||
position: r.position,
|
||||
});
|
||||
|
||||
export class Access {
|
||||
/**
|
||||
* `policy` is D37/D61's admin rule; the default is the one constant in @chat/shared. Tests pass
|
||||
* 'roles' to check the other reading.
|
||||
*/
|
||||
constructor(
|
||||
private readonly db: DB,
|
||||
readonly policy: AdminChannelPolicy = ADMIN_CHANNEL_POLICY,
|
||||
) {}
|
||||
|
||||
static for(db: DB, policy?: AdminChannelPolicy): Access {
|
||||
return new Access(db, policy);
|
||||
}
|
||||
|
||||
// ---- loads ----
|
||||
|
||||
private rank(userId: string, serverId: string): ServerRole | null {
|
||||
const row = this.db
|
||||
.prepare('SELECT role, banned FROM members WHERE server_id = ? AND user_id = ?')
|
||||
.get(serverId, userId) as { role: ServerRole; banned: number } | undefined;
|
||||
return !row || row.banned === 1 ? null : row.role;
|
||||
}
|
||||
|
||||
private roles(serverId: string): Role[] {
|
||||
return (
|
||||
this.db.prepare('SELECT * FROM roles WHERE server_id = ?').all(serverId) as RoleRow[]
|
||||
).map(toRole);
|
||||
}
|
||||
|
||||
private memberRoleIds(userId: string, serverId: string): string[] {
|
||||
return (
|
||||
this.db
|
||||
.prepare('SELECT role_id FROM member_roles WHERE server_id = ? AND user_id = ?')
|
||||
.all(serverId, userId) as { role_id: string }[]
|
||||
).map((r) => r.role_id);
|
||||
}
|
||||
|
||||
private overridesOf(channelId: string): OverrideLike[] {
|
||||
return (
|
||||
this.db
|
||||
.prepare('SELECT role_id, allow, deny FROM channel_overrides WHERE channel_id = ?')
|
||||
.all(channelId) as { role_id: string; allow: number; deny: number }[]
|
||||
).map((o) => ({ roleId: o.role_id, allow: o.allow, deny: o.deny }));
|
||||
}
|
||||
|
||||
private channel(channelId: string): ChannelRow | undefined {
|
||||
return this.db.prepare('SELECT * FROM channels WHERE id = ?').get(channelId) as
|
||||
ChannelRow | undefined;
|
||||
}
|
||||
|
||||
/** One load of a server: roles, members with their roles, channels and overrides. */
|
||||
load(serverId: string): ServerAccessData {
|
||||
const members = new Map<string, { rank: ServerRole; roleIds: string[] }>();
|
||||
for (const m of this.db
|
||||
.prepare('SELECT user_id, role FROM members WHERE server_id = ? AND banned = 0')
|
||||
.all(serverId) as { user_id: string; role: ServerRole }[]) {
|
||||
members.set(m.user_id, { rank: m.role, roleIds: [] });
|
||||
}
|
||||
for (const r of this.db
|
||||
.prepare('SELECT user_id, role_id FROM member_roles WHERE server_id = ?')
|
||||
.all(serverId) as { user_id: string; role_id: string }[]) {
|
||||
members.get(r.user_id)?.roleIds.push(r.role_id);
|
||||
}
|
||||
const overrides = new Map<string, OverrideLike[]>();
|
||||
for (const o of this.db
|
||||
.prepare(
|
||||
`SELECT o.channel_id, o.role_id, o.allow, o.deny FROM channel_overrides o
|
||||
JOIN channels c ON c.id = o.channel_id WHERE c.server_id = ?`,
|
||||
)
|
||||
.all(serverId) as { channel_id: string; role_id: string; allow: number; deny: number }[]) {
|
||||
const list = overrides.get(o.channel_id) ?? [];
|
||||
list.push({ roleId: o.role_id, allow: o.allow, deny: o.deny });
|
||||
overrides.set(o.channel_id, list);
|
||||
}
|
||||
return {
|
||||
serverId,
|
||||
roles: this.roles(serverId),
|
||||
members,
|
||||
channels: this.db
|
||||
.prepare('SELECT * FROM channels WHERE server_id = ? ORDER BY position, id')
|
||||
.all(serverId) as ChannelRow[],
|
||||
overrides,
|
||||
};
|
||||
}
|
||||
|
||||
/** Channel permissions of one member from a `load()` (0 for a non-member). */
|
||||
permsIn(data: ServerAccessData, userId: string, channelId: string): number {
|
||||
const m = data.members.get(userId);
|
||||
if (!m) return 0;
|
||||
return computePerms(
|
||||
{
|
||||
rank: m.rank,
|
||||
roles: data.roles,
|
||||
memberRoleIds: m.roleIds,
|
||||
overrides: data.overrides.get(channelId) ?? [],
|
||||
},
|
||||
this.policy,
|
||||
);
|
||||
}
|
||||
|
||||
/** Visible channel ids of one member from a `load()`. */
|
||||
visibleIn(data: ServerAccessData, userId: string): Set<string> {
|
||||
const out = new Set<string>();
|
||||
for (const c of data.channels) {
|
||||
if (hasPerm(this.permsIn(data, userId, c.id), Perm.VIEW_CHANNEL)) out.add(c.id);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---- single checks ----
|
||||
|
||||
serverPerms(userId: string, serverId: string): number {
|
||||
const rank = this.rank(userId, serverId);
|
||||
if (rank === null) return 0;
|
||||
return computePerms(
|
||||
{ rank, roles: this.roles(serverId), memberRoleIds: this.memberRoleIds(userId, serverId) },
|
||||
this.policy,
|
||||
);
|
||||
}
|
||||
|
||||
channelPerms(userId: string, channelId: string): number {
|
||||
const ch = this.channel(channelId);
|
||||
return ch ? this.permsFor(userId, ch) : 0;
|
||||
}
|
||||
|
||||
private permsFor(userId: string, ch: ChannelRow): number {
|
||||
const rank = this.rank(userId, ch.server_id);
|
||||
if (rank === null) return 0;
|
||||
return computePerms(
|
||||
{
|
||||
rank,
|
||||
roles: this.roles(ch.server_id),
|
||||
memberRoleIds: this.memberRoleIds(userId, ch.server_id),
|
||||
overrides: this.overridesOf(ch.id),
|
||||
},
|
||||
this.policy,
|
||||
);
|
||||
}
|
||||
|
||||
canView(userId: string, channelId: string): boolean {
|
||||
return hasPerm(this.channelPerms(userId, channelId), Perm.VIEW_CHANNEL);
|
||||
}
|
||||
|
||||
/**
|
||||
* The channel, if the user can VIEW it and has every bit in `bits`. 404 (the same body as a
|
||||
* missing channel) when they can't view it; 403 when they can but lack a bit.
|
||||
*/
|
||||
requireChannelPerm(
|
||||
userId: string,
|
||||
channelId: string,
|
||||
bits: number = Perm.VIEW_CHANNEL,
|
||||
): ChannelRow {
|
||||
const ch = this.channel(channelId);
|
||||
if (!ch) throw notFound('Channel not found');
|
||||
const p = this.permsFor(userId, ch);
|
||||
if (!hasPerm(p, Perm.VIEW_CHANNEL)) throw notFound('Channel not found');
|
||||
if (!hasPerm(p, bits)) throw forbidden();
|
||||
return ch;
|
||||
}
|
||||
|
||||
/** A server-scope bit: 404 for non-members (like today), 403 for members without it. */
|
||||
requireServerPerm(userId: string, serverId: string, bits: number): ServerRole {
|
||||
const rank = this.rank(userId, serverId);
|
||||
if (rank === null) throw notFound('Server not found');
|
||||
const p = computePerms(
|
||||
{ rank, roles: this.roles(serverId), memberRoleIds: this.memberRoleIds(userId, serverId) },
|
||||
this.policy,
|
||||
);
|
||||
if (!hasPerm(p, bits)) throw forbidden();
|
||||
return rank;
|
||||
}
|
||||
|
||||
/** The user's top position (D40): owner/admin Infinity, -1 for a non-member. */
|
||||
top(userId: string, serverId: string): number {
|
||||
return topPosition(
|
||||
this.rank(userId, serverId),
|
||||
this.roles(serverId),
|
||||
this.memberRoleIds(userId, serverId),
|
||||
);
|
||||
}
|
||||
|
||||
// ---- sets ----
|
||||
|
||||
/** Channel ids the user can VIEW, in one server or (no serverId) in all their servers. */
|
||||
visibleChannelIds(userId: string, serverId?: string): Set<string> {
|
||||
const servers = serverId
|
||||
? [serverId]
|
||||
: (
|
||||
this.db
|
||||
.prepare('SELECT server_id FROM members WHERE user_id = ? AND banned = 0')
|
||||
.all(userId) as { server_id: string }[]
|
||||
).map((r) => r.server_id);
|
||||
const out = new Set<string>();
|
||||
for (const s of servers) {
|
||||
if (this.rank(userId, s) === null) continue;
|
||||
for (const id of this.visibleIn(this.load(s), userId)) out.add(id);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Every user id that can VIEW the channel (push and audience fan-out). */
|
||||
channelViewers(channelId: string): string[] {
|
||||
const ch = this.channel(channelId);
|
||||
if (!ch) return [];
|
||||
const data = this.load(ch.server_id);
|
||||
return [...data.members.keys()].filter((u) =>
|
||||
hasPerm(this.permsIn(data, u, channelId), Perm.VIEW_CHANNEL),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* D61: the channel-permissions page lists every channel's NAME (never its content) to the owner
|
||||
* and admins, whatever the admin policy, so they can always fix access. Everyone else gets only
|
||||
* what they can see; `visible` says whether this user can VIEW each one. Non-members: 404.
|
||||
*/
|
||||
channelNamesForSettings(
|
||||
userId: string,
|
||||
serverId: string,
|
||||
): {
|
||||
id: string;
|
||||
name: string;
|
||||
type: 'text' | 'voice';
|
||||
categoryId: string | null;
|
||||
visible: boolean;
|
||||
}[] {
|
||||
const rank = this.rank(userId, serverId);
|
||||
if (rank === null) throw notFound('Server not found');
|
||||
const data = this.load(serverId);
|
||||
const seeAll = rank === 'owner' || rank === 'admin';
|
||||
const visible = this.visibleIn(data, userId);
|
||||
return data.channels
|
||||
.filter((c) => seeAll || visible.has(c.id))
|
||||
.map((c) => ({
|
||||
id: c.id,
|
||||
name: c.name,
|
||||
type: c.type,
|
||||
categoryId: c.category_id,
|
||||
visible: visible.has(c.id),
|
||||
}));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* Blocking (M18, DESIGN-0.4 section 4): the one place that knows who blocked whom. Every
|
||||
* enforcement point asks `between` / `blockedBy` (cached per database, invalidated on change),
|
||||
* and SQL that must filter before a LIMIT uses `NOT_BLOCKED_AUTHOR`, so there is no ad-hoc
|
||||
* blocks SQL elsewhere.
|
||||
*/
|
||||
import type { DB } from '../db/index.js';
|
||||
|
||||
/**
|
||||
* SQL condition for "the author isn't someone the reader blocked". Bind the reader's id for the
|
||||
* `?`. `col` is the author column (default `author_id`).
|
||||
*/
|
||||
export const notBlockedAuthor = (col = 'author_id') =>
|
||||
`${col} NOT IN (SELECT blocked_id FROM blocks WHERE blocker_id = ?)`;
|
||||
|
||||
export class Blocks {
|
||||
private static readonly byDb = new WeakMap<DB, Blocks>();
|
||||
|
||||
/** The shared instance for this database (the app has one; worker tests open their own). */
|
||||
static for(db: DB): Blocks {
|
||||
let b = Blocks.byDb.get(db);
|
||||
if (!b) Blocks.byDb.set(db, (b = new Blocks(db)));
|
||||
return b;
|
||||
}
|
||||
|
||||
/** userId -> the people that user has blocked. */
|
||||
private readonly cache = new Map<string, ReadonlySet<string>>();
|
||||
|
||||
private constructor(private readonly db: DB) {}
|
||||
|
||||
/** The people `userId` has blocked. */
|
||||
blockedBy(userId: string): ReadonlySet<string> {
|
||||
let set = this.cache.get(userId);
|
||||
if (!set) {
|
||||
set = new Set(
|
||||
(
|
||||
this.db.prepare('SELECT blocked_id FROM blocks WHERE blocker_id = ?').all(userId) as {
|
||||
blocked_id: string;
|
||||
}[]
|
||||
).map((r) => r.blocked_id),
|
||||
);
|
||||
this.cache.set(userId, set);
|
||||
}
|
||||
return set;
|
||||
}
|
||||
|
||||
/** Has either of the two blocked the other? (D4: 1:1 DMs and rings are blocked both ways.) */
|
||||
between(a: string, b: string): boolean {
|
||||
return a !== b && (this.blockedBy(a).has(b) || this.blockedBy(b).has(a));
|
||||
}
|
||||
|
||||
/** After any change to `blockerId`'s blocks. */
|
||||
invalidate(blockerId: string): void {
|
||||
this.cache.delete(blockerId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
/**
|
||||
* Server-side authorization helpers. Every route that touches servers, channels, DMs or messages
|
||||
* must go through these: the UI hiding a button is never the security boundary.
|
||||
*
|
||||
* Conventions:
|
||||
* - "can*" helpers return booleans (for filtering lists, socket room joins).
|
||||
* - "require*" helpers throw HttpError. When the user can't see the resource at all we throw 404
|
||||
* (not 403) so ids can't be probed; when they can see it but lack the role we throw 403.
|
||||
* - Banned members are treated as non-members everywhere.
|
||||
* - Instance admins get no implicit access to servers they aren't in (privacy by default).
|
||||
*/
|
||||
import { Perm, roleAtLeast, type ServerRole } from '@chat/shared';
|
||||
import type { DB } from '../db/index.js';
|
||||
import { forbidden, HttpError, notFound } from '../lib/errors.js';
|
||||
import { Access } from './access.js';
|
||||
import { Blocks } from './blocks.js';
|
||||
|
||||
// Pure role logic lives in @chat/shared so the client shows the same buttons the server allows.
|
||||
export { canModerate, roleAtLeast } from '@chat/shared';
|
||||
|
||||
/** The user's role in a server, or null if not a member (or banned). */
|
||||
export function getServerRole(db: DB, userId: string, serverId: string): ServerRole | null {
|
||||
const row = db
|
||||
.prepare('SELECT role, banned FROM members WHERE server_id = ? AND user_id = ?')
|
||||
.get(serverId, userId) as { role: ServerRole; banned: number } | undefined;
|
||||
if (!row || row.banned === 1) return null;
|
||||
return row.role;
|
||||
}
|
||||
|
||||
export function isBanned(db: DB, userId: string, serverId: string): boolean {
|
||||
const row = db
|
||||
.prepare('SELECT banned FROM members WHERE server_id = ? AND user_id = ?')
|
||||
.get(serverId, userId) as { banned: number } | undefined;
|
||||
return row?.banned === 1;
|
||||
}
|
||||
|
||||
/** Throws 404 if the user isn't a member, 403 if their role is below `min`. Returns the role. */
|
||||
export function requireServerRole(
|
||||
db: DB,
|
||||
userId: string,
|
||||
serverId: string,
|
||||
min: ServerRole = 'member',
|
||||
): ServerRole {
|
||||
const role = getServerRole(db, userId, serverId);
|
||||
if (role === null) throw notFound('Server not found');
|
||||
if (!roleAtLeast(role, min)) throw forbidden();
|
||||
return role;
|
||||
}
|
||||
|
||||
export interface ChannelRow {
|
||||
id: string;
|
||||
server_id: string;
|
||||
category_id: string | null;
|
||||
type: 'text' | 'voice';
|
||||
name: string;
|
||||
position: number;
|
||||
topic: string | null;
|
||||
}
|
||||
|
||||
/** 0.6 (D44): VIEW_CHANNEL from the Access service (roles, overrides, D37 admin rule). */
|
||||
export function canAccessChannel(db: DB, userId: string, channelId: string): boolean {
|
||||
return Access.for(db).canView(userId, channelId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the channel or throws 404 (missing, not a member, or no VIEW: the same body); with
|
||||
* `bits`, throws 403 when the user can view it but lacks any of them (D44).
|
||||
*/
|
||||
export function requireChannelAccess(
|
||||
db: DB,
|
||||
userId: string,
|
||||
channelId: string,
|
||||
bits: number = Perm.VIEW_CHANNEL,
|
||||
): ChannelRow {
|
||||
return Access.for(db).requireChannelPerm(userId, channelId, bits);
|
||||
}
|
||||
|
||||
export interface DmChannelRow {
|
||||
id: string;
|
||||
kind: 'dm' | 'group';
|
||||
/** 1:1 only (null for groups): the pair, kept so there's one 1:1 DM per pair. */
|
||||
user_a: string | null;
|
||||
user_b: string | null;
|
||||
name: string | null;
|
||||
icon_media: string | null;
|
||||
owner_id: string | null;
|
||||
}
|
||||
|
||||
/** Is the user a current member of this DM or group? (M9: dm_members is the only access rule.) */
|
||||
export function isDmMember(db: DB, userId: string, dmChannelId: string): boolean {
|
||||
return (
|
||||
db
|
||||
.prepare('SELECT 1 FROM dm_members WHERE dm_channel_id = ? AND user_id = ?')
|
||||
.get(dmChannelId, userId) !== undefined
|
||||
);
|
||||
}
|
||||
|
||||
/** Only current members can read or write a DM or group DM. */
|
||||
export function canAccessDm(db: DB, userId: string, dmChannelId: string): boolean {
|
||||
return isDmMember(db, userId, dmChannelId);
|
||||
}
|
||||
|
||||
/** Current members, longest-standing first. */
|
||||
export function dmMemberIds(db: DB, dmChannelId: string): string[] {
|
||||
return (
|
||||
db
|
||||
.prepare('SELECT user_id FROM dm_members WHERE dm_channel_id = ? ORDER BY joined_at, rowid')
|
||||
.all(dmChannelId) as { user_id: string }[]
|
||||
).map((r) => r.user_id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Who can DM whom (PLAN story 4, spam limit): two different users who are both non-banned members
|
||||
* of at least one common server. Needed to open a new DM and to post/react/type in an existing one;
|
||||
* reading old DM history only needs canAccessDm.
|
||||
*/
|
||||
export function sharesServer(db: DB, userId: string, otherId: string): boolean {
|
||||
if (userId === otherId) return false;
|
||||
return (
|
||||
db
|
||||
.prepare(
|
||||
`SELECT 1 FROM members a JOIN members b ON b.server_id = a.server_id
|
||||
WHERE a.user_id = ? AND b.user_id = ? AND a.banned = 0 AND b.banned = 0 LIMIT 1`,
|
||||
)
|
||||
.get(userId, otherId) !== undefined
|
||||
);
|
||||
}
|
||||
|
||||
/** The other person in a 1:1 DM. */
|
||||
export const dmPartner = (dm: DmChannelRow, userId: string): string =>
|
||||
(dm.user_a === userId ? dm.user_b : dm.user_a) as string;
|
||||
|
||||
/**
|
||||
* D16 (QA-69) / D5: the one refusal for "you can't post in this 1:1 DM", whether the two no
|
||||
* longer share a server or one of them blocked the other. Same status, code and body for send,
|
||||
* edit, react, typing, pin and unpin, so a blocked person can't tell a block from a closed DM.
|
||||
* Never mentions blocking.
|
||||
*/
|
||||
export const cantSend = () => new HttpError(403, 'cant_send', "Couldn't send");
|
||||
/** D5: the same for calls (start, token) in a closed or blocked 1:1 DM. */
|
||||
export const cantCall = () => new HttpError(403, 'cant_call', "Couldn't call");
|
||||
/** D5: adding someone to a group, or creating one with them, when either blocked the other. */
|
||||
export const cantAdd = () => new HttpError(403, 'cant_add', "Couldn't add");
|
||||
|
||||
/**
|
||||
* A member who may send: in a 1:1 DM the two must still share a server and neither may have
|
||||
* blocked the other (M18, D4), else `refuse()` (cantSend by default; cantCall for calls). In a
|
||||
* group, being a current member is enough (leaving or removal takes away all access instead;
|
||||
* blocks in groups are hidden by the client, D3).
|
||||
* This is THE send check for DMs: sending, editing, reacting, typing, pinning, unpinning and
|
||||
* calls all use it (MessageService.conv with post, CallService, the socket's typing handler).
|
||||
*/
|
||||
export function requireDmPost(
|
||||
db: DB,
|
||||
userId: string,
|
||||
dmChannelId: string,
|
||||
refuse: () => HttpError = cantSend,
|
||||
): DmChannelRow {
|
||||
const dm = requireDmAccess(db, userId, dmChannelId);
|
||||
if (dm.kind === 'dm' && !canPostInDm(db, userId, dm)) throw refuse();
|
||||
return dm;
|
||||
}
|
||||
|
||||
/** The rule behind requireDmPost for a 1:1 (also DmDto.canMessage). Groups: always true. */
|
||||
export function canPostInDm(db: DB, userId: string, dm: DmChannelRow): boolean {
|
||||
if (dm.kind !== 'dm') return true;
|
||||
const other = dmPartner(dm, userId);
|
||||
return sharesServer(db, userId, other) && !Blocks.for(db).between(userId, other);
|
||||
}
|
||||
|
||||
export function requireDmAccess(db: DB, userId: string, dmChannelId: string): DmChannelRow {
|
||||
const dm = db.prepare('SELECT * FROM dm_channels WHERE id = ?').get(dmChannelId) as
|
||||
DmChannelRow | undefined;
|
||||
if (!dm || !isDmMember(db, userId, dmChannelId)) throw notFound('Conversation not found');
|
||||
return dm;
|
||||
}
|
||||
|
||||
export interface MessageAuthRow {
|
||||
id: string;
|
||||
channel_id: string | null;
|
||||
dm_channel_id: string | null;
|
||||
author_id: string;
|
||||
deleted_at: string | null;
|
||||
}
|
||||
|
||||
/** Can the user read the message (it's in a channel/DM they can access)? */
|
||||
export function canReadMessage(db: DB, userId: string, messageId: string): boolean {
|
||||
const m = db
|
||||
.prepare(
|
||||
'SELECT id, channel_id, dm_channel_id, author_id, deleted_at FROM messages WHERE id = ?',
|
||||
)
|
||||
.get(messageId) as MessageAuthRow | undefined;
|
||||
if (!m || m.deleted_at) return false;
|
||||
return m.channel_id
|
||||
? canAccessChannel(db, userId, m.channel_id)
|
||||
: canAccessDm(db, userId, m.dm_channel_id as string);
|
||||
}
|
||||
|
||||
/** Only the author can edit. */
|
||||
export function canEditMessage(db: DB, userId: string, messageId: string): boolean {
|
||||
const m = db.prepare('SELECT author_id, deleted_at FROM messages WHERE id = ?').get(messageId) as
|
||||
{ author_id: string; deleted_at: string | null } | undefined;
|
||||
return (
|
||||
m !== undefined &&
|
||||
!m.deleted_at &&
|
||||
m.author_id === userId &&
|
||||
canReadMessage(db, userId, messageId)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Authors can delete their own while they can VIEW the channel (D47); deleting someone else's
|
||||
* needs MANAGE_MESSAGES in that channel (thread replies: the parent channel, D39).
|
||||
*/
|
||||
export function canDeleteMessage(db: DB, userId: string, messageId: string): boolean {
|
||||
const m = db
|
||||
.prepare(
|
||||
'SELECT id, channel_id, dm_channel_id, author_id, deleted_at FROM messages WHERE id = ?',
|
||||
)
|
||||
.get(messageId) as MessageAuthRow | undefined;
|
||||
if (!m || m.deleted_at || !canReadMessage(db, userId, messageId)) return false;
|
||||
if (m.author_id === userId) return true;
|
||||
if (!m.channel_id) return false;
|
||||
return (Access.for(db).channelPerms(userId, m.channel_id) & Perm.MANAGE_MESSAGES) !== 0;
|
||||
}
|
||||
|
||||
export interface CategoryRow {
|
||||
id: string;
|
||||
server_id: string;
|
||||
name: string;
|
||||
position: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the category or throws 404 (missing / not a member); with `bits` (server scope, e.g.
|
||||
* MANAGE_CHANNELS), 403 for members without them. Category names aren't secret (D45).
|
||||
*/
|
||||
export function requireCategoryAccess(
|
||||
db: DB,
|
||||
userId: string,
|
||||
categoryId: string,
|
||||
bits = 0,
|
||||
): CategoryRow {
|
||||
const category = db.prepare('SELECT * FROM categories WHERE id = ?').get(categoryId) as
|
||||
CategoryRow | undefined;
|
||||
if (!category) throw notFound('Category not found');
|
||||
Access.for(db).requireServerPerm(userId, category.server_id, bits);
|
||||
return category;
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import type { FastifyReply, FastifyRequest, preHandlerHookHandler } from 'fastify';
|
||||
import { forbidden, unauthorized } from '../lib/errors.js';
|
||||
import type { UserRow } from '../services/users.js';
|
||||
|
||||
export const SESSION_COOKIE = 'sid';
|
||||
|
||||
declare module 'fastify' {
|
||||
interface FastifyRequest {
|
||||
/** Set by the onRequest hook when a valid session cookie is present. */
|
||||
user: UserRow | null;
|
||||
}
|
||||
}
|
||||
|
||||
/** preHandler: 401 unless logged in. */
|
||||
export const requireAuth: preHandlerHookHandler = async (
|
||||
req: FastifyRequest,
|
||||
_reply: FastifyReply,
|
||||
) => {
|
||||
if (!req.user) throw unauthorized();
|
||||
};
|
||||
|
||||
/** preHandler: 401 unless logged in, 403 unless instance admin. */
|
||||
export const requireInstanceAdmin: preHandlerHookHandler = async (
|
||||
req: FastifyRequest,
|
||||
_reply: FastifyReply,
|
||||
) => {
|
||||
if (!req.user) throw unauthorized();
|
||||
if (req.user.is_instance_admin !== 1) throw forbidden('Only the instance admin can do that');
|
||||
};
|
||||
|
||||
/** Narrow req.user after requireAuth ran. */
|
||||
export function currentUser(req: FastifyRequest): UserRow {
|
||||
if (!req.user) throw unauthorized();
|
||||
return req.user;
|
||||
}
|
||||
@@ -0,0 +1,356 @@
|
||||
import { cleanDisplayText, STATUS_SWEEP_MS } from '@chat/shared';
|
||||
import { existsSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { parsePushAllow } from './lib/push-endpoint.js';
|
||||
|
||||
export type CookieSecureMode = 'auto' | 'always' | 'never';
|
||||
|
||||
export const DEFAULT_APP_NAME = 'Doghouse';
|
||||
export const DEFAULT_PUBLIC_URL = 'https://doghouse.snoooopy.online';
|
||||
|
||||
export interface AppConfig {
|
||||
/** APP_NAME: shown in the UI title and auth screen. */
|
||||
appName: string;
|
||||
/** NODE_ENV=production: strict origin check (PUBLIC_URL only). */
|
||||
production: boolean;
|
||||
/** PUBLIC_URL origin, e.g. https://doghouse.snoooopy.online */
|
||||
publicUrl: string;
|
||||
/** LIVEKIT_PUBLIC_URL (milestone 5), default wss://<public host>/livekit */
|
||||
livekitPublicUrl: string;
|
||||
host: string;
|
||||
port: number;
|
||||
/** SQLite file path, or ':memory:' for tests. */
|
||||
dbPath: string;
|
||||
/** Directory with the built frontend (index.html). null = do not serve static files. */
|
||||
staticDir: string | null;
|
||||
/** Where uploaded files are stored (random names, no extensions). Default DATA_DIR/uploads. */
|
||||
uploadsDir: string;
|
||||
/** Profile/server/group images from the media pipeline (M7). Default DATA_DIR/media. */
|
||||
mediaDir: string;
|
||||
/** 'auto' sets Secure when the request arrived over HTTPS (honours X-Forwarded-Proto). */
|
||||
cookieSecure: CookieSecureMode;
|
||||
/**
|
||||
* Number of reverse-proxy hops to trust for X-Forwarded-For/-Proto/-Host (QA-1). Default 1 = our
|
||||
* nginx container. The client IP is then the entry nginx added, never a client-supplied one.
|
||||
* 0 = trust nothing (app exposed directly).
|
||||
*/
|
||||
trustProxy: number;
|
||||
/**
|
||||
* Origins allowed for state-changing requests and socket handshakes. Production: only PUBLIC_URL.
|
||||
* Dev/test: PUBLIC_URL + ALLOWED_ORIGINS, and same-host origins are accepted as well.
|
||||
*/
|
||||
allowedOrigins: string[];
|
||||
sessionTtlDays: number;
|
||||
rateLimit: {
|
||||
enabled: boolean;
|
||||
authMax: number;
|
||||
authWindowMs: number;
|
||||
/** Messages per user per window (POST messages). Edits/reactions/uploads get their own buckets. */
|
||||
messageMax: number;
|
||||
messageWindowMs: number;
|
||||
};
|
||||
logLevel: string;
|
||||
/** MAX_UPLOAD_MB: default upload limit (admins can change it later in instance settings). */
|
||||
maxUploadMb: number;
|
||||
/** How long a user stays visible after their last socket closes before going offline. */
|
||||
presenceGraceMs: number;
|
||||
/** D49: how often expired custom status text is cleared and broadcast. */
|
||||
statusSweepMs: number;
|
||||
/** LiveKit (milestone 5). Voice is off when apiKey/apiSecret are empty. */
|
||||
livekit: LivekitConfig;
|
||||
/**
|
||||
* VIDEO_ENABLED (story 16, default on): webcams in voice channels and DM calls. One flag drives
|
||||
* the Permissions-Policy header (`permissionsPolicy`), the LiveKit grants
|
||||
* (`canPublishSourcesFor`) and the client UI (instance info), so they can't disagree.
|
||||
*/
|
||||
videoEnabled: boolean;
|
||||
/** CALL_RING_TIMEOUT_MS: how long a DM call rings before it's missed (default 30 s). */
|
||||
callRingMs: number;
|
||||
/** M12 web push. */
|
||||
push: PushConfig;
|
||||
}
|
||||
|
||||
export interface PushConfig {
|
||||
/** Where the generated VAPID pair lives (DATA_DIR/vapid.json); null = keep it in memory (tests). */
|
||||
vapidPath: string | null;
|
||||
/** VAPID_PUBLIC_KEY / VAPID_PRIVATE_KEY overrides. */
|
||||
vapidPublicKey?: string;
|
||||
vapidPrivateKey?: string;
|
||||
/** PUSH_ENDPOINT_ALLOW: extra allowed push hosts. */
|
||||
allow: string[];
|
||||
/** Tests only (NODE_ENV=test): origins of a local mock push service. */
|
||||
testOrigins: string[];
|
||||
}
|
||||
|
||||
export interface LivekitConfig {
|
||||
/** LIVEKIT_API_KEY */
|
||||
apiKey: string;
|
||||
/** LIVEKIT_API_SECRET, at least 32 characters. */
|
||||
apiSecret: string;
|
||||
/** LIVEKIT_URL: how the app reaches LiveKit's API (server-to-server), e.g. http://doghouse-livekit:7880 */
|
||||
url: string;
|
||||
/**
|
||||
* What browsers connect to. Production (or LIVEKIT_PUBLIC_URL set): livekitPublicUrl. Development
|
||||
* without LIVEKIT_PUBLIC_URL: '' = same origin `/livekit` (the Vite proxy strips the prefix).
|
||||
*/
|
||||
clientUrl: string;
|
||||
/** Token lifetime in seconds (DESIGN decisions log: 10 minutes). */
|
||||
tokenTtlSec: number;
|
||||
}
|
||||
|
||||
export const LIVEKIT_MIN_SECRET = 32;
|
||||
|
||||
/** Validates the LIVEKIT_* variables. Both key and secret empty = voice disabled. */
|
||||
export function parseLivekit(
|
||||
env: NodeJS.ProcessEnv,
|
||||
livekitPublicUrl: string,
|
||||
production: boolean,
|
||||
) {
|
||||
const apiKey = env.LIVEKIT_API_KEY?.trim() ?? '';
|
||||
const apiSecret = env.LIVEKIT_API_SECRET?.trim() ?? '';
|
||||
if (!!apiKey !== !!apiSecret) {
|
||||
throw new Error(
|
||||
'Set both LIVEKIT_API_KEY and LIVEKIT_API_SECRET (or neither to turn voice off)',
|
||||
);
|
||||
}
|
||||
if (apiSecret && apiSecret.length < LIVEKIT_MIN_SECRET) {
|
||||
throw new Error(`LIVEKIT_API_SECRET must be at least ${LIVEKIT_MIN_SECRET} characters`);
|
||||
}
|
||||
const url = (env.LIVEKIT_URL?.trim() || 'http://doghouse-livekit:7880').replace(/\/$/, '');
|
||||
if (!/^https?:\/\//.test(url)) {
|
||||
throw new Error(`LIVEKIT_URL must start with http:// or https://, got "${url}"`);
|
||||
}
|
||||
const explicit = !!env.LIVEKIT_PUBLIC_URL?.trim();
|
||||
return {
|
||||
apiKey,
|
||||
apiSecret,
|
||||
url,
|
||||
clientUrl: production || explicit ? livekitPublicUrl : '',
|
||||
tokenTtlSec: 600,
|
||||
} satisfies LivekitConfig;
|
||||
}
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
function defaultStaticDir(): string | null {
|
||||
const candidates = [
|
||||
path.resolve(process.cwd(), 'public'),
|
||||
path.resolve(here, '../public'),
|
||||
path.resolve(here, '../../web/dist'),
|
||||
];
|
||||
return candidates.find((d) => existsSync(path.join(d, 'index.html'))) ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* TRUST_PROXY_HOPS: integer hop count (QA-1, DESIGN decisions log). Default 1 (our nginx); 0 when
|
||||
* the app is reached directly; 2 with a CDN in front of nginx. Booleans are rejected on purpose:
|
||||
* "trust every hop" would let clients spoof X-Forwarded-For.
|
||||
*/
|
||||
export function parseTrustProxyHops(v: string | undefined): number {
|
||||
if (v === undefined || v.trim() === '') return 1;
|
||||
const n = Number(v.trim());
|
||||
if (!/^\d+$/.test(v.trim()) || n > 10) {
|
||||
throw new Error(`TRUST_PROXY_HOPS must be a whole number of proxy hops (0-10), got "${v}"`);
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
/** APP_NAME, cleaned like any display name; falls back to "Doghouse". */
|
||||
/** Normalise PUBLIC_URL to an origin (scheme://host[:port]); throws on anything that isn't http(s). */
|
||||
export function parsePublicUrl(v: string | undefined): string {
|
||||
const raw = (v ?? '').trim() || DEFAULT_PUBLIC_URL;
|
||||
let u: URL;
|
||||
try {
|
||||
u = new URL(raw);
|
||||
} catch {
|
||||
throw new Error(`PUBLIC_URL must be a URL like ${DEFAULT_PUBLIC_URL}, got "${raw}"`);
|
||||
}
|
||||
if (u.protocol !== 'https:' && u.protocol !== 'http:') {
|
||||
throw new Error(
|
||||
`PUBLIC_URL must start with https:// (or http:// for local testing), got "${raw}"`,
|
||||
);
|
||||
}
|
||||
return u.origin;
|
||||
}
|
||||
|
||||
export function parseAppName(v: string | undefined): string {
|
||||
const name = cleanDisplayText(v ?? '');
|
||||
return name ? [...name].slice(0, 32).join('') : DEFAULT_APP_NAME;
|
||||
}
|
||||
|
||||
function bool(v: string | undefined, fallback: boolean): boolean {
|
||||
if (v === undefined || v === '') return fallback;
|
||||
return ['1', 'true', 'yes', 'on'].includes(v.toLowerCase());
|
||||
}
|
||||
|
||||
/** DB_PATH, else DATA_DIR/chat.db (DATA_DIR defaults to ./data). Also used by scripts. */
|
||||
export function resolveDbPath(env: NodeJS.ProcessEnv = process.env): string {
|
||||
return env.DB_PATH ?? path.resolve(env.DATA_DIR ?? './data', 'chat.db');
|
||||
}
|
||||
|
||||
export function loadConfig(env: NodeJS.ProcessEnv = process.env): AppConfig {
|
||||
const secure = (env.COOKIE_SECURE ?? 'auto').toLowerCase();
|
||||
const cookieSecure: CookieSecureMode =
|
||||
secure === 'true' || secure === 'always'
|
||||
? 'always'
|
||||
: secure === 'false' || secure === 'never'
|
||||
? 'never'
|
||||
: 'auto';
|
||||
const dataDir = env.DATA_DIR ?? './data';
|
||||
const production = env.NODE_ENV === 'production';
|
||||
const publicUrl = parsePublicUrl(env.PUBLIC_URL);
|
||||
const extraOrigins = (env.ALLOWED_ORIGINS ?? '')
|
||||
.split(',')
|
||||
.map((s) => s.trim().replace(/\/$/, ''))
|
||||
.filter(Boolean);
|
||||
const livekitPublicUrl =
|
||||
env.LIVEKIT_PUBLIC_URL?.trim() || `${publicUrl.replace(/^http/, 'ws')}/livekit`;
|
||||
return {
|
||||
appName: parseAppName(env.APP_NAME),
|
||||
production,
|
||||
publicUrl,
|
||||
livekitPublicUrl,
|
||||
host: env.HOST ?? '0.0.0.0',
|
||||
port: Number(env.PORT ?? 3000),
|
||||
dbPath: resolveDbPath(env),
|
||||
staticDir: env.STATIC_DIR ?? defaultStaticDir(),
|
||||
uploadsDir: path.resolve(env.UPLOADS_DIR ?? path.join(dataDir, 'uploads')),
|
||||
mediaDir: path.resolve(env.MEDIA_DIR ?? path.join(dataDir, 'media')),
|
||||
cookieSecure,
|
||||
trustProxy: parseTrustProxyHops(env.TRUST_PROXY_HOPS),
|
||||
allowedOrigins: production ? [publicUrl] : [publicUrl, ...extraOrigins],
|
||||
sessionTtlDays: Number(env.SESSION_TTL_DAYS ?? 30),
|
||||
rateLimit: {
|
||||
enabled: bool(env.RATE_LIMIT, true),
|
||||
authMax: Number(env.AUTH_RATE_LIMIT_MAX ?? 10),
|
||||
authWindowMs: Number(env.AUTH_RATE_LIMIT_WINDOW_MS ?? 60_000),
|
||||
messageMax: Number(env.MESSAGE_RATE_LIMIT_MAX ?? 10),
|
||||
messageWindowMs: Number(env.MESSAGE_RATE_LIMIT_WINDOW_MS ?? 10_000),
|
||||
},
|
||||
logLevel: env.LOG_LEVEL ?? 'info',
|
||||
presenceGraceMs: Number(env.PRESENCE_GRACE_MS ?? 10_000),
|
||||
statusSweepMs: Number(env.STATUS_SWEEP_MS ?? STATUS_SWEEP_MS),
|
||||
maxUploadMb: parseMaxUploadMb(env.MAX_UPLOAD_MB),
|
||||
livekit: parseLivekit(env, livekitPublicUrl, production),
|
||||
videoEnabled: parseFlag('VIDEO_ENABLED', env.VIDEO_ENABLED, true),
|
||||
callRingMs: parseRingMs(env.CALL_RING_TIMEOUT_MS),
|
||||
push: {
|
||||
vapidPath: path.resolve(dataDir, 'vapid.json'),
|
||||
vapidPublicKey: env.VAPID_PUBLIC_KEY?.trim() || undefined,
|
||||
vapidPrivateKey: env.VAPID_PRIVATE_KEY?.trim() || undefined,
|
||||
allow: parsePushAllow(env.PUSH_ENDPOINT_ALLOW),
|
||||
// Only ever honoured under NODE_ENV=test.
|
||||
testOrigins:
|
||||
env.NODE_ENV === 'test'
|
||||
? (env.PUSH_TEST_ORIGINS ?? '')
|
||||
.split(',')
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean)
|
||||
: [],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** A strict on/off variable: true/false/1/0/yes/no/on/off; anything else is a startup error. */
|
||||
export function parseFlag(name: string, v: string | undefined, fallback: boolean): boolean {
|
||||
const raw = (v ?? '').trim().toLowerCase();
|
||||
if (!raw) return fallback;
|
||||
if (['1', 'true', 'yes', 'on'].includes(raw)) return true;
|
||||
if (['0', 'false', 'no', 'off'].includes(raw)) return false;
|
||||
throw new Error(`${name} must be true or false, got "${v}"`);
|
||||
}
|
||||
|
||||
/** CALL_RING_TIMEOUT_MS: 1 s to 5 min, default 30 s (tests shorten it). */
|
||||
export function parseRingMs(v: string | undefined): number {
|
||||
const raw = (v ?? '').trim();
|
||||
if (!raw) return 30_000;
|
||||
const n = Number(raw);
|
||||
if (!Number.isInteger(n) || n < 1000 || n > 300_000) {
|
||||
throw new Error(
|
||||
`CALL_RING_TIMEOUT_MS must be whole milliseconds from 1000 to 300000, got "${raw}"`,
|
||||
);
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
/**
|
||||
* The one place the webcam flag becomes a Permissions-Policy header (DESIGN-0.2 section 6):
|
||||
* `camera=(self)` when video is on, `camera=()` when it's off. Microphone and screen capture are
|
||||
* always allowed for the site itself.
|
||||
*/
|
||||
export function permissionsPolicy(config: Pick<AppConfig, 'videoEnabled'>): string {
|
||||
return [
|
||||
'microphone=(self)',
|
||||
'display-capture=(self)',
|
||||
'fullscreen=(self)',
|
||||
'autoplay=(self)',
|
||||
config.videoEnabled ? 'camera=(self)' : 'camera=()',
|
||||
'geolocation=()',
|
||||
'payment=()',
|
||||
'usb=()',
|
||||
].join(', ');
|
||||
}
|
||||
|
||||
/** LiveKit track sources a voice or call token may publish (same flag as the header). */
|
||||
export type PublishSource = 'microphone' | 'screen_share' | 'screen_share_audio' | 'camera';
|
||||
export function canPublishSourcesFor(config: Pick<AppConfig, 'videoEnabled'>): PublishSource[] {
|
||||
const base: PublishSource[] = ['microphone', 'screen_share', 'screen_share_audio'];
|
||||
return config.videoEnabled ? [...base, 'camera'] : base;
|
||||
}
|
||||
|
||||
/** MAX_UPLOAD_MB: whole megabytes, 1..1024, default 25. */
|
||||
export function parseMaxUploadMb(v: string | undefined): number {
|
||||
const raw = (v ?? '').trim();
|
||||
if (!raw) return 25;
|
||||
const n = Number(raw);
|
||||
if (!Number.isInteger(n) || n < 1 || n > 1024) {
|
||||
throw new Error(
|
||||
`MAX_UPLOAD_MB must be a whole number of megabytes from 1 to 1024, got "${raw}"`,
|
||||
);
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
/** Config for tests: in-memory DB, no static files, rate limiting off unless asked for. */
|
||||
export function testConfig(overrides: Partial<AppConfig> = {}): AppConfig {
|
||||
return {
|
||||
appName: DEFAULT_APP_NAME,
|
||||
production: false,
|
||||
publicUrl: 'http://localhost:3000',
|
||||
livekitPublicUrl: 'ws://localhost:3000/livekit',
|
||||
host: '127.0.0.1',
|
||||
port: 0,
|
||||
dbPath: ':memory:',
|
||||
staticDir: null,
|
||||
uploadsDir: path.join(tmpdir(), `chat-test-uploads-${process.pid}`),
|
||||
mediaDir: path.join(tmpdir(), `chat-test-media-${process.pid}`),
|
||||
cookieSecure: 'auto',
|
||||
trustProxy: 1,
|
||||
allowedOrigins: [],
|
||||
sessionTtlDays: 30,
|
||||
rateLimit: {
|
||||
enabled: false,
|
||||
authMax: 10,
|
||||
authWindowMs: 60_000,
|
||||
messageMax: 10,
|
||||
messageWindowMs: 10_000,
|
||||
},
|
||||
logLevel: 'silent',
|
||||
presenceGraceMs: 30,
|
||||
statusSweepMs: STATUS_SWEEP_MS,
|
||||
maxUploadMb: 25,
|
||||
livekit: {
|
||||
apiKey: 'testkey',
|
||||
apiSecret: 'test-secret-that-is-at-least-32-characters-long',
|
||||
url: 'http://127.0.0.1:7880',
|
||||
clientUrl: 'ws://localhost:3000/livekit',
|
||||
tokenTtlSec: 600,
|
||||
},
|
||||
videoEnabled: true,
|
||||
callRingMs: 30_000,
|
||||
push: { vapidPath: null, allow: [], testOrigins: [] },
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
/**
|
||||
* M25 (D25): thread replies keep their channel's `channel_id` and set `thread_id`, so every query
|
||||
* about a server channel's own messages must leave them out. These helpers are the only place the
|
||||
* condition is written (conv-sql.test.ts fails if a service writes it by hand or forgets it).
|
||||
*/
|
||||
|
||||
/** Where a message lives. A thread's id is also its conversation id (read states, pins, drafts). */
|
||||
export type ConvKind = 'channel' | 'dm' | 'thread';
|
||||
|
||||
/** Main channel messages only: not a reply inside one of the channel's threads. */
|
||||
export const mainOnly = (alias = ''): string => `${alias ? `${alias}.` : ''}thread_id IS NULL`;
|
||||
|
||||
/**
|
||||
* The SQL condition for "this message is in this conversation", with exactly one `?` for the
|
||||
* conversation id. A channel is its main messages (mainOnly); a thread is its replies.
|
||||
*/
|
||||
export function convWhere(kind: ConvKind, alias = ''): string {
|
||||
const a = alias ? `${alias}.` : '';
|
||||
if (kind === 'thread') return `${a}thread_id = ?`;
|
||||
if (kind === 'dm') return `${a}dm_channel_id = ?`;
|
||||
return `${a}channel_id = ? AND ${mainOnly(alias)}`;
|
||||
}
|
||||
|
||||
/** The same test as convWhere, on a row already read. */
|
||||
export function inConv(
|
||||
m: { channel_id: string | null; dm_channel_id: string | null; thread_id?: string | null },
|
||||
kind: ConvKind,
|
||||
id: string,
|
||||
): boolean {
|
||||
if (kind === 'thread') return m.thread_id === id;
|
||||
if (kind === 'dm') return m.dm_channel_id === id;
|
||||
return m.channel_id === id && (m.thread_id ?? null) === null;
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { EVERYONE_DEFAULT_PERMS } from '@chat/shared';
|
||||
import { newId, nowIso } from '../lib/ids.js';
|
||||
import type { DB } from './index.js';
|
||||
|
||||
/**
|
||||
* D42: give every server that has no `@everyone` role one, with today's member rights (95).
|
||||
* Runs inside migration 011's transaction (the backfill) and again at start-up (belt and braces
|
||||
* for hand-made data). Returns how many were created. Idempotent: the partial unique index
|
||||
* `idx_roles_everyone` allows one per server.
|
||||
*/
|
||||
export function ensureEveryoneRoles(db: DB): number {
|
||||
const missing = db
|
||||
.prepare(
|
||||
`SELECT s.id FROM servers s
|
||||
WHERE NOT EXISTS (SELECT 1 FROM roles r WHERE r.server_id = s.id AND r.is_everyone = 1)`,
|
||||
)
|
||||
.all() as { id: string }[];
|
||||
if (missing.length === 0) return 0;
|
||||
const insert = db.prepare(
|
||||
`INSERT INTO roles (id, server_id, name, color, position, permissions, is_everyone, created_at)
|
||||
VALUES (?, ?, '@everyone', NULL, 0, ?, 1, ?)`,
|
||||
);
|
||||
const now = nowIso();
|
||||
db.transaction(() => {
|
||||
for (const s of missing) insert.run(newId(), s.id, EVERYONE_DEFAULT_PERMS, now);
|
||||
})();
|
||||
return missing.length;
|
||||
}
|
||||
|
||||
/** `ServerService.create`: the new server's `@everyone`, inside the caller's transaction. */
|
||||
export function insertEveryoneRole(db: DB, serverId: string, now = nowIso()): string {
|
||||
const id = newId();
|
||||
db.prepare(
|
||||
`INSERT INTO roles (id, server_id, name, color, position, permissions, is_everyone, created_at)
|
||||
VALUES (?, ?, '@everyone', NULL, 0, ?, 1, ?)`,
|
||||
).run(id, serverId, EVERYONE_DEFAULT_PERMS, now);
|
||||
return id;
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
import Database from 'better-sqlite3';
|
||||
import { mkdirSync, readdirSync, readFileSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { ensureEveryoneRoles } from './everyone.js';
|
||||
|
||||
export type DB = Database.Database;
|
||||
|
||||
const MIGRATIONS_DIR = fileURLToPath(new URL('./migrations', import.meta.url));
|
||||
|
||||
/** Open the database with the pragmas we rely on, then apply pending migrations. */
|
||||
export function openDb(dbPath: string): DB {
|
||||
if (dbPath !== ':memory:') mkdirSync(path.dirname(dbPath), { recursive: true });
|
||||
const db = new Database(dbPath);
|
||||
db.pragma('journal_mode = WAL');
|
||||
db.pragma('foreign_keys = ON');
|
||||
db.pragma('synchronous = NORMAL');
|
||||
db.pragma('busy_timeout = 5000');
|
||||
migrate(db);
|
||||
return db;
|
||||
}
|
||||
|
||||
/** QA-122 (D34): why `openExistingDb` refused a path. */
|
||||
export class NoDatabaseError extends Error {}
|
||||
|
||||
/**
|
||||
* Open the server's existing database for a maintenance command (rebuild-search): the file must
|
||||
* already exist and have a `messages` table, so a wrong DATA_DIR or DB_PATH is refused instead
|
||||
* of creating and migrating an empty `chat.db` (QA-122). Same pragmas and migrations as `openDb`.
|
||||
*/
|
||||
export function openExistingDb(dbPath: string): DB {
|
||||
let db: DB;
|
||||
try {
|
||||
db = new Database(dbPath, { fileMustExist: true });
|
||||
} catch {
|
||||
throw new NoDatabaseError(
|
||||
`No database at ${dbPath}. Set DATA_DIR (or DB_PATH) to the server's data folder.`,
|
||||
);
|
||||
}
|
||||
const hasMessages = db
|
||||
.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'messages'")
|
||||
.get();
|
||||
if (!hasMessages) {
|
||||
db.close();
|
||||
throw new NoDatabaseError(`${dbPath} is not a Doghouse database (it has no messages table).`);
|
||||
}
|
||||
db.pragma('journal_mode = WAL');
|
||||
db.pragma('foreign_keys = ON');
|
||||
db.pragma('synchronous = NORMAL');
|
||||
db.pragma('busy_timeout = 5000');
|
||||
migrate(db);
|
||||
return db;
|
||||
}
|
||||
|
||||
/**
|
||||
* JS steps that run right after a migration's SQL, inside the same transaction (D42: ULIDs can't be
|
||||
* made in plain SQL, so 011's `@everyone` backfill lives here).
|
||||
*/
|
||||
const JS_STEPS: Record<string, (db: DB) => unknown> = {
|
||||
'011_roles_status.sql': ensureEveryoneRoles,
|
||||
};
|
||||
|
||||
const ADD_COLUMN = /^\s*ALTER\s+TABLE\s+"?(\w+)"?\s+ADD\s+COLUMN\s+"?(\w+)"?[^;]*;/gim;
|
||||
|
||||
/**
|
||||
* Drop `ALTER TABLE t ADD COLUMN c ...;` statements whose column already exists, so additive
|
||||
* migrations can be re-applied safely (e.g. a database whose schema_migrations row was lost, or a
|
||||
* partly hand-migrated copy). Everything else in the file runs unchanged.
|
||||
*/
|
||||
export function skipExistingColumns(db: DB, sql: string): string {
|
||||
return sql.replace(ADD_COLUMN, (stmt, table: string, column: string) => {
|
||||
const cols = db.prepare(`SELECT name FROM pragma_table_info(?)`).all(table) as {
|
||||
name: string;
|
||||
}[];
|
||||
return cols.some((c) => c.name.toLowerCase() === column.toLowerCase())
|
||||
? `-- skipped, column exists: ${table}.${column}`
|
||||
: stmt;
|
||||
});
|
||||
}
|
||||
|
||||
const BLOCK = /^--\s*@begin unless-column (\w+)\.(\w+)\s*$([\s\S]*?)^--\s*@end\s*$/gm;
|
||||
|
||||
/**
|
||||
* `-- @begin unless-column t.c` ... `-- @end`: drop the block if table t already has column c
|
||||
* (a rebuild that has already happened, e.g. migration 006 re-applied after a lost
|
||||
* schema_migrations row).
|
||||
*/
|
||||
export function skipDoneBlocks(db: DB, sql: string): string {
|
||||
return sql.replace(BLOCK, (_all, table: string, column: string, body: string) => {
|
||||
const cols = db.prepare(`SELECT name FROM pragma_table_info(?)`).all(table) as {
|
||||
name: string;
|
||||
}[];
|
||||
return cols.some((c) => c.name.toLowerCase() === column.toLowerCase())
|
||||
? `-- skipped, column exists: ${table}.${column}`
|
||||
: body;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply plain-SQL migrations (NNN_name.sql) in order, each inside a transaction.
|
||||
*
|
||||
* A file whose first line is `-- @foreign-keys: off` runs with foreign keys off (needed to rebuild
|
||||
* a table other tables reference, so the DROP can't cascade). PRAGMA foreign_keys can't change
|
||||
* inside a transaction, so it's switched around it, and PRAGMA foreign_key_check must come back
|
||||
* empty before the migration commits.
|
||||
*/
|
||||
export function migrate(db: DB, dir = MIGRATIONS_DIR): string[] {
|
||||
db.exec(
|
||||
'CREATE TABLE IF NOT EXISTS schema_migrations (version TEXT PRIMARY KEY, applied_at TEXT NOT NULL)',
|
||||
);
|
||||
const applied = new Set(
|
||||
db
|
||||
.prepare('SELECT version FROM schema_migrations')
|
||||
.all()
|
||||
.map((r) => (r as { version: string }).version),
|
||||
);
|
||||
const files = readdirSync(dir)
|
||||
.filter((f) => /^\d+_.+\.sql$/.test(f))
|
||||
.sort();
|
||||
const ran: string[] = [];
|
||||
for (const file of files) {
|
||||
if (applied.has(file)) continue;
|
||||
const sql = readFileSync(path.join(dir, file), 'utf8');
|
||||
const fkOff = /^--\s*@foreign-keys:\s*off\s*$/m.test(sql.split('\n', 1)[0] ?? '');
|
||||
const fkWasOn = db.pragma('foreign_keys', { simple: true }) === 1;
|
||||
if (fkOff && fkWasOn) db.pragma('foreign_keys = OFF');
|
||||
try {
|
||||
db.transaction(() => {
|
||||
db.exec(skipExistingColumns(db, skipDoneBlocks(db, sql)));
|
||||
JS_STEPS[file]?.(db);
|
||||
if (fkOff) {
|
||||
const problems = db.pragma('foreign_key_check') as unknown[];
|
||||
if (problems.length) {
|
||||
throw new Error(`${file}: foreign key check failed: ${JSON.stringify(problems)}`);
|
||||
}
|
||||
}
|
||||
db.prepare('INSERT INTO schema_migrations (version, applied_at) VALUES (?, ?)').run(
|
||||
file,
|
||||
new Date().toISOString(),
|
||||
);
|
||||
}).immediate();
|
||||
} finally {
|
||||
if (fkOff && fkWasOn) db.pragma('foreign_keys = ON');
|
||||
}
|
||||
ran.push(file);
|
||||
}
|
||||
return ran;
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
-- Full v1 data model (DESIGN.md section 4). All ids are ULIDs (TEXT) unless noted.
|
||||
-- Timestamps are ISO-8601 UTC strings.
|
||||
|
||||
CREATE TABLE users (
|
||||
id TEXT PRIMARY KEY,
|
||||
username TEXT NOT NULL COLLATE NOCASE UNIQUE,
|
||||
display_name TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
avatar_path TEXT,
|
||||
status TEXT NOT NULL DEFAULT 'offline' CHECK (status IN ('online', 'idle', 'offline')),
|
||||
theme_json TEXT,
|
||||
created_at TEXT NOT NULL,
|
||||
is_instance_admin INTEGER NOT NULL DEFAULT 0 CHECK (is_instance_admin IN (0, 1))
|
||||
);
|
||||
|
||||
-- id is the SHA-256 (hex) of the cookie token, so a leaked DB does not leak live sessions.
|
||||
CREATE TABLE sessions (
|
||||
id TEXT PRIMARY KEY,
|
||||
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
expires_at TEXT NOT NULL,
|
||||
user_agent TEXT,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX idx_sessions_user ON sessions(user_id);
|
||||
CREATE INDEX idx_sessions_expires ON sessions(expires_at);
|
||||
|
||||
CREATE TABLE instance_settings (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL
|
||||
);
|
||||
INSERT INTO instance_settings (key, value) VALUES ('registration_open', 'true'), ('max_upload_mb', '25');
|
||||
|
||||
CREATE TABLE servers (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
icon_path TEXT,
|
||||
owner_id TEXT NOT NULL REFERENCES users(id),
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE members (
|
||||
server_id TEXT NOT NULL REFERENCES servers(id) ON DELETE CASCADE,
|
||||
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
role TEXT NOT NULL DEFAULT 'member' CHECK (role IN ('owner', 'admin', 'member')),
|
||||
joined_at TEXT NOT NULL,
|
||||
banned INTEGER NOT NULL DEFAULT 0 CHECK (banned IN (0, 1)),
|
||||
PRIMARY KEY (server_id, user_id)
|
||||
);
|
||||
CREATE INDEX idx_members_user ON members(user_id);
|
||||
|
||||
-- server_id NULL = instance-level invite (lets someone register while registration is closed).
|
||||
CREATE TABLE invites (
|
||||
code TEXT PRIMARY KEY,
|
||||
server_id TEXT REFERENCES servers(id) ON DELETE CASCADE,
|
||||
created_by TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
max_uses INTEGER,
|
||||
uses INTEGER NOT NULL DEFAULT 0,
|
||||
expires_at TEXT,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX idx_invites_server ON invites(server_id);
|
||||
|
||||
CREATE TABLE categories (
|
||||
id TEXT PRIMARY KEY,
|
||||
server_id TEXT NOT NULL REFERENCES servers(id) ON DELETE CASCADE,
|
||||
name TEXT NOT NULL,
|
||||
position INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
CREATE INDEX idx_categories_server ON categories(server_id, position);
|
||||
|
||||
-- Deleting a category moves its channels to "no category" instead of orphaning/deleting them.
|
||||
CREATE TABLE channels (
|
||||
id TEXT PRIMARY KEY,
|
||||
server_id TEXT NOT NULL REFERENCES servers(id) ON DELETE CASCADE,
|
||||
category_id TEXT REFERENCES categories(id) ON DELETE SET NULL,
|
||||
type TEXT NOT NULL CHECK (type IN ('text', 'voice')),
|
||||
name TEXT NOT NULL,
|
||||
position INTEGER NOT NULL DEFAULT 0,
|
||||
topic TEXT
|
||||
);
|
||||
CREATE INDEX idx_channels_server ON channels(server_id, position);
|
||||
|
||||
CREATE TABLE dm_channels (
|
||||
id TEXT PRIMARY KEY,
|
||||
user_a TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
user_b TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
created_at TEXT NOT NULL,
|
||||
CHECK (user_a < user_b),
|
||||
UNIQUE (user_a, user_b)
|
||||
);
|
||||
CREATE INDEX idx_dm_user_b ON dm_channels(user_b);
|
||||
|
||||
-- Exactly one of channel_id / dm_channel_id is set.
|
||||
CREATE TABLE messages (
|
||||
id TEXT PRIMARY KEY,
|
||||
channel_id TEXT REFERENCES channels(id) ON DELETE CASCADE,
|
||||
dm_channel_id TEXT REFERENCES dm_channels(id) ON DELETE CASCADE,
|
||||
author_id TEXT NOT NULL REFERENCES users(id),
|
||||
content TEXT NOT NULL DEFAULT '',
|
||||
reply_to_id TEXT REFERENCES messages(id) ON DELETE SET NULL,
|
||||
edited_at TEXT,
|
||||
deleted_at TEXT,
|
||||
created_at TEXT NOT NULL,
|
||||
CHECK ((channel_id IS NULL) <> (dm_channel_id IS NULL))
|
||||
);
|
||||
CREATE INDEX idx_messages_channel ON messages(channel_id, id);
|
||||
CREATE INDEX idx_messages_dm ON messages(dm_channel_id, id);
|
||||
|
||||
CREATE TABLE attachments (
|
||||
id TEXT PRIMARY KEY,
|
||||
message_id TEXT REFERENCES messages(id) ON DELETE CASCADE,
|
||||
uploader_id TEXT NOT NULL REFERENCES users(id),
|
||||
path TEXT NOT NULL,
|
||||
filename TEXT NOT NULL,
|
||||
mime TEXT NOT NULL,
|
||||
size INTEGER NOT NULL,
|
||||
width INTEGER,
|
||||
height INTEGER,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX idx_attachments_message ON attachments(message_id);
|
||||
|
||||
CREATE TABLE reactions (
|
||||
message_id TEXT NOT NULL REFERENCES messages(id) ON DELETE CASCADE,
|
||||
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
emoji TEXT NOT NULL,
|
||||
PRIMARY KEY (message_id, user_id, emoji)
|
||||
);
|
||||
|
||||
-- channel_id holds either a server channel id or a dm_channel id (both ULIDs, no collision).
|
||||
CREATE TABLE read_states (
|
||||
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
channel_id TEXT NOT NULL,
|
||||
last_read_message_id TEXT,
|
||||
PRIMARY KEY (user_id, channel_id)
|
||||
);
|
||||
@@ -0,0 +1,12 @@
|
||||
-- Milestone 4: DMs and presence.
|
||||
|
||||
-- Who opened the conversation. The other participant only sees it once it has a message,
|
||||
-- so opening a DM never pings anyone.
|
||||
ALTER TABLE dm_channels ADD COLUMN created_by TEXT REFERENCES users(id) ON DELETE SET NULL;
|
||||
|
||||
-- The status a user picked. The live status (online/idle/offline) is in memory only, so a
|
||||
-- restart never leaves ghosts; users.status from 001 is unused.
|
||||
ALTER TABLE users ADD COLUMN presence TEXT NOT NULL DEFAULT 'online'
|
||||
CHECK (presence IN ('online', 'idle', 'dnd', 'invisible'));
|
||||
|
||||
CREATE INDEX idx_dm_user_a ON dm_channels(user_a);
|
||||
@@ -0,0 +1,4 @@
|
||||
-- M6: the upload limit defaults to MAX_UPLOAD_MB from .env (also the ceiling, matching the proxy's
|
||||
-- client_max_body_size). Drop the old seeded default so the env value applies; a value an admin
|
||||
-- set explicitly (anything but the old default) is kept.
|
||||
DELETE FROM instance_settings WHERE key = 'max_upload_mb' AND value = '25';
|
||||
@@ -0,0 +1,10 @@
|
||||
-- M7 (0.2): profiles and display pictures (DESIGN-0.2 section 1). Additive only: 0.1.x code
|
||||
-- ignores these columns, so rolling back means restoring the 0.1.2 build (see CHANGES-M7.md).
|
||||
-- Each ADD COLUMN is skipped by the migrator if the column already exists, so re-running this
|
||||
-- file (e.g. after restoring an older schema_migrations table) is safe.
|
||||
-- avatar_media replaces the never-used avatar_path (left in place, always NULL).
|
||||
ALTER TABLE users ADD COLUMN avatar_media TEXT;
|
||||
ALTER TABLE users ADD COLUMN banner_media TEXT;
|
||||
ALTER TABLE users ADD COLUMN banner_color TEXT CHECK (banner_color IS NULL OR banner_color GLOB '#[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f]');
|
||||
ALTER TABLE users ADD COLUMN about TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE users ADD COLUMN pronouns TEXT NOT NULL DEFAULT '';
|
||||
@@ -0,0 +1,9 @@
|
||||
-- M8 (0.2): server icons and banners on the shared media pipeline (DESIGN-0.2 sections 0 and 2).
|
||||
-- Additive only. Each ADD COLUMN is skipped by the migrator if the column already exists.
|
||||
-- 0.1 icons (servers.icon_path, a file in the uploads dir) can't be converted in SQL: the app
|
||||
-- converts them at startup (services/server-media.ts, convertLegacyServerIcons), only for rows
|
||||
-- with icon_path set and icon_media still NULL, so it is idempotent. The 0.1 file and icon_path
|
||||
-- are kept so a rollback to 0.1.2 still shows the icon; both are cleared when an admin changes or
|
||||
-- removes the icon in 0.2.
|
||||
ALTER TABLE servers ADD COLUMN icon_media TEXT;
|
||||
ALTER TABLE servers ADD COLUMN banner_media TEXT;
|
||||
@@ -0,0 +1,70 @@
|
||||
-- @foreign-keys: off
|
||||
-- M9 (0.2): group DMs (DESIGN-0.2 sections 3 and 6).
|
||||
--
|
||||
-- dm_channels is rebuilt (SQLite can't drop NOT NULL in place) with the standard copy, drop,
|
||||
-- rename steps. The migrator runs this file with foreign keys off (the "@foreign-keys: off" line)
|
||||
-- so dropping the old table can't cascade into DM messages, then runs PRAGMA foreign_key_check
|
||||
-- before committing. messages.dm_channel_id still says REFERENCES dm_channels(id), which now
|
||||
-- resolves to the new table. The rebuild block is skipped if dm_channels already has `kind`, and
|
||||
-- everything else is IF NOT EXISTS / OR IGNORE / skipped-if-present, so re-applying this file
|
||||
-- (e.g. a lost schema_migrations row) changes nothing.
|
||||
--
|
||||
-- Rollback to 0.1.2 needs the 0.1.2 database backup: 0.1.2 can read 1:1 DMs from this schema
|
||||
-- (same columns), but it doesn't know groups. See CHANGES-M9.md.
|
||||
|
||||
-- @begin unless-column dm_channels.kind
|
||||
CREATE TABLE dm_channels_new (
|
||||
id TEXT PRIMARY KEY,
|
||||
kind TEXT NOT NULL DEFAULT 'dm' CHECK (kind IN ('dm', 'group')),
|
||||
user_a TEXT REFERENCES users(id) ON DELETE CASCADE,
|
||||
user_b TEXT REFERENCES users(id) ON DELETE CASCADE,
|
||||
name TEXT,
|
||||
icon_media TEXT,
|
||||
owner_id TEXT REFERENCES users(id) ON DELETE SET NULL,
|
||||
created_by TEXT REFERENCES users(id) ON DELETE SET NULL,
|
||||
created_at TEXT NOT NULL,
|
||||
CHECK (kind = 'group' OR (user_a IS NOT NULL AND user_b IS NOT NULL AND user_a < user_b)),
|
||||
CHECK (kind = 'dm' OR (user_a IS NULL AND user_b IS NULL))
|
||||
);
|
||||
INSERT INTO dm_channels_new (id, kind, user_a, user_b, created_by, created_at)
|
||||
SELECT id, 'dm', user_a, user_b, created_by, created_at FROM dm_channels;
|
||||
DROP TABLE dm_channels;
|
||||
ALTER TABLE dm_channels_new RENAME TO dm_channels;
|
||||
-- One 1:1 DM per pair (the old UNIQUE(user_a, user_b), now for kind = 'dm' only).
|
||||
CREATE UNIQUE INDEX idx_dm_pair ON dm_channels(user_a, user_b) WHERE kind = 'dm';
|
||||
CREATE INDEX idx_dm_user_b ON dm_channels(user_b) WHERE kind = 'dm';
|
||||
-- @end
|
||||
|
||||
-- Membership for both kinds: every access check goes through this table alone.
|
||||
CREATE TABLE IF NOT EXISTS dm_members (
|
||||
dm_channel_id TEXT NOT NULL REFERENCES dm_channels(id) ON DELETE CASCADE,
|
||||
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
joined_at TEXT NOT NULL,
|
||||
PRIMARY KEY (dm_channel_id, user_id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_dm_members_user ON dm_members(user_id, dm_channel_id);
|
||||
INSERT OR IGNORE INTO dm_members (dm_channel_id, user_id, joined_at)
|
||||
SELECT id, user_a, created_at FROM dm_channels WHERE kind = 'dm';
|
||||
INSERT OR IGNORE INTO dm_members (dm_channel_id, user_id, joined_at)
|
||||
SELECT id, user_b, created_at FROM dm_channels WHERE kind = 'dm';
|
||||
|
||||
-- Who left or was removed (section 6): a leaver can't be re-added by anyone; someone the owner
|
||||
-- removed can be re-added only by the owner (removed_by is set). Cleared when they're re-added.
|
||||
CREATE TABLE IF NOT EXISTS dm_departures (
|
||||
dm_channel_id TEXT NOT NULL REFERENCES dm_channels(id) ON DELETE CASCADE,
|
||||
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
left_at TEXT NOT NULL,
|
||||
removed_by TEXT REFERENCES users(id) ON DELETE SET NULL,
|
||||
PRIMARY KEY (dm_channel_id, user_id)
|
||||
);
|
||||
|
||||
-- Private media (section 6): a scoped id is served only to current members of its group.
|
||||
CREATE TABLE IF NOT EXISTS media_scopes (
|
||||
media_id TEXT PRIMARY KEY,
|
||||
dm_channel_id TEXT NOT NULL REFERENCES dm_channels(id) ON DELETE CASCADE
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_media_scopes_dm ON media_scopes(dm_channel_id);
|
||||
|
||||
-- System messages (joins, leaves, renames, ...): rendered from system_json, never from content.
|
||||
ALTER TABLE messages ADD COLUMN type TEXT NOT NULL DEFAULT 'default' CHECK (type IN ('default', 'system'));
|
||||
ALTER TABLE messages ADD COLUMN system_json TEXT;
|
||||
@@ -0,0 +1,16 @@
|
||||
-- M10: DM and group calls (DESIGN-0.2 section 4). Additive and idempotent: safe to re-apply.
|
||||
-- One row per call. answered = someone other than the caller picked up (accept or joined).
|
||||
CREATE TABLE IF NOT EXISTS calls (
|
||||
id TEXT PRIMARY KEY,
|
||||
dm_channel_id TEXT NOT NULL REFERENCES dm_channels(id) ON DELETE CASCADE,
|
||||
started_by TEXT NOT NULL REFERENCES users(id),
|
||||
started_at TEXT NOT NULL,
|
||||
ended_at TEXT,
|
||||
answered INTEGER NOT NULL DEFAULT 0 CHECK (answered IN (0, 1))
|
||||
);
|
||||
|
||||
-- At most one active call per DM, enforced by the database (concurrent starts from both sides).
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_calls_one_active
|
||||
ON calls (dm_channel_id) WHERE ended_at IS NULL;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_calls_dm ON calls (dm_channel_id, started_at);
|
||||
@@ -0,0 +1,33 @@
|
||||
-- M12: web push (DESIGN-0.3 section 2). Additive and idempotent: safe to re-apply.
|
||||
CREATE TABLE IF NOT EXISTS push_subscriptions (
|
||||
id TEXT PRIMARY KEY,
|
||||
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
endpoint TEXT NOT NULL UNIQUE,
|
||||
p256dh TEXT NOT NULL,
|
||||
auth TEXT NOT NULL,
|
||||
device_label TEXT,
|
||||
user_agent TEXT,
|
||||
created_at TEXT NOT NULL,
|
||||
last_success_at TEXT,
|
||||
last_error_at TEXT,
|
||||
enabled INTEGER NOT NULL DEFAULT 1 CHECK (enabled IN (0, 1))
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_push_user ON push_subscriptions (user_id);
|
||||
|
||||
-- Per-scope levels. scope_id is a server id, a channel id or a DM id; no foreign key on purpose
|
||||
-- (a row for a scope that is gone does nothing and is cleaned up when the user is deleted).
|
||||
CREATE TABLE IF NOT EXISTS notification_prefs (
|
||||
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
scope_type TEXT NOT NULL CHECK (scope_type IN ('server', 'channel', 'dm')),
|
||||
scope_id TEXT NOT NULL,
|
||||
level TEXT NOT NULL CHECK (level IN ('all', 'mentions', 'none')),
|
||||
PRIMARY KEY (user_id, scope_type, scope_id)
|
||||
);
|
||||
|
||||
ALTER TABLE users ADD COLUMN notif_show_content INTEGER NOT NULL DEFAULT 1;
|
||||
ALTER TABLE users ADD COLUMN notif_dnd INTEGER NOT NULL DEFAULT 0;
|
||||
ALTER TABLE users ADD COLUMN quiet_start TEXT;
|
||||
ALTER TABLE users ADD COLUMN quiet_end TEXT;
|
||||
ALTER TABLE users ADD COLUMN quiet_tz TEXT;
|
||||
-- JSON array of user ids mentioned, resolved on the server at send time (never taken from the client).
|
||||
ALTER TABLE messages ADD COLUMN mentions_json TEXT;
|
||||
@@ -0,0 +1,24 @@
|
||||
-- 0.4 (DESIGN-0.4 decision D1): pinned messages (M17) and blocking (M18) in one additive
|
||||
-- migration. Idempotent: safe to re-apply. 0.3 ignores both tables, so a rollback is "restore the
|
||||
-- backup" or simply run 0.3 on this database.
|
||||
|
||||
-- Pins (section 3). conv_id is a server channel id or a dm_channel id, like read_states.
|
||||
-- Messages are soft-deleted, so the delete path also removes the pin in the same transaction;
|
||||
-- the cascade covers hard deletes and channel or DM removal.
|
||||
CREATE TABLE IF NOT EXISTS pins (
|
||||
message_id TEXT PRIMARY KEY REFERENCES messages(id) ON DELETE CASCADE,
|
||||
conv_id TEXT NOT NULL,
|
||||
pinned_by TEXT REFERENCES users(id) ON DELETE SET NULL,
|
||||
pinned_at TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_pins_conv ON pins(conv_id, pinned_at);
|
||||
|
||||
-- Blocks (section 4): used from M18.
|
||||
CREATE TABLE IF NOT EXISTS blocks (
|
||||
blocker_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
blocked_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
created_at TEXT NOT NULL,
|
||||
PRIMARY KEY (blocker_id, blocked_id),
|
||||
CHECK (blocker_id <> blocked_id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_blocks_blocked ON blocks(blocked_id);
|
||||
@@ -0,0 +1,107 @@
|
||||
-- 0.5 (DESIGN-0.5 section 0): the one migration for search (D26), custom emoji (D27) and threads
|
||||
-- (D25). It only adds things; no table is rebuilt. Safe to re-apply (a lost schema_migrations
|
||||
-- row): every CREATE has IF NOT EXISTS, the ADD COLUMN is skipped when the column exists, and the
|
||||
-- search index (and search_rowids) is emptied before it is filled again.
|
||||
--
|
||||
-- Rollback to 0.4.1 on this data: 0.4.1 ignores these tables and the new column. The search
|
||||
-- triggers keep running under 0.4.1 (they are part of the database), so the index stays in step
|
||||
-- and upgrading again needs no rebuild.
|
||||
|
||||
-- ---- Threads (D25, section 4a). Created first: messages.thread_id refers to it. ----
|
||||
CREATE TABLE IF NOT EXISTS threads (
|
||||
id TEXT PRIMARY KEY, -- ULID; also the conv id for read states, pins, drafts
|
||||
channel_id TEXT NOT NULL REFERENCES channels(id) ON DELETE CASCADE,
|
||||
parent_message_id TEXT NOT NULL UNIQUE REFERENCES messages(id) ON DELETE CASCADE,
|
||||
name TEXT NOT NULL, -- defaults to the first 60 chars of the parent
|
||||
created_by TEXT REFERENCES users(id) ON DELETE SET NULL,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
-- Not in the design text: "the channel's threads, newest activity first" (4e) needs a lookup by
|
||||
-- channel, and deleting a channel cascades through it.
|
||||
CREATE INDEX IF NOT EXISTS idx_threads_channel ON threads(channel_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS thread_follows (
|
||||
thread_id TEXT NOT NULL REFERENCES threads(id) ON DELETE CASCADE,
|
||||
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
following INTEGER NOT NULL,
|
||||
PRIMARY KEY (thread_id, user_id)
|
||||
);
|
||||
|
||||
-- Replies keep their channel_id (the CHECK on messages stays as it is) and add the thread id.
|
||||
ALTER TABLE messages ADD COLUMN thread_id TEXT REFERENCES threads(id) ON DELETE CASCADE;
|
||||
CREATE INDEX IF NOT EXISTS idx_messages_thread ON messages(thread_id, id) WHERE thread_id IS NOT NULL;
|
||||
CREATE INDEX IF NOT EXISTS idx_messages_channel_main ON messages(channel_id, id) WHERE thread_id IS NULL;
|
||||
|
||||
-- QA-116 (D32): deleting a channel nulls reply_to_id on every reply into it (ON DELETE SET NULL),
|
||||
-- which was a full scan of messages per deleted message without this index.
|
||||
CREATE INDEX IF NOT EXISTS idx_messages_reply_to ON messages(reply_to_id) WHERE reply_to_id IS NOT NULL;
|
||||
|
||||
-- ---- Custom server emoji (D27, section 3a) ----
|
||||
CREATE TABLE IF NOT EXISTS custom_emoji (
|
||||
id TEXT PRIMARY KEY, -- ULID, what messages and reactions refer to
|
||||
server_id TEXT NOT NULL REFERENCES servers(id) ON DELETE CASCADE,
|
||||
name TEXT NOT NULL COLLATE NOCASE, -- 2-32 of [A-Za-z0-9_]
|
||||
media_id TEXT NOT NULL,
|
||||
animated INTEGER NOT NULL DEFAULT 0,
|
||||
created_by TEXT REFERENCES users(id) ON DELETE SET NULL,
|
||||
created_at TEXT NOT NULL,
|
||||
UNIQUE (server_id, name)
|
||||
);
|
||||
|
||||
-- ---- Search (D26, section 2a) ----
|
||||
-- An external-content FTS5 index over messages.content: it stores the index, not a second copy
|
||||
-- of the text. Only normal messages that aren't deleted are in it. Each trigger has the same
|
||||
-- condition, so the index never gets an entry it can't remove.
|
||||
CREATE VIRTUAL TABLE IF NOT EXISTS messages_fts USING fts5(
|
||||
content,
|
||||
content='messages',
|
||||
content_rowid='rowid',
|
||||
tokenize='unicode61 remove_diacritics 2'
|
||||
);
|
||||
|
||||
-- D32 (QA-111): which message each indexed rowid belonged to when it was indexed. messages has a
|
||||
-- TEXT primary key, so its rowid can be renumbered (VACUUM, a dump and restore); comparing this
|
||||
-- table with messages at start finds that, and the server rebuilds both. The same triggers keep
|
||||
-- it in step with messages_fts (also under 0.4.1 after a rollback).
|
||||
CREATE TABLE IF NOT EXISTS search_rowids (
|
||||
rowid INTEGER PRIMARY KEY,
|
||||
message_id TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TRIGGER IF NOT EXISTS messages_fts_insert AFTER INSERT ON messages
|
||||
WHEN new.type = 'default' AND new.deleted_at IS NULL
|
||||
BEGIN
|
||||
INSERT INTO messages_fts(rowid, content) VALUES (new.rowid, new.content);
|
||||
INSERT OR REPLACE INTO search_rowids(rowid, message_id) VALUES (new.rowid, new.id);
|
||||
END;
|
||||
|
||||
CREATE TRIGGER IF NOT EXISTS messages_fts_update AFTER UPDATE OF content, deleted_at ON messages
|
||||
BEGIN
|
||||
INSERT INTO messages_fts(messages_fts, rowid, content)
|
||||
SELECT 'delete', old.rowid, old.content
|
||||
WHERE old.type = 'default' AND old.deleted_at IS NULL;
|
||||
DELETE FROM search_rowids
|
||||
WHERE rowid = old.rowid AND old.type = 'default' AND old.deleted_at IS NULL;
|
||||
INSERT INTO messages_fts(rowid, content)
|
||||
SELECT new.rowid, new.content
|
||||
WHERE new.type = 'default' AND new.deleted_at IS NULL;
|
||||
INSERT OR REPLACE INTO search_rowids(rowid, message_id)
|
||||
SELECT new.rowid, new.id
|
||||
WHERE new.type = 'default' AND new.deleted_at IS NULL;
|
||||
END;
|
||||
|
||||
CREATE TRIGGER IF NOT EXISTS messages_fts_delete AFTER DELETE ON messages
|
||||
WHEN old.type = 'default' AND old.deleted_at IS NULL
|
||||
BEGIN
|
||||
INSERT INTO messages_fts(messages_fts, rowid, content) VALUES ('delete', old.rowid, old.content);
|
||||
DELETE FROM search_rowids WHERE rowid = old.rowid;
|
||||
END;
|
||||
|
||||
-- Backfill: existing normal, non-deleted messages (not FTS5 'rebuild', which would index system
|
||||
-- messages too). 'delete-all' first, so a re-applied migration doesn't index anything twice.
|
||||
INSERT INTO messages_fts(messages_fts) VALUES ('delete-all');
|
||||
INSERT INTO messages_fts(rowid, content)
|
||||
SELECT rowid, content FROM messages WHERE type = 'default' AND deleted_at IS NULL;
|
||||
DELETE FROM search_rowids;
|
||||
INSERT INTO search_rowids(rowid, message_id)
|
||||
SELECT rowid, id FROM messages WHERE type = 'default' AND deleted_at IS NULL;
|
||||
@@ -0,0 +1,46 @@
|
||||
-- 0.6 (DESIGN-0.6 section 2, D42): roles, member roles, channel overrides (stories 28, 29) and the
|
||||
-- custom status columns (story 30). Additive only; nothing is rebuilt. Safe to re-apply (a lost
|
||||
-- schema_migrations row): every CREATE has IF NOT EXISTS and the ADD COLUMNs are skipped when the
|
||||
-- column exists.
|
||||
--
|
||||
-- @everyone for every existing server is inserted by the JS step that runs right after this file
|
||||
-- in the same transaction (db/everyone.ts: ULIDs can't be made in SQL), and again by the start-up
|
||||
-- check for any server that is missing one.
|
||||
--
|
||||
-- Rollback to 0.5.0 on this data (D43): 0.5.0 ignores these tables and columns and starts, BUT it
|
||||
-- has no private channels: every member can then read every private channel's history.
|
||||
|
||||
CREATE TABLE IF NOT EXISTS roles (
|
||||
id TEXT PRIMARY KEY,
|
||||
server_id TEXT NOT NULL REFERENCES servers(id) ON DELETE CASCADE,
|
||||
name TEXT NOT NULL,
|
||||
color TEXT CHECK (color IS NULL OR color GLOB '#[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f]'),
|
||||
position INTEGER NOT NULL,
|
||||
permissions INTEGER NOT NULL,
|
||||
is_everyone INTEGER NOT NULL DEFAULT 0 CHECK (is_everyone IN (0, 1)),
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_roles_server ON roles(server_id, position);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_roles_everyone ON roles(server_id) WHERE is_everyone = 1;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS member_roles (
|
||||
server_id TEXT NOT NULL,
|
||||
user_id TEXT NOT NULL,
|
||||
role_id TEXT NOT NULL REFERENCES roles(id) ON DELETE CASCADE,
|
||||
PRIMARY KEY (server_id, user_id, role_id),
|
||||
FOREIGN KEY (server_id, user_id) REFERENCES members(server_id, user_id) ON DELETE CASCADE
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_member_roles_role ON member_roles(role_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS channel_overrides (
|
||||
channel_id TEXT NOT NULL REFERENCES channels(id) ON DELETE CASCADE,
|
||||
role_id TEXT NOT NULL REFERENCES roles(id) ON DELETE CASCADE,
|
||||
allow INTEGER NOT NULL DEFAULT 0,
|
||||
deny INTEGER NOT NULL DEFAULT 0,
|
||||
CHECK ((allow & deny) = 0),
|
||||
PRIMARY KEY (channel_id, role_id)
|
||||
);
|
||||
|
||||
ALTER TABLE users ADD COLUMN status_text TEXT;
|
||||
ALTER TABLE users ADD COLUMN status_emoji TEXT;
|
||||
ALTER TABLE users ADD COLUMN status_expires_at TEXT;
|
||||
@@ -0,0 +1,37 @@
|
||||
import { NoDatabaseError, openExistingDb } from './index.js';
|
||||
import { rebuildSearchIndex } from './search-index.js';
|
||||
|
||||
export interface CommandOutput {
|
||||
log: (line: string) => void;
|
||||
error: (line: string) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* The rebuild-search command (D30, D32, D34): rebuild the message search index of the database
|
||||
* at `dbPath`. Refuses a missing file or one without a `messages` table (QA-122); waits for
|
||||
* another writer up to busy_timeout instead of failing at once (QA-123, `.immediate()`).
|
||||
* Returns the process exit code.
|
||||
*/
|
||||
export function rebuildSearchCommand(dbPath: string, out: CommandOutput = console): number {
|
||||
let db;
|
||||
try {
|
||||
db = openExistingDb(dbPath);
|
||||
} catch (err) {
|
||||
if (err instanceof NoDatabaseError) {
|
||||
out.error(err.message);
|
||||
return 1;
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
try {
|
||||
const started = Date.now();
|
||||
const n = rebuildSearchIndex(db);
|
||||
out.log(`Search index rebuilt: ${n} messages in ${Date.now() - started} ms (${dbPath})`);
|
||||
return 0;
|
||||
} catch (err) {
|
||||
out.error(`Search index not rebuilt: ${(err as Error).message} (${dbPath})`);
|
||||
return 1;
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import type { DB } from './index.js';
|
||||
|
||||
/**
|
||||
* The search index's contents (D26): every normal, non-deleted message, by its rowid. The same
|
||||
* condition as migration 010's triggers and backfill.
|
||||
*/
|
||||
export const SEARCHABLE = "type = 'default' AND deleted_at IS NULL";
|
||||
|
||||
/**
|
||||
* Empty the FTS5 index and `search_rowids` (D32) and fill both again from `messages`, exactly as
|
||||
* migration 010's backfill does ('delete-all', then INSERT ... SELECT), in one transaction. The
|
||||
* server does this at start when `checkSearchIndex` finds the index out of step; the
|
||||
* rebuild-search command runs it by hand. Returns how many messages were indexed.
|
||||
*
|
||||
* QA-123 (D34): an IMMEDIATE transaction takes the write lock up front, so while another
|
||||
* connection is writing it waits out `busy_timeout` instead of failing at once with
|
||||
* "database is locked" (a deferred one starts as a reader and can't wait to upgrade).
|
||||
*/
|
||||
export function rebuildSearchIndex(db: DB): number {
|
||||
return db
|
||||
.transaction(() => {
|
||||
db.prepare("INSERT INTO messages_fts(messages_fts) VALUES ('delete-all')").run();
|
||||
db.prepare('DELETE FROM search_rowids').run();
|
||||
db.prepare(
|
||||
`INSERT INTO search_rowids(rowid, message_id) SELECT rowid, id FROM messages WHERE ${SEARCHABLE}`,
|
||||
).run();
|
||||
return db
|
||||
.prepare(
|
||||
`INSERT INTO messages_fts(rowid, content) SELECT rowid, content FROM messages WHERE ${SEARCHABLE}`,
|
||||
)
|
||||
.run().changes;
|
||||
})
|
||||
.immediate();
|
||||
}
|
||||
|
||||
export type SearchIndexProblem = 'renumbered' | 'count';
|
||||
|
||||
/**
|
||||
* D32 (QA-111): is the index still about the rows it points at? messages has a TEXT primary key,
|
||||
* so its rowid is not a stable alias and a VACUUM or a dump and restore can renumber it. Any
|
||||
* `search_rowids` row whose messages row (by rowid, so an index lookup) is missing, has another
|
||||
* id, or is no longer searchable means the rowids moved; then the counts of searchable messages,
|
||||
* `search_rowids` and the FTS index's documents must agree. Rowid swaps and reordered rebuilds that
|
||||
* keep count, sum and max are caught by the id comparison. Returns the problem, or null.
|
||||
*/
|
||||
export function findSearchIndexProblem(db: DB): SearchIndexProblem | null {
|
||||
const moved = db
|
||||
.prepare(
|
||||
`SELECT 1 FROM search_rowids s LEFT JOIN messages m ON m.rowid = s.rowid
|
||||
WHERE m.id IS NULL OR m.id <> s.message_id OR NOT (m.type = 'default' AND m.deleted_at IS NULL)
|
||||
LIMIT 1`,
|
||||
)
|
||||
.get();
|
||||
if (moved) return 'renumbered';
|
||||
const c = db
|
||||
.prepare(
|
||||
`SELECT (SELECT count(*) FROM messages WHERE ${SEARCHABLE}) AS messages,
|
||||
(SELECT count(*) FROM search_rowids) AS rowids,
|
||||
(SELECT count(*) FROM messages_fts_docsize) AS fts`,
|
||||
)
|
||||
.get() as { messages: number; rowids: number; fts: number };
|
||||
return c.messages === c.rowids && c.rowids === c.fts ? null : 'count';
|
||||
}
|
||||
|
||||
export interface SearchIndexCheck {
|
||||
problem: SearchIndexProblem | null;
|
||||
/** Messages indexed by the rebuild, when there was one. */
|
||||
rebuilt: number | null;
|
||||
checkMs: number;
|
||||
rebuildMs: number;
|
||||
}
|
||||
|
||||
/** At start, after migrations: check, and rebuild both tables if anything is off. */
|
||||
export function checkSearchIndex(db: DB): SearchIndexCheck {
|
||||
const t0 = performance.now();
|
||||
const problem = findSearchIndexProblem(db);
|
||||
const t1 = performance.now();
|
||||
const rebuilt = problem ? rebuildSearchIndex(db) : null;
|
||||
return { problem, rebuilt, checkMs: t1 - t0, rebuildMs: performance.now() - t1 };
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { DB } from './index.js';
|
||||
|
||||
/**
|
||||
* D36 (QA-127): 0.4.1 doesn't know threads, so after a rollback a thread reply can be pinned
|
||||
* through its channel. Back on 0.5 that pin row still has the channel as `conv_id`, so it would
|
||||
* be listed nowhere, couldn't be unpinned and would take a hidden slot of the channel's 50. Run at
|
||||
* every start (like relocateEmoji): one UPDATE moves such pins to their thread. It's a no-op when
|
||||
* there is nothing to move. Moved pins don't count against the thread's limit (the limit only
|
||||
* applies to new pins), so none is ever cleared. Returns how many pins moved.
|
||||
*/
|
||||
export function relocateThreadPins(db: DB): number {
|
||||
return db
|
||||
.prepare(
|
||||
`UPDATE pins
|
||||
SET conv_id = (SELECT m.thread_id FROM messages m WHERE m.id = pins.message_id)
|
||||
WHERE EXISTS (SELECT 1 FROM messages m
|
||||
WHERE m.id = pins.message_id
|
||||
AND m.thread_id IS NOT NULL AND m.thread_id <> pins.conv_id)`,
|
||||
)
|
||||
.run().changes;
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { buildApp } from './app.js';
|
||||
import { loadConfig } from './config.js';
|
||||
import { attachSocket } from './realtime/socket.js';
|
||||
|
||||
const config = loadConfig();
|
||||
const app = await buildApp(config);
|
||||
attachSocket(app, config);
|
||||
|
||||
// Media folders no row points at (e.g. a crash between writing and swapping): startup + hourly.
|
||||
const sweepMedia = () => {
|
||||
try {
|
||||
app.services.media.sweep();
|
||||
} catch (err) {
|
||||
app.log.warn({ err }, 'media sweep failed');
|
||||
}
|
||||
};
|
||||
sweepMedia();
|
||||
|
||||
// Hourly housekeeping: expired sessions, never-sent uploads (24 h) and unreferenced files.
|
||||
const timer = setInterval(() => {
|
||||
app.services.auth.purgeExpiredSessions();
|
||||
try {
|
||||
app.services.uploads.purge();
|
||||
} catch (err) {
|
||||
app.log.warn({ err }, 'upload purge failed');
|
||||
}
|
||||
sweepMedia();
|
||||
}, 3_600_000);
|
||||
timer.unref();
|
||||
|
||||
for (const signal of ['SIGINT', 'SIGTERM'] as const) {
|
||||
process.on(signal, () => {
|
||||
void app.close().then(() => process.exit(0));
|
||||
});
|
||||
}
|
||||
|
||||
await app.listen({ host: config.host, port: config.port });
|
||||
app.log.info(`Static files: ${config.staticDir ?? '(none, API only)'}; DB: ${config.dbPath}`);
|
||||
@@ -0,0 +1,96 @@
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import type { BuildInfoDto } from '@chat/shared';
|
||||
|
||||
/**
|
||||
* Build info (D22, story 26). A packaged release has `build.json` at its root, written by
|
||||
* scripts/package.mjs from git; the server reads it once at start. A git checkout with no
|
||||
* build.json asks git (same rules as the packager); with neither, the commit is "dev".
|
||||
* The two rules below must match scripts/build-info.mjs (checked by build-info.test.ts).
|
||||
*/
|
||||
export const BUILD_HASH_LENGTH = 10;
|
||||
|
||||
/** Repo root (or /app in the image): apps/server/{src,dist}/lib -> four levels up. */
|
||||
export const APP_ROOT = path.resolve(import.meta.dirname, '..', '..', '..', '..');
|
||||
|
||||
/** `%ct` seconds as ISO 8601 UTC with a Z and no millis, e.g. 2026-11-20T03:14:00Z. */
|
||||
export function commitDateFromCt(ct: string): string | null {
|
||||
const s = ct.trim();
|
||||
if (!/^\d+$/.test(s)) return null;
|
||||
return new Date(Number(s) * 1000).toISOString().replace(/\.\d{3}Z$/, 'Z');
|
||||
}
|
||||
|
||||
/** The build hash: the first 10 characters of the full hash, never git's variable `--short`. */
|
||||
export function commitFromFullHash(full: string): string | null {
|
||||
const s = full.trim();
|
||||
return /^([0-9a-f]{40}|[0-9a-f]{64})$/.test(s) ? s.slice(0, BUILD_HASH_LENGTH) : null;
|
||||
}
|
||||
|
||||
const HASH = new RegExp(`^[0-9a-f]{${BUILD_HASH_LENGTH}}$`);
|
||||
const UTC_ISO = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/;
|
||||
|
||||
type Git = (...args: string[]) => string;
|
||||
|
||||
function gitIn(root: string): Git {
|
||||
return (...args) =>
|
||||
execFileSync('git', args, {
|
||||
cwd: root,
|
||||
encoding: 'utf8',
|
||||
stdio: ['ignore', 'pipe', 'ignore'],
|
||||
timeout: 5000,
|
||||
});
|
||||
}
|
||||
|
||||
export interface ReadBuildInfoOptions {
|
||||
version: string;
|
||||
root?: string;
|
||||
/** Test seam; null means "no git here". */
|
||||
git?: Git | null;
|
||||
log?: (msg: string) => void;
|
||||
}
|
||||
|
||||
/** Reads build.json, else git, else `{ commit: "dev", commitDate: null }`. Never throws. */
|
||||
export function readBuildInfo({
|
||||
version,
|
||||
root = APP_ROOT,
|
||||
git = gitIn(root),
|
||||
log,
|
||||
}: ReadBuildInfoOptions): BuildInfoDto {
|
||||
let text: string | null = null;
|
||||
try {
|
||||
text = readFileSync(path.join(root, 'build.json'), 'utf8');
|
||||
} catch {
|
||||
// No build.json: a git checkout or a hand-made tree.
|
||||
}
|
||||
if (text !== null) {
|
||||
try {
|
||||
const j = JSON.parse(text) as Partial<Record<keyof BuildInfoDto, unknown>>;
|
||||
if (
|
||||
typeof j.commit === 'string' &&
|
||||
HASH.test(j.commit) &&
|
||||
typeof j.commitDate === 'string' &&
|
||||
UTC_ISO.test(j.commitDate)
|
||||
) {
|
||||
return {
|
||||
version: typeof j.version === 'string' && j.version ? j.version : version,
|
||||
commit: j.commit,
|
||||
commitDate: j.commitDate,
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
// fall through
|
||||
}
|
||||
log?.('build.json is not valid; using git or "dev" instead');
|
||||
}
|
||||
if (git) {
|
||||
try {
|
||||
const commit = commitFromFullHash(git('rev-parse', 'HEAD'));
|
||||
const commitDate = commitDateFromCt(git('show', '-s', '--format=%ct', 'HEAD'));
|
||||
if (commit && commitDate) return { version, commit, commitDate };
|
||||
} catch {
|
||||
// No git, or not a repository.
|
||||
}
|
||||
}
|
||||
return { version, commit: 'dev', commitDate: null };
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { FastifyReply, FastifyRequest } from 'fastify';
|
||||
import type { Stats } from 'node:fs';
|
||||
|
||||
/**
|
||||
* Strong validator for a stored file. Stored files never change in place (a replaced image or a
|
||||
* new upload gets a new id), so the id plus size and mtime identifies the bytes exactly and leaks
|
||||
* nothing the requester doesn't already have.
|
||||
*/
|
||||
export function strongEtag(id: string, stat: Pick<Stats, 'size' | 'mtimeMs'>): string {
|
||||
return `"${id}-${stat.size.toString(16)}-${Math.trunc(stat.mtimeMs).toString(16)}"`;
|
||||
}
|
||||
|
||||
/**
|
||||
* True when the request's If-None-Match matches `etag` (RFC 9110 13.1.2: weak comparison, `*`
|
||||
* or a comma-separated list). Callers MUST run every access check before calling this: a 304 is
|
||||
* a statement that the requester may still see the file.
|
||||
*/
|
||||
export function notModified(req: FastifyRequest, etag: string): boolean {
|
||||
const header = req.headers['if-none-match'];
|
||||
if (typeof header !== 'string' || header.length === 0) return false;
|
||||
if (header.trim() === '*') return true;
|
||||
const bare = (t: string) => t.trim().replace(/^W\//, '');
|
||||
const want = bare(etag);
|
||||
return header.split(',').some((t) => bare(t) === want);
|
||||
}
|
||||
|
||||
/** Send a bodiless 304 carrying the validator and caching headers a 200 would have had. */
|
||||
export function sendNotModified(reply: FastifyReply, etag: string, cacheControl: string) {
|
||||
return reply.code(304).header('ETag', etag).header('Cache-Control', cacheControl).send();
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { SESSION_REQUIRED } from '@chat/shared';
|
||||
/** Error with an HTTP status that the global error handler turns into { error, message }. */
|
||||
export class HttpError extends Error {
|
||||
constructor(
|
||||
public readonly statusCode: number,
|
||||
public readonly code: string,
|
||||
message: string,
|
||||
public readonly details?: unknown,
|
||||
/** Extra response headers, e.g. Retry-After on a 429 (QA-77). */
|
||||
public readonly headers?: Record<string, string>,
|
||||
) {
|
||||
super(message);
|
||||
this.name = 'HttpError';
|
||||
}
|
||||
}
|
||||
|
||||
export const badRequest = (message: string, details?: unknown) =>
|
||||
new HttpError(400, 'bad_request', message, details);
|
||||
/** 401 for a missing or expired session only (SESSION_REQUIRED); the client logs out on it. */
|
||||
export const unauthorized = (message = 'You need to log in') =>
|
||||
new HttpError(401, SESSION_REQUIRED, message);
|
||||
/** A wrong username or password at login: 401, but not a lost session. */
|
||||
export const invalidCredentials = () =>
|
||||
new HttpError(401, 'invalid_credentials', 'Wrong username or password');
|
||||
export const forbidden = (message = 'You do not have permission to do that') =>
|
||||
new HttpError(403, 'forbidden', message);
|
||||
export const notFound = (message = 'Not found') => new HttpError(404, 'not_found', message);
|
||||
export const conflict = (message: string) => new HttpError(409, 'conflict', message);
|
||||
@@ -0,0 +1,119 @@
|
||||
/**
|
||||
* Upload helpers: magic-byte image detection with cheap dimension parsing, filename sanitising and
|
||||
* Content-Disposition. The client's declared MIME type is never trusted for serving.
|
||||
*/
|
||||
import path from 'node:path';
|
||||
|
||||
/** Types we serve inline. Everything else (including SVG, HTML, PDF) is served as a download. */
|
||||
export const INLINE_IMAGE_TYPES = ['image/png', 'image/jpeg', 'image/gif', 'image/webp'] as const;
|
||||
export type InlineImageType = (typeof INLINE_IMAGE_TYPES)[number];
|
||||
|
||||
export interface ImageInfo {
|
||||
mime: InlineImageType;
|
||||
width: number | null;
|
||||
height: number | null;
|
||||
}
|
||||
|
||||
const ascii = (buf: Buffer, start: number, end: number) => buf.toString('latin1', start, end);
|
||||
|
||||
/** Identify png/jpeg/gif/webp from the first bytes (64 KiB is plenty) and read the size if cheap. */
|
||||
export function sniffImage(head: Buffer): ImageInfo | null {
|
||||
if (
|
||||
head.length >= 24 &&
|
||||
head.readUInt32BE(0) === 0x89504e47 &&
|
||||
head.readUInt32BE(4) === 0x0d0a1a0a
|
||||
) {
|
||||
const ok = ascii(head, 12, 16) === 'IHDR';
|
||||
return {
|
||||
mime: 'image/png',
|
||||
width: ok ? head.readUInt32BE(16) : null,
|
||||
height: ok ? head.readUInt32BE(20) : null,
|
||||
};
|
||||
}
|
||||
if (head.length >= 10 && (ascii(head, 0, 6) === 'GIF87a' || ascii(head, 0, 6) === 'GIF89a')) {
|
||||
return { mime: 'image/gif', width: head.readUInt16LE(6), height: head.readUInt16LE(8) };
|
||||
}
|
||||
if (head.length >= 12 && ascii(head, 0, 4) === 'RIFF' && ascii(head, 8, 12) === 'WEBP') {
|
||||
return { mime: 'image/webp', ...webpSize(head) };
|
||||
}
|
||||
if (head.length >= 3 && head[0] === 0xff && head[1] === 0xd8 && head[2] === 0xff) {
|
||||
return { mime: 'image/jpeg', ...jpegSize(head) };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
type Size = { width: number | null; height: number | null };
|
||||
const NO_SIZE: Size = { width: null, height: null };
|
||||
|
||||
function webpSize(b: Buffer): Size {
|
||||
if (b.length < 30) return NO_SIZE;
|
||||
const chunk = ascii(b, 12, 16);
|
||||
if (chunk === 'VP8X') return { width: 1 + b.readUIntLE(24, 3), height: 1 + b.readUIntLE(27, 3) };
|
||||
if (chunk === 'VP8L' && b[20] === 0x2f) {
|
||||
const bits = b.readUInt32LE(21);
|
||||
return { width: (bits & 0x3fff) + 1, height: ((bits >> 14) & 0x3fff) + 1 };
|
||||
}
|
||||
if (chunk === 'VP8 ' && b[23] === 0x9d && b[24] === 0x01 && b[25] === 0x2a) {
|
||||
return { width: b.readUInt16LE(26) & 0x3fff, height: b.readUInt16LE(28) & 0x3fff };
|
||||
}
|
||||
return NO_SIZE;
|
||||
}
|
||||
|
||||
function jpegSize(b: Buffer): Size {
|
||||
let i = 2;
|
||||
while (i + 9 < b.length) {
|
||||
if (b[i] !== 0xff) return NO_SIZE;
|
||||
const marker = b[i + 1] as number;
|
||||
if (marker === 0xff) {
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
const len = b.readUInt16BE(i + 2);
|
||||
// SOF0-SOF15 except DHT (C4), JPG (C8) and DAC (CC) carry the frame size.
|
||||
if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc) {
|
||||
return { height: b.readUInt16BE(i + 5), width: b.readUInt16BE(i + 7) };
|
||||
}
|
||||
i += 2 + len;
|
||||
}
|
||||
return NO_SIZE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Display filename: basename only (no directories, either slash style), no control/bidi characters,
|
||||
* no leading dots, at most 200 characters. The stored path never uses this name.
|
||||
*/
|
||||
export function sanitizeFilename(name: string | undefined): string {
|
||||
const base = path.posix.basename((name ?? '').replace(/\\/g, '/'));
|
||||
const cleaned = base
|
||||
.normalize('NFC')
|
||||
.replace(
|
||||
// eslint-disable-next-line no-control-regex -- stripping control characters is the point
|
||||
/[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u202a-\u202e\u2066-\u2069\ufeff"<>:|?*]/g,
|
||||
'',
|
||||
)
|
||||
.replace(/^[.\s]+/, '')
|
||||
.trim();
|
||||
const chars = [...cleaned];
|
||||
if (chars.length === 0) return 'file';
|
||||
if (chars.length <= 200) return cleaned;
|
||||
const ext = path.extname(cleaned).slice(0, 16);
|
||||
return chars.slice(0, 200 - ext.length).join('') + ext;
|
||||
}
|
||||
|
||||
/** Declared MIME, kept only for display; anything malformed becomes octet-stream. */
|
||||
export function sanitizeMime(m: string | undefined): string {
|
||||
const v = (m ?? '').toLowerCase().split(';')[0]?.trim() ?? '';
|
||||
return /^[a-z0-9][a-z0-9!#$&^_.+-]{0,63}\/[a-z0-9][a-z0-9!#$&^_.+-]{0,63}$/.test(v)
|
||||
? v
|
||||
: 'application/octet-stream';
|
||||
}
|
||||
|
||||
/** RFC 6266 header with an ASCII fallback and a UTF-8 filename*. */
|
||||
export function contentDisposition(type: 'inline' | 'attachment', filename: string): string {
|
||||
const fallback = filename.replace(/[^\x20-\x7e]/g, '_').replace(/["\\]/g, '_');
|
||||
const encoded = encodeURIComponent(filename).replace(
|
||||
/['()*]/g,
|
||||
(c) => '%' + c.charCodeAt(0).toString(16).toUpperCase(),
|
||||
);
|
||||
return `${type}; filename="${fallback}"; filename*=UTF-8''${encoded}`;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { encodeTime, monotonicFactory } from 'ulid';
|
||||
|
||||
const next = monotonicFactory();
|
||||
|
||||
/** New ULID: time-sortable, safe to use as a pagination cursor. */
|
||||
export function newId(): string {
|
||||
return next();
|
||||
}
|
||||
|
||||
export function nowIso(): string {
|
||||
return new Date().toISOString();
|
||||
}
|
||||
|
||||
/** Smallest ULID for a moment in time: every id created at or after `iso` sorts >= this. */
|
||||
export function ulidFloor(iso: string): string {
|
||||
return encodeTime(new Date(iso).getTime(), 10) + '0'.repeat(16);
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
import { closeSync, fstatSync, openSync, readSync } from 'node:fs';
|
||||
import { crc32 } from 'node:zlib';
|
||||
import sharp from 'sharp';
|
||||
import { HttpError } from './errors.js';
|
||||
import type { ImageInfo } from './files.js';
|
||||
|
||||
/** Decompression-bomb guard (DESIGN decisions log): about 50 megapixels per frame/canvas. */
|
||||
export const MAX_IMAGE_PIXELS = 50_000_000;
|
||||
|
||||
// One image at a time is plenty for ~30 users, and keeps peak memory predictable.
|
||||
sharp.concurrency(1);
|
||||
sharp.cache(false);
|
||||
|
||||
export const imageTooLarge = () =>
|
||||
new HttpError(400, 'image_too_large', 'Images can be at most 50 megapixels');
|
||||
export const imageUnreadable = () =>
|
||||
new HttpError(400, 'bad_image', "That file looks like an image but couldn't be read");
|
||||
|
||||
export interface ScrubbedImage {
|
||||
size: number;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
/** First bytes of a file (enough for every header check below) and its size. */
|
||||
function readHead(file: string, max = 64 * 1024): { head: Buffer; size: number } {
|
||||
const fd = openSync(file, 'r');
|
||||
try {
|
||||
const buf = Buffer.alloc(max);
|
||||
return { head: buf.subarray(0, readSync(fd, buf, 0, max, 0)), size: fstatSync(fd).size };
|
||||
} finally {
|
||||
closeSync(fd);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Cheap structural check of the container header (QA-7): magic bytes alone don't make an image.
|
||||
* A file whose header is garbage must be reported as unreadable, not as "too large" because its
|
||||
* junk width/height bytes happen to be huge. Returns false when the header can't be a real image.
|
||||
*/
|
||||
export function headerIsPlausible(head: Buffer, mime: string, fileSize: number): boolean {
|
||||
switch (mime) {
|
||||
case 'image/png': {
|
||||
// Signature, then an IHDR chunk of length 13 with a valid CRC.
|
||||
if (head.length < 33 || head.readUInt32BE(8) !== 13) return false;
|
||||
if (head.toString('latin1', 12, 16) !== 'IHDR') return false;
|
||||
return crc32(head.subarray(12, 29)) === head.readUInt32BE(29);
|
||||
}
|
||||
case 'image/gif': {
|
||||
// Logical screen descriptor, optional global colour table, then an extension (0x21) or an
|
||||
// image descriptor (0x2c). Text after "GIF89a" fails this.
|
||||
if (head.length < 14) return false;
|
||||
if (head.readUInt16LE(6) === 0 || head.readUInt16LE(8) === 0) return false;
|
||||
const flags = head[10] as number;
|
||||
const table = flags & 0x80 ? 3 * 2 ** ((flags & 0x07) + 1) : 0;
|
||||
const next = head[13 + table];
|
||||
return next === 0x21 || next === 0x2c;
|
||||
}
|
||||
case 'image/webp': {
|
||||
// RIFF length must match the file (±1 padding byte), and the first chunk is VP8/VP8L/VP8X.
|
||||
if (head.length < 16) return false;
|
||||
const riff = head.readUInt32LE(4) + 8;
|
||||
if (Math.abs(riff - fileSize) > 1) return false;
|
||||
return ['VP8 ', 'VP8L', 'VP8X'].includes(head.toString('latin1', 12, 16));
|
||||
}
|
||||
default:
|
||||
// JPEG: sniffImage already walked the segment chain to find the frame header.
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-encode an uploaded image so no metadata survives (EXIF incl. GPS, XMP, IPTC, comments), in
|
||||
* its original format (detected from magic bytes, never the extension). `.rotate()` bakes the
|
||||
* EXIF orientation into the pixels first so photos still display upright. `animated: true` keeps
|
||||
* every frame of GIF/WebP animations. Throws 400 for oversized or undecodable images.
|
||||
*/
|
||||
export async function scrubImage(
|
||||
src: string,
|
||||
dest: string,
|
||||
sniffed: ImageInfo,
|
||||
): Promise<ScrubbedImage> {
|
||||
let file: { head: Buffer; size: number };
|
||||
try {
|
||||
file = readHead(src);
|
||||
} catch {
|
||||
throw imageUnreadable();
|
||||
}
|
||||
// Only a believable header gets to say "too large"; garbage is "couldn't read" (QA-7).
|
||||
if (!headerIsPlausible(file.head, sniffed.mime, file.size)) throw imageUnreadable();
|
||||
if ((sniffed.width ?? 0) * (sniffed.height ?? 0) > MAX_IMAGE_PIXELS) throw imageTooLarge();
|
||||
try {
|
||||
const img = sharp(src, {
|
||||
animated: true,
|
||||
limitInputPixels: MAX_IMAGE_PIXELS,
|
||||
failOn: 'error',
|
||||
});
|
||||
const meta = await img.metadata();
|
||||
// Animated images have no meaningful EXIF orientation, and rotating pages isn't supported.
|
||||
if ((meta.pages ?? 1) <= 1) img.rotate();
|
||||
switch (sniffed.mime) {
|
||||
case 'image/jpeg':
|
||||
img.jpeg({ quality: 90 });
|
||||
break;
|
||||
case 'image/png':
|
||||
img.png();
|
||||
break;
|
||||
case 'image/gif':
|
||||
img.gif();
|
||||
break;
|
||||
case 'image/webp':
|
||||
img.webp({ quality: 90 });
|
||||
break;
|
||||
}
|
||||
// No withMetadata()/keepExif(): sharp drops all metadata by default.
|
||||
const info = await img.toFile(dest);
|
||||
return { size: info.size, width: info.width, height: info.pageHeight ?? info.height };
|
||||
} catch (err) {
|
||||
if (err instanceof HttpError) throw err;
|
||||
if (/pixel limit/i.test((err as Error).message)) throw imageTooLarge();
|
||||
throw imageUnreadable();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import { cropSchema, MEDIA_KINDS, type CropRect, type MediaKind } from '@chat/shared';
|
||||
import type { FastifyRequest } from 'fastify';
|
||||
import type { MediaService } from '../services/media.js';
|
||||
import { badCrop, mediaTooLarge } from '../services/media.js';
|
||||
import { badRequest } from './errors.js';
|
||||
|
||||
/** Upload cap for a media kind: its own limit, never above the instance's MAX_UPLOAD_MB. */
|
||||
export function mediaLimitMb(kind: MediaKind, instanceMaxMb: number): number {
|
||||
return Math.min(MEDIA_KINDS[kind].maxMb, instanceMaxMb);
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a pipeline upload: multipart with a `crop` field (JSON {x, y, w, h}) and one `file` part,
|
||||
* in either order. The file is streamed to a temp file under the size cap. Returns the temp path
|
||||
* (the caller must media.discard() it) and the validated crop. Reused by every image route
|
||||
* (avatars and banners now; server icons/banners and group icons later).
|
||||
*/
|
||||
export async function receiveCroppedImage(
|
||||
req: FastifyRequest,
|
||||
media: MediaService,
|
||||
maxMb: number,
|
||||
/** Other short text fields the route takes (M24: an emoji's `name`). */
|
||||
extraFields: readonly string[] = [],
|
||||
): Promise<{ file: string; crop: CropRect; fields: Record<string, string> }> {
|
||||
if (!req.isMultipart()) throw badRequest('Send the image as multipart/form-data');
|
||||
const maxBytes = maxMb * 1024 * 1024;
|
||||
const declared = Number(req.headers['content-length'] ?? 0);
|
||||
// Cheap early reject; the streaming check is the real limit.
|
||||
if (declared > maxBytes + 64 * 1024) throw mediaTooLarge(maxMb);
|
||||
let file: string | null = null;
|
||||
let cropRaw: string | null = null;
|
||||
const fields: Record<string, string> = {};
|
||||
const nFields = 1 + extraFields.length;
|
||||
try {
|
||||
const parts = req.parts({
|
||||
limits: { fileSize: maxBytes, files: 1, fields: nFields, parts: nFields + 1, fieldSize: 200 },
|
||||
});
|
||||
for await (const part of parts) {
|
||||
if (part.type === 'file') {
|
||||
if (part.fieldname !== 'file' || file) {
|
||||
part.file.resume();
|
||||
throw badRequest('Send exactly one file, in the field "file"');
|
||||
}
|
||||
file = await media.receive(part.file, maxBytes, maxMb);
|
||||
} else if (part.fieldname === 'crop') {
|
||||
cropRaw = String(part.value);
|
||||
} else if (extraFields.includes(part.fieldname) && !(part.fieldname in fields)) {
|
||||
fields[part.fieldname] = String(part.value);
|
||||
} else {
|
||||
throw badRequest('Unexpected form field');
|
||||
}
|
||||
}
|
||||
if (!file) throw badRequest('No image in the request');
|
||||
if (cropRaw === null) throw badCrop('Missing crop');
|
||||
let json: unknown;
|
||||
try {
|
||||
json = JSON.parse(cropRaw);
|
||||
} catch {
|
||||
throw badCrop('The crop must be JSON {x, y, w, h}');
|
||||
}
|
||||
const parsed = cropSchema.safeParse(json);
|
||||
if (!parsed.success) throw badCrop('The crop must be whole, positive pixel values');
|
||||
return { file, crop: parsed.data, fields };
|
||||
} catch (err) {
|
||||
media.discard(file);
|
||||
const e = err as { code?: string; statusCode?: number };
|
||||
if (e.code === 'FST_REQ_FILE_TOO_LARGE') throw mediaTooLarge(maxMb);
|
||||
if (
|
||||
e.code === 'FST_FILES_LIMIT' ||
|
||||
e.code === 'FST_PARTS_LIMIT' ||
|
||||
e.code === 'FST_FIELDS_LIMIT'
|
||||
) {
|
||||
throw badRequest('Send one "crop" field and one "file"');
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import type { FastifyRequest } from 'fastify';
|
||||
|
||||
const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
|
||||
|
||||
function hostOf(origin: string): string | null {
|
||||
try {
|
||||
return new URL(origin).host.toLowerCase();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
type Headers = Record<string, string | string[] | undefined>;
|
||||
const header = (h: Headers, name: string) => (typeof h[name] === 'string' ? h[name] : undefined);
|
||||
|
||||
/**
|
||||
* The host the browser used. Only honours X-Forwarded-Host when we trust a proxy, and then only the
|
||||
* value our proxy set (the last one), mirroring how Fastify resolves request.host (QA-1).
|
||||
*/
|
||||
export function resolveHost(headers: Headers, trustProxyHops: number): string {
|
||||
const forwarded = trustProxyHops > 0 ? header(headers, 'x-forwarded-host') : undefined;
|
||||
const raw = forwarded ? forwarded.split(',').at(-1) : header(headers, 'host');
|
||||
return (raw ?? '').trim().toLowerCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* CSRF defence in depth (on top of SameSite=Lax): a state-changing request must come from our own
|
||||
* origin. In production only PUBLIC_URL's origin is accepted. In development and tests, same-host
|
||||
* origins are allowed too (localhost, Vite proxy) and ALLOWED_ORIGINS adds more.
|
||||
* Requests with no Origin header are allowed only with no Sec-Fetch-Site (curl, server-to-server)
|
||||
* or Sec-Fetch-Site: same-origin (D67). Behind a proxy that rewrites Host, production compares
|
||||
* Origin with PUBLIC_URL, not the Host, so the rewrite doesn't matter.
|
||||
*/
|
||||
export function isOriginAllowed(
|
||||
method: string,
|
||||
headers: Headers,
|
||||
host: string,
|
||||
allowedOrigins: string[],
|
||||
allowSameHost = true,
|
||||
): boolean {
|
||||
if (SAFE_METHODS.has(method.toUpperCase())) return true;
|
||||
const origin = header(headers, 'origin');
|
||||
// D67 (QA-163): no Origin is allowed only from non-browsers (no Sec-Fetch-Site) or the page
|
||||
// itself (same-origin). same-site is refused too: a sibling subdomain is the attacker.
|
||||
if (!origin) {
|
||||
const site = header(headers, 'sec-fetch-site');
|
||||
return site === undefined || site === 'same-origin';
|
||||
}
|
||||
if (origin === 'null') return false;
|
||||
if (allowedOrigins.includes(origin.replace(/\/$/, ''))) return true;
|
||||
// Production: only the configured PUBLIC_URL origin (DESIGN decisions log).
|
||||
if (!allowSameHost) return false;
|
||||
const originHost = hostOf(origin);
|
||||
return !!host && !!originHost && originHost === host.toLowerCase();
|
||||
}
|
||||
|
||||
export function requestIsAllowed(
|
||||
req: FastifyRequest,
|
||||
allowedOrigins: string[],
|
||||
allowSameHost = true,
|
||||
): boolean {
|
||||
// req.host is resolved by Fastify using the same trustProxy setting as req.ip.
|
||||
return isOriginAllowed(req.method, req.headers, req.host, allowedOrigins, allowSameHost);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import type { FastifyRequest } from 'fastify';
|
||||
|
||||
/**
|
||||
* D67 (QA-163): the request path the way the router reads it, for the few places that still
|
||||
* need a path (the 404 handler, the 429 wording): percent-decoded (an undecodable sequence is
|
||||
* kept as is), duplicate slashes collapsed, lower case, no query. Prefer the matched route
|
||||
* (`routeOf`) wherever there is one: `/%61pi/...` is routed as `/api/...`, so the raw URL lies.
|
||||
*/
|
||||
export function normalisedPath(rawUrl: string): string {
|
||||
let p = rawUrl.split('?')[0] ?? '';
|
||||
for (let i = 0; i < 3 && p.includes('%'); i++) {
|
||||
try {
|
||||
const next = decodeURIComponent(p);
|
||||
if (next === p) break;
|
||||
p = next;
|
||||
} catch {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return p
|
||||
.replace(/\\/g, '/')
|
||||
.replace(/\/{2,}/g, '/')
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
/** The matched route's pattern (`/api/channels/:id/messages`), else the normalised path. */
|
||||
export const routeOf = (req: FastifyRequest): string =>
|
||||
req.routeOptions.url ?? normalisedPath(req.url);
|
||||
@@ -0,0 +1,38 @@
|
||||
import type { FastifyRequest } from 'fastify';
|
||||
import { requireAuth } from '../auth/plugin.js';
|
||||
import type { AppConfig } from '../config.js';
|
||||
|
||||
/** The D57 limit itself: per user, MESSAGE_RATE_LIMIT_MAX per window. */
|
||||
function profileRateLimit(config: AppConfig) {
|
||||
return {
|
||||
max: config.rateLimit.messageMax,
|
||||
timeWindow: config.rateLimit.messageWindowMs,
|
||||
keyGenerator: (req: FastifyRequest) => req.user?.id ?? req.ip,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* D57: the one profile rate limit, keyed by user. Profile edits, custom status text and profile
|
||||
* pictures use it (D67, QA-166).
|
||||
*/
|
||||
export function profileLimited(config: AppConfig) {
|
||||
return { preHandler: requireAuth, config: { rateLimit: profileRateLimit(config) } };
|
||||
}
|
||||
|
||||
/**
|
||||
* D69 (QA-167): the same limit, but a request counts only when `counts(req)` says so. It runs
|
||||
* after auth and body parsing (preHandler), so `counts` can read the body and the stored user.
|
||||
* Requests that don't count are left alone (no route limit, as before D67).
|
||||
*/
|
||||
export function profileLimitedWhen(config: AppConfig, counts: (req: FastifyRequest) => boolean) {
|
||||
return {
|
||||
preHandler: requireAuth,
|
||||
config: {
|
||||
rateLimit: {
|
||||
...profileRateLimit(config),
|
||||
hook: 'preHandler' as const,
|
||||
allowList: (req: FastifyRequest) => !counts(req),
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
/**
|
||||
* Push endpoint allowlist (DESIGN-0.3 section 2, "Security"). The server POSTs to whatever endpoint a
|
||||
* user registers, so an unchecked one is a server-side request forgery hole into the homelab
|
||||
* network. The rules, all of which must hold:
|
||||
* - https only, no credentials (`user@`), no explicit port, no backslash/whitespace/control chars
|
||||
* - the host is a name (never an IP address, never `localhost`, no trailing dot)
|
||||
* - the host is on the allowlist: an exact name, or `*.suffix` (one or more labels before the suffix)
|
||||
* Matching is on the parsed host, so `fcm.googleapis.com.evil.test` and `evil.test/@fcm.googleapis.com`
|
||||
* don't match. Redirects are never followed when sending (see PushService), which covers an allowed
|
||||
* host that answers with a redirect to somewhere internal.
|
||||
*/
|
||||
/**
|
||||
* The one form an endpoint is stored and looked up in: `new URL(x).href` without a fragment (lower
|
||||
* case host, unicode dots and default parts folded, `#...` dropped), so one endpoint is one row.
|
||||
* Anything that doesn't parse is returned unchanged (it was or will be rejected anyway).
|
||||
*/
|
||||
export function normalizeEndpoint(raw: string): string {
|
||||
try {
|
||||
const u = new URL(raw);
|
||||
u.hash = '';
|
||||
return u.href;
|
||||
} catch {
|
||||
return raw;
|
||||
}
|
||||
}
|
||||
|
||||
export const DEFAULT_PUSH_ALLOW = [
|
||||
'fcm.googleapis.com',
|
||||
'*.push.apple.com',
|
||||
'updates.push.services.mozilla.com',
|
||||
'*.push.services.mozilla.com',
|
||||
'*.notify.windows.com',
|
||||
] as const;
|
||||
|
||||
/** PUSH_ENDPOINT_ALLOW: comma separated extra hosts, same syntax as the defaults. */
|
||||
export function parsePushAllow(v: string | undefined): string[] {
|
||||
const out: string[] = [];
|
||||
for (const raw of (v ?? '').split(',')) {
|
||||
const h = raw.trim().toLowerCase();
|
||||
if (!h) continue;
|
||||
if (!/^(\*\.)?([a-z0-9]([a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,}$/.test(h)) {
|
||||
throw new Error(`PUSH_ENDPOINT_ALLOW has an invalid host: "${raw.trim()}"`);
|
||||
}
|
||||
out.push(h);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export interface EndpointRules {
|
||||
/** Extra allowed hosts (PUSH_ENDPOINT_ALLOW). */
|
||||
extraAllow?: readonly string[];
|
||||
/**
|
||||
* Tests only: exact origins (e.g. `http://127.0.0.1:41234`) of a local mock push service. Never
|
||||
* set from the environment unless NODE_ENV=test (see loadConfig), and ignored in production.
|
||||
*/
|
||||
testOrigins?: readonly string[];
|
||||
}
|
||||
|
||||
const IPV4_LIKE = /^[0-9.]+$|^0x[0-9a-f]+$/i;
|
||||
|
||||
export function hostAllowed(host: string, allow: readonly string[]): boolean {
|
||||
return allow.some((rule) =>
|
||||
rule.startsWith('*.')
|
||||
? host.endsWith(rule.slice(1)) && host.length > rule.length - 1
|
||||
: host === rule,
|
||||
);
|
||||
}
|
||||
|
||||
/** Returns null when the endpoint is acceptable, or a short reason. */
|
||||
export function pushEndpointProblem(raw: string, rules: EndpointRules = {}): string | null {
|
||||
if (raw.length === 0 || raw.length > 2048) return 'Endpoint has the wrong length';
|
||||
// eslint-disable-next-line no-control-regex
|
||||
if (/[\s\\\u0000-\u001f\u007f]/.test(raw)) return 'Endpoint has forbidden characters';
|
||||
let u: URL;
|
||||
try {
|
||||
u = new URL(raw);
|
||||
} catch {
|
||||
return 'Endpoint is not a URL';
|
||||
}
|
||||
if (rules.testOrigins?.includes(u.origin) && u.username === '' && u.password === '') return null;
|
||||
if (u.protocol !== 'https:') return 'Endpoint must use https';
|
||||
if (u.username || u.password) return 'Endpoint must not contain credentials';
|
||||
// `new URL` drops an explicit default port, so look at the text too: authority = up to the first / ? #
|
||||
const authority = raw.slice('https://'.length).split(/[/?#]/)[0] as string;
|
||||
if (u.port !== '' || authority.includes(':') || authority.includes('@')) {
|
||||
return 'Endpoint must not have a port or credentials';
|
||||
}
|
||||
const host = u.hostname.toLowerCase();
|
||||
if (host.includes(':') || host.startsWith('[') || IPV4_LIKE.test(host)) {
|
||||
return 'Endpoint must be a host name, not an IP address';
|
||||
}
|
||||
if (host === 'localhost' || host.endsWith('.') || !host.includes('.')) {
|
||||
return 'Endpoint host is not allowed';
|
||||
}
|
||||
const allow = [...DEFAULT_PUSH_ALLOW, ...(rules.extraAllow ?? [])];
|
||||
if (!hostAllowed(host, allow)) return 'Endpoint host is not a known push service';
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
/**
|
||||
* The installable app (M11, DESIGN-0.3 section 1): the web app manifest and the service worker
|
||||
* source. Both are built per request from config, not served as static files, because the name
|
||||
* comes from APP_NAME and the worker carries the app version.
|
||||
*/
|
||||
|
||||
/** Theme colours of the default (dark) theme: apps/web/src/lib/theme/presets.ts bgPrimary. */
|
||||
export const MANIFEST_THEME_COLOR = '#313338';
|
||||
export const MANIFEST_BACKGROUND_COLOR = '#313338';
|
||||
|
||||
/** Home-screen labels are cut off after about 12 characters on most phones. */
|
||||
export function shortName(appName: string): string {
|
||||
const chars = [...appName.trim()];
|
||||
return chars.length <= 12 ? chars.join('') : chars.slice(0, 12).join('').trimEnd();
|
||||
}
|
||||
|
||||
export interface WebManifest {
|
||||
id: string;
|
||||
name: string;
|
||||
short_name: string;
|
||||
description: string;
|
||||
start_url: string;
|
||||
scope: string;
|
||||
display: 'standalone';
|
||||
orientation: 'any';
|
||||
background_color: string;
|
||||
theme_color: string;
|
||||
icons: { src: string; sizes: string; type: string; purpose: string }[];
|
||||
}
|
||||
|
||||
export function buildManifest(appName: string): WebManifest {
|
||||
const png = (file: string, size: number, purpose: string) => ({
|
||||
src: `/icons/${file}`,
|
||||
sizes: `${size}x${size}`,
|
||||
type: 'image/png',
|
||||
purpose,
|
||||
});
|
||||
return {
|
||||
id: '/',
|
||||
name: appName,
|
||||
short_name: shortName(appName),
|
||||
description: `${appName}: chat, voice and video on your own server.`,
|
||||
start_url: '/',
|
||||
scope: '/',
|
||||
display: 'standalone',
|
||||
orientation: 'any',
|
||||
background_color: MANIFEST_BACKGROUND_COLOR,
|
||||
theme_color: MANIFEST_THEME_COLOR,
|
||||
icons: [
|
||||
png('icon-192.png', 192, 'any'),
|
||||
png('icon-512.png', 512, 'any'),
|
||||
png('icon-maskable-512.png', 512, 'maskable'),
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
/** The version in apps/server/package.json (the same one the whole repo is released under). */
|
||||
export function readAppVersion(): string {
|
||||
const file = path.resolve(import.meta.dirname, '..', '..', 'package.json');
|
||||
return (JSON.parse(readFileSync(file, 'utf8')) as { version: string }).version;
|
||||
}
|
||||
|
||||
export const SW_VERSION_PLACEHOLDER = '__APP_VERSION__';
|
||||
|
||||
/** The worker's source with its version filled in, so every release is a different file. */
|
||||
export function renderServiceWorker(template: string, version: string): string {
|
||||
return template.replaceAll(SW_VERSION_PLACEHOLDER, version.replace(/[^\w.+-]/g, ''));
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* In-memory per-key sliding-window counter (group adds and group creation, DESIGN-0.2 section 6).
|
||||
* Counts per user like the message limits; resets on restart, which is fine for abuse limits.
|
||||
*/
|
||||
export class RateWindow {
|
||||
private readonly events = new Map<string, { at: number; n: number }[]>();
|
||||
|
||||
constructor(
|
||||
readonly max: number,
|
||||
readonly windowMs: number,
|
||||
private readonly now: () => number = Date.now,
|
||||
) {}
|
||||
|
||||
private live(key: string): { at: number; n: number }[] {
|
||||
const cutoff = this.now() - this.windowMs;
|
||||
const list = (this.events.get(key) ?? []).filter((e) => e.at > cutoff);
|
||||
if (list.length) this.events.set(key, list);
|
||||
else this.events.delete(key);
|
||||
return list;
|
||||
}
|
||||
|
||||
used(key: string): number {
|
||||
return this.live(key).reduce((s, e) => s + e.n, 0);
|
||||
}
|
||||
|
||||
/** Would `n` more fit in the window? */
|
||||
allows(key: string, n = 1): boolean {
|
||||
return this.used(key) + n <= this.max;
|
||||
}
|
||||
|
||||
/** Whole seconds until `n` more would fit again (0 if they fit now), for Retry-After. */
|
||||
retryAfterSec(key: string, n = 1): number {
|
||||
const list = this.live(key);
|
||||
let used = list.reduce((s, e) => s + e.n, 0);
|
||||
if (used + n <= this.max) return 0;
|
||||
const now = this.now();
|
||||
for (const e of list) {
|
||||
used -= e.n;
|
||||
if (used + n <= this.max) return Math.max(1, Math.ceil((e.at + this.windowMs - now) / 1000));
|
||||
}
|
||||
return Math.ceil(this.windowMs / 1000);
|
||||
}
|
||||
|
||||
record(key: string, n = 1): void {
|
||||
const list = this.live(key);
|
||||
list.push({ at: this.now(), n });
|
||||
this.events.set(key, list);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
/**
|
||||
* The FTS5 query for a search (D26). User text never reaches FTS5 as syntax: each word is one
|
||||
* double-quoted string (a quote inside it doubled), the words are ANDed (FTS5's implicit AND
|
||||
* between strings), and only the last one gets `*` for prefix matching. So `AND`, `NEAR`, `-`,
|
||||
* `*`, stray quotes and SQL-looking text are all searched as plain words.
|
||||
*
|
||||
* A "word" is a run of non-space characters with at least one letter or digit; anything else
|
||||
* (`-`, `*`, `🎉`, lone quotes) can't match a token of the `unicode61` index and is dropped.
|
||||
* Returns null when no word is left.
|
||||
*/
|
||||
export function ftsQuery(text: string): string | null {
|
||||
const words = text
|
||||
.split(/\s+/u)
|
||||
.filter((w) => /[\p{L}\p{N}]/u.test(w))
|
||||
.map((w) => `"${w.replaceAll('"', '""')}"`);
|
||||
if (words.length === 0) return null;
|
||||
words[words.length - 1] += '*';
|
||||
return words.join(' ');
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { permissionsPolicy, type AppConfig } from '../config.js';
|
||||
|
||||
/** ws(s)/http(s) origin of a URL, or null when it isn't one. */
|
||||
function originOf(url: string): string | null {
|
||||
try {
|
||||
const u = new URL(url);
|
||||
return ['ws:', 'wss:', 'http:', 'https:'].includes(u.protocol) ? u.origin : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** The same origin with the other scheme family: wss <-> https, ws <-> http. */
|
||||
function twin(origin: string): string {
|
||||
const u = new URL(origin);
|
||||
const swap: Record<string, string> = {
|
||||
'wss:': 'https:',
|
||||
'https:': 'wss:',
|
||||
'ws:': 'http:',
|
||||
'http:': 'ws:',
|
||||
};
|
||||
return `${swap[u.protocol]}//${u.host}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* connect-src: same origin, the WebSocket form of PUBLIC_URL (older Safari doesn't count wss as
|
||||
* 'self'), and LiveKit's signalling origin (wss for /rtc, https for its validate call on errors).
|
||||
*/
|
||||
export function connectSources(
|
||||
config: Pick<AppConfig, 'publicUrl' | 'livekitPublicUrl'>,
|
||||
): string[] {
|
||||
const out = new Set<string>(["'self'"]);
|
||||
for (const url of [config.publicUrl, config.livekitPublicUrl]) {
|
||||
const o = originOf(url);
|
||||
if (!o) continue;
|
||||
out.add(o.startsWith('ws') ? o : twin(o));
|
||||
out.add(o.startsWith('ws') ? twin(o) : o);
|
||||
}
|
||||
return [...out];
|
||||
}
|
||||
|
||||
/** Content-Security-Policy for the app (decisions log: headers come from the app, not nginx). */
|
||||
export function contentSecurityPolicy(
|
||||
config: Pick<AppConfig, 'publicUrl' | 'livekitPublicUrl'>,
|
||||
): string {
|
||||
return [
|
||||
"default-src 'self'",
|
||||
"script-src 'self'", // no inline scripts: theme-boot.js is a file
|
||||
// Svelte sets style="" attributes and transitions add <style> elements; styles can't run code.
|
||||
"style-src 'self' 'unsafe-inline'",
|
||||
"img-src 'self' data: blob:",
|
||||
"media-src 'self' blob:",
|
||||
"font-src 'self'",
|
||||
`connect-src ${connectSources(config).join(' ')}`,
|
||||
"worker-src 'self' blob:", // /sw.js (M11) and LiveKit's blob workers
|
||||
"manifest-src 'self'",
|
||||
"object-src 'none'",
|
||||
"base-uri 'self'",
|
||||
"form-action 'self'",
|
||||
"frame-ancestors 'none'",
|
||||
].join('; ');
|
||||
}
|
||||
|
||||
/** Headers sent on every response. Routes may override (attachments set a stricter CSP). */
|
||||
export function securityHeaders(
|
||||
config: Pick<AppConfig, 'publicUrl' | 'livekitPublicUrl' | 'videoEnabled'>,
|
||||
): Record<string, string> {
|
||||
return {
|
||||
'Content-Security-Policy': contentSecurityPolicy(config),
|
||||
'X-Content-Type-Options': 'nosniff',
|
||||
'Referrer-Policy': 'same-origin',
|
||||
'Permissions-Policy': permissionsPolicy(config),
|
||||
'X-Frame-Options': 'DENY',
|
||||
'Cross-Origin-Opener-Policy': 'same-origin',
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import type { z } from 'zod';
|
||||
import { badRequest } from './errors.js';
|
||||
|
||||
/** At most this many issues, and this many named keys per issue, go back to the client (D20). */
|
||||
export const MAX_ISSUES = 10;
|
||||
const MAX_ISSUE_MESSAGE = 300;
|
||||
|
||||
/**
|
||||
* One issue's message, kept short: zod names every unrecognised key, so a body with 50,000 unknown
|
||||
* keys would otherwise echo all of them (D20 info item).
|
||||
*/
|
||||
function issueMessage(issue: z.core.$ZodIssue): string {
|
||||
let message = issue.message;
|
||||
if (issue.code === 'unrecognized_keys' && issue.keys.length > MAX_ISSUES) {
|
||||
const shown = issue.keys.slice(0, MAX_ISSUES).map((k) => JSON.stringify(k.slice(0, 40)));
|
||||
message = `Unrecognized keys: ${shown.join(', ')} and ${issue.keys.length - MAX_ISSUES} more`;
|
||||
}
|
||||
return message.length > MAX_ISSUE_MESSAGE
|
||||
? `${message.slice(0, MAX_ISSUE_MESSAGE - 1)}…`
|
||||
: message;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a request body/query with a shared zod schema; 400 with field issues on failure. The
|
||||
* response lists at most MAX_ISSUES issues (D20), so an oversized body gets a small answer.
|
||||
*/
|
||||
export function parse<S extends z.ZodType>(schema: S, data: unknown): z.output<S> {
|
||||
const result = schema.safeParse(data ?? {});
|
||||
if (!result.success) {
|
||||
const issues = result.error.issues
|
||||
.slice(0, MAX_ISSUES)
|
||||
.map((i) => ({ path: i.path.join('.').slice(0, 200), message: issueMessage(i) }));
|
||||
throw badRequest(issues[0]?.message ?? 'Invalid request', issues);
|
||||
}
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* QA-64 defence in depth: refuse a raw array longer than its schema allows before zod runs, so an
|
||||
* oversized body (up to bodyLimit, about 1 MB) is never validated element by element.
|
||||
*/
|
||||
export function rejectLongArray(body: unknown, field: string, max: number, message: string): void {
|
||||
if (!body || typeof body !== 'object' || Array.isArray(body)) return;
|
||||
const value = (body as Record<string, unknown>)[field];
|
||||
if (Array.isArray(value) && value.length > max) {
|
||||
throw badRequest(message, [{ path: field, message }]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
import type { ServerToClientEvents } from '@chat/shared';
|
||||
|
||||
export type EventName = keyof ServerToClientEvents;
|
||||
export type EventPayload<E extends EventName> = Parameters<ServerToClientEvents[E]>[0];
|
||||
|
||||
export const serverRoom = (serverId: string) => `server:${serverId}`;
|
||||
export const userRoom = (userId: string) => `user:${userId}`;
|
||||
/** D46: a socket is in `chan:<id>` exactly when its user can VIEW that channel. */
|
||||
export const chanRoom = (channelId: string) => `chan:${channelId}`;
|
||||
|
||||
/**
|
||||
* What services need from the realtime layer. Services call this after a successful write; the
|
||||
* REST response is the source of truth and the socket only pushes (DESIGN.md section 5).
|
||||
*/
|
||||
export interface RealtimeHub {
|
||||
toServer<E extends EventName>(serverId: string, event: E, payload: EventPayload<E>): void;
|
||||
toUser<E extends EventName>(userId: string, event: E, payload: EventPayload<E>): void;
|
||||
/**
|
||||
* D46: every channel-scoped event (messages, reactions, pins, typing, threads, channel updates,
|
||||
* voice state). The room is resolved at emit time, never from a list computed earlier (D59).
|
||||
*/
|
||||
toChannel<E extends EventName>(channelId: string, event: E, payload: EventPayload<E>): void;
|
||||
/**
|
||||
* One event to every socket in any of these server rooms or user rooms, delivered once per
|
||||
* socket even if it's in several of them (presence fan-out). `exceptUserIds` (D50): none of
|
||||
* those users' sockets get it, whichever room they're in.
|
||||
*/
|
||||
toAudience<E extends EventName>(
|
||||
serverIds: readonly string[],
|
||||
userIds: readonly string[],
|
||||
event: E,
|
||||
payload: EventPayload<E>,
|
||||
exceptUserIds?: readonly string[],
|
||||
): void;
|
||||
/** Subscribe all of a user's open sockets to a server room (after join/create). */
|
||||
joinServer(userId: string, serverId: string): void;
|
||||
/** Unsubscribe all of a user's sockets from a server room (kick/ban/leave). */
|
||||
leaveServer(userId: string, serverId: string): void;
|
||||
/** Empty a server room entirely (server deleted). */
|
||||
closeServer(serverId: string): void;
|
||||
/** D46: put all of a user's open sockets into these channel rooms (synchronous). */
|
||||
joinChannels(userId: string, channelIds: readonly string[]): void;
|
||||
/** D46: take all of a user's open sockets out of these channel rooms (synchronous). */
|
||||
leaveChannels(userId: string, channelIds: readonly string[]): void;
|
||||
/** Channel ids whose room any of the user's open sockets is in right now. */
|
||||
channelRoomsOf(userId: string): Set<string>;
|
||||
/** Empty a channel room entirely (channel deleted). */
|
||||
closeChannel(channelId: string): void;
|
||||
}
|
||||
|
||||
export interface RecordedEvent {
|
||||
kind:
|
||||
| 'server'
|
||||
| 'user'
|
||||
| 'channel'
|
||||
| 'audience'
|
||||
| 'join'
|
||||
| 'leave'
|
||||
| 'close'
|
||||
| 'joinChannels'
|
||||
| 'leaveChannels'
|
||||
| 'closeChannel';
|
||||
target: string;
|
||||
event?: string;
|
||||
payload?: unknown;
|
||||
serverId?: string;
|
||||
serverIds?: readonly string[];
|
||||
userIds?: readonly string[];
|
||||
exceptUserIds?: readonly string[];
|
||||
channelIds?: readonly string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Used when no Socket.IO server is attached (tests, scripts). Records calls for assertions, and
|
||||
* keeps track of channel rooms as if each user had one socket open.
|
||||
*/
|
||||
export class RecordingHub implements RealtimeHub {
|
||||
readonly events: RecordedEvent[] = [];
|
||||
private readonly chanRooms = new Map<string, Set<string>>();
|
||||
toChannel<E extends EventName>(channelId: string, event: E, payload: EventPayload<E>): void {
|
||||
this.events.push({ kind: 'channel', target: channelId, event, payload });
|
||||
}
|
||||
joinChannels(userId: string, channelIds: readonly string[]): void {
|
||||
if (!channelIds.length) return;
|
||||
const set = this.chanRooms.get(userId) ?? new Set<string>();
|
||||
for (const c of channelIds) set.add(c);
|
||||
this.chanRooms.set(userId, set);
|
||||
this.events.push({ kind: 'joinChannels', target: userId, channelIds });
|
||||
}
|
||||
leaveChannels(userId: string, channelIds: readonly string[]): void {
|
||||
if (!channelIds.length) return;
|
||||
const set = this.chanRooms.get(userId);
|
||||
for (const c of channelIds) set?.delete(c);
|
||||
this.events.push({ kind: 'leaveChannels', target: userId, channelIds });
|
||||
}
|
||||
channelRoomsOf(userId: string): Set<string> {
|
||||
return new Set(this.chanRooms.get(userId) ?? []);
|
||||
}
|
||||
closeChannel(channelId: string): void {
|
||||
for (const set of this.chanRooms.values()) set.delete(channelId);
|
||||
this.events.push({ kind: 'closeChannel', target: channelId });
|
||||
}
|
||||
toServer<E extends EventName>(serverId: string, event: E, payload: EventPayload<E>): void {
|
||||
this.events.push({ kind: 'server', target: serverId, event, payload });
|
||||
}
|
||||
toUser<E extends EventName>(userId: string, event: E, payload: EventPayload<E>): void {
|
||||
this.events.push({ kind: 'user', target: userId, event, payload });
|
||||
}
|
||||
toAudience<E extends EventName>(
|
||||
serverIds: readonly string[],
|
||||
userIds: readonly string[],
|
||||
event: E,
|
||||
payload: EventPayload<E>,
|
||||
exceptUserIds?: readonly string[],
|
||||
): void {
|
||||
this.events.push({
|
||||
kind: 'audience',
|
||||
target: '',
|
||||
serverIds,
|
||||
userIds,
|
||||
event,
|
||||
payload,
|
||||
...(exceptUserIds?.length ? { exceptUserIds } : {}),
|
||||
});
|
||||
}
|
||||
joinServer(userId: string, serverId: string): void {
|
||||
this.events.push({ kind: 'join', target: userId, serverId });
|
||||
}
|
||||
leaveServer(userId: string, serverId: string): void {
|
||||
this.events.push({ kind: 'leave', target: userId, serverId });
|
||||
}
|
||||
closeServer(serverId: string): void {
|
||||
this.events.push({ kind: 'close', target: serverId });
|
||||
}
|
||||
clear(): void {
|
||||
this.events.length = 0;
|
||||
}
|
||||
named(event: string): RecordedEvent[] {
|
||||
return this.events.filter((e) => e.event === event);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
import {
|
||||
Perm,
|
||||
SESSION_REQUIRED,
|
||||
appVisibilitySchema,
|
||||
channelFocusSchema,
|
||||
presenceIdleSchema,
|
||||
presenceSetSchema,
|
||||
typingStartSchema,
|
||||
type ClientToServerEvents,
|
||||
type ServerToClientEvents,
|
||||
} from '@chat/shared';
|
||||
import { Access } from '../auth/access.js';
|
||||
import { dmMemberIds, requireDmPost } from '../auth/permissions.js';
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import { Server } from 'socket.io';
|
||||
import { SESSION_COOKIE } from '../auth/plugin.js';
|
||||
import type { AppConfig } from '../config.js';
|
||||
import { isOriginAllowed, resolveHost } from '../lib/origin.js';
|
||||
import {
|
||||
chanRoom,
|
||||
serverRoom,
|
||||
userRoom,
|
||||
type EventName,
|
||||
type EventPayload,
|
||||
type RealtimeHub,
|
||||
} from './hub.js';
|
||||
|
||||
export type IoServer = Server<ClientToServerEvents, ServerToClientEvents>;
|
||||
|
||||
/** Typing: at most one broadcast per channel per TYPING_MIN_INTERVAL_MS, and TYPING_BURST per 10 s per socket. */
|
||||
export const TYPING_MIN_INTERVAL_MS = 2_000;
|
||||
export const TYPING_BURST = 15;
|
||||
/** presence:set / presence:idle: at most PRESENCE_BURST per PRESENCE_WINDOW_MS per socket. */
|
||||
export const PRESENCE_BURST = 20;
|
||||
export const PRESENCE_WINDOW_MS = 60_000;
|
||||
|
||||
/** RealtimeHub backed by Socket.IO rooms: `user:<id>` per user, `server:<id>` per server. */
|
||||
export class SocketHub implements RealtimeHub {
|
||||
constructor(private readonly io: IoServer) {}
|
||||
|
||||
toServer<E extends EventName>(serverId: string, event: E, payload: EventPayload<E>): void {
|
||||
// Socket.IO's emit typing can't follow the generic mapping; payload type is checked above.
|
||||
(this.io.to(serverRoom(serverId)).emit as (e: string, p: unknown) => void)(event, payload);
|
||||
}
|
||||
toUser<E extends EventName>(userId: string, event: E, payload: EventPayload<E>): void {
|
||||
(this.io.to(userRoom(userId)).emit as (e: string, p: unknown) => void)(event, payload);
|
||||
}
|
||||
toAudience<E extends EventName>(
|
||||
serverIds: readonly string[],
|
||||
userIds: readonly string[],
|
||||
event: E,
|
||||
payload: EventPayload<E>,
|
||||
exceptUserIds: readonly string[] = [],
|
||||
): void {
|
||||
const rooms = [...serverIds.map(serverRoom), ...userIds.map(userRoom)];
|
||||
if (rooms.length === 0) return;
|
||||
const to = exceptUserIds.length
|
||||
? this.io.to(rooms).except(exceptUserIds.map(userRoom))
|
||||
: this.io.to(rooms);
|
||||
(to.emit as (e: string, p: unknown) => void)(event, payload);
|
||||
}
|
||||
joinServer(userId: string, serverId: string): void {
|
||||
this.io.in(userRoom(userId)).socketsJoin(serverRoom(serverId));
|
||||
}
|
||||
leaveServer(userId: string, serverId: string): void {
|
||||
this.io.in(userRoom(userId)).socketsLeave(serverRoom(serverId));
|
||||
}
|
||||
closeServer(serverId: string): void {
|
||||
this.io.in(serverRoom(serverId)).socketsLeave(serverRoom(serverId));
|
||||
}
|
||||
toChannel<E extends EventName>(channelId: string, event: E, payload: EventPayload<E>): void {
|
||||
(this.io.to(chanRoom(channelId)).emit as (e: string, p: unknown) => void)(event, payload);
|
||||
}
|
||||
// With the in-memory adapter (how Doghouse ships, one process) socketsJoin/socketsLeave are
|
||||
// synchronous: once these return, no later emit to the room reaches a socket that left (D46).
|
||||
joinChannels(userId: string, channelIds: readonly string[]): void {
|
||||
if (channelIds.length) this.io.in(userRoom(userId)).socketsJoin(channelIds.map(chanRoom));
|
||||
}
|
||||
leaveChannels(userId: string, channelIds: readonly string[]): void {
|
||||
if (channelIds.length) this.io.in(userRoom(userId)).socketsLeave(channelIds.map(chanRoom));
|
||||
}
|
||||
channelRoomsOf(userId: string): Set<string> {
|
||||
const adapter = this.io.of('/').adapter;
|
||||
const out = new Set<string>();
|
||||
for (const sid of adapter.rooms.get(userRoom(userId)) ?? []) {
|
||||
for (const room of adapter.sids.get(sid) ?? []) {
|
||||
if (room.startsWith('chan:')) out.add(room.slice(5));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
closeChannel(channelId: string): void {
|
||||
this.io.in(chanRoom(channelId)).socketsLeave(chanRoom(channelId));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Socket.IO on /ws. Authenticated with the same session cookie as REST. Push-only by design
|
||||
* (DESIGN.md section 5): writes go through REST. Each socket joins `user:<id>` and one
|
||||
* `server:<id>` room per (non-banned) membership.
|
||||
*/
|
||||
export function attachSocket(app: FastifyInstance, config: AppConfig): IoServer {
|
||||
const io: IoServer = new Server(app.server, {
|
||||
path: '/ws',
|
||||
serveClient: false,
|
||||
// Detect dead connections (network drop, killed phone app) within ~20 s, so presence never
|
||||
// keeps a ghost online for long (TESTPLAN story 5). Defaults are 25 s + 20 s.
|
||||
pingInterval: 10_000,
|
||||
pingTimeout: 10_000,
|
||||
allowRequest: (req, cb) => {
|
||||
// Treat the handshake like a state-changing request: Origin must be ours.
|
||||
// Same host resolution as Fastify (trusted hops only). No IP-based checks happen here; if any
|
||||
// are added, resolve the IP with the same TRUST_PROXY_HOPS rule (DESIGN decisions log).
|
||||
const host = resolveHost(req.headers, config.trustProxy);
|
||||
const ok = isOriginAllowed(
|
||||
'POST',
|
||||
req.headers,
|
||||
host,
|
||||
config.allowedOrigins,
|
||||
!config.production,
|
||||
);
|
||||
cb(ok ? null : 'origin not allowed', ok);
|
||||
},
|
||||
});
|
||||
|
||||
io.use((socket, next) => {
|
||||
const cookies = app.parseCookie(socket.handshake.headers.cookie ?? '');
|
||||
const user = app.services.auth.getSessionUser(cookies[SESSION_COOKIE]);
|
||||
if (!user) return next(new Error(SESSION_REQUIRED));
|
||||
socket.data.userId = user.id;
|
||||
next();
|
||||
});
|
||||
|
||||
io.on('connection', (socket) => {
|
||||
const userId = socket.data.userId as string;
|
||||
// D60 (QA-144): before anything else, tell the tab whose socket this is.
|
||||
socket.emit('session:hello', { userId });
|
||||
// D46/D59: every connect (and reconnect) builds the rooms from the access check right now.
|
||||
// The client never names rooms (there is no join event), so a reconnect can't undo AccessSync.
|
||||
const rooms = [
|
||||
userRoom(userId),
|
||||
...app.services.servers.serverIdsFor(userId).map((id) => serverRoom(id)),
|
||||
...[...Access.for(app.services.db).visibleChannelIds(userId)].map(chanRoom),
|
||||
];
|
||||
void socket.join(rooms);
|
||||
|
||||
const lastTyping = new Map<string, number>();
|
||||
let windowStart = Date.now();
|
||||
let inWindow = 0;
|
||||
socket.on('typing:start', (raw) => {
|
||||
const p = typingStartSchema.safeParse(raw);
|
||||
if (!p.success) return;
|
||||
// D51.3: an Invisible user's typing is dropped, so it can't tell them apart from offline.
|
||||
if (app.services.presence.pref(userId) === 'invisible') return;
|
||||
const now = Date.now();
|
||||
if (now - windowStart > 10_000) {
|
||||
windowStart = now;
|
||||
inWindow = 0;
|
||||
}
|
||||
if (++inWindow > TYPING_BURST) return;
|
||||
if (now - (lastTyping.get(p.data.channelId) ?? 0) < TYPING_MIN_INTERVAL_MS) return;
|
||||
const { db, users, messages } = app.services;
|
||||
const ref = messages.refFor(p.data.channelId);
|
||||
let room: string | string[];
|
||||
if (ref?.kind === 'channel' || ref?.kind === 'thread') {
|
||||
// M25: typing in a thread goes to the server room, like its channel (access is the channel's).
|
||||
const channelId =
|
||||
ref.kind === 'thread'
|
||||
? (
|
||||
db.prepare('SELECT channel_id FROM threads WHERE id = ?').get(ref.id) as {
|
||||
channel_id: string;
|
||||
}
|
||||
).channel_id
|
||||
: ref.id;
|
||||
// D38: typing is part of posting: SEND (and SEND_IN_THREADS in a thread), checked per
|
||||
// event, so a lost permission stops typing at once.
|
||||
const need =
|
||||
ref.kind === 'thread' ? Perm.SEND_MESSAGES | Perm.SEND_IN_THREADS : Perm.SEND_MESSAGES;
|
||||
if ((Access.for(db).channelPerms(userId, channelId) & need) !== need) return;
|
||||
const channel = db
|
||||
.prepare('SELECT server_id, type FROM channels WHERE id = ?')
|
||||
.get(channelId) as { server_id: string; type: string };
|
||||
if (channel.type !== 'text') return;
|
||||
// D46: typing goes to the channel's room (a thread's: its parent channel's).
|
||||
room = chanRoom(channelId);
|
||||
} else if (ref?.kind === 'dm') {
|
||||
// Current members only (1:1: while they may still post). Looked up per event, so someone
|
||||
// who left or was removed stops getting typing at once.
|
||||
try {
|
||||
requireDmPost(db, userId, ref.id);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
room = dmMemberIds(db, ref.id)
|
||||
.filter((id) => id !== userId)
|
||||
.map(userRoom);
|
||||
if (room.length === 0) return;
|
||||
} else return;
|
||||
lastTyping.set(p.data.channelId, now);
|
||||
const u = users.getById(userId);
|
||||
if (!u) return;
|
||||
// socket.to() excludes this socket; clients also ignore their own user id (other tabs).
|
||||
socket.to(room).emit('typing', {
|
||||
channelId: p.data.channelId,
|
||||
user: {
|
||||
id: u.id,
|
||||
username: u.username,
|
||||
displayName: u.display_name,
|
||||
avatar: u.avatar_media,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
socket.on('channel:focus', (raw) => {
|
||||
const p = channelFocusSchema.safeParse(raw);
|
||||
if (!p.success) return;
|
||||
const ref = app.services.messages.refFor(p.data.channelId);
|
||||
if (!ref) return;
|
||||
try {
|
||||
app.services.messages.markRead(userId, ref, p.data.messageId);
|
||||
} catch {
|
||||
/* not visible / not a text channel: ignore */
|
||||
}
|
||||
});
|
||||
|
||||
// ---- presence (story 5) ----
|
||||
const { presence } = app.services;
|
||||
// Each status change fans out to everyone who can see this user: cap it per socket.
|
||||
let presenceWindow = Date.now();
|
||||
let presenceCount = 0;
|
||||
const presenceAllowed = () => {
|
||||
const now = Date.now();
|
||||
if (now - presenceWindow > PRESENCE_WINDOW_MS) {
|
||||
presenceWindow = now;
|
||||
presenceCount = 0;
|
||||
}
|
||||
return ++presenceCount <= PRESENCE_BURST;
|
||||
};
|
||||
presence.connect(userId, socket.id);
|
||||
socket.on('disconnect', () => {
|
||||
presence.disconnect(userId, socket.id);
|
||||
app.services.push.socketGone(userId, socket.id);
|
||||
});
|
||||
// What this tab is looking at, so a push isn't sent for a conversation the user is reading.
|
||||
socket.on('app:visibility', (raw) => {
|
||||
const p = appVisibilitySchema.safeParse(raw);
|
||||
if (p.success) app.services.push.setVisibility(userId, socket.id, p.data);
|
||||
});
|
||||
socket.on('presence:idle', (raw) => {
|
||||
const p = presenceIdleSchema.safeParse(raw);
|
||||
if (p.success && presenceAllowed()) presence.setIdle(userId, socket.id, p.data.idle);
|
||||
});
|
||||
socket.on('presence:set', (raw) => {
|
||||
const p = presenceSetSchema.safeParse(raw);
|
||||
if (p.success && presenceAllowed()) presence.setPref(userId, p.data.status);
|
||||
});
|
||||
});
|
||||
|
||||
app.services.realtime = new SocketHub(io);
|
||||
|
||||
app.addHook('preClose', async () => {
|
||||
io.disconnectSockets(true);
|
||||
io.engine.close();
|
||||
});
|
||||
return io;
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { loginSchema, registerSchema } from '@chat/shared';
|
||||
import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
|
||||
import { SESSION_COOKIE } from '../auth/plugin.js';
|
||||
import type { AppConfig } from '../config.js';
|
||||
import { parse } from '../lib/validate.js';
|
||||
import type { AuthService, SessionInfo } from '../services/auth.js';
|
||||
import type { ServerService } from '../services/servers.js';
|
||||
import { toMeDto } from '../services/users.js';
|
||||
|
||||
export interface AuthRouteDeps {
|
||||
auth: AuthService;
|
||||
servers: ServerService;
|
||||
config: AppConfig;
|
||||
}
|
||||
|
||||
export function cookieIsSecure(req: FastifyRequest, config: AppConfig): boolean {
|
||||
if (config.cookieSecure === 'always') return true;
|
||||
if (config.cookieSecure === 'never') return false;
|
||||
return req.protocol === 'https';
|
||||
}
|
||||
|
||||
function setSessionCookie(
|
||||
req: FastifyRequest,
|
||||
reply: FastifyReply,
|
||||
config: AppConfig,
|
||||
s: SessionInfo,
|
||||
) {
|
||||
reply.setCookie(SESSION_COOKIE, s.token, {
|
||||
httpOnly: true,
|
||||
sameSite: 'lax',
|
||||
secure: cookieIsSecure(req, config),
|
||||
path: '/',
|
||||
expires: s.expiresAt,
|
||||
});
|
||||
}
|
||||
|
||||
export async function authRoutes(app: FastifyInstance, { auth, servers, config }: AuthRouteDeps) {
|
||||
// Only takes effect when @fastify/rate-limit is registered (config.rateLimit.enabled).
|
||||
const rateLimit = {
|
||||
rateLimit: { max: config.rateLimit.authMax, timeWindow: config.rateLimit.authWindowMs },
|
||||
};
|
||||
|
||||
app.post('/api/auth/register', { config: rateLimit }, async (req, reply) => {
|
||||
const input = parse(registerSchema, req.body);
|
||||
const user = await auth.register(input);
|
||||
// Signing up with a server invite link makes them a member; tell that server.
|
||||
for (const serverId of servers.serverIdsFor(user.id)) servers.announceJoin(serverId, user.id);
|
||||
setSessionCookie(req, reply, config, auth.createSession(user.id, req.headers['user-agent']));
|
||||
return reply.code(201).send({ user: toMeDto(user) });
|
||||
});
|
||||
|
||||
app.post('/api/auth/login', { config: rateLimit }, async (req, reply) => {
|
||||
const input = parse(loginSchema, req.body);
|
||||
const user = await auth.login(input);
|
||||
setSessionCookie(req, reply, config, auth.createSession(user.id, req.headers['user-agent']));
|
||||
return reply.send({ user: toMeDto(user) });
|
||||
});
|
||||
|
||||
app.post('/api/auth/logout', async (req, reply) => {
|
||||
// This browser's push subscription goes with the session (optional `pushEndpoint` in the body).
|
||||
const ep = (req.body as { pushEndpoint?: unknown } | null)?.pushEndpoint;
|
||||
if (req.user && typeof ep === 'string') app.services.push.removeByEndpoint(req.user.id, ep);
|
||||
auth.deleteSession(req.cookies[SESSION_COOKIE]);
|
||||
reply.clearCookie(SESSION_COOKIE, { path: '/' });
|
||||
return reply.code(204).send();
|
||||
});
|
||||
|
||||
/** 200 {user: null} when logged out (QA-4), so the first load doesn't log a 401. */
|
||||
app.get('/api/auth/me', async (req) => {
|
||||
return { user: req.user ? toMeDto(req.user) : null };
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { idSchema } from '@chat/shared';
|
||||
import type { FastifyInstance, FastifyRequest } from 'fastify';
|
||||
import { currentUser, requireAuth } from '../auth/plugin.js';
|
||||
import type { AppConfig } from '../config.js';
|
||||
import { parse } from '../lib/validate.js';
|
||||
import type { AppServices } from '../app.js';
|
||||
|
||||
/** M18 blocking: your own list. Responses never mention anyone else's blocks. */
|
||||
export async function blockRoutes(
|
||||
app: FastifyInstance,
|
||||
{ services, config }: { services: AppServices; config: AppConfig },
|
||||
) {
|
||||
const { blocks } = services;
|
||||
const uid = (req: FastifyRequest) => currentUser(req).id;
|
||||
const auth = { preHandler: requireAuth };
|
||||
const limited = {
|
||||
preHandler: requireAuth,
|
||||
config: {
|
||||
rateLimit: {
|
||||
max: config.rateLimit.messageMax * 3,
|
||||
timeWindow: config.rateLimit.messageWindowMs,
|
||||
keyGenerator: (req: FastifyRequest) => req.user?.id ?? req.ip,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
app.get('/api/me/blocks', auth, async (req) => ({ users: blocks.list(uid(req)) }));
|
||||
|
||||
app.put<{ Params: { userId: string } }>('/api/me/blocks/:userId', limited, async (req, reply) => {
|
||||
blocks.block(uid(req), parse(idSchema, req.params.userId));
|
||||
return reply.code(204).send();
|
||||
});
|
||||
|
||||
app.delete<{ Params: { userId: string } }>(
|
||||
'/api/me/blocks/:userId',
|
||||
limited,
|
||||
async (req, reply) => {
|
||||
blocks.unblock(uid(req), parse(idSchema, req.params.userId));
|
||||
return reply.code(204).send();
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import { idSchema, voiceSelfStateSchema } from '@chat/shared';
|
||||
import type { FastifyInstance, FastifyRequest } from 'fastify';
|
||||
import type { AppServices } from '../app.js';
|
||||
import { currentUser, requireAuth } from '../auth/plugin.js';
|
||||
import type { AppConfig } from '../config.js';
|
||||
import { parse } from '../lib/validate.js';
|
||||
|
||||
interface Params {
|
||||
dmId: string;
|
||||
callId: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* DM and group calls (M10, DESIGN-0.2 section 4). Every route answers 404 to anyone who isn't a
|
||||
* current member of the DM, exactly like the DM itself. LiveKit's webhook for call rooms arrives
|
||||
* on the shared /api/livekit/webhook (routes/voice.ts).
|
||||
*/
|
||||
export async function callRoutes(
|
||||
app: FastifyInstance,
|
||||
{ services, config }: { services: AppServices; config: AppConfig },
|
||||
) {
|
||||
const { calls } = services;
|
||||
const uid = (req: FastifyRequest) => currentUser(req).id;
|
||||
const id = (v: string) => parse(idSchema, v);
|
||||
const limited = (factor: number) => ({
|
||||
preHandler: requireAuth,
|
||||
config: {
|
||||
rateLimit: {
|
||||
max: config.rateLimit.messageMax * factor,
|
||||
timeWindow: config.rateLimit.messageWindowMs,
|
||||
keyGenerator: (req: FastifyRequest) => req.user?.id ?? req.ip,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
/** Start a call (201), or get the one already going (200: join it). Rings the other members. */
|
||||
app.post<{ Params: Params }>('/api/dms/:dmId/call', limited(1), async (req, reply) => {
|
||||
const r = calls.start(uid(req), id(req.params.dmId));
|
||||
return reply.code(r.created ? 201 : 200).send({ call: r.call });
|
||||
});
|
||||
|
||||
app.get<{ Params: Params }>('/api/dms/:dmId/call', { preHandler: requireAuth }, async (req) => ({
|
||||
call: calls.get(uid(req), id(req.params.dmId)),
|
||||
}));
|
||||
|
||||
/**
|
||||
* LiveKit token for the active call's own room, `call_<dmId>_<callId>` (QA-58): members only.
|
||||
* `?callId=` is the call the client means to join (QA-59), required since 0.5 (D10): if that
|
||||
* call has ended and another one is active, the answer is 409 instead of a token for the new
|
||||
* call; without it, 400 `call_id_required` (a 0.4 tab has to reload).
|
||||
*/
|
||||
app.post<{ Params: Params; Querystring: { callId?: string } }>(
|
||||
'/api/dms/:dmId/call/token',
|
||||
limited(1),
|
||||
async (req) => {
|
||||
const callId = req.query.callId === undefined ? undefined : id(req.query.callId);
|
||||
return calls.token(uid(req), id(req.params.dmId), callId);
|
||||
},
|
||||
);
|
||||
|
||||
/** Active calls in every DM I'm in (page load: rings still going, "Join call" banners). */
|
||||
app.get('/api/calls', { preHandler: requireAuth }, async (req) => ({
|
||||
calls: calls.listMine(uid(req)),
|
||||
}));
|
||||
|
||||
app.post<{ Params: Params }>('/api/calls/:callId/accept', limited(1), async (req) => ({
|
||||
call: calls.accept(uid(req), id(req.params.callId)),
|
||||
}));
|
||||
|
||||
app.post<{ Params: Params }>('/api/calls/:callId/decline', limited(1), async (req) => {
|
||||
calls.decline(uid(req), id(req.params.callId));
|
||||
return { ok: true };
|
||||
});
|
||||
|
||||
app.post<{ Params: Params }>('/api/calls/:callId/leave', limited(1), async (req) => {
|
||||
calls.leave(uid(req), id(req.params.callId));
|
||||
return { ok: true };
|
||||
});
|
||||
|
||||
app.post<{ Params: Params }>('/api/calls/:callId/state', limited(3), async (req) => ({
|
||||
call: calls.setSelf(uid(req), id(req.params.callId), parse(voiceSelfStateSchema, req.body)),
|
||||
}));
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
import {
|
||||
addGroupMembersSchema,
|
||||
createGroupSchema,
|
||||
dmCandidatesQuerySchema,
|
||||
GROUP_MAX_MEMBERS,
|
||||
idSchema,
|
||||
openDmSchema,
|
||||
updateGroupSchema,
|
||||
} from '@chat/shared';
|
||||
import type { PresenceSnapshotDto } from '@chat/shared';
|
||||
import type { FastifyInstance, FastifyRequest } from 'fastify';
|
||||
import type { AppServices } from '../app.js';
|
||||
import { currentUser, requireAuth } from '../auth/plugin.js';
|
||||
import type { AppConfig } from '../config.js';
|
||||
import { mediaLimitMb, receiveCroppedImage } from '../lib/media-upload.js';
|
||||
import { parse, rejectLongArray } from '../lib/validate.js';
|
||||
|
||||
const TOO_MANY_PEOPLE = `A group can have at most ${GROUP_MAX_MEMBERS} people`;
|
||||
|
||||
/**
|
||||
* DMs (story 4) and presence snapshots (story 5). DM messages, reads and reactions use the shared
|
||||
* message routes (/api/dms/:id/messages, /api/dms/:id/read, /api/messages/:id...).
|
||||
*/
|
||||
export async function dmRoutes(
|
||||
app: FastifyInstance,
|
||||
{ services, config }: { services: AppServices; config: AppConfig },
|
||||
) {
|
||||
const { dms, presence, servers, media, settings } = services;
|
||||
const uid = (req: FastifyRequest) => currentUser(req).id;
|
||||
const auth = { preHandler: requireAuth };
|
||||
// Group changes share the per-user message limit on top of the group add/create limits.
|
||||
const limited = {
|
||||
preHandler: requireAuth,
|
||||
config: {
|
||||
rateLimit: {
|
||||
max: config.rateLimit.messageMax,
|
||||
timeWindow: config.rateLimit.messageWindowMs,
|
||||
keyGenerator: (req: FastifyRequest) => req.user?.id ?? req.ip,
|
||||
},
|
||||
},
|
||||
};
|
||||
type DmParams = { Params: { dmId: string } };
|
||||
|
||||
app.get('/api/dms', auth, async (req) => ({ dms: dms.list(uid(req)) }));
|
||||
|
||||
app.post('/api/dms', auth, async (req, reply) => {
|
||||
const { userId } = parse(openDmSchema, req.body);
|
||||
const { dm, created } = dms.open(uid(req), userId);
|
||||
return reply.code(created ? 201 : 200).send({ dm });
|
||||
});
|
||||
|
||||
app.get('/api/dms/candidates', auth, async (req) => {
|
||||
const { q, dmId } = parse(dmCandidatesQuerySchema, req.query);
|
||||
return { users: dms.candidates(uid(req), q, dmId) };
|
||||
});
|
||||
|
||||
// ---- group DMs (M9, DESIGN-0.2 sections 3 and 6) ----
|
||||
|
||||
app.post('/api/dms/groups', limited, async (req, reply) => {
|
||||
rejectLongArray(req.body, 'userIds', GROUP_MAX_MEMBERS - 1, TOO_MANY_PEOPLE);
|
||||
const { userIds, name } = parse(createGroupSchema, req.body);
|
||||
return reply.code(201).send({ dm: dms.createGroup(uid(req), userIds, name ?? null) });
|
||||
});
|
||||
|
||||
/** Add people. On a 1:1 DM this creates a new group (201); on a group it adds to it (200). */
|
||||
app.post<DmParams>('/api/dms/:dmId/members', limited, async (req, reply) => {
|
||||
const dmId = parse(idSchema, req.params.dmId);
|
||||
rejectLongArray(req.body, 'userIds', GROUP_MAX_MEMBERS - 1, TOO_MANY_PEOPLE);
|
||||
const { userIds } = parse(addGroupMembersSchema, req.body);
|
||||
const { dm, created } = dms.addMembers(uid(req), dmId, userIds);
|
||||
return reply.code(created ? 201 : 200).send({ dm });
|
||||
});
|
||||
|
||||
/** Remove someone (owner), or leave when it's yourself. */
|
||||
app.delete<{ Params: { dmId: string; userId: string } }>(
|
||||
'/api/dms/:dmId/members/:userId',
|
||||
limited,
|
||||
async (req, reply) => {
|
||||
const dmId = parse(idSchema, req.params.dmId);
|
||||
const userId = parse(idSchema, req.params.userId);
|
||||
dms.removeMember(uid(req), dmId, userId);
|
||||
return reply.code(204).send();
|
||||
},
|
||||
);
|
||||
|
||||
app.patch<DmParams>('/api/dms/:dmId', limited, async (req) => {
|
||||
const dmId = parse(idSchema, req.params.dmId);
|
||||
return { dm: dms.update(uid(req), dmId, parse(updateGroupSchema, req.body)) };
|
||||
});
|
||||
|
||||
app.put<DmParams>('/api/dms/:dmId/icon', limited, async (req) => {
|
||||
const me = uid(req);
|
||||
const dmId = parse(idSchema, req.params.dmId);
|
||||
dms.requireIconAccess(me, dmId); // before the body is read
|
||||
const { file, crop } = await receiveCroppedImage(
|
||||
req,
|
||||
media,
|
||||
mediaLimitMb('groupIcon', settings.getAll().maxUploadMb),
|
||||
);
|
||||
let messageId: string | null = null;
|
||||
try {
|
||||
await media.replace(file, 'groupIcon', crop, (id) => {
|
||||
const r = dms.setIcon(me, dmId, id);
|
||||
messageId = r.messageId;
|
||||
return r.previous;
|
||||
});
|
||||
} finally {
|
||||
media.discard(file);
|
||||
}
|
||||
return { dm: dms.iconChanged(me, dmId, messageId) };
|
||||
});
|
||||
|
||||
app.delete<DmParams>('/api/dms/:dmId/icon', limited, async (req) => {
|
||||
const me = uid(req);
|
||||
const dmId = parse(idSchema, req.params.dmId);
|
||||
const r = services.db.transaction(() => dms.setIcon(me, dmId, null)).immediate();
|
||||
media.remove(r.previous);
|
||||
return { dm: dms.iconChanged(me, dmId, r.messageId) };
|
||||
});
|
||||
|
||||
app.get<DmParams>('/api/dms/:dmId', auth, async (req) => ({
|
||||
dm: dms.get(uid(req), parse(idSchema, req.params.dmId)),
|
||||
}));
|
||||
|
||||
/**
|
||||
* Live statuses of everyone who shares a server, a DM or a group with you (offline users are omitted),
|
||||
* plus your own choice. Socket `presence:update` keeps it current afterwards.
|
||||
*/
|
||||
app.get('/api/presence', auth, async (req) => {
|
||||
const me = uid(req);
|
||||
const db = services.db;
|
||||
const serverIds = servers.serverIdsFor(me);
|
||||
const people = new Set<string>(dms.partnersOf(me));
|
||||
if (serverIds.length) {
|
||||
const rows = db
|
||||
.prepare(
|
||||
`SELECT DISTINCT user_id FROM members
|
||||
WHERE banned = 0 AND server_id IN (${serverIds.map(() => '?').join(',')})`,
|
||||
)
|
||||
.all(...serverIds) as { user_id: string }[];
|
||||
for (const r of rows) people.add(r.user_id);
|
||||
}
|
||||
const snapshot: PresenceSnapshotDto = {
|
||||
presence: presence.statusesFor(me, people),
|
||||
custom: presence.customsFor(me, people),
|
||||
self: presence.selfView(me),
|
||||
};
|
||||
return snapshot;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { idSchema, renameEmojiSchema } from '@chat/shared';
|
||||
import type { FastifyInstance, FastifyRequest } from 'fastify';
|
||||
import type { AppServices } from '../app.js';
|
||||
import { currentUser, requireAuth } from '../auth/plugin.js';
|
||||
import { mediaLimitMb, receiveCroppedImage } from '../lib/media-upload.js';
|
||||
import { parse } from '../lib/validate.js';
|
||||
|
||||
/**
|
||||
* Custom server emoji (M24, D27). Upload: multipart `name`, `crop` and `file` (the existing
|
||||
* media pipeline, kind `emoji`: magic-byte type check, 256 KB, square, 64 and 128 WebP). The
|
||||
* image is served by GET /api/media like server icons.
|
||||
*/
|
||||
export async function emojiRoutes(app: FastifyInstance, { services }: { services: AppServices }) {
|
||||
const { emoji, media, settings } = services;
|
||||
const uid = (req: FastifyRequest) => currentUser(req).id;
|
||||
const auth = { preHandler: requireAuth };
|
||||
|
||||
app.get<{ Params: { serverId: string } }>('/api/servers/:serverId/emoji', auth, async (req) => ({
|
||||
emoji: emoji.list(uid(req), parse(idSchema, req.params.serverId)),
|
||||
}));
|
||||
|
||||
app.post<{ Params: { serverId: string } }>(
|
||||
'/api/servers/:serverId/emoji',
|
||||
auth,
|
||||
async (req, reply) => {
|
||||
const me = uid(req);
|
||||
const serverId = parse(idSchema, req.params.serverId);
|
||||
// Membership, the rate limit and the cap before the body is read.
|
||||
emoji.beginUpload(me, serverId);
|
||||
const { file, crop, fields } = await receiveCroppedImage(
|
||||
req,
|
||||
media,
|
||||
mediaLimitMb('emoji', settings.getAll().maxUploadMb),
|
||||
['name'],
|
||||
);
|
||||
let created;
|
||||
try {
|
||||
const name = emoji.checkName(serverId, fields.name);
|
||||
const { mediaId, animated } = await media.ingestImage(file, 'emoji', crop);
|
||||
try {
|
||||
created = emoji.create(me, serverId, name, mediaId, animated);
|
||||
} catch (err) {
|
||||
media.remove(mediaId);
|
||||
throw err;
|
||||
}
|
||||
} finally {
|
||||
media.discard(file);
|
||||
}
|
||||
return reply.code(201).send({ emoji: created });
|
||||
},
|
||||
);
|
||||
|
||||
app.patch<{ Params: { emojiId: string } }>('/api/emoji/:emojiId', auth, async (req) => {
|
||||
const { name } = parse(renameEmojiSchema, req.body);
|
||||
return { emoji: emoji.rename(uid(req), parse(idSchema, req.params.emojiId), name) };
|
||||
});
|
||||
|
||||
app.delete<{ Params: { emojiId: string } }>('/api/emoji/:emojiId', auth, async (req, reply) => {
|
||||
media.remove(emoji.delete(uid(req), parse(idSchema, req.params.emojiId)));
|
||||
return reply.code(204).send();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import {
|
||||
type BuildInfoDto,
|
||||
createInstanceInviteSchema,
|
||||
instanceSettingsPatchSchema,
|
||||
type InstanceInfoDto,
|
||||
type InviteDto,
|
||||
} from '@chat/shared';
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import { currentUser, requireInstanceAdmin } from '../auth/plugin.js';
|
||||
import type { DB } from '../db/index.js';
|
||||
import { parse } from '../lib/validate.js';
|
||||
import type { AuthService, InviteRow } from '../services/auth.js';
|
||||
import type { SettingsService } from '../services/settings.js';
|
||||
|
||||
export interface InstanceRouteDeps {
|
||||
appName: string;
|
||||
voiceEnabled: boolean;
|
||||
/** VIDEO_ENABLED: the same flag as the Permissions-Policy header and the token grants. */
|
||||
videoEnabled: boolean;
|
||||
callRingMs: number;
|
||||
/** apps/server/package.json version (QA-62). */
|
||||
version: string;
|
||||
/** D22: build.json or git, read once at start; also on /api/health. */
|
||||
build: BuildInfoDto;
|
||||
db: DB;
|
||||
auth: AuthService;
|
||||
settings: SettingsService;
|
||||
}
|
||||
|
||||
function toInviteDto(row: InviteRow): InviteDto {
|
||||
return {
|
||||
code: row.code,
|
||||
serverId: row.server_id,
|
||||
maxUses: row.max_uses,
|
||||
uses: row.uses,
|
||||
expiresAt: row.expires_at,
|
||||
};
|
||||
}
|
||||
|
||||
export async function instanceRoutes(
|
||||
app: FastifyInstance,
|
||||
{
|
||||
appName,
|
||||
voiceEnabled,
|
||||
videoEnabled,
|
||||
callRingMs,
|
||||
version,
|
||||
build,
|
||||
db,
|
||||
auth,
|
||||
settings,
|
||||
}: InstanceRouteDeps,
|
||||
) {
|
||||
/** Public: lets the login screen know whether to ask for an invite code / show "create admin". */
|
||||
app.get('/api/instance', async (): Promise<InstanceInfoDto> => {
|
||||
const hasUsers = db.prepare('SELECT 1 FROM users LIMIT 1').get() !== undefined;
|
||||
return {
|
||||
appName,
|
||||
registrationOpen: settings.isRegistrationOpen(),
|
||||
hasUsers,
|
||||
maxUploadMb: settings.getAll().maxUploadMb,
|
||||
voiceEnabled,
|
||||
videoEnabled,
|
||||
callRingMs,
|
||||
version,
|
||||
build,
|
||||
};
|
||||
});
|
||||
|
||||
app.get('/api/admin/settings', { preHandler: requireInstanceAdmin }, async () =>
|
||||
settings.getAll(),
|
||||
);
|
||||
|
||||
app.patch('/api/admin/settings', { preHandler: requireInstanceAdmin }, async (req) => {
|
||||
return settings.update(parse(instanceSettingsPatchSchema, req.body));
|
||||
});
|
||||
|
||||
app.get('/api/admin/invites', { preHandler: requireInstanceAdmin }, async () => {
|
||||
const rows = db
|
||||
.prepare('SELECT * FROM invites WHERE server_id IS NULL ORDER BY created_at DESC')
|
||||
.all() as InviteRow[];
|
||||
return { invites: rows.map(toInviteDto) };
|
||||
});
|
||||
|
||||
app.post('/api/admin/invites', { preHandler: requireInstanceAdmin }, async (req, reply) => {
|
||||
const input = parse(createInstanceInviteSchema, req.body);
|
||||
const row = auth.createInstanceInvite(currentUser(req).id, input);
|
||||
return reply.code(201).send({ invite: toInviteDto(row) });
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { displayNameSchema, updateMeSchema } from '@chat/shared';
|
||||
import type { FastifyInstance, FastifyRequest } from 'fastify';
|
||||
import { currentUser } from '../auth/plugin.js';
|
||||
import type { AppConfig } from '../config.js';
|
||||
import { profileLimitedWhen } from '../lib/profile-limit.js';
|
||||
import { parse } from '../lib/validate.js';
|
||||
import type { UserService } from '../services/users.js';
|
||||
|
||||
export async function meRoutes(
|
||||
app: FastifyInstance,
|
||||
{ users, config }: { users: UserService; config: AppConfig },
|
||||
) {
|
||||
/**
|
||||
* D69 (QA-167): only a real display-name change counts against the D57 limit (D67, QA-166).
|
||||
* Theme saves share this route and are not limited by it; an unchanged name isn't either.
|
||||
*/
|
||||
const changesName = (req: FastifyRequest): boolean => {
|
||||
const raw = (req.body as { displayName?: unknown } | null | undefined)?.displayName;
|
||||
if (raw === undefined) return false;
|
||||
const next = displayNameSchema.safeParse(raw);
|
||||
if (!next.success) return true; // a 400 anyway; counting it is the safe side
|
||||
return next.data !== users.getById(currentUser(req).id)?.display_name;
|
||||
};
|
||||
app.patch('/api/me', profileLimitedWhen(config, changesName), async (req) => {
|
||||
const input = parse(updateMeSchema, req.body);
|
||||
return { user: users.updateMe(currentUser(req).id, input) };
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
import {
|
||||
createMessageSchema,
|
||||
emojiSchema,
|
||||
idSchema,
|
||||
MAX_ATTACHMENTS,
|
||||
messagesQuerySchema,
|
||||
updateMessageSchema,
|
||||
} from '@chat/shared';
|
||||
import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
|
||||
import { createReadStream } from 'node:fs';
|
||||
import { stat } from 'node:fs/promises';
|
||||
import type { AppServices } from '../app.js';
|
||||
import { currentUser, requireAuth } from '../auth/plugin.js';
|
||||
import type { AppConfig } from '../config.js';
|
||||
import { notModified, sendNotModified, strongEtag } from '../lib/conditional.js';
|
||||
import { badRequest, notFound } from '../lib/errors.js';
|
||||
import { contentDisposition } from '../lib/files.js';
|
||||
import { parse, rejectLongArray } from '../lib/validate.js';
|
||||
import type { ConvRef } from '../services/messages.js';
|
||||
import { tooLarge } from '../services/uploads.js';
|
||||
|
||||
const TOO_MANY_ATTACHMENTS = `A message can have at most ${MAX_ATTACHMENTS} attachments`;
|
||||
|
||||
interface Params {
|
||||
channelId: string;
|
||||
messageId: string;
|
||||
emoji: string;
|
||||
attachmentId: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Messages, reactions, read states, uploads (story 3). Message posting, edits, reactions and
|
||||
* uploads are rate limited per user (falls back to IP), each with its own bucket.
|
||||
*/
|
||||
export async function messageRoutes(
|
||||
app: FastifyInstance,
|
||||
{ services, config }: { services: AppServices; config: AppConfig },
|
||||
) {
|
||||
const { messages, uploads, settings } = services;
|
||||
const uid = (req: FastifyRequest) => currentUser(req).id;
|
||||
const limited = (factor: number) => ({
|
||||
preHandler: requireAuth,
|
||||
config: {
|
||||
rateLimit: {
|
||||
max: config.rateLimit.messageMax * factor,
|
||||
timeWindow: config.rateLimit.messageWindowMs,
|
||||
keyGenerator: (req: FastifyRequest) => req.user?.id ?? req.ip,
|
||||
},
|
||||
},
|
||||
});
|
||||
const auth = { preHandler: requireAuth };
|
||||
const id = (v: string) => parse(idSchema, v);
|
||||
|
||||
// ---- messages: server text channels and DMs share one implementation ----
|
||||
// DM routes authorize strictly through canAccessDm/requireDmAccess (participants only, else 404).
|
||||
for (const [kind, base] of [
|
||||
['channel', '/api/channels/:channelId'],
|
||||
['dm', '/api/dms/:channelId'],
|
||||
// M25: a thread is a conversation of its own (D25); its access is its channel's.
|
||||
['thread', '/api/threads/:channelId'],
|
||||
] as const) {
|
||||
const ref = (req: FastifyRequest<{ Params: Params }>): ConvRef => ({
|
||||
kind,
|
||||
id: id(req.params.channelId),
|
||||
});
|
||||
|
||||
app.get<{ Params: Params }>(`${base}/messages`, auth, async (req) => {
|
||||
const q = parse(messagesQuerySchema, req.query);
|
||||
return messages.list(uid(req), ref(req), q);
|
||||
});
|
||||
|
||||
app.post<{ Params: Params }>(`${base}/messages`, limited(1), async (req, reply) => {
|
||||
rejectLongArray(req.body, 'attachmentIds', MAX_ATTACHMENTS, TOO_MANY_ATTACHMENTS);
|
||||
const input = parse(createMessageSchema, req.body);
|
||||
return reply.code(201).send({ message: messages.create(uid(req), ref(req), input) });
|
||||
});
|
||||
|
||||
// ---- pins (M17): anyone who can post in the chat can pin and unpin (DESIGN-0.4 D6, D9) ----
|
||||
app.get<{ Params: Params }>(`${base}/pins`, auth, async (req) => ({
|
||||
pins: messages.listPins(uid(req), ref(req)),
|
||||
}));
|
||||
|
||||
// D14 (QA-65): pin + unpin share one per-person limit of 10 a minute over all chats,
|
||||
// enforced in MessageService (429 too_many_pins), so these routes need only auth.
|
||||
app.put<{ Params: Params }>(`${base}/pins/:messageId`, auth, async (req, reply) => {
|
||||
const r = messages.pin(uid(req), ref(req), id(req.params.messageId));
|
||||
return reply.code(r.created ? 201 : 200).send({ pinned: true });
|
||||
});
|
||||
|
||||
app.delete<{ Params: Params }>(`${base}/pins/:messageId`, auth, async (req, reply) => {
|
||||
messages.unpin(uid(req), ref(req), id(req.params.messageId));
|
||||
return reply.code(204).send();
|
||||
});
|
||||
|
||||
app.post<{ Params: Params }>(`${base}/read`, auth, async (req) => {
|
||||
const body = (req.body ?? {}) as { messageId?: unknown };
|
||||
const messageId = body.messageId === undefined ? undefined : id(String(body.messageId));
|
||||
return { unread: messages.markRead(uid(req), ref(req), messageId) };
|
||||
});
|
||||
}
|
||||
|
||||
app.get<{ Params: Params }>('/api/messages/:messageId', auth, async (req) => ({
|
||||
message: messages.getForReader(uid(req), id(req.params.messageId)),
|
||||
}));
|
||||
|
||||
app.patch<{ Params: Params }>('/api/messages/:messageId', limited(2), async (req) => {
|
||||
const { content } = parse(updateMessageSchema, req.body);
|
||||
return { message: messages.update(uid(req), id(req.params.messageId), content) };
|
||||
});
|
||||
|
||||
app.delete<{ Params: Params }>('/api/messages/:messageId', limited(2), async (req, reply) => {
|
||||
messages.delete(uid(req), id(req.params.messageId));
|
||||
return reply.code(204).send();
|
||||
});
|
||||
|
||||
// ---- reactions (emoji is URL-encoded in the path) ----
|
||||
for (const [method, add] of [
|
||||
['PUT', true],
|
||||
['DELETE', false],
|
||||
] as const) {
|
||||
app.route<{ Params: Params }>({
|
||||
method,
|
||||
url: '/api/messages/:messageId/reactions/:emoji',
|
||||
...limited(3),
|
||||
handler: async (req) => {
|
||||
const emoji = parse(emojiSchema, req.params.emoji);
|
||||
return { reaction: messages.react(uid(req), id(req.params.messageId), emoji, add) };
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// ---- read states ----
|
||||
// M25 (D29): plus unread in the threads you follow.
|
||||
app.get('/api/unread', auth, async (req) => ({
|
||||
unread: messages.unreadFor(uid(req)),
|
||||
threads: messages.threadUnread(uid(req)),
|
||||
}));
|
||||
|
||||
// ---- uploads ----
|
||||
async function receiveFile(req: FastifyRequest, maxMb: number) {
|
||||
if (!req.isMultipart()) throw badRequest('Send the file as multipart/form-data');
|
||||
const maxBytes = maxMb * 1024 * 1024;
|
||||
const part = await req.file({ limits: { fileSize: maxBytes, files: 1, fields: 0 } });
|
||||
if (!part) throw badRequest('No file in the request');
|
||||
const stored = await uploads.store(part.file, maxBytes, maxMb);
|
||||
return { part, stored };
|
||||
}
|
||||
|
||||
app.post('/api/uploads', limited(1), async (req, reply) => {
|
||||
const maxMb = settings.getAll().maxUploadMb;
|
||||
const declared = Number(req.headers['content-length'] ?? 0);
|
||||
// Cheap early reject; the streaming check below is the real limit.
|
||||
if (declared > maxMb * 1024 * 1024 + 64 * 1024) throw tooLarge(maxMb);
|
||||
const { part, stored } = await receiveFile(req, maxMb);
|
||||
const attachment = uploads.create(uid(req), stored, part.filename, part.mimetype);
|
||||
return reply.code(201).send({ attachment });
|
||||
});
|
||||
|
||||
/**
|
||||
* Download. Inline only for verified png/jpeg/gif/webp; everything else is an attachment.
|
||||
* Access is checked by the caller before this runs, and the file is found before any header is
|
||||
* set, so a 404 is the same whatever the reason. Files from DMs and group DMs (and unsent
|
||||
* uploads) are `private, no-cache` with a strong ETag: the browser revalidates every time, the
|
||||
* access check runs again first, and a member gets a cheap 304 while a leaver gets the 404.
|
||||
*/
|
||||
async function sendStored(
|
||||
req: FastifyRequest,
|
||||
reply: FastifyReply,
|
||||
file: { id: string; path: string; filename: string; mime: string },
|
||||
privateFile: boolean,
|
||||
) {
|
||||
const full = uploads.filePath(file.path);
|
||||
const info = await stat(full).catch((e: NodeJS.ErrnoException) => {
|
||||
throw e.code === 'ENOENT' ? notFound('File not found') : e;
|
||||
});
|
||||
const etag = strongEtag(file.id, info);
|
||||
const cacheControl = privateFile ? 'private, no-cache' : 'private, max-age=31536000, immutable';
|
||||
if (notModified(req, etag)) return sendNotModified(reply, etag, cacheControl);
|
||||
const stream = createReadStream(full);
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
stream.once('open', () => resolve());
|
||||
stream.once('error', (e) =>
|
||||
reject((e as NodeJS.ErrnoException).code === 'ENOENT' ? notFound('File not found') : e),
|
||||
);
|
||||
});
|
||||
const inline = ['image/png', 'image/jpeg', 'image/gif', 'image/webp'].includes(file.mime);
|
||||
reply
|
||||
.header('Content-Type', inline ? file.mime : 'application/octet-stream')
|
||||
.header(
|
||||
'Content-Disposition',
|
||||
contentDisposition(inline ? 'inline' : 'attachment', file.filename),
|
||||
)
|
||||
.header('X-Content-Type-Options', 'nosniff')
|
||||
.header(
|
||||
'Content-Security-Policy',
|
||||
"default-src 'none'; img-src 'self'; style-src 'unsafe-inline'; sandbox",
|
||||
)
|
||||
.header('Cache-Control', cacheControl)
|
||||
.header('ETag', etag)
|
||||
.header('Cross-Origin-Resource-Policy', 'same-origin');
|
||||
return reply.send(stream);
|
||||
}
|
||||
|
||||
const download = async (req: FastifyRequest<{ Params: Params }>, reply: FastifyReply) => {
|
||||
// Access first: a cached ETag never turns a 404 into a 304.
|
||||
const row = uploads.requireViewable(uid(req), id(req.params.attachmentId));
|
||||
return sendStored(req, reply, row, uploads.isPrivate(row));
|
||||
};
|
||||
// Errors (401/404) are never cacheable either, so a 404 after leaving can't be served stale.
|
||||
const noStoreErrors = {
|
||||
...auth,
|
||||
onSend: async (_req: FastifyRequest, reply: FastifyReply, payload: unknown) => {
|
||||
if (reply.statusCode >= 400) reply.header('Cache-Control', 'no-store');
|
||||
return payload;
|
||||
},
|
||||
};
|
||||
app.get<{ Params: Params }>('/api/attachments/:attachmentId', noStoreErrors, download);
|
||||
app.get<{ Params: Params }>('/api/attachments/:attachmentId/*', noStoreErrors, download);
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
import {
|
||||
idSchema,
|
||||
MEDIA_SIZES,
|
||||
statusTextSchema,
|
||||
updateProfileSchema,
|
||||
type MediaKind,
|
||||
} from '@chat/shared';
|
||||
import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
|
||||
import { createReadStream } from 'node:fs';
|
||||
import { stat } from 'node:fs/promises';
|
||||
import type { AppServices } from '../app.js';
|
||||
import { isDmMember } from '../auth/permissions.js';
|
||||
import { currentUser, requireAuth } from '../auth/plugin.js';
|
||||
import type { AppConfig } from '../config.js';
|
||||
import { notModified, sendNotModified, strongEtag } from '../lib/conditional.js';
|
||||
import { notFound } from '../lib/errors.js';
|
||||
import { mediaLimitMb, receiveCroppedImage } from '../lib/media-upload.js';
|
||||
import { profileLimited } from '../lib/profile-limit.js';
|
||||
import { parse } from '../lib/validate.js';
|
||||
import { toMeDto, type ProfileImage } from '../services/users.js';
|
||||
|
||||
interface Params {
|
||||
userId: string;
|
||||
mediaId: string;
|
||||
size: string;
|
||||
}
|
||||
|
||||
const KIND: Record<ProfileImage, MediaKind> = { avatar: 'avatar', banner: 'profileBanner' };
|
||||
|
||||
/** Profiles and display pictures (M7, DESIGN-0.2 section 1) plus the media route (section 0). */
|
||||
export async function profileRoutes(
|
||||
app: FastifyInstance,
|
||||
{ services, config }: { services: AppServices; config: AppConfig },
|
||||
) {
|
||||
const { users, media, settings, dms, presence } = services;
|
||||
const uid = (req: FastifyRequest) => currentUser(req).id;
|
||||
const auth = { preHandler: requireAuth };
|
||||
const limited = profileLimited(config);
|
||||
|
||||
app.patch('/api/me/profile', limited, async (req) => ({
|
||||
user: users.updateProfile(uid(req), parse(updateProfileSchema, req.body)),
|
||||
}));
|
||||
|
||||
// D49: custom status text, rate limited like display-name changes (the same `limited`).
|
||||
app.put('/api/me/status-text', limited, async (req) => ({
|
||||
custom: presence.setCustom(uid(req), parse(statusTextSchema, req.body)),
|
||||
}));
|
||||
app.delete('/api/me/status-text', limited, async (req, reply) => {
|
||||
presence.setCustom(uid(req), null);
|
||||
return reply.code(204).send();
|
||||
});
|
||||
|
||||
for (const which of ['avatar', 'banner'] as const) {
|
||||
app.put(`/api/me/${which}`, limited, async (req) => {
|
||||
const me = uid(req);
|
||||
const kind = KIND[which];
|
||||
const { file, crop } = await receiveCroppedImage(
|
||||
req,
|
||||
media,
|
||||
mediaLimitMb(kind, settings.getAll().maxUploadMb),
|
||||
);
|
||||
try {
|
||||
await media.replace(file, kind, crop, (id) => users.setImage(me, which, id));
|
||||
} finally {
|
||||
media.discard(file);
|
||||
}
|
||||
users.broadcast(me);
|
||||
return { user: toMeDto(users.getById(me)!) };
|
||||
});
|
||||
|
||||
app.delete(`/api/me/${which}`, limited, async (req) => {
|
||||
const me = uid(req);
|
||||
const previous = users.setImage(me, which, null);
|
||||
media.remove(previous);
|
||||
if (previous) users.broadcast(me);
|
||||
return { user: toMeDto(users.getById(me)!) };
|
||||
});
|
||||
}
|
||||
|
||||
app.get<{ Params: Params }>('/api/users/:userId/profile', auth, async (req) => ({
|
||||
profile: users.profile(uid(req), parse(idSchema, req.params.userId)),
|
||||
}));
|
||||
|
||||
/**
|
||||
* Media variants. Needs a session; the id is an unguessable key handed out only by APIs that
|
||||
* apply their own visibility rules (DESIGN-0.2 section 0). Immutable: new image, new id.
|
||||
*
|
||||
* Scoped media (group DM icons, media_scopes, section 6) is served only to current members of
|
||||
* its group, checked on every request. Anyone else gets exactly the 404 a nonexistent id gets
|
||||
* (same status, headers and body: the same error is thrown before any header is set). Scoped
|
||||
* images are `private, no-cache` with a strong ETag, so the browser revalidates on every use:
|
||||
* the membership check runs before If-None-Match is looked at, so a member gets a 304 and
|
||||
* someone who left gets the 404 on the very next request even with a cached copy and a valid
|
||||
* ETag. Error responses here are never cacheable (no-store).
|
||||
*/
|
||||
app.get<{ Params: Params }>(
|
||||
'/api/media/:mediaId/:size',
|
||||
{
|
||||
...auth,
|
||||
onSend: async (_req, reply, payload) => {
|
||||
if (reply.statusCode >= 400) reply.header('Cache-Control', 'no-store');
|
||||
return payload;
|
||||
},
|
||||
},
|
||||
async (req, reply) => {
|
||||
const size = Number(req.params.size);
|
||||
if (!(MEDIA_SIZES as readonly number[]).includes(size)) throw notFound('Image not found');
|
||||
const file = media.filePath(req.params.mediaId, size);
|
||||
const scope = dms.mediaScope(req.params.mediaId);
|
||||
if (scope !== null && !isDmMember(services.db, currentUser(req).id, scope)) {
|
||||
throw notFound('Image not found');
|
||||
}
|
||||
return sendMedia(req, reply, `${req.params.mediaId}.${size}`, file, scope !== null);
|
||||
},
|
||||
);
|
||||
|
||||
async function sendMedia(
|
||||
req: FastifyRequest,
|
||||
reply: FastifyReply,
|
||||
key: string,
|
||||
file: string,
|
||||
scoped = false,
|
||||
) {
|
||||
const info = await stat(file).catch((e: NodeJS.ErrnoException) => {
|
||||
throw e.code === 'ENOENT' || e.code === 'ENOTDIR' ? notFound('Image not found') : e;
|
||||
});
|
||||
const etag = strongEtag(key, info);
|
||||
const cacheControl = scoped ? 'private, no-cache' : 'private, max-age=31536000, immutable';
|
||||
if (notModified(req, etag)) return sendNotModified(reply, etag, cacheControl);
|
||||
const stream = createReadStream(file);
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
stream.once('open', () => resolve());
|
||||
stream.once('error', (e) =>
|
||||
reject((e as NodeJS.ErrnoException).code === 'ENOENT' ? notFound('Image not found') : e),
|
||||
);
|
||||
});
|
||||
reply
|
||||
.header('Content-Type', 'image/webp')
|
||||
.header('Cache-Control', cacheControl)
|
||||
.header('ETag', etag)
|
||||
.header('X-Content-Type-Options', 'nosniff')
|
||||
.header('Content-Security-Policy', "default-src 'none'; sandbox")
|
||||
.header('Cross-Origin-Resource-Policy', 'same-origin');
|
||||
return reply.send(stream);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import {
|
||||
notifyPrefSchema,
|
||||
notifySettingsSchema,
|
||||
pushEndpointSchema,
|
||||
pushSubscribeSchema,
|
||||
} from '@chat/shared';
|
||||
import type { FastifyInstance, FastifyRequest } from 'fastify';
|
||||
import type { AppServices } from '../app.js';
|
||||
import { currentUser, requireAuth } from '../auth/plugin.js';
|
||||
import type { AppConfig } from '../config.js';
|
||||
import { notFound } from '../lib/errors.js';
|
||||
import { parse } from '../lib/validate.js';
|
||||
|
||||
/** Push: the public key, this user's devices, per-user settings, and a test button. */
|
||||
export async function pushRoutes(
|
||||
app: FastifyInstance,
|
||||
{ services, config }: { services: AppServices; config: AppConfig },
|
||||
) {
|
||||
const { push } = services;
|
||||
const uid = (req: FastifyRequest) => currentUser(req).id;
|
||||
const limited = (max: number) => ({
|
||||
preHandler: requireAuth,
|
||||
config: {
|
||||
rateLimit: {
|
||||
max,
|
||||
timeWindow: 60_000,
|
||||
keyGenerator: (req: FastifyRequest) => req.user?.id ?? req.ip,
|
||||
},
|
||||
},
|
||||
});
|
||||
void config;
|
||||
const auth = { preHandler: requireAuth };
|
||||
|
||||
// The public key only (the private key never leaves the server).
|
||||
app.get('/api/push/key', auth, async () => ({ publicKey: push.publicKey }));
|
||||
|
||||
app.get('/api/push/subscriptions', auth, async (req) => ({
|
||||
subscriptions: push.list(uid(req)),
|
||||
}));
|
||||
|
||||
app.post('/api/push/subscriptions', limited(20), async (req, reply) => {
|
||||
const input = parse(pushSubscribeSchema, req.body);
|
||||
const ua = typeof req.headers['user-agent'] === 'string' ? req.headers['user-agent'] : null;
|
||||
return reply.code(201).send({ subscription: push.subscribe(uid(req), input, ua) });
|
||||
});
|
||||
|
||||
// Turn this device off (by endpoint, owner only) or remove one from the list (by id).
|
||||
app.post('/api/push/unsubscribe', auth, async (req, reply) => {
|
||||
const { endpoint } = parse(pushEndpointSchema, req.body);
|
||||
push.removeByEndpoint(uid(req), endpoint);
|
||||
return reply.code(204).send();
|
||||
});
|
||||
app.delete<{ Params: { id: string } }>(
|
||||
'/api/push/subscriptions/:id',
|
||||
auth,
|
||||
async (req, reply) => {
|
||||
if (!push.removeById(uid(req), req.params.id)) throw notFound('Device not found');
|
||||
return reply.code(204).send();
|
||||
},
|
||||
);
|
||||
|
||||
app.post('/api/push/test', limited(5), async (req) => ({ sent: await push.sendTest(uid(req)) }));
|
||||
|
||||
app.get('/api/push/settings', auth, async (req) => push.getSettings(uid(req)));
|
||||
app.patch('/api/push/settings', auth, async (req) =>
|
||||
push.updateSettings(uid(req), parse(notifySettingsSchema, req.body)),
|
||||
);
|
||||
app.put('/api/push/prefs', auth, async (req, reply) => {
|
||||
push.setPref(uid(req), parse(notifyPrefSchema, req.body));
|
||||
return reply.code(204).send();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import { buildManifest, renderServiceWorker } from '../lib/pwa.js';
|
||||
|
||||
export interface PwaRouteDeps {
|
||||
appName: string;
|
||||
appVersion: string;
|
||||
staticDir: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /manifest.webmanifest and GET /sw.js. Neither is cached by the browser's HTTP cache
|
||||
* (`no-cache`), so a new release is noticed on the next launch and an old worker can't linger
|
||||
* (the browser also bypasses the HTTP cache for worker scripts when registered with
|
||||
* `updateViaCache: 'none'`).
|
||||
*/
|
||||
export async function pwaRoutes(app: FastifyInstance, deps: PwaRouteDeps): Promise<void> {
|
||||
const manifest = JSON.stringify(buildManifest(deps.appName));
|
||||
app.get('/manifest.webmanifest', async (_req, reply) => {
|
||||
return reply
|
||||
.header('Cache-Control', 'no-cache')
|
||||
.type('application/manifest+json; charset=utf-8')
|
||||
.send(manifest);
|
||||
});
|
||||
|
||||
const swFile = deps.staticDir ? path.join(deps.staticDir, 'sw.js') : null;
|
||||
let template: string | null = null;
|
||||
app.get('/sw.js', async (_req, reply) => {
|
||||
try {
|
||||
template ??= swFile ? readFileSync(swFile, 'utf8') : null;
|
||||
} catch {
|
||||
template = null;
|
||||
}
|
||||
if (template === null) {
|
||||
return reply.code(404).send({ error: 'not_found', message: 'Not found' });
|
||||
}
|
||||
return reply
|
||||
.header('Cache-Control', 'no-cache')
|
||||
.header('Service-Worker-Allowed', '/')
|
||||
.type('text/javascript; charset=utf-8')
|
||||
.send(renderServiceWorker(template, deps.appVersion));
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import {
|
||||
channelPermissionsSchema,
|
||||
createRoleSchema,
|
||||
idSchema,
|
||||
memberRolesSchema,
|
||||
reorderRolesSchema,
|
||||
updateRoleSchema,
|
||||
} from '@chat/shared';
|
||||
import type { FastifyInstance, FastifyRequest } from 'fastify';
|
||||
import type { AppServices } from '../app.js';
|
||||
import { currentUser, requireAuth } from '../auth/plugin.js';
|
||||
import { parse } from '../lib/validate.js';
|
||||
|
||||
interface Params {
|
||||
serverId: string;
|
||||
roleId: string;
|
||||
userId: string;
|
||||
channelId: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* M29 roles and channel permissions (DESIGN-0.6 section 6). Every check, the hierarchy (D40) and
|
||||
* the shared 30-a-minute write limit (D57) are in RoleService.
|
||||
*/
|
||||
export async function roleRoutes(app: FastifyInstance, { services }: { services: AppServices }) {
|
||||
const { roles, servers } = services;
|
||||
const auth = { preHandler: requireAuth };
|
||||
const uid = (req: FastifyRequest) => currentUser(req).id;
|
||||
const id = (v: string) => parse(idSchema, v);
|
||||
const base = '/api/servers/:serverId';
|
||||
|
||||
app.get<{ Params: Params }>(`${base}/roles`, auth, async (req) => ({
|
||||
roles: roles.list(uid(req), id(req.params.serverId)),
|
||||
}));
|
||||
|
||||
app.post<{ Params: Params }>(`${base}/roles`, auth, async (req, reply) => {
|
||||
const input = parse(createRoleSchema, req.body ?? {});
|
||||
const role = roles.create(uid(req), id(req.params.serverId), input);
|
||||
return reply.code(201).send({ role });
|
||||
});
|
||||
|
||||
// Registered before /roles/:roleId so "order" is never read as an id.
|
||||
app.put<{ Params: Params }>(`${base}/roles/order`, auth, async (req) => {
|
||||
const { roleIds } = parse(reorderRolesSchema, req.body ?? {});
|
||||
return { roles: roles.reorder(uid(req), id(req.params.serverId), roleIds) };
|
||||
});
|
||||
|
||||
app.patch<{ Params: Params }>(`${base}/roles/:roleId`, auth, async (req) => {
|
||||
const input = parse(updateRoleSchema, req.body ?? {});
|
||||
return {
|
||||
role: roles.update(uid(req), id(req.params.serverId), id(req.params.roleId), input),
|
||||
};
|
||||
});
|
||||
|
||||
app.delete<{ Params: Params }>(`${base}/roles/:roleId`, auth, async (req, reply) => {
|
||||
roles.remove(uid(req), id(req.params.serverId), id(req.params.roleId));
|
||||
return reply.code(204).send();
|
||||
});
|
||||
|
||||
app.put<{ Params: Params }>(`${base}/members/:userId/roles`, auth, async (req) => {
|
||||
const { roleIds } = parse(memberRolesSchema, req.body ?? {});
|
||||
return {
|
||||
member: roles.setMemberRoles(
|
||||
uid(req),
|
||||
id(req.params.serverId),
|
||||
id(req.params.userId),
|
||||
roleIds,
|
||||
(s, u) => servers.memberDto(s, u),
|
||||
),
|
||||
};
|
||||
});
|
||||
|
||||
app.get<{ Params: Params }>(`${base}/channels/:channelId/permissions`, auth, async (req) =>
|
||||
roles.getChannelPermissions(uid(req), id(req.params.serverId), id(req.params.channelId)),
|
||||
);
|
||||
|
||||
app.put<{ Params: Params }>(`${base}/channels/:channelId/permissions`, auth, async (req) => {
|
||||
const { overrides } = parse(channelPermissionsSchema, req.body ?? {});
|
||||
return roles.setChannelPermissions(
|
||||
uid(req),
|
||||
id(req.params.serverId),
|
||||
id(req.params.channelId),
|
||||
overrides,
|
||||
);
|
||||
});
|
||||
|
||||
/** D61: names only, for the channel-permissions page. */
|
||||
app.get<{ Params: Params }>(`${base}/channel-names`, auth, async (req) => ({
|
||||
channels: roles.channelNames(uid(req), id(req.params.serverId)),
|
||||
}));
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { searchQuerySchema } from '@chat/shared';
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import type { AppServices } from '../app.js';
|
||||
import { currentUser, requireAuth } from '../auth/plugin.js';
|
||||
import { parse } from '../lib/validate.js';
|
||||
|
||||
/** GET /api/search (M23, DESIGN-0.5 section 2b). The 30-a-minute limit is in SearchService. */
|
||||
export async function searchRoutes(app: FastifyInstance, { services }: { services: AppServices }) {
|
||||
app.get('/api/search', { preHandler: requireAuth }, async (req) =>
|
||||
services.search.search(currentUser(req).id, parse(searchQuerySchema, req.query)),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { idSchema, type MediaKind } from '@chat/shared';
|
||||
import type { FastifyInstance, FastifyRequest } from 'fastify';
|
||||
import type { AppServices } from '../app.js';
|
||||
import { currentUser, requireAuth } from '../auth/plugin.js';
|
||||
import type { AppConfig } from '../config.js';
|
||||
import { mediaLimitMb, receiveCroppedImage } from '../lib/media-upload.js';
|
||||
import { parse } from '../lib/validate.js';
|
||||
import type { ServerImage } from '../services/servers.js';
|
||||
|
||||
interface Params {
|
||||
serverId: string;
|
||||
}
|
||||
|
||||
const KIND: Record<ServerImage, MediaKind> = { icon: 'serverIcon', banner: 'serverBanner' };
|
||||
|
||||
/**
|
||||
* Server icons and banners (M8, DESIGN-0.2 section 2) on the shared media pipeline. Admin and
|
||||
* owner only: 403 for members, 404 for outsiders and banned users (checked before the body is
|
||||
* read, and again inside the swap transaction). Images are served by GET /api/media.
|
||||
*/
|
||||
export async function serverMediaRoutes(
|
||||
app: FastifyInstance,
|
||||
{ services, config }: { services: AppServices; config: AppConfig },
|
||||
) {
|
||||
const { servers, media, settings, uploads } = services;
|
||||
const uid = (req: FastifyRequest) => currentUser(req).id;
|
||||
const limited = {
|
||||
preHandler: requireAuth,
|
||||
config: {
|
||||
rateLimit: {
|
||||
max: config.rateLimit.messageMax,
|
||||
timeWindow: config.rateLimit.messageWindowMs,
|
||||
keyGenerator: (req: FastifyRequest) => req.user?.id ?? req.ip,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
for (const which of ['icon', 'banner'] as const) {
|
||||
app.put<{ Params: Params }>(`/api/servers/:serverId/${which}`, limited, async (req) => {
|
||||
const me = uid(req);
|
||||
const serverId = parse(idSchema, req.params.serverId);
|
||||
servers.requireAdmin(me, serverId);
|
||||
const kind = KIND[which];
|
||||
const { file, crop } = await receiveCroppedImage(
|
||||
req,
|
||||
media,
|
||||
mediaLimitMb(kind, settings.getAll().maxUploadMb),
|
||||
);
|
||||
let legacyPath: string | null = null;
|
||||
try {
|
||||
await media.replace(file, kind, crop, (id) => {
|
||||
const r = servers.setImage(me, serverId, which, id);
|
||||
legacyPath = r.legacyPath;
|
||||
return r.previous;
|
||||
});
|
||||
} finally {
|
||||
media.discard(file);
|
||||
}
|
||||
uploads.removeFile(legacyPath);
|
||||
return { server: servers.broadcastUpdate(me, serverId) };
|
||||
});
|
||||
|
||||
app.delete<{ Params: Params }>(`/api/servers/:serverId/${which}`, limited, async (req) => {
|
||||
const me = uid(req);
|
||||
const serverId = parse(idSchema, req.params.serverId);
|
||||
const { previous, legacyPath } = servers.setImage(me, serverId, which, null);
|
||||
media.remove(previous);
|
||||
uploads.removeFile(legacyPath);
|
||||
return { server: servers.broadcastUpdate(me, serverId, !!(previous || legacyPath)) };
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
import {
|
||||
createCategorySchema,
|
||||
createChannelSchema,
|
||||
createServerInviteSchema,
|
||||
createServerSchema,
|
||||
inviteCodeSchema,
|
||||
REORDER_MAX_IDS,
|
||||
reorderChannelsSchema,
|
||||
reorderSchema,
|
||||
transferOwnershipSchema,
|
||||
updateCategorySchema,
|
||||
updateChannelSchema,
|
||||
updateMemberSchema,
|
||||
updateServerSchema,
|
||||
} from '@chat/shared';
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import type { AppServices } from '../app.js';
|
||||
import { currentUser, requireAuth } from '../auth/plugin.js';
|
||||
import type { AppConfig } from '../config.js';
|
||||
import { parse, rejectLongArray } from '../lib/validate.js';
|
||||
|
||||
const TOO_MANY_IDS = `At most ${REORDER_MAX_IDS} items can be reordered at once`;
|
||||
|
||||
/** Union of all path params used below; each route only reads the ones in its URL. */
|
||||
interface Params {
|
||||
serverId: string;
|
||||
userId: string;
|
||||
code: string;
|
||||
categoryId: string;
|
||||
channelId: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Servers, members, bans, invites, categories, channels (story 2). Every handler goes through a
|
||||
* service method that takes the acting user id and enforces permissions (404 invisible, 403 role).
|
||||
*/
|
||||
export async function serverRoutes(
|
||||
app: FastifyInstance,
|
||||
{ services, config }: { services: AppServices; config: AppConfig },
|
||||
) {
|
||||
const { servers, channels, invites } = services;
|
||||
const auth = { preHandler: requireAuth };
|
||||
const uid = (req: Parameters<typeof currentUser>[0]) => currentUser(req).id;
|
||||
|
||||
// ---- servers ----
|
||||
app.get('/api/servers', auth, async (req) => ({ servers: servers.list(uid(req)) }));
|
||||
|
||||
app.post('/api/servers', auth, async (req, reply) => {
|
||||
const input = parse(createServerSchema, req.body);
|
||||
return reply.code(201).send({ server: servers.create(uid(req), input) });
|
||||
});
|
||||
|
||||
app.get<{ Params: Params }>('/api/servers/:serverId', auth, async (req) => ({
|
||||
server: servers.get(uid(req), req.params.serverId),
|
||||
}));
|
||||
|
||||
app.patch<{ Params: Params }>('/api/servers/:serverId', auth, async (req) => ({
|
||||
server: servers.update(uid(req), req.params.serverId, parse(updateServerSchema, req.body)),
|
||||
}));
|
||||
|
||||
app.delete<{ Params: Params }>('/api/servers/:serverId', auth, async (req, reply) => {
|
||||
const emojiMedia = services.emoji.mediaOf(req.params.serverId);
|
||||
const removed = servers.delete(uid(req), req.params.serverId);
|
||||
// M24: the server's emoji rows went with it; their images and reactions go too.
|
||||
for (const m of [...removed.media, ...emojiMedia]) services.media.remove(m);
|
||||
services.emoji.dropOrphanReactions();
|
||||
services.uploads.removeFile(removed.legacyPath);
|
||||
return reply.code(204).send();
|
||||
});
|
||||
|
||||
app.post<{ Params: Params }>('/api/servers/:serverId/transfer', auth, async (req) => {
|
||||
const { userId } = parse(transferOwnershipSchema, req.body);
|
||||
return { server: servers.transferOwnership(uid(req), req.params.serverId, userId) };
|
||||
});
|
||||
|
||||
// ---- members ----
|
||||
app.get<{ Params: Params }>('/api/servers/:serverId/members', auth, async (req) => ({
|
||||
members: servers.listMembers(uid(req), req.params.serverId),
|
||||
}));
|
||||
|
||||
app.patch<{ Params: Params }>('/api/servers/:serverId/members/:userId', auth, async (req) => {
|
||||
const { role } = parse(updateMemberSchema, req.body);
|
||||
return { member: servers.setRole(uid(req), req.params.serverId, req.params.userId, role) };
|
||||
});
|
||||
|
||||
/** Kick, or leave when :userId is "@me". */
|
||||
app.delete<{ Params: Params }>(
|
||||
'/api/servers/:serverId/members/:userId',
|
||||
auth,
|
||||
async (req, reply) => {
|
||||
const me = uid(req);
|
||||
const target = req.params.userId === '@me' ? me : req.params.userId;
|
||||
if (target === me) servers.leave(me, req.params.serverId);
|
||||
else servers.kick(me, req.params.serverId, target);
|
||||
return reply.code(204).send();
|
||||
},
|
||||
);
|
||||
|
||||
// ---- bans ----
|
||||
app.get<{ Params: Params }>('/api/servers/:serverId/bans', auth, async (req) => ({
|
||||
bans: servers.listBans(uid(req), req.params.serverId),
|
||||
}));
|
||||
|
||||
app.put<{ Params: Params }>('/api/servers/:serverId/bans/:userId', auth, async (req, reply) => {
|
||||
servers.ban(uid(req), req.params.serverId, req.params.userId);
|
||||
return reply.code(204).send();
|
||||
});
|
||||
|
||||
app.delete<{ Params: Params }>(
|
||||
'/api/servers/:serverId/bans/:userId',
|
||||
auth,
|
||||
async (req, reply) => {
|
||||
servers.unban(uid(req), req.params.serverId, req.params.userId);
|
||||
return reply.code(204).send();
|
||||
},
|
||||
);
|
||||
|
||||
// ---- invites ----
|
||||
app.get<{ Params: Params }>('/api/servers/:serverId/invites', auth, async (req) => ({
|
||||
invites: invites.list(uid(req), req.params.serverId),
|
||||
}));
|
||||
|
||||
app.post<{ Params: Params }>('/api/servers/:serverId/invites', auth, async (req, reply) => {
|
||||
const input = parse(createServerInviteSchema, req.body);
|
||||
return reply.code(201).send({ invite: invites.create(uid(req), req.params.serverId, input) });
|
||||
});
|
||||
|
||||
// Public preview: rate limited like auth because it's unauthenticated and takes a guessable input.
|
||||
app.get<{ Params: Params }>(
|
||||
'/api/invites/:code',
|
||||
{
|
||||
config: {
|
||||
rateLimit: { max: config.rateLimit.authMax * 3, timeWindow: config.rateLimit.authWindowMs },
|
||||
},
|
||||
},
|
||||
async (req) => ({
|
||||
invite: invites.preview(parse(inviteCodeSchema, req.params.code), !!req.user),
|
||||
}),
|
||||
);
|
||||
|
||||
app.post<{ Params: Params }>(
|
||||
'/api/invites/:code/join',
|
||||
{
|
||||
...auth,
|
||||
config: {
|
||||
rateLimit: { max: config.rateLimit.authMax * 3, timeWindow: config.rateLimit.authWindowMs },
|
||||
},
|
||||
},
|
||||
async (req, reply) => {
|
||||
const result = invites.join(uid(req), parse(inviteCodeSchema, req.params.code));
|
||||
return reply.code(result.joined ? 201 : 200).send(result);
|
||||
},
|
||||
);
|
||||
|
||||
app.delete<{ Params: Params }>('/api/invites/:code', auth, async (req, reply) => {
|
||||
invites.revoke(uid(req), req.params.code);
|
||||
return reply.code(204).send();
|
||||
});
|
||||
|
||||
// ---- categories ----
|
||||
app.post<{ Params: Params }>('/api/servers/:serverId/categories', auth, async (req, reply) => {
|
||||
const { name } = parse(createCategorySchema, req.body);
|
||||
return reply
|
||||
.code(201)
|
||||
.send({ category: channels.createCategory(uid(req), req.params.serverId, name) });
|
||||
});
|
||||
|
||||
app.put<{ Params: Params }>('/api/servers/:serverId/categories/order', auth, async (req) => {
|
||||
rejectLongArray(req.body, 'ids', REORDER_MAX_IDS, TOO_MANY_IDS);
|
||||
const { ids } = parse(reorderSchema, req.body);
|
||||
return { positions: channels.reorderCategories(uid(req), req.params.serverId, ids) };
|
||||
});
|
||||
|
||||
app.patch<{ Params: Params }>('/api/categories/:categoryId', auth, async (req) => {
|
||||
const { name } = parse(updateCategorySchema, req.body);
|
||||
return { category: channels.renameCategory(uid(req), req.params.categoryId, name) };
|
||||
});
|
||||
|
||||
app.delete<{ Params: Params }>('/api/categories/:categoryId', auth, async (req, reply) => {
|
||||
channels.deleteCategory(uid(req), req.params.categoryId);
|
||||
return reply.code(204).send();
|
||||
});
|
||||
|
||||
// ---- channels ----
|
||||
app.post<{ Params: Params }>('/api/servers/:serverId/channels', auth, async (req, reply) => {
|
||||
const input = parse(createChannelSchema, req.body);
|
||||
return reply
|
||||
.code(201)
|
||||
.send({ channel: channels.createChannel(uid(req), req.params.serverId, input) });
|
||||
});
|
||||
|
||||
app.put<{ Params: Params }>('/api/servers/:serverId/channels/order', auth, async (req) => {
|
||||
rejectLongArray(req.body, 'ids', REORDER_MAX_IDS, TOO_MANY_IDS);
|
||||
const { categoryId, ids } = parse(reorderChannelsSchema, req.body);
|
||||
return {
|
||||
positions: channels.reorderChannels(uid(req), req.params.serverId, categoryId, ids),
|
||||
};
|
||||
});
|
||||
|
||||
app.get<{ Params: Params }>('/api/channels/:channelId', auth, async (req) => ({
|
||||
channel: channels.getChannel(uid(req), req.params.channelId),
|
||||
}));
|
||||
|
||||
app.patch<{ Params: Params }>('/api/channels/:channelId', auth, async (req) => ({
|
||||
channel: channels.updateChannel(
|
||||
uid(req),
|
||||
req.params.channelId,
|
||||
parse(updateChannelSchema, req.body),
|
||||
),
|
||||
}));
|
||||
|
||||
app.delete<{ Params: Params }>('/api/channels/:channelId', auth, async (req, reply) => {
|
||||
channels.deleteChannel(uid(req), req.params.channelId);
|
||||
return reply.code(204).send();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { createThreadSchema, idSchema } from '@chat/shared';
|
||||
import type { FastifyInstance, FastifyRequest } from 'fastify';
|
||||
import type { AppServices } from '../app.js';
|
||||
import { currentUser, requireAuth } from '../auth/plugin.js';
|
||||
import { parse } from '../lib/validate.js';
|
||||
|
||||
interface Params {
|
||||
messageId: string;
|
||||
channelId: string;
|
||||
threadId: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Threads (M25, DESIGN-0.5 section 4). Messages, pins and read inside a thread are the shared
|
||||
* conversation routes under /api/threads/:threadId (routes/messages.ts). The 10-a-minute start
|
||||
* limit is in ThreadService.
|
||||
*/
|
||||
export async function threadRoutes(app: FastifyInstance, { services }: { services: AppServices }) {
|
||||
const { threads } = services;
|
||||
const auth = { preHandler: requireAuth };
|
||||
const uid = (req: FastifyRequest) => currentUser(req).id;
|
||||
const id = (v: string) => parse(idSchema, v);
|
||||
|
||||
app.post<{ Params: Params }>('/api/messages/:messageId/thread', auth, async (req, reply) => {
|
||||
const { name } = parse(createThreadSchema, req.body ?? {});
|
||||
const thread = threads.start(uid(req), id(req.params.messageId), name);
|
||||
return reply.code(201).send({ thread });
|
||||
});
|
||||
|
||||
app.get<{ Params: Params }>('/api/channels/:channelId/threads', auth, async (req) => ({
|
||||
threads: threads.list(uid(req), id(req.params.channelId)),
|
||||
}));
|
||||
|
||||
app.get<{ Params: Params }>('/api/threads/:threadId', auth, async (req) =>
|
||||
threads.get(uid(req), id(req.params.threadId)),
|
||||
);
|
||||
|
||||
app.put<{ Params: Params }>('/api/threads/:threadId/follow', auth, async (req) => ({
|
||||
thread: threads.follow(uid(req), id(req.params.threadId), true),
|
||||
}));
|
||||
|
||||
app.delete<{ Params: Params }>('/api/threads/:threadId/follow', auth, async (req) => ({
|
||||
thread: threads.follow(uid(req), id(req.params.threadId), false),
|
||||
}));
|
||||
|
||||
app.delete<{ Params: Params }>('/api/threads/:threadId', auth, async (req, reply) => {
|
||||
threads.delete(uid(req), id(req.params.threadId));
|
||||
return reply.code(204).send();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import { idSchema, voiceSelfStateSchema } from '@chat/shared';
|
||||
import type { FastifyInstance, FastifyRequest } from 'fastify';
|
||||
import { WebhookReceiver } from 'livekit-server-sdk';
|
||||
import type { AppServices } from '../app.js';
|
||||
import { currentUser, requireAuth } from '../auth/plugin.js';
|
||||
import type { AppConfig } from '../config.js';
|
||||
import { HttpError, notFound } from '../lib/errors.js';
|
||||
import { parse } from '../lib/validate.js';
|
||||
|
||||
interface Params {
|
||||
channelId: string;
|
||||
serverId: string;
|
||||
}
|
||||
|
||||
/** Voice (story 6/7): LiveKit tokens, self state, server snapshot, and the LiveKit webhook. */
|
||||
export async function voiceRoutes(
|
||||
app: FastifyInstance,
|
||||
{ services, config }: { services: AppServices; config: AppConfig },
|
||||
) {
|
||||
const { voice } = services;
|
||||
const uid = (req: FastifyRequest) => currentUser(req).id;
|
||||
const id = (v: string) => parse(idSchema, v);
|
||||
const limited = (factor: number) => ({
|
||||
preHandler: requireAuth,
|
||||
config: {
|
||||
rateLimit: {
|
||||
max: config.rateLimit.messageMax * factor,
|
||||
timeWindow: config.rateLimit.messageWindowMs,
|
||||
keyGenerator: (req: FastifyRequest) => req.user?.id ?? req.ip,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* A room-scoped LiveKit token (10 min); camera only when VIDEO_ENABLED is on. 404 if the channel isn't visible to you (not a member,
|
||||
* banned, kicked, unknown), 400 for text channels, 503 when LiveKit isn't configured.
|
||||
*/
|
||||
app.post<{ Params: Params }>('/api/voice/:channelId/token', limited(1), async (req) =>
|
||||
voice.token(uid(req), id(req.params.channelId)),
|
||||
);
|
||||
|
||||
/** Mute/deafen as the client sees itself; only while connected to that channel. */
|
||||
app.post<{ Params: Params }>('/api/voice/:channelId/state', limited(3), async (req) => ({
|
||||
channel: voice.setSelf(
|
||||
uid(req),
|
||||
id(req.params.channelId),
|
||||
parse(voiceSelfStateSchema, req.body),
|
||||
),
|
||||
}));
|
||||
|
||||
app.get<{ Params: Params }>(
|
||||
'/api/servers/:serverId/voice',
|
||||
{ preHandler: requireAuth },
|
||||
async (req) => ({ channels: voice.listForServer(uid(req), id(req.params.serverId)) }),
|
||||
);
|
||||
|
||||
// LiveKit -> app. Needs the exact raw body to check the signature, so this plugin scope parses
|
||||
// bodies as strings. Anything not signed with our API key/secret gets 401.
|
||||
await app.register(async (hook) => {
|
||||
const receiver = voice.enabled
|
||||
? new WebhookReceiver(config.livekit.apiKey, config.livekit.apiSecret)
|
||||
: null;
|
||||
hook.removeAllContentTypeParsers();
|
||||
hook.addContentTypeParser('*', { parseAs: 'string' }, (_req, body, done) => done(null, body));
|
||||
hook.post('/api/livekit/webhook', async (req, reply) => {
|
||||
if (!receiver) throw notFound();
|
||||
const body = typeof req.body === 'string' ? req.body : '';
|
||||
let event;
|
||||
try {
|
||||
event = await receiver.receive(body, req.headers.authorization);
|
||||
} catch {
|
||||
throw new HttpError(401, 'bad_signature', 'Webhook signature is missing or invalid');
|
||||
}
|
||||
voice.handleWebhook(event);
|
||||
services.calls.handleWebhook(event);
|
||||
return reply.code(200).send({ ok: true });
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
/**
|
||||
* Rebuild the message search index (D26) from the messages table:
|
||||
* node apps/server/dist/scripts/rebuild-search.js
|
||||
* Uses the same database as the server (DB_PATH, else DATA_DIR/chat.db), which must already
|
||||
* exist (QA-122). Safe while the server runs (one IMMEDIATE transaction that waits for other
|
||||
* writers, QA-123); searches see the old index until it commits. README: "Search index".
|
||||
*/
|
||||
import { resolveDbPath } from '../config.js';
|
||||
import { rebuildSearchCommand } from '../db/rebuild-command.js';
|
||||
|
||||
process.exitCode = rebuildSearchCommand(resolveDbPath());
|
||||
@@ -0,0 +1,58 @@
|
||||
import type { DB } from '../db/index.js';
|
||||
import { Access } from '../auth/access.js';
|
||||
import type { RealtimeHub } from '../realtime/hub.js';
|
||||
import type { Lifecycle } from './lifecycle.js';
|
||||
import { serverOverrides } from './role-dto.js';
|
||||
import { densePositions, toPositionList, viewerChannelDto } from './positions.js';
|
||||
|
||||
/**
|
||||
* D46 (DESIGN-0.6 §3.3): keep every socket's `chan:` rooms equal to what its user can VIEW.
|
||||
*
|
||||
* `apply(serverId, users)` recomputes visibility for those users (or every member, `'all'`) and,
|
||||
* for each one, in the same tick:
|
||||
* 1. takes their sockets out of the rooms of channels they lost and into the ones they gained;
|
||||
* 2. sends `channel:access { serverId, added, removed }` to their user room;
|
||||
* 3. evicts them from any voice channel of that server they can no longer view.
|
||||
*
|
||||
* Callers run it synchronously right after their write commits and before the HTTP response or
|
||||
* any later emit. With the in-memory adapter socketsLeave is synchronous, so once the response
|
||||
* returns, no event for a lost channel can reach the user (D46, D59).
|
||||
*/
|
||||
export class AccessSync {
|
||||
constructor(
|
||||
private readonly db: DB,
|
||||
private readonly hub: () => RealtimeHub,
|
||||
private readonly lifecycle: Lifecycle = {},
|
||||
) {}
|
||||
|
||||
apply(serverId: string, users: readonly string[] | 'all'): void {
|
||||
const access = Access.for(this.db);
|
||||
const data = access.load(serverId);
|
||||
const inServer = new Map(data.channels.map((c) => [c.id, c]));
|
||||
const targets = users === 'all' ? [...data.members.keys()] : [...new Set(users)];
|
||||
const hub = this.hub();
|
||||
const overridesOf = serverOverrides(this.db, serverId);
|
||||
for (const userId of targets) {
|
||||
const visible = access.visibleIn(data, userId); // empty for a non-member
|
||||
const current = [...hub.channelRoomsOf(userId)].filter((id) => inServer.has(id));
|
||||
const lost = current.filter((id) => !visible.has(id));
|
||||
const gained = [...visible].filter((id) => !current.includes(id));
|
||||
hub.leaveChannels(userId, lost);
|
||||
hub.joinChannels(userId, gained);
|
||||
if (lost.length || gained.length) {
|
||||
// D63, D63a: dense numbers, and the full list, so the rest of their list can't drift.
|
||||
const dense = densePositions(data.channels, visible);
|
||||
hub.toUser(userId, 'channel:access', {
|
||||
serverId,
|
||||
added: gained.map((id) =>
|
||||
viewerChannelDto(inServer.get(id)!, dense, overridesOf.get(id) ?? []),
|
||||
),
|
||||
removed: lost,
|
||||
positions: toPositionList(dense),
|
||||
});
|
||||
}
|
||||
// Voice state lives in VoiceService, not in socket rooms: check it whatever the sockets say.
|
||||
this.lifecycle.voiceAccessChanged?.(serverId, userId, visible);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
import { hash, verify, type Algorithm } from '@node-rs/argon2';
|
||||
import { createHash, randomBytes } from 'node:crypto';
|
||||
import type { LoginInput, RegisterInput } from '@chat/shared';
|
||||
import type { DB } from '../db/index.js';
|
||||
import { HttpError, conflict, forbidden, invalidCredentials } from '../lib/errors.js';
|
||||
import { newId, nowIso } from '../lib/ids.js';
|
||||
import { SettingsService } from './settings.js';
|
||||
import type { UserRow } from './users.js';
|
||||
|
||||
/** OWASP-recommended Argon2id parameters (19 MiB, t=2, p=1). */
|
||||
const ARGON2_OPTIONS = {
|
||||
algorithm: 2 as Algorithm, // Algorithm.Argon2id (const enum, can't be imported under verbatimModuleSyntax)
|
||||
memoryCost: 19456,
|
||||
timeCost: 2,
|
||||
parallelism: 1,
|
||||
} as const;
|
||||
|
||||
export function hashPassword(password: string): Promise<string> {
|
||||
return hash(password, ARGON2_OPTIONS);
|
||||
}
|
||||
|
||||
export async function verifyPassword(passwordHash: string, password: string): Promise<boolean> {
|
||||
try {
|
||||
return await verify(passwordHash, password);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Session tokens are random; the DB stores only their SHA-256 so a DB leak can't hijack sessions. */
|
||||
export function hashToken(token: string): string {
|
||||
return createHash('sha256').update(token).digest('hex');
|
||||
}
|
||||
|
||||
export interface InviteRow {
|
||||
code: string;
|
||||
server_id: string | null;
|
||||
created_by: string;
|
||||
max_uses: number | null;
|
||||
uses: number;
|
||||
expires_at: string | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface SessionInfo {
|
||||
token: string;
|
||||
expiresAt: Date;
|
||||
}
|
||||
|
||||
export class AuthService {
|
||||
private readonly settings: SettingsService;
|
||||
private dummyHash: Promise<string> | null = null;
|
||||
|
||||
constructor(
|
||||
private readonly db: DB,
|
||||
private readonly sessionTtlDays = 30,
|
||||
) {
|
||||
this.settings = new SettingsService(db);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an account. The "is this the first user?" check, the registration/invite check and the
|
||||
* insert run in one BEGIN IMMEDIATE transaction, so concurrent signups (even from separate
|
||||
* processes sharing the DB file) can never produce two instance admins.
|
||||
*/
|
||||
async register(input: RegisterInput): Promise<UserRow> {
|
||||
// Hash outside the transaction: it is slow and async, and the write lock must stay short.
|
||||
const passwordHash = await hashPassword(input.password);
|
||||
const id = newId();
|
||||
const createdAt = nowIso();
|
||||
|
||||
const tx = this.db.transaction((): UserRow => {
|
||||
const userCount = (this.db.prepare('SELECT COUNT(*) AS n FROM users').get() as { n: number })
|
||||
.n;
|
||||
const isFirstUser = userCount === 0;
|
||||
let invite: InviteRow | null = null;
|
||||
|
||||
// The very first account (the instance admin) can always be created.
|
||||
if (!isFirstUser && !this.settings.isRegistrationOpen()) {
|
||||
if (!input.inviteCode) {
|
||||
throw forbidden('Registration is invite-only. Ask an admin for an invite code.');
|
||||
}
|
||||
invite = this.consumeInvite(input.inviteCode);
|
||||
} else if (input.inviteCode) {
|
||||
// Open registration: an invite is optional, but if given it must be valid (and joins its server).
|
||||
invite = this.consumeInvite(input.inviteCode);
|
||||
}
|
||||
|
||||
const exists = this.db
|
||||
.prepare('SELECT 1 FROM users WHERE username = ? COLLATE NOCASE')
|
||||
.get(input.username);
|
||||
if (exists) throw conflict('That username is taken');
|
||||
|
||||
this.db
|
||||
.prepare(
|
||||
`INSERT INTO users (id, username, display_name, password_hash, created_at, is_instance_admin)
|
||||
VALUES (?, ?, ?, ?, ?, ?)`,
|
||||
)
|
||||
.run(
|
||||
id,
|
||||
input.username,
|
||||
input.displayName ?? input.username,
|
||||
passwordHash,
|
||||
createdAt,
|
||||
isFirstUser ? 1 : 0,
|
||||
);
|
||||
// A server invite link also makes the new account a member of that server.
|
||||
if (invite?.server_id) {
|
||||
this.db
|
||||
.prepare(
|
||||
"INSERT INTO members (server_id, user_id, role, joined_at, banned) VALUES (?, ?, 'member', ?, 0)",
|
||||
)
|
||||
.run(invite.server_id, id, createdAt);
|
||||
}
|
||||
return this.db.prepare('SELECT * FROM users WHERE id = ?').get(id) as UserRow;
|
||||
});
|
||||
return tx.immediate();
|
||||
}
|
||||
|
||||
/** Validate and use up one invite. Must be called inside a write transaction. */
|
||||
private consumeInvite(code: string): InviteRow {
|
||||
const invite = this.db.prepare('SELECT * FROM invites WHERE code = ?').get(code) as
|
||||
InviteRow | undefined;
|
||||
if (!invite) throw new HttpError(403, 'invalid_invite', 'That invite code is not valid');
|
||||
if (invite.expires_at && Date.parse(invite.expires_at) <= Date.now()) {
|
||||
throw new HttpError(403, 'invalid_invite', 'That invite code has expired');
|
||||
}
|
||||
if (invite.max_uses !== null && invite.uses >= invite.max_uses) {
|
||||
throw new HttpError(403, 'invalid_invite', 'That invite code has been used up');
|
||||
}
|
||||
this.db.prepare('UPDATE invites SET uses = uses + 1 WHERE code = ?').run(code);
|
||||
return invite;
|
||||
}
|
||||
|
||||
/** Instance-level invite (server_id NULL) for invite-only registration. */
|
||||
createInstanceInvite(
|
||||
createdBy: string,
|
||||
opts: { maxUses?: number | null; expiresInHours?: number | null } = {},
|
||||
): InviteRow {
|
||||
const code = randomBytes(6).toString('base64url');
|
||||
const expiresAt = opts.expiresInHours
|
||||
? new Date(Date.now() + opts.expiresInHours * 3_600_000).toISOString()
|
||||
: null;
|
||||
this.db
|
||||
.prepare(
|
||||
`INSERT INTO invites (code, server_id, created_by, max_uses, uses, expires_at, created_at)
|
||||
VALUES (?, NULL, ?, ?, 0, ?, ?)`,
|
||||
)
|
||||
.run(code, createdBy, opts.maxUses ?? null, expiresAt, nowIso());
|
||||
return this.db.prepare('SELECT * FROM invites WHERE code = ?').get(code) as InviteRow;
|
||||
}
|
||||
|
||||
/** Check credentials. Unknown users still cost one Argon2 verify so timing doesn't leak usernames. */
|
||||
async login(input: LoginInput): Promise<UserRow> {
|
||||
const user = this.db
|
||||
.prepare('SELECT * FROM users WHERE username = ? COLLATE NOCASE')
|
||||
.get(input.username) as UserRow | undefined;
|
||||
if (!user) {
|
||||
this.dummyHash ??= hashPassword(randomBytes(16).toString('hex'));
|
||||
await verifyPassword(await this.dummyHash, input.password);
|
||||
throw invalidCredentials();
|
||||
}
|
||||
const ok = await verifyPassword(user.password_hash, input.password);
|
||||
if (!ok) throw invalidCredentials();
|
||||
return user;
|
||||
}
|
||||
|
||||
createSession(userId: string, userAgent?: string): SessionInfo {
|
||||
const token = randomBytes(32).toString('base64url');
|
||||
const expiresAt = new Date(Date.now() + this.sessionTtlDays * 86_400_000);
|
||||
this.db
|
||||
.prepare(
|
||||
'INSERT INTO sessions (id, user_id, expires_at, user_agent, created_at) VALUES (?, ?, ?, ?, ?)',
|
||||
)
|
||||
.run(
|
||||
hashToken(token),
|
||||
userId,
|
||||
expiresAt.toISOString(),
|
||||
userAgent?.slice(0, 256) ?? null,
|
||||
nowIso(),
|
||||
);
|
||||
return { token, expiresAt };
|
||||
}
|
||||
|
||||
/** Resolve a cookie token to its user, or null if missing/expired. Expired rows are removed. */
|
||||
getSessionUser(token: string | undefined): UserRow | null {
|
||||
if (!token) return null;
|
||||
const id = hashToken(token);
|
||||
const row = this.db
|
||||
.prepare(
|
||||
`SELECT u.*, s.expires_at AS session_expires_at FROM sessions s
|
||||
JOIN users u ON u.id = s.user_id WHERE s.id = ?`,
|
||||
)
|
||||
.get(id) as (UserRow & { session_expires_at: string }) | undefined;
|
||||
if (!row) return null;
|
||||
if (Date.parse(row.session_expires_at) <= Date.now()) {
|
||||
this.db.prepare('DELETE FROM sessions WHERE id = ?').run(id);
|
||||
return null;
|
||||
}
|
||||
const { session_expires_at: _expires, ...user } = row;
|
||||
return user;
|
||||
}
|
||||
|
||||
deleteSession(token: string | undefined): void {
|
||||
if (!token) return;
|
||||
this.db.prepare('DELETE FROM sessions WHERE id = ?').run(hashToken(token));
|
||||
}
|
||||
|
||||
purgeExpiredSessions(): number {
|
||||
return this.db.prepare('DELETE FROM sessions WHERE expires_at <= ?').run(nowIso()).changes;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import { MAX_BLOCKS, type UserSummaryDto } from '@chat/shared';
|
||||
import { Blocks } from '../auth/blocks.js';
|
||||
import type { DB } from '../db/index.js';
|
||||
import { badRequest, HttpError, notFound } from '../lib/errors.js';
|
||||
import { nowIso } from '../lib/ids.js';
|
||||
import type { RealtimeHub } from '../realtime/hub.js';
|
||||
import { canSeeUser } from './presence.js';
|
||||
|
||||
/**
|
||||
* M18 blocking (DESIGN-0.4 section 4): the blocker's list and the block/unblock actions. What a
|
||||
* block changes is enforced where it applies, through auth/blocks.ts. Only the blocker hears
|
||||
* about it (`blocks:update` to their own tabs); nothing is ever sent to the blocked person.
|
||||
*/
|
||||
export class BlockService {
|
||||
/** Set by the app: a block ends a live 1:1 call between the two (CallService.blocked). */
|
||||
onBlocked: ((blockerId: string, blockedId: string) => void) | null = null;
|
||||
/** Set by the app: a block or unblock happened between the two (presence custom text, D50). */
|
||||
onChanged: ((a: string, b: string) => void) | null = null;
|
||||
|
||||
constructor(
|
||||
private readonly db: DB,
|
||||
private readonly hub: () => RealtimeHub,
|
||||
) {}
|
||||
|
||||
list(userId: string): UserSummaryDto[] {
|
||||
return (
|
||||
this.db
|
||||
.prepare(
|
||||
`SELECT u.id, u.username, u.display_name, u.avatar_media FROM blocks b
|
||||
JOIN users u ON u.id = b.blocked_id WHERE b.blocker_id = ?
|
||||
ORDER BY u.display_name COLLATE NOCASE, u.id`,
|
||||
)
|
||||
.all(userId) as {
|
||||
id: string;
|
||||
username: string;
|
||||
display_name: string;
|
||||
avatar_media: string | null;
|
||||
}[]
|
||||
).map((u) => ({
|
||||
id: u.id,
|
||||
username: u.username,
|
||||
displayName: u.display_name,
|
||||
avatar: u.avatar_media,
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Block (idempotent). You can block anyone you can see (a shared server or conversation, the
|
||||
* same rule as profiles); anyone else is the profile's 404, so ids can't be probed.
|
||||
*/
|
||||
block(userId: string, otherId: string): { created: boolean } {
|
||||
if (otherId === userId) throw badRequest("You can't block yourself");
|
||||
if (Blocks.for(this.db).blockedBy(userId).has(otherId)) return { created: false };
|
||||
if (!canSeeUser(this.db, userId, otherId)) throw notFound('User not found');
|
||||
const created = this.db
|
||||
.transaction(() => {
|
||||
const { n } = this.db
|
||||
.prepare('SELECT COUNT(*) AS n FROM blocks WHERE blocker_id = ?')
|
||||
.get(userId) as { n: number };
|
||||
if (n >= MAX_BLOCKS) {
|
||||
throw new HttpError(409, 'too_many', `You can block at most ${MAX_BLOCKS} people`);
|
||||
}
|
||||
return (
|
||||
this.db
|
||||
.prepare(
|
||||
'INSERT OR IGNORE INTO blocks (blocker_id, blocked_id, created_at) VALUES (?, ?, ?)',
|
||||
)
|
||||
.run(userId, otherId, nowIso()).changes > 0
|
||||
);
|
||||
})
|
||||
.immediate();
|
||||
Blocks.for(this.db).invalidate(userId);
|
||||
if (created) {
|
||||
this.hub().toUser(userId, 'blocks:update', { userId: otherId, blocked: true });
|
||||
this.onBlocked?.(userId, otherId);
|
||||
this.onChanged?.(userId, otherId);
|
||||
}
|
||||
return { created };
|
||||
}
|
||||
|
||||
/** Unblock (idempotent): 204 whether or not they were blocked, if you can see them. */
|
||||
unblock(userId: string, otherId: string): void {
|
||||
if (otherId === userId) throw badRequest("You can't block yourself");
|
||||
const gone =
|
||||
this.db
|
||||
.prepare('DELETE FROM blocks WHERE blocker_id = ? AND blocked_id = ?')
|
||||
.run(userId, otherId).changes > 0;
|
||||
Blocks.for(this.db).invalidate(userId);
|
||||
if (gone) {
|
||||
this.hub().toUser(userId, 'blocks:update', { userId: otherId, blocked: false });
|
||||
this.onChanged?.(userId, otherId);
|
||||
return;
|
||||
}
|
||||
if (!canSeeUser(this.db, userId, otherId)) throw notFound('User not found');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,934 @@
|
||||
import type { CallDto, CallStopReason, VoiceParticipantDto, VoiceTokenDto } from '@chat/shared';
|
||||
import { TrackSource } from 'livekit-server-sdk';
|
||||
import {
|
||||
dmMemberIds,
|
||||
isDmMember,
|
||||
requireDmAccess,
|
||||
requireDmPost,
|
||||
cantCall,
|
||||
type DmChannelRow,
|
||||
} from '../auth/permissions.js';
|
||||
import { Blocks } from '../auth/blocks.js';
|
||||
import type { DB } from '../db/index.js';
|
||||
import { HttpError, notFound } from '../lib/errors.js';
|
||||
import { newId, nowIso } from '../lib/ids.js';
|
||||
import { RateWindow } from '../lib/rate-window.js';
|
||||
import type { RealtimeHub } from '../realtime/hub.js';
|
||||
import {
|
||||
audit,
|
||||
fireAndForget,
|
||||
mintToken,
|
||||
publishSources,
|
||||
quiet,
|
||||
type LivekitApi,
|
||||
type LivekitGrantConfig,
|
||||
type LkParticipant,
|
||||
type LkWebhookEvent,
|
||||
type Logger,
|
||||
} from './livekit.js';
|
||||
import type { MessageService, StoredSystemInfo } from './messages.js';
|
||||
|
||||
export const CALL_ROOM_PREFIX = 'call_';
|
||||
/**
|
||||
* Every call gets its own LiveKit room, `call_<dmId>_<callId>` (QA-58). LiveKit removes people by
|
||||
* identity only, and a removal can be served up to about a second after it was asked for, by
|
||||
* whichever session then has that identity in the room. With one room per DM (0.3.0), a kick of
|
||||
* the previous call's session could land on the caller's next call. In a room of its own, a kick
|
||||
* can only reach the call it was made for.
|
||||
*/
|
||||
export const callRoomFor = (dmId: string, callId: string) => `${CALL_ROOM_PREFIX}${dmId}_${callId}`;
|
||||
/** `call_<dmId>_<callId>`, or the 0.3.0 per-DM name `call_<dmId>` (callId null). */
|
||||
export function parseCallRoom(room: string): { dmId: string; callId: string | null } | null {
|
||||
if (!room.startsWith(CALL_ROOM_PREFIX)) return null;
|
||||
const rest = room.slice(CALL_ROOM_PREFIX.length);
|
||||
const i = rest.indexOf('_');
|
||||
if (i < 0) return rest ? { dmId: rest, callId: null } : null;
|
||||
const dmId = rest.slice(0, i);
|
||||
const callId = rest.slice(i + 1);
|
||||
return dmId && callId ? { dmId, callId } : null;
|
||||
}
|
||||
|
||||
/** Starting calls: at most this many new calls per user per window (TESTPLAN: repeated calls). */
|
||||
/** Longest a call push may ring (the worker's `exp`), matching its 30 s TTL. */
|
||||
const CALL_PUSH_TTL_MS = 30_000;
|
||||
export const CALL_STARTS_PER_WINDOW = 10;
|
||||
export const CALL_STARTS_WINDOW_MS = 10 * 60_000;
|
||||
|
||||
export interface CallRow {
|
||||
id: string;
|
||||
dm_channel_id: string;
|
||||
started_by: string;
|
||||
started_at: string;
|
||||
ended_at: string | null;
|
||||
answered: 0 | 1;
|
||||
}
|
||||
|
||||
const isUniqueViolation = (e: unknown) =>
|
||||
(e as { code?: string }).code === 'SQLITE_CONSTRAINT_UNIQUE' ||
|
||||
/UNIQUE constraint failed: calls\.dm_channel_id/.test(String((e as Error).message));
|
||||
|
||||
/**
|
||||
* The database half of "start a call" (DESIGN-0.2 section 4): returns the DM's active call, or
|
||||
* creates one. The partial unique index `idx_calls_one_active` is what guarantees one active call
|
||||
* per DM: if two connections race, the loser's INSERT fails on it and it returns the winner's row.
|
||||
* Exported for the multi-connection concurrency test.
|
||||
*/
|
||||
export function claimCall(
|
||||
db: DB,
|
||||
dmId: string,
|
||||
userId: string,
|
||||
): { row: CallRow; created: boolean } {
|
||||
const active = db.prepare('SELECT * FROM calls WHERE dm_channel_id = ? AND ended_at IS NULL');
|
||||
const existing = active.get(dmId) as CallRow | undefined;
|
||||
if (existing) return { row: existing, created: false };
|
||||
const id = newId();
|
||||
try {
|
||||
db.prepare(
|
||||
'INSERT INTO calls (id, dm_channel_id, started_by, started_at, answered) VALUES (?, ?, ?, ?, 0)',
|
||||
).run(id, dmId, userId, nowIso());
|
||||
} catch (e) {
|
||||
if (!isUniqueViolation(e)) throw e;
|
||||
return { row: active.get(dmId) as CallRow, created: false };
|
||||
}
|
||||
return { row: db.prepare('SELECT * FROM calls WHERE id = ?').get(id) as CallRow, created: true };
|
||||
}
|
||||
|
||||
interface Person {
|
||||
sid: string;
|
||||
muted: boolean;
|
||||
deafened: boolean;
|
||||
sharing: boolean;
|
||||
camera: boolean;
|
||||
joinedAt: string;
|
||||
}
|
||||
|
||||
/** In-memory state of one active call: who's connected (from LiveKit) and who's being rung. */
|
||||
interface Live {
|
||||
row: CallRow;
|
||||
people: Map<string, Person>;
|
||||
/**
|
||||
* Everyone invited who hasn't joined, declined or timed out: the `ringing` list every member
|
||||
* sees. Never filtered by blocks (QA-70, D18), so it looks the same with or without one.
|
||||
*/
|
||||
ringing: Set<string>;
|
||||
/**
|
||||
* Members on the list who are not actually rung (no `call:ring`, no push) because of a block
|
||||
* either way with the caller. They stay listed and drop off at the ring timeout exactly like
|
||||
* someone who didn't answer (QA-70).
|
||||
*/
|
||||
silent: Set<string>;
|
||||
timer: ReturnType<typeof setTimeout> | null;
|
||||
/** Users who were sent a call push: they get the matching call-end. */
|
||||
pushed: Set<string>;
|
||||
/** Someone has been connected at some point: the room going empty now ends the call. */
|
||||
hadPeople: boolean;
|
||||
/**
|
||||
* LiveKit's id for this call's room session, from the first `room_started` or
|
||||
* `participant_joined`. Rooms are per call since 0.3.1, so this is a second line of defence
|
||||
* against a late `room_finished` of an earlier session (QA-54).
|
||||
*/
|
||||
roomSid: string | null;
|
||||
}
|
||||
|
||||
const callNotFound = () => notFound('Call not found');
|
||||
const tooManyCalls = (retryAfterSec: number) =>
|
||||
new HttpError(
|
||||
429,
|
||||
'too_many_calls',
|
||||
`You can start at most ${CALL_STARTS_PER_WINDOW} calls every ${CALL_STARTS_WINDOW_MS / 60_000} minutes`,
|
||||
undefined,
|
||||
{ 'retry-after': String(retryAfterSec) },
|
||||
);
|
||||
|
||||
/**
|
||||
* DM and group calls (PLAN-0.2 story 15, DESIGN-0.2 section 4). Media goes through LiveKit, one
|
||||
* room per call (`call_<dmId>_<callId>`, since 0.3.1); this service owns the ringing state machine, the calls table, the
|
||||
* call system messages, and dropping people who lose access.
|
||||
*
|
||||
* Ringing only reaches open tabs: `call:ring` goes to every socket in each callee's user room.
|
||||
* A server-side timer stops it after `ringMs`; if nobody but the caller ever picked up, the call
|
||||
* ends as missed.
|
||||
*/
|
||||
/** What the call service needs from web push (implemented by PushService). */
|
||||
export interface CallPushSink {
|
||||
notifyCall(call: {
|
||||
callId: string;
|
||||
dmId: string;
|
||||
fromUserId: string;
|
||||
userIds: string[];
|
||||
expMs: number;
|
||||
stillRinging: (userId: string) => boolean;
|
||||
}): string[];
|
||||
notifyCallEnd(end: {
|
||||
callId: string;
|
||||
dmId: string;
|
||||
fromUserId: string;
|
||||
userId: string;
|
||||
reason: 'answered' | 'declined' | 'ended' | 'missed';
|
||||
}): void;
|
||||
}
|
||||
|
||||
export class CallService {
|
||||
private readonly live = new Map<string, Live>();
|
||||
/** QA-101: null when RATE_LIMIT=false, like every other limit. */
|
||||
readonly starts: RateWindow | null;
|
||||
/** Set by the app (M13): rings closed or hidden devices and clears them again. */
|
||||
push: CallPushSink | null = null;
|
||||
/** Set by the app: someone connected to a call, so drop them from any voice channel. */
|
||||
onConnected: ((userId: string) => void) | null = null;
|
||||
|
||||
constructor(
|
||||
private readonly db: DB,
|
||||
private readonly hub: () => RealtimeHub,
|
||||
private readonly messages: MessageService,
|
||||
private readonly config: LivekitGrantConfig & { callRingMs: number },
|
||||
private readonly api: LivekitApi | null,
|
||||
private readonly log: Logger = quiet,
|
||||
callStartLimit = true,
|
||||
) {
|
||||
this.starts = callStartLimit
|
||||
? new RateWindow(CALL_STARTS_PER_WINDOW, CALL_STARTS_WINDOW_MS)
|
||||
: null;
|
||||
}
|
||||
|
||||
get enabled(): boolean {
|
||||
return !!this.config.apiKey && !!this.config.apiSecret;
|
||||
}
|
||||
|
||||
// ---- REST ----
|
||||
|
||||
/**
|
||||
* Start a call in a DM, or get the one already going (then it's like joining). Only members who
|
||||
* may post (a 1:1 whose people no longer share a server is read-only and can't call).
|
||||
*/
|
||||
start(userId: string, dmId: string): { call: CallDto; created: boolean } {
|
||||
// Closed or blocked 1:1 (M18, D5): the neutral "Couldn't call".
|
||||
const dm = requireDmPost(this.db, userId, dmId, cantCall);
|
||||
this.requireEnabled();
|
||||
const active = this.activeRow(dm.id);
|
||||
if (!active && this.starts && !this.starts.allows(userId))
|
||||
throw tooManyCalls(this.starts.retryAfterSec(userId));
|
||||
const { row, created } = this.db
|
||||
.transaction(() => claimCall(this.db, dm.id, userId))
|
||||
.immediate();
|
||||
if (!created) {
|
||||
const l = this.liveOf(row);
|
||||
if (l.ringing.has(userId)) this.answer(l, userId);
|
||||
return { call: this.dto(l, userId), created: false };
|
||||
}
|
||||
this.starts?.record(userId);
|
||||
const l = this.liveOf(row);
|
||||
// M18 (D4): nobody is rung by someone they blocked or who blocked them (in a group the call
|
||||
// still happens and they can join it from the chat; they just get no ring and no call push).
|
||||
// QA-70 (D18): they are still on the ringing list everyone sees; only the ring is skipped.
|
||||
const blocks = Blocks.for(this.db);
|
||||
for (const id of dmMemberIds(this.db, dm.id)) {
|
||||
if (id === userId) continue;
|
||||
l.ringing.add(id);
|
||||
if (blocks.between(userId, id)) l.silent.add(id);
|
||||
}
|
||||
l.timer = setTimeout(() => this.ringTimeout(dm.id, row.id), this.config.callRingMs);
|
||||
l.timer.unref?.();
|
||||
const messageId = this.messages.insertSystem(dm.id, userId, {
|
||||
event: 'call_started',
|
||||
targets: [],
|
||||
callId: row.id,
|
||||
});
|
||||
this.messages.announce(dm.id, [messageId]);
|
||||
for (const id of this.rung(l)) this.hub().toUser(id, 'call:ring', { call: this.dto(l, id) });
|
||||
this.pushRing(l);
|
||||
this.emit(dm.id);
|
||||
return { call: this.dto(l, userId), created: true };
|
||||
}
|
||||
|
||||
/** Accept on this device: ringing stops in the user's other tabs; the client then joins. */
|
||||
accept(userId: string, callId: string): CallDto {
|
||||
const l = this.requireLiveCall(userId, callId);
|
||||
this.answer(l, userId);
|
||||
return this.dto(l, userId);
|
||||
}
|
||||
|
||||
/** Decline: stops ringing for this user (all tabs). In a 1:1 it also ends the call. */
|
||||
decline(userId: string, callId: string): void {
|
||||
const l = this.requireLiveCall(userId, callId);
|
||||
const dm = this.dmRow(l.row.dm_channel_id);
|
||||
if (l.ringing.delete(userId)) this.stopRing(l, userId, 'declined');
|
||||
if (dm?.kind === 'dm' && userId !== l.row.started_by && !l.row.answered) {
|
||||
this.end(l, 'declined');
|
||||
return;
|
||||
}
|
||||
this.endIfOver(l);
|
||||
this.emit(l.row.dm_channel_id);
|
||||
}
|
||||
|
||||
/** Hang up. The caller hanging up while it rings cancels it; the last one out ends it. */
|
||||
leave(userId: string, callId: string): void {
|
||||
const l = this.requireLiveCall(userId, callId);
|
||||
// A normal leave makes no LiveKit call at all: the client has already disconnected (QA-54).
|
||||
// LiveKit closes the empty room by itself (`empty_timeout`).
|
||||
l.people.delete(userId);
|
||||
if (l.ringing.delete(userId)) this.stopRing(l, userId, 'declined');
|
||||
if (l.people.size === 0) {
|
||||
this.end(l, 'ended');
|
||||
return;
|
||||
}
|
||||
this.emit(l.row.dm_channel_id);
|
||||
}
|
||||
|
||||
/** A LiveKit token for this DM's call room: current members only (404 otherwise, like voice). */
|
||||
/**
|
||||
* `callId` (QA-59): the call the client is joining or rejoining. If it isn't the active call (it
|
||||
* ended, maybe with a new one started in the gap), refuse with 409 so a reconnect can never
|
||||
* join, and so pick up, the next call. D10: required since 0.5 (optional in 0.4 for cached
|
||||
* 0.3 bundles): without it the answer is 400 `call_id_required`, after the membership check,
|
||||
* so a non-member still gets the same 404 as for the DM itself.
|
||||
*/
|
||||
async token(userId: string, dmId: string, callId: string | undefined): Promise<VoiceTokenDto> {
|
||||
const dm = requireDmPost(this.db, userId, dmId, cantCall);
|
||||
this.requireEnabled();
|
||||
if (callId === undefined)
|
||||
throw new HttpError(400, 'call_id_required', 'Reload the page to join this call');
|
||||
const row = this.activeRow(dm.id);
|
||||
if (!row) throw new HttpError(409, 'no_active_call', 'There is no call in this conversation');
|
||||
if (row.id !== callId) throw new HttpError(409, 'call_ended', 'That call has ended');
|
||||
const user = this.db.prepare('SELECT display_name FROM users WHERE id = ?').get(userId) as {
|
||||
display_name: string;
|
||||
};
|
||||
return mintToken(
|
||||
this.config,
|
||||
{ id: userId, displayName: user.display_name },
|
||||
callRoomFor(dm.id, row.id),
|
||||
);
|
||||
}
|
||||
|
||||
/** The DM's current call (members only). */
|
||||
get(userId: string, dmId: string): CallDto | null {
|
||||
const dm = requireDmAccess(this.db, userId, dmId);
|
||||
const row = this.activeRow(dm.id);
|
||||
return row ? this.dto(this.liveOf(row), userId) : null;
|
||||
}
|
||||
|
||||
/** Every active call in a DM this user is in (page load: "Join call" banners and rings). */
|
||||
listMine(userId: string): CallDto[] {
|
||||
const rows = this.db
|
||||
.prepare(
|
||||
`SELECT c.* FROM calls c JOIN dm_members m ON m.dm_channel_id = c.dm_channel_id
|
||||
WHERE m.user_id = ? AND c.ended_at IS NULL ORDER BY c.started_at`,
|
||||
)
|
||||
.all(userId) as CallRow[];
|
||||
return rows.map((r) => this.dto(this.liveOf(r), userId));
|
||||
}
|
||||
|
||||
/** Mute/deafen as the client sees itself; only while connected to that call. */
|
||||
setSelf(userId: string, callId: string, s: { muted: boolean; deafened: boolean }): CallDto {
|
||||
const l = this.requireLiveCall(userId, callId);
|
||||
const p = l.people.get(userId);
|
||||
if (!p) throw new HttpError(409, 'not_in_call', "You're not connected to this call");
|
||||
p.deafened = s.deafened;
|
||||
p.muted = s.muted || s.deafened;
|
||||
this.emit(l.row.dm_channel_id);
|
||||
return this.dto(l, userId);
|
||||
}
|
||||
|
||||
// ---- LiveKit -> app ----
|
||||
|
||||
handleWebhook(ev: LkWebhookEvent): void {
|
||||
const room = ev.room?.name;
|
||||
const parsed = room ? parseCallRoom(room) : null;
|
||||
if (!room || !parsed) return;
|
||||
const dmId = parsed.dmId;
|
||||
const row = this.activeRow(dmId);
|
||||
if (row && parsed.callId !== row.id) {
|
||||
// The room of another (ended, or 0.3.0-style) call in this DM: it can't touch this call.
|
||||
// Someone joining it with an old token is put out; the kick can only reach that room.
|
||||
const p = ev.participant;
|
||||
if (ev.event === 'participant_joined' && p)
|
||||
this.kick(
|
||||
room,
|
||||
p.identity,
|
||||
p.sid,
|
||||
'joined the room of an ended call',
|
||||
parsed.callId ?? undefined,
|
||||
);
|
||||
else if (ev.event === 'room_finished')
|
||||
audit(this.log, {
|
||||
lk: 'webhook room_finished',
|
||||
room,
|
||||
sid: ev.room?.sid,
|
||||
callId: row.id,
|
||||
reason: "ignored: another call's room",
|
||||
});
|
||||
return;
|
||||
}
|
||||
const l = row ? this.liveOf(row) : null;
|
||||
if (
|
||||
l &&
|
||||
!l.roomSid &&
|
||||
ev.room?.sid &&
|
||||
['room_started', 'participant_joined'].includes(ev.event)
|
||||
)
|
||||
l.roomSid = ev.room.sid;
|
||||
if (ev.event === 'room_finished') {
|
||||
const base = { lk: 'webhook room_finished', room, sid: ev.room?.sid, callId: l?.row.id };
|
||||
const stale = l ? this.staleRoomFinished(l, ev) : null;
|
||||
if (!l) audit(this.log, { ...base, reason: 'ignored: no active call' });
|
||||
else if (!l.hadPeople) audit(this.log, { ...base, reason: 'ignored: nobody had joined yet' });
|
||||
else if (stale) audit(this.log, { ...base, reason: `ignored: ${stale}` });
|
||||
else void this.endIfRoomEmpty(l, room);
|
||||
return;
|
||||
}
|
||||
const p = ev.participant;
|
||||
if (!p) return;
|
||||
if (!l || !isDmMember(this.db, p.identity, dmId)) {
|
||||
// Not a member (removed, left, never was) or no call any more: out, even with a valid token.
|
||||
if (ev.event === 'participant_joined')
|
||||
this.kick(
|
||||
room,
|
||||
p.identity,
|
||||
p.sid,
|
||||
l ? 'joined but not a member of this DM' : 'joined with no active call',
|
||||
l?.row.id,
|
||||
);
|
||||
if (l && l.people.delete(p.identity)) this.afterPeopleChange(l);
|
||||
return;
|
||||
}
|
||||
switch (ev.event) {
|
||||
case 'participant_joined':
|
||||
this.upsert(l, p, true);
|
||||
break;
|
||||
case 'participant_left':
|
||||
case 'participant_connection_aborted': {
|
||||
const e = l.people.get(p.identity);
|
||||
const base = {
|
||||
lk: `webhook ${ev.event}`,
|
||||
room,
|
||||
identity: p.identity,
|
||||
sid: p.sid,
|
||||
callId: l.row.id,
|
||||
};
|
||||
if (e && (!p.sid || e.sid === p.sid)) {
|
||||
audit(this.log, { ...base, reason: 'removed from the call', people: l.people.size - 1 });
|
||||
l.people.delete(p.identity);
|
||||
this.afterPeopleChange(l);
|
||||
} else {
|
||||
audit(this.log, {
|
||||
...base,
|
||||
reason: e ? `ignored: the call has session ${e.sid}` : 'ignored: not in the call',
|
||||
});
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'track_published':
|
||||
case 'track_unpublished': {
|
||||
const e = this.upsert(l, p, false);
|
||||
const on = ev.event === 'track_published';
|
||||
if (ev.track?.source === TrackSource.SCREEN_SHARE) e.sharing = on;
|
||||
else if (ev.track?.source === TrackSource.CAMERA) {
|
||||
e.camera = on;
|
||||
if (on && !this.config.videoEnabled) this.revokeCamera(room, p.identity);
|
||||
} else if (ev.track?.source === TrackSource.MICROPHONE) {
|
||||
e.muted = e.deafened || !on || ev.track.muted;
|
||||
} else break;
|
||||
this.emit(dmId);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A `room_finished` that is about an earlier call in this DM (QA-54): another room session, or
|
||||
* made before this call started. (`createdAt` is whole seconds, so only a second that ended
|
||||
* before the call's start counts as earlier.)
|
||||
*/
|
||||
private staleRoomFinished(l: Live, ev: LkWebhookEvent): string | null {
|
||||
if (l.roomSid && ev.room?.sid && ev.room.sid !== l.roomSid)
|
||||
return 'another room session than this call';
|
||||
if (ev.createdAt !== undefined) {
|
||||
const at = Number(ev.createdAt);
|
||||
if (at > 0 && (at + 1) * 1000 <= Date.parse(l.row.started_at))
|
||||
return 'made before this call started';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Backstop for `room_finished`: ask LiveKit whether anyone is still in the room and ignore the
|
||||
* event if so. Fails open: no answer (an error, no API) ends the call as before.
|
||||
*/
|
||||
private async endIfRoomEmpty(l: Live, room: string): Promise<void> {
|
||||
let someoneThere = false;
|
||||
try {
|
||||
someoneThere = ((await this.api?.listParticipants(room))?.length ?? 0) > 0;
|
||||
} catch {
|
||||
someoneThere = false;
|
||||
}
|
||||
const base = { lk: 'webhook room_finished', room, callId: l.row.id };
|
||||
if (someoneThere) {
|
||||
audit(this.log, { ...base, reason: 'ignored: LiveKit says people are still in the room' });
|
||||
return;
|
||||
}
|
||||
if (this.live.get(l.row.dm_channel_id) === l) {
|
||||
audit(this.log, { ...base, reason: 'ending the call: the room is empty' });
|
||||
this.end(l, 'ended', false);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Startup: webhooks sent while the app was down are lost. Ask LiveKit who is in each call room;
|
||||
* an active call with nobody there is closed (missed or ended), people who may no longer be
|
||||
* there are removed, and call rooms without an active call are deleted.
|
||||
*/
|
||||
async rebuild(): Promise<void> {
|
||||
if (!this.api || !this.enabled) return;
|
||||
const rooms = new Set((await this.api.listRooms()).map((r) => r.name));
|
||||
for (const name of rooms) {
|
||||
const parsed = parseCallRoom(name);
|
||||
const active = parsed ? this.activeRow(parsed.dmId) : undefined;
|
||||
if (parsed && (!active || active.id !== parsed.callId)) {
|
||||
audit(this.log, {
|
||||
lk: 'deleteRoom',
|
||||
reason: 'start-up: room with no active call',
|
||||
room: name,
|
||||
});
|
||||
this.call(() => this.api?.deleteRoom(name), 'deleteRoom');
|
||||
}
|
||||
}
|
||||
const rows = this.db.prepare('SELECT * FROM calls WHERE ended_at IS NULL').all() as CallRow[];
|
||||
for (const row of rows) {
|
||||
const room = callRoomFor(row.dm_channel_id, row.id);
|
||||
const l = this.liveOf(row);
|
||||
const people = rooms.has(room) ? await this.api.listParticipants(room) : [];
|
||||
for (const p of people) {
|
||||
if (!isDmMember(this.db, p.identity, row.dm_channel_id))
|
||||
this.kick(room, p.identity, undefined, 'start-up: in the room but not a member', row.id);
|
||||
else {
|
||||
this.upsert(l, p, false, false);
|
||||
if (!this.config.videoEnabled && p.tracks.some((t) => t.source === TrackSource.CAMERA))
|
||||
this.revokeCamera(room, p.identity);
|
||||
}
|
||||
}
|
||||
if (l.people.size === 0) this.end(l, 'ended');
|
||||
else this.emit(row.dm_channel_id);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- app lifecycle ----
|
||||
|
||||
/**
|
||||
* Someone left or was removed from a group (or the group is gone): they stop ringing and are
|
||||
* dropped from its live call right away (removeParticipant, like a voice kick).
|
||||
*/
|
||||
memberGone(dmId: string, userId: string): void {
|
||||
const row = this.activeRow(dmId);
|
||||
const l = row ? this.liveOf(row) : this.live.get(dmId);
|
||||
if (!l) return;
|
||||
const room = callRoomFor(dmId, l.row.id);
|
||||
// A removed member keeps no ringing notification: stopRing also sends their call-end.
|
||||
if (l.ringing.delete(userId)) this.stopRing(l, userId, 'removed');
|
||||
const gone = l.people.get(userId);
|
||||
if (l.people.delete(userId))
|
||||
this.kick(room, userId, gone?.sid, 'removed from the group', l.row.id);
|
||||
this.hub().toUser(userId, 'call:state', { dmId, call: null });
|
||||
if (!row) {
|
||||
// The group itself was deleted (last member left): the calls row went with it.
|
||||
if (l.timer) clearTimeout(l.timer);
|
||||
this.live.delete(dmId);
|
||||
audit(this.log, { lk: 'deleteRoom', reason: 'the group was deleted', room });
|
||||
this.call(() => this.api?.deleteRoom(room), 'deleteRoom');
|
||||
return;
|
||||
}
|
||||
this.afterPeopleChange(l);
|
||||
}
|
||||
|
||||
/**
|
||||
* M18: `blockerId` just blocked `blockedId`. A live 1:1 call between them (ringing or
|
||||
* connected) ends at once through the normal end path, without a LiveKit kick by identity
|
||||
* (QA-54): both clients leave on `call:state null`. In group calls nobody is removed; only the
|
||||
* blocker stops being rung by a call the blocked person started (sent to the blocker alone, so
|
||||
* the blocked person's session sees no new event). The blocker stays on the ringing list until
|
||||
* the ring timeout, like anyone who doesn't answer (QA-70), so the list gives nothing away.
|
||||
*/
|
||||
blocked(blockerId: string, blockedId: string): void {
|
||||
for (const l of [...this.live.values()]) {
|
||||
if (l.row.ended_at) continue;
|
||||
const dm = this.dmRow(l.row.dm_channel_id);
|
||||
if (!dm) continue;
|
||||
if (dm.kind === 'dm') {
|
||||
const pair = new Set([dm.user_a, dm.user_b]);
|
||||
if (pair.has(blockerId) && pair.has(blockedId)) this.end(l, 'ended', false);
|
||||
continue;
|
||||
}
|
||||
if (l.row.started_by === blockedId && l.ringing.has(blockerId) && !l.silent.has(blockerId)) {
|
||||
this.stopRing(l, blockerId, 'ended');
|
||||
l.silent.add(blockerId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Disconnect a user from whatever call they're in (they joined a voice channel). */
|
||||
disconnectUser(userId: string): void {
|
||||
for (const l of [...this.live.values()]) {
|
||||
const gone = l.people.get(userId);
|
||||
if (l.people.delete(userId)) {
|
||||
this.kick(
|
||||
callRoomFor(l.row.dm_channel_id, l.row.id),
|
||||
userId,
|
||||
gone?.sid,
|
||||
'joined a voice channel',
|
||||
l.row.id,
|
||||
);
|
||||
this.afterPeopleChange(l);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Where this user is connected, if anywhere (tests and diagnostics). */
|
||||
callOf(userId: string): string | null {
|
||||
for (const l of this.live.values()) if (l.people.has(userId)) return l.row.id;
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Stop timers (app close). */
|
||||
close(): void {
|
||||
for (const l of this.live.values()) if (l.timer) clearTimeout(l.timer);
|
||||
}
|
||||
|
||||
// ---- internals ----
|
||||
|
||||
private requireEnabled(): void {
|
||||
if (!this.enabled) {
|
||||
throw new HttpError(503, 'voice_unavailable', 'Calls are not set up on this server');
|
||||
}
|
||||
}
|
||||
|
||||
private dmRow(dmId: string): DmChannelRow | undefined {
|
||||
return this.db.prepare('SELECT * FROM dm_channels WHERE id = ?').get(dmId) as
|
||||
DmChannelRow | undefined;
|
||||
}
|
||||
|
||||
private activeRow(dmId: string): CallRow | undefined {
|
||||
return this.db
|
||||
.prepare('SELECT * FROM calls WHERE dm_channel_id = ? AND ended_at IS NULL')
|
||||
.get(dmId) as CallRow | undefined;
|
||||
}
|
||||
|
||||
/** The call (by id) if it's active and the user is a member of its DM; 404 otherwise. */
|
||||
private requireLiveCall(userId: string, callId: string): Live {
|
||||
const row = this.db.prepare('SELECT * FROM calls WHERE id = ?').get(callId) as
|
||||
CallRow | undefined;
|
||||
if (!row || !isDmMember(this.db, userId, row.dm_channel_id)) throw callNotFound();
|
||||
if (row.ended_at) throw new HttpError(409, 'call_ended', 'That call has ended');
|
||||
return this.liveOf(row);
|
||||
}
|
||||
|
||||
private liveOf(row: CallRow): Live {
|
||||
let l = this.live.get(row.dm_channel_id);
|
||||
if (!l || l.row.id !== row.id) {
|
||||
if (l?.timer) clearTimeout(l.timer);
|
||||
l = {
|
||||
row,
|
||||
people: new Map(),
|
||||
ringing: new Set(),
|
||||
silent: new Set(),
|
||||
pushed: new Set(),
|
||||
timer: null,
|
||||
hadPeople: false,
|
||||
roomSid: null,
|
||||
};
|
||||
this.live.set(row.dm_channel_id, l);
|
||||
}
|
||||
return l;
|
||||
}
|
||||
|
||||
/** Someone other than the caller picked up (accept, or joined from any device). */
|
||||
private answer(l: Live, userId: string): void {
|
||||
if (l.ringing.delete(userId)) this.stopRing(l, userId, 'accepted');
|
||||
if (userId !== l.row.started_by && !l.row.answered) {
|
||||
this.db.prepare('UPDATE calls SET answered = 1 WHERE id = ?').run(l.row.id);
|
||||
l.row.answered = 1;
|
||||
}
|
||||
this.emit(l.row.dm_channel_id);
|
||||
}
|
||||
|
||||
/** Ring the callees' closed or hidden devices (web push). Open tabs ring over the socket. */
|
||||
private pushRing(l: Live): void {
|
||||
if (!this.push) return;
|
||||
const callId = l.row.id;
|
||||
const expMs = Date.now() + Math.min(this.config.callRingMs, CALL_PUSH_TTL_MS);
|
||||
const pushed = this.push.notifyCall({
|
||||
callId,
|
||||
dmId: l.row.dm_channel_id,
|
||||
fromUserId: l.row.started_by,
|
||||
userIds: this.rung(l),
|
||||
expMs,
|
||||
stillRinging: (id) => !l.row.ended_at && l.ringing.has(id) && !l.silent.has(id),
|
||||
});
|
||||
for (const id of pushed) l.pushed.add(id);
|
||||
}
|
||||
|
||||
/** Who on the list is actually rung (socket ring and push): not those silenced by a block. */
|
||||
private rung(l: Live): string[] {
|
||||
return [...l.ringing].filter((id) => !l.silent.has(id));
|
||||
}
|
||||
|
||||
/**
|
||||
* Ringing stops for one user: the socket event for open tabs, and call-end for pushed devices.
|
||||
* Someone listed but never rung (QA-70) gets nothing: there is no ring of theirs to stop.
|
||||
*/
|
||||
private stopRing(l: Live, userId: string, reason: CallStopReason | 'removed'): void {
|
||||
if (l.silent.delete(userId)) return;
|
||||
const dmId = l.row.dm_channel_id;
|
||||
this.hub().toUser(userId, 'call:stop-ring', { callId: l.row.id, dmId, reason });
|
||||
this.stopPush(
|
||||
l,
|
||||
userId,
|
||||
reason === 'accepted'
|
||||
? 'answered'
|
||||
: reason === 'timeout'
|
||||
? 'missed'
|
||||
: reason === 'declined'
|
||||
? 'declined'
|
||||
: 'ended',
|
||||
);
|
||||
}
|
||||
|
||||
private stopPush(
|
||||
l: Live,
|
||||
userId: string,
|
||||
reason: 'answered' | 'declined' | 'ended' | 'missed',
|
||||
): void {
|
||||
if (!this.push || !l.pushed.delete(userId)) return;
|
||||
this.push.notifyCallEnd({
|
||||
callId: l.row.id,
|
||||
dmId: l.row.dm_channel_id,
|
||||
fromUserId: l.row.started_by,
|
||||
userId,
|
||||
reason,
|
||||
});
|
||||
}
|
||||
|
||||
private ringTimeout(dmId: string, callId: string): void {
|
||||
const l = this.live.get(dmId);
|
||||
if (!l || l.row.id !== callId || l.row.ended_at) return;
|
||||
l.timer = null;
|
||||
for (const id of [...l.ringing]) this.stopRing(l, id, 'timeout');
|
||||
l.ringing.clear();
|
||||
if (!l.row.answered) this.end(l, 'timeout');
|
||||
else this.emit(dmId);
|
||||
}
|
||||
|
||||
private upsert(l: Live, p: LkParticipant, joined: boolean, emit = true): Person {
|
||||
let e = l.people.get(p.identity);
|
||||
if (!e || (joined && e.sid !== p.sid)) {
|
||||
const mic = p.tracks.find((t) => t.source === TrackSource.MICROPHONE);
|
||||
const joinedAtSec = Number(p.joinedAt ?? 0);
|
||||
e = {
|
||||
sid: p.sid,
|
||||
muted: !mic || mic.muted,
|
||||
deafened: false,
|
||||
sharing: p.tracks.some((t) => t.source === TrackSource.SCREEN_SHARE),
|
||||
camera: p.tracks.some((t) => t.source === TrackSource.CAMERA),
|
||||
joinedAt: new Date(joinedAtSec > 0 ? joinedAtSec * 1000 : Date.now()).toISOString(),
|
||||
};
|
||||
l.people.set(p.identity, e);
|
||||
l.hadPeople = true;
|
||||
if (joined) {
|
||||
this.onConnected?.(p.identity);
|
||||
// Joining from any device counts as picking up, and stops the ring everywhere.
|
||||
if (l.ringing.has(p.identity) || p.identity !== l.row.started_by)
|
||||
this.answer(l, p.identity);
|
||||
// One call at a time: leave any other DM call.
|
||||
for (const other of [...this.live.values()]) {
|
||||
const there = other.people.get(p.identity);
|
||||
if (other !== l && other.people.delete(p.identity)) {
|
||||
this.kick(
|
||||
callRoomFor(other.row.dm_channel_id, other.row.id),
|
||||
p.identity,
|
||||
there?.sid,
|
||||
'joined another call',
|
||||
other.row.id,
|
||||
);
|
||||
this.afterPeopleChange(other);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (emit) this.emit(l.row.dm_channel_id);
|
||||
}
|
||||
return e;
|
||||
}
|
||||
|
||||
private afterPeopleChange(l: Live): void {
|
||||
if (l.people.size === 0 && l.hadPeople) {
|
||||
this.end(l, 'ended');
|
||||
return;
|
||||
}
|
||||
this.endIfOver(l);
|
||||
if (!l.row.ended_at) this.emit(l.row.dm_channel_id);
|
||||
}
|
||||
|
||||
/** Nobody connected and nobody left to ring: nothing can happen in this call any more. */
|
||||
private endIfOver(l: Live): void {
|
||||
if (!l.row.ended_at && l.people.size === 0 && l.ringing.size === 0 && l.hadPeople) {
|
||||
this.end(l, 'ended');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* End the call: row closed, ringing stopped, `call_missed` (nobody picked up) or `call_ended`
|
||||
* with the duration, and `call:state null`. Anyone still connected (a caller whose call was
|
||||
* declined or timed out) is forced out with a sid-checked kick in this call's own room, so the
|
||||
* kick can't reach the next call even if LiveKit serves it late (QA-58). The room isn't deleted:
|
||||
* LiveKit closes it when empty.
|
||||
*/
|
||||
private end(l: Live, why: 'ended' | 'timeout' | 'declined', kickPeople = true): void {
|
||||
if (l.row.ended_at) return;
|
||||
const dmId = l.row.dm_channel_id;
|
||||
audit(this.log, {
|
||||
lk: 'call-end',
|
||||
reason: why,
|
||||
callId: l.row.id,
|
||||
room: callRoomFor(dmId, l.row.id),
|
||||
connected: l.people.size,
|
||||
});
|
||||
const endedAt = nowIso();
|
||||
const changed = this.db
|
||||
.prepare('UPDATE calls SET ended_at = ? WHERE id = ? AND ended_at IS NULL')
|
||||
.run(endedAt, l.row.id).changes;
|
||||
l.row.ended_at = endedAt;
|
||||
if (l.timer) clearTimeout(l.timer);
|
||||
l.timer = null;
|
||||
const reason: CallStopReason = why === 'timeout' ? 'timeout' : 'ended';
|
||||
for (const id of [...l.ringing]) this.stopRing(l, id, reason);
|
||||
l.ringing.clear();
|
||||
const connected = [...l.people.entries()];
|
||||
l.people.clear();
|
||||
this.live.delete(dmId);
|
||||
if (changed && this.dmRow(dmId)) {
|
||||
const info: StoredSystemInfo = l.row.answered
|
||||
? {
|
||||
event: 'call_ended',
|
||||
targets: [],
|
||||
callId: l.row.id,
|
||||
durationSec: Math.max(
|
||||
0,
|
||||
Math.round((Date.parse(endedAt) - Date.parse(l.row.started_at)) / 1000),
|
||||
),
|
||||
}
|
||||
: { event: 'call_missed', targets: [], callId: l.row.id };
|
||||
const messageId = this.messages.insertSystem(dmId, l.row.started_by, info);
|
||||
this.messages.announce(dmId, [messageId]);
|
||||
}
|
||||
for (const id of dmMemberIds(this.db, dmId)) {
|
||||
this.hub().toUser(id, 'call:state', { dmId, call: null });
|
||||
}
|
||||
if (kickPeople)
|
||||
for (const [id, e] of connected)
|
||||
this.kick(
|
||||
callRoomFor(dmId, l.row.id),
|
||||
id,
|
||||
e.sid,
|
||||
`call ended (${why}) with them still connected`,
|
||||
l.row.id,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Force someone out of a call room. The kick first looks the person up and only asks for the
|
||||
* removal if the session it meant (`sid`) is still there. LiveKit removes by identity, so a
|
||||
* removal served late could still reach a newer session of the same person in the same room;
|
||||
* rooms are per call so that can't be another call's session (QA-58). It fails closed: if
|
||||
* LiveKit can't be asked, nobody is kicked (the client also leaves by itself on `call:state`).
|
||||
*/
|
||||
private kick(
|
||||
room: string,
|
||||
identity: string,
|
||||
sid: string | undefined,
|
||||
reason: string,
|
||||
callId?: string,
|
||||
): void {
|
||||
const a = { room, identity, sid, callId, reason };
|
||||
fireAndForget(
|
||||
this.log,
|
||||
async () => {
|
||||
const api = this.api;
|
||||
if (!api) return;
|
||||
let there;
|
||||
try {
|
||||
there = (await api.listParticipants(room)).find((x) => x.identity === identity);
|
||||
} catch {
|
||||
audit(this.log, { lk: 'kick-skipped', ...a, why: 'lookup failed (fail closed)' });
|
||||
return;
|
||||
}
|
||||
if (!there) {
|
||||
audit(this.log, { lk: 'kick-skipped', ...a, why: 'not in the room any more' });
|
||||
return;
|
||||
}
|
||||
if (sid && there.sid && there.sid !== sid) {
|
||||
audit(this.log, {
|
||||
lk: 'kick-skipped',
|
||||
...a,
|
||||
why: 'a different session',
|
||||
nowSid: there.sid,
|
||||
});
|
||||
return;
|
||||
}
|
||||
audit(this.log, { lk: 'removeParticipant', ...a, sessionSid: there.sid });
|
||||
await api.removeParticipant(room, identity);
|
||||
},
|
||||
'removeParticipant',
|
||||
);
|
||||
}
|
||||
|
||||
private revokeCamera(room: string, identity: string): void {
|
||||
audit(this.log, {
|
||||
lk: 'updateParticipant',
|
||||
reason: 'camera not allowed (video off)',
|
||||
room,
|
||||
identity,
|
||||
});
|
||||
fireAndForget(
|
||||
this.log,
|
||||
() => this.api?.setPublishSources?.(room, identity, publishSources(this.config)),
|
||||
'updateParticipant',
|
||||
);
|
||||
}
|
||||
|
||||
private call(fn: () => Promise<unknown> | undefined, what: string): void {
|
||||
fireAndForget(this.log, fn, what);
|
||||
}
|
||||
|
||||
/**
|
||||
* The call as `readerId` sees it. `ringing` is the same unfiltered list for everyone (QA-70);
|
||||
* `ringsYou` (D20, QA-78) answers only for the reader whether this call rings them, so clients
|
||||
* never infer it from the list (a member skipped because of a block stays listed).
|
||||
*/
|
||||
private dto(l: Live, readerId: string): CallDto {
|
||||
const participants: VoiceParticipantDto[] = [...l.people.entries()]
|
||||
.map(([userId, e]) => ({
|
||||
userId,
|
||||
muted: e.muted,
|
||||
deafened: e.deafened,
|
||||
sharing: e.sharing,
|
||||
camera: e.camera,
|
||||
joinedAt: e.joinedAt,
|
||||
}))
|
||||
.sort((a, b) => a.joinedAt.localeCompare(b.joinedAt) || a.userId.localeCompare(b.userId));
|
||||
return {
|
||||
id: l.row.id,
|
||||
dmId: l.row.dm_channel_id,
|
||||
startedBy: l.row.started_by,
|
||||
startedAt: l.row.started_at,
|
||||
participants,
|
||||
ringing: [...l.ringing],
|
||||
ringsYou: l.ringing.has(readerId) && !l.silent.has(readerId) && !l.row.ended_at,
|
||||
};
|
||||
}
|
||||
|
||||
/** call:state to every current member of the DM (their user rooms, all tabs). */
|
||||
private emit(dmId: string): void {
|
||||
const row = this.activeRow(dmId);
|
||||
const l = row ? this.live.get(dmId) : undefined;
|
||||
for (const id of dmMemberIds(this.db, dmId))
|
||||
this.hub().toUser(id, 'call:state', { dmId, call: l ? this.dto(l, id) : null });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,299 @@
|
||||
import {
|
||||
Perm,
|
||||
normalizeChannelName,
|
||||
type CategoryDto,
|
||||
type ChannelDto,
|
||||
type CreateChannelInput,
|
||||
type PositionUpdate,
|
||||
type UpdateChannelInput,
|
||||
} from '@chat/shared';
|
||||
import { Access } from '../auth/access.js';
|
||||
import {
|
||||
requireCategoryAccess,
|
||||
requireChannelAccess,
|
||||
type ChannelRow,
|
||||
} from '../auth/permissions.js';
|
||||
import type { DB } from '../db/index.js';
|
||||
import { badRequest } from '../lib/errors.js';
|
||||
import { newId } from '../lib/ids.js';
|
||||
import type { Lifecycle } from './lifecycle.js';
|
||||
import type { RealtimeHub } from '../realtime/hub.js';
|
||||
import { toCategoryDto, toChannelDto } from './servers.js';
|
||||
import { channelOverrides } from './role-dto.js';
|
||||
import { denseFor, emitPositionChanges, snapshot, viewerChannelDto } from './positions.js';
|
||||
|
||||
const MAX_CHANNELS_PER_SERVER = 500;
|
||||
|
||||
/**
|
||||
* Categories and channels. Reads need VIEW on the channel; every write needs MANAGE_CHANNELS
|
||||
* (section 7; owner and admins have it), and a channel the actor can't view is a 404.
|
||||
*/
|
||||
export class ChannelService {
|
||||
constructor(
|
||||
private readonly db: DB,
|
||||
private readonly hub: () => RealtimeHub,
|
||||
private readonly lifecycle: Lifecycle = {},
|
||||
) {}
|
||||
|
||||
/** MANAGE_CHANNELS, server scope: 404 for non-members, 403 without the bit. */
|
||||
private manage(userId: string, serverId: string): void {
|
||||
Access.for(this.db).requireServerPerm(userId, serverId, Perm.MANAGE_CHANNELS);
|
||||
}
|
||||
|
||||
// ---- categories ----
|
||||
|
||||
createCategory(userId: string, serverId: string, name: string): CategoryDto {
|
||||
this.manage(userId, serverId);
|
||||
const id = newId();
|
||||
// D63a: category positions are kept dense (0..n-1) and are the same for every member.
|
||||
const { next } = this.db
|
||||
.prepare('SELECT COUNT(*) AS next FROM categories WHERE server_id = ?')
|
||||
.get(serverId) as { next: number };
|
||||
this.db
|
||||
.prepare('INSERT INTO categories (id, server_id, name, position) VALUES (?, ?, ?, ?)')
|
||||
.run(id, serverId, name, next);
|
||||
const category = toCategoryDto({ id, server_id: serverId, name, position: next });
|
||||
this.hub().toServer(serverId, 'category:create', { category });
|
||||
return category;
|
||||
}
|
||||
|
||||
renameCategory(userId: string, categoryId: string, name: string): CategoryDto {
|
||||
const cat = requireCategoryAccess(this.db, userId, categoryId, Perm.MANAGE_CHANNELS);
|
||||
this.db.prepare('UPDATE categories SET name = ? WHERE id = ?').run(name, categoryId);
|
||||
const category = toCategoryDto({ ...cat, name });
|
||||
this.hub().toServer(cat.server_id, 'category:update', { category });
|
||||
return category;
|
||||
}
|
||||
|
||||
/** Channels in the deleted category move to "no category", after the existing uncategorised ones. */
|
||||
deleteCategory(userId: string, categoryId: string): void {
|
||||
const cat = requireCategoryAccess(this.db, userId, categoryId, Perm.MANAGE_CHANNELS);
|
||||
const before = snapshot(this.db, cat.server_id);
|
||||
let categories: PositionUpdate[] = [];
|
||||
this.db.transaction(() => {
|
||||
const children = this.db
|
||||
.prepare('SELECT id FROM channels WHERE category_id = ? ORDER BY position, id')
|
||||
.all(categoryId) as { id: string }[];
|
||||
let { next } = this.db
|
||||
.prepare(
|
||||
'SELECT COALESCE(MAX(position) + 1, 0) AS next FROM channels WHERE server_id = ? AND category_id IS NULL',
|
||||
)
|
||||
.get(cat.server_id) as { next: number };
|
||||
const move = this.db.prepare(
|
||||
'UPDATE channels SET category_id = NULL, position = ? WHERE id = ?',
|
||||
);
|
||||
for (const ch of children) move.run(next++, ch.id);
|
||||
this.db.prepare('DELETE FROM categories WHERE id = ?').run(categoryId);
|
||||
// D63a: close the gap so category positions stay dense and identical for everyone.
|
||||
const rest = this.db
|
||||
.prepare('SELECT id FROM categories WHERE server_id = ? ORDER BY position, id')
|
||||
.all(cat.server_id) as { id: string }[];
|
||||
const set = this.db.prepare('UPDATE categories SET position = ? WHERE id = ?');
|
||||
categories = rest.map((r, position) => {
|
||||
set.run(position, r.id);
|
||||
return { id: r.id, position };
|
||||
});
|
||||
})();
|
||||
const hub = this.hub();
|
||||
hub.toServer(cat.server_id, 'category:delete', { serverId: cat.server_id, categoryId });
|
||||
if (categories.length)
|
||||
hub.toServer(cat.server_id, 'category:reorder', {
|
||||
serverId: cat.server_id,
|
||||
positions: categories,
|
||||
});
|
||||
// D63: moved channels (and nothing hidden) in each viewer's own numbers.
|
||||
emitPositionChanges(this.db, hub, cat.server_id, before);
|
||||
}
|
||||
|
||||
/** `ids` must be every category in the server, in the new order. */
|
||||
reorderCategories(userId: string, serverId: string, ids: string[]): PositionUpdate[] {
|
||||
this.manage(userId, serverId);
|
||||
const existing = (
|
||||
this.db.prepare('SELECT id FROM categories WHERE server_id = ?').all(serverId) as {
|
||||
id: string;
|
||||
}[]
|
||||
).map((r) => r.id);
|
||||
if (ids.length !== existing.length || !ids.every((id) => existing.includes(id))) {
|
||||
throw badRequest('ids must list every category in this server exactly once');
|
||||
}
|
||||
const positions = ids.map((id, position) => ({ id, position }));
|
||||
const update = this.db.prepare('UPDATE categories SET position = ? WHERE id = ?');
|
||||
this.db.transaction(() => positions.forEach((p) => update.run(p.position, p.id)))();
|
||||
this.hub().toServer(serverId, 'category:reorder', { serverId, positions });
|
||||
return positions;
|
||||
}
|
||||
|
||||
// ---- channels ----
|
||||
|
||||
getChannel(userId: string, channelId: string): ChannelDto {
|
||||
const row = requireChannelAccess(this.db, userId, channelId);
|
||||
return viewerChannelDto(
|
||||
row,
|
||||
denseFor(this.db, userId, row.server_id),
|
||||
channelOverrides(this.db, row.id),
|
||||
);
|
||||
}
|
||||
|
||||
private requireCategoryInServer(categoryId: string, serverId: string): void {
|
||||
const cat = this.db.prepare('SELECT server_id FROM categories WHERE id = ?').get(categoryId) as
|
||||
{ server_id: string } | undefined;
|
||||
if (!cat || cat.server_id !== serverId)
|
||||
throw badRequest('Category does not belong to this server');
|
||||
}
|
||||
|
||||
private cleanName(name: string, type: 'text' | 'voice'): string {
|
||||
const clean = normalizeChannelName(name, type);
|
||||
if (!clean) throw badRequest('Channel name needs at least one letter or number');
|
||||
return clean;
|
||||
}
|
||||
|
||||
createChannel(userId: string, serverId: string, input: CreateChannelInput): ChannelDto {
|
||||
this.manage(userId, serverId);
|
||||
const categoryId = input.categoryId ?? null;
|
||||
if (categoryId) this.requireCategoryInServer(categoryId, serverId);
|
||||
const { n } = this.db
|
||||
.prepare('SELECT COUNT(*) AS n FROM channels WHERE server_id = ?')
|
||||
.get(serverId) as { n: number };
|
||||
if (n >= MAX_CHANNELS_PER_SERVER) throw badRequest('This server has too many channels');
|
||||
const { next } = this.db
|
||||
.prepare(
|
||||
'SELECT COALESCE(MAX(position) + 1, 0) AS next FROM channels WHERE server_id = ? AND category_id IS ?',
|
||||
)
|
||||
.get(serverId, categoryId) as { next: number };
|
||||
const row: ChannelRow = {
|
||||
id: newId(),
|
||||
server_id: serverId,
|
||||
category_id: categoryId,
|
||||
type: input.type,
|
||||
name: this.cleanName(input.name, input.type),
|
||||
position: next,
|
||||
topic: input.topic?.trim() || null,
|
||||
};
|
||||
this.db
|
||||
.prepare(
|
||||
'INSERT INTO channels (id, server_id, category_id, type, name, position, topic) VALUES (?, ?, ?, ?, ?, ?, ?)',
|
||||
)
|
||||
.run(row.id, row.server_id, row.category_id, row.type, row.name, row.position, row.topic);
|
||||
// D46: viewers join its room and hear about it in their own room; nobody else learns of it.
|
||||
// D63: each with the position it has in their own list.
|
||||
const hub = this.hub();
|
||||
const views = snapshot(this.db, serverId);
|
||||
for (const [viewer, dense] of views) {
|
||||
if (!dense.has(row.id)) continue;
|
||||
hub.joinChannels(viewer, [row.id]);
|
||||
hub.toUser(viewer, 'channel:create', { channel: viewerChannelDto(row, dense) });
|
||||
}
|
||||
return viewerChannelDto(row, views.get(userId) ?? new Map());
|
||||
}
|
||||
|
||||
updateChannel(userId: string, channelId: string, input: UpdateChannelInput): ChannelDto {
|
||||
const ch = requireChannelAccess(this.db, userId, channelId, Perm.MANAGE_CHANNELS);
|
||||
const next: ChannelRow = { ...ch };
|
||||
const moving = input.categoryId !== undefined && input.categoryId !== ch.category_id;
|
||||
const before = moving ? snapshot(this.db, ch.server_id) : null;
|
||||
if (input.name !== undefined) next.name = this.cleanName(input.name, ch.type);
|
||||
if (input.topic !== undefined) next.topic = input.topic?.trim() || null;
|
||||
if (input.categoryId !== undefined && input.categoryId !== ch.category_id) {
|
||||
if (input.categoryId) this.requireCategoryInServer(input.categoryId, ch.server_id);
|
||||
next.category_id = input.categoryId;
|
||||
// Moving category: append at the end of the destination.
|
||||
next.position = (
|
||||
this.db
|
||||
.prepare(
|
||||
'SELECT COALESCE(MAX(position) + 1, 0) AS next FROM channels WHERE server_id = ? AND category_id IS ?',
|
||||
)
|
||||
.get(ch.server_id, input.categoryId) as { next: number }
|
||||
).next;
|
||||
}
|
||||
this.db
|
||||
.prepare(
|
||||
'UPDATE channels SET name = ?, topic = ?, category_id = ?, position = ? WHERE id = ?',
|
||||
)
|
||||
.run(next.name, next.topic, next.category_id, next.position, channelId);
|
||||
// D46: viewers only. D63: without `position` (each viewer numbers it differently); a move
|
||||
// between categories reaches each viewer as their own channel:reorder.
|
||||
const overrides = channelOverrides(this.db, next.id);
|
||||
const { position: _stored, ...channel } = toChannelDto(next, overrides);
|
||||
const hub = this.hub();
|
||||
hub.toChannel(channelId, 'channel:update', { channel });
|
||||
if (before) emitPositionChanges(this.db, hub, ch.server_id, before);
|
||||
return viewerChannelDto(next, denseFor(this.db, userId, ch.server_id), overrides);
|
||||
}
|
||||
|
||||
deleteChannel(userId: string, channelId: string): void {
|
||||
const ch = requireChannelAccess(this.db, userId, channelId, Perm.MANAGE_CHANNELS);
|
||||
const before = snapshot(this.db, ch.server_id);
|
||||
this.db.transaction(() => {
|
||||
this.db.prepare('DELETE FROM read_states WHERE channel_id = ?').run(channelId);
|
||||
// M25: its threads' read states too (the threads themselves go by the FK cascade).
|
||||
this.db
|
||||
.prepare(
|
||||
'DELETE FROM read_states WHERE channel_id IN (SELECT id FROM threads WHERE channel_id = ?)',
|
||||
)
|
||||
.run(channelId);
|
||||
this.db.prepare('DELETE FROM channels WHERE id = ?').run(channelId);
|
||||
})();
|
||||
// D46: to the channel's room, then the room is closed.
|
||||
this.hub().toChannel(channelId, 'channel:delete', { serverId: ch.server_id, channelId });
|
||||
if (ch.type === 'voice') this.lifecycle.voiceChannelDeleted?.(channelId, ch.server_id);
|
||||
this.hub().closeChannel(channelId);
|
||||
// D63: the channels after it close the gap, for its viewers only.
|
||||
emitPositionChanges(this.db, this.hub(), ch.server_id, before);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the full order of one category (null = uncategorised). Every channel currently in that
|
||||
* category must be listed; channels from other categories in the list are moved into it.
|
||||
*/
|
||||
reorderChannels(
|
||||
userId: string,
|
||||
serverId: string,
|
||||
categoryId: string | null,
|
||||
ids: string[],
|
||||
): PositionUpdate[] {
|
||||
this.manage(userId, serverId);
|
||||
if (categoryId) this.requireCategoryInServer(categoryId, serverId);
|
||||
const rows = this.db
|
||||
.prepare('SELECT id, category_id FROM channels WHERE server_id = ? ORDER BY position, id')
|
||||
.all(serverId) as {
|
||||
id: string;
|
||||
category_id: string | null;
|
||||
}[];
|
||||
// D62: a channel the mover can't VIEW counts as unknown (same 400 as a missing id). Hidden
|
||||
// channels already in the category keep their exact position slots; the listed (visible)
|
||||
// channels fill the remaining slots, with any extras appended at the end. The response never
|
||||
// echoes a hidden id.
|
||||
const visible = Access.for(this.db).visibleChannelIds(userId, serverId);
|
||||
const inServer = new Set(rows.filter((r) => visible.has(r.id)).map((r) => r.id));
|
||||
if (!ids.every((id) => inServer.has(id)))
|
||||
throw badRequest('Unknown channel id for this server');
|
||||
const inCategory = rows.filter((r) => r.category_id === categoryId).map((r) => r.id);
|
||||
const current = inCategory.filter((id) => visible.has(id));
|
||||
if (!current.every((id) => ids.includes(id))) {
|
||||
throw badRequest('ids must include every channel already in that category');
|
||||
}
|
||||
const slots: (string | null)[] = inCategory.map((id) => (visible.has(id) ? null : id));
|
||||
let open = slots.filter((id) => id === null).length;
|
||||
while (open < ids.length) {
|
||||
slots.push(null);
|
||||
open++;
|
||||
}
|
||||
let i = 0;
|
||||
const positions = slots.map((id, position) => ({
|
||||
id: id ?? ids[i++]!,
|
||||
position,
|
||||
categoryId,
|
||||
}));
|
||||
const update = this.db.prepare(
|
||||
'UPDATE channels SET position = ?, category_id = ? WHERE id = ?',
|
||||
);
|
||||
const before = snapshot(this.db, serverId);
|
||||
this.db.transaction(() => positions.forEach((p) => update.run(p.position, categoryId, p.id)))();
|
||||
const after = emitPositionChanges(this.db, this.hub(), serverId, before);
|
||||
// D63: the mover's own dense numbers for that category; never a hidden id (D45).
|
||||
const mine = after.get(userId) ?? new Map();
|
||||
return [...mine]
|
||||
.filter(([, p]) => p.categoryId === categoryId)
|
||||
.map(([id, p]) => ({ id, position: p.position, categoryId }));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,617 @@
|
||||
import {
|
||||
GROUP_ADDS_PER_WINDOW,
|
||||
GROUP_ADDS_WINDOW_MS,
|
||||
GROUP_CREATES_PER_HOUR,
|
||||
GROUP_MAX_MEMBERS,
|
||||
type DmCandidateDto,
|
||||
type DmDto,
|
||||
type UserSummaryDto,
|
||||
} from '@chat/shared';
|
||||
import {
|
||||
dmMemberIds,
|
||||
dmPartner,
|
||||
isDmMember,
|
||||
requireDmAccess,
|
||||
sharesServer,
|
||||
canPostInDm,
|
||||
cantAdd,
|
||||
cantSend,
|
||||
type DmChannelRow,
|
||||
} from '../auth/permissions.js';
|
||||
import type { DB } from '../db/index.js';
|
||||
import { badRequest, forbidden, HttpError, notFound } from '../lib/errors.js';
|
||||
import { Blocks } from '../auth/blocks.js';
|
||||
import { newId, nowIso } from '../lib/ids.js';
|
||||
import { RateWindow } from '../lib/rate-window.js';
|
||||
import type { RealtimeHub } from '../realtime/hub.js';
|
||||
import type { MediaService } from './media.js';
|
||||
import type { MessageService } from './messages.js';
|
||||
import type { UploadService } from './uploads.js';
|
||||
|
||||
interface DmRow extends DmChannelRow {
|
||||
created_at: string;
|
||||
created_by: string | null;
|
||||
last_message_id: string | null;
|
||||
}
|
||||
interface UserRow {
|
||||
id: string;
|
||||
username: string;
|
||||
display_name: string;
|
||||
avatar_media: string | null;
|
||||
}
|
||||
|
||||
const summary = (u: UserRow): UserSummaryDto => ({
|
||||
id: u.id,
|
||||
username: u.username,
|
||||
displayName: u.display_name,
|
||||
avatar: u.avatar_media,
|
||||
});
|
||||
|
||||
const LAST_MESSAGE = `(SELECT MAX(id) FROM messages m WHERE m.dm_channel_id = d.id AND m.deleted_at IS NULL)`;
|
||||
|
||||
const notShared = () => notFound('User not found, or you don’t share a server with them');
|
||||
const groupFull = () =>
|
||||
new HttpError(409, 'group_full', `A group can have at most ${GROUP_MAX_MEMBERS} people`);
|
||||
const tooManyAdds = () =>
|
||||
new HttpError(
|
||||
429,
|
||||
'too_many_adds',
|
||||
`You can add at most ${GROUP_ADDS_PER_WINDOW} people to groups every ${GROUP_ADDS_WINDOW_MS / 60_000} minutes`,
|
||||
);
|
||||
const tooManyGroups = () =>
|
||||
new HttpError(
|
||||
429,
|
||||
'too_many_groups',
|
||||
`You can create at most ${GROUP_CREATES_PER_HOUR} groups an hour`,
|
||||
);
|
||||
const notAGroup = () => badRequest('That only works in a group DM');
|
||||
|
||||
/** What happened to someone who is no longer in a group (dm_departures). */
|
||||
interface Departure {
|
||||
user_id: string;
|
||||
removed_by: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 1:1 DMs (PLAN story 4) and group DMs (0.2 item 3, DESIGN-0.2 sections 3 and 6).
|
||||
*
|
||||
* - Access to both kinds goes through dm_members only.
|
||||
* - 1:1: two users who share a server (non-banned members of one) can open a DM; posting needs
|
||||
* that to stay true, the history stays readable to the two.
|
||||
* - Groups: up to GROUP_MAX_MEMBERS people (checked inside the insert transaction). Any member can
|
||||
* add people they share a server with, rename it and change the icon; the owner removes members
|
||||
* and transfers ownership; anyone can leave. Leaving or removal takes away all access (404). If
|
||||
* the owner leaves, the longest-standing member becomes owner; when the last member leaves the
|
||||
* group, its messages and media are deleted. A leaver can't be re-added by anyone; someone the
|
||||
* owner removed can be re-added by the owner only. Adds: 20 people per user per 10 minutes
|
||||
* (creating counts), creating: 10 groups per user per hour.
|
||||
* - Group events (dm:update, dm:remove, system messages) go to current members' user rooms,
|
||||
* looked up when sent, so someone who's gone gets nothing more.
|
||||
*/
|
||||
export class DmService {
|
||||
readonly adds = new RateWindow(GROUP_ADDS_PER_WINDOW, GROUP_ADDS_WINDOW_MS);
|
||||
readonly creates = new RateWindow(GROUP_CREATES_PER_HOUR, 3_600_000);
|
||||
|
||||
/** Set by the app (M10): someone left or was removed, so drop them from the group's call. */
|
||||
onMemberGone: ((dmId: string, userId: string) => void) | null = null;
|
||||
|
||||
constructor(
|
||||
private readonly db: DB,
|
||||
private readonly hub: () => RealtimeHub,
|
||||
private readonly messages: MessageService,
|
||||
private readonly media: MediaService,
|
||||
private readonly uploads: UploadService,
|
||||
) {}
|
||||
|
||||
private user(id: string): UserRow | undefined {
|
||||
return this.db
|
||||
.prepare('SELECT id, username, display_name, avatar_media FROM users WHERE id = ?')
|
||||
.get(id) as UserRow | undefined;
|
||||
}
|
||||
|
||||
private members(dmId: string): UserSummaryDto[] {
|
||||
return (
|
||||
this.db
|
||||
.prepare(
|
||||
`SELECT u.id, u.username, u.display_name, u.avatar_media
|
||||
FROM dm_members dm JOIN users u ON u.id = dm.user_id
|
||||
WHERE dm.dm_channel_id = ? ORDER BY dm.joined_at, dm.rowid`,
|
||||
)
|
||||
.all(dmId) as UserRow[]
|
||||
).map(summary);
|
||||
}
|
||||
|
||||
private toDto(row: DmRow, viewerId: string): DmDto {
|
||||
const members = this.members(row.id);
|
||||
if (row.kind === 'group') {
|
||||
return {
|
||||
id: row.id,
|
||||
kind: 'group',
|
||||
user: null,
|
||||
members,
|
||||
name: row.name,
|
||||
icon: row.icon_media,
|
||||
ownerId: row.owner_id,
|
||||
lastMessageId: row.last_message_id,
|
||||
canMessage: true,
|
||||
createdAt: row.created_at,
|
||||
};
|
||||
}
|
||||
const otherId = dmPartner(row, viewerId);
|
||||
return {
|
||||
id: row.id,
|
||||
kind: 'dm',
|
||||
user: summary(this.user(otherId) as UserRow),
|
||||
members,
|
||||
name: null,
|
||||
icon: null,
|
||||
ownerId: null,
|
||||
lastMessageId: row.last_message_id,
|
||||
// Closed (no shared server) or blocked either way (M18): read-only for both.
|
||||
canMessage: canPostInDm(this.db, viewerId, row),
|
||||
createdAt: row.created_at,
|
||||
};
|
||||
}
|
||||
|
||||
private byId(id: string): DmRow {
|
||||
return this.db
|
||||
.prepare(`SELECT d.*, ${LAST_MESSAGE} AS last_message_id FROM dm_channels d WHERE d.id = ?`)
|
||||
.get(id) as DmRow;
|
||||
}
|
||||
|
||||
/** A group the user is in: 404 if not a member (or no such id), 400 for a 1:1 DM. */
|
||||
private requireGroup(userId: string, dmId: string): DmChannelRow {
|
||||
const dm = requireDmAccess(this.db, userId, dmId);
|
||||
if (dm.kind !== 'group') throw notAGroup();
|
||||
return dm;
|
||||
}
|
||||
|
||||
private departure(dmId: string, userId: string): Departure | undefined {
|
||||
return this.db
|
||||
.prepare(
|
||||
'SELECT user_id, removed_by FROM dm_departures WHERE dm_channel_id = ? AND user_id = ?',
|
||||
)
|
||||
.get(dmId, userId) as Departure | undefined;
|
||||
}
|
||||
|
||||
/** Tell every current member about the group's new state. */
|
||||
private broadcast(dmId: string): DmDto {
|
||||
const dto = this.toDto(this.byId(dmId), '');
|
||||
for (const id of dmMemberIds(this.db, dmId)) this.hub().toUser(id, 'dm:update', { dm: dto });
|
||||
return dto;
|
||||
}
|
||||
|
||||
/**
|
||||
* Open (or get) the DM with `otherId`. A new one needs a shared server; unknown users and users
|
||||
* you share nothing with both get the same 404, so ids can't be probed.
|
||||
*/
|
||||
open(userId: string, otherId: string): { dm: DmDto; created: boolean } {
|
||||
if (otherId === userId) throw badRequest("You can't message yourself");
|
||||
const [a, b] = userId < otherId ? [userId, otherId] : [otherId, userId];
|
||||
const find = this.db.prepare(
|
||||
"SELECT id FROM dm_channels WHERE kind = 'dm' AND user_a = ? AND user_b = ?",
|
||||
);
|
||||
const existing = find.get(a, b) as { id: string } | undefined;
|
||||
if (existing) return { dm: this.toDto(this.byId(existing.id), userId), created: false };
|
||||
if (!this.user(otherId) || !sharesServer(this.db, userId, otherId)) throw notShared();
|
||||
// M18 (D4, D5): no new DM if either blocked the other; the same refusal as sending (D16).
|
||||
if (Blocks.for(this.db).between(userId, otherId)) throw cantSend();
|
||||
const id = newId();
|
||||
const now = nowIso();
|
||||
// INSERT OR IGNORE + re-read: two simultaneous opens end up with the same row.
|
||||
const row = this.db.transaction(() => {
|
||||
this.db
|
||||
.prepare(
|
||||
`INSERT OR IGNORE INTO dm_channels (id, kind, user_a, user_b, created_at, created_by)
|
||||
VALUES (?, 'dm', ?, ?, ?, ?)`,
|
||||
)
|
||||
.run(id, a, b, now, userId);
|
||||
const r = find.get(a, b) as { id: string };
|
||||
const member = this.db.prepare(
|
||||
'INSERT OR IGNORE INTO dm_members (dm_channel_id, user_id, joined_at) VALUES (?, ?, ?)',
|
||||
);
|
||||
member.run(r.id, a, now);
|
||||
member.run(r.id, b, now);
|
||||
return r;
|
||||
})();
|
||||
return { dm: this.toDto(this.byId(row.id), userId), created: row.id === id };
|
||||
}
|
||||
|
||||
get(userId: string, dmId: string): DmDto {
|
||||
requireDmAccess(this.db, userId, dmId);
|
||||
return this.toDto(this.byId(dmId), userId);
|
||||
}
|
||||
|
||||
/**
|
||||
* The user's DMs and groups, newest activity first. A 1:1 DM someone else opened but never wrote
|
||||
* in stays hidden until it has a message, so opening a DM doesn't show up for the other person.
|
||||
* Groups always show (being added is the point).
|
||||
*/
|
||||
list(userId: string): DmDto[] {
|
||||
const rows = this.db
|
||||
.prepare(
|
||||
`SELECT * FROM (
|
||||
SELECT d.*, ${LAST_MESSAGE} AS last_message_id
|
||||
FROM dm_members dm JOIN dm_channels d ON d.id = dm.dm_channel_id
|
||||
WHERE dm.user_id = ?)
|
||||
WHERE kind = 'group' OR last_message_id IS NOT NULL OR created_by = ?
|
||||
ORDER BY COALESCE(last_message_id, id) DESC`,
|
||||
)
|
||||
.all(userId, userId) as DmRow[];
|
||||
return rows.map((r) => this.toDto(r, userId));
|
||||
}
|
||||
|
||||
/**
|
||||
* People the user may start a DM with or add to a group (shares a server), optionally filtered
|
||||
* by name. With `dmId` (a group the user is in), each is marked member / left / removed.
|
||||
*/
|
||||
candidates(userId: string, q = '', dmId?: string): DmCandidateDto[] {
|
||||
const dm = dmId ? this.requireGroup(userId, dmId) : null;
|
||||
const like = `%${q
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/[\\%_]/g, (c) => `\\${c}`)}%`;
|
||||
const rows = this.db
|
||||
.prepare(
|
||||
`SELECT DISTINCT u.id, u.username, u.display_name, u.avatar_media
|
||||
FROM members me
|
||||
JOIN members other ON other.server_id = me.server_id AND other.banned = 0
|
||||
JOIN users u ON u.id = other.user_id
|
||||
WHERE me.user_id = ? AND me.banned = 0 AND u.id <> ?
|
||||
AND (lower(u.username) LIKE ? ESCAPE '\\' OR lower(u.display_name) LIKE ? ESCAPE '\\')
|
||||
ORDER BY lower(u.display_name), u.id
|
||||
LIMIT 50`,
|
||||
)
|
||||
.all(userId, userId, like, like) as UserRow[];
|
||||
return rows.map((u) => {
|
||||
if (!dm) return { ...summary(u), groupState: null, canAdd: true };
|
||||
if (isDmMember(this.db, u.id, dm.id)) {
|
||||
return { ...summary(u), groupState: 'member', canAdd: false };
|
||||
}
|
||||
const d = this.departure(dm.id, u.id);
|
||||
if (!d) return { ...summary(u), groupState: null, canAdd: true };
|
||||
if (!d.removed_by) return { ...summary(u), groupState: 'left', canAdd: false };
|
||||
return { ...summary(u), groupState: 'removed', canAdd: dm.owner_id === userId };
|
||||
});
|
||||
}
|
||||
|
||||
/** Everyone the user shares a DM or group with (presence audience). */
|
||||
partnersOf(userId: string): string[] {
|
||||
return (
|
||||
this.db
|
||||
.prepare(
|
||||
`SELECT DISTINCT other.user_id AS other
|
||||
FROM dm_members me JOIN dm_members other ON other.dm_channel_id = me.dm_channel_id
|
||||
WHERE me.user_id = ? AND other.user_id <> me.user_id`,
|
||||
)
|
||||
.all(userId) as { other: string }[]
|
||||
).map((r) => r.other);
|
||||
}
|
||||
|
||||
// ---- groups ----
|
||||
|
||||
/** Everyone in `userIds` must exist and share a server with the adder (same 404 otherwise). */
|
||||
private checkAddable(userId: string, userIds: readonly string[]): void {
|
||||
for (const id of userIds) {
|
||||
if (id === userId) throw badRequest("You're already in this conversation");
|
||||
if (!this.user(id) || !sharesServer(this.db, userId, id)) throw notShared();
|
||||
}
|
||||
// M18: the adder and anyone being added, blocked either way -> neutral "Couldn't add" (D5).
|
||||
// Checked after the 404s above, so it says nothing about strangers.
|
||||
const blocks = Blocks.for(this.db);
|
||||
if (userIds.some((id) => blocks.between(userId, id))) throw cantAdd();
|
||||
}
|
||||
|
||||
private checkAddRate(userId: string, n: number): void {
|
||||
if (!this.adds.allows(userId, n)) throw tooManyAdds();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a group with the creator plus `userIds` (owner = creator). Counts towards both the
|
||||
* creation limit and the add limit.
|
||||
*/
|
||||
createGroup(userId: string, userIds: readonly string[], name: string | null = null): DmDto {
|
||||
if (new Set(userIds).size !== userIds.length) {
|
||||
throw badRequest('Each person can only be added once');
|
||||
}
|
||||
if (userIds.length + 1 > GROUP_MAX_MEMBERS) throw groupFull();
|
||||
this.checkAddable(userId, userIds);
|
||||
if (!this.creates.allows(userId)) throw tooManyGroups();
|
||||
this.checkAddRate(userId, userIds.length);
|
||||
const id = newId();
|
||||
const now = nowIso();
|
||||
this.db
|
||||
.transaction(() => {
|
||||
this.db
|
||||
.prepare(
|
||||
`INSERT INTO dm_channels (id, kind, name, owner_id, created_by, created_at)
|
||||
VALUES (?, 'group', ?, ?, ?, ?)`,
|
||||
)
|
||||
.run(id, name, userId, userId, now);
|
||||
const member = this.db.prepare(
|
||||
'INSERT INTO dm_members (dm_channel_id, user_id, joined_at) VALUES (?, ?, ?)',
|
||||
);
|
||||
// Same timestamp; rowid keeps the creator first in "longest-standing" order.
|
||||
for (const u of [userId, ...userIds]) member.run(id, u, now);
|
||||
})
|
||||
.immediate();
|
||||
this.creates.record(userId);
|
||||
this.adds.record(userId, userIds.length);
|
||||
return this.broadcast(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add people. On a 1:1 DM this creates a NEW group with both people plus the new ones (the 1:1
|
||||
* and its history stay private and untouched). Returns the group and whether it's new.
|
||||
*/
|
||||
addMembers(
|
||||
userId: string,
|
||||
dmId: string,
|
||||
userIds: readonly string[],
|
||||
): { dm: DmDto; created: boolean } {
|
||||
const dm = requireDmAccess(this.db, userId, dmId);
|
||||
if (new Set(userIds).size !== userIds.length) {
|
||||
throw badRequest('Each person can only be added once');
|
||||
}
|
||||
if (dm.kind === 'dm') {
|
||||
const partner = dmPartner(dm, userId);
|
||||
if (userIds.includes(partner)) throw badRequest(`They're already in this conversation`);
|
||||
return { dm: this.createGroup(userId, [partner, ...userIds]), created: true };
|
||||
}
|
||||
for (const id of userIds) {
|
||||
if (id === userId || isDmMember(this.db, id, dm.id)) {
|
||||
throw badRequest(`${id === userId ? "You're" : "They're"} already in this group`);
|
||||
}
|
||||
}
|
||||
for (const id of userIds) {
|
||||
const d = this.departure(dm.id, id);
|
||||
if (d && !d.removed_by) {
|
||||
throw new HttpError(
|
||||
403,
|
||||
'cannot_readd_left_member',
|
||||
'Someone who left this group can’t be added back. Start a new group instead.',
|
||||
);
|
||||
}
|
||||
if (d && dm.owner_id !== userId) {
|
||||
throw new HttpError(
|
||||
403,
|
||||
'cannot_readd_removed_member',
|
||||
'Only the group owner can add back someone they removed',
|
||||
);
|
||||
}
|
||||
}
|
||||
this.checkAddable(userId, userIds);
|
||||
this.checkAddRate(userId, userIds.length);
|
||||
const now = nowIso();
|
||||
const messageId = this.db
|
||||
.transaction(() => {
|
||||
// Re-checked under the write lock: concurrent adds can't pass the cap, nor add twice.
|
||||
if (!isDmMember(this.db, userId, dm.id)) throw notFound('Conversation not found');
|
||||
const count = (
|
||||
this.db
|
||||
.prepare('SELECT COUNT(*) AS n FROM dm_members WHERE dm_channel_id = ?')
|
||||
.get(dm.id) as { n: number }
|
||||
).n;
|
||||
if (count + userIds.length > GROUP_MAX_MEMBERS) throw groupFull();
|
||||
const insert = this.db.prepare(
|
||||
'INSERT OR IGNORE INTO dm_members (dm_channel_id, user_id, joined_at) VALUES (?, ?, ?)',
|
||||
);
|
||||
for (const id of userIds) {
|
||||
if (insert.run(dm.id, id, now).changes === 0) {
|
||||
throw badRequest("They're already in this group");
|
||||
}
|
||||
}
|
||||
this.db
|
||||
.prepare(
|
||||
`DELETE FROM dm_departures WHERE dm_channel_id = ? AND user_id IN (${userIds.map(() => '?').join(',')})`,
|
||||
)
|
||||
.run(dm.id, ...userIds);
|
||||
return this.messages.insertSystem(dm.id, userId, {
|
||||
event: 'member_add',
|
||||
targets: [...userIds],
|
||||
});
|
||||
})
|
||||
.immediate();
|
||||
this.adds.record(userId, userIds.length);
|
||||
const dto = this.broadcast(dm.id);
|
||||
this.messages.announce(dm.id, [messageId]);
|
||||
return { dm: dto, created: false };
|
||||
}
|
||||
|
||||
/** Remove someone (owner only) or, for yourself, leave. */
|
||||
removeMember(userId: string, dmId: string, targetId: string): void {
|
||||
if (targetId === userId) return this.leave(userId, dmId);
|
||||
const dm = this.requireGroup(userId, dmId);
|
||||
if (dm.owner_id !== userId) throw forbidden('Only the group owner can remove people');
|
||||
if (!isDmMember(this.db, targetId, dm.id)) throw notFound('Member not found');
|
||||
const messageId = this.db
|
||||
.transaction(() => {
|
||||
this.db
|
||||
.prepare('DELETE FROM dm_members WHERE dm_channel_id = ? AND user_id = ?')
|
||||
.run(dm.id, targetId);
|
||||
this.db
|
||||
.prepare(
|
||||
`INSERT OR REPLACE INTO dm_departures (dm_channel_id, user_id, left_at, removed_by)
|
||||
VALUES (?, ?, ?, ?)`,
|
||||
)
|
||||
.run(dm.id, targetId, nowIso(), userId);
|
||||
return this.messages.insertSystem(dm.id, userId, {
|
||||
event: 'member_remove',
|
||||
targets: [targetId],
|
||||
});
|
||||
})
|
||||
.immediate();
|
||||
this.hub().toUser(targetId, 'dm:remove', { dmId: dm.id, reason: 'remove' });
|
||||
this.onMemberGone?.(dm.id, targetId);
|
||||
this.broadcast(dm.id);
|
||||
this.messages.announce(dm.id, [messageId]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Leave a group. The owner leaving hands the group to the longest-standing member (system
|
||||
* message); the last member leaving deletes the group, its messages, files and icon.
|
||||
*/
|
||||
leave(userId: string, dmId: string): void {
|
||||
const dm = this.requireGroup(userId, dmId);
|
||||
const result = this.db
|
||||
.transaction(() => {
|
||||
const row = this.db
|
||||
.prepare('SELECT owner_id, icon_media FROM dm_channels WHERE id = ?')
|
||||
.get(dm.id) as { owner_id: string | null; icon_media: string | null };
|
||||
this.db
|
||||
.prepare('DELETE FROM dm_members WHERE dm_channel_id = ? AND user_id = ?')
|
||||
.run(dm.id, userId);
|
||||
const next = dmMemberIds(this.db, dm.id)[0];
|
||||
if (!next) {
|
||||
const files = (
|
||||
this.db
|
||||
.prepare(
|
||||
`SELECT a.path FROM attachments a JOIN messages m ON m.id = a.message_id
|
||||
WHERE m.dm_channel_id = ?`,
|
||||
)
|
||||
.all(dm.id) as { path: string }[]
|
||||
).map((r) => r.path);
|
||||
// read_states.channel_id has no FK (it also holds server channel ids).
|
||||
this.db.prepare('DELETE FROM read_states WHERE channel_id = ?').run(dm.id);
|
||||
this.db.prepare('DELETE FROM dm_channels WHERE id = ?').run(dm.id);
|
||||
return { deleted: true as const, files, icon: row.icon_media, messageIds: [] };
|
||||
}
|
||||
this.db
|
||||
.prepare(
|
||||
`INSERT OR REPLACE INTO dm_departures (dm_channel_id, user_id, left_at, removed_by)
|
||||
VALUES (?, ?, ?, NULL)`,
|
||||
)
|
||||
.run(dm.id, userId, nowIso());
|
||||
const messageIds = [
|
||||
this.messages.insertSystem(dm.id, userId, { event: 'member_leave', targets: [] }),
|
||||
];
|
||||
if (row.owner_id === userId || row.owner_id === null) {
|
||||
this.db.prepare('UPDATE dm_channels SET owner_id = ? WHERE id = ?').run(next, dm.id);
|
||||
messageIds.push(
|
||||
this.messages.insertSystem(dm.id, userId, {
|
||||
event: 'owner_change',
|
||||
targets: [next],
|
||||
reason: 'owner_left',
|
||||
}),
|
||||
);
|
||||
}
|
||||
return { deleted: false as const, files: [], icon: null, messageIds };
|
||||
})
|
||||
.immediate();
|
||||
// The leaver's other tabs drop the group too.
|
||||
this.hub().toUser(userId, 'dm:remove', { dmId: dm.id, reason: 'leave' });
|
||||
this.onMemberGone?.(dm.id, userId);
|
||||
if (result.deleted) {
|
||||
for (const f of result.files) this.uploads.removeFile(f);
|
||||
this.media.remove(result.icon);
|
||||
return;
|
||||
}
|
||||
this.broadcast(dm.id);
|
||||
this.messages.announce(dm.id, result.messageIds);
|
||||
}
|
||||
|
||||
/** Rename (any member; null clears) and/or transfer ownership (owner only). */
|
||||
update(userId: string, dmId: string, input: { name?: string | null; ownerId?: string }): DmDto {
|
||||
const dm = this.requireGroup(userId, dmId);
|
||||
if (input.ownerId !== undefined) {
|
||||
if (dm.owner_id !== userId) throw forbidden('Only the group owner can transfer ownership');
|
||||
if (input.ownerId === userId) throw badRequest('You already own this group');
|
||||
if (!isDmMember(this.db, input.ownerId, dm.id)) {
|
||||
throw badRequest('The new owner must be in the group');
|
||||
}
|
||||
}
|
||||
const messageIds = this.db
|
||||
.transaction(() => {
|
||||
const ids: string[] = [];
|
||||
if (!isDmMember(this.db, userId, dm.id)) throw notFound('Conversation not found');
|
||||
const cur = this.byId(dm.id);
|
||||
if (input.name !== undefined && input.name !== cur.name) {
|
||||
this.db.prepare('UPDATE dm_channels SET name = ? WHERE id = ?').run(input.name, dm.id);
|
||||
ids.push(
|
||||
this.messages.insertSystem(dm.id, userId, {
|
||||
event: 'rename',
|
||||
targets: [],
|
||||
name: input.name,
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (input.ownerId !== undefined) {
|
||||
if (cur.owner_id !== userId)
|
||||
throw forbidden('Only the group owner can transfer ownership');
|
||||
this.db
|
||||
.prepare('UPDATE dm_channels SET owner_id = ? WHERE id = ?')
|
||||
.run(input.ownerId, dm.id);
|
||||
ids.push(
|
||||
this.messages.insertSystem(dm.id, userId, {
|
||||
event: 'owner_change',
|
||||
targets: [input.ownerId],
|
||||
reason: 'transfer',
|
||||
}),
|
||||
);
|
||||
}
|
||||
return ids;
|
||||
})
|
||||
.immediate();
|
||||
if (!messageIds.length) return this.toDto(this.byId(dm.id), userId);
|
||||
const dto = this.broadcast(dm.id);
|
||||
this.messages.announce(dm.id, messageIds);
|
||||
return dto;
|
||||
}
|
||||
|
||||
/** Before reading an icon upload's body: must be a member of a group (404 / 400 otherwise). */
|
||||
requireIconAccess(userId: string, dmId: string): void {
|
||||
this.requireGroup(userId, dmId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Point the group at a new icon (or none). Run inside a transaction (MediaService.replace runs
|
||||
* the swap in one). The new media id is scoped to the group in the same transaction, before
|
||||
* anyone can learn it, so /api/media only ever serves it to current members. Returns the
|
||||
* previous id (for the caller to delete after commit) and the system message to announce.
|
||||
*/
|
||||
setIcon(
|
||||
userId: string,
|
||||
dmId: string,
|
||||
mediaId: string | null,
|
||||
): { previous: string | null; messageId: string | null } {
|
||||
const dm = this.requireGroup(userId, dmId);
|
||||
const previous = (
|
||||
this.db.prepare('SELECT icon_media FROM dm_channels WHERE id = ?').get(dm.id) as {
|
||||
icon_media: string | null;
|
||||
}
|
||||
).icon_media;
|
||||
if (previous === null && mediaId === null) return { previous, messageId: null };
|
||||
if (mediaId) {
|
||||
this.db
|
||||
.prepare('INSERT INTO media_scopes (media_id, dm_channel_id) VALUES (?, ?)')
|
||||
.run(mediaId, dm.id);
|
||||
}
|
||||
if (previous) this.db.prepare('DELETE FROM media_scopes WHERE media_id = ?').run(previous);
|
||||
this.db.prepare('UPDATE dm_channels SET icon_media = ? WHERE id = ?').run(mediaId, dm.id);
|
||||
const messageId = this.messages.insertSystem(dm.id, userId, {
|
||||
event: 'icon',
|
||||
targets: [],
|
||||
...(mediaId ? {} : { removed: true }),
|
||||
});
|
||||
return { previous, messageId };
|
||||
}
|
||||
|
||||
/** After an icon change committed: tell the members and post the system message. */
|
||||
iconChanged(userId: string, dmId: string, messageId: string | null): DmDto {
|
||||
if (!messageId) return this.get(userId, dmId);
|
||||
const dto = this.broadcast(dmId);
|
||||
this.messages.announce(dmId, [messageId]);
|
||||
return dto;
|
||||
}
|
||||
|
||||
/** The group a scoped media id belongs to, or null for unscoped (public-by-key) media. */
|
||||
mediaScope(mediaId: string): string | null {
|
||||
return (
|
||||
(
|
||||
this.db
|
||||
.prepare('SELECT dm_channel_id FROM media_scopes WHERE media_id = ?')
|
||||
.get(mediaId) as { dm_channel_id: string } | undefined
|
||||
)?.dm_channel_id ?? null
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
import {
|
||||
Perm,
|
||||
EMOJI_LIMIT_MESSAGE,
|
||||
EMOJI_UPLOADS_PER_MINUTE,
|
||||
MAX_SERVER_EMOJI,
|
||||
customReaction,
|
||||
isValidEmojiName,
|
||||
type CustomEmojiDto,
|
||||
} from '@chat/shared';
|
||||
import { Access } from '../auth/access.js';
|
||||
import { requireServerRole } from '../auth/permissions.js';
|
||||
import type { DB } from '../db/index.js';
|
||||
import { HttpError, forbidden, notFound } from '../lib/errors.js';
|
||||
import { newId, nowIso } from '../lib/ids.js';
|
||||
import { RateWindow } from '../lib/rate-window.js';
|
||||
import type { RealtimeHub } from '../realtime/hub.js';
|
||||
import type { MessageService } from './messages.js';
|
||||
|
||||
interface EmojiRow {
|
||||
id: string;
|
||||
server_id: string;
|
||||
name: string;
|
||||
media_id: string;
|
||||
animated: number;
|
||||
created_by: string | null;
|
||||
created_at: string;
|
||||
u_username: string | null;
|
||||
u_display_name: string | null;
|
||||
u_avatar: string | null;
|
||||
}
|
||||
|
||||
const SELECT = `SELECT e.*, u.username AS u_username, u.display_name AS u_display_name,
|
||||
u.avatar_media AS u_avatar FROM custom_emoji e LEFT JOIN users u ON u.id = e.created_by`;
|
||||
|
||||
const toDto = (r: EmojiRow): CustomEmojiDto => ({
|
||||
id: r.id,
|
||||
serverId: r.server_id,
|
||||
name: r.name,
|
||||
mediaId: r.media_id,
|
||||
animated: r.animated === 1,
|
||||
createdBy:
|
||||
r.created_by && r.u_username
|
||||
? {
|
||||
id: r.created_by,
|
||||
username: r.u_username,
|
||||
displayName: r.u_display_name ?? r.u_username,
|
||||
avatar: r.u_avatar,
|
||||
}
|
||||
: null,
|
||||
createdAt: r.created_at,
|
||||
});
|
||||
|
||||
export const emojiLimit = () => new HttpError(409, 'emoji_limit', EMOJI_LIMIT_MESSAGE);
|
||||
const nameTaken = (name: string) =>
|
||||
new HttpError(409, 'emoji_name_taken', `This server already has an emoji called :${name}:`);
|
||||
const badName = () =>
|
||||
new HttpError(400, 'bad_emoji_name', 'Emoji names are 2 to 32 letters, numbers or underscores');
|
||||
const isUnique = (e: unknown) =>
|
||||
(e as { code?: string }).code === 'SQLITE_CONSTRAINT_UNIQUE' ||
|
||||
/UNIQUE constraint failed: custom_emoji/.test(String((e as Error).message));
|
||||
|
||||
/**
|
||||
* Custom server emoji (M24, D27). Any non-banned member can add, up to MAX_SERVER_EMOJI per
|
||||
* server (checked in the insert transaction); the uploader, the owner or an admin can rename or
|
||||
* delete. Outsiders, banned and kicked users get 404 for everything, like the server itself.
|
||||
*/
|
||||
export class EmojiService {
|
||||
constructor(
|
||||
private readonly db: DB,
|
||||
private readonly hub: () => RealtimeHub,
|
||||
private readonly messages: MessageService,
|
||||
/** D27: 10 uploads a minute per user; null when RATE_LIMIT=false. */
|
||||
public limit: RateWindow | null = new RateWindow(EMOJI_UPLOADS_PER_MINUTE, 60_000),
|
||||
) {}
|
||||
|
||||
private row(emojiId: string): EmojiRow | undefined {
|
||||
return this.db.prepare(`${SELECT} WHERE e.id = ?`).get(emojiId) as EmojiRow | undefined;
|
||||
}
|
||||
|
||||
get(emojiId: string): CustomEmojiDto | null {
|
||||
const r = this.row(emojiId);
|
||||
return r ? toDto(r) : null;
|
||||
}
|
||||
|
||||
/** Any member (404 otherwise). Oldest first. */
|
||||
list(userId: string, serverId: string): CustomEmojiDto[] {
|
||||
requireServerRole(this.db, userId, serverId);
|
||||
return (
|
||||
this.db
|
||||
.prepare(`${SELECT} WHERE e.server_id = ? ORDER BY e.created_at, e.id`)
|
||||
.all(serverId) as EmojiRow[]
|
||||
).map(toDto);
|
||||
}
|
||||
|
||||
private count(serverId: string): number {
|
||||
return (
|
||||
this.db
|
||||
.prepare('SELECT COUNT(*) AS n FROM custom_emoji WHERE server_id = ?')
|
||||
.get(serverId) as {
|
||||
n: number;
|
||||
}
|
||||
).n;
|
||||
}
|
||||
|
||||
private nameInUse(serverId: string, name: string, exceptId: string | null = null): boolean {
|
||||
return !!this.db
|
||||
.prepare('SELECT 1 FROM custom_emoji WHERE server_id = ? AND name = ? AND id IS NOT ?')
|
||||
.get(serverId, name, exceptId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Before the upload body is read: membership (404), the per-user rate limit (429 with
|
||||
* Retry-After) and, as a cheap early answer, the cap. Every attempt that gets this far counts.
|
||||
*/
|
||||
beginUpload(userId: string, serverId: string): void {
|
||||
Access.for(this.db).requireServerPerm(userId, serverId, Perm.CREATE_EMOJI);
|
||||
if (this.limit) {
|
||||
if (!this.limit.allows(userId)) {
|
||||
throw new HttpError(
|
||||
429,
|
||||
'too_many_emoji_uploads',
|
||||
`You can add at most ${EMOJI_UPLOADS_PER_MINUTE} emoji a minute`,
|
||||
undefined,
|
||||
{ 'retry-after': String(this.limit.retryAfterSec(userId)) },
|
||||
);
|
||||
}
|
||||
this.limit.record(userId);
|
||||
}
|
||||
if (this.count(serverId) >= MAX_SERVER_EMOJI) throw emojiLimit();
|
||||
}
|
||||
|
||||
/** Name checks that can run before the image is processed (400 / 409). */
|
||||
checkName(serverId: string, name: string | undefined): string {
|
||||
if (name === undefined || !isValidEmojiName(name)) throw badName();
|
||||
if (this.nameInUse(serverId, name)) throw nameTaken(name);
|
||||
return name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Insert, re-checking membership, the cap and the name in one transaction (better-sqlite3 runs
|
||||
* it synchronously, so two uploads at once can't both be the 50th). The caller removes the media
|
||||
* if this throws.
|
||||
*/
|
||||
create(
|
||||
userId: string,
|
||||
serverId: string,
|
||||
name: string,
|
||||
mediaId: string,
|
||||
animated: boolean,
|
||||
): CustomEmojiDto {
|
||||
const id = newId();
|
||||
this.db
|
||||
.transaction(() => {
|
||||
// D38: CREATE_EMOJI, re-checked in the write transaction (D59).
|
||||
Access.for(this.db).requireServerPerm(userId, serverId, Perm.CREATE_EMOJI);
|
||||
if (!isValidEmojiName(name)) throw badName();
|
||||
if (this.count(serverId) >= MAX_SERVER_EMOJI) throw emojiLimit();
|
||||
if (this.nameInUse(serverId, name)) throw nameTaken(name);
|
||||
try {
|
||||
this.db
|
||||
.prepare(
|
||||
`INSERT INTO custom_emoji (id, server_id, name, media_id, animated, created_by, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
||||
)
|
||||
.run(id, serverId, name, mediaId, animated ? 1 : 0, userId, nowIso());
|
||||
} catch (e) {
|
||||
if (isUnique(e)) throw nameTaken(name);
|
||||
throw e;
|
||||
}
|
||||
})
|
||||
.immediate();
|
||||
const emoji = this.get(id) as CustomEmojiDto;
|
||||
this.hub().toServer(serverId, 'emoji:create', { emoji });
|
||||
return emoji;
|
||||
}
|
||||
|
||||
/** The emoji, if the user may rename or delete it: uploader, owner or admin (403), else 404. */
|
||||
private manageable(userId: string, emojiId: string): EmojiRow {
|
||||
const r = this.row(emojiId);
|
||||
if (!r) throw notFound('Emoji not found');
|
||||
// Outsiders, banned and kicked users: the same 404 as a missing emoji.
|
||||
try {
|
||||
requireServerRole(this.db, userId, r.server_id);
|
||||
} catch {
|
||||
throw notFound('Emoji not found');
|
||||
}
|
||||
// D38: your own needs CREATE_EMOJI, anyone's needs MANAGE_EMOJI (owner and admins have both).
|
||||
const perms = Access.for(this.db).serverPerms(userId, r.server_id);
|
||||
const need = r.created_by === userId ? Perm.CREATE_EMOJI : Perm.MANAGE_EMOJI;
|
||||
if ((perms & need) === 0) {
|
||||
throw forbidden(
|
||||
r.created_by === userId
|
||||
? "You don't have permission to change emoji"
|
||||
: 'Only the person who added this emoji or someone who can manage emoji can change it',
|
||||
);
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
rename(userId: string, emojiId: string, name: string): CustomEmojiDto {
|
||||
if (!isValidEmojiName(name)) throw badName();
|
||||
const r = this.manageable(userId, emojiId);
|
||||
if (r.name === name) return toDto(r);
|
||||
try {
|
||||
this.db.prepare('UPDATE custom_emoji SET name = ? WHERE id = ?').run(name, emojiId);
|
||||
} catch (e) {
|
||||
if (isUnique(e)) throw nameTaken(name);
|
||||
throw e;
|
||||
}
|
||||
const emoji = this.get(emojiId) as CustomEmojiDto;
|
||||
this.hub().toServer(r.server_id, 'emoji:update', { emoji });
|
||||
return emoji;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the row and its reactions in one transaction, then tell the server room
|
||||
* (`emoji:delete`) and each affected message's chat (`reaction:update`). Returns the media id
|
||||
* for the caller to delete. Old messages keep their token, which now renders as `:name:`.
|
||||
*/
|
||||
delete(userId: string, emojiId: string): string {
|
||||
const r = this.manageable(userId, emojiId);
|
||||
const announce = this.db.transaction(() => {
|
||||
this.db.prepare('DELETE FROM custom_emoji WHERE id = ?').run(emojiId);
|
||||
return this.messages.dropReactionsIn(customReaction(emojiId));
|
||||
})();
|
||||
this.hub().toServer(r.server_id, 'emoji:delete', { serverId: r.server_id, emojiId });
|
||||
announce();
|
||||
return r.media_id;
|
||||
}
|
||||
|
||||
/** Media ids of a server's emoji (the server delete removes them with its own images). */
|
||||
mediaOf(serverId: string): string[] {
|
||||
return (
|
||||
this.db.prepare('SELECT media_id FROM custom_emoji WHERE server_id = ?').all(serverId) as {
|
||||
media_id: string;
|
||||
}[]
|
||||
).map((r) => r.media_id);
|
||||
}
|
||||
|
||||
/** After a server is deleted: reactions with its emoji (anywhere) go, with reaction:update. */
|
||||
dropOrphanReactions(): void {
|
||||
const orphans = (
|
||||
this.db
|
||||
.prepare(
|
||||
`SELECT DISTINCT emoji FROM reactions WHERE emoji LIKE 'c:%'
|
||||
AND substr(emoji, 3) NOT IN (SELECT id FROM custom_emoji)`,
|
||||
)
|
||||
.all() as { emoji: string }[]
|
||||
).map((r) => r.emoji);
|
||||
for (const emoji of orphans) {
|
||||
this.db.transaction(() => this.messages.dropReactionsIn(emoji))()();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
import type {
|
||||
CreateServerInviteInput,
|
||||
InvitePreviewDto,
|
||||
ServerDetailDto,
|
||||
ServerInviteDto,
|
||||
} from '@chat/shared';
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import { getServerRole, requireServerRole } from '../auth/permissions.js';
|
||||
import type { DB } from '../db/index.js';
|
||||
import { HttpError, forbidden, notFound } from '../lib/errors.js';
|
||||
import { nowIso } from '../lib/ids.js';
|
||||
import type { InviteRow } from './auth.js';
|
||||
import type { ServerService } from './servers.js';
|
||||
|
||||
export function newInviteCode(): string {
|
||||
// 8 random bytes -> 11 url-safe chars; unguessable enough for invite links.
|
||||
return randomBytes(8).toString('base64url');
|
||||
}
|
||||
|
||||
export function inviteProblem(invite: InviteRow | undefined): string | null {
|
||||
if (!invite) return 'That invite code is not valid';
|
||||
if (invite.expires_at && Date.parse(invite.expires_at) <= Date.now())
|
||||
return 'That invite has expired';
|
||||
if (invite.max_uses !== null && invite.uses >= invite.max_uses)
|
||||
return 'That invite has been used up';
|
||||
return null;
|
||||
}
|
||||
|
||||
export const toServerInviteDto = (r: InviteRow): ServerInviteDto => ({
|
||||
code: r.code,
|
||||
serverId: r.server_id as string,
|
||||
maxUses: r.max_uses,
|
||||
uses: r.uses,
|
||||
expiresAt: r.expires_at,
|
||||
createdBy: r.created_by,
|
||||
createdAt: r.created_at,
|
||||
});
|
||||
|
||||
/** Server invite links: create, list, revoke, preview, join. */
|
||||
export class InviteService {
|
||||
constructor(
|
||||
private readonly db: DB,
|
||||
private readonly servers: ServerService,
|
||||
) {}
|
||||
|
||||
private getRow(code: string): InviteRow | undefined {
|
||||
return this.db.prepare('SELECT * FROM invites WHERE code = ?').get(code) as
|
||||
InviteRow | undefined;
|
||||
}
|
||||
|
||||
/** Any member can create an invite (as in Discord's defaults). */
|
||||
create(userId: string, serverId: string, input: CreateServerInviteInput): ServerInviteDto {
|
||||
requireServerRole(this.db, userId, serverId);
|
||||
const code = newInviteCode();
|
||||
const expiresAt = input.expiresInHours
|
||||
? new Date(Date.now() + input.expiresInHours * 3_600_000).toISOString()
|
||||
: null;
|
||||
this.db
|
||||
.prepare(
|
||||
`INSERT INTO invites (code, server_id, created_by, max_uses, uses, expires_at, created_at)
|
||||
VALUES (?, ?, ?, ?, 0, ?, ?)`,
|
||||
)
|
||||
.run(code, serverId, userId, input.maxUses ?? null, expiresAt, nowIso());
|
||||
return toServerInviteDto(this.getRow(code) as InviteRow);
|
||||
}
|
||||
|
||||
/** Admins see all invites; members see only their own. */
|
||||
list(userId: string, serverId: string): ServerInviteDto[] {
|
||||
const role = requireServerRole(this.db, userId, serverId);
|
||||
const rows = (
|
||||
role === 'member'
|
||||
? this.db
|
||||
.prepare(
|
||||
'SELECT * FROM invites WHERE server_id = ? AND created_by = ? ORDER BY created_at DESC',
|
||||
)
|
||||
.all(serverId, userId)
|
||||
: this.db
|
||||
.prepare('SELECT * FROM invites WHERE server_id = ? ORDER BY created_at DESC')
|
||||
.all(serverId)
|
||||
) as InviteRow[];
|
||||
return rows.map(toServerInviteDto);
|
||||
}
|
||||
|
||||
/** Revoke: the creator or a server admin/owner. Instance invites are handled by /api/admin. */
|
||||
revoke(userId: string, code: string): void {
|
||||
const invite = this.getRow(code);
|
||||
if (!invite || invite.server_id === null) throw notFound('Invite not found');
|
||||
const role = getServerRole(this.db, userId, invite.server_id);
|
||||
if (role === null) throw notFound('Invite not found');
|
||||
if (invite.created_by !== userId && role === 'member') throw forbidden();
|
||||
this.db.prepare('DELETE FROM invites WHERE code = ?').run(code);
|
||||
}
|
||||
|
||||
/**
|
||||
* Public preview for the /invite/:code page. Invalid, expired and used-up all look like 404.
|
||||
* `signedIn`: media ids need a session to use, so logged-out visitors get no icon id.
|
||||
*/
|
||||
preview(code: string, signedIn: boolean): InvitePreviewDto {
|
||||
const invite = this.getRow(code);
|
||||
if (inviteProblem(invite) || !invite?.server_id) throw notFound('Invite not found or expired');
|
||||
const server = this.db
|
||||
.prepare(
|
||||
`SELECT s.id, s.name, s.icon_media,
|
||||
(SELECT COUNT(*) FROM members m WHERE m.server_id = s.id AND m.banned = 0) AS member_count
|
||||
FROM servers s WHERE s.id = ?`,
|
||||
)
|
||||
.get(invite.server_id) as {
|
||||
id: string;
|
||||
name: string;
|
||||
icon_media: string | null;
|
||||
member_count: number;
|
||||
};
|
||||
return {
|
||||
code: invite.code,
|
||||
server: {
|
||||
id: server.id,
|
||||
name: server.name,
|
||||
icon: signedIn ? server.icon_media : null,
|
||||
memberCount: server.member_count,
|
||||
},
|
||||
expiresAt: invite.expires_at,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Join a server via invite. Already a member: no-op (no use consumed). Banned: 403.
|
||||
* Validation, use counting and the insert run in one IMMEDIATE transaction so a max_uses=1 invite
|
||||
* can't be used twice by concurrent requests.
|
||||
*/
|
||||
join(userId: string, code: string): { server: ServerDetailDto; joined: boolean } {
|
||||
const result = this.db
|
||||
.transaction((): { serverId: string; joined: boolean } => {
|
||||
const invite = this.getRow(code);
|
||||
const problem = inviteProblem(invite);
|
||||
if (problem || !invite?.server_id) {
|
||||
throw new HttpError(404, 'invalid_invite', problem ?? 'That invite code is not valid');
|
||||
}
|
||||
const serverId = invite.server_id;
|
||||
if (this.servers.isBanned(userId, serverId)) {
|
||||
throw new HttpError(403, 'banned', 'You are banned from this server');
|
||||
}
|
||||
if (getServerRole(this.db, userId, serverId) !== null) return { serverId, joined: false };
|
||||
this.db.prepare('UPDATE invites SET uses = uses + 1 WHERE code = ?').run(code);
|
||||
this.servers.addMember(serverId, userId);
|
||||
return { serverId, joined: true };
|
||||
})
|
||||
.immediate();
|
||||
if (result.joined) this.servers.announceJoin(result.serverId, userId);
|
||||
const role = getServerRole(this.db, userId, result.serverId) ?? 'member';
|
||||
return { server: this.servers.detail(result.serverId, userId, role), joined: result.joined };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
/**
|
||||
* Side effects other services need when access changes. Filled in by app.ts after all services
|
||||
* exist (voice is created last), so ServerService/ChannelService don't depend on VoiceService.
|
||||
*/
|
||||
export interface Lifecycle {
|
||||
/** Kicked, banned or left. */
|
||||
memberRemoved?(serverId: string, userId: string): void;
|
||||
/** A voice channel is gone (deleted on its own or with its server). */
|
||||
voiceChannelDeleted?(channelId: string, serverId: string): void;
|
||||
/** D46: the user's visible channels in this server changed; leave voice in any others. */
|
||||
voiceAccessChanged?(serverId: string, userId: string, visible: ReadonlySet<string>): void;
|
||||
/** D46: re-sync this user's (or every member's) channel rooms after an access change. */
|
||||
accessChanged?(serverId: string, userIds: readonly string[] | 'all'): void;
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
import type { VoiceTokenDto } from '@chat/shared';
|
||||
import { AccessToken, TrackSource } from 'livekit-server-sdk';
|
||||
import { canPublishSourcesFor, type AppConfig, type LivekitConfig } from '../config.js';
|
||||
|
||||
/** What voice-channel and call tokens are built from: the LiveKit keys plus the webcam flag. */
|
||||
export type LivekitGrantConfig = LivekitConfig & Pick<AppConfig, 'videoEnabled'>;
|
||||
|
||||
/** The parts of LiveKit's ParticipantInfo / TrackInfo we read (protocol classes satisfy this). */
|
||||
export interface LkTrack {
|
||||
sid?: string;
|
||||
source: TrackSource;
|
||||
muted: boolean;
|
||||
}
|
||||
export interface LkParticipant {
|
||||
sid: string;
|
||||
identity: string;
|
||||
joinedAt?: bigint | number;
|
||||
tracks: LkTrack[];
|
||||
}
|
||||
/** The parts of a verified LiveKit webhook event we use. */
|
||||
export interface LkWebhookEvent {
|
||||
event: string;
|
||||
/** `sid` is this room session's id: the room name is reused for every call in a DM. */
|
||||
room?: { name: string; sid?: string };
|
||||
/** When LiveKit made the event, in whole seconds (a bigint once parsed). */
|
||||
createdAt?: number | bigint;
|
||||
participant?: LkParticipant;
|
||||
track?: LkTrack;
|
||||
}
|
||||
|
||||
/** LiveKit's server API (RoomServiceClient), behind an interface so tests can fake it. */
|
||||
export interface LivekitApi {
|
||||
listRooms(): Promise<{ name: string }[]>;
|
||||
listParticipants(room: string): Promise<LkParticipant[]>;
|
||||
removeParticipant(room: string, identity: string): Promise<void>;
|
||||
deleteRoom(room: string): Promise<void>;
|
||||
/**
|
||||
* Replace what a connected participant may publish. LiveKit unpublishes tracks whose source is
|
||||
* no longer allowed (used when VIDEO_ENABLED is off but an old session still has a camera).
|
||||
*/
|
||||
setPublishSources?(room: string, identity: string, sources: TrackSource[]): Promise<void>;
|
||||
}
|
||||
|
||||
export interface Logger {
|
||||
warn(obj: unknown, msg?: string): void;
|
||||
info?(obj: unknown, msg?: string): void;
|
||||
debug?(obj: unknown, msg?: string): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Every change the server makes to LiveKit, and every webhook decision that can end a call, is
|
||||
* logged (info) with who, which room, which session and why, so that a call or session that
|
||||
* disappears can always be traced (QA-58). `lk` is the action, e.g. `removeParticipant`.
|
||||
*/
|
||||
export interface LkAudit {
|
||||
lk: string;
|
||||
reason: string;
|
||||
room?: string;
|
||||
identity?: string;
|
||||
sid?: string;
|
||||
callId?: string;
|
||||
[extra: string]: unknown;
|
||||
}
|
||||
export function audit(log: Logger, fields: LkAudit): void {
|
||||
try {
|
||||
log.info?.(fields, `LiveKit ${fields.lk}: ${fields.reason}`);
|
||||
} catch {
|
||||
/* logging never breaks a call */
|
||||
}
|
||||
}
|
||||
export const quiet: Logger = { warn: () => {} };
|
||||
|
||||
const SOURCE: Record<ReturnType<typeof canPublishSourcesFor>[number], TrackSource> = {
|
||||
microphone: TrackSource.MICROPHONE,
|
||||
screen_share: TrackSource.SCREEN_SHARE,
|
||||
screen_share_audio: TrackSource.SCREEN_SHARE_AUDIO,
|
||||
camera: TrackSource.CAMERA,
|
||||
};
|
||||
|
||||
/** The LiveKit sources a token may publish: mic and screen share always, camera with video on. */
|
||||
export function publishSources(config: Pick<AppConfig, 'videoEnabled'>): TrackSource[] {
|
||||
return canPublishSourcesFor(config).map((s) => SOURCE[s]);
|
||||
}
|
||||
|
||||
/**
|
||||
* A room-scoped token for one user (voice channels and DM calls share this, so grants can't
|
||||
* drift): join + subscribe, publish only the allowed sources, no data channel, no admin.
|
||||
*/
|
||||
export async function mintToken(
|
||||
config: LivekitGrantConfig,
|
||||
user: { id: string; displayName: string },
|
||||
room: string,
|
||||
): Promise<VoiceTokenDto> {
|
||||
const ttl = config.tokenTtlSec;
|
||||
const at = new AccessToken(config.apiKey, config.apiSecret, {
|
||||
identity: user.id,
|
||||
name: user.displayName,
|
||||
ttl,
|
||||
});
|
||||
at.addGrant({
|
||||
room,
|
||||
roomJoin: true,
|
||||
canSubscribe: true,
|
||||
canPublish: true,
|
||||
canPublishSources: publishSources(config),
|
||||
canPublishData: false,
|
||||
canUpdateOwnMetadata: false,
|
||||
roomAdmin: false,
|
||||
roomCreate: false,
|
||||
roomList: false,
|
||||
roomRecord: false,
|
||||
hidden: false,
|
||||
});
|
||||
return {
|
||||
token: await at.toJwt(),
|
||||
url: config.clientUrl,
|
||||
room,
|
||||
expiresAt: new Date(Date.now() + ttl * 1000).toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
/** Fire-and-forget LiveKit API call; "not found" just means they already left. */
|
||||
export function fireAndForget(
|
||||
log: Logger,
|
||||
fn: () => Promise<unknown> | undefined,
|
||||
what: string,
|
||||
): void {
|
||||
try {
|
||||
void fn()?.catch((err: unknown) => {
|
||||
const status = (err as { status?: number }).status;
|
||||
if (status !== 404) log.warn({ err }, `LiveKit ${what} failed`);
|
||||
});
|
||||
} catch (err) {
|
||||
log.warn({ err }, `LiveKit ${what} failed`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,414 @@
|
||||
import {
|
||||
MEDIA_ID_RE,
|
||||
MEDIA_KINDS,
|
||||
MEDIA_SIZES,
|
||||
type CropRect,
|
||||
type MediaKind,
|
||||
type MediaSize,
|
||||
} from '@chat/shared';
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import {
|
||||
closeSync,
|
||||
createWriteStream,
|
||||
existsSync,
|
||||
fstatSync,
|
||||
mkdirSync,
|
||||
openSync,
|
||||
readdirSync,
|
||||
readSync,
|
||||
renameSync,
|
||||
rmSync,
|
||||
statSync,
|
||||
} from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import type { Readable } from 'node:stream';
|
||||
import { pipeline } from 'node:stream/promises';
|
||||
import sharp, { type Metadata } from 'sharp';
|
||||
import type { DB } from '../db/index.js';
|
||||
import { badRequest, HttpError, notFound } from '../lib/errors.js';
|
||||
import { sniffImage, type ImageInfo } from '../lib/files.js';
|
||||
import { newId } from '../lib/ids.js';
|
||||
import {
|
||||
headerIsPlausible,
|
||||
imageTooLarge,
|
||||
imageUnreadable,
|
||||
MAX_IMAGE_PIXELS,
|
||||
} from '../lib/images.js';
|
||||
|
||||
/**
|
||||
* Animated images: the 50 MP cap (DESIGN decisions log) applies to the TOTAL pixels across all
|
||||
* frames (width x frame height x frames), checked from the header before any frame is decoded
|
||||
* (TESTPLAN-0.2: a 500-frame 1000x1000 GIF must not get through on its per-frame size).
|
||||
*/
|
||||
export const MAX_TOTAL_PIXELS = MAX_IMAGE_PIXELS;
|
||||
/** At most this many frames, whatever their size (encode time grows with frames x variants). */
|
||||
export const MAX_FRAMES = 300;
|
||||
/** Each sharp pipeline (one output variant) gives up after this long. */
|
||||
export const PROCESS_TIMEOUT_SECONDS = 30;
|
||||
/** Leftover temp files and unreferenced media folders younger than this are left alone. */
|
||||
const SWEEP_GRACE_MS = 3_600_000;
|
||||
|
||||
const SNIFF_BYTES = 64 * 1024;
|
||||
/** Sub-folder of the media dir for custom emoji images (D34). */
|
||||
export const EMOJI_SUBDIR = 'emoji';
|
||||
|
||||
export const unsupportedImage = () =>
|
||||
new HttpError(400, 'unsupported_image', 'Use a PNG, JPEG, WebP or GIF image');
|
||||
export const badCrop = (msg: string) => new HttpError(400, 'bad_crop', msg);
|
||||
const tooManyFrames = () =>
|
||||
new HttpError(400, 'image_too_large', `Animated images can have at most ${MAX_FRAMES} frames`);
|
||||
const tooManyTotalPixels = () =>
|
||||
new HttpError(
|
||||
400,
|
||||
'image_too_large',
|
||||
'Animated images can be at most 50 megapixels across all frames',
|
||||
);
|
||||
export const mediaTooLarge = (mb: number) =>
|
||||
new HttpError(
|
||||
413,
|
||||
'file_too_large',
|
||||
`Images can be at most ${mb < 1 ? `${Math.round(mb * 1024)} KB` : `${mb} MB`}`,
|
||||
);
|
||||
|
||||
/** What the pipeline learned about an uploaded image before decoding any pixels. */
|
||||
export interface InspectedImage {
|
||||
mime: ImageInfo['mime'];
|
||||
/** Displayed size: after EXIF orientation, one frame. */
|
||||
width: number;
|
||||
height: number;
|
||||
pages: number;
|
||||
}
|
||||
|
||||
function readHead(file: string): { head: Buffer; size: number } {
|
||||
const fd = openSync(file, 'r');
|
||||
try {
|
||||
const buf = Buffer.alloc(SNIFF_BYTES);
|
||||
return {
|
||||
head: buf.subarray(0, readSync(fd, buf, 0, SNIFF_BYTES, 0)),
|
||||
size: fstatSync(fd).size,
|
||||
};
|
||||
} finally {
|
||||
closeSync(fd);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Type from magic bytes (never the declared type or extension; SVG and everything else is
|
||||
* refused), plausibility of the header, then sharp's header-only metadata: per-frame and total
|
||||
* pixel caps and the frame cap. Throws 400s.
|
||||
*/
|
||||
export async function inspectImage(file: string): Promise<InspectedImage> {
|
||||
let head: Buffer;
|
||||
let size: number;
|
||||
try {
|
||||
({ head, size } = readHead(file));
|
||||
} catch {
|
||||
throw imageUnreadable();
|
||||
}
|
||||
const sniffed = sniffImage(head);
|
||||
if (!sniffed) throw unsupportedImage();
|
||||
if (!headerIsPlausible(head, sniffed.mime, size)) throw imageUnreadable();
|
||||
if ((sniffed.width ?? 0) * (sniffed.height ?? 0) > MAX_IMAGE_PIXELS) throw imageTooLarge();
|
||||
let meta: Metadata;
|
||||
try {
|
||||
// Header only, first page: reports `pages` and one frame's size without decoding anything.
|
||||
// (With `animated: true` sharp applies its own 268 MP default to width x height x pages and
|
||||
// throws before we can say why; we check the total ourselves below.)
|
||||
meta = await sharp(file, { failOn: 'error', limitInputPixels: false }).metadata();
|
||||
} catch {
|
||||
throw imageUnreadable();
|
||||
}
|
||||
const pages = Math.max(1, meta.pages ?? 1);
|
||||
const width = meta.width ?? 0;
|
||||
const frameHeight = meta.pageHeight ?? meta.height ?? 0;
|
||||
if (width <= 0 || frameHeight <= 0) throw imageUnreadable();
|
||||
if (width * frameHeight > MAX_IMAGE_PIXELS) throw imageTooLarge();
|
||||
if (pages > MAX_FRAMES) throw tooManyFrames();
|
||||
if (width * frameHeight * pages > MAX_TOTAL_PIXELS) throw tooManyTotalPixels();
|
||||
// EXIF orientations 5-8 swap the axes; the browser crop UI shows the image upright.
|
||||
const swap = pages === 1 && (meta.orientation ?? 1) >= 5;
|
||||
return {
|
||||
mime: sniffed.mime,
|
||||
width: swap ? frameHeight : width,
|
||||
height: swap ? width : frameHeight,
|
||||
pages,
|
||||
};
|
||||
}
|
||||
|
||||
/** Crop must be whole pixels, inside the image, and have the kind's aspect ratio (±1 px). */
|
||||
export function validateCrop(
|
||||
crop: CropRect,
|
||||
img: { width: number; height: number },
|
||||
aspect: number,
|
||||
) {
|
||||
const ints = [crop.x, crop.y, crop.w, crop.h].every((v) => Number.isInteger(v));
|
||||
if (!ints || crop.x < 0 || crop.y < 0 || crop.w < 1 || crop.h < 1) {
|
||||
throw badCrop('The crop must be whole, positive pixel values');
|
||||
}
|
||||
if (crop.x + crop.w > img.width || crop.y + crop.h > img.height) {
|
||||
throw badCrop('The crop goes outside the image');
|
||||
}
|
||||
if (Math.abs(crop.w - crop.h * aspect) > 1) {
|
||||
throw badCrop('The crop has the wrong shape for this image');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The one image pipeline for profile, server and group images (DESIGN-0.2 section 0).
|
||||
*
|
||||
* Input: the original upload plus a crop rect in (upright) source pixels. The client never
|
||||
* re-encodes. Here: magic-byte type check, header-only size/frame checks, then per variant a
|
||||
* single decode -> rotate (still images) -> extract(crop) -> resize -> WebP encode (animated WebP
|
||||
* when the source is animated). sharp writes no metadata unless asked, so EXIF/GPS/XMP are gone.
|
||||
*
|
||||
* Storage: `<dir>/<mediaId>/<size>.webp`; custom emoji (kind `emoji`) live one level down in
|
||||
* `<dir>/emoji/<mediaId>/<size>.webp` (D34, QA-120): 0.4.1's sweep only looks at top-level names
|
||||
* that are media ids, so after a rollback it leaves the `emoji` folder alone. Replacing an image writes the new folder first, swaps
|
||||
* the DB pointer in a transaction, then deletes the old folder. `sweep()` removes folders no row
|
||||
* points at (startup and hourly).
|
||||
*/
|
||||
export class MediaService {
|
||||
/** SQL queries returning a column `id` of media ids in use (one per table/column). */
|
||||
private readonly references: string[] = [];
|
||||
|
||||
constructor(
|
||||
private readonly db: DB,
|
||||
readonly dir: string,
|
||||
) {
|
||||
mkdirSync(path.join(dir, '.incoming'), { recursive: true });
|
||||
}
|
||||
|
||||
/** Register where media ids are stored, so the sweep knows what's in use. */
|
||||
addReferences(sql: string): void {
|
||||
this.references.push(sql);
|
||||
}
|
||||
|
||||
static newMediaId(): string {
|
||||
return newId() + randomBytes(16).toString('base64url');
|
||||
}
|
||||
|
||||
static isMediaId(id: string): boolean {
|
||||
return MEDIA_ID_RE.test(id);
|
||||
}
|
||||
|
||||
/** Folder that holds custom emoji media (D34). Not a media id, so no sweep treats it as one. */
|
||||
get emojiDir(): string {
|
||||
return path.join(this.dir, EMOJI_SUBDIR);
|
||||
}
|
||||
|
||||
/** Folder a new image of this kind is written to. */
|
||||
private folderFor(kind: MediaKind, mediaId: string): string {
|
||||
return kind === 'emoji' ? path.join(this.emojiDir, mediaId) : path.join(this.dir, mediaId);
|
||||
}
|
||||
|
||||
/** Existing folder of a media id: `<dir>/<id>` first, then `<dir>/emoji/<id>`; null if none. */
|
||||
private folderOf(mediaId: string): string | null {
|
||||
if (!MediaService.isMediaId(mediaId)) return null;
|
||||
for (const p of [path.join(this.dir, mediaId), path.join(this.emojiDir, mediaId)]) {
|
||||
if (existsSync(p)) return p;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Path of one stored variant; 404 for anything that isn't a valid id and size. */
|
||||
filePath(mediaId: string, size: number): string {
|
||||
if (!MediaService.isMediaId(mediaId) || !(MEDIA_SIZES as readonly number[]).includes(size)) {
|
||||
throw notFound('Image not found');
|
||||
}
|
||||
const folder = this.folderOf(mediaId) ?? path.join(this.dir, mediaId);
|
||||
return path.join(folder, `${size}.webp`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Move custom emoji folders a pre-release 0.5 build left at the top level into `emoji/`
|
||||
* (D34). Ids that aren't media ids, or have no top-level folder, are skipped. Returns how many
|
||||
* folders moved.
|
||||
*/
|
||||
relocateEmoji(mediaIds: Iterable<string>): number {
|
||||
let moved = 0;
|
||||
for (const id of mediaIds) {
|
||||
if (!MediaService.isMediaId(id)) continue;
|
||||
const from = path.join(this.dir, id);
|
||||
const to = path.join(this.emojiDir, id);
|
||||
if (!existsSync(from) || existsSync(to)) continue;
|
||||
mkdirSync(this.emojiDir, { recursive: true });
|
||||
renameSync(from, to);
|
||||
moved++;
|
||||
}
|
||||
return moved;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stream an upload to a temp file, enforcing maxBytes. The caller must `discard()` it when done.
|
||||
*/
|
||||
async receive(
|
||||
stream: Readable & { truncated?: boolean },
|
||||
maxBytes: number,
|
||||
maxMb: number,
|
||||
): Promise<string> {
|
||||
const dest = path.join(this.dir, '.incoming', `${newId()}-${randomBytes(6).toString('hex')}`);
|
||||
let size = 0;
|
||||
const out = createWriteStream(dest, { flags: 'wx', mode: 0o640 });
|
||||
try {
|
||||
await pipeline(
|
||||
stream,
|
||||
async function* (source: AsyncIterable<Buffer>) {
|
||||
for await (const chunk of source) {
|
||||
size += chunk.length;
|
||||
if (size > maxBytes) throw mediaTooLarge(maxMb);
|
||||
yield chunk;
|
||||
}
|
||||
},
|
||||
out,
|
||||
);
|
||||
if (stream.truncated) throw mediaTooLarge(maxMb);
|
||||
} catch (err) {
|
||||
// The write stream opens asynchronously: wait until it's closed, or the file can appear
|
||||
// after we've removed it (a leftover in .incoming under load).
|
||||
if (!out.closed) await new Promise<void>((resolve) => out.once('close', () => resolve()));
|
||||
rmSync(dest, { force: true });
|
||||
const e = err as { code?: string; statusCode?: number };
|
||||
if (e.code === 'FST_REQ_FILE_TOO_LARGE' || e.statusCode === 413) throw mediaTooLarge(maxMb);
|
||||
throw err;
|
||||
}
|
||||
if (size === 0) {
|
||||
rmSync(dest, { force: true });
|
||||
throw badRequest('The file is empty');
|
||||
}
|
||||
return dest;
|
||||
}
|
||||
|
||||
discard(file: string | null): void {
|
||||
if (file) rmSync(file, { force: true });
|
||||
}
|
||||
|
||||
/** Validate, crop and encode `src` into a new media folder. Returns the new media id. */
|
||||
async ingest(src: string, kind: MediaKind, crop: CropRect): Promise<string> {
|
||||
return (await this.ingestImage(src, kind, crop)).mediaId;
|
||||
}
|
||||
|
||||
/** `ingest`, also saying whether the image is animated (kept animated in the WebP). */
|
||||
async ingestImage(
|
||||
src: string,
|
||||
kind: MediaKind,
|
||||
crop: CropRect,
|
||||
): Promise<{ mediaId: string; animated: boolean }> {
|
||||
const spec = MEDIA_KINDS[kind];
|
||||
const img = await inspectImage(src);
|
||||
validateCrop(crop, img, spec.aspect);
|
||||
const id = MediaService.newMediaId();
|
||||
const tmp = path.join(this.dir, `.tmp-${id}`);
|
||||
mkdirSync(tmp);
|
||||
try {
|
||||
for (const size of spec.sizes) {
|
||||
const width = size;
|
||||
const height = Math.round(size / spec.aspect);
|
||||
const pipe = sharp(src, {
|
||||
animated: img.pages > 1,
|
||||
// For animated input sharp counts width x (frame height x frames): the total cap again.
|
||||
limitInputPixels: MAX_TOTAL_PIXELS,
|
||||
failOn: 'error',
|
||||
});
|
||||
if (img.pages === 1) pipe.rotate();
|
||||
await pipe
|
||||
.extract({ left: crop.x, top: crop.y, width: crop.w, height: crop.h })
|
||||
.resize(width, height, { fit: 'fill' })
|
||||
.webp({ quality: 85, effort: 4 })
|
||||
.timeout({ seconds: PROCESS_TIMEOUT_SECONDS })
|
||||
.toFile(path.join(tmp, `${size}.webp`));
|
||||
}
|
||||
const dest = this.folderFor(kind, id);
|
||||
mkdirSync(path.dirname(dest), { recursive: true });
|
||||
renameSync(tmp, dest);
|
||||
return { mediaId: id, animated: img.pages > 1 };
|
||||
} catch (err) {
|
||||
rmSync(tmp, { recursive: true, force: true });
|
||||
if (err instanceof HttpError) throw err;
|
||||
const msg = (err as Error).message;
|
||||
if (/pixel limit/i.test(msg)) throw imageTooLarge();
|
||||
if (/timeout/i.test(msg)) {
|
||||
throw new HttpError(400, 'image_too_complex', 'That image took too long to process');
|
||||
}
|
||||
throw imageUnreadable();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ingest, then let `swap(newId)` point the DB at the new id (it runs in a transaction and
|
||||
* returns the previous id), then delete the previous folder. On any error the new folder goes.
|
||||
*/
|
||||
async replace(
|
||||
src: string,
|
||||
kind: MediaKind,
|
||||
crop: CropRect,
|
||||
swap: (mediaId: string) => string | null,
|
||||
): Promise<{ mediaId: string; previous: string | null }> {
|
||||
const mediaId = await this.ingest(src, kind, crop);
|
||||
let previous: string | null;
|
||||
try {
|
||||
previous = this.db.transaction(() => swap(mediaId)).immediate();
|
||||
} catch (err) {
|
||||
this.remove(mediaId);
|
||||
throw err;
|
||||
}
|
||||
this.remove(previous);
|
||||
return { mediaId, previous };
|
||||
}
|
||||
|
||||
/** Delete a media folder, top level or under `emoji/` (no-op for anything not a media id). */
|
||||
remove(mediaId: string | null): void {
|
||||
if (!mediaId || !MediaService.isMediaId(mediaId)) return;
|
||||
rmSync(path.join(this.dir, mediaId), { recursive: true, force: true });
|
||||
rmSync(path.join(this.emojiDir, mediaId), { recursive: true, force: true });
|
||||
}
|
||||
|
||||
exists(mediaId: string): boolean {
|
||||
return this.folderOf(mediaId) !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove media folders no row points at, plus stale temp files (older than the grace period, so
|
||||
* an upload in progress is never touched). Looks at the top level and inside `emoji/`; the
|
||||
* `emoji` folder itself is never a media id, so it is never removed. Returns how many
|
||||
* folders/files were removed.
|
||||
*/
|
||||
sweep(graceMs = SWEEP_GRACE_MS, now = Date.now()): number {
|
||||
const used = new Set<string>();
|
||||
for (const sql of this.references) {
|
||||
for (const r of this.db.prepare(sql).all() as { id: string | null }[]) {
|
||||
if (r.id) used.add(r.id);
|
||||
}
|
||||
}
|
||||
const old = (p: string) => now - statSync(p).mtimeMs >= graceMs;
|
||||
let removed = 0;
|
||||
for (const name of readdirSync(this.dir)) {
|
||||
const full = path.join(this.dir, name);
|
||||
if (name === '.incoming') {
|
||||
for (const f of readdirSync(full)) {
|
||||
if (old(path.join(full, f))) {
|
||||
rmSync(path.join(full, f), { force: true });
|
||||
removed++;
|
||||
}
|
||||
}
|
||||
} else if (name === EMOJI_SUBDIR) {
|
||||
if (!statSync(full).isDirectory()) continue;
|
||||
for (const id of readdirSync(full)) {
|
||||
const p = path.join(full, id);
|
||||
if (MediaService.isMediaId(id) && !used.has(id) && old(p)) {
|
||||
rmSync(p, { recursive: true, force: true });
|
||||
removed++;
|
||||
}
|
||||
}
|
||||
} else if (
|
||||
(name.startsWith('.tmp-') || (MediaService.isMediaId(name) && !used.has(name))) &&
|
||||
old(full)
|
||||
) {
|
||||
rmSync(full, { recursive: true, force: true });
|
||||
removed++;
|
||||
}
|
||||
}
|
||||
return removed;
|
||||
}
|
||||
}
|
||||
|
||||
export type { MediaSize };
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,100 @@
|
||||
import type { ChannelDto, OverrideDto, PositionUpdate } from '@chat/shared';
|
||||
import { Access, type ServerAccessData } from '../auth/access.js';
|
||||
import type { ChannelRow } from '../auth/permissions.js';
|
||||
import type { DB } from '../db/index.js';
|
||||
import type { RealtimeHub } from '../realtime/hub.js';
|
||||
import { toChannelDto } from './servers.js';
|
||||
|
||||
/**
|
||||
* D63 (QA-150): positions a client sees are dense per viewer: a channel's index among the
|
||||
* channels that viewer can see in its category (0..n-1), never the stored number, whose gaps
|
||||
* would show where hidden channels are and how many.
|
||||
*/
|
||||
export type Dense = Map<string, { position: number; categoryId: string | null }>;
|
||||
|
||||
/** `channels` in stored order (position, id); only the ids in `visible` are numbered. */
|
||||
export function densePositions(
|
||||
channels: readonly ChannelRow[],
|
||||
visible: ReadonlySet<string>,
|
||||
): Dense {
|
||||
const sorted = [...channels].sort(
|
||||
(a, b) => a.position - b.position || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0),
|
||||
);
|
||||
const next = new Map<string | null, number>();
|
||||
const out: Dense = new Map();
|
||||
for (const c of sorted) {
|
||||
if (!visible.has(c.id)) continue;
|
||||
const i = next.get(c.category_id) ?? 0;
|
||||
out.set(c.id, { position: i, categoryId: c.category_id });
|
||||
next.set(c.category_id, i + 1);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export const toPositionList = (d: Dense): PositionUpdate[] =>
|
||||
[...d].map(([id, p]) => ({ id, position: p.position, categoryId: p.categoryId }));
|
||||
|
||||
/** A channel as this viewer sees it (dense position). */
|
||||
export function viewerChannelDto(
|
||||
row: ChannelRow,
|
||||
dense: Dense,
|
||||
overrides: OverrideDto[] = [],
|
||||
): ChannelDto {
|
||||
const dto = toChannelDto(row, overrides);
|
||||
const p = dense.get(row.id);
|
||||
// Not visible to this viewer (e.g. a creator whose roles don't give VIEW): after their list.
|
||||
const position =
|
||||
p?.position ?? [...dense.values()].filter((x) => x.categoryId === row.category_id).length;
|
||||
return { ...dto, position };
|
||||
}
|
||||
|
||||
/** Every member's dense view of one server. */
|
||||
export function snapshot(db: DB, serverId: string): Map<string, Dense> {
|
||||
const access = Access.for(db);
|
||||
const data = access.load(serverId);
|
||||
return snapshotOf(access, data);
|
||||
}
|
||||
|
||||
export function snapshotOf(access: Access, data: ServerAccessData): Map<string, Dense> {
|
||||
const out = new Map<string, Dense>();
|
||||
for (const userId of data.members.keys()) {
|
||||
out.set(userId, densePositions(data.channels, access.visibleIn(data, userId)));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The dense view for one user (empty for a non-member). */
|
||||
export function denseFor(db: DB, userId: string, serverId: string): Dense {
|
||||
const access = Access.for(db);
|
||||
const data = access.load(serverId);
|
||||
return densePositions(data.channels, access.visibleIn(data, userId));
|
||||
}
|
||||
|
||||
/**
|
||||
* After a structural change (reorder, move, delete): send each member `channel:reorder` with
|
||||
* only the channels whose dense position or category changed for them. Someone whose own view
|
||||
* didn't change (a hidden channel moved or went away) gets nothing, so no event hints at it.
|
||||
* Channels that appear or disappear for a user travel in channel:create / channel:delete /
|
||||
* channel:access instead.
|
||||
*/
|
||||
export function emitPositionChanges(
|
||||
db: DB,
|
||||
hub: RealtimeHub,
|
||||
serverId: string,
|
||||
before: Map<string, Dense>,
|
||||
): Map<string, Dense> {
|
||||
const after = snapshot(db, serverId);
|
||||
for (const [userId, now] of after) {
|
||||
const was = before.get(userId);
|
||||
if (!was) continue;
|
||||
const changed: PositionUpdate[] = [];
|
||||
for (const [id, p] of now) {
|
||||
const old = was.get(id);
|
||||
if (old && (old.position !== p.position || old.categoryId !== p.categoryId)) {
|
||||
changed.push({ id, position: p.position, categoryId: p.categoryId });
|
||||
}
|
||||
}
|
||||
if (changed.length) hub.toUser(userId, 'channel:reorder', { serverId, positions: changed });
|
||||
}
|
||||
return after;
|
||||
}
|
||||
@@ -0,0 +1,346 @@
|
||||
import {
|
||||
STATUS_EXPIRY_MAX_MS,
|
||||
type CustomStatusDto,
|
||||
type MyCustomStatusDto,
|
||||
type PresencePref,
|
||||
type PresenceSelfDto,
|
||||
type PresenceStatus,
|
||||
type StatusTextInput,
|
||||
} from '@chat/shared';
|
||||
import { badRequest } from '../lib/errors.js';
|
||||
import type { DB } from '../db/index.js';
|
||||
import type { RealtimeHub } from '../realtime/hub.js';
|
||||
|
||||
/** Who sees a user: the server rooms they're a (non-banned) member of, plus everyone they share a DM or group DM with. */
|
||||
export interface Audience {
|
||||
serverIds: string[];
|
||||
userIds: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* The single source of truth for "who can see this user" (DESIGN-0.2 section 1): presence fan-out,
|
||||
* profile visibility and `user:update` all use it. Banned members count as non-members.
|
||||
*/
|
||||
export function visibleTo(db: DB, userId: string): Audience {
|
||||
const serverIds = (
|
||||
db.prepare('SELECT server_id FROM members WHERE user_id = ? AND banned = 0').all(userId) as {
|
||||
server_id: string;
|
||||
}[]
|
||||
).map((r) => r.server_id);
|
||||
const userIds = (
|
||||
db
|
||||
.prepare(
|
||||
`SELECT DISTINCT other.user_id AS other
|
||||
FROM dm_members me JOIN dm_members other ON other.dm_channel_id = me.dm_channel_id
|
||||
WHERE me.user_id = ? AND other.user_id <> me.user_id`,
|
||||
)
|
||||
.all(userId) as { other: string }[]
|
||||
).map((r) => r.other);
|
||||
return { serverIds, userIds };
|
||||
}
|
||||
|
||||
/** True if `viewerId` is in `targetId`'s audience (shares a server, a DM or a group), or is them. */
|
||||
export function canSeeUser(db: DB, viewerId: string, targetId: string): boolean {
|
||||
if (viewerId === targetId) return true;
|
||||
const row = db
|
||||
.prepare(
|
||||
`SELECT 1 FROM members a JOIN members b ON b.server_id = a.server_id
|
||||
WHERE a.user_id = ? AND a.banned = 0 AND b.user_id = ? AND b.banned = 0
|
||||
UNION ALL
|
||||
SELECT 1 FROM dm_members a JOIN dm_members b ON b.dm_channel_id = a.dm_channel_id
|
||||
WHERE a.user_id = ? AND b.user_id = ?
|
||||
LIMIT 1`,
|
||||
)
|
||||
.get(viewerId, targetId, viewerId, targetId);
|
||||
return row !== undefined;
|
||||
}
|
||||
|
||||
interface Tab {
|
||||
idle: boolean;
|
||||
}
|
||||
|
||||
interface StatusRow {
|
||||
status_text: string | null;
|
||||
status_emoji: string | null;
|
||||
status_expires_at: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Live presence (PLAN story 5), in memory only so a restart never leaves ghosts; custom text
|
||||
* (D49) is stored on the user with an absolute expiry.
|
||||
*
|
||||
* - Every socket (tab/device) reports whether it's idle. The client calls a tab idle after
|
||||
* IDLE_AFTER_MS (10 minutes, D48) without input in a visible tab.
|
||||
* - online: at least one active tab. idle: connected but every tab idle, or chosen "idle".
|
||||
* dnd: chosen. offline: no sockets left after GRACE (a reload or a quick network blip doesn't
|
||||
* flicker), or chosen "invisible" (others see offline; the user sees "invisible").
|
||||
* - Changes go only to people who share a server (server rooms) or a DM (user rooms) with the user.
|
||||
* - D50/D51: `presence:update` is always `{ userId, status, custom }`. While others see offline
|
||||
* (really offline or Invisible) custom is null, so the two are the same payload. Custom text is
|
||||
* never sent between two people where either has blocked the other.
|
||||
*/
|
||||
export class PresenceService {
|
||||
private readonly tabs = new Map<string, Map<string, Tab>>();
|
||||
private readonly offlineTimers = new Map<string, NodeJS.Timeout>();
|
||||
/** Last status broadcast to others, per user. Absent = offline. */
|
||||
private readonly shown = new Map<string, PresenceStatus>();
|
||||
private sweeper: NodeJS.Timeout | null = null;
|
||||
|
||||
constructor(
|
||||
private readonly db: DB,
|
||||
private readonly hub: () => RealtimeHub,
|
||||
private readonly audienceOf: (userId: string) => Audience,
|
||||
private readonly graceMs: number,
|
||||
private readonly now: () => number = Date.now,
|
||||
) {}
|
||||
|
||||
pref(userId: string): PresencePref {
|
||||
const row = this.db.prepare('SELECT presence FROM users WHERE id = ?').get(userId) as
|
||||
{ presence: PresencePref } | undefined;
|
||||
return row?.presence ?? 'online';
|
||||
}
|
||||
|
||||
/** What other people see right now. */
|
||||
statusOf(userId: string): PresenceStatus {
|
||||
return this.shown.get(userId) ?? 'offline';
|
||||
}
|
||||
|
||||
/** D49: the user's own custom text, or null (none, or expired: reads treat it as empty at once). */
|
||||
customOf(userId: string): MyCustomStatusDto | null {
|
||||
const r = this.db
|
||||
.prepare('SELECT status_text, status_emoji, status_expires_at FROM users WHERE id = ?')
|
||||
.get(userId) as StatusRow | undefined;
|
||||
if (!r?.status_text) return null;
|
||||
if (r.status_expires_at && Date.parse(r.status_expires_at) <= this.now()) return null;
|
||||
return { text: r.status_text, emoji: r.status_emoji, expiresAt: r.status_expires_at };
|
||||
}
|
||||
|
||||
/** D50: what `viewerId` may see of `userId`'s custom text. */
|
||||
customFor(viewerId: string, userId: string): CustomStatusDto | null {
|
||||
if (viewerId !== userId) {
|
||||
if (this.statusOf(userId) === 'offline') return null;
|
||||
if (this.blockedWith(userId).includes(viewerId)) return null;
|
||||
}
|
||||
const c = this.customOf(userId);
|
||||
return c ? { text: c.text, emoji: c.emoji } : null;
|
||||
}
|
||||
|
||||
/** Everyone the user has blocked or who has blocked them (D50: either direction). */
|
||||
private blockedWith(userId: string): string[] {
|
||||
return (
|
||||
this.db
|
||||
.prepare(
|
||||
`SELECT blocked_id AS id FROM blocks WHERE blocker_id = ?
|
||||
UNION SELECT blocker_id AS id FROM blocks WHERE blocked_id = ?`,
|
||||
)
|
||||
.all(userId, userId) as { id: string }[]
|
||||
).map((r) => r.id);
|
||||
}
|
||||
|
||||
/** The user's own view: their choice, what others currently see, and their own text. */
|
||||
selfView(userId: string): PresenceSelfDto {
|
||||
return {
|
||||
pref: this.pref(userId),
|
||||
status: this.statusOf(userId),
|
||||
custom: this.customOf(userId),
|
||||
};
|
||||
}
|
||||
|
||||
connect(userId: string, socketId: string): void {
|
||||
const timer = this.offlineTimers.get(userId);
|
||||
if (timer) {
|
||||
clearTimeout(timer);
|
||||
this.offlineTimers.delete(userId);
|
||||
}
|
||||
let tabs = this.tabs.get(userId);
|
||||
if (!tabs) this.tabs.set(userId, (tabs = new Map()));
|
||||
tabs.set(socketId, { idle: false });
|
||||
this.refresh(userId);
|
||||
}
|
||||
|
||||
disconnect(userId: string, socketId: string): void {
|
||||
const tabs = this.tabs.get(userId);
|
||||
if (!tabs?.delete(socketId)) return;
|
||||
if (tabs.size > 0) return this.refresh(userId);
|
||||
this.tabs.delete(userId);
|
||||
// Last tab gone: wait a little before announcing offline (reloads, flaky mobile networks).
|
||||
this.offlineTimers.set(
|
||||
userId,
|
||||
setTimeout(() => {
|
||||
this.offlineTimers.delete(userId);
|
||||
this.refresh(userId);
|
||||
}, this.graceMs).unref(),
|
||||
);
|
||||
}
|
||||
|
||||
setIdle(userId: string, socketId: string, idle: boolean): void {
|
||||
const tab = this.tabs.get(userId)?.get(socketId);
|
||||
if (!tab || tab.idle === idle) return;
|
||||
tab.idle = idle;
|
||||
this.refresh(userId);
|
||||
}
|
||||
|
||||
setPref(userId: string, pref: PresencePref): void {
|
||||
this.db.prepare('UPDATE users SET presence = ? WHERE id = ?').run(pref, userId);
|
||||
this.refresh(userId, { self: true });
|
||||
}
|
||||
|
||||
/**
|
||||
* D49: set (or with null, clear) the custom text. `expiresAt` must be null or in the future and
|
||||
* at most 25 hours ahead (the client turns "today" into the browser's next midnight).
|
||||
*/
|
||||
setCustom(userId: string, input: StatusTextInput | null): MyCustomStatusDto | null {
|
||||
if (input?.expiresAt) {
|
||||
const at = Date.parse(input.expiresAt);
|
||||
const now = this.now();
|
||||
if (at <= now) throw badRequest('That time has already passed');
|
||||
if (at - now > STATUS_EXPIRY_MAX_MS) {
|
||||
throw badRequest('A status can clear at most 25 hours from now');
|
||||
}
|
||||
}
|
||||
this.db
|
||||
.prepare(
|
||||
'UPDATE users SET status_text = ?, status_emoji = ?, status_expires_at = ? WHERE id = ?',
|
||||
)
|
||||
.run(input?.text ?? null, input?.emoji ?? null, input?.expiresAt ?? null, userId);
|
||||
this.refresh(userId, { self: true, custom: true });
|
||||
return this.customOf(userId);
|
||||
}
|
||||
|
||||
/**
|
||||
* D49: clear expired text and tell people (reads already treat it as empty). Runs every
|
||||
* STATUS_SWEEP_MS from the app; returns who was cleared.
|
||||
*/
|
||||
sweep(): string[] {
|
||||
const nowIso = new Date(this.now()).toISOString();
|
||||
const ids = (
|
||||
this.db
|
||||
.prepare(
|
||||
`SELECT id FROM users WHERE status_text IS NOT NULL
|
||||
AND status_expires_at IS NOT NULL AND status_expires_at <= ?`,
|
||||
)
|
||||
.all(nowIso) as { id: string }[]
|
||||
).map((r) => r.id);
|
||||
const clear = this.db.prepare(
|
||||
'UPDATE users SET status_text = NULL, status_emoji = NULL, status_expires_at = NULL WHERE id = ?',
|
||||
);
|
||||
for (const id of ids) {
|
||||
clear.run(id);
|
||||
this.refresh(id, { self: true, custom: true });
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
/** D67: one sweep at once (text that expired while the server was down), then every `everyMs`. */
|
||||
startSweep(everyMs: number): void {
|
||||
if (this.sweeper) clearInterval(this.sweeper);
|
||||
this.sweep();
|
||||
this.sweeper = setInterval(() => this.sweep(), everyMs);
|
||||
this.sweeper.unref();
|
||||
}
|
||||
|
||||
/**
|
||||
* D50: a block or unblock between a and b (a acted). Each of them gets the other's presence
|
||||
* again, with custom text only if no block is left between them.
|
||||
* D67: only when that payload really changes. Status never does; custom text does only for a
|
||||
* user who is shown and has text, and only if b has not blocked a too (then both sides saw
|
||||
* `custom: null` before and still do).
|
||||
*/
|
||||
blockChanged(a: string, b: string): void {
|
||||
const reverse = this.db
|
||||
.prepare('SELECT 1 FROM blocks WHERE blocker_id = ? AND blocked_id = ?')
|
||||
.get(b, a);
|
||||
if (reverse) return;
|
||||
for (const [viewer, user] of [
|
||||
[a, b],
|
||||
[b, a],
|
||||
] as const) {
|
||||
const status = this.statusOf(user);
|
||||
if (status === 'offline' || !this.customOf(user) || !canSeeUser(this.db, viewer, user)) {
|
||||
continue;
|
||||
}
|
||||
this.hub().toUser(viewer, 'presence:update', {
|
||||
userId: user,
|
||||
status,
|
||||
custom: this.customFor(viewer, user),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private compute(userId: string): PresenceStatus {
|
||||
const tabs = this.tabs.get(userId);
|
||||
if (!tabs) {
|
||||
// In the grace period we keep showing the last status.
|
||||
return this.offlineTimers.has(userId) ? this.statusOf(userId) : 'offline';
|
||||
}
|
||||
const pref = this.pref(userId);
|
||||
if (pref === 'invisible') return 'offline';
|
||||
if (pref === 'dnd') return 'dnd';
|
||||
if (pref === 'idle') return 'idle';
|
||||
return [...tabs.values()].some((t) => !t.idle) ? 'online' : 'idle';
|
||||
}
|
||||
|
||||
/** Recompute; broadcast to the audience if what others see changed. */
|
||||
private refresh(userId: string, changed: { self?: boolean; custom?: boolean } = {}): void {
|
||||
const status = this.compute(userId);
|
||||
const before = this.statusOf(userId);
|
||||
if (status === 'offline') this.shown.delete(userId);
|
||||
else this.shown.set(userId, status);
|
||||
if (status !== before || (changed.custom && status !== 'offline')) {
|
||||
this.broadcast(userId, status);
|
||||
}
|
||||
if (status !== before || changed.self) {
|
||||
// The user's own tabs: their choice and how they look (invisible shows as invisible).
|
||||
this.hub().toUser(userId, 'presence:self', this.selfView(userId));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* D50/D51: one payload shape for everyone. Offline (real or Invisible): `custom: null` to all,
|
||||
* one emit. With text: the audience except blocked pairs, then `custom: null` to those of them
|
||||
* who are in the audience.
|
||||
*/
|
||||
private broadcast(userId: string, status: PresenceStatus): void {
|
||||
const { serverIds, userIds } = this.audienceOf(userId);
|
||||
const mine = status === 'offline' ? null : this.customOf(userId);
|
||||
const custom = mine ? { text: mine.text, emoji: mine.emoji } : null;
|
||||
const hub = this.hub();
|
||||
const blocked = custom ? this.blockedWith(userId) : [];
|
||||
hub.toAudience(serverIds, userIds, 'presence:update', { userId, status, custom }, blocked);
|
||||
for (const id of blocked) {
|
||||
if (canSeeUser(this.db, id, userId)) {
|
||||
hub.toUser(id, 'presence:update', { userId, status, custom: null });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Statuses of everyone the viewer shares a server or DM with (offline ones omitted). */
|
||||
statusesFor(viewerId: string, userIds: Iterable<string>): Record<string, PresenceStatus> {
|
||||
const out: Record<string, PresenceStatus> = {};
|
||||
for (const id of userIds) {
|
||||
if (id === viewerId) continue;
|
||||
const s = this.statusOf(id);
|
||||
if (s !== 'offline') out[id] = s;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** D50: custom text of those people, as the viewer may see it (offline, Invisible, blocks: none). */
|
||||
customsFor(viewerId: string, userIds: Iterable<string>): Record<string, CustomStatusDto> {
|
||||
const out: Record<string, CustomStatusDto> = {};
|
||||
for (const id of userIds) {
|
||||
if (id === viewerId) continue;
|
||||
const c = this.customFor(viewerId, id);
|
||||
if (c) out[id] = c;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Stop timers (app close). */
|
||||
close(): void {
|
||||
for (const t of this.offlineTimers.values()) clearTimeout(t);
|
||||
this.offlineTimers.clear();
|
||||
if (this.sweeper) clearInterval(this.sweeper);
|
||||
this.sweeper = null;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,57 @@
|
||||
import type { OverrideDto, RoleDto } from '@chat/shared';
|
||||
import type { DB } from '../db/index.js';
|
||||
import type { RoleRow } from '../auth/access.js';
|
||||
|
||||
/** D42: a role row as the API sends it. */
|
||||
export const toRoleDto = (r: RoleRow): RoleDto => ({
|
||||
id: r.id,
|
||||
serverId: r.server_id,
|
||||
name: r.name,
|
||||
color: r.color,
|
||||
position: r.position,
|
||||
permissions: r.permissions,
|
||||
isEveryone: r.is_everyone === 1,
|
||||
});
|
||||
|
||||
/** Every role of a server, highest first (`@everyone`, position 0, last). */
|
||||
export function serverRoles(db: DB, serverId: string): RoleDto[] {
|
||||
return (
|
||||
db
|
||||
.prepare('SELECT * FROM roles WHERE server_id = ? ORDER BY position DESC, id')
|
||||
.all(serverId) as RoleRow[]
|
||||
).map(toRoleDto);
|
||||
}
|
||||
|
||||
type OverrideRow = { channel_id: string; role_id: string; allow: number; deny: number };
|
||||
const toOverride = (o: OverrideRow): OverrideDto => ({
|
||||
roleId: o.role_id,
|
||||
allow: o.allow,
|
||||
deny: o.deny,
|
||||
});
|
||||
|
||||
/** One channel's overrides (stable order: by role id). */
|
||||
export function channelOverrides(db: DB, channelId: string): OverrideDto[] {
|
||||
return (
|
||||
db
|
||||
.prepare(
|
||||
'SELECT channel_id, role_id, allow, deny FROM channel_overrides WHERE channel_id = ? ORDER BY role_id',
|
||||
)
|
||||
.all(channelId) as OverrideRow[]
|
||||
).map(toOverride);
|
||||
}
|
||||
|
||||
/** Every channel's overrides in one server. */
|
||||
export function serverOverrides(db: DB, serverId: string): Map<string, OverrideDto[]> {
|
||||
const out = new Map<string, OverrideDto[]>();
|
||||
for (const o of db
|
||||
.prepare(
|
||||
`SELECT o.channel_id, o.role_id, o.allow, o.deny FROM channel_overrides o
|
||||
JOIN channels c ON c.id = o.channel_id WHERE c.server_id = ? ORDER BY o.role_id`,
|
||||
)
|
||||
.all(serverId) as OverrideRow[]) {
|
||||
const list = out.get(o.channel_id) ?? [];
|
||||
list.push(toOverride(o));
|
||||
out.set(o.channel_id, list);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,493 @@
|
||||
import {
|
||||
ALL_PERMS,
|
||||
MAX_ROLES_PER_SERVER,
|
||||
Perm,
|
||||
ROLE_WRITES_PER_MINUTE,
|
||||
type ChannelDto,
|
||||
type ChannelNameDto,
|
||||
type OverrideDto,
|
||||
type RoleDto,
|
||||
type MemberDto,
|
||||
type ServerRole,
|
||||
} from '@chat/shared';
|
||||
import type { DB } from '../db/index.js';
|
||||
import { Access, type RoleRow } from '../auth/access.js';
|
||||
import { HttpError, badRequest, conflict, forbidden, notFound } from '../lib/errors.js';
|
||||
import { newId, nowIso } from '../lib/ids.js';
|
||||
import { RateWindow } from '../lib/rate-window.js';
|
||||
import type { RealtimeHub } from '../realtime/hub.js';
|
||||
import type { Lifecycle } from './lifecycle.js';
|
||||
import type { ChannelRow } from '../auth/permissions.js';
|
||||
import { channelOverrides, serverRoles, toRoleDto } from './role-dto.js';
|
||||
import { toChannelDto } from './servers.js';
|
||||
|
||||
export interface CreateRoleInput {
|
||||
name: string;
|
||||
color?: string | null;
|
||||
permissions?: number;
|
||||
}
|
||||
export type UpdateRoleInput = Partial<CreateRoleInput>;
|
||||
|
||||
/** Who is acting, read inside the write transaction (D59). */
|
||||
interface Actor {
|
||||
rank: ServerRole;
|
||||
/** D40 "your top": Infinity for owner and admins. */
|
||||
top: number;
|
||||
/** Server-wide bits (`base`; every bit for owner and admins). */
|
||||
base: number;
|
||||
/** Owner or admin: the hierarchy rules don't limit them (D37). */
|
||||
privileged: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* M29 roles and channel permissions (DESIGN-0.6 section 6, D37-D40, D56, D57, D59, D61).
|
||||
*
|
||||
* Every write runs its checks and its changes in one SQLite transaction, so what is checked is
|
||||
* what is written (D59). AccessSync runs after the commit and before the response (D46). Writes are
|
||||
* last-write-wins at field level with no etag (D56) and share one 30-a-minute limit per user (D57).
|
||||
*/
|
||||
/** QA-153: the comparison key for role names. */
|
||||
export const roleNameKey = (name: string): string => name.normalize('NFC').toLowerCase();
|
||||
|
||||
/** D64a: the refusal for a write that would raise the editor's own permissions. */
|
||||
export const OWN_RAISE = "You can't give yourself permissions with this change";
|
||||
|
||||
export class RoleService {
|
||||
constructor(
|
||||
private readonly db: DB,
|
||||
private readonly hub: () => RealtimeHub,
|
||||
private readonly lifecycle: Lifecycle = {},
|
||||
/** D57: null = off (RATE_LIMIT=false). */
|
||||
readonly writes: RateWindow | null = new RateWindow(ROLE_WRITES_PER_MINUTE, 60_000),
|
||||
) {}
|
||||
|
||||
// ---- helpers ----
|
||||
|
||||
private actor(userId: string, serverId: string): Actor {
|
||||
const access = Access.for(this.db);
|
||||
const rank = access.requireServerPerm(userId, serverId, Perm.MANAGE_ROLES);
|
||||
const privileged = rank === 'owner' || rank === 'admin';
|
||||
return {
|
||||
rank,
|
||||
privileged,
|
||||
top: access.top(userId, serverId),
|
||||
base: privileged ? ALL_PERMS : access.serverPerms(userId, serverId),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* D64a: a member's own bits, server-wide (key '') and in every channel of the server, with the
|
||||
* shared function. Taken inside a write transaction before and after the change.
|
||||
*/
|
||||
private ownBits(userId: string, serverId: string): Map<string, number> {
|
||||
const access = Access.for(this.db);
|
||||
const data = access.load(serverId);
|
||||
const out = new Map<string, number>([['', access.serverPerms(userId, serverId)]]);
|
||||
for (const c of data.channels) out.set(c.id, access.permsIn(data, userId, c.id));
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* D64a: a role manager may not raise her own effective permissions anywhere in the server with
|
||||
* a role or override write (lowering them is fine). Owner and admins are exempt (they have every
|
||||
* bit). Call inside the transaction after the write; throwing rolls it back.
|
||||
*/
|
||||
private requireNoOwnRaise(
|
||||
actor: Actor,
|
||||
userId: string,
|
||||
serverId: string,
|
||||
before: Map<string, number> | null,
|
||||
): void {
|
||||
if (!before || actor.privileged) return;
|
||||
const after = this.ownBits(userId, serverId);
|
||||
for (const [key, bits] of after) {
|
||||
if (bits & ~(before.get(key) ?? 0)) throw forbidden(OWN_RAISE);
|
||||
}
|
||||
}
|
||||
|
||||
/** D57: counted per attempt by someone allowed to manage roles. */
|
||||
private count(userId: string): void {
|
||||
if (!this.writes) return;
|
||||
if (!this.writes.allows(userId)) {
|
||||
throw new HttpError(
|
||||
429,
|
||||
'too_many_role_writes',
|
||||
`You can change roles and permissions at most ${ROLE_WRITES_PER_MINUTE} times a minute`,
|
||||
undefined,
|
||||
{ 'retry-after': String(this.writes.retryAfterSec(userId)) },
|
||||
);
|
||||
}
|
||||
this.writes.record(userId);
|
||||
}
|
||||
|
||||
private rows(serverId: string): RoleRow[] {
|
||||
return this.db
|
||||
.prepare('SELECT * FROM roles WHERE server_id = ? ORDER BY position DESC, id')
|
||||
.all(serverId) as RoleRow[];
|
||||
}
|
||||
|
||||
private role(serverId: string, roleId: string): RoleRow {
|
||||
const row = this.db
|
||||
.prepare('SELECT * FROM roles WHERE id = ? AND server_id = ?')
|
||||
.get(roleId, serverId) as RoleRow | undefined;
|
||||
if (!row) throw notFound('Role not found');
|
||||
return row;
|
||||
}
|
||||
|
||||
/** QA-153: unique per server after NFC and lowercasing in JS (SQLite lower() folds only A-Z). */
|
||||
private nameTaken(serverId: string, name: string, exceptId?: string): boolean {
|
||||
const key = roleNameKey(name);
|
||||
return this.rows(serverId).some((r) => r.id !== exceptId && roleNameKey(r.name) === key);
|
||||
}
|
||||
|
||||
/** Custom roles renumbered 1..n in their current order; returns the changed positions. */
|
||||
private renumber(serverId: string): { id: string; position: number }[] {
|
||||
const custom = this.rows(serverId)
|
||||
.filter((r) => r.is_everyone === 0)
|
||||
.reverse(); // lowest first
|
||||
const set = this.db.prepare('UPDATE roles SET position = ? WHERE id = ?');
|
||||
const changed: { id: string; position: number }[] = [];
|
||||
custom.forEach((r, i) => {
|
||||
if (r.position !== i + 1) {
|
||||
set.run(i + 1, r.id);
|
||||
changed.push({ id: r.id, position: i + 1 });
|
||||
}
|
||||
});
|
||||
return changed;
|
||||
}
|
||||
|
||||
private positions(serverId: string): { id: string; position: number }[] {
|
||||
return this.rows(serverId).map((r) => ({ id: r.id, position: r.position }));
|
||||
}
|
||||
|
||||
/** D40: a non-admin may act only on roles strictly below their top. */
|
||||
private requireBelow(actor: Actor, role: RoleRow): void {
|
||||
if (!actor.privileged && role.position >= actor.top) {
|
||||
throw forbidden('You can only manage roles below your highest role');
|
||||
}
|
||||
}
|
||||
|
||||
/** D40: a non-admin may only turn on bits they have themselves. */
|
||||
private requireGrantable(actor: Actor, before: number, after: number): void {
|
||||
const added = after & ~before;
|
||||
if (!actor.privileged && (added & ~actor.base) !== 0) {
|
||||
throw forbidden("You can't grant a permission you don't have");
|
||||
}
|
||||
}
|
||||
|
||||
// ---- roles ----
|
||||
|
||||
list(userId: string, serverId: string): RoleDto[] {
|
||||
Access.for(this.db).requireServerPerm(userId, serverId, 0);
|
||||
return serverRoles(this.db, serverId);
|
||||
}
|
||||
|
||||
create(userId: string, serverId: string, input: CreateRoleInput): RoleDto {
|
||||
this.actor(userId, serverId);
|
||||
this.count(userId);
|
||||
let shifted: { id: string; position: number }[] = [];
|
||||
const role = this.db.transaction(() => {
|
||||
const actor = this.actor(userId, serverId);
|
||||
const permissions = input.permissions ?? 0;
|
||||
this.requireGrantable(actor, 0, permissions);
|
||||
const custom = this.rows(serverId).filter((r) => r.is_everyone === 0);
|
||||
if (custom.length >= MAX_ROLES_PER_SERVER) {
|
||||
throw conflict(`A server can have at most ${MAX_ROLES_PER_SERVER} roles`);
|
||||
}
|
||||
if (this.nameTaken(serverId, input.name)) throw conflict('A role with that name exists');
|
||||
// Owner/admin: on top. A member: directly below their top (which moves up by one).
|
||||
let position = custom.length + 1;
|
||||
if (!actor.privileged) {
|
||||
if (actor.top < 1) throw forbidden('You can only manage roles below your highest role');
|
||||
position = actor.top;
|
||||
this.db
|
||||
.prepare(
|
||||
'UPDATE roles SET position = position + 1 WHERE server_id = ? AND is_everyone = 0 AND position >= ?',
|
||||
)
|
||||
.run(serverId, position);
|
||||
shifted = custom
|
||||
.filter((r) => r.position >= position)
|
||||
.map((r) => ({ id: r.id, position: r.position + 1 }));
|
||||
}
|
||||
const id = newId();
|
||||
this.db
|
||||
.prepare(
|
||||
`INSERT INTO roles (id, server_id, name, color, position, permissions, is_everyone, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, 0, ?)`,
|
||||
)
|
||||
.run(id, serverId, input.name, input.color ?? null, position, permissions, nowIso());
|
||||
return this.role(serverId, id);
|
||||
})();
|
||||
const hub = this.hub();
|
||||
if (shifted.length) {
|
||||
hub.toServer(serverId, 'role:reorder', { serverId, positions: shifted });
|
||||
}
|
||||
const dto = toRoleDto(role);
|
||||
hub.toServer(serverId, 'role:create', { role: dto });
|
||||
return dto;
|
||||
}
|
||||
|
||||
/** D56: only the fields sent change; the last write wins. */
|
||||
update(userId: string, serverId: string, roleId: string, input: UpdateRoleInput): RoleDto {
|
||||
this.actor(userId, serverId);
|
||||
this.count(userId);
|
||||
let permsChanged = false;
|
||||
const row = this.db.transaction(() => {
|
||||
const actor = this.actor(userId, serverId);
|
||||
const role = this.role(serverId, roleId);
|
||||
if (role.is_everyone === 1 && (input.name !== undefined || input.color !== undefined)) {
|
||||
throw badRequest("@everyone can't be renamed or given a colour");
|
||||
}
|
||||
this.requireBelow(actor, role);
|
||||
if (input.permissions !== undefined) {
|
||||
this.requireGrantable(actor, role.permissions, input.permissions);
|
||||
permsChanged = input.permissions !== role.permissions;
|
||||
}
|
||||
if (input.name !== undefined && this.nameTaken(serverId, input.name, roleId)) {
|
||||
throw conflict('A role with that name exists');
|
||||
}
|
||||
const mine = permsChanged && !actor.privileged ? this.ownBits(userId, serverId) : null;
|
||||
this.db
|
||||
.prepare(`UPDATE roles SET name = ?, color = ?, permissions = ? WHERE id = ?`)
|
||||
.run(
|
||||
input.name ?? role.name,
|
||||
input.color !== undefined ? input.color : role.color,
|
||||
input.permissions ?? role.permissions,
|
||||
roleId,
|
||||
);
|
||||
// D64a: a bits edit may not raise her own (the base grant rule above should already hold).
|
||||
this.requireNoOwnRaise(actor, userId, serverId, mine);
|
||||
return this.role(serverId, roleId);
|
||||
})();
|
||||
if (permsChanged) this.lifecycle.accessChanged?.(serverId, 'all');
|
||||
const dto = toRoleDto(row);
|
||||
this.hub().toServer(serverId, 'role:update', { role: dto });
|
||||
return dto;
|
||||
}
|
||||
|
||||
remove(userId: string, serverId: string, roleId: string): void {
|
||||
this.actor(userId, serverId);
|
||||
this.count(userId);
|
||||
let shifted: { id: string; position: number }[] = [];
|
||||
this.db.transaction(() => {
|
||||
const actor = this.actor(userId, serverId);
|
||||
const role = this.role(serverId, roleId);
|
||||
if (role.is_everyone === 1) throw badRequest("@everyone can't be deleted");
|
||||
this.requireBelow(actor, role);
|
||||
// D64a: deleting a lower role she holds that carries a channel deny would raise her bits.
|
||||
const mine = actor.privileged ? null : this.ownBits(userId, serverId);
|
||||
// member_roles and channel_overrides rows go with it (ON DELETE CASCADE).
|
||||
this.db.prepare('DELETE FROM roles WHERE id = ?').run(roleId);
|
||||
shifted = this.renumber(serverId);
|
||||
this.requireNoOwnRaise(actor, userId, serverId, mine);
|
||||
})();
|
||||
// Holders lose its bits and its overrides stop applying (the client drops the id on
|
||||
// role:delete from members and overrides).
|
||||
this.lifecycle.accessChanged?.(serverId, 'all');
|
||||
const hub = this.hub();
|
||||
hub.toServer(serverId, 'role:delete', { serverId, roleId });
|
||||
if (shifted.length) hub.toServer(serverId, 'role:reorder', { serverId, positions: shifted });
|
||||
}
|
||||
|
||||
/**
|
||||
* `roleIds`: every custom role, highest first. A member may only permute roles strictly below
|
||||
* their top; every role at or above it must keep its place (D40). Positions only rank, so
|
||||
* nobody's bits change and no AccessSync is needed.
|
||||
*/
|
||||
reorder(userId: string, serverId: string, roleIds: string[]): RoleDto[] {
|
||||
this.actor(userId, serverId);
|
||||
this.count(userId);
|
||||
const changed = this.db.transaction(() => {
|
||||
const actor = this.actor(userId, serverId);
|
||||
const everyone = this.rows(serverId).find((r) => r.is_everyone === 1);
|
||||
if (everyone && roleIds.includes(everyone.id)) {
|
||||
throw badRequest('@everyone always stays at the bottom');
|
||||
}
|
||||
const custom = this.rows(serverId).filter((r) => r.is_everyone === 0); // highest first
|
||||
const known = new Set(custom.map((r) => r.id));
|
||||
if (roleIds.length !== custom.length || roleIds.some((id) => !known.has(id))) {
|
||||
throw badRequest('List every role of the server exactly once');
|
||||
}
|
||||
if (!actor.privileged) {
|
||||
custom.forEach((r, i) => {
|
||||
if (r.position >= actor.top && roleIds[i] !== r.id) {
|
||||
throw forbidden('You can only move roles below your highest role');
|
||||
}
|
||||
});
|
||||
}
|
||||
const n = roleIds.length;
|
||||
const set = this.db.prepare('UPDATE roles SET position = ? WHERE id = ?');
|
||||
const out: { id: string; position: number }[] = [];
|
||||
const before = new Map(custom.map((r) => [r.id, r.position]));
|
||||
roleIds.forEach((id, i) => {
|
||||
const position = n - i;
|
||||
if (before.get(id) !== position) {
|
||||
set.run(position, id);
|
||||
out.push({ id, position });
|
||||
}
|
||||
});
|
||||
return out;
|
||||
})();
|
||||
if (changed.length) {
|
||||
this.hub().toServer(serverId, 'role:reorder', { serverId, positions: changed });
|
||||
}
|
||||
return serverRoles(this.db, serverId);
|
||||
}
|
||||
|
||||
// ---- member roles ----
|
||||
|
||||
/** The whole set as one checked write (M29-03): one forbidden role fails the lot. */
|
||||
setMemberRoles(
|
||||
userId: string,
|
||||
serverId: string,
|
||||
targetId: string,
|
||||
roleIds: string[],
|
||||
memberDto: (serverId: string, userId: string) => MemberDto,
|
||||
): MemberDto {
|
||||
this.actor(userId, serverId);
|
||||
this.count(userId);
|
||||
let changed = false;
|
||||
this.db.transaction(() => {
|
||||
const actor = this.actor(userId, serverId);
|
||||
const access = Access.for(this.db);
|
||||
const target = this.db
|
||||
.prepare('SELECT role, banned FROM members WHERE server_id = ? AND user_id = ?')
|
||||
.get(serverId, targetId) as { role: ServerRole; banned: number } | undefined;
|
||||
if (!target || target.banned === 1) throw notFound('Member not found');
|
||||
if ((target.role === 'owner' || target.role === 'admin') && actor.rank !== 'owner') {
|
||||
throw forbidden("Only the owner can change an admin's or the owner's roles");
|
||||
}
|
||||
const roles = new Map(this.rows(serverId).map((r) => [r.id, r]));
|
||||
for (const id of roleIds) {
|
||||
const r = roles.get(id);
|
||||
if (!r) throw badRequest('Unknown role');
|
||||
if (r.is_everyone === 1) throw badRequest('Everyone has @everyone');
|
||||
}
|
||||
if (!actor.privileged) {
|
||||
if (access.top(targetId, serverId) >= actor.top) {
|
||||
throw forbidden('You can only change roles of members below you');
|
||||
}
|
||||
for (const id of roleIds) this.requireBelow(actor, roles.get(id)!);
|
||||
}
|
||||
const current = (
|
||||
this.db
|
||||
.prepare('SELECT role_id FROM member_roles WHERE server_id = ? AND user_id = ?')
|
||||
.all(serverId, targetId) as { role_id: string }[]
|
||||
).map((r) => r.role_id);
|
||||
const next = new Set(roleIds);
|
||||
changed = current.length !== next.size || current.some((id) => !next.has(id));
|
||||
// D64a (safest reading, pending a design answer): a write on her own roles may not raise her own bits,
|
||||
// adding or removing (dropping a role that carries a channel deny raises them).
|
||||
const mine = targetId === userId && changed ? this.ownBits(userId, serverId) : null;
|
||||
this.db
|
||||
.prepare('DELETE FROM member_roles WHERE server_id = ? AND user_id = ?')
|
||||
.run(serverId, targetId);
|
||||
const add = this.db.prepare(
|
||||
'INSERT INTO member_roles (server_id, user_id, role_id) VALUES (?, ?, ?)',
|
||||
);
|
||||
for (const id of roleIds) add.run(serverId, targetId, id);
|
||||
this.requireNoOwnRaise(actor, userId, serverId, mine);
|
||||
})();
|
||||
if (changed) this.lifecycle.accessChanged?.(serverId, [targetId]);
|
||||
const member = memberDto(serverId, targetId);
|
||||
if (changed) this.hub().toServer(serverId, 'member:update', { member });
|
||||
return member;
|
||||
}
|
||||
|
||||
// ---- channel permissions ----
|
||||
|
||||
/**
|
||||
* The channel, for someone allowed to manage its permissions. D61: owner and admins reach every
|
||||
* channel of the server (names and overrides, never content); a member needs VIEW there (404
|
||||
* otherwise, the same body as a missing id) and MANAGE_ROLES (403).
|
||||
*/
|
||||
private manageableChannel(userId: string, serverId: string, channelId: string): ChannelRow {
|
||||
const access = Access.for(this.db);
|
||||
const ch = this.db
|
||||
.prepare('SELECT * FROM channels WHERE id = ? AND server_id = ?')
|
||||
.get(channelId, serverId) as ChannelRow | undefined;
|
||||
const rank = access.requireServerPerm(userId, serverId, 0);
|
||||
if (rank === 'owner' || rank === 'admin') {
|
||||
if (!ch) throw notFound('Channel not found');
|
||||
return ch;
|
||||
}
|
||||
if (!ch || !access.canView(userId, channelId)) throw notFound('Channel not found');
|
||||
access.requireServerPerm(userId, serverId, Perm.MANAGE_ROLES);
|
||||
return ch;
|
||||
}
|
||||
|
||||
getChannelPermissions(
|
||||
userId: string,
|
||||
serverId: string,
|
||||
channelId: string,
|
||||
): { channelId: string; overrides: OverrideDto[] } {
|
||||
this.manageableChannel(userId, serverId, channelId);
|
||||
return { channelId, overrides: channelOverrides(this.db, channelId) };
|
||||
}
|
||||
|
||||
/**
|
||||
* The whole override set (D56: replaces it). A member may change only the entries of
|
||||
* `@everyone` and roles strictly below their top, and only bits in their server-wide base
|
||||
* (D40, D64); entries they can't touch must come back unchanged.
|
||||
*/
|
||||
setChannelPermissions(
|
||||
userId: string,
|
||||
serverId: string,
|
||||
channelId: string,
|
||||
overrides: OverrideDto[],
|
||||
): { channelId: string; overrides: OverrideDto[] } {
|
||||
this.manageableChannel(userId, serverId, channelId);
|
||||
this.count(userId);
|
||||
let changed = false;
|
||||
this.db.transaction(() => {
|
||||
this.manageableChannel(userId, serverId, channelId);
|
||||
const actor = this.actor(userId, serverId);
|
||||
const roles = new Map(this.rows(serverId).map((r) => [r.id, r]));
|
||||
for (const o of overrides) if (!roles.has(o.roleId)) throw badRequest('Unknown role');
|
||||
const before = new Map(channelOverrides(this.db, channelId).map((o) => [o.roleId, o]));
|
||||
const after = new Map(overrides.filter((o) => o.allow || o.deny).map((o) => [o.roleId, o]));
|
||||
// D64: what she may grant is judged against her server-wide base, not her bits in this
|
||||
// channel; D64a then refuses the write if it raises her own bits anywhere (below).
|
||||
const here = actor.base;
|
||||
for (const id of new Set([...before.keys(), ...after.keys()])) {
|
||||
const b = before.get(id) ?? { allow: 0, deny: 0 };
|
||||
const a = after.get(id) ?? { allow: 0, deny: 0 };
|
||||
const diff = (a.allow ^ b.allow) | (a.deny ^ b.deny);
|
||||
if (!diff) continue;
|
||||
changed = true;
|
||||
if (actor.privileged) continue;
|
||||
const role = roles.get(id);
|
||||
if (role && role.is_everyone !== 1) this.requireBelow(actor, role);
|
||||
if (diff & ~here) {
|
||||
throw forbidden("You can't change a permission you don't have");
|
||||
}
|
||||
}
|
||||
if (!changed) return;
|
||||
const mine = actor.privileged ? null : this.ownBits(userId, serverId);
|
||||
this.db.prepare('DELETE FROM channel_overrides WHERE channel_id = ?').run(channelId);
|
||||
const add = this.db.prepare(
|
||||
'INSERT INTO channel_overrides (channel_id, role_id, allow, deny) VALUES (?, ?, ?, ?)',
|
||||
);
|
||||
for (const o of after.values()) add.run(channelId, o.roleId, o.allow, o.deny);
|
||||
// D64a: e.g. an allow on a lower role she holds would undo a superior's deny on her top.
|
||||
this.requireNoOwnRaise(actor, userId, serverId, mine);
|
||||
})();
|
||||
const now = channelOverrides(this.db, channelId);
|
||||
if (changed) {
|
||||
// D46: rooms first, so someone who just lost VIEW doesn't get the update.
|
||||
this.lifecycle.accessChanged?.(serverId, 'all');
|
||||
const row = this.db
|
||||
.prepare('SELECT * FROM channels WHERE id = ?')
|
||||
.get(channelId) as ChannelRow;
|
||||
const { position: _p, ...channel } = toChannelDto(row, now) as ChannelDto;
|
||||
this.hub().toChannel(channelId, 'channel:update', { channel });
|
||||
}
|
||||
return { channelId, overrides: now };
|
||||
}
|
||||
|
||||
/** D61: the channel-permissions page's list: names only, never content. */
|
||||
channelNames(userId: string, serverId: string): ChannelNameDto[] {
|
||||
Access.for(this.db).requireServerPerm(userId, serverId, Perm.MANAGE_ROLES);
|
||||
return Access.for(this.db).channelNamesForSettings(userId, serverId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
import {
|
||||
SEARCH_PAGE_SIZE,
|
||||
SEARCH_PER_MINUTE,
|
||||
threadNameFor,
|
||||
type SearchPageDto,
|
||||
type SearchQuery,
|
||||
type SearchResultDto,
|
||||
} from '@chat/shared';
|
||||
import { Access } from '../auth/access.js';
|
||||
import { Blocks, notBlockedAuthor } from '../auth/blocks.js';
|
||||
import { getServerRole, isDmMember } from '../auth/permissions.js';
|
||||
import type { DB } from '../db/index.js';
|
||||
import { HttpError, notFound } from '../lib/errors.js';
|
||||
import { ulidFloor } from '../lib/ids.js';
|
||||
import { RateWindow } from '../lib/rate-window.js';
|
||||
import { ftsQuery } from '../lib/search-query.js';
|
||||
import type { MessageRow, MessageService } from './messages.js';
|
||||
|
||||
/**
|
||||
* The highlight markers (U+0002, U+0003: control characters that message text can never contain,
|
||||
* because cleanMessageText strips them on every write) and the snippet length in tokens (D26).
|
||||
*/
|
||||
const SNIPPET = `snippet(messages_fts, 0, char(2), char(3), '…', 12)`;
|
||||
|
||||
/**
|
||||
* One 404 for every scope or channel the reader can't search: missing, not a member, banned,
|
||||
* a DM they aren't in, a channel in another server. The body never says which (M23-04).
|
||||
*/
|
||||
const nothingHere = () => notFound('Nothing to search here');
|
||||
|
||||
type Row = MessageRow & {
|
||||
snip: string | null;
|
||||
thread_id: string | null;
|
||||
thread_name: string | null;
|
||||
thread_created_by: string | null;
|
||||
thread_parent_author: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Message search (M23, DESIGN-0.5 section 2, D26): one server (all its text channels and their
|
||||
* threads) or one DM, newest first, 25 a page. Blocked authors are left out in SQL before the
|
||||
* LIMIT (D17). Only normal, non-deleted messages are in the index (the triggers in migration
|
||||
* 010), and the query is built by `ftsQuery`, never from raw user text.
|
||||
*/
|
||||
export class SearchService {
|
||||
constructor(
|
||||
private readonly db: DB,
|
||||
private readonly messages: MessageService,
|
||||
/** 30 searches a minute per person; null = off (RATE_LIMIT=false). */
|
||||
readonly limit: RateWindow | null = new RateWindow(SEARCH_PER_MINUTE, 60_000),
|
||||
) {}
|
||||
|
||||
search(userId: string, q: SearchQuery): SearchPageDto {
|
||||
const scope = this.scope(userId, q.scope, q.in);
|
||||
const match = ftsQuery(q.q);
|
||||
const filtered = !!(q.from || q.in || q.before || q.after || q.has);
|
||||
if (!match) {
|
||||
if (q.q.trim())
|
||||
throw new HttpError(400, 'empty_query', 'Type a word or number to search for');
|
||||
if (!filtered) throw new HttpError(400, 'empty_query', 'Type something to search for');
|
||||
}
|
||||
this.count(userId);
|
||||
|
||||
const where: string[] = [];
|
||||
const args: unknown[] = [];
|
||||
const and = (sql: string, ...values: unknown[]) => {
|
||||
where.push(sql);
|
||||
args.push(...values);
|
||||
};
|
||||
and("m.type = 'default' AND m.deleted_at IS NULL");
|
||||
if (match) and('messages_fts MATCH ?', match);
|
||||
and(scope.sql, ...scope.args);
|
||||
and(notBlockedAuthor('m.author_id'), userId);
|
||||
if (q.from) and('m.author_id = ?', q.from);
|
||||
if (q.after) and('m.id >= ?', ulidFloor(q.after));
|
||||
if (q.before) and('m.id < ?', ulidFloor(q.before));
|
||||
if (q.cursor) and('m.id < ?', q.cursor);
|
||||
if (q.has === 'file') and('EXISTS (SELECT 1 FROM attachments a WHERE a.message_id = m.id)');
|
||||
if (q.has === 'link') and("m.content LIKE '%://%'");
|
||||
|
||||
const rows = this.db
|
||||
.prepare(
|
||||
`SELECT m.*, ${match ? SNIPPET : 'NULL'} AS snip, t.name AS thread_name,
|
||||
t.created_by AS thread_created_by,
|
||||
(SELECT p.author_id FROM messages p WHERE p.id = t.parent_message_id) AS thread_parent_author
|
||||
FROM ${match ? 'messages_fts JOIN messages m ON m.rowid = messages_fts.rowid' : 'messages m'}
|
||||
LEFT JOIN threads t ON t.id = m.thread_id
|
||||
WHERE ${where.join(' AND ')}
|
||||
ORDER BY m.id DESC
|
||||
LIMIT ?`,
|
||||
)
|
||||
.all(...args, SEARCH_PAGE_SIZE + 1) as Row[];
|
||||
const page = rows.slice(0, SEARCH_PAGE_SIZE);
|
||||
const dtos = this.messages.hydrate(page, userId);
|
||||
const names = this.convNames(userId, page);
|
||||
const blocked = Blocks.for(this.db).blockedBy(userId);
|
||||
const results: SearchResultDto[] = page.map((r, i) => {
|
||||
const convId = (r.channel_id ?? r.dm_channel_id) as string;
|
||||
return {
|
||||
message: dtos[i]!,
|
||||
convId,
|
||||
convName: names.get(convId) ?? '',
|
||||
snippet: r.snip,
|
||||
...(r.thread_id
|
||||
? {
|
||||
threadId: r.thread_id,
|
||||
// D36 (QA-128): "Thread" across a block on the starter or the parent's author.
|
||||
threadName: threadNameFor(
|
||||
{
|
||||
name: r.thread_name ?? '',
|
||||
createdBy: r.thread_created_by,
|
||||
parentAuthorId: r.thread_parent_author,
|
||||
},
|
||||
(id) => blocked.has(id),
|
||||
),
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
});
|
||||
return {
|
||||
results,
|
||||
nextCursor: rows.length > SEARCH_PAGE_SIZE ? (page[page.length - 1]?.id ?? null) : null,
|
||||
};
|
||||
}
|
||||
|
||||
/** The SQL condition for the scope, after checking the reader may search it (404 if not). */
|
||||
private scope(
|
||||
userId: string,
|
||||
scopeId: string,
|
||||
channelId: string | undefined,
|
||||
): { sql: string; args: unknown[] } {
|
||||
const server = this.db.prepare('SELECT id FROM servers WHERE id = ?').get(scopeId);
|
||||
if (server) {
|
||||
// The member check: not a member, or banned, reads as "no such server".
|
||||
if (getServerRole(this.db, userId, scopeId) === null) throw nothingHere();
|
||||
// D45: only channels the reader can VIEW (thread replies carry their parent channel's id,
|
||||
// so `threadId` results and the "in thread" marker follow the parent's visibility too).
|
||||
const visible = Access.for(this.db).visibleChannelIds(userId, scopeId);
|
||||
if (channelId) {
|
||||
const ch = this.db
|
||||
.prepare("SELECT id FROM channels WHERE id = ? AND server_id = ? AND type = 'text'")
|
||||
.get(channelId, scopeId);
|
||||
if (!ch || !visible.has(channelId)) throw nothingHere(); // hidden = missing
|
||||
return { sql: 'm.channel_id = ?', args: [channelId] };
|
||||
}
|
||||
return {
|
||||
sql: `m.channel_id IN (SELECT id FROM channels WHERE server_id = ? AND type = 'text')
|
||||
AND m.channel_id IN (SELECT value FROM json_each(?))`,
|
||||
args: [scopeId, JSON.stringify([...visible])],
|
||||
};
|
||||
}
|
||||
// A DM or group DM: requireDmAccess's rule (a current member), with the neutral 404.
|
||||
const dm = this.db.prepare('SELECT id FROM dm_channels WHERE id = ?').get(scopeId);
|
||||
if (!dm || !isDmMember(this.db, userId, scopeId)) throw nothingHere();
|
||||
if (channelId) throw nothingHere(); // `in` narrows a server search only
|
||||
return { sql: 'm.dm_channel_id = ?', args: [scopeId] };
|
||||
}
|
||||
|
||||
private count(userId: string): void {
|
||||
if (!this.limit) return;
|
||||
if (!this.limit.allows(userId)) {
|
||||
throw new HttpError(
|
||||
429,
|
||||
'too_many_searches',
|
||||
`You can search at most ${SEARCH_PER_MINUTE} times a minute`,
|
||||
undefined,
|
||||
{ 'retry-after': String(this.limit.retryAfterSec(userId)) },
|
||||
);
|
||||
}
|
||||
this.limit.record(userId);
|
||||
}
|
||||
|
||||
/** Channel name, group name, or the other members' names for a DM. */
|
||||
private convNames(userId: string, rows: readonly MessageRow[]): Map<string, string> {
|
||||
const out = new Map<string, string>();
|
||||
for (const r of rows) {
|
||||
const id = (r.channel_id ?? r.dm_channel_id) as string;
|
||||
if (out.has(id)) continue;
|
||||
if (r.channel_id) {
|
||||
const c = this.db.prepare('SELECT name FROM channels WHERE id = ?').get(id) as
|
||||
{ name: string } | undefined;
|
||||
out.set(id, c?.name ?? '');
|
||||
continue;
|
||||
}
|
||||
const dm = this.db.prepare('SELECT name FROM dm_channels WHERE id = ?').get(id) as
|
||||
{ name: string | null } | undefined;
|
||||
if (dm?.name) {
|
||||
out.set(id, dm.name);
|
||||
continue;
|
||||
}
|
||||
const others = this.db
|
||||
.prepare(
|
||||
`SELECT u.display_name FROM dm_members d JOIN users u ON u.id = d.user_id
|
||||
WHERE d.dm_channel_id = ? AND d.user_id <> ? ORDER BY u.display_name COLLATE NOCASE`,
|
||||
)
|
||||
.all(id, userId) as { display_name: string }[];
|
||||
out.set(id, others.map((o) => o.display_name).join(', '));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import { existsSync } from 'node:fs';
|
||||
import type { DB } from '../db/index.js';
|
||||
import { inspectImage, type MediaService } from './media.js';
|
||||
import type { UploadService } from './uploads.js';
|
||||
|
||||
interface Logger {
|
||||
warn: (obj: object, msg: string) => void;
|
||||
info: (obj: object, msg: string) => void;
|
||||
}
|
||||
|
||||
export interface LegacyIconResult {
|
||||
converted: number;
|
||||
/** Server ids whose 0.1 icon couldn't be converted (missing or unreadable file). */
|
||||
failed: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Data step of migration 005 (M8): put each 0.1 server icon (servers.icon_path, a file in the
|
||||
* uploads dir) through the media pipeline as a centred square crop and record it in icon_media.
|
||||
*
|
||||
* Idempotent: only rows with icon_path set and icon_media still NULL are touched, and the write is
|
||||
* conditional on that, so running it again (or concurrently) converts nothing twice. The 0.1 file
|
||||
* and icon_path are left alone so a rollback to 0.1.2 still shows the icon; they're cleared when an
|
||||
* admin changes or removes the icon in 0.2. A file that fails is logged and skipped (the server
|
||||
* shows initials in 0.2; nothing is deleted), and retried on the next start.
|
||||
*/
|
||||
export async function convertLegacyServerIcons(
|
||||
db: DB,
|
||||
uploads: UploadService,
|
||||
media: MediaService,
|
||||
log?: Logger,
|
||||
): Promise<LegacyIconResult> {
|
||||
const rows = db
|
||||
.prepare(
|
||||
'SELECT id, icon_path FROM servers WHERE icon_path IS NOT NULL AND icon_media IS NULL ORDER BY id',
|
||||
)
|
||||
.all() as { id: string; icon_path: string }[];
|
||||
const result: LegacyIconResult = { converted: 0, failed: [] };
|
||||
for (const row of rows) {
|
||||
try {
|
||||
const src = uploads.filePath(row.icon_path);
|
||||
if (!existsSync(src)) throw new Error('icon file missing');
|
||||
const img = await inspectImage(src);
|
||||
const side = Math.min(img.width, img.height);
|
||||
const crop = {
|
||||
x: Math.floor((img.width - side) / 2),
|
||||
y: Math.floor((img.height - side) / 2),
|
||||
w: side,
|
||||
h: side,
|
||||
};
|
||||
const mediaId = await media.ingest(src, 'serverIcon', crop);
|
||||
const changed = db
|
||||
.prepare(
|
||||
'UPDATE servers SET icon_media = ? WHERE id = ? AND icon_path = ? AND icon_media IS NULL',
|
||||
)
|
||||
.run(mediaId, row.id, row.icon_path).changes;
|
||||
if (changed === 0) {
|
||||
media.remove(mediaId);
|
||||
continue;
|
||||
}
|
||||
result.converted++;
|
||||
} catch (err) {
|
||||
result.failed.push(row.id);
|
||||
log?.warn(
|
||||
{ err, serverId: row.id, iconPath: row.icon_path },
|
||||
'could not convert a 0.1 server icon; it stays on disk and the server shows initials',
|
||||
);
|
||||
}
|
||||
}
|
||||
if (result.converted > 0) {
|
||||
log?.info({ converted: result.converted }, 'converted 0.1 server icons to the media pipeline');
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,479 @@
|
||||
import type {
|
||||
BanDto,
|
||||
CategoryDto,
|
||||
ChannelDto,
|
||||
CreateServerInput,
|
||||
MemberDto,
|
||||
OverrideDto,
|
||||
ServerDetailDto,
|
||||
ServerDto,
|
||||
ServerRole,
|
||||
UpdateServerInput,
|
||||
} from '@chat/shared';
|
||||
import {
|
||||
canModerate,
|
||||
getServerRole,
|
||||
isBanned,
|
||||
requireServerRole,
|
||||
type ChannelRow,
|
||||
type CategoryRow,
|
||||
} from '../auth/permissions.js';
|
||||
import type { DB } from '../db/index.js';
|
||||
import { HttpError, badRequest, forbidden, notFound } from '../lib/errors.js';
|
||||
import { newId, nowIso } from '../lib/ids.js';
|
||||
import { insertEveryoneRole } from '../db/everyone.js';
|
||||
import { Access } from '../auth/access.js';
|
||||
import { densePositions, viewerChannelDto } from './positions.js';
|
||||
import { serverOverrides, serverRoles } from './role-dto.js';
|
||||
import type { Lifecycle } from './lifecycle.js';
|
||||
import type { RealtimeHub } from '../realtime/hub.js';
|
||||
|
||||
export type ServerImage = 'icon' | 'banner';
|
||||
|
||||
export interface ServerRow {
|
||||
id: string;
|
||||
name: string;
|
||||
/** 0.1 icon file in the uploads dir; kept for rollback until the icon is changed in 0.2. */
|
||||
icon_path: string | null;
|
||||
icon_media: string | null;
|
||||
banner_media: string | null;
|
||||
owner_id: string;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
interface MemberJoinRow {
|
||||
server_id: string;
|
||||
user_id: string;
|
||||
role: ServerRole;
|
||||
joined_at: string;
|
||||
username: string;
|
||||
display_name: string;
|
||||
avatar_media: string | null;
|
||||
role_ids: string | null;
|
||||
}
|
||||
|
||||
export const toCategoryDto = (r: CategoryRow): CategoryDto => ({
|
||||
id: r.id,
|
||||
serverId: r.server_id,
|
||||
name: r.name,
|
||||
position: r.position,
|
||||
});
|
||||
|
||||
export const toChannelDto = (r: ChannelRow, overrides: OverrideDto[] = []): ChannelDto => ({
|
||||
id: r.id,
|
||||
serverId: r.server_id,
|
||||
categoryId: r.category_id,
|
||||
type: r.type,
|
||||
name: r.name,
|
||||
position: r.position,
|
||||
topic: r.topic,
|
||||
overrides,
|
||||
});
|
||||
|
||||
const toMemberDto = (r: MemberJoinRow): MemberDto => ({
|
||||
serverId: r.server_id,
|
||||
userId: r.user_id,
|
||||
username: r.username,
|
||||
displayName: r.display_name,
|
||||
avatar: r.avatar_media,
|
||||
role: r.role,
|
||||
joinedAt: r.joined_at,
|
||||
roleIds: r.role_ids ? r.role_ids.split(',') : [],
|
||||
});
|
||||
|
||||
function toServerBase(r: ServerRow): Omit<ServerDto, 'myRole'> {
|
||||
return {
|
||||
id: r.id,
|
||||
name: r.name,
|
||||
icon: r.icon_media,
|
||||
banner: r.banner_media,
|
||||
ownerId: r.owner_id,
|
||||
createdAt: r.created_at,
|
||||
};
|
||||
}
|
||||
|
||||
const MEMBER_SELECT = `SELECT m.server_id, m.user_id, m.role, m.joined_at, u.username, u.display_name, u.avatar_media,
|
||||
(SELECT group_concat(role_id) FROM (SELECT mr.role_id FROM member_roles mr JOIN roles r ON r.id = mr.role_id
|
||||
WHERE mr.server_id = m.server_id AND mr.user_id = m.user_id ORDER BY r.position DESC)) AS role_ids
|
||||
FROM members m JOIN users u ON u.id = m.user_id`;
|
||||
|
||||
/**
|
||||
* Servers, membership, roles, kick/ban, ownership. Every public method takes the acting user and
|
||||
* checks permissions itself, so routes can't forget to.
|
||||
*/
|
||||
export class ServerService {
|
||||
constructor(
|
||||
private readonly db: DB,
|
||||
private readonly hub: () => RealtimeHub,
|
||||
private readonly lifecycle: Lifecycle = {},
|
||||
) {}
|
||||
|
||||
private getRow(serverId: string): ServerRow | undefined {
|
||||
return this.db.prepare('SELECT * FROM servers WHERE id = ?').get(serverId) as
|
||||
ServerRow | undefined;
|
||||
}
|
||||
|
||||
/** Server ids the user may receive pushes for (non-banned memberships). */
|
||||
serverIdsFor(userId: string): string[] {
|
||||
return (
|
||||
this.db
|
||||
.prepare('SELECT server_id FROM members WHERE user_id = ? AND banned = 0')
|
||||
.all(userId) as { server_id: string }[]
|
||||
).map((r) => r.server_id);
|
||||
}
|
||||
|
||||
list(userId: string): ServerDto[] {
|
||||
const rows = this.db
|
||||
.prepare(
|
||||
`SELECT s.*, m.role AS my_role FROM servers s JOIN members m ON m.server_id = s.id
|
||||
WHERE m.user_id = ? AND m.banned = 0 ORDER BY m.joined_at, s.id`,
|
||||
)
|
||||
.all(userId) as (ServerRow & { my_role: ServerRole })[];
|
||||
return rows.map((r) => ({ ...toServerBase(r), myRole: r.my_role }));
|
||||
}
|
||||
|
||||
/** Full server with categories and channels (any member). */
|
||||
get(userId: string, serverId: string): ServerDetailDto {
|
||||
const myRole = requireServerRole(this.db, userId, serverId);
|
||||
return this.detail(serverId, userId, myRole);
|
||||
}
|
||||
|
||||
/**
|
||||
* D45: the server as `userId` sees it: only the channels they can VIEW. Categories are all
|
||||
* sent, even empty ones (names aren't secret; the client hides an empty category).
|
||||
*/
|
||||
detail(serverId: string, userId: string, myRole: ServerRole): ServerDetailDto {
|
||||
const row = this.getRow(serverId);
|
||||
if (!row) throw notFound('Server not found');
|
||||
const visible = Access.for(this.db).visibleChannelIds(userId, serverId);
|
||||
const categories = this.db
|
||||
.prepare('SELECT * FROM categories WHERE server_id = ? ORDER BY position, id')
|
||||
.all(serverId) as CategoryRow[];
|
||||
const channels = this.db
|
||||
.prepare('SELECT * FROM channels WHERE server_id = ? ORDER BY position, id')
|
||||
.all(serverId) as ChannelRow[];
|
||||
// D63, D63a: channel positions are this viewer's dense numbers per category; categories are
|
||||
// the same dense list for everyone (an all-hidden category looks exactly like an empty one).
|
||||
const dense = densePositions(channels, visible);
|
||||
const overrides = serverOverrides(this.db, serverId);
|
||||
return {
|
||||
...toServerBase(row),
|
||||
myRole,
|
||||
roles: serverRoles(this.db, serverId),
|
||||
myRoleIds: (
|
||||
this.db
|
||||
.prepare('SELECT role_id FROM member_roles WHERE server_id = ? AND user_id = ?')
|
||||
.all(serverId, userId) as { role_id: string }[]
|
||||
).map((r) => r.role_id),
|
||||
categories: categories.map((c, position) => ({ ...toCategoryDto(c), position })),
|
||||
channels: channels
|
||||
.filter((c) => visible.has(c.id))
|
||||
.map((c) => viewerChannelDto(c, dense, overrides.get(c.id) ?? [])),
|
||||
};
|
||||
}
|
||||
|
||||
/** Creates the server with the creator as owner, plus default categories and channels. */
|
||||
create(userId: string, input: CreateServerInput): ServerDetailDto {
|
||||
const id = newId();
|
||||
const now = nowIso();
|
||||
this.db.transaction(() => {
|
||||
this.db
|
||||
.prepare(
|
||||
'INSERT INTO servers (id, name, icon_path, owner_id, created_at) VALUES (?, ?, NULL, ?, ?)',
|
||||
)
|
||||
.run(id, input.name, userId, now);
|
||||
this.db
|
||||
.prepare(
|
||||
"INSERT INTO members (server_id, user_id, role, joined_at, banned) VALUES (?, ?, 'owner', ?, 0)",
|
||||
)
|
||||
.run(id, userId, now);
|
||||
insertEveryoneRole(this.db, id, now); // D42: same transaction as the server
|
||||
const textCat = newId();
|
||||
const voiceCat = newId();
|
||||
const cat = this.db.prepare(
|
||||
'INSERT INTO categories (id, server_id, name, position) VALUES (?, ?, ?, ?)',
|
||||
);
|
||||
cat.run(textCat, id, 'Text channels', 0);
|
||||
cat.run(voiceCat, id, 'Voice channels', 1);
|
||||
const ch = this.db.prepare(
|
||||
'INSERT INTO channels (id, server_id, category_id, type, name, position, topic) VALUES (?, ?, ?, ?, ?, 0, NULL)',
|
||||
);
|
||||
ch.run(newId(), id, textCat, 'text', 'general');
|
||||
ch.run(newId(), id, voiceCat, 'voice', 'General');
|
||||
})();
|
||||
const detail = this.detail(id, userId, 'owner');
|
||||
this.hub().joinServer(userId, id);
|
||||
this.hub().joinChannels(
|
||||
userId,
|
||||
detail.channels.map((c) => c.id),
|
||||
);
|
||||
this.hub().toUser(userId, 'server:join', { server: detail });
|
||||
return detail;
|
||||
}
|
||||
|
||||
update(userId: string, serverId: string, input: UpdateServerInput): ServerDto {
|
||||
const myRole = requireServerRole(this.db, userId, serverId, 'admin');
|
||||
if (input.name !== undefined) {
|
||||
this.db.prepare('UPDATE servers SET name = ? WHERE id = ?').run(input.name, serverId);
|
||||
}
|
||||
const base = toServerBase(this.getRow(serverId) as ServerRow);
|
||||
this.hub().toServer(serverId, 'server:update', { server: base });
|
||||
return { ...base, myRole };
|
||||
}
|
||||
|
||||
/** Admin+ check before an upload body is read (403 member, 404 outsider or banned). */
|
||||
requireAdmin(userId: string, serverId: string): void {
|
||||
requireServerRole(this.db, userId, serverId, 'admin');
|
||||
}
|
||||
|
||||
/**
|
||||
* Admin+: point the icon or banner at a media id (or null). Call inside the media swap
|
||||
* transaction so the role is re-checked at the moment of the write. Setting or clearing the icon
|
||||
* also drops the 0.1 icon file reference (returned as `legacyPath` for the caller to delete).
|
||||
*/
|
||||
setImage(
|
||||
userId: string,
|
||||
serverId: string,
|
||||
which: ServerImage,
|
||||
mediaId: string | null,
|
||||
): { previous: string | null; legacyPath: string | null } {
|
||||
requireServerRole(this.db, userId, serverId, 'admin');
|
||||
const row = this.getRow(serverId) as ServerRow;
|
||||
if (which === 'icon') {
|
||||
this.db
|
||||
.prepare('UPDATE servers SET icon_media = ?, icon_path = NULL WHERE id = ?')
|
||||
.run(mediaId, serverId);
|
||||
return { previous: row.icon_media, legacyPath: row.icon_path };
|
||||
}
|
||||
this.db.prepare('UPDATE servers SET banner_media = ? WHERE id = ?').run(mediaId, serverId);
|
||||
return { previous: row.banner_media, legacyPath: null };
|
||||
}
|
||||
|
||||
/** Tell the server's members about a change (if `emit`); returns the DTO with the caller's role. */
|
||||
broadcastUpdate(userId: string, serverId: string, emit = true): ServerDto {
|
||||
const myRole = requireServerRole(this.db, userId, serverId);
|
||||
const base = toServerBase(this.getRow(serverId) as ServerRow);
|
||||
if (emit) this.hub().toServer(serverId, 'server:update', { server: base });
|
||||
return { ...base, myRole };
|
||||
}
|
||||
|
||||
/** Owner only. Returns the server's image files for the caller to delete. */
|
||||
delete(
|
||||
userId: string,
|
||||
serverId: string,
|
||||
): { media: (string | null)[]; legacyPath: string | null } {
|
||||
requireServerRole(this.db, userId, serverId, 'owner');
|
||||
const row = this.getRow(serverId) as ServerRow;
|
||||
const voiceChannels = (
|
||||
this.db
|
||||
.prepare("SELECT id FROM channels WHERE server_id = ? AND type = 'voice'")
|
||||
.all(serverId) as { id: string }[]
|
||||
).map((r) => r.id);
|
||||
const allChannels = this.channelIdsOf(serverId);
|
||||
this.db.transaction(() => {
|
||||
// read_states.channel_id has no FK (it also holds DM ids), so clean it up by hand.
|
||||
this.db
|
||||
.prepare(
|
||||
`DELETE FROM read_states WHERE channel_id IN (SELECT id FROM channels WHERE server_id = ?)
|
||||
OR channel_id IN (SELECT t.id FROM threads t JOIN channels c ON c.id = t.channel_id
|
||||
WHERE c.server_id = ?)`,
|
||||
)
|
||||
.run(serverId, serverId);
|
||||
this.db.prepare('DELETE FROM servers WHERE id = ?').run(serverId);
|
||||
})();
|
||||
this.hub().toServer(serverId, 'server:delete', { serverId });
|
||||
for (const id of voiceChannels) this.lifecycle.voiceChannelDeleted?.(id, serverId);
|
||||
this.hub().closeServer(serverId);
|
||||
for (const id of allChannels) this.hub().closeChannel(id);
|
||||
return { media: [row.icon_media, row.banner_media], legacyPath: row.icon_path };
|
||||
}
|
||||
|
||||
/** Owner hands the server to another member; the old owner becomes an admin. */
|
||||
transferOwnership(userId: string, serverId: string, newOwnerId: string): ServerDto {
|
||||
requireServerRole(this.db, userId, serverId, 'owner');
|
||||
if (newOwnerId === userId) throw badRequest('You already own this server');
|
||||
if (getServerRole(this.db, newOwnerId, serverId) === null) {
|
||||
throw badRequest('The new owner must be a member of the server');
|
||||
}
|
||||
this.db.transaction(() => {
|
||||
this.db.prepare('UPDATE servers SET owner_id = ? WHERE id = ?').run(newOwnerId, serverId);
|
||||
const setRole = this.db.prepare(
|
||||
'UPDATE members SET role = ? WHERE server_id = ? AND user_id = ?',
|
||||
);
|
||||
setRole.run('owner', serverId, newOwnerId);
|
||||
setRole.run('admin', serverId, userId);
|
||||
})();
|
||||
const base = toServerBase(this.getRow(serverId) as ServerRow);
|
||||
this.hub().toServer(serverId, 'server:update', { server: base });
|
||||
for (const id of [newOwnerId, userId]) {
|
||||
this.hub().toServer(serverId, 'member:update', { member: this.memberDto(serverId, id) });
|
||||
}
|
||||
// D59: both the new and the old owner, in the same tick, before the response.
|
||||
this.lifecycle.accessChanged?.(serverId, [newOwnerId, userId]);
|
||||
return { ...base, myRole: 'admin' };
|
||||
}
|
||||
|
||||
// ---- members ----
|
||||
|
||||
memberDto(serverId: string, userId: string): MemberDto {
|
||||
const row = this.db
|
||||
.prepare(`${MEMBER_SELECT} WHERE m.server_id = ? AND m.user_id = ?`)
|
||||
.get(serverId, userId) as MemberJoinRow | undefined;
|
||||
if (!row) throw notFound('Member not found');
|
||||
return toMemberDto(row);
|
||||
}
|
||||
|
||||
listMembers(userId: string, serverId: string): MemberDto[] {
|
||||
requireServerRole(this.db, userId, serverId);
|
||||
const rows = this.db
|
||||
.prepare(
|
||||
`${MEMBER_SELECT} WHERE m.server_id = ? AND m.banned = 0
|
||||
ORDER BY CASE m.role WHEN 'owner' THEN 0 WHEN 'admin' THEN 1 ELSE 2 END, u.display_name COLLATE NOCASE`,
|
||||
)
|
||||
.all(serverId) as MemberJoinRow[];
|
||||
return rows.map(toMemberDto);
|
||||
}
|
||||
|
||||
/** Only the owner changes roles (admin <-> member). Ownership moves via transferOwnership. */
|
||||
setRole(userId: string, serverId: string, targetId: string, role: 'admin' | 'member'): MemberDto {
|
||||
requireServerRole(this.db, userId, serverId, 'owner');
|
||||
const targetRole = getServerRole(this.db, targetId, serverId);
|
||||
if (targetRole === null) throw notFound('Member not found');
|
||||
if (targetRole === 'owner') throw forbidden("The owner's role can't be changed");
|
||||
this.db
|
||||
.prepare('UPDATE members SET role = ? WHERE server_id = ? AND user_id = ?')
|
||||
.run(role, serverId, targetId);
|
||||
const member = this.memberDto(serverId, targetId);
|
||||
this.hub().toServer(serverId, 'member:update', { member });
|
||||
// D46: promote/demote changes what they can see (admins see private channels, D37).
|
||||
this.lifecycle.accessChanged?.(serverId, [targetId]);
|
||||
return member;
|
||||
}
|
||||
|
||||
/** Throws unless actor may moderate target. Returns the target's current role (null if not a member). */
|
||||
private requireModeration(
|
||||
actorId: string,
|
||||
serverId: string,
|
||||
targetId: string,
|
||||
): ServerRole | null {
|
||||
const actorRole = requireServerRole(this.db, actorId, serverId, 'admin');
|
||||
if (actorId === targetId) throw badRequest("You can't do that to yourself");
|
||||
const targetRole = getServerRole(this.db, targetId, serverId);
|
||||
if (!canModerate(actorRole, targetRole)) {
|
||||
throw forbidden(
|
||||
targetRole === 'owner'
|
||||
? "The server owner can't be kicked or banned"
|
||||
: 'Only the owner can act on admins',
|
||||
);
|
||||
}
|
||||
return targetRole;
|
||||
}
|
||||
|
||||
kick(actorId: string, serverId: string, targetId: string): void {
|
||||
const targetRole = this.requireModeration(actorId, serverId, targetId);
|
||||
if (targetRole === null) throw notFound('Member not found');
|
||||
this.db
|
||||
.prepare('DELETE FROM members WHERE server_id = ? AND user_id = ?')
|
||||
.run(serverId, targetId);
|
||||
this.removedFromServer(serverId, targetId, 'kick');
|
||||
}
|
||||
|
||||
/** Leave voluntarily. The owner must transfer ownership or delete the server instead. */
|
||||
leave(userId: string, serverId: string): void {
|
||||
const role = requireServerRole(this.db, userId, serverId);
|
||||
if (role === 'owner') {
|
||||
throw new HttpError(
|
||||
409,
|
||||
'owner_cannot_leave',
|
||||
'Transfer ownership or delete the server before leaving',
|
||||
);
|
||||
}
|
||||
this.db
|
||||
.prepare('DELETE FROM members WHERE server_id = ? AND user_id = ?')
|
||||
.run(serverId, userId);
|
||||
this.removedFromServer(serverId, userId, 'leave');
|
||||
}
|
||||
|
||||
/** Ban keeps a members row with banned=1 so old invites can't bring the user back. */
|
||||
ban(actorId: string, serverId: string, targetId: string): void {
|
||||
const exists = this.db.prepare('SELECT 1 FROM users WHERE id = ?').get(targetId);
|
||||
if (!exists) throw notFound('User not found');
|
||||
const targetRole = this.requireModeration(actorId, serverId, targetId);
|
||||
this.db.transaction(() => {
|
||||
this.db
|
||||
.prepare(
|
||||
`INSERT INTO members (server_id, user_id, role, joined_at, banned) VALUES (?, ?, 'member', ?, 1)
|
||||
ON CONFLICT(server_id, user_id) DO UPDATE SET banned = 1, role = 'member'`,
|
||||
)
|
||||
.run(serverId, targetId, nowIso());
|
||||
// D42: the members row stays (banned = 1), so its member_roles don't cascade; drop them here.
|
||||
this.db
|
||||
.prepare('DELETE FROM member_roles WHERE server_id = ? AND user_id = ?')
|
||||
.run(serverId, targetId);
|
||||
})();
|
||||
if (targetRole !== null) this.removedFromServer(serverId, targetId, 'ban');
|
||||
}
|
||||
|
||||
unban(actorId: string, serverId: string, targetId: string): void {
|
||||
requireServerRole(this.db, actorId, serverId, 'admin');
|
||||
const res = this.db
|
||||
.prepare('DELETE FROM members WHERE server_id = ? AND user_id = ? AND banned = 1')
|
||||
.run(serverId, targetId);
|
||||
if (res.changes === 0) throw notFound('Ban not found');
|
||||
}
|
||||
|
||||
listBans(actorId: string, serverId: string): BanDto[] {
|
||||
requireServerRole(this.db, actorId, serverId, 'admin');
|
||||
return (
|
||||
this.db
|
||||
.prepare(
|
||||
`SELECT u.id, u.username, u.display_name FROM members m JOIN users u ON u.id = m.user_id
|
||||
WHERE m.server_id = ? AND m.banned = 1 ORDER BY u.username COLLATE NOCASE`,
|
||||
)
|
||||
.all(serverId) as { id: string; username: string; display_name: string }[]
|
||||
).map((r) => ({ userId: r.id, username: r.username, displayName: r.display_name }));
|
||||
}
|
||||
|
||||
/** Every channel id of a server (for room bookkeeping). */
|
||||
private channelIdsOf(serverId: string): string[] {
|
||||
return (
|
||||
this.db.prepare('SELECT id FROM channels WHERE server_id = ?').all(serverId) as {
|
||||
id: string;
|
||||
}[]
|
||||
).map((r) => r.id);
|
||||
}
|
||||
|
||||
private removedFromServer(serverId: string, userId: string, reason: 'kick' | 'ban' | 'leave') {
|
||||
this.hub().leaveServer(userId, serverId);
|
||||
// D46: kick, ban and leave also leave every channel room of that server.
|
||||
this.hub().leaveChannels(userId, this.channelIdsOf(serverId));
|
||||
this.hub().toUser(userId, 'server:remove', { serverId, reason });
|
||||
this.hub().toServer(serverId, 'member:remove', { serverId, userId, reason });
|
||||
this.lifecycle.memberRemoved?.(serverId, userId);
|
||||
}
|
||||
|
||||
/** Add a user as a member (invite join). Caller has validated the invite and ban state. */
|
||||
addMember(serverId: string, userId: string): void {
|
||||
this.db
|
||||
.prepare(
|
||||
"INSERT INTO members (server_id, user_id, role, joined_at, banned) VALUES (?, ?, 'member', ?, 0)",
|
||||
)
|
||||
.run(serverId, userId, nowIso());
|
||||
}
|
||||
|
||||
/** Push the right events after a join (outside the DB transaction). */
|
||||
announceJoin(serverId: string, userId: string): void {
|
||||
this.hub().joinServer(userId, serverId);
|
||||
const detail = this.detail(serverId, userId, 'member');
|
||||
this.hub().joinChannels(
|
||||
userId,
|
||||
detail.channels.map((c) => c.id),
|
||||
);
|
||||
this.hub().toUser(userId, 'server:join', { server: detail });
|
||||
this.hub().toServer(serverId, 'member:join', { member: this.memberDto(serverId, userId) });
|
||||
}
|
||||
|
||||
isBanned(userId: string, serverId: string): boolean {
|
||||
return isBanned(this.db, userId, serverId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import type { InstanceSettingsDto, InstanceSettingsPatch } from '@chat/shared';
|
||||
import type { DB } from '../db/index.js';
|
||||
import { badRequest } from '../lib/errors.js';
|
||||
|
||||
export class SettingsService {
|
||||
/**
|
||||
* maxUploadCeilingMb: MAX_UPLOAD_MB from .env. It is the default and the ceiling (the reverse
|
||||
* proxy's client_max_body_size is sized for it); admins can only lower it.
|
||||
*/
|
||||
constructor(
|
||||
private readonly db: DB,
|
||||
private readonly maxUploadCeilingMb = 25,
|
||||
) {}
|
||||
|
||||
private get(key: string): string | undefined {
|
||||
const row = this.db.prepare('SELECT value FROM instance_settings WHERE key = ?').get(key) as
|
||||
{ value: string } | undefined;
|
||||
return row?.value;
|
||||
}
|
||||
|
||||
private set(key: string, value: string): void {
|
||||
this.db
|
||||
.prepare(
|
||||
'INSERT INTO instance_settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value',
|
||||
)
|
||||
.run(key, value);
|
||||
}
|
||||
|
||||
isRegistrationOpen(): boolean {
|
||||
return this.get('registration_open') !== 'false';
|
||||
}
|
||||
|
||||
getAll(): InstanceSettingsDto {
|
||||
return {
|
||||
registrationOpen: this.isRegistrationOpen(),
|
||||
maxUploadMb: Math.min(
|
||||
Number(this.get('max_upload_mb') ?? this.maxUploadCeilingMb),
|
||||
this.maxUploadCeilingMb,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
update(patch: InstanceSettingsPatch): InstanceSettingsDto {
|
||||
if (patch.maxUploadMb !== undefined && patch.maxUploadMb > this.maxUploadCeilingMb) {
|
||||
throw badRequest(
|
||||
`The upload limit can be at most ${this.maxUploadCeilingMb} MB (MAX_UPLOAD_MB in .env)`,
|
||||
);
|
||||
}
|
||||
this.db.transaction(() => {
|
||||
if (patch.registrationOpen !== undefined)
|
||||
this.set('registration_open', String(patch.registrationOpen));
|
||||
if (patch.maxUploadMb !== undefined) this.set('max_upload_mb', String(patch.maxUploadMb));
|
||||
})();
|
||||
return this.getAll();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
import {
|
||||
Perm,
|
||||
cleanDisplayText,
|
||||
THREAD_NAME_DEFAULT,
|
||||
THREAD_STARTS_PER_MINUTE,
|
||||
threadNameFor,
|
||||
tokensToShortcodes,
|
||||
type MessageDto,
|
||||
type ThreadDto,
|
||||
} from '@chat/shared';
|
||||
import { Blocks, notBlockedAuthor } from '../auth/blocks.js';
|
||||
import { canReadMessage, requireChannelAccess } from '../auth/permissions.js';
|
||||
import type { DB } from '../db/index.js';
|
||||
import { HttpError, notFound } from '../lib/errors.js';
|
||||
import { newId, nowIso } from '../lib/ids.js';
|
||||
import { RateWindow } from '../lib/rate-window.js';
|
||||
import type { RealtimeHub } from '../realtime/hub.js';
|
||||
import type { MessageRow, MessageService } from './messages.js';
|
||||
|
||||
interface ThreadRow {
|
||||
id: string;
|
||||
channel_id: string;
|
||||
parent_message_id: string;
|
||||
name: string;
|
||||
created_by: string | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
/** The default name: the parent's first 60 characters as one line (custom emoji as :name:). */
|
||||
export function defaultThreadName(content: string): string {
|
||||
const line = cleanDisplayText(tokensToShortcodes(content).replace(/\s+/g, ' ')).trim();
|
||||
return [...line].slice(0, THREAD_NAME_DEFAULT).join('').trim() || 'Thread';
|
||||
}
|
||||
|
||||
/**
|
||||
* Threads (M25, DESIGN-0.5 section 4, D25, D29). A thread hangs off one normal message in a
|
||||
* server text channel; its replies are messages with the channel's channel_id plus thread_id, and
|
||||
* everything about reading and writing them goes through MessageService with a `thread` conv
|
||||
* (access is the channel's). This service starts, lists, follows and deletes threads.
|
||||
*/
|
||||
export class ThreadService {
|
||||
constructor(
|
||||
private readonly db: DB,
|
||||
private readonly hub: () => RealtimeHub,
|
||||
private readonly messages: MessageService,
|
||||
/** 10 thread starts a minute per person; null = off (RATE_LIMIT=false). */
|
||||
readonly starts: RateWindow | null = new RateWindow(THREAD_STARTS_PER_MINUTE, 60_000),
|
||||
) {}
|
||||
|
||||
private row(id: string): ThreadRow | undefined {
|
||||
return this.db.prepare('SELECT * FROM threads WHERE id = ?').get(id) as ThreadRow | undefined;
|
||||
}
|
||||
|
||||
/** One thread as the reader sees it (counts leave out people they blocked). */
|
||||
private toDtos(rows: readonly ThreadRow[], readerId: string | null): ThreadDto[] {
|
||||
const live = `r.thread_id = ? AND r.type = 'default' AND r.deleted_at IS NULL
|
||||
AND ${notBlockedAuthor('r.author_id')}`;
|
||||
const stats = this.db.prepare(
|
||||
`SELECT COUNT(*) AS n, MAX(r.created_at) AS last FROM messages r WHERE ${live}`,
|
||||
);
|
||||
const follows = this.db.prepare(
|
||||
'SELECT following FROM thread_follows WHERE thread_id = ? AND user_id = ?',
|
||||
);
|
||||
const server = this.db.prepare('SELECT server_id FROM channels WHERE id = ?');
|
||||
const parent = this.db.prepare('SELECT author_id, deleted_at FROM messages WHERE id = ?');
|
||||
const blocked = readerId ? Blocks.for(this.db).blockedBy(readerId) : new Set<string>();
|
||||
return rows.map((t) => {
|
||||
const p = parent.get(t.parent_message_id) as
|
||||
{ author_id: string | null; deleted_at: string | null } | undefined;
|
||||
const s = stats.get(t.id, readerId ?? '') as { n: number; last: string | null };
|
||||
const f = readerId
|
||||
? (follows.get(t.id, readerId) as { following: number } | undefined)
|
||||
: undefined;
|
||||
return {
|
||||
id: t.id,
|
||||
// D36 (QA-128): "Thread" for a reader who blocked the starter or the parent's author.
|
||||
name: threadNameFor(
|
||||
{ name: t.name, createdBy: t.created_by, parentAuthorId: p?.author_id },
|
||||
(id) => blocked.has(id),
|
||||
),
|
||||
replyCount: s.n,
|
||||
lastReplyAt: s.last,
|
||||
channelId: t.channel_id,
|
||||
serverId: (server.get(t.channel_id) as { server_id: string }).server_id,
|
||||
parentMessageId: t.parent_message_id,
|
||||
createdBy: t.created_by,
|
||||
parentAuthorId: p && !p.deleted_at ? p.author_id : null,
|
||||
createdAt: t.created_at,
|
||||
following: f?.following === 1,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
private count(userId: string): void {
|
||||
if (!this.starts) return;
|
||||
if (!this.starts.allows(userId)) {
|
||||
throw new HttpError(
|
||||
429,
|
||||
'too_many_threads',
|
||||
`You can start at most ${THREAD_STARTS_PER_MINUTE} threads a minute`,
|
||||
undefined,
|
||||
{ 'retry-after': String(this.starts.retryAfterSec(userId)) },
|
||||
);
|
||||
}
|
||||
this.starts.record(userId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Start a thread on a message (4b). Only a normal, live message in a server text channel that
|
||||
* the user can post in: not a system message, a DM or group DM, or a reply in a thread (no
|
||||
* nesting). A message that already has a thread is 409 with that thread in `details.thread`.
|
||||
* Starting follows it and marks it read up to the parent (D29).
|
||||
*/
|
||||
start(userId: string, messageId: string, name?: string): ThreadDto {
|
||||
const m = this.db.prepare('SELECT * FROM messages WHERE id = ?').get(messageId) as
|
||||
MessageRow | undefined;
|
||||
if (!m || m.deleted_at || !canReadMessage(this.db, userId, messageId)) {
|
||||
throw notFound('Message not found');
|
||||
}
|
||||
if (!m.channel_id) {
|
||||
throw new HttpError(400, 'threads_not_in_dms', 'Threads are for server channels only');
|
||||
}
|
||||
if (m.thread_id) {
|
||||
throw new HttpError(400, 'nested_thread', "A reply in a thread can't start another thread");
|
||||
}
|
||||
if (m.type === 'system') {
|
||||
throw new HttpError(400, 'system_message', "System messages can't start a thread");
|
||||
}
|
||||
// D38: starting a thread needs SEND_IN_THREADS and SEND in the channel (text channels only).
|
||||
const need = Perm.SEND_MESSAGES | Perm.SEND_IN_THREADS;
|
||||
const c = this.messages.conv(userId, { kind: 'channel', id: m.channel_id }, need);
|
||||
const existing = this.db
|
||||
.prepare('SELECT * FROM threads WHERE parent_message_id = ?')
|
||||
.get(messageId) as ThreadRow | undefined;
|
||||
if (existing) throw this.already(existing, userId);
|
||||
this.count(userId);
|
||||
const id = newId();
|
||||
const thread = this.db
|
||||
.transaction((): ThreadRow | null => {
|
||||
this.messages.conv(userId, { kind: 'channel', id: m.channel_id as string }, need); // D59
|
||||
const again = this.db
|
||||
.prepare('SELECT * FROM threads WHERE parent_message_id = ?')
|
||||
.get(messageId) as ThreadRow | undefined;
|
||||
if (again) return again;
|
||||
this.db
|
||||
.prepare(
|
||||
`INSERT INTO threads (id, channel_id, parent_message_id, name, created_by, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?)`,
|
||||
)
|
||||
.run(id, m.channel_id, messageId, name || defaultThreadName(m.content), userId, nowIso());
|
||||
this.messages.setFollow(userId, id, true);
|
||||
this.messages.setRead(userId, id, messageId);
|
||||
return null;
|
||||
})
|
||||
.immediate();
|
||||
if (thread) throw this.already(thread, userId);
|
||||
const dto = this.toDtos([this.row(id) as ThreadRow], userId)[0] as ThreadDto;
|
||||
if (c.kind === 'channel') {
|
||||
const hub = this.hub();
|
||||
hub.toChannel(c.id, 'thread:create', { thread: { ...dto, following: false } });
|
||||
hub.toUser(userId, 'thread:follow', { threadId: id, following: true });
|
||||
hub.toChannel(c.id, 'message:update', {
|
||||
message: this.messages.hydrate([m])[0] as MessageDto,
|
||||
});
|
||||
}
|
||||
return dto;
|
||||
}
|
||||
|
||||
private already(t: ThreadRow, userId: string): HttpError {
|
||||
return new HttpError(409, 'thread_exists', 'This message already has a thread', {
|
||||
thread: this.toDtos([t], userId)[0],
|
||||
});
|
||||
}
|
||||
|
||||
/** A thread and its parent (null once the parent was deleted: "Original message was deleted"). */
|
||||
get(userId: string, threadId: string): { thread: ThreadDto; parent: MessageDto | null } {
|
||||
this.messages.conv(userId, { kind: 'thread', id: threadId });
|
||||
const t = this.row(threadId) as ThreadRow;
|
||||
const parent = this.db
|
||||
.prepare('SELECT * FROM messages WHERE id = ? AND deleted_at IS NULL')
|
||||
.get(t.parent_message_id) as MessageRow | undefined;
|
||||
const blocked =
|
||||
parent &&
|
||||
this.db
|
||||
.prepare('SELECT 1 FROM blocks WHERE blocker_id = ? AND blocked_id = ?')
|
||||
.get(userId, parent.author_id);
|
||||
return {
|
||||
thread: this.toDtos([t], userId)[0] as ThreadDto,
|
||||
parent: parent && !blocked ? (this.messages.hydrate([parent], userId)[0] ?? null) : null,
|
||||
};
|
||||
}
|
||||
|
||||
/** The channel's threads, newest activity first (the newest live reply, else the start). */
|
||||
list(userId: string, channelId: string): ThreadDto[] {
|
||||
this.messages.conv(userId, { kind: 'channel', id: channelId });
|
||||
const rows = this.db
|
||||
.prepare(
|
||||
`SELECT t.* FROM threads t WHERE t.channel_id = ?
|
||||
ORDER BY COALESCE((SELECT MAX(r.id) FROM messages r
|
||||
WHERE r.thread_id = t.id AND r.deleted_at IS NULL
|
||||
AND ${notBlockedAuthor('r.author_id')}), t.id) DESC
|
||||
LIMIT 100`,
|
||||
)
|
||||
.all(channelId, userId) as ThreadRow[];
|
||||
return this.toDtos(rows, userId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Follow or unfollow (D29). Anyone who can read the channel. Following a thread you never read
|
||||
* starts it at its newest reply, so you don't get its whole history as unread.
|
||||
*/
|
||||
follow(userId: string, threadId: string, following: boolean): ThreadDto {
|
||||
this.messages.conv(userId, { kind: 'thread', id: threadId });
|
||||
const changed = this.db.transaction(() => {
|
||||
const ch = this.messages.setFollow(userId, threadId, following);
|
||||
if (following) {
|
||||
const newest = this.db
|
||||
.prepare('SELECT MAX(id) AS id FROM messages WHERE thread_id = ?')
|
||||
.get(threadId) as { id: string | null };
|
||||
const t = this.row(threadId) as ThreadRow;
|
||||
this.messages.setRead(userId, threadId, newest.id ?? t.parent_message_id);
|
||||
}
|
||||
return ch;
|
||||
})();
|
||||
if (changed) this.hub().toUser(userId, 'thread:follow', { threadId, following });
|
||||
return this.toDtos([this.row(threadId) as ThreadRow], userId)[0] as ThreadDto;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a thread and every reply in it (server admins and the owner; not in the design, see
|
||||
* STATUS). The parent message stays. Replies' files go with them.
|
||||
*/
|
||||
delete(userId: string, threadId: string): void {
|
||||
const c = this.messages.conv(userId, { kind: 'thread', id: threadId });
|
||||
if (c.kind !== 'thread') return;
|
||||
// Section 7: MANAGE_MESSAGES in the parent channel (owner and admins have it).
|
||||
requireChannelAccess(this.db, userId, c.channelId, Perm.MANAGE_MESSAGES);
|
||||
const t = this.row(threadId) as ThreadRow;
|
||||
this.messages.dropThread(threadId);
|
||||
this.hub().toChannel(c.channelId, 'thread:delete', {
|
||||
serverId: c.serverId,
|
||||
channelId: c.channelId,
|
||||
threadId,
|
||||
parentMessageId: t.parent_message_id,
|
||||
});
|
||||
const parent = this.db
|
||||
.prepare('SELECT * FROM messages WHERE id = ? AND deleted_at IS NULL')
|
||||
.get(t.parent_message_id) as MessageRow | undefined;
|
||||
if (parent) {
|
||||
this.hub().toChannel(c.channelId, 'message:update', {
|
||||
message: this.messages.hydrate([parent])[0] as MessageDto,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
import type { AttachmentDto } from '@chat/shared';
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import { createWriteStream, mkdirSync, readdirSync, renameSync, rmSync, statSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import type { Readable } from 'node:stream';
|
||||
import { pipeline } from 'node:stream/promises';
|
||||
import { canReadMessage } from '../auth/permissions.js';
|
||||
import type { DB } from '../db/index.js';
|
||||
import { badRequest, HttpError, notFound } from '../lib/errors.js';
|
||||
import { sanitizeFilename, sanitizeMime, sniffImage, type ImageInfo } from '../lib/files.js';
|
||||
import { newId, nowIso } from '../lib/ids.js';
|
||||
import { scrubImage } from '../lib/images.js';
|
||||
|
||||
export interface AttachmentRow {
|
||||
id: string;
|
||||
message_id: string | null;
|
||||
uploader_id: string;
|
||||
path: string;
|
||||
filename: string;
|
||||
mime: string;
|
||||
size: number;
|
||||
width: number | null;
|
||||
height: number | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
const SNIFF_BYTES = 64 * 1024;
|
||||
export const tooLarge = (mb: number) =>
|
||||
new HttpError(413, 'file_too_large', `Files can be at most ${mb} MB`);
|
||||
|
||||
const isInline = (mime: string) =>
|
||||
['image/png', 'image/jpeg', 'image/gif', 'image/webp'].includes(mime);
|
||||
|
||||
export function toAttachmentDto(r: AttachmentRow): AttachmentDto {
|
||||
return {
|
||||
id: r.id,
|
||||
filename: r.filename,
|
||||
mime: r.mime,
|
||||
size: r.size,
|
||||
width: r.width,
|
||||
height: r.height,
|
||||
isImage: isInline(r.mime),
|
||||
url: `/api/attachments/${r.id}/${encodeURIComponent(r.filename)}`,
|
||||
};
|
||||
}
|
||||
|
||||
export interface StoredFile {
|
||||
name: string;
|
||||
size: number;
|
||||
image: ImageInfo | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Files live in `uploadsDir` under random names (no extension, no user input in the path).
|
||||
* Attachments are uploaded first (message_id NULL), then claimed by a message.
|
||||
*/
|
||||
export class UploadService {
|
||||
constructor(
|
||||
private readonly db: DB,
|
||||
readonly dir: string,
|
||||
) {
|
||||
mkdirSync(dir, { recursive: true });
|
||||
}
|
||||
|
||||
/** Random on-disk name: 26-char ULID + 8 random hex chars. */
|
||||
private newName(): string {
|
||||
return `${newId()}-${randomBytes(4).toString('hex')}`;
|
||||
}
|
||||
|
||||
/** Absolute path for a stored name; refuses anything that isn't one of our generated names. */
|
||||
filePath(name: string): string {
|
||||
if (!/^[0-9A-Z]{26}-[0-9a-f]{8}$/.test(name)) throw notFound('File not found');
|
||||
return path.join(this.dir, name);
|
||||
}
|
||||
|
||||
/** Stream to disk, enforcing maxBytes ourselves too (belt and braces with multipart's limit). */
|
||||
async store(
|
||||
stream: Readable & { truncated?: boolean },
|
||||
maxBytes: number,
|
||||
maxMb: number,
|
||||
): Promise<StoredFile> {
|
||||
const name = this.newName();
|
||||
const dest = this.filePath(name);
|
||||
let size = 0;
|
||||
const head: Buffer[] = [];
|
||||
let headLen = 0;
|
||||
try {
|
||||
await pipeline(
|
||||
stream,
|
||||
async function* (source: AsyncIterable<Buffer>) {
|
||||
for await (const chunk of source) {
|
||||
size += chunk.length;
|
||||
if (size > maxBytes) throw tooLarge(maxMb);
|
||||
if (headLen < SNIFF_BYTES) {
|
||||
head.push(chunk);
|
||||
headLen += chunk.length;
|
||||
}
|
||||
yield chunk;
|
||||
}
|
||||
},
|
||||
createWriteStream(dest, { flags: 'wx', mode: 0o640 }),
|
||||
);
|
||||
if (stream.truncated) throw tooLarge(maxMb);
|
||||
} catch (err) {
|
||||
rmSync(dest, { force: true });
|
||||
const e = err as { code?: string; statusCode?: number };
|
||||
if (e.code === 'FST_REQ_FILE_TOO_LARGE' || e.statusCode === 413) throw tooLarge(maxMb);
|
||||
throw err;
|
||||
}
|
||||
if (size === 0) {
|
||||
rmSync(dest, { force: true });
|
||||
throw badRequest('The file is empty');
|
||||
}
|
||||
const sniffed = sniffImage(Buffer.concat(head));
|
||||
if (!sniffed) return { name, size, image: null };
|
||||
// Images (detected by magic bytes) are re-encoded: orientation applied, EXIF/GPS/XMP dropped.
|
||||
const tmp = `${dest}.tmp`;
|
||||
try {
|
||||
const out = await scrubImage(dest, tmp, sniffed);
|
||||
renameSync(tmp, dest);
|
||||
return {
|
||||
name,
|
||||
size: out.size,
|
||||
image: { mime: sniffed.mime, width: out.width, height: out.height },
|
||||
};
|
||||
} catch (err) {
|
||||
rmSync(tmp, { force: true });
|
||||
rmSync(dest, { force: true });
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/** Record an uploaded file as an unattached attachment owned by the uploader. */
|
||||
create(
|
||||
uploaderId: string,
|
||||
file: StoredFile,
|
||||
filename: string | undefined,
|
||||
declaredMime: string | undefined,
|
||||
): AttachmentDto {
|
||||
const row: AttachmentRow = {
|
||||
id: newId(),
|
||||
message_id: null,
|
||||
uploader_id: uploaderId,
|
||||
path: file.name,
|
||||
filename: sanitizeFilename(filename),
|
||||
// Images: the type we detected. Other files: declared type for display only (always served as a download).
|
||||
mime: file.image?.mime ?? nonImageMime(sanitizeMime(declaredMime)),
|
||||
size: file.size,
|
||||
width: file.image?.width ?? null,
|
||||
height: file.image?.height ?? null,
|
||||
created_at: nowIso(),
|
||||
};
|
||||
this.db
|
||||
.prepare(
|
||||
`INSERT INTO attachments (id, message_id, uploader_id, path, filename, mime, size, width, height, created_at)
|
||||
VALUES (@id, @message_id, @uploader_id, @path, @filename, @mime, @size, @width, @height, @created_at)`,
|
||||
)
|
||||
.run(row);
|
||||
return toAttachmentDto(row);
|
||||
}
|
||||
|
||||
get(id: string): AttachmentRow | undefined {
|
||||
return this.db.prepare('SELECT * FROM attachments WHERE id = ?').get(id) as
|
||||
AttachmentRow | undefined;
|
||||
}
|
||||
|
||||
/** The attachment if the viewer may download it: its uploader before it's sent, else readers of the message. */
|
||||
requireViewable(userId: string, id: string): AttachmentRow {
|
||||
const row = this.get(id);
|
||||
if (!row) throw notFound('File not found');
|
||||
const ok = row.message_id
|
||||
? canReadMessage(this.db, userId, row.message_id)
|
||||
: row.uploader_id === userId;
|
||||
if (!ok) throw notFound('File not found');
|
||||
return row;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the browser must revalidate a file on every use (`private, no-cache` + ETag). D58: all
|
||||
* files are, server-channel ones included, because any channel can become private later and a
|
||||
* long-cached file would outlive the access. A member gets a cheap 304; someone who lost access
|
||||
* gets the 404 (the access check runs before the ETag is compared).
|
||||
*/
|
||||
isPrivate(_row: AttachmentRow): boolean {
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Claim pending uploads for a message (call inside the message transaction). */
|
||||
claim(userId: string, messageId: string, ids: readonly string[]): void {
|
||||
const stmt = this.db.prepare(
|
||||
'UPDATE attachments SET message_id = ? WHERE id = ? AND uploader_id = ? AND message_id IS NULL',
|
||||
);
|
||||
for (const id of ids) {
|
||||
if (stmt.run(messageId, id, userId).changes !== 1)
|
||||
throw badRequest('Attachment not found or already used');
|
||||
}
|
||||
}
|
||||
|
||||
forMessages(messageIds: readonly string[]): Map<string, AttachmentDto[]> {
|
||||
const out = new Map<string, AttachmentDto[]>();
|
||||
if (messageIds.length === 0) return out;
|
||||
const rows = this.db
|
||||
.prepare(
|
||||
`SELECT * FROM attachments WHERE message_id IN (${messageIds.map(() => '?').join(',')}) ORDER BY id`,
|
||||
)
|
||||
.all(...messageIds) as AttachmentRow[];
|
||||
for (const r of rows) {
|
||||
const list = out.get(r.message_id as string) ?? [];
|
||||
list.push(toAttachmentDto(r));
|
||||
out.set(r.message_id as string, list);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Remove a message's files (soft-deleted messages keep no content or files). */
|
||||
deleteForMessage(messageId: string): void {
|
||||
const rows = this.db
|
||||
.prepare('SELECT path FROM attachments WHERE message_id = ?')
|
||||
.all(messageId) as { path: string }[];
|
||||
this.db.prepare('DELETE FROM attachments WHERE message_id = ?').run(messageId);
|
||||
for (const r of rows) this.removeFile(r.path);
|
||||
}
|
||||
|
||||
removeFile(name: string | null): void {
|
||||
if (!name) return;
|
||||
try {
|
||||
rmSync(this.filePath(name), { force: true });
|
||||
} catch {
|
||||
/* not one of ours */
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Housekeeping (hourly): drop uploads never attached to a message after `maxAgeMs`, and files on
|
||||
* disk no row points at (left behind by cascades such as channel or server deletion).
|
||||
*/
|
||||
purge(maxAgeMs = 24 * 3_600_000, now = Date.now()): { orphans: number; files: number } {
|
||||
const cutoff = new Date(now - maxAgeMs).toISOString();
|
||||
const stale = this.db
|
||||
.prepare('SELECT path FROM attachments WHERE message_id IS NULL AND created_at < ?')
|
||||
.all(cutoff) as { path: string }[];
|
||||
this.db
|
||||
.prepare('DELETE FROM attachments WHERE message_id IS NULL AND created_at < ?')
|
||||
.run(cutoff);
|
||||
for (const r of stale) this.removeFile(r.path);
|
||||
|
||||
const referenced = new Set(
|
||||
(
|
||||
this.db
|
||||
.prepare(
|
||||
'SELECT path AS p FROM attachments UNION SELECT icon_path AS p FROM servers WHERE icon_path IS NOT NULL',
|
||||
)
|
||||
.all() as { p: string }[]
|
||||
).map((r) => r.p),
|
||||
);
|
||||
let files = 0;
|
||||
for (const name of readdirSync(this.dir)) {
|
||||
if (referenced.has(name) || !/^[0-9A-Z]{26}-[0-9a-f]{8}$/.test(name)) continue;
|
||||
const full = path.join(this.dir, name);
|
||||
// Grace period so a file being uploaded right now (row not written yet) isn't removed.
|
||||
if (now - statSync(full).mtimeMs < 3_600_000) continue;
|
||||
rmSync(full, { force: true });
|
||||
files++;
|
||||
}
|
||||
return { orphans: stale.length, files };
|
||||
}
|
||||
}
|
||||
|
||||
/** Never let a non-image upload claim an inline-able image type. */
|
||||
function nonImageMime(m: string): string {
|
||||
return m.startsWith('image/') ||
|
||||
m.includes('html') ||
|
||||
m.includes('xml') ||
|
||||
m.includes('javascript')
|
||||
? 'application/octet-stream'
|
||||
: m;
|
||||
}
|
||||
@@ -0,0 +1,312 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import {
|
||||
DEFAULT_THEME,
|
||||
THEME_PRESETS,
|
||||
themeSchema,
|
||||
type MeDto,
|
||||
type PresencePref,
|
||||
type ProfileDto,
|
||||
type Theme,
|
||||
type ThemeFallbackReason,
|
||||
type UpdateMeInput,
|
||||
type UpdateProfileInput,
|
||||
type UserProfileFields,
|
||||
} from '@chat/shared';
|
||||
import type { DB } from '../db/index.js';
|
||||
import { HttpError, notFound } from '../lib/errors.js';
|
||||
import type { RealtimeHub } from '../realtime/hub.js';
|
||||
import { canSeeUser, visibleTo } from './presence.js';
|
||||
|
||||
export interface UserRow {
|
||||
id: string;
|
||||
username: string;
|
||||
display_name: string;
|
||||
password_hash: string;
|
||||
/** Never used (0.1.x); avatar_media replaced it in migration 004. */
|
||||
avatar_path: string | null;
|
||||
avatar_media: string | null;
|
||||
banner_media: string | null;
|
||||
banner_color: string | null;
|
||||
about: string;
|
||||
pronouns: string;
|
||||
status: string;
|
||||
theme_json: string | null;
|
||||
created_at: string;
|
||||
is_instance_admin: number;
|
||||
presence: PresencePref;
|
||||
}
|
||||
|
||||
function rawTheme(json: string | null): Record<string, unknown> | null {
|
||||
if (!json) return null;
|
||||
try {
|
||||
const v: unknown = JSON.parse(json);
|
||||
return v && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, unknown>) : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The stored theme for display. A preset this version doesn't know (D19) shows as Dark; a known
|
||||
* preset with an invalid field (D20) keeps its preset. Either way the stored accent, size and
|
||||
* compact are kept where each is valid (the default otherwise), and the result is flagged so the
|
||||
* client never writes the stand-in back. Anything without a string preset is corrupt: null.
|
||||
*/
|
||||
export function parseTheme(json: string | null): {
|
||||
theme: Theme | null;
|
||||
/** Why the theme is a stand-in (D21, QA-85); false when it is the stored theme as is. */
|
||||
fallback: false | ThemeFallbackReason;
|
||||
} {
|
||||
const raw = rawTheme(json);
|
||||
if (!raw) return { theme: null, fallback: false };
|
||||
const parsed = themeSchema.safeParse(raw);
|
||||
if (parsed.success) return { theme: parsed.data, fallback: false };
|
||||
if (typeof raw.preset !== 'string') return { theme: null, fallback: false };
|
||||
const known = (THEME_PRESETS as readonly string[]).includes(raw.preset);
|
||||
const field = <K extends keyof Theme>(k: K): Theme[K] => {
|
||||
const one = themeSchema.shape[k].safeParse(raw[k]);
|
||||
return one.success ? (one.data as Theme[K]) : DEFAULT_THEME[k];
|
||||
};
|
||||
return {
|
||||
theme: {
|
||||
preset: known ? (raw.preset as Theme['preset']) : 'dark',
|
||||
accent: field('accent'),
|
||||
fontScale: field('fontScale'),
|
||||
compact: field('compact'),
|
||||
},
|
||||
fallback: known ? 'invalidField' : 'unknownPreset',
|
||||
};
|
||||
}
|
||||
|
||||
export function toProfileFields(row: UserRow): UserProfileFields {
|
||||
return {
|
||||
id: row.id,
|
||||
username: row.username,
|
||||
displayName: row.display_name,
|
||||
avatar: row.avatar_media,
|
||||
banner: row.banner_media,
|
||||
bannerColor: row.banner_color,
|
||||
about: row.about,
|
||||
pronouns: row.pronouns,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The stored theme's version (D20), which baseUpdatedAt must match. A 0.4 save stamps updatedAt
|
||||
* inside theme_json, so no migration (0.3 ignores it). QA-86: a theme stored without one (saved
|
||||
* by 0.3, including during a rollback) gets a version made from its contents, so null means only
|
||||
* "nothing stored", and a 0.3 save made after a device's change was based changes the version.
|
||||
*/
|
||||
function themeUpdatedAt(json: string | null): string | null {
|
||||
if (json === null) return null;
|
||||
const raw = rawTheme(json);
|
||||
if (typeof raw?.updatedAt === 'string') return raw.updatedAt;
|
||||
return legacyThemeVersion(json);
|
||||
}
|
||||
|
||||
/**
|
||||
* JSON with object keys sorted at every level and no whitespace, so the same value always gives
|
||||
* the same text. Built as a string (never as an object), so a stored `__proto__` key stays data.
|
||||
*/
|
||||
export function canonicalJson(v: unknown): string {
|
||||
if (Array.isArray(v)) return `[${v.map(canonicalJson).join(',')}]`;
|
||||
if (v && typeof v === 'object') {
|
||||
const keys = Object.keys(v).sort();
|
||||
return `{${keys.map((k) => `${JSON.stringify(k)}:${canonicalJson((v as Record<string, unknown>)[k])}`).join(',')}}`;
|
||||
}
|
||||
return JSON.stringify(v) ?? 'null';
|
||||
}
|
||||
|
||||
/**
|
||||
* QA-86: the version of a theme stored without updatedAt (saved by 0.3), from a canonical form of
|
||||
* its JSON: the same theme gives the same version whatever its key order or whitespace, and any
|
||||
* edit (e.g. a 0.3 save during a rollback) changes it. Unparseable text is hashed as it is.
|
||||
*/
|
||||
export function legacyThemeVersion(json: string): string {
|
||||
let text = json;
|
||||
try {
|
||||
text = canonicalJson(JSON.parse(json));
|
||||
} catch {
|
||||
/* corrupt: its raw text is still a stable version */
|
||||
}
|
||||
return `legacy:${createHash('sha256').update(text).digest('hex').slice(0, 16)}`;
|
||||
}
|
||||
|
||||
/** A new updatedAt, strictly after the current one (two saves in one millisecond stay distinct). */
|
||||
function nextUpdatedAt(current: string | null): string {
|
||||
const now = Date.now();
|
||||
const prev = current ? Date.parse(current) : NaN;
|
||||
return new Date(Number.isFinite(prev) && prev >= now ? prev + 1 : now).toISOString();
|
||||
}
|
||||
|
||||
function meTheme(
|
||||
json: string | null,
|
||||
): Pick<
|
||||
MeDto,
|
||||
'theme' | 'themeFallback' | 'themeFallbackReason' | 'themeUpdatedAt' | 'themeWriterTab'
|
||||
> {
|
||||
const { theme, fallback } = parseTheme(json);
|
||||
const version = themeUpdatedAt(json);
|
||||
const writer = rawTheme(json)?.writer as { tab?: unknown } | undefined;
|
||||
const tab =
|
||||
writer && typeof writer === 'object' && typeof writer.tab === 'string'
|
||||
? { themeWriterTab: writer.tab }
|
||||
: {};
|
||||
return fallback
|
||||
? { theme, themeFallback: true, themeFallbackReason: fallback, themeUpdatedAt: version, ...tab }
|
||||
: { theme, themeUpdatedAt: version, ...tab };
|
||||
}
|
||||
|
||||
export function toMeDto(row: UserRow): MeDto {
|
||||
return {
|
||||
...toProfileFields(row),
|
||||
isInstanceAdmin: row.is_instance_admin === 1,
|
||||
...meTheme(row.theme_json),
|
||||
createdAt: row.created_at,
|
||||
presence: row.presence,
|
||||
};
|
||||
}
|
||||
|
||||
export type ProfileImage = 'avatar' | 'banner';
|
||||
const IMAGE_COLUMN: Record<ProfileImage, 'avatar_media' | 'banner_media'> = {
|
||||
avatar: 'avatar_media',
|
||||
banner: 'banner_media',
|
||||
};
|
||||
|
||||
export class UserService {
|
||||
constructor(
|
||||
private readonly db: DB,
|
||||
private readonly hub: () => RealtimeHub,
|
||||
) {}
|
||||
|
||||
getById(id: string): UserRow | undefined {
|
||||
return this.db.prepare('SELECT * FROM users WHERE id = ?').get(id) as UserRow | undefined;
|
||||
}
|
||||
|
||||
private require(id: string): UserRow {
|
||||
const row = this.getById(id);
|
||||
if (!row) throw notFound('User not found');
|
||||
return row;
|
||||
}
|
||||
|
||||
/**
|
||||
* Push the user's public profile to everyone who can see them (shared server rooms and DM
|
||||
* partners, via presence.visibleTo) and to their own tabs. Nobody else gets it.
|
||||
*/
|
||||
broadcast(userId: string): void {
|
||||
const row = this.getById(userId);
|
||||
if (!row) return;
|
||||
const payload = { user: toProfileFields(row) };
|
||||
const { serverIds, userIds } = visibleTo(this.db, userId);
|
||||
this.hub().toAudience(serverIds, [...userIds, userId], 'user:update', payload);
|
||||
}
|
||||
|
||||
updateMe(userId: string, input: UpdateMeInput): MeDto {
|
||||
const before = this.require(userId);
|
||||
const sets: string[] = [];
|
||||
const params: unknown[] = [];
|
||||
if (input.displayName !== undefined) {
|
||||
sets.push('display_name = ?');
|
||||
params.push(input.displayName);
|
||||
}
|
||||
const writer = input.themeWriter;
|
||||
let themeSaved = false;
|
||||
const storedWriter = rawTheme(before.theme_json)?.writer as
|
||||
{ tab?: unknown; seq?: unknown } | undefined;
|
||||
// D21 (QA-83): an older save from the same tab, overtaken by a later one: keep the later one.
|
||||
const overtaken =
|
||||
writer !== undefined &&
|
||||
typeof storedWriter === 'object' &&
|
||||
storedWriter !== null &&
|
||||
storedWriter.tab === writer.tab &&
|
||||
typeof storedWriter.seq === 'number' &&
|
||||
writer.seq <= storedWriter.seq;
|
||||
if ((input.theme !== undefined || input.themePatch !== undefined) && !overtaken) {
|
||||
const stored = rawTheme(before.theme_json);
|
||||
const current = themeUpdatedAt(before.theme_json);
|
||||
// D20: a save based on an older version than what is stored is refused, not merged. A null
|
||||
// base only matches when no theme is stored at all (QA-86).
|
||||
if (input.baseUpdatedAt !== undefined && input.baseUpdatedAt !== current) {
|
||||
throw new HttpError(
|
||||
409,
|
||||
'theme_conflict',
|
||||
'Your theme was changed on another device. Showing that one.',
|
||||
);
|
||||
}
|
||||
const updatedAt = nextUpdatedAt(current);
|
||||
themeSaved = true;
|
||||
sets.push('theme_json = ?');
|
||||
params.push(
|
||||
JSON.stringify(
|
||||
input.theme !== undefined
|
||||
? { ...input.theme, updatedAt, writer }
|
||||
: // Merged into what is stored, so a preset (or any field) this version doesn't know is kept.
|
||||
{ ...(stored ?? { ...DEFAULT_THEME }), ...input.themePatch, updatedAt, writer },
|
||||
),
|
||||
);
|
||||
}
|
||||
if (sets.length > 0) {
|
||||
this.db.prepare(`UPDATE users SET ${sets.join(', ')} WHERE id = ?`).run(...params, userId);
|
||||
}
|
||||
const row = this.require(userId);
|
||||
if (row.display_name !== before.display_name) this.broadcast(userId);
|
||||
// D21 (QA-84): the user's other tabs and devices learn of the save; nobody else does.
|
||||
if (themeSaved) this.hub().toUser(userId, 'theme:update', meTheme(row.theme_json));
|
||||
return toMeDto(row);
|
||||
}
|
||||
|
||||
/** PATCH /api/me/profile: display name, About me, pronouns, banner colour. */
|
||||
updateProfile(userId: string, input: UpdateProfileInput): MeDto {
|
||||
const before = this.require(userId);
|
||||
const cols: [string, unknown][] = [];
|
||||
if (input.displayName !== undefined) cols.push(['display_name', input.displayName]);
|
||||
if (input.about !== undefined) cols.push(['about', input.about]);
|
||||
if (input.pronouns !== undefined) cols.push(['pronouns', input.pronouns]);
|
||||
if (input.bannerColor !== undefined) cols.push(['banner_color', input.bannerColor]);
|
||||
if (cols.length > 0) {
|
||||
this.db
|
||||
.prepare(`UPDATE users SET ${cols.map(([c]) => `${c} = ?`).join(', ')} WHERE id = ?`)
|
||||
.run(...cols.map(([, v]) => v), userId);
|
||||
}
|
||||
const row = this.require(userId);
|
||||
const changed = (['display_name', 'about', 'pronouns', 'banner_color'] as const).some(
|
||||
(c) => row[c] !== before[c],
|
||||
);
|
||||
if (changed) this.broadcast(userId);
|
||||
return toMeDto(row);
|
||||
}
|
||||
|
||||
/**
|
||||
* Point the avatar/banner at a new media id (null = remove). Returns the previous id so the
|
||||
* caller can delete its files. Call inside the media pipeline's swap transaction.
|
||||
*/
|
||||
setImage(userId: string, which: ProfileImage, mediaId: string | null): string | null {
|
||||
const col = IMAGE_COLUMN[which];
|
||||
const before = this.require(userId)[col];
|
||||
this.db.prepare(`UPDATE users SET ${col} = ? WHERE id = ?`).run(mediaId, userId);
|
||||
return before;
|
||||
}
|
||||
|
||||
/** GET /api/users/:id/profile: 404 unless the viewer shares a server or DM (or it's them). */
|
||||
profile(viewerId: string, userId: string): ProfileDto {
|
||||
const row = this.getById(userId);
|
||||
if (!row || !canSeeUser(this.db, viewerId, userId)) throw notFound('User not found');
|
||||
const mutual = this.db
|
||||
.prepare(
|
||||
`SELECT s.id, s.name, s.icon_media FROM servers s
|
||||
JOIN members a ON a.server_id = s.id AND a.user_id = ? AND a.banned = 0
|
||||
JOIN members b ON b.server_id = s.id AND b.user_id = ? AND b.banned = 0
|
||||
ORDER BY lower(s.name), s.id`,
|
||||
)
|
||||
.all(viewerId, userId) as { id: string; name: string; icon_media: string | null }[];
|
||||
return {
|
||||
...toProfileFields(row),
|
||||
createdAt: row.created_at,
|
||||
mutualServers: mutual.map((s) => ({
|
||||
id: s.id,
|
||||
name: s.name,
|
||||
icon: s.icon_media,
|
||||
})),
|
||||
};
|
||||
}
|
||||
}
|
||||
Loaded 100 of 264 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user