feat(agent): port high-risk partitions and approval gates

High-risk partitions move ssh/pgp/seed/nostr/managed_account records out of
the vault index into a separately encrypted file, so those kinds need a SECOND
factor beyond the master password. The index keeps a stub carrying kind, label
and archived — enough to list, nothing more.

Both file formats are byte-compatible with Python and verified bidirectionally:
TS unwraps a Python-written key envelope and reads a Python-written partition,
and Python unwraps a TS-written envelope and reads a TS-written partition. That
matters more than usual here — the entries are SSH keys, PGP keys and seeds, so
a partition only one implementation can open is lost secrets, not an
inconvenience. This required a Fernet encryptor in core, which had been
decrypt-only by design; the header now says why that exception exists and that
no other Fernet payload should ever be written.

**One deliberate divergence, and it is the reason this is not a straight port.**
Python records an unlock session in agent_high_risk_unlock.json, and that record
contains the partition_key_tag — the value the partition file's encryption key
is derived from. So for the life of any Python unlock session the partition is
decryptable from disk alone, with no factor, by anything that can read the app
directory; both files live in the same directory, so "can read one" implies "can
read the other". That voids the guarantee the partition exists to provide.
Verified empirically before writing any of this.

Here the tag lives only in the session agent's memory, beside the parent seeds
it already holds, with the same TTL discipline — and in the API process's memory
for the API. Nothing derived from the factor reaches disk, asserted by a test
that scans every file in the app directory for the tag, and confirmed on a live
install. No file format or interop changes; only where the live session lives.

Other properties the tests pin:
  - a locked partition refuses reveal rather than deriving from the stub, which
    would return a plausible wrong secret
  - locking the vault drops the high-risk grant, which is scoped to it
  - the grant expires on its own clock, typically much shorter than the seed's
  - unlock is owner-gated: a scoped token cannot reach it
  - the tag is absent from the audit log, which records only that an unlock
    happened
  - the factor comes from the environment, never argv
  - factor-set refuses to replace an existing factor, since a new partition key
    would make an existing partition permanently unreadable
  - migrate writes the partition BEFORE the index, so a crash between them
    cannot leave stubs pointing at records that were never stored

Approval gates port straight across: one-shot (or N-use) authorizations for
export / reveal_parent_seed / private_key_retrieval, consumed under the store
lock so two callers cannot both spend the last use, with every failure mode
getting its own reason string matching Python's. A corrupt store reads as empty,
which fails closed.

API: /api/v1/high-risk/{status,unlock,lock} are real rather than 501. Unlock
needs the bearer token, the master password header AND the factor header; a
wrong factor gets one indistinguishable reason so probing cannot tell failures
apart.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Vtx94nXDmNgXEeThUZP4QN
This commit is contained in:
thePR0M3TH3ANandClaude Opus 5 committed 2026-08-19 10:19:39 -04:00
1 parent 885cbe5665
commit 0c48c1f9dc
18 files changed
+1913 -15

No files matched your search

