SPB Git

Repository Public

SPV1.md 14.6 KB 202 lines markdown

1# SPV1 — SP Vault cryptographic protocol, version 123Status: implemented, **not independently audited**. Normative for `packages/protocol` (TypeScript, WebCrypto)4and `apple/SharedVaultKit` (Swift, CryptoKit). Both implementations must pass `packages/crypto-test-vectors/spv1.json`.56## 1. Primitives (suite 1)78| Purpose | Primitive | Implementation |9|---|---|---|10| Content encryption | AES-256-GCM, 96-bit random nonce, 128-bit tag | WebCrypto / CryptoKit |11| Key derivation | HKDF-SHA256 (RFC 5869) | WebCrypto / CryptoKit |12| Public-key encryption | HPKE base mode (RFC 9180): DHKEM(P-256, HKDF-SHA256) `0x0010`, HKDF-SHA256 `0x0001`, AES-256-GCM `0x0002` | `@hpke/core` over WebCrypto / CryptoKit `HPKE` |13| Signatures | ECDSA P-256 with SHA-256, signature = raw `r‖s` (64 bytes) | WebCrypto / CryptoKit |14| Hash, MAC | SHA-256, HMAC-SHA256 | WebCrypto / CryptoKit |15| Randomness | `crypto.getRandomValues` / `SystemRandomNumberGenerator` | OS CSPRNG |1617P-256 is chosen because it is the only curve the Apple Secure Enclave supports; it lets device private keys be18hardware-bound on Apple devices and non-extractable `CryptoKey`s in browsers, with one algorithm suite everywhere.19No password-derived key exists in SPV1 (no master password), therefore no Argon2id dependency: every secret that20protects data is a 256-bit random value. No primitive is implemented in this repository.2122Encodings: binary values are **base64url without padding** in JSON. Public keys are X9.63 uncompressed points23(65 bytes). Private keys, when serialized (account keyset only), are X9.63 private representations24(`04‖X‖Y‖D`, 97 bytes). Identifiers are lowercase UUIDv4 strings.2526### 1.1 Domain-separated context strings2728`ctx(label, f1, …, fn)` = UTF-8 `"SPV1"` ‖ for each of `label, f1…fn`: 2-byte big-endian length ‖ UTF-8 bytes.29Every AEAD associated data, HKDF info, HPKE info and signed message in SPV1 is a `ctx(...)` value, so no two30uses can collide and every ciphertext is bound to where it belongs. Integers are written in decimal ASCII;31binary fields are written as base64url text.3233## 2. Key hierarchy3435```36Recovery Key RK (256-bit, shown once, never leaves clients)37   └─ HKDF → recovery wrap key ──────────────┐38Device enc key (P-256, Secure Enclave /       │ AES-GCM39non-extractable WebCrypto), one per device    ▼40   └─ HPKE ──────────────────────────▶ Account Root Key ARK (256-bit random)41                                          └─ HKDF("keyset") → AES-GCM → Account keyset42                                                 ├─ account signing key  (ECDSA P-256)43                                                 └─ account encryption key (P-256 KEM)44                                                        └─ HPKE ▶ Vault Key VK[vault, epoch] (256-bit random)45                                                                     └─ HKDF(salt per record revision) → record key46                                                                            └─ AES-GCM → record plaintext47                                                                                   └─ (inside) attachment file keys48```4950* **ARK** — generated on the first device. Never stored unwrapped; held in memory only while unlocked.51* **Account keyset** — `{sig, enc}` private keys, JSON, encrypted with52  `K = HKDF(ikm=ARK, salt=∅, info=ctx("keyset-key", account_id))`, AAD `ctx("keyset", account_id)`.53  The server stores the ciphertext and the two public keys.54* **Device keys** — each device generates `dev_enc` (key agreement) and `dev_sig` (ECDSA). On Apple hardware55  with a Secure Enclave both are Secure Enclave keys gated by user presence; elsewhere they are56  non-extractable WebCrypto keys (web) or Keychain-stored software keys (reported as "software" in the device list).57  Private device keys are never exported, copied or synchronized.58* **Device certificate** — `sig_account(ctx("device-cert", account_id, device_id, dev_enc_pub, dev_sig_pub, created_at))`.59  A device without a valid certificate under the account signing key is ignored by every client, so the server60  cannot add a device.61* **ARK envelope (per device)** — `HPKE.Seal(pk=dev_enc_pub, info=ctx("ark-wrap", account_id, device_id), aad=∅, pt=ARK)`,62  serialized `enc(65) ‖ ct`.63* **Recovery envelope** — `wrap = HKDF(ikm=RK, salt=∅, info=ctx("recovery-wrap", account_id))`;64  `AES-GCM(wrap, nonce, ARK, aad=ctx("recovery", account_id, recovery_epoch))`, serialized `nonce(12) ‖ ct`.65  `auth = HKDF(ikm=RK, salt=∅, info=ctx("recovery-auth", account_id))`; the server stores `SHA-256(auth)` only and66  compares in constant time. RK rotation generates a new RK, increments `recovery_epoch`, replaces both.67* **Vault key** — per vault, per epoch. Delivered to each member account as68  `HPKE.Seal(pk=member_enc_pub, info=ctx("vault-key", vault_id, epoch, member_account_id), pt=VK)` and accompanied by69  `grant_sig = sig_granter(ctx("vault-grant", vault_id, epoch, member_account_id, role, b64(SHA-256(envelope))))`.70  The owner's own copy uses the same construction (uniform code path).71* **Record key** — `HKDF(ikm=VK, salt=record_salt(32 random bytes, fresh per revision), info=ctx("record-key"))`.72  One key encrypts exactly one message; nonce reuse under a key would need a 256-bit salt collision.7374### 2.1 Recovery key format7576`SPV1-` followed by Crockford base32 of `RK(32) ‖ SHA-256("SPV1 recovery checksum" ‖ RK)[0..3]` (35 bytes → 5677characters) in groups of four. Decoding is case-insensitive, maps `O→0`, `I/L→1`, ignores separators and rejects a78wrong checksum before any network request.7980## 3. Record envelope8182```json83{ "v": 1, "alg": 1, "kid": <vault key epoch>, "salt": "<32B>", "nonce": "<12B>", "ct": "<ciphertext‖tag>" }84```8586AAD = `ctx("record", vault_id, record_id, type, rev, kid)`, where `type ∈ {"item","vault-meta","collection"}` and87`rev` is the record revision (1, 2, 3 …). Moving a ciphertext to another vault, record, type or revision, or88replaying revision *n* as revision *n+1*, fails authentication.8990Plaintext is UTF-8 JSON, right-padded with spaces to a multiple of 256 bytes (JSON parsers ignore the padding) to91blunt length leakage. Decoders must reject: unknown `v`/`alg`, wrong sizes, authentication failure, non-JSON.9293Deletion is a tombstone: a new revision whose plaintext is `{"deleted":true}`, plus a server-side `deleted` flag94that the client cross-checks against the decrypted tombstone (a server cannot fake a deletion or hide one that a95client already saw at a higher revision).9697## 4. Attachments9899A random 256-bit file key and 8-byte file nonce prefix are stored **inside the item plaintext** together with the100encrypted-file manifest (`attachment_id`, size, chunk count, SHA-256 of the plaintext, name, MIME type).101The file is split into 1 MiB chunks; chunk *i* is `AES-GCM(file_key, nonce = prefix(8) ‖ u32be(i), chunk,102aad = ctx("chunk", attachment_id, i, final ? "1" : "0", total_chunks))`. Truncation, reordering, duplication and103cross-file substitution fail. The server sees only opaque chunk blobs, their sizes and count.104105## 5. Device pairing1061071. New device signs in with the account passkey (server authentication only — yields a *pending* session with no108   access to envelopes), generates its device keys, a random `pairing_id` and a 128-bit secret `N`, and posts109   `{pairing_id, dev_enc_pub, dev_sig_pub, tag = HMAC(N, ctx("pair", pairing_id, dev_enc_pub, dev_sig_pub))}`.1102. It displays `pairing_id` + `N` as a QR code / short text. `N` never reaches the server. The pairing expires111   after 5 minutes and is single-use.1123. A trusted, unlocked device reads the code, fetches the pairing, **verifies `tag`** (proves the public keys came113   from the device that displayed the code, not from the server), shows the device name and the 6-digit114   fingerprint `SAS = dec6(SHA-256(ctx("sas", pairing_id, dev_enc_pub, dev_sig_pub)))` which the user compares115   with the new device's screen, and on approval uploads the device certificate and the ARK envelope.1164. The new device unwraps ARK, decrypts the keyset, and verifies its own certificate under the account signing117   key recovered from the keyset; mismatch ⇒ abort.118119Recovery-key enrollment replaces steps 2–3: the fresh device proves `auth`, downloads the recovery envelope,120unwraps ARK, self-signs its certificate with the account signing key and wraps ARK for itself. Every enrollment121writes an audit event that all other devices surface.122123## 6. Revocation and rotation124125Revoking a device deletes its ARK envelope, certificate and sessions. A revoked device that was previously126unlocked may have retained ARK in memory or cached plaintext: revocation cannot erase what a device already had.127For that case clients offer **account rekey**: new ARK, new keyset encryption, new vault-key epochs for every128vault, re-wrap for remaining devices and (mandatory) new recovery key. Records are lazily re-encrypted under the129new epoch as they are edited; a "re-encrypt all now" action is available. Removing a vault member always creates130a new epoch. Data a former member already downloaded stays readable to them — only future revisions are protected.131132## 7. Rollback, replay and stale state133134* The server assigns every committed write a strictly increasing per-account `seq`; clients persist the highest135  `seq` and, per record, the highest `rev` ever authenticated. A response containing a lower `rev` for a known136  record, or a `seq` lower than the stored cursor, is reported as **server rollback** and not applied.137* Writes carry `base_rev`; the server rejects anything but `base_rev = current rev` (optimistic concurrency) and138  the AAD binds the new `rev`, so an old ciphertext cannot be re-labelled.139* Every write carries an idempotency key; retried requests return the original result.140* **Limits**: a malicious server can withhold recent writes from a device that has never seen them (freshness141  cannot be proven without a second channel), can roll back a brand-new device to any earlier consistent142  snapshot, and can delete data. Clients that are all offline cannot detect anything until they sync. Cross-device143  comparison of the signed *state digest* (Activity → "Verify sync state") detects divergence after the fact.144145## 8. What the server learns146147Account handle, WebAuthn credential public keys, device public keys and a platform label chosen by the client software (e.g. "MacBook Pro", "Web · Safari (Mac)"), number of vaults,148membership graph, per-record: opaque id, vault id, type tag, revision count, ciphertext length (bucketed to149256 bytes), timestamps, which device wrote; attachment sizes; IP addresses and timing. It never receives titles,150URLs, usernames, passwords, notes, tags, TOTP seeds, file names, vault names or search terms. For cleanup of orphaned files151the server also learns which record references which attachment id. Managed secrets (SP Vault Connect) are outside152this section: their names, kinds, allowed hosts and values are visible to the server by design.153154## 9. Sharing (SP Vault Relay)155156* To an account: `HPKE.Seal(pk=recipient_enc_pub, info=ctx("relay", share_id, sender_account_id,157  recipient_account_id), pt=item JSON)` + sender signature over `ctx("relay-sig", share_id, b64(SHA-256(ct)))`.158  The recipient's public key fingerprint is displayed for out-of-band comparison (trust on first use otherwise).159* Public link: 256-bit secret `S` in the URL fragment (never sent to the server);160  `key = HKDF(S, info=ctx("link-key", share_id))`, AES-GCM with AAD `ctx("link", share_id)`;161  the server authorizes download with `HKDF(S, info=ctx("link-auth", share_id))` (stores its SHA-256), enforces162  expiry and max retrievals. Anyone with the full link can read the secret; send the fragment separately when it matters.163164## 10. Versioning165166`v` and `alg` are in every envelope; decoders reject unknown values. A new suite gets a new `alg` number and new167vectors; clients must keep decrypting all published versions. Server schema changes are additive during rollouts.168169## 11. Server-verified signatures170171The server verifies (it holds public keys only): device certificates at enrolment, the device proof at sign-in172`sig_dev(ctx("login", webauthn_challenge, device_id))`, native step-up `sig_dev(ctx("stepup", challenge, device_id))`,173pairing completion `sig_dev(ctx("pair-complete", pairing_id))` and workload requests174`sig_identity(ctx("agent-request", identity_id, method, path, unix_ts, nonce, b64(SHA-256(body))))`.175These checks are defence in depth; clients never rely on the server having performed them.176177## 12. Audit chain178179`hash_n = b64(SHA-256(canonicalJson([hash_{n-1}, account_id, at, device_id, actor, kind, detail])))` per account,180`canonicalJson` = JSON with recursively sorted object keys. Clients recompute the chain over what they display.181The chain makes silent edits of past events detectable to a client that saw them; it cannot prove completeness182against a server that withholds the newest events.183184## 13. Details fixed by the implementations (normative)185186* **Keyset plaintext**: UTF-8 JSON `{"sig":"<b64u X9.63 private>","enc":"<b64u X9.63 private>"}`, not padded.187* **Relay and link plaintexts** are padded to 256-byte multiples exactly like records (§3).188* **Account fingerprint**: first 10 bytes of `SHA-256(ctx("account-fp", b64u(sig_pub), b64u(enc_pub)))`, upper-case hex in groups of four.189* **Device fingerprint** (display only): first 4 bytes of `SHA-256(ctx("device-fp", enc_pub, sig_pub))`.190* **Encrypted backup file** (`format: "spvault-backup"`, `v: 1`): `key = HKDF(ARK, salt=∅, info=ctx("backup-key", backup_id))`,191  `AES-GCM(key, nonce, payload JSON (unpadded), aad=ctx("backup", backup_id, account_id, created_at))`. The file carries192  the recovery envelope and epoch valid at creation and the keyset blob, so `file + that recovery key` opens it offline.193* **Record `type`** is one of `item`, `vault-meta`, `collection`; decoders reject any other value.194* **Item `type`** unknown to a client is treated as `note` (own-property lookup — never a prototype name).195* **Recovery key input**: case-insensitive, separators ignored, `O→0`, `I/L→1` applied before prefix detection; the196  `SPV1` prefix is optional and removed only when 60 symbols are present.197* **Base64url**: encoders emit the canonical form; signatures and tags are computed over the transmitted text, so a198  non-canonical re-encoding by a server breaks verification instead of creating an alias.199* **Public Suffix List**: each client ships a snapshot (TypeScript: the one inside the pinned `tldts`; Swift:200  `Resources/public_suffix_list.dat`). Snapshots of different dates can disagree on recently added private201  suffixes; the stricter answer (no match) is the safe failure. Releases should refresh both together.202
Files main
Menu

Theme