@theholocron/cli 5.0.0-alpha.526 → 5.0.0-alpha.528

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,342 @@ 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
+ * Whether each installation is active or suspended, as information only: a suspended one is sent no webhooks, which is
10390
+ * what `dev.suspendWhenIdle` wants of a development App while `holocron dev` is not running, and a prod App that is
10391
+ * suspended is for the person reading to notice. Never a failure.
10392
+ */
10393
+ function suspensionRow(name, installations) {
10394
+ const suspended = installations.filter((i) => i.suspended);
10395
+ const who = (i) => i.account?.login ?? `installation ${i.id}`;
10396
+ const detail = installations.length === 0 ? "no installations" : suspended.length === 0 ? `${installations.length} installation(s) active` : `${suspended.length} of ${installations.length} suspended, sent no webhooks (${suspended.map(who).join(", ")}); ${installations.length - suspended.length} active`;
10397
+ return {
10398
+ id: `${name}:suspension`,
10399
+ title: `${name}: suspension`,
10400
+ status: "ok",
10401
+ detail,
10402
+ problems: []
10403
+ };
10404
+ }
10405
+ /**
10406
+ * The events, permissions and installations rows of one App instance: the manifest against the live App, and the live
10407
+ * App against what each installation has accepted. A row that fails ends with the page that fixes it.
10408
+ */
10409
+ function appRows(name, manifest, app, installations) {
10410
+ const fix = `fix: ${appSettingsUrl(app)} (events are on the same page, under "Subscribe to events")`;
10411
+ const eventProblems = manifest.events.filter((e) => !app.events.includes(e)).map((e) => `missing event ${e}`);
10412
+ const extraEvents = app.events.filter((e) => !manifest.events.includes(e));
10413
+ const permissionProblems = permissionGaps(manifest.permissions, app.permissions);
10414
+ const extraPermissions = Object.keys(app.permissions).filter((p) => !(p in manifest.permissions));
10415
+ const installationProblems = installations.flatMap((installation) => {
10416
+ const gaps = [...permissionGaps(app.permissions, installation.permissions), ...app.events.filter((e) => !installation.events.includes(e)).map((e) => `missing event ${e}`)];
10417
+ if (gaps.length === 0) return [];
10418
+ const who = installation.account?.login ?? `installation ${installation.id}`;
10419
+ const url = installationSettingsUrl(installation.account, installation.id);
10420
+ return [`${who} has not accepted the current App: ${gaps.join("; ")}`, `fix: ${who} accepts the update at ${url}`];
10421
+ });
10422
+ return [
10423
+ row$26(name, "events", eventProblems.length > 0 ? [...eventProblems, fix] : [], `all ${manifest.events.length} subscribed${extrasNote("extra event(s)", extraEvents)}`),
10424
+ row$26(name, "permissions", permissionProblems.length > 0 ? [...permissionProblems, fix] : [], `all ${Object.keys(manifest.permissions).length} granted${extrasNote("extra permission(s)", extraPermissions)}`),
10425
+ row$26(name, "installations", installationProblems, `${installations.length} installation(s) up to date`),
10426
+ suspensionRow(name, installations)
10427
+ ];
10428
+ }
10429
+ // src/commands/webhook-deliveries/failed-deliveries.ts
10430
+ /** Whether a delivery reached the App's endpoint and was answered with a success (2xx). */
10431
+ const succeeded = (delivery) => delivery.statusCode >= 200 && delivery.statusCode < 300;
10432
+ /**
10433
+ * The deliveries that still need delivering again, oldest first (SPEC-0099, recovery 2). A delivery and its
10434
+ * redeliveries share one GUID, so each GUID is judged by its **latest** attempt: a first attempt that failed and was
10435
+ * redelivered successfully is done, and one whose latest redelivery failed too is returned once, as that attempt, never
10436
+ * once per attempt. A delivery that got no answer at all (`statusCode` `0`) has failed.
10437
+ */
10438
+ function failedDeliveries(deliveries) {
10439
+ const latest = /* @__PURE__ */ new Map();
10440
+ for (const delivery of deliveries) {
10441
+ const seen = latest.get(delivery.guid);
10442
+ if (seen === void 0 || delivery.deliveredAt > seen.deliveredAt) latest.set(delivery.guid, delivery);
10443
+ }
10444
+ return [...latest.values()].filter((delivery) => !succeeded(delivery)).sort((a, b) => a.deliveredAt.localeCompare(b.deliveredAt) || a.id - b.id);
10445
+ }
10446
+ // src/commands/doctor-github-app/read-app-credentials.ts
10447
+ /** The names the App's credentials are kept under, Sentinel's own first and the bare ones an older Environment has (#1864). */
10448
+ const APP_ID = ["SENTINEL_GITHUB_APP_ID", "GITHUB_APP_ID"];
10449
+ const PRIVATE_KEY = ["SENTINEL_GITHUB_APP_PRIVATE_KEY", "GITHUB_APP_PRIVATE_KEY"];
10450
+ /** The first of `names` the environment holds a value for. */
10451
+ function held(values, names) {
10452
+ return names.map((name) => values[name]).find((value) => value?.trim());
10453
+ }
10454
+ /** An error's message with the secrets it was handed taken out, so nothing read from the vault is ever printed. */
10455
+ function scrubbed$1(err, secrets) {
10456
+ return secrets.filter(Boolean).reduce((text, secret) => text.split(secret).join("[redacted]"), errorMessage(err));
10457
+ }
10458
+ /**
10459
+ * The App's id and key from its vault environment, read in memory and never printed or written, or the reason they cannot
10460
+ * be had (no `vault` provider, an environment that cannot be read, a name it does not hold). Shared by `doctor github-app`
10461
+ * and `redeliver webhooks`, which both call the App's own endpoints with its JWT.
10462
+ */
10463
+ async function readAppCredentials(instance, loader) {
10464
+ const vault = loader.has("vault") ? loader.get("vault") : void 0;
10465
+ if (!vault?.readEnvironment) return { reason: vault ? `${vault.providerName} cannot read an environment's variables` : "needs a `vault` provider in holocron.config.ts (1password)" };
10466
+ const environment = resolvedEnvironment(instance);
10467
+ let values;
10468
+ try {
10469
+ values = await vault.readEnvironment(environment);
10470
+ } catch (err) {
10471
+ return { reason: `cannot read the "${environment}" environment: ${errorMessage(err)}` };
10472
+ }
10473
+ return credentialsFromValues(values, environment);
10474
+ }
10475
+ /**
10476
+ * The App's id and key from the variables of a vault environment already read (`environment` names it in the reason),
10477
+ * or the reason one is missing. The key's literal `\n` line breaks are restored.
10478
+ */
10479
+ function credentialsFromValues(values, environment) {
10480
+ const appId = held(values, APP_ID);
10481
+ const key = held(values, PRIVATE_KEY);
10482
+ const missing = [appId ? void 0 : APP_ID, key ? void 0 : PRIVATE_KEY].filter((names) => names !== void 0);
10483
+ if (missing.length > 0) return { reason: `"${environment}" does not hold ${missing.map(([preferred, older]) => `${preferred} (or ${older})`).join(" or ")}` };
10484
+ const privateKey = key.includes("\n") ? key : key.replace(/\\n/g, "\n");
10485
+ return { creds: {
10486
+ appId: appId.trim(),
10487
+ privateKey
10488
+ } };
10489
+ }
10490
+ // src/commands/doctor-github-app/delivery-row.ts
10491
+ const DAY_MS$1 = 864e5;
10492
+ /** The most failed deliveries a row names; the rest are counted. */
10493
+ const MAX_NAMED = 10;
10494
+ /**
10495
+ * The `deliveries` row of one App instance (SPEC-0099, signal 3): how many webhook deliveries in the last day failed and
10496
+ * have not been delivered again successfully. A failing row names the oldest ones and ends with the command that repairs
10497
+ * them. A delivery log that cannot be read (an API without the call, a refusal) is a skip with the reason, never a failure
10498
+ * of the check.
10499
+ */
10500
+ async function deliveryRow(name, creds, api, now, secrets) {
10501
+ const id = `${name}:deliveries`;
10502
+ const title = `${name}: deliveries`;
10503
+ if (!api.listAppDeliveries) return {
10504
+ id,
10505
+ title,
10506
+ status: "skip",
10507
+ detail: "the delivery log is not read here",
10508
+ problems: []
10509
+ };
10510
+ let failed;
10511
+ try {
10512
+ failed = failedDeliveries(await api.listAppDeliveries(creds, { since: (/* @__PURE__ */ new Date(now - DAY_MS$1)).toISOString() }));
10513
+ } catch (err) {
10514
+ return {
10515
+ id,
10516
+ title,
10517
+ status: "skip",
10518
+ detail: `cannot read the delivery log: ${scrubbed$1(err, secrets)}`,
10519
+ problems: []
10520
+ };
10521
+ }
10522
+ if (failed.length === 0) return {
10523
+ id,
10524
+ title,
10525
+ status: "ok",
10526
+ detail: "no failed webhook deliveries in the last day",
10527
+ problems: []
10528
+ };
10529
+ const named = failed.slice(0, MAX_NAMED).map((d) => {
10530
+ return `${d.action === null ? d.event : `${d.event}.${d.action}`}, ${d.status || `status ${d.statusCode}`}, ${d.deliveredAt}`;
10531
+ });
10532
+ const more = failed.length > MAX_NAMED ? [`and ${failed.length - MAX_NAMED} more`] : [];
10533
+ return {
10534
+ id,
10535
+ title,
10536
+ status: "fail",
10537
+ detail: `${failed.length} failed webhook deliver${failed.length === 1 ? "y" : "ies"} in the last day; repair with \`holocron redeliver webhooks --app ${name}\``,
10538
+ problems: [...named, ...more]
10539
+ };
10540
+ }
10541
+ // src/commands/doctor-github-app/parse-manifest.ts
10542
+ const LEVELS = [
10543
+ "read",
10544
+ "write",
10545
+ "admin"
10546
+ ];
10547
+ /** Reads the permissions and events out of an App manifest's text; throws an `Error` saying what is wrong with it. */
10548
+ function parseManifest(text) {
10549
+ const raw = JSON.parse(text);
10550
+ const permissions = raw.default_permissions;
10551
+ 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");
10552
+ 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)}`);
10553
+ const events = raw.default_events ?? [];
10554
+ if (!Array.isArray(events) || !events.every((e) => typeof e === "string")) throw new Error("`default_events` must be a list of event names");
10555
+ return {
10556
+ permissions,
10557
+ events
10558
+ };
10559
+ }
10560
+ // src/commands/doctor-github-app/doctor-github-app.ts
10561
+ /**
10562
+ * `holocron doctor github-app` — does each registered GitHub App instance have what its manifest declares?
10563
+ *
10564
+ * GitHub has no API that changes an existing App's permissions or event subscriptions, so each instance is changed by
10565
+ * hand in its settings page and a missed one fails quietly. Read-only: for every entry of `githubApps` it reads the
10566
+ * manifest file, reads the instance's `SENTINEL_GITHUB_APP_ID` and `SENTINEL_GITHUB_APP_PRIVATE_KEY` (else the bare `GITHUB_APP_ID` and
10567
+ * `GITHUB_APP_PRIVATE_KEY`) from its vault environment in
10568
+ * memory (never printed, never written), signs the App's own JWT and calls `GET /app` and `GET /app/installations`.
10569
+ * Rows per instance: reachable; events (every manifest event is subscribed); permissions (each manifest permission is
10570
+ * granted at least at its level, `read < write < admin`); installations (none lags the App, which is a pending
10571
+ * update an owner has not accepted); deliveries (no webhook delivery of the last day failed and stayed failed, SPEC-0099;
10572
+ * 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
10573
+ * that fails ends with the settings page that fixes it. An instance whose credentials cannot be read is a skip with
10574
+ * the reason; an unreadable manifest, a rejected JWT or a gap is a failure.
10575
+ */
10576
+ const defaultApi$1 = {
10577
+ getApp,
10578
+ listAppInstallations,
10579
+ listAppDeliveries
10580
+ };
10581
+ async function runDoctorGitHubApp(input) {
10582
+ const print = input.print ?? ((line) => console.log(line));
10583
+ const logger = input.logger ?? getLogger();
10584
+ const instances = input.loaded.resolved.githubApps ?? [];
10585
+ const loader = input.loader ?? new PluginLoader(input.loaded.resolved, input.context);
10586
+ if (instances.length > 0) {
10587
+ await loader.load();
10588
+ assertPluginsResolvable(loader, "doctor github-app");
10589
+ }
10590
+ const rows = [];
10591
+ if (instances.length === 0) rows.push(row$25("github-app", "reachable", "skip", "no `githubApps` are declared in holocron.config.ts"));
10592
+ for (const instance of instances) rows.push(...await checkInstance(instance, loader, input));
10593
+ printCheckRows(rows, print);
10594
+ const summary = summariseChecks(rows);
10595
+ printCheckSummary(summary, print);
10596
+ const status = summary.fail > 0 ? "fail" : summary.ok === 0 ? "skip" : "ok";
10597
+ logger.info({
10598
+ ...summary,
10599
+ status
10600
+ }, "doctor github-app");
10601
+ return {
10602
+ status,
10603
+ rows,
10604
+ summary,
10605
+ ...status === "skip" ? { reason: [...new Set(rows.map((r) => r.detail))].join("; ") } : {}
10606
+ };
10607
+ }
10608
+ function row$25(name, what, status, detail) {
10609
+ return {
10610
+ id: `${name}:${what}`,
10611
+ title: `${name}: ${what}`,
10612
+ status,
10613
+ detail,
10614
+ problems: []
10615
+ };
10616
+ }
10617
+ async function checkInstance(instance, loader, input) {
10618
+ const { name } = instance;
10619
+ const readManifest = input.readManifest ?? ((path) => readFileSync(join(input.context.repoRoot, path), "utf8"));
10620
+ let manifest;
10621
+ try {
10622
+ manifest = parseManifest(readManifest(instance.manifest));
10623
+ } catch (err) {
10624
+ return [row$25(name, "manifest", "fail", `cannot read ${instance.manifest}: ${errorMessage(err)}`)];
10625
+ }
10626
+ const read = await readAppCredentials(instance, loader);
10627
+ if ("reason" in read) return [row$25(name, "reachable", "skip", read.reason)];
10628
+ const api = input.api ?? defaultApi$1;
10629
+ const secrets = [read.creds.privateKey];
10630
+ try {
10631
+ const app = await api.getApp(read.creds);
10632
+ const installations = await api.listAppInstallations(read.creds);
10633
+ const owner = app.owner ? `, owned by ${app.owner.login}` : "";
10634
+ return [
10635
+ row$25(name, "reachable", "ok", `${app.slug}${owner}, settings: ${appSettingsUrl(app)}`),
10636
+ ...appRows(name, manifest, app, installations),
10637
+ await deliveryRow(name, read.creds, api, (input.now ?? Date.now)(), secrets)
10638
+ ];
10639
+ } catch (err) {
10640
+ return [row$25(name, "reachable", "fail", `cannot call GitHub as the App: ${scrubbed$1(err, secrets)}`)];
10641
+ }
10642
+ }
10643
+ // src/commands/doctor-github-app/doctor-github-app.command.ts
10644
+ const doctorGitHubAppCommand = {
10645
+ command: "github-app",
10646
+ describe: "Compare each registered GitHub App's events, permissions and installations with its manifest (read-only)",
10647
+ handler: async (argv) => {
10648
+ const tokens = tokenContext(argv.token);
10649
+ if (!tokens) return;
10650
+ const loaded = await loadConfig(argv.cwd);
10651
+ applyResolvedConfig(argv, loaded.resolved);
10652
+ if ((await runDoctorGitHubApp({
10653
+ loaded,
10654
+ context: {
10655
+ repoRoot: argv.cwd,
10656
+ ...tokens,
10657
+ org: resolveOrg(argv, loaded.resolved)
10658
+ }
10659
+ })).status === "fail") process.exitCode = 1;
10660
+ }
10661
+ };
10662
+ // src/commands/set-installations-suspended/set-installations-suspended.ts
10663
+ const GITHUB = {
10664
+ list: (creds) => listAppInstallations(creds),
10665
+ suspend: (creds, id) => suspendAppInstallation(creds, id),
10666
+ unsuspend: (creds, id) => unsuspendAppInstallation(creds, id)
10667
+ };
10668
+ /**
10669
+ * Suspends or unsuspends every installation of a GitHub App with the App's own JWT: `holocron dev`'s switch for the
10670
+ * development App (`dev.suspendWhenIdle`). A suspended installation is sent no
10671
+ * webhooks, so nothing fails against a tunnel that is down. An installation already in the wanted state is not called, so
10672
+ * a second run changes nothing. Stops at the first refusal, leaving the others as they were.
10673
+ */
10674
+ async function setInstallationsSuspended(input) {
10675
+ const api = input.api ?? GITHUB;
10676
+ const installations = await api.list(input.creds);
10677
+ let changed = 0;
10678
+ for (const installation of installations) {
10679
+ if (installation.suspended === input.suspended) continue;
10680
+ await (input.suspended ? api.suspend : api.unsuspend)(input.creds, installation.id);
10681
+ changed++;
10682
+ }
10683
+ return {
10684
+ total: installations.length,
10685
+ changed
10350
10686
  };
10351
10687
  }
10352
10688
  // src/commands/run-cloudflared/run-cloudflared.ts
@@ -10614,6 +10950,7 @@ async function runDev(input) {
10614
10950
  if (dryRun) {
10615
10951
  row(true, `vault ${input.environment}`, "would read its variables for the application");
10616
10952
  row(true, shown, `would run beside cloudflared, with PORT=${input.port}`);
10953
+ if (input.suspendWhenIdle) row(true, "GitHub App", "would unsuspend its installations while this runs, and suspend them after");
10617
10954
  return finish("ok");
10618
10955
  }
10619
10956
  let values;
@@ -10632,6 +10969,37 @@ async function runDev(input) {
10632
10969
  row(false, "cloudflared", describeError(err));
10633
10970
  return finish("fail");
10634
10971
  }
10972
+ const switchInstallations = input.switchInstallations ?? setInstallationsSuspended;
10973
+ let appCreds;
10974
+ if (input.suspendWhenIdle) {
10975
+ appCreds = credentialsFromValues(values, input.environment);
10976
+ if ("reason" in appCreds) {
10977
+ row(false, "GitHub App", `${appCreds.reason}; \`dev.suspendWhenIdle\` needs its id and key`);
10978
+ return finish("fail");
10979
+ }
10980
+ try {
10981
+ const result = await switchInstallations({
10982
+ creds: appCreds.creds,
10983
+ suspended: false
10984
+ });
10985
+ row(true, "GitHub App", `${result.total} installation(s) active (${result.changed} unsuspended)`);
10986
+ } catch (err) {
10987
+ row(false, "GitHub App", `could not unsuspend its installations: ${describeError(err)}`);
10988
+ return finish("fail");
10989
+ }
10990
+ }
10991
+ const suspendAgain = async () => {
10992
+ if (!appCreds || "reason" in appCreds) return;
10993
+ try {
10994
+ const result = await switchInstallations({
10995
+ creds: appCreds.creds,
10996
+ suspended: true
10997
+ });
10998
+ row(true, "GitHub App", `${result.total} installation(s) suspended again`);
10999
+ } catch (err) {
11000
+ row(false, "GitHub App", `could not suspend its installations, do it by hand: ${describeError(err)}`);
11001
+ }
11002
+ };
10635
11003
  print("");
