Repository Public
1<div align="center">23<img src="docs/brand/logo.svg" alt="SP Message logo" width="560">45<br><br>67<img src="docs/brand/icon.png" alt="SP Message icon" width="112" height="112">89# SP Message1011**Private, invitation-only, end-to-end encrypted messaging — MLS (RFC 9420) for every conversation, passkey sign-in, client-side encrypted attachments and WebRTC calls through a self-hosted TURN relay. The server is a delivery service that holds no key able to decrypt anything.**1213**Author: [Simon-Pierre Boucher](https://www.spboucher.ai)**1415[](https://message.spboucher.ai)1617181920212223242526272829303132333435363738394041[](https://git.spboucher.ai/sp-message/commits)42[](https://git.spboucher.ai/sp-message/commits)43[](https://git.spboucher.ai/sp-message/insights)44[](https://git.spboucher.ai/sp-message)45[](https://git.spboucher.ai/sp-message/insights)46[](https://git.spboucher.ai/sp-message)47[](https://git.spboucher.ai/sp-message/branches)48[](https://git.spboucher.ai/sp-message/tags)49[](https://git.spboucher.ai/sp-message)5051525354555657585960616263646566676869</div>7071---7273## Table of contents7475- [Overview](#-overview)76- [Features](#-features)77- [Architecture](#-architecture)78- [Stack](#-stack)79- [Repository layout](#-repository-layout)80- [Getting started](#-getting-started)81- [Configuration](#-configuration)82- [API](#-api)83- [Data model](#-data-model)84- [Security and privacy](#-security-and-privacy)85- [Testing](#-testing)86- [Deployment and operations](#-deployment-and-operations)87- [Incidents and gotchas](#-incidents-and-gotchas)88- [Status, limits and open items](#-status-limits-and-open-items)89- [Documentation](#-documentation)90- [Author](#-author)91- [License](#-license)9293---9495## 🎯 Overview9697SP Message is a private messaging service — **https://message.spboucher.ai** — for a small circle of invited people.9899Self-hosted on MacLustr: custom TypeScript backend (Fastify, PostgreSQL, WebSocket), custom React interface, passkey sign-in (WebAuthn), MLS (RFC 9420) encryption for every conversation, client-side encrypted attachments, WebRTC calls through a self-hosted TURN relay.100101- **Invitation only.** No account exists without an invitation or the one-time administrator bootstrap.102- **The server is a delivery service.** It authenticates accounts, stores and orders ciphertext, hands out public key packages and relays events. It holds no key able to decrypt a message, a file or a call.103- **Authentication and encryption are separate.** Passkeys only prove who signs in; they never encrypt anything. Encryption identities are generated on the device.104- **Honest about its limits.** The MLS library has had no independent audit, and a web-delivered E2EE application trusts the server that serves its code — both are stated plainly in [`docs/THREAT-MODEL.md`](docs/THREAT-MODEL.md).105106### The SP Message family107108| Piece | spbgit repository | Role |109|---|---|---|110| Backend, web application, client engine | **[sp-message](https://git.spboucher.ai/sp-message)** (this repository) | `https://message.spboucher.ai` |111| macOS and iOS apps | [sp-message-apple](https://git.spboucher.ai/sp-message-apple) | SwiftUI interface around the same client engine, hosted by [`native/core.ts`](native/core.ts) |112113## ✨ Features114115| Area | What the code does |116|---|---|117| **Accounts** | one-time administrator bootstrap, invitations (single or limited use, expiry, revocation, approval), passkey sign-in with discoverable credentials and required user verification, revocable sessions |118| **Identity and devices** | Ed25519 identity key generated on the first device; one Ed25519 device key per browser, valid only with a certificate signed by the identity key; adding a device is never silent (six-digit code comparison, or recovery key) |119| **Messaging** | one MLS group per conversation (direct or group), every device a leaf; forward secrecy and post-compromise security; total order of epochs enforced by the server; per-conversation sequence numbers; persistent outbox |120| **Encrypted application messages** | edits, deletions, reactions, pins, read receipts, group name, disappearing timer, shared tasks, call signalling |121| **Attachments** | random 256-bit key per file, 1 MiB chunks, AES-256-GCM, resumable chunked upload, tamper / reorder / truncation detection, membership-checked download, quota |122| **Calls** | WebRTC full mesh up to 6 participants; offers, answers and ICE candidates travel as MLS messages; screen sharing, mute, camera off / switch, speaker selection, picture-in-picture, call waiting, ICE restart, call history |123| **Verification** | pinned identity keys (trust on first use), 60-digit safety number and QR code, warning when a key changes — a changed key is not used until accepted |124| **Self-sync** | drafts, private notes and preferences sealed with a key derived from the identity key and synced between a person's own devices |125| **Premium** | search, scheduling, tasks, notes, bookmarks, waveforms, verification QR |126| **Administration** | overview (accounts, devices, connections, storage, TURN), people, invitations, sessions, audit log, *reset encryption identity*, disable account |127| **Native host** | `native/core.ts` runs the same engine inside the Apple apps: HTTP, WebSocket and storage are provided by Swift through a message bridge |128| **Operations** | operator CLI, migrations applied at start, encrypted backup with restore verification, health endpoints |129130## 🏗 Architecture131132```mermaid133flowchart LR134 subgraph Clients135 W["Browser — React + engine<br/>IndexedDB: keys, group states,<br/>decrypted history"]136 N["Apple apps — SwiftUI<br/>same engine via native/core.ts"]137 end138 subgraph GW["Gateway BHS64"]139 C["Caddy · HTTPS / WSS<br/>message.spboucher.ai"]140 T["coturn 4.6.1<br/>TURN / STUN 3478"]141 end142 subgraph NODE["MacLustr node M4M64c"]143 S["sp-message · port 8720<br/>Fastify API · WebSocket gateway · web"]144 PG[("PostgreSQL 17 · sp_message<br/>accounts, devices, ciphertext")]145 B[("blobs/<br/>encrypted chunks")]146 K["sp-message-backup<br/>daily 03:25"]147 end148 W -->|HTTPS / WSS| C149 N -->|HTTPS / WSS| C150 C -->|WireGuard| S151 S --- PG152 S --- B153 K --> PG154 W <-.->|"WebRTC media (DTLS-SRTP), direct or relayed"| T155 N <-.-> T156```157158### What was chosen, and what was evaluated and left out159160| Need | Choice | Reason |161|---|---|---|162| Hosting node | **M4M64c**, port 8720, PM2, placed by `mld` | Node, pnpm and PostgreSQL 17 present |163| Public entry | Caddy on the gateway (MacLustr Tunnel) | automatic TLS; WebSocket passes through |164| Metadata store | PostgreSQL 17, database `sp_message` (local to the node) | transactions order the group epochs |165| Ephemeral state | in-process (single Node process) | **Redis was evaluated and not added**: nothing needs to be shared between processes yet. Rate-limit counters, presence and typing state are lost on restart, which is acceptable |166| Object storage | directory tree behind a four-function interface (`server/src/files.ts`) | objects are already ciphertext; **MinIO/S3 was evaluated and not added**. The interface makes the swap local to one file |167| TURN/STUN | **coturn 4.6.1** on the gateway, UDP/TCP 3478, relay ports 49160–49400 | LAN nodes sit behind NAT; only the gateway has a public address |168| SFU | **not deployed** | an SFU terminates DTLS and would see media without frame encryption; group calls are capped at 6 by the mesh |169170### Sending a message171172```mermaid173sequenceDiagram174 autonumber175 participant A as Device A (engine)176 participant S as Server (delivery service)177 participant B as Device B (engine)178 A->>A: MLS encrypt (application message, client id)179 A->>S: POST /api/conversations/:id/messages (ciphertext)180 S->>S: membership check, sequence number, store ciphertext181 S-->>A: sequence number182 S-->>B: WebSocket event183 B->>S: GET /api/sync (everything after the device cursor)184 S-->>B: ordered ciphertext185 B->>B: MLS decrypt, sender read from authenticated content186 B->>S: POST /api/conversations/:id/ack187 Note over S: ciphertext older than 90 days is deleted188```189190### Adding a device by approval191192```mermaid193sequenceDiagram194 autonumber195 participant N as New device196 participant S as Server197 participant T as Trusted device198 N->>N: generate device key + one-time HPKE key199 N->>S: POST /api/devices (public keys)200 N->>N: show six-digit code derived from the HPKE key201 S-->>T: device link request202 T->>T: show the same code — the person compares203 T->>S: POST /api/devices/:id/approve (certificate + identity key sealed with HPKE)204 S-->>N: certificate + sealed identity key205 N->>N: open the seal, upload key packages206 Note over T,N: a server substituting keys changes the code207```208209### Protocol notes210211- Ciphersuite `MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519` (all primitives from WebCrypto).212- Commits (membership changes) are accepted only if built on the current epoch (`409` otherwise; the client re-syncs and retries).213- Clients *reconcile* groups with the directory: they add newly certified devices of accounts **already in the group**, and remove revoked devices and departed accounts. They never add an account because the server lists it.214- Typing indicators and presence are plain events (metadata only); presence is opt-in.215- Recovery key: 160 random bits shown once; it decrypts a backup of the identity key (HKDF-SHA256 → AES-256-GCM).216- Attachments: nonce = random prefix ‖ chunk index, associated data = index and final-chunk flag. Key, name, type, dimensions, thumbnail and waveform travel only inside the encrypted message.217218## 🧱 Stack219220| Layer | Technology | Version (read in the repository) | Role |221|---|---|---|---|222| Server | Fastify · `@fastify/cookie` · `@fastify/static` | ^5.12.8 · ^11.1.5 · ^10.1.11 | API, sessions, web bundle |223| Realtime | `ws` | ^8.23.0 | WebSocket gateway (`/ws`) |224| Database | PostgreSQL · `postgres` | 17 · ^4.1.1 | accounts, devices, ciphertext |225| Validation | Zod | ^4.6.7 | request bodies |226| Auth | `@simplewebauthn/server` · `/browser` | ^14.1.0 · ^14.0.0 | passkeys |227| MLS | `ts-mls` | ^1.6.4 | RFC 9420 |228| HPKE | `@hpke/core` | ^1.10.1 | RFC 9180, device approval |229| Primitives | `@noble/curves` · `@noble/hashes` · `@noble/ciphers` | ^2.4.0 | Ed25519 and helpers |230| Web | React · react-dom · `qrcode` | ^19.3.1 · ^1.5.4 | interface, verification QR |231| Tooling | TypeScript · Vite · esbuild · tsx | ^7.0.2 · ^8.3.8 · ^0.28.2 · ^4.23.15 | typecheck, web bundle, server bundle |232| Tests | `node:test` · Playwright | — · ^1.65.1 | integration, browser |233| Relay | coturn | 4.6.1 | TURN/STUN |234| Runtime | Node.js | ≥ 22 | `engines` |235236<details>237<summary><b>Library evaluation (docs/ARCHITECTURE.md § 7)</b></summary>238239| Library | Licence | Role | Maturity |240|---|---|---|---|241| `ts-mls` | MIT | MLS RFC 9420 | actively maintained, test vectors, **no independent audit** (stated by its author) |242| `@hpke/core` | MIT | HPKE RFC 9180 | maintained, WebCrypto based |243| `@noble/curves` | MIT | Ed25519 public keys | audited family of libraries |244| `@simplewebauthn/*` | MIT | WebAuthn | widely deployed |245| WebCrypto | — | AES-GCM, HKDF, SHA-256, Ed25519, X25519 | platform |246247Rejected: `@signalapp/libsignal-client` (AGPL-3.0, Node native addon, no supported browser build); `libsignal-protocol-typescript` (GPL-3.0, unmaintained); Matrix vodozemac (audited, but Olm/Megolm has weaker group post-compromise security and its JS binding is tied to the Matrix stack); OpenMLS / mls-rs (Rust, more mature, **no published browser package** — the natural replacement if `ts-mls` proves insufficient). A Signal-style double ratchet for 1:1 plus MLS for groups was considered; a single protocol was preferred to halve the cryptographic surface.248249</details>250251## 🗂 Repository layout252253```254server/src/ Fastify API, WebSocket gateway, WebAuthn, blob store, operator CLI — 11 files, 1 628 lines255 index.ts server start, security headers, WebSocket upgrade (/ws)256 auth.ts session.ts passkeys, bootstrap, invitations, sessions257 messaging.ts conversations, commits, messages, key packages, sync258 files.ts encrypted object store (four-function interface)259 hub.ts WebSocket hub (events, presence, typing)260 admin.ts cli.ts administration routes, operator CLI261 config.ts db.ts util.ts262web/src/core/ client engine, no DOM — 9 files, 2 592 lines263 engine.ts mls.ts crypto.ts identity, MLS, sync, outbox264 media.ts calls.ts attachments, WebRTC calls265 store.ts transport.ts bytes.ts types.ts266web/src/ui/ React interface — 8 files, 2 639 lines (shell, chat, details, callui, settings, admin, app, bits)267web/src/styles.css the design system (376 lines)268web/public/ icon.svg, manifest.webmanifest (installable web app)269native/core.ts engine host for the native Apple apps (315 lines)270db/migrations/ 001_init.sql, 002_operator_invitations.sql — applied at start271scripts/ build.mjs, node-setup.sh, backup.sh (with restore verification), restore.sh272tests/ integration.test.ts, e2e/ (Playwright), load.ts, native-peer.ts, harness.ts273docs/ ARCHITECTURE, THREAT-MODEL, SECURITY-REVIEW, OPERATIONS + brand/274```275276## 🚀 Getting started277278```bash279pnpm install280pnpm build # server bundle + web bundle into dist/281pnpm test # 20 integration tests: real server, real PostgreSQL, simulated devices with software passkeys282pnpm test:e2e # 9 browser tests (Chromium, virtual passkey authenticators, real WebRTC call)283pnpm test:load # 16 accounts, 480 group messages, ordering check284pnpm audit --prod # dependency vulnerabilities285node dist/cli.mjs bootstrap|invite|status|revoke-sessions286```287288Tests refuse to run against a database whose name does not end in `_test`.289290| `pnpm` script | Effect |291|---|---|292| `dev:server` · `dev:web` | `tsx watch server/src/index.ts` · Vite |293| `build` | `scripts/build.mjs` (esbuild → `dist/server.mjs`, `dist/cli.mjs`) then `vite build` |294| `start` · `cli` | `node dist/server.mjs` · `node dist/cli.mjs` |295| `typecheck` | `tsc -p .` |296| `test` · `test:e2e` · `test:load` | integration · browser · load |297| `audit` | `pnpm audit --prod` |298299### Operator CLI300301```bash302node dist/cli.mjs status303node dist/cli.mjs bootstrap --ttl 60 # first administrator, single use304node dist/cli.mjs bootstrap --recover # additional administrator when all admin passkeys are lost305node dist/cli.mjs invite --for "Name" --hours 72306node dist/cli.mjs revoke-sessions <handle>307node dist/cli.mjs migrate308```309310## ⚙️ Configuration311312Names only — values live in the `mld` manifest, never in this repository.313314| Variable | Role |315|---|---|316| `HOST`, `PORT` | listening address (8720 in production) |317| `DATABASE_URL` | PostgreSQL |318| `SPM_ORIGIN`, `SPM_RP_ID` | site origin and WebAuthn relying-party id |319| `SPM_TRUST_PROXY` | trusted reverse proxy |320| `SPM_DATA_DIR` | encrypted object store |321| `SPM_WEB_DIR` | web bundle directory |322| `SPM_TURN_URLS`, `SPM_TURN_SECRET` | TURN relay and its shared **secret** |323| `SPM_MAX_FILE_BYTES` | attachment size limit (default 4 GiB) |324| `SPM_MESSAGE_RETENTION_DAYS` | server-side ciphertext retention (default 90) |325| `SPM_APPLE_APP_IDS` | app ids served by `/.well-known/apple-app-site-association` |326| `SPM_RATE_SCALE` | rate-limit multiplier |327| `SPM_LOG_LEVEL`, `SPM_VERSION` | logging, reported version |328329## 🔌 API33033161 HTTP routes (counted in `server/src`) plus the WebSocket endpoint `/ws`, refused with `401` without a session.332333<details open>334<summary><b>Accounts, passkeys, sessions</b></summary>335336| Route | Role |337|---|---|338| `POST /api/invitations/check` | validate an invitation or bootstrap token (sent in the body, never in a path) |339| `POST /api/register/options` · `/verify` | create an account with a passkey |340| `POST /api/login/options` · `/verify` · `POST /api/logout` | sign in, sign out |341| `GET /api/me` · `PATCH /api/profile` | session and profile |342| `GET /api/passkeys` · `POST /api/passkeys/options` · `/verify` · `DELETE /api/passkeys/:id` | passkey management |343| `GET /api/sessions` · `DELETE /api/sessions/:id` · `POST /api/session/device` | sessions, binding a session to a device |344345</details>346347<details>348<summary><b>Identity, devices, key packages</b></summary>349350| Route | Role |351|---|---|352| `POST /api/identity` | publish the public identity key |353| `GET`/`POST /api/devices` · `POST /api/devices/:id/approve` · `DELETE /api/devices/:id` | device list, link request, approval, removal |354| `GET`/`PUT /api/backup` | identity-key backup (encrypted with the recovery key) |355| `POST /api/keypackages` · `POST /api/keypackages/claim` · `GET /api/keypackages/count` | MLS key packages (capped at 120 per device) |356| `GET /api/directory` · `POST /api/users/lookup` | directory of accounts and their certified devices |357358</details>359360<details>361<summary><b>Conversations, sync, self-sync</b></summary>362363| Route | Role |364|---|---|365| `POST /api/conversations` | create a direct or group conversation |366| `POST /api/conversations/:id/commit` | MLS commit, accepted only on the current epoch (`409` otherwise) |367| `GET`/`POST /api/conversations/:id/messages` | ciphertext, ordered |368| `POST /api/conversations/:id/ack` · `/leave` · `/resync` | acknowledgement, leaving, resync request |369| `POST /api/welcomes/ack` | welcome messages |370| `GET /api/sync` | everything after the device cursor |371| `GET /api/self` · `PUT`/`DELETE /api/self/:key` | sealed blobs synced between a person's own devices (200 blobs of 256 KB) |372373</details>374375<details>376<summary><b>Files, calls, administration, health</b></summary>377378| Route | Role |379|---|---|380| `POST /api/files` · `PUT`/`GET /api/files/:id/chunks/:n` · `POST /api/files/:id/complete` | resumable chunked upload, download |381| `GET /api/files/:id` · `POST /api/files/:id/share` · `DELETE /api/files/:id` | status, attach to a conversation, delete |382| `GET /api/turn` | ICE servers and TURN credentials for a call |383| `GET /api/admin/stats` · `/users` · `/users/:id/sessions` · `/invitations` · `/audit` | administration views |384| `POST /api/admin/invitations` · `DELETE /api/admin/invitations/:id` | invitations |385| `PATCH /api/admin/users/:id` · `POST /api/admin/users/:id/reset-identity` · `DELETE /api/admin/sessions/:id` | disable, reset encryption identity, end a session |386| `GET /api/health/live` · `GET /api/health/ready` | process; database and data directory writable |387| `GET /.well-known/apple-app-site-association` · `GET /robots.txt` | Apple association file, crawlers |388389</details>390391## 🗄 Data model39239320 PostgreSQL tables (`db/migrations/001_init.sql`, 209 lines; `002_operator_invitations.sql`). The server stores public keys and ciphertext only.394395| Group | Tables |396|---|---|397| Accounts | `users`, `passkeys`, `sessions`, `challenges`, `bootstrap_tokens`, `invitations` |398| Devices and keys | `devices`, `key_packages`, `key_backups` |399| Conversations | `conversations`, `conversation_members`, `messages`, `welcomes`, `device_cursors`, `resync_requests` |400| Files | `files`, `file_access` |401| Self-sync and settings | `self_blobs`, `settings` |402| Audit | `audit_log` |403404```mermaid405erDiagram406 users ||--o{ passkeys : has407 users ||--o{ sessions : opens408 devices ||--o{ sessions : binds409 users ||--o{ devices : certifies410 users ||--o{ invitations : issues411 users ||--o{ key_backups : keeps412 users ||--o{ self_blobs : syncs413 users ||--o{ files : uploads414 devices ||--o{ key_packages : uploads415 conversations ||--o{ conversation_members : lists416 users ||--o{ conversation_members : joins417 conversations ||--o{ messages : orders418 conversations ||--o{ welcomes : delivers419 devices ||--o{ welcomes : receives420 conversations ||--o{ device_cursors : positions421 devices ||--o{ device_cursors : tracks422 conversations ||--o{ resync_requests : repairs423 files ||--o{ file_access : grants424 conversations ||--o{ file_access : scopes425```426427## 🔐 Security and privacy428429| Adversary | Can | Cannot |430|---|---|---|431| **Network attacker** | see that a device talks to the site and to the TURN relay; volume and timing | read or alter anything: TLS to the gateway, WireGuard gateway→node, MLS inside, DTLS-SRTP for calls |432| **Curious server administrator / database or backup thief** | read accounts, usernames, public keys, membership, timestamps, sizes, acknowledgements, typing and presence events, IP addresses in session and audit records | read message text, reactions, read receipts, group names, file content, file names, thumbnails, call media |433| **Malicious server (actively lying)** | withhold, delay or drop messages; refuse service; list a false member (**ignored for key distribution**); advertise a false device (**refused**: no certificate); advertise a new identity key (**warning**, not used until accepted) | add a reader without a visible key-change warning; forge a message; replace a working group state; substitute keys during device approval without changing the code |434| **Malicious server delivering altered web code** | **everything** — the main residual risk of any web-delivered E2EE application | native apps with signed binaries remove it |435| **TURN relay operator** | see which IP addresses exchange media and how much | decrypt media |436| **Removed member / revoked device** | keep what it already decrypted | decrypt anything sent after the commit that removed it; fetch ciphertext |437| **Thief of a passkey alone** | sign in, see the conversation list, request a device link | read any message: needs approval from a trusted device or the recovery key |438439Full table: [`docs/THREAT-MODEL.md`](docs/THREAT-MODEL.md).440441**Design decisions**442443- Tokens (session, invitation, bootstrap) are random 256-bit values stored only as SHA-256; invitation and bootstrap tokens travel in the URL fragment and in request bodies, never in a path or query string, so proxies do not log them.444- CSRF: SameSite=Strict cookie + Origin check + custom header; WebSocket origin and session checks; security headers; CSP without inline script.445- Logs record method, path and status. The audit log records administrative and security events with no content.446- Notifications never include message text.447- Disappearing messages are deleted on the server at expiry as well as on devices (a recipient can still copy them).448- Rate limiting: fixed-window, in-memory, single process.449450**Security review (2026-11-18, before public exposure)** — performed by the author of the code; **this is not an independent audit**. Seven findings, all fixed: two *High* (a client extended a group to any account the server listed; a welcome could replace a working group state), two *Medium*, two *Low*, one *Info*. Details, tests and evidence: [`docs/SECURITY-REVIEW.md`](docs/SECURITY-REVIEW.md).451452**Residual risks, stated plainly**4534541. `ts-mls` has had **no independent security audit**.4552. **Web delivery trust**: altered JavaScript served by the origin could exfiltrate keys.4563. **Metadata** is visible to the server by design (membership, timing, sizes). No sealed sender, no padding policy beyond the library default.4574. Local history in IndexedDB is stored decrypted (secrets are wrapped, messages are not).4585. Trust on first use until two people compare safety numbers.4596. One-time key packages can run out; the last-resort package is then reused.4607. Denial of service by the server or a flooding member is only rate-limited.4618. No protection against screenshots, compromised browsers or malicious extensions.462463## 🧪 Testing464465| Suite | Command | Count | What it uses |466|---|---|---|---|467| Integration | `pnpm test` | **20** | real server, real PostgreSQL, simulated devices with software passkeys |468| Browser | `pnpm test:e2e` | **9** | Chromium, virtual passkey authenticators, a real WebRTC call |469| Load | `pnpm test:load` | 16 accounts, 480 group messages | ordering check — 7 200 decryptions in 1.2 s, identical order on every device (2026-11-18) |470| Dependencies | `pnpm audit --prod` | — | no known vulnerabilities (2026-11-18) |471472<details>473<summary><b>The 20 integration tests</b></summary>4744751. bootstrap: one-time administrator creation with a passkey4762. registration is impossible without an invitation4773. invitations: single use, revocation, expiry, approval4784. passkey sign-in, counters, sessions4795. CSRF and transport checks4806. identity creation on the client; the server only receives public keys4817. direct conversation: end-to-end encrypted, authenticated sender, no plaintext on the server4828. edits, deletions, reactions, pins, read receipts; only the author can edit4839. offline delivery, ordering and deduplication after reconnection48410. group conversation: add, remove, removed member loses access48511. concurrent commits: the server orders epochs and the loser recovers48612. second device by approval: same code on both sides, joins every conversation48713. device approval rejects a forged certificate; recovery key restores the identity48814. a server-injected device without a valid certificate is never added to a group48915. an account the server adds to the member list on its own is never given the group keys49016. identity key change raises a warning instead of being trusted silently49117. attachments: client-side encryption, resumable chunks, tamper detection, access control, quota49218. disappearing messages are removed from the server49319. administration: disabling an account cuts sessions and removes its devices from groups49420. rate limiting on sign-in495496</details>497498<details>499<summary><b>The 9 browser tests</b></summary>5005011. sign-in page, and an invalid invitation link5022. administrator bootstrap with a passkey and client-side key generation5033. invitation dashboard, onboarding of an invited person, first encrypted conversation5044. reply, reaction, edit, typing indicator, delivery and read state5055. encrypted attachment: image upload, preview, download5066. contact verification shows the same safety number on both sides5077. audio/video call between two browsers with authenticated signalling5088. second device: approval with matching codes, then messages arrive on both5099. settings, admin people view, mobile navigation, sign-out and sign-in again510511</details>512513## 📦 Deployment and operations514515| Item | Location |516|---|---|517| Application (git clone, source of truth) | `M4M64c:~/apps/sp-message` (origin: spbgit `sp-message.git`) |518| Processes | PM2 `sp-message` (API, WebSocket, web), `sp-message-backup` (03:25 daily) |519| Database | PostgreSQL 17, `sp_message`, local |520| Encrypted objects | `~/sp-message-data/blobs` on the node |521| Backups | `~/backups/sp-message` on the node (14 database archives + mirror of objects) |522| Backup key | `~/.config/sp-message/backup.key` on the node — copy it off the node; without it backups cannot be read |523| Manifest | `mld` manifest on the gateway M1M32 (environment, TURN secret) |524| TURN relay | `coturn` on BHS64 |525| Public route | Caddy on BHS64, managed by `mld` |526527> **Do not `mld move` this app**: the database and the objects do not follow.528529```bash530ssh M4M64c531cd ~/apps/sp-message && git pull # or edit here532pnpm install --frozen-lockfile && node scripts/build.mjs && node_modules/.bin/vite build533pm2 restart sp-message # migrations run at start; clients reconnect by themselves534git add -A && git commit -m "…" && git push origin main535```536537Run `pnpm test` and `pnpm test:e2e` on a machine with a `sp_message_test` database before a release.538539**Health and monitoring**540541- `GET /api/health/live` (process), `GET /api/health/ready` (database and data directory writable).542- `mld status --live`; `mld heal` restarts the process and the route every 5 minutes if needed.543- Logs: `pm2 logs sp-message` (method, path, status; no bodies). Backup log: `pm2 logs sp-message-backup`.544- Admin → Overview shows accounts, devices, connections, storage and whether TURN is configured.545- TURN: `ssh BHS64 systemctl status coturn`, `journalctl -u coturn`.546547**Backup and recovery** — `scripts/backup.sh` dumps the database, encrypts it (AES-256, PBKDF2, key file), mirrors the objects, then **restores the archive into a scratch database and compares row counts**; it fails loudly otherwise. Recovery on a fresh node:5485491. `mld deploy sp-message --node <node>` (creates an empty database), `pm2 stop sp-message`.5502. Copy `backup.key` to `~/.config/sp-message/`, the archive and `blobs/` to `~/backups/sp-message/`.5513. `dropdb sp_message && createdb sp_message && zsh scripts/restore.sh ~/backups/sp-message/db-<stamp>.dump.enc`5524. `pm2 start sp-message`.553554A restore brings back accounts, passkeys, devices, conversations, undelivered ciphertext and files. It cannot bring back messages already delivered and purged, nor anything that only lived on a lost device.555556## 🧯 Incidents and gotchas557558| Situation | Action |559|---|---|560| A person lost one device | They remove it in Settings → Devices from another device |561| A person lost every device, has the recovery key | They sign in with their passkey on a new device and choose “Use my recovery key” |562| A person lost every device and the recovery key | Admin → People → Manage → *Reset encryption identity*; the person enrols again; contacts see a key-change warning and must accept and add them back |563| A person lost every passkey | Their account cannot sign in; disable it and invite them again |564| Administrator lost every passkey | `node dist/cli.mjs bootstrap --recover` on the node |565| Suspected compromise of an account | Admin → People → Disable (sessions end, devices are removed from all groups) |566| TURN secret leaked | New secret in `/etc/turnserver.conf` and in the manifest (`SPM_TURN_SECRET`), restart coturn, `mld deploy sp-message` |567568- **Tests need a `_test` database**: they refuse to run otherwise.569- **Never `mld move`**: data does not follow the app.570- **History on a new device starts when the device is added** — a consequence of forward secrecy, not a bug.571- **Scheduled messages** are sent by the device that scheduled them, which must be open at that time.572- **Upload resumption** survives network loss, not a page reload.573- **Safari may evict IndexedDB** after 7 days without use in a tab; installing the site to the Home Screen avoids the eviction policy.574- **Calls on restrictive networks**: TURN listens on UDP/TCP 3478 without TLS; networks that only allow 443 will not connect calls.575- **Restart loses ephemeral state**: rate-limit counters, presence and typing state are in-process.576577## 🧭 Status, limits and open items578579| Phase | Criteria | Status |580|---|---|---|581| 1 Foundation | bootstrap is single use; no registration without invitation; invitation rules enforced | Met (integration tests 1–4) |582| 2 Secure messaging | no plaintext in the database; sender authenticated; offline delivery in order without duplicates | Met (tests 7–9) |583| 3 Media | ciphertext at rest; tampering and reordering detected; access limited to members; quota | Met (test 17, browser test 5) |584| 4 Multi-device and groups | matching codes; forged certificate refused; removed member cannot read; key-change warning | Met (tests 10–16) |585| 5 Calls | two browsers exchange live video with encrypted signalling; relay-only path works | Met for 1:1. Group mesh implemented, **not tested with 3+ real participants** |586| 6 Premium | search, scheduling, tasks, notes, bookmarks, waveforms, verification QR | Implemented, with the limits below |587| 7 Hardening | review, tests, load, deployment, backup with restore verification | Done |588589**Not implemented, or limited**590591- On-device transcription, local translation, semantic search, AI assistance: not implemented; nothing is sent to any AI provider.592- Push notifications when the app is closed: not implemented (needs a service worker and Web Push).593- Message retention: ciphertext older than 90 days is deleted from the server; devices keep their own history.594- Browser limits: iOS Safari has no screen sharing and no speaker selection; picture-in-picture and QR scanning depend on the browser; HEIC previews render only where the browser decodes HEIC.595596**Open items (not fixed)**5975981. Independent audit of `ts-mls` and of this integration: **not done**.5992. Real Face ID / Touch ID and real iPhone / iPad / Mac Safari: **not tested** (virtual authenticator in Chromium only).6003. Group calls with three or more real participants: not tested.6014. The gateway access log records request paths; no secret is ever placed in a path.6025. No `turns:` listener on 443.6036. Backups stay on the hosting node; an off-node copy is not configured.6047. No step-up passkey check for administrative actions.605606## 📚 Documentation607608| Document | Content |609|---|---|610| [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) | Components, protocol design, library evaluation, phases and acceptance criteria, platform limits |611| [docs/THREAT-MODEL.md](docs/THREAT-MODEL.md) | Assets, adversaries, what each one can and cannot do, residual risks |612| [docs/SECURITY-REVIEW.md](docs/SECURITY-REVIEW.md) | Review performed before exposure: findings, fixes, tests, open items |613| [docs/OPERATIONS.md](docs/OPERATIONS.md) | Deployment, operator commands, backups, recovery, monitoring |614615## 👤 Author616617<div align="center">618<img src="docs/brand/icon.png" width="64" height="64" alt=""><br>619620**Simon-Pierre Boucher** — design, development, operations<br>621[www.spboucher.ai](https://www.spboucher.ai) · [git.spboucher.ai](https://git.spboucher.ai) · contact@spboucher.ai622623</div>624625## 📄 License626627`UNLICENSED` (`package.json`, private repository) — all rights reserved © 2026 Simon-Pierre Boucher.628