Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Add Tauri secure storage for Ensu secrets

Prateek Sunalbd7d6784af9d
diff --git a/rust/apps/ensu/src-tauri/Cargo.lock b/rust/apps/ensu/src-tauri/Cargo.lock
index 5b71ed86d4..a54cd958fd 100644
--- a/rust/apps/ensu/src-tauri/Cargo.lock
+++ b/rust/apps/ensu/src-tauri/Cargo.lock
@@ -18,6 +18,17 @@ dependencies = [
"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",
+]
+
[[package]]
name = "aho-corasick"
version = "1.1.4"
@@ -81,6 +92,123 @@ version = "0.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50"
+[[package]]
+name = "async-broadcast"
+version = "0.7.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532"
+dependencies = [
+ "event-listener",
+ "event-listener-strategy",
+ "futures-core",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "async-channel"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2"
+dependencies = [
+ "concurrent-queue",
+ "event-listener-strategy",
+ "futures-core",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "async-io"
+version = "2.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc"
+dependencies = [
+ "autocfg",
+ "cfg-if",
+ "concurrent-queue",
+ "futures-io",
+ "futures-lite",
+ "parking",
+ "polling",
+ "rustix",
+ "slab",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "async-lock"
+version = "3.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "290f7f2596bd5b78a9fec8088ccd89180d7f9f55b94b0576823bbbdc72ee8311"
+dependencies = [
+ "event-listener",
+ "event-listener-strategy",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "async-process"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75"
+dependencies = [
+ "async-channel",
+ "async-io",
+ "async-lock",
+ "async-signal",
+ "async-task",
+ "blocking",
+ "cfg-if",
+ "event-listener",
+ "futures-lite",
+ "rustix",
+]
+
+[[package]]
+name = "async-recursion"
+version = "1.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3b43422f69d8ff38f95f1b2bb76517c91589a924d1559a0e935d7c8ce0274c11"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.117",
+]
+
+[[package]]
+name = "async-signal"
+version = "0.2.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "43c070bbf59cd3570b6b2dd54cd772527c7c3620fce8be898406dd3ed6adc64c"
+dependencies = [
+ "async-io",
+ "async-lock",
+ "atomic-waker",
+ "cfg-if",
+ "futures-core",
+ "futures-io",
+ "rustix",
+ "signal-hook-registry",
+ "slab",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "async-task"
+version = "4.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de"
+
+[[package]]
+name = "async-trait"
+version = "0.1.89"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.117",
+]
+
[[package]]
name = "atk"
version = "0.15.1"
@@ -161,6 +289,26 @@ dependencies = [
"syn 2.0.117",
]
+[[package]]
+name = "bip39"
+version = "2.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "90dbd31c98227229239363921e60fcf5e558e43ec69094d46fc4996f08d1d5bc"
+dependencies = [
+ "bitcoin_hashes",
+ "serde",
+ "unicode-normalization",
+]
+
+[[package]]
+name = "bitcoin_hashes"
+version = "0.14.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "26ec84b80c482df901772e931a9a681e26a1b9ee2302edeff23cb30328745c8b"
+dependencies = [
+ "hex-conservative",
+]
+
[[package]]
name = "bitflags"
version = "1.3.2"
@@ -217,6 +365,19 @@ dependencies = [
"generic-array",
]
+[[package]]
+name = "blocking"
+version = "1.6.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e83f8d02be6967315521be875afa792a316e28d57b5a2d401897e2a7921b7f21"
+dependencies = [
+ "async-channel",
+ "async-task",
+ "futures-io",
+ "futures-lite",
+ "piper",
+]
+
[[package]]
name = "brotli"
version = "7.0.0"
@@ -306,6 +467,15 @@ dependencies = [
"toml 0.7.8",
]
+[[package]]
+name = "cbc"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6"
+dependencies = [
+ "cipher",
+]
+
[[package]]
name = "cc"
version = "1.2.56"
@@ -475,6 +645,15 @@ dependencies = [
"memchr",
]
+[[package]]
+name = "concurrent-queue"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973"
+dependencies = [
+ "crossbeam-utils",
+]
+
[[package]]
name = "constant_time_eq"
version = "0.4.2"
@@ -712,6 +891,35 @@ dependencies = [
"syn 2.0.117",
]
+[[package]]
+name = "dbus"
+version = "0.9.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "21b3aa68d7e7abee336255bd7248ea965cc393f3e70411135a6f6a4b651345d4"
+dependencies = [
+ "libc",
+ "libdbus-sys",
+ "windows-sys 0.59.0",
+]
+
+[[package]]
+name = "dbus-secret-service"
+version = "4.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "708b509edf7889e53d7efb0ffadd994cc6c2345ccb62f55cfd6b0682165e4fa6"
+dependencies = [
+ "aes",
+ "block-padding",
+ "cbc",
+ "dbus",
+ "fastrand",
+ "hkdf",
+ "num",
+ "once_cell",
+ "sha2",
+ "zeroize",
+]
+
[[package]]
name = "deranged"
version = "0.5.8"
@@ -846,6 +1054,12 @@ dependencies = [
"cfg-if",
]
+[[package]]
+name = "endi"
+version = "1.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099"
+
[[package]]
name = "ensu-db"
version = "0.1.0"
@@ -883,6 +1097,7 @@ dependencies = [
"ensu-sync",
"ente-core",
"inference_rs",
+ "keyring",
"serde",
"serde_json",
"tauri",
@@ -896,6 +1111,7 @@ version = "0.0.1"
dependencies = [
"argon2",
"base64 0.22.1",
+ "bip39",
"blake2b_simd",
"crypto_secretstream",
"getrandom 0.2.17",
@@ -922,6 +1138,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef"
dependencies = [
"enumflags2_derive",
+ "serde",
]
[[package]]
@@ -951,6 +1168,27 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "event-listener"
+version = "5.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e13b66accf52311f30a0db42147dadea9850cb48cd070028831ae5f5d4b856ab"
+dependencies = [
+ "concurrent-queue",
+ "parking",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "event-listener-strategy"
+version = "0.5.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93"
+dependencies = [
+ "event-listener",
+ "pin-project-lite",
+]
+
[[package]]
name = "fallible-iterator"
version = "0.3.0"
@@ -1124,6 +1362,19 @@ version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718"
+[[package]]
+name = "futures-lite"
+version = "2.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad"
+dependencies = [
+ "fastrand",
+ "futures-core",
+ "futures-io",
+ "parking",
+ "pin-project-lite",
+]
+
[[package]]
name = "futures-macro"
version = "0.3.32"
@@ -1390,7 +1641,7 @@ checksum = "10c6ae9f6fa26f4fb2ac16b528d138d971ead56141de489f8111e259b9df3c4a"
dependencies = [
"anyhow",
"heck 0.4.1",
- "proc-macro-crate",
+ "proc-macro-crate 1.3.1",
"proc-macro-error",
"proc-macro2",
"quote",
@@ -1485,7 +1736,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "684c0456c086e8e7e9af73ec5b84e35938df394712054550e81558d21c44ab0d"
dependencies = [
"anyhow",
- "proc-macro-crate",
+ "proc-macro-crate 1.3.1",
"proc-macro-error",
"proc-macro2",
"quote",
@@ -1565,12 +1816,27 @@ version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
+[[package]]
+name = "hermit-abi"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c"
+
[[package]]
name = "hex"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
+[[package]]
+name = "hex-conservative"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fda06d18ac606267c40c04e41b9947729bf8b9efe74bd4e82b61a5f26a510b9f"
+dependencies = [
+ "arrayvec",
+]
+
[[package]]
name = "hkdf"
version = "0.12.4"
@@ -2086,6 +2352,23 @@ dependencies = [
"serde_json",
]
+[[package]]
+name = "keyring"
+version = "3.6.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "eebcc3aff044e5944a8fbaf69eb277d11986064cba30c468730e8b9909fb551c"
+dependencies = [
+ "byteorder",
+ "dbus-secret-service",
+ "linux-keyutils",
+ "log",
+ "secret-service",
+ "security-framework 2.11.1",
+ "security-framework 3.7.0",
+ "windows-sys 0.60.2",
+ "zeroize",
+]
+
[[package]]
name = "kuchikiki"
version = "0.8.2"
@@ -2117,6 +2400,15 @@ version = "0.2.183"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5b646652bf6661599e1da8901b3b9522896f01e736bad5f723fe7a3a27f899d"
+[[package]]
+name = "libdbus-sys"
+version = "0.2.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "328c4789d42200f1eeec05bd86c9c13c7f091d2ba9a6ea35acdf51f31bc0f043"
+dependencies = [
+ "pkg-config",
+]
+
[[package]]
name = "libloading"
version = "0.8.9"
@@ -2150,6 +2442,16 @@ dependencies = [
"vcpkg",
]
+[[package]]
+name = "linux-keyutils"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "761e49ec5fd8a5a463f9b84e877c373d888935b71c6be78f3767fe2ae6bed18e"
+dependencies = [
+ "bitflags 2.11.0",
+ "libc",
+]
+
[[package]]
name = "linux-raw-sys"
version = "0.12.1"
@@ -2362,6 +2664,19 @@ version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086"
+[[package]]
+name = "nix"
+version = "0.29.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46"
+dependencies = [
+ "bitflags 2.11.0",
+ "cfg-if",
+ "cfg_aliases",
+ "libc",
+ "memoffset",
+]
+
[[package]]
name = "nodrop"
version = "0.1.14"
@@ -2387,6 +2702,20 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "num"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23"
+dependencies = [
+ "num-bigint",
+ "num-complex",
+ "num-integer",
+ "num-iter",
+ "num-rational",
+ "num-traits",
+]
+
[[package]]
name = "num-bigint"
version = "0.4.6"
@@ -2397,6 +2726,15 @@ dependencies = [
"num-traits",
]
+[[package]]
+name = "num-complex"
+version = "0.4.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495"
+dependencies = [
+ "num-traits",
+]
+
[[package]]
name = "num-conv"
version = "0.2.0"
@@ -2412,6 +2750,28 @@ dependencies = [
"num-traits",
]
+[[package]]
+name = "num-iter"
+version = "0.1.45"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1429034a0490724d0075ebb2bc9e875d6503c3cf69e235a8941aa757d83ef5bf"
+dependencies = [
+ "autocfg",
+ "num-integer",
+ "num-traits",
+]
+
+[[package]]
+name = "num-rational"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824"
+dependencies = [
+ "num-bigint",
+ "num-integer",
+ "num-traits",
+]
+
[[package]]
name = "num-traits"
version = "0.2.19"
@@ -2436,7 +2796,7 @@ version = "0.5.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dcbff9bc912032c62bf65ef1d5aea88983b420f4f839db1e9b0c281a25c9c799"
dependencies = [
- "proc-macro-crate",
+ "proc-macro-crate 1.3.1",
"proc-macro2",
"quote",
"syn 1.0.109",
@@ -2509,6 +2869,16 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"
+[[package]]
+name = "ordered-stream"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50"
+dependencies = [
+ "futures-core",
+ "pin-project-lite",
+]
+
[[package]]
name = "pango"
version = "0.15.10"
@@ -2534,6 +2904,12 @@ dependencies = [
"system-deps 6.2.2",
]
+[[package]]
+name = "parking"
+version = "2.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba"
+
[[package]]
name = "parking_lot"
version = "0.12.5"
@@ -2726,6 +3102,17 @@ version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
+[[package]]
+name = "piper"
+version = "0.2.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1"
+dependencies = [
+ "atomic-waker",
+ "fastrand",
+ "futures-io",
+]
+
[[package]]
name = "pkg-config"
version = "0.3.32"
@@ -2764,6 +3151,20 @@ dependencies = [
"miniz_oxide",
]
+[[package]]
+name = "polling"
+version = "3.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218"
+dependencies = [
+ "cfg-if",
+ "concurrent-queue",
+ "hermit-abi",
+ "pin-project-lite",
+ "rustix",
+ "windows-sys 0.61.2",
+]
+
[[package]]
name = "poly1305"
version = "0.8.0"
@@ -2825,6 +3226,15 @@ dependencies = [
"toml_edit 0.19.15",
]
+[[package]]
+name = "proc-macro-crate"
+version = "3.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f"
+dependencies = [
+ "toml_edit 0.25.4+spec-1.1.0",
+]
+
[[package]]
name = "proc-macro-error"
version = "1.0.4"
@@ -3300,7 +3710,7 @@ dependencies = [
"openssl-probe",
"rustls-pki-types",
"schannel",
- "security-framework",
+ "security-framework 3.7.0",
]
[[package]]
@@ -3399,6 +3809,38 @@ version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
+[[package]]
+name = "secret-service"
+version = "4.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e4d35ad99a181be0a60ffcbe85d680d98f87bdc4d7644ade319b87076b9dbfd4"
+dependencies = [
+ "aes",
+ "cbc",
+ "futures-util",
+ "generic-array",
+ "hkdf",
+ "num",
+ "once_cell",
+ "rand 0.8.5",
+ "serde",
+ "sha2",
+ "zbus",
+]
+
+[[package]]
+name = "security-framework"
+version = "2.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02"
+dependencies = [
+ "bitflags 2.11.0",
+ "core-foundation 0.9.4",
+ "core-foundation-sys",
+ "libc",
+ "security-framework-sys",
+]
+
[[package]]
name = "security-framework"
version = "3.7.0"
@@ -3597,6 +4039,17 @@ dependencies = [
"stable_deref_trait",
]
+[[package]]
+name = "sha1"
+version = "0.10.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba"
+dependencies = [
+ "cfg-if",
+ "cpufeatures",
+ "digest",
+]
+
[[package]]
name = "sha2"
version = "0.10.9"
@@ -3623,6 +4076,16 @@ version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
+[[package]]
+name = "signal-hook-registry"
+version = "1.4.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"
+dependencies = [
+ "errno",
+ "libc",
+]
+
[[package]]
name = "simd-adler32"
version = "0.3.8"
@@ -3731,6 +4194,12 @@ dependencies = [
"loom",
]
+[[package]]
+name = "static_assertions"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
+
[[package]]
name = "string_cache"
version = "0.8.9"
@@ -4313,7 +4782,7 @@ checksum = "dd79e69d3b627db300ff956027cc6c3798cef26d22526befdfcd12feeb6d2257"
dependencies = [
"serde",
"serde_spanned",
- "toml_datetime",
+ "toml_datetime 0.6.11",
"toml_edit 0.19.15",
]
@@ -4325,7 +4794,7 @@ checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362"
dependencies = [
"serde",
"serde_spanned",
- "toml_datetime",
+ "toml_datetime 0.6.11",
"toml_edit 0.22.27",
]
@@ -4338,6 +4807,15 @@ dependencies = [
"serde",
]
+[[package]]
+name = "toml_datetime"
+version = "1.0.0+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32c2555c699578a4f59f0cc68e5116c8d7cabbd45e1409b989d4be085b53f13e"
+dependencies = [
+ "serde_core",
+]
+
[[package]]
name = "toml_edit"
version = "0.19.15"
@@ -4347,7 +4825,7 @@ dependencies = [
"indexmap 2.13.0",
"serde",
"serde_spanned",
- "toml_datetime",
+ "toml_datetime 0.6.11",
"winnow 0.5.40",
]
@@ -4360,11 +4838,32 @@ dependencies = [
"indexmap 2.13.0",
"serde",
"serde_spanned",
- "toml_datetime",
+ "toml_datetime 0.6.11",
"toml_write",
"winnow 0.7.15",
]
+[[package]]
+name = "toml_edit"
+version = "0.25.4+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7193cbd0ce53dc966037f54351dbbcf0d5a642c7f0038c382ef9e677ce8c13f2"
+dependencies = [
+ "indexmap 2.13.0",
+ "toml_datetime 1.0.0+spec-1.1.0",
+ "toml_parser",
+ "winnow 0.7.15",
+]
+
+[[package]]
+name = "toml_parser"
+version = "1.0.9+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "702d4415e08923e7e1ef96cd5727c0dfed80b4d2fa25db9647fe5eb6f7c5a4c4"
+dependencies = [
+ "winnow 0.7.15",
+]
+
[[package]]
name = "toml_write"
version = "0.1.2"
@@ -4489,12 +4988,32 @@ version = "1.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "562d481066bde0658276a35467c4af00bdc6ee726305698a55b86e61d7ad82bb"
+[[package]]
+name = "uds_windows"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e"
+dependencies = [
+ "memoffset",
+ "tempfile",
+ "windows-sys 0.61.2",
+]
+
[[package]]
name = "unicode-ident"
version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
+[[package]]
+name = "unicode-normalization"
+version = "0.1.25"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8"
+dependencies = [
+ "tinyvec",
+]
+
[[package]]
name = "unicode-segmentation"
version = "1.12.0"
@@ -5062,6 +5581,15 @@ dependencies = [
"windows-targets 0.52.6",
]
+[[package]]
+name = "windows-sys"
+version = "0.59.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
+dependencies = [
+ "windows-targets 0.52.6",
+]
+
[[package]]
name = "windows-sys"
version = "0.60.2"
@@ -5586,6 +6114,16 @@ dependencies = [
"rustix",
]
+[[package]]
+name = "xdg-home"
+version = "1.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ec1cdab258fb55c0da61328dc52c8764709b249011b2cad0454c72f0bf10a1f6"
+dependencies = [
+ "libc",
+ "windows-sys 0.59.0",
+]
+
[[package]]
name = "xsalsa20poly1305"
version = "0.9.1"
@@ -5622,6 +6160,62 @@ dependencies = [
"synstructure",
]
+[[package]]
+name = "zbus"
+version = "4.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bb97012beadd29e654708a0fdb4c84bc046f537aecfde2c3ee0a9e4b4d48c725"
+dependencies = [
+ "async-broadcast",
+ "async-process",
+ "async-recursion",
+ "async-trait",
+ "enumflags2",
+ "event-listener",
+ "futures-core",
+ "futures-sink",
+ "futures-util",
+ "hex",
+ "nix",
+ "ordered-stream",
+ "rand 0.8.5",
+ "serde",
+ "serde_repr",
+ "sha1",
+ "static_assertions",
+ "tracing",
+ "uds_windows",
+ "windows-sys 0.52.0",
+ "xdg-home",
+ "zbus_macros",
+ "zbus_names",
+ "zvariant",
+]
+
+[[package]]
+name = "zbus_macros"
+version = "4.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "267db9407081e90bbfa46d841d3cbc60f59c0351838c4bc65199ecd79ab1983e"
+dependencies = [
+ "proc-macro-crate 3.5.0",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.117",
+ "zvariant_utils",
+]
+
+[[package]]
+name = "zbus_names"
+version = "3.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4b9b1fef7d021261cc16cba64c351d291b715febe0fa10dc3a443ac5a5022e6c"
+dependencies = [
+ "serde",
+ "static_assertions",
+ "zvariant",
+]
+
[[package]]
name = "zerocopy"
version = "0.8.42"
@@ -5721,3 +6315,40 @@ name = "zmij"
version = "1.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa"
+
+[[package]]
+name = "zvariant"
+version = "4.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2084290ab9a1c471c38fc524945837734fbf124487e105daec2bb57fd48c81fe"
+dependencies = [
+ "endi",
+ "enumflags2",
+ "serde",
+ "static_assertions",
+ "zvariant_derive",
+]
+
+[[package]]
+name = "zvariant_derive"
+version = "4.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "73e2ba546bda683a90652bac4a279bc146adad1386f25379cf73200d2002c449"
+dependencies = [
+ "proc-macro-crate 3.5.0",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.117",
+ "zvariant_utils",
+]
+
+[[package]]
+name = "zvariant_utils"
+version = "2.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c51bcff7cc3dbb5055396bcf774748c3dab426b4b8659046963523cee4808340"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.117",
+]
diff --git a/rust/apps/ensu/src-tauri/Cargo.toml b/rust/apps/ensu/src-tauri/Cargo.toml
index 59da245c51..58b59f1099 100644
--- a/rust/apps/ensu/src-tauri/Cargo.toml
+++ b/rust/apps/ensu/src-tauri/Cargo.toml
@@ -16,6 +16,7 @@ ensu-db = { path = "../../../ensu/db" }
ensu-sync = { path = "../../../ensu/sync" }
inference_rs = { path = "../../../ensu/inference" }
uuid = { version = "1", features = ["v4"] }
+keyring = { version = "3", default-features = false, features = ["apple-native", "windows-native", "linux-native-sync-persistent", "crypto-rust"] }
[features]
custom-protocol = ["tauri/custom-protocol"]
diff --git a/rust/apps/ensu/src-tauri/src/commands.rs b/rust/apps/ensu/src-tauri/src/commands.rs
index 989f68da64..fe1ee0b615 100644
--- a/rust/apps/ensu/src-tauri/src/commands.rs
+++ b/rust/apps/ensu/src-tauri/src/commands.rs
@@ -38,6 +38,8 @@ struct ChatDbHolder {
db: Arc<EnsuDb<SqliteBackend>>,
}
+const SECURE_STORAGE_SERVICE: &str = "io.ente.ensu";
+
#[derive(Debug, Serialize)]
pub struct ApiError {
code: String,
@@ -76,6 +78,11 @@ fn fs_thread_error() -> ApiError {
ApiError::new("io_thread", "FS task failed")
}
+fn secure_storage_entry(key: &str) -> Result<keyring::Entry, ApiError> {
+ keyring::Entry::new(SECURE_STORAGE_SERVICE, key)
+ .map_err(|err| ApiError::new("secure_storage", err.to_string()))
+}
+
fn default_llm_threads() -> i32 {
let available = std::thread::available_parallelism()
.map(|count| count.get())
@@ -760,6 +767,7 @@ pub struct ChatMessageUpsertInput {
sender: String,
text: String,
created_at: i64,
+ remote_id: Option<String>,
deleted_at: Option<i64>,
attachments: Option<Vec<ChatAttachmentInput>>,
}
@@ -1029,16 +1037,38 @@ pub async fn chat_db_insert_message_with_uuid(
.collect::<Result<Vec<_>, ApiError>>()?;
with_chat_db_async(&state, app, key_b64, move |db| {
- let message = db.insert_message_with_uuid(
- message_uuid,
- session_uuid,
- sender,
- &input.text,
- parent,
- attachments,
- input.created_at,
- input.deleted_at,
- )?;
+ let attachment_metas = attachments
+ .iter()
+ .cloned()
+ .map(ensu_db::AttachmentMeta::from)
+ .collect::<Vec<_>>();
+ let message = if let Some(remote_id) = input.remote_id.as_deref() {
+ let message = db.upsert_message_from_remote(
+ message_uuid,
+ session_uuid,
+ remote_id,
+ sender,
+ &input.text,
+ parent,
+ attachment_metas,
+ input.created_at,
+ )?;
+ if let Some(deleted_at) = input.deleted_at {
+ db.apply_message_tombstone(message_uuid, deleted_at)?;
+ }
+ message
+ } else {
+ db.insert_message_with_uuid(
+ message_uuid,
+ session_uuid,
+ sender,
+ &input.text,
+ parent,
+ attachments,
+ input.created_at,
+ input.deleted_at,
+ )?
+ };
build_message_dto(db, message)
})
.await
@@ -1545,6 +1575,33 @@ fn parse_uuid(value: &str) -> Result<Uuid, ApiError> {
Uuid::parse_str(value).map_err(|err| ApiError::new("uuid", err.to_string()))
}
+#[tauri::command]
+pub fn secure_storage_get(key: String) -> Result<Option<String>, ApiError> {
+ let entry = secure_storage_entry(&key)?;
+ match entry.get_password() {
+ Ok(value) => Ok(Some(value)),
+ Err(keyring::Error::NoEntry) => Ok(None),
+ Err(err) => Err(ApiError::new("secure_storage", err.to_string())),
+ }
+}
+
+#[tauri::command]
+pub fn secure_storage_set(key: String, value: String) -> Result<(), ApiError> {
+ let entry = secure_storage_entry(&key)?;
+ entry
+ .set_password(&value)
+ .map_err(|err| ApiError::new("secure_storage", err.to_string()))
+}
+
+#[tauri::command]
+pub fn secure_storage_delete(key: String) -> Result<(), ApiError> {
+ let entry = secure_storage_entry(&key)?;
+ match entry.delete_credential() {
+ Ok(()) | Err(keyring::Error::NoEntry) => Ok(()),
+ Err(err) => Err(ApiError::new("secure_storage", err.to_string())),
+ }
+}
+
fn chat_db_path(app: &AppHandle) -> Result<PathBuf, ApiError> {
let resolver = app.path_resolver();
let dir = resolver
diff --git a/rust/apps/ensu/src-tauri/src/main.rs b/rust/apps/ensu/src-tauri/src/main.rs
index ab69d29c60..53164e98fe 100644
--- a/rust/apps/ensu/src-tauri/src/main.rs
+++ b/rust/apps/ensu/src-tauri/src/main.rs
@@ -23,6 +23,9 @@ fn main() {
commands::crypto_decrypt_box,
commands::crypto_encrypt_blob,
commands::crypto_decrypt_blob,
+ commands::secure_storage_get,
+ commands::secure_storage_set,
+ commands::secure_storage_delete,
commands::auth_derive_srp_credentials,
commands::auth_decrypt_secrets,
commands::auth_decrypt_keys_only,
diff --git a/web/apps/ensu/src/pages/chat.tsx b/web/apps/ensu/src/pages/chat.tsx
index 6287a01241..984c34516a 100644
--- a/web/apps/ensu/src/pages/chat.tsx
+++ b/web/apps/ensu/src/pages/chat.tsx
@@ -19,6 +19,7 @@ import { savedLocalUser } from "ente-accounts/services/accounts-db";
import { openAccountsManagePasskeysPage } from "ente-accounts/services/passkey";
import { NavbarBase } from "ente-base/components/Navbar";
import { useBaseContext } from "ente-base/context";
+import { getKV, removeKV, setKV } from "ente-base/kv";
import log from "ente-base/log";
import { savedLogs } from "ente-base/log-web";
import { savedAuthToken } from "ente-base/token";
@@ -43,12 +44,14 @@ import {
cachedLocalChatKey,
getOrCreateChatKey,
getOrCreateLocalChatKey,
+ initChatKeyStore,
} from "services/chat/chatKey";
import {
addMessage,
createSession,
deleteSession,
getBranchSelections,
+ initializeChatStorePersistence,
listMessages,
listSessions,
readDecryptedAttachmentBytes,
@@ -80,8 +83,9 @@ import type {
ModelSettings,
} from "services/llm/types";
import {
- clearMasterKeyFromSession,
+ clearMasterKeyFromEverywhere,
masterKeyFromSession,
+ updateSessionFromTauriSecureStorageIfNeeded,
} from "services/session";
const formatTime = (timestamp: number) => {
@@ -188,6 +192,8 @@ const buildChatSystemPrompt = () => {
const SESSION_TITLE_PROMPT =
"You create concise chat titles. Given the provided message, summarize the user's goal in 5-7 words. Use plain words. Don't use markdown characters in the title. No quotes, no emojis, no trailing punctuation, and output only the title.";
+const MODEL_SETTINGS_KEY = "ensu.modelSettings";
+
const REPEAT_PENALTY = 1.18;
const STREAMING_OUTRO_DURATION_MS = 520;
@@ -811,6 +817,7 @@ const Page: React.FC = () => {
const [loadingPhrase, setLoadingPhrase] = useState<string | null>(null);
const [loadingDots, setLoadingDots] = useState(1);
const [isDownloading, setIsDownloading] = useState(false);
+ const [isChatStoreBridgeReady, setIsChatStoreBridgeReady] = useState(false);
const [attachmentPreviews, setAttachmentPreviews] = useState<
Record<string, string>
>({});
@@ -933,6 +940,8 @@ const Page: React.FC = () => {
);
const refreshAuthState = useCallback(async () => {
+ await initChatKeyStore();
+ await updateSessionFromTauriSecureStorageIfNeeded();
const token = await savedAuthToken();
const hasToken = !!token;
@@ -953,7 +962,7 @@ const Page: React.FC = () => {
masterKey = await masterKeyFromSession();
} catch (error) {
log.error("Failed to read master key from session", error);
- clearMasterKeyFromSession();
+ await clearMasterKeyFromEverywhere();
}
if (!masterKey) {
@@ -1030,6 +1039,32 @@ const Page: React.FC = () => {
routeInitializedRef.current = false;
}, [chatKey]);
+ useEffect(() => {
+ if (!chatKey) {
+ setIsChatStoreBridgeReady(false);
+ return;
+ }
+
+ let cancelled = false;
+ const run = async () => {
+ try {
+ await initializeChatStorePersistence(chatKey);
+ } catch (error) {
+ log.error("Failed to initialize chat persistence", error);
+ } finally {
+ if (!cancelled) {
+ setIsChatStoreBridgeReady(true);
+ }
+ }
+ };
+ run();
+
+ return () => {
+ cancelled = true;
+ setIsChatStoreBridgeReady(false);
+ };
+ }, [chatKey]);
+
useEffect(() => {
isDraftSessionRef.current = isDraftSession;
}, [isDraftSession]);
@@ -1050,7 +1085,7 @@ const Page: React.FC = () => {
masterKey = await masterKeyFromSession();
} catch (error) {
log.error("Failed to read master key from session", error);
- clearMasterKeyFromSession();
+ await clearMasterKeyFromEverywhere();
}
const remoteKey = cachedChatKey();
@@ -1199,47 +1234,49 @@ const Page: React.FC = () => {
}, [loading]);
useEffect(() => {
- if (typeof window === "undefined") return;
- const raw = window.localStorage.getItem("ensu.modelSettings");
- if (!raw) return;
- try {
- const parsed = JSON.parse(raw) as {
- useCustomModel?: boolean;
- modelUrl?: string;
- mmprojUrl?: string;
- contextLength?: string;
- maxTokens?: string;
- };
- const rawContextLength = parsed.contextLength ?? "";
- const clampedContextLength =
- !isTauriRuntime &&
- rawContextLength &&
- Number(rawContextLength) > DEFAULT_WEB_CONTEXT_SIZE
- ? String(DEFAULT_WEB_CONTEXT_SIZE)
- : rawContextLength;
- if (clampedContextLength !== rawContextLength) {
- const nextSettings = {
- useCustomModel: !!parsed.useCustomModel,
- modelUrl: parsed.modelUrl ?? "",
- mmprojUrl: allowMmproj ? (parsed.mmprojUrl ?? "") : "",
- contextLength: clampedContextLength,
- maxTokens: parsed.maxTokens ?? "",
+ let cancelled = false;
+ void getKV(MODEL_SETTINGS_KEY)
+ .then(async (raw) => {
+ if (!raw || typeof raw !== "object") return;
+ const parsed = raw as {
+ useCustomModel?: boolean;
+ modelUrl?: string;
+ mmprojUrl?: string;
+ contextLength?: string;
+ maxTokens?: string;
};
- window.localStorage.setItem(
- "ensu.modelSettings",
- JSON.stringify(nextSettings),
+ const rawContextLength = parsed.contextLength ?? "";
+ const clampedContextLength =
+ !isTauriRuntime &&
+ rawContextLength &&
+ Number(rawContextLength) > DEFAULT_WEB_CONTEXT_SIZE
+ ? String(DEFAULT_WEB_CONTEXT_SIZE)
+ : rawContextLength;
+ if (clampedContextLength !== rawContextLength) {
+ const nextSettings = {
+ useCustomModel: !!parsed.useCustomModel,
+ modelUrl: parsed.modelUrl ?? "",
+ mmprojUrl: allowMmproj ? (parsed.mmprojUrl ?? "") : "",
+ contextLength: clampedContextLength,
+ maxTokens: parsed.maxTokens ?? "",
+ };
+ await setKV(MODEL_SETTINGS_KEY, nextSettings);
+ }
+ if (cancelled) return;
+ setUseCustomModel(
+ MODEL_SETTINGS_ENABLED && !!parsed.useCustomModel,
);
- }
- setUseCustomModel(
- MODEL_SETTINGS_ENABLED && !!parsed.useCustomModel,
- );
- setModelUrl(parsed.modelUrl ?? "");
- setMmprojUrl(allowMmproj ? (parsed.mmprojUrl ?? "") : "");
- setContextLength(clampedContextLength);
- setMaxTokens(parsed.maxTokens ?? "");
- } catch (error) {
- log.error("Failed to read model settings", error);
- }
+ setModelUrl(parsed.modelUrl ?? "");
+ setMmprojUrl(allowMmproj ? (parsed.mmprojUrl ?? "") : "");
+ setContextLength(clampedContextLength);
+ setMaxTokens(parsed.maxTokens ?? "");
+ })
+ .catch((error) => {
+ log.error("Failed to read model settings", error);
+ });
+ return () => {
+ cancelled = true;
+ };
}, [allowMmproj, isTauriRuntime]);
const applyDownloadProgress = useCallback((progress: DownloadProgress) => {
@@ -1618,13 +1655,13 @@ const Page: React.FC = () => {
}, [deleteSessionTarget]);
useEffect(() => {
- if (!chatKey) return;
+ if (!chatKey || !isChatStoreBridgeReady) return;
if (isLoggedIn) {
void syncNow();
return;
}
void refreshSessions();
- }, [chatKey, isLoggedIn, refreshSessions, syncNow]);
+ }, [chatKey, isChatStoreBridgeReady, isLoggedIn, refreshSessions, syncNow]);
useEffect(() => {
currentSessionIdRef.current = currentSessionId;
@@ -1772,9 +1809,23 @@ const Page: React.FC = () => {
setBranchSelections({});
return;
}
- setBranchSelections(
- getBranchSelections(currentSession.rootSessionUuid),
- );
+ let cancelled = false;
+ void getBranchSelections(currentSession.rootSessionUuid)
+ .then((selections) => {
+ if (!cancelled) {
+ setBranchSelections(selections);
+ }
+ })
+ .catch((error) => {
+ log.error("Failed to load branch selections", error);
+ if (!cancelled) {
+ setBranchSelections({});
+ }
+ });
+
+ return () => {
+ cancelled = true;
+ };
}, [currentSession?.rootSessionUuid]);
useEffect(() => {
@@ -2266,7 +2317,11 @@ const Page: React.FC = () => {
]);
const updateBranchSelectionState = useCallback(
- (selectionKey: string, selectedMessageUuid: string, persist = true) => {
+ async (
+ selectionKey: string,
+ selectedMessageUuid: string,
+ persist = true,
+ ) => {
setBranchSelections((prev) => ({
...prev,
[selectionKey]: selectedMessageUuid,
@@ -2280,7 +2335,7 @@ const Page: React.FC = () => {
return;
}
- setBranchSelection(
+ await setBranchSelection(
rootSessionUuid,
selectionKey,
selectedMessageUuid,
@@ -3466,7 +3521,7 @@ const Page: React.FC = () => {
);
}, [contextLength, maxTokens, mmprojUrl, modelUrl, isTauriRuntime]);
- const handleSaveModel = useCallback(() => {
+ const handleSaveModel = useCallback(async () => {
if (!validateModelSettings()) return;
setIsSavingModel(true);
const payload = {
@@ -3476,12 +3531,7 @@ const Page: React.FC = () => {
contextLength,
maxTokens,
};
- if (typeof window !== "undefined") {
- window.localStorage.setItem(
- "ensu.modelSettings",
- JSON.stringify(payload),
- );
- }
+ await setKV(MODEL_SETTINGS_KEY, payload);
setUseCustomModel(true);
setLoadedModelName(null);
setIsSavingModel(false);
@@ -3495,10 +3545,8 @@ const Page: React.FC = () => {
isTauriRuntime,
]);
- const handleUseDefaultModel = useCallback(() => {
- if (typeof window !== "undefined") {
- window.localStorage.removeItem("ensu.modelSettings");
- }
+ const handleUseDefaultModel = useCallback(async () => {
+ await removeKV(MODEL_SETTINGS_KEY);
setUseCustomModel(false);
setModelUrl("");
setMmprojUrl("");
diff --git a/web/apps/ensu/src/services/chat/chatKey.ts b/web/apps/ensu/src/services/chat/chatKey.ts
index 54fb8eec75..f1155e5f97 100644
--- a/web/apps/ensu/src/services/chat/chatKey.ts
+++ b/web/apps/ensu/src/services/chat/chatKey.ts
@@ -1,36 +1,227 @@
import { HTTPError } from "ente-base/http";
import { ensureCryptoInit, enteWasm } from "../wasm";
import { ChatKeyNotFoundError, createChatKey, getChatKey } from "./gateway";
+import {
+ isTauriAppRuntime,
+ secureStorageDelete,
+ secureStorageGet,
+ secureStorageSet,
+} from "../secure-storage";
const CHAT_KEY_LOCAL_STORAGE_KEY = "ensu.chatKey";
const LOCAL_CHAT_KEY_LOCAL_STORAGE_KEY = "ensu.chatKey.local";
+const CHAT_KEY_FILE_NAME = "chat-keys.json";
+const REMOTE_CHAT_KEY_SECURE_STORAGE_KEY = "remoteChatKey";
+const LOCAL_CHAT_KEY_SECURE_STORAGE_KEY = "localChatKey";
+
+type PersistedChatKeys = {
+ remoteChatKey?: string;
+ localChatKey?: string;
+};
+
+let _persistedChatKeys: PersistedChatKeys = {};
+let _chatKeyStoreInitPromise: Promise<void> | undefined;
+
+const readLocalStorageKey = (key: string) => {
+ if (typeof localStorage === "undefined") return undefined;
+ return localStorage.getItem(key) ?? undefined;
+};
+
+const writeLocalStorageKey = (key: string, value: string) => {
+ if (typeof localStorage === "undefined") return;
+ localStorage.setItem(key, value);
+};
+
+const removeLocalStorageKey = (key: string) => {
+ if (typeof localStorage === "undefined") return;
+ localStorage.removeItem(key);
+};
+
+const nativeChatKeyPath = async () => {
+ const { appDataDir, join } = await import("@tauri-apps/api/path");
+ const root = await appDataDir();
+ return join(root, CHAT_KEY_FILE_NAME);
+};
+
+const readNativeChatKeys = async (): Promise<PersistedChatKeys> => {
+ if (!isTauriAppRuntime()) return {};
+
+ const [{ exists, readBinaryFile }, path] = await Promise.all([
+ import("@tauri-apps/api/fs"),
+ nativeChatKeyPath(),
+ ]);
+
+ if (!(await exists(path))) return {};
+
+ try {
+ const raw = new TextDecoder().decode(await readBinaryFile(path));
+ const parsed = JSON.parse(raw) as PersistedChatKeys;
+ return {
+ remoteChatKey:
+ typeof parsed.remoteChatKey === "string"
+ ? parsed.remoteChatKey
+ : undefined,
+ localChatKey:
+ typeof parsed.localChatKey === "string"
+ ? parsed.localChatKey
+ : undefined,
+ };
+ } catch {
+ return {};
+ }
+};
+
+const persistNativeChatKeys = async () => {
+ if (!isTauriAppRuntime()) return;
+
+ const operations: Promise<void>[] = [];
+ if (_persistedChatKeys.remoteChatKey) {
+ operations.push(
+ secureStorageSet(
+ REMOTE_CHAT_KEY_SECURE_STORAGE_KEY,
+ _persistedChatKeys.remoteChatKey,
+ ),
+ );
+ } else {
+ operations.push(secureStorageDelete(REMOTE_CHAT_KEY_SECURE_STORAGE_KEY));
+ }
+
+ if (_persistedChatKeys.localChatKey) {
+ operations.push(
+ secureStorageSet(
+ LOCAL_CHAT_KEY_SECURE_STORAGE_KEY,
+ _persistedChatKeys.localChatKey,
+ ),
+ );
+ } else {
+ operations.push(secureStorageDelete(LOCAL_CHAT_KEY_SECURE_STORAGE_KEY));
+ }
+
+ await Promise.all(operations);
+};
+
+const persistNativeChatKeysSoon = () => {
+ persistNativeChatKeys().catch(() => {
+ // Best effort cache persistence.
+ });
+};
+
+export const initChatKeyStore = async () => {
+ if (!isTauriAppRuntime()) return;
+
+ _chatKeyStoreInitPromise ??= (async () => {
+ const [secureRemoteChatKey, secureLocalChatKey, nativeKeys] =
+ await Promise.all([
+ secureStorageGet(
+ REMOTE_CHAT_KEY_SECURE_STORAGE_KEY,
+ ).catch(() => undefined),
+ secureStorageGet(
+ LOCAL_CHAT_KEY_SECURE_STORAGE_KEY,
+ ).catch(() => undefined),
+ readNativeChatKeys(),
+ ]);
+ const remoteChatKey =
+ secureRemoteChatKey ??
+ nativeKeys.remoteChatKey ??
+ readLocalStorageKey(CHAT_KEY_LOCAL_STORAGE_KEY);
+ const localChatKey =
+ secureLocalChatKey ??
+ nativeKeys.localChatKey ??
+ readLocalStorageKey(LOCAL_CHAT_KEY_LOCAL_STORAGE_KEY);
+
+ _persistedChatKeys = { remoteChatKey, localChatKey };
+
+ if (
+ secureRemoteChatKey !== remoteChatKey ||
+ secureLocalChatKey !== localChatKey
+ ) {
+ try {
+ await persistNativeChatKeys();
+ removeLocalStorageKey(CHAT_KEY_LOCAL_STORAGE_KEY);
+ removeLocalStorageKey(LOCAL_CHAT_KEY_LOCAL_STORAGE_KEY);
+ } catch {
+ // Keep legacy localStorage keys when secure storage is unavailable.
+ }
+ } else {
+ removeLocalStorageKey(CHAT_KEY_LOCAL_STORAGE_KEY);
+ removeLocalStorageKey(LOCAL_CHAT_KEY_LOCAL_STORAGE_KEY);
+ }
+
+ try {
+ const { removeFile } = await import("@tauri-apps/api/fs");
+ const path = await nativeChatKeyPath();
+ await removeFile(path);
+ } catch {
+ // ignore missing legacy file
+ }
+ })().catch((error) => {
+ _chatKeyStoreInitPromise = undefined;
+ throw error;
+ });
+
+ return _chatKeyStoreInitPromise;
+};
+
+const setCachedChatKey = (chatKey: string) => {
+ if (isTauriAppRuntime()) {
+ _persistedChatKeys.remoteChatKey = chatKey;
+ persistNativeChatKeysSoon();
+ return;
+ }
+
+ writeLocalStorageKey(CHAT_KEY_LOCAL_STORAGE_KEY, chatKey);
+};
+
+const setCachedLocalChatKey = (chatKey: string) => {
+ if (isTauriAppRuntime()) {
+ _persistedChatKeys.localChatKey = chatKey;
+ persistNativeChatKeysSoon();
+ return;
+ }
+
+ writeLocalStorageKey(LOCAL_CHAT_KEY_LOCAL_STORAGE_KEY, chatKey);
+};
/**
* Return the cached chat key (base64), if present.
*/
export const cachedChatKey = (): string | undefined => {
- if (typeof localStorage === "undefined") return undefined;
- const value = localStorage.getItem(CHAT_KEY_LOCAL_STORAGE_KEY);
- return value ?? undefined;
+ if (isTauriAppRuntime()) {
+ return _persistedChatKeys.remoteChatKey;
+ }
+
+ return readLocalStorageKey(CHAT_KEY_LOCAL_STORAGE_KEY);
};
/**
* Return the cached local-only chat key (base64), if present.
*/
export const cachedLocalChatKey = (): string | undefined => {
- if (typeof localStorage === "undefined") return undefined;
- const value = localStorage.getItem(LOCAL_CHAT_KEY_LOCAL_STORAGE_KEY);
- return value ?? undefined;
+ if (isTauriAppRuntime()) {
+ return _persistedChatKeys.localChatKey;
+ }
+
+ return readLocalStorageKey(LOCAL_CHAT_KEY_LOCAL_STORAGE_KEY);
};
export const clearCachedChatKey = () => {
- if (typeof localStorage === "undefined") return;
- localStorage.removeItem(CHAT_KEY_LOCAL_STORAGE_KEY);
+ if (isTauriAppRuntime()) {
+ delete _persistedChatKeys.remoteChatKey;
+ persistNativeChatKeysSoon();
+ return;
+ }
+
+ removeLocalStorageKey(CHAT_KEY_LOCAL_STORAGE_KEY);
};
export const clearLocalChatKey = () => {
- if (typeof localStorage === "undefined") return;
- localStorage.removeItem(LOCAL_CHAT_KEY_LOCAL_STORAGE_KEY);
+ if (isTauriAppRuntime()) {
+ delete _persistedChatKeys.localChatKey;
+ persistNativeChatKeysSoon();
+ return;
+ }
+
+ removeLocalStorageKey(LOCAL_CHAT_KEY_LOCAL_STORAGE_KEY);
};
/**
@@ -39,6 +230,7 @@ export const clearLocalChatKey = () => {
* The key is stored on the server encrypted with the user's master key.
*/
export const getOrCreateChatKey = async (masterKeyB64: string) => {
+ await initChatKeyStore();
const cached = cachedChatKey();
if (cached) return cached;
@@ -52,7 +244,7 @@ export const getOrCreateChatKey = async (masterKeyB64: string) => {
remote.header,
masterKeyB64,
);
- localStorage.setItem(CHAT_KEY_LOCAL_STORAGE_KEY, chatKey);
+ setCachedChatKey(chatKey);
return chatKey;
} catch (e) {
if (!(e instanceof ChatKeyNotFoundError)) throw e;
@@ -65,7 +257,7 @@ export const getOrCreateChatKey = async (masterKeyB64: string) => {
encrypted.encrypted_data,
encrypted.decryption_header,
);
- localStorage.setItem(CHAT_KEY_LOCAL_STORAGE_KEY, chatKey);
+ setCachedChatKey(chatKey);
return chatKey;
} catch (error) {
if (error instanceof HTTPError && error.res.status === 409) {
@@ -75,7 +267,7 @@ export const getOrCreateChatKey = async (masterKeyB64: string) => {
remote.header,
masterKeyB64,
);
- localStorage.setItem(CHAT_KEY_LOCAL_STORAGE_KEY, resolved);
+ setCachedChatKey(resolved);
return resolved;
}
throw error;
@@ -87,14 +279,13 @@ export const getOrCreateChatKey = async (masterKeyB64: string) => {
* Get or create a local-only chat key (used when the user is not signed in).
*/
export const getOrCreateLocalChatKey = async () => {
+ await initChatKeyStore();
const cached = cachedLocalChatKey();
if (cached) return cached;
await ensureCryptoInit();
const wasm = await enteWasm();
const chatKey = await wasm.crypto_generate_key();
- if (typeof localStorage !== "undefined") {
- localStorage.setItem(LOCAL_CHAT_KEY_LOCAL_STORAGE_KEY, chatKey);
- }
+ setCachedLocalChatKey(chatKey);
return chatKey;
};
diff --git a/web/apps/ensu/src/services/chat/store.ts b/web/apps/ensu/src/services/chat/store.ts
index 12c0a105aa..edc026b05a 100644
--- a/web/apps/ensu/src/services/chat/store.ts
+++ b/web/apps/ensu/src/services/chat/store.ts
@@ -1,5 +1,7 @@
import log from "ente-base/log";
-import { base64ToBytes, bytesToBase64 } from "services/base64";
+import { getKV, removeKV, setKV } from "ente-base/kv";
+import { deleteDB, openDB, type DBSchema, type IDBPDatabase } from "idb";
+import { base64ToBytes } from "services/base64";
import { decryptAttachmentBytes, encryptAttachmentBytes } from "./attachments";
import { cachedLocalChatKey } from "./chatKey";
import {
@@ -10,6 +12,7 @@ import {
} from "./crypto";
const STORAGE_KEY = "ensu.chat.store.v1";
+const NATIVE_MIGRATION_KEY = "ensu.chat.nativeMigration.v1";
export type AttachmentKind = "image" | "document";
@@ -86,6 +89,21 @@ type ChatStoreState = {
attachmentBytes: StoredAttachmentBytes[];
};
+interface IndexedChatDBSchema extends DBSchema {
+ sessions: {
+ key: string;
+ value: StoredSession;
+ };
+ messages: {
+ key: string;
+ value: StoredMessage;
+ };
+ attachmentBytes: {
+ key: string;
+ value: StoredAttachmentBytes;
+ };
+}
+
interface ChatObjectStore<K extends ChatStoreName> {
get: (key: string) => Promise<ChatDbSchema[K] | undefined>;
getAll: () => Promise<ChatDbSchema[K][]>;
@@ -277,20 +295,6 @@ const withNativeDbRecovery = async <T>(
}
};
-const cloneStoreState = (state: ChatStoreState): ChatStoreState => ({
- sessions: state.sessions.map((session) => ({ ...session })),
- messages: state.messages.map((message) => ({
- ...message,
- attachments: message.attachments?.map((attachment) => ({
- ...attachment,
- })),
- })),
- attachmentBytes: state.attachmentBytes.map((attachment) => ({
- id: attachment.id,
- data: new Uint8Array(attachment.data),
- })),
-});
-
const loadChatStoreState = (): ChatStoreState => {
if (typeof localStorage === "undefined") {
return { sessions: [], messages: [], attachmentBytes: [] };
@@ -331,35 +335,6 @@ const loadChatStoreState = (): ChatStoreState => {
}
};
-const saveChatStoreState = (state: ChatStoreState) => {
- if (typeof localStorage === "undefined") return;
-
- const persisted: PersistedChatStore = {
- sessions: state.sessions,
- messages: state.messages,
- attachmentBytes: state.attachmentBytes.map((attachment) => ({
- id: attachment.id,
- data: bytesToBase64(attachment.data),
- })),
- };
- localStorage.setItem(STORAGE_KEY, JSON.stringify(persisted));
-};
-
-const getStoreKey = (name: ChatStoreName, value: ChatDbSchema[ChatStoreName]) => {
- if (name === "sessions") {
- return (value as StoredSession).sessionUuid;
- }
- if (name === "messages") {
- return (value as StoredMessage).messageUuid;
- }
- return (value as StoredAttachmentBytes).id;
-};
-
-const getStoreCollection = <K extends ChatStoreName>(
- state: ChatStoreState,
- name: K,
-): ChatDbSchema[K][] => state[name] as ChatDbSchema[K][];
-
const cloneStoreEntry = <K extends ChatStoreName>(
name: K,
value: ChatDbSchema[K],
@@ -382,81 +357,108 @@ const cloneStoreEntry = <K extends ChatStoreName>(
return cloned;
};
-const createObjectStore = <K extends ChatStoreName>(
- state: ChatStoreState,
+let _chatDb: Promise<ChatDbLike> | undefined;
+let _chatPersistenceInitPromise: Promise<void> | undefined;
+let _chatPersistenceInitKey: string | undefined;
+
+const normalizeStoredSession = (session: StoredSession): StoredSession => ({
+ ...session,
+ remoteId: session.remoteId ?? null,
+ needsSync: session.needsSync ?? true,
+ deletedAt:
+ session.deletedAt ?? (session.isDeleted ? session.updatedAt : null),
+});
+
+const normalizeStoredMessage = (message: StoredMessage): StoredMessage => ({
+ ...message,
+ attachments: message.attachments ?? [],
+ remoteId: message.remoteId ?? null,
+ deletedAt:
+ message.deletedAt ?? (message.isDeleted ? message.createdAt : null),
+});
+
+const normalizeStoreEntry = <K extends ChatStoreName>(
name: K,
-): ChatObjectStore<K> => ({
- get: async (key) =>
- (() => {
- const entry = getStoreCollection(state, name).find(
- (candidate) => getStoreKey(name, candidate) === key,
- );
- return entry ? cloneStoreEntry(name, entry) : undefined;
- })(),
- getAll: async () =>
- getStoreCollection(state, name).map((entry) =>
- cloneStoreEntry(name, entry),
- ),
- put: async (value) => {
- const collection = getStoreCollection(state, name);
- const key = getStoreKey(name, value);
- const index = collection.findIndex((entry) => getStoreKey(name, entry) === key);
- const nextValue = cloneStoreEntry(name, value);
- if (index >= 0) {
- collection[index] = nextValue;
- } else {
- collection.push(nextValue);
- }
+ value: ChatDbSchema[K],
+): ChatDbSchema[K] => {
+ if (name === "sessions") {
+ return normalizeStoredSession(value as StoredSession) as ChatDbSchema[K];
+ }
+ if (name === "messages") {
+ return normalizeStoredMessage(value as StoredMessage) as ChatDbSchema[K];
+ }
+ return value;
+};
+
+const createIndexedDbChatDb = (
+ db: IDBPDatabase<IndexedChatDBSchema>,
+): ChatDbLike => ({
+ get: async (name, key) => {
+ const entry = (await db.get(name, key)) as
+ | ChatDbSchema[typeof name]
+ | undefined;
+ if (!entry) return undefined;
+ return cloneStoreEntry(name, normalizeStoreEntry(name, entry));
},
- delete: async (key) => {
- const collection = getStoreCollection(state, name);
- const index = collection.findIndex((entry) => getStoreKey(name, entry) === key);
- if (index >= 0) {
- collection.splice(index, 1);
- }
+ getAll: async (name) => {
+ const entries = (await db.getAll(name)) as ChatDbSchema[typeof name][];
+ return entries.map((entry) =>
+ cloneStoreEntry(name, normalizeStoreEntry(name, entry)),
+ );
},
-});
-
-const createLocalStorageChatDb = (): ChatDbLike => ({
- get: async (name, key) => createObjectStore(loadChatStoreState(), name).get(key),
- getAll: async (name) => createObjectStore(loadChatStoreState(), name).getAll(),
put: async (name, value) => {
- const state = loadChatStoreState();
- await createObjectStore(state, name).put(value);
- saveChatStoreState(state);
+ await db.put(name, cloneStoreEntry(name, value));
},
delete: async (name, key) => {
- const state = loadChatStoreState();
- await createObjectStore(state, name).delete(key);
- saveChatStoreState(state);
+ await db.delete(name, key);
},
- transaction: () => {
- const state = cloneStoreState(loadChatStoreState());
+ transaction: (names, mode) => {
+ const tx = db.transaction(names, mode);
return {
- objectStore: <K extends ChatStoreName>(name: K): ChatObjectStore<K> => {
- const base = createObjectStore(state, name);
- return {
- get: base.get,
- getAll: base.getAll,
- put: async (value: ChatDbSchema[K]) => {
- await base.put(value);
- saveChatStoreState(state);
- },
- delete: async (key: string) => {
- await base.delete(key);
- saveChatStoreState(state);
- },
- };
- },
- done: Promise.resolve(),
+ objectStore: <K extends ChatStoreName>(name: K): ChatObjectStore<K> => ({
+ get: async (key) => {
+ const entry = (await tx.objectStore(name).get(
+ key,
+ )) as ChatDbSchema[K] | undefined;
+ if (!entry) return undefined;
+ return cloneStoreEntry(name, normalizeStoreEntry(name, entry));
+ },
+ getAll: async () => {
+ const entries = (await tx.objectStore(name).getAll()) as ChatDbSchema[K][];
+ return entries.map((entry) =>
+ cloneStoreEntry(name, normalizeStoreEntry(name, entry)),
+ );
+ },
+ put: async (value: ChatDbSchema[K]) => {
+ await tx.objectStore(name).put(cloneStoreEntry(name, value));
+ },
+ delete: async (key: string) => {
+ await tx.objectStore(name).delete(key);
+ },
+ }),
+ done: tx.done,
};
},
- close: () => {},
+ close: () => db.close(),
});
-let _chatDb: Promise<ChatDbLike> | undefined;
+const openChatDb = async () => {
+ const db = await openDB<IndexedChatDBSchema>("ensu-chat", 1, {
+ upgrade(db) {
+ if (!db.objectStoreNames.contains("sessions")) {
+ db.createObjectStore("sessions", { keyPath: "sessionUuid" });
+ }
+ if (!db.objectStoreNames.contains("messages")) {
+ db.createObjectStore("messages", { keyPath: "messageUuid" });
+ }
+ if (!db.objectStoreNames.contains("attachmentBytes")) {
+ db.createObjectStore("attachmentBytes", { keyPath: "id" });
+ }
+ },
+ });
-const openChatDb = async () => createLocalStorageChatDb();
+ return createIndexedDbChatDb(db);
+};
const chatDb = () => (_chatDb ??= openChatDb());
@@ -584,6 +586,180 @@ const deserializeAttachments = async (
);
};
+const hasLegacyChatStore = () =>
+ typeof localStorage !== "undefined" && !!localStorage.getItem(STORAGE_KEY);
+
+const isNativeMigrationDone = () =>
+ typeof localStorage !== "undefined" &&
+ localStorage.getItem(NATIVE_MIGRATION_KEY) === "1";
+
+const markNativeMigrationDone = () => {
+ if (typeof localStorage === "undefined") return;
+ localStorage.setItem(NATIVE_MIGRATION_KEY, "1");
+};
+
+const migrateLegacyLocalChatStoreToIndexedDb = async () => {
+ if (typeof localStorage === "undefined") return;
+
+ const legacy = loadChatStoreState();
+ if (
+ !legacy.sessions.length &&
+ !legacy.messages.length &&
+ !legacy.attachmentBytes.length
+ ) {
+ localStorage.removeItem(STORAGE_KEY);
+ return;
+ }
+
+ log.info("Migrating legacy local chat store to IndexedDB", {
+ sessions: legacy.sessions.length,
+ messages: legacy.messages.length,
+ attachmentBytes: legacy.attachmentBytes.length,
+ });
+
+ const db = await chatDb();
+ const tx = db.transaction(
+ ["sessions", "messages", "attachmentBytes"],
+ "readwrite",
+ );
+
+ for (const session of legacy.sessions) {
+ await tx.objectStore("sessions").put(normalizeStoredSession(session));
+ }
+
+ for (const message of legacy.messages) {
+ await tx.objectStore("messages").put(normalizeStoredMessage(message));
+ }
+
+ for (const attachment of legacy.attachmentBytes) {
+ await tx.objectStore("attachmentBytes").put({
+ id: attachment.id,
+ data: new Uint8Array(attachment.data),
+ });
+ }
+
+ await tx.done;
+ localStorage.removeItem(STORAGE_KEY);
+ log.info("Finished migrating legacy local chat store to IndexedDB");
+};
+
+const migrateLegacyChatStoreToNative = async (chatKey: string) => {
+ if (!isTauriRuntime() || typeof localStorage === "undefined") return;
+
+ const legacy = loadChatStoreState();
+ if (
+ !legacy.sessions.length &&
+ !legacy.messages.length &&
+ !legacy.attachmentBytes.length
+ ) {
+ localStorage.removeItem(STORAGE_KEY);
+ markNativeMigrationDone();
+ return;
+ }
+
+ log.info("Migrating legacy local chat store to native DB", {
+ sessions: legacy.sessions.length,
+ messages: legacy.messages.length,
+ attachmentBytes: legacy.attachmentBytes.length,
+ });
+
+ const sessions = [...legacy.sessions].sort(
+ (left, right) => left.createdAt - right.createdAt,
+ );
+ for (const session of sessions) {
+ const title = await decryptSessionTitle(session, chatKey);
+ await invokeChat("chat_db_upsert_session", {
+ keyB64: chatKey,
+ input: {
+ sessionUuid: session.sessionUuid,
+ title,
+ createdAt: session.createdAt,
+ updatedAt: session.updatedAt,
+ remoteId: session.remoteId ?? null,
+ needsSync: session.needsSync ?? false,
+ deletedAt: session.deletedAt ?? null,
+ },
+ });
+ }
+
+ const messages = [...legacy.messages].sort(
+ (left, right) => left.createdAt - right.createdAt,
+ );
+ for (const message of messages) {
+ const attachments = await deserializeAttachments(
+ message.attachments,
+ chatKey,
+ );
+
+ if (!message.remoteId) {
+ const existing = await invokeChat<NativeMessage | null>(
+ "chat_db_get_message",
+ { keyB64: chatKey, messageUuid: message.messageUuid },
+ );
+ if (existing) {
+ continue;
+ }
+ }
+
+ await invokeChat("chat_db_insert_message_with_uuid", {
+ keyB64: chatKey,
+ input: {
+ messageUuid: message.messageUuid,
+ sessionUuid: message.sessionUuid,
+ parentMessageUuid: message.parentMessageUuid ?? null,
+ sender: message.sender,
+ text: await decryptMessageText(message, chatKey),
+ createdAt: message.createdAt,
+ remoteId: message.remoteId ?? null,
+ deletedAt: message.deletedAt ?? null,
+ attachments: attachments.map((attachment) => ({
+ id: attachment.id,
+ kind: attachment.kind,
+ name: attachment.name,
+ size: attachment.size,
+ uploadedAt: attachment.uploadedAt ?? null,
+ })),
+ },
+ });
+ }
+
+ for (const attachment of legacy.attachmentBytes) {
+ await writeAttachmentBytes(attachment.id, attachment.data);
+ }
+
+ localStorage.removeItem(STORAGE_KEY);
+ markNativeMigrationDone();
+ log.info("Finished migrating legacy local chat store to native DB");
+};
+
+export const initializeChatStorePersistence = async (chatKey: string) => {
+ if (_chatPersistenceInitKey === chatKey && _chatPersistenceInitPromise) {
+ return _chatPersistenceInitPromise;
+ }
+
+ _chatPersistenceInitKey = chatKey;
+ const initPromise = (async () => {
+ if (isTauriRuntime()) {
+ if (!hasLegacyChatStore() && isNativeMigrationDone()) return;
+ await migrateLegacyChatStoreToNative(chatKey);
+ return;
+ }
+
+ if (!hasLegacyChatStore()) return;
+ await migrateLegacyLocalChatStoreToIndexedDb();
+ })().catch((error) => {
+ if (_chatPersistenceInitPromise === initPromise) {
+ _chatPersistenceInitPromise = undefined;
+ _chatPersistenceInitKey = undefined;
+ }
+ log.error("Failed to initialize chat persistence", error);
+ throw error;
+ });
+
+ _chatPersistenceInitPromise = initPromise;
+ return initPromise;
+};
+
const fetchStore = async () => {
const db = await chatDb();
const [sessions, messages] = await Promise.all([
@@ -1024,65 +1200,58 @@ export const updateMessage = async (
await tx.done;
};
-const BRANCH_SELECTIONS_KEY = "ensu.chat.branchSelections.v1";
+const branchSelectionsKey = (rootSessionUuid: string) =>
+ `ensu.chat.branchSelections.v1.${rootSessionUuid}`;
-type BranchSelectionsStore = Record<string, Record<string, string>>;
+export const getBranchSelections = async (rootSessionUuid: string) => {
+ const stored = await getKV(branchSelectionsKey(rootSessionUuid));
+ if (!stored || typeof stored !== "object") return {};
-const loadBranchSelections = (): BranchSelectionsStore => {
- const json = localStorage.getItem(BRANCH_SELECTIONS_KEY);
- if (!json) return {};
- try {
- const parsed = JSON.parse(json) as BranchSelectionsStore;
- return parsed ?? {};
- } catch (error) {
- log.error("Failed to parse branch selections", error);
- return {};
- }
-};
-
-const saveBranchSelections = (store: BranchSelectionsStore) =>
- localStorage.setItem(BRANCH_SELECTIONS_KEY, JSON.stringify(store));
-
-export const getBranchSelections = (rootSessionUuid: string) => {
- const store = loadBranchSelections();
- return store[rootSessionUuid] ?? {};
+ return Object.fromEntries(
+ Object.entries(stored).filter(
+ (entry): entry is [string, string] =>
+ typeof entry[0] === "string" && typeof entry[1] === "string",
+ ),
+ );
};
export const resetChatStore = async () => {
if (typeof window === "undefined") return;
localStorage.removeItem(STORAGE_KEY);
- localStorage.removeItem(BRANCH_SELECTIONS_KEY);
if (isTauriRuntime()) {
await invokeChat("chat_db_reset");
return;
}
+ try {
+ if (_chatDb) {
+ (await _chatDb).close();
+ }
+ } catch (error) {
+ log.error("Failed to close chat IndexedDB before reset", error);
+ }
_chatDb = undefined;
+ await deleteDB("ensu-chat");
};
-export const setBranchSelection = (
+export const setBranchSelection = async (
rootSessionUuid: string,
selectionKey: string,
selectedMessageUuid: string,
) => {
- const store = loadBranchSelections();
- const selections = store[rootSessionUuid] ?? {};
+ const selections = await getBranchSelections(rootSessionUuid);
selections[selectionKey] = selectedMessageUuid;
- store[rootSessionUuid] = selections;
- saveBranchSelections(store);
+ await setKV(branchSelectionsKey(rootSessionUuid), selections);
};
-export const deleteBranchSelections = (rootSessionUuid: string) => {
- const store = loadBranchSelections();
- delete store[rootSessionUuid];
- saveBranchSelections(store);
-};
+export const deleteBranchSelections = (rootSessionUuid: string) =>
+ removeKV(branchSelectionsKey(rootSessionUuid));
export const deleteSession = async (sessionUuid: string, chatKey: string) => {
if (isTauriRuntime()) {
await deleteSessionNative(sessionUuid, chatKey);
- deleteBranchSelections(sessionUuid);
+ await deleteBranchSelections(sessionUuid);
return;
}
@@ -1110,7 +1279,7 @@ export const deleteSession = async (sessionUuid: string, chatKey: string) => {
);
await tx.done;
- deleteBranchSelections(sessionUuid);
+ await deleteBranchSelections(sessionUuid);
};
let _attachmentDir: Promise<string> | undefined;
@@ -1442,6 +1611,7 @@ export const insertMessageFromRemote = async (
sender: input.sender,
text: input.text,
createdAt: input.createdAt,
+ remoteId: input.remoteId ?? null,
deletedAt: input.deletedAt ?? null,
attachments: input.attachments?.map((attachment) => ({
id: attachment.id,
@@ -1529,7 +1699,7 @@ export const markSessionDeletedAt = async (
sessionUuid,
deletedAt,
});
- deleteBranchSelections(sessionUuid);
+ await deleteBranchSelections(sessionUuid);
return;
}
@@ -1555,7 +1725,7 @@ export const markSessionDeletedAt = async (
);
await tx.done;
- deleteBranchSelections(sessionUuid);
+ await deleteBranchSelections(sessionUuid);
};
export const markMessageDeletedAt = async (
@@ -1707,7 +1877,7 @@ export const hardDeleteEntity = async (
uuid: deletion.uuid,
});
if (deletion.type === "session") {
- deleteBranchSelections(deletion.uuid);
+ await deleteBranchSelections(deletion.uuid);
}
return;
}
@@ -1736,7 +1906,7 @@ export const hardDeleteEntity = async (
),
);
- deleteBranchSelections(deletion.uuid);
+ await deleteBranchSelections(deletion.uuid);
return;
}
diff --git a/web/apps/ensu/src/services/chat/sync.ts b/web/apps/ensu/src/services/chat/sync.ts
index aa48a18f32..77dc08b1e4 100644
--- a/web/apps/ensu/src/services/chat/sync.ts
+++ b/web/apps/ensu/src/services/chat/sync.ts
@@ -4,6 +4,7 @@ import {
ensureOk,
HTTPError,
} from "ente-base/http";
+import { getKV, setKV } from "ente-base/kv";
import log from "ente-base/log";
import { apiOrigin, apiURL } from "ente-base/origins";
import { savedAuthToken } from "ente-base/token";
@@ -241,19 +242,15 @@ export const downloadAttachment = async (attachmentId: string) => {
};
const cursorStorageKey = () => {
- if (typeof localStorage === "undefined") {
- return "ensu.chat.sync.cursor.anon";
- }
const userId = savedLocalUser()?.id ?? "anon";
return `ensu.chat.sync.cursor.${userId}`;
};
-const loadCursor = (): DiffCursor => {
- if (typeof localStorage === "undefined") return { ...DEFAULT_CURSOR };
- const raw = localStorage.getItem(cursorStorageKey());
- if (!raw) return { ...DEFAULT_CURSOR };
+const loadCursor = async (): Promise<DiffCursor> => {
+ const raw = await getKV(cursorStorageKey());
+ if (!raw || typeof raw !== "object") return { ...DEFAULT_CURSOR };
try {
- const parsed = JSON.parse(raw) as Partial<DiffCursor>;
+ const parsed = raw as Partial<DiffCursor>;
return { ...DEFAULT_CURSOR, ...parsed };
} catch (error) {
log.error("Failed to parse chat sync cursor", error);
@@ -261,13 +258,10 @@ const loadCursor = (): DiffCursor => {
}
};
-const saveCursor = (cursor: DiffCursor) => {
- if (typeof localStorage === "undefined") return;
- localStorage.setItem(cursorStorageKey(), JSON.stringify(cursor));
-};
+const saveCursor = (cursor: DiffCursor) => setKV(cursorStorageKey(), cursor);
const pullChat = async (chatKey: string) => {
- let cursor = loadCursor();
+ let cursor = await loadCursor();
let previousCursor = "";
let iterations = 0;
@@ -276,7 +270,7 @@ const pullChat = async (chatKey: string) => {
await applyDiff(response, chatKey);
const nextCursor = normalizeCursor(response);
- saveCursor(nextCursor);
+ await saveCursor(nextCursor);
const serialized = JSON.stringify(nextCursor);
if (serialized === previousCursor) {
log.warn("Chat sync cursor stalled; stopping pull loop");
diff --git a/web/apps/ensu/src/services/secure-storage.ts b/web/apps/ensu/src/services/secure-storage.ts
new file mode 100644
index 0000000000..985fa0f735
--- /dev/null
+++ b/web/apps/ensu/src/services/secure-storage.ts
@@ -0,0 +1,30 @@
+const isTauriRuntime = () =>
+ typeof window !== "undefined" &&
+ ("__TAURI__" in window || "__TAURI_IPC__" in window);
+
+const tauriInvoke = async <T>(
+ command: string,
+ args?: Record<string, unknown>,
+): Promise<T> => {
+ const { invoke } = await import("@tauri-apps/api/tauri");
+ return invoke<T>(command, args);
+};
+
+export const secureStorageGet = async (key: string) => {
+ if (!isTauriRuntime()) return undefined;
+ return tauriInvoke<string | null>("secure_storage_get", { key }).then(
+ (value) => value ?? undefined,
+ );
+};
+
+export const secureStorageSet = async (key: string, value: string) => {
+ if (!isTauriRuntime()) return;
+ await tauriInvoke("secure_storage_set", { key, value });
+};
+
+export const secureStorageDelete = async (key: string) => {
+ if (!isTauriRuntime()) return;
+ await tauriInvoke("secure_storage_delete", { key });
+};
+
+export const isTauriAppRuntime = isTauriRuntime;
diff --git a/web/apps/ensu/src/services/session.ts b/web/apps/ensu/src/services/session.ts
index 7f6df4c874..8b5f1181e8 100644
--- a/web/apps/ensu/src/services/session.ts
+++ b/web/apps/ensu/src/services/session.ts
@@ -1,4 +1,11 @@
+import log from "ente-base/log";
import { ensureCryptoInit, enteWasm } from "./wasm";
+import {
+ isTauriAppRuntime,
+ secureStorageDelete,
+ secureStorageGet,
+ secureStorageSet,
+} from "./secure-storage";
/**
* Session storage key used to store the encrypted master key.
@@ -8,6 +15,8 @@ import { ensureCryptoInit, enteWasm } from "./wasm";
* apps.
*/
const MASTER_KEY_SESSION_KEY = "encryptionKey";
+const MASTER_KEY_SECURE_STORAGE_KEY = "masterKey";
+let _tauriMasterKeyCache: string | undefined;
interface SessionKeyData {
encryptedData: string;
@@ -27,6 +36,24 @@ const sessionKeyData = async (keyDataB64: string): Promise<SessionKeyData> => {
/** Return the decrypted master key (base64) from session storage, if present. */
export const masterKeyFromSession = async (): Promise<string | undefined> => {
+ if (isTauriAppRuntime()) {
+ if (_tauriMasterKeyCache) return _tauriMasterKeyCache;
+ try {
+ const masterKey = await secureStorageGet(
+ MASTER_KEY_SECURE_STORAGE_KEY,
+ );
+ if (masterKey) {
+ _tauriMasterKeyCache = masterKey;
+ return masterKey;
+ }
+ } catch (error) {
+ log.warn(
+ "Failed to read master key from secure storage during session lookup",
+ error,
+ );
+ }
+ }
+
const value = sessionStorage.getItem(MASTER_KEY_SESSION_KEY);
if (!value) return undefined;
@@ -34,11 +61,24 @@ export const masterKeyFromSession = async (): Promise<string | undefined> => {
await ensureCryptoInit();
const wasm = await enteWasm();
- return await wasm.crypto_decrypt_box(encryptedData, nonce, key);
+ const masterKey = await wasm.crypto_decrypt_box(encryptedData, nonce, key);
+ if (isTauriAppRuntime()) {
+ _tauriMasterKeyCache = masterKey;
+ }
+ return masterKey;
};
-/** Save the master key (base64) in session storage. */
+/** Save the master key (base64) in session storage and secure storage on Tauri. */
export const saveMasterKeyInSession = async (masterKeyB64: string) => {
+ if (isTauriAppRuntime()) {
+ _tauriMasterKeyCache = masterKeyB64;
+ try {
+ await secureStorageSet(MASTER_KEY_SECURE_STORAGE_KEY, masterKeyB64);
+ } catch (error) {
+ log.warn("Failed to save master key to secure storage", error);
+ }
+ }
+
sessionStorage.setItem(
MASTER_KEY_SESSION_KEY,
JSON.stringify(await sessionKeyData(masterKeyB64)),
@@ -47,5 +87,34 @@ export const saveMasterKeyInSession = async (masterKeyB64: string) => {
/** Remove the master key from session storage. */
export const clearMasterKeyFromSession = () => {
+ if (isTauriAppRuntime()) {
+ _tauriMasterKeyCache = undefined;
+ }
sessionStorage.removeItem(MASTER_KEY_SESSION_KEY);
};
+
+/** Remove the master key from session storage and Tauri secure storage. */
+export const clearMasterKeyFromEverywhere = async () => {
+ clearMasterKeyFromSession();
+ if (isTauriAppRuntime()) {
+ try {
+ await secureStorageDelete(MASTER_KEY_SECURE_STORAGE_KEY);
+ } catch (error) {
+ log.warn("Failed to delete master key from secure storage", error);
+ }
+ }
+};
+
+/** Hydrate session storage from Tauri secure storage when possible. */
+export const updateSessionFromTauriSecureStorageIfNeeded = async () => {
+ if (!isTauriAppRuntime()) return;
+ if (_tauriMasterKeyCache) return;
+
+ try {
+ const masterKey = await secureStorageGet(MASTER_KEY_SECURE_STORAGE_KEY);
+ if (!masterKey) return;
+ _tauriMasterKeyCache = masterKey;
+ } catch (error) {
+ log.warn("Failed to read master key from secure storage", error);
+ }
+};
diff --git a/web/apps/ensu/src/types/tauri.d.ts b/web/apps/ensu/src/types/tauri.d.ts
index 2c8f4fbe9f..343b760621 100644
--- a/web/apps/ensu/src/types/tauri.d.ts
+++ b/web/apps/ensu/src/types/tauri.d.ts
@@ -27,3 +27,7 @@ declare module "@tauri-apps/api/dialog" {
options?: Record<string, unknown>,
): Promise<string | null>;
}
+
+declare module "@tauri-apps/api/shell" {
+ export function open(path: string): Promise<void>;
+}
diff --git a/web/packages/accounts/services/accounts-db.ts b/web/packages/accounts/services/accounts-db.ts
index a1b6214674..586e933225 100644
--- a/web/packages/accounts/services/accounts-db.ts
+++ b/web/packages/accounts/services/accounts-db.ts
@@ -109,6 +109,21 @@ const LocalUser = z.object({
isTwoFactorEnabled: z.boolean().nullish().transform(nullToUndefined),
});
+const readLocalUserRecord = (): PartialLocalUser | undefined => {
+ const jsonString = localStorage.getItem("user");
+ if (!jsonString) return undefined;
+ return PartialLocalUser.parse(JSON.parse(jsonString));
+};
+
+const writeLocalUserRecord = (user: PartialLocalUser | undefined) => {
+ if (!user || Object.keys(user).length === 0) {
+ localStorage.removeItem("user");
+ return;
+ }
+
+ localStorage.setItem("user", JSON.stringify(user));
+};
+
/**
* Return the local storage value of the user's data.
*
@@ -119,9 +134,8 @@ const LocalUser = z.object({
* Use {@link replaceSavedLocalUser} to updated the saved value.
*/
export const savedPartialLocalUser = (): PartialLocalUser | undefined => {
- const jsonString = localStorage.getItem("user");
- if (!jsonString) return undefined;
- const result = PartialLocalUser.parse(JSON.parse(jsonString));
+ const result = readLocalUserRecord();
+ if (!result) return undefined;
void ensureTokensMatch(result);
return result;
};
@@ -134,8 +148,9 @@ export const savedPartialLocalUser = (): PartialLocalUser | undefined => {
* This method replaces the existing data. Use {@link updateSavedLocalUser} to
* update selected fields while keeping the other fields as it is.
*/
-export const replaceSavedLocalUser = (partialLocalUser: PartialLocalUser) =>
- localStorage.setItem("user", JSON.stringify(partialLocalUser));
+export const replaceSavedLocalUser = (partialLocalUser: PartialLocalUser) => {
+ writeLocalUserRecord(partialLocalUser);
+};
/**
* Partially update the saved user data.
@@ -167,7 +182,6 @@ export const updateSavedLocalUser = (updates: Partial<PartialLocalUser>) =>
export const savedLocalUser = (): LocalUser | undefined => {
const jsonString = localStorage.getItem("user");
if (!jsonString) return undefined;
- // We might have some data, but not all of it. So do a non-throwing parse.
const { success, data } = LocalUser.safeParse(JSON.parse(jsonString));
if (success) void ensureTokensMatch(data);
return success ? data : undefined;
diff --git a/web/packages/base/token.ts b/web/packages/base/token.ts
index 109322b339..2fab35dd9f 100644
--- a/web/packages/base/token.ts
+++ b/web/packages/base/token.ts
@@ -19,24 +19,27 @@ export const ensureAuthToken = async () => {
* The user's auth token is stored in KV DB using {@link saveAuthToken} during
* the login / signup flow. This function returns that saved auth token.
*
- * The underlying data is stored in IndexedDB, and can be accessed from web
- * workers.
- *
* If your code is running in a context where the user is already expected to be
* logged in, use {@link ensureAuthToken} instead.
*/
-export const savedAuthToken = () => getKVS("token");
+export const savedAuthToken = async () => {
+ return getKVS("token");
+};
/**
- * Save the user's auth token in KV DB.
+ * Save the user's auth token.
*
* This is the setter corresponding to {@link savedAuthToken}.
*/
-export const saveAuthToken = (token: string) => setKV("token", token);
+export const saveAuthToken = (token: string) => {
+ return setKV("token", token);
+};
/**
- * Remove the user's auth token from KV DB.
+ * Remove the user's auth token.
*
* See {@link saveAuthToken}.
*/
-export const removeAuthToken = () => removeKV("token");
+export const removeAuthToken = () => {
+ return removeKV("token");
+};