Files
SeedPass/js/packages/cli/test/profiles.test.ts
T
thePR0M3TH3ANandClaude Fable 5 0f8ce35c47 cross-impl: prove Python/TS profile interop, fix two compatibility bugs
Fixtures show both implementations compute the same values. This adds the
missing half: proof they can read each other's on-disk profiles and
backups, using each side's real code paths.

scripts/cross_impl_check.py (12 checks, wired into CI):
  A. Python creates a profile -> TS opens the index, derives every secret
     identically, and unlocks it with the master password alone
  B. TS creates a profile -> Python decrypts parent_seed.enc and the index,
     recovers the same seed, derives the same secrets
  C. Portable backups round-trip both directions (Python verifies the
     checksum of a TS-written export)
  D. Both implementations reject a bad-checksum mnemonic

Two real compatibility bugs it caught, both fixed:

- TS-created profiles were unopenable by Python. Python only honors the
  recorded parent-seed KDF parameters when kdf.name is exactly "pbkdf2";
  TS wrote "pbkdf2-sha256" with an empty salt and 100k iterations, so
  Python fell back to its config defaults (200k, fingerprint salt) and
  derived a different key. TS now writes exactly what
  PasswordManager._build_seed_kdf_config does, and its own unlock path
  honors the recorded salt and iteration count.

- TS accepted invalid BIP-39 mnemonics. Seed derivation takes any string,
  so a typo'd phrase silently produced a *different* vault -- unopenable
  by Python and unrecoverable by the user. Mnemonics are now validated
  wherever they enter (profile creation and SEEDPASS_MNEMONIC), with an
  error that says why it matters.

Also: docs/typescript_cutover_plan.md records the gate list for promoting
TS to main and retiring Python to legacy/reference -- P0 gates 1-4 are
green, 5-7 (feature parity tail, packaging, migration/rollback) are not.
The Python tree stays in CI after cutover as the compatibility oracle.

Regression tests for both bugs. 151 core + 46 CLI tests green,
12/12 cross-implementation checks green.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-14 16:15:19 -04:00

185 lines
7.2 KiB
TypeScript