10636
11004
  print(`running ${shown} and cloudflared (Ctrl-C stops both): ${tunnel.url} to localhost:${input.port}`);
10637
11005
  let exitCode;
@@ -10660,9 +11028,11 @@ async function runDev(input) {
10660
11028
  }));
10661
11029
  } catch (err) {
10662
11030
  row(false, "dev", describeError(err));
11031
+ await suspendAgain();
10663
11032
  return finish("fail");
10664
11033
  }
10665
11034
  row(exitCode === 0, "dev", `ended with ${exitCode}`);
11035
+ await suspendAgain();
10666
11036
  return finish(exitCode === 0 ? "ok" : "fail", { exitCode });
10667
11037
  }
10668
11038
  // src/commands/dev/dev.command.ts
@@ -11534,7 +11904,7 @@ async function runDoctorDns(input) {
11534
11904
  });
11535
11905
  else if (!loader.has("dns")) {
11536
11906
  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));
11907
+ for (const zone of zones) rows.push(row$24(zone, "skip", why));
11538
11908
  for (const { hostname } of domains) rows.push(domainRow(hostname, "skip", why));
11539
11909
  } else {
11540
11910
  const dns = loader.get("dns");
@@ -11556,7 +11926,7 @@ async function runDoctorDns(input) {
11556
11926
  ...status === "skip" ? { reason: [...new Set(rows.map((r) => r.detail))].join("; ") } : {}
11557
11927
  };
11558
11928
  }
