SPB Git

Repository Public

SPV1.md 14.6 KB

# SPV1 — SP Vault cryptographic protocol, version 1

Status: implemented, not independently audited. Normative for packages/protocol (TypeScript, WebCrypto) and apple/SharedVaultKit (Swift, CryptoKit). Both implementations must pass packages/crypto-test-vectors/spv1.json.

# 1. Primitives (suite 1)

Purpose Primitive Implementation
Content encryption AES-256-GCM, 96-bit random nonce, 128-bit tag WebCrypto / CryptoKit
Key derivation HKDF-SHA256 (RFC 5869) WebCrypto / CryptoKit
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
Signatures ECDSA P-256 with SHA-256, signature = raw r‖s (64 bytes) WebCrypto / CryptoKit
Hash, MAC SHA-256, HMAC-SHA256 WebCrypto / CryptoKit
Randomness crypto.getRandomValues / SystemRandomNumberGenerator OS CSPRNG

P-256 is chosen because it is the only curve the Apple Secure Enclave supports; it lets device private keys be hardware-bound on Apple devices and non-extractable CryptoKeys in browsers, with one algorithm suite everywhere. No password-derived key exists in SPV1 (no master password), therefore no Argon2id dependency: every secret that protects data is a 256-bit random value. No primitive is implemented in this repository.

Encodings: binary values are base64url without padding in JSON. Public keys are X9.63 uncompressed points (65 bytes). Private keys, when serialized (account keyset only), are X9.63 private representations (04‖X‖Y‖D, 97 bytes). Identifiers are lowercase UUIDv4 strings.

# 1.1 Domain-separated context strings

ctx(label, f1, …, fn) = UTF-8 "SPV1" ‖ for each of label, f1…fn: 2-byte big-endian length ‖ UTF-8 bytes. Every AEAD associated data, HKDF info, HPKE info and signed message in SPV1 is a ctx(...) value, so no two uses can collide and every ciphertext is bound to where it belongs. Integers are written in decimal ASCII; binary fields are written as base64url text.

# 2. Key hierarchy

text
Recovery Key RK (256-bit, shown once, never leaves clients)
   └─ HKDF → recovery wrap key ──────────────┐
Device enc key (P-256, Secure Enclave /       │ AES-GCM
non-extractable WebCrypto), one per device    ▼
   └─ HPKE ──────────────────────────▶ Account Root Key ARK (256-bit random)
                                          └─ HKDF("keyset") → AES-GCM → Account keyset
                                                 ├─ account signing key  (ECDSA P-256)
                                                 └─ account encryption key (P-256 KEM)
                                                        └─ HPKE ▶ Vault Key VK[vault, epoch] (256-bit random)
                                                                     └─ HKDF(salt per record revision) → record key
                                                                            └─ AES-GCM → record plaintext
                                                                                   └─ (inside) attachment file keys
  • ARK — generated on the first device. Never stored unwrapped; held in memory only while unlocked.
  • Account keyset — {sig, enc} private keys, JSON, encrypted with K = HKDF(ikm=ARK, salt=∅, info=ctx("keyset-key", account_id)), AAD ctx("keyset", account_id). The server stores the ciphertext and the two public keys.
  • Device keys — each device generates dev_enc (key agreement) and dev_sig (ECDSA). On Apple hardware with a Secure Enclave both are Secure Enclave keys gated by user presence; elsewhere they are non-extractable WebCrypto keys (web) or Keychain-stored software keys (reported as "software" in the device list). Private device keys are never exported, copied or synchronized.
  • Device certificate — sig_account(ctx("device-cert", account_id, device_id, dev_enc_pub, dev_sig_pub, created_at)). A device without a valid certificate under the account signing key is ignored by every client, so the server cannot add a device.
  • ARK envelope (per device) — HPKE.Seal(pk=dev_enc_pub, info=ctx("ark-wrap", account_id, device_id), aad=∅, pt=ARK), serialized enc(65) ‖ ct.
  • Recovery envelope — wrap = HKDF(ikm=RK, salt=∅, info=ctx("recovery-wrap", account_id)); AES-GCM(wrap, nonce, ARK, aad=ctx("recovery", account_id, recovery_epoch)), serialized nonce(12) ‖ ct. auth = HKDF(ikm=RK, salt=∅, info=ctx("recovery-auth", account_id)); the server stores SHA-256(auth) only and compares in constant time. RK rotation generates a new RK, increments recovery_epoch, replaces both.
  • Vault key — per vault, per epoch. Delivered to each member account as HPKE.Seal(pk=member_enc_pub, info=ctx("vault-key", vault_id, epoch, member_account_id), pt=VK) and accompanied by grant_sig = sig_granter(ctx("vault-grant", vault_id, epoch, member_account_id, role, b64(SHA-256(envelope)))). The owner's own copy uses the same construction (uniform code path).
  • Record key — HKDF(ikm=VK, salt=record_salt(32 random bytes, fresh per revision), info=ctx("record-key")). One key encrypts exactly one message; nonce reuse under a key would need a 256-bit salt collision.

