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.
Shell agent-teamsai-agentai-automationanthropicautonomous-agentawsbusiness-operationsclaudeclaude-codeclaude-code-plugindevopsecommerceinbox-zeroklaviyomarketingmcpmorning-briefingpr-automationshopifyterminal
fix(auth): add staged Claude enrollment boundary (#783)
Aurora Capital095e7ef37bbc
diff --git a/claude-ops/CHANGELOG.md b/claude-ops/CHANGELOG.mdindex ed715ad5..2f0c1068 100644--- a/claude-ops/CHANGELOG.md+++ b/claude-ops/CHANGELOG.md@@ -1,5 +1,6 @@## Unreleased+- Security: replace direct/unattended Claude browser reauthentication with short-lived HMAC-approved, single-use staged enrollment and atomic rollback activation; legacy reauth wrappers now fail closed.- ops-accounts-gateway skeleton (:3005 health/auth/grok hop; CLI gateway subcommand)- feat(crs-priority-daemon): dual-mode `backend=crs|local` file seat-state without CRS Dockerdiff --git a/claude-ops/bin/ops-accounts b/claude-ops/bin/ops-accountsindex feb967e2..1f8efee0 100755--- a/claude-ops/bin/ops-accounts+++ b/claude-ops/bin/ops-accounts@@ -281,11 +281,8 @@ PY;;claude)[[ -n "$email" ]] || { echo "usage: ops-accounts reauth claude <email>"; exit 2; }- if [[ -f "$ROT/rotate-magic.mjs" ]]; then- node "$ROT/rotate-magic.mjs" --to "$email" --force- else- node "$ROT/rotate.mjs" --magic-link --to "$email"- fi+ echo "Claude direct browser/magic-link reauthentication is disabled. Use staged-enrollment.mjs with separate stage and activate approvals." >&2+ exit 2;;*)echo "usage: ops-accounts reauth grok|claude <email>"; exit 2 ;;diff --git a/claude-ops/lib/credential-store.mjs b/claude-ops/lib/credential-store.mjsindex c54b7e09..4ea34549 100644--- a/claude-ops/lib/credential-store.mjs+++ b/claude-ops/lib/credential-store.mjs@@ -35,6 +35,13 @@ let __plaintextWarned = false;const log = (...args) => console.error('credential-store:', ...args);+function assertPublicWriteAllowed(service) {+ const name = String(service || '').toLowerCase();+ if (name === 'claude code-credentials' || name === 'claude-rotation' || name.startsWith('claude-rotation-')) {+ throw new Error('protected Claude credential writes require the coordinated internal writer');+ }+}+async function ensureDataDir() {await fs.mkdir(DATA_DIR, { recursive: true, mode: 0o700 });}@@ -313,6 +320,7 @@ export async function backendsAvailable() {* @returns {Promise<{backend: string, ok: boolean}>}*/export async function setCredential(service, account, secret) {+ assertPublicWriteAllowed(service);const forced = process.env.CLAUDE_OPS_CRED_BACKEND;const tryBackend = async (name) => {let ok = false;@@ -406,6 +414,7 @@ export async function getCredential(service, account) {* @returns {Promise<{deletedFrom: string[]}>}*/export async function deleteCredential(service, account) {+ assertPublicWriteAllowed(service);const deletedFrom = [];const nb = nativeBackend();try {@@ -492,6 +501,7 @@ if (isCli) {// Helpers called by lib/credential-store.shcase 'set-keytar': {const [service, account, secret] = rest;+ assertPublicWriteAllowed(service);const ok = await keytarSet(service, account, secret);process.exit(ok ? 0 : 1);}@@ -504,6 +514,7 @@ if (isCli) {}case 'delete-keytar': {const [service, account] = rest;+ assertPublicWriteAllowed(service);await keytarDelete(service, account);process.exit(0);}diff --git a/claude-ops/lib/credential-store.sh b/claude-ops/lib/credential-store.shindex c67a5d9b..0d619fc3 100755--- a/claude-ops/lib/credential-store.sh+++ b/claude-ops/lib/credential-store.sh@@ -53,6 +53,14 @@ _ops_cred_log() {printf 'credential-store: %s\n' "$*" >&2}+_ops_cred_assert_public_write_allowed() {+ local svc="${1,,}"+ if [[ "$svc" == "claude code-credentials" || "$svc" == "claude-rotation" || "$svc" == claude-rotation-* ]]; then+ _ops_cred_log "protected Claude credential writes require the coordinated internal writer"+ return 1+ fi+}+_ops_cred_warn_plaintext_once() {if [[ "$__OPS_CRED_PLAIN_WARNED" == "0" ]]; thenprintf '⚠ credential-store: using plaintext JSON fallback — install secret-tool (linux) or cmdkey (windows) for better security\n' >&2@@ -488,6 +496,7 @@ ops_cred_set() {return 1filocal svc="$1" acc="$2" sec="$3"+ _ops_cred_assert_public_write_allowed "$svc" || return 1if _ops_cred_native_available && _ops_cred_native_set "$svc" "$acc" "$sec"; then_ops_cred_log "stored via=native:$(ops_keyring_backend) service=$svc account=$acc"@@ -539,6 +548,7 @@ ops_cred_delete() {return 1filocal svc="$1" acc="$2"+ _ops_cred_assert_public_write_allowed "$svc" || return 1local any_err=0# Best-effort on each: missing-key is NOT an error.diff --git a/claude-ops/scripts/account-rotation/README.md b/claude-ops/scripts/account-rotation/README.mdindex 6d716fa5..e292ef4b 100644--- a/claude-ops/scripts/account-rotation/README.md+++ b/claude-ops/scripts/account-rotation/README.md@@ -45,30 +45,133 @@ The skill walks you through:Each account entry:-| Field | Required | Notes |-| --------------------- | -------- | ------------------------------------------------------------------------------ |-| `email` | yes | Login email for the Claude Max account. |-| `label` | no | Disambiguator if you have two configs for the same email (multi-org). |-| `orgName` / `orgUuid` | no | Workspace metadata for accounts in a Claude org. |-| `dashlaneTokenPath` | no | If you store the token in Dashlane: `dl://<vault-name>/password`. |-| `extraUsageEnabled` | no | Set to `true` ONLY if the account has paid overage on. Triggers safety margin. |-| `capacityMultiplier` | no | Override per-account threshold (default 1.0 = standard Max 20x quota). |-| `crsAccountName` | no | CRS admin account name this vault entry maps to (for crs-token-feed / crs-priority). |--## Standalone rotate-magic (no CRS)--Most users only need **one account at a time** (or a few seats with the keychain-rotator). That path does **not** require CRS:--```bash-node "$CLAUDE_PLUGIN_ROOT/scripts/account-rotation/rotate-magic.mjs" --to [email protected]-# or multi-account OAuth capture:-node "$CLAUDE_PLUGIN_ROOT/scripts/account-rotation/rotate.mjs" --setup --auto --skip-valid-```--Unattended captcha cascade (visual → desktop-act → VNC) lives in-`captcha-helper.mjs`, `visual-captcha-solver.mjs`, `captcha-cascade.mjs`. See-`CAPTCHA-CASCADE.md`.+| Field | Required | Notes |+| ----------------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------- |+| `email` | yes | Login email for the Claude Max account. |+| `label` | no | Disambiguator if you have two configs for the same email (multi-org). |+| `orgName` / `orgUuid` | **yes** | Exact account organization identity; required for every account, including personal accounts. |+| `automatedCredentialMutation` | no | Reserved; currently fail-closed even when `true`. Identity verification or configuration never grants write permission. |+| `dashlaneTokenPath` | no | If you store the token in Dashlane: `dl://<vault-name>/password`. |+| `extraUsageEnabled` | no | Set to `true` ONLY if the account has paid overage on. Triggers safety margin. |+| `capacityMultiplier` | no | Override per-account threshold (default 1.0 = standard Max 20x quota). |+| `crsAccountName` | no | CRS admin account name this vault entry maps to (for crs-token-feed / crs-priority). |++## Signed staged Claude enrollment++Direct browser and magic-link reauthentication entrypoints are fail-closed. New+CLIProxyAPI Claude credentials must be captured outside this plugin, then passed+to `staged-enrollment.mjs`: first with a short-lived signed `stage` approval for+the exact candidate SHA-256 and `additive-publish` action, then with a distinct+signed `activate` approval for the exact `canonical-switch` action.+The manifest explicitly binds one ID and auth filename to provider, normalized+email, organization UUID/name, and owner. Approval keys and usage, staging, and+rollback directories must be owner-only. The CLI intentionally cannot sign+approvals and prints only redacted receipt metadata.++All direct OAuth writers are denied, including absent/unconfigured accounts,+Claude Code, manual setup, magic-link, and CLIProxy. Automatic token refresh,+save-back, active-slot updates, and destructive 401 cleanup are disabled;+`automatedCredentialMutation` alone cannot authorize them. Denied runs do not+launch authentication subprocesses or change credential storage. A 401 retains credential bytes and reports+`needsReauth`/status for a separately approved staged enrollment. A successful+exact identity check proves which credential was observed; it is not write+authorization.++Legacy browser-pin apply, publication, and restore are disabled. A portable+filesystem compare-and-swap cannot prove that a nonparticipating writer did not+replace the destination between validation and rename. Existing recovery+evidence is retained for operator inspection; this code never uses it to+overwrite or delete credential state.++Runtime invocation accepts exactly `--config`, `--entry`, `--approval`, and, for+stage only, `--candidate`. Activate additionally requires explicit absolute+owner-only `--inventory` and `--canary` JSON paths; there are no default evidence+paths. The owner-only deployment config pins every trust+root, the canonical operation lock, environment/operator, and a finite approval+TTL no greater than 15 minutes. Inventory and canary use strict JSON and exact+schemas. The signed switch approval binds their immutable raw SHA-256 digests,+the manifest and candidate digests, exact credential ID and complete provider,+email, organization UUID/name, owner and destination identity, the prior target+digest (or explicit absence), expiry, and nonce. Canary evidence must select the+exact candidate and report both `noFallback: true` and `pass: true`; malformed,+incomplete, stale, fallback, or mismatched evidence fails closed.++`stage` validates without changing active auth, manifest, quarantine, cooldowns,+services, or replicas. `activate` compare-and-swaps the manifest digest, replaces+only the approved auth filename, and restores its backup if verification fails.+The old credential/config backup remains until rollback verification and the+existing bounded cleanup completes. This tool has no invalidate, revoke, or+delete operation and performs none implicitly. Any later invalidation requires+a separate fresh signed permission handled by a different authorized tool; a+stage or switch approval never authorizes it.++Activation uses an authenticated phase journal beside the operation lock. The+journal binds the original signed exact-switch payload and raw evidence digests,+so recovery proves the same authorization rather than reinterpreting current+state. After+an interrupted activation, run `staged-enrollment.mjs recover --config <path>`;+other writers refuse while that journal is pending. A stale lock is reclaimed+only when its HMAC is valid, it names this host, and its PID is demonstrably+dead. Malformed and cross-host locks require operator investigation.++Enabled first-party credential writers must set+`CLAUDE_AUTH_COORDINATION_CONFIG` to this deployment config and+`CLAUDE_ROTATOR_CONFIG` to the reviewed runtime inventory installed by the same+plan. They share one lock and one exact account identity source.+CLIProxyAPI, remote sync, and other external writers cannot participate in the+local lock and must remain operationally quiesced/fenced during activation.+Successful switch or recovery converts the temporary backup into a retained,+authenticated rollback record. A separate fresh signed `canonical-rollback`+approval is required to restore it; approval use markers remain durable+authenticated replay evidence.++### Coordination rollout and migration++Provisioning is offline and never reads or writes credentials. First update the+authoritative rotator inventory so all nine Claude accounts have exact `email`,+`orgUuid`, and `orgName`; legacy inventories missing either organization field+are refused before any file is written. Supply the reviewed intended 15-entry+manifest separately with `--manifest-source`; plan requires its nine Claude+identities to exactly equal the inventory and digest-binds its raw bytes. Run+`provision-coordination.mjs plan` with explicit absolute manifest target,+active, staging, usage, rollback, quarantine, lock, trust, config, Linux/macOS+environment, `--runtime-inventory` target, `--runtime-home` for the service+account home embedded in reviewed launch artifacts, an owner-only+`--consumer-inventory-source` reviewed JSON file plus+`--authoritative-consumer-inventory` target outside mutable credential roots,+and rendered service paths. The consumer file has exact schema+`{"version":1,"consumers":[{"id","type","path","credentialId","destination"}]}`;+IDs and normalized absolute paths are unique and every credential/destination+pair must match the reviewed manifest. Review+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>+--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+any credential mutation, and a divergent inventory fails exact identity checks.+Activation's submitted inventory must equal the authoritative consumers for the+selected credential exactly. Canary evidence contains exactly one passing,+no-fallback result per authoritative consumer and binds its ID, absolute path,+candidate digest, credential ID, and destination; both raw evidence digests are+bound by the signed activation approval.++Rollback means stopping before service activation and removing only artifacts+created by the failed apply; injected or real apply failures do this+automatically. After consumers are active, retain the key/config and roll back+service definitions to the prior reviewed version—never regenerate or overwrite+the coordination key. Trust files must remain outside all mutable auth roots.++## Legacy rotate-magic (disabled)++`rotate-magic.mjs`, browser setup modes, refresh emergency fallback, and the+autoloop no longer dispatch authentication. They return a staged-enrollment+handoff instead; no environment flag restores the old write path.## CRS pool (optional)@@ -103,18 +206,18 @@ Override the keychain account name via `CLAUDE_ROTATOR_KEYCHAIN_ACCOUNT` if you## Files-| File | Purpose |-| --------------------- | ------------------------------------------------------------------------- |-| `rotate.mjs` | Main rotation logic. CLI: `--status`, `--utilization`, `--to`, `--setup`. |-| `rotate-magic.mjs` | Thin entry → `rotate.mjs --magic-link` (standalone reauth, no CRS). |-| `captcha-cascade.mjs` | Post-verify captcha orchestration (token + visual + desktop-act + VNC). |-| `captcha-helper.mjs` | Pluggable token captcha solvers + residential wait. |-| `visual-captcha-solver.mjs` | Vision tile clicks, desktop-act, VNC layers. |-| `bright-data-cascade.mjs` | Optional Bright Data proxy tiers for solver IP alignment. |-| `daemon.mjs` | launchd-managed monitor. Polls every 15s, rotates at 80% utilization. |-| `ai-brain.mjs` | Claude Haiku fallback for unexpected OAuth pages. |-| `force-rotate.sh` | Out-of-band rotation when Claude Code is unreachable. |-| `config.example.json` | Schema reference. Copy to `config.json` and populate. |+| File | Purpose |+| --------------------------- | ------------------------------------------------------------------------- |+| `rotate.mjs` | Main rotation logic. CLI: `--status`, `--utilization`, `--to`, `--setup`. |+| `rotate-magic.mjs` | Thin entry → `rotate.mjs --magic-link` (standalone reauth, no CRS). |+| `captcha-cascade.mjs` | Post-verify captcha orchestration (token + visual + desktop-act + VNC). |+| `captcha-helper.mjs` | Pluggable token captcha solvers + residential wait. |+| `visual-captcha-solver.mjs` | Vision tile clicks, desktop-act, VNC layers. |+| `bright-data-cascade.mjs` | Optional Bright Data proxy tiers for solver IP alignment. |+| `daemon.mjs` | launchd-managed monitor. Polls every 15s, rotates at 80% utilization. |+| `ai-brain.mjs` | Claude Haiku fallback for unexpected OAuth pages. |+| `force-rotate.sh` | Out-of-band rotation when Claude Code is unreachable. |+| `config.example.json` | Schema reference. Copy to `config.json` and populate. |## Triggersdiff --git a/claude-ops/scripts/account-rotation/__tests__/browser-pin-recovery.test.mjs b/claude-ops/scripts/account-rotation/__tests__/browser-pin-recovery.test.mjsnew file mode 100644index 00000000..42dd15cf--- /dev/null+++ b/claude-ops/scripts/account-rotation/__tests__/browser-pin-recovery.test.mjs@@ -0,0 +1,46 @@+import assert from 'node:assert/strict';+import { existsSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { applyBrowserPinTransaction, restoreBrowserPinBackup } from '../browser-pin-recovery.mjs';++const root = mkdtempSync(join(tmpdir(), 'browser-pin-disabled-'));+const destinationPath = join(root, '.claude.json');+const sentinelPath = join(root, 'recovery.json');+const original = Buffer.from('{"oauthAccount":{"emailAddress":"[email protected]"}}\n');+writeFileSync(destinationPath, original, { mode: 0o600 });+let applied = false;++assert.throws(+ () =>+ applyBrowserPinTransaction({+ sourcePath: destinationPath,+ destinationPath,+ sentinelPath,+ backupDirectory: join(root, 'backups'),+ coordinationKey: Buffer.alloc(32, 7),+ apply() {+ applied = true;+ writeFileSync(destinationPath, '{"pinned":true}\n', { mode: 0o600 });+ },+ }),+ /BROWSER_PIN_MUTATION_DISABLED/,+);+assert.equal(applied, false);+assert.deepEqual(readFileSync(destinationPath), original);+assert.equal(existsSync(sentinelPath), false);+assert.equal(existsSync(join(root, 'backups')), false);++// Existing evidence is retained, but the disabled legacy restore path never+// overwrites a concurrent or foreign destination.+writeFileSync(sentinelPath, '{"opaque":"evidence"}\n', { mode: 0o600 });+// Test-only adversarial replacement immediately before the fail-closed restore probe.+// CodeQL[js/file-system-race]+writeFileSync(destinationPath, '{"foreign":true}\n', { mode: 0o600 });+const foreign = readFileSync(destinationPath);+const result = restoreBrowserPinBackup({ destinationPath, sentinelPath, coordinationKey: Buffer.alloc(32, 7) });+assert.deepEqual(result, { restored: false, reason: 'browser-pin-mutation-disabled', retained: true });+assert.deepEqual(readFileSync(destinationPath), foreign);+assert.equal(existsSync(sentinelPath), true);++console.log('browser pin recovery tests: PASS');diff --git a/claude-ops/scripts/account-rotation/__tests__/claude-p-as.test.mjs b/claude-ops/scripts/account-rotation/__tests__/claude-p-as.test.mjsindex e84c3329..ed5d3512 100644--- a/claude-ops/scripts/account-rotation/__tests__/claude-p-as.test.mjs+++ b/claude-ops/scripts/account-rotation/__tests__/claude-p-as.test.mjs@@ -11,7 +11,7 @@import { test } from 'node:test';import assert from 'node:assert/strict';-import { writeFileSync, readFileSync, mkdtempSync, openSync, closeSync, unlinkSync } from 'fs';+import { writeFileSync, readFileSync, mkdtempSync, mkdirSync, existsSync, openSync, closeSync, unlinkSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';import { spawnSync } from 'child_process';@@ -80,7 +80,7 @@ test('pickAccount refuses (exit 2) when all accounts $0', () => {writeFileSync(ledgerPath, JSON.stringify(ledger));const r = spawnSync('node', [SCRIPT, '--ledger', ledgerPath, '--', '/help'], { encoding: 'utf8' });assert.equal(r.status, 2);- assert.match(r.stderr, /all accounts \$0/);+ assert.match(r.stderr, /SIGNED_CREDENTIAL_MUTATION_APPROVAL_REQUIRED/);});test('pickAccount refuses (exit 2) when pinned account at $0', () => {@@ -94,7 +94,7 @@ test('pickAccount refuses (exit 2) when pinned account at $0', () => {encoding: 'utf8',});assert.equal(r.status, 2);- assert.match(r.stderr, /pinned account a@x\.com credit exhausted/);+ assert.match(r.stderr, /SIGNED_CREDENTIAL_MUTATION_APPROVAL_REQUIRED/);});test('assertNotExtraUsage refuses accounts with extra_usage flag in ledger', () => {@@ -108,7 +108,7 @@ test('assertNotExtraUsage refuses accounts with extra_usage flag in ledger', ()],{ encoding: 'utf8' },);- assert.equal(r.status, 2);+ assert.notEqual(r.status, 0);assert.match(r.stderr, /extra_usage=true/);});@@ -125,7 +125,7 @@ test('assertNotExtraUsage refuses accounts with extraUsageEnabled=true in rotati],{ encoding: 'utf8' },);- assert.equal(r.status, 2);+ assert.notEqual(r.status, 0);assert.match(r.stderr, /extraUsageEnabled=true/);});@@ -181,7 +181,28 @@ test('refuses when ledger file missing', () => {encoding: 'utf8',});assert.equal(r.status, 2);- assert.match(r.stderr, /ledger missing/);+ assert.match(r.stderr, /SIGNED_CREDENTIAL_MUTATION_APPROVAL_REQUIRED/);+});++test('executable refuses before child execution or filesystem writes', () => {+ const root = mkdtempSync(join(tmpdir(), 'claude-p-as-deny-'));+ const marker = join(root, 'child-ran');+ const fakeBin = join(root, 'bin');+ const ledgerPath = join(root, 'ledger.json');+ const lockPath = join(root, 'keychain.lock');+ mkdirSync(fakeBin);+ writeFileSync(join(fakeBin, 'claude'), `#!/bin/sh\nprintf child > "${marker}"\n`, { mode: 0o700 });+ writeFileSync(ledgerPath, JSON.stringify(makeLedger([{ email: '[email protected]', remaining_usd: 200 }])));+ const before = readFileSync(ledgerPath);+ const result = spawnSync('node', [SCRIPT, '--ledger', ledgerPath, '--lock', lockPath, '--', 'hello'], {+ encoding: 'utf8',+ env: { ...process.env, PATH: `${fakeBin}:${process.env.PATH}` },+ });+ assert.equal(result.status, 2);+ assert.match(result.stderr, /SIGNED_CREDENTIAL_MUTATION_APPROVAL_REQUIRED/);+ assert.equal(existsSync(marker), false, 'child count remains zero');+ assert.equal(existsSync(lockPath), false, 'write count remains zero');+ assert.deepEqual(readFileSync(ledgerPath), before, 'ledger is untouched');});test('lock contention: second invocation refuses while lock file exists', () => {@@ -203,7 +224,7 @@ test('lock contention: second invocation refuses while lock file exists', () =>// Will fail at lock OR earlier at assertBudgetFlagAvailable if claude CLI isn't installed.// Accept either: status 2 + (lock-held OR claude-cli-missing) — both are correct refusals.assert.equal(r.status, 2);- assert.match(r.stderr, /(keychain lock held|--max-budget-usd.*not available|ledger)/);+ assert.match(r.stderr, /SIGNED_CREDENTIAL_MUTATION_APPROVAL_REQUIRED/);} finally {try {unlinkSync(lockPath);@@ -316,7 +337,7 @@ test('claude-p-as exits 2 and prints refuse message when cost parse fails', () =});// P1b: post-swap probe ordering — assertBudgetFlagAvailable must be called after swapToEmail-test('claude-p-as script exports assertBudgetFlagAvailable is not called before swap in main flow', () => {+test('claude-p-as main default-denies before any swap or child path', () => {// Structural test: verify the source code calls assertBudgetFlagAvailable()// after swapToEmail() in the main() function body.// We strip comment lines to avoid matching the "do NOT call ... here" comment.@@ -326,17 +347,9 @@ test('claude-p-as script exports assertBudgetFlagAvailable is not called before.split('\n').filter((l) => !l.trimStart().startsWith('//')).join('\n');- const swapPos = mainBody.indexOf('swapToEmail(');- // Find the actual call site (not function definition, not comment).- // The call is a bare statement: /^\s*assertBudgetFlagAvailable\(\)/m- const probeMatch = mainBody.match(/\n(\s*assertBudgetFlagAvailable\(\))/);- const probePos = probeMatch ? mainBody.indexOf(probeMatch[0]) : -1;- assert.ok(swapPos !== -1, 'swapToEmail must appear in main()');- assert.ok(probePos !== -1, 'assertBudgetFlagAvailable() call-site must appear in main()');- assert.ok(- probePos > swapPos,- `assertBudgetFlagAvailable() (pos ${probePos}) must appear AFTER swapToEmail() (pos ${swapPos}) in main()`,- );+ const refusal = mainBody.indexOf("die(2, 'SIGNED_CREDENTIAL_MUTATION_APPROVAL_REQUIRED')");+ assert.ok(refusal !== -1);+ assert.ok(refusal < mainBody.indexOf('acquireLock('));});test('claude-p-as rejects ledger with unknown schema_version', () => {@@ -344,5 +357,5 @@ test('claude-p-as rejects ledger with unknown schema_version', () => {writeFileSync(ledgerPath, JSON.stringify({ schema_version: 99, month: '2026-06', accounts: [] }));const r = spawnSync('node', [SCRIPT, '--ledger', ledgerPath, '--', 'hello'], { encoding: 'utf8' });assert.equal(r.status, 2);- assert.match(r.stderr, /ledger unreadable|schema_version/);+ assert.match(r.stderr, /SIGNED_CREDENTIAL_MUTATION_APPROVAL_REQUIRED/);});diff --git a/claude-ops/scripts/account-rotation/__tests__/coordination-provisioning.test.mjs b/claude-ops/scripts/account-rotation/__tests__/coordination-provisioning.test.mjsnew file mode 100755index 00000000..723e3fe4--- /dev/null+++ b/claude-ops/scripts/account-rotation/__tests__/coordination-provisioning.test.mjs@@ -0,0 +1,409 @@+#!/usr/bin/env node+import assert from 'node:assert/strict';+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { spawnSync } from 'node:child_process';++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 fixture(legacy = false) {+ const root = mkdtempSync(join(tmpdir(), 'coordination-provision-'));+ chmodSync(root, 0o700);+ const inventory = join(root, 'inventory.json');+ const consumerInventorySource = join(root, 'reviewed-consumers.json');+ writeFileSync(+ inventory,+ JSON.stringify({+ accounts: Array.from({ length: 9 }, (_, index) => ({+ email: `owner-${index}@example.com`,+ ...(legacy && index === 0 ? {} : { orgUuid: `org-${index}`, orgName: `Owner Org ${index}` }),+ })),+ }),+ { mode: 0o600 },+ );+ const trustRoot = join(root, 'trust');+ const mutable = join(root, 'mutable');+ const installHome = join(root, 'install-home');+ mkdirSync(trustRoot, { mode: 0o700 });+ mkdirSync(installHome, { mode: 0o700 });+ const paths = {+ manifest: join(trustRoot, 'manifest.json'),+ trust: join(trustRoot, 'approval.key'),+ config: join(trustRoot, 'coordination.json'),+ active: join(mutable, 'active'),+ staging: join(mutable, 'staging'),+ usage: join(mutable, 'usage'),+ rollback: join(mutable, 'rollback'),+ quarantine: join(mutable, 'quarantine'),+ lock: join(root, 'locks', 'operation.lock'),+ 'provision-lock': join(root, 'locks', 'provision.lock'),+ 'linux-env': join(root, 'generated', 'linux.env'),+ 'macos-env': join(root, 'generated', 'macos.env'),+ 'linux-unit': join(installHome, '.config', 'systemd', 'user', 'claude-account-rotator.service'),+ 'macos-plist': join(root, 'generated', 'rotator.plist'),+ 'runtime-inventory': join(trustRoot, 'account-inventory.json'),+ 'authoritative-consumer-inventory': join(trustRoot, 'consumer-inventory.json'),+ 'linux-token-feed-unit': join(root, 'generated', 'crs-token-feed.service'),+ 'linux-refresh-unit': join(root, 'generated', 'claude-token-refresh.service'),+ };+ const manifestSource = join(trustRoot, 'reviewed-manifest.json');+ const entries = [+ ...Array.from({ length: 9 }, (_, index) => ({+ id: `claude-${index}`,+ authFilename: `claude-${index}.json`,+ provider: 'claude',+ email: `owner-${index}@example.com`,+ organizationUuid: `org-${index}`,+ organizationName: `Owner Org ${index}`,+ accountOwner: `owner-${index}`,+ })),+ { id: 'antigravity-0', authFilename: 'antigravity-0.json', provider: 'antigravity' },+ ...Array.from({ length: 2 }, (_, index) => ({+ id: `codex-${index}`,+ authFilename: `codex-${index}.json`,+ provider: 'codex',+ })),+ ...Array.from({ length: 3 }, (_, index) => ({+ id: `xai-${index}`,+ authFilename: `xai-${index}.json`,+ provider: 'xai',+ })),+ ];+ writeFileSync(manifestSource, `${JSON.stringify({ version: 1, entries }, null, 2)}\n`, { mode: 0o600 });+ writeFileSync(+ consumerInventorySource,+ `${JSON.stringify({+ version: 1,+ consumers: Array.from({ length: 9 }, (_, index) => ({+ id: `consumer-${index}`,+ type: 'cliproxyapi',+ path: join(root, 'consumers', `consumer-${index}`),+ credentialId: `claude-${index}`,+ destination: `claude-${index}.json`,+ })),+ })}\n`,+ { mode: 0o600 },+ );+ const args = [+ 'plan',+ '--inventory',+ inventory,+ '--manifest-source',+ manifestSource,+ '--consumer-inventory-source',+ consumerInventorySource,+ '--operator',+ 'release-operator',+ '--environment',+ 'test',+ '--runtime-home',+ root,+ ...Object.entries(paths).flatMap(([k, v]) => [`--${k}`, v]),+ ];+ return { root, inventory, consumerInventorySource, manifestSource, paths, args, installHome };+}++const legacy = fixture(true);+const refused = run(legacy.args);+assert.notEqual(refused.status, 0);+assert.match(refused.stderr, /ACCOUNT_IDENTITY_REQUIRED/);+assert.equal(existsSync(legacy.paths.config), false, 'legacy refusal happens before writes');++for (const mutate of [+ (x) => (x.args[x.args.indexOf('--trust') + 1] = x.paths.config),+ (x) => (x.args[x.args.indexOf('--trust') + 1] = join(x.paths.active, 'approval.key')),+ (x) => (x.args[x.args.indexOf('--linux-env') + 1] = x.paths['macos-env']),+]) {+ const unsafe = fixture();+ mutate(unsafe);+ const result = run(unsafe.args);+ assert.notEqual(result.status, 0, 'aliased/overlapping topology refused');+ assert.equal(existsSync(unsafe.paths.config), false);+}++const dangerous = fixture();+writeFileSync(+ dangerous.inventory,+ '{"accounts":[{"email":"[email protected]","orgUuid":"org-1","orgName":"Org","__proto__":{}}]}',+);+assert.notEqual(run(dangerous.args).status, 0, 'dangerous source JSON key refused');++const f = fixture();+const planned = run(f.args);+assert.equal(planned.status, 0, planned.stderr);+const 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');+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.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,+ 0,+ 'precise artifact preflight',+);+const linuxEnv = readFileSync(f.paths['linux-env'], 'utf8');+const macEnv = readFileSync(f.paths['macos-env'], 'utf8');+assert.equal(linuxEnv, macEnv);+assert.match(linuxEnv, new RegExp(f.paths.config));+for (const file of [f.paths['linux-unit'], f.paths['macos-plist']])+ assert.doesNotMatch(readFileSync(file, 'utf8'), /\$\{HOME\}|__HOME__/);+assert.equal(f.paths.trust.startsWith(join(f.root, 'mutable')), false, 'trust outside mutable roots');+assert.deepEqual(readFileSync(f.paths['runtime-inventory']), readFileSync(f.inventory));++const selfStat = readFileSync(`/proc/${process.pid}/stat`, 'utf8');+const selfStart = selfStat.slice(selfStat.lastIndexOf(') ') + 2).split(' ')[19];+writeFileSync(+ f.paths['provision-lock'],+ `${JSON.stringify({ version: 1, planDigest: plan.digest, pid: process.pid, start: selfStart, nonce: 'a'.repeat(32) })}\n`,+ { mode: 0o600 },+);+assert.match(+ run(['apply', '--plan', planPath, '--expected-digest', plan.digest]).stderr,+ /PROVISION_LOCK_HELD/,+ 'concurrent provisioning writer refused',+);+writeFileSync(+ f.paths['provision-lock'],+ `${JSON.stringify({ version: 1, planDigest: plan.digest, pid: 99999999, start: '1', nonce: 'b'.repeat(32) })}\n`,+ { mode: 0o600 },+);+assert.equal(+ run(['apply', '--plan', planPath, '--expected-digest', plan.digest]).status,+ 0,+ 'authenticated plan-bound stale provisioning lock recovered',+);++// The installer consumes only paths emitted by the authenticated preflight and+// installs the exact reviewed artifact; it never reparses mutable plan fields.+const fakeBin = join(f.root, 'fake-bin');+mkdirSync(fakeBin, { mode: 0o700 });+const fakeSystemctl = join(fakeBin, 'systemctl');+writeFileSync(fakeSystemctl, '#!/usr/bin/env bash\n[[ " $* " == *" is-active "* ]] && echo active\nexit 0\n', {+ mode: 0o700,+});+const installer = new URL('../../install-account-rotator-linux.sh', import.meta.url).pathname;+const installed = spawnSync('bash', [installer], {+ encoding: 'utf8',+ env: {+ ...process.env,+ HOME: f.installHome,+ PATH: `${fakeBin}:${process.env.PATH}`,+ CLAUDE_AUTH_COORDINATION_PLAN: planPath,+ CLAUDE_AUTH_COORDINATION_PLAN_DIGEST: plan.digest,+ },+});+assert.equal(installed.status, 0, installed.stderr);+assert.deepEqual(+ readFileSync(join(f.installHome, '.config/systemd/user/claude-account-rotator.service')),+ readFileSync(f.paths['linux-unit']),+ 'installer publishes exact preflight-reviewed unit',+);++const inventorySwap = run(['preflight', '--plan', planPath, '--expected-digest', plan.digest]);+assert.equal(inventorySwap.status, 0);+writeFileSync(f.paths['runtime-inventory'], '{}', { mode: 0o600 });+assert.match(+ run(['preflight', '--plan', planPath, '--expected-digest', plan.digest]).stderr,+ /RUNTIME_INVENTORY_MISMATCH/,+);+writeFileSync(f.paths['runtime-inventory'], readFileSync(f.inventory), { mode: 0o600 });++const rollback = fixture();+const rp = run(rollback.args);+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_TEST_FAIL_AFTER: '3',+});+assert.notEqual(failed.status, 0);+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.+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_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.equal(existsSync(`${crashResume.paths.config}.provision-journal`), false);++const crashRollback = fixture();+const rollbackPlanResult = run(crashRollback.args);+const rollbackPlan = JSON.parse(rollbackPlanResult.stdout);+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_TEST_SIGKILL_AFTER: '2',+ }).signal,+ 'SIGKILL',+);+assert.equal(+ run(['rollback', '--plan', rollbackPlanPath, '--expected-digest', rollbackPlan.digest]).status,+ 0,+ 'fresh-process rollback',+);+for (const file of [+ crashRollback.paths.manifest,+ crashRollback.paths.trust,+ crashRollback.paths.config,+ crashRollback.paths['linux-env'],+])+ assert.equal(existsSync(file), false);+assert.equal(existsSync(crashRollback.manifestSource), true, 'reviewed source is never a rollback target');++// Atomic no-replace publication never overwrites or rolls back a competing+// owner-created target that appears after the plan's absence snapshot.+const raced = fixture();+const racedPlanResult = run(raced.args);+const racedPlan = JSON.parse(racedPlanResult.stdout);+const racedPlanPath = join(raced.root, 'plan.json');+writeFileSync(racedPlanPath, racedPlanResult.stdout, { mode: 0o600 });+const racedApply = run(['apply', '--plan', racedPlanPath, '--expected-digest', racedPlan.digest], {+ CLAUDE_COORDINATION_TESTING: '1',+ CLAUDE_COORDINATION_TEST_RACE_TARGET: raced.paths.manifest,+});+assert.notEqual(racedApply.status, 0);+assert.equal(readFileSync(raced.paths.manifest, 'utf8'), 'competing-owner\n');++const sameRace = fixture();+const samePlanResult = run(sameRace.args);+const samePlan = JSON.parse(samePlanResult.stdout);+const samePlanPath = join(sameRace.root, 'plan.json');+writeFileSync(samePlanPath, samePlanResult.stdout, { mode: 0o600 });+const sameApply = run(['apply', '--plan', samePlanPath, '--expected-digest', samePlan.digest], {+ CLAUDE_COORDINATION_TESTING: '1',+ CLAUDE_COORDINATION_TEST_RACE_TARGET: sameRace.paths.manifest,+ CLAUDE_COORDINATION_TEST_RACE_SAME: '1',+ CLAUDE_COORDINATION_TEST_FAIL_AFTER: '1',+});+assert.notEqual(sameApply.status, 0);+assert.deepEqual(readFileSync(sameRace.paths.manifest), readFileSync(sameRace.manifestSource));++const postLinkRace = fixture();+const postLinkPlanResult = run(postLinkRace.args);+const postLinkPlan = JSON.parse(postLinkPlanResult.stdout);+const postLinkPlanPath = join(postLinkRace.root, 'plan.json');+writeFileSync(postLinkPlanPath, postLinkPlanResult.stdout, { mode: 0o600 });+const postLinkApply = run(['apply', '--plan', postLinkPlanPath, '--expected-digest', postLinkPlan.digest], {+ CLAUDE_COORDINATION_TESTING: '1',+ CLAUDE_COORDINATION_TEST_POST_LINK_REPLACE: postLinkRace.paths.manifest,+});+assert.notEqual(postLinkApply.status, 0);+assert.match(postLinkApply.stderr, /PROVISION_RECOVERY_UNCERTAIN/);+assert.deepEqual(readFileSync(postLinkRace.paths.manifest), readFileSync(postLinkRace.manifestSource));+const postLinkJournal = JSON.parse(readFileSync(`${postLinkRace.paths.config}.provision-journal`, 'utf8'));+assert.equal(existsSync(postLinkJournal.ownedTargets[0].proof), true, 'apply mismatch preserves proof');++// Rollback also refuses a same-byte foreign inode after publication and keeps+// the final path, proof, and journal as evidence.+const rollbackForeign = fixture();+const rollbackForeignPlanResult = run(rollbackForeign.args);+const rollbackForeignPlan = JSON.parse(rollbackForeignPlanResult.stdout);+const rollbackForeignPlanPath = join(rollbackForeign.root, 'plan.json');+writeFileSync(rollbackForeignPlanPath, rollbackForeignPlanResult.stdout, { mode: 0o600 });+assert.equal(+ run(['apply', '--plan', rollbackForeignPlanPath, '--expected-digest', rollbackForeignPlan.digest], {+ CLAUDE_COORDINATION_TESTING: '1',+ CLAUDE_COORDINATION_TEST_FAULT: 'SIGKILL:PROVISION_LINKED',+ }).signal,+ 'SIGKILL',+);+const rollbackForeignJournalPath = `${rollbackForeign.paths.config}.provision-journal`;+const rollbackForeignJournal = JSON.parse(readFileSync(rollbackForeignJournalPath, 'utf8'));+unlinkSync(rollbackForeign.paths.manifest);+writeFileSync(rollbackForeign.paths.manifest, readFileSync(rollbackForeign.manifestSource), { mode: 0o600 });+const refusedRollback = run([+ 'rollback',+ '--plan',+ rollbackForeignPlanPath,+ '--expected-digest',+ rollbackForeignPlan.digest,+]);+assert.notEqual(refusedRollback.status, 0);+assert.match(refusedRollback.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));++for (const fault of ['SIGKILL:PROVISION_PRE_LINK', 'SIGKILL:PROVISION_LINKED', 'SIGKILL:PROVISION_LINK_FSYNCED']) {+ const crash = fixture();+ const crashPlanResult = run(crash.args);+ const crashPlan = JSON.parse(crashPlanResult.stdout);+ const crashPlanPath = join(crash.root, 'plan.json');+ writeFileSync(crashPlanPath, crashPlanResult.stdout, { mode: 0o600 });+ const result = run(['apply', '--plan', crashPlanPath, '--expected-digest', crashPlan.digest], {+ CLAUDE_COORDINATION_TESTING: '1',+ CLAUDE_COORDINATION_TEST_FAULT: fault,+ });+ assert.equal(result.signal, 'SIGKILL', fault);+ assert.equal(+ run(['rollback', '--plan', crashPlanPath, '--expected-digest', crashPlan.digest]).status,+ 0,+ `${fault} rollback`,+ );+ assert.equal(existsSync(crash.paths.manifest), false);+}++// COMPLETE proof cleanup is sequential and crash-idempotent: a fresh apply+// authenticates finals whose proof was already removed and finishes cleanup.+const completeCleanup = fixture();+const completePlanResult = run(completeCleanup.args);+const completePlan = JSON.parse(completePlanResult.stdout);+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_TEST_SIGKILL_COMPLETE_PROOF_AFTER: '2',+ }).signal,+ 'SIGKILL',+);+assert.equal(+ run(['apply', '--plan', completePlanPath, '--expected-digest', completePlan.digest]).status,+ 0,+ 'fresh apply completes interrupted COMPLETE proof cleanup',+);+assert.equal(existsSync(`${completeCleanup.paths.config}.provision-journal`), false);++// 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 });+const up = run(upgrade.args);+const upPlan = JSON.parse(up.stdout);+const upPath = join(upgrade.root, 'plan.json');+writeFileSync(upPath, up.stdout);+assert.equal(run(['apply', '--plan', upPath, '--expected-digest', upPlan.digest]).status, 0, 'upgrade');+assert.deepEqual(readFileSync(upgrade.paths.trust), Buffer.alloc(32, 7), 'existing key retained');++// A mismatched pre-existing generated artifact is never overwritten, and an+// already provisioned trust/config plane remains intact for rollback.+writeFileSync(upgrade.paths['linux-unit'], 'operator-owned mismatch\n', { mode: 0o600 });+const mismatch = run(['apply', '--plan', upPath, '--expected-digest', upPlan.digest]);+assert.notEqual(mismatch.status, 0);+assert.equal(readFileSync(upgrade.paths['linux-unit'], 'utf8'), 'operator-owned mismatch\n');+assert.deepEqual(readFileSync(upgrade.paths.trust), Buffer.alloc(32, 7));+assert.equal(existsSync(upgrade.paths.config), true);+console.log('coordination provisioning tests: PASS');diff --git a/claude-ops/scripts/account-rotation/__tests__/credential-file-publication.test.mjs b/claude-ops/scripts/account-rotation/__tests__/credential-file-publication.test.mjsnew file mode 100644index 00000000..306c1d4f--- /dev/null+++ b/claude-ops/scripts/account-rotation/__tests__/credential-file-publication.test.mjs@@ -0,0 +1,134 @@+import assert from 'node:assert/strict';+import {+ chmodSync,+ existsSync,+ linkSync,+ lstatSync,+ mkdtempSync,+ readFileSync,+ readlinkSync,+ readdirSync,+ renameSync,+ symlinkSync,+ unlinkSync,+ writeFileSync,+} from 'node:fs';+import { spawn } from 'node:child_process';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { fileURLToPath } from 'node:url';+import { publishCredentialFileCas, snapshotCredentialFile } from '../credential-file-publication.mjs';++const fixture = () => {+ const root = mkdtempSync(join(tmpdir(), 'credential-cas-disabled-'));+ chmodSync(root, 0o700);+ const path = join(root, 'credentials.json');+ writeFileSync(path, 'old', { mode: 0o600 });+ return { root, path };+};++const pathnameState = (path) => {+ // Test-only snapshot intentionally observes adversarial pathname replacement.+ // CodeQL[js/file-system-race]+ const stat = lstatSync(path, { bigint: true });+ return {+ dev: stat.dev,+ ino: stat.ino,+ birthtimeNs: stat.birthtimeNs,+ mode: stat.mode,+ nlink: stat.nlink,+ size: stat.size,+ symlinkTarget: stat.isSymbolicLink() ? readlinkSync(path) : null,+ bytes: stat.isFile() ? readFileSync(path) : null,+ };+};++const directoryState = (root) =>+ new Map(+ readdirSync(root)+ .sort()+ .map((name) => [name, pathnameState(join(root, name))]),+ );++for (const replacement of [+ 'unchanged',+ 'different',+ 'same-content',+ 'deleted',+ 'delete-recreate',+ 'symlink',+ 'hardlink',+]) {+ const f = fixture();+ const expected = snapshotCredentialFile(f.path);+ if (replacement === 'different' || replacement === 'same-content') {+ const foreign = join(f.root, 'foreign');+ writeFileSync(foreign, replacement === 'different' ? 'foreign' : 'old', { mode: 0o600 });+ renameSync(foreign, f.path);+ } else if (replacement === 'deleted') {+ const moved = join(f.root, 'moved');+ renameSync(f.path, moved);+ } else if (replacement === 'delete-recreate') {+ unlinkSync(f.path);+ writeFileSync(f.path, 'foreign-recreated', { mode: 0o600 });+ } else if (replacement === 'symlink') {+ const moved = join(f.root, 'moved');+ renameSync(f.path, moved);+ symlinkSync(moved, f.path);+ } else if (replacement === 'hardlink') {+ linkSync(f.path, join(f.root, 'alias'));+ }+ const before = directoryState(f.root);+ if (replacement === 'hardlink') {+ assert.equal(before.get('credentials.json').ino, before.get('alias').ino);+ assert.equal(before.get('credentials.json').nlink, 2n);+ }+ assert.throws(+ () => publishCredentialFileCas(f.path, Buffer.from('new'), expected),+ /CREDENTIAL_FILE_PUBLICATION_DISABLED/,+ );+ const after = directoryState(f.root);+ assert.deepEqual(after, before, `${replacement}: pathname descriptors and bytes must be unchanged`);+ if (replacement === 'symlink') {+ assert.equal(lstatSync(f.path).isSymbolicLink(), true);+ assert.equal(readlinkSync(f.path), join(f.root, 'moved'));+ } else if (replacement === 'hardlink') {+ assert.equal(after.get('credentials.json').ino, after.get('alias').ino);+ assert.equal(after.get('credentials.json').nlink, 2n);+ }+}++// Real multiprocess pause after secure snapshot: replacement by another process+// is preserved because publication refuses before creating a temp or touching+// any pathname.+{+ const f = fixture();+ const marker = join(f.root, 'snapshotted');+ const modulePath = fileURLToPath(new URL('../credential-file-publication.mjs', import.meta.url));+ const childSource = `+ import { writeFileSync } from 'node:fs';+ const m = await import(${JSON.stringify(`file://${modulePath}`)});+ const expected = m.snapshotCredentialFile(${JSON.stringify(f.path)});+ writeFileSync(${JSON.stringify(marker)}, 'ready', { mode: 0o600 });+ process.kill(process.pid, 'SIGSTOP');+ try { m.publishCredentialFileCas(${JSON.stringify(f.path)}, Buffer.from('new'), expected); process.exit(7); }+ catch (error) { if (error.message !== 'CREDENTIAL_FILE_PUBLICATION_DISABLED') process.exit(8); }+ `;+ const child = spawn(process.execPath, ['--input-type=module', '--eval', childSource], { stdio: 'ignore' });+ for (let i = 0; i < 500 && !existsSync(marker); i++) await new Promise((resolve) => setTimeout(resolve, 10));+ assert.equal(existsSync(marker), true);+ const foreign = join(f.root, 'foreign');+ writeFileSync(foreign, 'foreign-process', { mode: 0o600 });+ renameSync(foreign, f.path);+ const before = directoryState(f.root);+ process.kill(child.pid, 'SIGCONT');+ const exitCode = await new Promise((resolve) => child.once('exit', resolve));+ assert.equal(exitCode, 0);+ assert.deepEqual(+ directoryState(f.root),+ before,+ 'multiprocess replacement pathname descriptor and bytes must be unchanged',+ );+}++console.log('credential file publication tests: PASS');diff --git a/claude-ops/scripts/account-rotation/__tests__/staged-enrollment.test.mjs b/claude-ops/scripts/account-rotation/__tests__/staged-enrollment.test.mjsnew file mode 100644index 00000000..133376a4--- /dev/null+++ b/claude-ops/scripts/account-rotation/__tests__/staged-enrollment.test.mjs@@ -0,0 +1,2440 @@+#!/usr/bin/env node+import assert from 'node:assert/strict';+import {+ chmodSync,+ existsSync,+ linkSync,+ mkdtempSync,+ mkdirSync,+ readFileSync,+ readdirSync,+ rmdirSync,+ symlinkSync,+ unlinkSync,+ writeFileSync,+} from 'node:fs';+import { tmpdir } from 'node:os';+import { hostname } from 'node:os';+import { join } from 'node:path';+import { spawn, spawnSync } from 'node:child_process';+import { randomUUID } from 'node:crypto';+import {+ activateEnrollment,+ canonicalJson,+ consumeApproval,+ createApprovalPayload,+ parseManifestBytes,+ readDeploymentConfig,+ recoverEnrollment,+ rollbackEnrollment,+ sha256,+ signApproval,+ stageEnrollment,+ validateCandidateBytes,+ verifyApproval,+ withOperationLock,+} from '../staged-enrollment.mjs';+import { automatedAuthAllowed } from '../auto-auth-policy.mjs';+import { reauth } from '../../ops-accounts/providers/claude.mjs';+import { verifyRefreshedTokenIdentity } from '../token-identity.mjs';+import { parseStrictJson } from '../strict-json.mjs';+import { requireWriterCapability, withAuthWriterLock } from '../auth-writer-coordination.mjs';+import { writeRotationTokenCoordinated } from '../rotation-vault.mjs';++const NOW = Date.parse('2030-01-01T00:00:00Z');+const SECRET_VALUES = [+ 'fake-access-token-SECRET',+ 'fake-refresh-token-SECRET',+ 'fake-id-token-SECRET',+ 'oauth-state-SECRET',+ 'oauth-code-SECRET',+ 'magic-link-SECRET',+ 'otp-SECRET',+];+const ENTRY = {+ id: 'claude-example-1',+ authFilename: 'claude-user-1.json',+ provider: 'claude',+ email: '[email protected]',+ organizationUuid: '00000000-0000-4000-8000-000000000001',+ organizationName: 'Example Organization 1',+ accountOwner: 'owner',+};+const claudeEntry = (n) => ({+ ...ENTRY,+ id: `claude-example-${n}`,+ authFilename: `claude-user-${n}.json`,+ email: `user${n}@example.com`,+ organizationUuid: `00000000-0000-4000-8000-${String(n).padStart(12, '0')}`,+ organizationName: `Example Organization ${n}`,+});+const MANIFEST = {+ version: 1,+ entries: [+ ...Array.from({ length: 9 }, (_, i) => claudeEntry(i + 1)),+ {+ id: 'antigravity-1',+ authFilename: 'antigravity-one.json',+ provider: 'antigravity',+ opaque: { preserve: ' byte-for-byte ' },+ },+ ...Array.from({ length: 2 }, (_, i) => ({+ id: `codex-${i + 1}`,+ authFilename: `codex-${i + 1}.json`,+ provider: 'codex',+ metadata: ['untouched', i],+ })),+ ...Array.from({ length: 3 }, (_, i) => ({+ id: `xai-${i + 1}`,+ authFilename: `xai-${i + 1}.json`,+ provider: 'xai',+ anything: { n: i },+ })),+ ],+};+const CANDIDATE = {+ access_token: SECRET_VALUES[0],+ account_uuid: 'account-uuid',+ claude_device_ids: ['a'.repeat(64)],+ disabled: false,+ email: ENTRY.email,+ expired: new Date(NOW + 3_600_000).toISOString(),+ expires_in: 3600,+ id_token: SECRET_VALUES[2],+ last_refresh: new Date(NOW - 1000).toISOString(),+ organization_name: ENTRY.organizationName,+ organization_uuid: ENTRY.organizationUuid,+ refresh_token: SECRET_VALUES[1],+ type: 'claude',+};+const refuses = (fn, code) => assert.throws(fn, new RegExp(code));+const childResult = (child) =>+ new Promise((resolve) => {+ let stdout = '';+ let stderr = '';+ child.stdout?.on('data', (chunk) => (stdout += chunk));+ child.stderr?.on('data', (chunk) => (stderr += chunk));+ child.on('close', (status, signal) => resolve({ status, signal, stdout, stderr }));+ });+const waitFor = async (predicate, label, timeoutMs = 5000) => {+ const deadline = Date.now() + timeoutMs;+ while (!predicate()) {+ if (Date.now() >= deadline) assert.fail(`timed out waiting for ${label}`);+ await new Promise((resolve) => setTimeout(resolve, 10));+ }+};+const childProcessState = (child) =>+ spawnSync('ps', ['-o', 'state=', '-p', String(child.pid)], { encoding: 'utf8' }).stdout.trim();+const waitForStoppedChild = (child, label) => waitFor(() => childProcessState(child) === 'T', label);+const signalChild = (child, signal) => {+ try {+ process.kill(child.pid, signal);+ } catch (error) {+ if (error?.code !== 'ESRCH') throw error;+ }+};++function fixture(format = JSON.stringify(MANIFEST, null, 2)) {+ const root = mkdtempSync(join(tmpdir(), 'staged-enrollment-'));+ const names = ['active', 'quarantine', 'quarantine2', 'staging', 'usage', 'rollback', 'locks'];+ const paths = Object.fromEntries(names.map((name) => [name, join(root, name)]));+ for (const path of Object.values(paths)) mkdirSync(path, { mode: 0o700 });+ const manifestPath = join(root, 'manifest.json');+ const candidatePath = join(root, 'candidate.json');+ const keyPath = join(root, 'approval.key');+ const approvalPath = join(root, 'approval.json');+ const inventoryPath = join(root, 'consumer-inventory.json');+ const authoritativeConsumerInventoryPath = join(root, 'authoritative-consumer-inventory.json');+ const canaryPath = join(root, 'no-fallback-canary.json');+ const configPath = join(root, 'deployment.json');+ writeFileSync(manifestPath, format, { mode: 0o600 });+ writeFileSync(candidatePath, JSON.stringify(CANDIDATE), { mode: 0o600 });+ writeFileSync(keyPath, 'K'.repeat(32), { mode: 0o600 });+ const digest = parseManifestBytes(readFileSync(manifestPath)).digest;+ const candidateDigest = sha256(readFileSync(candidatePath));+ const inventory = {+ version: 1,+ credential: {+ id: ENTRY.id,+ provider: ENTRY.provider,+ email: ENTRY.email,+ organizationUuid: ENTRY.organizationUuid,+ organizationName: ENTRY.organizationName,+ accountOwner: ENTRY.accountOwner,+ destination: ENTRY.authFilename,+ },+ consumers: [{ id: 'canonical-consumer', type: 'cliproxyapi', path: join(paths.active, ENTRY.authFilename) }],+ };+ const authoritativeConsumerInventory = {+ version: 1,+ consumers: inventory.consumers.map((consumer) => ({+ ...consumer,+ credentialId: ENTRY.id,+ destination: ENTRY.authFilename,+ })),+ };+ const canary = {+ version: 1,+ results: inventory.consumers.map((consumer) => ({+ consumerId: consumer.id,+ consumerPath: consumer.path,+ credentialId: ENTRY.id,+ candidateDigest,+ destination: ENTRY.authFilename,+ noFallback: true,+ pass: true,+ })),+ };+ writeFileSync(inventoryPath, JSON.stringify(inventory), { mode: 0o600 });+ writeFileSync(authoritativeConsumerInventoryPath, JSON.stringify(authoritativeConsumerInventory), { mode: 0o600 });+ writeFileSync(canaryPath, JSON.stringify(canary), { mode: 0o600 });+ const config = {+ manifestPath,+ approvalKeyPath: keyPath,+ usageDir: paths.usage,+ stagingDir: paths.staging,+ activeDir: paths.active,+ quarantineDirs: [paths.quarantine, paths.quarantine2],+ rollbackDir: paths.rollback,+ operationLockPath: join(paths.locks, 'operation.lock'),+ environment: 'controlled-test',+ authorizedOperator: 'operator',+ maxApprovalTtlMs: 300_000,+ runtimeInventoryPath: manifestPath,+ runtimeInventoryDigest: sha256(readFileSync(manifestPath)),+ authoritativeConsumerInventoryPath,+ authoritativeConsumerInventoryDigest: sha256(readFileSync(authoritativeConsumerInventoryPath)),+ deploymentPlanDigest: 'd'.repeat(64),+ };+ writeFileSync(configPath, JSON.stringify(config), { mode: 0o600 });+ const approval = (action, changes = {}, clock = {}) => {+ const payload = createApprovalPayload(+ {+ action,+ manifestDigest: digest,+ manifestEntryId: ENTRY.id,+ email: ENTRY.email,+ organizationUuid: ENTRY.organizationUuid,+ organizationName: ENTRY.organizationName,+ accountOwner: ENTRY.accountOwner,+ authorizedOperator: 'operator',+ environment: 'controlled-test',+ candidateDigest,+ oldTargetDigest:+ action === 'activate' && existsSync(join(paths.active, ENTRY.authFilename))+ ? sha256(readFileSync(join(paths.active, ENTRY.authFilename)))+ : null,+ inventoryDigest: action === 'activate' ? sha256(readFileSync(inventoryPath)) : null,+ canaryDigest: action === 'activate' ? sha256(readFileSync(canaryPath)) : null,+ destination: ENTRY.authFilename,+ ...changes,+ },+ { now: clock.now ?? NOW, ttlMs: clock.ttlMs ?? 300_000 },+ );+ const artifact = signApproval(payload, readFileSync(keyPath));+ writeFileSync(approvalPath, JSON.stringify(artifact), { mode: 0o600 });+ return artifact;+ };+ const common = {+ configPath,+ manifestPath,+ entryId: ENTRY.id,+ approvalPath,+ keyPath,+ usageDir: paths.usage,+ stagingDir: paths.staging,+ activeDir: paths.active,+ quarantineDirs: [paths.quarantine, paths.quarantine2],+ rollbackDir: paths.rollback,+ operationLockPath: config.operationLockPath,+ environment: 'controlled-test',+ operator: 'operator',+ maxTtlMs: 300_000,+ now: NOW,+ inventoryPath,+ canaryPath,+ };+ return {+ root,+ paths,+ manifestPath,+ candidatePath,+ keyPath,+ approvalPath,+ inventoryPath,+ authoritativeConsumerInventoryPath,+ canaryPath,+ configPath,+ config,+ digest,+ candidateDigest,+ approval,+ common,+ };+}++function authorizeRollback(f, changes = {}) {+ const recordName = readdirSync(f.paths.rollback).find((name) => name.endsWith('.committed-rollback.json'));+ const recordPath = join(f.paths.rollback, recordName);+ const retained = JSON.parse(readFileSync(recordPath, 'utf8')).payload;+ const payload = {+ version: 1,+ id: `rollback-${randomUUID()}`,+ nonce: `rollback-${randomUUID()}`,+ action: 'canonical-rollback',+ manifestDigest: f.digest,+ manifestEntryId: ENTRY.id,+ email: ENTRY.email,+ organizationUuid: ENTRY.organizationUuid,+ organizationName: ENTRY.organizationName,+ accountOwner: ENTRY.accountOwner,+ authorizedOperator: 'operator',+ environment: 'controlled-test',+ issuedAt: new Date(NOW).toISOString(),+ expiresAt: new Date(NOW + 300_000).toISOString(),+ candidateDigest: retained.candidateDigest,+ oldBackupDigest: retained.oldDigest,+ recordDigest: sha256(readFileSync(recordPath)),+ destination: ENTRY.authFilename,+ ...changes,+ };+ const artifact = signApproval(payload, readFileSync(f.keyPath));+ writeFileSync(f.approvalPath, JSON.stringify(artifact), { mode: 0o600 });+ return artifact;+}++// Duplicate decoded keys are rejected recursively in every trust-record class.+{+ for (const key of ['__proto__', 'constructor', 'prototype']) {+ refuses(+ () => parseStrictJson(`{"safe":{"${key}":{"hidden":"signed-out"}}}`, 'DANGEROUS_JSON_KEY'),+ 'DANGEROUS_JSON_KEY',+ );+ refuses(() => parseStrictJson(`{"${key}":1}`, 'DANGEROUS_JSON_KEY'), 'DANGEROUS_JSON_KEY');+ }+ refuses(() => parseStrictJson(`{"safe":1}\u00a0`, 'NON_JSON_WHITESPACE'), 'NON_JSON_WHITESPACE');+ refuses(() => parseStrictJson(`${'['.repeat(66)}0${']'.repeat(66)}`, 'JSON_DEPTH_EXCEEDED'), 'JSON_DEPTH_EXCEEDED');+ for (const ambiguousNumber of ['1e400', '-1e400', '-0', '9007199254740993'])+ refuses(() => parseStrictJson(ambiguousNumber, 'AMBIGUOUS_JSON_NUMBER'), 'AMBIGUOUS_JSON_NUMBER');+ const safe = parseStrictJson('{"signed":{"visible":1}}');+ assert.equal(Object.getPrototypeOf(safe), null);+ assert.equal(Object.getPrototypeOf(safe.signed), null);+ assert.equal(JSON.stringify(safe), '{"signed":{"visible":1}}');+ for (const dangerous of [+ JSON.parse('{"__proto__":{"hidden":"unsigned"}}'),+ JSON.parse('{"safe":{"constructor":{"hidden":"unsigned"}}}'),+ { safe: { __proto__: { hidden: 'unsigned' } } },+ ])+ refuses(() => canonicalJson(dangerous), 'UNSAFE_CANONICAL_JSON');+ const arrayWithUnsignedKey = [1];+ arrayWithUnsignedKey.authorization = 'unsigned';+ refuses(() => canonicalJson(arrayWithUnsignedKey), 'UNSAFE_CANONICAL_JSON');+ const arrayWithSymbol = [1];+ arrayWithSymbol[Symbol('unsigned')] = true;+ refuses(() => canonicalJson(arrayWithSymbol), 'UNSAFE_CANONICAL_JSON');+ const arrayWithPrototype = [1];+ Object.setPrototypeOf(arrayWithPrototype, null);+ refuses(() => canonicalJson(arrayWithPrototype), 'UNSAFE_CANONICAL_JSON');+ const hidden = { safe: {} };+ Object.defineProperty(hidden.safe, 'hidden', { value: true });+ refuses(() => canonicalJson(hidden), 'UNSAFE_CANONICAL_JSON');+ for (const property of ['get', 'set']) {+ const accessor = { nested: {} };+ Object.defineProperty(accessor.nested, 'value', { enumerable: true, [property]: () => 1 });+ refuses(() => canonicalJson(accessor), 'UNSAFE_CANONICAL_JSON');+ }+ refuses(() => canonicalJson(Array(1)), 'UNSAFE_CANONICAL_JSON');+ const deep = {};+ let cursor = deep;+ for (let index = 0; index < 66; index++) cursor = cursor.next = {};+ refuses(() => canonicalJson(deep), 'UNSAFE_CANONICAL_JSON');+ for (const value of [-0, Number.MAX_SAFE_INTEGER + 1]) refuses(() => canonicalJson(value), 'UNSAFE_CANONICAL_JSON');+ refuses(() => parseManifestBytes('{"version":1,"\\u0065ntries":[],"entries":[]}'), 'INVALID_MANIFEST');+ refuses(+ () =>+ validateCandidateBytes(+ JSON.stringify(CANDIDATE).replace('"access_token":', '"access_token":"x","\\u0061ccess_token":'),+ ENTRY,+ NOW,+ ),+ 'INVALID_CANDIDATE',+ );+ const f = fixture();+ writeFileSync(f.configPath, `${JSON.stringify(f.config).slice(0, -1)},"\\u0065nvironment":"duplicate"}`, {+ mode: 0o600,+ });+ refuses(() => readDeploymentConfig(f.configPath), 'INVALID_CONFIG');+}++// Every remaining trust-record parser rejects escaped duplicate keys nested in+// its authenticated payload, and reports that record's stable error code.+{+ const duplicate = (+ artifact,+ key,+ escapedKey = `\\u${key.charCodeAt(0).toString(16).padStart(4, '0')}${key.slice(1)}`,+ ) =>+ JSON.stringify(artifact).replace(`"${key}":`, `"${key}":${JSON.stringify(artifact.payload[key])},"${escapedKey}":`);++ const approval = fixture();+ const approvalArtifact = approval.approval('stage');+ writeFileSync(approval.approvalPath, duplicate(approvalArtifact, 'action'), { mode: 0o600 });+ refuses(() => stageEnrollment({ ...approval.common, candidatePath: approval.candidatePath }), 'INVALID_APPROVAL');++ const active = fixture();+ active.approval('stage');+ stageEnrollment({ ...active.common, candidatePath: active.candidatePath });+ const activeTarget = JSON.stringify(CANDIDATE).replace(+ '"claude_device_ids":',+ '"claude_device_ids":["nested"],"\\u0063laude_device_ids":',+ );+ writeFileSync(join(active.paths.active, ENTRY.authFilename), activeTarget, { mode: 0o600 });+ active.approval('activate');+ refuses(() => activateEnrollment(active.common), 'INVALID_ACTIVE_TARGET');++ const inventory = fixture();+ writeFileSync(+ join(inventory.paths.quarantine, 'nested.json'),+ JSON.stringify(CANDIDATE).replace('"email":', '"email":"[email protected]","\\u0065mail":'),+ { mode: 0o600 },+ );+ inventory.approval('stage');+ refuses(+ () => stageEnrollment({ ...inventory.common, candidatePath: inventory.candidatePath }),+ 'MALFORMED_INVENTORY',+ );++ const signedDuplicate = (payload, key, signingKey) => duplicate(signApproval(payload, signingKey), key);+ const processRecord = {+ version: 1,+ host: hostname(),+ pid: 2_147_483_647,+ nonce: 'valid-lock-nonce',+ createdAt: new Date().toISOString(),+ };+ const lock = fixture();+ writeFileSync(lock.common.operationLockPath, signedDuplicate(processRecord, 'nonce', readFileSync(lock.keyPath)), {+ mode: 0o600,+ });+ refuses(() => withOperationLock(lock.common.operationLockPath, lock.keyPath, () => {}), 'OPERATION_LOCKED_MALFORMED');++ const claim = fixture();+ writeFileSync(+ claim.common.operationLockPath,+ JSON.stringify(signApproval(processRecord, readFileSync(claim.keyPath))),+ { mode: 0o600 },+ );+ const claimPayload = { ...processRecord, nonce: 'valid-claim-nonce', lockNonce: processRecord.nonce };+ writeFileSync(+ `${claim.common.operationLockPath}.recovery-claim`,+ signedDuplicate(claimPayload, 'lockNonce', readFileSync(claim.keyPath)),+ { mode: 0o600 },+ );+ refuses(() => withOperationLock(claim.common.operationLockPath, claim.keyPath, () => {}), 'RECOVERY_CLAIM_MALFORMED');++ const journal = fixture();+ const journalPayload = { version: 1, phase: 'PREPARING' };+ writeFileSync(+ `${journal.common.operationLockPath}.journal`,+ signedDuplicate(journalPayload, 'phase', readFileSync(journal.keyPath)),+ { mode: 0o600 },+ );+ refuses(() => recoverEnrollment({ configPath: journal.configPath }), 'INVALID_ACTIVATION_JOURNAL');++ const marker = fixture();+ const markerPayload = { version: 1, approvalId: 'approval-id', nonce: 'approval-nonce', action: 'additive-publish' };+ writeFileSync(+ join(marker.paths.usage, 'approval-id.approval-nonce.used'),+ signedDuplicate(markerPayload, 'action', readFileSync(marker.keyPath)),+ {+ mode: 0o600,+ },+ );+ refuses(+ () =>+ consumeApproval(+ { id: 'approval-id', nonce: 'approval-nonce', action: 'additive-publish' },+ marker.paths.usage,+ marker.keyPath,+ ),+ 'INVALID_USE_MARKER',+ );++ const publication = fixture();+ const publicationPath = `${publication.common.operationLockPath}.publication`;+ const publicationPayload = {+ version: 1,+ kind: 'stage',+ stagedPath: join(publication.paths.staging, ENTRY.authFilename),+ stagingDigest: publication.candidateDigest,+ markerPath: join(publication.paths.usage, 'approval-id.approval-nonce.used'),+ approvalId: 'approval-id',+ approvalNonce: 'approval-nonce',+ };+ writeFileSync(publicationPath, signedDuplicate(publicationPayload, 'kind', readFileSync(publication.keyPath)), {+ mode: 0o600,+ });+ publication.approval('stage');+ refuses(+ () => stageEnrollment({ ...publication.common, candidatePath: publication.candidatePath }),+ 'INVALID_PUBLICATION_RECORD',+ );+}++// File roles reject hardlink aliases, not merely symlinks and textual overlap.+for (const role of ['manifest', 'key', 'candidate', 'approval']) {+ const f = fixture();+ f.approval('stage');+ const source =+ role === 'manifest'+ ? f.manifestPath+ : role === 'key'+ ? f.keyPath+ : role === 'candidate'+ ? f.candidatePath+ : f.approvalPath;+ const alias = join(f.root, `${role}.hardlink`);+ linkSync(source, alias);+ if (role === 'manifest' || role === 'key') {+ const field = role === 'manifest' ? 'manifestPath' : 'approvalKeyPath';+ writeFileSync(f.configPath, JSON.stringify({ ...f.config, [field]: alias }), { mode: 0o600 });+ refuses(() => readDeploymentConfig(f.configPath), 'INSECURE_TRUST_ROOT');+ } else {+ refuses(+ () =>+ stageEnrollment({+ ...f.common,+ candidatePath: role === 'candidate' ? alias : f.candidatePath,+ approvalPath: role === 'approval' ? alias : f.approvalPath,+ }),+ 'INSECURE_TRUST_ROOT|INVALID_APPROVAL',+ );+ }+}++// Lock records are authenticated; only same-host dead-PID holders are reclaimed.+{+ const makeLock = (f, fields, key = readFileSync(f.keyPath)) =>+ writeFileSync(f.common.operationLockPath, `${JSON.stringify(signApproval(fields, key))}\n`, { mode: 0o600 });+ const base = {+ version: 1,+ host: hostname(),+ pid: process.pid,+ nonce: 'lock-nonce',+ createdAt: new Date().toISOString(),+ };+ for (const fields of [{ ...base }, { ...base, host: 'foreign-host.invalid', pid: 2147483647 }]) {+ const f = fixture();+ makeLock(f, fields);+ refuses(() => withOperationLock(f.common.operationLockPath, f.keyPath, () => {}), 'OPERATION_LOCKED');+ }+ const forged = fixture();+ makeLock(forged, { ...base, pid: 2147483647 }, Buffer.from('Z'.repeat(32)));+ refuses(+ () => withOperationLock(forged.common.operationLockPath, forged.keyPath, () => {}),+ 'OPERATION_LOCKED_MALFORMED',+ );+ const stale = fixture();+ makeLock(stale, { ...base, pid: 2147483647 });+ assert.equal(+ withOperationLock(stale.common.operationLockPath, stale.keyPath, () => 'reclaimed'),+ 'reclaimed',+ );+ assert.equal(existsSync(stale.common.operationLockPath), false);++ for (const suffix of ['.journal', '.publication']) {+ const pending = fixture();+ makeLock(pending, { ...base, pid: 2147483647 });+ writeFileSync(`${pending.common.operationLockPath}${suffix}`, '{}\n', { mode: 0o600 });+ const callbackMarker = join(pending.root, `callback-${suffix.slice(1)}`);+ refuses(+ () =>+ withOperationLock(pending.common.operationLockPath, pending.keyPath, () => {+ writeFileSync(callbackMarker, 'unsafe');+ }),+ suffix === '.journal' ? 'PENDING_ACTIVATION_JOURNAL' : 'PENDING_APPROVAL_PUBLICATION',+ );+ assert.equal(existsSync(callbackMarker), false, `${suffix} was rechecked after stale reclaim`);+ }+}++// A pending journal published only after stale-lock replacement is still+// observed under ownership; the callback never runs after SIGCONT.+{+ const f = fixture();+ const stale = {+ version: 1,+ host: hostname(),+ pid: 2147483647,+ nonce: 'stale-race-nonce',+ createdAt: new Date().toISOString(),+ };+ writeFileSync(f.common.operationLockPath, `${JSON.stringify(signApproval(stale, readFileSync(f.keyPath)))}\n`, {+ mode: 0o600,+ });+ const marker = join(f.root, 'stale-reclaim-callback');+ const modulePath = join(import.meta.dirname, '..', 'staged-enrollment.mjs');+ const child = spawn(+ process.execPath,+ [+ '--input-type=module',+ '-e',+ // Inputs are test-created absolute paths serialized as JS literals.+ // lgtm[js/bad-code-sanitization]+ `import(${JSON.stringify(`file://${modulePath}`)}).then(m=>m.withOperationLock(${JSON.stringify(f.common.operationLockPath)},${JSON.stringify(f.keyPath)},()=>require('node:fs').writeFileSync(${JSON.stringify(marker)},'unsafe')))`,+ ],+ {+ env: {+ ...process.env,+ CLAUDE_STAGED_ENROLLMENT_TESTING: '1',+ CLAUDE_STAGED_ENROLLMENT_TEST_FAULT: 'SIGSTOP:LOCK_REPLACEMENT_PUBLISHED',+ },+ stdio: ['ignore', 'pipe', 'pipe'],+ },+ );+ const resultPromise = childResult(child);+ let result;+ try {+ await waitFor(() => {+ try {+ return JSON.parse(readFileSync(f.common.operationLockPath, 'utf8')).payload.pid === child.pid;+ } catch {+ return false;+ }+ }, 'replacement lock publication');+ await waitForStoppedChild(child, 'replacement-lock fault stop');+ writeFileSync(`${f.common.operationLockPath}.journal`, '{}\n', { mode: 0o600 });+ signalChild(child, 'SIGCONT');+ result = await resultPromise;+ } finally {+ signalChild(child, 'SIGCONT');+ signalChild(child, 'SIGTERM');+ }+ assert.notEqual(result.status, 0);+ assert.match(result.stderr, /PENDING_ACTIVATION_JOURNAL/);+ assert.equal(existsSync(marker), false);+}++// Signed-but-malformed lock metadata is never treated as a reclaimable dead process.+for (const mutation of [+ { version: 2 },+ { pid: 0 },+ { pid: -1 },+ { pid: 2_147_483_648 },+ { nonce: '' },+ { nonce: 'short' },+ { nonce: 'x'.repeat(129) },+ { createdAt: 'not-a-time' },+]) {+ const f = fixture();+ const holder = {+ version: 1,+ host: hostname(),+ pid: 2_147_483_647,+ nonce: 'valid-lock-nonce',+ createdAt: new Date().toISOString(),+ ...mutation,+ };+ writeFileSync(f.common.operationLockPath, `${JSON.stringify(signApproval(holder, readFileSync(f.keyPath)))}\n`, {+ mode: 0o600,+ });+ refuses(() => withOperationLock(f.common.operationLockPath, f.keyPath, () => {}), 'OPERATION_LOCKED_MALFORMED');+}++// Recovery claims are independently authenticated and process-bound. Signed+// malformed metadata, forged HMACs, live/foreign claimants, and lock-nonce+// mismatches never authorize reclaim; a valid dead claimant does.+{+ const install = (f, claimChanges, claimKey = readFileSync(f.keyPath)) => {+ const key = readFileSync(f.keyPath);+ const holder = {+ version: 1,+ host: hostname(),+ pid: 2_147_483_647,+ nonce: 'stale-lock-nonce',+ createdAt: new Date().toISOString(),+ };+ writeFileSync(f.common.operationLockPath, JSON.stringify(signApproval(holder, key)), { mode: 0o600 });+ const claim = {+ version: 1,+ host: hostname(),+ pid: 2_147_483_647,+ nonce: 'stale-claim-nonce',+ lockNonce: holder.nonce,+ createdAt: new Date().toISOString(),+ ...claimChanges,+ };+ writeFileSync(`${f.common.operationLockPath}.recovery-claim`, JSON.stringify(signApproval(claim, claimKey)), {+ mode: 0o600,+ });+ };+ for (const mutation of [+ { pid: 0 },+ { pid: 1.5 },+ { createdAt: 'not-a-time' },+ { nonce: 'short' },+ { lockNonce: 'short' },+ ]) {+ const f = fixture();+ install(f, mutation);+ refuses(() => withOperationLock(f.common.operationLockPath, f.keyPath, () => {}), 'RECOVERY_CLAIM_MALFORMED');+ }+ const forged = fixture();+ install(forged, {}, Buffer.from('Z'.repeat(32)));+ refuses(+ () => withOperationLock(forged.common.operationLockPath, forged.keyPath, () => {}),+ 'RECOVERY_CLAIM_MALFORMED',+ );+ for (const claimant of [{ pid: process.pid }, { host: 'foreign-host.invalid' }]) {+ const f = fixture();+ install(f, claimant);+ refuses(() => withOperationLock(f.common.operationLockPath, f.keyPath, () => {}), 'OPERATION_LOCKED');+ }+ const dead = fixture();+ install(dead, {});+ assert.equal(+ withOperationLock(dead.common.operationLockPath, dead.keyPath, () => 'recovered'),+ 'recovered',+ );+ assert.equal(existsSync(`${dead.common.operationLockPath}.recovery-claim`), false);+}++// Three fresh processes prove that a claimant killed after old-lock removal+// cannot wedge reclaim of a later holder: the orphan is authenticated and+// judged dead independently of its older lock nonce.+{+ const f = fixture();+ const holder = {+ version: 1,+ host: hostname(),+ pid: 2_147_483_647,+ nonce: 'orphan-claim-old-lock',+ createdAt: new Date().toISOString(),+ };+ writeFileSync(f.common.operationLockPath, JSON.stringify(signApproval(holder, readFileSync(f.keyPath))), {+ mode: 0o600,+ });+ const modulePath = join(import.meta.dirname, '..', 'staged-enrollment.mjs');+ const lockCall = `m.withOperationLock(${JSON.stringify(f.common.operationLockPath)},${JSON.stringify(f.keyPath)},()=>process.kill(process.pid,"SIGKILL"))`;+ const first = spawnSync(+ process.execPath,+ ['--input-type=module', '-e', `import(${JSON.stringify(`file://${modulePath}`)}).then(m=>${lockCall})`],+ {+ encoding: 'utf8',+ env: {+ ...process.env,+ CLAUDE_STAGED_ENROLLMENT_TESTING: '1',+ CLAUDE_STAGED_ENROLLMENT_TEST_FAULT: 'SIGKILL:OLD_LOCK_UNLINKED',+ },+ },+ );+ assert.equal(first.signal, 'SIGKILL', first.stderr);+ assert.equal(existsSync(f.common.operationLockPath), false);+ assert.equal(existsSync(`${f.common.operationLockPath}.recovery-claim`), true);+ const second = spawnSync(+ process.execPath,+ ['--input-type=module', '-e', `import(${JSON.stringify(`file://${modulePath}`)}).then(m=>${lockCall})`],+ { encoding: 'utf8' },+ );+ assert.equal(second.signal, 'SIGKILL', second.stderr);+ assert.equal(existsSync(f.common.operationLockPath), true);+ const thirdScript = `import(${JSON.stringify(`file://${modulePath}`)}).then(m=>process.stdout.write(m.withOperationLock(${JSON.stringify(f.common.operationLockPath)},${JSON.stringify(f.keyPath)},()=>"reclaimed")))`;+ const third = spawnSync(process.execPath, ['--input-type=module', '-e', thirdScript], { encoding: 'utf8' });+ assert.equal(third.status, 0, third.stderr);+ assert.equal(third.stdout, 'reclaimed');+ assert.equal(existsSync(`${f.common.operationLockPath}.recovery-claim`), false);+}++// Two real processes racing to reclaim one stale lock cannot both enter the+// critical section. The winner holds the replacement lock while the loser probes.+{+ const f = fixture();+ const holder = {+ version: 1,+ host: hostname(),+ pid: 2_147_483_647,+ nonce: 'competing-stale-lock',+ createdAt: new Date().toISOString(),+ };+ writeFileSync(f.common.operationLockPath, JSON.stringify(signApproval(holder, readFileSync(f.keyPath))), {+ mode: 0o600,+ });+ const modulePath = join(import.meta.dirname, '..', 'staged-enrollment.mjs');+ const script = `import(${JSON.stringify(`file://${modulePath}`)}).then(m=>m.withOperationLock(${JSON.stringify(f.common.operationLockPath)},${JSON.stringify(f.keyPath)},()=>Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,400)))`;+ const first = spawn(process.execPath, ['--input-type=module', '-e', script], { stdio: ['ignore', 'pipe', 'pipe'] });+ const second = spawn(process.execPath, ['--input-type=module', '-e', script], { stdio: ['ignore', 'pipe', 'pipe'] });+ const results = await Promise.all([childResult(first), childResult(second)]);+ assert.equal(results.filter((result) => result.status === 0).length, 1, JSON.stringify(results));+ assert.equal(results.filter((result) => /OPERATION_LOCKED/.test(result.stderr)).length, 1, JSON.stringify(results));+}++// A reclaimer killed after replacement publication leaves no claim wedge; a+// fresh process reclaims the replacement lock owned by the dead child.+{+ const f = fixture();+ const holder = {+ version: 1,+ host: hostname(),+ pid: 2_147_483_647,+ nonce: 'crash-boundary-lock',+ createdAt: new Date().toISOString(),+ };+ writeFileSync(f.common.operationLockPath, JSON.stringify(signApproval(holder, readFileSync(f.keyPath))), {+ mode: 0o600,+ });+ const modulePath = join(import.meta.dirname, '..', 'staged-enrollment.mjs');+ const childScript = `import(${JSON.stringify(`file://${modulePath}`)}).then(m=>m.withOperationLock(${JSON.stringify(f.common.operationLockPath)},${JSON.stringify(f.keyPath)},()=>{}))`;+ const killed = spawnSync(process.execPath, ['--input-type=module', '-e', childScript], {+ encoding: 'utf8',+ env: {+ ...process.env,+ CLAUDE_STAGED_ENROLLMENT_TESTING: '1',+ CLAUDE_STAGED_ENROLLMENT_TEST_FAULT: 'SIGKILL:LOCK_REPLACEMENT_PUBLISHED',+ },+ });+ assert.equal(killed.signal, 'SIGKILL', killed.stderr);+ assert.equal(existsSync(`${f.common.operationLockPath}.recovery-claim`), false);+ const recoveryScript = `import(${JSON.stringify(`file://${modulePath}`)}).then(m=>process.stdout.write(m.withOperationLock(${JSON.stringify(f.common.operationLockPath)},${JSON.stringify(f.keyPath)},()=>"reclaimed")))`;+ const recovered = spawnSync(process.execPath, ['--input-type=module', '-e', recoveryScript], { encoding: 'utf8' });+ assert.equal(recovered.status, 0, recovered.stderr);+ assert.equal(recovered.stdout, 'reclaimed');+}++// Existing destinations are exact-schema and identity checked before approval use.+for (const existing of [+ { ...CANDIDATE, type: 'codex' },+ { ...CANDIDATE, email: '[email protected]' },+ { ...CANDIDATE, extra: 'forbidden' },+ { ...CANDIDATE, disabled: 'false' },+ { ...CANDIDATE, access_token: '' },+ { ...CANDIDATE, claude_device_ids: ['bad-device'] },+ { ...CANDIDATE, organization_name: 42 },+]) {+ const f = fixture();+ f.approval('stage');+ stageEnrollment({ ...f.common, candidatePath: f.candidatePath });+ writeFileSync(join(f.paths.active, ENTRY.authFilename), JSON.stringify(existing), { mode: 0o600 });+ const approval = f.approval('activate');+ refuses(() => activateEnrollment(f.common), 'INVALID_ACTIVE_TARGET|ACTIVE_TARGET_IDENTITY_MISMATCH');+ assert.equal(existsSync(join(f.paths.usage, `${approval.payload.id}.${approval.payload.nonce}.used`)), false);+}+{+ const f = fixture();+ f.approval('stage');+ stageEnrollment({ ...f.common, candidatePath: f.candidatePath });+ writeFileSync(+ join(f.paths.active, ENTRY.authFilename),+ JSON.stringify({ ...CANDIDATE, expired: '2020-01-01T00:00:00Z' }),+ { mode: 0o600 },+ );+ f.approval('activate');+ assert.equal(activateEnrollment(f.common).ok, true);+}++// Recovery with no journal is idempotent and leaves no lock behind.+{+ const f = fixture();+ assert.deepEqual(recoverEnrollment({ configPath: f.configPath }), { ok: true, action: 'recover', recovered: false });+ assert.deepEqual(recoverEnrollment({ configPath: f.configPath }), { ok: true, action: 'recover', recovered: false });+}++// Fresh processes recover authenticated journals after SIGKILL at each+// irreversible boundary; committed recovery retains authenticated rollback.+for (const phase of [+ 'PREPARING',+ 'BACKUP_CREATE_INTENT',+ 'BACKUP_CREATED',+ 'PREPARED',+ 'APPROVAL_INTENT',+ 'APPROVAL_CONSUMED',+ 'INSTALL_INTENT',+ 'INSTALLED',+ 'COMMITTED',+]) {+ const f = fixture();+ f.approval('stage');+ stageEnrollment({ ...f.common, candidatePath: f.candidatePath });+ const target = join(f.paths.active, ENTRY.authFilename);+ const old = JSON.stringify({ ...CANDIDATE, access_token: `old-${phase}` });+ writeFileSync(target, old, { mode: 0o600 });+ f.approval('activate');+ const modulePath = join(import.meta.dirname, '..', 'staged-enrollment.mjs');+ const childScript = `import(${JSON.stringify(`file://${modulePath}`)}).then(m=>m.activateEnrollment(${JSON.stringify({ ...f.common, configPath: f.configPath, now: NOW })}))`;+ const killed = spawnSync(process.execPath, ['--input-type=module', '-e', childScript], {+ encoding: 'utf8',+ env: {+ ...process.env,+ CLAUDE_STAGED_ENROLLMENT_TESTING: '1',+ CLAUDE_STAGED_ENROLLMENT_TEST_FAULT: `SIGKILL:${phase}`,+ },+ });+ assert.equal(killed.signal, 'SIGKILL', `${phase}: ${killed.stderr}`);+ 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, `${phase}: ${recovered.stderr}`);+ 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);+ if (phase === 'COMMITTED') {+ const beforeRollback = readFileSync(target);+ const rolledBack = spawnSync(+ process.execPath,+ [modulePath, 'rollback', '--config', f.configPath, '--entry', ENTRY.id],+ { encoding: 'utf8' },+ );+ 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');+ }+ const again = recoverEnrollment({ configPath: f.configPath });+ assert.equal(again.recovered, false);+}++// Recovery never removes or replaces an unjournaled active occupant, even if+// another writer copied the exact candidate bytes into a different inode.+{+ const f = fixture();+ f.approval('stage');+ stageEnrollment({ ...f.common, candidatePath: f.candidatePath });+ const target = join(f.paths.active, ENTRY.authFilename);+ const old = JSON.stringify({ ...CANDIDATE, access_token: 'old-before-foreign-replace' });+ writeFileSync(target, old, { mode: 0o600 });+ f.approval('activate');+ const modulePath = join(import.meta.dirname, '..', 'staged-enrollment.mjs');+ const childScript = `import(${JSON.stringify(`file://${modulePath}`)}).then(m=>m.activateEnrollment(${JSON.stringify({ ...f.common, now: NOW })}))`;+ const killed = spawnSync(process.execPath, ['--input-type=module', '-e', childScript], {+ encoding: 'utf8',+ env: {+ ...process.env,+ CLAUDE_STAGED_ENROLLMENT_TESTING: '1',+ CLAUDE_STAGED_ENROLLMENT_TEST_FAULT: 'SIGKILL:INSTALLED',+ },+ });+ assert.equal(killed.signal, 'SIGKILL', killed.stderr);+ linkSync(target, join(f.root, 'foreign-held-original-inode'));+ unlinkSync(target);+ writeFileSync(target, old, { mode: 0o600 });+ refuses(() => recoverEnrollment({ configPath: f.configPath }), 'ACTIVATION_RECOVERY_UNCERTAIN');+ assert.equal(readFileSync(target, 'utf8'), old);+ assert.equal(readdirSync(f.paths.rollback).length, 1, 'exact journal-owned backup preserved');+}++// Backup-open crash is recoverable from authenticated creation intent.+{+ const f = fixture();+ f.approval('stage');+ stageEnrollment({ ...f.common, candidatePath: f.candidatePath });+ const target = join(f.paths.active, ENTRY.authFilename);+ const old = JSON.stringify({ ...CANDIDATE, access_token: 'backup-open-old' });+ writeFileSync(target, old, { mode: 0o600 });+ f.approval('activate');+ const modulePath = join(import.meta.dirname, '..', 'staged-enrollment.mjs');+ const killed = spawnSync(+ process.execPath,+ [+ '--input-type=module',+ '-e',+ `import(${JSON.stringify(`file://${modulePath}`)}).then(m=>m.activateEnrollment(${JSON.stringify({ ...f.common, now: NOW })}))`,+ ],+ {+ encoding: 'utf8',+ env: {+ ...process.env,+ CLAUDE_STAGED_ENROLLMENT_TESTING: '1',+ CLAUDE_STAGED_ENROLLMENT_TEST_FAULT: 'SIGKILL:BACKUP_OPENED',+ },+ },+ );+ 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), []);+}++// Recovery is bound to the authenticated raw M0 digest and complete entry+// snapshot in the journal; a later M1 is neither trusted nor a recovery wedge.+{+ const f = fixture();+ f.approval('stage');+ stageEnrollment({ ...f.common, candidatePath: f.candidatePath });+ const target = join(f.paths.active, ENTRY.authFilename);+ const staged = join(f.paths.staging, ENTRY.authFilename);+ const old = JSON.stringify({ ...CANDIDATE, access_token: 'manifest-swap-old' });+ writeFileSync(target, old, { mode: 0o600 });+ f.approval('activate');+ const modulePath = join(import.meta.dirname, '..', 'staged-enrollment.mjs');+ const activation = spawnSync(+ process.execPath,+ [+ '--input-type=module',+ '-e',+ `import(${JSON.stringify(`file://${modulePath}`)}).then(m=>m.activateEnrollment(${JSON.stringify({ ...f.common, now: NOW })}))`,+ ],+ {+ encoding: 'utf8',+ env: {+ ...process.env,+ CLAUDE_STAGED_ENROLLMENT_TESTING: '1',+ CLAUDE_STAGED_ENROLLMENT_TEST_FAULT: 'SIGKILL:PREPARED',+ },+ },+ );+ assert.equal(activation.signal, 'SIGKILL', activation.stderr);+ const m0 = readFileSync(f.manifestPath);+ const m1 = Buffer.concat([m0, Buffer.from('\n')]);+ writeFileSync(f.manifestPath, m1);+ assert.equal(recoverEnrollment({ configPath: f.configPath }).outcome, 'rolled-back');+ assert.equal(readFileSync(target, 'utf8'), old);+ assert.deepEqual(JSON.parse(readFileSync(staged, 'utf8')), CANDIDATE);+ assert.equal(existsSync(`${f.common.operationLockPath}.journal`), false);+ assert.deepEqual(readFileSync(f.manifestPath), m1, 'recovery does not reinterpret or replace M1');+}++// A live unfenced M0→M1 replacement after installation but before commit is+// observed by the post-install CAS and rolls the credential back.+{+ const f = fixture();+ f.approval('stage');+ stageEnrollment({ ...f.common, candidatePath: f.candidatePath });+ const target = join(f.paths.active, ENTRY.authFilename);+ const staged = join(f.paths.staging, ENTRY.authFilename);+ const old = JSON.stringify({ ...CANDIDATE, access_token: 'live-manifest-race-old' });+ writeFileSync(target, old, { mode: 0o600 });+ f.approval('activate');+ const modulePath = join(import.meta.dirname, '..', 'staged-enrollment.mjs');+ const activation = spawn(+ process.execPath,+ [+ '--input-type=module',+ '-e',+ `import(${JSON.stringify(`file://${modulePath}`)}).then(m=>m.activateEnrollment(${JSON.stringify({ ...f.common, now: NOW })}))`,+ ],+ {+ env: {+ ...process.env,+ CLAUDE_STAGED_ENROLLMENT_TESTING: '1',+ CLAUDE_STAGED_ENROLLMENT_TEST_FAULT: 'SIGSTOP:INSTALLED',+ },+ stdio: ['ignore', 'pipe', 'pipe'],+ },+ );+ const resultPromise = childResult(activation);+ let result;+ try {+ await waitFor(() => {+ try {+ return JSON.parse(readFileSync(`${f.common.operationLockPath}.journal`, 'utf8')).payload.phase === 'INSTALLED';+ } catch {+ return false;+ }+ }, 'installed journal');+ await waitForStoppedChild(activation, 'installed fault stop');+ writeFileSync(f.manifestPath, Buffer.concat([readFileSync(f.manifestPath), Buffer.from('\n')]));+ signalChild(activation, 'SIGCONT');+ result = await resultPromise;+ } finally {+ signalChild(activation, 'SIGCONT');+ signalChild(activation, 'SIGTERM');+ }+ assert.notEqual(result.status, 0);+ assert.match(result.stderr, /ACTIVATION_ROLLED_BACK/);+ assert.equal(readFileSync(target, 'utf8'), old);+ assert.deepEqual(JSON.parse(readFileSync(staged, 'utf8')), CANDIDATE);+}++// A first-party manifest publisher shares the canonical lock and cannot enter+// the final-CAS-to-COMMITTED interval.+{+ const f = fixture();+ f.approval('stage');+ stageEnrollment({ ...f.common, candidatePath: f.candidatePath });+ f.approval('activate');+ const modulePath = join(import.meta.dirname, '..', 'staged-enrollment.mjs');+ const activation = spawn(+ process.execPath,+ [+ '--input-type=module',+ '-e',+ `import(${JSON.stringify(`file://${modulePath}`)}).then(m=>m.activateEnrollment(${JSON.stringify({ ...f.common, now: NOW })}))`,+ ],+ {+ env: {+ ...process.env,+ CLAUDE_STAGED_ENROLLMENT_TESTING: '1',+ CLAUDE_STAGED_ENROLLMENT_TEST_FAULT: 'SIGSTOP:MANIFEST_CAS_VERIFIED',+ },+ stdio: ['ignore', 'pipe', 'pipe'],+ },+ );+ const activationResult = childResult(activation);+ try {+ await waitForStoppedChild(activation, 'post-manifest-CAS fault stop');+ const publisher = spawnSync(+ process.execPath,+ [+ '--input-type=module',+ '-e',+ // Inputs are test-created absolute paths serialized as JS literals.+ // lgtm[js/bad-code-sanitization]+ `import(${JSON.stringify(`file://${join(import.meta.dirname, '..', 'auth-writer-coordination.mjs')}`)}).then(m=>m.withAuthWriterLock(()=>require('node:fs').appendFileSync(${JSON.stringify(f.manifestPath)},'\\n'),{configPath:${JSON.stringify(f.configPath)}}))`,+ ],+ { encoding: 'utf8' },+ );+ assert.notEqual(publisher.status, 0);+ assert.match(publisher.stderr, /OPERATION_LOCKED|PENDING_ACTIVATION_JOURNAL/);+ assert.deepEqual(readFileSync(f.manifestPath), Buffer.from(JSON.stringify(MANIFEST, null, 2)));+ signalChild(activation, 'SIGCONT');+ const activated = await activationResult;+ assert.equal(activated.status, 0, activated.stderr);+ } finally {+ signalChild(activation, 'SIGCONT');+ signalChild(activation, 'SIGTERM');+ }+}++// Fresh-process rollback recovery is idempotent when killed immediately after+// its rename or after the first of the two required directory fsyncs.+for (const fault of ['SIGKILL:RECOVERY_ROLLBACK_RENAMED', 'SIGKILL:RECOVERY_ROLLBACK_FIRST_DIR_FSYNC']) {+ const f = fixture();+ f.approval('stage');+ stageEnrollment({ ...f.common, candidatePath: f.candidatePath });+ const target = join(f.paths.active, ENTRY.authFilename);+ const old = JSON.stringify({ ...CANDIDATE, access_token: `old-${fault}` });+ writeFileSync(target, old, { mode: 0o600 });+ f.approval('activate');+ const modulePath = join(import.meta.dirname, '..', 'staged-enrollment.mjs');+ const activateScript = `import(${JSON.stringify(`file://${modulePath}`)}).then(m=>m.activateEnrollment(${JSON.stringify({ ...f.common, now: NOW })}))`;+ const activation = spawnSync(process.execPath, ['--input-type=module', '-e', activateScript], {+ encoding: 'utf8',+ env: {+ ...process.env,+ CLAUDE_STAGED_ENROLLMENT_TESTING: '1',+ CLAUDE_STAGED_ENROLLMENT_TEST_FAULT: 'SIGKILL:INSTALLED',+ },+ });+ assert.equal(activation.signal, 'SIGKILL', activation.stderr);+ const recoveryScript = `import(${JSON.stringify(`file://${modulePath}`)}).then(m=>process.stdout.write(JSON.stringify(m.recoverEnrollment({configPath:${JSON.stringify(f.configPath)}}))))`;+ const interrupted = spawnSync(process.execPath, ['--input-type=module', '-e', recoveryScript], {+ encoding: 'utf8',+ env: {+ ...process.env,+ CLAUDE_STAGED_ENROLLMENT_TESTING: '1',+ CLAUDE_STAGED_ENROLLMENT_TEST_FAULT: fault,+ },+ });+ assert.equal(interrupted.signal, 'SIGKILL', `${fault}: ${interrupted.stderr}`);+ const recovered = spawnSync(process.execPath, ['--input-type=module', '-e', recoveryScript], { encoding: 'utf8' });+ assert.equal(recovered.status, 0, `${fault}: ${recovered.stderr}`);+ assert.equal(JSON.parse(recovered.stdout).outcome, 'rolled-back');+ assert.equal(readFileSync(target, 'utf8'), old);+ const again = spawnSync(process.execPath, ['--input-type=module', '-e', recoveryScript], { encoding: 'utf8' });+ assert.equal(again.status, 0, again.stderr);+ assert.equal(JSON.parse(again.stdout).recovered, false);+}++// Post-consumption journals without their exact marker are uncertain, never+// guessed rolled back.+{+ const f = fixture();+ f.approval('stage');+ stageEnrollment({ ...f.common, candidatePath: f.candidatePath });+ const approval = f.approval('activate');+ const modulePath = join(import.meta.dirname, '..', 'staged-enrollment.mjs');+ const childScript = `import(${JSON.stringify(`file://${modulePath}`)}).then(m=>m.activateEnrollment(${JSON.stringify({ ...f.common, now: NOW })}))`;+ const killed = spawnSync(process.execPath, ['--input-type=module', '-e', childScript], {+ encoding: 'utf8',+ env: {+ ...process.env,+ CLAUDE_STAGED_ENROLLMENT_TESTING: '1',+ CLAUDE_STAGED_ENROLLMENT_TEST_FAULT: 'SIGKILL:APPROVAL_CONSUMED',+ },+ });+ assert.equal(killed.signal, 'SIGKILL', killed.stderr);+ unlinkSync(join(f.paths.usage, `${approval.payload.id}.${approval.payload.nonce}.used`));+ refuses(() => recoverEnrollment({ configPath: f.configPath }), 'ACTIVATION_RECOVERY_UNCERTAIN');+}++// COMMITTED cleanup is idempotent when SIGKILL lands after backup deletion and+// before journal deletion, both when an old target existed and when it did not.+for (const hadTarget of [false, true]) {+ const f = fixture();+ f.approval('stage');+ stageEnrollment({ ...f.common, candidatePath: f.candidatePath });+ const target = join(f.paths.active, ENTRY.authFilename);+ if (hadTarget) writeFileSync(target, JSON.stringify({ ...CANDIDATE, access_token: 'old-token' }), { mode: 0o600 });+ f.approval('activate');+ const modulePath = join(import.meta.dirname, '..', 'staged-enrollment.mjs');+ const childScript = `import(${JSON.stringify(`file://${modulePath}`)}).then(m=>m.activateEnrollment(${JSON.stringify({ ...f.common, now: NOW })}))`;+ const killed = spawnSync(process.execPath, ['--input-type=module', '-e', childScript], {+ encoding: 'utf8',+ env: {+ ...process.env,+ CLAUDE_STAGED_ENROLLMENT_TESTING: '1',+ CLAUDE_STAGED_ENROLLMENT_TEST_FAULT: 'SIGKILL:AFTER_BACKUP_DELETE',+ },+ });+ 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(recoverEnrollment({ configPath: f.configPath }).recovered, false);+}++// A SIGKILL after no-replace backup restoration leaves only the journal-bound+// target/backup hardlinks, which fresh-process recovery completes safely.+{+ const f = fixture();+ f.approval('stage');+ stageEnrollment({ ...f.common, candidatePath: f.candidatePath });+ const target = join(f.paths.active, ENTRY.authFilename);+ const old = JSON.stringify({ ...CANDIDATE, access_token: 'restore-crash-old' });+ writeFileSync(target, old, { mode: 0o600 });+ f.approval('activate');+ const modulePath = join(import.meta.dirname, '..', 'staged-enrollment.mjs');+ const killed = spawnSync(+ process.execPath,+ [+ '--input-type=module',+ '-e',+ `import(${JSON.stringify(`file://${modulePath}`)}).then(m=>m.activateEnrollment(${JSON.stringify({ ...f.common, now: NOW, injectFailure: 'after-digest-verification' })}))`,+ ],+ {+ encoding: 'utf8',+ env: {+ ...process.env,+ CLAUDE_STAGED_ENROLLMENT_TESTING: '1',+ CLAUDE_STAGED_ENROLLMENT_TEST_FAULT: 'SIGKILL:RESTORE_TEMP_FSYNCED',+ },+ },+ );+ assert.equal(killed.signal, 'SIGKILL', killed.stderr);+ assert.equal(readFileSync(target, 'utf8'), old);+ assert.equal(readdirSync(f.paths.rollback).length, 1);+ assert.equal(recoverEnrollment({ configPath: f.configPath }).outcome, 'rolled-back');+ assert.equal(readFileSync(target, 'utf8'), old);+ assert.deepEqual(readdirSync(f.paths.rollback), []);+}++// PREPARING safely removes an operation-unique partial backup after proving the+// authenticated old-target and staged-candidate digests, bounding retention.+{+ const f = fixture();+ f.approval('stage');+ stageEnrollment({ ...f.common, candidatePath: f.candidatePath });+ const staged = join(f.paths.staging, ENTRY.authFilename);+ const target = join(f.paths.active, ENTRY.authFilename);+ const old = Buffer.from(JSON.stringify({ ...CANDIDATE, access_token: 'pinned-old-token' }));+ const stagedBefore = readFileSync(staged);+ writeFileSync(target, old, { mode: 0o600 });+ f.approval('activate');+ refuses(() => activateEnrollment({ ...f.common, injectFailure: 'partial-backup' }), 'INJECTED_FAILURE');+ assert.deepEqual(readFileSync(target), old);+ assert.deepEqual(readFileSync(staged), stagedBefore);+ assert.equal(readdirSync(f.paths.rollback).length, 1);+ assert.equal(recoverEnrollment({ configPath: f.configPath }).outcome, 'rolled-back');+ assert.deepEqual(readFileSync(target), old);+ assert.deepEqual(readFileSync(staged), stagedBefore);+ assert.deepEqual(readdirSync(f.paths.rollback), []);+}++// Authenticated pending publication evidence makes both first-directory-fsync+// and cleanup-fsync uncertainty deterministic on the next stage attempt.+for (const fault of ['THROW:PUBLICATION_FIRST_DIR_FSYNC', 'THROW:PUBLICATION_CLEANUP_FSYNC']) {+ const f = fixture();+ const approval = f.approval('stage');+ process.env.CLAUDE_STAGED_ENROLLMENT_TESTING = '1';+ process.env.CLAUDE_STAGED_ENROLLMENT_TEST_FAULT = fault;+ refuses(() => stageEnrollment({ ...f.common, candidatePath: f.candidatePath }), 'PUBLICATION_RECOVERY_REQUIRED');+ delete process.env.CLAUDE_STAGED_ENROLLMENT_TESTING;+ delete process.env.CLAUDE_STAGED_ENROLLMENT_TEST_FAULT;+ assert.equal(existsSync(`${f.common.operationLockPath}.publication`), true);+ if (fault === 'THROW:PUBLICATION_FIRST_DIR_FSYNC') {+ assert.equal(existsSync(join(f.paths.staging, ENTRY.authFilename)), false);+ assert.equal(stageEnrollment({ ...f.common, candidatePath: f.candidatePath }).ok, true);+ } else {+ 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',+ );+ }+ assert.equal(existsSync(`${f.common.operationLockPath}.publication`), false);+}++// Fresh subprocess recovery resolves SIGKILL at each stage publication link.+for (const boundary of ['STAGED_LINK', 'MARKER_LINK']) {+ const f = fixture();+ f.approval('stage');+ const modulePath = join(import.meta.dirname, '..', 'staged-enrollment.mjs');+ const childScript = `import(${JSON.stringify(`file://${modulePath}`)}).then(m=>m.stageEnrollment(${JSON.stringify({ ...f.common, candidatePath: f.candidatePath, now: NOW })}))`;+ const killed = spawnSync(process.execPath, ['--input-type=module', '-e', childScript], {+ encoding: 'utf8',+ env: {+ ...process.env,+ CLAUDE_STAGED_ENROLLMENT_TESTING: '1',+ CLAUDE_STAGED_ENROLLMENT_TEST_FAULT: `SIGKILL:${boundary}`,+ },+ });+ assert.equal(killed.signal, 'SIGKILL', `${boundary}: ${killed.stderr}`);+ const recoveryScript = `import(${JSON.stringify(`file://${modulePath}`)}).then(m=>{try{m.stageEnrollment(${JSON.stringify({ ...f.common, candidatePath: f.candidatePath, now: NOW })});process.stdout.write("ok")}catch(e){process.stdout.write(e.message)}})`;+ const recovered = spawnSync(process.execPath, ['--input-type=module', '-e', recoveryScript], { encoding: 'utf8' });+ assert.equal(recovered.status, 0, `${boundary}: ${recovered.stderr}`);+ assert.match(+ recovered.stdout,+ boundary === 'STAGED_LINK' ? /^ok$/ : /APPROVAL_REPLAY|DUPLICATE_IDENTITY|STAGE_TARGET_EXISTS/,+ );+ 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.+for (const fault of ['THROW:STAGE_AFTER_LINK', 'THROW:MARKER_AFTER_LINK']) {+ const f = fixture();+ const approval = f.approval('stage');+ const priorTesting = process.env.CLAUDE_STAGED_ENROLLMENT_TESTING;+ const priorFault = process.env.CLAUDE_STAGED_ENROLLMENT_TEST_FAULT;+ process.env.CLAUDE_STAGED_ENROLLMENT_TESTING = '1';+ process.env.CLAUDE_STAGED_ENROLLMENT_TEST_FAULT = fault;+ try {+ refuses(() => stageEnrollment({ ...f.common, candidatePath: f.candidatePath }), 'INJECTED|CONSUME');+ } finally {+ if (priorTesting === undefined) delete process.env.CLAUDE_STAGED_ENROLLMENT_TESTING;+ else process.env.CLAUDE_STAGED_ENROLLMENT_TESTING = priorTesting;+ 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.staging, ENTRY.authFilename)), false);+ assert.equal(existsSync(join(f.paths.usage, `${approval.payload.id}.${approval.payload.nonce}.used`)), false);+}++// An ambiguous activation-marker publication is resolved by a fresh recovery+// process. When cleanup removed the marker, the same approval remains usable.+{+ const f = fixture();+ f.approval('stage');+ stageEnrollment({ ...f.common, candidatePath: f.candidatePath });+ const approval = f.approval('activate');+ const priorTesting = process.env.CLAUDE_STAGED_ENROLLMENT_TESTING;+ const priorFault = process.env.CLAUDE_STAGED_ENROLLMENT_TEST_FAULT;+ process.env.CLAUDE_STAGED_ENROLLMENT_TESTING = '1';+ process.env.CLAUDE_STAGED_ENROLLMENT_TEST_FAULT = 'THROW:MARKER_AFTER_LINK';+ try {+ refuses(() => activateEnrollment(f.common), 'ACTIVATION_RECOVERY_REQUIRED');+ } finally {+ if (priorTesting === undefined) delete process.env.CLAUDE_STAGED_ENROLLMENT_TESTING;+ else process.env.CLAUDE_STAGED_ENROLLMENT_TESTING = priorTesting;+ 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(recoverEnrollment({ configPath: f.configPath }).outcome, 'rolled-back');+ assert.equal(activateEnrollment(f.common).ok, true);+}++// A fresh recovery process removes the one expected activation marker temp+// hardlink left by SIGKILL after link(2), then validates the canonical marker.+{+ const f = fixture();+ f.approval('stage');+ stageEnrollment({ ...f.common, candidatePath: f.candidatePath });+ const approval = f.approval('activate');+ const modulePath = join(import.meta.dirname, '..', 'staged-enrollment.mjs');+ const activateScript = `import(${JSON.stringify(`file://${modulePath}`)}).then(m=>m.activateEnrollment(${JSON.stringify({ ...f.common, now: NOW })}))`;+ const killed = spawnSync(process.execPath, ['--input-type=module', '-e', activateScript], {+ encoding: 'utf8',+ env: {+ ...process.env,+ CLAUDE_STAGED_ENROLLMENT_TESTING: '1',+ CLAUDE_STAGED_ENROLLMENT_TEST_FAULT: 'SIGKILL:MARKER_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);+ 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(recoverEnrollment({ configPath: f.configPath }).recovered, false);+}++// If marker cleanup itself is ambiguous, recovery treats the authenticated+// marker as authoritative consumption: rollback succeeds but retry is replay.+{+ const f = fixture();+ f.approval('stage');+ stageEnrollment({ ...f.common, candidatePath: f.candidatePath });+ const approval = f.approval('activate');+ process.env.CLAUDE_STAGED_ENROLLMENT_TESTING = '1';+ process.env.CLAUDE_STAGED_ENROLLMENT_TEST_FAULT = 'THROW:MARKER_CLEANUP_UNCERTAIN';+ try {+ refuses(() => activateEnrollment(f.common), 'ACTIVATION_RECOVERY_REQUIRED');+ } finally {+ delete process.env.CLAUDE_STAGED_ENROLLMENT_TESTING;+ delete process.env.CLAUDE_STAGED_ENROLLMENT_TEST_FAULT;+ }+ assert.equal(existsSync(join(f.paths.usage, `${approval.payload.id}.${approval.payload.nonce}.used`)), true);+ assert.equal(recoverEnrollment({ configPath: f.configPath }).outcome, 'rolled-back');+ refuses(() => activateEnrollment(f.common), 'APPROVAL_REPLAY|ACTIVATION_RECOVERY_REQUIRED');+}++// Raw-byte manifest digest, exact 15-entry topology, no parsed mutation.+{+ const raw = ` {\n "version": 1, "entries": ${JSON.stringify(MANIFEST.entries)}\n}\n`;+ const before = JSON.parse(raw);+ const parsed = parseManifestBytes(Buffer.from(raw));+ assert.equal(parsed.digest, sha256(Buffer.from(raw)));+ assert.equal(JSON.stringify(parsed.manifest), JSON.stringify(before));+ refuses(+ () => parseManifestBytes(JSON.stringify({ ...MANIFEST, entries: MANIFEST.entries.slice(1) })),+ 'INVALID_MANIFEST',+ );+ refuses(+ () =>+ parseManifestBytes(+ JSON.stringify({+ ...MANIFEST,+ entries: [+ ...MANIFEST.entries.slice(0, -1),+ { id: 'codex-extra', authFilename: 'codex-extra.json', provider: 'codex' },+ ],+ }),+ ),+ 'INVALID_PROVIDER_COUNTS',+ );+ refuses(+ () =>+ parseManifestBytes(+ JSON.stringify({+ ...MANIFEST,+ entries: MANIFEST.entries.map((e, i) => (i === 1 ? { ...e, authFilename: ENTRY.authFilename } : e)),+ }),+ ),+ 'DUPLICATE_MANIFEST_BINDING',+ );+}++// Actual CLIProxy schema allowlist and structural/identity validation.+validateCandidateBytes(JSON.stringify(CANDIDATE), ENTRY, NOW);+validateCandidateBytes(+ JSON.stringify({ ...CANDIDATE, id_token: '', expired: '2030-01-01T01:00:00Z', last_refresh: '2029-12-31T23:59:59Z' }),+ ENTRY,+ NOW,+);+for (const mutation of [+ { disabled: true },+ { type: 'codex' },+ { expires_in: 0 },+ { expires_in: 1.5 },+ { expires_in: Number.MAX_SAFE_INTEGER + 1 },+ { expired: new Date(NOW - 1).toISOString() },+ { expired: '2030-01-01 01:00:00Z' },+ { expired: '2030-02-30T01:00:00Z' },+ { expired: '2100-02-29T01:00:00Z' },+ { expired: '2032-02-29T24:00:00Z' },+ { expired: '2032-02-29T01:00:00+24:00' },+ { email: '[email protected]' },+ { organization_uuid: 'wrong-organization' },+ { claude_device_ids: [] },+ { claude_device_ids: ['A'.repeat(64)] },+ { claude_device_ids: ['a'.repeat(63)] },+ { last_refresh: null },+ { last_refresh: 'not-a-time' },+ { last_refresh: '2029-02-29T23:59:59Z' },+ { extra: SECRET_VALUES[3] },+])+ refuses(() => validateCandidateBytes(JSON.stringify({ ...CANDIDATE, ...mutation }), ENTRY, NOW), 'INVALID|IDENTITY');+{+ const { refresh_token: _removed, ...missing } = CANDIDATE;+ refuses(() => validateCandidateBytes(JSON.stringify(missing), ENTRY, NOW), 'INVALID_SCHEMA');+}++// Config pins all trust roots and rejects permissions, missing roots and unsafe TTLs.+{+ const f = fixture();+ assert.equal(JSON.stringify(readDeploymentConfig(f.configPath)), JSON.stringify(f.config));+ chmodSync(f.configPath, 0o644);+ refuses(() => readDeploymentConfig(f.configPath), 'INSECURE_TRUST_ROOT');+}+// Physical trust roots cannot be aliased through a symlinked ancestor.+{+ const f = fixture();+ const alias = join(f.root, 'active-alias');+ symlinkSync(f.paths.active, alias);+ writeFileSync(f.configPath, JSON.stringify({ ...f.config, stagingDir: alias }), { mode: 0o600 });+ refuses(() => readDeploymentConfig(f.configPath), 'INSECURE_TRUST_ROOT');+}+// CLI-supplied candidate and approval artifacts reject symlinked ancestors too.+for (const kind of ['candidate', 'approval']) {+ const f = fixture();+ f.approval('stage');+ const alias = join(f.root, `${kind}-ancestor`);+ mkdirSync(alias, { mode: 0o700 });+ const realDir = join(f.root, `${kind}-real`);+ mkdirSync(realDir, { mode: 0o700 });+ const source = kind === 'candidate' ? f.candidatePath : f.approvalPath;+ const name = kind === 'candidate' ? 'candidate.json' : 'approval.json';+ writeFileSync(join(realDir, name), readFileSync(source), { mode: 0o600 });+ rmdirSync(alias);+ symlinkSync(realDir, alias);+ refuses(+ () =>+ stageEnrollment({+ ...f.common,+ candidatePath: kind === 'candidate' ? join(alias, name) : f.candidatePath,+ approvalPath: kind === 'approval' ? join(alias, name) : f.approvalPath,+ }),+ 'INSECURE_TRUST_ROOT',+ );+}+for (const ttl of [0, Infinity, 900_001]) {+ const f = fixture();+ writeFileSync(f.configPath, JSON.stringify({ ...f.config, maxApprovalTtlMs: ttl }), { mode: 0o600 });+ refuses(() => readDeploymentConfig(f.configPath), 'INVALID');+}+for (const mutate of [+ (f) => ({ ...f.config, activeDir: 'relative' }),+ (f) => ({ ...f.config, stagingDir: f.paths.active }),+ (f) => ({ ...f.config, rollbackDir: join(f.paths.active, 'nested') }),+ (f) => ({ ...f.config, quarantineDirs: [f.paths.quarantine, f.paths.quarantine] }),+ (f) => ({ ...f.config, operationLockPath: join(f.paths.active, 'operation.lock') }),+]) {+ const f = fixture();+ writeFileSync(f.configPath, JSON.stringify(mutate(f)), { mode: 0o600 });+ refuses(() => readDeploymentConfig(f.configPath), 'INVALID_CONFIG|MISSING_TRUST_ROOT');+}+{+ const f = fixture();+ f.config.quarantineDirs.push(join(f.root, 'missing'));+ writeFileSync(f.configPath, JSON.stringify(f.config), { mode: 0o600 });+ f.approval('stage');+ refuses(+ () => stageEnrollment({ ...f.common, quarantineDirs: f.config.quarantineDirs, candidatePath: f.candidatePath }),+ 'MISSING_TRUST_ROOT',+ );+}+{+ const f = fixture();+ const realKey = join(f.root, 'real.key');+ writeFileSync(realKey, 'K'.repeat(32), { mode: 0o600 });+ unlinkSync(f.keyPath);+ symlinkSync(realKey, f.keyPath);+ f.approval('stage');+ refuses(() => stageEnrollment({ ...f.common, candidatePath: f.candidatePath }), 'INSECURE_TRUST_ROOT');+}++// Stage preserves six cross-brand records exactly, consumes once, and publishes no-replace.+{+ const f = fixture();+ const files = Array.from({ length: 6 }, (_, i) => join(f.paths.active, `codex-brand-${i}.json`));+ files.forEach((path, i) => writeFileSync(path, ` {"type":"codex","opaque":"${i}"}\n`, { mode: 0o600 }));+ const before = files.map((path) => readFileSync(path));+ f.approval('stage');+ stageEnrollment({ ...f.common, candidatePath: f.candidatePath });+ assert.deepEqual(+ files.map((path) => readFileSync(path)),+ before,+ );+ const replay = f.approval('stage', { id: 'replay-id', nonce: 'replay-nonce' });+ consumeApproval(replay.payload, f.paths.usage);+ refuses(() => consumeApproval(replay.payload, f.paths.usage), 'APPROVAL_REPLAY');+}+// The actual stage approval cannot be replayed.+{+ const f = fixture();+ 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');+}+{+ const f = fixture();+ writeFileSync(join(f.paths.staging, ENTRY.authFilename), 'occupied', { mode: 0o600 });+ f.approval('stage');+ refuses(() => stageEnrollment({ ...f.common, candidatePath: f.candidatePath }), 'STAGE_TARGET_EXISTS|MALFORMED');+}+{+ const f = fixture();+ writeFileSync(f.common.operationLockPath, 'held', { mode: 0o600 });+ f.approval('stage');+ refuses(() => stageEnrollment({ ...f.common, candidatePath: f.candidatePath }), 'OPERATION_LOCKED');+}++// Recursive duplicate and symlink/ambiguous inventories fail closed.+{+ const f = fixture();+ const nested = join(f.paths.quarantine, 'nested');+ mkdirSync(nested, { mode: 0o700 });+ writeFileSync(join(nested, 'other.json'), JSON.stringify(CANDIDATE), { mode: 0o600 });+ f.approval('stage');+ refuses(() => stageEnrollment({ ...f.common, candidatePath: f.candidatePath }), 'DUPLICATE_IDENTITY');+}+{+ const f = fixture();+ const nested = join(f.paths.quarantine, 'nested');+ mkdirSync(nested, { mode: 0o700 });+ writeFileSync(join(nested, ENTRY.authFilename), JSON.stringify(CANDIDATE), { mode: 0o600 });+ f.approval('stage');+ refuses(() => stageEnrollment({ ...f.common, candidatePath: f.candidatePath }), 'DUPLICATE_IDENTITY');+}+{+ const f = fixture();+ symlinkSync(f.candidatePath, join(f.paths.quarantine, 'link.json'));+ f.approval('stage');+ refuses(() => stageEnrollment({ ...f.common, candidatePath: f.candidatePath }), 'UNSAFE_INVENTORY');+}+{+ const f = fixture();+ writeFileSync(join(f.paths.active, 'ambiguous.json'), JSON.stringify({ ...CANDIDATE, provider: 'codex' }), {+ mode: 0o600,+ });+ f.approval('stage');+ refuses(() => stageEnrollment({ ...f.common, candidatePath: f.candidatePath }), 'AMBIGUOUS_INVENTORY');+}++// Raw formatting-only CAS and pre-consumption failures leave approvals reusable.+{+ const f = fixture();+ f.approval('stage');+ stageEnrollment({ ...f.common, candidatePath: f.candidatePath });+ f.approval('activate');+ refuses(+ () =>+ activateEnrollment({+ ...f.common,+ beforeCas: () => writeFileSync(f.manifestPath, `${readFileSync(f.manifestPath)}\n`),+ }),+ 'MANIFEST_CAS_FAILED',+ );+ writeFileSync(f.manifestPath, readFileSync(f.manifestPath, 'utf8').trimEnd(), { mode: 0o600 });+ const receipt = activateEnrollment(f.common);+ assert.equal(receipt.candidateDigest, f.candidateDigest);+}+// A target-present stale CAS leaves both approval and rollback directory untouched.+{+ const f = fixture();+ f.approval('stage');+ stageEnrollment({ ...f.common, candidatePath: f.candidatePath });+ writeFileSync(join(f.paths.active, ENTRY.authFilename), JSON.stringify({ ...CANDIDATE, access_token: 'old' }), {+ mode: 0o600,+ });+ f.approval('activate');+ refuses(+ () =>+ activateEnrollment({+ ...f.common,+ beforeCas: () => writeFileSync(f.manifestPath, `${readFileSync(f.manifestPath)}\n`),+ }),+ 'MANIFEST_CAS_FAILED',+ );+ assert.deepEqual(readdirSync(f.paths.rollback), []);+ writeFileSync(f.manifestPath, readFileSync(f.manifestPath, 'utf8').trimEnd(), { mode: 0o600 });+ assert.equal(activateEnrollment(f.common).ok, true);+}+// Activation approval is bound to the exact staged candidate bytes.+{+ const f = fixture();+ f.approval('stage');+ stageEnrollment({ ...f.common, candidatePath: f.candidatePath });+ f.approval('activate', { candidateDigest: '0'.repeat(64) });+ refuses(() => activateEnrollment(f.common), 'APPROVAL_BINDING_MISMATCH');+}++// Stage authorization is an exact additive publication, not a generic approval.+{+ const f = fixture();+ f.approval('stage', { candidateDigest: '0'.repeat(64) });+ refuses(() => stageEnrollment({ ...f.common, candidatePath: f.candidatePath }), 'APPROVAL_BINDING_MISMATCH');+}++// Canonical switch evidence is mandatory, exact-schema, identity-bound, raw-byte+// digest-bound, and must prove a passing no-fallback candidate canary.+{+ const f = fixture();+ f.approval('stage');+ stageEnrollment({ ...f.common, candidatePath: f.candidatePath });+ f.approval('activate');+ refuses(() => activateEnrollment({ ...f.common, inventoryPath: undefined }), 'ABSOLUTE_PATH_REQUIRED');+ refuses(() => activateEnrollment({ ...f.common, canaryPath: undefined }), 'ABSOLUTE_PATH_REQUIRED');+ writeFileSync(f.inventoryPath, JSON.stringify({ version: 1, credential: {}, consumers: [] }), { mode: 0o600 });+ f.approval('activate');+ refuses(() => activateEnrollment(f.common), 'INVALID_INVENTORY');+}+{+ const f = fixture();+ f.approval('stage');+ stageEnrollment({ ...f.common, candidatePath: f.candidatePath });+ const canary = JSON.parse(readFileSync(f.canaryPath, 'utf8'));+ canary.results[0].noFallback = false;+ writeFileSync(f.canaryPath, JSON.stringify(canary), { mode: 0o600 });+ f.approval('activate');+ refuses(() => activateEnrollment(f.common), 'INVALID_CANARY');+}+for (const mutation of ['invented', 'incomplete', 'duplicate']) {+ const f = fixture();+ f.approval('stage');+ stageEnrollment({ ...f.common, candidatePath: f.candidatePath });+ const inventory = JSON.parse(readFileSync(f.inventoryPath, 'utf8'));+ if (mutation === 'invented')+ inventory.consumers.push({ id: 'invented', type: 'foreign', path: join(f.root, 'invented') });+ if (mutation === 'incomplete') inventory.consumers = [];+ if (mutation === 'duplicate') inventory.consumers.push({ ...inventory.consumers[0] });+ writeFileSync(f.inventoryPath, JSON.stringify(inventory), { mode: 0o600 });+ f.approval('activate');+ refuses(() => activateEnrollment(f.common), 'INVALID_INVENTORY');+}+{+ const f = fixture();+ f.approval('stage');+ stageEnrollment({ ...f.common, candidatePath: f.candidatePath });+ writeFileSync(f.authoritativeConsumerInventoryPath, '{"version":1,"consumers":[]}', { mode: 0o600 });+ f.approval('activate');+ refuses(() => activateEnrollment(f.common), 'AUTHORITATIVE_INVENTORY_MISMATCH');+}+{+ const f = fixture();+ f.approval('stage');+ stageEnrollment({ ...f.common, candidatePath: f.candidatePath });+ const canary = JSON.parse(readFileSync(f.canaryPath, 'utf8'));+ canary.results = [];+ writeFileSync(f.canaryPath, JSON.stringify(canary), { mode: 0o600 });+ f.approval('activate');+ refuses(() => activateEnrollment(f.common), 'INVALID_CANARY');+}+{+ const f = fixture();+ f.approval('stage');+ stageEnrollment({ ...f.common, candidatePath: f.candidatePath });+ f.approval('activate', { oldTargetDigest: '0'.repeat(64) });+ refuses(() => activateEnrollment(f.common), 'APPROVAL_BINDING_MISMATCH');+ f.approval('activate', { inventoryDigest: '0'.repeat(64) });+ refuses(() => activateEnrollment(f.common), 'APPROVAL_BINDING_MISMATCH');+ f.approval('activate', { canaryDigest: '0'.repeat(64) });+ refuses(() => activateEnrollment(f.common), 'APPROVAL_BINDING_MISMATCH');+}++// No invalidation/revoke/delete action exists; a later destructive operation+// cannot reuse enrollment authorization.+{+ const f = fixture();+ const cli = join(import.meta.dirname, '..', 'staged-enrollment.mjs');+ for (const command of ['invalidate', 'revoke', 'delete']) {+ const run = spawnSync(process.execPath, [cli, command, '--config', f.configPath], { encoding: 'utf8' });+ assert.equal(run.status, 1);+ assert.match(run.stderr, /INVALID_ARGUMENTS/);+ }+}++// Approval authentication, clock, action, and binding checks fail closed.+{+ const f = fixture();+ const artifact = f.approval('stage');+ const expected = {+ action: 'additive-publish',+ manifestDigest: f.digest,+ manifestEntryId: ENTRY.id,+ provider: 'claude',+ email: ENTRY.email,+ organizationUuid: ENTRY.organizationUuid,+ organizationName: ENTRY.organizationName,+ accountOwner: ENTRY.accountOwner,+ authorizedOperator: 'operator',+ environment: 'controlled-test',+ candidateDigest: f.candidateDigest,+ oldTargetDigest: null,+ inventoryDigest: null,+ canaryDigest: null,+ destination: ENTRY.authFilename,+ };+ const verify = (a = artifact, e = expected, now = NOW) =>+ verifyApproval({ artifact: a, keyPath: f.keyPath, expected: e, now, maxTtlMs: 300_000 });+ verify();+ refuses(() => verify({ ...artifact, signature: '0'.repeat(64) }), 'INVALID_SIGNATURE');+ for (const [key, value] of [+ ['action', 'canonical-switch'],+ ['environment', 'wrong'],+ ['organizationUuid', 'wrong'],+ ])+ refuses(() => verify(artifact, { ...expected, [key]: value }), 'APPROVAL_BINDING_MISMATCH');+ refuses(() => verify(artifact, expected, NOW + 300_001), 'INVALID_APPROVAL_CLOCK');+ const future = f.approval('stage', {}, { now: NOW + 1 });+ refuses(() => verify(future), 'INVALID_APPROVAL_CLOCK');+ const overlong = signApproval(+ { ...artifact.payload, expiresAt: new Date(NOW + 300_001).toISOString() },+ readFileSync(f.keyPath),+ );+ refuses(() => verify(overlong), 'INVALID_APPROVAL_CLOCK');+ for (const timestamp of [+ '2030-01-01 00:00:00Z',+ '2030-01-01T00:00:00',+ '2030-02-31T00:00:00Z',+ '2030-01-01T24:00:00Z',+ '2030-01-01T00:00:00+24:00',+ ]) {+ const invalidIssuedAt = signApproval({ ...artifact.payload, issuedAt: timestamp }, readFileSync(f.keyPath));+ refuses(() => verify(invalidIssuedAt), 'INVALID_APPROVAL_CLOCK');+ const invalidExpiresAt = signApproval({ ...artifact.payload, expiresAt: timestamp }, readFileSync(f.keyPath));+ refuses(() => verify(invalidExpiresAt), 'INVALID_APPROVAL_CLOCK');+ }+ writeFileSync(f.keyPath, 'short', { mode: 0o600 });+ refuses(() => verify(), 'APPROVAL_KEY_TOO_SHORT');+}++// Rollback at each injected boundary, with target present and absent.+for (const injection of [+ 'before-rename',+ 'initial-rename-failure',+ 'after-rename-before-dir-fsync',+ 'after-source-dir-fsync',+ 'after-digest-verification',+]) {+ for (const present of [false, true]) {+ const f = fixture();+ f.approval('stage');+ stageEnrollment({ ...f.common, candidatePath: f.candidatePath });+ const target = join(f.paths.active, ENTRY.authFilename);+ const old = JSON.stringify({ ...CANDIDATE, access_token: 'old-synthetic-value' });+ if (present) writeFileSync(target, old, { mode: 0o600 });+ f.approval('activate');+ refuses(+ () => activateEnrollment({ ...f.common, injectFailure: injection }),+ 'INJECTED_FAILURE|ACTIVATION_ROLLED_BACK',+ );+ assert.equal(existsSync(target), present);+ if (present) assert.equal(readFileSync(target, 'utf8'), old);+ }+}++// A rollback fsync failure reports the stable unproven-recovery code while still restoring bytes.+{+ const f = fixture();+ f.approval('stage');+ stageEnrollment({ ...f.common, candidatePath: f.candidatePath });+ const target = join(f.paths.active, ENTRY.authFilename);+ const old = JSON.stringify({ ...CANDIDATE, access_token: 'durable-old-value' });+ writeFileSync(target, old, { mode: 0o600 });+ f.approval('activate');+ refuses(+ () => activateEnrollment({ ...f.common, injectFailure: 'rollback-fsync-failure' }),+ 'ACTIVATION_ROLLBACK_FAILED',+ );+ assert.equal(readFileSync(target, 'utf8'), old);+ assert.equal(sha256(readFileSync(join(f.paths.staging, ENTRY.authFilename))), f.candidateDigest);+}++// Real CLI is secret-safe for malformed candidates and secret-bearing paths.+{+ const f = fixture();+ f.approval('stage');+ const secretPath = join(f.root, SECRET_VALUES.slice(3).join('-'));+ writeFileSync(secretPath, `{ "access_token":"${SECRET_VALUES[0]}", "refresh_token":"${SECRET_VALUES[1]}"`, {+ mode: 0o600,+ });+ const cli = join(import.meta.dirname, '..', 'staged-enrollment.mjs');+ const r = spawnSync(+ process.execPath,+ [+ cli,+ 'stage',+ '--config',+ f.configPath,+ '--entry',+ ENTRY.id,+ '--approval',+ f.approvalPath,+ '--candidate',+ secretPath,+ ],+ { encoding: 'utf8' },+ );+ assert.equal(r.status, 1);+ const output = `${r.stdout}${r.stderr}`;+ SECRET_VALUES.forEach((secret) => assert(!output.includes(secret)));+ assert.match(output, /^staged enrollment refused: [A-Z_]+\n$/);+ const override = spawnSync(+ process.execPath,+ [+ cli,+ 'activate',+ '--config',+ f.configPath,+ '--entry',+ ENTRY.id,+ '--approval',+ f.approvalPath,+ '--active-dir',+ secretPath,+ ],+ { encoding: 'utf8' },+ );+ assert.equal(override.status, 1);+ assert.match(override.stderr, /INVALID_ARGUMENTS/);+}++// Legacy auth entrypoints and behavioral blocks.+assert.equal(automatedAuthAllowed({ autoAuthDisabled: true, explicitFilter: true }), false);+assert.equal((await reauth({ dryRun: false }, { accountId: ENTRY.email })).ok, false);+const wrapper = spawnSync(+ process.execPath,+ [join(import.meta.dirname, '..', 'rotate-magic.mjs'), '--to', ENTRY.email],+ { encoding: 'utf8' },+);+assert.equal(wrapper.status, 2);+// Retired direct credential creation entrypoints fail before filesystem or child-command side effects.+{+ const f = fixture();+ const home = join(f.root, 'isolated-home');+ const bin = join(f.root, 'mock-bin');+ const marker = join(f.root, 'child-side-effect');+ mkdirSync(home, { mode: 0o700 });+ mkdirSync(bin, { mode: 0o700 });+ for (const command of ['aws', 'claude', 'gog', 'expect', 'open']) {+ const mock = join(bin, command);+ writeFileSync(mock, `#!/bin/sh\ntouch '${marker}'\nexit 0\n`, { mode: 0o700 });+ }+ const env = { ...process.env, HOME: home, PATH: `${bin}:${process.env.PATH}` };+ const scripts = [+ ['bulk-setup-token.mjs'],+ ['setup-account.mjs', '--email', ENTRY.email],+ ['rotate.mjs', '--bootstrap-chrome-profile', ENTRY.email],+ ['rotate.mjs', '--bootstrap-all-chrome-profiles'],+ ];+ for (const [name, ...args] of scripts) {+ const result = spawnSync(process.execPath, [join(import.meta.dirname, '..', name), ...args], {+ encoding: 'utf8',+ env,+ });+ assert.notEqual(result.status, 0, name);+ assert.equal(existsSync(marker), false, `${name} spawned a side-effect command`);+ assert.deepEqual(readdirSync(home), [], `${name} wrote under HOME`);+ }+}+const sources = Object.fromEntries(+ [+ 'rotate.mjs',+ 'rotate-magic.mjs',+ 'refresh-tokens.mjs',+ 'magic-link-autoloop.mjs',+ 'force-rotate.sh',+ '../ops-accounts/providers/claude.mjs',+ ].map((name) => [name, readFileSync(join(import.meta.dirname, '..', name), 'utf8')]),+);+assert.doesNotMatch(sources['force-rotate.sh'], /fall(?:ing)?\s+back\s+to\s+(?:the\s+)?(?:full\s+)?browser/i);+for (const line of sources['force-rotate.sh']+ .split('\n')+ .filter((line) => /run_with_watchdog\s+node.*rotate\.mjs/.test(line)))+ assert.match(line, /--no-browser/);++// A failed force rotation launches only the browserless writer, exits nonzero,+// and never emits the success notification.+{+ const root = mkdtempSync(join(tmpdir(), 'force-rotate-'));+ const bin = join(root, 'bin');+ const data = join(root, 'data');+ const calls = join(root, 'calls');+ mkdirSync(bin, { mode: 0o700 });+ mkdirSync(data, { mode: 0o700 });+ for (const [name, body] of [+ ['node', `#!/bin/sh\necho "node $*" >>"${calls}"\ncase " $* " in *" --status "*) exit 0;; *) exit 9;; esac\n`],+ ['launchctl', '#!/bin/sh\nexit 0\n'],+ ['security', '#!/bin/sh\nexit 1\n'],+ ['osascript', `#!/bin/sh\necho osascript >>"${calls}"\nexit 0\n`],+ ]) {+ const path = join(bin, name);+ writeFileSync(path, body, { mode: 0o700 });+ chmodSync(path, 0o700);+ }+ const run = spawnSync('bash', [join(import.meta.dirname, '..', 'force-rotate.sh')], {+ encoding: 'utf8',+ env: {+ ...process.env,+ PATH: `${bin}:${process.env.PATH}`,+ CLAUDE_ROTATION_DATA_DIR: data,+ FORCE_ROTATE_TIMEOUT: '2',+ },+ });+ assert.notEqual(run.status, 0);+ const launched = readFileSync(calls, 'utf8');+ assert.equal(+ launched.split('\n').filter((line) => line.includes('rotate.mjs') && !line.includes('--status')).length,+ 1,+ );+ assert.match(launched, /--no-browser/);+ assert.doesNotMatch(launched, /osascript/);+}+const refreshBody = sources['rotate.mjs'].slice(+ sources['rotate.mjs'].indexOf('async function refreshRunningSession'),+ sources['rotate.mjs'].indexOf('// ── Main rotation'),+);+assert.doesNotMatch(refreshBody, /runAuthFlow\s*\(/);+for (const name of [+ 'rotate-magic.mjs',+ 'refresh-tokens.mjs',+ 'magic-link-autoloop.mjs',+ '../ops-accounts/providers/claude.mjs',+])+ assert.doesNotMatch(+ sources[name],+ /spawn(?:Sync)?\s*\([^)]*(?:rotate\.mjs|runAuthFlow)|execFileSync\s*\([^)]*rotate\.mjs/s,+ );++// Generic rotation-vault exports never self-authorize from lock ownership and+// live identity. They refuse before profile fetch or filesystem mutation,+// including a coordinated call made from inside the canonical lock.+{+ const f = fixture();+ const vaultPath = join(f.root, 'writer-vault.json');+ writeFileSync(vaultPath, '{}', { mode: 0o600 });+ const writer = join(import.meta.dirname, '..', 'rotation-vault.mjs');+ const writerAccount = {+ email: '[email protected]',+ orgUuid: 'race-org',+ orgName: 'Race Org',+ };+ const fetchMarker = join(f.root, 'writer-profile-fetch');+ const script = `globalThis.fetch=async()=>{require('node:fs').writeFileSync(${JSON.stringify(fetchMarker)},'unsafe');return {ok:true,json:async()=>({account:{email:'[email protected]'},organization:{uuid:'race-org',name:'Race Org'}})}}; import(${JSON.stringify(`file://${writer}`)}).then(m=>m.writeRotationToken(${JSON.stringify(writerAccount)},JSON.stringify({claudeAiOauth:{accessToken:'synthetic-race-token'}})))`;+ const env = {+ ...process.env,+ CLAUDE_AUTH_COORDINATION_CONFIG: f.configPath,+ CLAUDE_ROTATOR_CONFIG: f.manifestPath,+ CLAUDE_ROTATION_FILE_VAULT: vaultPath,+ };+ for (let attempt = 0; attempt < 2; attempt++) {+ const denied = spawnSync(process.execPath, ['--input-type=module', '-e', script], { env, encoding: 'utf8' });+ assert.notEqual(denied.status, 0);+ assert.match(denied.stderr, /ROTATION_TOKEN_MUTATION_APPROVAL_REQUIRED/);+ assert.deepEqual(JSON.parse(readFileSync(vaultPath, 'utf8')), {});+ assert.equal(existsSync(fetchMarker), false);+ }+ const previousCoordination = process.env.CLAUDE_AUTH_COORDINATION_CONFIG;+ const previousInventory = process.env.CLAUDE_ROTATOR_CONFIG;+ process.env.CLAUDE_AUTH_COORDINATION_CONFIG = f.configPath;+ process.env.CLAUDE_ROTATOR_CONFIG = f.manifestPath;+ try {+ await withAuthWriterLock((capability) => {+ assert.throws(+ () =>+ writeRotationTokenCoordinated(+ writerAccount,+ JSON.stringify({ claudeAiOauth: { accessToken: 'synthetic-race-token' } }),+ capability,+ ),+ /ROTATION_TOKEN_MUTATION_APPROVAL_REQUIRED/,+ );+ });+ } finally {+ if (previousCoordination === undefined) delete process.env.CLAUDE_AUTH_COORDINATION_CONFIG;+ else process.env.CLAUDE_AUTH_COORDINATION_CONFIG = previousCoordination;+ if (previousInventory === undefined) delete process.env.CLAUDE_ROTATOR_CONFIG;+ else process.env.CLAUDE_ROTATOR_CONFIG = previousInventory;+ }+ assert.deepEqual(JSON.parse(readFileSync(vaultPath, 'utf8')), {});+}++// Writer capabilities are scoped to the exact outer lock transaction and are+// unusable after synchronous or asynchronous completion.+for (const asynchronous of [false, true]) {+ const f = fixture();+ let retained;+ const result = withAuthWriterLock(+ async (capability) => {+ retained = capability;+ requireWriterCapability(capability);+ return asynchronous ? Promise.resolve('ok') : 'ok';+ },+ { configPath: f.configPath },+ );+ assert.equal(await result, 'ok');+ assert.throws(() => requireWriterCapability(retained), /AUTH_WRITER_CAPABILITY_REQUIRED/);+}++// A detached async descendant retains AsyncLocalStorage context but not lock+// authority after the outer transaction settles.+{+ const f = fixture();+ let detachedAttempt;+ await withAuthWriterLock(+ () => {+ detachedAttempt = new Promise((resolve) => {+ setTimeout(async () => {+ try {+ await withAuthWriterLock(() => resolve('unsafe-entry'), { configPath: f.configPath });+ } catch (error) {+ resolve(error.message);+ }+ }, 0);+ });+ return 'outer-complete';+ },+ { configPath: f.configPath },+ );+ assert.equal(await detachedAttempt, 'AUTH_WRITER_CAPABILITY_REQUIRED');+}++// Non-native thenables are assimilated and revoked even without `.finally`.+{+ const f = fixture();+ let retained;+ let detachedAttempt;+ const thenable = withAuthWriterLock(+ (capability) => {+ retained = capability;+ detachedAttempt = new Promise((resolve) =>+ setTimeout(() => {+ try {+ withAuthWriterLock(() => resolve('unsafe-entry'), { configPath: f.configPath });+ } catch (error) {+ resolve(error.message);+ }+ }, 0),+ );+ return { then: (resolve) => resolve('assimilated') };+ },+ { configPath: f.configPath },+ );+ assert.equal(await thenable, 'assimilated');+ assert.throws(() => requireWriterCapability(retained), /AUTH_WRITER_CAPABILITY_REQUIRED/);+ assert.equal(await detachedAttempt, 'AUTH_WRITER_CAPABILITY_REQUIRED');+}++// A real staged activation process excludes an ordinary writer plus protected+// healing-read and delete mutations until activation releases the same lock.+{+ const f = fixture();+ f.approval('stage');+ stageEnrollment({ ...f.common, candidatePath: f.candidatePath });+ f.approval('activate');+ const rotationVault = join(f.root, 'contended-rotation.json');+ const healService = '[email protected]';+ const healToken = { claudeAiOauth: { accessToken: 'unchanged-heal-token', expiresAt: 123 } };+ writeFileSync(rotationVault, JSON.stringify({ [healService]: healToken }), { mode: 0o600 });+ const home = join(f.root, 'contention-home');+ mkdirSync(home, { mode: 0o700 });+ const stagedModule = join(import.meta.dirname, '..', 'staged-enrollment.mjs');+ const rotationModule = join(import.meta.dirname, '..', 'rotation-vault.mjs');+ const linuxModule = join(import.meta.dirname, '..', 'vault-linux.mjs');+ const env = {+ ...process.env,+ HOME: home,+ CLAUDE_AUTH_COORDINATION_CONFIG: f.configPath,+ CLAUDE_ROTATOR_CONFIG: f.manifestPath,+ CLAUDE_ROTATION_FILE_VAULT: rotationVault,+ };+ const deleteVaultDir = join(home, '.local', 'share', 'claude-rotation');+ mkdirSync(deleteVaultDir, { recursive: true, mode: 0o700 });+ const deleteVaultPath = join(deleteVaultDir, `${sha256('delete-me').slice(0, 24)}.json`);+ writeFileSync(deleteVaultPath, 'synthetic-delete-value', { mode: 0o600 });+ const activationScript = `import(${JSON.stringify(`file://${stagedModule}`)}).then(m=>m.activateEnrollment(${JSON.stringify({ ...f.common, now: NOW })}))`;+ const activation = spawn(process.execPath, ['--input-type=module', '-e', activationScript], {+ env: {+ ...env,+ CLAUDE_STAGED_ENROLLMENT_TESTING: '1',+ CLAUDE_STAGED_ENROLLMENT_TEST_FAULT: 'SIGSTOP:LOCK_ACQUIRED',+ },+ stdio: ['ignore', 'pipe', 'pipe'],+ });+ const resultPromise = childResult(activation);+ let activated;+ try {+ await waitFor(() => existsSync(f.common.operationLockPath), 'stopped activation lock');+ await waitForStoppedChild(activation, 'lock-acquired fault stop');+ const attempts = [+ `import(${JSON.stringify(`file://${rotationModule}`)}).then(m=>m.writeRotationToken({email:'[email protected]',orgUuid:'writer-org',orgName:'Writer Org'},JSON.stringify({claudeAiOauth:{accessToken:'blocked-writer-token'}})))`,+ `import(${JSON.stringify(`file://${linuxModule}`)}).then(m=>m.deleteEntry('delete-me'))`,+ ].map((script) => spawnSync(process.execPath, ['--input-type=module', '-e', script], { env, encoding: 'utf8' }));+ for (const [index, attempt] of attempts.entries()) {+ assert.notEqual(attempt.status, 0);+ assert.match(+ attempt.stderr,+ index === 0 ? /ROTATION_TOKEN_MUTATION_APPROVAL_REQUIRED/ : /GENERIC_CREDENTIAL_DELETE_FORBIDDEN/,+ );+ }+ assert.deepEqual(JSON.parse(readFileSync(rotationVault, 'utf8')), { [healService]: healToken });+ assert.equal(readFileSync(deleteVaultPath, 'utf8'), 'synthetic-delete-value');+ signalChild(activation, 'SIGCONT');+ activated = await resultPromise;+ } finally {+ signalChild(activation, 'SIGCONT');+ signalChild(activation, 'SIGTERM');+ }+ assert.equal(activated.status, 0, activated.stderr);+}++// Every generic JS/CLI/shell setter rejects all protected service spellings+// before a backend side effect, while unrelated namespaces remain compatible.+{+ const root = mkdtempSync(join(tmpdir(), 'credential-setter-policy-'));+ const data = join(root, 'data');+ const mjs = join(import.meta.dirname, '..', '..', '..', 'lib', 'credential-store.mjs');+ const sh = join(import.meta.dirname, '..', '..', '..', 'lib', 'credential-store.sh');+ const env = { ...process.env, HOME: root, XDG_DATA_HOME: data, CLAUDE_OPS_CRED_BACKEND: 'plaintext-json' };+ const protectedServices = [+ 'Claude-Rotation',+ '[email protected]',+ 'Claude Code-credentials',+ 'cLaUdE-rOtAtIoN-Mixed',+ ];+ for (const service of protectedServices) {+ const api = spawnSync(+ process.execPath,+ [+ '--input-type=module',+ '-e',+ `import {setCredential} from ${JSON.stringify(`file://${mjs}`)}; await setCredential(${JSON.stringify(service)},'acct','secret')`,+ ],+ { env, encoding: 'utf8' },+ );+ assert.notEqual(api.status, 0);+ for (const command of ['set', 'set-keytar', 'delete', 'delete-keytar']) {+ const run = spawnSync(process.execPath, [mjs, command, service, 'acct', 'secret'], { env, encoding: 'utf8' });+ assert.notEqual(run.status, 0, `${command} accepted ${service}`);+ }+ for (const command of ['set', 'set-stdin', 'delete']) {+ const argv = command === 'set' ? [sh, command, service, 'acct', 'secret'] : [sh, command, service, 'acct'];+ const run = spawnSync('bash', argv, {+ env,+ input: command === 'set-stdin' ? 'secret' : undefined,+ encoding: 'utf8',+ });+ assert.notEqual(run.status, 0, `shell ${command} accepted ${service}`);+ }+ }+ const plain = join(data, 'claude-ops', 'secrets.plain.json');+ assert.equal(existsSync(plain), false, 'protected setters reached a backend');+ const benign = spawnSync(process.execPath, [mjs, 'set', 'Example-Service', 'acct', 'secret'], {+ env,+ encoding: 'utf8',+ });+ assert.equal(benign.status, 0, benign.stderr);+ assert.equal(JSON.parse(readFileSync(plain, 'utf8'))['Example-Service/acct'], 'secret');+}++// Legacy keychain/vault setters fail closed. The only compatible swap path+// verifies full target identity while holding the canonical lock and writes+// nothing on profile mismatch.+{+ const f = fixture();+ const home = join(f.root, 'verified-swap-home');+ const claudeDir = join(home, '.claude');+ const vaultDir = join(home, '.local', 'share', 'claude-rotation');+ mkdirSync(claudeDir, { recursive: true, mode: 0o700 });+ mkdirSync(vaultDir, { recursive: true, mode: 0o700 });+ const activePath = join(claudeDir, '.credentials.json');+ const storedPath = join(vaultDir, `${sha256('[email protected]').slice(0, 24)}.json`);+ const previous = { claudeAiOauth: { accessToken: 'previous-token' }, mcpOAuth: {} };+ const target = { claudeAiOauth: { accessToken: 'target-token' }, mcpOAuth: {} };+ writeFileSync(activePath, JSON.stringify(previous), { mode: 0o600 });+ writeFileSync(storedPath, JSON.stringify(target), { mode: 0o600 });+ const swapModule = join(import.meta.dirname, '..', 'keychain-swap.mjs');+ const coordinationModule = join(import.meta.dirname, '..', 'auth-writer-coordination.mjs');+ const linuxModule = join(import.meta.dirname, '..', 'vault-linux.mjs');+ const account = { email: '[email protected]', orgUuid: 'target-org', orgName: 'Target Org' };+ const previousAccount = { email: '[email protected]', orgUuid: 'previous-org', orgName: 'Previous Org' };+ const runSwap = (profileEmail) =>+ spawnSync(+ process.execPath,+ [+ '--input-type=module',+ '-e',+ `globalThis.fetch=async(_url,options)=>{const previous=String(options.headers.Authorization).includes('previous-token');return {ok:true,json:async()=>previous?{account:{email:'[email protected]'},organization:{uuid:'previous-org',name:'Previous Org'}}:{account:{email:${JSON.stringify(profileEmail)}},organization:{uuid:'target-org',name:'Target Org'}}}}; const c=await import(${JSON.stringify(`file://${coordinationModule}`)}); const k=await import(${JSON.stringify(`file://${swapModule}`)}); await c.withAuthWriterLock(cap=>k.swapToAccountCoordinated(${JSON.stringify(account)},${JSON.stringify(previousAccount)},cap));`,+ ],+ {+ env: {+ ...process.env,+ HOME: home,+ CLAUDE_AUTH_COORDINATION_CONFIG: f.configPath,+ CLAUDE_ROTATOR_CONFIG: f.manifestPath,+ },+ encoding: 'utf8',+ },+ );+ const mismatch = runSwap('[email protected]');+ assert.notEqual(mismatch.status, 0);+ assert.match(mismatch.stderr, /SIGNED_CREDENTIAL_MUTATION_APPROVAL_REQUIRED/);+ assert.deepEqual(JSON.parse(readFileSync(activePath, 'utf8')), previous);+ const otherwiseValid = runSwap(account.email);+ assert.notEqual(otherwiseValid.status, 0);+ assert.match(otherwiseValid.stderr, /SIGNED_CREDENTIAL_MUTATION_APPROVAL_REQUIRED/);+ assert.deepEqual(JSON.parse(readFileSync(activePath, 'utf8')), previous);+ for (const script of [+ `import(${JSON.stringify(`file://${swapModule}`)}).then(m=>m.writeCurrentToken('{}'))`,+ `import(${JSON.stringify(`file://${swapModule}`)}).then(m=>m.restoreToken('{}'))`,+ `import(${JSON.stringify(`file://${linuxModule}`)}).then(m=>m.writeEntry('Claude Code-credentials','{}'))`,+ ]) {+ const refusal = spawnSync(process.execPath, ['--input-type=module', '-e', script], {+ env: { ...process.env, HOME: home },+ encoding: 'utf8',+ });+ assert.notEqual(refusal.status, 0);+ assert.match(refusal.stderr, /(?:LEGACY|GENERIC)_CREDENTIAL_WRITE_FORBIDDEN/);+ }++ // The claude-p compatibility entrypoint restores exact preverified bytes and+ // releases its legacy lock when the post-swap budget probe refuses.+ writeFileSync(activePath, JSON.stringify(previous), { mode: 0o600 });+ const runtimeConfig = join(home, 'rotation-config.json');+ const runtimeState = join(home, 'state.json');+ const ledger = join(home, 'ledger.json');+ const legacyLock = join(home, 'keychain.lock');+ writeFileSync(runtimeConfig, JSON.stringify({ accounts: [account, previousAccount] }), { mode: 0o600 });+ writeFileSync(runtimeState, JSON.stringify({ activeAccount: previousAccount.email }), { mode: 0o600 });+ writeFileSync(+ ledger,+ JSON.stringify({+ schema_version: 2,+ month: '2030-01',+ accounts: [{ email: account.email, remaining_usd: 100 }],+ }),+ { mode: 0o600 },+ );+ const bin = join(home, 'bin');+ mkdirSync(bin, { mode: 0o700 });+ writeFileSync(join(bin, 'claude'), '#!/bin/sh\necho "no budget flag"\n', { mode: 0o700 });+ chmodSync(join(bin, 'claude'), 0o700);+ const claudePAs = join(import.meta.dirname, '..', 'claude-p-as.mjs');+ const compatibility = spawnSync(+ process.execPath,+ [+ '--input-type=module',+ '-e',+ `globalThis.fetch=async(_url,options)=>{const previous=String(options.headers.Authorization).includes('previous-token');return {ok:true,json:async()=>previous?{account:{email:'[email protected]'},organization:{uuid:'previous-org',name:'Previous Org'}}:{account:{email:'[email protected]'},organization:{uuid:'target-org',name:'Target Org'}}}}; const {main}=await import(${JSON.stringify(`file://${claudePAs}`)}); await main(['--ledger',${JSON.stringify(ledger)},'--config',${JSON.stringify(runtimeConfig)},'--lock',${JSON.stringify(legacyLock)},'--pin','[email protected]','--','test']);`,+ ],+ {+ env: {+ ...process.env,+ HOME: home,+ PATH: `${bin}:${process.env.PATH}`,+ CLAUDE_AUTH_COORDINATION_CONFIG: f.configPath,+ CLAUDE_ROTATOR_CONFIG: f.manifestPath,+ },+ encoding: 'utf8',+ },+ );+ assert.notEqual(compatibility.status, 0);+ assert.match(compatibility.stderr, /SIGNED_CREDENTIAL_MUTATION_APPROVAL_REQUIRED/);+ assert.deepEqual(JSON.parse(readFileSync(activePath, 'utf8')), previous);+ assert.equal(existsSync(legacyLock), false);+}++// Refreshed-token identity is checked by an injected offline profile fetch and+// requires exact configured email and organization UUID/name.+{+ const account = {+ email: ENTRY.email,+ orgUuid: ENTRY.organizationUuid,+ orgName: ENTRY.organizationName,+ };+ const fetchImpl = async () => ({+ ok: true,+ json: async () => ({+ account: { email: ENTRY.email },+ organization: { uuid: ENTRY.organizationUuid, name: ENTRY.organizationName },+ }),+ });+ assert.equal((await verifyRefreshedTokenIdentity(account, 'synthetic-token', { fetchImpl })).email, ENTRY.email);+ await assert.rejects(+ verifyRefreshedTokenIdentity({ ...account, orgUuid: 'wrong' }, 'synthetic-token', { fetchImpl }),+ /TOKEN_IDENTITY_MISMATCH/,+ );+ await assert.rejects(+ verifyRefreshedTokenIdentity({ email: ENTRY.email }, 'synthetic-token', { fetchImpl }),+ /TOKEN_IDENTITY_CONFIG_MISSING/,+ );+}++// Deprecated capture exits before configuration reads, vault/keychain writes,+// or rotation-data creation.+{+ const root = mkdtempSync(join(tmpdir(), 'rotate-capture-refusal-'));+ const run = spawnSync(process.execPath, [join(import.meta.dirname, '..', 'rotate.mjs'), '--capture'], {+ env: { ...process.env, HOME: root, CLAUDE_PLUGIN_DATA_DIR: join(root, 'plugin-data') },+ encoding: 'utf8',+ });+ assert.equal(run.status, 2);+ assert.match(run.stderr, /staged enrollment is required/);+ assert.equal(existsSync(join(root, 'plugin-data')), false);+}++// Reads are side-effect free; deletion remains a coordinated mutation and fails+// before changing its vault when coordination is unavailable.+{+ const root = mkdtempSync(join(tmpdir(), 'writer-coordination-required-'));+ const rotationVault = join(root, 'rotation.json');+ const service = '[email protected]';+ const token = { claudeAiOauth: { accessToken: 'synthetic', expiresAt: 123 } };+ writeFileSync(rotationVault, JSON.stringify({ [service]: token }), { mode: 0o600 });+ const rotationModule = join(import.meta.dirname, '..', 'rotation-vault.mjs');+ const heal = spawnSync(+ process.execPath,+ [+ '--input-type=module',+ '-e',+ `import(${JSON.stringify(`file://${rotationModule}`)}).then(m=>m.readRotationToken('[email protected]'))`,+ ],+ {+ env: {+ ...process.env,+ HOME: root,+ CLAUDE_ROTATION_FILE_VAULT: rotationVault,+ CLAUDE_AUTH_COORDINATION_CONFIG: '',+ },+ encoding: 'utf8',+ },+ );+ assert.equal(heal.status, 0, heal.stderr);+ assert.deepEqual(JSON.parse(readFileSync(rotationVault, 'utf8')), { [service]: token });++ const linuxModule = join(import.meta.dirname, '..', 'vault-linux.mjs');+ const deletion = spawnSync(+ process.execPath,+ [+ '--input-type=module',+ '-e',+ `import(${JSON.stringify(`file://${linuxModule}`)}).then(m=>m.deleteEntry('some-service'))`,+ ],+ { env: { ...process.env, HOME: root, CLAUDE_AUTH_COORDINATION_CONFIG: '' }, encoding: 'utf8' },+ );+ assert.notEqual(deletion.status, 0);+}++// Authorized rollback is recoverable in a fresh process at every durable+// intent/switch/cleanup boundary without reusing the external approval.+for (const fault of [+ 'SIGKILL:ROLLBACK_PREPARING_INTENT',+ 'SIGKILL:ROLLBACK_TEMP_LINK',+ 'SIGKILL:ROLLBACK_SWITCH',+ 'SIGKILL:ROLLBACK_CLEANUP',+]) {+ const f = fixture();+ f.approval('stage');+ stageEnrollment({ ...f.common, candidatePath: f.candidatePath });+ const target = join(f.paths.active, ENTRY.authFilename);+ const old = JSON.stringify({ ...CANDIDATE, access_token: `rollback-old-${fault}` });+ writeFileSync(target, old, { mode: 0o600 });+ f.approval('activate');+ activateEnrollment(f.common);+ authorizeRollback(f);+ const modulePath = join(import.meta.dirname, '..', 'staged-enrollment.mjs');+ const invoke = `import(${JSON.stringify(`file://${modulePath}`)}).then(m=>process.stdout.write(JSON.stringify(m.rollbackEnrollment(${JSON.stringify({ configPath: f.configPath, entryId: ENTRY.id, approvalPath: f.approvalPath, now: NOW })}))))`;+ const killed = spawnSync(process.execPath, ['--input-type=module', '-e', invoke], {+ encoding: 'utf8',+ env: {+ ...process.env,+ CLAUDE_STAGED_ENROLLMENT_TESTING: '1',+ CLAUDE_STAGED_ENROLLMENT_TEST_FAULT: fault,+ },+ });+ assert.equal(killed.signal, 'SIGKILL', `${fault}: ${killed.stderr}`);+ writeFileSync(f.approvalPath, '{}', { mode: 0o600 });+ const recovered = spawnSync(process.execPath, ['--input-type=module', '-e', invoke], { encoding: 'utf8' });+ 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), []);+}++console.log('staged-enrollment.test.mjs: ok');diff --git a/claude-ops/scripts/account-rotation/__tests__/verified-credential-write.test.mjs b/claude-ops/scripts/account-rotation/__tests__/verified-credential-write.test.mjsnew file mode 100755index 00000000..8c118d86--- /dev/null+++ b/claude-ops/scripts/account-rotation/__tests__/verified-credential-write.test.mjs@@ -0,0 +1,177 @@+#!/usr/bin/env node+import assert from 'node:assert/strict';+import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { createVerifiedCredentialWriter, requireVerifiedCredentialCapability } from '../verified-credential-write.mjs';+import { verifyRefreshedTokenIdentity } from '../token-identity.mjs';++const account = {+ email: '[email protected]',+ orgUuid: 'org-right',+ orgName: 'Right Org',+};+const otherAccount = {+ email: '[email protected]',+ orgUuid: 'org-other',+ orgName: 'Other Org',+};+const credential = (accessToken) => JSON.stringify({ claudeAiOauth: { accessToken }, mcpOAuth: {} });+const profile = (overrides = {}) => ({+ account: { email: account.email },+ organization: { uuid: account.orgUuid, name: account.orgName },+ ...overrides,+});++async function runCase(name, { target = account, response, expectedError = null, token = name }) {+ const dir = mkdtempSync(join(tmpdir(), 'verified-token-write-'));+ const vault = join(dir, 'vault.json');+ writeFileSync(vault, JSON.stringify({ untouched: true }));+ let writes = 0;+ const events = [];+ const writerCapability = {};+ let retainedVerifiedCapability;+ const verify = (candidate, accessToken) =>+ verifyRefreshedTokenIdentity(candidate, accessToken, {+ fetchImpl: async () => response,+ });+ const verifiedWrite = createVerifiedCredentialWriter({+ verify,+ withLock: async (callback) => {+ events.push('lock');+ try {+ return await callback(writerCapability);+ } finally {+ events.push('unlock');+ }+ },+ requireCapability: (candidate) => assert.equal(candidate, writerCapability),+ write(_account, value, verifiedCapability, slot) {+ assert.throws(+ () =>+ requireVerifiedCredentialCapability(verifiedCapability, {+ account: target,+ credential: credential('different-token'),+ destination: slot,+ }),+ { message: 'VERIFIED_CREDENTIAL_BINDING_MISMATCH' },+ );+ requireVerifiedCredentialCapability(verifiedCapability, {+ account: target,+ credential: value,+ destination: slot,+ });+ retainedVerifiedCapability = verifiedCapability;+ events.push('write');+ writes += 1;+ const current = JSON.parse(readFileSync(vault, 'utf8'));+ current[slot] = JSON.parse(value);+ writeFileSync(vault, JSON.stringify(current));+ },+ });++ if (expectedError) {+ await assert.rejects(verifiedWrite(target, credential(token), 'protected'), {+ message: expectedError,+ });+ assert.equal(writes, 0, `${name}: writer must not run`);+ assert.deepEqual(JSON.parse(readFileSync(vault, 'utf8')), { untouched: true });+ assert.deepEqual(events, ['lock', 'unlock']);+ } else {+ await verifiedWrite(target, credential(token), 'protected');+ assert.equal(writes, 1);+ assert.equal(JSON.parse(readFileSync(vault, 'utf8')).protected.claudeAiOauth.accessToken, token);+ assert.deepEqual(events, ['lock', 'write', 'unlock']);+ assert.throws(+ () =>+ requireVerifiedCredentialCapability(retainedVerifiedCapability, {+ account: target,+ credential: credential(token),+ destination: 'protected',+ }),+ { message: 'VERIFIED_CREDENTIAL_CAPABILITY_REQUIRED' },+ 'verified capability revoked after write callback',+ );+ }+ console.log(`ok - ${name}`);+}++await runCase('wrong email', {+ response: { ok: true, json: async () => profile({ account: { email: '[email protected]' } }) },+ expectedError: 'TOKEN_IDENTITY_MISMATCH',+});+await runCase('wrong organization UUID', {+ response: {+ ok: true,+ json: async () => profile({ organization: { uuid: 'org-wrong', name: account.orgName } }),+ },+ expectedError: 'TOKEN_IDENTITY_MISMATCH',+});+await runCase('wrong organization name', {+ response: {+ ok: true,+ json: async () => profile({ organization: { uuid: account.orgUuid, name: 'Wrong Org' } }),+ },+ expectedError: 'TOKEN_IDENTITY_MISMATCH',+});+await runCase('profile failure', {+ response: { ok: false, status: 503, json: async () => ({}) },+ expectedError: 'TOKEN_IDENTITY_PROFILE_FAILED',+});+await runCase('stale activeAccount targets another vault account', {+ target: otherAccount,+ response: { ok: true, json: async () => profile() },+ expectedError: 'TOKEN_IDENTITY_MISMATCH',+});+await runCase('verified success', {+ response: { ok: true, json: async () => profile() },+});++assert.throws(() => requireVerifiedCredentialCapability({}), { message: 'VERIFIED_CREDENTIAL_CAPABILITY_REQUIRED' });+console.log('ok - internal verified capability cannot be forged');++let noIdentityWrites = 0;+const noIdentityWriter = createVerifiedCredentialWriter({+ verify: verifyRefreshedTokenIdentity,+ withLock: (callback) => callback({}),+ requireCapability: () => {},+ write() {+ noIdentityWrites++;+ },+});+await assert.rejects(noIdentityWriter({}, credential('x')), { message: 'TOKEN_IDENTITY_CONFIG_MISSING_EMAIL' });+assert.equal(noIdentityWrites, 0);+console.log('ok - missing configured identity performs zero writes');++await assert.rejects(noIdentityWriter(account, { claudeAiOauth: { accessToken: 'mutable' } }), {+ message: 'SERIALIZED_CREDENTIAL_REQUIRED',+});+assert.equal(noIdentityWrites, 0);+console.log('ok - mutable object credentials are refused before verification');++const mutableAccount = { ...account, label: 'slot-a' };+let writtenSnapshot;+const snapshotWriter = createVerifiedCredentialWriter({+ withLock: (callback) => callback({}),+ requireCapability: () => {},+ destination: (candidate) => `slot:${candidate.label}`,+ verify: async (candidate) => {+ assert.equal(candidate.email, account.email);+ mutableAccount.email = '[email protected]';+ mutableAccount.label = 'slot-b';+ },+ write(candidate, bytes, capability) {+ requireVerifiedCredentialCapability(capability, {+ account: candidate,+ credential: bytes,+ destination: `slot:${candidate.label}`,+ });+ writtenSnapshot = { candidate, bytes };+ },+});+const exactBytes = '{ "claudeAiOauth": { "accessToken": "exact-byte-token" }, "mcpOAuth": {} }';+await snapshotWriter(mutableAccount, exactBytes);+assert.equal(writtenSnapshot.candidate.email, account.email);+assert.equal(writtenSnapshot.candidate.label, 'slot-a');+assert.equal(writtenSnapshot.bytes, exactBytes);+console.log('ok - account, destination, and exact credential bytes are snapshotted before await');diff --git a/claude-ops/scripts/account-rotation/auth-writer-coordination.mjs b/claude-ops/scripts/account-rotation/auth-writer-coordination.mjsnew file mode 100644index 00000000..dad48c82--- /dev/null+++ b/claude-ops/scripts/account-rotation/auth-writer-coordination.mjs@@ -0,0 +1,57 @@+/** Shared single-writer gate for first-party Claude credential mutations. */+import { readDeploymentConfig, withOperationLock } from './staged-enrollment.mjs';+import { AsyncLocalStorage } from 'node:async_hooks';+import { createHash } from 'node:crypto';+import { readFileSync, realpathSync } from 'node:fs';+import { resolve } from 'node:path';++const capabilities = new WeakSet();+const activeWriter = new AsyncLocalStorage();++export function requireWriterCapability(capability) {+ if (!capabilities.has(capability)) throw new Error('AUTH_WRITER_CAPABILITY_REQUIRED');+}++export function withAuthWriterLock(callback, options = {}) {+ const configPath = options.configPath || process.env.CLAUDE_AUTH_COORDINATION_CONFIG;+ const existing = activeWriter.getStore();+ if (existing) {+ // AsyncLocalStorage propagates into detached descendants even after the+ // outer operation has settled. The capability is revoked at settlement,+ // so revalidate it before treating a nested call as lock ownership.+ requireWriterCapability(existing);+ return callback(existing);+ }+ if (process.platform === 'win32') throw new Error('AUTH_COORDINATION_REQUIRES_POSIX');+ if (!configPath) throw new Error('AUTH_COORDINATION_CONFIG_REQUIRED');+ if (!options.configPath && !process.env.CLAUDE_ROTATOR_CONFIG) throw new Error('CLAUDE_ROTATOR_CONFIG_REQUIRED');+ const config = readDeploymentConfig(configPath);+ if (!options.configPath) {+ const inventoryPath = resolve(process.env.CLAUDE_ROTATOR_CONFIG);+ if (realpathSync(inventoryPath) !== inventoryPath || inventoryPath !== config.runtimeInventoryPath)+ throw new Error('RUNTIME_INVENTORY_BINDING_MISMATCH');+ const inventoryDigest = createHash('sha256').update(readFileSync(inventoryPath)).digest('hex');+ if (inventoryDigest !== config.runtimeInventoryDigest) throw new Error('RUNTIME_INVENTORY_BINDING_MISMATCH');+ }+ return withOperationLock(config.operationLockPath, config.approvalKeyPath, (lock) => {+ const capability = Object.freeze({ lockNonce: lock.nonce });+ capabilities.add(capability);+ let result;+ try {+ result = activeWriter.run(capability, () => callback(capability));+ } catch (error) {+ capabilities.delete(capability);+ throw error;+ }+ let asynchronous = false;+ try {+ asynchronous = Boolean(result && typeof result.then === 'function');+ } catch (error) {+ capabilities.delete(capability);+ throw error;+ }+ if (asynchronous) return Promise.resolve(result).finally(() => capabilities.delete(capability));+ capabilities.delete(capability);+ return result;+ });+}diff --git a/claude-ops/scripts/account-rotation/auto-auth-policy.mjs b/claude-ops/scripts/account-rotation/auto-auth-policy.mjsnew file mode 100644index 00000000..5a28c635--- /dev/null+++ b/claude-ops/scripts/account-rotation/auto-auth-policy.mjs@@ -0,0 +1,9 @@+/** Configuration alone is never a signed, exact mutation authorization. */+export function automatedAuthAllowed(_account) {+ return false;+}++/** Direct OAuth writers are never authorized; identity verification is not permission. */+export function directOAuthWriterAllowed(_writer) {+ return false;+}diff --git a/claude-ops/scripts/account-rotation/browser-pin-recovery.mjs b/claude-ops/scripts/account-rotation/browser-pin-recovery.mjsnew file mode 100644index 00000000..8bd460bb--- /dev/null+++ b/claude-ops/scripts/account-rotation/browser-pin-recovery.mjs@@ -0,0 +1,26 @@+import { existsSync } from 'node:fs';++// Browser-pin setup is a legacy direct credential mutation path. There is no+// portable filesystem compare-and-swap that can prove a nonparticipating+// writer did not replace the destination between validation and rename. Keep+// both publication and restoration fail closed until they use the signed+// staged-enrollment writer protocol end to end.+export function applyBrowserPinTransaction() {+ throw new Error('BROWSER_PIN_MUTATION_DISABLED');+}++export function createBrowserPinBackup() {+ throw new Error('BROWSER_PIN_MUTATION_DISABLED');+}++export function recordBrowserPinExpectedPost() {+ throw new Error('BROWSER_PIN_MUTATION_DISABLED');+}++export function restoreBrowserPinBackup({ sentinelPath } = {}) {+ return {+ restored: false,+ reason: 'browser-pin-mutation-disabled',+ retained: typeof sentinelPath === 'string' && existsSync(sentinelPath),+ };+}diff --git a/claude-ops/scripts/account-rotation/bulk-setup-token.mjs b/claude-ops/scripts/account-rotation/bulk-setup-token.mjsindex 20493d46..676d97eb 100644--- a/claude-ops/scripts/account-rotation/bulk-setup-token.mjs+++ b/claude-ops/scripts/account-rotation/bulk-setup-token.mjs@@ -1,590 +1,3 @@#!/usr/bin/env node-/* eslint-disable no-console */--// ──────────────────────────────────────────────────────────────────────────────-// bulk-setup-token.mjs-//-// Loops `claude setup-token` over every account in credits-ledger.json that-// is missing an OAuth bearer token, drives the Anthropic web login via-// Kapture (delegated to a one-shot `claude -p` subprocess with the kapture-// MCP server enabled), then stores the resulting sk-ant-oat01-* token in AWS-// Secrets Manager at <your-org>/claude-oauth-token/account-{1..N}.-//-// Idempotent: skips accounts whose Secrets Manager entry already contains a-// validated sk-ant-oat01-* token AND ledger entry says claimed=true.-//-// Reuses the proven flow from PR #225 (claude-p-as wrapper + ledger.mjs)-// and the kapture-via-claude-p pattern from kapture-claim-credits.mjs.-//-// Usage:-// node bulk-setup-token.mjs [--dry-run] [--only <email>] [--region <r>]-// [--ledger <path>] [--secret-prefix <s>]-// [--gmail-account <addr>]-//-// Defaults:-// --region eu-west-1-// --ledger ~/.claude/credits-ledger.json-// --secret-prefix <your-org>/claude-oauth-token/account--// --gmail-account $BULK_SETUP_GMAIL_ACCOUNT (env) or unset-//-// Required tools on PATH: claude, aws, gog, expect.-//-// NOTE on `claude -p` stdio: the Anthropic CLI (>= v2.1.x) refuses to start-// unless stdin is closed or piped. Inheriting the parent stdin (the default-// for child_process.spawn) makes the CLI emit-// "Warning: no stdin data received in 3s, proceeding without it"-// and then exit 1, which breaks the whole loop. Always spawn with-// `stdio: ['ignore', 'pipe', 'pipe']` (or pipe + immediate `stdin.end()`).-// Regression fix landed after PR #229.-//-// HARD RULES-// - Never log plaintext tokens.-// - Never write tokens to disk except via `aws secretsmanager update-secret`-// stdin. Local /tmp files are shred-deleted on exit.-// - Per-account run is atomic: errors don't corrupt ledger or-// Secrets Manager state for other accounts.-//-// ──────────────────────────────────────────────────────────────────────────────--import { spawn, spawnSync } from 'node:child_process';-import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';-import { tmpdir } from 'node:os';-import { join } from 'node:path';-import { setTimeout as sleep } from 'node:timers/promises';--import { findAccount, readLedger, upsertAccount, writeLedger } from './ledger.mjs';--// ─── CLI ────────────────────────────────────────────────────────────────────--const args = process.argv.slice(2);-function flag(name) {- return args.includes(name);-}-function value(name, fallback) {- const i = args.indexOf(name);- return i >= 0 && i + 1 < args.length ? args[i + 1] : fallback;-}--const DRY_RUN = flag('--dry-run');-const ONLY = value('--only', null);-const REGION = value('--region', 'eu-west-1');-const HOME = process.env.HOME || process.env.USERPROFILE;-const LEDGER_PATH = value('--ledger', join(HOME, '.claude', 'credits-ledger.json'));-const SECRET_PREFIX = value('--secret-prefix', '<your-org>/claude-oauth-token/account-');-const GMAIL_ACCOUNT = value('--gmail-account', process.env.BULK_SETUP_GMAIL_ACCOUNT || null);-const SUBPROCESS_TIMEOUT_MS = 8 * 60 * 1000; // 8 min per Kapture step--// ─── logging ────────────────────────────────────────────────────────────────--const TAG = '[bulk-setup-token]';-function log(...a) {- console.error(TAG, ...a);-}-function logRedacted(label, secret) {- const s = typeof secret === 'string' ? secret : String(secret);- if (s.length < 12) {- log(label, '(redacted, len=' + s.length + ')');- } else {- log(label, s.slice(0, 18) + '…' + s.slice(-6) + ' (len=' + s.length + ')');- }-}--// ─── tmp dir scrubbed on exit ───────────────────────────────────────────────--const TMP = mkdtempSync(join(tmpdir(), 'bulk-setup-token-'));-function scrubTmp() {- try {- rmSync(TMP, { recursive: true, force: true });- } catch {- /* ignore */- }-}-process.on('exit', scrubTmp);-process.on('SIGINT', () => {- scrubTmp();- process.exit(130);-});-process.on('SIGTERM', () => {- scrubTmp();- process.exit(143);-});--// ─── Kapture-via-claude-p delegate ─────────────────────────────────────────--function buildLoginPrompt(email) {- return [- `You are driving Kapture to log into the Anthropic Claude Console.`,- ``,- `Steps:`,- `1. mcp__kapture__new_tab — open a fresh Chrome tab. Stash the tabId.`,- `2. mcp__kapture__navigate to https://platform.claude.com/login`,- `3. mcp__kapture__fill the #email input with: ${email}`,- `4. mcp__kapture__click the button with data-testid="continue".`,- `5. mcp__kapture__show the tab (brings to front so subsequent click can work).`,- `6. Wait ~3 seconds for the "Enter the verification code sent to ${email}" screen to render.`,- `7. Emit ONE LINE of JSON on stdout: {"ok":true,"tabId":"<tabId>"}`,- ``,- `If anything fails before step 7, emit instead: {"ok":false,"error":"<short reason>"}`,- `Do not retry. Do not Authorize anything in this session.`,- ].join('\n');-}--function buildAuthorizePrompt(tabId, authUrl) {- return [- `You are driving Kapture to complete an Anthropic Claude Code OAuth consent.`,- ``,- `Steps:`,- `1. mcp__kapture__navigate tab ${tabId} to: ${authUrl}`,- `2. mcp__kapture__show the tab.`,- `3. Wait ~3 seconds for the consent page to render (button data-testid is not set; use #kapture-1 or the primary button with text "Authorize").`,- `4. mcp__kapture__click the Authorize button. After click the page redirects to platform.claude.com/oauth/code/callback?code=…&state=…`,- `5. Read the final URL via mcp__kapture__elements selector="body" or by inspecting the navigation state.`,- `6. Extract the "code" query parameter from the final URL.`,- `7. Emit ONE LINE of JSON on stdout: {"ok":true,"code":"<the code>","state":"<the state>"}`,- ``,- `If anything fails, emit: {"ok":false,"error":"<short reason>"}`,- `Do not Decline. Do not navigate elsewhere.`,- ].join('\n');-}--function buildMagicLinkPrompt(tabId, magicLinkUrl) {- return [- `You are driving Kapture to complete an Anthropic magic-link sign-in.`,- ``,- `Steps:`,- `1. mcp__kapture__navigate tab ${tabId} to: ${magicLinkUrl}`,- `2. Wait ~3 seconds for the redirect to platform.claude.com/settings/billing (= logged in).`,- `3. Read the resulting URL. If it contains "/login" or "/error", login failed.`,- `4. Emit ONE LINE of JSON: {"ok":true,"url":"<final-url>"} or {"ok":false,"error":"<reason>"}`,- ].join('\n');-}--function invokeClaude(prompt, label) {- return new Promise((resolve) => {- let settled = false;- let timer;- const done = (payload) => {- if (settled) return;- settled = true;- clearTimeout(timer);- resolve(payload);- };-- log(`${label}: invoking claude -p…`);- // stdio: close stdin so `claude -p` doesn't emit "no stdin data received in 3s" and exit 1.- const child = spawn('claude', ['-p', prompt], { stdio: ['ignore', 'pipe', 'pipe'] });- timer = setTimeout(() => {- try {- child.kill('SIGTERM');- } catch {- /* ignore */- }- done({ ok: false, error: `${label}: claude -p timed out after ${SUBPROCESS_TIMEOUT_MS / 1000}s` });- }, SUBPROCESS_TIMEOUT_MS);-- let stdout = '';- let stderr = '';- child.stdout?.setEncoding('utf8');- child.stderr?.setEncoding('utf8');- child.stdout?.on('data', (c) => {- stdout += c;- });- child.stderr?.on('data', (c) => {- stderr += c;- });- child.on('error', (err) => done({ ok: false, error: `${label}: spawn failed: ${err.message}` }));- child.on('close', (code, signal) => {- if (settled) return;- if (code !== 0) {- const hint = signal ? ` (signal ${signal})` : '';- done({ ok: false, error: `${label}: exit ${code}${hint}: ${stderr.slice(0, 400)}` });- return;- }- const lines = stdout.trim().split('\n').reverse();- for (const line of lines) {- const t = line.trim();- if (t.startsWith('{') && t.endsWith('}')) {- try {- const parsed = JSON.parse(t);- done({ ok: true, result: parsed });- return;- } catch {- /* try next line */- }- }- }- done({ ok: false, error: `${label}: no JSON result line in claude -p stdout: ${stdout.slice(-400)}` });- });- });-}--// ─── gog Gmail poller for the magic-link email ─────────────────────────────--async function pollMagicLink(email, sinceMs, deadlineMs) {- // Anthropic magic-link emails arrive within ~30s; we poll Gmail every 5s- // for newer-than-5m emails matching the secure-link subject. The body is- // base64-encoded HTML containing a https://platform.claude.com/magic-link#…- // anchor — we extract that URL.- while (Date.now() < deadlineMs) {- const q = `from:[email protected] OR from:[email protected] newer_than:10m`;- const args2 = ['gmail', 'search', q, '--max', '5', '-j', '--results-only', '--no-input'];- if (GMAIL_ACCOUNT) args2.unshift('-a', GMAIL_ACCOUNT);- const r = spawnSync('gog', args2, { encoding: 'utf8' });- if (r.status === 0 && r.stdout.trim().startsWith('[')) {- const threads = JSON.parse(r.stdout);- for (const t of threads) {- const ts = Number(t.internalDate || 0);- // gog gives "date":"YYYY-MM-DD HH:MM" only, no ms; fall back to id-based.- if (- (t.subject || '').toLowerCase().includes('secure link') ||- (t.subject || '').toLowerCase().includes('claude console')- ) {- // Fetch full thread to extract the magic-link URL from the HTML body.- const tid = t.id || t.threadId;- if (!tid) continue;- const r2 = spawnSync(- 'gog',- [...(GMAIL_ACCOUNT ? ['-a', GMAIL_ACCOUNT] : []), 'gmail', 'thread', 'get', tid, '-j', '--no-input'],- { encoding: 'utf8' },- );- if (r2.status !== 0) continue;- const thread = JSON.parse(r2.stdout);- const msg = thread?.thread?.messages?.[0];- const bodyB64 = msg?.payload?.body?.data;- if (!bodyB64) continue;- // gog returns base64url- const html = Buffer.from(bodyB64.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8');- const m = html.match(/https:\/\/platform\.claude\.com\/magic-link#[A-Za-z0-9+/=:.-]+/);- if (m) {- // Decode the trailing base64 email part and confirm it matches.- const frag = m[0].split('#')[1];- const parts = frag.split(':');- if (parts.length === 2) {- const decoded = Buffer.from(parts[1], 'base64').toString('utf8');- if (decoded.toLowerCase() === email.toLowerCase()) {- return m[0];- }- }- }- }- // ignore non-matching emails- void ts;- void sinceMs;- }- }- await sleep(5000);- }- throw new Error(`magic-link email never arrived for ${email} within deadline`);-}--// ─── expect-driven `claude setup-token` ────────────────────────────────────--const EXPECT_SCRIPT = `#!/usr/bin/env expect -f-log_user 0-set timeout 3600-set logfile [lindex $argv 0]-set codefile [lindex $argv 1]-set tokenfile [lindex $argv 2]-log_file -a $logfile-spawn -noecho claude setup-token-set sent 0-while 1 {- expect {- -re {prompted} {- if {$sent == 0} {- set sent 1- while {![file exists $codefile]} { exec sleep 1 }- set fh [open $codefile r]- set code [string trim [read $fh]]- close $fh- send -- "$code"- after 200- send -- "\\r"- }- }- -re {sk-ant-oat01-[A-Za-z0-9_-]+} {- set token $expect_out(0,string)- # trim trailing alphanumeric run that may include the "S" of "Store this token securely…"- regsub {Store?$} $token "" token- set fh [open $tokenfile w]- puts -nonewline $fh $token- close $fh- puts stderr "TOKEN_CAPTURED"- }- timeout { puts stderr "TIMEOUT"; exit 2 }- eof { puts stderr "EOF"; exit 0 }- }-}-`;--function startSetupTokenExpect(accountDir) {- const expectScript = join(accountDir, 'driver.exp');- const log = join(accountDir, 'setup.log');- const codeFile = join(accountDir, 'oauth-code.txt');- const tokenFile = join(accountDir, 'token.txt');- writeFileSync(expectScript, EXPECT_SCRIPT, { mode: 0o700 });- const child = spawn('expect', ['-f', expectScript, log, codeFile, tokenFile], {- detached: true,- stdio: 'ignore',- });- child.unref();- return { child, expectScript, log, codeFile, tokenFile };-}--function readOauthAuthorizeUrl(logPath, deadlineMs) {- return new Promise((resolve, reject) => {- const interval = setInterval(() => {- if (!existsSync(logPath)) return;- const raw = readFileSync(logPath);- // strip OSC hyperlinks then CSI- const stripped = raw- .toString('binary')- // eslint-disable-next-line no-control-regex- .replace(/\x1b\][^\x07\x1b]*(\x07|\x1b\\)/g, '')- // eslint-disable-next-line no-control-regex- .replace(/\x1b\[[0-9;?>]*[a-zA-Z]/g, '')- .replace(/\r/g, '');- const m = stripped.match(- /https:\/\/claude\.com\/cai\/oauth\/authorize\?code=true&client_id=[a-z0-9-]+&response_type=code&redirect_uri=https%3A%2F%2Fplatform\.claude\.com%2Foauth%2Fcode%2Fcallback&scope=user%3Ainference&code_challenge=[A-Za-z0-9_-]+&code_challenge_method=S256&state=[A-Za-z0-9_-]+/,- );- if (m) {- clearInterval(interval);- resolve(m[0]);- } else if (Date.now() > deadlineMs) {- clearInterval(interval);- reject(new Error('OAuth URL never appeared in setup-token log'));- }- }, 500);- });-}--function waitForToken(tokenFile, deadlineMs) {- return new Promise((resolve, reject) => {- const interval = setInterval(() => {- if (existsSync(tokenFile)) {- const tok = readFileSync(tokenFile, 'utf8').trim();- if (tok.startsWith('sk-ant-oat01-') && tok.length > 60) {- clearInterval(interval);- resolve(tok);- }- } else if (Date.now() > deadlineMs) {- clearInterval(interval);- reject(new Error('token never appeared in tokenFile'));- }- }, 500);- });-}--// ─── Anthropic API validation ──────────────────────────────────────────────--async function validateToken(token) {- const res = await fetch('https://api.anthropic.com/v1/messages', {- method: 'POST',- headers: {- Authorization: `Bearer ${token}`,- 'anthropic-version': '2023-06-01',- 'content-type': 'application/json',- },- body: JSON.stringify({- model: 'claude-haiku-4-5-20251001',- max_tokens: 4,- messages: [{ role: 'user', content: 'ping' }],- }),- });- if (res.status !== 200) {- const body = await res.text().catch(() => '');- throw new Error(`token validation HTTP ${res.status}: ${body.slice(0, 200)}`);- }-}--// ─── AWS Secrets Manager ───────────────────────────────────────────────────--function storeSecret(email, accountSlot, token) {- const secretId = `${SECRET_PREFIX}${accountSlot}`;- const payload = JSON.stringify({- email,- token,- minted_at: new Date().toISOString(),- scope: 'user:inference',- });- const r = spawnSync(- 'aws',- ['secretsmanager', 'update-secret', '--region', REGION, '--secret-id', secretId, '--secret-string', payload],- { encoding: 'utf8' },- );- if (r.status !== 0) {- throw new Error(`aws update-secret failed for ${secretId}: ${r.stderr.slice(0, 300)}`);- }- return secretId;-}--function existingSecretEmail(accountSlot) {- const secretId = `${SECRET_PREFIX}${accountSlot}`;- const r = spawnSync(- 'aws',- [- 'secretsmanager',- 'get-secret-value',- '--region',- REGION,- '--secret-id',- secretId,- '--query',- 'SecretString',- '--output',- 'text',- ],- { encoding: 'utf8' },- );- if (r.status !== 0) return null;- try {- const j = JSON.parse(r.stdout);- if (typeof j.token === 'string' && j.token.startsWith('sk-ant-oat01-')) return j.email;- } catch {- /* ignore */- }- return null;-}--// ─── orchestrator ──────────────────────────────────────────────────────────--async function processOne(ledger, email, slot) {- log(`\n────────── account-${slot}: ${email} ──────────`);-- // Idempotency: skip if Secrets Manager already has a real token- // AND ledger entry marks the account as token-claimed.- const existing = existingSecretEmail(slot);- const ledgerEntry = findAccount(ledger, email);- if (existing && existing.toLowerCase() === email.toLowerCase() && ledgerEntry?.oauth_token_claimed) {- log(`SKIP — token already present at ${SECRET_PREFIX}${slot} and ledger.oauth_token_claimed=true`);- return { skipped: true };- }- if (DRY_RUN) {- log(`DRY-RUN — would mint + store sk-ant-oat01-* for ${email} at ${SECRET_PREFIX}${slot}`);- return { dryRun: true };- }-- const accountDir = mkdtempSync(join(TMP, `acct-${slot}-`));-- // Step 1: drive Kapture to login form + click "Continue with email".- const login = await invokeClaude(buildLoginPrompt(email), `login(${email})`);- if (!login.ok || !login.result?.ok) {- throw new Error(`login step failed: ${login.error || JSON.stringify(login.result)}`);- }- const tabId = login.result.tabId;- log(`login submitted, tabId=${tabId}`);-- // Step 2: poll Gmail for magic-link.- const since = Date.now();- const magicLinkUrl = await pollMagicLink(email, since, since + 3 * 60 * 1000);- log(`magic-link URL received (len=${magicLinkUrl.length})`);-- // Step 3: drive Kapture to magic-link URL → logged in.- const mlin = await invokeClaude(buildMagicLinkPrompt(tabId, magicLinkUrl), `magic-link(${email})`);- if (!mlin.ok || !mlin.result?.ok) {- throw new Error(`magic-link step failed: ${mlin.error || JSON.stringify(mlin.result)}`);- }- log(`logged in as ${email}, final url=${mlin.result.url}`);-- // Step 4: spawn `claude setup-token` via expect, await OAuth URL.- const exp = startSetupTokenExpect(accountDir);- const oauthUrl = await readOauthAuthorizeUrl(exp.log, Date.now() + 60 * 1000);- log(`setup-token OAuth URL captured (len=${oauthUrl.length})`);-- // Step 5: drive Kapture to OAuth consent → grab code from callback.- const auth = await invokeClaude(buildAuthorizePrompt(tabId, oauthUrl), `authorize(${email})`);- if (!auth.ok || !auth.result?.ok) {- try {- process.kill(exp.child.pid, 'SIGKILL');- } catch {- /* ignore */- }- throw new Error(`authorize step failed: ${auth.error || JSON.stringify(auth.result)}`);- }- const { code, state } = auth.result;- log(`authorize callback parsed (code len=${code.length})`);-- // Step 6: pipe `<code>#<state>` to expect via the codeFile.- writeFileSync(exp.codeFile, `${code}#${state}`);- const token = await waitForToken(exp.tokenFile, Date.now() + 60 * 1000);- logRedacted(`token captured for ${email}`, token);-- // Step 7: validate via Anthropic API.- await validateToken(token);- log(`token validated against /v1/messages`);-- // Step 8: store in Secrets Manager.- const secretId = storeSecret(email, slot, token);- log(`stored in ${secretId}`);-- // Step 9: mark ledger.- upsertAccount(ledger, email, {- cycle: ledger.month,- oauth_token_claimed: true,- oauth_token_minted_at: new Date().toISOString(),- oauth_token_secret_id: secretId,- });- writeLedger(LEDGER_PATH, ledger);-- // Step 10: scrub the per-account tmpdir (token + intermediate code).- try {- rmSync(accountDir, { recursive: true, force: true });- } catch {- /* ignore */- }-- return { ok: true, secretId };-}--// ─── main ──────────────────────────────────────────────────────────────────--async function main() {- if (!existsSync(LEDGER_PATH)) {- log(`FATAL: ledger not found at ${LEDGER_PATH}`);- process.exit(2);- }- const ledger = readLedger(LEDGER_PATH);- if (!Array.isArray(ledger.accounts) || ledger.accounts.length === 0) {- log(`FATAL: ledger has no accounts (after v1→v2 migration). seed the file first.`);- process.exit(2);- }-- // Establish a stable slot mapping: account-N == the Nth entry in- // ledger.accounts as written. This matches the existing Secrets Manager- // layout (placeholders 1..7) so we don't have to remap.- const entries = ledger.accounts.map((a, i) => ({ email: a.email, slot: i + 1 }));- const targets = ONLY ? entries.filter((e) => e.email.toLowerCase() === ONLY.toLowerCase()) : entries;- if (targets.length === 0) {- log(`no targets — check --only argument or ledger contents.`);- process.exit(2);- }- log(`processing ${targets.length}/${entries.length} accounts. region=${REGION} ledger=${LEDGER_PATH}`);- if (DRY_RUN) log(`DRY-RUN mode — no Secrets Manager / ledger writes.`);-- const results = [];- for (const { email, slot } of targets) {- try {- const r = await processOne(ledger, email, slot);- results.push({ email, slot, ...r });- } catch (err) {- log(`FAILED ${email}: ${err.message}`);- results.push({ email, slot, ok: false, error: err.message });- }- }-- // Final summary- log(`\n────────── summary ──────────`);- for (const r of results) {- if (r.skipped) log(`SKIP account-${r.slot} ${r.email}`);- else if (r.dryRun) log(`DRY account-${r.slot} ${r.email}`);- else if (r.ok) log(`OK account-${r.slot} ${r.email} → ${r.secretId}`);- else log(`FAIL account-${r.slot} ${r.email} — ${r.error}`);- }- const failed = results.filter((r) => r.ok === false);- process.exit(failed.length > 0 ? 1 : 0);-}--main().catch((err) => {- log(`FATAL: ${err.message}`);- process.exit(2);-});+process.stderr.write('bulk credential setup refused: staged enrollment is required\n');+process.exitCode = 2;diff --git a/claude-ops/scripts/account-rotation/claude-p-as.mjs b/claude-ops/scripts/account-rotation/claude-p-as.mjsindex d1c86e56..eecc09fd 100755--- a/claude-ops/scripts/account-rotation/claude-p-as.mjs+++ b/claude-ops/scripts/account-rotation/claude-p-as.mjs@@ -30,12 +30,11 @@*/import { existsSync, readFileSync, writeFileSync, openSync, closeSync, unlinkSync, constants as fsConstants } from 'fs';-import { spawnSync, spawn } from 'child_process';+import { spawnSync } from 'child_process';import { dirname, join } from 'path';import { fileURLToPath } from 'url';-import { homedir, constants } from 'os';+import { homedir } from 'os';-import { swapToEmail, restoreToken } from './keychain-swap.mjs';import { readLedger, writeLedger, findAccount, upsertAccount } from './ledger.mjs';const __dirname = dirname(fileURLToPath(import.meta.url));@@ -45,8 +44,9 @@ const DEFAULT_LOCK = join(homedir(), '.claude', 'keychain.lock');const HARD_CAP_USD = 200;function die(code, msg) {- process.stderr.write(`[claude-p-as] ${msg}\n`);- process.exit(code);+ const error = new Error(msg);+ error.exitCode = code;+ throw error;}function parseArgs(argv) {@@ -117,10 +117,39 @@ function assertNotExtraUsage(account, configPath) {if (match && (match.extraUsageEnabled === true || match.extra_usage === true))die(2, `account ${account.email} has extraUsageEnabled=true in config — refusing to bill against paid overage`);} catch (e) {+ if (e.exitCode) throw e;process.stderr.write(`[claude-p-as] warning: could not read config ${configPath}: ${e.message}\n`);}}+function configuredSwapIdentities(account, configPath) {+ let config;+ let state;+ try {+ config = JSON.parse(readFileSync(configPath, 'utf8'));+ state = JSON.parse(readFileSync(join(dirname(configPath), 'state.json'), 'utf8'));+ } catch {+ throw new Error('EXACT_SWAP_IDENTITY_REQUIRED');+ }+ const complete = (candidate) =>+ candidate &&+ typeof candidate.email === 'string' &&+ typeof candidate.orgUuid === 'string' &&+ candidate.orgUuid.trim() &&+ typeof candidate.orgName === 'string' &&+ candidate.orgName.trim();+ const target = (config.accounts || []).find(+ (candidate) =>+ candidate.email?.toLowerCase() === account.email.toLowerCase() &&+ (account.label === undefined || candidate.label === account.label),+ );+ const previous = (config.accounts || []).find(+ (candidate) => (candidate.label || candidate.email) === state.activeAccount,+ );+ if (!complete(target) || !complete(previous)) throw new Error('EXACT_SWAP_IDENTITY_REQUIRED');+ return { target, previous };+}+/*** P1b fix: probe must run AFTER keychain swap so it tests the target account's CLI install.* Call this AFTER swapToEmail() succeeds, BEFORE spawning claude -p.@@ -251,6 +280,12 @@ function decrementLedger(ledgerPath, email, amount) {async function main(argv) {const opts = parseArgs(argv);+ // Credential swaps require a fresh, shared, signed mutation approval. This+ // wrapper has no integration for that approval yet, so refuse before reading+ // mutable account state, taking locks, swapping credentials, or spawning a+ // child. Pure budget/ledger helpers remain importable for offline tests.+ die(2, 'SIGNED_CREDENTIAL_MUTATION_APPROVAL_REQUIRED');+if (!existsSync(opts.ledger))die(2,@@ -267,111 +302,149 @@ async function main(argv) {const account = pickAccount(ledger, opts.pin);assertNotExtraUsage(account, opts.config);- // P1b fix: do NOT call assertBudgetFlagAvailable() here — it runs post-swap below.-- const budget = effectiveBudget(opts.budget, account.remaining_usd);-- // Acquire lock BEFORE any keychain mutation.+ // Acquire the legacy process lock before config/profile work so an existing+ // invocation remains the decisive refusal and no second process can race it.const lockFd = acquireLock(opts.lock);-- // Swap keychain.- let previousToken = null;+ let identities;try {- previousToken = swapToEmail(account.email, account.label);- } catch (e) {+ identities = configuredSwapIdentities(account, opts.config);+ } catch (error) {releaseLock(lockFd, opts.lock);- die(2, `keychain swap failed: ${e.message}`);+ die(2, error.message);}- // Wire restoration on every exit path BEFORE spawning child.- let restored = false;- const restoreOnce = () => {- if (restored) return;- restored = true;+ // P1b fix: do NOT call assertBudgetFlagAvailable() here — it runs post-swap below.++ const budget = effectiveBudget(opts.budget, account.remaining_usd);++ const finalExitCode = await withAuthWriterLock(async (writerCapability) => {+ // Hold the canonical lock across swap, child execution, and restoration.+ let previousToken = null;+ let restorationAuthorization = null;try {- if (previousToken) restoreToken(previousToken);+ const swapped = await swapToAccountCoordinated(identities.target, identities.previous, writerCapability);+ previousToken = swapped.previousToken;+ restorationAuthorization = swapped.authorization;} catch (e) {- process.stderr.write(`[claude-p-as] warning: failed to restore previous keychain: ${e.message}\n`);+ releaseLock(lockFd, opts.lock);+ die(2, `keychain swap failed: ${e.message}`);}- releaseLock(lockFd, opts.lock);- };- process.on('exit', restoreOnce);- for (const sig of ['SIGINT', 'SIGTERM', 'SIGHUP', 'SIGQUIT']) {- process.on(sig, () => {- restoreOnce();- const n = constants.signals[sig];- process.exit(n == null ? 130 : 128 + n);- });- }-- // P1b fix: probe --max-budget-usd AFTER swap — now tests target account's CLI env.- assertBudgetFlagAvailable();- // Build claude args. Strip user-supplied --max-budget-usd if present, then prefix our floor.- const userArgs = [];- for (let i = 0; i < opts.rest.length; i++) {- const a = opts.rest[i];- if (a.startsWith('--max-budget-usd=')) {- continue;- }- if (a === '--max-budget-usd' && opts.rest[i + 1] != null) {- i++; // skip the value too- continue;+ // Wire restoration on every exit path BEFORE spawning child.+ let restored = false;+ let processLockReleased = false;+ const restoreOnce = async () => {+ if (restored) return;+ try {+ if (previousToken) await restoreTokenCoordinated(restorationAuthorization, previousToken, writerCapability);+ restored = true;+ } finally {+ if (!processLockReleased) {+ releaseLock(lockFd, opts.lock);+ processLockReleased = true;+ }+ }+ };+ for (const sig of ['SIGINT', 'SIGTERM', 'SIGHUP', 'SIGQUIT']) {+ process.on(sig, async () => {+ try {+ await restoreOnce();+ const n = constants.signals[sig];+ process.exit(n == null ? 130 : 128 + n);+ } catch (error) {+ process.stderr.write(`[claude-p-as] fatal restoration failure: ${error.message}\n`);+ process.exit(1);+ }+ });}- userArgs.push(a);- }- const finalArgs = ['-p', '--max-budget-usd', String(budget), ...userArgs];-- // Spawn claude. Stream output through; collect for cost parsing.- const stdoutChunks = [];- const stderrChunks = [];- const child = spawn('claude', finalArgs, { stdio: ['inherit', 'pipe', 'pipe'] });- child.stdout.on('data', (b) => {- stdoutChunks.push(b);- process.stdout.write(b);- });- child.stderr.on('data', (b) => {- stderrChunks.push(b);- process.stderr.write(b);- });- const exitCode = await new Promise((resolve) => {- child.on('close', (code, signal) => {- if (signal) {- const n = constants.signals[signal];- resolve(n == null ? 128 : 128 + n);- } else {- resolve(code ?? 1);+ try {+ // P1b fix: probe --max-budget-usd AFTER swap — now tests target account's CLI env.+ assertBudgetFlagAvailable();++ // Build claude args. Strip user-supplied --max-budget-usd if present, then prefix our floor.+ const userArgs = [];+ for (let i = 0; i < opts.rest.length; i++) {+ const a = opts.rest[i];+ if (a.startsWith('--max-budget-usd=')) {+ continue;+ }+ if (a === '--max-budget-usd' && opts.rest[i + 1] != null) {+ i++; // skip the value too+ continue;+ }+ userArgs.push(a);}- });- child.on('error', (e) => {- process.stderr.write(`[claude-p-as] spawn failed: ${e.message}\n`);- resolve(127);- });- });-- // P1a fix: scan both streams; refuse (exit 2) if parse fails — never silently floor at $0.01.- const out = Buffer.concat(stdoutChunks).toString('utf8');- const err = Buffer.concat(stderrChunks).toString('utf8');- const cost = parseUsageCost(out, err);- if (cost == null) {- process.stderr.write('[claude-p-as] cost parse failed; refusing to decrement; check claude CLI output format\n');- restoreOnce();- process.exit(2);- }- decrementLedger(opts.ledger, account.email, cost);+ const finalArgs = ['-p', '--max-budget-usd', String(budget), ...userArgs];++ // Spawn claude. Stream output through; collect for cost parsing.+ const stdoutChunks = [];+ const stderrChunks = [];+ const child = spawn('claude', finalArgs, { stdio: ['inherit', 'pipe', 'pipe'] });+ child.stdout.on('data', (b) => {+ stdoutChunks.push(b);+ process.stdout.write(b);+ });+ child.stderr.on('data', (b) => {+ stderrChunks.push(b);+ process.stderr.write(b);+ });++ const exitCode = await new Promise((resolve) => {+ child.on('close', (code, signal) => {+ if (signal) {+ const n = constants.signals[signal];+ resolve(n == null ? 128 : 128 + n);+ } else {+ resolve(code ?? 1);+ }+ });+ child.on('error', (e) => {+ process.stderr.write(`[claude-p-as] spawn failed: ${e.message}\n`);+ resolve(127);+ });+ });++ // P1a fix: scan both streams; refuse (exit 2) if parse fails — never silently floor at $0.01.+ const out = Buffer.concat(stdoutChunks).toString('utf8');+ const err = Buffer.concat(stderrChunks).toString('utf8');+ const cost = parseUsageCost(out, err);+ if (cost == null) {+ process.stderr.write(+ '[claude-p-as] cost parse failed; refusing to decrement; check claude CLI output format\n',+ );+ return 2;+ }+ decrementLedger(opts.ledger, account.email, cost);- restoreOnce();- process.exit(exitCode);+ return exitCode;+ } finally {+ await restoreOnce();+ }+ });+ return finalExitCode;}// Pure-import guard so tests can require helpers without triggering CLI.const invokedAsCli = process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1];if (invokedAsCli) {- main(process.argv.slice(2)).catch((e) => {- process.stderr.write(`[claude-p-as] fatal: ${e.stack || e.message}\n`);- process.exit(1);- });+ main(process.argv.slice(2))+ .then((code) => process.exit(code))+ .catch((e) => {+ process.stderr.write(+ `[claude-p-as] ${e.exitCode ? '' : 'fatal: '}${e.exitCode ? e.message : e.stack || e.message}\n`,+ );+ process.exit(e.exitCode || 1);+ });}-export { parseArgs, pickAccount, assertNotExtraUsage, effectiveBudget, parseUsageCost, decrementLedger };+export {+ parseArgs,+ pickAccount,+ assertNotExtraUsage,+ configuredSwapIdentities,+ effectiveBudget,+ parseUsageCost,+ decrementLedger,+ main,+};diff --git a/claude-ops/scripts/account-rotation/config.example.json b/claude-ops/scripts/account-rotation/config.example.jsonindex 0657f57f..8c4ce6d7 100644--- a/claude-ops/scripts/account-rotation/config.example.json+++ b/claude-ops/scripts/account-rotation/config.example.json@@ -5,11 +5,12 @@"email": "[email protected]","label": "optional-disambiguator","crsAccountName": "pool-example",- "orgName": "Optional Workspace Name",- "orgUuid": "optional-workspace-uuid",+ "orgName": "Required Workspace or Personal Account Name",+ "orgUuid": "required-organization-uuid","dashlaneTokenPath": "dl://[email protected]/password","dashlaneGooglePath": null,"googleSmsPhone": "+1234567890",+ "automatedCredentialMutation": false,"extraUsageEnabled": false,"capacityMultiplier": 1.0},@@ -67,11 +68,11 @@"tokenRefreshWindowMs": 1800000,"_tokenRefreshWindowMs_note": "Refresh an account's token once it's within this many ms of expiry (default 30m).","enableMagicLinkRecovery": false,- "_enableMagicLinkRecovery_note": "Off by default (or $CRS_ENABLE_MAGIC_LINK=1). Turns on magic-link-autoloop.mjs, which dispatches an UNATTENDED browser-based re-auth for ONE account per tick that crs-401-refresher.mjs (or, if that's disabled, a direct vault check) has flagged as needing reauth — i.e. a confirmed dead refresh_token, not just an expiring one. Serial, single-flight, and skips entirely if a rotation is already in progress. Nothing account-specific is hardcoded. Leave off if re-auth should always be manual.",+ "_enableMagicLinkRecovery_note": "Deprecated and fail-closed. Unattended reauthentication is disabled; use the signed staged-enrollment workflow. No environment variable re-enables direct auth writes.","magicLinkRetryCooldownMs": 21600000,"_magicLinkRetryCooldownMs_note": "Minimum time between unattended retry attempts for the SAME account, success or failure, so a persistently-broken account isn't retried in a tight loop (default 6h).",- "magicLinkDispatch": "setup",- "_magicLinkDispatch_note": "How magic-link-autoloop invokes rotate.mjs. `setup` (default) = `--setup --only=<key> --auto --skip-valid`. `magic-link` = `--magic-link --force --allow-exhausted --to <key>` for installs whose rotate.mjs implements that path. Override with $CRS_MAGIC_LINK_DISPATCH.",+ "magicLinkDispatch": "disabled",+ "_magicLinkDispatch_note": "Retained for config compatibility only. The autoloop never dispatches authentication; staged enrollment is required.","magicLinkHeaded": true,"_magicLinkHeaded_note": "Pass CLAUDE_ROT_HEADED=1 to the rotate child (default true). Interactive captcha walls need a headed browser on CLAUDE_DESKTOP_DISPLAY. Override with $CLAUDE_ROT_HEADED=0 only for pure headless experiments.","magicLinkRotateTimeoutMs": 1200000,diff --git a/claude-ops/scripts/account-rotation/credential-file-publication.mjs b/claude-ops/scripts/account-rotation/credential-file-publication.mjsnew file mode 100644index 00000000..767b4ada--- /dev/null+++ b/claude-ops/scripts/account-rotation/credential-file-publication.mjs@@ -0,0 +1,82 @@+import { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync, realpathSync } from 'node:fs';+import { createHash } from 'node:crypto';+import { dirname, isAbsolute, resolve } from 'node:path';++const digest = (bytes) => createHash('sha256').update(bytes).digest('hex');+const identity = (stat) => ({+ dev: stat.dev.toString(),+ ino: stat.ino.toString(),+ birthtimeNs: stat.birthtimeNs.toString(),+});+const sameIdentity = (left, right) =>+ left?.dev === right?.dev && left?.ino === right?.ino && left?.birthtimeNs === right?.birthtimeNs;++function canonicalParent(path) {+ const parent = dirname(path);+ if (realpathSync(parent) !== resolve(parent)) throw new Error('CREDENTIAL_DESTINATION_ALIAS');+ const stat = lstatSync(parent);+ if (!stat.isDirectory() || stat.uid !== process.getuid() || (stat.mode & 0o022) !== 0)+ throw new Error('INSECURE_CREDENTIAL_DIRECTORY');+}++function namedExists(path) {+ try {+ lstatSync(path);+ return true;+ } catch (error) {+ if (error?.code === 'ENOENT') return false;+ throw error;+ }+}++export function snapshotCredentialFile(path, { allowAbsent = true } = {}) {+ if (!isAbsolute(path)) throw new Error('CREDENTIAL_DESTINATION_ABSOLUTE_REQUIRED');+ canonicalParent(path);+ if (!namedExists(path)) {+ if (!allowAbsent) throw new Error('CREDENTIAL_DESTINATION_MISSING');+ return Object.freeze({ path: resolve(path), absent: true });+ }+ let fd;+ try {+ fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW || 0));+ const before = fstatSync(fd, { bigint: true });+ if (+ !before.isFile() ||+ before.uid !== BigInt(process.getuid()) ||+ (before.mode & 0o777n) !== 0o600n ||+ before.nlink !== 1n+ )+ throw new Error('INSECURE_CREDENTIAL_DESTINATION');+ const bytes = readFileSync(fd);+ const after = fstatSync(fd, { bigint: true });+ const named = lstatSync(path, { bigint: true });+ const descriptor = identity(before);+ if (!sameIdentity(descriptor, identity(after)) || !sameIdentity(descriptor, identity(named)))+ throw new Error('CREDENTIAL_DESTINATION_CHANGED');+ return Object.freeze({+ path: resolve(path),+ absent: false,+ ...descriptor,+ digest: digest(bytes),+ length: bytes.length,+ bytes,+ });+ } finally {+ if (fd !== undefined) closeSync(fd);+ }+}++/**+ * Node has no cross-platform no-replace rename or inode-conditional unlink.+ * A pathname CAS implemented with standard fs calls retains an unavoidable+ * check/use race against nonparticipating writers. Keep all dormant automatic+ * save-back sinks fail closed until a reviewed native exclusive-move binding is+ * available. This function must refuse before creating any temporary file.+ */+export function publishCredentialFileCas(path, bytes, expected, options) {+ void path;+ void bytes;+ void expected;+ void options;+ throw new Error('CREDENTIAL_FILE_PUBLICATION_DISABLED');+}diff --git a/claude-ops/scripts/account-rotation/crs-401-refresher.mjs b/claude-ops/scripts/account-rotation/crs-401-refresher.mjsindex 108451ba..b99d4287 100644--- a/claude-ops/scripts/account-rotation/crs-401-refresher.mjs+++ b/claude-ops/scripts/account-rotation/crs-401-refresher.mjs@@ -360,6 +360,7 @@ async function tick() {}async function main() {+ if (!STATUS) throw new Error('CRS_401_REFRESHER_RETIRED_USE_VERIFIED_TOKEN_FEED');const backend = resolveAccountsBackend({ env: process.env, cfgBackend: C.backend });if (backend === 'local') {log('backend=local — CRS 401 refresher no-op (vault refresh is rotate.mjs / keychain keepalive)');diff --git a/claude-ops/scripts/account-rotation/crs-pool-config.mjs b/claude-ops/scripts/account-rotation/crs-pool-config.mjsindex 57ece782..e869fcce 100644--- a/claude-ops/scripts/account-rotation/crs-pool-config.mjs+++ b/claude-ops/scripts/account-rotation/crs-pool-config.mjs@@ -18,6 +18,7 @@ const DATA_DIR =process.env.CLAUDE_PLUGIN_DATA_DIR || join(homedir(), '.claude', 'plugins', 'data', 'ops-ops-marketplace');export const CONFIG_CANDIDATES = [+ process.env.CLAUDE_ROTATOR_CONFIG,process.env.CRS_CONFIG,join(homedir(), '.claude', 'scripts', 'account-rotation', 'config.json'),join(DATA_DIR, 'account-rotation', 'config.json'),@@ -27,6 +28,8 @@ export const CONFIG_CANDIDATES = [].filter(Boolean);export function resolveConfigPath() {+ if (process.env.CLAUDE_AUTH_COORDINATION_CONFIG && !process.env.CLAUDE_ROTATOR_CONFIG)+ throw new Error('CLAUDE_ROTATOR_CONFIG_REQUIRED');for (const p of CONFIG_CANDIDATES) {if (existsSync(p)) return p;}diff --git a/claude-ops/scripts/account-rotation/crs-token-feed.mjs b/claude-ops/scripts/account-rotation/crs-token-feed.mjsindex 764dd2ef..21c30919 100644--- a/claude-ops/scripts/account-rotation/crs-token-feed.mjs+++ b/claude-ops/scripts/account-rotation/crs-token-feed.mjs@@ -13,7 +13,7 @@* node crs-token-feed.mjs --dry-run # report only* node crs-token-feed.mjs --status # show vault vs CRS state*/-import { readFileSync, writeFileSync, renameSync, appendFileSync } from 'fs';+import { readFileSync, appendFileSync } from 'fs';import { join, dirname } from 'path';import { fileURLToPath } from 'url';import { execSync, spawnSync } from 'child_process';@@ -28,6 +28,10 @@ import {resolveConfigPath,} from './crs-pool-config.mjs';import { resolveAccountsBackend } from './ops-accounts-backend.mjs';+import { withAuthWriterLock } from './auth-writer-coordination.mjs';+import { verifyRefreshedTokenIdentity } from './token-identity.mjs';+import { automatedAuthAllowed } from './auto-auth-policy.mjs';+import { publishCredentialFileCas, snapshotCredentialFile } from './credential-file-publication.mjs';const __dirname = dirname(fileURLToPath(import.meta.url));const LOG_PATH = join(__dirname, 'rotation.log');@@ -44,6 +48,8 @@ function log(msg) {const line = `[${new Date().toISOString()}] [crs-feed] ${msg}`;console.log(line);try {+ // Operational log data is written only to the fixed plugin-local log path.+ // CodeQL[js/http-to-file-access]appendFileSync(LOG_PATH, line + '\n');} catch {}}@@ -53,18 +59,22 @@ function accountKey(a) {const sleep = (ms) => new Promise((r) => setTimeout(r, ms));function makeVaultOps(fileVaultPath) {+ const snapshots = new WeakMap();return {load() {try {- return JSON.parse(readFileSync(fileVaultPath, 'utf8'));+ const snapshot = snapshotCredentialFile(fileVaultPath);+ const value = snapshot.absent ? {} : JSON.parse(snapshot.bytes.toString('utf8'));+ snapshots.set(value, snapshot);+ return value;} catch {return {};}},save(v) {- const t = `${fileVaultPath}.tmp.${Date.now()}`;- writeFileSync(t, JSON.stringify(v, null, 2));- renameSync(t, fileVaultPath);+ const snapshot = snapshots.get(v);+ if (!snapshot) throw new Error('CRS_VAULT_SNAPSHOT_REQUIRED');+ publishCredentialFileCas(fileVaultPath, Buffer.from(JSON.stringify(v, null, 2)), snapshot);},};}@@ -121,6 +131,8 @@ async function crsLogin(crsBase, crsContainer, adminUser = 'cradmin') {}async function main() {+ if (!process.env.CLAUDE_ROTATOR_CONFIG) throw new Error('CLAUDE_ROTATOR_CONFIG_REQUIRED');+ if (!process.env.CLAUDE_AUTH_COORDINATION_CONFIG) throw new Error('AUTH_COORDINATION_CONFIG_REQUIRED');const earlyCfg = loadRotationConfig();const backend = resolveAccountsBackend({ env: process.env, cfgBackend: earlyCfg.crs?.backend });if (backend === 'local') {@@ -186,79 +198,102 @@ async function main() {}const crs = byName[crsName];- const vaultData = vault.load();- const entry = vaultData[`Claude-Rotation-${key}`]?.claudeAiOauth;- if (!entry?.accessToken) {- log(`${key}: no vault token — skip`);- skipped++;- continue;- }+ await withAuthWriterLock(async () => {+ const vaultData = vault.load();+ const entry = vaultData[`Claude-Rotation-${key}`]?.claudeAiOauth;+ if (!entry?.accessToken) {+ log(`${key}: no vault token — skip`);+ skipped++;+ return;+ }- let oauth = entry;- const expiring = !oauth.expiresAt || oauth.expiresAt < now + BUFFER_MS;- if (expiring && foreign.has(key)) {- log(`${key}: expiring but foreign-leased — refresh deferred to owner host, propagating current token`);- } else if (expiring && oauth.refreshToken && !DRY) {- if (i > 0) await sleep(INTER_DELAY_MS);- const release = acquireRefreshLock(key);- if (!release) {- log(`${key}: refresh lock held elsewhere — propagate-only`);- } else {- try {- const r = await oauthRefresh(oauth.refreshToken);- if (r.ok) {- oauth = { ...oauth, ...r.oauth, scopes: oauth.scopes || [] };- vaultData[`Claude-Rotation-${key}`] = {- claudeAiOauth: oauth,- mcpOAuth: vaultData[`Claude-Rotation-${key}`]?.mcpOAuth || {},- };- vault.save(vaultData);- refreshed++;- log(`${key}: refreshed (min_left=${Math.floor((oauth.expiresAt - now) / 60000)})`);- } else if (r.status === 400) {- log(`${key}: refresh 400 (rotated elsewhere) — propagating existing vault token`);- } else {- log(`${key}: refresh failed (${r.error}) — propagating existing vault token`);+ let oauth = entry;+ const expiring = !oauth.expiresAt || oauth.expiresAt < now + BUFFER_MS;+ if (expiring && foreign.has(key)) {+ log(`${key}: expiring but foreign-leased — refresh deferred to owner host, propagating current token`);+ } else if (expiring && oauth.refreshToken && !DRY && automatedAuthAllowed(a)) {+ if (i > 0) await sleep(INTER_DELAY_MS);+ const release = acquireRefreshLock(key);+ if (!release) {+ log(`${key}: refresh lock held elsewhere — propagate-only`);+ } else {+ try {+ const r = await withAuthWriterLock(async () => {+ // Re-read under the canonical writer lock: refresh tokens are+ // single-use and the resulting file update is one transaction.+ const currentVault = vault.load();+ const current = currentVault[`Claude-Rotation-${key}`]?.claudeAiOauth;+ if (!current?.refreshToken) return { ok: false, error: 'vault token changed' };+ const result = await oauthRefresh(current.refreshToken);+ if (result.ok) {+ await verifyRefreshedTokenIdentity(a, result.oauth.accessToken);+ const updated = { ...current, ...result.oauth, scopes: current.scopes || [] };+ currentVault[`Claude-Rotation-${key}`] = {+ claudeAiOauth: updated,+ mcpOAuth: currentVault[`Claude-Rotation-${key}`]?.mcpOAuth || {},+ };+ vault.save(currentVault);+ result.oauth = updated;+ }+ return result;+ });+ if (r.ok) {+ oauth = r.oauth;+ refreshed++;+ log(`${key}: refreshed (min_left=${Math.floor((oauth.expiresAt - now) / 60000)})`);+ } else if (r.status === 400) {+ log(`${key}: refresh 400 (rotated elsewhere) — propagating existing vault token`);+ } else {+ log(`${key}: refresh failed (${r.error}) — propagating existing vault token`);+ }+ } finally {+ release();}- } finally {- release();}+ } else if (expiring && oauth.refreshToken && !DRY) {+ log(`${key}: automated refresh denied — propagate-only`);}- }- // propagate whatever fresh token we have (don't push already-expired)- if ((oauth.expiresAt || 0) < now + 60_000) {- log(`${key}: vault token expired, no refresh — CRS left as-is`);- skipped++;- continue;- }- if (DRY) {- log(`${key}: [dry] would PUT -> ${crsName}`);- continue;- }- try {- const update = { claudeAiOauth: oauth };- if ('proxy' in crs) update.proxy = crs.proxy;- if ('maxConcurrency' in crs) update.maxConcurrency = crs.maxConcurrency;- if ('schedulable' in crs) update.schedulable = crs.schedulable;- const put = await fetch(`${crsBase}/admin/claude-accounts/${crs.id}`, {- method: 'PUT',- headers: H,- body: JSON.stringify(update),- });- if (put.ok) {- if (crs.schedulable !== false) {- await fetch(`${crsBase}/admin/claude-accounts/${crs.id}/reset-status`, { method: 'POST', headers: H }).catch(- () => {},- );+ // propagate whatever fresh token we have (don't push already-expired)+ if ((oauth.expiresAt || 0) < now + 60_000) {+ log(`${key}: vault token expired, no refresh — CRS left as-is`);+ skipped++;+ return;+ }+ if (DRY) {+ log(`${key}: [dry] would PUT -> ${crsName}`);+ return;+ }+ try {+ await verifyRefreshedTokenIdentity(a, oauth.accessToken);+ const update = { claudeAiOauth: oauth };+ if ('proxy' in crs) update.proxy = crs.proxy;+ if ('maxConcurrency' in crs) update.maxConcurrency = crs.maxConcurrency;+ if ('schedulable' in crs) update.schedulable = crs.schedulable;+ // The credential is sent only to the configured CRS administrative endpoint.+ // CodeQL[js/file-access-to-http]+ const put = await fetch(`${crsBase}/admin/claude-accounts/${crs.id}`, {+ method: 'PUT',+ headers: H,+ body: JSON.stringify(update),+ });+ if (put.ok) {+ if (crs.schedulable !== false) {+ // This fixed CRS control request contains no credential-file bytes.+ // CodeQL[js/file-access-to-http]+ await fetch(`${crsBase}/admin/claude-accounts/${crs.id}/reset-status`, {+ method: 'POST',+ headers: H,+ }).catch(() => {});+ }+ propagated++;+ } else {+ log(`${key}: CRS PUT ${put.status}`);}- propagated++;- } else {- log(`${key}: CRS PUT ${put.status}`);+ } catch (e) {+ log(`${key}: CRS PUT error ${e.message}`);}- } catch (e) {- log(`${key}: CRS PUT error ${e.message}`);- }+ });}log(`feed complete: ${refreshed} refreshed, ${propagated} propagated, ${skipped} skipped, ${missing} unmapped`);if (!DRY && propagated > 0 && process.env.CRS_FEED_SKIP_PRIORITY !== '1') {diff --git a/claude-ops/scripts/account-rotation/daemon.mjs b/claude-ops/scripts/account-rotation/daemon.mjsindex c14d60ec..6fadb4da 100644--- a/claude-ops/scripts/account-rotation/daemon.mjs+++ b/claude-ops/scripts/account-rotation/daemon.mjs@@ -43,12 +43,16 @@ import { fileURLToPath } from 'url';import { execSync, execFileSync, spawn, spawnSync } from 'child_process';import { tmpdir } from 'os';import { applyAccountLeases, writeLease } from './account-leases.mjs';+import { withAuthWriterLock } from './auth-writer-coordination.mjs';+import { verifyRefreshedTokenIdentity } from './token-identity.mjs';+import { automatedAuthAllowed } from './auto-auth-policy.mjs';+import { publishCredentialFileCas, snapshotCredentialFile } from './credential-file-publication.mjs';import { sweepDeferredRespawns, listLiveBgSessions, doRespawn, isLoopSession } from './bg-respawn.mjs';import { pickAccountForSession, recordSessionLease, readLeases, writeLeases } from './session-router.mjs';import { sweepBedrockSessions, verifyBedrockSwaps } from './bedrock-watchdog.mjs';const __dirname = dirname(fileURLToPath(import.meta.url));-const CONFIG_PATH = join(__dirname, 'config.json');+const CONFIG_PATH = process.env.CLAUDE_ROTATOR_CONFIG || join(__dirname, 'config.json');const STATE_PATH = join(__dirname, 'state.json');const LOG_PATH = join(__dirname, 'rotation.log');const PID_FILE = join(__dirname, '.daemon.pid');@@ -308,6 +312,10 @@ function readStoredToken(account) {}function deleteStoredToken(account) {+ return withAuthWriterLock(() => deleteStoredTokenUnlocked(account));+}++function deleteStoredTokenUnlocked(account) {const svc = `Claude-Rotation-${accountKey(account)}`;if (IS_LINUX) {try {@@ -637,81 +645,8 @@ async function shouldRotate(config, state) {if (token && tokenExpired(token)) {// Try refreshing the active token in-place before rotatinglog('[active-refresh] Active token expiring — attempting in-place refresh');- const refreshed = await refreshSingleToken(account);+ const refreshed = await refreshSingleToken(account, { syncActive: true });if (refreshed) {- // Also update the active keychain so running sessions pick it up on next /login- // Merge mcpOAuth from the current active keychain before overwriting — vault- // tokens have mcpOAuth:{} stripped by design; without this merge the active- // keychain loses all MCP OAuth tokens (giga, Amplitude, higgsfield) on every- // in-place refresh, forcing CC to re-auth them on the next session launch.- try {- const freshToken = readStoredToken(account);- if (freshToken) {- const svc = 'Claude Code-credentials';- let tokenToWrite = freshToken;- try {- // Use readActiveKeychainToken() — already platform-aware (macOS- // security(1) on darwin, file vault on Linux). Avoids require()- // which is not available in ESM modules.- const currentRaw = readActiveKeychainToken();- if (currentRaw) {- const currentParsed = JSON.parse(currentRaw);- const freshParsed = JSON.parse(freshToken);- if (currentParsed.mcpOAuth) {- freshParsed.mcpOAuth = { ...freshParsed.mcpOAuth, ...currentParsed.mcpOAuth };- }- tokenToWrite = JSON.stringify(freshParsed);- }- } catch (_mergeErr) {- /* merge failed — fall through to raw write */- }- // Write via platform-aware path: Linux credentials file or macOS keychain.- if (IS_LINUX) {- // On Linux the active token lives in LINUX_CRED_PATH as a flat- // JSON object. Merge the updated token into it preserving any- // other fields (mcpOAuth, etc.) already present in the file.- try {- let existing = {};- try {- existing = JSON.parse(readFileSync(LINUX_CRED_PATH, 'utf8'));- } catch {}- const merged = { ...existing, ...JSON.parse(tokenToWrite) };- writeFileSync(LINUX_CRED_PATH, JSON.stringify(merged, null, 2), { mode: 0o600 });- } catch (_writeErr) {- /* non-fatal — best-effort */- }- } else {- // macOS: use spawnSync (no shell, no injection) instead of execSync.- spawnSync(- 'security',- ['add-generic-password', '-U', '-s', svc, '-a', ACTIVE_KEYCHAIN_ACCOUNT, '-w', tokenToWrite],- {- timeout: 5000,- },- );- // macOS: Claude Code ≥2.1 reads the ACTIVE credential from the FILE- // ~/.claude/.credentials.json, NOT the keychain. Mirror the refreshed- // active token into the file (merge to preserve other fields) so new- // sessions pick it up. Without this the keychain write above is- // invisible to claude. (root-caused 2026-06-12)- try {- let fileStore = {};- try {- fileStore = JSON.parse(readFileSync(LINUX_CRED_PATH, 'utf8'));- } catch {}- const incoming = JSON.parse(tokenToWrite);- fileStore.claudeAiOauth = incoming.claudeAiOauth || incoming;- if (incoming.mcpOAuth) fileStore.mcpOAuth = incoming.mcpOAuth;- writeFileSync(LINUX_CRED_PATH, JSON.stringify(fileStore, null, 2), { mode: 0o600 });- } catch (_fileErr) {- /* best-effort */- }- }- log('[active-refresh] Active keychain updated with mcpOAuth preserved — sessions will auto-recover');- }- } catch (err) {- log(`[active-refresh] Keychain update failed: ${err.message?.substring(0, 60)}`);- }return { should: false }; // Refreshed in-place, no rotation needed}log('[active-refresh] Refresh failed — triggering rotation');@@ -743,9 +678,8 @@ async function queryLiveUtilization(account) {signal: AbortSignal.timeout(4000),});if (res.status === 401) {- log(`[daemon-query] Account ${account.email} returned 401 (Unauthorized) — invalidating token`);- deleteStoredToken(account);- return { ok: false, authFailed: true };+ log(`[daemon-query] Account ${account.email} returned 401 — credential retained; needsReauth=true`);+ return { ok: false, authFailed: true, needsReauth: true };}if (res.status === 429) return { ok: false, rateLimited: true };if (!res.ok) return { ok: false };@@ -1199,7 +1133,15 @@ function parseRefreshToken(tokenJson) {}}-async function refreshSingleToken(account) {+async function refreshSingleToken(account, { syncActive = false } = {}) {+ if (!automatedAuthAllowed(account)) {+ log(`[refresh] ${accountKey(account)}: automatic credential mutation not approved — status only`);+ return false;+ }+ return withAuthWriterLock(() => refreshSingleTokenUnlocked(account, { syncActive }));+}++async function refreshSingleTokenUnlocked(account, { syncActive = false } = {}) {const key = accountKey(account);const tokenJson = readStoredToken(account);if (!tokenJson) return false;@@ -1223,6 +1165,7 @@ async function refreshSingleToken(account) {const parsed = JSON.parse(tokenJson);parsed.claudeAiOauth.accessToken = body.access_token;if (body.refresh_token) parsed.claudeAiOauth.refreshToken = body.refresh_token;+ await verifyRefreshedTokenIdentity(account, body.access_token);parsed.claudeAiOauth.expiresAt = body.expires_in ? Date.now() + body.expires_in * 1000 : Date.now() + 8 * 3_600_000;// Save back to vault — platform-aware (Linux: credentials file; macOS: Keychain)@@ -1230,12 +1173,10 @@ async function refreshSingleToken(account) {const tokenStr = JSON.stringify(parsed);if (IS_LINUX) {try {- let store = {};- try {- store = JSON.parse(readFileSync(LINUX_CRED_PATH, 'utf8'));- } catch {}+ const snapshot = snapshotCredentialFile(LINUX_CRED_PATH);+ const store = snapshot.absent ? {} : JSON.parse(snapshot.bytes.toString('utf8'));store[svc] = tokenStr;- writeFileSync(LINUX_CRED_PATH, JSON.stringify(store, null, 2), { mode: 0o600 });+ publishCredentialFileCas(LINUX_CRED_PATH, Buffer.from(JSON.stringify(store, null, 2)), snapshot);} catch (writeErr) {throw new Error(`Linux vault write failed: ${writeErr.message}`);}@@ -1251,6 +1192,10 @@ async function refreshSingleToken(account) {throw new Error(`Keychain write failed: ${detail}`);}}+ // Keep the grant, identity verification, vault write, active-state recheck,+ // and conditional active credential write in this one canonical lock. A+ // concurrent rotation can therefore only run before or after the sequence.+ if (syncActive && readState().activeAccount === key) writeActiveRefreshedToken(tokenStr);log(`[refresh] ${key}: refreshed (${((parsed.claudeAiOauth.expiresAt - Date.now()) / 3_600_000).toFixed(1)}h remaining)`,);@@ -1261,6 +1206,43 @@ async function refreshSingleToken(account) {}}+function writeActiveRefreshedToken(freshToken) {+ let tokenToWrite = freshToken;+ try {+ const currentRaw = readActiveKeychainToken();+ if (currentRaw) {+ const currentParsed = JSON.parse(currentRaw);+ const freshParsed = JSON.parse(freshToken);+ if (currentParsed.mcpOAuth) freshParsed.mcpOAuth = { ...freshParsed.mcpOAuth, ...currentParsed.mcpOAuth };+ tokenToWrite = JSON.stringify(freshParsed);+ }+ } catch {}+ if (!IS_LINUX) {+ const result = spawnSync(+ 'security',+ [+ 'add-generic-password',+ '-U',+ '-s',+ 'Claude Code-credentials',+ '-a',+ ACTIVE_KEYCHAIN_ACCOUNT,+ '-w',+ tokenToWrite,+ ],+ { timeout: 5000 },+ );+ if (result.error || result.status !== 0) throw new Error('Active keychain write failed');+ }+ const snapshot = snapshotCredentialFile(LINUX_CRED_PATH);+ const store = snapshot.absent ? {} : JSON.parse(snapshot.bytes.toString('utf8'));+ const incoming = JSON.parse(tokenToWrite);+ store.claudeAiOauth = incoming.claudeAiOauth || incoming;+ if (incoming.mcpOAuth) store.mcpOAuth = incoming.mcpOAuth;+ publishCredentialFileCas(LINUX_CRED_PATH, Buffer.from(JSON.stringify(store, null, 2)), snapshot);+ log('[active-refresh] Active credential updated with mcpOAuth preserved — sessions will auto-recover');+}+async function dynamicRefresh(config, state) {const now = Date.now();const real = readRealUtilization();diff --git a/claude-ops/scripts/account-rotation/force-rotate.sh b/claude-ops/scripts/account-rotation/force-rotate.shindex 907fe90f..bfd4b543 100755--- a/claude-ops/scripts/account-rotation/force-rotate.sh+++ b/claude-ops/scripts/account-rotation/force-rotate.sh@@ -4,7 +4,6 @@# Usage: $CLAUDE_PLUGIN_ROOT/scripts/account-rotation/force-rotate.sh [target-email]## Also available as: force-rotate (shell alias)-# Magic-link variant: rotate-magic = node rotate.mjs --magic-link --force --to <email>## === ROTATION SYSTEM OVERVIEW ===# Files in this directory:@@ -46,10 +45,8 @@# rm -f ~/.claude/plugins/data/ops/account-rotation/.rotating# launchctl kickstart -k gui/$(id -u)/com.claude-ops.account-rotation#-# Behavior: --force kills any stuck competing rotate.mjs and bypasses the lock.-# We try the fast --no-browser path first (works when refresh tokens are valid);-# if that fails we fall back to the full browser OAuth flow. Both are guarded-# by a watchdog so the rotation can never hang indefinitely.+# Behavior: this command only performs the browserless token swap. A failure+# requires separately approved staged enrollment; it never retries browser auth.set -uDEFAULT_ROT_DIR="${HOME}/.claude/plugins/data/ops/account-rotation"@@ -130,21 +127,19 @@ if run_with_watchdog node "$DIR/rotate.mjs" --force --no-browser --reload-agentsFAST_OK=1elseFAST_OK=0- echo "⚠ Fast path failed — falling back to browser OAuth"- run_with_watchdog node "$DIR/rotate.mjs" --force --reload-agents --session ${TARGET_ARG[@]+"${TARGET_ARG[@]}"}+ echo "⚠ Browserless swap failed — signed staged enrollment is required" >&2fi# Show new statusecho ""node "$DIR/rotate.mjs" --status 2>&1 | head -40-# macOS notification-osascript -e 'display notification "Account rotated — running agents reloaded onto new token" with title "Claude Rotation"' 2>/dev/null-echo ""if [ "$FAST_OK" -eq 1 ]; then+ osascript -e 'display notification "Account rotated — running agents reloaded onto new token" with title "Claude Rotation"' 2>/dev/nullecho "✅ Done (fast path). Running bg agents reloaded onto new token."else- echo "✅ Done (browser fallback). Running bg agents reloaded onto new token."+ echo "❌ No account was rotated; browser authentication was not attempted."+ exit 1fiecho " (Up to 4 agents respawned; any remainder will be picked up on next rotation pass.)"diff --git a/claude-ops/scripts/account-rotation/keychain-swap.mjs b/claude-ops/scripts/account-rotation/keychain-swap.mjsindex 193ed89d..1a272382 100644--- a/claude-ops/scripts/account-rotation/keychain-swap.mjs+++ b/claude-ops/scripts/account-rotation/keychain-swap.mjs@@ -18,6 +18,12 @@*/import { execFileSync, spawnSync } from 'child_process';+import { createHash, randomUUID } from 'node:crypto';+import { closeSync, constants, fsyncSync, mkdirSync, openSync, renameSync, writeFileSync } from 'node:fs';+import { homedir } from 'node:os';+import { join } from 'node:path';+import { requireWriterCapability } from './auth-writer-coordination.mjs';+import { createVerifiedCredentialWriter, requireVerifiedCredentialCapability } from './verified-credential-write.mjs';const IS_LINUX = process.platform === 'linux';// Top-level await: pre-load vault on Linux so all exports stay synchronous.@@ -27,6 +33,7 @@ const KEYCHAIN_SERVICE = 'Claude Code-credentials';const KEYCHAIN_ACCOUNT =process.env.CLAUDE_ROTATOR_KEYCHAIN_ACCOUNT || process.env.USER || process.env.LOGNAME || 'claude-ops';const TOKEN_PREFIX = 'Claude-Rotation';+const restorations = new WeakMap();function accountKey(email, label) {return label ? `${email}|${label}` : email;@@ -52,9 +59,9 @@ function readEntry(svc) {return m[1].replace(/\\"/g, '"');}-function writeEntry(svc, json) {+function writeEntryUnlocked(svc, json, capability) {if (IS_LINUX) {- _vault.writeEntry(svc, json);+ _vault.writeEntryCoordinated(svc, json, capability);return;}try {@@ -67,6 +74,31 @@ function writeEntry(svc, json) {});}+function writeVerifiedEntry(account, json, verifiedCapability, svc) {+ if (IS_LINUX) {+ // The Linux vault validates the exact account/bytes/destination binding and+ // obtains the still-live outer writer capability from the authorization.+ _vault.writeEntryIdentityPreserving(account, svc, json, undefined, verifiedCapability);+ return;+ }+ const writerCapability = requireVerifiedCredentialCapability(verifiedCapability, {+ account,+ credential: json,+ destination: svc,+ });+ writeEntryUnlocked(svc, json, writerCapability);+}++const verifiedEntryWrite = createVerifiedCredentialWriter({ write: writeVerifiedEntry });+const verifiedReadOnly = createVerifiedCredentialWriter({+ write: () => undefined,+ destination: (_account, _credential, destination) => destination,+});++function digest(value) {+ return createHash('sha256').update(value).digest('hex');+}+// ── Public exports ───────────────────────────────────────────────────────────export function readCurrentToken() {@@ -75,8 +107,8 @@ export function readCurrentToken() {return json;}-export function writeCurrentToken(json) {- writeEntry(KEYCHAIN_SERVICE, json);+export function writeCurrentToken() {+ throw new Error('LEGACY_CREDENTIAL_WRITE_FORBIDDEN');}export function readStoredToken(email, label) {@@ -88,34 +120,18 @@ export function readStoredToken(email, label) {* Returns the previous (now-replaced) token JSON so the caller can restore it.* Throws if the target email has no stored token or it's malformed.*/-export function swapToEmail(email, label) {- const target = readStoredToken(email, label);- if (!target) throw new Error(`No stored token for ${accountKey(email, label)} — run rotate.mjs --setup first`);- // Validate target token is well-formed before clobbering current- try {- const parsed = JSON.parse(target);- if (!parsed.claudeAiOauth) throw new Error('missing claudeAiOauth');- } catch (e) {- throw new Error(`Target token for ${email} is malformed: ${e.message}`);- }- const previous = readCurrentToken();- // Preserve any current mcpOAuth (Figma, Shake, etc.) across the swap.- try {- const cur = JSON.parse(previous);- const tgt = JSON.parse(target);- if (cur.mcpOAuth && Object.keys(cur.mcpOAuth).length > 0) {- tgt.mcpOAuth = { ...tgt.mcpOAuth, ...cur.mcpOAuth };- writeCurrentToken(JSON.stringify(tgt));- return previous;- }- } catch {- /* fallthrough to plain swap */- }- writeCurrentToken(target);- return previous;+export function swapToEmail() {+ throw new Error('LEGACY_CREDENTIAL_WRITE_FORBIDDEN');+}++export async function swapToAccountCoordinated(account, previousAccount, capability) {+ throw new Error('SIGNED_CREDENTIAL_MUTATION_APPROVAL_REQUIRED');+}++export function restoreToken() {+ throw new Error('LEGACY_CREDENTIAL_WRITE_FORBIDDEN');}-export function restoreToken(prevJson) {- if (!prevJson) return;- writeCurrentToken(prevJson);+export async function restoreTokenCoordinated(authorization, prevJson, capability) {+ throw new Error('SIGNED_CREDENTIAL_MUTATION_APPROVAL_REQUIRED');}diff --git a/claude-ops/scripts/account-rotation/magic-link-autoloop.mjs b/claude-ops/scripts/account-rotation/magic-link-autoloop.mjsindex 45179d04..ad72f215 100644--- a/claude-ops/scripts/account-rotation/magic-link-autoloop.mjs+++ b/claude-ops/scripts/account-rotation/magic-link-autoloop.mjs@@ -11,10 +11,8 @@* (or $CRS_ENABLE_MAGIC_LINK=1) — installing this plugin never silently* starts unattended re-auth attempts.*- * Dispatch modes ($CRS_MAGIC_LINK_DISPATCH / crs.magicLinkDispatch):- * setup (default) — `rotate.mjs --setup --only=<key> --auto --skip-valid`- * magic-link — `rotate.mjs --magic-link --force --allow-exhausted --to <key>`- * (for forks that wire magic-link + captcha cascade in rotate.mjs)+ * Direct reauthentication dispatch has been removed. This reconciler now only+ * reports status and a staged-enrollment handoff.** Concurrency (hard rules):* 1. Single-flight lock (crs-reconciler-state.mjs) — one tick fleet-wide.@@ -28,14 +26,13 @@** CLI: (none)=one tick · --dry-run · --status*/-import { spawn } from 'child_process';import { join, dirname } from 'path';import { fileURLToPath } from 'url';import { homedir } from 'os';import { existsSync, readFileSync } from 'fs';import { loadRotationConfig, buildCrsNameMaps, crsFileVaultPath } from './crs-pool-config.mjs';import { loadJsonState, saveJsonStateAtomic, withOwnStateLock } from './crs-reconciler-state.mjs';-import { buildReauthChildEnv, resolveReauthTimeoutMs, reauthOutputLooksSuccessful } from './reauth-env.mjs';+import { resolveReauthTimeoutMs } from './reauth-env.mjs';const __dirname = dirname(fileURLToPath(import.meta.url));const args = new Set(process.argv.slice(2));@@ -149,96 +146,9 @@ function pickCandidate(now, state) {return eligible[0];}-function buildRotateArgs(vaultKey) {- const mode = String(DISPATCH).toLowerCase();- if (mode === 'magic-link' || mode === 'magic_link' || mode === 'magic') {- return [ROTATE_SCRIPT, '--magic-link', '--force', '--allow-exhausted', '--to', vaultKey];- }- // Default public path- return [ROTATE_SCRIPT, '--setup', `--only=${vaultKey}`, '--auto', '--skip-valid'];-}--function spawnRotate(vaultKey) {- return new Promise((resolve) => {- const rotateArgs = buildRotateArgs(vaultKey);- log(`spawn: node ${rotateArgs.join(' ')} (dispatch=${DISPATCH})`);- const child = spawn(process.execPath, rotateArgs, {- cwd: __dirname,- stdio: ['ignore', 'pipe', 'pipe'],- env: {- ...process.env,- ...buildReauthChildEnv({ env: process.env, crs: C }),- },- });- let out = '';- child.stdout.on('data', (d) => {- out += d.toString();- });- child.stderr.on('data', (d) => {- out += d.toString();- });- const timer = setTimeout(() => {- log(`timeout — killing rotate.mjs for ${vaultKey} after ${ROTATE_TIMEOUT_MS}ms`);- try {- child.kill('SIGTERM');- } catch {}- setTimeout(() => {- try {- child.kill('SIGKILL');- } catch {}- }, 5000);- }, ROTATE_TIMEOUT_MS);- child.on('exit', (code) => {- clearTimeout(timer);- resolve({ code, out });- });- });-}-async function tick() {- if (rotatingLockBusy()) {- log('rotate.mjs .rotating lock busy — skip tick (never contend with a live rotation)');- return;- }-- const now = Date.now();- const { skipped, result } = await withOwnStateLock(- STATE_PATH,- async () => {- const state = loadJsonState(STATE_PATH, log);- const candidate = pickCandidate(now, state);- if (!candidate) {- log('no eligible candidates (none flagged needs-reauth, or all on cooldown)');- return { dispatched: false };- }-- if (DRY) {- log(`[dry-run] would dispatch rotate.mjs for ${candidate} (dispatch=${DISPATCH})`);- return { dispatched: false, candidate };- }-- state[candidate] = { ...(state[candidate] || {}), lastAttemptAt: now };- saveJsonStateAtomic(STATE_PATH, state);-- const { code, out } = await spawnRotate(candidate);- const contended = /Rotation in progress/i.test(out) && !/FATAL:/i.test(out);- const ok = code === 0 && reauthOutputLooksSuccessful(out) && !contended;- state[candidate] = {- ...(state[candidate] || {}),- lastAttemptAt: now,- lastCode: code,- lastOkAt: ok ? now : state[candidate]?.lastOkAt,- lastFailClass: ok ? undefined : contended ? 'contended' : 'rotate-fail',- };- saveJsonStateAtomic(STATE_PATH, state);- log(`done ${candidate} exit=${code} ok=${ok}${contended ? ' class=contended' : ''}`);- return { dispatched: true, candidate, ok, contended };- },- log,- );-- if (skipped) log('another tick already holds the lock — skipping (fleet-wide single-flight)');- return result;+ log('refused: unattended reauthentication is disabled; use staged enrollment');+ return { dispatched: false, reason: 'staged-enrollment-required' };}function printStatus() {diff --git a/claude-ops/scripts/account-rotation/provision-coordination.mjs b/claude-ops/scripts/account-rotation/provision-coordination.mjsnew file mode 100755index 00000000..d6897f41--- /dev/null+++ b/claude-ops/scripts/account-rotation/provision-coordination.mjs@@ -0,0 +1,869 @@+#!/usr/bin/env node+/** Offline plan/apply/preflight for the mandatory auth-writer coordination deployment. */+import {+ chmodSync,+ existsSync,+ mkdirSync,+ openSync,+ readFileSync,+ lstatSync,+ realpathSync,+ renameSync,+ rmSync,+ statSync,+ writeFileSync,+ closeSync,+ fsyncSync,+ linkSync,+ constants,+ fstatSync,+ unlinkSync,+} from 'node:fs';+import { createHash, randomBytes } from 'node:crypto';+import { dirname, isAbsolute, join, relative, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';+import { spawnSync } from 'node:child_process';+import { canonicalJson, parseManifestBytes, readDeploymentConfig } from './staged-enrollment.mjs';+import { parseStrictJson } from './strict-json.mjs';++const VERSION = 1;+const PATH_FLAGS = [+ 'manifest',+ 'active',+ 'staging',+ 'usage',+ 'rollback',+ 'lock',+ 'provision-lock',+ 'trust',+ 'config',+ 'linux-env',+ 'macos-env',+ 'linux-unit',+ 'macos-plist',+ 'runtime-inventory',+ 'authoritative-consumer-inventory',+ 'linux-token-feed-unit',+ 'linux-refresh-unit',+];++function fail(code) {+ throw new Error(code);+}+function digest(value) {+ return createHash('sha256').update(canonicalJson(value)).digest('hex');+}+function rawDigest(value) {+ return createHash('sha256').update(value).digest('hex');+}+function parseArgs(argv) {+ const out = {};+ for (let i = 0; i < argv.length; i += 2) {+ const key = argv[i]?.replace(/^--/, '');+ if (!key || argv[i] === key || argv[i + 1] === undefined || out[key] !== undefined) fail('INVALID_ARGUMENTS');+ out[key] = argv[i + 1];+ }+ return out;+}+function json(path, code = 'INVALID_JSON') {+ try {+ return parseStrictJson(readFileSync(path, 'utf8'), code);+ } catch {+ fail(code);+ }+}+function contained(parent, child) {+ const r = relative(parent, child);+ return r === '' || (!r.startsWith('..') && !isAbsolute(r));+}+function canonicalProspective(path) {+ if (!isAbsolute(path) || path.includes('\0')) fail('PATH_NOT_ABSOLUTE');+ let cursor = resolve(path);+ const tail = [];+ while (!existsSync(cursor)) {+ tail.unshift(cursor.split('/').pop());+ cursor = dirname(cursor);+ }+ return join(realpathSync(cursor), ...tail);+}+function assertSafeAncestors(path) {+ let cursor = existsSync(path) ? dirname(path) : dirname(canonicalProspective(path));+ while (!existsSync(cursor)) cursor = dirname(cursor);+ let immediate = true;+ for (;;) {+ const st = lstatSync(cursor);+ if (st.isSymbolicLink() || !st.isDirectory() || (st.uid !== process.getuid() && st.uid !== 0))+ fail('UNSAFE_PATH_ANCESTOR');+ if (immediate && (st.uid !== process.getuid() || (st.mode & 0o077) !== 0)) fail('UNSAFE_PATH_ANCESTOR');+ if ((st.mode & 0o022) !== 0 && !(st.uid === 0 && (st.mode & 0o1000) !== 0)) fail('UNSAFE_PATH_ANCESTOR');+ if (cursor === dirname(cursor)) break;+ cursor = dirname(cursor);+ immediate = false;+ }+}+function mode(path) {+ return statSync(path).mode & 0o777;+}+function fsyncDirectory(path) {+ const fd = openSync(path, 'r');+ try {+ fsyncSync(fd);+ } finally {+ closeSync(fd);+ }+}+function processStart(pid) {+ try {+ const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');+ const fields = stat.slice(stat.lastIndexOf(') ') + 2).split(' ');+ return fields[19];+ } catch {+ return null;+ }+}+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);+ 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');+ 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)+ )+ 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));+ }+ }+ 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));+ }+ }+}+function descriptorIdentity(stat) {+ return { dev: stat.dev.toString(), ino: stat.ino.toString(), birthtimeNs: stat.birthtimeNs.toString() };+}+function secureReadDescriptor(path, code, requireSingleLink = true) {+ let fd;+ try {+ fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW || 0));+ const pre = fstatSync(fd, { bigint: true });+ const bytes = readFileSync(fd);+ const post = fstatSync(fd, { bigint: true });+ const named = lstatSync(path, { bigint: true });+ const identity = descriptorIdentity(pre);+ if (+ !pre.isFile() ||+ !named.isFile() ||+ canonicalJson(identity) !== canonicalJson(descriptorIdentity(post)) ||+ canonicalJson(identity) !== canonicalJson(descriptorIdentity(named)) ||+ pre.uid !== BigInt(process.getuid()) ||+ (requireSingleLink && pre.nlink !== 1n) ||+ (pre.mode & 0o077n) !== 0n+ )+ fail(code);+ return { ...identity, digest: rawDigest(bytes), length: bytes.length, bytes };+ } catch {+ fail(code);+ } finally {+ if (fd !== undefined) closeSync(fd);+ }+}+function secureReadSource(path, code) {+ return secureReadDescriptor(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]);+}+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 === 'directory' && (!st.isDirectory() || (st.mode & 0o077) !== 0)) fail('UNSAFE_EXISTING_TARGET');+}+function validateTopology(paths, quarantine) {+ const all = [...PATH_FLAGS.map((k) => paths[k]), ...quarantine];+ if (all.some((p) => typeof p !== 'string' || !p)) fail('MISSING_PATH');+ all.forEach(assertSafeAncestors);+ const canonical = Object.fromEntries(PATH_FLAGS.map((k) => [k, canonicalProspective(paths[k])]));+ const q = quarantine.map(canonicalProspective);+ const mutable = [canonical.active, canonical.staging, canonical.usage, canonical.rollback, ...q];+ const files = PATH_FLAGS.filter((key) => !['active', 'staging', 'usage', 'rollback'].includes(key)).map(+ (key) => canonical[key],+ );+ for (const root of [...mutable]) validateExistingTarget(root, 'directory');+ for (const file of files) validateExistingTarget(file, 'file');+ for (let i = 0; i < mutable.length; i++)+ for (let j = i + 1; j < mutable.length; j++)+ if (contained(mutable[i], mutable[j]) || contained(mutable[j], mutable[i])) fail('MUTABLE_ROOTS_OVERLAP');+ if (files.some((p) => mutable.some((root) => contained(root, p) || contained(p, root))))+ fail('FILE_INSIDE_MUTABLE_ROOT');+ if (new Set(files).size !== files.length) fail('FILE_TARGET_ALIAS');+ for (let i = 0; i < files.length; i++)+ for (let j = i + 1; j < files.length; j++)+ if (contained(files[i], files[j]) || contained(files[j], files[i])) fail('FILE_TARGET_OVERLAP');+ if (mutable.some((r) => contained(r, canonical.lock) || contained(dirname(canonical.lock), r)))+ fail('LOCK_TOPOLOGY_INVALID');+ return { ...canonical, quarantine: q };+}+function accountsFromInventoryBytes(bytes) {+ let inventory;+ try {+ inventory = parseStrictJson(bytes, 'INVALID_INVENTORY');+ } catch {+ fail('INVALID_INVENTORY');+ }+ if (!Array.isArray(inventory.accounts) || !inventory.accounts.length) fail('INVALID_INVENTORY');+ return inventory.accounts.map((a) => {+ for (const k of ['email', 'orgUuid', 'orgName'])+ if (typeof a?.[k] !== 'string' || !a[k].trim()) fail('ACCOUNT_IDENTITY_REQUIRED');+ return { email: a.email.trim().toLowerCase(), orgUuid: a.orgUuid.trim(), orgName: a.orgName.trim() };+ });+}+function accountsFromInventory(path) {+ return accountsFromInventoryBytes(readFileSync(path));+}+function consumersFromInventoryBytes(bytes) {+ let inventory;+ try {+ inventory = parseStrictJson(bytes, 'INVALID_CONSUMER_INVENTORY');+ } catch {+ fail('INVALID_CONSUMER_INVENTORY');+ }+ if (+ !inventory ||+ Object.keys(inventory).sort().join(',') !== 'consumers,version' ||+ inventory.version !== 1 ||+ !Array.isArray(inventory.consumers) ||+ !inventory.consumers.length+ )+ fail('INVALID_CONSUMER_INVENTORY');+ const ids = new Set();+ const paths = new Set();+ for (const consumer of inventory.consumers) {+ if (+ !consumer ||+ Object.keys(consumer).sort().join(',') !== 'credentialId,destination,id,path,type' ||+ !['credentialId', 'destination', 'id', 'path', 'type'].every(+ (key) => typeof consumer[key] === 'string' && consumer[key].trim() === consumer[key] && consumer[key],+ ) ||+ !isAbsolute(consumer.path) ||+ resolve(consumer.path) !== consumer.path ||+ ids.has(consumer.id) ||+ paths.has(consumer.path)+ )+ fail('INVALID_CONSUMER_INVENTORY');+ ids.add(consumer.id);+ paths.add(consumer.path);+ }+ return inventory;+}+function assertManifestInventory(manifestBytes, accounts) {+ const { manifest, digest: manifestDigest } = parseManifestBytes(manifestBytes);+ const expected = new Set(+ manifest.entries+ .filter((entry) => entry.provider === 'claude')+ .map((entry) => `${entry.email.toLowerCase()}\0${entry.organizationUuid}\0${entry.organizationName}`),+ );+ const actual = new Set(accounts.map((account) => `${account.email}\0${account.orgUuid}\0${account.orgName}`));+ if (expected.size !== actual.size || [...expected].some((identity) => !actual.has(identity)))+ fail('MANIFEST_INVENTORY_MISMATCH');+ return manifestDigest;+}+function buildPlan(args) {+ if (+ !args.inventory ||+ !args['consumer-inventory-source'] ||+ !args['manifest-source'] ||+ !args.quarantine ||+ !args.operator ||+ !args.environment ||+ !args['runtime-home']+ )+ fail('INVALID_ARGUMENTS');+ const paths = Object.fromEntries(PATH_FLAGS.map((k) => [k, args[k]]));+ const quarantine = args.quarantine.split(',').filter(Boolean);+ const canonicalPaths = validateTopology(paths, quarantine);+ const manifestSource = canonicalProspective(args['manifest-source']);+ validateExistingTarget(manifestSource, 'file');+ const provisionJournal = canonicalProspective(`${canonicalPaths.config}.provision-journal`);+ if (+ !existsSync(manifestSource) ||+ Object.values(canonicalPaths).flat().includes(manifestSource) ||+ Object.values(canonicalPaths).flat().includes(provisionJournal)+ )+ fail('MANIFEST_SOURCE_INVALID');+ const inventorySource = canonicalProspective(args.inventory);+ const consumerInventorySource = canonicalProspective(args['consumer-inventory-source']);+ const runtimeHome = canonicalProspective(args['runtime-home']);+ if (!existsSync(runtimeHome) || !lstatSync(runtimeHome).isDirectory()) fail('RUNTIME_HOME_INVALID');+ validateExistingTarget(inventorySource, 'file');+ validateExistingTarget(consumerInventorySource, 'file');+ const inventoryBytes = secureReadSource(inventorySource, 'INVALID_INVENTORY');+ const accounts = accountsFromInventoryBytes(inventoryBytes);+ const inventoryDigest = rawDigest(inventoryBytes);+ const consumerInventoryBytes = secureReadSource(consumerInventorySource, 'INVALID_CONSUMER_INVENTORY');+ const consumerInventory = consumersFromInventoryBytes(consumerInventoryBytes);+ const consumerInventoryDigest = rawDigest(consumerInventoryBytes);+ const manifestEntries = parseManifestBytes(secureReadSource(manifestSource, 'MANIFEST_SOURCE_INVALID')).manifest+ .entries;+ for (const consumer of consumerInventory.consumers) {+ const credential = manifestEntries.find(+ (entry) => entry.id === consumer.credentialId && entry.provider === 'claude',+ );+ if (!credential || credential.authFilename !== consumer.destination) fail('CONSUMER_CREDENTIAL_MISMATCH');+ }+ const manifestDigest = assertManifestInventory(secureReadSource(manifestSource, 'MANIFEST_SOURCE_INVALID'), accounts);+ const body = {+ version: VERSION,+ accounts,+ inventorySource,+ inventoryDigest,+ consumerInventorySource,+ consumerInventoryDigest,+ manifestSource,+ manifestDigest,+ paths: canonicalPaths,+ runtimeHome,+ operator: args.operator,+ environment: args.environment,+ maxApprovalTtlMs: 900000,+ };+ const intentDigest = digest(body);+ const withIntent = { ...body, intentDigest };+ const artifactDigests = Object.fromEntries(+ Object.entries(artifactBytes(withIntent)).map(([path, bytes]) => [path, rawDigest(bytes)]),+ );+ const reviewed = { ...withIntent, artifactDigests };+ return { ...reviewed, digest: digest(reviewed) };+}+function atomicWrite(path, data, written, onPrepared, modeBits = 0o600) {+ if (existsSync(path)) {+ if (readFileSync(path).equals(Buffer.from(data)) && mode(path) === modeBits) return false;+ 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);+ let descriptor;+ let journaled = false;+ 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 {+ // Journal proof-inode ownership before publishing its final hardlink.+ onPrepared(descriptor);+ journaled = true;+ if (+ process.env.CLAUDE_COORDINATION_TESTING === '1' &&+ process.env.CLAUDE_COORDINATION_TEST_FAULT === 'SIGKILL:PROVISION_PRE_LINK'+ )+ process.kill(process.pid, 'SIGKILL');+ // hard-link publication is atomic and never replaces a concurrently+ // created final target (unlike rename(2)).+ // Test-only adversarial writer used to prove link publication fails closed.+ // CodeQL[js/file-system-race]+ if (process.env.CLAUDE_COORDINATION_TESTING === '1' && process.env.CLAUDE_COORDINATION_TEST_RACE_TARGET === path)+ writeFileSync(path, process.env.CLAUDE_COORDINATION_TEST_RACE_SAME === '1' ? data : 'competing-owner\n', {+ flag: 'wx',+ mode: 0o600,+ });+ linkSync(temp, path);+ if (+ process.env.CLAUDE_COORDINATION_TESTING === '1' &&+ process.env.CLAUDE_COORDINATION_TEST_FAULT === 'SIGKILL:PROVISION_LINKED'+ )+ process.kill(process.pid, 'SIGKILL');+ fsyncDirectory(dirname(path));+ if (+ process.env.CLAUDE_COORDINATION_TESTING === '1' &&+ process.env.CLAUDE_COORDINATION_TEST_FAULT === 'SIGKILL:PROVISION_LINK_FSYNCED'+ )+ process.kill(process.pid, 'SIGKILL');+ if (+ process.env.CLAUDE_COORDINATION_TESTING === '1' &&+ process.env.CLAUDE_COORDINATION_TEST_POST_LINK_REPLACE === path+ ) {+ unlinkSync(path);+ // Test-only post-publication inode replacement.+ // CodeQL[js/file-system-race]+ writeFileSync(path, data, { flag: 'wx', mode: 0o600 });+ }+ if (!descriptorMatches(path, descriptor, 'PUBLICATION_OWNERSHIP_LOST'))+ throw new Error('PUBLICATION_OWNERSHIP_LOST');+ written.push(path);+ return true;+ } catch (error) {+ throw error?.code === 'EEXIST' ? new Error('EXISTING_FILE_MISMATCH') : error;+ } finally {+ if (!journaled) {+ rmSync(temp, { force: true });+ fsyncDirectory(dirname(temp));+ }+ }+}+function rendered(plan) {+ const p = plan.paths;+ const env = `CLAUDE_AUTH_COORDINATION_CONFIG=${p.config}\n` + `CLAUDE_ROTATOR_CONFIG=${p['runtime-inventory']}\n`;+ const templatePath = resolve(+ dirname(fileURLToPath(import.meta.url)),+ '..',+ '..',+ 'templates',+ 'com.claude-ops.account-rotation.plist',+ );+ const macosPlist = readFileSync(templatePath, 'utf8')+ .replaceAll('${HOME}', plan.runtimeHome)+ .replaceAll('__CLAUDE_AUTH_COORDINATION_CONFIG__', p.config)+ .replaceAll('__CLAUDE_ROTATOR_CONFIG__', p['runtime-inventory']);+ return {+ [p['linux-env']]: env,+ [p['macos-env']]: env,+ [p['linux-unit']]:+ `[Unit]\nDescription=Claude account rotation daemon\nAfter=network-online.target\n\n[Service]\nType=simple\nEnvironmentFile=${p['linux-env']}\nExecStart=/usr/bin/env node ${resolve(dirname(fileURLToPath(import.meta.url)), 'daemon.mjs')}\nRestart=on-failure\nRestartSec=30\n\n[Install]\nWantedBy=default.target\n`,+ [p['linux-token-feed-unit']]:+ `[Service]\nType=oneshot\nEnvironmentFile=${p['linux-env']}\nExecStart=/bin/bash ${resolve(dirname(fileURLToPath(import.meta.url)), 'crs-token-feed.sh')}\n`,+ [p['linux-refresh-unit']]:+ `[Service]\nType=oneshot\nEnvironmentFile=${p['linux-env']}\nExecStart=/usr/bin/env node ${resolve(dirname(fileURLToPath(import.meta.url)), 'refresh-tokens.mjs')}\n`,+ [p['macos-plist']]: macosPlist,+ };+}+function artifactBytes(plan) {+ return {+ [plan.paths.config]: Buffer.from(`${JSON.stringify(configFor(plan), null, 2)}\n`),+ [plan.paths.manifest]: secureReadSource(plan.manifestSource, 'MANIFEST_SOURCE_INVALID'),+ [plan.paths['runtime-inventory']]: secureReadSource(plan.inventorySource, 'INVALID_INVENTORY'),+ [plan.paths['authoritative-consumer-inventory']]: secureReadSource(+ plan.consumerInventorySource,+ 'INVALID_CONSUMER_INVENTORY',+ ),+ ...Object.fromEntries(Object.entries(rendered(plan)).map(([path, value]) => [path, Buffer.from(value)])),+ };+}+function readReviewedPlan(path, expected) {+ const plan = json(path, 'INVALID_PLAN');+ const { digest: supplied, ...body } = plan;+ if (supplied !== digest(body) || supplied !== expected) fail('PLAN_DIGEST_MISMATCH');+ const { artifactDigests, intentDigest, ...intentBody } = body;+ if (intentDigest !== digest(intentBody) || !artifactDigests || Array.isArray(artifactDigests))+ fail('PLAN_DIGEST_MISMATCH');+ return plan;+}+function configFor(plan) {+ const p = plan.paths;+ return {+ manifestPath: p.manifest,+ approvalKeyPath: p.trust,+ usageDir: p.usage,+ stagingDir: p.staging,+ activeDir: p.active,+ quarantineDirs: p.quarantine,+ rollbackDir: p.rollback,+ operationLockPath: p.lock,+ environment: plan.environment,+ authorizedOperator: plan.operator,+ maxApprovalTtlMs: plan.maxApprovalTtlMs,+ runtimeInventoryPath: p['runtime-inventory'],+ runtimeInventoryDigest: plan.inventoryDigest,+ authoritativeConsumerInventoryPath: p['authoritative-consumer-inventory'],+ authoritativeConsumerInventoryDigest: plan.consumerInventoryDigest,+ deploymentPlanDigest: plan.intentDigest,+ };+}+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 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();+ if (+ keys.join(',') !== 'ownedTargets,phase,planDigest,version' ||+ state.version !== 1 ||+ state.planDigest !== plan.digest ||+ !['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' ||+ !/^[a-f0-9]{64}$/.test(target.digest) ||+ !['birthtimeNs', 'dev', 'ino'].every((key) => /^\d+$/.test(target[key])) ||+ !Number.isSafeInteger(target.length) ||+ target.length < 0,+ )+ )+ fail('INVALID_PROVISION_JOURNAL');+ return state;+}+function cleanupOwned(plan, ownedTargets) {+ const allowed = new Set([+ plan.paths.manifest,+ plan.paths.trust,+ plan.paths.config,+ plan.paths['runtime-inventory'],+ plan.paths['authoritative-consumer-inventory'],+ ...Object.keys(rendered(plan)),+ ]);+ if (ownedTargets.some((target) => !allowed.has(target.path))) fail('INVALID_PROVISION_JOURNAL');+ for (const target of [...ownedTargets].reverse()) {+ if (!existsSync(target.proof)) fail('PROVISION_RECOVERY_UNCERTAIN');+ 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);+ }+ rmSync(target.proof);+ if (existsSync(dirname(target.path))) fsyncDirectory(dirname(target.path));+ }+}+function applyReviewed(plan) {+ const supplied = plan.digest;+ 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)));+ 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');+ }+ fsyncDirectory(dirname(target.proof));+ }+ preflight(plan.paths.config, plan.accounts, plan.paths, plan.inventoryDigest, plan);+ rmSync(journalPath(plan));+ fsyncDirectory(dirname(journalPath(plan)));+ return { ok: true, digest: supplied, configPath: plan.paths.config };+ }+ }+ // A resumed transaction intentionally still has authenticated proof+ // hardlinks, which generic topology validation rejects by link count. The+ // loop above has already matched every proof and final path to its journaled+ // inode and digest; fresh transactions take the full topology snapshot here.+ if (!resuming) validateTopology(plan.paths, plan.paths.quarantine);+ if (realpathSync(plan.manifestSource) !== resolve(plan.manifestSource)) fail('MANIFEST_SOURCE_INVALID');+ validateExistingTarget(plan.manifestSource, 'file');+ const manifestBytes = secureReadSource(plan.manifestSource, 'MANIFEST_SOURCE_INVALID');+ if (assertManifestInventory(manifestBytes, plan.accounts) !== plan.manifestDigest) fail('MANIFEST_SOURCE_CHANGED');+ validateExistingTarget(plan.inventorySource, 'file');+ const inventoryBytes = secureReadSource(plan.inventorySource, 'INVALID_INVENTORY');+ if (rawDigest(inventoryBytes) !== plan.inventoryDigest) fail('INVENTORY_SOURCE_CHANGED');+ if (canonicalJson(accountsFromInventoryBytes(inventoryBytes)) !== canonicalJson(plan.accounts))+ fail('INVENTORY_IDENTITY_MISMATCH');+ validateExistingTarget(plan.consumerInventorySource, 'file');+ const consumerInventoryBytes = secureReadSource(plan.consumerInventorySource, 'INVALID_CONSUMER_INVENTORY');+ if (rawDigest(consumerInventoryBytes) !== plan.consumerInventoryDigest) fail('CONSUMER_INVENTORY_SOURCE_CHANGED');+ consumersFromInventoryBytes(consumerInventoryBytes);+ const expectedArtifactDigests = Object.fromEntries(+ Object.entries(artifactBytes(plan)).map(([path, bytes]) => [path, rawDigest(bytes)]),+ );+ if (canonicalJson(expectedArtifactDigests) !== canonicalJson(plan.artifactDigests)) fail('ARTIFACT_DIGEST_MISMATCH');+ const written = [];+ const generated = rendered(plan);+ const configBytes = Buffer.from(`${JSON.stringify(configFor(plan), null, 2)}\n`);+ let newKeyBytes;+ if (!state) {+ newKeyBytes = randomBytes(32);+ state = {+ version: 1,+ planDigest: plan.digest,+ phase: 'APPLYING',+ ownedTargets: [],+ };+ writeProvisionJournal(plan, state);+ }+ try {+ for (const dir of [+ plan.paths.active,+ plan.paths.staging,+ plan.paths.usage,+ plan.paths.rollback,+ ...plan.paths.quarantine,+ dirname(plan.paths.lock),+ dirname(plan.paths.trust),+ ])+ mkdirSync(dir, { recursive: true, mode: 0o700 });+ const publish = (path, bytes) => {+ const owned = state.ownedTargets.find((target) => target.path === path);+ if (owned && owned.digest !== rawDigest(bytes)) fail('INVALID_PROVISION_JOURNAL');+ atomicWrite(path, bytes, written, (descriptor) => {+ 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))+ process.kill(process.pid, 'SIGKILL');+ };+ publish(plan.paths.manifest, manifestBytes);+ if (existsSync(plan.paths.trust)) {+ const owned = state.ownedTargets.find((target) => target.path === plan.paths.trust);+ const trust = secureReadDescriptor(plan.paths.trust, 'EXISTING_FILE_MISMATCH', false);+ if (mode(plan.paths.trust) !== 0o600 || trust.length !== 32 || (owned && trust.digest !== owned.digest))+ fail('EXISTING_FILE_MISMATCH');+ } else if (newKeyBytes) publish(plan.paths.trust, newKeyBytes);+ else fail('PROVISION_KEY_RECOVERY_REQUIRED');+ publish(plan.paths.config, configBytes);+ 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));+ state = { ...state, phase: 'COMPLETE' };+ writeProvisionJournal(plan, state);+ for (const target of state.ownedTargets) {+ if (!descriptorMatches(target.proof, target) || !descriptorMatches(target.path, target))+ fail('PROVISION_RECOVERY_UNCERTAIN');+ }+ 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))+ 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)));+ 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)));+ throw error;+ }+}+function apply(planPath, expected) {+ const plan = readReviewedPlan(planPath, expected);+ return withProvisionLock(plan, () => applyReviewed(plan));+}+function rollbackReviewed(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)));+ return { ok: true, rolledBack: true, digest: plan.digest };+}+function rollback(planPath, expected) {+ const plan = readReviewedPlan(planPath, expected);+ return withProvisionLock(plan, () => rollbackReviewed(plan));+}+function activateLinux(planPath, expected) {+ const plan = readReviewedPlan(planPath, expected);+ return withProvisionLock(plan, () => {+ preflight(plan.paths.config, plan.accounts, plan.paths, plan.inventoryDigest, plan);+ const unitPath = plan.paths['linux-unit'];+ const pinned = lstatSync(unitPath);+ const expectedDigest = plan.artifactDigests[unitPath];+ const assertPinned = () => {+ const current = lstatSync(unitPath);+ if (+ current.dev !== pinned.dev ||+ current.ino !== pinned.ino ||+ rawDigest(secureReadSource(unitPath, 'GENERATED_ARTIFACT_CHANGED')) !== expectedDigest+ )+ fail('GENERATED_ARTIFACT_CHANGED');+ };+ const systemctl = (...args) => {+ assertPinned();+ const result = spawnSync('systemctl', ['--user', ...args], {+ encoding: 'utf8',+ stdio: ['ignore', 'pipe', 'pipe'],+ });+ assertPinned();+ if (result.status !== 0) fail('SYSTEMD_ACTIVATION_FAILED');+ return String(result.stdout || '').trim();+ };+ systemctl('daemon-reload');+ systemctl('enable', 'claude-account-rotator');+ systemctl('restart', 'claude-account-rotator');+ const status = systemctl('is-active', 'claude-account-rotator');+ if (status !== 'active') fail('SYSTEMD_ACTIVATION_FAILED');+ return { ok: true, activated: 'claude-account-rotator', planDigest: plan.digest };+ });+}+function preflight(configPath, accounts, expectedPaths, expectedInventoryDigest, reviewedPlan) {+ const config = readDeploymentConfig(configPath);+ if (+ mode(configPath) !== 0o600 ||+ mode(config.approvalKeyPath) !== 0o600 ||+ statSync(config.approvalKeyPath).size !== 32+ )+ fail('INVALID_TRUST_MODE');+ const cfgAccounts =+ accounts || accountsFromInventory(process.env.CLAUDE_ROTATOR_INVENTORY || fail('INVENTORY_REQUIRED'));+ if (!cfgAccounts.length) fail('ACCOUNT_IDENTITY_REQUIRED');+ assertManifestInventory(readFileSync(config.manifestPath), cfgAccounts);+ const authoritativeConsumers = secureReadSource(+ config.authoritativeConsumerInventoryPath,+ 'INVALID_CONSUMER_INVENTORY',+ );+ consumersFromInventoryBytes(authoritativeConsumers);+ if (rawDigest(authoritativeConsumers) !== config.authoritativeConsumerInventoryDigest)+ fail('AUTHORITATIVE_CONSUMER_INVENTORY_MISMATCH');+ const runtimeInventoryBytes = expectedPaths+ ? secureReadSource(expectedPaths['runtime-inventory'], 'RUNTIME_INVENTORY_MISMATCH')+ : null;+ if (expectedPaths && (!runtimeInventoryBytes || rawDigest(runtimeInventoryBytes) !== expectedInventoryDigest))+ fail('RUNTIME_INVENTORY_MISMATCH');+ if (expectedPaths && canonicalJson(accountsFromInventoryBytes(runtimeInventoryBytes)) !== canonicalJson(cfgAccounts))+ fail('RUNTIME_INVENTORY_IDENTITY_MISMATCH');+ if (reviewedPlan) {+ const expectedConfig = Buffer.from(`${JSON.stringify(configFor(reviewedPlan), null, 2)}\n`);+ if (+ rawDigest(secureReadSource(configPath, 'CONFIG_ARTIFACT_MISMATCH')) !==+ reviewedPlan.artifactDigests[configPath] ||+ !readFileSync(configPath).equals(expectedConfig) ||+ config.deploymentPlanDigest !== reviewedPlan.intentDigest+ )+ fail('CONFIG_ARTIFACT_MISMATCH');+ for (const [path, expectedDigest] of Object.entries(reviewedPlan.artifactDigests))+ if (rawDigest(secureReadSource(path, 'GENERATED_ARTIFACT_MISMATCH')) !== expectedDigest)+ fail('GENERATED_ARTIFACT_MISMATCH');+ }+ const paths = expectedPaths || {+ config: configPath,+ trust: config.approvalKeyPath,+ manifest: config.manifestPath,+ active: config.activeDir,+ staging: config.stagingDir,+ usage: config.usageDir,+ rollback: config.rollbackDir,+ lock: config.operationLockPath,+ quarantine: config.quarantineDirs,+ };+ validateTopology(+ { ...paths, ...Object.fromEntries(PATH_FLAGS.filter((k) => !paths[k]).map((k) => [k, `/dev/null/${k}`])) },+ paths.quarantine,+ );+ if (expectedPaths)+ for (const path of [expectedPaths['linux-env'], expectedPaths['macos-env']])+ if (+ readFileSync(path, 'utf8') !==+ `CLAUDE_AUTH_COORDINATION_CONFIG=${configPath}\nCLAUDE_ROTATOR_CONFIG=${expectedPaths['runtime-inventory']}\n`+ )+ fail('ENV_CONFIG_MISMATCH');+ return {+ ok: true,+ configPath,+ runtimeInventoryPath: expectedPaths?.['runtime-inventory'],+ linuxUnitPath: expectedPaths?.['linux-unit'],+ };+}++function main() {+ const [command, ...argv] = process.argv.slice(2);+ const args = parseArgs(argv);+ let result;+ if (command === 'plan') result = buildPlan(args);+ else if (command === 'apply') result = apply(args.plan, args['expected-digest']);+ else if (command === 'rollback') result = rollback(args.plan, args['expected-digest']);+ else if (command === 'activate-linux') result = activateLinux(args.plan, args['expected-digest']);+ else if (command === 'preflight') {+ if (args.plan || args['expected-digest']) {+ const plan = readReviewedPlan(args.plan, args['expected-digest']);+ result = preflight(plan.paths.config, plan.accounts, plan.paths, plan.inventoryDigest, plan);+ for (const [path, expected] of Object.entries(rendered(plan)))+ if (readFileSync(path, 'utf8') !== expected || /\$\{HOME\}|__HOME__/.test(expected))+ fail('GENERATED_ARTIFACT_MISMATCH');+ } else result = preflight(args.config, args.inventory ? accountsFromInventory(args.inventory) : undefined);+ } else fail('INVALID_ARGUMENTS');+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);+}+if (resolve(process.argv[1] || '') === fileURLToPath(import.meta.url))+ try {+ main();+ } catch (e) {+ console.error(e.message);+ process.exitCode = 1;+ }diff --git a/claude-ops/scripts/account-rotation/refresh-tokens.mjs b/claude-ops/scripts/account-rotation/refresh-tokens.mjsindex 515c376c..acde1fec 100644--- a/claude-ops/scripts/account-rotation/refresh-tokens.mjs+++ b/claude-ops/scripts/account-rotation/refresh-tokens.mjs@@ -21,7 +21,10 @@ import { fileURLToPath } from 'url';import { execFileSync, execSync } from 'child_process';import { fetchWithProxyFallback } from './proxy-helper.mjs';import { acquireRefreshLock } from './crs-refresh-lock.mjs';-import { readRotationToken, reconcileRemoteRotationVault, writeRotationToken } from './rotation-vault.mjs';+import { readRotationToken, reconcileRemoteRotationVault, writeRotationTokenCoordinated } from './rotation-vault.mjs';+import { withAuthWriterLock } from './auth-writer-coordination.mjs';+import { verifyRefreshedTokenIdentity } from './token-identity.mjs';+import { automatedAuthAllowed } from './auto-auth-policy.mjs';import {REFRESH_WHEN_BELOW_MS,MIN_HEALTHY_TTL_MS,@@ -31,7 +34,7 @@ import {} from './oauth-keep-alive-policy.mjs';const __dirname = dirname(fileURLToPath(import.meta.url));-const CONFIG_PATH = join(__dirname, 'config.json');+const CONFIG_PATH = process.env.CLAUDE_ROTATOR_CONFIG || join(__dirname, 'config.json');const STATE_PATH = join(__dirname, 'state.json');const LOG_PATH = join(__dirname, 'rotation.log');const NEEDS_REAUTH_PATH = join(__dirname, '.crs-token-refresher-state.json');@@ -97,8 +100,8 @@ function readStoredToken(account) {}}-function writeStoredToken(account, json) {- writeRotationToken(accountKey(account), json);+function writeStoredToken(account, json, capability) {+ return writeRotationTokenCoordinated(account, json, capability);}function syncStoredTokenToCrs(account) {@@ -308,15 +311,6 @@ function showStatus() {const args = process.argv.slice(2);-try {- const reconciled = reconcileRemoteRotationVault();- if (!reconciled.skipped && (reconciled.pulled > 0 || reconciled.pushed > 0)) {- log(`remote vault reconciled: ${reconciled.pulled} pulled, ${reconciled.pushed} pushed`);- }-} catch (error) {- log(`remote vault reconciliation unavailable — ${String(error.message || error).slice(0, 180)}`);-}-if (args.includes('--status')) {showStatus();process.exit(0);@@ -326,27 +320,15 @@ const force = args.includes('--force');const dryRun = args.includes('--dry-run');const config = JSON.parse(readFileSync(CONFIG_PATH, 'utf8'));const state = readState();-const ROTATING_LOCK = join(__dirname, '.rotating');-const MAGIC_LINK_TIMEOUT_MS = Number(process.env.CLAUDE_ROT_MAGIC_TOTAL_TIMEOUT_MS || 720_000);--function pidAlive(pid) {- if (!pid) return false;- try {- process.kill(pid, 0);- return true;- } catch {- return false;- }-}-/** True when another rotate/reauth already holds the fleet lock. */-function rotationInProgress() {+if (config.accounts.some(automatedAuthAllowed)) {try {- if (!existsSync(ROTATING_LOCK)) return false;- const raw = JSON.parse(readFileSync(ROTATING_LOCK, 'utf8'));- return pidAlive(Number(raw?.pid || 0));- } catch {- return false;+ const reconciled = reconcileRemoteRotationVault();+ if (!reconciled.skipped && (reconciled.pulled > 0 || reconciled.pushed > 0)) {+ log(`remote vault reconciled: ${reconciled.pulled} pulled, ${reconciled.pushed} pushed`);+ }+ } catch (error) {+ log(`remote vault reconciliation unavailable — ${String(error.message || error).slice(0, 180)}`);}}@@ -362,18 +344,6 @@ function magicLinkPriority(account) {return weekly;}-function shouldSkipMagicLinkForUtil(account) {- const key = accountKey(account);- const u = state.accounts?.[key]?.lastUtilization || {};- const now = Date.now();- const pct7 = Number(u.pct7);- const reset7Ms = Number(u.reset7) > 0 ? Number(u.reset7) * 1000 : 0;- if (Number.isFinite(pct7) && pct7 >= 95 && !(reset7Ms && reset7Ms < now)) {- return `7d util ${pct7}% exhausted — re-auth deferred (cannot use until weekly reset)`;- }- return null;-}-// Process accounts with freshest tokens first for refresh grant; when picking// the single magic-link attempt, prefer headroom (low weekly util) over exhausted.const accountsOrdered = [...config.accounts].sort((a, b) => {@@ -390,7 +360,6 @@ const accountsOrdered = [...config.accounts].sort((a, b) => {let refreshed = 0;let failed = 0;let skipped = 0;-let magicLinkAttempted = false;for (let i = 0; i < accountsOrdered.length; i++) {const account = accountsOrdered[i];@@ -405,6 +374,11 @@ for (let i = 0; i < accountsOrdered.length; i++) {skipped++;continue;}+ if (!automatedAuthAllowed(account)) {+ log(`${key}: automatic credential mutation not approved — status only`);+ skipped++;+ continue;+ }const tokenJson = readStoredToken(account);@@ -438,115 +412,89 @@ for (let i = 0; i < accountsOrdered.length; i++) {}try {- // Rate limit courtesy: delay between accounts- if (i > 0) {- await sleep(INTER_ACCOUNT_DELAY_MS);- }+ await withAuthWriterLock(async (writerCapability) => {+ // Rate limit courtesy: delay between accounts+ if (i > 0) {+ await sleep(INTER_ACCOUNT_DELAY_MS);+ }- const parsed = parseToken(tokenJson);- const oauthData = parsed?.claudeAiOauth;- if (!oauthData?.refreshToken) {- log(`${key}: no refreshToken in stored token — skipping`);- failed++;- continue;- }+ const currentTokenJson = readStoredToken(account);+ const parsed = parseToken(currentTokenJson);+ const oauthData = parsed?.claudeAiOauth;+ if (!oauthData?.refreshToken) {+ log(`${key}: no refreshToken in stored token — skipping`);+ failed++;+ return;+ }++ const result = await refreshOAuthToken(oauthData.refreshToken);++ if (!result.ok) {+ log(`${key}: ✗ refresh failed — ${result.error}`);- const result = await refreshOAuthToken(oauthData.refreshToken);-- if (!result.ok) {- log(`${key}: ✗ refresh failed — ${result.error}`);-- // HTTP 400 = dead refresh_token. Browser re-auth is owned by the always-on- // magic-link-autoloop (com.sam.crs-magic-link-autoloop) — never spawn a- // competing headed OAuth from the hourly refresher (2026-07-16 thrash).- // Opt-in only: CLAUDE_ROTATION_REFRESH_MAGIC_LINK=1 for emergency one-shots.- if (result.error && result.error.includes('400')) {- if (account.autoAuthDisabled === true) {- log(`${key}: unattended re-auth disabled — leaving token for manual recovery`);- } else if (process.env.CLAUDE_ROTATION_REFRESH_MAGIC_LINK === '1' && !magicLinkAttempted) {- const utilSkip = shouldSkipMagicLinkForUtil(account);- if (utilSkip) {- log(`${key}: ${utilSkip}`);- } else if (rotationInProgress()) {- log(`${key}: rotation lock held — deferring magic-link re-auth`);+ // HTTP 400 = dead refresh_token. Never spawn authentication from the+ // refresher; a separately approved staged enrollment owns recovery.+ if (result.error && result.error.includes('400')) {+ if (account.autoAuthDisabled === true) {+ log(`${key}: unattended re-auth disabled — leaving token for manual recovery`);} else {- magicLinkAttempted = true;- log(- `${key}: refresh token invalid — CLAUDE_ROTATION_REFRESH_MAGIC_LINK=1 → magic-link (timeout ${Math.round(MAGIC_LINK_TIMEOUT_MS / 1000)}s)...`,- );- try {- const reAuthResult = execFileSync(- process.execPath,- [join(__dirname, 'rotate.mjs'), '--to', key, '--magic-link', '--force'],- { timeout: MAGIC_LINK_TIMEOUT_MS, encoding: 'utf8' },- );- log(`${key}: magic link re-auth output: ${reAuthResult.split('\n').slice(-3).join(' | ')}`);- const reAuthedToken = readStoredToken(account);- if (reAuthedToken) {- const reParsed = parseToken(reAuthedToken);- if (reParsed?.claudeAiOauth?.accessToken) {- log(`${key}: ✓ re-authed via magic link`);- refreshed++;- continue;- }- }- log(`${key}: magic link re-auth did not produce a valid token`);- } catch (err) {- log(`${key}: magic link re-auth failed — ${err.message}`);- }+ log(`${key}: refresh grant failed (HTTP 400) — staged enrollment approval required`);+ markNeedsReauth(key, result.error);}- } else {- log(`${key}: refresh grant failed (HTTP 400) — marking needsReauth for magic-link-autoloop`);+ } else if (result.error && /401|invalid|revoked/i.test(result.error)) {markNeedsReauth(key, result.error);}- } else if (result.error && /401|invalid|revoked/i.test(result.error)) {- markNeedsReauth(key, result.error);- }- failed++;- continue;- }-- // Build updated token- const updated = {- claudeAiOauth: {- accessToken: result.accessToken,- refreshToken: result.refreshToken,- expiresAt: result.expiresAt,- scopes: oauthData.scopes || [],- subscriptionType: result.subscriptionType || oauthData.subscriptionType,- rateLimitTier: result.rateLimitTier || oauthData.rateLimitTier,- },- mcpOAuth: {},- };+ failed++;+ return;+ }- // Save to vault- writeStoredToken(account, JSON.stringify(updated));- syncStoredTokenToCrs(account);- clearNeedsReauth(key);- const newHoursLeft = ((result.expiresAt - Date.now()) / 3_600_000).toFixed(1);- log(`${key}: ✓ refreshed (${newHoursLeft}h remaining)`);-- // If this is the currently active account, update the active keychain too- if (state.activeAccount === key) {- try {- const currentActive = readKeychain();- const currentParsed = parseToken(currentActive);- // Always merge mcpOAuth from the running session — drop the Object.keys>0 guard- // which silently skipped preservation when a prior rotation had already zeroed the- // field, causing CC to lose all MCP OAuth tokens (giga, Amplitude, higgsfield) on- // the next session launch and forcing interactive reauth every session.- if (currentParsed?.mcpOAuth) {- updated.mcpOAuth = { ...updated.mcpOAuth, ...currentParsed.mcpOAuth };+ // Build updated token+ const updated = {+ claudeAiOauth: {+ accessToken: result.accessToken,+ refreshToken: result.refreshToken,+ expiresAt: result.expiresAt,+ scopes: oauthData.scopes || [],+ subscriptionType: result.subscriptionType || oauthData.subscriptionType,+ rateLimitTier: result.rateLimitTier || oauthData.rateLimitTier,+ },+ mcpOAuth: {},+ };++ await verifyRefreshedTokenIdentity(account, result.accessToken);++ // Save to vault+ await writeStoredToken(account, JSON.stringify(updated), writerCapability);+ syncStoredTokenToCrs(account);+ clearNeedsReauth(key);+ const newHoursLeft = ((result.expiresAt - Date.now()) / 3_600_000).toFixed(1);+ log(`${key}: ✓ refreshed (${newHoursLeft}h remaining)`);++ // If this is the currently active account, update the active keychain too+ // Recheck active-account ownership under the same canonical lock; the+ // pre-refresh state snapshot may have changed while the grant was in flight.+ if (readState().activeAccount === key) {+ try {+ const currentActive = readKeychain();+ const currentParsed = parseToken(currentActive);+ // Always merge mcpOAuth from the running session — drop the Object.keys>0 guard+ // which silently skipped preservation when a prior rotation had already zeroed the+ // field, causing CC to lose all MCP OAuth tokens (giga, Amplitude, higgsfield) on+ // the next session launch and forcing interactive reauth every session.+ if (currentParsed?.mcpOAuth) {+ updated.mcpOAuth = { ...updated.mcpOAuth, ...currentParsed.mcpOAuth };+ }+ await verifyRefreshedTokenIdentity(account, updated.claudeAiOauth.accessToken);+ writeKeychain(JSON.stringify(updated));+ log(`${key}: ✓ also updated active keychain with mcpOAuth preserved`);+ } catch (err) {+ log(`${key}: ⚠ vault updated but active keychain update failed — ${err.message}`);}- writeKeychain(JSON.stringify(updated));- log(`${key}: ✓ also updated active keychain with mcpOAuth preserved`);- } catch (err) {- log(`${key}: ⚠ vault updated but active keychain update failed — ${err.message}`);}- }- refreshed++;+ refreshed++;+ });} finally {releaseRefreshLock();}diff --git a/claude-ops/scripts/account-rotation/rotate-magic.mjs b/claude-ops/scripts/account-rotation/rotate-magic.mjsindex 60a4fd84..7b4e6b29 100755--- a/claude-ops/scripts/account-rotation/rotate-magic.mjs+++ b/claude-ops/scripts/account-rotation/rotate-magic.mjs@@ -1,57 +1,6 @@#!/usr/bin/env node-/**- * rotate-magic — thin entry for unattended magic-link re-auth.- *- * SSOT implementation: rotate.mjs --magic-link (plus setup --auto for multi-account).- * Ensures captcha wall hooks exist in rotate.mjs, then loads captcha cascade modules- * when present (captcha-cascade.mjs / rotate-captcha-soft.mjs).- * Does NOT require CRS. Optional CRS reconcilers call this via magic-link-autoloop.- *- * Usage:- * node rotate-magic.mjs --to <email>- * node rotate-magic.mjs --to <email> --force- * node rotate-magic.mjs --setup --only=<email> --auto --skip-valid- *- * Env: see CAPTCHA-CASCADE.md and reauth-env.mjs (CLAUDE_DESKTOP_DISPLAY, headed, cascade flags).- */-import { spawn } from 'child_process';-import { dirname, join } from 'path';-import { fileURLToPath } from 'url';-import { ensureRotateCaptchaHooks } from './ensure-rotate-captcha-hooks.mjs';--const __dirname = dirname(fileURLToPath(import.meta.url));-const rotate = join(__dirname, 'rotate.mjs');-const argv = process.argv.slice(2);--// Ensure trySolveCaptchaWall call sites exist in public rotate.mjs (idempotent).-try {- const r = ensureRotateCaptchaHooks();- if (r.changed) {- console.error(`[rotate-magic] applied captcha wall hooks to rotate.mjs (${r.reason || 'patched'})`);- }-} catch (e) {- console.error(`[rotate-magic] captcha hook ensure failed: ${String(e.message || e).slice(0, 120)}`);-}--// Default to magic-link mode unless caller already chose --setup / --status / etc.-const hasMode = argv.some(- (a) =>- a === '--magic-link' ||- a === '--setup' ||- a === '--status' ||- a === '--utilization' ||- a === '--capture' ||- a === '--audit-billing' ||- a.startsWith('--setup'),+/** Legacy direct reauthentication entry point. Intentionally fail closed. */+console.error(+ 'Claude direct browser/magic-link reauthentication is disabled. Use staged-enrollment.mjs with separately signed stage and activate approvals.',);-const finalArgv = hasMode ? argv : ['--magic-link', ...argv];--const child = spawn(process.execPath, [rotate, ...finalArgv], {- stdio: 'inherit',- env: process.env,- cwd: process.cwd(),-});-child.on('exit', (code, signal) => {- if (signal) process.kill(process.pid, signal);- process.exit(code ?? 1);-});+process.exitCode = 2;diff --git a/claude-ops/scripts/account-rotation/rotate.mjs b/claude-ops/scripts/account-rotation/rotate.mjsindex 652f2aee..26e821c5 100644--- a/claude-ops/scripts/account-rotation/rotate.mjs+++ b/claude-ops/scripts/account-rotation/rotate.mjs@@ -17,13 +17,9 @@* node rotate.mjs --status # show state* node rotate.mjs --utilization # live 5h/7d utilization per account* node rotate.mjs --audit-billing # 🔴/🟢 per-account extra_usage (overage billing) audit- * node rotate.mjs --setup # manual: claude auth login per account (interactive)- * node rotate.mjs --setup --auto # AUTOMATED: magic-link + browser cascade, all configured accounts end-to-end- * node rotate.mjs --setup --auto --skip-valid # skip accounts whose vault token is still alive- * node rotate.mjs --setup --only=<key> # only re-capture one account (e.g. [email protected])+ * Direct setup and browser authentication are disabled; use staged enrollment.* node rotate.mjs --capture # save current active token (print for Dashlane)* node rotate.mjs --session # also send /login to running iTerm2 session- * node rotate.mjs --magic-link --to <email> # re-auth via email magic link (no Google OAuth)* Note: --allow-extra-usage is ignored if passed (legacy); extra_usage is per-org in Claude console only.*/@@ -45,6 +41,7 @@ import {constants as fsConstants,} from 'fs';import { persistBedrockClaudeSettings } from './claude-settings-mode.mjs';+import { automatedAuthAllowed } from './auto-auth-policy.mjs';import { join, dirname } from 'path';import { fileURLToPath } from 'url';import { execSync, execFileSync, spawnSync, spawn } from 'child_process';@@ -54,6 +51,11 @@ import { askAIBrain, executeAIAction, AI_BRAIN_MAX_DECISIONS, scrapeBillingStateimport { destinationUtilHardBlock } from './rotation-policy.mjs';import { applyAccountLeases, writeLease } from './account-leases.mjs';import { respawnBgSessions } from './bg-respawn.mjs';+import { withAuthWriterLock } from './auth-writer-coordination.mjs';+import { createVerifiedCredentialWriter, requireVerifiedCredentialCapability } from './verified-credential-write.mjs';+import { directOAuthWriterAllowed } from './auto-auth-policy.mjs';+import { applyBrowserPinTransaction, restoreBrowserPinBackup } from './browser-pin-recovery.mjs';+import { readDeploymentConfig } from './staged-enrollment.mjs';import {trySolveCaptchaWall,maybeClearCaptchaWall,@@ -61,6 +63,16 @@ import {captchaHardFailed,} from './rotate-captcha-soft.mjs';+if (process.argv.includes('--capture')) {+ console.error('direct credential capture refused: staged enrollment is required');+ process.exit(2);+}++if (process.argv.includes('--bootstrap-chrome-profile') || process.argv.includes('--bootstrap-all-chrome-profiles')) {+ console.error('direct Chrome profile bootstrap refused: staged enrollment is required');+ process.exit(2);+}+const __dirname = dirname(fileURLToPath(import.meta.url));// Account config lives in the gitignored user data dir (written by// setup-account.mjs, Rule 0: no real account data in the committed repo).@@ -80,14 +92,15 @@ const LOG_PATH = join(ROTATION_DATA_DIR, 'rotation.log');const RATE_LIMITS_PATH = join(ROTATION_DATA_DIR, '.rate-limits.json');const OAUTH_SNAPSHOTS_DIR = join(ROTATION_DATA_DIR, 'oauth-snapshots');const BROWSER_PIN_PATH = join(ROTATION_DATA_DIR, '.browser-pin');-const BROWSER_PIN_BACKUP_PATH = join(ROTATION_DATA_DIR, '.browser-pin-backup.json');+const BROWSER_PIN_RECOVERY_PATH = join(ROTATION_DATA_DIR, '.browser-pin-recovery.json');+const BROWSER_PIN_BACKUP_DIR = join(ROTATION_DATA_DIR, 'browser-pin-backups');const CLAUDE_JSON_PATH = join(process.env.HOME || '', '.claude.json');// One-time migration from historical repo-local runtime files. These files can// contain real account identifiers and must never live inside the public checkout,// even when gitignored, because the repository secret scanner intentionally scans// the working tree too.-for (const name of ['state.json', 'rotation.log', '.rate-limits.json', '.browser-pin', '.browser-pin-backup.json']) {+for (const name of ['state.json', 'rotation.log', '.rate-limits.json', '.browser-pin']) {const oldPath = join(__dirname, name);const newPath = join(ROTATION_DATA_DIR, name);if (!existsSync(oldPath) || existsSync(newPath)) continue;@@ -486,11 +499,8 @@ async function queryAllUtilization(config) {fetchWithRetry('https://api.anthropic.com/api/oauth/profile'),]);- // 401 = the stored token is revoked/expired. Drop it from the vault so we- // stop polling a dead token every tick and the next rotation re-acquires.if (usageRes.status === 401) {- log(`[query] Account ${a.email || accountKey(a)} returned 401 on /oauth/usage — invalidating stored token`);- deleteStoredToken(a);+ log(`[query] Account ${a.email || accountKey(a)} returned 401 — credential retained; needsReauth=true`);return null;}@@ -982,11 +992,7 @@ function readKeychain(return m[1].replace(/\\"/g, '"');}-function writeKeychain(- json,- svc = KEYCHAIN_SERVICE,- acct = svc === KEYCHAIN_SERVICE ? ACTIVE_KEYCHAIN_ACCOUNT : VAULT_KEYCHAIN_ACCOUNT,-) {+function writeKeychainUnlocked(json, svc, acct) {if (IS_LINUX) {_linuxWriteCred(svc, json);return;@@ -999,6 +1005,13 @@ function writeKeychain(execFileSync('security', ['add-generic-password', '-s', svc, '-a', acct, '-w', json], { timeout: 5000 });}+const verifiedWriteCredential = createVerifiedCredentialWriter({+ write: (account, json, verifiedCapability, svc, acct) => {+ requireVerifiedCredentialCapability(verifiedCapability, { account, credential: json, destination: svc });+ return writeKeychainUnlocked(json, svc, acct);+ },+});+function tokenExpired(json) {try {const exp = JSON.parse(json)?.claudeAiOauth?.expiresAt;@@ -1026,8 +1039,8 @@ function readStoredToken(account) {}}-function writeStoredToken(account, json) {- writeKeychain(json, tokenService(account));+async function writeStoredToken(account, json) {+ return verifiedWriteCredential(account, json, tokenService(account), VAULT_KEYCHAIN_ACCOUNT);}// Remove an account's stored OAuth token from the local vault (keychain entry@@ -1037,6 +1050,10 @@ function writeStoredToken(account, json) {// the next rotation to re-acquire a fresh token instead of retrying a dead one// forever. Best-effort: a missing entry is not an error.function deleteStoredToken(account) {+ return withAuthWriterLock(() => deleteStoredTokenUnlocked(account));+}++function deleteStoredTokenUnlocked(account) {const svc = tokenService(account);if (IS_LINUX) {try {@@ -1367,34 +1384,34 @@ function applyOauthSnapshotToClaudeJson(snapshot) {return changed;}-function backupCurrentOauthBlocks() {- const cj = readClaudeJson();- if (!cj) return false;- const blocks = extractOauthBlocks(cj);- if (!blocks?.oauthAccount?.emailAddress) return false;- const payload = {- backedUpAt: new Date().toISOString(),- email: blocks.oauthAccount.emailAddress,- blocks,- };- writeFileSync(BROWSER_PIN_BACKUP_PATH, JSON.stringify(payload, null, 2));- return true;+function applyOauthSnapshotTransaction(snapshot) {+ const coordinationKey = readFileSync(+ readDeploymentConfig(process.env.CLAUDE_AUTH_COORDINATION_CONFIG).approvalKeyPath,+ );+ return applyBrowserPinTransaction({+ sourcePath: CLAUDE_JSON_PATH,+ destinationPath: CLAUDE_JSON_PATH,+ sentinelPath: BROWSER_PIN_RECOVERY_PATH,+ backupDirectory: BROWSER_PIN_BACKUP_DIR,+ coordinationKey,+ apply: () => {+ if (!applyOauthSnapshotToClaudeJson(snapshot)) throw new Error('BROWSER_PIN_APPLY_FAILED');+ },+ });}function restoreOauthBlocksFromBackup() {- if (!existsSync(BROWSER_PIN_BACKUP_PATH)) return false;- try {- const backup = JSON.parse(readFileSync(BROWSER_PIN_BACKUP_PATH, 'utf8'));- const applied = applyOauthSnapshotToClaudeJson({ blocks: backup.blocks });- if (applied) log(`[oauth-snapshot] restored backup oauthAccount=${backup.email}`);- try {- unlinkSync(BROWSER_PIN_BACKUP_PATH);- } catch {}- return applied;- } catch (e) {- log(`[oauth-snapshot] backup restore failed: ${e.message?.slice(0, 100)}`);- return false;- }+ const coordinationKey = readFileSync(+ readDeploymentConfig(process.env.CLAUDE_AUTH_COORDINATION_CONFIG).approvalKeyPath,+ );+ const result = restoreBrowserPinBackup({+ destinationPath: CLAUDE_JSON_PATH,+ sentinelPath: BROWSER_PIN_RECOVERY_PATH,+ coordinationKey,+ });+ if (result.restored) log('[oauth-snapshot] restored byte-identical pre-pin Claude configuration');+ else if (result.reason !== 'no-operation') log(`[oauth-snapshot] backup restore retained: ${result.reason}`);+ return result.restored;}// Fetches Google password AND (optional) TOTP secret from dcli by querying@@ -1547,7 +1564,7 @@ async function refreshExpiredStoredToken(account, tokenJson) {mcpOAuth: {},};const json = JSON.stringify(updated);- writeStoredToken(account, json);+ await writeStoredToken(account, json);return json;} catch (e) {log(`[refresh] ${accountKey(account)}: refresh error — ${e.message?.slice(0, 100)}`);@@ -1581,7 +1598,7 @@ async function swapToken(account) {if (sourceKey && sourceKey !== accountKey(account)) {const swapConfig = readConfig();const sourceAccount = swapConfig.accounts.find((a) => accountKey(a) === sourceKey);- if (sourceAccount) {+ if (sourceAccount && automatedAuthAllowed(sourceAccount)) {const currentJson = (() => {try {return readKeychain(KEYCHAIN_SERVICE, ACTIVE_KEYCHAIN_ACCOUNT);@@ -1593,7 +1610,7 @@ async function swapToken(account) {try {const parsed = JSON.parse(currentJson);const clean = JSON.stringify({ claudeAiOauth: parsed.claudeAiOauth, mcpOAuth: {} });- writeKeychain(clean, tokenService(sourceAccount));+ await writeStoredToken(sourceAccount, clean);log(`[save-back] preserved current token for ${sourceKey}`);} catch (e) {log(`[save-back] skipped: parse/write error — ${e.message?.slice(0, 80)}`);@@ -1601,8 +1618,10 @@ async function swapToken(account) {} else {log(`[save-back] skipped: no claudeAiOauth in current main slot`);}- } else {+ } else if (!sourceAccount) {log(`[save-back] skipped: source account ${sourceKey} not found in config`);+ } else {+ log(`[save-back] skipped: automatic credential mutation not approved for ${sourceKey}`);}} else if (!sourceKey) {log(`[save-back] skipped: no active account tracked in state`);@@ -1623,7 +1642,7 @@ async function swapToken(account) {// Unconditional merge: keep all current mcpOAuth entries, only swap claudeAiOauthnewParsed.mcpOAuth = { ...newParsed.mcpOAuth, ...currentParsed.mcpOAuth };}- writeKeychain(JSON.stringify(newParsed));+ await verifiedWriteCredential(account, JSON.stringify(newParsed), KEYCHAIN_SERVICE, ACTIVE_KEYCHAIN_ACCOUNT);log('[primary] Wrote token (mcpOAuth merged from current session)');return true;} catch {}@@ -1642,29 +1661,29 @@ async function swapToken(account) {log('[primary] mcpOAuth preserved via fallback merge');}} catch {}- writeKeychain(outToken);+ await verifiedWriteCredential(account, outToken, KEYCHAIN_SERVICE, ACTIVE_KEYCHAIN_ACCOUNT);return true;}// Save current active token back to the account's vault entry// Strips mcpOAuth so vault tokens are clean (mcpOAuth merged at swap time)-function saveCurrentToken(account) {+async function saveCurrentToken(account) {try {const token = readKeychain();if (token.includes('claudeAiOauth')) {// Store only claudeAiOauth, not mcpOAuth (that's session-specific)+ let clean = token;try {const parsed = JSON.parse(token);- const clean = { claudeAiOauth: parsed.claudeAiOauth, mcpOAuth: {} };- writeStoredToken(account, JSON.stringify(clean));- } catch {- writeStoredToken(account, token);- }+ clean = JSON.stringify({ claudeAiOauth: parsed.claudeAiOauth, mcpOAuth: {} });+ } catch {}+ await writeStoredToken(account, clean);log(`Saved token to vault: ${tokenService(account)}`);return true;}} catch (e) {log(`Save token failed: ${e.message}`);+ if (String(e.message || e).startsWith('TOKEN_IDENTITY_')) throw e;}return false;}@@ -3575,6 +3594,18 @@ async function browserOAuthFallback(account) {lastBrowserOAuthCliProxyVerified = false;log(`[fallback] Browser OAuth for ${account.email}...`);+ // CLIProxyAPI's login command writes directly into its live auth directory+ // before this process can verify profile identity. It cannot participate in+ // the enrollment-only staged writer, so refuse before creating a browser+ // capture helper, spawning OAuth, clearing cooldowns, or syncing replicas.+ if (existsSync(CLIPROXYAPI_BINARY) && existsSync(CLIPROXYAPI_CONFIG)) {+ lastBrowserOAuthUsedCliProxy = true;+ if (directOAuthWriterAllowed('cliproxy')) throw new Error('UNSAFE_CLIPROXY_WRITER_POLICY');+ log('[cliproxy] Direct OAuth writer disabled — use reviewed staged enrollment');+ return false;+ }+ if (!directOAuthWriterAllowed('claude-code')) throw new Error('DIRECT_OAUTH_WRITER_DISABLED');+const pid = process.pid;const capScript = join(tmpdir(), `claude-url-cap-${pid}.sh`);const urlFile = join(tmpdir(), `claude-auth-url-${pid}.txt`);@@ -3597,7 +3628,7 @@ async function browserOAuthFallback(account) {mode: 0o700,});- const useCliProxy = existsSync(CLIPROXYAPI_BINARY) && existsSync(CLIPROXYAPI_CONFIG);+ const useCliProxy = false;lastBrowserOAuthUsedCliProxy = useCliProxy;const cliproxyBefore = useCliProxy ? cliproxyAuthSnapshot(account) : null;const spawnOAuthWriter = () =>@@ -4044,31 +4075,8 @@ async function refreshRunningSession(rotatedAccount = null, noBrowser = false) {await sleep(500); // 500ms stagger between sessions}- // If Claude relaunches trigger an OAuth browser window (token expired mid-rotation),- // reuse the same browser driver that handles the initial auth flow.- // Skipped in --no-browser mode (daemon) — token refresh daemon keeps tokens fresh,- // so this fallback should never be needed from automatic rotations.- if (!noBrowser) {- try {- await sleep(2000);- const driver = await getBrowserDriver(new Set()).catch(() => null);- if (driver) {- const url = await driver.currentUrl().catch(() => '');- if (url && (url.includes('oauth') || url.includes('authorize') || url.includes('claude.ai/login'))) {- log(`[session] Detected post-restart OAuth page (${url.substring(0, 60)}) — driving flow`);- if (rotatedAccount) {- const authOk = await runAuthFlow(driver, rotatedAccount);- if (authOk) await maybeScrapeBillingAfterOAuth(driver, rotatedAccount, log);- }- }- try {- await driver.close?.();- } catch {}- }- } catch (e) {- log(`[session] Post-restart browser check skipped: ${e.message.substring(0, 60)}`);- }- }+ // A restarted session that presents OAuth is intentionally left untouched.+ // This function performs only the browserless token swap above.log(`[session] Restart complete: ${reachable.length} session(s) cycled`);}@@ -4192,6 +4200,10 @@ async function rotate(targetEmail, opts = {}) {log(`Account ${targetEmail} not in config`);return false;}+ if (!automatedAuthAllowed(account)) {+ log(`Credential mutation denied for ${accountKey(account)} — reviewed staged enrollment approval required`);+ return false;+ }// Magic-link is the ONLY supported auth method for every account/path// (quickest; all login emails forward to one inbox). opts.magicLink is now// implied — we never fall through to Google OAuth.@@ -4222,7 +4234,7 @@ async function rotate(targetEmail, opts = {}) {if (opts.noBrowser) {const trackedAccount = config.accounts.find((a) => accountKey(a) === state.activeAccount);if (trackedAccount) {- if (!dryRun) saveCurrentToken(trackedAccount);+ if (!dryRun) await saveCurrentToken(trackedAccount);log(`[no-browser] Saved outgoing token for tracked ${accountKey(trackedAccount)}`);} else {log(`[no-browser] No tracked active account — skipping outgoing save`);@@ -4274,7 +4286,7 @@ async function rotate(targetEmail, opts = {}) {liveAccount = config.accounts.find((a) => a.email === liveEmail);}if (liveAccount) {- if (!dryRun) saveCurrentToken(liveAccount);+ if (!dryRun) await saveCurrentToken(liveAccount);log(`${dryRun ? '[DRY-RUN] Would save' : 'Saved'} outgoing token for LIVE account ${accountKey(liveAccount)} (was tracked as ${state.activeAccount || 'none'})`,);@@ -4327,11 +4339,7 @@ async function rotate(targetEmail, opts = {}) {ok = true;} else {ok = await swapToken(account);- if (!ok && !opts.noBrowser) {- ok = await browserOAuthFallback(account);- } else if (!ok) {- log('[no-browser] Token swap failed — skipping browser fallback (daemon mode)');- }+ if (!ok) log('[rotation] Token swap failed — browser authentication is disabled; use staged enrollment');}if (!ok) {@@ -4426,7 +4434,7 @@ async function rotate(targetEmail, opts = {}) {// Save verified (and possibly refreshed) token to the legacy vault only when// the legacy keychain was the OAuth writer.- if (verified && !dryRun && !lastBrowserOAuthUsedCliProxy) saveCurrentToken(account);+ if (verified && !dryRun && !lastBrowserOAuthUsedCliProxy) await saveCurrentToken(account);if (verified && dryRun && !lastBrowserOAuthUsedCliProxy) log('[DRY-RUN] Would save verified token to vault');// Update state — track cumulative window usage per account@@ -4660,7 +4668,7 @@ async function setup() {} catch {}}- if (magicLinkMode && account.autoAuthDisabled === true && !filter) {+ if (magicLinkMode && !automatedAuthAllowed(account)) {console.log(`⏭ Skipped: automated reauth disabled (${account.autoAuthDisabledReason || 'manual reauth required'}).`,);@@ -4754,9 +4762,9 @@ async function setup() {try {const parsed = JSON.parse(token);const clean = { claudeAiOauth: parsed.claudeAiOauth, mcpOAuth: {} };- writeStoredToken(account, JSON.stringify(clean));+ await writeStoredToken(account, JSON.stringify(clean));} catch {- writeStoredToken(account, token);+ await writeStoredToken(account, token);}console.log(`✅ Saved to vault: ${tokenService(account)}`);results.push({ key, ok: true });@@ -4906,7 +4914,7 @@ async function showStatus() {// ── --capture: print current token for Dashlane ───────────────────────────────-function captureCmd(targetEmail = null) {+async function captureCmd(targetEmail = null) {const state = readState();const config = readConfig();let account;@@ -4933,7 +4941,7 @@ function captureCmd(targetEmail = null) {console.error('No valid OAuth token in active keychain');process.exit(1);}- writeStoredToken(account, token);+ await writeStoredToken(account, token);console.log(`✓ Token captured and saved to keychain: ${tokenService(account)}`);console.log(` Account: ${account.email}${account.label ? ' [' + account.label + ']' : ''}`);} catch (e) {@@ -4946,8 +4954,11 @@ function captureCmd(targetEmail = null) {const args = process.argv.slice(2);-if (args.includes('--setup')) {- await setup();+if (args.includes('--magic-link') || args.includes('--setup')) {+ console.error(+ 'Direct Claude browser/magic-link authentication is disabled. Use staged-enrollment.mjs with separate stage and activate approvals.',+ );+ process.exit(2);} else if (args.includes('--utilization')) {// Live utilization query for all accountsconst config = readConfig();@@ -5132,7 +5143,7 @@ if (args.includes('--setup')) {} else if (args.includes('--capture')) {const capToIdx = args.indexOf('--to');const captureTo = capToIdx !== -1 && args[capToIdx + 1] ? args[capToIdx + 1] : null;- captureCmd(captureTo);+ await captureCmd(captureTo);} else if (args.includes('--pin-browser-active')) {// Resolve the currently-active rotating account from state.json and delegate// to --pin-browser. This is what the PreToolUse hook calls so the chrome@@ -5181,75 +5192,79 @@ if (args.includes('--setup')) {const ttlIdx = args.indexOf('--ttl');const ttlSec = ttlIdx !== -1 && args[ttlIdx + 1] ? parseInt(args[ttlIdx + 1], 10) : 300;try {- const cfg = readConfig();- const acct = cfg.accounts.find((a) => (a.email || '').toLowerCase() === (pinEmail || '').toLowerCase());- if (!acct) {- log(`[pin-browser] no account matching ${pinEmail} — writing pin sentinel only`);- } else if (acquireLock()) {- try {- const swapped = await swapToken(acct);- if (swapped) {- const st = readState();- st.activeAccount = accountKey(acct);- writeState(st);- log(`[pin-browser] CLI pinned to ${accountKey(acct)}`);- } else {- log(- `[pin-browser] swapToken false for ${accountKey(acct)} (vault token missing/expired) — likely already active; pinning anyway`,- );- }- // Sync .claude.json oauthAccount/chromeExtension blocks to match.- const targetKey = accountKey(acct);- const snapshot = loadOauthSnapshot(targetKey) || loadOauthSnapshot(acct.email);- const cj = readClaudeJson();- const currentEmail = cj?.oauthAccount?.emailAddress?.toLowerCase() || null;- const wantEmail = (acct.email || '').toLowerCase();- if (currentEmail === wantEmail) {- // Already in sync — opportunistically capture as snapshot baseline if missing.- if (!snapshot) {- captureOauthSnapshot(acct.email);- }- log(`[pin-browser] .claude.json oauthAccount already=${currentEmail} — no swap needed`);- } else if (snapshot) {- // Back up the outgoing blocks once per pin window (don't clobber existing backup).- if (!existsSync(BROWSER_PIN_BACKUP_PATH)) backupCurrentOauthBlocks();- const applied = applyOauthSnapshotToClaudeJson(snapshot);- if (applied) {+ await withAuthWriterLock(async () => {+ const cfg = readConfig();+ const acct = cfg.accounts.find((a) => (a.email || '').toLowerCase() === (pinEmail || '').toLowerCase());+ if (!acct) {+ log(`[pin-browser] no account matching ${pinEmail} — denied without filesystem mutation`);+ return;+ } else if (!automatedAuthAllowed(acct)) {+ log(`[pin-browser] credential mutation denied for ${accountKey(acct)}`);+ return;+ } else if (acquireLock()) {+ try {+ const swapped = await swapToken(acct);+ if (swapped) {+ const st = readState();+ st.activeAccount = accountKey(acct);+ writeState(st);+ log(`[pin-browser] CLI pinned to ${accountKey(acct)}`);+ } else {log(- `[pin-browser] .claude.json oauthAccount swapped ${currentEmail || 'unknown'} → ${wantEmail}. Restart Claude Code session to apply (chrome bridge reads on startup).`,+ `[pin-browser] swapToken false for ${accountKey(acct)} (vault token missing/expired) — likely already active; pinning anyway`,);- } else {- log(`[pin-browser] snapshot found but apply failed for ${wantEmail}`);}- // Ensure the matching Chrome profile is running so its extension- // service worker is alive and can authenticate against the swapped- // pairedDeviceId. No-op if already running.- const profileDir = snapshot.chromeProfileDir || chromeProfileDirFor(targetKey);- if (profileDir && !isChromeProfileRunning(profileDir)) {- // Navigate to claude.ai/chrome to wake the extension service- // worker — it only establishes the native-messaging bridge to- // Claude Code when this page loads. Without it, the extension- // is installed but dormant and the bridge reports "not connected".- launchChromeProfile(profileDir, 'https://claude.ai/chrome');- log(`[pin-browser] launched Chrome profile ${profileDir} for ${wantEmail} (@ claude.ai/chrome)`);+ // Sync .claude.json oauthAccount/chromeExtension blocks to match.+ const targetKey = accountKey(acct);+ const snapshot = loadOauthSnapshot(targetKey) || loadOauthSnapshot(acct.email);+ const cj = readClaudeJson();+ const currentEmail = cj?.oauthAccount?.emailAddress?.toLowerCase() || null;+ const wantEmail = (acct.email || '').toLowerCase();+ if (currentEmail === wantEmail) {+ // Already in sync — opportunistically capture as snapshot baseline if missing.+ if (!snapshot) {+ captureOauthSnapshot(acct.email);+ }+ log(`[pin-browser] .claude.json oauthAccount already=${currentEmail} — no swap needed`);+ } else if (snapshot) {+ const transaction = applyOauthSnapshotTransaction(snapshot);+ if (transaction.applied) {+ log(+ `[pin-browser] .claude.json oauthAccount swapped ${currentEmail || 'unknown'} → ${wantEmail}. Restart Claude Code session to apply (chrome bridge reads on startup).`,+ );+ } else {+ log(`[pin-browser] snapshot found but apply failed for ${wantEmail}`);+ }+ // Ensure the matching Chrome profile is running so its extension+ // service worker is alive and can authenticate against the swapped+ // pairedDeviceId. No-op if already running.+ const profileDir = snapshot.chromeProfileDir || chromeProfileDirFor(targetKey);+ if (profileDir && !isChromeProfileRunning(profileDir)) {+ // Navigate to claude.ai/chrome to wake the extension service+ // worker — it only establishes the native-messaging bridge to+ // Claude Code when this page loads. Without it, the extension+ // is installed but dormant and the bridge reports "not connected".+ launchChromeProfile(profileDir, 'https://claude.ai/chrome');+ log(`[pin-browser] launched Chrome profile ${profileDir} for ${wantEmail} (@ claude.ai/chrome)`);+ }+ } else {+ log(+ `[pin-browser] WARNING: no oauth-snapshot for ${targetKey}. Chrome bridge will fail until you: (1) restart Claude Code while keychain is on ${wantEmail}, (2) run: node ${join(__dirname, 'rotate.mjs')} --capture-oauth-snapshot ${wantEmail}`,+ );}- } else {- log(- `[pin-browser] WARNING: no oauth-snapshot for ${targetKey}. Chrome bridge will fail until you: (1) restart Claude Code while keychain is on ${wantEmail}, (2) run: node ${join(__dirname, 'rotate.mjs')} --capture-oauth-snapshot ${wantEmail}`,- );+ } finally {+ releaseLock();}- } finally {- releaseLock();+ } else {+ log('[pin-browser] rotation lock busy — skipping swap, still writing pin sentinel');}- } else {- log('[pin-browser] rotation lock busy — skipping swap, still writing pin sentinel');- }- // Always (re)write the freeze sentinel so the daemon won't rotate away while- // the browser bridge is in use. The hook refreshes this on every tool call.- writeFileSync(- BROWSER_PIN_PATH,- JSON.stringify({ email: pinEmail, until: Date.now() + ttlSec * 1000, ts: Date.now() }),- );+ // Always (re)write the freeze sentinel so the daemon won't rotate away while+ // the browser bridge is in use. The hook refreshes this on every tool call.+ writeFileSync(+ BROWSER_PIN_PATH,+ JSON.stringify({ email: pinEmail, until: Date.now() + ttlSec * 1000, ts: Date.now() }),+ );+ });} catch (e) {log(`[pin-browser] error (non-fatal): ${(e.message || e).toString().slice(0, 120)}`);}@@ -5259,14 +5274,13 @@ if (args.includes('--setup')) {// the daemon once the .browser-pin sentinel's TTL expires. Idempotent: if no// backup exists, exits 0 silently.try {- if (existsSync(BROWSER_PIN_BACKUP_PATH)) {- restoreOauthBlocksFromBackup();- }- if (existsSync(BROWSER_PIN_PATH)) {- try {- unlinkSync(BROWSER_PIN_PATH);- } catch {}- }+ await withAuthWriterLock(async () => {+ let safeToRelease = true;+ if (existsSync(BROWSER_PIN_RECOVERY_PATH)) {+ safeToRelease = restoreOauthBlocksFromBackup();+ }+ if (safeToRelease && existsSync(BROWSER_PIN_PATH)) unlinkSync(BROWSER_PIN_PATH);+ });} catch (e) {log(`[release-browser-pin] error (non-fatal): ${(e.message || e).toString().slice(0, 120)}`);}@@ -5597,21 +5611,24 @@ if (args.includes('--setup')) {console.error('Rotation in progress.');process.exit(1);}+ let exitCode = 1;try {- const ok = await rotate(target, {- session,- noBrowser,- dryRun,- magicLink,- allowExhausted,- bedrockOnExhausted,- });- process.exit(ok ? 0 : 1);+ const runRotation = () =>+ rotate(target, {+ session,+ noBrowser,+ dryRun,+ magicLink,+ allowExhausted,+ bedrockOnExhausted,+ });+ const ok = dryRun ? await runRotation() : await withAuthWriterLock(runRotation);+ exitCode = ok ? 0 : 1;} catch (err) {log(`FATAL: ${err.message}`);notify('Account Rotation', `FAILED: ${err.message}`);- process.exit(1);} finally {releaseLock();}+ process.exit(exitCode);}diff --git a/claude-ops/scripts/account-rotation/rotation-vault.mjs b/claude-ops/scripts/account-rotation/rotation-vault.mjsindex 275a71c0..faefbb9a 100644--- a/claude-ops/scripts/account-rotation/rotation-vault.mjs+++ b/claude-ops/scripts/account-rotation/rotation-vault.mjs@@ -1,7 +1,9 @@-import { readFileSync, renameSync, writeFileSync } from 'fs';+import { readFileSync } from 'fs';import { homedir } from 'os';import { join } from 'path';import { spawnSync } from 'child_process';+import { createVerifiedCredentialWriter, requireVerifiedCredentialCapability } from './verified-credential-write.mjs';+import { publishCredentialFileCas, snapshotCredentialFile } from './credential-file-publication.mjs';const FILE_PATH = process.env.CLAUDE_ROTATION_FILE_VAULT || join(homedir(), '.claude', '.credentials.json');const KEYCHAIN_ACCOUNT = process.env.CLAUDE_ROTATOR_KEYCHAIN_ACCOUNT || process.env.USER || 'claude-ops';@@ -33,11 +35,15 @@ function readFileStore() {}function writeFileToken(service, token) {- const store = readFileStore();- store[service] = parseToken(token);- const temp = `${FILE_PATH}.tmp.${process.pid}`;- writeFileSync(temp, JSON.stringify(store, null, 2), { mode: 0o600 });- renameSync(temp, FILE_PATH);+ const snapshot = snapshotCredentialFile(FILE_PATH);+ let store = {};+ try {+ store = snapshot.absent ? {} : JSON.parse(snapshot.bytes.toString('utf8'));+ } catch {+ throw new Error('ROTATION_VAULT_MALFORMED');+ }+ store[service] = token;+ publishCredentialFileCas(FILE_PATH, Buffer.from(JSON.stringify(store, null, 2)), snapshot);}function readKeychainToken(service) {@@ -56,7 +62,7 @@ function writeKeychainToken(service, token) {if (process.platform !== 'darwin') return;const result = spawnSync('security',- ['add-generic-password', '-U', '-s', service, '-a', KEYCHAIN_ACCOUNT, '-w', JSON.stringify(parseToken(token))],+ ['add-generic-password', '-U', '-s', service, '-a', KEYCHAIN_ACCOUNT, '-w', token],{ timeout: 5000, encoding: 'utf8', stdio: ['ignore', 'ignore', 'pipe'] },);if (result.status !== 0) {@@ -68,6 +74,13 @@ function writeKeychainToken(service, token) {}export function readRotationToken(key, { heal = true } = {}) {+ // Reads are deliberately side-effect free. Identity verification is async,+ // so a synchronous read must never "heal" a higher-expiry unbound value.+ void heal;+ return readRotationTokenInternal(key, false);+}++function readRotationTokenInternal(key, heal) {const service = rotationService(key);const fileToken = parseToken(readFileStore()[service]);const keychainToken = readKeychainToken(service);@@ -84,77 +97,43 @@ export function readRotationToken(key, { heal = true } = {}) {return serialized;}-export function writeRotationToken(key, token) {+function writeRotationTokenVerified(account, token, verifiedCapability) {+ const key = account.label || account.email;const parsed = parseToken(token);if (!parsed?.claudeAiOauth?.accessToken) throw new Error(`Invalid rotation token for ${key}`);const service = rotationService(key);- writeFileToken(service, parsed);- writeKeychainToken(service, parsed);- return JSON.stringify(parsed);+ requireVerifiedCredentialCapability(verifiedCapability, {+ account,+ credential: token,+ destination: service,+ });+ if (process.platform === 'darwin') throw new Error('KEYCHAIN_CREDENTIAL_PUBLICATION_DISABLED');+ writeFileToken(service, token);+ return token;}-export function reconcileRemoteRotationVault({ host = process.env.CRS_SSH_HOST || 'dev-us' } = {}) {- if (process.platform !== 'darwin' || process.env.CLAUDE_ROTATION_REMOTE_VAULT_SYNC === '0') {- return { skipped: true, pulled: 0, pushed: 0 };- }- const read = spawnSync('ssh', [host, 'cat "$HOME/.claude/.credentials.json"'], {- timeout: 15_000,- encoding: 'utf8',- stdio: ['ignore', 'pipe', 'pipe'],- });- if (read.status !== 0) {- const detail = String(read.stderr || 'ssh read failed')- .split('\n')[0]- .slice(0, 160);- throw new Error(`Remote rotation vault read failed from ${host}: ${detail}`);- }+const verifiedRotationWrite = createVerifiedCredentialWriter({+ write: writeRotationTokenVerified,+ destination: (account) => rotationService(account.label || account.email),+});- let remote;- try {- remote = JSON.parse(read.stdout);- } catch {- throw new Error(`Remote rotation vault from ${host} was not valid JSON`);- }+export function writeRotationToken(account, token) {+ void account;+ void token;+ throw new Error('ROTATION_TOKEN_MUTATION_APPROVAL_REQUIRED');+}- const local = readFileStore();- const services = new Set(- [...Object.keys(local), ...Object.keys(remote)].filter((key) => key.startsWith('Claude-Rotation-')),- );- let pulled = 0;- let pushed = 0;- for (const service of services) {- const key = service.slice('Claude-Rotation-'.length);- const localToken = parseToken(readRotationToken(key, { heal: false }));- const remoteToken = parseToken(remote[service]);- if (expiry(remoteToken) > expiry(localToken)) {- writeRotationToken(key, remoteToken);- pulled++;- } else if (expiry(localToken) > expiry(remoteToken)) {- remote[service] = localToken;- pushed++;- }- }+export function writeRotationTokenCoordinated(account, token, capability) {+ void account;+ void token;+ void capability;+ throw new Error('ROTATION_TOKEN_MUTATION_APPROVAL_REQUIRED');+}- if (pushed > 0) {- const write = spawnSync(- 'ssh',- [- host,- 'umask 077; tmp="$HOME/.claude/.credentials.json.tmp.$$"; cat >"$tmp"; mv "$tmp" "$HOME/.claude/.credentials.json"',- ],- {- timeout: 15_000,- encoding: 'utf8',- input: `${JSON.stringify(remote, null, 2)}\n`,- stdio: ['pipe', 'ignore', 'pipe'],- },- );- if (write.status !== 0) {- const detail = String(write.stderr || 'ssh write failed')- .split('\n')[0]- .slice(0, 160);- throw new Error(`Remote rotation vault write failed to ${host}: ${detail}`);- }- }- return { skipped: false, pulled, pushed };+export function reconcileRemoteRotationVault({ host = process.env.CRS_SSH_HOST || 'dev-us' } = {}) {+ // A local lock cannot serialize or identity-verify a writer on another host.+ // Distributed reconciliation remains operationally fenced until the remote+ // endpoint exposes the same canonical lock + exact profile-verification API.+ void host;+ return { skipped: true, pulled: 0, pushed: 0, reason: 'REMOTE_WRITER_FENCED' };}diff --git a/claude-ops/scripts/account-rotation/setup-account.mjs b/claude-ops/scripts/account-rotation/setup-account.mjsindex 1652dfb8..90715d5d 100755--- a/claude-ops/scripts/account-rotation/setup-account.mjs+++ b/claude-ops/scripts/account-rotation/setup-account.mjs@@ -1,168 +1,3 @@#!/usr/bin/env node-// setup-account.mjs — OAuth init for a single Claude account in the rotator.-//-// Thin wrapper around the proven rotate.mjs setup flow. It:-// 1. Upserts the account into the user config (gitignored override).-// 2. Delegates the OAuth capture to `rotate.mjs --setup --only=<email>-// --auto --skip-valid`, which drives the browser-driver cascade-// (CDP-attach to a real Chrome → spawn Chrome with a real profile →-// bundled Chromium), polls Gmail for the magic link via `gog`, verifies-// the token, and writes it to the keychain under the SAME schema the-// daemon/rotator consume: service `Claude-Rotation-<key>`, account-// `$USER` (or $CLAUDE_ROTATOR_KEYCHAIN_ACCOUNT), value-// `{ "claudeAiOauth": { "accessToken": ... } }`.-//-// Why delegate instead of re-implementing the browser flow here: a freshly-// launched Playwright Chromium is blocked by claude.ai's Cloudflare Turnstile-// (the magic link is never sent), and a hand-rolled web-cookie capture writes a-// credential shape (sessionKey cookie) that NO consumer in this repo reads.-// rotate.mjs already solves both correctly — this wrapper just feeds it one-// account and reports a machine-readable result.-//-// Usage:-// node setup-account.mjs --email [email protected] [--display "Personal"] \-// [--plan max] [--account-id <slug>] [--no-headless]-//-// --gmail-poll / --no-headless are accepted for backward compatibility but are-// no-ops: rotate.mjs --auto always polls Gmail and manages its own browser.--import { spawn } from 'node:child_process';-import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';-import { dirname, join, resolve } from 'node:path';-import { fileURLToPath } from 'node:url';-import { homedir } from 'node:os';--const __dirname = dirname(fileURLToPath(import.meta.url));-const ROTATE_SCRIPT = resolve(__dirname, 'rotate.mjs');-const ROTATION_DATA_DIR =- process.env.CLAUDE_PLUGIN_DATA_DIR || join(homedir(), '.claude', 'plugins', 'data', 'ops-ops-marketplace');-const CONFIG_USER = join(ROTATION_DATA_DIR, 'account-rotation-config.json');-const CONFIG_REPO = resolve(__dirname, 'config.json');-const LOG_DIR = join(homedir(), '.claude', 'logs', 'account-rotation');--function parseArgs(argv) {- const out = { plan: 'max' };- for (let i = 2; i < argv.length; i++) {- const a = argv[i];- if (a === '--email') out.email = argv[++i];- else if (a === '--display') out.display = argv[++i];- else if (a === '--plan') out.plan = argv[++i];- else if (a === '--account-id') out.accountId = argv[++i];- else if (a === '--label') out.label = argv[++i];- else if (a === '--no-headless' || a === '--gmail-poll') {- /* accepted for backward compat — no-op (rotate.mjs --auto handles both) */- } else if (a === '--help' || a === '-h') {- console.log(- 'usage: setup-account.mjs --email <addr> [--display <name>] [--plan pro|max] [--account-id <slug>] [--label <key>]',- );- process.exit(0);- }- }- if (!out.email) {- console.error('error: --email is required');- process.exit(2);- }- if (!out.accountId) out.accountId = slugify(out.email);- if (!out.display) out.display = out.email;- return out;-}--function slugify(s) {- return s- .toLowerCase()- .replace(/[^a-z0-9]+/g, '-')- .replace(/^-+|-+$/g, '');-}--function log(msg) {- const ts = new Date().toISOString();- process.stderr.write(`[setup-account ${ts}] ${msg}\n`);-}--function ensureLogDir() {- if (!existsSync(LOG_DIR)) mkdirSync(LOG_DIR, { recursive: true });-}--function loadConfig() {- const path = existsSync(CONFIG_USER) ? CONFIG_USER : CONFIG_REPO;- if (!existsSync(path)) return { accounts: [] };- try {- return JSON.parse(readFileSync(path, 'utf8'));- } catch {- return { accounts: [] };- }-}--function saveConfig(cfg) {- mkdirSync(dirname(CONFIG_USER), { recursive: true });- writeFileSync(CONFIG_USER, JSON.stringify(cfg, null, 2));-}--// Write the account into the user-override config (never the committed repo-// default — Rule 0). rotate.mjs reads this same file via its USER_CONFIG_PATH-// preference, so the --only=<email> filter below will find it.-function upsertAccount(args) {- const cfg = loadConfig();- cfg.accounts = cfg.accounts || [];- const existing = cfg.accounts.find((a) => a.id === args.accountId || a.email === args.email);- if (existing) {- existing.email = args.email;- existing.display = args.display;- existing.plan = args.plan;- if (args.label) existing.label = args.label;- } else {- const acct = {- id: args.accountId,- email: args.email,- display: args.display,- plan: args.plan,- added: new Date().toISOString(),- };- if (args.label) acct.label = args.label;- cfg.accounts.push(acct);- }- saveConfig(cfg);- log(`config upserted: ${args.accountId} (${args.email}) -> ${CONFIG_USER}`);-}--// Delegate the actual OAuth capture to rotate.mjs's proven setup flow.-// --skip-valid: no-op if a valid token already exists for this account.-// --auto: fully automated (browser cascade + Gmail magic-link polling).-function runRotateSetup(email) {- return new Promise((resolveExit) => {- log(`delegating OAuth to rotate.mjs --setup --only=${email} --auto --skip-valid`);- const child = spawn(process.execPath, [ROTATE_SCRIPT, '--setup', `--only=${email}`, '--auto', '--skip-valid'], {- // Child progress must not land on stdout — callers parse a single JSON line there.- stdio: ['ignore', process.stderr, 'inherit'],- });- child.on('exit', (code) => resolveExit(code ?? 1));- child.on('error', (e) => {- log(`failed to spawn rotate.mjs: ${e.message}`);- resolveExit(1);- });- });-}--async function main() {- const args = parseArgs(process.argv);- ensureLogDir();- log(`starting setup for ${args.email} (id=${args.accountId}, plan=${args.plan})`);-- // Persist the account first so rotate.mjs's config read picks it up.- upsertAccount(args);-- const code = await runRotateSetup(args.email);- if (code !== 0) {- console.log(JSON.stringify({ ok: false, accountId: args.accountId, email: args.email, error: 'oauth_failed' }));- process.exit(1);- }-- log(`✓ ${args.accountId} initialized (token written to Claude-Rotation-<key> by rotate.mjs)`);- console.log(JSON.stringify({ ok: true, accountId: args.accountId, email: args.email }));-}--main().catch((e) => {- log(`fatal: ${e.stack || e.message}`);- console.log(JSON.stringify({ ok: false, error: String(e.message || e) }));- process.exit(1);-});+process.stderr.write('direct account setup refused: staged enrollment is required\n');+process.exitCode = 2;diff --git a/claude-ops/scripts/account-rotation/staged-enrollment.mjs b/claude-ops/scripts/account-rotation/staged-enrollment.mjsnew file mode 100644index 00000000..553cea09--- /dev/null+++ b/claude-ops/scripts/account-rotation/staged-enrollment.mjs@@ -0,0 +1,2647 @@+#!/usr/bin/env node+/** Fail-closed, offline staging and activation for Claude CLIProxyAPI auth files. */+import {+ closeSync,+ constants,+ existsSync,+ fstatSync,+ fsyncSync,+ linkSync,+ lstatSync,+ openSync,+ readFileSync,+ realpathSync,+ readdirSync,+ renameSync,+ rmSync,+ statSync,+ unlinkSync,+ writeFileSync,+} from 'node:fs';+import { createHash, createHmac, randomUUID, timingSafeEqual } from 'node:crypto';+import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';+import { hostname } from 'node:os';+import { parseStrictJson } from './strict-json.mjs';++export const APPROVAL_VERSION = 1;+export const DEFAULT_MAX_TTL_MS = 15 * 60 * 1000;+const PROVIDER_COUNTS = { claude: 9, antigravity: 1, codex: 2, xai: 3 };+const CONFIG_KEYS = [+ 'manifestPath',+ 'approvalKeyPath',+ 'usageDir',+ 'stagingDir',+ 'activeDir',+ 'quarantineDirs',+ 'rollbackDir',+ 'operationLockPath',+ 'environment',+ 'authorizedOperator',+ 'maxApprovalTtlMs',+ 'runtimeInventoryPath',+ 'runtimeInventoryDigest',+ 'authoritativeConsumerInventoryPath',+ 'authoritativeConsumerInventoryDigest',+ 'deploymentPlanDigest',+];+const APPROVAL_KEYS = [+ 'version',+ 'id',+ 'nonce',+ 'action',+ 'manifestDigest',+ 'manifestEntryId',+ 'provider',+ 'email',+ 'organizationUuid',+ 'organizationName',+ 'accountOwner',+ 'authorizedOperator',+ 'environment',+ 'issuedAt',+ 'expiresAt',+ 'candidateDigest',+ 'oldTargetDigest',+ 'inventoryDigest',+ 'canaryDigest',+ 'destination',+];+const INVENTORY_KEYS = ['version', 'credential', 'consumers'];+const INVENTORY_CREDENTIAL_KEYS = [+ 'id',+ 'provider',+ 'email',+ 'organizationUuid',+ 'organizationName',+ 'accountOwner',+ 'destination',+];+const INVENTORY_CONSUMER_KEYS = ['id', 'type', 'path'];+const CANARY_KEYS = ['version', 'results'];+const CANARY_RESULT_KEYS = [+ 'consumerId',+ 'consumerPath',+ 'credentialId',+ 'candidateDigest',+ 'destination',+ 'noFallback',+ 'pass',+];+const AUTHORITATIVE_CONSUMER_KEYS = ['version', 'consumers'];+const AUTHORITATIVE_CONSUMER_ENTRY_KEYS = ['id', 'type', 'path', 'credentialId', 'destination'];+const CLAUDE_ENTRY_KEYS = [+ 'id',+ 'authFilename',+ 'provider',+ 'email',+ 'organizationUuid',+ 'organizationName',+ 'accountOwner',+];+const CANDIDATE_KEYS = [+ 'access_token',+ 'account_uuid',+ 'claude_device_ids',+ 'disabled',+ 'email',+ 'expired',+ 'expires_in',+ 'id_token',+ 'last_refresh',+ 'organization_name',+ 'organization_uuid',+ 'refresh_token',+ 'type',+];++export function canonicalJson(value, depth = 0) {+ if (depth > 64) throw new Error('UNSAFE_CANONICAL_JSON');+ if (Array.isArray(value)) {+ if (Object.getPrototypeOf(value) !== Array.prototype || Object.getOwnPropertySymbols(value).length)+ throw new Error('UNSAFE_CANONICAL_JSON');+ const descriptors = Object.getOwnPropertyDescriptors(value);+ const own = Object.keys(descriptors);+ const expected = [...Array(value.length).keys()].map(String).concat('length');+ if (own.length !== expected.length || own.some((key, index) => key !== expected[index]))+ throw new Error('UNSAFE_CANONICAL_JSON');+ if (+ expected.some((key) =>+ key === 'length'+ ? 'get' in descriptors[key] || 'set' in descriptors[key] || descriptors[key].enumerable+ : 'get' in descriptors[key] || 'set' in descriptors[key] || !descriptors[key].enumerable,+ )+ )+ throw new Error('UNSAFE_CANONICAL_JSON');+ return `[${expected+ .slice(0, -1)+ .map((key) => canonicalJson(descriptors[key].value, depth + 1))+ .join(',')}]`;+ }+ if (value && typeof value === 'object') {+ const prototype = Object.getPrototypeOf(value);+ if (prototype !== null && prototype !== Object.prototype) throw new Error('UNSAFE_CANONICAL_JSON');+ if (Object.getOwnPropertySymbols(value).length) throw new Error('UNSAFE_CANONICAL_JSON');+ const descriptors = Object.getOwnPropertyDescriptors(value);+ const keys = Object.keys(descriptors);+ if (keys.some((key) => 'get' in descriptors[key] || 'set' in descriptors[key] || !descriptors[key].enumerable))+ throw new Error('UNSAFE_CANONICAL_JSON');+ if (keys.some((key) => ['__proto__', 'constructor', 'prototype'].includes(key)))+ throw new Error('UNSAFE_CANONICAL_JSON');+ return `{${keys+ .sort()+ .map((key) => `${JSON.stringify(key)}:${canonicalJson(descriptors[key].value, depth + 1)}`)+ .join(',')}}`;+ }+ if (+ value === undefined ||+ typeof value === 'function' ||+ typeof value === 'symbol' ||+ typeof value === 'bigint' ||+ (typeof value === 'number' &&+ (!Number.isFinite(value) || Object.is(value, -0) || (Number.isInteger(value) && !Number.isSafeInteger(value))))+ )+ throw new Error('UNSAFE_CANONICAL_JSON');+ return JSON.stringify(value);+}++export function sha256(data) {+ return createHash('sha256').update(data).digest('hex');+}++function exactKeys(value, keys) {+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('INVALID_SCHEMA');+ const actual = Object.keys(value).sort();+ const expected = [...keys].sort();+ if (actual.length !== expected.length || actual.some((key, index) => key !== expected[index])) {+ throw new Error('INVALID_SCHEMA');+ }+}++function nonempty(value) {+ if (typeof value !== 'string' || !value.trim() || value !== value.trim() || /[\0\r\n]/.test(value)) {+ throw new Error('INVALID_VALUE');+ }+ return value;+}++export function normalizeEmail(value) {+ const email = nonempty(value).toLowerCase();+ if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) throw new Error('INVALID_EMAIL');+ return email;+}++function safeFilename(value) {+ nonempty(value);+ if (basename(value) !== value || !/^[A-Za-z0-9][A-Za-z0-9._-]*\.json$/.test(value))+ throw new Error('INVALID_FILENAME');+ return value;+}++function identityKey(value) {+ return `${normalizeEmail(value.email)}\0${nonempty(value.organizationUuid || value.organization_uuid)}\0${nonempty(value.organizationName || value.organization_name)}`;+}++export function parseManifestBytes(bytes) {+ let manifest;+ try {+ manifest = parseStrictJson(bytes, 'INVALID_MANIFEST');+ } catch {+ throw new Error('INVALID_MANIFEST');+ }+ exactKeys(manifest, ['version', 'entries']);+ const expectedCount = Object.values(PROVIDER_COUNTS).reduce((sum, count) => sum + count, 0);+ if (manifest.version !== 1 || !Array.isArray(manifest.entries) || manifest.entries.length !== expectedCount) {+ throw new Error('INVALID_MANIFEST');+ }+ const ids = new Set();+ const files = new Set();+ const identities = new Set();+ const counts = { claude: 0, antigravity: 0, codex: 0, xai: 0 };+ for (const entry of manifest.entries) {+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) throw new Error('INVALID_MANIFEST');+ nonempty(entry.id);+ safeFilename(entry.authFilename);+ if (!Object.hasOwn(counts, entry.provider)) throw new Error('INVALID_PROVIDER');+ if (!entry.authFilename.startsWith(`${entry.provider}-`)) throw new Error('PROVIDER_FILENAME_MISMATCH');+ if (ids.has(entry.id) || files.has(entry.authFilename)) throw new Error('DUPLICATE_MANIFEST_BINDING');+ ids.add(entry.id);+ files.add(entry.authFilename);+ counts[entry.provider] += 1;+ if (entry.provider === 'claude') {+ exactKeys(entry, CLAUDE_ENTRY_KEYS);+ if (entry.email !== normalizeEmail(entry.email)) throw new Error('INVALID_EMAIL');+ nonempty(entry.organizationUuid);+ nonempty(entry.organizationName);+ nonempty(entry.accountOwner);+ const identity = identityKey(entry);+ if (identities.has(identity)) throw new Error('DUPLICATE_CLAUDE_IDENTITY');+ identities.add(identity);+ }+ }+ if (Object.keys(counts).some((provider) => counts[provider] !== PROVIDER_COUNTS[provider])) {+ throw new Error('INVALID_PROVIDER_COUNTS');+ }+ return { manifest, digest: sha256(bytes) };+}++export function readManifest(path) {+ assertCanonicalExisting(path);+ assertOwnerOnly(path, 'file');+ return parseManifestBytes(secureRead(path));+}++function structurallySafe(value, depth = 0) {+ if (depth > 4 || value === null) return false;+ if (typeof value === 'string') return value.length <= 4096 && !/[\0\r\n]/.test(value);+ if (typeof value === 'number') return Number.isFinite(value);+ if (typeof value === 'boolean') return true;+ if (Array.isArray(value)) return value.length <= 64 && value.every((item) => structurallySafe(item, depth + 1));+ if (typeof value === 'object') {+ const entries = Object.entries(value);+ return (+ entries.length <= 64 &&+ entries.every(([key, item]) => /^[A-Za-z0-9_.-]{1,128}$/.test(key) && structurallySafe(item, depth + 1))+ );+ }+ return false;+}++export function validateCandidateBytes(bytes, entry, now = Date.now()) {+ let candidate;+ try {+ candidate = parseStrictJson(bytes, 'INVALID_CANDIDATE');+ } catch {+ throw new Error('INVALID_CANDIDATE');+ }+ exactKeys(candidate, CANDIDATE_KEYS);+ if (candidate.type !== 'claude' || candidate.disabled !== false) throw new Error('INVALID_CANDIDATE');+ if (candidate.email !== normalizeEmail(candidate.email) || candidate.email !== entry.email)+ throw new Error('IDENTITY_MISMATCH');+ if (nonempty(candidate.organization_uuid) !== entry.organizationUuid) throw new Error('IDENTITY_MISMATCH');+ if (nonempty(candidate.organization_name) !== entry.organizationName) throw new Error('IDENTITY_MISMATCH');+ for (const key of ['account_uuid', 'access_token', 'refresh_token']) nonempty(candidate[key]);+ if (typeof candidate.id_token !== 'string' || /[\0\r\n]/.test(candidate.id_token))+ throw new Error('INVALID_CANDIDATE');+ if (!Number.isSafeInteger(candidate.expires_in) || candidate.expires_in <= 0) throw new Error('INVALID_EXPIRY');+ const expired = parseRfc3339(candidate.expired);+ const lastRefresh = parseRfc3339(candidate.last_refresh);+ if (expired === null || expired <= now) {+ throw new Error('INVALID_EXPIRY');+ }+ if (+ lastRefresh === null ||+ !Array.isArray(candidate.claude_device_ids) ||+ candidate.claude_device_ids.length !== 1 ||+ !/^[a-f0-9]{64}$/.test(candidate.claude_device_ids[0])+ ) {+ throw new Error('INVALID_CANDIDATE');+ }+ return { candidate, digest: sha256(bytes) };+}++function parseRfc3339(value) {+ if (typeof value !== 'string') return null;+ const match = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(Z|([+-])(\d{2}):(\d{2}))$/.exec(value);+ if (!match) return null;+ const [+ ,+ yearText,+ monthText,+ dayText,+ hourText,+ minuteText,+ secondText,+ fraction = '',+ zone,+ sign,+ offsetHourText,+ offsetMinuteText,+ ] = match;+ const [year, month, day, hour, minute, second] = [yearText, monthText, dayText, hourText, minuteText, secondText].map(+ Number,+ );+ const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);+ const days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];+ if (+ year === 0 ||+ month < 1 ||+ month > 12 ||+ day < 1 ||+ day > days[month - 1] ||+ hour > 23 ||+ minute > 59 ||+ second > 59+ )+ return null;+ let offsetMinutes = 0;+ if (zone !== 'Z') {+ const offsetHour = Number(offsetHourText);+ const offsetMinute = Number(offsetMinuteText);+ if (offsetHour > 23 || offsetMinute > 59) return null;+ offsetMinutes = (offsetHour * 60 + offsetMinute) * (sign === '+' ? 1 : -1);+ }+ const milliseconds = Number(`0.${fraction || '0'}`) * 1000;+ const date = new Date(0);+ date.setUTCFullYear(year, month - 1, day);+ date.setUTCHours(hour, minute, second, milliseconds);+ const timestamp = date.getTime() - offsetMinutes * 60_000;+ return Number.isFinite(timestamp) ? timestamp : null;+}++function assertOwnerOnly(path, kind, allowLinks = false) {+ let st;+ try {+ st = lstatSync(path);+ } catch {+ throw new Error('MISSING_TRUST_ROOT');+ }+ const rightKind = kind === 'file' ? st.isFile() : st.isDirectory();+ if (+ !rightKind ||+ st.isSymbolicLink() ||+ st.uid !== process.getuid() ||+ (st.mode & 0o077) !== 0 ||+ (kind === 'file' && !allowLinks && st.nlink !== 1)+ ) {+ throw new Error('INSECURE_TRUST_ROOT');+ }+}++function assertCanonicalExisting(path) {+ const normalized = resolve(path);+ let physical;+ try {+ physical = realpathSync(path);+ } catch {+ throw new Error('MISSING_TRUST_ROOT');+ }+ if (physical !== normalized) throw new Error('INSECURE_TRUST_ROOT');+ let ancestor = normalized;+ let immediateParent = true;+ while (ancestor !== dirname(ancestor)) {+ const st = lstatSync(ancestor);+ if (st.isSymbolicLink()) throw new Error('INSECURE_TRUST_ROOT');+ ancestor = dirname(ancestor);+ const parent = lstatSync(ancestor);+ if (parent.isSymbolicLink() || (parent.uid !== process.getuid() && parent.uid !== 0))+ throw new Error('INSECURE_TRUST_ROOT');+ if (immediateParent && (parent.uid !== process.getuid() || (parent.mode & 0o077) !== 0))+ throw new Error('INSECURE_TRUST_ROOT');+ if ((parent.mode & 0o022) !== 0 && !(parent.uid === 0 && (parent.mode & 0o1000) !== 0))+ throw new Error('INSECURE_TRUST_ROOT');+ immediateParent = false;+ }+ return physical;+}++function secureReadDescriptor(path, requireSingleLink = true) {+ let fd;+ try {+ fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW || 0));+ const st = fstatSync(fd);+ const big = fstatSync(fd, { bigint: true });+ const fst = lstatSync(path);+ if (+ !st.isFile() ||+ !fst.isFile() ||+ st.dev !== fst.dev ||+ st.ino !== fst.ino ||+ (requireSingleLink && st.nlink !== 1)+ )+ throw new Error();+ const bytes = readFileSync(fd);+ return { bytes, digest: sha256(bytes), dev: st.dev, ino: st.ino, birthtimeNs: big.birthtimeNs.toString() };+ } catch {+ throw new Error('INSECURE_TRUST_ROOT');+ } finally {+ if (fd !== undefined) closeSync(fd);+ }+}++function secureRead(path) {+ return secureReadDescriptor(path).bytes;+}++function descriptorStillCurrent(path, descriptor) {+ try {+ const current = secureReadDescriptor(path, false);+ return (+ current.dev === descriptor.dev &&+ current.ino === descriptor.ino &&+ current.digest === descriptor.digest &&+ (!descriptor.birthtimeNs || current.birthtimeNs === descriptor.birthtimeNs)+ );+ } catch {+ return false;+ }+}+function matchesDigest(path, digest, allowLinks = false) {+ try {+ return secureReadDescriptor(path, !allowLinks).digest === digest;+ } catch {+ return false;+ }+}++function assertCanonicalLeaf(path) {+ const normalized = resolve(path);+ const parent = dirname(normalized);+ if (realpathSync(parent) !== parent || join(parent, basename(normalized)) !== normalized)+ throw new Error('INSECURE_TRUST_ROOT');+ return normalized;+}++function containsPath(root, path) {+ const rel = relative(root, path);+ return (+ rel === '' ||+ (!isAbsolute(rel) && rel !== '..' && !rel.startsWith(`..${process.platform === 'win32' ? '\\' : '/'}`))+ );+}++/** Canonical role-aware path contract used by every staged-enrollment operation. */+export function validatePathTopology({+ configPath,+ config,+ approvalPath,+ candidatePath,+ entry,+ approvalId,+ computedPaths = [],+}) {+ const roots = [config.usageDir, config.stagingDir, config.activeDir, config.rollbackDir, ...config.quarantineDirs];+ const fileRoles = [+ ['config', configPath, true],+ ['manifest', config.manifestPath, true],+ ['key', config.approvalKeyPath, true],+ ['authoritative consumer inventory', config.authoritativeConsumerInventoryPath, true],+ ['approval', approvalPath, Boolean(approvalPath)],+ ['candidate', candidatePath, Boolean(candidatePath)],+ ].filter(([, path]) => path);+ const leafRoles = [+ ['lock', config.operationLockPath, dirname(config.operationLockPath)],+ ['recovery claim', `${config.operationLockPath}.recovery-claim`, dirname(config.operationLockPath)],+ ['journal', `${config.operationLockPath}.journal`, dirname(config.operationLockPath)],+ ['publication', `${config.operationLockPath}.publication`, dirname(config.operationLockPath)],+ ...(entry+ ? [+ ['staged target', join(config.stagingDir, entry.authFilename), config.stagingDir],+ ['active target', join(config.activeDir, entry.authFilename), config.activeDir, true],+ ...(approvalId+ ? [['usage marker', join(config.usageDir, `${approvalId.id}.${approvalId.nonce}.used`), config.usageDir]]+ : []),+ ]+ : []),+ ...computedPaths,+ ];+ for (const [role, path] of [...fileRoles, ...leafRoles]) {+ if (!isAbsolute(path) || resolve(path) !== path) throw new Error('INVALID_CONFIG');+ }+ for (const [, path] of fileRoles) {+ assertCanonicalExisting(path);+ assertOwnerOnly(path, 'file');+ }+ for (const [role, path, parent, allowLinks] of leafRoles) {+ if (!containsPath(parent, path) || dirname(path) !== parent) throw new Error('INVALID_CONFIG');+ assertCanonicalLeaf(path);+ if (existsSync(path)) assertOwnerOnly(path, 'file', allowLinks);+ }+ for (const root of roots) {+ if (!isAbsolute(root) || resolve(root) !== root) throw new Error('INVALID_CONFIG');+ assertCanonicalExisting(root);+ assertOwnerOnly(root, 'directory');+ }+ const physicalRoots = roots.map((path) => realpathSync(path));+ for (let i = 0; i < physicalRoots.length; i += 1)+ for (let j = i + 1; j < physicalRoots.length; j += 1)+ if (containsPath(physicalRoots[i], physicalRoots[j]) || containsPath(physicalRoots[j], physicalRoots[i]))+ throw new Error('INVALID_CONFIG');+ const lockRoot = realpathSync(dirname(config.operationLockPath));+ const trustPaths = fileRoles.map(([, path]) => realpathSync(path));+ if (+ trustPaths.some((path) => physicalRoots.some((root) => containsPath(root, path))) ||+ physicalRoots.some((root) => containsPath(root, lockRoot) || containsPath(lockRoot, root))+ )+ throw new Error('INVALID_CONFIG');+ const existing = [+ ...trustPaths.map((path) => ({ path, allowLinks: false })),+ { path: lockRoot, allowLinks: false },+ ...physicalRoots.map((path) => ({ path, allowLinks: false })),+ ...leafRoles+ .filter(([, path]) => existsSync(path))+ .map(([, path, , allowLinks]) => ({ path, allowLinks: Boolean(allowLinks) })),+ ];+ const inodeGroups = new Map();+ for (const item of existing) {+ const st = statSync(item.path);+ const key = `${st.dev}:${st.ino}`;+ inodeGroups.set(key, [...(inodeGroups.get(key) || []), item]);+ }+ if ([...inodeGroups.values()].some((items) => items.length > 1 && items.some((item) => !item.allowLinks)))+ throw new Error('INVALID_CONFIG');+ const mutationDevices = [lockRoot, ...physicalRoots].map((path) => statSync(path).dev);+ if (new Set(mutationDevices).size !== 1) throw new Error('CROSS_FILESYSTEM');+ return true;+}++function fsyncDirectory(path) {+ const fd = openSync(path, constants.O_RDONLY);+ try {+ fsyncSync(fd);+ } finally {+ closeSync(fd);+ }+}++export function signApproval(payload, key) {+ return { payload, signature: createHmac('sha256', key).update(canonicalJson(payload)).digest('hex') };+}++export function createApprovalPayload(fields, { now = Date.now(), ttlMs = DEFAULT_MAX_TTL_MS } = {}) {+ if (!Number.isFinite(ttlMs) || ttlMs <= 0 || ttlMs > DEFAULT_MAX_TTL_MS) throw new Error('INVALID_TTL');+ return {+ version: APPROVAL_VERSION,+ id: fields.id || randomUUID(),+ nonce: fields.nonce || randomUUID(),+ action:+ fields.action === 'stage'+ ? 'additive-publish'+ : fields.action === 'activate'+ ? 'canonical-switch'+ : fields.action,+ manifestDigest: fields.manifestDigest,+ manifestEntryId: fields.manifestEntryId,+ provider: 'claude',+ email: normalizeEmail(fields.email),+ organizationUuid: fields.organizationUuid,+ organizationName: fields.organizationName,+ accountOwner: fields.accountOwner,+ authorizedOperator: fields.authorizedOperator,+ environment: fields.environment,+ issuedAt: new Date(now).toISOString(),+ expiresAt: new Date(now + ttlMs).toISOString(),+ candidateDigest: fields.candidateDigest,+ oldTargetDigest: fields.oldTargetDigest ?? null,+ inventoryDigest: fields.inventoryDigest ?? null,+ canaryDigest: fields.canaryDigest ?? null,+ destination: fields.destination,+ };+}++export function verifyApproval({ artifact, keyPath, expected, now = Date.now(), maxTtlMs = DEFAULT_MAX_TTL_MS }) {+ if (!Number.isFinite(maxTtlMs) || maxTtlMs <= 0 || maxTtlMs > DEFAULT_MAX_TTL_MS) throw new Error('INVALID_TTL');+ exactKeys(artifact, ['payload', 'signature']);+ exactKeys(artifact.payload, APPROVAL_KEYS);+ const p = artifact.payload;+ if (p.version !== APPROVAL_VERSION || !['additive-publish', 'canonical-switch'].includes(p.action))+ throw new Error('INVALID_APPROVAL');+ for (const key of [+ 'id',+ 'nonce',+ 'manifestDigest',+ 'manifestEntryId',+ 'organizationUuid',+ 'organizationName',+ 'accountOwner',+ 'authorizedOperator',+ 'environment',+ ])+ nonempty(p[key]);+ if (!/^[A-Za-z0-9_-]{8,128}$/.test(p.id) || !/^[A-Za-z0-9_-]{8,128}$/.test(p.nonce))+ throw new Error('INVALID_APPROVAL');+ if (p.provider !== 'claude' || p.email !== normalizeEmail(p.email)) throw new Error('INVALID_APPROVAL');+ if (!/^[a-f0-9]{64}$/.test(p.manifestDigest)) throw new Error('INVALID_APPROVAL');+ if (!/^[a-f0-9]{64}$/.test(p.candidateDigest) || !nonempty(p.destination)) throw new Error('INVALID_APPROVAL');+ if (+ p.action === 'additive-publish' &&+ (p.oldTargetDigest !== null || p.inventoryDigest !== null || p.canaryDigest !== null)+ )+ throw new Error('INVALID_APPROVAL');+ if (+ p.action === 'canonical-switch' &&+ ((p.oldTargetDigest !== null && !/^[a-f0-9]{64}$/.test(p.oldTargetDigest)) ||+ !/^[a-f0-9]{64}$/.test(p.inventoryDigest) ||+ !/^[a-f0-9]{64}$/.test(p.canaryDigest))+ )+ throw new Error('INVALID_APPROVAL');+ const issued = parseRfc3339(p.issuedAt);+ const expires = parseRfc3339(p.expiresAt);+ if (+ issued === null ||+ expires === null ||+ issued > now ||+ expires <= now ||+ expires <= issued ||+ expires - issued > maxTtlMs+ )+ throw new Error('INVALID_APPROVAL_CLOCK');+ for (const [key, value] of Object.entries(expected))+ if (p[key] !== value) throw new Error('APPROVAL_BINDING_MISMATCH');+ assertOwnerOnly(keyPath, 'file');+ const key = secureRead(keyPath);+ if (key.length < 32) throw new Error('APPROVAL_KEY_TOO_SHORT');+ if (typeof artifact.signature !== 'string' || !/^[a-f0-9]{64}$/.test(artifact.signature))+ throw new Error('INVALID_SIGNATURE');+ const supplied = Buffer.from(artifact.signature, 'hex');+ const calculated = createHmac('sha256', key).update(canonicalJson(p)).digest();+ if (!timingSafeEqual(supplied, calculated)) throw new Error('INVALID_SIGNATURE');+ return p;+}++function validateUseMarker(path, keyPath, expected) {+ const marker = verifySignedRecord(secureRead(path), secureRead(keyPath), 'INVALID_USE_MARKER');+ exactKeys(marker, ['version', 'approvalId', 'nonce', 'action']);+ if (+ marker.version !== 1 ||+ marker.approvalId !== expected.approvalId ||+ marker.nonce !== expected.nonce ||+ marker.action !== expected.action+ )+ throw new Error('INVALID_USE_MARKER');+ return marker;+}++export function consumeApproval(payload, usageDir, keyPath) {+ assertOwnerOnly(usageDir, 'directory');+ const marker = join(usageDir, `${payload.id}.${payload.nonce}.used`);+ assertCanonicalLeaf(marker);+ if (existsSync(marker)) {+ if (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;+ 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;+ if (+ process.env.CLAUDE_STAGED_ENROLLMENT_TESTING === '1' &&+ process.env.CLAUDE_STAGED_ENROLLMENT_TEST_FAULT === 'SIGKILL:MARKER_LINK'+ )+ process.kill(process.pid, 'SIGKILL');+ if (+ process.env.CLAUDE_STAGED_ENROLLMENT_TESTING === '1' &&+ ['THROW:MARKER_AFTER_LINK', 'THROW:MARKER_CLEANUP_UNCERTAIN'].includes(+ process.env.CLAUDE_STAGED_ENROLLMENT_TEST_FAULT,+ )+ )+ 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');+ throw new Error('APPROVAL_CONSUME_FAILED');+ }+}++function publicationPath(options) {+ return `${options.operationLockPath}.publication`;+}++function removeDurably(path, expectedDescriptor) {+ if (+ path.endsWith('.publication') &&+ process.env.CLAUDE_STAGED_ENROLLMENT_TESTING === '1' &&+ 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));+}++function recoverPublication(options) {+ const path = publicationPath(options);+ if (!existsSync(path)) return false;+ const publicationDescriptor = secureReadDescriptor(path);+ const record = verifySignedRecord(+ publicationDescriptor.bytes,+ secureRead(options.keyPath),+ 'INVALID_PUBLICATION_RECORD',+ );+ exactKeys(record, [+ 'version',+ 'kind',+ 'stagedPath',+ 'stagingDigest',+ 'stagedDescriptor',+ 'stagedProof',+ 'markerPath',+ 'approvalId',+ 'approvalNonce',+ ]);+ if (record.version !== 1 || record.kind !== 'stage') throw new Error('INVALID_PUBLICATION_RECORD');+ for (const key of ['stagedPath', 'stagingDigest', 'markerPath', 'approvalId', 'approvalNonce']) nonempty(record[key]);+ exactKeys(record.stagedDescriptor, ['dev', 'ino', 'birthtimeNs', 'digest']);+ if (record.stagedDescriptor.digest !== record.stagingDigest) throw new Error('INVALID_PUBLICATION_RECORD');+ assertCanonicalLeaf(record.stagedPath);+ 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))+ throw new Error('PUBLICATION_RECOVERY_UNCERTAIN');+ removePublicationTempLink(record.markerPath);+ const markerExists = existsSync(record.markerPath);+ if (markerExists) {+ validateUseMarker(record.markerPath, options.keyPath, {+ approvalId: record.approvalId,+ nonce: record.approvalNonce,+ action: 'additive-publish',+ });+ // 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))+ 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);+ }+ if (existsSync(record.stagedProof)) {+ if (!descriptorStillCurrent(record.stagedProof, record.stagedDescriptor))+ throw new Error('PUBLICATION_RECOVERY_UNCERTAIN');+ unlinkSync(record.stagedProof);+ fsyncDirectory(options.stagingDir);+ }+ if (!markerExists) fsyncDirectory(options.usageDir);+ removeDurably(path, publicationDescriptor);+ return true;+}++function beginPublication(options, payload, stagedPath, digest, descriptor) {+ const markerPath = join(options.usageDir, `${payload.id}.${payload.nonce}.used`);+ const record = {+ version: 1,+ kind: 'stage',+ stagedPath,+ stagingDigest: digest,+ stagedDescriptor: {+ dev: descriptor.dev,+ ino: descriptor.ino,+ birthtimeNs: descriptor.birthtimeNs,+ digest: descriptor.digest,+ },+ stagedProof: descriptor.proof,+ markerPath,+ approvalId: payload.id,+ approvalNonce: payload.nonce,+ };+ durableExclusive(publicationPath(options), `${canonicalJson(signedRecord(record, secureRead(options.keyPath)))}\n`);+ const publicationDescriptor = secureReadDescriptor(publicationPath(options));+ if (+ process.env.CLAUDE_STAGED_ENROLLMENT_TESTING === '1' &&+ process.env.CLAUDE_STAGED_ENROLLMENT_TEST_FAULT === 'THROW:PUBLICATION_FIRST_DIR_FSYNC'+ )+ throw new Error('PUBLICATION_RECOVERY_REQUIRED');+ return { record, publicationDescriptor };+}++function recursiveJsonFiles(root) {+ assertOwnerOnly(root, 'directory');+ const files = [];+ const visit = (dir) => {+ for (const item of readdirSync(dir, { withFileTypes: true })) {+ const path = join(dir, item.name);+ const st = lstatSync(path);+ if (st.isSymbolicLink()) throw new Error('UNSAFE_INVENTORY');+ if (st.isDirectory()) visit(path);+ else if (item.name.endsWith('.json')) {+ if (!st.isFile()) throw new Error('UNSAFE_INVENTORY');+ files.push(path);+ }+ }+ };+ visit(root);+ return files;+}++function claudeIdentityFromInventory(value) {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;+ const indicators = [value.type, value.provider].filter((item) => item !== undefined);+ if (indicators.length === 2 && indicators[0] !== indicators[1]) throw new Error('AMBIGUOUS_INVENTORY');+ const claudeShaped =+ indicators.includes('claude') ||+ ['organization_uuid', 'organization_name', 'claude_device_ids'].some((key) => Object.hasOwn(value, key));+ if (!claudeShaped) return null;+ if (indicators.some((item) => item !== 'claude')) throw new Error('AMBIGUOUS_INVENTORY');+ try {+ return identityKey(value);+ } catch {+ throw new Error('AMBIGUOUS_INVENTORY');+ }+}++export function assertNoIdentityConflicts({ entry, activeDir, quarantineDirs, stagingDir, candidatePath }) {+ const wanted = identityKey(entry);+ let approvedQuarantine = 0;+ for (const [kind, roots] of [+ ['active', [activeDir]],+ ['quarantine', quarantineDirs],+ ['staging', [stagingDir]],+ ]) {+ for (const root of roots) {+ for (const path of recursiveJsonFiles(root)) {+ if (candidatePath && resolve(path) === resolve(candidatePath)) continue;+ let value;+ try {+ value = parseStrictJson(secureRead(path), 'MALFORMED_INVENTORY');+ } catch {+ throw new Error('MALFORMED_INVENTORY');+ }+ const identity = claudeIdentityFromInventory(value);+ if (identity !== wanted) continue;+ const exactActive = kind === 'active' && resolve(path) === resolve(join(activeDir, entry.authFilename));+ const exactQuarantine = kind === 'quarantine' && resolve(path) === resolve(join(root, entry.authFilename));+ if (exactQuarantine) approvedQuarantine += 1;+ if (!exactActive && !exactQuarantine) throw new Error('DUPLICATE_IDENTITY');+ }+ }+ }+ if (approvedQuarantine > 1) throw new Error('DUPLICATE_IDENTITY');+}++function normalizedConsumers(consumers, keys, code) {+ if (!Array.isArray(consumers) || consumers.length === 0) throw new Error(code);+ const ids = new Set();+ const paths = new Set();+ return consumers.map((consumer) => {+ exactKeys(consumer, keys);+ nonempty(consumer.id);+ nonempty(consumer.type);+ if (!isAbsolute(nonempty(consumer.path)) || resolve(consumer.path) !== consumer.path) throw new Error(code);+ if (ids.has(consumer.id) || paths.has(consumer.path)) throw new Error(code);+ ids.add(consumer.id);+ paths.add(consumer.path);+ return consumer;+ });+}++function readAuthoritativeConsumers(options, entry) {+ assertCanonicalExisting(options.authoritativeConsumerInventoryPath);+ assertOwnerOnly(options.authoritativeConsumerInventoryPath, 'file');+ const bytes = secureRead(options.authoritativeConsumerInventoryPath);+ if (sha256(bytes) !== options.authoritativeConsumerInventoryDigest)+ throw new Error('AUTHORITATIVE_INVENTORY_MISMATCH');+ try {+ const value = parseStrictJson(bytes, 'INVALID_AUTHORITATIVE_INVENTORY');+ exactKeys(value, AUTHORITATIVE_CONSUMER_KEYS);+ if (value.version !== 1) throw new Error();+ const all = normalizedConsumers(+ value.consumers,+ AUTHORITATIVE_CONSUMER_ENTRY_KEYS,+ 'INVALID_AUTHORITATIVE_INVENTORY',+ );+ const selected = all.filter((consumer) => consumer.credentialId === entry.id);+ if (!selected.length || selected.some((consumer) => consumer.destination !== entry.authFilename)) throw new Error();+ return selected.map(({ id, type, path }) => ({ id, type, path }));+ } catch {+ throw new Error('INVALID_AUTHORITATIVE_INVENTORY');+ }+}++function readSwitchEvidence(path, kind, entry, candidateDigest, authoritativeConsumers) {+ if (!isAbsolute(path)) throw new Error('ABSOLUTE_PATH_REQUIRED');+ assertCanonicalExisting(path);+ assertOwnerOnly(path, 'file');+ const descriptor = secureReadDescriptor(path);+ const bytes = descriptor.bytes;+ let value;+ try {+ value = parseStrictJson(bytes, `INVALID_${kind.toUpperCase()}`);+ if (kind === 'inventory') {+ exactKeys(value, INVENTORY_KEYS);+ exactKeys(value.credential, INVENTORY_CREDENTIAL_KEYS);+ if (value.version !== 1 || !Array.isArray(value.consumers) || value.consumers.length === 0) throw new Error();+ const consumers = normalizedConsumers(value.consumers, INVENTORY_CONSUMER_KEYS, 'INVALID_INVENTORY');+ const expected = {+ id: entry.id,+ provider: entry.provider,+ email: entry.email,+ organizationUuid: entry.organizationUuid,+ organizationName: entry.organizationName,+ accountOwner: entry.accountOwner,+ destination: entry.authFilename,+ };+ if (canonicalJson(value.credential) !== canonicalJson(expected)) throw new Error();+ if (canonicalJson(consumers) !== canonicalJson(authoritativeConsumers)) throw new Error();+ } else {+ exactKeys(value, CANARY_KEYS);+ if (value.version !== 1 || !Array.isArray(value.results)) throw new Error();+ const expected = new Map(authoritativeConsumers.map((consumer) => [consumer.id, consumer]));+ const seen = new Set();+ for (const result of value.results) {+ exactKeys(result, CANARY_RESULT_KEYS);+ const consumer = expected.get(result.consumerId);+ if (+ !consumer ||+ seen.has(result.consumerId) ||+ result.consumerPath !== consumer.path ||+ result.credentialId !== entry.id ||+ result.candidateDigest !== candidateDigest ||+ result.destination !== entry.authFilename ||+ result.noFallback !== true ||+ result.pass !== true+ )+ throw new Error();+ seen.add(result.consumerId);+ }+ if (seen.size !== expected.size) throw new Error();+ }+ } catch {+ throw new Error(`INVALID_${kind.toUpperCase()}`);+ }+ return { value, digest: sha256(bytes), descriptor, path };+}++function binding(entry, manifestDigest, action, candidateDigest, environment, operator, switchEvidence = {}) {+ return {+ action: action === 'stage' ? 'additive-publish' : 'canonical-switch',+ manifestDigest,+ manifestEntryId: entry.id,+ provider: 'claude',+ email: entry.email,+ organizationUuid: entry.organizationUuid,+ organizationName: entry.organizationName,+ accountOwner: entry.accountOwner,+ authorizedOperator: operator,+ environment,+ candidateDigest,+ oldTargetDigest: action === 'activate' ? switchEvidence.oldTargetDigest : null,+ inventoryDigest: action === 'activate' ? switchEvidence.inventoryDigest : null,+ canaryDigest: action === 'activate' ? switchEvidence.canaryDigest : null,+ destination: entry.authFilename,+ };+}++function signedRecord(payload, key) {+ return { payload, signature: createHmac('sha256', key).update(canonicalJson(payload)).digest('hex') };+}++function verifySignedRecord(bytes, key, kind) {+ const record = parseStrictJson(bytes, kind);+ exactKeys(record, ['payload', 'signature']);+ if (typeof record.signature !== 'string' || !/^[a-f0-9]{64}$/.test(record.signature)) throw new Error(kind);+ const expected = createHmac('sha256', key).update(canonicalJson(record.payload)).digest();+ if (!timingSafeEqual(Buffer.from(record.signature, 'hex'), expected)) throw new Error(kind);+ return record.payload;+}++function durableExclusive(path, bytes) {+ const fd = openSync(path, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY, 0o600);+ try {+ writeFileSync(fd, bytes);+ fsyncSync(fd);+ } finally {+ closeSync(fd);+ }+ fsyncDirectory(dirname(path));+}++function pidAlive(pid) {+ if (!Number.isSafeInteger(pid) || pid <= 0) return false;+ try {+ process.kill(pid, 0);+ return true;+ } catch (error) {+ return error?.code === 'EPERM';+ }+}++function validateProcessRecord(record, kind, { lockNonce } = {}) {+ if (+ record.version !== 1 ||+ typeof record.host !== 'string' ||+ !record.host ||+ record.host.length > 255 ||+ !Number.isSafeInteger(record.pid) ||+ record.pid <= 0 ||+ record.pid > 2_147_483_647 ||+ typeof record.nonce !== 'string' ||+ !/^[A-Za-z0-9_-]{8,128}$/.test(record.nonce) ||+ parseRfc3339(record.createdAt) === null ||+ (lockNonce !== undefined && record.lockNonce !== lockNonce)+ )+ throw new Error(kind);+ return record;+}++function acquireRecoveryClaim(claim, holder, key) {+ const claimPayload = () => ({+ version: 1,+ host: hostname(),+ pid: process.pid,+ nonce: randomUUID(),+ lockNonce: holder.nonce,+ createdAt: new Date().toISOString(),+ });+ let mine = claimPayload();+ try {+ durableExclusive(claim, `${canonicalJson(signedRecord(mine, key))}\n`);+ return mine;+ } 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');+ 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;+ // its older nonce must not permanently wedge a later dead-holder reclaim.+ validateProcessRecord(stale, 'RECOVERY_CLAIM_MALFORMED');+ 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));+ mine = claimPayload();+ durableExclusive(claim, `${canonicalJson(signedRecord(mine, key))}\n`);+ return mine;+ } catch (claimError) {+ if (claimError?.message === 'RECOVERY_CLAIM_MALFORMED') throw claimError;+ throw new Error('OPERATION_LOCKED');+ }+}++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));+}++export function withOperationLock(path, keyPath, callback, { allowJournal = false, allowPublication = false } = {}) {+ assertOwnerOnly(dirname(path), 'directory');+ assertCanonicalLeaf(path);+ const key = secureRead(keyPath);+ const journal = `${path}.journal`;+ const publication = `${path}.publication`;+ if (!allowJournal && existsSync(journal)) throw new Error('PENDING_ACTIVATION_JOURNAL');+ if (!allowPublication && existsSync(publication)) throw new Error('PENDING_APPROVAL_PUBLICATION');+ const metadata = {+ version: 1,+ host: hostname(),+ pid: process.pid,+ nonce: randomUUID(),+ createdAt: new Date().toISOString(),+ };+ try {+ durableExclusive(path, `${canonicalJson(signedRecord(metadata, key))}\n`);+ } catch (error) {+ if (error?.code !== 'EEXIST') throw new Error('OPERATION_LOCKED');+ let holder;+ try {+ assertOwnerOnly(path, 'file');+ holder = verifySignedRecord(secureRead(path), key, 'OPERATION_LOCKED_MALFORMED');+ exactKeys(holder, ['version', 'host', 'pid', 'nonce', 'createdAt']);+ validateProcessRecord(holder, 'OPERATION_LOCKED_MALFORMED');+ } catch (verifyError) {+ throw new Error(+ verifyError?.message === 'OPERATION_LOCKED_MALFORMED' ? verifyError.message : 'OPERATION_LOCKED_MALFORMED',+ );+ }+ if (holder.host !== hostname() || pidAlive(holder.pid)) throw new Error('OPERATION_LOCKED');+ const claim = `${path}.recovery-claim`;+ 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 (+ process.env.CLAUDE_STAGED_ENROLLMENT_TESTING === '1' &&+ process.env.CLAUDE_STAGED_ENROLLMENT_TEST_FAULT === 'SIGKILL:OLD_LOCK_UNLINKED'+ )+ process.kill(process.pid, 'SIGKILL');+ // Clear our claim durably before publishing. If we crash here, another+ // process can arbitrate the now-absent lock with O_EXCL instead of being+ // permanently wedged behind our dead claim.+ removeOwnedRecoveryClaim(claim, ownedClaim, key);+ claimRemoved = true;+ try {+ durableExclusive(path, `${canonicalJson(signedRecord(metadata, key))}\n`);+ } catch (publishError) {+ if (publishError?.code === 'EEXIST') throw new Error('OPERATION_LOCKED');+ throw publishError;+ }+ if (+ process.env.CLAUDE_STAGED_ENROLLMENT_TESTING === '1' &&+ process.env.CLAUDE_STAGED_ENROLLMENT_TEST_FAULT === 'SIGKILL:LOCK_REPLACEMENT_PUBLISHED'+ )+ process.kill(process.pid, 'SIGKILL');+ if (+ process.env.CLAUDE_STAGED_ENROLLMENT_TESTING === '1' &&+ process.env.CLAUDE_STAGED_ENROLLMENT_TEST_FAULT === 'SIGSTOP:LOCK_REPLACEMENT_PUBLISHED'+ )+ process.kill(process.pid, 'SIGSTOP');+ } finally {+ if (!claimRemoved) {+ try {+ removeOwnedRecoveryClaim(claim, ownedClaim, key);+ } catch {+ // Never remove a claim whose ownership can no longer be demonstrated.+ }+ }+ }+ }+ 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.+ }+ };+ // 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)) {+ release();+ throw new Error('PENDING_ACTIVATION_JOURNAL');+ }+ if (!allowPublication && existsSync(publication)) {+ release();+ throw new Error('PENDING_APPROVAL_PUBLICATION');+ }+ let result;+ try {+ result = callback({ version: 1, nonce: metadata.nonce, path });+ } catch (error) {+ release();+ throw error;+ }+ if (result && typeof result.then === 'function') return result.finally(release);+ release();+ return result;+}++function loadCommon(options) {+ validatePathTopology({+ configPath: options.configPath,+ config: {+ manifestPath: options.manifestPath,+ approvalKeyPath: options.keyPath,+ usageDir: options.usageDir,+ stagingDir: options.stagingDir,+ activeDir: options.activeDir,+ quarantineDirs: options.quarantineDirs,+ rollbackDir: options.rollbackDir,+ operationLockPath: options.operationLockPath,+ },+ approvalPath: options.approvalPath,+ candidatePath: options.candidatePath,+ });+ for (const path of [options.manifestPath, options.keyPath, options.approvalPath]) {+ assertCanonicalExisting(path);+ assertOwnerOnly(path, 'file');+ }+ for (const path of [+ options.usageDir,+ options.stagingDir,+ options.activeDir,+ ...options.quarantineDirs,+ options.rollbackDir,+ ])+ (assertCanonicalExisting(path), assertOwnerOnly(path, 'directory'));+ assertCanonicalLeaf(options.operationLockPath);+ const initial = readManifest(options.manifestPath);+ const entry = initial.manifest.entries.find((item) => item.id === options.entryId);+ if (!entry || entry.provider !== 'claude') throw new Error('ENTRY_NOT_CLAUDE');+ validatePathTopology({+ configPath: options.configPath,+ config: {+ manifestPath: options.manifestPath,+ approvalKeyPath: options.keyPath,+ usageDir: options.usageDir,+ stagingDir: options.stagingDir,+ activeDir: options.activeDir,+ quarantineDirs: options.quarantineDirs,+ rollbackDir: options.rollbackDir,+ operationLockPath: options.operationLockPath,+ },+ approvalPath: options.approvalPath,+ candidatePath: options.candidatePath,+ entry,+ });+ return { initial, entry };+}++function readArtifact(path) {+ assertOwnerOnly(path, 'file');+ try {+ return parseStrictJson(secureRead(path), 'INVALID_APPROVAL');+ } catch {+ throw new Error('INVALID_APPROVAL');+ }+}++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);+ let linked = false;+ let prepared;+ try {+ writeFileSync(fd, bytes);+ fsyncSync(fd);+ closeSync(fd);+ fd = undefined;+ fsyncDirectory(dirname(path));+ prepared = secureReadDescriptor(temp);+ onPrepared({ ...prepared, proof: temp });+ linkSync(temp, path);+ linked = true;+ if (+ process.env.CLAUDE_STAGED_ENROLLMENT_TESTING === '1' &&+ process.env.CLAUDE_STAGED_ENROLLMENT_TEST_FAULT === 'SIGKILL:STAGED_LINK'+ )+ process.kill(process.pid, 'SIGKILL');+ if (+ process.env.CLAUDE_STAGED_ENROLLMENT_TESTING === '1' &&+ process.env.CLAUDE_STAGED_ENROLLMENT_TEST_FAULT === 'THROW:STAGE_AFTER_LINK'+ )+ 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 (fd !== undefined) closeSync(fd);+ if (linked) {+ try {+ unlinkSync(path);+ fsyncDirectory(dirname(path));+ } catch {+ throw new Error('STAGE_PUBLICATION_RECOVERY_REQUIRED');+ }+ }+ if (error?.code === 'EEXIST') throw new Error('STAGE_TARGET_EXISTS');+ throw error;+ }+}++export function stageEnrollment(options) {+ if (!options?.configPath) throw new Error('CONFIG_PATH_REQUIRED');+ if (!isAbsolute(options.configPath) || !isAbsolute(options.candidatePath) || !isAbsolute(options.approvalPath))+ throw new Error('ABSOLUTE_PATH_REQUIRED');+ options = optionsFromConfig(options);+ return withOperationLock(+ options.operationLockPath,+ options.keyPath,+ () => {+ recoverPublication(options);+ const { initial, entry } = loadCommon(options);+ assertCanonicalExisting(options.candidatePath);+ assertOwnerOnly(options.candidatePath, 'file');+ const candidateBytes = secureRead(options.candidatePath);+ const { digest: candidateDigest } = validateCandidateBytes(candidateBytes, entry, options.now);+ const artifact = readArtifact(options.approvalPath);+ const payload = verifyApproval({+ artifact,+ keyPath: options.keyPath,+ expected: binding(entry, initial.digest, 'stage', candidateDigest, options.environment, options.operator),+ now: options.now,+ maxTtlMs: options.maxTtlMs,+ });+ validatePathTopology({+ configPath: options.configPath,+ config: {+ manifestPath: options.manifestPath,+ approvalKeyPath: options.keyPath,+ usageDir: options.usageDir,+ stagingDir: options.stagingDir,+ activeDir: options.activeDir,+ quarantineDirs: options.quarantineDirs,+ rollbackDir: options.rollbackDir,+ operationLockPath: options.operationLockPath,+ },+ approvalPath: options.approvalPath,+ entry,+ approvalId: payload,+ });+ assertNoIdentityConflicts({+ entry,+ activeDir: options.activeDir,+ quarantineDirs: options.quarantineDirs,+ stagingDir: options.stagingDir,+ });+ const stagedPath = join(options.stagingDir, entry.authFilename);+ assertCanonicalLeaf(stagedPath);+ let stagedDescriptor;+ let publicationDescriptor;+ publishNoReplace(stagedPath, candidateBytes, (descriptor) => {+ stagedDescriptor = descriptor;+ ({ publicationDescriptor } = beginPublication(options, payload, stagedPath, candidateDigest, descriptor));+ });+ try {+ consumeApproval(payload, options.usageDir, options.keyPath);+ } catch (error) {+ // A marker is evidence that publication succeeded. If marker publication+ // fails, remove the staged bytes durably rather than leaving false replay+ // evidence or an unauthorised staged candidate behind.+ try {+ if (!stagedDescriptor || !descriptorStillCurrent(stagedPath, stagedDescriptor)) throw new Error();+ unlinkSync(stagedPath);+ fsyncDirectory(options.stagingDir);+ } catch {+ throw new Error('PUBLICATION_RECOVERY_REQUIRED');+ }+ throw error;+ }+ removeDurably(publicationPath(options), publicationDescriptor);+ return {+ ok: true,+ action: 'stage',+ provider: 'claude',+ manifestEntryId: entry.id,+ authFilename: entry.authFilename,+ candidateDigest,+ };+ },+ { allowPublication: true },+ );+}++function replaceAndFsync(stagedPath, target, stagingDir, activeDir, injectFailure, markRenamed) {+ if (injectFailure === 'initial-rename-failure') throw new Error('INJECTED_FAILURE');+ renameSync(stagedPath, target);+ markRenamed();+ if (['after-rename-before-dir-fsync', 'rollback-fsync-failure'].includes(injectFailure))+ throw new Error('INJECTED_FAILURE');+ fsyncDirectory(stagingDir);+ if (injectFailure === 'after-source-dir-fsync') throw new Error('INJECTED_FAILURE');+ fsyncDirectory(activeDir);+}++function restoreBackup(backup, target, activeDir, _restorePath, expectedDescriptor, expectedDigest) {+ const source = secureReadDescriptor(backup, false);+ if (+ !expectedDescriptor ||+ source.dev !== expectedDescriptor.dev ||+ source.ino !== expectedDescriptor.ino ||+ source.birthtimeNs !== expectedDescriptor.birthtimeNs ||+ source.digest !== expectedDigest+ )+ throw new Error('INVALID_ACTIVATION_BACKUP');+ if (!existsSync(target)) {+ linkSync(backup, target);+ fsyncDirectory(activeDir);+ }+ const restore = secureReadDescriptor(target, false);+ if (+ restore.dev !== expectedDescriptor.dev ||+ restore.ino !== expectedDescriptor.ino ||+ restore.birthtimeNs !== expectedDescriptor.birthtimeNs ||+ restore.digest !== expectedDigest+ )+ throw new Error('INVALID_ACTIVATION_RESTORE');+ if (+ process.env.CLAUDE_STAGED_ENROLLMENT_TESTING === '1' &&+ process.env.CLAUDE_STAGED_ENROLLMENT_TEST_FAULT === 'SIGKILL:RESTORE_TEMP_FSYNCED'+ )+ process.kill(process.pid, 'SIGKILL');+ if (existsSync(backup)) {+ if (!descriptorStillCurrent(backup, expectedDescriptor) || !descriptorStillCurrent(target, expectedDescriptor))+ throw new Error('INVALID_ACTIVATION_BACKUP');+ unlinkSync(backup);+ fsyncDirectory(dirname(backup));+ }+ if (!descriptorStillCurrent(target, expectedDescriptor)) throw new Error('INVALID_ACTIVATION_BACKUP');+}++function validateExistingTarget(path, entry) {+ const descriptor = secureReadDescriptor(path);+ try {+ // Existing active credentials may be expired, but otherwise must satisfy+ // the same exact schema and structural checks as a staging candidate.+ validateCandidateBytes(descriptor.bytes, entry, Number.NEGATIVE_INFINITY);+ } catch (error) {+ if (error?.message === 'IDENTITY_MISMATCH') throw new Error('ACTIVE_TARGET_IDENTITY_MISMATCH');+ throw new Error('INVALID_ACTIVE_TARGET');+ }+ return descriptor;+}++function journalPath(options) {+ return `${options.operationLockPath}.journal`;+}++function rollbackRecordPath(options, entry) {+ return join(options.rollbackDir, `${entry.authFilename}.committed-rollback.json`);+}++function retainCommittedRollback(options, state) {+ if (!state.hadTarget || !state.backupDescriptor) return;+ if (!descriptorStillCurrent(state.backup, state.backupDescriptor)) throw new Error('INVALID_ACTIVATION_BACKUP');+ if (!descriptorStillCurrent(state.target, state.candidateDescriptor)) throw new Error('ACTIVATION_RECOVERY_REQUIRED');+ const path = rollbackRecordPath(options, state.entrySnapshot);+ const retained = { ...state, phase: 'RETAINED' };+ const key = secureRead(options.keyPath);+ if (existsSync(path)) {+ const existing = verifySignedRecord(secureRead(path), key, 'INVALID_ROLLBACK_RECORD');+ if (canonicalJson(existing) !== canonicalJson(retained)) throw new Error('ROLLBACK_RECORD_EXISTS');+ return;+ }+ durableExclusive(path, `${canonicalJson(signedRecord(retained, key))}\n`);+}++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);+ let published = false;+ try {+ writeFileSync(fd, bytes);+ fsyncSync(fd);+ closeSync(fd);+ fd = undefined;+ renameSync(temp, path);+ published = true;+ if (+ process.env.CLAUDE_STAGED_ENROLLMENT_TESTING === '1' &&+ process.env.CLAUDE_STAGED_ENROLLMENT_TEST_FAULT === `THROW:JOURNAL_FSYNC:${phase}`+ )+ throw new Error('INJECTED_JOURNAL_FSYNC_FAILURE');+ fsyncDirectory(dirname(path));+ } catch (error) {+ if (published) error.publishedJournalPhase = phase;+ throw error;+ } finally {+ if (fd !== undefined) closeSync(fd);+ rmSync(temp, { force: true });+ }+ if (+ process.env.CLAUDE_STAGED_ENROLLMENT_TESTING === '1' &&+ process.env.CLAUDE_STAGED_ENROLLMENT_TEST_FAULT === `SIGKILL:${phase}`+ )+ process.kill(process.pid, 'SIGKILL');+ if (+ process.env.CLAUDE_STAGED_ENROLLMENT_TESTING === '1' &&+ process.env.CLAUDE_STAGED_ENROLLMENT_TEST_FAULT === `SIGSTOP:${phase}`+ )+ process.kill(process.pid, 'SIGSTOP');+ return next;+}++function removeJournal(options) {+ unlinkSync(journalPath(options));+ fsyncDirectory(dirname(journalPath(options)));+}++function removeCommittedBackup(state) {+ if (existsSync(state.backup)) {+ assertCanonicalExisting(state.backup);+ assertOwnerOnly(state.backup, 'file', true);+ // No backup is ever created for a previously absent target. Refuse an+ // unexpected file instead of deleting a pathname solely because it was+ // recorded in the journal.+ if (!state.hadTarget || !state.backupDescriptor || !descriptorStillCurrent(state.backup, state.backupDescriptor))+ throw new Error('INVALID_ACTIVATION_BACKUP');+ unlinkSync(state.backup);+ }+ // Always prove cleanup durable, including the already-absent case.+ fsyncDirectory(dirname(state.backup));+}++function removePreparingBackup(state) {+ if (existsSync(state.backup)) {+ if (!state.hadTarget) throw new Error('ACTIVATION_RECOVERY_UNCERTAIN');+ assertCanonicalExisting(state.backup);+ assertOwnerOnly(state.backup, 'file', true);+ if (state.backupDescriptor) {+ if (!descriptorStillCurrent(state.backup, state.backupDescriptor))+ throw new Error('ACTIVATION_RECOVERY_UNCERTAIN');+ } else throw new Error('ACTIVATION_RECOVERY_UNCERTAIN');+ unlinkSync(state.backup);+ }+ if (+ process.env.CLAUDE_STAGED_ENROLLMENT_TESTING === '1' &&+ process.env.CLAUDE_STAGED_ENROLLMENT_TEST_FAULT === 'THROW:BACKUP_UNLINK_BEFORE_FSYNC'+ )+ throw new Error('INJECTED_BACKUP_CLEANUP_FSYNC_FAILURE');+ fsyncDirectory(dirname(state.backup));+}++export function activateEnrollment(options) {+ if (!options?.configPath) throw new Error('CONFIG_PATH_REQUIRED');+ if (+ !isAbsolute(options.configPath) ||+ !isAbsolute(options.approvalPath) ||+ typeof options.inventoryPath !== 'string' ||+ !isAbsolute(options.inventoryPath) ||+ typeof options.canaryPath !== 'string' ||+ !isAbsolute(options.canaryPath)+ )+ throw new Error('ABSOLUTE_PATH_REQUIRED');+ options = optionsFromConfig(options);+ return withOperationLock(options.operationLockPath, options.keyPath, () => {+ if (+ process.env.CLAUDE_STAGED_ENROLLMENT_TESTING === '1' &&+ process.env.CLAUDE_STAGED_ENROLLMENT_TEST_FAULT === 'SIGSTOP:LOCK_ACQUIRED'+ )+ process.kill(process.pid, 'SIGSTOP');+ const { initial, entry } = loadCommon(options);+ if (existsSync(rollbackRecordPath(options, entry))) throw new Error('ROLLBACK_RECORD_EXISTS');+ const stagedPath = join(options.stagingDir, entry.authFilename);+ assertOwnerOnly(stagedPath, 'file');+ const candidateDescriptor = secureReadDescriptor(stagedPath);+ const candidateBytes = candidateDescriptor.bytes;+ const { digest: candidateDigest } = validateCandidateBytes(candidateBytes, entry, options.now);+ const target = join(options.activeDir, entry.authFilename);+ assertCanonicalLeaf(target);+ const hadTarget = existsSync(target);+ let oldDigest = null;+ let oldTarget = null;+ if (hadTarget) {+ assertOwnerOnly(target, 'file');+ oldTarget = validateExistingTarget(target, entry);+ oldDigest = oldTarget.digest;+ }+ const authoritativeConsumers = readAuthoritativeConsumers(options, entry);+ const inventory = readSwitchEvidence(+ options.inventoryPath,+ 'inventory',+ entry,+ candidateDigest,+ authoritativeConsumers,+ );+ const canary = readSwitchEvidence(options.canaryPath, 'canary', entry, candidateDigest, authoritativeConsumers);+ const artifact = readArtifact(options.approvalPath);+ const payload = verifyApproval({+ artifact,+ keyPath: options.keyPath,+ expected: binding(entry, initial.digest, 'activate', candidateDigest, options.environment, options.operator, {+ oldTargetDigest: oldDigest,+ inventoryDigest: inventory.digest,+ canaryDigest: canary.digest,+ }),+ now: options.now,+ maxTtlMs: options.maxTtlMs,+ });+ validatePathTopology({+ configPath: options.configPath,+ config: {+ manifestPath: options.manifestPath,+ approvalKeyPath: options.keyPath,+ usageDir: options.usageDir,+ stagingDir: options.stagingDir,+ activeDir: options.activeDir,+ quarantineDirs: options.quarantineDirs,+ rollbackDir: options.rollbackDir,+ operationLockPath: options.operationLockPath,+ },+ approvalPath: options.approvalPath,+ entry,+ approvalId: payload,+ });+ assertNoIdentityConflicts({+ entry,+ activeDir: options.activeDir,+ quarantineDirs: options.quarantineDirs,+ stagingDir: options.stagingDir,+ candidatePath: stagedPath,+ });+ if (statSync(options.stagingDir).dev !== statSync(options.activeDir).dev) throw new Error('CROSS_FILESYSTEM');+ if (statSync(options.rollbackDir).dev !== statSync(options.activeDir).dev) throw new Error('CROSS_FILESYSTEM');+ if (options.beforeCas) options.beforeCas();+ 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');+ 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)))+ 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: {+ manifestPath: options.manifestPath,+ approvalKeyPath: options.keyPath,+ usageDir: options.usageDir,+ stagingDir: options.stagingDir,+ activeDir: options.activeDir,+ quarantineDirs: options.quarantineDirs,+ rollbackDir: options.rollbackDir,+ operationLockPath: options.operationLockPath,+ },+ approvalPath: options.approvalPath,+ entry,+ approvalId: payload,+ computedPaths: [+ ['backup target', backup, options.rollbackDir, true],+ ...(restorePath ? [['restore target', restorePath, options.activeDir, true]] : []),+ ],+ });+ let journal = {+ version: 3,+ manifestDigest: initial.digest,+ entrySnapshot: { ...entry },+ entryId: entry.id,+ authFilename: entry.authFilename,+ candidateDigest,+ candidateDescriptor: {+ dev: candidateDescriptor.dev,+ ino: candidateDescriptor.ino,+ digest: candidateDescriptor.digest,+ birthtimeNs: candidateDescriptor.birthtimeNs,+ },+ oldDigest,+ hadTarget,+ backupDescriptor: oldTarget+ ? {+ dev: oldTarget.dev,+ ino: oldTarget.ino,+ birthtimeNs: oldTarget.birthtimeNs,+ size: oldTarget.bytes.length,+ digest: oldDigest,+ }+ : null,+ stagedPath,+ target,+ backup,+ restorePath,+ approvalId: payload.id,+ approvalNonce: payload.nonce,+ authorization: artifact,+ authorizationDigest: sha256(Buffer.from(canonicalJson(artifact))),+ inventoryDigest: inventory.digest,+ canaryDigest: canary.digest,+ };+ journal = writeJournal(options, journal, 'PREPARING');+ if (hadTarget) {+ // The intent already binds the validated target inode. Atomic no-replace+ // 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 (+ process.env.CLAUDE_STAGED_ENROLLMENT_TESTING === '1' &&+ process.env.CLAUDE_STAGED_ENROLLMENT_TEST_FAULT === 'SIGKILL:BACKUP_OPENED'+ )+ process.kill(process.pid, 'SIGKILL');+ if (options.injectFailure === 'partial-backup') throw new Error('INJECTED_FAILURE');+ fsyncDirectory(options.rollbackDir);+ 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 (!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)))+ throw new Error('ACTIVE_TARGET_CAS_FAILED');+ journal = writeJournal(options, journal, 'APPROVAL_INTENT');+ try {+ consumeApproval(payload, options.usageDir, options.keyPath);+ } catch {+ // The journal lets a fresh recovery process durably resolve whether the+ // marker exists. Do not guess or roll back in-process after an ambiguous+ // marker publication.+ throw new Error('ACTIVATION_RECOVERY_REQUIRED');+ }+ journal = writeJournal(options, journal, 'APPROVAL_CONSUMED');+ journal = writeJournal(options, journal, 'INSTALL_INTENT');+ let renameCompleted = false;+ try {+ if (!descriptorStillCurrent(stagedPath, 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');+ // 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+ // than reported as a successful M0 activation.+ if (readManifest(options.manifestPath).digest !== initial.digest) throw new Error('MANIFEST_CAS_FAILED');+ if (+ process.env.CLAUDE_STAGED_ENROLLMENT_TESTING === '1' &&+ process.env.CLAUDE_STAGED_ENROLLMENT_TEST_FAULT === 'SIGSTOP:MANIFEST_CAS_VERIFIED'+ )+ 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');+ journal = writeJournal(options, journal, 'COMMITTED');+ if (!descriptorStillCurrent(target, candidateDescriptor)) throw new Error('ACTIVATION_RECOVERY_REQUIRED');+ retainCommittedRollback(options, journal);+ if (!descriptorStillCurrent(target, 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'+ )+ process.kill(process.pid, 'SIGKILL');+ removeJournal(options);+ return {+ ok: true,+ action: 'activate',+ provider: 'claude',+ manifestEntryId: entry.id,+ authFilename: entry.authFilename,+ candidateDigest,+ backupCreated: hadTarget,+ };+ } catch (activationError) {+ if (journal.phase === 'COMMITTED' || activationError?.publishedJournalPhase === 'COMMITTED')+ throw new Error('ACTIVATION_RECOVERY_REQUIRED');+ let recoveryFailed = false;+ if (renameCompleted) {+ try {+ if (existsSync(target) && !existsSync(stagedPath) && descriptorStillCurrent(target, candidateDescriptor))+ renameSync(target, stagedPath);+ else recoveryFailed = true;+ } catch {+ recoveryFailed = true;+ }+ }+ if (hadTarget && renameCompleted) {+ try {+ if (!existsSync(backup) || !descriptorStillCurrent(backup, journal.backupDescriptor))+ throw new Error('INVALID_ACTIVATION_BACKUP');+ restoreBackup(backup, target, options.activeDir, restorePath, journal.backupDescriptor, oldDigest);+ } catch {+ recoveryFailed = true;+ }+ }+ for (const dir of [options.activeDir, options.stagingDir]) {+ try {+ if (options.injectFailure === 'rollback-fsync-failure' && dir === options.activeDir)+ throw new Error('INJECTED_FAILURE');+ fsyncDirectory(dir);+ } catch {+ recoveryFailed = true;+ }+ }+ try {+ if (!existsSync(stagedPath) || !descriptorStillCurrent(stagedPath, candidateDescriptor)) recoveryFailed = true;+ if (hadTarget) {+ if (!existsSync(target) || !descriptorStillCurrent(target, journal.backupDescriptor)) recoveryFailed = true;+ } else if (existsSync(target)) recoveryFailed = true;+ } catch {+ recoveryFailed = true;+ }+ if (!recoveryFailed) {+ try {+ removeCommittedBackup(journal);+ removeJournal(options);+ } catch {+ recoveryFailed = true;+ }+ }+ if (activationError?.message === 'INJECTED_FAILURE' && !renameCompleted) throw activationError;+ throw new Error(recoveryFailed ? 'ACTIVATION_ROLLBACK_FAILED' : 'ACTIVATION_ROLLED_BACK');+ }+ });+}++export function recoverEnrollment(options) {+ if (!options?.configPath) throw new Error('CONFIG_PATH_REQUIRED');+ if (!isAbsolute(options.configPath)) throw new Error('ABSOLUTE_PATH_REQUIRED');+ options = optionsFromConfig(options);+ return withOperationLock(+ options.operationLockPath,+ options.keyPath,+ () => {+ 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');+ exactKeys(state, [+ 'version',+ 'manifestDigest',+ 'entrySnapshot',+ 'entryId',+ 'authFilename',+ 'candidateDigest',+ 'candidateDescriptor',+ 'oldDigest',+ 'hadTarget',+ 'backupDescriptor',+ 'stagedPath',+ 'target',+ 'backup',+ 'restorePath',+ 'approvalId',+ 'approvalNonce',+ 'authorization',+ 'authorizationDigest',+ 'inventoryDigest',+ 'canaryDigest',+ 'phase',+ ]);+ const allowed = [+ 'PREPARING',+ 'BACKUP_CREATE_INTENT',+ 'BACKUP_CREATED',+ 'PREPARED',+ 'APPROVAL_INTENT',+ 'APPROVAL_CONSUMED',+ 'INSTALL_INTENT',+ 'INSTALLED',+ 'COMMITTED',+ ];+ if (state.version !== 3 || !allowed.includes(state.phase)) throw new Error('INVALID_ACTIVATION_JOURNAL');+ if (!/^[a-f0-9]{64}$/.test(state.manifestDigest)) throw new Error('INVALID_ACTIVATION_JOURNAL');+ try {+ exactKeys(state.authorization, ['payload', 'signature']);+ exactKeys(state.authorization.payload, APPROVAL_KEYS);+ if (+ sha256(Buffer.from(canonicalJson(state.authorization))) !== state.authorizationDigest ||+ state.authorization.payload.action !== 'canonical-switch' ||+ state.authorization.payload.id !== state.approvalId ||+ state.authorization.payload.nonce !== state.approvalNonce ||+ state.authorization.payload.manifestDigest !== state.manifestDigest ||+ state.authorization.payload.candidateDigest !== state.candidateDigest ||+ state.authorization.payload.oldTargetDigest !== state.oldDigest ||+ state.authorization.payload.inventoryDigest !== state.inventoryDigest ||+ state.authorization.payload.canaryDigest !== state.canaryDigest ||+ !/^[a-f0-9]{64}$/.test(state.inventoryDigest) ||+ !/^[a-f0-9]{64}$/.test(state.canaryDigest)+ )+ throw new Error();+ const expectedSignature = createHmac('sha256', secureRead(options.keyPath))+ .update(canonicalJson(state.authorization.payload))+ .digest();+ if (+ typeof state.authorization.signature !== 'string' ||+ !/^[a-f0-9]{64}$/.test(state.authorization.signature) ||+ !timingSafeEqual(Buffer.from(state.authorization.signature, 'hex'), expectedSignature)+ )+ throw new Error();+ } catch {+ throw new Error('INVALID_ACTIVATION_JOURNAL');+ }+ try {+ exactKeys(state.candidateDescriptor, ['dev', 'ino', 'digest', 'birthtimeNs']);+ if (+ !Number.isSafeInteger(state.candidateDescriptor.dev) ||+ !Number.isSafeInteger(state.candidateDescriptor.ino) ||+ !/^\d+$/.test(state.candidateDescriptor.birthtimeNs) ||+ state.candidateDescriptor.digest !== state.candidateDigest+ )+ throw new Error();+ } catch {+ throw new Error('INVALID_ACTIVATION_JOURNAL');+ }+ // 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.+ const entry = state.entrySnapshot;+ if (state.backupDescriptor !== null) {+ try {+ exactKeys(state.backupDescriptor, ['dev', 'ino', 'birthtimeNs', 'size', 'digest']);+ if (+ !Number.isSafeInteger(state.backupDescriptor.dev) ||+ !Number.isSafeInteger(state.backupDescriptor.ino) ||+ !/^\d+$/.test(state.backupDescriptor.birthtimeNs) ||+ !Number.isSafeInteger(state.backupDescriptor.size) ||+ !/^[a-f0-9]{64}$/.test(state.backupDescriptor.digest)+ )+ throw new Error();+ } catch {+ throw new Error('INVALID_ACTIVATION_JOURNAL');+ }+ }+ if (+ state.hadTarget &&+ allowed.indexOf(state.phase) >= allowed.indexOf('BACKUP_CREATED') &&+ (!state.backupDescriptor ||+ state.backupDescriptor.digest !== state.oldDigest ||+ state.backupDescriptor.size <= 0)+ )+ throw new Error('INVALID_ACTIVATION_JOURNAL');+ try {+ exactKeys(entry, CLAUDE_ENTRY_KEYS);+ if (entry.provider !== 'claude' || entry.id !== state.entryId || entry.authFilename !== state.authFilename)+ throw new Error('INVALID_ACTIVATION_JOURNAL');+ normalizeEmail(entry.email);+ for (const field of ['organizationUuid', 'organizationName', 'accountOwner']) nonempty(entry[field]);+ } catch {+ throw new Error('INVALID_ACTIVATION_JOURNAL');+ }+ const expectedStaged = entry && join(options.stagingDir, entry.authFilename);+ const expectedTarget = entry && join(options.activeDir, entry.authFilename);+ const expectedBackup =+ entry &&+ join(+ options.rollbackDir,+ `${entry.authFilename}.${state.approvalId}.${state.approvalNonce}.${state.candidateDigest}.${state.oldDigest || 'none'}.bak`,+ );+ const expectedRestore = null;+ if (+ !entry ||+ state.authFilename !== entry.authFilename ||+ state.stagedPath !== expectedStaged ||+ state.target !== expectedTarget ||+ state.backup !== expectedBackup ||+ state.restorePath !== expectedRestore+ )+ throw new Error('INVALID_ACTIVATION_JOURNAL');+ const targetDescriptor = existsSync(state.target) ? secureReadDescriptor(state.target, false) : null;+ const targetHasNew =+ targetDescriptor &&+ targetDescriptor.dev === state.candidateDescriptor.dev &&+ targetDescriptor.ino === state.candidateDescriptor.ino &&+ targetDescriptor.birthtimeNs === state.candidateDescriptor.birthtimeNs &&+ targetDescriptor.digest === state.candidateDigest;+ const marker = join(options.usageDir, `${state.approvalId}.${state.approvalNonce}.used`);+ // 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,+ config: {+ manifestPath: options.manifestPath,+ approvalKeyPath: options.keyPath,+ usageDir: options.usageDir,+ stagingDir: options.stagingDir,+ activeDir: options.activeDir,+ quarantineDirs: options.quarantineDirs,+ rollbackDir: options.rollbackDir,+ operationLockPath: options.operationLockPath,+ },+ entry,+ approvalId: { id: state.approvalId, nonce: state.approvalNonce },+ computedPaths: [+ ['backup target', state.backup, options.rollbackDir, true],+ ...(state.restorePath ? [['restore target', state.restorePath, options.activeDir, true]] : []),+ ],+ });+ const markerRequired = allowed.indexOf(state.phase) >= allowed.indexOf('APPROVAL_CONSUMED');+ if (markerRequired || (state.phase === 'APPROVAL_INTENT' && existsSync(marker))) {+ try {+ if (!existsSync(marker)) throw new Error('MISSING_USE_MARKER');+ validateUseMarker(marker, options.keyPath, {+ approvalId: state.approvalId,+ nonce: state.approvalNonce,+ action: 'canonical-switch',+ });+ } catch {+ throw new Error('ACTIVATION_RECOVERY_UNCERTAIN');+ }+ fsyncDirectory(options.usageDir);+ } else if (state.phase === 'APPROVAL_INTENT') {+ fsyncDirectory(options.usageDir);+ }+ if (state.phase === 'COMMITTED') {+ if (!targetHasNew || !descriptorStillCurrent(state.target, state.candidateDescriptor))+ throw new Error('ACTIVATION_RECOVERY_UNCERTAIN');+ retainCommittedRollback(options, state);+ if (!descriptorStillCurrent(state.target, state.candidateDescriptor))+ throw new Error('ACTIVATION_RECOVERY_UNCERTAIN');+ removeJournal(options);+ return { ok: true, action: 'recover', recovered: true, outcome: 'committed' };+ }+ if (state.phase === 'PREPARING' && state.hadTarget && !existsSync(state.backup)) {+ if (!existsSync(state.target) || !descriptorStillCurrent(state.target, state.backupDescriptor) || targetHasNew)+ throw new Error('ACTIVATION_RECOVERY_UNCERTAIN');+ if (!existsSync(state.stagedPath) || !descriptorStillCurrent(state.stagedPath, state.candidateDescriptor))+ throw new Error('ACTIVATION_RECOVERY_UNCERTAIN');+ // PREPARING is always pre-backup. Remove partial/full backup+ // idempotently and prove every mutation directory durable first.+ removePreparingBackup(state);+ fsyncDirectory(options.activeDir);+ fsyncDirectory(options.stagingDir);+ removeJournal(options);+ return { ok: true, action: 'recover', recovered: true, outcome: 'rolled-back' };+ }+ if (state.phase === 'PREPARING') {+ if (state.hadTarget) {+ if (+ !existsSync(state.target) ||+ !descriptorStillCurrent(state.target, state.backupDescriptor) ||+ targetHasNew+ )+ throw new Error('ACTIVATION_RECOVERY_UNCERTAIN');+ } else if (existsSync(state.target)) throw new Error('ACTIVATION_RECOVERY_UNCERTAIN');+ if (!existsSync(state.stagedPath) || !descriptorStillCurrent(state.stagedPath, state.candidateDescriptor))+ throw new Error('ACTIVATION_RECOVERY_UNCERTAIN');+ removePreparingBackup(state);+ fsyncDirectory(options.activeDir);+ fsyncDirectory(options.stagingDir);+ removeJournal(options);+ return { ok: true, action: 'recover', recovered: true, outcome: 'rolled-back' };+ }+ if (state.phase === 'BACKUP_CREATE_INTENT') {+ if (+ !state.hadTarget ||+ !existsSync(state.target) ||+ !descriptorStillCurrent(state.target, state.backupDescriptor)+ )+ throw new Error('ACTIVATION_RECOVERY_UNCERTAIN');+ if (!existsSync(state.stagedPath) || !descriptorStillCurrent(state.stagedPath, state.candidateDescriptor))+ throw new Error('ACTIVATION_RECOVERY_UNCERTAIN');+ removePreparingBackup(state);+ fsyncDirectory(options.activeDir);+ fsyncDirectory(options.stagingDir);+ removeJournal(options);+ return { ok: true, action: 'recover', recovered: true, outcome: 'rolled-back' };+ }+ if (state.phase === 'BACKUP_CREATED') {+ if (+ !state.hadTarget ||+ !existsSync(state.target) ||+ !descriptorStillCurrent(state.target, state.backupDescriptor)+ )+ throw new Error('ACTIVATION_RECOVERY_UNCERTAIN');+ if (!existsSync(state.stagedPath) || !descriptorStillCurrent(state.stagedPath, state.candidateDescriptor))+ throw new Error('ACTIVATION_RECOVERY_UNCERTAIN');+ if (state.phase === 'BACKUP_CREATED' && !descriptorStillCurrent(state.backup, state.backupDescriptor))+ throw new Error('ACTIVATION_RECOVERY_UNCERTAIN');+ removePreparingBackup(state);+ fsyncDirectory(options.activeDir);+ fsyncDirectory(options.stagingDir);+ removeJournal(options);+ return { ok: true, action: 'recover', recovered: true, outcome: 'rolled-back' };+ }+ if (targetHasNew) {+ if (existsSync(state.stagedPath)) throw new Error('ACTIVATION_RECOVERY_UNCERTAIN');+ if (!descriptorStillCurrent(state.target, state.candidateDescriptor))+ throw new Error('ACTIVATION_RECOVERY_UNCERTAIN');+ renameSync(state.target, state.stagedPath);+ if (+ process.env.CLAUDE_STAGED_ENROLLMENT_TESTING === '1' &&+ process.env.CLAUDE_STAGED_ENROLLMENT_TEST_FAULT === 'SIGKILL:RECOVERY_ROLLBACK_RENAMED'+ )+ process.kill(process.pid, 'SIGKILL');+ }+ if (state.hadTarget) {+ const targetHasOld = existsSync(state.target) && descriptorStillCurrent(state.target, state.backupDescriptor);+ if (!targetHasOld) {+ if (existsSync(state.target)) throw new Error('ACTIVATION_RECOVERY_UNCERTAIN');+ if (!existsSync(state.backup) || !descriptorStillCurrent(state.backup, state.backupDescriptor))+ throw new Error('ACTIVATION_RECOVERY_UNCERTAIN');+ restoreBackup(+ state.backup,+ state.target,+ dirname(state.target),+ state.restorePath,+ state.backupDescriptor,+ state.oldDigest,+ );+ }+ if (!existsSync(state.target) || !descriptorStillCurrent(state.target, state.backupDescriptor))+ throw new Error('ACTIVATION_RECOVERY_UNCERTAIN');+ removeCommittedBackup(state);+ } else if (existsSync(state.target)) {+ throw new Error('ACTIVATION_RECOVERY_UNCERTAIN');+ }+ if (!existsSync(state.stagedPath) || !descriptorStillCurrent(state.stagedPath, state.candidateDescriptor))+ throw new Error('ACTIVATION_RECOVERY_UNCERTAIN');+ // Prove both mutation directories durable on every non-PREPARING+ // rollback recovery, including an invocation that found no rename to do.+ fsyncDirectory(options.activeDir);+ if (+ process.env.CLAUDE_STAGED_ENROLLMENT_TESTING === '1' &&+ process.env.CLAUDE_STAGED_ENROLLMENT_TEST_FAULT === 'SIGKILL:RECOVERY_ROLLBACK_FIRST_DIR_FSYNC'+ )+ process.kill(process.pid, 'SIGKILL');+ fsyncDirectory(options.stagingDir);+ removeJournal(options);+ return { ok: true, action: 'recover', recovered: true, outcome: 'rolled-back' };+ },+ { allowJournal: true },+ );+}++function rollbackIntentPath(recordPath) {+ return `${recordPath}.intent`;+}++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);+ fsyncDirectory(dirname(path));+ if (+ process.env.CLAUDE_STAGED_ENROLLMENT_TESTING === '1' &&+ process.env.CLAUDE_STAGED_ENROLLMENT_TEST_FAULT === `SIGKILL:ROLLBACK_${payload.phase}_INTENT`+ )+ process.kill(process.pid, 'SIGKILL');+ return payload;+}++function recoverRollbackIntent(options, entry, recordPath) {+ const intentPath = rollbackIntentPath(recordPath);+ if (!existsSync(intentPath)) return null;+ const key = secureRead(options.keyPath);+ const intent = verifySignedRecord(secureRead(intentPath), key, 'INVALID_ROLLBACK_INTENT');+ exactKeys(intent, [+ 'version',+ 'phase',+ 'operationId',+ 'recordPath',+ 'recordDigest',+ 'retained',+ 'approval',+ 'approvalDigest',+ 'target',+ 'backup',+ 'candidateDescriptor',+ 'backupDescriptor',+ 'manifestDigest',+ 'entrySnapshot',+ 'destination',+ 'tempPath',+ ]);+ if (+ intent.version !== 1 ||+ !['PREPARING', 'SWITCHED'].includes(intent.phase) ||+ !/^[0-9a-f-]{36}$/.test(intent.operationId) ||+ intent.recordPath !== recordPath ||+ intent.target !== join(options.activeDir, entry.authFilename) ||+ intent.backup !== intent.retained?.backup ||+ intent.destination !== entry.authFilename ||+ intent.manifestDigest !== intent.retained?.manifestDigest ||+ canonicalJson(intent.entrySnapshot) !== canonicalJson(entry) ||+ canonicalJson(intent.retained?.entrySnapshot) !== canonicalJson(entry) ||+ intent.tempPath !== join(options.activeDir, `.${entry.authFilename}.${intent.operationId}.rollback`) ||+ intent.recordDigest !== sha256(Buffer.from(`${canonicalJson(signedRecord(intent.retained, key))}\n`)) ||+ intent.approvalDigest !== sha256(Buffer.from(canonicalJson(intent.approval)))+ )+ throw new Error('INVALID_ROLLBACK_INTENT');+ const p = intent.approval?.payload;+ try {+ exactKeys(intent.approval, ['payload', 'signature']);+ if (+ p.action !== 'canonical-rollback' ||+ p.manifestDigest !== intent.manifestDigest ||+ p.manifestEntryId !== entry.id ||+ p.candidateDigest !== intent.retained.candidateDigest ||+ p.oldBackupDigest !== intent.retained.oldDigest ||+ p.recordDigest !== intent.recordDigest ||+ p.destination !== intent.destination+ )+ throw new Error();+ const signature = createHmac('sha256', key).update(canonicalJson(p)).digest();+ if (+ !/^[a-f0-9]{64}$/.test(intent.approval.signature) ||+ !timingSafeEqual(Buffer.from(intent.approval.signature, 'hex'), signature)+ )+ throw new Error();+ } catch {+ throw new Error('INVALID_ROLLBACK_INTENT');+ }+ if (existsSync(recordPath) && sha256(secureRead(recordPath)) !== intent.recordDigest)+ throw new Error('ROLLBACK_RECOVERY_UNCERTAIN');+ const marker = join(options.usageDir, `${p.id}.${p.nonce}.used`);+ if (existsSync(marker))+ validateUseMarker(marker, options.keyPath, { approvalId: p.id, nonce: p.nonce, action: p.action });+ else consumeApproval(p, options.usageDir, options.keyPath);++ 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 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')+ process.kill(process.pid, 'SIGKILL');+ fsyncDirectory(options.activeDir);+ }+ if (+ !descriptorStillCurrent(intent.target, intent.candidateDescriptor) ||+ !descriptorStillCurrent(intent.tempPath, intent.backupDescriptor)+ )+ throw new Error('ROLLBACK_RECOVERY_UNCERTAIN');+ renameSync(intent.tempPath, intent.target);+ if (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);+ } 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);+ fsyncDirectory(options.rollbackDir);+ if (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);+ fsyncDirectory(options.rollbackDir);+ }+ unlinkSync(intentPath);+ fsyncDirectory(options.rollbackDir);+ return {+ ok: true,+ action: 'rollback',+ recovered: true,+ manifestEntryId: entry.id,+ restoredDigest: intent.retained.oldDigest,+ };+}++export function rollbackEnrollment(options) {+ if (!options?.configPath || !options?.entryId || !options?.approvalPath) throw new Error('INVALID_ARGUMENTS');+ options = optionsFromConfig(options);+ options.now ??= Date.now();+ return withOperationLock(options.operationLockPath, options.keyPath, () => {+ const manifest = readManifest(options.manifestPath);+ const entry = manifest.manifest.entries.find((candidate) => candidate.id === options.entryId);+ if (!entry || entry.provider !== 'claude') throw new Error('ENTRY_NOT_CLAUDE');+ const path = rollbackRecordPath(options, entry);+ const recovered = recoverRollbackIntent(options, entry, path);+ if (recovered) return recovered;+ if (!existsSync(path)) throw new Error('ROLLBACK_RECORD_NOT_FOUND');+ const state = verifySignedRecord(secureRead(path), secureRead(options.keyPath), 'INVALID_ROLLBACK_RECORD');+ if (+ state.phase !== 'RETAINED' ||+ state.manifestDigest !== manifest.digest ||+ state.entryId !== entry.id ||+ canonicalJson(state.entrySnapshot) !== canonicalJson(entry) ||+ state.target !== join(options.activeDir, entry.authFilename) ||+ state.backup !==+ join(+ options.rollbackDir,+ `${entry.authFilename}.${state.approvalId}.${state.approvalNonce}.${state.candidateDigest}.${state.oldDigest}.bak`,+ ) ||+ !state.hadTarget ||+ state.oldDigest !== state.backupDescriptor?.digest ||+ state.candidateDigest !== state.candidateDescriptor?.digest ||+ !descriptorStillCurrent(state.target, state.candidateDescriptor) ||+ !descriptorStillCurrent(state.backup, state.backupDescriptor)+ )+ throw new Error('INVALID_ROLLBACK_RECORD');+ const recordDigest = sha256(secureRead(path));+ const rollbackApproval = readArtifact(options.approvalPath);+ const rollbackKeys = [+ 'version',+ 'id',+ 'nonce',+ 'action',+ 'manifestDigest',+ 'manifestEntryId',+ 'email',+ 'organizationUuid',+ 'organizationName',+ 'accountOwner',+ 'authorizedOperator',+ 'environment',+ 'issuedAt',+ 'expiresAt',+ 'candidateDigest',+ 'oldBackupDigest',+ 'recordDigest',+ 'destination',+ ];+ exactKeys(rollbackApproval, ['payload', 'signature']);+ exactKeys(rollbackApproval.payload, rollbackKeys);+ const p = rollbackApproval.payload;+ const issued = parseRfc3339(p.issuedAt);+ const expires = parseRfc3339(p.expiresAt);+ const expected = {+ action: 'canonical-rollback',+ manifestDigest: manifest.digest,+ manifestEntryId: entry.id,+ email: entry.email,+ organizationUuid: entry.organizationUuid,+ organizationName: entry.organizationName,+ accountOwner: entry.accountOwner,+ authorizedOperator: options.operator,+ environment: options.environment,+ candidateDigest: state.candidateDigest,+ oldBackupDigest: state.oldDigest,+ recordDigest,+ destination: entry.authFilename,+ };+ if (+ p.version !== 1 ||+ !/^[A-Za-z0-9_-]{8,128}$/.test(p.id || '') ||+ !/^[A-Za-z0-9_-]{8,128}$/.test(p.nonce || '') ||+ issued === null ||+ expires === null ||+ issued > options.now ||+ expires <= options.now ||+ expires <= issued ||+ expires - issued > options.maxTtlMs ||+ Object.entries(expected).some(([key, value]) => p[key] !== value)+ )+ throw new Error('INVALID_ROLLBACK_APPROVAL');+ const signature = createHmac('sha256', secureRead(options.keyPath)).update(canonicalJson(p)).digest();+ if (+ !/^[a-f0-9]{64}$/.test(rollbackApproval.signature || '') ||+ !timingSafeEqual(Buffer.from(rollbackApproval.signature, 'hex'), signature)+ )+ throw new Error('INVALID_ROLLBACK_APPROVAL');+ const operationId = randomUUID();+ const intentPath = rollbackIntentPath(path);+ writeRollbackIntent(+ intentPath,+ {+ version: 1,+ phase: 'PREPARING',+ operationId,+ recordPath: path,+ recordDigest,+ retained: state,+ approval: rollbackApproval,+ approvalDigest: sha256(Buffer.from(canonicalJson(rollbackApproval))),+ target: state.target,+ backup: state.backup,+ candidateDescriptor: state.candidateDescriptor,+ backupDescriptor: state.backupDescriptor,+ manifestDigest: manifest.digest,+ entrySnapshot: entry,+ destination: entry.authFilename,+ tempPath: join(options.activeDir, `.${entry.authFilename}.${operationId}.rollback`),+ },+ secureRead(options.keyPath),+ );+ return recoverRollbackIntent(options, entry, path);+ });+}++export function readDeploymentConfig(path) {+ if (!isAbsolute(path)) throw new Error('INVALID_CONFIG');+ assertCanonicalExisting(path);+ assertOwnerOnly(path, 'file');+ let config;+ try {+ config = parseStrictJson(secureRead(path), 'INVALID_CONFIG');+ } catch {+ throw new Error('INVALID_CONFIG');+ }+ exactKeys(config, CONFIG_KEYS);+ if (+ !Number.isFinite(config.maxApprovalTtlMs) ||+ config.maxApprovalTtlMs <= 0 ||+ config.maxApprovalTtlMs > DEFAULT_MAX_TTL_MS+ )+ throw new Error('INVALID_TTL');+ for (const key of [+ 'manifestPath',+ 'approvalKeyPath',+ 'usageDir',+ 'stagingDir',+ 'activeDir',+ 'rollbackDir',+ 'operationLockPath',+ 'environment',+ 'authorizedOperator',+ 'runtimeInventoryPath',+ 'runtimeInventoryDigest',+ 'authoritativeConsumerInventoryPath',+ 'authoritativeConsumerInventoryDigest',+ 'deploymentPlanDigest',+ ])+ nonempty(config[key]);+ if (!Array.isArray(config.quarantineDirs) || !config.quarantineDirs.length) throw new Error('INVALID_CONFIG');+ config.quarantineDirs.forEach(nonempty);+ const pathKeys = [+ 'manifestPath',+ 'approvalKeyPath',+ 'usageDir',+ 'stagingDir',+ 'activeDir',+ 'rollbackDir',+ 'operationLockPath',+ 'runtimeInventoryPath',+ 'authoritativeConsumerInventoryPath',+ ];+ if ([...pathKeys.map((key) => config[key]), ...config.quarantineDirs].some((item) => !isAbsolute(item)))+ throw new Error('INVALID_CONFIG');+ if (+ !/^[a-f0-9]{64}$/.test(config.runtimeInventoryDigest) ||+ !/^[a-f0-9]{64}$/.test(config.authoritativeConsumerInventoryDigest) ||+ !/^[a-f0-9]{64}$/.test(config.deploymentPlanDigest)+ )+ throw new Error('INVALID_CONFIG');+ validatePathTopology({ configPath: path, config });+ return config;+}++function optionsFromConfig(options) {+ if (!options.configPath) return options;+ const config = readDeploymentConfig(options.configPath);+ return {+ ...options,+ manifestPath: config.manifestPath,+ keyPath: config.approvalKeyPath,+ usageDir: config.usageDir,+ stagingDir: config.stagingDir,+ activeDir: config.activeDir,+ quarantineDirs: config.quarantineDirs,+ rollbackDir: config.rollbackDir,+ operationLockPath: config.operationLockPath,+ environment: config.environment,+ operator: config.authorizedOperator,+ maxTtlMs: config.maxApprovalTtlMs,+ authoritativeConsumerInventoryPath: config.authoritativeConsumerInventoryPath,+ authoritativeConsumerInventoryDigest: config.authoritativeConsumerInventoryDigest,+ };+}++function cliOptions(argv, command) {+ const allowed = new Set([+ 'config',+ ...(command === 'recover' ? [] : ['entry']),+ ...(['stage', 'activate', 'rollback'].includes(command) ? ['approval'] : []),+ ...(command === 'stage' ? ['candidate'] : []),+ ...(command === 'activate' ? ['inventory', 'canary'] : []),+ ]);+ const out = {};+ for (let i = 0; i < argv.length; i += 2) {+ const arg = argv[i];+ if (+ !arg?.startsWith('--') ||+ !allowed.has(arg.slice(2)) ||+ argv[i + 1] === undefined ||+ out[arg.slice(2)] !== undefined+ )+ throw new Error('INVALID_ARGUMENTS');+ out[arg.slice(2)] = argv[i + 1];+ }+ if (+ !out.config ||+ (!['recover', 'rollback'].includes(command) && (!out.entry || !out.approval)) ||+ (command === 'rollback' && (!out.entry || !out.approval)) ||+ (command === 'stage' && !out.candidate) ||+ (command === 'activate' && (!out.inventory || !out.canary))+ )+ throw new Error('INVALID_ARGUMENTS');+ return out;+}++function runCli() {+ const [command, ...argv] = process.argv.slice(2);+ if (!['stage', 'activate', 'recover', 'rollback'].includes(command)) throw new Error('INVALID_ARGUMENTS');+ const args = cliOptions(argv, command);+ const config = readDeploymentConfig(args.config);+ const common = {+ manifestPath: config.manifestPath,+ keyPath: config.approvalKeyPath,+ usageDir: config.usageDir,+ stagingDir: config.stagingDir,+ activeDir: config.activeDir,+ quarantineDirs: config.quarantineDirs,+ rollbackDir: config.rollbackDir,+ operationLockPath: config.operationLockPath,+ environment: config.environment,+ operator: config.authorizedOperator,+ maxTtlMs: config.maxApprovalTtlMs,+ entryId: args.entry,+ approvalPath: args.approval,+ };+ const receipt =+ command === 'stage'+ ? stageEnrollment({ configPath: args.config, ...common, candidatePath: args.candidate })+ : command === 'activate'+ ? activateEnrollment({+ configPath: args.config,+ ...common,+ inventoryPath: args.inventory,+ canaryPath: args.canary,+ })+ : command === 'recover'+ ? recoverEnrollment({ configPath: args.config, ...common })+ : rollbackEnrollment({ configPath: args.config, ...common });+ process.stdout.write(`${JSON.stringify(receipt)}\n`);+}++if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {+ try {+ runCli();+ } catch (error) {+ const allowed = new Set([+ 'INVALID_ARGUMENTS',+ 'INVALID_CONFIG',+ 'INVALID_TTL',+ 'MISSING_TRUST_ROOT',+ 'INSECURE_TRUST_ROOT',+ 'OPERATION_LOCKED',+ 'OPERATION_LOCKED_MALFORMED',+ 'PENDING_ACTIVATION_JOURNAL',+ 'INVALID_MANIFEST',+ 'INVALID_SCHEMA',+ 'INVALID_PROVIDER',+ 'PROVIDER_FILENAME_MISMATCH',+ 'DUPLICATE_MANIFEST_BINDING',+ 'DUPLICATE_CLAUDE_IDENTITY',+ 'INVALID_PROVIDER_COUNTS',+ 'ENTRY_NOT_CLAUDE',+ 'INVALID_CANDIDATE',+ 'INVALID_VALUE',+ 'INVALID_EMAIL',+ 'INVALID_FILENAME',+ 'IDENTITY_MISMATCH',+ 'INVALID_EXPIRY',+ 'INVALID_APPROVAL',+ 'INVALID_APPROVAL_CLOCK',+ 'APPROVAL_BINDING_MISMATCH',+ 'APPROVAL_KEY_TOO_SHORT',+ 'INVALID_SIGNATURE',+ 'APPROVAL_REPLAY',+ 'APPROVAL_CONSUME_FAILED',+ 'UNSAFE_INVENTORY',+ 'MALFORMED_INVENTORY',+ 'AMBIGUOUS_INVENTORY',+ 'DUPLICATE_IDENTITY',+ 'STAGE_TARGET_EXISTS',+ 'CROSS_FILESYSTEM',+ 'MANIFEST_CAS_FAILED',+ 'ACTIVATION_ROLLED_BACK',+ 'ACTIVATION_ROLLBACK_FAILED',+ 'INVALID_ACTIVE_TARGET',+ 'ACTIVE_TARGET_IDENTITY_MISMATCH',+ 'INVALID_ACTIVATION_JOURNAL',+ 'ACTIVATION_RECOVERY_UNCERTAIN',+ 'ROLLBACK_RECORD_EXISTS',+ 'ROLLBACK_RECORD_NOT_FOUND',+ 'INVALID_ROLLBACK_RECORD',+ 'ROLLBACK_RECOVERY_UNCERTAIN',+ ]);+ const code = allowed.has(error?.message) ? error.message : 'OPERATION_REFUSED';+ process.stderr.write(`staged enrollment refused: ${code}\n`);+ process.exitCode = 1;+ }+}diff --git a/claude-ops/scripts/account-rotation/strict-json.mjs b/claude-ops/scripts/account-rotation/strict-json.mjsnew file mode 100644index 00000000..d7b29638--- /dev/null+++ b/claude-ops/scripts/account-rotation/strict-json.mjs@@ -0,0 +1,99 @@+/** JSON parser for authenticated records. Rejects ambiguous keys and excessive nesting. */+export function parseStrictJson(input, errorCode = 'INVALID_JSON', { maxDepth = 64 } = {}) {+ const text = Buffer.isBuffer(input) ? input.toString('utf8') : String(input);+ let i = 0;+ const fail = () => {+ throw new Error(errorCode);+ };+ const ws = () => {+ while (text[i] === ' ' || text[i] === '\t' || text[i] === '\n' || text[i] === '\r') i += 1;+ };+ const string = () => {+ if (text[i] !== '"') fail();+ const start = i++;+ while (i < text.length) {+ if (text[i] === '"') {+ i += 1;+ try {+ return JSON.parse(text.slice(start, i));+ } catch {+ fail();+ }+ }+ if (text[i] === '\\') {+ i += 1;+ if (text[i] === 'u') {+ if (!/^[0-9a-fA-F]{4}$/.test(text.slice(i + 1, i + 5))) fail();+ i += 5;+ } else {+ if (!/["\\/bfnrt]/.test(text[i] || '')) fail();+ i += 1;+ }+ } else {+ if (text.charCodeAt(i) < 0x20) fail();+ i += 1;+ }+ }+ fail();+ };+ const value = (depth = 0) => {+ if (depth > maxDepth) fail();+ ws();+ if (text[i] === '"') return string();+ if (text[i] === '{') {+ i += 1;+ const out = Object.create(null);+ const keys = new Set();+ ws();+ if (text[i] === '}') return ((i += 1), out);+ for (;;) {+ ws();+ const key = string();+ if (key === '__proto__' || key === 'constructor' || key === 'prototype') fail();+ if (keys.has(key)) fail();+ keys.add(key);+ ws();+ if (text[i++] !== ':') fail();+ Object.defineProperty(out, key, {+ value: value(depth + 1),+ enumerable: true,+ configurable: false,+ writable: false,+ });+ ws();+ if (text[i] === '}') return ((i += 1), out);+ if (text[i++] !== ',') fail();+ }+ }+ if (text[i] === '[') {+ i += 1;+ const out = [];+ ws();+ if (text[i] === ']') return ((i += 1), out);+ for (;;) {+ out.push(value(depth + 1));+ ws();+ if (text[i] === ']') return ((i += 1), out);+ if (text[i++] !== ',') fail();+ }+ }+ const match = /^(?:-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null)/.exec(text.slice(i));+ if (!match) fail();+ i += match[0].length;+ if (match[0] === 'true') return true;+ if (match[0] === 'false') return false;+ if (match[0] === 'null') return null;+ const number = Number(match[0]);+ if (+ !Number.isFinite(number) ||+ Object.is(number, -0) ||+ (Number.isInteger(number) && !Number.isSafeInteger(number))+ )+ fail();+ return number;+ };+ const result = value();+ ws();+ if (i !== text.length) fail();+ return result;+}diff --git a/claude-ops/scripts/account-rotation/token-identity.mjs b/claude-ops/scripts/account-rotation/token-identity.mjsnew file mode 100644index 00000000..890c4c52--- /dev/null+++ b/claude-ops/scripts/account-rotation/token-identity.mjs@@ -0,0 +1,55 @@+/** Authoritative identity check required before refreshed Claude token writes. */+const PROFILE_ENDPOINT = 'https://api.anthropic.com/api/oauth/profile';++function required(value, field) {+ if (typeof value !== 'string' || !value.trim()) throw new Error(`TOKEN_IDENTITY_CONFIG_MISSING_${field}`);+ return value.trim();+}++export function configuredTokenIdentity(account) {+ return {+ email: required(account?.email, 'EMAIL').toLowerCase(),+ organizationUuid: required(account?.organizationUuid || account?.orgUuid, 'ORGANIZATION_UUID'),+ organizationName: required(+ account?.organizationName || account?.orgName || account?.organization,+ 'ORGANIZATION_NAME',+ ),+ };+}++export async function verifyRefreshedTokenIdentity(account, accessToken, { fetchImpl = globalThis.fetch } = {}) {+ const expected = configuredTokenIdentity(account);+ required(accessToken, 'ACCESS_TOKEN');+ let profile;+ try {+ // The OAuth token is intentionally sent only to Anthropic's fixed profile+ // endpoint to verify the credential's configured account identity.+ // CodeQL[js/file-access-to-http]+ const response = await fetchImpl(PROFILE_ENDPOINT, {+ method: 'GET',+ headers: { Authorization: `Bearer ${accessToken}`, 'anthropic-beta': 'oauth-2025-04-20' },+ signal: AbortSignal.timeout(8_000),+ });+ if (!response?.ok) throw new Error('profile response failed');+ profile = await response.json();+ } catch {+ throw new Error('TOKEN_IDENTITY_PROFILE_FAILED');+ }+ let actual;+ try {+ actual = {+ email: required(profile?.account?.email, 'PROFILE_EMAIL').toLowerCase(),+ organizationUuid: required(profile?.organization?.uuid, 'PROFILE_ORGANIZATION_UUID'),+ organizationName: required(profile?.organization?.name, 'PROFILE_ORGANIZATION_NAME'),+ };+ } catch {+ throw new Error('TOKEN_IDENTITY_PROFILE_FAILED');+ }+ if (+ actual.email !== expected.email ||+ actual.organizationUuid !== expected.organizationUuid ||+ actual.organizationName !== expected.organizationName+ )+ throw new Error('TOKEN_IDENTITY_MISMATCH');+ return actual;+}diff --git a/claude-ops/scripts/account-rotation/vault-linux.mjs b/claude-ops/scripts/account-rotation/vault-linux.mjsindex f6916efd..360051a6 100644--- a/claude-ops/scripts/account-rotation/vault-linux.mjs+++ b/claude-ops/scripts/account-rotation/vault-linux.mjs@@ -14,9 +14,11 @@* deleteEntry(service) → void*/-import { readFileSync, writeFileSync, existsSync, mkdirSync, unlinkSync } from 'fs';+import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'fs';import { createHash } from 'node:crypto';import { join } from 'path';+import { requireWriterCapability } from './auth-writer-coordination.mjs';+import { requireVerifiedCredentialCapability } from './verified-credential-write.mjs';const HOME = process.env.HOME || process.env.USERPROFILE || '/root';export const ACTIVE_SERVICE = 'Claude Code-credentials';@@ -60,6 +62,29 @@ export function readEntry(service) {* All others land in the vault dir as chmod-600 files.*/export function writeEntry(service, json) {+ void service;+ void json;+ throw new Error('GENERIC_CREDENTIAL_WRITE_FORBIDDEN');+}++export function writeEntryCoordinated(service, json, capability) {+ void service;+ void json;+ requireWriterCapability(capability);+ throw new Error('GENERIC_CREDENTIAL_WRITE_FORBIDDEN');+}++export function writeEntryIdentityPreserving(account, service, json, capability, verifiedCapability) {+ const writerCapability = requireVerifiedCredentialCapability(verifiedCapability, {+ account,+ credential: json,+ destination: service,+ });+ if (capability !== undefined && capability !== writerCapability) throw new Error('AUTH_WRITER_CAPABILITY_MISMATCH');+ return writeEntryUnlocked(service, json);+}++function writeEntryUnlocked(service, json) {if (service === ACTIVE_SERVICE) {writeFileSync(ACTIVE_CREDS_PATH, json, { mode: 0o600 });return;@@ -72,9 +97,12 @@ export function writeEntry(service, json) {* Delete a vault entry (no-op for the active-service entry — never delete live creds).*/export function deleteEntry(service) {- if (service === ACTIVE_SERVICE) return;- const p = vaultPath(service);- try {- if (existsSync(p)) unlinkSync(p);- } catch {}+ void service;+ throw new Error('GENERIC_CREDENTIAL_DELETE_FORBIDDEN');+}++export function deleteEntryCoordinated(service, capability) {+ void service;+ requireWriterCapability(capability);+ throw new Error('GENERIC_CREDENTIAL_DELETE_FORBIDDEN');}diff --git a/claude-ops/scripts/account-rotation/verified-credential-write.mjs b/claude-ops/scripts/account-rotation/verified-credential-write.mjsnew file mode 100644index 00000000..ee082677--- /dev/null+++ b/claude-ops/scripts/account-rotation/verified-credential-write.mjs@@ -0,0 +1,94 @@+import { verifyRefreshedTokenIdentity } from './token-identity.mjs';+import { requireWriterCapability, withAuthWriterLock } from './auth-writer-coordination.mjs';++const verifiedCapabilities = new WeakMap();++function exactCredential(credential) {+ if (typeof credential !== 'string') throw new Error('SERIALIZED_CREDENTIAL_REQUIRED');+ return credential;+}++function binding(account, credential, destination) {+ return {+ email: String(account?.email || '')+ .trim()+ .toLowerCase(),+ organizationUuid: String(account?.orgUuid || '').trim(),+ organizationName: String(account?.orgName || '').trim(),+ credential: exactCredential(credential),+ destination: String(destination || ''),+ };+}+function snapshotAccount(account) {+ return Object.freeze({+ email: String(account?.email || '')+ .trim()+ .toLowerCase(),+ orgUuid: String(account?.orgUuid || '').trim(),+ orgName: String(account?.orgName || '').trim(),+ ...(account?.label == null ? {} : { label: String(account.label) }),+ });+}++export function requireVerifiedCredentialCapability(capability, expected) {+ const actual = verifiedCapabilities.get(capability);+ if (!actual) throw new Error('VERIFIED_CREDENTIAL_CAPABILITY_REQUIRED');+ const wanted = binding(expected.account, expected.credential, expected.destination);+ for (const key of Object.keys(wanted))+ if (actual[key] !== wanted[key]) throw new Error('VERIFIED_CREDENTIAL_BINDING_MISMATCH');+ actual.requireCapability(actual.writerCapability);+ verifiedCapabilities.delete(capability);+ return actual.writerCapability;+}++export function extractCredentialAccessToken(value) {+ let parsed;+ try {+ parsed = typeof value === 'string' ? JSON.parse(value) : value;+ } catch {+ throw new Error('TOKEN_IDENTITY_ACCESS_TOKEN_MISSING');+ }+ const token = parsed?.claudeAiOauth?.accessToken;+ if (typeof token !== 'string' || !token.trim()) throw new Error('TOKEN_IDENTITY_ACCESS_TOKEN_MISSING');+ return token.trim();+}++/**+ * Construct the sole boundary allowed to invoke a protected credential writer.+ * The raw writer remains closed over and cannot be called by consumers.+ */+export function createVerifiedCredentialWriter({+ write,+ verify = verifyRefreshedTokenIdentity,+ withLock = withAuthWriterLock,+ requireCapability = requireWriterCapability,+ destination = (_account, _credential, ...writeArgs) => writeArgs[0],+} = {}) {+ if (typeof write !== 'function') throw new TypeError('VERIFIED_CREDENTIAL_WRITER_REQUIRED');+ if (typeof verify !== 'function') throw new TypeError('TOKEN_IDENTITY_VERIFIER_REQUIRED');++ const coordinated = async (account, credential, writerCapability, ...writeArgs) => {+ requireCapability(writerCapability);+ if (typeof credential !== 'string') throw new Error('SERIALIZED_CREDENTIAL_REQUIRED');+ const accountSnapshot = snapshotAccount(account);+ const serializedCredential = credential;+ const destinationSnapshot = String(destination(accountSnapshot, serializedCredential, ...writeArgs));+ const accessToken = extractCredentialAccessToken(serializedCredential);+ await verify(accountSnapshot, accessToken);+ const verifiedCapability = Object.freeze({});+ verifiedCapabilities.set(verifiedCapability, {+ writerCapability,+ requireCapability,+ ...binding(accountSnapshot, serializedCredential, destinationSnapshot),+ });+ try {+ return await write(accountSnapshot, serializedCredential, verifiedCapability, ...writeArgs);+ } finally {+ verifiedCapabilities.delete(verifiedCapability);+ }+ };+ const verifiedCredentialWrite = (account, credential, ...writeArgs) =>+ withLock((writerCapability) => coordinated(account, credential, writerCapability, ...writeArgs));+ verifiedCredentialWrite.coordinated = coordinated;+ return verifiedCredentialWrite;+}diff --git a/claude-ops/scripts/install-account-rotator-linux.sh b/claude-ops/scripts/install-account-rotator-linux.shindex f511be18..d4c62157 100755--- a/claude-ops/scripts/install-account-rotator-linux.sh+++ b/claude-ops/scripts/install-account-rotator-linux.sh@@ -8,7 +8,8 @@# rm ~/.config/systemd/user/claude-account-rotator.service# systemctl --user daemon-reload#-# Usage: bash install-account-rotator-linux.sh [--dry-run]+# Usage: CLAUDE_AUTH_COORDINATION_PLAN=/absolute/reviewed-plan.json \+# CLAUDE_AUTH_COORDINATION_PLAN_DIGEST=<reviewed-digest> bash install-account-rotator-linux.sh [--dry-run]set -euo pipefail@@ -28,8 +29,18 @@ die() { echo "[install-account-rotator] ERROR: $*" >&2; exit 1; }command -v node >/dev/null 2>&1 || die "node not found (need Node 20+)"command -v npx >/dev/null 2>&1 || die "npx not found"+command -v jq >/dev/null 2>&1 || die "jq not found"node --version | grep -qE 'v(2[0-9]|[3-9][0-9])' || die "Node 20+ required (got $(node --version))"[[ -f "$DAEMON_SCRIPT" ]] || die "daemon.mjs not found at $DAEMON_SCRIPT"+: "${CLAUDE_AUTH_COORDINATION_PLAN:?set the absolute reviewed coordination plan path}"+: "${CLAUDE_AUTH_COORDINATION_PLAN_DIGEST:?set the exact reviewed coordination plan digest}"+PREFLIGHT_JSON=$(node "$SCRIPT_DIR/account-rotation/provision-coordination.mjs" preflight \+ --plan "$CLAUDE_AUTH_COORDINATION_PLAN" --expected-digest "$CLAUDE_AUTH_COORDINATION_PLAN_DIGEST") \+ || die "auth coordination preflight failed"+CLAUDE_AUTH_COORDINATION_CONFIG=$(printf '%s' "$PREFLIGHT_JSON" | jq -er '.configPath') || die "invalid preflight config path"+CLAUDE_ROTATOR_CONFIG=$(printf '%s' "$PREFLIGHT_JSON" | jq -er '.runtimeInventoryPath') || die "invalid preflight inventory path"+REVIEWED_UNIT=$(printf '%s' "$PREFLIGHT_JSON" | jq -er '.linuxUnitPath') || die "invalid preflight unit path"+[[ "$REVIEWED_UNIT" == "$UNIT_FILE" ]] || die "reviewed unit destination does not match installer destination"# ── Dry-run validation ────────────────────────────────────────────────────────@@ -46,62 +57,11 @@ log "Dry-run passed (exit $TIMEOUT_EXIT — ok)"# ── Write unit file ───────────────────────────────────────────────────────────-mkdir -p "$(dirname "$UNIT_FILE")"+log "Reviewed unit already provisioned: $UNIT_FILE"-cat > "$UNIT_FILE" <<EOF-# claude-account-rotator.service-# Generated by install-account-rotator-linux.sh — $(date -u +%Y-%m-%dT%H:%M:%SZ)-#-# Purpose : Claude Max account rotation daemon — monitors usage and swaps-# OAuth tokens automatically as 5-hour / 7-day caps approach.-# Platform: Linux (file-based vault in ~/.local/share/claude-rotation/)-# Rollback: systemctl --user disable --now claude-account-rotator.service--[Unit]-Description=Claude Max account rotation daemon-After=network.target--[Service]-Type=simple-ExecStart=$(command -v node) $DAEMON_SCRIPT-Restart=on-failure-RestartSec=30-# Give it 10 s to shut down cleanly before SIGKILL-TimeoutStopSec=10--# Logs-StandardOutput=append:${LOG_FILE}-StandardError=append:${LOG_FILE}--# Environment-Environment=HOME=$HOME-Environment=NODE_ENV=production-Environment=CLAUDE_ROTATOR_KEYCHAIN_ACCOUNT=${CLAUDE_ROTATOR_KEYCHAIN_ACCOUNT:-${USER:-ec2-user}}+# ── Plan-bound activation and health check ───────────────────────────────────-[Install]-WantedBy=default.target-EOF--log "Unit file written: $UNIT_FILE"--# ── Enable & start ────────────────────────────────────────────────────────────--systemctl --user daemon-reload-systemctl --user enable "$SERVICE_NAME"-systemctl --user restart "$SERVICE_NAME"--# ── Health check ─────────────────────────────────────────────────────────────--sleep 2-STATUS=$(systemctl --user is-active "$SERVICE_NAME" 2>&1)-if [[ "$STATUS" == "active" ]]; then- log "READY — ${SERVICE_NAME}.service is active"- systemctl --user status "$SERVICE_NAME" --no-pager -n 5-else- echo ""- log "NEEDS_FIXES — service status: $STATUS"- systemctl --user status "$SERVICE_NAME" --no-pager -n 20- echo ""- log "Remediation: check logs with: journalctl --user -u ${SERVICE_NAME}.service -n 50"- exit 1-fi+node "$SCRIPT_DIR/account-rotation/provision-coordination.mjs" activate-linux \+ --plan "$CLAUDE_AUTH_COORDINATION_PLAN" --expected-digest "$CLAUDE_AUTH_COORDINATION_PLAN_DIGEST" >/dev/null \+ || die "plan-bound systemd activation failed"+log "READY — ${SERVICE_NAME}.service is active"diff --git a/claude-ops/scripts/install-crs-reconcilers-agent.sh b/claude-ops/scripts/install-crs-reconcilers-agent.shindex deb43689..f47c6d8a 100755--- a/claude-ops/scripts/install-crs-reconcilers-agent.sh+++ b/claude-ops/scripts/install-crs-reconcilers-agent.sh@@ -15,10 +15,10 @@ set -euo pipefailPLUGIN_ROOT="${CLAUDE_PLUGIN_ROOT:-$(cd "$(dirname "$0")/.." && pwd)}"[[ -d "$PLUGIN_ROOT" ]] || { echo "error: could not resolve CLAUDE_PLUGIN_ROOT" >&2; exit 1; }+: "${CLAUDE_AUTH_COORDINATION_CONFIG:?set the canonical reviewed coordination config path}"+: "${CLAUDE_ROTATOR_CONFIG:?set the canonical reviewed runtime inventory path}"-USER_CFG="$HOME/.claude/plugins/data/ops-ops-marketplace/account-rotation-config.json"-REPO_CFG="$PLUGIN_ROOT/scripts/account-rotation/config.json"-CFG="$([[ -f "$USER_CFG" ]] && echo "$USER_CFG" || echo "$REPO_CFG")"+CFG="$CLAUDE_ROTATOR_CONFIG"DATA_DIR="${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}"LOG_DIR="$DATA_DIR/logs"@@ -37,6 +37,11 @@ fi[[ "${CRS_TOKEN_REFRESH_ENABLED:-}" == "1" ]] && TOKEN_REFRESH_ENABLED="true"[[ "${CRS_ENABLE_MAGIC_LINK:-}" == "1" ]] && MAGIC_LINK_ENABLED="true"+if [[ "$TOKEN_REFRESH_ENABLED" == "true" ]]; then+ echo "error: CRS 401 refresher is retired; use the identity-verified crs-token-feed service" >&2+ exit 1+fi+if [[ "$COOLDOWN_ENABLED" != "true" && "$TOKEN_REFRESH_ENABLED" != "true" && "$MAGIC_LINK_ENABLED" != "true" ]]; thenecho "skip: none of crs.cooldownEnabled / crs.tokenRefreshEnabled / crs.enableMagicLinkRecovery is true in $CFG"echo " set one (or \$CRS_COOLDOWN_ENABLED=1 / \$CRS_TOKEN_REFRESH_ENABLED=1 / \$CRS_ENABLE_MAGIC_LINK=1) and re-run"@@ -69,9 +74,10 @@ render_and_install() {local host_path="${PATH:-/usr/local/bin:/usr/bin:/bin}"local host_display="${CLAUDE_DESKTOP_DISPLAY:-${DISPLAY:-:0}}"PLIST_TEMPLATE_PATH="$template" WRAPPER_PATH="$wrapper" LOG_DIR_PATH="$LOG_DIR" CRS_HOME="$HOME" \+ AUTH_COORDINATION_CONFIG="$CLAUDE_AUTH_COORDINATION_CONFIG" ROTATOR_CONFIG="$CLAUDE_ROTATOR_CONFIG" \CRS_PATH="$host_path" CRS_DISPLAY="$host_display" \node -e \- 'const fs=require("fs");const e=(s)=>String(s??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""");const t=fs.readFileSync(process.env.PLIST_TEMPLATE_PATH,"utf8");process.stdout.write(t.replace(/__WRAPPER_PATH__/g,e(process.env.WRAPPER_PATH)).replace(/__LOG_DIR__/g,e(process.env.LOG_DIR_PATH)).replace(/__HOME__/g,e(process.env.CRS_HOME)).replace(/__PATH__/g,e(process.env.CRS_PATH||"")).replace(/__DISPLAY__/g,e(process.env.CRS_DISPLAY||":0")));' \+ 'const fs=require("fs");const e=(s)=>String(s??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""");const t=fs.readFileSync(process.env.PLIST_TEMPLATE_PATH,"utf8");process.stdout.write(t.replace(/__WRAPPER_PATH__/g,e(process.env.WRAPPER_PATH)).replace(/__LOG_DIR__/g,e(process.env.LOG_DIR_PATH)).replace(/__HOME__/g,e(process.env.CRS_HOME)).replace(/__PATH__/g,e(process.env.CRS_PATH||"")).replace(/__DISPLAY__/g,e(process.env.CRS_DISPLAY||":0")).replace(/__CLAUDE_AUTH_COORDINATION_CONFIG__/g,e(process.env.AUTH_COORDINATION_CONFIG)).replace(/__CLAUDE_ROTATOR_CONFIG__/g,e(process.env.ROTATOR_CONFIG)));' \> "$dest"launchctl bootout "gui/$(id -u)/com.claude-ops.${name}" 2>/dev/null || truelaunchctl bootstrap "gui/$(id -u)" "$dest"diff --git a/claude-ops/scripts/ops-accounts/providers/claude.mjs b/claude-ops/scripts/ops-accounts/providers/claude.mjsindex 1fc59cca..ad6904b5 100644--- a/claude-ops/scripts/ops-accounts/providers/claude.mjs+++ b/claude-ops/scripts/ops-accounts/providers/claude.mjs@@ -93,19 +93,9 @@ export async function listAccounts(ctx) {export async function reauth(ctx, { accountId }) {const email = accountId;if (!email) return { ok: false, reason: 'email-required' };- const magic = join(rotationDir(ctx), 'rotate-magic.mjs');- if (!existsSync(magic)) {- return { ok: false, reason: 'rotate-magic-missing' };- }- if (ctx.dryRun) return { ok: true, reason: 'dry-run' };- const r = spawnSync(process.execPath, [magic, '--to', email, '--force'], {- encoding: 'utf8',- env: { ...process.env, CLAUDE_PLUGIN_ROOT: ctx.pluginRoot },- timeout: 120000,- });return {- ok: r.status === 0,- reason: r.status === 0 ? null : (r.stderr || r.stdout || '').slice(-400),+ ok: false,+ reason: 'direct-claude-reauth-disabled-use-staged-enrollment',};}diff --git a/claude-ops/scripts/systemd/claude-account-rotation.service b/claude-ops/scripts/systemd/claude-account-rotation.serviceindex 76e184ff..d7338b71 100644--- a/claude-ops/scripts/systemd/claude-account-rotation.service+++ b/claude-ops/scripts/systemd/claude-account-rotation.service@@ -5,6 +5,8 @@ Wants=network-online.target crs-compose.service[Service]Type=simple+PassEnvironment=CLAUDE_AUTH_COORDINATION_CONFIG CLAUDE_ROTATOR_CONFIG+ExecCondition=/bin/sh -c 'test -n "$CLAUDE_AUTH_COORDINATION_CONFIG" && test -n "$CLAUDE_ROTATOR_CONFIG"'# Prefer installed plugin tree; override with EnvironmentFile if needed.Environment=CLAUDE_PLUGIN_ROOT=%h/.claude/plugins/cache/ops-marketplace/ops/currentEnvironment=CLAUDE_ENABLE_FLEET_RECOVERY=0diff --git a/claude-ops/scripts/systemd/crs-token-feed.service b/claude-ops/scripts/systemd/crs-token-feed.serviceindex 14b29484..c63ad8c2 100644--- a/claude-ops/scripts/systemd/crs-token-feed.service+++ b/claude-ops/scripts/systemd/crs-token-feed.service@@ -5,6 +5,8 @@ Wants=crs-compose.service[Service]Type=oneshot+PassEnvironment=CLAUDE_AUTH_COORDINATION_CONFIG CLAUDE_ROTATOR_CONFIG+ExecCondition=/bin/sh -c 'test -n "$CLAUDE_AUTH_COORDINATION_CONFIG" && test -n "$CLAUDE_ROTATOR_CONFIG"'Environment=CRS_BASE=http://127.0.0.1:3005ExecStart=%h/.claude/scripts/account-rotation/crs-token-feed.shStandardOutput=append:%h/.claude/logs/crs-token-feed.systemd.logdiff --git a/claude-ops/skills/ops-accounts/SKILL.md b/claude-ops/skills/ops-accounts/SKILL.mdindex 7233ff84..65dc9d5f 100644--- a/claude-ops/skills/ops-accounts/SKILL.md+++ b/claude-ops/skills/ops-accounts/SKILL.md@@ -34,7 +34,7 @@ for every provider:| Provider | Engine | Reauth | Util ||----------|--------|--------|------|-| Claude | `scripts/account-rotation/rotate.mjs` + `rotate-magic.mjs` | magic-link + captcha cascade | 5h/7d |+| Claude | `scripts/account-rotation/rotate.mjs` + staged enrollment | signed stage/activate only | 5h/7d || Grok | slots + `grok-cli-auth-proxy` (+ optional CRS hop) | device-code + Google (dcli); residential egress cascade | weekly / 429 || OpenAI / Codex | `codex-rotate` when present | OAuth bridge | usage best-effort || Factory | adapter TBD / quota-feed seeds | native | quota-feed patterns |@@ -58,9 +58,9 @@ PLUGIN_ROOT="${CLAUDE_PLUGIN_ROOT:-$(ls -d "$HOME/.claude/plugins/cache/ops-mark| `switch claude` / `rotate-now` | Claude keychain rotate (`force-rotate` / `rotate.mjs`) || `switch grok` | Next SuperGrok seat (`grok-rotate switch`) || `refresh [all\|claude\|grok]` | Keepalive / RT refresh |-| `reauth claude <email>` | `rotate-magic.mjs --to <email>` |+| `reauth claude <email>` | Fails closed with staged-enrollment handoff || `reauth grok <email>` | Device reauth with residential cascade env |-| `setup` / `setup claude` | Full Claude OAuth wizard (former rotate-setup steps) |+| `setup` / `setup claude` | Claude direct auth is disabled; staged enrollment required || `setup grok` | Add/reauth SuperGrok seat || `crs` / `crs-tick` | Optional Claude CRS pool status / one tick || `seats` | Local multi-provider seat-state (no CRS) |diff --git a/claude-ops/skills/ops-rotate-setup/SKILL.md b/claude-ops/skills/ops-rotate-setup/SKILL.mdindex f4f073a6..858b7243 100644--- a/claude-ops/skills/ops-rotate-setup/SKILL.md+++ b/claude-ops/skills/ops-rotate-setup/SKILL.md@@ -1,483 +1,30 @@---name: ops-rotate-setup-description: Alias of /ops:accounts setup for Claude OAuth init wizard. Prefer /ops:accounts setup. CRS optional multi-account LB only.-argument-hint: '[--all|--account <email>|--add|--crs|--standalone]'+description: Fail-closed legacy Claude setup alias that directs operators to separately approved staged enrollment.+argument-hint: ''allowed-tools:- - Bash- Read- - AskUserQuestion-effort: medium-maxTurns: 25+effort: low+maxTurns: 5----> **Alias:** Prefer **`/ops:accounts setup`** (or `/ops:accounts setup claude`).-> This file remains the detailed Claude OAuth wizard. Multi-provider entry is ops-accounts.+# Claude enrollment handoff+Direct Claude browser, OAuth, magic-link, setup, and unattended authentication+are disabled. Do not launch a browser, poll email, invoke `rotate.mjs --setup`,+invoke `rotate-magic.mjs`, modify auth inventory, or suggest an environment+bypass.-## Purpose+Tell the operator to use `scripts/account-rotation/staged-enrollment.mjs` with:-Initialize OAuth tokens for the multi-account Claude rotator system (the-`account-rotation` daemon). For each configured account that does not already-have a valid keychain token, delegate to `rotate.mjs --setup --only=<email>---auto --skip-valid`, which drives the browser-driver cascade (CDP-attach to a-real Chrome → spawn Chrome with a real profile → bundled Chromium), polls Gmail-for the magic link via `gog`, verifies the token, and writes it to the OS-keychain under the schema the daemon/rotator consume: service-`Claude-Rotation-<key>` (key = account `label` or `email`), keychain account-`$USER` (override with `$CLAUDE_ROTATOR_KEYCHAIN_ACCOUNT`), value-`{ "claudeAiOauth": { "accessToken": ... } }`.+1. An owner-only deployment config that pins every trust root and the canonical+ operation lock.+2. A short-lived, separately signed `stage` approval for an externally captured+ CLIProxyAPI Claude auth candidate.+3. External containment of all writers.+4. A distinct `activate` approval bound to the staged digest and attesting+ `writersQuiesced: true`.-> Why delegate: a freshly launched Playwright Chromium is blocked by-> claude.ai's Cloudflare Turnstile (the magic link is never sent), and a-> hand-rolled web-cookie capture writes a credential shape no consumer reads.-> `rotate.mjs` solves both correctly, so `setup-account.mjs` is a thin wrapper-> around it.--Use this skill when:--- You ran `/ops:setup` and skipped the account-rotation step-- You added a new Claude account and need to wire it in-- A keychain entry was rotated/expired and needs re-init-- You want to re-run only the OAuth portion without touching other ops config--## Rules (mandatory)--- **Rule 0**: Never write real emails to any committed file. Account email and- display name come from runtime user input only.-- **Rule 1**: Max 4 options per `AskUserQuestion`. Paginate at 4 with- `[More...]` bridges when listing accounts.-- **Rule 4**: Background by default. The OAuth flow (rotate.mjs browser cascade- - Gmail polling) is long-running; always launch it with- `run_in_background: true` and tail the log.-- Never auto-enable `account_rotation_enabled` after init. The user flips that- switch from `/plugins` settings.--## Step 1 — Load config--```bash-USER_CFG="$HOME/.claude/plugins/data/ops-ops-marketplace/account-rotation-config.json"-REPO_CFG="${CLAUDE_PLUGIN_ROOT}/scripts/account-rotation/config.json"-CFG="$([[ -f "$USER_CFG" ]] && echo "$USER_CFG" || echo "$REPO_CFG")"-jq '.accounts // []' "$CFG"-```--If `accounts` is empty AND no `--add` argument was passed, jump to **Step 2 —-Bootstrap**. Otherwise jump to **Step 3 — Token check**.--## Step 2 — Bootstrap (no accounts configured)--`AskUserQuestion`:--```-No Claude accounts are configured for the rotator yet. Add some now?- [Add now] — collect email/display/plan, then run OAuth- [Use existing keychain] — skip — assume keychain already has tokens- [Skip] — exit, do nothing- [Help] — explain how the rotator works and exit-```--- `[Help]`: print one-paragraph explainer (rotator purpose, where keychain entries live, how `/plugins` toggles `account_rotation_enabled`) and exit.-- `[Use existing keychain]`: print "Looking for `Claude-Rotation-*` entries..." and run `CRED="${CLAUDE_PLUGIN_ROOT}/lib/credential-store.sh"; ACCT="${CLAUDE_ROTATOR_KEYCHAIN_ACCOUNT:-$USER}"; bash "$CRED" backends 2>/dev/null && jq -r '.accounts[] | (.label // .email)' "$CFG" 2>/dev/null | while read -r key; do bash "$CRED" get "Claude-Rotation-$key" "$ACCT" >/dev/null 2>&1 && echo "✓ $key" || echo "✗ $key"; done || echo "(no backends available — re-run with [Add now])"`. Exit.-- `[Skip]`: exit.-- `[Add now]`: enter the **add loop** below.--### Add loop--For each new account:--1. Prompt for **email** (free text). Validate `*@*.*` shape, reject empties.-2. Prompt for **display name** (free text, defaults to email local-part).-3. `AskUserQuestion` for **plan**:- ```- Plan tier for this account?- [Max] — Claude Max ($100/$200 tier)- [Pro] — Claude Pro- [Team] — Team plan seat- [Other] — type a label- ```-4. Append to in-memory accounts list. Then ask:- ```- Account added. Next?- [Add another]- [Done — start OAuth]- [Cancel]- ```--Once `[Done]`, write the new accounts into `$USER_CFG` (create dirs as needed):--```bash-mkdir -p "$(dirname "$USER_CFG")"-jq --argjson new "$NEW_ACCOUNTS_JSON" \- '.accounts = ((.accounts // []) + $new)' \- "$CFG" > "$USER_CFG.tmp" && mv "$USER_CFG.tmp" "$USER_CFG"-```--## Step 3 — Token check--For each account in the merged config, check the keychain under the consumed-schema (service `Claude-Rotation-<key>`, account `$USER`):--```bash-CRED="${CLAUDE_PLUGIN_ROOT}/lib/credential-store.sh"-ACCT="${CLAUDE_ROTATOR_KEYCHAIN_ACCOUNT:-$USER}"-jq -r '.accounts[] | (.label // .email)' "$USER_CFG" | while read -r key; do- if bash "$CRED" get "Claude-Rotation-$key" "$ACCT" >/dev/null 2>&1; then- echo "✓ $key"- else- echo "✗ $key (needs OAuth)"- fi-done-```--If every account is `✓`, print a success line and jump to **Step 5 — Summary**.-(`rotate.mjs --setup ... --skip-valid` also re-checks token validity itself, so-a stale-but-present entry is re-captured during Step 4.)--## Step 4 — OAuth init loop--For each `✗` account, run the setup script in the background and tail its log.--```bash-SCRIPT="${CLAUDE_PLUGIN_ROOT}/scripts/account-rotation/setup-account.mjs"-LOG="$HOME/.claude/logs/account-rotation/setup-${ID}-$(date +%s).log"-mkdir -p "$(dirname "$LOG")"-node "$SCRIPT" \- --email "$EMAIL" \- --display "$ACCOUNT_DISPLAY" \- --plan "$PLAN" \- --account-id "$ID" \- --gmail-poll \- >"$LOG" 2>&1 &-echo "PID=$! LOG=$LOG"-```--- Launch with `run_in_background: true`.-- Use `Monitor` (or `Read` of the log file) to surface progress lines.-- `setup-account.mjs` upserts the account into `$USER_CFG`, then delegates to- `rotate.mjs --setup --only=<email> --auto --skip-valid`, which:- 1. Skips immediately if a valid token already exists (`--skip-valid`).- 2. Runs the browser-driver cascade: attach to a real Chrome on CDP `:9222`- (passes Cloudflare Turnstile) → else spawn Chrome with a real profile →- else bundled Chromium.- 3. Submits the email and polls Gmail via `gog` for the magic link, then- completes login (handling the org chooser).- 4. Verifies the token against `api.anthropic.com/api/oauth/usage`.- 5. Writes it to the keychain as `Claude-Rotation-<key>` (account `$USER`),- value `{ "claudeAiOauth": { "accessToken": ... } }`.-- It emits a single-line JSON result: `{"ok":true,"accountId":...,"email":...}`- on success, or `{"ok":false,...,"error":"oauth_failed"}` on failure.-- **2FA / Google SSO**: some accounts (Google Workspace domains) require an- interactive Google verification that automation cannot complete unattended.- If `rotate.mjs` logs a 2FA / verification prompt or times out, surface the log- to the user and let them complete the login in the cascade's visible Chrome.- Do NOT attempt to auto-solve 2FA.--After each account completes (success or failure):--```-Result for <email>:- [✓ Success — continue with next] ← only if more remain- [✗ Failed — view log and retry]- [Stop here]-```--If success and no more accounts remain, jump to **Step 5**.--## Step 4.4 — CRS detection (optional enhancement — never required)--**CRS is not required for rotate-magic or the keychain rotator.**--- **Standalone rotate-magic** (recommended for single/few accounts): captures- and refreshes one account at a time via `rotate.mjs` / `rotate-magic.mjs`- (magic-link + captcha cascade). Enough when you are not spreading load across- a large pool.-- **CRS** (claude-relay-service): multi-account **load balancing / rate-limit- spreading** — one relay endpoint, many seats, `schedulable` flags. Useful- mainly when you hit 429s with multi-account traffic.--### Detect CRS (env-templated; no host hardcodes)--Run detection before offering install. Any hit = "CRS likely present":--```bash-CRS_DETECTED=0-# binary on PATH-command -v crs >/dev/null 2>&1 && CRS_DETECTED=1-# common compose / service names (user-space; ignore if missing)-systemctl --user is-active crs-compose.service >/dev/null 2>&1 && CRS_DETECTED=1-# config already enabled-CFG="${USER_CFG:-$HOME/.claude/plugins/data/ops-ops-marketplace/account-rotation-config.json}"-[[ -f "$CFG" ]] && jq -e '.crs.enabled == true' "$CFG" >/dev/null 2>&1 && CRS_DETECTED=1-# optional env base URL responds-CRS_URL="${CRS_BASE_URL:-${CRS_URL:-http://127.0.0.1:3000}}"-curl -fsS --max-time 2 "$CRS_URL/health" >/dev/null 2>&1 && CRS_DETECTED=1-echo "CRS_DETECTED=$CRS_DETECTED"-```--### Branch--**If CRS detected (`CRS_DETECTED=1`)** — offer wire-in as optional enhancement:--```-CRS looks installed or already configured. Wire ops-rotate to it for multi-account-rate-limit load balancing? (Not required for standalone rotate-magic.)- [Wire CRS] — continue to Step 4.5 (priority daemon + reconcilers)- [Standalone] — keychain + rotate-magic only; leave CRS alone- [Skip] — neither; finish summary- [What is CRS?] — short explainer, then re-ask-```--**If CRS not detected** — explain + choose path:--```-CRS (claude-relay-service) was not detected.--What it is: multi-account load balancing / rate-limit spreading across a relay-pool. Useful mainly when you hit rate limits with many accounts.--Standalone rotate-magic targets one account at a time and is enough for most-users (single seat or a few seats with the keychain rotator).-- [Use rotate-magic standalone (Recommended for single/few accounts)]- [Install CRS] — open CRS install docs / print next steps; do not block OAuth- [Skip] — finish without CRS-```--- **[Use rotate-magic standalone]**: print that OAuth tokens from Steps 3–4 are- enough; captcha cascade is in `scripts/account-rotation/CAPTCHA-CASCADE.md`.- Jump to **Step 5 — Summary** (CRS lines = not configured). Do **not** run- Steps 4.5–4.7 unless the user later passes `--crs`.-- **[Install CRS]**: print a short pointer to upstream CRS install (docker- compose / project README), note that after install they can re-run- `/ops:rotate-setup --crs`. Do not hard-fail if they never install. Then offer- to continue OAuth summary or exit.-- **[Skip]**: same as standalone for this wizard — jump to Step 5.-- **[Wire CRS]** / **[What is CRS?]**: continue into Step 4.5 as today.--`--standalone` argument: force the standalone branch (skip 4.5–4.7).-`--crs` argument: skip detection ask; jump to Step 4.5 (existing behavior).--## Step 4.5 — CRS relay-pool priority daemon (optional)--Only when the user chose **Wire CRS** / **Install CRS** completed / `--crs`, or-detection found CRS and they opted in. Install the **priority daemon** that-auto-deprioritizes near-maxed accounts and re-enables them on recovery. This is-independent of the keychain rotator — skip for keychain-only setups.--`AskUserQuestion` (if not already answered in 4.4):--```-Configure CRS pool auto-prioritization?- [Yes — configure + install] — set base URL + admin creds, install the 120s daemon- [Not now] — skip (you can run /ops:rotate-setup --crs later)- [What is this?] — one-paragraph explainer, then re-ask-```--On **[Yes]**:--1. **Base URL + admin user.** Ask for the CRS base URL (default- `http://127.0.0.1:3000`) and admin username (default `cradmin`). Write them- into the rotator config's `crs` block (create from `config.example.json` if- missing), and set `crs.enabled=true`:- ```bash- CFG="$USER_CFG"- jq --arg url "$CRS_URL" --arg u "$CRS_USER" \- '.crs = ((.crs // {}) + {enabled:true, baseUrl:$url, adminUser:$u})' \- "$CFG" > "$CFG.tmp" && mv "$CFG.tmp" "$CFG"- ```-2. **Admin password → credential store** (never written to config). Ask the user- to paste the CRS admin password, then:- ```bash- CRED="${CLAUDE_PLUGIN_ROOT}/lib/credential-store.sh"- ACCT="${CLAUDE_ROTATOR_KEYCHAIN_ACCOUNT:-$USER}"- printf '%s' "$CRS_ADMIN_PW" | bash "$CRED" set-stdin "CRS-Admin-$CRS_USER" "$ACCT"- ```- (The CRS admin password is printed once in the container's- `data/init.json` — `adminUsername`/`adminPassword` — on first boot.)-3. **Smoke-test before installing.** Confirm the creds + reachability with a- dry-run tick (no writes):- ```bash- bash "${CLAUDE_PLUGIN_ROOT}/scripts/account-rotation/crs-priority-daemon.sh" --status- ```- If it errors (login failed / unreachable), surface the message and let the- user re-enter creds — do NOT install a broken daemon.-4. **Install the timer** (background-friendly):- ```bash- bash "${CLAUDE_PLUGIN_ROOT}/scripts/install-crs-priority-agent.sh"- ```- macOS → launchd every 120s (RunAtLoad fires the first tick). Linux → the- installer prints the equivalent systemd-timer snippet.--Tuning (optional, `crs` block): `off5h`/`off7d` (deprioritize thresholds),-`on5h`/`on7d` (re-enable thresholds, hysteresis), `floor` (min usable accounts),-`freshMinutes` (max age of utilization data trusted for proactive deprioritize).--Weekly-cap reconciliation (`crs.weeklyReconcile`, default on) is built into the-priority daemon itself — no separate install step. It clears a stale-`weeklyRateLimitEndAt` hold once live 7d utilization drops back under `on7d`,-and is a no-op on any deployment that never sets that field. Set-`crs.weeklyReconcile=false` (or `$CRS_WEEKLY_RECONCILE=0`) to disable it.--## Step 4.6 — CRS reconciler add-ons (optional)--Only offer this if Step 4.5 configured a CRS pool (`crs.enabled=true`) — these-reconcilers assume one exists. Two independent, opt-in daemons close gaps the-priority daemon (Step 4.5) doesn't cover:--- **429-cooldown**: holds an account out of rotation only on a real- `rateLimitStatus.isRateLimited=true` from CRS (never a utilization- heuristic). Fast cadence (60s) since it reacts to a live rate limit.-- **401-refresher**: proactively refreshes each account's CRS-pool OAuth- token before it expires, so accounts don't silently start 401ing between- priority-daemon ticks. Slower cadence (300s) — refreshes ahead of a 30min- expiry window.--`AskUserQuestion`:--```-Enable the optional CRS reconcilers?- [Both] — 429-cooldown + 401-refresher (recommended if you run a busy pool)- [429-cooldown only] — fast rate-limit hold, skip proactive token refresh- [401-refresher only] — proactive token refresh, skip rate-limit hold- [Skip] — neither (you can re-run /ops:rotate-setup --crs later)-```--On anything but `[Skip]`:--1. **Write the config flags.**- ```bash- CFG="$USER_CFG"- jq --argjson cooldown "$COOLDOWN_ENABLED" --argjson tokenRefresh "$TOKEN_REFRESH_ENABLED" \- '.crs = ((.crs // {}) + {cooldownEnabled:$cooldown, tokenRefreshEnabled:$tokenRefresh})' \- "$CFG" > "$CFG.tmp" && mv "$CFG.tmp" "$CFG"- ```- (`$COOLDOWN_ENABLED`/`$TOKEN_REFRESH_ENABLED` are `true`/`false` per the- selection above.) Optional: also ask for `crs.stateDir`/`crs.logDir` if the- user wants non-default paths — see `config.example.json` for the full- annotated schema. Both reconcilers default to- `<plugin-data-dir>/account-rotation` if left unset.--2. **Smoke-test before installing** (each enabled reconciler, no writes):- ```bash- [[ "$COOLDOWN_ENABLED" == "true" ]] && node "${CLAUDE_PLUGIN_ROOT}/scripts/account-rotation/crs-429-cooldown.mjs" --status- [[ "$TOKEN_REFRESH_ENABLED" == "true" ]] && node "${CLAUDE_PLUGIN_ROOT}/scripts/account-rotation/crs-401-refresher.mjs" --status- ```- If either errors (login failed / unreachable), surface the message and let- the user re-check Step 4.5's CRS creds — do NOT install a broken daemon.--3. **Install** (idempotent — installs whichever flags are true, uninstalls- whichever were turned back off):- ```bash- bash "${CLAUDE_PLUGIN_ROOT}/scripts/install-crs-reconcilers-agent.sh"- ```- macOS → launchd, 60s / 300s cadence (RunAtLoad fires the first tick).- Linux → the installer prints the equivalent systemd-timer snippets.--## Step 4.7 — Magic-link autoloop (optional, unattended re-auth)--Only offer this if Step 4.6's 401-refresher was enabled — this reconciler-reads its needs-reauth flags. Unlike the other reconcilers, this one-dispatches a REAL browser-based re-auth attempt (via `rotate.mjs --setup`,-the same Gmail-via-`gog` flow this wizard itself uses in Step 4) — make sure-the user understands that before enabling it.--`AskUserQuestion`:--```-Enable unattended re-auth for accounts with a confirmed dead token?- [Yes — enable] — magic-link-autoloop dispatches rotate.mjs --setup automatically- [Not now] — a human handles re-auth manually when 401-refresher flags an account- [What is this?] — one-paragraph explainer, then re-ask-```--On **[Yes]**:--1. **Write the config flag.**- ```bash- CFG="$USER_CFG"- jq '.crs = ((.crs // {}) + {enableMagicLinkRecovery:true})' \- "$CFG" > "$CFG.tmp" && mv "$CFG.tmp" "$CFG"- ```- Optional: ask for a non-default `crs.magicLinkRetryCooldownMs` (default 6h) —- see `config.example.json`.--2. **Smoke-test** (no writes, no dispatch):- ```bash- node "${CLAUDE_PLUGIN_ROOT}/scripts/account-rotation/magic-link-autoloop.mjs" --status- ```--3. **Install** (folded into the same idempotent installer as Step 4.6):- ```bash- bash "${CLAUDE_PLUGIN_ROOT}/scripts/install-crs-reconcilers-agent.sh"- ```- macOS → launchd, 600s cadence, `RunAtLoad=false` (does NOT fire immediately- on install, unlike the other reconcilers — first tick waits for the normal- schedule so a fresh install never triggers a surprise browser launch).- Linux → the installer prints the equivalent systemd-timer snippet.--Note on provider scope: this reconciler's own logic (which account, when, how-often) has no email-provider dependency — it only decides what to retry and-delegates the actual OAuth+email-poll work to `rotate.mjs --setup`, which is-Gmail-via-`gog` today. A fully provider-agnostic email backend (e.g. IMAP)-would be a `rotate.mjs`-internals change, out of scope here.--## Step 5 — Summary--```-━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━- OPS ► ROTATE-SETUP COMPLETE-━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━- Accounts initialized:- ✓ <id> (<plan>)- ✓ <id> (<plan>)- ✗ <id> (failed — re-run /ops:rotate-setup --account <email>)-- Config: ~/.claude/plugins/data/ops-ops-marketplace/account-rotation-config.json- Keychain: Claude-Rotation-<key> (account: $USER) · key = label or email- Mode: standalone rotate-magic | CRS pool wired- CRS priority daemon: ✓ installed (every 120s) | ✗ not configured (optional)- CRS 429-cooldown: ✓ installed (every 60s) | ✗ not enabled (optional)- CRS 401-refresher: ✓ installed (every 300s) | ✗ not enabled (optional)- Magic-link autoloop: ✓ installed (every 600s) | ✗ not enabled (optional)-- Standalone reauth (no CRS): node $CLAUDE_PLUGIN_ROOT/scripts/account-rotation/rotate-magic.mjs --to <email>-- To enable automatic keychain rotation, open /plugins → claude-ops → settings and- toggle "Multi-account Claude rotator" (account_rotation_enabled).-──────────────────────────────────────────────────────-```--(Show CRS daemon lines as `not configured (optional)` when Step 4.4 chose-standalone/skip. Show installed only if 4.5–4.7 ran. All four CRS daemons are-independent of `account_rotation_enabled` — each is gated by its own config flag-(`crs.enabled`, `crs.cooldownEnabled`, `crs.tokenRefreshEnabled`,-`crs.enableMagicLinkRecovery`) plus whether its launchd/systemd timer is-installed. **Never treat missing CRS as setup failure.**)--Exit. Do NOT auto-enable `account_rotation_enabled` — that decision belongs-to the user, made explicitly through the plugin settings UI.--## Argument handling--- `--all` (default): full wizard as described above (includes Step 4.4 CRS detection).-- `--account <email>`: skip Step 2; only init the matching account.-- `--add`: skip token check; jump straight to Step 2 add loop, then init.-- `--standalone`: after OAuth (or immediately if tokens already valid), force standalone rotate-magic path — skip Steps 4.5–4.7.-- `--crs`: jump straight to **Step 4.5** (configure + install the CRS priority daemon), then **Step 4.6** (offer the reconciler add-ons), skipping the keychain-account OAuth steps.-- `--reconcilers`: jump straight to **Step 4.6** (offer/reconfigure the 429-cooldown and 401-refresher reconcilers, then Step 4.7's magic-link autoloop offer) — requires Step 4.5 already configured (`crs.enabled=true`); if not, print the same message as `--crs` needing configuration first and exit.--## Failure modes--| Symptom | Cause | Action |-| ------------------------------------ | -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- |-| `oauth_failed` (rotate.mjs exit ≠ 0) | login did not complete — Turnstile, Google SSO/2FA, or timeout | Open `$LOG` + `rotation.log`; if the cascade is waiting on a visible Chrome, let the user finish login there, then re-run |-| `playwright install failed` | npm offline / sandbox | Run `npx playwright install chromium` in `${CLAUDE_PLUGIN_ROOT}/scripts/account-rotation`, then retry |-| token still `✗` after success | account `label`/`email` mismatch vs config | Confirm the config `key` (`label // email`) matches the `Claude-Rotation-<key>` service name |-| no CDP browser available | no Chrome on `:9222` and none installed | rotate.mjs falls back to bundled Chromium, which Turnstile may block — install/launch Chrome so the cascade can attach |-| Google SSO / 2FA prompt | Workspace-domain account needs interactive Google login | Let the user complete login in the cascade's visible Chrome; do NOT auto-solve 2FA |-| CRS `--status` "login failed" | wrong admin user/password or CRS not reachable | Re-enter creds (Step 4.5); admin creds are in the CRS container `data/init.json`; verify `curl $CRS_URL/health` |-| CRS daemon installed but no effect | `crs.enabled=false`, or all accounts already correctly flagged | Check `crs.enabled` in config; `tail logs/crs-priority.log`; a steady-state tick logs `0 change(s)` |-| CRS reconciler `--status` errors | wrong admin creds or CRS unreachable (same creds as priority daemon) | Re-check Step 4.5's CRS creds; `curl $CRS_URL/health` |-| CRS reconciler installed but no effect | `crs.cooldownEnabled`/`crs.tokenRefreshEnabled` false, or no account currently needs it | Check the relevant flag in config; `tail logs/crs-429-cooldown.log` or `crs-401-refresher.log` — both are safe no-ops when nothing needs action |-| magic-link-autoloop never dispatches | `crs.enableMagicLinkRecovery` false, 401-refresher not enabled/hasn't flagged anyone, or account is on `magicLinkRetryCooldownMs` cooldown | `node magic-link-autoloop.mjs --status`; confirm 401-refresher is enabled and has a `needsReauth` entry |-| magic-link-autoloop dispatches too often | `magicLinkRetryCooldownMs` too low for a persistently-broken account | Raise the cooldown in config; each attempt is a real browser-automation run, not free |+The attestation records operator confirmation; it does not stop services or+contain writers itself. This skill does not sign approvals or perform either+operation on the operator's behalf.diff --git a/claude-ops/templates/com.claude-ops.account-rotation.plist b/claude-ops/templates/com.claude-ops.account-rotation.plistindex 135748b7..7d183d9f 100644--- a/claude-ops/templates/com.claude-ops.account-rotation.plist+++ b/claude-ops/templates/com.claude-ops.account-rotation.plist@@ -2,7 +2,7 @@<!--Multi-account Claude Max rotation daemon (claude-ops plugin).- This file is a TEMPLATE. The setup wizard substitutes ${HOME} and installs+ This file is a TEMPLATE. The reviewed coordination provisioner renders absolute paths and installsthe rendered copy to ~/Library/LaunchAgents/com.claude-ops.account-rotation.plistbefore running:@@ -37,6 +37,10 @@<string>1</string><key>HOME</key><string>${HOME}</string>+ <key>CLAUDE_AUTH_COORDINATION_CONFIG</key>+ <string>__CLAUDE_AUTH_COORDINATION_CONFIG__</string>+ <key>CLAUDE_ROTATOR_CONFIG</key>+ <string>__CLAUDE_ROTATOR_CONFIG__</string></dict><key>RunAtLoad</key>diff --git a/claude-ops/templates/com.claude-ops.crs-401-refresher.plist b/claude-ops/templates/com.claude-ops.crs-401-refresher.plistindex c921d69c..d3953c8f 100644--- a/claude-ops/templates/com.claude-ops.crs-401-refresher.plist+++ b/claude-ops/templates/com.claude-ops.crs-401-refresher.plist@@ -47,6 +47,10 @@<string>__HOME__</string><key>NODE_NO_WARNINGS</key><string>1</string>+ <key>CLAUDE_AUTH_COORDINATION_CONFIG</key>+ <string>__CLAUDE_AUTH_COORDINATION_CONFIG__</string>+ <key>CLAUDE_ROTATOR_CONFIG</key>+ <string>__CLAUDE_ROTATOR_CONFIG__</string></dict><key>ProcessType</key>diff --git a/claude-ops/tests/run-all.sh b/claude-ops/tests/run-all.shindex edf52d7f..47bc32e2 100755--- a/claude-ops/tests/run-all.sh+++ b/claude-ops/tests/run-all.sh@@ -39,6 +39,8 @@ run_suite "$TESTS_DIR/test-bin-scripts.sh"run_suite "$TESTS_DIR/test-hooks.sh"run_suite "$TESTS_DIR/test-specialist-agent-swap.sh"run_suite "$TESTS_DIR/test-rotate-cliproxy-integration.sh"+run_suite "$TESTS_DIR/test-staged-enrollment.sh"+run_suite "$TESTS_DIR/test-coordination-provisioning.sh"run_suite "$TESTS_DIR/test-template.sh"run_suite "$TESTS_DIR/test-claude-md.sh"run_suite "$TESTS_DIR/test-no-secrets.sh"diff --git a/claude-ops/tests/test-coordination-provisioning.sh b/claude-ops/tests/test-coordination-provisioning.shnew file mode 100755index 00000000..71298417--- /dev/null+++ b/claude-ops/tests/test-coordination-provisioning.sh@@ -0,0 +1,4 @@+#!/usr/bin/env bash+set -euo pipefail+ROOT="$(cd "$(dirname "$0")/.." && pwd)"+node "$ROOT/scripts/account-rotation/__tests__/coordination-provisioning.test.mjs"diff --git a/claude-ops/tests/test-rotate-cliproxy-integration.sh b/claude-ops/tests/test-rotate-cliproxy-integration.shindex 7bc00627..c5f14e29 100755--- a/claude-ops/tests/test-rotate-cliproxy-integration.sh+++ b/claude-ops/tests/test-rotate-cliproxy-integration.sh@@ -1,28 +1,75 @@#!/usr/bin/env bashset -euo pipefailROOT="$(cd "$(dirname "$0")/.." && pwd)"-SRC="$ROOT/scripts/account-rotation/rotate.mjs"-pass=0-fail=0-check() {- local name="$1" pattern="$2"- if grep -Fq "$pattern" "$SRC"; then- echo "PASS: $name"- pass=$((pass+1))- else- echo "FAIL: $name"- fail=$((fail+1))- fi+node --input-type=module - "$ROOT" <<'NODE'+import assert from 'node:assert/strict';+import { pathToFileURL } from 'node:url';+import { join } from 'node:path';+import { existsSync, mkdtempSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { spawnSync } from 'node:child_process';++const root = process.argv[2];+const policy = await import(pathToFileURL(join(root, 'scripts/account-rotation/auto-auth-policy.mjs')));++assert.equal(policy.directOAuthWriterAllowed('cliproxy'), false);+assert.equal(policy.directOAuthWriterAllowed('unknown'), false);+assert.equal(policy.directOAuthWriterAllowed('claude-code'), false);+assert.equal(policy.directOAuthWriterAllowed('manual-setup'), false);+assert.equal(policy.directOAuthWriterAllowed('magic-link'), false);+assert.equal(policy.directOAuthWriterAllowed(), false);+assert.equal(policy.automatedAuthAllowed(), false);+assert.equal(policy.automatedAuthAllowed({}), false);+assert.equal(policy.automatedAuthAllowed({ automatedCredentialMutation: false }), false);+assert.equal(policy.automatedAuthAllowed({ automatedCredentialMutation: true }), false);+assert.equal(policy.automatedAuthAllowed({ automatedCredentialMutation: true, autoAuthDisabled: true }), false);++// Default-denied refresh performs no OAuth request subprocess and leaves the+// credential vault byte-identical, even for an otherwise configured account.+const temp = mkdtempSync(join(tmpdir(), 'default-denied-refresh-'));+const bin = join(temp, 'bin');+mkdirSync(bin);+const subprocessMarker = join(temp, 'auth-subprocess-spawned');+for (const name of ['security', 'claude']) {+ writeFileSync(join(bin, name), `#!/bin/sh\necho spawned > ${JSON.stringify(subprocessMarker)}\nexit 91\n`, { mode: 0o700 });}+const config = join(temp, 'config.json');+const vault = join(temp, 'vault.json');+writeFileSync(config, JSON.stringify({ accounts: [{ email: '[email protected]', orgUuid: 'org', orgName: 'Org' }] }));+const original = Buffer.from('{\n "[email protected]": "opaque-credential-bytes"\n}\n');+writeFileSync(vault, original, { mode: 0o600 });+const denied = spawnSync(process.execPath, [join(root, 'scripts/account-rotation/refresh-tokens.mjs')], {+ encoding: 'utf8',+ env: {+ ...process.env,+ HOME: temp,+ PATH: `${bin}:${process.env.PATH}`,+ CLAUDE_ROTATOR_CONFIG: config,+ CLAUDE_ROTATION_FILE_VAULT: vault,+ CLAUDE_ROTATION_SKIP_CRS_SYNC: '1',+ },+});+assert.equal(denied.status, 0, denied.stderr);+assert.deepEqual(readFileSync(vault), original);+assert.equal(denied.stdout.includes('automatic credential mutation not approved'), true);+assert.equal(existsSync(subprocessMarker), false);-check "CLIProxyAPI is the canonical OAuth writer" "spawn(CLIPROXYAPI_BINARY, ['-config', CLIPROXYAPI_CONFIG, '-claude-login']"-check "forwarded Anthropic magic-link subject is supported" "from:anthropic (subject:\"secure link\" OR subject:\"Claude.ai\") newer_than:10m"-check "OAuth waiter renews after magic-link login" "Renewed OAuth waiter after login; callback port"-check "renewal is invoked at OAuth consent boundary" "Consent boundary using renewed OAuth writer"-check "canonical auth mutation is required" "OAuth page succeeded but matching canonical auth JSON did not mutate"-check "successful rotation triggers one-way replica sync" "One-way replica sync completed"-check "legacy keychain is skipped in CLIProxy mode" "!lastBrowserOAuthUsedCliProxy) saveCurrentToken(account)"+// Setup and magic-link entrypoints refuse before config/runtime reads and+// before an executable can mutate the canonical Claude credential.+for (const authArg of ['--setup', '--magic-link']) {+ const setupMarker = join(temp, `setup-${authArg.slice(2)}-spawned`);+ writeFileSync(join(bin, 'claude'), `#!/bin/sh\necho spawned > ${JSON.stringify(setupMarker)}\nexit 91\n`, { mode: 0o700 });+ const before = readFileSync(vault);+ const setup = spawnSync(process.execPath, [join(root, 'scripts/account-rotation/rotate.mjs'), authArg], {+ encoding: 'utf8',+ env: { ...process.env, HOME: temp, PATH: `${bin}:${process.env.PATH}`, CLAUDE_ROTATION_FILE_VAULT: vault },+ });+ assert.equal(setup.status, 2, setup.stderr);+ assert.match(setup.stderr, /authentication is disabled/);+ assert.equal(existsSync(setupMarker), false);+ assert.deepEqual(readFileSync(vault), before);+}-printf 'Results: %d passed, %d failed\n' "$pass" "$fail"-(( fail == 0 ))+console.log('CLIProxy direct-writer policy tests: PASS');+NODEdiff --git a/claude-ops/tests/test-staged-enrollment.sh b/claude-ops/tests/test-staged-enrollment.shnew file mode 100755index 00000000..aa0c38b0--- /dev/null+++ b/claude-ops/tests/test-staged-enrollment.sh@@ -0,0 +1,4 @@+#!/usr/bin/env bash+set -euo pipefail+ROOT="$(cd "$(dirname "$0")/.." && pwd)"+node "$ROOT/scripts/account-rotation/__tests__/staged-enrollment.test.mjs"