Compare commits
4 Commits
5d04e18482
...
fb7f2e55c0
| Author | SHA1 | Date | |
|---|---|---|---|
| fb7f2e55c0 | |||
| a1c370359e | |||
| b82a803e0c | |||
| bcae7b346e |
@@ -0,0 +1,30 @@
|
||||
---
|
||||
title: "Register venter ikke lenger på en server som ikke svarer"
|
||||
date: 2026-10-15
|
||||
author: "Claude"
|
||||
---
|
||||
|
||||
Prism ble stående med et tomt vindu i flere minutter 2026-10-15 mens zyon var nede.
|
||||
En av grunnene lå her: `Shade.initialize()` ventet på `transport.register()` uten
|
||||
tidsgrense. Når pakkene droppes i stedet for å avvises, betyr det ca. 2 minutter før kjernen
|
||||
gir opp TCP-handshaken. Og feilmeldingen lovet «Will retry on next replenish», men
|
||||
replenish registrerer aldri. En identitet som startet mens serveren var nede, forble
|
||||
uregistrert til neste restart.
|
||||
|
||||
## Endret
|
||||
|
||||
- **`ShadeFetchTransport`**: alle forespørsler går gjennom én `request()` med tidsgrense (`requestTimeoutMs`, standard 15 000, `DEFAULT_REQUEST_TIMEOUT_MS` eksporteres) og en valgfri `fetch`-override. Når tidsgrensen nås, kommer en `NetworkError` med «No response from <host> within N ms».
|
||||
- **`ShadeConfig`**: `registration: 'await' | 'background'`, `requestTimeoutMs`, `fetch`. Standard er `'await'`, så eksisterende brukere får fortsatt «registrert når `createShade` er ferdig», bare med tidsgrense. `'background'` er for apper der det å åpne identiteten skal være helt lokalt (Prisms unlock-port).
|
||||
- **Ekte retry**: en register som feiler, prøves på nytt med backoff 5/15/30/60 s til den lykkes. Retryen avbrytes av `shutdown()`, `rotate()` og `importBackup()`, så en gammel identitet aldri publiseres etter rotasjon.
|
||||
- De tre stedene som bygde `ShadeFetchTransport` bruker nå samme `makeTransport()`, så tidsgrense og fetch følger med ved rotasjon og restore.
|
||||
|
||||
## Verifisert
|
||||
|
||||
`tests/registration.test.ts` (5 nye) mot en fetch som aldri svarer: `'background'`
|
||||
blir ferdig uten å vente, `'await'` gir opp ved tidsgrensen, en feilet register blir
|
||||
prøvd på nytt etter 5 s, og `shutdown` stopper retryene. To nye transporttester for
|
||||
tidsgrensen og fetch-overriden. Hele suiten: 1206 grønne, typecheck ren på alle 26 pakker.
|
||||
|
||||
> [!NOTE]
|
||||
> Ikke publisert ennå. Registryet bor på `gt.zyon.no`, som var nede da dette ble skrevet.
|
||||
> Neste steg er 4.13.2, og deretter at Prism bumper og setter `registration: 'background'` og `fetch: serverLink.fetch`.
|
||||
@@ -0,0 +1,20 @@
|
||||
---
|
||||
title: "Vault v2 og Kotlin-vaulten (4.14.0/4.14.1)"
|
||||
date: 2026-10-16
|
||||
author: "Claude"
|
||||
---
|
||||
|
||||
Shade fikk det Scaffold-vaulten trengte for å bli telefonens kilde når PC-en er av, uten at serveren fylles opp.
|
||||
|
||||
- **4.14.0 — vault v2:**
|
||||
- Filer komprimeres med deflate-raw når det lønner seg, og deles i forseglede biter på 4 MiB. Manifestene komprimeres også (`SVM2`).
|
||||
- Push bruker en lokal indeks og laster ikke ned forrige versjon. En push uten endringer committer ingenting.
|
||||
- Ny lat lesing med `manifest` og `readEntry`.
|
||||
- Relayet registrerer hvilke objekter hver versjon refererer til, og har fått en signert `prune`-rute. SQLite-lageret migrerer seg selv.
|
||||
- Kryss-språk-vektorene ligger i `test-vectors/vault-v2.json`.
|
||||
- **4.14.1 — `edit`:** endrer noen få filer mot hodet som faktisk ble lest, og prøver igjen ved `SEQ_CONFLICT`. Dette er det en kø med to skrivere trenger. `push` publiserer hele samlingen, og ville mistet en fil som en annen enhet la til i mellomtiden.
|
||||
- **Kotlin, `no.zyon.shade.vault`:** en full port av v2 (lese, forsegle, signere, `edit`).
|
||||
- 71 Android-tester er grønne.
|
||||
- Live kryss-sjekk TS↔Kotlin mot ekte vault-ruter (`scripts/vault-live-kotlin.ts`).
|
||||
|
||||
Verifisert: shade-vault 61, storage-sqlite 47 og shade-server 55 grønne, og typecheck er ren for alle 26 pakkene. Publisert til Gitea-registeret. Commitet lokalt og tagget (`v4.14.0`, `v4.14.1`), men ikke pushet til remote. Kotlin-filene i `android/` er ennå ikke commitet.
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
project: "Shade"
|
||||
phase: "Post-4.x GA — hardening til revisjonsklar (G0–G4) før V5.0-design"
|
||||
updated: 2026-08-14
|
||||
updated: 2026-10-15
|
||||
focus: "GCM-nonce-fiksen er levert (2026-08-13) og @shade/vault står ferdig og testet (2026-08-14), men er IKKE deployet eller publisert. De tre gjenstående G0-P0-ene er publiserings- og CI-saker. Historikk: G0 fikk en andre bestiller: @shade/vault (server-side kryptert fillager, bestilt 2026-08-13 av Scaffold-backupen) bygger på at-rest-stacken, og skal ikke reise seg på en kjent GCM-svakhet. Nonce-fiksens migreringssti er verifisert gratis — aeadOpen leser alltid nonce fra prefiks, så eksisterende blobber åpnes uendret."
|
||||
blockers:
|
||||
- "P0: @shade/observer@4.11.1 tomt på registry (outDir=dist-build, publish shipper dist/)"
|
||||
@@ -17,6 +17,9 @@ blockers:
|
||||
|
||||
## Nå
|
||||
Gated hardening — hard utgangsport per steg (full plan + funn: helsesjekk-artifact 2026-07-10, se log.md).
|
||||
- [ ] **Publiser 4.13.2** (register med tidsgrense + ekte retry + `registration: 'background'`,
|
||||
gjort 2026-10-15, se `logs/2026-10-15-register-venter-ikke-lenger-pa-en-server-som-ikke-svarer.md`).
|
||||
Venter på at `gt.zyon.no` er oppe. UNCOMMITTED.
|
||||
- [ ] **G0 — Stopp blødningen (P0):** ~~tilfeldig nonce per skriving i
|
||||
storage-encrypted~~ (gjort 2026-08-13 — 9 nye tester, ingen migrering nødvendig,
|
||||
Android var aldri rammet; se `logs/2026-08-13-gcm-nonce-reuse-fikset.md`.
|
||||
|
||||
68
CHANGELOG.md
68
CHANGELOG.md
@@ -5,6 +5,74 @@ All notable changes to Shade are documented in this file.
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [4.14.1] — 2026-10-16 — Vault: `edit` for vaults two devices write
|
||||
|
||||
- `VaultClient.edit(change, at)` changes a few files against the head that
|
||||
was actually read and commits `head + 1`; on `SEQ_CONFLICT` it re-reads and
|
||||
calls `change` again. `push` publishes a whole collection and would drop a
|
||||
file another device appended in between — right for a backup with one
|
||||
writer, wrong for a queue a phone appends to while a PC drains it.
|
||||
|
||||
## [4.14.0] — 2026-10-16 — Vault v2: smaller, cheaper pushes, big files, retention
|
||||
|
||||
### Added
|
||||
- **`@shade/vault`: compressed and multi-part entries.** A file is deflated
|
||||
(raw, kept only if it saves ≥ 5 %, skipped for known compressed formats)
|
||||
and split into 4 MiB parts. `VaultEntry` gains optional `enc` and `parts`;
|
||||
`size` stays the plaintext length. Files over the relay's 8 MiB object limit
|
||||
can now be backed up at all.
|
||||
- **Manifest v2**: `"SVM2"` + deflate-raw(JSON). Push writes v2; readers
|
||||
accept v1 and v2 and refuse anything else.
|
||||
- **`VaultIndex`** — `push(files, at, message?, { index })` returns an `index`
|
||||
to persist. With a fresh one, an unchanged file is recognised by plaintext
|
||||
SHA-256 with no download, no seal and no upload (renames and copies too).
|
||||
- **A push that changes nothing commits nothing** (`unchanged: true`), unless a
|
||||
`message` asks for a version.
|
||||
- **Lazy reads**: `VaultClient.manifest(seq?)` and `readEntry(entry)`; `pull`
|
||||
is built on them. Exported helpers: `openEntryBytes`, `entryObjectHashes`,
|
||||
`packEntry`, `sealEntry`, `encodeManifest`/`decodeManifest`, `vaultIndexFrom`.
|
||||
- **Retention**: signed `POST /v1/vault/:id/prune` `{ keep }`,
|
||||
`VaultClient.prune(keep)` → `{ removedVersions, removedObjects, freedBytes }`.
|
||||
The relay records each commit's referenced hashes and collects objects no
|
||||
remaining version uses. Versions from before this pin their objects until
|
||||
they are pruned themselves. `VaultRoutesOptions.pruneGraceMs` (default 1 h)
|
||||
protects uploads whose commit is still in flight.
|
||||
- `VaultStore.prune` and an optional `refs` argument on `appendLog`;
|
||||
`SqliteVaultStore` migrates its schema in place on open.
|
||||
- `test-vectors/vault-v2.json` for the Kotlin port; `@shade/vault/testing`
|
||||
(fixed-nonce sealing, vectors only).
|
||||
|
||||
### Changed
|
||||
- Push without an index reads only the head manifest and downloads a previous
|
||||
file only when its path and size match — it used to download every file of
|
||||
the head. Freshly sealed objects are no longer have-checked (their names are
|
||||
new by construction). A reused entry takes the file's current `mode`.
|
||||
- `VaultTransport` has a required `prune` method; custom transports must add it.
|
||||
|
||||
## [4.13.2] — 2026-10-15 — No prekey-server call can hang an identity open
|
||||
|
||||
### Fixed
|
||||
- **`@shade/transport`: every prekey-server request has a deadline**
|
||||
(`requestTimeoutMs`, default 15 000; `DEFAULT_REQUEST_TIMEOUT_MS` exported).
|
||||
A server that drops packets instead of refusing them held each call until
|
||||
the kernel gave up on the TCP handshake — about two minutes on Linux.
|
||||
Expiry throws a `NetworkError` naming the host.
|
||||
- **`@shade/sdk`: a failed initial registration is actually retried** — with
|
||||
backoff (5/15/30/60 s) until it succeeds, the identity rotates or is
|
||||
restored, or `shutdown()` runs. The old log line promised a retry "on next
|
||||
replenish", but replenish never registers: an identity that came up while
|
||||
the server was unreachable stayed unregistered until the next restart.
|
||||
|
||||
### Added
|
||||
- `ShadeConfig.registration: 'await' | 'background'` (default `'await'`, now
|
||||
bounded by the timeout). `'background'` opens the identity without waiting
|
||||
on the network — for apps whose unlock must be purely local.
|
||||
- `ShadeConfig.requestTimeoutMs` and `ShadeConfig.fetch` (also on
|
||||
`ShadeFetchTransport`): observe reachability, or stub the network in tests.
|
||||
|
||||
Found by Prism: with the relay unreachable, unlock — and with it the first
|
||||
terminal — waited minutes on a register call.
|
||||
|
||||
## [4.13.1] — 2026-10-06 — Inbox keeps per-recipient order across retries
|
||||
|
||||
### Fixed
|
||||
|
||||
@@ -49,6 +49,9 @@ dependencies {
|
||||
|
||||
tasks.withType<Test>().configureEach {
|
||||
useJUnit()
|
||||
// VaultLiveTest is gated on this; as an input, a new spec (a new live
|
||||
// relay) reruns the tests instead of reporting a stale UP-TO-DATE.
|
||||
inputs.property("shadeVaultLiveSpec", System.getenv("SHADE_VAULT_LIVE_SPEC") ?: "")
|
||||
testLogging {
|
||||
events("passed", "failed", "skipped")
|
||||
showStandardStreams = false
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package no.zyon.shade.blob
|
||||
|
||||
import no.zyon.shade.crypto.CryptoProvider
|
||||
import no.zyon.shade.serialization.canonicalJson
|
||||
import org.json.JSONObject
|
||||
import java.net.URI
|
||||
import java.net.http.HttpClient
|
||||
@@ -187,62 +188,6 @@ class BlobClient(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Mirror of TS `signPayload`'s canonicalization: sorted keys, compact
|
||||
* JSON, signature field absent. Only handles the subset of types we
|
||||
* need (strings + longs + base64 strings) — keeping the implementation
|
||||
* narrow so it can't accidentally diverge from `JSON.stringify` on
|
||||
* structurally-different inputs.
|
||||
*/
|
||||
internal fun canonicalJson(map: Map<String, Any>): String {
|
||||
val sb = StringBuilder()
|
||||
sb.append('{')
|
||||
var first = true
|
||||
for ((key, value) in map.toSortedMap()) {
|
||||
if (!first) sb.append(',')
|
||||
first = false
|
||||
appendJsonString(sb, key)
|
||||
sb.append(':')
|
||||
appendJsonValue(sb, value)
|
||||
}
|
||||
sb.append('}')
|
||||
return sb.toString()
|
||||
}
|
||||
|
||||
private fun appendJsonValue(sb: StringBuilder, value: Any) {
|
||||
when (value) {
|
||||
is String -> appendJsonString(sb, value)
|
||||
is Long, is Int -> sb.append(value.toString())
|
||||
is Boolean -> sb.append(value.toString())
|
||||
else -> throw IllegalArgumentException(
|
||||
"canonicalJson: unsupported value type ${value::class.java}",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun appendJsonString(sb: StringBuilder, s: String) {
|
||||
sb.append('"')
|
||||
for (c in s) {
|
||||
when (c) {
|
||||
'\\' -> sb.append("\\\\")
|
||||
'"' -> sb.append("\\\"")
|
||||
'\b' -> sb.append("\\b")
|
||||
'\u000C' -> sb.append("\\f")
|
||||
'\n' -> sb.append("\\n")
|
||||
'\r' -> sb.append("\\r")
|
||||
'\t' -> sb.append("\\t")
|
||||
else -> {
|
||||
if (c.code < 0x20) {
|
||||
sb.append("\\u").append("%04x".format(c.code))
|
||||
} else {
|
||||
sb.append(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
sb.append('"')
|
||||
}
|
||||
|
||||
class BlobClientException(
|
||||
val code: String,
|
||||
val statusCode: Int,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
package no.zyon.shade.blob
|
||||
|
||||
import com.google.crypto.tink.subtle.Ed25519Sign
|
||||
import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters
|
||||
import no.zyon.shade.crypto.CryptoProvider
|
||||
|
||||
/**
|
||||
@@ -72,13 +72,20 @@ fun deriveBlobSigningSeed(crypto: CryptoProvider, masterKey: ByteArray, app: Str
|
||||
|
||||
/**
|
||||
* Recover the Ed25519 public key from a 32-byte seed. Mirrors
|
||||
* `@shade/crypto-web`'s `ed25519PublicKeyFromSeed`. Tink's
|
||||
* `Ed25519Sign.KeyPair.newKeyPairFromSeed(seed)` exposes both halves;
|
||||
* we discard the private half here.
|
||||
* `@shade/crypto-web`'s `ed25519PublicKeyFromSeed`.
|
||||
*
|
||||
* BouncyCastle rather than Tink, although the rest of the module signs with
|
||||
* Tink: this is the one primitive the vault and blob code use OUTSIDE the
|
||||
* injected [CryptoProvider], so whatever it calls is a hard dependency of
|
||||
* every app that reads a vault. An Android app cannot take JVM Tink (it
|
||||
* drags in full `protobuf-java`, which collides with Firebase's
|
||||
* `protobuf-javalite`), while BouncyCastle is already here for scrypt and
|
||||
* already in every app that embeds this module. RFC 8032 fixes the result,
|
||||
* so the two produce the same bytes — the blob and vault vectors pin it.
|
||||
*/
|
||||
fun ed25519PublicKeyFromSeed(seed: ByteArray): ByteArray {
|
||||
require(seed.size == 32) { "Ed25519 seed must be 32 bytes" }
|
||||
return Ed25519Sign.KeyPair.newKeyPairFromSeed(seed).publicKey
|
||||
return Ed25519PrivateKeyParameters(seed, 0).generatePublicKey().encoded
|
||||
}
|
||||
|
||||
/** Convert a 32-byte slotId into the lowercase-hex wire form (64 chars). */
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
package no.zyon.shade.serialization
|
||||
|
||||
/**
|
||||
* JSON written exactly the way JavaScript's `JSON.stringify` writes it —
|
||||
* because signatures are computed over these bytes, and a TS relay verifies
|
||||
* them over *its* re-serialisation of the parsed body.
|
||||
*
|
||||
* Two entry points:
|
||||
*
|
||||
* - [canonicalJson]: mirror of TS `canonicalizePayload` (`@shade/server`).
|
||||
* Top-level keys sorted, nested values serialised as-is — `JSON.stringify`
|
||||
* of an object built by inserting the sorted keys, so a nested object keeps
|
||||
* its insertion order and is NOT sorted. The vault's signed bodies carry an
|
||||
* array of hashes and an array of seqs, which is why arrays are supported.
|
||||
* - [stringifyJson]: plain `JSON.stringify` of a value, insertion order kept.
|
||||
* Used where key order is not part of any contract but reproducing the TS
|
||||
* bytes keeps vector tests exact (vault manifests).
|
||||
*
|
||||
* Deliberately narrow: strings, integers, booleans, null, lists and string-
|
||||
* keyed maps. Floating-point numbers are refused rather than formatted —
|
||||
* JavaScript's shortest-round-trip number printing is not something to
|
||||
* approximate in a signature path, and no Shade payload needs it.
|
||||
*/
|
||||
internal fun canonicalJson(map: Map<String, Any>): String {
|
||||
val sb = StringBuilder()
|
||||
sb.append('{')
|
||||
var first = true
|
||||
for ((key, value) in map.toSortedMap()) {
|
||||
if (!first) sb.append(',')
|
||||
first = false
|
||||
appendJsonString(sb, key)
|
||||
sb.append(':')
|
||||
appendJsonValue(sb, value)
|
||||
}
|
||||
sb.append('}')
|
||||
return sb.toString()
|
||||
}
|
||||
|
||||
/** `JSON.stringify(value)` — maps keep their iteration (insertion) order. */
|
||||
internal fun stringifyJson(value: Any?): String {
|
||||
val sb = StringBuilder()
|
||||
appendJsonValue(sb, value)
|
||||
return sb.toString()
|
||||
}
|
||||
|
||||
private fun appendJsonValue(sb: StringBuilder, value: Any?) {
|
||||
when (value) {
|
||||
null -> sb.append("null")
|
||||
is String -> appendJsonString(sb, value)
|
||||
is Long, is Int, is Short, is Byte -> sb.append(value.toString())
|
||||
is Boolean -> sb.append(value.toString())
|
||||
is Map<*, *> -> {
|
||||
sb.append('{')
|
||||
var first = true
|
||||
for ((k, v) in value) {
|
||||
require(k is String) { "stringifyJson: map keys must be strings, got ${k?.javaClass}" }
|
||||
if (!first) sb.append(',')
|
||||
first = false
|
||||
appendJsonString(sb, k)
|
||||
sb.append(':')
|
||||
appendJsonValue(sb, v)
|
||||
}
|
||||
sb.append('}')
|
||||
}
|
||||
is Iterable<*> -> {
|
||||
sb.append('[')
|
||||
var first = true
|
||||
for (v in value) {
|
||||
if (!first) sb.append(',')
|
||||
first = false
|
||||
appendJsonValue(sb, v)
|
||||
}
|
||||
sb.append(']')
|
||||
}
|
||||
is Array<*> -> appendJsonValue(sb, value.asList())
|
||||
else -> throw IllegalArgumentException(
|
||||
"canonicalJson: unsupported value type ${value::class.java}",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* `JSON.stringify` string escaping (ES2019 "well-formed"): the two-character
|
||||
* escapes for `" \ \b \f \n \r \t`, `\u00XX` (lowercase) for other control
|
||||
* characters and for lone surrogates, everything else — including non-ASCII
|
||||
* — emitted literally and left to UTF-8.
|
||||
*/
|
||||
private fun appendJsonString(sb: StringBuilder, s: String) {
|
||||
sb.append('"')
|
||||
var i = 0
|
||||
while (i < s.length) {
|
||||
val c = s[i]
|
||||
when {
|
||||
c == '\\' -> sb.append("\\\\")
|
||||
c == '"' -> sb.append("\\\"")
|
||||
c == '\b' -> sb.append("\\b")
|
||||
c == '\u000C' -> sb.append("\\f")
|
||||
c == '\n' -> sb.append("\\n")
|
||||
c == '\r' -> sb.append("\\r")
|
||||
c == '\t' -> sb.append("\\t")
|
||||
c.code < 0x20 -> sb.append("\\u").append("%04x".format(c.code))
|
||||
c.isHighSurrogate() && i + 1 < s.length && s[i + 1].isLowSurrogate() -> {
|
||||
sb.append(c).append(s[i + 1])
|
||||
i++
|
||||
}
|
||||
c.isSurrogate() -> sb.append("\\u").append("%04x".format(c.code))
|
||||
else -> sb.append(c)
|
||||
}
|
||||
i++
|
||||
}
|
||||
sb.append('"')
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
package no.zyon.shade.vault
|
||||
|
||||
import no.zyon.shade.crypto.CryptoProvider
|
||||
import java.security.MessageDigest
|
||||
import java.util.Base64
|
||||
|
||||
/** A file as the app sees it, before encryption. */
|
||||
class VaultFile(val path: String, val bytes: ByteArray, val mode: String? = null)
|
||||
|
||||
/**
|
||||
* A few files changed, for [VaultClient.edit] — mirror of TS `VaultEdit`.
|
||||
*/
|
||||
class VaultEdit(
|
||||
/** Files to add, or to replace at the same path. Paths must be distinct. */
|
||||
val put: List<VaultFile> = emptyList(),
|
||||
/** Paths to drop. A path that is not there is ignored. */
|
||||
val remove: List<String> = emptyList(),
|
||||
)
|
||||
|
||||
/** What [VaultClient.edit] did. */
|
||||
data class VaultEditResult(
|
||||
/** The head after the edit: the new version, or the unchanged head. */
|
||||
val seq: Long,
|
||||
/** False when the edit changed nothing and no version was committed. */
|
||||
val committed: Boolean,
|
||||
)
|
||||
|
||||
/** A whole version, decrypted. */
|
||||
class VaultPull(val manifest: VaultManifest, val files: Map<String, ByteArray>)
|
||||
|
||||
/**
|
||||
* The client half of `@shade/vault` v2 for a phone: read a vault whose writer
|
||||
* (the PC) may be switched off, and edit a vault several devices write to —
|
||||
* such as a queue of changes the phone appends to and the PC drains.
|
||||
*
|
||||
* What it deliberately does not port is TS `push` (publish a whole
|
||||
* collection from local files, with an index): a phone is not the source of
|
||||
* truth for a workspace, and a whole-collection push from a stale view is
|
||||
* exactly how another device's latest file gets lost. [edit] is the write
|
||||
* primitive here.
|
||||
*
|
||||
* Blocking, like the transport: call from a background dispatcher.
|
||||
*
|
||||
* @param clock wall clock for `signedAt` — the relay rejects signatures older
|
||||
* than five minutes, so this must be real time outside tests.
|
||||
* @param chunkSize part size; tests only. Real writers use [VAULT_CHUNK_SIZE]
|
||||
* so every implementation splits identically.
|
||||
*/
|
||||
class VaultClient(
|
||||
private val crypto: CryptoProvider,
|
||||
private val keys: VaultKeys,
|
||||
private val transport: VaultTransport,
|
||||
private val chunkSize: Int = VAULT_CHUNK_SIZE,
|
||||
private val clock: () -> Long = System::currentTimeMillis,
|
||||
) {
|
||||
val vaultId: String get() = keys.vaultId
|
||||
|
||||
/** Version history, newest last. [limit] counts back from the head. */
|
||||
fun log(limit: Int? = null): VaultLog = transport.log(keys.vaultId, limit)
|
||||
|
||||
/**
|
||||
* Fetch and open just a version's manifest; defaults to the head. The
|
||||
* cheap way to list a thousand-file workspace: one download, then
|
||||
* [readEntry] only what the user opens.
|
||||
*
|
||||
* @throws VaultException `NOT_FOUND` when there is no such version
|
||||
* (including the head of an empty vault — see [headManifest]).
|
||||
*/
|
||||
fun manifest(seq: Long? = null): VaultManifest {
|
||||
// The head needs only the newest row; an older version needs the log
|
||||
// to find its row, since `limit` counts back from the head.
|
||||
val log = transport.log(keys.vaultId, if (seq == null) 1 else null)
|
||||
val wanted = seq ?: log.head
|
||||
val row = log.entries.firstOrNull { it.seq == wanted }
|
||||
?: throw VaultException(VaultException.CODE_NOT_FOUND, 0, "vault has no version $wanted")
|
||||
return openRow(row)
|
||||
}
|
||||
|
||||
/** The head manifest, or null when nothing has ever been committed. */
|
||||
fun headManifest(): VaultManifest? {
|
||||
val log = transport.log(keys.vaultId, 1)
|
||||
val row = log.entries.firstOrNull { it.seq == log.head } ?: return null
|
||||
return openRow(row)
|
||||
}
|
||||
|
||||
/** Fetch, verify, decrypt and reassemble one file of a manifest. */
|
||||
fun readEntry(entry: VaultEntry): ByteArray {
|
||||
val objects = entryObjectHashes(entry).map { transport.get(keys.vaultId, it) }
|
||||
return openEntryBytes(crypto, keys.contentKey, keys.vaultId, entry, objects)
|
||||
}
|
||||
|
||||
/** Fetch a version and decrypt all of it; defaults to the head. */
|
||||
fun pull(seq: Long? = null): VaultPull {
|
||||
val manifest = manifest(seq)
|
||||
val files = LinkedHashMap<String, ByteArray>()
|
||||
for (entry in manifest.entries) files[entry.path] = readEntry(entry)
|
||||
return VaultPull(manifest, files)
|
||||
}
|
||||
|
||||
/**
|
||||
* Change a few files against the head that was actually read, and only it
|
||||
* — mirror of TS `VaultClient.edit`.
|
||||
*
|
||||
* Reads the head, lets [change] decide from exactly that manifest (null
|
||||
* for an empty vault), keeps every entry it did not touch as-is — same
|
||||
* hash, same parts, never re-sealed — and commits `head + 1`. If another
|
||||
* device committed in between, the relay answers SEQ_CONFLICT and this
|
||||
* starts over from the new head, calling [change] again: it must be a
|
||||
* pure decision about the manifest it is given.
|
||||
*
|
||||
* Returning null, or an edit with no puts that removes nothing present,
|
||||
* commits nothing.
|
||||
*
|
||||
* One deliberate difference from TS: a file sealed in a lost attempt is
|
||||
* not sealed again on the retry. Its objects are already on the relay
|
||||
* (covered by the prune grace period), and on a phone the upload is the
|
||||
* expensive part. The committed manifest is the same either way.
|
||||
*
|
||||
* @throws VaultException SEQ_CONFLICT after [maxAttempts] lost races, or
|
||||
* any other relay refusal at once.
|
||||
* @throws VaultFormatException when the head cannot be read — editing on
|
||||
* top of a manifest this client cannot parse would drop its files.
|
||||
*/
|
||||
fun edit(at: Long, maxAttempts: Int = 5, change: (VaultManifest?) -> VaultEdit?): VaultEditResult {
|
||||
val attempts = maxOf(1, maxAttempts)
|
||||
// Plaintext digest + path → the entry its upload produced, across attempts.
|
||||
val sealedThisEdit = HashMap<String, VaultEntry>()
|
||||
var attempt = 1
|
||||
while (true) {
|
||||
val log = transport.log(keys.vaultId, 1)
|
||||
val head = log.head
|
||||
val row = log.entries.firstOrNull { it.seq == head }
|
||||
val manifest = row?.let { openRow(it) }
|
||||
val edit = change(manifest)
|
||||
val put = edit?.put.orEmpty()
|
||||
val remove = edit?.remove.orEmpty().toSet()
|
||||
val current = manifest?.entries.orEmpty()
|
||||
val replaced = put.map { it.path }.toSet()
|
||||
require(replaced.size == put.size) { "VaultEdit.put lists the same path more than once" }
|
||||
if (put.isEmpty() && current.none { it.path in remove }) {
|
||||
return VaultEditResult(seq = head, committed = false)
|
||||
}
|
||||
|
||||
val entries = current.filterTo(ArrayList()) { it.path !in remove && it.path !in replaced }
|
||||
for (file in put) {
|
||||
val key = sha256Hex(file.bytes) + "\u0000" + file.path
|
||||
val located = sealedThisEdit.getOrPut(key) { upload(file) }
|
||||
entries.add(located.copy(mode = file.mode))
|
||||
}
|
||||
|
||||
try {
|
||||
val seq = commitManifest(entries, head + 1, at)
|
||||
return VaultEditResult(seq = seq, committed = true)
|
||||
} catch (e: VaultException) {
|
||||
// Only a lost race is worth another go; the manifest object
|
||||
// just uploaded is an orphan the relay's GC will collect.
|
||||
if (attempt >= attempts || !e.isSeqConflict) throw e
|
||||
}
|
||||
attempt++
|
||||
}
|
||||
}
|
||||
|
||||
/** Add or replace [files], keeping everything else — [edit] with only puts. */
|
||||
fun append(files: List<VaultFile>, at: Long, maxAttempts: Int = 5): VaultEditResult =
|
||||
edit(at, maxAttempts) { VaultEdit(put = files) }
|
||||
|
||||
/**
|
||||
* Drop every version not in [keep] and let the relay delete objects only
|
||||
* those versions used. [keep] must include the current head.
|
||||
*/
|
||||
fun prune(keep: List<Long>): VaultPruneResult =
|
||||
transport.prune(keys.vaultId, sign(mapOf("keep" to keep)))
|
||||
|
||||
// ─── Internals ───────────────────────────────────────────
|
||||
|
||||
/** Seal one file into fresh objects and PUT them; the entry, without mode. */
|
||||
private fun upload(file: VaultFile): VaultEntry {
|
||||
val sealed = sealEntry(crypto, keys.contentKey, keys.vaultId, file.bytes, chunkSize)
|
||||
// No have-check: every object was just sealed under a fresh nonce,
|
||||
// so its name is new by construction.
|
||||
for (obj in sealed.objects) {
|
||||
transport.put(keys.vaultId, obj.hash, sign(mapOf("data" to Base64.getEncoder().encodeToString(obj.bytes))))
|
||||
}
|
||||
return VaultEntry(
|
||||
path = file.path,
|
||||
hash = sealed.locator.hash,
|
||||
size = file.bytes.size.toLong(),
|
||||
enc = sealed.locator.enc,
|
||||
parts = sealed.locator.parts,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Seal and upload a v2 manifest naming [entries], then commit it as [seq].
|
||||
* Every entry's objects must already be on the relay. `hashes` lists every
|
||||
* part of every entry: the relay checks they exist, and records them as
|
||||
* what the version references — a part left out may be pruned.
|
||||
*/
|
||||
private fun commitManifest(entries: List<VaultEntry>, seq: Long, at: Long): Long {
|
||||
val manifest = VaultManifest(version = 2, seq = seq, at = at, entries = entries)
|
||||
val sealed = sealManifest(crypto, keys.contentKey, keys.vaultId, manifest)
|
||||
transport.put(keys.vaultId, sealed.hash, sign(mapOf("data" to Base64.getEncoder().encodeToString(sealed.bytes))))
|
||||
val hashes = LinkedHashSet<String>().apply { entries.forEach { addAll(entryObjectHashes(it)) } }
|
||||
return transport.commit(
|
||||
keys.vaultId,
|
||||
sign(
|
||||
linkedMapOf(
|
||||
"manifest" to sealed.hash,
|
||||
"seq" to seq,
|
||||
"at" to at,
|
||||
"hashes" to hashes.toList(),
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
private fun sign(body: Map<String, Any>): String = signVaultBody(crypto, keys, body, clock()).json
|
||||
|
||||
private fun openRow(row: VaultLogEntry): VaultManifest =
|
||||
openManifest(crypto, keys.contentKey, keys.vaultId, row.manifest, transport.get(keys.vaultId, row.manifest))
|
||||
|
||||
private fun sha256Hex(bytes: ByteArray): String = toHex(MessageDigest.getInstance("SHA-256").digest(bytes))
|
||||
}
|
||||
@@ -0,0 +1,364 @@
|
||||
package no.zyon.shade.vault
|
||||
|
||||
import no.zyon.shade.blob.aeadSeal
|
||||
import no.zyon.shade.crypto.CryptoProvider
|
||||
import no.zyon.shade.serialization.stringifyJson
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.security.GeneralSecurityException
|
||||
import java.security.MessageDigest
|
||||
import java.util.zip.DataFormatException
|
||||
import java.util.zip.Deflater
|
||||
import java.util.zip.Inflater
|
||||
|
||||
/**
|
||||
* Sealing, naming, packing and manifest encoding — mirror of
|
||||
* `@shade/vault/src/crypto.ts`. The cross-language contract is the
|
||||
* "Format (v2)" section of `docs/vault.md`; vectors in
|
||||
* `test-vectors/vault-v2.json`.
|
||||
*
|
||||
* Every object on the relay is `nonce(12) || ciphertext || tag(16)`, named by
|
||||
* the lowercase hex SHA-256 of those bytes. Hashing the *ciphertext* is what
|
||||
* lets the relay check an upload without holding a key; the price is that
|
||||
* identical plaintext gets a new name on every seal (fresh nonce), so
|
||||
* unchanged files must reuse their old entry instead of being re-sealed.
|
||||
*/
|
||||
|
||||
private const val NONCE_LEN = 12
|
||||
private const val TAG_LEN = 16
|
||||
|
||||
/**
|
||||
* Largest stored (post-compression) slice sealed as one object: 4 MiB.
|
||||
* Part of the wire contract — every writer splits at the same boundary.
|
||||
*/
|
||||
const val VAULT_CHUNK_SIZE = 4 * 1024 * 1024
|
||||
|
||||
/**
|
||||
* Ceiling on an inflated manifest. Manifests are sealed under our own key, so
|
||||
* a decompression bomb could only come from a device that holds it — but a
|
||||
* corrupted write should fail with a message, not by exhausting the heap.
|
||||
*/
|
||||
private const val MAX_MANIFEST_BYTES = 256L * 1024 * 1024
|
||||
|
||||
/** ASCII "SVM2" — marks a compressed v2 manifest. */
|
||||
private val MANIFEST_V2_MAGIC = byteArrayOf(0x53, 0x56, 0x4d, 0x32)
|
||||
|
||||
/** One sealed object: its relay name and its bytes. */
|
||||
class SealedObject(val hash: String, val bytes: ByteArray)
|
||||
|
||||
/** Lowercase hex SHA-256 — the name of an object. */
|
||||
fun objectHash(sealed: ByteArray): String =
|
||||
toHex(MessageDigest.getInstance("SHA-256").digest(sealed))
|
||||
|
||||
/**
|
||||
* AAD for an object: binds the vault, so a ciphertext lifted from one vault
|
||||
* cannot be planted in another even by someone who can write to both. The
|
||||
* content hash is deliberately not in it — it is derived from the very bytes
|
||||
* being sealed.
|
||||
*/
|
||||
fun vaultObjectAad(vaultId: String): ByteArray =
|
||||
"shade-vault-object-v1|$vaultId".toByteArray(Charsets.UTF_8)
|
||||
|
||||
/** Encrypt one object under a fresh random nonce and give it its name. */
|
||||
fun sealObject(crypto: CryptoProvider, contentKey: ByteArray, vaultId: String, plaintext: ByteArray): SealedObject {
|
||||
val (ciphertext, nonce) = crypto.aesGcmEncrypt(contentKey, plaintext, vaultObjectAad(vaultId))
|
||||
val bytes = ByteArray(NONCE_LEN + ciphertext.size)
|
||||
System.arraycopy(nonce, 0, bytes, 0, NONCE_LEN)
|
||||
System.arraycopy(ciphertext, 0, bytes, NONCE_LEN, ciphertext.size)
|
||||
return SealedObject(objectHash(bytes), bytes)
|
||||
}
|
||||
|
||||
/**
|
||||
* [sealObject] with a caller-chosen nonce — for cross-language vectors ONLY.
|
||||
* Mirror of `@shade/vault/testing`'s `sealObjectWithNonce`. `internal` so it
|
||||
* is reachable from this module's tests and from nowhere else: a nonce reused
|
||||
* under one content key breaks AES-GCM outright.
|
||||
*/
|
||||
internal fun sealObjectWithNonce(contentKey: ByteArray, vaultId: String, plaintext: ByteArray, nonce: ByteArray): SealedObject {
|
||||
val bytes = aeadSeal(contentKey, nonce, plaintext, vaultObjectAad(vaultId))
|
||||
return SealedObject(objectHash(bytes), bytes)
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrypt one object, verifying its name first: a relay that returned the
|
||||
* wrong object would otherwise surface as an AEAD failure, which reads like
|
||||
* key corruption and sends the user looking in the wrong place.
|
||||
*/
|
||||
fun openObject(
|
||||
crypto: CryptoProvider,
|
||||
contentKey: ByteArray,
|
||||
vaultId: String,
|
||||
expectedHash: String,
|
||||
bytes: ByteArray,
|
||||
): ByteArray {
|
||||
if (bytes.size < NONCE_LEN + TAG_LEN) {
|
||||
throw VaultFormatException("vault object too short to be a sealed object")
|
||||
}
|
||||
val actual = objectHash(bytes)
|
||||
if (actual != expectedHash) {
|
||||
throw VaultFormatException("vault object hash mismatch: expected $expectedHash, got $actual")
|
||||
}
|
||||
return try {
|
||||
crypto.aesGcmDecrypt(
|
||||
contentKey,
|
||||
bytes.copyOfRange(NONCE_LEN, bytes.size),
|
||||
bytes.copyOfRange(0, NONCE_LEN),
|
||||
vaultObjectAad(vaultId),
|
||||
)
|
||||
} catch (e: GeneralSecurityException) {
|
||||
// The hash matched, so the relay returned what was asked for; a tag
|
||||
// failure now means a wrong key or an object from another vault.
|
||||
throw VaultFormatException("vault object $expectedHash failed authentication (wrong key or vault?)", e)
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Compression ─────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Raw DEFLATE (RFC 1951) at zlib's default level — what the TS side's
|
||||
* `CompressionStream('deflate-raw')` produces. Readers never depend on the
|
||||
* exact bytes, only on the stream inflating to the original.
|
||||
*/
|
||||
fun deflateRaw(bytes: ByteArray): ByteArray {
|
||||
val deflater = Deflater(Deflater.DEFAULT_COMPRESSION, true)
|
||||
try {
|
||||
deflater.setInput(bytes)
|
||||
deflater.finish()
|
||||
val out = ByteArrayOutputStream(maxOf(64, bytes.size / 2))
|
||||
val buf = ByteArray(64 * 1024)
|
||||
while (!deflater.finished()) {
|
||||
val n = deflater.deflate(buf)
|
||||
out.write(buf, 0, n)
|
||||
}
|
||||
return out.toByteArray()
|
||||
} finally {
|
||||
deflater.end()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Inverse of [deflateRaw], refusing to produce more than [limit] bytes.
|
||||
*
|
||||
* Strict about the stream's end, like the TS `DecompressionStream`: a stream
|
||||
* that stops before its final block is "truncated", and bytes after the final
|
||||
* block are "trailing data" — both are corruption, not something to paper
|
||||
* over by returning whatever inflated so far.
|
||||
*/
|
||||
fun inflateRaw(bytes: ByteArray, limit: Long): ByteArray {
|
||||
val inflater = Inflater(true)
|
||||
try {
|
||||
// With `nowrap`, zlib may need one byte past the end of the stream
|
||||
// before it reports `finished()` (documented on Inflater's
|
||||
// constructor). Feed a dummy byte so a valid stream always finishes;
|
||||
// it is never consumed, which is how trailing data is recognised below.
|
||||
inflater.setInput(bytes.copyOf(bytes.size + 1))
|
||||
val out = ByteArrayOutputStream()
|
||||
val buf = ByteArray(64 * 1024)
|
||||
var stalls = 0
|
||||
while (!inflater.finished()) {
|
||||
val n = try {
|
||||
inflater.inflate(buf)
|
||||
} catch (e: DataFormatException) {
|
||||
throw VaultFormatException("vault inflate failed: ${e.message ?: "corrupt deflate stream"}", e)
|
||||
}
|
||||
if (n == 0) {
|
||||
if (inflater.finished()) break
|
||||
if (inflater.needsDictionary()) throw VaultFormatException("vault inflate failed: stream wants a preset dictionary")
|
||||
if (inflater.needsInput()) throw VaultFormatException("vault inflate failed: truncated deflate stream")
|
||||
// Neither progress nor a reason: never spin forever on it.
|
||||
if (++stalls > 2) throw VaultFormatException("vault inflate failed: no progress")
|
||||
continue
|
||||
}
|
||||
stalls = 0
|
||||
if (out.size().toLong() + n > limit) throw VaultFormatException("vault inflate exceeded $limit bytes")
|
||||
out.write(buf, 0, n)
|
||||
}
|
||||
if (inflater.remaining > 1) {
|
||||
throw VaultFormatException("vault inflate failed: ${inflater.remaining - 1} byte(s) of trailing data")
|
||||
}
|
||||
return out.toByteArray()
|
||||
} finally {
|
||||
inflater.end()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Does this file start with the signature of an already-compressed format?
|
||||
* Part of the contract so ports make the same `enc` choice: PNG, JPEG, WebP
|
||||
* ("RIFF"…"WEBP"), MP4 family ("ftyp" at offset 4), GIF, gzip, zip ("PK",
|
||||
* which also covers docx/xlsx/jar/apk).
|
||||
*/
|
||||
fun looksCompressed(b: ByteArray): Boolean {
|
||||
fun at(offset: Int, vararg sig: Int): Boolean =
|
||||
b.size >= offset + sig.size && sig.indices.all { (b[offset + it].toInt() and 0xff) == sig[it] }
|
||||
return at(0, 0x89, 0x50, 0x4e, 0x47) || // PNG
|
||||
at(0, 0xff, 0xd8, 0xff) || // JPEG
|
||||
(at(0, 0x52, 0x49, 0x46, 0x46) && at(8, 0x57, 0x45, 0x42, 0x50)) || // RIFF....WEBP
|
||||
at(4, 0x66, 0x74, 0x79, 0x70) || // ....ftyp
|
||||
at(0, 0x47, 0x49, 0x46, 0x38) || // GIF8
|
||||
at(0, 0x1f, 0x8b) || // gzip
|
||||
at(0, 0x50, 0x4b) // PK
|
||||
}
|
||||
|
||||
// ─── Entries ─────────────────────────────────────────────────
|
||||
|
||||
/** A file's bytes as they will be stored, before sealing. */
|
||||
class PackedEntry(
|
||||
/** [VAULT_ENC_DEFLATE_RAW] when the stored bytes are compressed, else null. */
|
||||
val enc: String?,
|
||||
/** The plaintext, or its deflate-raw. */
|
||||
val stored: ByteArray,
|
||||
/** [stored] in slices of at most the chunk size. Never empty. */
|
||||
val chunks: List<ByteArray>,
|
||||
)
|
||||
|
||||
/**
|
||||
* Turn a file's plaintext into the slices that get sealed.
|
||||
*
|
||||
* Compression is kept only when it saves at least 5 %, as the integer test
|
||||
* `compressed * 20 <= plain * 19` so no port disagrees over rounding. The
|
||||
* whole file is compressed first and THEN split: a reader concatenates the
|
||||
* opened parts and inflates once, so parts carry no framing of their own.
|
||||
*
|
||||
* [chunkSize] exists for tests and vectors; real writers use the default.
|
||||
*/
|
||||
fun packEntry(plaintext: ByteArray, chunkSize: Int = VAULT_CHUNK_SIZE): PackedEntry {
|
||||
require(chunkSize >= 1) { "vault chunk size must be a positive integer, got $chunkSize" }
|
||||
var stored = plaintext
|
||||
var enc: String? = null
|
||||
if (plaintext.isNotEmpty() && !looksCompressed(plaintext)) {
|
||||
val deflated = deflateRaw(plaintext)
|
||||
if (deflated.size.toLong() * 20 <= plaintext.size.toLong() * 19) {
|
||||
stored = deflated
|
||||
enc = VAULT_ENC_DEFLATE_RAW
|
||||
}
|
||||
}
|
||||
// An empty file is still one (empty) object: an entry always names
|
||||
// something the relay holds, so a reader never special-cases.
|
||||
val chunks = ArrayList<ByteArray>()
|
||||
var i = 0
|
||||
while (i < stored.size || chunks.isEmpty()) {
|
||||
chunks.add(stored.copyOfRange(i, minOf(stored.size, i + chunkSize)))
|
||||
i += chunkSize
|
||||
}
|
||||
return PackedEntry(enc, stored, chunks)
|
||||
}
|
||||
|
||||
/** The manifest fields that locate a file's ciphertext. */
|
||||
data class EntryLocator(val hash: String, val parts: List<String>? = null, val enc: String? = null)
|
||||
|
||||
/** Shape an entry's locator from its sealed parts (one part → no `parts`). */
|
||||
fun entryLocator(packed: PackedEntry, sealed: List<SealedObject>): EntryLocator {
|
||||
require(sealed.isNotEmpty()) { "an entry has at least one object" }
|
||||
return EntryLocator(
|
||||
hash = sealed[0].hash,
|
||||
parts = if (sealed.size > 1) sealed.map { it.hash } else null,
|
||||
enc = packed.enc,
|
||||
)
|
||||
}
|
||||
|
||||
/** The locator for a file's manifest entry, and the objects to upload. */
|
||||
class SealedEntry(val locator: EntryLocator, val objects: List<SealedObject>)
|
||||
|
||||
/** Pack and seal one file. */
|
||||
fun sealEntry(
|
||||
crypto: CryptoProvider,
|
||||
contentKey: ByteArray,
|
||||
vaultId: String,
|
||||
plaintext: ByteArray,
|
||||
chunkSize: Int = VAULT_CHUNK_SIZE,
|
||||
): SealedEntry {
|
||||
val packed = packEntry(plaintext, chunkSize)
|
||||
val objects = packed.chunks.map { sealObject(crypto, contentKey, vaultId, it) }
|
||||
return SealedEntry(entryLocator(packed, objects), objects)
|
||||
}
|
||||
|
||||
/**
|
||||
* Every object an entry needs, in read order — also exactly what a commit's
|
||||
* signed `hashes` must list, or a part may be collected by the next prune.
|
||||
*/
|
||||
fun entryObjectHashes(entry: VaultEntry): List<String> =
|
||||
if (!entry.parts.isNullOrEmpty()) entry.parts else listOf(entry.hash)
|
||||
|
||||
/**
|
||||
* Reassemble a file from its fetched objects, in [entryObjectHashes] order:
|
||||
* verify and open each part, concatenate, inflate if `enc`, check the size.
|
||||
*
|
||||
* The size check is what catches a part list that lost or gained an element
|
||||
* — every part authenticates on its own, so such an entry would otherwise
|
||||
* open cleanly into a truncated or padded file.
|
||||
*/
|
||||
fun openEntryBytes(
|
||||
crypto: CryptoProvider,
|
||||
contentKey: ByteArray,
|
||||
vaultId: String,
|
||||
entry: VaultEntry,
|
||||
objects: List<ByteArray>,
|
||||
): ByteArray {
|
||||
val hashes = entryObjectHashes(entry)
|
||||
if (!entry.parts.isNullOrEmpty() && entry.parts[0] != entry.hash) {
|
||||
throw VaultFormatException("vault entry ${entry.path}: hash must equal parts[0]")
|
||||
}
|
||||
if (objects.size != hashes.size) {
|
||||
throw VaultFormatException("vault entry ${entry.path}: expected ${hashes.size} object(s), got ${objects.size}")
|
||||
}
|
||||
if (entry.size < 0 || entry.size > Int.MAX_VALUE - 8) {
|
||||
throw VaultFormatException("vault entry ${entry.path}: size ${entry.size} cannot be held in memory")
|
||||
}
|
||||
|
||||
val stored = ByteArrayOutputStream()
|
||||
for (i in hashes.indices) {
|
||||
stored.write(openObject(crypto, contentKey, vaultId, hashes[i], objects[i]))
|
||||
}
|
||||
|
||||
val plaintext = when (entry.enc) {
|
||||
null -> stored.toByteArray()
|
||||
VAULT_ENC_DEFLATE_RAW -> inflateRaw(stored.toByteArray(), entry.size)
|
||||
// Guessing would hand back bytes that look like the file and are not.
|
||||
else -> throw VaultFormatException("vault entry ${entry.path}: unsupported encoding ${entry.enc}")
|
||||
}
|
||||
if (plaintext.size.toLong() != entry.size) {
|
||||
throw VaultFormatException(
|
||||
"vault entry ${entry.path}: size mismatch, manifest says ${entry.size}, got ${plaintext.size}",
|
||||
)
|
||||
}
|
||||
return plaintext
|
||||
}
|
||||
|
||||
// ─── Manifests ───────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* A manifest's plaintext before sealing: v1 is bare UTF-8 JSON, v2 is "SVM2"
|
||||
* + deflate-raw of it. The version field decides the container.
|
||||
*/
|
||||
fun encodeManifest(manifest: VaultManifest): ByteArray {
|
||||
require(manifest.version == 1 || manifest.version == 2) {
|
||||
"unsupported vault manifest version: ${manifest.version}"
|
||||
}
|
||||
val json = stringifyJson(manifest.toJsonMap()).toByteArray(Charsets.UTF_8)
|
||||
if (manifest.version == 1) return json
|
||||
return MANIFEST_V2_MAGIC + deflateRaw(json)
|
||||
}
|
||||
|
||||
/** Parse a manifest's plaintext, v1 or v2, refusing any other version. */
|
||||
fun decodeManifest(plain: ByteArray): VaultManifest {
|
||||
val isV2 = plain.size >= MANIFEST_V2_MAGIC.size &&
|
||||
MANIFEST_V2_MAGIC.indices.all { plain[it] == MANIFEST_V2_MAGIC[it] }
|
||||
val json = if (isV2) {
|
||||
inflateRaw(plain.copyOfRange(MANIFEST_V2_MAGIC.size, plain.size), MAX_MANIFEST_BYTES)
|
||||
} else {
|
||||
plain
|
||||
}
|
||||
return parseManifestJson(String(json, Charsets.UTF_8))
|
||||
}
|
||||
|
||||
/** A manifest is stored as an ordinary object; this is the encoding step around it. */
|
||||
fun sealManifest(crypto: CryptoProvider, contentKey: ByteArray, vaultId: String, manifest: VaultManifest): SealedObject =
|
||||
sealObject(crypto, contentKey, vaultId, encodeManifest(manifest))
|
||||
|
||||
fun openManifest(
|
||||
crypto: CryptoProvider,
|
||||
contentKey: ByteArray,
|
||||
vaultId: String,
|
||||
expectedHash: String,
|
||||
bytes: ByteArray,
|
||||
): VaultManifest = decodeManifest(openObject(crypto, contentKey, vaultId, expectedHash, bytes))
|
||||
@@ -0,0 +1,44 @@
|
||||
package no.zyon.shade.vault
|
||||
|
||||
/**
|
||||
* The relay refused a request. [code] is the relay's own error code
|
||||
* (`BAD_REQUEST`, `UNAUTHORIZED`, `NOT_FOUND`, `SEQ_CONFLICT`, `TOO_LARGE`,
|
||||
* `MISSING_OBJECTS`), or `SHADE_NETWORK` when the response carried none.
|
||||
*
|
||||
* Kept apart from [VaultFormatException] because the reactions differ: a
|
||||
* relay refusal may be retried or shown as "offline / rejected", while a
|
||||
* format failure means the bytes themselves are wrong and retrying is futile.
|
||||
*/
|
||||
class VaultException(
|
||||
val code: String,
|
||||
/** HTTP status, or 0 when the failure is local (e.g. a missing version). */
|
||||
val statusCode: Int,
|
||||
message: String,
|
||||
/** The relay's head, sent along with `SEQ_CONFLICT`. */
|
||||
val head: Long? = null,
|
||||
/** Up to 20 hashes the relay reported missing with `MISSING_OBJECTS`. */
|
||||
val missing: List<String> = emptyList(),
|
||||
cause: Throwable? = null,
|
||||
) : RuntimeException("[$code @ $statusCode] $message", cause) {
|
||||
|
||||
/**
|
||||
* Two devices committed from the same head and this one lost. The answer
|
||||
* is to re-read the head and rebuild the edit on top of it — never to
|
||||
* resend the same commit, which would just lose again.
|
||||
*/
|
||||
val isSeqConflict: Boolean get() = code == CODE_SEQ_CONFLICT
|
||||
|
||||
companion object {
|
||||
const val CODE_SEQ_CONFLICT = "SEQ_CONFLICT"
|
||||
const val CODE_NOT_FOUND = "NOT_FOUND"
|
||||
const val CODE_MISSING_OBJECTS = "MISSING_OBJECTS"
|
||||
const val CODE_NETWORK = "SHADE_NETWORK"
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Bytes that do not decode to what the vault format promises: a hash
|
||||
* mismatch, a failed AEAD tag, corrupt or oversized deflate, an unknown
|
||||
* manifest version or entry encoding, a size that does not add up.
|
||||
*/
|
||||
class VaultFormatException(message: String, cause: Throwable? = null) : RuntimeException(message, cause)
|
||||
@@ -0,0 +1,80 @@
|
||||
package no.zyon.shade.vault
|
||||
|
||||
import no.zyon.shade.blob.ed25519PublicKeyFromSeed
|
||||
import no.zyon.shade.crypto.CryptoProvider
|
||||
|
||||
/**
|
||||
* Everything a vault needs, derived from the account master key.
|
||||
*
|
||||
* Mirror of `@shade/vault`'s `VaultKeys` / `deriveVaultKeys`, and of the three
|
||||
* `deriveVault*` functions in `@shade/storage-encrypted/crypto/kdf.ts`:
|
||||
*
|
||||
* vaultId = hex(HKDF(masterKey, info=`shade-vault-id-v1:<app>`)) // relay-visible opaque id
|
||||
* contentKey = HKDF(masterKey, info=`shade-vault-content-v1:<app>`) // AES-256-GCM key for every object
|
||||
* signingSeed = HKDF(masterKey, info=`shade-vault-sig-v1:<app>`) // Ed25519 seed, TOFU-pinned by the relay
|
||||
* publicKey = Ed25519 public key of signingSeed
|
||||
*
|
||||
* This is what makes recovery "username and password": a phone that can
|
||||
* derive the profile master can derive these too, and read a vault whose
|
||||
* writer — the PC — is switched off.
|
||||
*
|
||||
* Its own HKDF branch rather than a reuse of `shade-blob-*-v1`: whoever holds
|
||||
* a vault key reads every file, so it must not be derivable from the profile
|
||||
* blob's key or vice versa. Reference vectors: `test-vectors/vault-v2.json`
|
||||
* ("vault-v2 keys").
|
||||
*/
|
||||
class VaultKeys(
|
||||
/** Lowercase hex (64 chars) — the id in every relay URL. */
|
||||
val vaultId: String,
|
||||
val contentKey: ByteArray,
|
||||
val signingSeed: ByteArray,
|
||||
val publicKey: ByteArray,
|
||||
)
|
||||
|
||||
private const val VAULT_ID_INFO_PREFIX = "shade-vault-id-v1:"
|
||||
private const val VAULT_CONTENT_INFO_PREFIX = "shade-vault-content-v1:"
|
||||
private const val VAULT_SIG_INFO_PREFIX = "shade-vault-sig-v1:"
|
||||
|
||||
private const val DERIVED_LEN = 32
|
||||
|
||||
/**
|
||||
* Derive a vault's keys for namespace [app] (e.g. `"scaffold"`). Distinct
|
||||
* collections under one master MUST use distinct `app` strings — the phone's
|
||||
* outgoing change queue is a second vault with its own `app`, not a path
|
||||
* prefix inside the first, so the two never contend for one `seq`.
|
||||
*
|
||||
* No HKDF salt: the TS side passes `undefined`, which RFC 5869 (and
|
||||
* `@noble/hashes`) turn into 32 zero bytes — exactly what Tink does with an
|
||||
* empty salt. The vectors pin it.
|
||||
*/
|
||||
fun deriveVaultKeys(crypto: CryptoProvider, masterKey: ByteArray, app: String): VaultKeys {
|
||||
require(masterKey.size == 32) { "masterKey must be 32 bytes" }
|
||||
require(app.isNotEmpty()) { "app namespace must be non-empty" }
|
||||
fun derive(prefix: String): ByteArray =
|
||||
crypto.hkdf(masterKey, ByteArray(0), (prefix + app).toByteArray(Charsets.UTF_8), DERIVED_LEN)
|
||||
|
||||
val signingSeed = derive(VAULT_SIG_INFO_PREFIX)
|
||||
return VaultKeys(
|
||||
vaultId = toHex(derive(VAULT_ID_INFO_PREFIX)),
|
||||
contentKey = derive(VAULT_CONTENT_INFO_PREFIX),
|
||||
signingSeed = signingSeed,
|
||||
publicKey = ed25519PublicKeyFromSeed(signingSeed),
|
||||
)
|
||||
}
|
||||
|
||||
/** Lowercase hex — the encoding of vault ids and object names on the wire. */
|
||||
fun toHex(bytes: ByteArray): String {
|
||||
val out = CharArray(bytes.size * 2)
|
||||
val digits = "0123456789abcdef"
|
||||
for (i in bytes.indices) {
|
||||
val v = bytes[i].toInt() and 0xff
|
||||
out[i * 2] = digits[v ushr 4]
|
||||
out[i * 2 + 1] = digits[v and 0x0f]
|
||||
}
|
||||
return String(out)
|
||||
}
|
||||
|
||||
private val HEX64 = Regex("^[0-9a-f]{64}$")
|
||||
|
||||
/** True for a 64-char lowercase hex string — a vault id or an object name. */
|
||||
internal fun isHex64(s: String): Boolean = HEX64.matches(s)
|
||||
@@ -0,0 +1,183 @@
|
||||
package no.zyon.shade.vault
|
||||
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONException
|
||||
import org.json.JSONObject
|
||||
|
||||
/**
|
||||
* The vault's data model — mirror of `@shade/vault/src/types.ts`.
|
||||
*
|
||||
* Objects are content-addressed (named by the SHA-256 of their ciphertext), a
|
||||
* manifest names the collection (paths live only inside it, encrypted), and
|
||||
* the log is append-only. See `docs/vault.md` for why.
|
||||
*/
|
||||
|
||||
/** The only entry encoding v2 defines: RFC 1951 raw DEFLATE, no zlib/gzip header. */
|
||||
const val VAULT_ENC_DEFLATE_RAW = "deflate-raw"
|
||||
|
||||
/**
|
||||
* One file in a manifest.
|
||||
*
|
||||
* [enc] is kept as a raw string rather than an enum on purpose: a manifest
|
||||
* written by a newer client may name an encoding this one does not know, and
|
||||
* the right reaction is to refuse *reading that file* (see [openEntryBytes]),
|
||||
* not to refuse the whole manifest — every other file is still readable.
|
||||
*/
|
||||
data class VaultEntry(
|
||||
/** Path within the collection, as the app understands it. */
|
||||
val path: String,
|
||||
/** Lowercase hex SHA-256 of the (first) ciphertext object. */
|
||||
val hash: String,
|
||||
/** PLAINTEXT byte length — before compression, whatever [enc] says. */
|
||||
val size: Long,
|
||||
/** Optional app-defined mode/metadata, opaque to the vault. */
|
||||
val mode: String? = null,
|
||||
/** Present only when the stored bytes are compressed. */
|
||||
val enc: String? = null,
|
||||
/** Present only when there is more than one object; `parts[0] == hash`. */
|
||||
val parts: List<String>? = null,
|
||||
)
|
||||
|
||||
/** The full contents of a collection at one point in time. */
|
||||
data class VaultManifest(
|
||||
/** 1: bare JSON. 2: "SVM2" + deflate-raw(JSON). Writers emit 2; readers accept both. */
|
||||
val version: Int,
|
||||
/** Monotonic, assigned by the client and checked by the relay. */
|
||||
val seq: Long,
|
||||
/** Epoch millis when the commit was made. */
|
||||
val at: Long,
|
||||
/** Optional human note, e.g. "nattlig backup". */
|
||||
val message: String? = null,
|
||||
val entries: List<VaultEntry>,
|
||||
)
|
||||
|
||||
/** One row of the append-only log. */
|
||||
data class VaultLogEntry(
|
||||
val seq: Long,
|
||||
/** Hash of the encrypted manifest object. */
|
||||
val manifest: String,
|
||||
val at: Long,
|
||||
/** Total bytes of all objects the manifest references, for quota display. */
|
||||
val bytes: Long,
|
||||
)
|
||||
|
||||
/** What `GET /v1/vault/:id/log` returns. */
|
||||
data class VaultLog(
|
||||
val entries: List<VaultLogEntry>,
|
||||
/** Highest seq the relay holds; `0` when the vault is empty. */
|
||||
val head: Long,
|
||||
)
|
||||
|
||||
/** What `POST /v1/vault/:id/prune` returns. */
|
||||
data class VaultPruneResult(
|
||||
val removedVersions: Long,
|
||||
val removedObjects: Long,
|
||||
val freedBytes: Long,
|
||||
)
|
||||
|
||||
// ─── JSON ────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* The entry as an insertion-ordered map, in the order TS builds it
|
||||
* (`{ path, ...locator, size }`, then `mode`), so `JSON.stringify` on either
|
||||
* side yields the same bytes. Key order is not part of the contract — readers
|
||||
* never depend on it — but matching it keeps the manifest vector exact.
|
||||
* Absent optionals are left out, as `JSON.stringify` drops `undefined`.
|
||||
*/
|
||||
internal fun VaultEntry.toJsonMap(): Map<String, Any> {
|
||||
val m = LinkedHashMap<String, Any>()
|
||||
m["path"] = path
|
||||
m["hash"] = hash
|
||||
if (parts != null) m["parts"] = parts
|
||||
if (enc != null) m["enc"] = enc
|
||||
m["size"] = size
|
||||
if (mode != null) m["mode"] = mode
|
||||
return m
|
||||
}
|
||||
|
||||
internal fun VaultManifest.toJsonMap(): Map<String, Any> {
|
||||
val m = LinkedHashMap<String, Any>()
|
||||
m["version"] = version
|
||||
m["seq"] = seq
|
||||
m["at"] = at
|
||||
m["entries"] = entries.map { it.toJsonMap() }
|
||||
if (message != null) m["message"] = message
|
||||
return m
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a manifest's JSON. Malformed structure surfaces as
|
||||
* [VaultFormatException], never as a raw `JSONException` — a caller showing
|
||||
* "the backup could not be read" should not have to know which parser ran.
|
||||
*/
|
||||
internal fun parseManifestJson(text: String): VaultManifest {
|
||||
try {
|
||||
val o = JSONObject(text)
|
||||
// Strict like TS `version !== 1 && version !== 2`: "2" or 2.5 are refused.
|
||||
val version = when ((o.opt("version") as? Number)?.toDouble()) {
|
||||
1.0 -> 1
|
||||
2.0 -> 2
|
||||
else -> -1
|
||||
}
|
||||
if (version != 1 && version != 2) {
|
||||
// Refusing beats guessing: a future manifest may describe a file
|
||||
// this reader cannot represent, and committing on top of a
|
||||
// half-understood head would drop it.
|
||||
throw VaultFormatException(
|
||||
"unsupported vault manifest version: ${if (o.has("version")) o.get("version") else "undefined"}",
|
||||
)
|
||||
}
|
||||
val arr = o.getJSONArray("entries")
|
||||
val entries = ArrayList<VaultEntry>(arr.length())
|
||||
for (i in 0 until arr.length()) entries.add(parseEntryJson(arr.getJSONObject(i)))
|
||||
return VaultManifest(
|
||||
version = version,
|
||||
seq = o.getLong("seq"),
|
||||
at = o.getLong("at"),
|
||||
message = optString(o, "message"),
|
||||
entries = entries,
|
||||
)
|
||||
} catch (e: JSONException) {
|
||||
throw VaultFormatException("vault manifest is not valid JSON: ${e.message}", e)
|
||||
}
|
||||
}
|
||||
|
||||
private fun parseEntryJson(o: JSONObject): VaultEntry {
|
||||
val parts = if (o.has("parts") && !o.isNull("parts")) {
|
||||
val a = o.getJSONArray("parts")
|
||||
List(a.length()) { a.getString(it) }
|
||||
} else {
|
||||
null
|
||||
}
|
||||
return VaultEntry(
|
||||
path = o.getString("path"),
|
||||
hash = o.getString("hash"),
|
||||
size = o.getLong("size"),
|
||||
mode = optString(o, "mode"),
|
||||
enc = optString(o, "enc"),
|
||||
parts = parts,
|
||||
)
|
||||
}
|
||||
|
||||
/** `org.json`'s `optString` turns null into "null" and numbers into strings; this does not. */
|
||||
private fun optString(o: JSONObject, key: String): String? =
|
||||
if (o.has(key) && !o.isNull(key)) o.getString(key) else null
|
||||
|
||||
internal fun parseLogJson(text: String): VaultLog {
|
||||
try {
|
||||
val o = JSONObject(text)
|
||||
val arr: JSONArray = o.getJSONArray("entries")
|
||||
val entries = List(arr.length()) { i ->
|
||||
val e = arr.getJSONObject(i)
|
||||
VaultLogEntry(
|
||||
seq = e.getLong("seq"),
|
||||
manifest = e.getString("manifest"),
|
||||
at = e.getLong("at"),
|
||||
bytes = e.optLong("bytes", 0L),
|
||||
)
|
||||
}
|
||||
return VaultLog(entries = entries, head = o.getLong("head"))
|
||||
} catch (e: JSONException) {
|
||||
throw VaultFormatException("vault log response is malformed: ${e.message}", e)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package no.zyon.shade.vault
|
||||
|
||||
import no.zyon.shade.crypto.CryptoProvider
|
||||
import no.zyon.shade.serialization.canonicalJson
|
||||
import no.zyon.shade.serialization.stringifyJson
|
||||
import java.util.Base64
|
||||
|
||||
/**
|
||||
* A request body signed the way the relay verifies it.
|
||||
*
|
||||
* [canonical] is kept alongside the wire JSON so tests can compare it with
|
||||
* the TS bytes directly instead of reverse-engineering a failing signature.
|
||||
*/
|
||||
class SignedPayload(
|
||||
/** The JSON to send: the payload fields + `signedAt` + `signature`. */
|
||||
val json: String,
|
||||
/** The exact bytes the signature covers. */
|
||||
val canonical: ByteArray,
|
||||
val signedAt: Long,
|
||||
val signature: ByteArray,
|
||||
)
|
||||
|
||||
/**
|
||||
* Mirror of `@shade/server`'s `signPayload`: Ed25519 over `JSON.stringify` of
|
||||
* every field except `signature` (with `signedAt` added), top-level keys
|
||||
* sorted, nested values as-is; the wire body then carries `signedAt` and the
|
||||
* signature in standard base64.
|
||||
*
|
||||
* [signedAt] is a parameter so the vectors can pin it; the relay rejects a
|
||||
* value more than five minutes old or one minute in the future, so real
|
||||
* callers pass the current wall clock.
|
||||
*/
|
||||
fun signPayload(
|
||||
crypto: CryptoProvider,
|
||||
signingSeed: ByteArray,
|
||||
payload: Map<String, Any>,
|
||||
signedAt: Long,
|
||||
): SignedPayload {
|
||||
require(signingSeed.size == 32) { "signingSeed must be 32 bytes (Ed25519)" }
|
||||
require("signature" !in payload && "signedAt" !in payload) {
|
||||
"payload must not carry signature/signedAt — they are added here"
|
||||
}
|
||||
val withTime = LinkedHashMap(payload).apply { put("signedAt", signedAt) }
|
||||
val canonical = canonicalJson(withTime).toByteArray(Charsets.UTF_8)
|
||||
val signature = crypto.sign(signingSeed, canonical)
|
||||
val wire = LinkedHashMap<String, Any>(withTime).apply {
|
||||
put("signature", Base64.getEncoder().encodeToString(signature))
|
||||
}
|
||||
return SignedPayload(stringifyJson(wire), canonical, signedAt, signature)
|
||||
}
|
||||
|
||||
/**
|
||||
* Sign a vault request body with the vault's key, the pubkey INSIDE the
|
||||
* signed payload — appended afterwards it would not be covered, and could be
|
||||
* swapped in transit on the first (TOFU-pinning) write.
|
||||
*/
|
||||
fun signVaultBody(
|
||||
crypto: CryptoProvider,
|
||||
keys: VaultKeys,
|
||||
body: Map<String, Any>,
|
||||
signedAt: Long,
|
||||
): SignedPayload {
|
||||
val withKey = LinkedHashMap(body).apply {
|
||||
put("publicKey", Base64.getEncoder().encodeToString(keys.publicKey))
|
||||
}
|
||||
return signPayload(crypto, keys.signingSeed, withKey, signedAt)
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
package no.zyon.shade.vault
|
||||
|
||||
import org.json.JSONException
|
||||
import org.json.JSONObject
|
||||
import java.io.IOException
|
||||
import java.io.InputStream
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
|
||||
/**
|
||||
* How a [VaultClient] reaches the relay — mirror of `@shade/vault`'s
|
||||
* `VaultTransport`. Bodies arrive already signed (as JSON text): the
|
||||
* transport moves bytes and maps errors, it never holds a key.
|
||||
*
|
||||
* Blocking by design, like [no.zyon.shade.blob.BlobClient]: call it from a
|
||||
* background dispatcher (`Dispatchers.IO`), never from the main thread.
|
||||
*/
|
||||
interface VaultTransport {
|
||||
/** Does the relay already hold this object? */
|
||||
fun has(vaultId: String, hash: String): Boolean
|
||||
|
||||
fun put(vaultId: String, hash: String, signedBody: String)
|
||||
|
||||
/** The raw sealed object. */
|
||||
fun get(vaultId: String, hash: String): ByteArray
|
||||
|
||||
fun log(vaultId: String, limit: Int? = null): VaultLog
|
||||
|
||||
/** Returns the committed seq. Throws [VaultException] with `SEQ_CONFLICT` when beaten to it. */
|
||||
fun commit(vaultId: String, signedBody: String): Long
|
||||
|
||||
fun prune(vaultId: String, signedBody: String): VaultPruneResult
|
||||
}
|
||||
|
||||
/**
|
||||
* Plain HTTP against a relay running `createVaultRoutes`.
|
||||
*
|
||||
* Built on `HttpURLConnection` rather than `java.net.http.HttpClient` (which
|
||||
* [no.zyon.shade.blob.BlobClient] uses): `java.net.http` does not exist on
|
||||
* Android at any API level, and this client exists for a phone. OkHttp would
|
||||
* also work but would add a dependency to a library that has none for HTTP;
|
||||
* `HttpURLConnection` is on both the JVM (tests) and Android.
|
||||
*/
|
||||
class VaultHttpTransport(
|
||||
baseUrl: String,
|
||||
private val connectTimeoutMs: Int = 15_000,
|
||||
/** Generous: one object is up to 4 MiB, and phones sit on slow uplinks. */
|
||||
private val readTimeoutMs: Int = 60_000,
|
||||
) : VaultTransport {
|
||||
|
||||
private val base = baseUrl.trimEnd('/')
|
||||
|
||||
override fun has(vaultId: String, hash: String): Boolean {
|
||||
val res = request("HEAD", objectPath(vaultId, hash), null)
|
||||
return when (res.status) {
|
||||
200 -> true
|
||||
404 -> false
|
||||
else -> fail(res, "have-check")
|
||||
}
|
||||
}
|
||||
|
||||
override fun put(vaultId: String, hash: String, signedBody: String) {
|
||||
val res = request("PUT", objectPath(vaultId, hash), signedBody)
|
||||
if (res.status !in 200..299) fail(res, "upload")
|
||||
}
|
||||
|
||||
override fun get(vaultId: String, hash: String): ByteArray {
|
||||
val res = request("GET", objectPath(vaultId, hash), null)
|
||||
if (res.status !in 200..299) fail(res, "download")
|
||||
return res.body
|
||||
}
|
||||
|
||||
override fun log(vaultId: String, limit: Int?): VaultLog {
|
||||
val q = if (limit == null) "" else "?limit=$limit"
|
||||
val res = request("GET", "${vaultPath(vaultId)}/log$q", null)
|
||||
if (res.status !in 200..299) fail(res, "log")
|
||||
return parseLogJson(res.body.toString(Charsets.UTF_8))
|
||||
}
|
||||
|
||||
override fun commit(vaultId: String, signedBody: String): Long {
|
||||
val res = request("POST", "${vaultPath(vaultId)}/commit", signedBody)
|
||||
if (res.status !in 200..299) fail(res, "commit")
|
||||
return jsonBody(res, "commit").getLong("seq")
|
||||
}
|
||||
|
||||
override fun prune(vaultId: String, signedBody: String): VaultPruneResult {
|
||||
val res = request("POST", "${vaultPath(vaultId)}/prune", signedBody)
|
||||
if (res.status !in 200..299) fail(res, "prune")
|
||||
val o = jsonBody(res, "prune")
|
||||
return VaultPruneResult(
|
||||
removedVersions = o.getLong("removedVersions"),
|
||||
removedObjects = o.getLong("removedObjects"),
|
||||
freedBytes = o.getLong("freedBytes"),
|
||||
)
|
||||
}
|
||||
|
||||
// ─── Plumbing ────────────────────────────────────────────
|
||||
|
||||
private class Response(val status: Int, val body: ByteArray)
|
||||
|
||||
/** Ids are validated before they reach a URL, so nothing can smuggle a path. */
|
||||
private fun vaultPath(vaultId: String): String {
|
||||
require(isHex64(vaultId)) { "vaultId must be 64 lowercase hex chars" }
|
||||
return "/v1/vault/$vaultId"
|
||||
}
|
||||
|
||||
private fun objectPath(vaultId: String, hash: String): String {
|
||||
require(isHex64(hash)) { "object hash must be 64 lowercase hex chars" }
|
||||
return "${vaultPath(vaultId)}/object/$hash"
|
||||
}
|
||||
|
||||
private fun request(method: String, path: String, jsonBody: String?): Response {
|
||||
val conn = try {
|
||||
URL(base + path).openConnection() as HttpURLConnection
|
||||
} catch (e: IOException) {
|
||||
throw VaultException(VaultException.CODE_NETWORK, 0, "vault $method $path: ${e.message}", cause = e)
|
||||
}
|
||||
try {
|
||||
conn.requestMethod = method
|
||||
conn.connectTimeout = connectTimeoutMs
|
||||
conn.readTimeout = readTimeoutMs
|
||||
conn.useCaches = false
|
||||
if (jsonBody != null) {
|
||||
val bytes = jsonBody.toByteArray(Charsets.UTF_8)
|
||||
conn.doOutput = true
|
||||
conn.setRequestProperty("content-type", "application/json")
|
||||
conn.setFixedLengthStreamingMode(bytes.size)
|
||||
conn.outputStream.use { it.write(bytes) }
|
||||
}
|
||||
val status = conn.responseCode
|
||||
// A non-2xx body is on the error stream; HEAD has neither.
|
||||
val stream: InputStream? = if (status >= 400) conn.errorStream else if (method == "HEAD") null else conn.inputStream
|
||||
val body = stream?.use { it.readBytes() } ?: ByteArray(0)
|
||||
return Response(status, body)
|
||||
} catch (e: IOException) {
|
||||
throw VaultException(VaultException.CODE_NETWORK, 0, "vault $method $path: ${e.message}", cause = e)
|
||||
} finally {
|
||||
conn.disconnect()
|
||||
}
|
||||
}
|
||||
|
||||
private fun jsonBody(res: Response, what: String): JSONObject = try {
|
||||
JSONObject(res.body.toString(Charsets.UTF_8))
|
||||
} catch (e: JSONException) {
|
||||
throw VaultException(VaultException.CODE_NETWORK, res.status, "vault $what response not JSON", cause = e)
|
||||
}
|
||||
|
||||
/** Turn a non-2xx into a [VaultException] that carries the relay's own code. */
|
||||
private fun fail(res: Response, what: String): Nothing {
|
||||
var code = VaultException.CODE_NETWORK
|
||||
var detail = "HTTP ${res.status}"
|
||||
var head: Long? = null
|
||||
var missing = emptyList<String>()
|
||||
try {
|
||||
val o = JSONObject(res.body.toString(Charsets.UTF_8))
|
||||
o.optJSONObject("error")?.let { err ->
|
||||
code = err.optString("code", code)
|
||||
detail = err.optString("message", detail)
|
||||
}
|
||||
if (o.has("head") && !o.isNull("head")) head = o.getLong("head")
|
||||
o.optJSONArray("missing")?.let { a -> missing = List(a.length()) { a.getString(it) } }
|
||||
} catch (_: JSONException) {
|
||||
// Non-JSON error body (a proxy's HTML page): the status is all we have.
|
||||
}
|
||||
throw VaultException(code, res.status, "vault $what failed — $detail", head = head, missing = missing)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
package no.zyon.shade
|
||||
|
||||
import com.sun.net.httpserver.HttpServer
|
||||
import no.zyon.shade.crypto.CryptoProvider
|
||||
import no.zyon.shade.crypto.TinkProvider
|
||||
import no.zyon.shade.serialization.canonicalJson
|
||||
import no.zyon.shade.vault.VaultClient
|
||||
import no.zyon.shade.vault.VaultEdit
|
||||
import no.zyon.shade.vault.VaultException
|
||||
import no.zyon.shade.vault.VaultFile
|
||||
import no.zyon.shade.vault.VaultFormatException
|
||||
import no.zyon.shade.vault.VaultHttpTransport
|
||||
import no.zyon.shade.vault.VaultKeys
|
||||
import no.zyon.shade.vault.VaultLog
|
||||
import no.zyon.shade.vault.VaultLogEntry
|
||||
import no.zyon.shade.vault.VaultManifest
|
||||
import no.zyon.shade.vault.VaultPruneResult
|
||||
import no.zyon.shade.vault.VaultTransport
|
||||
import no.zyon.shade.vault.deriveVaultKeys
|
||||
import no.zyon.shade.vault.entryObjectHashes
|
||||
import no.zyon.shade.vault.objectHash
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import java.net.InetSocketAddress
|
||||
import java.util.Base64
|
||||
|
||||
/**
|
||||
* [VaultClient.edit] and friends against an in-memory relay that enforces
|
||||
* what the real routes enforce: hash-checked uploads, TOFU Ed25519 over the
|
||||
* canonical body, `seq == head + 1`, and every referenced object present.
|
||||
* A signature or hash the TS relay would refuse fails here too.
|
||||
*/
|
||||
class VaultClientTest {
|
||||
|
||||
private val crypto = TinkProvider()
|
||||
private val master = ByteArray(32) { (it * 7 + 3).toByte() }
|
||||
private val keys = deriveVaultKeys(crypto, master, "prism-queue-test")
|
||||
private val at = 1_786_600_000_000L
|
||||
|
||||
/** The relay, minus HTTP. */
|
||||
private class MemoryRelay(private val crypto: CryptoProvider) : VaultTransport {
|
||||
val objects = HashMap<String, ByteArray>()
|
||||
val log = ArrayList<VaultLogEntry>()
|
||||
val committedHashes = HashMap<Long, List<String>>()
|
||||
var pinned: ByteArray? = null
|
||||
var puts = 0
|
||||
/** Runs just before a commit is checked — the "other device" hook. */
|
||||
var beforeCommit: (() -> Unit)? = null
|
||||
|
||||
private fun authorize(body: JSONObject) {
|
||||
val sig = Base64.getDecoder().decode(body.getString("signature"))
|
||||
val fields = LinkedHashMap<String, Any>()
|
||||
for (k in body.keys()) if (k != "signature") fields[k] = plain(body.get(k))
|
||||
val canonical = canonicalJson(fields).toByteArray()
|
||||
val key = pinned ?: Base64.getDecoder().decode(body.getString("publicKey")).also { pinned = it }
|
||||
if (!crypto.verify(key, canonical, sig)) throw VaultException("UNAUTHORIZED", 401, "bad signature")
|
||||
}
|
||||
|
||||
private fun plain(v: Any): Any = when (v) {
|
||||
is JSONArray -> List(v.length()) { plain(v.get(it)) }
|
||||
is Int -> v.toLong()
|
||||
else -> v
|
||||
}
|
||||
|
||||
private fun head() = log.lastOrNull()?.seq ?: 0L
|
||||
|
||||
override fun has(vaultId: String, hash: String) = hash in objects
|
||||
|
||||
override fun put(vaultId: String, hash: String, signedBody: String) {
|
||||
val body = JSONObject(signedBody)
|
||||
authorize(body)
|
||||
val data = Base64.getDecoder().decode(body.getString("data"))
|
||||
if (objectHash(data) != hash) throw VaultException("BAD_REQUEST", 400, "hash mismatch")
|
||||
objects[hash] = data
|
||||
puts++
|
||||
}
|
||||
|
||||
override fun get(vaultId: String, hash: String) =
|
||||
objects[hash] ?: throw VaultException("NOT_FOUND", 404, "no such object")
|
||||
|
||||
override fun log(vaultId: String, limit: Int?) =
|
||||
VaultLog(if (limit == null) log.toList() else log.takeLast(limit), head())
|
||||
|
||||
override fun commit(vaultId: String, signedBody: String): Long {
|
||||
beforeCommit?.let { beforeCommit = null; it() }
|
||||
val body = JSONObject(signedBody)
|
||||
authorize(body)
|
||||
val seq = body.getLong("seq")
|
||||
if (seq != head() + 1) throw VaultException("SEQ_CONFLICT", 409, "expected seq ${head() + 1}, got $seq", head = head())
|
||||
val hashes = List(body.getJSONArray("hashes").length()) { body.getJSONArray("hashes").getString(it) }
|
||||
val manifest = body.getString("manifest")
|
||||
if (manifest !in objects || hashes.any { it !in objects }) throw VaultException("MISSING_OBJECTS", 409, "missing")
|
||||
log.add(VaultLogEntry(seq, manifest, body.getLong("at"), 0))
|
||||
committedHashes[seq] = hashes
|
||||
return seq
|
||||
}
|
||||
|
||||
override fun prune(vaultId: String, signedBody: String) = VaultPruneResult(0, 0, 0)
|
||||
}
|
||||
|
||||
private fun text(s: String) = s.toByteArray()
|
||||
|
||||
@Test
|
||||
fun emptyVaultAndNoOpEditsCommitNothing() {
|
||||
val relay = MemoryRelay(crypto)
|
||||
val client = VaultClient(crypto, keys, relay)
|
||||
assertNull(client.headManifest())
|
||||
assertThrows(VaultException::class.java) { client.manifest() }
|
||||
|
||||
var seen: VaultManifest? = VaultManifest(2, 99, 0, null, emptyList())
|
||||
assertEquals(0L, client.edit(at) { seen = it; null }.seq)
|
||||
assertNull(seen)
|
||||
val noop = client.edit(at) { VaultEdit(remove = listOf("not-there")) }
|
||||
assertFalse(noop.committed)
|
||||
assertEquals(0, relay.puts)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun appendThenEditKeepsUntouchedEntriesByteForByte() {
|
||||
val relay = MemoryRelay(crypto)
|
||||
val client = VaultClient(crypto, keys, relay, chunkSize = 64)
|
||||
val big = ByteArray(1000).also { java.util.Random(1).nextBytes(it) } // 16 parts, incompressible
|
||||
val note = text("# Plan\n" + "- [ ] gjør noe\n".repeat(40))
|
||||
val r1 = client.append(
|
||||
listOf(VaultFile("big.bin", big), VaultFile("plan.md", note, mode = "644"), VaultFile("empty", ByteArray(0))),
|
||||
at,
|
||||
)
|
||||
assertEquals(1L, r1.seq)
|
||||
assertTrue(r1.committed)
|
||||
|
||||
val m1 = client.manifest()
|
||||
assertEquals(2, m1.version)
|
||||
val bigEntry = m1.entries.single { it.path == "big.bin" }
|
||||
assertEquals(16, bigEntry.parts!!.size)
|
||||
assertEquals(bigEntry.parts!![0], bigEntry.hash)
|
||||
assertNull(bigEntry.enc)
|
||||
val planEntry = m1.entries.single { it.path == "plan.md" }
|
||||
assertEquals("deflate-raw", planEntry.enc)
|
||||
assertEquals("644", planEntry.mode)
|
||||
assertArrayEquals(big, client.readEntry(bigEntry))
|
||||
assertArrayEquals(note, client.readEntry(planEntry))
|
||||
assertArrayEquals(ByteArray(0), client.readEntry(m1.entries.single { it.path == "empty" }))
|
||||
// Commit lists every part of every entry.
|
||||
assertEquals(m1.entries.flatMap { entryObjectHashes(it) }.toSet(), relay.committedHashes[1L]!!.toSet())
|
||||
|
||||
val putsBefore = relay.puts
|
||||
val r2 = client.edit(at + 1) { head ->
|
||||
assertEquals(1L, head!!.seq)
|
||||
VaultEdit(put = listOf(VaultFile("queue/001.json", text("""{"op":"check"}"""))), remove = listOf("empty"))
|
||||
}
|
||||
assertEquals(2L, r2.seq)
|
||||
assertEquals(2, relay.puts - putsBefore) // one new object + the manifest; nothing re-sealed
|
||||
|
||||
val m2 = client.manifest()
|
||||
assertEquals(listOf("big.bin", "plan.md", "queue/001.json"), m2.entries.map { it.path })
|
||||
assertEquals(bigEntry, m2.entries[0])
|
||||
assertEquals(planEntry, m2.entries[1])
|
||||
assertEquals(m2.entries.flatMap { entryObjectHashes(it) }.toSet(), relay.committedHashes[2L]!!.toSet())
|
||||
|
||||
// Old versions stay readable; pull decrypts everything.
|
||||
assertEquals(3, client.manifest(1).entries.size)
|
||||
val pulled = client.pull()
|
||||
assertArrayEquals(text("""{"op":"check"}"""), pulled.files["queue/001.json"])
|
||||
assertEquals(2L, client.log().head)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun seqConflictRereadsTheHeadAndRetries() {
|
||||
val relay = MemoryRelay(crypto)
|
||||
val phone = VaultClient(crypto, keys, relay)
|
||||
val pc = VaultClient(crypto, keys, relay)
|
||||
phone.append(listOf(VaultFile("a.txt", text("a"))), at)
|
||||
|
||||
// The PC drains the queue between the phone's read and its commit.
|
||||
relay.beforeCommit = { pc.edit(at) { VaultEdit(remove = listOf("a.txt"), put = listOf(VaultFile("pc.txt", text("pc")))) } }
|
||||
|
||||
val heads = ArrayList<Long?>()
|
||||
val putsBefore = relay.puts
|
||||
val r = phone.edit(at + 5) { head ->
|
||||
heads.add(head?.seq)
|
||||
VaultEdit(put = listOf(VaultFile("b.txt", text("b"))))
|
||||
}
|
||||
assertEquals(listOf<Long?>(1L, 2L), heads) // change() saw the new head on the retry
|
||||
assertEquals(3L, r.seq)
|
||||
assertTrue(r.committed)
|
||||
val m = phone.manifest()
|
||||
assertEquals(setOf("pc.txt", "b.txt"), m.entries.map { it.path }.toSet()) // the PC's edit survived
|
||||
assertArrayEquals(text("b"), phone.readEntry(m.entries.single { it.path == "b.txt" }))
|
||||
// Phone: b.txt sealed once + two manifests. PC: pc.txt + its manifest.
|
||||
assertEquals(5, relay.puts - putsBefore)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givesUpAfterMaxAttemptsAndPassesOtherErrorsThrough() {
|
||||
val relay = MemoryRelay(crypto)
|
||||
val client = VaultClient(crypto, keys, relay)
|
||||
val other = VaultClient(crypto, keys, relay)
|
||||
var calls = 0
|
||||
val loseEveryRace = object : VaultTransport by relay {
|
||||
override fun commit(vaultId: String, signedBody: String): Long {
|
||||
other.append(listOf(VaultFile("x${calls++}", text("x"))), at)
|
||||
return relay.commit(vaultId, signedBody)
|
||||
}
|
||||
}
|
||||
val e = assertThrows(VaultException::class.java) {
|
||||
VaultClient(crypto, keys, loseEveryRace).edit(at, maxAttempts = 3) { VaultEdit(put = listOf(VaultFile("p", text("p")))) }
|
||||
}
|
||||
assertTrue(e.isSeqConflict)
|
||||
assertEquals(3, calls)
|
||||
|
||||
val refusing = object : VaultTransport by relay {
|
||||
override fun commit(vaultId: String, signedBody: String): Long =
|
||||
throw VaultException("MISSING_OBJECTS", 409, "missing")
|
||||
}
|
||||
var attempts = 0
|
||||
val e2 = assertThrows(VaultException::class.java) {
|
||||
VaultClient(crypto, keys, refusing).edit(at) { attempts++; VaultEdit(put = listOf(VaultFile("q", text("q")))) }
|
||||
}
|
||||
assertEquals("MISSING_OBJECTS", e2.code)
|
||||
assertEquals(1, attempts)
|
||||
assertTrue(client.headManifest() != null)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun refusesToEditOnTopOfAnUnreadableHead() {
|
||||
val relay = MemoryRelay(crypto)
|
||||
VaultClient(crypto, keys, relay).append(listOf(VaultFile("a", text("a"))), at)
|
||||
val wrongKey = VaultKeys(keys.vaultId, ByteArray(32) { 9 }, keys.signingSeed, keys.publicKey)
|
||||
assertThrows(VaultFormatException::class.java) {
|
||||
VaultClient(crypto, wrongKey, relay).edit(at) { VaultEdit(put = listOf(VaultFile("b", text("b")))) }
|
||||
}
|
||||
assertEquals(1L, relay.log.size.toLong())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun httpTransportMapsRelayErrors() {
|
||||
val server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0)
|
||||
server.createContext("/") { ex ->
|
||||
val path = ex.requestURI.path
|
||||
val (status, body) = when {
|
||||
path.endsWith("/commit") -> 409 to """{"error":{"code":"SEQ_CONFLICT","message":"expected seq 4, got 3"},"head":3}"""
|
||||
path.endsWith("/log") -> 200 to """{"entries":[{"seq":3,"manifest":"${"a".repeat(64)}","at":5,"bytes":10}],"head":3}"""
|
||||
ex.requestMethod == "HEAD" -> 404 to ""
|
||||
ex.requestMethod == "GET" -> 200 to "raw-bytes"
|
||||
else -> 502 to "<html>bad gateway</html>"
|
||||
}
|
||||
val bytes = body.toByteArray()
|
||||
ex.sendResponseHeaders(status, if (ex.requestMethod == "HEAD" || bytes.isEmpty()) -1 else bytes.size.toLong())
|
||||
if (bytes.isNotEmpty() && ex.requestMethod != "HEAD") ex.responseBody.use { it.write(bytes) }
|
||||
ex.close()
|
||||
}
|
||||
server.start()
|
||||
try {
|
||||
val t = VaultHttpTransport("http://127.0.0.1:${server.address.port}/")
|
||||
val id = keys.vaultId
|
||||
val hash = "b".repeat(64)
|
||||
assertEquals(3L, t.log(id, 1).head)
|
||||
assertEquals(10L, t.log(id).entries.single().bytes)
|
||||
assertFalse(t.has(id, hash))
|
||||
assertArrayEquals("raw-bytes".toByteArray(), t.get(id, hash))
|
||||
val e = assertThrows(VaultException::class.java) { t.commit(id, "{}") }
|
||||
assertTrue(e.isSeqConflict)
|
||||
assertEquals(409, e.statusCode)
|
||||
assertEquals(3L, e.head)
|
||||
val e2 = assertThrows(VaultException::class.java) { t.put(id, hash, "{}") }
|
||||
assertEquals(VaultException.CODE_NETWORK, e2.code)
|
||||
assertEquals(502, e2.statusCode)
|
||||
assertThrows(IllegalArgumentException::class.java) { t.get(id, "../../etc/passwd") }
|
||||
} finally {
|
||||
server.stop(0)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package no.zyon.shade
|
||||
|
||||
import no.zyon.shade.crypto.TinkProvider
|
||||
import no.zyon.shade.vault.VaultClient
|
||||
import no.zyon.shade.vault.VaultEdit
|
||||
import no.zyon.shade.vault.VaultFile
|
||||
import no.zyon.shade.vault.VaultHttpTransport
|
||||
import no.zyon.shade.vault.deriveVaultKeys
|
||||
import no.zyon.shade.vault.toHex
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Assume.assumeTrue
|
||||
import org.junit.Test
|
||||
import java.io.File
|
||||
import java.security.MessageDigest
|
||||
|
||||
/**
|
||||
* Live cross-check against the real TS vault routes — skipped unless
|
||||
* `SHADE_VAULT_LIVE_SPEC` points at the spec file a TS driver wrote.
|
||||
*
|
||||
* Run it via `bun run scripts/vault-live-kotlin.ts`: the driver serves `createVaultRoutes`
|
||||
* on a local port, pushes files with the TS client and writes
|
||||
* `{ url, masterKey, app, files: {path: sha256}, kotlinOut }`. This test reads
|
||||
* every file back, then edits the vault from Kotlin and records what it wrote
|
||||
* in `kotlinOut`; the driver then reads that back with the TS client.
|
||||
*/
|
||||
class VaultLiveTest {
|
||||
|
||||
private fun sha256(b: ByteArray) = toHex(MessageDigest.getInstance("SHA-256").digest(b))
|
||||
|
||||
private fun fromHex(s: String) =
|
||||
ByteArray(s.length / 2) { ((Character.digit(s[it * 2], 16) shl 4) + Character.digit(s[it * 2 + 1], 16)).toByte() }
|
||||
|
||||
@Test
|
||||
fun readsTsWritesAndAppendsForTs() {
|
||||
val specPath = System.getenv("SHADE_VAULT_LIVE_SPEC")
|
||||
assumeTrue("SHADE_VAULT_LIVE_SPEC not set — live cross-check skipped", !specPath.isNullOrEmpty())
|
||||
val spec = JSONObject(File(specPath!!).readText())
|
||||
val crypto = TinkProvider()
|
||||
val keys = deriveVaultKeys(crypto, fromHex(spec.getString("masterKey")), spec.getString("app"))
|
||||
val client = VaultClient(crypto, keys, VaultHttpTransport(spec.getString("url")))
|
||||
|
||||
// Read what TS pushed.
|
||||
val head = client.manifest()
|
||||
val want = spec.getJSONObject("files")
|
||||
assertEquals(want.keySet(), head.entries.map { it.path }.toSet())
|
||||
for (entry in head.entries) {
|
||||
assertEquals(entry.path, want.getString(entry.path), sha256(client.readEntry(entry)))
|
||||
}
|
||||
assertTrue("TS pushed a multi-part file", head.entries.any { (it.parts?.size ?: 0) > 1 })
|
||||
assertTrue("TS pushed a compressed file", head.entries.any { it.enc == "deflate-raw" })
|
||||
|
||||
// Append from Kotlin: a compressible note, a 2-part binary, a removal.
|
||||
val note = ("# Fra telefonen\n" + "- [x] lest workspace mens PC-en var av\n".repeat(200)).toByteArray()
|
||||
val big = ByteArray(5 * 1024 * 1024).also { java.util.Random(42).nextBytes(it) }
|
||||
val result = client.edit(System.currentTimeMillis()) { h ->
|
||||
assertEquals(head.seq, h!!.seq)
|
||||
VaultEdit(
|
||||
put = listOf(VaultFile("from-kotlin/note.md", note, mode = "644"), VaultFile("from-kotlin/big.bin", big)),
|
||||
remove = listOf("hello.txt"),
|
||||
)
|
||||
}
|
||||
assertTrue(result.committed)
|
||||
assertEquals(head.seq + 1, result.seq)
|
||||
|
||||
val out = JSONObject()
|
||||
.put("seq", result.seq)
|
||||
.put("removed", "hello.txt")
|
||||
.put("files", JSONObject().put("from-kotlin/note.md", sha256(note)).put("from-kotlin/big.bin", sha256(big)))
|
||||
File(spec.getString("kotlinOut")).writeText(out.toString())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,333 @@
|
||||
package no.zyon.shade
|
||||
|
||||
import no.zyon.shade.crypto.TinkProvider
|
||||
import no.zyon.shade.vault.VAULT_CHUNK_SIZE
|
||||
import no.zyon.shade.vault.VaultEntry
|
||||
import no.zyon.shade.vault.VaultFormatException
|
||||
import no.zyon.shade.vault.VaultKeys
|
||||
import no.zyon.shade.vault.VaultManifest
|
||||
import no.zyon.shade.vault.decodeManifest
|
||||
import no.zyon.shade.vault.deflateRaw
|
||||
import no.zyon.shade.vault.deriveVaultKeys
|
||||
import no.zyon.shade.vault.encodeManifest
|
||||
import no.zyon.shade.vault.entryLocator
|
||||
import no.zyon.shade.vault.entryObjectHashes
|
||||
import no.zyon.shade.vault.inflateRaw
|
||||
import no.zyon.shade.vault.looksCompressed
|
||||
import no.zyon.shade.vault.openEntryBytes
|
||||
import no.zyon.shade.vault.openManifest
|
||||
import no.zyon.shade.vault.openObject
|
||||
import no.zyon.shade.vault.packEntry
|
||||
import no.zyon.shade.vault.sealObject
|
||||
import no.zyon.shade.vault.sealObjectWithNonce
|
||||
import no.zyon.shade.vault.signPayload
|
||||
import no.zyon.shade.vault.signVaultBody
|
||||
import no.zyon.shade.vault.toHex
|
||||
import no.zyon.shade.vault.vaultObjectAad
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import java.io.File
|
||||
import java.util.Base64
|
||||
|
||||
/**
|
||||
* `@shade/vault` v2 against `test-vectors/vault-v2.json` — the cross-language
|
||||
* contract in `docs/vault.md`. Every byte a reader or signer depends on is
|
||||
* compared exactly; generated by `scripts/generate-vectors.ts vault-v2.json`.
|
||||
*/
|
||||
class VaultVectorTest {
|
||||
|
||||
private val crypto = TinkProvider()
|
||||
private val vectors: JSONArray = run {
|
||||
val obj = JSONObject(File("../../test-vectors/vault-v2.json").readText())
|
||||
assertEquals("vault-v2.json schema version", 2, obj.getInt("version"))
|
||||
obj.getJSONArray("vectors")
|
||||
}
|
||||
|
||||
private fun byPrefix(prefix: String): List<JSONObject> =
|
||||
(0 until vectors.length()).map { vectors.getJSONObject(it) }
|
||||
.filter { it.getString("description").startsWith(prefix) }
|
||||
.also { assertTrue("no vectors for '$prefix'", it.isNotEmpty()) }
|
||||
|
||||
private fun fromHex(s: String): ByteArray =
|
||||
ByteArray(s.length / 2) { ((Character.digit(s[it * 2], 16) shl 4) + Character.digit(s[it * 2 + 1], 16)).toByte() }
|
||||
|
||||
private val keyVector = byPrefix("vault-v2 keys").single()
|
||||
private val keys: VaultKeys = deriveVaultKeys(crypto, fromHex(keyVector.getString("masterKey")), keyVector.getString("app"))
|
||||
|
||||
private fun entryFrom(o: JSONObject): VaultEntry = VaultEntry(
|
||||
path = o.getString("path"),
|
||||
hash = o.getString("hash"),
|
||||
size = o.getLong("size"),
|
||||
mode = if (o.has("mode")) o.getString("mode") else null,
|
||||
enc = if (o.has("enc") && !o.isNull("enc")) o.getString("enc") else null,
|
||||
parts = o.optJSONArray("parts")?.let { a -> List(a.length()) { a.getString(it) } },
|
||||
)
|
||||
|
||||
private fun manifestFrom(o: JSONObject): VaultManifest {
|
||||
val a = o.getJSONArray("entries")
|
||||
return VaultManifest(
|
||||
version = o.getInt("version"),
|
||||
seq = o.getLong("seq"),
|
||||
at = o.getLong("at"),
|
||||
message = if (o.has("message")) o.getString("message") else null,
|
||||
entries = List(a.length()) { entryFrom(a.getJSONObject(it)) },
|
||||
)
|
||||
}
|
||||
|
||||
/** Vector JSON → plain Kotlin values, keeping key order (org.json does not, but only top-level is sorted anyway). */
|
||||
private fun toKotlin(v: Any?): Any = when (v) {
|
||||
is JSONObject -> LinkedHashMap<String, Any>().apply { for (k in v.keys()) put(k, toKotlin(v.get(k))) }
|
||||
is JSONArray -> List(v.length()) { toKotlin(v.get(it)) }
|
||||
is Int -> v.toLong()
|
||||
is Long, is String, is Boolean -> v
|
||||
else -> error("unexpected vector value ${v?.javaClass}")
|
||||
}
|
||||
|
||||
// ─── Keys ────────────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
fun keysMatchVector() {
|
||||
assertEquals(keyVector.getString("vaultId"), keys.vaultId)
|
||||
assertEquals(keyVector.getString("contentKey"), toHex(keys.contentKey))
|
||||
assertEquals(keyVector.getString("signingSeed"), toHex(keys.signingSeed))
|
||||
assertEquals(keyVector.getString("publicKey"), toHex(keys.publicKey))
|
||||
assertEquals(keyVector.getString("objectAad"), toHex(vaultObjectAad(keys.vaultId)))
|
||||
assertEquals(keyVector.getString("objectAadUtf8"), String(vaultObjectAad(keys.vaultId), Charsets.UTF_8))
|
||||
}
|
||||
|
||||
// ─── Entries ─────────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
fun entryPackingMatchesVectors() {
|
||||
for (v in byPrefix("vault-v2 entry")) {
|
||||
val what = v.getString("description")
|
||||
val plaintext = fromHex(v.getString("plaintext"))
|
||||
val chunkSize = v.getInt("chunkSize")
|
||||
val packed = packEntry(plaintext, chunkSize)
|
||||
val wantEnc = if (v.isNull("enc")) null else v.getString("enc")
|
||||
assertEquals("$what: enc", wantEnc, packed.enc)
|
||||
// Compressed bytes need not match zlib-for-zlib (readers never
|
||||
// depend on them; the JDK's zlib and Bun's diverge on longer
|
||||
// inputs) — but ours must inflate back, and the vector's must too.
|
||||
if (packed.enc != null) {
|
||||
assertArrayEquals("$what: own stored inflates", plaintext, inflateRaw(packed.stored, plaintext.size.toLong()))
|
||||
assertArrayEquals("$what: vector stored inflates", plaintext, inflateRaw(fromHex(v.getString("stored")), plaintext.size.toLong()))
|
||||
} else {
|
||||
assertEquals("$what: stored", v.getString("stored"), toHex(packed.stored))
|
||||
}
|
||||
|
||||
// Splitting and sealing are exact: chunk the vector's stored bytes
|
||||
// the way packEntry does and seal each slice under the pinned nonce.
|
||||
val stored = fromHex(v.getString("stored"))
|
||||
val chunks = stored.toList().chunked(chunkSize).map { it.toByteArray() }.ifEmpty { listOf(ByteArray(0)) }
|
||||
val parts = v.getJSONArray("parts")
|
||||
assertEquals("$what: part count", parts.length(), chunks.size)
|
||||
val sealed = (0 until parts.length()).map { i ->
|
||||
val p = parts.getJSONObject(i)
|
||||
assertEquals("$what: part $i plaintext", p.getString("plaintext"), toHex(chunks[i]))
|
||||
val obj = sealObjectWithNonce(keys.contentKey, keys.vaultId, chunks[i], fromHex(p.getString("nonce")))
|
||||
assertEquals("$what: part $i wire", p.getString("wire"), toHex(obj.bytes))
|
||||
assertEquals("$what: part $i hash", p.getString("hash"), obj.hash)
|
||||
obj
|
||||
}
|
||||
val vectorPacked = no.zyon.shade.vault.PackedEntry(wantEnc, stored, chunks)
|
||||
|
||||
val want = entryFrom(v.getJSONObject("entry"))
|
||||
val loc = entryLocator(vectorPacked, sealed)
|
||||
assertEquals("$what: hash", want.hash, loc.hash)
|
||||
assertEquals("$what: parts", want.parts, loc.parts)
|
||||
assertEquals("$what: locator enc", want.enc, loc.enc)
|
||||
assertEquals("$what: object hashes", sealed.map { it.hash }, entryObjectHashes(want))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun entryReadsBackFromWire() {
|
||||
for (v in byPrefix("vault-v2 entry")) {
|
||||
val entry = entryFrom(v.getJSONObject("entry"))
|
||||
val parts = v.getJSONArray("parts")
|
||||
val wires = List(parts.length()) { fromHex(parts.getJSONObject(it).getString("wire")) }
|
||||
val plain = openEntryBytes(crypto, keys.contentKey, keys.vaultId, entry, wires)
|
||||
assertEquals(v.getString("description"), v.getString("plaintext"), toHex(plain))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun entryReadRefusesWhatDoesNotAddUp() {
|
||||
val v = byPrefix("vault-v2 entry: multi-part").single()
|
||||
val entry = entryFrom(v.getJSONObject("entry"))
|
||||
val parts = v.getJSONArray("parts")
|
||||
val wires = List(parts.length()) { fromHex(parts.getJSONObject(it).getString("wire")) }
|
||||
|
||||
// Parts swapped: each fetched object must hash to its slot.
|
||||
assertThrows(VaultFormatException::class.java) {
|
||||
openEntryBytes(crypto, keys.contentKey, keys.vaultId, entry, listOf(wires[1], wires[0]) + wires.drop(2))
|
||||
}
|
||||
// A part dropped from the list (consistently, so every hash checks out).
|
||||
val shorter = entry.copy(parts = entry.parts!!.dropLast(1))
|
||||
assertThrows(VaultFormatException::class.java) {
|
||||
openEntryBytes(crypto, keys.contentKey, keys.vaultId, shorter, wires.dropLast(1))
|
||||
}
|
||||
// Size lies.
|
||||
assertThrows(VaultFormatException::class.java) {
|
||||
openEntryBytes(crypto, keys.contentKey, keys.vaultId, entry.copy(size = entry.size + 1), wires)
|
||||
}
|
||||
// An encoding this reader does not know is refused, not guessed.
|
||||
assertThrows(VaultFormatException::class.java) {
|
||||
openEntryBytes(crypto, keys.contentKey, keys.vaultId, entry.copy(enc = "zstd"), wires)
|
||||
}
|
||||
// hash must equal parts[0].
|
||||
assertThrows(VaultFormatException::class.java) {
|
||||
openEntryBytes(crypto, keys.contentKey, keys.vaultId, entry.copy(hash = entry.parts!![1]), wires)
|
||||
}
|
||||
// A flipped ciphertext bit no longer matches its name.
|
||||
val tampered = wires[0].copyOf().also { it[20] = (it[20].toInt() xor 1).toByte() }
|
||||
assertThrows(VaultFormatException::class.java) {
|
||||
openObject(crypto, keys.contentKey, keys.vaultId, entry.parts!![0], tampered)
|
||||
}
|
||||
// Right name, wrong vault: the AAD binds the vaultId.
|
||||
assertThrows(VaultFormatException::class.java) {
|
||||
openObject(crypto, keys.contentKey, "0".repeat(64), entry.parts!![0], wires[0])
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Manifests ───────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
fun manifestsDecodeFromWire() {
|
||||
for (prefix in listOf("vault-v2 manifest v2", "vault-v2 manifest v1")) {
|
||||
val v = byPrefix(prefix).single()
|
||||
val want = manifestFrom(v.getJSONObject("manifest"))
|
||||
val got = openManifest(crypto, keys.contentKey, keys.vaultId, v.getString("hash"), fromHex(v.getString("wire")))
|
||||
assertEquals(prefix, want, got)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun manifestsEncodeLikeTypeScript() {
|
||||
for (prefix in listOf("vault-v2 manifest v2", "vault-v2 manifest v1")) {
|
||||
val v = byPrefix(prefix).single()
|
||||
val m = manifestFrom(v.getJSONObject("manifest"))
|
||||
val plain = encodeManifest(m)
|
||||
// Key order is not contract, but writing it in TS order makes the
|
||||
// JSON identical; v1 is that JSON, so its whole plaintext matches.
|
||||
val ownJson = if (m.version == 2) String(inflateRaw(plain.copyOfRange(4, plain.size), 1L shl 20)) else String(plain)
|
||||
assertEquals("$prefix: json", v.getString("json"), ownJson)
|
||||
assertArrayEquals("$prefix: magic", if (m.version == 2) "SVM2".toByteArray() else "{\"v".toByteArray(), plain.copyOf(if (m.version == 2) 4 else 3))
|
||||
if (m.version == 1) assertEquals("$prefix: plaintext", v.getString("plaintext"), toHex(plain))
|
||||
val sealed = sealObjectWithNonce(keys.contentKey, keys.vaultId, fromHex(v.getString("plaintext")), fromHex(v.getString("nonce")))
|
||||
assertEquals("$prefix: wire", v.getString("wire"), toHex(sealed.bytes))
|
||||
assertEquals("$prefix: hash", v.getString("hash"), sealed.hash)
|
||||
assertEquals("$prefix: round trip", m, decodeManifest(plain))
|
||||
}
|
||||
val v2 = byPrefix("vault-v2 manifest v2").single()
|
||||
val json = String(inflateRaw(fromHex(v2.getString("plaintext")).copyOfRange(4, fromHex(v2.getString("plaintext")).size), 1 shl 20))
|
||||
assertEquals(v2.getString("json"), json)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun manifestRefusesUnknownVersion() {
|
||||
for (bad in listOf("""{"version":3,"seq":1,"at":1,"entries":[]}""", """{"version":"2","seq":1,"at":1,"entries":[]}""", """{"seq":1,"at":1,"entries":[]}""")) {
|
||||
assertThrows(bad, VaultFormatException::class.java) { decodeManifest(bad.toByteArray()) }
|
||||
}
|
||||
val v3 = byteArrayOf(0x53, 0x56, 0x4d, 0x32) + deflateRaw("""{"version":3,"seq":1,"at":1,"entries":[]}""".toByteArray())
|
||||
assertThrows(VaultFormatException::class.java) { decodeManifest(v3) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun freshSealOpensAndRoundTripsAManifest() {
|
||||
val m = manifestFrom(byPrefix("vault-v2 manifest v2").single().getJSONObject("manifest"))
|
||||
val a = sealObject(crypto, keys.contentKey, keys.vaultId, encodeManifest(m))
|
||||
val b = sealObject(crypto, keys.contentKey, keys.vaultId, encodeManifest(m))
|
||||
// Fresh nonce: same plaintext, different names — why unchanged entries are reused, not re-sealed.
|
||||
assertFalse(a.hash == b.hash)
|
||||
assertEquals(m, openManifest(crypto, keys.contentKey, keys.vaultId, a.hash, a.bytes))
|
||||
}
|
||||
|
||||
// ─── Signing ─────────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
fun signedBodiesMatchVectors() {
|
||||
for (v in byPrefix("vault-v2 signed")) {
|
||||
val what = v.getString("description")
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
val body = toKotlin(v.getJSONObject("body")) as Map<String, Any>
|
||||
val signed = signPayload(crypto, keys.signingSeed, body, v.getLong("signedAt"))
|
||||
assertEquals("$what: canonical", v.getString("canonical"), String(signed.canonical, Charsets.UTF_8))
|
||||
assertEquals("$what: canonicalHex", v.getString("canonicalHex"), toHex(signed.canonical))
|
||||
assertEquals("$what: signature", v.getString("signature"), toHex(signed.signature))
|
||||
|
||||
val wire = JSONObject(signed.json)
|
||||
assertEquals(v.getString("signatureBase64"), wire.getString("signature"))
|
||||
assertEquals(v.getLong("signedAt"), wire.getLong("signedAt"))
|
||||
assertTrue(crypto.verify(keys.publicKey, signed.canonical, Base64.getDecoder().decode(wire.getString("signature"))))
|
||||
|
||||
// The vault helper adds publicKey itself and must land on the same bytes.
|
||||
val withoutKey = body.filterKeys { it != "publicKey" }
|
||||
val viaKeys = signVaultBody(crypto, keys, withoutKey, v.getLong("signedAt"))
|
||||
assertArrayEquals("$what: signVaultBody", signed.canonical, viaKeys.canonical)
|
||||
assertArrayEquals(signed.signature, viaKeys.signature)
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Packing rules ───────────────────────────────────────
|
||||
|
||||
@Test
|
||||
fun packingRules() {
|
||||
// Empty file: one empty part, never compressed.
|
||||
val empty = packEntry(ByteArray(0))
|
||||
assertNull(empty.enc)
|
||||
assertEquals(1, empty.chunks.size)
|
||||
assertEquals(0, empty.chunks[0].size)
|
||||
|
||||
// Random bytes do not shrink ≥5 %: stored as-is.
|
||||
val random = ByteArray(10_000).also { java.util.Random(7).nextBytes(it) }
|
||||
assertNull(packEntry(random).enc)
|
||||
|
||||
// Exactly at a chunk boundary: no trailing empty part.
|
||||
val twoChunks = packEntry(random, chunkSize = 5_000)
|
||||
assertEquals(2, twoChunks.chunks.size)
|
||||
assertEquals(VAULT_CHUNK_SIZE, 4 * 1024 * 1024)
|
||||
|
||||
// Compressible text compresses and inflates back.
|
||||
val text = "hei hei hei hei\n".repeat(500).toByteArray()
|
||||
val p = packEntry(text)
|
||||
assertEquals("deflate-raw", p.enc)
|
||||
assertArrayEquals(text, inflateRaw(p.stored, text.size.toLong()))
|
||||
|
||||
val magics = listOf(
|
||||
byteArrayOf(0x89.toByte(), 0x50, 0x4e, 0x47),
|
||||
byteArrayOf(0xff.toByte(), 0xd8.toByte(), 0xff.toByte()),
|
||||
"RIFF\u0000\u0000\u0000\u0000WEBP".toByteArray(),
|
||||
"\u0000\u0000\u0000\u0018ftypmp42".toByteArray(),
|
||||
"GIF89a".toByteArray(),
|
||||
byteArrayOf(0x1f, 0x8b.toByte()),
|
||||
"PK\u0003\u0004".toByteArray(),
|
||||
)
|
||||
for (m in magics) {
|
||||
assertTrue(toHex(m), looksCompressed(m))
|
||||
assertNull(packEntry(m + ByteArray(4000)).enc)
|
||||
}
|
||||
assertFalse(looksCompressed("RIFF\u0000\u0000\u0000\u0000WAVE".toByteArray()))
|
||||
assertFalse(looksCompressed("P".toByteArray()))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun inflateIsStrictAboutTheStreamEnd() {
|
||||
val text = "abcabcabc-".repeat(1000).toByteArray()
|
||||
val d = deflateRaw(text)
|
||||
assertArrayEquals(text, inflateRaw(d, text.size.toLong()))
|
||||
assertThrows(VaultFormatException::class.java) { inflateRaw(d.copyOf(d.size - 3), text.size.toLong()) }
|
||||
assertThrows(VaultFormatException::class.java) { inflateRaw(d + byteArrayOf(1, 2, 3), text.size.toLong()) }
|
||||
assertThrows(VaultFormatException::class.java) { inflateRaw(d, text.size.toLong() - 1) }
|
||||
assertThrows(VaultFormatException::class.java) { inflateRaw(byteArrayOf(0xff.toByte(), 0xff.toByte(), 0xff.toByte()), 100) }
|
||||
assertArrayEquals(ByteArray(0), inflateRaw(deflateRaw(ByteArray(0)), 0))
|
||||
}
|
||||
}
|
||||
102
docs/vault.md
102
docs/vault.md
@@ -50,21 +50,84 @@ const crypto = new SubtleCryptoProvider();
|
||||
const keys = await deriveVaultKeys(masterKey, 'scaffold');
|
||||
const client = new VaultClient(crypto, keys, new HttpVaultTransport('https://vault.example'));
|
||||
|
||||
// Back up. Unchanged files are not re-uploaded.
|
||||
const res = await client.push(files, Date.now(), 'nightly');
|
||||
// → { seq: 4, uploaded: 2, reused: 489, bytesUploaded: 1_204 }
|
||||
// Back up. Unchanged files are not re-uploaded. Persist `res.index` and pass
|
||||
// it to the next push: an unchanged file is then recognised locally, with no
|
||||
// download at all.
|
||||
const res = await client.push(files, Date.now(), undefined, { index: savedIndex });
|
||||
// → { seq: 4, uploaded: 2, reused: 489, bytesUploaded: 1_204, unchanged: false, index }
|
||||
|
||||
// Restore — the newest, or any earlier version.
|
||||
const { manifest, files: restored } = await client.pull();
|
||||
const old = await client.pull(2);
|
||||
|
||||
// History.
|
||||
// Lazy: list a version, then fetch only what is opened.
|
||||
const m = await client.manifest();
|
||||
const bytes = await client.readEntry(m.entries[0]);
|
||||
|
||||
// History, and retention.
|
||||
const log = await client.history();
|
||||
await client.prune([log.head - 1, log.head]); // → { removedVersions, removedObjects, freedBytes }
|
||||
```
|
||||
|
||||
`push` takes `at` rather than reading the clock, so a queued backup records
|
||||
when it was *taken* rather than when it finally reached the relay.
|
||||
|
||||
**A push that changes nothing commits nothing.** Same paths, same modes, every
|
||||
file reused, no `message`: the result is `{ unchanged: true, seq: head }` and
|
||||
the log does not grow. Pushes run on every workspace change; a version per
|
||||
trigger would fill the log with empty commits. Pass a `message` to force one.
|
||||
|
||||
**The index** (`VaultIndex`, plain JSON) maps each path to its plaintext
|
||||
SHA-256 and the entry it was stored as. It is trusted only when its `vaultId`
|
||||
matches and its `seq` is still the relay's head; otherwise the push reads the
|
||||
head manifest and downloads only same-path, same-size candidates to compare. It
|
||||
holds plaintext hashes, so keep it with the files, never on the relay. After a
|
||||
restore, `vaultIndexFrom(vaultId, manifest, files)` builds one, so the first
|
||||
push from a fresh device is free too.
|
||||
|
||||
## Format (v2) — the cross-language contract
|
||||
|
||||
Every object is `nonce(12) || AES-256-GCM(contentKey, plaintext, aad)`, named
|
||||
by the lowercase hex SHA-256 of those bytes, with
|
||||
`aad = utf8("shade-vault-object-v1|" + vaultId)`.
|
||||
|
||||
**Entries.** A file's plaintext becomes its *stored* bytes, then *parts*:
|
||||
|
||||
1. Unless the plaintext is empty or starts with a known compressed signature —
|
||||
PNG `89 50 4E 47`, JPEG `FF D8 FF`, WebP `"RIFF"` + `"WEBP"` at offset 8,
|
||||
MP4 family `"ftyp"` at offset 4, GIF `"GIF8"`, gzip `1F 8B`, zip `"PK"` —
|
||||
deflate it (raw RFC 1951, zlib default level). Keep the result, and set
|
||||
`enc: "deflate-raw"`, only if `compressed * 20 <= plain * 19` (≤ 95 %, in
|
||||
integers so no port rounds differently).
|
||||
2. Split the stored bytes into slices of at most 4 MiB (4 194 304). An empty
|
||||
file is one empty slice.
|
||||
3. Seal each slice as its own object. One slice: `hash` names it and there is
|
||||
no `parts`. Several: `parts` lists their hashes in order and
|
||||
`hash = parts[0]`.
|
||||
|
||||
`size` is always the **plaintext** length. A reader fetches
|
||||
`parts ?? [hash]`, verifies and opens each, concatenates, inflates if `enc`,
|
||||
and checks the result against `size`. An unknown `enc` is refused.
|
||||
|
||||
**Manifests.** v2 plaintext is ASCII `"SVM2"` followed by deflate-raw of the
|
||||
UTF-8 JSON; v1 is the bare JSON. A reader inflates when the magic is present,
|
||||
parses, and accepts `version` 1 or 2 only — refusing beats guessing, since
|
||||
silently dropping a field it cannot represent would lose data on its next
|
||||
commit. JSON key order is not part of the contract. A v1-only reader fails on a
|
||||
v2 manifest at JSON parse, loudly, rather than misreading it.
|
||||
|
||||
**Commits** list every part of every entry in the signed `hashes`. The relay
|
||||
checks they exist and records them as what the version references; a part
|
||||
left out may be collected by the next prune.
|
||||
|
||||
**Signed bodies** are canonicalised as JSON of every field except
|
||||
`signature`, top-level keys sorted, nested values as-is; the signature is
|
||||
Ed25519 over those bytes with the vault's signing seed, base64 on the wire.
|
||||
|
||||
Vectors for all of the above: `test-vectors/vault-v2.json` (regenerate with
|
||||
`bun run scripts/generate-vectors.ts vault-v2.json`). Compressed bytes are
|
||||
pinned (`stored`) for writer parity; a reader needs only `wire`.
|
||||
|
||||
## Server
|
||||
|
||||
```ts
|
||||
@@ -83,6 +146,7 @@ Routes:
|
||||
| `GET /v1/vault/:id/object/:hash` | raw ciphertext |
|
||||
| `PUT /v1/vault/:id/object/:hash` | signed; verifies hash matches bytes |
|
||||
| `POST /v1/vault/:id/commit` | signed; refuses a stale `seq` or a missing object |
|
||||
| `POST /v1/vault/:id/prune` | signed `{ keep: number[] }`; must keep the head |
|
||||
|
||||
Auth is TOFU-Ed25519, as for blobs: the first signed write pins a pubkey, and
|
||||
every later write must be signed by it. The pubkey travels **inside** the
|
||||
@@ -106,6 +170,31 @@ mounted, with a warning that says why.
|
||||
### Limits
|
||||
|
||||
Per object 8 MiB, per vault 512 MiB, both overridable via `VaultRoutesOptions`.
|
||||
Files larger than an object are split into 4 MiB parts by the client, so the
|
||||
per-object limit no longer caps file size.
|
||||
|
||||
### Retention
|
||||
|
||||
`prune` deletes every log entry not in `keep` and then every object no
|
||||
remaining entry references. The client chooses the policy — only it can read
|
||||
the manifests — and the relay executes it:
|
||||
|
||||
- `keep` must include the current head, or the request fails with
|
||||
`SEQ_CONFLICT` (and the head). That is also what a keep-list computed before
|
||||
another device's commit, or a replayed prune, runs into.
|
||||
- Prune never pins an owner: on a vault with no owner it is a 404.
|
||||
- An entry newer than the head the route checked is never removed, even if a
|
||||
commit lands mid-request.
|
||||
- An object no version has ever referenced (an upload whose commit is still
|
||||
in flight) survives for `pruneGraceMs`, default one hour.
|
||||
- **Versions committed before ref tracking** have no recorded hash list. Every
|
||||
object present when such a version was written (for SQLite: when the
|
||||
database was migrated) is pinned and never collected while any untracked
|
||||
version remains. Once the last one is pruned, nothing has an unknown
|
||||
reference set, and the pins are released.
|
||||
|
||||
`SqliteVaultStore` migrates in place on open: `refs_known` on the log,
|
||||
`pinned` on objects, a `shade_vault_refs` table. No manual step.
|
||||
|
||||
## What the relay learns
|
||||
|
||||
@@ -121,6 +210,5 @@ share, which is exactly what a blind store must not do.
|
||||
## Status
|
||||
|
||||
Client, routes, `MemoryVaultStore` and `SqliteVaultStore` are implemented and
|
||||
tested (16 unit + 7 store tests, plus an end-to-end suite against a real
|
||||
workspace of 491 files). Not yet: a Postgres store, rate limiting on the vault
|
||||
routes, and garbage collection of objects no manifest references any more.
|
||||
tested, v2 format and prune included, with cross-language vectors. Not yet: a
|
||||
Postgres store, rate limiting on the vault routes, and the Kotlin port of v2.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/cli",
|
||||
"version": "4.13.1",
|
||||
"version": "4.14.1",
|
||||
"type": "module",
|
||||
"main": "src/cli.ts",
|
||||
"bin": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/core",
|
||||
"version": "4.13.1",
|
||||
"version": "4.14.1",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/crypto-web",
|
||||
"version": "4.13.1",
|
||||
"version": "4.14.1",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/dashboard",
|
||||
"version": "4.13.1",
|
||||
"version": "4.14.1",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/files",
|
||||
"version": "4.13.1",
|
||||
"version": "4.14.1",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/inbox-server",
|
||||
"version": "4.13.1",
|
||||
"version": "4.14.1",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/inbox",
|
||||
"version": "4.13.1",
|
||||
"version": "4.14.1",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/key-transparency",
|
||||
"version": "4.13.1",
|
||||
"version": "4.14.1",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/keychain",
|
||||
"version": "4.13.1",
|
||||
"version": "4.14.1",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/observability",
|
||||
"version": "4.13.1",
|
||||
"version": "4.14.1",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/observer",
|
||||
"version": "4.13.1",
|
||||
"version": "4.14.1",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/proto",
|
||||
"version": "4.13.1",
|
||||
"version": "4.14.1",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/recovery",
|
||||
"version": "4.13.1",
|
||||
"version": "4.14.1",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/sdk",
|
||||
"version": "4.13.1",
|
||||
"version": "4.14.1",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { StorageProvider } from '@shade/core';
|
||||
import { ConfigurationError } from '@shade/core';
|
||||
import type { ObservabilityHook } from '@shade/observability';
|
||||
import { DEFAULT_REQUEST_TIMEOUT_MS } from '@shade/transport';
|
||||
|
||||
/**
|
||||
* Shade SDK configuration.
|
||||
@@ -84,6 +85,29 @@ export interface ShadeConfig {
|
||||
* Default: KT verification disabled. Set this to enable.
|
||||
*/
|
||||
keyTransparency?: ShadeKTConfig;
|
||||
|
||||
/**
|
||||
* What `initialize()` does about registering with the prekey server.
|
||||
*
|
||||
* - `'await'` (default): wait for it — at most `requestTimeoutMs` — so a
|
||||
* peer can fetch this identity's bundle the moment `createShade`
|
||||
* resolves.
|
||||
* - `'background'`: don't wait. For apps where opening the identity must
|
||||
* not depend on the network, e.g. a local unlock gate.
|
||||
*
|
||||
* Either way a registration that fails is retried in the background with
|
||||
* backoff until it succeeds or `shutdown()` runs.
|
||||
*/
|
||||
registration?: 'await' | 'background';
|
||||
|
||||
/** Every prekey-server request gives up after this many ms. Default 15 000. */
|
||||
requestTimeoutMs?: number;
|
||||
|
||||
/**
|
||||
* Fetch for every prekey-server request — to observe the server's
|
||||
* reachability, or to stub the network in tests. Default: global fetch.
|
||||
*/
|
||||
fetch?: typeof fetch;
|
||||
}
|
||||
|
||||
/** Public configuration shape for `Shade.keyTransparency`. */
|
||||
@@ -117,6 +141,9 @@ export interface ResolvedConfig {
|
||||
};
|
||||
observability?: ObservabilityHook;
|
||||
keyTransparency?: ResolvedKTConfig;
|
||||
registration: 'await' | 'background';
|
||||
requestTimeoutMs: number;
|
||||
fetch?: typeof fetch;
|
||||
}
|
||||
|
||||
export interface ResolvedKTConfig {
|
||||
@@ -146,8 +173,20 @@ export function resolveConfig(input: ShadeConfig): ResolvedConfig {
|
||||
address: input.address,
|
||||
autoReplenish,
|
||||
autoRotate: input.autoRotate ?? false,
|
||||
registration: input.registration ?? 'await',
|
||||
requestTimeoutMs: input.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,
|
||||
};
|
||||
|
||||
if (resolved.registration !== 'await' && resolved.registration !== 'background') {
|
||||
throw new ConfigurationError(`registration must be 'await' or 'background'`);
|
||||
}
|
||||
if (!Number.isFinite(resolved.requestTimeoutMs) || resolved.requestTimeoutMs <= 0) {
|
||||
throw new ConfigurationError('requestTimeoutMs must be a positive number');
|
||||
}
|
||||
if (input.fetch !== undefined) {
|
||||
resolved.fetch = input.fetch;
|
||||
}
|
||||
|
||||
if (input.observer) {
|
||||
if (!input.observer.token || input.observer.token.length < 16) {
|
||||
throw new ConfigurationError('observer.token must be at least 16 characters');
|
||||
|
||||
@@ -143,6 +143,9 @@ export interface ShadeUploadOptions extends TransferOptions {
|
||||
generateThumbnail?: boolean | ThumbnailGenerationOptions;
|
||||
}
|
||||
|
||||
/** Delays between retries of the initial registration; the last repeats. */
|
||||
const REGISTRATION_RETRY_MS: readonly number[] = [5_000, 15_000, 30_000, 60_000];
|
||||
|
||||
/**
|
||||
* The high-level Shade API.
|
||||
*
|
||||
@@ -157,6 +160,9 @@ export class Shade {
|
||||
private manager!: ShadeSessionManager;
|
||||
private transport!: ShadeFetchTransport;
|
||||
private _background: BackgroundTasks | null = null;
|
||||
/** Pending retry of the initial registration; see [retryRegistration]. */
|
||||
private registrationRetry: ReturnType<typeof setTimeout> | null = null;
|
||||
private shutDown = false;
|
||||
private address!: string;
|
||||
private initialized = false;
|
||||
|
||||
@@ -279,28 +285,23 @@ export class Shade {
|
||||
};
|
||||
}
|
||||
|
||||
this.transport = new ShadeFetchTransport({
|
||||
baseUrl: this.config.prekeyServer,
|
||||
crypto: this.crypto,
|
||||
signingPrivateKey: identity.signingPrivateKey,
|
||||
...(ktOpts ? { keyTransparency: ktOpts } : {}),
|
||||
});
|
||||
this.transport = this.makeTransport(identity.signingPrivateKey, ktOpts);
|
||||
|
||||
// Step 5: Initial prekeys + register
|
||||
const otpks = await this.manager.generateOneTimePreKeys(20);
|
||||
const bundle = await this.manager.createPreKeyBundle();
|
||||
const publicIdentity = this.manager.getPublicIdentity();
|
||||
const register = () =>
|
||||
this.transport.register(this.address, publicIdentity, bundle.signedPreKey, otpks);
|
||||
|
||||
if (this.config.registration === 'background') {
|
||||
this.retryRegistration(register, 0, 0);
|
||||
} else {
|
||||
try {
|
||||
await this.transport.register(
|
||||
this.address,
|
||||
this.manager.getPublicIdentity(),
|
||||
bundle.signedPreKey,
|
||||
otpks,
|
||||
);
|
||||
await register();
|
||||
} catch (err) {
|
||||
console.warn(
|
||||
`[Shade] Failed to register with prekey server at ${this.config.prekeyServer}: ${(err as Error).message}. Will retry on next replenish.`,
|
||||
);
|
||||
this.retryRegistration(register, 1, undefined, err as Error);
|
||||
}
|
||||
}
|
||||
|
||||
// Step 6: Background tasks
|
||||
@@ -742,6 +743,10 @@ export class Shade {
|
||||
async rotate(): Promise<void> {
|
||||
if (!this.initialized) throw new Error('Not initialized');
|
||||
|
||||
// The initial registration's retry would publish the identity we are
|
||||
// about to replace; this rotation registers the new one itself.
|
||||
this.cancelRegistrationRetry();
|
||||
|
||||
// Rotate locally first
|
||||
const newBundle = await this.manager.rotateIdentity();
|
||||
|
||||
@@ -749,11 +754,7 @@ export class Shade {
|
||||
// signed operations (replenish, delete, register) work
|
||||
const identity = await this.storage.getIdentityKeyPair();
|
||||
if (!identity) throw new Error('Identity missing after rotate');
|
||||
this.transport = new ShadeFetchTransport({
|
||||
baseUrl: this.config.prekeyServer,
|
||||
crypto: this.crypto,
|
||||
signingPrivateKey: identity.signingPrivateKey,
|
||||
});
|
||||
this.transport = this.makeTransport(identity.signingPrivateKey);
|
||||
|
||||
// Re-upload the new bundle
|
||||
await this.transport.register(
|
||||
@@ -822,17 +823,79 @@ export class Shade {
|
||||
: {}),
|
||||
});
|
||||
await this.manager.initialize();
|
||||
this.transport = new ShadeFetchTransport({
|
||||
// Same reason as in rotate(): the pending retry is for the old identity.
|
||||
this.cancelRegistrationRetry();
|
||||
this.transport = this.makeTransport(restored.signingPrivateKey);
|
||||
}
|
||||
}
|
||||
|
||||
private makeTransport(
|
||||
signingPrivateKey: Uint8Array,
|
||||
keyTransparency?: KTVerifierOptions,
|
||||
): ShadeFetchTransport {
|
||||
return new ShadeFetchTransport({
|
||||
baseUrl: this.config.prekeyServer,
|
||||
crypto: this.crypto,
|
||||
signingPrivateKey: restored.signingPrivateKey,
|
||||
signingPrivateKey,
|
||||
requestTimeoutMs: this.config.requestTimeoutMs,
|
||||
...(this.config.fetch ? { fetch: this.config.fetch } : {}),
|
||||
...(keyTransparency ? { keyTransparency } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Register with the prekey server, retrying with backoff until it works,
|
||||
* the identity changes, or the instance shuts down.
|
||||
*
|
||||
* This used to be one attempt whose failure promised "will retry on next
|
||||
* replenish" — but replenish never registers, so an identity that came
|
||||
* up while the server was unreachable stayed unregistered until the next
|
||||
* restart.
|
||||
*
|
||||
* `attempt` 0 is the first try (no delay unless `delayMs` says so); each
|
||||
* failure moves one step along [REGISTRATION_RETRY_MS].
|
||||
*/
|
||||
private retryRegistration(
|
||||
register: () => Promise<void>,
|
||||
attempt: number,
|
||||
delayMs?: number,
|
||||
lastError?: Error,
|
||||
): void {
|
||||
if (this.shutDown) return;
|
||||
const steps = REGISTRATION_RETRY_MS;
|
||||
const delay = delayMs ?? steps[Math.min(Math.max(attempt - 1, 0), steps.length - 1)] ?? 60_000;
|
||||
if (lastError) {
|
||||
console.warn(
|
||||
`[Shade] Failed to register with prekey server at ${this.config.prekeyServer}: ${lastError.message}. Retrying in ${Math.round(delay / 1000)} s.`,
|
||||
);
|
||||
}
|
||||
this.registrationRetry = setTimeout(() => {
|
||||
this.registrationRetry = null;
|
||||
if (this.shutDown) return;
|
||||
register().then(
|
||||
() => {
|
||||
if (attempt > 0) {
|
||||
console.warn(`[Shade] Registered with prekey server at ${this.config.prekeyServer}.`);
|
||||
}
|
||||
},
|
||||
(err: Error) => this.retryRegistration(register, attempt + 1, undefined, err),
|
||||
);
|
||||
}, delay);
|
||||
(this.registrationRetry as unknown as { unref?: () => void }).unref?.();
|
||||
}
|
||||
|
||||
private cancelRegistrationRetry(): void {
|
||||
if (this.registrationRetry !== null) {
|
||||
clearTimeout(this.registrationRetry);
|
||||
this.registrationRetry = null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Clean shutdown: stop timers, close storage if it supports it */
|
||||
async shutdown(): Promise<void> {
|
||||
this._background?.stop();
|
||||
this.cancelRegistrationRetry();
|
||||
this.shutDown = true;
|
||||
if (this.transferEngine !== null) this.transferEngine.destroy();
|
||||
if (this.controlChannel !== null) this.controlChannel.destroy();
|
||||
if (this.webrtcRuntime !== null) {
|
||||
|
||||
111
packages/shade-sdk/tests/registration.test.ts
Normal file
111
packages/shade-sdk/tests/registration.test.ts
Normal file
@@ -0,0 +1,111 @@
|
||||
import { describe, test, expect } from 'bun:test';
|
||||
import { createShade } from '../src/index.js';
|
||||
|
||||
/**
|
||||
* Opening an identity used to wait on the prekey server with no deadline:
|
||||
* with the server unreachable (packets dropped, not refused) `createShade`
|
||||
* hung until the kernel gave up on the TCP handshake, about two minutes —
|
||||
* and the failed registration was never retried, despite the log saying
|
||||
* it would be.
|
||||
*/
|
||||
describe('registration with an unreachable prekey server', () => {
|
||||
/** Never answers; honours abort like the real fetch. Counts calls. */
|
||||
function blackHole() {
|
||||
const urls: string[] = [];
|
||||
const fetch = ((url: string, init?: RequestInit) => {
|
||||
urls.push(url);
|
||||
return new Promise<Response>((_resolve, reject) => {
|
||||
init?.signal?.addEventListener('abort', () => reject(init.signal!.reason));
|
||||
});
|
||||
}) as unknown as typeof globalThis.fetch;
|
||||
return { fetch, urls };
|
||||
}
|
||||
|
||||
test("'background' opens the identity without waiting on the server", async () => {
|
||||
const net = blackHole();
|
||||
const started = Date.now();
|
||||
const shade = await createShade({
|
||||
prekeyServer: 'https://prekey.invalid',
|
||||
address: 'alice',
|
||||
autoReplenish: false,
|
||||
registration: 'background',
|
||||
requestTimeoutMs: 60_000,
|
||||
fetch: net.fetch,
|
||||
});
|
||||
try {
|
||||
expect(Date.now() - started).toBeLessThan(5_000);
|
||||
expect(shade.myAddress).toBe('alice');
|
||||
await new Promise((r) => setTimeout(r, 20));
|
||||
expect(net.urls).toEqual(['https://prekey.invalid/v1/keys/register']);
|
||||
} finally {
|
||||
await shade.shutdown();
|
||||
}
|
||||
});
|
||||
|
||||
test("'await' gives up at the request deadline instead of hanging", async () => {
|
||||
const net = blackHole();
|
||||
const started = Date.now();
|
||||
const shade = await createShade({
|
||||
prekeyServer: 'https://prekey.invalid',
|
||||
address: 'bob',
|
||||
autoReplenish: false,
|
||||
requestTimeoutMs: 100,
|
||||
fetch: net.fetch,
|
||||
});
|
||||
try {
|
||||
expect(Date.now() - started).toBeLessThan(5_000);
|
||||
expect(net.urls).toHaveLength(1);
|
||||
} finally {
|
||||
await shade.shutdown();
|
||||
}
|
||||
});
|
||||
|
||||
test('a failed registration is retried until the server answers', async () => {
|
||||
let calls = 0;
|
||||
const fetch = (async () => {
|
||||
calls += 1;
|
||||
if (calls === 1) throw new TypeError('Unable to connect');
|
||||
return new Response('{}', { status: 200 });
|
||||
}) as unknown as typeof globalThis.fetch;
|
||||
const shade = await createShade({
|
||||
prekeyServer: 'https://prekey.invalid',
|
||||
address: 'carol',
|
||||
autoReplenish: false,
|
||||
fetch,
|
||||
});
|
||||
try {
|
||||
expect(calls).toBe(1);
|
||||
// First retry is due 5 s after the failure.
|
||||
await new Promise((r) => setTimeout(r, 5_300));
|
||||
expect(calls).toBe(2);
|
||||
} finally {
|
||||
await shade.shutdown();
|
||||
}
|
||||
}, 10_000);
|
||||
|
||||
test('shutdown stops the retries', async () => {
|
||||
let calls = 0;
|
||||
const fetch = (async () => {
|
||||
calls += 1;
|
||||
throw new TypeError('Unable to connect');
|
||||
}) as unknown as typeof globalThis.fetch;
|
||||
const shade = await createShade({
|
||||
prekeyServer: 'https://prekey.invalid',
|
||||
address: 'dave',
|
||||
autoReplenish: false,
|
||||
fetch,
|
||||
});
|
||||
await shade.shutdown();
|
||||
await new Promise((r) => setTimeout(r, 5_300));
|
||||
expect(calls).toBe(1);
|
||||
}, 10_000);
|
||||
|
||||
test('nonsense settings are refused up front', async () => {
|
||||
await expect(
|
||||
createShade({ prekeyServer: 'https://x.invalid', requestTimeoutMs: 0 }),
|
||||
).rejects.toThrow('requestTimeoutMs');
|
||||
await expect(
|
||||
createShade({ prekeyServer: 'https://x.invalid', registration: 'later' as never }),
|
||||
).rejects.toThrow('registration');
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/server",
|
||||
"version": "4.13.1",
|
||||
"version": "4.14.1",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/storage-encrypted",
|
||||
"version": "4.13.1",
|
||||
"version": "4.14.1",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/storage-indexeddb",
|
||||
"version": "4.13.1",
|
||||
"version": "4.14.1",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/storage-postgres",
|
||||
"version": "4.13.1",
|
||||
"version": "4.14.1",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/storage-sqlite",
|
||||
"version": "4.13.1",
|
||||
"version": "4.14.1",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Database } from 'bun:sqlite';
|
||||
import type { VaultLogEntry, VaultStore } from '@shade/vault';
|
||||
import type { VaultLogEntry, VaultPrunePlan, VaultPruneResult, VaultStore } from '@shade/vault';
|
||||
|
||||
/**
|
||||
* SQLite-backed VaultStore for the V4.13 encrypted file store.
|
||||
@@ -9,6 +9,13 @@ import type { VaultLogEntry, VaultStore } from '@shade/vault';
|
||||
* never decrypts anything — it enforces auth, verifies that an object's bytes
|
||||
* hash to its name, and refuses a commit whose objects are not all present.
|
||||
*
|
||||
* A fourth table, `shade_vault_refs`, records which objects each version
|
||||
* references (the commit's signed hashes plus its manifest). The relay cannot
|
||||
* read manifests, so this is what prune computes garbage from. Versions from
|
||||
* before it existed have `refs_known = 0`, and every object that was in the
|
||||
* database when the columns were added is `pinned` — see `VaultPrunePlan` for
|
||||
* why that is the safe reading and how the pins are eventually released.
|
||||
*
|
||||
* Objects are stored as BLOBs rather than base64 text. A workspace backup is
|
||||
* a few hundred files where the blob primitive holds one small profile, so the
|
||||
* 33% base64 overhead stops being a rounding error.
|
||||
@@ -31,6 +38,8 @@ export class SqliteVaultStore implements VaultStore {
|
||||
log: ReturnType<Database['prepare']>;
|
||||
logLimit: ReturnType<Database['prepare']>;
|
||||
appendLog: ReturnType<Database['prepare']>;
|
||||
appendRef: ReturnType<Database['prepare']>;
|
||||
pinAll: ReturnType<Database['prepare']>;
|
||||
usage: ReturnType<Database['prepare']>;
|
||||
};
|
||||
|
||||
@@ -56,6 +65,7 @@ export class SqliteVaultStore implements VaultStore {
|
||||
bytes BLOB NOT NULL,
|
||||
size INTEGER NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
pinned INTEGER NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (vault_id, hash)
|
||||
);
|
||||
|
||||
@@ -65,9 +75,38 @@ export class SqliteVaultStore implements VaultStore {
|
||||
manifest TEXT NOT NULL,
|
||||
at INTEGER NOT NULL,
|
||||
bytes INTEGER NOT NULL,
|
||||
refs_known INTEGER NOT NULL DEFAULT 1,
|
||||
PRIMARY KEY (vault_id, seq)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS shade_vault_refs (
|
||||
vault_id TEXT NOT NULL,
|
||||
seq INTEGER NOT NULL,
|
||||
hash TEXT NOT NULL,
|
||||
PRIMARY KEY (vault_id, seq, hash)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS shade_vault_refs_by_hash ON shade_vault_refs (vault_id, hash);
|
||||
`);
|
||||
|
||||
// Databases from before ref tracking. The defaults here are the whole
|
||||
// migration: every existing log row becomes untracked (refs_known = 0),
|
||||
// and every existing object pinned (pinned = 1), because any of them may
|
||||
// be referenced by one of those rows. New rows always set both columns
|
||||
// explicitly, so these defaults only ever apply to the old ones.
|
||||
const has = (table: string, column: string): boolean =>
|
||||
(this.db.prepare(`PRAGMA table_info(${table})`).all() as Array<{ name: string }>).some(
|
||||
(c) => c.name === column,
|
||||
);
|
||||
this.db.transaction(() => {
|
||||
if (!has('shade_vault_log', 'refs_known')) {
|
||||
this.db.exec(
|
||||
'ALTER TABLE shade_vault_log ADD COLUMN refs_known INTEGER NOT NULL DEFAULT 0',
|
||||
);
|
||||
}
|
||||
if (!has('shade_vault_objects', 'pinned')) {
|
||||
this.db.exec('ALTER TABLE shade_vault_objects ADD COLUMN pinned INTEGER NOT NULL DEFAULT 1');
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
private prepareStatements() {
|
||||
@@ -82,7 +121,7 @@ export class SqliteVaultStore implements VaultStore {
|
||||
// An object's name IS its content hash, so a repeat upload is the same
|
||||
// bytes by definition — ignoring it is correct, not lossy.
|
||||
putObject: this.db.prepare(
|
||||
'INSERT OR IGNORE INTO shade_vault_objects (vault_id, hash, bytes, size, created_at) VALUES (?, ?, ?, ?, ?)',
|
||||
'INSERT OR IGNORE INTO shade_vault_objects (vault_id, hash, bytes, size, created_at, pinned) VALUES (?, ?, ?, ?, ?, 0)',
|
||||
),
|
||||
getObject: this.db.prepare(
|
||||
'SELECT bytes FROM shade_vault_objects WHERE vault_id = ? AND hash = ?',
|
||||
@@ -95,8 +134,12 @@ export class SqliteVaultStore implements VaultStore {
|
||||
'SELECT seq, manifest, at, bytes FROM (SELECT seq, manifest, at, bytes FROM shade_vault_log WHERE vault_id = ? ORDER BY seq DESC LIMIT ?) ORDER BY seq ASC',
|
||||
),
|
||||
appendLog: this.db.prepare(
|
||||
'INSERT INTO shade_vault_log (vault_id, seq, manifest, at, bytes) VALUES (?, ?, ?, ?, ?)',
|
||||
'INSERT INTO shade_vault_log (vault_id, seq, manifest, at, bytes, refs_known) VALUES (?, ?, ?, ?, ?, ?)',
|
||||
),
|
||||
appendRef: this.db.prepare(
|
||||
'INSERT OR IGNORE INTO shade_vault_refs (vault_id, seq, hash) VALUES (?, ?, ?)',
|
||||
),
|
||||
pinAll: this.db.prepare('UPDATE shade_vault_objects SET pinned = 1 WHERE vault_id = ?'),
|
||||
usage: this.db.prepare(
|
||||
'SELECT COALESCE(SUM(size), 0) AS total FROM shade_vault_objects WHERE vault_id = ?',
|
||||
),
|
||||
@@ -139,8 +182,100 @@ export class SqliteVaultStore implements VaultStore {
|
||||
return rows;
|
||||
}
|
||||
|
||||
async appendLog(vaultId: string, entry: VaultLogEntry): Promise<void> {
|
||||
this.stmts.appendLog.run(vaultId, entry.seq, entry.manifest, entry.at, entry.bytes);
|
||||
async appendLog(vaultId: string, entry: VaultLogEntry, refs?: readonly string[]): Promise<void> {
|
||||
this.db.transaction(() => {
|
||||
this.stmts.appendLog.run(
|
||||
vaultId,
|
||||
entry.seq,
|
||||
entry.manifest,
|
||||
entry.at,
|
||||
entry.bytes,
|
||||
refs ? 1 : 0,
|
||||
);
|
||||
if (refs) {
|
||||
for (const h of refs) this.stmts.appendRef.run(vaultId, entry.seq, h);
|
||||
} else {
|
||||
// Untracked: it can reference anything stored so far, so pin all of it.
|
||||
this.stmts.pinAll.run(vaultId);
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
/**
|
||||
* One transaction, so a commit cannot interleave between deciding what is
|
||||
* garbage and deleting it. bun:sqlite is synchronous, and a write
|
||||
* transaction holds the database lock for its whole duration.
|
||||
*/
|
||||
async prune(vaultId: string, plan: VaultPrunePlan): Promise<VaultPruneResult> {
|
||||
return this.db.transaction((): VaultPruneResult => {
|
||||
const keep = new Set(plan.keep);
|
||||
const rows = this.db
|
||||
.prepare('SELECT seq, refs_known FROM shade_vault_log WHERE vault_id = ?')
|
||||
.all(vaultId) as Array<{ seq: number; refs_known: number }>;
|
||||
const removed = rows.filter((r) => r.seq <= plan.upTo && !keep.has(r.seq)).map((r) => r.seq);
|
||||
const untrackedRemains = rows.some(
|
||||
(r) => r.refs_known === 0 && !(r.seq <= plan.upTo && !keep.has(r.seq)),
|
||||
);
|
||||
|
||||
// The removed seqs go into a temp table so every query below can say
|
||||
// "the log as it will be" without string-building an IN list.
|
||||
this.db.exec(
|
||||
'CREATE TEMP TABLE IF NOT EXISTS shade_vault_prune_removed (seq INTEGER PRIMARY KEY)',
|
||||
);
|
||||
this.db.exec('DELETE FROM shade_vault_prune_removed');
|
||||
const addRemoved = this.db.prepare('INSERT INTO shade_vault_prune_removed (seq) VALUES (?)');
|
||||
for (const seq of removed) addRemoved.run(seq);
|
||||
|
||||
if (!untrackedRemains) {
|
||||
// No version with an unknown reference set is left, so nothing can
|
||||
// depend on a pin any more.
|
||||
this.db.prepare('UPDATE shade_vault_objects SET pinned = 0 WHERE vault_id = ?').run(vaultId);
|
||||
}
|
||||
|
||||
// Garbage: not pinned, not used by a remaining version, and — if no
|
||||
// version ever used it — older than the grace for in-flight uploads.
|
||||
const garbage = this.db
|
||||
.prepare(
|
||||
`SELECT o.hash AS hash, o.size AS size FROM shade_vault_objects o
|
||||
WHERE o.vault_id = ?1
|
||||
AND o.pinned = 0
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM shade_vault_refs r
|
||||
WHERE r.vault_id = ?1 AND r.hash = o.hash
|
||||
AND r.seq NOT IN (SELECT seq FROM shade_vault_prune_removed))
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM shade_vault_log l
|
||||
WHERE l.vault_id = ?1 AND l.manifest = o.hash
|
||||
AND l.seq NOT IN (SELECT seq FROM shade_vault_prune_removed))
|
||||
AND (
|
||||
o.created_at <= ?2
|
||||
OR EXISTS (SELECT 1 FROM shade_vault_refs r WHERE r.vault_id = ?1 AND r.hash = o.hash)
|
||||
OR EXISTS (SELECT 1 FROM shade_vault_log l WHERE l.vault_id = ?1 AND l.manifest = o.hash))`,
|
||||
)
|
||||
.all(vaultId, plan.protectSince) as Array<{ hash: string; size: number }>;
|
||||
|
||||
const delObject = this.db.prepare(
|
||||
'DELETE FROM shade_vault_objects WHERE vault_id = ? AND hash = ?',
|
||||
);
|
||||
let freedBytes = 0;
|
||||
for (const g of garbage) {
|
||||
delObject.run(vaultId, g.hash);
|
||||
freedBytes += g.size;
|
||||
}
|
||||
this.db
|
||||
.prepare(
|
||||
'DELETE FROM shade_vault_refs WHERE vault_id = ? AND seq IN (SELECT seq FROM shade_vault_prune_removed)',
|
||||
)
|
||||
.run(vaultId);
|
||||
this.db
|
||||
.prepare(
|
||||
'DELETE FROM shade_vault_log WHERE vault_id = ? AND seq IN (SELECT seq FROM shade_vault_prune_removed)',
|
||||
)
|
||||
.run(vaultId);
|
||||
this.db.exec('DELETE FROM shade_vault_prune_removed');
|
||||
|
||||
return { removedVersions: removed.length, removedObjects: garbage.length, freedBytes };
|
||||
})();
|
||||
}
|
||||
|
||||
async usage(vaultId: string): Promise<number> {
|
||||
|
||||
@@ -118,3 +118,134 @@ describe('semantics', () => {
|
||||
store.close();
|
||||
});
|
||||
});
|
||||
|
||||
describe('prune', () => {
|
||||
const h = (c: string) => c.repeat(64);
|
||||
|
||||
test('removes unkept versions and only the objects nothing else uses', async () => {
|
||||
const store = new SqliteVaultStore(scratch('prune'));
|
||||
await store.putObject(VAULT, h('1'), new Uint8Array(10)); // manifest 1
|
||||
await store.putObject(VAULT, h('2'), new Uint8Array(20)); // manifest 2
|
||||
await store.putObject(VAULT, h('a'), new Uint8Array(30)); // shared file
|
||||
await store.putObject(VAULT, h('b'), new Uint8Array(40)); // only in v1
|
||||
await store.appendLog(VAULT, { seq: 1, manifest: h('1'), at: 1, bytes: 0 }, [h('1'), h('a'), h('b')]);
|
||||
await store.appendLog(VAULT, { seq: 2, manifest: h('2'), at: 2, bytes: 0 }, [h('2'), h('a')]);
|
||||
|
||||
const res = await store.prune(VAULT, { keep: [2], upTo: 2, protectSince: Date.now() });
|
||||
expect(res).toEqual({ removedVersions: 1, removedObjects: 2, freedBytes: 50 });
|
||||
expect(await store.hasObject(VAULT, h('a'))).toBe(true);
|
||||
expect(await store.hasObject(VAULT, h('b'))).toBe(false);
|
||||
expect((await store.log(VAULT)).map((e) => e.seq)).toEqual([2]);
|
||||
store.close();
|
||||
});
|
||||
|
||||
test('a fresh, never-committed upload survives; a stale one does not', async () => {
|
||||
const store = new SqliteVaultStore(scratch('grace'));
|
||||
await store.putObject(VAULT, h('1'), new Uint8Array(1));
|
||||
await store.appendLog(VAULT, { seq: 1, manifest: h('1'), at: 1, bytes: 0 }, [h('1')]);
|
||||
await store.putObject(VAULT, h('c'), new Uint8Array(5));
|
||||
|
||||
const kept = await store.prune(VAULT, { keep: [1], upTo: 1, protectSince: Date.now() - 60_000 });
|
||||
expect(kept.removedObjects).toBe(0);
|
||||
const gone = await store.prune(VAULT, { keep: [1], upTo: 1, protectSince: Date.now() + 1 });
|
||||
expect(gone.removedObjects).toBe(1);
|
||||
expect(await store.hasObject(VAULT, h('c'))).toBe(false);
|
||||
store.close();
|
||||
});
|
||||
|
||||
test('never removes an entry above upTo, even when it is not in keep', async () => {
|
||||
const store = new SqliteVaultStore(scratch('upto'));
|
||||
for (let seq = 1; seq <= 3; seq++) {
|
||||
await store.appendLog(VAULT, { seq, manifest: `${seq}`.repeat(64), at: seq, bytes: 0 }, []);
|
||||
}
|
||||
await store.prune(VAULT, { keep: [2], upTo: 2, protectSince: 0 });
|
||||
expect((await store.log(VAULT)).map((e) => e.seq)).toEqual([2, 3]);
|
||||
store.close();
|
||||
});
|
||||
|
||||
test('untracked entries pin what existed when they were appended, until they are gone', async () => {
|
||||
const store = new SqliteVaultStore(scratch('pin'));
|
||||
await store.putObject(VAULT, h('1'), new Uint8Array(1));
|
||||
await store.putObject(VAULT, h('b'), new Uint8Array(1));
|
||||
await store.appendLog(VAULT, { seq: 1, manifest: h('1'), at: 1, bytes: 0 }); // no refs
|
||||
await store.putObject(VAULT, h('2'), new Uint8Array(1));
|
||||
await store.appendLog(VAULT, { seq: 2, manifest: h('2'), at: 2, bytes: 0 }, [h('2')]);
|
||||
await store.putObject(VAULT, h('3'), new Uint8Array(1));
|
||||
await store.appendLog(VAULT, { seq: 3, manifest: h('3'), at: 3, bytes: 0 }, [h('3')]);
|
||||
|
||||
const first = await store.prune(VAULT, { keep: [1, 3], upTo: 3, protectSince: Date.now() });
|
||||
expect(first.removedObjects).toBe(1); // only manifest 2
|
||||
expect(await store.hasObject(VAULT, h('b'))).toBe(true);
|
||||
|
||||
const second = await store.prune(VAULT, { keep: [3], upTo: 3, protectSince: Date.now() });
|
||||
expect(second.removedObjects).toBe(2); // manifest 1 and b, unpinned
|
||||
expect(await store.hasObject(VAULT, h('3'))).toBe(true);
|
||||
store.close();
|
||||
});
|
||||
|
||||
test('a database from before ref tracking migrates with everything pinned', async () => {
|
||||
// The exact pre-v2 schema, with a version and its objects in it.
|
||||
const path = scratch('migrate');
|
||||
const { Database } = await import('bun:sqlite');
|
||||
const old = new Database(path, { create: true });
|
||||
old.exec(`
|
||||
CREATE TABLE shade_vault_objects (vault_id TEXT NOT NULL, hash TEXT NOT NULL, bytes BLOB NOT NULL,
|
||||
size INTEGER NOT NULL, created_at INTEGER NOT NULL, PRIMARY KEY (vault_id, hash));
|
||||
CREATE TABLE shade_vault_log (vault_id TEXT NOT NULL, seq INTEGER NOT NULL, manifest TEXT NOT NULL,
|
||||
at INTEGER NOT NULL, bytes INTEGER NOT NULL, PRIMARY KEY (vault_id, seq));
|
||||
`);
|
||||
old.prepare('INSERT INTO shade_vault_objects VALUES (?, ?, ?, ?, ?)').run(VAULT, h('1'), new Uint8Array(1), 1, 0);
|
||||
old.prepare('INSERT INTO shade_vault_objects VALUES (?, ?, ?, ?, ?)').run(VAULT, h('a'), new Uint8Array(1), 1, 0);
|
||||
old.prepare('INSERT INTO shade_vault_log VALUES (?, ?, ?, ?, ?)').run(VAULT, 1, h('1'), 1, 2);
|
||||
old.close();
|
||||
|
||||
const store = new SqliteVaultStore(path);
|
||||
// A tracked version on top, then drop nothing but nothing referenced by it:
|
||||
// the old file object must survive because version 1 may use it.
|
||||
await store.putObject(VAULT, h('2'), new Uint8Array(1));
|
||||
await store.appendLog(VAULT, { seq: 2, manifest: h('2'), at: 2, bytes: 0 }, [h('2')]);
|
||||
const res = await store.prune(VAULT, { keep: [1, 2], upTo: 2, protectSince: Date.now() });
|
||||
expect(res.removedObjects).toBe(0);
|
||||
expect(await store.hasObject(VAULT, h('a'))).toBe(true);
|
||||
store.close();
|
||||
|
||||
// Reopening runs the migration check again and must be a no-op.
|
||||
const again = new SqliteVaultStore(path);
|
||||
expect((await again.log(VAULT)).map((e) => e.seq)).toEqual([1, 2]);
|
||||
const final = await again.prune(VAULT, { keep: [2], upTo: 2, protectSince: Date.now() });
|
||||
expect(final).toMatchObject({ removedVersions: 1, removedObjects: 2 });
|
||||
again.close();
|
||||
});
|
||||
});
|
||||
|
||||
describe('through the real routes and client', () => {
|
||||
test('v2 push, index reuse, multi-part and prune all work on SQLite', async () => {
|
||||
const { SubtleCryptoProvider } = await import('@shade/crypto-web');
|
||||
const { createVaultRoutes } = await import('@shade/vault/server');
|
||||
const { HttpVaultTransport, VaultClient, deriveVaultKeys } = await import('@shade/vault');
|
||||
const crypto = new SubtleCryptoProvider();
|
||||
const store = new SqliteVaultStore(scratch('e2e'));
|
||||
const routes = createVaultRoutes(store, crypto, { pruneGraceMs: 0 });
|
||||
const transport = new HttpVaultTransport('http://v', (i, init) => routes.fetch(new Request(i, init)));
|
||||
const keys = await deriveVaultKeys(new Uint8Array(32).fill(5), 'scaffold');
|
||||
const client = new VaultClient(crypto, keys, transport, { chunkSize: 512 });
|
||||
|
||||
const big = new Uint8Array(2000);
|
||||
globalThis.crypto.getRandomValues(big);
|
||||
const text = new TextEncoder().encode('linje\n'.repeat(500));
|
||||
const first = await client.push([{ path: 'big.bin', bytes: big }, { path: 't.md', bytes: text }], 1);
|
||||
const same = await client.push([{ path: 'big.bin', bytes: big }, { path: 't.md', bytes: text }], 2, undefined, {
|
||||
index: first.index,
|
||||
});
|
||||
expect(same.unchanged).toBe(true);
|
||||
await client.push([{ path: 't.md', bytes: text }], 3, undefined, { index: same.index });
|
||||
|
||||
const pruned = await client.prune([2]);
|
||||
expect(pruned.removedVersions).toBe(1);
|
||||
expect(pruned.removedObjects).toBe(5); // big.bin's 4 parts + manifest 1
|
||||
const { files } = await client.pull();
|
||||
expect(files.get('t.md')).toEqual(text);
|
||||
expect(files.has('big.bin')).toBe(false);
|
||||
store.close();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/streams",
|
||||
"version": "4.13.1",
|
||||
"version": "4.14.1",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/transfer",
|
||||
"version": "4.13.1",
|
||||
"version": "4.14.1",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/transport-bridge",
|
||||
"version": "4.13.1",
|
||||
"version": "4.14.1",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/transport-webrtc",
|
||||
"version": "4.13.1",
|
||||
"version": "4.14.1",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/transport",
|
||||
"version": "4.13.1",
|
||||
"version": "4.14.1",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -14,6 +14,9 @@ import {
|
||||
KTVerificationError,
|
||||
} from '@shade/key-transparency';
|
||||
|
||||
/** How long any prekey-server request may go unanswered. */
|
||||
export const DEFAULT_REQUEST_TIMEOUT_MS = 15_000;
|
||||
|
||||
/**
|
||||
* HTTP transport client for the Shade Prekey Server.
|
||||
*
|
||||
@@ -67,15 +70,31 @@ export class ShadeFetchTransport {
|
||||
private readonly crypto: CryptoProvider;
|
||||
private readonly signingPrivateKey?: Uint8Array;
|
||||
private readonly kt?: KTVerifierOptions;
|
||||
private readonly fetchImpl: (url: string, init: RequestInit) => Promise<Response>;
|
||||
private readonly requestTimeoutMs: number;
|
||||
|
||||
constructor(options: {
|
||||
baseUrl: string;
|
||||
crypto: CryptoProvider;
|
||||
signingPrivateKey?: Uint8Array;
|
||||
keyTransparency?: KTVerifierOptions;
|
||||
/**
|
||||
* Fetch for every request. Lets an app observe its server's
|
||||
* reachability, or tests stub the network. Default: global fetch.
|
||||
*/
|
||||
fetch?: typeof fetch;
|
||||
/**
|
||||
* A request with no response by then fails with a `NetworkError`.
|
||||
* Default 15 000. Without it an unreachable server (packets dropped,
|
||||
* not refused) held each call until the kernel gave up on the TCP
|
||||
* handshake — about two minutes on Linux.
|
||||
*/
|
||||
requestTimeoutMs?: number;
|
||||
}) {
|
||||
this.baseUrl = options.baseUrl;
|
||||
this.crypto = options.crypto;
|
||||
this.fetchImpl = options.fetch ?? ((url, init) => fetch(url, init));
|
||||
this.requestTimeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
|
||||
if (options.signingPrivateKey !== undefined) {
|
||||
this.signingPrivateKey = options.signingPrivateKey;
|
||||
}
|
||||
@@ -84,6 +103,22 @@ export class ShadeFetchTransport {
|
||||
}
|
||||
}
|
||||
|
||||
/** Every request goes through here, so every request has a deadline. */
|
||||
private async request(url: string, init: RequestInit = {}): Promise<Response> {
|
||||
const timeout = AbortSignal.timeout(this.requestTimeoutMs);
|
||||
const signal = init.signal ? AbortSignal.any([init.signal, timeout]) : timeout;
|
||||
try {
|
||||
return await this.fetchImpl(url, { ...init, signal });
|
||||
} catch (err) {
|
||||
if (timeout.aborted && !init.signal?.aborted) {
|
||||
throw new NetworkError(
|
||||
`No response from ${new URL(url).host} within ${this.requestTimeoutMs} ms`,
|
||||
);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
private headers(): Record<string, string> {
|
||||
return { 'Content-Type': 'application/json' };
|
||||
}
|
||||
@@ -133,7 +168,7 @@ export class ShadeFetchTransport {
|
||||
|
||||
const signed = await this.sign(body);
|
||||
|
||||
const res = await fetch(`${this.baseUrl}/v1/keys/register`, {
|
||||
const res = await this.request(`${this.baseUrl}/v1/keys/register`, {
|
||||
method: 'POST',
|
||||
headers: this.headers(),
|
||||
body: JSON.stringify(signed),
|
||||
@@ -159,7 +194,7 @@ export class ShadeFetchTransport {
|
||||
* direct access to the proof side-channel.
|
||||
*/
|
||||
async fetchBundleVerified(address: string): Promise<FetchBundleResult> {
|
||||
const res = await fetch(`${this.baseUrl}/v1/keys/bundle/${encodeURIComponent(address)}`, {
|
||||
const res = await this.request(`${this.baseUrl}/v1/keys/bundle/${encodeURIComponent(address)}`, {
|
||||
headers: this.headers(),
|
||||
});
|
||||
if (!res.ok) {
|
||||
@@ -283,7 +318,7 @@ export class ShadeFetchTransport {
|
||||
};
|
||||
const signed = await this.sign(body);
|
||||
|
||||
const res = await fetch(`${this.baseUrl}/v1/keys/replenish`, {
|
||||
const res = await this.request(`${this.baseUrl}/v1/keys/replenish`, {
|
||||
method: 'POST',
|
||||
headers: this.headers(),
|
||||
body: JSON.stringify(signed),
|
||||
@@ -295,7 +330,7 @@ export class ShadeFetchTransport {
|
||||
|
||||
/** Get remaining one-time prekey count (anonymous) */
|
||||
async getKeyCount(address: string): Promise<number> {
|
||||
const res = await fetch(`${this.baseUrl}/v1/keys/count/${encodeURIComponent(address)}`, {
|
||||
const res = await this.request(`${this.baseUrl}/v1/keys/count/${encodeURIComponent(address)}`, {
|
||||
headers: this.headers(),
|
||||
});
|
||||
if (!res.ok) throw new NetworkError(`Count failed: ${res.status}`, res.status);
|
||||
@@ -306,7 +341,7 @@ export class ShadeFetchTransport {
|
||||
/** Delete all keys for this identity (signed) */
|
||||
async unregister(address: string): Promise<void> {
|
||||
const signed = await this.sign({ address });
|
||||
const res = await fetch(`${this.baseUrl}/v1/keys/${encodeURIComponent(address)}`, {
|
||||
const res = await this.request(`${this.baseUrl}/v1/keys/${encodeURIComponent(address)}`, {
|
||||
method: 'DELETE',
|
||||
headers: this.headers(),
|
||||
body: JSON.stringify(signed),
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
export { ShadeFetchTransport } from './fetch-transport.js';
|
||||
export { ShadeFetchTransport, DEFAULT_REQUEST_TIMEOUT_MS } from './fetch-transport.js';
|
||||
export type { FetchBundleResult, KTVerifierOptions } from './fetch-transport.js';
|
||||
export { ShadeWebSocket } from './ws-adapter.js';
|
||||
|
||||
@@ -82,3 +82,44 @@ describe('ShadeFetchTransport', () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* A server that drops packets instead of refusing them used to hold every
|
||||
* call until the kernel gave up on the TCP handshake — two minutes on
|
||||
* Linux. Every request now has a deadline.
|
||||
*/
|
||||
describe('ShadeFetchTransport request deadline', () => {
|
||||
/** A fetch that never answers, but honours abort like the real one. */
|
||||
const blackHole = ((_url: unknown, init?: RequestInit) =>
|
||||
new Promise<Response>((_resolve, reject) => {
|
||||
init?.signal?.addEventListener('abort', () => reject(init.signal!.reason));
|
||||
})) as unknown as typeof fetch;
|
||||
|
||||
test('a request nobody answers fails with a NetworkError at the deadline', async () => {
|
||||
const transport = new ShadeFetchTransport({
|
||||
baseUrl: 'https://prekey.invalid',
|
||||
crypto,
|
||||
fetch: blackHole,
|
||||
requestTimeoutMs: 50,
|
||||
});
|
||||
const started = Date.now();
|
||||
const err = await transport.getKeyCount('bob').catch((e) => e);
|
||||
expect(err.name).toBe('NetworkError');
|
||||
expect(err.message).toContain('No response from prekey.invalid within 50 ms');
|
||||
expect(Date.now() - started).toBeLessThan(2_000);
|
||||
});
|
||||
|
||||
test('every request goes through the supplied fetch', async () => {
|
||||
const urls: string[] = [];
|
||||
const transport = new ShadeFetchTransport({
|
||||
baseUrl: 'https://prekey.invalid',
|
||||
crypto,
|
||||
fetch: (async (url: string) => {
|
||||
urls.push(url);
|
||||
return new Response(JSON.stringify({ count: 7 }), { status: 200 });
|
||||
}) as unknown as typeof fetch,
|
||||
});
|
||||
expect(await transport.getKeyCount('bob')).toBe(7);
|
||||
expect(urls).toEqual(['https://prekey.invalid/v1/keys/count/bob']);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
{
|
||||
"name": "@shade/vault",
|
||||
"version": "4.13.1",
|
||||
"version": "4.14.1",
|
||||
"description": "Server-side encrypted file store for Shade — content-addressed objects with an append-only manifest log",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
"exports": {
|
||||
".": "./src/index.ts",
|
||||
"./server": "./src/server.ts"
|
||||
"./server": "./src/server.ts",
|
||||
"./testing": "./src/testing.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@noble/hashes": "^2.0.1",
|
||||
|
||||
@@ -2,10 +2,12 @@
|
||||
* The client half: turn a set of files into an encrypted, versioned vault,
|
||||
* and turn it back again on a machine that has nothing but the credentials.
|
||||
*
|
||||
* The push is deliberately have-check-first. A workspace changes a few lines
|
||||
* at a time, so asking "do you already have these hashes?" and uploading only
|
||||
* the misses turns a full backup into a handful of small writes. Everything
|
||||
* unchanged keeps its hash from the previous commit and costs nothing.
|
||||
* A workspace changes a few lines at a time, so a push has to cost what
|
||||
* changed, not what exists. Everything unchanged keeps the entry — and so the
|
||||
* objects — it had in the previous version, and costs nothing. Recognising
|
||||
* "unchanged" is the expensive part: with a `VaultIndex` from the previous
|
||||
* push it is a local hash comparison; without one, the previous manifest is
|
||||
* read and only same-path, same-size candidates are downloaded to compare.
|
||||
*/
|
||||
|
||||
import type { CryptoProvider } from '@shade/core';
|
||||
@@ -19,8 +21,24 @@ import {
|
||||
deriveVaultId,
|
||||
deriveVaultSigningSeed,
|
||||
} from '@shade/storage-encrypted';
|
||||
import { openManifest, openObject, sealManifest, sealObject, toHex } from './crypto.js';
|
||||
import type { VaultEntry, VaultLog, VaultManifest } from './types.js';
|
||||
import { sha256 } from '@noble/hashes/sha2.js';
|
||||
import {
|
||||
entryObjectHashes,
|
||||
openEntryBytes,
|
||||
openManifest,
|
||||
sealEntry,
|
||||
sealManifest,
|
||||
toHex,
|
||||
} from './crypto.js';
|
||||
import type {
|
||||
VaultEntry,
|
||||
VaultIndex,
|
||||
VaultIndexEntry,
|
||||
VaultLog,
|
||||
VaultLogEntry,
|
||||
VaultManifest,
|
||||
VaultPruneResult,
|
||||
} from './types.js';
|
||||
|
||||
/** A file as the app sees it, before encryption. */
|
||||
export interface VaultFile {
|
||||
@@ -61,15 +79,37 @@ export interface VaultTransport {
|
||||
get(vaultId: string, hash: string): Promise<Uint8Array>;
|
||||
log(vaultId: string, limit?: number): Promise<VaultLog>;
|
||||
commit(vaultId: string, body: unknown): Promise<{ seq: number }>;
|
||||
prune(vaultId: string, body: unknown): Promise<VaultPruneResult>;
|
||||
}
|
||||
|
||||
export interface PushOptions {
|
||||
/**
|
||||
* The index the previous push returned. Trusted only when it belongs to
|
||||
* this vault and its `seq` is still the relay's head; otherwise ignored.
|
||||
*/
|
||||
index?: VaultIndex;
|
||||
}
|
||||
|
||||
export interface PushResult {
|
||||
/** The version now at the head — the new one, or the old one if `unchanged`. */
|
||||
seq: number;
|
||||
/** Objects actually sent — the rest were already on the relay. */
|
||||
/** Data objects sent (the manifest is not counted). */
|
||||
uploaded: number;
|
||||
/** Objects skipped because the relay had them. */
|
||||
/** Files whose previous entry was reused without sealing anything. */
|
||||
reused: number;
|
||||
bytesUploaded: number;
|
||||
/** Nothing differed from the head, so no version was committed. */
|
||||
unchanged: boolean;
|
||||
/** Describes the head after this push; persist it and pass it to the next one. */
|
||||
index: VaultIndex;
|
||||
}
|
||||
|
||||
export interface VaultClientOptions {
|
||||
/**
|
||||
* Override the 4 MiB part size. Internal — tests and vectors only. A real
|
||||
* writer must use the default so every implementation splits identically.
|
||||
*/
|
||||
chunkSize?: number;
|
||||
}
|
||||
|
||||
export class VaultClient {
|
||||
@@ -77,6 +117,7 @@ export class VaultClient {
|
||||
private readonly crypto: CryptoProvider,
|
||||
private readonly keys: VaultKeys,
|
||||
private readonly transport: VaultTransport,
|
||||
private readonly options: VaultClientOptions = {},
|
||||
) {}
|
||||
|
||||
get vaultId(): string {
|
||||
@@ -104,54 +145,122 @@ export class VaultClient {
|
||||
* `at` is passed in rather than read from the clock so a caller can make a
|
||||
* commit reproducible in tests, and so a queued backup records when it was
|
||||
* *taken* rather than when it finally reached the relay.
|
||||
*
|
||||
* When nothing differs from the head — same paths, same modes, every file
|
||||
* reused — and no `message` asks for a version anyway, nothing is
|
||||
* committed. Pushes run on every workspace change, and a version per
|
||||
* trigger that changed nothing would grow the log for nothing.
|
||||
*/
|
||||
async push(files: VaultFile[], at: number, message?: string): Promise<PushResult> {
|
||||
const { head } = await this.transport.log(this.keys.vaultId, 1);
|
||||
async push(
|
||||
files: VaultFile[],
|
||||
at: number,
|
||||
message?: string,
|
||||
opts: PushOptions = {},
|
||||
): Promise<PushResult> {
|
||||
const { head, entries: tail } = await this.transport.log(this.keys.vaultId, 1);
|
||||
const headRow = tail.find((e) => e.seq === head);
|
||||
|
||||
const fresh = (prior: VaultIndex | undefined): prior is VaultIndex =>
|
||||
prior !== undefined && prior.vaultId === this.keys.vaultId && prior.seq === head;
|
||||
|
||||
// Reuse beats re-sealing: sealing is nondeterministic (fresh nonce), so
|
||||
// re-sealing an untouched file would produce a new hash and a pointless
|
||||
// upload every single time.
|
||||
//
|
||||
// With a fresh index, reuse is decided locally by plaintext hash — also
|
||||
// across paths, so a renamed or copied file costs nothing either. Without
|
||||
// one, read only the head manifest, and download a previous file only
|
||||
// when its path and size both match (a different size cannot be the same
|
||||
// content). That is the old behaviour's correctness at a fraction of its
|
||||
// cost: it used to download every file of the head on every push.
|
||||
let headEntries: VaultEntry[] | null = null;
|
||||
const byHash = new Map<string, VaultEntry>();
|
||||
let byPath = new Map<string, VaultEntry>();
|
||||
if (fresh(opts.index)) {
|
||||
headEntries = Object.values(opts.index.entries).map((e) => e.entry);
|
||||
for (const e of Object.values(opts.index.entries)) byHash.set(e.sha256, e.entry);
|
||||
} else if (headRow) {
|
||||
// A head this client cannot read (a newer format, a corrupt manifest)
|
||||
// must not block a backup; it only costs the reuse.
|
||||
const manifest = await this.openRow(headRow).catch(() => null);
|
||||
if (manifest) {
|
||||
headEntries = manifest.entries;
|
||||
byPath = new Map(manifest.entries.map((e) => [e.path, e]));
|
||||
}
|
||||
}
|
||||
|
||||
const entries: VaultEntry[] = [];
|
||||
const indexEntries: Record<string, VaultIndexEntry> = {};
|
||||
let uploaded = 0;
|
||||
let reused = 0;
|
||||
let bytesUploaded = 0;
|
||||
|
||||
// Reuse the previous manifest's hashes for unchanged content: sealing is
|
||||
// nondeterministic (fresh nonce), so re-sealing an untouched file would
|
||||
// produce a new hash and a pointless upload every single time.
|
||||
const previous = head > 0 ? await this.pull().catch(() => null) : null;
|
||||
const byPath = new Map(previous?.manifest.entries.map((e) => [e.path, e]) ?? []);
|
||||
const priorPlain = previous?.files ?? new Map<string, Uint8Array>();
|
||||
|
||||
for (const file of files) {
|
||||
const prior = byPath.get(file.path);
|
||||
const priorBytes = priorPlain.get(file.path);
|
||||
if (prior && priorBytes && sameBytes(priorBytes, file.bytes)) {
|
||||
entries.push({ ...prior, size: file.bytes.length });
|
||||
reused++;
|
||||
continue;
|
||||
const digest = toHex(sha256(file.bytes));
|
||||
let prior = byHash.get(digest);
|
||||
if (!prior) {
|
||||
const candidate = byPath.get(file.path);
|
||||
if (candidate && candidate.size === file.bytes.length) {
|
||||
const old = await this.readEntry(candidate).catch(() => null);
|
||||
if (old && sameBytes(old, file.bytes)) prior = candidate;
|
||||
}
|
||||
}
|
||||
|
||||
const sealed = await sealObject(
|
||||
let entry: VaultEntry;
|
||||
if (prior) {
|
||||
entry = { ...prior, path: file.path, size: file.bytes.length };
|
||||
reused++;
|
||||
} else {
|
||||
const sealed = await sealEntry(
|
||||
this.crypto,
|
||||
this.keys.contentKey,
|
||||
this.keys.vaultId,
|
||||
file.bytes,
|
||||
this.options.chunkSize === undefined ? {} : { chunkSize: this.options.chunkSize },
|
||||
);
|
||||
if (!(await this.transport.has(this.keys.vaultId, sealed.hash))) {
|
||||
// No have-check first: every object here was just sealed under a
|
||||
// fresh nonce, so its name is new by construction, and asking would
|
||||
// only add a round trip per part.
|
||||
for (const obj of sealed.objects) {
|
||||
await this.transport.put(
|
||||
this.keys.vaultId,
|
||||
sealed.hash,
|
||||
await this.sign({ data: toBase64(sealed.bytes) }),
|
||||
obj.hash,
|
||||
await this.sign({ data: toBase64(obj.bytes) }),
|
||||
);
|
||||
uploaded++;
|
||||
bytesUploaded += sealed.bytes.length;
|
||||
} else {
|
||||
reused++;
|
||||
bytesUploaded += obj.bytes.length;
|
||||
}
|
||||
const entry: VaultEntry = { path: file.path, hash: sealed.hash, size: file.bytes.length };
|
||||
entry = { path: file.path, ...sealed.locator, size: file.bytes.length };
|
||||
// A second copy later in this same push reuses what was just sealed.
|
||||
byHash.set(digest, entry);
|
||||
}
|
||||
// The mode is metadata of this push, not of the content: a reused entry
|
||||
// takes the new one, and loses the old one if the file has none now.
|
||||
delete entry.mode;
|
||||
if (file.mode !== undefined) entry.mode = file.mode;
|
||||
|
||||
entries.push(entry);
|
||||
indexEntries[file.path] = { sha256: digest, entry };
|
||||
}
|
||||
|
||||
const manifest: VaultManifest = { version: 1, seq: head + 1, at, entries };
|
||||
if (
|
||||
message === undefined &&
|
||||
headRow &&
|
||||
headEntries &&
|
||||
uploaded === 0 &&
|
||||
sameEntries(headEntries, entries)
|
||||
) {
|
||||
return {
|
||||
seq: head,
|
||||
uploaded: 0,
|
||||
reused,
|
||||
bytesUploaded: 0,
|
||||
unchanged: true,
|
||||
index: { vaultId: this.keys.vaultId, seq: head, entries: indexEntries },
|
||||
};
|
||||
}
|
||||
|
||||
const manifest: VaultManifest = { version: 2, seq: head + 1, at, entries };
|
||||
if (message !== undefined) manifest.message = message;
|
||||
|
||||
const sealedManifest = await sealManifest(
|
||||
@@ -166,58 +275,233 @@ export class VaultClient {
|
||||
await this.sign({ data: toBase64(sealedManifest.bytes) }),
|
||||
);
|
||||
|
||||
// Every part, not just each entry's `hash`: the relay checks these exist
|
||||
// before publishing the version, and records them as what it references —
|
||||
// a part missing here would be fair game for the next prune.
|
||||
const hashes = [...new Set(entries.flatMap((e) => entryObjectHashes(e)))];
|
||||
const { seq } = await this.transport.commit(
|
||||
this.keys.vaultId,
|
||||
await this.sign({
|
||||
manifest: sealedManifest.hash,
|
||||
seq: manifest.seq,
|
||||
at,
|
||||
hashes: entries.map((e) => e.hash),
|
||||
hashes,
|
||||
}),
|
||||
);
|
||||
|
||||
return { seq, uploaded, reused, bytesUploaded };
|
||||
return {
|
||||
seq,
|
||||
uploaded,
|
||||
reused,
|
||||
bytesUploaded,
|
||||
unchanged: false,
|
||||
index: { vaultId: this.keys.vaultId, seq, entries: indexEntries },
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch a version and decrypt it. Defaults to the newest.
|
||||
* Change a few files against the head that was actually read, and only it.
|
||||
*
|
||||
* Restoring is the whole point of the exercise, so this returns the plain
|
||||
* files rather than a handle: a caller that has to make a second round of
|
||||
* decisions to get their data back does not have a backup.
|
||||
* `push` publishes a whole collection — right for a backup, where this
|
||||
* client is the only writer and the files on disk are the truth. It is
|
||||
* wrong for a vault two devices write to, such as a queue a phone appends
|
||||
* to while a PC drains it: a push computed from a stale view would commit
|
||||
* a collection without the other device's latest file, and it would be
|
||||
* gone. `edit` instead reads the head, lets `change` decide from exactly
|
||||
* that manifest, keeps every entry it did not touch as-is, and commits
|
||||
* `head + 1`. If another device committed in between, the relay refuses
|
||||
* with SEQ_CONFLICT and this starts over from the new head — `change` is
|
||||
* called again, so it must be a pure decision about the manifest it gets.
|
||||
*
|
||||
* Returning `null` (or an edit that changes nothing) commits nothing.
|
||||
*/
|
||||
async pull(seq?: number): Promise<{ manifest: VaultManifest; files: Map<string, Uint8Array> }> {
|
||||
const log = await this.transport.log(this.keys.vaultId);
|
||||
const wanted = seq ?? log.head;
|
||||
const row = log.entries.find((e) => e.seq === wanted);
|
||||
if (!row) throw new Error(`vault has no version ${wanted}`);
|
||||
async edit(
|
||||
change: (head: VaultManifest | null) => VaultEdit | null | Promise<VaultEdit | null>,
|
||||
at: number,
|
||||
opts: { maxAttempts?: number } = {},
|
||||
): Promise<{ seq: number; committed: boolean }> {
|
||||
const attempts = Math.max(1, opts.maxAttempts ?? 5);
|
||||
for (let attempt = 1; ; attempt++) {
|
||||
const { head, entries: tail } = await this.transport.log(this.keys.vaultId, 1);
|
||||
const row = tail.find((e) => e.seq === head);
|
||||
const manifest = row ? await this.openRow(row) : null;
|
||||
const edit = await change(manifest);
|
||||
const put = edit?.put ?? [];
|
||||
const remove = new Set(edit?.remove ?? []);
|
||||
const current = manifest?.entries ?? [];
|
||||
const replaced = new Set(put.map((f) => f.path));
|
||||
if (put.length === 0 && !current.some((e) => remove.has(e.path))) {
|
||||
return { seq: head, committed: false };
|
||||
}
|
||||
|
||||
const manifestBytes = await this.transport.get(this.keys.vaultId, row.manifest);
|
||||
const manifest = await openManifest(
|
||||
const entries = current.filter((e) => !remove.has(e.path) && !replaced.has(e.path));
|
||||
for (const file of put) {
|
||||
const sealed = await sealEntry(
|
||||
this.crypto,
|
||||
this.keys.contentKey,
|
||||
this.keys.vaultId,
|
||||
row.manifest,
|
||||
manifestBytes,
|
||||
);
|
||||
|
||||
const files = new Map<string, Uint8Array>();
|
||||
for (const entry of manifest.entries) {
|
||||
const bytes = await this.transport.get(this.keys.vaultId, entry.hash);
|
||||
files.set(
|
||||
entry.path,
|
||||
await openObject(this.crypto, this.keys.contentKey, this.keys.vaultId, entry.hash, bytes),
|
||||
file.bytes,
|
||||
this.options.chunkSize === undefined ? {} : { chunkSize: this.options.chunkSize },
|
||||
);
|
||||
for (const obj of sealed.objects) {
|
||||
await this.transport.put(this.keys.vaultId, obj.hash, await this.sign({ data: toBase64(obj.bytes) }));
|
||||
}
|
||||
const entry: VaultEntry = { path: file.path, ...sealed.locator, size: file.bytes.length };
|
||||
if (file.mode !== undefined) entry.mode = file.mode;
|
||||
entries.push(entry);
|
||||
}
|
||||
|
||||
const next: VaultManifest = { version: 2, seq: head + 1, at, entries };
|
||||
const sealedManifest = await sealManifest(this.crypto, this.keys.contentKey, this.keys.vaultId, next);
|
||||
await this.transport.put(
|
||||
this.keys.vaultId,
|
||||
sealedManifest.hash,
|
||||
await this.sign({ data: toBase64(sealedManifest.bytes) }),
|
||||
);
|
||||
try {
|
||||
const { seq } = await this.transport.commit(
|
||||
this.keys.vaultId,
|
||||
await this.sign({
|
||||
manifest: sealedManifest.hash,
|
||||
seq: next.seq,
|
||||
at,
|
||||
hashes: [...new Set(entries.flatMap((e) => entryObjectHashes(e)))],
|
||||
}),
|
||||
);
|
||||
return { seq, committed: true };
|
||||
} catch (e) {
|
||||
// The objects just uploaded are orphans now; the relay's prune grace
|
||||
// and GC take care of them. Only a lost race is worth another go.
|
||||
if (attempt >= attempts || !isSeqConflict(e)) throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch and open just a version's manifest. Defaults to the newest.
|
||||
*
|
||||
* The cheap way to answer "what is in the backup?" — a file browser lists a
|
||||
* thousand-file workspace with one download, then `readEntry`s what the
|
||||
* user actually opens.
|
||||
*/
|
||||
async manifest(seq?: number): Promise<VaultManifest> {
|
||||
// The head needs only the newest row; an older version needs the log to
|
||||
// find its row, since `limit` counts back from the head.
|
||||
const log = await this.transport.log(this.keys.vaultId, seq === undefined ? 1 : undefined);
|
||||
const wanted = seq ?? log.head;
|
||||
const row = log.entries.find((e) => e.seq === wanted);
|
||||
if (!row) throw new Error(`vault has no version ${wanted}`);
|
||||
return this.openRow(row);
|
||||
}
|
||||
|
||||
/** Fetch, verify, decrypt and reassemble one file of a manifest. */
|
||||
async readEntry(entry: VaultEntry): Promise<Uint8Array> {
|
||||
const objects: Uint8Array[] = [];
|
||||
for (const hash of entryObjectHashes(entry)) {
|
||||
objects.push(await this.transport.get(this.keys.vaultId, hash));
|
||||
}
|
||||
return openEntryBytes(this.crypto, this.keys.contentKey, this.keys.vaultId, entry, objects);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch a version and decrypt all of it. Defaults to the newest.
|
||||
*
|
||||
* Restoring is the whole point of the exercise, so this returns the plain
|
||||
* files rather than a handle: a caller that has to make a second round of
|
||||
* decisions to get their data back does not have a backup. Callers that do
|
||||
* want to choose use `manifest` + `readEntry`, which this is built from.
|
||||
*/
|
||||
async pull(seq?: number): Promise<{ manifest: VaultManifest; files: Map<string, Uint8Array> }> {
|
||||
const manifest = await this.manifest(seq);
|
||||
const files = new Map<string, Uint8Array>();
|
||||
for (const entry of manifest.entries) files.set(entry.path, await this.readEntry(entry));
|
||||
return { manifest, files };
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop every version not in `keep`, and let the relay delete the objects
|
||||
* only those versions used. `keep` must include the current head; the
|
||||
* relay refuses with SEQ_CONFLICT otherwise, which is also what a
|
||||
* keep-list computed before another device's commit runs into.
|
||||
*/
|
||||
async prune(keep: number[]): Promise<VaultPruneResult> {
|
||||
const res = await this.transport.prune(this.keys.vaultId, await this.sign({ keep }));
|
||||
return {
|
||||
removedVersions: res.removedVersions,
|
||||
removedObjects: res.removedObjects,
|
||||
freedBytes: res.freedBytes,
|
||||
};
|
||||
}
|
||||
|
||||
private async openRow(row: VaultLogEntry): Promise<VaultManifest> {
|
||||
const bytes = await this.transport.get(this.keys.vaultId, row.manifest);
|
||||
return openManifest(this.crypto, this.keys.contentKey, this.keys.vaultId, row.manifest, bytes);
|
||||
}
|
||||
|
||||
/** Version history, newest last. */
|
||||
async history(limit?: number): Promise<VaultLog> {
|
||||
return this.transport.log(this.keys.vaultId, limit);
|
||||
}
|
||||
}
|
||||
|
||||
/** A few files changed, for `VaultClient.edit`. */
|
||||
export interface VaultEdit {
|
||||
/** Files to add, or to replace at the same path. */
|
||||
put?: VaultFile[];
|
||||
/** Paths to drop. A path that is not there is ignored. */
|
||||
remove?: string[];
|
||||
}
|
||||
|
||||
/** The relay's "someone committed first" — the one failure worth retrying. */
|
||||
function isSeqConflict(e: unknown): boolean {
|
||||
return e instanceof Error && /SEQ_CONFLICT/.test(e.message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the index for a version you already hold in plaintext — after a
|
||||
* restore, say, so the first push from a fresh device needs no download.
|
||||
*/
|
||||
export function vaultIndexFrom(
|
||||
vaultId: string,
|
||||
manifest: VaultManifest,
|
||||
files: Map<string, Uint8Array>,
|
||||
): VaultIndex {
|
||||
const entries: Record<string, VaultIndexEntry> = {};
|
||||
for (const entry of manifest.entries) {
|
||||
const bytes = files.get(entry.path);
|
||||
if (bytes) entries[entry.path] = { sha256: toHex(sha256(bytes)), entry };
|
||||
}
|
||||
return { vaultId, seq: manifest.seq, entries };
|
||||
}
|
||||
|
||||
/**
|
||||
* Would committing `next` publish the same collection as `head`?
|
||||
*
|
||||
* Compared as a set by path, field by field, rather than by JSON: order of
|
||||
* files is not meaningful, and a reader's view of an entry is exactly these
|
||||
* fields.
|
||||
*/
|
||||
function sameEntries(head: VaultEntry[], next: VaultEntry[]): boolean {
|
||||
if (head.length !== next.length) return false;
|
||||
const byPath = new Map(head.map((e) => [e.path, e]));
|
||||
if (byPath.size !== head.length) return false;
|
||||
for (const e of next) {
|
||||
const h = byPath.get(e.path);
|
||||
if (
|
||||
!h ||
|
||||
h.hash !== e.hash ||
|
||||
h.size !== e.size ||
|
||||
h.mode !== e.mode ||
|
||||
h.enc !== e.enc ||
|
||||
(h.parts ?? []).join(',') !== (e.parts ?? []).join(',')
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
byPath.delete(e.path);
|
||||
}
|
||||
return byPath.size === 0;
|
||||
}
|
||||
|
||||
function sameBytes(a: Uint8Array, b: Uint8Array): boolean {
|
||||
if (a.length !== b.length) return false;
|
||||
for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
|
||||
|
||||
@@ -16,9 +16,34 @@
|
||||
|
||||
import { sha256 } from '@noble/hashes/sha2.js';
|
||||
import type { CryptoProvider } from '@shade/core';
|
||||
import type { VaultManifest } from './types.js';
|
||||
import type { VaultEntry, VaultEntryEncoding, VaultManifest } from './types.js';
|
||||
|
||||
const NONCE_LEN = 12;
|
||||
const TAG_LEN = 16;
|
||||
|
||||
/**
|
||||
* Largest stored (post-compression) slice sealed as one object: 4 MiB.
|
||||
*
|
||||
* The relay's per-object ceiling defaults to 8 MiB, and a file used to be
|
||||
* exactly one object — so a 9 MB PDF simply could not be backed up. Splitting
|
||||
* at 4 MiB leaves headroom under that ceiling for the nonce and tag, keeps a
|
||||
* single upload short enough to retry cheaply on a phone, and is part of the
|
||||
* wire contract: a Kotlin writer must split at the same boundary, or the two
|
||||
* would produce manifests the other cannot reproduce in a vector test.
|
||||
*/
|
||||
export const VAULT_CHUNK_SIZE = 4 * 1024 * 1024;
|
||||
|
||||
/**
|
||||
* Ceiling on an inflated manifest, as a defence against a decompression bomb.
|
||||
*
|
||||
* Every manifest is sealed under our own key, so a bomb could only come from
|
||||
* a device that already holds that key — but an accident (a corrupted write,
|
||||
* a buggy port) should fail with a message, not by exhausting memory.
|
||||
*/
|
||||
const MAX_MANIFEST_BYTES = 256 * 1024 * 1024;
|
||||
|
||||
/** ASCII "SVM2" — the prefix that marks a compressed v2 manifest. */
|
||||
const MANIFEST_V2_MAGIC = new Uint8Array([0x53, 0x56, 0x4d, 0x32]);
|
||||
|
||||
/** Lowercase hex SHA-256 — the name of an object. */
|
||||
export function objectHash(sealed: Uint8Array): string {
|
||||
@@ -36,7 +61,7 @@ export function objectHash(sealed: Uint8Array): string {
|
||||
* being sealed, so it cannot be known before sealing, and the relay's own
|
||||
* hash check already covers substitution.
|
||||
*/
|
||||
function objectAad(vaultId: string): Uint8Array {
|
||||
export function vaultObjectAad(vaultId: string): Uint8Array {
|
||||
return new TextEncoder().encode(`shade-vault-object-v1|${vaultId}`);
|
||||
}
|
||||
|
||||
@@ -55,7 +80,7 @@ export async function sealObject(
|
||||
const { ciphertext, nonce } = await crypto.aesGcmEncrypt(
|
||||
contentKey,
|
||||
plaintext,
|
||||
objectAad(vaultId),
|
||||
vaultObjectAad(vaultId),
|
||||
);
|
||||
const bytes = new Uint8Array(NONCE_LEN + ciphertext.length);
|
||||
bytes.set(nonce, 0);
|
||||
@@ -77,7 +102,7 @@ export async function openObject(
|
||||
expectedHash: string,
|
||||
bytes: Uint8Array,
|
||||
): Promise<Uint8Array> {
|
||||
if (bytes.length < NONCE_LEN + 16) {
|
||||
if (bytes.length < NONCE_LEN + TAG_LEN) {
|
||||
throw new Error('vault object too short to be a sealed object');
|
||||
}
|
||||
const actual = objectHash(bytes);
|
||||
@@ -88,19 +113,301 @@ export async function openObject(
|
||||
contentKey,
|
||||
bytes.subarray(NONCE_LEN),
|
||||
bytes.subarray(0, NONCE_LEN),
|
||||
objectAad(vaultId),
|
||||
vaultObjectAad(vaultId),
|
||||
);
|
||||
}
|
||||
|
||||
/** A manifest is stored as an ordinary object; this is the JSON step around it. */
|
||||
// ─── Compression ─────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Run bytes through a (De)CompressionStream, refusing to produce more than
|
||||
* `limit` bytes.
|
||||
*
|
||||
* The streams API rather than `node:zlib`: it is the one deflate that exists
|
||||
* in browsers, Bun, Node and Deno alike, so the same client can run in a web
|
||||
* app without a polyfill. It offers no level knob — it compresses at zlib's
|
||||
* default, which is byte-identical to `deflateRawSync` without options and to
|
||||
* `java.util.zip.Deflater(DEFAULT_COMPRESSION, nowrap = true)` on the JVM. The
|
||||
* difference to level 9 on text is a percent or two; portability wins.
|
||||
*/
|
||||
async function pump(
|
||||
bytes: Uint8Array,
|
||||
stream: CompressionStream | DecompressionStream,
|
||||
limit: number,
|
||||
): Promise<Uint8Array> {
|
||||
const writer = stream.writable.getWriter();
|
||||
// Not awaited before reading: a stream applies backpressure, so waiting for
|
||||
// the write to drain before anyone reads would deadlock on large inputs.
|
||||
// Its failure surfaces through the reader below, so swallowing it here only
|
||||
// prevents an unhandled-rejection warning.
|
||||
const written = writer
|
||||
.write(bytes as unknown as Uint8Array<ArrayBuffer>)
|
||||
.then(() => writer.close())
|
||||
.catch(() => {});
|
||||
const reader = stream.readable.getReader();
|
||||
const chunks: Uint8Array[] = [];
|
||||
let total = 0;
|
||||
for (;;) {
|
||||
const { value, done } = await reader.read();
|
||||
if (done) break;
|
||||
total += value.length;
|
||||
if (total > limit) {
|
||||
await reader.cancel().catch(() => {});
|
||||
throw new Error(`vault inflate exceeded ${limit} bytes`);
|
||||
}
|
||||
chunks.push(value);
|
||||
}
|
||||
await written;
|
||||
return concatBytes(chunks, total);
|
||||
}
|
||||
|
||||
/** Raw DEFLATE (RFC 1951) — no zlib or gzip header, which a port would have to strip. */
|
||||
export async function deflateRaw(bytes: Uint8Array): Promise<Uint8Array> {
|
||||
return pump(bytes, new CompressionStream('deflate-raw'), Number.MAX_SAFE_INTEGER);
|
||||
}
|
||||
|
||||
/** Inverse of `deflateRaw`, refusing output longer than `limit`. */
|
||||
export async function inflateRaw(bytes: Uint8Array, limit: number): Promise<Uint8Array> {
|
||||
try {
|
||||
return await pump(bytes, new DecompressionStream('deflate-raw'), limit);
|
||||
} catch (e) {
|
||||
// The streams API rejects corrupt input with an empty message in some
|
||||
// runtimes, which would surface as "Error: " with nothing to go on.
|
||||
const why = (e as Error)?.message || 'corrupt deflate stream';
|
||||
throw new Error(`vault inflate failed: ${why}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Does this file start with the signature of a format that is already
|
||||
* compressed?
|
||||
*
|
||||
* Purely a CPU saving: the ≤95 % rule below would reject a JPEG anyway, but
|
||||
* only after deflating every byte of it. The list is part of the contract so
|
||||
* that a port makes the same choices and produces the same `enc` on the same
|
||||
* input — PNG, JPEG, WebP ("RIFF"…"WEBP"), MP4/MOV/HEIC ("ftyp" at offset 4),
|
||||
* GIF, gzip and zip ("PK", which also covers docx/xlsx/jar/apk).
|
||||
*/
|
||||
export function looksCompressed(b: Uint8Array): boolean {
|
||||
const at = (offset: number, sig: number[]): boolean =>
|
||||
b.length >= offset + sig.length && sig.every((v, i) => b[offset + i] === v);
|
||||
return (
|
||||
at(0, [0x89, 0x50, 0x4e, 0x47]) || // PNG
|
||||
at(0, [0xff, 0xd8, 0xff]) || // JPEG
|
||||
(at(0, [0x52, 0x49, 0x46, 0x46]) && at(8, [0x57, 0x45, 0x42, 0x50])) || // RIFF....WEBP
|
||||
at(4, [0x66, 0x74, 0x79, 0x70]) || // ....ftyp (MP4 family)
|
||||
at(0, [0x47, 0x49, 0x46, 0x38]) || // GIF8
|
||||
at(0, [0x1f, 0x8b]) || // gzip
|
||||
at(0, [0x50, 0x4b]) // PK (zip)
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Entries ─────────────────────────────────────────────────
|
||||
|
||||
/** A file's bytes as they will be stored, before sealing. */
|
||||
export interface PackedEntry {
|
||||
/** Set only when the stored bytes are deflate-raw of the plaintext. */
|
||||
enc?: VaultEntryEncoding;
|
||||
/** The stored bytes: the plaintext, or its deflate-raw. */
|
||||
stored: Uint8Array;
|
||||
/** `stored`, split into slices of at most the chunk size. Never empty. */
|
||||
chunks: Uint8Array[];
|
||||
}
|
||||
|
||||
export interface PackOptions {
|
||||
/**
|
||||
* Override the slice size. Internal: exists so tests and cross-language
|
||||
* vectors can exercise multi-part entries without megabytes of fixture.
|
||||
* Production writers must use `VAULT_CHUNK_SIZE`.
|
||||
*/
|
||||
chunkSize?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Turn a file's plaintext into the slices that get sealed — deterministic,
|
||||
* and the half of the format a port has to reproduce byte for byte.
|
||||
*
|
||||
* Compression is kept only when it saves at least 5 %, written as the integer
|
||||
* test `compressed * 20 <= plain * 19` so no implementation can disagree with
|
||||
* another over floating-point rounding at the boundary. Below that, the
|
||||
* reader's inflate pass costs more than the bytes it saves.
|
||||
*
|
||||
* Compression runs over the whole file and THEN the result is split, not per
|
||||
* chunk: a reader concatenates the opened parts and inflates once. That keeps
|
||||
* the dictionary spanning the whole file, and means `parts` are opaque slices
|
||||
* with no framing of their own.
|
||||
*/
|
||||
export async function packEntry(plaintext: Uint8Array, opts: PackOptions = {}): Promise<PackedEntry> {
|
||||
const chunkSize = opts.chunkSize ?? VAULT_CHUNK_SIZE;
|
||||
if (!Number.isInteger(chunkSize) || chunkSize < 1) {
|
||||
throw new Error(`vault chunk size must be a positive integer, got ${chunkSize}`);
|
||||
}
|
||||
|
||||
let stored = plaintext;
|
||||
let enc: VaultEntryEncoding | undefined;
|
||||
if (plaintext.length > 0 && !looksCompressed(plaintext)) {
|
||||
const deflated = await deflateRaw(plaintext);
|
||||
if (deflated.length * 20 <= plaintext.length * 19) {
|
||||
stored = deflated;
|
||||
enc = 'deflate-raw';
|
||||
}
|
||||
}
|
||||
|
||||
// An empty file is still one (empty) object, exactly as in v1: an entry
|
||||
// always names something the relay holds, so a reader never special-cases.
|
||||
const chunks: Uint8Array[] = [];
|
||||
for (let i = 0; i < stored.length || chunks.length === 0; i += chunkSize) {
|
||||
chunks.push(stored.subarray(i, i + chunkSize));
|
||||
}
|
||||
return enc ? { enc, stored, chunks } : { stored, chunks };
|
||||
}
|
||||
|
||||
/** The manifest fields that locate a file's ciphertext. */
|
||||
export interface EntryLocator {
|
||||
hash: string;
|
||||
parts?: string[];
|
||||
enc?: VaultEntryEncoding;
|
||||
}
|
||||
|
||||
/** Shape an entry's locator from its sealed parts (one part → no `parts`). */
|
||||
export function entryLocator(packed: PackedEntry, sealed: SealedObject[]): EntryLocator {
|
||||
const locator: EntryLocator = { hash: sealed[0]!.hash };
|
||||
if (sealed.length > 1) locator.parts = sealed.map((o) => o.hash);
|
||||
if (packed.enc) locator.enc = packed.enc;
|
||||
return locator;
|
||||
}
|
||||
|
||||
/** Pack and seal one file: the locator for its manifest entry, and the objects to upload. */
|
||||
export async function sealEntry(
|
||||
crypto: CryptoProvider,
|
||||
contentKey: Uint8Array,
|
||||
vaultId: string,
|
||||
plaintext: Uint8Array,
|
||||
opts: PackOptions = {},
|
||||
): Promise<{ locator: EntryLocator; objects: SealedObject[] }> {
|
||||
const packed = await packEntry(plaintext, opts);
|
||||
const objects: SealedObject[] = [];
|
||||
for (const chunk of packed.chunks) {
|
||||
objects.push(await sealObject(crypto, contentKey, vaultId, chunk));
|
||||
}
|
||||
return { locator: entryLocator(packed, objects), objects };
|
||||
}
|
||||
|
||||
/**
|
||||
* Every object an entry needs, in read order.
|
||||
*
|
||||
* This is also what a commit's signed `hashes` must list. The relay cannot
|
||||
* read manifests, so `hashes` is the only way it learns what a version
|
||||
* references — for the missing-object check, and since prune, for deciding
|
||||
* what is still in use. A part left out of it may be garbage-collected.
|
||||
*/
|
||||
export function entryObjectHashes(entry: Pick<VaultEntry, 'hash' | 'parts'>): string[] {
|
||||
return entry.parts && entry.parts.length > 0 ? entry.parts : [entry.hash];
|
||||
}
|
||||
|
||||
/**
|
||||
* Reassemble a file from its fetched objects, in `entryObjectHashes` order:
|
||||
* verify and open each part, concatenate, inflate if `enc`, check the size.
|
||||
*
|
||||
* Order is guarded by the manifest: `parts` sits inside the sealed manifest,
|
||||
* and each fetched object must hash to the name in its slot. The size check
|
||||
* covers the rest — every part authenticates on its own, so an entry whose
|
||||
* part list lost or gained an element would otherwise open cleanly into a
|
||||
* truncated or padded file.
|
||||
*/
|
||||
export async function openEntryBytes(
|
||||
crypto: CryptoProvider,
|
||||
contentKey: Uint8Array,
|
||||
vaultId: string,
|
||||
entry: VaultEntry,
|
||||
objects: Uint8Array[],
|
||||
): Promise<Uint8Array> {
|
||||
const hashes = entryObjectHashes(entry);
|
||||
if (entry.parts && entry.parts.length > 0 && entry.parts[0] !== entry.hash) {
|
||||
throw new Error(`vault entry ${entry.path}: hash must equal parts[0]`);
|
||||
}
|
||||
if (objects.length !== hashes.length) {
|
||||
throw new Error(
|
||||
`vault entry ${entry.path}: expected ${hashes.length} object(s), got ${objects.length}`,
|
||||
);
|
||||
}
|
||||
|
||||
const opened: Uint8Array[] = [];
|
||||
let storedLen = 0;
|
||||
for (let i = 0; i < hashes.length; i++) {
|
||||
const plain = await openObject(crypto, contentKey, vaultId, hashes[i]!, objects[i]!);
|
||||
opened.push(plain);
|
||||
storedLen += plain.length;
|
||||
}
|
||||
const stored = concatBytes(opened, storedLen);
|
||||
|
||||
let plaintext: Uint8Array;
|
||||
if (entry.enc === undefined) {
|
||||
plaintext = stored;
|
||||
} else if (entry.enc === 'deflate-raw') {
|
||||
plaintext = await inflateRaw(stored, entry.size);
|
||||
} else {
|
||||
// Same reasoning as an unknown manifest version: guessing would hand back
|
||||
// bytes that look like the file and are not.
|
||||
throw new Error(`vault entry ${entry.path}: unsupported encoding ${String(entry.enc)}`);
|
||||
}
|
||||
|
||||
if (plaintext.length !== entry.size) {
|
||||
throw new Error(
|
||||
`vault entry ${entry.path}: size mismatch, manifest says ${entry.size}, got ${plaintext.length}`,
|
||||
);
|
||||
}
|
||||
return plaintext;
|
||||
}
|
||||
|
||||
// ─── Manifests ───────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* A manifest's plaintext before sealing.
|
||||
*
|
||||
* v1 is bare UTF-8 JSON. v2 is "SVM2" followed by deflate-raw of that JSON:
|
||||
* a workspace manifest is hundreds of near-identical path/hash lines, which
|
||||
* compress roughly 2:1 even though the hashes are random, and a new manifest
|
||||
* object is written on every single push. The magic, rather than sniffing for
|
||||
* `{`, makes the format self-describing — and a v1-only reader fails on it
|
||||
* loudly at JSON.parse instead of misreading it.
|
||||
*
|
||||
* The version field decides the container, so the same function writes the
|
||||
* v1 vectors that keep old manifests readable.
|
||||
*/
|
||||
export async function encodeManifest(manifest: VaultManifest): Promise<Uint8Array> {
|
||||
const json = new TextEncoder().encode(JSON.stringify(manifest));
|
||||
if (manifest.version === 1) return json;
|
||||
const deflated = await deflateRaw(json);
|
||||
return concatBytes([MANIFEST_V2_MAGIC, deflated], MANIFEST_V2_MAGIC.length + deflated.length);
|
||||
}
|
||||
|
||||
/** Parse a manifest's plaintext, v1 or v2, refusing any other version. */
|
||||
export async function decodeManifest(plain: Uint8Array): Promise<VaultManifest> {
|
||||
const isV2 =
|
||||
plain.length >= MANIFEST_V2_MAGIC.length &&
|
||||
MANIFEST_V2_MAGIC.every((v, i) => plain[i] === v);
|
||||
const json = isV2
|
||||
? await inflateRaw(plain.subarray(MANIFEST_V2_MAGIC.length), MAX_MANIFEST_BYTES)
|
||||
: plain;
|
||||
const parsed = JSON.parse(new TextDecoder().decode(json)) as VaultManifest;
|
||||
if (parsed.version !== 1 && parsed.version !== 2) {
|
||||
// Refusing beats guessing: a future manifest may mean a file the reader
|
||||
// cannot represent, and silently dropping it would lose data on the next
|
||||
// commit made from this client.
|
||||
throw new Error(`unsupported vault manifest version: ${String(parsed.version)}`);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
/** A manifest is stored as an ordinary object; this is the encoding step around it. */
|
||||
export async function sealManifest(
|
||||
crypto: CryptoProvider,
|
||||
contentKey: Uint8Array,
|
||||
vaultId: string,
|
||||
manifest: VaultManifest,
|
||||
): Promise<SealedObject> {
|
||||
const json = new TextEncoder().encode(JSON.stringify(manifest));
|
||||
return sealObject(crypto, contentKey, vaultId, json);
|
||||
return sealObject(crypto, contentKey, vaultId, await encodeManifest(manifest));
|
||||
}
|
||||
|
||||
export async function openManifest(
|
||||
@@ -110,15 +417,18 @@ export async function openManifest(
|
||||
expectedHash: string,
|
||||
bytes: Uint8Array,
|
||||
): Promise<VaultManifest> {
|
||||
const plain = await openObject(crypto, contentKey, vaultId, expectedHash, bytes);
|
||||
const parsed = JSON.parse(new TextDecoder().decode(plain)) as VaultManifest;
|
||||
if (parsed.version !== 1) {
|
||||
// Refusing beats guessing: a future manifest may mean a file the reader
|
||||
// cannot represent, and silently dropping it would lose data on the next
|
||||
// commit made from this client.
|
||||
throw new Error(`unsupported vault manifest version: ${parsed.version}`);
|
||||
return decodeManifest(await openObject(crypto, contentKey, vaultId, expectedHash, bytes));
|
||||
}
|
||||
return parsed;
|
||||
|
||||
function concatBytes(chunks: Uint8Array[], total: number): Uint8Array {
|
||||
if (chunks.length === 1 && chunks[0]!.length === total) return chunks[0]!;
|
||||
const out = new Uint8Array(total);
|
||||
let offset = 0;
|
||||
for (const c of chunks) {
|
||||
out.set(c, offset);
|
||||
offset += c.length;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Lowercase hex of arbitrary bytes — used for vaultId and pubkeys on the wire. */
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
|
||||
import { fromBase64 } from '@shade/core';
|
||||
import type { VaultTransport } from './client.js';
|
||||
import type { VaultLog } from './types.js';
|
||||
import type { VaultLog, VaultPruneResult } from './types.js';
|
||||
|
||||
type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
|
||||
|
||||
@@ -75,6 +75,16 @@ export class HttpVaultTransport implements VaultTransport {
|
||||
if (!res.ok) return this.fail(res, 'commit');
|
||||
return (await res.json()) as { seq: number };
|
||||
}
|
||||
|
||||
async prune(vaultId: string, body: unknown): Promise<VaultPruneResult> {
|
||||
const res = await this.fetchImpl(this.url(`/v1/vault/${vaultId}/prune`), {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
if (!res.ok) return this.fail(res, 'prune');
|
||||
return (await res.json()) as VaultPruneResult;
|
||||
}
|
||||
}
|
||||
|
||||
export { fromBase64 };
|
||||
|
||||
@@ -2,5 +2,5 @@ export * from './types.js';
|
||||
export * from './crypto.js';
|
||||
export * from './client.js';
|
||||
export { MemoryVaultStore } from './store.js';
|
||||
export type { VaultStore } from './store.js';
|
||||
export type { VaultStore, VaultPrunePlan } from './store.js';
|
||||
export { HttpVaultTransport } from './http-transport.js';
|
||||
|
||||
@@ -6,6 +6,8 @@
|
||||
* HEAD /v1/vault/:vaultId/object/:hash → 200 | 404 (have-check)
|
||||
* PUT /v1/vault/:vaultId/object/:hash → { stored } (signed)
|
||||
* POST /v1/vault/:vaultId/commit → { seq } (signed)
|
||||
* POST /v1/vault/:vaultId/prune → { removedVersions, removedObjects,
|
||||
* freedBytes, head } (signed)
|
||||
*
|
||||
* Auth is the same TOFU-Ed25519 scheme the blob primitive uses: the first
|
||||
* signed write pins a pubkey for the vault, and every later write must be
|
||||
@@ -30,10 +32,19 @@ export interface VaultRoutesOptions {
|
||||
maxObjectBytes?: number;
|
||||
/** Whole-vault ceiling. Defaults to 512 MiB. */
|
||||
maxVaultBytes?: number;
|
||||
/**
|
||||
* How long an uploaded-but-never-committed object survives a prune.
|
||||
* Defaults to one hour — long enough for a slow phone to finish a large
|
||||
* push between its first upload and its commit.
|
||||
*/
|
||||
pruneGraceMs?: number;
|
||||
}
|
||||
|
||||
const DEFAULT_MAX_OBJECT = 8 * 1024 * 1024;
|
||||
const DEFAULT_MAX_VAULT = 512 * 1024 * 1024;
|
||||
const DEFAULT_PRUNE_GRACE = 60 * 60 * 1000;
|
||||
/** A keep-list longer than this is not a retention policy, it is a mistake. */
|
||||
const MAX_KEEP = 100_000;
|
||||
|
||||
function fail(code: string, message: string, status: ContentfulStatusCode) {
|
||||
return { body: { error: { code, message } }, status };
|
||||
@@ -47,6 +58,7 @@ export function createVaultRoutes(
|
||||
const app = new Hono();
|
||||
const maxObject = options.maxObjectBytes ?? DEFAULT_MAX_OBJECT;
|
||||
const maxVault = options.maxVaultBytes ?? DEFAULT_MAX_VAULT;
|
||||
const pruneGrace = options.pruneGraceMs ?? DEFAULT_PRUNE_GRACE;
|
||||
|
||||
/**
|
||||
* Check a signed request against the vault's pinned key, pinning it on the
|
||||
@@ -208,19 +220,89 @@ export function createVaultRoutes(
|
||||
return c.json({ ...f.body, missing: missing.slice(0, 20) }, f.status);
|
||||
}
|
||||
|
||||
await store.appendLog(vaultId, {
|
||||
// The signed `hashes` plus the manifest are everything this version
|
||||
// references. Recording them is what lets prune collect garbage later
|
||||
// without ever reading a manifest — so a client that leaves a part out of
|
||||
// `hashes` is telling the relay that part may be deleted.
|
||||
const refs = [...new Set([body.manifest, ...hashes])];
|
||||
await store.appendLog(
|
||||
vaultId,
|
||||
{
|
||||
seq: body.seq,
|
||||
manifest: body.manifest,
|
||||
at: typeof body.at === 'number' ? body.at : Date.now(),
|
||||
bytes: await store.usage(vaultId),
|
||||
});
|
||||
},
|
||||
refs,
|
||||
);
|
||||
|
||||
return c.json({ seq: body.seq, head: body.seq });
|
||||
});
|
||||
|
||||
/**
|
||||
* Retention: drop versions and the objects only they used.
|
||||
*
|
||||
* Without this the log is append-only in the literal sense, and a vault
|
||||
* pushed on every edit grows until it hits the quota and stops accepting
|
||||
* backups — the failure arriving exactly when the user is relying on it.
|
||||
* The client decides the policy (keep the last N, one per day, …) because
|
||||
* only it can read the manifests; the relay just executes a keep-list.
|
||||
*/
|
||||
app.post('/v1/vault/:vaultId/prune', async (c) => {
|
||||
const vaultId = c.req.param('vaultId');
|
||||
if (!ID_REGEX.test(vaultId)) {
|
||||
const f = fail('BAD_REQUEST', 'vaultId must be 64 lowercase hex chars', 400);
|
||||
return c.json(f.body, f.status);
|
||||
}
|
||||
|
||||
const body = (await c.req.json().catch(() => null)) as Record<string, unknown> | null;
|
||||
const keep = body?.keep;
|
||||
if (
|
||||
!body ||
|
||||
!Array.isArray(keep) ||
|
||||
keep.length > MAX_KEEP ||
|
||||
!keep.every((s) => Number.isSafeInteger(s) && (s as number) >= 0)
|
||||
) {
|
||||
const f = fail('BAD_REQUEST', 'expected { keep: number[], signedAt, signature }', 400);
|
||||
return c.json(f.body, f.status);
|
||||
}
|
||||
|
||||
// Deliberately not `authorize`'s TOFU path: a prune must never be the
|
||||
// write that pins an owner. On a vault nobody has written to there is
|
||||
// nothing to prune, and accepting it would hand the vault to whoever
|
||||
// asked first.
|
||||
if (!(await store.getOwner(vaultId))) {
|
||||
const f = fail('NOT_FOUND', 'no such vault', 404);
|
||||
return c.json(f.body, f.status);
|
||||
}
|
||||
const auth = await authorize(vaultId, body);
|
||||
if (!auth.ok) {
|
||||
const f = fail(auth.code, auth.message, auth.status);
|
||||
return c.json(f.body, f.status);
|
||||
}
|
||||
|
||||
const head = await store.head(vaultId);
|
||||
if (!(keep as number[]).includes(head)) {
|
||||
// Pruning the head would leave the vault restoring to something other
|
||||
// than what was last backed up. It is also what a keep-list computed
|
||||
// before another device's commit looks like — so this is a conflict the
|
||||
// client resolves by re-reading, not a malformed request. A replayed
|
||||
// prune hits the same wall as soon as anything has been committed.
|
||||
const f = fail('SEQ_CONFLICT', `keep must include the current head ${head}`, 409);
|
||||
return c.json({ ...f.body, head }, f.status);
|
||||
}
|
||||
|
||||
const result = await store.prune(vaultId, {
|
||||
keep: keep as number[],
|
||||
upTo: head,
|
||||
protectSince: Date.now() - pruneGrace,
|
||||
});
|
||||
return c.json({ ...result, head });
|
||||
});
|
||||
|
||||
return app;
|
||||
}
|
||||
|
||||
export type { VaultStore } from './store.js';
|
||||
export type { VaultStore, VaultPrunePlan } from './store.js';
|
||||
export { MemoryVaultStore } from './store.js';
|
||||
export type { VaultManifest };
|
||||
|
||||
@@ -6,7 +6,42 @@
|
||||
* what makes a SQLite, Postgres or object-store implementation equivalent.
|
||||
*/
|
||||
|
||||
import type { VaultLogEntry } from './types.js';
|
||||
import type { VaultLogEntry, VaultPruneResult } from './types.js';
|
||||
|
||||
/**
|
||||
* What the relay is asked to forget, already checked by the route.
|
||||
*
|
||||
* The relay cannot read a manifest, so it cannot know on its own which
|
||||
* objects a version uses. It knows because every commit since prune existed
|
||||
* hands the store its `refs` — the signed `hashes` plus the manifest object —
|
||||
* and that list is what garbage collection is computed from.
|
||||
*
|
||||
* **Versions committed before ref tracking have no list.** Their objects are
|
||||
* "pinned": every object present when such an entry was appended (or, for a
|
||||
* SQLite database, when it was migrated) is treated as referenced for as long
|
||||
* as any untracked entry remains in the log. Pinning is coarse — it protects
|
||||
* objects the old entry may not use — but it is the only safe reading of "we
|
||||
* do not know", and it is self-limiting: once the last untracked version has
|
||||
* been pruned, no unknown reference set is left, the pins are dropped and
|
||||
* those objects are collected like any other.
|
||||
*/
|
||||
export interface VaultPrunePlan {
|
||||
/** Sequence numbers to keep. The route has checked that the head is among them. */
|
||||
keep: readonly number[];
|
||||
/**
|
||||
* Only entries with `seq <= upTo` may be removed — the head the route saw.
|
||||
* A commit that lands between that check and the prune is newer, and must
|
||||
* survive even though it is not in `keep`.
|
||||
*/
|
||||
upTo: number;
|
||||
/**
|
||||
* Epoch millis. An object no version has ever referenced, stored after
|
||||
* this, is left alone: it is most likely an upload whose commit is still
|
||||
* on its way, and deleting it would fail that push with MISSING_OBJECTS.
|
||||
* Objects that a removed version referenced get no such grace.
|
||||
*/
|
||||
protectSince: number;
|
||||
}
|
||||
|
||||
export interface VaultStore {
|
||||
/** Ed25519 pubkey pinned on first write (TOFU), or null for a fresh vault. */
|
||||
@@ -21,7 +56,19 @@ export interface VaultStore {
|
||||
head(vaultId: string): Promise<number>;
|
||||
/** Newest last. `limit` counts back from the head. */
|
||||
log(vaultId: string, limit?: number): Promise<VaultLogEntry[]>;
|
||||
appendLog(vaultId: string, entry: VaultLogEntry): Promise<void>;
|
||||
/**
|
||||
* Append a version. `refs` is every object hash it references, manifest
|
||||
* included; the routes always pass it. Omitting it records the entry as
|
||||
* untracked, with the pinning described on `VaultPrunePlan` — that is how
|
||||
* entries from before ref tracking behave, and how tests simulate them.
|
||||
*/
|
||||
appendLog(vaultId: string, entry: VaultLogEntry, refs?: readonly string[]): Promise<void>;
|
||||
|
||||
/**
|
||||
* Remove log entries and garbage-collect the objects nothing left uses.
|
||||
* Must be atomic with respect to other writes to the same vault.
|
||||
*/
|
||||
prune(vaultId: string, plan: VaultPrunePlan): Promise<VaultPruneResult>;
|
||||
|
||||
/** Total stored bytes, for quota decisions. */
|
||||
usage(vaultId: string): Promise<number>;
|
||||
@@ -36,6 +83,12 @@ export class MemoryVaultStore implements VaultStore {
|
||||
private owners = new Map<string, Uint8Array>();
|
||||
private objects = new Map<string, Map<string, Uint8Array>>();
|
||||
private logs = new Map<string, VaultLogEntry[]>();
|
||||
/** Per vault: seq → referenced hashes, or null for an untracked entry. */
|
||||
private refs = new Map<string, Map<number, Set<string> | null>>();
|
||||
/** Per vault: objects an untracked entry may reference. */
|
||||
private pinned = new Map<string, Set<string>>();
|
||||
/** Per vault: when each object was first stored, for the prune grace. */
|
||||
private storedAt = new Map<string, Map<string, number>>();
|
||||
|
||||
async getOwner(vaultId: string): Promise<Uint8Array | null> {
|
||||
return this.owners.get(vaultId) ?? null;
|
||||
@@ -59,7 +112,15 @@ export class MemoryVaultStore implements VaultStore {
|
||||
}
|
||||
|
||||
async putObject(vaultId: string, hash: string, bytes: Uint8Array): Promise<void> {
|
||||
this.bucket(vaultId).set(hash, bytes);
|
||||
const bucket = this.bucket(vaultId);
|
||||
if (bucket.has(hash)) return;
|
||||
bucket.set(hash, bytes);
|
||||
let times = this.storedAt.get(vaultId);
|
||||
if (!times) {
|
||||
times = new Map();
|
||||
this.storedAt.set(vaultId, times);
|
||||
}
|
||||
times.set(hash, Date.now());
|
||||
}
|
||||
|
||||
async getObject(vaultId: string, hash: string): Promise<Uint8Array | null> {
|
||||
@@ -76,10 +137,76 @@ export class MemoryVaultStore implements VaultStore {
|
||||
return limit === undefined ? [...l] : l.slice(Math.max(0, l.length - limit));
|
||||
}
|
||||
|
||||
async appendLog(vaultId: string, entry: VaultLogEntry): Promise<void> {
|
||||
async appendLog(vaultId: string, entry: VaultLogEntry, refs?: readonly string[]): Promise<void> {
|
||||
const l = this.logs.get(vaultId) ?? [];
|
||||
if (l.some((e) => e.seq === entry.seq)) {
|
||||
// Mirrors the SQLite primary key: two rows with one seq would make
|
||||
// history ambiguous, and prune would not know which refs to drop.
|
||||
throw new Error(`vault ${vaultId} already has seq ${entry.seq}`);
|
||||
}
|
||||
l.push(entry);
|
||||
this.logs.set(vaultId, l);
|
||||
|
||||
let byseq = this.refs.get(vaultId);
|
||||
if (!byseq) {
|
||||
byseq = new Map();
|
||||
this.refs.set(vaultId, byseq);
|
||||
}
|
||||
if (refs) {
|
||||
byseq.set(entry.seq, new Set(refs));
|
||||
} else {
|
||||
// An untracked entry can only reference what was here when it was
|
||||
// committed — so pin exactly that.
|
||||
byseq.set(entry.seq, null);
|
||||
const pins = this.pinned.get(vaultId) ?? new Set<string>();
|
||||
for (const h of this.bucket(vaultId).keys()) pins.add(h);
|
||||
this.pinned.set(vaultId, pins);
|
||||
}
|
||||
}
|
||||
|
||||
async prune(vaultId: string, plan: VaultPrunePlan): Promise<VaultPruneResult> {
|
||||
// No await anywhere below: the whole prune runs in one turn of the event
|
||||
// loop, which is what makes it atomic against a concurrent commit.
|
||||
const keep = new Set(plan.keep);
|
||||
const log = this.logs.get(vaultId) ?? [];
|
||||
const byseq = this.refs.get(vaultId) ?? new Map<number, Set<string> | null>();
|
||||
const bucket = this.bucket(vaultId);
|
||||
const times = this.storedAt.get(vaultId) ?? new Map<string, number>();
|
||||
|
||||
const removed = log.filter((e) => e.seq <= plan.upTo && !keep.has(e.seq));
|
||||
const remaining = log.filter((e) => !(e.seq <= plan.upTo && !keep.has(e.seq)));
|
||||
|
||||
const everReferenced = new Set<string>();
|
||||
for (const e of log) {
|
||||
everReferenced.add(e.manifest);
|
||||
for (const h of byseq.get(e.seq) ?? []) everReferenced.add(h);
|
||||
}
|
||||
|
||||
const inUse = new Set<string>();
|
||||
let untrackedRemains = false;
|
||||
for (const e of remaining) {
|
||||
inUse.add(e.manifest);
|
||||
const r = byseq.get(e.seq);
|
||||
if (r === undefined || r === null) untrackedRemains = true;
|
||||
else for (const h of r) inUse.add(h);
|
||||
}
|
||||
if (!untrackedRemains) this.pinned.delete(vaultId);
|
||||
const pins = this.pinned.get(vaultId) ?? new Set<string>();
|
||||
|
||||
let removedObjects = 0;
|
||||
let freedBytes = 0;
|
||||
for (const [hash, bytes] of [...bucket]) {
|
||||
if (inUse.has(hash) || pins.has(hash)) continue;
|
||||
if (!everReferenced.has(hash) && (times.get(hash) ?? 0) > plan.protectSince) continue;
|
||||
bucket.delete(hash);
|
||||
times.delete(hash);
|
||||
removedObjects++;
|
||||
freedBytes += bytes.length;
|
||||
}
|
||||
|
||||
for (const e of removed) byseq.delete(e.seq);
|
||||
this.logs.set(vaultId, remaining);
|
||||
return { removedVersions: removed.length, removedObjects, freedBytes };
|
||||
}
|
||||
|
||||
async usage(vaultId: string): Promise<number> {
|
||||
|
||||
77
packages/shade-vault/src/testing.ts
Normal file
77
packages/shade-vault/src/testing.ts
Normal file
@@ -0,0 +1,77 @@
|
||||
/**
|
||||
* Deterministic sealing, for cross-language test vectors only.
|
||||
*
|
||||
* Production sealing takes its nonce from the `CryptoProvider`, which is the
|
||||
* point: a nonce reused under one content key breaks AES-GCM outright. A
|
||||
* vector, though, has to pin every byte so a Kotlin port can reproduce the
|
||||
* same wire bytes — so this takes the nonce from the caller.
|
||||
*
|
||||
* Lives behind its own export (`@shade/vault/testing`) and is not re-exported
|
||||
* from the package root, so it cannot be picked up by accident from an
|
||||
* autocomplete list next to `sealObject`.
|
||||
*/
|
||||
|
||||
import {
|
||||
entryLocator,
|
||||
objectHash,
|
||||
packEntry,
|
||||
vaultObjectAad,
|
||||
type EntryLocator,
|
||||
type PackOptions,
|
||||
type PackedEntry,
|
||||
type SealedObject,
|
||||
} from './crypto.js';
|
||||
|
||||
const NONCE_LEN = 12;
|
||||
|
||||
/** `sealObject` with a caller-chosen nonce. Never use outside vectors and tests. */
|
||||
export async function sealObjectWithNonce(
|
||||
contentKey: Uint8Array,
|
||||
vaultId: string,
|
||||
plaintext: Uint8Array,
|
||||
nonce: Uint8Array,
|
||||
): Promise<SealedObject> {
|
||||
if (nonce.length !== NONCE_LEN) throw new Error(`nonce must be ${NONCE_LEN} bytes`);
|
||||
const subtle = globalThis.crypto.subtle;
|
||||
const key = await subtle.importKey(
|
||||
'raw',
|
||||
contentKey as unknown as ArrayBuffer,
|
||||
'AES-GCM',
|
||||
false,
|
||||
['encrypt'],
|
||||
);
|
||||
const ct = new Uint8Array(
|
||||
await subtle.encrypt(
|
||||
{
|
||||
name: 'AES-GCM',
|
||||
iv: nonce as unknown as ArrayBuffer,
|
||||
additionalData: vaultObjectAad(vaultId) as unknown as ArrayBuffer,
|
||||
},
|
||||
key,
|
||||
plaintext as unknown as ArrayBuffer,
|
||||
),
|
||||
);
|
||||
const bytes = new Uint8Array(NONCE_LEN + ct.length);
|
||||
bytes.set(nonce, 0);
|
||||
bytes.set(ct, NONCE_LEN);
|
||||
return { hash: objectHash(bytes), bytes };
|
||||
}
|
||||
|
||||
/**
|
||||
* `sealEntry` with one caller-chosen nonce per part — the same `packEntry`
|
||||
* the real writer uses, so a vector pins the production format, not a copy.
|
||||
*/
|
||||
export async function sealEntryWithNonces(
|
||||
contentKey: Uint8Array,
|
||||
vaultId: string,
|
||||
plaintext: Uint8Array,
|
||||
nonceFor: (partIndex: number) => Uint8Array,
|
||||
opts: PackOptions = {},
|
||||
): Promise<{ packed: PackedEntry; locator: EntryLocator; objects: SealedObject[] }> {
|
||||
const packed = await packEntry(plaintext, opts);
|
||||
const objects: SealedObject[] = [];
|
||||
for (let i = 0; i < packed.chunks.length; i++) {
|
||||
objects.push(await sealObjectWithNonce(contentKey, vaultId, packed.chunks[i]!, nonceFor(i)));
|
||||
}
|
||||
return { packed, locator: entryLocator(packed, objects), objects };
|
||||
}
|
||||
@@ -22,22 +22,50 @@
|
||||
* of that, which is the versioning half of the requirement.
|
||||
*/
|
||||
|
||||
/** One file in a manifest. `hash` names the ciphertext object. */
|
||||
/**
|
||||
* How an entry's stored bytes relate to its plaintext. Absent means stored
|
||||
* as-is; `deflate-raw` means RFC 1951 raw DEFLATE (no zlib/gzip header).
|
||||
*/
|
||||
export type VaultEntryEncoding = 'deflate-raw';
|
||||
|
||||
/**
|
||||
* One file in a manifest. `hash` names the ciphertext object.
|
||||
*
|
||||
* v2 adds two optional fields, and an entry without them is exactly a v1
|
||||
* entry — so a v2 reader needs no separate path for old manifests:
|
||||
*
|
||||
* - `enc`: the stored bytes are compressed. Set only when that saved at least
|
||||
* 5 %, so a reader can never assume it.
|
||||
* - `parts`: the stored bytes were split into several objects (files larger
|
||||
* than one 4 MiB chunk). Listed in order; `hash` is then `parts[0]`, which
|
||||
* keeps "`hash` names an object the relay holds" true for every entry.
|
||||
*/
|
||||
export interface VaultEntry {
|
||||
/** Path within the collection, as the app understands it. */
|
||||
path: string;
|
||||
/** Lowercase hex SHA-256 of the ciphertext object. */
|
||||
/** Lowercase hex SHA-256 of the (first) ciphertext object. */
|
||||
hash: string;
|
||||
/** Plaintext byte length, for progress reporting and sanity checks. */
|
||||
/**
|
||||
* PLAINTEXT byte length — before compression, whatever `enc` says. Readers
|
||||
* check the reassembled file against it.
|
||||
*/
|
||||
size: number;
|
||||
/** Optional app-defined mode/metadata, opaque to the vault. */
|
||||
mode?: string;
|
||||
/** Present only when the stored bytes are compressed. */
|
||||
enc?: VaultEntryEncoding;
|
||||
/** Present only when there is more than one object; `parts[0] === hash`. */
|
||||
parts?: string[];
|
||||
}
|
||||
|
||||
/** The full contents of a collection at one point in time. */
|
||||
export interface VaultManifest {
|
||||
/** Schema version — a client that does not know it must refuse, not guess. */
|
||||
version: 1;
|
||||
/**
|
||||
* Schema version — a client that does not know it must refuse, not guess.
|
||||
* 1: bare JSON. 2: "SVM2" + deflate-raw(JSON), entries may carry `enc` and
|
||||
* `parts`. Writers emit 2; readers accept both.
|
||||
*/
|
||||
version: 1 | 2;
|
||||
/** Monotonic, assigned by the client and checked by the relay. */
|
||||
seq: number;
|
||||
/** Epoch millis when the commit was made. */
|
||||
@@ -64,6 +92,48 @@ export interface VaultLog {
|
||||
head: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* What the client remembers about its own last push, so the next one can skip
|
||||
* re-reading the relay.
|
||||
*
|
||||
* Without it, deciding "is this file unchanged?" means downloading and
|
||||
* decrypting the previous version of it — on a push that runs after every
|
||||
* edit, that is the whole workspace pulled down to upload three lines. With
|
||||
* it, an unchanged file is recognised by its plaintext SHA-256 and reuses the
|
||||
* entry (and objects) it already has, with no network at all.
|
||||
*
|
||||
* Only trusted when `vaultId` matches and `seq` is still the relay's head:
|
||||
* after another device commits, the entries no longer describe the head, and
|
||||
* the push falls back to reading it. Plain JSON on purpose — callers persist
|
||||
* it to disk next to the files it describes.
|
||||
*
|
||||
* It holds plaintext hashes of the user's files, so store it where the files
|
||||
* themselves live, never on the relay.
|
||||
*/
|
||||
export interface VaultIndex {
|
||||
vaultId: string;
|
||||
/** The version these entries describe. */
|
||||
seq: number;
|
||||
/** Keyed by path. */
|
||||
entries: Record<string, VaultIndexEntry>;
|
||||
}
|
||||
|
||||
export interface VaultIndexEntry {
|
||||
/** Lowercase hex SHA-256 of the file's plaintext. */
|
||||
sha256: string;
|
||||
entry: VaultEntry;
|
||||
}
|
||||
|
||||
/** What `POST /v1/vault/:id/prune` returns. */
|
||||
export interface VaultPruneResult {
|
||||
/** Log entries removed. */
|
||||
removedVersions: number;
|
||||
/** Objects deleted because no remaining version references them. */
|
||||
removedObjects: number;
|
||||
/** Bytes those objects occupied. */
|
||||
freedBytes: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Error codes clients branch on.
|
||||
*
|
||||
|
||||
714
packages/shade-vault/tests/vault-v2.test.ts
Normal file
714
packages/shade-vault/tests/vault-v2.test.ts
Normal file
@@ -0,0 +1,714 @@
|
||||
/**
|
||||
* Vault v2: compression, multi-part entries, the compressed manifest, the
|
||||
* local index, lazy reads and prune.
|
||||
*
|
||||
* Same rule as vault.test.ts: the client talks to the REAL route handlers.
|
||||
* The counting transport only wraps the HTTP one, so "this push downloaded
|
||||
* nothing" is measured on the actual wire calls, not on a mock's opinion.
|
||||
*/
|
||||
import { describe, test, expect } from 'bun:test';
|
||||
import { SubtleCryptoProvider } from '@shade/crypto-web';
|
||||
import { signPayload } from '@shade/server';
|
||||
import { toBase64 } from '@shade/core';
|
||||
import { createVaultRoutes, type VaultRoutesOptions } from '../src/server.js';
|
||||
import { MemoryVaultStore } from '../src/store.js';
|
||||
import type { VaultStore } from '../src/store.js';
|
||||
import { HttpVaultTransport } from '../src/http-transport.js';
|
||||
import { VaultClient, deriveVaultKeys, vaultIndexFrom } from '../src/client.js';
|
||||
import type { VaultKeys, VaultTransport } from '../src/client.js';
|
||||
import {
|
||||
VAULT_CHUNK_SIZE,
|
||||
decodeManifest,
|
||||
entryObjectHashes,
|
||||
openEntryBytes,
|
||||
openObject,
|
||||
packEntry,
|
||||
sealManifest,
|
||||
sealObject,
|
||||
} from '../src/crypto.js';
|
||||
import type { VaultLog, VaultManifest, VaultPruneResult } from '../src/types.js';
|
||||
|
||||
const crypto = new SubtleCryptoProvider();
|
||||
const AT = 1_786_600_000_000;
|
||||
|
||||
function enc(s: string): Uint8Array {
|
||||
return new TextEncoder().encode(s);
|
||||
}
|
||||
function dec(b: Uint8Array): string {
|
||||
return new TextDecoder().decode(b);
|
||||
}
|
||||
function random(n: number): Uint8Array {
|
||||
const out = new Uint8Array(n);
|
||||
// getRandomValues caps at 64 KiB per call.
|
||||
for (let i = 0; i < n; i += 65_536) globalThis.crypto.getRandomValues(out.subarray(i, i + 65_536));
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Wraps the real HTTP transport and counts every call by kind. */
|
||||
class CountingTransport implements VaultTransport {
|
||||
counts = { has: 0, put: 0, get: 0, log: 0, commit: 0, prune: 0 };
|
||||
constructor(private readonly inner: VaultTransport) {}
|
||||
reset() {
|
||||
for (const k of Object.keys(this.counts) as Array<keyof typeof this.counts>) this.counts[k] = 0;
|
||||
}
|
||||
has(v: string, h: string) {
|
||||
this.counts.has++;
|
||||
return this.inner.has(v, h);
|
||||
}
|
||||
put(v: string, h: string, b: unknown) {
|
||||
this.counts.put++;
|
||||
return this.inner.put(v, h, b);
|
||||
}
|
||||
get(v: string, h: string) {
|
||||
this.counts.get++;
|
||||
return this.inner.get(v, h);
|
||||
}
|
||||
log(v: string, l?: number): Promise<VaultLog> {
|
||||
this.counts.log++;
|
||||
return this.inner.log(v, l);
|
||||
}
|
||||
commit(v: string, b: unknown) {
|
||||
this.counts.commit++;
|
||||
return this.inner.commit(v, b);
|
||||
}
|
||||
prune(v: string, b: unknown): Promise<VaultPruneResult> {
|
||||
this.counts.prune++;
|
||||
return this.inner.prune(v, b);
|
||||
}
|
||||
}
|
||||
|
||||
async function harness(
|
||||
opts: {
|
||||
store?: VaultStore;
|
||||
master?: Uint8Array;
|
||||
chunkSize?: number;
|
||||
routes?: VaultRoutesOptions;
|
||||
} = {},
|
||||
) {
|
||||
const store = opts.store ?? new MemoryVaultStore();
|
||||
const routes = createVaultRoutes(store, crypto, opts.routes ?? {});
|
||||
const fetchImpl = (input: string, init?: RequestInit) => routes.fetch(new Request(input, init));
|
||||
const transport = new CountingTransport(new HttpVaultTransport('http://vault.test', fetchImpl));
|
||||
const keys = await deriveVaultKeys(opts.master ?? new Uint8Array(32).fill(7), 'scaffold');
|
||||
const client = new VaultClient(
|
||||
crypto,
|
||||
keys,
|
||||
transport,
|
||||
opts.chunkSize === undefined ? {} : { chunkSize: opts.chunkSize },
|
||||
);
|
||||
/** A second device: same credentials, its own transport and no index. */
|
||||
const device = () =>
|
||||
new VaultClient(crypto, keys, new HttpVaultTransport('http://vault.test', fetchImpl));
|
||||
return { store, routes, transport, keys, client, device };
|
||||
}
|
||||
|
||||
/**
|
||||
* Write a version exactly as a pre-v2 relay and client did: a bare-JSON v1
|
||||
* manifest, one object per file, and a log row with no recorded refs.
|
||||
*/
|
||||
async function legacyPush(
|
||||
store: VaultStore,
|
||||
keys: VaultKeys,
|
||||
seq: number,
|
||||
files: Array<{ path: string; bytes: Uint8Array }>,
|
||||
): Promise<{ manifest: string; objects: string[] }> {
|
||||
if (!(await store.getOwner(keys.vaultId))) await store.setOwner(keys.vaultId, keys.publicKey);
|
||||
const entries = [];
|
||||
const objects: string[] = [];
|
||||
for (const f of files) {
|
||||
const o = await sealObject(crypto, keys.contentKey, keys.vaultId, f.bytes);
|
||||
await store.putObject(keys.vaultId, o.hash, o.bytes);
|
||||
objects.push(o.hash);
|
||||
entries.push({ path: f.path, hash: o.hash, size: f.bytes.length });
|
||||
}
|
||||
const manifest: VaultManifest = { version: 1, seq, at: AT, entries };
|
||||
const m = await sealManifest(crypto, keys.contentKey, keys.vaultId, manifest);
|
||||
await store.putObject(keys.vaultId, m.hash, m.bytes);
|
||||
await store.appendLog(keys.vaultId, {
|
||||
seq,
|
||||
manifest: m.hash,
|
||||
at: AT,
|
||||
bytes: await store.usage(keys.vaultId),
|
||||
});
|
||||
return { manifest: m.hash, objects };
|
||||
}
|
||||
|
||||
async function signedPost(
|
||||
routes: { fetch: (r: Request) => Response | Promise<Response> },
|
||||
path: string,
|
||||
seed: Uint8Array,
|
||||
publicKey: Uint8Array,
|
||||
body: Record<string, unknown>,
|
||||
) {
|
||||
const signed = await signPayload(crypto, seed, { ...body, publicKey: toBase64(publicKey) });
|
||||
return routes.fetch(
|
||||
new Request(`http://v${path}`, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify(signed),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
describe('entry packing', () => {
|
||||
test('compressible text is stored deflated, and size stays the plaintext length', async () => {
|
||||
const text = enc('## Nå\n- [ ] noe å gjøre\n'.repeat(200));
|
||||
const packed = await packEntry(text);
|
||||
expect(packed.enc).toBe('deflate-raw');
|
||||
expect(packed.stored.length).toBeLessThan(text.length / 10);
|
||||
expect(packed.chunks.length).toBe(1);
|
||||
|
||||
const { client } = await harness();
|
||||
await client.push([{ path: 'plan.md', bytes: text }], AT);
|
||||
const manifest = await client.manifest();
|
||||
expect(manifest.entries[0]!.enc).toBe('deflate-raw');
|
||||
expect(manifest.entries[0]!.size).toBe(text.length);
|
||||
expect(dec(await client.readEntry(manifest.entries[0]!))).toBe(dec(text));
|
||||
});
|
||||
|
||||
test('incompressible bytes are stored as-is', async () => {
|
||||
const packed = await packEntry(random(10_000));
|
||||
expect(packed.enc).toBeUndefined();
|
||||
});
|
||||
|
||||
test('known compressed formats are not even tried', async () => {
|
||||
// Highly compressible body, but a PNG/zip/MP4 signature in front: the
|
||||
// magic wins, which is what saves the CPU on a photo library.
|
||||
const body = new Uint8Array(5000);
|
||||
const png = new Uint8Array([0x89, 0x50, 0x4e, 0x47, ...body]);
|
||||
const zip = new Uint8Array([0x50, 0x4b, 0x03, 0x04, ...body]);
|
||||
const mp4 = new Uint8Array([0, 0, 0, 0x20, 0x66, 0x74, 0x79, 0x70, ...body]);
|
||||
const webp = new Uint8Array([...enc('RIFF'), 0, 0, 0, 0, ...enc('WEBP'), ...body]);
|
||||
for (const b of [png, zip, mp4, webp]) expect((await packEntry(b)).enc).toBeUndefined();
|
||||
expect((await packEntry(new Uint8Array([0x00, ...body]))).enc).toBe('deflate-raw');
|
||||
});
|
||||
|
||||
test('an empty file is one empty object, as in v1', async () => {
|
||||
const packed = await packEntry(new Uint8Array(0));
|
||||
expect(packed.enc).toBeUndefined();
|
||||
expect(packed.chunks.length).toBe(1);
|
||||
expect(packed.chunks[0]!.length).toBe(0);
|
||||
|
||||
const { client } = await harness();
|
||||
await client.push([{ path: 'tom.txt', bytes: new Uint8Array(0) }], AT);
|
||||
expect((await client.pull()).files.get('tom.txt')!.length).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('multi-part entries', () => {
|
||||
test('a file larger than the chunk size is split, and every part is committed', async () => {
|
||||
const { client, store, keys } = await harness({ chunkSize: 1024 });
|
||||
const big = random(5000); // incompressible → 5 parts of ≤ 1024
|
||||
const res = await client.push([{ path: 'stor.bin', bytes: big }], AT);
|
||||
expect(res.uploaded).toBe(5);
|
||||
|
||||
const entry = (await client.manifest()).entries[0]!;
|
||||
expect(entry.parts!.length).toBe(5);
|
||||
expect(entry.hash).toBe(entry.parts![0]!);
|
||||
expect(entry.size).toBe(5000);
|
||||
expect(await client.readEntry(entry)).toEqual(big);
|
||||
|
||||
// Every part was recorded as referenced: a prune with nothing to drop
|
||||
// must not collect any of them.
|
||||
const pruned = await client.prune([1]);
|
||||
expect(pruned.removedObjects).toBe(0);
|
||||
for (const h of entry.parts!) expect(await store.hasObject(keys.vaultId, h)).toBe(true);
|
||||
});
|
||||
|
||||
test('compression runs before splitting, and parts reassemble before inflating', async () => {
|
||||
const { client } = await harness({ chunkSize: 64 });
|
||||
const text = enc(Array.from({ length: 300 }, (_, i) => `linje ${i * 7919}\n`).join(''));
|
||||
await client.push([{ path: 'logg.md', bytes: text }], AT);
|
||||
const entry = (await client.manifest()).entries[0]!;
|
||||
expect(entry.enc).toBe('deflate-raw');
|
||||
expect(entry.parts!.length).toBeGreaterThan(1);
|
||||
expect(dec(await client.readEntry(entry))).toBe(dec(text));
|
||||
});
|
||||
|
||||
test('a dropped part, a part under the wrong name, or a bad hash field is refused', async () => {
|
||||
const { client, keys, transport } = await harness({ chunkSize: 1024 });
|
||||
await client.push([{ path: 'x.bin', bytes: random(3000) }], AT);
|
||||
const entry = (await client.manifest()).entries[0]!;
|
||||
const objects = await Promise.all(
|
||||
entryObjectHashes(entry).map((h) => transport.get(keys.vaultId, h)),
|
||||
);
|
||||
|
||||
// Each remaining part authenticates on its own; only the size check
|
||||
// notices the file is short.
|
||||
const truncated = { ...entry, parts: entry.parts!.slice(0, 2) };
|
||||
await expect(
|
||||
openEntryBytes(crypto, keys.contentKey, keys.vaultId, truncated, objects.slice(0, 2)),
|
||||
).rejects.toThrow(/size mismatch/);
|
||||
|
||||
// Bytes handed back out of order fail on their names.
|
||||
await expect(
|
||||
openEntryBytes(crypto, keys.contentKey, keys.vaultId, entry, [
|
||||
objects[0]!,
|
||||
objects[2]!,
|
||||
objects[1]!,
|
||||
]),
|
||||
).rejects.toThrow(/hash mismatch/);
|
||||
|
||||
const misnamed = { ...entry, hash: entry.parts![1]! };
|
||||
await expect(
|
||||
openEntryBytes(crypto, keys.contentKey, keys.vaultId, misnamed, objects),
|
||||
).rejects.toThrow(/parts\[0\]/);
|
||||
});
|
||||
|
||||
test('a file over the real 4 MiB chunk fits under the relay object ceiling', async () => {
|
||||
// The point of parts: before v2, one file was one object, and anything
|
||||
// over 8 MiB could not be backed up at all.
|
||||
const { client } = await harness();
|
||||
const big = random(9 * 1024 * 1024);
|
||||
const res = await client.push([{ path: 'video.mov', bytes: big }], AT);
|
||||
expect(res.uploaded).toBe(3);
|
||||
const entry = (await client.manifest()).entries[0]!;
|
||||
expect(entry.parts!.length).toBe(Math.ceil(big.length / VAULT_CHUNK_SIZE));
|
||||
expect(await client.readEntry(entry)).toEqual(big);
|
||||
});
|
||||
});
|
||||
|
||||
describe('manifest v2', () => {
|
||||
test('push writes a compressed v2 manifest', async () => {
|
||||
const { client, store, keys } = await harness();
|
||||
await client.push([{ path: 'a.md', bytes: enc('A') }], AT, 'første');
|
||||
const row = (await store.log(keys.vaultId))[0]!;
|
||||
const plain = await openObject(
|
||||
crypto,
|
||||
keys.contentKey,
|
||||
keys.vaultId,
|
||||
row.manifest,
|
||||
(await store.getObject(keys.vaultId, row.manifest))!,
|
||||
);
|
||||
expect(dec(plain.subarray(0, 4))).toBe('SVM2');
|
||||
const manifest = await decodeManifest(plain);
|
||||
expect(manifest.version).toBe(2);
|
||||
expect(manifest.message).toBe('første');
|
||||
});
|
||||
|
||||
test('a v1 vault written by the old client is still readable, and pushable on top', async () => {
|
||||
const { client, store, keys } = await harness();
|
||||
await legacyPush(store, keys, 1, [
|
||||
{ path: 'gammel.md', bytes: enc('fra v1') },
|
||||
{ path: 'annen.md', bytes: enc('også v1') },
|
||||
]);
|
||||
const { manifest, files } = await client.pull();
|
||||
expect(manifest.version).toBe(1);
|
||||
expect(dec(files.get('gammel.md')!)).toBe('fra v1');
|
||||
|
||||
// A v2 push reuses the v1 entries it can prove unchanged.
|
||||
const res = await client.push(
|
||||
[
|
||||
{ path: 'gammel.md', bytes: enc('fra v1') },
|
||||
{ path: 'annen.md', bytes: enc('endret') },
|
||||
],
|
||||
AT + 1,
|
||||
);
|
||||
expect(res.seq).toBe(2);
|
||||
expect(res.reused).toBe(1);
|
||||
expect(res.uploaded).toBe(1);
|
||||
expect(dec((await client.pull(1)).files.get('annen.md')!)).toBe('også v1');
|
||||
});
|
||||
|
||||
test('an unknown manifest version is refused', async () => {
|
||||
await expect(decodeManifest(enc(JSON.stringify({ version: 3, entries: [] })))).rejects.toThrow(
|
||||
/unsupported vault manifest version: 3/,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the local index', () => {
|
||||
const files = () => [
|
||||
{ path: 'plan.md', bytes: enc('# Plan\n') },
|
||||
{ path: 'stor.md', bytes: enc('x'.repeat(50_000)) },
|
||||
{ path: 'run.sh', bytes: enc('#!/bin/sh\n'), mode: '755' },
|
||||
];
|
||||
|
||||
test('an unchanged push with a fresh index touches nothing: no seal, no download, no commit', async () => {
|
||||
const { client, transport } = await harness();
|
||||
const first = await client.push(files(), AT);
|
||||
expect(first.unchanged).toBe(false);
|
||||
|
||||
// Through JSON, as a caller persisting it to disk would.
|
||||
const index = JSON.parse(JSON.stringify(first.index));
|
||||
transport.reset();
|
||||
const second = await client.push(files(), AT + 1, undefined, { index });
|
||||
expect(second).toMatchObject({ seq: 1, uploaded: 0, reused: 3, bytesUploaded: 0, unchanged: true });
|
||||
expect(transport.counts.put).toBe(0);
|
||||
expect(transport.counts.get).toBe(0);
|
||||
expect(transport.counts.has).toBe(0);
|
||||
expect(transport.counts.commit).toBe(0);
|
||||
expect(second.index).toEqual(first.index);
|
||||
expect((await client.history()).head).toBe(1);
|
||||
});
|
||||
|
||||
test('a changed file uploads only itself, still without downloading', async () => {
|
||||
const { client, transport } = await harness();
|
||||
const { index } = await client.push(files(), AT);
|
||||
transport.reset();
|
||||
const changed = files();
|
||||
changed[0] = { path: 'plan.md', bytes: enc('# Plan v2\n') };
|
||||
const res = await client.push(changed, AT + 1, undefined, { index });
|
||||
expect(res).toMatchObject({ seq: 2, uploaded: 1, reused: 2, unchanged: false });
|
||||
expect(transport.counts.get).toBe(0);
|
||||
expect(transport.counts.put).toBe(2); // the file + the manifest
|
||||
expect(transport.counts.commit).toBe(1);
|
||||
expect(dec((await client.pull()).files.get('plan.md')!)).toBe('# Plan v2\n');
|
||||
expect(res.index.seq).toBe(2);
|
||||
});
|
||||
|
||||
test('a renamed file reuses its objects', async () => {
|
||||
const { client, store, keys } = await harness();
|
||||
const { index } = await client.push(files(), AT);
|
||||
const before = await store.usage(keys.vaultId);
|
||||
const renamed = files().map((f) => (f.path === 'stor.md' ? { ...f, path: 'arkiv/stor.md' } : f));
|
||||
const res = await client.push(renamed, AT + 1, undefined, { index });
|
||||
expect(res.uploaded).toBe(0);
|
||||
expect(res.unchanged).toBe(false); // the path set changed
|
||||
expect((await client.pull()).files.get('arkiv/stor.md')!.length).toBe(50_000);
|
||||
// Only a new manifest was stored.
|
||||
expect((await store.usage(keys.vaultId)) - before).toBeLessThan(2000);
|
||||
});
|
||||
|
||||
test('a mode change alone is a new version', async () => {
|
||||
const { client } = await harness();
|
||||
const { index } = await client.push(files(), AT);
|
||||
const chmod = files().map((f) => (f.path === 'run.sh' ? { ...f, mode: '644' } : f));
|
||||
const res = await client.push(chmod, AT + 1, undefined, { index });
|
||||
expect(res).toMatchObject({ seq: 2, uploaded: 0, unchanged: false });
|
||||
expect((await client.manifest()).entries.find((e) => e.path === 'run.sh')!.mode).toBe('644');
|
||||
});
|
||||
|
||||
test('a deleted file is a new version', async () => {
|
||||
const { client } = await harness();
|
||||
const { index } = await client.push(files(), AT);
|
||||
const res = await client.push(files().slice(0, 2), AT + 1, undefined, { index });
|
||||
expect(res).toMatchObject({ seq: 2, unchanged: false });
|
||||
});
|
||||
|
||||
test('a message forces a version even when nothing changed', async () => {
|
||||
const { client, transport } = await harness();
|
||||
const { index } = await client.push(files(), AT);
|
||||
transport.reset();
|
||||
const res = await client.push(files(), AT + 1, 'nattlig backup', { index });
|
||||
expect(res).toMatchObject({ seq: 2, uploaded: 0, unchanged: false });
|
||||
expect(transport.counts.commit).toBe(1);
|
||||
});
|
||||
|
||||
test('an unchanged push without an index commits nothing either, reading only what it must', async () => {
|
||||
const { client, transport } = await harness();
|
||||
await client.push(files(), AT);
|
||||
transport.reset();
|
||||
const res = await client.push(files(), AT + 1);
|
||||
expect(res).toMatchObject({ seq: 1, uploaded: 0, reused: 3, unchanged: true });
|
||||
expect(transport.counts.commit).toBe(0);
|
||||
expect(transport.counts.put).toBe(0);
|
||||
// The manifest, plus one download per same-path same-size candidate.
|
||||
expect(transport.counts.get).toBe(1 + 3);
|
||||
});
|
||||
|
||||
test('without an index, a file whose size changed is not downloaded to compare', async () => {
|
||||
const { client, transport } = await harness();
|
||||
await client.push(files(), AT);
|
||||
transport.reset();
|
||||
const changed = files();
|
||||
changed[1] = { path: 'stor.md', bytes: enc('y'.repeat(60_000)) };
|
||||
await client.push(changed, AT + 1);
|
||||
expect(transport.counts.get).toBe(1 + 2); // manifest + the two same-size files
|
||||
});
|
||||
|
||||
test('a stale index (another device committed) falls back and stays correct', async () => {
|
||||
const { client, device } = await harness();
|
||||
const { index } = await client.push(files(), AT);
|
||||
await device().push([{ path: 'plan.md', bytes: enc('fra telefonen') }], AT + 1);
|
||||
|
||||
const res = await client.push(files(), AT + 2, undefined, { index });
|
||||
// Reverts the phone's edit and restores the other files: a real change.
|
||||
expect(res).toMatchObject({ seq: 3, unchanged: false });
|
||||
const { files: back } = await client.pull();
|
||||
expect(dec(back.get('plan.md')!)).toBe('# Plan\n');
|
||||
expect(back.get('stor.md')!.length).toBe(50_000);
|
||||
expect(res.index.seq).toBe(3);
|
||||
});
|
||||
|
||||
test('an index for a different vault is ignored', async () => {
|
||||
const { client, transport } = await harness();
|
||||
const { index } = await client.push(files(), AT);
|
||||
transport.reset();
|
||||
const foreign = { ...index, vaultId: 'f'.repeat(64) };
|
||||
const res = await client.push(files(), AT + 1, undefined, { index: foreign });
|
||||
expect(res.unchanged).toBe(true);
|
||||
expect(transport.counts.get).toBeGreaterThan(0); // had to read the head instead
|
||||
});
|
||||
|
||||
test('vaultIndexFrom after a restore makes the first push from a fresh device free', async () => {
|
||||
const { client, device, keys } = await harness();
|
||||
await client.push(files(), AT);
|
||||
const phone = device();
|
||||
const { manifest, files: restored } = await phone.pull();
|
||||
const index = vaultIndexFrom(keys.vaultId, manifest, restored);
|
||||
const res = await phone.push(files(), AT + 1, undefined, { index });
|
||||
expect(res).toMatchObject({ unchanged: true, uploaded: 0 });
|
||||
});
|
||||
|
||||
test('two copies of one file in a single push share their objects', async () => {
|
||||
const { client } = await harness();
|
||||
const same = enc('identisk innhold '.repeat(100));
|
||||
const res = await client.push(
|
||||
[
|
||||
{ path: 'a.md', bytes: same },
|
||||
{ path: 'kopi/a.md', bytes: same },
|
||||
],
|
||||
AT,
|
||||
);
|
||||
expect(res.uploaded).toBe(1);
|
||||
const { files: back } = await client.pull();
|
||||
expect(dec(back.get('kopi/a.md')!)).toBe(dec(same));
|
||||
});
|
||||
});
|
||||
|
||||
describe('lazy reads', () => {
|
||||
test('manifest() fetches only the manifest; readEntry only the file asked for', async () => {
|
||||
const { client, transport } = await harness({ chunkSize: 1024 });
|
||||
await client.push(
|
||||
[
|
||||
{ path: 'a.bin', bytes: random(3000) },
|
||||
{ path: 'b.md', bytes: enc('B') },
|
||||
],
|
||||
AT,
|
||||
);
|
||||
transport.reset();
|
||||
const manifest = await client.manifest();
|
||||
expect(transport.counts.get).toBe(1);
|
||||
expect(manifest.entries.map((e) => e.path)).toEqual(['a.bin', 'b.md']);
|
||||
|
||||
transport.reset();
|
||||
await client.readEntry(manifest.entries[1]!);
|
||||
expect(transport.counts.get).toBe(1);
|
||||
await client.readEntry(manifest.entries[0]!);
|
||||
expect(transport.counts.get).toBe(1 + 3);
|
||||
});
|
||||
|
||||
test('manifest(seq) reads an older version', async () => {
|
||||
const { client } = await harness();
|
||||
await client.push([{ path: 'p', bytes: enc('1') }], AT);
|
||||
await client.push([{ path: 'p', bytes: enc('2') }], AT + 1);
|
||||
expect((await client.manifest(1)).seq).toBe(1);
|
||||
await expect(client.manifest(7)).rejects.toThrow(/no version 7/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('prune', () => {
|
||||
async function threeVersions(store?: VaultStore) {
|
||||
const h = await harness({ ...(store ? { store } : {}), routes: { pruneGraceMs: 0 } });
|
||||
const stable = { path: 'stabil.md', bytes: enc('rører seg aldri '.repeat(500)) };
|
||||
await h.client.push([stable, { path: 'plan.md', bytes: random(3000) }], AT);
|
||||
await h.client.push([stable, { path: 'plan.md', bytes: random(3000) }], AT + 1);
|
||||
await h.client.push([stable, { path: 'plan.md', bytes: random(3000) }], AT + 2);
|
||||
return h;
|
||||
}
|
||||
|
||||
test('keeps what remaining versions use and frees the rest', async () => {
|
||||
const { client, store, keys } = await threeVersions();
|
||||
const before = await store.usage(keys.vaultId);
|
||||
|
||||
const res = await client.prune([3]);
|
||||
// Versions 1 and 2: each had its own plan.md and manifest.
|
||||
expect(res.removedVersions).toBe(2);
|
||||
expect(res.removedObjects).toBe(4);
|
||||
expect(res.freedBytes).toBe(before - (await store.usage(keys.vaultId)));
|
||||
expect(res.freedBytes).toBeGreaterThan(6000);
|
||||
|
||||
const log = await client.history();
|
||||
expect(log.entries.map((e) => e.seq)).toEqual([3]);
|
||||
expect(log.head).toBe(3);
|
||||
// The stable file, first uploaded in version 1, survives: version 3 uses it.
|
||||
const { files } = await client.pull();
|
||||
expect(dec(files.get('stabil.md')!)).toBe('rører seg aldri '.repeat(500));
|
||||
await expect(client.pull(1)).rejects.toThrow(/no version 1/);
|
||||
|
||||
// And the vault keeps working after a prune.
|
||||
const next = await client.push([{ path: 'ny.md', bytes: enc('etter') }], AT + 3);
|
||||
expect(next.seq).toBe(4);
|
||||
});
|
||||
|
||||
test('keeping an older version keeps its objects', async () => {
|
||||
const { client } = await threeVersions();
|
||||
const res = await client.prune([1, 3]);
|
||||
expect(res.removedVersions).toBe(1);
|
||||
expect(res.removedObjects).toBe(2);
|
||||
expect((await client.pull(1)).files.get('plan.md')!.length).toBe(3000);
|
||||
});
|
||||
|
||||
test('is refused when the keep-list leaves out the head', async () => {
|
||||
const { client, store, keys } = await threeVersions();
|
||||
await expect(client.prune([1, 2])).rejects.toThrow(/409.*SEQ_CONFLICT/);
|
||||
expect((await store.log(keys.vaultId)).length).toBe(3);
|
||||
});
|
||||
|
||||
test('is refused with a bad signature, or signed by another key', async () => {
|
||||
const { routes, keys, store } = await threeVersions();
|
||||
const attacker = await deriveVaultKeys(new Uint8Array(32).fill(9), 'scaffold');
|
||||
const res = await signedPost(
|
||||
routes,
|
||||
`/v1/vault/${keys.vaultId}/prune`,
|
||||
attacker.signingSeed,
|
||||
attacker.publicKey,
|
||||
{ keep: [3] },
|
||||
);
|
||||
expect(res.status).toBe(401);
|
||||
|
||||
// Correct key, tampered body after signing.
|
||||
const signed = await signPayload(crypto, keys.signingSeed, {
|
||||
keep: [3],
|
||||
publicKey: toBase64(keys.publicKey),
|
||||
});
|
||||
const tampered = await routes.fetch(
|
||||
new Request(`http://v/v1/vault/${keys.vaultId}/prune`, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ ...signed, keep: [1, 3] }),
|
||||
}),
|
||||
);
|
||||
expect(tampered.status).toBe(401);
|
||||
expect((await store.log(keys.vaultId)).length).toBe(3);
|
||||
});
|
||||
|
||||
test('cannot be the write that pins an owner', async () => {
|
||||
const store = new MemoryVaultStore();
|
||||
const routes = createVaultRoutes(store, crypto);
|
||||
const keys = await deriveVaultKeys(new Uint8Array(32).fill(3), 'scaffold');
|
||||
const res = await signedPost(
|
||||
routes,
|
||||
`/v1/vault/${keys.vaultId}/prune`,
|
||||
keys.signingSeed,
|
||||
keys.publicKey,
|
||||
{ keep: [0] },
|
||||
);
|
||||
expect(res.status).toBe(404);
|
||||
expect(await store.getOwner(keys.vaultId)).toBeNull();
|
||||
});
|
||||
|
||||
test('rejects a malformed keep-list', async () => {
|
||||
const { routes, keys } = await threeVersions();
|
||||
for (const keep of [undefined, 'alle', [3, -1], [3, 1.5]]) {
|
||||
const res = await signedPost(
|
||||
routes,
|
||||
`/v1/vault/${keys.vaultId}/prune`,
|
||||
keys.signingSeed,
|
||||
keys.publicKey,
|
||||
keep === undefined ? {} : { keep },
|
||||
);
|
||||
expect(res.status).toBe(400);
|
||||
}
|
||||
});
|
||||
|
||||
test('legacy versions without a recorded hash list keep their objects', async () => {
|
||||
const { client, store, keys } = await harness({ routes: { pruneGraceMs: 0 } });
|
||||
const legacy = await legacyPush(store, keys, 1, [{ path: 'gammel.md', bytes: enc('v1-data') }]);
|
||||
await client.push([{ path: 'ny.md', bytes: random(2000) }], AT + 1);
|
||||
await client.push([{ path: 'ny.md', bytes: random(2000) }], AT + 2);
|
||||
|
||||
// Drop version 2 but keep the legacy one: its objects are pinned, since
|
||||
// the relay has no idea which objects it uses.
|
||||
const res = await client.prune([1, 3]);
|
||||
expect(res.removedVersions).toBe(1);
|
||||
expect(res.removedObjects).toBe(2); // version 2's file and manifest only
|
||||
for (const h of [legacy.manifest, ...legacy.objects]) {
|
||||
expect(await store.hasObject(keys.vaultId, h)).toBe(true);
|
||||
}
|
||||
expect(dec((await client.pull(1)).files.get('gammel.md')!)).toBe('v1-data');
|
||||
|
||||
// Once the legacy version itself is pruned, no unknown reference set is
|
||||
// left and its objects are ordinary garbage.
|
||||
const second = await client.prune([3]);
|
||||
expect(second.removedVersions).toBe(1);
|
||||
for (const h of [legacy.manifest, ...legacy.objects]) {
|
||||
expect(await store.hasObject(keys.vaultId, h)).toBe(false);
|
||||
}
|
||||
expect((await client.pull()).files.get('ny.md')!.length).toBe(2000);
|
||||
});
|
||||
|
||||
test('an upload whose commit has not arrived yet survives the grace period', async () => {
|
||||
const { client, keys, store } = await threeVersions(); // grace 0 here…
|
||||
const orphan = await sealObject(crypto, keys.contentKey, keys.vaultId, enc('på vei'));
|
||||
await store.putObject(keys.vaultId, orphan.hash, orphan.bytes);
|
||||
|
||||
// …so under a real grace, a fresh orphan is left alone.
|
||||
const routes = createVaultRoutes(store, crypto, { pruneGraceMs: 60_000 });
|
||||
const res = await signedPost(
|
||||
routes,
|
||||
`/v1/vault/${keys.vaultId}/prune`,
|
||||
keys.signingSeed,
|
||||
keys.publicKey,
|
||||
{ keep: [3] },
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
expect(await store.hasObject(keys.vaultId, orphan.hash)).toBe(true);
|
||||
// While objects only an old version used are freed at once.
|
||||
expect((await res.json()).removedObjects).toBe(4);
|
||||
|
||||
// With no grace, the orphan is collected.
|
||||
await client.prune([3]);
|
||||
expect(await store.hasObject(keys.vaultId, orphan.hash)).toBe(false);
|
||||
});
|
||||
|
||||
test('the store never removes an entry newer than the head the route checked', async () => {
|
||||
const { store, keys } = await threeVersions();
|
||||
const res = await store.prune(keys.vaultId, { keep: [2], upTo: 2, protectSince: Date.now() });
|
||||
expect(res.removedVersions).toBe(1);
|
||||
expect((await store.log(keys.vaultId)).map((e) => e.seq)).toEqual([2, 3]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('edit against the head that was read', () => {
|
||||
const text = (s: string) => new TextEncoder().encode(s);
|
||||
const decode = (b: Uint8Array) => new TextDecoder().decode(b);
|
||||
|
||||
test('a drain that raced an append keeps the appended file', async () => {
|
||||
// The queue case: a phone appends while the PC removes what it applied.
|
||||
// A whole-collection push from the PC's stale view would drop the
|
||||
// phone's new file; edit retries on the new head instead.
|
||||
const { client, device } = await harness();
|
||||
const phone = device();
|
||||
await phone.edit(() => ({ put: [{ path: 'intents/a.json', bytes: text('a') }] }), 1);
|
||||
|
||||
let calls = 0;
|
||||
const res = await client.edit(async (head) => {
|
||||
calls++;
|
||||
if (calls === 1) {
|
||||
// Between this read and the commit, the phone appends.
|
||||
await phone.edit(() => ({ put: [{ path: 'intents/b.json', bytes: text('b') }] }), 2);
|
||||
}
|
||||
expect(head).not.toBeNull();
|
||||
return { remove: ['intents/a.json'] };
|
||||
}, 3);
|
||||
|
||||
expect(calls).toBe(2);
|
||||
expect(res.committed).toBe(true);
|
||||
const after = await client.manifest();
|
||||
expect(after.entries.map((e) => e.path)).toEqual(['intents/b.json']);
|
||||
expect(decode(await client.readEntry(after.entries[0]!))).toBe('b');
|
||||
});
|
||||
|
||||
test('an edit that changes nothing commits nothing', async () => {
|
||||
const { client, transport } = await harness();
|
||||
await client.edit(() => ({ put: [{ path: 'x', bytes: text('x') }] }), 1);
|
||||
const before = transport.counts.commit;
|
||||
const res = await client.edit(() => ({ remove: ['not-there'] }), 2);
|
||||
expect(res).toEqual({ seq: 1, committed: false });
|
||||
expect(await client.edit(() => null, 3)).toEqual({ seq: 1, committed: false });
|
||||
expect(transport.counts.commit).toBe(before);
|
||||
});
|
||||
|
||||
test('untouched entries keep their objects', async () => {
|
||||
const { client } = await harness();
|
||||
await client.edit(() => ({ put: [{ path: 'keep', bytes: text('k') }, { path: 'drop', bytes: text('d') }] }), 1);
|
||||
const first = await client.manifest();
|
||||
await client.edit(() => ({ remove: ['drop'], put: [{ path: 'new', bytes: text('n') }] }), 2);
|
||||
const second = await client.manifest();
|
||||
const keep = (m: typeof first) => m.entries.find((e) => e.path === 'keep')!;
|
||||
expect(keep(second).hash).toBe(keep(first).hash);
|
||||
expect(second.entries.map((e) => e.path).sort()).toEqual(['keep', 'new']);
|
||||
});
|
||||
});
|
||||
100
packages/shade-vault/tests/vectors.test.ts
Normal file
100
packages/shade-vault/tests/vectors.test.ts
Normal file
@@ -0,0 +1,100 @@
|
||||
/**
|
||||
* The vault-v2 cross-language vectors, checked against this implementation.
|
||||
*
|
||||
* The Kotlin port is written against `test-vectors/vault-v2.json`; this test
|
||||
* is what stops the file and the TypeScript code from drifting apart, so a
|
||||
* port that matches the vectors also matches the client that wrote them.
|
||||
* Regenerate with `bun run scripts/generate-vectors.ts vault-v2.json`.
|
||||
*/
|
||||
import { describe, test, expect } from 'bun:test';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { SubtleCryptoProvider } from '@shade/crypto-web';
|
||||
import { canonicalizePayload } from '@shade/server';
|
||||
import { deriveVaultKeys } from '../src/client.js';
|
||||
import {
|
||||
decodeManifest,
|
||||
encodeManifest,
|
||||
openEntryBytes,
|
||||
openManifest,
|
||||
packEntry,
|
||||
toHex,
|
||||
vaultObjectAad,
|
||||
} from '../src/crypto.js';
|
||||
import { sealEntryWithNonces, sealObjectWithNonce } from '../src/testing.js';
|
||||
import type { VaultEntry } from '../src/types.js';
|
||||
|
||||
const crypto = new SubtleCryptoProvider();
|
||||
const file = JSON.parse(
|
||||
readFileSync(join(import.meta.dir, '..', '..', '..', 'test-vectors', 'vault-v2.json'), 'utf-8'),
|
||||
) as { version: number; vectors: any[] };
|
||||
|
||||
function fromHex(s: string): Uint8Array {
|
||||
const out = new Uint8Array(s.length / 2);
|
||||
for (let i = 0; i < out.length; i++) out[i] = parseInt(s.slice(i * 2, i * 2 + 2), 16);
|
||||
return out;
|
||||
}
|
||||
const byPrefix = (p: string) => file.vectors.filter((v) => v.description.startsWith(p));
|
||||
|
||||
describe('vault-v2 vectors', async () => {
|
||||
const k = byPrefix('vault-v2 keys')[0];
|
||||
const keys = await deriveVaultKeys(fromHex(k.masterKey), k.app);
|
||||
|
||||
test('the file is schema version 2 and has every kind', () => {
|
||||
expect(file.version).toBe(2);
|
||||
expect(byPrefix('vault-v2 entry').length).toBe(3);
|
||||
expect(byPrefix('vault-v2 manifest').length).toBe(2);
|
||||
expect(byPrefix('vault-v2 signed').length).toBe(2);
|
||||
});
|
||||
|
||||
test('key derivation and AAD', () => {
|
||||
expect(keys.vaultId).toBe(k.vaultId);
|
||||
expect(toHex(keys.contentKey)).toBe(k.contentKey);
|
||||
expect(toHex(keys.signingSeed)).toBe(k.signingSeed);
|
||||
expect(toHex(keys.publicKey)).toBe(k.publicKey);
|
||||
expect(toHex(vaultObjectAad(keys.vaultId))).toBe(k.objectAad);
|
||||
});
|
||||
|
||||
test('entries: readers reassemble, writers reproduce every byte', async () => {
|
||||
for (const v of byPrefix('vault-v2 entry')) {
|
||||
const entry = v.entry as VaultEntry;
|
||||
const wires = v.parts.map((p: any) => fromHex(p.wire));
|
||||
const plain = await openEntryBytes(crypto, keys.contentKey, keys.vaultId, entry, wires);
|
||||
expect(toHex(plain)).toBe(v.plaintext);
|
||||
|
||||
const packed = await packEntry(plain, { chunkSize: v.chunkSize });
|
||||
expect(toHex(packed.stored)).toBe(v.stored);
|
||||
expect(packed.enc ?? null).toBe(v.enc);
|
||||
|
||||
const resealed = await sealEntryWithNonces(
|
||||
keys.contentKey,
|
||||
keys.vaultId,
|
||||
plain,
|
||||
(i) => fromHex(v.parts[i].nonce),
|
||||
{ chunkSize: v.chunkSize },
|
||||
);
|
||||
expect(resealed.objects.map((o) => toHex(o.bytes))).toEqual(v.parts.map((p: any) => p.wire));
|
||||
expect({ path: entry.path, ...resealed.locator, size: plain.length, ...(entry.mode ? { mode: entry.mode } : {}) }).toEqual(entry);
|
||||
}
|
||||
});
|
||||
|
||||
test('manifests: v2 and v1 both open; encoding reproduces the plaintext', async () => {
|
||||
for (const v of byPrefix('vault-v2 manifest')) {
|
||||
const opened = await openManifest(crypto, keys.contentKey, keys.vaultId, v.hash, fromHex(v.wire));
|
||||
expect(opened).toEqual(v.manifest);
|
||||
expect(await decodeManifest(fromHex(v.plaintext))).toEqual(v.manifest);
|
||||
expect(toHex(await encodeManifest(v.manifest))).toBe(v.plaintext);
|
||||
const sealed = await sealObjectWithNonce(keys.contentKey, keys.vaultId, fromHex(v.plaintext), fromHex(v.nonce));
|
||||
expect(sealed.hash).toBe(v.hash);
|
||||
}
|
||||
});
|
||||
|
||||
test('signed bodies: canonical bytes and a deterministic Ed25519 signature', async () => {
|
||||
for (const v of byPrefix('vault-v2 signed')) {
|
||||
const canonical = canonicalizePayload({ ...v.body, signedAt: v.signedAt, signature: '' });
|
||||
expect(toHex(canonical)).toBe(v.canonicalHex);
|
||||
expect(toHex(await crypto.sign(keys.signingSeed, canonical))).toBe(v.signature);
|
||||
expect(await crypto.verify(keys.publicKey, canonical, fromHex(v.signature))).toBe(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/widgets",
|
||||
"version": "4.13.1",
|
||||
"version": "4.14.1",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -9,7 +9,9 @@
|
||||
* Bump `VECTOR_FILE_VERSION` whenever the vector schema (NOT just values)
|
||||
* changes, so downstream consumers can fail loudly on mismatch.
|
||||
*
|
||||
* Usage: bun run scripts/generate-vectors.ts
|
||||
* Usage: bun run scripts/generate-vectors.ts [file.json …]
|
||||
* With file names, only those are regenerated — so adding a vector file
|
||||
* does not churn the others.
|
||||
*/
|
||||
import { writeFileSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
@@ -38,6 +40,18 @@ import {
|
||||
buildApprovalRequest,
|
||||
type ApprovalRequestFrame,
|
||||
} from '../packages/shade-sdk/src/index.js';
|
||||
import { deriveVaultKeys } from '../packages/shade-vault/src/client.js';
|
||||
import {
|
||||
encodeManifest,
|
||||
entryObjectHashes,
|
||||
vaultObjectAad,
|
||||
} from '../packages/shade-vault/src/crypto.js';
|
||||
import {
|
||||
sealEntryWithNonces,
|
||||
sealObjectWithNonce,
|
||||
} from '../packages/shade-vault/src/testing.js';
|
||||
import type { VaultEntry, VaultManifest } from '../packages/shade-vault/src/types.js';
|
||||
import { canonicalizePayload } from '../packages/shade-server/src/auth.js';
|
||||
|
||||
const VECTOR_FILE_VERSION = 2;
|
||||
|
||||
@@ -821,6 +835,146 @@ async function generateApprovalVectors(): Promise<Vector[]> {
|
||||
return [...payloads, e2e];
|
||||
}
|
||||
|
||||
async function generateVaultV2Vectors(): Promise<Vector[]> {
|
||||
// One vault, derived from a pinned master, used by every vector below —
|
||||
// so a port checks its key derivation once and then the formats on top.
|
||||
const masterKey = new Uint8Array(32).map((_, i) => i + 1);
|
||||
const app = 'scaffold';
|
||||
const keys = await deriveVaultKeys(masterKey, app);
|
||||
const te = new TextEncoder();
|
||||
|
||||
const vectors: Vector[] = [
|
||||
{
|
||||
description:
|
||||
'vault-v2 keys: vaultId/contentKey/signingSeed = HKDF branches of masterKey for app; publicKey = Ed25519(signingSeed)',
|
||||
masterKey: hex(masterKey),
|
||||
app,
|
||||
vaultId: keys.vaultId,
|
||||
contentKey: hex(keys.contentKey),
|
||||
signingSeed: hex(keys.signingSeed),
|
||||
publicKey: hex(keys.publicKey),
|
||||
objectAad: hex(vaultObjectAad(keys.vaultId)),
|
||||
objectAadUtf8: `shade-vault-object-v1|${keys.vaultId}`,
|
||||
},
|
||||
];
|
||||
|
||||
// Entries. `stored` is pinned so a writer can be checked byte for byte
|
||||
// (zlib default level, raw deflate); a reader must only need `wire`.
|
||||
const pngLike = new Uint8Array(48);
|
||||
pngLike.set([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
|
||||
const entryCases: Array<{ name: string; path: string; plaintext: Uint8Array; chunkSize?: number; mode?: string }> = [
|
||||
{
|
||||
name: 'small text, compressed, one part',
|
||||
path: '.scaffold/plan.md',
|
||||
plaintext: te.encode('# Plan\n\n## Nå\n- [ ] noe\n- [ ] noe\n- [ ] noe\n- [ ] noe annet\n'.repeat(4)),
|
||||
},
|
||||
{
|
||||
name: 'multi-part (chunkSize 32), compressed — concatenate parts, then inflate',
|
||||
path: 'logs/2026-10-16.md',
|
||||
plaintext: te.encode(
|
||||
Array.from({ length: 40 }, (_, i) => `linje ${i}: ${(i * 7919) % 1000}\n`).join(''),
|
||||
),
|
||||
chunkSize: 32,
|
||||
mode: '644',
|
||||
},
|
||||
{
|
||||
name: 'PNG magic, never compressed, one part',
|
||||
path: 'bilde.png',
|
||||
plaintext: pngLike,
|
||||
},
|
||||
];
|
||||
|
||||
const committedHashes: string[] = [];
|
||||
const manifestEntries: VaultEntry[] = [];
|
||||
for (const [n, c] of entryCases.entries()) {
|
||||
const sealed = await sealEntryWithNonces(
|
||||
keys.contentKey,
|
||||
keys.vaultId,
|
||||
c.plaintext,
|
||||
(part) => new Uint8Array(12).map((_, i) => (n + 1) * 0x10 + part + i),
|
||||
c.chunkSize === undefined ? {} : { chunkSize: c.chunkSize },
|
||||
);
|
||||
const entry: VaultEntry = { path: c.path, ...sealed.locator, size: c.plaintext.length };
|
||||
if (c.mode !== undefined) entry.mode = c.mode;
|
||||
manifestEntries.push(entry);
|
||||
committedHashes.push(...entryObjectHashes(entry));
|
||||
vectors.push({
|
||||
description: `vault-v2 entry: ${c.name}`,
|
||||
chunkSize: c.chunkSize ?? 4 * 1024 * 1024,
|
||||
plaintext: hex(c.plaintext),
|
||||
stored: hex(sealed.packed.stored),
|
||||
enc: sealed.packed.enc ?? null,
|
||||
parts: sealed.objects.map((o, i) => ({
|
||||
nonce: hex(o.bytes.subarray(0, 12)),
|
||||
plaintext: hex(sealed.packed.chunks[i]!),
|
||||
wire: hex(o.bytes),
|
||||
hash: o.hash,
|
||||
})),
|
||||
entry,
|
||||
});
|
||||
}
|
||||
|
||||
// Manifests: v2 (what push writes) and v1 (what old vaults hold).
|
||||
const v2: VaultManifest = { version: 2, seq: 7, at: 1_786_600_000_000, entries: manifestEntries, message: 'nattlig backup' };
|
||||
const v1: VaultManifest = {
|
||||
version: 1,
|
||||
seq: 1,
|
||||
at: 1_786_500_000_000,
|
||||
entries: [{ path: 'notes.yaml', hash: manifestEntries[2]!.hash, size: 48 }],
|
||||
};
|
||||
let manifestHash = '';
|
||||
for (const [m, nonceByte] of [[v2, 0xc0], [v1, 0xd0]] as const) {
|
||||
const plain = await encodeManifest(m);
|
||||
const sealed = await sealObjectWithNonce(keys.contentKey, keys.vaultId, plain, new Uint8Array(12).fill(nonceByte));
|
||||
if (m.version === 2) manifestHash = sealed.hash;
|
||||
vectors.push({
|
||||
description:
|
||||
m.version === 2
|
||||
? 'vault-v2 manifest v2: plaintext = "SVM2" || deflate-raw(json utf-8)'
|
||||
: 'vault-v2 manifest v1: plaintext = json utf-8 (back-compat, still readable)',
|
||||
manifest: m,
|
||||
json: JSON.stringify(m),
|
||||
plaintext: hex(plain),
|
||||
nonce: hex(sealed.bytes.subarray(0, 12)),
|
||||
wire: hex(sealed.bytes),
|
||||
hash: sealed.hash,
|
||||
});
|
||||
}
|
||||
|
||||
// Signed request bodies. Canonical form: every field except `signature`,
|
||||
// top-level keys sorted, JSON.stringify — the same function the relay
|
||||
// verifies with. Nested arrays keep their order.
|
||||
const signed: Array<[string, Record<string, unknown>]> = [
|
||||
[
|
||||
'commit',
|
||||
{
|
||||
manifest: manifestHash,
|
||||
seq: 7,
|
||||
at: 1_786_600_000_000,
|
||||
hashes: [...new Set(committedHashes)],
|
||||
publicKey: Buffer.from(keys.publicKey).toString('base64'),
|
||||
},
|
||||
],
|
||||
['prune', { keep: [5, 7], publicKey: Buffer.from(keys.publicKey).toString('base64') }],
|
||||
];
|
||||
for (const [what, body] of signed) {
|
||||
const signedAt = 1_786_600_000_123;
|
||||
const canonical = canonicalizePayload({ ...body, signedAt, signature: '' });
|
||||
const sig = await crypto.sign(keys.signingSeed, canonical);
|
||||
vectors.push({
|
||||
description: `vault-v2 signed ${what}: signature = Ed25519(signingSeed, canonical); wire body = fields + signedAt + signature(base64)`,
|
||||
body,
|
||||
signedAt,
|
||||
canonical: new TextDecoder().decode(canonical),
|
||||
canonicalHex: hex(canonical),
|
||||
signature: hex(sig),
|
||||
signatureBase64: Buffer.from(sig).toString('base64'),
|
||||
});
|
||||
}
|
||||
|
||||
return vectors;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
console.log('Generating cross-platform test vectors…');
|
||||
|
||||
@@ -837,9 +991,12 @@ async function main() {
|
||||
['storage-hkdf.json', { vectors: await generateStorageEncryptionSubset() }],
|
||||
['blob.json', { vectors: await generateBlobVectors() }],
|
||||
['approval.json', { vectors: await generateApprovalVectors() }],
|
||||
['vault-v2.json', { vectors: await generateVaultV2Vectors() }],
|
||||
];
|
||||
|
||||
const only = new Set(process.argv.slice(2));
|
||||
for (const [name, data] of files) {
|
||||
if (only.size > 0 && !only.has(name)) continue;
|
||||
const path = join(OUT_DIR, name);
|
||||
const versioned = { version: VECTOR_FILE_VERSION, ...data };
|
||||
writeFileSync(path, JSON.stringify(versioned, null, 2) + '\n');
|
||||
|
||||
107
scripts/vault-live-kotlin.ts
Normal file
107
scripts/vault-live-kotlin.ts
Normal file
@@ -0,0 +1,107 @@
|
||||
/**
|
||||
* Live cross-check of the Kotlin vault client against the real TS routes.
|
||||
*
|
||||
* bun run scripts/vault-live-kotlin.ts
|
||||
*
|
||||
* Serves `createVaultRoutes` (memory store) on a free local port, pushes a
|
||||
* few files with the TS client — one compressed, one multi-part, one PNG —
|
||||
* then runs the gated `VaultLiveTest` in android/ with `SHADE_VAULT_LIVE_SPEC`
|
||||
* set. That test reads every file back from Kotlin and edits the vault
|
||||
* (adds two files, removes one). This script then reads the Kotlin-written
|
||||
* version back with the TS client, checks every byte and that untouched
|
||||
* entries kept their objects, and finally edits on top of it from TS.
|
||||
*
|
||||
* Vectors pin the format byte for byte; this pins the conversation — real
|
||||
* HTTP, real signature checks, real SEQ handling — which no vector can.
|
||||
*/
|
||||
import { createHash, randomBytes } from 'node:crypto';
|
||||
import { mkdtemp, readFile, writeFile } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join, resolve } from 'node:path';
|
||||
import { SubtleCryptoProvider } from '../packages/shade-crypto-web/src/index.js';
|
||||
import { createVaultRoutes, MemoryVaultStore } from '../packages/shade-vault/src/server.js';
|
||||
import { HttpVaultTransport } from '../packages/shade-vault/src/http-transport.js';
|
||||
import { VaultClient, deriveVaultKeys } from '../packages/shade-vault/src/client.js';
|
||||
|
||||
const sha256 = (b: Uint8Array) => createHash('sha256').update(b).digest('hex');
|
||||
const enc = (s: string) => new TextEncoder().encode(s);
|
||||
function check(cond: unknown, what: string): asserts cond {
|
||||
if (!cond) throw new Error(`live cross-check failed: ${what}`);
|
||||
}
|
||||
|
||||
const crypto = new SubtleCryptoProvider();
|
||||
const routes = createVaultRoutes(new MemoryVaultStore(), crypto);
|
||||
const server = Bun.serve({ port: 0, hostname: '127.0.0.1', fetch: (req) => routes.fetch(req) });
|
||||
const url = `http://127.0.0.1:${server.port}`;
|
||||
|
||||
try {
|
||||
const masterKey = new Uint8Array(randomBytes(32));
|
||||
const app = 'kotlin-live';
|
||||
const keys = await deriveVaultKeys(masterKey, app);
|
||||
const client = new VaultClient(crypto, keys, new HttpVaultTransport(url));
|
||||
|
||||
const files = [
|
||||
{ path: 'hello.txt', bytes: enc('hei fra TS\n') },
|
||||
{ path: '.scaffold/plan.md', bytes: enc('# Plan\n' + '- [ ] noe å gjøre\n'.repeat(300)), mode: '644' },
|
||||
{ path: 'big.bin', bytes: new Uint8Array(randomBytes(9 * 1024 * 1024)) }, // 3 parts at 4 MiB
|
||||
{ path: 'pic.png', bytes: new Uint8Array([0x89, 0x50, 0x4e, 0x47, ...randomBytes(2000)]) },
|
||||
];
|
||||
const pushed = await client.push(files, Date.now(), 'from TS');
|
||||
console.log(`TS pushed seq ${pushed.seq} (${pushed.uploaded} objects) to ${url}`);
|
||||
const before = await client.manifest();
|
||||
|
||||
const dir = await mkdtemp(join(tmpdir(), 'shade-vault-live-'));
|
||||
const specPath = join(dir, 'spec.json');
|
||||
const kotlinOut = join(dir, 'kotlin-out.json');
|
||||
await writeFile(
|
||||
specPath,
|
||||
JSON.stringify({
|
||||
url,
|
||||
masterKey: Buffer.from(masterKey).toString('hex'),
|
||||
app,
|
||||
files: Object.fromEntries(files.map((f) => [f.path, sha256(f.bytes)])),
|
||||
kotlinOut,
|
||||
}),
|
||||
);
|
||||
|
||||
const androidDir = resolve(import.meta.dir, '../android');
|
||||
const gradle = Bun.spawn(
|
||||
['./gradlew', ':shade-android:test', '--tests', 'no.zyon.shade.VaultLiveTest', '--console=plain'],
|
||||
{ cwd: androidDir, env: { ...process.env, SHADE_VAULT_LIVE_SPEC: specPath }, stdout: 'inherit', stderr: 'inherit' },
|
||||
);
|
||||
check((await gradle.exited) === 0, 'Kotlin VaultLiveTest failed');
|
||||
|
||||
const out = JSON.parse(await readFile(kotlinOut, 'utf8')) as {
|
||||
seq: number;
|
||||
removed: string;
|
||||
files: Record<string, string>;
|
||||
};
|
||||
const after = await client.pull();
|
||||
check(after.manifest.seq === out.seq, `head is ${after.manifest.seq}, Kotlin committed ${out.seq}`);
|
||||
check(!after.files.has(out.removed), `${out.removed} should be gone`);
|
||||
for (const [path, digest] of Object.entries(out.files)) {
|
||||
check(after.files.has(path), `${path} missing`);
|
||||
check(sha256(after.files.get(path)!) === digest, `${path} bytes differ`);
|
||||
}
|
||||
for (const f of files.filter((f) => f.path !== out.removed)) {
|
||||
check(sha256(after.files.get(f.path)!) === sha256(f.bytes), `${f.path} changed`);
|
||||
const was = before.entries.find((e) => e.path === f.path)!;
|
||||
const now = after.manifest.entries.find((e) => e.path === f.path)!;
|
||||
check(JSON.stringify(was) === JSON.stringify(now), `${f.path} entry was rewritten`);
|
||||
}
|
||||
const kotlinBig = after.manifest.entries.find((e) => e.path === 'from-kotlin/big.bin')!;
|
||||
check((kotlinBig.parts?.length ?? 0) === 2, 'Kotlin big.bin should be 2 parts');
|
||||
check(
|
||||
after.manifest.entries.find((e) => e.path === 'from-kotlin/note.md')?.enc === 'deflate-raw',
|
||||
'Kotlin note.md should be compressed',
|
||||
);
|
||||
|
||||
// And TS can keep editing on top of a Kotlin-written head.
|
||||
const ts = await client.edit(() => ({ put: [{ path: 'from-ts.txt', bytes: enc('ok') }] }), Date.now());
|
||||
check(ts.committed && ts.seq === out.seq + 1, 'TS edit on top of Kotlin head');
|
||||
console.log(
|
||||
`LIVE OK — TS→Kotlin read ${files.length} files; Kotlin edit seq ${out.seq} read back by TS; TS edit seq ${ts.seq}`,
|
||||
);
|
||||
} finally {
|
||||
server.stop(true);
|
||||
}
|
||||
227
test-vectors/vault-v2.json
Normal file
227
test-vectors/vault-v2.json
Normal file
@@ -0,0 +1,227 @@
|
||||
{
|
||||
"version": 2,
|
||||
"vectors": [
|
||||
{
|
||||
"description": "vault-v2 keys: vaultId/contentKey/signingSeed = HKDF branches of masterKey for app; publicKey = Ed25519(signingSeed)",
|
||||
"masterKey": "0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20",
|
||||
"app": "scaffold",
|
||||
"vaultId": "9360b12394a010ecfa677dfc38941a00c43ebb22e79a681f76d928285de52dc2",
|
||||
"contentKey": "a5990e3c71b6c11902b0f05afe65d2a1476222026a5ff5a897a670af92629d8e",
|
||||
"signingSeed": "718e842f89c926369c0d2cc9f05b5f40f8bafe30599747b1d1de67fb5ffbca4b",
|
||||
"publicKey": "60666a9e492ce5808d5ce3e2c409d5d374bc540f5546ac54da78acd186959117",
|
||||
"objectAad": "73686164652d7661756c742d6f626a6563742d76317c39333630623132333934613031306563666136373764666333383934316130306334336562623232653739613638316637366439323832383564653532646332",
|
||||
"objectAadUtf8": "shade-vault-object-v1|9360b12394a010ecfa677dfc38941a00c43ebb22e79a681f76d928285de52dc2"
|
||||
},
|
||||
{
|
||||
"description": "vault-v2 entry: small text, compressed, one part",
|
||||
"chunkSize": 4194304,
|
||||
"plaintext": "2320506c616e0a0a2323204ec3a50a2d205b205d206e6f650a2d205b205d206e6f650a2d205b205d206e6f650a2d205b205d206e6f6520616e6e65740a2320506c616e0a0a2323204ec3a50a2d205b205d206e6f650a2d205b205d206e6f650a2d205b205d206e6f650a2d205b205d206e6f6520616e6e65740a2320506c616e0a0a2323204ec3a50a2d205b205d206e6f650a2d205b205d206e6f650a2d205b205d206e6f650a2d205b205d206e6f6520616e6e65740a2320506c616e0a0a2323204ec3a50a2d205b205d206e6f650a2d205b205d206e6f650a2d205b205d206e6f650a2d205b205d206e6f6520616e6e65740a",
|
||||
"stored": "535608c849cce3e2525656f03bbc944b57215a2156212f3f153f4b21312f2fb5844b79686a0600",
|
||||
"enc": "deflate-raw",
|
||||
"parts": [
|
||||
{
|
||||
"nonce": "101112131415161718191a1b",
|
||||
"plaintext": "535608c849cce3e2525656f03bbc944b57215a2156212f3f153f4b21312f2fb5844b79686a0600",
|
||||
"wire": "101112131415161718191a1b3df181a4021d0d030b94331430d5e4a11b55bbf4164312f6280db7db72629e5183b7bd473ac4d8c7b6ed2edc7b18a6e6c11c5c340906e4",
|
||||
"hash": "19b8d667f1d6455f49687a54b5ea3e7540ff13138abd34a68ece85e26fac2480"
|
||||
}
|
||||
],
|
||||
"entry": {
|
||||
"path": ".scaffold/plan.md",
|
||||
"hash": "19b8d667f1d6455f49687a54b5ea3e7540ff13138abd34a68ece85e26fac2480",
|
||||
"enc": "deflate-raw",
|
||||
"size": 244
|
||||
}
|
||||
},
|
||||
{
|
||||
"description": "vault-v2 entry: multi-part (chunkSize 32), compressed — concatenate parts, then inflate",
|
||||
"chunkSize": 32,
|
||||
"plaintext": "6c696e6a6520303a20300a6c696e6a6520313a203931390a6c696e6a6520323a203833380a6c696e6a6520333a203735370a6c696e6a6520343a203637360a6c696e6a6520353a203539350a6c696e6a6520363a203531340a6c696e6a6520373a203433330a6c696e6a6520383a203335320a6c696e6a6520393a203237310a6c696e6a652031303a203139300a6c696e6a652031313a203130390a6c696e6a652031323a2032380a6c696e6a652031333a203934370a6c696e6a652031343a203836360a6c696e6a652031353a203738350a6c696e6a652031363a203730340a6c696e6a652031373a203632330a6c696e6a652031383a203534320a6c696e6a652031393a203436310a6c696e6a652032303a203338300a6c696e6a652032313a203239390a6c696e6a652032323a203231380a6c696e6a652032333a203133370a6c696e6a652032343a2035360a6c696e6a652032353a203937350a6c696e6a652032363a203839340a6c696e6a652032373a203831330a6c696e6a652032383a203733320a6c696e6a652032393a203635310a6c696e6a652033303a203537300a6c696e6a652033313a203438390a6c696e6a652033323a203430380a6c696e6a652033333a203332370a6c696e6a652033343a203234360a6c696e6a652033353a203136350a6c696e6a652033363a2038340a6c696e6a652033373a20330a6c696e6a652033383a203932320a6c696e6a652033393a203834310a",
|
||||
"stored": "3dd1316e84310884d17e4f314730600ccc7d52245ae5fe65f4479eedfc49483ce1f7f7efcf1716b15eefffa7116373c3898ebe114465ddd8c4a97323899cbc7188b47da3881d71a38948bf31849769e9226c3e04236cc9604eb80c16c46c216c137da4b024aac5b043d492c38a382e8835915b121b621f517c11d1a2b8113e9f733c1493c583b090c53791a2781253a2f8217a44f122da44f1262a44f1214e8a128bc812258cd82d4a38b1d7e76b8208172536e15b9648c28e2cf158448922048926c6058979c6ecf507",
|
||||
"enc": "deflate-raw",
|
||||
"parts": [
|
||||
{
|
||||
"nonce": "202122232425262728292a2b",
|
||||
"plaintext": "3dd1316e84310884d17e4f314730600ccc7d52245ae5fe65f4479eedfc49483c",
|
||||
"wire": "202122232425262728292a2b0e79d38efa3cc03de999a559f68f49e2dc720f2b54641279bf38c56fbb5657b7006f03b9ac641e01a39c9c300b6727bc",
|
||||
"hash": "cd82d8614493d470a9dfdb05d5bff314c9f2db8b20182154177751c5c47838b3"
|
||||
},
|
||||
{
|
||||
"nonce": "2122232425262728292a2b2c",
|
||||
"plaintext": "e1f7f7efcf1716b15eefffa7116373c3898ebe114465ddd8c4a97323899cbc71",
|
||||
"wire": "2122232425262728292a2b2c8e0fc4531fc8900f2cf5e44a0ca9d99ae969c571754f1fcb8ea3682976ab70a4da805b0ebbec3b183a6187688b283599",
|
||||
"hash": "dc1ee30922d1aa7d7709c1842c301b104cef41222a04318aff7b4f9be86229a1"
|
||||
},
|
||||
{
|
||||
"nonce": "22232425262728292a2b2c2d",
|
||||
"plaintext": "88b47da3881d71a38948bf31849769e9226c3e04236cc9604eb80c16c46c216c",
|
||||
"wire": "22232425262728292a2b2c2dca0d1c8465b46b1edc12987c6288d4df1327df36c40d998240b918dd99e4a1633179bc85a965eb2fc2923c6623b11a64",
|
||||
"hash": "1040602c1eb4eb76619af24ceab63b9dd0879858f02e3810f97b35d5a466f3d5"
|
||||
},
|
||||
{
|
||||
"nonce": "232425262728292a2b2c2d2e",
|
||||
"plaintext": "137da4b024aac5b043d492c38a382e8835915b121b621f517c11d1a2b8113e9f",
|
||||
"wire": "232425262728292a2b2c2d2eb6ad5e0146a9cd45e063c0d6a0706a8ef94ae7dc57222ec73a49de99cabe4b47ad115ba42b0d88d520b3ec4cfe6ce107",
|
||||
"hash": "1b733f9993aa55c6aef12b8efaf338f81be7b22738e0b3a169084af15d18a12f"
|
||||
},
|
||||
{
|
||||
"nonce": "2425262728292a2b2c2d2e2f",
|
||||
"plaintext": "733c1493c583b090c53791a2781253a2f8217a44f122da44f1262a44f1214e8a",
|
||||
"wire": "2425262728292a2b2c2d2e2fd929c8f629fc833859bc2f6516434460e22fe68efb36823c7fcd67744d90253c7d9d8276663308a283256c0553bbc893",
|
||||
"hash": "5abd3592557cfa7a6767042afa52be02c22ecd0e418c3e1929fa662a5c85cb49"
|
||||
},
|
||||
{
|
||||
"nonce": "25262728292a2b2c2d2e2f30",
|
||||
"plaintext": "128bc812258cd82d4a38b1d7e76b8208172536e15b9648c28e2cf15844892204",
|
||||
"wire": "25262728292a2b2c2d2e2f300feb2c185b6c0d9c9b7c53c8b4667e470524922fb75bf5a86849b848fa6d6c616f3909067dda152d8f7c2a0078de3ed6",
|
||||
"hash": "46fdb7c7d2e74f2d1000f4e97a159bf5f68f85ed36a36046c31646c1d32a62f2"
|
||||
},
|
||||
{
|
||||
"nonce": "262728292a2b2c2d2e2f3031",
|
||||
"plaintext": "8926c6058979c6ecf507",
|
||||
"wire": "262728292a2b2c2d2e2f3031dd501f12336af9813a6b845aa252e8bb446f9eff169d0db9d476",
|
||||
"hash": "2bcd7c174155c4a3e93df91e47158ec6b4ff0eb8bf5b4b216bcf126767037efc"
|
||||
}
|
||||
],
|
||||
"entry": {
|
||||
"path": "logs/2026-10-16.md",
|
||||
"hash": "cd82d8614493d470a9dfdb05d5bff314c9f2db8b20182154177751c5c47838b3",
|
||||
"parts": [
|
||||
"cd82d8614493d470a9dfdb05d5bff314c9f2db8b20182154177751c5c47838b3",
|
||||
"dc1ee30922d1aa7d7709c1842c301b104cef41222a04318aff7b4f9be86229a1",
|
||||
"1040602c1eb4eb76619af24ceab63b9dd0879858f02e3810f97b35d5a466f3d5",
|
||||
"1b733f9993aa55c6aef12b8efaf338f81be7b22738e0b3a169084af15d18a12f",
|
||||
"5abd3592557cfa7a6767042afa52be02c22ecd0e418c3e1929fa662a5c85cb49",
|
||||
"46fdb7c7d2e74f2d1000f4e97a159bf5f68f85ed36a36046c31646c1d32a62f2",
|
||||
"2bcd7c174155c4a3e93df91e47158ec6b4ff0eb8bf5b4b216bcf126767037efc"
|
||||
],
|
||||
"enc": "deflate-raw",
|
||||
"size": 543,
|
||||
"mode": "644"
|
||||
}
|
||||
},
|
||||
{
|
||||
"description": "vault-v2 entry: PNG magic, never compressed, one part",
|
||||
"chunkSize": 4194304,
|
||||
"plaintext": "89504e470d0a1a0a00000000000000000000000000000000000000000000000000000000000000000000000000000000",
|
||||
"stored": "89504e470d0a1a0a00000000000000000000000000000000000000000000000000000000000000000000000000000000",
|
||||
"enc": null,
|
||||
"parts": [
|
||||
{
|
||||
"nonce": "303132333435363738393a3b",
|
||||
"plaintext": "89504e470d0a1a0a00000000000000000000000000000000000000000000000000000000000000000000000000000000",
|
||||
"wire": "303132333435363738393a3b69d66e5792c16a018c81a00c8d7739372b72143758d5f60c7fceb1e92a465ca1c10c59e9fd22d991085376961813de4939087ff23a9d4fae2bb4ad92b4c7c559",
|
||||
"hash": "1124f8b638b462ccd8857e71cb5ba722e624a097cda768566ee643c7a57a6de4"
|
||||
}
|
||||
],
|
||||
"entry": {
|
||||
"path": "bilde.png",
|
||||
"hash": "1124f8b638b462ccd8857e71cb5ba722e624a097cda768566ee643c7a57a6de4",
|
||||
"size": 48
|
||||
}
|
||||
},
|
||||
{
|
||||
"description": "vault-v2 manifest v2: plaintext = \"SVM2\" || deflate-raw(json utf-8)",
|
||||
"manifest": {
|
||||
"version": 2,
|
||||
"seq": 7,
|
||||
"at": 1786600000000,
|
||||
"entries": [
|
||||
{
|
||||
"path": ".scaffold/plan.md",
|
||||
"hash": "19b8d667f1d6455f49687a54b5ea3e7540ff13138abd34a68ece85e26fac2480",
|
||||
"enc": "deflate-raw",
|
||||
"size": 244
|
||||
},
|
||||
{
|
||||
"path": "logs/2026-10-16.md",
|
||||
"hash": "cd82d8614493d470a9dfdb05d5bff314c9f2db8b20182154177751c5c47838b3",
|
||||
"parts": [
|
||||
"cd82d8614493d470a9dfdb05d5bff314c9f2db8b20182154177751c5c47838b3",
|
||||
"dc1ee30922d1aa7d7709c1842c301b104cef41222a04318aff7b4f9be86229a1",
|
||||
"1040602c1eb4eb76619af24ceab63b9dd0879858f02e3810f97b35d5a466f3d5",
|
||||
"1b733f9993aa55c6aef12b8efaf338f81be7b22738e0b3a169084af15d18a12f",
|
||||
"5abd3592557cfa7a6767042afa52be02c22ecd0e418c3e1929fa662a5c85cb49",
|
||||
"46fdb7c7d2e74f2d1000f4e97a159bf5f68f85ed36a36046c31646c1d32a62f2",
|
||||
"2bcd7c174155c4a3e93df91e47158ec6b4ff0eb8bf5b4b216bcf126767037efc"
|
||||
],
|
||||
"enc": "deflate-raw",
|
||||
"size": 543,
|
||||
"mode": "644"
|
||||
},
|
||||
{
|
||||
"path": "bilde.png",
|
||||
"hash": "1124f8b638b462ccd8857e71cb5ba722e624a097cda768566ee643c7a57a6de4",
|
||||
"size": 48
|
||||
}
|
||||
],
|
||||
"message": "nattlig backup"
|
||||
},
|
||||
"json": "{\"version\":2,\"seq\":7,\"at\":1786600000000,\"entries\":[{\"path\":\".scaffold/plan.md\",\"hash\":\"19b8d667f1d6455f49687a54b5ea3e7540ff13138abd34a68ece85e26fac2480\",\"enc\":\"deflate-raw\",\"size\":244},{\"path\":\"logs/2026-10-16.md\",\"hash\":\"cd82d8614493d470a9dfdb05d5bff314c9f2db8b20182154177751c5c47838b3\",\"parts\":[\"cd82d8614493d470a9dfdb05d5bff314c9f2db8b20182154177751c5c47838b3\",\"dc1ee30922d1aa7d7709c1842c301b104cef41222a04318aff7b4f9be86229a1\",\"1040602c1eb4eb76619af24ceab63b9dd0879858f02e3810f97b35d5a466f3d5\",\"1b733f9993aa55c6aef12b8efaf338f81be7b22738e0b3a169084af15d18a12f\",\"5abd3592557cfa7a6767042afa52be02c22ecd0e418c3e1929fa662a5c85cb49\",\"46fdb7c7d2e74f2d1000f4e97a159bf5f68f85ed36a36046c31646c1d32a62f2\",\"2bcd7c174155c4a3e93df91e47158ec6b4ff0eb8bf5b4b216bcf126767037efc\"],\"enc\":\"deflate-raw\",\"size\":543,\"mode\":\"644\"},{\"path\":\"bilde.png\",\"hash\":\"1124f8b638b462ccd8857e71cb5ba722e624a097cda768566ee643c7a57a6de4\",\"size\":48}],\"message\":\"nattlig backup\"}",
|
||||
"plaintext": "53564d32ad92cd6e9c370c455fa5d0fab32352fcd3bc4a910529918ed1f1d8f54c1b2081dfbd98a208d24d57e596c03d87e0fddefeccf7ebf3eba59df068d7fcbd9df4687e6b275013e9ffccd1f2727b7fce6b3bfdfabdbdf9ed4b3bb5c7ebf2aad7f3fef476f6cbe3cb6e47fbe2d7fb0a66d816d1822dc45c34c5d49982d3472a53af8201c33cf62017cb95c68952be90acb73b70b553db5967bfe5c3bb7f6d47bb3e7fcb7642a28fe387c5f9f5e9fa093bca03f407907f69ac6db84d80688e4dda7deedad17973540da0350b77586007436002556558bc486d588c76b4377fbfddaffe3fb2f682ccd127e20677ddaa7d2e30c2353a04745a590488e89d0698576950cd4813c4e9d08e069dba745c9041192a02d30b69a5878c987b77d3696cd5318741afa93178b393488dcdf788d0316ace39dc99977816605896d7185606911a883a2c7b0c0799ddc80b78833960b5a3f1fd6d3c915957b9baa86827f472c6c88e0b31d7ee49606b244c9ce522e8bc8c57d06c4723a91dba74632a156ee8bd17e554079e515c62659c7b880fe9246b80902cd8035db0b01d0d636d5da004cc8b7ce41cbb262429b0e592a0aa9e61511c140812ab00ff761d9ab5dae7ff6a19d338dacbebce766a42d47eaa5c3c9f773ebe5d9e7e2a3c2095850c0b125c6b9bb1a6c20a0e57c41424ef53d7761563914ca1b1d4595d76d20f2cd9c7e7a3bde4f5ea4f77f4c56fb7f3f3d32fe1ebb73fdedac75f",
|
||||
"nonce": "c0c0c0c0c0c0c0c0c0c0c0c0",
|
||||
"wire": "c0c0c0c0c0c0c0c0c0c0c0c01190980ff0edf6049a9dd9120f8c01a273076cddd38f51af94f999837a8d78f3197a2a1ce77cde7fe2b3b455a7ae03810e2dd77e8bed66bcf7ccc2939a86639bb84872395229dea7dbef6c454a5444e080685320990a600753dbbaa6992e654d4827c8b3186c98b66a1f48766a6d41d1caeadbcfd3c82023b6171ab2a89b87acb7de83069a47280aba9bf01a784cfdab45983a96015890a00db4a70cd1fea7ecefc2ce813a193d941f0f93d2654c6fb0eb8d9d1e5327af17e03828aa1e33fbb0963d647d794c9e758bbfbfda7f6d799563d4532494abe21eae51e69da7b9721f54c6b08f3977138869268ec0005fdf8e2dfe69f715e34a403788d9ea35b8a1da9c62e5aeac7b88564d787d8f2ecb9e8c9d1316722651c245ceeca875ac91dcc920e26158b40ab594d0ae006f7c9df76559f377ef1373ed3bdb3dafd7bf9b263e9ac6a0563f4ea31478567a4ec548d8bd7dcc8206f9a2703d2a535ddf93935f2fd47b0937d760cb694434989262cead89b35bce9f3d69a09dcb0e8ac4ea1046e13ff06306cd644e9d53aa5c99847aed0847f5804c9ba09e661fad5641116846f102af64e1d170af6f54a149c757830e7ac5c415510de66874a7fd488d01b58e779ef002afb7ae07049fe6b57b957e35ac70d9d6904c5a1f55c0ffe55da94ec6b88731e5b7a361242303e48906991f863c9c6d4f783899d0ba97168fcf9e96aa26c922ec66b0d7e61b2e56f7f52143d964bc40ec9222f3d91892bcaed3d3137e0ddb6c68b223",
|
||||
"hash": "cc6c2374920cb357e44ec3b907177b8f10bde789df9e7a707d483be7dce68609"
|
||||
},
|
||||
{
|
||||
"description": "vault-v2 manifest v1: plaintext = json utf-8 (back-compat, still readable)",
|
||||
"manifest": {
|
||||
"version": 1,
|
||||
"seq": 1,
|
||||
"at": 1786500000000,
|
||||
"entries": [
|
||||
{
|
||||
"path": "notes.yaml",
|
||||
"hash": "1124f8b638b462ccd8857e71cb5ba722e624a097cda768566ee643c7a57a6de4",
|
||||
"size": 48
|
||||
}
|
||||
]
|
||||
},
|
||||
"json": "{\"version\":1,\"seq\":1,\"at\":1786500000000,\"entries\":[{\"path\":\"notes.yaml\",\"hash\":\"1124f8b638b462ccd8857e71cb5ba722e624a097cda768566ee643c7a57a6de4\",\"size\":48}]}",
|
||||
"plaintext": "7b2276657273696f6e223a312c22736571223a312c226174223a313738363530303030303030302c22656e7472696573223a5b7b2270617468223a226e6f7465732e79616d6c222c2268617368223a2231313234663862363338623436326363643838353765373163623562613732326536323461303937636461373638353636656536343363376135376136646534222c2273697a65223a34387d5d7d",
|
||||
"nonce": "d0d0d0d0d0d0d0d0d0d0d0d0",
|
||||
"wire": "d0d0d0d0d0d0d0d0d0d0d0d0eaa53cdb2e8e93a47c29a2ea9d62c2d3beb5304d6c2250d6edbe3db0219d612e8203060d698f80c3d527dab75c10856f061f55aac3c8dcf44d454b09038791d993576c4099bfb0db8e98d9d1d583858b61a63667bd3fcac71b6c60ecd62213e3775cbb519da048a55c73d064ea0be5518952e92d5d508c0fe0be4c12d60125ab19f908e13687f2322b647f347297d037e0b3b6e6d2b32fb2723ca9cc39b7227869596194bce9568fbde4004d53a8",
|
||||
"hash": "d450e5f430700dc7d33adf75904f92069c5e4075276dbbdca7b484603c783475"
|
||||
},
|
||||
{
|
||||
"description": "vault-v2 signed commit: signature = Ed25519(signingSeed, canonical); wire body = fields + signedAt + signature(base64)",
|
||||
"body": {
|
||||
"manifest": "cc6c2374920cb357e44ec3b907177b8f10bde789df9e7a707d483be7dce68609",
|
||||
"seq": 7,
|
||||
"at": 1786600000000,
|
||||
"hashes": [
|
||||
"19b8d667f1d6455f49687a54b5ea3e7540ff13138abd34a68ece85e26fac2480",
|
||||
"cd82d8614493d470a9dfdb05d5bff314c9f2db8b20182154177751c5c47838b3",
|
||||
"dc1ee30922d1aa7d7709c1842c301b104cef41222a04318aff7b4f9be86229a1",
|
||||
"1040602c1eb4eb76619af24ceab63b9dd0879858f02e3810f97b35d5a466f3d5",
|
||||
"1b733f9993aa55c6aef12b8efaf338f81be7b22738e0b3a169084af15d18a12f",
|
||||
"5abd3592557cfa7a6767042afa52be02c22ecd0e418c3e1929fa662a5c85cb49",
|
||||
"46fdb7c7d2e74f2d1000f4e97a159bf5f68f85ed36a36046c31646c1d32a62f2",
|
||||
"2bcd7c174155c4a3e93df91e47158ec6b4ff0eb8bf5b4b216bcf126767037efc",
|
||||
"1124f8b638b462ccd8857e71cb5ba722e624a097cda768566ee643c7a57a6de4"
|
||||
],
|
||||
"publicKey": "YGZqnkks5YCNXOPixAnV03S8VA9VRqxU2nis0YaVkRc="
|
||||
},
|
||||
"signedAt": 1786600000123,
|
||||
"canonical": "{\"at\":1786600000000,\"hashes\":[\"19b8d667f1d6455f49687a54b5ea3e7540ff13138abd34a68ece85e26fac2480\",\"cd82d8614493d470a9dfdb05d5bff314c9f2db8b20182154177751c5c47838b3\",\"dc1ee30922d1aa7d7709c1842c301b104cef41222a04318aff7b4f9be86229a1\",\"1040602c1eb4eb76619af24ceab63b9dd0879858f02e3810f97b35d5a466f3d5\",\"1b733f9993aa55c6aef12b8efaf338f81be7b22738e0b3a169084af15d18a12f\",\"5abd3592557cfa7a6767042afa52be02c22ecd0e418c3e1929fa662a5c85cb49\",\"46fdb7c7d2e74f2d1000f4e97a159bf5f68f85ed36a36046c31646c1d32a62f2\",\"2bcd7c174155c4a3e93df91e47158ec6b4ff0eb8bf5b4b216bcf126767037efc\",\"1124f8b638b462ccd8857e71cb5ba722e624a097cda768566ee643c7a57a6de4\"],\"manifest\":\"cc6c2374920cb357e44ec3b907177b8f10bde789df9e7a707d483be7dce68609\",\"publicKey\":\"YGZqnkks5YCNXOPixAnV03S8VA9VRqxU2nis0YaVkRc=\",\"seq\":7,\"signedAt\":1786600000123}",
|
||||
"canonicalHex": "7b226174223a313738363630303030303030302c22686173686573223a5b2231396238643636376631643634353566343936383761353462356561336537353430666631333133386162643334613638656365383565323666616332343830222c2263643832643836313434393364343730613964666462303564356266663331346339663264623862323031383231353431373737353163356334373833386233222c2264633165653330393232643161613764373730396331383432633330316231303463656634313232326130343331386166663762346639626538363232396131222c2231303430363032633165623465623736363139616632346365616236336239646430383739383538663032653338313066393762333564356134363666336435222c2231623733336639393933616135356336616566313262386566616633333866383162653762323237333865306233613136393038346166313564313861313266222c2235616264333539323535376366613761363736373034326166613532626530326332326563643065343138633365313932396661363632613563383563623439222c2234366664623763376432653734663264313030306634653937613135396266356636386638356564333661333630343663333136343663316433326136326632222c2232626364376331373431353563346133653933646639316534373135386563366234666630656238626635623462323136626366313236373637303337656663222c2231313234663862363338623436326363643838353765373163623562613732326536323461303937636461373638353636656536343363376135376136646534225d2c226d616e6966657374223a2263633663323337343932306362333537653434656333623930373137376238663130626465373839646639653761373037643438336265376463653638363039222c227075626c69634b6579223a2259475a716e6b6b733559434e584f506978416e56303353385641395652717855326e6973305961566b52633d222c22736571223a372c227369676e65644174223a313738363630303030303132337d",
|
||||
"signature": "495f601cfbe2574b483a1710e4e40ec252a21f27a0454f7220537d3d9b19230ae38402d9119ae4df9f2506c01472370ed30d26bd22ccac1e2ce4fa6028c5790b",
|
||||
"signatureBase64": "SV9gHPviV0tIOhcQ5OQOwlKiHyegRU9yIFN9PZsZIwrjhALZEZrk358lBsAUcjcO0w0mvSLMrB4s5PpgKMV5Cw=="
|
||||
},
|
||||
{
|
||||
"description": "vault-v2 signed prune: signature = Ed25519(signingSeed, canonical); wire body = fields + signedAt + signature(base64)",
|
||||
"body": {
|
||||
"keep": [
|
||||
5,
|
||||
7
|
||||
],
|
||||
"publicKey": "YGZqnkks5YCNXOPixAnV03S8VA9VRqxU2nis0YaVkRc="
|
||||
},
|
||||
"signedAt": 1786600000123,
|
||||
"canonical": "{\"keep\":[5,7],\"publicKey\":\"YGZqnkks5YCNXOPixAnV03S8VA9VRqxU2nis0YaVkRc=\",\"signedAt\":1786600000123}",
|
||||
"canonicalHex": "7b226b656570223a5b352c375d2c227075626c69634b6579223a2259475a716e6b6b733559434e584f506978416e56303353385641395652717855326e6973305961566b52633d222c227369676e65644174223a313738363630303030303132337d",
|
||||
"signature": "928c803849691673610b9cb98062f75e81bdbac9b192880ffcd70d57abe0bb3b1878183b1827601a9b43dd4d8e615f9790a97ecfe2da35beacf5200129a73f0e",
|
||||
"signatureBase64": "koyAOElpFnNhC5y5gGL3XoG9usmxkogP/NcNV6vguzsYeBg7GCdgGptD3U2OYV+XkKl+z+LaNb6s9SABKac/Dg=="
|
||||
}
|
||||
]
|
||||
}
|
||||
Reference in New Issue
Block a user