Minimal MLS-only wire-server subset in Rust (axum + SQLite), RFC 9420 codec, E2EE messaging with notifications/WebSocket
  • Rust 99.8%
  • TypeScript 0.1%
Find a file
Repository files (latest commit first)
Filename Latest commit message Latest commit date
keith9681 144508a345
Some checks failed
CI / check (push) Has been cancelled
CI / audit (push) Has been cancelled
test(commits): no-token requests expect 401 like every route (A-group tail)
Missed hunk from the A-group batch: the shared AccessAuth answers
missing credentials with 401; the commits-specific 403 guard
(unbound token) in the same test is untouched.
2026-11-11 01:53:20 +00:00
.github/workflows feat: M0-M5 implementation baseline (consolidated backlog commit) 2026-11-07 10:45:44 +08:00
docs feat(auth): missing-token 401 with refresh semantics; /events alias; /cookies stub (A+B+D groups) 2026-11-11 00:43:51 +00:00
migrations feat(assets): per-user quota ledger with named over-quota rejection (T10) 2026-11-11 00:19:08 +00:00
src feat(commits): external-commit acceptance with backlog catch-up (C group body) 2026-11-11 01:52:08 +00:00
tests test(commits): no-token requests expect 401 like every route (A-group tail) 2026-11-11 01:53:20 +00:00
tools fix(key-packages): accept the webapp's 100-package upload; name 413/415 2026-11-10 00:09:24 +08:00
.env.example feat(m11,t06): local asset storage with upload, download and token lifecycle 2026-11-09 20:24:15 +08:00
.gitignore chore: ignore .tmp-issues scratch dir (issue dumps from the gitforge API) 2026-11-09 07:49:40 +08:00
Cargo.lock fix(auth): JSON rejection log never echoes request values 2026-11-10 00:32:08 +08:00
Cargo.toml fix(auth): JSON rejection log never echoes request values 2026-11-10 00:32:08 +08:00
make.ts chore(make): local-only deploy helper with machine-specific note (E group) 2026-11-11 00:45:19 +00:00
README.md 文档:对齐 432323d——StrictJson 命名 413/415,key-packages 512 KiB 2026-11-10 00:15:31 +08:00

wire-rs

A focused Rust/Axum implementation of the MLS-only wire-server subset. Through M10 it provides zauth authentication, Argon2id password hashing, file-backed SQLite persistence, MLS group messaging (commit bundles, application/proposal messages, Welcome delivery, and event generation), notification backlog and WebSocket delivery, and removal keys with backend-signed External Remove Proposals. M11 turns that protocol surface into something a real wire-webapp can boot against without a frontend change: /v{N}/ version prefixes with the API pinned to v8, the bootstrap stubs the webapp calls before it shows anything, device updates (PUT/GET /clients/{cid}), self and 1:1 MLS conversations, and local asset storage. These authentication endpoints:

  • POST /register
  • POST /activate / GET /activate / POST /activate/send
  • POST /login
  • POST /access
  • POST /access/logout
  • GET /self
  • HEAD /self/password

these six device endpoints:

  • POST /clients
  • GET /clients
  • GET /clients/{cid}
  • PUT /clients/{cid}
  • GET /users/{uid}/clients
  • DELETE /clients/{cid}

and these MLS conversation endpoints:

  • POST /conversations
  • GET /conversations
  • GET /conversations/{cid}
  • GET /conversations/{domain}/{cid}
  • POST /conversations/list-ids
  • POST /conversations/list
  • GET /conversations/mls-self
  • GET /one2one-conversations/{domain}/{uid} (and /conversations/one2one/{domain}/{uid})
  • GET|PUT /conversations/{cid}/self
  • GET|PUT /conversations/{domain}/{cid}/self
  • GET /conversations/{cid}/roles
  • POST /conversations/{domain}/{cid}/typing

and these MLS key package endpoints:

  • POST /mls/key-packages/self/{cid}
  • POST /mls/key-packages/claim/{user}
  • POST /mls/key-packages/claim/{domain}/{uid}
  • GET /mls/key-packages/self/{cid}/count

and these MLS messaging endpoints (M6–M9):

  • POST /mls/commit-bundles
  • GET /conversations/{cid}/groupinfo
  • GET /conversations/{domain}/{cid}/groupinfo
  • POST /mls/messages

It also provides GET /healthz and GET /api-version, the notification and WebSocket routes, POST /mls/commit-bundles, POST /mls/messages, GET /mls/public-keys, and the M11 surface: /assets (upload, download, delete, token lifecycle) and the frontend-bootstrap stubs (/feature-configs, /system/settings(/unauthorized), /properties[/{key}], /list-connections, /calls/config(/v2), /teams[/{tid}[/…]], /users/{domain}/{uid}, /list-users, /users/list-clients, /users/list-prekeys, /search/contacts, the handle routes, /self/consent, /self/locale, /self/supported-protocols). Every route is reachable both unprefixed and under /v{N}/ for N in the supported range 0–8. M9 publishes the backend's removal key at GET /mls/public-keys, signs one External Remove Proposal per MLS conversation when a roster device is deleted through DELETE /clients/{cid}, and fans the proposal out as the existing conversation.mls-message-add event. M10 adds no endpoint and no migration; it freezes the end-to-end script, the golden corpora and the negative suite as rerunnable assets. Proteus/mixed conversations, channels/meetings, real teams, SSO, conferencing, federation, guest links and REST member changes remain out of scope. Key package PUT (replace) and DELETE are not implemented and return the uniform 405 error.

Frontend integration (M11)

