From ec8420cdab7e9b111cc955340407999f9819b30a Mon Sep 17 00:00:00 2001 From: Anthony Ettinger Date: Mon, 30 Nov 2026 16:54:42 +0000 Subject: [PATCH] Free end-to-end encrypted backups on c0mpute (Sign in with c0mpute) sk33p login / logout / backup FILE [--name N] / backups / restore NAME [-o OUT] / backup --rm NAME, plus local MCP tools backup, list_backups, restore. - Sign in: OAuth 2.1 + PKCE (S256) loopback redirect against c0mpute.com, scope storage:write, public client c0c_T6_uQc-rZh8zTgXvzFfHUA (registered via RFC 7591 POST /api/oauth/register). `login --token c0k_...` for headless machines. Token in ~/.config/sk33p/c0mpute.json (0600); logout revokes it (RFC 7009). - sk33p's encryption (src/vault.rs), symmetric only so quantum-safe: Argon2id (64 MiB, t=3, p=1) or keyfile HKDF -> 256-bit KEK wrapping a random 256-bit key per file, XChaCha20-Poly1305 for both. Versioned header with algorithm ids, fully authenticated; unknown versions/ids are refused. - c0mpute packaging (src/sealed.rs): a port of @profullstack/c0mpute-sealed's c0mpute-private-v1 format and signed v1 hosting record, checked against the reference Rust crate (opens with the owner's identity, custody unwraps). - File names, sizes and keys live in an encrypted index object at an address derived from the key and the account, so a new machine needs only login + key. A mistyped passphrase is refused instead of starting an empty second set. - Cloud: pricing card, FAQ ("Do you keep my files?") and /docs section. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 588 +++++++++++++++++++++++++++- Cargo.toml | 15 +- README.md | 48 +++ cloud/src/page.ts | 29 +- cloud/test/app.test.ts | 17 + src/backup.rs | 849 +++++++++++++++++++++++++++++++++++++++++ src/c0mpute.rs | 429 +++++++++++++++++++++ src/cli.rs | 12 + src/main.rs | 5 + src/mcp.rs | 47 +++ src/sealed.rs | 385 +++++++++++++++++++ src/vault.rs | 288 ++++++++++++++ 12 files changed, 2703 insertions(+), 9 deletions(-) create mode 100644 src/backup.rs create mode 100644 src/c0mpute.rs create mode 100644 src/sealed.rs create mode 100644 src/vault.rs diff --git a/Cargo.lock b/Cargo.lock index f738488..0028a4f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,12 +2,103 @@ # It is not intended for manual editing. version = 3 +[[package]] +name = "aead" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" +dependencies = [ + "crypto-common", + "generic-array", +] + +[[package]] +name = "aes" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures 0.2.17", +] + +[[package]] +name = "aes-gcm" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1" +dependencies = [ + "aead", + "aes", + "cipher", + "ctr", + "ghash", + "subtle", + "zeroize", +] + +[[package]] +name = "argon2" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c3610892ee6e0cbce8ae2700349fcf8f98adb0dbfbee85aec3c9179d29cc072" +dependencies = [ + "base64ct", + "blake2", + "cpufeatures 0.2.17", + "password-hash", +] + +[[package]] +name = "arrayvec" +version = "0.7.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47a64a0fd06e123e9e3cf3ad01432af17dcab8185e8023edcf184fe696f9675d" + [[package]] name = "base64" version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + +[[package]] +name = "blake2" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe" +dependencies = [ + "digest", +] + +[[package]] +name = "blake3" +version = "1.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64c0e36294adc8db531500e3f2b8ec75c4af9177271e9c6d33f93609d56e57cd" +dependencies = [ + "arrayvec", + "cc", + "cfg-if", + "constant_time_eq", + "cpufeatures 0.3.1", +] + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + [[package]] name = "cc" version = "1.12.0" @@ -24,6 +115,142 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" +[[package]] +name = "chacha20" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures 0.2.17", +] + +[[package]] +name = "chacha20poly1305" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35" +dependencies = [ + "aead", + "chacha20", + "cipher", + "poly1305", + "zeroize", +] + +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common", + "inout", + "zeroize", +] + +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + +[[package]] +name = "constant_time_eq" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "144e7f1de087984240b7816d47f698b414979faa6f40839c5b86d6bd47db57b7" +dependencies = [ + "rustversion", +] + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "rand_core", + "typenum", +] + +[[package]] +name = "ctr" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835" +dependencies = [ + "cipher", +] + +[[package]] +name = "curve25519-dalek" +version = "4.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "curve25519-dalek-derive", + "digest", + "fiat-crypto", + "rustc_version", + "subtle", + "zeroize", +] + +[[package]] +name = "curve25519-dalek-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid", + "zeroize", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", + "subtle", +] + [[package]] name = "displaydoc" version = "0.2.7" @@ -32,9 +259,39 @@ checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.10", +] + +[[package]] +name = "ed25519" +version = "2.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" +dependencies = [ + "pkcs8", + "signature", +] + +[[package]] +name = "ed25519-dalek" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9" +dependencies = [ + "curve25519-dalek", + "ed25519", + "serde", + "sha2", + "subtle", + "zeroize", ] +[[package]] +name = "fiat-crypto" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" + [[package]] name = "find-msvc-tools" version = "0.1.16" @@ -50,6 +307,16 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + [[package]] name = "getrandom" version = "0.2.17" @@ -61,6 +328,34 @@ dependencies = [ "wasi", ] +[[package]] +name = "ghash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1" +dependencies = [ + "opaque-debug", + "polyval", +] + +[[package]] +name = "hkdf" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" +dependencies = [ + "hmac", +] + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest", +] + [[package]] name = "hqtui" version = "0.2.0" @@ -170,6 +465,15 @@ dependencies = [ "icu_properties", ] +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "generic-array", +] + [[package]] name = "itoa" version = "1.0.19" @@ -206,12 +510,62 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "opaque-debug" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" + +[[package]] +name = "password-hash" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166" +dependencies = [ + "base64ct", + "rand_core", + "subtle", +] + [[package]] name = "percent-encoding" version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "spki", +] + +[[package]] +name = "poly1305" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf" +dependencies = [ + "cpufeatures 0.2.17", + "opaque-debug", + "universal-hash", +] + +[[package]] +name = "polyval" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "opaque-debug", + "universal-hash", +] + [[package]] name = "potential_utf" version = "0.1.6" @@ -221,6 +575,15 @@ dependencies = [ "zerovec", ] +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -239,6 +602,36 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "libc", + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom", +] + [[package]] name = "ring" version = "0.17.14" @@ -250,7 +643,37 @@ dependencies = [ "getrandom", "libc", "untrusted", - "windows-sys", + "windows-sys 0.52.0", +] + +[[package]] +name = "rpassword" +version = "7.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa2c5d9304b618df61ff17f3d3485c6e1854a3d94902a49abbb8d43dfbe0464" +dependencies = [ + "libc", + "rtoolbox", + "windows-sys 0.61.2", +] + +[[package]] +name = "rtoolbox" +version = "0.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a1efe12a1469752d0e6ff5ebec0b6ef4924cc5c4c71046b0ec730040535819d" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", ] [[package]] @@ -288,6 +711,18 @@ dependencies = [ "untrusted", ] +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + [[package]] name = "serde" version = "1.0.229" @@ -295,6 +730,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" dependencies = [ "serde_core", + "serde_derive", ] [[package]] @@ -314,7 +750,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.10", ] [[package]] @@ -330,20 +766,52 @@ dependencies = [ "zmij", ] +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest", +] + [[package]] name = "shlex" version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "rand_core", +] + [[package]] name = "sk33p" version = "0.2.0" dependencies = [ + "aes-gcm", + "argon2", + "base64", + "blake3", "cc", + "chacha20poly1305", + "ed25519-dalek", + "hkdf", "hqtui", + "rand", + "rpassword", "serde_json", + "sha2", "ureq", + "x25519-dalek", + "zeroize", ] [[package]] @@ -352,6 +820,16 @@ version = "1.16.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + [[package]] name = "stable_deref_trait" version = "1.2.1" @@ -364,6 +842,17 @@ version = "2.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "syn" version = "3.0.10" @@ -383,7 +872,7 @@ checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.10", ] [[package]] @@ -396,12 +885,28 @@ dependencies = [ "zerovec", ] +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + [[package]] name = "unicode-ident" version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" +[[package]] +name = "universal-hash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" +dependencies = [ + "crypto-common", + "subtle", +] + [[package]] name = "untrusted" version = "0.9.0" @@ -419,6 +924,8 @@ dependencies = [ "once_cell", "rustls", "rustls-pki-types", + "serde", + "serde_json", "url", "webpki-roots 0.26.11", ] @@ -450,6 +957,12 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" @@ -474,6 +987,12 @@ dependencies = [ "rustls-pki-types", ] +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + [[package]] name = "windows-sys" version = "0.52.0" @@ -483,6 +1002,15 @@ dependencies = [ "windows-targets", ] +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + [[package]] name = "windows-targets" version = "0.52.6" @@ -553,6 +1081,18 @@ version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" +[[package]] +name = "x25519-dalek" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7e468321c81fb07fa7f4c636c3972b9100f0346e5b6a9f2bd0603a52f7ed277" +dependencies = [ + "curve25519-dalek", + "rand_core", + "serde", + "zeroize", +] + [[package]] name = "yoke" version = "0.8.4" @@ -572,10 +1112,30 @@ checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.10", "synstructure", ] +[[package]] +name = "zerocopy" +version = "0.8.66" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cba8a86aee14fc8cc6c208af60854b3d4ab7185a9a369a12c648faa2716ff42a" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.66" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f89bca3b96ceb3cfcb4572790402f977442270d252b9a8504ebc258760c55f94" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "zerofrom" version = "0.1.8" @@ -593,7 +1153,7 @@ checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.10", "synstructure", ] @@ -602,6 +1162,20 @@ name = "zeroize" version = "1.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] [[package]] name = "zerotrie" @@ -633,7 +1207,7 @@ checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.10", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index e08cff0..b9be371 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,7 +15,20 @@ build = "build.rs" [dependencies] serde_json = "1" hqtui = { git = "https://github.com/profullstack/hqtui" } -ureq = { version = "2", default-features = false, features = ["tls"] } +ureq = { version = "2", default-features = false, features = ["tls", "json"] } +# Backups: sk33p's E2E layer (symmetric, quantum-safe) and c0mpute's sealed format. +argon2 = { version = "0.5", default-features = false, features = ["alloc"] } +chacha20poly1305 = "0.10" +aes-gcm = { version = "0.10", features = ["zeroize"] } +hkdf = "0.12" +sha2 = "0.10" +blake3 = "1" +x25519-dalek = { version = "2", features = ["static_secrets", "zeroize"] } +ed25519-dalek = { version = "2", features = ["zeroize"] } +rand = "0.8" +base64 = "0.22" +zeroize = "1" +rpassword = "7" [build-dependencies] cc = "1" diff --git a/README.md b/README.md index d605be5..46efc4f 100644 --- a/README.md +++ b/README.md @@ -67,6 +67,54 @@ explanation and preview (with FILE it sends the same context). Each ask is one call against your API plan. Get a free key at https://sk33p.pwa.pit.world/key and save it: `mkdir -p ~/.config/sk33p && echo sk33p_... > ~/.config/sk33p/key`. +## Back up to c0mpute (free) + +End-to-end encrypted workbook backups on the [c0mpute](https://c0mpute.com) network, +free with a c0mpute account. Encryption happens in `sk33p` on your machine; neither +sk33p nor c0mpute can read the backups or see their names. + +```sh +sk33p login # Sign in with c0mpute: browser, OAuth 2.1 + PKCE, scope storage:write +sk33p login --token c0k_... # or store a c0mpute API key (no browser on this machine) +sk33p backup budget.xlsx # asks for a backup passphrase (twice, the first time) +sk33p backup q3.xlsx --name "Q3 forecast" +sk33p backups # NAME SIZE BACKED UP (UTC), from the encrypted index +sk33p restore "Q3 forecast" -o q3.xlsx +sk33p backup --rm budget.xlsx +sk33p logout # revokes the OAuth token and forgets it +``` + +- **Key**: a passphrase typed at the prompt, `--keyfile PATH` (created with 32 random + bytes when missing), `$SK33P_BACKUP_KEYFILE` or `$SK33P_PASSPHRASE`. It never leaves + the machine. There is no recovery: lose it and the backups are gone. +- **Quantum-safe**: 256-bit symmetric encryption (XChaCha20-Poly1305) with an Argon2id + key. The passphrase goes through Argon2id (64 MiB, 3 passes, random salt) to a 256-bit + key that wraps a fresh random 256-bit key per file. No public-key step, so a quantum + computer only gets Grover's square-root speedup (about 128-bit strength left). Blob + header: magic `SK33PE2E`, format version, algorithm ids, KDF parameters, salt, nonces, + wrapped key; all authenticated. Unknown versions or algorithm ids are refused, so the + format can be upgraded later. +- **On the network**: each encrypted file is packaged in c0mpute's private-storage + format (`c0mpute-private-v1`) and held in 3 copies by c0mpute nodes. That envelope + wraps its key to your c0mpute storage identity with X25519 and authenticates the upload + with ed25519; neither protects readable data, since what they wrap is already sk33p + ciphertext. Names, sizes and dates live in an encrypted index object whose address is + derived from your key and account, so another machine with the same login and key + finds everything. c0mpute sees ciphertext, padded sizes and upload times. +- **Limits**: 100 MB per backup (sk33p). c0mpute's free app-upload limits per account: + 4 GiB per upload, 20 GiB a day, 200 GiB in all, 60 uploads an hour. +- **Once per c0mpute account**: link a storage identity with the c0mpute CLI, + `c0mpute storage key init` then `c0mpute storage key link`. +- **MCP**: `sk33p mcp` adds `backup`, `list_backups` and `restore` (key from the + `keyfile` argument, `$SK33P_BACKUP_KEYFILE` or `$SK33P_PASSPHRASE`). + +| Variable | Default | | +|---|---|---| +| `SK33P_C0MPUTE_URL` | `https://c0mpute.com` | sign-in and storage API | +| `SK33P_C0MPUTE_GATEWAY` | `https://gateway.c0mpute.com` | where backups are read from | +| `SK33P_C0MPUTE_TOKEN` | `~/.config/sk33p/c0mpute.json` (0600) | the c0mpute token | +| `SK33P_CONFIG_DIR` | `~/.config/sk33p` | | + ## Hosted API and MCP The same engine over HTTPS and remote MCP at **https://sk33p.pwa.pit.world**: evaluate diff --git a/cloud/src/page.ts b/cloud/src/page.ts index b111699..346c6fa 100644 --- a/cloud/src/page.ts +++ b/cloud/src/page.ts @@ -141,12 +141,13 @@ note.textContent=(r.headers.get('x-sk33p-remaining')??'?')+' tries left today.'}

Terminal

$0 forever, MIT
  • TUI, CLI and local MCP
  • Runs on your machine, no limits
  • Linux x86_64 / arm64, macOS arm64
Install

Free API

$0 with an email
  • ${L.free.calls} API + MCP calls a day
  • Files up to ${Math.round(L.free.maxBytes / 1048576)} MB
  • All tools: eval, read, write, sheets, convert, ask
Get a free key
+

Back up to c0mpute

$0 sign in with c0mpute
  • Encrypted on your machine before upload; neither sk33p nor c0mpute can read it
  • Quantum-safe: XChaCha20-Poly1305, 256-bit keys, Argon2id passphrase key
  • Workbooks up to 100 MB each, 3 copies on the c0mpute network
  • sk33p login then sk33p backup budget.xlsx
How it works

Pro

$${cfg.proUsd} per ${cfg.proDays} days
  • ${L.pro.calls.toLocaleString('en-US')} calls a day
  • Files up to ${Math.round(L.pro.maxBytes / 1048576)} MB
  • Pay with any coin or PayPal via CoinPay
  • No subscription: buy more days when you want
Go Pro

Questions

What is the engine?

SkeeptoEngine, a C++20 calculation core by Stéphane Allez (MIT): 344 worksheet functions including dynamic arrays, XLOOKUP, LET, LAMBDA helpers and financial solvers. sk33p is an independent Rust frontend for it.

-
Do you keep my files?

No. Each call runs in a fresh, sandboxed process in a scratch directory that is deleted when the call ends. We store your key's hash, your email and a daily call count.

+
Do you keep my files?

The hosted API keeps nothing: each call runs in a fresh, sandboxed process in a scratch directory that is deleted when the call ends. We store your key's hash, your email and a daily call count.

Optional free backups (sk33p backup) go to your own c0mpute storage, not to us, and are encrypted on your machine before upload with a passphrase or keyfile that never leaves it. Neither sk33p nor c0mpute can read them, or see their file names; the network holds ciphertext and its size. Lose the passphrase and nobody can recover them.

What happens when I hit the limit?

The API answers 402 with the next step (a free key, or Pro) instead of a bare error. Counts reset at midnight UTC.

Anything Excel does that sk33p does not?

No ^ operator (use POWER()), one workbook per process, no charts or macros. Number formats from .xlsx are applied.

@@ -270,6 +271,32 @@ Tools: eval, read_range, write_cells, list_sheets, convert (files as base64), as Local, unlimited, no account: install the app and run \`sk33p mcp\` (stdio; the same tools on file paths). +## Back up to c0mpute (free) + +End-to-end encrypted workbook backups on the c0mpute network, free for anyone with a c0mpute account. Everything below runs in the \`sk33p\` app on your machine; the hosted API is not involved and keeps nothing. + +\`\`\` +sk33p login # Sign in with c0mpute (browser; OAuth 2.1 + PKCE, scope storage:write) +sk33p login --token c0k_... # or a c0mpute API key, on a machine without a browser +sk33p backup budget.xlsx # asks for your backup passphrase the first time +sk33p backups # name, size, date (from your encrypted index) +sk33p restore budget.xlsx -o budget.xlsx +sk33p backup --rm budget.xlsx +sk33p logout +\`\`\` + +Use \`--keyfile PATH\` (created with 32 random bytes if missing), \`$SK33P_BACKUP_KEYFILE\` or \`$SK33P_PASSPHRASE\` instead of typing a passphrase. The local MCP server (\`sk33p mcp\`) has the same as tools: backup, list_backups, restore. + +**Encryption (quantum-safe).** 256-bit symmetric encryption (XChaCha20-Poly1305) with an Argon2id key: your passphrase goes through Argon2id (64 MiB, 3 passes) to a 256-bit key that wraps a fresh random 256-bit key per file. There is no public-key step in sk33p's encryption, so a quantum computer gains only Grover's square-root speedup (about 128-bit strength left). The header records the format version and algorithm ids, and every byte of it is authenticated. + +**What c0mpute sees.** Each encrypted file is then packaged in c0mpute's private-storage format and kept in 3 copies by c0mpute nodes. That envelope uses X25519 (a copy of its key wrapped to your c0mpute storage identity) and ed25519 (authenticating the upload to the network); they protect no readable data, since what they wrap is already sk33p ciphertext. File names are inside an encrypted index, never sent in the clear. c0mpute sees ciphertext, padded sizes and upload times. + +**Free limits.** sk33p caps each backup at 100 MB. c0mpute's app-upload limits per account: 4 GiB per upload, 20 GiB per 24 hours, 200 GiB in all, 60 uploads an hour. + +**Once per account.** c0mpute needs a storage identity linked to your account: \`c0mpute storage key init\` then \`c0mpute storage key link\` with the c0mpute CLI. + +**No recovery.** Lose the passphrase or keyfile and the backups cannot be opened by anyone. + ## The app \`${INSTALL}\` diff --git a/cloud/test/app.test.ts b/cloud/test/app.test.ts index 6e5c166..4834899 100644 --- a/cloud/test/app.test.ts +++ b/cloud/test/app.test.ts @@ -162,6 +162,23 @@ describe('pages', () => { expect(await (await req('/docs.md')).text()).toContain('## MCP') expect(await (await req('/llms.txt')).text()).toContain('# sk33p') expect((await req('/.well-known/openwebring.json')).status).toBe(200) + expect((await req('/nope')).status).toBe(404) + }) + + test('free c0mpute backups: pricing card, FAQ and docs say what is and is not kept', async () => { + const { req } = setup() + const home = await (await req('/')).text() + expect(home).toContain('Back up to c0mpute') + expect(home).toContain('href="/docs#back-up-to-c0mpute-free"') + expect(home).toContain('The hosted API keeps nothing') + expect(home).toContain('Neither sk33p nor c0mpute can read them') + const docs = await (await req('/docs.md')).text() + expect(docs).toContain('## Back up to c0mpute (free)') + expect(docs).toContain('256-bit symmetric encryption (XChaCha20-Poly1305) with an Argon2id key') + expect(docs).toContain('sk33p login --token c0k_') + expect(docs).not.toContain('ML-KEM') + const html = await (await req('/docs')).text() + expect(html).toContain('id="back-up-to-c0mpute-free"') expect(await (await req('/healthz')).json()).toEqual({ ok: true }) expect((await req('/nope')).status).toBe(404) }) diff --git a/src/backup.rs b/src/backup.rs new file mode 100644 index 0000000..0b148df --- /dev/null +++ b/src/backup.rs @@ -0,0 +1,849 @@ +//! Free end-to-end encrypted workbook backups on the c0mpute network. +//! +//! Two layers, both made on this machine: +//! +//! 1. **sk33p's encryption** (`vault.rs`): XChaCha20-Poly1305 with a random +//! 256-bit key per file, wrapped by a 256-bit key from the user's +//! passphrase (Argon2id) or keyfile. Symmetric only, so quantum-safe. +//! 2. **c0mpute's sealed format** (`sealed.rs`): the packaging c0mpute's +//! storage network accepts. Holders and gateways only ever see this. +//! +//! File names never leave the machine in the clear: each backup is an opaque +//! object, and the list of backups (name, size, date, and the keys needed to +//! fetch each object) is itself an encrypted index object whose network +//! address is derived from the passphrase or keyfile and the account, so any +//! machine with both finds it again. Nothing is stored by sk33p's servers. +use crate::c0mpute::{self, Client, Ctx}; +use crate::sealed::{self, Object}; +use crate::vault::{self, Secret}; +use serde_json::{json, Value}; +use std::path::{Path, PathBuf}; +use zeroize::Zeroizing; + +/// sk33p's own cap per backup (c0mpute's free app-upload limits are larger: +/// 4 GiB per upload, 20 GiB a day, 200 GiB per account). +pub const MAX_BACKUP_BYTES: usize = 100 * 1024 * 1024; +const MAX_NAME: usize = 200; + +#[derive(Clone, Debug, PartialEq)] +pub struct Entry { + pub name: String, + /// Plaintext size of the workbook. + pub size: u64, + /// Bytes stored on the network (both layers, padded). + pub stored: u64, + /// Unix seconds of the last backup under this name. + pub at: u64, + pub site_id: String, + obj_name: String, + seed: [u8; 32], + dek: [u8; 32], + seq: u64, +} + +impl Entry { + fn object(&self) -> Object { + Object { seed: self.seed, name: self.obj_name.clone(), dek: self.dek } + } + fn to_json(&self) -> Value { + json!({"name": self.name, "size": self.size, "stored": self.stored, "at": self.at, "site_id": self.site_id, + "obj": self.obj_name, "seed": sealed::hex(&self.seed), "dek": sealed::b64url(&self.dek), "seq": self.seq}) + } + fn from_json(v: &Value) -> Result { + let s = |k: &str| v[k].as_str().map(String::from).ok_or(format!("backup index: missing {k}")); + let n = |k: &str| v[k].as_u64().ok_or(format!("backup index: missing {k}")); + Ok(Entry { + name: s("name")?, + size: n("size")?, + stored: n("stored")?, + at: n("at")?, + site_id: s("site_id")?, + obj_name: s("obj")?, + seed: sealed::unhex(&s("seed")?)?.try_into().map_err(|_| "backup index: bad seed")?, + dek: sealed::from_b64url(&s("dek")?)?.try_into().map_err(|_| "backup index: bad key")?, + seq: n("seq")?, + }) + } + /// What a person (or an agent) should see: no keys. + pub fn public(&self) -> Value { + json!({"name": self.name, "size": self.size, "stored": self.stored, "at": self.at, "ref": format!("c0p1:{}", self.site_id)}) + } +} + +/// The decrypted list of backups, and where it lives. +pub struct Index { + pub files: Vec, + seq: u64, + obj: Object, + pub found: bool, +} + +impl Index { + fn plaintext(&self, seq: u64) -> Zeroizing> { + Zeroizing::new(json!({"v": 1, "seq": seq, "files": self.files.iter().map(Entry::to_json).collect::>()}).to_string().into_bytes()) + } +} + +/// The index object's keys, from the passphrase/keyfile and the account. +fn index_object(secret: &Secret, identity: &str) -> Result { + let loc = secret.locator(identity)?; + let name: [u8; 16] = sealed::hkdf32(loc.as_ref(), b"", b"sk33p index name v1")[..16].try_into().unwrap(); + Ok(Object { + seed: sealed::hkdf32(loc.as_ref(), b"", b"sk33p index signing seed v1"), + name: sealed::name_from(&name), + dek: sealed::hkdf32(loc.as_ref(), b"", b"sk33p index object key v1"), + }) +} + +fn now_ms() -> u64 { + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(1) +} + +/// A signed-in session for backup commands. +pub struct Session { + client: Client, + identity: String, + recipient: [u8; 32], +} + +impl Session { + pub fn open(ctx: &Ctx) -> Result { + let client = Client::new(ctx.clone())?; + let identity = client.identity()?; + let recipient = sealed::parse_identity(&identity)?; + Ok(Session { client, identity, recipient }) + } + + fn ctx(&self) -> &Ctx { + &self.client.ctx + } + + pub fn index(&self, secret: &Secret) -> Result { + let obj = index_object(secret, &self.identity)?; + let site = obj.site_id(); + let Some(blob) = c0mpute::fetch(&self.ctx().gateway, &site)? else { + return Ok(Index { files: vec![], seq: 0, obj, found: false }); + }; + let inner = sealed::open(&blob, &obj.dek, Some(&site))?; + if inner.is_empty() { + return Ok(Index { files: vec![], seq: 0, obj, found: false }); + } + let plain = vault::decrypt(&inner, secret)?; + let v: Value = serde_json::from_slice(&plain).map_err(|e| format!("backup index: {e}"))?; + if v["v"] != 1 { + return Err("backup index is from a newer sk33p; upgrade".into()); + } + let files = v["files"].as_array().ok_or("backup index: no files")?.iter().map(Entry::from_json).collect::>()?; + Ok(Index { files, seq: v["seq"].as_u64().unwrap_or(0), obj, found: true }) + } + + /// Compare the index address with the one this machine used before, so a + /// mistyped passphrase does not quietly start a second, empty set. + fn check_known(&self, idx: &Index, allow_new: bool) -> Result<(), String> { + let cfg = self.ctx().load()?; + let known = cfg["index"][&self.identity].as_str(); + if !idx.found && !allow_new && known.is_some_and(|k| k != idx.obj.site_id()) { + return Err("this passphrase or keyfile is not the one this machine backed up with before (that set is under a different key). \ + Use the same one, or pass --new-key to start a separate set." + .into()); + } + Ok(()) + } + + fn remember(&self, idx: &Index) -> Result<(), String> { + let mut cfg = self.ctx().load()?; + if !cfg["index"].is_object() { + cfg["index"] = json!({}); + } + cfg["index"][&self.identity] = json!(idx.obj.site_id()); + self.ctx().save(&cfg) + } + + /// Publish sealed objects plus the new index in one upload session. + fn publish(&self, mut objects: Vec, idx: &mut Index, secret: &Secret) -> Result<(), String> { + let seq = now_ms().max(idx.seq + 1); + let inner = vault::encrypt(&idx.plaintext(seq), secret)?; + let index_sealed = sealed::seal(&inner, &idx.obj, &self.recipient, seq)?; + let root = objects.first().map(|o| o.site_id.clone()).unwrap_or_else(|| index_sealed.site_id.clone()); + objects.push(index_sealed); + let bytes = objects.iter().map(|o| o.blob.len()).sum(); + let up = self.client.start_upload(bytes, objects.len())?; + for o in &objects { + self.client.put_object(&up, &o.site_id, &o.blob, &o.record)?; + } + let ids: Vec = objects.iter().map(|o| o.site_id.clone()).collect(); + self.client.complete(&up, &root, &ids)?; + idx.seq = seq; + idx.found = true; + self.remember(idx) + } + + /// Encrypt `bytes` and store them as backup `name` (replacing an older + /// backup of that name). `confirm_new` runs before a brand-new set is + /// started (the CLI asks for the passphrase again there). + pub fn backup(&self, secret: &Secret, name: &str, bytes: &[u8], allow_new: bool, confirm_new: &dyn Fn() -> Result<(), String>) -> Result { + check_name(name)?; + if bytes.len() > MAX_BACKUP_BYTES { + return Err(format!("{name}: {} MiB is over the {} MiB free backup limit", bytes.len() >> 20, MAX_BACKUP_BYTES >> 20)); + } + let mut idx = self.index(secret)?; + self.check_known(&idx, allow_new)?; + if !idx.found { + confirm_new()?; + } + let prev = idx.files.iter().position(|e| e.name == name); + let mut obj = match prev { + Some(i) => idx.files[i].object(), + None => Object::fresh(), + }; + obj.dek = Object::fresh().dek; + let seq = now_ms().max(prev.map(|i| idx.files[i].seq + 1).unwrap_or(0)); + let inner = vault::encrypt(bytes, secret)?; + let s = sealed::seal(&inner, &obj, &self.recipient, seq)?; + let entry = Entry { + name: name.to_string(), + size: bytes.len() as u64, + stored: s.blob.len() as u64, + at: seq / 1000, + site_id: s.site_id.clone(), + obj_name: obj.name.clone(), + seed: obj.seed, + dek: obj.dek, + seq, + }; + match prev { + Some(i) => idx.files[i] = entry.clone(), + None => idx.files.push(entry.clone()), + } + self.publish(vec![s], &mut idx, secret)?; + Ok(entry) + } + + pub fn list(&self, secret: &Secret) -> Result, String> { + let idx = self.index(secret)?; + if !idx.found { + let cfg = self.ctx().load()?; + if cfg["index"][&self.identity].as_str().is_some_and(|k| k != idx.obj.site_id()) { + return Err("no backups under this passphrase or keyfile (this machine used a different one before)".into()); + } + } + Ok(idx.files) + } + + /// The decrypted bytes of backup `name`. + pub fn restore(&self, secret: &Secret, name: &str) -> Result<(Entry, Zeroizing>), String> { + let idx = self.index(secret)?; + let e = idx.files.into_iter().find(|e| e.name == name).ok_or_else(|| format!("no backup named {name:?} (see `sk33p backups`)"))?; + let blob = c0mpute::fetch(&self.ctx().gateway, &e.site_id)?.ok_or_else(|| format!("{name}: the network has no copy of this backup right now"))?; + let inner = sealed::open(&blob, &e.dek, Some(&e.site_id))?; + let plain = vault::decrypt(&inner, secret)?; + Ok((e, plain)) + } + + /// Drop backup `name` from the index and replace its object on the + /// network with an empty one, so holders stop keeping the ciphertext. + pub fn remove(&self, secret: &Secret, name: &str) -> Result { + let mut idx = self.index(secret)?; + let i = idx.files.iter().position(|e| e.name == name).ok_or_else(|| format!("no backup named {name:?}"))?; + let e = idx.files.remove(i); + let mut obj = e.object(); + obj.dek = Object::fresh().dek; + let empty = sealed::seal(&[], &obj, &self.recipient, now_ms().max(e.seq + 1))?; + self.publish(vec![empty], &mut idx, secret)?; + Ok(e) + } +} + +fn check_name(name: &str) -> Result<(), String> { + if name.trim().is_empty() || name.len() > MAX_NAME || name.chars().any(|c| c.is_control()) { + return Err(format!("backup name must be 1-{MAX_NAME} printable characters")); + } + Ok(()) +} + +/// The file name a backup restores to by default: its name without any path. +pub fn default_out(name: &str) -> PathBuf { + let base = Path::new(name).file_name().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default(); + PathBuf::from(if base.is_empty() || base == ".." { "restored.sker".into() } else { base }) +} + +/// Write a restored file without clobbering anything unless asked. +pub fn write_out(path: &Path, bytes: &[u8], overwrite: bool) -> Result<(), String> { + if path.exists() && !overwrite { + return Err(format!("{} exists: pass -o OUT or --force", path.display())); + } + std::fs::write(path, bytes).map_err(|e| format!("{}: {e}", path.display())) +} + +pub fn human(n: u64) -> String { + match n { + n if n >= 1 << 30 => format!("{:.1} GiB", n as f64 / (1u64 << 30) as f64), + n if n >= 1 << 20 => format!("{:.1} MiB", n as f64 / (1u64 << 20) as f64), + n if n >= 1 << 10 => format!("{:.1} KiB", n as f64 / 1024.0), + n => format!("{n} B"), + } +} + +/// Unix seconds as `YYYY-MM-DD HH:MM` UTC. +pub fn date(secs: u64) -> String { + let days = (secs / 86400) as i64; + let (h, m) = ((secs % 86400) / 3600, (secs % 3600) / 60); + // civil-from-days (Howard Hinnant) + let z = days + 719_468; + let era = z.div_euclid(146_097); + let doe = z - era * 146_097; + let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = doy - (153 * mp + 2) / 5 + 1; + let mo = if mp < 10 { mp + 3 } else { mp - 9 }; + let y = yoe + era * 400 + (mo <= 2) as i64; + format!("{y:04}-{mo:02}-{d:02} {h:02}:{m:02}") +} + +// ── secrets ───────────────────────────────────────────────────────────────── + +/// A keyfile's bytes; `create` makes a new 32-byte random one (mode 0600). +pub fn read_keyfile(path: &Path, create: bool) -> Result { + if !path.exists() && create { + use rand::RngCore; + let mut k = Zeroizing::new([0u8; 32]); + rand::rngs::OsRng.fill_bytes(k.as_mut()); + let mut o = std::fs::OpenOptions::new(); + o.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + o.mode(0o600); + } + use std::io::Write; + o.open(path).and_then(|mut f| f.write_all(k.as_ref())).map_err(|e| format!("{}: {e}", path.display()))?; + eprintln!("created keyfile {} (32 random bytes). Keep a copy somewhere safe: without it these backups cannot be opened.", path.display()); + } + let b = std::fs::read(path).map_err(|e| format!("keyfile {}: {e}", path.display()))?; + Secret::keyfile(b) +} + +/// The secret for agents and scripts: an explicit keyfile, else +/// $SK33P_BACKUP_KEYFILE, else $SK33P_PASSPHRASE. +pub fn secret_from_env(keyfile: Option<&str>, create: bool) -> Result, String> { + if let Some(k) = keyfile.map(String::from).or_else(|| std::env::var("SK33P_BACKUP_KEYFILE").ok().filter(|s| !s.is_empty())) { + return read_keyfile(Path::new(&k), create).map(Some); + } + Ok(std::env::var("SK33P_PASSPHRASE").ok().filter(|s| !s.is_empty()).map(Secret::passphrase)) +} + +fn prompt(msg: &str) -> Result { + rpassword::prompt_password(msg).map_err(|e| format!("cannot read a passphrase here ({e}): use --keyfile or $SK33P_PASSPHRASE")) +} + +// ── CLI ───────────────────────────────────────────────────────────────────── + +struct Flags { + pos: Vec, + name: Option, + out: Option, + keyfile: Option, + token: Option, + rm: Option, + bools: Vec, +} + +fn flags(args: &[String]) -> Result { + let mut f = Flags { pos: vec![], name: None, out: None, keyfile: None, token: None, rm: None, bools: vec![] }; + let mut it = args.iter(); + while let Some(a) = it.next() { + let mut val = |what: &str| it.next().cloned().ok_or(format!("{a} needs {what}")); + match a.as_str() { + "--name" | "-n" => f.name = Some(val("a name")?), + "-o" | "--out" => f.out = Some(val("a path")?), + "--keyfile" | "-k" => f.keyfile = Some(val("a path")?), + "--token" => f.token = Some(val("a c0mpute API key")?), + "--rm" => f.rm = Some(val("a backup name")?), + "--force" | "--new-key" | "--json" | "--no-browser" => f.bools.push(a.clone()), + x if x.starts_with('-') && x.len() > 1 => return Err(format!("unknown option {x}")), + _ => f.pos.push(a.clone()), + } + } + Ok(f) +} + +impl Flags { + fn has(&self, f: &str) -> bool { + self.bools.iter().any(|b| b == f) + } + fn secret(&self, create: bool) -> Result { + if let Some(s) = secret_from_env(self.keyfile.as_deref(), create)? { + return Ok(s); + } + let p = prompt("backup passphrase: ")?; + if p.is_empty() { + return Err("empty passphrase".into()); + } + Ok(Secret::passphrase(p)) + } +} + +/// The re-type check before a new set starts with a prompted passphrase. +fn confirm_for(f: &Flags) -> impl Fn() -> Result<(), String> + '_ { + move || { + let interactive = f.keyfile.is_none() + && std::env::var("SK33P_BACKUP_KEYFILE").map(|s| s.is_empty()).unwrap_or(true) + && std::env::var("SK33P_PASSPHRASE").map(|s| s.is_empty()).unwrap_or(true); + if !interactive { + return Ok(()); + } + eprintln!("No backups yet under this passphrase. It encrypts every backup on this machine;"); + eprintln!("sk33p and c0mpute never see it and cannot recover it. Lose it and the backups are gone."); + Ok(()) + } +} + +pub fn cmd(which: &str, args: &[String]) -> Result<(), String> { + let f = flags(args)?; + let ctx = Ctx::from_env()?; + match which { + "login" => { + if let Some(t) = f.token.clone().or_else(|| f.pos.first().cloned()) { + c0mpute::save_token(&ctx, t.trim(), c0mpute::SCOPE, "key")?; + let s = Session::open(&ctx)?; + println!("signed in to c0mpute with an API key; storage identity {}", s.identity); + return Ok(()); + } + let no_browser = f.has("--no-browser"); + let scope = c0mpute::login(&ctx, |url| { + eprintln!("Sign in with c0mpute in your browser:\n {url}\n(waiting for the browser to come back to this machine...)"); + if !no_browser { + for opener in ["xdg-open", "open"] { + let ok = std::process::Command::new(opener) + .arg(url) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .spawn() + .is_ok(); + if ok { + break; + } + } + } + })?; + println!("signed in to c0mpute (scope: {scope}); token saved to {}", ctx.config.display()); + match Session::open(&ctx) { + Ok(s) => println!("storage identity {}: `sk33p backup FILE` is ready", s.identity), + Err(e) => eprintln!("note: {e}"), + } + Ok(()) + } + "logout" => { + if c0mpute::logout(&ctx)? { + println!("signed out of c0mpute"); + } else { + println!("not signed in"); + } + Ok(()) + } + "backup" => { + let s = Session::open(&ctx)?; + if let Some(name) = &f.rm { + let secret = f.secret(false)?; + let e = s.remove(&secret, name)?; + println!("removed backup {} ({})", e.name, human(e.size)); + return Ok(()); + } + let [file] = f.pos.as_slice() else { + return Err("usage: sk33p backup FILE [--name NAME] [--keyfile K] | sk33p backup --rm NAME".into()); + }; + let bytes = std::fs::read(file).map_err(|e| format!("{file}: {e}"))?; + let name = f.name.clone().unwrap_or_else(|| default_out(file).to_string_lossy().into_owned()); + let secret = f.secret(true)?; + let is_prompted = matches!(secret, Secret::Passphrase(..)) && f.keyfile.is_none() && std::env::var("SK33P_PASSPHRASE").map(|v| v.is_empty()).unwrap_or(true); + let first = confirm_for(&f); + let confirm = || -> Result<(), String> { + first()?; + if is_prompted { + let again = prompt("repeat the passphrase: ")?; + let Secret::Passphrase(p, _) = &secret else { unreachable!() }; + if again.as_str() != p.as_str() { + return Err("passphrases do not match; nothing was uploaded".into()); + } + } + Ok(()) + }; + let e = s.backup(&secret, &name, &bytes, f.has("--new-key"), &confirm)?; + println!("backed up {} ({}) to c0mpute: encrypted here, {} on the network", e.name, human(e.size), human(e.stored)); + Ok(()) + } + "backups" => { + let s = Session::open(&ctx)?; + let files = s.list(&f.secret(false)?)?; + if f.has("--json") { + println!("{}", json!(files.iter().map(Entry::public).collect::>())); + } else if files.is_empty() { + println!("no backups yet: sk33p backup FILE"); + } else { + let w = files.iter().map(|e| e.name.chars().count()).max().unwrap_or(4).max(4); + println!("{:10} BACKED UP (UTC)", "NAME", "SIZE"); + for e in &files { + println!("{:10} {}", e.name, human(e.size), date(e.at)); + } + } + Ok(()) + } + "restore" => { + let [name] = f.pos.as_slice() else { + return Err("usage: sk33p restore NAME [-o OUT] [--force]".into()); + }; + let s = Session::open(&ctx)?; + let (e, bytes) = s.restore(&f.secret(false)?, name)?; + let out = f.out.clone().map(PathBuf::from).unwrap_or_else(|| default_out(name)); + write_out(&out, &bytes, f.has("--force"))?; + println!("restored {} ({}) to {}", e.name, human(e.size), out.display()); + Ok(()) + } + _ => Err(format!("unknown command {which}")), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::HashMap; + use std::io::{Read, Write}; + use std::sync::{Arc, Mutex}; + + #[test] + fn dates_and_sizes() { + assert_eq!(date(0), "1970-01-01 00:00"); + assert_eq!(date(1_796_056_974), "2026-11-30 16:42"); + assert_eq!(human(1536), "1.5 KiB"); + assert_eq!(default_out("../../etc/passwd"), PathBuf::from("passwd")); + assert_eq!(default_out("budget.xlsx"), PathBuf::from("budget.xlsx")); + assert!(check_name("").is_err() && check_name("a\nb").is_err() && check_name("Q3 budget.xlsx").is_ok()); + } + + /// Everything the stand-in saw: requests (method, path, body) and the + /// latest published blob per site. + #[derive(Default)] + struct World { + requests: Vec<(String, String, Vec)>, + sites: HashMap)>, + staged: HashMap>, + code_challenge: String, + token: String, + } + + type Request = (String, String, HashMap, Vec); + + fn read_request(s: &mut std::net::TcpStream) -> Option { + let mut buf = vec![]; + let mut chunk = [0u8; 65536]; + let (head_end, len) = loop { + let n = s.read(&mut chunk).ok()?; + if n == 0 { + return None; + } + buf.extend_from_slice(&chunk[..n]); + if let Some(i) = buf.windows(4).position(|w| w == b"\r\n\r\n") { + let head = String::from_utf8_lossy(&buf[..i]).to_string(); + let len = head.lines().find_map(|l| l.to_lowercase().strip_prefix("content-length:").map(|v| v.trim().parse().unwrap_or(0))).unwrap_or(0usize); + break (i, len); + } + }; + while buf.len() < head_end + 4 + len { + let n = s.read(&mut chunk).ok()?; + if n == 0 { + break; + } + buf.extend_from_slice(&chunk[..n]); + } + let head = String::from_utf8_lossy(&buf[..head_end]).to_string(); + let mut lines = head.lines(); + let first: Vec<&str> = lines.next()?.split_whitespace().collect(); + let headers = lines.filter_map(|l| l.split_once(':').map(|(k, v)| (k.trim().to_lowercase(), v.trim().to_string()))).collect(); + Some((first[0].to_string(), first[1].to_string(), headers, buf[head_end + 4..].to_vec())) + } + + /// A stand-in for c0mpute.com + its ingest/read gateway. It checks what + /// the real gateway checks: ticket, sealed shape, record signature over + /// the manifest of the uploaded bytes, and a growing seq. + fn fake_c0mpute(identity: String) -> (String, Arc>) { + let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let base = format!("http://{}", l.local_addr().unwrap()); + let world = Arc::new(Mutex::new(World::default())); + let w = world.clone(); + std::thread::spawn(move || { + for s in l.incoming() { + let Ok(mut s) = s else { continue }; + let Some((method, target, headers, body)) = read_request(&mut s) else { continue }; + let mut st = w.lock().unwrap(); + st.requests.push((method.clone(), target.clone(), body.clone())); + let path = target.split('?').next().unwrap().to_string(); + let auth = headers.get("authorization").cloned().unwrap_or_default(); + let token_ok = !st.token.is_empty() && auth == format!("Bearer {}", st.token); + let form = |b: &[u8]| -> HashMap { + String::from_utf8_lossy(b).split('&').filter_map(|kv| kv.split_once('=')).map(|(k, v)| (k.to_string(), c0mpute_test_decode(v))).collect() + }; + let (status, ctype, out): (&str, &str, Vec) = match (method.as_str(), path.as_str()) { + ("GET", "/oauth/authorize") => { + let q = form(target.split_once('?').unwrap().1.as_bytes()); + assert_eq!(q["client_id"], c0mpute::CLIENT_ID); + assert_eq!(q["scope"], "storage:write"); + assert_eq!(q["code_challenge_method"], "S256"); + st.code_challenge = q["code_challenge"].clone(); + let loc = format!("{}?code=c0a_testcode&state={}", q["redirect_uri"], q["state"]); + let _ = write!(s, "HTTP/1.1 302 Found\r\nlocation: {loc}\r\ncontent-length: 0\r\nconnection: close\r\n\r\n"); + continue; + } + ("POST", "/api/oauth/token") => { + let f = form(&body); + use sha2::Digest; + let ok = f.get("code").map(String::as_str) == Some("c0a_testcode") + && sealed::b64url(&sha2::Sha256::digest(f["code_verifier"].as_bytes())) == st.code_challenge + && f["redirect_uri"].starts_with("http://127.0.0.1:"); + if ok { + st.token = "c0k_test_storage_only".into(); + ("200 OK", "application/json", br#"{"access_token":"c0k_test_storage_only","token_type":"Bearer","scope":"storage:write"}"#.to_vec()) + } else { + ("400 Bad Request", "application/json", br#"{"error":"invalid_grant"}"#.to_vec()) + } + } + ("POST", "/api/oauth/revoke") => { + st.token.clear(); + ("200 OK", "application/json", b"{}".to_vec()) + } + (_, p) if p.starts_with("/api/") && !token_ok => ("401 Unauthorized", "application/json", br#"{"error":{"code":"unauthorized","message":"no"}}"#.to_vec()), + ("GET", "/api/v1/storage/identity") => ("200 OK", "application/json", json!({"linked": true, "identity": identity}).to_string().into_bytes()), + ("POST", "/api/v1/storage/uploads") => { + let v: Value = serde_json::from_slice(&body).unwrap(); + assert!(v["objects"].as_u64().unwrap() >= 2 && v["bytes"].as_u64().unwrap() > 0); + ("201 Created", "application/json", json!({"upload_id": "up_1", "ticket": "tkt_1", "ingest_url": base_of(&headers)}).to_string().into_bytes()) + } + ("POST", p) if p.starts_with("/api/v1/storage/uploads/") => ("200 OK", "application/json", br#"{"status":"publishing"}"#.to_vec()), + ("PUT", p) if p.starts_with("/storage/v1/sealed/") => { + assert_eq!(auth, "Bearer tkt_1"); + let site = p.rsplit('/').next().unwrap().to_string(); + let off: usize = target.split("offset=").nth(1).unwrap().parse().unwrap(); + let staged = st.staged.entry(site).or_default(); + assert_eq!(off, staged.len()); + staged.extend_from_slice(&body); + ("200 OK", "application/json", json!({"received": staged.len()}).to_string().into_bytes()) + } + ("POST", p) if p.starts_with("/storage/v1/sealed/") && p.ends_with("/finish") => { + let site = p.split('/').nth(4).unwrap().to_string(); + let rec: Value = serde_json::from_slice::(&body).unwrap()["record"].clone(); + let blob = st.staged.remove(&site).unwrap(); + match check_record(&site, &rec, &blob, st.sites.get(&site).map(|x| x.0)) { + Ok(seq) => { + st.sites.insert(site, (seq, blob)); + ("200 OK", "application/json", br#"{"published":true}"#.to_vec()) + } + Err(e) => ("400 Bad Request", "application/json", json!({ "error": e }).to_string().into_bytes()), + } + } + ("GET", p) if p.starts_with("/s/") && p.ends_with("/o") => { + let site = p.split('/').nth(2).unwrap(); + match st.sites.get(site) { + Some((_, b)) => ("200 OK", "application/octet-stream", b.clone()), + None => ("404 Not Found", "text/plain", b"not found".to_vec()), + } + } + _ => ("404 Not Found", "text/plain", b"no route".to_vec()), + }; + let _ = write!(s, "HTTP/1.1 {status}\r\ncontent-type: {ctype}\r\ncontent-length: {}\r\nconnection: close\r\n\r\n", out.len()); + let _ = s.write_all(&out); + } + }); + (base, world) + } + + fn base_of(h: &HashMap) -> String { + format!("http://{}", h["host"]) + } + + /// The real gateway's checks, in brief. + fn check_record(site: &str, rec: &Value, blob: &[u8], have: Option) -> Result { + if rec["v"] != 1 || rec["site_id"] != site || rec["domains"] != json!([]) || rec["size"] != blob.len() { + return Err("bad record".into()); + } + if blob[..8] != sealed::MAGIC || u16::from_be_bytes([blob[56], blob[57]]) != 16 { + return Err("not sealed".into()); + } + let name = rec["name"].as_str().unwrap(); + let owner = rec["owner"].as_str().unwrap(); + if sealed::site_id_for(owner, name) != site { + return Err("site id".into()); + } + let hashes: Vec = blob.chunks(1 << 20).map(|c| format!("\"{}\"", sealed::hex(blake3::hash(c).as_bytes()))).collect(); + let manifest = format!( + "{{\"v\":1,\"name\":\"{name}\",\"files\":{{\"o\":{{\"size\":{},\"content_type\":\"application/octet-stream\",\"chunks\":[{}]}}}}}}", + blob.len(), + hashes.join(",") + ); + if sealed::hex(blake3::hash(manifest.as_bytes()).as_bytes()) != rec["manifest"] { + return Err("manifest".into()); + } + let seq = rec["seq"].as_u64().unwrap(); + let msg = format!("c0mpute-hosting-v1\n{site}\n{name}\n{owner}\n{}\n{seq}\n{}\n", rec["manifest"].as_str().unwrap(), blob.len()); + let pk: [u8; 32] = sealed::unhex(owner).unwrap().try_into().unwrap(); + let sig = ed25519_dalek::Signature::from_slice(&sealed::unhex(rec["sig"].as_str().unwrap()).unwrap()).unwrap(); + ed25519_dalek::VerifyingKey::from_bytes(&pk).unwrap().verify_strict(msg.as_bytes(), &sig).map_err(|_| "record signature")?; + if have.is_some_and(|h| h >= seq) { + return Err("an equal or newer version is already on the network".into()); + } + Ok(seq) + } + + #[test] + fn login_backup_list_restore_remove_against_a_stand_in() { + let id_secret = [5u8; 32]; + let id_pub = x25519_dalek::PublicKey::from(&x25519_dalek::StaticSecret::from(id_secret)); + let identity = format!("c0ps1.{}", sealed::b64url(id_pub.as_bytes())); + let (base, world) = fake_c0mpute(identity.clone()); + let dir = std::env::temp_dir().join(format!("sk33p-backup-test-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let ctx = Ctx { base: base.clone(), gateway: base.clone(), config: dir.join("cfg").join("c0mpute.json") }; + + // Sign in: the "browser" follows the authorize redirect to our loopback port. + let scope = c0mpute::login(&ctx, |url| { + let url = url.to_string(); + std::thread::spawn(move || { + let _ = ureq::get(&url).call(); + }); + }) + .unwrap(); + assert_eq!(scope, "storage:write"); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + assert_eq!(std::fs::metadata(&ctx.config).unwrap().permissions().mode() & 0o777, 0o600); + } + assert_eq!(ctx.token().unwrap(), "c0k_test_storage_only"); + + let s = Session::open(&ctx).unwrap(); + let pass = "orange tractor 42 lantern"; + let secret = Secret::passphrase(pass.into()); + assert!(s.list(&secret).unwrap().is_empty()); + + let name = "Q3-forecast-SECRETNAME.xlsx"; + let content = b"PK\x03\x04 pretend workbook: revenue,expenses,SECRETCELL".to_vec(); + let confirmed = std::cell::Cell::new(0); + let e = s.backup(&secret, name, &content, false, &|| { + confirmed.set(confirmed.get() + 1); + Ok(()) + }) + .unwrap(); + assert_eq!(confirmed.get(), 1, "a new set is confirmed once"); + assert_eq!(e.size, content.len() as u64); + let e2 = s.backup(&secret, "notes.csv", b"a,b\n1,2\n", false, &|| panic!("not a new set")).unwrap(); + + let listed = s.list(&secret).unwrap(); + assert_eq!(listed.iter().map(|e| e.name.as_str()).collect::>(), vec![name, "notes.csv"]); + assert_eq!(listed[1].size, 8); + + let (_, back) = s.restore(&secret, name).unwrap(); + assert_eq!(&back[..], &content[..]); + + // Backing up the same name again replaces that object (same site, newer seq). + let newer = b"PK\x03\x04 version two".to_vec(); + let e3 = s.backup(&secret, name, &newer, false, &|| panic!()).unwrap(); + assert_eq!(e3.site_id, e.site_id); + assert_eq!(&s.restore(&secret, name).unwrap().1[..], &newer[..]); + + // Wrong passphrase: no backups found, and it will not start a second set by accident. + let wrong = Secret::passphrase("orange tractor 43 lantern".into()); + assert!(s.list(&wrong).unwrap_err().contains("different one")); + assert!(s.backup(&wrong, "x", b"x", false, &|| Ok(())).unwrap_err().contains("--new-key")); + assert!(s.restore(&wrong, name).is_err()); + + // What left this machine: no file name, no plaintext, no passphrase, no keys. + { + let w = world.lock().unwrap(); + let all: Vec = w.requests.iter().flat_map(|(m, t, b)| [m.as_bytes(), t.as_bytes(), b.as_slice()].concat()).collect(); + let has = |needle: &[u8]| all.windows(needle.len()).any(|x| x == needle); + for leak in [&b"SECRETNAME"[..], b"Q3-forecast", b"SECRETCELL", b"notes.csv", pass.as_bytes(), b"orange tractor"] { + assert!(!has(leak), "{:?} was sent to c0mpute", String::from_utf8_lossy(leak)); + } + assert!(!has(&e.dek) && !has(sealed::b64url(&e.dek).as_bytes()) && !has(sealed::hex(&e.seed).as_bytes()), "a key was sent"); + assert!(!has(&e2.dek)); + // Every uploaded object is c0mpute ciphertext. + for (_, b) in w.sites.values() { + assert_eq!(&b[..8], &sealed::MAGIC); + } + assert_eq!(w.sites.len(), 3, "two backups and one index"); + } + + // The owner's c0mpute identity can open the outer layer (as `c0mpute storage get` + // would), and finds only sk33p ciphertext inside. + { + let w = world.lock().unwrap(); + let blob = &w.sites[&e.site_id].1; + let inner = open_with_identity(blob, &id_secret).expect("wrapped to the owner"); + assert_eq!(&inner[..8], vault::MAGIC); + assert_eq!(vault::header(&inner).unwrap().kdf, vault::KDF_ARGON2ID); + } + + // Remove: gone from the list, and its object is replaced by an empty one. + s.remove(&secret, "notes.csv").unwrap(); + assert_eq!(s.list(&secret).unwrap().len(), 1); + { + let w = world.lock().unwrap(); + let blob = &w.sites[&e2.site_id].1; + assert!(sealed::open(blob, &e2.dek, None).is_err(), "old key no longer opens it"); + } + assert!(s.restore(&secret, "notes.csv").unwrap_err().contains("no backup named")); + + // Another machine: same account + passphrase find everything (no local state). + let ctx2 = Ctx { config: dir.join("cfg2").join("c0mpute.json"), ..ctx.clone() }; + c0mpute::save_token(&ctx2, "c0k_test_storage_only", "storage:write", "key").unwrap(); + let s2 = Session::open(&ctx2).unwrap(); + assert_eq!(s2.list(&Secret::passphrase(pass.into())).unwrap().len(), 1); + + // Keyfile sets are separate from passphrase sets. + let kf = dir.join("backup.key"); + let k = read_keyfile(&kf, true).unwrap(); + s2.backup(&k, "k.sker", b"keyfile backup", true, &|| Ok(())).unwrap(); + assert_eq!(&s2.restore(&read_keyfile(&kf, false).unwrap(), "k.sker").unwrap().1[..], b"keyfile backup"); + + // Logout revokes and forgets the token. + assert!(c0mpute::logout(&ctx).unwrap()); + assert!(ctx.token().is_err()); + assert!(Session::open(&ctx2).err().unwrap().contains("sk33p login"), "revoked at the server"); + let _ = std::fs::remove_dir_all(&dir); + } + + /// Unwrap the data key with the owner's X25519 storage secret by trying + /// every slot (what the c0mpute CLI does), then open. + fn open_with_identity(blob: &[u8], secret: &[u8; 32]) -> Option> { + use aes_gcm::aead::{Aead, KeyInit, Payload}; + let me = x25519_dalek::PublicKey::from(&x25519_dalek::StaticSecret::from(*secret)); + let aad = [&blob[..8], &blob[8..24], &blob[24..56]].concat(); + for i in 0..16 { + let slot = &blob[60 + i * 80..60 + (i + 1) * 80]; + let eph: [u8; 32] = slot[..32].try_into().unwrap(); + let ss = x25519_dalek::StaticSecret::from(*secret).diffie_hellman(&x25519_dalek::PublicKey::from(eph)); + let kek = sealed::hkdf32(ss.as_bytes(), &[&eph[..], me.as_bytes()].concat(), b"c0mpute-private-v1 wrap"); + let c = aes_gcm::Aes256Gcm::new((&kek).into()); + if let Ok(dek) = c.decrypt((&[0u8; 12]).into(), Payload { msg: &slot[32..], aad: &aad }) { + return sealed::open(blob, &dek.try_into().ok()?, None).ok(); + } + } + None + } + + fn c0mpute_test_decode(v: &str) -> String { + let mut out = vec![]; + let b = v.as_bytes(); + let mut i = 0; + while i < b.len() { + if b[i] == b'%' && i + 2 < b.len() { + out.push(u8::from_str_radix(&v[i + 1..i + 3], 16).unwrap()); + i += 3; + } else { + out.push(if b[i] == b'+' { b' ' } else { b[i] }); + i += 1; + } + } + String::from_utf8(out).unwrap() + } +} diff --git a/src/c0mpute.rs b/src/c0mpute.rs new file mode 100644 index 0000000..c0a556b --- /dev/null +++ b/src/c0mpute.rs @@ -0,0 +1,429 @@ +//! Sign in with c0mpute and talk to its storage API. +//! +//! * Sign-in is OAuth 2.1 with PKCE (S256) as a public client: c0mpute.com +//! allows `http://127.0.0.1:/callback` redirects for desktop and +//! CLI apps (RFC 8252), so `sk33p login` listens on a loopback port, opens +//! the browser at `/oauth/authorize?scope=storage:write`, and swaps the code +//! at `/api/oauth/token` for a `c0k_` key that works only on the storage +//! upload routes. sk33p's client id was registered once with +//! `POST https://c0mpute.com/api/oauth/register` (RFC 7591, public client). +//! * `sk33p login --token c0k_...` stores an existing c0mpute API key instead +//! (headless machines, CI). +//! * The token lives in `~/.config/sk33p/c0mpute.json`, mode 0600. +//! * Storage: `GET /api/v1/storage/identity`, `POST /api/v1/storage/uploads` +//! (a ticket), then the ingest gateway's `PUT /storage/v1/sealed/` +//! and `POST .../finish`; reads are open: `GET /s//o`. +use serde_json::{json, Value}; +use sha2::Digest; +use std::io::{BufRead, BufReader, Read, Write}; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +pub const DEFAULT_BASE: &str = "https://c0mpute.com"; +pub const DEFAULT_GATEWAY: &str = "https://gateway.c0mpute.com"; +/// sk33p's public OAuth client on c0mpute.com (no secret exists for it). +pub const CLIENT_ID: &str = "c0c_T6_uQc-rZh8zTgXvzFfHUA"; +pub const SCOPE: &str = "storage:write"; +const PIECE: usize = 16 * 1024 * 1024; +const LOGIN_WAIT: Duration = Duration::from_secs(300); + +/// Where to find c0mpute and where sk33p keeps its sign-in. +#[derive(Clone, Debug)] +pub struct Ctx { + pub base: String, + pub gateway: String, + pub config: PathBuf, +} + +impl Ctx { + /// From the environment: $SK33P_C0MPUTE_URL, $SK33P_C0MPUTE_GATEWAY, + /// $SK33P_CONFIG_DIR (else $XDG_CONFIG_HOME/sk33p or ~/.config/sk33p). + pub fn from_env() -> Result { + let env = |k: &str| std::env::var(k).ok().map(|v| v.trim().trim_end_matches('/').to_string()).filter(|v| !v.is_empty()); + let dir = match env("SK33P_CONFIG_DIR") { + Some(d) => PathBuf::from(d), + None => std::env::var_os("XDG_CONFIG_HOME") + .map(PathBuf::from) + .or_else(|| std::env::var_os("HOME").map(|h| Path::new(&h).join(".config"))) + .ok_or("no HOME to keep the c0mpute sign-in in")? + .join("sk33p"), + }; + Ok(Ctx { + base: env("SK33P_C0MPUTE_URL").unwrap_or_else(|| DEFAULT_BASE.into()), + gateway: env("SK33P_C0MPUTE_GATEWAY").unwrap_or_else(|| DEFAULT_GATEWAY.into()), + config: dir.join("c0mpute.json"), + }) + } + + pub fn load(&self) -> Result { + match std::fs::read_to_string(&self.config) { + Ok(t) => serde_json::from_str(&t).map_err(|e| format!("{}: {e}", self.config.display())), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(json!({})), + Err(e) => Err(format!("{}: {e}", self.config.display())), + } + } + + /// Write the config with mode 0600 (created that way, never world-readable). + pub fn save(&self, v: &Value) -> Result<(), String> { + if let Some(d) = self.config.parent() { + std::fs::create_dir_all(d).map_err(|e| format!("{}: {e}", d.display()))?; + } + let tmp = self.config.with_extension("json.tmp"); + let mut o = std::fs::OpenOptions::new(); + o.write(true).create(true).truncate(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + o.mode(0o600); + } + let mut f = o.open(&tmp).map_err(|e| format!("{}: {e}", tmp.display()))?; + f.write_all(serde_json::to_string_pretty(v).unwrap().as_bytes()).map_err(|e| e.to_string())?; + drop(f); + std::fs::rename(&tmp, &self.config).map_err(|e| format!("{}: {e}", self.config.display())) + } + + pub fn token(&self) -> Result { + if let Ok(t) = std::env::var("SK33P_C0MPUTE_TOKEN") { + if !t.trim().is_empty() { + return Ok(t.trim().to_string()); + } + } + self.load()?["access_token"].as_str().map(String::from).ok_or_else(|| "not signed in to c0mpute: run `sk33p login`".to_string()) + } +} + +fn agent() -> ureq::Agent { + ureq::AgentBuilder::new() + .timeout_connect(Duration::from_secs(15)) + .timeout(Duration::from_secs(300)) + .user_agent(concat!("sk33p/", env!("CARGO_PKG_VERSION"))) + .build() +} + +/// The body of an HTTP answer as JSON, or a readable error. +fn answer(r: Result, what: &str) -> Result { + match r { + Ok(r) => { + let t = r.into_string().map_err(|e| format!("{what}: {e}"))?; + Ok(if t.trim().is_empty() { json!({}) } else { serde_json::from_str(&t).map_err(|e| format!("{what}: {e}"))? }) + } + Err(ureq::Error::Status(code, r)) => { + let t = r.into_string().unwrap_or_default(); + let v: Value = serde_json::from_str(&t).unwrap_or(json!({})); + let msg = v["error"]["message"] + .as_str() + .or(v["error_description"].as_str()) + .or(v["error"].as_str()) + .map(String::from) + .unwrap_or_else(|| t.chars().take(200).collect()); + let code_name = v["error"]["code"].as_str().unwrap_or(""); + if code == 401 { + return Err(format!("{what}: c0mpute refused the sign-in ({msg}); run `sk33p login` again")); + } + if code_name == "not_linked" { + return Err(format!( + "{what}: this c0mpute account has no storage identity yet. Once, on a computer with the c0mpute CLI: \ + `c0mpute storage key init` then `c0mpute storage key link` (see c0mpute.com docs: private storage)" + )); + } + Err(format!("{what}: HTTP {code}: {msg}")) + } + Err(ureq::Error::Transport(t)) => Err(format!("{what}: {t}")), + } +} + +pub struct Client { + pub ctx: Ctx, + token: String, + http: ureq::Agent, +} + +/// An open upload session: a ticket for the ingest gateway. +pub struct Upload { + pub id: String, + pub ticket: String, + pub ingest: String, +} + +impl Client { + pub fn new(ctx: Ctx) -> Result { + let token = ctx.token()?; + Ok(Client { ctx, token, http: agent() }) + } + + fn auth(&self) -> String { + format!("Bearer {}", self.token) + } + + /// The account's linked storage identity (`c0ps1...`). + pub fn identity(&self) -> Result { + let v = answer(self.http.get(&format!("{}/api/v1/storage/identity", self.ctx.base)).set("authorization", &self.auth()).call(), "c0mpute storage identity")?; + v["identity"].as_str().map(String::from).ok_or_else(|| "c0mpute did not return a storage identity".into()) + } + + pub fn start_upload(&self, bytes: usize, objects: usize) -> Result { + let v = answer( + self.http + .post(&format!("{}/api/v1/storage/uploads", self.ctx.base)) + .set("authorization", &self.auth()) + .send_json(json!({"bytes": bytes, "objects": objects})), + "c0mpute upload", + )?; + Ok(Upload { + id: v["upload_id"].as_str().ok_or("c0mpute upload: no upload_id")?.into(), + ticket: v["ticket"].as_str().ok_or("c0mpute upload: no ticket")?.into(), + ingest: v["ingest_url"].as_str().map(|s| s.trim_end_matches('/').to_string()).unwrap_or_else(|| self.ctx.gateway.clone()), + }) + } + + /// Send one sealed object to the ingest gateway and publish it. + pub fn put_object(&self, up: &Upload, site_id: &str, blob: &[u8], record: &Value) -> Result<(), String> { + let url = format!("{}/storage/v1/sealed/{site_id}", up.ingest); + let ticket = format!("Bearer {}", up.ticket); + let mut offset = 0; + let mut tries = 0; + while offset < blob.len() { + let end = (offset + PIECE).min(blob.len()); + let r = self + .http + .put(&format!("{url}?offset={offset}")) + .set("authorization", &ticket) + .set("content-type", "application/octet-stream") + .send_bytes(&blob[offset..end]); + match r { + Ok(_) => { + offset = end; + tries = 0; + } + Err(ureq::Error::Status(409, resp)) => { + // The gateway says how much it has: resume from there. + let v: Value = serde_json::from_str(&resp.into_string().unwrap_or_default()).unwrap_or(json!({})); + match v["received"].as_u64() { + Some(n) if n as usize <= blob.len() && tries < 5 => { + offset = n as usize; + tries += 1; + } + _ => return Err(format!("c0mpute gateway refused the upload: {}", v["error"].as_str().unwrap_or("conflict"))), + } + } + Err(e) => { + tries += 1; + if tries > 4 { + return answer(Err(e), "c0mpute gateway upload").map(|_| ()); + } + std::thread::sleep(Duration::from_millis(500 << tries)); + } + } + } + answer( + self.http.post(&format!("{url}/finish")).set("authorization", &ticket).send_json(json!({"record": record})), + "c0mpute gateway publish", + ) + .map(|_| ()) + } + + /// Tell c0mpute.com what the upload published (its quota and status pages). + pub fn complete(&self, up: &Upload, root: &str, site_ids: &[String]) -> Result { + answer( + self.http + .post(&format!("{}/api/v1/storage/uploads/{}", self.ctx.base, up.id)) + .set("authorization", &self.auth()) + .send_json(json!({"ref": format!("c0p1:{root}"), "site_ids": site_ids})), + "c0mpute upload", + ) + } +} + +/// The newest published ciphertext of a site, or None when there is none. +/// Reads are open on any gateway (the hash/site id is the capability). +pub fn fetch(gateway: &str, site_id: &str) -> Result>, String> { + let url = format!("{gateway}/s/{site_id}/o"); + match agent().get(&url).call() { + Ok(r) => { + let mut b = vec![]; + r.into_reader().take(256 * 1024 * 1024).read_to_end(&mut b).map_err(|e| format!("GET {url}: {e}"))?; + Ok(Some(b)) + } + Err(ureq::Error::Status(404, _)) => Ok(None), + Err(e) => answer(Err(e), &format!("GET {url}")).map(|_| None), + } +} + +fn pkce() -> (String, String) { + use rand::RngCore; + let mut v = [0u8; 32]; + rand::rngs::OsRng.fill_bytes(&mut v); + let verifier = crate::sealed::b64url(&v); + let challenge = crate::sealed::b64url(&sha2::Sha256::digest(verifier.as_bytes())); + (verifier, challenge) +} + +fn query_param(target: &str, key: &str) -> Option { + let q = target.split_once('?')?.1; + q.split('&').find_map(|kv| { + let (k, v) = kv.split_once('=')?; + (k == key).then(|| percent_decode(v)) + }) +} + +fn percent_decode(s: &str) -> String { + let b = s.as_bytes(); + let mut out = vec![]; + let mut i = 0; + while i < b.len() { + match b[i] { + b'+' => out.push(b' '), + b'%' if i + 2 < b.len() => { + if let Some(x) = std::str::from_utf8(&b[i + 1..i + 3]).ok().and_then(|h| u8::from_str_radix(h, 16).ok()) { + out.push(x); + i += 2; + } else { + out.push(b'%'); + } + } + c => out.push(c), + } + i += 1; + } + String::from_utf8_lossy(&out).into_owned() +} + +fn enc(s: &str) -> String { + s.bytes() + .map(|b| match b { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => (b as char).to_string(), + _ => format!("%{b:02X}"), + }) + .collect() +} + +/// Browser sign-in: listen on 127.0.0.1, hand `open` the authorize URL (it +/// opens a browser or prints it), wait for the redirect, swap the code for a +/// token and save it. Returns the scope c0mpute granted. +pub fn login(ctx: &Ctx, open: impl FnOnce(&str)) -> Result { + let listener = std::net::TcpListener::bind("127.0.0.1:0").map_err(|e| format!("loopback listener: {e}"))?; + let port = listener.local_addr().map_err(|e| e.to_string())?.port(); + let redirect = format!("http://127.0.0.1:{port}/callback"); + let (verifier, challenge) = pkce(); + let state = crate::sealed::b64url(&{ + use rand::RngCore; + let mut s = [0u8; 16]; + rand::rngs::OsRng.fill_bytes(&mut s); + s + }); + let client_id = std::env::var("SK33P_C0MPUTE_CLIENT_ID").ok().filter(|s| !s.is_empty()).unwrap_or_else(|| CLIENT_ID.into()); + let url = format!( + "{}/oauth/authorize?response_type=code&client_id={}&redirect_uri={}&scope={}&state={}&code_challenge={}&code_challenge_method=S256", + ctx.base, + enc(&client_id), + enc(&redirect), + enc(SCOPE), + enc(&state), + enc(&challenge) + ); + open(&url); + listener.set_nonblocking(true).map_err(|e| e.to_string())?; + let started = std::time::Instant::now(); + let code = loop { + if started.elapsed() > LOGIN_WAIT { + return Err("timed out waiting for the c0mpute sign-in (5 minutes)".into()); + } + let (stream, _) = match listener.accept() { + Ok(x) => x, + Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => { + std::thread::sleep(Duration::from_millis(50)); + continue; + } + Err(e) => return Err(e.to_string()), + }; + stream.set_nonblocking(false).map_err(|e| e.to_string())?; + stream.set_read_timeout(Some(Duration::from_secs(10))).ok(); + let mut reader = BufReader::new(stream); + let mut line = String::new(); + reader.read_line(&mut line).ok(); + let target = line.split_whitespace().nth(1).unwrap_or("").to_string(); + let mut stream = reader.into_inner(); + if !target.starts_with("/callback") { + let _ = write!(stream, "HTTP/1.1 404 Not Found\r\ncontent-length: 0\r\nconnection: close\r\n\r\n"); + continue; + } + let page = |msg: &str| format!("sk33p

sk33p

{msg}

"); + if query_param(&target, "state").as_deref() != Some(state.as_str()) { + let body = page("This sign-in did not come from this sk33p (state mismatch). Run sk33p login again."); + let _ = write!(stream, "HTTP/1.1 400 Bad Request\r\ncontent-type: text/html\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}", body.len()); + return Err("sign-in state mismatch; run `sk33p login` again".into()); + } + if let Some(err) = query_param(&target, "error") { + let body = page("Sign-in was not completed. You can close this tab."); + let _ = write!(stream, "HTTP/1.1 200 OK\r\ncontent-type: text/html\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}", body.len()); + return Err(format!("c0mpute sign-in failed: {err}")); + } + let Some(code) = query_param(&target, "code") else { continue }; + let body = page("Signed in to c0mpute. You can close this tab and go back to the terminal."); + let _ = write!(stream, "HTTP/1.1 200 OK\r\ncontent-type: text/html\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}", body.len()); + break code; + }; + let v = answer( + agent().post(&format!("{}/api/oauth/token", ctx.base)).send_form(&[ + ("grant_type", "authorization_code"), + ("code", &code), + ("client_id", &client_id), + ("redirect_uri", &redirect), + ("code_verifier", &verifier), + ]), + "c0mpute token", + )?; + let token = v["access_token"].as_str().ok_or("c0mpute token: no access_token")?; + let scope = v["scope"].as_str().unwrap_or(SCOPE).to_string(); + save_token(ctx, token, &scope, "oauth")?; + Ok(scope) +} + +pub fn save_token(ctx: &Ctx, token: &str, scope: &str, kind: &str) -> Result<(), String> { + let mut cfg = ctx.load()?; + cfg["base"] = json!(ctx.base); + cfg["access_token"] = json!(token); + cfg["scope"] = json!(scope); + cfg["kind"] = json!(kind); + ctx.save(&cfg) +} + +/// Forget the sign-in; an OAuth token is also revoked at c0mpute.com. +pub fn logout(ctx: &Ctx) -> Result { + let mut cfg = ctx.load()?; + let Some(token) = cfg["access_token"].as_str().map(String::from) else { + return Ok(false); + }; + if cfg["kind"] == "oauth" { + // RFC 7009: 200 whether or not it existed. Offline is fine: forget it anyway. + let _ = agent().post(&format!("{}/api/oauth/revoke", ctx.base)).send_form(&[("token", &token)]); + } + if let Some(o) = cfg.as_object_mut() { + o.remove("access_token"); + o.remove("scope"); + o.remove("kind"); + } + ctx.save(&cfg)?; + Ok(true) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn query_and_encoding() { + assert_eq!(query_param("/callback?code=c0a_x%2By&state=s+1", "code").as_deref(), Some("c0a_x+y")); + assert_eq!(query_param("/callback?code=a&state=s+1", "state").as_deref(), Some("s 1")); + assert_eq!(query_param("/callback", "code"), None); + assert_eq!(enc("http://127.0.0.1:5/callback"), "http%3A%2F%2F127.0.0.1%3A5%2Fcallback"); + assert_eq!(enc("storage:write"), "storage%3Awrite"); + } + + #[test] + fn pkce_is_s256_of_the_verifier() { + let (v, c) = pkce(); + assert!(v.len() >= 43); + assert_eq!(c, crate::sealed::b64url(&sha2::Sha256::digest(v.as_bytes()))); + } +} diff --git a/src/cli.rs b/src/cli.rs index 89f59aa..108997a 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -20,6 +20,18 @@ USAGE ask c0mpute for a formula (via $SK33P_API, key from $SK33P_KEY or ~/.config/sk33p/key; anonymous quota without) sk33p mcp run a Model Context Protocol server on stdio + +BACKUPS (free, on c0mpute, end-to-end encrypted on this machine) + sk33p login [--no-browser] sign in with c0mpute (browser, OAuth + PKCE) + sk33p login --token c0k_... or store a c0mpute API key (headless machines) + sk33p logout forget (and revoke) the c0mpute sign-in + sk33p backup FILE [--name NAME] encrypt FILE here and store it on c0mpute (max 100 MiB) + sk33p backups [--json] list backups: name, size, date + sk33p restore NAME [-o OUT] [--force] + fetch and decrypt a backup + sk33p backup --rm NAME delete a backup + each asks for your backup passphrase (or --keyfile PATH, $SK33P_BACKUP_KEYFILE, + $SK33P_PASSPHRASE). It never leaves this machine; lose it and the backups are gone. sk33p --version | --help TUI KEYS diff --git a/src/main.rs b/src/main.rs index d4e7f82..cbe33fa 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,9 +1,13 @@ mod ask; +mod backup; +mod c0mpute; mod cli; mod demo; mod engine; mod mcp; +mod sealed; mod tui; +mod vault; fn main() { let args: Vec = std::env::args().skip(1).collect(); @@ -18,6 +22,7 @@ fn main() { } Some("mcp") => mcp::serve(), Some("ask") => ask::cmd(&args[1..]), + Some(cmd @ ("login" | "logout" | "backup" | "backups" | "restore")) => backup::cmd(cmd, &args[1..]), Some("snapshot") => tui::snapshot_cmd(&args[1..]), Some("demo") => (|| { let out = args.get(1).cloned().unwrap_or_else(|| "sk33p-demo.xlsx".into()); diff --git a/src/mcp.rs b/src/mcp.rs index fdaedaf..ac96471 100644 --- a/src/mcp.rs +++ b/src/mcp.rs @@ -49,6 +49,30 @@ fn tools() -> Value { "inputSchema": {"type": "object", "properties": { "input": {"type": "string"}, "output": {"type": "string"}, "sheet": {"type": "string"} }, "required": ["input", "output"]} + }, + { + "name": "backup", + "description": "Back up a workbook to the user's free c0mpute storage, encrypted on this machine first (sk33p and c0mpute only ever hold ciphertext). Needs `sk33p login` once, and a keyfile (argument or $SK33P_BACKUP_KEYFILE) or $SK33P_PASSPHRASE.", + "inputSchema": {"type": "object", "properties": { + "path": {"type": "string"}, + "name": {"type": "string", "description": "backup name (default: the file name); an existing backup of that name is replaced"}, + "keyfile": {"type": "string", "description": "path of the backup keyfile (created with 32 random bytes when missing)"} + }, "required": ["path"]} + }, + { + "name": "list_backups", + "description": "List the user's encrypted c0mpute backups (name, size in bytes, unix time) from the encrypted index.", + "inputSchema": {"type": "object", "properties": {"keyfile": {"type": "string"}}} + }, + { + "name": "restore", + "description": "Fetch a backup from c0mpute, decrypt it on this machine and write it to `out`.", + "inputSchema": {"type": "object", "properties": { + "name": {"type": "string"}, + "out": {"type": "string", "description": "where to write the workbook"}, + "overwrite": {"type": "boolean"}, + "keyfile": {"type": "string"} + }, "required": ["name", "out"]} } ]) } @@ -149,6 +173,29 @@ fn call(name: &str, a: &Value) -> Result { e.save(Path::new(output))?; Ok(json!({"written": output})) } + "backup" | "list_backups" | "restore" => { + let secret = crate::backup::secret_from_env(s(a, "keyfile"), name == "backup")?.ok_or( + "no backup key: pass keyfile, or set $SK33P_BACKUP_KEYFILE or $SK33P_PASSPHRASE for the MCP server (there is no terminal to ask in)", + )?; + let session = crate::backup::Session::open(&crate::c0mpute::Ctx::from_env()?)?; + match name { + "backup" => { + let path = s(a, "path").ok_or("path is required")?; + let bytes = std::fs::read(path).map_err(|e| format!("{path}: {e}"))?; + let default = crate::backup::default_out(path).to_string_lossy().into_owned(); + let e = session.backup(&secret, s(a, "name").unwrap_or(&default), &bytes, false, &|| Ok(()))?; + Ok(json!({"backed_up": e.public()})) + } + "list_backups" => Ok(json!(session.list(&secret)?.iter().map(|e| e.public()).collect::>())), + _ => { + let n = s(a, "name").ok_or("name is required")?; + let out = s(a, "out").ok_or("out is required")?; + let (e, bytes) = session.restore(&secret, n)?; + crate::backup::write_out(Path::new(out), &bytes, a.get("overwrite").and_then(Value::as_bool).unwrap_or(false))?; + Ok(json!({"restored": e.public(), "written": out})) + } + } + } _ => Err(format!("unknown tool {name}")), } } diff --git a/src/sealed.rs b/src/sealed.rs new file mode 100644 index 0000000..581d269 --- /dev/null +++ b/src/sealed.rs @@ -0,0 +1,385 @@ +//! c0mpute's `c0mpute-private-v1` sealed object format: the outer layer of a +//! sk33p backup on the c0mpute network. +//! +//! A port of `@profullstack/c0mpute-sealed` (packages/sealed/src/format.js in +//! the c0mpute repo), which is itself byte-compatible with the reference Rust +//! crate `c0mpute-sealed`. c0mpute's ingest gateway only accepts objects in +//! this format, and anyone can read them back by site id, so this layer is +//! transport packaging, not sk33p's protection: what goes inside is already a +//! sk33p E2E blob (see `vault.rs`) that only the passphrase or keyfile opens. +//! +//! The data key of each object is also wrapped to the account's c0mpute +//! storage identity (X25519), as c0mpute's app-upload API expects, so the +//! owner can fetch the inner ciphertext with `c0mpute storage get` too. That +//! wrap is classical crypto protecting bytes that are already encrypted with a +//! 256-bit symmetric key; the per-object ed25519 key only authenticates the +//! upload to the network. +use aes_gcm::aead::{Aead, KeyInit, Payload}; +use aes_gcm::Aes256Gcm; +use rand::RngCore; +use sha2::Sha256; + +pub const MAGIC: [u8; 8] = *b"C0PRIV\x00\x01"; +pub const MAX_RECIPIENTS: usize = 16; +const SLOT_LEN: usize = 32 + 32 + 16; +const FIXED_LEN: usize = 8 + 16 + 32 + 4; +const ROSTER_LEN: usize = 12 + (1 + MAX_RECIPIENTS * 32) + 16; +pub const HEADER_LEN: usize = FIXED_LEN + MAX_RECIPIENTS * SLOT_LEN + ROSTER_LEN; +pub const CHUNK_PLAINTEXT: usize = 64 * 1024; +const TAG_LEN: usize = 16; +const SIG_LEN: usize = 64; +const MIN_PADDED: u64 = 4096; +/// The hosting layer hashes a site file in chunks of this size. +const FILE_CHUNK_BYTES: usize = 1024 * 1024; +/// One object holds at most this much content (c0mpute's part size). +pub const MAX_CONTENT: usize = 192 * 1024 * 1024; +pub const IDENTITY_PREFIX: &str = "c0ps1."; + +const INFO_COMMIT: &[u8] = b"c0mpute-private-v1 commit"; +const INFO_BODY: &[u8] = b"c0mpute-private-v1 body"; +const INFO_WRAP: &[u8] = b"c0mpute-private-v1 wrap"; +const INFO_CUSTODY: &[u8] = b"c0mpute-private-v1 custody"; +const SIG_DOMAIN: &str = "c0mpute-private-v1 object"; +const RECORD_DOMAIN: &str = "c0mpute-hosting-v1"; + +pub fn hkdf32(ikm: &[u8], salt: &[u8], info: &[u8]) -> [u8; 32] { + let mut out = [0u8; 32]; + hkdf::Hkdf::::new(Some(salt), ikm).expand(info, &mut out).expect("32 bytes is a valid HKDF length"); + out +} + +pub fn hex(b: &[u8]) -> String { + b.iter().map(|x| format!("{x:02x}")).collect() +} + +pub fn unhex(s: &str) -> Result, String> { + if s.len() % 2 != 0 { + return Err("bad hex".into()); + } + (0..s.len()).step_by(2).map(|i| u8::from_str_radix(&s[i..i + 2], 16).map_err(|_| "bad hex".to_string())).collect() +} + +pub fn b64url(b: &[u8]) -> String { + use base64::Engine as _; + base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(b) +} + +pub fn from_b64url(s: &str) -> Result, String> { + use base64::Engine as _; + base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(s.trim().trim_end_matches('=')).map_err(|_| "not base64url".to_string()) +} + +fn random() -> [u8; N] { + let mut b = [0u8; N]; + rand::rngs::OsRng.fill_bytes(&mut b); + b +} + +/// The X25519 key of a `c0ps1.` storage identity. +pub fn parse_identity(id: &str) -> Result<[u8; 32], String> { + let rest = id.trim().strip_prefix(IDENTITY_PREFIX).ok_or("not a c0mpute storage identity (expected c0ps1...)")?; + let k = from_b64url(rest)?; + let k: [u8; 32] = k.try_into().map_err(|_| "storage identity must be a 32-byte key")?; + if k.iter().all(|&b| b == 0) { + return Err("storage identity is all zeros".into()); + } + Ok(k) +} + +/// Padme bucket of `len`, never below 4096. +pub fn padme(len: u64) -> u64 { + if len <= MIN_PADDED { + return MIN_PADDED; + } + let e = 63 - len.leading_zeros() as u64; // floor(log2 len) + let s = 64 - e.leading_zeros() as u64; // floor(log2 e) + 1 + let step = 1u64 << (e - s); + len.div_ceil(step) * step +} + +pub fn site_id_for(owner_hex: &str, name: &str) -> String { + hex(blake3::hash(format!("c0mpute-site\n{owner_hex}\n{name}").as_bytes()).as_bytes())[..20].to_string() +} + +/// 16 bytes as 26 lowercase base32 characters: a valid hosting site name. +pub fn name_from(b: &[u8; 16]) -> String { + const ALPHA: &[u8] = b"abcdefghijklmnopqrstuvwxyz234567"; + let (mut out, mut acc, mut bits) = (String::new(), 0u32, 0u32); + for &byte in b { + acc = ((acc << 8) | byte as u32) & 0xffff; + bits += 8; + while bits >= 5 { + bits -= 5; + out.push(ALPHA[((acc >> bits) & 31) as usize] as char); + } + } + if bits > 0 { + out.push(ALPHA[((acc << (5 - bits)) & 31) as usize] as char); + } + out +} + +pub fn owner_hex(seed: &[u8; 32]) -> String { + hex(ed25519_dalek::SigningKey::from_bytes(seed).verifying_key().as_bytes()) +} + +fn aes(key: &[u8; 32]) -> Aes256Gcm { + Aes256Gcm::new(key.into()) +} + +fn seal_aes(key: &[u8; 32], nonce: &[u8; 12], aad: &[u8], msg: &[u8]) -> Vec { + aes(key).encrypt(nonce.into(), Payload { msg, aad }).expect("AES-GCM encryption does not fail") +} + +fn open_aes(key: &[u8; 32], nonce: &[u8; 12], aad: &[u8], msg: &[u8]) -> Result, String> { + aes(key).decrypt(nonce.into(), Payload { msg, aad }).map_err(|_| "sealed object failed authentication".to_string()) +} + +fn x25519_shared(secret: [u8; 32], public: &[u8; 32]) -> Result<[u8; 32], String> { + let ss = x25519_dalek::StaticSecret::from(secret).diffie_hellman(&x25519_dalek::PublicKey::from(*public)); + if ss.as_bytes().iter().all(|&b| b == 0) { + return Err("recipient key is a low-order point".into()); + } + Ok(*ss.as_bytes()) +} + +fn x25519_public(secret: [u8; 32]) -> [u8; 32] { + *x25519_dalek::PublicKey::from(&x25519_dalek::StaticSecret::from(secret)).as_bytes() +} + +/// The object's ed25519 signing seed, wrapped to the owner's storage key +/// (Meta.custody): lets the owner's c0mpute CLI manage objects an app made. +fn wrap_custody(seed: &[u8; 32], recipient: &[u8; 32]) -> Result { + let owner = ed25519_dalek::SigningKey::from_bytes(seed).verifying_key().to_bytes(); + let eph = random::<32>(); + let eph_pub = x25519_public(eph); + let kek = hkdf32(&x25519_shared(eph, recipient)?, &[eph_pub.as_slice(), recipient].concat(), INFO_CUSTODY); + let ct = seal_aes(&kek, &[0u8; 12], &[MAGIC.as_slice(), &owner].concat(), seed); + Ok(b64url(&[eph_pub.as_slice(), &ct].concat())) +} + +fn chunk_nonce(i: u64, last: bool) -> [u8; 12] { + let mut n = [0u8; 12]; + n[3..11].copy_from_slice(&i.to_be_bytes()); + n[11] = last as u8; + n +} + +fn chunk_aad(stream: &[u8], commit: &[u8], i: u64, last: bool) -> Vec { + [MAGIC.as_slice(), stream, commit, &i.to_be_bytes(), &[last as u8]].concat() +} + +/// What to seal: the object's identity on the network and its keys. +pub struct Object { + /// ed25519 seed of the per-object key. Keeping it lets sk33p publish a + /// newer version of the same object (an update or an empty replacement). + pub seed: [u8; 32], + /// 26-char network name; the site id derives from it and the key. + pub name: String, + /// The data key (AES-256) of this object. + pub dek: [u8; 32], +} + +impl Object { + pub fn fresh() -> Object { + Object { seed: random(), name: name_from(&random()), dek: random() } + } + pub fn owner(&self) -> String { + owner_hex(&self.seed) + } + pub fn site_id(&self) -> String { + site_id_for(&self.owner(), &self.name) + } +} + +/// A sealed blob and the signed hosting record that publishes it. +pub struct Sealed { + pub blob: Vec, + pub site_id: String, + pub record: serde_json::Value, +} + +fn json_str(s: &str) -> String { + serde_json::Value::String(s.into()).to_string() +} + +/// Seal `content` as a `kind: "file"` object wrapped to `recipient` (the +/// account's storage identity), with no file name or type in the metadata. +/// `version` (milliseconds) must grow for each new version of one object. +pub fn seal(content: &[u8], obj: &Object, recipient: &[u8; 32], version: u64) -> Result { + if content.len() > MAX_CONTENT { + return Err(format!("one sealed object holds at most {} MiB", MAX_CONTENT >> 20)); + } + let owner = obj.owner(); + let site_id = site_id_for(&owner, &obj.name); + let custody = wrap_custody(&obj.seed, recipient)?; + let meta = format!( + "{{\"v\":1,\"kind\":\"file\",\"name\":{},\"site_id\":{},\"owner\":{},\"size\":{},\"created\":{},\"version\":{},\"custody\":{}}}", + json_str(&obj.name), + json_str(&site_id), + json_str(&owner), + content.len(), + version / 1000, + version.max(1), + json_str(&custody) + ); + let meta = meta.into_bytes(); + let stream: [u8; 16] = random(); + let commit = hkdf32(&obj.dek, &stream, INFO_COMMIT); + let msg = format!( + "{SIG_DOMAIN}\n{site_id}\n{}\n{}\n{}\n{}", + hex(&stream), + hex(&commit), + hex(blake3::hash(&meta).as_bytes()), + hex(blake3::hash(content).as_bytes()) + ); + use ed25519_dalek::Signer; + let signer = ed25519_dalek::SigningKey::from_bytes(&obj.seed); + let sig = signer.sign(msg.as_bytes()).to_bytes(); + + // Key slots: one real (to the owner), fifteen shaped like real ones, shuffled. + let slot_aad = [MAGIC.as_slice(), &stream, &commit].concat(); + let mut slots: Vec> = vec![]; + let eph = random::<32>(); + let eph_pub = x25519_public(eph); + let kek = hkdf32(&x25519_shared(eph, recipient)?, &[eph_pub.as_slice(), recipient].concat(), INFO_WRAP); + slots.push([eph_pub.as_slice(), &seal_aes(&kek, &[0u8; 12], &slot_aad, &obj.dek)].concat()); + while slots.len() < MAX_RECIPIENTS { + slots.push([x25519_public(random()).as_slice(), &random::<48>()].concat()); + } + for i in (1..slots.len()).rev() { + let j = (rand::rngs::OsRng.next_u32() as usize) % (i + 1); + slots.swap(i, j); + } + let mut blob = Vec::with_capacity(HEADER_LEN + content.len() + 8192); + blob.extend_from_slice(&MAGIC); + blob.extend_from_slice(&stream); + blob.extend_from_slice(&commit); + blob.extend_from_slice(&[0, MAX_RECIPIENTS as u8, 0, 0]); + for s in &slots { + blob.extend_from_slice(s); + } + let mut roster = vec![0u8; ROSTER_LEN]; + rand::rngs::OsRng.fill_bytes(&mut roster); + blob.extend_from_slice(&roster); + debug_assert_eq!(blob.len(), HEADER_LEN); + + let mut plain = Vec::with_capacity(4 + meta.len() + SIG_LEN + content.len()); + plain.extend_from_slice(&(meta.len() as u32).to_be_bytes()); + plain.extend_from_slice(&meta); + plain.extend_from_slice(&sig); + plain.extend_from_slice(content); + let padded = padme(plain.len() as u64) as usize; + plain.resize(padded, 0); + let body_key = hkdf32(&obj.dek, &stream, INFO_BODY); + let chunks = padded.div_ceil(CHUNK_PLAINTEXT); + for (i, c) in plain.chunks(CHUNK_PLAINTEXT).enumerate() { + let last = i == chunks - 1; + blob.extend_from_slice(&seal_aes(&body_key, &chunk_nonce(i as u64, last), &chunk_aad(&stream, &commit, i as u64, last), c)); + } + + // The hosting record: one file "o", hashed in 1 MiB chunks. + let hashes: Vec = blob.chunks(FILE_CHUNK_BYTES).map(|c| format!("\"{}\"", hex(blake3::hash(c).as_bytes()))).collect(); + let manifest = format!( + "{{\"v\":1,\"name\":{},\"files\":{{\"o\":{{\"size\":{},\"content_type\":\"application/octet-stream\",\"chunks\":[{}]}}}}}}", + json_str(&obj.name), + blob.len(), + hashes.join(",") + ); + let manifest_hash = hex(blake3::hash(manifest.as_bytes()).as_bytes()); + let seq = version.max(1); + let rmsg = format!("{RECORD_DOMAIN}\n{site_id}\n{}\n{owner}\n{manifest_hash}\n{seq}\n{}\n", obj.name, blob.len()); + let record = serde_json::json!({ + "v": 1, "site_id": site_id, "name": obj.name, "owner": owner, "manifest": manifest_hash, + "seq": seq, "size": blob.len(), "domains": [], "sig": hex(&signer.sign(rmsg.as_bytes()).to_bytes()), + }); + Ok(Sealed { blob, site_id, record }) +} + +/// Open a sealed object with its data key: checks the key commitment, every +/// chunk, the owner signature and (when given) the expected site id. +pub fn open(blob: &[u8], dek: &[u8; 32], expected_site_id: Option<&str>) -> Result, String> { + if blob.len() < HEADER_LEN + TAG_LEN || blob[..8] != MAGIC { + return Err("not a c0mpute sealed object".into()); + } + let stream = &blob[8..24]; + let commit = &blob[24..56]; + if hkdf32(dek, stream, INFO_COMMIT) != commit { + return Err("wrong key for this sealed object".into()); + } + let body_key = hkdf32(dek, stream, INFO_BODY); + let body = &blob[HEADER_LEN..]; + let n = body.len().div_ceil(CHUNK_PLAINTEXT + TAG_LEN); + let mut plain = Vec::with_capacity(body.len()); + for (i, c) in body.chunks(CHUNK_PLAINTEXT + TAG_LEN).enumerate() { + let last = i == n - 1; + plain.extend(open_aes(&body_key, &chunk_nonce(i as u64, last), &chunk_aad(stream, commit, i as u64, last), c)?); + } + if plain.len() < 4 { + return Err("sealed object is truncated".into()); + } + let meta_len = u32::from_be_bytes(plain[..4].try_into().unwrap()) as usize; + let meta_bytes = plain.get(4..4 + meta_len).ok_or("sealed object is truncated")?; + let meta: serde_json::Value = serde_json::from_slice(meta_bytes).map_err(|e| format!("sealed metadata: {e}"))?; + let size = meta["size"].as_u64().ok_or("sealed metadata has no size")? as usize; + let sig = plain.get(4 + meta_len..4 + meta_len + SIG_LEN).ok_or("sealed object is truncated")?; + let content = plain.get(4 + meta_len + SIG_LEN..4 + meta_len + SIG_LEN + size).ok_or("sealed object is truncated")?; + let (owner, name, site) = (meta["owner"].as_str().unwrap_or(""), meta["name"].as_str().unwrap_or(""), meta["site_id"].as_str().unwrap_or("")); + if site_id_for(owner, name) != site { + return Err("sealed object: site id does not match its owner key".into()); + } + if expected_site_id.is_some_and(|e| e != site) { + return Err("sealed object is not the one requested".into()); + } + let msg = format!( + "{SIG_DOMAIN}\n{site}\n{}\n{}\n{}\n{}", + hex(stream), + hex(commit), + hex(blake3::hash(meta_bytes).as_bytes()), + hex(blake3::hash(content).as_bytes()) + ); + let pk: [u8; 32] = unhex(owner)?.try_into().map_err(|_| "bad owner key")?; + let vk = ed25519_dalek::VerifyingKey::from_bytes(&pk).map_err(|_| "bad owner key")?; + let sig = ed25519_dalek::Signature::from_slice(sig).map_err(|_| "bad signature")?; + vk.verify_strict(msg.as_bytes(), &sig).map_err(|_| "sealed object: owner signature does not verify")?; + Ok(content.to_vec()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn padme_matches_the_reference() { + assert_eq!(padme(1), 4096); + assert_eq!(padme(4096), 4096); + assert_eq!(padme(4097), 4352); // e=12, s=4, step 256 + assert_eq!(padme(1_000_000), 1_015_808); + } + + #[test] + fn names_are_26_base32_chars() { + let n = name_from(&[0xff; 16]); + assert_eq!(n.len(), 26); + assert!(n.chars().all(|c| c.is_ascii_lowercase() || ('2'..='7').contains(&c))); + } + + #[test] + fn seal_open_round_trip_and_shape() { + let id = x25519_public(random()); + let obj = Object::fresh(); + let s = seal(b"inner ciphertext", &obj, &id, 1_700_000_000_000).unwrap(); + assert_eq!(&s.blob[..8], &MAGIC); + assert_eq!(u16::from_be_bytes([s.blob[56], s.blob[57]]) as usize, MAX_RECIPIENTS); + assert_eq!((s.blob.len() - HEADER_LEN) % (CHUNK_PLAINTEXT + TAG_LEN), 4096 + TAG_LEN); + assert_eq!(s.record["size"], s.blob.len()); + assert_eq!(s.site_id, obj.site_id()); + assert_eq!(open(&s.blob, &obj.dek, Some(&s.site_id)).unwrap(), b"inner ciphertext"); + assert!(open(&s.blob, &[7u8; 32], None).is_err()); + let mut bad = s.blob.clone(); + let at = HEADER_LEN + 10; + bad[at] ^= 1; + assert!(open(&bad, &obj.dek, None).is_err()); + assert!(open(&s.blob, &obj.dek, Some("00000000000000000000")).is_err()); + } +} diff --git a/src/vault.rs b/src/vault.rs new file mode 100644 index 0000000..29bfb1f --- /dev/null +++ b/src/vault.rs @@ -0,0 +1,288 @@ +//! sk33p's own end-to-end encryption for backups: symmetric only, so it stays +//! safe against quantum attacks (Grover's search leaves a 256-bit key about +//! 128 bits of strength; Shor's algorithm does not apply, there is no +//! public-key step). +//! +//! * The key-encryption key (KEK, 256 bits) comes from the user's passphrase +//! through Argon2id (64 MiB, 3 passes, 1 lane, 16-byte random salt per +//! blob), or from a keyfile through HKDF-SHA256. +//! * Every blob gets a fresh random 256-bit file key, wrapped by the KEK with +//! XChaCha20-Poly1305; the content is sealed with the file key and +//! XChaCha20-Poly1305 (random 192-bit nonces). +//! * The whole header (format version, algorithm ids, KDF parameters, salt, +//! nonces, wrapped key) is authenticated: changing any byte fails. +//! +//! Blob layout (version 1, 136-byte header): +//! +//! ```text +//! magic "SK33PE2E" (8) | version 1 (1) | kdf id (1) | aead id (1) | wrap id (1) +//! | argon2 m_kib u32be | t u32be | p u32be | salt (16) +//! | wrap nonce (24) | wrapped file key (32 + 16 tag) | body nonce (24) +//! | ciphertext + 16-byte tag +//! ``` +//! +//! A reader refuses versions and algorithm ids it does not know, so a later +//! format (for example a hybrid X25519 + ML-KEM-768 wrap for sharing between +//! devices) can be added as version 2 without misreading old blobs. +//! Nothing secret leaves the machine: not the passphrase, not a key. +use chacha20poly1305::aead::{Aead, KeyInit, Payload}; +use chacha20poly1305::XChaCha20Poly1305; +use rand::RngCore; +use std::collections::HashMap; +use std::sync::Mutex; +use zeroize::{Zeroize, Zeroizing}; + +pub const MAGIC: &[u8; 8] = b"SK33PE2E"; +pub const VERSION: u8 = 1; +pub const KDF_ARGON2ID: u8 = 1; +pub const KDF_KEYFILE_HKDF: u8 = 2; +pub const AEAD_XCHACHA20POLY1305: u8 = 1; +pub const WRAP_XCHACHA20POLY1305: u8 = 1; +const FIXED: usize = 8 + 4 + 12 + 16; +pub const HEADER_LEN: usize = FIXED + 24 + 48 + 24; +const TAG: usize = 16; + +/// Argon2id cost: 64 MiB, 3 passes, 1 lane (RFC 9106's second recommendation). +pub const ARGON_M_KIB: u32 = 64 * 1024; +pub const ARGON_T: u32 = 3; +pub const ARGON_P: u32 = 1; +/// Refuse to run absurd KDF costs a hostile blob could ask for. +const ARGON_MAX_M_KIB: u32 = 4 * 1024 * 1024; +const ARGON_MAX_T: u32 = 64; + +/// What unlocks backups: a passphrase or the bytes of a keyfile. +pub enum Secret { + Passphrase(Zeroizing, KeyCache), + Keyfile(Zeroizing>), +} + +/// Argon2id results by (salt, params), so one command derives each KEK once. +#[derive(Default)] +pub struct KeyCache(Mutex>>); + +impl Secret { + pub fn passphrase(p: String) -> Secret { + Secret::Passphrase(Zeroizing::new(p), KeyCache::default()) + } + pub fn keyfile(bytes: Vec) -> Result { + if bytes.len() < 16 { + return Err("keyfile is too short (want at least 16 random bytes; 32 recommended)".into()); + } + Ok(Secret::Keyfile(Zeroizing::new(bytes))) + } + fn kdf_id(&self) -> u8 { + match self { + Secret::Passphrase(..) => KDF_ARGON2ID, + Secret::Keyfile(_) => KDF_KEYFILE_HKDF, + } + } + + /// The 256-bit KEK for a blob's salt and KDF parameters. + fn kek(&self, kdf: u8, salt: &[u8; 16], m: u32, t: u32, p: u32) -> Result, String> { + match (self, kdf) { + (Secret::Passphrase(pass, cache), KDF_ARGON2ID) => { + let mut ck = [0u8; 28]; + ck[..16].copy_from_slice(salt); + ck[16..20].copy_from_slice(&m.to_be_bytes()); + ck[20..24].copy_from_slice(&t.to_be_bytes()); + ck[24..].copy_from_slice(&p.to_be_bytes()); + if let Some(k) = cache.0.lock().unwrap().get(&ck) { + return Ok(k.clone()); + } + let k = argon2id(pass.as_bytes(), salt, m, t, p)?; + cache.0.lock().unwrap().insert(ck, k.clone()); + Ok(k) + } + (Secret::Keyfile(bytes), KDF_KEYFILE_HKDF) => Ok(Zeroizing::new(crate::sealed::hkdf32(bytes, salt, b"sk33p-e2e-v1 keyfile kek"))), + (Secret::Passphrase(..), KDF_KEYFILE_HKDF) => Err("this backup was made with a keyfile: pass --keyfile".into()), + (Secret::Keyfile(_), KDF_ARGON2ID) => Err("this backup was made with a passphrase, not a keyfile".into()), + (_, other) => Err(format!("unknown key derivation id {other} (a newer sk33p made this; upgrade)")), + } + } + + /// A key for things that must be found again without any stored salt + /// (where the encrypted index lives), bound to `context` (the account's + /// storage identity) so two accounts with one passphrase do not collide. + pub fn locator(&self, context: &str) -> Result, String> { + let salt: [u8; 16] = crate::sealed::hkdf32(context.as_bytes(), b"sk33p-locator-v1", b"salt")[..16].try_into().unwrap(); + let base = match self { + Secret::Passphrase(..) => self.kek(KDF_ARGON2ID, &salt, ARGON_M_KIB, ARGON_T, ARGON_P)?, + Secret::Keyfile(_) => self.kek(KDF_KEYFILE_HKDF, &salt, 0, 0, 0)?, + }; + Ok(Zeroizing::new(crate::sealed::hkdf32(base.as_ref(), context.as_bytes(), b"sk33p-locator-v1"))) + } +} + +fn argon2id(pass: &[u8], salt: &[u8; 16], m: u32, t: u32, p: u32) -> Result, String> { + if m > ARGON_MAX_M_KIB || t > ARGON_MAX_T || t == 0 || p == 0 || p > 16 { + return Err("backup asks for unreasonable Argon2id parameters".into()); + } + let params = argon2::Params::new(m, t, p, Some(32)).map_err(|e| format!("argon2: {e}"))?; + let a = argon2::Argon2::new(argon2::Algorithm::Argon2id, argon2::Version::V0x13, params); + let mut out = Zeroizing::new([0u8; 32]); + a.hash_password_into(pass, salt, out.as_mut()).map_err(|e| format!("argon2: {e}"))?; + Ok(out) +} + +fn xchacha(key: &[u8; 32]) -> XChaCha20Poly1305 { + XChaCha20Poly1305::new(key.into()) +} + +fn random() -> [u8; N] { + let mut b = [0u8; N]; + rand::rngs::OsRng.fill_bytes(&mut b); + b +} + +/// Encrypt `plain` under `secret`. The result names no file and holds no key. +pub fn encrypt(plain: &[u8], secret: &Secret) -> Result, String> { + let kdf = secret.kdf_id(); + let (m, t, p) = if kdf == KDF_ARGON2ID { (ARGON_M_KIB, ARGON_T, ARGON_P) } else { (0, 0, 0) }; + let salt: [u8; 16] = random(); + let mut h = Vec::with_capacity(HEADER_LEN + plain.len() + TAG); + h.extend_from_slice(MAGIC); + h.extend_from_slice(&[VERSION, kdf, AEAD_XCHACHA20POLY1305, WRAP_XCHACHA20POLY1305]); + for x in [m, t, p] { + h.extend_from_slice(&x.to_be_bytes()); + } + h.extend_from_slice(&salt); + debug_assert_eq!(h.len(), FIXED); + let kek = secret.kek(kdf, &salt, m, t, p)?; + let mut file_key = Zeroizing::new(random::<32>()); + let wrap_nonce: [u8; 24] = random(); + let wrapped = xchacha(&kek) + .encrypt((&wrap_nonce).into(), Payload { msg: file_key.as_ref(), aad: &h[..FIXED] }) + .map_err(|_| "key wrap failed")?; + h.extend_from_slice(&wrap_nonce); + h.extend_from_slice(&wrapped); + let body_nonce: [u8; 24] = random(); + h.extend_from_slice(&body_nonce); + debug_assert_eq!(h.len(), HEADER_LEN); + let ct = xchacha(&file_key).encrypt((&body_nonce).into(), Payload { msg: plain, aad: &h }).map_err(|_| "encryption failed")?; + file_key.zeroize(); + h.extend_from_slice(&ct); + Ok(h) +} + +/// The header fields of a blob, for display and tests. +#[derive(Debug, PartialEq)] +pub struct Header { + pub version: u8, + pub kdf: u8, + pub aead: u8, + pub wrap: u8, + pub argon: (u32, u32, u32), +} + +pub fn header(blob: &[u8]) -> Result { + if blob.len() < 12 || &blob[..8] != MAGIC { + return Err("not a sk33p encrypted backup".into()); + } + if blob[8] != VERSION { + return Err(format!("backup format version {} is not supported by this sk33p (it reads version {VERSION}); upgrade sk33p", blob[8])); + } + if blob.len() < HEADER_LEN + TAG { + return Err("encrypted backup is truncated".into()); + } + let u = |i: usize| u32::from_be_bytes(blob[i..i + 4].try_into().unwrap()); + let h = Header { version: blob[8], kdf: blob[9], aead: blob[10], wrap: blob[11], argon: (u(12), u(16), u(20)) }; + if h.aead != AEAD_XCHACHA20POLY1305 || h.wrap != WRAP_XCHACHA20POLY1305 || !(h.kdf == KDF_ARGON2ID || h.kdf == KDF_KEYFILE_HKDF) { + return Err(format!("backup uses unknown algorithm ids (kdf {}, aead {}, wrap {}); upgrade sk33p", h.kdf, h.aead, h.wrap)); + } + Ok(h) +} + +/// Decrypt a blob made by [`encrypt`]. Wrong secret or any changed byte fails. +pub fn decrypt(blob: &[u8], secret: &Secret) -> Result>, String> { + let h = header(blob)?; + let salt: [u8; 16] = blob[24..40].try_into().unwrap(); + let kek = secret.kek(h.kdf, &salt, h.argon.0, h.argon.1, h.argon.2)?; + let wrap_nonce: [u8; 24] = blob[40..64].try_into().unwrap(); + let file_key = xchacha(&kek) + .decrypt((&wrap_nonce).into(), Payload { msg: &blob[64..112], aad: &blob[..FIXED] }) + .map_err(|_| "wrong passphrase or keyfile (or the backup was changed)".to_string())?; + let file_key: Zeroizing<[u8; 32]> = Zeroizing::new(file_key.as_slice().try_into().map_err(|_| "bad wrapped key")?); + let body_nonce: [u8; 24] = blob[112..136].try_into().unwrap(); + xchacha(&file_key) + .decrypt((&body_nonce).into(), Payload { msg: &blob[HEADER_LEN..], aad: &blob[..HEADER_LEN] }) + .map(Zeroizing::new) + .map_err(|_| "backup failed authentication: it was changed or corrupted".to_string()) +} + +#[cfg(test)] +pub mod tests { + use super::*; + + /// Cheap passphrase secret for tests (the real cost is fixed in encrypt). + pub fn pass(p: &str) -> Secret { + Secret::passphrase(p.into()) + } + + #[test] + fn round_trip_passphrase_and_keyfile() { + let s = pass("correct horse battery staple"); + let blob = encrypt(b"A1,B1\n1,2\n", &s).unwrap(); + assert_eq!(&decrypt(&blob, &s).unwrap()[..], b"A1,B1\n1,2\n"); + let k = Secret::keyfile(vec![9u8; 32]).unwrap(); + let blob = encrypt(b"x", &k).unwrap(); + assert_eq!(&decrypt(&blob, &k).unwrap()[..], b"x"); + assert!(decrypt(&blob, &Secret::keyfile(vec![8u8; 32]).unwrap()).is_err()); + assert!(decrypt(&blob, &s).unwrap_err().contains("keyfile")); + assert!(Secret::keyfile(vec![1; 4]).is_err()); + } + + #[test] + fn wrong_passphrase_fails() { + let blob = encrypt(b"secret sheet", &pass("one")).unwrap(); + let e = decrypt(&blob, &pass("two")).unwrap_err(); + assert!(e.contains("wrong passphrase"), "{e}"); + } + + #[test] + fn tampering_fails_anywhere() { + let s = pass("p"); + let blob = encrypt(b"some workbook bytes", &s).unwrap(); + // body, wrapped key, salt, an algorithm id, KDF params, the body nonce + for at in [blob.len() - 1, HEADER_LEN, 70, 30, 13, 120] { + let mut b = blob.clone(); + b[at] ^= 0x40; + assert!(decrypt(&b, &s).is_err(), "byte {at} changed but decrypt passed"); + } + assert!(decrypt(&blob[..blob.len() - 3], &s).is_err()); + } + + #[test] + fn header_records_algorithms_and_rejects_unknown_versions() { + let blob = encrypt(b"x", &pass("p")).unwrap(); + assert_eq!( + header(&blob).unwrap(), + Header { version: 1, kdf: KDF_ARGON2ID, aead: AEAD_XCHACHA20POLY1305, wrap: WRAP_XCHACHA20POLY1305, argon: (65536, 3, 1) } + ); + let kblob = encrypt(b"x", &Secret::keyfile(vec![3; 32]).unwrap()).unwrap(); + assert_eq!(header(&kblob).unwrap().kdf, KDF_KEYFILE_HKDF); + let mut v2 = blob.clone(); + v2[8] = 2; + let e = decrypt(&v2, &pass("p")).unwrap_err(); + assert!(e.contains("version 2 is not supported") && e.contains("upgrade"), "{e}"); + let mut alg = blob.clone(); + alg[10] = 9; + assert!(header(&alg).unwrap_err().contains("unknown algorithm")); + assert!(header(b"PK\x03\x04 not ours at all").is_err()); + } + + #[test] + fn hostile_kdf_params_are_refused() { + let mut blob = encrypt(b"x", &pass("p")).unwrap(); + blob[12..16].copy_from_slice(&u32::MAX.to_be_bytes()); + assert!(decrypt(&blob, &pass("p")).unwrap_err().contains("unreasonable")); + } + + #[test] + fn locator_depends_on_secret_and_account() { + let a = Secret::keyfile(vec![1; 32]).unwrap(); + let b = Secret::keyfile(vec![2; 32]).unwrap(); + assert_eq!(*a.locator("c0ps1.x").unwrap(), *a.locator("c0ps1.x").unwrap()); + assert_ne!(*a.locator("c0ps1.x").unwrap(), *b.locator("c0ps1.x").unwrap()); + assert_ne!(*a.locator("c0ps1.x").unwrap(), *a.locator("c0ps1.y").unwrap()); + } +}