25 Commits

Author SHA1 Message Date
adlee-was-taken
dd0010db62 feat(relay): expand to dev-c role + python/ts MCP fallback shims
queue.ts and server.ts now know about dev-c alongside pm/dev-a/dev-b
so the four-role coordination paradigm works end-to-end. start.sh
opens a fourth window for dev-c. call.py and call.ts are HTTP shims
that agents can use when the MCP relay tools aren't registered in
their session (the kickoff prompts reference call.py by path as a
fallback).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-05 17:49:21 -04:00
adlee-was-taken
29146439bb fix(ext): glyph + vault polish — distinct identity glyph, sticky-bar form-actions hidden
GLYPH_TYPE_IDENTITY changed from ⌬ to ◍ so it's visually distinct from
GLYPH_DEVICES (also ⌬). Adds a CSS rule asserting [hidden] over the
.form-actions display:flex so the fullscreen sticky save bar can hide
the inner action row by attribute.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-05 17:49:16 -04:00
adlee-was-taken
cf66bd97b7 chore: bump crate and extension versions to 0.5.0
Catches the workspace and the extension manifests up to the v0.5.x
release line (was still showing 0.2.0).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-05 17:49:09 -04:00
adlee-was-taken
061facd5a9 docs(reviews): whole-codebase architecture audit 2026-05-04
Three-reviewer architecture audit (DEV-A: core, DEV-B: cli/server/wasm,
DEV-C: extension/relay) plus PM synthesis. Lens: make the codebase
readable for a smart developer who doesn't know Rust but wants to learn
by tinkering.

Top synthesis findings (P1):
- SessionHandle has no impl Drop; .free() is a cleanup no-op (cross-cutting Rust+JS)
- cli/main.rs is a 2641-line monolith with no submodule boundaries
- setup.ts (1220 LOC) bypasses the SW and orchestrates WASM directly
- vault.ts (1027 LOC) owns shell + sidebar + list + drawer + routing
- shared/state.ts is fully any-typed
- recovery_qr.rs is undocumented vs. rest of crypto-adjacent core
- duplicated SW router helpers (storage + itemToManifestEntry)
- pure parsers (parse_month_year, base32_decode_lenient) belong in core
- 16x duplicated git invocation boilerplate with one-line errors

CLI/extension parity: 22/23 capabilities ✓; only true gap is `relicario
status` (no get_vault_status); `detach` is partial via update_item.

Also fixes tools/relay/queue.test.ts:54 to match the dev-c role
expansion already in queue.ts (was failing 1/4; now 5/5 pass).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-04 23:27:26 -04:00
adlee-was-taken
bd6a30155e Merge feature/v0.5.1-stream-b-settings: unified left-nav settings (Autofill/Display/Security/Generator/Retention/Backup/Import) 2026-05-03 21:51:43 -04:00
adlee-was-taken
8baef5b3cb fix(ext/settings): restore settings-security.ts from main (Stream C real implementation) 2026-05-03 21:51:08 -04:00
adlee-was-taken
ddfb95d683 fix(ext/settings): call teardownSettings in popup render to prevent listener leak 2026-05-03 21:47:46 -04:00
adlee-was-taken
7df76c692a feat(ext/settings): settings left-nav skeleton with section routing
Two-panel layout (148px nav sidebar + content area) with 7 nav items
(Autofill, Display, Security, Generator, Retention, Backup, Import),
stub section functions, and settings layout CSS classes.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-03 21:46:11 -04:00
adlee-was-taken
b4d253c60b chore(ext/settings): stub settings-security.ts (DEV-C replaces implementation) 2026-05-03 21:45:14 -04:00
adlee-was-taken
c16adc4335 Merge feature/v0.5.1-stream-a-layout: 3-column vault layout, toast system, glyph constants, emoji sweep 2026-05-03 21:41:57 -04:00
adlee-was-taken
9a8cdf8e4f fix: replace all remaining emoji with monochrome glyph constants
- trash.ts TYPE_ICONS map uses GLYPH_TYPE_* constants
- field-history.ts copy button uses GLYPH_COPY
- attachments-disclosure.ts thumbnail/icon uses GLYPH_TYPE_DOCUMENT
- settings.ts sync button uses GLYPH_SYNC
- document.ts thumb/sigblock/preview use GLYPH_TYPE_DOCUMENT + GLYPH_PREVIEW
- glyphs.ts adds GLYPH_COPY, GLYPH_SYNC, GLYPH_PREVIEW
- vault.ts adds GLYPH_DEVICES import + devices sidebar nav button

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-03 21:37:23 -04:00
adlee-was-taken
ade44b4ea1 feat(ext/vault): wire renderSettings / teardownSettings from settings component 2026-05-03 21:37:23 -04:00
adlee-was-taken
1d4b018f9a feat(ext/vault): bottom sheet type picker for new item 2026-05-03 21:37:23 -04:00
adlee-was-taken
882a89bedd feat(ext/vault): detail drawer — open/close state + core fields display 2026-05-03 21:37:23 -04:00
adlee-was-taken
37c20b28a6 feat(ext/vault): 3-column shell — sidebar category nav + list pane 2026-05-03 21:37:23 -04:00
adlee-was-taken
3553150a53 feat(ext/vault): 3-column layout CSS — drawer, bottom sheet, list rows, responsive 2026-05-03 21:37:23 -04:00
adlee-was-taken
b50f49b597 fix(ext/vault): replace emoji typeIcon with glyph constants 2026-05-03 21:37:23 -04:00
adlee-was-taken
1ec8965910 feat(ext): shared toast notification system 2026-05-03 21:37:23 -04:00
adlee-was-taken
ad6e4a2cd9 feat(ext/popup): polished 2-column type-picker with glyph icons 2026-05-03 21:37:23 -04:00
adlee-was-taken
b768f649a2 feat(ext/popup): empty states with glyph icons in item-list 2026-05-03 21:37:23 -04:00
adlee-was-taken
8b197a7525 fix(ext/popup): replace emoji in SETTINGS_OPTIONS with glyph constants 2026-05-03 21:37:23 -04:00
adlee-was-taken
117716f6cf fix(ext/popup): replace emoji typeIcon with glyph constants in item-list 2026-05-03 21:37:23 -04:00
adlee-was-taken
c5e8b52e12 fix(ext/popup): replace inline &#x2934; vault-tab button with GLYPH_VAULT_TAB 2026-05-03 21:37:23 -04:00
adlee-was-taken
a1b66a9147 feat(ext/glyphs): add GLYPH_VAULT_TAB and per-type icon constants 2026-05-03 21:37:23 -04:00
adlee-was-taken
934dfe05c2 Merge feature/v0.5.1-stream-c-recovery-qr: Recovery QR (Rust core + WASM + CLI + settings-security.ts + setup wizard) 2026-05-03 21:26:40 -04:00
33 changed files with 2823 additions and 348 deletions

6
Cargo.lock generated
View File

