@theholocron/cli 5.0.0-alpha.525 → 5.0.0-alpha.527

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
@@ -35,7 +35,7 @@ import { ADR_DIR, ADR_STATUSES, CLOSED_STATUSES, SPEC_DIRS, SPEC_STATUSES, WITHD
35
35
  import { stringifyJson } from "@theholocron/json-utils";
36
36
  import { findRootSync, isWorkspaceRoot, walkFilesSync } from "@theholocron/fs-utils";
37
37
  import { appManifestPage, buildAppManifest, convertAppManifest, serveAppManifest, serveHandler, superviseProcesses } from "@theholocron/dagobah";
38
- import { createGitHubClient, getApp, listAppDeliveries, listAppInstallations, redeliverAppDelivery } from "@theholocron/github-client";
38
+ import { createGitHubClient, getApp, listAppDeliveries, listAppInstallations, redeliverAppDelivery, suspendAppInstallation, unsuspendAppInstallation } from "@theholocron/github-client";
39
39
  import { createServer } from "node:http";
40
40
  import { promisify } from "node:util";
41
41
  import { loadConfigPath } from "@theholocron/datapad";
@@ -3125,6 +3125,7 @@ function validateDev(dev) {
3125
3125
  }
3126
3126
  if (dev.port !== void 0 && !(Number.isInteger(dev.port) && dev.port >= 1 && dev.port <= 65535)) throw new ConfigError(`\`dev.port\` must be a port from 1 to 65535, got ${JSON.stringify(dev.port)}`);
3127
3127
  if (dev.command !== void 0 && !(Array.isArray(dev.command) && dev.command.length > 0 && dev.command.every(nonEmpty))) throw new ConfigError("`dev.command` must be the program and its arguments, e.g. [\"pnpm\", \"run\", \"serve\"]");
3128
+ if (dev.suspendWhenIdle !== void 0 && typeof dev.suspendWhenIdle !== "boolean") throw new ConfigError(`\`dev.suspendWhenIdle\` must be true or false, got ${JSON.stringify(dev.suspendWhenIdle)}`);
3128
3129
  if (dev.serve !== void 0) {
3129
3130
  const { serve } = dev;
3130
3131
  if (!nonEmpty(serve.handler)) throw new ConfigError("`dev.serve.handler` must be the path of the module that exports the handler");
@@ -10346,7 +10347,324 @@ function resolveDevOptions(flags, config, self = [process.execPath, process.argv
10346
10347
  name,
10347
10348
  hostname,
10348
10349
  port: flags.port ?? config?.port ?? DEFAULT_PORT,
10349
- command
10350
+ command,
10351
+ suspendWhenIdle: config?.suspendWhenIdle ?? false
10352
+ };
10353
+ }
10354
+ // src/commands/doctor-github-app/permission-gaps.ts
10355
+ const LEVELS$1 = [
10356
+ "read",
10357
+ "write",
10358
+ "admin"
10359
+ ];
10360
+ /** The permissions in `want` that `have` lacks or holds at a lower level (`read < write < admin`), one line each. */
10361
+ function permissionGaps(want, have) {
10362
+ return Object.entries(want).flatMap(([name, level]) => {
10363
+ const held = have[name];
10364
+ if (held === void 0) return [`missing permission ${name} (${level})`];
10365
+ return LEVELS$1.indexOf(held) < LEVELS$1.indexOf(level) ? [`permission ${name} is ${held}, wants ${level}`] : [];
10366
+ });
10367
+ }
10368
+ // src/commands/doctor-github-app/settings-urls.ts
10369
+ /** The App's permissions page (its events are on the same page, under "Subscribe to events"), by who owns it. */
10370
+ function appSettingsUrl(app) {
10371
+ return app.owner?.type === "Organization" ? `https://github.com/organizations/${app.owner.login}/settings/apps/${app.slug}/permissions` : `https://github.com/settings/apps/${app.slug}/permissions`;
10372
+ }
10373
+ /** The page where an account accepts an App's new permissions: its installation. */
10374
+ function installationSettingsUrl(account, id) {
10375
+ if (account?.type === "Organization") return `https://github.com/organizations/${account.login}/settings/installations/${id}`;
10376
+ return `https://github.com/settings/installations/${id}`;
10377
+ }
10378
+ // src/commands/doctor-github-app/app-rows.ts
10379
+ const row$26 = (name, what, problems, ok) => ({
10380
+ id: `${name}:${what}`,
10381
+ title: `${name}: ${what}`,
10382
+ status: problems.length > 0 ? "fail" : "ok",
10383
+ detail: problems.length > 0 ? `${problems.length} problem(s)` : ok,
10384
+ problems
10385
+ });
10386
+ /** Extras are information only: they never fail a row, they are named in its detail. */
10387
+ const extrasNote = (noun, extras) => extras.length > 0 ? `; info: ${extras.length} ${noun} not in the manifest (${extras.join(", ")})` : "";
10388
+ /**
10389
+ * The events, permissions and installations rows of one App instance: the manifest against the live App, and the live
10390
+ * App against what each installation has accepted. A row that fails ends with the page that fixes it.
10391
+ */
10392
+ function appRows(name, manifest, app, installations) {
10393
+ const fix = `fix: ${appSettingsUrl(app)} (events are on the same page, under "Subscribe to events")`;
10394
+ const eventProblems = manifest.events.filter((e) => !app.events.includes(e)).map((e) => `missing event ${e}`);
10395
+ const extraEvents = app.events.filter((e) => !manifest.events.includes(e));
10396
+ const permissionProblems = permissionGaps(manifest.permissions, app.permissions);
10397
+ const extraPermissions = Object.keys(app.permissions).filter((p) => !(p in manifest.permissions));
10398
+ const installationProblems = installations.flatMap((installation) => {
10399
+ const gaps = [...permissionGaps(app.permissions, installation.permissions), ...app.events.filter((e) => !installation.events.includes(e)).map((e) => `missing event ${e}`)];
10400
+ if (gaps.length === 0) return [];
10401
+ const who = installation.account?.login ?? `installation ${installation.id}`;
10402
+ const url = installationSettingsUrl(installation.account, installation.id);
10403
+ return [`${who} has not accepted the current App: ${gaps.join("; ")}`, `fix: ${who} accepts the update at ${url}`];
10404
+ });
10405
+ return [
10406
+ row$26(name, "events", eventProblems.length > 0 ? [...eventProblems, fix] : [], `all ${manifest.events.length} subscribed${extrasNote("extra event(s)", extraEvents)}`),
10407
+ row$26(name, "permissions", permissionProblems.length > 0 ? [...permissionProblems, fix] : [], `all ${Object.keys(manifest.permissions).length} granted${extrasNote("extra permission(s)", extraPermissions)}`),
10408
+ row$26(name, "installations", installationProblems, `${installations.length} installation(s) up to date`)
10409
+ ];
10410
+ }
10411
+ // src/commands/webhook-deliveries/failed-deliveries.ts
10412
+ /** Whether a delivery reached the App's endpoint and was answered with a success (2xx). */
10413
+ const succeeded = (delivery) => delivery.statusCode >= 200 && delivery.statusCode < 300;
10414
+ /**
10415
+ * The deliveries that still need delivering again, oldest first (SPEC-0099, recovery 2). A delivery and its
10416
+ * redeliveries share one GUID, so each GUID is judged by its **latest** attempt: a first attempt that failed and was
10417
+ * redelivered successfully is done, and one whose latest redelivery failed too is returned once, as that attempt, never
10418
+ * once per attempt. A delivery that got no answer at all (`statusCode` `0`) has failed.
10419
+ */
10420
+ function failedDeliveries(deliveries) {
10421
+ const latest = /* @__PURE__ */ new Map();
10422
+ for (const delivery of deliveries) {
10423
+ const seen = latest.get(delivery.guid);
10424
+ if (seen === void 0 || delivery.deliveredAt > seen.deliveredAt) latest.set(delivery.guid, delivery);
10425
+ }
10426
+ return [...latest.values()].filter((delivery) => !succeeded(delivery)).sort((a, b) => a.deliveredAt.localeCompare(b.deliveredAt) || a.id - b.id);
10427
+ }
10428
+ // src/commands/doctor-github-app/read-app-credentials.ts
10429
+ /** The names the App's credentials are kept under, Sentinel's own first and the bare ones an older Environment has (#1864). */
10430
+ const APP_ID = ["SENTINEL_GITHUB_APP_ID", "GITHUB_APP_ID"];
10431
+ const PRIVATE_KEY = ["SENTINEL_GITHUB_APP_PRIVATE_KEY", "GITHUB_APP_PRIVATE_KEY"];
10432
+ /** The first of `names` the environment holds a value for. */
10433
+ function held(values, names) {
10434
+ return names.map((name) => values[name]).find((value) => value?.trim());
10435
+ }
10436
+ /** An error's message with the secrets it was handed taken out, so nothing read from the vault is ever printed. */
10437
+ function scrubbed$1(err, secrets) {
10438
+ return secrets.filter(Boolean).reduce((text, secret) => text.split(secret).join("[redacted]"), errorMessage(err));
10439
+ }
10440
+ /**
10441
+ * The App's id and key from its vault environment, read in memory and never printed or written, or the reason they cannot
10442
+ * be had (no `vault` provider, an environment that cannot be read, a name it does not hold). Shared by `doctor github-app`
10443
+ * and `redeliver webhooks`, which both call the App's own endpoints with its JWT.
10444
+ */
10445
+ async function readAppCredentials(instance, loader) {
10446
+ const vault = loader.has("vault") ? loader.get("vault") : void 0;
10447
+ if (!vault?.readEnvironment) return { reason: vault ? `${vault.providerName} cannot read an environment's variables` : "needs a `vault` provider in holocron.config.ts (1password)" };
10448
+ const environment = resolvedEnvironment(instance);
10449
+ let values;
10450
+ try {
10451
+ values = await vault.readEnvironment(environment);
10452
+ } catch (err) {
10453
+ return { reason: `cannot read the "${environment}" environment: ${errorMessage(err)}` };
10454
+ }
10455
+ return credentialsFromValues(values, environment);
10456
+ }
10457
+ /**
10458
+ * The App's id and key from the variables of a vault environment already read (`environment` names it in the reason),
10459
+ * or the reason one is missing. The key's literal `\n` line breaks are restored.
10460
+ */
10461
+ function credentialsFromValues(values, environment) {
10462
+ const appId = held(values, APP_ID);
10463
+ const key = held(values, PRIVATE_KEY);
10464
+ const missing = [appId ? void 0 : APP_ID, key ? void 0 : PRIVATE_KEY].filter((names) => names !== void 0);
10465
+ if (missing.length > 0) return { reason: `"${environment}" does not hold ${missing.map(([preferred, older]) => `${preferred} (or ${older})`).join(" or ")}` };
10466
+ const privateKey = key.includes("\n") ? key : key.replace(/\\n/g, "\n");
10467
+ return { creds: {
10468
+ appId: appId.trim(),
10469
+ privateKey
10470
+ } };
10471
+ }
10472
+ // src/commands/doctor-github-app/delivery-row.ts
10473
+ const DAY_MS$1 = 864e5;
10474
+ /** The most failed deliveries a row names; the rest are counted. */
10475
+ const MAX_NAMED = 10;
10476
+ /**
10477
+ * The `deliveries` row of one App instance (SPEC-0099, signal 3): how many webhook deliveries in the last day failed and
10478
+ * have not been delivered again successfully. A failing row names the oldest ones and ends with the command that repairs
10479
+ * them. A delivery log that cannot be read (an API without the call, a refusal) is a skip with the reason, never a failure
10480
+ * of the check.
10481
+ */
10482
+ async function deliveryRow(name, creds, api, now, secrets) {
10483
+ const id = `${name}:deliveries`;
10484
+ const title = `${name}: deliveries`;
10485
+ if (!api.listAppDeliveries) return {
10486
+ id,
10487
+ title,
10488
+ status: "skip",
10489
+ detail: "the delivery log is not read here",
10490
+ problems: []
10491
+ };
10492
+ let failed;
10493
+ try {
10494
+ failed = failedDeliveries(await api.listAppDeliveries(creds, { since: (/* @__PURE__ */ new Date(now - DAY_MS$1)).toISOString() }));
10495
+ } catch (err) {
10496
+ return {
10497
+ id,
10498
+ title,
10499
+ status: "skip",
10500
+ detail: `cannot read the delivery log: ${scrubbed$1(err, secrets)}`,
10501
+ problems: []
10502
+ };
10503
+ }
10504
+ if (failed.length === 0) return {
10505
+ id,
10506
+ title,
10507
+ status: "ok",
10508
+ detail: "no failed webhook deliveries in the last day",
10509
+ problems: []
10510
+ };
10511
+ const named = failed.slice(0, MAX_NAMED).map((d) => {
10512
+ return `${d.action === null ? d.event : `${d.event}.${d.action}`}, ${d.status || `status ${d.statusCode}`}, ${d.deliveredAt}`;
10513
+ });
10514
+ const more = failed.length > MAX_NAMED ? [`and ${failed.length - MAX_NAMED} more`] : [];
10515
+ return {
10516
+ id,
10517
+ title,
10518
+ status: "fail",
10519
+ detail: `${failed.length} failed webhook deliver${failed.length === 1 ? "y" : "ies"} in the last day; repair with \`holocron redeliver webhooks --app ${name}\``,
10520
+ problems: [...named, ...more]
10521
+ };
10522
+ }
10523
+ // src/commands/doctor-github-app/parse-manifest.ts
10524
+ const LEVELS = [
10525
+ "read",
10526
+ "write",
10527
+ "admin"
10528
+ ];
10529
+ /** Reads the permissions and events out of an App manifest's text; throws an `Error` saying what is wrong with it. */
10530
+ function parseManifest(text) {
10531
+ const raw = JSON.parse(text);
10532
+ const permissions = raw.default_permissions;
10533
+ if (typeof permissions !== "object" || permissions === null || Array.isArray(permissions)) throw new Error("`default_permissions` must be an object of permission name to read, write or admin");
10534
+ for (const [name, level] of Object.entries(permissions)) if (typeof level !== "string" || !LEVELS.includes(level)) throw new Error(`\`default_permissions.${name}\` must be read, write or admin, got ${JSON.stringify(level)}`);
10535
+ const events = raw.default_events ?? [];
10536
+ if (!Array.isArray(events) || !events.every((e) => typeof e === "string")) throw new Error("`default_events` must be a list of event names");
10537
+ return {
10538
+ permissions,
10539
+ events
10540
+ };
10541
+ }
10542
+ // src/commands/doctor-github-app/doctor-github-app.ts
10543
+ /**
10544
+ * `holocron doctor github-app` — does each registered GitHub App instance have what its manifest declares?
10545
+ *
10546
+ * GitHub has no API that changes an existing App's permissions or event subscriptions, so each instance is changed by
10547
+ * hand in its settings page and a missed one fails quietly. Read-only: for every entry of `githubApps` it reads the
10548
+ * manifest file, reads the instance's `SENTINEL_GITHUB_APP_ID` and `SENTINEL_GITHUB_APP_PRIVATE_KEY` (else the bare `GITHUB_APP_ID` and
10549
+ * `GITHUB_APP_PRIVATE_KEY`) from its vault environment in
10550
+ * memory (never printed, never written), signs the App's own JWT and calls `GET /app` and `GET /app/installations`.
10551
+ * Rows per instance: reachable; events (every manifest event is subscribed); permissions (each manifest permission is
10552
+ * granted at least at its level, `read < write < admin`); installations (none lags the App, which is a pending
10553
+ * update an owner has not accepted); deliveries (no webhook delivery of the last day failed and stayed failed, SPEC-0099;
10554
+ * a log that cannot be read is a skip). Extras on the App are named in a row's detail as `info`, never a failure. A row
10555
+ * that fails ends with the settings page that fixes it. An instance whose credentials cannot be read is a skip with
10556
+ * the reason; an unreadable manifest, a rejected JWT or a gap is a failure.
10557
+ */
10558
+ const defaultApi$1 = {
10559
+ getApp,
10560
+ listAppInstallations,
10561
+ listAppDeliveries
10562
+ };
10563
+ async function runDoctorGitHubApp(input) {
10564
+ const print = input.print ?? ((line) => console.log(line));
10565
+ const logger = input.logger ?? getLogger();
10566
+ const instances = input.loaded.resolved.githubApps ?? [];
10567
+ const loader = input.loader ?? new PluginLoader(input.loaded.resolved, input.context);
10568
+ if (instances.length > 0) {
10569
+ await loader.load();
10570
+ assertPluginsResolvable(loader, "doctor github-app");
10571
+ }
10572
+ const rows = [];
10573
+ if (instances.length === 0) rows.push(row$25("github-app", "reachable", "skip", "no `githubApps` are declared in holocron.config.ts"));
10574
+ for (const instance of instances) rows.push(...await checkInstance(instance, loader, input));
10575
+ printCheckRows(rows, print);
10576
+ const summary = summariseChecks(rows);
10577
+ printCheckSummary(summary, print);
10578
+ const status = summary.fail > 0 ? "fail" : summary.ok === 0 ? "skip" : "ok";
10579
+ logger.info({
10580
+ ...summary,
10581
+ status
10582
+ }, "doctor github-app");
10583
+ return {
10584
+ status,
10585
+ rows,
10586
+ summary,
10587
+ ...status === "skip" ? { reason: [...new Set(rows.map((r) => r.detail))].join("; ") } : {}
10588
+ };
10589
+ }
10590
+ function row$25(name, what, status, detail) {
10591
+ return {
10592
+ id: `${name}:${what}`,
10593
+ title: `${name}: ${what}`,
10594
+ status,
10595
+ detail,
10596
+ problems: []
10597
+ };
10598
+ }
10599
+ async function checkInstance(instance, loader, input) {
10600
+ const { name } = instance;
10601
+ const readManifest = input.readManifest ?? ((path) => readFileSync(join(input.context.repoRoot, path), "utf8"));
10602
+ let manifest;
10603
+ try {
10604
+ manifest = parseManifest(readManifest(instance.manifest));
10605
+ } catch (err) {
10606
+ return [row$25(name, "manifest", "fail", `cannot read ${instance.manifest}: ${errorMessage(err)}`)];
10607
+ }
10608
+ const read = await readAppCredentials(instance, loader);
10609
+ if ("reason" in read) return [row$25(name, "reachable", "skip", read.reason)];
10610
+ const api = input.api ?? defaultApi$1;
10611
+ const secrets = [read.creds.privateKey];
10612
+ try {
10613
+ const app = await api.getApp(read.creds);
10614
+ const installations = await api.listAppInstallations(read.creds);
10615
+ const owner = app.owner ? `, owned by ${app.owner.login}` : "";
10616
+ return [
10617
+ row$25(name, "reachable", "ok", `${app.slug}${owner}, settings: ${appSettingsUrl(app)}`),
10618
+ ...appRows(name, manifest, app, installations),
10619
+ await deliveryRow(name, read.creds, api, (input.now ?? Date.now)(), secrets)
10620
+ ];
10621
+ } catch (err) {
10622
+ return [row$25(name, "reachable", "fail", `cannot call GitHub as the App: ${scrubbed$1(err, secrets)}`)];
10623
+ }
10624
+ }
10625
+ // src/commands/doctor-github-app/doctor-github-app.command.ts
10626
+ const doctorGitHubAppCommand = {
10627
+ command: "github-app",
10628
+ describe: "Compare each registered GitHub App's events, permissions and installations with its manifest (read-only)",
10629
+ handler: async (argv) => {
10630
+ const tokens = tokenContext(argv.token);
10631
+ if (!tokens) return;
10632
+ const loaded = await loadConfig(argv.cwd);
10633
+ applyResolvedConfig(argv, loaded.resolved);
10634
+ if ((await runDoctorGitHubApp({
10635
+ loaded,
10636
+ context: {
10637
+ repoRoot: argv.cwd,
10638
+ ...tokens,
10639
+ org: resolveOrg(argv, loaded.resolved)
10640
+ }
10641
+ })).status === "fail") process.exitCode = 1;
10642
+ }
10643
+ };
10644
+ // src/commands/set-installations-suspended/set-installations-suspended.ts
10645
+ const GITHUB = {
10646
+ list: (creds) => listAppInstallations(creds),
10647
+ suspend: (creds, id) => suspendAppInstallation(creds, id),
10648
+ unsuspend: (creds, id) => unsuspendAppInstallation(creds, id)
10649
+ };
10650
+ /**
10651
+ * Suspends or unsuspends every installation of a GitHub App with the App's own JWT: `holocron dev`'s switch for the
10652
+ * development App (`dev.suspendWhenIdle`). A suspended installation is sent no
10653
+ * webhooks, so nothing fails against a tunnel that is down. An installation already in the wanted state is not called, so
10654
+ * a second run changes nothing. Stops at the first refusal, leaving the others as they were.
10655
+ */
10656
+ async function setInstallationsSuspended(input) {
10657
+ const api = input.api ?? GITHUB;
10658
+ const installations = await api.list(input.creds);
10659
+ let changed = 0;
10660
+ for (const installation of installations) {
10661
+ if (installation.suspended === input.suspended) continue;
10662
+ await (input.suspended ? api.suspend : api.unsuspend)(input.creds, installation.id);
10663
+ changed++;
10664
+ }
10665
+ return {
10666
+ total: installations.length,
10667
+ changed
10350
10668
  };
10351
10669
  }
10352
10670
  // src/commands/run-cloudflared/run-cloudflared.ts
@@ -10614,6 +10932,7 @@ async function runDev(input) {
10614
10932
  if (dryRun) {
10615
10933
  row(true, `vault ${input.environment}`, "would read its variables for the application");
10616
10934
  row(true, shown, `would run beside cloudflared, with PORT=${input.port}`);
10935
+ if (input.suspendWhenIdle) row(true, "GitHub App", "would unsuspend its installations while this runs, and suspend them after");
10617
10936
  return finish("ok");
10618
10937
  }
10619
10938
  let values;
@@ -10632,6 +10951,37 @@ async function runDev(input) {
10632
10951
  row(false, "cloudflared", describeError(err));
10633
10952
  return finish("fail");
10634
10953
  }
10954
+ const switchInstallations = input.switchInstallations ?? setInstallationsSuspended;
10955
+ let appCreds;
10956
+ if (input.suspendWhenIdle) {
10957
+ appCreds = credentialsFromValues(values, input.environment);
10958
+ if ("reason" in appCreds) {
10959
+ row(false, "GitHub App", `${appCreds.reason}; \`dev.suspendWhenIdle\` needs its id and key`);
10960
+ return finish("fail");
10961
+ }
10962
+ try {
10963
+ const result = await switchInstallations({
10964
+ creds: appCreds.creds,
10965
+ suspended: false
10966
+ });
10967
+ row(true, "GitHub App", `${result.total} installation(s) active (${result.changed} unsuspended)`);
10968
+ } catch (err) {
10969
+ row(false, "GitHub App", `could not unsuspend its installations: ${describeError(err)}`);
10970
+ return finish("fail");
10971
+ }
10972
+ }
10973
+ const suspendAgain = async () => {
10974
+ if (!appCreds || "reason" in appCreds) return;
10975
+ try {
10976
+ const result = await switchInstallations({
10977
+ creds: appCreds.creds,
10978
+ suspended: true
10979
+ });
10980
+ row(true, "GitHub App", `${result.total} installation(s) suspended again`);
10981
+ } catch (err) {
10982
+ row(false, "GitHub App", `could not suspend its installations, do it by hand: ${describeError(err)}`);
10983
+ }
10984
+ };
10635
10985
  print("");
10636
10986
  print(`running ${shown} and cloudflared (Ctrl-C stops both): ${tunnel.url} to localhost:${input.port}`);
10637
10987
  let exitCode;
@@ -10660,9 +11010,11 @@ async function runDev(input) {
10660
11010
  }));
10661
11011
  } catch (err) {
10662
11012
  row(false, "dev", describeError(err));
11013
+ await suspendAgain();
10663
11014
  return finish("fail");
10664
11015
  }
