diff --git a/src-tauri/src/backup_crypto.rs b/src-tauri/src/backup_crypto.rs
new file mode 100644
index 00000000..20dfb24c
--- /dev/null
+++ b/src-tauri/src/backup_crypto.rs
@@ -0,0 +1,288 @@
+//! End-to-end encryption for scheduled backups.
+//!
+//! A backup is encrypted on the user's computer before it is uploaded, so
+//! Stroke Cloud (and anyone with access to it) only ever holds ciphertext.
+//!
+//! - **Data key (DEK):** 32 random bytes, fresh for every backup.
+//! - **Wrapped DEK:** `nonce24 || XChaCha20-Poly1305(sync_key, nonce, dek,
+//! aad = "stroke-backup-dek-v1")`, 72 bytes. The sync key is the account's
+//! end-to-end sync key (`sync.rs`), unlocked only by the sync passphrase.
+//! - **Key id:** the first 8 bytes of SHA-256("stroke-backup-key-id" ||
+//! sync_key), hex. Says which sync key wrapped the DEK without revealing it.
+//! - **File:** `"STRKBAK1" || key_id(8 raw) || wrapped_dek(72) ||
+//! nonce_prefix(19)` (107 bytes), then the plaintext in 64 KiB chunks, each
+//! `XChaCha20-Poly1305(dek, prefix || counter_u32_be || last_flag, chunk,
+//! aad = the 107-byte header)`. The last chunk has flag 1, so a truncated or
+//! reordered file fails to open. An empty input is one empty last chunk.
+//!
+//! The browser decrypts the same format (stroke-web
+//! `src/lib/backups/crypto.ts`); keep the two in step.
+
+use std::io::{Read, Write};
+use std::path::Path;
+
+use chacha20poly1305::aead::{Aead, KeyInit, Payload};
+use chacha20poly1305::{XChaCha20Poly1305, XNonce};
+use sha2::{Digest, Sha256};
+
+pub const MAGIC: &[u8; 8] = b"STRKBAK1";
+const DEK_AAD: &[u8] = b"stroke-backup-dek-v1";
+pub const CHUNK: usize = 64 * 1024;
+const TAG: usize = 16;
+const WRAPPED_LEN: usize = 24 + 32 + TAG;
+pub const HEADER_LEN: usize = 8 + 8 + WRAPPED_LEN + 19;
+
+fn random() -> [u8; N] {
+ let mut b = [0u8; N];
+ getrandom::getrandom(&mut b).expect("the OS random source is available");
+ b
+}
+
+/// Which sync key wrapped a backup's data key, as 16 hex characters.
+pub fn key_id(sync_key: &[u8; 32]) -> String {
+ hex::encode(&key_id_raw(sync_key))
+}
+
+fn key_id_raw(sync_key: &[u8; 32]) -> [u8; 8] {
+ let mut h = Sha256::new();
+ h.update(b"stroke-backup-key-id");
+ h.update(sync_key);
+ let d = h.finalize();
+ d[..8].try_into().expect("8 of 32 bytes")
+}
+
+pub fn wrap_dek(sync_key: &[u8; 32], dek: &[u8; 32]) -> Vec {
+ let nonce: [u8; 24] = random();
+ let ct = XChaCha20Poly1305::new(sync_key.into())
+ .encrypt(XNonce::from_slice(&nonce), Payload { msg: dek, aad: DEK_AAD })
+ .expect("in-memory encryption cannot fail");
+ [nonce.as_slice(), &ct].concat()
+}
+
+pub fn unwrap_dek(sync_key: &[u8; 32], wrapped: &[u8]) -> Result<[u8; 32], String> {
+ if wrapped.len() != WRAPPED_LEN {
+ return Err("The backup's key is damaged.".into());
+ }
+ let (nonce, ct) = wrapped.split_at(24);
+ let dek = XChaCha20Poly1305::new(sync_key.into())
+ .decrypt(XNonce::from_slice(nonce), Payload { msg: ct, aad: DEK_AAD })
+ .map_err(|_| "This backup was encrypted with another sync key. Unlock sync with the passphrase it was made under.".to_string())?;
+ dek.try_into().map_err(|_| "The backup's key is damaged.".to_string())
+}
+
+/// Re-wrap a data key under a new sync key (after a sync reset on a device
+/// that still had the old key).
+pub fn rewrap(old: &[u8; 32], new: &[u8; 32], wrapped: &[u8]) -> Result, String> {
+ Ok(wrap_dek(new, &unwrap_dek(old, wrapped)?))
+}
+
+fn chunk_nonce(prefix: &[u8; 19], counter: u32, last: bool) -> [u8; 24] {
+ let mut n = [0u8; 24];
+ n[..19].copy_from_slice(prefix);
+ n[19..23].copy_from_slice(&counter.to_be_bytes());
+ n[23] = u8::from(last);
+ n
+}
+
+/// Read until `buf` is full or the input ends; returns how much was read.
+fn fill(r: &mut impl Read, buf: &mut [u8]) -> std::io::Result {
+ let mut n = 0;
+ while n < buf.len() {
+ match r.read(&mut buf[n..])? {
+ 0 => break,
+ k => n += k,
+ }
+ }
+ Ok(n)
+}
+
+/// What the server keeps beside an encrypted backup.
+#[derive(Debug, Clone)]
+pub struct Sealed {
+ pub key_id: String,
+ /// base64url (unpadded) of the 72-byte wrapped data key.
+ pub wrapped_key: String,
+}
+
+pub fn b64(bytes: &[u8]) -> String {
+ use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
+ URL_SAFE_NO_PAD.encode(bytes)
+}
+
+pub fn unb64(s: &str) -> Result, String> {
+ use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
+ URL_SAFE_NO_PAD.decode(s.trim_end_matches('=')).map_err(|e| e.to_string())
+}
+
+pub fn encrypt_stream(sync_key: &[u8; 32], mut input: impl Read, mut out: impl Write) -> Result {
+ let dek: [u8; 32] = random();
+ let wrapped = wrap_dek(sync_key, &dek);
+ let prefix: [u8; 19] = random();
+ let mut header = Vec::with_capacity(HEADER_LEN);
+ header.extend_from_slice(MAGIC);
+ header.extend_from_slice(&key_id_raw(sync_key));
+ header.extend_from_slice(&wrapped);
+ header.extend_from_slice(&prefix);
+ out.write_all(&header).map_err(|e| e.to_string())?;
+
+ let cipher = XChaCha20Poly1305::new((&dek).into());
+ let mut cur = vec![0u8; CHUNK];
+ let mut next = vec![0u8; CHUNK];
+ let mut cur_len = fill(&mut input, &mut cur).map_err(|e| e.to_string())?;
+ let mut counter: u32 = 0;
+ loop {
+ // Look one chunk ahead: the last chunk is the one with nothing after it.
+ let next_len = if cur_len == CHUNK { fill(&mut input, &mut next).map_err(|e| e.to_string())? } else { 0 };
+ let last = next_len == 0;
+ let nonce = chunk_nonce(&prefix, counter, last);
+ let ct = cipher
+ .encrypt(XNonce::from_slice(&nonce), Payload { msg: &cur[..cur_len], aad: &header })
+ .map_err(|_| "Encryption failed.".to_string())?;
+ out.write_all(&ct).map_err(|e| e.to_string())?;
+ if last {
+ break;
+ }
+ counter = counter.checked_add(1).ok_or("The backup is too large to encrypt.")?;
+ std::mem::swap(&mut cur, &mut next);
+ cur_len = next_len;
+ }
+ out.flush().map_err(|e| e.to_string())?;
+ Ok(Sealed { key_id: key_id(sync_key), wrapped_key: b64(&wrapped) })
+}
+
+/// Decrypt a backup. `wrapped_override` is the server's copy of the wrapped
+/// key, which may have been re-wrapped under a newer sync key since the file
+/// was written.
+pub fn decrypt_stream(
+ sync_key: &[u8; 32],
+ mut input: impl Read,
+ mut out: impl Write,
+ wrapped_override: Option<&[u8]>,
+) -> Result<(), String> {
+ let mut header = [0u8; HEADER_LEN];
+ if fill(&mut input, &mut header).map_err(|e| e.to_string())? != HEADER_LEN || &header[..8] != MAGIC {
+ return Err("This isn't an encrypted Stroke backup.".into());
+ }
+ let wrapped = wrapped_override.unwrap_or(&header[16..16 + WRAPPED_LEN]);
+ let dek = unwrap_dek(sync_key, wrapped)?;
+ let prefix: [u8; 19] = header[16 + WRAPPED_LEN..].try_into().expect("19 bytes");
+ let cipher = XChaCha20Poly1305::new((&dek).into());
+
+ let size = CHUNK + TAG;
+ let mut cur = vec![0u8; size];
+ let mut next = vec![0u8; size];
+ let mut cur_len = fill(&mut input, &mut cur).map_err(|e| e.to_string())?;
+ let mut counter: u32 = 0;
+ loop {
+ let next_len = if cur_len == size { fill(&mut input, &mut next).map_err(|e| e.to_string())? } else { 0 };
+ let last = next_len == 0;
+ let nonce = chunk_nonce(&prefix, counter, last);
+ let pt = cipher
+ .decrypt(XNonce::from_slice(&nonce), Payload { msg: &cur[..cur_len], aad: &header })
+ .map_err(|_| "The backup is damaged or incomplete.".to_string())?;
+ out.write_all(&pt).map_err(|e| e.to_string())?;
+ if last {
+ break;
+ }
+ counter = counter.checked_add(1).ok_or("The backup is damaged.")?;
+ std::mem::swap(&mut cur, &mut next);
+ cur_len = next_len;
+ }
+ out.flush().map_err(|e| e.to_string())
+}
+
+pub fn encrypt_file(sync_key: &[u8; 32], src: &Path, dst: &Path) -> Result {
+ let input = std::io::BufReader::new(std::fs::File::open(src).map_err(|e| e.to_string())?);
+ let out = std::io::BufWriter::new(std::fs::File::create(dst).map_err(|e| e.to_string())?);
+ encrypt_stream(sync_key, input, out)
+}
+
+pub fn is_encrypted(head: &[u8]) -> bool {
+ head.len() >= 8 && &head[..8] == MAGIC
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn round_trip(len: usize) {
+ let key = [7u8; 32];
+ let data: Vec = (0..len).map(|i| (i * 31 % 251) as u8).collect();
+ let mut enc = Vec::new();
+ let sealed = encrypt_stream(&key, data.as_slice(), &mut enc).unwrap();
+ assert_eq!(sealed.key_id, key_id(&key));
+ assert!(is_encrypted(&enc));
+ let mut dec = Vec::new();
+ decrypt_stream(&key, enc.as_slice(), &mut dec, None).unwrap();
+ assert_eq!(dec, data, "len {len}");
+ }
+
+ #[test]
+ fn round_trips_at_chunk_edges() {
+ for len in [0, 1, CHUNK - 1, CHUNK, CHUNK + 1, 3 * CHUNK, 3 * CHUNK + 17] {
+ round_trip(len);
+ }
+ }
+
+ #[test]
+ fn wrong_key_truncation_and_tampering_fail() {
+ let key = [1u8; 32];
+ let data = vec![9u8; 2 * CHUNK + 5];
+ let mut enc = Vec::new();
+ encrypt_stream(&key, data.as_slice(), &mut enc).unwrap();
+ assert!(decrypt_stream(&[2u8; 32], enc.as_slice(), Vec::new(), None).is_err());
+ // Cut off at a chunk boundary: the new last chunk was not sealed as last.
+ let cut = &enc[..HEADER_LEN + 2 * (CHUNK + TAG)];
+ assert!(decrypt_stream(&key, cut, Vec::new(), None).is_err());
+ let mut bad = enc.clone();
+ let n = bad.len();
+ bad[n - 20] ^= 1;
+ assert!(decrypt_stream(&key, bad.as_slice(), Vec::new(), None).is_err());
+ let mut bad_header = enc.clone();
+ bad_header[HEADER_LEN - 1] ^= 1;
+ assert!(decrypt_stream(&key, bad_header.as_slice(), Vec::new(), None).is_err());
+ }
+
+ #[test]
+ fn rewrapped_key_opens_with_the_new_sync_key() {
+ let (old, new) = ([3u8; 32], [4u8; 32]);
+ let data = b"CREATE TABLE t (x int);".to_vec();
+ let mut enc = Vec::new();
+ let sealed = encrypt_stream(&old, data.as_slice(), &mut enc).unwrap();
+ let re = rewrap(&old, &new, &unb64(&sealed.wrapped_key).unwrap()).unwrap();
+ let mut dec = Vec::new();
+ decrypt_stream(&new, enc.as_slice(), &mut dec, Some(&re)).unwrap();
+ assert_eq!(dec, data);
+ assert!(decrypt_stream(&new, enc.as_slice(), Vec::new(), None).is_err());
+ }
+
+ /// A fixed vector the browser's decryptor is tested against.
+ #[test]
+ fn known_answer_for_the_web_decryptor() {
+ let key = [0x42u8; 32];
+ let dek = [0x11u8; 32];
+ let prefix = [0x22u8; 19];
+ let wrap_nonce = [0x33u8; 24];
+ let wrapped = [
+ wrap_nonce.as_slice(),
+ &XChaCha20Poly1305::new((&key).into())
+ .encrypt(XNonce::from_slice(&wrap_nonce), Payload { msg: &dek, aad: DEK_AAD })
+ .unwrap(),
+ ]
+ .concat();
+ let mut header = Vec::new();
+ header.extend_from_slice(MAGIC);
+ header.extend_from_slice(&key_id_raw(&key));
+ header.extend_from_slice(&wrapped);
+ header.extend_from_slice(&prefix);
+ let ct = XChaCha20Poly1305::new((&dek).into())
+ .encrypt(XNonce::from_slice(&chunk_nonce(&prefix, 0, true)), Payload { msg: b"hello", aad: &header })
+ .unwrap();
+ let file = [header.as_slice(), &ct].concat();
+ let mut dec = Vec::new();
+ decrypt_stream(&key, file.as_slice(), &mut dec, None).unwrap();
+ assert_eq!(dec, b"hello");
+ // Printed for the web test: cargo test known_answer -- --nocapture
+ println!("KAT {}", b64(&file));
+ }
+}
diff --git a/src-tauri/src/cloud_backup.rs b/src-tauri/src/cloud_backup.rs
index 3e1e7786..b61437ef 100644
--- a/src-tauri/src/cloud_backup.rs
+++ b/src-tauri/src/cloud_backup.rs
@@ -167,6 +167,14 @@ pub async fn backup_job_run(
let t = token(&app).await?;
let base = base_url();
+ // Backups are encrypted on this computer with the account's sync key, so
+ // Stroke Cloud only ever holds ciphertext. Stroke Cloud requires it; an S3
+ // bucket gets it whenever sync is set up here.
+ let sync_key = crate::sync::load_local(&app).await.map(|(k, _)| k);
+ if job.destination == "stroke" && sync_key.is_none() {
+ return Err("Backups to Stroke Cloud are end-to-end encrypted with your sync key. Set up or unlock sync (Settings → Sync) on this computer first.".into());
+ }
+
// S3 keys first: without them there is nothing to claim the tick for.
let s3 = if job.destination == "s3" {
match load_s3(&app, &job.id).await {
@@ -180,7 +188,7 @@ pub async fn backup_job_run(
let claim = http()
.post(format!("{base}/api/backups/runs"))
.bearer_auth(&t)
- .json(&serde_json::json!({ "job_id": job.id, "slot": slot }));
+ .json(&serde_json::json!({ "job_id": job.id, "slot": slot, "encrypted": sync_key.is_some() }));
let run = match send_json(claim).await {
Ok(v) => v,
Err(ApiError::Server(code, msg)) if code == "claimed" => return Ok(RunOutcome::skipped(msg)),
@@ -192,12 +200,15 @@ pub async fn backup_job_run(
}
let dir = app.path().app_cache_dir().map_err(|e| e.to_string())?.join("scheduled-backups");
- let result = dump_and_upload(&dir, &job, config, s3, &base, &t, &run_id).await;
+ let result = dump_and_upload(&dir, &job, config, s3, sync_key, &base, &t, &run_id).await;
let body = match &result {
Ok(done) => serde_json::json!({
"status": "success", "tables": done.tables, "rows": done.rows,
"bytes": done.bytes, "object_key": done.object_key,
+ "encrypted": done.sealed.is_some(),
+ "key_id": done.sealed.as_ref().map(|s| s.key_id.clone()),
+ "wrapped_key": done.sealed.as_ref().map(|s| s.wrapped_key.clone()),
}),
Err(e) => serde_json::json!({ "status": "failed", "error": e }),
};
@@ -216,6 +227,7 @@ struct Done {
rows: usize,
bytes: u64,
object_key: Option,
+ sealed: Option,
}
async fn dump_and_upload(
@@ -223,6 +235,7 @@ async fn dump_and_upload(
job: &JobSpec,
config: AnyConnectionConfig,
s3: Option,
+ sync_key: Option<[u8; 32]>,
base: &str,
token: &str,
run_id: &str,
@@ -230,6 +243,7 @@ async fn dump_and_upload(
std::fs::create_dir_all(dir).map_err(|e| e.to_string())?;
let sql_path = dir.join(format!("{run_id}.sql"));
let gz_path = dir.join(format!("{run_id}.sql.gz"));
+ let enc_path = dir.join(format!("{run_id}.sql.gz.stroke"));
let cleanup = |paths: &[&PathBuf]| {
for p in paths {
let _ = std::fs::remove_file(p);
@@ -249,20 +263,34 @@ async fn dump_and_upload(
}
let src = sql_path.clone();
let dst = gz_path.clone();
- let bytes = tokio::task::spawn_blocking(move || gzip(&src, &dst)).await.map_err(|e| e.to_string())??;
+ let mut bytes = tokio::task::spawn_blocking(move || gzip(&src, &dst)).await.map_err(|e| e.to_string())??;
let _ = std::fs::remove_file(&sql_path);
+ // Encrypt on this computer; what leaves it is ciphertext.
+ let (file, sealed) = match sync_key {
+ Some(key) => {
+ let (src, dst) = (gz_path.clone(), enc_path.clone());
+ let sealed = tokio::task::spawn_blocking(move || crate::backup_crypto::encrypt_file(&key, &src, &dst))
+ .await
+ .map_err(|e| e.to_string())??;
+ let _ = std::fs::remove_file(&gz_path);
+ bytes = std::fs::metadata(&enc_path).map_err(|e| e.to_string())?.len();
+ (enc_path.clone(), Some(sealed))
+ }
+ None => (gz_path.clone(), None),
+ };
+
let object_key = match s3 {
- Some(s) => Some(upload_s3(&gz_path, job, &s, bytes).await?),
+ Some(s) => Some(upload_s3(&file, job, &s, bytes, sealed.is_some()).await?),
None => {
- upload_stroke(&gz_path, base, token, run_id).await?;
+ upload_stroke(&file, base, token, run_id).await?;
None
}
};
- Ok(Done { tables: export.table_count, rows: export.row_count, bytes, object_key })
+ Ok(Done { tables: export.table_count, rows: export.row_count, bytes, object_key, sealed })
}
.await;
- cleanup(&[&sql_path, &gz_path]);
+ cleanup(&[&sql_path, &gz_path, &enc_path]);
result
}
@@ -347,12 +375,13 @@ fn key_safe(s: &str) -> String {
/// The user's bucket: one PUT, the payload streamed from disk and left
/// unsigned (`UNSIGNED-PAYLOAD`, accepted by S3, R2, MinIO and the rest).
-async fn upload_s3(path: &Path, job: &JobSpec, s: &S3Secret, bytes: u64) -> Result {
+async fn upload_s3(path: &Path, job: &JobSpec, s: &S3Secret, bytes: u64, encrypted: bool) -> Result {
let bucket = job.s3_bucket.as_deref().filter(|b| !b.is_empty()).ok_or("The schedule has no S3 bucket.")?;
let region = if s.region.is_empty() { "us-east-1" } else { s.region.as_str() };
let stamp = chrono::Utc::now().format("%Y-%m-%dT%H-%M-%SZ");
let prefix = job.s3_prefix.as_deref().map(key_safe).filter(|p| !p.is_empty());
- let name = format!("{}-{stamp}.sql.gz", key_safe(&job.label).replace('/', "-"));
+ let ext = if encrypted { "sql.gz.stroke" } else { "sql.gz" };
+ let name = format!("{}-{stamp}.{ext}", key_safe(&job.label).replace('/', "-"));
let key = match prefix {
Some(p) => format!("{p}/{name}"),
None => name,
@@ -393,7 +422,7 @@ async fn upload_s3(path: &Path, job: &JobSpec, s: &S3Secret, bytes: u64) -> Resu
.header("authorization", auth)
.header("x-amz-content-sha256", "UNSIGNED-PAYLOAD")
.header("x-amz-date", amz_date)
- .header("content-type", "application/gzip")
+ .header("content-type", if encrypted { "application/octet-stream" } else { "application/gzip" })
.header("content-length", bytes.to_string())
.timeout(Duration::from_secs(3600))
.body(body)
@@ -410,6 +439,41 @@ async fn upload_s3(path: &Path, job: &JobSpec, s: &S3Secret, bytes: u64) -> Resu
Ok(key)
}
+/// After a sync reset on this device: re-wrap every backup key the old sync
+/// key wrapped, so those backups open with the new one.
+pub(crate) async fn rewrap_backup_keys(token: &str, old: &[u8; 32], new: &[u8; 32]) -> Result<(), String> {
+ #[derive(Deserialize)]
+ struct Key {
+ id: String,
+ key_id: String,
+ wrapped_key: String,
+ }
+ #[derive(Deserialize)]
+ struct Keys {
+ keys: Vec,
+ }
+ let base = base_url();
+ let list: Keys = serde_json::from_value(
+ send_json(http().get(format!("{base}/api/backups/keys")).bearer_auth(token)).await.map_err(api_message)?,
+ )
+ .map_err(|e| e.to_string())?;
+ let old_id = crate::backup_crypto::key_id(old);
+ let new_id = crate::backup_crypto::key_id(new);
+ let mut updates = Vec::new();
+ for k in list.keys.into_iter().filter(|k| k.key_id == old_id) {
+ let wrapped = crate::backup_crypto::unb64(&k.wrapped_key)?;
+ let re = crate::backup_crypto::rewrap(old, new, &wrapped)?;
+ updates.push(serde_json::json!({ "id": k.id, "key_id": new_id, "wrapped_key": crate::backup_crypto::b64(&re) }));
+ }
+ if updates.is_empty() {
+ return Ok(());
+ }
+ send_json(http().post(format!("{base}/api/backups/keys")).bearer_auth(token).json(&serde_json::json!({ "keys": updates })))
+ .await
+ .map(|_| ())
+ .map_err(api_message)
+}
+
/// Ids are UUIDs from the app, but escape anything else defensively.
fn enc(s: &str) -> String {
s.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_').collect()
diff --git a/src-tauri/src/db/backup.rs b/src-tauri/src/db/backup.rs
index 8ee75faa..412d221e 100644
--- a/src-tauri/src/db/backup.rs
+++ b/src-tauri/src/db/backup.rs
@@ -113,6 +113,9 @@ pub struct BackupFileInfo {
pub stroke: bool,
/// A cancelled Stroke export: restoring it would load a fraction of the data.
pub incomplete: bool,
+ /// An end-to-end encrypted scheduled backup: opened with the sync key on restore.
+ #[serde(default)]
+ pub encrypted: bool,
}
fn default_true() -> bool { true }
@@ -592,7 +595,7 @@ pub async fn backup_import(
let rep = Reporter::restore(&app);
let script = match (sql, path) {
(Some(s), _) => s,
- (None, Some(p)) => read_script(&rep, &p).await?,
+ (None, Some(p)) => read_script(&app, &rep, &p).await?,
(None, None) => return Err("Nothing to restore: no file or SQL given".into()),
};
match require_conn(&state)? {
@@ -611,8 +614,25 @@ pub async fn backup_import(
}
}
-async fn read_script(rep: &Reporter, path: &str) -> Result {
- let bytes = tokio::fs::read(path).await.map_err(|e| format!("Could not read {path}: {e}"))?;
+async fn read_script(app: &AppHandle, rep: &Reporter, path: &str) -> Result {
+ let mut bytes = tokio::fs::read(path).await.map_err(|e| format!("Could not read {path}: {e}"))?;
+ // A scheduled backup: encrypted with the account's sync key, then gzip.
+ if crate::backup_crypto::is_encrypted(&bytes) {
+ let (key, _) = crate::sync::load_local(app)
+ .await
+ .ok_or("This backup is end-to-end encrypted. Unlock sync (Settings → Sync) with your sync passphrase to restore it.")?;
+ rep.log("info", "Decrypting the backup on this computer");
+ let mut plain = Vec::with_capacity(bytes.len());
+ crate::backup_crypto::decrypt_stream(&key, bytes.as_slice(), &mut plain, None)?;
+ bytes = plain;
+ }
+ if bytes.starts_with(&[0x1f, 0x8b]) {
+ let mut out = Vec::with_capacity(bytes.len() * 4);
+ flate2::read::GzDecoder::new(bytes.as_slice())
+ .read_to_end(&mut out)
+ .map_err(|e| format!("Could not unzip {path}: {e}"))?;
+ bytes = out;
+ }
match String::from_utf8(bytes) {
Ok(s) => Ok(s),
Err(e) => {
@@ -633,6 +653,18 @@ pub async fn backup_inspect_file(path: String) -> Result
f.read(&mut head).map_err(|e| format!("Could not read {path}: {e}"))?
};
head.truncate(n);
+ if crate::backup_crypto::is_encrypted(&head) {
+ return Ok(BackupFileInfo { size: meta.len(), engine: None, stroke: true, incomplete: false, encrypted: true });
+ }
+ if head.starts_with(&[0x1f, 0x8b]) {
+ // Gzip: look at the start of what it holds.
+ let mut f = File::open(&path).map_err(|e| format!("Could not open {path}: {e}"))?;
+ let mut inner = vec![0u8; 4096];
+ let mut dec = flate2::read::GzDecoder::new(&mut f);
+ let k = dec.read(&mut inner).unwrap_or(0);
+ inner.truncate(k);
+ return Ok(inspect_head(meta.len(), &String::from_utf8_lossy(&inner)));
+ }
Ok(inspect_head(meta.len(), &String::from_utf8_lossy(&head)))
}
@@ -649,7 +681,7 @@ fn inspect_head(size: u64, head: &str) -> BackupFileInfo {
else if head.starts_with("PRAGMA foreign_keys=OFF;\nBEGIN TRANSACTION;") { Some("SQLite".into()) }
else { None }
});
- BackupFileInfo { size, engine, stroke, incomplete }
+ BackupFileInfo { size, engine, stroke, incomplete, encrypted: false }
}
// ── Shared helpers ────────────────────────────────────────────────────────────
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 6a96ba07..9fc1e053 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -10,6 +10,7 @@
static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;
mod account;
+mod backup_crypto;
mod cloud_backup;
mod shares;
mod nightly;
diff --git a/src-tauri/src/sync.rs b/src-tauri/src/sync.rs
index 62a4f9ea..4f527135 100644
--- a/src-tauri/src/sync.rs
+++ b/src-tauri/src/sync.rs
@@ -343,7 +343,7 @@ struct StoredKey {
wrapped: String,
}
-async fn load_local(app: &tauri::AppHandle) -> Option<([u8; 32], String)> {
+pub(crate) async fn load_local(app: &tauri::AppHandle) -> Option<([u8; 32], String)> {
let raw = crate::secrets::read_all_async(app).await.get(SYNC_KEY_VAULT).cloned()?;
let s: StoredKey = serde_json::from_str(&raw).ok()?;
let key: [u8; 32] = unb64(&s.key).ok()?.try_into().ok()?;
@@ -480,10 +480,19 @@ pub async fn sync_unlock(app: tauri::AppHandle, passphrase: String) -> Result<()
pub async fn sync_reset(app: tauri::AppHandle, passphrase: String) -> Result<(), String> {
check_passphrase(&passphrase)?;
let tok = token(&app).await?;
+ // The key this device still holds, if any: encrypted backups are re-wrapped
+ // under the new key, so a reset from here doesn't strand them.
+ let old = load_local(&app).await.map(|(k, _)| k);
let key = random::<32>();
let (wrapped, kdf) = blocking(move || wrap_key(&passphrase, &key)).await??;
put_key(&account::base_url(), &tok, &wrapped, &kdf, true).await.map_err(sync_message)?;
- store_local(&app, &key, &wrapped).await
+ store_local(&app, &key, &wrapped).await?;
+ if let Some(old) = old {
+ if let Err(e) = crate::cloud_backup::rewrap_backup_keys(&tok, &old, &key).await {
+ eprintln!("[sync] re-wrapping backup keys failed: {e}");
+ }
+ }
+ Ok(())
}
#[tauri::command]
@@ -548,6 +557,17 @@ mod tests {
Kdf { alg: "argon2id".into(), salt: b64(&seq::<16>(1)), m: 64, t: 1, p: 1 }
}
+ /// A fixed vector the website's unlock (stroke-web src/lib/backups/crypto.ts)
+ /// is checked against: passphrase "correct horse battery", key 0x42 * 32.
+ #[test]
+ fn known_answer_for_the_web_unlock() {
+ let kdf = Kdf { alg: "argon2id".into(), salt: b64(&[7u8; 16]), m: 1024, t: 2, p: 1 };
+ let kek = derive_kek("correct horse battery", &kdf).unwrap();
+ let wrapped = wrap_key_with_nonce(&kek, &[9u8; 24], &[0x42u8; 32]);
+ assert_eq!(unwrap_key("correct horse battery", &wrapped, &kdf).unwrap(), [0x42u8; 32]);
+ println!("UNLOCK {} {}", kdf.salt, wrapped);
+ }
+
#[test]
fn record_round_trip() {
let key = random::<32>();
diff --git a/src/lib/api.js b/src/lib/api.js
index 300667df..44eab18e 100644
--- a/src/lib/api.js
+++ b/src/lib/api.js
@@ -1868,7 +1868,7 @@ export async function mcpSetReadonly(readonly) {
* @typedef {{ includeSchema?: boolean, includeData?: boolean, includeSequences?: boolean, includeEnums?: boolean, includeFunctions?: boolean, includeTriggers?: boolean, includeViews?: boolean }} BackupOptions
* @typedef {{ sql: string, tableCount: number, rowCount: number, cancelled: boolean, path: string | null, bytes: number, failedTables: number, elapsedMs: number }} BackupExportResult
* @typedef {{ statementsOk: number, statementsErr: number, statementsSkipped: number, cancelled: boolean, errors: string[], elapsedMs: number }} BackupImportResult
- * @typedef {{ size: number, engine: string | null, stroke: boolean, incomplete: boolean }} BackupFileInfo
+ * @typedef {{ size: number, engine: string | null, stroke: boolean, incomplete: boolean, encrypted?: boolean }} BackupFileInfo
*/
/**
@@ -1924,7 +1924,8 @@ export async function pickBackupSavePath(defaultName) {
*/
export async function pickBackupFile() {
const { open } = await import('@tauri-apps/plugin-dialog')
- const path = await open({ multiple: false, filters: [{ name: 'SQL', extensions: ['sql', 'txt'] }] })
+ // .gz and .stroke: scheduled backups (gzip, and end-to-end encrypted).
+ const path = await open({ multiple: false, filters: [{ name: 'SQL backups', extensions: ['sql', 'txt', 'gz', 'stroke'] }] })
return typeof path === 'string' ? path : null
}
diff --git a/src/lib/components/BackupPage.svelte b/src/lib/components/BackupPage.svelte
index 34899f17..591866ff 100644
--- a/src/lib/components/BackupPage.svelte
+++ b/src/lib/components/BackupPage.svelte
@@ -2,6 +2,7 @@
import { onDestroy } from 'svelte'
import FieldSelect from './FieldSelect.svelte'
import ScheduledBackups from './ScheduledBackups.svelte'
+ import LockKeyhole from '@lucide/svelte/icons/lock-keyhole'
import CalendarClock from '@lucide/svelte/icons/calendar-clock'
import { toast } from '$lib/components/ui/sonner/toast.svelte.js'
import { Button } from '$lib/components/ui/button/index.js'
@@ -888,6 +889,13 @@
{/if}
+ {#if importInfo?.encrypted}
+
+
+ End-to-end encrypted
+ A scheduled backup. It opens on this computer with your sync key; unlock sync first if it's locked.
+
+ {/if}
{#if importInfo?.incomplete}
diff --git a/src/lib/components/ScheduledBackups.svelte b/src/lib/components/ScheduledBackups.svelte
index a8f07e27..9d9678f8 100644
--- a/src/lib/components/ScheduledBackups.svelte
+++ b/src/lib/components/ScheduledBackups.svelte
@@ -4,6 +4,8 @@
// and history live on stroke.click; this device runs the jobs for
// connections saved on it (see $lib/stores/scheduled-backups.js).
import { onMount } from 'svelte'
+ import { invoke } from '@tauri-apps/api/core'
+ import LockKeyhole from '@lucide/svelte/icons/lock-keyhole'
import { Cron } from 'croner'
import { toast } from '$lib/components/ui/sonner/toast.svelte.js'
import { Button } from '$lib/components/ui/button/index.js'
@@ -45,8 +47,20 @@
const atLimit = $derived(!!overview && overview.jobs.length >= overview.max_jobs)
const usedPct = $derived(overview ? Math.min(100, (overview.used_bytes / overview.quota_bytes) * 100) : 0)
+ /** The sync key is on this computer: backups can be encrypted before upload. */
+ let syncUnlocked = $state(/** @type {boolean|null} */ (null))
+ async function checkSync() {
+ try {
+ const st = /** @type {{ unlocked: boolean }} */ (await invoke('sync_state'))
+ syncUnlocked = !!st.unlocked
+ } catch {
+ syncUnlocked = false
+ }
+ }
+
onMount(() => {
if ($isSignedIn) void refreshBackupJobs()
+ void checkSync()
})
// ── Form ───────────────────────────────────────────────────────────────────
@@ -101,6 +115,7 @@
/** @param {BackupJob|null} job */
async function openForm(job = null) {
formError = null
+ void checkSync()
editing = job?.id ?? null
destination = job?.destination ?? 'stroke'
keep = String(job?.keep ?? 7)
@@ -136,6 +151,7 @@
if (!connection || saving) return
formError = null
if (nextRun.error) { formError = nextRun.error; return }
+ if (destination === 'stroke' && !syncUnlocked) { formError = 'Set up or unlock sync (Settings → Sync) first: Stroke Cloud backups are encrypted with your sync key.'; return }
if (destination === 's3') {
if (!s3Bucket.trim()) { formError = 'Name the bucket.'; return }
if (!s3HasKeys && (!s3AccessKey.trim() || !s3Secret.trim())) { formError = 'Add the access key and secret.'; return }
@@ -400,6 +416,17 @@
{/if}
+
+
+ {#if destination === 'stroke' || syncUnlocked}
+ Encrypted on this computer with your sync key. Stroke can't read it, and without your sync passphrase nobody can, you included.
+ {:else}
+ Set up sync to encrypt these too; until then the bucket gets the plain .sql.gz.
+ {/if}
+
+ {#if destination === 'stroke' && syncUnlocked === false}
+ Stroke Cloud needs sync set up and unlocked on this computer (Settings → Sync).
+ {/if}
{#if formError}{formError}
{/if}