Files
SeedPass/js/packages/cli/test/nostr.test.ts
T
thePR0M3TH3ANandClaude Opus 5 51855ddea6 Validate high-risk partition records before deriving secrets from them
The first real finding from the new lint gate, and the one that justified
turning it on.

`decryptPartition` proves a partition file is AUTHENTIC — it decrypts under
the partition key and Fernet carries an HMAC, so nobody without the factor
wrote it. It proves nothing about a record's SHAPE: it checks only that each
value is an object. Both hydration paths then asserted the result straight
into `Entry` and handed it to materializeSecret.

That was the one place in the vault where a record reached secret derivation
without passing the schema. Every entry arriving through the index goes
through parseVaultIndex; the partition path did not — and the partition is
where the ssh keys, pgp keys and seeds live. Python writes these files and
validates nothing, so a shape divergence between the implementations, a
renamed field or a kind added on one side, would not have raised anything
here. It would have derived from whatever fields it found and returned a
confidently wrong secret, which is worse than an error by a wide margin.

`parsePartitionRecord` validates per RECORD rather than per file, so one odd
record fails one entry instead of locking the user out of every secret in the
partition. The error names the entry and nothing else, because the record IS
the secret — asserted, along with the fact that a record of an unknown kind
is still carried through untouched per spec §8.2, which validation must not
quietly have turned into a refusal.

Typing the API's hydration path properly removed the round trip it used to
make — Entry to Record and back — so the fix subtracts assertions rather than
trading one for another.

Also clears the twelve dead imports the gate found. One of them was not dead:
the `cause` binding in decryptPartition is discarded on purpose, because the
reason a Fernet decrypt failed distinguishes "wrong key" from "corrupt blob"
and surfacing that hands a caller an oracle for probing the factor. It is now
`catch {}` with that written down, which says it better than an ignored name.

Chained assertions: 44 -> 42. Tests: 689 passing.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Vtx94nXDmNgXEeThUZP4QN
2026-08-20 12:52:58 -04:00

130 lines
5.2 KiB
TypeScript

/**
* End-to-end CLI relay sync: create a profile, add entries, sync to an
* in-process relay, destroy the local vault, restore it from the relay.
*/
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { mkdtemp, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import process from "node:process";
import { mnemonics, nostrKeyCases } from "@seedpass/test-vectors";
import { generateFingerprint } from "@seedpass/core";
import { buildProgram, type ProgramIo } from "../src/index.js";
import { MockRelay } from "../../core/test/mockRelay.js";
const MNEMONIC = mnemonics["abandon12"]!;
const FINGERPRINT = generateFingerprint(MNEMONIC);
let appDir: string;
let relay: MockRelay;
async function run(...argv: string[]): Promise<{ stdout: string; error?: unknown }> {
const out: string[] = [];
const io: ProgramIo = { out: (l: string) => out.push(l), err: () => {} };
let error: unknown;
try {
await buildProgram(io).parseAsync(["node", "seedpass-js", "--app-dir", appDir, ...argv]);
} catch (e) {
error = e;
}
return { stdout: out.join("\n"), error };
}
beforeAll(async () => {
appDir = await mkdtemp(join(tmpdir(), "seedpass-nostr-"));
process.env["SEEDPASS_MNEMONIC"] = MNEMONIC;
process.env["SEEDPASS_PASSWORD"] = "nostr-test-pw";
relay = new MockRelay();
await relay.start();
await run("fingerprint", "add", "--name", "sync-test");
});
afterAll(async () => {
await relay.stop();
delete process.env["SEEDPASS_PASSWORD"];
});
describe("nostr CLI", () => {
it("get-pubkey matches the app-1237 fixture npub", async () => {
const fixture = nostrKeyCases.find(
(c) => c.mnemonic_id === "abandon12" && c.account_index === 0,
)!;
const r = await run("nostr", "get-pubkey");
expect(r.stdout).toBe(fixture.npub);
});
it("manages the relay list in config", async () => {
await run("nostr", "add-relay", relay.url);
const list = JSON.parse((await run("nostr", "list-relays")).stdout) as string[];
expect(list).toContain(relay.url);
// Keep only the mock relay so sync never touches the network
while (true) {
const current = JSON.parse((await run("nostr", "list-relays")).stdout) as string[];
const removable = current.findIndex((u) => u !== relay.url);
if (removable === -1) break;
await run("nostr", "remove-relay", String(removable + 1));
}
const final = JSON.parse((await run("nostr", "list-relays")).stdout) as string[];
expect(final).toEqual([relay.url]);
const bad = await run("nostr", "add-relay", "https://not-a-relay");
expect(String((bad.error as Error).message)).toContain("ws://");
});
it("merges rather than discarding unsynced local entries", async () => {
// Publish a snapshot, then create a local entry that the snapshot does
// not contain. A restore must not silently throw that entry away.
await run("entry", "add", "key-value", "pre-sync", "k", "in-snapshot");
await run("nostr", "sync", "--chunk-limit", "400");
await run("entry", "add", "key-value", "local-only", "k", "not-in-snapshot");
const restored = JSON.parse((await run("nostr", "restore")).stdout);
expect(restored.mode).toBe("merged");
expect(restored.local_backup).toBeTruthy();
const labels = (JSON.parse((await run("entry", "list")).stdout) as { label: string }[]).map(
(r) => r.label,
);
expect(labels).toContain("local-only");
expect(labels).toContain("pre-sync");
expect((await run("entry", "reveal", "local-only")).stdout).toBe("not-in-snapshot");
});
it("requires explicit confirmation to discard local state", async () => {
const denied = await run("nostr", "restore", "--replace");
expect(String((denied.error as Error).message)).toContain("--yes");
});
it("syncs the vault to the relay and restores after local destruction", async () => {
await run("entry", "add", "key-value", "synced-secret", "k", "value-roundtrip");
await run("entry", "add", "password", "synced-site", "--length", "20");
const sync = await run("nostr", "sync", "--chunk-limit", "300");
const syncRow = JSON.parse(sync.stdout);
expect(syncRow.manifest_id).toMatch(/^[0-9a-f]{64}$/);
expect(syncRow.chunk_event_ids.length).toBeGreaterThan(0);
expect(relay.events.some((e) => e.kind === 30070)).toBe(true);
// Destroy the local vault
const vaultPath = join(appDir, FINGERPRINT, "seedpass_entries_db.json.enc");
await writeFile(vaultPath, "garbage");
const broken = await run("entry", "list");
expect(broken.error).toBeTruthy();
// Restore from the relay alone
const restore = await run("nostr", "restore");
const restored = JSON.parse(restore.stdout);
// The local vault was unreadable, so this is a recovery, not a merge
expect(restored.mode).toBe("restored");
expect(restored.deltas_applied).toBe(0);
const list = JSON.parse((await run("entry", "list")).stdout) as { label: string }[];
expect(list.map((e) => e.label)).toContain("synced-secret");
expect(list.map((e) => e.label)).toContain("synced-site");
const reveal = await run("entry", "reveal", "synced-secret");
expect(reveal.stdout).toBe("value-roundtrip");
});
});