10665
11016
  row(exitCode === 0, "dev", `ended with ${exitCode}`);
11017
+ await suspendAgain();
10666
11018
  return finish(exitCode === 0 ? "ok" : "fail", { exitCode });
10667
11019
  }
10668
11020
  // src/commands/dev/dev.command.ts
@@ -11534,7 +11886,7 @@ async function runDoctorDns(input) {
11534
11886
  });
11535
11887
  else if (!loader.has("dns")) {
11536
11888
  const why = whyMissing(loader, "dns", "no `dns` provider to check them with");
11537
- for (const zone of zones) rows.push(row$26(zone, "skip", why));
11889
+ for (const zone of zones) rows.push(row$24(zone, "skip", why));
11538
11890
  for (const { hostname } of domains) rows.push(domainRow(hostname, "skip", why));
11539
11891
  } else {
11540
11892
  const dns = loader.get("dns");
@@ -11556,7 +11908,7 @@ async function runDoctorDns(input) {
11556
11908
  ...status === "skip" ? { reason: [...new Set(rows.map((r) => r.detail))].join("; ") } : {}
11557
11909
  };
11558
11910
  }
11559
- function row$26(zone, status, detail, problems = []) {
11911
+ function row$24(zone, status, detail, problems = []) {
11560
11912
  return {
11561
11913
  id: `dns-${zone}`,
11562
11914
  title: `${zone} records exist`,
@@ -11585,7 +11937,7 @@ async function checkDomain(dns, deploy, project, hostname) {
11585
11937
  return noToken !== void 0 ? domainRow(hostname, "skip", noToken) : domainRow(hostname, "fail", errorMessage(err));
11586
11938
  }
11587
11939
  }
11588
- async function checkZone(dns, zone, wanted, rowOf = (...args) => row$26(zone, ...args)) {
11940
+ async function checkZone(dns, zone, wanted, rowOf = (...args) => row$24(zone, ...args)) {
11589
11941
  try {
11590
11942
  const have = await dns.listRecords(zone);
11591
11943
  const problems = declaredVsActual(new Map(wanted.map((w) => [keyOf(w), w])), new Map(have.map((h) => [keyOf(h), h])), {
@@ -11672,367 +12024,119 @@ async function checkEnvironments(loader, named) {
11672
12024
  });
11673
12025
  return problems.length > 0 ? make("fail", `${problems.length} problem(s)`, problems) : make("ok", `${names.length} of ${names.length} exist`);
11674
12026
  } catch (err) {
11675
- const noToken = missingTokenReason(err);
11676
- return noToken !== void 0 ? make("skip", noToken) : make("fail", errorMessage(err));
11677
- }
11678
- }
11679
- // src/commands/doctor-environments/doctor-environments.command.ts
11680
- const doctorEnvironmentsCommand = {
11681
- command: "environments",
11682
- describe: "Check that the deployment environments the config relies on exist (read-only)",
11683
- handler: async (argv) => {
11684
- const tokens = tokenContext(argv.token);
11685
- if (!tokens) return;
11686
- const loaded = await loadConfig(argv.cwd);
11687
- applyResolvedConfig(argv, loaded.resolved);
11688
- if ((await runDoctorEnvironments({
11689
- loaded,
11690
- context: {
11691
- repoRoot: argv.cwd,
11692
- ...tokens,
11693
- org: resolveOrg(argv, loaded.resolved)
11694
- }
11695
- })).status === "fail") process.exitCode = 1;
11696
- }
11697
- };
11698
- // src/commands/doctor-errors/declared-projects.ts
11699
- /**
11700
- * The error tracker projects the config declares: every project a notifications layout's `relay.errors.projects`
11701
- * sends alerts from, in order, each once.
11702
- */
11703
- function declaredProjects$1(layouts) {
11704
- return [...new Set(layouts.flatMap((layout) => layout.relay?.errors?.projects ?? []))];
11705
- }
11706
- // src/commands/doctor-errors/errors-rows.ts
11707
- const row$25 = (id, title, status, detail, problems = []) => ({
11708
- id,
11709
- title,
11710
- status,
11711
- detail,
11712
- problems
11713
- });
11714
- /**
11715
- * The rows `holocron doctor errors` prints for one {@link ErrorsInspection}: the organization, then for each declared
11716
- * project that it exists, has a client key and is watched by an enabled alert rule. Pure. A project missing, a project
11717
- * with no key and a project no enabled rule watches fail; alert rules the token could not read are a skip. The Comlink
11718
- * relay's integration and rule have their own rows in `doctor notifications`.
11719
- */
11720
- function errorsRows(found, providerName) {
11721
- const orgSlug = found.org.slug;
11722
- if (!found.org.exists) {
11723
- const problem = `${providerName} has no organization named ${orgSlug}; check the \`org\` option of the \`errors\` provider`;
11724
- const rows = [row$25("errors:org", "organization exists", "fail", `${orgSlug} not found`, [problem])];
11725
- for (const project of found.projects) rows.push(row$25(`errors:project:${project.slug}`, `project ${project.slug} exists`, "skip", "not checked: no organization"));
11726
- return rows;
11727
- }
11728
- const rows = [row$25("errors:org", "organization exists", "ok", `${orgSlug} (${found.org.name ?? orgSlug})`)];
11729
- if (found.projects.length === 0) {
11730
- rows.push(row$25("errors:projects", "declared projects", "skip", "none declared: no `relay.errors.projects` in a layout"));
11731
- return rows;
11732
- }
11733
- for (const project of found.projects) {
11734
- const slug = project.slug;
11735
- if (!project.exists) {
11736
- const problem = `no project ${slug} in ${found.org.slug}; create it in ${providerName}`;
11737
- rows.push(row$25(`errors:project:${slug}`, `project ${slug} exists`, "fail", "not found", [problem]), row$25(`errors:dsn:${slug}`, `project ${slug} has a key`, "skip", "not checked: no project"), row$25(`errors:alerts:${slug}`, `project ${slug} has an alert rule`, "skip", "not checked: no project"));
11738
- continue;
11739
- }
11740
- rows.push(row$25(`errors:project:${slug}`, `project ${slug} exists`, "ok", slug));
11741
- rows.push(project.hasDsn ? row$25(`errors:dsn:${slug}`, `project ${slug} has a key`, "ok", "a client key (DSN) exists") : row$25(`errors:dsn:${slug}`, `project ${slug} has a key`, "fail", "no client key", [`${slug} has no client key, so an SDK has no DSN to send to; add one in ${providerName}`]));
11742
- if (project.alertRules === void 0) rows.push(row$25(`errors:alerts:${slug}`, `project ${slug} has an alert rule`, "skip", found.alertsUnreadable ? `could not read the alert rules: ${found.alertsUnreadable}` : "not read"));
11743
- else if (project.alertRules === 0) rows.push(row$25(`errors:alerts:${slug}`, `project ${slug} has an alert rule`, "fail", "no enabled rule", [`no enabled alert rule watches ${slug}, so its errors reach no one`]));
11744
- else rows.push(row$25(`errors:alerts:${slug}`, `project ${slug} has an alert rule`, "ok", `${project.alertRules} enabled rule(s)`));
11745
- }
11746
- return rows;
11747
- }
11748
- // src/commands/doctor-errors/doctor-errors.ts
11749
- /**
11750
- * `holocron doctor errors` — does the error tracker the config declares have the organization, projects, keys and
11751
- * alert rules it relies on?
11752
- *
11753
- * Read-only: it never creates a project or a rule, and prints names and counts only, never a DSN, a key or a token.
11754
- * The rows (`errorsRows()`): the organization; for each project a notifications layout's `relay.errors.projects`
11755
- * declares, that it exists, has a client key and is watched by an enabled alert rule. The Comlink relay's own
11756
- * integration and rule are `doctor notifications`' rows and are not repeated. A project the provider says is missing
11757
- * fails; anything that cannot be read (no token, no `org`, a token without the alert scope) is a skip with the reason.
11758
- */
11759
- const skip$2 = (detail) => ({
11760
- id: "errors",
11761
- title: "errors",
11762
- status: "skip",
11763
- detail,
11764
- problems: []
11765
- });
11766
- async function runDoctorErrors(input) {
11767
- const print = input.print ?? ((line) => console.log(line));
11768
- const logger = input.logger ?? getLogger();
11769
- const loader = input.loader ?? new PluginLoader(input.loaded.resolved, input.context);
11770
- await loader.load();
11771
- assertPluginsResolvable(loader, "doctor errors");
11772
- let rows;
11773
- if (!loader.has("errors")) {
11774
- const failure = loader.loadFailures().find((f) => f.key === "errors");
11775
- rows = [skip$2(failure ? `\`${failure.provider}\` failed to load: ${describeError(failure.error)}` : "no `errors` provider is configured in holocron.config.ts")];
11776
- } else {
11777
- const errors = loader.get("errors");
11778
- if (!errors.inspect) rows = [skip$2(`${errors.providerName} cannot read its organization`)];
11779
- else {
11780
- const layouts = (loader.has("notifications") ? loader.get("notifications") : []).flatMap((p) => p.layout ? [p.layout] : []);
11781
- try {
11782
- rows = errorsRows(await errors.inspect({ projects: declaredProjects$1(layouts) }), errors.providerName);
11783
- } catch (err) {
11784
- rows = [skip$2(missingTokenReason(err) ?? `could not read ${errors.providerName}: ${describeError(err)}`)];
11785
- }
11786
- }
11787
- }
11788
- printCheckRows(rows, print);
11789
- const summary = summariseChecks(rows);
11790
- printCheckSummary(summary, print);
11791
- const status = summary.fail > 0 ? "fail" : summary.ok === 0 ? "skip" : "ok";
11792
- logger.info({
11793
- ...summary,
11794
- status
11795
- }, "doctor errors");
11796
- return {
11797
- status,
11798
- rows,
11799
- summary,
11800
- ...status === "skip" ? { reason: rows.map((r) => r.detail).join("; ") } : {}
11801
- };
11802
- }
11803
- // src/commands/doctor-errors/doctor-errors.command.ts
11804
- const doctorErrorsCommand = {
11805
- command: "errors",
11806
- describe: "Check the error tracker's organization, declared projects, keys and alert rules (read-only)",
11807
- handler: async (argv) => {
11808
- const tokens = tokenContext(argv.token);
11809
- if (!tokens) return;
11810
- const loaded = await loadConfig(argv.cwd);
11811
- applyResolvedConfig(argv, loaded.resolved);
11812
- if ((await runDoctorErrors({
11813
- loaded,
11814
- context: {
11815
- repoRoot: argv.cwd,
11816
- ...tokens,
11817
- org: resolveOrg(argv, loaded.resolved)
11818
- }
11819
- })).status === "fail") process.exitCode = 1;
11820
- }
11821
- };
11822
- // src/commands/doctor-github-app/permission-gaps.ts
11823
- const LEVELS$1 = [
11824
- "read",
11825
- "write",
11826
- "admin"
11827
- ];
11828
- /** The permissions in `want` that `have` lacks or holds at a lower level (`read < write < admin`), one line each. */
11829
- function permissionGaps(want, have) {
11830
- return Object.entries(want).flatMap(([name, level]) => {
11831
- const held = have[name];
11832
- if (held === void 0) return [`missing permission ${name} (${level})`];
11833
- return LEVELS$1.indexOf(held) < LEVELS$1.indexOf(level) ? [`permission ${name} is ${held}, wants ${level}`] : [];
11834
- });
11835
- }
11836
- // src/commands/doctor-github-app/settings-urls.ts
11837
- /** The App's permissions page (its events are on the same page, under "Subscribe to events"), by who owns it. */
11838
- function appSettingsUrl(app) {
11839
- return app.owner?.type === "Organization" ? `https://github.com/organizations/${app.owner.login}/settings/apps/${app.slug}/permissions` : `https://github.com/settings/apps/${app.slug}/permissions`;
11840
- }
11841
- /** The page where an account accepts an App's new permissions: its installation. */
11842
- function installationSettingsUrl(account, id) {
11843
- if (account?.type === "Organization") return `https://github.com/organizations/${account.login}/settings/installations/${id}`;
11844
- return `https://github.com/settings/installations/${id}`;
11845
- }
11846
- // src/commands/doctor-github-app/app-rows.ts
11847
- const row$24 = (name, what, problems, ok) => ({
11848
- id: `${name}:${what}`,
11849
- title: `${name}: ${what}`,
11850
- status: problems.length > 0 ? "fail" : "ok",
11851
- detail: problems.length > 0 ? `${problems.length} problem(s)` : ok,
11852
- problems
11853
- });
11854
- /** Extras are information only: they never fail a row, they are named in its detail. */
11855
- const extrasNote = (noun, extras) => extras.length > 0 ? `; info: ${extras.length} ${noun} not in the manifest (${extras.join(", ")})` : "";
11856
- /**
11857
- * The events, permissions and installations rows of one App instance: the manifest against the live App, and the live
11858
- * App against what each installation has accepted. A row that fails ends with the page that fixes it.
11859
- */
11860
- function appRows(name, manifest, app, installations) {
11861
- const fix = `fix: ${appSettingsUrl(app)} (events are on the same page, under "Subscribe to events")`;
11862
- const eventProblems = manifest.events.filter((e) => !app.events.includes(e)).map((e) => `missing event ${e}`);
11863
- const extraEvents = app.events.filter((e) => !manifest.events.includes(e));
11864
- const permissionProblems = permissionGaps(manifest.permissions, app.permissions);
11865
- const extraPermissions = Object.keys(app.permissions).filter((p) => !(p in manifest.permissions));
11866
- const installationProblems = installations.flatMap((installation) => {
11867
- const gaps = [...permissionGaps(app.permissions, installation.permissions), ...app.events.filter((e) => !installation.events.includes(e)).map((e) => `missing event ${e}`)];
11868
- if (gaps.length === 0) return [];
11869
- const who = installation.account?.login ?? `installation ${installation.id}`;
11870
- const url = installationSettingsUrl(installation.account, installation.id);
11871
- return [`${who} has not accepted the current App: ${gaps.join("; ")}`, `fix: ${who} accepts the update at ${url}`];
11872
- });
11873
- return [
11874
- row$24(name, "events", eventProblems.length > 0 ? [...eventProblems, fix] : [], `all ${manifest.events.length} subscribed${extrasNote("extra event(s)", extraEvents)}`),
11875
- row$24(name, "permissions", permissionProblems.length > 0 ? [...permissionProblems, fix] : [], `all ${Object.keys(manifest.permissions).length} granted${extrasNote("extra permission(s)", extraPermissions)}`),
11876
- row$24(name, "installations", installationProblems, `${installations.length} installation(s) up to date`)
11877
- ];
11878
- }
11879
- // src/commands/webhook-deliveries/failed-deliveries.ts
11880
- /** Whether a delivery reached the App's endpoint and was answered with a success (2xx). */
11881
- const succeeded = (delivery) => delivery.statusCode >= 200 && delivery.statusCode < 300;
11882
- /**
11883
- * The deliveries that still need delivering again, oldest first (SPEC-0099, recovery 2). A delivery and its
11884
- * redeliveries share one GUID, so each GUID is judged by its **latest** attempt: a first attempt that failed and was
11885
- * redelivered successfully is done, and one whose latest redelivery failed too is returned once, as that attempt, never
11886
- * once per attempt. A delivery that got no answer at all (`statusCode` `0`) has failed.
11887
- */
11888
- function failedDeliveries(deliveries) {
11889
- const latest = /* @__PURE__ */ new Map();
11890
- for (const delivery of deliveries) {
11891
- const seen = latest.get(delivery.guid);
11892
- if (seen === void 0 || delivery.deliveredAt > seen.deliveredAt) latest.set(delivery.guid, delivery);
12027
+ const noToken = missingTokenReason(err);
12028
+ return noToken !== void 0 ? make("skip", noToken) : make("fail", errorMessage(err));
11893
12029
  }
11894
- return [...latest.values()].filter((delivery) => !succeeded(delivery)).sort((a, b) => a.deliveredAt.localeCompare(b.deliveredAt) || a.id - b.id);
11895
- }
11896
- // src/commands/doctor-github-app/read-app-credentials.ts
11897
- /** The names the App's credentials are kept under, Sentinel's own first and the bare ones an older Environment has (#1864). */
11898
- const APP_ID = ["SENTINEL_GITHUB_APP_ID", "GITHUB_APP_ID"];
11899
- const PRIVATE_KEY = ["SENTINEL_GITHUB_APP_PRIVATE_KEY", "GITHUB_APP_PRIVATE_KEY"];
11900
- /** The first of `names` the environment holds a value for. */
11901
- function held(values, names) {
11902
- return names.map((name) => values[name]).find((value) => value?.trim());
11903
- }
11904
- /** An error's message with the secrets it was handed taken out, so nothing read from the vault is ever printed. */
11905
- function scrubbed$1(err, secrets) {
11906
- return secrets.filter(Boolean).reduce((text, secret) => text.split(secret).join("[redacted]"), errorMessage(err));
11907
12030
  }
12031
+ // src/commands/doctor-environments/doctor-environments.command.ts
12032
+ const doctorEnvironmentsCommand = {
12033
+ command: "environments",
12034
+ describe: "Check that the deployment environments the config relies on exist (read-only)",
12035
+ handler: async (argv) => {
12036
+ const tokens = tokenContext(argv.token);
12037
+ if (!tokens) return;
12038
+ const loaded = await loadConfig(argv.cwd);
12039
+ applyResolvedConfig(argv, loaded.resolved);
12040
+ if ((await runDoctorEnvironments({
12041
+ loaded,
12042
+ context: {
12043
+ repoRoot: argv.cwd,
12044
+ ...tokens,
12045
+ org: resolveOrg(argv, loaded.resolved)
12046
+ }
12047
+ })).status === "fail") process.exitCode = 1;
12048
+ }
12049
+ };
12050
+ // src/commands/doctor-errors/declared-projects.ts
11908
12051
  /**
11909
- * The App's id and key from its vault environment, read in memory and never printed or written, or the reason they cannot
11910
- * be had (no `vault` provider, an environment that cannot be read, a name it does not hold). Shared by `doctor github-app`
11911
- * and `redeliver webhooks`, which both call the App's own endpoints with its JWT.
12052
+ * The error tracker projects the config declares: every project a notifications layout's `relay.errors.projects`
12053
+ * sends alerts from, in order, each once.
11912
12054
  */
11913
- async function readAppCredentials(instance, loader) {
11914
- const vault = loader.has("vault") ? loader.get("vault") : void 0;
11915
- if (!vault?.readEnvironment) return { reason: vault ? `${vault.providerName} cannot read an environment's variables` : "needs a `vault` provider in holocron.config.ts (1password)" };
11916
- const environment = resolvedEnvironment(instance);
11917
- let values;
11918
- try {
11919
- values = await vault.readEnvironment(environment);
11920
- } catch (err) {
11921
- return { reason: `cannot read the "${environment}" environment: ${errorMessage(err)}` };
11922
- }
11923
- const appId = held(values, APP_ID);
11924
- const key = held(values, PRIVATE_KEY);
11925
- const missing = [appId ? void 0 : APP_ID, key ? void 0 : PRIVATE_KEY].filter((names) => names !== void 0);
11926
- if (missing.length > 0) return { reason: `"${environment}" does not hold ${missing.map(([preferred, older]) => `${preferred} (or ${older})`).join(" or ")}` };
11927
- const privateKey = key.includes("\n") ? key : key.replace(/\\n/g, "\n");
11928
- return { creds: {
11929
- appId: appId.trim(),
11930
- privateKey
11931
- } };
12055
+ function declaredProjects$1(layouts) {
12056
+ return [...new Set(layouts.flatMap((layout) => layout.relay?.errors?.projects ?? []))];
11932
12057
  }
11933
- // src/commands/doctor-github-app/delivery-row.ts
11934
- const DAY_MS$1 = 864e5;
11935
- /** The most failed deliveries a row names; the rest are counted. */
11936
- const MAX_NAMED = 10;
12058
+ // src/commands/doctor-errors/errors-rows.ts
12059
+ const row$23 = (id, title, status, detail, problems = []) => ({
12060
+ id,
12061
+ title,
12062
+ status,
12063
+ detail,
12064
+ problems
12065
+ });
11937
12066
  /**
11938
- * The `deliveries` row of one App instance (SPEC-0099, signal 3): how many webhook deliveries in the last day failed and
11939
- * have not been delivered again successfully. A failing row names the oldest ones and ends with the command that repairs
11940
- * them. A delivery log that cannot be read (an API without the call, a refusal) is a skip with the reason, never a failure
11941
- * of the check.
12067
+ * The rows `holocron doctor errors` prints for one {@link ErrorsInspection}: the organization, then for each declared
12068
+ * project that it exists, has a client key and is watched by an enabled alert rule. Pure. A project missing, a project
12069
+ * with no key and a project no enabled rule watches fail; alert rules the token could not read are a skip. The Comlink
12070
+ * relay's integration and rule have their own rows in `doctor notifications`.
11942
12071
  */
11943
- async function deliveryRow(name, creds, api, now, secrets) {
11944
- const id = `${name}:deliveries`;
11945
- const title = `${name}: deliveries`;
11946
- if (!api.listAppDeliveries) return {
11947
- id,
11948
- title,
11949
- status: "skip",
11950
- detail: "the delivery log is not read here",
11951
- problems: []
11952
- };
11953
- let failed;
11954
- try {
11955
- failed = failedDeliveries(await api.listAppDeliveries(creds, { since: (/* @__PURE__ */ new Date(now - DAY_MS$1)).toISOString() }));
11956
- } catch (err) {
11957
- return {
11958
- id,
11959
- title,
11960
- status: "skip",
11961
- detail: `cannot read the delivery log: ${scrubbed$1(err, secrets)}`,
11962
- problems: []
11963
- };
12072
+ function errorsRows(found, providerName) {
12073
+ const orgSlug = found.org.slug;
12074
+ if (!found.org.exists) {
12075
+ const problem = `${providerName} has no organization named ${orgSlug}; check the \`org\` option of the \`errors\` provider`;
12076
+ const rows = [row$23("errors:org", "organization exists", "fail", `${orgSlug} not found`, [problem])];
12077
+ for (const project of found.projects) rows.push(row$23(`errors:project:${project.slug}`, `project ${project.slug} exists`, "skip", "not checked: no organization"));
12078
+ return rows;
11964
12079
  }
11965
- if (failed.length === 0) return {
11966
- id,
11967
- title,
11968
- status: "ok",
11969
- detail: "no failed webhook deliveries in the last day",
11970
- problems: []
11971
- };
11972
- const named = failed.slice(0, MAX_NAMED).map((d) => {
11973
- return `${d.action === null ? d.event : `${d.event}.${d.action}`}, ${d.status || `status ${d.statusCode}`}, ${d.deliveredAt}`;
11974
- });
11975
- const more = failed.length > MAX_NAMED ? [`and ${failed.length - MAX_NAMED} more`] : [];
11976
- return {
11977
- id,
11978
- title,
11979
- status: "fail",
11980
- detail: `${failed.length} failed webhook deliver${failed.length === 1 ? "y" : "ies"} in the last day; repair with \`holocron redeliver webhooks --app ${name}\``,
11981
- problems: [...named, ...more]
11982
- };
11983
- }
11984
- // src/commands/doctor-github-app/parse-manifest.ts
11985
- const LEVELS = [
11986
- "read",
11987
- "write",
11988
- "admin"
11989
- ];
11990
- /** Reads the permissions and events out of an App manifest's text; throws an `Error` saying what is wrong with it. */
11991
- function parseManifest(text) {
11992
- const raw = JSON.parse(text);
11993
- const permissions = raw.default_permissions;
11994
- if (typeof permissions !== "object" || permissions === null || Array.isArray(permissions)) throw new Error("`default_permissions` must be an object of permission name to read, write or admin");
11995
- for (const [name, level] of Object.entries(permissions)) if (typeof level !== "string" || !LEVELS.includes(level)) throw new Error(`\`default_permissions.${name}\` must be read, write or admin, got ${JSON.stringify(level)}`);
11996
- const events = raw.default_events ?? [];
11997
- if (!Array.isArray(events) || !events.every((e) => typeof e === "string")) throw new Error("`default_events` must be a list of event names");
11998
- return {
11999
- permissions,
12000
- events
12001
- };
12080
+ const rows = [row$23("errors:org", "organization exists", "ok", `${orgSlug} (${found.org.name ?? orgSlug})`)];
12081
+ if (found.projects.length === 0) {
12082
+ rows.push(row$23("errors:projects", "declared projects", "skip", "none declared: no `relay.errors.projects` in a layout"));
12083
+ return rows;
12084
+ }
12085
+ for (const project of found.projects) {
12086
+ const slug = project.slug;
12087
+ if (!project.exists) {
12088
+ const problem = `no project ${slug} in ${found.org.slug}; create it in ${providerName}`;
12089
+ rows.push(row$23(`errors:project:${slug}`, `project ${slug} exists`, "fail", "not found", [problem]), row$23(`errors:dsn:${slug}`, `project ${slug} has a key`, "skip", "not checked: no project"), row$23(`errors:alerts:${slug}`, `project ${slug} has an alert rule`, "skip", "not checked: no project"));
12090
+ continue;
12091
+ }
12092
+ rows.push(row$23(`errors:project:${slug}`, `project ${slug} exists`, "ok", slug));
12093
+ rows.push(project.hasDsn ? row$23(`errors:dsn:${slug}`, `project ${slug} has a key`, "ok", "a client key (DSN) exists") : row$23(`errors:dsn:${slug}`, `project ${slug} has a key`, "fail", "no client key", [`${slug} has no client key, so an SDK has no DSN to send to; add one in ${providerName}`]));
12094
+ if (project.alertRules === void 0) rows.push(row$23(`errors:alerts:${slug}`, `project ${slug} has an alert rule`, "skip", found.alertsUnreadable ? `could not read the alert rules: ${found.alertsUnreadable}` : "not read"));
12095
+ else if (project.alertRules === 0) rows.push(row$23(`errors:alerts:${slug}`, `project ${slug} has an alert rule`, "fail", "no enabled rule", [`no enabled alert rule watches ${slug}, so its errors reach no one`]));
12096
+ else rows.push(row$23(`errors:alerts:${slug}`, `project ${slug} has an alert rule`, "ok", `${project.alertRules} enabled rule(s)`));
12097
+ }
12098
+ return rows;
12002
12099
  }
12003
- // src/commands/doctor-github-app/doctor-github-app.ts
12100
+ // src/commands/doctor-errors/doctor-errors.ts
12004
12101
  /**
12005
- * `holocron doctor github-app` — does each registered GitHub App instance have what its manifest declares?
12102
+ * `holocron doctor errors` — does the error tracker the config declares have the organization, projects, keys and
12103
+ * alert rules it relies on?
12006
12104
  *
12007
- * GitHub has no API that changes an existing App's permissions or event subscriptions, so each instance is changed by
12008
- * hand in its settings page and a missed one fails quietly. Read-only: for every entry of `githubApps` it reads the
12009
- * manifest file, reads the instance's `SENTINEL_GITHUB_APP_ID` and `SENTINEL_GITHUB_APP_PRIVATE_KEY` (else the bare `GITHUB_APP_ID` and
12010
- * `GITHUB_APP_PRIVATE_KEY`) from its vault environment in
12011
- * memory (never printed, never written), signs the App's own JWT and calls `GET /app` and `GET /app/installations`.
12012
- * Rows per instance: reachable; events (every manifest event is subscribed); permissions (each manifest permission is
12013
- * granted at least at its level, `read < write < admin`); installations (none lags the App, which is a pending
12014
- * update an owner has not accepted); deliveries (no webhook delivery of the last day failed and stayed failed, SPEC-0099;
12015
- * a log that cannot be read is a skip). Extras on the App are named in a row's detail as `info`, never a failure. A row
12016
- * that fails ends with the settings page that fixes it. An instance whose credentials cannot be read is a skip with
12017
- * the reason; an unreadable manifest, a rejected JWT or a gap is a failure.
12105
+ * Read-only: it never creates a project or a rule, and prints names and counts only, never a DSN, a key or a token.
12106
+ * The rows (`errorsRows()`): the organization; for each project a notifications layout's `relay.errors.projects`
12107
+ * declares, that it exists, has a client key and is watched by an enabled alert rule. The Comlink relay's own
12108
+ * integration and rule are `doctor notifications`' rows and are not repeated. A project the provider says is missing
12109
+ * fails; anything that cannot be read (no token, no `org`, a token without the alert scope) is a skip with the reason.
12018
12110
  */
12019
- const defaultApi$1 = {
12020
- getApp,
12021
- listAppInstallations,
12022
- listAppDeliveries
12023
- };
12024
- async function runDoctorGitHubApp(input) {
12111
+ const skip$2 = (detail) => ({
12112
+ id: "errors",
12113
+ title: "errors",
12114
+ status: "skip",
12115
+ detail,
12116
+ problems: []
12117
+ });
12118
+ async function runDoctorErrors(input) {
12025
12119
  const print = input.print ?? ((line) => console.log(line));
12026
12120
  const logger = input.logger ?? getLogger();
12027
- const instances = input.loaded.resolved.githubApps ?? [];
12028
12121
  const loader = input.loader ?? new PluginLoader(input.loaded.resolved, input.context);
12029
- if (instances.length > 0) {
12030
- await loader.load();
12031
- assertPluginsResolvable(loader, "doctor github-app");
12122
+ await loader.load();
12123
+ assertPluginsResolvable(loader, "doctor errors");
12124
+ let rows;
12125
+ if (!loader.has("errors")) {
12126
+ const failure = loader.loadFailures().find((f) => f.key === "errors");
12127
+ rows = [skip$2(failure ? `\`${failure.provider}\` failed to load: ${describeError(failure.error)}` : "no `errors` provider is configured in holocron.config.ts")];
12128
+ } else {
12129
+ const errors = loader.get("errors");
12130
+ if (!errors.inspect) rows = [skip$2(`${errors.providerName} cannot read its organization`)];
12131
+ else {
12132
+ const layouts = (loader.has("notifications") ? loader.get("notifications") : []).flatMap((p) => p.layout ? [p.layout] : []);
12133
+ try {
12134
+ rows = errorsRows(await errors.inspect({ projects: declaredProjects$1(layouts) }), errors.providerName);
12135
+ } catch (err) {
12136
+ rows = [skip$2(missingTokenReason(err) ?? `could not read ${errors.providerName}: ${describeError(err)}`)];
12137
+ }
12138
+ }
12032
12139
  }
12033
- const rows = [];
12034
- if (instances.length === 0) rows.push(row$23("github-app", "reachable", "skip", "no `githubApps` are declared in holocron.config.ts"));
12035
- for (const instance of instances) rows.push(...await checkInstance(instance, loader, input));
12036
12140
  printCheckRows(rows, print);
12037
12141
  const summary = summariseChecks(rows);
12038
12142
  printCheckSummary(summary, print);
@@ -12040,59 +12144,24 @@ async function runDoctorGitHubApp(input) {
12040
12144
  logger.info({
12041
12145
  ...summary,
12042
12146
  status
12043
- }, "doctor github-app");
12147
+ }, "doctor errors");
12044
12148
  return {
12045
12149
  status,
12046
12150
  rows,
12047
12151
  summary,
12048
- ...status === "skip" ? { reason: [...new Set(rows.map((r) => r.detail))].join("; ") } : {}
12049
- };
12050
- }
12051
- function row$23(name, what, status, detail) {
12052
- return {
12053
- id: `${name}:${what}`,
12054
- title: `${name}: ${what}`,
12055
- status,
12056
- detail,
12057
- problems: []
12152
+ ...status === "skip" ? { reason: rows.map((r) => r.detail).join("; ") } : {}
12058
12153
  };
12059
12154
  }
12060
- async function checkInstance(instance, loader, input) {
12061
- const { name } = instance;
12062
- const readManifest = input.readManifest ?? ((path) => readFileSync(join(input.context.repoRoot, path), "utf8"));
12063
- let manifest;
12064
- try {
12065
- manifest = parseManifest(readManifest(instance.manifest));
12066
- } catch (err) {
12067
- return [row$23(name, "manifest", "fail", `cannot read ${instance.manifest}: ${errorMessage(err)}`)];
12068
- }
12069
- const read = await readAppCredentials(instance, loader);
12070
- if ("reason" in read) return [row$23(name, "reachable", "skip", read.reason)];
12071
- const api = input.api ?? defaultApi$1;
12072
- const secrets = [read.creds.privateKey];
12073
- try {
12074
- const app = await api.getApp(read.creds);
12075
- const installations = await api.listAppInstallations(read.creds);
12076
- const owner = app.owner ? `, owned by ${app.owner.login}` : "";
12077
- return [
12078
- row$23(name, "reachable", "ok", `${app.slug}${owner}, settings: ${appSettingsUrl(app)}`),
12079
- ...appRows(name, manifest, app, installations),
12080
- await deliveryRow(name, read.creds, api, (input.now ?? Date.now)(), secrets)
12081
- ];
12082
- } catch (err) {
12083
- return [row$23(name, "reachable", "fail", `cannot call GitHub as the App: ${scrubbed$1(err, secrets)}`)];
12084
- }
12085
- }
12086
- // src/commands/doctor-github-app/doctor-github-app.command.ts
12087
- const doctorGitHubAppCommand = {
12088
- command: "github-app",
12089
- describe: "Compare each registered GitHub App's events, permissions and installations with its manifest (read-only)",
12155
+ // src/commands/doctor-errors/doctor-errors.command.ts
12156
+ const doctorErrorsCommand = {
12157
+ command: "errors",
12158
+ describe: "Check the error tracker's organization, declared projects, keys and alert rules (read-only)",
12090
12159
  handler: async (argv) => {
12091
12160
  const tokens = tokenContext(argv.token);
12092
12161
  if (!tokens) return;
12093
12162
  const loaded = await loadConfig(argv.cwd);
12094
12163
  applyResolvedConfig(argv, loaded.resolved);
12095
- if ((await runDoctorGitHubApp({
12164
+ if ((await runDoctorErrors({
12096
12165
  loaded,
12097
12166
  context: {
12098
12167
  repoRoot: argv.cwd,