@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.
@@ -0,0 +1,20 @@
1
+ /**
2
+ * U9b-2 · SA multi-profile store — public surface (storage + principal resolution only).
3
+ * No CLI command wiring (that is U9b-3). Node stdlib only; no new dependencies.
4
+ */
5
+ export { StoreError } from './errors.js';
6
+ export { canonicalJson, isCanonicalB64 } from './canonical.js';
7
+ export { assertProfileName, assertHandoffId, assertRotationOperationId, assertReceiptId } from './names.js';
8
+ export { normalizeBaseUrl, assertBaseUrlMatch, resolveEffectiveBaseUrl } from './base-url.js';
9
+ export { REAL_FS, makeFsyncDir } from './fsops.js';
10
+ export { PROFILE_SCHEMA_VERSION, validateProfile, validateProvisionalHandoff, validateFinalizedHandoff, assertHandoffNotExpired, validateRotationArtifact, validateReceipt, assertTransition, } from './schema.js';
11
+ export { atomicCreate, atomicReplace, atomicCreateIdempotent, reconcileFinalizedDurable, evidenceSecure, } from './atomic-write.js';
12
+ export { acquireLock, reclaimStaleLock } from './lock.js';
13
+ export { saDir, handoffDir, rotationDir, receiptDir, profileFile, profileLock, migrationLease, handoffFile, handoffLease, rotationFile, receiptFile, ensureSaDir, ensureHandoffDir, ensureRotationDir, ensureReceiptDir, assertSaChain, assertHandoffChain, assertRotationChain, assertReceiptChain, assertNotSymlink, assertRegularFile, } from './paths.js';
14
+ export { acquireProfileLock, acquireMigrationLease, createProfile, loadProfile, replaceProfile, bumpIdentityRotationClaimAttempts, deleteTerminalProfile, deleteProfileUnderLock, abortUnprovisionedLegacyProfile, } from './profile-store.js';
15
+ export { acquireHandoffLease, createProvisionalHandoff, } from './handoff-store.js';
16
+ export { createRotationArtifact, loadRotationArtifact, deleteRotationArtifact } from './rotation-store.js';
17
+ export { acquireIdentityRotationLease, withIdentityRotationLease, journalStart, journalLoad, journalTryLoad, journalAppend, journalMarkComplete, journalDelete, validateJournal, IDENTITY_ROTATION_JOURNAL_SCHEMA_VERSION, IDENTITY_ROTATION_MAX_BATCH, IDENTITY_ROTATION_LEASE_CODES, } from './identity-rotation-journal.js';
18
+ export { createReceipt, loadReceipt, deleteReceipt } from './receipt-store.js';
19
+ export { durableDelete, confirmDurableAbsence, deleteEvidenceSecure } from './durable-delete.js';
20
+ export { resolvePrincipal } from './resolve-principal.js';
@@ -0,0 +1,294 @@
1
+ /**
2
+ * U9b-2 · Exclusive lock/lease primitive (§10.b #5/#6). Node stdlib only, via injectable {@link FsOps}.
3
+ *
4
+ * Acquisition writes and fsyncs a unique same-directory staging file, then atomically publishes it
5
+ * with `link(..., lockPath)`: exactly one holder and contenders can never observe half-written metadata.
6
+ * If staging fails, we close and unlink ONLY our own incomplete file and throw a stable error. Release
7
+ * and `assertOwned` verify the ownership nonce (+pid+hostname) and unlink only the caller's own lock.
8
+ *
9
+ * No auto-removal, no TTL stealing. A live/foreign holder → `busy`; an apparently-stale lock
10
+ * (same host + PID provably dead via ESRCH) → `stale`, NOT reclaimed. `ownershipNonce` identifies
11
+ * the lock only; it is NOT a process-start proof. NFS/network filesystems are best-effort.
12
+ */
13
+ import { hostname } from 'node:os';
14
+ import { randomBytes } from 'node:crypto';
15
+ import { StoreError, errnoOf } from './errors.js';
16
+ import { assertRegularFile } from './paths.js';
17
+ import { REAL_FS } from './fsops.js';
18
+ function pidLiveness(pid) {
19
+ try {
20
+ process.kill(pid, 0);
21
+ return 'alive';
22
+ }
23
+ catch (e) {
24
+ const c = errnoOf(e);
25
+ if (c === 'ESRCH')
26
+ return 'dead';
27
+ if (c === 'EPERM')
28
+ return 'alive'; // exists, owned by another user
29
+ return 'unknown';
30
+ }
31
+ }
32
+ function readMeta(fs, lockPath) {
33
+ let raw;
34
+ try {
35
+ raw = fs.readFileSync(lockPath);
36
+ }
37
+ catch {
38
+ return null;
39
+ }
40
+ try {
41
+ const o = JSON.parse(raw);
42
+ if (typeof o.pid === 'number' &&
43
+ typeof o.hostname === 'string' &&
44
+ typeof o.ownershipNonce === 'string' &&
45
+ typeof o.createdAt === 'string') {
46
+ return o;
47
+ }
48
+ }
49
+ catch {
50
+ /* fallthrough */
51
+ }
52
+ return null;
53
+ }
54
+ function writeFull(fs, fd, buf) {
55
+ let off = 0;
56
+ while (off < buf.length) {
57
+ const n = fs.writeSync(fd, buf, off, buf.length - off);
58
+ if (n <= 0)
59
+ throw new StoreError('sa_store_io_error');
60
+ off += n;
61
+ }
62
+ }
63
+ /**
64
+ * Acquire the EXCLUSIVE recovery-claim for one specific dead lock instance — an O_EXCL marker at
65
+ * `<lock>.recovering.<deadNonce>`, keyed by the DEAD instance's `ownershipNonce`, so exactly ONE recoverer of THAT
66
+ * exact instance proceeds. A SEPARATE file (never a rename of the lease → a live lease is never moved/orphaned).
67
+ *
68
+ * SAFETY-FIRST (SEGUNDO RE-GATE R2): the claim is **NOT auto-reclaimable**. On `EEXIST` we fail CLOSED with
69
+ * `codes.busy` — we NEVER `readMeta→unlink` a contended claim, because that "recover a lock with the same
70
+ * read→unlink protocol" is itself a TOCTOU (a concurrent recoverer could re-take the claim between the read and the
71
+ * unlink, and a stale observation must never authorise deleting a substituted claim). A claim left behind by a
72
+ * recoverer that crashed inside its own ~2-syscall critical section therefore requires EXPLICIT manual cleanup
73
+ * (`rm <lock>.recovering.*`) — a documented, fail-closed degraded state, NOT auto-recovery. Plain lockfiles cannot
74
+ * auto-recover safely without a fencing token; we do not over-claim crash-recovery of the claim itself.
75
+ */
76
+ function acquireRecoveryClaim(claimPath, fs, codes) {
77
+ try {
78
+ return fs.openSync(claimPath, 'wx', 0o600); // O_EXCL — the ONE recoverer of this dead instance
79
+ }
80
+ catch (e) {
81
+ if (errnoOf(e) === 'EEXIST')
82
+ throw new StoreError(codes.busy); // held (live OR crashed) → fail-closed, manual cleanup
83
+ throw new StoreError('sa_store_io_error', errnoOf(e));
84
+ }
85
+ }
86
+ /**
87
+ * EXPLICIT recovery of a provably-stale lock (the "manual recovery" path referenced by `acquireLock`): remove the
88
+ * lock file ONLY when it is a REGULAR file on THIS host whose PID is provably dead (ESRCH). NOT a TTL steal.
89
+ *
90
+ * SERIALIZATION (S1/T1 · RE-GATE F1): recoverers of THE SAME dead instance are serialized by an O_EXCL
91
+ * recovery-claim keyed by the dead `ownershipNonce` (`<path>.recovering.<nonce>`) — a SEPARATE file, never a rename
92
+ * of the lease, so a live lease is never moved/orphaned/dispossessed. UNDER that exclusive claim the lease can only
93
+ * be the exact dead instance (dead PID present) or absent — no fresh acquirer can O_EXCL-create over the present
94
+ * lease, and only WE may remove it — so the nonce re-validation before the single `unlink` can never race a live
95
+ * lease into being removed. Every unlink/close/cleanup failure is surfaced (never silent success), with
96
+ * primary>cleanup precedence. Returns `true` when reclaimed (or already gone); `codes.busy` for a
97
+ * live/foreign/contended holder; `codes.corrupt` for a malformed lock.
98
+ *
99
+ * Crash of a recoverer INSIDE its own claim critical section (documented, SEGUNDO RE-GATE R2): the claim is
100
+ * fail-closed and NOT auto-reclaimable — a second recoverer gets `codes.busy` and NEVER re-takes or unlinks it
101
+ * (so a stale observation can never authorise deleting a substituted claim/lease). That leftover
102
+ * `<path>.recovering.<nonce>` requires EXPLICIT manual cleanup (`rm`). This is the safety-first trade plain
103
+ * lockfiles must make without a fencing token; the backend commit idempotency (Capa 2) is the ultimate guard.
104
+ */
105
+ export function reclaimStaleLock(lockPath, codes, fs = REAL_FS) {
106
+ // Fast path (advisory): only bother taking the claim for a REGULAR, same-host, provably-dead lock.
107
+ if (assertRegularFile(lockPath, { notRegular: codes.corrupt }, fs) === 'absent')
108
+ return true;
109
+ const seen = readMeta(fs, lockPath);
110
+ if (!seen)
111
+ throw new StoreError(codes.corrupt);
112
+ if (seen.hostname !== hostname())
113
+ throw new StoreError(codes.busy); // foreign host → never steal
114
+ if (pidLiveness(seen.pid) !== 'dead')
115
+ throw new StoreError(codes.busy); // alive/unknown → never steal
116
+ const claimPath = `${lockPath}.recovering.${seen.ownershipNonce}`;
117
+ const claimFd = acquireRecoveryClaim(claimPath, fs, codes); // exclusive per-dead-instance recovery serialization
118
+ // R1: the claim carries the SAME full `LockMeta` shape `acquireLock` writes (pid/hostname/ownershipNonce/createdAt)
119
+ // — the exact bytes reclaimStaleLock persists — so a crash after the fsync leaves a well-formed (not corrupt) claim.
120
+ const claimMeta = { pid: process.pid, hostname: hostname(), ownershipNonce: randomBytes(16).toString('hex'), createdAt: new Date().toISOString() };
121
+ let primary;
122
+ let hasPrimary = false;
123
+ let reclaimed = false;
124
+ try {
125
+ writeFull(fs, claimFd, Buffer.from(`${JSON.stringify(claimMeta)}\n`, 'utf8'));
126
+ fs.fsyncSync(claimFd);
127
+ // Under the exclusive claim: the lease is either the exact dead instance we saw, or absent. Unlink ONLY that.
128
+ if (assertRegularFile(lockPath, { notRegular: codes.corrupt }, fs) === 'absent') {
129
+ reclaimed = true; // already gone
130
+ }
131
+ else {
132
+ const cur = readMeta(fs, lockPath);
133
+ if (!cur)
134
+ throw new StoreError(codes.corrupt);
135
+ if (cur.ownershipNonce !== seen.ownershipNonce || cur.hostname !== hostname() || pidLiveness(cur.pid) !== 'dead') {
136
+ throw new StoreError(codes.busy); // substituted / live → fail-closed, NEVER unlink it
137
+ }
138
+ try {
139
+ fs.unlinkSync(lockPath);
140
+ }
141
+ catch (e) {
142
+ if (errnoOf(e) !== 'ENOENT')
143
+ throw new StoreError('sa_store_io_error', errnoOf(e)); // ENOENT ⇒ already gone
144
+ }
145
+ reclaimed = true;
146
+ }
147
+ }
148
+ catch (e) {
149
+ primary = e;
150
+ hasPrimary = true;
151
+ }
152
+ // Release the claim ALL-ATTEMPT + FAIL-CLOSED (R3/R4): ALWAYS attempt BOTH close and unlink; capture EACH with an
153
+ // EXPLICIT boolean flag (a thrown value may be ANY JS value — `undefined`/`null`/`false`/`0`/`''` — so truthiness
154
+ // must never gate it). Precedence by IDENTITY: primary > close > unlink. `close` failing does not stop the unlink
155
+ // (we own the claim, so no one else removes it); ENOENT on unlink ⇒ already gone (not an error).
156
+ let closeErr;
157
+ let hasCloseErr = false;
158
+ try {
159
+ fs.closeSync(claimFd);
160
+ }
161
+ catch (e) {
162
+ closeErr = e;
163
+ hasCloseErr = true;
164
+ }
165
+ let unlinkErr;
166
+ let hasUnlinkErr = false;
167
+ try {
168
+ fs.unlinkSync(claimPath);
169
+ }
170
+ catch (e) {
171
+ if (errnoOf(e) !== 'ENOENT') {
172
+ unlinkErr = e;
173
+ hasUnlinkErr = true;
174
+ }
175
+ }
176
+ if (hasPrimary)
177
+ throw primary;
178
+ if (hasCloseErr)
179
+ throw closeErr instanceof StoreError ? closeErr : new StoreError('sa_store_io_error', errnoOf(closeErr));
180
+ if (hasUnlinkErr)
181
+ throw unlinkErr instanceof StoreError ? unlinkErr : new StoreError('sa_store_io_error', errnoOf(unlinkErr));
182
+ return reclaimed;
183
+ }
184
+ export function acquireLock(lockPath, codes, fs = REAL_FS) {
185
+ const meta = {
186
+ pid: process.pid,
187
+ hostname: hostname(),
188
+ ownershipNonce: randomBytes(16).toString('hex'),
189
+ createdAt: new Date().toISOString(),
190
+ };
191
+ // Build the inode privately, then publish it atomically. Opening `lockPath` itself before writing
192
+ // creates a real race: an EEXIST contender can read the still-empty/partial file and misclassify a
193
+ // live holder as `corrupt`. A same-directory hard link is atomic and fails with EEXIST when another
194
+ // fully-published contender won. A crash before publication leaves no functional lock; a crash after
195
+ // publication may leave only an inert staging hard-link, while `lockPath` remains valid and owned.
196
+ const stagingPath = `${lockPath}.creating.${meta.pid}.${meta.ownershipNonce}`;
197
+ let fd;
198
+ try {
199
+ fd = fs.openSync(stagingPath, 'wx', 0o600);
200
+ }
201
+ catch (e) {
202
+ throw new StoreError('sa_store_io_error', errnoOf(e));
203
+ }
204
+ try {
205
+ writeFull(fs, fd, Buffer.from(`${JSON.stringify(meta)}\n`, 'utf8'));
206
+ fs.fsyncSync(fd);
207
+ }
208
+ catch (e) {
209
+ try {
210
+ fs.closeSync(fd);
211
+ }
212
+ catch {
213
+ /* ignore */
214
+ }
215
+ try {
216
+ fs.unlinkSync(stagingPath); // remove ONLY our own incomplete staging inode
217
+ }
218
+ catch {
219
+ /* best-effort */
220
+ }
221
+ throw e instanceof StoreError ? e : new StoreError('sa_store_io_error', errnoOf(e));
222
+ }
223
+ try {
224
+ fs.closeSync(fd);
225
+ }
226
+ catch {
227
+ /* ignore */
228
+ }
229
+ try {
230
+ fs.linkSync(stagingPath, lockPath);
231
+ }
232
+ catch (e) {
233
+ try {
234
+ fs.unlinkSync(stagingPath);
235
+ }
236
+ catch {
237
+ /* best-effort */
238
+ }
239
+ if (errnoOf(e) === 'EEXIST') {
240
+ // Path safety (U9b-3a-bis §10.c#16, F1): only a REGULAR lock file may be read. symlink →
241
+ // sa_store_symlink_rejected; special/directory/absent → codes.corrupt; non-ENOENT lstat →
242
+ // sa_store_lstat_failed. NEVER readMeta a non-regular inode (a FIFO/socket/device could block).
243
+ // Publication happens only after a complete fsynced write, so a live contender cannot expose
244
+ // transient empty/partial metadata here.
245
+ assertRegularFile(lockPath, { notFound: codes.corrupt, notRegular: codes.corrupt }, fs);
246
+ const existing = readMeta(fs, lockPath);
247
+ if (!existing)
248
+ throw new StoreError(codes.corrupt);
249
+ const sameHost = existing.hostname === hostname();
250
+ if (sameHost && pidLiveness(existing.pid) === 'dead')
251
+ throw new StoreError(codes.stale);
252
+ throw new StoreError(codes.busy);
253
+ }
254
+ throw new StoreError('sa_store_io_error', errnoOf(e));
255
+ }
256
+ try {
257
+ fs.unlinkSync(stagingPath);
258
+ }
259
+ catch {
260
+ /* best-effort: lockPath is already the valid, owned publication */
261
+ }
262
+ let released = false;
263
+ // Re-check on every ownership decision via the SSOT regular-file gate (U9b-3a-bis §10.c#16, F1): a symlink
264
+ // → sa_store_symlink_rejected; a special/directory inode → codes.corrupt; a non-ENOENT lstat → sa_store_lstat_failed
265
+ // — all fail closed WITHOUT reading or unlinking. Only a REGULAR file reaches readMeta; absent → not-owner.
266
+ const ownedState = () => {
267
+ if (assertRegularFile(lockPath, { notRegular: codes.corrupt }, fs) === 'absent')
268
+ return 'notowner';
269
+ const current = readMeta(fs, lockPath); // only a regular file reaches here
270
+ if (current &&
271
+ current.ownershipNonce === meta.ownershipNonce &&
272
+ current.pid === meta.pid &&
273
+ current.hostname === meta.hostname) {
274
+ return 'owner';
275
+ }
276
+ return 'notowner';
277
+ };
278
+ return {
279
+ assertOwned() {
280
+ if (released)
281
+ throw new StoreError(codes.mismatch);
282
+ if (ownedState() !== 'owner')
283
+ throw new StoreError(codes.mismatch);
284
+ },
285
+ release() {
286
+ if (released)
287
+ return;
288
+ if (ownedState() !== 'owner')
289
+ throw new StoreError(codes.mismatch); // symlink/special/lstat-fail already threw
290
+ fs.unlinkSync(lockPath);
291
+ released = true;
292
+ },
293
+ };
294
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * U9b-2 · Path-safe name validation for profiles and handoffs (§10.b «PATH SAFETY»).
3
+ *
4
+ * Allowlist ONLY: `^[a-z0-9][a-z0-9_-]{0,63}$` (lowercase ASCII, no dot, no separator).
5
+ * This rejects empty, `.`, `..`, `/`, `\`, absolute paths, traversal, and any
6
+ * Unicode/confusable up front — the value is validated BEFORE a path is ever built.
7
+ */
8
+ import { StoreError } from './errors.js';
9
+ const NAME_RE = /^[a-z0-9][a-z0-9_-]{0,63}$/;
10
+ // Windows reserved device names (case-insensitive). The allowlist is lowercase, so a
11
+ // name like `con`/`nul`/`com1` would otherwise pass — reject them explicitly.
12
+ const RESERVED = new Set([
13
+ 'con',
14
+ 'prn',
15
+ 'aux',
16
+ 'nul',
17
+ ...Array.from({ length: 9 }, (_, i) => `com${i + 1}`),
18
+ ...Array.from({ length: 9 }, (_, i) => `lpt${i + 1}`),
19
+ ]);
20
+ function assertName(name, code) {
21
+ // nosemgrep: nodejs_scan.javascript-dos-rule-regex_dos -- NAME_RE is anchored and limits names to 128 characters.
22
+ if (typeof name !== 'string' || !NAME_RE.test(name) || RESERVED.has(name)) {
23
+ throw new StoreError(code);
24
+ }
25
+ return name;
26
+ }
27
+ /** Validate a profile name; throws `sa_profile_name_invalid` on any violation. */
28
+ export function assertProfileName(name) {
29
+ return assertName(name, 'sa_profile_name_invalid');
30
+ }
31
+ /** Validate a handoff id; throws `sa_handoff_id_invalid` on any violation. */
32
+ export function assertHandoffId(id) {
33
+ return assertName(id, 'sa_handoff_id_invalid');
34
+ }
35
+ // U9b-3a: rotation-artifact and receipt filenames are CANONICAL UUIDs (lowercase, RFC-4122 v1-5), NOT the
36
+ // generic profile/handoff name allowlist. A canonical UUID contains only [0-9a-f-] → path-safe by
37
+ // construction (no `/`,`\`,`.`,`..`, traversal). Validated BEFORE any path is built.
38
+ const CANONICAL_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}$/;
39
+ function assertUuid(id, code) {
40
+ // nosemgrep: nodejs_scan.javascript-dos-rule-regex_dos -- canonical UUID validation is fixed-width.
41
+ if (typeof id !== 'string' || !CANONICAL_UUID_RE.test(id))
42
+ throw new StoreError(code);
43
+ return id;
44
+ }
45
+ /** Validate a rotation-artifact operationId (canonical UUID); throws `sa_rotation_artifact_id_invalid`. */
46
+ export function assertRotationOperationId(id) {
47
+ return assertUuid(id, 'sa_rotation_artifact_id_invalid');
48
+ }
49
+ /** Validate a receipt id (canonical UUID); throws `sa_receipt_id_invalid`. */
50
+ export function assertReceiptId(id) {
51
+ return assertUuid(id, 'sa_receipt_id_invalid');
52
+ }
@@ -0,0 +1,219 @@
1
+ /**
2
+ * U9b-2/3a · Directory layout + managed-chain symlink/reparse rejection (§10.b «PATH SAFETY»).
3
+ *
4
+ * `root` is the trusted, injected HOME-equivalent boundary (production `os.homedir()`, tests a temp
5
+ * dir — so no test touches the real HOME). EVERY managed component under root (`.airctrl`, `.../sa`,
6
+ * `.../sa/handoffs|rotations|receipts`) is verified NOT to be a symlink/junction/reparse point before
7
+ * AND after we create it — checking only the final file is insufficient (a `.airctrl` junction would
8
+ * redirect the whole subtree). On POSIX a pre-existing managed dir with looser perms is tightened to
9
+ * 0700 (mkdir(mode) does NOT fix an existing dir); a non-directory or a symlinked component fails
10
+ * closed. Node reports Windows directory junctions as symbolic links via `lstat`, so the reproduced
11
+ * junction is blocked.
12
+ *
13
+ * U9b-3a F2: every filesystem inspection/creation/chmod flows through an injectable `FsOps` (default
14
+ * `REAL_FS`), so fault-injection tests exercise the SAME instance the stores capture — no bypass to
15
+ * the global `node:fs`. Callers pass their captured `fs`; the default preserves existing callers.
16
+ */
17
+ import { join } from 'node:path';
18
+ import { StoreError, errnoOf } from './errors.js';
19
+ import { REAL_FS } from './fsops.js';
20
+ const posix = process.platform !== 'win32';
21
+ const SA_SEGMENTS = ['.airctrl', 'sa'];
22
+ const HANDOFF_SEGMENTS = ['.airctrl', 'sa', 'handoffs'];
23
+ // U9b-3a: two more managed subtrees under `~/.airctrl/sa/` with the same 0700/symlink guarantees.
24
+ const ROTATION_SEGMENTS = ['.airctrl', 'sa', 'rotations'];
25
+ const RECEIPT_SEGMENTS = ['.airctrl', 'sa', 'receipts'];
26
+ // U4 Capa 3: the identity-rotation journal + its dedicated operation-bound lease live in their own managed
27
+ // subtree with the SAME 0700/symlink/path-safety guarantees.
28
+ const IDENTITY_ROTATION_SEGMENTS = ['.airctrl', 'sa', 'identity-rotations'];
29
+ export function saDir(root) {
30
+ return join(root, ...SA_SEGMENTS);
31
+ }
32
+ export function handoffDir(root) {
33
+ return join(root, ...HANDOFF_SEGMENTS);
34
+ }
35
+ export function rotationDir(root) {
36
+ return join(root, ...ROTATION_SEGMENTS);
37
+ }
38
+ export function receiptDir(root) {
39
+ return join(root, ...RECEIPT_SEGMENTS);
40
+ }
41
+ export function profileFile(name) {
42
+ return `${name}.json`;
43
+ }
44
+ export function profileLock(name) {
45
+ return `${name}.lock`;
46
+ }
47
+ /** U9b-4 · per-profile migration lease — a DISTINCT namespace from the brief `profileLock` (`${name}.lock`); this
48
+ * lease is held across the WHOLE `sa migrate` flow (unlock/prepare/status/complete), never during a profile lock. */
49
+ export function migrationLease(name) {
50
+ return `${name}.migration.lease`;
51
+ }
52
+ export function handoffFile(id) {
53
+ return `${id}.json`;
54
+ }
55
+ export function handoffLease(id) {
56
+ return `${id}.lease`;
57
+ }
58
+ export function rotationFile(operationId) {
59
+ return `${operationId}.json`;
60
+ }
61
+ export function receiptFile(id) {
62
+ return `${id}.json`;
63
+ }
64
+ export function identityRotationDir(root) {
65
+ return join(root, ...IDENTITY_ROTATION_SEGMENTS);
66
+ }
67
+ /** U4 Capa 3 · the single append-only journal file for an operation (`<operationId>.journal.json`). */
68
+ export function identityRotationJournalFile(operationId) {
69
+ return `${operationId}.journal.json`;
70
+ }
71
+ /** U4 Capa 3 · the DEDICATED operation-bound lease (distinct namespace from profile/migration/handoff leases). */
72
+ export function identityRotationLeaseFile(operationId) {
73
+ return `${operationId}.lease`;
74
+ }
75
+ export function ensureIdentityRotationDir(root, fs = REAL_FS) {
76
+ return ensureManaged(root, IDENTITY_ROTATION_SEGMENTS, fs);
77
+ }
78
+ export function assertIdentityRotationChain(root, fs = REAL_FS) {
79
+ assertManagedChain(root, IDENTITY_ROTATION_SEGMENTS, fs);
80
+ }
81
+ /** Throw `sa_store_symlink_rejected` if `path` exists AND is a symlink/junction. Absent → ok. Via `fs`. */
82
+ export function assertNotSymlink(path, fs = REAL_FS) {
83
+ let info;
84
+ try {
85
+ info = fs.lstat(path);
86
+ }
87
+ catch (e) {
88
+ throw new StoreError('sa_store_lstat_failed', errnoOf(e));
89
+ }
90
+ if (info.kind === 'symlink')
91
+ throw new StoreError('sa_store_symlink_rejected');
92
+ }
93
+ /**
94
+ * U9b-3a-bis (§10.c#16, F2/F4): SSOT that a managed leaf is a REGULAR file BEFORE any read/reconcile/delete.
95
+ * A non-ENOENT `lstat` failure → `sa_store_lstat_failed` (NEVER a conflict/reconcile code); a symlink →
96
+ * `sa_store_symlink_rejected`; a directory/special inode (FIFO/socket/device) → the surface's `notRegular`
97
+ * code (NEVER read/unlinked). `absent`: with `notFound` (read paths) → throw it; without (delete paths) →
98
+ * return `'absent'` so the caller's unlink ENOENT maps to its own absent outcome. Returns `'present'` only for
99
+ * a regular file. The ONLY primitive that gates a managed-leaf read/delete; no per-store duplication.
100
+ */
101
+ export function assertRegularFile(path, opts, fs = REAL_FS) {
102
+ let info;
103
+ try {
104
+ info = fs.lstat(path);
105
+ }
106
+ catch (e) {
107
+ throw new StoreError('sa_store_lstat_failed', errnoOf(e));
108
+ }
109
+ if (info.kind === 'absent') {
110
+ if (opts.notFound)
111
+ throw new StoreError(opts.notFound);
112
+ return 'absent';
113
+ }
114
+ if (info.kind === 'symlink')
115
+ throw new StoreError('sa_store_symlink_rejected');
116
+ if (info.kind !== 'file')
117
+ throw new StoreError(opts.notRegular);
118
+ return 'present';
119
+ }
120
+ /** Validate one managed component: reject symlink/junction/non-dir; on POSIX tighten perms to 0700. */
121
+ function checkManagedDir(dir, fs) {
122
+ let info;
123
+ try {
124
+ info = fs.lstat(dir);
125
+ }
126
+ catch (e) {
127
+ throw new StoreError('sa_store_lstat_failed', errnoOf(e));
128
+ }
129
+ if (info.kind === 'symlink')
130
+ throw new StoreError('sa_store_symlink_rejected');
131
+ if (info.kind !== 'directory')
132
+ throw new StoreError('sa_store_not_a_directory');
133
+ if (posix && (info.mode & 0o777) !== 0o700) {
134
+ try {
135
+ fs.chmodSync(dir, 0o700);
136
+ }
137
+ catch (e) {
138
+ throw new StoreError('sa_store_dir_perms_failed', errnoOf(e));
139
+ }
140
+ }
141
+ }
142
+ /** Walk `segments` under `root`, creating each missing dir 0700 and validating every component. */
143
+ function ensureManaged(root, segments, fs) {
144
+ let dir = root;
145
+ for (const seg of segments) {
146
+ dir = join(dir, seg);
147
+ let existed;
148
+ try {
149
+ existed = fs.lstat(dir).kind !== 'absent';
150
+ }
151
+ catch (e) {
152
+ throw new StoreError('sa_store_lstat_failed', errnoOf(e));
153
+ }
154
+ if (!existed) {
155
+ try {
156
+ fs.mkdir(dir, 0o700);
157
+ }
158
+ catch (e) {
159
+ // Another process may have created the shared managed dir concurrently — EEXIST is benign;
160
+ // fall through to checkManagedDir which validates (and rejects a symlink) either way.
161
+ if (errnoOf(e) !== 'EEXIST')
162
+ throw new StoreError('sa_store_dir_create_failed', errnoOf(e));
163
+ }
164
+ }
165
+ checkManagedDir(dir, fs); // re-lstat AFTER create: a symlink component fails closed
166
+ }
167
+ return dir;
168
+ }
169
+ /** Read-only validation of the managed chain (no creation); tolerates a not-yet-created leaf. */
170
+ function assertManagedChain(root, segments, fs) {
171
+ let dir = root;
172
+ for (const seg of segments) {
173
+ dir = join(dir, seg);
174
+ let info;
175
+ try {
176
+ info = fs.lstat(dir);
177
+ }
178
+ catch (e) {
179
+ throw new StoreError('sa_store_lstat_failed', errnoOf(e));
180
+ }
181
+ if (info.kind === 'absent')
182
+ return; // chain not fully present yet → caller's read will 404
183
+ if (info.kind === 'symlink')
184
+ throw new StoreError('sa_store_symlink_rejected');
185
+ if (info.kind !== 'directory')
186
+ throw new StoreError('sa_store_not_a_directory');
187
+ }
188
+ }
189
+ export function ensureSaDir(root, fs = REAL_FS) {
190
+ return ensureManaged(root, SA_SEGMENTS, fs);
191
+ }
192
+ export function ensureHandoffDir(root, fs = REAL_FS) {
193
+ return ensureManaged(root, HANDOFF_SEGMENTS, fs);
194
+ }
195
+ export function ensureRotationDir(root, fs = REAL_FS) {
196
+ return ensureManaged(root, ROTATION_SEGMENTS, fs);
197
+ }
198
+ export function ensureReceiptDir(root, fs = REAL_FS) {
199
+ return ensureManaged(root, RECEIPT_SEGMENTS, fs);
200
+ }
201
+ export function assertSaChain(root, fs = REAL_FS) {
202
+ assertManagedChain(root, SA_SEGMENTS, fs);
203
+ }
204
+ export function assertHandoffChain(root, fs = REAL_FS) {
205
+ assertManagedChain(root, HANDOFF_SEGMENTS, fs);
206
+ }
207
+ export function assertRotationChain(root, fs = REAL_FS) {
208
+ assertManagedChain(root, ROTATION_SEGMENTS, fs);
209
+ }
210
+ export function assertReceiptChain(root, fs = REAL_FS) {
211
+ assertManagedChain(root, RECEIPT_SEGMENTS, fs);
212
+ }
213
+ /** Validate the config dir chain (`.airctrl`), creating it. Used by config.ts. */
214
+ export function ensureConfigDir(root, fs = REAL_FS) {
215
+ return ensureManaged(root, ['.airctrl'], fs);
216
+ }
217
+ export function assertConfigChain(root, fs = REAL_FS) {
218
+ assertManagedChain(root, ['.airctrl'], fs);
219
+ }