M11 is scoped by the frontend's boot sequence, not by protocol completeness: every endpoint the webapp calls before it can render is a real route, stubs answer the exact shapes libraries/api-client expects, and nothing on that path answers 404/405.

  • Version contract. GET /api-version reports supported: [0,1,2,3,4,5,6,7,8], development: [], federation: false and the configured domain; a webapp with MAX_API_VERSION=8 therefore negotiates v8. Every route also accepts /v{N}/… for N in 0–8, stripping the prefix before matching (/v8/self ≡ /self, /v08/self too). A syntactically valid prefix outside the range answers the reference's 404 {"code":404,"label":"unsupported-version","message":"Version v<N> is not supported"} (the request's own segment), and a segment that is not a version (/v/self, /vx/self) is routed as it arrived. The prefix keeps method, headers, body and query string, so /v8/await upgrades and POST /v8/register behave like their unprefixed forms.
  • Bootstrap stubs. GET /feature-configs enables MLS only (supportedProtocols:["mls"], allowedCipherSuites:[1]) and keeps consumableNotifications disabled, which is what makes the webapp use /await + /notifications. /system/settings(/unauthorized), /list-connections, /calls/config(/v2), /teams and the /teams/{tid}/… family (404 no-team), /users/{domain}/{uid}, /list-users, /users/list-clients, /users/list-prekeys (always empty), /users/{domain}/{uid}/prekeys (404), /search/contacts (local handle/name/name-word prefix search, search_policy: "full_search"), the handle routes (POST /handles and POST /users/handles return free candidates; PUT /self/handle persists), /self/consent (GET empty, PUT validated and not persisted), /self/locale, /self/supported-protocols and GET /users/{domain}/{uid}/supported-protocols (always ["mls"]), and /conversations/{cid}/roles are real routes with the reference shapes; /properties persists per-user JSON (migration 0009). GET /notifications/last?client= and GET /notifications/{id} read one device's queue with gundeck's toNotifSingle filter (client_id IS NULL OR client_id = ?, so user-level rows are visible to every device of the user); every unavailable answer is the same 404 not-found (Some notifications not found) so device existence never leaks. GET /conversations/{cid}/self and PUT (mute/archive, accepted and not persisted) round out the conversation surface; POST /conversations/list-ids and POST /conversations/list are static segments registered ahead of /{cid}, which is what turned the reference 400 into a 200.
  • Device updates. PUT /clients/{cid} accepts the UpdateClient subset the webapp sends (unlike POST /clients, it writes no user.client-add notification, matching Brig where only addClient emits it): mls_public_keys (first write wins; the same value is idempotent, a different one is 400 mls-duplicate-public-key, and a multi-scheme request is atomic), capabilities (overwritten, [] included), prekeys/lastkey (validated, never stored — exactly like POST /clients), and label (absent/null leaves it unchanged). GET /clients/{cid} returns the full self Client. Both are scoped to the token user; unknown or foreign devices answer 404 client-not-found. This is the hard prerequisite for MLS initialisation.
  • Self and 1:1 conversations. GET /conversations/mls-self lazily creates exactly one type:1 conversation per user, with id = the user's own UUID (the reference's selfConv), a random 32-byte group_id, epoch:0, cipher_suite:1, access:["private"], access_role:[], and the user as the only wire_admin member. GET /one2one-conversations/{domain}/{uid} (alias /conversations/one2one/…) lazily creates a type:2 conversation whose id is the reference's deterministic one2OneConvId(BaseProtocolMLSTag, a, b) (SHA-256 over the fixed namespace and the two sorted (domain, uid) pairs, truncated to 16 bytes with version-5 bits), both users wire_member, and returns {"conversation":…,"public_keys":{"removal":{"ed25519":…}}} (public_keys is {} when REMOVAL_PRIVATE_KEY is unset). POST /one2one-conversations answers 400 mls-only. POST /mls/commit-bundles accepts the first commit of both kinds (0 → 1, Welcome and events fanned out to the other devices), and because their membership is fixed, an Add naming a user outside the conversation answers 403 action-denied (Insufficient authorization (missing add_conversation_member)).
  • Domain-qualified local routes. GET /conversations/{domain}/{cid} (and /self, /groupinfo) plus POST …/typing and POST /mls/key-packages/claim/{domain}/{uid} are the spellings the v8 frontend uses. This deployment only serves its own DOMAIN: a foreign conversation domain is 404 no-conversation, a foreign claim domain is 400 invalid-user. Typing is membership-checked, acknowledged with 200, and never fanned out.
  • Assets. POST /assets takes the reference's multipart/mixed pair (JSON metadata then application/octet-stream) and stores the bytes under ASSETS_DIR, answering 201 with {key,domain,token,expires?} and a relative Location. GET /assets/{key} (and /assets/{domain}/{key}) streams the bytes to a caller holding the Asset-Token header or asset_token query, or to anyone when the asset is public; DELETE /assets/{key} removes row and file; POST|DELETE /assets/{key}/token renews a token or makes the asset public. Keys are 3-<retention>-<uuid>; the path on disk is derived from the server's UUID only, never from the client's string. Uploads are bounded to 25 MiB of request body, metadata to 4 KiB, and malformed multipart input to 400/415.

Notification delivery (M8)

MLS events are generated, persisted, and broadcast in-process (M7); M8 delivers them:

  • GET /notifications?since=&client=&size= returns the authenticated user's backlog: since is an exclusive cursor over the time-ordered UUIDv7 id, size is the reference range 100–10000 with default 1000, client optionally narrows to one device's rows (user-level rows are always included via client_id IS NULL OR client_id = ?). A page is {notifications:[{id,payload:[event]}],has_more,time}; a since that names no row of this user answers 404 not-found (Some notifications not found), and a malformed cursor answers 400 bad-request (Invalid Notification ID).
  • GET /notifications/last?client= returns the newest row of that same filtered queue ({"id","payload":[…]}); missing client or an empty queue is the same 404 not-found. GET /notifications/{id}?client= returns one row by id with the same filter when client is present, or by user_id alone when it is omitted.
  • WebSocket /await?access_token= (or Authorization: Bearer) upgrades to a real-time stream after authentication. Frames are binary {id,transient,payload:[event]}. /await never replays: reconnecting clients resume through GET /notifications?since=, so delivery is at-least-once and de-duplication by id is the client's job. A client that falls behind the bounded in-process ring is closed with 1003 and resynchronises through the backlog; an idle connection gets a protocol ping after 20 s and is closed with 1002 after 20 s more without a pong; an application-level ping data frame gets a binary pong.
  • Both endpoints require a valid unexpired access token (a user token is rejected), and neither ever returns another user's rows: the token's user id is the only identity source, and a cursor into somebody else's queue reads as 404 rather than as an answer about that row.
  • Single-instance premise: since paging and frame ordering rely on notifications.id being totally ordered, which holds inside one process (the bus carries the same-millisecond carry). Multi-instance deployments are out of scope for this iteration.

M8 adds one migration, 0007_notifications_user_id_index, which creates notifications_user_id_idx ON notifications(user_id, id): without it the cursor query falls back to notifications_user_created_idx plus a temporary B-tree sort, so LIMIT cannot stop early. No column or table is added; the existing six notifications columns are sufficient for both the backlog and the WebSocket stream.

Requirements

  • Stable Rust and Cargo
  • Bun
  • No external database service or database credentials

SQLite is the only persistence backend. Both serve and the explicit migrate command open the configured SQLite file, but the server never applies migrations implicitly. /healthz reports process liveness only and does not claim database availability.

Configuration

Set environment variables in your shell. .env.example documents the required values but is not loaded automatically.

Variable Purpose
LISTEN_ADDR HTTP socket address, for example 127.0.0.1:3000
DOMAIN Public host name used in qualified IDs, /api-version, and MLS credential identities, without scheme or path
DATABASE_URL File-backed SQLite URL or filesystem path used by migrate and the HTTP server
ZAUTH_PRIVATE_KEY Padded Base64URL-encoded 64-byte libsodium Ed25519 secret key
REMOVAL_PRIVATE_KEY Optional key of the same format, used to sign MLS removal proposals
ASSETS_DIR Optional directory for uploaded assets; without it the /assets routes answer 500 internal-server-error

Examples of SQLite locations:

DATABASE_URL=sqlite://./wire-rs.db
DATABASE_URL=./wire-rs.db

Only file-backed databases are accepted; in-memory locations, URL query options, fragments, and non-SQLite schemes are rejected. The zauth key consists of a 32-byte Ed25519 seed followed by its corresponding 32-byte public key. Its canonical encoding is 88 characters, including == padding. YOUR_ZAUTH_PRIVATE_KEY_HERE is only a placeholder: inject a real key through the environment and never commit it. Configuration debug output and public errors redact database locations and key material.

ASSETS_DIR is optional and is the only place uploaded bytes are written: serve creates the directory (recursively) at startup and fails when it cannot, and a path that is empty, whitespace-only, contains a NUL, or names an existing file is a configuration error. Sub-directories are sharded by the first two hex digits of the asset's UUID, and every file name is a server-generated UUID, so no client-supplied string ever reaches the filesystem. Without ASSETS_DIR the process still starts and serves everything except the four asset routes, which answer 500 internal-server-error.

REMOVAL_PRIVATE_KEY is optional and follows exactly the same value rules as ZAUTH_PRIVATE_KEY: a padded Base64URL-encoded 64-byte libsodium Ed25519 secret key (32-byte seed plus its matching 32-byte public key, 88 characters including ==), validated by round-trip and by deriving the public half from the seed. A malformed value fails startup; an absent one does not — the process serves every other endpoint and only the removal-key route answers 400 mls-not-enabled. .env.example holds only the YOUR_REMOVAL_PRIVATE_KEY_HERE placeholder, and debug output prints removal_private_key: "<redacted>" whether or not it is set.

Commands

Run all commands from the repository root:

bun make.ts build    # cargo build
bun make.ts test     # default tests; real-file DB integration tests remain ignored
bun make.ts run      # start HTTP server without running migrations
bun make.ts migrate  # apply pending migrations to DATABASE_URL
bun make.ts test:db  # run all ignored SQLite integration tests on temporary files

Run migrate before starting a server against a new database. The command is idempotent and creates the configured file when needed. Its CLI error is deliberately generic and does not print the file location. migrate loads the same configuration as serve, so LISTEN_ADDR, DOMAIN, ZAUTH_PRIVATE_KEY and DATABASE_URL must all be set — REMOVAL_PRIVATE_KEY and ASSETS_DIR are the only optional variables.

Every pooled SQLite connection enables foreign keys and WAL, uses a bounded five-second busy timeout, and verifies those effective settings after connecting. Multi-step authentication and client writes use BEGIN IMMEDIATE on one acquired connection. SQL values are bound parameters.

Verification

M10 froze the protocol surface and M11 extended it; both are rerunnable assets. No external database, service or credential is needed: the database suites create and remove their own temporary SQLite files, every key is a public synthetic test key, and the asset suites create and remove their own ASSETS_DIR under the OS temp directory.

Command Expected What it proves
bun make.ts test 886 passed / 0 failed / 179 ignored (~29 s warm) Default suite: domain, HTTP via the real app(), golden JSON, golden MLS bytes, negative matrices, the M11 stubs/properties/asset HTTP surface and the version-prefix matrix
bun make.ts test:db 177 passed / 0 failed over 14 suites (~78 s) Real file-backed SQLite: migrations, auth, clients, conversations, commits, concurrency, events, key packages, messages, notifications, properties, removal, assets
cargo test --features openmls-interop --no-fail-fast 971 passed / 0 failed / 194 ignored (~35 s after build) Adds OpenMLS cross-checks: byte-for-byte re-serialisation of 13 real fixtures, real app over real SQLite, and the removal closed loop
bun make.ts build then cargo test --features openmls-interop --test mls_live_process_openmls -- --ignored --nocapture --test-threads=1 14 passed / 0 failed (~39 s) Real target/debug/wire-rs.exe process, real TCP, real SQLite and real OpenMLS: the full script, the unified negative suite, notification/WS behaviour, removal-key delivery, and M11's self and 1:1 conversations (first commit 0 → 1, Welcome fan-out, two-way messages, and the fixed-membership refusal). Run it three times; it leaves no process or file behind
cargo fmt --check exit 0 Formatting
cargo clean -p wire-rs then cargo clippy --all-targets -- -D warnings 0 warnings, prints Checking wire-rs v0.1.0 Lints, default feature set
the same with --features openmls-interop 0 warnings Lints, interop feature
TEST_DATABASE_URL=<temp db> then cargo test --test ws_http -- --ignored --test-threads=1 2 passed / 0 failed (41 filtered out) The two DB-backed WebSocket cases, which are not yet wired into test:db (see the limitations below)