11559
- function row$26(zone, status, detail, problems = []) {
11929
+ function row$24(zone, status, detail, problems = []) {
11560
11930
  return {
11561
11931
  id: `dns-${zone}`,
11562
11932
  title: `${zone} records exist`,
@@ -11585,7 +11955,7 @@ async function checkDomain(dns, deploy, project, hostname) {
11585
11955
  return noToken !== void 0 ? domainRow(hostname, "skip", noToken) : domainRow(hostname, "fail", errorMessage(err));
11586
11956
  }
11587
11957
  }
11588
- async function checkZone(dns, zone, wanted, rowOf = (...args) => row$26(zone, ...args)) {
11958
+ async function checkZone(dns, zone, wanted, rowOf = (...args) => row$24(zone, ...args)) {
11589
11959
  try {
11590
11960
  const have = await dns.listRecords(zone);
11591
11961
  const problems = declaredVsActual(new Map(wanted.map((w) => [keyOf(w), w])), new Map(have.map((h) => [keyOf(h), h])), {
@@ -11672,367 +12042,119 @@ async function checkEnvironments(loader, named) {
11672
12042
  });
11673
12043
  return problems.length > 0 ? make("fail", `${problems.length} problem(s)`, problems) : make("ok", `${names.length} of ${names.length} exist`);
11674
12044
  } 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);
12045
+ const noToken = missingTokenReason(err);
12046
+ return noToken !== void 0 ? make("skip", noToken) : make("fail", errorMessage(err));
11893
12047
  }
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
12048
  }
12049
+ // src/commands/doctor-environments/doctor-environments.command.ts
12050
+ const doctorEnvironmentsCommand = {
12051
+ command: "environments",
12052
+ describe: "Check that the deployment environments the config relies on exist (read-only)",
12053
+ handler: async (argv) => {
12054
+ const tokens = tokenContext(argv.token);
12055
+ if (!tokens) return;
12056
+ const loaded = await loadConfig(argv.cwd);
12057
+ applyResolvedConfig(argv, loaded.resolved);
12058
+ if ((await runDoctorEnvironments({
12059
+ loaded,
12060
+ context: {
12061
+ repoRoot: argv.cwd,
12062
+ ...tokens,
12063
+ org: resolveOrg(argv, loaded.resolved)
12064
+ }
12065
+ })).status === "fail") process.exitCode = 1;
12066
+ }
12067
+ };
12068
+ // src/commands/doctor-errors/declared-projects.ts
11908
12069
  /**
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.
12070
+ * The error tracker projects the config declares: every project a notifications layout's `relay.errors.projects`
12071
+ * sends alerts from, in order, each once.
11912
12072
  */
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
- } };
12073
+ function declaredProjects$1(layouts) {
12074
+ return [...new Set(layouts.flatMap((layout) => layout.relay?.errors?.projects ?? []))];
11932
12075
  }
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;
12076
+ // src/commands/doctor-errors/errors-rows.ts
12077
+ const row$23 = (id, title, status, detail, problems = []) => ({
12078
+ id,
12079
+ title,
12080
+ status,
12081
+ detail,
12082
+ problems
12083
+ });
11937
12084
  /**
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.
12085
+ * The rows `holocron doctor errors` prints for one {@link ErrorsInspection}: the organization, then for each declared
12086
+ * project that it exists, has a client key and is watched by an enabled alert rule. Pure. A project missing, a project
12087
+ * with no key and a project no enabled rule watches fail; alert rules the token could not read are a skip. The Comlink
12088
+ * relay's integration and rule have their own rows in `doctor notifications`.
11942
12089
  */
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
- };
12090
+ function errorsRows(found, providerName) {
12091
+ const orgSlug = found.org.slug;
12092
+ if (!found.org.exists) {
12093
+ const problem = `${providerName} has no organization named ${orgSlug}; check the \`org\` option of the \`errors\` provider`;
12094
+ const rows = [row$23("errors:org", "organization exists", "fail", `${orgSlug} not found`, [problem])];
12095
+ for (const project of found.projects) rows.push(row$23(`errors:project:${project.slug}`, `project ${project.slug} exists`, "skip", "not checked: no organization"));
12096
+ return rows;
11964
12097
  }
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
- };
12098
+ const rows = [row$23("errors:org", "organization exists", "ok", `${orgSlug} (${found.org.name ?? orgSlug})`)];
12099
+ if (found.projects.length === 0) {
12100
+ rows.push(row$23("errors:projects", "declared projects", "skip", "none declared: no `relay.errors.projects` in a layout"));
12101
+ return rows;
12102
+ }
12103
+ for (const project of found.projects) {
12104
+ const slug = project.slug;
12105
+ if (!project.exists) {
12106
+ const problem = `no project ${slug} in ${found.org.slug}; create it in ${providerName}`;
12107
+ 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"));
12108
+ continue;
12109
+ }
12110
+ rows.push(row$23(`errors:project:${slug}`, `project ${slug} exists`, "ok", slug));
12111
+ 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}`]));
12112
+ 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"));
12113
+ 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`]));
12114
+ else rows.push(row$23(`errors:alerts:${slug}`, `project ${slug} has an alert rule`, "ok", `${project.alertRules} enabled rule(s)`));
12115
+ }
12116
+ return rows;
12002
12117
  }
