Compare commits
40 Commits
feature/v0
...
42143fabec
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
42143fabec | ||
|
|
098ac208ea | ||
|
|
6c8e702260 | ||
|
|
4e9859d461 | ||
|
|
6bb7dedc3e | ||
|
|
ffa8232dfd | ||
|
|
9c47709d14 | ||
|
|
7144e40287 | ||
|
|
4c632a98fc | ||
|
|
e42e83ccc5 | ||
|
|
3b94a30fc8 | ||
|
|
7d6fd76e86 | ||
|
|
4dc034d846 | ||
|
|
3021ef9d9f | ||
|
|
b2749826b1 | ||
|
|
a332a9e80d | ||
|
|
d45dd10917 | ||
|
|
4d02a50cc8 | ||
|
|
5d9a7ee8d3 | ||
|
|
006e67c361 | ||
|
|
95d1ff833c | ||
|
|
4fc1357368 | ||
|
|
df58b0dda1 | ||
|
|
ed9fcbe6ba | ||
|
|
0172a06698 | ||
|
|
6d5a2570d4 | ||
|
|
6a1c6d5875 | ||
|
|
6d8f699fcb | ||
|
|
c0921b134d | ||
|
|
0443f6a3b4 | ||
|
|
5e8e617a4d | ||
|
|
efac53d527 | ||
|
|
af8626fb5f | ||
|
|
9c97f9f939 | ||
|
|
76d092d4f6 | ||
|
|
1342228a51 | ||
|
|
d539050aec | ||
|
|
8fd9a05875 | ||
|
|
8a72b5e192 | ||
|
|
ca059e7507 |
@@ -1,4 +1,10 @@
|
||||
{
|
||||
"mcpServers": {
|
||||
"relay": {
|
||||
"type": "sse",
|
||||
"url": "http://localhost:7331/sse"
|
||||
}
|
||||
},
|
||||
"enabledPlugins": {
|
||||
"superpowers@claude-plugins-official": true
|
||||
}
|
||||
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -7,3 +7,4 @@ extension/dist-firefox/
|
||||
extension/wasm/
|
||||
reference.jpg
|
||||
ref.jpg
|
||||
tools/relay/node_modules/
|
||||
|
||||
108
CHANGELOG.md
108
CHANGELOG.md
@@ -1,9 +1,76 @@
|
||||
# Changelog
|
||||
|
||||
## Unreleased
|
||||
## v0.5.0 — 2026-05-02
|
||||
|
||||
Three release trains roll into one tag — backup/restore + LastPass
|
||||
import (originally v0.3.0), device authentication (originally v0.4.0),
|
||||
and the v0.5.0 polish + harden bundle (security fixes + UX fixes +
|
||||
two confirmed bugs).
|
||||
|
||||
### Security
|
||||
|
||||
- **Pre-receive hook now actually verifies signatures (audit S1, HIGH).**
|
||||
Earlier `relicario-server` builds accepted any commit with a
|
||||
`Good signature` line on stderr regardless of which key signed it —
|
||||
device-auth was a no-op. The hook now builds an `allowed_signers`
|
||||
file from `devices.json` at the commit (via `GIT_CONFIG_*` env, no
|
||||
global git-config mutation), parses the SSH SHA-256 fingerprint out
|
||||
of `git verify-commit --raw` stderr, and rejects unregistered keys or
|
||||
revoked keys whose committer-date is at or after the revocation
|
||||
timestamp. Bootstrap mode is preserved only when **both**
|
||||
`devices.json` AND `revoked.json` are empty (closes an
|
||||
empty-devices.json privilege-escalation route).
|
||||
- **Backup-restore tar unpacking hardened (audit S2).** `relicario
|
||||
backup restore` no longer trusts `tar::Archive::unpack`'s defaults.
|
||||
A new `relicario_core::safe_unpack_git_archive` validates each
|
||||
entry's path components (rejects `..`, absolute paths, Windows
|
||||
drive prefixes), rejects symlinks/hardlinks, and caps total
|
||||
uncompressed size at the lower of 100×compressed-bytes or 1 GiB.
|
||||
The CLI restore path adds a paranoid `dest.starts_with(.git/)`
|
||||
check after path-joining as defense-in-depth.
|
||||
- **`RELICARIO_*` env-var surface audited (audit S3).** `docs/SECURITY.md`
|
||||
gains a per-variable trust table. `RELICARIO_NO_GROUPS_CACHE` (a
|
||||
developer escape hatch, not a user knob) is now
|
||||
`cfg(debug_assertions)`-gated and is a no-op in `--release` builds;
|
||||
the env-var lookup is removed from the binary by the optimiser.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Strength meter no longer goes stale after the regenerate button (B1).**
|
||||
Programmatic `input.value = newPassword` doesn't fire `input`
|
||||
events; the regenerate handler now dispatches a synthetic
|
||||
`InputEvent('input', { bubbles: true })` so the meter listener
|
||||
re-rates the new value.
|
||||
- **Snake_case error codes no longer leak into the UI (B2 / P4).**
|
||||
Errors like `vault_locked`, `origin_mismatch`, `unauthorized_sender`
|
||||
used to render verbatim in the fullscreen vault tab and (in some
|
||||
cases) the popup. New `extension/src/shared/error-copy.ts` central
|
||||
registry maps every service-worker error code to friendly
|
||||
title/body/CTA copy; the popup and fullscreen tab consume the
|
||||
same map. The fullscreen lock screen's `vault_locked` block now
|
||||
reads `Vault locked / Unlock your vault to continue. / [Unlock
|
||||
vault]`. A generated test enumerates the live error codes via
|
||||
grep so the registry can't drift.
|
||||
|
||||
### Added
|
||||
|
||||
- **Sidebar logo in the fullscreen vault tab.** The
|
||||
`vault-sidebar__header` now renders the 16-optimized SVG logo
|
||||
inline before the "Relicario" wordmark (20×20 px, `flex-shrink: 0`
|
||||
so it survives narrow-pane wraps). Popup unaffected.
|
||||
- **Password coloring (P1).** Revealed passwords in the popup
|
||||
item-detail, fullscreen item view, field-history viewer, and
|
||||
generator preview render digits and symbols in distinct colors.
|
||||
Defaults: blue digits, red symbols. Users can override via the
|
||||
new Display section in settings (color pickers + live preview
|
||||
swatch + reset). Defaults round-trip via
|
||||
`chrome.storage.sync.password_display_scheme`; cross-device when
|
||||
Chrome sync is enabled.
|
||||
- **Setup wizard hands off to the fullscreen vault tab on completion
|
||||
(P2).** Both create-new and attach-existing flows now open
|
||||
`vault.html` in a new tab and best-effort close the setup tab
|
||||
after device registration succeeds — replaces the prior
|
||||
setup-tab-stays-open terminal screen.
|
||||
- **Sync now button** in the extension settings view — surfaces the
|
||||
previously hidden `{ type: 'sync' }` SW message to users with success /
|
||||
error feedback.
|
||||
@@ -59,6 +126,30 @@
|
||||
file `cmd_backup_export` writes on success). Reads "never" for
|
||||
fresh vaults, "4 days ago" otherwise.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Form layout in the fullscreen vault tab is now visually consistent
|
||||
(P3).** Notes, custom-fields disclosure, attachments disclosure, and
|
||||
form-actions in fullscreen logins now sit inside a `.form-lower`
|
||||
wrapper with the same `max-width: 960px; margin: 0 auto` envelope as
|
||||
the `.form-grid` cards above. Removes the visual rhythm break at the
|
||||
2-col → full-width transition. The popup surface is unchanged.
|
||||
- **Documentation refreshed for v0.5.0 (doc audit, 14 findings).**
|
||||
`docs/architecture/overview.md` now describes four codebases (the
|
||||
`relicario-server` pre-receive hook crate is no longer invisible);
|
||||
`CLAUDE.md` project tree and roadmap reflect current state;
|
||||
`docs/SECURITY.md` names the server crate and its `verify-commit` /
|
||||
`generate-hook` subcommands and notes the without-the-hook-it's-
|
||||
advisory caveat; `docs/ARCHITECTURE.md` shows `settings.enc` as a
|
||||
parallel artifact in the vault-creation flow; the foundational
|
||||
design spec gains a "historical" status banner pointing readers at
|
||||
the current docs.
|
||||
- `relicario generate` now consults `VaultSettings.generator_defaults` when
|
||||
invoked inside an initialized vault. Explicit flags (`--length`,
|
||||
`--bip39`, `--words`, `--symbols`, `--separator`) override the vault
|
||||
default. Outside a vault, behavior is unchanged (length 20, safe symbol
|
||||
set, 5 BIP39 words, space separator).
|
||||
|
||||
### Known limitations
|
||||
|
||||
- **Mid-restore failure leaves the target remote in a half-written
|
||||
@@ -74,6 +165,13 @@
|
||||
|
||||
### Internal
|
||||
|
||||
- 5 stale local feature branches and 3 worktrees pruned (audit C1).
|
||||
- Pre-existing clippy warnings cleaned up across `relicario-{core,cli}`
|
||||
(deref operators, `Option::is_none_or` over `map_or(true, ...)`,
|
||||
`iter_mut().enumerate()` patterns, `div_ceil()`) so the workspace
|
||||
builds clean under `-D warnings`.
|
||||
- `Cargo.lock` regenerated and committed; was stale since the
|
||||
`--totp-qr` commit.
|
||||
- Refactored `cmd_add` and `cmd_edit` in the CLI: each `ItemCore` variant
|
||||
now has its own `build_*_item` / `edit_*` helper. Pure mechanical
|
||||
extraction; behavior unchanged. The dispatcher matches and delegates.
|
||||
@@ -83,14 +181,6 @@
|
||||
`setup.ts` since it walks live wizard state. Setup.ts went from
|
||||
1205 → 1137 lines.
|
||||
|
||||
### Changed
|
||||
|
||||
- `relicario generate` now consults `VaultSettings.generator_defaults` when
|
||||
invoked inside an initialized vault. Explicit flags (`--length`,
|
||||
`--bip39`, `--words`, `--symbols`, `--separator`) override the vault
|
||||
default. Outside a vault, behavior is unchanged (length 20, safe symbol
|
||||
set, 5 BIP39 words, space separator).
|
||||
|
||||
## v0.2.0 — 2026-04-27
|
||||
|
||||
### Fixed
|
||||
|
||||
12
CLAUDE.md
12
CLAUDE.md
@@ -48,9 +48,11 @@ crates/
|
||||
│ ├── src/helpers.rs # vault_dir, git_command, iso8601
|
||||
│ ├── src/session.rs # UnlockedVault (master key in Zeroizing)
|
||||
│ └── tests/ # basic_flows, edit_and_history, attachments, settings, vault_detection
|
||||
└── relicario-wasm/ # WASM bindings for the extension
|
||||
├── src/lib.rs # #[wasm_bindgen] surface
|
||||
└── src/session.rs # opaque SessionHandle → Zeroizing<[u8;32]>
|
||||
├── relicario-wasm/ # WASM bindings for the extension
|
||||
│ ├── src/lib.rs # #[wasm_bindgen] surface
|
||||
│ └── src/session.rs # opaque SessionHandle → Zeroizing<[u8;32]>
|
||||
└── relicario-server/ # `relicario-server` binary (pre-receive Git hook)
|
||||
└── src/main.rs # verify-commit + generate-hook subcommands
|
||||
```
|
||||
|
||||
## Key design decisions
|
||||
@@ -76,7 +78,7 @@ passphrase (UTF-8 bytes) || image_secret (32 bytes from reference JPEG)
|
||||
|
||||
- Tests use fast Argon2id params (m=256, t=1, p=1) so they don't take forever.
|
||||
- Test JPEGs are generated synthetically via `make_test_jpeg()` — no binary test fixtures.
|
||||
- Item IDs are random 8-char hex strings.
|
||||
- Item IDs and Field IDs are random 16-char hex strings (64 bits of OsRng entropy). AttachmentIds are content-addressed: first 32 hex chars of SHA-256 over the plaintext (128 bits).
|
||||
- Git history is preserved as an audit log — no squashing.
|
||||
- The CLI shells out to `git` for sync — no libgit2/gitoxide dependency.
|
||||
|
||||
@@ -90,4 +92,4 @@ Full threat model, entropy analysis, and architecture: `docs/superpowers/specs/2
|
||||
|
||||
## Roadmap
|
||||
|
||||
Next: WASM build + Chrome MV3 browser extension (Plan 2). Then mobile (Rust core compiles to ARM).
|
||||
Next: v0.5.0 polish + harden (in progress). After that, Phases 3/4 of the fullscreen UX redesign (vault-tab shell + command palette), Plan 1C-γ (attachments + Document + trash/history/device UI), and the LastPass importer. Mobile (Rust core compiles to ARM) and recovery QR remain on the roadmap.
|
||||
|
||||
940
Cargo.lock
generated
940
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@@ -91,6 +91,7 @@ pub fn store_device_keys(
|
||||
}
|
||||
|
||||
/// Load the signing private key for a device.
|
||||
#[allow(dead_code)]
|
||||
pub fn load_signing_key(name: &str) -> Result<Zeroizing<String>> {
|
||||
let path = device_dir(name)?.join("signing.key");
|
||||
let key = fs::read_to_string(&path)
|
||||
@@ -99,6 +100,7 @@ pub fn load_signing_key(name: &str) -> Result<Zeroizing<String>> {
|
||||
}
|
||||
|
||||
/// Load the deploy private key for a device.
|
||||
#[allow(dead_code)]
|
||||
pub fn load_deploy_key(name: &str) -> Result<Zeroizing<String>> {
|
||||
let path = device_dir(name)?.join("deploy.key");
|
||||
let key = fs::read_to_string(&path)
|
||||
@@ -115,6 +117,7 @@ pub fn load_gitea_key_id(name: &str) -> Result<u64> {
|
||||
}
|
||||
|
||||
/// Delete the local key directory for a device.
|
||||
#[allow(dead_code)]
|
||||
pub fn delete_device_keys(name: &str) -> Result<()> {
|
||||
let dir = device_dir(name)?;
|
||||
if dir.exists() {
|
||||
|
||||
@@ -21,7 +21,9 @@ struct CreateKeyRequest<'a> {
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct DeployKey {
|
||||
pub id: u64,
|
||||
#[allow(dead_code)]
|
||||
pub title: String,
|
||||
#[allow(dead_code)]
|
||||
pub key: String,
|
||||
}
|
||||
|
||||
@@ -89,6 +91,7 @@ impl GiteaClient {
|
||||
}
|
||||
|
||||
/// List all deploy keys.
|
||||
#[allow(dead_code)]
|
||||
pub fn list_deploy_keys(&self) -> Result<Vec<DeployKey>> {
|
||||
let url = format!(
|
||||
"{}/repos/{}/{}/keys",
|
||||
|
||||
@@ -34,6 +34,7 @@ pub fn vault_dir() -> Result<PathBuf> {
|
||||
}
|
||||
|
||||
/// Path to the `.relicario/` configuration directory within the vault.
|
||||
#[allow(dead_code)]
|
||||
pub fn relicario_dir() -> Result<PathBuf> {
|
||||
Ok(vault_dir()?.join(".relicario"))
|
||||
}
|
||||
@@ -88,19 +89,21 @@ fn plural(n: i64) -> &'static str { if n == 1 { "" } else { "s" } }
|
||||
///
|
||||
/// **Plaintext leak:** group names land on disk in cleartext alongside the
|
||||
/// vault directory. This is intentional — the file feeds shell completion,
|
||||
/// which cannot prompt for a passphrase. Set `RELICARIO_NO_GROUPS_CACHE=1`
|
||||
/// to suppress the write.
|
||||
/// which cannot prompt for a passphrase. In debug builds, set
|
||||
/// `RELICARIO_NO_GROUPS_CACHE=1` to suppress the write.
|
||||
pub fn groups_cache_path(vault_dir: &Path) -> PathBuf {
|
||||
vault_dir.join(".relicario").join("groups.cache")
|
||||
}
|
||||
|
||||
/// Write the sorted set of group names to `<vault_dir>/.relicario/groups.cache`,
|
||||
/// one name per line. A no-op if `RELICARIO_NO_GROUPS_CACHE` is set.
|
||||
/// one name per line. In debug builds, setting `RELICARIO_NO_GROUPS_CACHE`
|
||||
/// suppresses the write (developer debugging tool). In release builds the env
|
||||
/// var is ignored.
|
||||
pub fn write_groups_cache(
|
||||
vault_dir: &Path,
|
||||
groups: &std::collections::BTreeSet<String>,
|
||||
) -> std::io::Result<()> {
|
||||
if std::env::var_os("RELICARIO_NO_GROUPS_CACHE").is_some() {
|
||||
if cfg!(debug_assertions) && std::env::var_os("RELICARIO_NO_GROUPS_CACHE").is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
let path = groups_cache_path(vault_dir);
|
||||
|
||||
@@ -170,7 +170,7 @@ enum Commands {
|
||||
///
|
||||
/// For `--group <TAB>` autocomplete, the bash/zsh/fish scripts read
|
||||
/// the plaintext `${RELICARIO_VAULT}/.relicario/groups.cache` file,
|
||||
/// which the CLI refreshes on every manifest read. Set
|
||||
/// which the CLI refreshes on every manifest read. In debug builds, set
|
||||
/// `RELICARIO_NO_GROUPS_CACHE=1` to opt out of the cache (completion
|
||||
/// will fall back to no value enumeration).
|
||||
///
|
||||
@@ -540,7 +540,7 @@ fn cmd_init(image: PathBuf, output: PathBuf) -> Result<()> {
|
||||
};
|
||||
let carrier = fs::read(&image)
|
||||
.with_context(|| format!("failed to read carrier image {}", image.display()))?;
|
||||
let stego = imgsecret::embed(&carrier, &*image_secret)?;
|
||||
let stego = imgsecret::embed(&carrier, &image_secret)?;
|
||||
fs::write(&output, &stego)
|
||||
.with_context(|| format!("failed to write reference image {}", output.display()))?;
|
||||
|
||||
@@ -550,7 +550,7 @@ fn cmd_init(image: PathBuf, output: PathBuf) -> Result<()> {
|
||||
let params = KdfParams { argon2_m: 65536, argon2_t: 3, argon2_p: 4 };
|
||||
|
||||
// Derive master key, then persist an empty Manifest + default VaultSettings.
|
||||
let master_key = derive_master_key(passphrase.as_bytes(), &*image_secret, &salt, ¶ms)?;
|
||||
let master_key = derive_master_key(passphrase.as_bytes(), &image_secret, &salt, ¶ms)?;
|
||||
|
||||
fs::create_dir_all(&relicario_dir)?;
|
||||
fs::create_dir_all(root.join("items"))?;
|
||||
@@ -645,6 +645,7 @@ fn cmd_add(kind: AddKind) -> Result<()> {
|
||||
// (for attachment-cap settings + writing the encrypted blob alongside
|
||||
// the item).
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn build_login_item(
|
||||
title: Option<String>,
|
||||
username: Option<String>,
|
||||
@@ -860,6 +861,7 @@ fn build_document_item(
|
||||
Ok(item)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn build_totp_item(
|
||||
title: Option<String>,
|
||||
issuer: Option<String>,
|
||||
@@ -924,7 +926,7 @@ fn prompt_optional(label: &str) -> Result<Option<String>> {
|
||||
|
||||
fn parse_month_year(s: &str) -> Result<relicario_core::MonthYear> {
|
||||
// Accepts MM/YYYY or MM-YYYY or MM/YY.
|
||||
let (m_str, y_str) = s.split_once(|c: char| c == '/' || c == '-')
|
||||
let (m_str, y_str) = s.split_once(['/', '-'])
|
||||
.ok_or_else(|| anyhow::anyhow!("expected MM/YYYY"))?;
|
||||
let month: u8 = m_str.parse().context("invalid month")?;
|
||||
let year: u16 = if y_str.len() == 2 {
|
||||
@@ -998,12 +1000,12 @@ fn cmd_get(query: String, show: bool, copy: bool) -> Result<()> {
|
||||
if let Some(u) = &l.url { println!("URL: {u}"); }
|
||||
if let Some(t) = &l.totp {
|
||||
if show {
|
||||
println!("TOTP: {}", data_encoding::BASE32.encode(&*t.secret));
|
||||
println!("TOTP: {}", data_encoding::BASE32.encode(&t.secret));
|
||||
} else {
|
||||
println!("TOTP: **** (use --show to reveal)");
|
||||
}
|
||||
}
|
||||
if let Some(p) = &l.password { Some(p.clone()) } else { None }
|
||||
l.password.clone()
|
||||
}
|
||||
ItemCore::SecureNote(n) => {
|
||||
if show { println!("Body:\n{}", n.body.as_str()); }
|
||||
@@ -1125,8 +1127,8 @@ fn cmd_list(
|
||||
Some(t) => e.r#type == t,
|
||||
None => true,
|
||||
})
|
||||
.filter(|e| group_filter.as_ref().map_or(true, |g| e.group.as_deref() == Some(g.as_str())))
|
||||
.filter(|e| tag_filter.as_ref().map_or(true, |t| e.tags.iter().any(|x| x == t)))
|
||||
.filter(|e| group_filter.as_ref().is_none_or(|g| e.group.as_deref() == Some(g.as_str())))
|
||||
.filter(|e| tag_filter.as_ref().is_none_or(|t| e.tags.iter().any(|x| x == t)))
|
||||
.collect();
|
||||
entries.sort_by(|a, b| a.title.to_lowercase().cmp(&b.title.to_lowercase()));
|
||||
|
||||
@@ -1135,7 +1137,7 @@ fn cmd_list(
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
println!("{:<16} {:<14} {:<6} {}", "ID", "TYPE", "FAV", "TITLE");
|
||||
println!("{:<16} {:<14} {:<6} TITLE", "ID", "TYPE", "FAV");
|
||||
for e in entries {
|
||||
let fav = if e.favorite { " *" } else { "" };
|
||||
println!("{:<16} {:<14} {:<6} {}", e.id.as_str(), format!("{:?}", e.r#type), fav, e.title);
|
||||
@@ -1718,9 +1720,32 @@ fn cmd_backup_restore(input: PathBuf, target: PathBuf) -> Result<()> {
|
||||
|
||||
// .git/ history.
|
||||
if let Some(tar_bytes) = &unpacked.git_archive {
|
||||
let mut archive = tar::Archive::new(tar_bytes.as_slice());
|
||||
archive.unpack(target.join(".git"))
|
||||
.with_context(|| "failed to untar .git/")?;
|
||||
// Cap: 100× the compressed bundle size, or 1 GiB, whichever is lower.
|
||||
let cap = std::cmp::min(
|
||||
(tar_bytes.len() as u64).saturating_mul(100),
|
||||
relicario_core::DEFAULT_MAX_UNCOMPRESSED,
|
||||
);
|
||||
let entries = relicario_core::safe_unpack_git_archive(tar_bytes, cap)
|
||||
.with_context(|| "failed to safely unpack .git/ archive")?;
|
||||
let git_dir = target.join(".git");
|
||||
for (rel_path, body) in entries {
|
||||
let dest = git_dir.join(&rel_path);
|
||||
// Paranoid OS-level check even after textual validation in core.
|
||||
if !dest.starts_with(&git_dir) {
|
||||
anyhow::bail!(
|
||||
"tar entry {} resolved outside .git/ (path traversal blocked)",
|
||||
rel_path.display()
|
||||
);
|
||||
}
|
||||
if let Some(parent) = dest.parent() {
|
||||
fs::create_dir_all(parent).with_context(|| {
|
||||
format!("create parent {}", parent.display())
|
||||
})?;
|
||||
}
|
||||
fs::write(&dest, &body).with_context(|| {
|
||||
format!("write {}", dest.display())
|
||||
})?;
|
||||
}
|
||||
} else {
|
||||
// No history bundled — start a fresh git repo.
|
||||
let status = crate::helpers::git_command(&target, &["init"]).status()?;
|
||||
@@ -1950,7 +1975,7 @@ fn cmd_attachments(query: String) -> Result<()> {
|
||||
let entry = resolve_query(&manifest, &query)?;
|
||||
let item = vault.load_item(&entry.id)?;
|
||||
if item.attachments.is_empty() { eprintln!("(no attachments)"); return Ok(()); }
|
||||
println!("{:<17} {:>12} {:<22} {}", "AID", "SIZE", "MIME", "FILENAME");
|
||||
println!("{:<17} {:>12} {:<22} FILENAME", "AID", "SIZE", "MIME");
|
||||
for a in &item.attachments {
|
||||
println!("{:<17} {:>12} {:<22} {}", a.id.as_str(), a.size, a.mime_type, a.filename);
|
||||
}
|
||||
@@ -2518,7 +2543,7 @@ fn cmd_device(action: DeviceAction) -> Result<()> {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
println!("{:<20} {:<20} {}", "NAME", "ADDED", "SIGNING KEY (prefix)");
|
||||
println!("{:<20} {:<20} SIGNING KEY (prefix)", "NAME", "ADDED");
|
||||
println!("{}", "-".repeat(72));
|
||||
for d in &devices {
|
||||
let marker = if d.name == current { " *" } else { "" };
|
||||
|
||||
@@ -50,7 +50,7 @@ impl UnlockedVault {
|
||||
|
||||
let master_key = derive_master_key(
|
||||
passphrase.as_bytes(),
|
||||
&*image_secret,
|
||||
&image_secret,
|
||||
&salt,
|
||||
¶ms,
|
||||
)?;
|
||||
|
||||
@@ -68,7 +68,7 @@ fn detach_removes_attachment_and_blob() {
|
||||
// Encrypted blob file is gone.
|
||||
let blob_path = v.path()
|
||||
.join("attachments")
|
||||
.join(stdout.lines().nth(1).is_some().then_some("").unwrap_or(""));
|
||||
.join("");
|
||||
let item_attach_dir = std::fs::read_dir(v.path().join("attachments"))
|
||||
.unwrap().next().unwrap().unwrap().path();
|
||||
let blob = item_attach_dir.join(format!("{aid}.enc"));
|
||||
|
||||
@@ -78,6 +78,7 @@ impl TestVault {
|
||||
cmd.output().unwrap()
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn run_with_backup_pass(&self, args: &[&str], backup_pass: &str) -> std::process::Output {
|
||||
let mut cmd = Command::cargo_bin("relicario").unwrap();
|
||||
cmd.current_dir(self.dir.path())
|
||||
@@ -91,6 +92,7 @@ impl TestVault {
|
||||
cmd.output().unwrap()
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn run_with_input(&self, args: &[&str], extra: &[&str]) -> std::process::Output {
|
||||
let mut cmd = Command::cargo_bin("relicario").unwrap();
|
||||
cmd.current_dir(self.dir.path())
|
||||
|
||||
@@ -408,7 +408,7 @@ mod tests {
|
||||
blob.extend_from_slice(&[0u8; 16]);
|
||||
|
||||
let key = Zeroizing::new([0u8; 32]);
|
||||
let err = decrypt(&*key, &blob).expect_err("v1 blob should fail decrypt");
|
||||
let err = decrypt(&key, &blob).expect_err("v1 blob should fail decrypt");
|
||||
match err {
|
||||
RelicarioError::UnsupportedFormatVersion { found, expected } => {
|
||||
assert_eq!(found, 0x01);
|
||||
|
||||
@@ -106,6 +106,16 @@ pub fn verify(public_key_openssh: &str, data: &[u8], signature_b64: &str) -> Res
|
||||
Ok(verifying_key.verify(data, &signature).is_ok())
|
||||
}
|
||||
|
||||
/// Compute the OpenSSH SHA-256 fingerprint of a public key.
|
||||
/// Output format matches `ssh-keygen -lf` and `git verify-commit --raw`:
|
||||
/// `SHA256:<43-char base64 without padding>`.
|
||||
pub fn fingerprint(public_key_openssh: &str) -> Result<String> {
|
||||
use ssh_key::HashAlg;
|
||||
let public = PublicKey::from_openssh(public_key_openssh)
|
||||
.map_err(|e| RelicarioError::DeviceKey(format!("parse public key: {e}")))?;
|
||||
Ok(public.fingerprint(HashAlg::Sha256).to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -132,4 +142,27 @@ mod tests {
|
||||
let sig = sign(&private, b"hello").unwrap();
|
||||
assert!(!verify(&other_public, b"hello", &sig).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fingerprint_matches_ssh_keygen_format() {
|
||||
let (_, public) = generate_keypair().unwrap();
|
||||
let fp = fingerprint(&public).unwrap();
|
||||
assert!(fp.starts_with("SHA256:"), "fingerprint should start with SHA256: prefix, got {fp}");
|
||||
let body = fp.strip_prefix("SHA256:").unwrap();
|
||||
assert_eq!(body.len(), 43, "SHA-256 fingerprint body is 43 base64 chars (no padding)");
|
||||
assert!(body.chars().all(|c| c.is_ascii_alphanumeric() || c == '+' || c == '/'));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fingerprint_is_deterministic() {
|
||||
let (_, public) = generate_keypair().unwrap();
|
||||
assert_eq!(fingerprint(&public).unwrap(), fingerprint(&public).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fingerprint_differs_per_key() {
|
||||
let (_, p1) = generate_keypair().unwrap();
|
||||
let (_, p2) = generate_keypair().unwrap();
|
||||
assert_ne!(fingerprint(&p1).unwrap(), fingerprint(&p2).unwrap());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,6 +51,10 @@ pub enum RelicarioError {
|
||||
#[error("backup envelope schema v{found}; this Relicario reads v{expected}")]
|
||||
BackupSchemaMismatch { found: u32, expected: u32 },
|
||||
|
||||
/// An error during backup restore (e.g., tar safety validation failure).
|
||||
#[error("backup restore: {0}")]
|
||||
BackupRestore(String),
|
||||
|
||||
/// CSV header doesn't match the LastPass column layout.
|
||||
#[error("unrecognized CSV header — expected LastPass export format ({0})")]
|
||||
ImportCsvHeader(String),
|
||||
|
||||
@@ -83,7 +83,7 @@ const BITS_PER_BLOCK: usize = 12; // EMBED_POSITIONS.len()
|
||||
|
||||
/// Number of 8x8 blocks needed to hold one complete copy of the 256-bit secret.
|
||||
/// ceil(256 / 12) = 22 blocks per copy.
|
||||
const BLOCKS_PER_COPY: usize = (SECRET_BITS + BITS_PER_BLOCK - 1) / BITS_PER_BLOCK; // 22
|
||||
const BLOCKS_PER_COPY: usize = SECRET_BITS.div_ceil(BITS_PER_BLOCK); // 22
|
||||
|
||||
/// Mid-frequency DCT coefficient positions for embedding, specified as
|
||||
/// (row, col) indices into the 8x8 DCT coefficient matrix.
|
||||
@@ -302,9 +302,9 @@ fn read_block_abs(y: &YChannel, px: usize, py: usize) -> Option<[[f64; 8]; 8]> {
|
||||
return None;
|
||||
}
|
||||
let mut block = [[0.0f64; 8]; 8];
|
||||
for row in 0..8 {
|
||||
for col in 0..8 {
|
||||
block[row][col] = y.get(px + col, py + row);
|
||||
for (row, block_row) in block.iter_mut().enumerate() {
|
||||
for (col, cell) in block_row.iter_mut().enumerate() {
|
||||
*cell = y.get(px + col, py + row);
|
||||
}
|
||||
}
|
||||
Some(block)
|
||||
@@ -323,9 +323,9 @@ fn read_block(y: &YChannel, bx: usize, by: usize, region: &EmbedRegion) -> [[f64
|
||||
fn write_block(y: &mut YChannel, bx: usize, by: usize, region: &EmbedRegion, block: &[[f64; 8]; 8]) {
|
||||
let start_x = region.x_offset + bx * BLOCK_SIZE;
|
||||
let start_y = region.y_offset + by * BLOCK_SIZE;
|
||||
for row in 0..8 {
|
||||
for col in 0..8 {
|
||||
y.set(start_x + col, start_y + row, block[row][col]);
|
||||
for (row, block_row) in block.iter().enumerate() {
|
||||
for (col, &cell) in block_row.iter().enumerate() {
|
||||
y.set(start_x + col, start_y + row, cell);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -349,17 +349,17 @@ fn write_block(y: &mut YChannel, bx: usize, by: usize, region: &EmbedRegion, blo
|
||||
/// where c(0) = sqrt(1/8) and c(k) = sqrt(2/8) for k > 0.
|
||||
fn dct1d(input: &[f64; 8]) -> [f64; 8] {
|
||||
let mut output = [0.0f64; 8];
|
||||
for k in 0..8 {
|
||||
for (k, out_k) in output.iter_mut().enumerate() {
|
||||
let ck = if k == 0 {
|
||||
(1.0 / 8.0_f64).sqrt()
|
||||
} else {
|
||||
(2.0 / 8.0_f64).sqrt()
|
||||
};
|
||||
let mut sum = 0.0;
|
||||
for i in 0..8 {
|
||||
sum += input[i] * ((2 * i + 1) as f64 * k as f64 * PI / 16.0).cos();
|
||||
for (i, &x) in input.iter().enumerate() {
|
||||
sum += x * ((2 * i + 1) as f64 * k as f64 * PI / 16.0).cos();
|
||||
}
|
||||
output[k] = ck * sum;
|
||||
*out_k = ck * sum;
|
||||
}
|
||||
output
|
||||
}
|
||||
@@ -370,17 +370,17 @@ fn dct1d(input: &[f64; 8]) -> [f64; 8] {
|
||||
/// x[i] = sum_{k=0}^{7} c(k) * X[k] * cos((2i+1)*k*pi/16)
|
||||
fn idct1d(input: &[f64; 8]) -> [f64; 8] {
|
||||
let mut output = [0.0f64; 8];
|
||||
for i in 0..8 {
|
||||
for (i, out_i) in output.iter_mut().enumerate() {
|
||||
let mut sum = 0.0;
|
||||
for k in 0..8 {
|
||||
for (k, &x) in input.iter().enumerate() {
|
||||
let ck = if k == 0 {
|
||||
(1.0 / 8.0_f64).sqrt()
|
||||
} else {
|
||||
(2.0 / 8.0_f64).sqrt()
|
||||
};
|
||||
sum += ck * input[k] * ((2 * i + 1) as f64 * k as f64 * PI / 16.0).cos();
|
||||
sum += ck * x * ((2 * i + 1) as f64 * k as f64 * PI / 16.0).cos();
|
||||
}
|
||||
output[i] = sum;
|
||||
*out_i = sum;
|
||||
}
|
||||
output
|
||||
}
|
||||
@@ -501,7 +501,7 @@ fn bytes_to_bits(bytes: &[u8]) -> Vec<u8> {
|
||||
///
|
||||
/// Pads the last byte with zeros if the bit count is not a multiple of 8.
|
||||
fn bits_to_bytes(bits: &[u8]) -> Vec<u8> {
|
||||
let mut bytes = Vec::with_capacity((bits.len() + 7) / 8);
|
||||
let mut bytes = Vec::with_capacity(bits.len().div_ceil(8));
|
||||
for chunk in bits.chunks(8) {
|
||||
let mut byte = 0u8;
|
||||
for (i, &bit) in chunk.iter().enumerate() {
|
||||
|
||||
@@ -52,18 +52,15 @@ pub enum TotpAlgorithm {
|
||||
Sha512,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum TotpKind {
|
||||
#[default]
|
||||
Totp,
|
||||
Hotp { counter: u64 },
|
||||
Steam,
|
||||
}
|
||||
|
||||
impl Default for TotpKind {
|
||||
fn default() -> Self { TotpKind::Totp }
|
||||
}
|
||||
|
||||
/// Compute a TOTP/Steam code for `config` at the given Unix timestamp.
|
||||
///
|
||||
/// For TOTP and Steam: counter = `now_unix_seconds / period_seconds`.
|
||||
|
||||
@@ -85,4 +85,7 @@ pub mod import_lastpass;
|
||||
pub use import_lastpass::{parse_lastpass_csv, ImportWarning};
|
||||
|
||||
pub mod device;
|
||||
pub use device::{DeviceEntry, RevokedEntry, generate_keypair, sign, verify};
|
||||
pub use device::{fingerprint, DeviceEntry, RevokedEntry, generate_keypair, sign, verify};
|
||||
|
||||
pub mod tar_safe;
|
||||
pub use tar_safe::{safe_unpack_git_archive, DEFAULT_MAX_UNCOMPRESSED};
|
||||
|
||||
138
crates/relicario-core/src/tar_safe.rs
Normal file
138
crates/relicario-core/src/tar_safe.rs
Normal file
@@ -0,0 +1,138 @@
|
||||
//! Safe tar unpacking for backup restore.
|
||||
//!
|
||||
//! The standard `tar::Archive::unpack` has no guards against path traversal,
|
||||
//! absolute paths, symlinks, hardlinks, or tar bombs. This module replaces it
|
||||
//! with `safe_unpack_git_archive`, which validates every entry before returning
|
||||
//! `(relative_path, bytes)` pairs to the caller.
|
||||
|
||||
use std::io::Read;
|
||||
use std::path::{Component, PathBuf};
|
||||
|
||||
use tar::EntryType;
|
||||
|
||||
use crate::error::{RelicarioError, Result};
|
||||
|
||||
/// Default cap on total uncompressed bytes extracted in one restore (1 GiB).
|
||||
pub const DEFAULT_MAX_UNCOMPRESSED: u64 = 1024 * 1024 * 1024;
|
||||
|
||||
/// Decode `tar_bytes` and return `(relative_path, file_bytes)` pairs for
|
||||
/// regular files only.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns `Err(RelicarioError::BackupRestore(...))` if:
|
||||
///
|
||||
/// - Any path component is `..` (`Component::ParentDir`) — "path traversal blocked".
|
||||
/// - Any path starts with `/` (`Component::RootDir`) — "path traversal blocked".
|
||||
/// - Any path has a Windows drive prefix (`Component::Prefix`) — "path traversal blocked".
|
||||
/// - An entry is a symlink or hardlink — "symlink/link rejected".
|
||||
/// - An entry's declared size exceeds `max_uncompressed_bytes` — "size cap exceeded".
|
||||
/// - The running total of all entry sizes exceeds `max_uncompressed_bytes` — "size cap exceeded".
|
||||
/// - An entry has an unexpected type (not regular file, not directory) — "unexpected entry type".
|
||||
pub fn safe_unpack_git_archive(
|
||||
tar_bytes: &[u8],
|
||||
max_uncompressed_bytes: u64,
|
||||
) -> Result<Vec<(PathBuf, Vec<u8>)>> {
|
||||
let mut archive = tar::Archive::new(tar_bytes);
|
||||
let entries = archive
|
||||
.entries()
|
||||
.map_err(|e| RelicarioError::BackupRestore(format!("failed to read tar entries: {e}")))?;
|
||||
|
||||
let mut result: Vec<(PathBuf, Vec<u8>)> = Vec::new();
|
||||
let mut cumulative: u64 = 0;
|
||||
|
||||
for entry in entries {
|
||||
let mut entry = entry.map_err(|e| {
|
||||
RelicarioError::BackupRestore(format!("failed to read tar entry: {e}"))
|
||||
})?;
|
||||
|
||||
let header = entry.header();
|
||||
let entry_type = header.entry_type();
|
||||
|
||||
// Reject symlinks and hardlinks.
|
||||
match entry_type {
|
||||
EntryType::Symlink => {
|
||||
return Err(RelicarioError::BackupRestore(
|
||||
"symlink entry rejected".to_string(),
|
||||
));
|
||||
}
|
||||
EntryType::Link => {
|
||||
return Err(RelicarioError::BackupRestore(
|
||||
"hardlink entry rejected".to_string(),
|
||||
));
|
||||
}
|
||||
EntryType::Directory => {
|
||||
// Directories are implicit — skip without reading body.
|
||||
continue;
|
||||
}
|
||||
EntryType::Regular | EntryType::Continuous | EntryType::GNUSparse => {
|
||||
// These are normal file types; fall through to path checks.
|
||||
}
|
||||
_ => {
|
||||
return Err(RelicarioError::BackupRestore(format!(
|
||||
"unexpected entry type: {:?}",
|
||||
entry_type
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
// Validate the path.
|
||||
let path = entry.path().map_err(|e| {
|
||||
RelicarioError::BackupRestore(format!("invalid path in tar entry: {e}"))
|
||||
})?;
|
||||
let path = path.into_owned();
|
||||
|
||||
for component in path.components() {
|
||||
match component {
|
||||
Component::ParentDir => {
|
||||
return Err(RelicarioError::BackupRestore(
|
||||
"path traversal blocked: entry contains '..' component".to_string(),
|
||||
));
|
||||
}
|
||||
Component::RootDir => {
|
||||
return Err(RelicarioError::BackupRestore(
|
||||
"path traversal blocked: entry has absolute path".to_string(),
|
||||
));
|
||||
}
|
||||
Component::Prefix(_) => {
|
||||
return Err(RelicarioError::BackupRestore(
|
||||
"path traversal blocked: entry has Windows drive prefix".to_string(),
|
||||
));
|
||||
}
|
||||
Component::Normal(_) | Component::CurDir => {
|
||||
// Acceptable components.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check declared size before reading body.
|
||||
let claimed = header.size().map_err(|e| {
|
||||
RelicarioError::BackupRestore(format!("could not read entry size: {e}"))
|
||||
})?;
|
||||
|
||||
if claimed > max_uncompressed_bytes {
|
||||
return Err(RelicarioError::BackupRestore(format!(
|
||||
"size cap exceeded: entry claims {claimed} bytes (cap {max_uncompressed_bytes})"
|
||||
)));
|
||||
}
|
||||
|
||||
let new_total = cumulative.saturating_add(claimed);
|
||||
if new_total > max_uncompressed_bytes {
|
||||
return Err(RelicarioError::BackupRestore(format!(
|
||||
"size cap exceeded: cumulative size would reach {new_total} bytes (cap {max_uncompressed_bytes})"
|
||||
)));
|
||||
}
|
||||
|
||||
// Read the file body.
|
||||
let mut body = Vec::with_capacity(claimed as usize);
|
||||
entry.read_to_end(&mut body).map_err(|e| {
|
||||
RelicarioError::BackupRestore(format!("failed to read entry body: {e}"))
|
||||
})?;
|
||||
|
||||
cumulative += body.len() as u64;
|
||||
|
||||
result.push((path, body));
|
||||
}
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
@@ -19,7 +19,7 @@ impl MonthYear {
|
||||
if !(1..=12).contains(&month) {
|
||||
return Err("month must be 1..=12");
|
||||
}
|
||||
if year < 2000 || year > 2099 {
|
||||
if !(2000..=2099).contains(&year) {
|
||||
return Err("year must be 2000..=2099");
|
||||
}
|
||||
Ok(Self { month, year })
|
||||
|
||||
187
crates/relicario-core/tests/safe_unpack.rs
Normal file
187
crates/relicario-core/tests/safe_unpack.rs
Normal file
@@ -0,0 +1,187 @@
|
||||
use std::path::PathBuf;
|
||||
use tar::{Builder, Header, EntryType};
|
||||
use relicario_core::safe_unpack_git_archive;
|
||||
|
||||
/// Craft a raw POSIX ustar tar with a single entry using the given raw path bytes.
|
||||
/// The tar crate's `Builder` sanitises paths, so we write the 512-byte header
|
||||
/// manually to produce truly malicious archives.
|
||||
fn raw_tar_with_path(raw_path: &[u8], content: &[u8]) -> Vec<u8> {
|
||||
let mut buf = vec![0u8; 512]; // one header block
|
||||
|
||||
// Bytes 0-99: name field (null-padded)
|
||||
let name_len = raw_path.len().min(100);
|
||||
buf[..name_len].copy_from_slice(&raw_path[..name_len]);
|
||||
|
||||
// Bytes 100-107: mode = "0000644\0"
|
||||
buf[100..108].copy_from_slice(b"0000644\0");
|
||||
|
||||
// Bytes 108-115: uid
|
||||
buf[108..116].copy_from_slice(b"0000000\0");
|
||||
|
||||
// Bytes 116-123: gid
|
||||
buf[116..124].copy_from_slice(b"0000000\0");
|
||||
|
||||
// Bytes 124-135: size (octal, 11 digits + null)
|
||||
let size_str = format!("{:011o}\0", content.len());
|
||||
buf[124..136].copy_from_slice(size_str.as_bytes());
|
||||
|
||||
// Bytes 136-147: mtime
|
||||
buf[136..148].copy_from_slice(b"00000000000\0");
|
||||
|
||||
// Bytes 148-155: checksum placeholder (spaces during compute)
|
||||
buf[148..156].copy_from_slice(b" ");
|
||||
|
||||
// Byte 156: typeflag = '0' (regular file)
|
||||
buf[156] = b'0';
|
||||
|
||||
// Bytes 257-262: magic "ustar\0"
|
||||
buf[257..263].copy_from_slice(b"ustar\0");
|
||||
// Bytes 263-264: version "00"
|
||||
buf[263..265].copy_from_slice(b"00");
|
||||
|
||||
// Compute checksum (sum of all bytes, checksum field treated as spaces).
|
||||
let checksum: u32 = buf.iter().map(|&b| b as u32).sum();
|
||||
let cksum_str = format!("{:06o}\0 ", checksum);
|
||||
buf[148..156].copy_from_slice(cksum_str.as_bytes());
|
||||
|
||||
// Append padded content blocks.
|
||||
let mut out = buf;
|
||||
if !content.is_empty() {
|
||||
out.extend_from_slice(content);
|
||||
// Pad to 512-byte boundary.
|
||||
let remainder = content.len() % 512;
|
||||
if remainder != 0 {
|
||||
out.extend(vec![0u8; 512 - remainder]);
|
||||
}
|
||||
}
|
||||
|
||||
// Two zero blocks = end-of-archive.
|
||||
out.extend(vec![0u8; 1024]);
|
||||
out
|
||||
}
|
||||
|
||||
/// Build a tar with a raw symlink entry (typeflag = '2').
|
||||
fn raw_symlink_tar() -> Vec<u8> {
|
||||
let mut buf = vec![0u8; 512];
|
||||
|
||||
// name
|
||||
buf[..9].copy_from_slice(b"evil_link");
|
||||
// mode
|
||||
buf[100..108].copy_from_slice(b"0000755\0");
|
||||
// uid/gid
|
||||
buf[108..116].copy_from_slice(b"0000000\0");
|
||||
buf[116..124].copy_from_slice(b"0000000\0");
|
||||
// size = 0
|
||||
buf[124..136].copy_from_slice(b"00000000000\0");
|
||||
// mtime
|
||||
buf[136..148].copy_from_slice(b"00000000000\0");
|
||||
// checksum placeholder
|
||||
buf[148..156].copy_from_slice(b" ");
|
||||
// typeflag = '2' (symlink)
|
||||
buf[156] = b'2';
|
||||
// linkname
|
||||
let target = b"/etc/passwd";
|
||||
buf[157..157 + target.len()].copy_from_slice(target);
|
||||
// magic
|
||||
buf[257..263].copy_from_slice(b"ustar\0");
|
||||
buf[263..265].copy_from_slice(b"00");
|
||||
|
||||
// Compute checksum.
|
||||
let checksum: u32 = buf.iter().map(|&b| b as u32).sum();
|
||||
let cksum_str = format!("{:06o}\0 ", checksum);
|
||||
buf[148..156].copy_from_slice(cksum_str.as_bytes());
|
||||
|
||||
let mut out = buf;
|
||||
out.extend(vec![0u8; 1024]); // end-of-archive
|
||||
out
|
||||
}
|
||||
|
||||
fn build_normal_tar() -> Vec<u8> {
|
||||
let mut buf = Vec::new();
|
||||
{
|
||||
let mut builder = Builder::new(&mut buf);
|
||||
let content = b"hello";
|
||||
let mut header = Header::new_gnu();
|
||||
header.set_entry_type(EntryType::Regular);
|
||||
header.set_size(content.len() as u64);
|
||||
header.set_cksum();
|
||||
builder
|
||||
.append_data(&mut header, "subdir/hello.txt", content.as_ref())
|
||||
.unwrap();
|
||||
builder.finish().unwrap();
|
||||
}
|
||||
buf
|
||||
}
|
||||
|
||||
fn build_oversize_tar() -> Vec<u8> {
|
||||
// Actual 2048-byte body; test will use cap=1024
|
||||
let mut buf = Vec::new();
|
||||
{
|
||||
let mut builder = Builder::new(&mut buf);
|
||||
let content = vec![0u8; 2048];
|
||||
let mut header = Header::new_gnu();
|
||||
header.set_entry_type(EntryType::Regular);
|
||||
header.set_size(content.len() as u64);
|
||||
header.set_cksum();
|
||||
builder
|
||||
.append_data(&mut header, "bigfile.bin", content.as_slice())
|
||||
.unwrap();
|
||||
builder.finish().unwrap();
|
||||
}
|
||||
buf
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restore_rejects_path_traversal() {
|
||||
// Craft a tar with "../../escaped.txt" using raw bytes (Builder sanitises paths).
|
||||
let bytes = raw_tar_with_path(b"../../escaped.txt", b"evil content");
|
||||
let err = safe_unpack_git_archive(&bytes, 1024 * 1024).unwrap_err();
|
||||
let msg = format!("{err:#}");
|
||||
assert!(
|
||||
msg.contains("path traversal") || msg.contains(".."),
|
||||
"got: {msg}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restore_rejects_absolute_path() {
|
||||
// Craft a tar with "/etc/escaped.txt" using raw bytes.
|
||||
let bytes = raw_tar_with_path(b"/etc/escaped.txt", b"evil content");
|
||||
let err = safe_unpack_git_archive(&bytes, 1024 * 1024).unwrap_err();
|
||||
let msg = format!("{err:#}");
|
||||
assert!(
|
||||
msg.contains("path traversal") || msg.contains("absolute"),
|
||||
"got: {msg}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restore_rejects_symlink() {
|
||||
let bytes = raw_symlink_tar();
|
||||
let err = safe_unpack_git_archive(&bytes, 1024 * 1024).unwrap_err();
|
||||
let msg = format!("{err:#}");
|
||||
assert!(
|
||||
msg.contains("symlink") || msg.contains("link"),
|
||||
"got: {msg}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restore_rejects_size_bomb() {
|
||||
let bytes = build_oversize_tar(); // actual 2048-byte entry
|
||||
let err = safe_unpack_git_archive(&bytes, 1024).unwrap_err(); // cap = 1024 bytes
|
||||
let msg = format!("{err:#}");
|
||||
assert!(
|
||||
msg.contains("size") || msg.contains("cap") || msg.contains("too large"),
|
||||
"got: {msg}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restore_accepts_normal_files() {
|
||||
let buf = build_normal_tar();
|
||||
let entries = safe_unpack_git_archive(&buf, 1024 * 1024).expect("happy path");
|
||||
assert_eq!(entries.len(), 1);
|
||||
assert_eq!(entries[0].0, PathBuf::from("subdir/hello.txt"));
|
||||
assert_eq!(entries[0].1, b"hello");
|
||||
}
|
||||
@@ -9,3 +9,10 @@ anyhow = "1"
|
||||
clap = { version = "4", features = ["derive"] }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
tempfile = "3"
|
||||
regex = "1"
|
||||
|
||||
[dev-dependencies]
|
||||
assert_cmd = "2"
|
||||
predicates = "3"
|
||||
tempfile = "3"
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! relicario-server -- pre-receive hook for signature verification.
|
||||
|
||||
use std::fs;
|
||||
use std::process::Command;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
@@ -34,49 +35,120 @@ fn main() -> Result<()> {
|
||||
}
|
||||
|
||||
fn verify_commit(commit: &str) -> Result<()> {
|
||||
// Get devices.json at this commit
|
||||
let devices_json = match git_show(commit, ".relicario/devices.json") {
|
||||
Ok(json) => json,
|
||||
Err(_) => {
|
||||
// No devices.json yet -- bootstrap mode, allow unsigned
|
||||
eprintln!("OK: commit {} (bootstrap - no devices.json)", commit);
|
||||
eprintln!("OK: commit {commit} (bootstrap - no devices.json)");
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
let devices: Vec<DeviceEntry> = serde_json::from_str(&devices_json)
|
||||
.context("parse devices.json")?;
|
||||
|
||||
// Bootstrap: if devices.json is empty, allow unsigned
|
||||
if devices.is_empty() {
|
||||
eprintln!("OK: commit {} (bootstrap - empty devices.json)", commit);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Get revoked.json (may not exist)
|
||||
let revoked: Vec<RevokedEntry> = git_show(commit, ".relicario/revoked.json")
|
||||
.ok()
|
||||
.and_then(|s| serde_json::from_str(&s).ok())
|
||||
.unwrap_or_default();
|
||||
|
||||
// Get commit signature
|
||||
// True bootstrap: no devices ever registered and none revoked.
|
||||
if devices.is_empty() && revoked.is_empty() {
|
||||
eprintln!("OK: commit {commit} (bootstrap - no devices registered)");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Build temp allowed-signers file from registered devices.
|
||||
let tmp = tempfile::tempdir().context("create tempdir")?;
|
||||
let allowed_path = tmp.path().join("allowed_signers");
|
||||
let mut allowed_body = String::new();
|
||||
for d in &devices {
|
||||
allowed_body.push_str("relicario ");
|
||||
allowed_body.push_str(d.public_key.trim());
|
||||
allowed_body.push('\n');
|
||||
}
|
||||
fs::write(&allowed_path, &allowed_body).context("write allowed_signers")?;
|
||||
|
||||
// Run git verify-commit --raw. Capture both exit code and stderr.
|
||||
// NOTE: we do NOT short-circuit on non-zero exit here because even for
|
||||
// unregistered keys git still outputs "Good ... key SHA256:..." on stderr.
|
||||
let output = Command::new("git")
|
||||
.args(["verify-commit", "--raw", commit])
|
||||
.env("GIT_CONFIG_COUNT", "1")
|
||||
.env("GIT_CONFIG_KEY_0", "gpg.ssh.allowedSignersFile")
|
||||
.env("GIT_CONFIG_VALUE_0", allowed_path.as_os_str())
|
||||
.output()
|
||||
.context("git verify-commit")?;
|
||||
|
||||
// Check if signed
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
if !stderr.contains("GOODSIG") && !stderr.contains("Good signature") {
|
||||
eprintln!("REJECT: commit {} is not signed by a registered device", commit);
|
||||
|
||||
// Parse the SHA-256 fingerprint from stderr.
|
||||
// SSH signature output: "Good "git" signature ... with ED25519 key SHA256:<base64>"
|
||||
let re = regex::Regex::new(r"key (SHA256:[A-Za-z0-9+/]+)").expect("static regex");
|
||||
let signing_fp = match re.captures(&stderr).and_then(|c| c.get(1)) {
|
||||
Some(m) => m.as_str().to_string(),
|
||||
None => {
|
||||
// No fingerprint in stderr = unsigned or completely malformed signature.
|
||||
eprintln!(
|
||||
"REJECT: commit {commit} — no valid signature found (stderr: {})",
|
||||
stderr.trim()
|
||||
);
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
|
||||
// Build fingerprint → entry maps.
|
||||
let mut device_by_fp: std::collections::HashMap<String, &DeviceEntry> =
|
||||
std::collections::HashMap::new();
|
||||
for d in &devices {
|
||||
if let Ok(fp) = relicario_core::device::fingerprint(&d.public_key) {
|
||||
device_by_fp.insert(fp, d);
|
||||
}
|
||||
}
|
||||
|
||||
let mut revoked_by_fp: std::collections::HashMap<String, &RevokedEntry> =
|
||||
std::collections::HashMap::new();
|
||||
for r in &revoked {
|
||||
if let Ok(fp) = relicario_core::device::fingerprint(&r.public_key) {
|
||||
revoked_by_fp.insert(fp, r);
|
||||
}
|
||||
}
|
||||
|
||||
// Get committer date (NOT author date).
|
||||
let ct_out = Command::new("git")
|
||||
.args(["show", "-s", "--format=%ct", commit])
|
||||
.output()
|
||||
.context("git show committer date")?;
|
||||
let committer_ts: i64 = String::from_utf8_lossy(&ct_out.stdout)
|
||||
.trim()
|
||||
.parse()
|
||||
.context("parse committer timestamp")?;
|
||||
|
||||
// Check revocation FIRST (revoked entries may not be in devices anymore).
|
||||
if let Some(r) = revoked_by_fp.get(&signing_fp) {
|
||||
if committer_ts >= r.revoked_at {
|
||||
eprintln!(
|
||||
"REJECT: commit {commit} — signed by revoked device '{}' \
|
||||
(committer ts {committer_ts} >= revoked_at {})",
|
||||
r.name, r.revoked_at
|
||||
);
|
||||
std::process::exit(1);
|
||||
}
|
||||
// Historical commit: committer_ts < revoked_at → was valid when signed.
|
||||
eprintln!(
|
||||
"OK: commit {commit} — historical commit signed by '{}' before revocation",
|
||||
r.name
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Not revoked — must be in active devices.
|
||||
if !device_by_fp.contains_key(&signing_fp) {
|
||||
eprintln!(
|
||||
"REJECT: commit {commit} — signed by unregistered device (fingerprint {signing_fp})"
|
||||
);
|
||||
std::process::exit(1);
|
||||
}
|
||||
|
||||
// Ensure the signing key is not revoked.
|
||||
// The allowed-signers file approach means git verify-commit already checks
|
||||
// against the list; we additionally guard against revoked.json entries.
|
||||
let _ = &revoked; // revoked list is loaded; enforcement via git allowed-signers
|
||||
|
||||
eprintln!("OK: commit {} verified", commit);
|
||||
eprintln!("OK: commit {commit} verified (signed by '{}')", device_by_fp[&signing_fp].name);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
230
crates/relicario-server/tests/verify_commit.rs
Normal file
230
crates/relicario-server/tests/verify_commit.rs
Normal file
@@ -0,0 +1,230 @@
|
||||
//! Acceptance tests for `relicario-server verify-commit`.
|
||||
//!
|
||||
//! Four scenarios from audit S1:
|
||||
//! 1. Registered non-revoked key → exit 0
|
||||
//! 2. Unregistered key → exit 1 (stderr contains "unregistered")
|
||||
//! 3. Revoked key, commit AFTER revoked_at → exit 1 (stderr contains "revoked")
|
||||
//! 4. Revoked key, commit BEFORE revoked_at (historical) → exit 0
|
||||
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
use assert_cmd::Command as AssertCommand;
|
||||
use predicates::prelude::*;
|
||||
use relicario_core::device::{generate_keypair, DeviceEntry, RevokedEntry};
|
||||
use tempfile::TempDir;
|
||||
|
||||
fn write_keypair(dir: &Path, name: &str) -> (PathBuf, PathBuf, String) {
|
||||
let (priv_pem, pub_line) = generate_keypair().expect("generate keypair");
|
||||
let priv_path = dir.join(format!("{name}.key"));
|
||||
let pub_path = dir.join(format!("{name}.pub"));
|
||||
fs::write(&priv_path, priv_pem.as_str()).unwrap();
|
||||
fs::write(&pub_path, &pub_line).unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
fs::set_permissions(&priv_path, fs::Permissions::from_mode(0o600)).unwrap();
|
||||
}
|
||||
(priv_path, pub_path, pub_line)
|
||||
}
|
||||
|
||||
fn git(repo: &Path, args: &[&str], extra_env: &[(&str, &str)]) {
|
||||
let mut cmd = Command::new("git");
|
||||
cmd.current_dir(repo).args(args);
|
||||
for (k, v) in extra_env {
|
||||
cmd.env(k, v);
|
||||
}
|
||||
let status = cmd.status().expect("spawn git");
|
||||
assert!(status.success(), "git {args:?} failed");
|
||||
}
|
||||
|
||||
fn init_repo(repo: &Path) {
|
||||
git(repo, &["init", "-q", "-b", "main"], &[]);
|
||||
git(repo, &["config", "user.email", "test@test"], &[]);
|
||||
git(repo, &["config", "user.name", "test"], &[]);
|
||||
git(repo, &["commit", "--allow-empty", "-q", "-m", "init"], &[]);
|
||||
}
|
||||
|
||||
fn sign_commit(
|
||||
repo: &Path,
|
||||
signing_key: &Path,
|
||||
allowed_signers: &Path,
|
||||
committer_unix: i64,
|
||||
msg: &str,
|
||||
file_path: &str,
|
||||
file_content: &str,
|
||||
) -> String {
|
||||
fs::write(repo.join(file_path), file_content).unwrap();
|
||||
git(repo, &["add", file_path], &[]);
|
||||
let date = format!("@{committer_unix} +0000");
|
||||
git(
|
||||
repo,
|
||||
&[
|
||||
"-c", "gpg.format=ssh",
|
||||
"-c", &format!("user.signingkey={}", signing_key.display()),
|
||||
"-c", &format!("gpg.ssh.allowedSignersFile={}", allowed_signers.display()),
|
||||
"commit", "-S", "-q", "-m", msg,
|
||||
],
|
||||
&[
|
||||
("GIT_AUTHOR_DATE", &date),
|
||||
("GIT_COMMITTER_DATE", &date),
|
||||
],
|
||||
);
|
||||
let out = Command::new("git")
|
||||
.current_dir(repo)
|
||||
.args(["rev-parse", "HEAD"])
|
||||
.output()
|
||||
.unwrap();
|
||||
String::from_utf8(out.stdout).unwrap().trim().to_string()
|
||||
}
|
||||
|
||||
fn write_device_files(repo: &Path, devices: &[DeviceEntry], revoked: &[RevokedEntry]) {
|
||||
let dir = repo.join(".relicario");
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
fs::write(dir.join("devices.json"), serde_json::to_string_pretty(devices).unwrap()).unwrap();
|
||||
fs::write(dir.join("revoked.json"), serde_json::to_string_pretty(revoked).unwrap()).unwrap();
|
||||
git(repo, &["add", ".relicario"], &[]);
|
||||
git(repo, &["commit", "-q", "-m", "device files"], &[]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registered_non_revoked_key_accepted() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let repo = tmp.path();
|
||||
init_repo(repo);
|
||||
|
||||
let (priv_a, _, pub_a) = write_keypair(repo, "alice");
|
||||
write_device_files(
|
||||
repo,
|
||||
&[DeviceEntry {
|
||||
name: "alice".into(),
|
||||
public_key: pub_a.clone(),
|
||||
added_at: 1_700_000_000,
|
||||
added_by: "bootstrap".into(),
|
||||
}],
|
||||
&[],
|
||||
);
|
||||
|
||||
let allowed = repo.join("test_allowed_signers");
|
||||
fs::write(&allowed, format!("relicario {}\n", pub_a.trim())).unwrap();
|
||||
|
||||
let sha = sign_commit(repo, &priv_a, &allowed, 1_710_000_000, "x", "a.txt", "hi");
|
||||
|
||||
AssertCommand::cargo_bin("relicario-server")
|
||||
.unwrap()
|
||||
.current_dir(repo)
|
||||
.args(["verify-commit", &sha])
|
||||
.assert()
|
||||
.success();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unregistered_key_rejected() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let repo = tmp.path();
|
||||
init_repo(repo);
|
||||
|
||||
let (_, _, pub_a) = write_keypair(repo, "alice");
|
||||
let (priv_evil, _, pub_evil) = write_keypair(repo, "evil");
|
||||
|
||||
// Only Alice is registered.
|
||||
write_device_files(
|
||||
repo,
|
||||
&[DeviceEntry {
|
||||
name: "alice".into(),
|
||||
public_key: pub_a.clone(),
|
||||
added_at: 1_700_000_000,
|
||||
added_by: "bootstrap".into(),
|
||||
}],
|
||||
&[],
|
||||
);
|
||||
|
||||
// Evil signs against a file containing both keys so git commit signing works,
|
||||
// but the binary's allowed-signers (from devices.json) only has Alice.
|
||||
let allowed = repo.join("test_allowed_signers");
|
||||
fs::write(
|
||||
&allowed,
|
||||
format!("relicario {}\nrelicario {}\n", pub_a.trim(), pub_evil.trim()),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let sha = sign_commit(repo, &priv_evil, &allowed, 1_710_000_000, "evil", "a.txt", "hi");
|
||||
|
||||
AssertCommand::cargo_bin("relicario-server")
|
||||
.unwrap()
|
||||
.current_dir(repo)
|
||||
.args(["verify-commit", &sha])
|
||||
.assert()
|
||||
.failure()
|
||||
.stderr(predicate::str::contains("unregistered"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn revoked_key_after_revoked_at_rejected() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let repo = tmp.path();
|
||||
init_repo(repo);
|
||||
|
||||
let (priv_a, _, pub_a) = write_keypair(repo, "alice");
|
||||
|
||||
// Alice's entry is only in revoked.json (was removed from devices.json after revocation).
|
||||
write_device_files(
|
||||
repo,
|
||||
&[],
|
||||
&[RevokedEntry {
|
||||
name: "alice".into(),
|
||||
public_key: pub_a.clone(),
|
||||
revoked_at: 1_705_000_000,
|
||||
revoked_by: "admin".into(),
|
||||
}],
|
||||
);
|
||||
|
||||
let allowed = repo.join("test_allowed_signers");
|
||||
fs::write(&allowed, format!("relicario {}\n", pub_a.trim())).unwrap();
|
||||
|
||||
// Commit dated AFTER revocation.
|
||||
let sha = sign_commit(repo, &priv_a, &allowed, 1_710_000_000, "post", "a.txt", "hi");
|
||||
|
||||
AssertCommand::cargo_bin("relicario-server")
|
||||
.unwrap()
|
||||
.current_dir(repo)
|
||||
.args(["verify-commit", &sha])
|
||||
.assert()
|
||||
.failure()
|
||||
.stderr(predicate::str::contains("revoked"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn revoked_key_before_revoked_at_accepted_historical() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let repo = tmp.path();
|
||||
init_repo(repo);
|
||||
|
||||
let (priv_a, _, pub_a) = write_keypair(repo, "alice");
|
||||
|
||||
// Same as above: Alice only in revoked.json.
|
||||
write_device_files(
|
||||
repo,
|
||||
&[],
|
||||
&[RevokedEntry {
|
||||
name: "alice".into(),
|
||||
public_key: pub_a.clone(),
|
||||
revoked_at: 1_705_000_000,
|
||||
revoked_by: "admin".into(),
|
||||
}],
|
||||
);
|
||||
|
||||
let allowed = repo.join("test_allowed_signers");
|
||||
fs::write(&allowed, format!("relicario {}\n", pub_a.trim())).unwrap();
|
||||
|
||||
// Commit dated BEFORE revocation -- historical case must pass.
|
||||
let sha = sign_commit(repo, &priv_a, &allowed, 1_700_000_000, "historical", "a.txt", "hi");
|
||||
|
||||
AssertCommand::cargo_bin("relicario-server")
|
||||
.unwrap()
|
||||
.current_dir(repo)
|
||||
.args(["verify-commit", &sha])
|
||||
.assert()
|
||||
.success();
|
||||
}
|
||||
@@ -83,8 +83,9 @@ vault_salt ────────►│ │
|
||||
|
||||
┌──────────────────┐
|
||||
master_key ────────►│ XChaCha20- │──────► manifest.enc
|
||||
empty manifest ────►│ Poly1305 │
|
||||
└──────────────────┘
|
||||
empty manifest ────►│ Poly1305 │ settings.enc
|
||||
default settings ──►│ encrypt (×2) │ (parallel artifacts;
|
||||
└──────────────────┘ independent nonces)
|
||||
|
||||
┌──────────────────┐
|
||||
│ git init │──────► vault repo
|
||||
@@ -92,6 +93,14 @@ empty manifest ────►│ Poly1305 │
|
||||
└──────────────────┘
|
||||
```
|
||||
|
||||
Item creation, the typed-item envelope (`Item` + per-type `ItemCore`),
|
||||
attachment encryption, and field-history tracking are not shown above —
|
||||
they are described in [`crates/relicario-core/ARCHITECTURE.md`](../crates/relicario-core/ARCHITECTURE.md).
|
||||
The flow above covers only the crypto-pipeline shape that vault init
|
||||
establishes; the per-item lifecycle reuses the same `master_key` +
|
||||
XChaCha20-Poly1305 primitives against `items/<id>.enc` and
|
||||
`attachments/<item-id>/<aid>.enc`.
|
||||
|
||||
## Unlock Flow (every vault operation)
|
||||
|
||||
```
|
||||
|
||||
@@ -48,6 +48,19 @@ When enabled, device authentication provides:
|
||||
- **Push access control**: Deploy keys managed via Gitea API
|
||||
- **Instant revocation**: One command cuts off both signing and push
|
||||
|
||||
Enforcement requires deploying the `relicario-server` pre-receive hook
|
||||
on the vault remote. The crate provides two subcommands:
|
||||
|
||||
- `relicario-server generate-hook` — emits the hook script to install at
|
||||
`<repo>/hooks/pre-receive`
|
||||
- `relicario-server verify-commit <sha>` — checks one commit's signature
|
||||
against `.relicario/devices.json` and `.relicario/revoked.json` as of
|
||||
that commit; the hook calls this for every pushed ref
|
||||
|
||||
Without the server hook, signed commits provide authorship metadata only
|
||||
— any process with push access can land an unsigned commit, since
|
||||
verification is otherwise advisory.
|
||||
|
||||
See `docs/superpowers/specs/2026-05-02-device-authentication-design.md`.
|
||||
|
||||
## Access Control
|
||||
@@ -57,5 +70,35 @@ Without device authentication, access control is transport-layer only:
|
||||
- **CLI**: SSH key authentication to git remote
|
||||
- **Extension**: Git credentials in browser storage
|
||||
|
||||
Device registration was optional before v0.4.0. With device auth enabled,
|
||||
all commits must be signed by a registered device.
|
||||
Device registration is optional but recommended for shared vaults.
|
||||
|
||||
## Configuration env vars
|
||||
|
||||
Relicario reads the following environment variables. Each is a trust
|
||||
boundary: an attacker who can set them in the user's environment can
|
||||
influence Relicario's behavior. They are listed here for security
|
||||
reviewers to audit the surface in one place.
|
||||
|
||||
### User-facing (active in all builds)
|
||||
|
||||
| Variable | Purpose | Trust |
|
||||
|---|---|---|
|
||||
| `RELICARIO_IMAGE` | Override the reference-image JPEG path used during vault unlock. | Trusted: filesystem path under the user's control. Read-only; its bytes feed `imgsecret::extract_secret`. |
|
||||
| `RELICARIO_GITEA_URL` | Gitea API base URL for `relicario device add`. Equivalent to `--gitea-url`. | Trusted: HTTPS URL. Used only in the device-add code path. |
|
||||
| `RELICARIO_GITEA_TOKEN` | Gitea personal-access token. Equivalent to `--gitea-token`. | **Secret**: anyone who can read this env var can manage the user's deploy keys via the Gitea API. The CLI never logs it. |
|
||||
| `RELICARIO_GITEA_OWNER` | Gitea repository owner (e.g. `alee`). Equivalent to `--owner`. | Trusted: opaque string. |
|
||||
| `RELICARIO_GITEA_REPO` | Gitea repository name (e.g. `vault`). Equivalent to `--repo`. | Trusted: opaque string. |
|
||||
|
||||
### Debug-only (compiled out of `cargo build --release`)
|
||||
|
||||
The following variables are gated behind `cfg(debug_assertions)` and
|
||||
are **no-ops** in release builds. The env-var lookup is removed by the
|
||||
optimiser from any binary built without debug assertions (i.e. the
|
||||
standard `--release` profile).
|
||||
|
||||
| Variable | Purpose |
|
||||
|---|---|
|
||||
| `RELICARIO_NO_GROUPS_CACHE` | Suppress the plaintext `groups.cache` write. Developer debugging tool for the cache logic. |
|
||||
| `RELICARIO_TEST_PASSPHRASE` | Bypass the `rpassword` prompt during integration tests. |
|
||||
| `RELICARIO_TEST_ITEM_SECRET` | Bypass the `rpassword` prompt for item-secret fields during integration tests. |
|
||||
| `RELICARIO_TEST_BACKUP_PASSPHRASE` | Bypass the `rpassword` prompt for backup export/restore passphrases during integration tests. |
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Architecture overview — Relicario
|
||||
|
||||
This is the cross-codebase entry point. It describes how the three Relicario codebases fit together, the contracts that flow between them, and the conventions they share. It is **deliberately thin**; the deep content lives in per-codebase docs.
|
||||
This is the cross-codebase entry point. It describes how the four Relicario codebases fit together, the contracts that flow between them, and the conventions they share. It is **deliberately thin**; the deep content lives in per-codebase docs.
|
||||
|
||||
> If you are about to make a change in a single codebase, read its `ARCHITECTURE.md` first:
|
||||
>
|
||||
@@ -10,44 +10,48 @@ This is the cross-codebase entry point. It describes how the three Relicario cod
|
||||
>
|
||||
> If you want historical *why*, see `docs/superpowers/specs/` — those are time-stamped decision artifacts. This overview describes what *is*.
|
||||
|
||||
## The three codebases
|
||||
## The four codebases
|
||||
|
||||
```
|
||||
┌─────────────────────┐
|
||||
│ relicario-core │
|
||||
│ (Rust, no I/O) │
|
||||
│ crypto · items │
|
||||
│ manifest · stego │
|
||||
└──────────┬──────────┘
|
||||
│
|
||||
┌─────────────────────┼─────────────────────┐
|
||||
│ │ │
|
||||
▼ ▼ ▼
|
||||
┌────────────────┐ ┌────────────────────┐ (compiled to WASM
|
||||
│ relicario-cli │ │ relicario-wasm │ inside the )
|
||||
│ (Rust binary) │ │ (#[wasm_bindgen] │ extension │
|
||||
│ │ │ bindings) │ │
|
||||
│ filesystem + │ │ │ │
|
||||
│ git + │ └────────┬───────────┘ │
|
||||
│ clap UX │ │ │
|
||||
└────────────────┘ ▼ │
|
||||
┌─────────────────────┐ │
|
||||
│ extension │ │
|
||||
│ (TypeScript) │ │
|
||||
│ popup · vault │ │
|
||||
│ setup · content │ │
|
||||
│ service worker │ │
|
||||
└─────────────────────┘
|
||||
┌─────────────────────┐
|
||||
│ relicario-core │
|
||||
│ (Rust, no I/O) │
|
||||
│ crypto · items │
|
||||
│ manifest · stego │
|
||||
│ device keys + fp │
|
||||
└──┬───────────┬──────┘
|
||||
│ │
|
||||
┌────────────────┼───────────┴──────┬────────────────────┐
|
||||
│ │ │ │
|
||||
▼ ▼ ▼ ▼
|
||||
┌────────────────┐ ┌──────────────────┐ ┌────────────────────┐
|
||||
│ relicario-cli │ │ relicario-server │ │ relicario-wasm │
|
||||
│ (Rust binary) │ │ (Rust binary) │ │ (#[wasm_bindgen] │
|
||||
│ │ │ │ │ bindings) │
|
||||
│ filesystem + │ │ pre-receive hook │ │ │
|
||||
│ git + │ │ verify-commit + │ │ compiled to WASM │
|
||||
│ clap UX │ │ generate-hook │ │ for the extension │
|
||||
└────────────────┘ └──────────────────┘ └──────────┬─────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────────┐
|
||||
│ extension │
|
||||
│ (TypeScript) │
|
||||
│ popup · vault │
|
||||
│ setup · content │
|
||||
│ service worker │
|
||||
└─────────────────────┘
|
||||
```
|
||||
|
||||
| Codebase | Language | Role | Key boundary |
|
||||
|---|---|---|---|
|
||||
| `relicario-core` | Rust | Crypto, item types, manifest, attachments, imgsecret, generators. Pure, no I/O. | Only `bytes-in / bytes-out`. No filesystem, no git, no network. |
|
||||
| `relicario-core` | Rust | Crypto, item types, manifest, attachments, imgsecret, generators, device keys / fingerprints. Pure, no I/O. | Only `bytes-in / bytes-out`. No filesystem, no git, no network. |
|
||||
| `relicario-cli` | Rust binary | Wraps core with filesystem ops, git plumbing, clap UX. | Only entry point that runs without a browser; sole working interface during disaster recovery. |
|
||||
| `relicario-wasm` | Rust → WASM | Thin `#[wasm_bindgen]` exports from core for the extension. | Compiles `relicario-core` to WASM; no extra logic. |
|
||||
| `relicario-server` | Rust binary | Pre-receive Git hook (`verify-commit`) plus hook installer (`generate-hook`) running on the vault remote. Verifies SSH-signed commits against `.relicario/devices.json` and `.relicario/revoked.json`. | Lives on the git server, not on a client device. The only Relicario component the user does not run themselves. Sees only public key material. |
|
||||
| `extension` | TypeScript | Browser-resident UI. Five entry-point bundles (popup, vault tab, setup, content script, service worker). | The service worker is the only crypto holder; popup/vault/content/setup never touch the master key. |
|
||||
|
||||
The CLI and the extension are **at parity**: every user-facing capability lands in both surfaces together. Diverging is allowed only with a documented reason. See the per-codebase docs for which surface owns which user flow.
|
||||
The CLI and the extension are **at parity**: every user-facing capability lands in both surfaces together. Diverging is allowed only with a documented reason. See the per-codebase docs for which surface owns which user flow. The server has no user-facing surface — it is a server-side enforcer of the device-auth invariant the clients already agreed to.
|
||||
|
||||
## Inter-codebase contracts
|
||||
|
||||
@@ -151,6 +155,7 @@ The CLI keeps its master key in process memory; if the process exits or crashes,
|
||||
| Target | Tool | Output | When to run |
|
||||
|---|---|---|---|
|
||||
| Native CLI | `cargo build` (debug or `--release`) | `target/{debug,release}/relicario` | After CLI changes; for distribution |
|
||||
| Server hook | `cargo build -p relicario-server --release` | `target/release/relicario-server` | After server changes; deploy onto the git remote |
|
||||
| Native test suites | `cargo test` (workspace) | — | After any Rust change |
|
||||
| WASM module | `wasm-pack build --target web` (via `npm run build:wasm`) | `extension/wasm/relicario_wasm{,_bg.wasm,.js}` | After core or wasm crate changes |
|
||||
| Chrome extension | `webpack` (`npm run build`) | `extension/dist/` | After TS or WASM changes; for Chrome distribution |
|
||||
@@ -196,6 +201,7 @@ Core tests use **fast Argon2id params** (m=256, t=1, p=1) so they don't take for
|
||||
| A new popup view, vault tab feature, or autofill change | [`extension/ARCHITECTURE.md`](../../extension/ARCHITECTURE.md) |
|
||||
| A new SW message type | `extension/src/shared/messages.ts` (capability sets), then [`extension/ARCHITECTURE.md § Invariants`](../../extension/ARCHITECTURE.md) |
|
||||
| A new GitHost (e.g. GitLab support) | `extension/src/service-worker/git-host.ts` (interface) and existing implementations |
|
||||
| The pre-receive hook / device-auth enforcement | `crates/relicario-server/src/main.rs`, then `docs/superpowers/specs/2026-05-02-device-authentication-design.md` for rationale |
|
||||
| Adding a new item type | core's `item_types/` mod, then CLI's `build_*_item`/`edit_*` helpers, then extension's `popup/components/types/<type>.ts` |
|
||||
| Threat model / why a primitive was chosen | `docs/superpowers/specs/2026-04-11-relicario-design.md` (historical, but authoritative for rationale) |
|
||||
| Format of the import/export feature | `docs/superpowers/specs/2026-04-27-relicario-import-export-design.md` (designed but not yet implemented) |
|
||||
|
||||
165
docs/superpowers/MULTI-AGENT.md
Normal file
165
docs/superpowers/MULTI-AGENT.md
Normal file
@@ -0,0 +1,165 @@
|
||||
# Multi-Agent Development Paradigm
|
||||
|
||||
This repo uses a three-terminal workflow for large development lifts: one Claude Code session acts as **PM** and two act as **senior developers** (Dev-A, Dev-B), each working in their own git worktree on a parallel feature branch.
|
||||
|
||||
A local relay MCP server eliminates manual message copying between terminals — agents call `post_message`/`read_messages` instead of asking the user to copy-paste.
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
| Role | Terminal | Branch | Responsibilities |
|
||||
|------|----------|--------|-----------------|
|
||||
| PM | 1 | `main` (read-only) | Drive doc-audit follow-ups, review PRs, write CHANGELOG, authorize merges and tagging |
|
||||
| Dev-A | 2 | `feature/<release>-plan-a-*` | Implement Plan A tasks in their own worktree |
|
||||
| Dev-B | 3 | `feature/<release>-plan-b-*` | Implement Plan B tasks in their own worktree |
|
||||
| Relay server | 4 | — | Message bus; Ctrl-C to stop at end of lift |
|
||||
|
||||
**User's job:** authorize merges (the PM asks), resolve escalations the PM can't handle, and watch the streams. You are no longer the message bus.
|
||||
|
||||
---
|
||||
|
||||
## Starting a lift
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- [ ] Kickoff prompts exist in `docs/superpowers/coordination/` (generate with the `multi-agent-kickoff` skill if not)
|
||||
- [ ] No uncommitted changes in main that would confuse the devs
|
||||
- [ ] `tools/relay/` is present (run `ls tools/relay/` to confirm)
|
||||
|
||||
### Launch sequence
|
||||
|
||||
```bash
|
||||
# 1. Start the relay server (this terminal becomes the relay log)
|
||||
tools/relay/start.sh # prints copy-paste instructions, then starts server
|
||||
|
||||
# Optional: use a multiplexer to auto-open all four terminals
|
||||
tools/relay/start.sh --tmux # creates tmux session "relay-lift" with 4 windows
|
||||
tools/relay/start.sh --kitty # creates kitty tab "relay" + 3 windows
|
||||
```
|
||||
|
||||
`start.sh` prints the paths to the three kickoff prompt files. In each Claude Code terminal, run `cat <path>` and paste everything below the `---` line as the first message.
|
||||
|
||||
---
|
||||
|
||||
## Coordination protocol
|
||||
|
||||
Agents communicate by posting structured blocks to each other's inboxes. Four message kinds:
|
||||
|
||||
| Kind | Block header | When used |
|
||||
|------|-------------|-----------|
|
||||
| `status` | `## STATUS UPDATE — DEV-*` | After completing a task, getting blocked, or reaching a review-ready state |
|
||||
| `question` | `## QUESTION TO PM — DEV-*` | When a dev needs PM input mid-task |
|
||||
| `directive` | `## DIRECTIVE TO DEV-*` | When PM instructs a dev to proceed, hold, rescope, or approve a PR |
|
||||
| `free` | (none) | Ad-hoc messages not covered by the above |
|
||||
|
||||
A well-formed `status` block:
|
||||
|
||||
```
|
||||
## STATUS UPDATE — DEV-B
|
||||
Time: 2026-05-02T14:30:00-07:00
|
||||
Branch: feature/v0.5.0-plan-b-extension-ux
|
||||
Task: P4 / error-copy map
|
||||
Status: DONE
|
||||
Last commit: abc1234 feat(extension): centralize ERROR_COPY map
|
||||
Tests: green
|
||||
Notes: No issues. Ready for PM review of P4 before starting B1.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Using the relay tools
|
||||
|
||||
All three Claude Code sessions have these tools available when the relay server is running:
|
||||
|
||||
```
|
||||
post_message(from, to, kind, body) → { id }
|
||||
read_messages(for) → RelayMessage[] (drains inbox)
|
||||
list_pending(for) → { count, kinds } (non-destructive)
|
||||
```
|
||||
|
||||
Typical dev flow per task:
|
||||
|
||||
```
|
||||
1. read_messages(for="dev-b") # check for directives before starting
|
||||
2. ... do the work ...
|
||||
3. post_message(from="dev-b", to="pm", kind="status", body="## STATUS UPDATE...")
|
||||
```
|
||||
|
||||
Typical PM flow:
|
||||
|
||||
```
|
||||
1. read_messages(for="pm") # see what devs posted
|
||||
2. ... review ...
|
||||
3. post_message(from="pm", to="dev-b", kind="directive", body="## DIRECTIVE TO DEV-B...")
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## If the relay server isn't running
|
||||
|
||||
Claude Code will show a yellow MCP connection warning for the `relay` server. The tools will be unavailable.
|
||||
|
||||
Agents fall back to the manual protocol: they emit the structured blocks as text and ask the user to copy-paste them to the relevant terminal. This is slower but fully functional — the coordination protocol works either way.
|
||||
|
||||
To restart a crashed server mid-lift:
|
||||
|
||||
```bash
|
||||
tools/relay/start.sh
|
||||
```
|
||||
|
||||
In-flight messages are lost on restart. Any agent with unread messages should re-post them.
|
||||
|
||||
---
|
||||
|
||||
## Generating kickoff prompts
|
||||
|
||||
### Full workflow (spec → plans → kickoff)
|
||||
|
||||
**Step 1 — Write a spec**
|
||||
|
||||
Run the `superpowers:brainstorming` skill. At the end it invokes `superpowers:writing-plans` for each dev stream. Each stream gets its own plan file in `docs/superpowers/plans/`. The spec lives in `docs/superpowers/specs/`.
|
||||
|
||||
**Step 2 — Invoke the kickoff skill**
|
||||
|
||||
Say anything like:
|
||||
- "kick off the multi-agent thing for v0.6.0"
|
||||
- "spin up PM and devs for this release"
|
||||
- "set up the three-terminal paradigm"
|
||||
|
||||
The `multi-agent-kickoff` skill auto-triggers on those phrases. It will:
|
||||
|
||||
1. Auto-discover the spec and plans by date/release label (asks to confirm if ambiguous)
|
||||
2. Generate `docs/superpowers/coordination/<release>-pm-prompt.md` and one `-dev-<letter>-prompt.md` per plan
|
||||
3. Inject the relay paragraph, branch names, worktree paths, test commands, and scope partitioning automatically from the plans and `CLAUDE.md`
|
||||
4. Commit the prompts and print launch instructions
|
||||
|
||||
N>2 devs works automatically — 3 plans produces PM + Dev-A/B/C prompts.
|
||||
|
||||
**Step 3 — Launch**
|
||||
|
||||
```bash
|
||||
tools/relay/start.sh # prints prompt file paths, starts relay server
|
||||
# open N+1 terminals, paste each prompt below its '---' line
|
||||
```
|
||||
|
||||
The skill reminder: run `tools/relay/start.sh` **before** opening the Claude Code sessions — the MCP tools need the server up when each session initializes.
|
||||
|
||||
---
|
||||
|
||||
## Ending a lift
|
||||
|
||||
1. PM emits `REVIEW-COMPLETE` and `MERGE-APPROVED` for each dev's PR
|
||||
2. User merges each PR (the PM session does `gh pr merge` with user authorization)
|
||||
3. PM tags the release (only after explicit user `yes`)
|
||||
4. Ctrl-C the relay terminal — all in-memory messages are discarded
|
||||
|
||||
---
|
||||
|
||||
## Roles and boundaries (quick reference)
|
||||
|
||||
**PM must not:** write feature code, merge without user authorization, tag without user approval, run `git push --force` / `git reset --hard` without asking.
|
||||
|
||||
**Devs must not:** merge their branch to main, push `--force`, run `git reset --hard` without asking.
|
||||
|
||||
**User must:** authorize all merges and the release tag. Everything else is delegated.
|
||||
@@ -5,8 +5,9 @@ Pre-v0.5.0 audit of Relicario's documentation against the current codebase.
|
||||
## Summary
|
||||
|
||||
- **Total findings:** 14
|
||||
- **Fixed inline:** 6
|
||||
- **Need user input (proposed only):** 8
|
||||
- **Fixed inline (initial pass):** 6
|
||||
- **Fixed during v0.5.0 PM run (this audit, follow-up commits):** 8
|
||||
- **No action needed:** 0
|
||||
- **Top 3 recommendations:**
|
||||
1. **Add `relicario-server` to architecture docs.** It exists in `crates/`, is referenced by SECURITY.md, and underpins device-auth, but `docs/architecture/overview.md`'s "three codebases" framing and `CLAUDE.md`'s project-structure tree still pretend it doesn't exist (Findings 1, 2, 9). This is the single biggest gap before tagging v0.5.0.
|
||||
2. **Replace `CLAUDE.md`'s Roadmap.** It still says "Next: WASM build + Chrome MV3 browser extension (Plan 2)" — a milestone that shipped weeks ago. Multiple subsequent train rounds (typed items, attachments, backup, LastPass, device auth, fullscreen UX phases) have shipped, none of which are reflected (Finding 3).
|
||||
@@ -24,7 +25,7 @@ The codebase itself is well-documented — `crates/{relicario-core,relicario-cli
|
||||
**Issue:** The repo now has **four** Rust crates (`relicario-core`, `relicario-cli`, `relicario-wasm`, `relicario-server`) plus the extension. The framing "The three codebases" + accompanying ASCII diagram + four-row table all predate the May 2026 server crate. `relicario-server` is the pre-receive hook binary that enforces device-signature verification — load-bearing for the device-auth model that SECURITY.md already advertises.
|
||||
**Fix:** Re-title the section ("The four codebases" or "The relicario codebases"), add a server box to the diagram, add a row to the table. The role is "Pre-receive Git hook that verifies commit signatures against `.relicario/devices.json` and `.relicario/revoked.json`".
|
||||
**Severity:** must-fix-before-v0.5.0
|
||||
**Status:** Proposed; needs user decision (>50 words of new prose; touches the framing of the whole overview doc)
|
||||
**Status:** Fixed in `ca059e7` (PM follow-up, 2026-05-02): "four codebases" framing, ASCII diagram fans core out to cli + server + wasm, table row added, build matrix gains `cargo build -p relicario-server`, "Where to look next" points at server src + design spec.
|
||||
|
||||
---
|
||||
|
||||
@@ -34,7 +35,7 @@ The codebase itself is well-documented — `crates/{relicario-core,relicario-cli
|
||||
**Issue:** The `crates/` tree only lists `relicario-core/`, `relicario-cli/`, `relicario-wasm/`. `relicario-server/` is missing. Since CLAUDE.md is the project-level summary every Claude session reads, this is the highest-leverage staleness.
|
||||
**Fix:** Add a fourth crate entry for `relicario-server/` with `src/main.rs # pre-receive hook: verify_commit + generate_hook`.
|
||||
**Severity:** must-fix-before-v0.5.0
|
||||
**Status:** Proposed; needs user decision (CLAUDE.md is user-controlled per audit constraints)
|
||||
**Status:** Fixed in `8fd9a05` (PM follow-up, 2026-05-02 with user approval): added `relicario-server/` entry to project tree.
|
||||
|
||||
---
|
||||
|
||||
@@ -44,7 +45,7 @@ The codebase itself is well-documented — `crates/{relicario-core,relicario-cli
|
||||
**Issue:** Says `Next: WASM build + Chrome MV3 browser extension (Plan 2). Then mobile (Rust core compiles to ARM).` Plan 2 (extension) shipped, then Plans 1A-1C, 3A (backup), 3B (LastPass), Plan 4 (security fixes + device auth), and Phases 1-2B of the fullscreen UX redesign all shipped. The current "next thing" per project memory is v0.5.0 polish + harden plus Phase 3/4 of fullscreen UX.
|
||||
**Fix:** Replace with a current-state Roadmap line (e.g. `Next: v0.5.0 polish + harden, then Phase 3 (vault tab shell). Mobile (ARM) and recovery QR remain on the roadmap.`).
|
||||
**Severity:** must-fix-before-v0.5.0
|
||||
**Status:** Proposed; needs user decision (CLAUDE.md is user-controlled; phrasing is a judgment call)
|
||||
**Status:** Fixed in `8fd9a05` (PM follow-up, 2026-05-02 with user approval): replaced with the v0.5.0 / Phases 3-4 / 1C-γ / LastPass / mobile / recovery-QR picture.
|
||||
|
||||
---
|
||||
|
||||
@@ -54,7 +55,7 @@ The codebase itself is well-documented — `crates/{relicario-core,relicario-cli
|
||||
**Issue:** Audit M8 bumped `ItemId`/`FieldId` to 16-char hex (64 bits). Verified against `crates/relicario-core/src/ids.rs:3-4, 35-37` and `tests/integration` — they're 16 hex chars. The same line also doesn't mention that `AttachmentId` was bumped to 32 hex chars / 128 bits (audit I2/B4).
|
||||
**Fix:** Change to: `Item IDs and Field IDs are random 16-char hex strings (64 bits of OsRng entropy). AttachmentIds are content-addressed: first 32 hex chars of SHA-256(plaintext) (128 bits, audit I2/B4).`
|
||||
**Severity:** must-fix-before-v0.5.0
|
||||
**Status:** Proposed; needs user decision (CLAUDE.md is user-controlled)
|
||||
**Status:** Fixed in `8fd9a05` (PM follow-up, 2026-05-02 with user approval): now reads "Item IDs and Field IDs are random 16-char hex strings (64 bits of OsRng entropy). AttachmentIds are content-addressed: first 32 hex chars of SHA-256 over the plaintext (128 bits)."
|
||||
|
||||
---
|
||||
|
||||
@@ -114,7 +115,7 @@ The codebase itself is well-documented — `crates/{relicario-core,relicario-cli
|
||||
**Issue:** The vault-creation pipeline in this doc shows `master_key → XChaCha20-Poly1305 → manifest.enc` only. In reality `cmd_init` also encrypts and writes `settings.enc` (default `VaultSettings`). Field-history-tracked items, attachments, the `Item` envelope shape — none of these are in the flow doc. Without context on typed items, a new contributor reading this doc would have a v0.1-era model of the system.
|
||||
**Fix:** Add a settings.enc step to the flow; either expand the items section or note that the full item lifecycle is in `crates/relicario-core/ARCHITECTURE.md`.
|
||||
**Severity:** nice-to-have (the per-codebase ARCHITECTURE.md files are the source of truth; this top-level doc could just point at them)
|
||||
**Status:** Proposed; needs user decision (>50 words of new prose, design choice between rewriting vs trimming)
|
||||
**Status:** Fixed in `76d092d` (PM follow-up, 2026-05-02): trim path. Added settings.enc as a parallel artifact in the encrypt step, then a short paragraph pointing at `crates/relicario-core/ARCHITECTURE.md` for the per-item lifecycle.
|
||||
|
||||
---
|
||||
|
||||
@@ -124,7 +125,7 @@ The codebase itself is well-documented — `crates/{relicario-core,relicario-cli
|
||||
**Issue:** Says `Device registration was optional before v0.4.0. With device auth enabled, all commits must be signed by a registered device.` But (a) v0.4.0 hasn't been tagged yet — the changelog goes v0.1.0 → v0.2.0 → "Unreleased", and the next tag-in-flight per project memory is v0.5.0; (b) per the v0.5.0 polish + harden spec, device-auth enforcement is **currently a no-op** because the pre-receive hook fix (S1) hasn't landed. Saying "all commits MUST be signed" is aspirational, not current.
|
||||
**Fix:** Reword to clarify (a) the actual version line (e.g. "Pre-v0.5.0 vaults can opt out by leaving `devices.json` empty"), AND (b) acknowledge that signature *enforcement* depends on the pre-receive hook being deployed and the S1 fix landing. Could just be a one-line caveat.
|
||||
**Severity:** must-fix-before-v0.5.0 (security-doc accuracy is part of the legibility pitch)
|
||||
**Status:** Proposed; needs user decision (security wording — exact phrasing matters)
|
||||
**Status:** Fixed in `1342228` (PM follow-up, 2026-05-02 with user approval): dropped the "before v0.4.0" version line entirely (v0.4.0 was never tagged); replaced with a single line saying registration is optional but recommended for shared vaults. Enforcement story now lives in the Device Authentication section (see F12).
|
||||
|
||||
---
|
||||
|
||||
@@ -134,7 +135,7 @@ The codebase itself is well-documented — `crates/{relicario-core,relicario-cli
|
||||
**Issue:** The "Device Authentication" section refers to a "pre-receive hook" but never says it lives in `crates/relicario-server`, what binary the hook calls (`relicario-server verify-commit <sha>`), or how to install it (`relicario-server generate-hook`). For a self-hosted user reading this to decide whether to enable it, those are the two essential operational facts.
|
||||
**Fix:** Add a short paragraph naming the crate and the two subcommands, pointing to the design spec.
|
||||
**Severity:** nice-to-have
|
||||
**Status:** Proposed; needs user decision (>50 words of new prose)
|
||||
**Status:** Fixed in `1342228` (PM follow-up, 2026-05-02): added paragraph naming the `relicario-server` crate, both subcommands (`generate-hook`, `verify-commit`), and the caveat that signed commits without the server hook provide authorship metadata only.
|
||||
|
||||
---
|
||||
|
||||
@@ -144,7 +145,7 @@ The codebase itself is well-documented — `crates/{relicario-core,relicario-cli
|
||||
**Issue:** This doc is explicitly historical (per `docs/architecture/overview.md` "Stale spec docs" disclaimer), so editing it as architecture would violate convention. Still worth flagging that "Post-V1 Ideas" lists secure notes, secure documents, mobile, LastPass import, Firefox extension, TOTP — most of which have shipped. Per project policy this is *informational only*; the spec is a time-stamped decision artifact.
|
||||
**Fix:** None — leave alone. If desired, prepend a one-line "Status: V1 shipped 2026-04-22; many Post-V1 ideas have since landed — see CHANGELOG.md" at the top of the file.
|
||||
**Severity:** informational
|
||||
**Status:** Proposed; needs user decision (touches a historical spec the user may want to leave frozen)
|
||||
**Status:** Fixed in `9c97f9f` (PM follow-up, 2026-05-02): added the optional one-line status banner at the top of the spec pointing at CHANGELOG.md and overview.md for current state. Body of the spec untouched per the "specs are frozen decision artifacts" convention.
|
||||
|
||||
---
|
||||
|
||||
@@ -160,10 +161,18 @@ The codebase itself is well-documented — `crates/{relicario-core,relicario-cli
|
||||
|
||||
## Inline-fix verification
|
||||
|
||||
Files modified during this audit:
|
||||
### Initial pass (commit `900ccf1`):
|
||||
|
||||
- `README.md` — vault layout (`items/`, `settings.enc`, `attachments/`), crate tree (added `relicario-wasm`, `relicario-server`, typed-items modules), ID width, Roadmap.
|
||||
- `docs/ARCHITECTURE.md` — git-server box (`items/`, `settings.enc`, `attachments/`, `revoked.json`), crate-architecture inner box (current core modules), removed "Future: relicario-wasm" line.
|
||||
- `docs/architecture/overview.md` — conventions table (16-char hex IDs, 128-bit AttachmentIds).
|
||||
|
||||
No source files, `Cargo.lock`, or extension code were modified. CLAUDE.md, SECURITY.md, and the foundational design spec were not modified — those changes need user review per the audit constraints.
|
||||
### v0.5.0 PM follow-up pass (commits `ca059e7`, `8fd9a05`, `1342228`, `76d092d`, `9c97f9f`):
|
||||
|
||||
- `docs/architecture/overview.md` — F1: four-codebases framing, ASCII diagram fans out to server, table row, build matrix, "Where to look next".
|
||||
- `CLAUDE.md` — F2: project tree gains `relicario-server`. F3: Roadmap line replaced. F4: Item/Field/Attachment ID widths and entropy noted.
|
||||
- `docs/SECURITY.md` — F11: dropped `before v0.4.0` line. F12: Device Authentication section now names the `relicario-server` crate and its subcommands, with the "without the hook, commits are advisory" caveat.
|
||||
- `docs/ARCHITECTURE.md` — F10: settings.enc shown alongside manifest.enc in the Vault Creation Flow; pointer added to per-crate ARCHITECTURE.md for typed-items detail.
|
||||
- `docs/superpowers/specs/2026-04-11-relicario-design.md` — F13: optional one-line "historical spec" status banner at top.
|
||||
|
||||
No source files, `Cargo.lock`, or extension code were modified at any point.
|
||||
|
||||
1448
docs/superpowers/coordination/v0.5.1-dev-a-prompt.md
Normal file
1448
docs/superpowers/coordination/v0.5.1-dev-a-prompt.md
Normal file
File diff suppressed because it is too large
Load Diff
1074
docs/superpowers/coordination/v0.5.1-dev-b-prompt.md
Normal file
1074
docs/superpowers/coordination/v0.5.1-dev-b-prompt.md
Normal file
File diff suppressed because it is too large
Load Diff
1353
docs/superpowers/coordination/v0.5.1-dev-c-prompt.md
Normal file
1353
docs/superpowers/coordination/v0.5.1-dev-c-prompt.md
Normal file
File diff suppressed because it is too large
Load Diff
165
docs/superpowers/coordination/v0.5.1-pm-prompt.md
Normal file
165
docs/superpowers/coordination/v0.5.1-pm-prompt.md
Normal file
@@ -0,0 +1,165 @@
|
||||
# PM Kickoff Prompt — v0.5.1 UX Polish + Recovery QR
|
||||
|
||||
Paste everything below the `---` line into a fresh Claude Code terminal as the first user message.
|
||||
|
||||
---
|
||||
|
||||
You are the **project manager** for the Relicario v0.5.1 release. Three senior developers report to you, each working in their own terminal on a parallel feature branch. The user runs all four terminals and relays messages between them.
|
||||
|
||||
## Setup
|
||||
|
||||
- Working directory: `/home/alee/Sources/relicario`
|
||||
- Branch: stay on `main`. Do not check out feature branches.
|
||||
- Today: 2026-05-03. Project rules in `CLAUDE.md` apply (Spanish flourish, capitalization, autonomy defaults, never run git-destructive commands without asking).
|
||||
|
||||
## Required reading (in order)
|
||||
|
||||
1. `CLAUDE.md` — project rules
|
||||
2. `docs/superpowers/specs/2026-05-03-v0.5.x-ux-polish-and-recovery-qr-design.md` — full spec
|
||||
3. `docs/superpowers/coordination/v0.5.1-dev-a-prompt.md` — Dev A's plan (Stream A: fullscreen + popup layout)
|
||||
4. `docs/superpowers/coordination/v0.5.1-dev-b-prompt.md` — Dev B's plan (Stream B: settings UX)
|
||||
5. `docs/superpowers/coordination/v0.5.1-dev-c-prompt.md` — Dev C's plan (Stream C: recovery QR)
|
||||
|
||||
## Your authority
|
||||
|
||||
- Approve or deny scope changes from devs
|
||||
- Review and merge PRs from all three feature branches
|
||||
- **Drive the interface contract** between B and C (see below) — this is your first hands-on action
|
||||
- Write the `CHANGELOG.md` entry for v0.5.1
|
||||
- Tag `v0.5.1` once everything is integrated **— but only after explicit user approval**
|
||||
|
||||
## Your boundaries
|
||||
|
||||
- Don't write feature code yourself. Edits to docs / CHANGELOG / CLAUDE.md are fine.
|
||||
- Don't deviate from the spec without user approval.
|
||||
- Don't merge a PR until the dev says `REVIEW-READY` and you've run `gh pr diff` to confirm.
|
||||
- Don't tag without user approval.
|
||||
- Project rule: ask the user before any git-destructive op.
|
||||
|
||||
## Stream overview
|
||||
|
||||
| Stream | Branch | Owner | Core files |
|
||||
|--------|--------|-------|-----------|
|
||||
| A — Fullscreen + popup layout | `feature/v0.5.1-stream-a-layout` | DEV-A | `vault.ts`, `vault.css`, `item-list.ts`, `item-form.ts`, `glyphs.ts`, `toast.ts` |
|
||||
| B — Settings UX | `feature/v0.5.1-stream-b-settings` | DEV-B | `settings.ts`, `settings-vault.ts` (decomposed), `settings-security.ts` (stub only) |
|
||||
| C — Recovery QR | `feature/v0.5.1-stream-c-recovery-qr` | DEV-C | `recovery_qr.rs`, WASM `session.rs`/`lib.rs`, `settings-security.ts`, `setup.ts` |
|
||||
|
||||
## Interface contracts (enforce before work starts)
|
||||
|
||||
### A–B: Settings component signature
|
||||
|
||||
DEV-B's settings component is wired into vault.ts by DEV-A. Both must agree before either proceeds with their vault.ts / settings.ts work.
|
||||
|
||||
**Agreed interface** (post to both devs as your first directive):
|
||||
|
||||
```ts
|
||||
// extension/src/popup/components/settings.ts
|
||||
|
||||
/**
|
||||
* Render the full sectioned settings view into `container`.
|
||||
* May be called from vault.ts (fullscreen, full-width pane) or popup.ts (popup).
|
||||
*/
|
||||
export async function renderSettings(container: HTMLElement): Promise<void>;
|
||||
|
||||
/**
|
||||
* Teardown: close any open generator panel, remove keyboard listeners.
|
||||
* Call before navigating away from the settings view.
|
||||
*/
|
||||
export function teardownSettings(): void;
|
||||
```
|
||||
|
||||
DEV-A imports `{ renderSettings, teardownSettings }` from `settings.ts` in vault.ts.
|
||||
DEV-B exports these names with these exact signatures.
|
||||
|
||||
### B–C: Security section component signature
|
||||
|
||||
DEV-C owns and implements `settings-security.ts`. DEV-B imports it for the Security section. They must agree before DEV-B writes B4 (Security section) or DEV-C writes C8 (settings-security.ts).
|
||||
|
||||
**Agreed interface** (post to both devs as your first directive):
|
||||
|
||||
```ts
|
||||
// extension/src/popup/components/settings-security.ts
|
||||
|
||||
/**
|
||||
* Render the three-state Recovery QR + trusted devices security section
|
||||
* into `container`. `sessionHandle` is the current WASM session handle value
|
||||
* (from the service-worker's session), or null if the vault is locked.
|
||||
*/
|
||||
export async function renderSecuritySection(
|
||||
container: HTMLElement,
|
||||
sessionHandle: number | null,
|
||||
): Promise<void>;
|
||||
|
||||
/**
|
||||
* Teardown: remove any event listeners attached during render.
|
||||
*/
|
||||
export function teardownSecuritySection(): void;
|
||||
```
|
||||
|
||||
DEV-B stubs this interface in `settings-security.ts` immediately after receiving this directive. DEV-C replaces it with the real implementation.
|
||||
|
||||
## Merge order and strategy
|
||||
|
||||
1. **C lands first** (or concurrently with A; no A or B dependency). Merge once DEV-C posts REVIEW-READY.
|
||||
2. **A and B can merge in either order** after C is on main, since both will rebase/merge main before PR.
|
||||
3. No squash merges — git history is preserved per project rule.
|
||||
4. No force pushes. Each dev opens a PR; PM reviews diff; PM merges with `gh pr merge --merge`.
|
||||
|
||||
## Coordination protocol
|
||||
|
||||
You are one of four terminals. The user relays messages.
|
||||
|
||||
**You receive:** `## STATUS UPDATE — DEV-A/B/C` or `## QUESTION TO PM — DEV-X` blocks.
|
||||
|
||||
**You emit:** a `## DIRECTIVE TO DEV-X` block. Format:
|
||||
|
||||
```
|
||||
## DIRECTIVE TO DEV-A (or B or C)
|
||||
Time: <iso8601>
|
||||
Action: PROCEED | HOLD | RESCOPE | REVIEW-COMPLETE | MERGE-APPROVED
|
||||
Notes: <one paragraph max>
|
||||
Next: <one concrete instruction or "continue plan">
|
||||
```
|
||||
|
||||
When asked "status?" by the user at any time:
|
||||
|
||||
```
|
||||
## RELEASE STATUS — v0.5.1
|
||||
Dev A: <task X of Y, status>
|
||||
Dev B: <task X of Y, status>
|
||||
Dev C: <task X of Y, status>
|
||||
PM: <current action>
|
||||
Blockers: <list, or "none">
|
||||
Next milestone: <e.g., "Dev C REVIEW-READY", "all three merged">
|
||||
```
|
||||
|
||||
## Reviewing PRs
|
||||
|
||||
When a dev posts `Action: REVIEW-READY` with a PR URL:
|
||||
1. `gh pr view <url>` to read description and CI status
|
||||
2. `gh pr diff <url>` to read changes
|
||||
3. Check diff against the spec sections owned by that stream
|
||||
4. If green: post `Action: MERGE-APPROVED` and run `gh pr merge --merge`
|
||||
5. If red: post `Action: HOLD` with specific concerns
|
||||
|
||||
## Pre-tag checklist
|
||||
|
||||
Before tagging v0.5.1:
|
||||
|
||||
- [ ] `feature/v0.5.1-stream-a-layout` merged to main
|
||||
- [ ] `feature/v0.5.1-stream-b-settings` merged to main
|
||||
- [ ] `feature/v0.5.1-stream-c-recovery-qr` merged to main
|
||||
- [ ] `cargo test` green on main
|
||||
- [ ] `bun run test` green (extension)
|
||||
- [ ] `cargo build -p relicario-wasm --target wasm32-unknown-unknown` green
|
||||
- [ ] `bun run build` + `bun run build:firefox` clean (extension)
|
||||
- [ ] No emoji in any UI surface (grep: `'🔑\|📝\|🪪\|💳\|🗝\|📄\|⏱️'` in `extension/src/`)
|
||||
- [ ] `GLYPH_VAULT_TAB` in glyphs.ts; no inline `⤴` anywhere
|
||||
- [ ] `recovery_qr_generated_at` is the only persisted QR artifact (grep: no QR SVG in chrome.storage calls)
|
||||
- [ ] Settings left-nav sections all render without console errors
|
||||
- [ ] `CHANGELOG.md` entry for v0.5.1 written
|
||||
- [ ] Explicit user approval to tag
|
||||
|
||||
## First action
|
||||
|
||||
After reading: post a `## RELEASE STATUS — v0.5.1` block, then post your first directive to all three devs simultaneously — confirming the A–B and B–C interface contracts above. Wait for devs to acknowledge before instructing them to proceed with their task lists.
|
||||
956
docs/superpowers/plans/2026-05-02-relay-server.md
Normal file
956
docs/superpowers/plans/2026-05-02-relay-server.md
Normal file
@@ -0,0 +1,956 @@
|
||||
# Relay Server Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Build a local MCP SSE server that gives PM, Dev-A, and Dev-B Claude Code sessions native `post_message`/`read_messages`/`list_pending` tools, eliminating manual copy-paste during multi-agent development lifts.
|
||||
|
||||
**Architecture:** A single Node.js process hosts an HTTP server with SSE transport for the MCP protocol. Three named in-memory FIFO queues (one per role) hold consume-once messages. A `start.sh` launcher prints copy-paste instructions (default) or spawns a tmux/kitty layout (flags). The multi-agent-kickoff skill templates get a `<<RELAY_PARAGRAPH>>` placeholder injected so every future lift prompt auto-includes relay instructions.
|
||||
|
||||
**Tech Stack:** Node.js v25, `@modelcontextprotocol/sdk` (MCP + SSE transport), `tsx` (dev dep, runs TypeScript directly), Node built-in `node:test` runner. No Express, no Hono, no Zod as a direct dep.
|
||||
|
||||
---
|
||||
|
||||
## File map
|
||||
|
||||
| Action | Path | Responsibility |
|
||||
|--------|------|----------------|
|
||||
| Create | `tools/relay/package.json` | npm metadata, scripts, single runtime dep + tsx devDep |
|
||||
| Create | `tools/relay/tsconfig.json` | TypeScript config for ESM Node target |
|
||||
| Create | `tools/relay/queue.ts` | `RelayQueue` class — in-memory FIFO, `post`/`read`/`pending`, `isRole` guard |
|
||||
| Create | `tools/relay/queue.test.ts` | Node `node:test` unit tests for queue (5 cases) |
|
||||
| Create | `tools/relay/server.ts` | MCP `Server` + `SSEServerTransport` HTTP server on port 7331 |
|
||||
| Create | `tools/relay/start.sh` | Launcher: `--manual` (default), `--tmux`, `--kitty` |
|
||||
| Modify | `.gitignore` | Add `tools/relay/node_modules/` |
|
||||
| Modify | `.claude/settings.json` | Add `mcpServers.relay` SSE entry |
|
||||
| Create | `docs/superpowers/MULTI-AGENT.md` | Paradigm reference README |
|
||||
| Modify | `~/.claude/skills/multi-agent-kickoff/templates/pm-prompt.md` | Add `<<RELAY_PARAGRAPH>>` section |
|
||||
| Modify | `~/.claude/skills/multi-agent-kickoff/templates/dev-prompt.md` | Add `<<RELAY_PARAGRAPH>>` section |
|
||||
| Modify | `~/.claude/skills/multi-agent-kickoff/SKILL.md` | Placeholder ref + step 8 update + `<<DEV_ROLE>>` placeholder |
|
||||
|
||||
---
|
||||
|
||||
## Task 1: Scaffold `tools/relay/`
|
||||
|
||||
**Files:**
|
||||
- Create: `tools/relay/package.json`
|
||||
- Create: `tools/relay/tsconfig.json`
|
||||
- Modify: `.gitignore`
|
||||
|
||||
- [ ] **Step 1: Create `tools/relay/package.json`**
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "@relicario/relay",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"start": "npx tsx server.ts",
|
||||
"test": "node --import=tsx/esm --test queue.test.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@modelcontextprotocol/sdk": "^1.10.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"tsx": "^4.19.0",
|
||||
"@types/node": "^22.0.0"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Create `tools/relay/tsconfig.json`**
|
||||
|
||||
```json
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"strict": true,
|
||||
"noEmit": true
|
||||
},
|
||||
"include": ["*.ts"]
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Add to root `.gitignore`**
|
||||
|
||||
Open `/home/alee/Sources/relicario/.gitignore` and append:
|
||||
|
||||
```
|
||||
tools/relay/node_modules/
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Install dependencies and verify**
|
||||
|
||||
```bash
|
||||
cd tools/relay && npm install
|
||||
```
|
||||
|
||||
Expected: `node_modules/` created, no errors. Verify with:
|
||||
|
||||
```bash
|
||||
ls node_modules/@modelcontextprotocol/sdk && ls node_modules/tsx
|
||||
```
|
||||
|
||||
Expected: both directories exist.
|
||||
|
||||
- [ ] **Step 5: Commit scaffold**
|
||||
|
||||
```bash
|
||||
git add tools/relay/package.json tools/relay/tsconfig.json tools/relay/package-lock.json .gitignore
|
||||
git commit -m "chore(relay): scaffold tools/relay with MCP SDK dep"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 2: `queue.ts` — TDD
|
||||
|
||||
**Files:**
|
||||
- Create: `tools/relay/queue.ts`
|
||||
- Create: `tools/relay/queue.test.ts`
|
||||
|
||||
- [ ] **Step 1: Write the failing tests**
|
||||
|
||||
Create `tools/relay/queue.test.ts`:
|
||||
|
||||
```typescript
|
||||
import { describe, it, beforeEach } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { RelayQueue, isRole } from "./queue.ts";
|
||||
|
||||
describe("RelayQueue", () => {
|
||||
let q: RelayQueue;
|
||||
|
||||
beforeEach(() => {
|
||||
q = new RelayQueue();
|
||||
});
|
||||
|
||||
it("post + read roundtrip returns the message with correct fields", () => {
|
||||
q.post("dev-b", "pm", "status", "Task P4 DONE");
|
||||
const msgs = q.read("pm");
|
||||
assert.equal(msgs.length, 1);
|
||||
assert.equal(msgs[0].from, "dev-b");
|
||||
assert.equal(msgs[0].to, "pm");
|
||||
assert.equal(msgs[0].kind, "status");
|
||||
assert.equal(msgs[0].body, "Task P4 DONE");
|
||||
assert.ok(typeof msgs[0].id === "string" && msgs[0].id.length > 0);
|
||||
assert.ok(typeof msgs[0].ts === "string");
|
||||
});
|
||||
|
||||
it("consume-once: second read returns empty", () => {
|
||||
q.post("dev-a", "pm", "question", "Should I use approach A?");
|
||||
q.read("pm");
|
||||
const second = q.read("pm");
|
||||
assert.deepEqual(second, []);
|
||||
});
|
||||
|
||||
it("list_pending does not drain inbox", () => {
|
||||
q.post("dev-b", "pm", "directive", "PROCEED");
|
||||
const before = q.pending("pm");
|
||||
assert.equal(before.count, 1);
|
||||
const after = q.read("pm");
|
||||
assert.equal(after.length, 1);
|
||||
});
|
||||
|
||||
it("FIFO ordering across multiple senders", () => {
|
||||
q.post("dev-a", "pm", "status", "first");
|
||||
q.post("dev-b", "pm", "status", "second");
|
||||
q.post("dev-a", "pm", "question", "third");
|
||||
const msgs = q.read("pm");
|
||||
assert.equal(msgs.length, 3);
|
||||
assert.equal(msgs[0].body, "first");
|
||||
assert.equal(msgs[1].body, "second");
|
||||
assert.equal(msgs[2].body, "third");
|
||||
});
|
||||
|
||||
it("isRole rejects unknown strings", () => {
|
||||
assert.ok(isRole("pm"));
|
||||
assert.ok(isRole("dev-a"));
|
||||
assert.ok(isRole("dev-b"));
|
||||
assert.ok(!isRole("dev-c"));
|
||||
assert.ok(!isRole(""));
|
||||
assert.ok(!isRole("PM"));
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run tests to confirm they fail**
|
||||
|
||||
```bash
|
||||
cd tools/relay && node --import=tsx/esm --test queue.test.ts
|
||||
```
|
||||
|
||||
Expected: fails with `Cannot find module './queue.ts'` or similar. If it fails with a different error, investigate before continuing.
|
||||
|
||||
- [ ] **Step 3: Write `queue.ts`**
|
||||
|
||||
Create `tools/relay/queue.ts`:
|
||||
|
||||
```typescript
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
export type Role = "pm" | "dev-a" | "dev-b";
|
||||
export type MessageKind = "status" | "question" | "directive" | "free";
|
||||
|
||||
export interface RelayMessage {
|
||||
id: string;
|
||||
from: Role;
|
||||
to: Role;
|
||||
kind: MessageKind;
|
||||
body: string;
|
||||
ts: string;
|
||||
}
|
||||
|
||||
const KNOWN_ROLES = new Set<string>(["pm", "dev-a", "dev-b"]);
|
||||
|
||||
export function isRole(s: string): s is Role {
|
||||
return KNOWN_ROLES.has(s);
|
||||
}
|
||||
|
||||
export class RelayQueue {
|
||||
private readonly queues = new Map<Role, RelayMessage[]>([
|
||||
["pm", []],
|
||||
["dev-a", []],
|
||||
["dev-b", []],
|
||||
]);
|
||||
|
||||
post(from: Role, to: Role, kind: MessageKind, body: string): RelayMessage {
|
||||
const msg: RelayMessage = {
|
||||
id: randomUUID(),
|
||||
from,
|
||||
to,
|
||||
kind,
|
||||
body,
|
||||
ts: new Date().toISOString(),
|
||||
};
|
||||
this.queues.get(to)!.push(msg);
|
||||
return msg;
|
||||
}
|
||||
|
||||
read(forRole: Role): RelayMessage[] {
|
||||
const inbox = this.queues.get(forRole)!;
|
||||
const messages = [...inbox];
|
||||
inbox.length = 0;
|
||||
return messages;
|
||||
}
|
||||
|
||||
pending(forRole: Role): { count: number; kinds: MessageKind[] } {
|
||||
const inbox = this.queues.get(forRole)!;
|
||||
return {
|
||||
count: inbox.length,
|
||||
kinds: inbox.map((m) => m.kind),
|
||||
};
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run tests to confirm they pass**
|
||||
|
||||
```bash
|
||||
cd tools/relay && node --import=tsx/esm --test queue.test.ts
|
||||
```
|
||||
|
||||
Expected output (all 5 passing):
|
||||
```
|
||||
▶ RelayQueue
|
||||
✔ post + read roundtrip returns the message with correct fields
|
||||
✔ consume-once: second read returns empty
|
||||
✔ list_pending does not drain inbox
|
||||
✔ FIFO ordering across multiple senders
|
||||
✔ isRole rejects unknown strings
|
||||
▶ RelayQueue (Xms)
|
||||
ℹ tests 5
|
||||
ℹ pass 5
|
||||
ℹ fail 0
|
||||
```
|
||||
|
||||
If any test fails, fix `queue.ts` before proceeding.
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add tools/relay/queue.ts tools/relay/queue.test.ts
|
||||
git commit -m "feat(relay): in-memory queue with consume-once semantics"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 3: `server.ts`
|
||||
|
||||
**Files:**
|
||||
- Create: `tools/relay/server.ts`
|
||||
|
||||
- [ ] **Step 1: Write `server.ts`**
|
||||
|
||||
Create `tools/relay/server.ts`:
|
||||
|
||||
```typescript
|
||||
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
||||
import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
|
||||
import {
|
||||
CallToolRequestSchema,
|
||||
ListToolsRequestSchema,
|
||||
} from "@modelcontextprotocol/sdk/types.js";
|
||||
import http from "node:http";
|
||||
import { RelayQueue, isRole } from "./queue.ts";
|
||||
|
||||
const PORT = 7331;
|
||||
const queue = new RelayQueue();
|
||||
|
||||
const mcpServer = new Server(
|
||||
{ name: "relay", version: "0.1.0" },
|
||||
{ capabilities: { tools: {} } }
|
||||
);
|
||||
|
||||
const TOOLS = [
|
||||
{
|
||||
name: "post_message",
|
||||
description:
|
||||
"Push a message to a recipient's inbox. Returns the assigned message id.",
|
||||
inputSchema: {
|
||||
type: "object" as const,
|
||||
properties: {
|
||||
from: {
|
||||
type: "string",
|
||||
enum: ["pm", "dev-a", "dev-b"],
|
||||
description: "Your role name",
|
||||
},
|
||||
to: {
|
||||
type: "string",
|
||||
enum: ["pm", "dev-a", "dev-b"],
|
||||
description: "Recipient role name",
|
||||
},
|
||||
kind: {
|
||||
type: "string",
|
||||
enum: ["status", "question", "directive", "free"],
|
||||
description: "Message type matching the coordination protocol",
|
||||
},
|
||||
body: {
|
||||
type: "string",
|
||||
description: "Message body — freeform markdown, typically the full formatted block",
|
||||
},
|
||||
},
|
||||
required: ["from", "to", "kind", "body"],
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "read_messages",
|
||||
description:
|
||||
"Pop and return all pending messages for this recipient. Inbox is empty after this call (consume-once).",
|
||||
inputSchema: {
|
||||
type: "object" as const,
|
||||
properties: {
|
||||
for: {
|
||||
type: "string",
|
||||
enum: ["pm", "dev-a", "dev-b"],
|
||||
description: "Your role name",
|
||||
},
|
||||
},
|
||||
required: ["for"],
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "list_pending",
|
||||
description:
|
||||
"Return count and kinds of pending messages without consuming them.",
|
||||
inputSchema: {
|
||||
type: "object" as const,
|
||||
properties: {
|
||||
for: {
|
||||
type: "string",
|
||||
enum: ["pm", "dev-a", "dev-b"],
|
||||
description: "Your role name",
|
||||
},
|
||||
},
|
||||
required: ["for"],
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
mcpServer.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS }));
|
||||
|
||||
mcpServer.setRequestHandler(CallToolRequestSchema, async (request) => {
|
||||
const { name, arguments: args } = request.params;
|
||||
const a = args as Record<string, string>;
|
||||
|
||||
if (name === "post_message") {
|
||||
if (!isRole(a.from)) {
|
||||
return { content: [{ type: "text" as const, text: `Error: unknown role "${a.from}"` }], isError: true };
|
||||
}
|
||||
if (!isRole(a.to)) {
|
||||
return { content: [{ type: "text" as const, text: `Error: unknown role "${a.to}"` }], isError: true };
|
||||
}
|
||||
const kind = a.kind as "status" | "question" | "directive" | "free";
|
||||
const msg = queue.post(a.from, a.to, kind, a.body);
|
||||
const ts = new Date(msg.ts).toTimeString().slice(0, 8);
|
||||
const preview = a.body.slice(0, 60).replace(/\n/g, " ");
|
||||
const ellipsis = a.body.length > 60 ? "..." : "";
|
||||
process.stdout.write(`[${ts}] ${a.from} → ${a.to} [${kind}] "${preview}${ellipsis}"\n`);
|
||||
return { content: [{ type: "text" as const, text: JSON.stringify({ id: msg.id }) }] };
|
||||
}
|
||||
|
||||
if (name === "read_messages") {
|
||||
if (!isRole(a.for)) {
|
||||
return { content: [{ type: "text" as const, text: `Error: unknown role "${a.for}"` }], isError: true };
|
||||
}
|
||||
const messages = queue.read(a.for);
|
||||
return { content: [{ type: "text" as const, text: JSON.stringify(messages) }] };
|
||||
}
|
||||
|
||||
if (name === "list_pending") {
|
||||
if (!isRole(a.for)) {
|
||||
return { content: [{ type: "text" as const, text: `Error: unknown role "${a.for}"` }], isError: true };
|
||||
}
|
||||
const result = queue.pending(a.for);
|
||||
return { content: [{ type: "text" as const, text: JSON.stringify(result) }] };
|
||||
}
|
||||
|
||||
return {
|
||||
content: [{ type: "text" as const, text: `Error: unknown tool "${name}"` }],
|
||||
isError: true,
|
||||
};
|
||||
});
|
||||
|
||||
const transports = new Map<string, SSEServerTransport>();
|
||||
|
||||
const httpServer = http.createServer(async (req, res) => {
|
||||
try {
|
||||
if (req.method === "GET" && req.url === "/sse") {
|
||||
const transport = new SSEServerTransport("/message", res);
|
||||
transports.set(transport.sessionId, transport);
|
||||
transport.onclose = () => transports.delete(transport.sessionId);
|
||||
await mcpServer.connect(transport);
|
||||
} else if (req.method === "POST" && req.url?.startsWith("/message")) {
|
||||
const url = new URL(req.url, `http://127.0.0.1:${PORT}`);
|
||||
const sessionId = url.searchParams.get("sessionId") ?? "";
|
||||
const transport = transports.get(sessionId);
|
||||
if (transport) {
|
||||
await transport.handlePostMessage(req, res);
|
||||
} else {
|
||||
res.writeHead(404, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify({ error: "session not found" }));
|
||||
}
|
||||
} else {
|
||||
res.writeHead(404).end("not found");
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("[relay] error:", err);
|
||||
if (!res.headersSent) res.writeHead(500).end(String(err));
|
||||
}
|
||||
});
|
||||
|
||||
httpServer.listen(PORT, "127.0.0.1", () => {
|
||||
console.log(`[relay] server ready on :${PORT}`);
|
||||
console.log(`[relay] tools: post_message, read_messages, list_pending`);
|
||||
console.log(`[relay] waiting for connections — Ctrl-C to stop`);
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Smoke-test server startup**
|
||||
|
||||
In one terminal:
|
||||
```bash
|
||||
cd tools/relay && npx tsx server.ts
|
||||
```
|
||||
|
||||
Expected output:
|
||||
```
|
||||
[relay] server ready on :7331
|
||||
[relay] tools: post_message, read_messages, list_pending
|
||||
[relay] waiting for connections — Ctrl-C to stop
|
||||
```
|
||||
|
||||
In a second terminal, verify the port is listening:
|
||||
```bash
|
||||
curl -s --max-time 2 http://127.0.0.1:7331/sse | head -3
|
||||
```
|
||||
|
||||
Expected: SSE `data:` stream begins (it won't complete — the connection stays open). Ctrl-C both.
|
||||
|
||||
If the server errors on startup, check that `@modelcontextprotocol/sdk` is installed and review any TypeScript errors by running `npx tsc --noEmit` in `tools/relay/`.
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git add tools/relay/server.ts
|
||||
git commit -m "feat(relay): MCP SSE server with post_message/read_messages/list_pending"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 4: `start.sh`
|
||||
|
||||
**Files:**
|
||||
- Create: `tools/relay/start.sh`
|
||||
|
||||
- [ ] **Step 1: Write `start.sh`**
|
||||
|
||||
Create `tools/relay/start.sh`:
|
||||
|
||||
```bash
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
REPO_ROOT="$(git -C "$SCRIPT_DIR" rev-parse --show-toplevel)"
|
||||
PORT=7331
|
||||
MODE="manual"
|
||||
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
--tmux) MODE="tmux" ;;
|
||||
--kitty) MODE="kitty" ;;
|
||||
--manual) MODE="manual" ;;
|
||||
*) echo "Unknown option: $arg" >&2; echo "Usage: $0 [--manual|--tmux|--kitty]" >&2; exit 1 ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# Port check
|
||||
if lsof -ti:"$PORT" &>/dev/null; then
|
||||
echo "Error: port $PORT is already in use."
|
||||
echo "Relay already running? Kill it with: kill \$(lsof -ti:$PORT)"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Install deps (no-op if node_modules current)
|
||||
cd "$SCRIPT_DIR"
|
||||
npm install --silent
|
||||
|
||||
# Discover latest coordination prompts for instructions
|
||||
COORD_DIR="$REPO_ROOT/docs/superpowers/coordination"
|
||||
PM_PROMPT="$(ls -t "$COORD_DIR"/*-pm-prompt.md 2>/dev/null | head -1 || echo "(none found — run multi-agent-kickoff skill first)")"
|
||||
DEV_A_PROMPT="$(ls -t "$COORD_DIR"/*-dev-a-prompt.md 2>/dev/null | head -1 || echo "(none found)")"
|
||||
DEV_B_PROMPT="$(ls -t "$COORD_DIR"/*-dev-b-prompt.md 2>/dev/null | head -1 || echo "(none found)")"
|
||||
|
||||
print_manual_instructions() {
|
||||
echo ""
|
||||
echo "╔══════════════════════════════════════════════════════════════╗"
|
||||
echo "║ RELAY SERVER — MULTI-AGENT LIFT LAUNCHER ║"
|
||||
echo "╚══════════════════════════════════════════════════════════════╝"
|
||||
echo ""
|
||||
echo "Open 3 new terminals. In each, start Claude Code and paste"
|
||||
echo "the content BELOW the '---' line from the corresponding file."
|
||||
echo ""
|
||||
echo " Terminal 1 (PM): cat '$PM_PROMPT'"
|
||||
echo " Terminal 2 (Dev A): cat '$DEV_A_PROMPT'"
|
||||
echo " Terminal 3 (Dev B): cat '$DEV_B_PROMPT'"
|
||||
echo ""
|
||||
echo "This terminal becomes the relay log. Keep it open."
|
||||
echo ""
|
||||
echo "══════════════════════════════════════════════════════════════"
|
||||
}
|
||||
|
||||
launch_tmux() {
|
||||
SESSION="relay-lift"
|
||||
tmux new-session -d -s "$SESSION" -n "relay" \
|
||||
"cd '$SCRIPT_DIR' && npx tsx server.ts"
|
||||
tmux new-window -t "$SESSION:" -n "pm" "cd '$REPO_ROOT' && claude"
|
||||
tmux new-window -t "$SESSION:" -n "dev-a" "cd '$REPO_ROOT' && claude"
|
||||
tmux new-window -t "$SESSION:" -n "dev-b" "cd '$REPO_ROOT' && claude"
|
||||
echo ""
|
||||
echo "[relay] Opened tmux session '$SESSION' with 4 windows: relay, pm, dev-a, dev-b."
|
||||
echo "[relay] Paste the kickoff prompt into each Claude window."
|
||||
echo " Prompts:"
|
||||
echo " PM: $PM_PROMPT"
|
||||
echo " Dev A: $DEV_A_PROMPT"
|
||||
echo " Dev B: $DEV_B_PROMPT"
|
||||
echo ""
|
||||
tmux attach-session -t "$SESSION"
|
||||
}
|
||||
|
||||
launch_kitty() {
|
||||
kitty @ launch --new-tab --tab-title "relay" -- \
|
||||
bash -c "cd '$SCRIPT_DIR' && npx tsx server.ts"
|
||||
kitty @ launch --new-window --window-title "PM" -- \
|
||||
bash -c "cd '$REPO_ROOT' && claude"
|
||||
kitty @ launch --new-window --window-title "Dev-A" -- \
|
||||
bash -c "cd '$REPO_ROOT' && claude"
|
||||
kitty @ launch --new-window --window-title "Dev-B" -- \
|
||||
bash -c "cd '$REPO_ROOT' && claude"
|
||||
echo ""
|
||||
echo "[relay] Opened kitty tab 'relay' + 3 windows (PM, Dev-A, Dev-B)."
|
||||
echo " Paste the kickoff prompts into each Claude window."
|
||||
echo " PM: $PM_PROMPT"
|
||||
echo " Dev A: $DEV_A_PROMPT"
|
||||
echo " Dev B: $DEV_B_PROMPT"
|
||||
}
|
||||
|
||||
case "$MODE" in
|
||||
manual)
|
||||
print_manual_instructions
|
||||
exec npx tsx "$SCRIPT_DIR/server.ts"
|
||||
;;
|
||||
tmux)
|
||||
launch_tmux
|
||||
;;
|
||||
kitty)
|
||||
launch_kitty
|
||||
;;
|
||||
esac
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Make executable**
|
||||
|
||||
```bash
|
||||
chmod +x tools/relay/start.sh
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Smoke-test `--manual` mode**
|
||||
|
||||
```bash
|
||||
cd /home/alee/Sources/relicario && tools/relay/start.sh
|
||||
```
|
||||
|
||||
Expected: prints the launch box with prompt paths, then server starts and shows `[relay] server ready on :7331`. Ctrl-C to stop.
|
||||
|
||||
- [ ] **Step 4: Commit**
|
||||
|
||||
```bash
|
||||
git add tools/relay/start.sh
|
||||
git commit -m "feat(relay): start.sh launcher with --manual/--tmux/--kitty modes"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 5: Claude Code MCP configuration
|
||||
|
||||
**Files:**
|
||||
- Modify: `.claude/settings.json`
|
||||
|
||||
- [ ] **Step 1: Read current `.claude/settings.json`**
|
||||
|
||||
```bash
|
||||
cat .claude/settings.json
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Add the relay MCP server entry**
|
||||
|
||||
The file currently has `{ "enabledPlugins": { ... } }`. Add `"mcpServers"` at the top level:
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"relay": {
|
||||
"type": "sse",
|
||||
"url": "http://localhost:7331/sse"
|
||||
}
|
||||
},
|
||||
"enabledPlugins": {
|
||||
"superpowers@claude-plugins-official": true
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Preserve whatever is already in `enabledPlugins` — only add the `mcpServers` key.
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git add .claude/settings.json
|
||||
git commit -m "chore(relay): add relay MCP server to project Claude config"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 6: `docs/superpowers/MULTI-AGENT.md`
|
||||
|
||||
**Files:**
|
||||
- Create: `docs/superpowers/MULTI-AGENT.md`
|
||||
|
||||
- [ ] **Step 1: Write the paradigm README**
|
||||
|
||||
Create `docs/superpowers/MULTI-AGENT.md`:
|
||||
|
||||
```markdown
|
||||
# Multi-Agent Development Paradigm
|
||||
|
||||
This repo uses a three-terminal workflow for large development lifts: one Claude Code session acts as **PM** and two act as **senior developers** (Dev-A, Dev-B), each working in their own git worktree on a parallel feature branch.
|
||||
|
||||
A local relay MCP server eliminates manual message copying between terminals — agents call `post_message`/`read_messages` instead of asking the user to copy-paste.
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
| Role | Terminal | Branch | Responsibilities |
|
||||
|------|----------|--------|-----------------|
|
||||
| PM | 1 | `main` (read-only) | Drive doc-audit follow-ups, review PRs, write CHANGELOG, authorize merges and tagging |
|
||||
| Dev-A | 2 | `feature/<release>-plan-a-*` | Implement Plan A tasks in their own worktree |
|
||||
| Dev-B | 3 | `feature/<release>-plan-b-*` | Implement Plan B tasks in their own worktree |
|
||||
| Relay server | 4 | — | Message bus; Ctrl-C to stop at end of lift |
|
||||
|
||||
**User's job:** authorize merges (the PM asks), resolve escalations the PM can't handle, and watch the streams. You are no longer the message bus.
|
||||
|
||||
---
|
||||
|
||||
## Starting a lift
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- [ ] Kickoff prompts exist in `docs/superpowers/coordination/` (generate with the `multi-agent-kickoff` skill if not)
|
||||
- [ ] No uncommitted changes in main that would confuse the devs
|
||||
- [ ] `tools/relay/` is present (run `ls tools/relay/` to confirm)
|
||||
|
||||
### Launch sequence
|
||||
|
||||
```bash
|
||||
# 1. Start the relay server (this terminal becomes the relay log)
|
||||
tools/relay/start.sh # prints copy-paste instructions, then starts server
|
||||
|
||||
# Optional: use a multiplexer to auto-open all four terminals
|
||||
tools/relay/start.sh --tmux # creates tmux session "relay-lift" with 4 windows
|
||||
tools/relay/start.sh --kitty # creates kitty tab "relay" + 3 windows
|
||||
```
|
||||
|
||||
`start.sh` prints the paths to the three kickoff prompt files. In each Claude Code terminal, run `cat <path>` and paste everything below the `---` line as the first message.
|
||||
|
||||
---
|
||||
|
||||
## Coordination protocol
|
||||
|
||||
Agents communicate by posting structured blocks to each other's inboxes. Four message kinds:
|
||||
|
||||
| Kind | Block header | When used |
|
||||
|------|-------------|-----------|
|
||||
| `status` | `## STATUS UPDATE — DEV-*` | After completing a task, getting blocked, or reaching a review-ready state |
|
||||
| `question` | `## QUESTION TO PM — DEV-*` | When a dev needs PM input mid-task |
|
||||
| `directive` | `## DIRECTIVE TO DEV-*` | When PM instructs a dev to proceed, hold, rescope, or approve a PR |
|
||||
| `free` | (none) | Ad-hoc messages not covered by the above |
|
||||
|
||||
A well-formed `status` block:
|
||||
|
||||
```
|
||||
## STATUS UPDATE — DEV-B
|
||||
Time: 2026-05-02T14:30:00-07:00
|
||||
Branch: feature/v0.5.0-plan-b-extension-ux
|
||||
Task: P4 / error-copy map
|
||||
Status: DONE
|
||||
Last commit: abc1234 feat(extension): centralize ERROR_COPY map
|
||||
Tests: green
|
||||
Notes: No issues. Ready for PM review of P4 before starting B1.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Using the relay tools
|
||||
|
||||
All three Claude Code sessions have these tools available when the relay server is running:
|
||||
|
||||
```
|
||||
post_message(from, to, kind, body) → { id }
|
||||
read_messages(for) → RelayMessage[] (drains inbox)
|
||||
list_pending(for) → { count, kinds } (non-destructive)
|
||||
```
|
||||
|
||||
Typical dev flow per task:
|
||||
|
||||
```
|
||||
1. read_messages(for="dev-b") # check for directives before starting
|
||||
2. ... do the work ...
|
||||
3. post_message(from="dev-b", to="pm", kind="status", body="## STATUS UPDATE...")
|
||||
```
|
||||
|
||||
Typical PM flow:
|
||||
|
||||
```
|
||||
1. read_messages(for="pm") # see what devs posted
|
||||
2. ... review ...
|
||||
3. post_message(from="pm", to="dev-b", kind="directive", body="## DIRECTIVE TO DEV-B...")
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## If the relay server isn't running
|
||||
|
||||
Claude Code will show a yellow MCP connection warning for the `relay` server. The tools will be unavailable.
|
||||
|
||||
Agents fall back to the manual protocol: they emit the structured blocks as text and ask the user to copy-paste them to the relevant terminal. This is slower but fully functional — the coordination protocol works either way.
|
||||
|
||||
To restart a crashed server mid-lift:
|
||||
|
||||
```bash
|
||||
tools/relay/start.sh
|
||||
```
|
||||
|
||||
In-flight messages are lost on restart. Any agent with unread messages should re-post them.
|
||||
|
||||
---
|
||||
|
||||
## Generating kickoff prompts
|
||||
|
||||
Use the `multi-agent-kickoff` skill (in the `superpowers` plugin). It auto-discovers the spec and plans for the release, substitutes all placeholders including the relay paragraph, and writes files to `docs/superpowers/coordination/`.
|
||||
|
||||
The skill reminder: run `tools/relay/start.sh` **before** opening the three Claude Code sessions — the MCP tools need the server to be up when each session initializes.
|
||||
|
||||
---
|
||||
|
||||
## Ending a lift
|
||||
|
||||
1. PM emits `REVIEW-COMPLETE` and `MERGE-APPROVED` for each dev's PR
|
||||
2. User merges each PR (the PM session does `gh pr merge` with user authorization)
|
||||
3. PM tags the release (only after explicit user `yes`)
|
||||
4. Ctrl-C the relay terminal — all in-memory messages are discarded
|
||||
|
||||
---
|
||||
|
||||
## Roles and boundaries (quick reference)
|
||||
|
||||
**PM must not:** write feature code, merge without user authorization, tag without user approval, run `git push --force` / `git reset --hard` without asking.
|
||||
|
||||
**Devs must not:** merge their branch to main, push `--force`, run `git reset --hard` without asking.
|
||||
|
||||
**User must:** authorize all merges and the release tag. Everything else is delegated.
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Commit**
|
||||
|
||||
```bash
|
||||
git add docs/superpowers/MULTI-AGENT.md
|
||||
git commit -m "docs: add multi-agent development paradigm README"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 7: Update `multi-agent-kickoff` skill
|
||||
|
||||
**Files:**
|
||||
- Modify: `~/.claude/skills/multi-agent-kickoff/templates/pm-prompt.md`
|
||||
- Modify: `~/.claude/skills/multi-agent-kickoff/templates/dev-prompt.md`
|
||||
- Modify: `~/.claude/skills/multi-agent-kickoff/SKILL.md`
|
||||
|
||||
- [ ] **Step 1: Read current templates**
|
||||
|
||||
```bash
|
||||
cat ~/.claude/skills/multi-agent-kickoff/templates/pm-prompt.md
|
||||
cat ~/.claude/skills/multi-agent-kickoff/templates/dev-prompt.md
|
||||
```
|
||||
|
||||
Note where the "Setup" section ends in each template. The relay paragraph goes right after it (before "Required reading").
|
||||
|
||||
- [ ] **Step 2: Add `<<RELAY_PARAGRAPH>>` to `pm-prompt.md`**
|
||||
|
||||
In `~/.claude/skills/multi-agent-kickoff/templates/pm-prompt.md`, find the "## Setup" section and add the placeholder block immediately after it (before the "## Required reading" heading):
|
||||
|
||||
```markdown
|
||||
<<RELAY_PARAGRAPH>>
|
||||
```
|
||||
|
||||
The generated output for this placeholder (substituted by the skill at generation time) is:
|
||||
|
||||
```markdown
|
||||
## Relay server
|
||||
|
||||
A message-bus MCP server is running on `localhost:7331`. You have three native tools:
|
||||
|
||||
- `post_message(from, to, kind, body)` — push a message; `from` is always `"pm"` for you
|
||||
- `read_messages(for)` — drain your inbox; call with `for="pm"` before each action
|
||||
- `list_pending(for)` — check inbox count without consuming
|
||||
|
||||
Recipients: `pm`, `dev-a`, `dev-b`. Use these instead of asking the user to copy-paste. After sending any directive, call `post_message(from="pm", to="dev-a", kind="directive", body="...")`.
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Add `<<RELAY_PARAGRAPH>>` to `dev-prompt.md`**
|
||||
|
||||
In `~/.claude/skills/multi-agent-kickoff/templates/dev-prompt.md`, find the "## Setup" section and add immediately after it (before "## Required reading"):
|
||||
|
||||
```markdown
|
||||
<<RELAY_PARAGRAPH>>
|
||||
```
|
||||
|
||||
The generated output for this placeholder is role-specific (uses `<<DEV_ROLE>>`):
|
||||
|
||||
```markdown
|
||||
## Relay server
|
||||
|
||||
A message-bus MCP server is running on `localhost:7331`. You have three native tools:
|
||||
|
||||
- `post_message(from, to, kind, body)` — push a message; your `from` is always `"<<DEV_ROLE>>"`
|
||||
- `read_messages(for)` — drain your inbox; call with `for="<<DEV_ROLE>>"` before each task
|
||||
- `list_pending(for)` — check inbox count without consuming
|
||||
|
||||
Recipients: `pm`, `dev-a`, `dev-b`. Use these instead of asking the user to copy-paste. Before starting each task: `read_messages(for="<<DEV_ROLE>>")`. After emitting any status/question block: `post_message(from="<<DEV_ROLE>>", to="pm", kind="status"|"question", body="...")`.
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Update `SKILL.md` — add two entries to the placeholder reference table**
|
||||
|
||||
In `~/.claude/skills/multi-agent-kickoff/SKILL.md`, find the "### Common to all prompts" section of the Placeholder reference and add:
|
||||
|
||||
```markdown
|
||||
- `<<RELAY_PARAGRAPH>>` — the relay server instruction block (substituted from the template above). For the PM prompt, `from` is hardcoded to `"pm"`. For dev prompts, uses `<<DEV_ROLE>>`.
|
||||
```
|
||||
|
||||
In the "### Per-dev" section, add:
|
||||
|
||||
```markdown
|
||||
- `<<DEV_ROLE>>` — lowercase relay role name, e.g. `dev-a`, `dev-b`. Derived from `<<DEV_LETTER>>` by lowercasing and prepending `dev-`. Set when `<<DEV_LETTER>>` is set.
|
||||
```
|
||||
|
||||
- [ ] **Step 5: Update `SKILL.md` — step 8 (kickoff instructions)**
|
||||
|
||||
Find step 8 in the Process section ("Print kickoff instructions") and prepend a bullet:
|
||||
|
||||
```markdown
|
||||
8. **Print kickoff instructions.** Tell the user exactly what to do:
|
||||
- **Start the relay server first:** `tools/relay/start.sh` (or `--tmux`/`--kitty` for auto-layout). The server must be running before the sessions open so the MCP tools initialize correctly.
|
||||
- Open three terminal windows (or panes — their choice of multiplexer)
|
||||
...rest of existing bullets unchanged...
|
||||
```
|
||||
|
||||
Also update the "After generation" section — change bullet 4 ("From that point on, they're the message bus...") to:
|
||||
|
||||
```markdown
|
||||
4. The relay server handles message routing — agents call `post_message`/`read_messages` directly. The user only needs to step in for escalations the PM can't resolve, or if the relay server is down (manual fallback: copy-paste the block to the relevant terminal as before)
|
||||
```
|
||||
|
||||
- [ ] **Step 6: Commit skill changes**
|
||||
|
||||
The skill files live outside the git repo, so no git commit needed. Verify the changes look right:
|
||||
|
||||
```bash
|
||||
grep -n "RELAY_PARAGRAPH\|DEV_ROLE\|relay server" ~/.claude/skills/multi-agent-kickoff/SKILL.md | head -10
|
||||
grep -n "RELAY_PARAGRAPH" ~/.claude/skills/multi-agent-kickoff/templates/pm-prompt.md
|
||||
grep -n "RELAY_PARAGRAPH" ~/.claude/skills/multi-agent-kickoff/templates/dev-prompt.md
|
||||
```
|
||||
|
||||
Expected: each grep returns at least one match.
|
||||
|
||||
---
|
||||
|
||||
## Final verification
|
||||
|
||||
- [ ] **Run queue tests one more time from repo root**
|
||||
|
||||
```bash
|
||||
cd tools/relay && node --import=tsx/esm --test queue.test.ts
|
||||
```
|
||||
|
||||
Expected: 5 passing, 0 failing.
|
||||
|
||||
- [ ] **Start server and verify it binds**
|
||||
|
||||
```bash
|
||||
tools/relay/start.sh &
|
||||
sleep 1
|
||||
curl -s --max-time 1 http://127.0.0.1:7331/sse | head -1 || true
|
||||
kill %1
|
||||
```
|
||||
|
||||
Expected: `data:` line appears (SSE stream started), then server killed cleanly.
|
||||
|
||||
- [ ] **Verify MCP config is present**
|
||||
|
||||
```bash
|
||||
python3 -c "import json; d=json.load(open('.claude/settings.json')); print(d['mcpServers']['relay'])"
|
||||
```
|
||||
|
||||
Expected: `{'type': 'sse', 'url': 'http://localhost:7331/sse'}`
|
||||
|
||||
- [ ] **Verify skill placeholders were added**
|
||||
|
||||
```bash
|
||||
grep "RELAY_PARAGRAPH" ~/.claude/skills/multi-agent-kickoff/templates/pm-prompt.md \
|
||||
~/.claude/skills/multi-agent-kickoff/templates/dev-prompt.md
|
||||
```
|
||||
|
||||
Expected: one match per file.
|
||||
@@ -1,5 +1,7 @@
|
||||
# Relicario — Design Specification
|
||||
|
||||
> **Status:** historical. V1 shipped 2026-04-22; several "Post-V1 Ideas" listed below (typed items, attachments, secure documents, TOTP, Firefox extension, LastPass import, device authentication) have since shipped. See `CHANGELOG.md` and `docs/architecture/overview.md` for current state. Do not edit this spec as if it were architecture documentation — it is a time-stamped decision artifact.
|
||||
|
||||
A git-backed, self-hostable password manager with a Rust core, CLI, and Chrome browser extension. The reference image as a DCT-embedded secret carrier is the core differentiator.
|
||||
|
||||
## Overview
|
||||
|
||||
218
docs/superpowers/specs/2026-05-02-relay-server-design.md
Normal file
218
docs/superpowers/specs/2026-05-02-relay-server-design.md
Normal file
@@ -0,0 +1,218 @@
|
||||
# Relay Server Design
|
||||
|
||||
**Date:** 2026-05-02
|
||||
**Status:** Approved
|
||||
**Scope:** Dev tooling — not shipped in any product artifact
|
||||
|
||||
---
|
||||
|
||||
## Problem
|
||||
|
||||
Multi-agent development lifts (PM + Dev-A + Dev-B in parallel Claude Code sessions) require passing status updates, questions, and directives between terminals. Today the user manually copies and pastes every message block. This is error-prone, breaks flow, and scales poorly as lift complexity grows.
|
||||
|
||||
## Goal
|
||||
|
||||
A lightweight MCP server running on localhost that gives all three Claude Code sessions native tools to post and read messages. The user stops being the message bus.
|
||||
|
||||
---
|
||||
|
||||
## Repository layout
|
||||
|
||||
```
|
||||
tools/relay/
|
||||
├── package.json # private, not published; single dep: @modelcontextprotocol/sdk
|
||||
├── tsconfig.json
|
||||
├── server.ts # MCP SSE server entry point (~150 lines)
|
||||
├── queue.ts # in-memory queue logic (~50 lines)
|
||||
├── queue.test.ts # Node built-in test runner
|
||||
└── start.sh # launcher script
|
||||
```
|
||||
|
||||
Added to root `.gitignore`: `tools/relay/node_modules/`, `tools/relay/dist/`.
|
||||
|
||||
---
|
||||
|
||||
## Tech stack
|
||||
|
||||
- **Runtime:** Node.js (v25, already installed at `/usr/bin/node`)
|
||||
- **Package manager:** npm (bun has known compat gaps with the MCP SDK's SSE transport)
|
||||
- **Dependencies:** `@modelcontextprotocol/sdk`, `tsx` (devDependency, runs TypeScript directly — no compile step)
|
||||
- **Transport:** SSE (`SSEServerTransport` from the SDK handles the HTTP layer — no Express or Hono needed)
|
||||
- **Port:** `7331` (hardcoded; easy to remember, unlikely to collide)
|
||||
|
||||
---
|
||||
|
||||
## Queue model
|
||||
|
||||
Three named inboxes: `pm`, `dev-a`, `dev-b`. Each is a FIFO array in memory.
|
||||
|
||||
Message shape:
|
||||
|
||||
```ts
|
||||
interface RelayMessage {
|
||||
id: string; // uuid v4
|
||||
from: string; // sender role name
|
||||
to: string; // recipient role name
|
||||
kind: "status" | "question" | "directive" | "free";
|
||||
body: string; // freeform, typically the existing markdown block format
|
||||
ts: string; // ISO 8601
|
||||
}
|
||||
```
|
||||
|
||||
`kind` maps to the existing coordination protocol:
|
||||
|
||||
| kind | existing block |
|
||||
|-------------|-----------------------------|
|
||||
| `status` | `## STATUS UPDATE — DEV-*` |
|
||||
| `question` | `## QUESTION TO PM — DEV-*` |
|
||||
| `directive` | `## DIRECTIVE TO DEV-*` |
|
||||
| `free` | ad-hoc / unstructured |
|
||||
|
||||
Messages are **consume-once**: `read_messages` drains the inbox. There is no persistence — if the server restarts mid-lift, in-flight messages are lost. Acceptable for a dev tool; agents re-send on reconnect.
|
||||
|
||||
---
|
||||
|
||||
## MCP tool surface
|
||||
|
||||
All three tools are exposed to every connected session.
|
||||
|
||||
### `post_message`
|
||||
|
||||
```
|
||||
post_message(from: "pm"|"dev-a"|"dev-b", to: "pm"|"dev-a"|"dev-b", kind: "status"|"question"|"directive"|"free", body: string) → { id: string }
|
||||
```
|
||||
|
||||
Pushes one message onto the target's inbox. Returns the assigned message id. Errors if `to` or `from` is not a known role. Agents declare their own identity via `from` — the kickoff prompt tells each agent its role name.
|
||||
|
||||
### `read_messages`
|
||||
|
||||
```
|
||||
read_messages(for: "pm"|"dev-a"|"dev-b") → RelayMessage[]
|
||||
```
|
||||
|
||||
Pops and returns all pending messages for that recipient, in FIFO order. After this call the inbox is empty.
|
||||
|
||||
### `list_pending`
|
||||
|
||||
```
|
||||
list_pending(for: "pm"|"dev-a"|"dev-b") → { count: number, kinds: string[] }
|
||||
```
|
||||
|
||||
Returns count and kind breakdown of pending messages without consuming them. Lets an agent cheaply check "do I have anything to act on?" before committing to a `read_messages` call.
|
||||
|
||||
---
|
||||
|
||||
## Server terminal output
|
||||
|
||||
Every `post_message` call prints a one-liner to stdout in the dedicated relay terminal:
|
||||
|
||||
```
|
||||
[14:32:01] dev-b → pm [status] "Task P4 DONE, last commit abc1234..."
|
||||
[14:33:15] pm → dev-b [directive] "PROCEED to task B1"
|
||||
```
|
||||
|
||||
This log is the operational value of keeping the server in a dedicated terminal rather than backgrounding it.
|
||||
|
||||
---
|
||||
|
||||
## Launcher script (`start.sh`)
|
||||
|
||||
`start.sh` accepts one optional flag:
|
||||
|
||||
| Flag | Behavior |
|
||||
|------------|----------|
|
||||
| *(default)*| `--manual` mode: prints three labeled prompt blocks (one per role) for copy-paste into fresh Claude Code sessions, then starts the server in the foreground |
|
||||
| `--tmux` | Creates a new tmux window with four panes: relay server + PM + Dev-A + Dev-B, each pre-loaded with its kickoff command |
|
||||
| `--kitty` | Same layout using kitty's `launch --new-tab` / `--new-window` |
|
||||
|
||||
Execution order (all modes):
|
||||
|
||||
1. `cd tools/relay && npm install --silent` (no-op if `node_modules` is current)
|
||||
2. Print the session snippet (copy-paste blocks or multiplexer launch)
|
||||
3. Foreground `npx tsx server.ts` — the terminal that ran `start.sh` becomes the relay terminal; no compile step needed
|
||||
|
||||
Port-already-in-use check before step 3: if `:7331` is bound, print `relay already running? kill it with: kill $(lsof -ti:7331)` and exit 1.
|
||||
|
||||
---
|
||||
|
||||
## Claude Code configuration
|
||||
|
||||
Add to project `.claude/settings.json`:
|
||||
|
||||
```json
|
||||
"mcpServers": {
|
||||
"relay": {
|
||||
"type": "sse",
|
||||
"url": "http://localhost:7331/sse"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This is project-scoped — the relay tools only appear in Relicario Claude Code sessions. When the server is not running, Claude Code shows a yellow MCP connection warning but does not break. Agents gracefully fall back to asking the user to relay manually (existing behavior).
|
||||
|
||||
---
|
||||
|
||||
## Kickoff prompt changes
|
||||
|
||||
One paragraph added near the top of each coordination prompt (`v0.5.0-pm-prompt.md`, `v0.5.0-dev-a-prompt.md`, `v0.5.0-dev-b-prompt.md` as template):
|
||||
|
||||
> **Relay server:** A message-bus MCP server is running. You have three tools: `post_message(to, kind, body)`, `read_messages(for)`, `list_pending(for)`. Recipients: `pm`, `dev-a`, `dev-b`. Use these instead of asking the user to copy-paste. Before starting each task call `read_messages(for="<your-role>")`. After emitting any status, question, or directive block, call `post_message` with `kind` set to the block type and `body` set to the formatted block.
|
||||
|
||||
The `multi-agent-kickoff` skill is updated to:
|
||||
- Remind the user to run `tools/relay/start.sh` before opening the three sessions
|
||||
- Inject the relay paragraph automatically into every generated kickoff prompt
|
||||
|
||||
---
|
||||
|
||||
## Error handling
|
||||
|
||||
| Scenario | Behavior |
|
||||
|----------|----------|
|
||||
| Unknown `to` in `post_message` | MCP error returned; message not queued |
|
||||
| Server crash / restart | In-flight messages lost; agent re-sends |
|
||||
| Port 7331 in use at startup | Startup exits 1 with a kill hint |
|
||||
| Session connects before server starts | Claude Code shows MCP warning; agent falls back to manual relay |
|
||||
|
||||
No authentication. This is localhost-only, single-machine, dev-tool use.
|
||||
|
||||
---
|
||||
|
||||
## Testing
|
||||
|
||||
`queue.test.ts` using Node's built-in `node:test` runner. No extra test dep.
|
||||
|
||||
Coverage:
|
||||
- `post_message` + `read_messages` roundtrip (single and multiple messages)
|
||||
- Consume-once: second `read_messages` on same inbox returns empty
|
||||
- `list_pending` does not drain inbox
|
||||
- FIFO ordering across multiple senders to the same inbox
|
||||
- Unknown recipient returns an error
|
||||
|
||||
No integration test against the MCP SSE transport — that is the SDK's responsibility.
|
||||
|
||||
---
|
||||
|
||||
## Top-level README (`docs/superpowers/MULTI-AGENT.md`)
|
||||
|
||||
A durable reference document covering the whole development paradigm — not the relay server specifically, but the entire three-terminal workflow that the relay server enables. Lives in `docs/superpowers/` alongside the specs and plans it describes.
|
||||
|
||||
**Contents:**
|
||||
|
||||
1. **Overview** — the PM/Dev-A/Dev-B pattern: why three terminals, what each role owns, what the user's job is (authorize merges, resolve escalations)
|
||||
2. **Starting a lift** — prerequisites checklist, then: `tools/relay/start.sh` → three sessions → paste kickoff prompts
|
||||
3. **Coordination protocol reference** — the four message kinds (`status`, `question`, `directive`, `free`), when each is used, what a well-formed body looks like
|
||||
4. **Using the relay tools** — `post_message`, `read_messages`, `list_pending` with one-liner examples
|
||||
5. **If the relay server isn't running** — fallback to manual copy-paste; the coordination protocol still works, just with the user as bus
|
||||
6. **Generating kickoff prompts** — point to the `multi-agent-kickoff` skill; note that the skill injects the relay paragraph automatically
|
||||
7. **Ending a lift** — PM emits MERGE-APPROVED, devs push branches, user authorizes merges, Ctrl-C the relay terminal
|
||||
|
||||
This README is written for future-you opening the repo six months from now, not for the current lift.
|
||||
|
||||
---
|
||||
|
||||
## What this is not
|
||||
|
||||
- Not a product feature — never bundled with the extension or CLI
|
||||
- Not persistent — no SQLite, no file queue, in-memory only
|
||||
- Not authenticated — localhost dev tool, no threat model
|
||||
- Not a general-purpose message bus — three hardcoded roles, no dynamic registration
|
||||
@@ -0,0 +1,357 @@
|
||||
# v0.5.x — UX Polish, Settings Redesign & Recovery QR — Design
|
||||
|
||||
**Date:** 2026-05-03
|
||||
**Status:** Draft
|
||||
**Target:** v0.5.1 / next release train
|
||||
|
||||
## Overview
|
||||
|
||||
Three parallel streams building on the v0.5.0 base:
|
||||
|
||||
- **Stream A — Fullscreen + popup layout polish** — fullscreen vault tab gets a new 3-column layout (sidebar with type-category nav, full-width list, slide-in detail drawer); popup gets a polished type-picker; glyph additions; toast system; empty states.
|
||||
- **Stream B — Settings UX redesign** — replace the current flat settings dump with a left-nav sectioned settings page; Security section with trusted-devices and Recovery QR integration.
|
||||
- **Stream C — Recovery QR + setup wizard** — implement the recovery QR cryptographic feature (Rust core + WASM); integrate into the setup wizard's final step; wire into the vault-tab Security settings section.
|
||||
|
||||
Streams A and B share no files with Stream C (Rust/WASM). A and B share only `glyphs.ts` and `styles.css`; all other files are disjoint. All three can run in parallel.
|
||||
|
||||
---
|
||||
|
||||
## Stream A — Fullscreen + Popup Layout Polish
|
||||
|
||||
### A1. Fullscreen vault tab — 3-column layout
|
||||
|
||||
**Current state.** `extension/src/vault/vault.ts` renders a fixed sidebar (~220px) with brand, search, item list, and bottom nav buttons. Clicking `+ new item` navigates to the type-picker. The main pane shows the selected item in a single-column layout.
|
||||
|
||||
**New layout.**
|
||||
|
||||
```
|
||||
┌─────────────┬──────────────────────────┬──────────────────────────┐
|
||||
│ sidebar │ full-width list │ detail drawer (440px) │
|
||||
│ (200px) │ (flex: 1) │ slides in on row click │
|
||||
└─────────────┴──────────────────────────┴──────────────────────────┘
|
||||
```
|
||||
|
||||
**Sidebar changes:**
|
||||
- Replaces the current flat item list with **type-category nav**: all items are listed by section (Logins N, Secure Notes N, Cards N, Identities N, TOTP N, Keys N, Documents N) plus an "All items" entry at the top.
|
||||
- Search bar stays above the category list.
|
||||
- Bottom nav buttons remain (+ new item, ▦ trash, ⌬ devices, ⚙ settings, ⏻ lock) — the `+ new item` button triggers the bottom sheet (see A3).
|
||||
- `⧉` replaces the current `⤴` pop-out button in the **popup toolbar only** — it stays in the popup toolbar and is not added to the fullscreen sidebar (you're already there).
|
||||
|
||||
**Full-width list:**
|
||||
- Each row: 32px type icon (rounded, gold-tinted on selection) + title (13px) + subtitle (URL or type description, 11px muted) + `last-modified` age (10px dim, right-aligned).
|
||||
- Clicking a row: highlights the row and slides in the detail drawer from the right. The list narrows to accommodate the 440px drawer — flex layout handles this naturally.
|
||||
- Active row stays highlighted while drawer is open.
|
||||
|
||||
**Detail drawer (440px):**
|
||||
- Header: type pill (e.g. `LOGIN`) left, action buttons right (`edit`, `history`, `copy pwd` where applicable), `✕` close.
|
||||
- Body: title (18-20px bold) + subtitle (URL/description, muted), then a **2-column field grid** for sibling fields (username/password, first/last name, number/expiry, etc.). Full-width spans for URL, notes, address, and any field without a natural pair.
|
||||
- Close (`✕` or Esc): drawer slides out, list returns to full width.
|
||||
- At ≤ 720px viewport: drawer pushes full-page (list hidden), back breadcrumb `← <Section>` navigates back.
|
||||
|
||||
**Files affected:**
|
||||
- `extension/src/vault/vault.ts` — full layout rewrite (sidebar list → category nav, main pane wiring, drawer state)
|
||||
- `extension/src/vault/vault.css` — layout rules for 3-column, drawer, list rows, responsive breakpoint
|
||||
|
||||
### A2. Fullscreen vault tab — "new item" bottom sheet
|
||||
|
||||
**Current state.** Clicking `+ new item` in the sidebar sets `state.newType = null` and calls `renderPane()` which renders the type-picker inline in the main pane.
|
||||
|
||||
**New behaviour.** A bottom sheet slides up from the bottom edge of the **main pane** (pane-only scrim — sidebar stays interactive).
|
||||
|
||||
- Sheet structure: drag handle, "New item — choose type" label, 7-item type grid (Login, Secure Note, TOTP, Card, Identity, SSH/API Key, Document) as cards with large glyph (28px), name (11px muted). Selected type border turns gold on hover.
|
||||
- Clicking a type: sheet closes, main pane renders the add form for that type.
|
||||
- Dismissing (Esc, click scrim, `✕`): sheet closes, main pane returns to previous state.
|
||||
- Scrim covers the main pane only (not the sidebar). Sidebar nav remains clickable.
|
||||
|
||||
**Files affected:**
|
||||
- `extension/src/vault/vault.ts` — sheet trigger, render, dismiss logic
|
||||
- `extension/src/vault/vault.css` — sheet, scrim, type-card styles
|
||||
|
||||
### A3. Popup — polished type-picker page
|
||||
|
||||
**Current state.** `+ new` button in the popup toolbar navigates directly to the `add` route. `renderItemForm` is called with `state.newType = null`, which presumably renders a type picker inline.
|
||||
|
||||
**New behaviour.** Keep the current navigation model (navigate to `add` route) but upgrade the type-picker page:
|
||||
- Back arrow + "New item" title in the search-bar row (replacing search input).
|
||||
- 2-column grid of type cards: icon (glyph, 20px), name (12px bold), description (10px muted). E.g. "Login / Username + password", "TOTP / 2FA token".
|
||||
- Glyphs not emoji for type icons (use the per-type glyph table from A5).
|
||||
- `Esc` navigates back to the list.
|
||||
- Keyhint bar updates to show `Esc back`.
|
||||
|
||||
**Files affected:**
|
||||
- `extension/src/popup/components/item-list.ts` — `+ new` button label/glyph, keyhint
|
||||
- `extension/src/popup/components/item-form.ts` (or wherever the type picker lives) — card layout, glyphs
|
||||
|
||||
### A4. Glyphs
|
||||
|
||||
Add to `extension/src/shared/glyphs.ts`:
|
||||
|
||||
```ts
|
||||
export const GLYPH_VAULT_TAB = '⧉'; // pop-out to fullscreen vault tab (replaces ⤴)
|
||||
```
|
||||
|
||||
Remove the inline `⤴` from `extension/src/popup/components/item-list.ts:69` and replace with `GLYPH_VAULT_TAB`.
|
||||
|
||||
### A5. Item row type icons
|
||||
|
||||
The popup item list (`buildRowsHtml` in `item-list.ts`) currently renders title-only rows with no visual type anchor. Add a per-type glyph to each row using the item's `ManifestEntry.type` field:
|
||||
|
||||
| Type | Glyph |
|
||||
|------|-------|
|
||||
| login | `◉` |
|
||||
| secure_note | `◫` |
|
||||
| totp | `⊡` |
|
||||
| card | `▭` |
|
||||
| identity | `⌬` |
|
||||
| key | `⊹` |
|
||||
| document | `≡` |
|
||||
|
||||
Icon: 26×26px, rounded, `--bg-elevated` fill, gold-tinted border on active row.
|
||||
|
||||
**Files affected:** `extension/src/popup/components/item-list.ts`, `extension/src/popup/styles.css`
|
||||
|
||||
### A6. Empty states
|
||||
|
||||
Two surfaces:
|
||||
|
||||
1. **Popup item list, vault empty** — centered message: glyph `◈` (28px dim), "No items yet", "Press `+` to add your first item."
|
||||
2. **Popup item list, search returns nothing** — centered message: glyph `⊘` (28px dim), "No results for "{query}"", "Try a shorter search term."
|
||||
3. **Fullscreen list pane, section empty** — same treatment scaled for the wider pane.
|
||||
|
||||
**Files affected:** `extension/src/popup/components/item-list.ts`, `extension/src/vault/vault.ts`
|
||||
|
||||
### A7. Toast notification system
|
||||
|
||||
Replace the current ad-hoc `sync-status` div with a shared toast system:
|
||||
|
||||
- `showToast(message: string, type: 'success' | 'error' | 'info', durationMs = 2500)` in `extension/src/shared/toast.ts`.
|
||||
- Toasts appear bottom-center of the popup / bottom-right of the vault tab, auto-dismiss.
|
||||
- Used for: sync success/failure, copy-to-clipboard confirmation, device registration success.
|
||||
|
||||
**Files affected:** new `extension/src/shared/toast.ts`, `extension/src/popup/styles.css`, `extension/src/vault/vault.css`, call sites in `item-list.ts` and `vault.ts`
|
||||
|
||||
---
|
||||
|
||||
## Stream B — Settings UX Redesign
|
||||
|
||||
### B1. Settings page structure
|
||||
|
||||
Replace the current flat settings dump (`settings.ts` + `settings-vault.ts`) with a unified settings page that renders within the fullscreen vault tab's main pane (and a compact equivalent in the popup).
|
||||
|
||||
**Left-nav sections:**
|
||||
|
||||
```
|
||||
Device
|
||||
⊙ Autofill
|
||||
◈ Display
|
||||
Vault
|
||||
◉ Security ← Recovery QR + trusted devices (replaces devices.ts nav)
|
||||
↻ Generator
|
||||
▦ Retention
|
||||
⤓ Backup
|
||||
≡ Import
|
||||
```
|
||||
|
||||
Each section renders its content in the right panel. The left nav is 148px; content area fills the remainder.
|
||||
|
||||
**Device vs Vault distinction:**
|
||||
- "Device" sections read/write `chrome.storage.local` (per-browser settings).
|
||||
- "Vault" sections read/write encrypted `VaultSettings` (shared across devices via git).
|
||||
|
||||
**Files affected:**
|
||||
- `extension/src/popup/components/settings.ts` — rewrite as sectioned layout
|
||||
- `extension/src/popup/components/settings-vault.ts` — content moves into new section components
|
||||
|
||||
**Note on vault.ts:** DEV-B delivers the settings component with a stable export signature. The `⚙ settings` nav wiring in `vault.ts` is updated as part of Stream A's vault.ts rewrite. DEV-A and DEV-B must agree on the component's export signature before either lands.
|
||||
|
||||
### B2. Autofill section (Device)
|
||||
|
||||
Content replaces the current flat settings dump:
|
||||
|
||||
- **Capture** group: "Auto-detect logins" toggle (was checkbox); "Prompt style" select (bar / toast).
|
||||
- **Blocked sites** group: list of blacklisted hostnames, each with a remove button. Add-hostname input at bottom.
|
||||
|
||||
All options use the standardised `setting-row` pattern: left (title + description), right (control).
|
||||
|
||||
### B3. Display section (Device)
|
||||
|
||||
Moves the existing password-coloring UI (digit color picker, symbol color picker, live swatch, reset) from its current location into a proper Display section card.
|
||||
|
||||
### B4. Security section (Vault)
|
||||
|
||||
**Recovery QR card** (three states, see Stream C for implementation):
|
||||
|
||||
- **State 1 — no QR:** amber warning ("▲ No recovery QR generated — losing your reference image would make this vault unrecoverable"), single "Generate recovery QR…" button.
|
||||
- **State 2 — QR exists, at rest:** green status ("◉ Recovery QR is set up"), last-generated date. Buttons: "Show / print QR…" and "Regenerate…". **No QR is visible in this state.**
|
||||
- **State 3 — explicit view:** modal overlay (scrim over main pane only). QR rendered at ~140×140px. Warning: "▲ Close this window before stepping away. This QR is only displayed, never saved." Actions: "⎙ Print" (triggers `window.print()` scoped to modal) and "Done" (dismisses).
|
||||
|
||||
**Trusted devices** group: subsumes the current `⌬ devices` sidebar nav entry. Each registered device shows name, registration date, fingerprint, and a revoke button. "Register this device" entry for unregistered browsers. Once Stream B lands, the `⌬ devices` button is removed from the vault sidebar nav (settings → Security replaces it).
|
||||
|
||||
### B5. Generator section (Vault)
|
||||
|
||||
Pulls the existing generator-defaults content from `settings-vault.ts` into the new section layout. No functional changes — just consistent styling.
|
||||
|
||||
### B6. Retention section (Vault)
|
||||
|
||||
Pulls the existing retention content (trash retention, field history retention). No functional changes.
|
||||
|
||||
### B7. Backup section (Vault)
|
||||
|
||||
Pulls the existing backup & restore section. No functional changes.
|
||||
|
||||
### B8. Import section (Vault)
|
||||
|
||||
Pulls the existing import section. No functional changes.
|
||||
|
||||
---
|
||||
|
||||
## Stream C — Recovery QR
|
||||
|
||||
### C1. Rust core — `relicario-core/src/recovery_qr.rs`
|
||||
|
||||
Per the existing spec at `docs/superpowers/specs/2026-05-01-recovery-qr-design.md`. Key implementation points:
|
||||
|
||||
**KDF input:**
|
||||
```
|
||||
b"relicario-recovery-v1\0" || u64_be(len(nfc(passphrase))) || nfc(passphrase)
|
||||
```
|
||||
Fed to Argon2id with production params (`m=64MiB, t=3, p=4`), fresh 32-byte salt per generation.
|
||||
|
||||
**Wrap:** `XChaCha20-Poly1305(wrap_key, nonce=OsRng(24), image_secret)` — 32+16=48 bytes ciphertext.
|
||||
|
||||
**Binary payload (109 bytes):**
|
||||
```
|
||||
[magic "RREC" 4B][version 0x01 1B][salt 32B][nonce 24B][ciphertext 48B]
|
||||
```
|
||||
|
||||
**QR encoding:** byte mode, error-correction M, version 6 (41×41 modules). Library: `qrcode` crate (already in workspace or add it).
|
||||
|
||||
**API surface:**
|
||||
```rust
|
||||
pub struct RecoveryQrPayload { /* opaque */ }
|
||||
|
||||
pub fn generate_recovery_qr(
|
||||
passphrase: &str,
|
||||
image_secret: &[u8; 32],
|
||||
) -> Result<RecoveryQrPayload, RelicarioError>;
|
||||
|
||||
pub fn recovery_qr_to_svg(payload: &RecoveryQrPayload) -> String;
|
||||
|
||||
pub fn unwrap_recovery_qr(
|
||||
payload_bytes: &[u8],
|
||||
passphrase: &str,
|
||||
) -> Result<Zeroizing<[u8; 32]>, RelicarioError>;
|
||||
```
|
||||
|
||||
The payload bytes are never written to disk by this module — callers are responsible for rendering only.
|
||||
|
||||
**Passphrase entropy floor:** enforce `zxcvbn score ≥ 3` at vault init in the CLI and the setup wizard (already gated in the extension by 1C-α; confirm CLI `create` command applies the same gate).
|
||||
|
||||
**Files affected:**
|
||||
- `crates/relicario-core/src/recovery_qr.rs` — new module
|
||||
- `crates/relicario-core/src/lib.rs` — pub mod recovery_qr
|
||||
- `crates/relicario-core/src/error.rs` — add `RecoveryQr` error variants if needed
|
||||
- `crates/relicario-core/Cargo.toml` — add `qrcode` crate
|
||||
- `crates/relicario-core/tests/` — new `recovery_qr.rs` test file
|
||||
|
||||
### C2. CLI — `relicario recovery-qr` subcommand group
|
||||
|
||||
```
|
||||
relicario recovery-qr generate # prompts passphrase, renders QR to terminal (kitty/iTerm2 inline protocol or ASCII fallback)
|
||||
relicario recovery-qr unwrap # prompts passphrase, prints image_secret as hex
|
||||
```
|
||||
|
||||
`generate` never writes a file. It renders the QR inline in the terminal using the Kitty graphics protocol if `$TERM` indicates support, falling back to ASCII art via the `qrcode` crate's built-in ASCII renderer.
|
||||
|
||||
**Files affected:** `crates/relicario-cli/src/main.rs`
|
||||
|
||||
### C3. WASM bindings
|
||||
|
||||
```ts
|
||||
// relicario-wasm/src/lib.rs
|
||||
generate_recovery_qr(passphrase: &str, image_secret: &[u8]) -> Result<String, JsValue> // returns SVG string
|
||||
unwrap_recovery_qr(payload_b64: &str, passphrase: &str) -> Result<Vec<u8>, JsValue> // returns image_secret bytes
|
||||
```
|
||||
|
||||
**Files affected:** `crates/relicario-wasm/src/lib.rs`, `crates/relicario-wasm/Cargo.toml`
|
||||
|
||||
### C4. Extension — Recovery QR in Security settings
|
||||
|
||||
Implement the three-state Security section card described in B4:
|
||||
|
||||
- State determined by `chrome.storage.local.recovery_qr_generated_at` (timestamp or null).
|
||||
- "Generate recovery QR…" button: calls WASM `generate_recovery_qr(passphrase, image_secret)` → stores `recovery_qr_generated_at = Date.now()` in local storage → transitions to State 3 (show modal with SVG).
|
||||
- "Show / print QR…" button: re-derives QR (requires vault to be unlocked, master key in session) → shows State 3 modal.
|
||||
- "Regenerate…" button: same as generate, with a confirmation step first.
|
||||
- Print: injects SVG into a `<iframe>` styled for print, calls `iframe.contentWindow.print()`.
|
||||
|
||||
**Files affected:**
|
||||
- New `extension/src/popup/components/settings-security.ts`
|
||||
- `extension/src/popup/components/settings.ts` — wire Security section
|
||||
|
||||
### C5. Extension — Recovery QR in setup wizard (Step 5 "Done")
|
||||
|
||||
The wizard's final step adds a **skippable banner** above the "Download reference image" button:
|
||||
|
||||
```
|
||||
◫ Generate a recovery QR before you go
|
||||
If you lose your reference image, this QR lets you recover your vault.
|
||||
[Generate now] [Skip — I'll do this in Settings]
|
||||
```
|
||||
|
||||
- "Generate now": calls WASM → shows QR modal inline on the wizard page. After dismissing, banner becomes green "◉ Recovery QR generated".
|
||||
- "Skip": dismisses banner permanently for this session; user can generate later from Settings → Security.
|
||||
- The banner is informational, not a blocker. Vault is fully usable without a recovery QR.
|
||||
|
||||
**Files affected:** `extension/src/setup/setup.ts`
|
||||
|
||||
### C6. Setup wizard redesign (Style C)
|
||||
|
||||
Redesign the setup wizard from the current single-column glass-card layout to **Style C (centered hero card)**:
|
||||
|
||||
- Full-page dark background (`--bg-page`).
|
||||
- Relicario logo glyph + wordmark centered at top.
|
||||
- **Colored progress track**: 5 segments, `--success` fill for completed, `--gold` for current, `--border` for pending.
|
||||
- Centered card (max-width 560px): step eyebrow label ("Step N of 5 · <step name>"), h2 heading, hint text, form content, action row.
|
||||
- **Glyphs not emoji** throughout. Mode cards use `◈` (create new) and `⌥` (attach). Mode-card glyphs at 28px. All other icons from the existing glyph set.
|
||||
- Probe-banner success state uses `◉` (filled circle, matches ⊙/⊘ family).
|
||||
- Action row: "◂ back" text button (left), "Continue ▸" primary button (right).
|
||||
|
||||
This is a pure CSS/markup change — no logic changes.
|
||||
|
||||
**Files affected:** `extension/src/setup/setup.ts`, setup CSS (inline or extracted)
|
||||
|
||||
---
|
||||
|
||||
## Responsive behaviour
|
||||
|
||||
| Viewport | Fullscreen behaviour |
|
||||
|---|---|
|
||||
| ≥ 960px | 3-column: sidebar + list + drawer |
|
||||
| 720–960px | 2-column: sidebar + list; drawer pushes full-pane on click |
|
||||
| ≤ 720px | Sidebar collapses (hamburger/icon strip); list full-width; detail is full-page push |
|
||||
|
||||
The popup is always narrow (~340px) — popup-specific components are unaffected by the fullscreen responsive rules.
|
||||
|
||||
---
|
||||
|
||||
## Acceptance criteria (shared)
|
||||
|
||||
- `cargo test` green. `bun run test` green. `bun run build` + `bun run build:firefox` clean.
|
||||
- No raw `snake_case` error codes in any UI surface.
|
||||
- No emoji in any UI surface — all icons are Unicode monochrome glyphs.
|
||||
- `glyphs.ts` is the single source of truth for all icon constants; no inline Unicode literals at call sites.
|
||||
- QR code is never written to any file, `chrome.storage`, or git. `recovery_qr_generated_at` (timestamp only) is the only persisted artifact.
|
||||
- Settings left-nav sections all render without console errors. Device sections read/write `chrome.storage.local`. Vault sections read/write `VaultSettings`.
|
||||
|
||||
---
|
||||
|
||||
## Stream split summary (for multi-agent kickoff)
|
||||
|
||||
| Stream | Owner | Core files | Dependency |
|
||||
|---|---|---|---|
|
||||
| A — Fullscreen + popup layout | DEV-A | `vault.ts`, `vault.css`, `item-list.ts`, `glyphs.ts` | none |
|
||||
| B — Settings UX | DEV-B | `settings.ts`, `settings-vault.ts`, new `settings-security.ts` | waits for C4 interface (can stub) |
|
||||
| C — Recovery QR | DEV-C | `recovery_qr.rs`, `relicario-wasm/src/lib.rs`, `setup.ts`, `settings-security.ts` | none |
|
||||
|
||||
B and C share `settings-security.ts` — DEV-C owns the file, DEV-B wires it into the nav. Coordinate on interface (component export signature) before DEV-B proceeds with B4.
|
||||
@@ -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');
|
||||
});
|
||||
});
|
||||
17
extension/src/popup/components/settings-security.ts
Normal file
17
extension/src/popup/components/settings-security.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
// extension/src/popup/components/settings-security.ts
|
||||
// Stub — real implementation provided by Stream C (DEV-C).
|
||||
|
||||
export async function renderSecuritySection(
|
||||
container: HTMLElement,
|
||||
_sessionHandle: number | null,
|
||||
): Promise<void> {
|
||||
container.innerHTML = `
|
||||
<div class="settings-section-placeholder">
|
||||
<span class="muted">Security settings — loading…</span>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
export function teardownSecuritySection(): void {
|
||||
// no-op in stub
|
||||
}
|
||||
@@ -1,18 +1,111 @@
|
||||
/// Settings view — capture toggle, prompt style, and blacklist management.
|
||||
|
||||
import { sendMessage, navigate, escapeHtml } from '../../shared/state';
|
||||
import type { DeviceSettings } from '../../shared/types';
|
||||
import { GLYPH_TRASH, GLYPH_DEVICES } from '../../shared/glyphs';
|
||||
import { sendMessage, escapeHtml, openVaultTab } from '../../shared/state';
|
||||
import type { VaultSettings, DeviceSettings, TrashRetention, HistoryRetention } from '../../shared/types';
|
||||
import type { ColorScheme } from '../../shared/color-scheme';
|
||||
import {
|
||||
loadColorScheme, saveColorScheme, resetColorScheme,
|
||||
DEFAULT_DIGIT_COLOR, DEFAULT_SYMBOL_COLOR,
|
||||
} from '../../shared/color-scheme';
|
||||
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> {
|
||||
app.innerHTML = '<div class="pad" style="text-align:center; padding-top:20px;"><span class="spinner"></span></div>';
|
||||
type SettingsSection =
|
||||
| '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([
|
||||
sendMessage({ type: 'get_settings' }),
|
||||
sendMessage({ type: 'get_blacklist' }),
|
||||
@@ -26,166 +119,314 @@ export async function renderSettings(app: HTMLElement): Promise<void> {
|
||||
? (blacklistResp.data as { blacklist: string[] }).blacklist
|
||||
: [];
|
||||
|
||||
const blacklistHtml = blacklist.length > 0
|
||||
? blacklist.map((h) => `
|
||||
<div style="display:flex; align-items:center; justify-content:space-between; padding:4px 0; border-bottom:1px solid #21262d;">
|
||||
<span style="font-size:12px; overflow:hidden; text-overflow:ellipsis;">${escapeHtml(h)}</span>
|
||||
<button class="relicario-remove-bl" data-hostname="${escapeHtml(h)}" style="
|
||||
background:transparent; color:#ab2b20; border:none; cursor:pointer;
|
||||
font-size:11px; padding:2px 6px;
|
||||
">remove</button>
|
||||
</div>
|
||||
`).join('')
|
||||
: '<p class="muted" style="font-size:12px;">no blacklisted 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;">←</button>
|
||||
<span style="font-size:14px; font-weight:600;">settings</span>
|
||||
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 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 class="setting-row__control">
|
||||
<input type="checkbox" id="capture-enabled" ${settings.captureEnabled ? 'checked' : ''}>
|
||||
</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 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 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 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>
|
||||
|
||||
<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>
|
||||
<h3 class="settings-section-title" style="margin-top:20px;">Blocked sites</h3>
|
||||
<div id="blacklist-container">
|
||||
${blacklist.length > 0
|
||||
? blacklist.map((h) => `
|
||||
<div class="setting-row">
|
||||
<div class="setting-row__info">
|
||||
<div class="setting-row__title">${escapeHtml(h)}</div>
|
||||
</div>
|
||||
<button class="btn remove-bl" data-hostname="${escapeHtml(h)}" style="font-size:11px;">remove</button>
|
||||
</div>
|
||||
`).join('')
|
||||
: '<p class="muted" style="font-size:12px; padding:8px 0;">No blocked sites.</p>'}
|
||||
</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) => {
|
||||
const checked = (e.target as HTMLInputElement).checked;
|
||||
await sendMessage({ type: 'update_settings', settings: { captureEnabled: checked } });
|
||||
const enabled = (e.target as HTMLInputElement).checked;
|
||||
await sendMessage({ type: 'update_settings', settings: { captureEnabled: enabled } });
|
||||
});
|
||||
|
||||
// Style buttons
|
||||
document.getElementById('style-bar')?.addEventListener('click', async () => {
|
||||
await sendMessage({ type: 'update_settings', settings: { captureStyle: 'bar' } });
|
||||
renderSettings(app);
|
||||
renderAutofillSection(content);
|
||||
});
|
||||
|
||||
document.getElementById('style-toast')?.addEventListener('click', async () => {
|
||||
await sendMessage({ type: 'update_settings', settings: { captureStyle: 'toast' } });
|
||||
renderSettings(app);
|
||||
renderAutofillSection(content);
|
||||
});
|
||||
|
||||
// Blacklist remove buttons
|
||||
document.querySelectorAll('.relicario-remove-bl').forEach((btn) => {
|
||||
content.querySelectorAll<HTMLButtonElement>('.remove-bl').forEach((btn) => {
|
||||
btn.addEventListener('click', async () => {
|
||||
const hostname = (btn as HTMLElement).dataset.hostname;
|
||||
if (hostname) {
|
||||
await sendMessage({ type: 'remove_blacklist', hostname });
|
||||
renderSettings(app);
|
||||
}
|
||||
const host = btn.dataset.hostname;
|
||||
if (!host) return;
|
||||
await sendMessage({ type: 'remove_blacklist', hostname: host });
|
||||
renderAutofillSection(content);
|
||||
});
|
||||
});
|
||||
|
||||
// Render Display section after the rest of the DOM is ready
|
||||
await renderDisplaySection();
|
||||
}
|
||||
|
||||
function updateSwatch(swatch: HTMLElement, digitColor: string, symbolColor: string): 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;
|
||||
|
||||
async function renderDisplaySection(content: HTMLElement): Promise<void> {
|
||||
const scheme = await loadColorScheme();
|
||||
|
||||
container.innerHTML = `
|
||||
<div style="font-size:12px; color:#8b949e; margin-bottom:6px;">display</div>
|
||||
<div style="margin-bottom:8px;">
|
||||
<label style="display:flex; align-items:center; gap:8px; font-size:13px;">
|
||||
<input type="color" id="display-digit-color" value="${escapeHtml(scheme.digit_color)}">
|
||||
digit color
|
||||
</label>
|
||||
content.innerHTML = `
|
||||
<h3 class="settings-section-title">Password coloring</h3>
|
||||
<div class="setting-row">
|
||||
<div class="setting-row__info">
|
||||
<div class="setting-row__title">Digit color</div>
|
||||
</div>
|
||||
<div class="setting-row__control">
|
||||
<input type="color" id="digit-color" value="${escapeHtml(scheme.digit_color)}">
|
||||
</div>
|
||||
</div>
|
||||
<div style="margin-bottom:8px;">
|
||||
<label style="display:flex; align-items:center; gap:8px; font-size:13px;">
|
||||
<input type="color" id="display-symbol-color" value="${escapeHtml(scheme.symbol_color)}">
|
||||
symbol color
|
||||
</label>
|
||||
<div class="setting-row">
|
||||
<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 id="display-swatch" class="color-preview-swatch"></div>
|
||||
<div style="margin-top:8px;">
|
||||
<button id="display-reset" class="btn" style="font-size:11px;">reset to defaults</button>
|
||||
<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>
|
||||
`;
|
||||
|
||||
const digitInput = document.getElementById('display-digit-color') as HTMLInputElement;
|
||||
const symbolInput = document.getElementById('display-symbol-color') as HTMLInputElement;
|
||||
const swatch = document.getElementById('display-swatch') as HTMLElement;
|
||||
|
||||
// Render initial swatch
|
||||
updateSwatch(swatch, scheme.digit_color, scheme.symbol_color);
|
||||
|
||||
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);
|
||||
function refreshPreview(s: ColorScheme): void {
|
||||
const preview = document.getElementById('color-preview');
|
||||
if (!preview) return;
|
||||
preview.style.setProperty('--relicario-pwd-digit-color', s.digit_color);
|
||||
preview.style.setProperty('--relicario-pwd-symbol-color', s.symbol_color);
|
||||
preview.innerHTML = '';
|
||||
preview.appendChild(colorizePassword('Abc123!@#'));
|
||||
}
|
||||
|
||||
digitInput.addEventListener('change', () => void onColorChange());
|
||||
symbolInput.addEventListener('change', () => void onColorChange());
|
||||
refreshPreview(scheme);
|
||||
|
||||
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();
|
||||
digitInput.value = DEFAULT_DIGIT_COLOR;
|
||||
symbolInput.value = DEFAULT_SYMBOL_COLOR;
|
||||
updateSwatch(swatch, DEFAULT_DIGIT_COLOR, DEFAULT_SYMBOL_COLOR);
|
||||
renderDisplaySection(content);
|
||||
});
|
||||
}
|
||||
|
||||
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 & restore</h3>
|
||||
<div class="setting-row">
|
||||
<div class="setting-row__info">
|
||||
<div class="setting-row__title">Export & 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;
|
||||
|
||||
@@ -11,7 +11,7 @@ import { renderUnlock } from './components/unlock';
|
||||
import { renderItemList } from './components/item-list';
|
||||
import { renderItemDetail } from './components/item-detail';
|
||||
import { renderItemForm } from './components/item-form';
|
||||
import { renderSettings } from './components/settings';
|
||||
import { renderSettings, teardownSettings } from './components/settings';
|
||||
import { renderVaultSettings } from './components/settings-vault';
|
||||
import { renderTrash } from './components/trash';
|
||||
import { renderDevices } from './components/devices';
|
||||
@@ -178,6 +178,7 @@ function render(): void {
|
||||
teardownTrash();
|
||||
teardownDevices();
|
||||
teardownFieldHistory();
|
||||
teardownSettings();
|
||||
|
||||
switch (currentState.view) {
|
||||
case 'locked':
|
||||
|
||||
@@ -1573,3 +1573,92 @@ textarea {
|
||||
margin-top: 8px;
|
||||
background: var(--bg-input);
|
||||
}
|
||||
|
||||
/* === 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; }
|
||||
|
||||
@@ -1290,6 +1290,13 @@ textarea {
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
.vault-sidebar__header .brand-logo {
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
margin: 0;
|
||||
display: block;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.vault-sidebar__search {
|
||||
padding: 8px 12px;
|
||||
|
||||
@@ -258,6 +258,7 @@ function renderShell(app: HTMLElement): void {
|
||||
app.innerHTML = `
|
||||
<div class="vault-sidebar">
|
||||
<div class="vault-sidebar__header">
|
||||
<img class="brand-logo" src="icons/relicario-logo-16.svg" alt="">
|
||||
<span class="brand">Relicario</span>
|
||||
</div>
|
||||
<div class="vault-sidebar__search">
|
||||
|
||||
1701
tools/relay/package-lock.json
generated
Normal file
1701
tools/relay/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
17
tools/relay/package.json
Normal file
17
tools/relay/package.json
Normal file
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"name": "@relicario/relay",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"start": "npx tsx server.ts",
|
||||
"test": "node --import=tsx/esm --test queue.test.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@modelcontextprotocol/sdk": "^1.10.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"tsx": "^4.19.0",
|
||||
"@types/node": "^22.0.0"
|
||||
}
|
||||
}
|
||||
58
tools/relay/queue.test.ts
Normal file
58
tools/relay/queue.test.ts
Normal file
@@ -0,0 +1,58 @@
|
||||
import { describe, it, beforeEach } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { RelayQueue, isRole } from "./queue.ts";
|
||||
|
||||
describe("RelayQueue", () => {
|
||||
let q: RelayQueue;
|
||||
|
||||
beforeEach(() => {
|
||||
q = new RelayQueue();
|
||||
});
|
||||
|
||||
it("post + read roundtrip returns the message with correct fields", () => {
|
||||
q.post("dev-b", "pm", "status", "Task P4 DONE");
|
||||
const msgs = q.read("pm");
|
||||
assert.equal(msgs.length, 1);
|
||||
assert.equal(msgs[0].from, "dev-b");
|
||||
assert.equal(msgs[0].to, "pm");
|
||||
assert.equal(msgs[0].kind, "status");
|
||||
assert.equal(msgs[0].body, "Task P4 DONE");
|
||||
assert.ok(typeof msgs[0].id === "string" && msgs[0].id.length > 0);
|
||||
assert.ok(typeof msgs[0].ts === "string");
|
||||
});
|
||||
|
||||
it("consume-once: second read returns empty", () => {
|
||||
q.post("dev-a", "pm", "question", "Should I use approach A?");
|
||||
q.read("pm");
|
||||
const second = q.read("pm");
|
||||
assert.deepEqual(second, []);
|
||||
});
|
||||
|
||||
it("list_pending does not drain inbox", () => {
|
||||
q.post("dev-b", "pm", "directive", "PROCEED");
|
||||
const before = q.pending("pm");
|
||||
assert.equal(before.count, 1);
|
||||
const after = q.read("pm");
|
||||
assert.equal(after.length, 1);
|
||||
});
|
||||
|
||||
it("FIFO ordering across multiple senders", () => {
|
||||
q.post("dev-a", "pm", "status", "first");
|
||||
q.post("dev-b", "pm", "status", "second");
|
||||
q.post("dev-a", "pm", "question", "third");
|
||||
const msgs = q.read("pm");
|
||||
assert.equal(msgs.length, 3);
|
||||
assert.equal(msgs[0].body, "first");
|
||||
assert.equal(msgs[1].body, "second");
|
||||
assert.equal(msgs[2].body, "third");
|
||||
});
|
||||
|
||||
it("isRole rejects unknown strings", () => {
|
||||
assert.ok(isRole("pm"));
|
||||
assert.ok(isRole("dev-a"));
|
||||
assert.ok(isRole("dev-b"));
|
||||
assert.ok(!isRole("dev-c"));
|
||||
assert.ok(!isRole(""));
|
||||
assert.ok(!isRole("PM"));
|
||||
});
|
||||
});
|
||||
55
tools/relay/queue.ts
Normal file
55
tools/relay/queue.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
export type Role = "pm" | "dev-a" | "dev-b";
|
||||
export type MessageKind = "status" | "question" | "directive" | "free";
|
||||
|
||||
export interface RelayMessage {
|
||||
id: string;
|
||||
from: Role;
|
||||
to: Role;
|
||||
kind: MessageKind;
|
||||
body: string;
|
||||
ts: string;
|
||||
}
|
||||
|
||||
const KNOWN_ROLES = new Set<string>(["pm", "dev-a", "dev-b"]);
|
||||
|
||||
export function isRole(s: string): s is Role {
|
||||
return KNOWN_ROLES.has(s);
|
||||
}
|
||||
|
||||
export class RelayQueue {
|
||||
private readonly queues = new Map<Role, RelayMessage[]>([
|
||||
["pm", []],
|
||||
["dev-a", []],
|
||||
["dev-b", []],
|
||||
]);
|
||||
|
||||
post(from: Role, to: Role, kind: MessageKind, body: string): RelayMessage {
|
||||
const msg: RelayMessage = {
|
||||
id: randomUUID(),
|
||||
from,
|
||||
to,
|
||||
kind,
|
||||
body,
|
||||
ts: new Date().toISOString(),
|
||||
};
|
||||
this.queues.get(to)!.push(msg);
|
||||
return msg;
|
||||
}
|
||||
|
||||
read(forRole: Role): RelayMessage[] {
|
||||
const inbox = this.queues.get(forRole)!;
|
||||
const messages = [...inbox];
|
||||
inbox.length = 0;
|
||||
return messages;
|
||||
}
|
||||
|
||||
pending(forRole: Role): { count: number; kinds: MessageKind[] } {
|
||||
const inbox = this.queues.get(forRole)!;
|
||||
return {
|
||||
count: inbox.length,
|
||||
kinds: inbox.map((m) => m.kind),
|
||||
};
|
||||
}
|
||||
}
|
||||
159
tools/relay/server.ts
Normal file
159
tools/relay/server.ts
Normal file
@@ -0,0 +1,159 @@
|
||||
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
||||
import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
|
||||
import {
|
||||
CallToolRequestSchema,
|
||||
ListToolsRequestSchema,
|
||||
} from "@modelcontextprotocol/sdk/types.js";
|
||||
import http from "node:http";
|
||||
import { RelayQueue, isRole } from "./queue.ts";
|
||||
|
||||
const PORT = 7331;
|
||||
const queue = new RelayQueue();
|
||||
|
||||
const mcpServer = new Server(
|
||||
{ name: "relay", version: "0.1.0" },
|
||||
{ capabilities: { tools: {} } }
|
||||
);
|
||||
|
||||
const TOOLS = [
|
||||
{
|
||||
name: "post_message",
|
||||
description:
|
||||
"Push a message to a recipient's inbox. Returns the assigned message id.",
|
||||
inputSchema: {
|
||||
type: "object" as const,
|
||||
properties: {
|
||||
from: {
|
||||
type: "string",
|
||||
enum: ["pm", "dev-a", "dev-b"],
|
||||
description: "Your role name",
|
||||
},
|
||||
to: {
|
||||
type: "string",
|
||||
enum: ["pm", "dev-a", "dev-b"],
|
||||
description: "Recipient role name",
|
||||
},
|
||||
kind: {
|
||||
type: "string",
|
||||
enum: ["status", "question", "directive", "free"],
|
||||
description: "Message type matching the coordination protocol",
|
||||
},
|
||||
body: {
|
||||
type: "string",
|
||||
description: "Message body — freeform markdown, typically the full formatted block",
|
||||
},
|
||||
},
|
||||
required: ["from", "to", "kind", "body"],
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "read_messages",
|
||||
description:
|
||||
"Pop and return all pending messages for this recipient. Inbox is empty after this call (consume-once).",
|
||||
inputSchema: {
|
||||
type: "object" as const,
|
||||
properties: {
|
||||
for: {
|
||||
type: "string",
|
||||
enum: ["pm", "dev-a", "dev-b"],
|
||||
description: "Your role name",
|
||||
},
|
||||
},
|
||||
required: ["for"],
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "list_pending",
|
||||
description:
|
||||
"Return count and kinds of pending messages without consuming them.",
|
||||
inputSchema: {
|
||||
type: "object" as const,
|
||||
properties: {
|
||||
for: {
|
||||
type: "string",
|
||||
enum: ["pm", "dev-a", "dev-b"],
|
||||
description: "Your role name",
|
||||
},
|
||||
},
|
||||
required: ["for"],
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
mcpServer.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS }));
|
||||
|
||||
mcpServer.setRequestHandler(CallToolRequestSchema, async (request) => {
|
||||
const { name, arguments: args } = request.params;
|
||||
const a = args as Record<string, string>;
|
||||
|
||||
if (name === "post_message") {
|
||||
if (!isRole(a.from)) {
|
||||
return { content: [{ type: "text" as const, text: `Error: unknown role "${a.from}"` }], isError: true };
|
||||
}
|
||||
if (!isRole(a.to)) {
|
||||
return { content: [{ type: "text" as const, text: `Error: unknown role "${a.to}"` }], isError: true };
|
||||
}
|
||||
const kind = a.kind as "status" | "question" | "directive" | "free";
|
||||
const msg = queue.post(a.from, a.to, kind, a.body);
|
||||
const ts = new Date(msg.ts).toTimeString().slice(0, 8);
|
||||
const preview = a.body.slice(0, 60).replace(/\n/g, " ");
|
||||
const ellipsis = a.body.length > 60 ? "..." : "";
|
||||
process.stdout.write(`[${ts}] ${a.from} → ${a.to} [${kind}] "${preview}${ellipsis}"\n`);
|
||||
return { content: [{ type: "text" as const, text: JSON.stringify({ id: msg.id }) }] };
|
||||
}
|
||||
|
||||
if (name === "read_messages") {
|
||||
if (!isRole(a.for)) {
|
||||
return { content: [{ type: "text" as const, text: `Error: unknown role "${a.for}"` }], isError: true };
|
||||
}
|
||||
const messages = queue.read(a.for);
|
||||
return { content: [{ type: "text" as const, text: JSON.stringify(messages) }] };
|
||||
}
|
||||
|
||||
if (name === "list_pending") {
|
||||
if (!isRole(a.for)) {
|
||||
return { content: [{ type: "text" as const, text: `Error: unknown role "${a.for}"` }], isError: true };
|
||||
}
|
||||
const result = queue.pending(a.for);
|
||||
return { content: [{ type: "text" as const, text: JSON.stringify(result) }] };
|
||||
}
|
||||
|
||||
return {
|
||||
content: [{ type: "text" as const, text: `Error: unknown tool "${name}"` }],
|
||||
isError: true,
|
||||
};
|
||||
});
|
||||
|
||||
const transports = new Map<string, SSEServerTransport>();
|
||||
|
||||
const httpServer = http.createServer(async (req, res) => {
|
||||
try {
|
||||
if (req.method === "GET" && req.url === "/sse") {
|
||||
const transport = new SSEServerTransport("/message", res);
|
||||
transports.set(transport.sessionId, transport);
|
||||
transport.onclose = () => transports.delete(transport.sessionId);
|
||||
await mcpServer.connect(transport);
|
||||
} else if (req.method === "POST" && req.url?.startsWith("/message")) {
|
||||
const url = new URL(req.url, `http://127.0.0.1:${PORT}`);
|
||||
const sessionId = url.searchParams.get("sessionId") ?? "";
|
||||
const transport = transports.get(sessionId);
|
||||
if (transport) {
|
||||
await transport.handlePostMessage(req, res);
|
||||
} else {
|
||||
res.writeHead(404, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify({ error: "session not found" }));
|
||||
}
|
||||
} else {
|
||||
res.writeHead(404).end("not found");
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("[relay] error:", err);
|
||||
if (!res.headersSent) res.writeHead(500).end(String(err));
|
||||
}
|
||||
});
|
||||
|
||||
httpServer.listen(PORT, "127.0.0.1", () => {
|
||||
console.log(`[relay] server ready on :${PORT}`);
|
||||
console.log(`[relay] tools: post_message, read_messages, list_pending`);
|
||||
console.log(`[relay] waiting for connections — Ctrl-C to stop`);
|
||||
});
|
||||
99
tools/relay/start.sh
Executable file
99
tools/relay/start.sh
Executable file
@@ -0,0 +1,99 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
REPO_ROOT="$(git -C "$SCRIPT_DIR" rev-parse --show-toplevel)"
|
||||
PORT=7331
|
||||
MODE="manual"
|
||||
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
--tmux) MODE="tmux" ;;
|
||||
--kitty) MODE="kitty" ;;
|
||||
--manual) MODE="manual" ;;
|
||||
*) echo "Unknown option: $arg" >&2; echo "Usage: $0 [--manual|--tmux|--kitty]" >&2; exit 1 ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# Port check
|
||||
if lsof -ti:"$PORT" &>/dev/null; then
|
||||
echo "Error: port $PORT is already in use."
|
||||
echo "Relay already running? Kill it with: kill \$(lsof -ti:$PORT)"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Install deps (no-op if node_modules current)
|
||||
cd "$SCRIPT_DIR"
|
||||
npm install --silent
|
||||
|
||||
# Discover latest coordination prompts for instructions
|
||||
COORD_DIR="$REPO_ROOT/docs/superpowers/coordination"
|
||||
PM_PROMPT="$(ls -t "$COORD_DIR"/*-pm-prompt.md 2>/dev/null | head -1 || echo "(none found — run multi-agent-kickoff skill first)")"
|
||||
DEV_A_PROMPT="$(ls -t "$COORD_DIR"/*-dev-a-prompt.md 2>/dev/null | head -1 || echo "(none found)")"
|
||||
DEV_B_PROMPT="$(ls -t "$COORD_DIR"/*-dev-b-prompt.md 2>/dev/null | head -1 || echo "(none found)")"
|
||||
|
||||
print_manual_instructions() {
|
||||
echo ""
|
||||
echo "╔══════════════════════════════════════════════════════════════╗"
|
||||
echo "║ RELAY SERVER — MULTI-AGENT LIFT LAUNCHER ║"
|
||||
echo "╚══════════════════════════════════════════════════════════════╝"
|
||||
echo ""
|
||||
echo "Open 3 new terminals. In each, start Claude Code and paste"
|
||||
echo "the content BELOW the '---' line from the corresponding file."
|
||||
echo ""
|
||||
echo " Terminal 1 (PM): cat '$PM_PROMPT'"
|
||||
echo " Terminal 2 (Dev A): cat '$DEV_A_PROMPT'"
|
||||
echo " Terminal 3 (Dev B): cat '$DEV_B_PROMPT'"
|
||||
echo ""
|
||||
echo "This terminal becomes the relay log. Keep it open."
|
||||
echo ""
|
||||
echo "══════════════════════════════════════════════════════════════"
|
||||
}
|
||||
|
||||
launch_tmux() {
|
||||
SESSION="relay-lift"
|
||||
tmux new-session -d -s "$SESSION" -n "relay" \
|
||||
"cd '$SCRIPT_DIR' && npx tsx server.ts"
|
||||
tmux new-window -t "$SESSION:" -n "pm" "cd '$REPO_ROOT' && claude"
|
||||
tmux new-window -t "$SESSION:" -n "dev-a" "cd '$REPO_ROOT' && claude"
|
||||
tmux new-window -t "$SESSION:" -n "dev-b" "cd '$REPO_ROOT' && claude"
|
||||
echo ""
|
||||
echo "[relay] Opened tmux session '$SESSION' with 4 windows: relay, pm, dev-a, dev-b."
|
||||
echo "[relay] Paste the kickoff prompt into each Claude window."
|
||||
echo " Prompts:"
|
||||
echo " PM: $PM_PROMPT"
|
||||
echo " Dev A: $DEV_A_PROMPT"
|
||||
echo " Dev B: $DEV_B_PROMPT"
|
||||
echo ""
|
||||
tmux attach-session -t "$SESSION"
|
||||
}
|
||||
|
||||
launch_kitty() {
|
||||
kitty @ launch --new-tab --tab-title "relay" -- \
|
||||
bash -c "cd '$SCRIPT_DIR' && npx tsx server.ts"
|
||||
kitty @ launch --new-window --window-title "PM" -- \
|
||||
bash -c "cd '$REPO_ROOT' && claude"
|
||||
kitty @ launch --new-window --window-title "Dev-A" -- \
|
||||
bash -c "cd '$REPO_ROOT' && claude"
|
||||
kitty @ launch --new-window --window-title "Dev-B" -- \
|
||||
bash -c "cd '$REPO_ROOT' && claude"
|
||||
echo ""
|
||||
echo "[relay] Opened kitty tab 'relay' + 3 windows (PM, Dev-A, Dev-B)."
|
||||
echo " Paste the kickoff prompts into each Claude window."
|
||||
echo " PM: $PM_PROMPT"
|
||||
echo " Dev A: $DEV_A_PROMPT"
|
||||
echo " Dev B: $DEV_B_PROMPT"
|
||||
}
|
||||
|
||||
case "$MODE" in
|
||||
manual)
|
||||
print_manual_instructions
|
||||
exec npx tsx "$SCRIPT_DIR/server.ts"
|
||||
;;
|
||||
tmux)
|
||||
launch_tmux
|
||||
;;
|
||||
kitty)
|
||||
launch_kitty
|
||||
;;
|
||||
esac
|
||||
10
tools/relay/tsconfig.json
Normal file
10
tools/relay/tsconfig.json
Normal file
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"strict": true,
|
||||
"noEmit": true
|
||||
},
|
||||
"include": ["*.ts"]
|
||||
}
|
||||
Reference in New Issue
Block a user