@@ -2156,7 +2156,7 @@ checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a"
[[package]] [[package]]
name = "relicario-cli" name = "relicario-cli"
version = "0.2.0" version = "0.5.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"arboard", "arboard",
@@ -2185,7 +2185,7 @@ dependencies = [
[[package]] [[package]]
name = "relicario-core" name = "relicario-core"
version = "0.2.0" version = "0.5.0"
dependencies = [ dependencies = [
"argon2", "argon2",
"base64", "base64",
@@ -2231,7 +2231,7 @@ dependencies = [
[[package]] [[package]]
name = "relicario-wasm" name = "relicario-wasm"
version = "0.2.0" version = "0.5.0"
dependencies = [ dependencies = [
"base64", "base64",
"ed25519-dalek", "ed25519-dalek",

View File

@@ -1,6 +1,6 @@
[package] [package]
name = "relicario-cli" name = "relicario-cli"
version = "0.2.0" version = "0.5.0"
edition = "2021" edition = "2021"
description = "CLI for relicario password manager" description = "CLI for relicario password manager"

View File

@@ -1,6 +1,6 @@
[package] [package]
name = "relicario-core" name = "relicario-core"
version = "0.2.0" version = "0.5.0"
edition = "2021" edition = "2021"
description = "Core library for relicario password manager" description = "Core library for relicario password manager"

View File

@@ -1,6 +1,6 @@
[package] [package]
name = "relicario-wasm" name = "relicario-wasm"
version = "0.2.0" version = "0.5.0"
edition = "2021" edition = "2021"
description = "WASM bindings for relicario password manager" description = "WASM bindings for relicario password manager"

View File

@@ -0,0 +1,265 @@
# Relicario — Whole-Codebase Architecture Review
**Date:** 2026-05-04
**Reviewers:** DEV-A (Rust core), DEV-B (Rust consumers — CLI, server, WASM), DEV-C (TypeScript — extension, relay)
**Synthesis:** PM
**Goal lens:** "Make this app's architecture logical and readable for a smart developer who doesn't know Rust but wants to learn by tinkering."
## Executive summary
The architecture is fundamentally sound: bytes-in/bytes-out core, no I/O leakage from `relicario-core`, a server that structurally cannot decrypt (no AEAD or KDF crate in its dep graph), a service-worker boundary in the extension that holds (content scripts make zero WASM calls), and CLI/extension parity at 22/23 capabilities. What hurts the goal lens is uneven detail: a few outsized files (`cli/main.rs` 2641 LOC, `extension/src/setup/setup.ts` 1220 LOC, `extension/src/vault/vault.ts` 1027 LOC) absorb concerns that belong in smaller modules, and a couple of cross-cutting boilerplate clusters (16× duplicated git-shell error UX in the CLI; duplicated SW router helpers; hand-maintained `wasm.d.ts`) make a learner re-derive the same pattern repeatedly. The single most important thing to address is a defense-in-depth crypto issue spanning Rust and JS: `SessionHandle` has no `impl Drop`, so the wasm-bindgen-generated `.free()` is a no-op for cleanup — the master key stays in WASM linear memory until JS explicitly calls `lock()`. The strongest aspects worth preserving are the documentation density of the security-critical core files (`crypto.rs`, `imgsecret.rs`, `backup.rs`, `tar_safe.rs` all open with multi-paragraph rationale), the discriminated-union message contract in the extension (`shared/messages.ts` + the popup-only / content-callable capability sets), and the server's structural enforcement of the ciphertext-only invariant via its import surface. These three patterns are the model for what every other surface should look like.
## Top-priority recommendations (P1)
### P1.1 — `SessionHandle` has no `impl Drop`; `.free()` is a cleanup no-op
**Area:** cross-cutting (wasm + extension)
**File(s):** `crates/relicario-wasm/src/lib.rs:15-23`, `crates/relicario-wasm/src/session.rs:1-58`, `extension/src/service-worker/session.ts:26`
**Found by:** DEV-B (Rust side, headline finding); DEV-C (symmetric JS-side concern, originally [P2])
**Observation:** `SessionHandle` is `pub struct SessionHandle(u32)` with no `Drop` impl. wasm-bindgen's auto-generated JS `.free()` drops a `u32` — i.e. nothing. The `SESSIONS` HashMap entry stays alive with the master key and image_secret in WASM linear memory until JS calls the explicit `lock(handle)` (which calls `session::remove`). DEV-C separately observed `service-worker/session.ts:26` swallows `free()` errors with `try { current.free() }` — that swallow is hiding the fact that the call wasn't doing crypto cleanup anyway.
**Why it matters for the user's goal:** This is the only finding in the review where the gap between "what the code looks like it does" and "what it actually does" is dangerous. A tinkerer reading `session.ts` reasonably assumes `free()` cleans up the WASM-side key; it does not. Defense-in-depth here is one Rust block and one JS audit.
**Suggested direction:** Add `impl Drop for SessionHandle { fn drop(&mut self) { session::remove(self.0); } }` to the WASM crate so `.free()` becomes the safety net and `lock()` becomes the explicit "I am done" call. In parallel, remove the `try { ... }` swallow at `service-worker/session.ts:26` (let exceptions propagate or log + counter) and audit every `.free()` callsite under `extension/src/` to ensure `wasm.lock(handle)` happens first regardless. A `wasm-bindgen-test` covering construct → drop → confirm registry empty locks the contract.
**Effort:** S (Rust fix) + S (JS audit) = ~1-2 hours total
### P1.2 — `crates/relicario-cli/src/main.rs` is a 2641-line monolith
**Area:** cli
**File(s):** `crates/relicario-cli/src/main.rs:1-2641`
**Found by:** DEV-B
**Observation:** The clap surface (lines 1-455) is a tour of the product and reads beautifully. Past line 456 the file becomes flat: every `cmd_*`, every `build_*_item`, every `edit_*`, six prompt helpers, three parsing helpers, and 24+ git shell-outs all live as peers. `cmd_add` calls 7 different `build_*_item` functions (each ~50-60 lines) with no module boundaries. Searching "where does add work?" requires scrolling, not navigating.
**Why it matters for the user's goal:** This is the first file a tinkerer opens after `cargo run -p relicario-cli -- --help`. Today they have to scroll through 2200 lines of flat code to follow any one command end-to-end. Splitting this is the precondition for fixing P1.3 and centralizing several other CLI patterns (groups-cache discipline, prompt helpers).
**Suggested direction:** Keep `main.rs` as clap definitions + the dispatching `match` (~470 lines). Split into `commands/{add,get,list,edit,trash,backup,import,attach,settings,sync,status,device,recovery_qr}.rs`, plus `prompt.rs` (the six `prompt_*` helpers + `prompt_secret`) and `parse.rs` (`parse_month_year`, `base32_decode_lenient`, `guess_mime`). Same LOC, different reading experience.
**Effort:** M (mechanical split, no logic changes)
### P1.3 — Git invocation boilerplate duplicated 16× with one-line errors
**Area:** cli
**File(s):** `crates/relicario-cli/src/main.rs:601, 602, 610, 986, 988, 1477, 1480, 1767, 1897, 1900, 2432, 2438, 2533, 2540` (and others)
**Found by:** DEV-B
**Observation:** Every `git_command` invocation that bails uses the same shape: `.args([...]).status()? + if !status.success() { bail!("git foo failed") }`. Child stderr is inherited interactively, but in test runs and noninteractive tooling it's lost, and the bail message is just the verb. When this fires in the wild — pre-receive reject, missing remote, dirty tree, signing-key prompt — the user sees one line and nothing actionable.
**Why it matters for the user's goal:** This is the *entire* error UX for the git side of the CLI. Failures are common, the diagnostic is uniformly unhelpful, and a learner will hit "git commit failed" with no context the first time they touch a misconfigured remote.
**Suggested direction:** Add `helpers::git_run(repo, args, context)` that uses `.output()` (capturing stderr), prints captured stderr unmodified on failure, and embeds the human-readable `context` ("commit add: GitHub", "register device", "purge trashed item"). 16 copies become one-liners.
**Effort:** S (single helper + sweep)
### P1.4 — `extension/src/setup/setup.ts` bypasses the SW and orchestrates WASM directly
**Area:** extension
**File(s):** `extension/src/setup/setup.ts:28-37`, `:1118-1120` (and the whole 1220-LOC file)
**Found by:** DEV-C
**Observation:** Popup, vault tab, and content scripts all funnel WASM through the service-worker. `setup.ts` is the only surface that imports `relicario-wasm` directly and orchestrates `unlock` / `embed_image_secret` / `register_device` / `manifest_encrypt` itself — duplicating ~400 LOC of crypto orchestration the SW already knows how to do. Side-effect: the setup tab can't be locked by the same session-timer the rest of the extension uses, and `WizardState` (passphrase + JPEG bytes + WASM handle) persists in module scope if the user abandons mid-wizard.
**Why it matters for the user's goal:** This is the single biggest "code lies about the pattern" surface in the extension. A learner who opens `setup.ts` first will see WASM imported directly and conclude that's how the extension works — it isn't; everywhere else routes through `chrome.runtime.sendMessage`. The file is also a 1220-LOC procedural wizard that could be a step registry.
**Suggested direction:** Add `create_vault` and `attach_vault` messages to the SW; turn `setup.ts` into a UI that posts those messages with the gathered config + image bytes. Convert the 6-step flow into a `{ id, render, attach }[]` step registry. The 1220 LOC drops to ~500. Add a `clearWizardState()` bound to `beforeunload` and to "return to step 0" so abandoned wizards don't persist sensitive material.
**Effort:** L (architectural — touches setup, the SW message router, and `wasm.d.ts`/types)
### P1.5 — `extension/src/vault/vault.ts` is a 1027-LOC do-everything file
**Area:** extension
**File(s):** `extension/src/vault/vault.ts:1-1027`
**Found by:** DEV-C
**Observation:** Single file owns: shell init, hash routing, sidebar render, list render, drawer state, type-picker, form-wrapper, deep-link routing, teardown coupling. Adding a new pane view today is a 5-place edit (`teardownPaneComponents` lines 813-820 is the symptom). Two state-management oddities sit inside: vault tab intercepts `vault_locked` errors via the RPC layer while the popup uses the `session_expired` event (two channels for one outcome), and `state.drawerOpen = true` survives navigation to non-list views.
**Why it matters for the user's goal:** This is the second steepest cliff for a tinkerer (after `setup.ts`). The vault tab is the user's primary fullscreen experience; the file that drives it should read as orchestration, not implementation.
**Suggested direction:** Split into `vault-shell.ts`, `vault-sidebar.ts`, `vault-list.ts`, `vault-drawer.ts`, `vault-form-wrapper.ts`, leaving `vault.ts` to own only routing and state. While doing so, lift the `vault_locked` RPC intercept into `shared/state.ts` (or a wrapper around `sendMessage`) so popup and vault use one path; reset `state.drawerOpen` at the start of `renderPane` for non-list views.
**Effort:** M (mechanical split, plus one channel-unification touch)
### P1.6 — `extension/src/shared/state.ts` is fully `any`-typed
**Area:** extension (shared)
**File(s):** `extension/src/shared/state.ts:10-35`
**Found by:** DEV-C
**Observation:** `StateHost` is the bridge that lets popup components run inside the vault tab — and it's the bridge most likely to drift between the two render targets — but its entire contract is `any`-typed. TS gives no signal when popup-only state shape diverges from vault-tab expectations. Module-scope `host` singleton additionally has no double-registration guard; tests forget a reset and the leak silently breaks isolation.
**Why it matters for the user's goal:** Two-render-target reuse is exactly the kind of architecture decision that pays off in maintainability — but only if the contract is type-checked. As-is, the bridge is the weakest learning surface in the extension.
**Suggested direction:** Define a concrete `StateHost` interface: `state: PopupState`, `navigate: (view: View) => void`, `popOutToTab(): void`, `isInTab(): boolean`, `openVaultTab(hash?: string): void`. Make `getState`/`setState` generic over `keyof PopupState`. Throw on `registerHost()` re-register; export a `__resetHostForTests()` helper.
**Effort:** S-M (type definitions + sweep through callers)
### P1.7 — `crates/relicario-core/src/recovery_qr.rs` is undocumented
**Area:** core
**File(s):** `crates/relicario-core/src/recovery_qr.rs:1-130`
**Found by:** DEV-A
**Observation:** No module-level `//!` header. No doc comments on `RecoveryQrPayload`, `generate_recovery_qr`, `unwrap_recovery_qr`, or `recovery_qr_to_svg`. Magic constants (`RREC`, `VERSION = 0x01`, `PAYLOAD_LEN = 109`) sit at the top with no explanation; the 4+1+32+24+48 layout is hand-counted with no struct, diagram, or asserts. The domain-separation prefix `b"relicario-recovery-v1\0"` exists but isn't explained. `production_params()` redeclares `KdfParams::default()` values with no comment on why the recovery format pins them.
**Why it matters for the user's goal:** Every other security-relevant file in the core (`crypto.rs`, `imgsecret.rs`, `backup.rs`, `tar_safe.rs`) has explanatory framing. A learner hitting `recovery_qr.rs` sees a different style and assumes either it doesn't matter or they've stumbled out of the documented zone. It does matter — this is the vault-key escape hatch — and a misuse here (e.g., reusing `production_params` as `KdfParams::default()` and then changing the default) silently breaks all extant recovery QRs.
**Suggested direction:** Add a module-level `//!` summarizing the format, the KDF-input domain separation, and the parameter-pinning rationale. Add a short ASCII diagram of the 109-byte layout near the constants. Doc-comment the four public functions. Either replace `production_params()` with a `const` or add a comment explaining the deliberate divergence from `KdfParams::default()`.
**Effort:** S (documentation only)
### P1.8 — `tools/relay/queue.test.ts` fails on uncommitted state
**Area:** tooling
**File(s):** `tools/relay/queue.test.ts:54`
**Found by:** DEV-C (verified via `bun test` → 1 fail / 4 pass)
**Observation:** Uncommitted changes added `dev-c` to the `Role` union and `KNOWN_ROLES` set in `queue.ts`, but the test still asserts the old enum: `assert.ok(!isRole("dev-c"))`. One-line fix.
**Why it matters for the user's goal:** A learner running `bun test` from `tools/relay/` immediately sees a failure and assumes the codebase is broken. The relay is the literal coordination substrate of this review; a green test run is table stakes.
**Suggested direction:** Update the test assertion to `assert.ok(isRole("dev-c"))` and add a negative case (`assert.ok(!isRole("dev-d"))`). Confirm `start.sh` opens a fourth window for dev-c (DEV-C suspected `:80` still hardcodes "Dev-B" in user-facing output).
**Effort:** S (one-line edit + one-launcher-line check)
### P1.9 — Duplicated SW router helpers (storage helpers + `itemToManifestEntry`)
**Area:** extension (service-worker)
**File(s):** `extension/src/service-worker/router/popup-only.ts:687-703` and `:~169`; `extension/src/service-worker/router/content-callable.ts:187-205` and `:~169`
**Found by:** DEV-C
**Observation:** Three identical `chrome.storage.local` helpers (`loadDeviceSettings`, `loadBlacklist`, `saveBlacklist`) and the 17-line `itemToManifestEntry()` projection are duplicated across both router files. Both code paths can mutate the blacklist via different definitions; future drift will silently corrupt one path. Manifest schema refactors will need to be made twice.
**Why it matters for the user's goal:** A learner reading either router file sees private helpers and assumes that's where they live; finding the same name in the sibling router with a near-identical body is a routine "wait, why is this duplicated?" moment that should not exist in a tightly-typed message-router architecture.
**Suggested direction:** Extract the three storage helpers to `service-worker/storage.ts`; move `itemToManifestEntry` into `service-worker/vault.ts`. Import from both router files. Pair this with [P1.6] for `shared/state.ts` typing — both are about giving the extension's "shared utilities" a concrete shape.
**Effort:** S (extract + sweep)
### P1.10 — Pure parsers in CLI that the extension will eventually need
**Area:** cli → core
**File(s):** `crates/relicario-cli/src/main.rs:942-980` (`parse_month_year`, `base32_decode_lenient`, `guess_mime`)
**Found by:** DEV-B
**Observation:** Three pure parsers producing typed core values currently live only in the CLI. Per the project's CLI/extension parity philosophy (CLAUDE.md memory rule), anything the CLI does in pure logic the extension will eventually need too — QR-import, month-year smart input, attachment MIME detection. There is also a `base32_encode` in `core/item.rs` and a `decode_base32_totp` in `core/import_lastpass.rs` that are inverse pairs in different modules — DEV-A flagged the same shape from the core side ([P2] base32 has three implementations).
**Why it matters for the user's goal:** Parity is a stated design philosophy, and parser drift between CLI and extension is the most likely place for it to fail silently.
**Suggested direction:** Migrate to core: `MonthYear::parse` (already partial in `time.rs`), `Totp::parse_secret` (or `ItemCore::parse_totp_seed`), `mime::guess_for_extension`. Pair with extracting a `pub(crate) mod base32` in core with `encode_rfc4648` / `decode_rfc4648`, leaving Steam's bespoke alphabet where it is. The CLI keeps thin wrappers; the WASM crate exposes the new functions; the extension calls them via SW message handlers.
**Effort:** M (move + adjust CLI callers + add WASM exports)
## P2 recommendations
### Core (Rust)
- **`extract_with_crop_recovery` is narrower than the spec describes.** `crates/relicario-core/src/imgsecret.rs:849-899`. Spec promises 15% from any edge; impl pins `dx=0, dy=0` and varies only `orig_w`/`orig_h`. Left/top crops won't recover. Either extend the recovery loop or update the spec language to "right/bottom crop tolerance only." (DEV-A)
- **Stale "in-progress rewrite" headers** in `vault.rs:1-7`, `manifest.rs:1-2`, `attachment.rs:1-4`. Each comment describes work that already shipped. Replace with one-line module summaries. (DEV-A)
- **Two dead fields in `EmbedRegion`** (`imgsecret.rs:225-229`). `region_width`/`region_height` are computed, stored, and silenced with `#[allow(dead_code)]`. Either delete or comment the future use. (DEV-A)
- **Three base32 implementations.** `item.rs:255-275`, `import_lastpass.rs:202-220`, `item_types/totp.rs:13` (Steam, intentionally different). Extract a `pub(crate) mod base32`; leave Steam alone with a neighbour comment. (DEV-A; folds into P1.10.)
- **Backup format embeds the reference JPEG as base64-in-JSON** (`backup.rs:148-152, 274-280, 343-345`). Round-trip works; bloats by ~33% over the binary baseline post-zstd. Defer until backup-size pressure shows up. (DEV-A)
### CLI (Rust)
- **`build_*_item` functions mix prompting, parsing, and core construction.** `main.rs:664-921`. Compress with a `prompt_or_flag<T>` helper. (DEV-B)
- **`refresh_groups_cache` invocation discipline is manual at 7 sites.** `main.rs:641, 998, 1123, 1197, 1414, 1432, 1474`. Rule "every mutating handler must call this" is unenforced. Wrap in `Vault::after_manifest_change(&self, manifest: &Manifest)`. (DEV-B)
- **`ParamsFile` defined twice with mismatching shapes.** Write side `main.rs:2287` has `aead`, `salt_path`, `format_version`; read side `session.rs:114` takes only `kdf`. Single struct in core or shared session module. (DEV-B)
- **`cmd_purge` and `cmd_trash_empty` duplicate the manifest-add-and-commit dance** (`main.rs:1476-1480, 1896-1900`). 50-item purge does 150 git invocations; batch the staging. (DEV-B)
### Server (Rust)
- **`generate-hook` assumes `$PATH`.** `relicario-server/src/main.rs:170`. Most Gitea hook environments don't have `/usr/local/bin`; `command not found` is the failure mode. Embed `current_exe()` or emit an explicit `PATH=` line. (DEV-B)
- **Bootstrap branch is permissive.** `:38-44, 54-57`. Missing `.relicario/devices.json` at `newrev` is treated as bootstrap. An attacker pushing a brand-new branch that strips `.relicario/` could push unsigned commits. Either document the rule or enforce: `oldrev != 0``devices.json` must exist in `newrev`. (DEV-B)
- **stdin-parsing lives in the shell hook only.** `:130-189`. Wiring up the binary by hand isn't possible without re-implementing the per-line `<old> <new> <ref>` parse. Add `verify-commit --from-stdin` or doc-comment the constraint. (DEV-B)
- **Test coverage gaps** (`tests/verify_commit.rs`): unsigned-commit, malformed `devices.json`, bootstrap-empty, stripped-`.relicario/`. Each is one extra `#[test]`. (DEV-B)
### WASM (Rust)
- **Redundant double-lookup pattern.** `lib.rs:73, 84, 92, 103, 111, 122, 160, 172` all do `need_key(handle)?` then `session::with(handle.0, |k| ...).unwrap()` — two HashMap lookups per call. Single-`with` helper that returns `JsError` on miss. (DEV-B)
- **`Vec<u8>` getters clone on every read.** `EncryptedAttachment::aid` and `bytes` (`lib.rs:141-150`). Document "call once, cache locally" or consume by value. (DEV-B)
- **`wasm_*_recovery_qr` prefix is inconsistent** with everything else. `lib.rs:497, 510`. Rename to `generate_recovery_qr_svg` and `unwrap_recovery_qr` (and update `extension/src/wasm.d.ts`). Trivial breaking rename — do it before any new caller appears. (DEV-B)
- **`device.rs` and `session.rs` use different concurrency primitives** (`Lazy<Mutex<...>>` vs `thread_local! { RefCell<...> }`). Pick one. (DEV-B)
- **`extension/src/wasm.d.ts` is hand-written and explicitly requires manual sync** with `crates/relicario-wasm/src/lib.rs`. Every change to `#[wasm_bindgen]` must be mirrored manually; today they're aligned. Add a CI check comparing `wasm-pack`generated `.d.ts` against this file, or import the generated file directly. (DEV-C; partner finding to DEV-B's WASM section.)
### Extension — service-worker
- **Inactivity timer reset skips content-callable messages** (`service-worker/index.ts:76-78`). A user actively autofilling but not opening the popup will be force-locked despite continuous use. Reset on all messages except known read-only content calls. (DEV-C)
- **Session expiry clears `state.manifest` but leaves `state.gitHost`** (`service-worker/index.ts:51-58`). Cached git-host client survives expiry; rotation could mix with stale connection state. Null `state.gitHost` alongside. (DEV-C)
- **`try { current.free() }` swallows free errors** (`service-worker/session.ts:26`). See P1.1 — this becomes important once `impl Drop` lands. (DEV-C)
### Extension — popup + components
- **Duplicated teardown helpers** (`settings.ts:56-65` and `settings-vault.ts:15-22`). After the recent stub-restore commits (`8baef5b`, `ddfb95d`), teardown leaks are a known regression class — duplicated cleanup is exactly the pattern that re-introduces them. Extract a single `teardownSettingsCommon()`. (DEV-C; originally P1, demoted by PM because the leak vector is small but the duplication is real.)
- **Settings module-scope singletons** (`settings.ts:33-34`). `pendingVaultSettings` and `sessionHandle` survive section navigation. Reset on `renderSection` entry, or scope into a closure per render. (DEV-C)
- **Item-list popover wires listeners on every render** (`item-list.ts:152-353`) without a reuse path. Cache the DOM and reuse, or use AbortController. (DEV-C)
- **`Promise.all` without per-promise error handling** (`devices.ts:47-50`, `trash.ts:39-46`). Single rejected RPC fails the whole render. Use `Promise.allSettled`. (DEV-C)
- **Generator-panel cleanup not idempotent-guarded** (`generator-panel.ts:89-261`). Currently safe by accident. Add `if (!activePanel) return`. (DEV-C)
- **Popup teardown calls every type module unconditionally** (`popup.ts:178-181`). Track last-mounted type. (DEV-C)
### Extension — vault tab
- **Vault tab intercepts `vault_locked` via RPC; popup uses `session_expired` event.** `vault/vault.ts:47-74`. See P1.5 — collapse into one mechanism in `shared/state.ts`. (DEV-C)
- **Drawer doesn't auto-close on non-list view changes** (`vault.ts:495-536`). Reset `state.drawerOpen = false` in `renderPane`. (DEV-C)
- **Sidebar re-renders on every search keystroke without debounce** (`vault.ts:648-695`). 50-100ms debounce. (DEV-C)
### Extension — content scripts
- **`fillFields()` returns silently when no password field is found** (`content/fill.ts:50-64`). Dynamic forms can race the listener; user clicks autofill, nothing happens. Send a `fill_failed` ack. (DEV-C)
- **MutationObserver scan is not debounced** (`content/detector.ts:96-103`). SPA churn re-runs the full scan many times per second. Wrap in `requestIdleCallback` or 200ms timer. (DEV-C)
- **Outside-click listener leaks on alternate close paths** (`content/icon.ts:169-175`). AbortController scoped to picker open, or remove in every close path. (DEV-C)
### Extension — setup
- **`setup.ts` 1220-LOC procedural wizard.** Step registry pattern. See P1.4. (DEV-C)
- **`WizardState` is module-scope; sensitive material persists if user abandons mid-wizard** (`setup.ts:69-94`). Add `clearWizardState()` on `beforeunload` and on returning to step 0. Folds into P1.4. (DEV-C)
- **Manifest path constants duplicated** between `setup/probe.ts:11-23` and `service-worker/vault.ts`. Define `VAULT_PATHS` in `shared/types.ts` (or `shared/paths.ts`). (DEV-C)
### Extension — shared utilities
- **Base `Response` is `{ data?: unknown }`; every consumer does hand-written `as ListItemsResponse` casts** (`shared/messages.ts:85-87`). Generic `Response<TKind extends Request['type']>` mapped from a single `MessageMap` table. (DEV-C)
- **`group-autocomplete.ts:26` builds list HTML via `innerHTML` with only `&quot;` escaping.** Group names are user-entered. `<` and `>` aren't escaped — markup-injection risk. Use `document.createElement('option')`. (DEV-C)
- **`restore_backup` flattens `newRemote` inline** (`shared/messages.ts:56-66`). Inconsistent with sibling messages. Extract `RestoreBackupPayload`. (DEV-C)
### WASM boundary (JS side)
- **`__stubs__/relicario_wasm.stub.ts` only stubs 7 of ~25 exports.** Adding a vitest test that touches a new WASM call needs an ad-hoc per-test mock. Round out the stub or provide a `mockWasm({...})` test helper. (DEV-C)
### Relay tooling
- **`tools/relay/start.sh:80` may still reference "Dev-B"** in user-facing output despite the dev-c expansion. Confirm a fourth window opens for dev-c. (DEV-C)
- **`tools/relay/call.py` and `call.ts` are untracked but load-bearing** for the multi-agent fallback path (kickoff prompts reference `call.py` by path). Either track them with a one-line header explaining "MCP-fallback shim" or add to `.gitignore`. (DEV-C)
- **In-memory queue has no TTL, persistence, or cap** (`queue.ts:21-27`). Document the dev-only ephemeral contract or add a per-role cap. (DEV-C)
### Cross-cutting
- **`#[allow(dead_code)]` without explanation** appears in `cli/device.rs`, `cli/gitea.rs`, and `wasm/device.rs`. Each is either "API completeness" or "scar tissue." Annotate with `// TODO(<plan>):` or delete. (DEV-B)
- **Direct `chrome.storage.local` reads from popup components** (`settings-security.ts:112-113`, `setup.ts:1056-1062`). Every other module routes via `sendMessage`. Pick one paradigm and document the exception. (DEV-C)
- **`bun test` is not the project's intended runner** (`extension/package.json:13` is `vitest run`; `tools/relay/` uses `node:test` via `bun test`). README clarification. (DEV-C)
- **Error formatting is inconsistent** across all three Rust crates: CLI mixes sentence-case and lowercase fragments; server is `eprintln!("REJECT: ...")` *except* the malformed-devices.json path; WASM ranges from explicit messages to `RelicarioError::Display` passthrough. Short style note + audit pass. (DEV-B)
## P3 / nice-to-have
A long tail of style sweeps and small ergonomic wins. Pulling the most representative; full lists in the per-reviewer notes.
- Inconsistent error types and constant styles in core (`MonthYear::new -> Result<_, &'static str>`; `pub const MAGIC: [u8;4]` vs `const MAGIC: &[u8;4]`; empty `[dev-dependencies]`). (DEV-A)
- Mid-file `use` blocks in `item.rs:117-122` and `attachment.rs:43-46`. (DEV-A)
- `r#type` field on `Item` and `ManifestEntry` — rename to `item_type` with `#[serde(rename = "type")]`. (DEV-A)
- BIP39 minimum word count of 3 is misleading vs. the 128-bit-security framing — restrict to canonical sets or rename to "BIP39-wordlist passphrase generator." (DEV-A)
- `STEAM_ALPHABET` source comment contradicts its own test about the '5' character. (DEV-A)
- `let _ = entry;` newcomer-hostile pattern repeated 6× in CLI. (DEV-B)
- `cmd_recovery_qr_unwrap` doesn't check empty input before base64 decode; QR ASCII and "NOT been saved" mixed on stdout (pipe-unfriendly). (DEV-B)
- `Lock` CLI subcommand is a visible no-op; either `#[command(hide = true)]` or document the parity rationale. (DEV-B)
- Three test-only env vars duplicated under `#[cfg(debug_assertions)]/#[cfg(not(debug_assertions))]` — one macro flattens ~30 lines. (DEV-B)
- WASM exports use snake_case in JS (`manifest_encrypt`); JS idiom is camelCase. Decide once via `#[wasm_bindgen(js_name = ...)]`. (DEV-B/DEV-C)
- Glyph-rule partial adoption — six popup files use raw glyph literals (`⧉`, `↻`, `▸`, `▾`, `≡`, `⤓`) inline despite the `glyphs.ts` abstraction. Add the missing constants and migrate. (DEV-C)
- `TotpKind = 'totp' | 'steam' | { hotp: { counter: number } }` mixed string/object union — flat discriminated union reads cheaper. (DEV-C)
- `void tick()` in `totp-tools.ts:39-46` swallows promise rejections. (DEV-C)
- `setup.ts:1-7` header says "5-step flow"; code is 6 steps (0..5). (DEV-C)
- `helpers.rs:37 #[allow(dead_code)] pub fn relicario_dir()` has no callers but several `vault_dir.join(".relicario")` sites should use it. (DEV-B)
- `gitea.rs` constructs a fresh `reqwest::blocking::Client::new()` per method call — make it a struct field. (DEV-B)
## Cross-cutting themes
**1. The "where the work happens" boundary holds, but two surfaces lie about it.** `relicario-core` is genuinely platform-agnostic (no fs, no net, no git) and the server provably cannot decrypt (no AEAD/KDF crate present). The extension's content scripts make zero direct WASM calls. These are excellent structural invariants. The two surfaces that break the pattern are `extension/src/setup/setup.ts` (loads WASM and orchestrates crypto directly, bypassing the SW) and the `SessionHandle` `.free()` non-cleanup contract on the WASM/JS boundary. Both are P1; both are also single-surface fixes. The architecture is one P1.1 + one P1.4 away from being uniform.
**2. Duplication concentrates at boundaries, not inside modules.** The two router files duplicate storage helpers and `itemToManifestEntry` (P1.9). The CLI duplicates git-shell error UX 16× (P1.3). Three base32 implementations live in core (P2). Two `ParamsFile` definitions disagree (P2). `parse_month_year` / `base32_decode_lenient` / `guess_mime` live only in the CLI but the extension will need them (P1.10). The pattern: every time a concept crosses a module/crate boundary, the second crossing copies the first instead of importing it. The remedy is small extractions (one helper module per cluster), not refactors. None of these are individually expensive; together they account for a meaningful fraction of total findings.
**3. Three files account for most of the readability cost.** `cli/main.rs` (2641 LOC), `setup.ts` (1220 LOC), `vault.ts` (1027 LOC). Each carries multiple concerns that belong in sibling modules. Splitting all three is cumulative ~M-L effort and unlocks several smaller cleanups (centralizing groups-cache discipline depends on splitting `main.rs`; the SW message-routing fix depends on extracting `setup.ts`'s WASM orchestration; lifting the `vault_locked` channel depends on splitting `vault.ts`). For the user's stated learning-by-tinkering goal, these three splits are the highest-leverage architectural moves available.
**4. Documentation density is uneven in exactly one place.** Core's security-critical files (`crypto.rs`, `imgsecret.rs`, `backup.rs`, `tar_safe.rs`) open with multi-paragraph rationale walking through the *why*. `recovery_qr.rs` does not — and it's the user-visible last-resort recovery mechanism. Bringing one file up to the existing standard is a P1.7 effort of S. Beyond that one file, the core doc story is genuinely strong; preserve it.
## What's strong (preserve)
- **`crypto.rs`, `imgsecret.rs`, `backup.rs`, `tar_safe.rs`: documentation density.** Each opens with multi-paragraph rationale (XChaCha20 vs AES-GCM, QIM with QUANT_STEP=50, length-prefixed concatenation, tar-bomb defenses). This is the model the rest of the crate should be measured against.
- **`relicario-server` trust-model enforcement via the import surface.** The server cannot decrypt the vault even in principle: no AEAD or KDF crate in its dep graph; the entire `relicario-core` import surface is `DeviceEntry`, `RevokedEntry`, `fingerprint`, and (in tests) `generate_keypair` — all plaintext device metadata. This is structural, not by convention.
- **Discriminated-union message contract in the extension.** `shared/messages.ts` + the `POPUP_ONLY_TYPES` / `CONTENT_CALLABLE_TYPES` capability sets give every router handler typed dispatch with origin-aware gating. Content scripts make zero WASM calls and re-validate origin in `fill.ts:32-38`. The boundary discipline holds.
- **Test design across the codebase.** Synthetic JPEGs via `make_test_jpeg()` (no binary fixtures), raw-byte tar bombs that bypass the tar crate's sanitizer, RFC6238 vector for TOTP, an independent reference impl cross-check for Steam, ~30 LastPass importer cases, NFC/NFD round-trips, day-boundary tests for retention. The tests are themselves a documentation artifact.
- **Helpers.rs in the CLI.** Small, focused, tested, and the doc-comment at `:90-93` explaining the plaintext `groups.cache` trade-off is admirably explicit. The git-command hardening (`core.hooksPath=/dev/null`, `commit.gpgsign=false`, `core.editor=true`) is exactly the right kind of comment to leave for a learner.
## CLI/extension parity status
Per DEV-C's full table: **22 of 23 CLI subcommands have a clean extension equivalent**.
- **Clean parity (✓)**: `init`, `add` (all 7 item kinds), `get`, `list` (with all filters), `edit`, `history`, `rm` (soft delete), `restore`, `purge`, `trash list`/`empty`, `backup export`/`restore`, `import lastpass`, `attach`, `attachments`, `extract`, `generate`, `settings *`, `sync`, `lock`, `rate`, `device add`/`revoke`/list, `recovery-qr generate`/`unwrap`. The settings unification under v0.5.1's left-nav (commit `bd6a301`) is the right shape.
- **Partial (✗ish)**: `detach <item> <aid>`. Extension uses a roundtrip through `update_item` with the `attachments[]` mutated client-side. Functional but racy if two devices edit at once. **Suggested fix**: add a `delete_attachment` SW message that does the surgical remove server-side. (P3.)
- **True gap (✗)**: `relicario status`. CLI shows pending sync state, ahead/behind, dirty-tree summary; extension surfaces nothing comparable. **Suggested fix**: `get_vault_status` message returning `{ ahead, behind, lastSyncAt, pendingItems }` plus a small status indicator in the vault sidebar. (P2.)
- **Browser-only (by design)**: `get_autofill_candidates`, `get_credentials`, `check_credential`, `blacklist_site`, `capture_save_login`, `fill_credentials`, `ack_autofill_origin`, `get_blacklist`, `remove_blacklist`, `get_active_tab_url`, `update_settings` for `DeviceSettings`. No CLI counterpart needed.
- **CLI-only (by design)**: `completions <shell>`. n/a.
**No "CLI first, extension follow-up" violations found** under this lens. The parity philosophy is intact; the one gap and the one partial are surgical fixes, not architectural debt.
## Beginner-friendliness assessment
Three reviewers converge on a consistent story for a smart developer who's never written Rust but wants to learn by tinkering.
**Where the floor is high already:**
- `crates/relicario-core/` reads beautifully: bytes-in/bytes-out boundary holds, public API is enumerated in one `lib.rs`, module names map directly to vault concepts (`item`, `manifest`, `attachment`, `settings`, `generators`, `vault`, `backup`, `device`, `recovery_qr`), and the algorithmically dense `imgsecret.rs` is the most heavily commented. A reader can land in `crypto.rs`, follow `derive_master_key``encrypt``vault::encrypt_item`, and reach `tests/integration.rs::full_workflow_login_and_note` in one sitting.
- `relicario-server` is 189 lines, one trust-model question, every dependency is plaintext metadata. Readable end-to-end in under ten minutes.
- The extension's discriminated-union message contract (`shared/messages.ts` + `types.ts`) gives the entire vocabulary in 500 lines. The per-type item form modules (`popup/components/types/login.ts` and siblings) are small parallel surfaces — once one clicks, the others read as variations.
**Where the cliff is:**
- **`cli/main.rs`** at 2641 LOC is the first real wall. A reader following `cmd_add` finds 7 peer `build_*_item` functions plus 6 prompt helpers plus 3 parsers, all in a flat file. (P1.2.)
- **`extension/src/setup/setup.ts`** at 1220 LOC is the second wall, and it's worse because it lies about the architecture: a reader who opens this file first sees WASM imported directly and concludes that's the pattern — it isn't. (P1.4.)
- **`extension/src/vault/vault.ts`** at 1027 LOC is the third. The vault tab is the user's primary surface; the orchestrator file shouldn't also be the implementation file. (P1.5.)
- **`shared/state.ts`** is the weakest learning surface in the extension — `any`-typed bridge between popup and vault tab, no double-registration guard. (P1.6.)
- **`recovery_qr.rs`** in core is the one file where a reader will hit a wall in an otherwise-well-documented crate. (P1.7.)
**The single most valuable change** for the user's stated goal: split `cli/main.rs` into a `commands/` folder (P1.2). It's the first file a tinkerer opens, the change is mechanical, and it unlocks several smaller cleanups (centralized git error UX, unified groups-cache discipline). After that, in order: bring `recovery_qr.rs` to the existing core doc standard (P1.7), extract `setup.ts`'s WASM orchestration into SW messages (P1.4), and split `vault.ts` (P1.5). The four together turn "this is mostly readable" into "this is uniformly readable."
## Open architectural decisions (escalated by reviewers; user judgement)
Pulled from DEV-B's question list and DEV-C's flags. None are blockers for the synthesis; each is a one-paragraph user decision.
1. **Was `impl Drop for SessionHandle` deliberately omitted?** (e.g. to avoid double-free if JS holds two refs.) PM verdict at synthesis: not deliberate; it's the headline fix (P1.1). User: confirm.
2. **Should CLI `parse_month_year`, `base32_decode_lenient`, `guess_mime` migrate to core?** PM verdict: yes, for parity (P1.10). User: confirm timing.
3. **Is "missing `.relicario/devices.json` = bootstrap = accept" intended in perpetuity?** Or should it tighten once a repo has any non-empty devices.json in history? (DEV-B P2.) User: pick a rule.
4. **Is the `Lock` no-op CLI subcommand worth keeping visible in `--help` for parity?** Or hide behind `#[command(hide = true)]`? (DEV-B P3.) User: pick.
5. **Has Task 12 shipped?** `cmd_backup_export` still reads `devices.json` per a "Task 12 will remove" TODO at `main.rs:1535-1537`. (DEV-B P3.) User: confirm and clean up.
6. **Track `tools/relay/call.py` and `call.ts`, or `.gitignore` them?** They're load-bearing for the multi-agent fallback path. (DEV-C P2.) PM verdict: track them — they're documented in coordination prompts.
7. **WASM JS naming: snake_case (current) or camelCase?** Trivial breaking rename via `#[wasm_bindgen(js_name = ...)]`, but only if done before the surface grows. (DEV-B/DEV-C P3.) User: pick once.
8. **`.gitea_env_vars` is untracked.** Name suggests local credentials. PM verdict: should be `.gitignore`d if it isn't already. User: confirm.
## Appendix: pointers to per-reviewer notes
- [DEV-A notes — Rust core](./2026-05-04-dev-a-notes.md)
- [DEV-B notes — Rust consumers (CLI, server, WASM)](./2026-05-04-dev-b-notes.md)
- [DEV-C notes — TypeScript (extension + relay)](./2026-05-04-dev-c-notes.md)

View File

@@ -0,0 +1,191 @@
# DEV-A Architecture Review Notes — Rust Core
Scope: `crates/relicario-core/src/**` (17 source files, ~5.5 kLOC) and `crates/relicario-core/tests/**` (9 integration suites). HEAD reviewed; the only uncommitted change in core is a version bump (`0.2.0 → 0.5.0` in `Cargo.toml`), nothing semantic.
## Summary
The crate has a clear, well-shaped architecture: a thin `lib.rs` re-exporting one concept per module, a unified `RelicarioError` enum, and a strict bytes-in/bytes-out posture (no fs, no net, no git anywhere — the boundary is held). The strongest part is the documentation density of the security-critical files: `crypto.rs`, `imgsecret.rs`, `backup.rs`, and `tar_safe.rs` each open with multi-paragraph rationale that walks a reader through the *why* (XChaCha20 vs AES-GCM, QIM with QUANT_STEP=50, length-prefixed concatenation, tar-bomb defenses) — exactly the "legibility-as-security" philosophy the README aspires to. Tests are excellent: RFC6238 vector for TOTP, an independent reference impl cross-check for Steam, NFC/NFD round-trips, raw-byte tar bombs that bypass the tar crate's sanitiser, and ~30 LastPass importer cases. The weakest part is unevenness — `recovery_qr.rs` is essentially undocumented despite being the user-visible last-resort recovery mechanism, and three modules (`vault.rs`, `manifest.rs`, `attachment.rs`) still carry "during this rewrite" / "added later in Task 22" headers from work that has long since shipped, which will mislead a newcomer about what's load-bearing.
`cargo clippy -p relicario-core --all-targets --no-deps` runs clean (no warnings).
## Findings (prioritized)
### P1 — `recovery_qr.rs` doc gap is conspicuous against the rest of the crate
**File(s):** `crates/relicario-core/src/recovery_qr.rs:1-130` (whole file)
**Observation:** No module-level `//!` header. No doc comments on `RecoveryQrPayload`, `generate_recovery_qr`, `unwrap_recovery_qr`, or `recovery_qr_to_svg`. Magic constants (`RREC`, `VERSION = 0x01`, `PAYLOAD_LEN = 109`) sit at top with no explanation, and the 4+1+32+24+48 layout is hand-counted with no struct, no diagram, and no asserts. The domain-separation prefix `b"relicario-recovery-v1\0"` exists but isn't explained. `production_params()` redeclares the same values as `KdfParams::default()` with no comment on why the recovery format pins them.
**Why it matters:** Every other security-relevant file (`crypto.rs`, `imgsecret.rs`, `backup.rs`, `tar_safe.rs`) has the explanatory framing this codebase rewards readers for. A newcomer hitting `recovery_qr.rs` sees a different style and assumes either it doesn't matter or they've stumbled out of the documented zone. It does matter — this is a vault-key escape hatch — and a misuse here (e.g., reusing `production_params` as `KdfParams::default()` and then changing the default) silently breaks all extant recovery QRs.
**Suggested direction:** Add a module-level `//!` summarizing the format, the KDF-input domain separation, and the parameter-pinning rationale. Add a short ASCII diagram of the 109-byte layout near the constants. Doc-comment the four public functions. Either replace `production_params()` with a `const` or add a comment explaining the deliberate divergence from `KdfParams::default()`.
### P2 — Stale "in-progress rewrite" headers in three core files
**File(s):**
- `crates/relicario-core/src/vault.rs:1-7` ("v1 helpers ... intentionally NOT carried forward. The CLI rewrite in Plan 1B switches to the new helpers.")
- `crates/relicario-core/src/manifest.rs:1-2` ("Lives next to the old entry.rs Manifest during this rewrite; entry.rs is deleted in Task 25.")
- `crates/relicario-core/src/attachment.rs:1-4` ("Encryption helpers ... are added later in Task 22 once the crypto module is settled.")
**Observation:** Each comment describes work that has already shipped. Task 22 added the helpers (they're 30 lines below in the same file). `entry.rs` is gone. Plan 1B is merged. The text reads as if there's a sibling file or a future change to wait for.
**Why it matters:** A newcomer trying to understand the manifest will go looking for `entry.rs` to compare. A newcomer reading `attachment.rs` will read past the helpers thinking "those are coming later." These are the cheapest possible cleanup — comment edits — and they each remove a tripwire.
**Suggested direction:** Replace with a one-line description of what the module *is*, not what it was during the rewrite.
### P2 — `extract_with_crop_recovery` is narrower than the spec describes
**File(s):** `crates/relicario-core/src/imgsecret.rs:849-899`
**Observation:** The design spec (`docs/superpowers/specs/2026-04-11-relicario-design.md` §imgsecret extraction step 3) says crop recovery iterates `(dx, dy)` from -15% to +15% stepping by 8 px (~16,800 candidates for 4000×3000). The code only varies assumed original `orig_w`/`orig_h` while pinning `dx = 0, dy = 0`. The successful-crop test at `imgsecret.rs:1108-1137` only crops the *right* edge, where dx=0 happens to be the correct offset.
**Why it matters:** Crops from the *left* or *top* (e.g. an Instagram square crop centered on a portrait, or any social-media platform that re-frames around faces) won't recover. The spec promises "15% from any edge"; the implementation delivers ~15% from the right and bottom only. Either the spec is wrong (which is allowed — the spec is marked historical) or the implementation has a quiet hole in the recovery surface. If the user ever uploads their reference JPEG to a service that left-crops, recovery will fail and the failure mode looks like "your image is wrong" rather than "we don't try that crop direction."
**Suggested direction:** Either (a) extend the recovery loop with a small dx/dy search bounded by the 15% margin, or (b) update the spec language and the user-facing docs to say "right/bottom crop tolerance only." A third option is to add a test that left-crops a watermarked image and currently fails — that captures the gap and lets future work close it.
### P2 — Two dead fields in `EmbedRegion`
**File(s):** `crates/relicario-core/src/imgsecret.rs:225-229`
**Observation:** `region_width` and `region_height` are computed in `compute_region`, stored in the struct, and silenced with `#[allow(dead_code)]`. Nothing reads them — downstream code uses `blocks_x` / `blocks_y` and `BLOCK_SIZE`.
**Why it matters:** The `#[allow(dead_code)]` is an explicit "I know this is unused" — a newcomer reasonably assumes the fields are load-bearing and will hunt for the consumers, finding nothing. Either they're pre-positioned for a future feature (in which case a comment saying so would help) or they should go.
**Suggested direction:** Delete both fields and the allow attributes, or add a one-line comment explaining the future use. (The struct is private, so removal is risk-free.)
### P2 — Three base32 implementations live in one crate
**File(s):**
- `crates/relicario-core/src/item.rs:255-275` (`base32_encode`, RFC 4648 alphabet)
- `crates/relicario-core/src/import_lastpass.rs:202-220` (`decode_base32_totp`, same alphabet)
- `crates/relicario-core/src/item_types/totp.rs:13` (`STEAM_ALPHABET`, *different* alphabet — by design)
**Observation:** The first two are inverses of each other but live in different modules with no shared helper. The third is intentionally different (Steam Guard's de-ambiguated alphabet). They all hand-roll the bit-packing loop.
**Why it matters:** A reader who finds one of the three has to grep to discover whether there are others, and whether they agree. A future change to the RFC 4648 path (e.g., padding behavior) needs to be applied in two places.
**Suggested direction:** Extract a small `pub(crate) mod base32` with `encode_rfc4648`, `decode_rfc4648`, leaving Steam's bespoke alphabet where it is (with a `// not RFC 4648 — Steam Guard's de-ambiguated alphabet` neighbour comment).
### P2 — Backup format embeds the reference JPEG as base64-in-JSON
**File(s):** `crates/relicario-core/src/backup.rs:148-152, 274-280, 343-345`
**Observation:** The `Envelope.vault.reference_jpg: Option<String>` carries the JPEG as base64-encoded JSON string. After zstd (which can't compress JPEG), a 4 MB reference photo bloats by ~33% from base64 plus JSON overhead.
**Why it matters:** Backup files for users who bundle the reference image will be substantially larger than necessary. Round-trip works (covered by `tests/backup.rs:96-106`), so this is a footprint concern, not a correctness one. Worth flagging if backup size ever shows up in a complaint.
**Suggested direction:** Bump `FORMAT_VERSION` and put `reference_jpg` and `git_archive` in a binary tail outside the JSON envelope, base64 only the small bytes. Defer until there's actual user pressure on backup size.
### P3 — Inconsistent error types and constant styles
**Observations (all small, batched here):**
- `crates/relicario-core/src/time.rs:18``MonthYear::new` returns `Result<Self, &'static str>` instead of `RelicarioError`. Every other constructor in the crate uses the unified error type.
- `crates/relicario-core/src/backup.rs:30` declares `pub const MAGIC: [u8; 4] = *b"RBAK";`; `crates/relicario-core/src/recovery_qr.rs:7` declares `const MAGIC: &[u8; 4] = b"RREC";`. Two different idioms for the same concept in adjacent files.
- `crates/relicario-core/Cargo.toml:36` has an empty `[dev-dependencies]` table (delete the header).
- `crates/relicario-core/src/crypto.rs:248-261` `derive_master_key_raw` is `pub` but only consumed by `recovery_qr.rs` inside this crate (verified via grep). `pub(crate)` would prevent accidental external misuse.
**Why it matters:** Each is trivial in isolation, but for a Rust newcomer reading the crate front-to-back, every inconsistency is a moment of "wait, why is this one different?" — and the answer is almost always "no reason, just historical."
**Suggested direction:** Pick one form for each pattern, sweep.
### P3 — Mid-file `use` blocks in `item.rs` and `attachment.rs`
**File(s):** `crates/relicario-core/src/item.rs:117-122`, `crates/relicario-core/src/attachment.rs:43-46`
**Observation:** Both files have `use` statements partway down the file (in `item.rs`, after `Section`; in `attachment.rs`, after `AttachmentSummary`). Idiomatic Rust hoists all `use` to the top.
**Why it matters:** Newcomer expectation; trivial to fix.
### P3 — `derive_icon_hint` only handles `Login` with no comment about other types
**File(s):** `crates/relicario-core/src/manifest.rs:84, 92-99`
**Observation:** Only `ItemCore::Login` produces a hostname hint; `_ => None` for the other six. No comment explaining why card-brand / favicon-from-URL / etc aren't derived for other types.
**Suggested direction:** One-line `// only Login items have a URL today; other types don't have an obvious icon source.` (Or implement card-brand / identity-favicon if the popup UI wants them.)
### P3 — `attachment.rs` has WHAT-comments on a deref pattern
**File(s):** `crates/relicario-core/src/attachment.rs:60-63, 83-85`
**Observation:** Two "Call-site adaptation" sections explain `&**master_key` in prose. The pattern is idiomatic Rust deref-coercion; the comment explains *what* not *why*.
**Suggested direction:** Delete both comment blocks. The code is self-documenting; if anything, the cognitive load is in the comment, not the deref.
### P3 — TOTP dynamic-truncation extraction is reproduced four times
**File(s):** `crates/relicario-core/src/item_types/totp.rs:75-99` (3 algorithm arms each duplicate the DT slice math), `217-228` (test reference impl reproduces it again).
**Suggested direction:** Extract a `fn dt(hmac_out: &[u8]) -> u32` helper. The test would still need its own copy as the cross-check.
### P3 — `STEAM_ALPHABET` source comment contradicts its own test
**File(s):** `crates/relicario-core/src/item_types/totp.rs:13` and `:287-291`
**Observation:** Source comment says "excludes ambiguous glyphs (0/O, 1/I/L, S/5, A/Z)". Test docstring at line 287 says "Note: '5' IS in the alphabet — S is excluded, so 5 is unambiguous." The test is right; the source comment is wrong about '5'.
**Suggested direction:** Fix the source comment to match the test (and the actual alphabet).
### P3 — `device.rs::sign` and `verify` share an extraction pattern that begs for a helper
**File(s):** `crates/relicario-core/src/device.rs:64-72, 86-94`
**Observation:** Both functions do `key_data.ed25519().ok_or(...)?.try_into::<[u8; 32]>().map_err(...)?`. Five-line copy.
**Suggested direction:** A `fn ed25519_bytes_from_private(...) -> Result<[u8; 32]>` and a `fn ed25519_bytes_from_public(...)` would each fold the extraction. Minor; not worth a refactor on its own but a free win if the file is being touched.
### P3 — `imgsecret.rs::read_block`'s `.unwrap()` deserves a one-liner
**File(s):** `crates/relicario-core/src/imgsecret.rs:315-319`
**Observation:** `read_block_abs(...).unwrap()` is safe because `compute_region` guarantees the block lies inside the embed region, but the invariant isn't stated.
**Suggested direction:** `// safe: compute_region ensures (start_x, start_y) + 8 fits within the image`. Same idea as the existing `expect("ascii-only charset")` in `generators.rs:64`.
### P3 — `r#type` field on `Item` and `ManifestEntry`
**File(s):** `crates/relicario-core/src/item.rs:134`, `crates/relicario-core/src/manifest.rs:23`
**Observation:** Using `r#type` (raw identifier) because `type` is a reserved keyword. Functional but jarring; a Rust newcomer doesn't know what `r#` means and won't immediately realize it's a field name not a type prefix.
**Suggested direction:** Rename to `item_type` with `#[serde(rename = "type")]` to keep wire format. Minor ergonomic win.
### P3 — BIP39 minimum word count of 3 is misleading
**File(s):** `crates/relicario-core/src/generators.rs:79-86`
**Observation:** `word_count` accepted range is `3..=12`. BIP39 spec proper starts at 12 words. 3-word output has only ~33 bits of entropy and would never pass `validate_passphrase_strength` for security uses, but the API permits it. The comment "This gives full-entropy sourcing even for short passphrases" elides that effective entropy is `word_count * log2(2048) = 11 * word_count`, not 128 bits.
**Suggested direction:** Either restrict to BIP39's actual word counts (12, 15, 18, 21, 24) or document that this is a *passphrase generator inspired by BIP39* (using its wordlist) rather than a BIP39 mnemonic generator. The latter is honest about what the code actually does.
### P3 — `StrengthEstimate::guesses_log10` uses base-10 while the spec talks bits
**File(s):** `crates/relicario-core/src/generators.rs:111-113`
**Observation:** `guesses_log10: f64` is base-10 log of guess count; the design spec discusses entropy in bits. Mild domain-translation friction for callers.
**Suggested direction:** Add a one-line comment showing the bits conversion (`bits ≈ guesses_log10 * log2(10) ≈ guesses_log10 * 3.32`), or expose a `bits_estimate()` accessor.
## File-by-file walk
**`lib.rs` (99 lines).** Crate-level docs are tight and accurate; the crypto pipeline diagram in the header is the right thing to greet a newcomer with. Public re-exports surface every meaningful type from one location. Clear.
**`error.rs` (195 lines).** Single error enum with thiserror. Every variant carries helpful context (item id, byte counts, found/expected version) except `Decrypt` which is opaque on purpose (audit M4). Tests exercise the public message format. Reads well.
**`crypto.rs` (437 lines).** The cornerstone. Module-level doc explains why XChaCha over AES-GCM and the binary layout. `derive_master_key` does NFC normalization + length-prefixed concatenation, both with explicit "audit H1" provenance comments. `decrypt_v1` rejection is tested. `derive_master_key_raw` is the seam used by the recovery QR. Solid.
**`ids.rs` (161 lines).** `ItemId`/`FieldId` are 64-bit random hex; `AttachmentId` is content-addressed (SHA-256 truncated to 128 bits). `is_valid()` provides a path-traversal guard (tested for `../../etc`). Header comment cites the audit IDs (M8, I2/B4) that motivated the entropy bumps from v1 — that traceability is great.
**`time.rs` (63 lines).** `now_unix()` and `MonthYear`. Only blemish is `MonthYear::new -> Result<_, &'static str>`; everything else returns `RelicarioError`.
**`vault.rs` (90 lines).** Six typed encrypt/decrypt wrappers (item / manifest / settings) that JSON-roundtrip through the crypto layer. Mechanical and correct. Stale module header (P2).
**`item.rs` (497 lines).** Defines the Item envelope, Field/FieldKind/FieldValue, Section, FieldHistoryEntry. Kind/value invariant enforced at construction and `validate()` post-deserialization. `set_field_value` captures history for password/concealed/totp kinds with kind-change rejection. `prune_history` honors LastN/Days/Forever. Mid-file `use` block (P3). Inline `base32_encode` (P2 above). Otherwise solid; the test at `set_field_value_captures_history_for_password` is exactly the right shape.
**`manifest.rs` (159 lines).** Browse-without-decrypt index v2. `upsert`/`remove`/`get`/`search`. `derive_icon_hint` only handles Login (P3). `r#type` field (P3). Stale header (P2).
**`attachment.rs` (166 lines).** `AttachmentRef` (carried on Item) and `AttachmentSummary` (carried in Manifest) plus `encrypt_attachment`/`decrypt_attachment`. The cap check fires before any crypto work — good order. Stale header + WHAT-comments (P2 + P3).
**`settings.rs` (184 lines).** `VaultSettings` with `TrashRetention`, `HistoryRetention`, `GeneratorRequest`, `AttachmentCaps`, plus the autofill TOFU ack map. Defaults match the design spec. `should_purge` is tested at the day-boundary. Clear.
**`generators.rs` (269 lines).** CSPRNG passwords (rejection-sampled via `Uniform::from`) and BIP39 passphrases (with capitalization variants) plus a zxcvbn-backed strength gate. Solid except the BIP39 lower-bound and `guesses_log10` ergonomics (both P3).
**`imgsecret.rs` (1138 lines).** The novel component. Documentation is excellent — DCT, QIM, EMBED_POSITIONS, MAX_DIMENSION rejection, JPEG header peek (audit M3), even an inline ITU-R BT.601 derivation. Tests cover round-trip, recompression to Q85, 10% crop, oversized-header rejection, and synthetic JPEG generation. Three real concerns: dead `region_width`/`region_height` (P2), narrower-than-spec crop recovery (P2), unannotated `unwrap()` in `read_block` (P3). The 1100-line size is fine — the algorithm warrants it.
**`backup.rs` (348 lines).** `.relbak` container: magic + version + salt + nonce + zstd(JSON envelope). Pinned Argon2id params. Schema/format versioning is paranoid in the right places. Reference-JPEG embedding is base64-in-JSON (P2). Otherwise solid.
**`device.rs` (168 lines).** ed25519 keypair generation in OpenSSH format, sign/verify, and SHA-256 fingerprint. The ssh-key + ed25519-dalek choreography is awkward but unavoidable. Sign/verify share an extraction pattern (P3). Tests cover sign, verify, wrong-data, wrong-key, and fingerprint format/determinism — comprehensive.
**`recovery_qr.rs` (129 lines).** The doc-gap finding (P1). Mechanically correct: domain-separated KDF input, AEAD wrap of the 32-byte image_secret, 109-byte payload that fits a QR v40 at EcLevel::M, SVG render via `qrcode`. But the documentation density doesn't match the rest of the crate.
**`import_lastpass.rs` (220 lines).** Header validation is strict (column count + order). Per-row failures degrade gracefully into `ImportWarning` rather than aborting. SecureNote vs Login dispatch via the `http://sn` sentinel matches the spec (D10). Custom base32 decoder (P2). Otherwise clean.
**`tar_safe.rs` (138 lines).** Replaces `tar::Archive::unpack` with a validated extractor. Rejects `..`, absolute paths, Windows prefixes, symlinks, hardlinks, oversized claimed sizes, and cumulative-size bombs. Returns `(PathBuf, Vec<u8>)` to the caller. Surgical and well-scoped.
**`item_types/mod.rs` (127 lines).** `ItemType` and `ItemCore` enums plus a `pub use` of every per-type core. The `// INVARIANT: no *Core struct may have a field serialized as "type"` comment at line 38 is exactly the kind of cross-cutting note that earns its keep — preserving that convention is what `ItemCore`'s tag-based serde works against. Comprehensive round-trip test at `item_core_round_trips_for_all_seven_types`.
**`item_types/login.rs` (63 lines).** Username/password/url/totp, all Optional, password Zeroizing. `omitted_fields_dont_appear_in_json` is the right shape for a serde test.
**`item_types/secure_note.rs` (30 lines).** Just a Zeroizing body. Right-sized.
**`item_types/identity.rs` (45 lines).** Five Optional fields. `empty_identity_omits_all_fields` round-trips to `{}` — clean.
**`item_types/card.rs` (68 lines).** Number/holder/expiry/cvv/pin/kind. `CardKind` defaults to `Credit`. `MonthYear` reused from `time.rs`.
**`item_types/key.rs` (42 lines).** Key material as Zeroizing string + label/public_key/algorithm. Loose schema (algorithm is a free string), which is appropriate for "any kind of key material."
**`item_types/document.rs` (40 lines).** Filename + mime + AttachmentId pointer to the primary blob. The actual bytes live in the attachment store, not the item.
**`item_types/totp.rs` (293 lines).** TotpCore + the shared TotpConfig (also reused as a field on Login). RFC6238 SHA1 vector check, an independent reference impl for Steam, an alphabet exhaustiveness sweep. HOTP is rejected with a typed error rather than silently mis-counted — the right choice for a stateless library. DT extraction duplicated four times (P3). Source vs test comment disagreement on the '5' character (P3).
**Tests folder (9 files, ~1.1 kLOC).** `integration.rs` covers the full encrypt/decrypt pipeline plus two-factor independence. `format_v2.rs` pins the version byte, the v1-rejection error type, and the length-prefix domain separation. `field_history.rs` covers capture, prune, and survival across encrypt/decrypt. `attachments.rs` covers round-trip + AID determinism + cap. `backup.rs` is thorough — round-trip with and without reference image / git archive, bad magic, unsupported version, wrong passphrase, truncation, tag tamper, NFC/NFD passphrase round-trip. `generators.rs` does class-balance statistics across 10k chars (well-documented why aggregating, since per-call cap is 128). `import_lastpass.rs` is the single largest suite (~30 cases) and exercises every column-mapping edge. `recovery_qr.rs` is minimal but covers the essentials. `safe_unpack.rs` builds raw-byte tars by hand to bypass `tar::Builder`'s sanitizer — exactly the right way to test a security boundary. The `fast_params()` helper is repeated across most files; a `tests/common/mod.rs` could DRY it but it's not a real cost.
## Beginner-friendliness assessment
For a competent dev who has never written Rust, this crate is unusually approachable. The boundary discipline is consistent (no I/O anywhere), the public surface is enumerated in one place (`lib.rs`), the module names map directly to vault concepts a reader already understands (item, manifest, attachment, settings, generators, vault, backup, device, recovery_qr), and the most algorithmically dense file (`imgsecret.rs`) is the most heavily commented. A reader can land in `crypto.rs`, follow `derive_master_key``encrypt``vault::encrypt_item`, and reach `tests/integration.rs::full_workflow_login_and_note` to see the whole pipeline run, all in one sitting. The Rust idioms that would trip up a newcomer (deref-coercion, `r#type` raw identifiers, `Zeroizing` wrappers, `&**master_key`) are all present, but they cluster in patterns a reader will see often enough to absorb.
The single change that would help most: write `recovery_qr.rs` to the same documentation standard as `crypto.rs` and `backup.rs`. It's the only file where a learning reader will hit a wall. Closing that gap brings the floor up to the ceiling and makes the "read it like a security proof" pitch true everywhere, not just in 16 of 17 files.

View File

@@ -0,0 +1,240 @@
# DEV-B Architecture Review Notes — Rust Consumers (CLI, Server, WASM)
**Date:** 2026-05-04
**Scope:** `crates/relicario-cli/`, `crates/relicario-server/`, `crates/relicario-wasm/`
**Out of scope:** `relicario-core` internals (DEV-A), `extension/` and `tools/relay/` (DEV-C)
**Method:** read-only walk of every src + test file; `cargo check` and `cargo clippy` per crate; `cargo build --target wasm32-unknown-unknown` for the WASM crate.
## Summary
The consumer layer is in good shape conceptually but uneven in execution. **`relicario-server` is the highlight**: 189 lines, one obvious responsibility, every dependency on `relicario-core` is plaintext device metadata only — the "server only ever sees ciphertext" invariant is structurally enforced by the import surface, not just by convention. **`relicario-wasm` is small and clean but has one real Rust-side defect**: `SessionHandle` lacks an `impl Drop`, so when wasm-bindgen's auto-generated `.free()` runs, the master key stays in WASM linear memory until `lock()` is also called explicitly — defense-in-depth that is currently missing. **`relicario-cli` does its job correctly but is hard to read**: `src/main.rs` is a 2641-line file with no submodule boundaries between the clap surface, item builders, edit handlers, prompt helpers, and parsers — the single biggest readability blocker in the consumer layer. Across all three crates, naming and module structure are good; what hurts is duplicated boilerplate and the absence of a few obvious helpers.
---
## Findings
### relicario-cli
#### P1 — `main.rs` is a 2641-line monolith with no submodule boundaries
**File(s):** `crates/relicario-cli/src/main.rs:1-2641`
**Observation:** every subcommand handler, every per-type item builder, every per-type edit handler, prompt helpers, parsing helpers, the `ParamsFile` shape, the clap surface, and 24+ git shell-outs all live in one file. The clap surface (lines 1-455) reads as a tour of the product and is excellent; lines 456-2641 are a flat sequence of `cmd_*`, `build_*_item`, `edit_*`, prompt helpers, and parse helpers, all peers. A newcomer searching "where does add work?" finds `cmd_add` calling 7 different `build_*_item` functions (each ~50-60 lines) with no module boundaries.
**Why it matters:** this is the first file a newcomer opens. Today they have to scroll, not navigate.
**Suggested direction:** keep `main.rs` as clap definitions + `match` dispatcher only (~470 lines). Split into `commands/{add,get,list,edit,trash,backup,import,attach,settings,sync,status,device,recovery_qr}.rs`, plus `prompt.rs` (the six `prompt_*` helpers + `prompt_secret`) and `parse.rs` (`parse_month_year`, `base32_decode_lenient`, `guess_mime`). Same LOC, completely different reading experience.
#### P1 — Git invocation boilerplate duplicated ~16× with one-line errors
**File(s):** `crates/relicario-cli/src/main.rs:601, 602, 610, 986, 988, 1477, 1480, 1767, 1897, 1900, 2432, 2438, 2533, 2540` (and others)
**Observation:** every `git_command` invocation that bails uses the same shape: `git_command(repo).args([...]).status()? + if !status.success() { bail!("git foo failed") }`. Child stderr is inherited to the parent tty (which helps interactively) but in test runs and noninteractive tooling it is lost, and the bail message is just the verb (`"git commit failed"`). When this fires in the wild — pre-receive reject, missing remote, dirty tree, signing-key prompt — the user sees one line of "$verb failed" and nothing else.
**Why it matters:** this is the entire error UX for the git side of the CLI. Failure modes are common; the diagnostic is actively unhelpful.
**Suggested direction:** add `helpers::git_run(repo, args, context)` that uses `.output()` (capturing stderr), prints captured stderr unmodified on failure, and includes the human-readable `context` ("commit add: GitHub", "register device", "purge trashed item"). Replaces 16 copies with one-liners.
#### P2 — `build_*_item` functions mix prompting, parsing, and core construction
**File(s):** `crates/relicario-cli/src/main.rs:664-921`
Each `build_*` does its own prompt-or-flag fallback (`title.map(Ok).unwrap_or_else(|| prompt("Title"))?`), parses domain values (URL, MonthYear, base32 TOTP), then constructs an `ItemCore`. Adding a new item type is currently 50-80 lines of mechanical code. A `prompt_or_flag<T>` helper plus per-type builders that take already-validated values would compress this materially.
#### P2 — Pure parsers belong in core, not the CLI
**File(s):** `crates/relicario-cli/src/main.rs:942-980`
`base32_decode_lenient` and `parse_month_year` are pure parsing producing typed core values. Per the user's CLI/extension parity philosophy, these need to be reachable from WASM too — the extension will want them when it gets QR-import / month-year smart input. `MonthYear::parse` and an `ItemCore::parse_totp_seed` (or `Totp::parse_secret`) on the core side would avoid future duplication.
#### P2 — `refresh_groups_cache` invocation discipline is manual at 7 sites
**File(s):** `crates/relicario-cli/src/main.rs:641, 998, 1123, 1197, 1414, 1432, 1474` (and `helpers.rs:90-93` for the doc comment)
The plaintext `groups.cache` is updated by-hand after every manifest mutation. The "failures are silently swallowed" rationale is documented at `main.rs:462`, but the rule "every mutating handler must call this" is not enforced — easy to forget on a new command. Either invoke from `Vault::save_manifest` (couples session to cache layout — maybe wrong) or wrap in `Vault::after_manifest_change(&self, manifest: &Manifest)`.
#### P2 — `ParamsFile` is defined twice with mismatching shapes
**File(s):** `crates/relicario-cli/src/main.rs:2287` (write) vs `crates/relicario-cli/src/session.rs:114` (read)
The write side has `aead`, `salt_path`, `format_version`; the read side takes only `kdf`. Two definitions of the on-disk `params.json` shape, in different files, with overlapping but non-equal fields. A single `Params` struct in `relicario-core` (or in `session.rs`) used by both readers and writers would eliminate the drift risk.
#### P2 — `cmd_purge` and `cmd_trash_empty` duplicate the manifest-add-and-commit dance
**File(s):** `crates/relicario-cli/src/main.rs:1476-1480, 1896-1900`
Same three lines, same error strings, same git rm + git add + git commit per item. `cmd_trash_empty` invokes `purge_item` per item, each of which is its own three-git-invocation loop. Batching the staging would reduce a 50-item purge from 150 git invocations to 3.
#### P3 — Selection of the `let _ = entry;` pattern, repeated 6×
**File(s):** `crates/relicario-cli/src/main.rs:1170, 1407, 1426, 1469, 1913, 2030`
Drop-the-borrow-before-reborrow-mutably is a Rust newcomer's worst surprise. A NLL-friendly refactor (clone `id` and `title` eagerly, let the borrow end naturally) would make these lines disappear.
#### P3 — Other nits
- `cmd_recovery_qr_unwrap` does not check for empty input before base64 decode (`main.rs:2625-2630`)
- `cmd_recovery_qr_generate` mixes the QR ASCII and a "NOT been saved to disk" message both on stdout — pipe-unfriendly (`main.rs:2612-2614`)
- `Lock` subcommand is a no-op but visible in `--help`; either `#[command(hide = true)]` or accept the parity-with-extension argument and document why (`main.rs:445`, doc-comment at `:166`)
- `tests/attachments.rs:69-76` has a dead variable (`blob_path`) kept "to avoid an unused warning" — delete
- Three test-only env vars (`RELICARIO_TEST_PASSPHRASE`, `RELICARIO_TEST_ITEM_SECRET`, `RELICARIO_TEST_BACKUP_PASSPHRASE`) each duplicated under `#[cfg(debug_assertions)]/#[cfg(not(debug_assertions))]` — one macro would flatten ~30 lines
- `cmd_backup_export` still reads `devices.json` (with `[]` fallback) per a "Task 12 will remove" TODO at `:1535-1537`. If Task 12 has shipped, this code can simplify
- `format!("{:?}", e.r#type)` for the TYPE column at `main.rs:1158` — Debug-format for user-facing output. Add `Display` to `ItemType` in core
- `helpers.rs:37 #[allow(dead_code)] pub fn relicario_dir()` — helper has no callers but several `vault_dir.join(".relicario")` sites in main.rs should be using it
- `device.rs:94, 103, 120` and `gitea.rs:24, 26, 47, 77, 94, 101` have `#[allow(dead_code)]` markers without explanation. Either wire up or add `// TODO(<plan>):` so a newcomer knows whether they're scaffolding or scar tissue
- `gitea.rs` constructs a fresh `reqwest::blocking::Client::new()` per method call (3 sites) — make it a struct field
- `tests/edit_and_history.rs` writes hardcoded prompt sequences (`["", "", "", "", "", "y"]`) blindly; if main.rs reorders prompts, tests hang silently. A scripted-test layer (`expect_prompt("Title"); respond("");`) would survive refactors
---
### relicario-server
#### Trust-model assessment (the headline question)
**The server respects the "ciphertext only" invariant. Confirmed.** The crate's entire `relicario-core` import surface is `DeviceEntry`, `RevokedEntry`, `fingerprint` (and `generate_keypair` in tests) — every one of those is plaintext-only device metadata. There is no import of `vault`, `crypto`, `imgsecret`, `item`, `manifest`, or `settings`. A grep over `crates/relicario-server/` for `decrypt|wrapped|encrypted|vault::` returns nothing. The Cargo.toml dep surface (`anyhow`, `clap`, `serde_json`, `tempfile`, `regex`) confirms it: there is no AEAD or KDF crate present. The server cannot decrypt the vault even in principle — it never reads the passphrase, the reference image, the salt, or the params.
The two on-disk files the server reads from the commit tree are `.relicario/devices.json` and `.relicario/revoked.json` (`main.rs:38, 48`), both plaintext metadata. All other operations are `git` subprocesses (`git show`, `git verify-commit --raw`, `git show -s --format=%ct`) plus local fingerprint computation. `generate-hook` emits a pure shell script that re-invokes `relicario-server verify-commit` per commit; it embeds no secret material. **No P1 findings.**
#### P2 — `generate-hook` assumes `$PATH`
**File(s):** `crates/relicario-server/src/main.rs:170`
The emitted script calls `relicario-server verify-commit "$commit"` with no path. Most Gitea deployments do not put `/usr/local/bin` on the hook process's `$PATH`, so this will fail with "command not found" or silently no-op. Either embed `std::env::current_exe()` at hook-generation time, or document an explicit `PATH=` line in the emitted script. There is no test that the generated hook actually executes.
#### P2 — Bootstrap branch is permissive
**File(s):** `crates/relicario-server/src/main.rs:38-44, 54-57`
A missing `.relicario/devices.json` at `newrev` is treated as bootstrap and accepted. Combined with "devices empty AND revoked empty → OK", an attacker who pushes a brand-new branch with no `.relicario/` directory could push arbitrary unsigned commits. There's no test for "second push to an established repo where devices.json was stripped." Worth either documenting the rule (first push wins; once devices.json exists in history, it can never be removed) or enforcing it: `oldrev != 0` should imply `devices.json` exists in `newrev`.
#### P2 — stdin-parsing lives in the shell hook only; binary alone is not hook-shaped
**File(s):** `crates/relicario-server/src/main.rs:130-189` (`generate_hook`)
The Rust binary's `verify-commit` takes a single SHA argument; the per-line `<old> <new> <ref>` parsing is delegated to bash in `generate_hook`. Defensible split, but means anyone wiring up a hook by hand cannot use the binary alone. A `verify-commit --from-stdin` mode (or at least a doc comment on `VerifyCommit` calling this out) would help.
#### P2 — Test coverage gaps vs. trust-model
**File(s):** `crates/relicario-server/tests/verify_commit.rs`
Tests cover: accepted, unregistered → reject, revoked-after → reject, revoked-before → accept. Missing: unsigned commit (no signature at all), malformed `devices.json` (parse error path on `:46`), bootstrap-empty-devices acceptance (`:54`), and one of the two stripped-`.relicario/` cases. Each is one extra `#[test]`.
#### P3 — Server nits
- Regex compiled per call at `main.rs:85` — use `LazyLock` or `once_cell::sync::Lazy`; the `expect("static regex")` comment hints the author knew
- The malformed-devices.json path at `:46` returns an `anyhow` chain on stderr without the consistent `REJECT: ...` prefix the rest of the file uses — ops parsing logs for `REJECT:` will miss it
- No `--version` flag exposed in clap (small ops courtesy)
- `generate-hook` doesn't tell users to `chmod +x` the result (one-line comment header in the emitted script would help)
---
### relicario-wasm
#### P1 — `SessionHandle` has no `impl Drop`; master key leaks on JS GC / `.free()`
**File(s):** `crates/relicario-wasm/src/lib.rs:15-23` and `crates/relicario-wasm/src/session.rs:1-58`
**Observation:** `SessionHandle` is `pub struct SessionHandle(u32)` with no `Drop` impl. wasm-bindgen auto-generates a JS-side `.free()` that, on the Rust side, drops the `SessionHandle` wrapper — i.e. drops a `u32`, a no-op. The `SESSIONS` HashMap entry stays alive **with the master key + image_secret still in WASM linear memory** until JS calls the explicit `lock(handle)` function (which calls `session::remove`). I confirmed via `grep -n "impl Drop" crates/relicario-wasm/src/*.rs` — empty.
**Why it matters:** every `.free()` callsite that does not also call `lock()` first is a key-residency window of unbounded duration. wasm-bindgen does **not** auto-call `free()` on JS GC, but JS code that does call `.free()` reasonably expects the Rust side to clean up. The current contract requires JS to call `lock()` *and then* `free()`, which is asymmetric and easy to get wrong on the JS side (see boundary notes for DEV-C).
**Suggested direction:** add
```rust
impl Drop for SessionHandle {
fn drop(&mut self) { session::remove(self.0); }
}
```
to `lib.rs`. `lock()` becomes the explicit "I am done now" call; `.free()` (auto or manual on the JS side) is the safety net. Defense in depth — the cost is one impl block. Worth a `wasm-bindgen-test` covering construct → drop → confirm registry empty.
#### P2 — Redundant `need_key` + `with(...).unwrap()` double-lookup
**File(s):** `crates/relicario-wasm/src/lib.rs:73, 84, 92, 103, 111, 122, 160, 172`
Every per-call op does `need_key(handle)?` and then `session::with(handle.0, |k| ...).unwrap()`. Two HashMap lookups per call, with the second `.unwrap()` justified only because the first proved the key existed. Single-threaded WASM makes this safe today, but if anyone ever introduces a reentrant path (`Serializer` callback that calls back into WASM), the assumption breaks. Refactor to a single `session::with(...).ok_or_else(|| JsError::new("invalid or locked session handle"))?` helper.
#### P2 — `Vec<u8>` getters clone on every read
**File(s):** `crates/relicario-wasm/src/lib.rs:141-150` (`EncryptedAttachment::aid` and `bytes`)
Each call clones the whole field. JS can call `enc.bytes` repeatedly without realising. For attachment payloads (potentially MB-sized), that's a real cost. Either consume by value or document "call once, cache locally."
#### P2 — Naming: `wasm_*_recovery_qr` prefix is inconsistent with everything else
**File(s):** `crates/relicario-wasm/src/lib.rs:497, 510`
`wasm_generate_recovery_qr` and `wasm_unwrap_recovery_qr` are the only exports with the `wasm_` prefix. Rename to `generate_recovery_qr_svg` and `unwrap_recovery_qr` (and update `extension/src/wasm.d.ts` accordingly). Trivial breaking rename, do it before any new caller appears.
#### P2 — `device.rs` and `session.rs` use different concurrency primitives
**File(s):** `crates/relicario-wasm/src/device.rs` (`Lazy<Mutex<...>>`) vs `crates/relicario-wasm/src/session.rs:14-17` (`thread_local! { RefCell<HashMap<...>> }`)
Both work in single-threaded WASM. The inconsistency hurts readability — pick one pattern. `thread_local! + RefCell` is fine and avoids `Mutex` overhead; `Mutex` over `Lazy` is closer to typical Rust idioms. Either is defensible; consistency is the win.
#### P3 — WASM nits
- All `#[wasm_bindgen]` exports use snake_case (`manifest_encrypt`, `parse_lastpass_csv_json`); JS idiom is camelCase. The `wasm.d.ts` mirrors snake_case verbatim, so it's consistent — but if DEV-C ever wants idiomatic JS naming, `#[wasm_bindgen(js_name = "manifestEncrypt")]` is the path. Decide once, cite the decision in the module doc
- `lib.rs:50` comment "Subsequent wasm_bindgen fns added in Tasks 19-21" is stale historical scaffolding; remove
- `device.rs:18 #[allow(dead_code)] deploy_private` — wire it or remove it
- `session.rs:24 if *n == 0 { *n = 1; }` runs on every insert; logically only matters after wraparound — move into the `wrapping_add` returned-zero branch
- `session_tests` mod inside `lib.rs:522-591` covers session + lastpass; rename or split
- `SessionHandle` doc-comment says "opaque to JS" but `value()` getter (`:21-22`) makes the u32 visible — align the comment with the API
- `pack_backup_json` does six `b64.decode().map_err(...)` blocks (`lib.rs:387-410`) — a small `b64_decode(s) -> Result<Vec<u8>, JsError>` helper would compress ~20 lines
- `get_field_history` walks sections and constructs `serde_json::json!` manually rather than serializing a typed struct (`lib.rs:262-295`); the `_ => String::new()` fallback at `:277` silently swallows future `FieldValue` variants. Use exhaustive match
---
### Cross-cutting (all three crates)
1. **Pure parsers / formatters belong in core.** `parse_month_year`, `base32_decode_lenient`, `guess_mime` (CLI), and `get_field_history`'s walk (WASM) are all examples of logic that today lives in a consumer crate but logically belongs in `relicario-core` so all consumers share it. The CLI/extension parity philosophy makes this concrete: anything the CLI does in pure logic, the extension will eventually need too.
2. **Error formatting is inconsistent.** CLI uses `anyhow::bail!` with a mix of sentence-case ("Settings updated.") and lowercase fragments ("git commit failed"). Server is uniformly `eprintln!("REJECT: ...")` *except* for the malformed-devices.json path that surfaces an anyhow chain. WASM uses `JsError::new(&e.to_string())` mostly, but the messages range from "salt must be exactly 32 bytes" to whatever `RelicarioError::Display` produces. A short style note ("user-facing errors lead with sentence-case context, internal errors use lowercase") plus an audit pass would unify these.
3. **`#[allow(dead_code)]` without explanation appears in cli/device.rs, cli/gitea.rs, and wasm/device.rs.** Each one is either "API completeness for a feature that hasn't shipped" or "scar tissue from a refactor." A newcomer cannot tell which. Either delete or annotate with `// TODO(<plan>):`.
4. **Layering is correct.** None of the three consumer crates reaches past `relicario-core`'s public API. The CLI doesn't import from server or wasm; server doesn't import from CLI or wasm; wasm doesn't import from CLI or server. The only shared concept (device entries, fingerprints) is correctly a core export. ¡Chido! [cool!]
5. **Workspace `Cargo.toml` working-tree changes are cosmetic** (version bumps `0.2.0 → 0.5.0` on cli/core/wasm). No structural concern. Worth committing or reverting before the next merge to keep `git status` quiet.
---
## File-by-file walk
### relicario-cli
- **`Cargo.toml`** — 18 runtime + 4 dev deps, all reasonable. `arboard` (clipboard), `rqrr` (QR decode), `qrcode` (QR encode), `image`, `rpassword`, `dirs`, `reqwest` blocking + JSON for Gitea, `data-encoding`, `tar`. Platform concerns ferried correctly away from core.
- **`src/main.rs`** — entrypoint, dispatcher, **and** every command handler, item builder, edit handler, prompt helper, parse helper. 2641 lines, 71 functions. Clap surface (lines 1-455) is itself a tour of the product and is excellent. Past line 456 the file becomes flat; see P1 #1.
- **`src/helpers.rs`** — the cleanest file. ~239 lines: `vault_dir`, `git_command` (with `core.hooksPath=/dev/null`, `commit.gpgsign=false`, `core.editor=true` hardening — newcomers should read the comment at `:42-45`), `iso8601`, `humanize_age`, `groups_cache_path`, `sanitize_for_commit`, `decode_totp_qr`. Has its own `#[cfg(test)] mod tests` covering `humanize_age`, `sanitize_for_commit`, `iso8601`. `find_vault_dir_from` walks parents. Plaintext `groups.cache` is a deliberate trade-off and the doc-comment at `:90-93` is admirably explicit.
- **`src/session.rs`** — short and clear (~151 lines). `UnlockedVault { root, master_key: Zeroizing<[u8; 32]> }` plus `load_*`/`save_*` for Item, Manifest, VaultSettings. `unlock_interactive()` does passphrase prompt → image extract → KDF. `key()` accessor returns `&Zeroizing<...>` used at 4 call sites; consider passing through `encrypt_attachment`/`decrypt_attachment` methods so the key never leaves this module. `read_params` defines an inner `ParamsFile` struct that mismatches the writer in `main.rs:2287` — see P2.
- **`src/device.rs`** — ~169 lines. ed25519 keypair storage under `~/.config/relicario/devices/<name>/`. `configure_git_signing` runs four `git config` calls. Three `#[allow(dead_code)]` items (`load_signing_key`, `load_deploy_key`, `delete_device_keys`) — API completeness without callers.
- **`src/gitea.rs`** — ~117 lines. Plain blocking reqwest client. `create_deploy_key` parses the JSON response into `DeployKey { id, title, key }` (latter two `#[allow(dead_code)]`). `delete_deploy_key` treats 404 as success — sensible. Each method allocates a fresh `reqwest::blocking::Client::new()`.
- **`tests/basic_flows.rs`** — 137 lines. Tests at the right level: spawn binary via `assert_cmd`, assert on stdout/stderr/exit. `init_creates_expected_layout`, `add_login_then_list_shows_it`, `get_masks_by_default_shows_with_flag`, `rm_restore_purge_cycle`, `generate_random_and_bip39`. Solid CLI-surface coverage.
- **`tests/edit_and_history.rs`** — 191 lines. Most subtle test, interactive `edit` flow. `run_edit_with_pw_change` and `run_edit_totp` write hardcoded prompt sequences (`["", "", "", "", "", "y"]`) to stdin — fragile to prompt reordering. See P3.
- **`tests/attachments.rs`** — 106 lines. Round-trip attach → extract → detach. Has a dead variable kept "to avoid an unused warning" (P3). `attach_rejects_over_cap` exercises only the per-attachment cap, not per-item or per-vault — coverage gap.
- **`tests/settings.rs`** — 158 lines. `settings_roundtrip_trash_retention`, conflicting-flags rejection, generator-defaults end-to-end, `status` command coverage including `last_backup` round-trip. Solid.
- **`tests/backup.rs`** — 142 lines. Export/restore round-trip, `--include-image`, `--no-history`, refusal of non-empty target, wrong-passphrase failure. Excellent coverage.
- **`tests/import_lastpass.rs`** — 127 lines. Importer integration: success, single-commit guarantee, zero-items rejection, header validation, duplicate-import-IDs-are-unique invariant.
- **`tests/smart_inputs.rs`** — 210 lines. Completion-script smoke tests, groups-cache write/suppress, `rate` command (strong/weak/`-` stdin), `--totp-qr` via in-process synthesized QR PNG (`make_test_qr`) — adheres to "synthetic fixtures, no binary blobs."
- **`tests/vault_detection.rs`** — 59 lines. `list_refuses_without_vault_marker`, `get_finds_vault_in_parent_dir`, `v1_vault_is_rejected_with_clear_error` (`.idfoto/` ignored because lookup is for `.relicario/`).
- **`tests/common/mod.rs`** — 132 lines. `TestVault` harness; `init()` creates a `TempDir`, generates synthetic JPEG via `make_test_jpeg`, runs binary with `RELICARIO_TEST_PASSPHRASE` set. `run`, `run_with_input`, `run_with_backup_pass` variants. No shared global state — parallel-test safe.
### relicario-server
- **`src/main.rs`** — 189 lines, very legible. Two clap subcommands cleanly mapped. `verify_commit` reads devices.json + revoked.json from the commit's tree (`git show`), spawns `git verify-commit --raw` with a dynamically-built allowed-signers file injected via `GIT_CONFIG_*` env vars (a clever touch — chido [cool] — avoids touching user gitconfig), parses the SHA-256 fingerprint from stderr, then enforces revocation-first then registration logic. Uses committer timestamp (not author) for revocation cutoff (`:115-123`) — correct for non-rebased histories. All rejection paths use `eprintln!("REJECT: ...")` with actionable context (commit SHA, fingerprint, reason) and exit 1 — visible to the pushing client via `git push` stderr. `generate_hook` emits a clean bash script handling branch creation (`oldrev = 000...`) and branch deletion (`newrev = 000...`).
- **`tests/verify_commit.rs`** — 230 lines, four named scenarios mapping to audit S1. Each test stands up a tempdir git repo, generates real ed25519 keypairs via `relicario_core::device::generate_keypair`, signs a commit with explicit committer date, and shells out to the cargo-built binary via `assert_cmd`. Coverage gaps noted in P2.
- **`Cargo.toml`** — minimal, no surprises. Importantly: no AEAD or KDF crate, which structurally guarantees the server cannot decrypt.
### relicario-wasm
- **`Cargo.toml`** — 27 lines. Right deps. `getrandom = { features = ["js"] }` correctly enabled for browser entropy routing. `image` is dev-only — good. `relicario-core/Cargo.toml` does NOT enable the `js` getrandom feature (correct: core stays platform-agnostic), and the wasm crate "lifts" the feature flag for the dep graph.
- **`src/lib.rs`** — 591 lines, the bulk of the surface. Module doc-comment is concise. Imports are sprinkled mid-file (`:52, :138, :180, :310, :340, :469, :491`) instead of clustered at the top — historical from incremental authoring per Task 19/20/21 markers. Consolidating saves scroll. Sections are demarcated by `// ── ... ──` dividers which help.
- **`src/session.rs`** — 57 lines. `SessionData { master_key, image_secret }` stored in `thread_local! { RefCell<HashMap<u32, _>> }`, monotonic `NEXT_HANDLE` u32 (skips 0 on wraparound). `insert`, `with`, `with_image_secret`, `remove`, `clear` (test-only). Missing `impl Drop for SessionHandle` — see P1.
- **`src/device.rs`** — 71 lines. Clean. `Zeroizing<String>` for private keys (correct — `String::zeroize` wipes the heap allocation). Uses `Lazy<Mutex<DeviceState>>` (different pattern from `session.rs` — see P2).
### Build / clippy
- `cargo check -p relicario-cli` — clean
- `cargo check -p relicario-server` — clean
- `cargo check -p relicario-wasm` — clean
- `cargo build -p relicario-wasm --target wasm32-unknown-unknown` — clean, finishes in ~6s, zero warnings
- `cargo clippy --workspace` — silent (per subagent reports)
---
## Boundary notes for DEV-C
These are the items that look fine from the Rust side but DEV-C must verify on the TypeScript side:
1. **CRITICAL — every `.free()` callsite on a `SessionHandle`.** wasm-bindgen's auto-generated `.free()` does NOT remove the entry from the Rust-side `SESSIONS` registry today, because there is no `impl Drop for SessionHandle` (P1 above). Until that lands, every `.free()` callsite in TypeScript that does not first call `wasm.lock(handle)` is a master-key residency window in WASM linear memory of unbounded duration. Audit `extension/src` for every `.free()` on a `SessionHandle`. The Rust-side fix is preferred (defense in depth); DEV-C should also confirm that every TS-side lock path calls `wasm.lock(handle)` before `.free()` regardless.
2. **Verify every `.free()` callsite, full stop.** Same principle applies to `EncryptedAttachment.free()` and `TotpCode.free()`. wasm-bindgen will not call `free` automatically when the JS object is GC'd — JS GC does not trigger Rust drop. Any handle that goes out of scope without explicit `.free()` leaks in WASM linear memory.
3. **`unlock()` failure semantics.** When unlock throws (bad passphrase, bad params_json, salt wrong length, image_secret extract failure), no `SessionHandle` is created. TS callers should not wrap in `try { ... } finally { handle.free() }` because the handle var will be undefined.
4. **`manifest_decrypt`/`item_decrypt`/`settings_decrypt` return `JsValue` typed as `unknown` in TS.** Rust uses `serde_wasm_bindgen::Serializer::new().serialize_maps_as_objects(true)` (`lib.rs:65`). Verify TS doesn't assume `Map` semantics anywhere — should be plain JS objects. Binary fields decode to `Uint8Array`; confirm TS doesn't try to `JSON.stringify` a decrypted item containing binary.
5. **`*_encrypt` functions take `*_json: string`.** TS must `JSON.stringify` before calling. wasm-bindgen TS bindings will catch this at compile time, but verify no `as any` casts bypass.
6. **`totp_compute(_, now_unix_seconds: bigint)` and `attachment_encrypt(_, _, max_bytes: bigint)`** — TS must use `BigInt(...)`, not `number`. wasm-bindgen throws at runtime on mismatch.
7. **`Uint8Array` arguments are copied into WASM linear memory.** TS doesn't need defensive copies. But a `Uint8Array` view onto a `SharedArrayBuffer` may behave differently — verify TS isn't passing those.
8. **`EncryptedAttachment.aid` and `.bytes` clone on every read** (P2). TS code that does `enc.bytes` twice does double work + double copy. Cache locally.
9. **`SessionHandle.value` getter is exposed.** It's a u32 monotonic counter. If TS ever logs it (telemetry/debug), it's a session correlation identifier that survives across handles.
10. **`get_field_history` returns JS objects with snake_case keys** (`field_id`, `field_name`, `current_value`, `changed_at`). Verify TS components consume these names — easy mismatch with TS-side camelCase conventions.
11. **`register_device`/`sign_for_git`/`get_device_info`/`clear_device` are global, not per-session** — backed by `static DEVICE_STATE` (`Lazy<Mutex<>>`). Single SW = single state, fine. If TS ever instantiates multiple WASM modules (e.g. one per offscreen doc), each gets its own state — verify TS uses one shared init path.
12. **Naming inconsistency**: only `wasm_generate_recovery_qr` and `wasm_unwrap_recovery_qr` carry the `wasm_` prefix. If DEV-C maintains a name-mapping table or auto-generated wrappers, flag for a rename pass.
13. **`parse_lastpass_csv_json` returns `string` (JSON-encoded), not a `JsValue`.** TS must `JSON.parse` the result — different shape from `manifest_decrypt` which returns already-deserialized `unknown`. Verify `import_lastpass.ts` does `JSON.parse(...)` on the result.
14. **All exports are snake_case in JS.** If DEV-C ever wants idiomatic camelCase, the mechanism is `#[wasm_bindgen(js_name = "...")]` per export. Decide once, before the surface grows.
---
## Beginner-friendliness assessment
For a competent dev who's never written Rust:
- **Server is ideal.** 189 lines, one trust-model question, every dependency is plaintext metadata. A newcomer can read it end-to-end in under ten minutes and walk away understanding what the server does and does not do. The single change that would help most is a paragraph-length module-level comment near the top of `main.rs` explaining *why* the server only verifies signatures (because the vault is encrypted client-side, the server has no key, the hook's only job is to gate writes by device authenticity). That paragraph would make the trust story self-evident on first contact.
- **WASM is approachable but has one cliff.** 720 lines across 3 files; `lib.rs` reads top-to-bottom okay; the doc-comment on `SessionHandle` is clear about the opaque-handle contract; the section dividers help. The cliff is the missing `Drop` impl: a beginner reasonably assumes wasm-bindgen handles registry cleanup automatically (it does not). A short comment in `session.rs` saying "**Drop the SessionHandle ≠ remove from registry; you must call `lock()`**" would prevent that mistake — but better to fix the missing `Drop` so the comment isn't needed.
- **CLI has one big roadblock and a lot of small ones.** `helpers.rs`, `session.rs`, `device.rs`, `gitea.rs` all read like real code: small modules, focused responsibilities, doc-comment headers, sensible names. `helpers.rs`'s tests double as documentation. The clap surface in `main.rs:1-455` is itself a product tour. Past line 456, `main.rs` becomes a 2200-line flat file with no submodule boundaries. A newcomer searching "where does add work?" finds `cmd_add` calling 7 different `build_*_item` functions (each ~50-60 lines) plus 6 prompt helpers, all peers. Plus the Rust-specific tripwires — the `let _ = entry;` pattern repeated 6×, the `Zeroizing` newtype, the `Option<Foo>::map(Ok).unwrap_or_else(...)?` chain at every builder — compound the unfamiliarity.
**Single biggest change across the consumer layer:** split `crates/relicario-cli/src/main.rs` into a folder. Keep `main.rs` as clap definitions + dispatcher (~470 lines, very readable). Move every `cmd_*` to `commands/<name>.rs`, prompts to `prompt.rs`, parsers to `parse.rs`. Same LOC, completely different reading experience — and this is the precondition for fixing the duplicated git boilerplate (CLI P1 #2) and centralizing `refresh_groups_cache`.
---
## Open questions for DEV-B (escalated to PM separately)
1. Was `impl Drop for SessionHandle` deliberately omitted (e.g. to avoid double-free if JS holds two refs to the same handle)? If yes, document it; if no, this is the headline fix.
2. CLI `parse_month_year`, `base32_decode_lenient`, `guess_mime` — should they migrate to `relicario-core` for CLI/extension parity?
3. Is "missing `.relicario/devices.json` = bootstrap = accept" intended in perpetuity, or should it be tightened once a repo has any non-empty devices.json in history?
4. Is the `Lock` no-op CLI subcommand worth keeping visible in `--help` for parity with the extension, or hide behind `#[command(hide = true)]`?
5. `cmd_backup_export` still reads `devices.json` per a "Task 12 will remove" TODO. Is Task 12 landed, deferred, or abandoned?

View File

@@ -0,0 +1,343 @@
# DEV-C Architecture Review Notes — TypeScript (Extension + Relay)
**Reviewer:** dev-c (TypeScript scope) **Date:** 2026-05-04 **Branch:** main (read-only review)
## Summary
The TypeScript layer is **soundly organized but unevenly distributed**: a tight discriminated-union message contract (`shared/messages.ts`) and a clean Manifest V3 trust split (popup/setup/content/SW) anchor a codebase that earns its complexity from the two-factor unlock UX. The strongest part is the **service-worker router**: every popup/content message has a typed handler with origin-aware gating, and content scripts never touch WASM. The weakest parts are **two oversized modules that pre-empt the otherwise-clean component model**: `extension/src/setup/setup.ts` (1220 LOC) bypasses the SW and orchestrates WASM directly, and `extension/src/vault/vault.ts` (1027 LOC) inlines shell, sidebar, list, drawer, type-picker, form-wrapper and routing into one file. **CLI/extension parity is excellent overall** — every CLI subcommand has a UI path through the unified left-nav settings (v0.5.1) or vault tab — with two real gaps: explicit per-attachment detach (extension does it via `update_item`) and a vault-status surface equivalent to `relicario status`. One **broken test** in uncommitted relay code (`tools/relay/queue.test.ts:54`) blocks `bun test` from going green.
## Findings (prioritized: P1 / P2 / P3)
### Extension — service-worker
**[P1] router/popup-only.ts:687703 & router/content-callable.ts:187205 — duplicated storage helpers (`loadDeviceSettings`, `loadBlacklist`, `saveBlacklist`)**
WHY: Three identical chrome.storage.local helpers in both router files; both code paths can mutate blacklist via different definitions, so future drift will silently corrupt one path.
DIRECTION: Extract to `service-worker/storage.ts`; import from both routers.
**[P1] router/popup-only.ts:~169 & router/content-callable.ts:~169 — `itemToManifestEntry()` duplicated**
WHY: Identical 17-line manifest projection in both router files; refactors of the manifest schema will need to be made twice.
DIRECTION: Move into `service-worker/vault.ts` and import.
**[P2] service-worker/index.ts:7678 — inactivity timer reset skips content-callable messages**
WHY: Only popup/vault sends reset the timer; a user who is actively autofilling but never opens the popup will eventually be force-locked despite continuous use. Conversely, "every_time" mode is fine.
DIRECTION: Reset on all messages except known read-only content calls (`get_autofill_candidates`); document the exclusion in the timer module.
**[P2] service-worker/index.ts:5158 — session expiry clears `state.manifest` but leaves `state.gitHost`**
WHY: After expiry, the cached git-host client survives; the next unlock could mix with stale connection state if a remote was rotated.
DIRECTION: Null `state.gitHost` alongside `state.manifest` in the expiry callback; the initializer rebuilds it on demand.
**[P2] service-worker/session.ts:26 — `try { current.free() }` swallows free errors**
WHY: A double-free or invalid-handle on the WASM session would be silently ignored, masking a lifecycle bug that could leave the master key zeroed but the JS handle dangling.
DIRECTION: Let exceptions propagate (or log + counter); silent swallow is the wrong default for crypto state transitions.
**[P3] service-worker/index.ts:6165 — chrome.storage.local.get on startup swallows errors**
WHY: A typo or storage quota event leaves the timer in default state with no signal in the logs.
DIRECTION: Surface failure via console.warn with the key name.
**[P3] service-worker/git-host.ts vs github.ts/gitea.ts — deploy-key API only on Gitea side**
WHY: The interface is asymmetric; either GitHub doesn't need it (document) or it's an unimplemented feature.
DIRECTION: Add a doc comment on `GitHost` explaining the asymmetry, or add the GitHub op.
### Extension — popup + components
**[P1] settings.ts:5665 & settings-vault.ts:1522 — duplicated teardown helpers**
WHY: After the stub-restore commits (`8baef5b`, `ddfb95d`), teardown leaks are a known regression class; duplicated cleanup is exactly the shape that re-introduces them.
DIRECTION: Extract `teardownSettingsCommon()` into a single helper; have each settings section call it on unmount.
**[P2] popup.ts:178181 — teardown calls every type module unconditionally**
WHY: Cycling views runs all 7 type teardowns on each transition; harmless today, but makes the lifecycle hard to reason about and hides which module was actually mounted.
DIRECTION: Track last-mounted type and tear down only that one (or use a registry of `() => teardown` returned by mount).
**[P2] settings.ts:3334 — `pendingVaultSettings` and `sessionHandle` are module-scope singletons**
WHY: Section navigation can leave stale `pendingVaultSettings` from a previous section in scope; the current code is safe by accident, not by design.
DIRECTION: Reset to `null` on each `renderSection` entry, or scope into a closure per render.
**[P2] item-list.ts:152353 — settings-picker popover wires listeners on every render without a reuse path**
WHY: Open/close cycles attach + detach listeners cleanly today, but rapid re-opens with throttled `setTimeout` cleanup are exactly the pattern teardown bugs hide in.
DIRECTION: Cache the popover DOM and reuse, or use AbortController for the listeners with an explicit `signal` per open.
**[P2] devices.ts:4750 & trash.ts:3946 — `Promise.all` without per-promise error handling**
WHY: A single rejected RPC fails the whole render; the second response is discarded even when its data was fetched successfully.
DIRECTION: `Promise.allSettled`, then check `.ok` per response.
**[P2] generator-panel.ts:89261 — module-scope `activePanel`; `closeGeneratorPanel()` not idempotent-guarded**
WHY: The cleanup is currently a no-op when called twice, but the contract is implicit.
DIRECTION: Add `if (!activePanel) return` at top.
**[P3] form-header.ts:20 + types/login.ts — `isInTab()` checked twice (header + caller)**
WHY: Redundant coupling; the popout button visibility decision happens in two places.
DIRECTION: Pass `showPopout: boolean` into `renderFormHeader` once.
**[P3] popup.ts:3638 — `isInTab()` heuristic is `window.location.search.length > 0`**
WHY: Any query string on `popup.html` triggers tab mode; brittle if popup is ever opened with diagnostic params.
DIRECTION: Parse a specific param (`?view=tab` or check `window.location.pathname.endsWith('vault.html')`).
**[P3] item-form.ts:95104 — `renderComingSoon()` defined but unused**
WHY: Document type now has a real form (`types/document.ts`); the placeholder is dead code.
DIRECTION: Delete or leave a one-line comment explaining future use.
**[P3] types/login.ts ~700 LOC — `renderForm` mixes HTML, wiring, password-strength, TOTP-ticker, and section editor**
WHY: The reference implementation for the other 6 type modules; size makes the per-affordance lifecycle hard to follow for a learner.
DIRECTION: Extract `wireUrlField`, `wirePasswordField`, `wireTotpField` from the body of `renderForm`. Other type modules already follow simpler patterns.
### Extension — vault tab
**[P1] vault/vault.ts (1027 LOC) — single file owns shell + sidebar + list + drawer + type-picker + form-wrapper + routing + teardown**
WHY: A learner opening this file faces all responsibilities at once; teardown coupling (`teardownPaneComponents` lines 813820) makes adding a new pane view a 5-place edit.
DIRECTION: Split into `vault-shell.ts`, `vault-sidebar.ts`, `vault-list.ts`, `vault-drawer.ts`, `vault-form-wrapper.ts`, leaving `vault.ts` to own only routing and state.
**[P2] vault/vault.ts:4774 — vault tab intercepts `vault_locked` errors via the RPC layer; popup uses only the `session_expired` event**
WHY: Two different mechanisms reach the same outcome; popup-targeted components running in the vault tab don't know which channel will fire first.
DIRECTION: Lift the RPC `vault_locked` intercept into `shared/state.ts` (or a wrapper around `sendMessage`) so both surfaces use one path.
**[P2] vault/vault.ts:495536 — drawer doesn't auto-close on non-list view changes**
WHY: Selecting an item opens the drawer; navigating to Trash via the sidebar leaves `state.drawerOpen = true` even though the drawer is no longer rendered.
DIRECTION: `state.drawerOpen = false` at the start of `renderPane`, or when a non-list view becomes active.
**[P2] vault/vault.ts:648695 — sidebar categories re-render on every search keystroke without debounce**
WHY: Counts and active state must sync, but at hundreds of items the keystroke path stamps the whole sidebar.
DIRECTION: 50100ms debounce on the search input handler before re-rendering.
**[P3] vault/vault.ts:1826 — backup-panel and import-panel are `vault/components/`-only by design**
WHY: Correct call (popup has no room for these), but worth noting in the file header so a contributor doesn't try to import them into popup.
DIRECTION: Add a short comment in `vault/components/index.ts` (or top of each file) explaining the vault-tab-only scope.
### Extension — content scripts
**[P2] content/fill.ts:5064 — `fillFields()` returns silently when no password field is found**
WHY: Dynamic forms (React/SPA mounting after `document_idle`) can race the fill listener; user clicks autofill, nothing visible happens, no error reaches the popup.
DIRECTION: Send a `{type: 'fill_failed', reason: 'no_password_field'}` ack back to SW so the icon can flash an error glyph.
**[P2] content/detector.ts:96103 — MutationObserver `scan()` is not debounced**
WHY: SPA churn fires DOM mutations many times per second; the detector re-runs the full scan each time. WeakSet stops icon double-injection, but the scan cost is wasted.
DIRECTION: Wrap `scan()` in `requestIdleCallback` or a 200ms timer.
**[P2] content/icon.ts:169175 — outside-click listener registered in `setTimeout(0)` not removed on alternate close paths**
WHY: Picker can close via Escape or programmatic destroy; the doc-level listener for outside-click leaks unless `closeOverlay()` is the close path.
DIRECTION: Store the handler reference and `removeEventListener` in every close path; or `AbortController` scoped to picker open.
**[P3] capture.ts vs detector.ts vs fill.ts — username-finder logic copy-pasted three ways**
WHY: `findUsernameField`, `findUsernameForFill`, `findUsernameValue` are three forks of the same heuristic.
DIRECTION: Extract a shared `getUsernameField(pwField, scope, { valueOnly?: boolean })`.
**[P3] capture.ts:269299 — submit-button hook scope is `form ?? pwField.parentElement`**
WHY: A submit button outside the form (e.g. a custom React `<button onClick={...}>` siblings to the form) won't trigger capture; the user never sees the save prompt.
DIRECTION: Walk up to the nearest form ancestor and listen for `keydown.Enter` on the password field as a fallback.
**[Positive note] content scripts make zero direct WASM calls and re-validate origin in `fill.ts:3238`** — boundary discipline holds.
### Extension — setup
**[P1] setup/setup.ts:2837, 11181120 — WASM is loaded and called directly inside the setup wizard, bypassing the service-worker abstraction the rest of the codebase uses**
WHY: Popup, vault tab, and content all funnel WASM through the SW; setup is the only surface that imports `relicario-wasm` and orchestrates `unlock`/`embed_image_secret`/`register_device`/`manifest_encrypt` itself. This duplicates ~400 LOC of crypto orchestration that the SW already knows how to do, and it means the setup tab can't be locked by the same session-timer the rest of the extension uses.
DIRECTION: Add `create_vault` and `attach_vault` messages to the SW; turn `setup.ts` into a UI that posts those messages with the gathered config + image bytes. This collapses ~600 LOC into ~200 and unifies the crypto state machine.
**[P2] setup/setup.ts (1220 LOC) — render/attach pairs per step are inlined**
WHY: 6 steps × (renderStepN, attachStepN) = a switch statement that reads procedurally; adding a step means edits to the renderer, the attacher, and the wizard state.
DIRECTION: Step registry: `{ id: 0, render: () => string, attach: (root) => Teardown }[]` keyed by mode. The 1220 LOC drops to ~500 after the WASM extraction in [P1] above and this restructure.
**[P2] setup/setup.ts:6994 — `WizardState` is module-scope; passphrase + JPEG bytes + WASM handle persist if the user abandons mid-wizard**
WHY: A user who closes the setup tab mid-flow leaves sensitive material in JS memory until the page is unloaded. The handle isn't `free()`d.
DIRECTION: Add a `clearWizardState()` called on `beforeunload` and on returning to step 0; explicitly `Zeroize`-equivalent for the byte arrays where possible.
**[P2] setup/probe.ts:1123 vs service-worker/vault.ts — manifest path constants duplicated (`.relicario/salt`, `.relicario/params.json`, `manifest.enc`)**
WHY: Two sources of truth; if the metadata layout ever moves, probe and vault disagree about whether a remote is initialized.
DIRECTION: Define `VAULT_PATHS` in `shared/types.ts` (or a new `shared/paths.ts`) and import into both.
**[P3] setup/setup.ts:56, 8283 — passphrase score uses `-1` as "not yet scored" sentinel**
WHY: The score is conflated with strength label index 0..4; `-1` magic number is checked in two places.
DIRECTION: Use `{ scored: false } | { scored: true; score: number; guessesLog10: number }`.
**[P3] setup/setup.ts:10561062 — `recovery_qr_generated_at` written directly to `chrome.storage.local`, bypassing `WizardState`**
WHY: One piece of setup result state lives outside the wizard's own state model.
DIRECTION: Add it to `WizardState`, persist on a single `finishSetup` storage write.
**[P3] setup/setup.ts:17 — header comment says "5-step flow"; code is 6 steps (0..5)**
WHY: Cosmetic but actively misleading; line 42 even has a comment about the renumber.
DIRECTION: Update header.
### Extension — shared utilities
**[P1] shared/state.ts:1035 — entire `StateHost` contract is `any`-typed**
WHY: This is the bridge that lets popup components run in the vault tab; it's also the bridge most likely to drift between the two render targets, and TS gives no signal when it does.
DIRECTION: Define a concrete `StateHost` interface with `state: PopupState`, `navigate: (view: View) => void`, `popOutToTab(): void`, `isInTab(): boolean`, `openVaultTab(hash?: string): void`. Make `getState`/`setState` generic over `keyof PopupState`.
**[P1] shared/state.ts:20 — module-scope `host` singleton with no double-registration guard**
WHY: A second `registerHost()` call silently overwrites; in tests, the leak from a previous test breaks isolation if `beforeEach` forgets a reset.
DIRECTION: Throw on re-register; export a `__resetHostForTests()` helper for vitest.
**[P2] shared/messages.ts:8587 — base `Response` is `{ data?: unknown }`; every consumer casts via `Extract<Response, { ok: true }>` plus `data: ...`**
WHY: The pattern works but every call site has a hand-written `as ListItemsResponse` cast; the discriminated-union narrowing the rest of the file relies on stops at `ok: true`.
DIRECTION: Generic `Response<TKind extends Request['type']>` mapped from a single `MessageMap` table, so the response type is inferred at the send site.
**[P2] shared/form-affordances/group-autocomplete.ts:26 — `list.innerHTML = ...map(g => …).join('')` with only `replace(/"/g, '&quot;')` sanitization**
WHY: Group names come from user-entered item data. `<` and `>` are not escaped; a malicious / mistaken group name could inject markup into the autocomplete list.
DIRECTION: `document.createElement('option')` per group with `option.value = g; list.appendChild(option)`.
**[P2] shared/messages.ts:5666 — `restore_backup` flattens `newRemote` inline; other multi-field messages factor out a payload type**
WHY: Inconsistent shape vs sibling messages; harder to reuse the type for the form that posts it.
DIRECTION: Extract `RestoreBackupPayload` and intersect with `{ type: 'restore_backup' }`.
**[P3] glyphs.ts vs popup/components — raw glyph literals (`⧉`, `↻`, `▸`, `▾`, `≡`, `⤓`) appear inline in `item-form.ts`, `item-list.ts`, `settings.ts`, `generator-panel.ts`, `attachments-disclosure.ts`, `fields.ts`**
WHY: The whole point of `glyphs.ts` is the no-inline-emoji rule; partial adoption defeats the audit story.
DIRECTION: Add the missing constants (`GLYPH_COLLAPSE`, `GLYPH_EXPAND`, `GLYPH_ATTACHMENT`, `GLYPH_REGENERATE`, `GLYPH_OVERFLOW`, `GLYPH_DOWNLOAD`) and migrate the call sites. Pair with `extension/src/shared/__tests__/glyphs.test.ts` to lock it in.
**[P3] shared/types.ts:82 — `TotpKind = 'totp' | 'steam' | { hotp: { counter: number } }`**
WHY: Mixed string/object union forces every consumer to do `typeof k === 'string' ? k : k.hotp`; a flat discriminated union is cheaper to read.
DIRECTION: `{ kind: 'totp' } | { kind: 'steam' } | { kind: 'hotp'; counter: number }` with serde rename if the wire format must stay.
**[P3] shared/form-affordances/totp-tools.ts:3946 — `void tick()` swallows promise rejections**
WHY: TOTP preview RPC can fail (e.g., decrypt error); the user sees a frozen ticker with no signal.
DIRECTION: `try { await tick() } catch (e) { renderError(row, e) }`.
### WASM boundary (JS side)
**[P2] extension/src/wasm.d.ts — declarations are hand-written and explicitly require manual sync with `crates/relicario-wasm/src/lib.rs`**
WHY: Comment at top of the file says so; this is exactly the kind of contract that drifts when one side adds a new export. (Today, declarations and the Rust signatures are aligned.)
DIRECTION: Add a CI check that compares `crates/relicario-wasm/pkg/relicario_wasm.d.ts` (wasm-pack output) against `extension/src/wasm.d.ts`, or import the generated `.d.ts` directly via `wasm-pack build --target web` and the runtime loader. Note for DEV-B in boundary section.
**[P2] extension/src/__stubs__/relicario_wasm.stub.ts — only 7 of ~25 exports are stubbed; the rest will throw `wasm stub: X not mocked`**
WHY: Adding a vitest test that touches a new WASM call needs an ad-hoc mock per test; central stub is incomplete.
DIRECTION: Either round out the stub with throwing stubs for the full surface, or provide a `mockWasm({ unlock, item_decrypt, ... })` test helper.
### Relay tooling
**[P1] tools/relay/queue.test.ts:54 — `assert.ok(!isRole("dev-c"))` fails (verified: `bun test` → 1 fail)**
WHY: Uncommitted change added `dev-c` to the `Role` union and `KNOWN_ROLES` set in `queue.ts`, but the test still asserts the old enum. This is a P1 because it's a real test failure on uncommitted code, blocking a green test run.
DIRECTION: Update the test assertion to `assert.ok(isRole("dev-c"))` and add a negative case (`assert.ok(!isRole("dev-d"))`).
**[P1] tools/relay/start.sh — kitty mode launches Dev-C window? Verify against the script**
WHY: The 4-role refactor (pm/dev-a/dev-b/dev-c) needs a fourth window in the launcher. Per the subagent's read, `start.sh:80` still hardcodes "Dev-B" in user-facing output.
DIRECTION: Update the launcher prints to mention all 4 roles and confirm a 4th `--type=tab --hold` window is opened with the dev-c prompt.
**[P2] tools/relay/call.py and tools/relay/call.ts — untracked, no .gitignore policy**
WHY: Coordination prompts (including this one's "Fallback" section) reference `call.py` by path — it's load-bearing for the multi-agent flow, not an experiment. Untracked load-bearing files are a coordination footgun (a fresh checkout breaks the fallback).
DIRECTION: Track both with a one-line header explaining "MCP-fallback shim for the relay; see docs/superpowers/coordination/...". If either is genuinely scratch, add to `.gitignore` instead — but pick one.
**[P2] tools/relay/queue.ts:2127 — in-memory queue with no TTL, persistence, or cap**
WHY: A long-running relay accumulates messages indefinitely; if a session sleeps for a day, the queue is the only audit trail and could grow unbounded.
DIRECTION: Document the dev-only ephemeral contract at the top of `queue.ts`, or add a per-role cap (e.g., last 1000 messages).
**[P3] tools/relay/server.ts:115127 — `makeServer()` factory pattern is correct but unexplained**
WHY: The diff swap from a global `mcpServer` to per-connection factories is load-bearing for concurrent client isolation, but a future contributor might revert it as "unnecessary complexity".
DIRECTION: One-line comment above `makeServer`: "Per-connection MCP server prevents routing collisions across concurrent SSE clients."
### CLI/extension parity gaps
**[P2] No equivalent to `relicario status`** — CLI shows pending sync state, ahead/behind, dirty-tree summary; extension surfaces nothing comparable. The vault-tab footer or a sidebar badge would be the natural home.
DIRECTION: Add a `get_vault_status` message returning `{ ahead: n, behind: n, lastSyncAt: ts, pendingItems: n }` and a small status indicator in the vault sidebar.
**[P3] No explicit per-attachment detach message** — CLI has `relicario detach <item> <aid>`; extension forces a roundtrip through `update_item` with the `attachments[]` mutated client-side. Functional, but it's racy if two devices edit at once.
DIRECTION: Add a `delete_attachment` message that does the surgical remove on the SW side.
**[P3] CLI `list --tag X` filter** — extension does tag filtering client-side after `list_items`; that's fine for the family-vault scale spec but may surprise a learner who reads the CLI side first.
DIRECTION: Document the choice in `messages.ts` near `list_items`.
### Cross-cutting
**[P2] Direct `chrome.storage.local` reads from popup components** — `settings-security.ts:112113` and `setup.ts:10561062` read storage directly while every other popup module routes via `sendMessage`. Inconsistency makes the data-flow story split across two paradigms.
DIRECTION: Pick one: either every storage read goes through `get_settings`/`get_session_config`, or document explicitly that `setup` and `settings-security` are SW-bypass code paths for stated reasons.
**[P2] `bun test` is not the project's intended runner** — `extension/package.json:13` defines `test: vitest run`, but `tools/relay/` uses `node:test` via `bun test`. A learner will hit failures running `bun test` from the repo root because `bun` doesn't load `happy-dom`.
DIRECTION: Add a top-level README note: "extension uses `cd extension && npm run test`; relay uses `cd tools/relay && bun test`."
**[P3] Manifest version 0.5.0** — both `extension/manifest.json` and `manifest.firefox.json` show `0.5.0`, while `package.json` is also `0.5.0`. The roadmap is at v0.5.1-dev; uncommitted bumps to package.json/manifest may be coming. Worth a quick PM check.
## File-by-file walk
### `extension/src/wasm.d.ts` and `__stubs__/relicario_wasm.stub.ts`
Hand-written ambient module declarations mirroring `crates/relicario-wasm/src/lib.rs`. 25+ exports cover unlock/lock, manifest+item+settings encrypt/decrypt, attachment encrypt/decrypt, ID generation, password/passphrase generation + zxcvbn rate, image-secret embed/extract, TOTP compute, device register/sign/get/clear, recovery-QR. The stub used by vitest covers only 7 exports — every other call throws "not mocked" at test time.
### `extension/src/shared/`
`types.ts` (286 LOC) is the canonical TS view of the Rust core schema; well-commented mappings to serde. `messages.ts` (207 LOC) is the discriminated-union message contract and the `POPUP_ONLY_TYPES` / `CONTENT_CALLABLE_TYPES` capability sets that the router uses for sender gating. `state.ts` (62 LOC) is the popup-vs-vault host indirection — currently `any`-typed. `glyphs.ts` (39 LOC, recently edited) is the centralized monospace glyph set. `color-scheme.ts`, `error-copy.ts`, `base32.ts`, `password-coloring.ts`, `toast.ts` are tight focused utilities. `form-affordances/` holds 5 input-behavior wirings (group autocomplete, notes mono toggle, password reveal/strength/QR, TOTP preview/QR, URL fill) plus a tiny `index.ts`.
### `extension/src/service-worker/`
`index.ts` is the entry point: WASM load on first message, RouterState construction, session-timer wiring, `chrome.runtime.onMessage` listener. `vault.ts` (397 LOC) is the encrypted I/O layer — every WASM call passes the `SessionHandle`, never a raw key. `session.ts` is the single-handle store; `session-timer.ts` implements both `inactivity` and `every_time` modes. `devices.ts` reads/writes `.relicario/devices.json` and `revoked.json`. `gitea.ts` and `github.ts` mirror each other (Gitea has deploy-key ops; GitHub doesn't); `git-host.ts` is the abstraction. `router/index.ts` classifies the sender and dispatches to `popup-only.ts` (40+ handlers) or `content-callable.ts` (5 handlers).
### `extension/src/popup/`
`popup.ts` (entry) wires the host registration, view router, and lock/unlock flow. `index.html` is a single `#popup-app` container. `styles.css` carries the popup theme. `components/` holds the visible widgets: `unlock`, `item-list`, `item-detail`, `item-form`, `form-header`, `fields`, `field-history`, `attachments-disclosure`, `generator-panel`, `devices`, `trash`, plus the new `settings.ts` / `settings-vault.ts` / `settings-security.ts` left-nav (v0.5.1). `components/types/` holds the 7 type-specific item modules — `login.ts` is the reference, the others (secure-note, identity, card, key, document, totp) are smaller variants.
### `extension/src/vault/`
`vault.html` (12 LOC) loads `vault.css` + `vault.js`. `vault.css` (~2200 LOC) carries the dark/gold theme + 3-column layout. `vault.ts` (1027 LOC) orchestrates everything: shell init, hash routing, sidebar, list, drawer, type-picker, form-wrapper, deep-link routing, teardown. `components/backup-panel.ts` and `components/import-panel.ts` are vault-tab-only (high-risk operations need fullscreen affordances). Tests: `form-wrapper.test.ts`, `sidebar-glyphs.test.ts`.
### `extension/src/content/`
`detector.ts` finds password fields and injects icons via a MutationObserver. `fill.ts` receives `fill_credentials`, re-validates the page hostname, and uses the native-setter trick to set values past React/Vue. `capture.ts` hooks form submits and shows a closed-Shadow-DOM save prompt. `icon.ts` renders the in-page icon and credentials picker. `shadow.ts` is the closed-Shadow-DOM helper. **Zero WASM calls; clean boundary.**
### `extension/src/setup/`
`setup.ts` (1220 LOC) is the 6-step (0..5) wizard: mode pick → remote config → image select / passphrase → derive+verify or create+embed → device register → recovery QR. Imports WASM directly. `setup-helpers.ts` (84 LOC) is a clean utility module (escapeHtml, debounced rate, strength labels). `probe.ts` (23 LOC) checks for an existing vault on the configured remote.
### `tools/relay/`
`server.ts` is the MCP server with HTTP/SSE transport (per-connection `makeServer()`). `queue.ts` is the in-memory FIFO with `Role` enum and `isRole()` guard. `queue.test.ts` is `node:test` based (4 pass / 1 fail on uncommitted state). `call.py` and `call.ts` are the MCP-fallback shims (untracked). `start.sh` launches manual / tmux / kitty modes. `package.json`, `tsconfig.json` keep the relay self-contained.
## CLI/extension parity table
| CLI capability | Extension equivalent | Notes |
|---|---|---|
| `init --image --output` | `save_setup` + setup wizard step 3-new | ✓ (parity via setup.ts; see [P1] about routing through SW) |
| `add login/secure_note/identity/card/key/document/totp` | `add_item` + `types/<kind>.ts` form | ✓ |
| `get <query> [--show] [--copy]` | `get_item` + popup detail; clipboard via `navigator.clipboard` | ✓ |
| `list [--type] [--group] [--tag] [--trashed]` | `list_items`, `list_trashed`, client-side filter; `list_groups` for autocomplete | ✓ |
| `edit <query> [--totp-qr]` | `update_item` + `wireTotpQr` (jsQR lazy import) | ✓ |
| `history <query>` | `get_field_history` + `field-history.ts` | ✓ |
| `rm <query>` (soft) | `delete_item` | ✓ |
| `restore <query>` | `restore_item` | ✓ |
| `purge <query>` | `purge_item` | ✓ |
| `trash list / empty` | `list_trashed` / `purge_all_trash` + `trash.ts` | ✓ |
| `backup export` | `export_backup` + `backup-panel.ts` | ✓ |
| `backup restore` | `restore_backup` + `backup-panel.ts` (restore path) | ✓ |
| `import lastpass <csv>` | `parse_lastpass_csv` + `import_lastpass_commit` + `import-panel.ts` | ✓ |
| `attach <query> <file>` | `upload_attachment` | ✓ |
| `attachments <query>` | `AttachmentRef[]` already inside `get_item` | ✓ (no separate message; same data) |
| `extract <query> <aid>` | `download_attachment` | ✓ |
| `detach <query> <aid>` | (no message) — done via `update_item` with mutated `attachments[]` | **partial / ✗** |
| `generate --length / --bip39 …` | `generate_password` / `generate_passphrase` + `generator-panel.ts` | ✓ |
| `settings trash-retention / history-retention / attachment-cap / generator-defaults` | `get_vault_settings` / `update_vault_settings` + `settings-vault.ts` | ✓ |
| `sync` | `sync` | ✓ |
| `status` | (no message) | **✗ — gap** |
| `lock` | `lock` | ✓ |
| `completions <shell>` | N/A (CLI-only) | n/a |
| `rate <passphrase>` | `rate_passphrase` (zxcvbn gate) | ✓ |
| `device add / revoke` (+ list) | `add_device` / `register_this_device` / `revoke_device` / `list_devices` / `list_revoked` + `devices.ts` | ✓ |
| `recovery-qr generate / unwrap` | `generate_recovery_qr` / `unwrap_recovery_qr` + `settings-security.ts` | ✓ |
| (browser-only autofill) | `get_autofill_candidates`, `get_credentials`, `check_credential`, `blacklist_site`, `capture_save_login`, `fill_credentials`, `ack_autofill_origin`, `get_blacklist`, `remove_blacklist`, `get_active_tab_url` | extension-only (no CLI counterpart, by design) |
| (browser-only device UX) | `get_settings` / `update_settings` (DeviceSettings: captureEnabled, captureStyle) | extension-only |
**Summary:** 22/23 CLI capabilities have a clean extension path; `status` is the one true gap, and `detach` is partial. No "CLI first, extension follow-up" violations under this lens.
## Boundary notes for DEV-B
1. **`extension/src/wasm.d.ts` is hand-maintained** — every change to `crates/relicario-wasm/src/lib.rs`'s `#[wasm_bindgen]` surface must be mirrored manually. Worth a CI guardrail comparing the wasm-packgenerated `.d.ts` against this file. (See [P2] in WASM boundary.)
2. **The session handle is opaque on the JS side** (`SessionHandle.value: number`, `free()`). DEV-B owns the Rust-side lifecycle: confirm that double-`free()` from JS is a no-op rather than a panic, since `service-worker/session.ts:26` currently swallows free errors silently. If the Rust side could panic on double-free, the silent swallow becomes a crash mask.
3. **`attachment_encrypt(handle, plaintext, max_bytes: bigint)`** — the JS side passes `BigInt` for `max_bytes`. Confirm the Rust binding accepts `u64` and that the conversion is loss-free. The extension is going to push this with γ₁ enforcement (per project memory).
4. **`register_device(name)` returns `{ signing_public_key, deploy_public_key }`** as a plain object (not a class). Setup wizard relies on both being hex strings (`device.public_key` lookup paths). Confirm the device key types stay strings on the Rust side rather than ever moving to `Uint8Array`.
5. **`generate_recovery_qr(handle, passphrase) → string`** and `unwrap_recovery_qr(payload_b64, passphrase) → Uint8Array` — the QR payload format is a contract between this surface and the CLI's `recovery-qr` subcommand. If DEV-B is reviewing recovery-QR end-to-end, confirm that re-deriving from a recovery QR produces the same `master_key` regardless of which side (CLI vs extension) generated it.
6. **`extract_image_secret(image_bytes) → Uint8Array` and `embed_image_secret(carrier, secret) → Uint8Array`** — the central-embed DCT scheme has `MAX_DIMENSION` and `QUANT_STEP = 50.0` constants on the Rust side. The setup wizard does no client-side dimension check before passing the image; if a >MAX_DIMENSION JPEG is selected, the failure message bubbles up generically. DEV-B may want a more specific Rust-side error variant the extension can re-render.
## Beginner-friendliness assessment (TS side)
**Reading order recommendation:** start with `extension/src/shared/messages.ts` and `types.ts` — they tell you the entire vocabulary in 500 lines. Then `service-worker/router/index.ts` to see how messages get routed. Then pick **one** vertical to follow end-to-end: `popup/components/types/login.ts``service-worker/router/popup-only.ts` (the `add_item`/`update_item` handlers) → `service-worker/vault.ts`. After that, `content/detector.ts` + `content/fill.ts` + the corresponding `content-callable.ts` handlers cover the autofill story.
**Trip wires:** the two oversized files (`vault.ts` 1027 LOC, `setup.ts` 1220 LOC) are the steepest cliffs. A learner who opens `setup.ts` first will see WASM imported directly and conclude that's the pattern — it isn't; that file is the exception. Adding a short `EXTENSION_ARCH.md` (or a comment block at the top of `setup.ts`) noting "WASM is loaded directly here only because vault creation predates the SW; everywhere else, route through `chrome.runtime.sendMessage`" would save half a day.
**Strongest learning surfaces:** the discriminated-union message contract, the per-type item form modules (small, parallel, easy to diff), and `service-worker/router/router.test.ts`. The shared form-affordances are also a model of pure-function wiring with explicit teardown — once those patterns click, the rest of the popup is "more of the same."
**Weakest learning surface:** `shared/state.ts` — it's the bridge between popup and vault tab, but the `any` typing tells you nothing about what flows through it. Tightening this is a high-leverage change.
## Uncommitted-state read
The working tree has substantial uncommitted changes. Architecturally relevant:
- **`extension/src/vault/vault.ts` (+151/99) and `vault.css` (+238/99)** — appear to be active work on the form wrapper sticky bar, drawer field grid, and gold-rebrand color palette (Phase 2B). Treat these as **in flight, ignore for this review** — they don't change the architectural shape, only the visual surface.
- **`extension/src/shared/glyphs.ts` (+/2) and `__tests__/glyphs.test.ts` (+/2)** — small additions, likely a new glyph constant. Doesn't affect the [P3] glyph adoption finding (the inline-literal call sites would still need migration).
- **`extension/manifest.json` and `manifest.firefox.json` (+/2)** — likely a version bump in flight; PM should decide whether v0.5.1-dev gets a synced bump in `package.json` too.
- **`tools/relay/queue.ts`, `server.ts`, `start.sh` (modified) + `call.py`, `call.ts` (untracked)** — these are **architecturally relevant**: the dev-c role expansion is real, and `call.py`/`call.ts` are documented-but-untracked fallback shims. The broken test (`queue.test.ts:54`) is the P1 the rest of this review flags. **Do not ignore.**
- **`Cargo.lock`, `crates/*/Cargo.toml`** — out of scope; flag to DEV-A/DEV-B if not already on their list.
- **`.gitea_env_vars` (untracked)** — name suggests local credentials; should be `.gitignore`d if not already (PM check).
- **`docs/superpowers/coordination/v0.5.1-*` and `architecture-review-*`** — coordination prompt evolution; not architectural.
**My call:** vault/vault.css/glyphs/manifest changes are in-flight and shouldn't change findings. The relay changes ARE architecturally on-the-table because the new dev-c role + factory pattern are visible in the running review process. The relay test failure is treated as a P1 because it blocks `bun test` from going green and the kickoff prompt explicitly says "Review is not gated on green; it's gated on understanding" — but this is one cheap fix away from a green test run, and a learner running `bun test` first will assume the codebase is broken.

View File

@@ -1,7 +1,7 @@
{ {
"manifest_version": 3, "manifest_version": 3,
"name": "Relicario", "name": "Relicario",
"version": "0.2.0", "version": "0.5.0",
"description": "Two-factor encrypted password manager", "description": "Two-factor encrypted password manager",
"icons": { "icons": {
"16": "icons/icon-16.png", "16": "icons/icon-16.png",

View File

@@ -1,7 +1,7 @@
{ {
"manifest_version": 3, "manifest_version": 3,
"name": "Relicario", "name": "Relicario",
"version": "0.2.0", "version": "0.5.0",
"description": "Two-factor encrypted password manager", "description": "Two-factor encrypted password manager",
"icons": { "icons": {
"16": "icons/icon-16.png", "16": "icons/icon-16.png",

View File

@@ -1,12 +1,12 @@
{ {
"name": "relicario-extension", "name": "relicario-extension",
"version": "0.2.0", "version": "0.5.0",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "relicario-extension", "name": "relicario-extension",
"version": "0.2.0", "version": "0.5.0",
"dependencies": { "dependencies": {
"jsqr": "^1.4.0" "jsqr": "^1.4.0"
}, },

View File

@@ -1,6 +1,6 @@
{ {
"name": "relicario-extension", "name": "relicario-extension",
"version": "0.2.0", "version": "0.5.0",
"private": true, "private": true,
"scripts": { "scripts": {
"build": "webpack --mode production", "build": "webpack --mode production",

View File

@@ -0,0 +1,22 @@
import { describe, it, expect, vi } from 'vitest';
vi.stubGlobal('chrome', {
storage: {
local: {
get: vi.fn((_keys: unknown, cb: (r: Record<string, unknown>) => void) => cb({})),
set: vi.fn((_data: unknown, cb?: () => void) => cb?.()),
},
},
});
import * as settingsMod from '../settings';
describe('settings module contract', () => {
it('exports renderSettings as a function', () => {
expect(typeof settingsMod.renderSettings).toBe('function');
});
it('exports teardownSettings as a function', () => {
expect(typeof settingsMod.teardownSettings).toBe('function');
});
});

View File

@@ -7,6 +7,7 @@
import { sendMessage, escapeHtml } from '../../shared/state'; import { sendMessage, escapeHtml } from '../../shared/state';
import type { AttachmentRef, VaultSettings } from '../../shared/types'; import type { AttachmentRef, VaultSettings } from '../../shared/types';
import { GLYPH_TYPE_DOCUMENT } from '../../shared/glyphs';
export type DisclosureMode = 'edit' | 'view'; export type DisclosureMode = 'edit' | 'view';
@@ -53,8 +54,8 @@ export function renderAttachmentsDisclosure(opts: AttachmentsDisclosureOpts): st
const action = opts.mode === 'edit' ? '×' : '↓'; const action = opts.mode === 'edit' ? '×' : '↓';
const actionClass = opts.mode === 'edit' ? 'attachment-row__remove' : 'attachment-row__download'; const actionClass = opts.mode === 'edit' ? 'attachment-row__remove' : 'attachment-row__download';
const iconHtml = isImage(a.mime_type) const iconHtml = isImage(a.mime_type)
? `<span class="attachment-row__thumb" data-att-id="${escapeHtml(a.id)}" data-mime="${escapeHtml(a.mime_type)}">📄</span>` ? `<span class="attachment-row__thumb" data-att-id="${escapeHtml(a.id)}" data-mime="${escapeHtml(a.mime_type)}">${GLYPH_TYPE_DOCUMENT}</span>`
: `<span class="attachment-row__icon">📄</span>`; : `<span class="attachment-row__icon">${GLYPH_TYPE_DOCUMENT}</span>`;
return ` return `
<div class="attachment-row" data-att-id="${escapeHtml(a.id)}"> <div class="attachment-row" data-att-id="${escapeHtml(a.id)}">
${iconHtml} ${iconHtml}

View File

@@ -3,6 +3,7 @@
import { getState, setState, sendMessage, navigate, escapeHtml } from '../../shared/state'; import { getState, setState, sendMessage, navigate, escapeHtml } from '../../shared/state';
import { colorizePassword } from '../../shared/password-coloring'; import { colorizePassword } from '../../shared/password-coloring';
import type { FieldHistoryView } from '../../shared/types'; import type { FieldHistoryView } from '../../shared/types';
import { GLYPH_COPY } from '../../shared/glyphs';
function relativeTime(unixSec: number): string { function relativeTime(unixSec: number): string {
const now = Math.floor(Date.now() / 1000); const now = Math.floor(Date.now() / 1000);
@@ -75,7 +76,7 @@ export async function renderFieldHistory(app: HTMLElement): Promise<void> {
${isCurrent ? '<span class="history-entry__current">current</span>' : ''} ${isCurrent ? '<span class="history-entry__current">current</span>' : ''}
<span>${isCurrent ? 'set' : 'changed'} ${relativeTime(timestamp)}</span> <span>${isCurrent ? 'set' : 'changed'} ${relativeTime(timestamp)}</span>
</div> </div>
<button class="history-entry__copy" data-entry-copy="${escapeHtml(entryKey)}" title="Copy">📋</button> <button class="history-entry__copy" data-entry-copy="${escapeHtml(entryKey)}" title="Copy">${GLYPH_COPY}</button>
</div> </div>
`; `;
} }
@@ -140,7 +141,7 @@ export async function renderFieldHistory(app: HTMLElement): Promise<void> {
const value = valueStore.get(key) ?? ''; const value = valueStore.get(key) ?? '';
await navigator.clipboard.writeText(value); await navigator.clipboard.writeText(value);
btn.textContent = '✓'; btn.textContent = '✓';
setTimeout(() => { btn.textContent = '📋'; }, 1500); setTimeout(() => { btn.textContent = GLYPH_COPY; }, 1500);
}); });
}); });
} }

View File

@@ -3,15 +3,19 @@
import { navigate, getState, setState, escapeHtml, popOutToTab, isInTab } from '../../shared/state'; import { navigate, getState, setState, escapeHtml, popOutToTab, isInTab } from '../../shared/state';
import type { Item, ItemType } from '../../shared/types'; import type { Item, ItemType } from '../../shared/types';
import {
GLYPH_TYPE_LOGIN, GLYPH_TYPE_SECURE_NOTE, GLYPH_TYPE_TOTP,
GLYPH_TYPE_CARD, GLYPH_TYPE_IDENTITY, GLYPH_TYPE_KEY, GLYPH_TYPE_DOCUMENT,
} from '../../shared/glyphs';
const TYPE_OPTIONS: Array<{ type: ItemType; icon: string; label: string }> = [ const TYPE_OPTIONS: Array<{ type: ItemType; icon: string; label: string; description: string }> = [
{ type: 'login', icon: '🔑', label: 'login' }, { type: 'login', icon: GLYPH_TYPE_LOGIN, label: 'Login', description: 'Username + password' },
{ type: 'secure_note', icon: '📝', label: 'secure note' }, { type: 'secure_note', icon: GLYPH_TYPE_SECURE_NOTE, label: 'Secure Note', description: 'Encrypted text note' },
{ type: 'identity', icon: '👤', label: 'identity' }, { type: 'identity', icon: GLYPH_TYPE_IDENTITY, label: 'Identity', description: 'Personal details' },
{ type: 'card', icon: '💳', label: 'card' }, { type: 'card', icon: GLYPH_TYPE_CARD, label: 'Card', description: 'Credit / debit card' },
{ type: 'key', icon: '🔐', label: 'key' }, { type: 'key', icon: GLYPH_TYPE_KEY, label: 'SSH / API Key', description: 'Keys and tokens' },
{ type: 'document', icon: '📄', label: 'document' }, { type: 'document', icon: GLYPH_TYPE_DOCUMENT, label: 'Document', description: 'File attachment' },
{ type: 'totp', icon: '⏱️', label: 'totp' }, { type: 'totp', icon: GLYPH_TYPE_TOTP, label: 'TOTP', description: '2FA authenticator' },
]; ];
import * as login from './types/login'; import * as login from './types/login';
import * as secureNote from './types/secure-note'; import * as secureNote from './types/secure-note';
@@ -54,36 +58,36 @@ export function renderItemForm(app: HTMLElement, mode: 'add' | 'edit'): void {
function renderTypeSelection(app: HTMLElement): void { function renderTypeSelection(app: HTMLElement): void {
app.innerHTML = ` app.innerHTML = `
<div class="pad"> <div class="pad">
<div style="display:flex; align-items:center; gap:12px;"> <div style="display:flex; align-items:center; gap:12px; margin-bottom:12px;">
<button class="btn" id="back-btn"> back</button> <button class="btn" id="back-btn"> back</button>
<h3 style="margin:0;">new item</h3> <span style="font-size:14px; font-weight:600;">New item</span>
<span style="flex:1;"></span> <span style="flex:1;"></span>
${isInTab() ? '' : '<button class="btn" id="popout-btn" title="Open in tab"></button>'} ${isInTab() ? '' : '<button class="btn" id="popout-btn" title="Open in tab"></button>'}
</div> </div>
${isInTab() ? '<div class="form-subtitle">esc to cancel</div>' : '<div style="margin-bottom:16px;"></div>'} <div class="type-card-grid">
<div class="type-select-list">
${TYPE_OPTIONS.map((opt) => ` ${TYPE_OPTIONS.map((opt) => `
<button class="type-select-row" data-type="${opt.type}"> <button class="type-card" data-type="${opt.type}">
<span class="type-select-icon">${opt.icon}</span> <span class="type-card__icon" aria-hidden="true">${opt.icon}</span>
<span>${escapeHtml(opt.label)}</span> <span class="type-card__label">${escapeHtml(opt.label)}</span>
<span class="type-card__desc">${escapeHtml(opt.description)}</span>
</button> </button>
`).join('')} `).join('')}
</div> </div>
<div class="keyhints"><span><kbd>Esc</kbd> back</span></div>
</div> </div>
`; `;
document.getElementById('back-btn')?.addEventListener('click', () => navigate('list')); document.getElementById('back-btn')?.addEventListener('click', () => navigate('list'));
document.getElementById('popout-btn')?.addEventListener('click', popOutToTab); document.getElementById('popout-btn')?.addEventListener('click', popOutToTab);
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') navigate('list');
}, { once: true });
document.querySelectorAll<HTMLButtonElement>('[data-type]').forEach((btn) => { document.querySelectorAll<HTMLButtonElement>('[data-type]').forEach((btn) => {
btn.addEventListener('click', () => { btn.addEventListener('click', () => {
const type = btn.dataset.type as ItemType; const type = btn.dataset.type as ItemType;
setState({ newType: type }); setState({ newType: type });
if (type === 'login' || type === 'secure_note') {
renderItemForm(app, 'add'); renderItemForm(app, 'add');
} else {
popOutToTab();
}
}); });
}); });
} }

View File

@@ -3,6 +3,13 @@
/// to the detail view. /// to the detail view.
import { getState, setState, sendMessage, navigate, escapeHtml, openVaultTab } from '../../shared/state'; import { getState, setState, sendMessage, navigate, escapeHtml, openVaultTab } from '../../shared/state';
import { showToast } from '../../shared/toast';
import {
GLYPH_VAULT_TAB,
GLYPH_DEVICES, GLYPH_LOCK,
GLYPH_TYPE_LOGIN, GLYPH_TYPE_SECURE_NOTE, GLYPH_TYPE_TOTP,
GLYPH_TYPE_CARD, GLYPH_TYPE_IDENTITY, GLYPH_TYPE_KEY, GLYPH_TYPE_DOCUMENT,
} from '../../shared/glyphs';
import type { ItemId, ItemType, ManifestEntry, Item } from '../../shared/types'; import type { ItemId, ItemType, ManifestEntry, Item } from '../../shared/types';
/// Extract the display hostname from an icon_hint or fallback to the first tag. /// Extract the display hostname from an icon_hint or fallback to the first tag.
@@ -12,30 +19,46 @@ function metaLine(e: ManifestEntry): string {
return ''; return '';
} }
/// Emoji icon per item type. Placeholder until we ship real SVG icons. /// Glyph icon per item type.
function typeIcon(t: ItemType): string { function typeIcon(t: ItemType): string {
switch (t) { switch (t) {
case 'login': return '🔑'; case 'login': return GLYPH_TYPE_LOGIN;
case 'secure_note': return '📝'; case 'secure_note': return GLYPH_TYPE_SECURE_NOTE;
case 'identity': return '🪪'; case 'identity': return GLYPH_TYPE_IDENTITY;
case 'card': return '💳'; case 'card': return GLYPH_TYPE_CARD;
case 'key': return '🗝'; case 'key': return GLYPH_TYPE_KEY;
case 'document': return '📄'; case 'document': return GLYPH_TYPE_DOCUMENT;
case 'totp': return '⏱'; case 'totp': return GLYPH_TYPE_TOTP;
} }
} }
function buildRowsHtml(): string { function buildRowsHtml(): string {
const state = getState(); const state = getState();
const filtered = getFilteredEntries(); const filtered = getFilteredEntries();
return filtered.length > 0 if (filtered.length > 0) {
? filtered.map(([id, e], i) => ` return filtered.map(([id, e], i) => `
<div class="entry-row ${i === state.selectedIndex ? 'selected' : ''}" data-id="${escapeHtml(id)}" data-index="${i}"> <div class="entry-row ${i === state.selectedIndex ? 'selected' : ''}" data-id="${escapeHtml(id)}" data-index="${i}">
<span class="entry-name"><span class="type-icon" aria-hidden="true">${typeIcon(e.type)}</span> ${escapeHtml(e.title)}${e.attachment_summaries.length > 0 ? ' <span class="entry-row__attach-indicator" title="has attachments">📎</span>' : ''}</span> <span class="entry-name"><span class="type-icon" aria-hidden="true">${typeIcon(e.type)}</span> ${escapeHtml(e.title)}${e.attachment_summaries.length > 0 ? ' <span class="entry-row__attach-indicator" title="has attachments"></span>' : ''}</span>
<span class="entry-meta">${escapeHtml(metaLine(e))}</span> <span class="entry-meta">${escapeHtml(metaLine(e))}</span>
</div> </div>
`).join('') `).join('');
: '<div class="empty">no items</div>'; }
if (state.searchQuery) {
return `
<div class="empty-state">
<span class="empty-state__icon" aria-hidden="true">⊘</span>
<div class="empty-state__title">No results for "${escapeHtml(state.searchQuery)}"</div>
<div class="empty-state__hint">Try a shorter search term.</div>
</div>
`;
}
return `
<div class="empty-state">
<span class="empty-state__icon" aria-hidden="true">◈</span>
<div class="empty-state__title">No items yet</div>
<div class="empty-state__hint">Press <kbd>+</kbd> to add your first item.</div>
</div>
`;
} }
function updateItemList(): void { function updateItemList(): void {
@@ -66,7 +89,7 @@ export function renderItemList(app: HTMLElement): void {
<button class="btn" id="new-btn" style="font-size:11px;">+ new</button> <button class="btn" id="new-btn" style="font-size:11px;">+ new</button>
<button class="btn" id="sync-btn" style="font-size:11px;">sync</button> <button class="btn" id="sync-btn" style="font-size:11px;">sync</button>
<span style="flex:1;"></span> <span style="flex:1;"></span>
<button class="btn" id="vault-btn" style="font-size:11px;" title="Open vault (Shift+F)">&#x2934;</button> <button class="btn" id="vault-btn" style="font-size:11px;" title="Open vault (Shift+F)">${GLYPH_VAULT_TAB}</button>
<button class="btn" id="settings-btn" style="font-size:11px;">settings</button> <button class="btn" id="settings-btn" style="font-size:11px;">settings</button>
<button class="btn" id="lock-btn" style="font-size:11px;">lock</button> <button class="btn" id="lock-btn" style="font-size:11px;">lock</button>
</div> </div>
@@ -108,11 +131,14 @@ export function renderItemList(app: HTMLElement): void {
if (listResp.ok) { if (listResp.ok) {
const data = listResp.data as { items: Array<[ItemId, ManifestEntry]> }; const data = listResp.data as { items: Array<[ItemId, ManifestEntry]> };
setState({ entries: data.items, loading: false }); setState({ entries: data.items, loading: false });
showToast('Synced', 'success');
return; return;
} }
setState({ loading: false, error: listResp.error }); setState({ loading: false, error: listResp.error });
showToast(listResp.error ?? 'Sync failed', 'error');
} else { } else {
setState({ loading: false, error: resp.error }); setState({ loading: false, error: resp.error });
showToast(resp.error ?? 'Sync failed', 'error');
} }
}); });
@@ -253,8 +279,8 @@ function handleListKeydown(e: KeyboardEvent): void {
// ---------------------------------------------------------------------- // ----------------------------------------------------------------------
const SETTINGS_OPTIONS: Array<{ view: 'settings' | 'settings-vault'; icon: string; label: string }> = [ const SETTINGS_OPTIONS: Array<{ view: 'settings' | 'settings-vault'; icon: string; label: string }> = [
{ view: 'settings', icon: '🖥', label: 'device settings' }, { view: 'settings', icon: GLYPH_DEVICES, label: 'device settings' },
{ view: 'settings-vault', icon: '🔐', label: 'vault settings' }, { view: 'settings-vault', icon: GLYPH_LOCK, label: 'vault settings' },
]; ];
function showSettingsPicker(anchor: HTMLElement): void { function showSettingsPicker(anchor: HTMLElement): void {

View File

@@ -1,18 +1,111 @@
/// Settings view — capture toggle, prompt style, and blacklist management. import { sendMessage, escapeHtml, openVaultTab } from '../../shared/state';
import type { VaultSettings, DeviceSettings, TrashRetention, HistoryRetention } from '../../shared/types';
import { sendMessage, navigate, escapeHtml } from '../../shared/state'; import type { ColorScheme } from '../../shared/color-scheme';
import type { DeviceSettings } from '../../shared/types';
import { GLYPH_TRASH, GLYPH_DEVICES } from '../../shared/glyphs';
import { import {
loadColorScheme, saveColorScheme, resetColorScheme, loadColorScheme, saveColorScheme, resetColorScheme,
DEFAULT_DIGIT_COLOR, DEFAULT_SYMBOL_COLOR, DEFAULT_DIGIT_COLOR, DEFAULT_SYMBOL_COLOR,
} from '../../shared/color-scheme'; } from '../../shared/color-scheme';
import { colorizePassword } from '../../shared/password-coloring'; import { colorizePassword } from '../../shared/password-coloring';
import { openGeneratorPanel, closeGeneratorPanel, isGeneratorPanelOpen } from './generator-panel';
import { renderSecuritySection, teardownSecuritySection } from './settings-security';
export async function renderSettings(app: HTMLElement): Promise<void> { type SettingsSection =
app.innerHTML = '<div class="pad" style="text-align:center; padding-top:20px;"><span class="spinner"></span></div>'; | 'autofill'
| 'display'
| 'security'
| 'generator'
| 'retention'
| 'backup'
| 'import';
// Load settings and blacklist in parallel const NAV_ITEMS: Array<{ id: SettingsSection; icon: string; label: string; group: 'device' | 'vault' }> = [
{ id: 'autofill', icon: '⊙', label: 'Autofill', group: 'device' },
{ id: 'display', icon: '◈', label: 'Display', group: 'device' },
{ id: 'security', icon: '◉', label: 'Security', group: 'vault' },
{ id: 'generator', icon: '↻', label: 'Generator', group: 'vault' },
{ id: 'retention', icon: '▦', label: 'Retention', group: 'vault' },
{ id: 'backup', icon: '⤓', label: 'Backup', group: 'vault' },
{ id: 'import', icon: '≡', label: 'Import', group: 'vault' },
];
let activeSection: SettingsSection = 'autofill';
let activeKeyHandler: ((e: KeyboardEvent) => void) | null = null;
let pendingVaultSettings: VaultSettings | null = null;
let sessionHandle: number | null = null;
export async function renderSettings(container: HTMLElement): Promise<void> {
container.innerHTML = `
<div class="settings-layout">
<nav class="settings-nav" id="settings-nav">
<div class="settings-nav__group-label">Device</div>
${NAV_ITEMS.filter(n => n.group === 'device').map(navItemHtml).join('')}
<div class="settings-nav__group-label">Vault</div>
${NAV_ITEMS.filter(n => n.group === 'vault').map(navItemHtml).join('')}
</nav>
<div class="settings-content" id="settings-content"></div>
</div>
`;
const unlockedResp = await sendMessage({ type: 'is_unlocked' });
sessionHandle = (unlockedResp.ok && unlockedResp.data && (unlockedResp.data as { unlocked: boolean }).unlocked) ? 1 : null;
wireNav();
await renderSection(activeSection);
}
export function teardownSettings(): void {
closeGeneratorPanel();
teardownSecuritySection();
if (activeKeyHandler) {
document.removeEventListener('keydown', activeKeyHandler);
activeKeyHandler = null;
}
pendingVaultSettings = null;
sessionHandle = null;
}
function navItemHtml(item: (typeof NAV_ITEMS)[0]): string {
const active = item.id === activeSection ? ' settings-nav__item--active' : '';
return `
<button class="settings-nav__item${active}" data-section="${item.id}">
<span class="settings-nav__icon" aria-hidden="true">${item.icon}</span>
<span class="settings-nav__label">${escapeHtml(item.label)}</span>
</button>
`;
}
function wireNav(): void {
document.getElementById('settings-nav')?.querySelectorAll<HTMLButtonElement>('[data-section]')
.forEach((btn) => {
btn.addEventListener('click', async () => {
teardownSecuritySection();
closeGeneratorPanel();
activeSection = btn.dataset.section as SettingsSection;
document.querySelectorAll('.settings-nav__item').forEach(b => b.classList.remove('settings-nav__item--active'));
btn.classList.add('settings-nav__item--active');
await renderSection(activeSection);
});
});
}
async function renderSection(section: SettingsSection): Promise<void> {
const content = document.getElementById('settings-content');
if (!content) return;
switch (section) {
case 'autofill': return renderAutofillSection(content);
case 'display': return renderDisplaySection(content);
case 'security': return renderSecuritySection(content, sessionHandle);
case 'generator': return renderGeneratorSection(content);
case 'retention': return renderRetentionSection(content);
case 'backup': return renderBackupSection(content);
case 'import': return renderImportSection(content);
}
}
// --- Section stubs (filled in by Tasks 3-9) ---
async function renderAutofillSection(content: HTMLElement): Promise<void> {
const [settingsResp, blacklistResp] = await Promise.all([ const [settingsResp, blacklistResp] = await Promise.all([
sendMessage({ type: 'get_settings' }), sendMessage({ type: 'get_settings' }),
sendMessage({ type: 'get_blacklist' }), sendMessage({ type: 'get_blacklist' }),
@@ -26,166 +119,314 @@ export async function renderSettings(app: HTMLElement): Promise<void> {
? (blacklistResp.data as { blacklist: string[] }).blacklist ? (blacklistResp.data as { blacklist: string[] }).blacklist
: []; : [];
const blacklistHtml = blacklist.length > 0 content.innerHTML = `
<h3 class="settings-section-title">Capture</h3>
<div class="setting-row">
<div class="setting-row__info">
<div class="setting-row__title">Auto-detect logins</div>
<div class="setting-row__desc">Show a prompt when a login form is detected.</div>
</div>
<div class="setting-row__control">
<input type="checkbox" id="capture-enabled" ${settings.captureEnabled ? 'checked' : ''}>
</div>
</div>
<div class="setting-row">
<div class="setting-row__info">
<div class="setting-row__title">Prompt style</div>
<div class="setting-row__desc">How to prompt when a login is detected.</div>
</div>
<div class="setting-row__control" style="display:flex; gap:6px;">
<button class="btn ${settings.captureStyle === 'bar' ? 'btn-active' : ''}" id="style-bar" style="font-size:11px;">bar</button>
<button class="btn ${settings.captureStyle === 'toast' ? 'btn-active' : ''}" id="style-toast" style="font-size:11px;">toast</button>
</div>
</div>
<h3 class="settings-section-title" style="margin-top:20px;">Blocked sites</h3>
<div id="blacklist-container">
${blacklist.length > 0
? blacklist.map((h) => ` ? blacklist.map((h) => `
<div style="display:flex; align-items:center; justify-content:space-between; padding:4px 0; border-bottom:1px solid #21262d;"> <div class="setting-row">
<span style="font-size:12px; overflow:hidden; text-overflow:ellipsis;">${escapeHtml(h)}</span> <div class="setting-row__info">
<button class="relicario-remove-bl" data-hostname="${escapeHtml(h)}" style=" <div class="setting-row__title">${escapeHtml(h)}</div>
background:transparent; color:#ab2b20; border:none; cursor:pointer; </div>
font-size:11px; padding:2px 6px; <button class="btn remove-bl" data-hostname="${escapeHtml(h)}" style="font-size:11px;">remove</button>
">remove</button>
</div> </div>
`).join('') `).join('')
: '<p class="muted" style="font-size:12px;">no blacklisted sites</p>'; : '<p class="muted" style="font-size:12px; padding:8px 0;">No blocked sites.</p>'}
app.innerHTML = `
<div class="pad" style="padding-top:12px;">
<div style="display:flex; align-items:center; margin-bottom:16px;">
<button id="settings-back" class="btn" style="font-size:11px; margin-right:8px;">&larr;</button>
<span style="font-size:14px; font-weight:600;">settings</span>
</div>
<div style="margin-bottom:16px;">
<label style="display:flex; align-items:center; gap:8px; cursor:pointer; font-size:13px;">
<input type="checkbox" id="capture-enabled" ${settings.captureEnabled ? 'checked' : ''}>
auto-detect logins
</label>
</div>
<div style="margin-bottom:16px;">
<div style="font-size:12px; color:#8b949e; margin-bottom:6px;">prompt style</div>
<div style="display:flex; gap:8px;">
<button id="style-bar" class="btn" style="font-size:11px; ${settings.captureStyle === 'bar' ? 'background:#7c5719; color:#fff;' : ''}">bar</button>
<button id="style-toast" class="btn" style="font-size:11px; ${settings.captureStyle === 'toast' ? 'background:#7c5719; color:#fff;' : ''}">toast</button>
</div>
</div>
<div style="margin-bottom:16px;">
<button class="btn" id="trash-btn" style="width:100%;margin-bottom:8px;">${GLYPH_TRASH} trash</button>
<button class="btn" id="devices-btn" style="width:100%;margin-bottom:8px;">${GLYPH_DEVICES} devices</button>
<button class="btn" id="sync-now-btn" style="width:100%;margin-bottom:8px;">📤 Sync now</button>
<div id="sync-status" class="muted" style="font-size:12px;min-height:16px;"></div>
</div>
<div style="margin-bottom:16px;" id="display-section-container">
</div>
<div>
<div style="font-size:12px; color:#8b949e; margin-bottom:6px;">blacklisted sites</div>
<div id="blacklist-container">
${blacklistHtml}
</div>
</div>
</div> </div>
`; `;
// Back button
document.getElementById('settings-back')?.addEventListener('click', () => {
navigate('locked');
});
// Navigation buttons
document.getElementById('trash-btn')?.addEventListener('click', () => navigate('trash'));
document.getElementById('devices-btn')?.addEventListener('click', () => navigate('devices'));
// Sync now button
document.getElementById('sync-now-btn')?.addEventListener('click', async () => {
const btn = document.getElementById('sync-now-btn') as HTMLButtonElement | null;
const status = document.getElementById('sync-status');
if (!btn || !status) return;
btn.disabled = true;
status.textContent = 'syncing...';
const result = await sendMessage({ type: 'sync' });
btn.disabled = false;
status.textContent = result.ok ? 'synced ✓' : `sync failed: ${result.error}`;
});
// Capture enabled toggle
document.getElementById('capture-enabled')?.addEventListener('change', async (e) => { document.getElementById('capture-enabled')?.addEventListener('change', async (e) => {
const checked = (e.target as HTMLInputElement).checked; const enabled = (e.target as HTMLInputElement).checked;
await sendMessage({ type: 'update_settings', settings: { captureEnabled: checked } }); await sendMessage({ type: 'update_settings', settings: { captureEnabled: enabled } });
}); });
// Style buttons
document.getElementById('style-bar')?.addEventListener('click', async () => { document.getElementById('style-bar')?.addEventListener('click', async () => {
await sendMessage({ type: 'update_settings', settings: { captureStyle: 'bar' } }); await sendMessage({ type: 'update_settings', settings: { captureStyle: 'bar' } });
renderSettings(app); renderAutofillSection(content);
}); });
document.getElementById('style-toast')?.addEventListener('click', async () => { document.getElementById('style-toast')?.addEventListener('click', async () => {
await sendMessage({ type: 'update_settings', settings: { captureStyle: 'toast' } }); await sendMessage({ type: 'update_settings', settings: { captureStyle: 'toast' } });
renderSettings(app); renderAutofillSection(content);
}); });
// Blacklist remove buttons content.querySelectorAll<HTMLButtonElement>('.remove-bl').forEach((btn) => {
document.querySelectorAll('.relicario-remove-bl').forEach((btn) => {
btn.addEventListener('click', async () => { btn.addEventListener('click', async () => {
const hostname = (btn as HTMLElement).dataset.hostname; const host = btn.dataset.hostname;
if (hostname) { if (!host) return;
await sendMessage({ type: 'remove_blacklist', hostname }); await sendMessage({ type: 'remove_blacklist', hostname: host });
renderSettings(app); renderAutofillSection(content);
}
}); });
}); });
// Render Display section after the rest of the DOM is ready
await renderDisplaySection();
} }
function updateSwatch(swatch: HTMLElement, digitColor: string, symbolColor: string): void { async function renderDisplaySection(content: HTMLElement): Promise<void> {
swatch.style.setProperty('--relicario-pwd-digit-color', digitColor);
swatch.style.setProperty('--relicario-pwd-symbol-color', symbolColor);
swatch.innerHTML = '';
swatch.appendChild(colorizePassword('Abc123!@#xyz'));
}
async function renderDisplaySection(): Promise<void> {
// The Display section container must be present in the DOM before we call this
const container = document.getElementById('display-section-container');
if (!container) return;
const scheme = await loadColorScheme(); const scheme = await loadColorScheme();
container.innerHTML = ` content.innerHTML = `
<div style="font-size:12px; color:#8b949e; margin-bottom:6px;">display</div> <h3 class="settings-section-title">Password coloring</h3>
<div style="margin-bottom:8px;"> <div class="setting-row">
<label style="display:flex; align-items:center; gap:8px; font-size:13px;"> <div class="setting-row__info">
<input type="color" id="display-digit-color" value="${escapeHtml(scheme.digit_color)}"> <div class="setting-row__title">Digit color</div>
digit color
</label>
</div> </div>
<div style="margin-bottom:8px;"> <div class="setting-row__control">
<label style="display:flex; align-items:center; gap:8px; font-size:13px;"> <input type="color" id="digit-color" value="${escapeHtml(scheme.digit_color)}">
<input type="color" id="display-symbol-color" value="${escapeHtml(scheme.symbol_color)}">
symbol color
</label>
</div> </div>
<div id="display-swatch" class="color-preview-swatch"></div> </div>
<div style="margin-top:8px;"> <div class="setting-row">
<button id="display-reset" class="btn" style="font-size:11px;">reset to defaults</button> <div class="setting-row__info">
<div class="setting-row__title">Symbol color</div>
</div>
<div class="setting-row__control">
<input type="color" id="symbol-color" value="${escapeHtml(scheme.symbol_color)}">
</div>
</div>
<div class="setting-row">
<div class="setting-row__info">
<div class="setting-row__title">Preview</div>
</div>
<div class="setting-row__control">
<span id="color-preview" style="font-family:monospace; font-size:13px;"></span>
</div>
</div>
<div style="margin-top:12px;">
<button class="btn" id="reset-colors" style="font-size:11px;">Reset defaults</button>
</div> </div>
`; `;
const digitInput = document.getElementById('display-digit-color') as HTMLInputElement; function refreshPreview(s: ColorScheme): void {
const symbolInput = document.getElementById('display-symbol-color') as HTMLInputElement; const preview = document.getElementById('color-preview');
const swatch = document.getElementById('display-swatch') as HTMLElement; if (!preview) return;
preview.style.setProperty('--relicario-pwd-digit-color', s.digit_color);
// Render initial swatch preview.style.setProperty('--relicario-pwd-symbol-color', s.symbol_color);
updateSwatch(swatch, scheme.digit_color, scheme.symbol_color); preview.innerHTML = '';
preview.appendChild(colorizePassword('Abc123!@#'));
async function onColorChange(): Promise<void> {
const newScheme = { digit_color: digitInput.value, symbol_color: symbolInput.value };
await saveColorScheme(newScheme);
updateSwatch(swatch, newScheme.digit_color, newScheme.symbol_color);
} }
digitInput.addEventListener('change', () => void onColorChange()); refreshPreview(scheme);
symbolInput.addEventListener('change', () => void onColorChange());
document.getElementById('display-reset')?.addEventListener('click', async () => { document.getElementById('digit-color')?.addEventListener('change', async (e) => {
const color = (e.target as HTMLInputElement).value;
const current = await loadColorScheme();
await saveColorScheme({ ...current, digit_color: color });
refreshPreview({ ...current, digit_color: color });
});
document.getElementById('symbol-color')?.addEventListener('change', async (e) => {
const color = (e.target as HTMLInputElement).value;
const current = await loadColorScheme();
await saveColorScheme({ ...current, symbol_color: color });
refreshPreview({ ...current, symbol_color: color });
});
document.getElementById('reset-colors')?.addEventListener('click', async () => {
await resetColorScheme(); await resetColorScheme();
digitInput.value = DEFAULT_DIGIT_COLOR; renderDisplaySection(content);
symbolInput.value = DEFAULT_SYMBOL_COLOR;
updateSwatch(swatch, DEFAULT_DIGIT_COLOR, DEFAULT_SYMBOL_COLOR);
}); });
} }
async function renderGeneratorSection(content: HTMLElement): Promise<void> {
content.innerHTML = '<p class="muted" style="padding:20px;font-size:12px;">Loading…</p>';
const resp = await sendMessage({ type: 'get_vault_settings' });
if (!resp.ok) {
const errorMsg = (resp as { ok: false; error: string }).error;
content.innerHTML = `<p class="muted" style="padding:20px;">Failed to load: ${escapeHtml(errorMsg)}</p>`;
return;
}
const settings = (resp.data as { settings: VaultSettings }).settings;
content.innerHTML = `
<h3 class="settings-section-title">Generator defaults</h3>
<div class="setting-row">
<div class="setting-row__info">
<div class="setting-row__title">Configure generator</div>
<div class="setting-row__desc">Password length, character classes, passphrase word count.</div>
</div>
<div class="setting-row__control">
<button class="btn" id="open-generator-panel" style="font-size:11px;">Configure ▸</button>
</div>
</div>
`;
document.getElementById('open-generator-panel')?.addEventListener('click', (e) => {
const trigger = e.currentTarget as HTMLElement;
if (isGeneratorPanelOpen()) {
closeGeneratorPanel();
return;
}
openGeneratorPanel({
parent: content,
trigger,
initial: settings.generator_defaults,
context: 'configure-defaults',
});
});
}
async function renderRetentionSection(content: HTMLElement): Promise<void> {
content.innerHTML = '<p class="muted" style="padding:20px;font-size:12px;">Loading…</p>';
const resp = await sendMessage({ type: 'get_vault_settings' });
if (!resp.ok) {
content.innerHTML = `<p class="muted" style="padding:20px;">Failed to load: ${escapeHtml(resp.error ?? 'unknown')}</p>`;
return;
}
const settings = (resp.data as { settings: VaultSettings }).settings;
pendingVaultSettings = { ...settings };
content.innerHTML = `
<h3 class="settings-section-title">Trash retention</h3>
<div class="setting-row">
<div class="setting-row__info">
<div class="setting-row__title">Keep deleted items for</div>
<div class="setting-row__desc">Items in trash older than this are permanently deleted on the next sync.</div>
</div>
<div class="setting-row__control">
<select id="trash-retention" style="font-size:12px;">
<option value="days:7">7 days</option>
<option value="days:30">30 days</option>
<option value="days:90">90 days</option>
<option value="forever">Forever</option>
</select>
</div>
</div>
<h3 class="settings-section-title" style="margin-top:20px;">Field history retention</h3>
<div class="setting-row">
<div class="setting-row__info">
<div class="setting-row__title">Keep password history for</div>
<div class="setting-row__desc">History entries older than this are pruned on save.</div>
</div>
<div class="setting-row__control">
<select id="history-retention" style="font-size:12px;">
<option value="last_n:5">Last 5</option>
<option value="last_n:10">Last 10</option>
<option value="days:90">90 days</option>
<option value="days:365">1 year</option>
<option value="forever">Forever</option>
</select>
</div>
</div>
<div style="margin-top:12px;">
<button class="btn btn-primary" id="save-retention" style="font-size:11px;">Save retention settings</button>
</div>
`;
// Set current select values
(document.getElementById('trash-retention') as HTMLSelectElement).value =
trashRetentionToValue(settings.trash_retention);
(document.getElementById('history-retention') as HTMLSelectElement).value =
historyRetentionToValue(settings.field_history_retention);
document.getElementById('trash-retention')?.addEventListener('change', (e) => {
if (pendingVaultSettings) {
pendingVaultSettings.trash_retention = valueToTrashRetention((e.target as HTMLSelectElement).value);
}
});
document.getElementById('history-retention')?.addEventListener('change', (e) => {
if (pendingVaultSettings) {
pendingVaultSettings.field_history_retention = valueToHistoryRetention((e.target as HTMLSelectElement).value);
}
});
document.getElementById('save-retention')?.addEventListener('click', async () => {
if (!pendingVaultSettings) return;
const r = await sendMessage({ type: 'update_vault_settings', settings: pendingVaultSettings });
if (!r.ok) alert(`Save failed: ${r.error}`);
});
}
function trashRetentionToValue(r: TrashRetention): string {
if (r.kind === 'forever') return 'forever';
return `days:${r.value}`;
}
function valueToTrashRetention(v: string): TrashRetention {
if (v === 'forever') return { kind: 'forever' };
const m = /^days:(\d+)$/.exec(v);
if (m) return { kind: 'days', value: Number(m[1]) };
return { kind: 'forever' };
}
function historyRetentionToValue(r: HistoryRetention): string {
if (r.kind === 'forever') return 'forever';
if (r.kind === 'last_n') return `last_n:${r.value}`;
return `days:${r.value}`;
}
function valueToHistoryRetention(v: string): HistoryRetention {
if (v === 'forever') return { kind: 'forever' };
const mLast = /^last_n:(\d+)$/.exec(v);
if (mLast) return { kind: 'last_n', value: Number(mLast[1]) };
const mDays = /^days:(\d+)$/.exec(v);
if (mDays) return { kind: 'days', value: Number(mDays[1]) };
return { kind: 'forever' };
}
function renderBackupSection(content: HTMLElement): void {
content.innerHTML = `
<h3 class="settings-section-title">Backup &amp; restore</h3>
<div class="setting-row">
<div class="setting-row__info">
<div class="setting-row__title">Export &amp; restore backup</div>
<div class="setting-row__desc">Download an encrypted backup or restore from a file. Opens in the vault tab.</div>
</div>
<div class="setting-row__control">
<button class="btn" id="open-backup-tab" style="font-size:11px;">Open backup ▸</button>
</div>
</div>
`;
document.getElementById('open-backup-tab')?.addEventListener('click', () => openVaultTab('backup'));
}
function renderImportSection(content: HTMLElement): void {
content.innerHTML = `
<h3 class="settings-section-title">Import</h3>
<div class="setting-row">
<div class="setting-row__info">
<div class="setting-row__title">Import from LastPass</div>
<div class="setting-row__desc">Import a LastPass CSV export. Opens in the vault tab for review before committing.</div>
</div>
<div class="setting-row__control">
<button class="btn" id="open-import-tab" style="font-size:11px;">Open import ▸</button>
</div>
</div>
`;
document.getElementById('open-import-tab')?.addEventListener('click', () => openVaultTab('import'));
}
export { renderAutofillSection, renderDisplaySection, renderGeneratorSection,
renderRetentionSection, renderBackupSection, renderImportSection };
// Suppress unused-import warnings — these are used by Tasks 3-9
void sendMessage;
void loadColorScheme;
void saveColorScheme;
void resetColorScheme;
void DEFAULT_DIGIT_COLOR;
void DEFAULT_SYMBOL_COLOR;
void colorizePassword;
void openGeneratorPanel;
void pendingVaultSettings;
void activeKeyHandler;

View File

@@ -2,10 +2,19 @@
import { getState, setState, sendMessage, navigate, escapeHtml } from '../../shared/state'; import { getState, setState, sendMessage, navigate, escapeHtml } from '../../shared/state';
import type { ItemId, ManifestEntry, VaultSettings } from '../../shared/types'; import type { ItemId, ManifestEntry, VaultSettings } from '../../shared/types';
import {
GLYPH_TYPE_LOGIN, GLYPH_TYPE_SECURE_NOTE, GLYPH_TYPE_IDENTITY, GLYPH_TYPE_CARD,
GLYPH_TYPE_KEY, GLYPH_TYPE_DOCUMENT, GLYPH_TYPE_TOTP,
} from '../../shared/glyphs';
const TYPE_ICONS: Record<string, string> = { const TYPE_ICONS: Record<string, string> = {
login: '🔑', secure_note: '📝', identity: '👤', card: '💳', login: GLYPH_TYPE_LOGIN,
key: '🔐', document: '📄', totp: '⏱️', secure_note: GLYPH_TYPE_SECURE_NOTE,
identity: GLYPH_TYPE_IDENTITY,
card: GLYPH_TYPE_CARD,
key: GLYPH_TYPE_KEY,
document: GLYPH_TYPE_DOCUMENT,
totp: GLYPH_TYPE_TOTP,
}; };
function relativeTime(unixSec: number): string { function relativeTime(unixSec: number): string {
@@ -64,7 +73,7 @@ export async function renderTrash(app: HTMLElement): Promise<void> {
? `<p class="muted" style="text-align:center;margin-top:32px;">Trash is empty</p>` ? `<p class="muted" style="text-align:center;margin-top:32px;">Trash is empty</p>`
: items.map(([id, entry]) => ` : items.map(([id, entry]) => `
<div class="trash-row" data-id="${escapeHtml(id)}"> <div class="trash-row" data-id="${escapeHtml(id)}">
<span class="trash-row__icon">${TYPE_ICONS[entry.type] ?? '📦'}</span> <span class="trash-row__icon">${TYPE_ICONS[entry.type] ?? ''}</span>
<div class="trash-row__info"> <div class="trash-row__info">
<span class="trash-row__title">${escapeHtml(entry.title)}</span> <span class="trash-row__title">${escapeHtml(entry.title)}</span>
<span class="trash-row__meta">trashed ${relativeTime(entry.trashed_at ?? 0)}</span> <span class="trash-row__meta">trashed ${relativeTime(entry.trashed_at ?? 0)}</span>

View File

@@ -4,7 +4,7 @@
import { getState, setState, sendMessage, navigate, escapeHtml, popOutToTab } from '../../../shared/state'; import { getState, setState, sendMessage, navigate, escapeHtml, popOutToTab } from '../../../shared/state';
import { renderFormHeader } from '../form-header'; import { renderFormHeader } from '../form-header';
import { REQUIRED_PILL_HTML } from '../../../shared/glyphs'; import { REQUIRED_PILL_HTML, GLYPH_TYPE_DOCUMENT, GLYPH_PREVIEW } from '../../../shared/glyphs';
import type { Item, ItemId, ManifestEntry, Section, AttachmentRef } from '../../../shared/types'; import type { Item, ItemId, ManifestEntry, Section, AttachmentRef } from '../../../shared/types';
import { import {
renderSectionsEditor, wireSectionsEditor, renderSectionsEditor, wireSectionsEditor,
@@ -76,7 +76,7 @@ export function renderForm(app: HTMLElement, mode: 'add' | 'edit', existing: Ite
} }
return ` return `
<div class="document-primary-row" id="primary-picker"> <div class="document-primary-row" id="primary-picker">
<span class="document-primary-row__thumb">📄</span> <span class="document-primary-row__thumb">${GLYPH_TYPE_DOCUMENT}</span>
<span class="document-primary-row__name">${escapeHtml(primaryRef.filename)}</span> <span class="document-primary-row__name">${escapeHtml(primaryRef.filename)}</span>
<span class="document-primary-row__meta">${formatBytes(primaryRef.size)}</span> <span class="document-primary-row__meta">${formatBytes(primaryRef.size)}</span>
<span class="document-primary-row__action">↑ change</span> <span class="document-primary-row__action">↑ change</span>
@@ -283,13 +283,13 @@ export async function renderDetail(app: HTMLElement, item: Item): Promise<void>
<div class="detail-title" style="margin-bottom:12px;">${escapeHtml(item.title)}</div> <div class="detail-title" style="margin-bottom:12px;">${escapeHtml(item.title)}</div>
<div class="document-signature-block" id="doc-sigblock"> <div class="document-signature-block" id="doc-sigblock">
<div class="document-signature-block__thumb" data-att-id="${escapeHtml(primaryRef.id)}" data-mime="${escapeHtml(primaryRef.mime_type)}">📄</div> <div class="document-signature-block__thumb" data-att-id="${escapeHtml(primaryRef.id)}" data-mime="${escapeHtml(primaryRef.mime_type)}">${GLYPH_TYPE_DOCUMENT}</div>
<div class="document-signature-block__info"> <div class="document-signature-block__info">
<div class="document-signature-block__name">${escapeHtml(primaryRef.filename)}</div> <div class="document-signature-block__name">${escapeHtml(primaryRef.filename)}</div>
<div class="document-signature-block__meta">${formatBytes(primaryRef.size)} · ${new Date(primaryRef.created * 1000).toISOString().slice(0, 10)}</div> <div class="document-signature-block__meta">${formatBytes(primaryRef.size)} · ${new Date(primaryRef.created * 1000).toISOString().slice(0, 10)}</div>
<div class="document-signature-block__actions"> <div class="document-signature-block__actions">
<span id="doc-download" style="cursor:pointer;color:#d2ab43;">↓ download</span> <span id="doc-download" style="cursor:pointer;color:#d2ab43;">↓ download</span>
${isImageMime ? '<span id="doc-preview" style="cursor:pointer;color:#d2ab43;margin-left:10px;">🔍 preview</span>' : ''} ${isImageMime ? `<span id="doc-preview" style="cursor:pointer;color:#d2ab43;margin-left:10px;">${GLYPH_PREVIEW} preview</span>` : ''}
</div> </div>
</div> </div>
</div> </div>

View File

@@ -11,7 +11,7 @@ import { renderUnlock } from './components/unlock';
import { renderItemList } from './components/item-list'; import { renderItemList } from './components/item-list';
import { renderItemDetail } from './components/item-detail'; import { renderItemDetail } from './components/item-detail';
import { renderItemForm } from './components/item-form'; import { renderItemForm } from './components/item-form';
import { renderSettings } from './components/settings'; import { renderSettings, teardownSettings } from './components/settings';
import { renderVaultSettings } from './components/settings-vault'; import { renderVaultSettings } from './components/settings-vault';
import { renderTrash } from './components/trash'; import { renderTrash } from './components/trash';
import { renderDevices } from './components/devices'; import { renderDevices } from './components/devices';
@@ -178,6 +178,7 @@ function render(): void {
teardownTrash(); teardownTrash();
teardownDevices(); teardownDevices();
teardownFieldHistory(); teardownFieldHistory();
teardownSettings();
switch (currentState.view) { switch (currentState.view) {
case 'locked': case 'locked':

View File

@@ -1608,3 +1608,183 @@ textarea {
margin-top: 8px; margin-top: 8px;
background: var(--bg-input); background: var(--bg-input);
} }
.empty-state {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 40px 20px;
text-align: center;
}
.empty-state__icon {
font-size: 28px;
color: var(--text-muted, #8b949e);
margin-bottom: 12px;
display: block;
}
.empty-state__title {
font-size: 13px;
font-weight: 600;
margin-bottom: 4px;
}
.empty-state__hint {
font-size: 11px;
color: var(--text-muted, #8b949e);
}
.type-card-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-bottom: 12px;
}
.type-card {
display: flex;
flex-direction: column;
align-items: flex-start;
padding: 10px 12px;
background: var(--bg-elevated, #161b22);
border: 1px solid var(--border-mid, #30363d);
border-radius: 6px;
cursor: pointer;
text-align: left;
transition: border-color 0.15s;
}
.type-card:hover { border-color: var(--gold-base, #a88a4a); }
.type-card__icon { font-size: 20px; margin-bottom: 4px; }
.type-card__label { font-size: 12px; font-weight: 600; }
/* Toast notifications */
.relicario-toast-container {
position: fixed;
bottom: 16px;
left: 50%;
transform: translateX(-50%);
display: flex;
flex-direction: column;
gap: 6px;
pointer-events: none;
z-index: 9999;
}
.vault-shell .relicario-toast-container {
left: auto;
right: 24px;
transform: none;
}
.relicario-toast {
padding: 8px 16px;
border-radius: 6px;
font-size: 12px;
opacity: 0;
transform: translateY(8px);
transition: opacity 0.2s, transform 0.2s;
pointer-events: none;
}
.relicario-toast--visible {
opacity: 1;
transform: translateY(0);
}
.relicario-toast--success { background: #1f4a24; color: #aff0b5; border: 1px solid #238636; }
.relicario-toast--error { background: #4a1f1f; color: #f0afaf; border: 1px solid #ab2b20; }
.relicario-toast--info { background: #1f2d4a; color: #afc8f0; border: 1px solid #1f6feb; }
.type-card__desc { font-size: 10px; color: var(--text-muted, #8b949e); margin-top: 2px; }
/* === Settings layout === */
.settings-layout {
display: flex;
height: 100%;
overflow: hidden;
}
.settings-nav {
width: 148px;
min-width: 148px;
border-right: 1px solid var(--border, #30363d);
padding: 12px 0;
overflow-y: auto;
flex-shrink: 0;
}
.settings-nav__group-label {
font-size: 10px;
text-transform: uppercase;
letter-spacing: 0.06em;
color: var(--text-muted, #8b949e);
padding: 8px 12px 4px;
}
.settings-nav__item {
display: flex;
align-items: center;
gap: 8px;
width: 100%;
padding: 7px 12px;
background: transparent;
border: none;
cursor: pointer;
font-size: 13px;
color: inherit;
text-align: left;
}
.settings-nav__item:hover { background: var(--bg-hover, #161b22); }
.settings-nav__item--active { background: var(--bg-selected, #1c2d41); }
.settings-nav__icon { font-size: 14px; flex-shrink: 0; }
.settings-content {
flex: 1;
overflow-y: auto;
padding: 20px 24px;
min-width: 0;
}
.setting-row {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
padding: 12px 0;
border-bottom: 1px solid var(--border-subtle, #21262d);
}
.setting-row:last-child { border-bottom: none; }
.setting-row__info { flex: 1; }
.setting-row__title { font-size: 13px; font-weight: 500; }
.setting-row__desc { font-size: 11px; color: var(--text-muted, #8b949e); margin-top: 2px; }
.setting-row__control { flex-shrink: 0; }
.settings-section-title {
font-size: 12px;
text-transform: uppercase;
letter-spacing: 0.05em;
color: var(--text-muted, #8b949e);
margin: 0 0 12px;
padding-bottom: 6px;
border-bottom: 1px solid var(--border, #30363d);
}
.setting-card {
padding: 12px 16px;
border-radius: 6px;
border: 1px solid var(--border, #30363d);
margin-bottom: 12px;
}
.setting-card--ok { border-color: var(--success, #238636); background: rgba(35, 134, 54, 0.06); }
.setting-card--warn { border-color: var(--gold, #b8860b); background: rgba(184, 134, 11, 0.06); }
.setting-card__status { font-size: 13px; margin-bottom: 8px; }
.setting-card__actions { display: flex; gap: 8px; }

View File

@@ -41,3 +41,30 @@ describe('glyph constants', () => {
expect(GLYPH_NEXT).toBe('▸'); expect(GLYPH_NEXT).toBe('▸');
}); });
}); });
describe('Stream A glyphs (vault tab + type icons)', () => {
it('exports GLYPH_VAULT_TAB as U+29C9', () => {
expect(glyphs.GLYPH_VAULT_TAB).toBe('⧉');
});
it('exports per-type glyph constants', () => {
expect(glyphs.GLYPH_TYPE_LOGIN).toBe('◉');
expect(glyphs.GLYPH_TYPE_SECURE_NOTE).toBe('◫');
expect(glyphs.GLYPH_TYPE_TOTP).toBe('⊡');
expect(glyphs.GLYPH_TYPE_CARD).toBe('▭');
expect(glyphs.GLYPH_TYPE_IDENTITY).toBe('◍');
expect(glyphs.GLYPH_TYPE_KEY).toBe('⊹');
expect(glyphs.GLYPH_TYPE_DOCUMENT).toBe('≡');
});
it('per-type glyphs are single codepoints (no emoji)', () => {
const typeGlyphs = [
glyphs.GLYPH_TYPE_LOGIN, glyphs.GLYPH_TYPE_SECURE_NOTE, glyphs.GLYPH_TYPE_TOTP,
glyphs.GLYPH_TYPE_CARD, glyphs.GLYPH_TYPE_IDENTITY, glyphs.GLYPH_TYPE_KEY,
glyphs.GLYPH_TYPE_DOCUMENT,
];
for (const g of typeGlyphs) {
expect([...g].length).toBe(1);
}
});
});

View File

@@ -17,6 +17,19 @@ export const GLYPH_DEVICES = '⌬'; // sidebar devices nav
export const GLYPH_SETTINGS = '⚙'; // sidebar settings nav export const GLYPH_SETTINGS = '⚙'; // sidebar settings nav
export const GLYPH_LOCK = '⏻'; // sidebar lock nav export const GLYPH_LOCK = '⏻'; // sidebar lock nav
export const GLYPH_NEXT = '▸'; // forward / next button (matches ▾/▸ disclosure family) export const GLYPH_NEXT = '▸'; // forward / next button (matches ▾/▸ disclosure family)
export const GLYPH_COPY = '⎘'; // copy to clipboard
export const GLYPH_SYNC = '⇅'; // sync / upload
export const GLYPH_PREVIEW = '⊕'; // preview / expand
export const GLYPH_VAULT_TAB = '⧉'; // U+29C9 pop-out to fullscreen vault tab
export const GLYPH_TYPE_LOGIN = '◉'; // login
export const GLYPH_TYPE_SECURE_NOTE = '◫'; // secure note
export const GLYPH_TYPE_TOTP = '⊡'; // totp / 2FA
export const GLYPH_TYPE_CARD = '▭'; // card
export const GLYPH_TYPE_IDENTITY = '◍'; // identity (distinct from GLYPH_DEVICES ⌬)
export const GLYPH_TYPE_KEY = '⊹'; // SSH / API key
export const GLYPH_TYPE_DOCUMENT = '≡'; // document
/// Inline HTML snippet for the required-field pill. Use after a label's text: /// Inline HTML snippet for the required-field pill. Use after a label's text:
/// `<label class="label" for="f-title">title ${REQUIRED_PILL_HTML}</label>` /// `<label class="label" for="f-title">title ${REQUIRED_PILL_HTML}</label>`

View File

@@ -0,0 +1,26 @@
export function showToast(
message: string,
type: 'success' | 'error' | 'info' = 'info',
durationMs = 2500,
): void {
let container = document.querySelector<HTMLElement>('.relicario-toast-container');
if (!container) {
container = document.createElement('div');
container.className = 'relicario-toast-container';
document.body.appendChild(container);
}
const toast = document.createElement('div');
toast.className = `relicario-toast relicario-toast--${type}`;
toast.textContent = message;
container.appendChild(toast);
requestAnimationFrame(() => {
requestAnimationFrame(() => toast.classList.add('relicario-toast--visible'));
});
setTimeout(() => {
toast.classList.remove('relicario-toast--visible');
toast.addEventListener('transitionend', () => toast.remove(), { once: true });
}, durationMs);
}

View File

@@ -438,6 +438,14 @@ textarea {
margin-top: 16px; margin-top: 16px;
} }
/* When the sticky save bar (fullscreen) provides external actions,
the form's inner action row sets the [hidden] attribute. The default
user-agent rule for [hidden] is display:none, but our .form-actions
display:flex above wins specificity. Re-assert hidden takes priority. */
.form-actions[hidden] {
display: none !important;
}
.inline-row { .inline-row {
display: flex; display: flex;
gap: 8px; gap: 8px;
@@ -626,16 +634,18 @@ textarea {
.gen-trigger { .gen-trigger {
background: #7c5719; background: #7c5719;
color: #fff3cf; color: #fff3cf;
border: none; border: 1px solid #7c5719;
border-radius: 4px; border-radius: 3px;
padding: 0 12px; padding: 0 8px;
font-size: 16px; font-size: 14px;
cursor: pointer; cursor: pointer;
line-height: 1; line-height: 1;
min-width: 38px; min-width: 28px;
height: 28px;
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
vertical-align: middle;
} }
.gen-trigger:hover { background: #aa812a; } .gen-trigger:hover { background: #aa812a; }
.gen-trigger[aria-expanded="true"] { background: #aa812a; } .gen-trigger[aria-expanded="true"] { background: #aa812a; }
@@ -1291,8 +1301,8 @@ textarea {
gap: 8px; gap: 8px;
} }
.vault-sidebar__header .brand-logo { .vault-sidebar__header .brand-logo {
width: 20px; width: 36px;
height: 20px; height: 36px;
margin: 0; margin: 0;
display: block; display: block;
flex-shrink: 0; flex-shrink: 0;
@@ -1396,6 +1406,392 @@ textarea {
color: #484f58; color: #484f58;
} }
/* === 3-column shell === */
.vault-shell {
display: flex;
height: 100vh;
overflow: hidden;
background: var(--bg-page, #0d1117);
position: relative;
}
.vault-sidebar {
width: 200px;
min-width: 200px;
display: flex;
flex-direction: column;
border-right: 1px solid var(--border, #30363d);
background: var(--bg-page);
overflow-y: auto;
flex-shrink: 0;
position: relative;
z-index: 5;
}
.vault-list-pane {
flex: 1;
display: flex;
flex-direction: column;
overflow-y: auto;
min-width: 0;
}
/* Pane occupies the same flex slot as list-pane for non-list views */
.vault-pane {
flex: 1;
display: flex;
flex-direction: column;
overflow-y: auto;
min-width: 0;
padding: 24px 32px;
}
.vault-pane--empty {
align-items: center;
justify-content: center;
color: var(--text-dim);
font-size: 14px;
}
/* View-specific visibility: only one of list-pane / vault-pane is visible.
Default to list view if neither class is set. */
.vault-shell .vault-pane { display: none; }
.vault-shell--pane .vault-list-pane { display: none; }
.vault-shell--pane .vault-pane { display: flex; }
.vault-shell--pane .vault-drawer { display: none; }
.vault-drawer {
width: 440px;
min-width: 440px;
max-width: 440px;
border-left: 1px solid var(--border, #30363d);
background: var(--bg-elevated, #161b22);
overflow-y: auto;
transform: translateX(100%);
transition: transform 0.2s ease;
flex-shrink: 0;
}
.vault-drawer--open {
transform: translateX(0);
}
/* Empty state — centered, gold-accented icon, polished */
.empty-state {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 10px;
padding: 48px 24px;
text-align: center;
min-height: 240px;
}
.empty-state__icon {
display: inline-flex;
align-items: center;
justify-content: center;
width: 72px;
height: 72px;
border-radius: 50%;
background: var(--gold-soft);
border: 1px solid var(--gold-ring);
color: var(--gold-text);
font-size: 30px;
line-height: 1;
margin-bottom: 4px;
}
.empty-state__title {
font-size: 14px;
font-weight: 600;
color: var(--text);
letter-spacing: 0.02em;
}
.empty-state__hint {
font-size: 12px;
color: var(--text-muted);
max-width: 320px;
}
.vault-list-row {
display: flex;
align-items: center;
gap: 10px;
padding: 10px 16px;
cursor: pointer;
border-bottom: 1px solid var(--border-subtle, #21262d);
transition: background 0.1s;
}
.vault-list-row:hover { background: var(--bg-hover, #161b22); }
.vault-list-row--selected {
background: var(--bg-selected, #1c2d41);
border-left: 2px solid var(--gold, #b8860b);
}
.vault-list-row__icon {
width: 32px;
height: 32px;
display: flex;
align-items: center;
justify-content: center;
background: var(--bg-elevated, #161b22);
border-radius: 6px;
border: 1px solid var(--border, #30363d);
font-size: 14px;
flex-shrink: 0;
}
.vault-list-row--selected .vault-list-row__icon { border-color: var(--gold, #b8860b); }
.vault-list-row__text { flex: 1; min-width: 0; }
.vault-list-row__title {
font-size: 13px;
font-weight: 500;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.vault-list-row__subtitle {
font-size: 11px;
color: var(--text-muted, #8b949e);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
margin-top: 1px;
}
.vault-list-row__age {
font-size: 10px;
color: var(--text-dim, #6e7681);
flex-shrink: 0;
}
/* Type picker — secondary panel that slides out from behind the left sidebar */
.vault-type-panel-scrim {
position: absolute;
inset: 0 0 0 200px;
background: rgba(0, 0, 0, 0.45);
opacity: 0;
pointer-events: none;
transition: opacity 0.2s ease;
z-index: 3;
}
.vault-type-panel-scrim--visible {
opacity: 1;
pointer-events: auto;
}
.vault-type-panel {
position: absolute;
top: 0;
bottom: 0;
left: 200px;
width: 280px;
background: var(--bg-elevated);
border-right: 1px solid var(--border-mid);
transform: translateX(-100%);
transition: transform 0.22s ease;
z-index: 4;
overflow-y: auto;
padding: 14px 12px;
box-shadow: 8px 0 24px rgba(0, 0, 0, 0.45);
}
.vault-type-panel--open { transform: translateX(0); }
.vault-type-panel__head {
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 4px 10px;
margin-bottom: 8px;
border-bottom: 1px solid var(--border-soft);
}
.vault-type-panel__title {
font-size: 12px;
font-weight: 600;
color: var(--gold-text);
text-transform: uppercase;
letter-spacing: 0.08em;
}
.vault-type-panel__close {
background: transparent;
border: none;
color: var(--text-muted);
cursor: pointer;
font-size: 14px;
padding: 2px 6px;
border-radius: 3px;
}
.vault-type-panel__close:hover { color: var(--text); background: var(--bg-pane); }
.vault-type-panel__hint {
font-size: 11px;
color: var(--text-dim);
padding: 0 4px 8px;
}
.vault-type-list {
display: flex;
flex-direction: column;
gap: 2px;
}
.vault-type-item {
display: flex;
align-items: center;
gap: 12px;
padding: 9px 10px;
background: transparent;
border: 1px solid transparent;
border-radius: 5px;
cursor: pointer;
text-align: left;
color: var(--text);
font: inherit;
font-size: 13px;
transition: background 0.1s, border-color 0.1s;
}
.vault-type-item:hover {
background: var(--bg-pane);
border-color: var(--border-mid);
}
.vault-type-item:focus-visible {
outline: none;
border-color: var(--gold-base);
background: var(--gold-soft);
}
.vault-type-item__icon {
display: inline-flex;
align-items: center;
justify-content: center;
width: 28px;
height: 28px;
flex-shrink: 0;
background: var(--gold-soft);
border: 1px solid var(--gold-ring);
border-radius: 5px;
font-size: 15px;
color: var(--gold-text);
}
.vault-type-item__name {
flex: 1;
color: var(--text);
}
/* Sidebar nav button — primary new-item variant */
.vault-sidebar__nav-item--primary {
color: var(--gold-text);
font-weight: 600;
}
.vault-sidebar__nav-item--primary:hover {
background: var(--gold-soft);
color: var(--gold-hi-end);
}
/* Drawer header and body */
.vault-drawer__header {
display: flex;
align-items: center;
padding: 12px 16px;
border-bottom: 1px solid var(--border, #30363d);
gap: 8px;
}
.vault-drawer__type-pill {
font-size: 10px;
text-transform: uppercase;
letter-spacing: 0.05em;
padding: 2px 8px;
background: var(--bg-page, #0d1117);
border: 1px solid var(--border, #30363d);
border-radius: 4px;
color: var(--text-muted, #8b949e);
}
.vault-drawer__actions { display: flex; gap: 6px; margin-left: auto; }
.vault-drawer__close {
background: transparent;
border: none;
cursor: pointer;
font-size: 16px;
color: var(--text-muted, #8b949e);
padding: 4px 6px;
}
.vault-drawer__body { padding: 20px 20px 16px; }
.vault-drawer__title { font-size: 18px; font-weight: 700; margin-bottom: 4px; }
.vault-drawer__subtitle { font-size: 12px; color: var(--text-muted, #8b949e); margin-bottom: 16px; }
.vault-drawer__field-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 12px;
}
.vault-drawer__field-grid > .vault-drawer__field--full { grid-column: 1 / -1; }
.vault-drawer__field-label {
font-size: 10px;
text-transform: uppercase;
letter-spacing: 0.04em;
color: var(--text-muted, #8b949e);
margin-bottom: 2px;
}
.vault-drawer__field-value {
font-size: 13px;
word-break: break-all;
}
/* Category nav */
.vault-category-row {
display: flex;
align-items: center;
gap: 8px;
width: 100%;
padding: 6px 12px;
background: transparent;
border: none;
cursor: pointer;
color: inherit;
font-size: 13px;
text-align: left;
}
.vault-category-row:hover { background: var(--bg-hover, #161b22); }
.vault-category-row--active { background: var(--bg-selected, #1c2d41); }
.vault-category-row__icon { font-size: 14px; flex-shrink: 0; }
.vault-category-row__label { flex: 1; }
.vault-category-row__count { font-size: 11px; color: var(--text-muted, #8b949e); }
/* === Responsive === */
@media (max-width: 960px) {
.vault-drawer {
position: absolute;
right: 0;
top: 0;
height: 100%;
}
}
@media (max-width: 720px) {
.vault-sidebar {
width: 48px;
min-width: 48px;
}
.vault-sidebar__category-label,
.vault-sidebar__category-count,
.vault-sidebar__nav-label {
display: none;
}
.vault-sidebar__nav-item { justify-content: center; padding: 10px 0; }
}
/* --- Lock screen (vault tab) --- */ /* --- Lock screen (vault tab) --- */
.vault-lock-screen { .vault-lock-screen {
@@ -1627,7 +2023,7 @@ textarea {
display: grid; display: grid;
grid-template-columns: 1fr 1fr; grid-template-columns: 1fr 1fr;
gap: 24px; gap: 24px;
max-width: 960px; max-width: 1100px;
margin: 0 auto; margin: 0 auto;
} }
@media (max-width: 720px) { @media (max-width: 720px) {
@@ -1637,7 +2033,7 @@ textarea {
/* P3: lower form sections constrained to the same envelope as .form-grid. /* P3: lower form sections constrained to the same envelope as .form-grid.
Gated on surface === 'fullscreen' in login.ts; popup unaffected. */ Gated on surface === 'fullscreen' in login.ts; popup unaffected. */
.form-lower { .form-lower {
max-width: 960px; max-width: 1100px;
margin: 0 auto; margin: 0 auto;
} }
.form-lower > .form-group, .form-lower > .form-group,
@@ -1690,6 +2086,9 @@ textarea {
flex-direction: column; flex-direction: column;
height: 100%; height: 100%;
overflow: hidden; overflow: hidden;
width: 100%;
max-width: 1280px;
margin: 0 auto;
} }
.form-scroll { .form-scroll {
flex: 1; flex: 1;
@@ -1719,3 +2118,41 @@ textarea {
background: linear-gradient(to top, rgba(17, 22, 30, 0.7), transparent); background: linear-gradient(to top, rgba(17, 22, 30, 0.7), transparent);
pointer-events: none; pointer-events: none;
} }
/* Toast notifications */
.relicario-toast-container {
position: fixed;
bottom: 16px;
left: 50%;
transform: translateX(-50%);
display: flex;
flex-direction: column;
gap: 6px;
pointer-events: none;
z-index: 9999;
}
.vault-shell .relicario-toast-container {
left: auto;
right: 24px;
transform: none;
}
.relicario-toast {
padding: 8px 16px;
border-radius: 6px;
font-size: 12px;
opacity: 0;
transform: translateY(8px);
transition: opacity 0.2s, transform 0.2s;
pointer-events: none;
}
.relicario-toast--visible {
opacity: 1;
transform: translateY(0);
}
.relicario-toast--success { background: #1f4a24; color: #aff0b5; border: 1px solid #238636; }
.relicario-toast--error { background: #4a1f1f; color: #f0afaf; border: 1px solid #ab2b20; }
.relicario-toast--info { background: #1f2d4a; color: #afc8f0; border: 1px solid #1f6feb; }

View File

@@ -10,18 +10,36 @@ import type {
} from '../shared/types'; } from '../shared/types';
import { registerHost } from '../shared/state'; import { registerHost } from '../shared/state';
import { lookupErrorCopy, type ErrorCta } from '../shared/error-copy'; import { lookupErrorCopy, type ErrorCta } from '../shared/error-copy';
import { GLYPH_TRASH, GLYPH_DEVICES, GLYPH_SETTINGS, GLYPH_LOCK } from '../shared/glyphs'; import {
GLYPH_TRASH, GLYPH_DEVICES, GLYPH_SETTINGS, GLYPH_LOCK,
GLYPH_TYPE_LOGIN, GLYPH_TYPE_SECURE_NOTE, GLYPH_TYPE_TOTP,
GLYPH_TYPE_CARD, GLYPH_TYPE_IDENTITY, GLYPH_TYPE_KEY, GLYPH_TYPE_DOCUMENT,
} from '../shared/glyphs';
import { renderItemDetail } from '../popup/components/item-detail'; import { renderItemDetail } from '../popup/components/item-detail';
import { renderItemForm } from '../popup/components/item-form'; import { renderItemForm } from '../popup/components/item-form';
import { renderTrash, teardown as teardownTrash } from '../popup/components/trash'; import { renderTrash, teardown as teardownTrash } from '../popup/components/trash';
import { renderDevices, teardown as teardownDevices } from '../popup/components/devices'; import { renderDevices, teardown as teardownDevices } from '../popup/components/devices';
import { renderSettings } from '../popup/components/settings'; import { renderSettings, teardownSettings } from '../popup/components/settings';
import { renderVaultSettings as renderVaultSettingsView } from '../popup/components/settings-vault'; import { renderVaultSettings as renderVaultSettingsView } from '../popup/components/settings-vault';
import { renderFieldHistory, teardown as teardownFieldHistory } from '../popup/components/field-history'; import { renderFieldHistory, teardown as teardownFieldHistory } from '../popup/components/field-history';
import { renderBackupPanel, teardown as teardownBackup } from './components/backup-panel'; import { renderBackupPanel, teardown as teardownBackup } from './components/backup-panel';
import { renderImportPanel, teardown as teardownImport } from './components/import-panel'; import { renderImportPanel, teardown as teardownImport } from './components/import-panel';
import { applyColorScheme } from '../shared/color-scheme'; import { applyColorScheme } from '../shared/color-scheme';
// ---------------------------------------------------------------------------
// Type picker (right side panel)
// ---------------------------------------------------------------------------
const PICKER_TYPES: Array<{ type: ItemType; label: string }> = [
{ type: 'login', label: 'Login' },
{ type: 'secure_note', label: 'Secure Note' },
{ type: 'totp', label: 'TOTP' },
{ type: 'card', label: 'Card' },
{ type: 'identity', label: 'Identity' },
{ type: 'key', label: 'SSH / API Key' },
{ type: 'document', label: 'Document' },
];
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// Helpers // Helpers
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@@ -29,6 +47,27 @@ import { applyColorScheme } from '../shared/color-scheme';
function sendMessage(request: Request): Promise<Response> { function sendMessage(request: Request): Promise<Response> {
return new Promise((resolve) => { return new Promise((resolve) => {
chrome.runtime.sendMessage(request, (response: Response) => { chrome.runtime.sendMessage(request, (response: Response) => {
// MV3 service workers are evicted after ~30s idle, which wipes the
// in-memory session/manifest/gitHost. The fullscreen tab stays open
// and has no signal that the SW restarted — the next RPC just comes
// back `vault_locked`. Treat that as "session lost" and force the
// lock screen so the user can re-enter their passphrase. Skip for
// is_unlocked / unlock themselves to avoid loops on cold start.
if (
response &&
!response.ok &&
response.error === 'vault_locked' &&
request.type !== 'is_unlocked' &&
request.type !== 'unlock' &&
state.unlocked
) {
state.unlocked = false;
state.selectedId = null;
state.selectedItem = null;
state.entries = [];
state.error = 'Session expired — please unlock again.';
render();
}
resolve(response); resolve(response);
}); });
}); });
@@ -60,26 +99,35 @@ function renderErrorBlock(code: string | null | undefined): string {
function typeIcon(t: ItemType): string { function typeIcon(t: ItemType): string {
switch (t) { switch (t) {
case 'login': return '\u{1F511}'; // key case 'login': return GLYPH_TYPE_LOGIN;
case 'secure_note': return '\u{1F4DD}'; // memo case 'secure_note': return GLYPH_TYPE_SECURE_NOTE;
case 'identity': return '\u{1FAAA}'; // id card case 'identity': return GLYPH_TYPE_IDENTITY;
case 'card': return '\u{1F4B3}'; // credit card case 'card': return GLYPH_TYPE_CARD;
case 'key': return '\u{1F5DD}'; // old key case 'key': return GLYPH_TYPE_KEY;
case 'document': return '\u{1F4C4}'; // page facing up case 'document': return GLYPH_TYPE_DOCUMENT;
case 'totp': return '⏱'; // stopwatch case 'totp': return GLYPH_TYPE_TOTP;
} }
} }
function typeLabel(t: ItemType): string { function typeLabel(t: ItemType): string {
switch (t) { const labels: Record<ItemType, string> = {
case 'login': return 'Logins'; login: 'Login',
case 'secure_note': return 'Secure Notes'; secure_note: 'Secure Note',
case 'identity': return 'Identities'; identity: 'Identity',
case 'card': return 'Cards'; card: 'Card',
case 'key': return 'Keys'; key: 'SSH / API Key',
case 'document': return 'Documents'; document: 'Document',
case 'totp': return 'TOTP'; totp: 'TOTP',
};
return labels[t];
} }
function relativeTime(unixSec: number): string {
const diffS = Math.floor(Date.now() / 1000) - unixSec;
if (diffS < 60) return 'just now';
if (diffS < 3600) return `${Math.floor(diffS / 60)}m ago`;
if (diffS < 86400) return `${Math.floor(diffS / 3600)}h ago`;
return `${Math.floor(diffS / 86400)}d ago`;
} }
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@@ -138,6 +186,8 @@ interface VaultState {
selectedIndex: number; selectedIndex: number;
searchQuery: string; searchQuery: string;
activeGroup: string | null; activeGroup: string | null;
drawerOpen: boolean;
typePanelOpen: boolean;
vaultSettings: VaultSettings | null; vaultSettings: VaultSettings | null;
generatorDefaults: GeneratorRequest | null; generatorDefaults: GeneratorRequest | null;
error: string | null; error: string | null;
@@ -157,6 +207,8 @@ const state: VaultState = {
selectedIndex: 0, selectedIndex: 0,
searchQuery: '', searchQuery: '',
activeGroup: null, activeGroup: null,
drawerOpen: false,
typePanelOpen: false,
vaultSettings: null, vaultSettings: null,
generatorDefaults: null, generatorDefaults: null,
error: null, error: null,
@@ -180,7 +232,9 @@ registerHost({
navigate: (view: string, extras?: any) => { navigate: (view: string, extras?: any) => {
Object.assign(state, { view, error: null, loading: false, ...extras }); Object.assign(state, { view, error: null, loading: false, ...extras });
setHash(view as VaultView); setHash(view as VaultView);
renderSidebarList(); applyShellViewClass();
renderSidebarCategories();
if (state.view === 'list') renderListPane();
renderPane(); renderPane();
}, },
sendMessage, sendMessage,
@@ -249,40 +303,254 @@ function renderLockScreen(app: HTMLElement): void {
} }
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// Shell (sidebar + pane) // Shell (3-column: sidebar + list pane + drawer)
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
function renderShell(app: HTMLElement): void { function renderShell(app: HTMLElement): void {
// Only create the shell structure if it's not present yet if (!app.querySelector('.vault-shell')) {
if (!app.querySelector('.vault-sidebar')) {
app.innerHTML = ` app.innerHTML = `
<div class="vault-shell">
<div class="vault-sidebar"> <div class="vault-sidebar">
<div class="vault-sidebar__header"> <div class="vault-sidebar__header">
<img class="brand-logo" src="icons/relicario-logo-16.svg" alt=""> <img class="brand-logo" src="icons/relicario-logo.svg" alt="">
<span class="brand">Relicario</span> <span class="brand">Relicario</span>
</div> </div>
<div class="vault-sidebar__search"> <div class="vault-sidebar__search">
<input type="text" id="vault-search" placeholder="/ search..." /> <input type="text" id="vault-search" placeholder="/ search" />
</div> </div>
<div class="vault-sidebar__list" id="vault-sidebar-list"></div> <nav class="vault-sidebar__categories" id="vault-categories" aria-label="Item types"></nav>
<div class="vault-sidebar__nav"> <div class="vault-sidebar__nav">
<button class="vault-sidebar__nav-item" data-nav="add">+ new item</button> <button class="vault-sidebar__nav-item vault-sidebar__nav-item--primary" data-nav="add" title="New item">+ new item</button>
<button class="vault-sidebar__nav-item" data-nav="trash">${GLYPH_TRASH} trash</button> <button class="vault-sidebar__nav-item" data-nav="trash" title="Trash">${GLYPH_TRASH} <span class="vault-sidebar__nav-label">trash</span></button>
<button class="vault-sidebar__nav-item" data-nav="devices">${GLYPH_DEVICES} devices</button> <button class="vault-sidebar__nav-item" data-nav="devices" title="Devices">${GLYPH_DEVICES} <span class="vault-sidebar__nav-label">devices</span></button>
<button class="vault-sidebar__nav-item" data-nav="settings">${GLYPH_SETTINGS} settings</button> <button class="vault-sidebar__nav-item" data-nav="settings" title="Settings">${GLYPH_SETTINGS} <span class="vault-sidebar__nav-label">settings</span></button>
<button class="vault-sidebar__nav-item" data-nav="lock">${GLYPH_LOCK} lock</button> <button class="vault-sidebar__nav-item" data-nav="lock" title="Lock">${GLYPH_LOCK} <span class="vault-sidebar__nav-label">lock</span></button>
</div> </div>
</div> </div>
<div class="vault-pane vault-pane--empty" id="vault-pane"> <div class="vault-list-pane" id="vault-list-pane"></div>
select an item <div class="vault-pane" id="vault-pane"></div>
<div class="vault-drawer" id="vault-drawer"></div>
<div class="vault-type-panel-scrim" id="vault-type-scrim"></div>
<aside class="vault-type-panel" id="vault-type-panel" aria-label="Choose item type"></aside>
</div> </div>
`; `;
wireSidebar(); wireSidebar();
wireTypePanel();
} }
renderSidebarList(); applyShellViewClass();
renderSidebarCategories();
if (state.view === 'list') {
renderListPane();
if (state.drawerOpen && state.selectedItem) {
renderDrawer(state.selectedItem);
}
} else {
renderPane(); renderPane();
} }
}
// Toggle which middle column is visible based on the current view.
// list view → list-pane (+ optional drawer); other views → vault-pane.
function applyShellViewClass(): void {
const shell = document.querySelector('.vault-shell');
if (!shell) return;
shell.classList.toggle('vault-shell--list', state.view === 'list');
shell.classList.toggle('vault-shell--pane', state.view !== 'list');
}
// ---------------------------------------------------------------------------
// Right-side type picker panel
// ---------------------------------------------------------------------------
function wireTypePanel(): void {
document.getElementById('vault-type-scrim')?.addEventListener('click', closeTypePanel);
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && state.typePanelOpen) closeTypePanel();
});
}
function openTypePanel(): void {
const panel = document.getElementById('vault-type-panel');
const scrim = document.getElementById('vault-type-scrim');
if (!panel || !scrim) return;
panel.innerHTML = `
<div class="vault-type-panel__head">
<div class="vault-type-panel__title">New item</div>
<button class="vault-type-panel__close" id="vault-type-close" title="Close (Esc)" aria-label="Close">✕</button>
</div>
<div class="vault-type-panel__hint">Choose a type</div>
<div class="vault-type-list" role="menu">
${PICKER_TYPES.map((t) => `
<button class="vault-type-item" data-type="${t.type}" role="menuitem">
<span class="vault-type-item__icon" aria-hidden="true">${typeIcon(t.type)}</span>
<span class="vault-type-item__name">${escapeHtml(t.label)}</span>
</button>
`).join('')}
</div>
`;
panel.classList.add('vault-type-panel--open');
scrim.classList.add('vault-type-panel-scrim--visible');
state.typePanelOpen = true;
panel.querySelector('#vault-type-close')?.addEventListener('click', closeTypePanel);
panel.querySelectorAll<HTMLButtonElement>('[data-type]').forEach((btn) => {
btn.addEventListener('click', () => {
const type = btn.dataset.type as ItemType;
closeTypePanel();
// Use the host's navigate hook so view + hash + visibility all update
// together. This was the bug: bare setHash + renderPane left the
// shell stuck in list view with #vault-pane hidden.
state.newType = type;
state.selectedId = null;
state.selectedItem = null;
state.drawerOpen = false;
state.view = 'add';
setHash('add', type);
applyShellViewClass();
renderSidebarCategories();
renderPane();
});
});
// Focus first item for keyboard users
(panel.querySelector('.vault-type-item') as HTMLElement | null)?.focus();
}
function closeTypePanel(): void {
document.getElementById('vault-type-panel')?.classList.remove('vault-type-panel--open');
document.getElementById('vault-type-scrim')?.classList.remove('vault-type-panel-scrim--visible');
state.typePanelOpen = false;
}
// ---------------------------------------------------------------------------
// Drawer (implemented in Task 10)
// ---------------------------------------------------------------------------
function openDrawer(): void {
document.getElementById('vault-drawer')?.classList.add('vault-drawer--open');
}
function closeDrawer(): void {
state.drawerOpen = false;
state.selectedId = null;
state.selectedItem = null;
document.getElementById('vault-drawer')?.classList.remove('vault-drawer--open');
}
function getDrawerCoreFields(item: Item): Array<[string, string, boolean]> {
const core = item.core as unknown as Record<string, unknown>;
if (!core) return [];
const fields: Array<[string, string, boolean]> = [];
switch (item.type) {
case 'login':
if ('username' in core) fields.push(['username', String(core.username ?? ''), false]);
if ('password' in core) fields.push(['password', '••••••••', false]);
if ('url' in core) fields.push(['url', String(core.url ?? ''), true]);
break;
case 'card': {
if ('number' in core) fields.push(['number', String(core.number ?? ''), false]);
if ('holder' in core) fields.push(['holder', String(core.holder ?? ''), false]);
if ('expiry' in core && core.expiry) {
const exp = core.expiry as { month: number; year: number };
fields.push(['expiry', `${String(exp.month).padStart(2, '0')}/${exp.year}`, false]);
}
if ('cvv' in core) fields.push(['cvv', '•••', false]);
if ('pin' in core) fields.push(['pin', '••••', false]);
break;
}
case 'identity':
if ('full_name' in core) fields.push(['full name', String(core.full_name ?? ''), true]);
if ('email' in core) fields.push(['email', String(core.email ?? ''), true]);
if ('phone' in core) fields.push(['phone', String(core.phone ?? ''), false]);
if ('address' in core) fields.push(['address', String(core.address ?? ''), true]);
if ('date_of_birth' in core) fields.push(['date of birth', String(core.date_of_birth ?? ''), false]);
break;
case 'key':
if ('label' in core) fields.push(['label', String(core.label ?? ''), true]);
if ('algorithm' in core) fields.push(['algorithm', String(core.algorithm ?? ''), false]);
if ('public_key' in core) fields.push(['public key', String(core.public_key ?? ''), true]);
break;
case 'secure_note':
if ('body' in core) fields.push(['body', String(core.body ?? ''), true]);
break;
case 'totp':
if ('issuer' in core) fields.push(['issuer', String(core.issuer ?? ''), false]);
if ('label' in core) fields.push(['label', String(core.label ?? ''), false]);
break;
case 'document':
if ('filename' in core) fields.push(['filename', String(core.filename ?? ''), true]);
if ('mime_type' in core) fields.push(['type', String(core.mime_type ?? ''), false]);
break;
}
if (item.notes) fields.push(['notes', item.notes, true]);
return fields;
}
function renderDrawer(item: Item): void {
const drawer = document.getElementById('vault-drawer');
if (!drawer) return;
const coreFields = getDrawerCoreFields(item);
drawer.innerHTML = `
<div class="vault-drawer__header">
<span class="vault-drawer__type-pill">${item.type.replace('_', ' ').toUpperCase()}</span>
<div class="vault-drawer__actions">
<button class="btn" id="drawer-edit-btn" style="font-size:11px;">edit</button>
<button class="vault-drawer__close" id="drawer-close-btn" title="Close (Esc)">✕</button>
</div>
</div>
<div class="vault-drawer__body">
<div class="vault-drawer__title">${escapeHtml(item.title)}</div>
${item.type === 'login' && (item.core as { url?: string }).url
? `<div class="vault-drawer__subtitle">${escapeHtml((item.core as { url?: string }).url ?? '')}</div>`
: ''}
<div class="vault-drawer__field-grid">
${coreFields.map(([label, value, full]) => `
<div class="vault-drawer__field${full ? ' vault-drawer__field--full' : ''}">
<div class="vault-drawer__field-label">${escapeHtml(label)}</div>
<div class="vault-drawer__field-value">${escapeHtml(value)}</div>
</div>
`).join('')}
</div>
</div>
`;
document.getElementById('drawer-close-btn')?.addEventListener('click', () => {
closeDrawer();
renderListPane();
});
document.getElementById('drawer-edit-btn')?.addEventListener('click', () => {
if (state.selectedId) {
setHash('edit', state.selectedId);
renderPane();
}
});
}
// ---------------------------------------------------------------------------
// Item selection (implemented in Task 10)
// ---------------------------------------------------------------------------
async function selectItemForDrawer(id: string): Promise<void> {
const resp = await sendMessage({ type: 'get_item', id });
if (!resp.ok) return;
const data = resp.data as { item: Item };
state.selectedId = id;
state.selectedItem = data.item;
state.drawerOpen = true;
renderSidebarCategories();
renderListPane();
renderDrawer(data.item);
openDrawer();
}
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// Sidebar wiring // Sidebar wiring
@@ -293,7 +561,8 @@ function wireSidebar(): void {
const searchInput = document.getElementById('vault-search') as HTMLInputElement | null; const searchInput = document.getElementById('vault-search') as HTMLInputElement | null;
searchInput?.addEventListener('input', () => { searchInput?.addEventListener('input', () => {
state.searchQuery = searchInput.value; state.searchQuery = searchInput.value;
renderSidebarList(); renderSidebarCategories();
renderListPane();
}); });
// Nav buttons // Nav buttons
@@ -313,26 +582,35 @@ function wireSidebar(): void {
state.selectedId = null; state.selectedId = null;
state.selectedItem = null; state.selectedItem = null;
state.newType = null; state.newType = null;
setHash('add'); state.drawerOpen = false;
renderPane(); closeDrawer();
openTypePanel();
return; return;
} }
if (nav === 'trash' || nav === 'devices' || nav === 'settings') { if (nav === 'trash' || nav === 'devices' || nav === 'settings') {
state.selectedId = null; state.selectedId = null;
state.selectedItem = null; state.selectedItem = null;
state.newType = null; state.newType = null;
state.drawerOpen = false;
state.view = nav;
setHash(nav); setHash(nav);
applyShellViewClass();
renderPane(); renderPane();
return; return;
} }
}); });
}); });
// Global "/" shortcut to focus search // Global "/" shortcut to focus search; Esc to close drawer
document.addEventListener('keydown', (e) => { document.addEventListener('keydown', (e) => {
if (e.key === '/' && !isEditableTarget(e.target)) { if (e.key === '/' && !isEditableTarget(e.target)) {
e.preventDefault(); e.preventDefault();
searchInput?.focus(); searchInput?.focus();
return;
}
if (e.key === 'Escape' && state.drawerOpen) {
closeDrawer();
renderListPane();
} }
}); });
} }
@@ -346,7 +624,7 @@ function isEditableTarget(target: EventTarget | null): boolean {
} }
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// Sidebar list // Sidebar category nav
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
function getFilteredEntries(): Array<[ItemId, ManifestEntry]> { function getFilteredEntries(): Array<[ItemId, ManifestEntry]> {
@@ -367,70 +645,100 @@ function getFilteredEntries(): Array<[ItemId, ManifestEntry]> {
return filtered; return filtered;
} }
function renderSidebarList(): void { function renderSidebarCategories(): void {
const container = document.getElementById('vault-sidebar-list'); const container = document.getElementById('vault-categories');
if (!container) return; if (!container) return;
const filtered = getFilteredEntries(); const filtered = getFilteredEntries();
// Group by type
const groups = new Map<ItemType, Array<[ItemId, ManifestEntry]>>();
for (const entry of filtered) {
const t = entry[1].type;
if (!groups.has(t)) groups.set(t, []);
groups.get(t)!.push(entry);
}
if (filtered.length === 0) {
container.innerHTML = '<div class="empty">no items</div>';
return;
}
let html = '';
// Stable type ordering
const typeOrder: ItemType[] = ['login', 'secure_note', 'identity', 'card', 'key', 'document', 'totp']; const typeOrder: ItemType[] = ['login', 'secure_note', 'identity', 'card', 'key', 'document', 'totp'];
for (const t of typeOrder) {
const items = groups.get(t); const allCount = filtered.length;
if (!items || items.length === 0) continue; const isAllActive = !state.activeGroup && state.view === 'list';
html += `<div class="vault-group-header">${typeIcon(t)} ${escapeHtml(typeLabel(t))}</div>`;
for (const [id, e] of items) { let html = `
const sel = id === state.selectedId ? ' selected' : ''; <button class="vault-category-row ${isAllActive ? 'vault-category-row--active' : ''}" data-group="">
const meta = e.icon_hint ? escapeHtml(e.icon_hint) : ''; <span class="vault-category-row__icon">◈</span>
html += ` <span class="vault-category-row__label vault-sidebar__category-label">All items</span>
<div class="vault-entry${sel}" data-id="${escapeHtml(id)}"> <span class="vault-category-row__count vault-sidebar__category-count">${allCount}</span>
<span class="vault-entry__title">${escapeHtml(e.title)}</span> </button>
${meta ? `<span class="vault-entry__meta">${meta}</span>` : ''} `;
</div>
for (const t of typeOrder) {
const count = filtered.filter(([, e]) => e.type === t).length;
// Always show Login (staple type); hide other types when empty.
if (count === 0 && t !== 'login') continue;
const isActive = state.activeGroup === t;
html += `
<button class="vault-category-row ${isActive ? 'vault-category-row--active' : ''}" data-group="${t}">
<span class="vault-category-row__icon">${typeIcon(t)}</span>
<span class="vault-category-row__label vault-sidebar__category-label">${typeLabel(t)}</span>
<span class="vault-category-row__count vault-sidebar__category-count">${count}</span>
</button>
`; `;
}
} }
container.innerHTML = html; container.innerHTML = html;
// Wire clicks container.querySelectorAll<HTMLButtonElement>('.vault-category-row').forEach((btn) => {
container.querySelectorAll('.vault-entry').forEach((el) => { btn.addEventListener('click', () => {
el.addEventListener('click', async () => { state.activeGroup = btn.dataset.group || null;
const id = (el as HTMLElement).dataset.id!; state.drawerOpen = false;
await selectItem(id); state.selectedId = null;
state.selectedItem = null;
state.view = 'list';
setHash('list');
applyShellViewClass();
renderSidebarCategories();
renderListPane();
closeDrawer();
}); });
}); });
} }
async function selectItem(id: ItemId): Promise<void> { // ---------------------------------------------------------------------------
state.loading = true; // List pane
const resp = await sendMessage({ type: 'get_item', id }); // ---------------------------------------------------------------------------
if (resp.ok) {
const data = resp.data as { item: Item }; function renderListPane(): void {
state.selectedId = id; const pane = document.getElementById('vault-list-pane');
state.selectedItem = data.item; if (!pane) return;
state.loading = false;
setHash('detail', id); const group = state.activeGroup as ItemType | null;
renderSidebarList(); let items = getFilteredEntries();
renderPane(); if (group) items = items.filter(([, e]) => e.type === group);
} else {
state.loading = false; if (items.length === 0) {
state.error = (resp as { error: string }).error; pane.innerHTML = `
<div class="empty-state">
<span class="empty-state__icon" aria-hidden="true">${state.searchQuery ? '⊘' : '◈'}</span>
<div class="empty-state__title">${state.searchQuery ? `No results for "${escapeHtml(state.searchQuery)}"` : 'No items yet'}</div>
<div class="empty-state__hint">${state.searchQuery ? 'Try a shorter search term.' : 'Click + new item to get started.'}</div>
</div>
`;
return;
} }
pane.innerHTML = items.map(([id, e]) => {
const sel = id === state.selectedId ? ' vault-list-row--selected' : '';
const subtitle = (e as any).icon_hint ?? (e.tags?.length > 0 ? e.tags.join(', ') : '');
const modifiedAgo = e.modified ? relativeTime(e.modified) : '';
return `
<div class="vault-list-row${sel}" data-id="${escapeHtml(id)}">
<div class="vault-list-row__icon" aria-hidden="true">${typeIcon(e.type)}</div>
<div class="vault-list-row__text">
<div class="vault-list-row__title">${escapeHtml(e.title)}</div>
${subtitle ? `<div class="vault-list-row__subtitle">${escapeHtml(subtitle)}</div>` : ''}
</div>
${modifiedAgo ? `<div class="vault-list-row__age">${escapeHtml(modifiedAgo)}</div>` : ''}
</div>
`;
}).join('');
pane.querySelectorAll<HTMLElement>('.vault-list-row').forEach((row) => {
row.addEventListener('click', async () => {
await selectItemForDrawer(row.dataset.id!);
});
});
} }
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@@ -446,8 +754,8 @@ const SAVE_HINT = isMac ? '⌘+S to save' : 'Ctrl+S to save';
function renderFormWrapped(app: HTMLElement, mode: 'add' | 'edit'): void { function renderFormWrapped(app: HTMLElement, mode: 'add' | 'edit'): void {
const itemType = state.selectedItem?.type ?? state.newType ?? 'login'; const itemType = state.selectedItem?.type ?? state.newType ?? 'login';
const typeLabel = itemType.replace('_', ' '); const typeLabelText = itemType.replace('_', ' ');
const titleText = mode === 'add' ? `new ${typeLabel}` : `edit ${typeLabel}`; const titleText = mode === 'add' ? `new ${typeLabelText}` : `edit ${typeLabelText}`;
const wrapper = document.createElement('div'); const wrapper = document.createElement('div');
wrapper.className = 'form-pane'; wrapper.className = 'form-pane';
wrapper.innerHTML = ` wrapper.innerHTML = `
@@ -505,6 +813,7 @@ export const __test__ = { renderFormWrapped };
function teardownPaneComponents(): void { function teardownPaneComponents(): void {
teardownTrash(); teardownTrash();
teardownDevices(); teardownDevices();
teardownSettings();
teardownFieldHistory(); teardownFieldHistory();
teardownBackup(); teardownBackup();
teardownImport(); teardownImport();
@@ -519,6 +828,7 @@ function renderPane(): void {
const route = parseHash(); const route = parseHash();
// Keep state.view in sync with hash for components that read it // Keep state.view in sync with hash for components that read it
state.view = route.view; state.view = route.view;
applyShellViewClass();
pane.className = 'vault-pane'; pane.className = 'vault-pane';
@@ -554,7 +864,7 @@ function renderPane(): void {
renderDevices(pane); renderDevices(pane);
break; break;
case 'settings': case 'settings':
renderSettings(pane); void renderSettings(pane);
break; break;
case 'settings-vault': case 'settings-vault':
renderVaultSettingsView(pane); renderVaultSettingsView(pane);
@@ -669,12 +979,15 @@ document.addEventListener('DOMContentLoaded', async () => {
if (!state.unlocked) return; if (!state.unlocked) return;
const route = parseHash(); const route = parseHash();
state.view = route.view;
applyShellViewClass();
// If navigating to a detail/edit view for an item we already have loaded // If navigating to a detail/edit view for an item we already have loaded
if ((route.view === 'detail' || route.view === 'edit') && route.id) { if ((route.view === 'detail' || route.view === 'edit') && route.id) {
if (state.selectedId === route.id && state.selectedItem) { if (state.selectedId === route.id && state.selectedItem) {
renderPane(); renderPane();
renderSidebarList(); renderSidebarCategories();
if (state.view === 'list') renderListPane();
return; return;
} }
// Need to fetch the item // Need to fetch the item
@@ -685,7 +998,30 @@ document.addEventListener('DOMContentLoaded', async () => {
// For non-item views, just re-render the pane // For non-item views, just re-render the pane
state.selectedId = null; state.selectedId = null;
state.selectedItem = null; state.selectedItem = null;
renderSidebarList(); renderSidebarCategories();
if (state.view === 'list') renderListPane();
renderPane(); renderPane();
}); });
}); });
// ---------------------------------------------------------------------------
// Legacy selectItem — used by hash-change deep linking
// ---------------------------------------------------------------------------
async function selectItem(id: ItemId): Promise<void> {
state.loading = true;
const resp = await sendMessage({ type: 'get_item', id });
if (resp.ok) {
const data = resp.data as { item: Item };
state.selectedId = id;
state.selectedItem = data.item;
state.loading = false;
setHash('detail', id);
renderSidebarCategories();
renderListPane();
renderPane();
} else {
state.loading = false;
state.error = (resp as { error: string }).error;
}
}

81
tools/relay/call.py Normal file
View File

@@ -0,0 +1,81 @@
#!/usr/bin/env python3
"""
CLI shim: call a relay MCP tool via raw SSE protocol.
Usage:
python3 call.py read_messages '{"for":"pm"}'
python3 call.py post_message '{"from":"pm","to":"dev-a","kind":"directive","body":"..."}'
python3 call.py list_pending '{"for":"pm"}'
"""
import sys, json, threading, requests, time
BASE = "http://localhost:7331"
tool_name = sys.argv[1]
args = json.loads(sys.argv[2]) if len(sys.argv) > 2 else {}
result = {"done": False, "value": None}
endpoint_url = {"url": None}
msg_id = 1
def read_sse():
with requests.get(f"{BASE}/sse", stream=True, timeout=15) as r:
for line in r.iter_lines(decode_unicode=True):
if not line:
continue
if line.startswith("data:"):
data = line[5:].strip()
if not endpoint_url["url"] and data.startswith("/message"):
endpoint_url["url"] = BASE + data
elif endpoint_url["url"]:
try:
payload = json.loads(data)
if payload.get("id") == msg_id:
result["value"] = payload
result["done"] = True
return
except json.JSONDecodeError:
pass
t = threading.Thread(target=read_sse, daemon=True)
t.start()
# Wait for endpoint
for _ in range(50):
if endpoint_url["url"]:
break
time.sleep(0.1)
if not endpoint_url["url"]:
print(json.dumps({"error": "no endpoint received"}))
sys.exit(1)
# Send initialize
init_payload = {
"jsonrpc": "2.0", "id": 0, "method": "initialize",
"params": {
"protocolVersion": "2024-11-05",
"capabilities": {},
"clientInfo": {"name": "relay-cli", "version": "0.1.0"}
}
}
requests.post(endpoint_url["url"], json=init_payload, timeout=5)
# Send tools/call
call_payload = {
"jsonrpc": "2.0", "id": msg_id, "method": "tools/call",
"params": {"name": tool_name, "arguments": args}
}
requests.post(endpoint_url["url"], json=call_payload, timeout=5)
# Wait for result
for _ in range(100):
if result["done"]:
break
time.sleep(0.1)
if result["done"]:
content = result["value"].get("result", {}).get("content", [])
for item in content:
if item.get("type") == "text":
print(item["text"])
else:
print(json.dumps({"error": "timeout waiting for response"}))
sys.exit(1)

25
tools/relay/call.ts Normal file
View File

@@ -0,0 +1,25 @@
/**
* CLI shim: call a relay MCP tool from bash.
* Usage:
* npx tsx call.ts read_messages '{"for":"pm"}'
* npx tsx call.ts post_message '{"from":"pm","to":"dev-a","kind":"directive","body":"..."}'
* npx tsx call.ts list_pending '{"for":"pm"}'
*/
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
const [, , toolName, argsJson] = process.argv;
if (!toolName) {
console.error("Usage: call.ts <tool_name> <args_json>");
process.exit(1);
}
const args = argsJson ? JSON.parse(argsJson) : {};
const url = new URL("http://localhost:7331/sse");
const transport = new SSEClientTransport(url);
const client = new Client({ name: "relay-cli", version: "0.1.0" }, { capabilities: {} });
await client.connect(transport);
const result = await client.callTool({ name: toolName, arguments: args });
console.log(JSON.stringify(result));
await client.close();

View File

@@ -51,7 +51,8 @@ describe("RelayQueue", () => {
assert.ok(isRole("pm")); assert.ok(isRole("pm"));
assert.ok(isRole("dev-a")); assert.ok(isRole("dev-a"));
assert.ok(isRole("dev-b")); assert.ok(isRole("dev-b"));
assert.ok(!isRole("dev-c")); assert.ok(isRole("dev-c"));
assert.ok(!isRole("dev-d"));
assert.ok(!isRole("")); assert.ok(!isRole(""));
assert.ok(!isRole("PM")); assert.ok(!isRole("PM"));
}); });

View File

@@ -1,6 +1,6 @@
import { randomUUID } from "node:crypto"; import { randomUUID } from "node:crypto";
export type Role = "pm" | "dev-a" | "dev-b"; export type Role = "pm" | "dev-a" | "dev-b" | "dev-c";
export type MessageKind = "status" | "question" | "directive" | "free"; export type MessageKind = "status" | "question" | "directive" | "free";
export interface RelayMessage { export interface RelayMessage {
@@ -12,7 +12,7 @@ export interface RelayMessage {
ts: string; ts: string;
} }
const KNOWN_ROLES = new Set<string>(["pm", "dev-a", "dev-b"]); const KNOWN_ROLES = new Set<string>(["pm", "dev-a", "dev-b", "dev-c"]);
export function isRole(s: string): s is Role { export function isRole(s: string): s is Role {
return KNOWN_ROLES.has(s); return KNOWN_ROLES.has(s);
@@ -23,6 +23,7 @@ export class RelayQueue {
["pm", []], ["pm", []],
["dev-a", []], ["dev-a", []],
["dev-b", []], ["dev-b", []],
["dev-c", []],
]); ]);
post(from: Role, to: Role, kind: MessageKind, body: string): RelayMessage { post(from: Role, to: Role, kind: MessageKind, body: string): RelayMessage {

View File

@@ -10,11 +10,6 @@ import { RelayQueue, isRole } from "./queue.ts";
const PORT = 7331; const PORT = 7331;
const queue = new RelayQueue(); const queue = new RelayQueue();
const mcpServer = new Server(
{ name: "relay", version: "0.1.0" },
{ capabilities: { tools: {} } }
);
const TOOLS = [ const TOOLS = [
{ {
name: "post_message", name: "post_message",
@@ -25,12 +20,12 @@ const TOOLS = [
properties: { properties: {
from: { from: {
type: "string", type: "string",
enum: ["pm", "dev-a", "dev-b"], enum: ["pm", "dev-a", "dev-b", "dev-c"],
description: "Your role name", description: "Your role name",
}, },
to: { to: {
type: "string", type: "string",
enum: ["pm", "dev-a", "dev-b"], enum: ["pm", "dev-a", "dev-b", "dev-c"],
description: "Recipient role name", description: "Recipient role name",
}, },
kind: { kind: {
@@ -55,7 +50,7 @@ const TOOLS = [
properties: { properties: {
for: { for: {
type: "string", type: "string",
enum: ["pm", "dev-a", "dev-b"], enum: ["pm", "dev-a", "dev-b", "dev-c"],
description: "Your role name", description: "Your role name",
}, },
}, },
@@ -71,7 +66,7 @@ const TOOLS = [
properties: { properties: {
for: { for: {
type: "string", type: "string",
enum: ["pm", "dev-a", "dev-b"], enum: ["pm", "dev-a", "dev-b", "dev-c"],
description: "Your role name", description: "Your role name",
}, },
}, },
@@ -80,41 +75,36 @@ const TOOLS = [
}, },
]; ];
mcpServer.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS })); function handleToolCall(name: string, args: Record<string, string>) {
mcpServer.setRequestHandler(CallToolRequestSchema, async (request) => {
const { name, arguments: args } = request.params;
const a = args as Record<string, string>;
if (name === "post_message") { if (name === "post_message") {
if (!isRole(a.from)) { if (!isRole(args.from)) {
return { content: [{ type: "text" as const, text: `Error: unknown role "${a.from}"` }], isError: true }; return { content: [{ type: "text" as const, text: `Error: unknown role "${args.from}"` }], isError: true };
} }
if (!isRole(a.to)) { if (!isRole(args.to)) {
return { content: [{ type: "text" as const, text: `Error: unknown role "${a.to}"` }], isError: true }; return { content: [{ type: "text" as const, text: `Error: unknown role "${args.to}"` }], isError: true };
} }
const kind = a.kind as "status" | "question" | "directive" | "free"; const kind = args.kind as "status" | "question" | "directive" | "free";
const msg = queue.post(a.from, a.to, kind, a.body); const msg = queue.post(args.from, args.to, kind, args.body);
const ts = new Date(msg.ts).toTimeString().slice(0, 8); const ts = new Date(msg.ts).toTimeString().slice(0, 8);
const preview = a.body.slice(0, 60).replace(/\n/g, " "); const preview = args.body.slice(0, 60).replace(/\n/g, " ");
const ellipsis = a.body.length > 60 ? "..." : ""; const ellipsis = args.body.length > 60 ? "..." : "";
process.stdout.write(`[${ts}] ${a.from}${a.to} [${kind}] "${preview}${ellipsis}"\n`); process.stdout.write(`[${ts}] ${args.from}${args.to} [${kind}] "${preview}${ellipsis}"\n`);
return { content: [{ type: "text" as const, text: JSON.stringify({ id: msg.id }) }] }; return { content: [{ type: "text" as const, text: JSON.stringify({ id: msg.id }) }] };
} }
if (name === "read_messages") { if (name === "read_messages") {
if (!isRole(a.for)) { if (!isRole(args.for)) {
return { content: [{ type: "text" as const, text: `Error: unknown role "${a.for}"` }], isError: true }; return { content: [{ type: "text" as const, text: `Error: unknown role "${args.for}"` }], isError: true };
} }
const messages = queue.read(a.for); const messages = queue.read(args.for);
return { content: [{ type: "text" as const, text: JSON.stringify(messages) }] }; return { content: [{ type: "text" as const, text: JSON.stringify(messages) }] };
} }
if (name === "list_pending") { if (name === "list_pending") {
if (!isRole(a.for)) { if (!isRole(args.for)) {
return { content: [{ type: "text" as const, text: `Error: unknown role "${a.for}"` }], isError: true }; return { content: [{ type: "text" as const, text: `Error: unknown role "${args.for}"` }], isError: true };
} }
const result = queue.pending(a.for); const result = queue.pending(args.for);
return { content: [{ type: "text" as const, text: JSON.stringify(result) }] }; return { content: [{ type: "text" as const, text: JSON.stringify(result) }] };
} }
@@ -122,7 +112,20 @@ mcpServer.setRequestHandler(CallToolRequestSchema, async (request) => {
content: [{ type: "text" as const, text: `Error: unknown tool "${name}"` }], content: [{ type: "text" as const, text: `Error: unknown tool "${name}"` }],
isError: true, isError: true,
}; };
}
function makeServer() {
const srv = new Server(
{ name: "relay", version: "0.1.0" },
{ capabilities: { tools: {} } }
);
srv.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS }));
srv.setRequestHandler(CallToolRequestSchema, async (request) => {
const { name, arguments: args } = request.params;
return handleToolCall(name, args as Record<string, string>);
}); });
return srv;
}
const transports = new Map<string, SSEServerTransport>(); const transports = new Map<string, SSEServerTransport>();
@@ -132,7 +135,8 @@ const httpServer = http.createServer(async (req, res) => {
const transport = new SSEServerTransport("/message", res); const transport = new SSEServerTransport("/message", res);
transports.set(transport.sessionId, transport); transports.set(transport.sessionId, transport);
transport.onclose = () => transports.delete(transport.sessionId); transport.onclose = () => transports.delete(transport.sessionId);
await mcpServer.connect(transport); // Each connection gets its own Server instance so multiple clients can coexist.
await makeServer().connect(transport);
} else if (req.method === "POST" && req.url?.startsWith("/message")) { } else if (req.method === "POST" && req.url?.startsWith("/message")) {
const url = new URL(req.url, `http://127.0.0.1:${PORT}`); const url = new URL(req.url, `http://127.0.0.1:${PORT}`);
const sessionId = url.searchParams.get("sessionId") ?? ""; const sessionId = url.searchParams.get("sessionId") ?? "";

View File

@@ -69,14 +69,14 @@ launch_tmux() {
} }
launch_kitty() { launch_kitty() {
kitty @ launch --new-tab --tab-title "relay" -- \ kitty @ launch --type=tab --tab-title "relay" -- \
bash -c "cd '$SCRIPT_DIR' && npx tsx server.ts" bash -c "cd '$SCRIPT_DIR' && npx tsx server.ts"
kitty @ launch --new-window --window-title "PM" -- \ kitty @ launch --type=tab --tab-title "PM" --hold -- \
bash -c "cd '$REPO_ROOT' && claude" bash -l -i -c "cd '$REPO_ROOT' && claude"
kitty @ launch --new-window --window-title "Dev-A" -- \ kitty @ launch --type=tab --tab-title "Dev-A" --hold -- \
bash -c "cd '$REPO_ROOT' && claude" bash -l -i -c "cd '$REPO_ROOT' && claude"
kitty @ launch --new-window --window-title "Dev-B" -- \ kitty @ launch --type=tab --tab-title "Dev-B" --hold -- \
bash -c "cd '$REPO_ROOT' && claude" bash -l -i -c "cd '$REPO_ROOT' && claude"
echo "" echo ""
echo "[relay] Opened kitty tab 'relay' + 3 windows (PM, Dev-A, Dev-B)." echo "[relay] Opened kitty tab 'relay' + 3 windows (PM, Dev-A, Dev-B)."
echo " Paste the kickoff prompts into each Claude window." echo " Paste the kickoff prompts into each Claude window."