The file beside the token that kept its scopes went with C4, and with it the re-mint of a token carrying a scope beyond the tools' (write:admin). The value written through own-put now holds the token and its scopes; a token minted with other scopes, or a value naming none, is minted again unasked and the one it replaces deleted at the forge. The Go bundles read the token out of that value. The lost test is back as a row of the scope test in test/token.test.ts. Builds: design 47 H2 §808; H-A-439
609 lines
32 KiB
TypeScript
609 lines
32 KiB
TypeScript
// The token the forge's tools and watcher authenticate with — and where it comes from.
|
|
//
|
|
// Nobody configures it. The forge is raised by the mesh, so there is no operator holding a token to
|
|
// paste in, and pasting one into settings would put a secret in the inventory in plaintext. What
|
|
// the mesh does deliver is the admin account: a login the manifest names and a password the vault
|
|
// minted and the host unsealed into a file (novox/hq ADR 0086). That account is enough to mint a
|
|
// token, so the module mints its own (hq issue 100, the forge's tools), for each of its two accounts, the tools'
|
|
// (`mesh-tools`) and the package seats' (`mesh-packages`):
|
|
//
|
|
// - **kept as a secret, the module's own in the vault** (design 47 H2 §808, §822; H-A-422, H-A-426): written through
|
|
// the seat `mesh-vault`'s two-step sealed write `own-put` under the account's name, so the vault keeps it as
|
|
// `module/gitea/<account>`, its newest generation only, and read through the seat's `get`, sealed to this process's
|
|
// key. Never a file in the runtime state and never plain in a state: the forge hands a token's value out exactly
|
|
// once, and the vault is where the module keeps what it must not lose;
|
|
// - **one name per mint**, `<account>-<generation>`, the generation the one this own-put makes (get's generation plus
|
|
// one; 1 when the vault holds none; H-A-430 (1)). The token minted is written through own-put first, and only then
|
|
// is the token it replaces deleted at the forge, by its id: no moment is without a valid token, and a mint that
|
|
// fails leaves the old one standing. The first mint replaces the tokens the module kept before under the account's
|
|
// old fixed name;
|
|
// - **minted by one process at a time** (§808). The runtime starts each of the bundle's entrypoints as a process of its
|
|
// own (novox/hq ADR 0193), and two that minted at once left the forge two tokens by one name (the 2026-10-14 outage).
|
|
// A process the forge refuses first reads the vault's token; only when the refused token is the vault's current one
|
|
// does it take the lease — the key `mint` in the module's state `token-lease`, created only, living `mint-lease` (a
|
|
// setting, default 60 s) — and mint. A process that finds the lease taken waits for that key to change, at most the
|
|
// lease, then reads the vault again; past it, the lease has expired and the waiter creates it itself;
|
|
// - **minted again when older than `token-ttl`** (a setting, default 24 hours), its age the vault's `changed-at`;
|
|
// - **minted again when minted with other scopes** (H-A-439): the value the vault keeps holds the token and the scopes
|
|
// it was minted with, so a token carrying a scope beyond the ones the tools take (such as write:admin) is minted again
|
|
// unasked, and the one it replaces deleted, as when the scopes were kept in a file beside the token;
|
|
// - minted for the account, not the administrator (novox/hq ADR 0365 §2, issue 469): the administrator's login mints
|
|
// it for the account, after making that account and its team, and deletes any token named `mesh-tools` the
|
|
// administrator itself still holds — the token the tools used before.
|
|
//
|
|
// An explicitly configured token still wins, and is never minted over: if it is rejected, that is
|
|
// reported, not repaired — somebody chose it.
|
|
//
|
|
// The token is never logged. Lines say that one was minted, reused or renewed, and under which name;
|
|
// never what it is.
|
|
|
|
import { existsSync, mkdirSync, rmSync, writeFileSync, readFileSync } from "node:fs";
|
|
import { randomBytes } from "node:crypto";
|
|
import { join } from "node:path";
|
|
import { generateKeyPair, open, sealAnonymous, type Box, type KeyPair } from "@novox/mesh-sdk/seal";
|
|
import { broker } from "@novox/mesh-sdk/messaging";
|
|
import { askRuntime } from "@novox/mesh-sdk/runtime";
|
|
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";
|
|
|
|
/** 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";
|
|
|
|
/** The module whose own secrets the vault keeps its tokens as (§822: the module named by the caller's account). */
|
|
export const VAULT_MODULE = "gitea";
|
|
|
|
/** The vault's name of an account's token: `module/gitea/<account>` (H-A-426). */
|
|
export function vaultName(account: string): string {
|
|
return `module/${VAULT_MODULE}/${account}`;
|
|
}
|
|
|
|
/** The forge's name of an account's token of one generation: `<account>-<generation>` (H-A-422 (2)). */
|
|
export function mintName(account: string, generation: number): string {
|
|
return `${account}-${generation}`;
|
|
}
|
|
|
|
/** The state the mint's lease is kept in, and its one key (§808, §820). */
|
|
export const LEASE_STATE = "token-lease";
|
|
export const LEASE_KEY = "mint";
|
|
|
|
/** token-ttl's and mint-lease's defaults (§808). */
|
|
export const TOKEN_TTL_DEFAULT = "24h";
|
|
export const MINT_LEASE_DEFAULT = "60s";
|
|
|
|
/** A setting the node-engine composes as `MESH_CONFIG_<NAME>`, a duration, in milliseconds; the default when unset, and
|
|
* when it is no duration (said). */
|
|
export function settingMs(env: NodeJS.ProcessEnv, setting: string, fallback: string, log: (line: string) => void = () => {}): number {
|
|
const raw = env[`MESH_CONFIG_${setting.toUpperCase().replace(/-/g, "_")}`];
|
|
const dflt = durationMs(fallback)!;
|
|
if (raw === undefined || raw.trim() === "") return dflt;
|
|
const ms = durationMs(raw);
|
|
if (ms === null) {
|
|
log(`the setting ${setting} is ${JSON.stringify(raw)}, no duration: the default ${fallback} holds`);
|
|
return dflt;
|
|
}
|
|
return ms;
|
|
}
|
|
|
|
/**
|
|
* The least the fifteen tools and the watcher need (gitea's route groups, 1.20+ scoped tokens):
|
|
* write:repository — create/delete repositories, pull requests (list/get/open/merge);
|
|
* write:issue — issues, comments, labels;
|
|
* read:package — the package registry's reads by the Go bundle (cmd/package-registry): the package seats'
|
|
* held, versions and the retention's survey (design 51: a read-only tool token; the
|
|
* writes go with the packages account's own token, packages-account.ts);
|
|
* read:user — GET /user/repos, which the watcher's poll and gitea_list_repos both call.
|
|
* It sits under the `user` category despite listing repositories, not `repository`
|
|
* — confirmed against the running forge (1.27.3), which answered
|
|
* `required=[read:user]` to a token carrying only the other two.
|
|
*
|
|
* **Not write:admin** (novox/hq ADR 0266). It was here so a person could settle the forge's users through
|
|
* `gitea_api` (novox/hq 229); whoever may call a tool includes agents, and the forge's administration is the
|
|
* operator's. The provisioner settles users with the admin account's own login (GiteaAdmin), never this token.
|
|
*
|
|
* A token kept from before a scope was added lacks it: the forge answers such a call with
|
|
* `403 token does not have at least one of required scope(s)`, and the client treats that like a
|
|
* 401 — the source re-mints by name, with the whole list, and the call is retried once.
|
|
*/
|
|
export const TOKEN_SCOPES: readonly string[] = ["write:repository", "write:issue", "read:user", "read:package"];
|
|
|
|
/** Where a client's token comes from, and what to do when the forge says it is wrong. */
|
|
export interface TokenSource {
|
|
/** The token to authenticate with now; minted, read or configured. */
|
|
current(): Promise<string>;
|
|
/** The forge answered 401 to `rejected`, or 403 for a scope it lacks. A fresh token, or a plain error when there is nothing to renew with. */
|
|
renew(rejected: string): Promise<string>;
|
|
}
|
|
|
|
/** A token somebody set — in settings or the environment. Never minted over. */
|
|
export class ConfiguredToken implements TokenSource {
|
|
constructor(private readonly token: string) {}
|
|
|
|
async current(): Promise<string> {
|
|
return this.token;
|
|
}
|
|
|
|
async renew(): Promise<string> {
|
|
throw new Error(
|
|
"the forge rejected the configured Gitea token (401). It was set explicitly (settings or GITEA_TOKEN), " +
|
|
"so the module does not mint over it — fix it, or unset it and the module mints its own",
|
|
);
|
|
}
|
|
}
|
|
|
|
/** The forge would not take the admin account: it refused the login the mesh holds (design 47 H2 §776). Said as the
|
|
* forge's refusal, never as an account to create: whether the forge is away is the seat's to judge (seat.ts). */
|
|
export class AdminRefused extends Error {
|
|
constructor(admin: string, status: number) {
|
|
super(`the forge refuses the mesh's admin account "${admin}" (${status})`);
|
|
this.name = "AdminRefused";
|
|
}
|
|
}
|
|
|
|
/** A token as the vault holds it: the token, the scopes it was minted with, the generation and when it changed (`get`'s
|
|
* answer, opened). */
|
|
export interface VaultToken {
|
|
readonly token: string;
|
|
readonly scopes: readonly string[];
|
|
readonly generation: number;
|
|
readonly changedAt: string;
|
|
}
|
|
|
|
/** The value the vault keeps for an account: the token and the scopes it was minted with (§808, H-A-439). */
|
|
export function vaultValue(token: string, scopes: readonly string[]): string {
|
|
return JSON.stringify({ token, scopes: [...scopes] });
|
|
}
|
|
|
|
/** A value the vault keeps, opened: its token and scopes. A value of another form names no scopes, so it is minted again. */
|
|
export function openValue(value: string): { token: string; scopes: readonly string[] } {
|
|
try {
|
|
const v = JSON.parse(value);
|
|
if (v && typeof v.token === "string" && Array.isArray(v.scopes)) return { token: v.token, scopes: v.scopes.map(String) };
|
|
} catch {
|
|
// not the token and its scopes
|
|
}
|
|
return { token: value.trim(), scopes: [] };
|
|
}
|
|
|
|
/** Whether two lists name the same scopes, in any order. */
|
|
function sameScopes(a: readonly string[], b: readonly string[]): boolean {
|
|
return [...a].sort().join(",") === [...b].sort().join(",");
|
|
}
|
|
|
|
/** The vault as the minter reaches it: the seat `mesh-vault`'s `get` and `own-put` (§808, §822). */
|
|
export interface TokenVault {
|
|
/** The account's token the vault holds, or null when it holds none. */
|
|
get(account: string): Promise<VaultToken | null>;
|
|
/** Write the account's token and the scopes it was minted with as the module's own; answers the generation the vault kept. */
|
|
put(account: string, token: string, scopes: readonly string[]): Promise<number>;
|
|
}
|
|
|
|
/** The lease `mint` in the state `token-lease` (§808). */
|
|
export interface MintLease {
|
|
/** Create the lease for `holder`, living `ms`; false when another holds it. */
|
|
take(holder: string, ms: number): Promise<boolean>;
|
|
/** The lease's holder and since when, or null when nobody holds it. */
|
|
read(): Promise<{ holder: string; since: string } | null>;
|
|
/** Delete the lease, when `holder` still holds it. */
|
|
release(holder: string): Promise<void>;
|
|
/** Resolves when the lease's key changes (deleted, or written again), or after `ms`, whichever is first. */
|
|
changed(ms: number): Promise<void>;
|
|
}
|
|
|
|
/** The vault's words when it holds no secret by the name asked (mesh-vault's Get). */
|
|
const HOLDS_NONE = /the vault holds no secret named/;
|
|
|
|
/** The vault over the bus: `get` sealed to this process's own key, made once a process; `own-put` in its two steps. */
|
|
export function vaultOverBus(request: (verb: string, body: unknown) => Promise<unknown> = (v, b) => broker().request(v, b)): TokenVault {
|
|
let keys: KeyPair | undefined;
|
|
return {
|
|
async get(account) {
|
|
keys ??= generateKeyPair();
|
|
let answer: { generation?: number; "changed-at"?: string; sealed?: Box };
|
|
try {
|
|
answer = (await request("seat:mesh-vault.get", { name: vaultName(account), public_key: keys.publicKey })) as typeof answer;
|
|
} catch (err) {
|
|
if (HOLDS_NONE.test(err instanceof Error ? err.message : String(err))) return null;
|
|
throw err;
|
|
}
|
|
if (!answer?.sealed) throw new Error(`the vault answered no sealed ${vaultName(account)}`);
|
|
return { ...openValue(open(answer.sealed, keys.privateKey)), generation: answer.generation ?? 0, changedAt: answer["changed-at"] ?? "" };
|
|
},
|
|
async put(account, token, scopes) {
|
|
const opened = (await request("seat:mesh-vault.own-put", { name: account })) as { call?: string; seal_to?: string };
|
|
if (!opened?.call || !opened.seal_to) throw new Error(`the vault opened no own-put call for ${vaultName(account)}`);
|
|
const kept = (await request("seat:mesh-vault.own-put", { call: opened.call, sealed: sealAnonymous(vaultValue(token, scopes), opened.seal_to) })) as { generation?: number };
|
|
return kept?.generation ?? 0;
|
|
},
|
|
};
|
|
}
|
|
|
|
/** The runtime's refusal of a create whose key has a value (mesh-sdk's CODE_CHANGED). */
|
|
const CODE_CHANGED = -32010;
|
|
|
|
/** The lease in the module's state `token-lease` over the runtime: a create with the lease as its time to live, and one
|
|
* watch of the key a process, handing each change to the waiters. */
|
|
export function leaseOverState(st: State<{ holder: string; since: string }> = state(LEASE_STATE),
|
|
ask: (method: string, params: unknown) => Promise<unknown> = askRuntime): MintLease {
|
|
const waiters = new Set<() => void>();
|
|
let watching: Promise<void> | undefined;
|
|
return {
|
|
async take(holder, ms) {
|
|
try {
|
|
await ask("mesh/state.create", { state: LEASE_STATE, key: LEASE_KEY, value: { holder, since: new Date().toISOString() },
|
|
ttl_seconds: Math.max(1, Math.ceil(ms / 1000)) });
|
|
return true;
|
|
} catch (err) {
|
|
if ((err as { code?: number }).code === CODE_CHANGED) return false;
|
|
throw err;
|
|
}
|
|
},
|
|
async read() {
|
|
return (await st.get(LEASE_KEY))?.value ?? null;
|
|
},
|
|
async release(holder) {
|
|
if ((await st.get(LEASE_KEY))?.value?.holder === holder) await st.delete(LEASE_KEY);
|
|
},
|
|
async changed(ms) {
|
|
watching ??= st.watch((change) => {
|
|
if (!change.current) for (const wake of [...waiters]) wake();
|
|
}, { key: LEASE_KEY });
|
|
await watching;
|
|
await new Promise<void>((resolve) => {
|
|
const wake = () => { clearTimeout(timer); waiters.delete(wake); resolve(); };
|
|
const timer = setTimeout(wake, ms);
|
|
waiters.add(wake);
|
|
// Released between the refused create and this wait: nothing to wait for.
|
|
void st.get(LEASE_KEY).then((e) => { if (!e) wake(); }, () => {});
|
|
});
|
|
},
|
|
};
|
|
}
|
|
|
|
export interface MintedTokenOptions {
|
|
/** The forge, e.g. http://127.0.0.1:3000. */
|
|
readonly url: string;
|
|
/** The admin login the manifest names. */
|
|
readonly admin: string;
|
|
/** The file the host unsealed the admin password into (ADR 0086). Read at mint time, so a rotation takes. */
|
|
readonly passwordFile: string;
|
|
/** The account the token is minted for, and the vault name it is kept under (H-A-426). */
|
|
readonly account: string;
|
|
/** The token's fixed name before a name per mint: the first mint deletes the account's tokens by it (H-A-430 (1)). */
|
|
readonly oldName: string;
|
|
readonly scopes?: readonly string[];
|
|
/** Run with the admin's password before each mint: makes the account and its team (tools-account.ts). */
|
|
readonly setUp?: (password: string) => Promise<void>;
|
|
/** Where the module keeps its token, and the mint's lease (§808). */
|
|
readonly vault: TokenVault;
|
|
readonly lease: MintLease;
|
|
/** token-ttl and mint-lease, in milliseconds (§808). */
|
|
readonly ttlMs?: number;
|
|
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. */
|
|
readonly stateDir?: string;
|
|
readonly now?: () => Date;
|
|
readonly log?: (line: string) => void;
|
|
readonly fetch?: typeof fetch;
|
|
}
|
|
|
|
/** 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;
|
|
private inflight: Promise<string> | null = null;
|
|
private readonly scopes: readonly string[];
|
|
private readonly ttlMs: number;
|
|
private readonly leaseMs: number;
|
|
private readonly holder: string;
|
|
private readonly now: () => Date;
|
|
private readonly log: (line: string) => void;
|
|
private readonly fetchImpl: typeof fetch;
|
|
|
|
constructor(private readonly opts: MintedTokenOptions) {
|
|
this.scopes = opts.scopes ?? TOKEN_SCOPES;
|
|
this.ttlMs = opts.ttlMs ?? durationMs(TOKEN_TTL_DEFAULT)!;
|
|
this.leaseMs = opts.leaseMs ?? durationMs(MINT_LEASE_DEFAULT)!;
|
|
this.holder = opts.holder ?? `${process.env.MESH_NODE || "unknown"}/${process.pid}`;
|
|
this.now = opts.now ?? (() => new Date());
|
|
this.log = opts.log ?? ((line) => console.log(`[gitea] ${line}`));
|
|
this.fetchImpl = opts.fetch ?? fetch;
|
|
}
|
|
|
|
/** The account this source mints for. */
|
|
get account(): string {
|
|
return this.opts.account;
|
|
}
|
|
|
|
/**
|
|
* The tools' token from the runtime's environment: the forge's URL, the admin login and password file the manifest
|
|
* hands the runtime, the vault and the lease over the bus. Throws, naming what is missing, rather than hand back a
|
|
* source that cannot mint. One source per account and runtime state in a process: two would each renew on a 401.
|
|
*/
|
|
static fromEnv(url: string, env: NodeJS.ProcessEnv = process.env): MintedToken {
|
|
const account = env.MESH_GITEA_TOOLS_USER || TOOLS_ACCOUNT;
|
|
const { admin, passwordFile } = adminFromEnv(env, "no Gitea token, and nothing to mint one with — set GITEA_TOKEN, or");
|
|
const key = `${account} ${env.MESH_GITEA_STATE_DIR ?? ""}`;
|
|
const shared = MintedToken.shared.get(key);
|
|
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,
|
|
// GiteaAdmin is loaded when first used: client.ts imports this file.
|
|
setUp: async (password) => {
|
|
const { GiteaAdmin } = await import("./client.js");
|
|
await setUpToolsAccount(new GiteaAdmin(url, admin, password), account, () => randomBytes(24).toString("base64url"), keepMainRules(env));
|
|
},
|
|
});
|
|
MintedToken.shared.set(key, source);
|
|
return source;
|
|
}
|
|
|
|
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"> {
|
|
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,
|
|
};
|
|
}
|
|
|
|
/** The token held, read from the vault when none is, minted when the vault holds none or one older than token-ttl. */
|
|
async current(): Promise<string> {
|
|
if (this.held !== null && !this.expired(this.held)) return this.held.token;
|
|
const kept = await this.opts.vault.get(this.opts.account);
|
|
if (kept === null) return this.mint("the vault holds no token for this account — minting one", null);
|
|
if (this.expired(kept)) return this.mint(`the vault's token is older than token-ttl (${this.ttlMs / 1000}s) — minting one`, kept.token);
|
|
if (!sameScopes(kept.scopes, this.scopes)) {
|
|
return this.mint(`the vault's token was minted with other scopes than the tools take now (${kept.scopes.join(", ") || "none kept"}) — minting one with them`, kept.token);
|
|
}
|
|
if (this.held === null) {
|
|
this.log(`reusing the token the vault keeps as ${vaultName(this.opts.account)} (generation ${kept.generation})`);
|
|
// A retirement of the admin's old token that failed after the mint is tried again, once a process.
|
|
if (this.retireFile && existsSync(this.retireFile)) await this.retireAdmin().catch((err) => this.log(`${err}`));
|
|
}
|
|
this.held = kept;
|
|
return kept.token;
|
|
}
|
|
|
|
async renew(rejected: string): Promise<string> {
|
|
// Another caller already renewed while this one was in flight with the old token.
|
|
if (this.held !== null && this.held.token !== rejected) return this.held.token;
|
|
// A refusal of a stale token mints nothing: the vault's newer one is used (§808).
|
|
const kept = await this.opts.vault.get(this.opts.account);
|
|
if (kept !== null && kept.token !== rejected) {
|
|
this.held = kept;
|
|
this.log(`the forge rejected the token held; the vault's ${vaultName(this.opts.account)} is newer (generation ${kept.generation}) — reusing it`);
|
|
return kept.token;
|
|
}
|
|
this.held = null;
|
|
return this.mint("the forge rejected the vault's token — minting a fresh one", rejected);
|
|
}
|
|
|
|
/** What the forge's scoped tokens say when a kept token predates a scope the tools now need. */
|
|
static lacksScope(status: number, body: string): boolean {
|
|
return status === 403 && /required scope/i.test(body);
|
|
}
|
|
|
|
private expired(t: VaultToken): boolean {
|
|
const at = Date.parse(t.changedAt);
|
|
return Number.isFinite(at) && this.now().getTime() - at > this.ttlMs;
|
|
}
|
|
|
|
/**
|
|
* One mint at a time: concurrent calls in this process share it, and a mint in another process is waited for (the
|
|
* lease). Holding the lease, the vault is read again: a token there that is not `stale` (the one refused or expired)
|
|
* was minted by the process that held the lease before — it is used, not minted over.
|
|
*/
|
|
private mint(why: string, stale: string | null): Promise<string> {
|
|
if (this.inflight === null) {
|
|
this.log(why);
|
|
this.inflight = this.leased(stale).finally(() => {
|
|
this.inflight = null;
|
|
});
|
|
}
|
|
return this.inflight;
|
|
}
|
|
|
|
private async leased(stale: string | null): Promise<string> {
|
|
for (;;) {
|
|
if (await this.opts.lease.take(this.holder, this.leaseMs)) {
|
|
try {
|
|
const kept = await this.opts.vault.get(this.opts.account);
|
|
if (kept !== null && kept.token !== stale && !this.expired(kept) && sameScopes(kept.scopes, this.scopes)) {
|
|
this.held = kept;
|
|
this.log(`another process minted it meanwhile — reusing the vault's generation ${kept.generation}`);
|
|
return kept.token;
|
|
}
|
|
return await this.doMint(kept);
|
|
} finally {
|
|
await this.opts.lease.release(this.holder).catch((err) =>
|
|
this.log(`the mint lease could not be deleted; it ends with mint-lease — ${err instanceof Error ? err.message : err}`));
|
|
}
|
|
}
|
|
const other = await this.opts.lease.read().catch(() => null);
|
|
this.log(`another process holds the mint lease${other ? ` (${other.holder} since ${other.since})` : ""} — waiting for it, at most mint-lease (${this.leaseMs / 1000}s)`);
|
|
await this.opts.lease.changed(this.leaseMs);
|
|
const kept = await this.opts.vault.get(this.opts.account);
|
|
if (kept !== null && kept.token !== stale && !this.expired(kept) && sameScopes(kept.scopes, this.scopes)) {
|
|
this.held = kept;
|
|
this.log(`the process that held the mint lease minted generation ${kept.generation} — reusing it`);
|
|
return kept.token;
|
|
}
|
|
}
|
|
}
|
|
|
|
/** The admin password, read now. */
|
|
private password(): string {
|
|
try {
|
|
return readFileSync(this.opts.passwordFile, "utf8").replace(/\n$/, "");
|
|
} catch (err) {
|
|
throw new Error(`cannot read the admin password at ${this.opts.passwordFile}: ${(err as Error).message}`);
|
|
}
|
|
}
|
|
|
|
/** One call to the forge's API with the admin login. */
|
|
private adminCall(password = this.password()): AdminCall {
|
|
const authorization = "Basic " + Buffer.from(`${this.opts.admin}:${password}`).toString("base64");
|
|
const api = `${this.opts.url.replace(/\/+$/, "")}/api/v1`;
|
|
const admin: AdminCall = async (method, path, body) => {
|
|
const res = await this.fetchImpl(api + path, {
|
|
method,
|
|
headers: { "Content-Type": "application/json", Authorization: authorization },
|
|
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
});
|
|
const text = await res.text();
|
|
let parsed: any = null;
|
|
if (text) {
|
|
try { parsed = JSON.parse(text); } catch { parsed = text; }
|
|
}
|
|
return { status: res.status, body: parsed };
|
|
};
|
|
return admin;
|
|
}
|
|
|
|
/** Where a retirement of the admin's old token that failed is remembered, to be tried again (retireAdmin). */
|
|
private get retireFile(): string | null {
|
|
return this.opts.stateDir ? join(this.opts.stateDir, `${this.opts.account}.retire-admin`) : null;
|
|
}
|
|
|
|
/**
|
|
* The admin's own token named `mesh-tools` goes: what the tools used before must not outlive the move (novox/hq ADR
|
|
* 0365 §2). Run after the account's token is minted and kept, so a failure here never leaves the tools without a
|
|
* token: it is said, remembered, and tried again when a process next reads the vault's token.
|
|
*/
|
|
private async retireAdmin(admin: AdminCall = this.adminCall()): Promise<void> {
|
|
if (this.opts.oldName !== TOKEN_NAME) return;
|
|
try {
|
|
const retired = await this.dropNamed(admin, `/users/${encodeURIComponent(this.opts.admin)}/tokens`, this.opts.admin, TOKEN_NAME);
|
|
if (retired > 0) this.log(`deleted ${retired} token(s) named "${TOKEN_NAME}" the admin account "${this.opts.admin}" held: the tools act as "${this.opts.account}" now`);
|
|
if (this.retireFile) rmSync(this.retireFile, { force: true });
|
|
} catch (err) {
|
|
if (this.retireFile) {
|
|
mkdirSync(this.opts.stateDir!, { recursive: true, mode: 0o700 });
|
|
writeFileSync(this.retireFile, `${new Date().toISOString()}\n`, { mode: 0o600 });
|
|
}
|
|
this.log(`FAILED to delete the token(s) named "${TOKEN_NAME}" the admin account "${this.opts.admin}" holds — tried again at the next start: ${(err as Error).message}`);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Mint `<account>-<generation>` (the generation this own-put makes), write it through own-put, and only then delete
|
|
* at the forge, by id, the token it replaces: `replaced`'s by its name, or at the first mint the tokens under the
|
|
* account's old fixed name (H-A-422 (2), H-A-430 (1)).
|
|
*/
|
|
private async doMint(replaced: VaultToken | null): Promise<string> {
|
|
const password = this.password();
|
|
const admin = this.adminCall(password);
|
|
const account = this.opts.account;
|
|
const tokens = `/users/${encodeURIComponent(account)}/tokens`;
|
|
const generation = (replaced?.generation ?? 0) + 1;
|
|
const name = mintName(account, generation);
|
|
|
|
// The account and its team first (novox/hq ADR 0365 §2): a failure here fails the mint, tried again at the next call.
|
|
const me = await admin("GET", "/user");
|
|
if (me.status === 401 || me.status === 403) throw new AdminRefused(this.opts.admin, me.status);
|
|
await this.opts.setUp?.(password);
|
|
|
|
let res = await admin("POST", tokens, { name, scopes: this.scopes });
|
|
if (res.status === 401 || res.status === 403) throw new AdminRefused(this.opts.admin, res.status);
|
|
if (res.status === 400 || res.status === 422) {
|
|
// A mint of this generation whose own-put never landed left its token at the forge, unused: deleted by its id
|
|
// (gitea refuses a delete by a name held twice), then minted again.
|
|
await this.dropNamed(admin, tokens, account, name, true);
|
|
res = await admin("POST", tokens, { name, scopes: this.scopes });
|
|
}
|
|
if (res.status !== 201 && res.status !== 200) {
|
|
throw new Error(`Gitea POST /users/${account}/tokens: ${res.status} ${detail(res.body)}`);
|
|
}
|
|
const token = typeof res.body?.sha1 === "string" ? res.body.sha1 : null;
|
|
if (!token) throw new Error(`Gitea POST /users/${account}/tokens: ${res.status} but no token in the reply`);
|
|
|
|
const kept = await this.opts.vault.put(account, token, this.scopes);
|
|
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)}`);
|
|
|
|
// Only now, with the new token kept, does the one it replaces go.
|
|
const gone = replaced ? mintName(account, replaced.generation) : this.opts.oldName;
|
|
try {
|
|
const dropped = await this.dropNamed(admin, tokens, account, gone);
|
|
if (dropped > 0) this.log(`deleted ${dropped} token(s) named "${gone}" "${account}" held: ${name} replaces them`);
|
|
} catch (err) {
|
|
this.log(`FAILED to delete the token "${gone}" ${name} replaces; the forge holds both until the next mint — ${(err as Error).message}`);
|
|
}
|
|
await this.retireAdmin(admin);
|
|
return token;
|
|
}
|
|
|
|
/** Delete every token named `name` an account holds, each by its id; answers how many. */
|
|
private async dropNamed(admin: AdminCall, tokens: string, account: string, name: string, replacing = false): Promise<number> {
|
|
const held: number[] = [];
|
|
for (let page = 1; page <= 100; page++) {
|
|
const listed = await admin("GET", `${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 (t?.name === name && typeof t.id === "number") held.push(t.id);
|
|
}
|
|
if (replacing) this.log(`the forge already holds ${held.length} token(s) named "${name}" — deleting each by its id and minting one`);
|
|
for (const id of held) {
|
|
const dropped = await admin("DELETE", `${tokens}/${id}`);
|
|
if (dropped.status !== 204 && dropped.status !== 404) {
|
|
throw new Error(`Gitea DELETE /users/${account}/tokens/${id} (named ${name}): ${dropped.status} ${detail(dropped.body)}`);
|
|
}
|
|
}
|
|
return held.length;
|
|
}
|
|
}
|
|
|
|
/** The admin login and password file the manifest hands the runtime, or an error naming what is missing. */
|
|
export function adminFromEnv(env: NodeJS.ProcessEnv, missingWords: string): { admin: string; passwordFile: string } {
|
|
const admin = env.MESH_GITEA_ADMIN_USER;
|
|
const passwordFile = env.MESH_GITEA_ADMIN_PASSWORD_FILE;
|
|
const missing = [admin ? null : "MESH_GITEA_ADMIN_USER", passwordFile ? null : "MESH_GITEA_ADMIN_PASSWORD_FILE"]
|
|
.filter((v): v is string => v !== null);
|
|
if (missing.length) throw new Error(`${missingWords} ${missing.join(", ")}`);
|
|
return { admin: admin!, passwordFile: passwordFile! };
|
|
}
|
|
|
|
// One vault and one lease a process, shared by both accounts' sources: one key and one watch.
|
|
let vaultOnce: TokenVault | undefined;
|
|
let leaseOnce: MintLease | undefined;
|
|
function sharedVault(): TokenVault {
|
|
return (vaultOnce ??= vaultOverBus());
|
|
}
|
|
function sharedLease(): MintLease {
|
|
return (leaseOnce ??= leaseOverState());
|
|
}
|
|
|
|
/** The tool forge_token_lease's reading (§808): the lease's holder and since when, and each account's token age, read
|
|
* from the vault's `changed-at`; never the token. */
|
|
export async function tokenLease(vault: TokenVault, lease: MintLease, accounts: readonly string[], now: Date = new Date()) {
|
|
const held = await lease.read();
|
|
const out: { account: string; vault: string; generation?: number; "changed-at"?: string; "age-seconds"?: number; held: boolean }[] = [];
|
|
for (const account of accounts) {
|
|
const t = await vault.get(account);
|
|
out.push(t === null ? { account, vault: vaultName(account), held: false } : {
|
|
account, vault: vaultName(account), held: true, generation: t.generation, "changed-at": t.changedAt,
|
|
"age-seconds": Math.max(0, Math.floor((now.getTime() - Date.parse(t.changedAt)) / 1000)),
|
|
});
|
|
}
|
|
return { lease: held === null ? { held: false } : { held: true, holder: held.holder, since: held.since }, tokens: out };
|
|
}
|
|
|
|
/** The vault and the lease this process mints through, for the tool forge_token_lease. */
|
|
export function processVaultAndLease(): { vault: TokenVault; lease: MintLease } {
|
|
return { vault: sharedVault(), lease: sharedLease() };
|
|
}
|
|
|
|
function detail(body: unknown): string {
|
|
return typeof body === "string" ? body : JSON.stringify(body);
|
|
}
|