What the suites pin down:

  • Golden JSON (tests/golden/json/**, tests/golden_json.rs): ten error bodies, four event envelopes, GET /mls/public-keys, a notifications page, the self-client list, a conversation and a claim bundle. Static bodies are byte-exact; dynamic bodies are normalised for UUIDs, timestamps and binary leaves and then compared byte-for-byte, with key order and key sets asserted separately. Every fixture has a recorded sha256, checked from disk, and a provenance entry (reference file/line and deliberate deviations) in tests/golden/PROVENANCE.md.
  • Golden MLS bytes (tests/golden/mls/**, tests/golden_mls_bytes.rs and tests/golden_mls_openmls.rs): thirteen real OpenMLS fixtures — KeyPackage, Welcome, Commit, two GroupInfos, a full CommitBundle, private and public messages, Add/Remove proposals and an External Remove Proposal's message/proposal/ref. This crate parses and re-serialises each to the same bytes, OpenMLS does the same on the other side, and tampering with a structural byte is rejected without a panic. Regeneration is an explicitly #[ignore]d generator because a KeyPackage contains a random init key: the fixtures are frozen snapshots, and regenerating them requires a reviewed manifest change.
  • The full script (live_process_the_full_m0_to_m9_script): register/login/access, devices with MLS keys, key package upload/claim, conversation creation, a real Welcome join, realtime and backlog application messages, a by-reference proposal and its commit, removal of a member, deletion of a roster device that makes the backend sign an External Remove Proposal, and that proposal committed to convergence — asserting HTTP responses, event recipients and SQLite rows at every step.
  • The M11 live cases (live_process_mls_self_conversation_takes_its_first_commit, live_process_one2one_conversation_takes_both_sides_devices): the server hands out the conversation's group_id, OpenMLS creates a group with exactly that id, the first commit is accepted at 0 → 1, the Welcome reaches only the intended devices, two-way application messages flow, the stored roster matches the ratchet tree, and adding a third user to a 1:1 conversation is refused with 403 action-denied and zero side effects.
  • The negative suite (live_process_the_unified_negative_suite): stale epochs, a forged proposal reference, a non-admin removal, self-removal, a removed member sending again, a partial-client removal, forged/expired/mistyped tokens, and unauthorised reads/deletions. Each case asserts status, label and message against the reference text plus a zero-side-effect snapshot. It also pins the documented deviation from M7: a proposal left unprocessed makes the next commit fail with mls-commit-missing-references (byte-identical to the golden body), and the same commit succeeds once the proposal is referenced.

Known limitations

The full per-milestone record lives in docs/milestones/M0.md–M11.md; the consolidated list is M10.md §6 plus M11.md §7. The points a first-time operator must know:

  • Single instance only. GET /notifications?since= paging, has_more and WebSocket frame order all rely on notifications.id being totally ordered inside one process. /await never replays; reconnection resumes through the backlog, and de-duplication by id is the client's job (at-least-once).
  • One cipher suite, one removal key. Ciphersuite 0x0001 (ed25519) only; GET /mls/public-keys publishes a single ed25519 key and clients must place it at ExternalSendersExtension[0]. There is no key rotation and no ?format=jwk.
  • Removal timing. Deleting a roster device removes it immediately, so the server roster is briefly one leaf short until the signed External Remove Proposal is committed; a backend-origin removal of a leaf that is already gone is a no-op. Without REMOVAL_PRIVATE_KEY such a deletion is refused with 400 mls-not-enabled and nothing is written. There is no leave-conversation route.
  • Deliberate two-transaction windows. State is committed before events are published and before per-conversation removal proposals are stored; a failure in that window returns 500 with the earlier write retained, and a device deletion that fails midway leaves the device deleted with the proposals already stored for earlier conversations.
  • Known protocol gaps. Commit signatures at epoch 0 cannot be verified (no group context yet), membership/confirmation tags are not checked, private messages are never decrypted, and GroupInfo/roster mismatch is diagnostic only.
  • Known test-side limits. The "one clock read" assertion is a black-box proxy (a clock read moved into the loop was caught 4 times in 12 runs); a negative epoch is only reachable through the fake repository; the MLS goldens are frozen snapshots; "send to a non-MLS conversation" cannot be constructed over HTTP because conversation creation only accepts mls; and the two DB-backed ws_http cases are not yet part of the test:db suite list, so they are run by the explicit command in the verification table.
  • M11 surface is deliberately minimal. consumableNotifications is disabled, teams are always empty (404 no-team), connections are always empty, calls have no ICE servers, and /users/list-prekeys is always empty. GET /search/contacts is a local prefix search over every other local user's handle, display name, and name-word prefixes (search_policy: "full_search"; empty q or a foreign domain yields an empty page). /properties and PUT /self/handle are the only stubs that persist anything; PUT /self/supported-protocols, PUT /self/consent, PUT /conversations/{cid}/self and PUT /self/locale are validated, answered 200, and otherwise ignored. GET /self and GET /users/{domain}/{uid}/supported-protocols always report ["mls"]. paging_state is always "" and has_more always false, because no list is paginated.
  • Self and 1:1 conversations carry documented deviations. Their group_id is random 32 bytes at lazy creation (the reference derives it deterministically), their access_role is [], and GET /conversations/{cid} with the caller's own UUID creates the self conversation on read (the reference's create-on-read), so that GET has a write side effect. The commit path classifies an unknown conversations.type as regular (the render path still answers 500), and the self/1:1 membership rule is enforced only for self/one2one rows.
  • Assets have no lifecycle management. Files are local, expires is stored but not enforced, there is no garbage collection (deleting a user drops the row but leaves the file), deleting a token makes the asset public rather than removing it, and re-issuing a token on an already-public asset returns a token that is inert until the asset becomes private again. Downloads are buffered up to the 25 MiB cap rather than streamed from disk.
  • Migration down-migrations cannot express everything. 0009 and 0010 are DROP TABLE downs, so their rows do not survive an undo/re-up cycle (other tables' rows do, and the DDL is restored byte for byte); and 0003_clients' down rejects a legacy database in which two users hold the same client id, which the pre-M2 global primary key cannot represent.
  • /v{N} is a prefix, not a separate API. A supported prefix is stripped before routing, so /conversations/list/self resolves {cid}=list and answers 400; only a syntactically valid out-of-range prefix is refused with unsupported-version.

HTTP authentication contract

Register and login

POST /register requires name, email, and password, and also accepts (type-checks and ignores) the v8 webapp fields email_code, locale, accent_id, label, and assets. Names are 1–128 Unicode characters, registration passwords are 8–1024 Unicode characters, and email addresses are validated, bounded, and normalized to lowercase. A successful response is 201 with the exact active SelfProfile, a Location containing the new UUID, and a zuid cookie. Accounts are active immediately — there is no email verification step — and registration does not return an access token.

POST /activate/send answers 200 with an empty body for a well-formed unused address, 409 key-exists when the email is already taken, and 400 invalid-email when it is malformed; no code is ever sent. POST /activate and GET /activate?code=&key= only answer the success shape {email?, first:false} (they never issue a cookie).

POST /login accepts exactly one identity (email or handle) plus password; login passwords are 6–1024 Unicode characters. Success is 200 with:

{
  "user": "<user-uuid>",
  "access_token": "<zauth-access-token>",
  "token_type": "Bearer",
  "expires_in": 900
}

Unknown identities and wrong passwords intentionally return the same 403 invalid-credentials error. persist=true adds an Expires attribute to the login cookie; other login cookies are session cookies. Passwords are stored only as randomly salted Argon2id PHC hashes using m=19456 KiB, t=2, p=1, with CPU-intensive work moved off Tokio worker threads.

Every issued zuid cookie has Path=/access; Secure; HttpOnly; SameSite=Lax and no Domain. Registration cookies include their token expiry. Access tokens expire exactly 900 seconds after issuance and use a fresh random zauth connection value.

Refresh an access token

POST /access requires a zuid request cookie. An old access token is optional and may be supplied as Authorization: Bearer <token> (preferred) or ?access_token=<token>.

The server verifies the user-token signature, canonical type, and current expiry, then requires the exact (user, session id, expiry) tuple to identify a live SQLite refresh session. A valid signature alone is not sufficient. If an old access token is supplied, its signature and access type must be valid and its user must match the cookie. As in Wire, an expired old access token does not block refresh; forgery, tampering, and wrong token types still fail.

Success is 200 with the four-field access-token response above.

POST /access?client_id=<cid> additionally binds an unbound refresh session to one of the cookie user's existing devices. The operation verifies device ownership and atomically persists (user, session, client), re-signs the same user-token session ID and expiry with i=<cid>, and returns an access token carrying the same i. The replacement zuid keeps the original persistent/session cookie type and all required security attributes. Subsequent refreshes inherit the binding; explicitly repeating the same ID is valid, attempting to change it fails, and the stale pre-binding cookie cannot be replayed. Malformed or duplicate client_id parameters return 400; unknown, foreign, or conflicting IDs return 403. A query may contain independent client_id and access_token parameters.

Logout

POST /access/logout requires both the zuid cookie and a matching access token. It validates the same live refresh session and deletes exactly that (user, session id) row. Success is 200 with an empty body and no Set-Cookie header. Repeated logout fails, and subsequent /access with that cookie returns 403.

Logout does not revoke stateless access tokens: an already issued access token can still call /self until its own expiry. An expired old access token is accepted for logout after signature/type/user validation, just as for refresh.

Get self

GET /self requires an access token through the Authorization header or access_token query parameter; a user cookie is not a substitute. The server checks the signature, access type, and current expiry, then looks up only the UUID contained in the token. Success returns the same exact SelfProfile shape as registration and never sets a cookie. A correctly signed token whose user no longer exists returns:

{"code":404,"label":"not-found","message":"User not found"}

Check password exists

HEAD /self/password requires the same access-token authentication as GET /self. It answers 200 with an empty body when the token user's password_hash is non-empty, and 404 with an empty body when the user is missing or the hash is empty. Every account created through POST /register stores a password (users.password_hash is NOT NULL), so a live user normally sees 200. GET and PUT on the same path are not implemented (uniform 405).

Device creation and listing

All self device routes require a valid, unexpired access token through Authorization: Bearer <token> (preferred) or access_token query. A zuid user cookie is not a substitute, and authentication runs before JSON body extraction. Client-bound access tokens are accepted normally.

POST /clients accepts the strict NewClient object. Required fields are prekeys, lastkey, and type; supported optional fields are label, class, cookie, password, model, capabilities, mls_public_keys, and verification_code. Non-null verification codes are not supported. Prekey JSON IDs, bounded standard-Base64 data, CBOR structure/depth, nested keys, and trailing bytes are validated, and lastkey.id must be 65535. The client ID is derived from the SHA-256 of the UTF-8 lastkey text, using the first eight bytes as a big-endian Word64. Proteus prekeys and lastkey are never stored or consumed in this MLS-only implementation; they are not written to key_packages or any prekey table. Passwords are used only for reauthentication.

Success is 201 with Location: <canonical-client-id> and a Self Client object. It always contains id, type, time, capabilities, and mls_public_keys; class, label, cookie, model, and last_active appear only when non-null. time is the database POSIX-millisecond creation value rendered as UTC YYYY-MM-DDTHH:MM:SS.sssZ. Capabilities are deduplicated and stably ordered, and MLS public keys use the four reference signature-scheme names with standard Base64 values. Responses never contain password, prekeys, or lastkey. In the same BEGIN IMMEDIATE transaction as the device row the server also writes a user-level user.client-add notification (client_id IS NULL, V6 clientSchema); the WebSocket /await push happens only after that transaction commits, so a brand-new device can then read the event through GET /notifications/last?client=<new>.

The first device of each type and a same-user/same-ID upsert do not require password reauthentication. A second new device of the same type returns 403 missing-auth until the correct password is supplied; a wrong password returns 403 invalid-credentials. Upsert returns 201 rather than 409, updates metadata/time without adding a row, and permits the same derived ID for different users. At most seven permanent devices are allowed (403 too-many-clients); a new temporary device replaces the user's previous temporary device and its client-bound refresh sessions. Public legal-hold creation is rejected with the reference 400 client-error.

GET /clients returns the token user's complete Self Client array. GET /users/{uid}/clients is deliberately unauthenticated and returns only id plus optional class for each device, including for other users; an unknown user returns []. Both list forms use numeric client-ID order, and the public form never exposes labels, models, cookies, capabilities, timestamps, or MLS keys.

Device deletion

DELETE /clients/{cid} accepts an object containing only optional/null password (6–1024 Unicode characters when present). The device is looked up by both token user and path ID. Unknown, foreign, and already deleted IDs uniformly return 404 client-not-found. Temporary devices may be deleted without a password; permanent devices require the same password reauthentication as creation; seeded legal-hold devices return the reference 400 client-error.

Success is 200 with an empty body. Device deletion and cascading removal of its client-bound refresh sessions occur in one immediate SQLite transaction. An old bound cookie therefore fails subsequent /access with 403, while other sessions and other users are unaffected. As with logout, already issued stateless access tokens remain valid until their own expiry.

Deleting a device that is on the MLS roster of one or more conversations also signs one External Remove Proposal per conversation, stores it as a pending proposal and fans it out to the remaining clients of that conversation as the existing conversation.mls-message-add event (no new event type, no new delivery path). The proposal is signed with REMOVAL_PRIVATE_KEY at the epoch and leaf index the conversation had when the request started, and its sender is external index 0, so clients that put the key from GET /mls/public-keys at ExternalSendersExtension[0] can verify it and commit it. The deleted device receives nothing, a device that is on no MLS roster is deleted exactly as before, and a device that is on a roster is not deleted when REMOVAL_PRIVATE_KEY is unset: the request answers the reference 400 mls-not-enabled and writes nothing, because this iteration has no log sink to record a skipped removal and its roster row would be gone without a proposal to explain it. There is no leave-conversation route in this iteration, so device deletion is the only trigger.

Conversation creation, detail, and listing

All three conversation routes require the same valid, unexpired access token as the device routes, supplied through Authorization: Bearer <token> or access_token query. A zuid user cookie is never a substitute, and authentication runs before JSON body extraction and before path/query business validation.

POST /conversations accepts the strict current NewConv object. Recognised fields are users, qualified_users, name, access, access_role, team, message_timer, receipt_mode, conversation_role, protocol, group_conv_type, cells, add_permission, skip_creator, parent, history, and optional group_id. Unknown and duplicate fields are rejected, and a body that is not a JSON object is rejected. protocol must spell out mls; an omitted, null, proteus, or mixed value is 400 bad-request. users and qualified_users must be empty because an MLS roster is only ever changed by commits: any entry returns the reference MLS error. name is null or 1–256 Unicode characters. access defaults to ["invite"] and access_role to ["team_member","non_team_member","service"]; both are deduplicated and stably ordered, and an explicit empty access_role renders as []. message_timer is a persisted nullable i64. receipt_mode is parsed strictly but ignored, and the response always reports 0. conversation_role defaults to wire_admin and applies only to requested other users, never to the creator. cells, skip_creator, group_conv_type, team, add_permission, parent, and history only accept their defaults.

group_id is optional. When omitted (the v8 frontend never sends one), the server mints 32 random bytes — the same length as self/1:1 — and returns them in the response. When supplied, it is standard Base64 (not Base64URL) of 1–1024 bytes, canonically padded: empty, non-canonical, URL-safe-alphabet, trailing-data, over-long, and explicit null values are rejected. The decoded (or minted) bytes are stored as a BLOB and re-rendered canonically in every response.

Success is 201 with Location: <new-conversation-uuid> and the current CreateGroupConversation shape: all Conversation fields flat, plus failed_to_add: []. The conversation UUID is minted server-side. The creator from the access token becomes the single wire_admin member, epoch is 0, and no group_clients row is written even when the creator already owns devices; the MLS roster is established by the first commit, not by REST creation.

GET /conversations/{cid} returns 200 with the current Conversation object (no failed_to_add, no deprecated top-level id). A malformed path UUID is 400 bad-request, an absent conversation is 404 no-conversation, and an existing conversation the caller does not belong to is 403 access-denied. GET /conversations/{domain}/{cid} is the same read for this deployment's DOMAIN; any other domain is 404 no-conversation. The qualified /self, /groupinfo, and POST …/typing routes follow the same local-only rule; typing acknowledges a member's JSON object with 200 and fans nothing out.

GET /conversations returns 200 with {"conversations":[...],"has_more":<bool>}. Each entry is an OwnConversation: the same fields plus the deprecated top-level id alias of qualified_id.id, and members.self rendered from the requesting user's own membership. Only the caller's own conversations are returned, in canonical UUID order; an empty page is exactly {"conversations":[],"has_more":false}. Query parameters are ids (1–32 comma-separated canonical UUIDs, mutually exclusive with start, always has_more: false), start (exclusive cursor), and size (1–500, default 32). Unknown or repeated parameters, empty or malformed values, ids combined with start, and out-of-range sizes are 400 bad-request. access_token is an authentication parameter rather than an unknown key, so it coexists with ids, start, and size; its duplicate or malformed values are still handled as authentication errors.

Shared metadata is rendered exactly as the reference current schema for an epoch-0 MLS group: qualified_id:{id,domain} (domain from DOMAIN), type: 0, unqualified creator, access, access_role, nullable name, last_event: "0.0", last_event_time: "1970-01-01T00:00:00.000Z", team: null, nullable message_timer, receipt_mode: 0, group_conv_type: "group_conversation", add_permission: null, cells_state: "disabled", parent: null, history: null, members: {self, others: []}, protocol: "mls", group_id, and epoch: 0. Because the epoch is 0, epoch_timestamp and cipher_suite are omitted; the fixed internal suite is never serialised. members.self contains qualified_id, the deprecated id alias, service: null, status: 0, status_ref: "0.0", status_time: "1970-01-01T00:00:00.000Z", otr_muted_status: null, otr_muted_ref: null, otr_archived: false, otr_archived_ref: null, hidden: false, hidden_ref: null, and conversation_role. Member objects never carry clients or leaf_index.

Minimal deviations from the reference server

  1. Upstream always mints the MLS group ID server-side. This project does the same when group_id is omitted (32 random bytes); a client may still supply one under the standard-Base64/BLOB contract above (older callers).
  2. Upstream has no static "duplicate client group_id" error. A repeated group_id — including across users and under concurrency — is this project's extension and uses the reference DuplicateEntry shape: 409 {"code":409,"label":"duplicate-entry","message":"Entry already exists"}. It is never reported as an MLS group/conversation mismatch, and every failure rolls back without leaking the existing conversation.
  3. Only cipher suite 0x0001 is supported and it is fixed internally; the request has no cipher_suite/ciphersuite field. Team, channel, meeting, history, and cells features are accepted only in their default form and are never silently persisted as if supported.

MLS key package upload, claim, and count

All key package routes require the same valid, unexpired access token as the device and conversation routes, through Authorization: Bearer <token> or access_token query. A zuid user cookie is never a substitute, and authentication runs before any path, query or body business validation.

POST /mls/key-packages/self/{cid} uploads a batch of MLS key packages for one of the token user's own devices. The body is the strict JSON object {"key_packages":["<standard Base64 of the TLS-serialised KeyPackage>", …]}. This route's body bound is 512 KiB of decompressed bytes (nginz's default_client_max_body_size for /mls/key-packages), not the service-wide 16 KiB. Unknown or duplicate fields, a body that is not an object, a non-string element, non-canonical or Base64URL text, missing padding, an element that is not exactly one parsable KeyPackage, more than 1000 elements, and an element above the decoded byte bound are all 400 bad-request with no detail about which check failed. A body above the route's 512 KiB limit is 413 payload-too-large (Request body too large); a missing or non-application/json Content-Type is 415 unsupported-media-type (Unsupported media type) — a charset parameter is fine. An empty array is legal and is a 201 no-op. This route has no ciphersuite parameter: the suite is taken from each key package itself.

Every element is validated before anything is stored, mirroring the reference traverse-then-insert, so a batch with one rejected element stores nothing at all. The checks run in the reference order and priority: ciphersuite (only 0x0001), KeyPackage signature, protocol version (1, i.e. MLS 1.0), LeafNode signature, BasicCredential identity, leaf source, capabilities, lifetime, and finally the registered signature key. The credential identity must be exactly {user uuid}:{client id}@{DOMAIN} of the uploading device, the leaf source must be key_package, the capabilities must include the basic credential type, and the lifetime must satisfy not_before <= now < not_after at the server clock. The last check compares leafNode.signatureKey byte for byte with the MLS ed25519 key that device registered through POST /clients as mls_public_keys.ed25519: a device that registered none is rejected with No key associated to the given identity and signature scheme, and a differing key with Unrecognised signature key. Success is 201 with an empty body. The batch is written in one immediate SQLite transaction, and re-uploading the same package replaces its row rather than adding one.

A stored row is (user_id, client_id, key_package_ref, data, ciphersuite), where data holds the uploaded raw MLS bytes verbatim — never a re-serialisation, so a later claim returns byte-identical data — and key_package_ref is the SHA-256 of the SignContent labelled MLS 1.0 KeyPackage Reference over those bytes. The composite foreign key to clients means deleting a device cascades to its key packages. There are deliberately no lifetime columns: expiry is decided at claim and count time by decoding data, exactly as the reference does, so M4 added no migration.

POST /mls/key-packages/claim/{user} takes no request body; any body is ignored. It consumes one usable key package per device of the target user inside a single immediate transaction, so concurrent claims can never hand out the same package twice, and returns 200 with {"key_packages":[{"user":{"id":"<uuid>","domain":"<domain>"},"client":"<hex>","key_package_ref":"<Base64>","key_package":"<Base64>"}, …]}. There is at most one entry per device, ordered by numeric client id, and a device picks its smallest reference. Exhaustion is not an error: a target with no usable package returns {"key_packages":[]} with 200, and a device without a usable package is simply omitted from the bundle. An unknown target user is 400 invalid-user, never 404, and a malformed user or client path segment is 400 bad-request. When the claimer claims its own user id and its access token carries the i client claim, that device is skipped entirely — neither consumed nor cleaned up; an unbound token skips nothing. Expired rows the claim passes are deleted, matching the reference cleanup, while rows whose data does not decode are left untouched.

POST /mls/key-packages/claim/{domain}/{uid} is the qualified spelling the v8 frontend uses. On this deployment's DOMAIN it behaves like the unqualified claim, with an optional skip_own=<client id> query that names the claimer's own device to leave out of a self claim (ignored for other targets). A foreign domain is 400 invalid-user, the same answer as an unknown local user.

GET /mls/key-packages/self/{cid}/count returns 200 with {"count":N}: the number of usable, not yet claimed packages of that device of the token user. A device that belongs to somebody else, or that does not exist, counts 0 without an error and without leaking anything. The count is read-only: it excludes expired packages but never deletes them.

Claim and count both accept an optional ciphersuite query parameter in the reference hexadecimal form: an optional 0x prefix, case-insensitive, at most four digits. 0x0001, 0X0001, 0x1, 1 and 0001 all name the one supported suite, and an absent parameter defaults to it. Any other parsable value is 400 mls-protocol-error with the message Unknown ciphersuite; unparsable hex, an empty value, an over-long value, a repeated ciphersuite, and any other unknown query parameter are 400 bad-request. access_token is the M1 authentication parameter, so it coexists with ciphersuite.

Key package deviations from the reference server

  1. Both /mls/key-packages/claim/{user} and /mls/key-packages/claim/{domain}/{uid} are registered; the qualified form rejects any domain other than this deployment's with 400 invalid-user. Bundle entries still render the qualified user object with DOMAIN.
  2. ciphersuite follows the reference V7 shape — optional, defaulting to 0x0001 — instead of the V8+ required parameter, and only 0x0001 is ever accepted.
  3. A claim selects the smallest key_package_ref deterministically, where the reference picks a usable package at random. The consumption semantics are identical.
  4. count is a read-only GET that skips expired rows without deleting them; the physical cleanup happens in the claim transaction, so both report the same number.
  5. There is no keyPackageMaximumLifetime setting: usability is exactly not_before <= now < not_after, which is the reference default.
  6. Only local users can be claimed — no federation or remote claim, no legalhold interception, and no account-status branches, because every user here is active. 409 decoding-error and 409 invalid-reference, which the reference raises only for remote bundles, cannot occur.
  7. Credentials are basic only; an x509 credential is rejected. The upload array and element bounds are this project's input-safety addition.
  8. Key package PUT (replace) and DELETE are not implemented and answer with the uniform 405 error.

MLS removal public keys

GET /mls/public-keys publishes the backend's removal key so clients can verify External Remove Proposals. It requires the same valid, unexpired access token as every other MLS route (Authorization: Bearer <token> or access_token query), but no client id: an access token without the i claim is accepted, because the reference route carries ZLocalUser and no ZClient. Success is 200 application/json with a single object, not an array, whose field names are the signature-scheme names:

{"removal":{"ed25519":"<standard Base64 of the 32-byte public key>"}}

Values are standard padded Base64 (44 characters for a 32-byte key), not Base64URL, matching the reference MLSPublicKey. Only ed25519 is published: cipher suite 0x0001 is the only one implemented and the server holds exactly one removal key, so the reference's three ECDSA scheme fields are omitted rather than fabricated. The reference's ?format=jwk is not implemented — the response is always the raw form and unknown query parameters are ignored. When REMOVAL_PRIVATE_KEY is unset the route answers the reference 400 {"code":400,"label":"mls-not-enabled","message":"MLS is not configured on this backend. See docs.wire.com for instructions on how to enable it"}. The body contains only the public key and the error text contains no configuration detail. POST, PUT, and DELETE on this path return the uniform 405 method-not-allowed, and /mls/public-keys/extra returns the uniform 404 not-found.

Errors and input limits

API errors use exactly {code,label,message}. Authentication failures use 403 invalid-credentials, including the reference messages Invalid zauth token, Zauth token falsified, Zauth token expired, Missing cookie, Missing token, and Missing cookie and token. Device errors include missing-auth, too-many-clients, client-not-found, invalid-user, mls-duplicate-public-key, and the reference legal-hold client-error; malformed prekeys use 400 bad-request with Malformed prekeys uploaded. Conversation errors are 404 no-conversation (Conversation not found), 403 access-denied (Conversation access denied), 400 non-empty-member-list (Attempting to add group members outside MLS), 409 duplicate-entry (Entry already exists), the existing 400 invalid-user for a token user that no longer exists, 400 bad-request for every malformed request/path/query, and 500 internal-server-error for storage failures. Key package errors are 400 mls-protocol-error — the one label whose message is dynamic, carrying the concrete public validation text such as Invalid KeyPackage signature, Unsupported ciphersuite 0x2, Unsupported protocol version, Client identity does not match credential identity, Expected 'key_package' source, got 'update', Missing BasicCredential capability, Key package is expired, Key package not_before date is in the future, No key associated to the given identity and signature scheme, Unrecognised signature key, and Unknown ciphersuite — plus the static 400 mls-invalid-leaf-node-signature (Invalid leaf node signature in key package), the existing 400 invalid-user for an unknown claim target, 400 bad-request for every decode, path and query fault, and 500 internal-server-error for storage failures. The removal-key routes answer 400 mls-not-enabled (MLS is not configured on this backend. See docs.wire.com for instructions on how to enable it) when REMOVAL_PRIVATE_KEY is unset: GET /mls/public-keys has no key to publish, and DELETE /clients/{cid} refuses to delete a device it is on the MLS roster of. M11 adds its own labels, all with the reference's text where the reference has one: 404 unsupported-version (Version v<N> is not supported) for a syntactically valid but out-of-range prefix; 400 mls-duplicate-public-key (MLS public key for the given signature scheme already exists) when a device change would replace an MLS key; 403 action-denied (Insufficient authorization (missing add_conversation_member)) for an Add outside a self/1:1 conversation's fixed membership; 400 mls-only (Proteus is not supported) for POST /one2one-conversations; 404 not-found with Property not found, Some notifications not found, Handle not found, User not found and Not found for the stub read paths; 404 no-team (Team not found) for every team route; 400 invalid-handle and 409 handle-exists for PUT /self/handle; 403 property-value-too-large and 403 property-key-too-large for the property bounds; and, for assets, 413 asset-too-large (Asset too large), 404 asset-not-found (Asset not found) and 403 unauthorised (Unauthorised). JSON bodies extracted by StrictJson name two further labels, distinct from the asset ones: 413 payload-too-large (Request body too large) when the decompressed body exceeds the route's DefaultBodyLimit, and 415 unsupported-media-type (Unsupported media type) when Content-Type is missing or not application/json (parameters such as charset=UTF-8 are accepted). The Bearer scheme is case-sensitive and must be exactly Bearer . Unknown routes, wrong methods on known routes, and other JSON extraction failures also return uniform JSON errors. Internal database, SQL, path, key, password, hash, and token details are never included in public errors; the dynamic MLS messages are reference-defined public texts and carry no server state.

JSON request bodies are limited to 16 KiB of decompressed bytes (gzip is decoded before the limit is applied). Documented exceptions: PUT /properties/{key} accepts up to 64 KiB of arbitrary JSON (handler-enforced; oversize is 403 property-value-too-large, not 413); POST /assets accepts up to 25 MiB of multipart/mixed (oversize is 413 asset-too-large; wrong multipart Content-Type is a separate 415), whose parts are bounded again by the parser (4 KiB of metadata and one application/octet-stream part); and POST /mls/key-packages/self/{cid} accepts up to 512 KiB (nginz default_client_max_body_size), answering 413 payload-too-large when exceeded. On every StrictJson route, a missing or non-application/json Content-Type is 415 unsupported-media-type, and every other JSON refusal stays 400 bad-request. Key package uploads are additionally bounded to 1000 array elements and to a fixed decoded size per element, and MLS binary parsing is bounded throughout: non-minimal VarInt encodings, oversized length prefixes, declared lengths that do not match the consumed bytes, trailing data, and elements that advance zero bytes are all rejected without allocation or panic. Tokens, Cookie/Authorization headers, query strings, and candidate cookie counts are bounded; duplicate cookies are tried in order so a later valid zuid can succeed without unbounded parsing or panics.

Database integration tests

test:db requires no external setup and does not read credentials. It creates a fresh temporary directory, pre-creates a separate real SQLite file for the migration and authentication suites, injects each path as TEST_DATABASE_URL, and runs the suites serially with ignored tests enabled. The owning invocation removes the directory and SQLite sidecar files.

The migration tests apply the embedded migrations twice, check all twelve tables plus constraints and indexes (including M8's 0007 (user_id, id) cursor index, M9's reversible 0008 proposals.origin column, M11's 0009 properties table and 0010 assets table, each checked for its columns, constraints, NULL semantics on pre-migration rows and a working undo/re-apply round trip), exercise foreign keys and checks, verify legacy-data copying and cross-user duplicate-ID protection, roll back to version zero, and apply the migrations again. Authentication tests cover repository queries, exact expiry, revocation, conflicts, rollback, malicious values as bound data, connection behavior, client binding races, and immediate write locking. Client tests cover composite identity, metadata/MLS keys, upsert/reauthentication, temporary replacement, user-scoped cascading deletion, and prekey non-persistence. Conversation tests cover the exact persisted row (BLOB group_id, ciphersuite=1, epoch=0, access metadata), the always-empty group_clients roster regardless of device count, group_id binary round-trips, unknown-creator rollback, duplicate and concurrent group_id conflicts, member isolation, list ordering/paging/isolation, hostile text as bound data, and the reversible 0004 metadata columns. Key package tests cover the exact stored rows (identifiers, key_package_ref BLOB, data BLOB, ciphersuite=1), batch atomicity and reference-idempotent re-upload, the read-only and scoped count, claim consumption in deterministic reference order, own-client skipping, user and client isolation, expired-row cleanup versus retained undecodable rows, suite filtering, eight-way concurrent claims consuming every package exactly once, immediate-write-lock behaviour with no partial batch or partial bundle, cascading device deletion, the unchanged table constraints, hostile blobs as bound parameters, and the trait-object contract. Real SQLite HTTP tests exercise both register → login → access → self → logout and register/login → client creation/reauthentication → self/public lists → client binding → deletion → bound-cookie rejection, plus register/login → optional client creation → MLS conversation creation → detail → listing and their non-member/not-found/duplicate/concurrent negatives, and register/login → device with a registered MLS ed25519 key → real signed key package upload → count → claim → exhaustion → cross-user isolation with their validation, authentication, ciphersuite, routing negatives and cascading deletion, including direct row/session checks and isolation of other sessions and users. Default bun make.ts test leaves these file-backed tests ignored and does not claim that they ran. The M11 suites cover the properties table over a real file (byte-exact JSON round trips, both size bounds, cross-pool reads, cascade and json_valid), the asset table over a real file and a real ASSETS_DIR (row and file across a restart, token renewal and public switching, owner-only deletion, cascade), the self and 1:1 conversations over a real file (deterministic ids incl. an independently recomputed fixed vector, eight-way concurrent lazy creation yielding exactly one row, list-ids inclusion, refusals), the four domain-level fixed-membership cases, and the asset and properties migrations' undo/re-up rounds. The removal suite (removal_db) covers a real DELETE /clients/{cid} against two MLS conversations plus a non-MLS one: one proposals row per MLS conversation (epoch, origin = 'backend', recomputed proposal_ref, bare Remove bytes), one notifications row per remaining client and none for the deleted device or a non-member, cross-conversation isolation, payloads that parse back as an External(0) Remove and verify under the configured key, a replayed deletion that is 404 and writes nothing, and self-consistent foreign keys.

Schema

The reversible migrations create twelve tables: users, clients, client_mls_public_keys, key_packages, conversations, members, group_clients, proposals, notifications, auth_sessions, properties, and assets. Clients have (user_id,id) identity (with the reverse unique pair required by existing foreign keys), client-owned refresh sessions use composite foreign keys, and MLS public keys are binary rows rather than key packages. key_packages stores the MLS key packages of M4 with the primary key (user_id,client_id,key_package_ref), a data BLOB holding the uploaded raw MLS bytes, a ciphersuite INTEGER checked to the Word16 range, and a composite foreign key to clients(user_id,id) with ON DELETE CASCADE; it is unrelated to Proteus prekeys, which this project never stores. It carries no lifetime columns, because expiry is derived from data at claim and count time as in the reference, which is why M4 needed no new migration. Conversations store the canonical UUID as TEXT, the MLS group_id (client-supplied or server-minted) as a UNIQUE BLOB, the fixed ciphersuite and initial epoch as INTEGER, and access, access_role, and nullable message_timer metadata as json_valid-checked TEXT. M11 reuses the conversations.type TEXT column for the new kinds: regular, self and one2one, rendered as the reference's 0/1/2; the self conversation's id is the user's own UUID and the 1:1 id is the reference's deterministic hash, so both are primary-key unique without a new constraint. The schema includes primary/foreign keys, uniqueness, nonnegative epoch/leaf/session checks, and query indexes — including notifications_user_created_idx (user_id, created, id) and M8's notifications_user_id_idx (user_id, id), which is what GET /notifications?since= pages through. M9's 0008 adds one nullable proposals.origin TEXT column, checked to client or backend, so the commit path can tell a backend-issued removal proposal from a client one; pre-M9 rows stay NULL, and the down migration drops the column again. M10 adds no migration. M11's 0009 adds properties(user_id, key, value, updated) with json_valid-checked TEXT values, a primary key on (user_id, key) and a cascade to users; its 0010 adds assets(id, user_id, key, token, public, retention, size, content_type, created, expires) with a UNIQUE key, public IN (0,1), retention BETWEEN 1 AND 5 and a cascade to users. Both downs are DROP TABLE, so the schema is at version 10 with twelve tables and an undo/re-up restores the DDL byte for byte while the dropped tables start empty. UUIDs use canonical TEXT, binary values use BLOB, POSIX timestamps and booleans use INTEGER, and notification payloads use TEXT. Down migrations preserve representable data and reject cross-user duplicate IDs that the legacy global-ID schema cannot express.

CI runs formatting, Clippy with warnings denied, build, default tests, temporary-file database tests, and cargo audit.