mirror of
https://github.com/Dasemu/Synapse.git
synced 2026-11-26 15:26:17 +00:00
feat: WebAssembly module system and the Secrets vault module
Merged because the PR is ready, mergeable, and all required CI checks pass.
This commit is contained in:
68 files changed
+8077
-109
No files matched your search
@@ -20,6 +20,12 @@ jobs:
|
||||
cargo clippy --workspace --all-targets -- -D warnings
|
||||
- name: Test
|
||||
run: cargo test --workspace
|
||||
- name: Modules (wasm)
|
||||
run: |
|
||||
rustup target add wasm32-unknown-unknown
|
||||
cd modules
|
||||
cargo fmt --all -- --check
|
||||
cargo clippy --target wasm32-unknown-unknown -- -D warnings
|
||||
|
||||
flutter:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
/target
|
||||
/modules/target
|
||||
.env
|
||||
.claude/settings.local.json
|
||||
@@ -16,6 +16,8 @@ and an optional self-hosted sync server. Local-only (standalone graph) or client
|
||||
- Run MCP (stdio): `cargo run -p synapse-mcp -- --graph <copy of a graph> [--allow-write]`
|
||||
- Run app: `cd app && flutter run -d linux` (or `-d windows`, an Android device); Flutter SDK
|
||||
in `~/development/flutter/bin`. Graph dir override: `SYNAPSE_GRAPH=/path`. See `docs/app.md`.
|
||||
- Build bundled modules (WASM, needs `rustup target add wasm32-unknown-unknown`):
|
||||
`scripts/build-modules.sh` (commit the `.wasm` it writes to `app/assets/modules/`)
|
||||
- Regenerate FFI bindings: `cd app && flutter_rust_bridge_codegen generate` (frb 2.13.0; commit
|
||||
the generated Rust and Dart files)
|
||||
|
||||
@@ -29,6 +31,8 @@ roadmap in `docs/plan.md`.
|
||||
- `synapse-history`: automatic git-like snapshots of the graph.
|
||||
- `synapse-caldav`: CalDAV calendar + VTODO tasks.
|
||||
- `synapse-sync` / `synapse-server`: client-server protocol and axum server (`docs/sync.md`).
|
||||
- `synapse-modules`: sandboxed WebAssembly modules (wasmi), permissions, host crypto
|
||||
(`docs/modules.md`); module sources and SDK in `modules/` (own workspace, wasm32 only).
|
||||
- `synapse-mcp`: MCP tools for AI assistants; stdio binary + HTTP service (`docs/mcp.md`).
|
||||
- `synapse-ffi`: the only API surface exposed to Flutter.
|
||||
|
||||
|
||||
Generated
+310
-3
@@ -17,6 +17,16 @@ version = "2.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
|
||||
|
||||
[[package]]
|
||||
name = "aead"
|
||||
version = "0.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1973cfbc1a2daf9cf550e74e1f088c28e7f7d8c1e1418fb6c9dc5184b7e84c99"
|
||||
dependencies = [
|
||||
"crypto-common 0.2.2",
|
||||
"inout",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "aho-corasick"
|
||||
version = "1.1.5"
|
||||
@@ -84,6 +94,18 @@ dependencies = [
|
||||
"rustversion",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "argon2"
|
||||
version = "0.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "134c52ddac6d63c576bef8168db10c83c49c26444ecbc68060fef078925a901c"
|
||||
dependencies = [
|
||||
"base64ct",
|
||||
"blake2",
|
||||
"cpufeatures",
|
||||
"password-hash",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "arrayvec"
|
||||
version = "0.7.8"
|
||||
@@ -208,6 +230,12 @@ version = "0.23.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
|
||||
|
||||
[[package]]
|
||||
name = "base64ct"
|
||||
version = "1.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "1.3.2"
|
||||
@@ -229,6 +257,15 @@ dependencies = [
|
||||
"crunchy",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "blake2"
|
||||
version = "0.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5b5d4d889834ee8ecfc0f8426ad30faf7cdcb10f741a8e6d7224d95325479f6f"
|
||||
dependencies = [
|
||||
"digest 0.11.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "blake3"
|
||||
version = "1.8.7"
|
||||
@@ -251,6 +288,15 @@ dependencies = [
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "block-buffer"
|
||||
version = "0.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"
|
||||
dependencies = [
|
||||
"hybrid-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bon"
|
||||
version = "3.10.2"
|
||||
@@ -350,10 +396,23 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cipher",
|
||||
"cpufeatures",
|
||||
"rand_core 0.10.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "chacha20poly1305"
|
||||
version = "0.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9b89e1c441e926b9c82a8d023f6e1b7ae0adcfaa7d621814e4d60789bac751cb"
|
||||
dependencies = [
|
||||
"aead",
|
||||
"chacha20",
|
||||
"cipher",
|
||||
"poly1305",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "chrono"
|
||||
version = "0.4.45"
|
||||
@@ -378,6 +437,17 @@ dependencies = [
|
||||
"phf",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cipher"
|
||||
version = "0.5.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c"
|
||||
dependencies = [
|
||||
"block-buffer 0.12.1",
|
||||
"crypto-common 0.2.2",
|
||||
"inout",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clru"
|
||||
version = "0.6.3"
|
||||
@@ -387,6 +457,12 @@ dependencies = [
|
||||
"hashbrown 0.16.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cmov"
|
||||
version = "0.5.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a"
|
||||
|
||||
[[package]]
|
||||
name = "combine"
|
||||
version = "4.6.9"
|
||||
@@ -503,6 +579,26 @@ dependencies = [
|
||||
"typenum",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crypto-common"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
|
||||
dependencies = [
|
||||
"getrandom 0.4.3",
|
||||
"hybrid-array",
|
||||
"rand_core 0.10.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ctutils"
|
||||
version = "0.4.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fe3e9d21d39e6f39ff46e03d5b621424f88ee23d8a1672c6bfc9ccc7f2da4f6a"
|
||||
dependencies = [
|
||||
"cmov",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "darling"
|
||||
version = "0.24.1"
|
||||
@@ -643,8 +739,19 @@ version = "0.10.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
|
||||
dependencies = [
|
||||
"block-buffer",
|
||||
"crypto-common",
|
||||
"block-buffer 0.10.4",
|
||||
"crypto-common 0.1.7",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "digest"
|
||||
version = "0.11.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
|
||||
dependencies = [
|
||||
"block-buffer 0.12.1",
|
||||
"crypto-common 0.2.2",
|
||||
"ctutils",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1766,6 +1873,15 @@ version = "1.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
|
||||
|
||||
[[package]]
|
||||
name = "hybrid-array"
|
||||
version = "0.4.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17"
|
||||
dependencies = [
|
||||
"typenum",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hyper"
|
||||
version = "1.12.0"
|
||||
@@ -1983,6 +2099,15 @@ dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "inout"
|
||||
version = "0.2.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3b5cf4372d022092674a83b8febf5865f7a573cc0c5baec5e49c879b6a20978f"
|
||||
dependencies = [
|
||||
"hybrid-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ipnet"
|
||||
version = "2.12.2"
|
||||
@@ -2124,6 +2249,12 @@ version = "1.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb"
|
||||
|
||||
[[package]]
|
||||
name = "leb128fmt"
|
||||
version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2"
|
||||
|
||||
[[package]]
|
||||
name = "levenshtein_automata"
|
||||
version = "0.2.1"
|
||||
@@ -2223,7 +2354,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"digest",
|
||||
"digest 0.10.7",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2425,6 +2556,16 @@ dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "password-hash"
|
||||
version = "0.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "aab41826031698d6ffcd9cff78ef56ef998e39dc7e5067cdfebe373842d4723b"
|
||||
dependencies = [
|
||||
"getrandom 0.4.3",
|
||||
"phc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pastey"
|
||||
version = "0.2.3"
|
||||
@@ -2437,6 +2578,17 @@ version = "2.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
|
||||
|
||||
[[package]]
|
||||
name = "phc"
|
||||
version = "0.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "44dc769b75f93afdddd8c7fa12d685292ddeff1e66f7f0f3a234cf1818afe892"
|
||||
dependencies = [
|
||||
"base64ct",
|
||||
"ctutils",
|
||||
"getrandom 0.4.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "phf"
|
||||
version = "0.12.1"
|
||||
@@ -2467,6 +2619,16 @@ version = "0.3.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
|
||||
|
||||
[[package]]
|
||||
name = "poly1305"
|
||||
version = "0.9.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6e2d0073b297041425c7c3df6eb4792d598a15323fe63346852b092eca02904c"
|
||||
dependencies = [
|
||||
"cpufeatures",
|
||||
"universal-hash",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "portable-atomic"
|
||||
version = "1.15.0"
|
||||
@@ -3315,6 +3477,12 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "spin"
|
||||
version = "0.9.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e"
|
||||
|
||||
[[package]]
|
||||
name = "sse-stream"
|
||||
version = "0.2.6"
|
||||
@@ -3334,6 +3502,16 @@ version = "1.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
|
||||
|
||||
[[package]]
|
||||
name = "string-interner"
|
||||
version = "0.19.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "23de088478b31c349c9ba67816fa55d9355232d63c3afea8bf513e31f0f1d2c0"
|
||||
dependencies = [
|
||||
"hashbrown 0.15.5",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "strsim"
|
||||
version = "0.11.1"
|
||||
@@ -3431,7 +3609,9 @@ dependencies = [
|
||||
"anyhow",
|
||||
"chrono",
|
||||
"flutter_rust_bridge",
|
||||
"serde_json",
|
||||
"synapse-core",
|
||||
"synapse-modules",
|
||||
"tempfile",
|
||||
"uuid",
|
||||
]
|
||||
@@ -3482,6 +3662,24 @@ dependencies = [
|
||||
"uuid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "synapse-modules"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"argon2",
|
||||
"base64 0.22.1",
|
||||
"chacha20poly1305",
|
||||
"getrandom 0.4.3",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"synapse-core",
|
||||
"tempfile",
|
||||
"thiserror",
|
||||
"wasmi",
|
||||
"wat",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "synapse-search"
|
||||
version = "0.1.0"
|
||||
@@ -4016,6 +4214,22 @@ dependencies = [
|
||||
"tinyvec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-width"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"
|
||||
|
||||
[[package]]
|
||||
name = "universal-hash"
|
||||
version = "0.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f4987bdc12753382e0bec4a65c50738ffaabc998b9cdd1f952fb5f39b0048a96"
|
||||
dependencies = [
|
||||
"crypto-common 0.2.2",
|
||||
"ctutils",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "untrusted"
|
||||
version = "0.9.0"
|
||||
@@ -4192,6 +4406,16 @@ dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-encoder"
|
||||
version = "0.262.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4495a6f85dd94c411c749303efcbc5defade0b0cbdbc0541495241ab917a9b5a"
|
||||
dependencies = [
|
||||
"leb128fmt",
|
||||
"wasmparser 0.262.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-streams"
|
||||
version = "0.4.2"
|
||||
@@ -4218,6 +4442,89 @@ dependencies = [
|
||||
"web-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasmi"
|
||||
version = "2.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "78693fcdd618e0fc34af59c6b8efa9ac5d58c68df940beff4bedddb6acfe7c27"
|
||||
dependencies = [
|
||||
"spin",
|
||||
"wasmi_collections",
|
||||
"wasmi_core",
|
||||
"wasmi_ir",
|
||||
"wasmparser 0.228.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasmi_collections"
|
||||
version = "2.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8a8be2aa467cf2d29e96ff759472c36eeb44a3c81c67fc9cb76c9a24c519c557"
|
||||
dependencies = [
|
||||
"string-interner",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasmi_core"
|
||||
version = "2.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "69372d5fda3ea3d1e0aa6603c7888110e0187e88ea17cd8fc2e2df0a0e1f37fa"
|
||||
dependencies = [
|
||||
"libm",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasmi_ir"
|
||||
version = "2.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8f17b774caa13c618c7244f1ee51fe23c5e7b8538a471fa46d9949779758aed6"
|
||||
dependencies = [
|
||||
"wasmi_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasmparser"
|
||||
version = "0.228.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4abf1132c1fdf747d56bbc1bb52152400c70f336870f968b85e89ea422198ae3"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"indexmap",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasmparser"
|
||||
version = "0.262.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "974d643b125b272607e2fff8012ea14a8328acd7621e4bafa7afb32500052b1b"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"indexmap",
|
||||
"semver",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wast"
|
||||
version = "262.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "30612a0c29249b5f185888a107e8a519d920226b7d07f9d351fd094e9f75eb23"
|
||||
dependencies = [
|
||||
"bumpalo",
|
||||
"leb128fmt",
|
||||
"memchr",
|
||||
"unicode-width",
|
||||
"wasm-encoder",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wat"
|
||||
version = "1.262.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e228027f2b07bbaf946980ebbe2437fca73be6f54c40c2a8d4f42f277075f8d1"
|
||||
dependencies = [
|
||||
"wast",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "web-sys"
|
||||
version = "0.3.106"
|
||||
|
||||
@@ -7,6 +7,9 @@ Recurring mistakes and how to avoid them. Add an entry when a mistake repeats.
|
||||
`dart analyze` locally; CI paths are ASCII so `flutter analyze` is fine there.
|
||||
- Generated FFI types share a namespace with Flutter widgets in Dart: avoid DTO names such as
|
||||
`PageView`, `Page`, `Route` in `synapse-ffi`.
|
||||
- wasmi 2's default tail-call dispatch overflowed the stack in debug test builds (an
|
||||
infinite-loop module crashed the process instead of running out of fuel). `synapse-modules`
|
||||
uses `portable-dispatch`; keep it, and keep the runaway-module test.
|
||||
- Fedora's packaged `cargo`/`rust` (in `/usr/bin`) shadows rustup's toolchain in some shells;
|
||||
mixing them breaks `target/` with E0514 ("compiled by an incompatible version of rustc").
|
||||
Prefix commands with `PATH="$HOME/.cargo/bin:$PATH"` (the Stop hook already does) and check
|
||||
|
||||
Executable
BIN
Binary file not shown.
+16
-1
@@ -19,10 +19,25 @@ class _SynapseAppState extends State<SynapseApp> {
|
||||
late final AppState _state =
|
||||
AppState(widget.backend, settings: widget.settings)
|
||||
..loadRecent()
|
||||
..loadTypeIcons();
|
||||
..loadTypeIcons()
|
||||
..modules.load();
|
||||
|
||||
/// Modules lock what they hold (the secrets vault) when the app is hidden (minimised,
|
||||
/// another app in front) or paused.
|
||||
late final _lifecycle = AppLifecycleListener(
|
||||
onHide: () => _state.modules.suspend(),
|
||||
onPause: () => _state.modules.suspend(),
|
||||
);
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_lifecycle;
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_lifecycle.dispose();
|
||||
_state.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import '../graph/graph_model.dart';
|
||||
@@ -133,6 +134,31 @@ abstract class GraphBackend {
|
||||
Float32List weights, {
|
||||
Float32List? initial,
|
||||
});
|
||||
// Modules: sandboxed WebAssembly extensions (docs/modules.md).
|
||||
Future<List<ModuleDto>> modules();
|
||||
|
||||
/// Reads a module file without installing it (manifest, for the consent dialog).
|
||||
Future<ModuleDto> inspectModule(Uint8List wasm);
|
||||
|
||||
/// Installs or updates a module; [granted] must list every permission it asks for.
|
||||
Future<ModuleDto> installModule(Uint8List wasm, List<String> granted);
|
||||
Future<void> setModuleEnabled(String id, bool enabled);
|
||||
|
||||
/// Removes a module from this device; [deleteData] also deletes its synced data.
|
||||
Future<void> uninstallModule(String id, {bool deleteData = false});
|
||||
|
||||
/// Sends a request to a module and returns its decoded JSON response.
|
||||
Future<Map<String, dynamic>> moduleCall(
|
||||
String id,
|
||||
Map<String, dynamic> request,
|
||||
);
|
||||
|
||||
/// Drops a module's running instance (its in-memory state, e.g. unlocked keys).
|
||||
Future<void> stopModule(String id);
|
||||
|
||||
/// Whether the graph already holds data for module [id] (synced or left by an earlier
|
||||
/// install); a module installed under that id can read it.
|
||||
Future<bool> moduleHasData(String id);
|
||||
}
|
||||
|
||||
class _FfiLayout implements LayoutEngine {
|
||||
@@ -362,4 +388,33 @@ class FfiGraphBackend implements GraphBackend {
|
||||
initial: initial,
|
||||
),
|
||||
);
|
||||
|
||||
@override
|
||||
Future<List<ModuleDto>> modules() => _g.modules();
|
||||
@override
|
||||
Future<ModuleDto> inspectModule(Uint8List wasm) =>
|
||||
_g.inspectModule(wasm: wasm);
|
||||
@override
|
||||
Future<ModuleDto> installModule(Uint8List wasm, List<String> granted) =>
|
||||
_g.installModule(wasm: wasm, granted: granted);
|
||||
@override
|
||||
Future<void> setModuleEnabled(String id, bool enabled) =>
|
||||
_g.setModuleEnabled(id: id, enabled: enabled);
|
||||
@override
|
||||
Future<void> uninstallModule(String id, {bool deleteData = false}) =>
|
||||
_g.uninstallModule(id: id, deleteData: deleteData);
|
||||
@override
|
||||
Future<Map<String, dynamic>> moduleCall(
|
||||
String id,
|
||||
Map<String, dynamic> request,
|
||||
) async {
|
||||
final out = await _g.moduleCall(id: id, request: jsonEncode(request));
|
||||
final v = jsonDecode(out);
|
||||
return v is Map<String, dynamic> ? v : {'error': 'bad response'};
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> stopModule(String id) => _g.stopModule(id: id);
|
||||
@override
|
||||
Future<bool> moduleHasData(String id) => _g.moduleHasData(id: id);
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import '../state/outline_ops.dart';
|
||||
import '../theme/theme.dart';
|
||||
import 'completion.dart';
|
||||
import 'markdown.dart';
|
||||
import '../widgets/module_ui.dart';
|
||||
|
||||
const indentWidth = 24.0;
|
||||
const _gutter = 18.0;
|
||||
@@ -323,6 +324,12 @@ class _BlockViewState extends State<BlockView> {
|
||||
onBlockRefNewTab: (r) => app.openIdInNewTab(r.pageId),
|
||||
onUrl: openUrl,
|
||||
onToggleTodo: () => widget.controller.cycleTodo(widget.node),
|
||||
macro: (name, args) {
|
||||
final id = app.modules.macroOwner(name);
|
||||
return id == null
|
||||
? null
|
||||
: ModuleMacro(moduleId: id, name: name.toLowerCase(), args: args);
|
||||
},
|
||||
maxWidth: width,
|
||||
);
|
||||
_renderedFor = content;
|
||||
@@ -347,6 +354,8 @@ class _BlockViewState extends State<BlockView> {
|
||||
Widget build(BuildContext context) {
|
||||
final app = AppScope.read(context);
|
||||
final hasRef = widget.node.content.contains('((');
|
||||
// Module macros appear (or go) as modules are installed, enabled or disabled.
|
||||
final hasMacro = widget.node.content.contains('{{');
|
||||
Widget build(double width) {
|
||||
final r = _render(context, width);
|
||||
return Text.rich(r.span, key: _key);
|
||||
@@ -362,9 +371,12 @@ class _BlockViewState extends State<BlockView> {
|
||||
constraints: const BoxConstraints(
|
||||
minHeight: blockFontSize * blockLineHeight,
|
||||
),
|
||||
child: hasRef
|
||||
child: hasRef || hasMacro
|
||||
? ListenableBuilder(
|
||||
listenable: app.refs,
|
||||
listenable: Listenable.merge([
|
||||
app.refs,
|
||||
if (hasMacro) app.modules,
|
||||
]),
|
||||
builder: (context, _) {
|
||||
_renderedFor = null;
|
||||
return build(box.maxWidth);
|
||||
|
||||
@@ -67,6 +67,7 @@ class RenderContext {
|
||||
this.onToggleTodo,
|
||||
this.onPageNewTab,
|
||||
this.onBlockRefNewTab,
|
||||
this.macro,
|
||||
this.maxWidth = 600,
|
||||
});
|
||||
|
||||
@@ -82,6 +83,9 @@ class RenderContext {
|
||||
/// Middle-click on a page link or block ref.
|
||||
final void Function(String title)? onPageNewTab;
|
||||
final void Function(BlockRefDtoLike ref)? onBlockRefNewTab;
|
||||
|
||||
/// Widget for a `{{name args}}` macro a module renders; null leaves it as text.
|
||||
final Widget? Function(String name, String args)? macro;
|
||||
final double maxWidth;
|
||||
}
|
||||
|
||||
@@ -100,6 +104,7 @@ final _heading = RegExp(r'^(#{1,6}) ');
|
||||
final _uuid = RegExp(
|
||||
r'^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$',
|
||||
);
|
||||
final _macro = RegExp(r'^\s*([a-z0-9_-]+)(?:\s+([^{}]*))?$');
|
||||
final _property = RegExp(r'^([A-Za-z0-9_\-]+):: ?(.*)$');
|
||||
|
||||
/// Renders Synapse outline Markdown of one block into a single [InlineSpan] tree.
|
||||
@@ -312,6 +317,23 @@ class BlockRenderer {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
// {{name args}}: a macro rendered by a module
|
||||
if (ctx.macro != null && s.startsWith('{{', i)) {
|
||||
final j = s.indexOf('}}', i + 2);
|
||||
final m = j < 0 ? null : _macro.firstMatch(s.substring(i + 2, j));
|
||||
final w = m == null ? null : ctx.macro!(m[1]!, (m[2] ?? '').trim());
|
||||
if (w != null) {
|
||||
flush(i);
|
||||
_atomic(
|
||||
WidgetSpan(alignment: PlaceholderAlignment.middle, child: w),
|
||||
1,
|
||||
off + i,
|
||||
j + 2 - i,
|
||||
);
|
||||
i = plain = j + 2;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
// ((block ref))
|
||||
if (s.startsWith('((', i)) {
|
||||
final j = s.indexOf('))', i + 2);
|
||||
|
||||
@@ -7,8 +7,8 @@ import '../frb_generated.dart';
|
||||
|
||||
import 'package:flutter_rust_bridge/flutter_rust_bridge_for_generated.dart';
|
||||
|
||||
// These functions are ignored because they are not marked as `pub`: `new`
|
||||
// These function are ignored because they are on traits that is not defined in current crate (put an empty `#[frb]` on it to unignore): `assert_fields_are_eq`, `assert_fields_are_eq`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `from`, `from`, `from`
|
||||
// These functions are ignored because they are not marked as `pub`: `new`, `new`
|
||||
// These function are ignored because they are on traits that is not defined in current crate (put an empty `#[frb]` on it to unignore): `assert_fields_are_eq`, `assert_fields_are_eq`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `from`, `from`, `from`
|
||||
|
||||
class AssetDto {
|
||||
final String hash;
|
||||
@@ -505,6 +505,95 @@ class LegacyCandidate {
|
||||
preselected == other.preselected;
|
||||
}
|
||||
|
||||
/// An installed (or inspected) module.
|
||||
class ModuleDto {
|
||||
final String id;
|
||||
final String name;
|
||||
final String version;
|
||||
final String description;
|
||||
final String author;
|
||||
|
||||
/// `storage`, `crypto`, `clipboard`, `pages:read`, `pages:write`.
|
||||
final List<String> permissions;
|
||||
final List<ModuleViewDto> views;
|
||||
|
||||
/// Block macros (`{{name args}}`) it renders.
|
||||
final List<String> macros;
|
||||
|
||||
/// How often the app sends it a `tick` request, if at all.
|
||||
final int? tickSeconds;
|
||||
final bool enabled;
|
||||
|
||||
/// Size of the module file in bytes.
|
||||
final BigInt size;
|
||||
|
||||
const ModuleDto({
|
||||
required this.id,
|
||||
required this.name,
|
||||
required this.version,
|
||||
required this.description,
|
||||
required this.author,
|
||||
required this.permissions,
|
||||
required this.views,
|
||||
required this.macros,
|
||||
this.tickSeconds,
|
||||
required this.enabled,
|
||||
required this.size,
|
||||
});
|
||||
|
||||
@override
|
||||
int get hashCode =>
|
||||
id.hashCode ^
|
||||
name.hashCode ^
|
||||
version.hashCode ^
|
||||
description.hashCode ^
|
||||
author.hashCode ^
|
||||
permissions.hashCode ^
|
||||
views.hashCode ^
|
||||
macros.hashCode ^
|
||||
tickSeconds.hashCode ^
|
||||
enabled.hashCode ^
|
||||
size.hashCode;
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) =>
|
||||
identical(this, other) ||
|
||||
other is ModuleDto &&
|
||||
runtimeType == other.runtimeType &&
|
||||
id == other.id &&
|
||||
name == other.name &&
|
||||
version == other.version &&
|
||||
description == other.description &&
|
||||
author == other.author &&
|
||||
permissions == other.permissions &&
|
||||
views == other.views &&
|
||||
macros == other.macros &&
|
||||
tickSeconds == other.tickSeconds &&
|
||||
enabled == other.enabled &&
|
||||
size == other.size;
|
||||
}
|
||||
|
||||
/// A view a module adds to the sidebar.
|
||||
class ModuleViewDto {
|
||||
final String id;
|
||||
final String title;
|
||||
final String? icon;
|
||||
|
||||
const ModuleViewDto({required this.id, required this.title, this.icon});
|
||||
|
||||
@override
|
||||
int get hashCode => id.hashCode ^ title.hashCode ^ icon.hashCode;
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) =>
|
||||
identical(this, other) ||
|
||||
other is ModuleViewDto &&
|
||||
runtimeType == other.runtimeType &&
|
||||
id == other.id &&
|
||||
title == other.title &&
|
||||
icon == other.icon;
|
||||
}
|
||||
|
||||
/// A level of a namespace (`A/B` under `A`); `id` is `None` when only deeper pages exist.
|
||||
class NamespaceEntry {
|
||||
final String title;
|
||||
|
||||
@@ -92,6 +92,15 @@ abstract class SynapseGraph implements RustOpaqueInterface {
|
||||
required String content,
|
||||
});
|
||||
|
||||
/// Reads and validates a module file without installing it (for the consent dialog).
|
||||
Future<ModuleDto> inspectModule({required List<int> wasm});
|
||||
|
||||
/// Installs or updates a module; `granted` must list every permission it asks for.
|
||||
Future<ModuleDto> installModule({
|
||||
required List<int> wasm,
|
||||
required List<String> granted,
|
||||
});
|
||||
|
||||
/// The journal of `date` (created if missing).
|
||||
Future<PageData> journal({required String date});
|
||||
|
||||
@@ -120,6 +129,16 @@ abstract class SynapseGraph implements RustOpaqueInterface {
|
||||
/// block's slot when `into` is its parent, otherwise they become last children of `into`.
|
||||
Future<List<BlockDto>> mergeBlock({required String id, required String into});
|
||||
|
||||
/// Sends a JSON request to a module and returns its JSON response.
|
||||
Future<String> moduleCall({required String id, required String request});
|
||||
|
||||
/// Whether the graph already holds data for module `id` (a module installed under that id
|
||||
/// can read it; the consent dialog warns about it).
|
||||
Future<bool> moduleHasData({required String id});
|
||||
|
||||
/// Installed modules, by name.
|
||||
Future<List<ModuleDto>> modules();
|
||||
|
||||
/// Moves a block with its subtree (drag and drop), possibly to another page.
|
||||
Future<List<BlockDto>> moveBlock({
|
||||
required String id,
|
||||
@@ -218,6 +237,8 @@ abstract class SynapseGraph implements RustOpaqueInterface {
|
||||
required String description,
|
||||
});
|
||||
|
||||
Future<void> setModuleEnabled({required String id, required bool enabled});
|
||||
|
||||
/// Replaces the tags of a page (names only, stored sorted). Journals and templates cannot
|
||||
/// be tagged.
|
||||
Future<PageDto> setPageTags({
|
||||
@@ -232,6 +253,9 @@ abstract class SynapseGraph implements RustOpaqueInterface {
|
||||
/// Sets (or with `None` clears) the emoji of a type, defining the type if needed.
|
||||
Future<void> setTypeIcon({required String name, String? icon});
|
||||
|
||||
/// Stops a module's running instance (dropping its in-memory state).
|
||||
Future<void> stopModule({required String id});
|
||||
|
||||
/// Every tag in use (listed or implied by a type) with its number of pages, most used first.
|
||||
Future<List<TagDto>> tagCatalog();
|
||||
|
||||
@@ -245,6 +269,10 @@ abstract class SynapseGraph implements RustOpaqueInterface {
|
||||
/// not used yet; each with its icon.
|
||||
Future<List<TagDto>> typeCatalog();
|
||||
|
||||
/// Removes a module from this device; `delete_data` also deletes its synced data on every
|
||||
/// device.
|
||||
Future<void> uninstallModule({required String id, required bool deleteData});
|
||||
|
||||
/// Replaces a block's Markdown (the debounced save while typing).
|
||||
Future<void> updateBlock({required String id, required String content});
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -160,6 +160,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
|
||||
@protected
|
||||
List<LegacyCandidate> dco_decode_list_legacy_candidate(dynamic raw);
|
||||
|
||||
@protected
|
||||
List<ModuleDto> dco_decode_list_module_dto(dynamic raw);
|
||||
|
||||
@protected
|
||||
List<ModuleViewDto> dco_decode_list_module_view_dto(dynamic raw);
|
||||
|
||||
@protected
|
||||
List<NamespaceEntry> dco_decode_list_namespace_entry(dynamic raw);
|
||||
|
||||
@@ -202,6 +208,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
|
||||
@protected
|
||||
List<TitleHit> dco_decode_list_title_hit(dynamic raw);
|
||||
|
||||
@protected
|
||||
ModuleDto dco_decode_module_dto(dynamic raw);
|
||||
|
||||
@protected
|
||||
ModuleViewDto dco_decode_module_view_dto(dynamic raw);
|
||||
|
||||
@protected
|
||||
NamespaceEntry dco_decode_namespace_entry(dynamic raw);
|
||||
|
||||
@@ -406,6 +418,14 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
|
||||
SseDeserializer deserializer,
|
||||
);
|
||||
|
||||
@protected
|
||||
List<ModuleDto> sse_decode_list_module_dto(SseDeserializer deserializer);
|
||||
|
||||
@protected
|
||||
List<ModuleViewDto> sse_decode_list_module_view_dto(
|
||||
SseDeserializer deserializer,
|
||||
);
|
||||
|
||||
@protected
|
||||
List<NamespaceEntry> sse_decode_list_namespace_entry(
|
||||
SseDeserializer deserializer,
|
||||
@@ -452,6 +472,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
|
||||
@protected
|
||||
List<TitleHit> sse_decode_list_title_hit(SseDeserializer deserializer);
|
||||
|
||||
@protected
|
||||
ModuleDto sse_decode_module_dto(SseDeserializer deserializer);
|
||||
|
||||
@protected
|
||||
ModuleViewDto sse_decode_module_view_dto(SseDeserializer deserializer);
|
||||
|
||||
@protected
|
||||
NamespaceEntry sse_decode_namespace_entry(SseDeserializer deserializer);
|
||||
|
||||
@@ -683,6 +709,18 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
|
||||
SseSerializer serializer,
|
||||
);
|
||||
|
||||
@protected
|
||||
void sse_encode_list_module_dto(
|
||||
List<ModuleDto> self,
|
||||
SseSerializer serializer,
|
||||
);
|
||||
|
||||
@protected
|
||||
void sse_encode_list_module_view_dto(
|
||||
List<ModuleViewDto> self,
|
||||
SseSerializer serializer,
|
||||
);
|
||||
|
||||
@protected
|
||||
void sse_encode_list_namespace_entry(
|
||||
List<NamespaceEntry> self,
|
||||
@@ -752,6 +790,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
|
||||
@protected
|
||||
void sse_encode_list_title_hit(List<TitleHit> self, SseSerializer serializer);
|
||||
|
||||
@protected
|
||||
void sse_encode_module_dto(ModuleDto self, SseSerializer serializer);
|
||||
|
||||
@protected
|
||||
void sse_encode_module_view_dto(ModuleViewDto self, SseSerializer serializer);
|
||||
|
||||
@protected
|
||||
void sse_encode_namespace_entry(
|
||||
NamespaceEntry self,
|
||||
|
||||
@@ -162,6 +162,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
|
||||
@protected
|
||||
List<LegacyCandidate> dco_decode_list_legacy_candidate(dynamic raw);
|
||||
|
||||
@protected
|
||||
List<ModuleDto> dco_decode_list_module_dto(dynamic raw);
|
||||
|
||||
@protected
|
||||
List<ModuleViewDto> dco_decode_list_module_view_dto(dynamic raw);
|
||||
|
||||
@protected
|
||||
List<NamespaceEntry> dco_decode_list_namespace_entry(dynamic raw);
|
||||
|
||||
@@ -204,6 +210,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
|
||||
@protected
|
||||
List<TitleHit> dco_decode_list_title_hit(dynamic raw);
|
||||
|
||||
@protected
|
||||
ModuleDto dco_decode_module_dto(dynamic raw);
|
||||
|
||||
@protected
|
||||
ModuleViewDto dco_decode_module_view_dto(dynamic raw);
|
||||
|
||||
@protected
|
||||
NamespaceEntry dco_decode_namespace_entry(dynamic raw);
|
||||
|
||||
@@ -408,6 +420,14 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
|
||||
SseDeserializer deserializer,
|
||||
);
|
||||
|
||||
@protected
|
||||
List<ModuleDto> sse_decode_list_module_dto(SseDeserializer deserializer);
|
||||
|
||||
@protected
|
||||
List<ModuleViewDto> sse_decode_list_module_view_dto(
|
||||
SseDeserializer deserializer,
|
||||
);
|
||||
|
||||
@protected
|
||||
List<NamespaceEntry> sse_decode_list_namespace_entry(
|
||||
SseDeserializer deserializer,
|
||||
@@ -454,6 +474,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
|
||||
@protected
|
||||
List<TitleHit> sse_decode_list_title_hit(SseDeserializer deserializer);
|
||||
|
||||
@protected
|
||||
ModuleDto sse_decode_module_dto(SseDeserializer deserializer);
|
||||
|
||||
@protected
|
||||
ModuleViewDto sse_decode_module_view_dto(SseDeserializer deserializer);
|
||||
|
||||
@protected
|
||||
NamespaceEntry sse_decode_namespace_entry(SseDeserializer deserializer);
|
||||
|
||||
@@ -685,6 +711,18 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
|
||||
SseSerializer serializer,
|
||||
);
|
||||
|
||||
@protected
|
||||
void sse_encode_list_module_dto(
|
||||
List<ModuleDto> self,
|
||||
SseSerializer serializer,
|
||||
);
|
||||
|
||||
@protected
|
||||
void sse_encode_list_module_view_dto(
|
||||
List<ModuleViewDto> self,
|
||||
SseSerializer serializer,
|
||||
);
|
||||
|
||||
@protected
|
||||
void sse_encode_list_namespace_entry(
|
||||
List<NamespaceEntry> self,
|
||||
@@ -754,6 +792,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
|
||||
@protected
|
||||
void sse_encode_list_title_hit(List<TitleHit> self, SseSerializer serializer);
|
||||
|
||||
@protected
|
||||
void sse_encode_module_dto(ModuleDto self, SseSerializer serializer);
|
||||
|
||||
@protected
|
||||
void sse_encode_module_view_dto(ModuleViewDto self, SseSerializer serializer);
|
||||
|
||||
@protected
|
||||
void sse_encode_namespace_entry(
|
||||
NamespaceEntry self,
|
||||
|
||||
@@ -9,6 +9,7 @@ import '../graph/network_canvas.dart';
|
||||
import '../theme/theme.dart';
|
||||
import '../widgets/dates.dart';
|
||||
import 'keymap.dart';
|
||||
import 'modules.dart';
|
||||
import 'settings.dart';
|
||||
import 'write_queue.dart';
|
||||
|
||||
@@ -37,6 +38,25 @@ class TagsTypesRoute extends AppRoute {
|
||||
const TagsTypesRoute();
|
||||
}
|
||||
|
||||
/// A view contributed by a module (rendered from the UI tree the module returns).
|
||||
class ModuleRoute extends AppRoute {
|
||||
const ModuleRoute(this.moduleId, this.viewId, {this.title = 'Module'});
|
||||
final String moduleId;
|
||||
final String viewId;
|
||||
|
||||
/// The view's title when it was opened (shown in the tab).
|
||||
final String title;
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) =>
|
||||
other is ModuleRoute &&
|
||||
other.moduleId == moduleId &&
|
||||
other.viewId == viewId;
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(moduleId, viewId);
|
||||
}
|
||||
|
||||
enum GraphMode {
|
||||
network('Network', Icons.hub_outlined),
|
||||
brain('Synapses', Icons.bolt_outlined),
|
||||
@@ -100,6 +120,7 @@ class AppTab {
|
||||
AllPagesRoute() => 'All pages',
|
||||
SettingsRoute() => 'Settings',
|
||||
TagsTypesRoute() => 'Tags & types',
|
||||
ModuleRoute(:final title) => title,
|
||||
TagRoute(:final name) => '#$name',
|
||||
GraphRoute() => 'Graph',
|
||||
PageTarget(:final title) => label ?? title ?? 'Page',
|
||||
@@ -111,6 +132,7 @@ class AppTab {
|
||||
AllPagesRoute() => Icons.description_outlined,
|
||||
SettingsRoute() => Icons.settings_outlined,
|
||||
TagsTypesRoute() => Icons.style_outlined,
|
||||
ModuleRoute() => Icons.extension_outlined,
|
||||
TagRoute() => Icons.sell_outlined,
|
||||
GraphRoute() => Icons.hub_outlined,
|
||||
PageTarget() => Icons.article_outlined,
|
||||
@@ -128,6 +150,12 @@ Map<String, dynamic>? routeToJson(AppRoute r, {String? label}) => switch (r) {
|
||||
AllPagesRoute() => {'t': 'all'},
|
||||
SettingsRoute() => {'t': 'settings'},
|
||||
TagsTypesRoute() => {'t': 'tags-types'},
|
||||
ModuleRoute() => {
|
||||
't': 'module',
|
||||
'id': r.moduleId,
|
||||
'view': r.viewId,
|
||||
'title': r.title,
|
||||
},
|
||||
TagRoute() => {'t': 'tag', 'name': r.name},
|
||||
GraphRoute() => {
|
||||
't': 'graph',
|
||||
@@ -156,6 +184,12 @@ AppRoute? routeFromJson(Object? j) {
|
||||
return const SettingsRoute();
|
||||
case 'tags-types':
|
||||
return const TagsTypesRoute();
|
||||
case 'module':
|
||||
final id = j['id'];
|
||||
final view = j['view'];
|
||||
final title = j['title'];
|
||||
if (id is! String || view is! String) return null;
|
||||
return ModuleRoute(id, view, title: title is String ? title : 'Module');
|
||||
case 'tag':
|
||||
final name = j['name'];
|
||||
return name is String && name.isNotEmpty ? TagRoute(name) : null;
|
||||
@@ -213,6 +247,9 @@ class AppState extends ChangeNotifier {
|
||||
|
||||
final SettingsStore _settings;
|
||||
|
||||
/// Installed modules, their views, macros and effects.
|
||||
late final ModulesController modules = ModulesController(backend);
|
||||
|
||||
/// Key bindings (defaults plus the user's overrides).
|
||||
late final Keymap keymap;
|
||||
|
||||
@@ -666,6 +703,12 @@ class AppState extends ChangeNotifier {
|
||||
void toggleTheme(Brightness current) {
|
||||
setTheme(current == Brightness.dark ? 'paper' : 'paper-dark');
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
modules.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolved `((block refs))`, loaded lazily and shared by every rendered block.
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import '../backend/graph_backend.dart';
|
||||
|
||||
/// What each permission lets a module do, for the install consent dialog.
|
||||
const permissionDescriptions = {
|
||||
'storage': 'Keep its own data in this graph (synced to your other devices)',
|
||||
'crypto': 'Derive keys from passwords and encrypt or decrypt data (keys stay in the app)',
|
||||
'clipboard': 'Copy text to the clipboard (cleared after a delay)',
|
||||
'pages:read': 'Read your pages',
|
||||
'pages:write': 'Create pages and add blocks to them',
|
||||
};
|
||||
|
||||
/// Modules bundled with the app (Flutter assets), offered for installation in Settings.
|
||||
const bundledModules = {
|
||||
'synapse.secrets': (
|
||||
asset: 'assets/modules/synapse.secrets.wasm',
|
||||
name: 'Secrets',
|
||||
description:
|
||||
'An encrypted vault for passwords, unlocked with a master password.',
|
||||
),
|
||||
};
|
||||
|
||||
/// Installed modules and the plumbing around them: sidebar views, block macros, periodic
|
||||
/// ticks, locking on suspend and the effects modules ask for (clipboard, notices).
|
||||
class ModulesController extends ChangeNotifier {
|
||||
ModulesController(this.backend);
|
||||
|
||||
final GraphBackend backend;
|
||||
|
||||
List<ModuleDto> installed = const [];
|
||||
|
||||
/// Bumped when modules ask for their block macros to be redrawn (lock, unlock, edits,
|
||||
/// a tick that changed something). Macro widgets listen to this controller.
|
||||
int macroVersion = 0;
|
||||
|
||||
/// Bumped when a view should re-render (a tick changed the module's state).
|
||||
int viewVersion = 0;
|
||||
|
||||
final _timers = <String, Timer>{};
|
||||
Timer? _clipboardTimer;
|
||||
|
||||
/// Text a module copied with a clear delay, until it is cleared.
|
||||
String? _clipboardSecret;
|
||||
bool _disposed = false;
|
||||
|
||||
Iterable<ModuleDto> get enabled => installed.where((m) => m.enabled);
|
||||
|
||||
/// Module id rendering `{{name ...}}` blocks (the first enabled one claiming it).
|
||||
String? macroOwner(String name) {
|
||||
final n = name.toLowerCase();
|
||||
for (final m in enabled) {
|
||||
if (m.macros.contains(n)) return m.id;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
ModuleDto? byId(String id) {
|
||||
for (final m in installed) {
|
||||
if (m.id == id) return m;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
Future<void> load() async {
|
||||
try {
|
||||
installed = await backend.modules();
|
||||
} catch (_) {
|
||||
installed = const [];
|
||||
}
|
||||
if (_disposed) return;
|
||||
_restartTimers();
|
||||
macroVersion++;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<ModuleDto> inspect(Uint8List wasm) => backend.inspectModule(wasm);
|
||||
|
||||
Future<bool> hasData(String id) async {
|
||||
try {
|
||||
return await backend.moduleHasData(id);
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
Future<ModuleDto> install(Uint8List wasm, List<String> granted) async {
|
||||
final m = await backend.installModule(wasm, granted);
|
||||
await load();
|
||||
return m;
|
||||
}
|
||||
|
||||
Future<void> setEnabled(String id, bool enabled) async {
|
||||
await backend.setModuleEnabled(id, enabled);
|
||||
await load();
|
||||
}
|
||||
|
||||
Future<void> uninstall(String id, {bool deleteData = false}) async {
|
||||
await backend.uninstallModule(id, deleteData: deleteData);
|
||||
await load();
|
||||
}
|
||||
|
||||
/// Sends a request; errors (including a crashed module) come back as `{'error': ...}`.
|
||||
Future<Map<String, dynamic>> call(
|
||||
String id,
|
||||
Map<String, dynamic> request,
|
||||
) async {
|
||||
try {
|
||||
return await backend.moduleCall(id, request);
|
||||
} catch (e) {
|
||||
return {'error': '$e'};
|
||||
}
|
||||
}
|
||||
|
||||
void _restartTimers() {
|
||||
for (final t in _timers.values) {
|
||||
t.cancel();
|
||||
}
|
||||
_timers.clear();
|
||||
for (final m in enabled) {
|
||||
final s = m.tickSeconds;
|
||||
if (s == null || s < 5) continue;
|
||||
_timers[m.id] = Timer.periodic(Duration(seconds: s), (_) => _tick(m.id));
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _tick(String id) async {
|
||||
final r = await call(id, {'op': 'tick'});
|
||||
if (_disposed || r['changed'] != true) return;
|
||||
refresh();
|
||||
}
|
||||
|
||||
/// Redraws module views and macros.
|
||||
void refresh() {
|
||||
macroVersion++;
|
||||
viewVersion++;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/// The app is going to the background: modules lock what they hold (e.g. the vault), and a
|
||||
/// secret still on the clipboard is cleared (a backgrounded app cannot rely on its timer).
|
||||
Future<void> suspend() async {
|
||||
await clearClipboard();
|
||||
var changed = false;
|
||||
for (final m in enabled.toList()) {
|
||||
final r = await call(m.id, {'op': 'suspend'});
|
||||
changed |= r['changed'] == true;
|
||||
}
|
||||
if (changed && !_disposed) refresh();
|
||||
}
|
||||
|
||||
/// Applies the `effects` of a module response. Returns the notices to show and the view to
|
||||
/// open, which need a `BuildContext` (the caller shows them).
|
||||
Future<({List<String> toasts, String? openView})> applyEffects(
|
||||
Map<String, dynamic> response,
|
||||
) async {
|
||||
final toasts = <String>[];
|
||||
String? openView;
|
||||
final effects = response['effects'];
|
||||
if (effects is! List) return (toasts: toasts, openView: openView);
|
||||
for (final e in effects) {
|
||||
if (e is! Map) continue;
|
||||
final copy = e['copy'];
|
||||
if (copy is Map && copy['text'] is String) {
|
||||
final text = copy['text'] as String;
|
||||
await Clipboard.setData(ClipboardData(text: text));
|
||||
final ms = copy['clear_after_ms'];
|
||||
_clipboardTimer?.cancel();
|
||||
_clipboardSecret = null;
|
||||
if (ms is int && ms > 0) {
|
||||
_clipboardSecret = text;
|
||||
_clipboardTimer = Timer(Duration(milliseconds: ms), clearClipboard);
|
||||
}
|
||||
}
|
||||
if (e['toast'] is String) toasts.add(e['toast'] as String);
|
||||
if (e['open_view'] is String) openView = e['open_view'] as String;
|
||||
if (e['refresh_macros'] == true) {
|
||||
macroVersion++;
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
return (toasts: toasts, openView: openView);
|
||||
}
|
||||
|
||||
/// Clears the clipboard if it still holds the secret a module copied (or if it cannot be
|
||||
/// read, as on Android in the background: then clearing is the safe choice).
|
||||
Future<void> clearClipboard() async {
|
||||
final secret = _clipboardSecret;
|
||||
_clipboardTimer?.cancel();
|
||||
_clipboardSecret = null;
|
||||
if (secret == null) return;
|
||||
String? now;
|
||||
var readable = true;
|
||||
try {
|
||||
now = (await Clipboard.getData(Clipboard.kTextPlain))?.text;
|
||||
} catch (_) {
|
||||
readable = false;
|
||||
}
|
||||
if (!readable || now == null || now == secret) {
|
||||
await Clipboard.setData(const ClipboardData(text: ''));
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_disposed = true;
|
||||
for (final t in _timers.values) {
|
||||
t.cancel();
|
||||
}
|
||||
clearClipboard().ignore();
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,441 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../state/app_state.dart';
|
||||
import '../theme/theme.dart';
|
||||
import '../editor/block_row.dart' show openUrl;
|
||||
import '../widgets/common.dart';
|
||||
import '../widgets/module_ui.dart';
|
||||
|
||||
/// A view contributed by a module. The module returns a UI tree (JSON, see
|
||||
/// `docs/modules.md`); buttons, submitted fields and `change` fields send an `event` with the
|
||||
/// current text of every field, and the module answers with the next tree plus effects.
|
||||
class ModuleView extends StatefulWidget {
|
||||
const ModuleView({super.key, required this.moduleId, required this.viewId});
|
||||
|
||||
final String moduleId;
|
||||
final String viewId;
|
||||
|
||||
@override
|
||||
State<ModuleView> createState() => _ModuleViewState();
|
||||
}
|
||||
|
||||
class _ModuleViewState extends State<ModuleView> {
|
||||
Map<String, dynamic>? _tree;
|
||||
String? _error;
|
||||
bool _busy = false;
|
||||
int _viewVersion = -1;
|
||||
|
||||
/// One controller per field id, kept across trees so typing and focus survive re-renders.
|
||||
final _fields = <String, TextEditingController>{};
|
||||
|
||||
/// The value each field had in the last tree (a new value from the module replaces the
|
||||
/// text; an unchanged one keeps what the user typed).
|
||||
final _sent = <String, String>{};
|
||||
final _hidden = <String, bool>{};
|
||||
Timer? _debounce;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_render();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_debounce?.cancel();
|
||||
for (final c in _fields.values) {
|
||||
c.dispose();
|
||||
}
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _render() async {
|
||||
final r = await AppScope.read(context).modules
|
||||
.call(widget.moduleId, {'op': 'render', 'view': widget.viewId});
|
||||
if (mounted) _apply(r);
|
||||
}
|
||||
|
||||
Future<void> _event(String action, {String? arg}) async {
|
||||
if (_busy) return;
|
||||
_debounce?.cancel();
|
||||
setState(() => _busy = true);
|
||||
final r = await AppScope.read(context).modules.call(widget.moduleId, {
|
||||
'op': 'event',
|
||||
'view': widget.viewId,
|
||||
'action': action,
|
||||
'arg': ?arg,
|
||||
'values': {for (final e in _fields.entries) e.key: e.value.text},
|
||||
});
|
||||
if (!mounted) return;
|
||||
setState(() => _busy = false);
|
||||
_apply(r);
|
||||
await applyModuleEffects(context, widget.moduleId, r);
|
||||
}
|
||||
|
||||
void _apply(Map<String, dynamic> r) {
|
||||
setState(() {
|
||||
final ui = r['ui'];
|
||||
if (ui is Map<String, dynamic>) {
|
||||
_tree = ui;
|
||||
_error = null;
|
||||
_syncFields(ui);
|
||||
} else if (r['error'] != null) {
|
||||
_error = '${r['error']}';
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// The `key` of the last tree: a different one is another screen.
|
||||
Object? _screen;
|
||||
|
||||
/// Applies field values from the new tree and drops controllers of fields that are gone.
|
||||
/// On a new screen every field starts from the tree, so text typed on one screen (a
|
||||
/// password) never carries over to a field with the same id on another.
|
||||
void _syncFields(Map<String, dynamic> tree) {
|
||||
if (tree['key'] != _screen) {
|
||||
_screen = tree['key'];
|
||||
_sent.clear();
|
||||
_hidden.clear();
|
||||
}
|
||||
final seen = <String>{};
|
||||
void walk(Object? w) {
|
||||
if (w is List) {
|
||||
w.forEach(walk);
|
||||
return;
|
||||
}
|
||||
if (w is! Map) return;
|
||||
if (w['type'] == 'field' && w['id'] is String) {
|
||||
final id = w['id'] as String;
|
||||
final value = w['value'] is String ? w['value'] as String : '';
|
||||
seen.add(id);
|
||||
final c = _fields.putIfAbsent(id, TextEditingController.new);
|
||||
if (_sent[id] != value) {
|
||||
c.text = value;
|
||||
_sent[id] = value;
|
||||
}
|
||||
}
|
||||
for (final k in const ['children', 'left', 'right', 'items']) {
|
||||
walk(w[k]);
|
||||
}
|
||||
}
|
||||
|
||||
walk(tree);
|
||||
for (final id in _fields.keys.toList()) {
|
||||
if (!seen.contains(id)) {
|
||||
_fields.remove(id)!.dispose();
|
||||
_sent.remove(id);
|
||||
_hidden.remove(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final modules = AppScope.read(context).modules;
|
||||
return ListenableBuilder(
|
||||
listenable: modules,
|
||||
builder: (context, _) {
|
||||
if (_viewVersion != modules.viewVersion) {
|
||||
final first = _viewVersion < 0;
|
||||
_viewVersion = modules.viewVersion;
|
||||
// A tick changed the module's state (auto-lock, a password hidden again).
|
||||
if (!first) scheduleMicrotask(() => mounted ? _render() : null);
|
||||
}
|
||||
final m = modules.byId(widget.moduleId);
|
||||
if (m == null || !m.enabled) {
|
||||
return const Center(
|
||||
child: Text('This module is not installed or is disabled.'),
|
||||
);
|
||||
}
|
||||
return LayoutBuilder(
|
||||
builder: (context, box) {
|
||||
final pad = sidePadding(box.maxWidth);
|
||||
return Stack(
|
||||
children: [
|
||||
SingleChildScrollView(
|
||||
padding: EdgeInsets.fromLTRB(pad, 28, pad, 60),
|
||||
child: _error != null
|
||||
? Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
_error!,
|
||||
style: TextStyle(
|
||||
color: Theme.of(context).colorScheme.error,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
OutlinedButton(
|
||||
onPressed: _render,
|
||||
child: const Text('Retry'),
|
||||
),
|
||||
],
|
||||
)
|
||||
: _tree == null
|
||||
? const SizedBox.shrink()
|
||||
: _widget(context, _tree!),
|
||||
),
|
||||
if (_busy)
|
||||
const Positioned(
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
child: LinearProgressIndicator(minHeight: 2),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
List<Widget> _children(BuildContext context, Object? list) => [
|
||||
if (list is List)
|
||||
for (final c in list)
|
||||
if (c is Map<String, dynamic>) _widget(context, c),
|
||||
];
|
||||
|
||||
Widget _widget(BuildContext context, Map<String, dynamic> w) {
|
||||
final colors = context.colors;
|
||||
String str(String k) => w[k] is String ? w[k] as String : '';
|
||||
switch (w['type']) {
|
||||
case 'column':
|
||||
final kids = _children(context, w['children']);
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
for (var i = 0; i < kids.length; i++) ...[
|
||||
if (i > 0) const SizedBox(height: 12),
|
||||
kids[i],
|
||||
],
|
||||
],
|
||||
);
|
||||
case 'row':
|
||||
final raw = (w['children'] is List ? w['children'] as List : const [])
|
||||
.whereType<Map<String, dynamic>>()
|
||||
.toList();
|
||||
final grows = raw.any(
|
||||
(c) => c['type'] == 'field' || c['type'] == 'pair',
|
||||
);
|
||||
if (!grows) {
|
||||
return Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 8,
|
||||
crossAxisAlignment: WrapCrossAlignment.center,
|
||||
children: [for (final c in raw) _widget(context, c)],
|
||||
);
|
||||
}
|
||||
return Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.center,
|
||||
children: [
|
||||
for (var i = 0; i < raw.length; i++) ...[
|
||||
if (i > 0) const SizedBox(width: 8),
|
||||
raw[i]['type'] == 'field' || raw[i]['type'] == 'pair'
|
||||
? Expanded(child: _widget(context, raw[i]))
|
||||
: _widget(context, raw[i]),
|
||||
],
|
||||
],
|
||||
);
|
||||
case 'split':
|
||||
final left = w['left'] is Map<String, dynamic>
|
||||
? _widget(context, w['left'] as Map<String, dynamic>)
|
||||
: const SizedBox.shrink();
|
||||
final right = w['right'] is Map<String, dynamic>
|
||||
? _widget(context, w['right'] as Map<String, dynamic>)
|
||||
: const SizedBox.shrink();
|
||||
return LayoutBuilder(
|
||||
builder: (context, box) => box.maxWidth < 640
|
||||
? Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [left, const SizedBox(height: 24), right],
|
||||
)
|
||||
: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Expanded(flex: 2, child: left),
|
||||
const SizedBox(width: 28),
|
||||
Expanded(flex: 3, child: right),
|
||||
],
|
||||
),
|
||||
);
|
||||
case 'heading':
|
||||
return Text(
|
||||
str('text'),
|
||||
style: TextStyle(
|
||||
fontFamily: titleFont,
|
||||
fontSize: 22,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: colors.ink,
|
||||
),
|
||||
);
|
||||
case 'text':
|
||||
final style = switch (w['style']) {
|
||||
'muted' => TextStyle(color: colors.muted),
|
||||
'error' => TextStyle(color: Theme.of(context).colorScheme.error),
|
||||
'mono' => TextStyle(fontFamily: monoFont, color: colors.ink),
|
||||
_ => TextStyle(color: colors.ink),
|
||||
};
|
||||
return SelectableText(str('text'), style: style.copyWith(height: 1.4));
|
||||
case 'divider':
|
||||
return Divider(color: colors.line, height: 1);
|
||||
case 'pair':
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
str('label'),
|
||||
style: TextStyle(fontSize: 12, color: colors.muted),
|
||||
),
|
||||
const SizedBox(height: 2),
|
||||
w['link'] == true && _isWebUrl(str('value'))
|
||||
? TextLink(str('value'), onTap: () => openUrl(str('value')))
|
||||
: SelectableText(
|
||||
str('value'),
|
||||
style: TextStyle(
|
||||
color: colors.ink,
|
||||
fontFamily: w['mono'] == true ? monoFont : null,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
case 'field':
|
||||
final id = str('id');
|
||||
final c = _fields.putIfAbsent(id, TextEditingController.new);
|
||||
final secret = w['secret'] == true;
|
||||
final hidden = _hidden[id] ?? true;
|
||||
final submit = w['submit'] is String ? w['submit'] as String : null;
|
||||
final change = w['change'] is String ? w['change'] as String : null;
|
||||
return TextField(
|
||||
key: ValueKey('module-field-$id'),
|
||||
controller: c,
|
||||
autofocus: w['autofocus'] == true,
|
||||
obscureText: secret && hidden,
|
||||
enableSuggestions: !secret,
|
||||
autocorrect: !secret,
|
||||
minLines: w['multiline'] == true ? 3 : 1,
|
||||
maxLines: w['multiline'] == true ? 8 : 1,
|
||||
style: TextStyle(fontFamily: secret && !hidden ? monoFont : null),
|
||||
decoration: InputDecoration(
|
||||
labelText: str('label'),
|
||||
hintText: w['hint'] is String ? w['hint'] as String : null,
|
||||
prefixIcon: moduleIcon(w['icon']) == null
|
||||
? null
|
||||
: Icon(moduleIcon(w['icon']), size: 18),
|
||||
suffixIcon: secret
|
||||
? IconButton(
|
||||
tooltip: hidden ? 'Show' : 'Hide',
|
||||
icon: Icon(
|
||||
hidden
|
||||
? Icons.visibility_outlined
|
||||
: Icons.visibility_off_outlined,
|
||||
size: 18,
|
||||
),
|
||||
onPressed: () => setState(() => _hidden[id] = !hidden),
|
||||
)
|
||||
: null,
|
||||
isDense: true,
|
||||
border: const OutlineInputBorder(),
|
||||
),
|
||||
onSubmitted: submit == null ? null : (_) => _event(submit),
|
||||
onChanged: change == null
|
||||
? null
|
||||
: (_) {
|
||||
_debounce?.cancel();
|
||||
_debounce = Timer(
|
||||
const Duration(milliseconds: 200),
|
||||
() => _event(change),
|
||||
);
|
||||
},
|
||||
);
|
||||
case 'button':
|
||||
final action = str('action');
|
||||
final arg = w['arg'] is String ? w['arg'] as String : null;
|
||||
final icon = moduleIcon(w['icon']);
|
||||
final label = Text(str('label'));
|
||||
final onPressed = _busy ? null : () => _event(action, arg: arg);
|
||||
return switch (w['style']) {
|
||||
'primary' =>
|
||||
icon == null
|
||||
? FilledButton(onPressed: onPressed, child: label)
|
||||
: FilledButton.icon(
|
||||
onPressed: onPressed,
|
||||
icon: Icon(icon, size: 18),
|
||||
label: label,
|
||||
),
|
||||
'danger' => TextButton.icon(
|
||||
style: TextButton.styleFrom(
|
||||
foregroundColor: Theme.of(context).colorScheme.error,
|
||||
),
|
||||
onPressed: onPressed,
|
||||
icon: Icon(icon ?? Icons.warning_amber_outlined, size: 18),
|
||||
label: label,
|
||||
),
|
||||
_ =>
|
||||
icon == null
|
||||
? TextButton(onPressed: onPressed, child: label)
|
||||
: TextButton.icon(
|
||||
onPressed: onPressed,
|
||||
icon: Icon(icon, size: 18),
|
||||
label: label,
|
||||
),
|
||||
};
|
||||
case 'list':
|
||||
final items = _children(context, w['items']);
|
||||
if (items.isEmpty) {
|
||||
return Text(str('empty'), style: TextStyle(color: colors.muted));
|
||||
}
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: items,
|
||||
);
|
||||
case 'item':
|
||||
final action = w['action'] is String ? w['action'] as String : null;
|
||||
final selected = w['selected'] == true;
|
||||
return Material(
|
||||
color: selected ? colors.accentSoft : Colors.transparent,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
child: InkWell(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
onTap: action == null || _busy
|
||||
? null
|
||||
: () => _event(
|
||||
action,
|
||||
arg: w['arg'] is String ? w['arg'] as String : null,
|
||||
),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
str('title'),
|
||||
style: TextStyle(
|
||||
color: colors.ink,
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
),
|
||||
if (str('subtitle').isNotEmpty)
|
||||
Text(
|
||||
str('subtitle'),
|
||||
style: TextStyle(fontSize: 12, color: colors.muted),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
}
|
||||
|
||||
/// Modules may only link to web pages.
|
||||
bool _isWebUrl(String s) {
|
||||
final u = Uri.tryParse(s.trim());
|
||||
return u != null &&
|
||||
(u.scheme == 'http' || u.scheme == 'https') &&
|
||||
u.host.isNotEmpty;
|
||||
}
|
||||
@@ -0,0 +1,453 @@
|
||||
import 'package:file_selector/file_selector.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import '../backend/graph_backend.dart';
|
||||
import '../state/app_state.dart';
|
||||
import '../state/modules.dart';
|
||||
import '../theme/theme.dart';
|
||||
|
||||
/// Picks a module file; replaced in tests.
|
||||
Future<Uint8List?> Function() pickModuleFile = () async {
|
||||
final file = await openFile(
|
||||
acceptedTypeGroups: const [
|
||||
XTypeGroup(label: 'Synapse module', extensions: ['wasm']),
|
||||
],
|
||||
);
|
||||
return file?.readAsBytes();
|
||||
};
|
||||
|
||||
/// Loads a bundled module; replaced in tests.
|
||||
Future<Uint8List> Function(String asset) loadBundledModule = (asset) async =>
|
||||
(await rootBundle.load(asset)).buffer.asUint8List();
|
||||
|
||||
/// Settings section: installed modules (enable, remove), bundled ones and install from file.
|
||||
class ModulesSettings extends StatelessWidget {
|
||||
const ModulesSettings({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final modules = AppScope.read(context).modules;
|
||||
final colors = context.colors;
|
||||
return ListenableBuilder(
|
||||
listenable: modules,
|
||||
builder: (context, _) {
|
||||
final installed = modules.installed;
|
||||
final available = bundledModules.entries
|
||||
.where((e) => installed.every((m) => m.id != e.key))
|
||||
.toList();
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
'Modules',
|
||||
style: Theme.of(context).textTheme.headlineSmall,
|
||||
),
|
||||
),
|
||||
TextButton.icon(
|
||||
key: const ValueKey('module-install-file'),
|
||||
onPressed: () => _installFromFile(context),
|
||||
icon: const Icon(Icons.upload_file_outlined, size: 18),
|
||||
label: const Text('Install from file…'),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
'Modules extend Synapse. Each one runs in a sandbox and can only do what you '
|
||||
'allow when you install it. Installed modules are per device; their data '
|
||||
'syncs with the graph.',
|
||||
style: TextStyle(color: colors.muted),
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
for (final m in installed) _InstalledModule(module: m),
|
||||
for (final e in available)
|
||||
_BundledModule(
|
||||
id: e.key,
|
||||
asset: e.value.asset,
|
||||
name: e.value.name,
|
||||
description: e.value.description,
|
||||
),
|
||||
if (installed.isEmpty && available.isEmpty)
|
||||
Text(
|
||||
'No modules installed.',
|
||||
style: TextStyle(color: colors.muted),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
static Future<void> _installFromFile(BuildContext context) async {
|
||||
final messenger = ScaffoldMessenger.of(context);
|
||||
final Uint8List? bytes;
|
||||
try {
|
||||
bytes = await pickModuleFile();
|
||||
} catch (e) {
|
||||
messenger.showSnackBar(
|
||||
SnackBar(content: Text('Could not read the file: $e')),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (bytes == null || !context.mounted) return;
|
||||
await installModuleBytes(context, bytes);
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the module, asks for consent to its permissions and installs it. Ids starting with
|
||||
/// `synapse.` are reserved for the modules bundled with the app ([bundled]), so a file cannot
|
||||
/// pose as one of them and inherit its data.
|
||||
Future<void> installModuleBytes(
|
||||
BuildContext context,
|
||||
Uint8List bytes, {
|
||||
bool bundled = false,
|
||||
}) async {
|
||||
final modules = AppScope.read(context).modules;
|
||||
final messenger = ScaffoldMessenger.of(context);
|
||||
final ModuleDto m;
|
||||
try {
|
||||
m = await modules.inspect(bytes);
|
||||
} catch (e) {
|
||||
messenger.showSnackBar(
|
||||
SnackBar(content: Text('Not a valid Synapse module: ${_message(e)}')),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (!bundled && m.id.startsWith('synapse.')) {
|
||||
messenger.showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(
|
||||
'${m.id}: ids starting with "synapse." are reserved for modules included '
|
||||
'with Synapse.',
|
||||
),
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
final previous = modules.byId(m.id);
|
||||
final existingData = previous == null && await modules.hasData(m.id);
|
||||
if (!context.mounted) return;
|
||||
final ok = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (ctx) => _ConsentDialog(
|
||||
module: m,
|
||||
previous: previous,
|
||||
existingData: existingData,
|
||||
),
|
||||
);
|
||||
if (ok != true) return;
|
||||
try {
|
||||
await modules.install(bytes, m.permissions);
|
||||
messenger.showSnackBar(
|
||||
SnackBar(content: Text('${m.name} ${m.version} installed.')),
|
||||
);
|
||||
} catch (e) {
|
||||
messenger.showSnackBar(
|
||||
SnackBar(content: Text('Could not install ${m.name}: ${_message(e)}')),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _message(Object e) {
|
||||
final s = '$e';
|
||||
return s.startsWith('Exception: ') ? s.substring(11) : s;
|
||||
}
|
||||
|
||||
class _ConsentDialog extends StatelessWidget {
|
||||
const _ConsentDialog({
|
||||
required this.module,
|
||||
this.previous,
|
||||
this.existingData = false,
|
||||
});
|
||||
final ModuleDto module;
|
||||
final ModuleDto? previous;
|
||||
|
||||
/// The graph already holds data under this module id, which it will be able to read.
|
||||
final bool existingData;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colors = context.colors;
|
||||
final m = module;
|
||||
final update = previous != null;
|
||||
return AlertDialog(
|
||||
title: Text(
|
||||
update
|
||||
? 'Update ${m.name} (${previous!.version} → ${m.version})?'
|
||||
: 'Install ${m.name} ${m.version}?',
|
||||
),
|
||||
content: SizedBox(
|
||||
width: 460,
|
||||
child: SingleChildScrollView(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
if (m.author.isNotEmpty)
|
||||
Text('By ${m.author}', style: TextStyle(color: colors.muted)),
|
||||
if (m.description.isNotEmpty) ...[
|
||||
const SizedBox(height: 8),
|
||||
Text(m.description),
|
||||
],
|
||||
if (existingData) ...[
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
'This graph already holds data of a module with the id ${m.id} '
|
||||
'(from another device or an earlier install). This module will be '
|
||||
'able to read it. Install it only if you trust where it comes from.',
|
||||
style: TextStyle(color: Theme.of(context).colorScheme.error),
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
m.permissions.isEmpty
|
||||
? 'It asks for no permissions.'
|
||||
: 'It will be allowed to:',
|
||||
style: const TextStyle(fontWeight: FontWeight.w600),
|
||||
),
|
||||
for (final p in m.permissions)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 6),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Icon(
|
||||
Icons.check_circle_outline,
|
||||
size: 16,
|
||||
color: colors.accent,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(child: Text(permissionDescriptions[p] ?? p)),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (m.views.isNotEmpty || m.macros.isNotEmpty) ...[
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
[
|
||||
if (m.views.isNotEmpty)
|
||||
'Adds ${m.views.map((v) => v.title).join(', ')} to the sidebar.',
|
||||
if (m.macros.isNotEmpty)
|
||||
'Renders ${m.macros.map((n) => '{{$n …}}').join(', ')} in blocks.',
|
||||
].join(' '),
|
||||
style: TextStyle(color: colors.muted),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context, false),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
FilledButton(
|
||||
key: const ValueKey('module-consent-install'),
|
||||
onPressed: () => Navigator.pop(context, true),
|
||||
child: Text(update ? 'Update' : 'Install'),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _InstalledModule extends StatelessWidget {
|
||||
const _InstalledModule({required this.module});
|
||||
final ModuleDto module;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colors = context.colors;
|
||||
final m = module;
|
||||
final modules = AppScope.read(context).modules;
|
||||
final icon = m.views.isEmpty ? null : m.views.first.icon;
|
||||
return Container(
|
||||
margin: const EdgeInsets.only(bottom: 10),
|
||||
padding: const EdgeInsets.fromLTRB(14, 10, 8, 10),
|
||||
decoration: BoxDecoration(
|
||||
border: Border.all(color: colors.line),
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 2, right: 12),
|
||||
child: icon == null
|
||||
? Icon(Icons.extension_outlined, color: colors.muted)
|
||||
: Text(icon, style: const TextStyle(fontSize: 20)),
|
||||
),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'${m.name} ${m.version}',
|
||||
style: TextStyle(
|
||||
fontWeight: FontWeight.w600,
|
||||
color: colors.ink,
|
||||
),
|
||||
),
|
||||
if (m.description.isNotEmpty)
|
||||
Text(m.description, style: TextStyle(color: colors.muted)),
|
||||
const SizedBox(height: 6),
|
||||
Wrap(
|
||||
spacing: 6,
|
||||
runSpacing: 4,
|
||||
children: [
|
||||
for (final p in m.permissions)
|
||||
Tooltip(
|
||||
message: permissionDescriptions[p] ?? p,
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 7,
|
||||
vertical: 2,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: colors.codeBg,
|
||||
borderRadius: BorderRadius.circular(5),
|
||||
),
|
||||
child: Text(
|
||||
p,
|
||||
style: TextStyle(fontSize: 12, color: colors.muted),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Column(
|
||||
children: [
|
||||
Switch(
|
||||
key: ValueKey('module-enabled-${m.id}'),
|
||||
value: m.enabled,
|
||||
onChanged: (v) => modules.setEnabled(m.id, v),
|
||||
),
|
||||
TextButton(
|
||||
key: ValueKey('module-remove-${m.id}'),
|
||||
onPressed: () => _remove(context),
|
||||
child: const Text('Remove'),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _remove(BuildContext context) async {
|
||||
final modules = AppScope.read(context).modules;
|
||||
var deleteData = false;
|
||||
final ok = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (ctx) => StatefulBuilder(
|
||||
builder: (ctx, setState) => AlertDialog(
|
||||
title: Text('Remove ${module.name}?'),
|
||||
content: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const Text(
|
||||
'It is removed from this device. Its data stays in the graph, so '
|
||||
'installing it again brings it back.',
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
CheckboxListTile(
|
||||
key: const ValueKey('module-remove-data'),
|
||||
contentPadding: EdgeInsets.zero,
|
||||
value: deleteData,
|
||||
onChanged: (v) => setState(() => deleteData = v ?? false),
|
||||
title: const Text(
|
||||
'Also delete its data on every synced device (cannot be undone)',
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(ctx, false),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
FilledButton(
|
||||
key: const ValueKey('module-remove-confirm'),
|
||||
onPressed: () => Navigator.pop(ctx, true),
|
||||
child: const Text('Remove'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
if (ok == true) {
|
||||
await modules.uninstall(module.id, deleteData: deleteData);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class _BundledModule extends StatelessWidget {
|
||||
const _BundledModule({
|
||||
required this.id,
|
||||
required this.asset,
|
||||
required this.name,
|
||||
required this.description,
|
||||
});
|
||||
final String id;
|
||||
final String asset;
|
||||
final String name;
|
||||
final String description;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colors = context.colors;
|
||||
return Container(
|
||||
margin: const EdgeInsets.only(bottom: 10),
|
||||
padding: const EdgeInsets.fromLTRB(14, 10, 8, 10),
|
||||
decoration: BoxDecoration(
|
||||
border: Border.all(color: colors.line),
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(right: 12),
|
||||
child: Icon(Icons.extension_outlined, color: colors.muted),
|
||||
),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
name,
|
||||
style: TextStyle(
|
||||
fontWeight: FontWeight.w600,
|
||||
color: colors.ink,
|
||||
),
|
||||
),
|
||||
Text(
|
||||
'$description Included with Synapse.',
|
||||
style: TextStyle(color: colors.muted),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
FilledButton.tonal(
|
||||
key: ValueKey('module-install-$id'),
|
||||
onPressed: () async {
|
||||
final bytes = await loadBundledModule(asset);
|
||||
if (context.mounted) {
|
||||
await installModuleBytes(context, bytes, bundled: true);
|
||||
}
|
||||
},
|
||||
child: const Text('Install'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -5,9 +5,10 @@ import '../state/app_state.dart';
|
||||
import '../state/keymap.dart';
|
||||
import '../theme/theme.dart';
|
||||
import '../widgets/common.dart';
|
||||
import 'modules_settings.dart';
|
||||
import 'theme_editor.dart';
|
||||
|
||||
/// Theme picker and key bindings.
|
||||
/// Theme picker, modules and key bindings.
|
||||
class SettingsView extends StatelessWidget {
|
||||
const SettingsView({super.key});
|
||||
|
||||
@@ -88,6 +89,8 @@ class SettingsView extends StatelessWidget {
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 36),
|
||||
const ModulesSettings(),
|
||||
const SizedBox(height: 36),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(child: _Heading('Keyboard shortcuts')),
|
||||
|
||||
@@ -9,6 +9,7 @@ import '../theme/theme.dart';
|
||||
import '../widgets/dates.dart';
|
||||
import 'all_pages_view.dart';
|
||||
import 'journals_view.dart';
|
||||
import 'module_view.dart';
|
||||
import 'page_screen.dart';
|
||||
import 'hubs_tree.dart';
|
||||
import 'quick_switcher.dart';
|
||||
@@ -135,6 +136,10 @@ class _ShellState extends State<Shell> {
|
||||
AllPagesRoute() => const AllPagesView(),
|
||||
SettingsRoute() => const SettingsView(),
|
||||
TagsTypesRoute() => const TagsTypesView(),
|
||||
ModuleRoute() => ModuleView(
|
||||
moduleId: route.moduleId,
|
||||
viewId: route.viewId,
|
||||
),
|
||||
TagRoute() => TagView(name: route.name),
|
||||
PageTarget() => PageScreen(target: route),
|
||||
},
|
||||
@@ -333,6 +338,37 @@ class _Sidebar extends StatelessWidget {
|
||||
onTap: () => go(const TagsTypesRoute()),
|
||||
onMiddle: () => newTab(const TagsTypesRoute()),
|
||||
),
|
||||
// Views of enabled modules.
|
||||
ListenableBuilder(
|
||||
listenable: app.modules,
|
||||
builder: (context, _) => Column(
|
||||
children: [
|
||||
for (final m in app.modules.enabled)
|
||||
for (final v in m.views)
|
||||
_NavItem(
|
||||
icon: v.icon == null ? Icons.extension_outlined : null,
|
||||
leading: v.icon == null
|
||||
? null
|
||||
: Padding(
|
||||
padding: const EdgeInsets.only(right: 10),
|
||||
child: Text(
|
||||
v.icon!,
|
||||
style: const TextStyle(fontSize: 14),
|
||||
),
|
||||
),
|
||||
label: v.title,
|
||||
selected:
|
||||
route is ModuleRoute &&
|
||||
route.moduleId == m.id &&
|
||||
route.viewId == v.id,
|
||||
onTap: () =>
|
||||
go(ModuleRoute(m.id, v.id, title: v.title)),
|
||||
onMiddle: () =>
|
||||
newTab(ModuleRoute(m.id, v.id, title: v.title)),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 22),
|
||||
Expanded(
|
||||
child: ListView(
|
||||
|
||||
@@ -6,6 +6,7 @@ import '../editor/block_row.dart';
|
||||
import '../editor/markdown.dart';
|
||||
import '../state/app_state.dart';
|
||||
import '../theme/theme.dart';
|
||||
import 'module_ui.dart';
|
||||
|
||||
/// Max width of the reading column.
|
||||
const contentWidth = 780.0;
|
||||
@@ -120,7 +121,7 @@ class _StaticBlockState extends State<StaticBlock> {
|
||||
final app = AppScope.read(context);
|
||||
return LayoutBuilder(
|
||||
builder: (context, box) => ListenableBuilder(
|
||||
listenable: app.refs,
|
||||
listenable: Listenable.merge([app.refs, app.modules]),
|
||||
builder: (context, _) {
|
||||
_r?.dispose();
|
||||
_r = BlockRenderer(
|
||||
@@ -134,6 +135,16 @@ class _StaticBlockState extends State<StaticBlock> {
|
||||
onPageNewTab: app.openTitleInNewTab,
|
||||
onBlockRefNewTab: (r) => app.openIdInNewTab(r.pageId),
|
||||
onUrl: openUrl,
|
||||
macro: (name, args) {
|
||||
final id = app.modules.macroOwner(name);
|
||||
return id == null
|
||||
? null
|
||||
: ModuleMacro(
|
||||
moduleId: id,
|
||||
name: name.toLowerCase(),
|
||||
args: args,
|
||||
);
|
||||
},
|
||||
maxWidth: box.maxWidth,
|
||||
),
|
||||
).render(widget.content);
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../state/app_state.dart';
|
||||
import '../theme/theme.dart';
|
||||
|
||||
/// Icon names modules may use in buttons and macro actions.
|
||||
IconData? moduleIcon(Object? name) => switch (name) {
|
||||
'add' => Icons.add,
|
||||
'lock' => Icons.lock_outline,
|
||||
'unlock' => Icons.lock_open_outlined,
|
||||
'copy' => Icons.copy_outlined,
|
||||
'eye' => Icons.visibility_outlined,
|
||||
'eye_off' => Icons.visibility_off_outlined,
|
||||
'edit' => Icons.edit_outlined,
|
||||
'delete' => Icons.delete_outline,
|
||||
'key' => Icons.key_outlined,
|
||||
'refresh' => Icons.refresh,
|
||||
'save' => Icons.check,
|
||||
'close' => Icons.close,
|
||||
'search' => Icons.search,
|
||||
'link' => Icons.link,
|
||||
'person' => Icons.person_outline,
|
||||
_ => null,
|
||||
};
|
||||
|
||||
/// Applies a module response's effects: clipboard (through the controller), notices as snack
|
||||
/// bars, and opening one of the module's views.
|
||||
Future<void> applyModuleEffects(
|
||||
BuildContext context,
|
||||
String moduleId,
|
||||
Map<String, dynamic> response,
|
||||
) async {
|
||||
final app = AppScope.read(context);
|
||||
final messenger = ScaffoldMessenger.maybeOf(context);
|
||||
final out = await app.modules.applyEffects(response);
|
||||
for (final t in out.toasts) {
|
||||
messenger?.showSnackBar(SnackBar(content: Text(t)));
|
||||
}
|
||||
final view = out.openView;
|
||||
if (view != null) {
|
||||
final m = app.modules.byId(moduleId);
|
||||
final decl = m?.views.where((v) => v.id == view).firstOrNull;
|
||||
if (decl != null) {
|
||||
app.go(ModuleRoute(moduleId, view, title: decl.title));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A `{{name args}}` macro rendered by a module inside a block: its label, a value (masked or
|
||||
/// not) and action buttons. Redrawn when the module asks (`ModulesController.macroVersion`).
|
||||
class ModuleMacro extends StatefulWidget {
|
||||
const ModuleMacro({
|
||||
super.key,
|
||||
required this.moduleId,
|
||||
required this.name,
|
||||
required this.args,
|
||||
});
|
||||
|
||||
final String moduleId;
|
||||
final String name;
|
||||
final String args;
|
||||
|
||||
@override
|
||||
State<ModuleMacro> createState() => _ModuleMacroState();
|
||||
}
|
||||
|
||||
class _ModuleMacroState extends State<ModuleMacro> {
|
||||
Map<String, dynamic>? _inline;
|
||||
int _version = -1;
|
||||
bool _busy = false;
|
||||
|
||||
Map<String, dynamic> get _request => {
|
||||
'name': widget.name,
|
||||
'args': widget.args,
|
||||
};
|
||||
|
||||
@override
|
||||
void didUpdateWidget(ModuleMacro old) {
|
||||
super.didUpdateWidget(old);
|
||||
if (old.args != widget.args || old.moduleId != widget.moduleId) {
|
||||
_version = -1;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _load(int version) async {
|
||||
_version = version;
|
||||
final r = await AppScope.read(context).modules
|
||||
.call(widget.moduleId, {'op': 'macro', ..._request});
|
||||
if (!mounted) return;
|
||||
setState(() => _inline = _inlineOf(r));
|
||||
}
|
||||
|
||||
Map<String, dynamic> _inlineOf(Map<String, dynamic> r) {
|
||||
final i = r['inline'];
|
||||
if (i is Map<String, dynamic>) return i;
|
||||
return {'text': widget.args, 'error': '${r['error'] ?? 'No answer'}'};
|
||||
}
|
||||
|
||||
Future<void> _action(String id) async {
|
||||
if (_busy) return;
|
||||
setState(() => _busy = true);
|
||||
final r = await AppScope.read(context).modules.call(widget.moduleId, {
|
||||
'op': 'macro_action',
|
||||
'action': id,
|
||||
..._request,
|
||||
});
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_busy = false;
|
||||
_inline = _inlineOf(r);
|
||||
});
|
||||
await applyModuleEffects(context, widget.moduleId, r);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final modules = AppScope.read(context).modules;
|
||||
return ListenableBuilder(
|
||||
listenable: modules,
|
||||
builder: (context, _) {
|
||||
if (_version != modules.macroVersion) {
|
||||
final v = modules.macroVersion;
|
||||
scheduleMicrotask(() {
|
||||
if (mounted && _version != v) _load(v);
|
||||
});
|
||||
}
|
||||
return _chip(context);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _chip(BuildContext context) {
|
||||
final colors = context.colors;
|
||||
final i = _inline;
|
||||
final small = TextStyle(fontSize: 13, color: colors.ink);
|
||||
final children = <Widget>[];
|
||||
if (i == null) {
|
||||
children.add(Text('{{${widget.name} ${widget.args}}}', style: small));
|
||||
} else {
|
||||
final icon = i['icon'];
|
||||
if (icon is String) {
|
||||
children.add(Text(icon, style: const TextStyle(fontSize: 12)));
|
||||
children.add(const SizedBox(width: 5));
|
||||
}
|
||||
children.add(
|
||||
Text(
|
||||
'${i['text'] ?? widget.args}',
|
||||
style: small.copyWith(fontWeight: FontWeight.w600),
|
||||
),
|
||||
);
|
||||
final error = i['error'];
|
||||
final masked = i['masked'];
|
||||
if (error is String) {
|
||||
children.add(const SizedBox(width: 8));
|
||||
children.add(
|
||||
Text(
|
||||
error,
|
||||
style: small.copyWith(color: Theme.of(context).colorScheme.error),
|
||||
),
|
||||
);
|
||||
} else if (masked is String) {
|
||||
children.add(const SizedBox(width: 8));
|
||||
children.add(
|
||||
SelectableText(
|
||||
masked,
|
||||
style: small.copyWith(
|
||||
fontFamily: i['revealed'] == true ? monoFont : null,
|
||||
color: i['revealed'] == true ? colors.ink : colors.muted,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
final actions = i['actions'];
|
||||
if (actions is List) {
|
||||
for (final a in actions) {
|
||||
if (a is! Map || a['id'] is! String) continue;
|
||||
children.add(
|
||||
IconButton(
|
||||
tooltip: a['label'] is String ? a['label'] as String : null,
|
||||
visualDensity: VisualDensity.compact,
|
||||
iconSize: 15,
|
||||
padding: EdgeInsets.zero,
|
||||
constraints: const BoxConstraints.tightFor(width: 26, height: 22),
|
||||
onPressed: _busy ? null : () => _action(a['id'] as String),
|
||||
icon: Icon(moduleIcon(a['icon']) ?? Icons.bolt_outlined),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Taps on the chip must not start editing the block.
|
||||
return GestureDetector(
|
||||
onTapUp: (_) {},
|
||||
behavior: HitTestBehavior.opaque,
|
||||
child: Container(
|
||||
margin: const EdgeInsets.symmetric(horizontal: 1),
|
||||
padding: const EdgeInsets.only(left: 7, right: 3, top: 1, bottom: 1),
|
||||
decoration: BoxDecoration(
|
||||
color: colors.codeBg,
|
||||
border: Border.all(color: colors.line),
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
),
|
||||
child: Row(mainAxisSize: MainAxisSize.min, children: children),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -6,9 +6,13 @@
|
||||
|
||||
#include "generated_plugin_registrant.h"
|
||||
|
||||
#include <file_selector_linux/file_selector_plugin.h>
|
||||
#include <url_launcher_linux/url_launcher_plugin.h>
|
||||
|
||||
void fl_register_plugins(FlPluginRegistry* registry) {
|
||||
g_autoptr(FlPluginRegistrar) file_selector_linux_registrar =
|
||||
fl_plugin_registry_get_registrar_for_plugin(registry, "FileSelectorPlugin");
|
||||
file_selector_plugin_register_with_registrar(file_selector_linux_registrar);
|
||||
g_autoptr(FlPluginRegistrar) url_launcher_linux_registrar =
|
||||
fl_plugin_registry_get_registrar_for_plugin(registry, "UrlLauncherPlugin");
|
||||
url_launcher_plugin_register_with_registrar(url_launcher_linux_registrar);
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
#
|
||||
|
||||
list(APPEND FLUTTER_PLUGIN_LIST
|
||||
file_selector_linux
|
||||
url_launcher_linux
|
||||
)
|
||||
|
||||
|
||||
+89
-1
@@ -65,6 +65,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.19.1"
|
||||
cross_file:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: cross_file
|
||||
sha256: f141ea4f277af142a0356955707f6556f37b03947d39d55585981a06ca437bd6
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.3.5+5"
|
||||
crypto:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -97,6 +105,70 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "7.0.1"
|
||||
file_selector:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: file_selector
|
||||
sha256: bd15e43e9268db636b53eeaca9f56324d1622af30e5c34d6e267649758c84d9a
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.1.0"
|
||||
file_selector_android:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: file_selector_android
|
||||
sha256: d670cd0ce77a2e785b18d8b4d0a8d6a222d6a813ec9b7ddf2790a1b4fb6fa92c
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.5.2+11"
|
||||
file_selector_ios:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: file_selector_ios
|
||||
sha256: "5b42ec0ef7626124b4624ea244341e9df780406793c204e89fa68a2e71af115c"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.5.3+7"
|
||||
file_selector_linux:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: file_selector_linux
|
||||
sha256: da76400e7872ce7637ffdce12749ec24169c25f6195c28372208e65a24bcd2ab
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.9.4+1"
|
||||
file_selector_macos:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: file_selector_macos
|
||||
sha256: d785431f1910aac8a50e5c492cae912320158030a88703c67b9ef7f1f96fd7ba
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.9.5+2"
|
||||
file_selector_platform_interface:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: file_selector_platform_interface
|
||||
sha256: "35e0bd61ebcdb91a3505813b055b09b79dfdc7d0aee9c09a7ba59ae4bb13dc85"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.7.0"
|
||||
file_selector_web:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: file_selector_web
|
||||
sha256: "73181fbc5257776d8ecaa6a94ab3c8e920ad143b9132a6d984a9271dfc6928d3"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.9.5"
|
||||
file_selector_windows:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: file_selector_windows
|
||||
sha256: fbefc5fb92c6d3cbe8d284a2cd971b593bb07d2cd6da8557b81a862250b4acec
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.9.3+6"
|
||||
flutter:
|
||||
dependency: "direct main"
|
||||
description: flutter
|
||||
@@ -146,6 +218,22 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.0.2"
|
||||
http:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: http
|
||||
sha256: "87721a4a50b19c7f1d49001e51409bddc46303966ce89a65af4f4e6004896412"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.6.0"
|
||||
http_parser:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: http_parser
|
||||
sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "4.1.2"
|
||||
integration_test:
|
||||
dependency: "direct dev"
|
||||
description: flutter
|
||||
@@ -541,4 +629,4 @@ packages:
|
||||
version: "3.1.4"
|
||||
sdks:
|
||||
dart: ">=3.13.5 <4.0.0"
|
||||
flutter: ">=3.44.0"
|
||||
flutter: ">=3.47.0"
|
||||
@@ -7,6 +7,7 @@ environment:
|
||||
sdk: ^3.13.5
|
||||
|
||||
dependencies:
|
||||
file_selector: ^1.1.0
|
||||
flutter:
|
||||
sdk: flutter
|
||||
flutter_rust_bridge: 2.13.0
|
||||
@@ -26,6 +27,8 @@ dev_dependencies:
|
||||
|
||||
flutter:
|
||||
uses-material-design: true
|
||||
assets:
|
||||
- assets/modules/
|
||||
fonts:
|
||||
- family: Inter
|
||||
fonts:
|
||||
|
||||
@@ -0,0 +1,439 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:synapse/src/backend/graph_backend.dart';
|
||||
import 'package:synapse/src/state/app_state.dart';
|
||||
import 'package:synapse/src/theme/theme.dart';
|
||||
import 'package:synapse/src/views/module_view.dart';
|
||||
import 'package:synapse/src/views/modules_settings.dart';
|
||||
import 'package:synapse/src/views/shell.dart';
|
||||
import 'package:synapse/src/widgets/module_ui.dart';
|
||||
|
||||
import 'support/memory_backend.dart';
|
||||
|
||||
ModuleDto vault({int? tick}) => ModuleDto(
|
||||
id: 'synapse.secrets',
|
||||
name: 'Secrets',
|
||||
version: '0.1.0',
|
||||
description: 'An encrypted vault.',
|
||||
author: 'Synapse',
|
||||
permissions: const ['storage', 'crypto', 'clipboard'],
|
||||
views: const [ModuleViewDto(id: 'vault', title: 'Secrets', icon: '🔑')],
|
||||
macros: const ['secret'],
|
||||
tickSeconds: tick,
|
||||
enabled: true,
|
||||
size: BigInt.from(1000),
|
||||
);
|
||||
|
||||
Future<AppState> pump(
|
||||
WidgetTester tester,
|
||||
MemoryBackend b, {
|
||||
AppRoute? route,
|
||||
double height = 1000,
|
||||
}) async {
|
||||
tester.view.physicalSize = Size(1600, height);
|
||||
tester.view.devicePixelRatio = 1;
|
||||
addTearDown(tester.view.reset);
|
||||
final app = AppState(b);
|
||||
await app.modules.load();
|
||||
if (route != null) app.go(route);
|
||||
await tester.pumpWidget(
|
||||
AppScope(
|
||||
state: app,
|
||||
child: MaterialApp(
|
||||
theme: buildTheme(Brightness.light),
|
||||
home: const Shell(),
|
||||
),
|
||||
),
|
||||
);
|
||||
await settle(tester);
|
||||
return app;
|
||||
}
|
||||
|
||||
Future<void> settle(WidgetTester tester) async {
|
||||
for (var i = 0; i < 6; i++) {
|
||||
await tester.pump(const Duration(milliseconds: 50));
|
||||
}
|
||||
}
|
||||
|
||||
/// Captures what the app puts on the clipboard.
|
||||
List<String?> mockClipboard(WidgetTester tester) {
|
||||
final writes = <String?>[];
|
||||
String? current;
|
||||
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
|
||||
SystemChannels.platform,
|
||||
(call) async {
|
||||
if (call.method == 'Clipboard.setData') {
|
||||
current = (call.arguments as Map)['text'] as String?;
|
||||
writes.add(current);
|
||||
}
|
||||
if (call.method == 'Clipboard.getData') return {'text': current};
|
||||
return null;
|
||||
},
|
||||
);
|
||||
addTearDown(
|
||||
() => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
|
||||
SystemChannels.platform,
|
||||
null,
|
||||
),
|
||||
);
|
||||
return writes;
|
||||
}
|
||||
|
||||
void main() {
|
||||
test('module routes survive a restart', () {
|
||||
const r = ModuleRoute('synapse.secrets', 'vault', title: 'Secrets');
|
||||
final back = routeFromJson(routeToJson(r));
|
||||
expect(back, r);
|
||||
expect((back! as ModuleRoute).title, 'Secrets');
|
||||
expect(routeFromJson({'t': 'module', 'id': 'x'}), isNull);
|
||||
});
|
||||
|
||||
testWidgets('installing a bundled module asks for its permissions first', (
|
||||
tester,
|
||||
) async {
|
||||
final b = MemoryBackend()..inspectResult = vault();
|
||||
loadBundledModule = (_) async => Uint8List(4);
|
||||
await pump(tester, b, route: const SettingsRoute(), height: 3000);
|
||||
|
||||
await tester.ensureVisible(
|
||||
find.byKey(const ValueKey('module-install-synapse.secrets')),
|
||||
);
|
||||
await tester.tap(
|
||||
find.byKey(const ValueKey('module-install-synapse.secrets')),
|
||||
);
|
||||
await settle(tester);
|
||||
expect(find.text('Install Secrets 0.1.0?'), findsOneWidget);
|
||||
expect(find.textContaining('Derive keys from passwords'), findsOneWidget);
|
||||
// Cancel installs nothing.
|
||||
await tester.tap(find.text('Cancel'));
|
||||
await settle(tester);
|
||||
expect(b.installedModules, isEmpty);
|
||||
|
||||
await tester.tap(
|
||||
find.byKey(const ValueKey('module-install-synapse.secrets')),
|
||||
);
|
||||
await settle(tester);
|
||||
await tester.tap(find.byKey(const ValueKey('module-consent-install')));
|
||||
await settle(tester);
|
||||
expect(b.installedModules.keys, ['synapse.secrets']);
|
||||
// Its view is in the sidebar.
|
||||
expect(
|
||||
find.widgetWithText(InkWell, 'Secrets').evaluate().isNotEmpty ||
|
||||
find.text('Secrets').evaluate().isNotEmpty,
|
||||
isTrue,
|
||||
);
|
||||
|
||||
// The "installed" notice would cover the buttons.
|
||||
tester
|
||||
.state<ScaffoldMessengerState>(find.byType(ScaffoldMessenger))
|
||||
.removeCurrentSnackBar();
|
||||
await settle(tester);
|
||||
// Disabling hides it; removing keeps data unless asked.
|
||||
await tester.ensureVisible(
|
||||
find.byKey(const ValueKey('module-enabled-synapse.secrets')),
|
||||
);
|
||||
await tester.tap(
|
||||
find.byKey(const ValueKey('module-enabled-synapse.secrets')),
|
||||
);
|
||||
await settle(tester);
|
||||
expect(b.installedModules['synapse.secrets']!.enabled, isFalse);
|
||||
await tester.tap(
|
||||
find.byKey(const ValueKey('module-remove-synapse.secrets')),
|
||||
);
|
||||
await settle(tester);
|
||||
await tester.tap(find.byKey(const ValueKey('module-remove-confirm')));
|
||||
await settle(tester);
|
||||
expect(b.installedModules, isEmpty);
|
||||
});
|
||||
|
||||
testWidgets(
|
||||
'a module view renders its tree, sends field values and applies effects',
|
||||
(tester) async {
|
||||
final writes = mockClipboard(tester);
|
||||
final b = MemoryBackend();
|
||||
b.installedModules['synapse.secrets'] = vault();
|
||||
var unlocked = false;
|
||||
b.moduleHandlers['synapse.secrets'] = (req) {
|
||||
if (req['op'] == 'event' && req['action'] == 'unlock') {
|
||||
unlocked = (req['values'] as Map)['password'] == 'correct horse';
|
||||
if (!unlocked) {
|
||||
return {
|
||||
'ui': {
|
||||
'type': 'column',
|
||||
'children': [
|
||||
{
|
||||
'type': 'field',
|
||||
'id': 'password',
|
||||
'label': 'Master password',
|
||||
'value': '',
|
||||
'secret': true,
|
||||
'submit': 'unlock',
|
||||
},
|
||||
{'type': 'text', 'text': 'Wrong password.', 'style': 'error'},
|
||||
{
|
||||
'type': 'button',
|
||||
'label': 'Unlock',
|
||||
'action': 'unlock',
|
||||
'style': 'primary',
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
if (req['op'] == 'event' && req['action'] == 'copy_password') {
|
||||
return {
|
||||
'ui': {'type': 'text', 'text': 'GitHub'},
|
||||
'effects': [
|
||||
{
|
||||
'copy': {'text': 'hunter2', 'clear_after_ms': 1000},
|
||||
},
|
||||
{'toast': 'Password copied.'},
|
||||
],
|
||||
};
|
||||
}
|
||||
if (unlocked) {
|
||||
return {
|
||||
'ui': {
|
||||
'type': 'column',
|
||||
'children': [
|
||||
{'type': 'heading', 'text': 'GitHub'},
|
||||
{
|
||||
'type': 'button',
|
||||
'label': 'Copy',
|
||||
'action': 'copy_password',
|
||||
'arg': 'id1',
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
}
|
||||
return {
|
||||
'ui': {
|
||||
'type': 'column',
|
||||
'children': [
|
||||
{
|
||||
'type': 'field',
|
||||
'id': 'password',
|
||||
'label': 'Master password',
|
||||
'value': '',
|
||||
'secret': true,
|
||||
'submit': 'unlock',
|
||||
},
|
||||
{
|
||||
'type': 'button',
|
||||
'label': 'Unlock',
|
||||
'action': 'unlock',
|
||||
'style': 'primary',
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
};
|
||||
await pump(
|
||||
tester,
|
||||
b,
|
||||
route: const ModuleRoute('synapse.secrets', 'vault', title: 'Secrets'),
|
||||
);
|
||||
expect(find.byType(ModuleView), findsOneWidget);
|
||||
final field = find.widgetWithText(TextField, 'Master password');
|
||||
expect(tester.widget<TextField>(field).obscureText, isTrue);
|
||||
|
||||
await tester.enterText(field, 'wrong');
|
||||
await tester.tap(find.text('Unlock'));
|
||||
await settle(tester);
|
||||
expect(find.text('Wrong password.'), findsOneWidget);
|
||||
expect((b.moduleRequests.last.$2['values'] as Map)['password'], 'wrong');
|
||||
|
||||
await tester.enterText(
|
||||
find.widgetWithText(TextField, 'Master password'),
|
||||
'correct horse',
|
||||
);
|
||||
await tester.testTextInput.receiveAction(TextInputAction.done);
|
||||
await settle(tester);
|
||||
expect(find.text('GitHub'), findsOneWidget);
|
||||
|
||||
await tester.tap(find.text('Copy'));
|
||||
await settle(tester);
|
||||
expect(writes, ['hunter2']);
|
||||
expect(find.text('Password copied.'), findsOneWidget);
|
||||
// The clipboard is cleared after the delay (only if it still holds our text).
|
||||
await tester.pump(const Duration(seconds: 2));
|
||||
expect(writes, ['hunter2', '']);
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets('blocks render module macros as chips with actions', (
|
||||
tester,
|
||||
) async {
|
||||
final writes = mockClipboard(tester);
|
||||
final b = MemoryBackend();
|
||||
b.installedModules['synapse.secrets'] = vault();
|
||||
b.moduleHandlers['synapse.secrets'] = (req) => switch (req['op']) {
|
||||
'macro' => {
|
||||
'inline': {
|
||||
'text': req['args'],
|
||||
'icon': '🔑',
|
||||
'masked': '••••••••',
|
||||
'actions': [
|
||||
{'id': 'copy', 'label': 'Copy password', 'icon': 'copy'},
|
||||
],
|
||||
},
|
||||
},
|
||||
'macro_action' => {
|
||||
'inline': {'text': req['args'], 'masked': '••••••••'},
|
||||
'effects': [
|
||||
{
|
||||
'copy': {'text': 's3cret'},
|
||||
},
|
||||
],
|
||||
},
|
||||
_ => {},
|
||||
};
|
||||
final p = b.createPage('Accounts');
|
||||
b.seed(p.id, [(0, 'GitHub: {{secret GitHub}} and {{embed nothing}}')]);
|
||||
await pump(tester, b, route: PageTarget(id: p.id));
|
||||
|
||||
expect(find.byType(ModuleMacro), findsOneWidget);
|
||||
expect(find.text('••••••••'), findsOneWidget);
|
||||
expect(
|
||||
find.textContaining('{{embed nothing}}', findRichText: true),
|
||||
findsOneWidget,
|
||||
);
|
||||
final req = b.moduleRequests.firstWhere((r) => r.$2['op'] == 'macro').$2;
|
||||
expect(req['name'], 'secret');
|
||||
expect(req['args'], 'GitHub');
|
||||
|
||||
await tester.tap(find.byTooltip('Copy password'));
|
||||
await settle(tester);
|
||||
expect(writes, ['s3cret']);
|
||||
expect(b.moduleRequests.last.$2['action'], 'copy');
|
||||
});
|
||||
|
||||
testWidgets('without the module, macros stay text', (tester) async {
|
||||
final b = MemoryBackend();
|
||||
final p = b.createPage('Accounts');
|
||||
b.seed(p.id, [(0, 'GitHub: {{secret GitHub}}')]);
|
||||
await pump(tester, b, route: PageTarget(id: p.id));
|
||||
expect(find.byType(ModuleMacro), findsNothing);
|
||||
expect(
|
||||
find.textContaining('{{secret GitHub}}', findRichText: true),
|
||||
findsOneWidget,
|
||||
);
|
||||
});
|
||||
|
||||
testWidgets('suspending the app locks modules and redraws them', (
|
||||
tester,
|
||||
) async {
|
||||
final b = MemoryBackend();
|
||||
b.installedModules['synapse.secrets'] = vault();
|
||||
b.moduleHandlers['synapse.secrets'] = (req) =>
|
||||
req['op'] == 'suspend' ? {'changed': true} : {};
|
||||
final app = await pump(tester, b);
|
||||
final before = app.modules.macroVersion;
|
||||
await app.modules.suspend();
|
||||
expect(b.moduleRequests.last.$2['op'], 'suspend');
|
||||
expect(app.modules.macroVersion, greaterThan(before));
|
||||
});
|
||||
|
||||
testWidgets('a file cannot pose as a bundled module', (tester) async {
|
||||
final b = MemoryBackend()..inspectResult = vault();
|
||||
pickModuleFile = () async => Uint8List(4);
|
||||
await pump(tester, b, route: const SettingsRoute(), height: 3000);
|
||||
await tester.tap(find.byKey(const ValueKey('module-install-file')));
|
||||
await settle(tester);
|
||||
expect(
|
||||
find.textContaining('reserved for modules included'),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(find.text('Install Secrets 0.1.0?'), findsNothing);
|
||||
expect(b.installedModules, isEmpty);
|
||||
});
|
||||
|
||||
testWidgets('installing over existing data warns in the consent dialog', (
|
||||
tester,
|
||||
) async {
|
||||
final m = vault();
|
||||
final b = MemoryBackend()
|
||||
..inspectResult = ModuleDto(
|
||||
id: 'acme.notes',
|
||||
name: 'Notes',
|
||||
version: '1',
|
||||
description: '',
|
||||
author: 'Acme',
|
||||
permissions: const ['storage'],
|
||||
views: const [],
|
||||
macros: const [],
|
||||
enabled: true,
|
||||
size: m.size,
|
||||
)
|
||||
..moduleData.add('acme.notes');
|
||||
pickModuleFile = () async => Uint8List(4);
|
||||
await pump(tester, b, route: const SettingsRoute(), height: 3000);
|
||||
await tester.tap(find.byKey(const ValueKey('module-install-file')));
|
||||
await settle(tester);
|
||||
expect(find.text('Install Notes 1?'), findsOneWidget);
|
||||
expect(find.textContaining('already holds data'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('suspending clears a copied secret from the clipboard', (
|
||||
tester,
|
||||
) async {
|
||||
final writes = mockClipboard(tester);
|
||||
final b = MemoryBackend();
|
||||
b.installedModules['synapse.secrets'] = vault();
|
||||
final app = await pump(tester, b);
|
||||
await app.modules.applyEffects({
|
||||
'effects': [
|
||||
{
|
||||
'copy': {'text': 'hunter2', 'clear_after_ms': 30000},
|
||||
},
|
||||
],
|
||||
});
|
||||
await app.modules.suspend();
|
||||
expect(writes, ['hunter2', '']);
|
||||
// The pending timer was cancelled: nothing more happens later.
|
||||
await tester.pump(const Duration(seconds: 31));
|
||||
expect(writes, ['hunter2', '']);
|
||||
});
|
||||
|
||||
testWidgets('fields start empty on a new screen even with a reused id', (
|
||||
tester,
|
||||
) async {
|
||||
final b = MemoryBackend();
|
||||
b.installedModules['synapse.secrets'] = vault();
|
||||
var screen = 'edit';
|
||||
b.moduleHandlers['synapse.secrets'] = (req) {
|
||||
if (req['op'] == 'event') screen = 'locked';
|
||||
return {
|
||||
'ui': {
|
||||
'type': 'column',
|
||||
'key': screen,
|
||||
'children': [
|
||||
{
|
||||
'type': 'field',
|
||||
'id': 'password',
|
||||
'label': screen == 'edit' ? 'Password' : 'Master password',
|
||||
'value': '',
|
||||
'secret': true,
|
||||
},
|
||||
{'type': 'button', 'label': 'Go', 'action': 'go'},
|
||||
],
|
||||
},
|
||||
};
|
||||
};
|
||||
await pump(
|
||||
tester,
|
||||
b,
|
||||
route: const ModuleRoute('synapse.secrets', 'vault', title: 'Secrets'),
|
||||
);
|
||||
await tester.enterText(find.widgetWithText(TextField, 'Password'), 'typed');
|
||||
await tester.tap(find.text('Go'));
|
||||
await settle(tester);
|
||||
final field = tester.widget<TextField>(
|
||||
find.widgetWithText(TextField, 'Master password'),
|
||||
);
|
||||
expect(field.controller!.text, '');
|
||||
});
|
||||
}
|
||||
@@ -18,6 +18,79 @@ class MemoryBackend implements GraphBackend {
|
||||
final outlines = <String, List<OutlineNode>>{};
|
||||
final aliases = <String, String>{};
|
||||
final calls = <String>[];
|
||||
|
||||
// ---------------------------------------------------------------- modules
|
||||
// Fakes: [moduleHandlers] answer requests the way a module would.
|
||||
final installedModules = <String, ModuleDto>{};
|
||||
final moduleHandlers =
|
||||
<String, Map<String, dynamic> Function(Map<String, dynamic>)>{};
|
||||
final moduleRequests = <(String, Map<String, dynamic>)>[];
|
||||
final stoppedModules = <String>[];
|
||||
|
||||
/// What [inspectModule] reads from any file; null means "not a module".
|
||||
ModuleDto? inspectResult;
|
||||
|
||||
@override
|
||||
Future<List<ModuleDto>> modules() async =>
|
||||
installedModules.values.toList()
|
||||
..sort((a, b) => a.name.compareTo(b.name));
|
||||
|
||||
@override
|
||||
Future<ModuleDto> inspectModule(Uint8List wasm) async =>
|
||||
inspectResult ?? (throw Exception('not a Synapse module'));
|
||||
|
||||
@override
|
||||
Future<ModuleDto> installModule(Uint8List wasm, List<String> granted) async {
|
||||
final m = await inspectModule(wasm);
|
||||
if (m.permissions.any((p) => !granted.contains(p))) {
|
||||
throw Exception('permission not granted');
|
||||
}
|
||||
final enabled = installedModules[m.id]?.enabled ?? true;
|
||||
return installedModules[m.id] = withEnabled(m, enabled);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> setModuleEnabled(String id, bool enabled) async {
|
||||
installedModules[id] = withEnabled(installedModules[id]!, enabled);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> uninstallModule(String id, {bool deleteData = false}) async {
|
||||
installedModules.remove(id);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Map<String, dynamic>> moduleCall(
|
||||
String id,
|
||||
Map<String, dynamic> request,
|
||||
) async {
|
||||
final m = installedModules[id];
|
||||
if (m == null || !m.enabled) throw Exception('module $id is not enabled');
|
||||
moduleRequests.add((id, request));
|
||||
return moduleHandlers[id]?.call(request) ?? {};
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> stopModule(String id) async => stoppedModules.add(id);
|
||||
|
||||
/// Module ids with data in the graph.
|
||||
final moduleData = <String>{};
|
||||
@override
|
||||
Future<bool> moduleHasData(String id) async => moduleData.contains(id);
|
||||
|
||||
static ModuleDto withEnabled(ModuleDto m, bool enabled) => ModuleDto(
|
||||
id: m.id,
|
||||
name: m.name,
|
||||
version: m.version,
|
||||
description: m.description,
|
||||
author: m.author,
|
||||
permissions: m.permissions,
|
||||
views: m.views,
|
||||
macros: m.macros,
|
||||
tickSeconds: m.tickSeconds,
|
||||
enabled: enabled,
|
||||
size: m.size,
|
||||
);
|
||||
int _seq = 0;
|
||||
|
||||
String _id() => 'id-${_seq++}';
|
||||
|
||||
@@ -6,9 +6,12 @@
|
||||
|
||||
#include "generated_plugin_registrant.h"
|
||||
|
||||
#include <file_selector_windows/file_selector_windows.h>
|
||||
#include <url_launcher_windows/url_launcher_windows.h>
|
||||
|
||||
void RegisterPlugins(flutter::PluginRegistry* registry) {
|
||||
FileSelectorWindowsRegisterWithRegistrar(
|
||||
registry->GetRegistrarForPlugin("FileSelectorWindows"));
|
||||
UrlLauncherWindowsRegisterWithRegistrar(
|
||||
registry->GetRegistrarForPlugin("UrlLauncherWindows"));
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
#
|
||||
|
||||
list(APPEND FLUTTER_PLUGIN_LIST
|
||||
file_selector_windows
|
||||
url_launcher_windows
|
||||
)
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ pub mod embed;
|
||||
pub mod error;
|
||||
pub mod hlc;
|
||||
pub mod model;
|
||||
pub mod module_data;
|
||||
pub mod parse;
|
||||
pub mod position;
|
||||
mod schema;
|
||||
@@ -20,6 +21,7 @@ pub mod types;
|
||||
|
||||
pub use error::{Error, Result};
|
||||
pub use model::*;
|
||||
pub use module_data::{MAX_MODULE_KEY, MAX_MODULE_VALUE, is_valid_module_id};
|
||||
pub use schema::VERSION as SCHEMA_VERSION;
|
||||
pub use store::Graph;
|
||||
pub use structure::{
|
||||
|
||||
@@ -206,6 +206,14 @@ pub enum Op {
|
||||
PutTypeDef {
|
||||
def: TypeDef,
|
||||
},
|
||||
/// An entry of a module's key-value store (`value: None` deletes it), last writer wins
|
||||
/// per (module, key).
|
||||
PutModuleData {
|
||||
module: String,
|
||||
key: String,
|
||||
#[serde(default)]
|
||||
value: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
/// Graph-wide metadata of a type name: types are names, not pages, so this is where their
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
//! Module data: a small key-value store per installed module (`module_data` table, schema v9).
|
||||
//!
|
||||
//! Each entry is keyed by (module id, key) and synced with its own op
|
||||
//! ([`Op::PutModuleData`], last writer wins per entry). A deleted entry is kept as a tombstone
|
||||
//! (`value` NULL) so the delete wins over older writes from other replicas. The core never
|
||||
//! interprets values: modules store their own encoding (the secrets module stores ciphertext).
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::model::Op;
|
||||
use crate::store::Graph;
|
||||
use rusqlite::{OptionalExtension, params};
|
||||
|
||||
/// Longest module id, in bytes.
|
||||
pub const MAX_MODULE_ID: usize = 64;
|
||||
/// Longest key, in bytes.
|
||||
pub const MAX_MODULE_KEY: usize = 256;
|
||||
/// Largest value, in bytes.
|
||||
pub const MAX_MODULE_VALUE: usize = 1 << 20;
|
||||
|
||||
/// Module ids are lowercase ASCII letters, digits, `.`, `-` and `_` (e.g. `synapse.secrets`).
|
||||
pub fn is_valid_module_id(id: &str) -> bool {
|
||||
!id.is_empty()
|
||||
&& id.len() <= MAX_MODULE_ID
|
||||
&& id
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"._-".contains(&b))
|
||||
&& !id.starts_with('.')
|
||||
}
|
||||
|
||||
fn check(module: &str, key: &str, value: Option<&str>) -> Result<()> {
|
||||
if !is_valid_module_id(module) {
|
||||
return Err(Error::Invalid(format!("invalid module id {module:?}")));
|
||||
}
|
||||
if key.is_empty() || key.len() > MAX_MODULE_KEY || key.chars().any(char::is_control) {
|
||||
return Err(Error::Invalid(format!("invalid module key {key:?}")));
|
||||
}
|
||||
if value.is_some_and(|v| v.len() > MAX_MODULE_VALUE) {
|
||||
return Err(Error::Invalid(format!("value of {key:?} is too large")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl Graph {
|
||||
/// The value of `key` for `module`, `None` when unset or deleted.
|
||||
pub fn module_data(&self, module: &str, key: &str) -> Result<Option<String>> {
|
||||
Ok(self
|
||||
.row(
|
||||
"SELECT value FROM module_data WHERE module=?1 AND key=?2",
|
||||
params![module, key],
|
||||
|r| r.get::<_, Option<String>>(0),
|
||||
)
|
||||
.optional()?
|
||||
.flatten())
|
||||
}
|
||||
|
||||
/// Live entries of `module` whose key starts with `prefix`, sorted by key.
|
||||
pub fn module_data_list(&self, module: &str, prefix: &str) -> Result<Vec<(String, String)>> {
|
||||
let mut st = self.conn().prepare_cached(
|
||||
"SELECT key, value FROM module_data
|
||||
WHERE module=?1 AND value IS NOT NULL AND substr(key, 1, length(?2))=?2
|
||||
ORDER BY key",
|
||||
)?;
|
||||
let rows = st
|
||||
.query_map(params![module, prefix], |r| Ok((r.get(0)?, r.get(1)?)))?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
Ok(rows)
|
||||
}
|
||||
|
||||
/// Number of live entries of `module` and their total size (keys plus values, bytes).
|
||||
pub fn module_data_usage(&self, module: &str) -> Result<(u64, u64)> {
|
||||
Ok(self.row(
|
||||
"SELECT count(*), coalesce(sum(length(CAST(key AS BLOB)) + length(CAST(value AS BLOB))), 0)
|
||||
FROM module_data WHERE module=?1 AND value IS NOT NULL",
|
||||
params![module],
|
||||
|r| Ok((r.get::<_, i64>(0)? as u64, r.get::<_, i64>(1)? as u64)),
|
||||
)?)
|
||||
}
|
||||
|
||||
/// Sets (`Some`) or deletes (`None`) an entry, logged as [`Op::PutModuleData`]. Deleting an
|
||||
/// unset key is a no-op.
|
||||
pub fn set_module_data(&self, module: &str, key: &str, value: Option<&str>) -> Result<()> {
|
||||
check(module, key, value)?;
|
||||
let tx = self.tx()?;
|
||||
if value.is_none() && self.module_data(module, key)?.is_none() {
|
||||
tx.commit()?;
|
||||
return Ok(());
|
||||
}
|
||||
let hlc = self.tick();
|
||||
self.write_module_data_row(module, key, value, &hlc)?;
|
||||
self.log(
|
||||
&hlc,
|
||||
&Op::PutModuleData {
|
||||
module: module.to_string(),
|
||||
key: key.to_string(),
|
||||
value: value.map(str::to_string),
|
||||
},
|
||||
)?;
|
||||
tx.commit()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Deletes every live entry of `module` (one op each). Returns how many were deleted.
|
||||
pub fn clear_module_data(&self, module: &str) -> Result<usize> {
|
||||
let tx = self.tx()?;
|
||||
let keys: Vec<String> = self
|
||||
.module_data_list(module, "")?
|
||||
.into_iter()
|
||||
.map(|(k, _)| k)
|
||||
.collect();
|
||||
for k in &keys {
|
||||
self.set_module_data(module, k, None)?;
|
||||
}
|
||||
tx.commit()?;
|
||||
Ok(keys.len())
|
||||
}
|
||||
|
||||
pub(crate) fn module_data_hlc(&self, module: &str, key: &str) -> Result<Option<String>> {
|
||||
Ok(self
|
||||
.row(
|
||||
"SELECT hlc FROM module_data WHERE module=?1 AND key=?2",
|
||||
params![module, key],
|
||||
|r| r.get(0),
|
||||
)
|
||||
.optional()?)
|
||||
}
|
||||
|
||||
pub(crate) fn write_module_data_row(
|
||||
&self,
|
||||
module: &str,
|
||||
key: &str,
|
||||
value: Option<&str>,
|
||||
hlc: &str,
|
||||
) -> Result<()> {
|
||||
self.exec(
|
||||
"INSERT OR REPLACE INTO module_data(module, key, value, hlc) VALUES (?1, ?2, ?3, ?4)",
|
||||
params![module, key, value, hlc],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Validates a remote [`Op::PutModuleData`] (same rules as local writes).
|
||||
pub(crate) fn check_remote(module: &str, key: &str, value: Option<&str>) -> bool {
|
||||
check(module, key, value).is_ok()
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
use rusqlite::OptionalExtension;
|
||||
|
||||
pub const VERSION: i64 = 8;
|
||||
pub const VERSION: i64 = 9;
|
||||
|
||||
pub const SCHEMA: &str = r#"
|
||||
CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
|
||||
@@ -116,6 +116,15 @@ CREATE TABLE IF NOT EXISTS type_defs (
|
||||
hlc TEXT NOT NULL
|
||||
);
|
||||
|
||||
-- v9: per-module key-value data; a NULL value is a tombstone.
|
||||
CREATE TABLE IF NOT EXISTS module_data (
|
||||
module TEXT NOT NULL,
|
||||
key TEXT NOT NULL,
|
||||
value TEXT,
|
||||
hlc TEXT NOT NULL,
|
||||
PRIMARY KEY (module, key)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS tombstones (id TEXT PRIMARY KEY, hlc TEXT NOT NULL);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS ops (
|
||||
@@ -281,7 +290,8 @@ pub fn migrate(conn: &rusqlite::Connection) -> rusqlite::Result<()> {
|
||||
// v7: a page's hub title is an implicit tag, so the index changes.
|
||||
rebuild_page_tags(conn)?;
|
||||
}
|
||||
// v8: `type_defs` (type icons) is created empty by `SCHEMA`; nothing to convert.
|
||||
// v8: `type_defs` (type icons) and v9: `module_data` are created empty by `SCHEMA`;
|
||||
// nothing to convert.
|
||||
conn.execute(
|
||||
"INSERT OR REPLACE INTO meta(key, value) VALUES ('schema', ?1)",
|
||||
[VERSION.to_string()],
|
||||
|
||||
@@ -1174,6 +1174,16 @@ impl Graph {
|
||||
true
|
||||
}
|
||||
}
|
||||
Op::PutModuleData { module, key, value } => {
|
||||
crate::module_data::check_remote(module, key, value.as_deref())
|
||||
&& self
|
||||
.module_data_hlc(module, key)?
|
||||
.is_none_or(|l| hlc > l.as_str())
|
||||
&& {
|
||||
self.write_module_data_row(module, key, value.as_deref(), hlc)?;
|
||||
true
|
||||
}
|
||||
}
|
||||
};
|
||||
if applied {
|
||||
self.log(hlc, op)?;
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
use synapse_core::{Graph, Op};
|
||||
|
||||
fn graph() -> (tempfile::TempDir, Graph) {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let g = Graph::open(dir.path()).unwrap();
|
||||
(dir, g)
|
||||
}
|
||||
|
||||
fn module_ops(g: &Graph) -> Vec<(String, Op)> {
|
||||
g.ops_since(0, 10_000)
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.filter(|r| matches!(r.op, Op::PutModuleData { .. }))
|
||||
.map(|r| (r.hlc, r.op))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn module_data_is_namespaced_listed_and_deleted() {
|
||||
let (_d, g) = graph();
|
||||
g.set_module_data("a.mod", "entry/1", Some("x")).unwrap();
|
||||
g.set_module_data("a.mod", "entry/2", Some("y")).unwrap();
|
||||
g.set_module_data("a.mod", "vault", Some("h")).unwrap();
|
||||
g.set_module_data("b.mod", "entry/1", Some("other"))
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
g.module_data("a.mod", "entry/1").unwrap().as_deref(),
|
||||
Some("x")
|
||||
);
|
||||
let keys: Vec<_> = g
|
||||
.module_data_list("a.mod", "entry/")
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.map(|(k, _)| k)
|
||||
.collect();
|
||||
assert_eq!(keys, ["entry/1", "entry/2"]);
|
||||
g.set_module_data("a.mod", "entry/1", None).unwrap();
|
||||
assert_eq!(g.module_data("a.mod", "entry/1").unwrap(), None);
|
||||
assert_eq!(g.module_data_list("a.mod", "").unwrap().len(), 2);
|
||||
// Deleting a missing key logs nothing.
|
||||
let before = module_ops(&g).len();
|
||||
g.set_module_data("a.mod", "missing", None).unwrap();
|
||||
assert_eq!(module_ops(&g).len(), before);
|
||||
assert_eq!(g.clear_module_data("a.mod").unwrap(), 2);
|
||||
assert!(g.module_data_list("a.mod", "").unwrap().is_empty());
|
||||
assert_eq!(g.module_data_list("b.mod", "").unwrap().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn module_data_validates_ids_keys_and_sizes() {
|
||||
let (_d, g) = graph();
|
||||
assert!(g.set_module_data("Bad Id", "k", Some("v")).is_err());
|
||||
assert!(g.set_module_data("ok", "", Some("v")).is_err());
|
||||
assert!(g.set_module_data("ok", "a\nb", Some("v")).is_err());
|
||||
let big = "x".repeat(synapse_core::MAX_MODULE_VALUE + 1);
|
||||
assert!(g.set_module_data("ok", "k", Some(&big)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn module_data_syncs_last_writer_wins_with_tombstones() {
|
||||
let (_a, a) = graph();
|
||||
let (_b, b) = graph();
|
||||
a.set_module_data("m", "k", Some("first")).unwrap();
|
||||
for (hlc, op) in module_ops(&a) {
|
||||
assert!(b.apply_remote(&hlc, &op).unwrap());
|
||||
}
|
||||
assert_eq!(b.module_data("m", "k").unwrap().as_deref(), Some("first"));
|
||||
// A later delete on b wins over a's older write replayed again.
|
||||
b.set_module_data("m", "k", None).unwrap();
|
||||
for (hlc, op) in module_ops(&a) {
|
||||
assert!(!b.apply_remote(&hlc, &op).unwrap());
|
||||
}
|
||||
assert_eq!(b.module_data("m", "k").unwrap(), None);
|
||||
// ...and reaches a.
|
||||
let ops = module_ops(&b);
|
||||
let (hlc, op) = ops.last().unwrap();
|
||||
assert!(a.apply_remote(hlc, op).unwrap());
|
||||
assert_eq!(a.module_data("m", "k").unwrap(), None);
|
||||
// Invalid remote ops are ignored.
|
||||
let bad = Op::PutModuleData {
|
||||
module: "Bad Id".into(),
|
||||
key: "k".into(),
|
||||
value: Some("v".into()),
|
||||
};
|
||||
assert!(!a.apply_remote("0000000000001-00000-x", &bad).unwrap());
|
||||
}
|
||||
@@ -506,7 +506,7 @@ fn old_ops_and_v2_databases_load() {
|
||||
r.get(0)
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(schema, "8");
|
||||
assert_eq!(schema, "9");
|
||||
let p = g.get_page(id).unwrap().unwrap();
|
||||
assert_eq!((p.kind, p.title.as_str()), (PageKind::Note, "Legacy"));
|
||||
let h = g.create_hub("New hub", "").unwrap();
|
||||
@@ -1190,7 +1190,7 @@ fn v7_databases_gain_type_definitions() {
|
||||
r.get(0)
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(schema, "8");
|
||||
assert_eq!(schema, "9");
|
||||
assert_eq!(type_row(&g, "persona"), Some(("persona".into(), 1, None)));
|
||||
g.set_type_icon("persona", Some("🧑")).unwrap();
|
||||
assert_eq!(type_row(&g, "persona").unwrap().2.as_deref(), Some("🧑"));
|
||||
|
||||
@@ -13,6 +13,8 @@ anyhow = "1"
|
||||
chrono.workspace = true
|
||||
flutter_rust_bridge = "=2.13.0"
|
||||
synapse-core.workspace = true
|
||||
synapse-modules = { path = "../synapse-modules" }
|
||||
serde_json.workspace = true
|
||||
uuid.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
|
||||
@@ -15,7 +15,7 @@ fn main() -> anyhow::Result<()> {
|
||||
let t = std::time::Instant::now();
|
||||
g.graph_data()?;
|
||||
let cached = t.elapsed();
|
||||
let mut by_kind = [0usize; 7];
|
||||
let mut by_kind = [0usize; 9];
|
||||
for &k in &d.kinds {
|
||||
by_kind[k as usize] += 1;
|
||||
}
|
||||
@@ -34,6 +34,8 @@ fn main() -> anyhow::Result<()> {
|
||||
"embed",
|
||||
"mention",
|
||||
"synapse",
|
||||
"contains",
|
||||
"tagged",
|
||||
];
|
||||
for (n, c) in names.iter().zip(by_kind) {
|
||||
println!(" {n:<10} {c}");
|
||||
|
||||
@@ -367,3 +367,61 @@ pub struct LegacyCandidate {
|
||||
pub blocks: u32,
|
||||
pub preselected: bool,
|
||||
}
|
||||
|
||||
/// A view a module adds to the sidebar.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct ModuleViewDto {
|
||||
pub id: String,
|
||||
pub title: String,
|
||||
pub icon: Option<String>,
|
||||
}
|
||||
|
||||
/// An installed (or inspected) module.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct ModuleDto {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub version: String,
|
||||
pub description: String,
|
||||
pub author: String,
|
||||
/// `storage`, `crypto`, `clipboard`, `pages:read`, `pages:write`.
|
||||
pub permissions: Vec<String>,
|
||||
pub views: Vec<ModuleViewDto>,
|
||||
/// Block macros (`{{name args}}`) it renders.
|
||||
pub macros: Vec<String>,
|
||||
/// How often the app sends it a `tick` request, if at all.
|
||||
pub tick_seconds: Option<u32>,
|
||||
pub enabled: bool,
|
||||
/// Size of the module file in bytes.
|
||||
pub size: u64,
|
||||
}
|
||||
|
||||
impl ModuleDto {
|
||||
pub(crate) fn new(m: &synapse_modules::Manifest, enabled: bool, size: u64) -> Self {
|
||||
Self {
|
||||
id: m.id.clone(),
|
||||
name: m.name.clone(),
|
||||
version: m.version.clone(),
|
||||
description: m.description.clone(),
|
||||
author: m.author.clone(),
|
||||
permissions: m
|
||||
.permissions
|
||||
.iter()
|
||||
.map(|p| p.as_str().to_string())
|
||||
.collect(),
|
||||
views: m
|
||||
.views
|
||||
.iter()
|
||||
.map(|v| ModuleViewDto {
|
||||
id: v.id.clone(),
|
||||
title: v.title.clone(),
|
||||
icon: v.icon.clone(),
|
||||
})
|
||||
.collect(),
|
||||
macros: m.macros.clone(),
|
||||
tick_seconds: m.tick_seconds,
|
||||
enabled,
|
||||
size,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -20,16 +20,21 @@ pub struct SynapseGraph {
|
||||
pub(crate) graph_cache: Mutex<Option<(super::graph_view::CacheKey, Arc<GraphData>)>>,
|
||||
/// Hubs and home hubs, keyed by op-log sequence.
|
||||
pub(crate) structure_cache: Mutex<Option<(i64, Arc<synapse_core::Structure>)>>,
|
||||
/// Installed modules (`<dir>/modules/`), started on first use.
|
||||
pub(crate) modules: synapse_modules::Registry,
|
||||
}
|
||||
|
||||
impl SynapseGraph {
|
||||
/// Opens (or creates) the graph stored in `dir`.
|
||||
pub fn open(dir: String) -> Result<SynapseGraph> {
|
||||
let graph = Graph::open(&dir).with_context(|| format!("opening graph at {dir}"))?;
|
||||
let graph = Arc::new(Mutex::new(graph));
|
||||
let modules = synapse_modules::Registry::open(std::path::Path::new(&dir), graph.clone());
|
||||
Ok(SynapseGraph {
|
||||
graph: Arc::new(Mutex::new(graph)),
|
||||
graph,
|
||||
graph_cache: Mutex::new(None),
|
||||
structure_cache: Mutex::new(None),
|
||||
modules,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
//! - `graph_view`: the whole page-level graph for the graph views (cached by op seq).
|
||||
//! - `structure`: hubs (folder-like pages), namespaces and the legacy page purge.
|
||||
//! - `tags`: free-form tags on pages (names, not pages) and their vocabulary.
|
||||
//! - `modules`: installed WebAssembly modules (synapse-modules) and requests to them.
|
||||
//! - `layout`: Barnes-Hut force-directed layout, stepped from Dart off the UI thread.
|
||||
//!
|
||||
//! Extension points for Phase 2 (one module each, methods on `SynapseGraph` or their own
|
||||
@@ -17,6 +18,7 @@ pub mod dto;
|
||||
pub mod graph;
|
||||
pub mod graph_view;
|
||||
pub mod layout;
|
||||
pub mod modules;
|
||||
pub mod outline;
|
||||
pub mod search;
|
||||
pub mod structure;
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
//! Installed modules: inspect, install, enable, uninstall, and JSON requests to them.
|
||||
//!
|
||||
//! Requests and responses are JSON strings (module API v1, see `docs/modules.md`); the app
|
||||
//! renders the UI trees and applies the effects. None of these calls hold the graph lock
|
||||
//! while a module runs: host functions lock it per call.
|
||||
|
||||
use super::dto::ModuleDto;
|
||||
use super::graph::SynapseGraph;
|
||||
use anyhow::{Result, anyhow};
|
||||
use synapse_modules::Permission;
|
||||
|
||||
impl SynapseGraph {
|
||||
/// Reads and validates a module file without installing it (for the consent dialog).
|
||||
pub fn inspect_module(&self, wasm: Vec<u8>) -> Result<ModuleDto> {
|
||||
let m = self.modules.inspect(&wasm)?;
|
||||
Ok(ModuleDto::new(&m, false, wasm.len() as u64))
|
||||
}
|
||||
|
||||
/// Installs or updates a module; `granted` must list every permission it asks for.
|
||||
pub fn install_module(&self, wasm: Vec<u8>, granted: Vec<String>) -> Result<ModuleDto> {
|
||||
let granted = granted
|
||||
.iter()
|
||||
.map(|p| Permission::parse(p).ok_or_else(|| anyhow!("unknown permission {p:?}")))
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
let info = self.modules.install(&wasm, &granted)?;
|
||||
Ok(ModuleDto::new(&info.manifest, info.enabled, info.size))
|
||||
}
|
||||
|
||||
/// Installed modules, by name.
|
||||
pub fn modules(&self) -> Vec<ModuleDto> {
|
||||
self.modules
|
||||
.list()
|
||||
.iter()
|
||||
.map(|i| ModuleDto::new(&i.manifest, i.enabled, i.size))
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn set_module_enabled(&self, id: String, enabled: bool) -> Result<()> {
|
||||
Ok(self.modules.set_enabled(&id, enabled)?)
|
||||
}
|
||||
|
||||
/// Removes a module from this device; `delete_data` also deletes its synced data on every
|
||||
/// device.
|
||||
pub fn uninstall_module(&self, id: String, delete_data: bool) -> Result<()> {
|
||||
Ok(self.modules.uninstall(&id, delete_data)?)
|
||||
}
|
||||
|
||||
/// Sends a JSON request to a module and returns its JSON response.
|
||||
pub fn module_call(&self, id: String, request: String) -> Result<String> {
|
||||
let req: serde_json::Value = serde_json::from_str(&request)?;
|
||||
Ok(self.modules.call(&id, &req)?.to_string())
|
||||
}
|
||||
|
||||
/// Whether the graph already holds data for module `id` (a module installed under that id
|
||||
/// can read it; the consent dialog warns about it).
|
||||
pub fn module_has_data(&self, id: String) -> Result<bool> {
|
||||
Ok(self.modules.has_data(&id)?)
|
||||
}
|
||||
|
||||
/// Stops a module's running instance (dropping its in-memory state).
|
||||
pub fn stop_module(&self, id: String) {
|
||||
self.modules.stop(&id);
|
||||
}
|
||||
}
|
||||
@@ -41,7 +41,7 @@ flutter_rust_bridge::frb_generated_boilerplate!(
|
||||
default_rust_auto_opaque = RustAutoOpaqueMoi,
|
||||
);
|
||||
pub(crate) const FLUTTER_RUST_BRIDGE_CODEGEN_VERSION: &str = "2.13.0";
|
||||
pub(crate) const FLUTTER_RUST_BRIDGE_CODEGEN_CONTENT_HASH: i32 = 272705018;
|
||||
pub(crate) const FLUTTER_RUST_BRIDGE_CODEGEN_CONTENT_HASH: i32 = -984841087;
|
||||
|
||||
// Section: executor
|
||||
|
||||
@@ -1458,6 +1458,118 @@ fn wire__crate__api__graph__SynapseGraph_insert_block_impl(
|
||||
},
|
||||
)
|
||||
}
|
||||
fn wire__crate__api__graph__SynapseGraph_inspect_module_impl(
|
||||
port_: flutter_rust_bridge::for_generated::MessagePort,
|
||||
ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr,
|
||||
rust_vec_len_: i32,
|
||||
data_len_: i32,
|
||||
) {
|
||||
FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::<flutter_rust_bridge::for_generated::SseCodec, _, _>(
|
||||
flutter_rust_bridge::for_generated::TaskInfo {
|
||||
debug_name: "SynapseGraph_inspect_module",
|
||||
port: Some(port_),
|
||||
mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal,
|
||||
},
|
||||
move || {
|
||||
let message = unsafe {
|
||||
flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire(
|
||||
ptr_,
|
||||
rust_vec_len_,
|
||||
data_len_,
|
||||
)
|
||||
};
|
||||
let mut deserializer =
|
||||
flutter_rust_bridge::for_generated::SseDeserializer::new(message);
|
||||
let api_that = <RustOpaqueMoi<
|
||||
flutter_rust_bridge::for_generated::RustAutoOpaqueInner<SynapseGraph>,
|
||||
>>::sse_decode(&mut deserializer);
|
||||
let api_wasm = <Vec<u8>>::sse_decode(&mut deserializer);
|
||||
deserializer.end();
|
||||
move |context| {
|
||||
transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>(
|
||||
(move || {
|
||||
let mut api_that_guard = None;
|
||||
let decode_indices_ =
|
||||
flutter_rust_bridge::for_generated::lockable_compute_decode_order(
|
||||
vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new(
|
||||
&api_that, 0, false,
|
||||
)],
|
||||
);
|
||||
for i in decode_indices_ {
|
||||
match i {
|
||||
0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
let api_that_guard = api_that_guard.unwrap();
|
||||
let output_ok = crate::api::graph::SynapseGraph::inspect_module(
|
||||
&*api_that_guard,
|
||||
api_wasm,
|
||||
)?;
|
||||
std::result::Result::Ok(output_ok)
|
||||
})(),
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
fn wire__crate__api__graph__SynapseGraph_install_module_impl(
|
||||
port_: flutter_rust_bridge::for_generated::MessagePort,
|
||||
ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr,
|
||||
rust_vec_len_: i32,
|
||||
data_len_: i32,
|
||||
) {
|
||||
FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::<flutter_rust_bridge::for_generated::SseCodec, _, _>(
|
||||
flutter_rust_bridge::for_generated::TaskInfo {
|
||||
debug_name: "SynapseGraph_install_module",
|
||||
port: Some(port_),
|
||||
mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal,
|
||||
},
|
||||
move || {
|
||||
let message = unsafe {
|
||||
flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire(
|
||||
ptr_,
|
||||
rust_vec_len_,
|
||||
data_len_,
|
||||
)
|
||||
};
|
||||
let mut deserializer =
|
||||
flutter_rust_bridge::for_generated::SseDeserializer::new(message);
|
||||
let api_that = <RustOpaqueMoi<
|
||||
flutter_rust_bridge::for_generated::RustAutoOpaqueInner<SynapseGraph>,
|
||||
>>::sse_decode(&mut deserializer);
|
||||
let api_wasm = <Vec<u8>>::sse_decode(&mut deserializer);
|
||||
let api_granted = <Vec<String>>::sse_decode(&mut deserializer);
|
||||
deserializer.end();
|
||||
move |context| {
|
||||
transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>(
|
||||
(move || {
|
||||
let mut api_that_guard = None;
|
||||
let decode_indices_ =
|
||||
flutter_rust_bridge::for_generated::lockable_compute_decode_order(
|
||||
vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new(
|
||||
&api_that, 0, false,
|
||||
)],
|
||||
);
|
||||
for i in decode_indices_ {
|
||||
match i {
|
||||
0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
let api_that_guard = api_that_guard.unwrap();
|
||||
let output_ok = crate::api::graph::SynapseGraph::install_module(
|
||||
&*api_that_guard,
|
||||
api_wasm,
|
||||
api_granted,
|
||||
)?;
|
||||
std::result::Result::Ok(output_ok)
|
||||
})(),
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
fn wire__crate__api__graph__SynapseGraph_journal_impl(
|
||||
port_: flutter_rust_bridge::for_generated::MessagePort,
|
||||
ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr,
|
||||
@@ -1791,6 +1903,168 @@ fn wire__crate__api__graph__SynapseGraph_merge_block_impl(
|
||||
},
|
||||
)
|
||||
}
|
||||
fn wire__crate__api__graph__SynapseGraph_module_call_impl(
|
||||
port_: flutter_rust_bridge::for_generated::MessagePort,
|
||||
ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr,
|
||||
rust_vec_len_: i32,
|
||||
data_len_: i32,
|
||||
) {
|
||||
FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::<flutter_rust_bridge::for_generated::SseCodec, _, _>(
|
||||
flutter_rust_bridge::for_generated::TaskInfo {
|
||||
debug_name: "SynapseGraph_module_call",
|
||||
port: Some(port_),
|
||||
mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal,
|
||||
},
|
||||
move || {
|
||||
let message = unsafe {
|
||||
flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire(
|
||||
ptr_,
|
||||
rust_vec_len_,
|
||||
data_len_,
|
||||
)
|
||||
};
|
||||
let mut deserializer =
|
||||
flutter_rust_bridge::for_generated::SseDeserializer::new(message);
|
||||
let api_that = <RustOpaqueMoi<
|
||||
flutter_rust_bridge::for_generated::RustAutoOpaqueInner<SynapseGraph>,
|
||||
>>::sse_decode(&mut deserializer);
|
||||
let api_id = <String>::sse_decode(&mut deserializer);
|
||||
let api_request = <String>::sse_decode(&mut deserializer);
|
||||
deserializer.end();
|
||||
move |context| {
|
||||
transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>(
|
||||
(move || {
|
||||
let mut api_that_guard = None;
|
||||
let decode_indices_ =
|
||||
flutter_rust_bridge::for_generated::lockable_compute_decode_order(
|
||||
vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new(
|
||||
&api_that, 0, false,
|
||||
)],
|
||||
);
|
||||
for i in decode_indices_ {
|
||||
match i {
|
||||
0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
let api_that_guard = api_that_guard.unwrap();
|
||||
let output_ok = crate::api::graph::SynapseGraph::module_call(
|
||||
&*api_that_guard,
|
||||
api_id,
|
||||
api_request,
|
||||
)?;
|
||||
std::result::Result::Ok(output_ok)
|
||||
})(),
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
fn wire__crate__api__graph__SynapseGraph_module_has_data_impl(
|
||||
port_: flutter_rust_bridge::for_generated::MessagePort,
|
||||
ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr,
|
||||
rust_vec_len_: i32,
|
||||
data_len_: i32,
|
||||
) {
|
||||
FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::<flutter_rust_bridge::for_generated::SseCodec, _, _>(
|
||||
flutter_rust_bridge::for_generated::TaskInfo {
|
||||
debug_name: "SynapseGraph_module_has_data",
|
||||
port: Some(port_),
|
||||
mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal,
|
||||
},
|
||||
move || {
|
||||
let message = unsafe {
|
||||
flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire(
|
||||
ptr_,
|
||||
rust_vec_len_,
|
||||
data_len_,
|
||||
)
|
||||
};
|
||||
let mut deserializer =
|
||||
flutter_rust_bridge::for_generated::SseDeserializer::new(message);
|
||||
let api_that = <RustOpaqueMoi<
|
||||
flutter_rust_bridge::for_generated::RustAutoOpaqueInner<SynapseGraph>,
|
||||
>>::sse_decode(&mut deserializer);
|
||||
let api_id = <String>::sse_decode(&mut deserializer);
|
||||
deserializer.end();
|
||||
move |context| {
|
||||
transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>(
|
||||
(move || {
|
||||
let mut api_that_guard = None;
|
||||
let decode_indices_ =
|
||||
flutter_rust_bridge::for_generated::lockable_compute_decode_order(
|
||||
vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new(
|
||||
&api_that, 0, false,
|
||||
)],
|
||||
);
|
||||
for i in decode_indices_ {
|
||||
match i {
|
||||
0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
let api_that_guard = api_that_guard.unwrap();
|
||||
let output_ok = crate::api::graph::SynapseGraph::module_has_data(
|
||||
&*api_that_guard,
|
||||
api_id,
|
||||
)?;
|
||||
std::result::Result::Ok(output_ok)
|
||||
})(),
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
fn wire__crate__api__graph__SynapseGraph_modules_impl(
|
||||
port_: flutter_rust_bridge::for_generated::MessagePort,
|
||||
ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr,
|
||||
rust_vec_len_: i32,
|
||||
data_len_: i32,
|
||||
) {
|
||||
FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::<flutter_rust_bridge::for_generated::SseCodec, _, _>(
|
||||
flutter_rust_bridge::for_generated::TaskInfo {
|
||||
debug_name: "SynapseGraph_modules",
|
||||
port: Some(port_),
|
||||
mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal,
|
||||
},
|
||||
move || {
|
||||
let message = unsafe {
|
||||
flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire(
|
||||
ptr_,
|
||||
rust_vec_len_,
|
||||
data_len_,
|
||||
)
|
||||
};
|
||||
let mut deserializer =
|
||||
flutter_rust_bridge::for_generated::SseDeserializer::new(message);
|
||||
let api_that = <RustOpaqueMoi<
|
||||
flutter_rust_bridge::for_generated::RustAutoOpaqueInner<SynapseGraph>,
|
||||
>>::sse_decode(&mut deserializer);
|
||||
deserializer.end();
|
||||
move |context| {
|
||||
transform_result_sse::<_, ()>((move || {
|
||||
let mut api_that_guard = None;
|
||||
let decode_indices_ =
|
||||
flutter_rust_bridge::for_generated::lockable_compute_decode_order(vec![
|
||||
flutter_rust_bridge::for_generated::LockableOrderInfo::new(
|
||||
&api_that, 0, false,
|
||||
),
|
||||
]);
|
||||
for i in decode_indices_ {
|
||||
match i {
|
||||
0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
let api_that_guard = api_that_guard.unwrap();
|
||||
let output_ok =
|
||||
Ok::<_, ()>(crate::api::graph::SynapseGraph::modules(&*api_that_guard))?;
|
||||
std::result::Result::Ok(output_ok)
|
||||
})())
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
fn wire__crate__api__graph__SynapseGraph_move_block_impl(
|
||||
port_: flutter_rust_bridge::for_generated::MessagePort,
|
||||
ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr,
|
||||
@@ -3231,6 +3505,63 @@ fn wire__crate__api__graph__SynapseGraph_set_hub_description_impl(
|
||||
},
|
||||
)
|
||||
}
|
||||
fn wire__crate__api__graph__SynapseGraph_set_module_enabled_impl(
|
||||
port_: flutter_rust_bridge::for_generated::MessagePort,
|
||||
ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr,
|
||||
rust_vec_len_: i32,
|
||||
data_len_: i32,
|
||||
) {
|
||||
FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::<flutter_rust_bridge::for_generated::SseCodec, _, _>(
|
||||
flutter_rust_bridge::for_generated::TaskInfo {
|
||||
debug_name: "SynapseGraph_set_module_enabled",
|
||||
port: Some(port_),
|
||||
mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal,
|
||||
},
|
||||
move || {
|
||||
let message = unsafe {
|
||||
flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire(
|
||||
ptr_,
|
||||
rust_vec_len_,
|
||||
data_len_,
|
||||
)
|
||||
};
|
||||
let mut deserializer =
|
||||
flutter_rust_bridge::for_generated::SseDeserializer::new(message);
|
||||
let api_that = <RustOpaqueMoi<
|
||||
flutter_rust_bridge::for_generated::RustAutoOpaqueInner<SynapseGraph>,
|
||||
>>::sse_decode(&mut deserializer);
|
||||
let api_id = <String>::sse_decode(&mut deserializer);
|
||||
let api_enabled = <bool>::sse_decode(&mut deserializer);
|
||||
deserializer.end();
|
||||
move |context| {
|
||||
transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>(
|
||||
(move || {
|
||||
let mut api_that_guard = None;
|
||||
let decode_indices_ =
|
||||
flutter_rust_bridge::for_generated::lockable_compute_decode_order(
|
||||
vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new(
|
||||
&api_that, 0, false,
|
||||
)],
|
||||
);
|
||||
for i in decode_indices_ {
|
||||
match i {
|
||||
0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
let api_that_guard = api_that_guard.unwrap();
|
||||
let output_ok = crate::api::graph::SynapseGraph::set_module_enabled(
|
||||
&*api_that_guard,
|
||||
api_id,
|
||||
api_enabled,
|
||||
)?;
|
||||
std::result::Result::Ok(output_ok)
|
||||
})(),
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
fn wire__crate__api__graph__SynapseGraph_set_page_tags_impl(
|
||||
port_: flutter_rust_bridge::for_generated::MessagePort,
|
||||
ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr,
|
||||
@@ -3402,6 +3733,58 @@ fn wire__crate__api__graph__SynapseGraph_set_type_icon_impl(
|
||||
},
|
||||
)
|
||||
}
|
||||
fn wire__crate__api__graph__SynapseGraph_stop_module_impl(
|
||||
port_: flutter_rust_bridge::for_generated::MessagePort,
|
||||
ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr,
|
||||
rust_vec_len_: i32,
|
||||
data_len_: i32,
|
||||
) {
|
||||
FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::<flutter_rust_bridge::for_generated::SseCodec, _, _>(
|
||||
flutter_rust_bridge::for_generated::TaskInfo {
|
||||
debug_name: "SynapseGraph_stop_module",
|
||||
port: Some(port_),
|
||||
mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal,
|
||||
},
|
||||
move || {
|
||||
let message = unsafe {
|
||||
flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire(
|
||||
ptr_,
|
||||
rust_vec_len_,
|
||||
data_len_,
|
||||
)
|
||||
};
|
||||
let mut deserializer =
|
||||
flutter_rust_bridge::for_generated::SseDeserializer::new(message);
|
||||
let api_that = <RustOpaqueMoi<
|
||||
flutter_rust_bridge::for_generated::RustAutoOpaqueInner<SynapseGraph>,
|
||||
>>::sse_decode(&mut deserializer);
|
||||
let api_id = <String>::sse_decode(&mut deserializer);
|
||||
deserializer.end();
|
||||
move |context| {
|
||||
transform_result_sse::<_, ()>((move || {
|
||||
let mut api_that_guard = None;
|
||||
let decode_indices_ =
|
||||
flutter_rust_bridge::for_generated::lockable_compute_decode_order(vec![
|
||||
flutter_rust_bridge::for_generated::LockableOrderInfo::new(
|
||||
&api_that, 0, false,
|
||||
),
|
||||
]);
|
||||
for i in decode_indices_ {
|
||||
match i {
|
||||
0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
let api_that_guard = api_that_guard.unwrap();
|
||||
let output_ok = Ok::<_, ()>({
|
||||
crate::api::graph::SynapseGraph::stop_module(&*api_that_guard, api_id);
|
||||
})?;
|
||||
std::result::Result::Ok(output_ok)
|
||||
})())
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
fn wire__crate__api__graph__SynapseGraph_tag_catalog_impl(
|
||||
port_: flutter_rust_bridge::for_generated::MessagePort,
|
||||
ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr,
|
||||
@@ -3610,6 +3993,63 @@ fn wire__crate__api__graph__SynapseGraph_type_catalog_impl(
|
||||
},
|
||||
)
|
||||
}
|
||||
fn wire__crate__api__graph__SynapseGraph_uninstall_module_impl(
|
||||
port_: flutter_rust_bridge::for_generated::MessagePort,
|
||||
ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr,
|
||||
rust_vec_len_: i32,
|
||||
data_len_: i32,
|
||||
) {
|
||||
FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::<flutter_rust_bridge::for_generated::SseCodec, _, _>(
|
||||
flutter_rust_bridge::for_generated::TaskInfo {
|
||||
debug_name: "SynapseGraph_uninstall_module",
|
||||
port: Some(port_),
|
||||
mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal,
|
||||
},
|
||||
move || {
|
||||
let message = unsafe {
|
||||
flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire(
|
||||
ptr_,
|
||||
rust_vec_len_,
|
||||
data_len_,
|
||||
)
|
||||
};
|
||||
let mut deserializer =
|
||||
flutter_rust_bridge::for_generated::SseDeserializer::new(message);
|
||||
let api_that = <RustOpaqueMoi<
|
||||
flutter_rust_bridge::for_generated::RustAutoOpaqueInner<SynapseGraph>,
|
||||
>>::sse_decode(&mut deserializer);
|
||||
let api_id = <String>::sse_decode(&mut deserializer);
|
||||
let api_delete_data = <bool>::sse_decode(&mut deserializer);
|
||||
deserializer.end();
|
||||
move |context| {
|
||||
transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>(
|
||||
(move || {
|
||||
let mut api_that_guard = None;
|
||||
let decode_indices_ =
|
||||
flutter_rust_bridge::for_generated::lockable_compute_decode_order(
|
||||
vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new(
|
||||
&api_that, 0, false,
|
||||
)],
|
||||
);
|
||||
for i in decode_indices_ {
|
||||
match i {
|
||||
0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
let api_that_guard = api_that_guard.unwrap();
|
||||
let output_ok = crate::api::graph::SynapseGraph::uninstall_module(
|
||||
&*api_that_guard,
|
||||
api_id,
|
||||
api_delete_data,
|
||||
)?;
|
||||
std::result::Result::Ok(output_ok)
|
||||
})(),
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
fn wire__crate__api__graph__SynapseGraph_update_block_impl(
|
||||
port_: flutter_rust_bridge::for_generated::MessagePort,
|
||||
ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr,
|
||||
@@ -4095,6 +4535,30 @@ impl SseDecode for Vec<crate::api::dto::LegacyCandidate> {
|
||||
}
|
||||
}
|
||||
|
||||
impl SseDecode for Vec<crate::api::dto::ModuleDto> {
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self {
|
||||
let mut len_ = <i32>::sse_decode(deserializer);
|
||||
let mut ans_ = Vec::with_capacity(len_ as usize);
|
||||
for idx_ in 0..len_ {
|
||||
ans_.push(<crate::api::dto::ModuleDto>::sse_decode(deserializer));
|
||||
}
|
||||
return ans_;
|
||||
}
|
||||
}
|
||||
|
||||
impl SseDecode for Vec<crate::api::dto::ModuleViewDto> {
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self {
|
||||
let mut len_ = <i32>::sse_decode(deserializer);
|
||||
let mut ans_ = Vec::with_capacity(len_ as usize);
|
||||
for idx_ in 0..len_ {
|
||||
ans_.push(<crate::api::dto::ModuleViewDto>::sse_decode(deserializer));
|
||||
}
|
||||
return ans_;
|
||||
}
|
||||
}
|
||||
|
||||
impl SseDecode for Vec<crate::api::dto::NamespaceEntry> {
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self {
|
||||
@@ -4227,6 +4691,50 @@ impl SseDecode for Vec<crate::api::dto::TitleHit> {
|
||||
}
|
||||
}
|
||||
|
||||
impl SseDecode for crate::api::dto::ModuleDto {
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self {
|
||||
let mut var_id = <String>::sse_decode(deserializer);
|
||||
let mut var_name = <String>::sse_decode(deserializer);
|
||||
let mut var_version = <String>::sse_decode(deserializer);
|
||||
let mut var_description = <String>::sse_decode(deserializer);
|
||||
let mut var_author = <String>::sse_decode(deserializer);
|
||||
let mut var_permissions = <Vec<String>>::sse_decode(deserializer);
|
||||
let mut var_views = <Vec<crate::api::dto::ModuleViewDto>>::sse_decode(deserializer);
|
||||
let mut var_macros = <Vec<String>>::sse_decode(deserializer);
|
||||
let mut var_tickSeconds = <Option<u32>>::sse_decode(deserializer);
|
||||
let mut var_enabled = <bool>::sse_decode(deserializer);
|
||||
let mut var_size = <u64>::sse_decode(deserializer);
|
||||
return crate::api::dto::ModuleDto {
|
||||
id: var_id,
|
||||
name: var_name,
|
||||
version: var_version,
|
||||
description: var_description,
|
||||
author: var_author,
|
||||
permissions: var_permissions,
|
||||
views: var_views,
|
||||
macros: var_macros,
|
||||
tick_seconds: var_tickSeconds,
|
||||
enabled: var_enabled,
|
||||
size: var_size,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
impl SseDecode for crate::api::dto::ModuleViewDto {
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self {
|
||||
let mut var_id = <String>::sse_decode(deserializer);
|
||||
let mut var_title = <String>::sse_decode(deserializer);
|
||||
let mut var_icon = <Option<String>>::sse_decode(deserializer);
|
||||
return crate::api::dto::ModuleViewDto {
|
||||
id: var_id,
|
||||
title: var_title,
|
||||
icon: var_icon,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
impl SseDecode for crate::api::dto::NamespaceEntry {
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self {
|
||||
@@ -4623,189 +5131,232 @@ fn pde_ffi_dispatcher_primary_impl(
|
||||
rust_vec_len,
|
||||
data_len,
|
||||
),
|
||||
27 => wire__crate__api__graph__SynapseGraph_journal_impl(port, ptr, rust_vec_len, data_len),
|
||||
28 => wire__crate__api__graph__SynapseGraph_journal_neighbors_impl(
|
||||
27 => wire__crate__api__graph__SynapseGraph_inspect_module_impl(
|
||||
port,
|
||||
ptr,
|
||||
rust_vec_len,
|
||||
data_len,
|
||||
),
|
||||
29 => {
|
||||
wire__crate__api__graph__SynapseGraph_journals_impl(port, ptr, rust_vec_len, data_len)
|
||||
}
|
||||
30 => wire__crate__api__graph__SynapseGraph_legacy_candidates_impl(
|
||||
28 => wire__crate__api__graph__SynapseGraph_install_module_impl(
|
||||
port,
|
||||
ptr,
|
||||
rust_vec_len,
|
||||
data_len,
|
||||
),
|
||||
29 => wire__crate__api__graph__SynapseGraph_journal_impl(port, ptr, rust_vec_len, data_len),
|
||||
30 => wire__crate__api__graph__SynapseGraph_journal_neighbors_impl(
|
||||
port,
|
||||
ptr,
|
||||
rust_vec_len,
|
||||
data_len,
|
||||
),
|
||||
31 => {
|
||||
wire__crate__api__graph__SynapseGraph_list_pages_impl(port, ptr, rust_vec_len, data_len)
|
||||
wire__crate__api__graph__SynapseGraph_journals_impl(port, ptr, rust_vec_len, data_len)
|
||||
}
|
||||
32 => wire__crate__api__graph__SynapseGraph_merge_block_impl(
|
||||
32 => wire__crate__api__graph__SynapseGraph_legacy_candidates_impl(
|
||||
port,
|
||||
ptr,
|
||||
rust_vec_len,
|
||||
data_len,
|
||||
),
|
||||
33 => {
|
||||
wire__crate__api__graph__SynapseGraph_list_pages_impl(port, ptr, rust_vec_len, data_len)
|
||||
}
|
||||
34 => wire__crate__api__graph__SynapseGraph_merge_block_impl(
|
||||
port,
|
||||
ptr,
|
||||
rust_vec_len,
|
||||
data_len,
|
||||
),
|
||||
35 => wire__crate__api__graph__SynapseGraph_module_call_impl(
|
||||
port,
|
||||
ptr,
|
||||
rust_vec_len,
|
||||
data_len,
|
||||
),
|
||||
36 => wire__crate__api__graph__SynapseGraph_module_has_data_impl(
|
||||
port,
|
||||
ptr,
|
||||
rust_vec_len,
|
||||
data_len,
|
||||
),
|
||||
37 => wire__crate__api__graph__SynapseGraph_modules_impl(port, ptr, rust_vec_len, data_len),
|
||||
38 => {
|
||||
wire__crate__api__graph__SynapseGraph_move_block_impl(port, ptr, rust_vec_len, data_len)
|
||||
}
|
||||
34 => wire__crate__api__graph__SynapseGraph_open_impl(port, ptr, rust_vec_len, data_len),
|
||||
35 => {
|
||||
39 => wire__crate__api__graph__SynapseGraph_open_impl(port, ptr, rust_vec_len, data_len),
|
||||
40 => {
|
||||
wire__crate__api__graph__SynapseGraph_open_page_impl(port, ptr, rust_vec_len, data_len)
|
||||
}
|
||||
36 => wire__crate__api__graph__SynapseGraph_outdent_block_impl(
|
||||
41 => wire__crate__api__graph__SynapseGraph_outdent_block_impl(
|
||||
port,
|
||||
ptr,
|
||||
rust_vec_len,
|
||||
data_len,
|
||||
),
|
||||
37 => wire__crate__api__graph__SynapseGraph_outline_impl(port, ptr, rust_vec_len, data_len),
|
||||
38 => wire__crate__api__graph__SynapseGraph_page_impl(port, ptr, rust_vec_len, data_len),
|
||||
39 => wire__crate__api__graph__SynapseGraph_page_by_title_impl(
|
||||
42 => wire__crate__api__graph__SynapseGraph_outline_impl(port, ptr, rust_vec_len, data_len),
|
||||
43 => wire__crate__api__graph__SynapseGraph_page_impl(port, ptr, rust_vec_len, data_len),
|
||||
44 => wire__crate__api__graph__SynapseGraph_page_by_title_impl(
|
||||
port,
|
||||
ptr,
|
||||
rust_vec_len,
|
||||
data_len,
|
||||
),
|
||||
40 => wire__crate__api__graph__SynapseGraph_page_structure_impl(
|
||||
45 => wire__crate__api__graph__SynapseGraph_page_structure_impl(
|
||||
port,
|
||||
ptr,
|
||||
rust_vec_len,
|
||||
data_len,
|
||||
),
|
||||
41 => wire__crate__api__graph__SynapseGraph_pages_with_tag_impl(
|
||||
46 => wire__crate__api__graph__SynapseGraph_pages_with_tag_impl(
|
||||
port,
|
||||
ptr,
|
||||
rust_vec_len,
|
||||
data_len,
|
||||
),
|
||||
42 => wire__crate__api__graph__SynapseGraph_purge_pages_impl(
|
||||
47 => wire__crate__api__graph__SynapseGraph_purge_pages_impl(
|
||||
port,
|
||||
ptr,
|
||||
rust_vec_len,
|
||||
data_len,
|
||||
),
|
||||
43 => wire__crate__api__graph__SynapseGraph_put_asset_bytes_impl(
|
||||
48 => wire__crate__api__graph__SynapseGraph_put_asset_bytes_impl(
|
||||
port,
|
||||
ptr,
|
||||
rust_vec_len,
|
||||
data_len,
|
||||
),
|
||||
44 => wire__crate__api__graph__SynapseGraph_put_asset_file_impl(
|
||||
49 => wire__crate__api__graph__SynapseGraph_put_asset_file_impl(
|
||||
port,
|
||||
ptr,
|
||||
rust_vec_len,
|
||||
data_len,
|
||||
),
|
||||
45 => wire__crate__api__graph__SynapseGraph_record_visit_impl(
|
||||
50 => wire__crate__api__graph__SynapseGraph_record_visit_impl(
|
||||
port,
|
||||
ptr,
|
||||
rust_vec_len,
|
||||
data_len,
|
||||
),
|
||||
46 => wire__crate__api__graph__SynapseGraph_related_impl(port, ptr, rust_vec_len, data_len),
|
||||
47 => wire__crate__api__graph__SynapseGraph_remove_alias_impl(
|
||||
51 => wire__crate__api__graph__SynapseGraph_related_impl(port, ptr, rust_vec_len, data_len),
|
||||
52 => wire__crate__api__graph__SynapseGraph_remove_alias_impl(
|
||||
port,
|
||||
ptr,
|
||||
rust_vec_len,
|
||||
data_len,
|
||||
),
|
||||
48 => wire__crate__api__graph__SynapseGraph_remove_from_hub_impl(
|
||||
53 => wire__crate__api__graph__SynapseGraph_remove_from_hub_impl(
|
||||
port,
|
||||
ptr,
|
||||
rust_vec_len,
|
||||
data_len,
|
||||
),
|
||||
49 => wire__crate__api__graph__SynapseGraph_remove_page_tag_impl(
|
||||
54 => wire__crate__api__graph__SynapseGraph_remove_page_tag_impl(
|
||||
port,
|
||||
ptr,
|
||||
rust_vec_len,
|
||||
data_len,
|
||||
),
|
||||
50 => {
|
||||
55 => {
|
||||
wire__crate__api__graph__SynapseGraph_remove_tag_impl(port, ptr, rust_vec_len, data_len)
|
||||
}
|
||||
51 => wire__crate__api__graph__SynapseGraph_remove_type_impl(
|
||||
56 => wire__crate__api__graph__SynapseGraph_remove_type_impl(
|
||||
port,
|
||||
ptr,
|
||||
rust_vec_len,
|
||||
data_len,
|
||||
),
|
||||
52 => wire__crate__api__graph__SynapseGraph_rename_page_impl(
|
||||
57 => wire__crate__api__graph__SynapseGraph_rename_page_impl(
|
||||
port,
|
||||
ptr,
|
||||
rust_vec_len,
|
||||
data_len,
|
||||
),
|
||||
53 => {
|
||||
58 => {
|
||||
wire__crate__api__graph__SynapseGraph_rename_tag_impl(port, ptr, rust_vec_len, data_len)
|
||||
}
|
||||
54 => wire__crate__api__graph__SynapseGraph_rename_type_impl(
|
||||
59 => wire__crate__api__graph__SynapseGraph_rename_type_impl(
|
||||
port,
|
||||
ptr,
|
||||
rust_vec_len,
|
||||
data_len,
|
||||
),
|
||||
55 => wire__crate__api__graph__SynapseGraph_search_blocks_impl(
|
||||
60 => wire__crate__api__graph__SynapseGraph_search_blocks_impl(
|
||||
port,
|
||||
ptr,
|
||||
rust_vec_len,
|
||||
data_len,
|
||||
),
|
||||
56 => wire__crate__api__graph__SynapseGraph_search_titles_impl(
|
||||
61 => wire__crate__api__graph__SynapseGraph_search_titles_impl(
|
||||
port,
|
||||
ptr,
|
||||
rust_vec_len,
|
||||
data_len,
|
||||
),
|
||||
57 => wire__crate__api__graph__SynapseGraph_set_collapsed_impl(
|
||||
62 => wire__crate__api__graph__SynapseGraph_set_collapsed_impl(
|
||||
port,
|
||||
ptr,
|
||||
rust_vec_len,
|
||||
data_len,
|
||||
),
|
||||
58 => wire__crate__api__graph__SynapseGraph_set_hub_description_impl(
|
||||
63 => wire__crate__api__graph__SynapseGraph_set_hub_description_impl(
|
||||
port,
|
||||
ptr,
|
||||
rust_vec_len,
|
||||
data_len,
|
||||
),
|
||||
59 => wire__crate__api__graph__SynapseGraph_set_page_tags_impl(
|
||||
64 => wire__crate__api__graph__SynapseGraph_set_module_enabled_impl(
|
||||
port,
|
||||
ptr,
|
||||
rust_vec_len,
|
||||
data_len,
|
||||
),
|
||||
60 => wire__crate__api__graph__SynapseGraph_set_page_type_impl(
|
||||
65 => wire__crate__api__graph__SynapseGraph_set_page_tags_impl(
|
||||
port,
|
||||
ptr,
|
||||
rust_vec_len,
|
||||
data_len,
|
||||
),
|
||||
61 => wire__crate__api__graph__SynapseGraph_set_type_icon_impl(
|
||||
66 => wire__crate__api__graph__SynapseGraph_set_page_type_impl(
|
||||
port,
|
||||
ptr,
|
||||
rust_vec_len,
|
||||
data_len,
|
||||
),
|
||||
62 => wire__crate__api__graph__SynapseGraph_tag_catalog_impl(
|
||||
67 => wire__crate__api__graph__SynapseGraph_set_type_icon_impl(
|
||||
port,
|
||||
ptr,
|
||||
rust_vec_len,
|
||||
data_len,
|
||||
),
|
||||
63 => {
|
||||
68 => wire__crate__api__graph__SynapseGraph_stop_module_impl(
|
||||
port,
|
||||
ptr,
|
||||
rust_vec_len,
|
||||
data_len,
|
||||
),
|
||||
69 => wire__crate__api__graph__SynapseGraph_tag_catalog_impl(
|
||||
port,
|
||||
ptr,
|
||||
rust_vec_len,
|
||||
data_len,
|
||||
),
|
||||
70 => {
|
||||
wire__crate__api__graph__SynapseGraph_timeline_impl(port, ptr, rust_vec_len, data_len)
|
||||
}
|
||||
65 => wire__crate__api__graph__SynapseGraph_type_catalog_impl(
|
||||
72 => wire__crate__api__graph__SynapseGraph_type_catalog_impl(
|
||||
port,
|
||||
ptr,
|
||||
rust_vec_len,
|
||||
data_len,
|
||||
),
|
||||
66 => wire__crate__api__graph__SynapseGraph_update_block_impl(
|
||||
73 => wire__crate__api__graph__SynapseGraph_uninstall_module_impl(
|
||||
port,
|
||||
ptr,
|
||||
rust_vec_len,
|
||||
data_len,
|
||||
),
|
||||
74 => wire__crate__api__graph__SynapseGraph_update_block_impl(
|
||||
port,
|
||||
ptr,
|
||||
rust_vec_len,
|
||||
@@ -4826,7 +5377,7 @@ fn pde_ffi_dispatcher_sync_impl(
|
||||
1 => wire__crate__api__layout__ForceLayout_new_impl(ptr, rust_vec_len, data_len),
|
||||
10 => wire__crate__api__graph__SynapseGraph_asset_path_impl(ptr, rust_vec_len, data_len),
|
||||
20 => wire__crate__api__graph__SynapseGraph_dir_impl(ptr, rust_vec_len, data_len),
|
||||
64 => wire__crate__api__graph__SynapseGraph_today_impl(ptr, rust_vec_len, data_len),
|
||||
71 => wire__crate__api__graph__SynapseGraph_today_impl(ptr, rust_vec_len, data_len),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
@@ -5131,6 +5682,53 @@ impl flutter_rust_bridge::IntoIntoDart<crate::api::dto::LegacyCandidate>
|
||||
}
|
||||
}
|
||||
// Codec=Dco (DartCObject based), see doc to use other codecs
|
||||
impl flutter_rust_bridge::IntoDart for crate::api::dto::ModuleDto {
|
||||
fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi {
|
||||
[
|
||||
self.id.into_into_dart().into_dart(),
|
||||
self.name.into_into_dart().into_dart(),
|
||||
self.version.into_into_dart().into_dart(),
|
||||
self.description.into_into_dart().into_dart(),
|
||||
self.author.into_into_dart().into_dart(),
|
||||
self.permissions.into_into_dart().into_dart(),
|
||||
self.views.into_into_dart().into_dart(),
|
||||
self.macros.into_into_dart().into_dart(),
|
||||
self.tick_seconds.into_into_dart().into_dart(),
|
||||
self.enabled.into_into_dart().into_dart(),
|
||||
self.size.into_into_dart().into_dart(),
|
||||
]
|
||||
.into_dart()
|
||||
}
|
||||
}
|
||||
impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive for crate::api::dto::ModuleDto {}
|
||||
impl flutter_rust_bridge::IntoIntoDart<crate::api::dto::ModuleDto> for crate::api::dto::ModuleDto {
|
||||
fn into_into_dart(self) -> crate::api::dto::ModuleDto {
|
||||
self
|
||||
}
|
||||
}
|
||||
// Codec=Dco (DartCObject based), see doc to use other codecs
|
||||
impl flutter_rust_bridge::IntoDart for crate::api::dto::ModuleViewDto {
|
||||
fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi {
|
||||
[
|
||||
self.id.into_into_dart().into_dart(),
|
||||
self.title.into_into_dart().into_dart(),
|
||||
self.icon.into_into_dart().into_dart(),
|
||||
]
|
||||
.into_dart()
|
||||
}
|
||||
}
|
||||
impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive
|
||||
for crate::api::dto::ModuleViewDto
|
||||
{
|
||||
}
|
||||
impl flutter_rust_bridge::IntoIntoDart<crate::api::dto::ModuleViewDto>
|
||||
for crate::api::dto::ModuleViewDto
|
||||
{
|
||||
fn into_into_dart(self) -> crate::api::dto::ModuleViewDto {
|
||||
self
|
||||
}
|
||||
}
|
||||
// Codec=Dco (DartCObject based), see doc to use other codecs
|
||||
impl flutter_rust_bridge::IntoDart for crate::api::dto::NamespaceEntry {
|
||||
fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi {
|
||||
[
|
||||
@@ -5673,6 +6271,26 @@ impl SseEncode for Vec<crate::api::dto::LegacyCandidate> {
|
||||
}
|
||||
}
|
||||
|
||||
impl SseEncode for Vec<crate::api::dto::ModuleDto> {
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) {
|
||||
<i32>::sse_encode(self.len() as _, serializer);
|
||||
for item in self {
|
||||
<crate::api::dto::ModuleDto>::sse_encode(item, serializer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl SseEncode for Vec<crate::api::dto::ModuleViewDto> {
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) {
|
||||
<i32>::sse_encode(self.len() as _, serializer);
|
||||
for item in self {
|
||||
<crate::api::dto::ModuleViewDto>::sse_encode(item, serializer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl SseEncode for Vec<crate::api::dto::NamespaceEntry> {
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) {
|
||||
@@ -5783,6 +6401,32 @@ impl SseEncode for Vec<crate::api::dto::TitleHit> {
|
||||
}
|
||||
}
|
||||
|
||||
impl SseEncode for crate::api::dto::ModuleDto {
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) {
|
||||
<String>::sse_encode(self.id, serializer);
|
||||
<String>::sse_encode(self.name, serializer);
|
||||
<String>::sse_encode(self.version, serializer);
|
||||
<String>::sse_encode(self.description, serializer);
|
||||
<String>::sse_encode(self.author, serializer);
|
||||
<Vec<String>>::sse_encode(self.permissions, serializer);
|
||||
<Vec<crate::api::dto::ModuleViewDto>>::sse_encode(self.views, serializer);
|
||||
<Vec<String>>::sse_encode(self.macros, serializer);
|
||||
<Option<u32>>::sse_encode(self.tick_seconds, serializer);
|
||||
<bool>::sse_encode(self.enabled, serializer);
|
||||
<u64>::sse_encode(self.size, serializer);
|
||||
}
|
||||
}
|
||||
|
||||
impl SseEncode for crate::api::dto::ModuleViewDto {
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) {
|
||||
<String>::sse_encode(self.id, serializer);
|
||||
<String>::sse_encode(self.title, serializer);
|
||||
<Option<String>>::sse_encode(self.icon, serializer);
|
||||
}
|
||||
}
|
||||
|
||||
impl SseEncode for crate::api::dto::NamespaceEntry {
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) {
|
||||
|
||||
@@ -588,3 +588,34 @@ fn a_hub_tag_and_a_same_name_type_need_no_tag_node_beside_the_hub() {
|
||||
("anime", 2)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn modules_install_and_answer_requests_over_ffi() {
|
||||
let (_d, g) = open();
|
||||
let wasm = std::fs::read(concat!(
|
||||
env!("CARGO_MANIFEST_DIR"),
|
||||
"/../../app/assets/modules/synapse.secrets.wasm"
|
||||
))
|
||||
.unwrap();
|
||||
let m = g.inspect_module(wasm.clone()).unwrap();
|
||||
assert_eq!(m.id, "synapse.secrets");
|
||||
assert_eq!(m.views[0].id, "vault");
|
||||
assert_eq!(m.macros, ["secret"]);
|
||||
assert!(g.install_module(wasm.clone(), vec![]).is_err());
|
||||
assert!(
|
||||
g.install_module(wasm.clone(), vec!["storage".into(), "nope".into()])
|
||||
.is_err()
|
||||
);
|
||||
let m = g.install_module(wasm, m.permissions.clone()).unwrap();
|
||||
assert!(m.enabled);
|
||||
assert_eq!(g.modules().len(), 1);
|
||||
let r = g
|
||||
.module_call(m.id.clone(), r#"{"op":"render","view":"vault"}"#.into())
|
||||
.unwrap();
|
||||
assert!(r.contains("Create vault"));
|
||||
assert!(g.module_call(m.id.clone(), "not json".into()).is_err());
|
||||
g.set_module_enabled(m.id.clone(), false).unwrap();
|
||||
assert!(g.module_call(m.id.clone(), "{}".into()).is_err());
|
||||
g.uninstall_module(m.id, true).unwrap();
|
||||
assert!(g.modules().is_empty());
|
||||
}
|
||||
@@ -202,7 +202,10 @@ impl History {
|
||||
Op::DeletePage { id } => touched.extend(graph.hub_members(id)?),
|
||||
// Deletions and moves do not say which page lost a block; those
|
||||
// pages are caught by the `updated_at` scan below.
|
||||
Op::DeleteBlock { .. } | Op::PutAsset { .. } | Op::PutTypeDef { .. } => {}
|
||||
Op::DeleteBlock { .. }
|
||||
| Op::PutAsset { .. }
|
||||
| Op::PutTypeDef { .. }
|
||||
| Op::PutModuleData { .. } => {}
|
||||
// The previous owner of an alias is unknown.
|
||||
Op::SetAlias { .. } => everything = true,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
[package]
|
||||
name = "synapse-modules"
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
description = "Sandboxed WebAssembly modules for Synapse: manifest, permissions, host API, registry"
|
||||
|
||||
[dependencies]
|
||||
argon2 = "0.6"
|
||||
base64 = "0.22"
|
||||
chacha20poly1305 = "0.11"
|
||||
getrandom = "0.4"
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
synapse-core.workspace = true
|
||||
thiserror.workspace = true
|
||||
# Portable loop dispatch: the default tail-call dispatch overflows the stack in debug builds
|
||||
# and depends on the optimiser per target (Android, Windows); hot paths (crypto) are native.
|
||||
wasmi = { version = "2", default-features = false, features = ["std", "stable", "validate", "portable-dispatch"] }
|
||||
zeroize = "1"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
wat = "1"
|
||||
@@ -0,0 +1,229 @@
|
||||
//! Host-side cryptography for modules (`crypto` permission): Argon2id key derivation and
|
||||
//! XChaCha20-Poly1305 authenticated encryption. Keys never enter the module: it gets opaque
|
||||
//! handles into a per-instance [`Keyring`], whose keys are zeroed when dropped.
|
||||
|
||||
use crate::{Error, Result};
|
||||
use argon2::{Algorithm, Argon2, Params, Version};
|
||||
use chacha20poly1305::XChaCha20Poly1305;
|
||||
use chacha20poly1305::aead::{Aead, KeyInit, Payload};
|
||||
use std::collections::HashMap;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
pub const KEY_LEN: usize = 32;
|
||||
pub const NONCE_LEN: usize = 24;
|
||||
/// Upper bounds for Argon2id parameters a module may ask for (memory in KiB).
|
||||
pub const MAX_KDF_MEMORY_KIB: u32 = 128 * 1024;
|
||||
pub const MAX_KDF_ITERATIONS: u32 = 10;
|
||||
pub const MAX_KDF_LANES: u32 = 4;
|
||||
/// Largest plaintext or ciphertext handled in one call.
|
||||
pub const MAX_CRYPTO_INPUT: usize = 1 << 20;
|
||||
const MAX_KEYS: usize = 64;
|
||||
/// Associated data prefix reserved for key wrapping, so data sealed with [`Keyring::seal`]
|
||||
/// can never be unwrapped as a key (importing a key the module knows) and a wrapped key can
|
||||
/// never be opened as data (exporting it).
|
||||
const WRAP_AAD: &[u8] = b"synapse.wrap\0";
|
||||
|
||||
fn wrap_aad(aad: &[u8]) -> Vec<u8> {
|
||||
[WRAP_AAD, aad].concat()
|
||||
}
|
||||
|
||||
type Key = Zeroizing<[u8; KEY_LEN]>;
|
||||
|
||||
pub fn random_bytes(n: usize) -> Result<Vec<u8>> {
|
||||
let mut v = vec![0u8; n];
|
||||
getrandom::fill(&mut v).map_err(|e| Error::Host(format!("no randomness: {e}")))?;
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
fn random_key() -> Result<Key> {
|
||||
let mut k = Zeroizing::new([0u8; KEY_LEN]);
|
||||
getrandom::fill(k.as_mut()).map_err(|e| Error::Host(format!("no randomness: {e}")))?;
|
||||
Ok(k)
|
||||
}
|
||||
|
||||
/// Keys of one module instance, addressed by small integer handles.
|
||||
#[derive(Default)]
|
||||
pub struct Keyring {
|
||||
keys: HashMap<u32, Key>,
|
||||
next: u32,
|
||||
}
|
||||
|
||||
impl Keyring {
|
||||
fn insert(&mut self, key: Key) -> Result<u32> {
|
||||
if self.keys.len() >= MAX_KEYS {
|
||||
return Err(Error::Invalid("too many keys; forget unused ones".into()));
|
||||
}
|
||||
self.next = self.next.wrapping_add(1).max(1);
|
||||
self.keys.insert(self.next, key);
|
||||
Ok(self.next)
|
||||
}
|
||||
|
||||
fn get(&self, handle: u32) -> Result<&Key> {
|
||||
self.keys
|
||||
.get(&handle)
|
||||
.ok_or_else(|| Error::Invalid(format!("unknown key handle {handle}")))
|
||||
}
|
||||
|
||||
/// Derives a key from a password with Argon2id.
|
||||
pub fn derive(
|
||||
&mut self,
|
||||
password: &str,
|
||||
salt: &[u8],
|
||||
memory_kib: u32,
|
||||
iterations: u32,
|
||||
lanes: u32,
|
||||
) -> Result<u32> {
|
||||
if memory_kib > MAX_KDF_MEMORY_KIB
|
||||
|| iterations > MAX_KDF_ITERATIONS
|
||||
|| lanes > MAX_KDF_LANES
|
||||
|| !(8..=64).contains(&salt.len())
|
||||
{
|
||||
return Err(Error::Invalid("Argon2 parameters out of range".into()));
|
||||
}
|
||||
let params = Params::new(memory_kib, iterations, lanes, Some(KEY_LEN))
|
||||
.map_err(|e| Error::Invalid(format!("Argon2 parameters: {e}")))?;
|
||||
let mut key = Zeroizing::new([0u8; KEY_LEN]);
|
||||
Argon2::new(Algorithm::Argon2id, Version::V0x13, params)
|
||||
.hash_password_into(password.as_bytes(), salt, key.as_mut())
|
||||
.map_err(|e| Error::Host(format!("Argon2: {e}")))?;
|
||||
self.insert(key)
|
||||
}
|
||||
|
||||
/// A new random key.
|
||||
pub fn generate(&mut self) -> Result<u32> {
|
||||
let k = random_key()?;
|
||||
self.insert(k)
|
||||
}
|
||||
|
||||
/// Encrypts with a fresh random nonce; returns `nonce || ciphertext`.
|
||||
pub fn seal(&self, key: u32, plaintext: &[u8], aad: &[u8]) -> Result<Vec<u8>> {
|
||||
if aad.starts_with(WRAP_AAD) {
|
||||
return Err(Error::Invalid("reserved associated data".into()));
|
||||
}
|
||||
self.seal_raw(key, plaintext, aad)
|
||||
}
|
||||
|
||||
fn seal_raw(&self, key: u32, plaintext: &[u8], aad: &[u8]) -> Result<Vec<u8>> {
|
||||
if plaintext.len() > MAX_CRYPTO_INPUT {
|
||||
return Err(Error::Invalid("plaintext too large".into()));
|
||||
}
|
||||
let cipher = XChaCha20Poly1305::new_from_slice(self.get(key)?.as_ref())
|
||||
.map_err(|_| Error::Host("bad key length".into()))?;
|
||||
let nonce = random_bytes(NONCE_LEN)?;
|
||||
let ct = cipher
|
||||
.encrypt(
|
||||
nonce.as_slice().try_into().expect("nonce length"),
|
||||
Payload {
|
||||
msg: plaintext,
|
||||
aad,
|
||||
},
|
||||
)
|
||||
.map_err(|_| Error::Host("encryption failed".into()))?;
|
||||
let mut out = nonce;
|
||||
out.extend(ct);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Decrypts `nonce || ciphertext`; fails when the key, data or associated data is wrong.
|
||||
pub fn open(&self, key: u32, data: &[u8], aad: &[u8]) -> Result<Zeroizing<Vec<u8>>> {
|
||||
if aad.starts_with(WRAP_AAD) {
|
||||
return Err(Error::Invalid("reserved associated data".into()));
|
||||
}
|
||||
self.open_raw(key, data, aad)
|
||||
}
|
||||
|
||||
fn open_raw(&self, key: u32, data: &[u8], aad: &[u8]) -> Result<Zeroizing<Vec<u8>>> {
|
||||
if data.len() < NONCE_LEN || data.len() > MAX_CRYPTO_INPUT + NONCE_LEN + 16 {
|
||||
return Err(Error::Decrypt);
|
||||
}
|
||||
let cipher = XChaCha20Poly1305::new_from_slice(self.get(key)?.as_ref())
|
||||
.map_err(|_| Error::Host("bad key length".into()))?;
|
||||
let (nonce, ct) = data.split_at(NONCE_LEN);
|
||||
cipher
|
||||
.decrypt(
|
||||
nonce.try_into().expect("nonce length"),
|
||||
Payload { msg: ct, aad },
|
||||
)
|
||||
.map(Zeroizing::new)
|
||||
.map_err(|_| Error::Decrypt)
|
||||
}
|
||||
|
||||
/// Encrypts key `target` with key `kek` (key wrapping).
|
||||
pub fn wrap(&self, kek: u32, target: u32, aad: &[u8]) -> Result<Vec<u8>> {
|
||||
let t = self.get(target)?.clone();
|
||||
self.seal_raw(kek, t.as_ref(), &wrap_aad(aad))
|
||||
}
|
||||
|
||||
/// Decrypts a wrapped key and returns a handle to it.
|
||||
pub fn unwrap_key(&mut self, kek: u32, data: &[u8], aad: &[u8]) -> Result<u32> {
|
||||
let plain = self.open_raw(kek, data, &wrap_aad(aad))?;
|
||||
let bytes: [u8; KEY_LEN] = plain.as_slice().try_into().map_err(|_| Error::Decrypt)?;
|
||||
self.insert(Zeroizing::new(bytes))
|
||||
}
|
||||
|
||||
pub fn forget(&mut self, handle: u32) {
|
||||
self.keys.remove(&handle);
|
||||
}
|
||||
|
||||
pub fn clear(&mut self) {
|
||||
self.keys.clear();
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.keys.len()
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.keys.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn seal_open_and_wrap_round_trip() {
|
||||
let mut k = Keyring::default();
|
||||
let kek = k
|
||||
.derive("correct horse", b"saltsaltsalt", 1024, 1, 1)
|
||||
.unwrap();
|
||||
let same = k
|
||||
.derive("correct horse", b"saltsaltsalt", 1024, 1, 1)
|
||||
.unwrap();
|
||||
let other = k.derive("wrong", b"saltsaltsalt", 1024, 1, 1).unwrap();
|
||||
let dek = k.generate().unwrap();
|
||||
let wrapped = k.wrap(kek, dek, b"vault").unwrap();
|
||||
let dek2 = k.unwrap_key(same, &wrapped, b"vault").unwrap();
|
||||
assert!(k.unwrap_key(other, &wrapped, b"vault").is_err());
|
||||
assert!(k.unwrap_key(same, &wrapped, b"other aad").is_err());
|
||||
|
||||
let ct = k.seal(dek, b"hunter2", b"entry/1").unwrap();
|
||||
assert_eq!(&**k.open(dek2, &ct, b"entry/1").unwrap(), b"hunter2");
|
||||
assert!(k.open(dek2, &ct, b"entry/2").is_err());
|
||||
let mut tampered = ct.clone();
|
||||
*tampered.last_mut().unwrap() ^= 1;
|
||||
assert!(k.open(dek2, &tampered, b"entry/1").is_err());
|
||||
// Fresh nonce each time.
|
||||
assert_ne!(ct, k.seal(dek, b"hunter2", b"entry/1").unwrap());
|
||||
|
||||
// Wrapped keys and sealed data cannot be confused.
|
||||
assert!(k.open(same, &wrapped, b"vault").is_err());
|
||||
let sealed_key = k.seal(kek, &[7u8; KEY_LEN], b"vault").unwrap();
|
||||
assert!(k.unwrap_key(same, &sealed_key, b"vault").is_err());
|
||||
assert!(k.seal(kek, b"x", b"synapse.wrap\0vault").is_err());
|
||||
|
||||
k.forget(dek2);
|
||||
assert!(k.open(dek2, &ct, b"entry/1").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_extreme_kdf_parameters() {
|
||||
let mut k = Keyring::default();
|
||||
assert!(
|
||||
k.derive("p", b"saltsaltsalt", MAX_KDF_MEMORY_KIB + 1, 1, 1)
|
||||
.is_err()
|
||||
);
|
||||
assert!(k.derive("p", b"short", 1024, 1, 1).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,483 @@
|
||||
//! A running module: a wasmi instance plus the host functions it may call.
|
||||
//!
|
||||
//! ABI (module API v1), all strings UTF-8 JSON:
|
||||
//! - The module exports `memory`, `syn_alloc(len: i32) -> i32` (a buffer the host may fill) and
|
||||
//! `syn_handle(ptr: i32, len: i32)` (handle one request from the app).
|
||||
//! - Inside `syn_handle` the module answers by calling the host import
|
||||
//! `synapse.respond(ptr, len)` once.
|
||||
//! - To use the host it calls `synapse.call(ptr, len) -> i32` with `{"fn": name, ...args}`; the
|
||||
//! host keeps the JSON reply (`{"ok": value}` or `{"error": message}`) and returns its length,
|
||||
//! then the module copies it into its own memory with `synapse.take(ptr)`.
|
||||
//!
|
||||
//! Every request runs with a fuel budget and the instance's memory is capped, so a broken or
|
||||
//! hostile module cannot hang or exhaust the app. A trap discards the instance (its state,
|
||||
//! such as unlocked keys, is lost); the next request starts a fresh one.
|
||||
|
||||
use crate::crypto::{Keyring, random_bytes};
|
||||
use crate::manifest::{Manifest, Permission};
|
||||
use crate::{Error, Result};
|
||||
use base64::Engine as _;
|
||||
use base64::engine::general_purpose::STANDARD as B64;
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use synapse_core::{Graph, Placement};
|
||||
use wasmi::{
|
||||
Caller, Config, Engine, Instance as WasmInstance, Linker, Memory, Module, Store, StoreLimits,
|
||||
StoreLimitsBuilder, TypedFunc,
|
||||
};
|
||||
|
||||
/// Fuel for one request (roughly one unit per instruction).
|
||||
pub const FUEL_PER_REQUEST: u64 = 1_000_000_000;
|
||||
/// Linear memory cap per instance.
|
||||
pub const MAX_MEMORY: usize = 64 << 20;
|
||||
/// Largest request, response or host-call payload.
|
||||
pub const MAX_MESSAGE: usize = 4 << 20;
|
||||
/// Host calls are not free: each costs this much fuel plus [`FUEL_PER_BYTE`] per byte in and
|
||||
/// out, so a loop of host calls runs out of fuel like any other loop.
|
||||
pub const FUEL_PER_HOST_CALL: u64 = 200_000;
|
||||
pub const FUEL_PER_BYTE: u64 = 20;
|
||||
/// Hard caps per request, whatever the fuel: host calls, bytes written to storage and key
|
||||
/// derivations (Argon2 is memory-hard and slow on purpose).
|
||||
pub const MAX_HOST_CALLS: u32 = 5_000;
|
||||
pub const MAX_WRITE_BYTES: usize = 16 << 20;
|
||||
pub const MAX_DERIVES: u32 = 3;
|
||||
/// Storage quota per module (all its live entries).
|
||||
pub const MAX_STORAGE_BYTES: u64 = 64 << 20;
|
||||
pub const MAX_STORAGE_ENTRIES: u64 = 50_000;
|
||||
/// Table elements per instance (tables live outside linear memory).
|
||||
pub const MAX_TABLE_ELEMENTS: usize = 10_000;
|
||||
|
||||
pub(crate) struct HostState {
|
||||
manifest: Manifest,
|
||||
graph: Arc<Mutex<Graph>>,
|
||||
keys: Keyring,
|
||||
pending: Vec<u8>,
|
||||
response: Option<Vec<u8>>,
|
||||
limits: StoreLimits,
|
||||
log: Vec<String>,
|
||||
/// Usage in the current request (reset by [`Running::request`]).
|
||||
calls: u32,
|
||||
written: usize,
|
||||
derives: u32,
|
||||
}
|
||||
|
||||
pub(crate) fn engine() -> Engine {
|
||||
let mut config = Config::default();
|
||||
config.consume_fuel(true);
|
||||
Engine::new(&config)
|
||||
}
|
||||
|
||||
/// Compiles a module (validation only; nothing runs).
|
||||
pub(crate) fn compile(engine: &Engine, wasm: &[u8]) -> Result<Module> {
|
||||
Module::new(engine, wasm).map_err(|e| Error::Invalid(format!("invalid WebAssembly: {e}")))
|
||||
}
|
||||
|
||||
pub struct Running {
|
||||
store: Store<HostState>,
|
||||
memory: Memory,
|
||||
alloc: TypedFunc<i32, i32>,
|
||||
handle: TypedFunc<(i32, i32), ()>,
|
||||
}
|
||||
|
||||
fn memory_of(caller: &Caller<'_, HostState>) -> Result<Memory, wasmi::Error> {
|
||||
caller
|
||||
.get_export("memory")
|
||||
.and_then(|e| e.into_memory())
|
||||
.ok_or_else(|| wasmi::Error::new("module exports no memory"))
|
||||
}
|
||||
|
||||
/// Takes the cost of a host call (and its payload) out of the request's fuel.
|
||||
fn charge(caller: &mut Caller<'_, HostState>, bytes: usize) -> Result<(), wasmi::Error> {
|
||||
let cost = FUEL_PER_HOST_CALL + FUEL_PER_BYTE * bytes as u64;
|
||||
let fuel = caller.get_fuel()?;
|
||||
if fuel < cost {
|
||||
return Err(wasmi::Error::new("out of fuel"));
|
||||
}
|
||||
caller.set_fuel(fuel - cost)
|
||||
}
|
||||
|
||||
fn read_bytes(caller: &Caller<'_, HostState>, ptr: i32, len: i32) -> Result<Vec<u8>, wasmi::Error> {
|
||||
let len = usize::try_from(len).map_err(|_| wasmi::Error::new("negative length"))?;
|
||||
if len > MAX_MESSAGE {
|
||||
return Err(wasmi::Error::new("message too large"));
|
||||
}
|
||||
let mut buf = vec![0u8; len];
|
||||
memory_of(caller)?
|
||||
.read(caller, ptr as u32 as usize, &mut buf)
|
||||
.map_err(|_| wasmi::Error::new("out of bounds read"))?;
|
||||
Ok(buf)
|
||||
}
|
||||
|
||||
impl Running {
|
||||
pub(crate) fn start(
|
||||
engine: &Engine,
|
||||
module: &Module,
|
||||
manifest: Manifest,
|
||||
graph: Arc<Mutex<Graph>>,
|
||||
) -> Result<Self> {
|
||||
let state = HostState {
|
||||
manifest,
|
||||
graph,
|
||||
keys: Keyring::default(),
|
||||
pending: Vec::new(),
|
||||
response: None,
|
||||
limits: StoreLimitsBuilder::new()
|
||||
.memory_size(MAX_MEMORY)
|
||||
.instances(1)
|
||||
.memories(1)
|
||||
.tables(4)
|
||||
.table_elements(MAX_TABLE_ELEMENTS)
|
||||
.trap_on_grow_failure(true)
|
||||
.build(),
|
||||
log: Vec::new(),
|
||||
calls: 0,
|
||||
written: 0,
|
||||
derives: 0,
|
||||
};
|
||||
let mut store = Store::new(engine, state);
|
||||
store.limiter(|s| &mut s.limits);
|
||||
let mut linker = Linker::<HostState>::new(engine);
|
||||
linker
|
||||
.func_wrap(
|
||||
"synapse",
|
||||
"call",
|
||||
|mut caller: Caller<'_, HostState>,
|
||||
ptr: i32,
|
||||
len: i32|
|
||||
-> Result<i32, wasmi::Error> {
|
||||
let req = read_bytes(&caller, ptr, len)?;
|
||||
let state = caller.data_mut();
|
||||
state.calls += 1;
|
||||
if state.calls > MAX_HOST_CALLS {
|
||||
return Err(wasmi::Error::new("too many host calls in one request"));
|
||||
}
|
||||
charge(&mut caller, req.len())?;
|
||||
let reply = match dispatch(caller.data_mut(), &req) {
|
||||
Ok(v) => json!({ "ok": v }),
|
||||
Err(e) => json!({ "error": e.to_string() }),
|
||||
};
|
||||
let bytes =
|
||||
serde_json::to_vec(&reply).map_err(|e| wasmi::Error::new(e.to_string()))?;
|
||||
if bytes.len() > MAX_MESSAGE {
|
||||
return Err(wasmi::Error::new("host reply too large"));
|
||||
}
|
||||
charge(&mut caller, bytes.len())?;
|
||||
let n = bytes.len() as i32;
|
||||
caller.data_mut().pending = bytes;
|
||||
Ok(n)
|
||||
},
|
||||
)
|
||||
.and_then(|l| {
|
||||
l.func_wrap(
|
||||
"synapse",
|
||||
"take",
|
||||
|mut caller: Caller<'_, HostState>, ptr: i32| -> Result<(), wasmi::Error> {
|
||||
let bytes = std::mem::take(&mut caller.data_mut().pending);
|
||||
memory_of(&caller)?
|
||||
.write(&mut caller, ptr as u32 as usize, &bytes)
|
||||
.map_err(|_| wasmi::Error::new("out of bounds write"))
|
||||
},
|
||||
)
|
||||
})
|
||||
.and_then(|l| {
|
||||
l.func_wrap(
|
||||
"synapse",
|
||||
"respond",
|
||||
|mut caller: Caller<'_, HostState>,
|
||||
ptr: i32,
|
||||
len: i32|
|
||||
-> Result<(), wasmi::Error> {
|
||||
let bytes = read_bytes(&caller, ptr, len)?;
|
||||
caller.data_mut().response = Some(bytes);
|
||||
Ok(())
|
||||
},
|
||||
)
|
||||
})
|
||||
.map_err(|e| Error::Host(e.to_string()))?;
|
||||
store
|
||||
.set_fuel(FUEL_PER_REQUEST)
|
||||
.map_err(|e| Error::Host(e.to_string()))?;
|
||||
let instance: WasmInstance = linker
|
||||
.instantiate_and_start(&mut store, module)
|
||||
.map_err(|e| Error::Module(format!("cannot start: {e}")))?;
|
||||
let memory = instance
|
||||
.get_memory(&store, "memory")
|
||||
.ok_or_else(|| Error::Module("exports no memory".into()))?;
|
||||
let alloc = instance
|
||||
.get_typed_func::<i32, i32>(&store, "syn_alloc")
|
||||
.map_err(|e| Error::Module(format!("syn_alloc: {e}")))?;
|
||||
let handle = instance
|
||||
.get_typed_func::<(i32, i32), ()>(&store, "syn_handle")
|
||||
.map_err(|e| Error::Module(format!("syn_handle: {e}")))?;
|
||||
Ok(Self {
|
||||
store,
|
||||
memory,
|
||||
alloc,
|
||||
handle,
|
||||
})
|
||||
}
|
||||
|
||||
/// Sends one request and returns the module's JSON response, with effects the module may
|
||||
/// not cause (by permission) removed. An error means the instance must be discarded.
|
||||
pub fn request(&mut self, request: &Value) -> Result<Value> {
|
||||
let bytes = serde_json::to_vec(request)?;
|
||||
if bytes.len() > MAX_MESSAGE {
|
||||
return Err(Error::Invalid("request too large".into()));
|
||||
}
|
||||
self.store
|
||||
.set_fuel(FUEL_PER_REQUEST)
|
||||
.map_err(|e| Error::Host(e.to_string()))?;
|
||||
let state = self.store.data_mut();
|
||||
state.response = None;
|
||||
state.pending.clear();
|
||||
state.calls = 0;
|
||||
state.written = 0;
|
||||
state.derives = 0;
|
||||
let ptr = self
|
||||
.alloc
|
||||
.call(&mut self.store, bytes.len() as i32)
|
||||
.map_err(|e| Error::Module(format!("syn_alloc failed: {e}")))?;
|
||||
self.memory
|
||||
.write(&mut self.store, ptr as u32 as usize, &bytes)
|
||||
.map_err(|_| Error::Module("syn_alloc returned a bad pointer".into()))?;
|
||||
self.handle
|
||||
.call(&mut self.store, (ptr, bytes.len() as i32))
|
||||
.map_err(|e| Error::Module(format!("crashed: {e}")))?;
|
||||
let out = self
|
||||
.store
|
||||
.data_mut()
|
||||
.response
|
||||
.take()
|
||||
.ok_or_else(|| Error::Module("gave no response".into()))?;
|
||||
let mut v: Value = serde_json::from_slice(&out)
|
||||
.map_err(|e| Error::Module(format!("bad response JSON: {e}")))?;
|
||||
filter_effects(&self.store.data().manifest, &mut v);
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// Log lines written by the module since the last call (for diagnostics).
|
||||
pub fn take_log(&mut self) -> Vec<String> {
|
||||
std::mem::take(&mut self.store.data_mut().log)
|
||||
}
|
||||
|
||||
pub fn keys_held(&self) -> usize {
|
||||
self.store.data().keys.len()
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes `copy` effects from modules without the clipboard permission.
|
||||
fn filter_effects(manifest: &Manifest, v: &mut Value) {
|
||||
if manifest.permissions.contains(&Permission::Clipboard) {
|
||||
return;
|
||||
}
|
||||
if let Some(effects) = v.get_mut("effects").and_then(Value::as_array_mut) {
|
||||
effects.retain(|e| e.get("copy").is_none());
|
||||
}
|
||||
}
|
||||
|
||||
fn need(state: &HostState, p: Permission) -> Result<()> {
|
||||
if state.manifest.permissions.contains(&p) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::Denied(p.as_str().into()))
|
||||
}
|
||||
}
|
||||
|
||||
fn arg_str<'a>(args: &'a Value, name: &str) -> Result<&'a str> {
|
||||
args.get(name)
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(|| Error::Invalid(format!("missing string argument {name:?}")))
|
||||
}
|
||||
|
||||
fn arg_u32(args: &Value, name: &str) -> Result<u32> {
|
||||
args.get(name)
|
||||
.and_then(Value::as_u64)
|
||||
.and_then(|n| u32::try_from(n).ok())
|
||||
.ok_or_else(|| Error::Invalid(format!("missing integer argument {name:?}")))
|
||||
}
|
||||
|
||||
fn arg_b64(args: &Value, name: &str) -> Result<Vec<u8>> {
|
||||
B64.decode(arg_str(args, name)?)
|
||||
.map_err(|_| Error::Invalid(format!("{name:?} is not base64")))
|
||||
}
|
||||
|
||||
fn graph(state: &HostState) -> std::sync::MutexGuard<'_, Graph> {
|
||||
state.graph.lock().unwrap_or_else(|p| p.into_inner())
|
||||
}
|
||||
|
||||
/// Runs one host function for the module.
|
||||
fn dispatch(state: &mut HostState, req: &[u8]) -> Result<Value> {
|
||||
let args: Value =
|
||||
serde_json::from_slice(req).map_err(|e| Error::Invalid(format!("bad call: {e}")))?;
|
||||
let name = arg_str(&args, "fn")?.to_string();
|
||||
let id = state.manifest.id.clone();
|
||||
match name.as_str() {
|
||||
"log" => {
|
||||
let msg = arg_str(&args, "msg")?;
|
||||
if state.log.len() < 200 {
|
||||
state.log.push(msg.chars().take(500).collect());
|
||||
}
|
||||
Ok(Value::Null)
|
||||
}
|
||||
"now" => Ok(json!(
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_millis() as u64)
|
||||
.unwrap_or(0)
|
||||
)),
|
||||
"random" => {
|
||||
let n = arg_u32(&args, "len")? as usize;
|
||||
if n > 4096 {
|
||||
return Err(Error::Invalid("at most 4096 random bytes".into()));
|
||||
}
|
||||
Ok(json!(B64.encode(random_bytes(n)?)))
|
||||
}
|
||||
"kv.get" => {
|
||||
need(state, Permission::Storage)?;
|
||||
Ok(json!(
|
||||
graph(state).module_data(&id, arg_str(&args, "key")?)?
|
||||
))
|
||||
}
|
||||
"kv.set" => {
|
||||
need(state, Permission::Storage)?;
|
||||
let key = arg_str(&args, "key")?;
|
||||
let value = match args.get("value") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(Value::String(s)) => Some(s.as_str()),
|
||||
Some(_) => return Err(Error::Invalid("value must be a string or null".into())),
|
||||
};
|
||||
let size = key.len() + value.map_or(0, str::len);
|
||||
if state.written + size > MAX_WRITE_BYTES {
|
||||
return Err(Error::Invalid(
|
||||
"too much data written in one request".into(),
|
||||
));
|
||||
}
|
||||
state.written += size;
|
||||
let g = graph(state);
|
||||
if let Some(v) = value {
|
||||
let (count, bytes) = g.module_data_usage(&id)?;
|
||||
let old = g.module_data(&id, key)?;
|
||||
let new_count = count + u64::from(old.is_none());
|
||||
let new_bytes = bytes - old.map_or(0, |o| (key.len() + o.len()) as u64)
|
||||
+ (key.len() + v.len()) as u64;
|
||||
if new_count > MAX_STORAGE_ENTRIES || new_bytes > MAX_STORAGE_BYTES {
|
||||
return Err(Error::Invalid("the module's storage quota is full".into()));
|
||||
}
|
||||
}
|
||||
g.set_module_data(&id, key, value)?;
|
||||
Ok(Value::Null)
|
||||
}
|
||||
"kv.list" => {
|
||||
need(state, Permission::Storage)?;
|
||||
let prefix = args.get("prefix").and_then(Value::as_str).unwrap_or("");
|
||||
let rows = graph(state).module_data_list(&id, prefix)?;
|
||||
let mut total = 0;
|
||||
let mut out = Vec::with_capacity(rows.len());
|
||||
for (k, v) in rows {
|
||||
total += k.len() + v.len() + 32;
|
||||
if total > MAX_MESSAGE - 1024 {
|
||||
return Err(Error::Invalid(
|
||||
"too much data to list at once; use a narrower prefix".into(),
|
||||
));
|
||||
}
|
||||
out.push(json!({ "key": k, "value": v }));
|
||||
}
|
||||
Ok(Value::Array(out))
|
||||
}
|
||||
"crypto.derive" => {
|
||||
need(state, Permission::Crypto)?;
|
||||
state.derives += 1;
|
||||
if state.derives > MAX_DERIVES {
|
||||
return Err(Error::Invalid(
|
||||
"too many key derivations in one request".into(),
|
||||
));
|
||||
}
|
||||
let h = state.keys.derive(
|
||||
arg_str(&args, "password")?,
|
||||
&arg_b64(&args, "salt")?,
|
||||
arg_u32(&args, "memory_kib")?,
|
||||
arg_u32(&args, "iterations")?,
|
||||
arg_u32(&args, "lanes")?,
|
||||
)?;
|
||||
Ok(json!(h))
|
||||
}
|
||||
"crypto.generate" => {
|
||||
need(state, Permission::Crypto)?;
|
||||
Ok(json!(state.keys.generate()?))
|
||||
}
|
||||
"crypto.seal" => {
|
||||
need(state, Permission::Crypto)?;
|
||||
let ct = state.keys.seal(
|
||||
arg_u32(&args, "key")?,
|
||||
arg_str(&args, "plaintext")?.as_bytes(),
|
||||
arg_str(&args, "aad")?.as_bytes(),
|
||||
)?;
|
||||
Ok(json!(B64.encode(ct)))
|
||||
}
|
||||
"crypto.open" => {
|
||||
need(state, Permission::Crypto)?;
|
||||
let plain = state.keys.open(
|
||||
arg_u32(&args, "key")?,
|
||||
&arg_b64(&args, "data")?,
|
||||
arg_str(&args, "aad")?.as_bytes(),
|
||||
)?;
|
||||
let text = std::str::from_utf8(&plain).map_err(|_| Error::Decrypt)?;
|
||||
Ok(json!(text))
|
||||
}
|
||||
"crypto.wrap" => {
|
||||
need(state, Permission::Crypto)?;
|
||||
let w = state.keys.wrap(
|
||||
arg_u32(&args, "key")?,
|
||||
arg_u32(&args, "target")?,
|
||||
arg_str(&args, "aad")?.as_bytes(),
|
||||
)?;
|
||||
Ok(json!(B64.encode(w)))
|
||||
}
|
||||
"crypto.unwrap" => {
|
||||
need(state, Permission::Crypto)?;
|
||||
let h = state.keys.unwrap_key(
|
||||
arg_u32(&args, "key")?,
|
||||
&arg_b64(&args, "data")?,
|
||||
arg_str(&args, "aad")?.as_bytes(),
|
||||
)?;
|
||||
Ok(json!(h))
|
||||
}
|
||||
"crypto.forget" => {
|
||||
need(state, Permission::Crypto)?;
|
||||
state.keys.forget(arg_u32(&args, "key")?);
|
||||
Ok(Value::Null)
|
||||
}
|
||||
"crypto.forget_all" => {
|
||||
need(state, Permission::Crypto)?;
|
||||
state.keys.clear();
|
||||
Ok(Value::Null)
|
||||
}
|
||||
"pages.get" => {
|
||||
need(state, Permission::PagesRead)?;
|
||||
let g = graph(state);
|
||||
let Some(page) = g.page_by_title(arg_str(&args, "title")?)? else {
|
||||
return Ok(Value::Null);
|
||||
};
|
||||
let mut md = String::new();
|
||||
for (depth, b) in g.page_tree(page.id)? {
|
||||
for (i, line) in b.content.lines().enumerate() {
|
||||
md.push_str(&" ".repeat(depth));
|
||||
md.push_str(if i == 0 { "- " } else { " " });
|
||||
md.push_str(line);
|
||||
md.push('\n');
|
||||
}
|
||||
}
|
||||
Ok(json!({ "title": page.title, "markdown": md }))
|
||||
}
|
||||
"pages.append" => {
|
||||
need(state, Permission::PagesWrite)?;
|
||||
let title = arg_str(&args, "title")?;
|
||||
let text = arg_str(&args, "text")?;
|
||||
let g = graph(state);
|
||||
let page = g.ensure_page(title, None)?;
|
||||
let b = g.insert_block(page.id, Placement::LastChildOf(None), text)?;
|
||||
Ok(json!({ "page": page.title, "block": b.id.to_string() }))
|
||||
}
|
||||
other => Err(Error::Invalid(format!("unknown host function {other:?}"))),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
//! Sandboxed WebAssembly modules that extend Synapse.
|
||||
//!
|
||||
//! A module is a single `.wasm` file with its [`Manifest`] embedded in a custom section. It
|
||||
//! runs in a wasmi interpreter (no JIT, so it works on every platform the app targets) with a
|
||||
//! fuel budget and a memory cap, and reaches the app only through host functions gated by the
|
||||
//! permissions the user granted at install time. Its UI is data: views and block macros are
|
||||
//! JSON trees the app renders. See `docs/modules.md`.
|
||||
|
||||
pub mod crypto;
|
||||
mod host;
|
||||
pub mod manifest;
|
||||
mod registry;
|
||||
|
||||
pub use host::{
|
||||
FUEL_PER_BYTE, FUEL_PER_HOST_CALL, FUEL_PER_REQUEST, MAX_DERIVES, MAX_HOST_CALLS, MAX_MEMORY,
|
||||
MAX_MESSAGE, MAX_STORAGE_BYTES, MAX_STORAGE_ENTRIES, MAX_TABLE_ELEMENTS, MAX_WRITE_BYTES,
|
||||
Running,
|
||||
};
|
||||
pub use manifest::{API_VERSION, MANIFEST_SECTION, Manifest, Permission, ViewDecl};
|
||||
pub use registry::{ModuleInfo, Registry};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum Error {
|
||||
#[error("invalid: {0}")]
|
||||
Invalid(String),
|
||||
#[error("permission denied: {0}")]
|
||||
Denied(String),
|
||||
#[error("not found: {0}")]
|
||||
NotFound(String),
|
||||
#[error("decryption failed (wrong key or tampered data)")]
|
||||
Decrypt,
|
||||
/// The module misbehaved (trap, out of fuel, bad response); its instance is discarded.
|
||||
#[error("module error: {0}")]
|
||||
Module(String),
|
||||
#[error("host error: {0}")]
|
||||
Host(String),
|
||||
#[error(transparent)]
|
||||
Core(#[from] synapse_core::Error),
|
||||
#[error(transparent)]
|
||||
Io(#[from] std::io::Error),
|
||||
#[error(transparent)]
|
||||
Json(#[from] serde_json::Error),
|
||||
}
|
||||
|
||||
pub type Result<T, E = Error> = std::result::Result<T, E>;
|
||||
@@ -0,0 +1,224 @@
|
||||
//! Module manifest: identity, permissions and contributions, embedded in the `.wasm` file as a
|
||||
//! custom section named [`MANIFEST_SECTION`] holding JSON.
|
||||
|
||||
use crate::{Error, Result};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Name of the custom section that holds the manifest JSON.
|
||||
pub const MANIFEST_SECTION: &str = "synapse.manifest";
|
||||
/// Module API version this host speaks.
|
||||
pub const API_VERSION: u32 = 1;
|
||||
|
||||
/// What a module may do. Host functions behind a permission fail for modules without it.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
pub enum Permission {
|
||||
/// Its own key-value store, synced with the graph.
|
||||
#[serde(rename = "storage")]
|
||||
Storage,
|
||||
/// Key derivation (Argon2id) and authenticated encryption (XChaCha20-Poly1305) done by
|
||||
/// the host; keys stay in the host.
|
||||
#[serde(rename = "crypto")]
|
||||
Crypto,
|
||||
/// Put text on the clipboard (cleared after a delay).
|
||||
#[serde(rename = "clipboard")]
|
||||
Clipboard,
|
||||
/// Read pages.
|
||||
#[serde(rename = "pages:read")]
|
||||
PagesRead,
|
||||
/// Create pages and add blocks to them.
|
||||
#[serde(rename = "pages:write")]
|
||||
PagesWrite,
|
||||
}
|
||||
|
||||
impl Permission {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Permission::Storage => "storage",
|
||||
Permission::Crypto => "crypto",
|
||||
Permission::Clipboard => "clipboard",
|
||||
Permission::PagesRead => "pages:read",
|
||||
Permission::PagesWrite => "pages:write",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse(s: &str) -> Option<Self> {
|
||||
serde_json::from_value(serde_json::Value::String(s.to_string())).ok()
|
||||
}
|
||||
}
|
||||
|
||||
/// A view the module adds to the sidebar, rendered from the UI tree it returns.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ViewDecl {
|
||||
pub id: String,
|
||||
pub title: String,
|
||||
#[serde(default)]
|
||||
pub icon: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Manifest {
|
||||
pub api: u32,
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub version: String,
|
||||
#[serde(default)]
|
||||
pub description: String,
|
||||
#[serde(default)]
|
||||
pub author: String,
|
||||
#[serde(default)]
|
||||
pub permissions: Vec<Permission>,
|
||||
#[serde(default)]
|
||||
pub views: Vec<ViewDecl>,
|
||||
/// Names of the `{{name args}}` block macros the module renders.
|
||||
#[serde(default)]
|
||||
pub macros: Vec<String>,
|
||||
/// When set, the app sends a `tick` request this often (seconds, >= 5) while it runs.
|
||||
#[serde(default)]
|
||||
pub tick_seconds: Option<u32>,
|
||||
}
|
||||
|
||||
fn simple_name(s: &str) -> bool {
|
||||
!s.is_empty()
|
||||
&& s.len() <= 32
|
||||
&& s.bytes()
|
||||
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-' || b == b'_')
|
||||
}
|
||||
|
||||
impl Manifest {
|
||||
pub fn parse(json: &[u8]) -> Result<Self> {
|
||||
let mut m: Manifest = serde_json::from_slice(json)
|
||||
.map_err(|e| Error::Invalid(format!("bad manifest: {e}")))?;
|
||||
if m.api != API_VERSION {
|
||||
return Err(Error::Invalid(format!(
|
||||
"module API {} is not supported (this app speaks {API_VERSION})",
|
||||
m.api
|
||||
)));
|
||||
}
|
||||
if !synapse_core::is_valid_module_id(&m.id) {
|
||||
return Err(Error::Invalid(format!("invalid module id {:?}", m.id)));
|
||||
}
|
||||
if m.name.trim().is_empty() || m.name.chars().count() > 64 {
|
||||
return Err(Error::Invalid("module name must be 1-64 characters".into()));
|
||||
}
|
||||
if m.version.trim().is_empty() || m.version.len() > 32 {
|
||||
return Err(Error::Invalid("invalid module version".into()));
|
||||
}
|
||||
if m.views.len() > 8 || m.macros.len() > 16 {
|
||||
return Err(Error::Invalid("too many views or macros".into()));
|
||||
}
|
||||
for v in &m.views {
|
||||
if !simple_name(&v.id) || v.title.trim().is_empty() || v.title.chars().count() > 64 {
|
||||
return Err(Error::Invalid(format!("invalid view {:?}", v.id)));
|
||||
}
|
||||
if v.icon.as_ref().is_some_and(|i| i.chars().count() > 16) {
|
||||
return Err(Error::Invalid(format!("invalid icon of view {:?}", v.id)));
|
||||
}
|
||||
}
|
||||
if let Some(m) = m.macros.iter().find(|n| !simple_name(n)) {
|
||||
return Err(Error::Invalid(format!("invalid macro name {m:?}")));
|
||||
}
|
||||
if m.tick_seconds.is_some_and(|t| t < 5) {
|
||||
return Err(Error::Invalid("tick_seconds must be at least 5".into()));
|
||||
}
|
||||
m.description
|
||||
.truncate(m.description.floor_char_boundary(1000));
|
||||
m.author.truncate(m.author.floor_char_boundary(100));
|
||||
m.permissions.sort();
|
||||
m.permissions.dedup();
|
||||
Ok(m)
|
||||
}
|
||||
|
||||
/// Reads the manifest from the custom section of a WebAssembly binary, without compiling it.
|
||||
pub fn from_wasm(wasm: &[u8]) -> Result<Self> {
|
||||
let section = custom_section(wasm, MANIFEST_SECTION)?
|
||||
.ok_or_else(|| Error::Invalid(format!("no {MANIFEST_SECTION} section")))?;
|
||||
Self::parse(section)
|
||||
}
|
||||
}
|
||||
|
||||
fn leb_u32(b: &[u8], pos: &mut usize) -> Result<u32> {
|
||||
let mut out: u32 = 0;
|
||||
for shift in (0..35).step_by(7) {
|
||||
let byte = *b
|
||||
.get(*pos)
|
||||
.ok_or_else(|| Error::Invalid("truncated module".into()))?;
|
||||
*pos += 1;
|
||||
out |= u32::from(byte & 0x7f) << shift;
|
||||
if byte & 0x80 == 0 {
|
||||
return Ok(out);
|
||||
}
|
||||
}
|
||||
Err(Error::Invalid("bad LEB128 in module".into()))
|
||||
}
|
||||
|
||||
/// The payload of the first custom section called `name`, if any.
|
||||
fn custom_section<'a>(wasm: &'a [u8], name: &str) -> Result<Option<&'a [u8]>> {
|
||||
if wasm.len() < 8 || &wasm[..4] != b"\0asm" {
|
||||
return Err(Error::Invalid("not a WebAssembly module".into()));
|
||||
}
|
||||
let mut pos = 8;
|
||||
while pos < wasm.len() {
|
||||
let id = wasm[pos];
|
||||
pos += 1;
|
||||
let size = leb_u32(wasm, &mut pos)? as usize;
|
||||
let end = pos
|
||||
.checked_add(size)
|
||||
.filter(|&e| e <= wasm.len())
|
||||
.ok_or_else(|| Error::Invalid("truncated module".into()))?;
|
||||
if id == 0 {
|
||||
let mut p = pos;
|
||||
let len = leb_u32(wasm, &mut p)? as usize;
|
||||
let name_end = p
|
||||
.checked_add(len)
|
||||
.filter(|&e| e <= end)
|
||||
.ok_or_else(|| Error::Invalid("bad custom section".into()))?;
|
||||
if &wasm[p..name_end] == name.as_bytes() {
|
||||
return Ok(Some(&wasm[name_end..end]));
|
||||
}
|
||||
}
|
||||
pos = end;
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn wasm_with(section: &str, payload: &[u8]) -> Vec<u8> {
|
||||
let mut w = b"\0asm\x01\0\0\0".to_vec();
|
||||
let mut body = vec![section.len() as u8];
|
||||
body.extend_from_slice(section.as_bytes());
|
||||
body.extend_from_slice(payload);
|
||||
w.push(0);
|
||||
w.push(body.len() as u8); // small payloads only
|
||||
w.extend(body);
|
||||
w
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_the_manifest_section() {
|
||||
let json = br#"{"api":1,"id":"x.y","name":"X","version":"1","permissions":["crypto","storage","crypto"]}"#;
|
||||
let m = Manifest::from_wasm(&wasm_with(MANIFEST_SECTION, json)).unwrap();
|
||||
assert_eq!(m.id, "x.y");
|
||||
assert_eq!(m.permissions, vec![Permission::Storage, Permission::Crypto]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_bad_manifests() {
|
||||
for json in [
|
||||
r#"{"api":2,"id":"x","name":"X","version":"1"}"#,
|
||||
r#"{"api":1,"id":"X Y","name":"X","version":"1"}"#,
|
||||
r#"{"api":1,"id":"x","name":"X","version":"1","permissions":["network"]}"#,
|
||||
r#"{"api":1,"id":"x","name":"X","version":"1","macros":["Bad Name"]}"#,
|
||||
r#"{"api":1,"id":"x","name":"X","version":"1","tick_seconds":1}"#,
|
||||
] {
|
||||
assert!(
|
||||
Manifest::from_wasm(&wasm_with(MANIFEST_SECTION, json.as_bytes())).is_err(),
|
||||
"{json}"
|
||||
);
|
||||
}
|
||||
assert!(Manifest::from_wasm(&wasm_with("other", b"{}")).is_err());
|
||||
assert!(Manifest::from_wasm(b"nope").is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,309 @@
|
||||
//! Installed modules of a graph: `<graph>/modules/<id>.wasm` plus `<graph>/modules/modules.json`
|
||||
//! (enabled flag and granted permissions). Installation is local to each device; module data
|
||||
//! (`module_data`) syncs with the graph.
|
||||
|
||||
use crate::host::{self, Running};
|
||||
use crate::manifest::{Manifest, Permission};
|
||||
use crate::{Error, Result};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use synapse_core::Graph;
|
||||
use wasmi::{Engine, Module};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
struct Entry {
|
||||
enabled: bool,
|
||||
granted: Vec<Permission>,
|
||||
}
|
||||
|
||||
/// An installed module as the app sees it.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ModuleInfo {
|
||||
pub manifest: Manifest,
|
||||
pub enabled: bool,
|
||||
/// Size of the `.wasm` file in bytes.
|
||||
pub size: u64,
|
||||
}
|
||||
|
||||
struct Loaded {
|
||||
manifest: Manifest,
|
||||
module: Module,
|
||||
running: Option<Running>,
|
||||
}
|
||||
|
||||
pub struct Registry {
|
||||
dir: PathBuf,
|
||||
graph: Arc<Mutex<Graph>>,
|
||||
engine: Engine,
|
||||
/// Serialises installs and the state file.
|
||||
state: Mutex<BTreeMap<String, Entry>>,
|
||||
/// One lock per module so a slow module does not block the others.
|
||||
loaded: Mutex<HashMap<String, Arc<Mutex<Option<Loaded>>>>>,
|
||||
}
|
||||
|
||||
fn state_path(dir: &Path) -> PathBuf {
|
||||
dir.join("modules.json")
|
||||
}
|
||||
|
||||
impl Registry {
|
||||
/// Opens the registry of the graph directory `graph_dir` (creating `modules/` lazily).
|
||||
pub fn open(graph_dir: &Path, graph: Arc<Mutex<Graph>>) -> Self {
|
||||
let dir = graph_dir.join("modules");
|
||||
let state = std::fs::read(state_path(&dir))
|
||||
.ok()
|
||||
.and_then(|b| serde_json::from_slice(&b).ok())
|
||||
.unwrap_or_default();
|
||||
Self {
|
||||
dir,
|
||||
graph,
|
||||
engine: host::engine(),
|
||||
state: Mutex::new(state),
|
||||
loaded: Mutex::new(HashMap::new()),
|
||||
}
|
||||
}
|
||||
|
||||
fn wasm_path(&self, id: &str) -> PathBuf {
|
||||
self.dir.join(format!("{id}.wasm"))
|
||||
}
|
||||
|
||||
fn save(&self, state: &BTreeMap<String, Entry>) -> Result<()> {
|
||||
std::fs::create_dir_all(&self.dir)?;
|
||||
let tmp = self.dir.join("modules.json.tmp");
|
||||
std::fs::write(&tmp, serde_json::to_vec_pretty(state)?)?;
|
||||
std::fs::rename(tmp, state_path(&self.dir))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn lock_state(&self) -> std::sync::MutexGuard<'_, BTreeMap<String, Entry>> {
|
||||
self.state.lock().unwrap_or_else(|p| p.into_inner())
|
||||
}
|
||||
|
||||
fn slot(&self, id: &str) -> Arc<Mutex<Option<Loaded>>> {
|
||||
self.loaded
|
||||
.lock()
|
||||
.unwrap_or_else(|p| p.into_inner())
|
||||
.entry(id.to_string())
|
||||
.or_default()
|
||||
.clone()
|
||||
}
|
||||
|
||||
/// Validates a module file without installing it: manifest and WebAssembly.
|
||||
pub fn inspect(&self, wasm: &[u8]) -> Result<Manifest> {
|
||||
let manifest = Manifest::from_wasm(wasm)?;
|
||||
host::compile(&self.engine, wasm)?;
|
||||
Ok(manifest)
|
||||
}
|
||||
|
||||
/// Installs or updates a module. `granted` must contain every permission the manifest
|
||||
/// asks for (the user saw and accepted them). An update keeps the enabled flag.
|
||||
pub fn install(&self, wasm: &[u8], granted: &[Permission]) -> Result<ModuleInfo> {
|
||||
let manifest = self.inspect(wasm)?;
|
||||
if let Some(p) = manifest.permissions.iter().find(|p| !granted.contains(p)) {
|
||||
return Err(Error::Denied(format!(
|
||||
"permission {} was not granted",
|
||||
p.as_str()
|
||||
)));
|
||||
}
|
||||
let mut state = self.lock_state();
|
||||
// A block macro belongs to one module: another installed module claiming the same
|
||||
// name would silently receive (and could spoof) its blocks.
|
||||
for other in self.list_locked(&state) {
|
||||
if other.manifest.id == manifest.id {
|
||||
continue;
|
||||
}
|
||||
if let Some(m) = manifest
|
||||
.macros
|
||||
.iter()
|
||||
.find(|m| other.manifest.macros.contains(m))
|
||||
{
|
||||
return Err(Error::Invalid(format!(
|
||||
"the macro {{{{{m}}}}} is already used by the module {}",
|
||||
other.manifest.name
|
||||
)));
|
||||
}
|
||||
}
|
||||
std::fs::create_dir_all(&self.dir)?;
|
||||
let path = self.wasm_path(&manifest.id);
|
||||
let tmp = path.with_extension("wasm.tmp");
|
||||
std::fs::write(&tmp, wasm)?;
|
||||
std::fs::rename(&tmp, &path)?;
|
||||
let enabled = state.get(&manifest.id).is_none_or(|e| e.enabled);
|
||||
state.insert(
|
||||
manifest.id.clone(),
|
||||
Entry {
|
||||
enabled,
|
||||
granted: manifest.permissions.clone(),
|
||||
},
|
||||
);
|
||||
self.save(&state)?;
|
||||
// Never wait for a module slot while holding the state lock: `call` takes them in
|
||||
// the opposite order.
|
||||
drop(state);
|
||||
// Drop a running older version.
|
||||
*self
|
||||
.slot(&manifest.id)
|
||||
.lock()
|
||||
.unwrap_or_else(|p| p.into_inner()) = None;
|
||||
Ok(ModuleInfo {
|
||||
manifest,
|
||||
enabled,
|
||||
size: wasm.len() as u64,
|
||||
})
|
||||
}
|
||||
|
||||
/// Installed modules, by name. A module whose file is missing or broken is skipped.
|
||||
pub fn list(&self) -> Vec<ModuleInfo> {
|
||||
let state = self.lock_state().clone();
|
||||
self.list_locked(&state)
|
||||
}
|
||||
|
||||
/// Whether the graph already holds data for module `id` (synced from another device or
|
||||
/// left by an earlier install): a module installed under that id can read it.
|
||||
pub fn has_data(&self, id: &str) -> Result<bool> {
|
||||
let g = self.graph.lock().unwrap_or_else(|p| p.into_inner());
|
||||
Ok(g.module_data_usage(id)?.0 > 0)
|
||||
}
|
||||
|
||||
fn list_locked(&self, state: &BTreeMap<String, Entry>) -> Vec<ModuleInfo> {
|
||||
let mut out: Vec<ModuleInfo> = state
|
||||
.iter()
|
||||
.filter_map(|(id, e)| {
|
||||
let bytes = std::fs::read(self.wasm_path(id)).ok()?;
|
||||
let manifest = Manifest::from_wasm(&bytes).ok()?;
|
||||
(&manifest.id == id).then_some(ModuleInfo {
|
||||
manifest,
|
||||
enabled: e.enabled,
|
||||
size: bytes.len() as u64,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
out.sort_by_key(|m| m.manifest.name.to_lowercase());
|
||||
out
|
||||
}
|
||||
|
||||
pub fn set_enabled(&self, id: &str, enabled: bool) -> Result<()> {
|
||||
let mut state = self.lock_state();
|
||||
let e = state
|
||||
.get_mut(id)
|
||||
.ok_or_else(|| Error::NotFound(id.to_string()))?;
|
||||
e.enabled = enabled;
|
||||
self.save(&state)?;
|
||||
drop(state);
|
||||
if !enabled {
|
||||
self.stop(id);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Removes the module file. Its synced data is deleted too only when `delete_data` (that
|
||||
/// deletion syncs to every device).
|
||||
pub fn uninstall(&self, id: &str, delete_data: bool) -> Result<()> {
|
||||
let mut state = self.lock_state();
|
||||
if state.remove(id).is_none() {
|
||||
return Err(Error::NotFound(id.to_string()));
|
||||
}
|
||||
self.save(&state)?;
|
||||
drop(state);
|
||||
self.stop(id);
|
||||
let _ = std::fs::remove_file(self.wasm_path(id));
|
||||
if delete_data {
|
||||
self.graph
|
||||
.lock()
|
||||
.unwrap_or_else(|p| p.into_inner())
|
||||
.clear_module_data(id)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Drops the running instance (its in-memory state, such as unlocked keys, is lost).
|
||||
pub fn stop(&self, id: &str) {
|
||||
// Release the map before waiting for a busy module, so other modules keep working.
|
||||
let slot = self
|
||||
.loaded
|
||||
.lock()
|
||||
.unwrap_or_else(|p| p.into_inner())
|
||||
.get(id)
|
||||
.cloned();
|
||||
if let Some(slot) = slot {
|
||||
*slot.lock().unwrap_or_else(|p| p.into_inner()) = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// Drops every running instance.
|
||||
pub fn stop_all(&self) {
|
||||
let slots: Vec<_> = self
|
||||
.loaded
|
||||
.lock()
|
||||
.unwrap_or_else(|p| p.into_inner())
|
||||
.values()
|
||||
.cloned()
|
||||
.collect();
|
||||
for s in slots {
|
||||
*s.lock().unwrap_or_else(|p| p.into_inner()) = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// Sends a request to an enabled module, starting it if needed. If the module traps, its
|
||||
/// instance is discarded and the error returned.
|
||||
pub fn call(&self, id: &str, request: &Value) -> Result<Value> {
|
||||
let entry = self
|
||||
.lock_state()
|
||||
.get(id)
|
||||
.cloned()
|
||||
.ok_or_else(|| Error::NotFound(id.to_string()))?;
|
||||
if !entry.enabled {
|
||||
return Err(Error::Invalid(format!("module {id} is disabled")));
|
||||
}
|
||||
let slot = self.slot(id);
|
||||
let mut guard = slot.lock().unwrap_or_else(|p| p.into_inner());
|
||||
// Disabled or removed while we waited for the slot: do not start it again.
|
||||
let entry = match self.lock_state().get(id) {
|
||||
Some(e) if e.enabled => e.clone(),
|
||||
_ => {
|
||||
*guard = None;
|
||||
return Err(Error::Invalid(format!("module {id} is disabled")));
|
||||
}
|
||||
};
|
||||
if guard.is_none() {
|
||||
let bytes = std::fs::read(self.wasm_path(id))?;
|
||||
let manifest = Manifest::from_wasm(&bytes)?;
|
||||
if manifest.id != id {
|
||||
return Err(Error::Invalid("module file does not match its id".into()));
|
||||
}
|
||||
// Permissions are the ones granted at install time (a file swapped behind our back
|
||||
// cannot gain more).
|
||||
if manifest
|
||||
.permissions
|
||||
.iter()
|
||||
.any(|p| !entry.granted.contains(p))
|
||||
{
|
||||
return Err(Error::Denied(
|
||||
"module asks for permissions not granted".into(),
|
||||
));
|
||||
}
|
||||
let module = host::compile(&self.engine, &bytes)?;
|
||||
*guard = Some(Loaded {
|
||||
manifest,
|
||||
module,
|
||||
running: None,
|
||||
});
|
||||
}
|
||||
let loaded = guard.as_mut().expect("loaded");
|
||||
if loaded.running.is_none() {
|
||||
loaded.running = Some(Running::start(
|
||||
&self.engine,
|
||||
&loaded.module,
|
||||
loaded.manifest.clone(),
|
||||
self.graph.clone(),
|
||||
)?);
|
||||
}
|
||||
let result = loaded.running.as_mut().expect("running").request(request);
|
||||
if matches!(result, Err(Error::Module(_))) {
|
||||
loaded.running = None;
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,711 @@
|
||||
use serde_json::{Value, json};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use synapse_core::Graph;
|
||||
use synapse_modules::{Error, MANIFEST_SECTION, Permission, Registry};
|
||||
|
||||
const SECRETS: &str = "synapse.secrets";
|
||||
|
||||
fn secrets_wasm() -> Vec<u8> {
|
||||
let p = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../app/assets/modules/synapse.secrets.wasm");
|
||||
std::fs::read(&p)
|
||||
.unwrap_or_else(|e| panic!("{}: {e} (run scripts/build-modules.sh)", p.display()))
|
||||
}
|
||||
|
||||
fn setup() -> (tempfile::TempDir, Arc<Mutex<Graph>>, Registry) {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let graph = Arc::new(Mutex::new(Graph::open(dir.path()).unwrap()));
|
||||
let reg = Registry::open(dir.path(), graph.clone());
|
||||
(dir, graph, reg)
|
||||
}
|
||||
|
||||
fn all_perms() -> Vec<Permission> {
|
||||
vec![
|
||||
Permission::Storage,
|
||||
Permission::Crypto,
|
||||
Permission::Clipboard,
|
||||
Permission::PagesRead,
|
||||
Permission::PagesWrite,
|
||||
]
|
||||
}
|
||||
|
||||
/// A module from WAT, with a manifest section appended.
|
||||
fn wat_module(wat: &str, manifest: Value) -> Vec<u8> {
|
||||
let mut wasm = wat::parse_str(wat).unwrap();
|
||||
let json = serde_json::to_vec(&manifest).unwrap();
|
||||
let mut body = Vec::new();
|
||||
leb(&mut body, MANIFEST_SECTION.len());
|
||||
body.extend_from_slice(MANIFEST_SECTION.as_bytes());
|
||||
body.extend_from_slice(&json);
|
||||
wasm.push(0);
|
||||
leb(&mut wasm, body.len());
|
||||
wasm.extend(body);
|
||||
wasm
|
||||
}
|
||||
|
||||
fn leb(out: &mut Vec<u8>, mut n: usize) {
|
||||
loop {
|
||||
let b = (n & 0x7f) as u8;
|
||||
n >>= 7;
|
||||
if n == 0 {
|
||||
out.push(b);
|
||||
return;
|
||||
}
|
||||
out.push(b | 0x80);
|
||||
}
|
||||
}
|
||||
|
||||
fn texts(v: &Value, out: &mut String) {
|
||||
match v {
|
||||
Value::String(s) => {
|
||||
out.push_str(s);
|
||||
out.push('\n');
|
||||
}
|
||||
Value::Array(a) => a.iter().for_each(|x| texts(x, out)),
|
||||
Value::Object(o) => o.values().for_each(|x| texts(x, out)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn ui_text(resp: &Value) -> String {
|
||||
let mut s = String::new();
|
||||
texts(&resp["ui"], &mut s);
|
||||
s
|
||||
}
|
||||
|
||||
fn event(reg: &Registry, action: &str, values: Value, arg: &str) -> Value {
|
||||
let r = reg
|
||||
.call(
|
||||
SECRETS,
|
||||
&json!({ "op": "event", "view": "vault", "action": action, "values": values, "arg": arg }),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(r.get("error").is_none(), "{action}: {r}");
|
||||
r
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn secrets_vault_end_to_end() {
|
||||
let (_dir, graph, reg) = setup();
|
||||
let wasm = secrets_wasm();
|
||||
let m = reg.inspect(&wasm).unwrap();
|
||||
assert_eq!(m.id, SECRETS);
|
||||
assert_eq!(
|
||||
m.permissions,
|
||||
vec![
|
||||
Permission::Storage,
|
||||
Permission::Crypto,
|
||||
Permission::Clipboard
|
||||
]
|
||||
);
|
||||
// Installing needs every requested permission granted.
|
||||
assert!(matches!(
|
||||
reg.install(&wasm, &[Permission::Storage]),
|
||||
Err(Error::Denied(_))
|
||||
));
|
||||
reg.install(&wasm, &m.permissions).unwrap();
|
||||
assert_eq!(reg.list().len(), 1);
|
||||
|
||||
let r = reg
|
||||
.call(SECRETS, &json!({ "op": "render", "view": "vault" }))
|
||||
.unwrap();
|
||||
assert!(ui_text(&r).contains("Create vault"), "{r}");
|
||||
|
||||
let r = event(
|
||||
®,
|
||||
"setup",
|
||||
json!({ "password": "short", "confirm": "short" }),
|
||||
"",
|
||||
);
|
||||
assert!(ui_text(&r).contains("at least 8"));
|
||||
let r = event(
|
||||
®,
|
||||
"setup",
|
||||
json!({ "password": "correct horse", "confirm": "correct horse" }),
|
||||
"",
|
||||
);
|
||||
assert!(ui_text(&r).contains("No secrets yet"), "{r}");
|
||||
|
||||
event(®, "new", json!({}), "");
|
||||
let r = event(
|
||||
®,
|
||||
"save",
|
||||
json!({ "name": "GitHub", "username": "dario", "password": "hunter2-XYZ", "url": "https://github.com", "notes": "" }),
|
||||
"",
|
||||
);
|
||||
assert!(ui_text(&r).contains("GitHub"));
|
||||
assert!(!ui_text(&r).contains("hunter2-XYZ"), "masked by default");
|
||||
|
||||
// Stored data is ciphertext only.
|
||||
{
|
||||
let g = graph.lock().unwrap();
|
||||
let rows = g.module_data_list(SECRETS, "").unwrap();
|
||||
assert_eq!(rows.len(), 3, "pointer, header, entry: {rows:?}");
|
||||
for (_, v) in &rows {
|
||||
assert!(!v.contains("hunter2") && !v.contains("GitHub") && !v.contains("dario"));
|
||||
}
|
||||
}
|
||||
|
||||
// Macro: masked, copy gives a clipboard effect.
|
||||
let r = reg
|
||||
.call(
|
||||
SECRETS,
|
||||
&json!({ "op": "macro", "name": "secret", "args": "github" }),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(r["inline"]["text"], "GitHub");
|
||||
assert_ne!(r["inline"]["masked"], "hunter2-XYZ");
|
||||
let r = reg
|
||||
.call(
|
||||
SECRETS,
|
||||
&json!({ "op": "macro_action", "name": "secret", "args": "GitHub", "action": "copy" }),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(r["effects"][0]["copy"]["text"], "hunter2-XYZ");
|
||||
let r = reg
|
||||
.call(
|
||||
SECRETS,
|
||||
&json!({ "op": "macro_action", "name": "secret", "args": "GitHub", "action": "reveal" }),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(r["inline"]["masked"], "hunter2-XYZ");
|
||||
let r = reg
|
||||
.call(
|
||||
SECRETS,
|
||||
&json!({ "op": "macro", "name": "secret", "args": "Nope" }),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(r["inline"]["error"].is_string());
|
||||
|
||||
// Lock: the macro no longer reveals anything.
|
||||
event(®, "lock", json!({}), "");
|
||||
let r = reg
|
||||
.call(
|
||||
SECRETS,
|
||||
&json!({ "op": "macro_action", "name": "secret", "args": "GitHub", "action": "copy" }),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(r["effects"][0]["open_view"], "vault");
|
||||
assert!(!r.to_string().contains("hunter2"));
|
||||
|
||||
let r = event(®, "unlock", json!({ "password": "wrong horse" }), "");
|
||||
assert!(ui_text(&r).contains("Wrong password"));
|
||||
let r = event(®, "unlock", json!({ "password": "correct horse" }), "");
|
||||
assert!(ui_text(&r).contains("GitHub"));
|
||||
|
||||
// Change the password: the old one stops working, entries survive.
|
||||
event(®, "change_password", json!({}), "");
|
||||
event(
|
||||
®,
|
||||
"save_password",
|
||||
json!({ "current": "correct horse", "new": "battery staple", "confirm": "battery staple" }),
|
||||
"",
|
||||
);
|
||||
// A restart (or crash) drops the instance: locked again.
|
||||
reg.stop(SECRETS);
|
||||
let r = event(®, "unlock", json!({ "password": "correct horse" }), "");
|
||||
assert!(ui_text(&r).contains("Wrong password"));
|
||||
let r = event(®, "unlock", json!({ "password": "battery staple" }), "");
|
||||
assert!(ui_text(&r).contains("GitHub"));
|
||||
|
||||
// Suspend locks.
|
||||
let r = reg.call(SECRETS, &json!({ "op": "suspend" })).unwrap();
|
||||
assert_eq!(r["changed"], true);
|
||||
|
||||
// Uninstall keeps synced data unless asked.
|
||||
reg.uninstall(SECRETS, false).unwrap();
|
||||
assert_eq!(
|
||||
graph
|
||||
.lock()
|
||||
.unwrap()
|
||||
.module_data_list(SECRETS, "")
|
||||
.unwrap()
|
||||
.len(),
|
||||
3
|
||||
);
|
||||
reg.install(&wasm, &m.permissions).unwrap();
|
||||
reg.uninstall(SECRETS, true).unwrap();
|
||||
assert!(
|
||||
graph
|
||||
.lock()
|
||||
.unwrap()
|
||||
.module_data_list(SECRETS, "")
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vault_data_syncs_as_ciphertext_and_unlocks_on_another_replica() {
|
||||
let (_a_dir, a_graph, a) = setup();
|
||||
let (_b_dir, b_graph, b) = setup();
|
||||
let wasm = secrets_wasm();
|
||||
let perms = a.inspect(&wasm).unwrap().permissions;
|
||||
a.install(&wasm, &perms).unwrap();
|
||||
b.install(&wasm, &perms).unwrap();
|
||||
event(
|
||||
&a,
|
||||
"setup",
|
||||
json!({ "password": "correct horse", "confirm": "correct horse" }),
|
||||
"",
|
||||
);
|
||||
event(&a, "new", json!({}), "");
|
||||
event(
|
||||
&a,
|
||||
"save",
|
||||
json!({ "name": "Bank", "password": "s3cret!" }),
|
||||
"",
|
||||
);
|
||||
let ops = a_graph.lock().unwrap().ops_since(0, 10_000).unwrap();
|
||||
{
|
||||
let g = b_graph.lock().unwrap();
|
||||
for op in &ops {
|
||||
if matches!(op.op, synapse_core::Op::PutModuleData { .. }) {
|
||||
assert!(!serde_json::to_string(&op.op).unwrap().contains("s3cret"));
|
||||
g.apply_remote(&op.hlc, &op.op).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
let r = b
|
||||
.call(
|
||||
SECRETS,
|
||||
&json!({ "op": "event", "action": "unlock", "values": { "password": "correct horse" } }),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(ui_text(&r).contains("Bank"), "{r}");
|
||||
let r = b
|
||||
.call(
|
||||
SECRETS,
|
||||
&json!({ "op": "macro_action", "name": "secret", "args": "bank", "action": "copy" }),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(r["effects"][0]["copy"]["text"], "s3cret!");
|
||||
}
|
||||
|
||||
const ECHO: &str = r#"
|
||||
(module
|
||||
(import "synapse" "call" (func $call (param i32 i32) (result i32)))
|
||||
(import "synapse" "take" (func $take (param i32)))
|
||||
(import "synapse" "respond" (func $respond (param i32 i32)))
|
||||
(memory (export "memory") 2)
|
||||
(global $next (mut i32) (i32.const 1024))
|
||||
(func (export "syn_alloc") (param $n i32) (result i32)
|
||||
(local $p i32)
|
||||
global.get $next
|
||||
local.set $p
|
||||
global.get $next
|
||||
local.get $n
|
||||
i32.add
|
||||
global.set $next
|
||||
local.get $p)
|
||||
;; Forwards the request to the host as a host call and returns the host's reply.
|
||||
(func (export "syn_handle") (param $p i32) (param $n i32)
|
||||
(local $len i32)
|
||||
local.get $p
|
||||
local.get $n
|
||||
call $call
|
||||
local.set $len
|
||||
i32.const 32768
|
||||
call $take
|
||||
i32.const 32768
|
||||
local.get $len
|
||||
call $respond))
|
||||
"#;
|
||||
|
||||
fn manifest(id: &str, perms: &[&str]) -> Value {
|
||||
json!({ "api": 1, "id": id, "name": id, "version": "1", "permissions": perms })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_functions_need_their_permission() {
|
||||
let (_dir, graph, reg) = setup();
|
||||
let wasm = wat_module(ECHO, manifest("test.echo", &[]));
|
||||
reg.install(&wasm, &[]).unwrap();
|
||||
let r = reg
|
||||
.call(
|
||||
"test.echo",
|
||||
&json!({ "fn": "kv.set", "key": "k", "value": "v" }),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(
|
||||
r["error"].as_str().unwrap().contains("permission denied"),
|
||||
"{r}"
|
||||
);
|
||||
let r = reg
|
||||
.call("test.echo", &json!({ "fn": "crypto.generate" }))
|
||||
.unwrap();
|
||||
assert!(r["error"].is_string());
|
||||
let r = reg
|
||||
.call("test.echo", &json!({ "fn": "pages.get", "title": "x" }))
|
||||
.unwrap();
|
||||
assert!(r["error"].is_string());
|
||||
let r = reg.call("test.echo", &json!({ "fn": "now" })).unwrap();
|
||||
assert!(r["ok"].as_u64().unwrap() > 0);
|
||||
|
||||
let wasm = wat_module(
|
||||
ECHO,
|
||||
manifest("test.store", &["storage", "pages:write", "pages:read"]),
|
||||
);
|
||||
reg.install(&wasm, &all_perms()).unwrap();
|
||||
let r = reg
|
||||
.call(
|
||||
"test.store",
|
||||
&json!({ "fn": "kv.set", "key": "k", "value": "v" }),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(r.get("error").is_none(), "{r}");
|
||||
let r = reg
|
||||
.call(
|
||||
"test.store",
|
||||
&json!({ "fn": "pages.append", "title": "Inbox", "text": "from a module" }),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(r["ok"]["page"], "Inbox");
|
||||
let r = reg
|
||||
.call(
|
||||
"test.store",
|
||||
&json!({ "fn": "pages.get", "title": "inbox" }),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(r["ok"]["markdown"], "- from a module\n");
|
||||
let g = graph.lock().unwrap();
|
||||
// Each module only sees its own namespace.
|
||||
assert_eq!(
|
||||
g.module_data("test.store", "k").unwrap().as_deref(),
|
||||
Some("v")
|
||||
);
|
||||
assert_eq!(g.module_data("test.echo", "k").unwrap(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copy_effects_need_the_clipboard_permission() {
|
||||
let (_dir, _graph, reg) = setup();
|
||||
// Echo answers with the host reply; make the module answer an arbitrary JSON instead by
|
||||
// sending a request the host rejects... simpler: a module that responds with its request.
|
||||
let wat = r#"
|
||||
(module
|
||||
(import "synapse" "respond" (func $respond (param i32 i32)))
|
||||
(memory (export "memory") 2)
|
||||
(func (export "syn_alloc") (param i32) (result i32) i32.const 1024)
|
||||
(func (export "syn_handle") (param $p i32) (param $n i32)
|
||||
local.get $p
|
||||
local.get $n
|
||||
call $respond))
|
||||
"#;
|
||||
let wasm = wat_module(wat, manifest("test.mirror", &[]));
|
||||
reg.install(&wasm, &[]).unwrap();
|
||||
let req = json!({ "effects": [{ "copy": { "text": "x" } }, { "toast": "hi" }] });
|
||||
let r = reg.call("test.mirror", &req).unwrap();
|
||||
assert_eq!(r["effects"], json!([{ "toast": "hi" }]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_runaway_module_is_stopped_and_restarted() {
|
||||
let (_dir, _graph, reg) = setup();
|
||||
let wat = r#"
|
||||
(module
|
||||
(memory (export "memory") 1)
|
||||
(func (export "syn_alloc") (param i32) (result i32) i32.const 1024)
|
||||
(func (export "syn_handle") (param i32 i32)
|
||||
(loop $l br $l)))
|
||||
"#;
|
||||
let wasm = wat_module(wat, manifest("test.loop", &[]));
|
||||
reg.install(&wasm, &[]).unwrap();
|
||||
assert!(matches!(
|
||||
reg.call("test.loop", &json!({})),
|
||||
Err(Error::Module(_))
|
||||
));
|
||||
// Still callable (a fresh instance), still stopped by the fuel limit.
|
||||
assert!(matches!(
|
||||
reg.call("test.loop", &json!({})),
|
||||
Err(Error::Module(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn memory_is_capped() {
|
||||
let (_dir, _graph, reg) = setup();
|
||||
let wat = r#"
|
||||
(module
|
||||
(memory (export "memory") 1)
|
||||
(func (export "syn_alloc") (param i32) (result i32) i32.const 1024)
|
||||
(func (export "syn_handle") (param i32 i32)
|
||||
;; 2000 pages = 125 MiB, over the cap: memory.grow returns -1, then trap.
|
||||
i32.const 2000
|
||||
memory.grow
|
||||
i32.const -1
|
||||
i32.eq
|
||||
if unreachable end))
|
||||
"#;
|
||||
let wasm = wat_module(wat, manifest("test.mem", &[]));
|
||||
reg.install(&wasm, &[]).unwrap();
|
||||
assert!(matches!(
|
||||
reg.call("test.mem", &json!({})),
|
||||
Err(Error::Module(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disabled_and_unknown_modules_refuse_calls() {
|
||||
let (dir, graph, reg) = setup();
|
||||
let wasm = wat_module(ECHO, manifest("test.echo", &[]));
|
||||
reg.install(&wasm, &[]).unwrap();
|
||||
reg.set_enabled("test.echo", false).unwrap();
|
||||
assert!(reg.call("test.echo", &json!({ "fn": "now" })).is_err());
|
||||
assert!(reg.call("nope", &json!({})).is_err());
|
||||
// State survives reopening.
|
||||
let reg2 = Registry::open(dir.path(), graph);
|
||||
assert!(!reg2.list()[0].enabled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_swapped_file_cannot_gain_permissions() {
|
||||
let (dir, _graph, reg) = setup();
|
||||
reg.install(&wat_module(ECHO, manifest("test.echo", &[])), &[])
|
||||
.unwrap();
|
||||
let evil = wat_module(ECHO, manifest("test.echo", &["storage"]));
|
||||
std::fs::write(dir.path().join("modules/test.echo.wasm"), evil).unwrap();
|
||||
assert!(matches!(
|
||||
reg.call("test.echo", &json!({ "fn": "now" })),
|
||||
Err(Error::Denied(_))
|
||||
));
|
||||
}
|
||||
|
||||
fn ops_of(g: &Arc<Mutex<Graph>>) -> Vec<(String, synapse_core::Op)> {
|
||||
g.lock()
|
||||
.unwrap()
|
||||
.ops_since(0, 100_000)
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.filter(|r| matches!(r.op, synapse_core::Op::PutModuleData { .. }))
|
||||
.map(|r| (r.hlc, r.op))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn sync(from: &Arc<Mutex<Graph>>, to: &Arc<Mutex<Graph>>) {
|
||||
let ops = ops_of(from);
|
||||
let g = to.lock().unwrap();
|
||||
for (hlc, op) in &ops {
|
||||
g.apply_remote(hlc, op).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
fn keys(g: &Arc<Mutex<Graph>>) -> Vec<String> {
|
||||
g.lock()
|
||||
.unwrap()
|
||||
.module_data_list(SECRETS, "")
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.map(|(k, _)| k)
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_vaults_set_up_before_syncing_merge_on_unlock() {
|
||||
let (_a_dir, a_graph, a) = setup();
|
||||
let (_b_dir, b_graph, b) = setup();
|
||||
let wasm = secrets_wasm();
|
||||
let perms = a.inspect(&wasm).unwrap().permissions;
|
||||
a.install(&wasm, &perms).unwrap();
|
||||
b.install(&wasm, &perms).unwrap();
|
||||
for (reg, name) in [(&a, "From A"), (&b, "From B")] {
|
||||
event(
|
||||
reg,
|
||||
"setup",
|
||||
json!({ "password": "correct horse", "confirm": "correct horse" }),
|
||||
"",
|
||||
);
|
||||
event(reg, "new", json!({}), "");
|
||||
event(reg, "save", json!({ "name": name, "password": "pw" }), "");
|
||||
}
|
||||
sync(&a_graph, &b_graph);
|
||||
sync(&b_graph, &a_graph);
|
||||
// B's data key may have lost the pointer: writing with it is refused until unlocked again.
|
||||
for reg in [&a, &b] {
|
||||
reg.stop(SECRETS);
|
||||
let r = event(reg, "unlock", json!({ "password": "correct horse" }), "");
|
||||
let t = ui_text(&r);
|
||||
assert!(t.contains("From A") && t.contains("From B"), "{t}");
|
||||
}
|
||||
// One header is left on each replica after syncing again.
|
||||
sync(&a_graph, &b_graph);
|
||||
sync(&b_graph, &a_graph);
|
||||
for g in [&a_graph, &b_graph] {
|
||||
let headers = keys(g)
|
||||
.into_iter()
|
||||
.filter(|k| k.starts_with("vault/"))
|
||||
.count();
|
||||
assert_eq!(headers, 1, "{:?}", keys(g));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_device_whose_key_was_replaced_must_unlock_again_before_writing() {
|
||||
let (_a_dir, a_graph, a) = setup();
|
||||
let (_b_dir, b_graph, b) = setup();
|
||||
let wasm = secrets_wasm();
|
||||
let perms = a.inspect(&wasm).unwrap().permissions;
|
||||
a.install(&wasm, &perms).unwrap();
|
||||
b.install(&wasm, &perms).unwrap();
|
||||
event(
|
||||
&a,
|
||||
"setup",
|
||||
json!({ "password": "correct horse", "confirm": "correct horse" }),
|
||||
"",
|
||||
);
|
||||
sync(&a_graph, &b_graph);
|
||||
event(&b, "unlock", json!({ "password": "correct horse" }), "");
|
||||
// A changes the password: the data key rotates.
|
||||
event(&a, "change_password", json!({}), "");
|
||||
event(
|
||||
&a,
|
||||
"save_password",
|
||||
json!({ "current": "correct horse", "new": "battery staple", "confirm": "battery staple" }),
|
||||
"",
|
||||
);
|
||||
sync(&a_graph, &b_graph);
|
||||
// B still holds the old key; saving with it is refused and B locks.
|
||||
event(&b, "new", json!({}), "");
|
||||
let r = event(&b, "save", json!({ "name": "Late", "password": "x" }), "");
|
||||
assert!(ui_text(&r).contains("changed on another device"), "{r}");
|
||||
assert!(!keys(&b_graph).iter().any(|k| k.starts_with("entry/")));
|
||||
let r = event(&b, "unlock", json!({ "password": "correct horse" }), "");
|
||||
assert!(ui_text(&r).contains("Wrong password"));
|
||||
let r = event(&b, "unlock", json!({ "password": "battery staple" }), "");
|
||||
assert!(!ui_text(&r).contains("Wrong password"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changing_the_password_rotates_the_data_key() {
|
||||
let (_dir, graph, reg) = setup();
|
||||
let wasm = secrets_wasm();
|
||||
reg.install(&wasm, ®.inspect(&wasm).unwrap().permissions)
|
||||
.unwrap();
|
||||
event(
|
||||
®,
|
||||
"setup",
|
||||
json!({ "password": "correct horse", "confirm": "correct horse" }),
|
||||
"",
|
||||
);
|
||||
event(®, "new", json!({}), "");
|
||||
event(
|
||||
®,
|
||||
"save",
|
||||
json!({ "name": "Bank", "password": "s3cret" }),
|
||||
"",
|
||||
);
|
||||
let before = keys(&graph);
|
||||
let entry_before = graph
|
||||
.lock()
|
||||
.unwrap()
|
||||
.module_data_list(SECRETS, "entry/")
|
||||
.unwrap();
|
||||
event(®, "change_password", json!({}), "");
|
||||
event(
|
||||
®,
|
||||
"save_password",
|
||||
json!({ "current": "correct horse", "new": "battery staple", "confirm": "battery staple" }),
|
||||
"",
|
||||
);
|
||||
let after = keys(&graph);
|
||||
let old_header = before.iter().find(|k| k.starts_with("vault/")).unwrap();
|
||||
assert!(!after.contains(old_header), "old header deleted: {after:?}");
|
||||
let entry_after = graph
|
||||
.lock()
|
||||
.unwrap()
|
||||
.module_data_list(SECRETS, "entry/")
|
||||
.unwrap();
|
||||
assert_ne!(entry_before[0].1, entry_after[0].1, "entry re-sealed");
|
||||
reg.stop(SECRETS);
|
||||
let r = event(®, "unlock", json!({ "password": "battery staple" }), "");
|
||||
assert!(ui_text(&r).contains("Bank"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn synced_headers_with_weak_kdf_parameters_are_ignored() {
|
||||
let (_dir, graph, reg) = setup();
|
||||
let wasm = secrets_wasm();
|
||||
reg.install(&wasm, ®.inspect(&wasm).unwrap().permissions)
|
||||
.unwrap();
|
||||
let weak = json!({ "v": 1, "key_id": "aa", "kdf": { "memory_kib": 8, "iterations": 1, "lanes": 1 }, "salt": "c2FsdHNhbHRzYWx0", "key": "AAAA" });
|
||||
graph
|
||||
.lock()
|
||||
.unwrap()
|
||||
.set_module_data(SECRETS, "vault/aa", Some(&weak.to_string()))
|
||||
.unwrap();
|
||||
let r = reg
|
||||
.call(SECRETS, &json!({ "op": "render", "view": "vault" }))
|
||||
.unwrap();
|
||||
assert!(ui_text(&r).contains("Create vault"), "{r}");
|
||||
}
|
||||
|
||||
/// Calls `kv.set` in a loop with the request stored at offset 0 (a data segment).
|
||||
fn flood_module() -> String {
|
||||
let req = r#"{"fn":"kv.set","key":"k","value":"0123456789012345678901234567890123456789"}"#;
|
||||
format!(
|
||||
r#"
|
||||
(module
|
||||
(import "synapse" "call" (func $call (param i32 i32) (result i32)))
|
||||
(memory (export "memory") 2)
|
||||
(data (i32.const 0) "{}")
|
||||
(func (export "syn_alloc") (param i32) (result i32) i32.const 4096)
|
||||
(func (export "syn_handle") (param i32 i32)
|
||||
(loop $l
|
||||
i32.const 0
|
||||
i32.const {}
|
||||
call $call
|
||||
drop
|
||||
br $l)))
|
||||
"#,
|
||||
req.replace('"', "\\\""),
|
||||
req.len()
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_calls_are_metered() {
|
||||
let (_dir, graph, reg) = setup();
|
||||
let wasm = wat_module(&flood_module(), manifest("test.flood", &["storage"]));
|
||||
reg.install(&wasm, &[Permission::Storage]).unwrap();
|
||||
let t = std::time::Instant::now();
|
||||
assert!(matches!(
|
||||
reg.call("test.flood", &json!({})),
|
||||
Err(Error::Module(_))
|
||||
));
|
||||
assert!(t.elapsed() < std::time::Duration::from_secs(20));
|
||||
let writes = ops_of(&graph).len();
|
||||
assert!(
|
||||
writes <= synapse_modules::MAX_HOST_CALLS as usize,
|
||||
"{writes}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tables_are_capped() {
|
||||
let (_dir, _graph, reg) = setup();
|
||||
let wat = r#"
|
||||
(module
|
||||
(table 50000000 funcref)
|
||||
(memory (export "memory") 1)
|
||||
(func (export "syn_alloc") (param i32) (result i32) i32.const 1024)
|
||||
(func (export "syn_handle") (param i32 i32)))
|
||||
"#;
|
||||
let wasm = wat_module(wat, manifest("test.table", &[]));
|
||||
reg.install(&wasm, &[]).unwrap();
|
||||
assert!(reg.call("test.table", &json!({})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_macro_name_belongs_to_one_module() {
|
||||
let (_dir, _graph, reg) = setup();
|
||||
let mut m = manifest("test.one", &[]);
|
||||
m["macros"] = json!(["secret"]);
|
||||
reg.install(&wat_module(ECHO, m), &[]).unwrap();
|
||||
let mut m = manifest("test.two", &[]);
|
||||
m["macros"] = json!(["secret"]);
|
||||
assert!(matches!(
|
||||
reg.install(&wat_module(ECHO, m), &[]),
|
||||
Err(Error::Invalid(_))
|
||||
));
|
||||
}
|
||||
@@ -256,7 +256,7 @@ impl Search {
|
||||
}
|
||||
// The previous owner of an alias is not in the op, so refresh all pages.
|
||||
Op::SetAlias { .. } => all_pages = true,
|
||||
Op::PutAsset { .. } | Op::PutTypeDef { .. } => {}
|
||||
Op::PutAsset { .. } | Op::PutTypeDef { .. } | Op::PutModuleData { .. } => {}
|
||||
}
|
||||
}
|
||||
stats.ops_processed += ops.len();
|
||||
|
||||
@@ -4,7 +4,7 @@ use serde::{Deserialize, Serialize};
|
||||
use synapse_core::{Backlink, Block, Op, OpRecord, Page};
|
||||
|
||||
/// Bumped on incompatible changes. Sent as `X-Synapse-Protocol` by clients.
|
||||
pub const PROTOCOL_VERSION: u32 = 1;
|
||||
pub const PROTOCOL_VERSION: u32 = 2;
|
||||
pub const HEADER_PROTOCOL: &str = "x-synapse-protocol";
|
||||
/// Bytes already stored of a partially uploaded blob (response header).
|
||||
pub const HEADER_UPLOAD_OFFSET: &str = "upload-offset";
|
||||
|
||||
+10
@@ -134,6 +134,16 @@ Tokens: `paper surface ink muted faint line accent accent-soft ref done code-bg
|
||||
`#rrggbbaa`, `rgb()/rgba()` or `hsl()/hsla()`. Tokens not listed keep their current value;
|
||||
comments, selectors and unknown properties are ignored (unknown `--vars` are reported).
|
||||
|
||||
## Modules
|
||||
Settings > Modules lists installed modules (enable switch, Remove with an option to delete
|
||||
their synced data), modules bundled in `assets/modules/` (Install) and "Install from file…"
|
||||
(`file_selector`). Every install shows the module's permissions for consent. Enabled modules
|
||||
add their views to the sidebar under Tags & types (`ModuleRoute`, saved with the tabs) and
|
||||
render their `{{name args}}` macros inside blocks (`ModuleMacro` chips through
|
||||
`RenderContext.macro`; unclaimed macros stay text). `ModulesController` (in `AppState`) sends
|
||||
`tick` requests, `suspend` when a phone app is paused, and applies effects (clipboard with
|
||||
delayed clearing, snack bars, opening a view). Format and API: `docs/modules.md`.
|
||||
|
||||
## Types and tags
|
||||
Both are plain names with no page, shown as one row of pills under the title.
|
||||
- **Type** (what a note is): at most one per page (persona, lugar, empresa, software, sueño,
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
app/ (Flutter, Dart) ──FFI──▶ synapse-ffi ──▶ synapse-core ◀── synapse-search
|
||||
│ ▲ ▲ synapse-import
|
||||
│ │ └─────── synapse-history
|
||||
├──▶ synapse-modules (WASM sandbox, host crypto)
|
||||
├──▶ synapse-ai ──┘ (Embedder) synapse-caldav
|
||||
└──▶ synapse-sync ──HTTP──▶ synapse-server (axum)
|
||||
AI assistant ──MCP stdio──▶ synapse-mcp ──▶ synapse-core │
|
||||
@@ -67,6 +68,14 @@ crates may add their own tables to the same database (prefix them: `search_*`, `
|
||||
- Exports use `synapse-tags::` and `synapse-type::` (see `history.md`); type definitions go
|
||||
to `types.json`.
|
||||
|
||||
## Modules (`synapse-core::module_data`, `synapse-modules`)
|
||||
Sandboxed WebAssembly extensions (`docs/modules.md`). The core only knows their data:
|
||||
`module_data(module, key, value, hlc)` (schema v9), one synced op `PutModuleData` per entry
|
||||
(LWW, NULL value = tombstone), never interpreted by the core. `synapse-modules` runs modules
|
||||
(wasmi, fuel and memory limits), checks permissions on every host call, keeps keys for the
|
||||
`crypto` host functions, and manages installation (`<graph>/modules/`, per device). The FFI
|
||||
exposes install/list/enable/uninstall and JSON requests; the app renders their UI trees.
|
||||
|
||||
## Hubs and namespaces (`synapse-core::structure`)
|
||||
Two orthogonal ways to organise pages.
|
||||
- **Namespace** (kinship by title, derived): `A/B` is a child of `A` (`namespace_parent`,
|
||||
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
# Modules
|
||||
|
||||
Modules extend Synapse without rebuilding the app. A module is one WebAssembly file that runs
|
||||
sandboxed in the app (`crates/synapse-modules`, wasmi interpreter: no JIT, so it runs on
|
||||
Linux, Windows and Android alike) and reaches the app only through host functions allowed by
|
||||
the permissions the user accepted when installing it. Its UI is data: views and block macros
|
||||
are JSON trees the app renders.
|
||||
|
||||
## Installing
|
||||
Settings → Modules: modules bundled with the app (`app/assets/modules/`, offered with an
|
||||
Install button) or **Install from file…** (`.wasm`). The app reads the manifest and shows a
|
||||
consent dialog with the permissions; installing an update with new permissions asks again.
|
||||
Ids starting with `synapse.` are reserved for bundled modules (a file cannot pose as one and
|
||||
inherit its data), and the dialog warns when the graph already holds data under the id
|
||||
(synced from another device), since the module will be able to read it. A block macro name
|
||||
belongs to one installed module: installing another module that claims it is refused.
|
||||
Installed modules live in `<graph>/modules/<id>.wasm` with `modules.json` (enabled flag and
|
||||
granted permissions), so installation is per device. A file swapped on disk cannot gain
|
||||
permissions: they are checked against `modules.json` on every start. Removing a module keeps
|
||||
its data unless "also delete its data" is ticked (that deletion syncs).
|
||||
|
||||
## Writing a module
|
||||
Use the SDK in `modules/sdk` (Rust, `wasm32-unknown-unknown`); `modules/secrets` is a complete
|
||||
example. Build every bundled module with `scripts/build-modules.sh` (needs
|
||||
`rustup target add wasm32-unknown-unknown`; it copies `<id>.wasm` into `app/assets/modules/`,
|
||||
which is committed so the app and the host tests use the same file).
|
||||
|
||||
```rust
|
||||
synapse_module_sdk::manifest!("../manifest.json");
|
||||
synapse_module_sdk::module!(handle);
|
||||
|
||||
fn handle(req: Value) -> Value { json!({ "ui": ui::text("Hello") }) }
|
||||
```
|
||||
|
||||
### Manifest (custom section `synapse.manifest`, JSON)
|
||||
| Field | Meaning |
|
||||
|---|---|
|
||||
| `api` | Module API version, `1` |
|
||||
| `id` | Lowercase letters, digits, `.`, `-`, `_` (≤ 64), e.g. `synapse.secrets` |
|
||||
| `name`, `version`, `description`, `author` | Shown in Settings and the consent dialog |
|
||||
| `permissions` | Any of `storage`, `crypto`, `clipboard`, `pages:read`, `pages:write` |
|
||||
| `views` | `[{id, title, icon?}]`: sidebar entries (icon is an emoji) |
|
||||
| `macros` | Names of `{{name args}}` block macros it renders |
|
||||
| `tick_seconds` | Optional (≥ 5): the app sends `{"op":"tick"}` this often |
|
||||
|
||||
### ABI (API v1)
|
||||
The module exports `memory`, `syn_alloc(len) -> ptr` and `syn_handle(ptr, len)`. The host
|
||||
writes a JSON request into a buffer from `syn_alloc` and calls `syn_handle`, which answers by
|
||||
calling the import `synapse.respond(ptr, len)`. Host calls: `synapse.call(ptr, len) -> n`
|
||||
with `{"fn": name, ...}`, then `synapse.take(ptr)` copies the `n`-byte reply
|
||||
(`{"ok": value}` or `{"error": message}`). The SDK wraps all of this.
|
||||
|
||||
Limits per request: 10⁹ fuel units (about a second of work; a module that runs out is
|
||||
stopped), where every host call also costs 200,000 units plus 20 per byte in and out; at most
|
||||
5,000 host calls, 16 MiB written to storage and 3 key derivations. Per instance: 64 MiB of
|
||||
linear memory, 10,000 table elements, 4 MiB per message. Per module: 64 MiB and 50,000 entries
|
||||
of storage. A module that traps loses its instance
|
||||
(and in-memory state); the next request starts a fresh one.
|
||||
|
||||
### Requests from the app
|
||||
| Request | Expected answer |
|
||||
|---|---|
|
||||
| `{"op":"render","view":id}` | `{"ui": tree}` |
|
||||
| `{"op":"event","view":id,"action":a,"arg":s?,"values":{field id: text}}` | `{"ui": tree, "effects": [...]}` |
|
||||
| `{"op":"macro","name":n,"args":s}` | `{"inline": chip}` |
|
||||
| `{"op":"macro_action","name":n,"args":s,"action":a}` | `{"inline": chip, "effects": [...]}` |
|
||||
| `{"op":"tick"}` | `{"changed": bool}` (true redraws views and macros) |
|
||||
| `{"op":"suspend"}` | `{"changed": bool}`; sent when a phone app is paused |
|
||||
|
||||
Any answer may be `{"error": message}`.
|
||||
|
||||
**UI tree** nodes (`type`): `column{children}`, `row{children}` (fields and pairs stretch),
|
||||
`split{left,right}` (side by side when wide, stacked when narrow), `heading{text}`,
|
||||
`text{text, style: muted|error|mono}`, `divider`, `pair{label, value, mono?, link?}` (links
|
||||
only for http/https), `field{id, label, value, secret?, multiline?, hint?, autofocus?,
|
||||
submit?: action, change?: action, icon?}`, `button{label, action, arg?, style:
|
||||
primary|danger|plain, icon?}`, `list{items, empty}`, `item{title, subtitle, action, arg,
|
||||
selected?}`. A field keeps what the user typed until the module sends a different `value`.
|
||||
Icon names: add, lock, unlock, copy, eye, eye_off, edit, delete, key, refresh, save, close,
|
||||
search, link, person.
|
||||
|
||||
**Chip** (macro): `{text, icon?, masked?, revealed?, error?, actions: [{id, label, icon}]}`.
|
||||
|
||||
**Effects**: `{"copy": {"text", "clear_after_ms"?}}` (needs `clipboard`; the app clears the
|
||||
clipboard later only if it still holds that text), `{"toast": text}`,
|
||||
`{"open_view": view id}`, `{"refresh_macros": true}`.
|
||||
|
||||
### Host functions
|
||||
| `fn` | Permission | Arguments → result |
|
||||
|---|---|---|
|
||||
| `log` | — | `msg` |
|
||||
| `now` | — | → ms since epoch |
|
||||
| `random` | — | `len` (≤ 4096) → base64 |
|
||||
| `kv.get` / `kv.set` / `kv.list` | `storage` | `key`, `value` (string or null to delete), `prefix` → `[{key, value}]` |
|
||||
| `crypto.derive` | `crypto` | `password, salt (b64), memory_kib ≤ 128 MiB, iterations ≤ 10, lanes ≤ 4` → key handle (Argon2id) |
|
||||
| `crypto.generate` | `crypto` | → random key handle |
|
||||
| `crypto.seal` / `crypto.open` | `crypto` | `key, plaintext / data (b64), aad` (XChaCha20-Poly1305, random nonce, `nonce‖ct`) |
|
||||
| `crypto.wrap` / `crypto.unwrap` | `crypto` | `key (kek), target / data, aad` → wrapped key / handle |
|
||||
| `crypto.forget` / `crypto.forget_all` | `crypto` | drop key handles (keys are zeroed) |
|
||||
| `pages.get` | `pages:read` | `title` → `{title, markdown}` or null |
|
||||
| `pages.append` | `pages:write` | `title, text` → adds a block (creates the page) |
|
||||
|
||||
Keys never enter the module: it holds handles; the host keeps the keys (zeroed on drop) and
|
||||
does the cryptography natively (Argon2 inside the interpreter would take seconds). Wrapping
|
||||
uses its own reserved associated data, so a wrapped key cannot be opened as data and data the
|
||||
module sealed cannot be unwrapped as a key.
|
||||
|
||||
`storage` is the module's own key-value store in the graph (`module_data` table, schema v9),
|
||||
synced with the op `put_module_data` (last writer wins per key, deletes are tombstones;
|
||||
keys ≤ 256 bytes, values ≤ 1 MiB). Modules never see each other's data.
|
||||
|
||||
## Secrets (`synapse.secrets`)
|
||||
An encrypted vault: Settings → Modules → Secrets → Install, then the **Secrets** sidebar
|
||||
view. Create the vault with a master password (≥ 8 characters), add entries (name, username,
|
||||
password with a generator, URL, notes), and reference one in any block with
|
||||
`{{secret Name}}`: it shows masked, with buttons to show it (hidden again after 20 s), copy
|
||||
the password or the username (the clipboard clears after 30 s, and when the app is hidden).
|
||||
- Crypto: a random 256-bit data key encrypts every entry (XChaCha20-Poly1305, the entry key
|
||||
as associated data). Each data key has a header `vault/<key id>` wrapping it with a key
|
||||
derived from the master password (Argon2id, 64 MiB, 3 iterations, random salt); `vault`
|
||||
points at the current one. Headers synced with weaker or heavier parameters are ignored.
|
||||
- Changing the password rotates the data key: every entry is re-sealed and the old header
|
||||
deleted. Older ciphertext and headers remain in the op log (and the server's) history, so
|
||||
someone with an old password and that history can read the entries as they were then, not
|
||||
later changes; the same goes for deleted entries.
|
||||
- Only ciphertext is stored and synced; the server and the op log never see names or values.
|
||||
Secrets are not part of history snapshots.
|
||||
- Locks after 5 minutes without use (checked on every request), on request, when the app is
|
||||
hidden or paused, or when the module stops. Forgetting the master password means the
|
||||
secrets are lost.
|
||||
- Two devices that set up a vault before syncing each get a data key; unlocking with the
|
||||
same password moves the other key's entries to the current one. A device whose key was
|
||||
replaced elsewhere (a password change) locks before writing and asks for the password again.
|
||||
- Android: the clipboard is not marked as sensitive (keyboards may show it in their clipboard
|
||||
history); it is cleared when the app is hidden.
|
||||
+7
-6
@@ -1,4 +1,4 @@
|
||||
# Sync protocol (v1)
|
||||
# Sync protocol (v2)
|
||||
|
||||
Replication of a graph between devices through a self-hosted server. The unit of sync is the
|
||||
**op log** of `synapse-core` (`Graph::ops_since` / `Graph::apply_remote`): each op carries a
|
||||
@@ -6,7 +6,7 @@ hybrid logical clock (HLC) `{millis}-{counter}-{actor}`; replicas merge with las
|
||||
per entity plus tombstones, so pushes and pulls are idempotent and order-insensitive.
|
||||
|
||||
Crates: `synapse-sync` (wire types in `protocol`, HTTP transport `Remote`, replicating
|
||||
`SyncClient`) and `synapse-server` (axum). Clients send `X-Synapse-Protocol: 1`; `PUT
|
||||
`SyncClient`) and `synapse-server` (axum). Clients send `X-Synapse-Protocol: 2`; `PUT
|
||||
/v1/graphs/{id}` returns the server's `protocol` and the client refuses a mismatch.
|
||||
|
||||
## Auth
|
||||
@@ -107,10 +107,11 @@ runtime (`start()` spawns onto the current one). After local edits call `trigger
|
||||
|
||||
## Op kinds
|
||||
`upsert_page`, `delete_page`, `upsert_block`, `delete_block`, `put_asset`, `set_alias` and
|
||||
`put_type_def` (type metadata: name, emoji, tombstone; LWW per type name key, schema v8).
|
||||
A client too old to know an op kind cannot parse a pull batch containing it: its sync stops
|
||||
with an error (local edits stay pending) until it is updated. The protocol version was not
|
||||
bumped for `put_type_def`, so update every client together with the server.
|
||||
`put_type_def` (type metadata: name, emoji, tombstone; LWW per type name key, schema v8) and
|
||||
`put_module_data` (a module's key-value entry, `value: null` deletes it; LWW per (module, key),
|
||||
schema v9; see `modules.md`). A client too old to know an op kind cannot parse a pull batch
|
||||
containing it, so new op kinds bump the protocol: v2 added `put_type_def` and
|
||||
`put_module_data`, and v1 clients get a clear version error instead of a stalled sync.
|
||||
|
||||
## Limits / not in v1
|
||||
- Per-user tokens and per-graph ACLs: `auth::Principal` already carries a graph allow-list;
|
||||
|
||||
Generated
+122
@@ -0,0 +1,122 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "base64"
|
||||
version = "0.22.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
|
||||
|
||||
[[package]]
|
||||
name = "itoa"
|
||||
version = "1.0.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.107"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_core"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
|
||||
dependencies = [
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_derive"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_json"
|
||||
version = "1.0.154"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
|
||||
dependencies = [
|
||||
"itoa",
|
||||
"memchr",
|
||||
"serde",
|
||||
"serde_core",
|
||||
"zmij",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "3.0.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "synapse-module-sdk"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "synapse-secrets"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"synapse-module-sdk",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
|
||||
|
||||
[[package]]
|
||||
name = "zmij"
|
||||
version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
|
||||
@@ -0,0 +1,16 @@
|
||||
# Synapse modules, built for wasm32-unknown-unknown (`scripts/build-modules.sh`).
|
||||
# A separate workspace: these crates never build for the host.
|
||||
[workspace]
|
||||
resolver = "3"
|
||||
members = ["sdk", "secrets"]
|
||||
|
||||
[workspace.package]
|
||||
edition = "2024"
|
||||
license = "AGPL-3.0-or-later"
|
||||
|
||||
[profile.release]
|
||||
opt-level = "s"
|
||||
lto = true
|
||||
codegen-units = 1
|
||||
panic = "abort"
|
||||
strip = "debuginfo"
|
||||
@@ -0,0 +1,10 @@
|
||||
[package]
|
||||
name = "synapse-module-sdk"
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
description = "Helpers to write Synapse modules (WebAssembly, module API v1)"
|
||||
|
||||
[dependencies]
|
||||
base64 = "0.22"
|
||||
serde_json = "1"
|
||||
@@ -0,0 +1,321 @@
|
||||
//! Helpers for writing Synapse modules (module API v1). See `docs/modules.md`.
|
||||
//!
|
||||
//! ```ignore
|
||||
//! synapse_module_sdk::manifest!("../manifest.json");
|
||||
//! synapse_module_sdk::module!(handle);
|
||||
//!
|
||||
//! fn handle(req: Value) -> Value {
|
||||
//! json!({ "ui": ui::text("Hello") })
|
||||
//! }
|
||||
//! ```
|
||||
|
||||
pub use serde_json::{self, Value, json};
|
||||
|
||||
use base64::Engine as _;
|
||||
use base64::engine::general_purpose::STANDARD as B64;
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod sys {
|
||||
#[link(wasm_import_module = "synapse")]
|
||||
unsafe extern "C" {
|
||||
pub fn call(ptr: *const u8, len: i32) -> i32;
|
||||
pub fn take(ptr: *mut u8);
|
||||
pub fn respond(ptr: *const u8, len: i32);
|
||||
}
|
||||
}
|
||||
|
||||
/// Embeds the manifest JSON file in the `synapse.manifest` custom section.
|
||||
#[macro_export]
|
||||
macro_rules! manifest {
|
||||
($path:literal) => {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
#[unsafe(link_section = "synapse.manifest")]
|
||||
#[used]
|
||||
static SYNAPSE_MANIFEST: [u8; include_bytes!($path).len()] = *include_bytes!($path);
|
||||
};
|
||||
}
|
||||
|
||||
/// Exports the ABI entry points, routing every request to `$handler: fn(Value) -> Value`.
|
||||
#[macro_export]
|
||||
macro_rules! module {
|
||||
($handler:path) => {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn syn_alloc(len: i32) -> i32 {
|
||||
$crate::__alloc(len)
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn syn_handle(ptr: i32, len: i32) {
|
||||
$crate::__handle(ptr, len, $handler)
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub fn __alloc(len: i32) -> i32 {
|
||||
let mut v = Vec::<u8>::with_capacity(len.max(0) as usize);
|
||||
let p = v.as_mut_ptr();
|
||||
std::mem::forget(v);
|
||||
p as usize as i32
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub fn __handle(ptr: i32, len: i32, handler: fn(Value) -> Value) {
|
||||
let len = len.max(0) as usize;
|
||||
// SAFETY: the host filled a buffer obtained from `__alloc(len)`.
|
||||
let bytes = unsafe { Vec::from_raw_parts(ptr as usize as *mut u8, len, len) };
|
||||
let req = serde_json::from_slice(&bytes).unwrap_or(Value::Null);
|
||||
drop(bytes);
|
||||
let resp = handler(req);
|
||||
let out = serde_json::to_vec(&resp).unwrap_or_else(|_| b"{}".to_vec());
|
||||
respond(&out);
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn respond(out: &[u8]) {
|
||||
// SAFETY: plain FFI with a valid buffer.
|
||||
unsafe { sys::respond(out.as_ptr(), out.len() as i32) }
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn respond(_out: &[u8]) {}
|
||||
|
||||
/// Calls a host function: `args` is an object, `name` goes in its `fn` field.
|
||||
pub fn host(name: &str, args: Value) -> Result<Value, String> {
|
||||
let mut args = match args {
|
||||
Value::Object(m) => m,
|
||||
_ => serde_json::Map::new(),
|
||||
};
|
||||
args.insert("fn".into(), Value::String(name.into()));
|
||||
let req = serde_json::to_vec(&Value::Object(args)).map_err(|e| e.to_string())?;
|
||||
let reply = raw_call(&req)?;
|
||||
let mut v: Value = serde_json::from_slice(&reply).map_err(|e| e.to_string())?;
|
||||
if let Some(e) = v.get("error").and_then(Value::as_str) {
|
||||
return Err(e.to_string());
|
||||
}
|
||||
Ok(v.get_mut("ok").map(Value::take).unwrap_or(Value::Null))
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn raw_call(req: &[u8]) -> Result<Vec<u8>, String> {
|
||||
// SAFETY: plain FFI; `take` writes exactly the announced length into our buffer.
|
||||
unsafe {
|
||||
let n = sys::call(req.as_ptr(), req.len() as i32);
|
||||
let mut buf = vec![0u8; n.max(0) as usize];
|
||||
sys::take(buf.as_mut_ptr());
|
||||
Ok(buf)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn raw_call(_req: &[u8]) -> Result<Vec<u8>, String> {
|
||||
Err("host functions are only available inside Synapse".into())
|
||||
}
|
||||
|
||||
pub fn log(msg: &str) {
|
||||
let _ = host("log", json!({ "msg": msg }));
|
||||
}
|
||||
|
||||
/// Milliseconds since the Unix epoch.
|
||||
pub fn now() -> u64 {
|
||||
host("now", json!({}))
|
||||
.ok()
|
||||
.and_then(|v| v.as_u64())
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
pub fn random(len: usize) -> Result<Vec<u8>, String> {
|
||||
let v = host("random", json!({ "len": len }))?;
|
||||
b64_decode(v.as_str().unwrap_or_default())
|
||||
}
|
||||
|
||||
pub fn b64_encode(bytes: &[u8]) -> String {
|
||||
B64.encode(bytes)
|
||||
}
|
||||
|
||||
pub fn b64_decode(s: &str) -> Result<Vec<u8>, String> {
|
||||
B64.decode(s).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// The module's synced key-value store (`storage` permission).
|
||||
pub mod kv {
|
||||
use super::*;
|
||||
|
||||
pub fn get(key: &str) -> Result<Option<String>, String> {
|
||||
Ok(host("kv.get", json!({ "key": key }))?
|
||||
.as_str()
|
||||
.map(str::to_string))
|
||||
}
|
||||
|
||||
pub fn set(key: &str, value: &str) -> Result<(), String> {
|
||||
host("kv.set", json!({ "key": key, "value": value })).map(|_| ())
|
||||
}
|
||||
|
||||
pub fn delete(key: &str) -> Result<(), String> {
|
||||
host("kv.set", json!({ "key": key, "value": null })).map(|_| ())
|
||||
}
|
||||
|
||||
pub fn list(prefix: &str) -> Result<Vec<(String, String)>, String> {
|
||||
let v = host("kv.list", json!({ "prefix": prefix }))?;
|
||||
Ok(v.as_array()
|
||||
.map(|a| {
|
||||
a.iter()
|
||||
.filter_map(|e| {
|
||||
Some((
|
||||
e.get("key")?.as_str()?.to_string(),
|
||||
e.get("value")?.as_str()?.to_string(),
|
||||
))
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default())
|
||||
}
|
||||
}
|
||||
|
||||
/// Host cryptography (`crypto` permission). Keys are opaque handles held by the host.
|
||||
pub mod crypto {
|
||||
use super::*;
|
||||
|
||||
pub type Key = u32;
|
||||
|
||||
fn key(v: Value) -> Result<Key, String> {
|
||||
v.as_u64()
|
||||
.and_then(|n| u32::try_from(n).ok())
|
||||
.ok_or_else(|| "bad key handle".to_string())
|
||||
}
|
||||
|
||||
/// Argon2id: memory in KiB, iterations, lanes.
|
||||
pub fn derive(
|
||||
password: &str,
|
||||
salt: &[u8],
|
||||
memory_kib: u32,
|
||||
iterations: u32,
|
||||
lanes: u32,
|
||||
) -> Result<Key, String> {
|
||||
key(host(
|
||||
"crypto.derive",
|
||||
json!({
|
||||
"password": password, "salt": b64_encode(salt),
|
||||
"memory_kib": memory_kib, "iterations": iterations, "lanes": lanes,
|
||||
}),
|
||||
)?)
|
||||
}
|
||||
|
||||
pub fn generate() -> Result<Key, String> {
|
||||
key(host("crypto.generate", json!({}))?)
|
||||
}
|
||||
|
||||
/// XChaCha20-Poly1305 with a random nonce; returns base64 of `nonce || ciphertext`.
|
||||
pub fn seal(key: Key, plaintext: &str, aad: &str) -> Result<String, String> {
|
||||
Ok(host(
|
||||
"crypto.seal",
|
||||
json!({ "key": key, "plaintext": plaintext, "aad": aad }),
|
||||
)?
|
||||
.as_str()
|
||||
.unwrap_or_default()
|
||||
.to_string())
|
||||
}
|
||||
|
||||
pub fn open(key: Key, data: &str, aad: &str) -> Result<String, String> {
|
||||
Ok(host(
|
||||
"crypto.open",
|
||||
json!({ "key": key, "data": data, "aad": aad }),
|
||||
)?
|
||||
.as_str()
|
||||
.unwrap_or_default()
|
||||
.to_string())
|
||||
}
|
||||
|
||||
pub fn wrap(kek: Key, target: Key, aad: &str) -> Result<String, String> {
|
||||
Ok(host(
|
||||
"crypto.wrap",
|
||||
json!({ "key": kek, "target": target, "aad": aad }),
|
||||
)?
|
||||
.as_str()
|
||||
.unwrap_or_default()
|
||||
.to_string())
|
||||
}
|
||||
|
||||
pub fn unwrap(kek: Key, data: &str, aad: &str) -> Result<Key, String> {
|
||||
key(host(
|
||||
"crypto.unwrap",
|
||||
json!({ "key": kek, "data": data, "aad": aad }),
|
||||
)?)
|
||||
}
|
||||
|
||||
pub fn forget(key: Key) {
|
||||
let _ = host("crypto.forget", json!({ "key": key }));
|
||||
}
|
||||
|
||||
pub fn forget_all() {
|
||||
let _ = host("crypto.forget_all", json!({}));
|
||||
}
|
||||
}
|
||||
|
||||
/// Builders for the declarative UI the app renders (see `docs/modules.md`).
|
||||
pub mod ui {
|
||||
use super::*;
|
||||
|
||||
pub fn column(children: Vec<Value>) -> Value {
|
||||
json!({ "type": "column", "children": children })
|
||||
}
|
||||
|
||||
pub fn row(children: Vec<Value>) -> Value {
|
||||
json!({ "type": "row", "children": children })
|
||||
}
|
||||
|
||||
/// Two panes side by side on wide screens, stacked on narrow ones.
|
||||
pub fn split(left: Value, right: Value) -> Value {
|
||||
json!({ "type": "split", "left": left, "right": right })
|
||||
}
|
||||
|
||||
pub fn heading(text: &str) -> Value {
|
||||
json!({ "type": "heading", "text": text })
|
||||
}
|
||||
|
||||
/// `style`: "body", "muted", "error" or "mono".
|
||||
pub fn text(text: &str) -> Value {
|
||||
json!({ "type": "text", "text": text })
|
||||
}
|
||||
|
||||
pub fn styled(text: &str, style: &str) -> Value {
|
||||
json!({ "type": "text", "text": text, "style": style })
|
||||
}
|
||||
|
||||
pub fn divider() -> Value {
|
||||
json!({ "type": "divider" })
|
||||
}
|
||||
|
||||
/// A labelled value; `mono` for passwords and codes.
|
||||
pub fn pair(label: &str, value: &str, mono: bool) -> Value {
|
||||
json!({ "type": "pair", "label": label, "value": value, "mono": mono })
|
||||
}
|
||||
|
||||
/// A text field; its current text is sent as `values[id]` with every event.
|
||||
pub fn field(id: &str, label: &str, value: &str) -> Value {
|
||||
json!({ "type": "field", "id": id, "label": label, "value": value })
|
||||
}
|
||||
|
||||
/// `style`: "primary", "danger" or "plain".
|
||||
pub fn button(label: &str, action: &str, style: &str) -> Value {
|
||||
json!({ "type": "button", "label": label, "action": action, "style": style })
|
||||
}
|
||||
|
||||
pub fn list(items: Vec<Value>, empty: &str) -> Value {
|
||||
json!({ "type": "list", "items": items, "empty": empty })
|
||||
}
|
||||
|
||||
pub fn item(title: &str, subtitle: &str, action: &str, arg: &str) -> Value {
|
||||
json!({ "type": "item", "title": title, "subtitle": subtitle, "action": action, "arg": arg })
|
||||
}
|
||||
|
||||
/// Sets extra properties on a widget (`with(field(..), json!({"secret": true}))`).
|
||||
pub fn with(mut w: Value, extra: Value) -> Value {
|
||||
if let (Some(o), Value::Object(e)) = (w.as_object_mut(), extra) {
|
||||
o.extend(e);
|
||||
}
|
||||
w
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
[package]
|
||||
name = "synapse-secrets"
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
description = "Synapse module: an encrypted vault of secrets"
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib", "rlib"]
|
||||
|
||||
[dependencies]
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
synapse-module-sdk = { path = "../sdk" }
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"api": 1,
|
||||
"id": "synapse.secrets",
|
||||
"name": "Secrets",
|
||||
"version": "0.1.0",
|
||||
"description": "An encrypted vault for passwords and other secrets, unlocked with a master password. Reference an entry in a block with {{secret Name}}.",
|
||||
"author": "Synapse",
|
||||
"permissions": ["storage", "crypto", "clipboard"],
|
||||
"views": [{ "id": "vault", "title": "Secrets", "icon": "🔑" }],
|
||||
"macros": ["secret"],
|
||||
"tick_seconds": 15
|
||||
}
|
||||
@@ -0,0 +1,986 @@
|
||||
//! Secrets: an encrypted vault for passwords and other secrets.
|
||||
//!
|
||||
//! Storage (the module's synced key-value store, so the server only ever sees ciphertext):
|
||||
//! - `vault/<key id>`: a header `{v, key_id, kdf: {memory_kib, iterations, lanes}, salt, key}`.
|
||||
//! `key` is a random data key wrapped by a key derived from the master password (Argon2id).
|
||||
//! Each data key has its own header, so a header written by another device never replaces
|
||||
//! one this device still uses.
|
||||
//! - `vault`: `{current: <key id>}`, the data key new entries use.
|
||||
//! - `entry/<id>`: `{k: <key id>, c: <ciphertext>}`, one entry (name, username, password,
|
||||
//! url, notes) sealed (XChaCha20-Poly1305) with data key `k`, with `entry/<id>` bound as
|
||||
//! associated data so entries cannot be swapped.
|
||||
//!
|
||||
//! Unlocking tries the password on every header; entries under another unlocked data key
|
||||
//! (two devices that set up a vault before syncing) are re-sealed under the current one and
|
||||
//! the extra headers dropped. Changing the password rotates the data key: every entry is
|
||||
//! re-sealed and the old header deleted, so an old password no longer opens current data
|
||||
//! (older ciphertext stays in the op log history; see docs/modules.md).
|
||||
//!
|
||||
//! Keys live in the host (`crypto` host functions); this module only holds handles, and
|
||||
//! decrypted entries while unlocked. The vault locks after [`AUTO_LOCK_MS`] without use (checked
|
||||
//! on every request), when the app is suspended or hidden, or on request. A revealed password
|
||||
//! hides again after [`REVEAL_MS`].
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use synapse_module_sdk::{Value, crypto, json, kv, ui};
|
||||
|
||||
synapse_module_sdk::manifest!("../manifest.json");
|
||||
synapse_module_sdk::module!(handle);
|
||||
|
||||
pub const AUTO_LOCK_MS: u64 = 5 * 60 * 1000;
|
||||
pub const REVEAL_MS: u64 = 20 * 1000;
|
||||
pub const CLIPBOARD_CLEAR_MS: u64 = 30 * 1000;
|
||||
pub const MIN_PASSWORD: usize = 8;
|
||||
const POINTER_KEY: &str = "vault";
|
||||
const HEADER_PREFIX: &str = "vault/";
|
||||
const ENTRY_PREFIX: &str = "entry/";
|
||||
const AAD_VAULT: &str = "synapse.secrets/vault/v1/";
|
||||
const KDF_MEMORY_KIB: u32 = 64 * 1024;
|
||||
const KDF_ITERATIONS: u32 = 3;
|
||||
const KDF_LANES: u32 = 1;
|
||||
/// Headers tried when unlocking (each costs one Argon2 run).
|
||||
const MAX_HEADERS: usize = 3;
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct Kdf {
|
||||
memory_kib: u32,
|
||||
iterations: u32,
|
||||
lanes: u32,
|
||||
}
|
||||
|
||||
impl Kdf {
|
||||
/// Synced headers are untrusted: refuse parameters that are too weak to protect the
|
||||
/// password or too heavy for a phone.
|
||||
fn acceptable(&self) -> bool {
|
||||
(32 * 1024..=128 * 1024).contains(&self.memory_kib)
|
||||
&& (2..=6).contains(&self.iterations)
|
||||
&& (1..=4).contains(&self.lanes)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct Header {
|
||||
v: u32,
|
||||
key_id: String,
|
||||
kdf: Kdf,
|
||||
salt: String,
|
||||
key: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct Pointer {
|
||||
current: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct Sealed {
|
||||
k: String,
|
||||
c: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Default, Serialize, Deserialize)]
|
||||
struct Entry {
|
||||
#[serde(skip)]
|
||||
id: String,
|
||||
name: String,
|
||||
#[serde(default)]
|
||||
username: String,
|
||||
#[serde(default)]
|
||||
password: String,
|
||||
#[serde(default)]
|
||||
url: String,
|
||||
#[serde(default)]
|
||||
notes: String,
|
||||
#[serde(default)]
|
||||
updated: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq)]
|
||||
enum Screen {
|
||||
List,
|
||||
Edit(Option<String>),
|
||||
ConfirmDelete(String),
|
||||
ChangePassword,
|
||||
}
|
||||
|
||||
struct State {
|
||||
/// The current data key: its id and handle.
|
||||
dek: Option<(String, crypto::Key)>,
|
||||
entries: Vec<Entry>,
|
||||
unreadable: usize,
|
||||
last_activity: u64,
|
||||
screen: Screen,
|
||||
filter: String,
|
||||
selected: Option<String>,
|
||||
/// When the selected entry's password was revealed.
|
||||
revealed_at: Option<u64>,
|
||||
/// Entry names (lowercase) revealed inline in blocks, with when.
|
||||
inline_revealed: Vec<(String, u64)>,
|
||||
/// Form values kept across renders (edit form after "Generate").
|
||||
form: serde_json::Map<String, Value>,
|
||||
message: Option<(String, bool)>,
|
||||
}
|
||||
|
||||
impl State {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
dek: None,
|
||||
entries: Vec::new(),
|
||||
unreadable: 0,
|
||||
last_activity: 0,
|
||||
screen: Screen::List,
|
||||
filter: String::new(),
|
||||
selected: None,
|
||||
revealed_at: None,
|
||||
inline_revealed: Vec::new(),
|
||||
form: serde_json::Map::new(),
|
||||
message: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static STATE: std::cell::RefCell<State> = std::cell::RefCell::new(State::new());
|
||||
}
|
||||
|
||||
fn entry_aad(id: &str) -> String {
|
||||
format!("synapse.secrets/{ENTRY_PREFIX}{id}")
|
||||
}
|
||||
|
||||
fn hex(bytes: &[u8]) -> String {
|
||||
bytes.iter().map(|b| format!("{b:02x}")).collect()
|
||||
}
|
||||
|
||||
/// A random password from letters, digits and symbols (rejection sampling, no bias).
|
||||
pub fn generate_password(len: usize) -> Result<String, String> {
|
||||
const ALPHABET: &[u8] =
|
||||
b"ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789!#$%&*+-=?@^_~";
|
||||
let limit = 256 - (256 % ALPHABET.len());
|
||||
let mut out = String::with_capacity(len);
|
||||
while out.len() < len {
|
||||
for b in synapse_module_sdk::random(len * 2)? {
|
||||
if (b as usize) < limit && out.len() < len {
|
||||
out.push(ALPHABET[b as usize % ALPHABET.len()] as char);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn pointer() -> Result<Option<String>, String> {
|
||||
Ok(kv::get(POINTER_KEY)?
|
||||
.and_then(|s| serde_json::from_str::<Pointer>(&s).ok())
|
||||
.map(|p| p.current))
|
||||
}
|
||||
|
||||
/// Valid headers, the current one first.
|
||||
fn headers() -> Result<Vec<Header>, String> {
|
||||
let current = pointer()?;
|
||||
let mut hs: Vec<Header> = kv::list(HEADER_PREFIX)?
|
||||
.into_iter()
|
||||
.filter_map(|(k, v)| {
|
||||
let h: Header = serde_json::from_str(&v).ok()?;
|
||||
(k[HEADER_PREFIX.len()..] == h.key_id && h.kdf.acceptable()).then_some(h)
|
||||
})
|
||||
.collect();
|
||||
hs.sort_by_key(|h| Some(&h.key_id) != current.as_ref());
|
||||
Ok(hs)
|
||||
}
|
||||
|
||||
fn derive(password: &str, h: &Header) -> Result<crypto::Key, String> {
|
||||
let salt = synapse_module_sdk::b64_decode(&h.salt)?;
|
||||
crypto::derive(
|
||||
password,
|
||||
&salt,
|
||||
h.kdf.memory_kib,
|
||||
h.kdf.iterations,
|
||||
h.kdf.lanes,
|
||||
)
|
||||
}
|
||||
|
||||
/// The data key of `h` if `password` opens it.
|
||||
fn open_header(password: &str, h: &Header) -> Result<Option<crypto::Key>, String> {
|
||||
let kek = derive(password, h)?;
|
||||
let dek = crypto::unwrap(kek, &h.key, &format!("{AAD_VAULT}{}", h.key_id));
|
||||
crypto::forget(kek);
|
||||
Ok(dek.ok())
|
||||
}
|
||||
|
||||
/// Writes the header of a data key and makes it current.
|
||||
fn save_header(password: &str, key_id: &str, dek: crypto::Key) -> Result<(), String> {
|
||||
let salt = synapse_module_sdk::random(16)?;
|
||||
let mut h = Header {
|
||||
v: 1,
|
||||
key_id: key_id.to_string(),
|
||||
kdf: Kdf {
|
||||
memory_kib: KDF_MEMORY_KIB,
|
||||
iterations: KDF_ITERATIONS,
|
||||
lanes: KDF_LANES,
|
||||
},
|
||||
salt: synapse_module_sdk::b64_encode(&salt),
|
||||
key: String::new(),
|
||||
};
|
||||
let kek = derive(password, &h)?;
|
||||
let wrapped = crypto::wrap(kek, dek, &format!("{AAD_VAULT}{key_id}"));
|
||||
crypto::forget(kek);
|
||||
h.key = wrapped?;
|
||||
kv::set(&format!("{HEADER_PREFIX}{key_id}"), &to_json(&h)?)?;
|
||||
set_pointer(key_id)
|
||||
}
|
||||
|
||||
fn set_pointer(key_id: &str) -> Result<(), String> {
|
||||
kv::set(
|
||||
POINTER_KEY,
|
||||
&to_json(&Pointer {
|
||||
current: key_id.to_string(),
|
||||
})?,
|
||||
)
|
||||
}
|
||||
|
||||
fn to_json<T: Serialize>(v: &T) -> Result<String, String> {
|
||||
serde_json::to_string(v).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
fn lock(s: &mut State) {
|
||||
crypto::forget_all();
|
||||
s.dek = None;
|
||||
s.entries.clear();
|
||||
s.unreadable = 0;
|
||||
s.screen = Screen::List;
|
||||
s.selected = None;
|
||||
s.revealed_at = None;
|
||||
s.inline_revealed.clear();
|
||||
s.form.clear();
|
||||
}
|
||||
|
||||
fn sealed_entries() -> Result<Vec<(String, Sealed)>, String> {
|
||||
Ok(kv::list(ENTRY_PREFIX)?
|
||||
.into_iter()
|
||||
.filter_map(|(k, v)| {
|
||||
let sealed = serde_json::from_str::<Sealed>(&v).ok()?;
|
||||
Some((k[ENTRY_PREFIX.len()..].to_string(), sealed))
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
fn seal_entry(key_id: &str, dek: crypto::Key, e: &Entry) -> Result<(), String> {
|
||||
let plain = serde_json::to_string(e).map_err(|e| e.to_string())?;
|
||||
let c = crypto::seal(dek, &plain, &entry_aad(&e.id))?;
|
||||
let sealed = Sealed {
|
||||
k: key_id.to_string(),
|
||||
c,
|
||||
};
|
||||
kv::set(&format!("{ENTRY_PREFIX}{}", e.id), &to_json(&sealed)?)
|
||||
}
|
||||
|
||||
fn open_entry(id: &str, dek: crypto::Key, sealed: &Sealed) -> Option<Entry> {
|
||||
let plain = crypto::open(dek, &sealed.c, &entry_aad(id)).ok()?;
|
||||
let mut e: Entry = serde_json::from_str(&plain).ok()?;
|
||||
e.id = id.to_string();
|
||||
Some(e)
|
||||
}
|
||||
|
||||
/// Re-seals every entry under `from` keys with `to` and returns how many moved.
|
||||
fn reseal(from: &[(String, crypto::Key)], to: &(String, crypto::Key)) -> Result<usize, String> {
|
||||
let mut moved = 0;
|
||||
for (id, sealed) in sealed_entries()? {
|
||||
let Some((_, k)) = from.iter().find(|(kid, _)| *kid == sealed.k) else {
|
||||
continue;
|
||||
};
|
||||
if let Some(e) = open_entry(&id, *k, &sealed) {
|
||||
seal_entry(&to.0, to.1, &e)?;
|
||||
moved += 1;
|
||||
}
|
||||
}
|
||||
Ok(moved)
|
||||
}
|
||||
|
||||
/// Tries `password` on the vault headers. On success the current data key is set, and
|
||||
/// entries under other data keys it opened are moved to it.
|
||||
fn unlock(s: &mut State, password: &str) -> Result<bool, String> {
|
||||
let hs = headers()?;
|
||||
if hs.is_empty() {
|
||||
return Err("there is no vault yet".into());
|
||||
}
|
||||
let mut keys = Vec::new();
|
||||
for h in hs.iter().take(MAX_HEADERS) {
|
||||
if let Some(k) = open_header(password, h)? {
|
||||
keys.push((h.key_id.clone(), k));
|
||||
}
|
||||
}
|
||||
if keys.is_empty() {
|
||||
return Ok(false);
|
||||
}
|
||||
let current = keys.remove(0);
|
||||
if !keys.is_empty() {
|
||||
reseal(&keys, ¤t)?;
|
||||
for (id, k) in &keys {
|
||||
kv::delete(&format!("{HEADER_PREFIX}{id}"))?;
|
||||
crypto::forget(*k);
|
||||
}
|
||||
}
|
||||
if pointer()?.as_ref() != Some(¤t.0) {
|
||||
set_pointer(¤t.0)?;
|
||||
}
|
||||
let skipped = hs.len() - keys.len() - 1;
|
||||
if skipped > 0 {
|
||||
s.message = Some((
|
||||
format!(
|
||||
"{skipped} other vault key(s) use a different password; their entries stay \
|
||||
unreadable until unlocked with it."
|
||||
),
|
||||
true,
|
||||
));
|
||||
}
|
||||
s.dek = Some(current);
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// False (and the vault locks) when another device replaced the current data key: writing
|
||||
/// with ours would create entries nobody else can read.
|
||||
fn still_current(s: &mut State) -> Result<bool, String> {
|
||||
let Some((id, _)) = &s.dek else {
|
||||
return Ok(false);
|
||||
};
|
||||
let ok = pointer()?.as_ref() == Some(id) && kv::get(&format!("{HEADER_PREFIX}{id}"))?.is_some();
|
||||
if !ok {
|
||||
lock(s);
|
||||
s.message = Some((
|
||||
"The vault changed on another device. Unlock it again.".into(),
|
||||
true,
|
||||
));
|
||||
}
|
||||
Ok(ok)
|
||||
}
|
||||
|
||||
fn load_entries(s: &mut State) -> Result<(), String> {
|
||||
let Some((key_id, dek)) = s.dek.clone() else {
|
||||
return Ok(());
|
||||
};
|
||||
let mut entries = Vec::new();
|
||||
let mut unreadable = 0;
|
||||
for (key, value) in kv::list(ENTRY_PREFIX)? {
|
||||
let id = &key[ENTRY_PREFIX.len()..];
|
||||
match serde_json::from_str::<Sealed>(&value)
|
||||
.ok()
|
||||
.filter(|sealed| sealed.k == key_id)
|
||||
.and_then(|sealed| open_entry(id, dek, &sealed))
|
||||
{
|
||||
Some(e) => entries.push(e),
|
||||
None => unreadable += 1,
|
||||
}
|
||||
}
|
||||
entries.sort_by_key(|e| e.name.to_lowercase());
|
||||
s.entries = entries;
|
||||
s.unreadable = unreadable;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn save_entry(s: &State, e: &Entry) -> Result<(), String> {
|
||||
let (key_id, dek) = s.dek.as_ref().ok_or("the vault is locked")?;
|
||||
seal_entry(key_id, *dek, e)
|
||||
}
|
||||
|
||||
fn find<'a>(s: &'a State, name: &str) -> Option<&'a Entry> {
|
||||
let key = name.trim().to_lowercase();
|
||||
s.entries
|
||||
.iter()
|
||||
.find(|e| e.name.trim().to_lowercase() == key)
|
||||
}
|
||||
|
||||
fn value<'a>(req: &'a Value, id: &str) -> &'a str {
|
||||
req.get("values")
|
||||
.and_then(|v| v.get(id))
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("")
|
||||
}
|
||||
|
||||
fn copy(text: &str) -> Value {
|
||||
json!({ "copy": { "text": text, "clear_after_ms": CLIPBOARD_CLEAR_MS } })
|
||||
}
|
||||
|
||||
fn toast(text: &str) -> Value {
|
||||
json!({ "toast": text })
|
||||
}
|
||||
|
||||
pub fn handle(req: Value) -> Value {
|
||||
STATE.with(|cell| {
|
||||
let mut s = cell.borrow_mut();
|
||||
let was_unlocked = s.dek.is_some();
|
||||
let now = synapse_module_sdk::now();
|
||||
let op = req.get("op").and_then(Value::as_str).unwrap_or("");
|
||||
// Every request checks the idle timeout before counting as activity, so a late tick
|
||||
// cannot leave the vault usable.
|
||||
if s.dek.is_some() && now.saturating_sub(s.last_activity) > AUTO_LOCK_MS {
|
||||
lock(&mut s);
|
||||
s.message = Some(("Locked after inactivity.".into(), false));
|
||||
}
|
||||
let result = match op {
|
||||
"render" => render(&mut s).map(|ui| json!({ "ui": ui })),
|
||||
"event" => {
|
||||
s.last_activity = now;
|
||||
event(&mut s, &req, now)
|
||||
}
|
||||
"macro" => Ok(json!({ "inline": inline(&s, args(&req), now) })),
|
||||
"macro_action" => {
|
||||
s.last_activity = now;
|
||||
macro_action(&mut s, &req, now)
|
||||
}
|
||||
"tick" => {
|
||||
Ok(json!({ "changed": tick(&mut s, now) || was_unlocked && s.dek.is_none() }))
|
||||
}
|
||||
"suspend" => {
|
||||
let was = s.dek.is_some();
|
||||
lock(&mut s);
|
||||
Ok(json!({ "changed": was }))
|
||||
}
|
||||
_ => Err(format!("unknown request {op:?}")),
|
||||
};
|
||||
result.unwrap_or_else(|e| json!({ "error": e }))
|
||||
})
|
||||
}
|
||||
|
||||
fn args(req: &Value) -> &str {
|
||||
req.get("args").and_then(Value::as_str).unwrap_or("").trim()
|
||||
}
|
||||
|
||||
fn tick(s: &mut State, now: u64) -> bool {
|
||||
let mut changed = false;
|
||||
if s.dek.is_some() && now.saturating_sub(s.last_activity) > AUTO_LOCK_MS {
|
||||
lock(s);
|
||||
s.message = Some(("Locked after inactivity.".into(), false));
|
||||
return true;
|
||||
}
|
||||
if s.revealed_at
|
||||
.is_some_and(|t| now.saturating_sub(t) > REVEAL_MS)
|
||||
{
|
||||
s.revealed_at = None;
|
||||
changed = true;
|
||||
}
|
||||
let before = s.inline_revealed.len();
|
||||
s.inline_revealed
|
||||
.retain(|(_, t)| now.saturating_sub(*t) <= REVEAL_MS);
|
||||
changed || before != s.inline_revealed.len()
|
||||
}
|
||||
|
||||
fn event(s: &mut State, req: &Value, now: u64) -> Result<Value, String> {
|
||||
let action = req.get("action").and_then(Value::as_str).unwrap_or("");
|
||||
let arg = req
|
||||
.get("arg")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
let mut effects: Vec<Value> = Vec::new();
|
||||
s.message = None;
|
||||
match action {
|
||||
"setup" => {
|
||||
let (pw, confirm) = (value(req, "password"), value(req, "confirm"));
|
||||
if !headers()?.is_empty() {
|
||||
s.message = Some(("A vault already exists: unlock it.".into(), true));
|
||||
} else if pw.chars().count() < MIN_PASSWORD {
|
||||
s.message = Some((format!("Use at least {MIN_PASSWORD} characters."), true));
|
||||
} else if pw != confirm {
|
||||
s.message = Some(("The passwords do not match.".into(), true));
|
||||
} else {
|
||||
let dek = crypto::generate()?;
|
||||
let key_id = hex(&synapse_module_sdk::random(8)?);
|
||||
save_header(pw, &key_id, dek)?;
|
||||
s.dek = Some((key_id, dek));
|
||||
s.entries.clear();
|
||||
effects.push(json!({ "refresh_macros": true }));
|
||||
}
|
||||
}
|
||||
"unlock" => {
|
||||
if unlock(s, value(req, "password"))? {
|
||||
s.screen = Screen::List;
|
||||
effects.push(json!({ "refresh_macros": true }));
|
||||
} else {
|
||||
s.message = Some(("Wrong password.".into(), true));
|
||||
}
|
||||
}
|
||||
"lock" => {
|
||||
lock(s);
|
||||
effects.push(json!({ "refresh_macros": true }));
|
||||
}
|
||||
_ if s.dek.is_none() => {
|
||||
s.message = Some(("The vault is locked.".into(), true));
|
||||
}
|
||||
"filter" => s.filter = value(req, "filter").to_string(),
|
||||
"select" => {
|
||||
s.selected = Some(arg);
|
||||
s.revealed_at = None;
|
||||
s.screen = Screen::List;
|
||||
}
|
||||
"new" => {
|
||||
s.form.clear();
|
||||
s.screen = Screen::Edit(None);
|
||||
}
|
||||
"edit" => {
|
||||
s.form.clear();
|
||||
s.screen = Screen::Edit(Some(arg));
|
||||
}
|
||||
"generate" => {
|
||||
if let Some(v) = req.get("values").and_then(Value::as_object) {
|
||||
s.form = v.clone();
|
||||
}
|
||||
s.form
|
||||
.insert("password".into(), Value::String(generate_password(20)?));
|
||||
}
|
||||
"save" => {
|
||||
let name = value(req, "name").trim().to_string();
|
||||
let id = match &s.screen {
|
||||
Screen::Edit(id) => id.clone(),
|
||||
_ => None,
|
||||
};
|
||||
if name.is_empty() {
|
||||
s.form = req
|
||||
.get("values")
|
||||
.and_then(Value::as_object)
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
s.message = Some(("The name is required.".into(), true));
|
||||
} else if s.entries.iter().any(|e| {
|
||||
e.name.trim().to_lowercase() == name.to_lowercase() && Some(&e.id) != id.as_ref()
|
||||
}) {
|
||||
s.form = req
|
||||
.get("values")
|
||||
.and_then(Value::as_object)
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
s.message = Some((format!("There is already an entry called {name}."), true));
|
||||
} else if still_current(s)? {
|
||||
let id = match id {
|
||||
Some(id) => id,
|
||||
None => hex(&synapse_module_sdk::random(12)?),
|
||||
};
|
||||
let e = Entry {
|
||||
id: id.clone(),
|
||||
name,
|
||||
username: value(req, "username").to_string(),
|
||||
password: value(req, "password").to_string(),
|
||||
url: value(req, "url").trim().to_string(),
|
||||
notes: value(req, "notes").to_string(),
|
||||
updated: now,
|
||||
};
|
||||
save_entry(s, &e)?;
|
||||
s.form.clear();
|
||||
s.selected = Some(id);
|
||||
s.screen = Screen::List;
|
||||
effects.push(json!({ "refresh_macros": true }));
|
||||
}
|
||||
}
|
||||
"cancel" => {
|
||||
s.form.clear();
|
||||
s.screen = Screen::List;
|
||||
}
|
||||
"delete" => s.screen = Screen::ConfirmDelete(arg),
|
||||
"confirm_delete" => {
|
||||
if let Screen::ConfirmDelete(id) = s.screen.clone()
|
||||
&& still_current(s)?
|
||||
{
|
||||
kv::delete(&format!("{ENTRY_PREFIX}{id}"))?;
|
||||
if s.selected.as_ref() == Some(&id) {
|
||||
s.selected = None;
|
||||
}
|
||||
s.screen = Screen::List;
|
||||
}
|
||||
effects.push(json!({ "refresh_macros": true }));
|
||||
}
|
||||
"reveal" => {
|
||||
s.revealed_at = match s.revealed_at {
|
||||
Some(_) => None,
|
||||
None => Some(now),
|
||||
}
|
||||
}
|
||||
"copy_password" | "copy_username" => {
|
||||
load_entries(s)?;
|
||||
if let Some(e) = s.entries.iter().find(|e| e.id == arg) {
|
||||
let (text, what) = if action == "copy_password" {
|
||||
(&e.password, "Password")
|
||||
} else {
|
||||
(&e.username, "Username")
|
||||
};
|
||||
effects.push(copy(text));
|
||||
effects.push(toast(&format!(
|
||||
"{what} copied; the clipboard clears in 30 s."
|
||||
)));
|
||||
}
|
||||
}
|
||||
"change_password" => s.screen = Screen::ChangePassword,
|
||||
"save_password" => {
|
||||
let (cur, new, confirm) = (
|
||||
value(req, "current"),
|
||||
value(req, "new"),
|
||||
value(req, "confirm"),
|
||||
);
|
||||
if new.chars().count() < MIN_PASSWORD {
|
||||
s.message = Some((format!("Use at least {MIN_PASSWORD} characters."), true));
|
||||
} else if new != confirm {
|
||||
s.message = Some(("The new passwords do not match.".into(), true));
|
||||
} else if still_current(s)? {
|
||||
let (old_id, old_dek) = s.dek.clone().ok_or("the vault is locked")?;
|
||||
let hs = headers()?;
|
||||
let h = hs
|
||||
.iter()
|
||||
.find(|h| h.key_id == old_id)
|
||||
.ok_or("the vault header is missing")?;
|
||||
match open_header(cur, h)? {
|
||||
None => s.message = Some(("The current password is wrong.".into(), true)),
|
||||
Some(k) => {
|
||||
crypto::forget(k);
|
||||
// Rotate the data key: an old password (and old headers kept by sync
|
||||
// history) must not open what is stored from now on.
|
||||
let new_dek = crypto::generate()?;
|
||||
let new_id = hex(&synapse_module_sdk::random(8)?);
|
||||
let next = (new_id.clone(), new_dek);
|
||||
reseal(&[(old_id.clone(), old_dek)], &next)?;
|
||||
save_header(new, &new_id, new_dek)?;
|
||||
for h in &hs {
|
||||
if h.key_id != new_id {
|
||||
kv::delete(&format!("{HEADER_PREFIX}{}", h.key_id))?;
|
||||
}
|
||||
}
|
||||
crypto::forget(old_dek);
|
||||
s.dek = Some(next);
|
||||
s.screen = Screen::List;
|
||||
s.message = Some(("Master password changed.".into(), false));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
other => return Err(format!("unknown action {other:?}")),
|
||||
}
|
||||
Ok(json!({ "ui": render(s)?, "effects": effects }))
|
||||
}
|
||||
|
||||
fn inline(s: &State, name: &str, now: u64) -> Value {
|
||||
if name.is_empty() {
|
||||
return json!({ "text": "secret", "icon": "🔑", "error": "Write {{secret Name}}" });
|
||||
}
|
||||
if s.dek.is_none() {
|
||||
return json!({
|
||||
"text": name, "icon": "🔒", "masked": "locked",
|
||||
"actions": [{ "id": "unlock", "label": "Unlock the vault", "icon": "lock" }],
|
||||
});
|
||||
}
|
||||
let Some(e) = find(s, name) else {
|
||||
return json!({ "text": name, "icon": "🔑", "error": "No such secret" });
|
||||
};
|
||||
let key = e.name.trim().to_lowercase();
|
||||
let revealed = s
|
||||
.inline_revealed
|
||||
.iter()
|
||||
.any(|(n, t)| *n == key && now.saturating_sub(*t) <= REVEAL_MS);
|
||||
let mut actions = vec![
|
||||
json!({ "id": "reveal", "label": if revealed { "Hide" } else { "Show" }, "icon": if revealed { "eye_off" } else { "eye" } }),
|
||||
json!({ "id": "copy", "label": "Copy password", "icon": "copy" }),
|
||||
];
|
||||
if !e.username.is_empty() {
|
||||
actions.push(json!({ "id": "copy_username", "label": "Copy username", "icon": "person" }));
|
||||
}
|
||||
json!({
|
||||
"text": e.name, "icon": "🔑",
|
||||
"masked": if revealed { e.password.clone() } else { "••••••••".to_string() },
|
||||
"revealed": revealed,
|
||||
"actions": actions,
|
||||
})
|
||||
}
|
||||
|
||||
fn macro_action(s: &mut State, req: &Value, now: u64) -> Result<Value, String> {
|
||||
let name = args(req).to_string();
|
||||
let action = req.get("action").and_then(Value::as_str).unwrap_or("");
|
||||
let mut effects = Vec::new();
|
||||
if action == "unlock" || s.dek.is_none() {
|
||||
effects.push(json!({ "open_view": "vault" }));
|
||||
return Ok(json!({ "inline": inline(s, &name, now), "effects": effects }));
|
||||
}
|
||||
load_entries(s)?;
|
||||
if let Some(e) = find(s, &name).cloned() {
|
||||
let key = e.name.trim().to_lowercase();
|
||||
match action {
|
||||
"reveal" => {
|
||||
let before = s.inline_revealed.len();
|
||||
s.inline_revealed.retain(|(n, _)| *n != key);
|
||||
if before == s.inline_revealed.len() {
|
||||
s.inline_revealed.push((key, now));
|
||||
}
|
||||
}
|
||||
"copy" => {
|
||||
effects.push(copy(&e.password));
|
||||
effects.push(toast("Password copied; the clipboard clears in 30 s."));
|
||||
}
|
||||
"copy_username" => {
|
||||
effects.push(copy(&e.username));
|
||||
effects.push(toast("Username copied."));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(json!({ "inline": inline(s, &name, now), "effects": effects }))
|
||||
}
|
||||
|
||||
fn message(s: &State) -> Vec<Value> {
|
||||
s.message
|
||||
.iter()
|
||||
.map(|(m, err)| ui::styled(m, if *err { "error" } else { "muted" }))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn secret_field(id: &str, label: &str, value: &str) -> Value {
|
||||
ui::with(ui::field(id, label, value), json!({ "secret": true }))
|
||||
}
|
||||
|
||||
/// The current screen's tree. Its `key` names the screen: the app starts with fresh fields
|
||||
/// when it changes, so text typed on one screen never shows up on another.
|
||||
fn render(s: &mut State) -> Result<Value, String> {
|
||||
let tree = render_screen(s)?;
|
||||
let key = match (&s.dek, &s.screen) {
|
||||
(None, _) => "locked".to_string(),
|
||||
(_, Screen::List) => "list".to_string(),
|
||||
(_, Screen::Edit(id)) => format!("edit:{}", id.as_deref().unwrap_or("")),
|
||||
(_, Screen::ConfirmDelete(_)) => "delete".to_string(),
|
||||
(_, Screen::ChangePassword) => "password".to_string(),
|
||||
};
|
||||
Ok(ui::with(tree, json!({ "key": key })))
|
||||
}
|
||||
|
||||
fn render_screen(s: &mut State) -> Result<Value, String> {
|
||||
let now = synapse_module_sdk::now();
|
||||
if s.dek.is_some() && now.saturating_sub(s.last_activity) > AUTO_LOCK_MS {
|
||||
lock(s);
|
||||
}
|
||||
let Some(_) = s.dek else {
|
||||
let exists = !headers()?.is_empty();
|
||||
let mut c = vec![ui::heading("Secrets")];
|
||||
if exists {
|
||||
c.push(ui::styled("The vault is locked.", "muted"));
|
||||
c.push(ui::with(
|
||||
secret_field("password", "Master password", ""),
|
||||
json!({ "autofocus": true, "submit": "unlock" }),
|
||||
));
|
||||
c.extend(message(s));
|
||||
c.push(ui::button("Unlock", "unlock", "primary"));
|
||||
} else {
|
||||
c.push(ui::text(
|
||||
"Create a vault protected by a master password. It encrypts every secret on \
|
||||
this device before it is stored or synced; without the password nobody, \
|
||||
including you, can read them again.",
|
||||
));
|
||||
c.push(ui::with(
|
||||
secret_field("password", "Master password", ""),
|
||||
json!({ "autofocus": true }),
|
||||
));
|
||||
c.push(ui::with(
|
||||
secret_field("confirm", "Repeat the password", ""),
|
||||
json!({ "submit": "setup" }),
|
||||
));
|
||||
c.extend(message(s));
|
||||
c.push(ui::button("Create vault", "setup", "primary"));
|
||||
}
|
||||
return Ok(ui::column(c));
|
||||
};
|
||||
load_entries(s)?;
|
||||
Ok(match s.screen.clone() {
|
||||
Screen::Edit(id) => edit_form(s, id.as_deref()),
|
||||
Screen::ConfirmDelete(id) => {
|
||||
let name = s
|
||||
.entries
|
||||
.iter()
|
||||
.find(|e| e.id == id)
|
||||
.map(|e| e.name.clone())
|
||||
.unwrap_or_default();
|
||||
ui::column(vec![
|
||||
ui::heading(&format!("Delete {name}?")),
|
||||
ui::text("It is deleted on every synced device."),
|
||||
ui::row(vec![
|
||||
ui::button("Delete", "confirm_delete", "danger"),
|
||||
ui::button("Cancel", "cancel", "plain"),
|
||||
]),
|
||||
])
|
||||
}
|
||||
Screen::ChangePassword => {
|
||||
let mut c = vec![
|
||||
ui::heading("Change master password"),
|
||||
secret_field("current", "Current password", ""),
|
||||
secret_field("new", "New password", ""),
|
||||
ui::with(
|
||||
secret_field("confirm", "Repeat the new password", ""),
|
||||
json!({ "submit": "save_password" }),
|
||||
),
|
||||
];
|
||||
c.extend(message(s));
|
||||
c.push(ui::row(vec![
|
||||
ui::button("Change", "save_password", "primary"),
|
||||
ui::button("Cancel", "cancel", "plain"),
|
||||
]));
|
||||
ui::column(c)
|
||||
}
|
||||
Screen::List => list_screen(s, now),
|
||||
})
|
||||
}
|
||||
|
||||
fn list_screen(s: &State, now: u64) -> Value {
|
||||
let filter = s.filter.trim().to_lowercase();
|
||||
let items: Vec<Value> = s
|
||||
.entries
|
||||
.iter()
|
||||
.filter(|e| {
|
||||
filter.is_empty()
|
||||
|| e.name.to_lowercase().contains(&filter)
|
||||
|| e.username.to_lowercase().contains(&filter)
|
||||
|| e.url.to_lowercase().contains(&filter)
|
||||
})
|
||||
.map(|e| {
|
||||
ui::with(
|
||||
ui::item(&e.name, &e.username, "select", &e.id),
|
||||
json!({ "selected": s.selected.as_ref() == Some(&e.id) }),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let mut left = vec![
|
||||
ui::row(vec![
|
||||
ui::with(
|
||||
ui::button("New", "new", "primary"),
|
||||
json!({ "icon": "add" }),
|
||||
),
|
||||
ui::with(
|
||||
ui::button("Lock", "lock", "plain"),
|
||||
json!({ "icon": "lock" }),
|
||||
),
|
||||
ui::with(
|
||||
ui::button("Change password", "change_password", "plain"),
|
||||
json!({ "icon": "key" }),
|
||||
),
|
||||
]),
|
||||
ui::with(
|
||||
ui::field("filter", "Search", &s.filter),
|
||||
json!({ "change": "filter", "icon": "search" }),
|
||||
),
|
||||
];
|
||||
left.extend(message(s));
|
||||
if s.unreadable > 0 {
|
||||
left.push(ui::styled(
|
||||
&format!(
|
||||
"{} entries could not be decrypted (another vault key?).",
|
||||
s.unreadable
|
||||
),
|
||||
"error",
|
||||
));
|
||||
}
|
||||
left.push(ui::list(items, "No secrets yet."));
|
||||
let right = match s
|
||||
.selected
|
||||
.as_ref()
|
||||
.and_then(|id| s.entries.iter().find(|e| &e.id == id))
|
||||
{
|
||||
None => ui::styled(
|
||||
"Select a secret. In any block, {{secret Name}} shows it masked with copy buttons.",
|
||||
"muted",
|
||||
),
|
||||
Some(e) => {
|
||||
let revealed = s
|
||||
.revealed_at
|
||||
.is_some_and(|t| now.saturating_sub(t) <= REVEAL_MS);
|
||||
let mut c = vec![ui::heading(&e.name)];
|
||||
if !e.username.is_empty() {
|
||||
c.push(ui::row(vec![
|
||||
ui::pair("Username", &e.username, false),
|
||||
ui::with(
|
||||
ui::button("Copy", "copy_username", "plain"),
|
||||
json!({ "arg": e.id, "icon": "copy" }),
|
||||
),
|
||||
]));
|
||||
}
|
||||
c.push(ui::row(vec![
|
||||
ui::pair(
|
||||
"Password",
|
||||
if revealed {
|
||||
&e.password
|
||||
} else {
|
||||
"••••••••"
|
||||
},
|
||||
true,
|
||||
),
|
||||
ui::with(
|
||||
ui::button(if revealed { "Hide" } else { "Show" }, "reveal", "plain"),
|
||||
json!({ "icon": if revealed { "eye_off" } else { "eye" } }),
|
||||
),
|
||||
ui::with(
|
||||
ui::button("Copy", "copy_password", "plain"),
|
||||
json!({ "arg": e.id, "icon": "copy" }),
|
||||
),
|
||||
]));
|
||||
if !e.url.is_empty() {
|
||||
c.push(ui::with(
|
||||
ui::pair("URL", &e.url, false),
|
||||
json!({ "link": true }),
|
||||
));
|
||||
}
|
||||
if !e.notes.is_empty() {
|
||||
c.push(ui::pair("Notes", &e.notes, false));
|
||||
}
|
||||
c.push(ui::styled(
|
||||
&format!("Use it in a block: {{{{secret {}}}}}", e.name),
|
||||
"muted",
|
||||
));
|
||||
c.push(ui::row(vec![
|
||||
ui::with(
|
||||
ui::button("Edit", "edit", "plain"),
|
||||
json!({ "arg": e.id, "icon": "edit" }),
|
||||
),
|
||||
ui::with(
|
||||
ui::button("Delete", "delete", "danger"),
|
||||
json!({ "arg": e.id, "icon": "delete" }),
|
||||
),
|
||||
]));
|
||||
ui::column(c)
|
||||
}
|
||||
};
|
||||
ui::split(ui::column(left), right)
|
||||
}
|
||||
|
||||
fn edit_form(s: &State, id: Option<&str>) -> Value {
|
||||
let base = id
|
||||
.and_then(|id| s.entries.iter().find(|e| e.id == id))
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let get = |k: &str, d: &str| -> String {
|
||||
s.form
|
||||
.get(k)
|
||||
.and_then(Value::as_str)
|
||||
.map_or_else(|| d.to_string(), str::to_string)
|
||||
};
|
||||
let mut c = vec![
|
||||
ui::heading(if id.is_some() {
|
||||
"Edit secret"
|
||||
} else {
|
||||
"New secret"
|
||||
}),
|
||||
ui::with(
|
||||
ui::field("name", "Name", &get("name", &base.name)),
|
||||
json!({ "autofocus": id.is_none() }),
|
||||
),
|
||||
ui::field("username", "Username", &get("username", &base.username)),
|
||||
ui::row(vec![
|
||||
secret_field("password", "Password", &get("password", &base.password)),
|
||||
ui::with(
|
||||
ui::button("Generate", "generate", "plain"),
|
||||
json!({ "icon": "refresh" }),
|
||||
),
|
||||
]),
|
||||
ui::field("url", "URL", &get("url", &base.url)),
|
||||
ui::with(
|
||||
ui::field("notes", "Notes", &get("notes", &base.notes)),
|
||||
json!({ "multiline": true }),
|
||||
),
|
||||
];
|
||||
c.extend(message(s));
|
||||
c.push(ui::row(vec![
|
||||
ui::with(
|
||||
ui::button("Save", "save", "primary"),
|
||||
json!({ "icon": "save" }),
|
||||
),
|
||||
ui::button("Cancel", "cancel", "plain"),
|
||||
]));
|
||||
ui::column(c)
|
||||
}
|
||||
Executable
+12
@@ -0,0 +1,12 @@
|
||||
#!/usr/bin/env bash
|
||||
# Builds the bundled Synapse modules (modules/*) to WebAssembly and copies them to
|
||||
# app/assets/modules/<module id>.wasm. Needs: rustup target add wasm32-unknown-unknown
|
||||
set -euo pipefail
|
||||
root="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
cd "$root/modules"
|
||||
cargo build --release --target wasm32-unknown-unknown
|
||||
out="$root/app/assets/modules"
|
||||
mkdir -p "$out"
|
||||
# crate name -> module id (the id in its manifest.json)
|
||||
cp target/wasm32-unknown-unknown/release/synapse_secrets.wasm "$out/synapse.secrets.wasm"
|
||||
ls -l "$out"
|
||||
Reference in new issue
Block a user