@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
package/dist/migrate.js
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* U9b-4-P0 · `sa migrate` scaffolding (§10.c#20 · A/B/C/E/K + post-gate F1–F3 · final). Holds the PURE, side-effect-free
|
|
3
|
+
* pieces the future driver (U9b-4-1) composes. NEITHER the `sa migrate` command NOR the fresh/resume state machine
|
|
4
|
+
* live here.
|
|
5
|
+
*
|
|
6
|
+
* TOCTOU-SAFE + BOUND + COMPOSED RESOLUTION (§10.c#20.A). Resolution, callback, and release are ONE operation over a
|
|
7
|
+
* SINGLE bound context, so there is no time-of-check/time-of-use window, no way to point the lease at a different
|
|
8
|
+
* target, and — critically — no way to resolve one context while releasing another:
|
|
9
|
+
*
|
|
10
|
+
* 1. {@link preflightMigratePrincipal} — PURE authority classification. It takes NO `root`/`fs`/lock, performs no
|
|
11
|
+
* I/O, and CAPTURES an IMMUTABLE env snapshot (the legacy bearer+baseUrl, or the `AC_API_BASE_URL` override) so
|
|
12
|
+
* phase 2 never re-reads `process.env`. It delegates bundle validation to the pure `resolvePrincipal`.
|
|
13
|
+
* 2. {@link acquireMigrationLeaseContext} — acquires the O_EXCL lease for `<root>/<profileName>.migration.lease`
|
|
14
|
+
* and RETURNS A BOUND CONTEXT (opaque, frozen) that captures `root`/`profileName`/`fs`/`handle` in a private WeakMap.
|
|
15
|
+
* 3. {@link withMigrationLease} — the ONLY way to obtain a {@link MigrateResolved}: over ONE context it verifies
|
|
16
|
+
* binding/ownership via the PRIVATE handle, loads+classifies ONCE, runs the driver callback with the computed
|
|
17
|
+
* result, and releases THAT SAME handle. The classifier is private; there is no exported `resolveMigrateUnderLease`
|
|
18
|
+
* that could be paired with a different context's release.
|
|
19
|
+
*
|
|
20
|
+
* Driver ordering: parse → {@link preflightMigratePrincipal} → {@link acquireMigrationLeaseContext}(root, profileName,
|
|
21
|
+
* fs) → `await`{@link withMigrationLease}(preflight, ctx, run). Ownership and release resolve EXCLUSIVELY from the
|
|
22
|
+
* private captured handle (never a substitutable public method); {@link releaseMigrationLease} exists ONLY for explicit
|
|
23
|
+
* cleanup of a context that is NOT taken into the combinator.
|
|
24
|
+
*/
|
|
25
|
+
import { resolvePrincipal, loadProfile, assertProfileName, resolveEffectiveBaseUrl, acquireMigrationLease, StoreError, REAL_FS, } from './store/index.js';
|
|
26
|
+
import { CliError } from './cli-error.js';
|
|
27
|
+
/** Canonical lowercase UUID v-agnostic (same shape the store/backend accept). */
|
|
28
|
+
const CANONICAL_UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
29
|
+
/**
|
|
30
|
+
* Validate the `sa migrate <serviceAccountId>` positional — the ONLY source of the SA id (§10.c#20.A: neither
|
|
31
|
+
* `sa_env_legacy` nor `/me` legacy carry it). A non-string / non-canonical-UUID → `sa_migration_service_account_id_invalid`
|
|
32
|
+
* WITHOUT echoing the value. Runs BEFORE any lease/filesystem work.
|
|
33
|
+
*/
|
|
34
|
+
export function assertMigrateServiceAccountId(id) {
|
|
35
|
+
if (typeof id !== 'string' || !CANONICAL_UUID.test(id)) {
|
|
36
|
+
throw new CliError('sa_migration_service_account_id_invalid');
|
|
37
|
+
}
|
|
38
|
+
return id;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* THE OFFICIAL `sa migrate` COMBINATOR (§10.c#20.A/B · corrección de composición final). Binds RESOLUTION + the
|
|
42
|
+
* driver callback + RELEASE into ONE operation over a SINGLE {@link MigrationLeaseContext} — so it is impossible to
|
|
43
|
+
* resolve with one context and release another (the old exported `resolveMigrateUnderLease` + `withMigrationLease`
|
|
44
|
+
* pair allowed `withMigrationLease(ctxB, () => resolveMigrateUnderLease(preA, ctxA))`, which resolved A but released
|
|
45
|
+
* B, leaving A's lease live). The resolver is now PRIVATE; the ONLY way to obtain a {@link MigrateResolved} is here.
|
|
46
|
+
*
|
|
47
|
+
* Sequence, all against the ONE captured handle: (1) `sa_migration_lease_unbound` if the context is fabricated/foreign
|
|
48
|
+
* (no handle → nothing to release); (2) `sa_migration_lease_profile_mismatch` if the context's `profileName` ≠ the
|
|
49
|
+
* preflight's; (3) `assertOwned` via the PRIVATE handle (`sa_migration_lease_owner_mismatch`); (4) load ONCE + classify
|
|
50
|
+
* with the same bound context; (5) run `run(resolved)` with the ALREADY-computed classification — the callback cannot
|
|
51
|
+
* choose another context; (6) release THAT SAME handle. Ratified precedence (F3, falsy-safe via explicit flags): a
|
|
52
|
+
* functional PRIMARY error from steps 2–5 wins by identity and swallows a release failure; a SUCCESS whose release
|
|
53
|
+
* throws (even a falsy throw) collapses to `sa_migration_lease_release_failed`. Steps 2–5 run INSIDE the try, so a
|
|
54
|
+
* binding/ownership/classify/callback error still releases the bound handle (the ratified cleanup). `unbound` is the
|
|
55
|
+
* sole pre-try throw (there is no handle to release).
|
|
56
|
+
*/
|
|
57
|
+
export async function withMigrationLease(pre, lease, run) {
|
|
58
|
+
const bound = boundOrThrow(lease); // fabricated/foreign context → sa_migration_lease_unbound (no handle to release)
|
|
59
|
+
let result;
|
|
60
|
+
let primary;
|
|
61
|
+
let hasPrimary = false;
|
|
62
|
+
try {
|
|
63
|
+
if (bound.profileName !== pre.profileName)
|
|
64
|
+
throw new CliError('sa_migration_lease_profile_mismatch'); // lease≠target
|
|
65
|
+
bound.handle.assertOwned(); // ownership via the PRIVATE handle (may throw sa_migration_lease_owner_mismatch)
|
|
66
|
+
const resolved = classifyMigrateUnderBound(pre, bound); // load ONCE + classify with THIS bound context
|
|
67
|
+
result = await run(resolved); // the driver callback receives the already-computed classification
|
|
68
|
+
}
|
|
69
|
+
catch (e) {
|
|
70
|
+
primary = e;
|
|
71
|
+
hasPrimary = true;
|
|
72
|
+
}
|
|
73
|
+
let hasReleaseError = false;
|
|
74
|
+
try {
|
|
75
|
+
bound.handle.release(); // release THAT SAME captured handle (idempotent → once)
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
hasReleaseError = true;
|
|
79
|
+
}
|
|
80
|
+
if (hasPrimary)
|
|
81
|
+
throw primary; // functional primary wins by identity (even a falsy throw)
|
|
82
|
+
if (hasReleaseError)
|
|
83
|
+
throw new CliError('sa_migration_lease_release_failed'); // success + any release throw (even falsy)
|
|
84
|
+
return result;
|
|
85
|
+
}
|
|
86
|
+
// Authority env vars that must NOT compete with the `profile-only` authority (own-presence only; value never read).
|
|
87
|
+
// `AC_API_BASE_URL` is config (snapshotted + compared under the lease, never forbidden). On the `legacy-env` path
|
|
88
|
+
// AC_TOKEN and the `service_account_legacy` marker are REQUIRED, so the ONLY explicit rejects there are the two vars
|
|
89
|
+
// `resolvePrincipal` would silently IGNORE (`AC_SA_PROFILE`, `AC_VAULT_PASSWORD`); the active-bundle fields collide
|
|
90
|
+
// via D12.
|
|
91
|
+
const PROFILE_ONLY_FORBIDDEN_ENV = [
|
|
92
|
+
'AC_TOKEN',
|
|
93
|
+
'AC_SA_SERVICE_ACCOUNT_ID',
|
|
94
|
+
'AC_SA_CREDENTIAL_ID',
|
|
95
|
+
'AC_SA_CAP_PRIVATE_KEY_B64',
|
|
96
|
+
'AC_SA_PROFILE',
|
|
97
|
+
'AC_VAULT_PASSWORD',
|
|
98
|
+
];
|
|
99
|
+
const LEGACY_ENV_EXPLICIT_FORBIDDEN = ['AC_SA_PROFILE', 'AC_VAULT_PASSWORD'];
|
|
100
|
+
/** Reject own-presence (never reads the value) of any listed authority var → `sa_migration_profile_conflict`. */
|
|
101
|
+
function assertNoAuthorityEnv(env, keys) {
|
|
102
|
+
for (const k of keys) {
|
|
103
|
+
if (Object.hasOwn(env, k))
|
|
104
|
+
throw new CliError('sa_migration_profile_conflict');
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* PHASE 1 (§10.c#20.A · F1/F2) — PURE authority preflight. The PRODUCTION function takes no `root`/`fs`/lock and does
|
|
109
|
+
* no I/O; it validates the positional UUID + `--profile`, classifies env authority, and CAPTURES the env snapshot phase
|
|
110
|
+
* 2 needs. (It delegates bundle validation to the pure `resolvePrincipal`, guarded so no profile is read.) The legacy
|
|
111
|
+
* marker `AC_SA_PRINCIPAL` selects the intent:
|
|
112
|
+
*
|
|
113
|
+
* - MARKER PRESENT (own-property, value-agnostic) ⇒ LEGACY-ENV intent. `AC_SA_PROFILE`/`AC_VAULT_PASSWORD` present →
|
|
114
|
+
* `sa_migration_profile_conflict`. Then `resolvePrincipal` validates the bundle (unknown marker →
|
|
115
|
+
* `sa_principal_unknown`; an active companion / `AC_SA_SERVICE_ACCOUNT_ID` present-even-empty + the marker → the
|
|
116
|
+
* ratified D12 `sa_principal_bundle_conflict`; a missing token/baseUrl → `sa_env_bundle_incomplete` /
|
|
117
|
+
* `sa_env_baseurl_missing`) — propagated by identity — and returns `sa_env_legacy` WITHOUT reading a profile (a
|
|
118
|
+
* throwing `loadProfileByName` guard proves it). The bearer + normalized baseUrl are captured.
|
|
119
|
+
* - MARKER ABSENT ⇒ PROFILE-ONLY intent. ANY competing authority var present → `sa_migration_profile_conflict`. The
|
|
120
|
+
* raw `AC_API_BASE_URL` (own-present → its value, else `undefined`) is captured immutably for the lease-time compare.
|
|
121
|
+
*/
|
|
122
|
+
export function preflightMigratePrincipal(input) {
|
|
123
|
+
const env = input.env ?? process.env;
|
|
124
|
+
const serviceAccountId = assertMigrateServiceAccountId(input.serviceAccountId);
|
|
125
|
+
const profileName = input.profileName;
|
|
126
|
+
assertProfileName(profileName);
|
|
127
|
+
if (Object.hasOwn(env, 'AC_SA_PRINCIPAL')) {
|
|
128
|
+
// LEGACY-ENV intent.
|
|
129
|
+
assertNoAuthorityEnv(env, LEGACY_ENV_EXPLICIT_FORBIDDEN);
|
|
130
|
+
const p = resolvePrincipal({
|
|
131
|
+
env,
|
|
132
|
+
loadHumanConfig: () => null, // machine-only: the human config never completes an SA bundle
|
|
133
|
+
loadProfileByName: () => {
|
|
134
|
+
throw new Error('preflightMigratePrincipal must not read a profile');
|
|
135
|
+
},
|
|
136
|
+
});
|
|
137
|
+
if (p.kind !== 'sa_env_legacy')
|
|
138
|
+
throw new CliError('sa_migration_profile_conflict');
|
|
139
|
+
return { authority: 'legacy-env', serviceAccountId, profileName, bearer: p.bearer, baseUrl: p.baseUrl };
|
|
140
|
+
}
|
|
141
|
+
// PROFILE-ONLY intent — no legacy marker; nothing may compete with the profile's authority.
|
|
142
|
+
assertNoAuthorityEnv(env, PROFILE_ONLY_FORBIDDEN_ENV);
|
|
143
|
+
// Immutable snapshot: a string is captured by value, so a later mutation of the caller's env object cannot change it.
|
|
144
|
+
const apiBaseOverride = Object.hasOwn(env, 'AC_API_BASE_URL') ? env['AC_API_BASE_URL'] : undefined;
|
|
145
|
+
return { authority: 'profile-only', serviceAccountId, profileName, apiBaseOverride };
|
|
146
|
+
}
|
|
147
|
+
const LEASE_INTERNALS = new WeakMap();
|
|
148
|
+
/** Resolve the captured internals or fail closed — a fabricated/foreign context → `sa_migration_lease_unbound`. */
|
|
149
|
+
function boundOrThrow(lease) {
|
|
150
|
+
const bound = LEASE_INTERNALS.get(lease);
|
|
151
|
+
if (!bound)
|
|
152
|
+
throw new CliError('sa_migration_lease_unbound');
|
|
153
|
+
return bound;
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Acquire the O_EXCL migration lease for `<root>/<profileName>.migration.lease` with `fs` and RETURN a bound context
|
|
157
|
+
* that captures `root`/`profileName`/`fs`/`handle`. All lock codes of the underlying primitive apply (`sa_migration_busy`,
|
|
158
|
+
* `sa_migration_lease_stale`, `sa_migration_lease_corrupt`, `sa_migration_lease_owner_mismatch`). The captured `fs`
|
|
159
|
+
* is the SAME instance phase 2 must (and does) use — there is no way to substitute it later.
|
|
160
|
+
*/
|
|
161
|
+
export function acquireMigrationLeaseContext(root, profileName, fs = REAL_FS) {
|
|
162
|
+
assertProfileName(profileName);
|
|
163
|
+
const handle = acquireMigrationLease(root, profileName, fs);
|
|
164
|
+
const ctx = Object.freeze({ profileName });
|
|
165
|
+
LEASE_INTERNALS.set(ctx, { root, profileName, fs, handle });
|
|
166
|
+
return ctx;
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* Release a bound migration-lease context (for cleanup paths that do not wrap work in {@link withMigrationLease}).
|
|
170
|
+
* Releases the PRIVATE captured handle (idempotent); a fabricated/foreign context → `sa_migration_lease_unbound`.
|
|
171
|
+
*/
|
|
172
|
+
export function releaseMigrationLease(lease) {
|
|
173
|
+
boundOrThrow(lease).handle.release();
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* Load the destination profile EXACTLY ONCE under the lease (§10.c#20.A · F2/F3), through the CAPTURED `fs`. A
|
|
177
|
+
* genuinely ABSENT profile → `null` — absence is NOT an error preserved by identity; it DRIVES the fresh/resume
|
|
178
|
+
* decision. `sa_profile_corrupt` / symlink / lstat failures ARE preserved by identity (never read the target, never
|
|
179
|
+
* degrade to fresh).
|
|
180
|
+
*/
|
|
181
|
+
function loadProfileOnceUnderLease(name, root, fs) {
|
|
182
|
+
try {
|
|
183
|
+
return loadProfile(root, name, fs); // real loader validates + threads the captured `fs` end-to-end
|
|
184
|
+
}
|
|
185
|
+
catch (e) {
|
|
186
|
+
if (e instanceof StoreError && e.code === 'sa_profile_not_found')
|
|
187
|
+
return null; // absence → fresh/resume decision
|
|
188
|
+
throw e; // sa_profile_corrupt / symlink / lstat preserved by identity
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* PRIVATE classifier (§10.c#20.A/C · F1/F2 + corrección de composición). Loads the profile ONCE via the CAPTURED
|
|
193
|
+
* `fs`/`root` and classifies fresh/resume against the CURRENT on-disk state. NOT exported: the ONLY way to obtain a
|
|
194
|
+
* {@link MigrateResolved} is through {@link withMigrationLease}, which performs the `unbound`/`profile_mismatch`/
|
|
195
|
+
* ownership checks and releases the SAME handle — so a caller can never resolve one context and release another.
|
|
196
|
+
*
|
|
197
|
+
* - PROFILE ABSENT ⇒ FRESH: requires `legacy-env` authority (`sa_migration_profile_conflict` otherwise); returns the
|
|
198
|
+
* bundle bearer/baseUrl CAPTURED by preflight.
|
|
199
|
+
* - PROFILE PRESENT ⇒ RESUME: requires `profile-only` authority (`sa_migration_profile_conflict` otherwise). A
|
|
200
|
+
* non-`legacy_migration` flow / `terminal`/unexpected stage → `sa_migration_profile_conflict`;
|
|
201
|
+
* `positional !== profile.serviceAccountId` → `sa_migration_sa_mismatch`; the CAPTURED `AC_API_BASE_URL` snapshot is
|
|
202
|
+
* compared to `profile.baseUrl` (`resolveEffectiveBaseUrl`: absent → normalize profile; present → normalize-equal or
|
|
203
|
+
* `sa_baseurl_conflict`; empty → `sa_baseurl_invalid`); `active` → recovery, earlier → in-progress.
|
|
204
|
+
*/
|
|
205
|
+
function classifyMigrateUnderBound(pre, bound) {
|
|
206
|
+
const profile = loadProfileOnceUnderLease(bound.profileName, bound.root, bound.fs);
|
|
207
|
+
if (profile === null) {
|
|
208
|
+
// FRESH — a profile that does not exist demands the LEGACY env authority.
|
|
209
|
+
if (pre.authority !== 'legacy-env')
|
|
210
|
+
throw new CliError('sa_migration_profile_conflict');
|
|
211
|
+
return { mode: 'fresh', serviceAccountId: pre.serviceAccountId, profileName: pre.profileName, bearer: pre.bearer, baseUrl: pre.baseUrl };
|
|
212
|
+
}
|
|
213
|
+
// RESUME — a present profile is the sole authority; the legacy env bundle must NOT be present.
|
|
214
|
+
if (pre.authority !== 'profile-only')
|
|
215
|
+
throw new CliError('sa_migration_profile_conflict');
|
|
216
|
+
if (profile.flow !== 'legacy_migration')
|
|
217
|
+
throw new CliError('sa_migration_profile_conflict');
|
|
218
|
+
if (profile.serviceAccountId !== pre.serviceAccountId)
|
|
219
|
+
throw new CliError('sa_migration_sa_mismatch');
|
|
220
|
+
const baseUrl = resolveEffectiveBaseUrl(profile.baseUrl, pre.apiBaseOverride); // captured snapshot only
|
|
221
|
+
switch (profile.stage) {
|
|
222
|
+
case 'legacy_source':
|
|
223
|
+
case 'capability_prepared':
|
|
224
|
+
case 'migration_prepared':
|
|
225
|
+
case 'activation_prepared':
|
|
226
|
+
return { mode: 'resume', serviceAccountId: pre.serviceAccountId, profileName: pre.profileName, profile, baseUrl, recovery: 'in_progress' };
|
|
227
|
+
case 'active':
|
|
228
|
+
return { mode: 'resume', serviceAccountId: pre.serviceAccountId, profileName: pre.profileName, profile, baseUrl, recovery: 'active' };
|
|
229
|
+
default: // terminal (or any unexpected stage) → not resumable as a live migration
|
|
230
|
+
throw new CliError('sa_migration_profile_conflict');
|
|
231
|
+
}
|
|
232
|
+
}
|
package/dist/parser.js
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* U9b-3b · Strict, spec-driven, side-effect-free argv parser (§10.c#15.A). No new dependency.
|
|
3
|
+
*
|
|
4
|
+
* Separates command · positionals · value-flags · repeatable-flags · `--` passthrough (ONLY for `run`) and
|
|
5
|
+
* the dynamic per-format option-spec of `generate`/`new`. A value-flag consumes EXACTLY the next token and
|
|
6
|
+
* that token is NEVER re-classified as a positional (fixes `get --profile prod <id>`); another flag can never
|
|
7
|
+
* serve as a value. There are NO zero-arg boolean flags in this CLI, so tokenizing is unambiguous: every
|
|
8
|
+
* `--x` consumes one token. Every failure is a stable-coded {@link ParseError}; the parser never mutates,
|
|
9
|
+
* reads the filesystem, or prints.
|
|
10
|
+
*/
|
|
11
|
+
import { RECORD_ENVIRONMENTS } from '@airctrl/sdk';
|
|
12
|
+
export class ParseError extends Error {
|
|
13
|
+
code;
|
|
14
|
+
constructor(code, detail) {
|
|
15
|
+
super(detail ? `${code}: ${detail}` : code);
|
|
16
|
+
this.name = 'ParseError';
|
|
17
|
+
this.code = code;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
/** Validate a record-variant flag against the SDK's canonical catalog before any identity/IO. */
|
|
21
|
+
export function recordEnvironmentFlag(value) {
|
|
22
|
+
if (value === undefined)
|
|
23
|
+
return undefined;
|
|
24
|
+
if (!RECORD_ENVIRONMENTS.some((environment) => environment === value))
|
|
25
|
+
throw new ParseError('cli_flag_invalid_value');
|
|
26
|
+
return value;
|
|
27
|
+
}
|
|
28
|
+
const isFlag = (t) => t.startsWith('--');
|
|
29
|
+
// Strict decimal: optional sign, digits with an optional single fractional part, NO whitespace, NO hex/oct/
|
|
30
|
+
// bin/exponent-only/Infinity/NaN. `Number()` alone would accept `0x10`, ` 5 `, `Infinity`, etc.
|
|
31
|
+
const DECIMAL_RE = /^-?(?:\d+(?:\.\d+)?|\.\d+)$/;
|
|
32
|
+
/** Coerce a raw flag value to the declared option type; throw `cli_flag_invalid_value` on mismatch. */
|
|
33
|
+
function coerceOption(_name, raw, type) {
|
|
34
|
+
if (type === 'boolean') {
|
|
35
|
+
if (raw === 'true')
|
|
36
|
+
return true;
|
|
37
|
+
if (raw === 'false')
|
|
38
|
+
return false;
|
|
39
|
+
throw new ParseError('cli_flag_invalid_value');
|
|
40
|
+
}
|
|
41
|
+
if (type === 'number') {
|
|
42
|
+
if (!DECIMAL_RE.test(raw))
|
|
43
|
+
throw new ParseError('cli_flag_invalid_value'); // rejects 0x10, whitespace, Infinity, NaN
|
|
44
|
+
const n = Number(raw);
|
|
45
|
+
if (!Number.isFinite(n))
|
|
46
|
+
throw new ParseError('cli_flag_invalid_value');
|
|
47
|
+
return n;
|
|
48
|
+
}
|
|
49
|
+
return raw; // string
|
|
50
|
+
}
|
|
51
|
+
export function parseArgv(args, spec) {
|
|
52
|
+
const positionals = [];
|
|
53
|
+
const rawFlags = [];
|
|
54
|
+
let childArgv;
|
|
55
|
+
// ── Pass 1: tokenize. Every `--x` consumes the next token (no zero-arg booleans). ─────────────────────
|
|
56
|
+
for (let i = 0; i < args.length; i += 1) {
|
|
57
|
+
const tok = args[i];
|
|
58
|
+
if (tok === '--') {
|
|
59
|
+
if (!spec.passthrough)
|
|
60
|
+
throw new ParseError('cli_unexpected_double_dash');
|
|
61
|
+
childArgv = args.slice(i + 1);
|
|
62
|
+
break;
|
|
63
|
+
}
|
|
64
|
+
if (isFlag(tok)) {
|
|
65
|
+
const name = tok.slice(2);
|
|
66
|
+
const next = args[i + 1];
|
|
67
|
+
if (next === undefined || isFlag(next) || next === '--')
|
|
68
|
+
throw new ParseError('cli_flag_missing_value');
|
|
69
|
+
rawFlags.push({ name, value: next });
|
|
70
|
+
i += 1;
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
positionals.push(tok);
|
|
74
|
+
}
|
|
75
|
+
// ── Positionals arity. ────────────────────────────────────────────────────────────────────────────────
|
|
76
|
+
if (positionals.length < spec.positionals.length)
|
|
77
|
+
throw new ParseError('cli_missing_positional');
|
|
78
|
+
if (positionals.length > spec.positionals.length)
|
|
79
|
+
throw new ParseError('cli_extra_positional');
|
|
80
|
+
// ── Pass 2: classify each flag against the fixed set, the repeatable set, or the dynamic option-spec. ──
|
|
81
|
+
const dynSpec = spec.optionsFromPositional !== undefined && spec.optionSpec
|
|
82
|
+
? spec.optionSpec(positionals[spec.optionsFromPositional] ?? '')
|
|
83
|
+
: undefined;
|
|
84
|
+
const fixed = new Set(spec.flags);
|
|
85
|
+
const repeatableSet = new Set(spec.repeatable ?? []);
|
|
86
|
+
const keyValueSet = new Set(spec.keyValue ?? []);
|
|
87
|
+
const flags = {};
|
|
88
|
+
const repeated = {};
|
|
89
|
+
const options = {};
|
|
90
|
+
const KEY_VALUE_RE = /^[^=]+=.*/s; // non-empty key, an '=', any (possibly empty) value
|
|
91
|
+
for (const { name, value } of rawFlags) {
|
|
92
|
+
if (keyValueSet.has(name) && !KEY_VALUE_RE.test(value))
|
|
93
|
+
throw new ParseError('cli_flag_invalid_value');
|
|
94
|
+
if (repeatableSet.has(name)) {
|
|
95
|
+
;
|
|
96
|
+
(repeated[name] ??= []).push(value);
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
if (fixed.has(name)) {
|
|
100
|
+
if (Object.hasOwn(flags, name))
|
|
101
|
+
throw new ParseError('cli_duplicate_flag');
|
|
102
|
+
flags[name] = value;
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
// OWN-property only: `in` would match inherited members (`toString`/`constructor`/`__proto__`) and
|
|
106
|
+
// misclassify them as known options/duplicates instead of `cli_unknown_flag`.
|
|
107
|
+
if (dynSpec && Object.hasOwn(dynSpec, name)) {
|
|
108
|
+
if (Object.hasOwn(options, name))
|
|
109
|
+
throw new ParseError('cli_duplicate_flag');
|
|
110
|
+
options[name] = coerceOption(name, value, dynSpec[name]);
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
throw new ParseError('cli_unknown_flag');
|
|
114
|
+
}
|
|
115
|
+
for (const req of spec.requiredFlags ?? []) {
|
|
116
|
+
if (!Object.hasOwn(flags, req))
|
|
117
|
+
throw new ParseError('cli_flag_missing_value');
|
|
118
|
+
}
|
|
119
|
+
return { positionals, flags, repeated, options, childArgv };
|
|
120
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* U9b-3e-1 · Shared `pat_expired` SSOT (§10.c#18.8 F3). Extracted from `cli.ts` so BOTH the read commands
|
|
3
|
+
* (`get`/`read`/`run`) and `sa verify` map the EXACT remote `pat_expired` (401) to a reconciliation from a single
|
|
4
|
+
* predicate — no divergent copy, and no import cycle between `cli.ts` and `sa-commands.ts`.
|
|
5
|
+
*
|
|
6
|
+
* Rule: an SA principal + `AirctrlError` + `status===401` + (`message==='pat_expired'` OR `code==='pat_expired'`)
|
|
7
|
+
* → `ReconcileError('pat_expired')`. ANY other error is rethrown as the SAME object (identity preserved); the CLI
|
|
8
|
+
* boundary (`toStableError`) then publishes ONLY the stable `code`, never the `message`.
|
|
9
|
+
*/
|
|
10
|
+
import { AirctrlError } from '@airctrl/sdk';
|
|
11
|
+
import { ReconcileError } from './cli-error.js';
|
|
12
|
+
/**
|
|
13
|
+
* For an SA principal, map the EXACT remote `pat_expired` (401) to a reconciliation; everything else rethrows.
|
|
14
|
+
* The first argument is the MINIMAL structural surface the predicate reads (U9b-3e-2 §10.c#18.7(e)) — a full
|
|
15
|
+
* `ResolvedClient` (get/read/run/verify) and the status-only `StatusResolution` both satisfy it, without duplicating
|
|
16
|
+
* the predicate or fabricating a read/unlock client.
|
|
17
|
+
*/
|
|
18
|
+
export async function withPatExpired(principal, fn) {
|
|
19
|
+
try {
|
|
20
|
+
return await fn();
|
|
21
|
+
}
|
|
22
|
+
catch (e) {
|
|
23
|
+
if (principal.principalKind === 'sa' &&
|
|
24
|
+
e instanceof AirctrlError &&
|
|
25
|
+
e.status === 401 &&
|
|
26
|
+
(e.message === 'pat_expired' || e.code === 'pat_expired')) {
|
|
27
|
+
throw new ReconcileError('pat_expired');
|
|
28
|
+
}
|
|
29
|
+
throw e;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { parseArgv, ParseError } from './parser.js';
|
|
2
|
+
import { resolveHumanClient } from './resolve-client.js';
|
|
3
|
+
const profile = ['profile'];
|
|
4
|
+
const accountProfile = ['account', ...profile];
|
|
5
|
+
export const PROJECT_SPECS = {
|
|
6
|
+
accounts: { positionals: [], flags: profile },
|
|
7
|
+
list: {
|
|
8
|
+
positionals: [],
|
|
9
|
+
flags: ['account', 'include-archived', ...profile],
|
|
10
|
+
requiredFlags: ['account'],
|
|
11
|
+
},
|
|
12
|
+
get: {
|
|
13
|
+
positionals: ['projectId'],
|
|
14
|
+
flags: accountProfile,
|
|
15
|
+
requiredFlags: ['account'],
|
|
16
|
+
},
|
|
17
|
+
create: {
|
|
18
|
+
positionals: [],
|
|
19
|
+
flags: ['account', 'name', 'description', ...profile],
|
|
20
|
+
requiredFlags: ['account', 'name'],
|
|
21
|
+
},
|
|
22
|
+
update: {
|
|
23
|
+
positionals: ['projectId'],
|
|
24
|
+
flags: ['account', 'name', 'description', 'active', ...profile],
|
|
25
|
+
requiredFlags: ['account', 'name', 'description', 'active'],
|
|
26
|
+
},
|
|
27
|
+
archive: {
|
|
28
|
+
positionals: ['projectId'],
|
|
29
|
+
flags: accountProfile,
|
|
30
|
+
requiredFlags: ['account'],
|
|
31
|
+
},
|
|
32
|
+
restore: {
|
|
33
|
+
positionals: ['projectId'],
|
|
34
|
+
flags: accountProfile,
|
|
35
|
+
requiredFlags: ['account'],
|
|
36
|
+
},
|
|
37
|
+
};
|
|
38
|
+
export const PROJECT_USAGE = `airctrl project commands
|
|
39
|
+
|
|
40
|
+
accounts
|
|
41
|
+
list --account <id> [--include-archived true|false]
|
|
42
|
+
get <projectId> --account <id>
|
|
43
|
+
create --account <id> --name <name> [--description <text>]
|
|
44
|
+
update <projectId> --account <id> --name <name> --description <text|null> --active true|false
|
|
45
|
+
archive|restore <projectId> --account <id>
|
|
46
|
+
`;
|
|
47
|
+
function booleanFlag(value) {
|
|
48
|
+
if (value === 'true')
|
|
49
|
+
return true;
|
|
50
|
+
if (value === 'false')
|
|
51
|
+
return false;
|
|
52
|
+
throw new ParseError('cli_flag_invalid_value');
|
|
53
|
+
}
|
|
54
|
+
function nullable(value) {
|
|
55
|
+
return value === 'null' ? null : value;
|
|
56
|
+
}
|
|
57
|
+
function clientFor(parsed, deps) {
|
|
58
|
+
return resolveHumanClient({ ...deps.resolve, profileFlag: parsed.flags.profile }).client;
|
|
59
|
+
}
|
|
60
|
+
function writeResult(value, deps) {
|
|
61
|
+
const out = deps.stdout ?? ((text) => process.stdout.write(text));
|
|
62
|
+
out(`${JSON.stringify(value ?? { ok: true }, null, 2)}\n`);
|
|
63
|
+
}
|
|
64
|
+
export async function runProjectCommand(argv, deps) {
|
|
65
|
+
const [command, ...rest] = argv;
|
|
66
|
+
if (command === undefined || command === 'help' || command === '--help') {
|
|
67
|
+
;
|
|
68
|
+
(deps.stdout ?? ((text) => process.stdout.write(text)))(PROJECT_USAGE);
|
|
69
|
+
return 0;
|
|
70
|
+
}
|
|
71
|
+
if (!Object.hasOwn(PROJECT_SPECS, command))
|
|
72
|
+
throw new ParseError('cli_unknown_command');
|
|
73
|
+
const parsed = parseArgv(rest, PROJECT_SPECS[command]);
|
|
74
|
+
const client = clientFor(parsed, deps);
|
|
75
|
+
const accountId = parsed.flags.account;
|
|
76
|
+
const projectId = parsed.positionals[0];
|
|
77
|
+
let result;
|
|
78
|
+
switch (command) {
|
|
79
|
+
case 'accounts':
|
|
80
|
+
result = await client.listAccounts();
|
|
81
|
+
break;
|
|
82
|
+
case 'list':
|
|
83
|
+
result = await client.listProjects({
|
|
84
|
+
accountId,
|
|
85
|
+
includeArchived: booleanFlag(parsed.flags['include-archived'] ?? 'false'),
|
|
86
|
+
});
|
|
87
|
+
break;
|
|
88
|
+
case 'get':
|
|
89
|
+
result = await client.getProject(projectId, { accountId });
|
|
90
|
+
break;
|
|
91
|
+
case 'create':
|
|
92
|
+
result = await client.createProject({
|
|
93
|
+
accountId,
|
|
94
|
+
name: parsed.flags.name,
|
|
95
|
+
description: parsed.flags.description,
|
|
96
|
+
});
|
|
97
|
+
break;
|
|
98
|
+
case 'update': {
|
|
99
|
+
const input = {
|
|
100
|
+
name: parsed.flags.name,
|
|
101
|
+
description: nullable(parsed.flags.description),
|
|
102
|
+
isActive: booleanFlag(parsed.flags.active),
|
|
103
|
+
};
|
|
104
|
+
await client.updateProject(projectId, input, { accountId });
|
|
105
|
+
result = undefined;
|
|
106
|
+
break;
|
|
107
|
+
}
|
|
108
|
+
case 'archive':
|
|
109
|
+
await client.setProjectArchiveState(projectId, true, { accountId });
|
|
110
|
+
result = undefined;
|
|
111
|
+
break;
|
|
112
|
+
case 'restore':
|
|
113
|
+
await client.setProjectArchiveState(projectId, false, { accountId });
|
|
114
|
+
result = undefined;
|
|
115
|
+
break;
|
|
116
|
+
default:
|
|
117
|
+
throw new ParseError('cli_unknown_command');
|
|
118
|
+
}
|
|
119
|
+
writeResult(result, deps);
|
|
120
|
+
return 0;
|
|
121
|
+
}
|
package/dist/prompt.js
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { createInterface } from 'node:readline';
|
|
2
|
+
/** Visible line prompt. */
|
|
3
|
+
export function promptLine(question) {
|
|
4
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
5
|
+
return new Promise((resolve) => {
|
|
6
|
+
rl.question(question, (answer) => {
|
|
7
|
+
rl.close();
|
|
8
|
+
resolve(answer.trim());
|
|
9
|
+
});
|
|
10
|
+
});
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Hidden prompt (masks typed characters) for secrets like the vault password.
|
|
14
|
+
* Falls back to a plain prompt if stdin is not a TTY.
|
|
15
|
+
*/
|
|
16
|
+
export function promptHidden(question) {
|
|
17
|
+
const stdin = process.stdin;
|
|
18
|
+
if (!stdin.isTTY)
|
|
19
|
+
return promptLine(question);
|
|
20
|
+
return new Promise((resolve) => {
|
|
21
|
+
const rl = createInterface({ input: stdin, output: process.stdout });
|
|
22
|
+
// Mask output: swallow the echoed characters after the question is written.
|
|
23
|
+
const rlAny = rl;
|
|
24
|
+
let first = true;
|
|
25
|
+
rlAny._writeToOutput = (str) => {
|
|
26
|
+
if (first) {
|
|
27
|
+
process.stdout.write(str); // write the question once
|
|
28
|
+
first = false;
|
|
29
|
+
}
|
|
30
|
+
// else: masked — write nothing
|
|
31
|
+
};
|
|
32
|
+
rl.question(question, (answer) => {
|
|
33
|
+
rl.close();
|
|
34
|
+
process.stdout.write('\n');
|
|
35
|
+
resolve(answer.trim());
|
|
36
|
+
});
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
/** Vault password from `AC_VAULT_PASSWORD` env (non-interactive) or a hidden prompt. */
|
|
40
|
+
export function resolveVaultPassword() {
|
|
41
|
+
const fromEnv = process.env.AC_VAULT_PASSWORD;
|
|
42
|
+
if (fromEnv)
|
|
43
|
+
return Promise.resolve(fromEnv);
|
|
44
|
+
return promptHidden('Vault password: ');
|
|
45
|
+
}
|