@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,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* U9b-3b · CLI error boundary types (§10.c#15.G). Every user-facing failure carries a STABLE `code`; the
|
|
3
|
+
* thin binary prints exactly `airctrl: <code>` (or the reconciliation form) and NEVER a raw message, path,
|
|
4
|
+
* bearer, capability, profile JSON or plaintext. The dispatcher/core THROWS these; only the bin maps them
|
|
5
|
+
* to a single stderr line + `process.exitCode`.
|
|
6
|
+
*/
|
|
7
|
+
/** A stable-coded CLI failure. `detail` is for local logic only and is NEVER printed. */
|
|
8
|
+
export class CliError extends Error {
|
|
9
|
+
code;
|
|
10
|
+
constructor(code, detail) {
|
|
11
|
+
super(detail ? `${code}: ${detail}` : code);
|
|
12
|
+
this.name = 'CliError';
|
|
13
|
+
this.code = code;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* A ratified SA reconciliation signal (§10.c#9): printed as `sa_reconciliation_required reason=<reason>`.
|
|
18
|
+
* `authorization_expired` (U9b-3a-bis §10.c#16) covers a durable authorize whose pending remote credential
|
|
19
|
+
* already expired (finalized/rotation-artifact/replay); the reason set stays a CLOSED union (no arbitrary reason).
|
|
20
|
+
*/
|
|
21
|
+
export class ReconcileError extends Error {
|
|
22
|
+
code = 'sa_reconciliation_required';
|
|
23
|
+
reason;
|
|
24
|
+
constructor(reason) {
|
|
25
|
+
super(`sa_reconciliation_required reason=${reason}`);
|
|
26
|
+
this.name = 'ReconcileError';
|
|
27
|
+
this.reason = reason;
|
|
28
|
+
}
|
|
29
|
+
}
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,502 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* U9b-3b · CLI core / dispatcher (§10.c#15.E–H). Importable and side-effect-free: importing this module
|
|
3
|
+
* runs NOTHING (the thin `index.ts` bin is the only entry that executes). The core NEVER calls
|
|
4
|
+
* `process.exit`; it returns an exit code and THROWS stable-coded errors (ParseError/StoreError/CliError/
|
|
5
|
+
* ReconcileError/AirctrlError). Ordering per command: parse → resolve principal/client ONCE → validate
|
|
6
|
+
* stage/deadline/project → prompt ONLY for human → run SDK. All seams (env, stdout/stderr, clock, vault
|
|
7
|
+
* prompt, spawn, principal/client factories) are injectable for deterministic tests.
|
|
8
|
+
*/
|
|
9
|
+
import { spawn as realSpawn } from 'node:child_process';
|
|
10
|
+
import os from 'node:os';
|
|
11
|
+
import { readFileSync } from 'node:fs';
|
|
12
|
+
import { generateSecret, canGenerate, isSecretFormat, generatorOptionSpec, AirctrlError, } from '@airctrl/sdk';
|
|
13
|
+
import { parseArgv, recordEnvironmentFlag, ParseError } from './parser.js';
|
|
14
|
+
import { resolveClient, resolveHumanClient } from './resolve-client.js';
|
|
15
|
+
import { CliError, ReconcileError } from './cli-error.js';
|
|
16
|
+
import { runSaCommand, buildSaDeps } from './sa-commands.js';
|
|
17
|
+
import { runGatewayCommand } from './gateway-commands.js';
|
|
18
|
+
import { runRecordCommand } from './record-commands.js';
|
|
19
|
+
import { runProjectCommand } from './project-commands.js';
|
|
20
|
+
import { runGroupCommand } from './group-commands.js';
|
|
21
|
+
import { runServiceAccountReadCommand, SERVICE_ACCOUNT_READ_SPECS, } from './service-account-read-commands.js';
|
|
22
|
+
import { withPatExpired } from './pat-expired.js';
|
|
23
|
+
import { StoreError } from './store/index.js';
|
|
24
|
+
import { loadConfig, resolveBaseUrl, saveConfig } from './config.js';
|
|
25
|
+
import { promptHidden, promptLine, resolveVaultPassword as realResolveVaultPassword } from './prompt.js';
|
|
26
|
+
// The 8 AIRCTRL control vars stripped from the child env before overlaying injected records (§10.c#15.F +
|
|
27
|
+
// §10.b#7.bis — `AC_SA_SERVICE_ACCOUNT_ID` companion added in U9b-3e-2 so a child never inherits SA authority/identity).
|
|
28
|
+
const CONTROL_VARS = [
|
|
29
|
+
'AC_TOKEN',
|
|
30
|
+
'AC_SA_CREDENTIAL_ID',
|
|
31
|
+
'AC_SA_CAP_PRIVATE_KEY_B64',
|
|
32
|
+
'AC_SA_SERVICE_ACCOUNT_ID',
|
|
33
|
+
'AC_SA_PRINCIPAL',
|
|
34
|
+
'AC_SA_PROFILE',
|
|
35
|
+
'AC_API_BASE_URL',
|
|
36
|
+
'AC_VAULT_PASSWORD',
|
|
37
|
+
];
|
|
38
|
+
/** Record name → env var key (UPPER_SNAKE, safe chars only) — unchanged from the human `run` behavior. */
|
|
39
|
+
function envName(recordName) {
|
|
40
|
+
return recordName
|
|
41
|
+
.trim()
|
|
42
|
+
.toUpperCase()
|
|
43
|
+
.replace(/[^A-Z0-9_]/g, '_')
|
|
44
|
+
.replace(/^_+|_+$/g, '');
|
|
45
|
+
}
|
|
46
|
+
/** Convert decrypted AIRCTRL records into the values a child process actually consumes. */
|
|
47
|
+
function injectRecord(injected, secret) {
|
|
48
|
+
if (secret.format === 'env') {
|
|
49
|
+
for (const [fieldName, fieldValue] of Object.entries(secret.fields)) {
|
|
50
|
+
if (!['string', 'number', 'boolean'].includes(typeof fieldValue))
|
|
51
|
+
continue;
|
|
52
|
+
const key = envName(fieldName);
|
|
53
|
+
if (key)
|
|
54
|
+
injected[key] = String(fieldValue);
|
|
55
|
+
}
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
const key = envName(secret.name);
|
|
59
|
+
if (!key)
|
|
60
|
+
return;
|
|
61
|
+
const body = secret.fields.body;
|
|
62
|
+
injected[key] = typeof body === 'string' ? body : secret.value;
|
|
63
|
+
}
|
|
64
|
+
/** Per-command grammars (exported so tests exercise the REAL specs, not a re-declared copy). */
|
|
65
|
+
export const SPECS = {
|
|
66
|
+
login: { positionals: [], flags: [] },
|
|
67
|
+
get: { positionals: ['recordId'], flags: ['profile', 'env'] },
|
|
68
|
+
read: { positionals: ['recordId'], flags: ['profile', 'scope', 'env'] },
|
|
69
|
+
run: { positionals: [], flags: ['project', 'profile', 'env'], passthrough: true },
|
|
70
|
+
generate: {
|
|
71
|
+
positionals: ['format'],
|
|
72
|
+
flags: [],
|
|
73
|
+
optionsFromPositional: 0,
|
|
74
|
+
optionSpec: (f) => generatorOptionSpec(f),
|
|
75
|
+
},
|
|
76
|
+
// `--project` is NOT a required flag: a human may rely on config `defaultProject`. Only `--name` is required.
|
|
77
|
+
// When neither `--project` nor the default resolves, the command throws `cli_project_required` (§10.c#15.F4).
|
|
78
|
+
create: {
|
|
79
|
+
positionals: ['format'],
|
|
80
|
+
flags: ['project', 'name', 'tags', 'secret-due', 'rotation-days', 'idempotency-key', 'profile', 'env'],
|
|
81
|
+
requiredFlags: ['name'],
|
|
82
|
+
repeatable: ['field'],
|
|
83
|
+
keyValue: ['field'],
|
|
84
|
+
},
|
|
85
|
+
set: {
|
|
86
|
+
positionals: ['format'],
|
|
87
|
+
flags: ['project', 'name', 'tags', 'secret-due', 'rotation-days', 'idempotency-key', 'profile', 'env'],
|
|
88
|
+
requiredFlags: ['name'],
|
|
89
|
+
repeatable: ['field'],
|
|
90
|
+
keyValue: ['field'],
|
|
91
|
+
},
|
|
92
|
+
new: {
|
|
93
|
+
positionals: ['format'],
|
|
94
|
+
flags: ['project', 'name', 'tags', 'secret-due', 'rotation-days', 'idempotency-key', 'profile', 'env'],
|
|
95
|
+
requiredFlags: ['name'],
|
|
96
|
+
optionsFromPositional: 0,
|
|
97
|
+
optionSpec: (f) => generatorOptionSpec(f),
|
|
98
|
+
},
|
|
99
|
+
import: {
|
|
100
|
+
positionals: ['kind', 'file'],
|
|
101
|
+
flags: [
|
|
102
|
+
'project',
|
|
103
|
+
'name',
|
|
104
|
+
'target-env',
|
|
105
|
+
'env',
|
|
106
|
+
'tags',
|
|
107
|
+
'secret-due',
|
|
108
|
+
'rotation-days',
|
|
109
|
+
'idempotency-key',
|
|
110
|
+
'profile',
|
|
111
|
+
],
|
|
112
|
+
requiredFlags: ['name'],
|
|
113
|
+
},
|
|
114
|
+
};
|
|
115
|
+
/** Top-level commands that can run with a Service Account identity. */
|
|
116
|
+
export const SERVICE_ACCOUNT_CORE_COMMANDS = ['get', 'read', 'run', 'generate'];
|
|
117
|
+
export const USAGE = `airctrl — inject AIRCTRL secrets into your process (client-side decrypt)
|
|
118
|
+
|
|
119
|
+
airctrl login
|
|
120
|
+
airctrl get <recordId> [--env development|staging|production] [--profile <name>]
|
|
121
|
+
airctrl read <recordId> [--scope a,b] [--env development|staging|production] [--profile <name>]
|
|
122
|
+
airctrl run [--project <id>] [--env development|staging|production] [--profile <name>] -- <cmd> [args]
|
|
123
|
+
airctrl generate <format> [--opt value …]
|
|
124
|
+
airctrl create|set <format> --name <n> [--project <id>] [--field k=v …] [--env development|staging|production] [--profile <name>]
|
|
125
|
+
airctrl new <format> --name <n> [--project <id>] [--opt value …] [--env development|staging|production] [--profile <name>]
|
|
126
|
+
airctrl import env <file> --name <n> [--project <id>] [--target-env <e>] [--env development|staging|production] [--profile <name>]
|
|
127
|
+
airctrl gateway <command> [args] [--profile <name>] (run: airctrl gateway help)
|
|
128
|
+
airctrl record <command> [args] [--profile <name>] (run: airctrl record help)
|
|
129
|
+
airctrl project <command> [args] [--profile <name>] (run: airctrl project help)
|
|
130
|
+
airctrl group <command> [args] [--profile <name>] (run: airctrl group help)
|
|
131
|
+
airctrl sa list|get [args] [--profile <name>] (run: airctrl sa help)
|
|
132
|
+
|
|
133
|
+
Env: AC_TOKEN, AC_API_BASE_URL, AC_VAULT_PASSWORD, AC_SA_* (see docs).
|
|
134
|
+
`;
|
|
135
|
+
// A stable error code is a short lower-snake token: starts lowercase, only [a-z0-9_], bounded length. This
|
|
136
|
+
// is the ONLY shape ever printed to stderr. API `code` values that fail it are discarded; API messages are
|
|
137
|
+
// private except for the closed product-code allowlist below, so attacker-influenced text never reaches the tty.
|
|
138
|
+
const STABLE_CODE_RE = /^[a-z][a-z0-9_]{0,63}$/;
|
|
139
|
+
const PUBLIC_ENTITLEMENT_ERROR_CODES = new Set([
|
|
140
|
+
'no_active_plan',
|
|
141
|
+
'plan_feature_locked',
|
|
142
|
+
'plan_limit_reached',
|
|
143
|
+
'record_type_limit_reached',
|
|
144
|
+
'record_type_locked',
|
|
145
|
+
'resource_locked',
|
|
146
|
+
'seats_exhausted',
|
|
147
|
+
'subscription_inactive',
|
|
148
|
+
]);
|
|
149
|
+
export function isStableCode(code) {
|
|
150
|
+
return typeof code === 'string' && STABLE_CODE_RE.test(code);
|
|
151
|
+
}
|
|
152
|
+
/** Translate any thrown value into a stable code (+optional reconciliation reason). Never leaks raw text. */
|
|
153
|
+
export function toStableError(e) {
|
|
154
|
+
if (e instanceof ReconcileError)
|
|
155
|
+
return { code: 'sa_reconciliation_required', reason: e.reason };
|
|
156
|
+
if (e instanceof ParseError)
|
|
157
|
+
return { code: e.code };
|
|
158
|
+
if (e instanceof CliError)
|
|
159
|
+
return { code: e.code };
|
|
160
|
+
if (e instanceof StoreError)
|
|
161
|
+
return { code: e.code };
|
|
162
|
+
if (e instanceof AirctrlError) {
|
|
163
|
+
// Nest's HTTP envelope uses the generic `forbidden` code and a stable message for entitlement failures.
|
|
164
|
+
// Promote only this closed set of public product codes; arbitrary API messages remain private even when
|
|
165
|
+
// they happen to match the stable-code syntax.
|
|
166
|
+
if (e.status === 403 && e.code === 'forbidden' && PUBLIC_ENTITLEMENT_ERROR_CODES.has(e.message)) {
|
|
167
|
+
return { code: e.message };
|
|
168
|
+
}
|
|
169
|
+
// Any other external API code is preserved ONLY if it passes the stable-code validator; otherwise it
|
|
170
|
+
// collapses to `cli_internal_error`. Details are never printed regardless.
|
|
171
|
+
if (isStableCode(e.code))
|
|
172
|
+
return { code: e.code };
|
|
173
|
+
}
|
|
174
|
+
return { code: 'cli_internal_error' };
|
|
175
|
+
}
|
|
176
|
+
function resolveClientDeps(deps, profileFlag) {
|
|
177
|
+
return {
|
|
178
|
+
env: deps.env,
|
|
179
|
+
profileFlag,
|
|
180
|
+
profileRoot: deps.profileRoot,
|
|
181
|
+
now: deps.now,
|
|
182
|
+
resolvePrincipalFn: deps.resolvePrincipalFn,
|
|
183
|
+
makeClient: deps.makeClient,
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
/** Build a child env: strip the 8 control vars from a copy, THEN overlay injected records (record wins). */
|
|
187
|
+
function sanitizeChildEnv(source, injected) {
|
|
188
|
+
const base = { ...source };
|
|
189
|
+
for (const k of CONTROL_VARS)
|
|
190
|
+
delete base[k];
|
|
191
|
+
return { ...base, ...injected };
|
|
192
|
+
}
|
|
193
|
+
function spawnChild(spawnFn, command, env) {
|
|
194
|
+
return new Promise((resolve, reject) => {
|
|
195
|
+
const child = spawnFn(command[0], command.slice(1), { stdio: 'inherit', env });
|
|
196
|
+
child.on('error', () => reject(new CliError('cli_child_spawn_failed')));
|
|
197
|
+
child.on('exit', (code, signal) => {
|
|
198
|
+
if (code !== null) {
|
|
199
|
+
resolve(code);
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
// Node v22: on 'exit', exactly one of (code, signal) is non-null. Translate a signal to the conventional
|
|
203
|
+
// `128 + signalNumber` exit STATUS (NOT a real re-raise of the signal). An unknown signal fails closed.
|
|
204
|
+
const n = os.constants.signals[signal];
|
|
205
|
+
if (typeof n === 'number') {
|
|
206
|
+
resolve(128 + n);
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
reject(new CliError('cli_internal_error'));
|
|
210
|
+
});
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
// ── Commands ────────────────────────────────────────────────────────────────────────────────────────────
|
|
214
|
+
async function cmdLogin(argv, deps) {
|
|
215
|
+
parseArgv(argv, SPECS.login); // strict: `login` takes NO positionals/flags → junk fails BEFORE any IO
|
|
216
|
+
const out = deps.stdout ?? ((s) => process.stdout.write(s));
|
|
217
|
+
const line = deps.promptLineFn ?? promptLine;
|
|
218
|
+
const hidden = deps.promptHiddenFn ?? promptHidden;
|
|
219
|
+
const load = deps.loadConfigFn ?? loadConfig;
|
|
220
|
+
const save = deps.saveConfigFn ?? saveConfig;
|
|
221
|
+
const cfg = load(deps.profileRoot);
|
|
222
|
+
const baseUrl = (await line(`API base URL [${resolveBaseUrl(cfg)}]: `)) || resolveBaseUrl(cfg);
|
|
223
|
+
const token = await hidden('Personal access token (sk-actrl-pat-…): ');
|
|
224
|
+
if (!token)
|
|
225
|
+
throw new CliError('cli_not_authenticated'); // no credential to store
|
|
226
|
+
const defaultProject = (await line('Default project id (optional): ')) || undefined;
|
|
227
|
+
save({ baseUrl, token, defaultProject }, deps.profileRoot);
|
|
228
|
+
out('Saved to ~/.airctrl/config.json\n');
|
|
229
|
+
return 0;
|
|
230
|
+
}
|
|
231
|
+
async function cmdGet(argv, deps) {
|
|
232
|
+
const parsed = parseArgv(argv, SPECS.get);
|
|
233
|
+
const environment = recordEnvironmentFlag(parsed.flags.env);
|
|
234
|
+
const rc = resolveClient(resolveClientDeps(deps, parsed.flags.profile));
|
|
235
|
+
const vaultPassword = rc.needsVaultPassword ? await (deps.resolveVaultPasswordFn ?? realResolveVaultPassword)() : undefined;
|
|
236
|
+
const secret = await withPatExpired(rc, () => rc.client.getSecret({ recordId: parsed.positionals[0], vaultPassword,
|
|
237
|
+
...(environment ? { environment } : {}) }));
|
|
238
|
+
(deps.stdout ?? ((s) => process.stdout.write(s)))(`${secret.value}\n`);
|
|
239
|
+
return 0;
|
|
240
|
+
}
|
|
241
|
+
async function cmdRead(argv, deps) {
|
|
242
|
+
const parsed = parseArgv(argv, SPECS.read);
|
|
243
|
+
const environment = recordEnvironmentFlag(parsed.flags.env);
|
|
244
|
+
const rc = resolveClient(resolveClientDeps(deps, parsed.flags.profile));
|
|
245
|
+
const scope = parsed.flags.scope
|
|
246
|
+
? parsed.flags.scope.split(',').map((x) => x.trim()).filter(Boolean)
|
|
247
|
+
: undefined;
|
|
248
|
+
const vaultPassword = rc.needsVaultPassword ? await (deps.resolveVaultPasswordFn ?? realResolveVaultPassword)() : undefined;
|
|
249
|
+
const rec = await withPatExpired(rc, () => rc.client.readRecord({ recordId: parsed.positionals[0], vaultPassword, scope, environment }));
|
|
250
|
+
(deps.stdout ?? ((s) => process.stdout.write(s)))(`${JSON.stringify(rec, null, 2)}\n`);
|
|
251
|
+
return 0;
|
|
252
|
+
}
|
|
253
|
+
async function cmdRun(argv, deps) {
|
|
254
|
+
const parsed = parseArgv(argv, SPECS.run);
|
|
255
|
+
const environment = recordEnvironmentFlag(parsed.flags.env);
|
|
256
|
+
const command = parsed.childArgv;
|
|
257
|
+
if (!command || command.length === 0)
|
|
258
|
+
throw new CliError('cli_missing_positional'); // no `-- <cmd>`
|
|
259
|
+
const rc = resolveClient(resolveClientDeps(deps, parsed.flags.profile));
|
|
260
|
+
// Resolve the project to a CONCRETE id BEFORE any prompt/fetch/spawn. `getAll` is never called with an
|
|
261
|
+
// undefined projectId (that would inject EVERY accessible secret — the widened-scope regression, F5).
|
|
262
|
+
let projectId;
|
|
263
|
+
if (rc.principalKind === 'sa') {
|
|
264
|
+
if (!parsed.flags.project)
|
|
265
|
+
throw new CliError('sa_run_requires_project'); // SA never reads human config
|
|
266
|
+
projectId = parsed.flags.project;
|
|
267
|
+
}
|
|
268
|
+
else {
|
|
269
|
+
const resolved = parsed.flags.project ?? rc.defaultProject; // human may use the config default
|
|
270
|
+
if (!resolved)
|
|
271
|
+
throw new CliError('cli_project_required'); // neither flag nor default → refuse, don't widen
|
|
272
|
+
projectId = resolved;
|
|
273
|
+
}
|
|
274
|
+
const vaultPassword = rc.needsVaultPassword ? await (deps.resolveVaultPasswordFn ?? realResolveVaultPassword)() : undefined;
|
|
275
|
+
const secrets = await withPatExpired(rc, () => rc.client.getAll({ projectId, vaultPassword, audit: false,
|
|
276
|
+
...(environment ? { environment } : {}) }));
|
|
277
|
+
const injected = {};
|
|
278
|
+
for (const secret of secrets)
|
|
279
|
+
injectRecord(injected, secret);
|
|
280
|
+
(deps.stderr ?? ((s) => process.stderr.write(s)))(`airctrl: injected ${secrets.length} secret(s)\n`); // COUNT only
|
|
281
|
+
const childEnv = sanitizeChildEnv(deps.env ?? process.env, injected);
|
|
282
|
+
return spawnChild(deps.spawnFn ?? realSpawn, command, childEnv);
|
|
283
|
+
}
|
|
284
|
+
async function cmdGenerate(argv, deps) {
|
|
285
|
+
// Pure local: NO principal/config/profile resolution, NO prompt, never vetoed by SA env vars.
|
|
286
|
+
const parsed = parseArgv(argv, SPECS.generate);
|
|
287
|
+
const format = parsed.positionals[0];
|
|
288
|
+
if (!isSecretFormat(format) || !canGenerate(format))
|
|
289
|
+
throw new CliError('cli_flag_invalid_value');
|
|
290
|
+
const { fields } = await generateSecret(format, parsed.options);
|
|
291
|
+
(deps.stdout ?? ((s) => process.stdout.write(s)))(`${JSON.stringify(fields, null, 2)}\n`);
|
|
292
|
+
return 0;
|
|
293
|
+
}
|
|
294
|
+
/** Resolve `--project` for a write command, falling back to the human default; refuse if neither exists. */
|
|
295
|
+
function requireProject(flagProject, defaultProject) {
|
|
296
|
+
const project = flagProject ?? defaultProject;
|
|
297
|
+
if (!project)
|
|
298
|
+
throw new CliError('cli_project_required');
|
|
299
|
+
return project;
|
|
300
|
+
}
|
|
301
|
+
function writeMetadata(flags) {
|
|
302
|
+
const metadata = {};
|
|
303
|
+
if (flags.tags !== undefined) {
|
|
304
|
+
if (flags.tags === 'none')
|
|
305
|
+
metadata.tags = [];
|
|
306
|
+
else {
|
|
307
|
+
const tags = flags.tags.split(',').map((tag) => tag.trim()).filter(Boolean);
|
|
308
|
+
if (tags.length === 0)
|
|
309
|
+
throw new ParseError('cli_flag_invalid_value');
|
|
310
|
+
metadata.tags = tags;
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
if (flags['secret-due'] !== undefined) {
|
|
314
|
+
metadata.secretDueAt = flags['secret-due'] === 'null' ? null : flags['secret-due'];
|
|
315
|
+
}
|
|
316
|
+
if (flags['rotation-days'] !== undefined) {
|
|
317
|
+
if (flags['rotation-days'] === 'null')
|
|
318
|
+
metadata.rotationIntervalDays = null;
|
|
319
|
+
else {
|
|
320
|
+
if (!/^\d+$/.test(flags['rotation-days']))
|
|
321
|
+
throw new ParseError('cli_flag_invalid_value');
|
|
322
|
+
const days = Number(flags['rotation-days']);
|
|
323
|
+
if (!Number.isSafeInteger(days) || days < 1)
|
|
324
|
+
throw new ParseError('cli_flag_invalid_value');
|
|
325
|
+
metadata.rotationIntervalDays = days;
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
if (flags['idempotency-key'] !== undefined)
|
|
329
|
+
metadata.idempotencyKey = flags['idempotency-key'];
|
|
330
|
+
return metadata;
|
|
331
|
+
}
|
|
332
|
+
async function cmdCreateOrSet(argv, deps, upsert) {
|
|
333
|
+
const parsed = parseArgv(argv, upsert ? SPECS.set : SPECS.create);
|
|
334
|
+
const environment = recordEnvironmentFlag(parsed.flags.env);
|
|
335
|
+
const { client, defaultProject } = resolveHumanClient(resolveClientDeps(deps, parsed.flags.profile)); // VETO first
|
|
336
|
+
const format = parsed.positionals[0];
|
|
337
|
+
if (!isSecretFormat(format))
|
|
338
|
+
throw new CliError('cli_flag_invalid_value');
|
|
339
|
+
const project = requireProject(parsed.flags.project, defaultProject);
|
|
340
|
+
const name = parsed.flags.name; // guaranteed present by spec.requiredFlags
|
|
341
|
+
const fieldValues = {};
|
|
342
|
+
for (const kv of parsed.repeated.field ?? []) {
|
|
343
|
+
const eq = kv.indexOf('=');
|
|
344
|
+
fieldValues[kv.slice(0, eq)] = kv.slice(eq + 1);
|
|
345
|
+
}
|
|
346
|
+
const vaultPassword = await (deps.resolveVaultPasswordFn ?? realResolveVaultPassword)();
|
|
347
|
+
const params = {
|
|
348
|
+
projectId: project,
|
|
349
|
+
name,
|
|
350
|
+
secretFormat: format,
|
|
351
|
+
fieldValues,
|
|
352
|
+
...writeMetadata(parsed.flags),
|
|
353
|
+
vaultPassword,
|
|
354
|
+
};
|
|
355
|
+
const out = deps.stdout ?? ((s) => process.stdout.write(s));
|
|
356
|
+
if (upsert) {
|
|
357
|
+
const { recordId, updated } = await client.setSecret({ ...params, ...(environment ? { environment } : {}) });
|
|
358
|
+
out(`${recordId} (${updated ? 'updated' : 'created'})\n`);
|
|
359
|
+
return 0;
|
|
360
|
+
}
|
|
361
|
+
const { recordId } = await client.createSecret(environment
|
|
362
|
+
? { projectId: project, name, secretFormat: format, tags: params.tags, idempotencyKey: params.idempotencyKey,
|
|
363
|
+
accessScope: 'environment', environmentValues: [{ environment, fieldValues,
|
|
364
|
+
secretDueAt: params.secretDueAt, rotationIntervalDays: params.rotationIntervalDays }], vaultPassword }
|
|
365
|
+
: params);
|
|
366
|
+
out(`${recordId}\n`);
|
|
367
|
+
return 0;
|
|
368
|
+
}
|
|
369
|
+
async function cmdNew(argv, deps) {
|
|
370
|
+
const parsed = parseArgv(argv, SPECS.new);
|
|
371
|
+
const environment = recordEnvironmentFlag(parsed.flags.env);
|
|
372
|
+
const { client, defaultProject } = resolveHumanClient(resolveClientDeps(deps, parsed.flags.profile)); // VETO first
|
|
373
|
+
const format = parsed.positionals[0];
|
|
374
|
+
if (!isSecretFormat(format) || !canGenerate(format))
|
|
375
|
+
throw new CliError('cli_flag_invalid_value');
|
|
376
|
+
const project = requireProject(parsed.flags.project, defaultProject);
|
|
377
|
+
const name = parsed.flags.name; // guaranteed present by spec.requiredFlags
|
|
378
|
+
const vaultPassword = await (deps.resolveVaultPasswordFn ?? realResolveVaultPassword)();
|
|
379
|
+
const metadata = writeMetadata(parsed.flags);
|
|
380
|
+
const common = { projectId: project, name, secretFormat: format,
|
|
381
|
+
tags: metadata.tags, idempotencyKey: metadata.idempotencyKey, vaultPassword };
|
|
382
|
+
const { recordId } = await client.createGeneratedRecord(environment
|
|
383
|
+
? { ...common, accessScope: 'environment', environmentValues: [{ environment, options: parsed.options,
|
|
384
|
+
secretDueAt: metadata.secretDueAt, rotationIntervalDays: metadata.rotationIntervalDays }] }
|
|
385
|
+
: { ...common, options: parsed.options, ...metadata });
|
|
386
|
+
(deps.stdout ?? ((s) => process.stdout.write(s)))(`${recordId}\n`);
|
|
387
|
+
return 0;
|
|
388
|
+
}
|
|
389
|
+
async function cmdImport(argv, deps) {
|
|
390
|
+
const parsed = parseArgv(argv, SPECS.import);
|
|
391
|
+
const environment = recordEnvironmentFlag(parsed.flags.env);
|
|
392
|
+
const { client, defaultProject } = resolveHumanClient(resolveClientDeps(deps, parsed.flags.profile)); // VETO first — BEFORE file read
|
|
393
|
+
if (parsed.positionals[0] !== 'env')
|
|
394
|
+
throw new CliError('cli_flag_invalid_value');
|
|
395
|
+
const project = requireProject(parsed.flags.project, defaultProject);
|
|
396
|
+
const name = parsed.flags.name; // guaranteed present by spec.requiredFlags
|
|
397
|
+
const targetEnv = parsed.flags['target-env'] ?? 'production';
|
|
398
|
+
// A bad path throws a raw fs error → the boundary maps it to `cli_internal_error` and NEVER prints the path.
|
|
399
|
+
const body = readFileSync(parsed.positionals[1], 'utf8');
|
|
400
|
+
const vaultPassword = await (deps.resolveVaultPasswordFn ?? realResolveVaultPassword)();
|
|
401
|
+
const { recordId, updated } = await client.setSecret({
|
|
402
|
+
projectId: project,
|
|
403
|
+
name,
|
|
404
|
+
secretFormat: 'env',
|
|
405
|
+
fieldValues: { target_env: targetEnv, body, notes: '' },
|
|
406
|
+
...(environment ? { environment } : {}),
|
|
407
|
+
...writeMetadata(parsed.flags),
|
|
408
|
+
vaultPassword,
|
|
409
|
+
});
|
|
410
|
+
(deps.stdout ?? ((s) => process.stdout.write(s)))(`${recordId} (${updated ? 'updated' : 'created'})\n`);
|
|
411
|
+
return 0;
|
|
412
|
+
}
|
|
413
|
+
/**
|
|
414
|
+
* Internal dispatcher retained for lifecycle regression coverage. The published binary calls
|
|
415
|
+
* `runPublicCli`, which does not expose the Web-only Service Account credential lifecycle.
|
|
416
|
+
*/
|
|
417
|
+
export async function runCli(argv, deps = {}) {
|
|
418
|
+
const [cmd, ...rest] = argv;
|
|
419
|
+
if (cmd === undefined || cmd === 'help' || cmd === '--help') {
|
|
420
|
+
;
|
|
421
|
+
(deps.stdout ?? ((s) => process.stdout.write(s)))(USAGE);
|
|
422
|
+
return 0;
|
|
423
|
+
}
|
|
424
|
+
switch (cmd) {
|
|
425
|
+
case 'login':
|
|
426
|
+
return cmdLogin(rest, deps);
|
|
427
|
+
case 'get':
|
|
428
|
+
return cmdGet(rest, deps);
|
|
429
|
+
case 'read':
|
|
430
|
+
return cmdRead(rest, deps);
|
|
431
|
+
case 'run':
|
|
432
|
+
return cmdRun(rest, deps);
|
|
433
|
+
case 'generate':
|
|
434
|
+
return cmdGenerate(rest, deps);
|
|
435
|
+
case 'create':
|
|
436
|
+
return cmdCreateOrSet(rest, deps, false);
|
|
437
|
+
case 'set':
|
|
438
|
+
return cmdCreateOrSet(rest, deps, true);
|
|
439
|
+
case 'new':
|
|
440
|
+
return cmdNew(rest, deps);
|
|
441
|
+
case 'import':
|
|
442
|
+
return cmdImport(rest, deps);
|
|
443
|
+
case 'gateway':
|
|
444
|
+
return runGatewayCommand(rest, {
|
|
445
|
+
resolve: resolveClientDeps(deps),
|
|
446
|
+
env: deps.env,
|
|
447
|
+
stdout: deps.stdout,
|
|
448
|
+
});
|
|
449
|
+
case 'record':
|
|
450
|
+
return runRecordCommand(rest, {
|
|
451
|
+
resolve: resolveClientDeps(deps),
|
|
452
|
+
resolveVaultPassword: deps.resolveVaultPasswordFn ?? realResolveVaultPassword,
|
|
453
|
+
stdout: deps.stdout,
|
|
454
|
+
});
|
|
455
|
+
case 'group':
|
|
456
|
+
return runGroupCommand(rest, {
|
|
457
|
+
resolve: resolveClientDeps(deps),
|
|
458
|
+
resolveVaultPassword: deps.resolveVaultPasswordFn ?? realResolveVaultPassword,
|
|
459
|
+
stdout: deps.stdout,
|
|
460
|
+
});
|
|
461
|
+
case 'project':
|
|
462
|
+
return runProjectCommand(rest, {
|
|
463
|
+
resolve: resolveClientDeps(deps),
|
|
464
|
+
stdout: deps.stdout,
|
|
465
|
+
});
|
|
466
|
+
case 'sa':
|
|
467
|
+
// `sa *`: ADMIN authorize/cancel/tokens/revoke-token (U9b-3c, human-only, veto SA) + MACHINE `bootstrap`
|
|
468
|
+
// (U9b-3d, §10.c#17, isolated: no config/PAT, authority from the finalized handoff). Dispatch inside runSaCommand.
|
|
469
|
+
return runSaCommand(rest, buildSaDeps({
|
|
470
|
+
resolve: resolveClientDeps(deps),
|
|
471
|
+
stdout: deps.stdout,
|
|
472
|
+
profileRoot: deps.profileRoot,
|
|
473
|
+
fsOps: deps.fsOps,
|
|
474
|
+
now: deps.now,
|
|
475
|
+
newOperationId: deps.newOperationId,
|
|
476
|
+
newIdempotencyKey: deps.newIdempotencyKey,
|
|
477
|
+
newReceiptId: deps.newReceiptId,
|
|
478
|
+
newClaimTicket: deps.newClaimTicket,
|
|
479
|
+
newBootstrap: deps.newBootstrap,
|
|
480
|
+
makeBootstrapClaimClient: deps.makeBootstrapClaimClient,
|
|
481
|
+
makeClient: deps.makeClient,
|
|
482
|
+
newCapability: deps.newCapability,
|
|
483
|
+
}));
|
|
484
|
+
default:
|
|
485
|
+
throw new ParseError('cli_unknown_command');
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
/** Public CLI dispatcher. Service Account credential lifecycle is intentionally Web-only. */
|
|
489
|
+
export async function runPublicCli(argv, deps = {}) {
|
|
490
|
+
if (argv[0] === 'sa') {
|
|
491
|
+
const subcommand = argv[1];
|
|
492
|
+
const isReadCommand = subcommand === undefined || subcommand === 'help' || subcommand === '--help' ||
|
|
493
|
+
Object.hasOwn(SERVICE_ACCOUNT_READ_SPECS, subcommand);
|
|
494
|
+
if (!isReadCommand)
|
|
495
|
+
throw new CliError('sa_lifecycle_web_only');
|
|
496
|
+
return runServiceAccountReadCommand(argv.slice(1), {
|
|
497
|
+
resolve: resolveClientDeps(deps),
|
|
498
|
+
stdout: deps.stdout,
|
|
499
|
+
});
|
|
500
|
+
}
|
|
501
|
+
return runCli(argv, deps);
|
|
502
|
+
}
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { chmodSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { StoreError } from './store/errors.js';
|
|
5
|
+
import { assertConfigChain, ensureConfigDir, assertNotSymlink, assertRegularFile } from './store/paths.js';
|
|
6
|
+
import { REAL_FS } from './store/fsops.js';
|
|
7
|
+
/** Default API endpoint used when neither env nor config specifies one (human path). */
|
|
8
|
+
export const DEFAULT_BASE_URL = 'https://api.airctrl.dev';
|
|
9
|
+
/**
|
|
10
|
+
* Resolve the config path. `root` (HOME-equivalent base) is injectable so tests never touch
|
|
11
|
+
* the real HOME; production omits it and uses `os.homedir()` (U9b-2 §10.b #9/#10).
|
|
12
|
+
*/
|
|
13
|
+
export function resolveConfigPath(root = homedir()) {
|
|
14
|
+
return join(root, '.airctrl', 'config.json');
|
|
15
|
+
}
|
|
16
|
+
export function configPath(root) {
|
|
17
|
+
return resolveConfigPath(root);
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Load the human config with the ratified fail-closed semantics (§10.b #9): missing → `null`;
|
|
21
|
+
* present-but-corrupt / invalid shape / SA fields / unreadable → `cli_config_corrupt`. Delegates to
|
|
22
|
+
* {@link loadConfigStrict} so there are NOT two loaders with contradictory security semantics.
|
|
23
|
+
*/
|
|
24
|
+
export function loadConfig(root, fs = REAL_FS) {
|
|
25
|
+
return loadConfigStrict(root, fs);
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Human/admin config is EXCLUSIVELY `{ baseUrl, token, defaultProject? }`. Reject extra keys,
|
|
29
|
+
* wrong types, and any SA material — `config.json` must never complete an SA bundle (D2/§10.b #9).
|
|
30
|
+
*/
|
|
31
|
+
export function validateHumanConfig(raw) {
|
|
32
|
+
if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {
|
|
33
|
+
throw new StoreError('cli_config_corrupt');
|
|
34
|
+
}
|
|
35
|
+
const obj = raw;
|
|
36
|
+
const allowed = new Set(['baseUrl', 'token', 'defaultProject']);
|
|
37
|
+
for (const key of Object.keys(obj)) {
|
|
38
|
+
if (!allowed.has(key))
|
|
39
|
+
throw new StoreError('cli_config_corrupt');
|
|
40
|
+
}
|
|
41
|
+
if (typeof obj.baseUrl !== 'string' || obj.baseUrl.length === 0)
|
|
42
|
+
throw new StoreError('cli_config_corrupt');
|
|
43
|
+
if (typeof obj.token !== 'string' || obj.token.length === 0)
|
|
44
|
+
throw new StoreError('cli_config_corrupt');
|
|
45
|
+
if (obj.defaultProject !== undefined && typeof obj.defaultProject !== 'string') {
|
|
46
|
+
throw new StoreError('cli_config_corrupt');
|
|
47
|
+
}
|
|
48
|
+
const cfg = { baseUrl: obj.baseUrl, token: obj.token };
|
|
49
|
+
if (obj.defaultProject !== undefined)
|
|
50
|
+
cfg.defaultProject = obj.defaultProject;
|
|
51
|
+
return cfg;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Fail-closed loader for the human config. Missing → `null`. Present but corrupt / invalid shape /
|
|
55
|
+
* SA fields / unreadable → throws `cli_config_corrupt` (NEVER a silent null→prod fallback). U9b-3
|
|
56
|
+
* will switch the CLI commands over to this; U9b-2 delivers the capability + tests only.
|
|
57
|
+
*/
|
|
58
|
+
export function loadConfigStrict(root, fs = REAL_FS) {
|
|
59
|
+
const path = resolveConfigPath(root);
|
|
60
|
+
assertConfigChain(root ?? homedir(), fs); // reject a symlinked `.airctrl` redirecting the read
|
|
61
|
+
// Regular-file gate on the sensitive config leaf (U9b-3a-bis §10.c#16, F2): absent → null; symlink →
|
|
62
|
+
// sa_store_symlink_rejected; special/directory → cli_config_corrupt; lstat-fail → sa_store_lstat_failed.
|
|
63
|
+
// NEVER readFileSync a non-regular inode; no `existsSync`/direct `node:fs` — the injected `fs` is used end-to-end.
|
|
64
|
+
if (assertRegularFile(path, { notRegular: 'cli_config_corrupt' }, fs) === 'absent')
|
|
65
|
+
return null;
|
|
66
|
+
let raw;
|
|
67
|
+
try {
|
|
68
|
+
raw = fs.readFileSync(path);
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
throw new StoreError('cli_config_corrupt');
|
|
72
|
+
}
|
|
73
|
+
let parsed;
|
|
74
|
+
try {
|
|
75
|
+
parsed = JSON.parse(raw);
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
throw new StoreError('cli_config_corrupt');
|
|
79
|
+
}
|
|
80
|
+
return validateHumanConfig(parsed);
|
|
81
|
+
}
|
|
82
|
+
export function saveConfig(config, root) {
|
|
83
|
+
const validated = validateHumanConfig(config); // never persist an invalid / SA-bearing object
|
|
84
|
+
ensureConfigDir(root ?? homedir()); // 0700 + reject a symlinked `.airctrl`
|
|
85
|
+
const path = resolveConfigPath(root);
|
|
86
|
+
assertNotSymlink(path);
|
|
87
|
+
writeFileSync(path, JSON.stringify(validated, null, 2), { encoding: 'utf8' });
|
|
88
|
+
try {
|
|
89
|
+
chmodSync(path, 0o600); // owner-only (best-effort; no-op on Windows)
|
|
90
|
+
}
|
|
91
|
+
catch {
|
|
92
|
+
/* windows / unsupported fs */
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
/** Resolve the bearer token: `AC_TOKEN` env wins (CI), else the stored config. */
|
|
96
|
+
export function resolveToken(config) {
|
|
97
|
+
return process.env.AC_TOKEN?.trim() || config?.token || null;
|
|
98
|
+
}
|
|
99
|
+
/** Resolve the API base URL: `AC_API_BASE_URL` env, else config, else prod. */
|
|
100
|
+
export function resolveBaseUrl(config) {
|
|
101
|
+
return process.env.AC_API_BASE_URL?.trim() || config?.baseUrl || DEFAULT_BASE_URL;
|
|
102
|
+
}
|
package/dist/deadline.js
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SSOT deadline boundary for SA credential lifecycle (U9b-4 · §10.c#20.I).
|
|
3
|
+
*
|
|
4
|
+
* The BACKEND is the authority: it rejects `expires_at <= Date.now()` as expired
|
|
5
|
+
* (apps/api/src/service-accounts/service-accounts.service.ts). The client boundary MUST match — a deadline reached
|
|
6
|
+
* EXACTLY is elapsed. An unparseable `expiresAt` is treated as expired (fail-closed), never as "no deadline".
|
|
7
|
+
*
|
|
8
|
+
* Pure predicate (no throw, no clock): callers pass `nowMs` and throw their own stable code.
|
|
9
|
+
*/
|
|
10
|
+
export function saDeadlineExpired(expiresAt, nowMs) {
|
|
11
|
+
const t = new Date(expiresAt).getTime();
|
|
12
|
+
return Number.isNaN(t) || nowMs >= t;
|
|
13
|
+
}
|