Skip to content

Business operating system for Claude Code — 57 skills, 21 agents, smart daemon. Unified inbox (WhatsApp/Email/Slack/Telegram), autonomous PR merge, full-AWS monitoring, revenue (Stripe+RevenueCat), e-commerce (Shopify), marketing (Klaviyo/Meta/GA4), voice (Bland/ElevenLabs), APM (Datadog/NewRelic/OTEL), YOLO mode.

fix(security): harden staged enrollment recovery (#786)

Aurora Capital663a2a68f634
diff --git a/claude-ops/scripts/account-rotation/README.md b/claude-ops/scripts/account-rotation/README.md
index e292ef4b..6913f759 100644
--- a/claude-ops/scripts/account-rotation/README.md
+++ b/claude-ops/scripts/account-rotation/README.md
@@ -147,10 +147,37 @@ and save its secret-free JSON output, then run `apply --plan <file>
--expected-digest <digest>`.
Apply refuses a changed plan, manifest, inventory binding, or mismatched
-existing trust/config file and is idempotent for a valid installation. Its
-fsynced apply journal supports fresh-process completion of the same reviewed
-plan; `rollback --plan <file> --expected-digest <digest>` removes only targets
-that were absent when that apply began. Run `preflight --plan <file>
+existing trust/config file. An absent-trust bootstrap plan is strictly one-shot:
+after success, or after any observable journal/progress (including SIGKILL), it
+returns `BOOTSTRAP_TRUST_REVIEW_REQUIRED` or
+`BOOTSTRAP_JOURNAL_REVIEW_REQUIRED`; a retained owner-only bootstrap-attempt
+marker also blocks repeated apply, rollback, and activation with the reviewed
+absence. Inspect the
+retained preparation, detached evidence, and journal records; establish or
+verify the owner-only trust root; then generate and review a **new present-trust
+plan**. That plan pins the trust descriptor/digest and any exact recovery journal
+state/topology and stale provision-lock descriptor and is the only plan permitted
+to finish, validate, or roll back the
+bounded interrupted transaction. `TRUST_SNAPSHOT_CHANGED`,
+`INVALID_PROVISION_JOURNAL`, `INVALID_PROVISION_RECEIPT`, and
+`PROVISION_RECOVERY_UNCERTAIN` require stopping writers, preserving all evidence,
+and generating another reviewed plan only after the descriptor discrepancy has
+been investigated. Never substitute a bootstrap key plus receipt: absent trust
+and receipts do not authenticate one another.
+
+Publication uses fsynced owner-only preparation files and no-replace hard links.
+Canonical names are detached atomically to uniquely named evidence before their
+descriptor is checked; the implementation does not claim conditional
+unlink-by-path and has no privileged broker. Exact digest-derived preparation
+aliases and detached tombstones are retained, are not auto-garbage-collected,
+and increase disk/inode usage. Readers permit only the explicitly bounded link
+topology and reject unrelated hardlinks. Operators must inventory and archive or
+remove evidence only through a separate reviewed maintenance procedure; routine
+provisioning does not authorize evidence garbage collection.
+
+Tests use temporary fixtures and require `CLAUDE_COORDINATION_TESTING=1` or
+`CLAUDE_STAGED_ENROLLMENT_TESTING=1` for fault hooks; they perform no live
+credential, service, config, or provisioning action. Run `preflight --plan <file>
--expected-digest <digest>` before enabling each writer, then roll out consumers
one at a time. Every service/manual invocation must receive both generated
environment variables; an omitted coordination environment fails closed before
diff --git a/claude-ops/scripts/account-rotation/__tests__/coordination-provisioning.test.mjs b/claude-ops/scripts/account-rotation/__tests__/coordination-provisioning.test.mjs
index 723e3fe4..259c2e97 100755
--- a/claude-ops/scripts/account-rotation/__tests__/coordination-provisioning.test.mjs
+++ b/claude-ops/scripts/account-rotation/__tests__/coordination-provisioning.test.mjs
@@ -1,6 +1,17 @@
#!/usr/bin/env node
import assert from 'node:assert/strict';
-import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';
+import {
+ chmodSync,
+ closeSync,
+ existsSync,
+ ftruncateSync,
+ mkdirSync,
+ mkdtempSync,
+ openSync,
+ readFileSync,
+ unlinkSync,
+ writeFileSync,
+} from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { spawnSync } from 'node:child_process';
@@ -9,6 +20,15 @@ const cli = new URL('../provision-coordination.mjs', import.meta.url).pathname;
function run(args, env = {}) {
return spawnSync(process.execPath, [cli, ...args], { encoding: 'utf8', env: { ...process.env, ...env } });
}
+function replaceFixtureContents(path, bytes) {
+ const fd = openSync(path, 'r+');
+ try {
+ ftruncateSync(fd, 0);
+ writeFileSync(fd, bytes);
+ } finally {
+ closeSync(fd);
+ }
+}
function fixture(legacy = false) {
const root = mkdtempSync(join(tmpdir(), 'coordination-provision-'));
chmodSync(root, 0o700);
@@ -134,17 +154,28 @@ assert.notEqual(run(dangerous.args).status, 0, 'dangerous source JSON key refuse
const f = fixture();
const planned = run(f.args);
assert.equal(planned.status, 0, planned.stderr);
-const plan = JSON.parse(planned.stdout);
+let plan = JSON.parse(planned.stdout);
assert.doesNotMatch(
planned.stdout,
/approvalKey|access[_-]?token|refresh[_-]?token/i,
'plan contains no key/token material',
);
-const planPath = join(f.root, 'plan.json');
+let planPath = join(f.root, 'plan.json');
writeFileSync(planPath, planned.stdout, { mode: 0o600 });
let applied = run(['apply', '--plan', planPath, '--expected-digest', plan.digest]);
assert.equal(applied.status, 0, applied.stderr);
-assert.equal(run(['apply', '--plan', planPath, '--expected-digest', plan.digest]).status, 0, 'idempotent rerun');
+assert.match(
+ run(['apply', '--plan', planPath, '--expected-digest', plan.digest]).stderr,
+ /BOOTSTRAP_TRUST_REVIEW_REQUIRED/,
+ 'an absent-trust plan is one-shot',
+);
+const presentPlanResult = run(f.args);
+assert.equal(presentPlanResult.status, 0, presentPlanResult.stderr);
+plan = JSON.parse(presentPlanResult.stdout);
+planPath = join(f.root, 'present-plan.json');
+writeFileSync(planPath, presentPlanResult.stdout, { mode: 0o600 });
+const presentApply = run(['apply', '--plan', planPath, '--expected-digest', plan.digest]);
+assert.equal(presentApply.status, 0, `reviewed present-trust rerun: ${presentApply.stderr}`);
assert.notEqual(run(['apply', '--plan', planPath, '--expected-digest', '0'.repeat(64)]).status, 0, 'digest mismatch');
assert.equal(
run(['preflight', '--plan', planPath, '--expected-digest', plan.digest]).status,
@@ -162,6 +193,36 @@ assert.deepEqual(readFileSync(f.paths['runtime-inventory']), readFileSync(f.inve
const selfStat = readFileSync(`/proc/${process.pid}/stat`, 'utf8');
const selfStart = selfStat.slice(selfStat.lastIndexOf(') ') + 2).split(' ')[19];
+const malformedLiveLock = fixture();
+mkdirSync(join(malformedLiveLock.root, 'locks'), { mode: 0o700 });
+writeFileSync(
+ malformedLiveLock.paths['provision-lock'],
+ `${JSON.stringify({ version: 1, planDigest: 'a'.repeat(64), pid: process.pid, start: '', nonce: 'a'.repeat(32) })}\n`,
+ { mode: 0o600 },
+);
+assert.match(run(malformedLiveLock.args).stderr, /INVALID_PROVISION_LOCK/);
+replaceFixtureContents(
+ malformedLiveLock.paths['provision-lock'],
+ `${JSON.stringify({
+ version: 1,
+ planDigest: 'a'.repeat(64),
+ pid: process.pid,
+ start: Number(selfStart),
+ nonce: 'a'.repeat(32),
+ })}\n`,
+);
+assert.match(run(malformedLiveLock.args).stderr, /INVALID_PROVISION_LOCK/);
+replaceFixtureContents(
+ malformedLiveLock.paths['provision-lock'],
+ `${JSON.stringify({
+ version: 1,
+ planDigest: 'a'.repeat(64),
+ pid: process.pid,
+ start: `0${selfStart}`,
+ nonce: 'a'.repeat(32),
+ })}\n`,
+);
+assert.match(run(malformedLiveLock.args).stderr, /INVALID_PROVISION_LOCK/);
writeFileSync(
f.paths['provision-lock'],
`${JSON.stringify({ version: 1, planDigest: plan.digest, pid: process.pid, start: selfStart, nonce: 'a'.repeat(32) })}\n`,
@@ -169,7 +230,7 @@ writeFileSync(
);
assert.match(
run(['apply', '--plan', planPath, '--expected-digest', plan.digest]).stderr,
- /PROVISION_LOCK_HELD/,
+ /PROVISION_LOCK_REVIEW_REQUIRED/,
'concurrent provisioning writer refused',
);
writeFileSync(
@@ -177,10 +238,16 @@ writeFileSync(
`${JSON.stringify({ version: 1, planDigest: plan.digest, pid: 99999999, start: '1', nonce: 'b'.repeat(32) })}\n`,
{ mode: 0o600 },
);
+const staleLockPlanResult = run(f.args);
+assert.equal(staleLockPlanResult.status, 0, staleLockPlanResult.stderr);
+const staleLockPlan = JSON.parse(staleLockPlanResult.stdout);
+const staleLockPlanPath = join(f.root, 'stale-lock-plan.json');
+writeFileSync(staleLockPlanPath, staleLockPlanResult.stdout, { mode: 0o600 });
+const staleLockRecovery = run(['apply', '--plan', staleLockPlanPath, '--expected-digest', staleLockPlan.digest]);
assert.equal(
- run(['apply', '--plan', planPath, '--expected-digest', plan.digest]).status,
+ staleLockRecovery.status,
0,
- 'authenticated plan-bound stale provisioning lock recovered',
+ `authenticated plan-bound stale provisioning lock recovered: ${staleLockRecovery.stderr}`,
);
// The installer consumes only paths emitted by the authenticated preflight and
@@ -224,30 +291,40 @@ const rplan = JSON.parse(rp.stdout);
const rpath = join(rollback.root, 'plan.json');
writeFileSync(rpath, rp.stdout);
const failed = run(['apply', '--plan', rpath, '--expected-digest', rplan.digest], {
+ CLAUDE_COORDINATION_TESTING: '1',
CLAUDE_COORDINATION_TEST_FAIL_AFTER: '3',
});
assert.notEqual(failed.status, 0);
+assert.match(
+ run(['apply', '--plan', rpath, '--expected-digest', rplan.digest]).stderr,
+ /BOOTSTRAP_ATTEMPT_REVIEW_REQUIRED/,
+ 'any failed bootstrap attempt permanently consumes the reviewed absence',
+);
for (const file of [rollback.paths.trust, rollback.paths.config, rollback.paths['linux-env']])
assert.equal(existsSync(file), false);
assert.equal(existsSync(rollback.paths.manifest), false);
-// SIGKILL leaves an owner-only digest-bound journal. A fresh process can either
-// finish the same reviewed plan or roll back only targets absent at plan start.
+// An interrupted absent-trust bootstrap is one-shot. Recovery requires a newly
+// generated and reviewed present-trust plan that pins both trust and progress.
const crashResume = fixture();
const crashPlanResult = run(crashResume.args);
const crashPlan = JSON.parse(crashPlanResult.stdout);
const crashPlanPath = join(crashResume.root, 'plan.json');
writeFileSync(crashPlanPath, crashPlanResult.stdout, { mode: 0o600 });
const killed = run(['apply', '--plan', crashPlanPath, '--expected-digest', crashPlan.digest], {
+ CLAUDE_COORDINATION_TESTING: '1',
CLAUDE_COORDINATION_TEST_SIGKILL_AFTER: '3',
});
assert.equal(killed.signal, 'SIGKILL');
assert.equal(existsSync(`${crashResume.paths.config}.provision-journal`), true);
-assert.equal(
- run(['apply', '--plan', crashPlanPath, '--expected-digest', crashPlan.digest]).status,
- 0,
- 'fresh-process resume',
-);
+assert.match(run(['apply', '--plan', crashPlanPath, '--expected-digest', crashPlan.digest]).stderr, /BOOTSTRAP_/);
+const crashRecoveryResult = run(crashResume.args);
+assert.equal(crashRecoveryResult.status, 0, crashRecoveryResult.stderr);
+const crashRecoveryPlan = JSON.parse(crashRecoveryResult.stdout);
+const crashRecoveryPath = join(crashResume.root, 'present-recovery-plan.json');
+writeFileSync(crashRecoveryPath, crashRecoveryResult.stdout, { mode: 0o600 });
+const crashRecoveryApply = run(['apply', '--plan', crashRecoveryPath, '--expected-digest', crashRecoveryPlan.digest]);
+assert.equal(crashRecoveryApply.status, 0, `new reviewed present-trust plan resumes: ${crashRecoveryApply.stderr}`);
assert.equal(existsSync(`${crashResume.paths.config}.provision-journal`), false);
const crashRollback = fixture();
@@ -257,14 +334,24 @@ const rollbackPlanPath = join(crashRollback.root, 'plan.json');
writeFileSync(rollbackPlanPath, rollbackPlanResult.stdout, { mode: 0o600 });
assert.equal(
run(['apply', '--plan', rollbackPlanPath, '--expected-digest', rollbackPlan.digest], {
+ CLAUDE_COORDINATION_TESTING: '1',
CLAUDE_COORDINATION_TEST_SIGKILL_AFTER: '2',
}).signal,
'SIGKILL',
);
+assert.match(
+ run(['rollback', '--plan', rollbackPlanPath, '--expected-digest', rollbackPlan.digest]).stderr,
+ /BOOTSTRAP_/,
+);
+const rollbackRecoveryResult = run(crashRollback.args);
+assert.equal(rollbackRecoveryResult.status, 0, rollbackRecoveryResult.stderr);
+const rollbackRecoveryPlan = JSON.parse(rollbackRecoveryResult.stdout);
+const rollbackRecoveryPath = join(crashRollback.root, 'present-rollback-plan.json');
+writeFileSync(rollbackRecoveryPath, rollbackRecoveryResult.stdout, { mode: 0o600 });
assert.equal(
- run(['rollback', '--plan', rollbackPlanPath, '--expected-digest', rollbackPlan.digest]).status,
+ run(['rollback', '--plan', rollbackRecoveryPath, '--expected-digest', rollbackRecoveryPlan.digest]).status,
0,
- 'fresh-process rollback',
+ 'new reviewed present-trust plan rolls back exact pinned progress',
);
for (const file of [
crashRollback.paths.manifest,
@@ -344,7 +431,11 @@ const refusedRollback = run([
rollbackForeignPlan.digest,
]);
assert.notEqual(refusedRollback.status, 0);
-assert.match(refusedRollback.stderr, /PROVISION_RECOVERY_UNCERTAIN/);
+assert.match(refusedRollback.stderr, /BOOTSTRAP_(ATTEMPT|JOURNAL)_REVIEW_REQUIRED/);
+writeFileSync(rollbackForeign.paths.trust, Buffer.alloc(32, 9), { flag: 'wx', mode: 0o600 });
+const foreignRecoveryResult = run(rollbackForeign.args);
+assert.notEqual(foreignRecoveryResult.status, 0);
+assert.match(foreignRecoveryResult.stderr, /PROVISION_RECOVERY_UNCERTAIN/);
assert.equal(existsSync(rollbackForeignJournalPath), true);
assert.equal(existsSync(rollbackForeignJournal.ownedTargets[0].proof), true, 'rollback mismatch preserves proof');
assert.deepEqual(readFileSync(rollbackForeign.paths.manifest), readFileSync(rollbackForeign.manifestSource));
@@ -360,8 +451,15 @@ for (const fault of ['SIGKILL:PROVISION_PRE_LINK', 'SIGKILL:PROVISION_LINKED', '
CLAUDE_COORDINATION_TEST_FAULT: fault,
});
assert.equal(result.signal, 'SIGKILL', fault);
+ assert.match(run(['rollback', '--plan', crashPlanPath, '--expected-digest', crashPlan.digest]).stderr, /BOOTSTRAP_/);
+ writeFileSync(crash.paths.trust, Buffer.alloc(32, 9), { flag: 'wx', mode: 0o600 });
+ const recoveryResult = run(crash.args);
+ assert.equal(recoveryResult.status, 0, recoveryResult.stderr);
+ const recoveryPlan = JSON.parse(recoveryResult.stdout);
+ const recoveryPath = join(crash.root, 'present-recovery-plan.json');
+ writeFileSync(recoveryPath, recoveryResult.stdout, { mode: 0o600 });
assert.equal(
- run(['rollback', '--plan', crashPlanPath, '--expected-digest', crashPlan.digest]).status,
+ run(['rollback', '--plan', recoveryPath, '--expected-digest', recoveryPlan.digest]).status,
0,
`${fault} rollback`,
);
@@ -377,17 +475,131 @@ const completePlanPath = join(completeCleanup.root, 'plan.json');
writeFileSync(completePlanPath, completePlanResult.stdout, { mode: 0o600 });
assert.equal(
run(['apply', '--plan', completePlanPath, '--expected-digest', completePlan.digest], {
+ CLAUDE_COORDINATION_TESTING: '1',
CLAUDE_COORDINATION_TEST_SIGKILL_COMPLETE_PROOF_AFTER: '2',
}).signal,
'SIGKILL',
);
assert.equal(
- run(['apply', '--plan', completePlanPath, '--expected-digest', completePlan.digest]).status,
+ (() => {
+ const recoveryResult = run(completeCleanup.args);
+ assert.equal(recoveryResult.status, 0, recoveryResult.stderr);
+ const recoveryPlan = JSON.parse(recoveryResult.stdout);
+ const recoveryPath = join(completeCleanup.root, 'present-complete-plan.json');
+ writeFileSync(recoveryPath, recoveryResult.stdout, { mode: 0o600 });
+ return run(['apply', '--plan', recoveryPath, '--expected-digest', recoveryPlan.digest]).status;
+ })(),
0,
'fresh apply completes interrupted COMPLETE proof cleanup',
);
assert.equal(existsSync(`${completeCleanup.paths.config}.provision-journal`), false);
+// Completion receipt publication recovers the exact deterministic preparation
+// inode after every crash boundary; a forged receipt or preparation is refused.
+for (const fault of ['SIGKILL:RECORD_PRE_LINK', 'SIGKILL:RECORD_LINKED', 'SIGKILL:RECORD_DIR_FSYNCED']) {
+ const receiptCrash = fixture();
+ writeFileSync(receiptCrash.paths.trust, Buffer.alloc(32, 7), { mode: 0o600 });
+ const receiptPlanResult = run(receiptCrash.args);
+ assert.equal(receiptPlanResult.status, 0, receiptPlanResult.stderr);
+ const receiptPlan = JSON.parse(receiptPlanResult.stdout);
+ const receiptPlanPath = join(receiptCrash.root, 'receipt-plan.json');
+ const receiptPath = `${receiptCrash.paths.config}.provision-receipt.${receiptPlan.digest}`;
+ writeFileSync(receiptPlanPath, receiptPlanResult.stdout, { mode: 0o600 });
+ const crashed = run(['apply', '--plan', receiptPlanPath, '--expected-digest', receiptPlan.digest], {
+ CLAUDE_COORDINATION_TESTING: '1',
+ CLAUDE_COORDINATION_TEST_RECORD_TARGET: receiptPath,
+ CLAUDE_COORDINATION_TEST_FAULT: fault,
+ });
+ assert.equal(crashed.signal, 'SIGKILL', fault);
+ const recoveryPlanResult = run(receiptCrash.args);
+ assert.equal(recoveryPlanResult.status, 0, recoveryPlanResult.stderr);
+ const recoveryPlan = JSON.parse(recoveryPlanResult.stdout);
+ const recoveryPlanPath = join(receiptCrash.root, `receipt-recovery-${fault.replaceAll(':', '-')}.json`);
+ writeFileSync(recoveryPlanPath, recoveryPlanResult.stdout, { mode: 0o600 });
+ const recovered = run(['apply', '--plan', recoveryPlanPath, '--expected-digest', recoveryPlan.digest]);
+ assert.equal(recovered.status, 0, `${fault} reviewed receipt recovery: ${recovered.stderr}`);
+}
+
+const forgedReceipt = fixture();
+writeFileSync(forgedReceipt.paths.trust, Buffer.alloc(32, 7), { mode: 0o600 });
+const forgedPlanResult = run(forgedReceipt.args);
+const forgedPlan = JSON.parse(forgedPlanResult.stdout);
+const forgedPlanPath = join(forgedReceipt.root, 'forged-receipt-plan.json');
+writeFileSync(forgedPlanPath, forgedPlanResult.stdout, { mode: 0o600 });
+assert.equal(run(['apply', '--plan', forgedPlanPath, '--expected-digest', forgedPlan.digest]).status, 0);
+const forgedReceiptPath = `${forgedReceipt.paths.config}.provision-receipt.${forgedPlan.digest}`;
+const authenticReceipt = JSON.parse(readFileSync(forgedReceiptPath, 'utf8'));
+unlinkSync(forgedReceiptPath);
+writeFileSync(forgedReceiptPath, `${JSON.stringify({ ...authenticReceipt, signature: '0'.repeat(64) })}\n`, {
+ mode: 0o600,
+});
+assert.match(
+ run(['apply', '--plan', forgedPlanPath, '--expected-digest', forgedPlan.digest]).stderr,
+ /INVALID_PROVISION_RECEIPT/,
+);
+
+const replacedTrust = fixture();
+writeFileSync(replacedTrust.paths.trust, Buffer.alloc(32, 7), { mode: 0o600 });
+const replacedTrustPlanResult = run(replacedTrust.args);
+const replacedTrustPlan = JSON.parse(replacedTrustPlanResult.stdout);
+const replacedTrustPlanPath = join(replacedTrust.root, 'replaced-trust-plan.json');
+writeFileSync(replacedTrustPlanPath, replacedTrustPlanResult.stdout, { mode: 0o600 });
+unlinkSync(replacedTrust.paths.trust);
+writeFileSync(replacedTrust.paths.trust, Buffer.alloc(32, 7), { mode: 0o600 });
+assert.match(
+ run(['apply', '--plan', replacedTrustPlanPath, '--expected-digest', replacedTrustPlan.digest]).stderr,
+ /TRUST_SNAPSHOT_CHANGED/,
+ 'same-byte trust replacement is rejected by descriptor identity',
+);
+
+const forgedJournal = fixture();
+writeFileSync(forgedJournal.paths.trust, Buffer.alloc(32, 7), { mode: 0o600 });
+writeFileSync(
+ `${forgedJournal.paths.config}.provision-journal`,
+ `${JSON.stringify({
+ version: 1,
+ operationId: 'a'.repeat(32),
+ planDigest: 'b'.repeat(64),
+ phase: 'APPLYING',
+ ownedTargets: [
+ {
+ path: forgedJournal.paths.manifest,
+ proof: forgedJournal.manifestSource,
+ digest: 'c'.repeat(64),
+ dev: '1',
+ ino: '1',
+ birthtimeNs: '1',
+ length: 1,
+ },
+ ],
+ })}\n`,
+ { mode: 0o600 },
+);
+assert.match(run(forgedJournal.args).stderr, /INVALID_PROVISION_JOURNAL/);
+
+const postPlanJournal = fixture();
+writeFileSync(postPlanJournal.paths.trust, Buffer.alloc(32, 7), { mode: 0o600 });
+const postPlanResult = run(postPlanJournal.args);
+const postPlan = JSON.parse(postPlanResult.stdout);
+const postPlanPath = join(postPlanJournal.root, 'post-plan-journal.json');
+writeFileSync(postPlanPath, postPlanResult.stdout, { mode: 0o600 });
+writeFileSync(
+ `${postPlanJournal.paths.config}.provision-journal`,
+ `${JSON.stringify({
+ version: 1,
+ operationId: 'a'.repeat(32),
+ planDigest: postPlan.digest,
+ phase: 'APPLYING',
+ ownedTargets: [],
+ })}\n`,
+ { mode: 0o600 },
+);
+assert.match(
+ run(['apply', '--plan', postPlanPath, '--expected-digest', postPlan.digest]).stderr,
+ /PROVISION_JOURNAL_REVIEW_REQUIRED/,
+ 'a correct-shape journal created after review is never recovery authority',
+);
+
// Upgrade keeps an existing owner-only key and provisions missing first-party artifacts.
const upgrade = fixture();
writeFileSync(upgrade.paths.trust, Buffer.alloc(32, 7), { mode: 0o600 });
diff --git a/claude-ops/scripts/account-rotation/__tests__/staged-enrollment.test.mjs b/claude-ops/scripts/account-rotation/__tests__/staged-enrollment.test.mjs
index a3628e5b..8071e48b 100644
--- a/claude-ops/scripts/account-rotation/__tests__/staged-enrollment.test.mjs
+++ b/claude-ops/scripts/account-rotation/__tests__/staged-enrollment.test.mjs
@@ -16,7 +16,7 @@ import {
} from 'node:fs';
import { tmpdir } from 'node:os';
import { hostname } from 'node:os';
-import { join } from 'node:path';
+import { basename, join } from 'node:path';
import { spawn, spawnSync } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import {
@@ -878,7 +878,7 @@ for (const phase of [
const receipt = JSON.parse(recovered.stdout);
assert.equal(receipt.recovered, true);
assert.equal(readFileSync(target, 'utf8'), phase === 'COMMITTED' ? JSON.stringify(CANDIDATE) : old);
- assert.equal(readdirSync(f.paths.rollback).length, phase === 'COMMITTED' ? 2 : 0);
+ assert.equal(readdirSync(f.paths.rollback).length, phase === 'COMMITTED' ? 3 : 0);
if (phase === 'COMMITTED') {
const beforeRollback = readFileSync(target);
const rolledBack = spawnSync(
@@ -889,7 +889,7 @@ for (const phase of [
assert.notEqual(rolledBack.status, 0);
assert.match(rolledBack.stderr, /INVALID_ARGUMENTS/);
assert.deepEqual(readFileSync(target), beforeRollback, 'unsigned rollback performs zero writes');
- assert.equal(readdirSync(f.paths.rollback).length, 2, 'unsigned rollback retains all evidence');
+ assert.equal(readdirSync(f.paths.rollback).length, 3, 'unsigned rollback retains all evidence');
}
const again = recoverEnrollment({ configPath: f.configPath });
assert.equal(again.recovered, false);
@@ -953,7 +953,10 @@ for (const phase of [
assert.equal(killed.signal, 'SIGKILL', killed.stderr);
assert.equal(recoverEnrollment({ configPath: f.configPath }).outcome, 'rolled-back');
assert.equal(readFileSync(target, 'utf8'), old);
- assert.deepEqual(readdirSync(f.paths.rollback), []);
+ assert.ok(
+ readdirSync(f.paths.rollback).every((name) => name.startsWith('.evidence-') || name.includes('.preparation-')),
+ 'rollback cleanup retains only authenticated evidence and deterministic preparations',
+ );
}
// Recovery is bound to the authenticated raw M0 digest and complete entry
@@ -1181,7 +1184,7 @@ for (const hadTarget of [false, true]) {
assert.equal(killed.signal, 'SIGKILL', killed.stderr);
assert.equal(recoverEnrollment({ configPath: f.configPath }).outcome, 'committed');
assert.equal(readFileSync(target, 'utf8'), JSON.stringify(CANDIDATE));
- assert.equal(readdirSync(f.paths.rollback).length, hadTarget ? 2 : 0);
+ assert.equal(readdirSync(f.paths.rollback).length, hadTarget ? 3 : 0);
assert.equal(recoverEnrollment({ configPath: f.configPath }).recovered, false);
}
@@ -1260,7 +1263,7 @@ for (const fault of ['THROW:PUBLICATION_FIRST_DIR_FSYNC', 'THROW:PUBLICATION_CLE
assert.equal(existsSync(join(f.paths.usage, `${approval.payload.id}.${approval.payload.nonce}.used`)), true);
refuses(
() => stageEnrollment({ ...f.common, candidatePath: f.candidatePath }),
- 'APPROVAL_REPLAY|STAGE_TARGET_EXISTS|DUPLICATE_IDENTITY',
+ 'APPROVAL_REPLAY|STAGE_TARGET_EXISTS|DUPLICATE_IDENTITY|INSECURE_TRUST_ROOT',
);
}
assert.equal(existsSync(`${f.common.operationLockPath}.publication`), false);
@@ -1286,13 +1289,13 @@ for (const boundary of ['STAGED_LINK', 'MARKER_LINK']) {
assert.equal(recovered.status, 0, `${boundary}: ${recovered.stderr}`);
assert.match(
recovered.stdout,
- boundary === 'STAGED_LINK' ? /^ok$/ : /APPROVAL_REPLAY|DUPLICATE_IDENTITY|STAGE_TARGET_EXISTS/,
+ boundary === 'STAGED_LINK' ? /^ok$/ : /APPROVAL_REPLAY|DUPLICATE_IDENTITY|STAGE_TARGET_EXISTS|INSECURE_TRUST_ROOT/,
);
assert.equal(existsSync(`${f.common.operationLockPath}.publication`), false);
}
-// A failed post-link durability step never leaves unauthorized staged bytes or
-// a replay marker behind when cleanup can be proven durable.
+// A failed post-link durability step removes only descriptor-pinned staged
+// bytes. A published signed marker remains authoritative and is never deleted.
for (const fault of ['THROW:STAGE_AFTER_LINK', 'THROW:MARKER_AFTER_LINK']) {
const f = fixture();
const approval = f.approval('stage');
@@ -1309,11 +1312,14 @@ for (const fault of ['THROW:STAGE_AFTER_LINK', 'THROW:MARKER_AFTER_LINK']) {
else process.env.CLAUDE_STAGED_ENROLLMENT_TEST_FAULT = priorFault;
}
assert.equal(existsSync(join(f.paths.staging, ENTRY.authFilename)), false);
- assert.equal(existsSync(join(f.paths.usage, `${approval.payload.id}.${approval.payload.nonce}.used`)), false);
+ assert.equal(
+ existsSync(join(f.paths.usage, `${approval.payload.id}.${approval.payload.nonce}.used`)),
+ fault === 'THROW:MARKER_AFTER_LINK',
+ );
}
-// An ambiguous activation-marker publication is resolved by a fresh recovery
-// process. When cleanup removed the marker, the same approval remains usable.
+// An ambiguous activation-marker publication is resolved fail closed: the
+// signed marker remains authoritative and the approval cannot be reused.
{
const f = fixture();
f.approval('stage');
@@ -1331,13 +1337,13 @@ for (const fault of ['THROW:STAGE_AFTER_LINK', 'THROW:MARKER_AFTER_LINK']) {
if (priorFault === undefined) delete process.env.CLAUDE_STAGED_ENROLLMENT_TEST_FAULT;
else process.env.CLAUDE_STAGED_ENROLLMENT_TEST_FAULT = priorFault;
}
- assert.equal(existsSync(join(f.paths.usage, `${approval.payload.id}.${approval.payload.nonce}.used`)), false);
+ assert.equal(existsSync(join(f.paths.usage, `${approval.payload.id}.${approval.payload.nonce}.used`)), true);
assert.equal(recoverEnrollment({ configPath: f.configPath }).outcome, 'rolled-back');
- assert.equal(activateEnrollment(f.common).ok, true);
+ refuses(() => activateEnrollment(f.common), 'APPROVAL_REPLAY|ACTIVATION_RECOVERY_REQUIRED');
}
-// A fresh recovery process removes the one expected activation marker temp
-// hardlink left by SIGKILL after link(2), then validates the canonical marker.
+// Fresh recovery validates the exact deterministic marker preparation alias
+// left by SIGKILL after link(2) and retains it as bounded evidence.
{
const f = fixture();
f.approval('stage');
@@ -1355,13 +1361,19 @@ for (const fault of ['THROW:STAGE_AFTER_LINK', 'THROW:MARKER_AFTER_LINK']) {
});
assert.equal(killed.signal, 'SIGKILL', killed.stderr);
const marker = join(f.paths.usage, `${approval.payload.id}.${approval.payload.nonce}.used`);
- assert.equal(readdirSync(f.paths.usage).filter((name) => name.endsWith('.tmp')).length, 1);
+ assert.equal(
+ readdirSync(f.paths.usage).filter((name) => name.startsWith(`${basename(marker)}.preparation-`)).length,
+ 1,
+ );
const recoveryScript = `import(${JSON.stringify(`file://${modulePath}`)}).then(m=>process.stdout.write(JSON.stringify(m.recoverEnrollment({configPath:${JSON.stringify(f.configPath)}}))))`;
const recovered = spawnSync(process.execPath, ['--input-type=module', '-e', recoveryScript], { encoding: 'utf8' });
assert.equal(recovered.status, 0, recovered.stderr);
assert.equal(JSON.parse(recovered.stdout).outcome, 'rolled-back');
assert.equal(existsSync(marker), true);
- assert.equal(readdirSync(f.paths.usage).filter((name) => name.endsWith('.tmp')).length, 0);
+ assert.equal(
+ readdirSync(f.paths.usage).filter((name) => name.startsWith(`${basename(marker)}.preparation-`)).length,
+ 1,
+ );
assert.equal(recoverEnrollment({ configPath: f.configPath }).recovered, false);
}
@@ -1552,7 +1564,10 @@ for (const mutate of [
f.approval('stage');
stageEnrollment({ ...f.common, candidatePath: f.candidatePath });
unlinkSync(join(f.paths.staging, ENTRY.authFilename));
- refuses(() => stageEnrollment({ ...f.common, candidatePath: f.candidatePath }), 'APPROVAL_REPLAY');
+ refuses(
+ () => stageEnrollment({ ...f.common, candidatePath: f.candidatePath }),
+ 'APPROVAL_REPLAY|INSECURE_TRUST_ROOT|PUBLICATION_RECOVERY_UNCERTAIN',
+ );
}
{
const f = fixture();
@@ -2406,6 +2421,80 @@ for (const asynchronous of [false, true]) {
// Authorized rollback is recoverable in a fresh process at every durable
// intent/switch/cleanup boundary without reusing the external approval.
+
+// A retained staging proof is re-homed as the rollback anchor rather than
+// copied to a third link, so a second complete rotation remains valid.
+{
+ const f = fixture();
+ f.approval('stage');
+ stageEnrollment({ ...f.common, candidatePath: f.candidatePath });
+ f.approval('activate');
+ activateEnrollment(f.common);
+
+ const secondCandidate = { ...CANDIDATE, access_token: 'second-rotation-access-token' };
+ writeFileSync(f.candidatePath, JSON.stringify(secondCandidate), { mode: 0o600 });
+ const secondDigest = sha256(readFileSync(f.candidatePath));
+ const secondCanary = JSON.parse(readFileSync(f.canaryPath, 'utf8'));
+ secondCanary.results.forEach((result) => (result.candidateDigest = secondDigest));
+ writeFileSync(f.canaryPath, JSON.stringify(secondCanary), { mode: 0o600 });
+ f.approval('stage', { id: 'second-stage', nonce: 'second-stage-nonce', candidateDigest: secondDigest });
+ stageEnrollment({ ...f.common, candidatePath: f.candidatePath });
+ f.approval('activate', {
+ id: 'second-activate',
+ nonce: 'second-activate-nonce',
+ candidateDigest: secondDigest,
+ canaryDigest: sha256(readFileSync(f.canaryPath)),
+ });
+ activateEnrollment(f.common);
+ assert.equal(
+ sha256(readFileSync(join(f.paths.active, ENTRY.authFilename))),
+ secondDigest,
+ 'second rotation becomes canonical',
+ );
+}
+
+{
+ const f = fixture();
+ f.approval('stage');
+ stageEnrollment({ ...f.common, candidatePath: f.candidatePath });
+ f.approval('activate');
+ activateEnrollment(f.common);
+ const active = join(f.paths.active, ENTRY.authFilename);
+ const activeDigest = sha256(readFileSync(active));
+ const activeProof = `${join(f.paths.staging, ENTRY.authFilename)}.preparation-${activeDigest}`;
+ const secondCandidate = { ...CANDIDATE, access_token: 'proof-race-second-token' };
+ writeFileSync(f.candidatePath, JSON.stringify(secondCandidate), { mode: 0o600 });
+ const secondDigest = sha256(readFileSync(f.candidatePath));
+ const secondCanary = JSON.parse(readFileSync(f.canaryPath, 'utf8'));
+ secondCanary.results.forEach((result) => (result.candidateDigest = secondDigest));
+ writeFileSync(f.canaryPath, JSON.stringify(secondCanary), { mode: 0o600 });
+ f.approval('stage', { id: 'proof-race-stage', nonce: 'proof-race-stage-nonce', candidateDigest: secondDigest });
+ stageEnrollment({ ...f.common, candidatePath: f.candidatePath });
+ const activation = f.approval('activate', {
+ id: 'proof-race-activate',
+ nonce: 'proof-race-activate-nonce',
+ candidateDigest: secondDigest,
+ canaryDigest: sha256(readFileSync(f.canaryPath)),
+ });
+ refuses(
+ () =>
+ activateEnrollment({
+ ...f.common,
+ beforeCas: () => {
+ unlinkSync(activeProof);
+ writeFileSync(activeProof, readFileSync(active), { mode: 0o600 });
+ },
+ }),
+ 'ACTIVE_TARGET_CAS_FAILED',
+ );
+ assert.equal(sha256(readFileSync(active)), activeDigest, 'proof replacement cannot switch the active target');
+ assert.equal(
+ existsSync(join(f.paths.usage, `${activation.payload.id}.${activation.payload.nonce}.used`)),
+ false,
+ 'proof replacement is rejected before approval consumption',
+ );
+}
+
for (const fault of [
'SIGKILL:ROLLBACK_PREPARING_INTENT',
'SIGKILL:ROLLBACK_TEMP_LINK',
@@ -2437,7 +2526,10 @@ for (const fault of [
assert.equal(recovered.status, 0, `${fault}: ${recovered.stderr}`);
assert.equal(JSON.parse(recovered.stdout).recovered, true);
assert.equal(readFileSync(target, 'utf8'), old);
- assert.deepEqual(readdirSync(f.paths.rollback), []);
+ assert.ok(
+ readdirSync(f.paths.rollback).every((name) => name.startsWith('.evidence-') || name.includes('.preparation-')),
+ `${fault}: rollback retains only authenticated evidence`,
+ );
}
console.log('staged-enrollment.test.mjs: ok');
diff --git a/claude-ops/scripts/account-rotation/provision-coordination.mjs b/claude-ops/scripts/account-rotation/provision-coordination.mjs
index d6897f41..1e1ace68 100755
--- a/claude-ops/scripts/account-rotation/provision-coordination.mjs
+++ b/claude-ops/scripts/account-rotation/provision-coordination.mjs
@@ -9,7 +9,6 @@ import {
lstatSync,
realpathSync,
renameSync,
- rmSync,
statSync,
writeFileSync,
closeSync,
@@ -19,7 +18,7 @@ import {
fstatSync,
unlinkSync,
} from 'node:fs';
-import { createHash, randomBytes } from 'node:crypto';
+import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { spawnSync } from 'node:child_process';
@@ -113,70 +112,87 @@ function fsyncDirectory(path) {
}
}
function processStart(pid) {
+ try {
+ process.kill(pid, 0);
+ } catch (error) {
+ return error?.code === 'ESRCH' ? { state: 'dead' } : { state: 'unknown' };
+ }
try {
const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');
const fields = stat.slice(stat.lastIndexOf(') ') + 2).split(' ');
- return fields[19];
+ if (!/^\d+$/.test(fields[19] || '')) return { state: 'unknown' };
+ return { state: 'live', value: fields[19] };
} catch {
- return null;
+ return { state: 'unknown' };
}
}
+function bootstrapAttemptPath(plan) {
+ return `${plan.paths['provision-lock']}.bootstrap-attempt`;
+}
+function validateProvisionLockRecord(record) {
+ if (
+ !record ||
+ Object.keys(record).sort().join(',') !== 'nonce,pid,planDigest,start,version' ||
+ record.version !== 1 ||
+ typeof record.planDigest !== 'string' ||
+ !/^[a-f0-9]{64}$/.test(record.planDigest || '') ||
+ !Number.isSafeInteger(record.pid) ||
+ record.pid <= 0 ||
+ typeof record.start !== 'string' ||
+ !/^(0|[1-9]\d*)$/.test(record.start || '') ||
+ typeof record.nonce !== 'string' ||
+ !/^[a-f0-9]{32}$/.test(record.nonce || '')
+ )
+ fail('INVALID_PROVISION_LOCK');
+ return record;
+}
function withProvisionLock(plan, callback) {
const path = plan.paths['provision-lock'];
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
let owned;
for (let attempt = 0; attempt < 2; attempt++) {
try {
- const fd = openSync(path, 'wx', 0o600);
const nonce = randomBytes(16).toString('hex');
- try {
- writeFileSync(
- fd,
- `${JSON.stringify({ version: 1, planDigest: plan.digest, pid: process.pid, start: processStart(process.pid), nonce })}\n`,
- );
- fsyncSync(fd);
- } finally {
- closeSync(fd);
- }
- fsyncDirectory(dirname(path));
- owned = lstatSync(path);
+ const self = processStart(process.pid);
+ if (self.state !== 'live') fail('PROVISION_LOCK_LIVENESS_UNKNOWN');
+ owned = publishExclusiveRecord(
+ path,
+ `${JSON.stringify({ version: 1, planDigest: plan.digest, pid: process.pid, start: self.value, nonce })}\n`,
+ 'PROVISION_LOCK_PUBLICATION_FAILED',
+ );
break;
} catch (error) {
if (error?.code !== 'EEXIST' || attempt > 0) throw error;
validateExistingTarget(path, 'file');
- const descriptor = lstatSync(path);
- const stale = json(path, 'INVALID_PROVISION_LOCK');
+ const descriptor = secureReadDescriptor(path, 'INVALID_PROVISION_LOCK');
+ if (!plan.provisionLockSnapshot || !descriptorEquals(descriptor, plan.provisionLockSnapshot))
+ fail('PROVISION_LOCK_REVIEW_REQUIRED');
+ const stale = validateProvisionLockRecord(parseStrictJson(descriptor.bytes, 'INVALID_PROVISION_LOCK'));
if (
- Object.keys(stale).sort().join(',') !== 'nonce,pid,planDigest,start,version' ||
- stale.version !== 1 ||
- stale.planDigest !== plan.digest ||
- !Number.isSafeInteger(stale.pid) ||
- typeof stale.start !== 'string' ||
- !/^[a-f0-9]{32}$/.test(stale.nonce)
+ ![plan.digest, plan.recoverySnapshot?.planDigest, plan.provisionLockSnapshot?.planDigest]
+ .filter(Boolean)
+ .includes(stale.planDigest)
)
fail('INVALID_PROVISION_LOCK');
- if (processStart(stale.pid) === stale.start) fail('PROVISION_LOCK_HELD');
- const current = lstatSync(path);
- if (current.dev !== descriptor.dev || current.ino !== descriptor.ino) fail('PROVISION_LOCK_OWNERSHIP_LOST');
- unlinkSync(path);
- fsyncDirectory(dirname(path));
+ const current = processStart(stale.pid);
+ if (current.state === 'unknown' || (current.state === 'live' && current.value === stale.start))
+ fail('PROVISION_LOCK_HELD');
+ removeOwnedPath(path, descriptor, 'PROVISION_LOCK_OWNERSHIP_LOST');
}
}
if (!owned) fail('PROVISION_LOCK_HELD');
try {
return callback();
} finally {
- if (existsSync(path)) {
- const current = lstatSync(path);
- if (current.dev !== owned.dev || current.ino !== owned.ino) fail('PROVISION_LOCK_OWNERSHIP_LOST');
- unlinkSync(path);
- fsyncDirectory(dirname(path));
- }
+ if (!removeOwnedPath(path, owned, 'PROVISION_LOCK_OWNERSHIP_LOST')) fail('PROVISION_LOCK_OWNERSHIP_LOST');
}
}
function descriptorIdentity(stat) {
return { dev: stat.dev.toString(), ino: stat.ino.toString(), birthtimeNs: stat.birthtimeNs.toString() };
}
+function descriptorEquals(actual, expected) {
+ return ['dev', 'ino', 'birthtimeNs', 'digest', 'length'].every((key) => actual[key] === expected[key]);
+}
function secureReadDescriptor(path, code, requireSingleLink = true) {
let fd;
try {
@@ -186,13 +202,18 @@ function secureReadDescriptor(path, code, requireSingleLink = true) {
const post = fstatSync(fd, { bigint: true });
const named = lstatSync(path, { bigint: true });
const identity = descriptorIdentity(pre);
+ const preparation = `${path}.preparation-${rawDigest(bytes)}`;
+ const boundedLinks =
+ pre.nlink === 2n &&
+ existsSync(preparation) &&
+ canonicalJson(identity) === canonicalJson(descriptorIdentity(lstatSync(preparation, { bigint: true })));
if (
!pre.isFile() ||
!named.isFile() ||
canonicalJson(identity) !== canonicalJson(descriptorIdentity(post)) ||
canonicalJson(identity) !== canonicalJson(descriptorIdentity(named)) ||
pre.uid !== BigInt(process.getuid()) ||
- (requireSingleLink && pre.nlink !== 1n) ||
+ (requireSingleLink && pre.nlink !== 1n && !boundedLinks) ||
(pre.mode & 0o077n) !== 0n
)
fail(code);
@@ -203,18 +224,169 @@ function secureReadDescriptor(path, code, requireSingleLink = true) {
if (fd !== undefined) closeSync(fd);
}
}
+function secureReadPublishedRecord(path, code) {
+ const descriptor = secureReadDescriptor(path, code, false);
+ const proof = `${path}.preparation-${descriptor.digest}`;
+ const named = lstatSync(path, { bigint: true });
+ if (named.nlink === 1n) return descriptor;
+ if (named.nlink !== 2n || !existsSync(proof) || !descriptorMatches(proof, descriptor, code)) fail(code);
+ return { ...descriptor, proof };
+}
function secureReadSource(path, code) {
- return secureReadDescriptor(path, code).bytes;
+ return secureReadPublishedRecord(path, code).bytes;
}
function descriptorMatches(path, expected, code = 'PROVISION_RECOVERY_UNCERTAIN') {
const actual = secureReadDescriptor(path, code, false);
- return ['dev', 'ino', 'birthtimeNs', 'digest', 'length'].every((key) => actual[key] === expected[key]);
+ return descriptorEquals(actual, expected);
+}
+function completionReceiptPath(plan) {
+ return `${plan.paths.config}.provision-receipt.${plan.digest}`;
+}
+function completionPayload(plan, trust) {
+ return {
+ version: 1,
+ planDigest: plan.digest,
+ trustSnapshot: plan.trustSnapshot,
+ trustDescriptor: Object.fromEntries(
+ ['dev', 'ino', 'birthtimeNs', 'digest', 'length'].map((key) => [key, trust[key]]),
+ ),
+ };
+}
+function reviewedTrust(plan) {
+ if (plan.trustSnapshot?.state !== 'present' || !existsSync(plan.paths.trust)) fail('TRUST_SNAPSHOT_CHANGED');
+ const trust = secureReadDescriptor(plan.paths.trust, 'TRUST_SNAPSHOT_CHANGED');
+ if (!descriptorEquals(trust, plan.trustSnapshot)) fail('TRUST_SNAPSHOT_CHANGED');
+ return trust;
+}
+function validateCompletionReceipt(plan, trust = reviewedTrust(plan)) {
+ const path = completionReceiptPath(plan);
+ if (!existsSync(path)) fail('INVALID_PROVISION_RECEIPT');
+ if (!descriptorMatches(plan.paths.trust, trust, 'TRUST_SNAPSHOT_CHANGED')) fail('TRUST_SNAPSHOT_CHANGED');
+ const receiptDescriptor = secureReadPublishedRecord(path, 'INVALID_PROVISION_RECEIPT');
+ let receipt;
+ try {
+ receipt = parseStrictJson(receiptDescriptor.bytes, 'INVALID_PROVISION_RECEIPT');
+ } catch {
+ fail('INVALID_PROVISION_RECEIPT');
+ }
+ if (!receipt || Object.keys(receipt).sort().join(',') !== 'payload,signature') fail('INVALID_PROVISION_RECEIPT');
+ const expected = completionPayload(plan, trust);
+ if (canonicalJson(receipt.payload) !== canonicalJson(expected) || !/^[a-f0-9]{64}$/.test(receipt.signature || ''))
+ fail('INVALID_PROVISION_RECEIPT');
+ const signature = createHmac('sha256', trust.bytes).update(canonicalJson(expected)).digest();
+ if (!timingSafeEqual(Buffer.from(receipt.signature, 'hex'), signature)) fail('INVALID_PROVISION_RECEIPT');
+ return true;
+}
+function publishCompletionReceipt(plan, trust) {
+ if (plan.trustSnapshot?.state !== 'present') return false;
+ const path = completionReceiptPath(plan);
+ trust ||= reviewedTrust(plan);
+ if (!descriptorMatches(plan.paths.trust, trust, 'TRUST_SNAPSHOT_CHANGED')) fail('TRUST_SNAPSHOT_CHANGED');
+ const payload = completionPayload(plan, trust);
+ const bytes = Buffer.from(
+ `${canonicalJson({ payload, signature: createHmac('sha256', trust.bytes).update(canonicalJson(payload)).digest('hex') })}\n`,
+ );
+ if (existsSync(path)) return validateCompletionReceipt(plan, trust);
+ publishExclusiveRecord(path, bytes, 'INVALID_PROVISION_RECEIPT');
+ return validateCompletionReceipt(plan, trust);
+}
+function publishExclusiveRecord(path, bytes, code) {
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
+ const expectedBytes = Buffer.from(bytes);
+ const temp = `${path}.preparation-${rawDigest(expectedBytes)}`;
+ let descriptor;
+ let fd;
+ try {
+ fd = openSync(temp, 'wx', 0o600);
+ } catch (error) {
+ if (error?.code !== 'EEXIST') throw error;
+ }
+ if (fd === undefined) {
+ descriptor = secureReadDescriptor(temp, code, false);
+ if (!descriptor.bytes.equals(expectedBytes)) fail(code);
+ } else {
+ try {
+ writeFileSync(fd, expectedBytes);
+ fsyncSync(fd);
+ const stat = fstatSync(fd, { bigint: true });
+ descriptor = {
+ ...descriptorIdentity(stat),
+ digest: rawDigest(expectedBytes),
+ length: expectedBytes.length,
+ };
+ } finally {
+ closeSync(fd);
+ }
+ }
+ fsyncDirectory(dirname(path));
+ if (
+ process.env.CLAUDE_COORDINATION_TESTING === '1' &&
+ process.env.CLAUDE_COORDINATION_TEST_RECORD_TARGET === path &&
+ process.env.CLAUDE_COORDINATION_TEST_FAULT === 'SIGKILL:RECORD_PRE_LINK'
+ )
+ process.kill(process.pid, 'SIGKILL');
+ if (existsSync(path)) {
+ if (!descriptorMatches(path, descriptor, code)) linkSync(temp, path);
+ } else linkSync(temp, path);
+ if (
+ process.env.CLAUDE_COORDINATION_TESTING === '1' &&
+ process.env.CLAUDE_COORDINATION_TEST_RECORD_TARGET === path &&
+ process.env.CLAUDE_COORDINATION_TEST_FAULT === 'SIGKILL:RECORD_LINKED'
+ )
+ process.kill(process.pid, 'SIGKILL');
+ fsyncDirectory(dirname(path));
+ if (!descriptorMatches(path, descriptor, code)) fail(code);
+ if (
+ process.env.CLAUDE_COORDINATION_TESTING === '1' &&
+ process.env.CLAUDE_COORDINATION_TEST_RECORD_TARGET === path &&
+ process.env.CLAUDE_COORDINATION_TEST_FAULT === 'SIGKILL:RECORD_DIR_FSYNCED'
+ )
+ process.kill(process.pid, 'SIGKILL');
+ // Retain the exact preparation alias. Readers permit only this digest-derived
+ // two-link topology and reject arbitrary hardlinks.
+ return descriptor;
+}
+
+function beginAbsentTrustBootstrap(plan) {
+ const path = bootstrapAttemptPath(plan);
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
+ let fd;
+ try {
+ fd = openSync(path, 'wx', 0o600);
+ writeFileSync(fd, `${canonicalJson({ version: 1, planDigest: plan.digest })}\n`);
+ fsyncSync(fd);
+ } catch (error) {
+ if (error?.code === 'EEXIST') fail('BOOTSTRAP_ATTEMPT_REVIEW_REQUIRED');
+ throw error;
+ } finally {
+ if (fd !== undefined) closeSync(fd);
+ }
+ fsyncDirectory(dirname(path));
+}
+function removeOwnedPath(path, expected, code = 'PROVISION_RECOVERY_UNCERTAIN') {
+ const detached = `${path}.detached-${process.pid}-${randomBytes(4).toString('hex')}`;
+ try {
+ renameSync(path, detached);
+ } catch (error) {
+ if (error?.code === 'ENOENT') return false;
+ throw error;
+ }
+ if (!descriptorMatches(detached, expected, code)) {
+ fsyncDirectory(dirname(path));
+ fail(code);
+ }
+ // Retain the detached inode as evidence. Restoring or automatically deleting
+ // it would reopen the replacement race this cleanup is intended to close.
+ fsyncDirectory(dirname(path));
+ return true;
}
function validateExistingTarget(path, kind) {
if (!existsSync(path)) return;
const st = lstatSync(path);
if (st.isSymbolicLink() || st.uid !== process.getuid()) fail('UNSAFE_EXISTING_TARGET');
- if (kind === 'file' && (!st.isFile() || st.nlink !== 1 || (st.mode & 0o077) !== 0)) fail('UNSAFE_EXISTING_TARGET');
+ if (kind === 'file' && (!st.isFile() || ![1, 2].includes(st.nlink) || (st.mode & 0o077) !== 0))
+ fail('UNSAFE_EXISTING_TARGET');
+ if (kind === 'file' && st.nlink === 2) secureReadPublishedRecord(path, 'UNSAFE_EXISTING_TARGET');
if (kind === 'directory' && (!st.isDirectory() || (st.mode & 0o077) !== 0)) fail('UNSAFE_EXISTING_TARGET');
}
function validateTopology(paths, quarantine) {
@@ -320,6 +492,61 @@ function buildPlan(args) {
const paths = Object.fromEntries(PATH_FLAGS.map((k) => [k, args[k]]));
const quarantine = args.quarantine.split(',').filter(Boolean);
const canonicalPaths = validateTopology(paths, quarantine);
+ const trustSnapshot = existsSync(canonicalPaths.trust)
+ ? { state: 'present', ...secureReadDescriptor(canonicalPaths.trust, 'INVALID_TRUST_SNAPSHOT') }
+ : { state: 'absent' };
+ delete trustSnapshot.bytes;
+ const recoveryJournalPath = `${canonicalPaths.config}.provision-journal`;
+ const transitionPath = `${recoveryJournalPath}.transition`;
+ const transitionSnapshot = existsSync(transitionPath)
+ ? secureReadDescriptor(transitionPath, 'INVALID_PROVISION_JOURNAL_TRANSITION')
+ : null;
+ let transition;
+ if (transitionSnapshot) {
+ transition = parseStrictJson(transitionSnapshot.bytes, 'INVALID_PROVISION_JOURNAL_TRANSITION');
+ delete transitionSnapshot.bytes;
+ }
+ if (trustSnapshot.state === 'absent' && (transitionSnapshot || existsSync(recoveryJournalPath)))
+ fail('BOOTSTRAP_JOURNAL_REVIEW_REQUIRED');
+ let recoverySnapshot = existsSync(recoveryJournalPath)
+ ? secureReadDescriptor(recoveryJournalPath, 'INVALID_PROVISION_JOURNAL')
+ : null;
+ if (transition) {
+ if (
+ transition.version !== 1 ||
+ transition.path !== recoveryJournalPath ||
+ transition.nextProof !== `${recoveryJournalPath}.preparation-${transition.next?.digest}` ||
+ !descriptorMatches(transition.nextProof, transition.next, 'INVALID_PROVISION_JOURNAL_TRANSITION')
+ )
+ fail('INVALID_PROVISION_JOURNAL_TRANSITION');
+ recoverySnapshot = {
+ ...transition.next,
+ bytes: secureReadDescriptor(transition.nextProof, 'INVALID_PROVISION_JOURNAL_TRANSITION', false).bytes,
+ };
+ }
+ if (recoverySnapshot) {
+ let recoveryState;
+ try {
+ recoveryState = parseStrictJson(recoverySnapshot.bytes, 'INVALID_PROVISION_JOURNAL');
+ } catch {
+ fail('INVALID_PROVISION_JOURNAL');
+ }
+ validateProvisionJournalState(recoveryState, canonicalPaths);
+ recoverySnapshot.topology = provisionRecoveryTopology(recoveryState);
+ recoverySnapshot.planDigest = recoveryState.planDigest;
+ recoverySnapshot.state = recoveryState;
+ delete recoverySnapshot.bytes;
+ }
+ const provisionLockSnapshot = existsSync(canonicalPaths['provision-lock'])
+ ? secureReadDescriptor(canonicalPaths['provision-lock'], 'INVALID_PROVISION_LOCK')
+ : null;
+ if (provisionLockSnapshot) {
+ const lockState = validateProvisionLockRecord(
+ parseStrictJson(provisionLockSnapshot.bytes, 'INVALID_PROVISION_LOCK'),
+ );
+ provisionLockSnapshot.planDigest = lockState.planDigest;
+ delete provisionLockSnapshot.bytes;
+ }
const manifestSource = canonicalProspective(args['manifest-source']);
validateExistingTarget(manifestSource, 'file');
const provisionJournal = canonicalProspective(`${canonicalPaths.config}.provision-journal`);
@@ -364,6 +591,10 @@ function buildPlan(args) {
operator: args.operator,
environment: args.environment,
maxApprovalTtlMs: 900000,
+ trustSnapshot,
+ recoverySnapshot,
+ provisionLockSnapshot,
+ transitionSnapshot,
};
const intentDigest = digest(body);
const withIntent = { ...body, intentDigest };
@@ -379,22 +610,34 @@ function atomicWrite(path, data, written, onPrepared, modeBits = 0o600) {
fail('EXISTING_FILE_MISMATCH');
}
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
- const temp = `${path}.tmp-${process.pid}-${randomBytes(4).toString('hex')}`;
- const fd = openSync(temp, 'wx', modeBits);
+ const temp = `${path}.preparation-${rawDigest(Buffer.from(data))}`;
let descriptor;
let journaled = false;
+ let fd;
try {
- writeFileSync(fd, data);
- fsyncSync(fd);
- const st = fstatSync(fd, { bigint: true });
- descriptor = {
- ...descriptorIdentity(st),
- digest: rawDigest(Buffer.from(data)),
- length: Buffer.byteLength(data),
- proof: temp,
- };
- } finally {
- closeSync(fd);
+ fd = openSync(temp, 'wx', modeBits);
+ } catch (error) {
+ if (error?.code !== 'EEXIST') throw error;
+ }
+ if (fd === undefined) {
+ descriptor = secureReadDescriptor(temp, 'PROVISION_RECOVERY_UNCERTAIN', false);
+ if (!descriptor.bytes.equals(Buffer.from(data)) || mode(temp) !== modeBits || lstatSync(temp).nlink !== 1)
+ fail('PROVISION_RECOVERY_UNCERTAIN');
+ descriptor.proof = temp;
+ } else {
+ try {
+ writeFileSync(fd, data);
+ fsyncSync(fd);
+ const st = fstatSync(fd, { bigint: true });
+ descriptor = {
+ ...descriptorIdentity(st),
+ digest: rawDigest(Buffer.from(data)),
+ length: Buffer.byteLength(data),
+ proof: temp,
+ };
+ } finally {
+ closeSync(fd);
+ }
}
fsyncDirectory(dirname(temp));
try {
@@ -443,10 +686,9 @@ function atomicWrite(path, data, written, onPrepared, modeBits = 0o600) {
} catch (error) {
throw error?.code === 'EEXIST' ? new Error('EXISTING_FILE_MISMATCH') : error;
} finally {
- if (!journaled) {
- rmSync(temp, { force: true });
- fsyncDirectory(dirname(temp));
- }
+ // Deterministic preparations are retained. If journal publication did not
+ // complete, the unbound owner-only inode is harmless recovery evidence.
+ if (!journaled) fsyncDirectory(dirname(temp));
}
}
function rendered(plan) {
@@ -498,6 +740,15 @@ function readReviewedPlan(path, expected) {
}
function configFor(plan) {
const p = plan.paths;
+ const {
+ trustSnapshot: _reviewedTrust,
+ recoverySnapshot: _reviewedRecovery,
+ provisionLockSnapshot: _reviewedProvisionLock,
+ transitionSnapshot: _reviewedTransition,
+ ...stableIntent
+ } = Object.fromEntries(
+ Object.entries(plan).filter(([key]) => !['digest', 'artifactDigests', 'intentDigest'].includes(key)),
+ );
return {
manifestPath: p.manifest,
approvalKeyPath: p.trust,
@@ -514,53 +765,179 @@ function configFor(plan) {
runtimeInventoryDigest: plan.inventoryDigest,
authoritativeConsumerInventoryPath: p['authoritative-consumer-inventory'],
authoritativeConsumerInventoryDigest: plan.consumerInventoryDigest,
- deploymentPlanDigest: plan.intentDigest,
+ deploymentPlanDigest: digest(stableIntent),
};
}
function journalPath(plan) {
return `${plan.paths.config}.provision-journal`;
}
-function writeProvisionJournal(plan, state) {
- const path = journalPath(plan);
- const temp = `${path}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
- mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
- const fd = openSync(temp, 'wx', 0o600);
- try {
- writeFileSync(fd, `${JSON.stringify(state, null, 2)}\n`);
- fsyncSync(fd);
- } finally {
- closeSync(fd);
- }
- renameSync(temp, path);
- fsyncDirectory(dirname(path));
+function journalTransitionPath(plan) {
+ return `${journalPath(plan)}.transition`;
}
-function readProvisionJournal(plan) {
- const path = journalPath(plan);
- if (!existsSync(path)) return null;
- validateExistingTarget(path, 'file');
- const state = json(path, 'INVALID_PROVISION_JOURNAL');
- const keys = Object.keys(state).sort();
+function provisionTargetPaths(paths) {
+ return new Set([
+ paths.manifest,
+ paths.trust,
+ paths.config,
+ paths['runtime-inventory'],
+ paths['authoritative-consumer-inventory'],
+ paths['linux-env'],
+ paths['macos-env'],
+ paths['linux-unit'],
+ paths['linux-token-feed-unit'],
+ paths['linux-refresh-unit'],
+ paths['macos-plist'],
+ ]);
+}
+function validateProvisionJournalState(state, paths, acceptedPlanDigests) {
+ const keys = Object.keys(state || {}).sort();
+ const allowed = provisionTargetPaths(paths);
if (
- keys.join(',') !== 'ownedTargets,phase,planDigest,version' ||
+ keys.join(',') !== 'operationId,ownedTargets,phase,planDigest,version' ||
state.version !== 1 ||
- state.planDigest !== plan.digest ||
+ !/^[a-f0-9]{32}$/.test(state.operationId || '') ||
+ !/^[a-f0-9]{64}$/.test(state.planDigest || '') ||
+ (acceptedPlanDigests && !acceptedPlanDigests.includes(state.planDigest)) ||
!['APPLYING', 'COMPLETE'].includes(state.phase) ||
!Array.isArray(state.ownedTargets) ||
state.ownedTargets.some(
(target) =>
!target ||
Object.keys(target).sort().join(',') !== 'birthtimeNs,dev,digest,ino,length,path,proof' ||
- typeof target.path !== 'string' ||
- typeof target.proof !== 'string' ||
+ !allowed.has(target.path) ||
+ target.proof !== `${target.path}.preparation-${target.digest}` ||
!/^[a-f0-9]{64}$/.test(target.digest) ||
!['birthtimeNs', 'dev', 'ino'].every((key) => /^\d+$/.test(target[key])) ||
!Number.isSafeInteger(target.length) ||
target.length < 0,
- )
+ ) ||
+ new Set(state.ownedTargets.map((target) => target.path)).size !== state.ownedTargets.length
)
fail('INVALID_PROVISION_JOURNAL');
+}
+function provisionRecoveryTopology(state) {
+ return state.ownedTargets.map((target) => {
+ if (!existsSync(target.proof) || !descriptorMatches(target.proof, target, 'PROVISION_RECOVERY_UNCERTAIN'))
+ fail('PROVISION_RECOVERY_UNCERTAIN');
+ const finalPresent = existsSync(target.path);
+ if (finalPresent && !descriptorMatches(target.path, target, 'PROVISION_RECOVERY_UNCERTAIN'))
+ fail('PROVISION_RECOVERY_UNCERTAIN');
+ const proofNlink = lstatSync(target.proof).nlink;
+ if (proofNlink !== (finalPresent ? 2 : 1)) fail('PROVISION_RECOVERY_UNCERTAIN');
+ return { path: target.path, finalPresent, proofNlink };
+ });
+}
+function writeProvisionJournal(plan, state) {
+ const path = journalPath(plan);
+ const bytes = Buffer.from(`${JSON.stringify(state, null, 2)}\n`);
+ const temp = `${path}.preparation-${rawDigest(bytes)}`;
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
+ let fd;
+ try {
+ fd = openSync(temp, 'wx', 0o600);
+ } catch (error) {
+ if (error?.code !== 'EEXIST') throw error;
+ }
+ if (fd !== undefined) {
+ try {
+ writeFileSync(fd, bytes);
+ fsyncSync(fd);
+ } finally {
+ closeSync(fd);
+ }
+ }
+ const descriptor = secureReadDescriptor(temp, 'INVALID_PROVISION_JOURNAL', false);
+ if (!descriptor.bytes.equals(bytes)) fail('INVALID_PROVISION_JOURNAL');
+ let prior = null;
+ if (existsSync(path)) {
+ prior = secureReadDescriptor(path, 'INVALID_PROVISION_JOURNAL', false);
+ if (!state.journalDescriptor || !descriptorEquals(prior, state.journalDescriptor))
+ fail('PROVISION_JOURNAL_OWNERSHIP_LOST');
+ if (descriptorEquals(prior, descriptor)) {
+ if (lstatSync(temp).nlink !== 2) fail('INVALID_PROVISION_JOURNAL');
+ fsyncDirectory(dirname(path));
+ Object.defineProperty(state, 'journalDescriptor', { value: descriptor, writable: true, configurable: true });
+ return;
+ }
+ if (lstatSync(temp).nlink !== 1) fail('INVALID_PROVISION_JOURNAL');
+ } else if (lstatSync(temp).nlink !== 1) fail('INVALID_PROVISION_JOURNAL');
+ const transitionPath = journalTransitionPath(plan);
+ const clean = (value) =>
+ value && Object.fromEntries(['dev', 'ino', 'birthtimeNs', 'digest', 'length'].map((key) => [key, value[key]]));
+ const transition = { version: 1, path, prior: clean(prior), next: clean(descriptor), nextProof: temp };
+ const transitionDescriptor = publishExclusiveRecord(
+ transitionPath,
+ `${canonicalJson(transition)}\n`,
+ 'INVALID_PROVISION_JOURNAL_TRANSITION',
+ );
+ if (prior) removeOwnedPath(path, prior, 'INVALID_PROVISION_JOURNAL');
+ linkSync(temp, path);
+ fsyncDirectory(dirname(path));
+ if (!descriptorMatches(path, descriptor, 'INVALID_PROVISION_JOURNAL')) fail('INVALID_PROVISION_JOURNAL');
+ removeOwnedPath(transitionPath, transitionDescriptor, 'INVALID_PROVISION_JOURNAL_TRANSITION');
+ Object.defineProperty(state, 'journalDescriptor', { value: descriptor, writable: true, configurable: true });
+}
+function recoverProvisionJournalTransition(plan) {
+ const path = journalTransitionPath(plan);
+ if (!existsSync(path)) return;
+ if (
+ !plan.transitionSnapshot ||
+ !descriptorMatches(path, plan.transitionSnapshot, 'INVALID_PROVISION_JOURNAL_TRANSITION')
+ )
+ fail('PROVISION_JOURNAL_TRANSITION_REVIEW_REQUIRED');
+ const descriptor = secureReadDescriptor(path, 'INVALID_PROVISION_JOURNAL_TRANSITION');
+ const transition = parseStrictJson(descriptor.bytes, 'INVALID_PROVISION_JOURNAL_TRANSITION');
+ if (
+ transition.version !== 1 ||
+ transition.path !== journalPath(plan) ||
+ transition.nextProof !== `${transition.path}.preparation-${transition.next?.digest}` ||
+ !descriptorMatches(transition.nextProof, transition.next, 'INVALID_PROVISION_JOURNAL_TRANSITION')
+ )
+ fail('INVALID_PROVISION_JOURNAL_TRANSITION');
+ if (existsSync(transition.path)) {
+ if (descriptorMatches(transition.path, transition.next, 'INVALID_PROVISION_JOURNAL_TRANSITION')) {
+ // already published
+ } else if (
+ transition.prior &&
+ descriptorMatches(transition.path, transition.prior, 'INVALID_PROVISION_JOURNAL_TRANSITION')
+ )
+ removeOwnedPath(transition.path, transition.prior, 'INVALID_PROVISION_JOURNAL_TRANSITION');
+ else fail('INVALID_PROVISION_JOURNAL_TRANSITION');
+ }
+ if (!existsSync(transition.path)) linkSync(transition.nextProof, transition.path);
+ fsyncDirectory(dirname(transition.path));
+ if (!descriptorMatches(transition.path, transition.next, 'INVALID_PROVISION_JOURNAL_TRANSITION'))
+ fail('INVALID_PROVISION_JOURNAL_TRANSITION');
+ removeOwnedPath(path, descriptor, 'INVALID_PROVISION_JOURNAL_TRANSITION');
+}
+function readProvisionJournal(plan) {
+ const path = journalPath(plan);
+ if (!existsSync(path)) return null;
+ if (!plan.recoverySnapshot) fail('PROVISION_JOURNAL_REVIEW_REQUIRED');
+ const descriptor = secureReadDescriptor(path, 'INVALID_PROVISION_JOURNAL');
+ if (!descriptorMatches(path, plan.recoverySnapshot, 'INVALID_PROVISION_JOURNAL')) fail('INVALID_PROVISION_JOURNAL');
+ let state;
+ try {
+ state = parseStrictJson(descriptor.bytes, 'INVALID_PROVISION_JOURNAL');
+ } catch {
+ fail('INVALID_PROVISION_JOURNAL');
+ }
+ validateProvisionJournalState(state, plan.paths, [plan.recoverySnapshot.planDigest]);
+ if (plan.recoverySnapshot?.state && canonicalJson(state) !== canonicalJson(plan.recoverySnapshot.state))
+ fail('INVALID_PROVISION_JOURNAL');
+ if (
+ plan.recoverySnapshot?.topology &&
+ canonicalJson(provisionRecoveryTopology(state)) !== canonicalJson(plan.recoverySnapshot.topology)
+ )
+ fail('PROVISION_RECOVERY_UNCERTAIN');
+ Object.defineProperty(state, 'journalDescriptor', { value: descriptor, writable: true, configurable: true });
return state;
}
+function removeProvisionJournal(plan, state) {
+ const descriptor = state?.journalDescriptor || plan.recoverySnapshot;
+ if (!descriptor) fail('PROVISION_RECOVERY_UNCERTAIN');
+ removeOwnedPath(journalPath(plan), descriptor, 'PROVISION_RECOVERY_UNCERTAIN');
+}
function cleanupOwned(plan, ownedTargets) {
const allowed = new Set([
plan.paths.manifest,
@@ -576,52 +953,53 @@ function cleanupOwned(plan, ownedTargets) {
if (!descriptorMatches(target.proof, target)) fail('PROVISION_RECOVERY_UNCERTAIN');
if (existsSync(target.path)) {
if (!descriptorMatches(target.path, target)) fail('PROVISION_RECOVERY_UNCERTAIN');
- rmSync(target.path);
+ removeOwnedPath(target.path, target);
}
- rmSync(target.proof);
+ removeOwnedPath(target.proof, target);
if (existsSync(dirname(target.path))) fsyncDirectory(dirname(target.path));
}
}
function applyReviewed(plan) {
const supplied = plan.digest;
+ let trust;
+ // Trust is the precondition for interpreting any mutable progress record.
+ if (plan.trustSnapshot?.state === 'absent') {
+ if (existsSync(journalPath(plan)) || existsSync(journalTransitionPath(plan)))
+ fail('BOOTSTRAP_JOURNAL_REVIEW_REQUIRED');
+ if (existsSync(plan.paths.trust)) fail('BOOTSTRAP_TRUST_REVIEW_REQUIRED');
+ } else trust = reviewedTrust(plan);
+ recoverProvisionJournalTransition(plan);
let state = readProvisionJournal(plan);
const resuming = Boolean(state);
if (state) {
for (const target of state.ownedTargets) {
- if (!existsSync(target.proof) && state.phase === 'COMPLETE') {
- if (!existsSync(target.path)) fail('PROVISION_RECOVERY_UNCERTAIN');
- if (!descriptorMatches(target.path, target)) fail('PROVISION_RECOVERY_UNCERTAIN');
- continue;
- }
if (!existsSync(target.proof)) fail('PROVISION_RECOVERY_UNCERTAIN');
if (!descriptorMatches(target.proof, target)) fail('PROVISION_RECOVERY_UNCERTAIN');
if (!existsSync(target.path)) {
cleanupOwned(plan, state.ownedTargets);
- rmSync(journalPath(plan), { force: true });
- fsyncDirectory(dirname(journalPath(plan)));
+ removeProvisionJournal(plan, state);
fail('PROVISION_RECOVERY_ROLLED_BACK');
}
if (!descriptorMatches(target.path, target)) fail('PROVISION_RECOVERY_UNCERTAIN');
}
if (state.phase === 'COMPLETE') {
for (const target of state.ownedTargets) {
- if (existsSync(target.proof)) {
- if (
- !descriptorMatches(target.proof, target) ||
- !existsSync(target.path) ||
- !descriptorMatches(target.path, target)
- )
- fail('PROVISION_RECOVERY_UNCERTAIN');
- unlinkSync(target.proof);
- if (process.env.CLAUDE_COORDINATION_TEST_SIGKILL_PROOF === target.proof) process.kill(process.pid, 'SIGKILL');
- } else {
- if (!existsSync(target.path) || !descriptorMatches(target.path, target)) fail('PROVISION_RECOVERY_UNCERTAIN');
- }
+ if (
+ !descriptorMatches(target.proof, target) ||
+ !existsSync(target.path) ||
+ !descriptorMatches(target.path, target)
+ )
+ fail('PROVISION_RECOVERY_UNCERTAIN');
+ if (
+ process.env.CLAUDE_COORDINATION_TESTING === '1' &&
+ process.env.CLAUDE_COORDINATION_TEST_SIGKILL_PROOF === target.proof
+ )
+ process.kill(process.pid, 'SIGKILL');
fsyncDirectory(dirname(target.proof));
}
preflight(plan.paths.config, plan.accounts, plan.paths, plan.inventoryDigest, plan);
- rmSync(journalPath(plan));
- fsyncDirectory(dirname(journalPath(plan)));
+ publishCompletionReceipt(plan, trust);
+ removeProvisionJournal(plan, state);
return { ok: true, digest: supplied, configPath: plan.paths.config };
}
}
@@ -655,6 +1033,7 @@ function applyReviewed(plan) {
newKeyBytes = randomBytes(32);
state = {
version: 1,
+ operationId: randomBytes(16).toString('hex'),
planDigest: plan.digest,
phase: 'APPLYING',
ownedTargets: [],
@@ -679,8 +1058,15 @@ function applyReviewed(plan) {
state.ownedTargets.push({ path, digest: rawDigest(bytes), ...descriptor });
writeProvisionJournal(plan, state);
});
- if (process.env.CLAUDE_COORDINATION_TEST_FAIL_AFTER === String(written.length)) fail('INJECTED_FAILURE');
- if (process.env.CLAUDE_COORDINATION_TEST_SIGKILL_AFTER === String(written.length))
+ if (
+ process.env.CLAUDE_COORDINATION_TESTING === '1' &&
+ process.env.CLAUDE_COORDINATION_TEST_FAIL_AFTER === String(written.length)
+ )
+ fail('INJECTED_FAILURE');
+ if (
+ process.env.CLAUDE_COORDINATION_TESTING === '1' &&
+ process.env.CLAUDE_COORDINATION_TEST_SIGKILL_AFTER === String(written.length)
+ )
process.kill(process.pid, 'SIGKILL');
};
publish(plan.paths.manifest, manifestBytes);
@@ -695,7 +1081,13 @@ function applyReviewed(plan) {
publish(plan.paths['runtime-inventory'], inventoryBytes);
publish(plan.paths['authoritative-consumer-inventory'], consumerInventoryBytes);
for (const [path, data] of Object.entries(generated)) publish(path, Buffer.from(data));
+ const priorJournalDescriptor = state.journalDescriptor;
state = { ...state, phase: 'COMPLETE' };
+ Object.defineProperty(state, 'journalDescriptor', {
+ value: priorJournalDescriptor,
+ writable: true,
+ configurable: true,
+ });
writeProvisionJournal(plan, state);
for (const target of state.ownedTargets) {
if (!descriptorMatches(target.proof, target) || !descriptorMatches(target.path, target))
@@ -703,44 +1095,63 @@ function applyReviewed(plan) {
}
let cleanedProofs = 0;
for (const target of state.ownedTargets) {
- unlinkSync(target.proof);
cleanedProofs += 1;
- if (process.env.CLAUDE_COORDINATION_TEST_SIGKILL_COMPLETE_PROOF_AFTER === String(cleanedProofs))
+ if (
+ process.env.CLAUDE_COORDINATION_TESTING === '1' &&
+ process.env.CLAUDE_COORDINATION_TEST_SIGKILL_COMPLETE_PROOF_AFTER === String(cleanedProofs)
+ )
process.kill(process.pid, 'SIGKILL');
}
for (const dir of new Set(state.ownedTargets.map((target) => dirname(target.proof)))) fsyncDirectory(dir);
preflight(plan.paths.config, plan.accounts, plan.paths, plan.inventoryDigest, plan);
- rmSync(journalPath(plan));
- fsyncDirectory(dirname(journalPath(plan)));
+ publishCompletionReceipt(plan, trust);
+ removeProvisionJournal(plan, state);
return { ok: true, digest: supplied, configPath: plan.paths.config };
} catch (error) {
if (state.phase === 'COMPLETE') throw error;
cleanupOwned(plan, state.ownedTargets);
- rmSync(journalPath(plan), { force: true });
- fsyncDirectory(dirname(journalPath(plan)));
+ removeProvisionJournal(plan, state);
throw error;
}
}
function apply(planPath, expected) {
const plan = readReviewedPlan(planPath, expected);
+ if (plan.trustSnapshot?.state === 'absent') {
+ if (existsSync(journalPath(plan)) || existsSync(journalTransitionPath(plan)))
+ fail('BOOTSTRAP_JOURNAL_REVIEW_REQUIRED');
+ if (existsSync(plan.paths.trust)) fail('BOOTSTRAP_TRUST_REVIEW_REQUIRED');
+ beginAbsentTrustBootstrap(plan);
+ }
return withProvisionLock(plan, () => applyReviewed(plan));
}
function rollbackReviewed(plan) {
+ recoverProvisionJournalTransition(plan);
const state = readProvisionJournal(plan);
if (!state) return { ok: true, rolledBack: false };
if (state.phase === 'COMPLETE') return applyReviewed(plan);
cleanupOwned(plan, state.ownedTargets);
- rmSync(journalPath(plan), { force: true });
- fsyncDirectory(dirname(journalPath(plan)));
+ removeProvisionJournal(plan, state);
return { ok: true, rolledBack: true, digest: plan.digest };
}
function rollback(planPath, expected) {
const plan = readReviewedPlan(planPath, expected);
- return withProvisionLock(plan, () => rollbackReviewed(plan));
+ if (plan.trustSnapshot?.state === 'absent') {
+ if (existsSync(bootstrapAttemptPath(plan))) fail('BOOTSTRAP_ATTEMPT_REVIEW_REQUIRED');
+ if (existsSync(journalPath(plan)) || existsSync(journalTransitionPath(plan)))
+ fail('BOOTSTRAP_JOURNAL_REVIEW_REQUIRED');
+ if (existsSync(plan.paths.trust)) fail('BOOTSTRAP_TRUST_REVIEW_REQUIRED');
+ }
+ return withProvisionLock(plan, () => {
+ if (plan.trustSnapshot?.state === 'present') reviewedTrust(plan);
+ return rollbackReviewed(plan);
+ });
}
function activateLinux(planPath, expected) {
const plan = readReviewedPlan(planPath, expected);
+ if (plan.trustSnapshot?.state !== 'present') fail('BOOTSTRAP_TRUST_REVIEW_REQUIRED');
return withProvisionLock(plan, () => {
+ const trust = reviewedTrust(plan);
+ validateCompletionReceipt(plan, trust);
preflight(plan.paths.config, plan.accounts, plan.paths, plan.inventoryDigest, plan);
const unitPath = plan.paths['linux-unit'];
const pinned = lstatSync(unitPath);
@@ -755,6 +1166,7 @@ function activateLinux(planPath, expected) {
fail('GENERATED_ARTIFACT_CHANGED');
};
const systemctl = (...args) => {
+ if (!descriptorMatches(plan.paths.trust, trust, 'TRUST_SNAPSHOT_CHANGED')) fail('TRUST_SNAPSHOT_CHANGED');
assertPinned();
const result = spawnSync('systemctl', ['--user', ...args], {
encoding: 'utf8',
@@ -804,7 +1216,7 @@ function preflight(configPath, accounts, expectedPaths, expectedInventoryDigest,
rawDigest(secureReadSource(configPath, 'CONFIG_ARTIFACT_MISMATCH')) !==
reviewedPlan.artifactDigests[configPath] ||
!readFileSync(configPath).equals(expectedConfig) ||
- config.deploymentPlanDigest !== reviewedPlan.intentDigest
+ config.deploymentPlanDigest !== configFor(reviewedPlan).deploymentPlanDigest
)
fail('CONFIG_ARTIFACT_MISMATCH');
for (const [path, expectedDigest] of Object.entries(reviewedPlan.artifactDigests))
diff --git a/claude-ops/scripts/account-rotation/staged-enrollment.mjs b/claude-ops/scripts/account-rotation/staged-enrollment.mjs
index 553cea09..99c451d7 100644
--- a/claude-ops/scripts/account-rotation/staged-enrollment.mjs
+++ b/claude-ops/scripts/account-rotation/staged-enrollment.mjs
@@ -13,9 +13,7 @@ import {
realpathSync,
readdirSync,
renameSync,
- rmSync,
statSync,
- unlinkSync,
writeFileSync,
} from 'node:fs';
import { createHash, createHmac, randomUUID, timingSafeEqual } from 'node:crypto';
@@ -362,12 +360,24 @@ function assertOwnerOnly(path, kind, allowLinks = false) {
st.isSymbolicLink() ||
st.uid !== process.getuid() ||
(st.mode & 0o077) !== 0 ||
- (kind === 'file' && !allowLinks && st.nlink !== 1)
+ (kind === 'file' && !allowLinks && st.nlink !== 1 && !hasBoundedPreparationAlias(path, st))
) {
throw new Error('INSECURE_TRUST_ROOT');
}
}
+function hasBoundedPreparationAlias(path, stat, bytes) {
+ if (!stat.isFile() || stat.nlink !== 2) return false;
+ try {
+ const digest = sha256(bytes ?? readFileSync(path));
+ const proof = `${path}.preparation-${digest}`;
+ const proofStat = lstatSync(proof);
+ return proofStat.isFile() && proofStat.dev === stat.dev && proofStat.ino === stat.ino && proofStat.nlink === 2;
+ } catch {
+ return false;
+ }
+}
+
function assertCanonicalExisting(path) {
const normalized = resolve(path);
let physical;
@@ -401,17 +411,27 @@ function secureReadDescriptor(path, requireSingleLink = true) {
fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW || 0));
const st = fstatSync(fd);
const big = fstatSync(fd, { bigint: true });
+ const bytes = readFileSync(fd);
+ const post = fstatSync(fd);
const fst = lstatSync(path);
if (
!st.isFile() ||
!fst.isFile() ||
st.dev !== fst.dev ||
st.ino !== fst.ino ||
- (requireSingleLink && st.nlink !== 1)
+ st.dev !== post.dev ||
+ st.ino !== post.ino ||
+ (requireSingleLink && st.nlink !== 1 && !hasBoundedPreparationAlias(path, st, bytes))
)
throw new Error();
- const bytes = readFileSync(fd);
- return { bytes, digest: sha256(bytes), dev: st.dev, ino: st.ino, birthtimeNs: big.birthtimeNs.toString() };
+ return {
+ bytes,
+ digest: sha256(bytes),
+ dev: st.dev,
+ ino: st.ino,
+ birthtimeNs: big.birthtimeNs.toString(),
+ nlink: st.nlink,
+ };
} catch {
throw new Error('INSECURE_TRUST_ROOT');
} finally {
@@ -430,12 +450,64 @@ function descriptorStillCurrent(path, descriptor) {
current.dev === descriptor.dev &&
current.ino === descriptor.ino &&
current.digest === descriptor.digest &&
+ current.nlink <= 2 &&
(!descriptor.birthtimeNs || current.birthtimeNs === descriptor.birthtimeNs)
);
} catch {
return false;
}
}
+
+function candidateTopologyCurrent(path, proof, descriptor) {
+ return (
+ existsSync(path) &&
+ existsSync(proof) &&
+ descriptorStillCurrent(path, descriptor) &&
+ descriptorStillCurrent(proof, descriptor) &&
+ lstatSync(path).nlink === 2 &&
+ lstatSync(proof).nlink === 2
+ );
+}
+
+function activeTargetTopologyCurrent(path, stagingDir, descriptor) {
+ const proof = `${join(stagingDir, basename(path))}.preparation-${descriptor.digest}`;
+ if (descriptor.nlink === 2) return candidateTopologyCurrent(path, proof, descriptor);
+ return (
+ descriptor.nlink === 1 &&
+ !existsSync(proof) &&
+ descriptorStillCurrent(path, descriptor) &&
+ lstatSync(path).nlink === 1
+ );
+}
+
+// Detach a name atomically before deciding whether its inode is ours. This is
+// deliberately rename-first: a pathname swap between a CAS and unlink(2)
+// otherwise lets an attacker make us delete an inode we never authenticated.
+// A foreign inode is retained under the private recovery name and never
+// unlinked; fail closed so an operator can inspect/reconcile it.
+function removeDescriptorSafely(path, descriptor, code = 'RECOVERY_UNCERTAIN') {
+ const evidenceDir = basename(path).length > 120 ? dirname(dirname(path)) : dirname(path);
+ const detached = join(evidenceDir, `.evidence-${sha256(path).slice(0, 16)}-${process.pid}-${randomUUID()}`);
+ try {
+ renameSync(path, detached);
+ } catch (error) {
+ if (error?.code === 'ENOENT') {
+ fsyncDirectory(dirname(path));
+ return false;
+ }
+ throw error;
+ }
+ if (!descriptorStillCurrent(detached, descriptor)) {
+ // The detached inode is evidence. Restoring the canonical name would
+ // reintroduce the pathname race that detach was intended to close.
+ fsyncDirectory(dirname(path));
+ throw new Error(code);
+ }
+ // Retain even authenticated cleanup as auditable evidence. A separate,
+ // operator-reviewed garbage collection pass may remove evidence later.
+ fsyncDirectory(dirname(path));
+ return true;
+}
function matchesDigest(path, digest, allowLinks = false) {
try {
return secureReadDescriptor(path, !allowLinks).digest === digest;
@@ -671,21 +743,12 @@ export function consumeApproval(payload, usageDir, keyPath) {
validateUseMarker(marker, keyPath, { approvalId: payload.id, nonce: payload.nonce, action: payload.action });
throw new Error('APPROVAL_REPLAY');
}
- const temp = join(usageDir, `.${basename(marker)}.${process.pid}.${randomUUID()}.tmp`);
- let fd;
- let linked = false;
+ const markerPayload = { version: 1, approvalId: payload.id, nonce: payload.nonce, action: payload.action };
+ const markerBytes = keyPath
+ ? `${canonicalJson(signedRecord(markerPayload, secureRead(keyPath)))}\n`
+ : `${payload.action}\n`;
try {
- fd = openSync(temp, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY, 0o600);
- const markerPayload = { version: 1, approvalId: payload.id, nonce: payload.nonce, action: payload.action };
- const markerBytes = keyPath
- ? `${canonicalJson(signedRecord(markerPayload, secureRead(keyPath)))}\n`
- : `${payload.action}\n`;
- writeFileSync(fd, markerBytes);
- fsyncSync(fd);
- closeSync(fd);
- fd = undefined;
- linkSync(temp, marker);
- linked = true;
+ durableExclusive(marker, markerBytes);
if (
process.env.CLAUDE_STAGED_ENROLLMENT_TESTING === '1' &&
process.env.CLAUDE_STAGED_ENROLLMENT_TEST_FAULT === 'SIGKILL:MARKER_LINK'
@@ -698,26 +761,11 @@ export function consumeApproval(payload, usageDir, keyPath) {
)
)
throw new Error('INJECTED_FAILURE');
- unlinkSync(temp);
- fsyncDirectory(usageDir);
} catch (error) {
- if (fd !== undefined) closeSync(fd);
- rmSync(temp, { force: true });
- if (linked) {
- try {
- if (
- process.env.CLAUDE_STAGED_ENROLLMENT_TESTING === '1' &&
- process.env.CLAUDE_STAGED_ENROLLMENT_TEST_FAULT === 'THROW:MARKER_CLEANUP_UNCERTAIN'
- )
- throw new Error('INJECTED_MARKER_CLEANUP_FAILURE');
- unlinkSync(marker);
- fsyncDirectory(usageDir);
- } catch {
- // The authenticated marker may be durable. Fail closed as consumed.
- throw new Error('APPROVAL_CONSUME_RECOVERY_REQUIRED');
- }
- }
if (error?.code === 'EEXIST') throw new Error('APPROVAL_REPLAY');
+ // Once the signed canonical marker may have been published it is
+ // authoritative. Never attempt deletion on a downstream failure.
+ if (existsSync(marker)) throw new Error('APPROVAL_CONSUME_RECOVERY_REQUIRED');
throw new Error('APPROVAL_CONSUME_FAILED');
}
}
@@ -733,32 +781,18 @@ function removeDurably(path, expectedDescriptor) {
process.env.CLAUDE_STAGED_ENROLLMENT_TEST_FAULT === 'THROW:PUBLICATION_CLEANUP_FSYNC'
)
throw new Error('PUBLICATION_RECOVERY_REQUIRED');
- if (existsSync(path)) {
- if (expectedDescriptor && !descriptorStillCurrent(path, expectedDescriptor))
- throw new Error('PUBLICATION_RECOVERY_UNCERTAIN');
- unlinkSync(path);
- }
- fsyncDirectory(dirname(path));
-}
-
-function removePublicationTempLink(path) {
- if (!existsSync(path)) return;
- const targetStat = lstatSync(path);
- if (!targetStat.isFile() || targetStat.nlink === 1) return;
- const prefix = `.${basename(path)}.`;
- const aliases = readdirSync(dirname(path)).filter((name) => {
- if (!name.startsWith(prefix) || !name.endsWith('.tmp')) return false;
- const stat = lstatSync(join(dirname(path), name));
- return stat.isFile() && stat.dev === targetStat.dev && stat.ino === targetStat.ino;
- });
- if (targetStat.nlink !== 2 || aliases.length !== 1) throw new Error('PUBLICATION_RECOVERY_UNCERTAIN');
- unlinkSync(join(dirname(path), aliases[0]));
- fsyncDirectory(dirname(path));
+ if (!expectedDescriptor) throw new Error('PUBLICATION_RECOVERY_UNCERTAIN');
+ removeDescriptorSafely(path, expectedDescriptor, 'PUBLICATION_RECOVERY_UNCERTAIN');
}
function recoverPublication(options) {
const path = publicationPath(options);
- if (!existsSync(path)) return false;
+ if (!existsSync(path)) {
+ // An unanchored filename pattern cannot authenticate a preparation inode.
+ // Leave orphan temps untouched unless an authenticated publication record
+ // names the exact expected proof.
+ return false;
+ }
const publicationDescriptor = secureReadDescriptor(path);
const record = verifySignedRecord(
publicationDescriptor.bytes,
@@ -784,10 +818,10 @@ function recoverPublication(options) {
assertCanonicalLeaf(record.markerPath);
if (!containsPath(options.stagingDir, record.stagedPath) || !containsPath(options.usageDir, record.markerPath))
throw new Error('INVALID_PUBLICATION_RECORD');
- if (!containsPath(options.stagingDir, record.stagedProof)) throw new Error('INVALID_PUBLICATION_RECORD');
- if (existsSync(record.stagedProof) && !descriptorStillCurrent(record.stagedProof, record.stagedDescriptor))
+ if (record.stagedProof !== `${record.stagedPath}.preparation-${record.stagingDigest}`)
+ throw new Error('INVALID_PUBLICATION_RECORD');
+ if (!existsSync(record.stagedProof) || !descriptorStillCurrent(record.stagedProof, record.stagedDescriptor))
throw new Error('PUBLICATION_RECOVERY_UNCERTAIN');
- removePublicationTempLink(record.markerPath);
const markerExists = existsSync(record.markerPath);
if (markerExists) {
validateUseMarker(record.markerPath, options.keyPath, {
@@ -797,21 +831,22 @@ function recoverPublication(options) {
});
// The durable use marker is authoritative evidence. Keep any successfully
// published staged bytes; absence means the operation rolled back consumed.
- if (existsSync(record.stagedPath) && !descriptorStillCurrent(record.stagedPath, record.stagedDescriptor))
+ if (
+ existsSync(record.stagedPath) &&
+ !candidateTopologyCurrent(record.stagedPath, record.stagedProof, record.stagedDescriptor)
+ )
throw new Error('PUBLICATION_RECOVERY_UNCERTAIN');
fsyncDirectory(options.usageDir);
if (existsSync(record.stagedPath)) fsyncDirectory(options.stagingDir);
} else if (existsSync(record.stagedPath)) {
if (!descriptorStillCurrent(record.stagedPath, record.stagedDescriptor))
throw new Error('PUBLICATION_RECOVERY_UNCERTAIN');
- unlinkSync(record.stagedPath);
- fsyncDirectory(options.stagingDir);
+ removeDescriptorSafely(record.stagedPath, record.stagedDescriptor, 'PUBLICATION_RECOVERY_UNCERTAIN');
}
- if (existsSync(record.stagedProof)) {
+ if (!markerExists && existsSync(record.stagedProof)) {
if (!descriptorStillCurrent(record.stagedProof, record.stagedDescriptor))
throw new Error('PUBLICATION_RECOVERY_UNCERTAIN');
- unlinkSync(record.stagedProof);
- fsyncDirectory(options.stagingDir);
+ removeDescriptorSafely(record.stagedProof, record.stagedDescriptor, 'PUBLICATION_RECOVERY_UNCERTAIN');
}
if (!markerExists) fsyncDirectory(options.usageDir);
removeDurably(path, publicationDescriptor);
@@ -894,7 +929,14 @@ export function assertNoIdentityConflicts({ entry, activeDir, quarantineDirs, st
if (candidatePath && resolve(path) === resolve(candidatePath)) continue;
let value;
try {
- value = parseStrictJson(secureRead(path), 'MALFORMED_INVENTORY');
+ if (kind === 'active') {
+ const descriptor = secureReadDescriptor(path, false);
+ if (descriptor.nlink === 2) {
+ const proof = `${join(stagingDir, basename(path))}.preparation-${descriptor.digest}`;
+ if (!candidateTopologyCurrent(path, proof, descriptor)) throw new Error();
+ } else if (descriptor.nlink !== 1) throw new Error();
+ value = parseStrictJson(descriptor.bytes, 'MALFORMED_INVENTORY');
+ } else value = parseStrictJson(secureRead(path), 'MALFORMED_INVENTORY');
} catch {
throw new Error('MALFORMED_INVENTORY');
}
@@ -1037,14 +1079,69 @@ function verifySignedRecord(bytes, key, kind) {
}
function durableExclusive(path, bytes) {
- const fd = openSync(path, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY, 0o600);
+ bytes = Buffer.from(bytes);
+ const temp = `${path}.preparation-${sha256(bytes)}`;
+ let descriptor;
+ let fd;
try {
- writeFileSync(fd, bytes);
- fsyncSync(fd);
- } finally {
- closeSync(fd);
+ fd = openSync(temp, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY, 0o600);
+ } catch (error) {
+ if (error?.code !== 'EEXIST') throw error;
}
- fsyncDirectory(dirname(path));
+ if (fd === undefined) {
+ descriptor = secureReadDescriptor(temp, false);
+ if (!descriptor.bytes.equals(bytes)) throw new Error('PUBLICATION_RECOVERY_UNCERTAIN');
+ } else {
+ try {
+ writeFileSync(fd, bytes);
+ fsyncSync(fd);
+ const st = fstatSync(fd);
+ const big = fstatSync(fd, { bigint: true });
+ descriptor = { bytes, digest: sha256(bytes), dev: st.dev, ino: st.ino, birthtimeNs: big.birthtimeNs.toString() };
+ } finally {
+ closeSync(fd);
+ }
+ fsyncDirectory(dirname(path));
+ if (!descriptorStillCurrent(temp, descriptor)) throw new Error('PUBLICATION_RECOVERY_UNCERTAIN');
+ }
+ if (
+ path.endsWith('.publication') &&
+ process.env.CLAUDE_STAGED_ENROLLMENT_TESTING === '1' &&
+ process.env.CLAUDE_STAGED_ENROLLMENT_TEST_FAULT === 'SIGKILL:PUBLICATION_BEFORE_LINK'
+ )
+ process.kill(process.pid, 'SIGKILL');
+ try {
+ if (existsSync(path)) {
+ if (!descriptorStillCurrent(path, descriptor)) {
+ const error = new Error('EEXIST');
+ error.code = 'EEXIST';
+ throw error;
+ }
+ } else linkSync(temp, path);
+ if (
+ path.endsWith('.publication') &&
+ process.env.CLAUDE_STAGED_ENROLLMENT_TESTING === '1' &&
+ process.env.CLAUDE_STAGED_ENROLLMENT_TEST_FAULT === 'SIGKILL:PUBLICATION_LINK'
+ )
+ process.kill(process.pid, 'SIGKILL');
+ fsyncDirectory(dirname(path));
+ if (!descriptorStillCurrent(path, descriptor)) throw new Error('PUBLICATION_RECOVERY_UNCERTAIN');
+ if (
+ path.endsWith('.publication') &&
+ process.env.CLAUDE_STAGED_ENROLLMENT_TESTING === '1' &&
+ process.env.CLAUDE_STAGED_ENROLLMENT_TEST_FAULT === 'SIGKILL:PUBLICATION_DIR_FSYNC'
+ )
+ process.kill(process.pid, 'SIGKILL');
+ if (
+ path.endsWith('.publication') &&
+ process.env.CLAUDE_STAGED_ENROLLMENT_TESTING === '1' &&
+ process.env.CLAUDE_STAGED_ENROLLMENT_TEST_FAULT === 'SIGKILL:PUBLICATION_CLEANUP'
+ )
+ process.kill(process.pid, 'SIGKILL');
+ } catch (error) {
+ throw error;
+ }
+ return descriptor;
}
function pidAlive(pid) {
@@ -1086,15 +1183,16 @@ function acquireRecoveryClaim(claim, holder, key) {
});
let mine = claimPayload();
try {
- durableExclusive(claim, `${canonicalJson(signedRecord(mine, key))}\n`);
- return mine;
+ const descriptor = durableExclusive(claim, `${canonicalJson(signedRecord(mine, key))}\n`);
+ return { payload: mine, descriptor };
} catch (error) {
if (error?.code !== 'EEXIST') throw new Error('OPERATION_LOCKED');
}
let stale;
try {
assertOwnerOnly(claim, 'file');
- stale = verifySignedRecord(secureRead(claim), key, 'RECOVERY_CLAIM_MALFORMED');
+ const staleDescriptor = secureReadDescriptor(claim);
+ stale = verifySignedRecord(staleDescriptor.bytes, key, 'RECOVERY_CLAIM_MALFORMED');
exactKeys(stale, ['version', 'host', 'pid', 'nonce', 'lockNonce', 'createdAt']);
// Authenticate and validate the claimant independently from the lock it
// originally observed. A dead same-host claimant can outlive that lock;
@@ -1103,13 +1201,11 @@ function acquireRecoveryClaim(claim, holder, key) {
if (typeof stale.lockNonce !== 'string' || !/^[A-Za-z0-9_-]{8,128}$/.test(stale.lockNonce))
throw new Error('RECOVERY_CLAIM_MALFORMED');
if (stale.host !== hostname() || pidAlive(stale.pid)) throw new Error('OPERATION_LOCKED');
- const current = verifySignedRecord(secureRead(claim), key, 'RECOVERY_CLAIM_MALFORMED');
- if (canonicalJson(current) !== canonicalJson(stale)) throw new Error('OPERATION_LOCKED');
- unlinkSync(claim);
- fsyncDirectory(dirname(claim));
+ if (!descriptorStillCurrent(claim, staleDescriptor)) throw new Error('OPERATION_LOCKED');
+ removeDescriptorSafely(claim, staleDescriptor, 'OPERATION_LOCKED');
mine = claimPayload();
- durableExclusive(claim, `${canonicalJson(signedRecord(mine, key))}\n`);
- return mine;
+ const descriptor = durableExclusive(claim, `${canonicalJson(signedRecord(mine, key))}\n`);
+ return { payload: mine, descriptor };
} catch (claimError) {
if (claimError?.message === 'RECOVERY_CLAIM_MALFORMED') throw claimError;
throw new Error('OPERATION_LOCKED');
@@ -1117,10 +1213,9 @@ function acquireRecoveryClaim(claim, holder, key) {
}
function removeOwnedRecoveryClaim(claim, ownedClaim, key) {
- const current = verifySignedRecord(secureRead(claim), key, 'RECOVERY_CLAIM_MALFORMED');
- if (canonicalJson(current) !== canonicalJson(ownedClaim)) throw new Error('OPERATION_LOCKED');
- unlinkSync(claim);
- fsyncDirectory(dirname(claim));
+ const current = verifySignedRecord(ownedClaim.descriptor.bytes, key, 'RECOVERY_CLAIM_MALFORMED');
+ if (canonicalJson(current) !== canonicalJson(ownedClaim.payload)) throw new Error('OPERATION_LOCKED');
+ removeDescriptorSafely(claim, ownedClaim.descriptor, 'OPERATION_LOCKED');
}
export function withOperationLock(path, keyPath, callback, { allowJournal = false, allowPublication = false } = {}) {
@@ -1128,8 +1223,10 @@ export function withOperationLock(path, keyPath, callback, { allowJournal = fals
assertCanonicalLeaf(path);
const key = secureRead(keyPath);
const journal = `${path}.journal`;
+ const journalTransition = `${journal}.transition`;
const publication = `${path}.publication`;
- if (!allowJournal && existsSync(journal)) throw new Error('PENDING_ACTIVATION_JOURNAL');
+ if (!allowJournal && (existsSync(journal) || existsSync(journalTransition)))
+ throw new Error('PENDING_ACTIVATION_JOURNAL');
if (!allowPublication && existsSync(publication)) throw new Error('PENDING_APPROVAL_PUBLICATION');
const metadata = {
version: 1,
@@ -1138,14 +1235,17 @@ export function withOperationLock(path, keyPath, callback, { allowJournal = fals
nonce: randomUUID(),
createdAt: new Date().toISOString(),
};
+ let ownedLockDescriptor;
try {
- durableExclusive(path, `${canonicalJson(signedRecord(metadata, key))}\n`);
+ ownedLockDescriptor = durableExclusive(path, `${canonicalJson(signedRecord(metadata, key))}\n`);
} catch (error) {
if (error?.code !== 'EEXIST') throw new Error('OPERATION_LOCKED');
let holder;
+ let holderDescriptor;
try {
assertOwnerOnly(path, 'file');
- holder = verifySignedRecord(secureRead(path), key, 'OPERATION_LOCKED_MALFORMED');
+ holderDescriptor = secureReadDescriptor(path);
+ holder = verifySignedRecord(holderDescriptor.bytes, key, 'OPERATION_LOCKED_MALFORMED');
exactKeys(holder, ['version', 'host', 'pid', 'nonce', 'createdAt']);
validateProcessRecord(holder, 'OPERATION_LOCKED_MALFORMED');
} catch (verifyError) {
@@ -1158,10 +1258,8 @@ export function withOperationLock(path, keyPath, callback, { allowJournal = fals
const ownedClaim = acquireRecoveryClaim(claim, holder, key);
let claimRemoved = false;
try {
- const current = verifySignedRecord(secureRead(path), key, 'OPERATION_LOCKED_MALFORMED');
- if (canonicalJson(current) !== canonicalJson(holder)) throw new Error('OPERATION_LOCKED');
- unlinkSync(path);
- fsyncDirectory(dirname(path));
+ if (!descriptorStillCurrent(path, holderDescriptor)) throw new Error('OPERATION_LOCKED');
+ removeDescriptorSafely(path, holderDescriptor, 'OPERATION_LOCKED');
if (
process.env.CLAUDE_STAGED_ENROLLMENT_TESTING === '1' &&
process.env.CLAUDE_STAGED_ENROLLMENT_TEST_FAULT === 'SIGKILL:OLD_LOCK_UNLINKED'
@@ -1173,7 +1271,7 @@ export function withOperationLock(path, keyPath, callback, { allowJournal = fals
removeOwnedRecoveryClaim(claim, ownedClaim, key);
claimRemoved = true;
try {
- durableExclusive(path, `${canonicalJson(signedRecord(metadata, key))}\n`);
+ ownedLockDescriptor = durableExclusive(path, `${canonicalJson(signedRecord(metadata, key))}\n`);
} catch (publishError) {
if (publishError?.code === 'EEXIST') throw new Error('OPERATION_LOCKED');
throw publishError;
@@ -1199,20 +1297,14 @@ export function withOperationLock(path, keyPath, callback, { allowJournal = fals
}
}
const release = () => {
- try {
- const current = verifySignedRecord(secureRead(path), key, 'OPERATION_LOCKED_MALFORMED');
- if (current.nonce === metadata.nonce) {
- unlinkSync(path);
- fsyncDirectory(dirname(path));
- }
- } catch {
- // Never remove a lock whose ownership can no longer be demonstrated.
- }
+ const current = verifySignedRecord(ownedLockDescriptor.bytes, key, 'OPERATION_LOCKED_MALFORMED');
+ if (current.nonce !== metadata.nonce) throw new Error('OPERATION_LOCKED');
+ if (!removeDescriptorSafely(path, ownedLockDescriptor, 'OPERATION_LOCKED')) throw new Error('OPERATION_LOCKED');
};
// The preflight check is only an optimization. Ownership is the
// synchronization point: crash state may be published while this process is
// waiting or reclaiming a stale lock.
- if (!allowJournal && existsSync(journal)) {
+ if (!allowJournal && (existsSync(journal) || existsSync(journalTransition))) {
release();
throw new Error('PENDING_ACTIVATION_JOURNAL');
}
@@ -1293,17 +1385,35 @@ function readArtifact(path) {
}
function publishNoReplace(path, bytes, onPrepared) {
- const temp = join(dirname(path), `.${basename(path)}.${process.pid}.${randomUUID()}.tmp`);
- let fd = openSync(temp, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY, 0o600);
+ const temp = `${path}.preparation-${sha256(bytes)}`;
+ let fd;
+ try {
+ fd = openSync(temp, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY, 0o600);
+ } catch (error) {
+ if (error?.code !== 'EEXIST') throw error;
+ }
let linked = false;
let prepared;
try {
- writeFileSync(fd, bytes);
- fsyncSync(fd);
- closeSync(fd);
- fd = undefined;
+ if (fd !== undefined) {
+ writeFileSync(fd, bytes);
+ fsyncSync(fd);
+ const st = fstatSync(fd);
+ const big = fstatSync(fd, { bigint: true });
+ prepared = {
+ bytes: Buffer.from(bytes),
+ digest: sha256(bytes),
+ dev: st.dev,
+ ino: st.ino,
+ birthtimeNs: big.birthtimeNs.toString(),
+ };
+ closeSync(fd);
+ fd = undefined;
+ }
fsyncDirectory(dirname(path));
- prepared = secureReadDescriptor(temp);
+ prepared ??= secureReadDescriptor(temp, false);
+ if (!descriptorStillCurrent(temp, prepared)) throw new Error('STAGE_PUBLICATION_RECOVERY_REQUIRED');
+ if (!prepared.bytes.equals(Buffer.from(bytes))) throw new Error('STAGE_PUBLICATION_RECOVERY_REQUIRED');
onPrepared({ ...prepared, proof: temp });
linkSync(temp, path);
linked = true;
@@ -1319,32 +1429,15 @@ function publishNoReplace(path, bytes, onPrepared) {
throw new Error('INJECTED_FAILURE');
if (!descriptorStillCurrent(temp, prepared) || !descriptorStillCurrent(path, prepared))
throw new Error('STAGE_PUBLICATION_RECOVERY_REQUIRED');
- unlinkSync(temp);
- fsyncDirectory(dirname(path));
} catch (error) {
if (linked && (!prepared || !descriptorStillCurrent(temp, prepared) || !descriptorStillCurrent(path, prepared)))
throw new Error('STAGE_PUBLICATION_RECOVERY_REQUIRED');
- if (existsSync(temp)) {
- let owned = false;
- if (prepared) owned = descriptorStillCurrent(temp, prepared);
- else if (fd !== undefined) {
- const opened = fstatSync(fd);
- const openedBig = fstatSync(fd, { bigint: true });
- const named = lstatSync(temp);
- owned =
- opened.dev === named.dev &&
- opened.ino === named.ino &&
- openedBig.birthtimeNs.toString() === statSync(temp, { bigint: true }).birthtimeNs.toString();
- }
- if (!owned) throw new Error('STAGE_PUBLICATION_RECOVERY_REQUIRED');
- unlinkSync(temp);
- fsyncDirectory(dirname(temp));
- }
+ if (existsSync(temp) && prepared && !descriptorStillCurrent(temp, prepared))
+ throw new Error('STAGE_PUBLICATION_RECOVERY_REQUIRED');
if (fd !== undefined) closeSync(fd);
if (linked) {
try {
- unlinkSync(path);
- fsyncDirectory(dirname(path));
+ removeDescriptorSafely(path, prepared, 'STAGE_PUBLICATION_RECOVERY_REQUIRED');
} catch {
throw new Error('STAGE_PUBLICATION_RECOVERY_REQUIRED');
}
@@ -1415,8 +1508,7 @@ export function stageEnrollment(options) {
// evidence or an unauthorised staged candidate behind.
try {
if (!stagedDescriptor || !descriptorStillCurrent(stagedPath, stagedDescriptor)) throw new Error();
- unlinkSync(stagedPath);
- fsyncDirectory(options.stagingDir);
+ removeDescriptorSafely(stagedPath, stagedDescriptor, 'PUBLICATION_RECOVERY_REQUIRED');
} catch {
throw new Error('PUBLICATION_RECOVERY_REQUIRED');
}
@@ -1447,7 +1539,7 @@ function replaceAndFsync(stagedPath, target, stagingDir, activeDir, injectFailur
fsyncDirectory(activeDir);
}
-function restoreBackup(backup, target, activeDir, _restorePath, expectedDescriptor, expectedDigest) {
+function restoreBackup(backup, target, activeDir, restorePath, expectedDescriptor, expectedDigest) {
const source = secureReadDescriptor(backup, false);
if (
!expectedDescriptor ||
@@ -1458,7 +1550,13 @@ function restoreBackup(backup, target, activeDir, _restorePath, expectedDescript
)
throw new Error('INVALID_ACTIVATION_BACKUP');
if (!existsSync(target)) {
- linkSync(backup, target);
+ if (restorePath) {
+ if (existsSync(restorePath)) throw new Error('INVALID_ACTIVATION_RESTORE');
+ renameSync(backup, restorePath);
+ fsyncDirectory(dirname(backup));
+ fsyncDirectory(dirname(restorePath));
+ linkSync(restorePath, target);
+ } else linkSync(backup, target);
fsyncDirectory(activeDir);
}
const restore = secureReadDescriptor(target, false);
@@ -1474,17 +1572,17 @@ function restoreBackup(backup, target, activeDir, _restorePath, expectedDescript
process.env.CLAUDE_STAGED_ENROLLMENT_TEST_FAULT === 'SIGKILL:RESTORE_TEMP_FSYNCED'
)
process.kill(process.pid, 'SIGKILL');
- if (existsSync(backup)) {
+ if (!restorePath && existsSync(backup)) {
if (!descriptorStillCurrent(backup, expectedDescriptor) || !descriptorStillCurrent(target, expectedDescriptor))
throw new Error('INVALID_ACTIVATION_BACKUP');
- unlinkSync(backup);
- fsyncDirectory(dirname(backup));
+ removeDescriptorSafely(backup, expectedDescriptor, 'INVALID_ACTIVATION_BACKUP');
}
if (!descriptorStillCurrent(target, expectedDescriptor)) throw new Error('INVALID_ACTIVATION_BACKUP');
}
-function validateExistingTarget(path, entry) {
- const descriptor = secureReadDescriptor(path);
+function validateExistingTarget(path, entry, stagingDir) {
+ const descriptor = secureReadDescriptor(path, false);
+ if (!activeTargetTopologyCurrent(path, stagingDir, descriptor)) throw new Error('INVALID_ACTIVE_TARGET');
try {
// Existing active credentials may be expired, but otherwise must satisfy
// the same exact schema and structural checks as a staging candidate.
@@ -1500,6 +1598,10 @@ function journalPath(options) {
return `${options.operationLockPath}.journal`;
}
+function journalTransitionPath(options) {
+ return `${journalPath(options)}.transition`;
+}
+
function rollbackRecordPath(options, entry) {
return join(options.rollbackDir, `${entry.authFilename}.committed-rollback.json`);
}
@@ -1523,17 +1625,63 @@ function writeJournal(options, state, phase) {
const path = journalPath(options);
const key = secureRead(options.keyPath);
const next = { ...state, phase };
- const temp = `${path}.${process.pid}.${randomUUID()}.tmp`;
const bytes = `${canonicalJson(signedRecord(next, key))}\n`;
- let fd = openSync(temp, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY, 0o600);
+ const temp = `${path}.preparation-${sha256(Buffer.from(bytes))}`;
+ let fd;
+ try {
+ fd = openSync(temp, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY, 0o600);
+ } catch (error) {
+ if (error?.code !== 'EEXIST') throw error;
+ }
let published = false;
+ let prepared;
try {
- writeFileSync(fd, bytes);
- fsyncSync(fd);
- closeSync(fd);
- fd = undefined;
- renameSync(temp, path);
- published = true;
+ if (fd !== undefined) {
+ writeFileSync(fd, bytes);
+ fsyncSync(fd);
+ const st = fstatSync(fd);
+ const big = fstatSync(fd, { bigint: true });
+ prepared = {
+ bytes: Buffer.from(bytes),
+ digest: sha256(bytes),
+ dev: st.dev,
+ ino: st.ino,
+ birthtimeNs: big.birthtimeNs.toString(),
+ };
+ closeSync(fd);
+ fd = undefined;
+ }
+ prepared ??= secureReadDescriptor(temp, false);
+ if (!descriptorStillCurrent(temp, prepared)) throw new Error('ACTIVATION_RECOVERY_REQUIRED');
+ if (!prepared.bytes.equals(Buffer.from(bytes))) throw new Error('ACTIVATION_RECOVERY_REQUIRED');
+ let prior = null;
+ if (existsSync(path)) {
+ prior = secureReadDescriptor(path, false);
+ if (!state.journalDescriptor || !descriptorStillCurrent(path, state.journalDescriptor))
+ throw new Error('ACTIVATION_RECOVERY_REQUIRED');
+ if (descriptorStillCurrent(path, prepared)) {
+ if (lstatSync(temp).nlink !== 2) throw new Error('ACTIVATION_RECOVERY_REQUIRED');
+ published = true;
+ } else {
+ if (lstatSync(temp).nlink !== 1) throw new Error('ACTIVATION_RECOVERY_REQUIRED');
+ }
+ } else if (lstatSync(temp).nlink !== 1) throw new Error('ACTIVATION_RECOVERY_REQUIRED');
+ if (!published) {
+ const clean = (value) =>
+ value && Object.fromEntries(['dev', 'ino', 'birthtimeNs', 'digest'].map((field) => [field, value[field]]));
+ const transition = { version: 1, path, prior: clean(prior), next: clean(prepared), nextProof: temp };
+ const transitionPath = journalTransitionPath(options);
+ const transitionDescriptor = durableExclusive(
+ transitionPath,
+ `${canonicalJson(signedRecord(transition, key))}\n`,
+ );
+ if (prior) removeDescriptorSafely(path, prior, 'ACTIVATION_RECOVERY_REQUIRED');
+ linkSync(temp, path);
+ published = true;
+ fsyncDirectory(dirname(path));
+ if (!descriptorStillCurrent(path, prepared)) throw new Error('ACTIVATION_RECOVERY_REQUIRED');
+ removeDescriptorSafely(transitionPath, transitionDescriptor, 'ACTIVATION_RECOVERY_REQUIRED');
+ }
if (
process.env.CLAUDE_STAGED_ENROLLMENT_TESTING === '1' &&
process.env.CLAUDE_STAGED_ENROLLMENT_TEST_FAULT === `THROW:JOURNAL_FSYNC:${phase}`
@@ -1545,7 +1693,6 @@ function writeJournal(options, state, phase) {
throw error;
} finally {
if (fd !== undefined) closeSync(fd);
- rmSync(temp, { force: true });
}
if (
process.env.CLAUDE_STAGED_ENROLLMENT_TESTING === '1' &&
@@ -1557,11 +1704,42 @@ function writeJournal(options, state, phase) {
process.env.CLAUDE_STAGED_ENROLLMENT_TEST_FAULT === `SIGSTOP:${phase}`
)
process.kill(process.pid, 'SIGSTOP');
+ Object.defineProperty(next, 'journalDescriptor', { value: prepared, writable: true, configurable: true });
return next;
}
+function recoverJournalTransition(options) {
+ const transitionPath = journalTransitionPath(options);
+ if (!existsSync(transitionPath)) return;
+ const key = secureRead(options.keyPath);
+ const transitionDescriptor = secureReadDescriptor(transitionPath);
+ const transition = verifySignedRecord(transitionDescriptor.bytes, key, 'INVALID_ACTIVATION_JOURNAL_TRANSITION');
+ exactKeys(transition, ['version', 'path', 'prior', 'next', 'nextProof']);
+ const path = journalPath(options);
+ if (
+ transition.version !== 1 ||
+ transition.path !== path ||
+ transition.nextProof !== `${path}.preparation-${transition.next?.digest}` ||
+ !descriptorStillCurrent(transition.nextProof, transition.next)
+ )
+ throw new Error('INVALID_ACTIVATION_JOURNAL_TRANSITION');
+ if (existsSync(path)) {
+ if (descriptorStillCurrent(path, transition.next)) {
+ // already published
+ } else if (transition.prior && descriptorStillCurrent(path, transition.prior))
+ removeDescriptorSafely(path, transition.prior, 'ACTIVATION_RECOVERY_REQUIRED');
+ else throw new Error('ACTIVATION_RECOVERY_REQUIRED');
+ }
+ if (!existsSync(path)) linkSync(transition.nextProof, path);
+ fsyncDirectory(dirname(path));
+ if (!descriptorStillCurrent(path, transition.next)) throw new Error('ACTIVATION_RECOVERY_REQUIRED');
+ removeDescriptorSafely(transitionPath, transitionDescriptor, 'ACTIVATION_RECOVERY_REQUIRED');
+}
+
function removeJournal(options) {
- unlinkSync(journalPath(options));
+ const path = journalPath(options);
+ const descriptor = secureReadDescriptor(path, false);
+ removeDescriptorSafely(path, descriptor, 'ACTIVATION_RECOVERY_REQUIRED');
fsyncDirectory(dirname(journalPath(options)));
}
@@ -1574,13 +1752,25 @@ function removeCommittedBackup(state) {
// recorded in the journal.
if (!state.hadTarget || !state.backupDescriptor || !descriptorStillCurrent(state.backup, state.backupDescriptor))
throw new Error('INVALID_ACTIVATION_BACKUP');
- unlinkSync(state.backup);
+ removeDescriptorSafely(state.backup, state.backupDescriptor, 'INVALID_ACTIVATION_BACKUP');
}
// Always prove cleanup durable, including the already-absent case.
fsyncDirectory(dirname(state.backup));
}
function removePreparingBackup(state) {
+ if (state.restorePath) {
+ if (existsSync(state.backup)) {
+ if (existsSync(state.restorePath) || !descriptorStillCurrent(state.backup, state.backupDescriptor))
+ throw new Error('ACTIVATION_RECOVERY_UNCERTAIN');
+ renameSync(state.backup, state.restorePath);
+ fsyncDirectory(dirname(state.backup));
+ fsyncDirectory(dirname(state.restorePath));
+ }
+ if (!descriptorStillCurrent(state.restorePath, state.backupDescriptor))
+ throw new Error('ACTIVATION_RECOVERY_UNCERTAIN');
+ return;
+ }
if (existsSync(state.backup)) {
if (!state.hadTarget) throw new Error('ACTIVATION_RECOVERY_UNCERTAIN');
assertCanonicalExisting(state.backup);
@@ -1589,7 +1779,7 @@ function removePreparingBackup(state) {
if (!descriptorStillCurrent(state.backup, state.backupDescriptor))
throw new Error('ACTIVATION_RECOVERY_UNCERTAIN');
} else throw new Error('ACTIVATION_RECOVERY_UNCERTAIN');
- unlinkSync(state.backup);
+ removeDescriptorSafely(state.backup, state.backupDescriptor, 'ACTIVATION_RECOVERY_UNCERTAIN');
}
if (
process.env.CLAUDE_STAGED_ENROLLMENT_TESTING === '1' &&
@@ -1629,10 +1819,12 @@ export function activateEnrollment(options) {
const hadTarget = existsSync(target);
let oldDigest = null;
let oldTarget = null;
+ let restorePath = null;
if (hadTarget) {
- assertOwnerOnly(target, 'file');
- oldTarget = validateExistingTarget(target, entry);
+ oldTarget = validateExistingTarget(target, entry, options.stagingDir);
oldDigest = oldTarget.digest;
+ if (oldTarget.nlink === 2)
+ restorePath = `${join(options.stagingDir, entry.authFilename)}.preparation-${oldDigest}`;
}
const authoritativeConsumers = readAuthoritativeConsumers(options, entry);
const inventory = readSwitchEvidence(
@@ -1684,14 +1876,18 @@ export function activateEnrollment(options) {
if (readManifest(options.manifestPath).digest !== initial.digest) throw new Error('MANIFEST_CAS_FAILED');
if (options.injectFailure === 'before-rename') throw new Error('INJECTED_FAILURE');
if (readManifest(options.manifestPath).digest !== initial.digest) throw new Error('MANIFEST_CAS_FAILED');
- if (!descriptorStillCurrent(stagedPath, candidateDescriptor)) throw new Error('CANDIDATE_CAS_FAILED');
+ const candidateProof = `${stagedPath}.preparation-${candidateDigest}`;
+ if (!candidateTopologyCurrent(stagedPath, candidateProof, candidateDescriptor))
+ throw new Error('CANDIDATE_CAS_FAILED');
if (!descriptorStillCurrent(inventory.path, inventory.descriptor)) throw new Error('INVENTORY_CAS_FAILED');
if (!descriptorStillCurrent(canary.path, canary.descriptor)) throw new Error('CANARY_CAS_FAILED');
- if (existsSync(target) !== hadTarget || (hadTarget && !descriptorStillCurrent(target, oldTarget)))
+ if (
+ existsSync(target) !== hadTarget ||
+ (hadTarget && !activeTargetTopologyCurrent(target, options.stagingDir, oldTarget))
+ )
throw new Error('ACTIVE_TARGET_CAS_FAILED');
const backupName = `${entry.authFilename}.${payload.id}.${payload.nonce}.${candidateDigest}.${oldDigest || 'none'}.bak`;
const backup = join(options.rollbackDir, backupName);
- const restorePath = null;
validatePathTopology({
configPath: options.configPath,
config: {
@@ -1709,7 +1905,7 @@ export function activateEnrollment(options) {
approvalId: payload,
computedPaths: [
['backup target', backup, options.rollbackDir, true],
- ...(restorePath ? [['restore target', restorePath, options.activeDir, true]] : []),
+ ...(restorePath ? [['restore target', restorePath, options.stagingDir, true]] : []),
],
});
let journal = {
@@ -1753,7 +1949,17 @@ export function activateEnrollment(options) {
// hardlink publication means recovery never has to infer ownership from
// a pathname or digest-only partial copy.
journal = writeJournal(options, journal, 'BACKUP_CREATE_INTENT');
- linkSync(target, backup);
+ if (!activeTargetTopologyCurrent(target, options.stagingDir, oldTarget))
+ throw new Error('ACTIVE_TARGET_CAS_FAILED');
+ if (restorePath) renameSync(restorePath, backup);
+ else linkSync(target, backup);
+ if (
+ !descriptorStillCurrent(target, oldTarget) ||
+ !descriptorStillCurrent(backup, oldTarget) ||
+ lstatSync(target).nlink !== 2 ||
+ lstatSync(backup).nlink !== 2
+ )
+ throw new Error('ACTIVE_TARGET_CAS_FAILED');
if (
process.env.CLAUDE_STAGED_ENROLLMENT_TESTING === '1' &&
process.env.CLAUDE_STAGED_ENROLLMENT_TEST_FAULT === 'SIGKILL:BACKUP_OPENED'
@@ -1761,14 +1967,23 @@ export function activateEnrollment(options) {
process.kill(process.pid, 'SIGKILL');
if (options.injectFailure === 'partial-backup') throw new Error('INJECTED_FAILURE');
fsyncDirectory(options.rollbackDir);
+ if (restorePath) fsyncDirectory(options.stagingDir);
journal = writeJournal(options, journal, 'BACKUP_CREATED');
}
journal = writeJournal(options, journal, 'PREPARED');
// Final CAS is immediately before backup authorization and approval use.
- if (!descriptorStillCurrent(stagedPath, candidateDescriptor)) throw new Error('CANDIDATE_CAS_FAILED');
+ if (!candidateTopologyCurrent(stagedPath, candidateProof, candidateDescriptor))
+ throw new Error('CANDIDATE_CAS_FAILED');
if (!descriptorStillCurrent(inventory.path, inventory.descriptor)) throw new Error('INVENTORY_CAS_FAILED');
if (!descriptorStillCurrent(canary.path, canary.descriptor)) throw new Error('CANARY_CAS_FAILED');
- if (existsSync(target) !== hadTarget || (hadTarget && !descriptorStillCurrent(target, oldTarget)))
+ if (
+ existsSync(target) !== hadTarget ||
+ (hadTarget &&
+ (!descriptorStillCurrent(target, oldTarget) ||
+ !descriptorStillCurrent(backup, oldTarget) ||
+ lstatSync(target).nlink !== 2 ||
+ lstatSync(backup).nlink !== 2))
+ )
throw new Error('ACTIVE_TARGET_CAS_FAILED');
journal = writeJournal(options, journal, 'APPROVAL_INTENT');
try {
@@ -1783,12 +1998,13 @@ export function activateEnrollment(options) {
journal = writeJournal(options, journal, 'INSTALL_INTENT');
let renameCompleted = false;
try {
- if (!descriptorStillCurrent(stagedPath, candidateDescriptor)) throw new Error('CANDIDATE_CAS_FAILED');
+ if (!candidateTopologyCurrent(stagedPath, candidateProof, candidateDescriptor))
+ throw new Error('CANDIDATE_CAS_FAILED');
replaceAndFsync(stagedPath, target, options.stagingDir, options.activeDir, options.injectFailure, () => {
renameCompleted = true;
});
journal = writeJournal(options, journal, 'INSTALLED');
- if (!descriptorStillCurrent(target, candidateDescriptor)) throw new Error('DIGEST_MISMATCH');
+ if (!candidateTopologyCurrent(target, candidateProof, candidateDescriptor)) throw new Error('DIGEST_MISMATCH');
// External publishers are required to be operationally fenced, while all
// first-party writers share this lock. This post-install CAS ensures an
// unfenced M0→M1 replacement observed before commit is rolled back rather
@@ -1800,11 +2016,14 @@ export function activateEnrollment(options) {
)
process.kill(process.pid, 'SIGSTOP');
if (options.injectFailure === 'after-digest-verification') throw new Error('INJECTED_FAILURE');
- if (!descriptorStillCurrent(target, candidateDescriptor)) throw new Error('ACTIVE_TARGET_CAS_FAILED');
+ if (!candidateTopologyCurrent(target, candidateProof, candidateDescriptor))
+ throw new Error('ACTIVE_TARGET_CAS_FAILED');
journal = writeJournal(options, journal, 'COMMITTED');
- if (!descriptorStillCurrent(target, candidateDescriptor)) throw new Error('ACTIVATION_RECOVERY_REQUIRED');
+ if (!candidateTopologyCurrent(target, candidateProof, candidateDescriptor))
+ throw new Error('ACTIVATION_RECOVERY_REQUIRED');
retainCommittedRollback(options, journal);
- if (!descriptorStillCurrent(target, candidateDescriptor)) throw new Error('ACTIVATION_RECOVERY_REQUIRED');
+ if (!candidateTopologyCurrent(target, candidateProof, candidateDescriptor))
+ throw new Error('ACTIVATION_RECOVERY_REQUIRED');
if (
process.env.CLAUDE_STAGED_ENROLLMENT_TESTING === '1' &&
process.env.CLAUDE_STAGED_ENROLLMENT_TEST_FAULT === 'SIGKILL:AFTER_BACKUP_DELETE'
@@ -1881,6 +2100,7 @@ export function recoverEnrollment(options) {
options.operationLockPath,
options.keyPath,
() => {
+ recoverJournalTransition(options);
const path = journalPath(options);
if (!existsSync(path)) return { ok: true, action: 'recover', recovered: false };
const state = verifySignedRecord(secureRead(path), secureRead(options.keyPath), 'INVALID_ACTIVATION_JOURNAL');
@@ -1961,6 +2181,13 @@ export function recoverEnrollment(options) {
} catch {
throw new Error('INVALID_ACTIVATION_JOURNAL');
}
+ const candidateProof = `${state.stagedPath}.preparation-${state.candidateDigest}`;
+ if (
+ !existsSync(candidateProof) ||
+ !descriptorStillCurrent(candidateProof, state.candidateDescriptor) ||
+ lstatSync(candidateProof).nlink !== 2
+ )
+ throw new Error('ACTIVATION_RECOVERY_UNCERTAIN');
// Recovery is bound to the signed raw M0 digest and complete M0 entry
// snapshot below. It must not reinterpret the transaction through a
// later same-ID M1 manifest or wedge until an operator restores M0.
@@ -2005,7 +2232,7 @@ export function recoverEnrollment(options) {
options.rollbackDir,
`${entry.authFilename}.${state.approvalId}.${state.approvalNonce}.${state.candidateDigest}.${state.oldDigest || 'none'}.bak`,
);
- const expectedRestore = null;
+ const expectedRestore = state.restorePath ? `${expectedStaged}.preparation-${state.oldDigest}` : null;
if (
!entry ||
state.authFilename !== entry.authFilename ||
@@ -2026,7 +2253,6 @@ export function recoverEnrollment(options) {
// consumeApproval publishes through one expected temp hardlink. A crash
// after link(2) may leave nlink=2; remove only the uniquely inode-matched
// expected temp after the signed journal has authenticated every path.
- removePublicationTempLink(marker);
fsyncDirectory(options.usageDir);
validatePathTopology({
configPath: options.configPath,
@@ -2044,7 +2270,7 @@ export function recoverEnrollment(options) {
approvalId: { id: state.approvalId, nonce: state.approvalNonce },
computedPaths: [
['backup target', state.backup, options.rollbackDir, true],
- ...(state.restorePath ? [['restore target', state.restorePath, options.activeDir, true]] : []),
+ ...(state.restorePath ? [['restore target', state.restorePath, options.stagingDir, true]] : []),
],
});
const markerRequired = allowed.indexOf(state.phase) >= allowed.indexOf('APPROVAL_CONSUMED');
@@ -2189,10 +2415,12 @@ function rollbackIntentPath(recordPath) {
}
function writeRollbackIntent(path, payload, key) {
- const temp = `${path}.${process.pid}.${randomUUID()}.tmp`;
const bytes = `${canonicalJson(signedRecord(payload, key))}\n`;
- durableExclusive(temp, bytes);
- renameSync(temp, path);
+ if (existsSync(path)) {
+ const prior = secureReadDescriptor(path, false);
+ removeDescriptorSafely(path, prior, 'ROLLBACK_RECOVERY_UNCERTAIN');
+ }
+ durableExclusive(path, bytes);
fsyncDirectory(dirname(path));
if (
process.env.CLAUDE_STAGED_ENROLLMENT_TESTING === '1' &&
@@ -2273,14 +2501,26 @@ function recoverRollbackIntent(options, entry, recordPath) {
const targetIsCandidate =
existsSync(intent.target) && descriptorStillCurrent(intent.target, intent.candidateDescriptor);
const targetIsBackup = existsSync(intent.target) && descriptorStillCurrent(intent.target, intent.backupDescriptor);
- const backupExact = existsSync(intent.backup) && descriptorStillCurrent(intent.backup, intent.backupDescriptor);
+ const restorePath = intent.retained?.restorePath;
+ if (restorePath && existsSync(intent.backup)) {
+ if (existsSync(restorePath) || !descriptorStillCurrent(intent.backup, intent.backupDescriptor))
+ throw new Error('ROLLBACK_RECOVERY_UNCERTAIN');
+ renameSync(intent.backup, restorePath);
+ fsyncDirectory(options.rollbackDir);
+ fsyncDirectory(options.stagingDir);
+ }
+ const backupSource = restorePath || intent.backup;
+ const backupExact = existsSync(backupSource) && descriptorStillCurrent(backupSource, intent.backupDescriptor);
const tempExact = existsSync(intent.tempPath) && descriptorStillCurrent(intent.tempPath, intent.backupDescriptor);
if (intent.phase === 'PREPARING') {
if (targetIsCandidate && backupExact) {
if (!tempExact) {
if (existsSync(intent.tempPath)) throw new Error('ROLLBACK_RECOVERY_UNCERTAIN');
- linkSync(intent.backup, intent.tempPath);
- if (process.env.CLAUDE_STAGED_ENROLLMENT_TEST_FAULT === 'SIGKILL:ROLLBACK_TEMP_LINK')
+ linkSync(backupSource, intent.tempPath);
+ if (
+ process.env.CLAUDE_STAGED_ENROLLMENT_TESTING === '1' &&
+ process.env.CLAUDE_STAGED_ENROLLMENT_TEST_FAULT === 'SIGKILL:ROLLBACK_TEMP_LINK'
+ )
process.kill(process.pid, 'SIGKILL');
fsyncDirectory(options.activeDir);
}
@@ -2290,27 +2530,36 @@ function recoverRollbackIntent(options, entry, recordPath) {
)
throw new Error('ROLLBACK_RECOVERY_UNCERTAIN');
renameSync(intent.tempPath, intent.target);
- if (process.env.CLAUDE_STAGED_ENROLLMENT_TEST_FAULT === 'SIGKILL:ROLLBACK_SWITCH')
+ if (
+ process.env.CLAUDE_STAGED_ENROLLMENT_TESTING === '1' &&
+ process.env.CLAUDE_STAGED_ENROLLMENT_TEST_FAULT === 'SIGKILL:ROLLBACK_SWITCH'
+ )
process.kill(process.pid, 'SIGKILL');
fsyncDirectory(options.activeDir);
} else if (!(targetIsBackup && !existsSync(intent.tempPath))) throw new Error('ROLLBACK_RECOVERY_UNCERTAIN');
- writeRollbackIntent(intentPath, { ...intent, phase: 'SWITCHED' }, key);
+ // Keep PREPARING as the durable recovery anchor. Target/temp topology
+ // distinguishes a completed switch without replacing the sole intent.
} else if (!targetIsBackup || existsSync(intent.tempPath)) throw new Error('ROLLBACK_RECOVERY_UNCERTAIN');
if (!descriptorStillCurrent(intent.target, intent.backupDescriptor)) throw new Error('ROLLBACK_RECOVERY_UNCERTAIN');
fsyncDirectory(options.activeDir);
if (existsSync(intent.backup)) {
if (!descriptorStillCurrent(intent.backup, intent.backupDescriptor)) throw new Error('ROLLBACK_RECOVERY_UNCERTAIN');
- unlinkSync(intent.backup);
+ removeDescriptorSafely(intent.backup, intent.backupDescriptor, 'ROLLBACK_RECOVERY_UNCERTAIN');
fsyncDirectory(options.rollbackDir);
- if (process.env.CLAUDE_STAGED_ENROLLMENT_TEST_FAULT === 'SIGKILL:ROLLBACK_CLEANUP')
+ if (
+ process.env.CLAUDE_STAGED_ENROLLMENT_TESTING === '1' &&
+ process.env.CLAUDE_STAGED_ENROLLMENT_TEST_FAULT === 'SIGKILL:ROLLBACK_CLEANUP'
+ )
process.kill(process.pid, 'SIGKILL');
}
if (existsSync(recordPath)) {
if (sha256(secureRead(recordPath)) !== intent.recordDigest) throw new Error('ROLLBACK_RECOVERY_UNCERTAIN');
- unlinkSync(recordPath);
+ const recordDescriptor = secureReadDescriptor(recordPath);
+ removeDescriptorSafely(recordPath, recordDescriptor, 'ROLLBACK_RECOVERY_UNCERTAIN');
fsyncDirectory(options.rollbackDir);
}
- unlinkSync(intentPath);
+ const intentDescriptor = secureReadDescriptor(intentPath);
+ removeDescriptorSafely(intentPath, intentDescriptor, 'ROLLBACK_RECOVERY_UNCERTAIN');
fsyncDirectory(options.rollbackDir);
return {
ok: true,