12003
- // src/commands/doctor-github-app/doctor-github-app.ts
12118
+ // src/commands/doctor-errors/doctor-errors.ts
12004
12119
  /**
12005
- * `holocron doctor github-app` — does each registered GitHub App instance have what its manifest declares?
12120
+ * `holocron doctor errors` — does the error tracker the config declares have the organization, projects, keys and
12121
+ * alert rules it relies on?
12006
12122
  *
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.
12123
+ * Read-only: it never creates a project or a rule, and prints names and counts only, never a DSN, a key or a token.
12124
+ * The rows (`errorsRows()`): the organization; for each project a notifications layout's `relay.errors.projects`
12125
+ * declares, that it exists, has a client key and is watched by an enabled alert rule. The Comlink relay's own
12126
+ * integration and rule are `doctor notifications`' rows and are not repeated. A project the provider says is missing
12127
+ * fails; anything that cannot be read (no token, no `org`, a token without the alert scope) is a skip with the reason.
12018
12128
  */
12019
- const defaultApi$1 = {
12020
- getApp,
12021
- listAppInstallations,
12022
- listAppDeliveries
12023
- };
12024
- async function runDoctorGitHubApp(input) {
12129
+ const skip$2 = (detail) => ({
12130
+ id: "errors",
12131
+ title: "errors",
12132
+ status: "skip",
12133
+ detail,
12134
+ problems: []
12135
+ });
12136
+ async function runDoctorErrors(input) {
12025
12137
  const print = input.print ?? ((line) => console.log(line));
12026
12138
  const logger = input.logger ?? getLogger();
12027
- const instances = input.loaded.resolved.githubApps ?? [];
12028
12139
  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");
12140
+ await loader.load();
12141
+ assertPluginsResolvable(loader, "doctor errors");
12142
+ let rows;
12143
+ if (!loader.has("errors")) {
12144
+ const failure = loader.loadFailures().find((f) => f.key === "errors");
12145
+ rows = [skip$2(failure ? `\`${failure.provider}\` failed to load: ${describeError(failure.error)}` : "no `errors` provider is configured in holocron.config.ts")];
12146
+ } else {
12147
+ const errors = loader.get("errors");
12148
+ if (!errors.inspect) rows = [skip$2(`${errors.providerName} cannot read its organization`)];
12149
+ else {
12150
+ const layouts = (loader.has("notifications") ? loader.get("notifications") : []).flatMap((p) => p.layout ? [p.layout] : []);
12151
+ try {
12152
+ rows = errorsRows(await errors.inspect({ projects: declaredProjects$1(layouts) }), errors.providerName);
12153
+ } catch (err) {
12154
+ rows = [skip$2(missingTokenReason(err) ?? `could not read ${errors.providerName}: ${describeError(err)}`)];
12155
+ }
12156
+ }
12032
12157
  }
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
12158
  printCheckRows(rows, print);
12037
12159
  const summary = summariseChecks(rows);
12038
12160
  printCheckSummary(summary, print);
@@ -12040,59 +12162,24 @@ async function runDoctorGitHubApp(input) {
12040
12162
  logger.info({
12041
12163
  ...summary,
12042
12164
  status
12043
- }, "doctor github-app");
12165
+ }, "doctor errors");
12044
12166
  return {
12045
12167
  status,
12046
12168
  rows,
12047
12169
  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: []
12170
+ ...status === "skip" ? { reason: rows.map((r) => r.detail).join("; ") } : {}
12058
12171
  };
12059
12172
  }
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)",
12173
+ // src/commands/doctor-errors/doctor-errors.command.ts
12174
+ const doctorErrorsCommand = {
12175
+ command: "errors",
12176
+ describe: "Check the error tracker's organization, declared projects, keys and alert rules (read-only)",
12090
12177
  handler: async (argv) => {
12091
12178
  const tokens = tokenContext(argv.token);
12092
12179
  if (!tokens) return;
12093
12180
  const loaded = await loadConfig(argv.cwd);
12094
12181
  applyResolvedConfig(argv, loaded.resolved);
12095
- if ((await runDoctorGitHubApp({
12182
+ if ((await runDoctorErrors({
12096
12183
  loaded,
12097
12184
  context: {
12098
12185
  repoRoot: argv.cwd,