Explorar el Código

Server: LYNX SHARE VPS as code (Caddy + TLS, share links API, WebSocket relay skeleton, backups, monitoring)

server/ holds everything that runs on the VPS: an idempotent setup.sh, deploy.sh, the Caddyfile (automatic HTTPS,
access log without client addresses), two sandboxed systemd services (lynx-api: /health and the Online Sessions P1
share links; lynx-relay: 4-peer WebSocket rooms), daily backups with rotation, a 5-minute health/resource monitor,
logrotate and journald caps, and an end-to-end smoke test. Live at api.lynx-share.com and relay.lynx-share.com.
docs/design/SHARE_API.md documents the API for the app round; docs/design/CRASH_REPORTS_VPS.md plans the
crash-report move (not switched).
Ka1-S hace 1 mes
padre
commit
97b215c193

+ 34 - 0
docs/analise/REA_rodada168v.md

@@ -0,0 +1,34 @@
+# Round 168v — LYNX SHARE VPS foundation (infrastructure)
+
+LYNX-own infrastructure (no FL Studio counterpart, no REA needed: ONLINE_SESSIONS.md §0 already shows FL has no
+collaboration feature). The user pays a VPS since 2026-11-02 ("put everything LYNX there").
+
+| Item | Asked | Before | Now |
+|---|---|---|---|
+| Server as code | `server/` with idempotent setup, Caddy + TLS, units, README | nothing on the VPS but base hardening | `server/setup.sh` (idempotent, verified by a second run: no restarts, env kept), `deploy.sh`, `caddy/Caddyfile`, `systemd/*`, `ops/*`, `README.md` |
+| DNS | subdomains to the VPS via Hostinger DNS API, touch only new records | zone: `@` ALIAS, `www` CNAME, `ftp` A | + `api` A and `relay` A → 179.66.129.177 (TTL 300), added with `overwrite:false` after `/validate`; the 3 old records unchanged (checked after). ufw: + 80/tcp, 443/tcp, 443/udp |
+| Health + uptime | `/health` + check | — | `GET /health` on both hosts; `lynx-monitor.timer` every 5 min (local + public HTTPS, restarts on 2 failures, resource line in `/var/log/lynx/monitor.log`) |
+| Share links (P1) | upload .lynxpack, cap, expiry, random id, delete token, download by link, API doc | — | `/v1/shares` (create / resumable PATCH / metadata / download with Range / delete), `/s/<id>` page; 2 GiB cap, 1–30 days, 128-bit id, 256-bit token (hash stored), zip + sha256 check, rate limits; doc `docs/design/SHARE_API.md` |
+| Relay skeleton (P2) | WS rooms, max 4 peers, room token, echo/forward | — | `relay.lynx-share.com`: `POST /v1/rooms`, `wss://…/v1/rooms/<room>/ws` (Bearer or `token.` subprotocol), peer numbers 1–4, unicast / broadcast / echo by first byte, join/leave/ping control, host token closes |
+| Crash reports | plan the move, don't switch | PHP on Hostinger | plan `docs/design/CRASH_REPORTS_VPS.md` (same contract at `/v1/crash`, PHP proxy step for old builds); nothing switched |
+| Ops | backups + rotation, log rotation, monitoring, restarts | — | `lynx-backup.timer` daily (14 kept, share blobs excluded), logrotate + journald cap, Caddy log roll, `Restart=always` + monitor, memory caps, sandboxed units |
+
+## Evidence (2026-11-02, from WSL)
+
+- `python3 server/tests/smoke.py` against the live URLs: 35 checks, 0 failures (bad name 400, >2 GB 413, upload without
+  token 401, non-zip 415, wrong offset 409 with the server offset, resume, sha256, identical download, Range 206, page,
+  no listing 404, delete; relay health, wrong token 401, 4 peers (one by subprotocol token), 5th 409, echo, unicast,
+  512 KB broadcast, ping/pong, host close disconnects all). Same test against local services: 0 failures.
+- 200 MB upload through Caddy: 31 s (~7 MB/s, the workstation's uplink), download 22 s, byte-identical; the API's
+  anonymous memory stayed at 31 MB (streamed, not buffered).
+- Rate limits: share create → 429 after the hourly budget (20); relay rooms → 429 after 10.
+- `systemctl kill -s KILL lynx-api` → back in 3 s (NRestarts=1). Backup run → archive 600 in a 700 folder with
+  `/etc/lynx`, Caddy certificates. Caddy access log: no `remote_ip`, no headers.
+- TLS: Let's Encrypt certificates for both names (http-01), HTTP → HTTPS 308.
+
+## Where I stopped
+
+- Done: everything above deployed and tested; docs written; landed on main (see report).
+- Next (other rounds): app side of P1 (SHARE_API.md §2.6), crash move steps 1–2, off-machine backups, AAAA records,
+  SSH `PasswordAuthentication no` after the user changes the root password.
+- Rerun: `server/deploy.sh` then `python3 server/tests/smoke.py` (aiohttp needed locally, e.g. a venv).

+ 57 - 0
docs/design/CRASH_REPORTS_VPS.md

@@ -0,0 +1,57 @@
+# Plan: move the crash-report API from Hostinger (PHP) to the LYNX SHARE VPS
+
+Status: **plan only** (round 168v, 2026-11-02). Nothing is switched: the app and the site still use
+`https://lynx-share.com/api/crash.php` and `reports.php`, and they keep working unchanged until the user OKs the steps
+below. LYNX-own infrastructure (no FL Studio counterpart).
+
+## Today
+
+- App: `CrashReporter::endpoint()` (`src/ui/CrashReporter.cpp`) posts gzip JSON (schema 1) to
+  `https://lynx-share.com/api/crash.php`; `LYNX_CRASH_ENDPOINT` overrides it (tests). Opt-in per report (PRIVACY.md).
+- Server: `website/api/crash.php` + `_common.php` on Hostinger shared hosting; reports stored outside `public_html` as
+  `<YYYY-MM>/<id>.json.gz` + `index.jsonl`; limits 30 per hashed address per day, 3000 per day, 50 000 per month; the
+  address only as a salted daily HMAC used for counting. Admin: `reports.php` (list / get / delete, bearer key whose
+  SHA-256 is in the file); the maintainer's `crash-fetch.sh` downloads them.
+- Weak points: shared hosting PHP limits, the reports live on the same account as the website, no backups of the
+  reports, the CDN in front of the site.
+
+## Target
+
+`lynx-api` on the VPS gains the same two endpoints with the **same contract**, so the app does not care which
+server answers:
+
+| New | Same as |
+|---|---|
+| `POST https://api.lynx-share.com/v1/crash` | `crash.php` — same schema-1 validation, gzip handling (1 MB compressed / 4 MB decoded caps, inflate with a running size check), same answers `{"ok":true,"id":…}` / `{"ok":false,"error":…}` and status codes, same limits |
+| `GET/POST https://api.lynx-share.com/v1/crash/admin?action=list|get|delete` | `reports.php` — same actions and output; the key's SHA-256 lives in `/etc/lynx/lynx.env` (`LYNX_CRASH_ADMIN_SHA256`), not in the repo |
+
+Storage: `/var/lib/lynx/crash/<YYYY-MM>/<id>.json.gz` + `index.jsonl` (same layout, so the files can be copied over
+as they are). They are included in the daily backup (`server/ops/backup.sh` already backs up `/var/lib/lynx` except
+share blobs), rotated 14 days. The address-hash salt stays a server secret in `lynx.env`.
+
+## Steps (each one reversible; the user OKs steps 3 and 5)
+
+1. **Implement** `crash.py` routes in `server/app/` (port of the PHP rules, unit-tested with the same reports the PHP
+   accepts / refuses: a test feeds `tests/` fixture reports and fuzzed bodies to both and compares answers on a local
+   `php -S` + local `lynx_api.py`). Deploy (`server/deploy.sh`); the endpoint is live but unused.
+2. **Copy the existing reports** once: `crash-fetch.sh` already mirrors them to `/mnt/d/lynx-work/crash-reports`;
+   upload that tree to `/var/lib/lynx/crash/` (`tar | ssh`), rebuild `index.jsonl`. `crash-fetch.sh` gets
+   `API=${CRASH_API:-…}` so it can read either server.
+3. **Forward on Hostinger** (user OK): `crash.php` becomes a thin proxy that re-posts the body to
+   `https://api.lynx-share.com/v1/crash` (PHP `curl`, 10 s timeout) and, if the VPS does not answer, stores it locally
+   as today. Every released LYNX (which has the old URL built in) then reaches the VPS with no app update, and a VPS
+   outage loses nothing.
+4. **App default** (next release after step 3 has run a week without errors): `CrashReporter::endpoint()` →
+   `https://api.lynx-share.com/v1/crash`, still overridable by `LYNX_CRASH_ENDPOINT`; PRIVACY.md and `docs/STORE.md`
+   name the new host (same data, same rules; the Store answer does not change: "crash reports, opt-in").
+5. **Retire** (user OK, months later): when no report has come through `crash.php` for 60 days (`index.jsonl` on
+   Hostinger), `crash.php` answers `410` with the new URL, and the PHP storage is deleted after a final copy.
+
+## Risks and checks
+
+- **TLS / DNS**: `api.lynx-share.com` is an A record to the VPS with a Let's Encrypt certificate renewed by Caddy;
+  `lynx-monitor.timer` checks the public HTTPS path every 5 minutes. The PHP fallback in step 3 covers outages.
+- **Privacy**: the VPS access log has no client addresses (Caddyfile `format filter`), the services log no addresses;
+  the counting hash is in memory or salted daily as today.
+- **Old builds**: covered by the proxy (step 3) for as long as it runs.
+- **Load**: a few reports a day; negligible next to share uploads.

+ 179 - 0
docs/design/SHARE_API.md

@@ -0,0 +1,179 @@
+# LYNX SHARE server API — share links (Online Sessions P1) and relay (P2/P4 skeleton)
+
+Status: **live since round 168v (2026-11-02)**, not used by the app yet. The app round that ships *Send project to a
+friend…* (ONLINE_SESSIONS.md §9 P1) and later the relay link builds on this contract. Server code and deployment:
+`server/` (README there). This is a LYNX-own feature (no FL Studio equivalent, ONLINE_SESSIONS.md §0).
+
+| Service | Base URL | Runs as |
+|---|---|---|
+| API (health, share links) | `https://api.lynx-share.com` | `lynx-api.service`, 127.0.0.1:8081 behind Caddy |
+| Relay (WebSocket rooms) | `https://relay.lynx-share.com` / `wss://relay.lynx-share.com` | `lynx-relay.service`, 127.0.0.1:8082 behind Caddy |
+
+Conventions: JSON bodies and answers (`Content-Type: application/json`), errors are `{"ok": false, "error": "<text
+for a human>"}` with a meaningful status code. Tokens always travel in `Authorization: Bearer <token>`, never in a
+URL (URLs end up in logs and chat apps). `api` in `/health` is the API version (`"1"`); a client that sees a newer
+major version than it knows should tell the user to update. Every limit below is a server setting
+(`/etc/lynx/lynx.env`, defaults in `server/env.example`).
+
+---
+
+## 1. Health
+
+`GET /health` on either host → `200`
+
+```json
+{"ok":true,"service":"lynx-api","api":"1","uptime":3600,"shares":2,"shareBytes":81234567,"diskFree":101094068224}
+{"ok":true,"service":"lynx-relay","api":"1","uptime":3600,"rooms":1,"peers":2,"maxPeers":4,"frames":1234}
+```
+
+The VPS checks both every 5 minutes (`lynx-monitor.timer`, local and through public HTTPS) and restarts what hangs.
+
+---
+
+## 2. Share links (P1: *Send project to a friend…*)
+
+The host's LYNX uploads a `.lynxpack` (the zip of ONLINE_SESSIONS.md §9 P1); the server answers a link the user
+pastes into WhatsApp / e-mail; the friend opens the link (a small page with a Download button) or pastes it into
+LYNX's *Open a friend's project…*, which downloads it directly.
+
+### 2.1 Lifecycle
+
+```
+POST   /v1/shares                  create (declare name, size, optional sha256, days)  -> id, token, uploadUrl
+PATCH  /v1/shares/<id>             upload bytes from Upload-Offset (repeat; resumable)  [token]
+GET    /v1/shares/<id>             metadata incl. "received" (resume point) and "complete"
+GET    /v1/shares/<id>/download    the file (Range supported)                          (public, by unguessable id)
+GET    /s/<id>                     human page with a Download button                   (the link users share)
+DELETE /v1/shares/<id>             delete now                                          [token]
+```
+
+- **id**: 128 random bits, 26 lowercase base-32 chars (`[a-z2-7]{26}`); knowing the link = being allowed to
+  download. There is no listing of any kind.
+- **token** (returned once, at create): 256 random bits. It is the upload *and* delete key; the server keeps only its
+  SHA-256. The app stores it next to the share (in the profile's `shares.json`) so the user can *Stop sharing* later.
+- **Expiry**: `days` 1…30 (default 7). Expired shares and uploads not finished within 24 h are deleted
+  automatically (checked every 10 minutes and on every access).
+
+### 2.2 Create
+
+`POST /v1/shares`
+
+```json
+{"name": "My song.lynxpack", "size": 81234567, "days": 7, "sha256": "<64 hex, optional but recommended>"}
+```
+
+- `name`: a file name ending in `.lynxpack`, at most 120 characters, no slashes or control characters.
+- `size`: exact byte count, at most **2 GiB** (`2147483648`).
+
+`201 Created`
+
+```json
+{"ok":true,"id":"ohqg5s…","name":"My song.lynxpack","size":81234567,"received":0,"complete":false,
+ "created":1793645658,"expires":1794250458,
+ "url":"https://api.lynx-share.com/s/ohqg5s…","downloadUrl":"https://api.lynx-share.com/v1/shares/ohqg5s…/download",
+ "token":"<keep secret>","uploadUrl":"https://api.lynx-share.com/v1/shares/ohqg5s…","offset":0,"chunkSize":8388608}
+```
+
+Errors: `400` bad field · `413` over 2 GiB · `429` limits (`Retry-After`): 20 creates per hour and 8 GiB declared per
+day per client · `507` the server's share storage (60 GiB) or disk is full.
+
+### 2.3 Upload (resumable, tus-like)
+
+`PATCH /v1/shares/<id>` with `Authorization: Bearer <token>`, `Upload-Offset: <n>`,
+`Content-Type: application/offset+octet-stream`, body = the bytes from offset `n` on (any length up to the rest of
+the file; `chunkSize` is only a suggestion — 8 MiB pieces give a smooth progress bar and lose little on a drop).
+
+- `200` → the metadata with `"offset": <new offset>` (also in the `Upload-Offset` header). When the offset reaches
+  `size`, the server checks the file (zip signature, and the `sha256` if one was declared) and answers
+  `"complete": true, "sha256": "<hex>"`.
+- **Resume after a drop**: `GET /v1/shares/<id>` → `"received"` is where to continue (what arrived before the drop is
+  kept).
+- `409` + `Upload-Offset: <server's offset>`: the offset does not match (send again from that offset), or another
+  upload to the same share is running, or it is already complete · `401` wrong token · `413` more bytes than declared ·
+  `415` the file does not start like a zip · `422` the finished file failed the check (sha256 / format): the share is
+  deleted, start again · `404` unknown or expired.
+
+### 2.4 Download
+
+`GET /v1/shares/<id>/download` → the file, `Content-Disposition: attachment; filename*=UTF-8''<name>`, with
+`Content-Length`, `Range` / `206` support (resumable downloads) and `ETag`/`Last-Modified`. `409` while the upload is
+not finished, `404` unknown/expired. The app verifies the `sha256` from `GET /v1/shares/<id>` after downloading.
+
+`GET /s/<id>` is the page people see when they open the link in a browser: name, size, expiry, a Download button
+and "Open it with LYNX SHARE". Later (P3) it can also offer a `lynx://open?share=<id>` button.
+
+### 2.5 Delete
+
+`DELETE /v1/shares/<id>` with the token → `204`. `401` wrong token, `404` unknown/expired.
+
+### 2.6 What the app round should do (P1)
+
+1. *File › Send project to a friend…*: build the `.lynxpack`, hash it (SHA-256) while writing, `POST`, then `PATCH`
+   in 8 MiB pieces on a background thread with a progress bar and a Cancel button (Cancel = `DELETE`). On a network
+   error, retry with back-off from `received`. Show the `url` with *Copy link* and the expiry date.
+2. Keep `{id, token, name, expires}` in the profile (`shares.json`); *Manage shared projects…* lists them with
+   *Copy link* / *Stop sharing*.
+3. *File › Open a friend's project…* accepts a link `https://api.lynx-share.com/s/<id>` (or the bare id), reads
+   the metadata, downloads with resume (`Range`), checks `sha256`, then opens the package as a local `.lynxpack`.
+4. Use JUCE `URL` / `WebInputStream` (already used by the crash reporter) — no new dependency. Test against a local
+   `python3 server/app/lynx_api.py` (env `LYNX_DATA_DIR`, `LYNX_PUBLIC_URL`, `LYNX_API_PORT`), never the live server.
+5. PRIVACY.md / Store answers: the project and its samples are uploaded **only when the user sends a project**, kept
+   until the chosen expiry (or *Stop sharing*), readable by whoever has the link; no address is stored (the access log
+   has no client addresses, rate limits use an in-memory salted hash).
+
+---
+
+## 3. Relay (P2/P4 skeleton)
+
+A dumb, end-to-end-blind forwarder for sessions whose peers cannot reach each other directly (ONLINE_SESSIONS.md
+§6.1 `RelayLink`, §9 P4). LYNX encrypts every frame before it reaches the relay (§6.4); the relay only routes by a
+one-byte peer number. Rooms live in memory: a relay restart drops them (clients reconnect and the host opens a new
+room). Today it only forwards/echoes; the session protocol on top is the app's (§6.2).
+
+### 3.1 Rooms
+
+`POST /v1/rooms` (no body) → `201`
+
+```json
+{"ok":true,"room":"2syq75e66t","token":"<room token>","hostToken":"<host token>","maxPeers":4,
+ "expires":1793688858,"ws":"wss://relay.lynx-share.com/v1/rooms/2syq75e66t/ws","subprotocol":"lynx-relay.v1"}
+```
+
+- The **room token** goes to everyone the host invites (inside the encrypted invite / knock flow, never in clear on
+  a public channel); the **host token** stays with the host and closes the room:
+  `DELETE /v1/rooms/<room>` with `Authorization: Bearer <hostToken>` → `204` (every peer is disconnected, close code
+  4000).
+- A room expires 12 h after its last connection ended. Limits: 10 rooms per hour per client, 200 rooms on the relay
+  (`503` when full), **4 peers per room** (ONLINE_SESSIONS.md §10 Q3: 4 proposed).
+
+### 3.2 Connect
+
+`GET wss://relay.lynx-share.com/v1/rooms/<room>/ws`, subprotocol `lynx-relay.v1`, room token as
+`Authorization: Bearer <token>` (native clients) or, for browsers that cannot set headers, as a second subprotocol
+`token.<token>`. Refusals before the upgrade: `401` wrong token, `404` unknown room, `409` room full, `429` too many
+connection attempts (60 per minute per client).
+
+On connect the relay assigns the lowest free **peer number 1…4** and sends text frames:
+
+| Server → client (text, JSON) | When |
+|---|---|
+| `{"type":"welcome","peer":2,"peers":[1,2],"maxPeers":4}` | right after connecting |
+| `{"type":"join","peer":3}` / `{"type":"leave","peer":3}` | another peer connects / disconnects |
+| `{"type":"pong","t":<echo>}` | answer to `{"type":"ping","t":…}` |
+| `{"type":"peers","peers":[1,2,3]}` | answer to `{"type":"peers"}` |
+| `{"type":"error","error":"…"}` | unknown control message |
+
+**Data = binary frames**: byte 0 is the destination peer (`0` = every other peer; your own number = echo back to
+yourself, for tests and RTT), bytes 1… are the payload. The relay delivers `[source peer][payload]`. At most 1 MiB per
+frame (`LYNX_RELAY_MAX_FRAME`); each peer may send 4 MiB/s on average (beyond that the relay slows the reader
+down instead of dropping, so the stream stays reliable and ordered). WebSocket pings every 25 s keep NAT mappings
+alive.
+
+### 3.3 Mapping to ONLINE_SESSIONS.md
+
+- §6.1 `RelayLink` = one WebSocket per peer; the `SessionLink` framing (`u32 length | u8 type | u8 stream |
+  payload`, Noise-encrypted) is the payload of the relay frame, so the relay never sees message types.
+- §6.3 rendezvous: the PHP mailbox planned on Hostinger can move here as plain HTTP endpoints of `lynx-api` (no PHP
+  time limits, real long polling or a WebSocket) — decided in P3.
+- §6.5 privacy: through the relay, peers do **not** see each other's IP address (only the relay does, and it logs
+  none).

+ 4 - 0
server/.gitignore

@@ -0,0 +1,4 @@
+__pycache__/
+*.pyc
+*.env
+!env.example

+ 100 - 0
server/README.md

@@ -0,0 +1,100 @@
+# LYNX SHARE server (VPS)
+
+Everything that runs on the LYNX SHARE VPS, as code. The website stays on Hostinger (`website/`,
+`scripts/deploy-site.sh`); this folder is the separate server for the app's online features.
+
+| URL | What | Code |
+|---|---|---|
+| `https://api.lynx-share.com/health` | health of the API service | `app/lynx_api.py` |
+| `https://api.lynx-share.com/v1/shares…`, `/s/<id>` | share links for `.lynxpack` files (Online Sessions P1) | `app/lynx_api.py` |
+| `https://relay.lynx-share.com/health`, `/v1/rooms…`, `wss://…/v1/rooms/<room>/ws` | WebSocket relay skeleton (Online Sessions P2/P4) | `app/lynx_relay.py` |
+
+API contract: [`docs/design/SHARE_API.md`](../docs/design/SHARE_API.md). Design background:
+[`docs/design/ONLINE_SESSIONS.md`](../docs/design/ONLINE_SESSIONS.md). Crash-report move (planned, not switched):
+[`docs/design/CRASH_REPORTS_VPS.md`](../docs/design/CRASH_REPORTS_VPS.md).
+
+## Layout
+
+```
+server/
+  setup.sh           idempotent installer, runs ON the VPS as root (packages, user, folders, env, code, units, ufw, Caddy)
+  deploy.sh          from a workstation: copies server/ to the VPS (/opt/lynx/src) and runs setup.sh
+  env.example        settings and limits; setup.sh creates /etc/lynx/lynx.env from it (chmod 600, random salt)
+  caddy/Caddyfile    reverse proxy + automatic HTTPS (Let's Encrypt), address-free access log
+  app/               the two services (Python 3 + aiohttp from Ubuntu's packages; no pip, no containers)
+  systemd/           lynx-api, lynx-relay (Restart=always, sandboxed), backup + monitor timers
+  ops/               backup.sh, monitor.sh, logrotate and journald settings
+  tests/smoke.py     end-to-end test (live or local)
+```
+
+## Machine
+
+Ubuntu 26.04 LTS, 2 vCPU, 7.7 GB RAM, 96 GB disk; `ssh lynx-vps` (root, key auth; alias in the maintainer's
+`~/.ssh/config`). Base hardening done by hand once (2026-11-02): ufw, fail2ban (sshd), unattended-upgrades. `setup.sh`
+never touches SSH settings and only *adds* firewall rules (22, 80, 443/tcp, 443/udp).
+
+DNS (Hostinger DNS API, zone `lynx-share.com`): `api` and `relay` are A records → `179.66.129.177` (TTL 300). The
+root, `www` and `ftp` records (website) are not touched. To recreate them:
+
+```sh
+T=$(cat ~/.config/hostinger/token)
+curl -X PUT -H "Authorization: Bearer $T" -H 'Content-Type: application/json' \
+  https://developers.hostinger.com/api/dns/v1/zones/lynx-share.com \
+  -d '{"overwrite":false,"zone":[{"name":"api","type":"A","ttl":300,"records":[{"content":"179.66.129.177"}]},
+                                 {"name":"relay","type":"A","ttl":300,"records":[{"content":"179.66.129.177"}]}]}'
+```
+
+(`"overwrite": false` adds/updates only the named records.) IPv6: the VPS has `2a02:4780:95:2d9b::1`; no AAAA records
+yet (add them once IPv6 reachability is checked from outside).
+
+## Deploy / redeploy
+
+```sh
+server/deploy.sh                 # copies server/, runs setup.sh; restarts the services only if code/units changed
+python3 server/tests/smoke.py    # end-to-end check of the live URLs (needs aiohttp locally)
+```
+
+Local run of the services (no VPS, for app development):
+
+```sh
+cd server/app
+LYNX_DATA_DIR=/tmp/lynx LYNX_PUBLIC_URL=http://127.0.0.1:8081 LYNX_MIN_FREE_BYTES=0 python3 lynx_api.py &
+python3 lynx_relay.py &
+python3 ../tests/smoke.py http://127.0.0.1:8081 ws://127.0.0.1:8082
+```
+
+## On the server
+
+| Path | What |
+|---|---|
+| `/opt/lynx/app`, `/opt/lynx/ops` | installed code (from `/opt/lynx/src`, the last deployed copy of this folder) |
+| `/etc/lynx/lynx.env` | settings + secrets (root, 600). Never in the repo. Edit, then `systemctl restart lynx-api lynx-relay` |
+| `/var/lib/lynx/shares/<id>/` | share metadata + file (user `lynx`, 700) |
+| `/var/backups/lynx/` | daily archives, 14 kept (root, 700) |
+| `/var/log/lynx/monitor.log`, `backup.log` | one line per check / backup (logrotate weekly, 8 kept) |
+| `/var/log/caddy/lynx-access.log` | access log without client addresses or headers (rolled at 20 MB, 10 kept, 30 days) |
+
+Services log to the journal (capped at 500 MB / 1 month): `journalctl -u lynx-api -u lynx-relay -u caddy`.
+
+**Restarts**: systemd `Restart=always` (crashes), `lynx-monitor.timer` every 5 min (hangs: two failed `/health` in a
+row → restart; public HTTPS failing while the services are fine → reload Caddy; warnings for disk ≥ 85 %, memory
+< 500 MB, inactive units, in the journal as `lynx-monitor`). Caddy renews certificates itself.
+
+**Backups** (`lynx-backup.timer`, daily ~04:20 UTC): `/etc/lynx`, `/etc/caddy`, `/var/lib/caddy` (certificates),
+`/var/lib/lynx` **without** share files (they are temporary, up to 60 GB, and the sender still has them). Restore:
+`tar -xzf /var/backups/lynx/lynx-<stamp>.tar.gz -C /` then `server/deploy.sh`. The archives are on the same disk:
+an off-machine copy is still open (see below).
+
+**Limits** (all in `lynx.env`): share files ≤ 2 GiB, 1–30 days (7 default), 60 GiB of shares in total, 10 GiB disk
+always left free, 20 shares/hour and 8 GiB/day per client, unfinished uploads dropped after 24 h; relay 4 peers per
+room, 200 rooms, 10 rooms/hour per client, 1 MiB per frame, 4 MiB/s per peer. Clients are told apart only by a salted
+hash of their address kept in memory (never stored or logged). Services are bound to 127.0.0.1 and sandboxed
+(`ProtectSystem=strict`, own user, memory caps 768 / 512 MB).
+
+## Open items
+
+- Off-machine backups (e.g. a weekly `rsync` pull to the maintainer's PC) — needs a destination decision.
+- External uptime check (from outside the VPS): `curl -sf https://api.lynx-share.com/health` from the workstation or a
+  free monitor service (needs a sign-up: the user decides).
+- Crash-report move: plan in `docs/design/CRASH_REPORTS_VPS.md`.
+- `PasswordAuthentication no` for SSH after the user changes the root password (not done by these scripts).

+ 408 - 0
server/app/lynx_api.py

@@ -0,0 +1,408 @@
+"""LYNX SHARE API service: /health and the Online Sessions P1 share links (/v1/shares, /s/<id>).
+
+Runs on 127.0.0.1:8081 behind Caddy (api.lynx-share.com). API reference: docs/design/SHARE_API.md.
+LYNX SHARE (AGPL-3.0-or-later).
+"""
+from __future__ import annotations
+
+import asyncio
+import hashlib
+import html
+import json
+import os
+import re
+import shutil
+import time
+import urllib.parse
+
+from aiohttp import web
+
+from lynx_common import (VERSION, RateLimiter, bearer, client_key, env_int, env_str, errors_middleware, fail,
+                         json_response, random_id, random_token, setup_logging, token_hash, token_matches)
+
+log = setup_logging("lynx-api")
+
+GiB = 1024 ** 3
+DATA_DIR = env_str("LYNX_DATA_DIR", "/var/lib/lynx")
+SHARES_DIR = os.path.join(DATA_DIR, "shares")
+PUBLIC_URL = env_str("LYNX_PUBLIC_URL", "https://api.lynx-share.com").rstrip("/")
+MAX_SIZE = env_int("LYNX_SHARE_MAX_BYTES", 2 * GiB)
+MAX_DAYS = env_int("LYNX_SHARE_MAX_DAYS", 30)
+DEFAULT_DAYS = env_int("LYNX_SHARE_DEFAULT_DAYS", 7)
+TOTAL_CAP = env_int("LYNX_SHARE_TOTAL_BYTES", 60 * GiB)        # all active shares together (declared sizes)
+CLIENT_DAILY_BYTES = env_int("LYNX_SHARE_CLIENT_DAILY_BYTES", 8 * GiB)
+CREATES_PER_HOUR = env_int("LYNX_SHARE_CREATES_PER_HOUR", 20)
+INCOMPLETE_HOURS = env_int("LYNX_SHARE_INCOMPLETE_HOURS", 24)  # unfinished uploads are dropped after this
+MIN_FREE_BYTES = env_int("LYNX_MIN_FREE_BYTES", 10 * GiB)      # keep this much disk free for everything else
+CHUNK = 1024 * 1024
+
+ID_RE = re.compile(r"^[a-z2-7]{26}$")
+NAME_RE = re.compile(r"^[^/\\\x00-\x1f\x7f]{1,120}\.lynxpack$", re.IGNORECASE)
+SHA_RE = re.compile(r"^[0-9a-f]{64}$")
+ZIP_MAGIC = b"PK\x03\x04"
+
+STARTED = time.time()
+create_limiter = RateLimiter(CREATES_PER_HOUR, 3600)
+patch_limiter = RateLimiter(600, 60)      # upload requests (not bytes) per client
+read_limiter = RateLimiter(300, 60)       # metadata / page / download requests per client
+daily_bytes: dict[str, tuple[str, int]] = {}  # client key -> (UTC day, declared bytes created that day)
+locks: dict[str, asyncio.Lock] = {}
+
+
+# ---- storage --------------------------------------------------------------------------------------------------
+
+def share_dir(sid: str) -> str:
+    return os.path.join(SHARES_DIR, sid)
+
+
+def blob_path(sid: str) -> str:
+    return os.path.join(share_dir(sid), "blob")
+
+
+def read_meta(sid: str) -> dict | None:
+    if not ID_RE.match(sid):
+        return None
+    try:
+        with open(os.path.join(share_dir(sid), "meta.json"), encoding="utf-8") as f:
+            meta = json.load(f)
+    except (OSError, ValueError):
+        return None
+    if is_dead(meta):
+        delete_share(sid)
+        return None
+    return meta
+
+
+def write_meta(meta: dict) -> None:
+    path = os.path.join(share_dir(meta["id"]), "meta.json")
+    tmp = path + ".tmp"
+    with open(tmp, "w", encoding="utf-8") as f:
+        json.dump(meta, f, separators=(",", ":"))
+    os.chmod(tmp, 0o600)
+    os.replace(tmp, path)
+
+
+def delete_share(sid: str) -> None:
+    shutil.rmtree(share_dir(sid), ignore_errors=True)
+    locks.pop(sid, None)
+
+
+def is_dead(meta: dict, now: float | None = None) -> bool:
+    now = now or time.time()
+    if now >= meta["expires"]:
+        return True
+    return not meta["complete"] and now >= meta["created"] + INCOMPLETE_HOURS * 3600
+
+
+def all_metas() -> list[dict]:
+    out = []
+    try:
+        names = os.listdir(SHARES_DIR)
+    except OSError:
+        return out
+    for sid in names:
+        m = read_meta(sid)
+        if m:
+            out.append(m)
+        elif ID_RE.match(sid) and not os.path.exists(os.path.join(share_dir(sid), "meta.json")):
+            # a folder without metadata is a create that died half-way
+            if time.time() - os.path.getmtime(share_dir(sid)) > 3600:
+                delete_share(sid)
+    return out
+
+
+def received_bytes(sid: str) -> int:
+    try:
+        return os.path.getsize(blob_path(sid))
+    except OSError:
+        return 0
+
+
+def public_view(meta: dict) -> dict:
+    sid = meta["id"]
+    v = {
+        "ok": True,
+        "id": sid,
+        "name": meta["name"],
+        "size": meta["size"],
+        "received": meta["size"] if meta["complete"] else received_bytes(sid),
+        "complete": meta["complete"],
+        "created": int(meta["created"]),
+        "expires": int(meta["expires"]),
+        "url": f"{PUBLIC_URL}/s/{sid}",
+        "downloadUrl": f"{PUBLIC_URL}/v1/shares/{sid}/download",
+    }
+    if meta["complete"]:
+        v["sha256"] = meta["sha256"]
+    return v
+
+
+def file_sha256(path: str) -> str:
+    h = hashlib.sha256()
+    with open(path, "rb") as f:
+        while True:
+            b = f.read(CHUNK)
+            if not b:
+                break
+            h.update(b)
+    return h.hexdigest()
+
+
+# ---- handlers -------------------------------------------------------------------------------------------------
+
+async def health(request: web.Request) -> web.Response:
+    du = shutil.disk_usage(DATA_DIR)
+    metas = all_metas()
+    return json_response(200, {
+        "ok": True, "service": "lynx-api", "api": VERSION,
+        "uptime": int(time.time() - STARTED),
+        "shares": len(metas),
+        "shareBytes": sum(m["size"] for m in metas),
+        "diskFree": du.free,
+    })
+
+
+async def create_share(request: web.Request) -> web.Response:
+    key = client_key(request)
+    if not create_limiter.allow(key):
+        return fail(429, "too many shares, try again later", {"Retry-After": "600"})
+    try:
+        body = await request.json()
+    except (ValueError, UnicodeDecodeError):
+        return fail(400, "body must be JSON")
+    if not isinstance(body, dict):
+        return fail(400, "body must be a JSON object")
+    name = body.get("name")
+    size = body.get("size")
+    days = body.get("days", DEFAULT_DAYS)
+    sha = body.get("sha256")
+    if not isinstance(name, str) or not NAME_RE.match(name):
+        return fail(400, "name must be a file name ending in .lynxpack (at most 120 characters)")
+    if not isinstance(size, int) or isinstance(size, bool) or size < len(ZIP_MAGIC):
+        return fail(400, "size must be the file size in bytes")
+    if size > MAX_SIZE:
+        return fail(413, f"file too large (at most {MAX_SIZE} bytes)")
+    if not isinstance(days, int) or isinstance(days, bool) or not 1 <= days <= MAX_DAYS:
+        return fail(400, f"days must be 1..{MAX_DAYS}")
+    if sha is not None and (not isinstance(sha, str) or not SHA_RE.match(sha.lower())):
+        return fail(400, "sha256 must be 64 hex digits")
+
+    today = time.strftime("%Y-%m-%d", time.gmtime())
+    day, used = daily_bytes.get(key, (today, 0))
+    if day != today:
+        used = 0
+    if used + size > CLIENT_DAILY_BYTES:
+        return fail(429, "daily upload volume reached, try again tomorrow", {"Retry-After": "3600"})
+    metas = all_metas()
+    if sum(m["size"] for m in metas) + size > TOTAL_CAP or shutil.disk_usage(DATA_DIR).free - size < MIN_FREE_BYTES:
+        return fail(507, "server storage is full, try again later")
+
+    sid = random_id()
+    token = random_token()
+    now = time.time()
+    meta = {
+        "id": sid, "name": name, "size": size, "expectedSha256": sha.lower() if sha else None, "sha256": None,
+        "complete": False, "created": now, "expires": now + days * 86400, "tokenHash": token_hash(token),
+        "downloads": 0,
+    }
+    os.makedirs(share_dir(sid), mode=0o700)
+    open(blob_path(sid), "wb").close()
+    os.chmod(blob_path(sid), 0o600)
+    write_meta(meta)
+    daily_bytes[key] = (today, used + size)
+    log.info("share created id=%s… size=%d days=%d", sid[:6], size, days)
+    view = public_view(meta)
+    view.update({"token": token, "uploadUrl": f"{PUBLIC_URL}/v1/shares/{sid}", "offset": 0, "chunkSize": 8 * CHUNK})
+    return json_response(201, view, {"Location": view["uploadUrl"]})
+
+
+async def get_share(request: web.Request) -> web.Response:
+    if not read_limiter.allow(client_key(request)):
+        return fail(429, "slow down", {"Retry-After": "60"})
+    meta = read_meta(request.match_info["id"])
+    if not meta:
+        return fail(404, "no such share (it may have expired)")
+    return json_response(200, public_view(meta))
+
+
+async def upload_chunk(request: web.Request) -> web.Response:
+    sid = request.match_info["id"]
+    if not patch_limiter.allow(client_key(request)):
+        return fail(429, "slow down", {"Retry-After": "60"})
+    meta = read_meta(sid)
+    if not meta:
+        return fail(404, "no such share (it may have expired)")
+    if not token_matches(bearer(request), meta["tokenHash"]):
+        return fail(401, "missing or wrong token")
+    if meta["complete"]:
+        return fail(409, "upload already complete")
+    try:
+        offset = int(request.headers["Upload-Offset"])
+    except (KeyError, ValueError):
+        return fail(400, "Upload-Offset header required")
+    lock = locks.setdefault(sid, asyncio.Lock())
+    if lock.locked():
+        return fail(409, "another upload to this share is running")
+    async with lock:
+        have = received_bytes(sid)
+        if offset != have:
+            return fail(409, "offset mismatch", {"Upload-Offset": str(have)})
+        path = blob_path(sid)
+        written = have
+        first = have == 0
+        with open(path, "r+b") as f:
+            f.seek(have)
+            try:
+                async for chunk in request.content.iter_chunked(CHUNK):
+                    if first:
+                        if len(chunk) < len(ZIP_MAGIC) and written + len(chunk) < meta["size"]:
+                            pass  # tiny first piece: checked when the file completes
+                        elif not (chunk[:len(ZIP_MAGIC)] == ZIP_MAGIC):
+                            f.truncate(have)
+                            return fail(415, "not a .lynxpack (zip) file")
+                        first = False
+                    if written + len(chunk) > meta["size"]:
+                        f.truncate(have)
+                        return fail(413, "more bytes than the declared size")
+                    f.write(chunk)
+                    written += len(chunk)
+            finally:
+                f.flush()
+        # a dropped connection leaves what arrived: the client resumes from GET /v1/shares/<id> "received"
+        if written == meta["size"]:
+            digest = await asyncio.get_running_loop().run_in_executor(None, file_sha256, path)
+            with open(path, "rb") as f:
+                magic = f.read(len(ZIP_MAGIC))
+            if magic != ZIP_MAGIC or (meta["expectedSha256"] and digest != meta["expectedSha256"]):
+                delete_share(sid)
+                return fail(422, "file check failed (sha256 or format); the share was deleted, start again")
+            meta["complete"] = True
+            meta["sha256"] = digest
+            write_meta(meta)
+            log.info("share complete id=%s… size=%d", sid[:6], written)
+        view = public_view(meta)
+        view["offset"] = written
+        return json_response(200, view, {"Upload-Offset": str(written)})
+
+
+async def download(request: web.Request) -> web.StreamResponse:
+    if not read_limiter.allow(client_key(request)):
+        return fail(429, "slow down", {"Retry-After": "60"})
+    sid = request.match_info["id"]
+    meta = read_meta(sid)
+    if not meta:
+        return fail(404, "no such share (it may have expired)")
+    if not meta["complete"]:
+        return fail(409, "upload not finished yet")
+    if "Range" not in request.headers:
+        meta["downloads"] = meta.get("downloads", 0) + 1
+        write_meta(meta)
+    quoted = urllib.parse.quote(meta["name"])
+    ascii_name = re.sub(r'[^A-Za-z0-9._ -]', "_", meta["name"])
+    return web.FileResponse(blob_path(sid), headers={
+        "Content-Type": "application/octet-stream",
+        "Content-Disposition": f"attachment; filename=\"{ascii_name}\"; filename*=UTF-8''{quoted}",
+        "Cache-Control": "private, no-store",
+        "X-Content-Type-Options": "nosniff",
+        "X-Robots-Tag": "noindex",
+    })
+
+
+async def delete(request: web.Request) -> web.Response:
+    sid = request.match_info["id"]
+    meta = read_meta(sid)
+    if not meta:
+        return fail(404, "no such share (it may have expired)")
+    if not token_matches(bearer(request), meta["tokenHash"]):
+        return fail(401, "missing or wrong token")
+    delete_share(sid)
+    log.info("share deleted id=%s…", sid[:6])
+    return web.Response(status=204)
+
+
+def human_size(n: int) -> str:
+    for unit in ("bytes", "KB", "MB", "GB"):
+        if n < 1024 or unit == "GB":
+            return f"{n:.0f} {unit}" if unit == "bytes" else f"{n:.1f} {unit}"
+        n /= 1024
+    return str(n)
+
+
+PAGE = """<!DOCTYPE html>
+<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
+<meta name="robots" content="noindex"><title>{title} - LYNX SHARE</title>
+<style>body{{margin:0;min-height:100vh;display:grid;place-items:center;background:#111214;color:#e8e8ea;
+font:16px/1.5 system-ui,sans-serif}}main{{max-width:28rem;padding:2rem;border:1px solid #2a2b30;border-radius:12px;
+background:#18191c}}h1{{font-size:1.2rem;margin:0 0 .5rem;word-break:break-all}}p{{color:#a0a1a8;margin:.25rem 0}}
+a.b{{display:inline-block;margin-top:1.2rem;padding:.6rem 1.2rem;border-radius:8px;background:#e5383b;color:#fff;
+text-decoration:none;font-weight:600}}a{{color:#e5383b}}</style></head><body><main>
+<p>LYNX SHARE project</p><h1>{title}</h1>{body}
+<p style="margin-top:1.5rem;font-size:.85rem">Open it with <a href="https://lynx-share.com">LYNX SHARE</a> (File &rsaquo; Open).</p>
+</main></body></html>"""
+
+
+async def page(request: web.Request) -> web.Response:
+    if not read_limiter.allow(client_key(request)):
+        return fail(429, "slow down", {"Retry-After": "60"})
+    meta = read_meta(request.match_info["id"])
+    headers = {"Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'", "X-Robots-Tag": "noindex",
+               "Cache-Control": "no-store", "Referrer-Policy": "no-referrer"}
+    if not meta:
+        text = PAGE.format(title="Link expired", body="<p>This share does not exist or has expired.</p>")
+        return web.Response(status=404, text=text, content_type="text/html", headers=headers)
+    if not meta["complete"]:
+        body = "<p>The upload is not finished yet. Try again in a moment.</p>"
+    else:
+        expires = time.strftime("%Y-%m-%d %H:%M UTC", time.gmtime(meta["expires"]))
+        body = (f"<p>{human_size(meta['size'])} &middot; expires {expires}</p>"
+                f"<a class=\"b\" href=\"/v1/shares/{meta['id']}/download\">Download</a>")
+    return web.Response(text=PAGE.format(title=html.escape(meta["name"]), body=body), content_type="text/html",
+                        headers=headers)
+
+
+async def index(request: web.Request) -> web.Response:
+    return json_response(200, {"ok": True, "service": "lynx-api", "api": VERSION,
+                               "docs": "https://github.com/Ka1-S/LYNX-SHARE/blob/main/docs/design/SHARE_API.md"})
+
+
+# ---- housekeeping ---------------------------------------------------------------------------------------------
+
+async def gc_loop(app: web.Application) -> None:
+    while True:
+        try:
+            before = len(os.listdir(SHARES_DIR))
+            left = len(all_metas())  # all_metas() deletes dead shares as it reads them
+            if before != left:
+                log.info("gc: %d shares removed, %d active", before - left, left)
+        except Exception:  # noqa: BLE001 - never let housekeeping kill the service
+            log.exception("gc failed")
+        await asyncio.sleep(600)
+
+
+async def on_startup(app: web.Application) -> None:
+    os.makedirs(SHARES_DIR, mode=0o700, exist_ok=True)
+    app["gc"] = asyncio.create_task(gc_loop(app))
+
+
+async def on_cleanup(app: web.Application) -> None:
+    app["gc"].cancel()
+
+
+def make_app() -> web.Application:
+    app = web.Application(middlewares=[errors_middleware], client_max_size=64 * 1024)
+    app.router.add_get("/", index)
+    app.router.add_get("/health", health)
+    app.router.add_post("/v1/shares", create_share)
+    app.router.add_get("/v1/shares/{id}", get_share)
+    app.router.add_patch("/v1/shares/{id}", upload_chunk)
+    app.router.add_delete("/v1/shares/{id}", delete)
+    app.router.add_get("/v1/shares/{id}/download", download)
+    app.router.add_get("/s/{id}", page)
+    app.on_startup.append(on_startup)
+    app.on_cleanup.append(on_cleanup)
+    return app
+
+
+if __name__ == "__main__":
+    web.run_app(make_app(), host=env_str("LYNX_API_HOST", "127.0.0.1"), port=env_int("LYNX_API_PORT", 8081),
+                access_log=None)

+ 118 - 0
server/app/lynx_common.py

@@ -0,0 +1,118 @@
+"""Shared helpers of the LYNX SHARE server services (lynx_api.py, lynx_relay.py).
+
+LYNX SHARE (AGPL-3.0-or-later). Standard library + aiohttp only (Ubuntu package python3-aiohttp).
+"""
+from __future__ import annotations
+
+import base64
+import hashlib
+import hmac
+import json
+import logging
+import os
+import secrets
+import time
+
+from aiohttp import web
+
+VERSION = "1"  # bumped when the HTTP API changes in a way clients must know about
+
+
+def env_int(name: str, default: int) -> int:
+    try:
+        return int(os.environ.get(name, default))
+    except ValueError:
+        return default
+
+
+def env_str(name: str, default: str) -> str:
+    return os.environ.get(name, default)
+
+
+def setup_logging(service: str) -> logging.Logger:
+    logging.basicConfig(level=env_str("LYNX_LOG_LEVEL", "INFO"),
+                        format="%(levelname)s " + service + ": %(message)s")
+    # aiohttp's own access log carries the client address; Caddy keeps the (address-free) access log instead.
+    logging.getLogger("aiohttp.access").setLevel(logging.WARNING)
+    return logging.getLogger(service)
+
+
+def random_id(nbytes: int = 16) -> str:
+    """Unguessable lowercase base32 id (16 bytes = 128 bits = 26 chars)."""
+    return base64.b32encode(secrets.token_bytes(nbytes)).decode("ascii").rstrip("=").lower()
+
+
+def random_token() -> str:
+    """256-bit bearer token, URL-safe."""
+    return secrets.token_urlsafe(32)
+
+
+def token_hash(token: str) -> str:
+    return hashlib.sha256(token.encode("utf-8")).hexdigest()
+
+
+def token_matches(token: str, stored_hash: str) -> bool:
+    return bool(token) and hmac.compare_digest(token_hash(token), stored_hash)
+
+
+def bearer(request: web.Request) -> str:
+    auth = request.headers.get("Authorization", "")
+    if auth.startswith("Bearer "):
+        return auth[7:].strip()
+    return ""
+
+
+def client_key(request: web.Request) -> str:
+    """Who is asking, for rate limits only. Never stored or logged: a salted hash kept in memory.
+
+    The services listen on 127.0.0.1 behind Caddy, which overwrites X-Forwarded-For with the real peer address
+    (no trusted_proxies configured), so the last element is the client."""
+    xff = request.headers.get("X-Forwarded-For", "")
+    ip = xff.split(",")[-1].strip() if xff else (request.remote or "")
+    if ":" in ip:  # IPv6: one key per /64, the smallest block a home line usually gets
+        parts = ip.split(":")
+        ip = ":".join(parts[:4])
+    salt = env_str("LYNX_SALT", "dev-salt")
+    return hmac.new(salt.encode(), ip.encode(), hashlib.sha256).hexdigest()[:24]
+
+
+class RateLimiter:
+    """Token buckets per client key: `rate` events per `per` seconds, burst = rate. In memory (one process)."""
+
+    def __init__(self, rate: float, per: float):
+        self.rate, self.per = float(rate), float(per)
+        self.buckets: dict[str, tuple[float, float]] = {}
+
+    def allow(self, key: str, cost: float = 1.0) -> bool:
+        now = time.monotonic()
+        tokens, last = self.buckets.get(key, (self.rate, now))
+        tokens = min(self.rate, tokens + (now - last) * self.rate / self.per)
+        if tokens < cost:
+            self.buckets[key] = (tokens, now)
+            return False
+        self.buckets[key] = (tokens - cost, now)
+        if len(self.buckets) > 50000:  # forget full buckets so memory stays bounded
+            self.buckets = {k: v for k, v in self.buckets.items() if v[0] < self.rate}
+        return True
+
+
+def json_response(status: int, body: dict, headers: dict | None = None) -> web.Response:
+    h = {"Cache-Control": "no-store", "X-Content-Type-Options": "nosniff"}
+    if headers:
+        h.update(headers)
+    return web.Response(status=status, text=json.dumps(body, separators=(",", ":")),
+                        content_type="application/json", headers=h)
+
+
+def fail(status: int, error: str, headers: dict | None = None) -> web.Response:
+    return json_response(status, {"ok": False, "error": error}, headers)
+
+
+@web.middleware
+async def errors_middleware(request: web.Request, handler):
+    try:
+        return await handler(request)
+    except web.HTTPException as e:
+        if e.status >= 400 and not isinstance(e, web.HTTPMethodNotAllowed):
+            return fail(e.status, e.reason.lower())
+        raise

+ 227 - 0
server/app/lynx_relay.py

@@ -0,0 +1,227 @@
+"""LYNX SHARE relay service: Online Sessions P2/P4 WebSocket relay skeleton (rooms of up to 4 peers).
+
+Runs on 127.0.0.1:8082 behind Caddy (relay.lynx-share.com). The relay only forwards frames: it never reads them.
+LYNX encrypts every session frame end to end (docs/design/ONLINE_SESSIONS.md §6.4), so the relay sees opaque bytes.
+Protocol reference: docs/design/SHARE_API.md ("Relay").
+LYNX SHARE (AGPL-3.0-or-later).
+"""
+from __future__ import annotations
+
+import asyncio
+import json
+import time
+
+from aiohttp import WSMsgType, web
+
+from lynx_common import (VERSION, RateLimiter, bearer, client_key, env_int, env_str, errors_middleware, fail,
+                         json_response, random_id, random_token, setup_logging, token_hash, token_matches)
+
+log = setup_logging("lynx-relay")
+
+MAX_PEERS = env_int("LYNX_RELAY_MAX_PEERS", 4)
+MAX_ROOMS = env_int("LYNX_RELAY_MAX_ROOMS", 200)
+ROOM_HOURS = env_int("LYNX_RELAY_ROOM_HOURS", 12)          # a room lives this long after its last connection
+MAX_FRAME = env_int("LYNX_RELAY_MAX_FRAME", 1024 * 1024)   # bytes per WebSocket message
+PEER_BYTES_PER_SEC = env_int("LYNX_RELAY_PEER_BPS", 4 * 1024 * 1024)
+ROOMS_PER_HOUR = env_int("LYNX_RELAY_ROOMS_PER_HOUR", 10)
+SUBPROTOCOL = "lynx-relay.v1"
+
+STARTED = time.time()
+room_limiter = RateLimiter(ROOMS_PER_HOUR, 3600)
+connect_limiter = RateLimiter(60, 60)
+frames_total = 0
+
+
+class Room:
+    def __init__(self, rid: str, token: str, host_token: str):
+        self.id = rid
+        self.token_hash = token_hash(token)
+        self.host_hash = token_hash(host_token)
+        self.peers: dict[int, web.WebSocketResponse] = {}
+        self.created = time.time()
+        self.touched = self.created
+
+    def expires(self) -> float:
+        return self.touched + ROOM_HOURS * 3600
+
+    def free_slot(self) -> int | None:
+        for n in range(1, MAX_PEERS + 1):
+            if n not in self.peers:
+                return n
+        return None
+
+
+rooms: dict[str, Room] = {}
+
+
+def room_token_from(request: web.Request) -> str:
+    """Native clients send Authorization: Bearer <token>; browsers cannot, so the token may also come as a second
+    WebSocket subprotocol "token.<token>" (never in the URL, which ends up in logs)."""
+    tok = bearer(request)
+    if tok:
+        return tok
+    for p in request.headers.get("Sec-WebSocket-Protocol", "").split(","):
+        p = p.strip()
+        if p.startswith("token."):
+            return p[6:]
+    return ""
+
+
+async def health(request: web.Request) -> web.Response:
+    return json_response(200, {
+        "ok": True, "service": "lynx-relay", "api": VERSION, "uptime": int(time.time() - STARTED),
+        "rooms": len(rooms), "peers": sum(len(r.peers) for r in rooms.values()), "maxPeers": MAX_PEERS,
+        "frames": frames_total,
+    })
+
+
+async def create_room(request: web.Request) -> web.Response:
+    if not room_limiter.allow(client_key(request)):
+        return fail(429, "too many rooms, try again later", {"Retry-After": "600"})
+    if len(rooms) >= MAX_ROOMS:
+        return fail(503, "relay is full, try again later", {"Retry-After": "300"})
+    rid = random_id(7)[:10]
+    while rid in rooms:
+        rid = random_id(7)[:10]
+    token, host_token = random_token(), random_token()
+    room = Room(rid, token, host_token)
+    rooms[rid] = room
+    log.info("room created %s… (%d rooms)", rid[:4], len(rooms))
+    base = env_str("LYNX_RELAY_PUBLIC_URL", "wss://relay.lynx-share.com").rstrip("/")
+    return json_response(201, {"ok": True, "room": rid, "token": token, "hostToken": host_token,
+                               "maxPeers": MAX_PEERS, "expires": int(room.expires()),
+                               "ws": f"{base}/v1/rooms/{rid}/ws", "subprotocol": SUBPROTOCOL})
+
+
+async def close_room(request: web.Request) -> web.Response:
+    room = rooms.get(request.match_info["room"])
+    if not room:
+        return fail(404, "no such room")
+    if not token_matches(bearer(request), room.host_hash):
+        return fail(401, "missing or wrong host token")
+    await drop_room(room, "closed by host")
+    return web.Response(status=204)
+
+
+async def drop_room(room: Room, reason: str) -> None:
+    rooms.pop(room.id, None)
+    for ws in list(room.peers.values()):
+        await ws.close(code=4000, message=reason.encode()[:120])
+    room.peers.clear()
+
+
+async def send_json(ws: web.WebSocketResponse, msg: dict) -> None:
+    if not ws.closed:
+        await ws.send_str(json.dumps(msg, separators=(",", ":")))
+
+
+async def broadcast(room: Room, msg: dict, skip: int | None = None) -> None:
+    for n, ws in list(room.peers.items()):
+        if n != skip:
+            await send_json(ws, msg)
+
+
+async def connect(request: web.Request) -> web.StreamResponse:
+    if not connect_limiter.allow(client_key(request)):
+        return fail(429, "slow down", {"Retry-After": "60"})
+    room = rooms.get(request.match_info["room"])
+    if not room:
+        return fail(404, "no such room")
+    if not token_matches(room_token_from(request), room.token_hash):
+        return fail(401, "missing or wrong room token")
+    slot = room.free_slot()
+    if slot is None:
+        return fail(409, f"room is full ({MAX_PEERS} peers)")
+
+    ws = web.WebSocketResponse(protocols=(SUBPROTOCOL,), heartbeat=25, max_msg_size=MAX_FRAME)
+    await ws.prepare(request)
+    room.peers[slot] = ws
+    room.touched = time.time()
+    await send_json(ws, {"type": "welcome", "peer": slot, "peers": sorted(room.peers), "maxPeers": MAX_PEERS})
+    await broadcast(room, {"type": "join", "peer": slot}, skip=slot)
+    log.info("room %s…: peer %d joined (%d/%d)", room.id[:4], slot, len(room.peers), MAX_PEERS)
+
+    global frames_total
+    budget, last = float(PEER_BYTES_PER_SEC), time.monotonic()
+    try:
+        async for msg in ws:
+            if msg.type == WSMsgType.BINARY:
+                data: bytes = msg.data
+                now = time.monotonic()
+                budget = min(PEER_BYTES_PER_SEC, budget + (now - last) * PEER_BYTES_PER_SEC)
+                last = now
+                budget -= len(data)
+                if budget < 0:  # over the rate: wait instead of dropping (the stream is reliable)
+                    await asyncio.sleep(-budget / PEER_BYTES_PER_SEC)
+                if len(data) < 1:
+                    continue
+                dest = data[0]
+                frames_total += 1
+                out = bytes([slot]) + data[1:]
+                targets = [n for n in room.peers if n != slot] if dest == 0 else [dest]
+                for n in targets:
+                    peer = room.peers.get(n)
+                    if peer is not None and not peer.closed:
+                        await peer.send_bytes(out)
+            elif msg.type == WSMsgType.TEXT:
+                try:
+                    ctl = json.loads(msg.data)
+                except ValueError:
+                    ctl = {}
+                if ctl.get("type") == "ping":
+                    await send_json(ws, {"type": "pong", "t": ctl.get("t")})
+                elif ctl.get("type") == "peers":
+                    await send_json(ws, {"type": "peers", "peers": sorted(room.peers)})
+                else:
+                    await send_json(ws, {"type": "error", "error": "unknown control message"})
+            elif msg.type == WSMsgType.ERROR:
+                break
+    finally:
+        if room.peers.get(slot) is ws:
+            del room.peers[slot]
+        room.touched = time.time()
+        await broadcast(room, {"type": "leave", "peer": slot})
+        log.info("room %s…: peer %d left (%d/%d)", room.id[:4], slot, len(room.peers), MAX_PEERS)
+    return ws
+
+
+async def index(request: web.Request) -> web.Response:
+    return json_response(200, {"ok": True, "service": "lynx-relay", "api": VERSION,
+                               "docs": "https://github.com/Ka1-S/LYNX-SHARE/blob/main/docs/design/SHARE_API.md"})
+
+
+async def gc_loop(app: web.Application) -> None:
+    while True:
+        await asyncio.sleep(300)
+        now = time.time()
+        for room in list(rooms.values()):
+            if not room.peers and now >= room.expires():
+                rooms.pop(room.id, None)
+                log.info("room %s… expired", room.id[:4])
+
+
+async def on_startup(app: web.Application) -> None:
+    app["gc"] = asyncio.create_task(gc_loop(app))
+
+
+async def on_shutdown(app: web.Application) -> None:
+    for room in list(rooms.values()):
+        await drop_room(room, "relay restarting")
+    app["gc"].cancel()
+
+
+def make_app() -> web.Application:
+    app = web.Application(middlewares=[errors_middleware], client_max_size=16 * 1024)
+    app.router.add_get("/", index)
+    app.router.add_get("/health", health)
+    app.router.add_post("/v1/rooms", create_room)
+    app.router.add_delete("/v1/rooms/{room}", close_room)
+    app.router.add_get("/v1/rooms/{room}/ws", connect)
+    app.on_startup.append(on_startup)
+    app.on_shutdown.append(on_shutdown)
+    return app
+
+
+if __name__ == "__main__":
+    web.run_app(make_app(), host=env_str("LYNX_RELAY_HOST", "127.0.0.1"), port=env_int("LYNX_RELAY_PORT", 8082),
+                access_log=None)

+ 54 - 0
server/caddy/Caddyfile

@@ -0,0 +1,54 @@
+# LYNX SHARE server: Caddy reverse proxy with automatic HTTPS (Let's Encrypt / ZeroSSL).
+# Installed to /etc/caddy/Caddyfile by server/setup.sh. The services listen on 127.0.0.1 only.
+{
+	# no admin endpoint on a public port (default is localhost:2019, kept)
+	servers {
+		protocols h1 h2 h3
+	}
+}
+
+(common) {
+	header {
+		Strict-Transport-Security "max-age=31536000"
+		X-Content-Type-Options nosniff
+		Referrer-Policy no-referrer
+		-Server
+	}
+	# Access log without client addresses or headers (privacy: same rule as the crash-report API, PRIVACY.md).
+	log {
+		output file /var/log/caddy/lynx-access.log {
+			roll_size 20MiB
+			roll_keep 10
+			roll_keep_for 720h
+		}
+		format filter {
+			wrap json
+			fields {
+				request>remote_ip delete
+				request>remote_port delete
+				request>client_ip delete
+				request>headers delete
+				resp_headers delete
+			}
+		}
+	}
+}
+
+api.lynx-share.com {
+	import common
+	# share uploads: at most 2 GiB per file (the service checks the declared size too)
+	request_body {
+		max_size 2100MB
+	}
+	reverse_proxy 127.0.0.1:8081 {
+		flush_interval -1
+	}
+}
+
+relay.lynx-share.com {
+	import common
+	request_body {
+		max_size 64KB
+	}
+	reverse_proxy 127.0.0.1:8082
+}

+ 10 - 0
server/deploy.sh

@@ -0,0 +1,10 @@
+#!/usr/bin/env bash
+# Deploy the repo's server/ folder to the LYNX SHARE VPS and run setup.sh there (idempotent).
+#   server/deploy.sh [ssh-host]      default host: lynx-vps (alias in ~/.ssh/config)
+# Then: python3 server/tests/smoke.py   (end-to-end check against the live URLs)
+set -euo pipefail
+HOST=${1:-lynx-vps}
+cd "$(dirname "$0")"
+tar --create --gzip --exclude='__pycache__' --exclude='*.pyc' --exclude='*.env' . \
+  | ssh "$HOST" 'set -e; rm -rf /opt/lynx/src.new; mkdir -p /opt/lynx/src.new; tar -xzf - -C /opt/lynx/src.new;
+                 rm -rf /opt/lynx/src; mv /opt/lynx/src.new /opt/lynx/src; bash /opt/lynx/src/setup.sh'

+ 22 - 0
server/env.example

@@ -0,0 +1,22 @@
+# /etc/lynx/lynx.env — created by setup.sh on the server only (chmod 600, root). Never commit the real file.
+# LYNX_SALT is generated by setup.sh (random, salts the in-memory rate-limit keys).
+LYNX_SALT=
+LYNX_DATA_DIR=/var/lib/lynx
+LYNX_PUBLIC_URL=https://api.lynx-share.com
+LYNX_RELAY_PUBLIC_URL=wss://relay.lynx-share.com
+# Share links (Online Sessions P1)
+LYNX_SHARE_MAX_BYTES=2147483648
+LYNX_SHARE_DEFAULT_DAYS=7
+LYNX_SHARE_MAX_DAYS=30
+LYNX_SHARE_TOTAL_BYTES=64424509440
+LYNX_SHARE_CLIENT_DAILY_BYTES=8589934592
+LYNX_SHARE_CREATES_PER_HOUR=20
+LYNX_SHARE_INCOMPLETE_HOURS=24
+LYNX_MIN_FREE_BYTES=10737418240
+# Relay (Online Sessions P2/P4 skeleton)
+LYNX_RELAY_MAX_PEERS=4
+LYNX_RELAY_MAX_ROOMS=200
+LYNX_RELAY_ROOM_HOURS=12
+LYNX_RELAY_MAX_FRAME=1048576
+LYNX_RELAY_PEER_BPS=4194304
+LYNX_RELAY_ROOMS_PER_HOUR=10

+ 20 - 0
server/ops/backup.sh

@@ -0,0 +1,20 @@
+#!/usr/bin/env bash
+# Daily backup of the LYNX SHARE service data (run by lynx-backup.timer as root).
+# Keeps LYNX_BACKUP_KEEP (default 14) daily archives in /var/backups/lynx (chmod 700, archives 600).
+# Share blobs (/var/lib/lynx/shares/*/blob) are NOT backed up: they are temporary (they expire in days), can be up to
+# 60 GB in total and the host re-uploads a link that was lost. Their metadata is backed up.
+set -euo pipefail
+DEST=/var/backups/lynx
+KEEP=${LYNX_BACKUP_KEEP:-14}
+install -d -m 700 "$DEST"
+STAMP=$(date -u +%Y%m%d-%H%M)
+OUT="$DEST/lynx-$STAMP.tar.gz"
+umask 077
+paths=()
+for p in /etc/lynx /etc/caddy /var/lib/caddy /var/lib/lynx; do [ -e "$p" ] && paths+=("$p"); done
+tar --create --gzip --file "$OUT.part" --warning=no-file-changed --exclude='/var/lib/lynx/shares/*/blob' \
+    --exclude='*.tmp' "${paths[@]}" 2>/dev/null || [ $? -eq 1 ]
+mv "$OUT.part" "$OUT"
+# rotation: newest $KEEP archives stay
+ls -1t "$DEST"/lynx-*.tar.gz 2>/dev/null | tail -n +"$((KEEP + 1))" | xargs -r rm -f
+echo "$(date -u +%FT%TZ) backup $OUT $(stat -c %s "$OUT") bytes, $(ls -1 "$DEST"/lynx-*.tar.gz | wc -l) kept" >> /var/log/lynx/backup.log

+ 4 - 0
server/ops/journald-lynx.conf

@@ -0,0 +1,4 @@
+# /etc/systemd/journald.conf.d/lynx.conf (installed by server/setup.sh): keep the journal small on the VPS.
+[Journal]
+SystemMaxUse=500M
+MaxRetentionSec=1month

+ 11 - 0
server/ops/logrotate-lynx

@@ -0,0 +1,11 @@
+# /etc/logrotate.d/lynx (installed by server/setup.sh). Caddy rolls its own access log (Caddyfile); the services log
+# to the journal (capped by /etc/systemd/journald.conf.d/lynx.conf).
+/var/log/lynx/*.log {
+	weekly
+	rotate 8
+	compress
+	delaycompress
+	missingok
+	notifempty
+	create 0640 root adm
+}

+ 37 - 0
server/ops/monitor.sh

@@ -0,0 +1,37 @@
+#!/usr/bin/env bash
+# LYNX SHARE health + resource check (lynx-monitor.timer, every 5 minutes, as root).
+# - restarts a service whose /health fails twice in a row (systemd's Restart=always covers crashes; this covers hangs)
+# - checks the public HTTPS path through Caddy (certificate, DNS, proxy) and reloads Caddy if only that fails
+# - logs one line per run to /var/log/lynx/monitor.log; warnings also go to the journal (journalctl -t lynx-monitor)
+set -uo pipefail
+LOG=/var/log/lynx/monitor.log
+STATE=/run/lynx-monitor; mkdir -p "$STATE"
+warn() { logger -t lynx-monitor -p user.warning "$*"; echo "$(date -u +%FT%TZ) WARN $*" >> "$LOG"; }
+
+check() { # name url unit
+  if curl -sf -m 10 -o /dev/null "$2"; then rm -f "$STATE/$1.fail"; echo ok; return; fi
+  if [ -e "$STATE/$1.fail" ]; then warn "$1 health failed twice: restarting $3"; systemctl restart "$3"; rm -f "$STATE/$1.fail"
+  else touch "$STATE/$1.fail"; fi
+  echo FAIL
+}
+api=$(check api http://127.0.0.1:8081/health lynx-api)
+relay=$(check relay http://127.0.0.1:8082/health lynx-relay)
+pub=ok
+for h in api relay; do
+  if ! curl -sf -m 15 -o /dev/null "https://$h.lynx-share.com/health"; then pub=FAIL; fi
+done
+if [ "$pub" = FAIL ] && [ "$api" = ok ] && [ "$relay" = ok ]; then
+  if [ -e "$STATE/public.fail" ]; then warn "public HTTPS failed twice: reloading caddy"; systemctl reload-or-restart caddy; rm -f "$STATE/public.fail"
+  else touch "$STATE/public.fail"; fi
+else rm -f "$STATE/public.fail"; fi
+
+load=$(cut -d' ' -f1-3 /proc/loadavg)
+mem=$(free -m | awk '/^Mem:/ {printf "%d/%dMB", $3, $2}')
+disk=$(df -P / | awk 'NR==2 {print $5}')
+diskpct=${disk%\%}
+shares=$(du -sm /var/lib/lynx/shares 2>/dev/null | cut -f1)
+echo "$(date -u +%FT%TZ) api=$api relay=$relay https=$pub load=[$load] mem=$mem disk=$disk shares=${shares:-0}MB" >> "$LOG"
+[ "$diskpct" -ge 85 ] && warn "disk at $disk"
+avail=$(free -m | awk '/^Mem:/ {print $7}'); [ "$avail" -lt 500 ] && warn "low memory: ${avail}MB available"
+for u in lynx-api lynx-relay caddy; do systemctl is-active -q "$u" || warn "$u is not active"; done
+exit 0

+ 82 - 0
server/setup.sh

@@ -0,0 +1,82 @@
+#!/usr/bin/env bash
+# LYNX SHARE server setup — idempotent; run as root ON THE VPS from a copy of the repo's server/ folder.
+# Normally started by server/deploy.sh from a workstation (copies server/ to /opt/lynx/src and runs this).
+# Safe to run again at any time: it installs/updates packages, code, Caddy config, units and timers, never touches
+# SSH settings, keeps /etc/lynx/lynx.env (secrets) and all data.
+set -euo pipefail
+[ "$(id -u)" = 0 ] || { echo "run as root"; exit 1; }
+SRC=$(cd "$(dirname "$0")" && pwd)
+export DEBIAN_FRONTEND=noninteractive
+
+echo "== packages"
+need=()
+for p in caddy python3-aiohttp curl logrotate ufw; do dpkg -s "$p" >/dev/null 2>&1 || need+=("$p"); done
+if [ ${#need[@]} -gt 0 ]; then apt-get update -q; apt-get install -y -q --no-install-recommends "${need[@]}"; fi
+
+echo "== user and folders"
+id lynx >/dev/null 2>&1 || useradd --system --home-dir /var/lib/lynx --shell /usr/sbin/nologin lynx
+install -d -m 755 /opt/lynx /opt/lynx/app /opt/lynx/ops
+install -d -m 700 -o lynx -g lynx /var/lib/lynx /var/lib/lynx/shares
+install -d -m 700 /etc/lynx /var/backups/lynx
+install -d -m 750 -g adm /var/log/lynx
+install -d -m 755 -o caddy -g caddy /var/log/caddy
+
+echo "== secrets (/etc/lynx/lynx.env, kept if present)"
+if [ ! -f /etc/lynx/lynx.env ]; then
+  umask 077
+  sed "s/^LYNX_SALT=.*/LYNX_SALT=$(head -c 32 /dev/urandom | od -An -tx1 | tr -d ' \n')/" "$SRC/env.example" > /etc/lynx/lynx.env
+fi
+chmod 600 /etc/lynx/lynx.env; chown root:root /etc/lynx/lynx.env
+# new keys added to env.example later are appended with their defaults (existing values are never changed)
+while IFS= read -r line; do
+  k=${line%%=*}; case "$line" in ''|\#*) continue;; esac
+  grep -q "^$k=" /etc/lynx/lynx.env || echo "$line" >> /etc/lynx/lynx.env
+done < "$SRC/env.example"
+
+echo "== code"
+changed=0
+for f in "$SRC"/app/*.py; do
+  cmp -s "$f" "/opt/lynx/app/$(basename "$f")" || { install -m 644 "$f" /opt/lynx/app/; changed=1; }
+done
+install -m 755 "$SRC"/ops/backup.sh "$SRC"/ops/monitor.sh /opt/lynx/ops/
+install -m 644 "$SRC"/ops/logrotate-lynx /etc/logrotate.d/lynx
+install -d /etc/systemd/journald.conf.d
+if ! cmp -s "$SRC/ops/journald-lynx.conf" /etc/systemd/journald.conf.d/lynx.conf; then
+  install -m 644 "$SRC/ops/journald-lynx.conf" /etc/systemd/journald.conf.d/lynx.conf
+  systemctl restart systemd-journald
+fi
+python3 -m py_compile /opt/lynx/app/*.py && rm -rf /opt/lynx/app/__pycache__
+
+echo "== systemd units"
+units_changed=0
+for f in "$SRC"/systemd/*; do
+  cmp -s "$f" "/etc/systemd/system/$(basename "$f")" || { install -m 644 "$f" /etc/systemd/system/; units_changed=1; }
+done
+systemctl daemon-reload
+systemctl enable -q lynx-api lynx-relay lynx-backup.timer lynx-monitor.timer caddy
+if [ $changed = 1 ] || [ $units_changed = 1 ]; then systemctl restart lynx-api lynx-relay; else systemctl start lynx-api lynx-relay; fi
+systemctl start lynx-backup.timer lynx-monitor.timer
+
+echo "== firewall (22 stays open; adds 80/443 for Caddy)"
+ufw allow 22/tcp >/dev/null
+ufw allow 80/tcp >/dev/null
+ufw allow 443/tcp >/dev/null
+ufw allow 443/udp >/dev/null   # HTTP/3
+ufw status | grep -q 'Status: active' || { echo "ufw inactive: enable it by hand after checking (ufw enable)"; }
+
+echo "== caddy"
+caddy validate --config "$SRC/caddy/Caddyfile" --adapter caddyfile >/dev/null 2>&1 || { caddy validate --config "$SRC/caddy/Caddyfile" --adapter caddyfile; exit 1; }
+if ! cmp -s "$SRC/caddy/Caddyfile" /etc/caddy/Caddyfile; then
+  install -m 644 "$SRC/caddy/Caddyfile" /etc/caddy/Caddyfile
+  systemctl reload-or-restart caddy
+fi
+systemctl is-active -q caddy || systemctl start caddy
+
+echo "== local health"
+for i in 1 2 3 4 5 6 7 8 9 10; do
+  if curl -sf -m 5 http://127.0.0.1:8081/health >/dev/null && curl -sf -m 5 http://127.0.0.1:8082/health >/dev/null; then break; fi
+  sleep 1
+done
+curl -sf -m 5 http://127.0.0.1:8081/health; echo
+curl -sf -m 5 http://127.0.0.1:8082/health; echo
+echo "setup done"

+ 31 - 0
server/systemd/lynx-api.service

@@ -0,0 +1,31 @@
+[Unit]
+Description=LYNX SHARE API (health, share links)
+After=network-online.target
+Wants=network-online.target
+
+[Service]
+User=lynx
+Group=lynx
+EnvironmentFile=/etc/lynx/lynx.env
+WorkingDirectory=/opt/lynx/app
+ExecStart=/usr/bin/python3 -s /opt/lynx/app/lynx_api.py
+Restart=always
+RestartSec=3
+MemoryMax=768M
+TasksMax=64
+Nice=5
+NoNewPrivileges=yes
+ProtectSystem=strict
+ProtectHome=yes
+PrivateTmp=yes
+PrivateDevices=yes
+ProtectKernelTunables=yes
+ProtectKernelModules=yes
+ProtectControlGroups=yes
+RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
+LockPersonality=yes
+ReadWritePaths=/var/lib/lynx
+UMask=0077
+
+[Install]
+WantedBy=multi-user.target

+ 8 - 0
server/systemd/lynx-backup.service

@@ -0,0 +1,8 @@
+[Unit]
+Description=LYNX SHARE daily backup of service data
+
+[Service]
+Type=oneshot
+ExecStart=/opt/lynx/ops/backup.sh
+Nice=15
+IOSchedulingClass=idle

+ 10 - 0
server/systemd/lynx-backup.timer

@@ -0,0 +1,10 @@
+[Unit]
+Description=LYNX SHARE daily backup
+
+[Timer]
+OnCalendar=*-*-* 04:20:00
+RandomizedDelaySec=15min
+Persistent=true
+
+[Install]
+WantedBy=timers.target

+ 7 - 0
server/systemd/lynx-monitor.service

@@ -0,0 +1,7 @@
+[Unit]
+Description=LYNX SHARE health and resource check
+
+[Service]
+Type=oneshot
+ExecStart=/opt/lynx/ops/monitor.sh
+Nice=10

+ 9 - 0
server/systemd/lynx-monitor.timer

@@ -0,0 +1,9 @@
+[Unit]
+Description=LYNX SHARE health and resource check every 5 minutes
+
+[Timer]
+OnBootSec=2min
+OnUnitActiveSec=5min
+
+[Install]
+WantedBy=timers.target

+ 31 - 0
server/systemd/lynx-relay.service

@@ -0,0 +1,31 @@
+[Unit]
+Description=LYNX SHARE relay (Online Sessions WebSocket rooms)
+After=network-online.target
+Wants=network-online.target
+
+[Service]
+User=lynx
+Group=lynx
+EnvironmentFile=/etc/lynx/lynx.env
+WorkingDirectory=/opt/lynx/app
+ExecStart=/usr/bin/python3 -s /opt/lynx/app/lynx_relay.py
+Restart=always
+RestartSec=3
+MemoryMax=512M
+TasksMax=64
+Nice=5
+NoNewPrivileges=yes
+ProtectSystem=strict
+ProtectHome=yes
+PrivateTmp=yes
+PrivateDevices=yes
+ProtectKernelTunables=yes
+ProtectKernelModules=yes
+ProtectControlGroups=yes
+RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
+LockPersonality=yes
+ReadOnlyPaths=/opt/lynx
+UMask=0077
+
+[Install]
+WantedBy=multi-user.target

+ 182 - 0
server/tests/smoke.py

@@ -0,0 +1,182 @@
+"""End-to-end smoke test of the LYNX SHARE server (share links + relay).
+
+    python3 server/tests/smoke.py                          # the live server (api./relay.lynx-share.com)
+    python3 server/tests/smoke.py http://127.0.0.1:8081 ws://127.0.0.1:8082    # local services
+
+Needs aiohttp (pip install aiohttp, or apt install python3-aiohttp). Creates one small share and one room, checks
+them, and deletes both. Exit code 0 = all good.
+"""
+from __future__ import annotations
+
+import asyncio
+import hashlib
+import io
+import json
+import os
+import sys
+import zipfile
+
+import aiohttp
+
+API = sys.argv[1] if len(sys.argv) > 1 else "https://api.lynx-share.com"
+RELAY = sys.argv[2] if len(sys.argv) > 2 else "wss://relay.lynx-share.com"
+RELAY_HTTP = RELAY.replace("wss://", "https://").replace("ws://", "http://")
+failures = 0
+
+
+def check(cond: bool, what: str) -> None:
+    global failures
+    print(("ok   " if cond else "FAIL ") + what)
+    if not cond:
+        failures += 1
+
+
+def make_pack(size: int) -> bytes:
+    buf = io.BytesIO()
+    with zipfile.ZipFile(buf, "w", zipfile.ZIP_STORED) as z:
+        z.writestr("project.lynx", json.dumps({"smoke": True}))
+        z.writestr("Samples/noise.bin", os.urandom(size))
+    return buf.getvalue()
+
+
+async def shares(s: aiohttp.ClientSession) -> None:
+    async with s.get(f"{API}/health") as r:
+        h = await r.json()
+        check(r.status == 200 and h.get("ok") and h.get("service") == "lynx-api", f"api /health {r.status} {h}")
+
+    pack = make_pack(3 * 1024 * 1024 + 123)
+    sha = hashlib.sha256(pack).hexdigest()
+
+    # bad requests are refused
+    async with s.post(f"{API}/v1/shares", json={"name": "x.exe", "size": 10}) as r:
+        check(r.status == 400, f"wrong extension refused ({r.status})")
+    async with s.post(f"{API}/v1/shares", json={"name": "big.lynxpack", "size": 3 * 1024 ** 3}) as r:
+        check(r.status == 413, f"over 2 GB refused ({r.status})")
+
+    async with s.post(f"{API}/v1/shares", json={"name": "Smoke test.lynxpack", "size": len(pack), "days": 1,
+                                                 "sha256": sha}) as r:
+        c = await r.json()
+        check(r.status == 201 and len(c["id"]) == 26 and c["token"], f"create {r.status}")
+    sid, tok = c["id"], c["token"]
+    auth = {"Authorization": f"Bearer {tok}"}
+
+    async with s.get(f"{API}/v1/shares/{sid}/download") as r:
+        check(r.status == 409, f"download before upload finished refused ({r.status})")
+    async with s.patch(c["uploadUrl"], data=pack[:100], headers={"Upload-Offset": "0"}) as r:
+        check(r.status == 401, f"upload without token refused ({r.status})")
+    async with s.patch(c["uploadUrl"], data=b"MZ" + pack[2:100], headers={**auth, "Upload-Offset": "0"}) as r:
+        check(r.status == 415, f"non-zip refused ({r.status})")
+
+    # resumable upload in two parts, with a wrong offset in between
+    half = len(pack) // 2
+    async with s.patch(c["uploadUrl"], data=pack[:half], headers={**auth, "Upload-Offset": "0"}) as r:
+        j = await r.json()
+        check(r.status == 200 and j["offset"] == half and not j["complete"], f"part 1 ({r.status})")
+    async with s.patch(c["uploadUrl"], data=pack[half:], headers={**auth, "Upload-Offset": "0"}) as r:
+        check(r.status == 409 and r.headers.get("Upload-Offset") == str(half), f"wrong offset refused ({r.status})")
+    async with s.get(f"{API}/v1/shares/{sid}") as r:
+        j = await r.json()
+        check(j["received"] == half, f"received after part 1 = {j['received']}")
+    async with s.patch(c["uploadUrl"], data=pack[half:], headers={**auth, "Upload-Offset": str(half)}) as r:
+        j = await r.json()
+        check(r.status == 200 and j["complete"] and j["sha256"] == sha, f"part 2 completes, sha256 ok ({r.status})")
+
+    async with s.get(j["downloadUrl"]) as r:
+        body = await r.read()
+        check(r.status == 200 and body == pack, f"download identical ({len(body)} bytes)")
+        check("attachment" in r.headers.get("Content-Disposition", ""), "download is an attachment")
+    async with s.get(j["downloadUrl"], headers={"Range": "bytes=10-19"}) as r:
+        body = await r.read()
+        check(r.status == 206 and body == pack[10:20], f"range request ({r.status})")
+    async with s.get(j["url"]) as r:
+        text = await r.text()
+        check(r.status == 200 and "Smoke test.lynxpack" in text and "Download" in text, f"link page ({r.status})")
+    async with s.get(f"{API}/v1/shares/{'a' * 26}") as r:
+        check(r.status == 404, f"unknown id 404 ({r.status})")
+    async with s.get(f"{API}/v1/shares/") as r:
+        check(r.status == 404, f"no listing ({r.status})")
+
+    async with s.delete(f"{API}/v1/shares/{sid}") as r:
+        check(r.status == 401, f"delete without token refused ({r.status})")
+    async with s.delete(f"{API}/v1/shares/{sid}", headers=auth) as r:
+        check(r.status == 204, f"delete ({r.status})")
+    async with s.get(j["downloadUrl"]) as r:
+        check(r.status == 404, f"gone after delete ({r.status})")
+
+
+async def relay(s: aiohttp.ClientSession) -> None:
+    async with s.get(f"{RELAY_HTTP}/health") as r:
+        h = await r.json()
+        check(r.status == 200 and h.get("service") == "lynx-relay", f"relay /health {r.status} {h}")
+    async with s.post(f"{RELAY_HTTP}/v1/rooms") as r:
+        room = await r.json()
+        check(r.status == 201 and room["maxPeers"] == 4, f"room created ({r.status})")
+    url = f"{RELAY}/v1/rooms/{room['room']}/ws"
+    auth = {"Authorization": f"Bearer {room['token']}"}
+
+    try:
+        async with s.ws_connect(url, headers={"Authorization": "Bearer wrong"}):
+            check(False, "wrong room token refused")
+    except aiohttp.WSServerHandshakeError as e:
+        check(e.status == 401, f"wrong room token refused ({e.status})")
+
+    peers = []
+    for i in range(4):
+        if i == 3:  # the browser way: token as a second subprotocol
+            ws = await s.ws_connect(url, protocols=("lynx-relay.v1", "token." + room["token"]))
+        else:
+            ws = await s.ws_connect(url, headers=auth, protocols=("lynx-relay.v1",))
+        w = await ws.receive_json(timeout=5)
+        check(w["type"] == "welcome" and w["peer"] == i + 1, f"peer {i + 1} welcome {w}")
+        peers.append(ws)
+    try:
+        async with s.ws_connect(url, headers=auth):
+            check(False, "5th peer refused")
+    except aiohttp.WSServerHandshakeError as e:
+        check(e.status == 409, f"5th peer refused ({e.status})")
+
+    async def next_binary(ws):
+        while True:
+            m = await ws.receive(timeout=5)
+            if m.type == aiohttp.WSMsgType.BINARY:
+                return m.data
+
+    # echo (destination = own peer id), unicast, broadcast
+    await peers[0].send_bytes(bytes([1]) + b"echo")
+    check(await next_binary(peers[0]) == bytes([1]) + b"echo", "echo to self")
+    await peers[0].send_bytes(bytes([3]) + b"to three")
+    check(await next_binary(peers[2]) == bytes([1]) + b"to three", "peer 1 -> peer 3")
+    big = os.urandom(512 * 1024)
+    await peers[1].send_bytes(bytes([0]) + big)
+    got = [await next_binary(p) for p in (peers[0], peers[2], peers[3])]
+    check(all(g == bytes([2]) + big for g in got), "peer 2 broadcast 512 KB to the 3 others")
+    await peers[3].send_json({"type": "ping", "t": 7})
+    while True:
+        m = await peers[3].receive_json(timeout=5)
+        if m["type"] == "pong":
+            break
+    check(m["t"] == 7, "ping/pong")
+
+    async with s.delete(f"{RELAY_HTTP}/v1/rooms/{room['room']}") as r:
+        check(r.status == 401, f"close without host token refused ({r.status})")
+    async with s.delete(f"{RELAY_HTTP}/v1/rooms/{room['room']}",
+                        headers={"Authorization": f"Bearer {room['hostToken']}"}) as r:
+        check(r.status == 204, f"room closed by host ({r.status})")
+    for ws in peers:
+        while (await ws.receive(timeout=5)).type not in (aiohttp.WSMsgType.CLOSE, aiohttp.WSMsgType.CLOSED,
+                                                         aiohttp.WSMsgType.CLOSING):
+            pass
+        await ws.close()
+    check(all(ws.closed for ws in peers), "every peer disconnected")
+
+
+async def main() -> int:
+    async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=120)) as s:
+        await shares(s)
+        await relay(s)
+    print("FAILURES:", failures)
+    return 1 if failures else 0
+
+
+if __name__ == "__main__":
+    sys.exit(asyncio.run(main()))