# 2.1 Recovery key format

SPV1- followed by Crockford base32 of RK(32) ‖ SHA-256("SPV1 recovery checksum" ‖ RK)[0..3] (35 bytes → 56 characters) in groups of four. Decoding is case-insensitive, maps O→0, I/L→1, ignores separators and rejects a wrong checksum before any network request.

# 3. Record envelope

json
{ "v": 1, "alg": 1, "kid": <vault key epoch>, "salt": "<32B>", "nonce": "<12B>", "ct": "<ciphertext‖tag>" }

AAD = ctx("record", vault_id, record_id, type, rev, kid), where type ∈ {"item","vault-meta","collection"} and rev is the record revision (1, 2, 3 …). Moving a ciphertext to another vault, record, type or revision, or replaying revision n as revision n+1, fails authentication.

Plaintext is UTF-8 JSON, right-padded with spaces to a multiple of 256 bytes (JSON parsers ignore the padding) to blunt length leakage. Decoders must reject: unknown v/alg, wrong sizes, authentication failure, non-JSON.

Deletion is a tombstone: a new revision whose plaintext is {"deleted":true}, plus a server-side deleted flag that the client cross-checks against the decrypted tombstone (a server cannot fake a deletion or hide one that a client already saw at a higher revision).

# 4. Attachments

A random 256-bit file key and 8-byte file nonce prefix are stored inside the item plaintext together with the encrypted-file manifest (attachment_id, size, chunk count, SHA-256 of the plaintext, name, MIME type). The file is split into 1 MiB chunks; chunk i is AES-GCM(file_key, nonce = prefix(8) ‖ u32be(i), chunk, aad = ctx("chunk", attachment_id, i, final ? "1" : "0", total_chunks)). Truncation, reordering, duplication and cross-file substitution fail. The server sees only opaque chunk blobs, their sizes and count.

# 5. Device pairing

  1. New device signs in with the account passkey (server authentication only — yields a pending session with no access to envelopes), generates its device keys, a random pairing_id and a 128-bit secret N, and posts {pairing_id, dev_enc_pub, dev_sig_pub, tag = HMAC(N, ctx("pair", pairing_id, dev_enc_pub, dev_sig_pub))}.
  2. It displays pairing_id + N as a QR code / short text. N never reaches the server. The pairing expires after 5 minutes and is single-use.
  3. A trusted, unlocked device reads the code, fetches the pairing, verifies tag (proves the public keys came from the device that displayed the code, not from the server), shows the device name and the 6-digit fingerprint SAS = dec6(SHA-256(ctx("sas", pairing_id, dev_enc_pub, dev_sig_pub))) which the user compares with the new device's screen, and on approval uploads the device certificate and the ARK envelope.
  4. The new device unwraps ARK, decrypts the keyset, and verifies its own certificate under the account signing key recovered from the keyset; mismatch ⇒ abort.

Recovery-key enrollment replaces steps 2–3: the fresh device proves auth, downloads the recovery envelope, unwraps ARK, self-signs its certificate with the account signing key and wraps ARK for itself. Every enrollment writes an audit event that all other devices surface.

# 6. Revocation and rotation

Revoking a device deletes its ARK envelope, certificate and sessions. A revoked device that was previously unlocked may have retained ARK in memory or cached plaintext: revocation cannot erase what a device already had. For that case clients offer account rekey: new ARK, new keyset encryption, new vault-key epochs for every vault, re-wrap for remaining devices and (mandatory) new recovery key. Records are lazily re-encrypted under the new epoch as they are edited; a "re-encrypt all now" action is available. Removing a vault member always creates a new epoch. Data a former member already downloaded stays readable to them — only future revisions are protected.

