SPB Git

Repository Public

MSP-1.md 10.3 KB 183 lines markdown

1<!--2MacLustr Storage Node3File: docs/MSP-1.md4Author: Simon-Pierre Boucher5Contact: contact@spboucher.ai6-->7# MacLustr Storage Protocol — MSP/189Application protocol between a mobile storage node (the iOS app) and the storage coordinator. JSON over HTTPS for control,10raw bytes for fragments. Every connection is opened by the device: nothing listens on the iPhone, so it works behind NAT,11cellular carriers and firewalls.1213Reference implementations: `server/src/msp.ts` (coordinator), `MacLustrStorageNode/Core/Networking/MSPClient.swift` and14`Core/Synchronization/NodeEngine.swift` (device), `server/test/device.ts` (scripted test device).1516## 1. Transports1718| Path | URL | TLS trust | When |19|---|---|---|---|20| Gateway | `https://storage.spboucher.ai` (MacLustr Tunnel: Caddy on BHS64 → WireGuard → coordinator) | system trust (public certificate) | always available; the only path used in the background |21| Local network | `https://<coordinator-ip>:8871`, found with Bonjour `_maclustr-msp._tcp` | self-signed certificate, accepted **only** if its SHA-256 equals the pin the device received through the gateway (`lan.pin_sha256`) | app in the foreground, device on the coordinator's network, option enabled |2223A Bonjour announcement is never trusted by itself: the device calls `GET /msp/1/hello` on the announced address and the TLS24handshake fails unless the certificate matches the pin. The admin API is not served on the local listener.2526Time is Unix seconds. Sizes are bytes. Errors: HTTP status + `{"error": "<code>"}`.2728## 2. Identity and request signature2930At pairing the device generates a P-256 key pair (Secure Enclave when the hardware has one; the private key cannot be31exported) and registers the public key (uncompressed X9.63, 65 bytes, base64).3233Every control request is a `POST /msp/1/<route>` with a JSON body and four headers:3435```36MSP-Device:    <device id>          ("pair" for the pairing request)37MSP-Timestamp: <unix seconds>38MSP-Nonce:     <16–64 url-safe characters, never reused>39MSP-Signature: base64( ECDSA-P256-SHA256, DER ) over the canonical request40```4142Canonical request (UTF-8, `\n` separators):4344```45MSP146POST47/msp/1/<route>            (path and query exactly as sent)48<MSP-Timestamp>49<MSP-Nonce>50<hex SHA-256 of the body>51```5253The coordinator refuses a request when: the device is unknown (`401 unknown_device`), the timestamp is more than 300 s off54(`401 clock_skew` — the device then reads `server_time` from `/hello` and retries once with an offset), the signature does55not verify (`401 bad_signature`), the nonce was already seen for this device (`401 replayed_request`; nonces are kept56600 s), the device is revoked or removed (`403 device_revoked` / `403 device_removed`). There is no bearer token and no57session: nothing replayable is ever transmitted.5859## 3. Routes6061### `GET /msp/1/hello` (no authentication)6263`{ protocol: "MSP/1", version, host, heartbeat_seconds, fragment_size, lan: { service, port, pin_sha256 } | null, server_time, via: "gateway" | "lan" }`6465### `POST /msp/1/pair`6667Body `{ code, public_key, name, model, os_version, app_version }`, signed with the key being registered (proof of possession).68The code comes from the dashboard: 12 characters (alphabet without I, L, O, U, 0, 1), valid 10 minutes by default, single69use, revocable; only its SHA-256 is stored. Case, spaces and dashes are ignored. QR payload: `msp1://pair?h=<host>&c=<code>`70(the app only accepts hosts of the MacLustr domain). 10 attempts per address per 10 minutes.7172Response `{ device_id, …hello fields }`. `403 invalid_pairing_code` for unknown, used, revoked or expired codes.7374### `POST /msp/1/heartbeat`7576Sent every `heartbeat_seconds` (30) while the app runs, and whenever iOS grants background time.7778```jsonc79{80  "state": "active" | "suspended", "mode": "active" | "station" | "background",81  "accepting": true, "reason": "",          // why not, when false: wifi_only, charging_only, thermal, low_battery, low_power_mode,82                                            // low_data_mode, low_space, quota_full, no_quota, suspended, offline83  "capacity": { "total", "free", "reserve", "quota", "used", "fragments", "writable" },   // measured on the device84  "device": { "name", "model", "os_version", "app_version" },85  "power": { "battery": 0.82 | null, "charging": true, "low_power": false },86  "thermal": "nominal" | "fair" | "serious" | "critical", "network": "wifi" | "cellular" | "wired" | "none",87  "policy": { "wifi_only", "charging_only", "cellular", "rate_limit_bps" },88  "rates": { "rx_bps", "tx_bps" }, "local": { "verify_ok", "verify_fail", "errors", "last_scrub" },89  "bench": { … }                            // optional: last on-device benchmark, sent once90}91```9293`capacity.quota` is the inventory/allocation message: the coordinator never allocates more than the quota, and never more94than `writable` at a time. Lowering the quota under what is stored makes the coordinator release fragments (delete tasks).9596Response `{ server_time, status, pending_tasks, expected: { fragments, bytes }, drain: {…} | null, …hello fields }`.97`status` is the coordinator's view: `active`, `suspended`, `draining`, `drained`. When `expected.fragments` differs from98what the device holds, the device sends its inventory.99100### `POST /msp/1/work`101102Body `{ max, wait, active: [task ids still in transfer] }`. Long poll: answers at once when work exists, otherwise holds103the request up to `wait` seconds (≤ 25) and answers as soon as work appears. `active` extends the leases of running transfers.104105Response `{ tasks: [ { task, op, fragment, size, reason, ticket?, ticket_expires?, nonce? } ], status }`.106107There are exactly four operations. The device executes nothing else, whatever the coordinator sends.108109| `op` | Device does | Completes with |110|---|---|---|111| `store` | downloads the fragment (`ticket`), checks size and SHA-256 = `fragment`, commits it atomically | `ack` with `proof` |112| `verify` | re-hashes the fragment it holds | `ack` with `proof`, or `ok:false, error: missing | corrupt` |113| `retrieve` | re-hashes, then uploads the fragment (`ticket`) | the upload itself (the coordinator checks the digest) |114| `delete` | deletes the fragment | `ack` |115116A task is leased for 15 minutes; an expired lease returns to the queue; after 8 leases it is abandoned. Store tasks are117only leased to a node that reported `accepting: true`; the three others are always served.118119### `POST /msp/1/ack`120121Body `{ results: [ { task, ok, proof?, error? } ] }`. **Proof of possession**: `hex SHA-256( nonce ‖ fragment bytes )` with122the task's `nonce` — it cannot be computed without reading the whole fragment, and cannot be replayed because the nonce is123new for each task. The coordinator computes the same value from its stable copy. A wrong proof counts as an integrity124failure: the placement is dropped, the device is told to delete, and the fragment is placed again.125126### Fragment transfers127128Authenticated by a **ticket** in the URL instead of a signature, because iOS may run a background transfer hours after the129request was created: `…/msp/1/fragments/<fragment id>?d=<device>&t=<task>&k=<ticket>`. A ticket is130`<expiry>.<HMAC-SHA256(ticket key, device|op|fragment|task|expiry)>`, valid 24 h, bound to one device, one task, one131fragment and one direction, and dead as soon as the task closes or the device is revoked. What it gives access to is one132opaque encrypted fragment.133134- **Download** `GET` — `200` whole fragment, or `206` with `Range: bytes=N-` (resume). `ETag` is the fragment id.135- **Upload** `PUT` — whole fragment, or the rest of an interrupted upload with `Content-Range: bytes N-M/TOTAL`.136  `HEAD …&op=retrieve` returns `MSP-Offset: <bytes already received>`. `202` while incomplete, `200137  { complete, verified, restored_stable_copy }` when the digest matches, `422 digest_mismatch` otherwise,138  `409` + `MSP-Offset` when the offset is wrong, `410 task_closed` when the fragment is no longer wanted.139140The device's `rate_limit_bps` is applied by the coordinator on both directions.141142### `POST /msp/1/inventory`143144Body `{ fragments: [ids held] }`. Response `{ delete: [ids the cluster does not expect here], missing: <count of expected145fragments that are absent> }`. The device deletes the first list (orphans); the coordinator forgets the placements of the146second and replicates again. Sent after pairing, at launch when the counts differ, after a local corruption, and daily.147148### `POST /msp/1/drain`149150| Body | Effect |151|---|---|152| `{ mode: "graceful", remove: false }` | status `draining`: no new fragment; each fragment is deleted from the device only after its stable copy is confirmed (pulled back with `retrieve` first if it is missing); ends `drained`, or removed when `remove` |153| `{ mode: "emergency", remove }` | the device already erased everything: placements are dropped at once, redundancy is rebuilt elsewhere |154| `{ cancel: true }` / `{ rejoin: true }` | back to `active` from `draining` / `drained` |155156### `POST /msp/1/rekey`157158Body `{ new_public_key, new_key_signature }`, where `new_key_signature` is the new key's signature over159`MSP1-REKEY\n<device id>\n<new_public_key>`; the request itself is signed by the current key. The old key stops working160at once. The app rotates its key every 30 days and on demand.161162## 4. Lifecycle163164```165pair ──► active ──► draining ──► drained ──► (rejoin) active166            │            └──────────────────► removed167            ├── suspended (by the cluster)  ◄──► active168            ├── emergency release ──► drained | removed169            └── revoked (by the cluster): every request and ticket refused170```171172A device that receives `device_revoked`, `device_removed` or `unknown_device` erases its fragments and its key and returns173to the pairing screen.174175## 5. What the protocol guarantees176177- The coordinator cannot make a device do anything but store, prove, return or delete an opaque fragment.178- A fragment is accepted by either side only if its SHA-256 equals its id.179- A captured request cannot be replayed (nonce + timestamp); a captured ticket only yields one ciphertext fragment.180- The device never receives a key able to decrypt what it stores.181- Redundancy on mobile nodes is in addition to the stable copy: the scheduler only places fragments whose stable copy is182  healthy, and a drain never deletes a fragment whose stable copy is not confirmed.183
Files main
Menu

Theme