@git.zone/cli 6.12.0 → 6.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,620 @@
1
+ import * as plugins from "../plugins.js";
2
+ import {
3
+ TestingCommandError,
4
+ TestingCommandRuntime,
5
+ } from "./classes.runtime.js";
6
+
7
+ export type TTestingArgv = Record<string, unknown> & {
8
+ _?: string[];
9
+ "--"?: string[];
10
+ };
11
+
12
+ export const testingCommands = [
13
+ ["whoami", "", "Show the current machine registration."],
14
+ [
15
+ "zone list",
16
+ "[--after <id>] [--limit <n>]",
17
+ "List permitted testing zones.",
18
+ ],
19
+ [
20
+ "grant request",
21
+ "--zone <id> --hostname <name> --idempotency-key <key>",
22
+ "Request approval for one exact hostname.",
23
+ ],
24
+ [
25
+ "grant list",
26
+ "[--state <state>] [--after <id>] [--limit <n>]",
27
+ "List machine grants.",
28
+ ],
29
+ ["grant status", "--grant <id>", "Read a grant and its cleanup state."],
30
+ [
31
+ "cert ensure",
32
+ "--grant <id> --idempotency-key <key> [--wait]",
33
+ "Ensure a usable certificate; print job metadata.",
34
+ ],
35
+ ["cert status", "--job <id> [--wait]", "Read or wait for a certificate job."],
36
+ [
37
+ "cert run",
38
+ "--grant <id> --idempotency-key <key> -- <program> <args...>",
39
+ "Obtain a certificate and run a child with temporary certificate files.",
40
+ ],
41
+ [
42
+ "dns list",
43
+ "--grant <id> [--after <id>] [--limit <n>]",
44
+ "List records owned by the grant.",
45
+ ],
46
+ [
47
+ "dns upsert",
48
+ "--grant <id> --record-key <key> --revision <n|new> --type <A|AAAA|CNAME> --value <value> --ttl <seconds> --idempotency-key <key> [--wait]",
49
+ "Create or update a record with a revision check.",
50
+ ],
51
+ [
52
+ "dns delete",
53
+ "--grant <id> --record-key <key> --revision <n> --idempotency-key <key> [--wait]",
54
+ "Delete an owned record with a revision check.",
55
+ ],
56
+ [
57
+ "dns status",
58
+ "--mutation <id> [--wait]",
59
+ "Read or wait for a DNS mutation.",
60
+ ],
61
+ [
62
+ "admin registration create",
63
+ "--name <name> --expires-at <UTC-date|epoch-ms> --idempotency-key <key> --secret-fd <fd>",
64
+ "Provision a machine; deliver its credential only to the preopened descriptor.",
65
+ ],
66
+ [
67
+ "admin registration list",
68
+ "[--state <active|revoked>] [--after <id>] [--limit <n>]",
69
+ "List machine registrations.",
70
+ ],
71
+ [
72
+ "admin registration rotate",
73
+ "--registration <id> --generation <n> --expires-at <UTC-date|epoch-ms> --secret-fd <fd>",
74
+ "Rotate a credential while preserving grants.",
75
+ ],
76
+ [
77
+ "admin registration revoke",
78
+ "--registration <id> --revision <n> --reason <text>",
79
+ "Revoke a machine registration.",
80
+ ],
81
+ [
82
+ "admin zone list",
83
+ "[--after <id>] [--limit <n>]",
84
+ "List testing-zone policies.",
85
+ ],
86
+ [
87
+ "admin zone put",
88
+ "--domain <id> --revision <n|new> --enabled <true|false> --record-types <A,AAAA,CNAME> --min-ttl <n> --max-ttl <n> --max-grants <n>",
89
+ "Create or update an explicit testing-zone policy.",
90
+ ],
91
+ [
92
+ "admin grant list",
93
+ "[--state <state>] [--after <id>] [--limit <n>]",
94
+ "List grants for operator review.",
95
+ ],
96
+ ["admin grant status", "--grant <id>", "Inspect a grant."],
97
+ [
98
+ "admin grant review",
99
+ "--grant <id> --revision <n> --action <approve|deny|reopen|revoke> --reason <text>",
100
+ "Review a grant with a revision check.",
101
+ ],
102
+ [
103
+ "admin recovery list",
104
+ "--kind <certificate|dns> [--state <state>] [--after <id>] [--limit <n>]",
105
+ "List retained recovery evidence.",
106
+ ],
107
+ [
108
+ "admin recovery status",
109
+ "--kind <certificate|dns> --operation <id>",
110
+ "Inspect a mutation, certificate job, or grant DNS cleanup.",
111
+ ],
112
+ [
113
+ "admin recovery action",
114
+ "--kind <certificate|dns> --operation <id> --revision <n> --action <recheck|retry-proven-unapplied|abandon> --reason <text> --idempotency-key <key>",
115
+ "Request a revision-checked recovery action.",
116
+ ],
117
+ ] as const;
118
+
119
+ const commonFlags = [
120
+ "help",
121
+ "h",
122
+ "json",
123
+ "plain",
124
+ "agent",
125
+ "quiet",
126
+ "interactive",
127
+ "check-updates",
128
+ "output",
129
+ "token-stdin",
130
+ "timeout-ms",
131
+ ];
132
+ const camel = (name: string) =>
133
+ name.replace(/-([a-z])/g, (_, letter: string) => letter.toUpperCase());
134
+
135
+ export class TestingInput {
136
+ public readonly command: string;
137
+ public readonly admin: boolean;
138
+ constructor(public readonly argv: TTestingArgv) {
139
+ this.command = (argv._ ?? []).slice(1).join(" ");
140
+ this.admin = this.command.startsWith("admin ");
141
+ const definition = testingCommands.find(
142
+ ([command]) => command === this.command,
143
+ );
144
+ if (!definition)
145
+ throw new TestingCommandError(
146
+ "invalid_input",
147
+ "Unknown testing command. Use gitzone testing --help.",
148
+ );
149
+ const commandFlags = [...definition[1].matchAll(/--([a-z][a-z-]*)/g)].map(
150
+ (match) => match[1],
151
+ );
152
+ const allowed = new Set([
153
+ "_",
154
+ "--",
155
+ ...[...commonFlags, ...commandFlags].flatMap((flag) => [
156
+ flag,
157
+ camel(flag),
158
+ ]),
159
+ ]);
160
+ if (Object.keys(argv).some((key) => !allowed.has(key))) {
161
+ throw new TestingCommandError(
162
+ "invalid_input",
163
+ "Unsupported testing option. Credentials must come from the environment or secret stdin.",
164
+ );
165
+ }
166
+ if (argv["--"] !== undefined && this.command !== "cert run") {
167
+ throw new TestingCommandError(
168
+ "invalid_input",
169
+ "Child arguments are supported only by cert run.",
170
+ );
171
+ }
172
+ for (const name of ["wait", "token-stdin"]) {
173
+ if (argv[name] !== undefined && typeof argv[name] !== "boolean") {
174
+ throw new TestingCommandError(
175
+ "invalid_input",
176
+ "Testing boolean options do not accept values.",
177
+ );
178
+ }
179
+ }
180
+ }
181
+
182
+ public text(name: string, optional = false, max = 1024): string | undefined {
183
+ const value = this.argv[name];
184
+ if (value === undefined && optional) return undefined;
185
+ if (
186
+ typeof value !== "string" ||
187
+ !value.trim() ||
188
+ value.length > max ||
189
+ /[\x00-\x1f\x7f]/.test(value)
190
+ ) {
191
+ throw new TestingCommandError(
192
+ "invalid_input",
193
+ `Specify a valid --${name} value.`,
194
+ );
195
+ }
196
+ return value;
197
+ }
198
+ public required(name: string, max = 1024) {
199
+ return this.text(name, false, max)!;
200
+ }
201
+ public number(
202
+ name: string,
203
+ min: number,
204
+ max: number,
205
+ fallback?: number,
206
+ ): number {
207
+ if (this.argv[name] === undefined && fallback !== undefined)
208
+ return fallback;
209
+ const value = this.required(name);
210
+ const number = Number(value);
211
+ if (
212
+ !/^\d+$/.test(value) ||
213
+ !Number.isSafeInteger(number) ||
214
+ number < min ||
215
+ number > max
216
+ ) {
217
+ throw new TestingCommandError(
218
+ "invalid_input",
219
+ `Specify a valid --${name} integer.`,
220
+ );
221
+ }
222
+ return number;
223
+ }
224
+ public choice<T extends string>(
225
+ name: string,
226
+ values: readonly T[],
227
+ optional = false,
228
+ ): T | undefined {
229
+ const value = this.text(name, optional);
230
+ if (value === undefined) return undefined;
231
+ if (!values.includes(value as T))
232
+ throw new TestingCommandError(
233
+ "invalid_input",
234
+ `Specify a supported --${name} value.`,
235
+ );
236
+ return value as T;
237
+ }
238
+ public revision(creation = false): number | null {
239
+ if (creation && this.argv.revision === "new") return null;
240
+ return this.number("revision", 1, Number.MAX_SAFE_INTEGER);
241
+ }
242
+ public page() {
243
+ return {
244
+ afterId: this.text("after", true),
245
+ limit: this.number("limit", 1, 100, 25),
246
+ };
247
+ }
248
+ public key() {
249
+ return this.required("idempotency-key", 128);
250
+ }
251
+ public expiry() {
252
+ const value = this.required("expires-at");
253
+ const at = /^\d+$/.test(value)
254
+ ? Number(value)
255
+ : /^\d{4}-\d\d-\d\dT.*Z$/.test(value)
256
+ ? Date.parse(value)
257
+ : NaN;
258
+ if (!Number.isSafeInteger(at) || at <= Date.now())
259
+ throw new TestingCommandError(
260
+ "invalid_input",
261
+ "Credential expiration must be a future UTC timestamp.",
262
+ );
263
+ return at;
264
+ }
265
+ }
266
+
267
+ async function unwrap<T>(
268
+ pending: Promise<plugins.dcrouterData.TTestingResult<T>>,
269
+ ): Promise<T> {
270
+ const result = await pending;
271
+ if (result.ok === false) {
272
+ throw new TestingCommandError(
273
+ result.error.code,
274
+ "The testing request was refused.",
275
+ { retryAt: result.error.retryAt },
276
+ );
277
+ }
278
+ return result.value;
279
+ }
280
+
281
+ type TOperation =
282
+ | plugins.dcrouterData.TTestingCertificateJob
283
+ | plugins.dcrouterData.TTestingDnsMutation;
284
+ const pendingStates = new Set(["queued", "running", "retry_wait"]);
285
+ export const unsuccessfulStates = new Set([
286
+ "failed",
287
+ "cancelled",
288
+ "indeterminate",
289
+ "abandoned_unverified",
290
+ ]);
291
+
292
+ async function poll<T extends TOperation>(
293
+ initial: T,
294
+ read: () => Promise<plugins.dcrouterData.TTestingResult<T>>,
295
+ runtime: TestingCommandRuntime,
296
+ ): Promise<T> {
297
+ let operation = initial;
298
+ try {
299
+ while (pendingStates.has(operation.state)) {
300
+ const delay = Math.max(
301
+ 250,
302
+ Number.isFinite(operation.pollAfterMs) ? operation.pollAfterMs : 2000,
303
+ operation.retryAt === undefined ? 0 : operation.retryAt - Date.now(),
304
+ );
305
+ if (delay >= runtime.check()) {
306
+ throw new TestingCommandError(
307
+ "retry_later",
308
+ "The next permitted poll is beyond this command deadline.",
309
+ );
310
+ }
311
+ await runtime.delay(delay);
312
+ operation = await unwrap(read());
313
+ }
314
+ return operation;
315
+ } catch (error) {
316
+ if (error instanceof TestingCommandError) {
317
+ throw new TestingCommandError(error.code, error.message, {
318
+ operationId: operation.id,
319
+ retryAt: error.details?.retryAt ?? operation.retryAt,
320
+ });
321
+ }
322
+ throw new TestingCommandError(
323
+ "transport_unavailable",
324
+ "Could not read the testing operation status.",
325
+ { operationId: operation.id, retryAt: operation.retryAt },
326
+ );
327
+ }
328
+ }
329
+
330
+ /** All operations use the published API client; no copied RPC envelopes or retries. */
331
+ export async function executeTesting(
332
+ input: TestingInput,
333
+ api: plugins.TestingApi,
334
+ runtime: TestingCommandRuntime,
335
+ ): Promise<unknown> {
336
+ const options = () => runtime.requestOptions();
337
+ const grant = () => input.required("grant");
338
+ const grantState = () =>
339
+ input.choice(
340
+ "state",
341
+ ["pending", "approved", "denied", "revoked"] as const,
342
+ true,
343
+ );
344
+ const kind = () => input.choice("kind", ["certificate", "dns"] as const)!;
345
+ const reason = () => input.required("reason");
346
+ const certificate = async (
347
+ initial: plugins.dcrouterData.TTestingCertificateJob,
348
+ wait = input.argv.wait === true,
349
+ ) =>
350
+ wait
351
+ ? poll(
352
+ initial,
353
+ () => api.getCertificateJob({ jobId: initial.id }, options()),
354
+ runtime,
355
+ )
356
+ : initial;
357
+ const dns = async (initial: plugins.dcrouterData.TTestingDnsMutation) =>
358
+ input.argv.wait === true
359
+ ? poll(
360
+ initial,
361
+ () => api.getDnsMutation({ mutationId: initial.id }, options()),
362
+ runtime,
363
+ )
364
+ : initial;
365
+
366
+ switch (input.command) {
367
+ case "whoami":
368
+ return unwrap(api.getRegistration(options()));
369
+ case "zone list":
370
+ case "admin zone list":
371
+ return unwrap(api.listZones(input.page(), options()));
372
+ case "grant request":
373
+ return unwrap(
374
+ api.requestGrant(
375
+ {
376
+ zoneId: input.required("zone"),
377
+ hostname: input.required("hostname"),
378
+ idempotencyKey: input.key(),
379
+ },
380
+ options(),
381
+ ),
382
+ );
383
+ case "grant list":
384
+ case "admin grant list":
385
+ return unwrap(
386
+ api.listGrants({ ...input.page(), state: grantState() }, options()),
387
+ );
388
+ case "grant status":
389
+ case "admin grant status":
390
+ return unwrap(api.getGrant({ grantId: grant() }, options()));
391
+ case "cert ensure":
392
+ return certificate(
393
+ await unwrap(
394
+ api.requestCertificate(
395
+ { grantId: grant(), idempotencyKey: input.key() },
396
+ options(),
397
+ ),
398
+ ),
399
+ );
400
+ case "cert status":
401
+ return certificate(
402
+ await unwrap(
403
+ api.getCertificateJob({ jobId: input.required("job") }, options()),
404
+ ),
405
+ );
406
+ case "cert run": {
407
+ const job = await certificate(
408
+ await unwrap(
409
+ api.requestCertificate(
410
+ { grantId: grant(), idempotencyKey: input.key() },
411
+ options(),
412
+ ),
413
+ ),
414
+ true,
415
+ );
416
+ if (job.state !== "ready")
417
+ throw new TestingCommandError(
418
+ "certificate_not_ready",
419
+ "The certificate requires resolution before a child can start.",
420
+ { operationId: job.id, retryAt: job.retryAt },
421
+ );
422
+ const material = await unwrap(
423
+ api.downloadCertificate({ jobId: job.id }, options()),
424
+ );
425
+ process.exitCode = await runtime.runChild(material, input.argv["--"]!);
426
+ return undefined;
427
+ }
428
+ case "dns list":
429
+ return unwrap(
430
+ api.listDnsRecords({ ...input.page(), grantId: grant() }, options()),
431
+ );
432
+ case "dns upsert":
433
+ return dns(
434
+ await unwrap(
435
+ api.upsertDnsRecord(
436
+ {
437
+ grantId: grant(),
438
+ clientRecordKey: input.required("record-key"),
439
+ expectedRevision: input.revision(true),
440
+ type: input.choice("type", ["A", "AAAA", "CNAME"] as const)!,
441
+ value: input.required("value"),
442
+ ttl: input.number("ttl", 1, 2147483647),
443
+ idempotencyKey: input.key(),
444
+ },
445
+ options(),
446
+ ),
447
+ ),
448
+ );
449
+ case "dns delete":
450
+ return dns(
451
+ await unwrap(
452
+ api.deleteDnsRecord(
453
+ {
454
+ grantId: grant(),
455
+ clientRecordKey: input.required("record-key"),
456
+ expectedRevision: input.revision()!,
457
+ idempotencyKey: input.key(),
458
+ },
459
+ options(),
460
+ ),
461
+ ),
462
+ );
463
+ case "dns status":
464
+ return dns(
465
+ await unwrap(
466
+ api.getDnsMutation(
467
+ { mutationId: input.required("mutation") },
468
+ options(),
469
+ ),
470
+ ),
471
+ );
472
+ case "admin registration list":
473
+ return unwrap(
474
+ api.listRegistrations(
475
+ {
476
+ ...input.page(),
477
+ state: input.choice("state", ["active", "revoked"] as const, true),
478
+ },
479
+ options(),
480
+ ),
481
+ );
482
+ case "admin registration create":
483
+ case "admin registration rotate": {
484
+ const fd = input.number("secret-fd", 3, 255);
485
+ TestingCommandRuntime.validateSecretFd(fd);
486
+ const credential = input.command.endsWith("create")
487
+ ? await unwrap(
488
+ api.createRegistration(
489
+ {
490
+ displayName: input.required("name"),
491
+ credentialExpiresAt: input.expiry(),
492
+ idempotencyKey: input.key(),
493
+ },
494
+ options(),
495
+ ),
496
+ )
497
+ : await unwrap(
498
+ api.rotateCredential(
499
+ {
500
+ registrationId: input.required("registration"),
501
+ expectedGeneration: input.number(
502
+ "generation",
503
+ 1,
504
+ Number.MAX_SAFE_INTEGER,
505
+ ),
506
+ credentialExpiresAt: input.expiry(),
507
+ },
508
+ options(),
509
+ ),
510
+ );
511
+ TestingCommandRuntime.deliverSecret(fd, credential.token);
512
+ return credential.registration;
513
+ }
514
+ case "admin registration revoke":
515
+ return unwrap(
516
+ api.revokeRegistration(
517
+ {
518
+ registrationId: input.required("registration"),
519
+ expectedRevision: input.revision()!,
520
+ reason: reason(),
521
+ },
522
+ options(),
523
+ ),
524
+ );
525
+ case "admin zone put": {
526
+ const recordTypes = input.required("record-types").split(",");
527
+ if (
528
+ !recordTypes.length ||
529
+ new Set(recordTypes).size !== recordTypes.length ||
530
+ recordTypes.some((type) => !["A", "AAAA", "CNAME"].includes(type))
531
+ ) {
532
+ throw new TestingCommandError(
533
+ "invalid_input",
534
+ "Specify unique permitted DNS record types.",
535
+ );
536
+ }
537
+ return unwrap(
538
+ api.putZone(
539
+ {
540
+ expectedRevision: input.revision(true),
541
+ policy: {
542
+ domainId: input.required("domain"),
543
+ enabled:
544
+ input.choice("enabled", ["true", "false"] as const) === "true",
545
+ permittedRecordTypes:
546
+ recordTypes as plugins.dcrouterData.TTestingDnsRecordType[],
547
+ minTtl: input.number("min-ttl", 1, 2147483647),
548
+ maxTtl: input.number("max-ttl", 1, 2147483647),
549
+ maxGrants: input.number("max-grants", 1, Number.MAX_SAFE_INTEGER),
550
+ },
551
+ },
552
+ options(),
553
+ ),
554
+ );
555
+ }
556
+ case "admin grant review":
557
+ return unwrap(
558
+ api.reviewGrant(
559
+ {
560
+ grantId: grant(),
561
+ expectedRevision: input.revision()!,
562
+ action: input.choice("action", [
563
+ "approve",
564
+ "deny",
565
+ "reopen",
566
+ "revoke",
567
+ ] as const)!,
568
+ reason: reason(),
569
+ },
570
+ options(),
571
+ ),
572
+ );
573
+ case "admin recovery list":
574
+ return unwrap(
575
+ api.listRecoveries(
576
+ {
577
+ ...input.page(),
578
+ kind: kind(),
579
+ state: input.choice(
580
+ "state",
581
+ [
582
+ "indeterminate",
583
+ "abandoned_unverified",
584
+ "running",
585
+ "retry_wait",
586
+ ] as const,
587
+ true,
588
+ ),
589
+ },
590
+ options(),
591
+ ),
592
+ );
593
+ case "admin recovery status":
594
+ return unwrap(
595
+ api.getRecovery(
596
+ { kind: kind(), operationId: input.required("operation") },
597
+ options(),
598
+ ),
599
+ );
600
+ case "admin recovery action":
601
+ return unwrap(
602
+ api.recover(
603
+ {
604
+ kind: kind(),
605
+ operationId: input.required("operation"),
606
+ expectedRevision: input.revision()!,
607
+ action: input.choice("action", [
608
+ "recheck",
609
+ "retry-proven-unapplied",
610
+ "abandon",
611
+ ] as const)!,
612
+ reason: reason(),
613
+ idempotencyKey: input.key(),
614
+ },
615
+ options(),
616
+ ),
617
+ );
618
+ }
619
+ throw new TestingCommandError("invalid_input", "Unknown testing command.");
620
+ }