# 7. Rollback, replay and stale state

  • The server assigns every committed write a strictly increasing per-account seq; clients persist the highest seq and, per record, the highest rev ever authenticated. A response containing a lower rev for a known record, or a seq lower than the stored cursor, is reported as server rollback and not applied.
  • Writes carry base_rev; the server rejects anything but base_rev = current rev (optimistic concurrency) and the AAD binds the new rev, so an old ciphertext cannot be re-labelled.
  • Every write carries an idempotency key; retried requests return the original result.
  • Limits: a malicious server can withhold recent writes from a device that has never seen them (freshness cannot be proven without a second channel), can roll back a brand-new device to any earlier consistent snapshot, and can delete data. Clients that are all offline cannot detect anything until they sync. Cross-device comparison of the signed state digest (Activity → "Verify sync state") detects divergence after the fact.

# 8. What the server learns

Account 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, membership graph, per-record: opaque id, vault id, type tag, revision count, ciphertext length (bucketed to 256 bytes), timestamps, which device wrote; attachment sizes; IP addresses and timing. It never receives titles, URLs, usernames, passwords, notes, tags, TOTP seeds, file names, vault names or search terms. For cleanup of orphaned files the server also learns which record references which attachment id. Managed secrets (SP Vault Connect) are outside this section: their names, kinds, allowed hosts and values are visible to the server by design.

# 9. Sharing (SP Vault Relay)

  • To an account: HPKE.Seal(pk=recipient_enc_pub, info=ctx("relay", share_id, sender_account_id, recipient_account_id), pt=item JSON) + sender signature over ctx("relay-sig", share_id, b64(SHA-256(ct))). The recipient's public key fingerprint is displayed for out-of-band comparison (trust on first use otherwise).
  • Public link: 256-bit secret S in the URL fragment (never sent to the server); key = HKDF(S, info=ctx("link-key", share_id)), AES-GCM with AAD ctx("link", share_id); the server authorizes download with HKDF(S, info=ctx("link-auth", share_id)) (stores its SHA-256), enforces expiry and max retrievals. Anyone with the full link can read the secret; send the fragment separately when it matters.

# 10. Versioning

v and alg are in every envelope; decoders reject unknown values. A new suite gets a new alg number and new vectors; clients must keep decrypting all published versions. Server schema changes are additive during rollouts.

# 11. Server-verified signatures

The server verifies (it holds public keys only): device certificates at enrolment, the device proof at sign-in sig_dev(ctx("login", webauthn_challenge, device_id)), native step-up sig_dev(ctx("stepup", challenge, device_id)), pairing completion sig_dev(ctx("pair-complete", pairing_id)) and workload requests sig_identity(ctx("agent-request", identity_id, method, path, unix_ts, nonce, b64(SHA-256(body)))). These checks are defence in depth; clients never rely on the server having performed them.

# 12. Audit chain

hash_n = b64(SHA-256(canonicalJson([hash_{n-1}, account_id, at, device_id, actor, kind, detail]))) per account, canonicalJson = JSON with recursively sorted object keys. Clients recompute the chain over what they display. The chain makes silent edits of past events detectable to a client that saw them; it cannot prove completeness against a server that withholds the newest events.

# 13. Details fixed by the implementations (normative)

  • Keyset plaintext: UTF-8 JSON {"sig":"<b64u X9.63 private>","enc":"<b64u X9.63 private>"}, not padded.
  • Relay and link plaintexts are padded to 256-byte multiples exactly like records (§3).
  • Account fingerprint: first 10 bytes of SHA-256(ctx("account-fp", b64u(sig_pub), b64u(enc_pub))), upper-case hex in groups of four.
  • Device fingerprint (display only): first 4 bytes of SHA-256(ctx("device-fp", enc_pub, sig_pub)).
  • Encrypted backup file (format: "spvault-backup", v: 1): key = HKDF(ARK, salt=∅, info=ctx("backup-key", backup_id)), AES-GCM(key, nonce, payload JSON (unpadded), aad=ctx("backup", backup_id, account_id, created_at)). The file carries the recovery envelope and epoch valid at creation and the keyset blob, so file + that recovery key opens it offline.
  • Record type is one of item, vault-meta, collection; decoders reject any other value.
  • Item type unknown to a client is treated as note (own-property lookup — never a prototype name).
  • Recovery key input: case-insensitive, separators ignored, O→0, I/L→1 applied before prefix detection; the SPV1 prefix is optional and removed only when 60 symbols are present.
  • Base64url: encoders emit the canonical form; signatures and tags are computed over the transmitted text, so a non-canonical re-encoding by a server breaks verification instead of creating an alias.
  • Public Suffix List: each client ships a snapshot (TypeScript: the one inside the pinned tldts; Swift: Resources/public_suffix_list.dat). Snapshots of different dates can disagree on recently added private suffixes; the stricter answer (no match) is the safe failure. Releases should refresh both together.
Files main
Menu

Theme