@airctrl/cli 0.0.0-stage → 0.4.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 +2080 -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 +487 -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 +330 -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,38 @@
|
|
|
1
|
+
import { parseArgv, ParseError } from './parser.js';
|
|
2
|
+
import { resolveHumanClient } from './resolve-client.js';
|
|
3
|
+
const accountProfile = ['account', 'profile'];
|
|
4
|
+
export const SERVICE_ACCOUNT_READ_SPECS = {
|
|
5
|
+
list: { positionals: [], flags: accountProfile, requiredFlags: ['account'] },
|
|
6
|
+
get: { positionals: ['serviceAccountId'], flags: accountProfile, requiredFlags: ['account'] },
|
|
7
|
+
};
|
|
8
|
+
export const SERVICE_ACCOUNT_READ_USAGE = `airctrl sa read-only commands
|
|
9
|
+
|
|
10
|
+
list --account <id>
|
|
11
|
+
get <serviceAccountId> --account <id>
|
|
12
|
+
`;
|
|
13
|
+
function clientFor(parsed, deps) {
|
|
14
|
+
return resolveHumanClient({ ...deps.resolve, profileFlag: parsed.flags.profile }).client;
|
|
15
|
+
}
|
|
16
|
+
function writeResult(value, deps) {
|
|
17
|
+
const out = deps.stdout ?? ((text) => process.stdout.write(text));
|
|
18
|
+
out(`${JSON.stringify(value, null, 2)}\n`);
|
|
19
|
+
}
|
|
20
|
+
export async function runServiceAccountReadCommand(argv, deps) {
|
|
21
|
+
const [command, ...rest] = argv;
|
|
22
|
+
if (command === undefined || command === 'help' || command === '--help') {
|
|
23
|
+
;
|
|
24
|
+
(deps.stdout ?? ((text) => process.stdout.write(text)))(SERVICE_ACCOUNT_READ_USAGE);
|
|
25
|
+
return 0;
|
|
26
|
+
}
|
|
27
|
+
if (!Object.hasOwn(SERVICE_ACCOUNT_READ_SPECS, command)) {
|
|
28
|
+
throw new ParseError('cli_unknown_command');
|
|
29
|
+
}
|
|
30
|
+
const parsed = parseArgv(rest, SERVICE_ACCOUNT_READ_SPECS[command]);
|
|
31
|
+
const client = clientFor(parsed, deps);
|
|
32
|
+
const options = { accountId: parsed.flags.account };
|
|
33
|
+
const result = command === 'list'
|
|
34
|
+
? await client.listServiceAccounts(options)
|
|
35
|
+
: await client.getServiceAccount(parsed.positionals[0], options);
|
|
36
|
+
writeResult(result, deps);
|
|
37
|
+
return 0;
|
|
38
|
+
}
|
|
@@ -0,0 +1,344 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* U9b-2 · Crash-safe atomic CREATE + REPLACE (§10.b #3/#4). Node stdlib only, via an injectable
|
|
3
|
+
* {@link FsOps} so the real create/replace paths (not just helpers) are fault-injection tested.
|
|
4
|
+
*
|
|
5
|
+
* CREATE (temp + exclusive hard-link): the destination name appears ONLY once the temp is fully
|
|
6
|
+
* written+fsynced and `link` publishes it. Commit point = a successful `link`; after it, `dest`
|
|
7
|
+
* is NEVER deleted during cleanup — a post-link failure is reconciled by reading `dest` back and
|
|
8
|
+
* comparing it to the exact canonical payload.
|
|
9
|
+
*
|
|
10
|
+
* REPLACE (temp + rename, under a caller-held lock): temp write+fsync, atomic rename over the
|
|
11
|
+
* existing file, chmod(dest), fsync(parent). POSIX gives the real guarantees; Windows fsync-dir /
|
|
12
|
+
* perms / rename durability are best-effort — Node documents fs.rename only as "Renames oldPath to newPath."
|
|
13
|
+
*
|
|
14
|
+
* U9b-3a-bis (§10.c#16): the single `durable:boolean` is replaced by structured {@link PersistenceEvidence}
|
|
15
|
+
* — `content` (committed|reconciled), `permissions` (secured|best_effort|failed: regular-file + 0600 on POSIX,
|
|
16
|
+
* best_effort on win32), `directory` (durable|unsupported|failed, AGGREGATED worst-of over every required
|
|
17
|
+
* fsyncDir), and an independent `residualTemp`. A managed secret file is NEVER read/reconciled without first
|
|
18
|
+
* verifying it is a REGULAR file (no FIFO/socket/device).
|
|
19
|
+
*/
|
|
20
|
+
import { join } from 'node:path';
|
|
21
|
+
import { randomBytes } from 'node:crypto';
|
|
22
|
+
import { StoreError, errnoOf } from './errors.js';
|
|
23
|
+
import { assertNotSymlink, assertRegularFile } from './paths.js';
|
|
24
|
+
import { canonicalJson } from './canonical.js';
|
|
25
|
+
import { REAL_FS } from './fsops.js';
|
|
26
|
+
/**
|
|
27
|
+
* SSOT security predicate for {@link PersistenceEvidence} (U9b-3c §10.c#16.F/D1). The ONLY judge of whether a
|
|
28
|
+
* managed write is safe to build on — shared by EVERY U9b-3c surface (handoff pre-HTTP, bootstrap finalize,
|
|
29
|
+
* rotation artifact, receipt) so no command re-implements the truth table. STRICT capability↔evidence
|
|
30
|
+
* consistency: it fails CLOSED on any contradiction, INCLUDING the four inverses (a `secured` on a non-POSIX
|
|
31
|
+
* fs, a `best_effort` on POSIX, a `durable` without the dir-fsync capability, an `unsupported` with it) — not
|
|
32
|
+
* just the obvious `failed`. `requireCleanTemp` gates the `residualTemp` axis ONLY: receipts pass `true` (a
|
|
33
|
+
* residual temp is a write failure); handoff/rotation pass `false` (a residual temp is a separate logged
|
|
34
|
+
* cleanup concern, never an insecurity). `content` (`committed`|`reconciled`) is never gated.
|
|
35
|
+
*/
|
|
36
|
+
export function evidenceSecure(ev, fs, opts) {
|
|
37
|
+
// permissions ↔ posixPermissions capability. Both crosses fail closed; `'failed'` is insecure everywhere.
|
|
38
|
+
const permissionsOk = fs.posixPermissions ? ev.permissions === 'secured' : ev.permissions === 'best_effort';
|
|
39
|
+
// directory ↔ directoryFsyncSupported capability. Both crosses fail closed; `'failed'` is insecure everywhere.
|
|
40
|
+
const directoryOk = fs.directoryFsyncSupported ? ev.directory === 'durable' : ev.directory === 'unsupported';
|
|
41
|
+
// file inode fsync must be durable (the SEPARATE axis from directory). content is NOT gated.
|
|
42
|
+
const fileOk = ev.file === 'durable';
|
|
43
|
+
// residualTemp only blocks when the surface demands a clean temp (receipts).
|
|
44
|
+
const tempOk = !ev.residualTemp || !opts.requireCleanTemp;
|
|
45
|
+
return permissionsOk && directoryOk && fileOk && tempOk;
|
|
46
|
+
}
|
|
47
|
+
// Directory-durability severity for worst-of aggregation: failed > unsupported > durable.
|
|
48
|
+
const DIR_SEVERITY = { durable: 0, unsupported: 1, failed: 2 };
|
|
49
|
+
function worseDir(a, b) {
|
|
50
|
+
return DIR_SEVERITY[a] >= DIR_SEVERITY[b] ? a : b;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Classify the permissions of a managed secret FILE. POSIX `secured` ⇔ regular file ∧ `(mode&0o777)===0o600`.
|
|
54
|
+
* win32 `best_effort` (chmod+lstat ok + regular file): the POSIX bits do NOT prove the effective ACL, but no
|
|
55
|
+
* real error occurred. `failed` = chmod failed ∨ lstat failed ∨ non-regular ∨ symlink ∨ (POSIX) mode≠0600.
|
|
56
|
+
*/
|
|
57
|
+
function classifyPermissions(fs, dest, chmodOk) {
|
|
58
|
+
if (!chmodOk)
|
|
59
|
+
return 'failed';
|
|
60
|
+
let info;
|
|
61
|
+
try {
|
|
62
|
+
info = fs.lstat(dest);
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
return 'failed';
|
|
66
|
+
}
|
|
67
|
+
if (info.kind !== 'file')
|
|
68
|
+
return 'failed'; // symlink / directory / special / absent → not a managed regular file
|
|
69
|
+
if (!fs.posixPermissions)
|
|
70
|
+
return 'best_effort'; // win32: bits reported, ACL not proven — but no real failure
|
|
71
|
+
return (info.mode & 0o777) === 0o600 ? 'secured' : 'failed';
|
|
72
|
+
}
|
|
73
|
+
function writeFull(fs, fd, buf) {
|
|
74
|
+
let off = 0;
|
|
75
|
+
while (off < buf.length) {
|
|
76
|
+
const n = fs.writeSync(fd, buf, off, buf.length - off);
|
|
77
|
+
if (n <= 0)
|
|
78
|
+
throw new StoreError('sa_store_io_error');
|
|
79
|
+
off += n;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
export function mapWriteErrno(e) {
|
|
83
|
+
const c = errnoOf(e);
|
|
84
|
+
if (c === 'EACCES' || c === 'EPERM')
|
|
85
|
+
return new StoreError('sa_store_access_denied');
|
|
86
|
+
if (c === 'ENOSPC')
|
|
87
|
+
return new StoreError('sa_store_no_space');
|
|
88
|
+
return new StoreError('sa_store_io_error');
|
|
89
|
+
}
|
|
90
|
+
// Classify a `link` failure. "Hard-link unsupported" is scoped NARROWLY to errnos that mean the
|
|
91
|
+
// operation is not supported here (ENOTSUP/EOPNOTSUPP/ENOSYS/EXDEV cross-device). EPERM is
|
|
92
|
+
// treated as access/policy denial (NOT auto-mapped to no-hardlink), keeping the classes distinct.
|
|
93
|
+
export function mapLinkErrno(e) {
|
|
94
|
+
const c = errnoOf(e);
|
|
95
|
+
if (c === 'EEXIST')
|
|
96
|
+
return new StoreError('sa_store_dest_exists');
|
|
97
|
+
if (c === 'EACCES' || c === 'EPERM')
|
|
98
|
+
return new StoreError('sa_store_access_denied');
|
|
99
|
+
if (c === 'ENOSPC')
|
|
100
|
+
return new StoreError('sa_store_no_space');
|
|
101
|
+
if (c === 'ENOTSUP' || c === 'EOPNOTSUPP' || c === 'ENOSYS' || c === 'EXDEV') {
|
|
102
|
+
return new StoreError('sa_store_no_hardlink');
|
|
103
|
+
}
|
|
104
|
+
return new StoreError('sa_store_io_error');
|
|
105
|
+
}
|
|
106
|
+
/** Write `canonical` to a fresh 0600 temp in `dir`, fully fsynced. Returns the temp path. */
|
|
107
|
+
function writeTemp(fs, dir, fileName, canonical) {
|
|
108
|
+
const tmp = join(dir, `.${fileName}.${randomBytes(9).toString('hex')}.tmp`);
|
|
109
|
+
let fd;
|
|
110
|
+
try {
|
|
111
|
+
fd = fs.openSync(tmp, 'wx', 0o600);
|
|
112
|
+
writeFull(fs, fd, Buffer.from(canonical, 'utf8'));
|
|
113
|
+
fs.fsyncSync(fd);
|
|
114
|
+
fs.closeSync(fd);
|
|
115
|
+
fd = undefined;
|
|
116
|
+
fs.chmodSync(tmp, 0o600);
|
|
117
|
+
return tmp;
|
|
118
|
+
}
|
|
119
|
+
catch (e) {
|
|
120
|
+
if (fd !== undefined) {
|
|
121
|
+
try {
|
|
122
|
+
fs.closeSync(fd);
|
|
123
|
+
}
|
|
124
|
+
catch {
|
|
125
|
+
/* ignore */
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
try {
|
|
129
|
+
fs.unlinkSync(tmp);
|
|
130
|
+
}
|
|
131
|
+
catch {
|
|
132
|
+
/* best-effort: our own temp */
|
|
133
|
+
}
|
|
134
|
+
throw e instanceof StoreError ? e : mapWriteErrno(e);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Atomically CREATE `dir/fileName` with `canonical`, exclusively (no overwrite). Commit point =
|
|
139
|
+
* successful hard-link. Post-link errors never delete `dest`; they are reconciled against `canonical`.
|
|
140
|
+
*/
|
|
141
|
+
export function atomicCreate(dir, fileName, canonical, fs = REAL_FS) {
|
|
142
|
+
const dest = join(dir, fileName);
|
|
143
|
+
assertNotSymlink(dest, fs);
|
|
144
|
+
const tmp = writeTemp(fs, dir, fileName, canonical);
|
|
145
|
+
// --- publish exclusively (commit point) ---
|
|
146
|
+
try {
|
|
147
|
+
fs.linkSync(tmp, dest);
|
|
148
|
+
}
|
|
149
|
+
catch (e) {
|
|
150
|
+
try {
|
|
151
|
+
fs.unlinkSync(tmp);
|
|
152
|
+
}
|
|
153
|
+
catch {
|
|
154
|
+
/* best-effort: our own temp; dest was NOT created */
|
|
155
|
+
}
|
|
156
|
+
throw e instanceof StoreError ? e : mapLinkErrno(e);
|
|
157
|
+
}
|
|
158
|
+
// --- post-commit: NEVER delete dest; best-effort durability + temp cleanup ---
|
|
159
|
+
return { outcome: 'created', ...finishPublish(fs, dir, dest, tmp, canonical, false) };
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Atomically REPLACE `dir/fileName` with `canonical` (caller MUST hold the profile lock and have
|
|
163
|
+
* verified the expected stage/transition). Rename is the swap; post-rename durability is best-effort.
|
|
164
|
+
*/
|
|
165
|
+
export function atomicReplace(dir, fileName, canonical, fs = REAL_FS) {
|
|
166
|
+
const dest = join(dir, fileName);
|
|
167
|
+
assertNotSymlink(dest, fs);
|
|
168
|
+
const tmp = writeTemp(fs, dir, fileName, canonical);
|
|
169
|
+
try {
|
|
170
|
+
fs.renameSync(tmp, dest);
|
|
171
|
+
}
|
|
172
|
+
catch (e) {
|
|
173
|
+
try {
|
|
174
|
+
fs.unlinkSync(tmp);
|
|
175
|
+
}
|
|
176
|
+
catch {
|
|
177
|
+
/* best-effort */
|
|
178
|
+
}
|
|
179
|
+
throw e instanceof StoreError ? e : mapWriteErrno(e);
|
|
180
|
+
}
|
|
181
|
+
// rename consumes the temp — no temp unlink phase → a SINGLE required fsyncDir.
|
|
182
|
+
return { outcome: 'replaced', ...finishPublish(fs, dir, dest, tmp, canonical, true) };
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* Shared post-commit sequence → structured evidence: chmod(dest) + classify permissions → fsync(parent) →
|
|
186
|
+
* unlink(temp) → fsync(parent). Never deletes dest. `directory` = worst-of every required fsyncDir (CREATE=2,
|
|
187
|
+
* REPLACE=1); the second fsync is attempted even if the temp unlink failed. A read-back verifies the bytes
|
|
188
|
+
* whenever durability is not fully proven or a temp lingered.
|
|
189
|
+
*/
|
|
190
|
+
function finishPublish(fs, dir, dest, tmp, canonical, skipTempUnlink) {
|
|
191
|
+
let chmodOk = true;
|
|
192
|
+
try {
|
|
193
|
+
fs.chmodSync(dest, 0o600);
|
|
194
|
+
}
|
|
195
|
+
catch {
|
|
196
|
+
chmodOk = false;
|
|
197
|
+
}
|
|
198
|
+
const permissions = classifyPermissions(fs, dest, chmodOk);
|
|
199
|
+
let directory = fs.fsyncDir(dir);
|
|
200
|
+
let residualTemp = false;
|
|
201
|
+
if (!skipTempUnlink) {
|
|
202
|
+
try {
|
|
203
|
+
fs.unlinkSync(tmp);
|
|
204
|
+
}
|
|
205
|
+
catch {
|
|
206
|
+
residualTemp = true;
|
|
207
|
+
}
|
|
208
|
+
directory = worseDir(directory, fs.fsyncDir(dir)); // second flush ALWAYS attempted; aggregate worst-of
|
|
209
|
+
}
|
|
210
|
+
if (directory !== 'durable' || residualTemp || permissions !== 'secured') {
|
|
211
|
+
reconcileAgainst(fs, dest, canonical); // read-back (regular-file guarded), not mere existence
|
|
212
|
+
}
|
|
213
|
+
// CREATE/REPLACE publish a temp that was write+fsync+close'd in `writeTemp`, so the inode's content is
|
|
214
|
+
// durable by construction — the SEPARATE `file` axis is `'durable'` here (F1). Only the parent dir-entry
|
|
215
|
+
// durability (`directory`) is best-effort/platform-dependent.
|
|
216
|
+
return { content: 'committed', permissions, file: 'durable', directory, residualTemp };
|
|
217
|
+
}
|
|
218
|
+
/** Read `dest` back and require it to equal the exact canonical payload; else fail closed. Regular-file first. */
|
|
219
|
+
export function reconcileAgainst(fs, dest, canonical) {
|
|
220
|
+
// lstat failure → sa_store_lstat_failed; symlink → sa_store_symlink_rejected; special → not-regular; absent
|
|
221
|
+
// (a just-published dest that vanished) → reconcile_failed. NEVER readFileSync a non-regular inode (F2/F4).
|
|
222
|
+
assertRegularFile(dest, { notFound: 'sa_store_reconcile_failed', notRegular: 'sa_store_not_regular_file' }, fs);
|
|
223
|
+
let actual;
|
|
224
|
+
try {
|
|
225
|
+
actual = fs.readFileSync(dest);
|
|
226
|
+
}
|
|
227
|
+
catch (e) {
|
|
228
|
+
throw new StoreError('sa_store_reconcile_failed', errnoOf(e));
|
|
229
|
+
}
|
|
230
|
+
if (actual !== canonical)
|
|
231
|
+
throw new StoreError('sa_store_reconcile_failed');
|
|
232
|
+
}
|
|
233
|
+
/**
|
|
234
|
+
* HONEST durability + permissions evidence for an ALREADY-EXISTING, canonically-identical destination
|
|
235
|
+
* (U9b-3a-bis §10.c#16). Byte-equality proves current CONTENT, not that those bytes survive a crash, so we
|
|
236
|
+
* re-flush the file: `openSync(dest,'r+')` — POSIX `O_RDWR` NEVER truncates and requires the file to exist;
|
|
237
|
+
* it is WRITABLE, which Windows `FlushFileBuffers` (the `fsync` backend) requires (GENERIC_WRITE). Then
|
|
238
|
+
* `fsyncSync(fd)`, close (exactly once), and `fsyncDir(parent)`. Never throws. The `directory` axis reflects
|
|
239
|
+
* the WORST of the file re-flush (a failure → at least `failed`) and the parent dir-fsync result; `permissions`
|
|
240
|
+
* re-verifies the existing file is a regular 0600 file (POSIX) / best_effort (win32).
|
|
241
|
+
*/
|
|
242
|
+
function reconcileExistingDurable(fs, dest, dir) {
|
|
243
|
+
const permissions = classifyPermissions(fs, dest, true); // verify existing mode (no chmod on the reconcile path)
|
|
244
|
+
// FILE axis: re-flush the inode. `openSync(dest,'r+')` — POSIX O_RDWR never truncates and requires the file
|
|
245
|
+
// to exist; it is WRITABLE, which Windows FlushFileBuffers requires. `file:'durable'` ONLY if open + fsync +
|
|
246
|
+
// close ALL succeed; any failure → `file:'failed'`. Close exactly once (only when opened).
|
|
247
|
+
let fileOk = true;
|
|
248
|
+
let fd;
|
|
249
|
+
try {
|
|
250
|
+
fd = fs.openSync(dest, 'r+');
|
|
251
|
+
fs.fsyncSync(fd);
|
|
252
|
+
}
|
|
253
|
+
catch {
|
|
254
|
+
fileOk = false;
|
|
255
|
+
}
|
|
256
|
+
finally {
|
|
257
|
+
if (fd !== undefined) {
|
|
258
|
+
try {
|
|
259
|
+
fs.closeSync(fd);
|
|
260
|
+
}
|
|
261
|
+
catch {
|
|
262
|
+
fileOk = false;
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
// DIRECTORY axis: EXCLUSIVELY the parent dir-entry fsync (F1 — a FILE failure is NEVER a directory failure).
|
|
267
|
+
// Attempted best-effort even if the file re-flush failed; a throw is honest `failed`, NOT a conflict.
|
|
268
|
+
let directory;
|
|
269
|
+
try {
|
|
270
|
+
directory = fs.fsyncDir(dir);
|
|
271
|
+
}
|
|
272
|
+
catch {
|
|
273
|
+
directory = 'failed';
|
|
274
|
+
}
|
|
275
|
+
return { permissions, file: fileOk ? 'durable' : 'failed', directory };
|
|
276
|
+
}
|
|
277
|
+
/**
|
|
278
|
+
* SSOT for idempotent atomic CREATE (U9b-3a §10.c#14). Shared by the provisional-handoff and rotation-artifact
|
|
279
|
+
* stores (NOT receipts — those are create-exclusive, no reconcile). Tries `atomicCreate`; on the ONLY caught
|
|
280
|
+
* error `sa_store_dest_exists`, strictly reconciles the existing destination against the expected canonical
|
|
281
|
+
* (via the caller's `validate`): a byte/schema mismatch → the stable `conflictCode` (never overwrite/delete,
|
|
282
|
+
* never leak raw errors/paths/content); an exact match → `{outcome:'reconciled', ...evidence}`.
|
|
283
|
+
*/
|
|
284
|
+
export function atomicCreateIdempotent(dir, fileName, canonical, opts, fs = REAL_FS) {
|
|
285
|
+
try {
|
|
286
|
+
return atomicCreate(dir, fileName, canonical, fs);
|
|
287
|
+
}
|
|
288
|
+
catch (e) {
|
|
289
|
+
if (!(e instanceof StoreError) || e.code !== 'sa_store_dest_exists')
|
|
290
|
+
throw e;
|
|
291
|
+
const dest = join(dir, fileName);
|
|
292
|
+
// Regular-file gate (F4): lstat-fail → sa_store_lstat_failed; symlink → sa_store_symlink_rejected; special →
|
|
293
|
+
// sa_store_not_regular_file; absent (raced away) → conflictCode. Conflict is asserted ONLY below, after a
|
|
294
|
+
// SAFE read+validate of a regular file whose canonical content differs — never from a failed inspection.
|
|
295
|
+
assertRegularFile(dest, { notFound: opts.conflictCode, notRegular: 'sa_store_not_regular_file' }, fs);
|
|
296
|
+
let raw;
|
|
297
|
+
try {
|
|
298
|
+
raw = fs.readFileSync(dest);
|
|
299
|
+
}
|
|
300
|
+
catch {
|
|
301
|
+
throw new StoreError(opts.conflictCode);
|
|
302
|
+
}
|
|
303
|
+
let validated;
|
|
304
|
+
try {
|
|
305
|
+
validated = opts.validate(JSON.parse(raw));
|
|
306
|
+
}
|
|
307
|
+
catch {
|
|
308
|
+
throw new StoreError(opts.conflictCode); // corrupt / wrong-shape persisted doc ⇒ not the same doc
|
|
309
|
+
}
|
|
310
|
+
if (canonicalJson(validated) !== canonical)
|
|
311
|
+
throw new StoreError(opts.conflictCode);
|
|
312
|
+
const { permissions, file, directory } = reconcileExistingDurable(fs, dest, dir);
|
|
313
|
+
return { outcome: 'reconciled', content: 'reconciled', permissions, file, directory, residualTemp: false };
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
/**
|
|
317
|
+
* Reconcile an ALREADY-FINALIZED handoff during `finalize` replay (caller holds the lease). Same strict
|
|
318
|
+
* canonical-match + honest-evidence contract as {@link atomicCreateIdempotent}, but the destination already
|
|
319
|
+
* exists (a REPLACE-phase reconcile): a mismatch → `conflictCode`; a match → `{outcome:'reconciled', …}`.
|
|
320
|
+
* Never overwrites/deletes; never leaks raw errors/paths/content.
|
|
321
|
+
*/
|
|
322
|
+
export function reconcileFinalizedDurable(fs, dest, dir, canonical, validate, conflictCode) {
|
|
323
|
+
// Regular-file gate (F4): lstat-fail → sa_store_lstat_failed; symlink → sa_store_symlink_rejected; special →
|
|
324
|
+
// sa_store_not_regular_file; absent → conflictCode. Conflict only from a safe read + canonical mismatch below.
|
|
325
|
+
assertRegularFile(dest, { notFound: conflictCode, notRegular: 'sa_store_not_regular_file' }, fs);
|
|
326
|
+
let raw;
|
|
327
|
+
try {
|
|
328
|
+
raw = fs.readFileSync(dest);
|
|
329
|
+
}
|
|
330
|
+
catch {
|
|
331
|
+
throw new StoreError(conflictCode);
|
|
332
|
+
}
|
|
333
|
+
let validated;
|
|
334
|
+
try {
|
|
335
|
+
validated = validate(JSON.parse(raw));
|
|
336
|
+
}
|
|
337
|
+
catch {
|
|
338
|
+
throw new StoreError(conflictCode);
|
|
339
|
+
}
|
|
340
|
+
if (canonicalJson(validated) !== canonical)
|
|
341
|
+
throw new StoreError(conflictCode);
|
|
342
|
+
const { permissions, file, directory } = reconcileExistingDurable(fs, dest, dir);
|
|
343
|
+
return { outcome: 'reconciled', content: 'reconciled', permissions, file, directory, residualTemp: false };
|
|
344
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* U9b-2 · baseUrl validation + normalization (§10.b #8).
|
|
3
|
+
*
|
|
4
|
+
* Uses the runtime `URL` parser (never manual parsing). Forbids userinfo, query and
|
|
5
|
+
* hash. HTTPS is required except for HTTP loopback (localhost / 127.0.0.1 / ::1).
|
|
6
|
+
* Normalizes hostname case, trailing slash and default ports, then compares canonical
|
|
7
|
+
* forms so an env override that is textually different but semantically identical is
|
|
8
|
+
* accepted, while a genuine mismatch fails closed.
|
|
9
|
+
*/
|
|
10
|
+
import { StoreError } from './errors.js';
|
|
11
|
+
function isLoopbackHost(hostname) {
|
|
12
|
+
const bare = hostname.replace(/^\[/, '').replace(/\]$/, '').toLowerCase();
|
|
13
|
+
return bare === 'localhost' || bare === '127.0.0.1' || bare === '::1';
|
|
14
|
+
}
|
|
15
|
+
/** Parse, validate and return the canonical form of `raw`. Throws stable codes. */
|
|
16
|
+
export function normalizeBaseUrl(raw) {
|
|
17
|
+
if (typeof raw !== 'string' || raw.trim().length === 0) {
|
|
18
|
+
throw new StoreError('sa_baseurl_invalid');
|
|
19
|
+
}
|
|
20
|
+
let u;
|
|
21
|
+
try {
|
|
22
|
+
u = new URL(raw.trim());
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
throw new StoreError('sa_baseurl_invalid');
|
|
26
|
+
}
|
|
27
|
+
if (u.username || u.password)
|
|
28
|
+
throw new StoreError('sa_baseurl_userinfo_forbidden');
|
|
29
|
+
if (u.search)
|
|
30
|
+
throw new StoreError('sa_baseurl_query_forbidden');
|
|
31
|
+
if (u.hash)
|
|
32
|
+
throw new StoreError('sa_baseurl_hash_forbidden');
|
|
33
|
+
const loopback = isLoopbackHost(u.hostname);
|
|
34
|
+
if (u.protocol === 'http:') {
|
|
35
|
+
if (!loopback)
|
|
36
|
+
throw new StoreError('sa_insecure_baseurl');
|
|
37
|
+
}
|
|
38
|
+
else if (u.protocol !== 'https:') {
|
|
39
|
+
throw new StoreError('sa_baseurl_scheme_forbidden');
|
|
40
|
+
}
|
|
41
|
+
const host = u.hostname.toLowerCase(); // URL keeps [..] brackets for IPv6
|
|
42
|
+
const port = u.port ? `:${u.port}` : ''; // URL already drops default 80/443
|
|
43
|
+
let path = u.pathname;
|
|
44
|
+
if (path === '/')
|
|
45
|
+
path = '';
|
|
46
|
+
else if (path.endsWith('/'))
|
|
47
|
+
path = path.replace(/\/+$/, '');
|
|
48
|
+
return `${u.protocol}//${host}${port}${path}`;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Assert two baseUrls are the same after normalization. Used when an SA env override
|
|
52
|
+
* (`AC_API_BASE_URL`) coexists with a profile/handoff-persisted baseUrl: equal → allow,
|
|
53
|
+
* different → `sa_baseurl_conflict` (never a silent override).
|
|
54
|
+
*/
|
|
55
|
+
export function assertBaseUrlMatch(a, b) {
|
|
56
|
+
const na = normalizeBaseUrl(a);
|
|
57
|
+
const nb = normalizeBaseUrl(b);
|
|
58
|
+
if (na !== nb)
|
|
59
|
+
throw new StoreError('sa_baseurl_conflict');
|
|
60
|
+
return na;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Resolve the authoritative baseUrl for a profile/handoff: the persisted value is authoritative;
|
|
64
|
+
* an optional `AC_API_BASE_URL` override is accepted ONLY if it normalizes identically (else
|
|
65
|
+
* `sa_baseurl_conflict`). Returns the canonical form. Reusable by U9b-3 for handoffs.
|
|
66
|
+
*/
|
|
67
|
+
export function resolveEffectiveBaseUrl(persisted, override) {
|
|
68
|
+
if (override === undefined)
|
|
69
|
+
return normalizeBaseUrl(persisted);
|
|
70
|
+
return assertBaseUrlMatch(persisted, override);
|
|
71
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* U9b-2 · Canonical JSON + canonical base64 helpers.
|
|
3
|
+
*
|
|
4
|
+
* A profile/handoff is persisted as canonical JSON (recursively key-sorted, no
|
|
5
|
+
* insignificant whitespace) so that post-commit reconciliation can compare the
|
|
6
|
+
* on-disk bytes against the exact payload the caller intended to write.
|
|
7
|
+
*/
|
|
8
|
+
/** Recursively key-sorted JSON with a trailing newline. Deterministic for a given value. */
|
|
9
|
+
export function canonicalJson(value) {
|
|
10
|
+
return `${stableStringify(value)}\n`;
|
|
11
|
+
}
|
|
12
|
+
function stableStringify(value) {
|
|
13
|
+
if (value === null || typeof value !== 'object')
|
|
14
|
+
return JSON.stringify(value);
|
|
15
|
+
if (Array.isArray(value))
|
|
16
|
+
return `[${value.map(stableStringify).join(',')}]`;
|
|
17
|
+
const obj = value;
|
|
18
|
+
const keys = Object.keys(obj).sort();
|
|
19
|
+
const parts = keys.map((k) => `${JSON.stringify(k)}:${stableStringify(obj[k])}`);
|
|
20
|
+
return `{${parts.join(',')}}`;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* True iff `s` is canonical (standard, padded) base64: decoding then re-encoding
|
|
24
|
+
* yields the exact same string. Rejects base64url, missing/extra padding, and
|
|
25
|
+
* embedded whitespace. When `expectedBytes` is given, also checks the byte length.
|
|
26
|
+
*/
|
|
27
|
+
export function isCanonicalB64(s, expectedBytes) {
|
|
28
|
+
if (typeof s !== 'string' || s.length === 0)
|
|
29
|
+
return false;
|
|
30
|
+
// nosemgrep: nodejs_scan.javascript-dos-rule-regex_dos -- anchored canonical base64 validation is linear and followed by decode/re-encode verification.
|
|
31
|
+
if (!/^[A-Za-z0-9+/]+={0,2}$/.test(s))
|
|
32
|
+
return false;
|
|
33
|
+
let buf;
|
|
34
|
+
try {
|
|
35
|
+
buf = Buffer.from(s, 'base64');
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
return false;
|
|
39
|
+
}
|
|
40
|
+
if (buf.toString('base64') !== s)
|
|
41
|
+
return false;
|
|
42
|
+
if (expectedBytes !== undefined && buf.length !== expectedBytes)
|
|
43
|
+
return false;
|
|
44
|
+
return true;
|
|
45
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* U9b-3e-P0 · Durable managed-file deletion SSOT (§10.c#18.5).
|
|
3
|
+
*
|
|
4
|
+
* The SINGLE primitive that removes a managed lifecycle leaf AND flushes the parent directory so the
|
|
5
|
+
* removal survives a crash — the previous per-store deletes did `unlinkSync` with NO `fsyncDir`, so a
|
|
6
|
+
* post-unlink crash could resurrect the directory entry. This is metadata / crash-consistency durability,
|
|
7
|
+
* NOT a secure erase: no physical byte shredding is performed or claimed.
|
|
8
|
+
*
|
|
9
|
+
* Contract (§10.c#18.5): the managed chain is validated with the SAME injected {@link FsOps} — the primitive
|
|
10
|
+
* HANDS its own instance to the `assertChain(fs)` callback, and every current caller validates with that
|
|
11
|
+
* parameter (tests assert the identity by reference). The parent flushed is ALWAYS `dirname(leafPath)` (derived
|
|
12
|
+
* here, never a caller-supplied directory — so evidence can never be forged by flushing an unrelated dir). The leaf is
|
|
13
|
+
* gated as a REGULAR file (symlink → `sa_store_symlink_rejected`, special/directory → `sa_store_not_regular_file`,
|
|
14
|
+
* non-ENOENT lstat → `sa_store_lstat_failed`, all WITHOUT unlink); a present regular file is unlinked; an
|
|
15
|
+
* `unlinkSync` ENOENT and an initially-absent leaf both resolve to `outcome:'absent'`. BOTH `deleted` and
|
|
16
|
+
* `absent` then run `fsyncDir(parent)` EXACTLY ONCE — so a retry that finds the leaf already gone still
|
|
17
|
+
* re-flushes the directory and can complete durably. A `fsyncDir` that RETURNS `'failed'` OR THROWS both
|
|
18
|
+
* collapse to `directory:'failed'` (no raw OS message/path/sentinel escapes). A non-ENOENT `unlinkSync`
|
|
19
|
+
* failure maps to the stable `sa_store_io_error`.
|
|
20
|
+
*/
|
|
21
|
+
import { dirname } from 'node:path';
|
|
22
|
+
import { StoreError, errnoOf } from './errors.js';
|
|
23
|
+
import { assertRegularFile } from './paths.js';
|
|
24
|
+
/**
|
|
25
|
+
* Flush `dir` for durability, collapsing BOTH a returned `'failed'` AND a direct throw of an injected
|
|
26
|
+
* `fsyncDir` into `'failed'` — never letting a raw OS message/path/sentinel escape. The single place the
|
|
27
|
+
* primitive (and the absence-confirmation helper) obtain directory evidence.
|
|
28
|
+
*/
|
|
29
|
+
function fsyncDirSafe(dir, fs) {
|
|
30
|
+
try {
|
|
31
|
+
return fs.fsyncDir(dir);
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
return 'failed'; // an injected/real fsyncDir throw is a failed flush — never propagate raw
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Remove a managed leaf and prove (or honestly fail to prove) the removal is directory-durable. `assertChain`
|
|
39
|
+
* validates the managed subtree with the SAME `fs` the primitive owns; `leafPath` is the file removed and its
|
|
40
|
+
* `dirname` is the flushed parent. No path classification or capability logic is duplicated here — it delegates
|
|
41
|
+
* to `assertRegularFile` and `fsyncDirSafe`.
|
|
42
|
+
*/
|
|
43
|
+
export function durableDelete(leafPath, assertChain, fs) {
|
|
44
|
+
assertChain(fs); // managed-chain fail-closed with the SAME fs (symlink/junction → sa_store_symlink_rejected; lstat-fail → sa_store_lstat_failed)
|
|
45
|
+
// Regular-file gate BEFORE unlink: absent → 'absent' (no notFound); symlink → sa_store_symlink_rejected;
|
|
46
|
+
// special/directory → sa_store_not_regular_file; non-ENOENT lstat → sa_store_lstat_failed. NEVER unlink a non-regular inode.
|
|
47
|
+
const present = assertRegularFile(leafPath, { notRegular: 'sa_store_not_regular_file' }, fs);
|
|
48
|
+
let outcome;
|
|
49
|
+
if (present === 'absent') {
|
|
50
|
+
outcome = 'absent';
|
|
51
|
+
}
|
|
52
|
+
else {
|
|
53
|
+
try {
|
|
54
|
+
fs.unlinkSync(leafPath);
|
|
55
|
+
outcome = 'deleted';
|
|
56
|
+
}
|
|
57
|
+
catch (e) {
|
|
58
|
+
if (errnoOf(e) === 'ENOENT')
|
|
59
|
+
outcome = 'absent'; // raced removal → absent (still flush below)
|
|
60
|
+
else
|
|
61
|
+
throw new StoreError('sa_store_io_error'); // non-ENOENT → stable code, never a raw OS message/path
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
// BOTH 'deleted' and 'absent' MUST flush the parent directory EXACTLY once so the (un)link is crash-durable.
|
|
65
|
+
const directory = fsyncDirSafe(dirname(leafPath), fs);
|
|
66
|
+
return { outcome, directory };
|
|
67
|
+
}
|
|
68
|
+
export function confirmDurableAbsence(leafPath, assertChain, fs) {
|
|
69
|
+
assertChain(fs);
|
|
70
|
+
// Re-lstat fail-closed: absent → confirm; symlink/special/lstat-fail preserve their code; a regular file
|
|
71
|
+
// reappeared → 'present' (the caller must NOT unlink it without ownership → lease branch).
|
|
72
|
+
if (assertRegularFile(leafPath, { notRegular: 'sa_store_not_regular_file' }, fs) === 'absent') {
|
|
73
|
+
return { outcome: 'absent', directory: fsyncDirSafe(dirname(leafPath), fs) };
|
|
74
|
+
}
|
|
75
|
+
return { outcome: 'present' };
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* SSOT security predicate for a {@link DurableDeleteResult} / {@link AbsenceProof} (§10.c#18.5) — the analogue
|
|
79
|
+
* of `evidenceSecure` for deletions, its OWN predicate (never reuse/deform `evidenceSecure`). STRICT
|
|
80
|
+
* capability↔evidence cross: a supported platform is secure ONLY with `directory:'durable'`; an unsupported
|
|
81
|
+
* one ONLY with `directory:'unsupported'`; `'failed'` and every contradictory cross fail closed. Identical for
|
|
82
|
+
* `deleted` and `absent` (the outcome is never consulted).
|
|
83
|
+
*/
|
|
84
|
+
export function deleteEvidenceSecure(result, fs) {
|
|
85
|
+
return fs.directoryFsyncSupported ? result.directory === 'durable' : result.directory === 'unsupported';
|
|
86
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* U9b-2 · Stable, secret-safe error type for the SA multi-profile store.
|
|
3
|
+
*
|
|
4
|
+
* `code` is a stable machine-readable identifier (never localized, never derived from
|
|
5
|
+
* OS messages). Messages carry ONLY the code plus non-secret descriptors (profile name,
|
|
6
|
+
* stage). They MUST NEVER include bearers, cap-private keys, claim tickets, profile
|
|
7
|
+
* contents, temp paths, or raw OS error strings — see §10.b «SECRET EXPOSURE».
|
|
8
|
+
*/
|
|
9
|
+
export class StoreError extends Error {
|
|
10
|
+
code;
|
|
11
|
+
constructor(code, detail) {
|
|
12
|
+
super(detail ? `${code}: ${detail}` : code);
|
|
13
|
+
this.name = 'StoreError';
|
|
14
|
+
this.code = code;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
/** Narrow an unknown thrown value to a Node errno string without leaking the message. */
|
|
18
|
+
export function errnoOf(e) {
|
|
19
|
+
if (e && typeof e === 'object' && 'code' in e) {
|
|
20
|
+
const c = e.code;
|
|
21
|
+
if (typeof c === 'string')
|
|
22
|
+
return c;
|
|
23
|
+
}
|
|
24
|
+
return undefined;
|
|
25
|
+
}
|