From fa98fba43ffad44464076c3d05033a6e3035b1ef Mon Sep 17 00:00:00 2001 From: Dasemu Date: Mon, 26 Oct 2026 16:19:45 +0100 Subject: [PATCH] docs: modules, the Secrets vault and sync protocol v2; lint modules in CI Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 6 ++ CLAUDE.md | 4 ++ LESSONS.md | 3 + docs/app.md | 10 ++++ docs/architecture.md | 9 +++ docs/modules.md | 118 +++++++++++++++++++++++++++++++++++++++ docs/sync.md | 13 +++-- 7 files changed, 157 insertions(+), 6 deletions(-) create mode 100644 docs/modules.md diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2dca6f4..73315fe 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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 diff --git a/CLAUDE.md b/CLAUDE.md index 29f36e6..22fa666 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -14,6 +14,8 @@ and an optional self-hosted sync server. Local-only (standalone graph) or client - Run server: `SYNAPSE_DATA_DIR=/tmp/syn SYNAPSE_AUTH_TOKEN=<16+ chars> cargo run -p synapse-server` - 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) @@ -27,6 +29,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-ffi`: the only API surface exposed to Flutter. ## Conventions diff --git a/LESSONS.md b/LESSONS.md index 63babab..16ccad6 100644 --- a/LESSONS.md +++ b/LESSONS.md @@ -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 diff --git a/docs/app.md b/docs/app.md index 45a3f30..56190d9 100644 --- a/docs/app.md +++ b/docs/app.md @@ -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, diff --git a/docs/architecture.md b/docs/architecture.md index c75bd99..3361a5a 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -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) ``` @@ -65,6 +66,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 (`/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`, diff --git a/docs/modules.md b/docs/modules.md new file mode 100644 index 0000000..27bb96f --- /dev/null +++ b/docs/modules.md @@ -0,0 +1,118 @@ +# 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. +Installed modules live in `/modules/.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 `.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), 64 MiB of linear memory, 4 MiB per message. 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 ≤ 256 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). + +`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). +- Crypto: a random 256-bit data key encrypts every entry (XChaCha20-Poly1305, the entry key + as associated data). The data key is wrapped by a key derived from the master password + (Argon2id, 64 MiB, 3 iterations, random salt). Changing the password re-wraps the data key. +- 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, on request, when a phone app is paused, or when the + module stops. Forgetting the master password means the secrets are lost. +- Create the vault on one device and unlock it on the others once synced: two vaults created + offline on two devices would each have their own data key (entries from the other one show + as "could not be decrypted"). diff --git a/docs/sync.md b/docs/sync.md index e3b99f0..ccfd424 100644 --- a/docs/sync.md +++ b/docs/sync.md @@ -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;