@airctrl/cli 0.0.0-stage → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2006 -2
- package/dist/cli-error.js +29 -0
- package/dist/cli.js +502 -0
- package/dist/config.js +102 -0
- package/dist/deadline.js +13 -0
- package/dist/gateway-commands.js +482 -0
- package/dist/group-commands.js +92 -0
- package/dist/identity-rotation.js +550 -0
- package/dist/index.js +21 -0
- package/dist/migrate.js +232 -0
- package/dist/parser.js +120 -0
- package/dist/pat-expired.js +31 -0
- package/dist/project-commands.js +121 -0
- package/dist/prompt.js +45 -0
- package/dist/record-commands.js +312 -0
- package/dist/resolve-client.js +160 -0
- package/dist/resolve-status-principal.js +69 -0
- package/dist/sa-commands.js +1485 -0
- package/dist/service-account-read-commands.js +38 -0
- package/dist/store/atomic-write.js +344 -0
- package/dist/store/base-url.js +71 -0
- package/dist/store/canonical.js +45 -0
- package/dist/store/durable-delete.js +86 -0
- package/dist/store/errors.js +25 -0
- package/dist/store/fsops.js +94 -0
- package/dist/store/handoff-store.js +183 -0
- package/dist/store/identity-rotation-journal.js +396 -0
- package/dist/store/index.js +20 -0
- package/dist/store/lock.js +294 -0
- package/dist/store/names.js +52 -0
- package/dist/store/paths.js +219 -0
- package/dist/store/profile-store.js +262 -0
- package/dist/store/receipt-store.js +75 -0
- package/dist/store/resolve-principal.js +125 -0
- package/dist/store/rotation-store.js +66 -0
- package/dist/store/schema.js +554 -0
- package/package.json +42 -4
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* U9b-2 · Injectable filesystem operations (§10.b #3/#4 fault-injection).
|
|
3
|
+
*
|
|
4
|
+
* Production uses REAL_FS (Node stdlib, no new deps). Tests pass a wrapper that fails a chosen
|
|
5
|
+
* op to exercise the real atomicCreate/atomicReplace/lock crash paths (partial write, fsync
|
|
6
|
+
* failure, link/rename errors, post-commit chmod/fsync/unlink, reconcile mismatch) WITHOUT
|
|
7
|
+
* changing the public API — every entry point defaults `fs` to REAL_FS.
|
|
8
|
+
*
|
|
9
|
+
* U9b-3a-bis (§10.c#16): `lstat` distinguishes a REGULAR file from special inodes (`kind:'file'`
|
|
10
|
+
* vs `'special'`); `fsyncDir` returns a DISCRIMINATED result (`durable|unsupported|failed`) instead
|
|
11
|
+
* of a boolean so a Windows-capability limitation is never conflated with a real POSIX failure; and
|
|
12
|
+
* `posixPermissions` declares whether POSIX permission bits are enforced/meaningful on this platform
|
|
13
|
+
* (used to classify a managed secret file as `secured` vs Windows `best_effort`).
|
|
14
|
+
*/
|
|
15
|
+
import { chmodSync, closeSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeSync } from 'node:fs';
|
|
16
|
+
const IS_WIN32 = process.platform === 'win32';
|
|
17
|
+
// U9b-3c §10.c#16.F/D1: the SINGLE source of the directory-fsync capability. Consumed by BOTH `makeFsyncDir`
|
|
18
|
+
// (whether it attempts open/fsync/close at all) AND `REAL_FS.directoryFsyncSupported` (what `evidenceSecure`
|
|
19
|
+
// cross-checks the `directory` axis against) — one constant, so declared-capability and impl never drift.
|
|
20
|
+
// `posixPermissions` derives from the same `IS_WIN32` but is a SEPARATE capability (not aliased): a POSIX FS
|
|
21
|
+
// without demonstrable dir-fsync is representable by injecting the two bits independently in tests.
|
|
22
|
+
const DIRECTORY_FSYNC_SUPPORTED = !IS_WIN32;
|
|
23
|
+
/**
|
|
24
|
+
* U9b-3a-bis (§10.c#16, F3): testable directory-fsync factory. `directoryFsyncSupported` is a CAPABILITY —
|
|
25
|
+
* when false (win32) it returns `unsupported` WITHOUT calling open/fsync/close (no attempted-op error to
|
|
26
|
+
* misclassify). When true it opens the dir, fsyncs it, and closes it: durability is affirmed ONLY when open,
|
|
27
|
+
* fsync AND close all succeed — a `close` failure (like an open/fsync failure) yields `failed`. `close` is
|
|
28
|
+
* attempted exactly once, only when the open succeeded. No errno/path ever escapes.
|
|
29
|
+
*/
|
|
30
|
+
export function makeFsyncDir(deps) {
|
|
31
|
+
return (dir) => {
|
|
32
|
+
if (!deps.directoryFsyncSupported)
|
|
33
|
+
return 'unsupported'; // capability: NO open/fsync/close attempted
|
|
34
|
+
let fd;
|
|
35
|
+
try {
|
|
36
|
+
fd = deps.openSync(dir, 'r');
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
return 'failed'; // never opened → nothing to close
|
|
40
|
+
}
|
|
41
|
+
let flushed = true;
|
|
42
|
+
try {
|
|
43
|
+
deps.fsyncSync(fd);
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
flushed = false;
|
|
47
|
+
}
|
|
48
|
+
let closed = true;
|
|
49
|
+
try {
|
|
50
|
+
deps.closeSync(fd); // exactly once (open succeeded)
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
closed = false;
|
|
54
|
+
}
|
|
55
|
+
return flushed && closed ? 'durable' : 'failed'; // NOT durable until close succeeds
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
const realFsyncDir = makeFsyncDir({ directoryFsyncSupported: DIRECTORY_FSYNC_SUPPORTED, openSync, fsyncSync, closeSync });
|
|
59
|
+
function realLstat(path) {
|
|
60
|
+
try {
|
|
61
|
+
const st = lstatSync(path);
|
|
62
|
+
// symlink FIRST (lstat does not follow); then directory; then REGULAR file; else special (FIFO/socket/device).
|
|
63
|
+
const kind = st.isSymbolicLink()
|
|
64
|
+
? 'symlink'
|
|
65
|
+
: st.isDirectory()
|
|
66
|
+
? 'directory'
|
|
67
|
+
: st.isFile()
|
|
68
|
+
? 'file'
|
|
69
|
+
: 'special';
|
|
70
|
+
return { kind, mode: st.mode };
|
|
71
|
+
}
|
|
72
|
+
catch (e) {
|
|
73
|
+
if (e && typeof e === 'object' && e.code === 'ENOENT')
|
|
74
|
+
return { kind: 'absent', mode: 0 };
|
|
75
|
+
throw e; // a non-ENOENT lstat failure is mapped to a stable code by the caller (paths.ts)
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
export const REAL_FS = {
|
|
79
|
+
openSync,
|
|
80
|
+
writeSync,
|
|
81
|
+
fsyncSync,
|
|
82
|
+
closeSync,
|
|
83
|
+
chmodSync,
|
|
84
|
+
linkSync,
|
|
85
|
+
renameSync,
|
|
86
|
+
unlinkSync,
|
|
87
|
+
readFileSync: (path) => readFileSync(path, 'utf8'),
|
|
88
|
+
lstat: realLstat,
|
|
89
|
+
mkdir: (path, mode) => mkdirSync(path, { mode }),
|
|
90
|
+
fsyncDir: realFsyncDir,
|
|
91
|
+
posixPermissions: !IS_WIN32,
|
|
92
|
+
// SAME source as `makeFsyncDir` above (DIRECTORY_FSYNC_SUPPORTED) — declared-capability ≡ impl, no drift.
|
|
93
|
+
directoryFsyncSupported: DIRECTORY_FSYNC_SUPPORTED,
|
|
94
|
+
};
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* U9b-3a · Handoff store at `<root>/.airctrl/sa/handoffs/<id>.json` (§10.c#14).
|
|
3
|
+
*
|
|
4
|
+
* PROTOCOL-AGNOSTIC: knows nothing about HTTP/SDK. TWO exact shapes selected by structural presence
|
|
5
|
+
* (no persisted discriminator): a PROVISIONAL handoff is written 0600 before the authorize HTTP; a
|
|
6
|
+
* bootstrap response then FINALIZES it (adds `credentialId`+`expiresAt`) under the SAME lease. Reading
|
|
7
|
+
* or deleting requires HOLDING the lease: `acquireHandoffLease` returns a handle bound to (root, id,
|
|
8
|
+
* ownership nonce, and a single captured `FsOps` instance); `loadProvisional`/`loadFinalized`/`finalize`/
|
|
9
|
+
* `delete` live ON that handle and call `assertOwned` first, so a released/tampered/foreign handle fails
|
|
10
|
+
* closed. The server stays the single-use authority over the ticket; the ticket is never echoed.
|
|
11
|
+
*
|
|
12
|
+
* FsOps is captured ONCE at acquisition and used for the lock, every read, `finalize`'s replace/reconcile,
|
|
13
|
+
* and delete — so fault-injection tests traverse the real productive path (no `node:fs` directly here).
|
|
14
|
+
*/
|
|
15
|
+
import { join } from 'node:path';
|
|
16
|
+
import { StoreError } from './errors.js';
|
|
17
|
+
import { canonicalJson } from './canonical.js';
|
|
18
|
+
import { assertHandoffId } from './names.js';
|
|
19
|
+
import { handoffDir, handoffFile, handoffLease, ensureHandoffDir, assertHandoffChain, assertRegularFile } from './paths.js';
|
|
20
|
+
import { atomicCreateIdempotent, atomicReplace, reconcileFinalizedDurable, } from './atomic-write.js';
|
|
21
|
+
import { acquireLock } from './lock.js';
|
|
22
|
+
import { durableDelete } from './durable-delete.js';
|
|
23
|
+
import { REAL_FS } from './fsops.js';
|
|
24
|
+
import { validateProvisionalHandoff, validateFinalizedHandoff, assertHandoffNotExpired, } from './schema.js';
|
|
25
|
+
const LEASE_CODES = {
|
|
26
|
+
busy: 'sa_handoff_busy',
|
|
27
|
+
stale: 'sa_handoff_lease_stale',
|
|
28
|
+
mismatch: 'sa_handoff_lease_invalid',
|
|
29
|
+
corrupt: 'sa_handoff_lease_corrupt',
|
|
30
|
+
};
|
|
31
|
+
/**
|
|
32
|
+
* Persist a NEW provisional handoff (validated + canonical), idempotently. An EEXIST with the SAME
|
|
33
|
+
* canonical document → `{outcome:'reconciled', …PersistenceEvidence}`; a different document → `sa_handoff_conflict`.
|
|
34
|
+
*/
|
|
35
|
+
export function createProvisionalHandoff(root, id, handoff, fs = REAL_FS) {
|
|
36
|
+
assertHandoffId(id);
|
|
37
|
+
const validated = validateProvisionalHandoff(handoff);
|
|
38
|
+
const dir = ensureHandoffDir(root, fs);
|
|
39
|
+
return atomicCreateIdempotent(dir, handoffFile(id), canonicalJson(validated), { validate: validateProvisionalHandoff, conflictCode: 'sa_handoff_conflict' }, fs);
|
|
40
|
+
}
|
|
41
|
+
/** Acquire the per-handoff lease and return a handle whose load/finalize/delete enforce ownership. */
|
|
42
|
+
export function acquireHandoffLease(root, id, fs = REAL_FS) {
|
|
43
|
+
assertHandoffId(id);
|
|
44
|
+
const dir = ensureHandoffDir(root, fs);
|
|
45
|
+
const lock = acquireLock(join(dir, handoffLease(id)), LEASE_CODES, fs);
|
|
46
|
+
const handoffPath = () => join(handoffDir(root), handoffFile(id));
|
|
47
|
+
/** Read + JSON-parse the handoff doc under ownership + chain/symlink checks (via the captured fs). */
|
|
48
|
+
const readDoc = () => {
|
|
49
|
+
lock.assertOwned();
|
|
50
|
+
assertHandoffChain(root, fs);
|
|
51
|
+
const path = handoffPath();
|
|
52
|
+
// Regular-file gate BEFORE read (F2): absent → sa_handoff_not_found; symlink → sa_store_symlink_rejected;
|
|
53
|
+
// lstat-fail → sa_store_lstat_failed; special → sa_handoff_corrupt. NEVER readFileSync a non-regular inode.
|
|
54
|
+
assertRegularFile(path, { notFound: 'sa_handoff_not_found', notRegular: 'sa_handoff_corrupt' }, fs);
|
|
55
|
+
let raw;
|
|
56
|
+
try {
|
|
57
|
+
raw = fs.readFileSync(path);
|
|
58
|
+
}
|
|
59
|
+
catch (e) {
|
|
60
|
+
const code = e?.code;
|
|
61
|
+
if (code === 'ENOENT')
|
|
62
|
+
throw new StoreError('sa_handoff_not_found');
|
|
63
|
+
throw new StoreError('sa_handoff_corrupt');
|
|
64
|
+
}
|
|
65
|
+
try {
|
|
66
|
+
return JSON.parse(raw);
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
throw new StoreError('sa_handoff_corrupt');
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
const tryValidate = (fn, raw) => {
|
|
73
|
+
try {
|
|
74
|
+
return fn(raw);
|
|
75
|
+
}
|
|
76
|
+
catch {
|
|
77
|
+
return null;
|
|
78
|
+
}
|
|
79
|
+
};
|
|
80
|
+
return {
|
|
81
|
+
loadProvisional() {
|
|
82
|
+
const parsed = readDoc();
|
|
83
|
+
const prov = tryValidate(validateProvisionalHandoff, parsed);
|
|
84
|
+
if (prov)
|
|
85
|
+
return prov;
|
|
86
|
+
if (tryValidate(validateFinalizedHandoff, parsed))
|
|
87
|
+
throw new StoreError('sa_handoff_not_provisional');
|
|
88
|
+
throw new StoreError('sa_handoff_corrupt');
|
|
89
|
+
},
|
|
90
|
+
loadFinalized(nowMs = Date.now()) {
|
|
91
|
+
const parsed = readDoc();
|
|
92
|
+
const fin = tryValidate(validateFinalizedHandoff, parsed);
|
|
93
|
+
if (fin) {
|
|
94
|
+
assertHandoffNotExpired(fin, nowMs);
|
|
95
|
+
return fin;
|
|
96
|
+
}
|
|
97
|
+
if (tryValidate(validateProvisionalHandoff, parsed))
|
|
98
|
+
throw new StoreError('sa_handoff_not_finalized');
|
|
99
|
+
throw new StoreError('sa_handoff_corrupt');
|
|
100
|
+
},
|
|
101
|
+
readState(nowMs = Date.now()) {
|
|
102
|
+
const parsed = readDoc(); // ONE read+parse under ownership
|
|
103
|
+
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
104
|
+
throw new StoreError('sa_handoff_corrupt');
|
|
105
|
+
}
|
|
106
|
+
const rec = parsed;
|
|
107
|
+
// Pick the phase by OWN-property presence of the finalized-only fields (F5: `Object.hasOwn`, never `in`,
|
|
108
|
+
// so a prototype-polluted/inherited `credentialId`/`expiresAt` cannot reclassify a valid provisional),
|
|
109
|
+
// then validate EXACTLY that phase. A validation failure is `sa_handoff_corrupt` — never a fallback.
|
|
110
|
+
const looksFinalized = Object.hasOwn(rec, 'credentialId') || Object.hasOwn(rec, 'expiresAt');
|
|
111
|
+
if (looksFinalized) {
|
|
112
|
+
const fin = tryValidate(validateFinalizedHandoff, parsed);
|
|
113
|
+
if (!fin)
|
|
114
|
+
throw new StoreError('sa_handoff_corrupt');
|
|
115
|
+
return { phase: 'finalized', handoff: fin, expired: new Date(fin.expiresAt).getTime() <= nowMs };
|
|
116
|
+
}
|
|
117
|
+
const prov = tryValidate(validateProvisionalHandoff, parsed);
|
|
118
|
+
if (!prov)
|
|
119
|
+
throw new StoreError('sa_handoff_corrupt');
|
|
120
|
+
return { phase: 'provisional', handoff: prov };
|
|
121
|
+
},
|
|
122
|
+
finalize(input) {
|
|
123
|
+
const parsed = readDoc();
|
|
124
|
+
const dir2 = handoffDir(root);
|
|
125
|
+
const dest = handoffPath();
|
|
126
|
+
// Provisional on disk → finalize forward (preserve operationId/ticket/SA/baseUrl exactly).
|
|
127
|
+
const prov = tryValidate(validateProvisionalHandoff, parsed);
|
|
128
|
+
if (prov) {
|
|
129
|
+
const finalized = validateFinalizedHandoff({
|
|
130
|
+
schemaVersion: prov.schemaVersion,
|
|
131
|
+
operationId: prov.operationId,
|
|
132
|
+
claimTicket: prov.claimTicket,
|
|
133
|
+
serviceAccountId: prov.serviceAccountId,
|
|
134
|
+
baseUrl: prov.baseUrl,
|
|
135
|
+
credentialId: input.credentialId,
|
|
136
|
+
expiresAt: input.expiresAt,
|
|
137
|
+
});
|
|
138
|
+
const r = atomicReplace(dir2, handoffFile(id), canonicalJson(finalized), fs);
|
|
139
|
+
return {
|
|
140
|
+
outcome: 'finalized',
|
|
141
|
+
content: r.content,
|
|
142
|
+
permissions: r.permissions,
|
|
143
|
+
file: r.file,
|
|
144
|
+
directory: r.directory,
|
|
145
|
+
residualTemp: r.residualTemp,
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
// Already finalized → idempotent replay. Build the EXPECTED doc from the existing provisional fields
|
|
149
|
+
// + the provided credentialId/expiresAt; identical → reconciled, different → conflict.
|
|
150
|
+
const fin = tryValidate(validateFinalizedHandoff, parsed);
|
|
151
|
+
if (fin) {
|
|
152
|
+
let expectedCanonical;
|
|
153
|
+
try {
|
|
154
|
+
const expected = validateFinalizedHandoff({
|
|
155
|
+
schemaVersion: fin.schemaVersion,
|
|
156
|
+
operationId: fin.operationId,
|
|
157
|
+
claimTicket: fin.claimTicket,
|
|
158
|
+
serviceAccountId: fin.serviceAccountId,
|
|
159
|
+
baseUrl: fin.baseUrl,
|
|
160
|
+
credentialId: input.credentialId,
|
|
161
|
+
expiresAt: input.expiresAt,
|
|
162
|
+
});
|
|
163
|
+
expectedCanonical = canonicalJson(expected);
|
|
164
|
+
}
|
|
165
|
+
catch {
|
|
166
|
+
throw new StoreError('sa_handoff_conflict');
|
|
167
|
+
}
|
|
168
|
+
return reconcileFinalizedDurable(fs, dest, dir2, expectedCanonical, validateFinalizedHandoff, 'sa_handoff_conflict');
|
|
169
|
+
}
|
|
170
|
+
throw new StoreError('sa_handoff_corrupt');
|
|
171
|
+
},
|
|
172
|
+
delete() {
|
|
173
|
+
lock.assertOwned(); // the lease check does not replace the managed-chain + regular-file gates (in durableDelete)
|
|
174
|
+
// Durable removal (U9b-3e-P0 §10.c#18.5): managed-chain + regular-file gate + unlink + `fsyncDir(parent)` so a
|
|
175
|
+
// crash after unlink cannot resurrect the entry. symlink/special/lstat-fail preserve their stable codes; absent
|
|
176
|
+
// still flushes the dir; non-ENOENT unlink → sa_store_io_error. NOT a secure erase.
|
|
177
|
+
return durableDelete(handoffPath(), (f) => assertHandoffChain(root, f), fs);
|
|
178
|
+
},
|
|
179
|
+
release() {
|
|
180
|
+
lock.release();
|
|
181
|
+
},
|
|
182
|
+
};
|
|
183
|
+
}
|
|
@@ -0,0 +1,396 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* U4 Capa 3 · C3.4 · Durable manifest/stage JOURNAL + dedicated operation-bound LEASE.
|
|
3
|
+
*
|
|
4
|
+
* The journal is a SINGLE append-only file per operation
|
|
5
|
+
* (`<root>/.airctrl/sa/identity-rotations/<operationId>.journal.json`), written with the SAME path-safety /
|
|
6
|
+
* regular-file / 0600 / atomic-create-replace / fsync / durable-delete guarantees as every other managed
|
|
7
|
+
* artifact. A single file (not one-per-batch) is used because the injectable `FsOps` has no `readdir`; atomic
|
|
8
|
+
* replace keeps every append crash-safe (temp + rename), and already-written batches are IMMUTABLE by
|
|
9
|
+
* validation — an append must extend the existing prefix by EXACTLY one ordinal; a replay of an existing batch
|
|
10
|
+
* with an identical body is a no-op, a divergent body is a stable conflict.
|
|
11
|
+
*
|
|
12
|
+
* Contract (C3.4): batches are immutable, consecutive, gap-free; each carries `ordinal`, `entryCursor`,
|
|
13
|
+
* `nextCursor`, a UUID `stageIdempotencyKey`, and the exact `{wrappers:[...]}` body. The generated `newCiphertext`
|
|
14
|
+
* bytes are persisted DURABLY here BEFORE the POST stage, so a resume re-sends byte-identical batches with the
|
|
15
|
+
* SAME keys (server replay = exact no-op) — the X25519 re-seal is never regenerated. A durable `complete` flag
|
|
16
|
+
* covers the empty manifest too. No batch is removed before the commit is confirmed and the local promotion
|
|
17
|
+
* completes; the whole journal is then durably deleted before stdout.
|
|
18
|
+
*
|
|
19
|
+
* The lease is a DEDICATED operation-bound lock (`<operationId>.lease`), separate from handoff/migration/profile
|
|
20
|
+
* leases (F5), with its own stable codes; no auto-reclaim, no TTL stealing — a stale lease requires explicit
|
|
21
|
+
* manual recovery.
|
|
22
|
+
*/
|
|
23
|
+
import { join } from 'node:path';
|
|
24
|
+
import { StoreError } from './errors.js';
|
|
25
|
+
import { canonicalJson, isCanonicalB64 } from './canonical.js';
|
|
26
|
+
import { assertRotationOperationId } from './names.js';
|
|
27
|
+
import { normalizeBaseUrl } from './base-url.js';
|
|
28
|
+
import { identityRotationDir, identityRotationJournalFile, identityRotationLeaseFile, ensureIdentityRotationDir, assertIdentityRotationChain, assertRegularFile, } from './paths.js';
|
|
29
|
+
import { atomicCreate, atomicReplace } from './atomic-write.js';
|
|
30
|
+
import { durableDelete } from './durable-delete.js';
|
|
31
|
+
import { acquireLock, reclaimStaleLock } from './lock.js';
|
|
32
|
+
import { REAL_FS } from './fsops.js';
|
|
33
|
+
export const IDENTITY_ROTATION_JOURNAL_SCHEMA_VERSION = 1;
|
|
34
|
+
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
|
|
35
|
+
export const IDENTITY_ROTATION_MAX_BATCH = 200;
|
|
36
|
+
const isPlainObject = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
37
|
+
const isUuid = (v) => typeof v === 'string' && UUID_RE.test(v);
|
|
38
|
+
const isNeStr = (v) => typeof v === 'string' && v.length > 0;
|
|
39
|
+
const isCursor = (v) => v === null || (typeof v === 'string' && v.length > 0);
|
|
40
|
+
const corrupt = () => {
|
|
41
|
+
throw new StoreError('sa_identity_rotation_journal_corrupt');
|
|
42
|
+
};
|
|
43
|
+
/** The re-sealed ciphertext must be an EXACT sealedbox wrapper JSON for its kind, with canonical base64 (F2/F4). */
|
|
44
|
+
function assertCiphertextShape(kind, ciphertext) {
|
|
45
|
+
let parsed;
|
|
46
|
+
try {
|
|
47
|
+
parsed = JSON.parse(ciphertext);
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
corrupt();
|
|
51
|
+
}
|
|
52
|
+
if (!isPlainObject(parsed) || parsed.v !== 1 || parsed.alg !== 'x25519-sealedbox')
|
|
53
|
+
corrupt();
|
|
54
|
+
const field = kind === 'record' ? 'sealed_dek_b64' : 'sealed_project_key_b64';
|
|
55
|
+
const own = Object.keys(parsed);
|
|
56
|
+
if (own.length !== 3 || !['v', 'alg', field].every((k) => own.includes(k)))
|
|
57
|
+
corrupt();
|
|
58
|
+
if (!isCanonicalB64(parsed[field]))
|
|
59
|
+
corrupt();
|
|
60
|
+
}
|
|
61
|
+
/** Intrinsic shape of ONE staged wrapper — exact own keys; record⇒keyVersion null, project⇒int>=1; ciphertext exact. */
|
|
62
|
+
function validateStageWrapper(v) {
|
|
63
|
+
if (!isPlainObject(v))
|
|
64
|
+
corrupt();
|
|
65
|
+
const rec = v;
|
|
66
|
+
const own = Object.keys(rec);
|
|
67
|
+
const allowed = ['wrapperKind', 'wrapperId', 'keyVersion', 'newCiphertext'];
|
|
68
|
+
if (own.length !== allowed.length || !allowed.every((k) => Object.prototype.hasOwnProperty.call(rec, k)))
|
|
69
|
+
corrupt();
|
|
70
|
+
if (rec.wrapperKind !== 'record' && rec.wrapperKind !== 'project')
|
|
71
|
+
corrupt();
|
|
72
|
+
const kind = rec.wrapperKind;
|
|
73
|
+
if (!isUuid(rec.wrapperId) || rec.wrapperId !== rec.wrapperId.toLowerCase())
|
|
74
|
+
corrupt();
|
|
75
|
+
const kv = rec.keyVersion;
|
|
76
|
+
if (kind === 'record') {
|
|
77
|
+
if (kv !== null)
|
|
78
|
+
corrupt(); // record ⇒ keyVersion MUST be null
|
|
79
|
+
}
|
|
80
|
+
else if (!(typeof kv === 'number' && Number.isInteger(kv) && kv >= 1)) {
|
|
81
|
+
corrupt(); // project ⇒ integer >= 1
|
|
82
|
+
}
|
|
83
|
+
if (!isNeStr(rec.newCiphertext))
|
|
84
|
+
corrupt();
|
|
85
|
+
assertCiphertextShape(kind, rec.newCiphertext);
|
|
86
|
+
return { wrapperKind: kind, wrapperId: rec.wrapperId, keyVersion: kv, newCiphertext: rec.newCiphertext };
|
|
87
|
+
}
|
|
88
|
+
/** Intrinsic shape of ONE batch (does NOT assume position): exact keys, ordinal a non-negative int, size 1..200,
|
|
89
|
+
* no duplicate wrapper identity WITHIN the batch. Cursor chaining + ordinal continuity are journal-level (F2). */
|
|
90
|
+
function validateBatchShape(v) {
|
|
91
|
+
if (!isPlainObject(v))
|
|
92
|
+
corrupt();
|
|
93
|
+
const rec = v;
|
|
94
|
+
const allowed = ['ordinal', 'entryCursor', 'nextCursor', 'stageIdempotencyKey', 'body'];
|
|
95
|
+
const own = Object.keys(rec);
|
|
96
|
+
if (own.length !== allowed.length || !allowed.every((k) => Object.prototype.hasOwnProperty.call(rec, k)))
|
|
97
|
+
corrupt();
|
|
98
|
+
if (!(typeof rec.ordinal === 'number' && Number.isInteger(rec.ordinal) && rec.ordinal >= 0))
|
|
99
|
+
corrupt();
|
|
100
|
+
if (!isCursor(rec.entryCursor) || !isCursor(rec.nextCursor))
|
|
101
|
+
corrupt();
|
|
102
|
+
if (!isUuid(rec.stageIdempotencyKey))
|
|
103
|
+
corrupt();
|
|
104
|
+
if (!isPlainObject(rec.body) || Object.keys(rec.body).length !== 1 || !Array.isArray(rec.body.wrappers))
|
|
105
|
+
corrupt();
|
|
106
|
+
const wrappers = (rec.body.wrappers).map(validateStageWrapper);
|
|
107
|
+
if (wrappers.length < 1 || wrappers.length > IDENTITY_ROTATION_MAX_BATCH)
|
|
108
|
+
corrupt(); // size 1..200
|
|
109
|
+
const ids = new Set();
|
|
110
|
+
for (const w of wrappers) {
|
|
111
|
+
const id = `${w.wrapperKind}:${w.wrapperId}`;
|
|
112
|
+
if (ids.has(id))
|
|
113
|
+
corrupt(); // no duplicate wrapper identity within the batch
|
|
114
|
+
ids.add(id);
|
|
115
|
+
}
|
|
116
|
+
return { ordinal: rec.ordinal, entryCursor: rec.entryCursor, nextCursor: rec.nextCursor, stageIdempotencyKey: rec.stageIdempotencyKey, body: { wrappers } };
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Validate a decoded object as a journal — exact envelope + FULL integrity (F2): consecutive gap-free ordinals
|
|
120
|
+
* from 0; `batches[0].entryCursor === null`; each `entryCursor` equals the previous `nextCursor`; no non-final
|
|
121
|
+
* batch closes the cursor (`nextCursor===null`); `complete=true` ⇒ cursor exhausted (empty OR last `nextCursor`
|
|
122
|
+
* null); `complete=false` ⇒ NOT already exhausted; no duplicate wrapper identity across the WHOLE journal.
|
|
123
|
+
*/
|
|
124
|
+
export function validateJournal(raw) {
|
|
125
|
+
if (!isPlainObject(raw))
|
|
126
|
+
corrupt();
|
|
127
|
+
const rec = raw;
|
|
128
|
+
const allowed = ['schemaVersion', 'operationId', 'serviceAccountId', 'baseUrl', 'batches', 'complete'];
|
|
129
|
+
const own = Object.keys(rec);
|
|
130
|
+
if (own.length !== allowed.length || !allowed.every((k) => Object.prototype.hasOwnProperty.call(rec, k)))
|
|
131
|
+
corrupt();
|
|
132
|
+
if (rec.schemaVersion !== IDENTITY_ROTATION_JOURNAL_SCHEMA_VERSION)
|
|
133
|
+
corrupt();
|
|
134
|
+
if (!isUuid(rec.operationId) || !isNeStr(rec.serviceAccountId))
|
|
135
|
+
corrupt();
|
|
136
|
+
try {
|
|
137
|
+
normalizeBaseUrl(rec.baseUrl);
|
|
138
|
+
}
|
|
139
|
+
catch {
|
|
140
|
+
corrupt();
|
|
141
|
+
}
|
|
142
|
+
if (typeof rec.complete !== 'boolean' || !Array.isArray(rec.batches))
|
|
143
|
+
corrupt();
|
|
144
|
+
const raws = rec.batches;
|
|
145
|
+
const batches = raws.map(validateBatchShape);
|
|
146
|
+
const globalIds = new Set();
|
|
147
|
+
for (let i = 0; i < batches.length; i++) {
|
|
148
|
+
const b = batches[i];
|
|
149
|
+
if (b.ordinal !== i)
|
|
150
|
+
corrupt(); // consecutive, gap-free, from 0
|
|
151
|
+
if (i === 0) {
|
|
152
|
+
if (b.entryCursor !== null)
|
|
153
|
+
corrupt(); // first entryCursor MUST be null
|
|
154
|
+
}
|
|
155
|
+
else if (b.entryCursor !== batches[i - 1].nextCursor) {
|
|
156
|
+
corrupt(); // each entryCursor chains to the previous nextCursor
|
|
157
|
+
}
|
|
158
|
+
if (i < batches.length - 1 && b.nextCursor === null)
|
|
159
|
+
corrupt(); // no premature close before the final batch
|
|
160
|
+
for (const w of b.body.wrappers) {
|
|
161
|
+
const id = `${w.wrapperKind}:${w.wrapperId}`;
|
|
162
|
+
if (globalIds.has(id))
|
|
163
|
+
corrupt(); // no duplicate wrapper identity across the whole journal
|
|
164
|
+
globalIds.add(id);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
const exhausted = batches.length === 0 ? false : batches[batches.length - 1].nextCursor === null;
|
|
168
|
+
const complete = rec.complete;
|
|
169
|
+
if (complete && batches.length > 0 && !exhausted)
|
|
170
|
+
corrupt(); // complete ⇒ cursor exhausted
|
|
171
|
+
if (!complete && exhausted)
|
|
172
|
+
corrupt(); // an exhausted journal cannot be represented as incomplete
|
|
173
|
+
return {
|
|
174
|
+
schemaVersion: 1,
|
|
175
|
+
operationId: rec.operationId,
|
|
176
|
+
serviceAccountId: rec.serviceAccountId,
|
|
177
|
+
baseUrl: rec.baseUrl,
|
|
178
|
+
batches,
|
|
179
|
+
complete,
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
function journalPath(root, operationId) {
|
|
183
|
+
return join(identityRotationDir(root), identityRotationJournalFile(operationId));
|
|
184
|
+
}
|
|
185
|
+
// ── Journal store internals (F3): PRIVATE — never take root/operationId/fs from an untrusted caller; the only
|
|
186
|
+
// public entry points are the lease-context-bound ops below. Every impl re-checks the file's `operationId`. ──
|
|
187
|
+
function startJournalImpl(root, operationId, input, fs) {
|
|
188
|
+
const existing = tryLoadJournalImpl(root, operationId, fs);
|
|
189
|
+
if (existing) {
|
|
190
|
+
if (existing.serviceAccountId !== input.serviceAccountId || normalizeBaseUrl(existing.baseUrl) !== normalizeBaseUrl(input.baseUrl)) {
|
|
191
|
+
throw new StoreError('sa_identity_rotation_journal_conflict');
|
|
192
|
+
}
|
|
193
|
+
return existing;
|
|
194
|
+
}
|
|
195
|
+
const journal = { schemaVersion: 1, operationId, serviceAccountId: input.serviceAccountId, baseUrl: input.baseUrl, batches: [], complete: false };
|
|
196
|
+
const dir = ensureIdentityRotationDir(root, fs);
|
|
197
|
+
atomicCreate(dir, identityRotationJournalFile(operationId), canonicalJson(journal), fs);
|
|
198
|
+
return journal;
|
|
199
|
+
}
|
|
200
|
+
function loadJournalImpl(root, operationId, fs) {
|
|
201
|
+
assertRotationOperationId(operationId);
|
|
202
|
+
assertIdentityRotationChain(root, fs);
|
|
203
|
+
const path = journalPath(root, operationId);
|
|
204
|
+
assertRegularFile(path, { notFound: 'sa_identity_rotation_journal_not_found', notRegular: 'sa_identity_rotation_journal_corrupt' }, fs);
|
|
205
|
+
let raw;
|
|
206
|
+
try {
|
|
207
|
+
raw = fs.readFileSync(path);
|
|
208
|
+
}
|
|
209
|
+
catch (e) {
|
|
210
|
+
if (e?.code === 'ENOENT')
|
|
211
|
+
throw new StoreError('sa_identity_rotation_journal_not_found');
|
|
212
|
+
throw new StoreError('sa_identity_rotation_journal_corrupt');
|
|
213
|
+
}
|
|
214
|
+
let parsed;
|
|
215
|
+
try {
|
|
216
|
+
parsed = JSON.parse(raw);
|
|
217
|
+
}
|
|
218
|
+
catch {
|
|
219
|
+
throw new StoreError('sa_identity_rotation_journal_corrupt');
|
|
220
|
+
}
|
|
221
|
+
const journal = validateJournal(parsed);
|
|
222
|
+
if (journal.operationId !== operationId)
|
|
223
|
+
throw new StoreError('sa_identity_rotation_operation_mismatch'); // file ↔ selector binding
|
|
224
|
+
return journal;
|
|
225
|
+
}
|
|
226
|
+
function tryLoadJournalImpl(root, operationId, fs) {
|
|
227
|
+
try {
|
|
228
|
+
return loadJournalImpl(root, operationId, fs);
|
|
229
|
+
}
|
|
230
|
+
catch (e) {
|
|
231
|
+
if (e instanceof StoreError && e.code === 'sa_identity_rotation_journal_not_found')
|
|
232
|
+
return null;
|
|
233
|
+
throw e;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
function appendBatchImpl(root, operationId, batch, fs) {
|
|
237
|
+
const journal = loadJournalImpl(root, operationId, fs);
|
|
238
|
+
const validated = validateBatchShape(batch); // intrinsic shape only — position-agnostic
|
|
239
|
+
const n = journal.batches.length;
|
|
240
|
+
if (validated.ordinal < n) {
|
|
241
|
+
if (canonicalJson(journal.batches[validated.ordinal]) !== canonicalJson(validated))
|
|
242
|
+
throw new StoreError('sa_identity_rotation_journal_conflict');
|
|
243
|
+
return journal; // exact replay → no-op (bytes preserved)
|
|
244
|
+
}
|
|
245
|
+
if (validated.ordinal > n)
|
|
246
|
+
throw new StoreError('sa_identity_rotation_journal_conflict'); // gap
|
|
247
|
+
if (journal.complete)
|
|
248
|
+
throw new StoreError('sa_identity_rotation_journal_conflict');
|
|
249
|
+
const expectedEntry = n === 0 ? null : journal.batches[n - 1].nextCursor;
|
|
250
|
+
if (validated.entryCursor !== expectedEntry)
|
|
251
|
+
throw new StoreError('sa_identity_rotation_journal_conflict'); // broken chain
|
|
252
|
+
const nextComplete = validated.nextCursor === null;
|
|
253
|
+
const next = { ...journal, batches: [...journal.batches, validated], complete: nextComplete };
|
|
254
|
+
atomicReplace(ensureIdentityRotationDir(root, fs), identityRotationJournalFile(operationId), canonicalJson(next), fs);
|
|
255
|
+
return next;
|
|
256
|
+
}
|
|
257
|
+
function markCompleteImpl(root, operationId, fs) {
|
|
258
|
+
const journal = loadJournalImpl(root, operationId, fs);
|
|
259
|
+
if (journal.complete)
|
|
260
|
+
return journal;
|
|
261
|
+
if (journal.batches.length !== 0)
|
|
262
|
+
throw new StoreError('sa_identity_rotation_journal_conflict'); // non-empty completes via append
|
|
263
|
+
const next = { ...journal, complete: true };
|
|
264
|
+
atomicReplace(ensureIdentityRotationDir(root, fs), identityRotationJournalFile(operationId), canonicalJson(next), fs);
|
|
265
|
+
return next;
|
|
266
|
+
}
|
|
267
|
+
function deleteImpl(root, operationId, fs) {
|
|
268
|
+
assertRotationOperationId(operationId);
|
|
269
|
+
// R2 · fail-closed: load + validate + assert the file's operationId matches BEFORE any unlink. A corrupt or
|
|
270
|
+
// cross-operation journal is NEVER deleted (bytes preserved); an already-absent journal is an idempotent absent.
|
|
271
|
+
try {
|
|
272
|
+
loadJournalImpl(root, operationId, fs);
|
|
273
|
+
}
|
|
274
|
+
catch (e) {
|
|
275
|
+
if (e instanceof StoreError && e.code === 'sa_identity_rotation_journal_not_found') {
|
|
276
|
+
return durableDelete(journalPath(root, operationId), (f) => assertIdentityRotationChain(root, f), fs); // absent (still flushes dir)
|
|
277
|
+
}
|
|
278
|
+
throw e; // corrupt / operation_mismatch → do NOT delete
|
|
279
|
+
}
|
|
280
|
+
return durableDelete(journalPath(root, operationId), (f) => assertIdentityRotationChain(root, f), fs);
|
|
281
|
+
}
|
|
282
|
+
// ── Dedicated operation-bound lease + BOUND authority context (F3/F5) ─────────────────────────────────
|
|
283
|
+
export const IDENTITY_ROTATION_LEASE_CODES = {
|
|
284
|
+
busy: 'sa_identity_rotation_lease_busy',
|
|
285
|
+
stale: 'sa_identity_rotation_lease_stale',
|
|
286
|
+
mismatch: 'sa_identity_rotation_lease_owner_mismatch',
|
|
287
|
+
corrupt: 'sa_identity_rotation_lease_corrupt',
|
|
288
|
+
};
|
|
289
|
+
const BOUND = new WeakMap();
|
|
290
|
+
/**
|
|
291
|
+
* Acquire the operation-bound lease. `reclaimStale` (resume path): when a PRIOR holder of THIS operation's lease
|
|
292
|
+
* crashed (e.g. SIGKILL) it leaves a stale lock (same host, PID provably dead). Because the lock file is
|
|
293
|
+
* op-specific, a same-operation resume may EXPLICITLY reclaim it (the documented "manual recovery") and retry
|
|
294
|
+
* exactly once — a live/foreign/unknown holder still fails `busy`, and a second stale after the retry propagates.
|
|
295
|
+
*/
|
|
296
|
+
export function acquireIdentityRotationLease(root, operationId, fs = REAL_FS, opts) {
|
|
297
|
+
assertRotationOperationId(operationId);
|
|
298
|
+
const dir = ensureIdentityRotationDir(root, fs);
|
|
299
|
+
const lockPath = join(dir, identityRotationLeaseFile(operationId));
|
|
300
|
+
let handle;
|
|
301
|
+
try {
|
|
302
|
+
handle = acquireLock(lockPath, IDENTITY_ROTATION_LEASE_CODES, fs);
|
|
303
|
+
}
|
|
304
|
+
catch (e) {
|
|
305
|
+
if (opts?.reclaimStale && e instanceof StoreError && e.code === IDENTITY_ROTATION_LEASE_CODES.stale) {
|
|
306
|
+
reclaimStaleLock(lockPath, IDENTITY_ROTATION_LEASE_CODES, fs); // this op only; dead-pid same-host regular file
|
|
307
|
+
handle = acquireLock(lockPath, IDENTITY_ROTATION_LEASE_CODES, fs); // retry ONCE — a fresh live/stale holder propagates
|
|
308
|
+
}
|
|
309
|
+
else {
|
|
310
|
+
throw e;
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
const ctx = Object.freeze({ __identityRotationLease: true });
|
|
314
|
+
BOUND.set(ctx, { handle, root, operationId, fs, released: false });
|
|
315
|
+
return ctx;
|
|
316
|
+
}
|
|
317
|
+
function bound(ctx) {
|
|
318
|
+
const b = BOUND.get(ctx);
|
|
319
|
+
if (!b)
|
|
320
|
+
throw new StoreError('sa_identity_rotation_lease_unbound'); // fabricated/copied/poisoned token
|
|
321
|
+
return b;
|
|
322
|
+
}
|
|
323
|
+
function withOwned(ctx, fn) {
|
|
324
|
+
const b = bound(ctx);
|
|
325
|
+
b.handle.assertOwned(); // owner-mismatch/stale/corrupt → stable code BEFORE any I/O
|
|
326
|
+
return fn(b);
|
|
327
|
+
}
|
|
328
|
+
function releaseBound(b) {
|
|
329
|
+
if (b.released)
|
|
330
|
+
return; // exactly once
|
|
331
|
+
try {
|
|
332
|
+
b.handle.release();
|
|
333
|
+
b.released = true;
|
|
334
|
+
}
|
|
335
|
+
catch (e) {
|
|
336
|
+
b.released = true;
|
|
337
|
+
if (e instanceof StoreError && (e.code === IDENTITY_ROTATION_LEASE_CODES.mismatch || e.code === IDENTITY_ROTATION_LEASE_CODES.corrupt))
|
|
338
|
+
throw e;
|
|
339
|
+
throw new StoreError('sa_identity_rotation_lease_release_failed');
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
// Context-bound public journal ops — the ONLY way to touch the journal (F3). Each asserts lease ownership first.
|
|
343
|
+
export function journalStart(ctx, input) {
|
|
344
|
+
return withOwned(ctx, (b) => startJournalImpl(b.root, b.operationId, input, b.fs));
|
|
345
|
+
}
|
|
346
|
+
export function journalLoad(ctx) {
|
|
347
|
+
return withOwned(ctx, (b) => loadJournalImpl(b.root, b.operationId, b.fs));
|
|
348
|
+
}
|
|
349
|
+
export function journalTryLoad(ctx) {
|
|
350
|
+
return withOwned(ctx, (b) => tryLoadJournalImpl(b.root, b.operationId, b.fs));
|
|
351
|
+
}
|
|
352
|
+
export function journalAppend(ctx, batch) {
|
|
353
|
+
return withOwned(ctx, (b) => appendBatchImpl(b.root, b.operationId, batch, b.fs));
|
|
354
|
+
}
|
|
355
|
+
export function journalMarkComplete(ctx) {
|
|
356
|
+
return withOwned(ctx, (b) => markCompleteImpl(b.root, b.operationId, b.fs));
|
|
357
|
+
}
|
|
358
|
+
export function journalDelete(ctx) {
|
|
359
|
+
return withOwned(ctx, (b) => deleteImpl(b.root, b.operationId, b.fs));
|
|
360
|
+
}
|
|
361
|
+
/**
|
|
362
|
+
* BOUND combinator (F3/R1): assert THIS context's lease ownership via the private handle BEFORE the callback
|
|
363
|
+
* (an owner-mismatch/stale/corrupt lease prevents the callback from ever starting), `await run()` so the lease
|
|
364
|
+
* stays HELD for the WHOLE promise (sync or async callbacks share the semantics), then release the lease EXACTLY
|
|
365
|
+
* once AFTER settlement with falsy-safe precedence (a functional PRIMARY rejection wins by identity even when it
|
|
366
|
+
* is `undefined`/`null`/`false`/`0`/`''`; a success whose release fails throws the release code). An unbound token
|
|
367
|
+
* throws before the callback. The CLI awaits this and produces stdout ONLY after a clean release.
|
|
368
|
+
*/
|
|
369
|
+
export async function withIdentityRotationLease(ctx, run) {
|
|
370
|
+
const b = bound(ctx); // unbound → throw BEFORE the callback
|
|
371
|
+
b.handle.assertOwned(); // owner-mismatch/stale/corrupt → throw BEFORE the callback (never starts)
|
|
372
|
+
let result;
|
|
373
|
+
let primary;
|
|
374
|
+
let hasPrimary = false;
|
|
375
|
+
try {
|
|
376
|
+
result = await run(); // lease held for the WHOLE promise (async work included)
|
|
377
|
+
}
|
|
378
|
+
catch (e) {
|
|
379
|
+
primary = e;
|
|
380
|
+
hasPrimary = true;
|
|
381
|
+
}
|
|
382
|
+
let releaseErr;
|
|
383
|
+
let hasReleaseErr = false;
|
|
384
|
+
try {
|
|
385
|
+
releaseBound(b); // exactly once, AFTER settlement
|
|
386
|
+
}
|
|
387
|
+
catch (e) {
|
|
388
|
+
releaseErr = e;
|
|
389
|
+
hasReleaseErr = true;
|
|
390
|
+
}
|
|
391
|
+
if (hasPrimary)
|
|
392
|
+
throw primary; // falsy-safe primary precedence
|
|
393
|
+
if (hasReleaseErr)
|
|
394
|
+
throw releaseErr;
|
|
395
|
+
return result;
|
|
396
|
+
}
|