gitea: a start ends the token files an earlier build kept, revoked at the forge, never read

G2 token-stand-in-goes (TypeScript half): at each start while a token file remains and once
this start's token is held, the forge's token lists are read before any token is deleted, a pair
is matched by the token's last eight characters and its scopes, revoked by its id and deleted;
a .tmp goes with its pair, a cut one unrevoked; a pair that stays is the finding
token-file-unrevoked. findingKey and findingValue move to findings.ts.

Builds: design 47 H2 H-A-575, H-A-602, H-A-642, H-A-699
This commit is contained in:
2026-11-25 17:10:33 +01:00
parent c1abd7e210
commit 5a82d93ccb
6 changed files with 324 additions and 25 deletions
+81 -5
View File
@@ -47,6 +47,7 @@ import { state, type State } from "@novox/mesh-sdk/state";
import { setUpToolsAccount, TOOLS_ACCOUNT, type AdminCall } from "./tools-account.js";
import { keepMainRules } from "./mainrules.js";
import { durationMs } from "./taken.js";
import { passOver, readLists, remaining, type FindingSink, type ForgeTokens, type Lists } from "./tokenfiles.js";
/** The tools' token's old fixed name in the forge's list, the one the admin's own token carried too (ADR 0365 §2). */
export const TOKEN_NAME = "mesh-tools";
@@ -283,8 +284,16 @@ export interface MintedTokenOptions {
readonly leaseMs?: number;
/** Who holds the lease when this process does: the node and the process. */
readonly holder?: string;
/** The module's runtime state directory, where a retirement of the admin's old token that failed is remembered. */
/** The module's runtime state directory, where a retirement of the admin's old token that failed is remembered, and
* where an earlier build kept the token files (tokenfiles.ts). */
readonly stateDir?: string;
/** The name of the token file an earlier build kept for this account (`token`, `packages-token`): at each start while
* it remains, it is ended once this start's token is held (H-A-575, H-A-699). */
readonly tokenFile?: string;
/** The accounts whose tokens at the forge are listed to find the files' tokens, besides the admin's (H-A-699 (2)). */
readonly listAccounts?: () => Promise<readonly string[]>;
/** The module's state `findings`, where a token file that stays is written (token-file-unrevoked). */
readonly findings?: FindingSink;
readonly now?: () => Date;
readonly log?: (line: string) => void;
readonly fetch?: typeof fetch;
@@ -293,6 +302,9 @@ export interface MintedTokenOptions {
/** The token the module mints for itself, kept in the vault and renewed when the forge rejects it. */
export class MintedToken implements TokenSource {
private held: VaultToken | null = null;
/** The forge's token lists, read once at this start before it deletes any token there: null when they could not be read. */
private fileLists: Lists | null | undefined;
private filesPassed = false;
private inflight: Promise<string> | null = null;
private readonly scopes: readonly string[];
private readonly ttlMs: number;
@@ -330,7 +342,11 @@ export class MintedToken implements TokenSource {
if (shared) return shared;
if (account === admin) throw new Error(`MESH_GITEA_TOOLS_USER names the admin account "${admin}"; the tools act as an account of their own (novox/hq ADR 0365)`);
const source = new MintedToken({
...MintedToken.settingsFromEnv(env), url, admin, passwordFile, account, oldName: TOKEN_NAME,
...MintedToken.settingsFromEnv(env), url, admin, passwordFile, account, oldName: TOKEN_NAME, tokenFile: "token",
listAccounts: async () => {
const { PACKAGES_ACCOUNT } = await import("./packages-account.js");
return [account, env.MESH_GITEA_PACKAGES_USER || PACKAGES_ACCOUNT];
},
// GiteaAdmin is loaded when first used: client.ts imports this file.
setUp: async (password) => {
const { GiteaAdmin } = await import("./client.js");
@@ -344,12 +360,12 @@ export class MintedToken implements TokenSource {
private static readonly shared = new Map<string, MintedToken>();
/** What every account's source takes from the environment: the vault and lease over the bus, the two settings. */
static settingsFromEnv(env: NodeJS.ProcessEnv): Pick<MintedTokenOptions, "vault" | "lease" | "ttlMs" | "leaseMs" | "stateDir"> {
static settingsFromEnv(env: NodeJS.ProcessEnv): Pick<MintedTokenOptions, "vault" | "lease" | "ttlMs" | "leaseMs" | "stateDir" | "findings"> {
const log = (line: string) => console.log(`[gitea] ${line}`);
return {
vault: sharedVault(), lease: sharedLease(),
ttlMs: settingMs(env, "token-ttl", TOKEN_TTL_DEFAULT, log), leaseMs: settingMs(env, "mint-lease", MINT_LEASE_DEFAULT, log),
stateDir: env.MESH_GITEA_STATE_DIR || undefined,
stateDir: env.MESH_GITEA_STATE_DIR || undefined, findings: state<unknown>("findings"),
};
}
@@ -368,6 +384,7 @@ export class MintedToken implements TokenSource {
if (this.retireFile && existsSync(this.retireFile)) await this.retireAdmin().catch((err) => this.log(`${err}`));
}
this.held = kept;
await this.endTokenFiles();
return kept.token;
}
@@ -403,7 +420,10 @@ export class MintedToken implements TokenSource {
private mint(why: string, stale: string | null): Promise<string> {
if (this.inflight === null) {
this.log(why);
this.inflight = this.leased(stale).finally(() => {
this.inflight = this.leased(stale).then(async (token) => {
await this.endTokenFiles();
return token;
}).finally(() => {
this.inflight = null;
});
}
@@ -438,6 +458,59 @@ export class MintedToken implements TokenSource {
}
}
/** The forge's token lists, once a start, when a token file of this account remains; a read that fails is said and
* leaves every file standing. */
private async readFileLists(admin: AdminCall = this.adminCall()): Promise<void> {
if (this.fileLists !== undefined || !this.opts.stateDir || !this.opts.tokenFile) return;
if (remaining(this.opts.stateDir, this.opts.tokenFile).length === 0) return;
try {
const accounts = [...(await this.opts.listAccounts?.() ?? [this.opts.account]), this.opts.admin];
this.fileLists = await readLists(this.forgeTokens(admin), accounts);
} catch (err) {
this.fileLists = null;
this.log(`the forge's token lists could not be read, so the token files an earlier build kept stay: ${err instanceof Error ? err.message : err}`);
}
}
private forgeTokens(admin: AdminCall): ForgeTokens {
return {
list: async (account) => {
const out: { id: number; token_last_eight: string; scopes: string[] }[] = [];
for (let page = 1; page <= 100; page++) {
const listed = await admin("GET", `/users/${encodeURIComponent(account)}/tokens?page=${page}&limit=50`);
if (listed.status !== 200 || !Array.isArray(listed.body)) throw new Error(`Gitea GET /users/${account}/tokens: ${listed.status} ${detail(listed.body)}`);
if (listed.body.length === 0) break;
for (const t of listed.body) {
if (typeof t?.id === "number" && typeof t?.token_last_eight === "string") {
out.push({ id: t.id, token_last_eight: t.token_last_eight, scopes: Array.isArray(t.scopes) ? t.scopes.map(String) : [] });
}
}
}
return out;
},
revoke: async (account, id) => {
const res = await admin("DELETE", `/users/${encodeURIComponent(account)}/tokens/${id}`);
return res.status === 204 || res.status === 404 ? null : `${res.status} ${detail(res.body)}`;
},
};
}
/** The earlier build's token files end once this start's token is held, at the first time in this process (H-A-575,
* H-A-602, H-A-699): never a failure of the token. */
private async endTokenFiles(): Promise<void> {
if (this.filesPassed || !this.opts.stateDir || !this.opts.tokenFile) return;
this.filesPassed = true;
if (remaining(this.opts.stateDir, this.opts.tokenFile).length === 0) return;
try {
await this.readFileLists();
if (!this.fileLists) return;
await passOver({ dir: this.opts.stateDir, base: this.opts.tokenFile, lists: this.fileLists, forge: this.forgeTokens(this.adminCall()),
findings: this.opts.findings, log: (l) => this.log(l), now: this.now });
} catch (err) {
this.log(`the token files an earlier build kept could not be ended: ${err instanceof Error ? err.message : err}`);
}
}
/** The admin password, read now. */
private password(): string {
try {
@@ -528,6 +601,9 @@ export class MintedToken implements TokenSource {
if (kept !== generation) this.log(`the vault kept ${vaultName(account)} at generation ${kept}, the forge names it ${name}`);
this.held = { token, scopes: this.scopes, generation: kept, changedAt: this.now().toISOString() };
this.log(`minted ${name} for "${account}" (${this.scopes.join(", ")}), kept in the vault as ${vaultName(account)}`);
// The lists are read now, after the own-put and before the drop of the old fixed name below: the earlier build's
// token files hold tokens of that name (H-A-699 (2)).
await this.readFileLists(admin);
// Only now, with the new token kept, does the one it replaces go.
const gone = replaced ? mintName(account, replaced.generation) : this.opts.oldName;