One instance-wide GitHub identity (box account or GitHub App) replaces the per-repo identity and the login-app variable; app keys are read again when the keys file changes

This commit is contained in:
aiongg committed 2026-11-08 20:56:53 +00:00
1 parent 3cda6c1b96
commit 72b1a4edfa
43 files changed
+312 -243

No files matched your search

+38 -26
View File
@@ -2,8 +2,8 @@
// - a decision answered by an operator gives `user:<login>` (the person who pressed the button acts under their own
// name, with their own token from the vault);
// - everything else (rules, reviews, fix-ups, pushes, automatic labels, CI) gives `app`.
// The per-repo setting `repo_identity` decides whether that is used at all: under `legacy` (the default) the box
// account makes every write as before, and `as` only appears in the audit row as a record of what it would be.
// The instance-wide setting `github_identity` decides whether that is used at all: under `box` (the default) the box
// account makes every write, and `as` only appears in the audit row as a record of what it would be.
import type { DatabaseSync } from "node:sqlite";
import { audit } from "../dash/audit.ts";
import type { Grant, Guarded } from "../core/guard.ts";
@@ -13,25 +13,26 @@ import { AppError, call, GITHUB_API } from "./app.ts";
import { AppNotInstalledError, installationToken, readAppSecrets, RepoNotInInstallationError } from "./install-token.ts";
export type Identity = "app" | `user:${string}`;
export type RepoIdentity = "legacy" | "app";
export const REPO_IDENTITIES: readonly RepoIdentity[] = ["legacy", "app"];
export type GithubIdentity = "box" | "app";
export const GITHUB_IDENTITIES: readonly GithubIdentity[] = ["box", "app"];
const key = (repo: string): string => `repo_identity:${repo}`;
const KEY = "github_identity";
export function repoIdentity(db: DatabaseSync, repo: string): RepoIdentity {
const row = db.prepare("SELECT value FROM main.settings WHERE key = ?").get(key(repo)) as { value: string } | undefined;
return row?.value === "app" ? "app" : "legacy";
/** The one instance-wide switch: whose account GitHub writes and dashboard sign-in use. Read at every use, never cached. */
export function githubIdentity(db: DatabaseSync): GithubIdentity {
const row = db.prepare("SELECT value FROM main.settings WHERE key = ?").get(KEY) as { value: string } | undefined;
return row?.value === "app" ? "app" : "box";
}
/** Returns false when nothing changed. */
export function setRepoIdentity(db: DatabaseSync, by: string, repo: string, value: unknown): boolean {
if (value !== "legacy" && value !== "app") throw new Error("the repo identity must be legacy or app");
if (!db.prepare("SELECT 1 FROM main.tracked_repos WHERE name = ?").get(repo)) throw new Error(`${repo} is not tracked`);
const was = repoIdentity(db, repo);
/** Returns false when nothing changed. A change ends every dashboard session, so everyone signs in again under the new mode. */
export function setGithubIdentity(db: DatabaseSync, by: string, value: unknown): boolean {
if (value !== "box" && value !== "app") throw new Error("the GitHub identity must be box or app");
const was = githubIdentity(db);
if (was === value) return false;
if (value === "legacy") db.prepare("DELETE FROM main.settings WHERE key = ?").run(key(repo));
else db.prepare("INSERT INTO main.settings (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value").run(key(repo), value);
audit(db, by, "repo-identity", repo, { identity: value, was });
if (value === "box") db.prepare("DELETE FROM main.settings WHERE key = ?").run(KEY);
else db.prepare("INSERT INTO main.settings (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value").run(KEY, value);
audit(db, by, "github-identity", value, { identity: value, was });
db.prepare("DELETE FROM sessions").run();
return true;
}
@@ -45,9 +46,9 @@ export function identityOfDecision(db: DatabaseSync, decisionId: string | undefi
/** The identity a grant was made for. */
export const identityFor = (g: Guarded | Grant): Identity => g.as;
/** What an audit row records: `legacy` while the repo is on the box account, else the grant's identity. */
/** What an audit row records: `legacy` while writes use the box account, else the grant's identity. */
export function auditIdentity(db: DatabaseSync, g: Guarded | Grant): "legacy" | Identity {
return repoIdentity(db, g.repo) === "legacy" ? "legacy" : identityFor(g);
return githubIdentity(db) === "box" ? "legacy" : identityFor(g);
}
/** Why a repo cannot use the app identity (no app registered, not installed, repo outside the installation), or null when it can. */
@@ -64,13 +65,24 @@ export async function appIdentityBlocker(repo: string, mint: (owner: string, rep
}
}
/** Sets a repo's identity after checking that the app can act there (checked for `app` only). Returns false when nothing changed. */
export async function setRepoIdentityChecked(db: DatabaseSync, by: string, repo: string, value: unknown, mint?: (owner: string, repo: string) => Promise<string>): Promise<boolean> {
if (value === "app") {
const why = await appIdentityBlocker(repo, mint);
if (why) throw new Error(why);
/** Thrown when the instance cannot switch to the app; `repos` are the tracked repos the app does not cover (empty when no app is registered). */
export class IdentityRefused extends Error {
repos: string[];
constructor(message: string, repos: string[]) { super(message); this.repos = repos; }
}
/** Sets the identity. Switching to `app` needs a registered app and an installation covering every tracked repo. Returns false when nothing changed. */
export async function setGithubIdentityChecked(
db: DatabaseSync, by: string, value: unknown, deps: { registered: boolean; mint?: (owner: string, repo: string) => Promise<string> },
): Promise<boolean> {
if (value === "app" && githubIdentity(db) !== "app") {
if (!deps.registered) throw new IdentityRefused("No GitHub App is registered.", []);
const repos = (db.prepare("SELECT name FROM main.tracked_repos ORDER BY name").all() as Array<{ name: string }>).map((r) => r.name);
const bad: string[] = [];
for (const r of repos) if (await appIdentityBlocker(r, deps.mint)) bad.push(r);
if (bad.length) throw new IdentityRefused(`The GitHub App does not cover ${bad.length === 1 ? "this repo" : "these repos"}: ${bad.join(", ")}.`, bad);
}
return setRepoIdentity(db, by, repo, value);
return setGithubIdentity(db, by, value);
}
/** Who a commit is made as, and the login its comments carry. */
@@ -102,7 +114,7 @@ export async function commitIdentity(
db: DatabaseSync, repo: string, box: () => Promise<{ login: string; email: string }>,
deps: { slug?: () => string | null; botId?: (slug: string) => Promise<number> } = {},
): Promise<CommitIdentity> {
if (repoIdentity(db, repo) === "app") {
if (githubIdentity(db) === "app") {
const slug = (deps.slug ?? (() => readAppSecrets()?.slug ?? null))();
if (slug) {
const id = await (deps.botId ?? ((s: string) => botUserId(s, () => installationToken(ownerOf(repo), repo))))(slug);
@@ -134,7 +146,7 @@ export function appSlug(): string | null {
/**
* Logins whose items and comments are ours: the box account (when recorded) and the bot of every app slug ever seen (a bare slug in the
* mirror, `<slug>[bot]` in REST), on every repo whatever its `repo_identity`, so items from before a switch stay ours.
* mirror, `<slug>[bot]` in REST), on every repo whatever the identity setting, so items from before a switch stay ours.
* `slug` is an extra slug injectable for tests; the registered app's is recorded and included by default.
*/
export function ownLogins(db: DatabaseSync, _repo: string, slug: string | null = null): Set<string> {
+6 -6
View File
@@ -1,6 +1,6 @@
// The user lane: a GitHub write that carries out an operator's answer is made as that operator, with the operator's
// GitHub App user token (src/github/vault.ts), never as the box account or the app. Only repos whose `repo_identity`
// is `app` use it; under `legacy` nothing here runs and the box account writes as before.
// GitHub App user token (src/github/vault.ts), never as the box account or the app. It applies while the GitHub
// identity is `app`; under `box` nothing here runs and the box account writes as before.
//
// A decision whose operator has no usable token, or no write access on the repo, does not fail: it waits
// (`decisions.exec_state` waiting-token / waiting-permission, with a plain reason) and runs again after that operator
@@ -8,7 +8,7 @@
import { statSync } from "node:fs";
import type { DatabaseSync } from "node:sqlite";
import { AppError, call, GITHUB_API } from "./app.ts";
import { identityOfDecision, repoIdentity } from "./identity.ts";
import { identityOfDecision, githubIdentity } from "./identity.ts";
import { openVault, type Vault } from "./vault.ts";
import { envVar } from "../env.ts";
import { appChildEnv } from "./install-token.ts";
@@ -38,7 +38,7 @@ export function markExecDone(db: DatabaseSync): void {
*/
export function initExecState(db: DatabaseSync, id: string): void {
const d = db.prepare("SELECT repo, answered_by FROM main.decisions WHERE id = ? AND answer IS NOT NULL AND applied_at IS NULL").get(id) as { repo: string | null; answered_by: string | null } | undefined;
if (!d?.repo || !d.answered_by || repoIdentity(db, d.repo) !== "app") return;
if (!d?.repo || !d.answered_by || githubIdentity(db) !== "app") return;
const has = db.prepare("SELECT 1 FROM main.user_tokens WHERE login = ? AND status = 'ok'").get(d.answered_by);
if (has) setExecState(db, id, "pending");
else setExecState(db, id, "waiting-token", SIGN_IN_REASON);
@@ -170,7 +170,7 @@ const answeredByMaintainer = (db: DatabaseSync, decisionId: string): boolean =>
* caller then uses its own transports and nothing changes. Only the repos on `app` are checked.
*/
export async function laneForDecision(db: DatabaseSync, deps: LaneDeps | undefined, decisionId: string, repos: string[]): Promise<LaneResult | null> {
const app = repos.filter((r) => repoIdentity(db, r) === "app");
const app = (githubIdentity(db) === "app" ? repos : []);
// A maintainer's answer is never carried out by the box account: a repo off the app identity refuses the write.
if (app.length < repos.length && answeredByMaintainer(db, decisionId)) return { state: "waiting-permission", reason: NOT_APP_REASON };
if (!app.length) return null;
@@ -184,7 +184,7 @@ export async function laneForDecision(db: DatabaseSync, deps: LaneDeps | undefin
/** The lane for an operator acting right now (a conversation card), or null when every repo is on the box account. */
export async function laneForOperator(db: DatabaseSync, deps: LaneDeps | undefined, login: string, repos: string[]): Promise<LaneResult | null> {
const app = repos.filter((r) => repoIdentity(db, r) === "app");
const app = (githubIdentity(db) === "app" ? repos : []);
return app.length ? resolveLane(deps ?? defaultLaneDeps(db), login, app) : null;
}
+5 -3
View File
@@ -29,16 +29,18 @@ const MAX_REVOKE_ATTEMPTS = 5;
export class Vault {
#db: DatabaseSync;
#box: TokenBox;
#provider: Provider;
#providerOf: () => Provider;
get #provider(): Provider { return this.#providerOf(); }
#sweeping = false;
#inflight = new Map<string, Promise<UserTokenResult>>();
/** Pause between rereads after a rejected refresh; tests set it to 0. */
waitMs = 300;
constructor(db: DatabaseSync, box: TokenBox, provider: Provider) {
/** `provider` may be a function, read at each use, so the GitHub App's registration can change while the vault lives. */
constructor(db: DatabaseSync, box: TokenBox, provider: Provider | (() => Provider)) {
this.#db = db;
this.#box = box;
this.#provider = provider;
this.#providerOf = typeof provider === "function" ? provider : () => provider;
}
/** A usable access token for `login`, refreshed when it is within a minute of expiry or `rejected` (a token GitHub answered 401 to). */
+3 -3
View File
@@ -8,7 +8,7 @@ import type { DatabaseSync } from "node:sqlite";
import { connect } from "../db.ts";
import { recordPush } from "../push-outcomes.ts";
import type { Grant, Guarded, GuardedItem, GuardedRepo } from "../core/guard.ts";
import { auditIdentity, repoIdentity } from "./identity.ts";
import { auditIdentity, githubIdentity } from "./identity.ts";
/** The PR steps that push to a contributor's branch or ask on the PR where it is closed to us (`lint`: the collect step of a stored patch). */
export type AskKind = "fixup" | "conflict" | "cifix" | "lint";
@@ -49,14 +49,14 @@ function covers(g: Guarded | Grant, repo: string, number?: number): void {
const idOf = (w: Writer, g: Guarded | Grant): string => auditIdentity(w.db, g);
// ---- identity lanes -------------------------------------------------------------
// A write made under a grant `as: "app"` on a repo whose repo_identity is `app` runs with an installation token: gh and
// A write made under a grant `as: "app"` while the GitHub identity is `app` runs with an installation token: gh and
// git children get a replaced environment (the box account's tokens are not in it) and GraphQL goes through a client
// with that environment. Every other write is unchanged: the box account's own credentials.
// Grants `as: user:<login>` belong to the user lane (the person's own token). They never get the app token: they
// stay on the box account at the callers of `inAppLane` (laneExec, laneGit, laneQuery, mergeViaCommand), where the
// user lane plugs in.
const inAppLane = (w: Writer, g: Guarded | Grant): boolean => g.as === "app" && repoIdentity(w.db, g.repo) === "app";
const inAppLane = (w: Writer, g: Guarded | Grant): boolean => g.as === "app" && githubIdentity(w.db) === "app";
/** The child environment for a grant's repo, holding an installation token. Never falls back to the box account: a failure is a clear error. */
async function appEnv(w: Writer, g: Guarded | Grant): Promise<Record<string, string>> {