@theholocron/cli 5.0.0-alpha.429 → 5.0.0-alpha.430

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/dist/cli.mjs CHANGED
@@ -194,13 +194,6 @@ const doctorCiEntry = {
194
194
  positionals: [],
195
195
  supportsDryRun: false
196
196
  };
197
- // src/commands/doctor-credentials/doctor-credentials.entry.ts
198
- const doctorCredentialsEntry = {
199
- name: "doctor credentials",
200
- description: "Check that the credentials environment exists and holds the tokens the plugins take (read-only)",
201
- positionals: [],
202
- supportsDryRun: false
203
- };
204
197
  // src/commands/doctor-dns/doctor-dns.entry.ts
205
198
  const doctorDnsEntry = {
206
199
  name: "doctor dns",
@@ -282,41 +275,41 @@ const doctorSecretsEntry = {
282
275
  name: "doctor secrets",
283
276
  description: "Check the secrets the config says must exist against the ones the provider holds (read-only, names only)",
284
277
  positionals: [],
285
- supportsDryRun: false
286
- };
287
- // src/commands/doctor-shared-values/doctor-shared-values.entry.ts
288
- const doctorSharedValuesEntry = {
289
- name: "doctor shared-values",
290
- description: "Find secrets that hold the same value in two layers: local, dev, ci and prod (read-only, names only)",
291
- positionals: [],
292
- options: [{
293
- key: "strict",
294
- flag: "--strict",
295
- type: "confirm",
296
- default: false,
297
- message: "Fail when a secret is shared between two layers?"
298
- }],
299
- supportsDryRun: false
300
- };
301
- // src/commands/doctor-tokens/doctor-tokens.entry.ts
302
- const doctorTokensEntry = {
303
- name: "doctor tokens",
304
- description: "Check that each token a configured plugin takes is set and still accepted (read-only; no token is printed)",
305
- positionals: [],
306
- supportsDryRun: false
307
- };
308
- // src/commands/doctor-variable-owners/doctor-variable-owners.entry.ts
309
- const doctorVariableOwnersEntry = {
310
- name: "doctor variable-owners",
311
- description: "Flag a variable name that lives in more than one place: 1Password Environments and GitHub Actions (read-only, names only)",
312
- positionals: [],
313
- supportsDryRun: false
314
- };
315
- // src/commands/doctor-variables/doctor-variables.entry.ts
316
- const doctorVariablesEntry = {
317
- name: "doctor variables",
318
- description: "Check the Actions variables the config declares against the ones the provider holds (read-only)",
319
- positionals: [],
278
+ options: [
279
+ {
280
+ key: "env",
281
+ flag: "--env",
282
+ type: "input",
283
+ message: "Environments to check (local, dev, ci, test, prod; comma-separated):"
284
+ },
285
+ {
286
+ key: "verify",
287
+ flag: "--verify",
288
+ type: "confirm",
289
+ default: false,
290
+ message: "Also ask each vendor whether the tokens are still accepted (goes online)?"
291
+ },
292
+ {
293
+ key: "shared",
294
+ flag: "--shared",
295
+ type: "confirm",
296
+ default: false,
297
+ message: "Compare the layers for a secret that holds the same value in two of them?"
298
+ },
299
+ {
300
+ key: "strict",
301
+ flag: "--strict",
302
+ type: "confirm",
303
+ default: false,
304
+ message: "Fail when a place holds a name nothing feeds, or two layers share a secret?"
305
+ },
306
+ {
307
+ key: "name",
308
+ flag: "--name",
309
+ type: "input",
310
+ message: "Look up one name:"
311
+ }
312
+ ],
320
313
  supportsDryRun: false
321
314
  };
322
315
  // src/commands/github-app-create/github-app-create.entry.ts
@@ -830,10 +823,13 @@ const registry = createCommandRegistry([
830
823
  {
831
824
  name: "sync secrets",
832
825
  description: "Read a vault environment + fan KEY=VALUEs out to secrets + deployment env vars",
833
- positionals: [{
834
- key: "environmentId",
835
- message: "Vault environment id:",
836
- type: "input"
826
+ positionals: [],
827
+ options: [{
828
+ key: "env",
829
+ flag: "--env",
830
+ type: "input",
831
+ required: true,
832
+ message: "Vault environment (a layer such as ci or prod, or an Environment name):"
837
833
  }],
838
834
  supportsDryRun: true
839
835
  },
@@ -841,7 +837,6 @@ const registry = createCommandRegistry([
841
837
  doctorMonitoringEntry,
842
838
  doctorNotificationsEntry,
843
839
  doctorEnvironmentsEntry,
844
- doctorCredentialsEntry,
845
840
  doctorProjectEntry,
846
841
  doctorGitHubAppEntry,
847
842
  doctorLogsEntry,
@@ -859,10 +854,6 @@ const registry = createCommandRegistry([
859
854
  doctorDnsEntry,
860
855
  doctorRepoEntry,
861
856
  doctorSecretsEntry,
862
- doctorTokensEntry,
863
- doctorVariablesEntry,
864
- doctorVariableOwnersEntry,
865
- doctorSharedValuesEntry,
866
857
  doctorCiEntry,
867
858
  notificationsSetupEntry,
868
859
  notificationsCreateServerEntry,
@@ -1477,7 +1468,7 @@ function isUnsyncedLayer(layer) {
1477
1468
  /**
1478
1469
  * The text of the error for an Environment of an unsynced layer, shared by the command and the config checks.
1479
1470
  *
1480
- * @param what - What names the layer, e.g. "`sync secrets dev`" or "a `repo.secrets.sync` entry".
1471
+ * @param what - What names the layer, e.g. "`sync secrets --env dev`" or "a `repo.secrets.sync` entry".
1481
1472
  * @param layer - The unsynced layer.
1482
1473
  */
1483
1474
  function unsyncedLayerMessage(what, layer) {
@@ -1494,12 +1485,12 @@ function unsyncedLayerMessage(what, layer) {
1494
1485
  */
1495
1486
  async function assertSyncableLayer(id, input) {
1496
1487
  if (isEnvironmentLayer(id)) {
1497
- if (isUnsyncedLayer(id)) throw new ConfigError(unsyncedLayerMessage(`\`sync secrets ${id}\``, id));
1488
+ if (isUnsyncedLayer(id)) throw new ConfigError(unsyncedLayerMessage(`\`sync secrets --env ${id}\``, id));
1498
1489
  return;
1499
1490
  }
1500
1491
  const slug = await repoSlug(input.repoRoot, input.gitExec).catch(() => void 0);
1501
1492
  if (slug === void 0) return;
1502
- for (const layer of UNSYNCED_LAYERS) if (id === layerEnvironment(slug, layer)) throw new ConfigError(unsyncedLayerMessage(`\`sync secrets\` for ${JSON.stringify(id)}`, layer));
1493
+ for (const layer of UNSYNCED_LAYERS) if (id === layerEnvironment(slug, layer)) throw new ConfigError(unsyncedLayerMessage(`\`sync secrets --env\` for ${JSON.stringify(id)}`, layer));
1503
1494
  }
1504
1495
  // src/config/validate-secrets-deploy/validate-secrets-deploy.ts
1505
1496
  /**
@@ -2345,7 +2336,6 @@ const COMMAND_CONTEXTS = {
2345
2336
  "doctor all": "workspace",
2346
2337
  "doctor notifications": "workspace",
2347
2338
  "doctor environments": "workspace",
2348
- "doctor credentials": "workspace",
2349
2339
  "doctor project": "workspace",
2350
2340
  "doctor logs": "workspace",
2351
2341
  "doctor github-app": "workspace",
@@ -2357,11 +2347,7 @@ const COMMAND_CONTEXTS = {
2357
2347
  "doctor dns": "workspace",
2358
2348
  "doctor repo": "workspace",
2359
2349
  "doctor secrets": "workspace",
2360
- "doctor tokens": "workspace",
2361
2350
  "doctor monitoring": "workspace",
2362
- "doctor variables": "workspace",
2363
- "doctor variable-owners": "workspace",
2364
- "doctor shared-values": "workspace",
2365
2351
  "doctor ci": "repo-aware",
2366
2352
  probe: "workspace",
2367
2353
  provider: "workspace",
@@ -6565,288 +6551,6 @@ const doctorCiCommand = {
6565
6551
  })).status === "fail") process.exitCode = 1;
6566
6552
  }
6567
6553
  };
6568
- const DAY_MS = 864e5;
6569
- /**
6570
- * How long a token has left, as `expires in 12 days`, and whether that is inside the warning window.
6571
- * A time that cannot be read is reported as no expiry rather than guessed at.
6572
- */
6573
- function describeExpiry(expiresAt, now) {
6574
- const left = Date.parse(expiresAt) - now.getTime();
6575
- if (Number.isNaN(left)) return void 0;
6576
- const soon = left <= 7 * DAY_MS;
6577
- const days = Math.floor(left / DAY_MS);
6578
- if (left <= 0) return {
6579
- text: "expired",
6580
- soon
6581
- };
6582
- if (days < 1) return {
6583
- text: "expires in less than a day",
6584
- soon
6585
- };
6586
- return {
6587
- text: `expires in ${days} ${days === 1 ? "day" : "days"}`,
6588
- soon
6589
- };
6590
- }
6591
- // src/commands/doctor-tokens/doctor-tokens.ts
6592
- /**
6593
- * `holocron doctor tokens` — is each token a configured plugin takes set, and still accepted?
6594
- *
6595
- * Read-only. For every token a configured plugin lists (its `tokens` export), the token is looked up the way the
6596
- * plugin does it (the process environment, then the repo's `.env` and the `credentials` providers, then the OS keyring)
6597
- * and the plugin's `verifyToken` is asked whether it is still accepted. Each row says where the token came from. A token is never printed. One that is not set is a skip, not a failure: whether it is needed
6598
- * depends on what is run. One that is set and rejected (expired, revoked, malformed) fails, and so does one that
6599
- * the plugin reports will expire within `TOKEN_EXPIRY_WARN_DAYS` days (a warning is a fail: the check has no third
6600
- * status). A token with no expiry shows nothing extra.
6601
- *
6602
- * What a token may do is not checked: GitHub does not return a fine-grained token's permissions.
6603
- */
6604
- async function runDoctorTokens(input) {
6605
- const print = input.print ?? ((line) => console.log(line));
6606
- const logger = input.logger ?? getLogger();
6607
- const importer = input.importer ?? defaultImporter;
6608
- const env = createEnvLookup(input.env);
6609
- const readToken = input.keyring ?? keyring.get;
6610
- const now = input.now ?? (() => /* @__PURE__ */ new Date());
6611
- const rows = [];
6612
- rows.push(...await loadCredentials(input));
6613
- for (const pkg of configuredPackages(input)) {
6614
- let module;
6615
- try {
6616
- module = await importer(pkg);
6617
- } catch (err) {
6618
- rows.push(row$12(pkg, "skip", `cannot load the plugin: ${errorMessage(err)}`));
6619
- continue;
6620
- }
6621
- for (const token of module.tokens ?? []) rows.push(await checkToken$1(token, module, env, readToken, now()));
6622
- }
6623
- if (rows.length === 0) rows.push(row$12("tokens", "skip", "no configured plugin lists the tokens it takes"));
6624
- printCheckRows(rows, print);
6625
- const summary = summariseChecks(rows);
6626
- printCheckSummary(summary, print);
6627
- const status = summary.fail > 0 ? "fail" : summary.ok === 0 ? "skip" : "ok";
6628
- logger.info({
6629
- ...summary,
6630
- status
6631
- }, "doctor tokens");
6632
- return {
6633
- status,
6634
- rows,
6635
- summary,
6636
- ...status === "skip" ? { reason: [...new Set(rows.map((r) => r.detail))].join("; ") } : {}
6637
- };
6638
- }
6639
- /** The package of every provider the config names, once each. */
6640
- function configuredPackages(input) {
6641
- const packages = Object.values(input.loaded.resolved.providers).flatMap((entry) => entry.cardinality === "single" ? [entry.tuple.packageName] : entry.tuples.map((t) => t.packageName));
6642
- return [...new Set(packages)];
6643
- }
6644
- /**
6645
- * Runs the step every command runs first: the repo's `.env` and the config's `credentials` providers are read into the
6646
- * credential store, which is where `checkToken` and the plugins look after the process environment. A provider that
6647
- * could not be read is a failing row (its tokens then fall through to the keyring, which is not what was meant), and a
6648
- * loader that throws is a skip.
6649
- */
6650
- async function loadCredentials(input) {
6651
- const loader = input.loader ?? new PluginLoader(input.loaded.resolved, input.context);
6652
- try {
6653
- await loader.load();
6654
- } catch (err) {
6655
- return [row$12("credentials", "skip", `could not load the credentials providers: ${errorMessage(err)}`)];
6656
- }
6657
- return loader.loadFailures().filter((failure) => failure.key === "credentials").map((failure) => row$12(`credentials ${failure.provider}`, "fail", `could not be read: ${errorMessage(failure.error)}`));
6658
- }
6659
- function row$12(id, status, detail) {
6660
- return {
6661
- id,
6662
- title: id,
6663
- status,
6664
- detail,
6665
- problems: []
6666
- };
6667
- }
6668
- async function checkToken$1(token, module, env, readToken, now) {
6669
- const { keyringKey, envName, vendorEnvName } = token;
6670
- const fromEnv = env.get(envName) ? envName : vendorEnvName && env.get(vendorEnvName) ? vendorEnvName : void 0;
6671
- const stored = fromEnv ? void 0 : findCredential(...vendorEnvName ? [envName, vendorEnvName] : [envName]);
6672
- const value = fromEnv ? env.get(fromEnv) : stored?.value ?? readToken(keyringKey);
6673
- if (!value) return row$12(keyringKey, "skip", `not set (${vendorEnvName ? `${envName} / ${vendorEnvName}` : envName}, or \`holocron new token ${keyringKey}\`)`);
6674
- const verify = token.verify ?? (token.verifiable === false ? void 0 : module.verifyToken);
6675
- if (!verify) return row$12(keyringKey, "skip", "set, but its plugin cannot verify it");
6676
- const from = fromEnv ?? stored?.source ?? "keyring";
6677
- try {
6678
- const verified = await verify(value);
6679
- if (!verified.ok) return row$12(keyringKey, "fail", `rejected (${from}): ${verified.message}`);
6680
- const expiry = verified.expiresAt ? describeExpiry(verified.expiresAt, now) : void 0;
6681
- if (!expiry) return row$12(keyringKey, "ok", `${verified.subject} (${from})`);
6682
- return expiry.soon ? {
6683
- ...row$12(keyringKey, "fail", `${verified.subject} (${from}), ${expiry.text}`),
6684
- problems: [`${expiry.text}: renew it`]
6685
- } : row$12(keyringKey, "ok", `${verified.subject} (${from}), ${expiry.text}`);
6686
- } catch (err) {
6687
- return row$12(keyringKey, "fail", `could not be verified (${from}): ${errorMessage(err)}`);
6688
- }
6689
- }
6690
- // src/commands/doctor-tokens/doctor-tokens.command.ts
6691
- const doctorTokensCommand = {
6692
- command: "tokens",
6693
- describe: "Check that each token a configured plugin takes is set and still accepted (read-only; no token is printed)",
6694
- handler: async (argv) => {
6695
- const tokens = tokenContext$1(argv.token);
6696
- if (!tokens) return;
6697
- const loaded = await loadConfig(argv.cwd);
6698
- applyResolvedConfig(argv, loaded.resolved);
6699
- if ((await runDoctorTokens({
6700
- loaded,
6701
- context: {
6702
- repoRoot: argv.cwd,
6703
- ...tokens,
6704
- org: resolveOrg(argv, loaded.resolved)
6705
- }
6706
- })).status === "fail") process.exitCode = 1;
6707
- }
6708
- };
6709
- // src/commands/doctor-credentials/doctor-credentials.ts
6710
- /**
6711
- * `holocron doctor credentials` — does the credentials environment exist, and does it hold the tokens the plugins take?
6712
- *
6713
- * Read-only, and it never reads a value: the providers are loaded without being asked for their variables, and each
6714
- * one lists only the names (`Credentials.inspect`). The names expected are the `envName` of every token the configured
6715
- * plugins list (their `tokens` export, the same list `doctor tokens` checks). There is one row per variable, in plain
6716
- * code-unit order so the output is the same on every machine: `ok` when the environment holds it, `fail` when it lacks
6717
- * one a plugin needs, and `skip` when it lacks one a plugin only falls back to (`optional`, the Discord webhook). A
6718
- * name any plugin needs is expected even if another plugin lists it as optional. A variable the environment holds
6719
- * beyond those gets no row. Each row names the provider and the environment, and says which spelling of the
6720
- * environment's name matched, since a provider that matches names exactly may find it under a different case than the
6721
- * config writes. A provider that is missing, cannot list names or cannot find the environment gets one row of its own.
6722
- */
6723
- async function runDoctorCredentials(input) {
6724
- const print = input.print ?? ((line) => console.log(line));
6725
- const logger = input.logger ?? getLogger();
6726
- const loader = input.loader ?? new PluginLoader(input.loaded.resolved, input.context, void 0, { readCredentials: false });
6727
- await loader.load();
6728
- assertPluginsResolvable$1(loader, "doctor credentials");
6729
- const rows = await checkCredentials(input, loader);
6730
- printCheckRows(rows, print);
6731
- const summary = summariseChecks(rows);
6732
- printCheckSummary(summary, print);
6733
- const status = summary.fail > 0 ? "fail" : summary.ok === 0 ? "skip" : "ok";
6734
- logger.info({
6735
- ...summary,
6736
- status
6737
- }, "doctor credentials");
6738
- return {
6739
- status,
6740
- rows,
6741
- summary,
6742
- ...status === "skip" ? { reason: [...new Set(rows.map((r) => r.detail))].join("; ") } : {}
6743
- };
6744
- }
6745
- /** A row for the provider as a whole, or for one of its variables when `name` is given. */
6746
- function row$11(provider, status, detail, name) {
6747
- return name === void 0 ? {
6748
- id: provider,
6749
- title: provider,
6750
- status,
6751
- detail,
6752
- problems: []
6753
- } : {
6754
- id: `${provider}:${name}`,
6755
- title: `${provider}: ${name}`,
6756
- status,
6757
- detail,
6758
- problems: []
6759
- };
6760
- }
6761
- async function checkCredentials(input, loader) {
6762
- const { resolved } = input.loaded;
6763
- if (!resolved.providers.credentials) return [row$11("credentials", "skip", "no `credentials` provider is configured")];
6764
- const rows = loader.loadFailures().filter((f) => f.key === "credentials").map((f) => row$11(f.provider, "fail", `failed to load: ${errorMessage(f.error)}`));
6765
- if (!loader.has("credentials")) return rows;
6766
- const expected = await expectedTokens(input);
6767
- const { tuples } = resolved.providers.credentials;
6768
- for (const impl of loader.get("credentials")) {
6769
- const tuple = tuples.find((t) => t.provider === impl.providerName);
6770
- const explicit = tuple && credentialsEnvironment(tuple, resolved);
6771
- if (!explicit && !derivesEnvironment(impl.providerName)) {
6772
- rows.push(row$11(impl.providerName, "skip", "no `environment` option and `credentials.environment` is not set"));
6773
- continue;
6774
- }
6775
- try {
6776
- const candidates = await resolveEnvironments(impl.providerName, explicit, {
6777
- repoRoot: input.context.repoRoot,
6778
- ...input.env ? { env: input.env } : {},
6779
- ...input.gitExec ? { gitExec: input.gitExec } : {}
6780
- });
6781
- rows.push(...await checkProvider(impl, candidates, expected));
6782
- } catch (err) {
6783
- rows.push(row$11(impl.providerName, "fail", errorMessage(err)));
6784
- }
6785
- }
6786
- return rows;
6787
- }
6788
- /**
6789
- * One row per expected variable, against the Environments the layer reads. A variable counts as present when any
6790
- * Environment found holds it (the first found wins, as in the credential store). A required Environment that does not
6791
- * exist is a failing row of its own, by name; a missing `- local` is not mentioned.
6792
- */
6793
- async function checkProvider(impl, candidates, expected) {
6794
- const provider = impl.providerName;
6795
- if (!impl.inspect) return [row$11(provider, "skip", "cannot list the variables without reading their values")];
6796
- if (expected.length === 0) return [row$11(provider, "skip", "no configured plugin lists the tokens it takes")];
6797
- if (candidates.length === 0) return [row$11(provider, "skip", "the `test` layer reads no Environment")];
6798
- const inspect = impl.inspect.bind(impl);
6799
- try {
6800
- const { found, missing } = await tryEnvironments(candidates, inspect);
6801
- const rows = missing.map((name) => row$11(provider, "fail", `${provider} has no Environment named "${name}"`));
6802
- const labels = found.map(({ name, result }) => result.environment === name ? `"${name}"` : `"${result.environment}" (the config writes "${name}")`);
6803
- const where = labels.join(", ");
6804
- if (found.length === 0) return rows;
6805
- for (const { name, optional } of expected) {
6806
- const at = found.findIndex((f) => f.result.names.includes(name));
6807
- if (at >= 0) rows.push(row$11(provider, "ok", `present in ${labels[at]}`, name));
6808
- else if (optional) rows.push(row$11(provider, "skip", `optional, not set in ${where}`, name));
6809
- else rows.push(row$11(provider, "fail", `missing from ${where}`, name));
6810
- }
6811
- return rows;
6812
- } catch (err) {
6813
- return [row$11(provider, "fail", errorMessage(err))];
6814
- }
6815
- }
6816
- /**
6817
- * The `envName` of every token the configured plugins list, once each, in plain code-unit order. A name any plugin
6818
- * needs is not `optional`. A plugin that cannot be loaded lists none.
6819
- */
6820
- async function expectedTokens(input) {
6821
- const importer = input.importer ?? defaultImporter;
6822
- const optionalOnly = /* @__PURE__ */ new Map();
6823
- for (const pkg of configuredPackages(input)) try {
6824
- for (const token of (await importer(pkg)).tokens ?? []) optionalOnly.set(token.envName, (optionalOnly.get(token.envName) ?? true) && token.optional === true);
6825
- } catch {}
6826
- return [...optionalOnly.keys()].sort().map((name) => ({
6827
- name,
6828
- optional: optionalOnly.get(name) === true
6829
- }));
6830
- }
6831
- // src/commands/doctor-credentials/doctor-credentials.command.ts
6832
- const doctorCredentialsCommand = {
6833
- command: "credentials",
6834
- describe: "Check that the credentials environment exists and holds the tokens the plugins take (read-only)",
6835
- handler: async (argv) => {
6836
- const tokens = tokenContext$1(argv.token);
6837
- if (!tokens) return;
6838
- const loaded = await loadConfig(argv.cwd);
6839
- applyResolvedConfig(argv, loaded.resolved);
6840
- if ((await runDoctorCredentials({
6841
- loaded,
6842
- context: {
6843
- repoRoot: argv.cwd,
6844
- ...tokens,
6845
- org: resolveOrg(argv, loaded.resolved)
6846
- }
6847
- })).status === "fail") process.exitCode = 1;
6848
- }
6849
- };
6850
6554
  // src/commands/missing-token/missing-token.ts
6851
6555
  /**
6852
6556
  * Why a provider call could not be tried for want of a token, or undefined when the error is something else. A plugin
@@ -7100,7 +6804,7 @@ async function runDoctorDns(input) {
7100
6804
  });
7101
6805
  else if (!loader.has("dns")) {
7102
6806
  const why = whyMissing(loader, "dns", "no `dns` provider to check them with");
7103
- for (const zone of zones) rows.push(row$10(zone, "skip", why));
6807
+ for (const zone of zones) rows.push(row$12(zone, "skip", why));
7104
6808
  for (const { hostname } of domains) rows.push(domainRow(hostname, "skip", why));
7105
6809
  } else {
7106
6810
  const dns = loader.get("dns");
@@ -7122,7 +6826,7 @@ async function runDoctorDns(input) {
7122
6826
  ...status === "skip" ? { reason: [...new Set(rows.map((r) => r.detail))].join("; ") } : {}
7123
6827
  };
7124
6828
  }
7125
- function row$10(zone, status, detail, problems = []) {
6829
+ function row$12(zone, status, detail, problems = []) {
7126
6830
  return {
7127
6831
  id: `dns-${zone}`,
7128
6832
  title: `${zone} records exist`,
@@ -7151,7 +6855,7 @@ async function checkDomain(dns, deploy, project, hostname) {
7151
6855
  return noToken !== void 0 ? domainRow(hostname, "skip", noToken) : domainRow(hostname, "fail", errorMessage(err));
7152
6856
  }
7153
6857
  }
7154
- async function checkZone(dns, zone, wanted, rowOf = (...args) => row$10(zone, ...args)) {
6858
+ async function checkZone(dns, zone, wanted, rowOf = (...args) => row$12(zone, ...args)) {
7155
6859
  try {
7156
6860
  const have = await dns.listRecords(zone);
7157
6861
  const problems = declaredVsActual(new Map(wanted.map((w) => [keyOf(w), w])), new Map(have.map((h) => [keyOf(h), h])), {
@@ -7286,7 +6990,7 @@ function installationSettingsUrl(account, id) {
7286
6990
  return `https://github.com/settings/installations/${id}`;
7287
6991
  }
7288
6992
  // src/commands/doctor-github-app/app-rows.ts
7289
- const row$9 = (name, what, problems, ok) => ({
6993
+ const row$11 = (name, what, problems, ok) => ({
7290
6994
  id: `${name}:${what}`,
7291
6995
  title: `${name}: ${what}`,
7292
6996
  status: problems.length > 0 ? "fail" : "ok",
@@ -7313,9 +7017,9 @@ function appRows(name, manifest, app, installations) {
7313
7017
  return [`${who} has not accepted the current App: ${gaps.join("; ")}`, `fix: ${who} accepts the update at ${url}`];
7314
7018
  });
7315
7019
  return [
7316
- row$9(name, "events", eventProblems.length > 0 ? [...eventProblems, fix] : [], `all ${manifest.events.length} subscribed${extrasNote("extra event(s)", extraEvents)}`),
7317
- row$9(name, "permissions", permissionProblems.length > 0 ? [...permissionProblems, fix] : [], `all ${Object.keys(manifest.permissions).length} granted${extrasNote("extra permission(s)", extraPermissions)}`),
7318
- row$9(name, "installations", installationProblems, `${installations.length} installation(s) up to date`)
7020
+ row$11(name, "events", eventProblems.length > 0 ? [...eventProblems, fix] : [], `all ${manifest.events.length} subscribed${extrasNote("extra event(s)", extraEvents)}`),
7021
+ row$11(name, "permissions", permissionProblems.length > 0 ? [...permissionProblems, fix] : [], `all ${Object.keys(manifest.permissions).length} granted${extrasNote("extra permission(s)", extraPermissions)}`),
7022
+ row$11(name, "installations", installationProblems, `${installations.length} installation(s) up to date`)
7319
7023
  ];
7320
7024
  }
7321
7025
  // src/commands/doctor-github-app/parse-manifest.ts
@@ -7373,7 +7077,7 @@ async function runDoctorGitHubApp(input) {
7373
7077
  assertPluginsResolvable$1(loader, "doctor github-app");
7374
7078
  }
7375
7079
  const rows = [];
7376
- if (instances.length === 0) rows.push(row$8("github-app", "reachable", "skip", "no `githubApps` are declared in holocron.config.ts"));
7080
+ if (instances.length === 0) rows.push(row$10("github-app", "reachable", "skip", "no `githubApps` are declared in holocron.config.ts"));
7377
7081
  for (const instance of instances) rows.push(...await checkInstance(instance, loader, input));
7378
7082
  printCheckRows(rows, print);
7379
7083
  const summary = summariseChecks(rows);
@@ -7390,7 +7094,7 @@ async function runDoctorGitHubApp(input) {
7390
7094
  ...status === "skip" ? { reason: [...new Set(rows.map((r) => r.detail))].join("; ") } : {}
7391
7095
  };
7392
7096
  }
7393
- function row$8(name, what, status, detail) {
7097
+ function row$10(name, what, status, detail) {
7394
7098
  return {
7395
7099
  id: `${name}:${what}`,
7396
7100
  title: `${name}: ${what}`,
@@ -7431,19 +7135,19 @@ async function checkInstance(instance, loader, input) {
7431
7135
  try {
7432
7136
  manifest = parseManifest(readManifest(instance.manifest));
7433
7137
  } catch (err) {
7434
- return [row$8(name, "manifest", "fail", `cannot read ${instance.manifest}: ${errorMessage(err)}`)];
7138
+ return [row$10(name, "manifest", "fail", `cannot read ${instance.manifest}: ${errorMessage(err)}`)];
7435
7139
  }
7436
7140
  const read = await readCredentials(instance, loader);
7437
- if ("reason" in read) return [row$8(name, "reachable", "skip", read.reason)];
7141
+ if ("reason" in read) return [row$10(name, "reachable", "skip", read.reason)];
7438
7142
  const api = input.api ?? defaultApi;
7439
7143
  const secrets = [read.creds.privateKey];
7440
7144
  try {
7441
7145
  const app = await api.getApp(read.creds);
7442
7146
  const installations = await api.listAppInstallations(read.creds);
7443
7147
  const owner = app.owner ? `, owned by ${app.owner.login}` : "";
7444
- return [row$8(name, "reachable", "ok", `${app.slug}${owner}, settings: ${appSettingsUrl(app)}`), ...appRows(name, manifest, app, installations)];
7148
+ return [row$10(name, "reachable", "ok", `${app.slug}${owner}, settings: ${appSettingsUrl(app)}`), ...appRows(name, manifest, app, installations)];
7445
7149
  } catch (err) {
7446
- return [row$8(name, "reachable", "fail", `cannot call GitHub as the App: ${scrubbed$1(err, secrets)}`)];
7150
+ return [row$10(name, "reachable", "fail", `cannot call GitHub as the App: ${scrubbed$1(err, secrets)}`)];
7447
7151
  }
7448
7152
  }
7449
7153
  // src/commands/doctor-github-app/doctor-github-app.command.ts
@@ -7510,7 +7214,7 @@ function datasetTargets(config) {
7510
7214
  * dataset, shared by every environment in it). Only a dataset the provider says is missing, or a token it refuses, fails;
7511
7215
  * a name, a token or a response that cannot be read is a skip with the reason.
7512
7216
  */
7513
- const row$7 = (id, title, status, detail, problems = []) => ({
7217
+ const row$9 = (id, title, status, detail, problems = []) => ({
7514
7218
  id,
7515
7219
  title,
7516
7220
  status,
@@ -7527,7 +7231,7 @@ async function runDoctorLogs(input) {
7527
7231
  if (!loader.has("logs")) {
7528
7232
  const failure = loader.loadFailures().find((f) => f.key === "logs");
7529
7233
  const why = failure ? `\`${failure.provider}\` failed to load: ${describeError(failure.error)}` : "no `logs` provider is configured in holocron.config.ts";
7530
- rows.push(row$7("logs", "logs", "skip", why));
7234
+ rows.push(row$9("logs", "logs", "skip", why));
7531
7235
  } else rows.push(...await checkLogs(loader.get("logs"), datasetTargets(input.loaded.resolved)));
7532
7236
  printCheckRows(rows, print);
7533
7237
  const summary = summariseChecks(rows);
@@ -7546,43 +7250,43 @@ async function runDoctorLogs(input) {
7546
7250
  }
7547
7251
  async function checkLogs(logs, targets) {
7548
7252
  const rows = [];
7549
- const token = await checkToken(logs);
7253
+ const token = await checkToken$1(logs);
7550
7254
  rows.push(token.row);
7551
7255
  for (const target of targets) {
7552
7256
  const id = `logs:dataset:${target.id}`;
7553
7257
  const title = `dataset for ${target.label}`;
7554
- if (!target.name) rows.push(row$7(id, title, "skip", `${target.variable} is not set here, so there is no name to look for`));
7555
- else if (!token.usable) rows.push(row$7(id, title, "skip", `${target.name}: not checked, the token is not usable`));
7556
- else if (!logs.readDataset) rows.push(row$7(id, title, "skip", `${logs.providerName} cannot read a dataset`));
7258
+ if (!target.name) rows.push(row$9(id, title, "skip", `${target.variable} is not set here, so there is no name to look for`));
7259
+ else if (!token.usable) rows.push(row$9(id, title, "skip", `${target.name}: not checked, the token is not usable`));
7260
+ else if (!logs.readDataset) rows.push(row$9(id, title, "skip", `${logs.providerName} cannot read a dataset`));
7557
7261
  else rows.push(...await checkDataset(logs, target, target.name, id, title));
7558
7262
  }
7559
7263
  const org = resolveValue$2(["AXIOM_ORG"], void 0, { prefix: PREFIX });
7560
- rows.push(org ? row$7("logs:org", "organization", "ok", `${PREFIX}_AXIOM_ORG (or AXIOM_ORG) is set`) : row$7("logs:org", "organization", "skip", `${PREFIX}_AXIOM_ORG (or AXIOM_ORG) is not set here; Sentinel's log links and check-dispatched need it`));
7264
+ rows.push(org ? row$9("logs:org", "organization", "ok", `${PREFIX}_AXIOM_ORG (or AXIOM_ORG) is set`) : row$9("logs:org", "organization", "skip", `${PREFIX}_AXIOM_ORG (or AXIOM_ORG) is not set here; Sentinel's log links and check-dispatched need it`));
7561
7265
  return rows;
7562
7266
  }
7563
7267
  /** Whether the provider accepts the token. `usable` is false when it was refused or could not be tried. */
7564
- async function checkToken(logs) {
7268
+ async function checkToken$1(logs) {
7565
7269
  const title = "token is accepted";
7566
7270
  if (!logs.checkToken) return {
7567
- row: row$7("logs:token", title, "skip", `${logs.providerName} cannot check a token`),
7271
+ row: row$9("logs:token", title, "skip", `${logs.providerName} cannot check a token`),
7568
7272
  usable: true
7569
7273
  };
7570
7274
  try {
7571
7275
  const result = await logs.checkToken();
7572
7276
  if (result.ok) return {
7573
- row: row$7("logs:token", title, "ok", `${logs.providerName} accepts the token`),
7277
+ row: row$9("logs:token", title, "ok", `${logs.providerName} accepts the token`),
7574
7278
  usable: true
7575
7279
  };
7576
7280
  const reason = result.reason ?? `${logs.providerName} refused the token`;
7577
7281
  return {
7578
- row: row$7("logs:token", title, "fail", reason, [reason]),
7282
+ row: row$9("logs:token", title, "fail", reason, [reason]),
7579
7283
  usable: false
7580
7284
  };
7581
7285
  } catch (err) {
7582
7286
  const noToken = missingTokenReason(err);
7583
7287
  const detail = noToken ?? `could not check the token: ${describeError(err)}`;
7584
7288
  return {
7585
- row: row$7("logs:token", title, "skip", detail),
7289
+ row: row$9("logs:token", title, "skip", detail),
7586
7290
  usable: noToken === void 0
7587
7291
  };
7588
7292
  }
@@ -7592,13 +7296,13 @@ async function checkDataset(logs, target, name, id, title) {
7592
7296
  const found = await logs.readDataset(name);
7593
7297
  if (!found.exists) {
7594
7298
  const problem = `dataset ${name} does not exist (${target.variable}); ${target.fix}`;
7595
- return [row$7(id, title, "fail", `${name} does not exist`, [problem])];
7299
+ return [row$9(id, title, "fail", `${name} does not exist`, [problem])];
7596
7300
  }
7597
7301
  const retention = found.retentionDays === void 0 ? `retention: ${logs.providerName} did not report one for ${name}` : `retention: ${found.retentionDays} days for ${name}`;
7598
- return [row$7(id, title, "ok", `${name} exists`), row$7(`logs:retention:${target.id}`, `retention of ${name}`, "skip", `info: ${retention}; one setting shared by every environment in the dataset (ADR-0019)`)];
7302
+ return [row$9(id, title, "ok", `${name} exists`), row$9(`logs:retention:${target.id}`, `retention of ${name}`, "skip", `info: ${retention}; one setting shared by every environment in the dataset (ADR-0019)`)];
7599
7303
  } catch (err) {
7600
7304
  const detail = missingTokenReason(err) ?? `could not read ${name}: ${describeError(err)}`;
7601
- return [row$7(id, title, "skip", detail)];
7305
+ return [row$9(id, title, "skip", detail)];
7602
7306
  }
7603
7307
  }
7604
7308
  // src/commands/doctor-logs/doctor-logs.command.ts
@@ -8553,7 +8257,7 @@ async function runNotificationsSetup(input$1) {
8553
8257
  print(` ${(changed ? style.success : style.skip)(`${verb} ${errors.providerName} ${what} ${name}${detail}`)}`);
8554
8258
  made(changed);
8555
8259
  }
8556
- if (!signingSecret) print(` ${style.warn(`${errors.providerName} did not give the integration's signing secret (it may only show it once, when the integration is made), so the Worker keeps the one it has. To set it: copy it from the integration's page, add it to Doppler as COMLINK_${errors.providerName.toUpperCase()}_SECRET and run holocron sync secrets`)}`);
8260
+ if (!signingSecret) print(` ${style.warn(`${errors.providerName} did not give the integration's signing secret (it may only show it once, when the integration is made), so the Worker keeps the one it has. To set it: copy it from the integration's page, add it to Doppler as COMLINK_${errors.providerName.toUpperCase()}_SECRET and run holocron sync secrets --env prod`)}`);
8557
8261
  });
8558
8262
  await attempt(`relay ${layout.relay.host}`, async () => {
8559
8263
  if (dryRun) {
@@ -10540,7 +10244,7 @@ const info = (id, title, noun, extras) => ({
10540
10244
  detail: `info: ${extras.length} ${noun} not in the template (never deleted)`,
10541
10245
  problems: extras
10542
10246
  });
10543
- const row$6 = (id, title, problems, ok) => ({
10247
+ const row$8 = (id, title, problems, ok) => ({
10544
10248
  id,
10545
10249
  title,
10546
10250
  status: problems.length > 0 ? "fail" : "ok",
@@ -10576,19 +10280,19 @@ function viewProblems(want, found) {
10576
10280
  function boardRows(boardName, template, state) {
10577
10281
  const id = `project:${boardName}`;
10578
10282
  const rows = [];
10579
- rows.push(row$6(`${id}:statuses`, `${boardName}: statuses`, listProblems("status", "statuses", template.statuses.map((s) => s.name), state.statuses), `${template.statuses.length} in order`));
10283
+ rows.push(row$8(`${id}:statuses`, `${boardName}: statuses`, listProblems("status", "statuses", template.statuses.map((s) => s.name), state.statuses), `${template.statuses.length} in order`));
10580
10284
  const extraStatuses = state.statuses.filter((s) => !template.statuses.some((t) => t.name === s));
10581
10285
  if (extraStatuses.length > 0) rows.push(info(`${id}:extra-statuses`, `${boardName}: extra statuses`, "status(es)", extraStatuses));
10582
- for (const want of template.fields) rows.push(row$6(`${id}:field:${want.name}`, `${boardName}: field ${want.name}`, fieldProblems(want, state.fields.find((f) => f.name === want.name)), want.options ? `${want.options.length} options in order` : want.type));
10286
+ for (const want of template.fields) rows.push(row$8(`${id}:field:${want.name}`, `${boardName}: field ${want.name}`, fieldProblems(want, state.fields.find((f) => f.name === want.name)), want.options ? `${want.options.length} options in order` : want.type));
10583
10287
  const extraFields = state.fields.filter((f) => !template.fields.some((t) => t.name === f.name));
10584
10288
  if (extraFields.length > 0) rows.push(info(`${id}:extra-fields`, `${boardName}: extra fields`, "field(s)", extraFields.map((f) => f.name)));
10585
- for (const want of template.views) rows.push(row$6(`${id}:view:${want.name}`, `${boardName}: view ${want.name}`, viewProblems(want, state.views.find((v) => v.name === want.name)), `${want.layout}${want.filter ? `, ${want.filter}` : ""}`));
10289
+ for (const want of template.views) rows.push(row$8(`${id}:view:${want.name}`, `${boardName}: view ${want.name}`, viewProblems(want, state.views.find((v) => v.name === want.name)), `${want.layout}${want.filter ? `, ${want.filter}` : ""}`));
10586
10290
  const extraViews = state.views.filter((v) => !template.views.some((t) => t.name === v.name));
10587
10291
  if (extraViews.length > 0) rows.push(info(`${id}:extra-views`, `${boardName}: extra views`, "view(s)", extraViews.map((v) => v.name)));
10588
10292
  for (const name of template.rules ?? []) {
10589
10293
  const found = state.rules.find((r) => r.name === name);
10590
10294
  const problems = !found ? [`missing rule ${name}`] : found.enabled ? [] : [`rule ${name} is off`];
10591
- rows.push(row$6(`${id}:rule:${name}`, `${boardName}: rule ${name}`, problems, "on"));
10295
+ rows.push(row$8(`${id}:rule:${name}`, `${boardName}: rule ${name}`, problems, "on"));
10592
10296
  }
10593
10297
  return rows;
10594
10298
  }
@@ -10648,7 +10352,7 @@ function itemRows(boardName, items) {
10648
10352
  * never fail the run. A template file that does not read is a failure naming the file. `--post [channel]` shares the
10649
10353
  * failing rows through the `notifications` provider's bot, like `doctor notifications --post`.
10650
10354
  */
10651
- const row$5 = (id, title, status, detail, problems = []) => ({
10355
+ const row$7 = (id, title, status, detail, problems = []) => ({
10652
10356
  id,
10653
10357
  title,
10654
10358
  status,
@@ -10702,14 +10406,14 @@ async function checkBoards(input, loader) {
10702
10406
  loader,
10703
10407
  ...input.io ? { io: input.io } : {}
10704
10408
  });
10705
- if (!opened.ok) return [row$5("project", "project", opened.kind, opened.reason, opened.problems)];
10409
+ if (!opened.ok) return [row$7("project", "project", opened.kind, opened.reason, opened.problems)];
10706
10410
  const { projects, owner, boards, templates, templateProblems } = opened.context;
10707
10411
  const rows = templateProblems.map((problem) => {
10708
10412
  /* v8 ignore next -- split always returns at least one element; the fallback only satisfies noUncheckedIndexedAccess */
10709
10413
  const file = problem.split(": ")[0] ?? problem;
10710
- return row$5(`project:template:${file}`, `template file ${file}`, "fail", problem);
10414
+ return row$7(`project:template:${file}`, `template file ${file}`, "fail", problem);
10711
10415
  });
10712
- if (boards.length === 0) return [...rows, row$5("project", "project", "skip", "no boards are declared in `providers.projects.boards`")];
10416
+ if (boards.length === 0) return [...rows, row$7("project", "project", "skip", "no boards are declared in `providers.projects.boards`")];
10713
10417
  for (const declared of boards) {
10714
10418
  const template = templates[declared.template];
10715
10419
  const title = `${declared.name}: board exists and is open`;
@@ -10717,18 +10421,18 @@ async function checkBoards(input, loader) {
10717
10421
  const board = await projects.find(owner, declared.name);
10718
10422
  if (!board) {
10719
10423
  const closed = (await projects.list(owner)).some((b) => b.name === declared.name && b.closed);
10720
- rows.push(row$5(`project:${declared.name}`, title, "fail", closed ? "the board is closed" : "no open board has this name", [closed ? "reopen it, or run `holocron setup project` to make a new one" : "run `holocron setup project`"]));
10424
+ rows.push(row$7(`project:${declared.name}`, title, "fail", closed ? "the board is closed" : "no open board has this name", [closed ? "reopen it, or run `holocron setup project` to make a new one" : "run `holocron setup project`"]));
10721
10425
  continue;
10722
10426
  }
10723
- rows.push(row$5(`project:${declared.name}`, title, "ok", board.url));
10427
+ rows.push(row$7(`project:${declared.name}`, title, "ok", board.url));
10724
10428
  if (!template) {
10725
- rows.push(row$5(`project:${declared.name}:template`, `${declared.name}: template ${declared.template}`, "fail", "no built-in or file template has this name"));
10429
+ rows.push(row$7(`project:${declared.name}:template`, `${declared.name}: template ${declared.template}`, "fail", "no built-in or file template has this name"));
10726
10430
  continue;
10727
10431
  }
10728
10432
  rows.push(...boardRows(declared.name, template, await projects.read(owner, board)));
10729
- rows.push(...projects.items ? itemRows(declared.name, await projects.items(owner, board, template)) : [row$5(`project:${declared.name}:items`, `${declared.name}: items`, "skip", "the provider cannot list a board's items")]);
10433
+ rows.push(...projects.items ? itemRows(declared.name, await projects.items(owner, board, template)) : [row$7(`project:${declared.name}:items`, `${declared.name}: items`, "skip", "the provider cannot list a board's items")]);
10730
10434
  } catch (err) {
10731
- rows.push(row$5(`project:${declared.name}`, title, "fail", describeError(err)));
10435
+ rows.push(row$7(`project:${declared.name}`, title, "fail", describeError(err)));
10732
10436
  }
10733
10437
  }
10734
10438
  return rows;
@@ -11402,19 +11106,19 @@ async function runDoctorRepo(input) {
11402
11106
  const rows = [];
11403
11107
  if (!loader.has("source")) {
11404
11108
  const why = whyMissing(loader, "source", "no `source` provider to read the repository with");
11405
- for (const check of checks) rows.push(row$4(check, { skip: why }));
11109
+ for (const check of checks) rows.push(row$6(check, { skip: why }));
11406
11110
  } else {
11407
11111
  const source = loader.get("source");
11408
11112
  for (const check of checks) {
11409
11113
  if (typeof source[check.needs] !== "function") {
11410
- rows.push(row$4(check, { skip: `provider does not implement ${check.needs}` }));
11114
+ rows.push(row$6(check, { skip: `provider does not implement ${check.needs}` }));
11411
11115
  continue;
11412
11116
  }
11413
11117
  try {
11414
- rows.push(row$4(check, await check.run(source)));
11118
+ rows.push(row$6(check, await check.run(source)));
11415
11119
  } catch (err) {
11416
11120
  const noToken = missingTokenReason(err);
11417
- if (noToken !== void 0) rows.push(row$4(check, { skip: noToken }));
11121
+ if (noToken !== void 0) rows.push(row$6(check, { skip: noToken }));
11418
11122
  else rows.push({
11419
11123
  id: check.id,
11420
11124
  title: check.title,
@@ -11440,7 +11144,7 @@ async function runDoctorRepo(input) {
11440
11144
  ...status === "skip" ? { reason: rows.map((r) => r.detail).join("; ") } : {}
11441
11145
  };
11442
11146
  }
11443
- function row$4(check, result) {
11147
+ function row$6(check, result) {
11444
11148
  const { id, title } = check;
11445
11149
  if ("skip" in result) return {
11446
11150
  id,
@@ -11635,83 +11339,6 @@ async function shadowRow(secrets, orgNames) {
11635
11339
  };
11636
11340
  }
11637
11341
  }
11638
- // src/commands/secrets-sync/deploy-filter/deploy-filter.ts
11639
- /**
11640
- * What `repo.secrets.deploy` lets one vault environment send to a deployment or a Worker: every entry naming it adds
11641
- * its `keys` and `prefix`. `undefined` when no entry names it, which the caller turns into a `ConfigError`; there is
11642
- * no default that sends everything.
11643
- *
11644
- * @param entries - `repo.secrets.deploy`, if the config has it.
11645
- * @param environmentId - The vault environment being synced.
11646
- */
11647
- function deployFilter(entries, environmentId) {
11648
- const matching = (entries ?? []).filter((entry) => entry.environment === environmentId);
11649
- if (matching.length === 0) return void 0;
11650
- return {
11651
- keys: [...new Set(matching.flatMap((entry) => entry.keys ?? []))],
11652
- prefixes: [...new Set(matching.flatMap((entry) => entry.prefix ? [entry.prefix] : []))]
11653
- };
11654
- }
11655
- // src/commands/secrets-sync/split-deploy-keys/split-deploy-keys.ts
11656
- /**
11657
- * Split a vault environment's key names by what a deployment may receive. A key passes when it is listed or starts
11658
- * with a prefix (case-sensitive). A listed key the vault does not hold stays in `send`, so the sync reports it as
11659
- * missing rather than dropping it. Only names go in and out.
11660
- *
11661
- * @param vaultKeys - The names the vault environment holds.
11662
- * @param filter - From `deployFilter()`.
11663
- */
11664
- function splitDeployKeys(vaultKeys, filter) {
11665
- const passes = (key) => filter.keys.includes(key) || filter.prefixes.some((p) => key.startsWith(p));
11666
- const send = vaultKeys.filter(passes);
11667
- const filtered = vaultKeys.filter((key) => !passes(key));
11668
- return {
11669
- send: [...send, ...filter.keys.filter((key) => !vaultKeys.includes(key))],
11670
- filtered
11671
- };
11672
- }
11673
- // src/commands/doctor-secrets/deploy-key-rows.ts
11674
- /**
11675
- * One row per vault environment `repo.secrets.deploy` names: the key names a deployment or Worker would receive from
11676
- * a `sync secrets`, and how many the filter keeps back, so a token that should not go out is visible before the
11677
- * sync. Names only: the values the vault returns are dropped at once. An environment that cannot be listed (no vault,
11678
- * no token, an error) is a skipped row with the reason, never a failure.
11679
- *
11680
- * @param entries - `repo.secrets.deploy`.
11681
- * @param vault - The `vault` provider, or why there is none.
11682
- */
11683
- async function deployKeyRows(entries, vault) {
11684
- const rows = [];
11685
- for (const environment of [...new Set(entries.map(resolvedEnvironment))]) {
11686
- const id = `deploy-${environment}`;
11687
- const title = `${environment} deployment receives only its keys`;
11688
- const skip = (detail) => rows.push({
11689
- id,
11690
- title,
11691
- status: "skip",
11692
- detail,
11693
- problems: []
11694
- });
11695
- const filter = deployFilter(entries, environment);
11696
- if ("why" in vault) skip(vault.why);
11697
- else if (!vault.readEnvironment) skip(`vault provider (${vault.providerName}) cannot list an environment's keys`);
11698
- else try {
11699
- const names = Object.keys(await vault.readEnvironment(environment)).sort();
11700
- const { send, filtered } = splitDeployKeys(names, filter);
11701
- const sends = send.filter((name) => names.includes(name));
11702
- rows.push({
11703
- id,
11704
- title,
11705
- status: "ok",
11706
- detail: `sends ${sends.length} of ${names.length}: ${sends.join(", ") || "(none)"}${filtered.length > 0 ? `; keeps back ${filtered.length}: ${filtered.join(", ")}` : ""}`,
11707
- problems: []
11708
- });
11709
- } catch (err) {
11710
- skip(missingTokenReason(err) ?? `could not read vault environment ${environment}: ${describeError(err)}`);
11711
- }
11712
- }
11713
- return rows;
11714
- }
11715
11342
  // src/commands/doctor-secrets/unique-names.ts
11716
11343
  /** Names that differ only in case are one secret to GitHub, so the first spelling wins. */
11717
11344
  const uniqueNames = (names) => {
@@ -11803,26 +11430,23 @@ async function syncedSecrets(entries, vault) {
11803
11430
  rows
11804
11431
  };
11805
11432
  }
11806
- // src/commands/doctor-secrets/doctor-secrets.ts
11433
+ // src/commands/doctor-secrets/ci-rows.ts
11807
11434
  /**
11808
- * `holocron doctor secrets` — do the secrets the config says must exist, exist?
11435
+ * The `ci` side of `doctor secrets`: the GitHub secrets the config expects (`repo.secrets`, the notification layouts'
11436
+ * secrets and what `repo.secrets.sync` fills) against the ones the `secrets` provider holds, who can read the
11437
+ * organization ones, and a skipped row for each `repo.secrets.sync` entry that could not be resolved.
11809
11438
  *
11810
- * Read-only, names only: GitHub never returns a value. One row for the repository's secrets, one for the
11811
- * organization's and one per environment, each only when the config expects something there (see
11812
- * {@link expectedSecrets}). A secret that exists but is not expected is never a problem. A scope that cannot be
11813
- * read because there is no provider, or no token for it, is a skip with the reason, not a failure.
11439
+ * @param loader - The loaded plugins.
11440
+ * @param config - The resolved config.
11441
+ * @param vault - The `vault` provider, or why there is none.
11442
+ * @param org - The organization the organization secrets live in, when it is known.
11443
+ * @returns The rows, what each scope held (names only, for the matrix), and whether the config declares anything on this
11444
+ * side (when it does not, the caller says so once).
11814
11445
  */
11815
- async function runDoctorSecrets(input) {
11816
- const print = input.print ?? ((line) => console.log(line));
11817
- const logger = input.logger ?? getLogger();
11818
- const loader = input.loader ?? new PluginLoader(input.loaded.resolved, input.context);
11819
- await loader.load();
11820
- assertPluginsResolvable$1(loader, "doctor secrets");
11821
- const config = input.loaded.resolved;
11446
+ async function ciRows(loader, config, vault, org) {
11822
11447
  const layouts = (loader.has("notifications") ? loader.get("notifications") : []).flatMap((p) => p.layout ? [p.layout] : []);
11823
11448
  const expected = expectedSecrets(config, layouts);
11824
- const org = input.context.org ?? (input.context.repo ?? config.repo?.name ?? "").split("/")[0];
11825
- const synced = await syncedSecrets(config.repo?.secrets?.sync ?? [], loader.has("vault") ? loader.get("vault") : { why: whyMissing(loader, "vault", "no `vault` provider to list the environment's keys with") });
11449
+ const synced = await syncedSecrets(config.repo?.secrets?.sync ?? [], vault);
11826
11450
  const foreignOrgs = /* @__PURE__ */ new Map();
11827
11451
  for (const { scope, names } of synced.scopes) if (scope.kind === "repo") expected.repo = uniqueNames([...expected.repo, ...names]);
11828
11452
  else if (scope.kind === "environment") expected.environments[scope.name] = uniqueNames([...expected.environments[scope.name] ?? [], ...names]);
@@ -11869,26 +11493,39 @@ async function runDoctorSecrets(input) {
11869
11493
  });
11870
11494
  }
11871
11495
  const rows = [];
11872
- const deployRows = await deployKeyRows(config.repo?.secrets?.deploy ?? [], loader.has("vault") ? loader.get("vault") : { why: whyMissing(loader, "vault", "no `vault` provider to list the environment's keys with") });
11873
- if (checks.length === 0 && synced.rows.length === 0 && deployRows.length === 0) rows.push({
11874
- id: "secrets",
11875
- title: "secrets",
11876
- status: "ok",
11877
- detail: "none declared",
11878
- problems: []
11879
- });
11880
- else if (!loader.has("secrets")) {
11496
+ const observations = [];
11497
+ if (checks.length === 0 && synced.rows.length === 0) return {
11498
+ declared: false,
11499
+ rows,
11500
+ observations
11501
+ };
11502
+ if (!loader.has("secrets")) {
11881
11503
  const why = whyMissing(loader, "secrets", "no `secrets` provider to check them with");
11882
- for (const { id, title } of checks) rows.push({
11883
- id,
11884
- title,
11885
- status: "skip",
11886
- detail: why,
11887
- problems: []
11888
- });
11504
+ for (const { id, title, scope, names } of checks) {
11505
+ rows.push({
11506
+ id,
11507
+ title,
11508
+ status: "skip",
11509
+ detail: why,
11510
+ problems: []
11511
+ });
11512
+ if (!("problem" in scope)) observations.push({
11513
+ scope,
11514
+ needed: names,
11515
+ unread: why
11516
+ });
11517
+ }
11889
11518
  } else {
11890
11519
  const secrets = loader.get("secrets");
11891
- for (const check of checks) rows.push(await checkScope(secrets, check));
11520
+ for (const check of checks) {
11521
+ const checked = await checkScope(secrets, check);
11522
+ rows.push(checked.row);
11523
+ if (!("problem" in check.scope)) observations.push({
11524
+ scope: check.scope,
11525
+ needed: check.names,
11526
+ ...checked.have ? { have: checked.have } : { unread: checked.row.detail }
11527
+ });
11528
+ }
11892
11529
  const readers = /* @__PURE__ */ new Map();
11893
11530
  for (const { scope, names, repos } of synced.scopes) {
11894
11531
  if (scope.kind !== "organization" || !repos) continue;
@@ -11912,31 +11549,22 @@ async function runDoctorSecrets(input) {
11912
11549
  for (const entry of readers.values()) rows.push(await accessRow(secrets, entry, entry.org === org));
11913
11550
  if (expected.org.length > 0) rows.push(await shadowRow(secrets, expected.org));
11914
11551
  }
11915
- rows.push(...synced.rows, ...deployRows);
11916
- printCheckRows(rows, print);
11917
- const summary = summariseChecks(rows);
11918
- printCheckSummary(summary, print);
11919
- const status = summary.fail > 0 ? "fail" : summary.ok === 0 ? "skip" : "ok";
11920
- logger.info({
11921
- ...summary,
11922
- status
11923
- }, "doctor secrets");
11552
+ rows.push(...synced.rows);
11924
11553
  return {
11925
- status,
11554
+ declared: true,
11926
11555
  rows,
11927
- summary,
11928
- ...status === "skip" ? { reason: rows.map((r) => r.detail).join("; ") } : {}
11556
+ observations
11929
11557
  };
11930
11558
  }
11931
11559
  async function checkScope(secrets, check) {
11932
11560
  const { id, title, scope, names } = check;
11933
- if ("problem" in scope) return {
11561
+ if ("problem" in scope) return { row: {
11934
11562
  id,
11935
11563
  title,
11936
11564
  status: "fail",
11937
11565
  detail: "1 problem(s)",
11938
11566
  problems: [scope.problem]
11939
- };
11567
+ } };
11940
11568
  try {
11941
11569
  const have = await secrets.listSecrets(scope);
11942
11570
  const spelled = new Map(names.map((name) => [name.toUpperCase(), name]));
@@ -11944,57 +11572,740 @@ async function checkScope(secrets, check) {
11944
11572
  noun: "secret",
11945
11573
  flagExtra: false
11946
11574
  });
11947
- return problems.length > 0 ? {
11948
- id,
11949
- title,
11950
- status: "fail",
11951
- detail: `${problems.length} problem(s)`,
11952
- problems
11953
- } : {
11954
- id,
11955
- title,
11956
- status: "ok",
11957
- detail: `${names.length} of ${names.length} exist`,
11958
- problems: []
11575
+ return {
11576
+ row: problems.length > 0 ? {
11577
+ id,
11578
+ title,
11579
+ status: "fail",
11580
+ detail: `${problems.length} problem(s)`,
11581
+ problems
11582
+ } : {
11583
+ id,
11584
+ title,
11585
+ status: "ok",
11586
+ detail: `${names.length} of ${names.length} exist`,
11587
+ problems: []
11588
+ },
11589
+ have
11959
11590
  };
11960
11591
  } catch (err) {
11961
11592
  const noToken = missingTokenReason(err);
11962
- if (noToken !== void 0) return {
11593
+ if (noToken !== void 0) return { row: {
11963
11594
  id,
11964
11595
  title,
11965
11596
  status: "skip",
11966
11597
  detail: noToken,
11967
11598
  problems: []
11968
- };
11969
- return {
11599
+ } };
11600
+ return { row: {
11970
11601
  id,
11971
11602
  title,
11972
11603
  status: "fail",
11973
11604
  detail: errorMessage(err),
11974
11605
  problems: []
11606
+ } };
11607
+ }
11608
+ }
11609
+ // src/commands/doctor-secrets/configured-packages.ts
11610
+ /**
11611
+ * The package of every provider the config names, once each. These are the plugins whose `tokens` export says which
11612
+ * variables a machine needs.
11613
+ *
11614
+ * @param input - The loaded config.
11615
+ */
11616
+ function configuredPackages(input) {
11617
+ const packages = Object.values(input.loaded.resolved.providers).flatMap((entry) => entry.cardinality === "single" ? [entry.tuple.packageName] : entry.tuples.map((t) => t.packageName));
11618
+ return [...new Set(packages)];
11619
+ }
11620
+ // src/commands/doctor-secrets/expected-tokens.ts
11621
+ /**
11622
+ * The `envName` of every token the configured plugins list (their `tokens` export), once each, in plain code-unit order
11623
+ * so the output is the same on every machine. A name any plugin needs is not `optional`, even if another plugin lists
11624
+ * it as optional. A plugin that cannot be loaded lists none.
11625
+ *
11626
+ * @param input - The loaded config and, for a test, the importer that loads a plugin package.
11627
+ */
11628
+ async function expectedTokens(input) {
11629
+ const importer = input.importer ?? defaultImporter;
11630
+ const optionalOnly = /* @__PURE__ */ new Map();
11631
+ for (const pkg of configuredPackages(input)) try {
11632
+ for (const token of (await importer(pkg)).tokens ?? []) optionalOnly.set(token.envName, (optionalOnly.get(token.envName) ?? true) && token.optional === true);
11633
+ } catch {}
11634
+ return [...optionalOnly.keys()].sort().map((name) => ({
11635
+ name,
11636
+ optional: optionalOnly.get(name) === true
11637
+ }));
11638
+ }
11639
+ // src/commands/doctor-secrets/matrix-names.ts
11640
+ const LAYER = /^.+ - (local|dev|ci|prod)$/;
11641
+ /**
11642
+ * The layer an Environment name ends in, or `fallback` for a name that is not a layer's.
11643
+ *
11644
+ * @param environment - The Environment's name.
11645
+ * @param fallback - The layer to use for a literal name.
11646
+ */
11647
+ function layerOf(environment, fallback) {
11648
+ return LAYER.exec(environment)?.[1] ?? fallback;
11649
+ }
11650
+ /**
11651
+ * The short label of an Environment in a column heading: its layer word, else the whole name.
11652
+ *
11653
+ * @param environment - The Environment's name.
11654
+ */
11655
+ function labelOf(environment) {
11656
+ return LAYER.exec(environment)?.[1] ?? environment;
11657
+ }
11658
+ /**
11659
+ * The group a vault provider's columns are listed under: `1Password` for the 1Password provider, else `Vault <name>`,
11660
+ * and plain `Vault` when there is no provider to name.
11661
+ *
11662
+ * @param providerName - The provider's name, when there is one.
11663
+ */
11664
+ function providerGroup(providerName) {
11665
+ if (providerName === void 0) return "Vault";
11666
+ return providerName === "1password" ? "1Password" : `Vault ${providerName}`;
11667
+ }
11668
+ // src/commands/doctor-secrets/credentials-rows.ts
11669
+ /** A row for the provider as a whole, or for one of its variables when `name` is given. */
11670
+ function row$5(provider, status, detail, name) {
11671
+ return name === void 0 ? {
11672
+ id: provider,
11673
+ title: provider,
11674
+ status,
11675
+ detail,
11676
+ problems: []
11677
+ } : {
11678
+ id: `${provider}:${name}`,
11679
+ title: `${provider}: ${name}`,
11680
+ status,
11681
+ detail,
11682
+ problems: []
11683
+ };
11684
+ }
11685
+ /**
11686
+ * Compares the tokens the plugins take with what the credentials providers hold, and returns the rows and the places for
11687
+ * the matrix's `local` and `dev` columns. Never throws for a provider that cannot be read: that is a row.
11688
+ *
11689
+ * @param input - The config, the loader and what to show.
11690
+ */
11691
+ async function credentialsRows(input) {
11692
+ const { loader } = input;
11693
+ const { resolved } = input.loaded;
11694
+ if (!resolved.providers.credentials) return {
11695
+ rows: input.asked ? [row$5("credentials", "skip", "no `credentials` provider is configured")] : [],
11696
+ places: []
11697
+ };
11698
+ const rows = loader.loadFailures().filter((f) => f.key === "credentials").map((f) => row$5(f.provider, "fail", `failed to load: ${errorMessage(f.error)}`));
11699
+ const places = [];
11700
+ if (!loader.has("credentials")) return {
11701
+ rows,
11702
+ places
11703
+ };
11704
+ const expected = await expectedTokens(input);
11705
+ const { tuples } = resolved.providers.credentials;
11706
+ for (const impl of loader.get("credentials")) {
11707
+ const tuple = tuples.find((t) => t.provider === impl.providerName);
11708
+ const explicit = tuple && credentialsEnvironment(tuple, resolved);
11709
+ if (!explicit && !derivesEnvironment(impl.providerName)) {
11710
+ rows.push(row$5(impl.providerName, "skip", "no `environment` option and `credentials.environment` is not set"));
11711
+ continue;
11712
+ }
11713
+ try {
11714
+ const checked = await checkProvider(impl, await resolveEnvironments(impl.providerName, explicit, {
11715
+ repoRoot: input.context.repoRoot,
11716
+ env: { HOLOCRON_ENVIRONMENT: "local" },
11717
+ ...input.gitExec ? { gitExec: input.gitExec } : {}
11718
+ }), expected);
11719
+ rows.push(...checked.rows);
11720
+ places.push(...checked.places);
11721
+ } catch (err) {
11722
+ rows.push(row$5(impl.providerName, "fail", errorMessage(err)));
11723
+ }
11724
+ }
11725
+ return {
11726
+ rows,
11727
+ places: places.filter((p) => input.wants(p.column.env))
11728
+ };
11729
+ }
11730
+ /**
11731
+ * One row per problem and one `ok` row, against the Environments the layer reads. A variable counts as present when any
11732
+ * Environment found holds it (the first found wins, as in the credential store). A required Environment that does not
11733
+ * exist is a failing row of its own, by name, and an unreadable place for the matrix; a missing `- local` is not mentioned.
11734
+ */
11735
+ async function checkProvider(impl, candidates, expected) {
11736
+ const provider = impl.providerName;
11737
+ if (!impl.inspect) return {
11738
+ rows: [row$5(provider, "skip", "cannot list the variables without reading their values")],
11739
+ places: []
11740
+ };
11741
+ if (expected.length === 0) return {
11742
+ rows: [row$5(provider, "skip", "no configured plugin lists the tokens it takes")],
11743
+ places: []
11744
+ };
11745
+ const inspect = impl.inspect.bind(impl);
11746
+ try {
11747
+ const { found, missing } = await tryEnvironments(candidates, inspect);
11748
+ const rows = missing.map((name) => row$5(provider, "fail", `${provider} has no Environment named "${name}"`));
11749
+ const group = providerGroup(provider);
11750
+ const unreadPlaces = missing.map((name) => ({
11751
+ column: {
11752
+ id: `vault:${name}`,
11753
+ group,
11754
+ label: labelOf(name),
11755
+ env: layerFor(name),
11756
+ reportedElsewhere: true,
11757
+ unreadReported: true
11758
+ },
11759
+ kind: "secret",
11760
+ needed: [],
11761
+ unread: `${provider} has no Environment named "${name}"`
11762
+ }));
11763
+ if (found.length === 0) return {
11764
+ rows,
11765
+ places: unreadPlaces
11766
+ };
11767
+ const where = found.map(({ name, result }) => result.environment === name ? `"${name}"` : `"${result.environment}" (the config writes "${name}")`).join(", ");
11768
+ const have = (name) => found.some((f) => f.result.names.includes(name));
11769
+ let present = 0;
11770
+ for (const { name, optional } of expected) if (have(name)) present++;
11771
+ else if (optional) rows.push(row$5(provider, "skip", `optional, not set in ${where}`, name));
11772
+ else rows.push(row$5(provider, "fail", `missing from ${where}`, name));
11773
+ if (present > 0) rows.push(row$5(provider, "ok", `${present} of ${expected.length} tokens present in ${where}`, "tokens"));
11774
+ const names = new Set(expected.map((e) => e.name));
11775
+ const places = [];
11776
+ const missingRequired = expected.filter((e) => !e.optional && !have(e.name)).map((e) => e.name);
11777
+ found.forEach(({ name, result }, index) => {
11778
+ places.push({
11779
+ column: {
11780
+ id: `vault:${name}`,
11781
+ group,
11782
+ label: labelOf(name),
11783
+ env: layerFor(name),
11784
+ reportedElsewhere: true,
11785
+ unreadReported: true
11786
+ },
11787
+ kind: "secret",
11788
+ needed: [...result.names.filter((n) => names.has(n)), ...index === found.length - 1 ? missingRequired : []],
11789
+ present: result.names,
11790
+ reasons: Object.fromEntries(expected.map((e) => [e.name.toUpperCase(), `a token the configured plugins take${e.optional ? " (optional)" : ""}`]))
11791
+ });
11792
+ });
11793
+ return {
11794
+ rows,
11795
+ places: [...places, ...unreadPlaces]
11796
+ };
11797
+ } catch (err) {
11798
+ return {
11799
+ rows: [row$5(provider, "fail", errorMessage(err))],
11800
+ places: []
11801
+ };
11802
+ }
11803
+ }
11804
+ /** The layer a credentials Environment belongs to: `local` for `- local` or a name that is not a layer's, else `dev`. */
11805
+ function layerFor(name) {
11806
+ return layerOf(name, "local") === "dev" ? "dev" : "local";
11807
+ }
11808
+ // src/commands/secrets-sync/deploy-filter/deploy-filter.ts
11809
+ /**
11810
+ * What `repo.secrets.deploy` lets one vault environment send to a deployment or a Worker: every entry naming it adds
11811
+ * its `keys` and `prefix`. `undefined` when no entry names it, which the caller turns into a `ConfigError`; there is
11812
+ * no default that sends everything.
11813
+ *
11814
+ * @param entries - `repo.secrets.deploy`, if the config has it.
11815
+ * @param environmentId - The vault environment being synced.
11816
+ */
11817
+ function deployFilter(entries, environmentId) {
11818
+ const matching = (entries ?? []).filter((entry) => entry.environment === environmentId);
11819
+ if (matching.length === 0) return void 0;
11820
+ return {
11821
+ keys: [...new Set(matching.flatMap((entry) => entry.keys ?? []))],
11822
+ prefixes: [...new Set(matching.flatMap((entry) => entry.prefix ? [entry.prefix] : []))]
11823
+ };
11824
+ }
11825
+ // src/commands/secrets-sync/split-deploy-keys/split-deploy-keys.ts
11826
+ /**
11827
+ * Split a vault environment's key names by what a deployment may receive. A key passes when it is listed or starts
11828
+ * with a prefix (case-sensitive). A listed key the vault does not hold stays in `send`, so the sync reports it as
11829
+ * missing rather than dropping it. Only names go in and out.
11830
+ *
11831
+ * @param vaultKeys - The names the vault environment holds.
11832
+ * @param filter - From `deployFilter()`.
11833
+ */
11834
+ function splitDeployKeys(vaultKeys, filter) {
11835
+ const passes = (key) => filter.keys.includes(key) || filter.prefixes.some((p) => key.startsWith(p));
11836
+ const send = vaultKeys.filter(passes);
11837
+ const filtered = vaultKeys.filter((key) => !passes(key));
11838
+ return {
11839
+ send: [...send, ...filter.keys.filter((key) => !vaultKeys.includes(key))],
11840
+ filtered
11841
+ };
11842
+ }
11843
+ // src/commands/doctor-secrets/deploy-key-rows.ts
11844
+ /**
11845
+ * One row per vault environment `repo.secrets.deploy` names: the key names a deployment or Worker would receive from
11846
+ * a `sync secrets`, and how many the filter keeps back, so a token that should not go out is visible before the
11847
+ * sync. Names only: the values the vault returns are dropped at once. An environment that cannot be listed (no vault,
11848
+ * no token, an error) is a skipped row with the reason, never a failure.
11849
+ *
11850
+ * @param entries - `repo.secrets.deploy`.
11851
+ * @param vault - The `vault` provider, or why there is none.
11852
+ */
11853
+ async function deployKeyRows(entries, vault) {
11854
+ const rows = [];
11855
+ for (const environment of [...new Set(entries.map(resolvedEnvironment))]) {
11856
+ const id = `deploy-${environment}`;
11857
+ const title = `${environment} deployment receives only its keys`;
11858
+ const skip = (detail) => rows.push({
11859
+ id,
11860
+ title,
11861
+ status: "skip",
11862
+ detail,
11863
+ problems: []
11864
+ });
11865
+ const filter = deployFilter(entries, environment);
11866
+ if ("why" in vault) skip(vault.why);
11867
+ else if (!vault.readEnvironment) skip(`vault provider (${vault.providerName}) cannot list an environment's keys`);
11868
+ else try {
11869
+ const names = Object.keys(await vault.readEnvironment(environment)).sort();
11870
+ const { send, filtered } = splitDeployKeys(names, filter);
11871
+ const sends = send.filter((name) => names.includes(name));
11872
+ rows.push({
11873
+ id,
11874
+ title,
11875
+ status: "ok",
11876
+ detail: `sends ${sends.length} of ${names.length}: ${sends.join(", ") || "(none)"}${filtered.length > 0 ? `; keeps back ${filtered.length}: ${filtered.join(", ")}` : ""}`,
11877
+ problems: []
11878
+ });
11879
+ } catch (err) {
11880
+ skip(missingTokenReason(err) ?? `could not read vault environment ${environment}: ${describeError(err)}`);
11881
+ }
11882
+ }
11883
+ return rows;
11884
+ }
11885
+ // src/commands/doctor-secrets/environment-skip-row.ts
11886
+ /** Why `doctor secrets` has nothing to compare for an environment, in one place. `test` has no layer. */
11887
+ const NOT_CHECKED = { test: "has no layer (tests use fakes and read none)" };
11888
+ /**
11889
+ * The skipped row for an environment `doctor secrets` does not compare, naming the environment and the reason.
11890
+ *
11891
+ * @param env - The environment asked for with `--env`.
11892
+ * @returns The row, or `undefined` for every environment but `test`, which have rows of their own.
11893
+ */
11894
+ function environmentSkipRow(env) {
11895
+ const reason = NOT_CHECKED[env];
11896
+ if (reason === void 0) return void 0;
11897
+ return {
11898
+ id: `env-${env}`,
11899
+ title: `${env} environment`,
11900
+ status: "skip",
11901
+ detail: `${env}: ${reason}`,
11902
+ problems: []
11903
+ };
11904
+ }
11905
+ // src/commands/doctor-secrets/matrix-build.ts
11906
+ /** Where a group sits among the columns: the vault first, then GitHub, then the deployments. */
11907
+ function groupRank(group) {
11908
+ if (group === "GitHub") return 1;
11909
+ if (group === "Deploy") return 2;
11910
+ return 0;
11911
+ }
11912
+ /**
11913
+ * What one place says about one name. A place that could not be read is `?` whatever the name. Otherwise the name is
11914
+ * `ok` where it is needed and found, `MISSING` where it is needed and not found, `extra` where it is found and nothing
11915
+ * needs it (unless the config lists it as set by hand, which is never reported), and `n/a` where it is neither.
11916
+ *
11917
+ * @param place - The place.
11918
+ * @param upper - The name, upper-cased: names are compared without regard to case, as GitHub does.
11919
+ * @param manual - The upper-cased names that are set by hand on purpose.
11920
+ */
11921
+ function cellFor(place, upper, manual) {
11922
+ if (place.unread !== void 0) return "?";
11923
+ const needed = place.needed.some((name) => name.toUpperCase() === upper);
11924
+ const found = (place.present ?? []).some((name) => name.toUpperCase() === upper);
11925
+ if (needed) return found ? "ok" : "MISSING";
11926
+ if (found) return manual.has(upper) ? "n/a" : "extra";
11927
+ return "n/a";
11928
+ }
11929
+ function columnsOf(places) {
11930
+ const seen = /* @__PURE__ */ new Map();
11931
+ for (const { column } of places) if (!seen.has(column.id)) seen.set(column.id, column);
11932
+ return [...seen.values()].map((column, index) => ({
11933
+ column,
11934
+ index
11935
+ })).sort((a, b) => groupRank(a.column.group) - groupRank(b.column.group) || a.index - b.index).map(({ column }) => column);
11936
+ }
11937
+ function rowsOf(places, columns, manual) {
11938
+ const names = /* @__PURE__ */ new Map();
11939
+ for (const place of places) for (const name of [...place.needed, ...place.present ?? []]) if (!names.has(name.toUpperCase())) names.set(name.toUpperCase(), name);
11940
+ return [...names].sort(([a], [b]) => a < b ? -1 : 1).map(([upper, name]) => {
11941
+ const cells = {};
11942
+ for (const column of columns) cells[column.id] = cellFor(places.find((p) => p.column.id === column.id), upper, manual);
11943
+ return {
11944
+ name,
11945
+ cells
11975
11946
  };
11947
+ });
11948
+ }
11949
+ /**
11950
+ * Builds the matrix from what is known about each place: one row per name, one column per place, in two blocks so a
11951
+ * visible value is never mistaken for a concealed one. Names only; no value is ever part of it.
11952
+ *
11953
+ * @param places - Every place that was looked at, with the names it holds and the names it should hold.
11954
+ * @param manual - Names set by hand on purpose (`doctor.manualSecrets`), never reported as `extra`.
11955
+ */
11956
+ function buildMatrix(places, manual = []) {
11957
+ const skip = new Set(manual.map((name) => name.toUpperCase()));
11958
+ const secretPlaces = places.filter((p) => p.kind === "secret");
11959
+ const variablePlaces = places.filter((p) => p.kind === "variable");
11960
+ const secret = columnsOf(secretPlaces);
11961
+ const variable = columnsOf(variablePlaces);
11962
+ return {
11963
+ columns: {
11964
+ secret,
11965
+ variable
11966
+ },
11967
+ secrets: rowsOf(secretPlaces, secret, skip),
11968
+ variables: rowsOf(variablePlaces, variable, skip),
11969
+ places
11970
+ };
11971
+ }
11972
+ // src/commands/doctor-secrets/matrix-explain.ts
11973
+ /**
11974
+ * The `--name` lookup: for one name, how each place stands and why, for example `ok, synced to repository secrets by
11975
+ * the third entry` or `extra, found here but no entry feeds it`. Informational only. Names only; no value is read.
11976
+ *
11977
+ * @param matrix - The matrix.
11978
+ * @param name - The name, compared without regard to case.
11979
+ * @param manual - Names set by hand on purpose (`doctor.manualSecrets`).
11980
+ * @returns One line per place that knows the name or could not be read, or one line saying nothing knows it.
11981
+ */
11982
+ function explainName(matrix, name, manual) {
11983
+ const upper = name.toUpperCase();
11984
+ const skip = new Set(manual.map((entry) => entry.toUpperCase()));
11985
+ const lines = [];
11986
+ for (const place of matrix.places) {
11987
+ const where = `${place.column.group} ${place.column.label} (${place.kind}s)`;
11988
+ const cell = cellFor(place, upper, skip);
11989
+ const found = (place.present ?? []).some((entry) => entry.toUpperCase() === upper);
11990
+ if (cell === "n/a" && !(skip.has(upper) && found)) continue;
11991
+ const why = cell === "?" ? `could not read it: ${place.unread}` : cell === "extra" ? "found here, but no entry feeds it" : cell === "n/a" ? "set by hand on purpose (doctor.manualSecrets)" : place.reasons?.[upper] ?? "needed by the config";
11992
+ lines.push(`${where}: ${cell}, ${why}`);
11993
+ }
11994
+ return lines.length > 0 ? lines : [`${name}: no place the config declares or reads holds or needs this name`];
11995
+ }
11996
+ // src/commands/doctor-secrets/matrix-places.ts
11997
+ function vaultGroup(vault) {
11998
+ return providerGroup("why" in vault ? void 0 : vault.providerName);
11999
+ }
12000
+ /** The keys of a vault Environment, by name only, or why they could not be read. */
12001
+ async function readNames(vault, environment) {
12002
+ if ("why" in vault) return vault;
12003
+ if (!vault.readEnvironment) return { why: `vault provider (${vault.providerName}) cannot list an environment's keys` };
12004
+ try {
12005
+ return Object.keys(await vault.readEnvironment(environment));
12006
+ } catch (err) {
12007
+ return { why: missingTokenReason(err) ?? `could not read vault environment ${environment}: ${describeError(err)}` };
12008
+ }
12009
+ }
12010
+ const scopeWords = (scope) => typeof scope === "string" || scope.kind === "repo" ? "repository" : scope.kind === "environment" ? `${scope.name} environment` : `${scope.name} organization`;
12011
+ const ordinal = (n) => `entry ${n}`;
12012
+ function addReason(reasons, name, why) {
12013
+ reasons[name.toUpperCase()] ??= why;
12014
+ }
12015
+ /**
12016
+ * Turns what the checks read into the places of the matrix: the GitHub scopes, the vault Environments the sync and
12017
+ * deploy entries name, and the deployments. Names only; the vault values are dropped as they are read. Each place says
12018
+ * which names it should hold and why, from the config, so the matrix and the `--name` lookup agree with the checks.
12019
+ *
12020
+ * @param input - The observations, the config and the vault.
12021
+ */
12022
+ async function matrixPlaces(input) {
12023
+ const { config, vault, wants } = input;
12024
+ const places = [];
12025
+ const group = vaultGroup(vault);
12026
+ const syncEntries = config.repo?.secrets?.sync ?? [];
12027
+ const deployEntries = config.repo?.secrets?.deploy ?? [];
12028
+ const variableEntries = config.repo?.variables?.sync ?? [];
12029
+ const sentTo = (environment, present) => {
12030
+ const filter = deployFilter(deployEntries, environment);
12031
+ return filter ? splitDeployKeys(present, filter).send : [];
12032
+ };
12033
+ const names = /* @__PURE__ */ new Map();
12034
+ const namesOf = async (environment) => {
12035
+ if (!names.has(environment)) names.set(environment, await readNames(vault, environment));
12036
+ return names.get(environment);
12037
+ };
12038
+ if (wants("ci")) {
12039
+ for (const obs of input.secrets) {
12040
+ const reasons = {};
12041
+ const { scope } = obs;
12042
+ const id = scope.kind === "repo" ? "github:repo" : `github:${scope.kind}:${scope.name}`;
12043
+ const own = scope.kind === "organization" && scope.name === input.org;
12044
+ const column = {
12045
+ id,
12046
+ group: "GitHub",
12047
+ label: scope.kind === "repo" ? "repo" : scope.kind === "environment" ? `env ${scope.name}` : `org${own ? "" : ` ${scope.name}`}`,
12048
+ env: "ci",
12049
+ reportedElsewhere: true
12050
+ };
12051
+ for (const [index, entry] of syncEntries.entries()) {
12052
+ if (JSON.stringify(parseScope(entry.scope ?? "repo")) !== JSON.stringify(scope)) continue;
12053
+ const fed = entry.keys ?? await namesOf(resolvedEnvironment(entry));
12054
+ for (const name of Array.isArray(fed) ? fed : []) addReason(reasons, name, `synced to ${scopeWords(scope)} secrets by ${ordinal(index + 1)} of repo.secrets.sync (from ${resolvedEnvironment(entry)})`);
12055
+ }
12056
+ const present = scope.kind === "organization" && obs.have ? obs.have.filter((name) => obs.needed.some((n) => n.toUpperCase() === name.toUpperCase())) : obs.have;
12057
+ places.push({
12058
+ column,
12059
+ kind: "secret",
12060
+ needed: obs.needed,
12061
+ reasons,
12062
+ ...present ? { present } : {},
12063
+ ...obs.unread !== void 0 ? { unread: obs.unread } : {}
12064
+ });
12065
+ }
12066
+ const variables = config.repo?.variables;
12067
+ for (const scope of ["repo", "org"]) {
12068
+ const seen = input.variables.filter((o) => o.scope === scope);
12069
+ if (seen.length === 0) continue;
12070
+ const reasons = {};
12071
+ const needed = Object.keys(scope === "repo" ? variables?.repo ?? {} : variables?.org ?? {});
12072
+ for (const name of needed) addReason(reasons, name, `declared in repo.variables.${scope}`);
12073
+ for (const [index, entry] of variableEntries.entries()) {
12074
+ if ((entry.scope ?? "repo").startsWith("org=") !== (scope === "org")) continue;
12075
+ for (const name of entry.keys) {
12076
+ needed.push(name);
12077
+ addReason(reasons, name, `synced to ${scope === "repo" ? "repository" : "organization"} variables by ${ordinal(index + 1)} of repo.variables.sync (from ${resolvedEnvironment(entry)})`);
12078
+ }
12079
+ }
12080
+ const unread = seen.find((o) => o.unread !== void 0)?.unread;
12081
+ const have = seen.flatMap((o) => o.have ?? []);
12082
+ places.push({
12083
+ column: {
12084
+ id: `github:${scope}-variables`,
12085
+ group: "GitHub",
12086
+ label: scope === "repo" ? "repo" : "org",
12087
+ env: "ci",
12088
+ reportedElsewhere: true
12089
+ },
12090
+ kind: "variable",
12091
+ needed,
12092
+ reasons,
12093
+ present: scope === "org" ? have.filter((n) => needed.some((m) => m.toUpperCase() === n.toUpperCase())) : have,
12094
+ ...unread !== void 0 ? { unread } : {}
12095
+ });
12096
+ }
12097
+ }
12098
+ const envs = /* @__PURE__ */ new Map();
12099
+ for (const entry of syncEntries) {
12100
+ const environment = resolvedEnvironment(entry);
12101
+ envs.set(`secret:${environment}`, {
12102
+ kind: "secret",
12103
+ env: layerOf(environment, "ci"),
12104
+ environment
12105
+ });
12106
+ }
12107
+ for (const entry of variableEntries) {
12108
+ const environment = resolvedEnvironment(entry);
12109
+ envs.set(`variable:${environment}`, {
12110
+ kind: "variable",
12111
+ env: layerOf(environment, "ci"),
12112
+ environment
12113
+ });
12114
+ }
12115
+ for (const entry of deployEntries) {
12116
+ const environment = resolvedEnvironment(entry);
12117
+ envs.set(`secret:${environment}`, {
12118
+ kind: "secret",
12119
+ env: layerOf(environment, "prod"),
12120
+ environment
12121
+ });
12122
+ }
12123
+ for (const { kind, env, environment } of envs.values()) {
12124
+ if (!wants(env)) continue;
12125
+ const found = await namesOf(environment);
12126
+ const present = Array.isArray(found) ? found : [];
12127
+ const needed = [];
12128
+ const reasons = {};
12129
+ if (kind === "secret") {
12130
+ for (const [index, entry] of syncEntries.entries()) {
12131
+ if (resolvedEnvironment(entry) !== environment) continue;
12132
+ for (const name of entry.keys ?? present) {
12133
+ needed.push(name);
12134
+ addReason(reasons, name, `read by ${ordinal(index + 1)} of repo.secrets.sync, which writes it to ${scopeWords(parseScope(entry.scope ?? "repo"))} secrets`);
12135
+ }
12136
+ }
12137
+ for (const name of sentTo(environment, present)) {
12138
+ needed.push(name);
12139
+ addReason(reasons, name, "sent to a deployment or Worker by repo.secrets.deploy");
12140
+ }
12141
+ } else for (const [index, entry] of variableEntries.entries()) {
12142
+ if (resolvedEnvironment(entry) !== environment) continue;
12143
+ for (const name of entry.keys) {
12144
+ needed.push(name);
12145
+ addReason(reasons, name, `written as a variable by ${ordinal(index + 1)} of repo.variables.sync`);
12146
+ }
12147
+ }
12148
+ places.push({
12149
+ column: {
12150
+ id: `vault:${environment}`,
12151
+ group,
12152
+ label: labelOf(environment),
12153
+ env,
12154
+ unreadReported: true
12155
+ },
12156
+ kind,
12157
+ needed,
12158
+ reasons,
12159
+ ...Array.isArray(found) ? { present } : { unread: found.why }
12160
+ });
12161
+ }
12162
+ if (wants("prod")) for (const environment of new Set(deployEntries.map(resolvedEnvironment))) {
12163
+ const found = await namesOf(environment);
12164
+ const needed = sentTo(environment, Array.isArray(found) ? found : []);
12165
+ const reasons = {};
12166
+ for (const name of needed) addReason(reasons, name, "a key repo.secrets.deploy lets a deployment or Worker receive");
12167
+ places.push({
12168
+ column: {
12169
+ id: `deploy:${environment}`,
12170
+ group: "Deploy",
12171
+ label: labelOf(environment),
12172
+ env: "prod"
12173
+ },
12174
+ kind: "secret",
12175
+ needed,
12176
+ reasons,
12177
+ unread: "the project or Worker is named when you sync (--project-id, --worker), not in the config, so it is not read"
12178
+ });
12179
+ }
12180
+ return places;
12181
+ }
12182
+ // src/commands/doctor-secrets/matrix-render.ts
12183
+ /** What each cell word means. Printed under the matrix every time, one meaning per line. */
12184
+ const MATRIX_LEGEND = [
12185
+ "ok present where it should be",
12186
+ "n/a not needed here",
12187
+ "MISSING needed here, not found",
12188
+ "extra found here, but nothing feeds it",
12189
+ "? could not read this place"
12190
+ ];
12191
+ const heading = (column) => `${column.group} ${column.label}`;
12192
+ function pad$1(text, width) {
12193
+ return text + " ".repeat(Math.max(0, width - text.length));
12194
+ }
12195
+ /** The block as a table: one line per name, one column per place. */
12196
+ function table(name, rows, columns) {
12197
+ const nameWidth = Math.max(name.length, ...rows.map((row) => row.name.length));
12198
+ const widths = columns.map((column) => Math.max(heading(column).length, ...rows.map((row) => row.cells[column.id].length)));
12199
+ const line = (first, cells) => [pad$1(first, nameWidth), ...cells.map((cell, i) => pad$1(cell, widths[i]))].join(" ").trimEnd();
12200
+ return [line(name, columns.map((column) => heading(column))), ...rows.map((row) => line(row.name, columns.map((column) => row.cells[column.id])))];
12201
+ }
12202
+ /** The block turned on its side: one short paragraph per name, for a terminal too narrow for the table. */
12203
+ function stacked(rows, columns) {
12204
+ return rows.flatMap((row) => [row.name, ...columns.map((column) => ` ${heading(column)}: ${row.cells[column.id]}`)]);
12205
+ }
12206
+ function block(title, noun, rows, columns, width) {
12207
+ if (rows.length === 0) return [title, ` (no ${noun} declared or found)`];
12208
+ const wide = table("name", rows, columns);
12209
+ return [title, ...Math.max(...wide.map((l) => l.length)) <= width ? wide : stacked(rows, columns)];
12210
+ }
12211
+ /**
12212
+ * Lays the matrix out as text: a heading and a block for the secrets, the same for the variables, then the legend.
12213
+ * The cells are words, not symbols or colour, so a pipe or a log reads the same. When the table would pass `width`
12214
+ * columns it is turned on its side (one paragraph per name) instead of wrapping mid-row.
12215
+ *
12216
+ * @param matrix - The matrix.
12217
+ * @param width - The terminal's width in columns.
12218
+ * @param only - Show only one block.
12219
+ */
12220
+ function renderMatrix(matrix, width, only) {
12221
+ const out = [];
12222
+ if (only !== "variables") out.push(...block("Secrets", "secrets", matrix.secrets, matrix.columns.secret, width), "");
12223
+ if (only !== "secrets") out.push(...block("Variables", "variables", matrix.variables, matrix.columns.variable, width), "");
12224
+ out.push("Legend", ...MATRIX_LEGEND.map((line) => ` ${line}`));
12225
+ return out;
12226
+ }
12227
+ // src/commands/doctor-secrets/matrix-rows.ts
12228
+ const where = (place) => `${place.column.group} ${place.column.label}`;
12229
+ function namesWith(place, cell, manual) {
12230
+ const names = /* @__PURE__ */ new Map();
12231
+ for (const name of [...place.needed, ...place.present ?? []]) names.set(name.toUpperCase(), name);
12232
+ return [...names].filter(([upper]) => cellFor(place, upper, manual) === cell).map(([, name]) => name).sort();
12233
+ }
12234
+ /**
12235
+ * The rows the matrix adds to `doctor secrets`, from the places it was built from:
12236
+ *
12237
+ * - `extra` names are advisory, one row per place: an `info` row (shown as skipped, exit 0), or a failure with `strict`.
12238
+ * - `MISSING` names fail, one row per place, except in a place another check already reports on (GitHub).
12239
+ * - A place that could not be read is a skipped row that names it and why, again except where another check says so.
12240
+ *
12241
+ * @param matrix - The matrix.
12242
+ * @param manual - Names set by hand on purpose (`doctor.manualSecrets`).
12243
+ * @param strict - Whether an `extra` name is a failure.
12244
+ */
12245
+ function matrixRows(matrix, manual, strict) {
12246
+ const skip = new Set(manual.map((name) => name.toUpperCase()));
12247
+ const rows = [];
12248
+ for (const place of matrix.places) {
12249
+ const id = `${place.kind}:${place.column.id}`;
12250
+ const title = `${where(place)} ${place.kind}s`;
12251
+ if (place.unread !== void 0) {
12252
+ if (!place.column.reportedElsewhere && !place.column.unreadReported) rows.push({
12253
+ id: `unread:${id}`,
12254
+ title,
12255
+ status: "skip",
12256
+ detail: `could not read ${where(place)}: ${place.unread}`,
12257
+ problems: []
12258
+ });
12259
+ continue;
12260
+ }
12261
+ const missing = place.column.reportedElsewhere ? [] : namesWith(place, "MISSING", skip);
12262
+ if (missing.length > 0) rows.push({
12263
+ id: `missing:${id}`,
12264
+ title,
12265
+ status: "fail",
12266
+ detail: `${missing.length} problem(s)`,
12267
+ problems: missing.map((name) => `missing ${place.kind} ${name}`)
12268
+ });
12269
+ const extra = namesWith(place, "extra", skip);
12270
+ if (extra.length > 0) {
12271
+ const what = `${extra.length} extra in ${where(place)}, nothing feeds ${extra.length === 1 ? "it" : "them"}: ${extra.join(", ")}`;
12272
+ rows.push({
12273
+ id: `extra:${id}`,
12274
+ title,
12275
+ status: strict ? "fail" : "skip",
12276
+ detail: strict ? what : `info: ${what}`,
12277
+ problems: []
12278
+ });
12279
+ }
11976
12280
  }
12281
+ return rows;
11977
12282
  }
11978
- // src/commands/doctor-secrets/doctor-secrets.command.ts
11979
- const doctorSecretsCommand = {
11980
- command: "secrets",
11981
- describe: "Check the secrets the config says must exist against the ones the provider holds (read-only, names only)",
11982
- handler: async (argv) => {
11983
- const tokens = tokenContext$1(argv.token);
11984
- if (!tokens) return;
11985
- const loaded = await loadConfig(argv.cwd);
11986
- applyResolvedConfig(argv, loaded.resolved);
11987
- if ((await runDoctorSecrets({
11988
- loaded,
11989
- context: {
11990
- repoRoot: argv.cwd,
11991
- ...tokens,
11992
- org: resolveOrg(argv, loaded.resolved)
11993
- }
11994
- })).status === "fail") process.exitCode = 1;
11995
- }
11996
- };
11997
- // src/commands/doctor-shared-values/compare-layers.ts
12283
+ // src/commands/doctor-secrets/memo-vault.ts
12284
+ /**
12285
+ * A vault that reads each Environment once. `doctor secrets` asks about the same Environment for several rows and for
12286
+ * the matrix; a provider that shells out (1Password) should not be asked again each time. An error is remembered too,
12287
+ * so a refused read is refused once. Only the provider's own methods are used; nothing is written.
12288
+ *
12289
+ * @param vault - The `vault` provider.
12290
+ * @returns A vault that answers `readEnvironment` from memory after the first read of an Environment, or the same vault
12291
+ * when it cannot read one.
12292
+ */
12293
+ function memoVault(vault) {
12294
+ const read = vault.readEnvironment;
12295
+ if (!read) return vault;
12296
+ const seen = /* @__PURE__ */ new Map();
12297
+ const memo = Object.create(vault);
12298
+ memo.readEnvironment = (environmentId) => {
12299
+ let result = seen.get(environmentId);
12300
+ if (!result) {
12301
+ result = read.call(vault, environmentId);
12302
+ seen.set(environmentId, result);
12303
+ }
12304
+ return result;
12305
+ };
12306
+ return memo;
12307
+ }
12308
+ // src/commands/doctor-secrets/compare-layers.ts
11998
12309
  /**
11999
12310
  * Finds, for every pair of layers, the secrets that hold the same value. A value is never compared as text: each is
12000
12311
  * turned into an HMAC under a salt made fresh for this call, so a digest means nothing outside it and is held only in
@@ -12034,7 +12345,7 @@ function compareLayers(layers, allow) {
12034
12345
  }
12035
12346
  return pairs;
12036
12347
  }
12037
- // src/commands/doctor-shared-values/compare-variables.ts
12348
+ // src/commands/doctor-secrets/compare-variables.ts
12038
12349
  /**
12039
12350
  * Compares the variables (the entries a vault holds visible) of `ci` with those of `dev`. The organization's constants
12040
12351
  * live in `ci` and have a copy in `dev`, with no fallback between layers (#2058), so a name `ci` has and `dev` lacks, or
@@ -12066,7 +12377,7 @@ function compareVariables(layers, allow) {
12066
12377
  differs: differs.sort()
12067
12378
  };
12068
12379
  }
12069
- // src/commands/doctor-shared-values/read-layers.ts
12380
+ // src/commands/doctor-secrets/read-layers.ts
12070
12381
  /** An error's text with every value read so far taken out, so a vault's message can never carry one to the output. */
12071
12382
  function scrubbed(err, known) {
12072
12383
  return known.reduce((text, value) => text.split(value).join("[redacted]"), describeError(err));
@@ -12082,12 +12393,12 @@ function scrubbed(err, known) {
12082
12393
  * @param vault - A `vault` provider that can read an environment.
12083
12394
  * @param slug - The `<org>/<repo>` the Environments are named from.
12084
12395
  */
12085
- async function readLayers(vault, slug) {
12086
- const layers = [];
12396
+ async function readLayers(vault, slug, layers = ENVIRONMENT_LAYERS) {
12397
+ const read = [];
12087
12398
  const rows = [];
12088
12399
  const known = [];
12089
12400
  let blind = false;
12090
- for (const layer of ENVIRONMENT_LAYERS) {
12401
+ for (const layer of layers) {
12091
12402
  const environment = layerEnvironment(slug, layer);
12092
12403
  let entries;
12093
12404
  try {
@@ -12113,7 +12424,7 @@ async function readLayers(vault, slug) {
12113
12424
  continue;
12114
12425
  }
12115
12426
  known.push(...entries.map((e) => e.value).filter(Boolean));
12116
- layers.push({
12427
+ read.push({
12117
12428
  layer,
12118
12429
  environment,
12119
12430
  entries
@@ -12127,42 +12438,33 @@ async function readLayers(vault, slug) {
12127
12438
  problems: []
12128
12439
  });
12129
12440
  return {
12130
- layers,
12441
+ layers: read,
12131
12442
  rows
12132
12443
  };
12133
12444
  }
12134
- // src/commands/doctor-shared-values/doctor-shared-values.ts
12135
- /**
12136
- * `holocron doctor shared-values` — does a secret hold the same value in two layers?
12137
- *
12138
- * A leak from CI should not expose what a laptop holds, so the layers (`<org/repo> - local|dev|ci|prod`) keep their
12139
- * own values (#2058, #2059). Read-only: it reads each layer's Environment in memory through the `vault` provider and
12140
- * compares the concealed entries by a salted hash made fresh for the run. It prints names only, one row per pair of
12141
- * layers; no value, hash or length reaches the output, a log or an error. A shared secret is an `info` row (shown as
12142
- * skipped) and the exit stays 0, unless `--strict` makes it a failure. A name in `doctor.sharedVariables` or passed
12143
- * with `--allow` is shared on purpose and left out. A layer that cannot be read is a skipped row; `local` missing is silent.
12144
- */
12445
+ // src/commands/doctor-secrets/shared-rows.ts
12145
12446
  function skipRow(id, title, detail) {
12146
12447
  return {
12147
- id,
12448
+ id: `shared:${id}`,
12148
12449
  title,
12149
12450
  status: "skip",
12150
12451
  detail,
12151
12452
  problems: []
12152
12453
  };
12153
12454
  }
12154
- async function runDoctorSharedValues(input) {
12155
- const print = input.print ?? ((line) => console.log(line));
12156
- const logger = input.logger ?? getLogger();
12157
- const loader = input.loader ?? new PluginLoader(input.loaded.resolved, input.context);
12158
- await loader.load();
12159
- assertPluginsResolvable$1(loader, "doctor shared-values");
12455
+ /**
12456
+ * Compares the secrets of the named layers by a per-run salted hash, in memory.
12457
+ *
12458
+ * @param input - The config, the vault and what to compare.
12459
+ * @returns The rows and the closing line of counts. Never throws for a layer that cannot be read: that is a skipped row.
12460
+ */
12461
+ async function sharedRows(input) {
12160
12462
  const rows = [];
12161
12463
  let compared = 0;
12162
12464
  let shared = 0;
12163
12465
  let drifted = 0;
12164
- const vault = loader.has("vault") ? loader.get("vault") : void 0;
12165
- if (!vault?.readEnvironment && !vault?.readEnvironmentEntries) rows.push(skipRow("vault", "read the layers", vault ? `${vault.providerName} cannot read an environment's variables` : "needs a `vault` provider in holocron.config.ts (1password)"));
12466
+ const { vault } = input;
12467
+ if ("why" in vault || !vault.readEnvironment && !vault.readEnvironmentEntries) rows.push(skipRow("vault", "read the layers", "why" in vault ? vault.why : `${vault.providerName} cannot read an environment's variables`));
12166
12468
  else {
12167
12469
  let slug;
12168
12470
  try {
@@ -12171,16 +12473,16 @@ async function runDoctorSharedValues(input) {
12171
12473
  rows.push(skipRow("slug", "name the layers", describeError(err)));
12172
12474
  }
12173
12475
  if (slug !== void 0) {
12174
- const read = await readLayers(vault, slug);
12476
+ const read = await readLayers(vault, slug, input.layers);
12175
12477
  rows.push(...read.rows);
12176
- const allow = [...input.loaded.resolved.doctor.sharedVariables ?? [], ...input.allow ?? []];
12478
+ const allow = [...input.loaded.resolved.doctor.sharedVariables ?? [], ...input.allow];
12177
12479
  for (const pair of compareLayers(read.layers, allow)) {
12178
12480
  compared++;
12179
12481
  shared += pair.names.length;
12180
12482
  const title = `${pair.layer} = ${pair.other}`;
12181
12483
  if (pair.names.length === 0) {
12182
12484
  rows.push({
12183
- id: `pair:${pair.layer}:${pair.other}`,
12485
+ id: `shared:pair:${pair.layer}:${pair.other}`,
12184
12486
  title,
12185
12487
  status: "ok",
12186
12488
  detail: "no secret shares a value",
@@ -12190,7 +12492,7 @@ async function runDoctorSharedValues(input) {
12190
12492
  }
12191
12493
  const what = `${pair.names.length === 1 ? "1 secret shares a value" : `${pair.names.length} secrets share a value`} between ${pair.other} and ${pair.layer}: ${pair.names.join(", ")}`;
12192
12494
  rows.push({
12193
- id: `pair:${pair.layer}:${pair.other}`,
12495
+ id: `shared:pair:${pair.layer}:${pair.other}`,
12194
12496
  title,
12195
12497
  status: input.strict ? "fail" : "skip",
12196
12498
  detail: input.strict ? what : `info: ${what}`,
@@ -12202,7 +12504,7 @@ async function runDoctorSharedValues(input) {
12202
12504
  if (names.length === 0) continue;
12203
12505
  drifted += names.length;
12204
12506
  rows.push({
12205
- id: `variables:${what.split(" ")[0]}`,
12507
+ id: `shared:variables:${what.split(" ")[0]}`,
12206
12508
  title: `variables ${what}`,
12207
12509
  status: "skip",
12208
12510
  detail: `info: ${names.length} variable${names.length === 1 ? "" : "s"}: ${names.join(", ")}`,
@@ -12212,423 +12514,19 @@ async function runDoctorSharedValues(input) {
12212
12514
  if (read.layers.length < 2) rows.push(skipRow("pairs", "compare the layers", "fewer than two layers could be read, so there is nothing to compare"));
12213
12515
  }
12214
12516
  }
12215
- printCheckRows(rows, print);
12216
- print(`${compared} pair${compared === 1 ? "" : "s"} compared, ${shared} shared name${shared === 1 ? "" : "s"}, ${drifted} variable${drifted === 1 ? "" : "s"} drifting`);
12217
- const summary = summariseChecks(rows);
12218
- printCheckSummary(summary, print);
12219
- const status = summary.fail > 0 ? "fail" : summary.ok === 0 ? "skip" : "ok";
12220
- logger.info({
12221
- ...summary,
12222
- status,
12223
- compared,
12224
- shared
12225
- }, "doctor shared-values");
12226
- return {
12227
- status,
12228
- rows,
12229
- summary,
12230
- ...status === "skip" ? { reason: [...new Set(rows.map((r) => r.detail))].join("; ") } : {}
12231
- };
12232
- }
12233
- // src/commands/doctor-shared-values/doctor-shared-values.command.ts
12234
- const doctorSharedValuesArgs = (y) => y.option("strict", {
12235
- type: "boolean",
12236
- default: false,
12237
- describe: "Fail (exit 1) when a secret holds the same value in two layers, instead of reporting it as info"
12238
- }).option("allow", {
12239
- type: "string",
12240
- array: true,
12241
- describe: "A name shared on purpose; repeat for more. `doctor.sharedVariables` in the config lists them too"
12242
- });
12243
- const doctorSharedValuesCommand = {
12244
- command: "shared-values",
12245
- describe: "Find secrets that hold the same value in two layers: local, dev, ci and prod (read-only, names only)",
12246
- builder: doctorSharedValuesArgs,
12247
- handler: async (argv) => {
12248
- const tokens = tokenContext$1(argv.token);
12249
- if (!tokens) return;
12250
- const loaded = await loadConfig(argv.cwd);
12251
- applyResolvedConfig(argv, loaded.resolved);
12252
- if ((await runDoctorSharedValues({
12253
- loaded,
12254
- context: {
12255
- repoRoot: argv.cwd,
12256
- ...tokens,
12257
- org: resolveOrg(argv, loaded.resolved)
12258
- },
12259
- strict: argv.strict === true,
12260
- allow: argv.allow ?? []
12261
- })).status === "fail") process.exitCode = 1;
12262
- }
12263
- };
12264
- // src/commands/doctor-variable-owners/create-loaders.ts
12265
- /**
12266
- * The loader that lists an Environment's variable names. Built with `readCredentials: false`, so the `credentials`
12267
- * providers are loaded but never asked for a value: only `Credentials.inspect` runs, and no value enters the process.
12268
- *
12269
- * @param loaded - The loaded config.
12270
- * @param context - The runtime context.
12271
- * @param importer - Replaces the plugin import, for a test.
12272
- */
12273
- function createNamesLoader(loaded, context, importer) {
12274
- return new PluginLoader(loaded.resolved, context, importer, { readCredentials: false });
12275
- }
12276
- /**
12277
- * The loader for the `secrets` and `source` providers that list GitHub names. Built normally, so the `credentials`
12278
- * providers are read into the in-process store and the GitHub plugin finds its token in the usual chain. The token is
12279
- * only used to authenticate; the check never prints or keeps it.
12280
- *
12281
- * @param loaded - The loaded config.
12282
- * @param context - The runtime context.
12283
- * @param importer - Replaces the plugin import, for a test.
12284
- */
12285
- function createGitHubLoader(loaded, context, importer) {
12286
- return new PluginLoader(loaded.resolved, context, importer);
12287
- }
12288
- // src/commands/doctor-variable-owners/name-index.ts
12289
- /** Every name across the places, folded to upper case as GitHub does, with the places that hold it. */
12290
- function nameIndex(sources) {
12291
- const index = /* @__PURE__ */ new Map();
12292
- for (const source of sources) for (const name of source.names) {
12293
- const key = name.toUpperCase();
12294
- const held = index.get(key) ?? {
12295
- name,
12296
- places: []
12297
- };
12298
- if (!held.places.includes(source)) held.places.push(source);
12299
- index.set(key, held);
12300
- }
12301
- return index;
12302
- }
12303
- // src/commands/doctor-variable-owners/find-duplicates.ts
12304
- /**
12305
- * The names that live in more than one place, sorted by name. A name is left out when `shared` lists it (deliberate sharing),
12306
- * and a GitHub copy is not counted when an Environment that holds the name fills it through a sync entry (`feeds`):
12307
- * that is the one allowed path. Places of one group count once, so the instances of one App never clash.
12308
- *
12309
- * @param sources - What each place holds.
12310
- * @param feeds - `repo.secrets.sync` and `repo.variables.sync`, as {@link SyncFeed}s.
12311
- * @param shared - `doctor.sharedVariables`.
12312
- */
12313
- function findDuplicates(sources, feeds, shared) {
12314
- const allowed = new Set(shared.map((name) => name.toUpperCase()));
12315
- const found = [];
12316
- for (const [key, holders] of [...nameIndex(sources)].sort(([a], [b]) => a < b ? -1 : 1)) {
12317
- if (allowed.has(key)) continue;
12318
- const filled = (place) => place.feed !== void 0 && feeds.some((feed) => feed.target === place.feed && (feed.keys === void 0 || feed.keys.some((k) => k.toUpperCase() === key)) && holders.places.some((other) => other.environment === feed.environment));
12319
- const places = holders.places.filter((place) => !filled(place));
12320
- if (new Set(places.map((place) => place.group)).size > 1) found.push({
12321
- name: holders.name,
12322
- places
12323
- });
12324
- }
12325
- return found;
12326
- }
12327
- // src/commands/doctor-variable-owners/find-prefixed-pairs.ts
12328
- /** The prefixes a name is renamed to: the organization's, then an application's own. */
12329
- const PAIR_PREFIXES = [
12330
- PREFIX,
12331
- "SENTINEL",
12332
- "COMLINK"
12333
- ];
12334
- /**
12335
- * The bare names (`X`) that exist beside a prefixed one (`HOLOCRON_X`, `SENTINEL_X`, `COMLINK_X`) in any place. The
12336
- * fallback is deliberate during a rename; a pair that outlives it is a leftover. Sorted by the bare name.
12337
- */
12338
- function findPrefixedPairs(sources) {
12339
- const index = nameIndex(sources);
12340
- const pairs = [];
12341
- for (const [key, bare] of [...index].sort(([a], [b]) => a < b ? -1 : 1)) for (const prefix of PAIR_PREFIXES) {
12342
- const prefixed = index.get(`${prefix}_${key}`);
12343
- if (prefixed) pairs.push({
12344
- bare,
12345
- prefixed
12346
- });
12347
- }
12348
- return pairs;
12349
- }
12350
- // src/commands/doctor-variable-owners/github-environments.ts
12351
- /** The GitHub Environments whose secrets are listed: the ones `repo.secrets.environments` and a sync entry name. */
12352
- function githubEnvironments(config, feeds) {
12353
- const prefix = "secrets:env=";
12354
- const fromSync = feeds.filter((f) => f.target.startsWith(prefix)).map((f) => f.target.slice(12));
12355
- return [.../* @__PURE__ */ new Set([...Object.keys(config.repo?.secrets?.environments ?? {}), ...fromSync])];
12356
- }
12357
- // src/commands/doctor-variable-owners/owner-environments.ts
12358
- /**
12359
- * The Environments the config names: each `credentials` provider's, `githubApps[].environment`, `dev.environment`
12360
- * and the one of every `repo.secrets.sync` and `repo.variables.sync` entry.
12361
- */
12362
- function ownerEnvironments(config) {
12363
- const names = /* @__PURE__ */ new Set();
12364
- const entry = config.providers.credentials;
12365
- for (const tuple of entry?.tuples ?? []) {
12366
- const named = credentialsEnvironment(tuple, config);
12367
- if (named !== void 0) names.add(named);
12368
- }
12369
- const instances = new Set((config.githubApps ?? []).map(resolvedEnvironment));
12370
- for (const environment of instances) names.add(environment);
12371
- if (config.dev?.environment) names.add(config.dev.environment);
12372
- for (const sync of [...config.repo?.secrets?.sync ?? [], ...config.repo?.variables?.sync ?? []]) names.add(resolvedEnvironment(sync));
12373
- return {
12374
- names: [...names],
12375
- instances
12376
- };
12377
- }
12378
- // src/commands/doctor-variable-owners/read-environments.ts
12379
- /**
12380
- * Reads the variable names of each Environment through `Credentials.inspect`, which lists names without reading a
12381
- * value. The first provider that can find the Environment answers. An Environment no provider can read is a skipped
12382
- * row naming why, never a failure.
12383
- *
12384
- * @param names - The Environments to read.
12385
- * @param instances - The Environments that are instances of one GitHub App: they share a group.
12386
- * @param providers - The loaded `credentials` providers.
12387
- * @param none - Why there is no provider, used when `providers` is empty.
12388
- */
12389
- async function readEnvironments(names, instances, providers, none) {
12390
- const sources = [];
12391
- const rows = [];
12392
- const skip = (name, detail) => rows.push({
12393
- id: `skip:env:${name}`,
12394
- title: `Environment "${name}"`,
12395
- status: "skip",
12396
- detail,
12397
- problems: []
12398
- });
12399
- for (const name of names) {
12400
- if (providers.length === 0) {
12401
- skip(name, none);
12402
- continue;
12403
- }
12404
- const readers = providers.filter((p) => p.inspect !== void 0);
12405
- if (readers.length === 0) {
12406
- skip(name, "no `credentials` provider can list names without reading values");
12407
- continue;
12408
- }
12409
- let why = "";
12410
- let found = false;
12411
- for (const provider of readers) try {
12412
- const inspection = await provider.inspect(name);
12413
- sources.push({
12414
- label: `Environment "${name}"`,
12415
- group: instances.has(name) ? "app instances" : `env:${name}`,
12416
- names: inspection.names,
12417
- environment: name
12418
- });
12419
- found = true;
12420
- break;
12421
- } catch (err) {
12422
- why = `could not read it with ${provider.providerName}: ${describeError(err)}`;
12423
- }
12424
- if (!found) skip(name, why);
12425
- }
12426
- return {
12427
- sources,
12428
- rows
12429
- };
12430
- }
12431
- // src/commands/doctor-variable-owners/feed-key.ts
12432
- /** The key that says which GitHub place a sync entry fills: `secrets:repo`, `variables:org=acme`, `secrets:env=prod`. */
12433
- function feedKey(kind, scope) {
12434
- if (scope.kind === "repo") return `${kind}:repo`;
12435
- return `${kind}:${scope.kind === "organization" ? "org" : "env"}=${scope.name}`;
12436
- }
12437
- // src/commands/doctor-variable-owners/read-github.ts
12438
- /**
12439
- * Reads the names of the Actions secrets (repository, organization and each Environment) and variables (repository and
12440
- * organization) through the `secrets` and `source` providers. GitHub never returns a secret's value, and the variables'
12441
- * values the provider returns are dropped at once. A place that cannot be read (no provider, the provider cannot
12442
- * list it, no token, an error) is a skipped row with the reason, never a failure.
12443
- */
12444
- async function readGitHub(input) {
12445
- const sources = [];
12446
- const rows = [];
12447
- const skip = (id, label, detail) => rows.push({
12448
- id: `skip:${id}`,
12449
- title: label,
12450
- status: "skip",
12451
- detail,
12452
- problems: []
12453
- });
12454
- const read = async (id, label, feed, list) => {
12455
- try {
12456
- const names = await list();
12457
- if ("skip" in names) skip(id, label, names.skip);
12458
- else sources.push({
12459
- label,
12460
- group: `github:${feed}`,
12461
- names,
12462
- feed
12463
- });
12464
- } catch (err) {
12465
- skip(id, label, missingTokenReason(err) ?? `could not read it: ${describeError(err)}`);
12466
- }
12467
- };
12468
- const secrets = (scope) => async () => "why" in input.secrets ? { skip: input.secrets.why } : input.secrets.listSecrets(scope);
12469
- const noOrg = "no organization: set `org` in the config or run inside a repository";
12470
- const org = input.org;
12471
- await read("repo-secrets", "repository secrets", feedKey("secrets", { kind: "repo" }), secrets({ kind: "repo" }));
12472
- if (org === void 0) {
12473
- skip("org-secrets", "organization secrets", noOrg);
12474
- skip("org-variables", "organization variables", noOrg);
12475
- } else {
12476
- const scope = {
12477
- kind: "organization",
12478
- name: org
12479
- };
12480
- await read("org-secrets", "organization secrets", feedKey("secrets", scope), secrets(scope));
12481
- }
12482
- for (const name of input.environments) {
12483
- const scope = {
12484
- kind: "environment",
12485
- name
12486
- };
12487
- await read(`env-secrets-${name}`, `${name} environment secrets`, feedKey("secrets", scope), secrets(scope));
12488
- }
12489
- const source = input.source;
12490
- await read("repo-variables", "repository variables", feedKey("variables", { kind: "repo" }), async () => {
12491
- if ("why" in source) return { skip: source.why };
12492
- if (!source.listVariables) return { skip: "the `source` provider cannot list variables" };
12493
- return Object.keys(await source.listVariables());
12494
- });
12495
- if (org !== void 0) await read("org-variables", "organization variables", feedKey("variables", {
12496
- kind: "organization",
12497
- name: org
12498
- }), async () => {
12499
- if ("why" in source) return { skip: source.why };
12500
- if (!source.listOrgVariables) return { skip: "the `source` provider cannot list organization variables" };
12501
- return Object.keys(await source.listOrgVariables(org));
12502
- });
12503
- return {
12504
- sources,
12505
- rows
12506
- };
12507
- }
12508
- // src/commands/doctor-variable-owners/sync-feeds.ts
12509
- /**
12510
- * The Environments that fill GitHub places, from `repo.secrets.sync` and `repo.variables.sync`: the one allowed copy of
12511
- * a name. An entry whose scope does not parse is left out (`doctor secrets` reports it).
12512
- */
12513
- function syncFeeds(config) {
12514
- const feeds = [];
12515
- const add = (kind, entries) => {
12516
- for (const entry of entries) try {
12517
- const target = feedKey(kind, parseScope(entry.scope ?? "repo"));
12518
- feeds.push({
12519
- environment: resolvedEnvironment(entry),
12520
- target,
12521
- ...entry.keys ? { keys: entry.keys } : {}
12522
- });
12523
- } catch {}
12524
- };
12525
- add("secrets", config.repo?.secrets?.sync ?? []);
12526
- add("variables", config.repo?.variables?.sync ?? []);
12527
- return feeds;
12528
- }
12529
- // src/commands/doctor-variable-owners/doctor-variable-owners.ts
12530
- /**
12531
- * `holocron doctor variable-owners` — does a variable live in more than one place?
12532
- *
12533
- * Read-only, and names only: no value is printed, logged or kept, and the Environments are listed by a loader that never
12534
- * reads a value. It gathers the variable names of every
12535
- * 1Password Environment the config names (through `Credentials.inspect`) and of the GitHub Actions secrets and variables
12536
- * (through the `secrets` and `source` providers), then reports a name that two places hold, one row per name (`fail`).
12537
- * Not reported: the copy a `repo.secrets.sync` or `repo.variables.sync` entry makes (the one allowed path), a name
12538
- * listed in `doctor.sharedVariables` (deliberate sharing), and the same name in the instances of one GitHub App
12539
- * (`githubApps`). A bare name next to its prefixed spelling (`X` and `HOLOCRON_X`) is an `info` row, shown as skipped,
12540
- * because the fallback is deliberate during a rename. A place that cannot be read is a skip with the reason. The GitHub
12541
- * reads use a second loader that does read the `credentials` providers, only so the GitHub plugin finds its token.
12542
- */
12543
- async function runDoctorVariableOwners(input) {
12544
- const print = input.print ?? ((line) => console.log(line));
12545
- const logger = input.logger ?? getLogger();
12546
- const loader = input.loader ?? createNamesLoader(input.loaded, input.context);
12547
- const githubLoader = input.githubLoader ?? createGitHubLoader(input.loaded, input.context);
12548
- await loader.load();
12549
- assertPluginsResolvable$1(loader, "doctor variable-owners");
12550
- await githubLoader.load();
12551
- const config = input.loaded.resolved;
12552
- const feeds = syncFeeds(config);
12553
- const { names, instances } = ownerEnvironments(config);
12554
- const org = input.context.org ?? (input.context.repo ?? config.repo?.name ?? "").split("/")[0];
12555
- const failedToLoad = loader.loadFailures().filter((f) => f.key === "credentials").map((f) => f.provider);
12556
- const environments = await readEnvironments(names, instances, loader.has("credentials") ? loader.get("credentials") : [], failedToLoad.length > 0 ? `a \`credentials\` provider failed to load (${failedToLoad.join(", ")})` : "no `credentials` provider is configured");
12557
- const github = await readGitHub({
12558
- secrets: githubLoader.has("secrets") ? githubLoader.get("secrets") : { why: whyMissing(githubLoader, "secrets", "no `secrets` provider to read the secret names with") },
12559
- source: githubLoader.has("source") ? githubLoader.get("source") : { why: whyMissing(githubLoader, "source", "no `source` provider to read the variable names with") },
12560
- org: org || void 0,
12561
- environments: githubEnvironments(config, feeds)
12562
- });
12563
- const sources = [...environments.sources, ...github.sources];
12564
- const rows = [...environments.rows, ...github.rows];
12565
- const duplicates = findDuplicates(sources, feeds, config.doctor.sharedVariables ?? []);
12566
- for (const { name, places } of duplicates) rows.push({
12567
- id: `owners:${name}`,
12568
- title: name,
12569
- status: "fail",
12570
- detail: `lives in ${places.length} places`,
12571
- problems: places.map((place) => `held by ${place.label}`)
12572
- });
12573
- for (const { bare, prefixed } of findPrefixedPairs(sources)) rows.push({
12574
- id: `pair:${bare.name}`,
12575
- title: `${bare.name} and ${prefixed.name}`,
12576
- status: "skip",
12577
- detail: `info: both exist (${bare.name} in ${bare.places.map((p) => p.label).join(", ")}; ${prefixed.name} in ${prefixed.places.map((p) => p.label).join(", ")}). Fine during a rename; a leftover after it`,
12578
- problems: []
12579
- });
12580
- if (duplicates.length === 0 && sources.length > 0) {
12581
- const distinct = new Set(sources.flatMap((s) => s.names.map((n) => n.toUpperCase())));
12582
- rows.push({
12583
- id: "owners",
12584
- title: "no variable lives in more than one place",
12585
- status: "ok",
12586
- detail: `${distinct.size} name(s) across ${sources.length} place(s) read`,
12587
- problems: []
12588
- });
12589
- }
12590
- printCheckRows(rows, print);
12591
- const summary = summariseChecks(rows);
12592
- printCheckSummary(summary, print);
12593
- const status = summary.fail > 0 ? "fail" : summary.ok === 0 ? "skip" : "ok";
12594
- logger.info({
12595
- ...summary,
12596
- status
12597
- }, "doctor variable-owners");
12598
12517
  return {
12599
- status,
12600
12518
  rows,
12601
- summary,
12602
- ...status === "skip" ? { reason: [...new Set(rows.map((r) => r.detail))].join("; ") } : {}
12519
+ note: `${compared} pair${compared === 1 ? "" : "s"} compared, ${shared} shared name${shared === 1 ? "" : "s"}, ${drifted} variable${drifted === 1 ? "" : "s"} drifting`
12603
12520
  };
12604
12521
  }
12605
- // src/commands/doctor-variable-owners/doctor-variable-owners.command.ts
12606
- const doctorVariableOwnersCommand = {
12607
- command: "variable-owners",
12608
- describe: "Flag a variable name that lives in more than one place: 1Password Environments and GitHub Actions (read-only, names only)",
12609
- handler: async (argv) => {
12610
- const tokens = tokenContext$1(argv.token);
12611
- if (!tokens) return;
12612
- const loaded = await loadConfig(argv.cwd);
12613
- applyResolvedConfig(argv, loaded.resolved);
12614
- if ((await runDoctorVariableOwners({
12615
- loaded,
12616
- context: {
12617
- repoRoot: argv.cwd,
12618
- ...tokens,
12619
- org: resolveOrg(argv, loaded.resolved)
12620
- }
12621
- })).status === "fail") process.exitCode = 1;
12622
- }
12623
- };
12624
- // src/commands/doctor-variables/sync-checks.ts
12522
+ // src/commands/doctor-secrets/sync-variable-checks.ts
12625
12523
  /** Re-keys what GitHub holds by the spelling the config declares, since GitHub treats names as case-insensitive. */
12626
12524
  function bySpelling$1(declared, have) {
12627
12525
  const spelled = new Map(declared.map((name) => [name.toUpperCase(), name]));
12628
12526
  return new Map(Object.entries(have).map(([name, value]) => [spelled.get(name.toUpperCase()) ?? name, value]));
12629
12527
  }
12630
12528
  /**
12631
- * The checks `repo.variables.sync` adds to `holocron doctor variables`: one per entry, that every key it lists exists
12529
+ * The checks `repo.variables.sync` adds to `holocron doctor secrets`: one per entry, that every key it lists exists
12632
12530
  * at its scope. The values live in the vault, which the doctor does not read, so only names (and, for an organization
12633
12531
  * entry, the visibility it writes) are compared and a value is never shown. A scope that is not `repo` or `org=<name>`
12634
12532
  * is rejected when the config loads, so it is not handled here.
@@ -12641,6 +12539,7 @@ function syncVariableChecks(entries) {
12641
12539
  const org = scope.startsWith("org=") ? scope.slice(4) : void 0;
12642
12540
  return {
12643
12541
  id: `sync-${entry.environment}-${scope}`,
12542
+ scope: org === void 0 ? "repo" : "org",
12644
12543
  title: `${org === void 0 ? "repository" : `${org} organization`} variables from ${entry.environment} exist`,
12645
12544
  async run(source) {
12646
12545
  const checked = entry.keys.length;
@@ -12652,7 +12551,8 @@ function syncVariableChecks(entries) {
12652
12551
  noun: "variable",
12653
12552
  flagExtra: false
12654
12553
  }),
12655
- checked
12554
+ checked,
12555
+ have: [...have.keys()]
12656
12556
  };
12657
12557
  }
12658
12558
  if (!source.listOrgVariables) return { skip: "provider does not implement listOrgVariables" };
@@ -12663,15 +12563,17 @@ function syncVariableChecks(entries) {
12663
12563
  flagExtra: false,
12664
12564
  show: (visibility) => `visibility ${visibility}`
12665
12565
  }),
12666
- checked
12566
+ checked,
12567
+ have: [...have.keys()]
12667
12568
  };
12668
12569
  }
12669
12570
  };
12670
12571
  });
12671
12572
  }
12672
- // src/commands/doctor-variables/doctor-variables.ts
12573
+ // src/commands/doctor-secrets/variable-rows.ts
12673
12574
  /**
12674
- * `holocron doctor variables` — do the Actions variables `repo.variables` declares exist, with those values?
12575
+ * The Actions-variable side of `holocron doctor secrets`: do the variables `repo.variables` declares exist, with those
12576
+ * values?
12675
12577
  *
12676
12578
  * Read-only. One row for the repository's variables and one for the organization's, each only when the config
12677
12579
  * declares that scope, and one per `repo.variables.sync` entry that checks its names exist (the values are in the
@@ -12681,13 +12583,15 @@ function syncVariableChecks(entries) {
12681
12583
  */
12682
12584
  const REPO_TITLE = "repository variables match";
12683
12585
  const ORG_TITLE = "organization variables match";
12684
- async function runDoctorVariables(input) {
12685
- const print = input.print ?? ((line) => console.log(line));
12686
- const logger = input.logger ?? getLogger();
12687
- const loader = input.loader ?? new PluginLoader(input.loaded.resolved, input.context);
12688
- await loader.load();
12689
- assertPluginsResolvable$1(loader, "doctor variables");
12690
- const config = input.loaded.resolved;
12586
+ /**
12587
+ * Runs the variable checks and returns their rows, and what each scope held (names only) so the matrix can show it.
12588
+ *
12589
+ * @param loader - The loaded plugins.
12590
+ * @param config - The resolved config.
12591
+ * @param org - The organization the organization variables live in, when it is known.
12592
+ * @returns Whether the config declares any variable, the rows, and one observation per scope read.
12593
+ */
12594
+ async function variableRows(loader, config, org) {
12691
12595
  const variables = config.repo?.variables;
12692
12596
  const prune = variables?.prune === true;
12693
12597
  const declares = (scope) => scope !== void 0 && (Object.keys(scope).length > 0 || prune);
@@ -12695,76 +12599,96 @@ async function runDoctorVariables(input) {
12695
12599
  if (declares(variables?.repo)) checks.push({
12696
12600
  id: "repo-variables",
12697
12601
  title: REPO_TITLE,
12602
+ scope: "repo",
12698
12603
  async run(source) {
12699
12604
  if (!source.listVariables) return { skip: "provider does not implement listVariables" };
12700
12605
  const declared = variables.repo;
12606
+ const have = await source.listVariables();
12701
12607
  return {
12702
- problems: compareRepo(declared, await source.listVariables(), prune),
12703
- checked: Object.keys(declared).length
12608
+ problems: compareRepo(declared, have, prune),
12609
+ checked: Object.keys(declared).length,
12610
+ have: Object.keys(have)
12704
12611
  };
12705
12612
  }
12706
12613
  });
12707
12614
  if (declares(variables?.org)) checks.push({
12708
12615
  id: "org-variables",
12709
12616
  title: ORG_TITLE,
12617
+ scope: "org",
12710
12618
  async run(source) {
12711
12619
  if (!source.listOrgVariables) return { skip: "provider does not implement listOrgVariables" };
12712
- const org = input.context.org ?? (input.context.repo ?? config.repo?.name ?? "").split("/")[0];
12713
12620
  if (!org) return {
12714
12621
  problems: ["no organization: set `org` in the config or run inside a repository"],
12715
12622
  checked: 0
12716
12623
  };
12717
12624
  const declared = variables.org;
12625
+ const have = await source.listOrgVariables(org);
12718
12626
  return {
12719
- problems: compareOrg(declared, await source.listOrgVariables(org), prune),
12720
- checked: Object.keys(declared).length
12627
+ problems: compareOrg(declared, have, prune),
12628
+ checked: Object.keys(declared).length,
12629
+ have: Object.keys(have)
12721
12630
  };
12722
12631
  }
12723
12632
  });
12724
12633
  checks.push(...syncVariableChecks(variables?.sync));
12725
12634
  const rows = [];
12726
- if (checks.length === 0) rows.push({
12727
- id: "variables",
12728
- title: "variables",
12729
- status: "ok",
12730
- detail: "none declared",
12731
- problems: []
12732
- });
12733
- else if (!loader.has("source")) {
12635
+ const observations = [];
12636
+ if (checks.length === 0) return {
12637
+ declared: false,
12638
+ rows,
12639
+ observations
12640
+ };
12641
+ if (!loader.has("source")) {
12734
12642
  const why = whyMissing(loader, "source", "no `source` provider to read them with");
12735
- for (const check of checks) rows.push(row$3(check, { skip: why }));
12643
+ for (const check of checks) {
12644
+ rows.push(row$4(check, { skip: why }));
12645
+ observations.push({
12646
+ scope: check.scope,
12647
+ unread: why
12648
+ });
12649
+ }
12736
12650
  } else {
12737
12651
  const source = loader.get("source");
12738
12652
  for (const check of checks) try {
12739
- rows.push(row$3(check, await check.run(source)));
12653
+ const result = await check.run(source);
12654
+ rows.push(row$4(check, result));
12655
+ observations.push("skip" in result ? {
12656
+ scope: check.scope,
12657
+ unread: result.skip
12658
+ } : {
12659
+ scope: check.scope,
12660
+ ...result.have ? { have: result.have } : {}
12661
+ });
12740
12662
  } catch (err) {
12741
12663
  const noToken = missingTokenReason(err);
12742
- if (noToken !== void 0) rows.push(row$3(check, { skip: noToken }));
12743
- else rows.push({
12744
- id: check.id,
12745
- title: check.title,
12746
- status: "fail",
12747
- detail: errorMessage(err),
12748
- problems: []
12749
- });
12664
+ if (noToken !== void 0) {
12665
+ rows.push(row$4(check, { skip: noToken }));
12666
+ observations.push({
12667
+ scope: check.scope,
12668
+ unread: noToken
12669
+ });
12670
+ } else {
12671
+ rows.push({
12672
+ id: check.id,
12673
+ title: check.title,
12674
+ status: "fail",
12675
+ detail: errorMessage(err),
12676
+ problems: []
12677
+ });
12678
+ observations.push({
12679
+ scope: check.scope,
12680
+ unread: errorMessage(err)
12681
+ });
12682
+ }
12750
12683
  }
12751
12684
  }
12752
- printCheckRows(rows, print);
12753
- const summary = summariseChecks(rows);
12754
- printCheckSummary(summary, print);
12755
- const status = summary.fail > 0 ? "fail" : summary.ok === 0 ? "skip" : "ok";
12756
- logger.info({
12757
- ...summary,
12758
- status
12759
- }, "doctor variables");
12760
12685
  return {
12761
- status,
12686
+ declared: true,
12762
12687
  rows,
12763
- summary,
12764
- ...status === "skip" ? { reason: rows.map((r) => r.detail).join("; ") } : {}
12688
+ observations
12765
12689
  };
12766
12690
  }
12767
- function row$3(check, result) {
12691
+ function row$4(check, result) {
12768
12692
  const { id, title } = check;
12769
12693
  if ("skip" in result) return {
12770
12694
  id,
@@ -12817,6 +12741,317 @@ function compareOrg(declared, have, prune) {
12817
12741
  show: (v) => `${JSON.stringify(v.value)} (${v.visibility})`
12818
12742
  });
12819
12743
  }
12744
+ const DAY_MS = 864e5;
12745
+ /**
12746
+ * How long a token has left, as `expires in 12 days`, and whether that is inside the warning window.
12747
+ * A time that cannot be read is reported as no expiry rather than guessed at.
12748
+ */
12749
+ function describeExpiry(expiresAt, now) {
12750
+ const left = Date.parse(expiresAt) - now.getTime();
12751
+ if (Number.isNaN(left)) return void 0;
12752
+ const soon = left <= 7 * DAY_MS;
12753
+ const days = Math.floor(left / DAY_MS);
12754
+ if (left <= 0) return {
12755
+ text: "expired",
12756
+ soon
12757
+ };
12758
+ if (days < 1) return {
12759
+ text: "expires in less than a day",
12760
+ soon
12761
+ };
12762
+ return {
12763
+ text: `expires in ${days} ${days === 1 ? "day" : "days"}`,
12764
+ soon
12765
+ };
12766
+ }
12767
+ // src/commands/doctor-secrets/verify-rows.ts
12768
+ /**
12769
+ * The `--verify` side of `holocron doctor secrets`: is each token a configured plugin takes set, and still accepted?
12770
+ *
12771
+ * Read-only, and the only part of the command that calls a vendor. For every token a configured plugin lists (its
12772
+ * `tokens` export), the token is looked up the way the plugin does it (the process environment, then the repo's `.env`
12773
+ * and the `credentials` providers, then the OS keyring) and the plugin's `verifyToken` is asked whether it is still
12774
+ * accepted. Each row says where the token came from. A token is never printed. One that is not set is a skip, not a
12775
+ * failure: whether it is needed depends on what is run. One that is set and rejected (expired, revoked, malformed) fails,
12776
+ * and so does one that the plugin reports will expire within `TOKEN_EXPIRY_WARN_DAYS` days (a warning is a fail: the
12777
+ * check has no third status). A token with no expiry shows nothing extra.
12778
+ *
12779
+ * What a token may do is not checked: GitHub does not return a fine-grained token's permissions.
12780
+ */
12781
+ function row$3(id, status, detail) {
12782
+ return {
12783
+ id: `verify:${id}`,
12784
+ title: `verify ${id}`,
12785
+ status,
12786
+ detail,
12787
+ problems: []
12788
+ };
12789
+ }
12790
+ /**
12791
+ * Asks each configured plugin's vendor whether its token is still accepted.
12792
+ *
12793
+ * @param input - The config, the loader that fills the credential store, and (for a test) the importer, environment,
12794
+ * keyring and clock.
12795
+ * @returns One row per token, plus a row for a credentials provider that could not be read.
12796
+ */
12797
+ async function verifyRows(input) {
12798
+ const importer = input.importer ?? defaultImporter;
12799
+ const env = createEnvLookup(input.env);
12800
+ const readToken = input.keyring ?? keyring.get;
12801
+ const now = input.now ?? (() => /* @__PURE__ */ new Date());
12802
+ const rows = [];
12803
+ rows.push(...await loadCredentials(input));
12804
+ for (const pkg of configuredPackages(input)) {
12805
+ let module;
12806
+ try {
12807
+ module = await importer(pkg);
12808
+ } catch (err) {
12809
+ rows.push(row$3(pkg, "skip", `cannot load the plugin: ${errorMessage(err)}`));
12810
+ continue;
12811
+ }
12812
+ for (const token of module.tokens ?? []) rows.push(await checkToken(token, module, env, readToken, now()));
12813
+ }
12814
+ if (rows.length === 0) rows.push(row$3("tokens", "skip", "no configured plugin lists the tokens it takes"));
12815
+ return rows;
12816
+ }
12817
+ /**
12818
+ * Runs the step every command runs first: the repo's `.env` and the config's `credentials` providers are read into the
12819
+ * credential store, which is where `checkToken` and the plugins look after the process environment. A provider that
12820
+ * could not be read is a failing row (its tokens then fall through to the keyring, which is not what was meant), and a
12821
+ * loader that throws is a skip.
12822
+ */
12823
+ async function loadCredentials(input) {
12824
+ try {
12825
+ await input.loader.load();
12826
+ } catch (err) {
12827
+ return [row$3("credentials", "skip", `could not load the credentials providers: ${errorMessage(err)}`)];
12828
+ }
12829
+ return input.loader.loadFailures().filter((failure) => failure.key === "credentials").map((failure) => row$3(`credentials ${failure.provider}`, "fail", `could not be read: ${errorMessage(failure.error)}`));
12830
+ }
12831
+ async function checkToken(token, module, env, readToken, now) {
12832
+ const { keyringKey, envName, vendorEnvName } = token;
12833
+ const fromEnv = env.get(envName) ? envName : vendorEnvName && env.get(vendorEnvName) ? vendorEnvName : void 0;
12834
+ const stored = fromEnv ? void 0 : findCredential(...vendorEnvName ? [envName, vendorEnvName] : [envName]);
12835
+ const value = fromEnv ? env.get(fromEnv) : stored?.value ?? readToken(keyringKey);
12836
+ if (!value) return row$3(keyringKey, "skip", `not set (${vendorEnvName ? `${envName} / ${vendorEnvName}` : envName}, or \`holocron new token ${keyringKey}\`)`);
12837
+ const verify = token.verify ?? (token.verifiable === false ? void 0 : module.verifyToken);
12838
+ if (!verify) return row$3(keyringKey, "skip", "set, but its plugin cannot verify it");
12839
+ const from = fromEnv ?? stored?.source ?? "keyring";
12840
+ try {
12841
+ const verified = await verify(value);
12842
+ if (!verified.ok) return row$3(keyringKey, "fail", `rejected (${from}): ${verified.message}`);
12843
+ const expiry = verified.expiresAt ? describeExpiry(verified.expiresAt, now) : void 0;
12844
+ if (!expiry) return row$3(keyringKey, "ok", `${verified.subject} (${from})`);
12845
+ return expiry.soon ? {
12846
+ ...row$3(keyringKey, "fail", `${verified.subject} (${from}), ${expiry.text}`),
12847
+ problems: [`${expiry.text}: renew it`]
12848
+ } : row$3(keyringKey, "ok", `${verified.subject} (${from}), ${expiry.text}`);
12849
+ } catch (err) {
12850
+ return row$3(keyringKey, "fail", `could not be verified (${from}): ${errorMessage(err)}`);
12851
+ }
12852
+ }
12853
+ // src/commands/doctor-secrets/doctor-secrets.ts
12854
+ /**
12855
+ * `holocron doctor secrets` — do the secrets the config says must exist, exist?
12856
+ *
12857
+ * Read-only, names only: GitHub never returns a value. One row for the repository's secrets, one for the
12858
+ * organization's and one per environment, each only when the config expects something there (see
12859
+ * {@link expectedSecrets}). A secret that exists but is not expected is never a problem. A scope that cannot be
12860
+ * read because there is no provider, or no token for it, is a skip with the reason, not a failure.
12861
+ *
12862
+ * `input.environments` (`--env`) limits the run: `ci` is the GitHub side (`repo.secrets.sync` and the declared
12863
+ * names), `prod` the `repo.secrets.deploy` destinations; `local`, `dev` and `test` are skipped rows that say why.
12864
+ */
12865
+ async function runDoctorSecrets(input) {
12866
+ const print = input.print ?? ((line) => console.log(line));
12867
+ const logger = input.logger ?? getLogger();
12868
+ const only = input.environments;
12869
+ const wants = (env) => only === void 0 || only.includes(env);
12870
+ const skipRow = (env) => {
12871
+ const row = only?.includes(env) ? environmentSkipRow(env) : void 0;
12872
+ return row ? [row] : [];
12873
+ };
12874
+ const rows = [];
12875
+ const places = [];
12876
+ const config = input.loaded.resolved;
12877
+ const manual = config.doctor.manualSecrets ?? [];
12878
+ const withSecrets = input.only !== "variables";
12879
+ const withVariables = input.only !== "secrets";
12880
+ let ran = false;
12881
+ const notes = [];
12882
+ const vaultOf = (loader) => loader.has("vault") ? loader.get("vault") : { why: whyMissing(loader, "vault", "no `vault` provider to list the environment's keys with") };
12883
+ let loading;
12884
+ const getLoader = () => loading ??= (async () => {
12885
+ const loader = input.loader ?? new PluginLoader(config, input.context);
12886
+ await loader.load();
12887
+ assertPluginsResolvable$1(loader, "doctor secrets");
12888
+ return loader;
12889
+ })();
12890
+ if ((wants("local") || wants("dev")) && withSecrets) {
12891
+ ran = true;
12892
+ const credentialsLoader = input.credentialsLoader ?? new PluginLoader(config, input.context, void 0, { readCredentials: false });
12893
+ await credentialsLoader.load();
12894
+ assertPluginsResolvable$1(credentialsLoader, "doctor secrets");
12895
+ const credentials = await credentialsRows({
12896
+ loaded: input.loaded,
12897
+ context: input.context,
12898
+ loader: credentialsLoader,
12899
+ ...input.importer ? { importer: input.importer } : {},
12900
+ ...input.gitExec ? { gitExec: input.gitExec } : {},
12901
+ wants,
12902
+ asked: only !== void 0
12903
+ });
12904
+ rows.push(...credentials.rows);
12905
+ places.push(...credentials.places);
12906
+ }
12907
+ if (wants("ci") || wants("prod")) {
12908
+ ran = true;
12909
+ const loader = await getLoader();
12910
+ const provider = vaultOf(loader);
12911
+ const vault = "why" in provider ? provider : memoVault(provider);
12912
+ const org = input.context.org ?? (input.context.repo ?? config.repo?.name ?? "").split("/")[0];
12913
+ const none = {
12914
+ declared: false,
12915
+ rows: [],
12916
+ observations: []
12917
+ };
12918
+ const ci = wants("ci") && withSecrets ? await ciRows(loader, config, vault, org) : none;
12919
+ const variables = wants("ci") && withVariables ? await variableRows(loader, config, org) : none;
12920
+ const deployRows = wants("prod") && withSecrets ? await deployKeyRows(config.repo?.secrets?.deploy ?? [], vault) : [];
12921
+ if (!ci.declared && !variables.declared && deployRows.length === 0) rows.push({
12922
+ id: "secrets",
12923
+ title: "secrets",
12924
+ status: "ok",
12925
+ detail: "none declared",
12926
+ problems: []
12927
+ });
12928
+ rows.push(...ci.rows, ...variables.rows, ...skipRow("test"), ...deployRows);
12929
+ places.push(...await matrixPlaces({
12930
+ config,
12931
+ vault,
12932
+ secrets: ci.observations,
12933
+ variables: variables.observations,
12934
+ org,
12935
+ wants
12936
+ }));
12937
+ } else rows.push(...skipRow("test"));
12938
+ if (input.verify) {
12939
+ ran = true;
12940
+ try {
12941
+ const loader = await getLoader();
12942
+ rows.push(...await verifyRows({
12943
+ loaded: input.loaded,
12944
+ loader: {
12945
+ load: async () => void 0,
12946
+ loadFailures: () => loader.loadFailures()
12947
+ },
12948
+ ...input.importer ? { importer: input.importer } : {},
12949
+ ...input.processEnv ? { env: input.processEnv } : {},
12950
+ ...input.keyring ? { keyring: input.keyring } : {},
12951
+ ...input.now ? { now: input.now } : {}
12952
+ }));
12953
+ } catch (err) {
12954
+ if (err instanceof WorkspaceContextError) throw err;
12955
+ rows.push({
12956
+ id: "verify:credentials",
12957
+ title: "verify credentials",
12958
+ status: "skip",
12959
+ detail: `could not load the credentials providers: ${errorMessage(err)}`,
12960
+ problems: []
12961
+ });
12962
+ }
12963
+ }
12964
+ if (input.shared) {
12965
+ ran = true;
12966
+ const layers = ENVIRONMENT_LAYERS.filter((layer) => wants(layer));
12967
+ if (layers.length < 2) rows.push({
12968
+ id: "shared:layers",
12969
+ title: "compare the layers",
12970
+ status: "skip",
12971
+ detail: "--shared needs two or more of local, dev, ci and prod in --env",
12972
+ problems: []
12973
+ });
12974
+ else {
12975
+ const shared = await sharedRows({
12976
+ loaded: input.loaded,
12977
+ context: input.context,
12978
+ vault: vaultOf(await getLoader()),
12979
+ ...input.gitExec ? { gitExec: input.gitExec } : {},
12980
+ layers,
12981
+ strict: input.strict === true,
12982
+ allow: input.allow ?? []
12983
+ });
12984
+ rows.push(...shared.rows);
12985
+ notes.push(shared.note);
12986
+ }
12987
+ }
12988
+ let matrix;
12989
+ if (ran) {
12990
+ matrix = buildMatrix(places.filter((place) => input.only === void 0 || place.kind === (input.only === "secrets" ? "secret" : "variable")), manual);
12991
+ if (input.name === void 0) rows.push(...matrixRows(matrix, manual, input.strict === true));
12992
+ }
12993
+ if (input.name !== void 0) {
12994
+ for (const line of matrix ? explainName(matrix, input.name, manual) : [`${input.name}: no environment was read`]) print(line);
12995
+ return {
12996
+ status: "ok",
12997
+ rows: [],
12998
+ summary: {
12999
+ ok: 0,
13000
+ fail: 0,
13001
+ skip: 0
13002
+ }
13003
+ };
13004
+ }
13005
+ if (matrix && matrix.places.length > 0) {
13006
+ const width = input.width ?? process.stdout.columns ?? 100;
13007
+ for (const line of renderMatrix(matrix, width, input.only)) print(line);
13008
+ print("");
13009
+ }
13010
+ printCheckRows(rows, print);
13011
+ for (const note of notes) print(note);
13012
+ const summary = summariseChecks(rows);
13013
+ printCheckSummary(summary, print);
13014
+ const status = summary.fail > 0 ? "fail" : summary.ok === 0 ? "skip" : "ok";
13015
+ logger.info({
13016
+ ...summary,
13017
+ status
13018
+ }, "doctor secrets");
13019
+ return {
13020
+ status,
13021
+ rows,
13022
+ summary,
13023
+ ...status === "skip" ? { reason: rows.map((r) => r.detail).join("; ") } : {}
13024
+ };
13025
+ }
13026
+ // src/commands/doctor-secrets/parse-env-list.ts
13027
+ /** The environments `--env` accepts, in the order they are checked and listed. */
13028
+ const DOCTOR_ENVIRONMENTS = [
13029
+ "local",
13030
+ "dev",
13031
+ "ci",
13032
+ "test",
13033
+ "prod"
13034
+ ];
13035
+ /**
13036
+ * Turns the `--env` values into the environments to check. Each value may itself be a comma-separated list, so
13037
+ * `--env local,dev` and `--env local --env dev` mean the same. Duplicates are collapsed, spaces around a name are
13038
+ * ignored, and the result is in {@link DOCTOR_ENVIRONMENTS} order whatever order was typed.
13039
+ *
13040
+ * @param values - The raw `--env` values, or `undefined` when the flag was not given.
13041
+ * @returns The environments named, or `undefined` for none given (run every environment the config declares).
13042
+ * @throws {ConfigError} For a name that is not one of {@link DOCTOR_ENVIRONMENTS}, or an empty name; the message lists the allowed ones.
13043
+ */
13044
+ function parseEnvList(values) {
13045
+ if (!values || values.length === 0) return void 0;
13046
+ const names = values.flatMap((value) => value.split(",").map((name) => name.trim()));
13047
+ const allowed = DOCTOR_ENVIRONMENTS.join(", ");
13048
+ const unknown = [...new Set(names.filter((name) => !DOCTOR_ENVIRONMENTS.includes(name)))];
13049
+ if (unknown.length > 0) {
13050
+ const shown = unknown.map((name) => name === "" ? "(empty)" : JSON.stringify(name)).join(", ");
13051
+ throw new ConfigError(`--env does not know ${shown}: use ${allowed}, comma-separated or repeated`);
13052
+ }
13053
+ return DOCTOR_ENVIRONMENTS.filter((env) => names.includes(env));
13054
+ }
12820
13055
  // src/commands/deep-checks/deep-checks.ts
12821
13056
  /**
12822
13057
  * Every `doctor <capability>` deep check, in the order `doctor --all` runs them. Adding one is an entry here
@@ -12906,91 +13141,68 @@ const DEEP_CHECKS = [
12906
13141
  {
12907
13142
  name: "secrets",
12908
13143
  capability: "secrets",
12909
- command: doctorSecretsCommand,
12910
- async run(input) {
12911
- const report = await runDoctorSecrets(input);
12912
- return {
12913
- status: report.status,
12914
- summary: report.summary,
12915
- ...report.reason ? { reason: report.reason } : {}
12916
- };
12917
- }
12918
- },
12919
- {
12920
- name: "credentials",
12921
- capability: "credentials",
12922
- command: doctorCredentialsCommand,
12923
- async run(input) {
12924
- const report = await runDoctorCredentials(input);
12925
- return {
12926
- status: report.status,
12927
- summary: report.summary,
12928
- ...report.reason ? { reason: report.reason } : {}
12929
- };
12930
- }
12931
- },
12932
- {
12933
- name: "tokens",
12934
- capability: "source",
12935
- command: doctorTokensCommand,
12936
- async run(input) {
12937
- const report = await runDoctorTokens(input);
12938
- return {
12939
- status: report.status,
12940
- summary: report.summary,
12941
- ...report.reason ? { reason: report.reason } : {}
12942
- };
12943
- }
12944
- },
12945
- {
12946
- name: "variables",
12947
- capability: "source",
12948
13144
  command: {
12949
- command: "variables",
12950
- describe: "Check the Actions variables the config declares against the ones the provider holds (read-only)",
13145
+ command: "secrets",
13146
+ describe: "Check the secrets the config says must exist against the ones the provider holds (read-only, names only)",
13147
+ builder: (y) => y.option("env", {
13148
+ type: "string",
13149
+ array: true,
13150
+ describe: "Environments to check: local, dev, ci, test, prod; comma-separated or repeated. Default: every environment the config declares"
13151
+ }).option("only-secrets", {
13152
+ type: "boolean",
13153
+ conflicts: "only-variables",
13154
+ describe: "Show only the secrets block"
13155
+ }).option("only-variables", {
13156
+ type: "boolean",
13157
+ conflicts: "only-secrets",
13158
+ describe: "Show only the variables block"
13159
+ }).option("verify", {
13160
+ type: "boolean",
13161
+ default: false,
13162
+ describe: "Also ask each vendor whether the tokens the plugins take are still accepted (goes online)"
13163
+ }).option("shared", {
13164
+ type: "boolean",
13165
+ default: false,
13166
+ describe: "Compare the layers named by --env (two or more) for a secret that holds the same value in two of them. Values are hashed in memory and never printed"
13167
+ }).option("allow", {
13168
+ type: "string",
13169
+ array: true,
13170
+ describe: "A name shared on purpose with --shared; repeat for more. `doctor.sharedVariables` in the config lists them too"
13171
+ }).option("strict", {
13172
+ type: "boolean",
13173
+ default: false,
13174
+ describe: "Fail (exit 1) when a place holds a name nothing feeds, or with --shared a secret two layers share, instead of reporting it as info"
13175
+ }).option("name", {
13176
+ type: "string",
13177
+ describe: "Print how each place stands for this one name, and why. Informational: exit 0"
13178
+ }),
12951
13179
  handler: async (argv) => {
13180
+ const environments = parseEnvList(argv.env);
12952
13181
  const tokens = tokenContext$1(argv.token);
12953
13182
  if (!tokens) return;
12954
13183
  const loaded = await loadConfig(argv.cwd);
12955
13184
  applyResolvedConfig(argv, loaded.resolved);
12956
- if ((await runDoctorVariables({
13185
+ if ((await runDoctorSecrets({
12957
13186
  loaded,
12958
13187
  context: {
12959
13188
  repoRoot: argv.cwd,
12960
13189
  ...tokens,
12961
13190
  org: resolveOrg(argv, loaded.resolved)
12962
- }
13191
+ },
13192
+ ...environments ? { environments } : {},
13193
+ ...argv.onlySecrets ? { only: "secrets" } : argv.onlyVariables ? { only: "variables" } : {},
13194
+ strict: argv.strict === true,
13195
+ ...argv.verify ? { verify: true } : {},
13196
+ ...argv.shared ? {
13197
+ shared: true,
13198
+ allow: argv.allow ?? []
13199
+ } : {},
13200
+ ...argv.name ? { name: argv.name } : {}
12963
13201
  })).status === "fail") process.exitCode = 1;
12964
13202
  }
12965
13203
  },
12966
13204
  async run(input) {
12967
- const report = await runDoctorVariables(input);
12968
- return {
12969
- status: report.status,
12970
- summary: report.summary,
12971
- ...report.reason ? { reason: report.reason } : {}
12972
- };
12973
- }
12974
- },
12975
- {
12976
- name: "variable-owners",
12977
- capability: "credentials",
12978
- command: doctorVariableOwnersCommand,
12979
- async run(input) {
12980
- const report = await runDoctorVariableOwners(input);
12981
- return {
12982
- status: report.status,
12983
- summary: report.summary,
12984
- ...report.reason ? { reason: report.reason } : {}
12985
- };
12986
- }
12987
- },
12988
- {
12989
- name: "shared-values",
12990
- capability: "vault",
12991
- command: doctorSharedValuesCommand,
12992
- async run(input) {
12993
- const report = await runDoctorSharedValues(input);
13205
+ const report = await runDoctorSecrets(input);
12994
13206
  return {
12995
13207
  status: report.status,
12996
13208
  summary: report.summary,
@@ -13431,7 +13643,7 @@ function resolveCredentialsFile(base, file, makeDir = (dir) => void mkdirSync(di
13431
13643
  * `holocron export tokens` — print the tokens a configured plugin takes as `NAME=value` lines, to move them into a
13432
13644
  * credentials environment (`op` cannot write to a 1Password Environment, so the last step is the app's import).
13433
13645
  *
13434
- * The names come from the plugins' `tokens` (the list `doctor tokens` and `doctor credentials` use) and each value from
13646
+ * The names come from the plugins' `tokens` (the list `doctor secrets --verify` and `doctor secrets --verify` use) and each value from
13435
13647
  * the OS keyring, or, with `--from-env`, from the environment first. Nothing but the lines ever carries a value: the
13436
13648
  * names, counts and what was not found go to stderr and the log gets counts only.
13437
13649
  *
@@ -19799,6 +20011,27 @@ const probeArgs = (y) => y.positional("provider", {
19799
20011
  default: false,
19800
20012
  describe: "Run a probe that changes things without asking first (required without a terminal)"
19801
20013
  }).epilogue(TOKEN_PROBE_HELP);
20014
+ // src/commands/owner-environments/owner-environments.ts
20015
+ /**
20016
+ * The Environments the config names: each `credentials` provider's, `githubApps[].environment`, `dev.environment`
20017
+ * and the one of every `repo.secrets.sync` and `repo.variables.sync` entry.
20018
+ */
20019
+ function ownerEnvironments(config) {
20020
+ const names = /* @__PURE__ */ new Set();
20021
+ const entry = config.providers.credentials;
20022
+ for (const tuple of entry?.tuples ?? []) {
20023
+ const named = credentialsEnvironment(tuple, config);
20024
+ if (named !== void 0) names.add(named);
20025
+ }
20026
+ const instances = new Set((config.githubApps ?? []).map(resolvedEnvironment));
20027
+ for (const environment of instances) names.add(environment);
20028
+ if (config.dev?.environment) names.add(config.dev.environment);
20029
+ for (const sync of [...config.repo?.secrets?.sync ?? [], ...config.repo?.variables?.sync ?? []]) names.add(resolvedEnvironment(sync));
20030
+ return {
20031
+ names: [...names],
20032
+ instances
20033
+ };
20034
+ }
19802
20035
  // src/commands/probe/app-vault.ts
19803
20036
  /**
19804
20037
  * The vault of an app that carries its own `holocron.config` (`apps/comlink`, `apps/sentinel`): those configs govern where
@@ -19900,7 +20133,7 @@ function comlinkProbes(deps) {
19900
20133
  const workers = deps.loader.has("workers") ? deps.loader.get("workers") : void 0;
19901
20134
  if (!workers?.secretNames) throw new Error("the `workers` provider cannot list a Worker's secrets");
19902
20135
  const have = new Set(await workers.secretNames(script));
19903
- const need = [[relayWebhookBinding(source), "run `holocron setup notifications`"], [relaySecretBinding(source), "add it to the vault and run `holocron sync secrets`, or `setup notifications`"]];
20136
+ const need = [[relayWebhookBinding(source), "run `holocron setup notifications`"], [relaySecretBinding(source), "add it to the vault and run `holocron sync secrets --env prod`, or `setup notifications`"]];
19904
20137
  for (const [name, fix] of need) probe.say(have.has(name) ? {
19905
20138
  status: "ok",
19906
20139
  label: name,
@@ -21509,12 +21742,12 @@ function defaultProviderTokens(loaded, importer = createDefaultImporter(dirname(
21509
21742
  }
21510
21743
  // src/commands/secrets-sync/resolve-environment-id/resolve-environment-id.ts
21511
21744
  /**
21512
- * The vault Environment `holocron sync secrets <environmentId>` reads. A layer word (`local`, `dev`, `ci`, `prod`) is the
21745
+ * The vault Environment `holocron sync secrets --env <environment>` reads. A layer word (`local`, `dev`, `ci`, `prod`) is the
21513
21746
  * Environment of that layer of this repository, `<org/repo> - <layer>`; any other text is a literal Environment name.
21514
21747
  * A literal name wins only when it is not exactly a layer word, so an Environment that is itself called `prod` cannot be
21515
21748
  * addressed by that name (spec `tech-environment-layers`, #2069).
21516
21749
  *
21517
- * @param id - The positional the user gave.
21750
+ * @param id - The `--env` value the user gave.
21518
21751
  * @param input - Where the repository is (its `origin` remote is read there), and optionally how to read it.
21519
21752
  * @throws {ConfigError} For a layer word when the remote cannot be read (the message names the `environment` option).
21520
21753
  */
@@ -24906,9 +25139,10 @@ function variableRoutes(entries, environmentId) {
24906
25139
  });
24907
25140
  }
24908
25141
  // src/commands/secrets-sync/secrets-sync.args.ts
24909
- const secretsSyncArgs = (y) => y.positional("environmentId", {
25142
+ const secretsSyncArgs = (y) => y.option("env", {
24910
25143
  type: "string",
24911
- describe: "Vault environment to read: a layer (local, dev, ci, prod) of this repository, or an Environment name"
25144
+ demandOption: true,
25145
+ describe: "Vault environment to read, one value: a layer (ci, prod) of this repository, or an Environment name. `local` and `dev` are never synced"
24912
25146
  }).option("project-id", {
24913
25147
  type: "string",
24914
25148
  describe: "Deployment project id (e.g., Vercel prj_*). Required when deployment is loaded."
@@ -24928,14 +25162,14 @@ const secretsSyncArgs = (y) => y.positional("environmentId", {
24928
25162
  });
24929
25163
  // src/commands/secrets-sync/secrets-sync.command.ts
24930
25164
  const secretsSyncCommand = {
24931
- command: "secrets [environmentId]",
25165
+ command: "secrets",
24932
25166
  describe: "Read a vault environment + fan KEY=VALUEs out to secrets + deployment env vars",
24933
25167
  builder: secretsSyncArgs,
24934
25168
  handler: async (argv) => {
24935
25169
  const tokens = tokenContext$1(argv.token);
24936
25170
  if (!tokens) return;
24937
25171
  const githubSecretScope = argv.githubSecretScope ? parseScope(argv.githubSecretScope) : void 0;
24938
- const [environmentId] = await promptForPositionals(getEntry("sync secrets"), argv);
25172
+ const environmentId = argv.env;
24939
25173
  await assertSyncableLayer(environmentId, { repoRoot: argv.cwd });
24940
25174
  const loaded = await loadConfig(argv.cwd);
24941
25175
  const environment = await resolveEnvironmentId(environmentId, { repoRoot: argv.cwd });