+152
View File
@@ -117,6 +117,22 @@ interface Held {
expiresAt: number;
}
/**
* A live high-risk unlock, held in memory only.
*
* `tag` is the partition key tag, from which the partition file's encryption
* key is derived — so it is key material, not an identifier. Python writes
* this value into `agent_high_risk_unlock.json`, which means that for the
* life of a Python unlock session the partition is decryptable from disk with
* no factor at all, defeating the second factor the partition exists to
* require. Keeping it here, in the process that already holds unlocked parent
* seeds, is the same trust boundary with none of the disk exposure.
*/
interface HighRiskSession {
tag: string;
expiresAt: number;
}
export interface AgentStatusProfile {
fingerprint: string;
expires_at: number;
@@ -132,10 +148,18 @@ const OWNER_OPS = new Set([
"lock",
"status",
"shutdown",
// High-risk unlock is strictly more privileged than an ordinary unlock:
// it is the second factor for the entry kinds deemed to need one, so a
// scoped token must never be able to reach it.
"high-risk-unlock",
"high-risk-lock",
"high-risk-status",
"high-risk-tag",
]);
export class AgentDaemon {
private held = new Map<string, Held>();
private highRisk = new Map<string, HighRiskSession>();
private tokens = new Map<string, TokenRecord>();
private audits = new Map<string, AuditLog>();
private auditQueue: Promise<unknown> = Promise.resolve();
@@ -465,6 +489,9 @@ export class AgentDaemon {
/** Drop everything derived from a profile's seed. */
private forget(fingerprint: string): void {
this.held.delete(fingerprint);
// A high-risk unlock is scoped to an unlocked profile; locking the vault
// must not leave the stronger grant standing.
this.highRisk.delete(fingerprint);
// Tokens are only meaningful while the profile is unlocked; leaving them
// resident would let them spring back to life on the next unlock.
for (const [id, token] of this.tokens) {
@@ -479,6 +506,28 @@ export class AgentDaemon {
for (const [fp, held] of this.held) {
if (held.expiresAt <= now) this.forget(fp);
}
// High-risk sessions expire on their own clock too: they are typically
// much shorter than the seed's TTL, and outliving it would silently
// extend the second factor.
for (const [fp, session] of this.highRisk) {
if (session.expiresAt <= now) this.highRisk.delete(fp);
}
}
/**
* The live partition key tag for a profile, or "" when not unlocked.
*
* Never logged and never included in an audit record: it is the key to the
* partition, so recording it would put it on disk by another route.
*/
private highRiskTag(fingerprint: string): string {
const session = this.highRisk.get(fingerprint);
if (!session) return "";
if (session.expiresAt <= Date.now() / 1000) {
this.highRisk.delete(fingerprint);
return "";
}
return session.tag;
}
private async handle(msg: Record<string, unknown>): Promise<Record<string, unknown>> {
@@ -704,6 +753,65 @@ export class AgentDaemon {
}
return { ok: true, expires_at: expiresAt };
}
case "high-risk-unlock": {
// The factor is verified by the CALLER (which reads the envelope and
// unwraps it); the agent receives the resulting tag. That keeps the
// KDF work out of the daemon and means a wrong factor never reaches
// it — but it also means this op hands over partition access, which
// is why it is owner-gated.
const fingerprint = String(msg["fingerprint"] ?? "");
const tag = String(msg["tag"] ?? "");
if (!FINGERPRINT_RE.test(fingerprint)) {
return { ok: false, error: "fingerprint must be 16 uppercase hex characters" };
}
if (!/^[0-9a-f]{64}$/.test(tag)) {
return { ok: false, error: "tag must be a 64-character hex digest" };
}
// A high-risk grant on a locked profile would outlive nothing and
// protect nothing: the vault index it applies to is not open.
if (!this.held.has(fingerprint)) {
return { ok: false, error: "profile not unlocked" };
}
const ttl = positiveIntField(msg["ttl"], 300);
if (ttl === null) return { ok: false, error: "ttl must be a positive integer" };
const expiresAt = Math.floor(Date.now() / 1000 + ttl);
this.highRisk.set(fingerprint, { tag, expiresAt });
try {
// Records THAT it was unlocked and for how long — never the tag.
await this.auditLog(fingerprint, "high_risk_unlocked", { ttl });
} catch (e) {
this.highRisk.delete(fingerprint);
throw e;
}
return { ok: true, expires_at: expiresAt };
}
case "high-risk-lock": {
const fingerprint = String(msg["fingerprint"] ?? "");
const had = this.highRisk.delete(fingerprint);
if (had) await this.auditLog(fingerprint, "high_risk_locked", {});
return { ok: true, locked: had };
}
case "high-risk-status": {
const fingerprint = String(msg["fingerprint"] ?? "");
const session = this.highRisk.get(fingerprint);
const live = this.highRiskTag(fingerprint) !== "";
return {
ok: true,
fingerprint,
unlocked: live,
// The expiry is safe to disclose; the tag is not, and is not here.
expires_at: live && session ? session.expiresAt : null,
};
}
case "high-risk-tag": {
// Owner-gated, and the only way the tag leaves the daemon. Returned
// to the owner's own CLI so it can open the partition; a scoped token
// cannot reach this op at all.
const fingerprint = String(msg["fingerprint"] ?? "");
const tag = this.highRiskTag(fingerprint);
if (!tag) return { ok: false, error: "high-risk partition is locked" };
return { ok: true, tag };
}
case "owner-mnemonic": {
// Owner-capability gated: this hands back the parent seed so the
// owner's CLI can operate the vault locally. It is deliberately NOT
@@ -869,6 +977,50 @@ export class AgentClient {
}
}
/**
* Hand a verified partition key tag to the agent for a bounded window.
*
* The tag is key material. It goes over the 0600 unix socket to a process
* that already holds this profile's parent seed, and is never written to
* disk by either side.
*/
async highRiskUnlock(
fingerprint: string,
tag: string,
ttl: number,
): Promise<number> {
const r = await this.ownerRequest({ op: "high-risk-unlock", fingerprint, tag, ttl });
if (!r["ok"]) throw new Error(String(r["error"]));
return Number(r["expires_at"] ?? 0);
}
async highRiskLock(fingerprint: string): Promise<boolean> {
const r = await this.ownerRequest({ op: "high-risk-lock", fingerprint });
if (!r["ok"]) throw new Error(String(r["error"]));
return Boolean(r["locked"]);
}
async highRiskStatus(
fingerprint: string,
): Promise<{ unlocked: boolean; expires_at: number | null }> {
const r = await this.ownerRequest({ op: "high-risk-status", fingerprint });
if (!r["ok"]) throw new Error(String(r["error"]));
return {
unlocked: Boolean(r["unlocked"]),
expires_at: r["expires_at"] === null ? null : Number(r["expires_at"]),
};
}
/** The live tag, or null when the partition is locked. */
async highRiskTag(fingerprint: string): Promise<string | null> {
try {
const r = await this.ownerRequest({ op: "high-risk-tag", fingerprint });
return r["ok"] ? String(r["tag"]) : null;
} catch {
return null;
}
}
async lock(fingerprint?: string): Promise<number> {
const r = await this.ownerRequest({ op: "lock", ...(fingerprint && { fingerprint }) });
if (!r["ok"]) throw new Error(String(r["error"]));
+110 -3
View File
@@ -38,6 +38,7 @@ import {
passwordPolicyFromRecord,
removeLink,
restoreEntry,
isPartitionStub,
buildSemanticRecords,
searchSemanticRecords,
semanticManifest,
@@ -56,6 +57,7 @@ import { openVault, saveVault, saveVaultHoldingLock, withVaultLock, atomicWrite
import { entryMetadata, refFor, resolveEntry } from "../refs.js";
import { materializeSecret } from "../secrets.js";
import { createIndexBackup } from "../backups.js";
import { factorConfigured, tagForFactor, readPartition, partitionPath } from "../highRisk.js";
import { HttpError, type ApiRequest, type ApiResponse, type ApiServer } from "./server.js";
/**
@@ -67,7 +69,6 @@ import { HttpError, type ApiRequest, type ApiResponse, type ApiServer } from "./
* an integrator hunting for a spelling mistake that is not there.
*/
export const UNPORTED_PREFIXES: Array<{ prefix: string; feature: string }> = [
{ prefix: "/api/v1/high-risk", feature: "high-risk partitions" },
{ prefix: "/api/v1/agent/job-profiles", feature: "agent job profiles" },
{ prefix: "/api/v1/agent/recovery", feature: "agent recovery split" },
];
@@ -91,9 +92,52 @@ export interface ApiContext {
notifications: Array<{ level: string; message: string }>;
/** Requests the process to exit; wired by the CLI command. */
requestShutdown: () => void;
/**
* Live high-risk partition key tag, or null when locked.
*
* In memory only — this value is the partition's encryption key, so writing
* it anywhere would let a reader of that file open the partition without
* the second factor.
*/
highRiskTag: string | null;
/** Unix seconds at which the high-risk unlock lapses. */
highRiskExpiresAt: number;
now: () => number;
}
/**
* Replace a high-risk stub with its real record, or refuse.
*
* A stub carries only kind/label/archived, so deriving from one produces the
* wrong secret rather than an error — which is why this refuses loudly
* instead of falling through.
*/
async function hydratePartitionedFor(
ctx: ApiContext,
id: string,
entry: Record<string, unknown>,
): Promise<Record<string, unknown>> {
if (!isPartitionStub(entry)) return entry;
const live = ctx.highRiskTag !== null && ctx.highRiskExpiresAt > ctx.now() / 1000;
if (!live) {
ctx.highRiskTag = null;
throw new HttpError(
423,
`entry ${id} is in the high-risk partition, which is locked. ` +
`POST /api/v1/high-risk/unlock with the factor first.`,
);
}
const partition = await readPartition(profileDir(ctx), ctx.highRiskTag!);
const full = partition[String(entry["partition_ref"] ?? id)];
if (!full) {
throw new HttpError(
409,
`entry ${id} points at a high-risk record that is not in the partition file`,
);
}
return full;
}
function requireUnlocked(ctx: ApiContext): string {
if (!ctx.mnemonic) throw new HttpError(423, "Vault is locked");
return ctx.mnemonic;
@@ -240,8 +284,9 @@ export function registerRoutes(server: ApiServer, ctx: ApiContext): void {
const mnemonic = requireUnlocked(ctx);
const vault = await readVault(ctx);
const id = entryIdOf(req);
const entry = vault.index.entries[id];
if (!entry) throw new HttpError(404, "Not found");
const stub = vault.index.entries[id];
if (!stub) throw new HttpError(404, "Not found");
const entry = await hydratePartitionedFor(ctx, id, stub as unknown as Record<string, unknown>);
const timestamp = optInt(req.query.get("at") ?? undefined, "at");
const config = await loadConfig(profileDir(ctx), mnemonic);
const secret = materializeSecret(vault.index, id, entry as Entry, mnemonic, {
@@ -817,6 +862,68 @@ export function registerRoutes(server: ApiServer, ctx: ApiContext): void {
};
});
// -------------------------------------------------------------- high risk
/**
* The high-risk unlock lives on the ApiContext, in memory, for exactly the
* reason the CLI keeps it in the agent: the partition key tag IS the
* partition's encryption key, so persisting it would let anything that can
* read the directory open the partition without the second factor.
*/
server.route("GET", "/api/v1/high-risk/status", async () => {
return {
json: {
fingerprint: ctx.fingerprint,
configured: factorConfigured(ctx.appDir.root),
unlocked: ctx.highRiskTag !== null && ctx.highRiskExpiresAt > ctx.now() / 1000,
expires_at: ctx.highRiskTag !== null ? ctx.highRiskExpiresAt : null,
partition_exists: existsSync(partitionPath(profileDir(ctx))),
},
};
});
server.route(
"POST",
"/api/v1/high-risk/unlock",
async (req) => {
// Password-gated on top of the bearer token, like every other route
// that reaches secrets — and then the FACTOR on top of that. The whole
// point of the partition is that the master password alone is not
// enough for these kinds.
await requirePassword(ctx, req);
const factor = req.headers["x-seedpass-high-risk-factor"];
if (!factor) {
throw new HttpError(
401,
"the high-risk factor is required in the X-SeedPass-High-Risk-Factor header",
);
}
if (!factorConfigured(ctx.appDir.root)) {
throw new HttpError(409, "high_risk_factor_not_configured");
}
const ttl = optInt(bodyObject(req)["ttl"], "ttl") ?? 300;
let tag: string;
try {
tag = await tagForFactor(ctx.appDir.root, factor);
} catch {
// One reason for every factor failure: a caller must not be able to
// tell "wrong factor" from "corrupt envelope" by probing.
throw new HttpError(401, "high_risk_factor_invalid");
}
ctx.highRiskTag = tag;
ctx.highRiskExpiresAt = Math.floor(ctx.now() / 1000 + ttl);
return { json: { status: "unlocked", expires_at: ctx.highRiskExpiresAt } };
},
{ requiresPassword: true },
);
server.route("POST", "/api/v1/high-risk/lock", async () => {
const was = ctx.highRiskTag !== null;
ctx.highRiskTag = null;
ctx.highRiskExpiresAt = 0;
return { json: { status: "ok", locked: was } };
});
// --------------------------------------------------------------- semantic
const semanticDir = (): string => join(profileDir(ctx), "semantic_index");
+7 -3
View File
@@ -42,6 +42,9 @@ export function buildContext(options: {
fingerprint: options.fingerprint,
mnemonic: options.mnemonic,
notifications: [],
// Locked until the factor is supplied; never restored from disk.
highRiskTag: null,
highRiskExpiresAt: 0,
now: options.now ?? (() => Date.now()),
requestShutdown: options.requestShutdown ?? (() => {}),
verifyPassword: async (password: string) => {
@@ -90,10 +93,11 @@ export async function serveApi(options: ServeApiOptions): Promise<void> {
const bound = await server.listen();
const stop = async (): Promise<void> => {
// Drop the seed before releasing the port, not after: the window between
// the two is a window where the process is still holding an unlocked seed
// with no way to say so.
// Both the seed and the high-risk tag go before the port closes, not
// after: the gap between them would be a window where the process still
// holds key material with no way to say so.
ctx.mnemonic = null;
ctx.highRiskTag = null;
await server.close();
};
+218
View File
@@ -0,0 +1,218 @@
/**
* Approval gates — parity with src/seedpass/core/agent_approval.py.
*
* An approval is a one-shot (or N-shot) authorization for a named dangerous
* action, issued out of band and consumed at the moment the action runs. It
* is the "someone deliberately said yes to this" record that sits between a
* policy saying an action NEEDS approval and the action happening.
*
* Approvals are stored at the app level rather than per profile, matching
* Python, and hold no secret material: an approval id is a capability to
* perform an action that the caller must ALSO be otherwise authorized for.
* It is not a credential on its own, which is why the store is readable
* without unlocking anything.
*/
import { randomBytes } from "node:crypto";
import { readFile } from "node:fs/promises";
import { existsSync } from "node:fs";
import { join } from "node:path";
import { atomicWrite, withVaultLock } from "./vaultFile.js";
import { utf8 } from "@seedpass/core";
export const APPROVAL_STORE_VERSION = 1;
export const APPROVAL_STORE_FILENAME = "agent_approvals.json";
/** Actions an approval may cover. Anything else is refused at issue time. */
export const VALID_APPROVAL_ACTIONS = [
"export",
"reveal_parent_seed",
"private_key_retrieval",
] as const;
export type ApprovalAction = (typeof VALID_APPROVAL_ACTIONS)[number];
export interface ApprovalRecord {
id: string;
action: string;
resource: string;
issued_by: string;
created_at_utc: string;
expires_at_utc: string;
uses_remaining: number;
revoked_at_utc: string | null;
}
interface ApprovalStore {
version: number;
approvals: ApprovalRecord[];
}
function emptyStore(): ApprovalStore {
return { version: APPROVAL_STORE_VERSION, approvals: [] };
}
export function approvalStorePath(appRoot: string): string {
return join(appRoot, APPROVAL_STORE_FILENAME);
}
async function loadStore(path: string): Promise<ApprovalStore> {
if (!existsSync(path)) return emptyStore();
try {
const data = JSON.parse(await readFile(path, "utf8"));
if (typeof data !== "object" || data === null || !Array.isArray(data.approvals)) {
return emptyStore();
}
return data as ApprovalStore;
} catch {
// A corrupt store reads as empty, which fails CLOSED: every approval
// check then denies rather than accidentally allowing.
return emptyStore();
}
}
async function saveStore(path: string, store: ApprovalStore): Promise<void> {
await atomicWrite(path, utf8(JSON.stringify(store, null, 2)));
}
/** Read-modify-write under a lock, so two agents cannot both spend one use. */
async function mutateStore<T>(
path: string,
fn: (store: ApprovalStore) => T | Promise<T>,
): Promise<T> {
return withVaultLock(path, async () => {
const store = await loadStore(path);
const result = await fn(store);
await saveStore(path, store);
return result;
});
}
export function isValidApprovalAction(action: string): action is ApprovalAction {
return (VALID_APPROVAL_ACTIONS as readonly string[]).includes(action);
}
export async function issueApproval(
appRoot: string,
options: {
action: string;
ttlSeconds: number;
uses: number;
resource?: string;
issuedBy?: string;
now?: number;
},
): Promise<ApprovalRecord> {
if (!isValidApprovalAction(options.action)) {
throw new Error(
`unknown approval action '${options.action}' ` +
`(expected one of ${VALID_APPROVAL_ACTIONS.join(", ")})`,
);
}
if (!Number.isInteger(options.ttlSeconds) || options.ttlSeconds < 1) {
throw new Error("ttl must be a positive integer number of seconds");
}
if (!Number.isInteger(options.uses) || options.uses < 1) {
throw new Error("uses must be a positive integer");
}
const now = options.now ?? Date.now();
const record: ApprovalRecord = {
// 18 random bytes, like Python's token_urlsafe(18). The id is the whole
// reference to this approval, so it must not be guessable.
id: randomBytes(18).toString("base64url"),
action: options.action,
resource: options.resource ?? "*",
issued_by: options.issuedBy ?? "manual",
created_at_utc: new Date(now).toISOString(),
expires_at_utc: new Date(now + options.ttlSeconds * 1000).toISOString(),
uses_remaining: options.uses,
revoked_at_utc: null,
};
await mutateStore(approvalStorePath(appRoot), (store) => {
store.approvals.push(record);
});
return record;
}
export async function listApprovals(
appRoot: string,
options: { includeRevoked?: boolean } = {},
): Promise<ApprovalRecord[]> {
const approvals = (await loadStore(approvalStorePath(appRoot))).approvals;
if (options.includeRevoked) return approvals;
return approvals.filter((a) => !a.revoked_at_utc);
}
export async function revokeApproval(
appRoot: string,
approvalId: string,
options: { now?: number } = {},
): Promise<boolean> {
const stamp = new Date(options.now ?? Date.now()).toISOString();
return mutateStore(approvalStorePath(appRoot), (store) => {
for (const record of store.approvals) {
if (record.id === approvalId && !record.revoked_at_utc) {
record.revoked_at_utc = stamp;
return true;
}
}
return false;
});
}
/** Does this policy require an approval for `action`? */
export function approvalRequired(policy: Record<string, unknown>, action: string): boolean {
const approvals = policy["approvals"];
if (typeof approvals !== "object" || approvals === null) return false;
const required = (approvals as Record<string, unknown>)["require_for"];
if (!Array.isArray(required)) return false;
const wanted = action.trim().toLowerCase();
return required.some((v) => String(v).trim().toLowerCase() === wanted);
}
export interface ConsumeResult {
ok: boolean;
/** Machine-readable outcome, matching Python's strings exactly. */
reason: string;
}
/**
* Spend one use of an approval.
*
* Every failure mode gets its own reason, and the whole check runs under the
* store lock so two callers cannot both spend the last use. The use is
* decremented and persisted BEFORE the caller acts on the result — an
* approval that was consumed but whose action then failed is the safe
* direction to err.
*/
export async function consumeApproval(
appRoot: string,
options: { approvalId: string; action: string; resource?: string; now?: number },
): Promise<ConsumeResult> {
const now = options.now ?? Date.now();
const resource = options.resource ?? "*";
return mutateStore(approvalStorePath(appRoot), (store) => {
for (const record of store.approvals) {
if (record.id !== options.approvalId) continue;
if (record.revoked_at_utc) return { ok: false, reason: "approval_revoked" };
if (String(record.action).toLowerCase() !== options.action.toLowerCase()) {
return { ok: false, reason: "approval_action_mismatch" };
}
const recordResource = String(record.resource ?? "*");
if (recordResource !== "*" && recordResource !== resource) {
return { ok: false, reason: "approval_resource_mismatch" };
}
const expires = record.expires_at_utc;
if (!expires || Date.parse(expires) <= now) {
return { ok: false, reason: "approval_expired" };
}
const uses = Number(record.uses_remaining ?? 0);
if (!Number.isFinite(uses) || uses <= 0) {
return { ok: false, reason: "approval_exhausted" };
}
record.uses_remaining = uses - 1;
return { ok: true, reason: "approval_consumed" };
}
return { ok: false, reason: "approval_not_found" };
});
}
+29 -4
View File
@@ -88,6 +88,32 @@ export function capabilities(): Record<string, unknown> {
locked_status: 423,
unported_status: 501,
},
high_risk: {
commands: [
"agent high-risk factor-set/status/unlock/lock/migrate",
"POST /api/v1/high-risk/unlock|lock",
"GET /api/v1/high-risk/status",
],
kinds: ["ssh", "pgp", "seed", "nostr", "managed_account"],
// The partition file and key envelope are byte-compatible with Python,
// so a partition made by either implementation opens in the other.
interop: "file formats shared with the Python implementation",
// Where this port DIVERGES, and why. Python records the unlock in
// agent_high_risk_unlock.json including the partition key tag, from
// which the partition's encryption key is derived — so during any
// Python session the partition is readable from disk with no factor.
// Here the tag lives only in the agent's memory (or the API process's).
session_storage: "in-memory only; the partition key tag never reaches disk",
factor_env: "SEEDPASS_HIGH_RISK_FACTOR",
api_factor_header: "X-SeedPass-High-Risk-Factor",
},
approvals: {
commands: ["agent approval issue/list/revoke"],
actions: ["export", "reveal_parent_seed", "private_key_retrieval"],
// An approval is not a credential: it authorizes an action for a caller
// that must ALSO be otherwise authorized.
semantics: "one-shot (or N-use) authorization, consumed at action time",
},
audit: {
commands: ["agent audit-verify", "agent audit-tail"],
chain: "HMAC-SHA256(prev_sig + canonical_payload), keyed by KEY_INDEX",
@@ -105,10 +131,9 @@ export function capabilities(): Record<string, unknown> {
// Python-derived state, recomputed on load. Carried through verbatim by
// the TS port so a Python profile round-trips, but not computed here.
"index0/atlas (preserved verbatim on read/write, never recomputed)",
// Deliberate: agent approval gates, high-risk partitions, job profiles
// and recovery split. The session agent's scoped tokens cover the
// automation cases; these add a second authorization model.
"agent approval gates, high-risk partitions, job profiles, recovery split",
// Deliberate: agent job profiles and recovery split. The session
// agent's scoped tokens cover the automation cases these serve.
"agent job profiles and recovery split",
// Deliberate: the TS interactive mode follows Python's legacy v1 menu
// tree. See docs/tui_v2_cutover_decision.md.
"Python's v2/v3 Textual TUIs (interactive mode follows the legacy v1 menus)",
+122
View File
@@ -0,0 +1,122 @@
/**
* High-risk partition: factor configuration and profile-level access.
*
* The on-disk formats (partition file, key envelope) live in core and are
* byte-compatible with Python, so a partition created by either
* implementation opens in the other. What lives here is the local plumbing:
* where the envelope sits, and how an unlock session is held.
*
* ONE DELIBERATE DIVERGENCE, and it is the whole reason this module exists
* rather than a straight port. Python records an unlock session in
* `agent_high_risk_unlock.json`, and that record contains the
* `partition_key_tag` — from which the partition file's encryption key is
* derived. So for the life of any Python unlock session, the high-risk
* partition is decryptable from disk alone, with no factor, by anything that
* can read the app directory. That voids the guarantee the partition exists
* to provide: these are precisely the secrets deemed to need a SECOND factor.
*
* The TypeScript port holds the unlocked tag in the session agent's memory
* instead, next to the parent seeds it already holds, with the same TTL
* discipline. Nothing derived from the factor is ever written to disk. This
* changes no file format and no interop — only where the live session lives.
*/
import { readFile } from "node:fs/promises";
import { existsSync } from "node:fs";
import { join } from "node:path";
import {
buildPartitionEnvelope,
decryptPartition,
encryptPartition,
generatePartitionKey,
partitionKeyTag,
unwrapPartitionKey,
HighRiskError,
PARTITION_FILENAME,
utf8,
} from "@seedpass/core";
import { atomicWrite } from "./vaultFile.js";
export const ENVELOPE_FILENAME = "agent_high_risk_partition.key.enc.json";
export function envelopePath(appRoot: string): string {
return join(appRoot, ENVELOPE_FILENAME);
}
export function partitionPath(profileDir: string): string {
return join(profileDir, PARTITION_FILENAME);
}
/** Has a high-risk factor been configured for this installation? */
export function factorConfigured(appRoot: string): boolean {
return existsSync(envelopePath(appRoot));
}
/**
* Set (or replace) the high-risk factor.
*
* Replacing the factor generates a NEW partition key, which makes any
* existing partition file undecryptable — so callers must re-encrypt an
* existing partition under the new key, or refuse. `setFactor` deliberately
* does not do that silently: losing a partition is losing secrets.
*/
export async function setFactor(appRoot: string, factor: string): Promise<string> {
if (!factor) throw new Error("the high-risk factor cannot be empty");
const partitionKey = generatePartitionKey();
const envelope = await buildPartitionEnvelope(partitionKey, factor);
await atomicWrite(envelopePath(appRoot), utf8(JSON.stringify(envelope, null, 2)));
return partitionKeyTag(partitionKey);
}
async function readEnvelope(appRoot: string): Promise<Record<string, unknown>> {
const path = envelopePath(appRoot);
if (!existsSync(path)) {
throw new HighRiskError("high_risk_partition_not_configured");
}
try {
return JSON.parse(await readFile(path, "utf8")) as Record<string, unknown>;
} catch {
throw new HighRiskError("invalid_partition_envelope");
}
}
/**
* Turn the factor into the partition key tag.
*
* The returned value is key material, not an identifier — see
* `partitionKeyTag` in core. Hold it in memory and drop it; never persist it.
*/
export async function tagForFactor(appRoot: string, factor: string): Promise<string> {
return partitionKeyTag(await unwrapPartitionKey(await readEnvelope(appRoot), factor));
}
/** Is this the configured factor? Answers without disclosing the tag. */
export async function verifyFactor(appRoot: string, factor: string): Promise<boolean> {
try {
await tagForFactor(appRoot, factor);
return true;
} catch {
return false;
}
}
/** Read a profile's partition, or `{}` when it has none. */
export async function readPartition(
profileDir: string,
tag: string,
): Promise<Record<string, Record<string, unknown>>> {
const path = partitionPath(profileDir);
if (!existsSync(path)) return {};
return decryptPartition(new Uint8Array(await readFile(path)), tag);
}
/** Write a profile's partition at 0600. */
export async function writePartition(
profileDir: string,
tag: string,
entries: Record<string, Record<string, unknown>>,
): Promise<string> {
const path = partitionPath(profileDir);
await atomicWrite(path, await encryptPartition(entries, tag));
return path;
}
+18
View File
@@ -10,3 +10,21 @@ export { AgentDaemon, AgentClient, agentSocketPath } from "./agent.js";
export { ApiServer, HttpError, resolveBind } from "./api/server.js";
export { registerRoutes, UNPORTED_PREFIXES, type ApiContext } from "./api/routes.js";
export { buildContext, serveApi } from "./api/serve.js";
export {
setFactor,
tagForFactor,
verifyFactor,
factorConfigured,
readPartition,
writePartition,
partitionPath,
} from "./highRisk.js";
export {
issueApproval,
listApprovals,
revokeApproval,
consumeApproval,
approvalRequired,
VALID_APPROVAL_ACTIONS,
type ApprovalRecord,
} from "./approvals.js";
+254 -2
View File
@@ -26,6 +26,10 @@ import {
parseBackupWrapper,
exportBackup,
findDerivationCollisions,
HIGH_RISK_KINDS,
isPartitionStub,
partitionStub,
type Entry,
buildSemanticRecords,
searchSemanticRecords,
semanticManifest,
@@ -170,6 +174,20 @@ import {
import { AgentClient, AgentDaemon, agentSocketPath, DEFAULT_TTL_SECONDS } from "./agent.js";
import { AuditLog } from "./audit.js";
import { createIndexBackup } from "./backups.js";
import {
factorConfigured,
setFactor,
tagForFactor,
readPartition,
writePartition,
partitionPath,
} from "./highRisk.js";
import {
issueApproval,
listApprovals,
revokeApproval,
VALID_APPROVAL_ACTIONS,
} from "./approvals.js";
import { runTui } from "./tui/app.js";
export interface ProgramIo {
@@ -404,9 +422,44 @@ async function openReadAccess(opts: GlobalOpts): Promise<ReadAccess> {
// Resolved on first use, not up front: reading the config costs another
// BIP-39 seed derivation, and `entry list` and friends never need a policy.
let basePolicy: PasswordPolicy | undefined;
/**
* Replace a high-risk stub with its real record.
*
* A stub carries only kind/label/archived, so materializing a secret from
* one would derive from the wrong fields — or, for an imported secret,
* from nothing at all. The full record lives in the partition, and reaching
* it needs the second factor to be live in the agent.
*/
const hydrate = async (id: string, entry: Entry): Promise<Entry> => {
const record = entry as unknown as Record<string, unknown>;
if (!isPartitionStub(record)) return entry;
const client = new AgentClient(agentSocketPath(app.root));
const fp = await currentFingerprint(app, opts);
const tag = await client.highRiskTag(fp);
if (!tag) {
throw new Error(
`entry ${id} is in the high-risk partition and the partition is ` +
`locked. Run 'agent high-risk unlock' with SEEDPASS_HIGH_RISK_FACTOR set.`,
);
}
const partition = await readPartition(app.profileDir(fp), tag);
const full = partition[String(record["partition_ref"] ?? id)];
if (!full) {
// The stub says a record exists and the partition disagrees. Say so
// rather than deriving from the stub and handing back a wrong secret.
throw new Error(
`entry ${id} points at a high-risk record that is not in the ` +
`partition file; the partition may be from a different factor.`,
);
}
return full as unknown as Entry;
};
const localSecret = async (id: string, timestamp?: number) => {
const entry = vault.index.entries[id];
if (!entry) throw new Error(`no entry ${id}`);
const stub = vault.index.entries[id];
if (!stub) throw new Error(`no entry ${id}`);
const entry = await hydrate(id, stub);
basePolicy ??= await basePolicyForOptions(opts, vault.mnemonic);
return materializeSecret(vault.index, id, entry, vault.mnemonic, {
...(timestamp !== undefined && { timestamp }),
@@ -1813,6 +1866,205 @@ export function buildProgram(io: ProgramIo = defaultIo): Command {
);
});
// ------------------------------------------------- high-risk partition
/**
* The factor never comes from argv — it is the second factor for exactly
* the secrets deemed to need one, and argv is in the process list and the
* shell history.
*/
function requireFactor(): string {
const factor = process.env["SEEDPASS_HIGH_RISK_FACTOR"];
if (!factor) {
throw new Error(
"set SEEDPASS_HIGH_RISK_FACTOR in the environment (never pass the " +
"high-risk factor on the command line)",
);
}
return factor;
}
const highRisk = agent
.command("high-risk")
.description("second-factor partition for ssh/pgp/seed/nostr entries");
highRisk
.command("factor-set")
.description("configure the high-risk factor (reads SEEDPASS_HIGH_RISK_FACTOR)")
.action(async () => {
const opts = program.opts() as GlobalOpts;
const app = new AppDir(resolveAppDir(opts.appDir));
if (factorConfigured(app.root)) {
// Replacing the factor mints a NEW partition key, which would leave
// any existing partition file undecryptable. Losing a partition is
// losing secrets, so this refuses rather than doing it quietly.
throw new Error(
"a high-risk factor is already configured. Replacing it generates a " +
"new partition key and would make any existing partition " +
"permanently unreadable; migrate the entries back out first.",
);
}
await setFactor(app.root, requireFactor());
io.out(JSON.stringify({ status: "ok", configured: true }));
});
highRisk
.command("status")
.description("whether the factor is configured and the partition unlocked")
.action(async () => {
const opts = program.opts() as GlobalOpts;
const app = new AppDir(resolveAppDir(opts.appDir));
const fp = await currentFingerprint(app, opts);
const client = new AgentClient(agentSocketPath(app.root));
let session = { unlocked: false, expires_at: null as number | null };
try {
session = await client.highRiskStatus(fp);
} catch {
// No agent running means nothing is unlocked, which is the honest
// answer rather than an error.
}
io.out(
JSON.stringify({
fingerprint: fp,
configured: factorConfigured(app.root),
unlocked: session.unlocked,
expires_at: session.expires_at,
partition_exists: existsSync(partitionPath(app.profileDir(fp))),
}),
);
});
highRisk
.command("unlock")
.description("unlock the partition for a bounded window (reads SEEDPASS_HIGH_RISK_FACTOR)")
.option("--ttl <seconds>", "unlock lifetime", "300")
.action(async (o: { ttl: string }) => {
const opts = program.opts() as GlobalOpts;
const app = new AppDir(resolveAppDir(opts.appDir));
const fp = await currentFingerprint(app, opts);
// Unwrapping happens HERE, not in the daemon: a wrong factor never
// reaches the process holding seeds, and the KDF cost stays out of it.
const tag = await tagForFactor(app.root, requireFactor());
const client = new AgentClient(agentSocketPath(app.root));
const expiresAt = await client.highRiskUnlock(
fp,
tag,
parseIntOption(o.ttl, "--ttl", { min: 1 }),
);
io.out(JSON.stringify({ status: "unlocked", fingerprint: fp, expires_at: expiresAt }));
});
highRisk
.command("lock")
.description("drop the high-risk unlock immediately")
.action(async () => {
const opts = program.opts() as GlobalOpts;
const app = new AppDir(resolveAppDir(opts.appDir));
const fp = await currentFingerprint(app, opts);
const client = new AgentClient(agentSocketPath(app.root));
io.out(JSON.stringify({ status: "ok", locked: await client.highRiskLock(fp) }));
});
highRisk
.command("migrate")
.description("move high-risk entries out of the vault index into the partition")
.option(
"--kind <kind...>",
`entry kinds to move (default: ${HIGH_RISK_KINDS.join(", ")})`,
)
.action(async (o: { kind?: string[] }) => {
const opts = program.opts() as GlobalOpts;
const app = new AppDir(resolveAppDir(opts.appDir));
const fp = await currentFingerprint(app, opts);
const tag = await tagForFactor(app.root, requireFactor());
const kinds = new Set(o.kind ?? [...HIGH_RISK_KINDS]);
const profileDir = app.profileDir(fp);
const moved: string[] = [];
await mutateVault(opts, async (vault) => {
const partition = await readPartition(profileDir, tag);
for (const [id, raw] of Object.entries(vault.index.entries)) {
const entry = raw as unknown as Record<string, unknown>;
if (isPartitionStub(entry)) continue; // already moved
const kind = String(entry["kind"] ?? entry["type"] ?? "").toLowerCase();
if (!kinds.has(kind)) continue;
partition[id] = entry;
(vault.index.entries as unknown as Record<string, unknown>)[id] =
partitionStub(id, entry, kind, Date.now() / 1000);
moved.push(id);
}
// Write the partition BEFORE the index. If the order were reversed a
// crash between them would leave stubs pointing at entries that were
// never stored — the vault would have lost the secrets outright.
if (moved.length > 0) await writePartition(profileDir, tag, partition);
});
io.out(
JSON.stringify({
moved_count: moved.length,
moved_indexes: moved.sort((a, b) => Number(a) - Number(b)),
partition_file: partitionPath(profileDir),
}),
);
});
// ------------------------------------------------------- approval gates
const approval = agent
.command("approval")
.description("one-shot authorizations for dangerous actions");
approval
.command("issue")
.description("issue an approval for a named action")
.requiredOption("--action <action>", VALID_APPROVAL_ACTIONS.join("|"))
.option("--resource <resource>", "restrict to one resource", "*")
.option("--ttl <seconds>", "lifetime", "300")
.option("--uses <n>", "how many times it may be consumed", "1")
.option("--issued-by <who>", "who authorized it, for the record", "manual")
.action(async (o: {
action: string; resource: string; ttl: string; uses: string; issuedBy: string;
}) => {
const opts = program.opts() as GlobalOpts;
const app = new AppDir(resolveAppDir(opts.appDir));
const record = await issueApproval(app.root, {
action: o.action,
resource: o.resource,
issuedBy: o.issuedBy,
ttlSeconds: parseIntOption(o.ttl, "--ttl", { min: 1 }),
uses: parseIntOption(o.uses, "--uses", { min: 1 }),
});
io.out(JSON.stringify(record, null, 2));
});
approval
.command("list")
.description("list approvals")
.option("--include-revoked", "also show revoked ones")
.action(async (o: { includeRevoked?: boolean }) => {
const opts = program.opts() as GlobalOpts;
const app = new AppDir(resolveAppDir(opts.appDir));
io.out(
JSON.stringify(
await listApprovals(app.root, {
...(o.includeRevoked !== undefined && { includeRevoked: o.includeRevoked }),
}),
null,
2,
),
);
});
approval
.command("revoke <approvalId>")
.description("revoke an approval immediately")
.action(async (approvalId: string) => {
const opts = program.opts() as GlobalOpts;
const app = new AppDir(resolveAppDir(opts.appDir));
const revoked = await revokeApproval(app.root, approvalId);
if (!revoked) throw new Error(`no active approval ${approvalId}`);
io.out(JSON.stringify({ status: "ok", revoked: approvalId }));
});
const util = program.command("util").description("utility commands");
util