/**
* Profile, config, and session-agent tests: the full unlock lifecycle with
* no SEEDPASS_MNEMONIC in the environment — the agent is the only seed
* source, exactly how an agent-driven workflow would run.
*/
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { mkdtemp, readFile } from "node:fs/promises";
import { existsSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import process from "node:process";
import { mnemonics } from "@seedpass/test-vectors";
import { generateFingerprint, sha256Hex, hexToBytes, utf8 } from "@seedpass/core";
import { buildProgram, AgentDaemon, agentSocketPath, type ProgramIo } from "../src/index.js";
const MNEMONIC = mnemonics["abandon12"]!;
const FINGERPRINT = generateFingerprint(MNEMONIC);
const PASSWORD = "profile-test-password";
let appDir: string;
let daemon: AgentDaemon;
interface RunResult {
stdout: string;
error?: unknown;
}
async function run(env: Record<string, string | undefined>, ...argv: string[]): Promise<RunResult> {
const saved: Record<string, string | undefined> = {};
for (const [k, v] of Object.entries(env)) {
saved[k] = process.env[k];
if (v === undefined) delete process.env[k];
else process.env[k] = v;
}
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;
} finally {
for (const [k, v] of Object.entries(saved)) {
if (v === undefined) delete process.env[k];
else process.env[k] = v;
}
}
return { stdout: out.join("\n"), error };
}
beforeAll(async () => {
appDir = await mkdtemp(join(tmpdir(), "seedpass-appdir-"));
process.env["SEEDPASS_AGENT_SOCK"] = join(appDir, "agent.sock");
daemon = new AgentDaemon(agentSocketPath(appDir), 900);
await daemon.start();
});
afterAll(async () => {
await daemon.stop();
delete process.env["SEEDPASS_AGENT_SOCK"];
});
describe("profile lifecycle", () => {
it("creates a Python-layout profile from env secrets", async () => {
const r = await run(
{ SEEDPASS_MNEMONIC: MNEMONIC, SEEDPASS_PASSWORD: PASSWORD },
"fingerprint", "add", "--name", "main",
);
expect(JSON.parse(r.stdout).fingerprint).toBe(FINGERPRINT);
expect(existsSync(join(appDir, FINGERPRINT, "parent_seed.enc"))).toBe(true);
expect(existsSync(join(appDir, FINGERPRINT, "seedpass_entries_db.json.enc"))).toBe(true);
const meta = JSON.parse(await readFile(join(appDir, "fingerprints.json"), "utf8"));
expect(meta).toEqual({
fingerprints: [FINGERPRINT],
last_used: FINGERPRINT,
names: { [FINGERPRINT]: "main" },
});
});
it("writes Python-compatible parent-seed KDF metadata", async () => {
// Python's PasswordManager._derive_seed_key only takes the recorded
// parameters when kdf.name is exactly "pbkdf2"; anything else makes it
// fall back to its config defaults and derive a different key, leaving
// TS-created profiles unopenable there.
const wrapper = JSON.parse(
await readFile(join(appDir, FINGERPRINT, "parent_seed.enc"), "utf8"),
) as { kdf: { name: string; params: { iterations: number }; salt_b64: string } };
expect(wrapper.kdf.name).toBe("pbkdf2");
expect(wrapper.kdf.params.iterations).toBe(200000);
// salt = sha256(fingerprint)[:16], as Python computes it
const expectedSalt = Buffer.from(
hexToBytes(sha256Hex(utf8(FINGERPRINT))).slice(0, 16),
).toString("base64");
expect(wrapper.kdf.salt_b64).toBe(expectedSalt);
});
it("refuses an invalid mnemonic instead of creating an unrecoverable vault", async () => {
// Valid words, wrong checksum. BIP-39 seed derivation would happily
// accept it and produce a different vault that nothing can recover.
const bogus = "gaze stereo trend brown chunk hero pole width once tent lift bird";
const r = await run(
{ SEEDPASS_MNEMONIC: bogus, SEEDPASS_PASSWORD: "x" },
"fingerprint", "add", "--name", "should-not-exist",
);
expect(String((r.error as Error).message)).toContain("valid BIP-39");
const meta = JSON.parse(await readFile(join(appDir, "fingerprints.json"), "utf8"));
expect(meta.fingerprints).toHaveLength(1);
});
it("lists and switches profiles", async () => {
const r = await run({}, "fingerprint", "list");
expect(JSON.parse(r.stdout)).toEqual([
{ fingerprint: FINGERPRINT, name: "main", current: true },
]);
});
});
describe("agent unlock lifecycle (no mnemonic in env)", () => {
it("locked vault refuses access with a helpful error", async () => {
const r = await run({ SEEDPASS_MNEMONIC: undefined }, "entry", "list");
expect(String((r.error as Error).message)).toContain("vault is locked");
});
it("vault unlock hands the seed to the agent using only the password", async () => {
const r = await run(
{ SEEDPASS_MNEMONIC: undefined, SEEDPASS_PASSWORD: PASSWORD },
"vault", "unlock", "--ttl", "60",
);
const row = JSON.parse(r.stdout);
expect(row.unlocked).toBe(FINGERPRINT);
expect(row.expires_at).toBeGreaterThan(Date.now() / 1000);
});
it("profile vault opens via the agent, no env mnemonic, no --vault", async () => {
const list = await run({ SEEDPASS_MNEMONIC: undefined }, "entry", "list");
expect(JSON.parse(list.stdout)).toEqual([]);
const add = await run(
{ SEEDPASS_MNEMONIC: undefined },
"entry", "add", "key-value", "agent-made", "k", "agent-value",
);
expect(JSON.parse(add.stdout).ref).toBe("sp://entry/0");
expect(add.stdout).not.toContain("agent-value");
const reveal = await run(
{ SEEDPASS_MNEMONIC: undefined },
"entry", "reveal", "agent-made",
);
expect(reveal.stdout).toBe("agent-value");
});
it("agent status shows the unlocked profile; lock drops it", async () => {
const status = await run({}, "agent", "status");
expect(JSON.parse(status.stdout).map((p: { fingerprint: string }) => p.fingerprint)).toEqual([
FINGERPRINT,
]);
const lock = await run({ SEEDPASS_MNEMONIC: undefined }, "vault", "lock");
expect(JSON.parse(lock.stdout).locked).toBe(1);
const denied = await run({ SEEDPASS_MNEMONIC: undefined }, "entry", "list");
expect(String((denied.error as Error).message)).toContain("vault is locked");
});
});
describe("config", () => {
it("returns defaults, persists sets, and redacts hashes", async () => {
const env = { SEEDPASS_MNEMONIC: MNEMONIC };
const defaults = JSON.parse((await run(env, "config", "get")).stdout);
expect(defaults.relays).toHaveLength(3);
expect(defaults.kdf_iterations).toBe(200000);
await run(env, "config", "set", "clipboard_clear_delay", "10");
await run(env, "config", "set", "relays", '["wss://relay.example"]');
const after = JSON.parse((await run(env, "config", "get")).stdout);
expect(after.clipboard_clear_delay).toBe(10);
expect(after.relays).toEqual(["wss://relay.example"]);
await run(env, "config", "set", "pin_hash", "supersecret");
const redacted = JSON.parse((await run(env, "config", "get", "pin_hash")).stdout);
expect(redacted.pin_hash).toBe("<redacted>");
});
});