From 9dcb39ecf1c25abb0507eb8d417e788c02b97e03 Mon Sep 17 00:00:00 2001 From: Jack Zhuang <50353452+hotlong@users.noreply.github.com> Date: Tue, 22 Sep 2026 11:25:11 +0800 Subject: [PATCH 1/7] feat(pm): fleet GitHub writes act as objectstack-fleet[bot] behind one fleet-wide write gate MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two seat accounts were restricted by the platform in one day. The token the seats wrote with was user-to-server (every write booked against a person), and the trigger was rate SHAPE, not quota: 17 issues in 29 s from N processes each pacing itself. This lands both halves of the answer. - scripts/pm/fleet-token.mjs: an RS256 App JWT on node crypto (no dependency); the installation token minted and cached at 0600, refreshed five minutes early, minting serialised through the write lease; --export / --print / --status; PEM, PEM-with-literal-\n and base64 key forms; every log, status, error and stack redacted, with a self-test that feeds a known token and key through every output path and greps them all. - scripts/pm/write-pace.mjs: rule 4, the fleet-wide LEASE (one write in flight, FIFO tickets, dead-holder reaping, a bounded wait that refuses loudly) and rule 5, BATCH MODE (N >= 5 raises the gap to 30 s for the next N writes, announced with the count and the estimate, fleet-wide through the shared log); --run for shell callers; the self-test measures both on real child processes by their timestamps. - scripts/pm/issue-create.mjs: the one door a new card leaves through: prose from files never argv, one POST behind both halves of the throttle, a read-back, the exit-code ladder. - scripts/pm/with-fleet.sh + fleet-git-credential.sh: mint, export (the existing GITHUB_TOKEN ?? GH_TOKEN call sites change by zero lines), git identity (committer = the bot by its USER id; author = the bot or a real login), git credential through GIT_CONFIG_* env pairs with nothing on disk, then the command behind the gate. - label-write and close-cards release the lease on a transport that threw; AGENTS.md carries the rule; lint.yml runs the three new self-tests. Clause-②: no Claude-Session: https://claude.ai/code/session_local_fce2b4bd-ec0d-4e1c-8395-224cd17995e6 Co-authored-by: Claude --- .github/workflows/lint.yml | 27 +- AGENTS.md | 16 + package.json | 3 + scripts/pm/close-cards.mjs | 3 +- scripts/pm/fleet-git-credential.sh | 40 ++ scripts/pm/fleet-token.mjs | 890 +++++++++++++++++++++++++++++ scripts/pm/issue-create.mjs | 581 +++++++++++++++++++ scripts/pm/label-write.mjs | 3 +- scripts/pm/with-fleet.sh | 278 +++++++++ scripts/pm/write-pace.mjs | 829 +++++++++++++++++++++++++-- 10 files changed, 2619 insertions(+), 51 deletions(-) create mode 100755 scripts/pm/fleet-git-credential.sh create mode 100644 scripts/pm/fleet-token.mjs create mode 100644 scripts/pm/issue-create.mjs create mode 100755 scripts/pm/with-fleet.sh diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 3b98eaca05e..2368f771e79 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -1355,12 +1355,35 @@ jobs: # the throttle would simply stop throttling — which is the shape # `check:self-test-wired` requires this step for. # - # Its last battery is the wiring: the five write transports each call both + # Its last battery is the wiring: the seven write transports each call both # halves, and the roster IS the set of files under scripts/pm that issue a - # write verb, so a SIXTH write path cannot land unpaced. + # write verb, so an EIGHTH write path cannot land unpaced. Two batteries + # run REAL child processes: the lease that keeps one write in flight + # fleet-wide, and the batch gap one process announces and two others obey, + # are claims about separate processes and are measured on separate + # processes, by their timestamps. - name: Write-pace throttle self-test run: pnpm check:pm-write-pace + # The fleet identity and the two doors — same family, same split. The + # minter's LIVE path is a POST to the platform signed with a private key, + # so the offline half is all CI can hold: a throwaway RSA pair, a fake + # platform through every branch, and the assertion that matters most — a + # known token and a known key fed through every output path and grepped + # out of ALL of them. The card-creation door and the shell wrapper both + # pin their wiring into the throttle above; the wrapper's self-test reads a + # fixture cache in place of the platform and proves what git sees (the + # bot as committer, no token in any remote or config file, a credential + # helper reached from the environment alone). + - name: Fleet token minter self-test + run: pnpm check:pm-fleet-token + + - name: Issue-create door self-test + run: pnpm check:pm-issue-create + + - name: with-fleet wrapper self-test + run: pnpm check:pm-with-fleet + - name: Stamped-post helper self-test run: pnpm check:pm-post-stamped diff --git a/AGENTS.md b/AGENTS.md index d2f42322601..b835b297c94 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -413,6 +413,22 @@ and posts a `Release:` line. Findings are filed unassigned; assign at the moment maintainer's own work under the shared account carries no claim comment and is indistinguishable from a dispatch — an accepted blind spot; per-seat identities are not introduced. +**Every GitHub write leaves through `scripts/pm/`, as the fleet's App identity, behind one shared +write gate — properties of the path, not of whoever remembered them.** A seat's writes act as +`objectstack-fleet[bot]`: `scripts/pm/fleet-token.mjs` mints the installation token from +`OS_FLEET_APP_ID`, `OS_FLEET_INSTALLATION_ID` and `OS_FLEET_PRIVATE_KEY` (PEM or base64), caches +it at mode 0600 and refreshes it early, and nothing is written under a person; +`scripts/pm/write-pace.mjs` serialises every write verb fleet-wide (one in flight), spaces them, +raises the gap for an announced batch and refuses on a platform back-off — its header is the +authority on every number. Use the tool that owns the write: `issue-create.mjs` for a new card, +`label-write.mjs` for labels and assignees, `post-stamped.mjs` for comments and bodies, +`close-cards.mjs` for closures; for a write no tool owns — a push, a PR flag, an auto-merge arm — +`scripts/pm/with-fleet.sh -- `, which mints, exports the identity for `gh` and `git`, +and runs the command behind the gate (`--read` for reads, which are never gated). ⛔ Never a bare +`curl`, `fetch` or `gh api -X POST|PATCH|PUT|DELETE` write from a seat; ⛔ never a token in a +remote URL, in a `git config` value on disk, or in a log line — the wrapper hands git its +credential through the environment, and `git remote -v` stays token-free. + **State on your PR that you did not set belongs to another actor — ask, never "correct" it.** Under one shared identity every other participant's write arrives unsigned: the PM flipping your draft to ready and arming auto-merge, a bot re-labelling, the platform diff --git a/package.json b/package.json index 65b1597536a..433c434a511 100644 --- a/package.json +++ b/package.json @@ -88,6 +88,9 @@ "check:pm-closed-card-sweep": "node scripts/pm/sweep-closed-cards.mjs --self-test", "check:pm-stale-finding": "node scripts/pm/sweep-stale-finding.mjs --self-test", "check:pm-write-pace": "node scripts/pm/write-pace.mjs --self-test", + "check:pm-fleet-token": "node scripts/pm/fleet-token.mjs --self-test", + "check:pm-issue-create": "node scripts/pm/issue-create.mjs --self-test", + "check:pm-with-fleet": "bash scripts/pm/with-fleet.sh --self-test", "check:pm-post-stamped": "node scripts/pm/post-stamped.mjs --self-test", "check:pm-label-write": "node scripts/pm/label-write.mjs --self-test", "check:pm-close-cards": "node scripts/pm/close-cards.mjs --self-test", diff --git a/scripts/pm/close-cards.mjs b/scripts/pm/close-cards.mjs index aa64b0d9935..87e20ea3dee 100644 --- a/scripts/pm/close-cards.mjs +++ b/scripts/pm/close-cards.mjs @@ -141,7 +141,7 @@ import { resolveSweepRepo, } from './check-half-states.mjs'; import { classifyHttp, parseOptions as parseLabelWriteOptions, runLabelWrite } from './label-write.mjs'; -import { isWriteMethod, noteResponse, paceWrite } from './write-pace.mjs'; +import { isWriteMethod, noteResponse, paceWrite, releaseWriteLease } from './write-pace.mjs'; import { EXIT_NOT_STORED as POST_STAMPED_EXIT_NOT_STORED, STAMP_TOKEN, @@ -455,6 +455,7 @@ async function rest(path, { method = 'GET', body = null } = {}) { ...(body ? { body: JSON.stringify(body) } : {}), }); } catch (e) { + if (paced) releaseWriteLease(); // ⏱ rule ④: no response will come, so the fleet's turn ends here return { status: 0, rateRemaining: null, json: null, detail: e?.message ?? 'fetch threw', call: `${method} ${path}` }; } const rateRemaining = res.headers.get('x-ratelimit-remaining'); diff --git a/scripts/pm/fleet-git-credential.sh b/scripts/pm/fleet-git-credential.sh new file mode 100755 index 00000000000..00310efc68c --- /dev/null +++ b/scripts/pm/fleet-git-credential.sh @@ -0,0 +1,40 @@ +#!/usr/bin/env bash +# fleet-git-credential.sh — the git credential helper `with-fleet.sh` hands git +# through the ENVIRONMENT, so a push can act as the fleet's App identity with +# nothing on disk: no token in a remote URL, no `git config` value in any file, +# and `git remote -v` unchanged. +# +# printf 'protocol=https\nhost=github.com\n' | GITHUB_TOKEN=… fleet-git-credential.sh get +# → username=x-access-token +# password=… +# +# git calls it as ` get` with the request on stdin. It answers ONLY for +# github.com (and its subdomains), ONLY for `get`, and ONLY when `GITHUB_TOKEN` +# is set — every other case prints nothing, which git reads as "this helper has +# no opinion" and moves on. `store` and `erase` are ignored on purpose: a token +# that lives fifty-five minutes has nothing to store and nothing to erase. +# +# ⛔ The token is read from the environment at the moment git asks and is +# written to stdout for git alone. It appears in no argument, no file and no +# log line of this script. + +set -euo pipefail + +op="${1:-get}" +[[ "$op" == get ]] || exit 0 + +host='' +while IFS= read -r line; do + case "$line" in + host=*) host="${line#host=}" ;; + esac +done + +case "$host" in + github.com | *.github.com) ;; + *) exit 0 ;; +esac + +[[ -n "${GITHUB_TOKEN:-}" ]] || exit 0 + +printf 'username=x-access-token\npassword=%s\n' "$GITHUB_TOKEN" diff --git a/scripts/pm/fleet-token.mjs b/scripts/pm/fleet-token.mjs new file mode 100644 index 00000000000..2ff2ecce43a --- /dev/null +++ b/scripts/pm/fleet-token.mjs @@ -0,0 +1,890 @@ +#!/usr/bin/env node +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * fleet-token — the fleet's GitHub identity, minted from the App and never from a person. + * + * node scripts/pm/fleet-token.mjs --export # `export GITHUB_TOKEN=…` lines, for `eval "$(…)"` + * node scripts/pm/fleet-token.mjs --print # the token alone on stdout, nothing else + * node scripts/pm/fleet-token.mjs --status # the cache, REDACTED: expiry, identity, permissions + * node scripts/pm/fleet-token.mjs --refresh # mint now, whatever the cache says + * node scripts/pm/fleet-token.mjs --self-test # offline: a throwaway RSA key, a fake platform, no network + * + * ## Why an App identity, and why an installation token specifically + * + * Two seat accounts were restricted by the platform in one day. The token the + * seats wrote with was USER-TO-SERVER — issued by a GitHub App, but acting as a + * person: `GET /user` answered a login, `X-OAuth-Scopes` was empty, + * `X-RateLimit-Limit` read 15000 and an expiry header was present — so every + * write was booked against that person, and the person was the thing the + * platform restricted. A SERVER-TO-SERVER installation token has nobody behind + * it: `GET /user` answers 403, the actor of every write is the App's bot user + * (`objectstack-fleet[bot]`), and a push made with it still dispatches + * workflows — the recursion guard that silences pushes applies only to the + * `GITHUB_TOKEN` Actions itself injects, never to an App of our own. + * + * The rate SHAPE that triggered the restriction is `write-pace.mjs`'s subject + * (its header carries the reading); this file's subject is the identity. + * + * ## Inputs — environment only, ⛔ none of them is ever committed + * + * OS_FLEET_APP_ID the App's numeric id (the JWT's `iss`) + * OS_FLEET_INSTALLATION_ID the installation on the organization + * OS_FLEET_PRIVATE_KEY the App's private key, in any of three spellings: + * PEM text; PEM with literal `\n` sequences (what + * most secret stores make of a multi-line value); + * or base64 of the PEM. Detected, never declared. + * OS_FLEET_API_URL optional; default https://api.github.com + * OS_FLEET_TOKEN_CACHE_FILE optional; default ~/.cache/objectstack-pm/fleet-token.json + * OS_FLEET_GIT_AUTHOR_LOGIN optional; a real login recorded as the commit + * AUTHOR by `with-fleet.sh` (the committer stays + * the bot, and so does the actor of every write) + * + * The private key is needed only to MINT. A fresh cache for the same + * installation serves `--print` / `--export` with the app and installation ids + * alone — which is what lets `with-fleet.sh --self-test` run offline. + * + * ## The JWT — node's `crypto`, no dependency + * + * RS256 over `base64url(header).base64url(payload)`; `iat = now − 60` (clock + * drift), `exp = now + 600` (the platform's ceiling — a longer one is refused + * by it, and by `buildAppJwt`), `iss = OS_FLEET_APP_ID`. `--self-test` + * generates a throwaway key pair and VERIFIES the signature with the public + * half, so the encoding is proven rather than eyeballed. + * + * ## The cache, and why the mint goes through the write gate + * + * `~/.cache/objectstack-pm/fleet-token.json` — beside `write-pace.jsonl`, for + * the same reason it lives there: every process on this host shares ONE + * throttle and should share ONE token, so a per-session scratchpad would mint + * once per session and let N sessions mint at once. Mode 0600, written to a + * temp file and renamed, refreshed `REFRESH_MARGIN_MS` (5 min) before expiry. + * + * The mint is a POST, and `write-pace.mjs` pins the closed set of files under + * `scripts/pm` that issue a write verb — so the mint is paced like any other, + * keyed to the App rather than to a token (it is not content and shares no + * budget with content). That pacing takes rule ④'s LEASE, which is exactly the + * cross-process lock a concurrent start needs: after the lease is granted the + * cache is READ AGAIN, and a sibling's fresh mint is used instead of a second + * one. + * + * ## Redaction — the rule every output path obeys + * + * The token is written to exactly three places: the cache file, and the two + * delivery modes `--print` and `--export`, whose whole purpose is to hand it + * to the caller. Every OTHER string this file produces — log lines, `--status`, + * error messages, the message of any thrown error — shows `redact(token)`: + * the first four characters and the length. Platform error bodies and thrown + * transport messages are scrubbed of the token and the JWT before they are + * re-thrown. `--self-test` feeds a known token and a known key through every + * one of those paths and greps them all. + * + * ## Exit codes — capture them BEFORE any pipe (label-write's ladder) + * + * 0 the token was delivered (or `--status`, or a self-test that reached its verdict). + * 2 usage. + * 3 PREREQUISITE NOT MET — an input missing or unreadable, the platform + * unreachable, the cache path unwritable, a rate-limit refusal. Nothing + * was minted and nothing is claimed. + * 5 the platform REFUSED the mint or the identity read — a 401 on the JWT, + * a 403/404 on the installation, a 422. The status and the platform's + * own sentence are printed, scrubbed. + * 10 the write throttle refused the mint (a stop marker is active, or no + * turn on the lease). `write-pace.mjs`'s prescription was printed. + */ + +import { spawnSync } from 'node:child_process'; +import { createPrivateKey, generateKeyPairSync, sign as cryptoSign, verify as cryptoVerify } from 'node:crypto'; +import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'; +import { homedir, tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; +import process from 'node:process'; +import { fileURLToPath } from 'node:url'; + +import { isEntrypoint } from '../invoked-as.mjs'; +import { EXIT_PREREQUISITE_NOT_MET, PROXY_FLAG, proxyRearmPlan } from './check-half-states.mjs'; +import { classifyHttp } from './label-write.mjs'; +import { EXIT_WRITE_PACE_REFUSED, isWriteMethod, noteResponse, paceFilePath, paceWrite, releaseWriteLease } from './write-pace.mjs'; + +const SELF_PATH = fileURLToPath(import.meta.url); +const PROXY_REARM_GUARD = 'OS_FLEET_TOKEN_PROXY_REARMED'; + +export const EXIT_OK = 0; +export const EXIT_USAGE = 2; +export const EXIT_PREREQUISITE = EXIT_PREREQUISITE_NOT_MET; +export const EXIT_PLATFORM_REFUSAL = 5; + +export const DEFAULT_API = 'https://api.github.com'; +export const JWT_TTL_S = 600; +export const JWT_BACKDATE_S = 60; +export const REFRESH_MARGIN_MS = 5 * 60 * 1000; +export const REQUIRED_INPUTS = Object.freeze(['OS_FLEET_APP_ID', 'OS_FLEET_INSTALLATION_ID']); +export const MINT_INPUT = 'OS_FLEET_PRIVATE_KEY'; + +/** A failure with the exit code it maps to. Its message is ALREADY redacted. */ +export class FleetTokenError extends Error { + constructor(message, exitCode) { + super(message); + this.name = 'FleetTokenError'; + this.exitCode = exitCode; + } +} + +// --------------------------------------------------------------------------- +// Pure core — the encoding, the claims, the key forms, the cache arithmetic and +// the redaction, each a function `--self-test` drives with fixtures. +// --------------------------------------------------------------------------- + +/** What a token looks like anywhere but the cache file and the delivery modes. */ +export function redact(token) { + const t = String(token ?? ''); + if (!t) return '(empty)'; + return `${t.slice(0, 4)}…(${t.length} chars)`; +} + +/** + * Remove every secret from a string that is about to be printed or thrown: + * the secrets this process KNOWS (the JWT, the token once minted), and any + * token-SHAPED run it does not — a platform sentence or a transport error can + * echo a credential this process never saw. + */ +export function scrub(text, secrets = []) { + let out = String(text ?? ''); + for (const s of secrets) { + if (typeof s !== 'string' || s.length < 8) continue; + out = out.split(s).join(''); + } + return out.replace(/\bgh[a-z]_[A-Za-z0-9_]{20,}\b/g, '').replace(/\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/g, ''); +} + +export function base64url(input) { + return Buffer.from(input).toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_'); +} + +export function fromBase64url(text) { + const padded = String(text).replace(/-/g, '+').replace(/_/g, '/'); + return Buffer.from(padded + '='.repeat((4 - (padded.length % 4)) % 4), 'base64'); +} + +/** + * The private key, from any of the three spellings. Returns the key object and + * which spelling arrived, and never the PEM text — the caller has no reason to + * hold it. + */ +export function readPrivateKey(raw) { + const text = String(raw ?? '').trim(); + if (!text) throw new FleetTokenError(`${MINT_INPUT} is empty`, EXIT_PREREQUISITE); + let pem = null; + let form = 'pem'; + if (text.includes('-----BEGIN')) { + pem = text; + } else { + let decoded = ''; + try { + decoded = Buffer.from(text, 'base64').toString('utf8'); + } catch { + decoded = ''; + } + if (decoded.includes('-----BEGIN')) { + pem = decoded; + form = 'base64'; + } + } + if (pem === null) { + throw new FleetTokenError(`${MINT_INPUT} is neither a PEM (no -----BEGIN line) nor base64 of one`, EXIT_PREREQUISITE); + } + if (pem.includes('\\n')) { + pem = pem.replace(/\\n/g, '\n'); + if (form === 'pem') form = 'pem-escaped'; + } + pem = `${pem.replace(/\r\n?/g, '\n').trim()}\n`; + let key; + try { + key = createPrivateKey(pem); + } catch (e) { + throw new FleetTokenError(`${MINT_INPUT} does not parse as a private key (${e?.message ?? 'unreadable'})`, EXIT_PREREQUISITE); + } + if (key.asymmetricKeyType !== 'rsa') { + throw new FleetTokenError(`${MINT_INPUT} is a ${key.asymmetricKeyType} key, and RS256 needs RSA`, EXIT_PREREQUISITE); + } + return { key, form }; +} + +/** The App JWT: RS256, backdated `iat`, an `exp` at or under the platform's ceiling. */ +export function buildAppJwt({ appId, key, nowS = Math.floor(Date.now() / 1000), ttlS = JWT_TTL_S } = {}) { + if (!Number.isInteger(ttlS) || ttlS <= 0 || ttlS > JWT_TTL_S) { + throw new RangeError(`a JWT lifetime over ${JWT_TTL_S}s is refused by the platform; got ${JSON.stringify(ttlS)}`); + } + const header = { alg: 'RS256', typ: 'JWT' }; + const payload = { iat: nowS - JWT_BACKDATE_S, exp: nowS + ttlS, iss: String(appId) }; + const signingInput = `${base64url(JSON.stringify(header))}.${base64url(JSON.stringify(payload))}`; + const signature = cryptoSign('RSA-SHA256', Buffer.from(signingInput), key); + return { jwt: `${signingInput}.${base64url(signature)}`, header, payload }; +} + +export function decodeJwt(jwt) { + const [h, p, s] = String(jwt).split('.'); + return { + header: JSON.parse(fromBase64url(h).toString('utf8')), + payload: JSON.parse(fromBase64url(p).toString('utf8')), + signature: s, + signingInput: `${h}.${p}`, + }; +} + +/** Does `publicKey` verify this JWT? The self-test's proof that the encoding is right. */ +export function verifyJwt(jwt, publicKey) { + const d = decodeJwt(jwt); + return cryptoVerify('RSA-SHA256', Buffer.from(d.signingInput), publicKey, fromBase64url(d.signature)); +} + +/** Where the cache lives for this environment. */ +export function cacheFilePath(env = process.env, home = homedir()) { + const override = typeof env.OS_FLEET_TOKEN_CACHE_FILE === 'string' ? env.OS_FLEET_TOKEN_CACHE_FILE.trim() : ''; + return override || join(home, '.cache', 'objectstack-pm', 'fleet-token.json'); +} + +/** Must this cache be replaced? Absent, unreadable, foreign, or inside the margin all say yes. */ +export function needsRefresh(cache, nowMs, { marginMs = REFRESH_MARGIN_MS, installationId } = {}) { + if (!cache || typeof cache !== 'object') return true; + if (typeof cache.token !== 'string' || !cache.token) return true; + if (!cache.bot || typeof cache.bot.login !== 'string' || !Number.isInteger(Number(cache.bot.id))) return true; + if (installationId !== undefined && String(cache.installation_id) !== String(installationId)) return true; + const exp = Date.parse(cache.expires_at); + if (!Number.isFinite(exp)) return true; + return exp - nowMs <= marginMs; +} + +export function readCache(file) { + try { + const parsed = JSON.parse(readFileSync(file, 'utf8')); + return parsed && typeof parsed === 'object' ? parsed : null; + } catch { + return null; + } +} + +/** Written to a sibling temp file at 0600 and renamed, so a reader never sees a torn cache. */ +export function writeCache(file, data) { + mkdirSync(dirname(file), { recursive: true, mode: 0o700 }); + const tmp = `${file}.tmp.${process.pid}`; + writeFileSync(tmp, `${JSON.stringify(data, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 }); + chmodSync(tmp, 0o600); + renameSync(tmp, file); +} + +/** The inputs, validated. `mint: true` also demands the private key. */ +export function readInputs(env = process.env, { mint = true } = {}) { + const missing = REQUIRED_INPUTS.filter((name) => !String(env[name] ?? '').trim()); + if (mint && !String(env[MINT_INPUT] ?? '').trim()) missing.push(MINT_INPUT); + if (missing.length) { + throw new FleetTokenError( + `missing ${missing.join(', ')} — the fleet identity is injected as environment variables (` + + `${[...REQUIRED_INPUTS, MINT_INPUT].join(', ')}); nothing was minted.`, + EXIT_PREREQUISITE, + ); + } + const appId = String(env.OS_FLEET_APP_ID).trim(); + const installationId = String(env.OS_FLEET_INSTALLATION_ID).trim(); + if (!/^\d+$/.test(appId)) throw new FleetTokenError('OS_FLEET_APP_ID must be the App\'s numeric id', EXIT_PREREQUISITE); + if (!/^\d+$/.test(installationId)) throw new FleetTokenError('OS_FLEET_INSTALLATION_ID must be the installation\'s numeric id', EXIT_PREREQUISITE); + const api = String(env.OS_FLEET_API_URL ?? '').trim().replace(/\/+$/, '') || DEFAULT_API; + const authorLogin = String(env.OS_FLEET_GIT_AUTHOR_LOGIN ?? '').trim() || null; + return { appId, installationId, api, authorLogin, privateKey: mint ? env[MINT_INPUT] : null }; +} + +/** POSIX shell single-quoting, so `eval "$(… --export)"` is exact for any byte. */ +export function shellQuote(value) { + return `'${String(value).replace(/'/g, "'\\''")}'`; +} + +/** The `--export` text. The ONE place besides `--print` where the token is spelled out. */ +export function exportLines(cache) { + const lines = [ + `export GITHUB_TOKEN=${shellQuote(cache.token)}`, + `export GH_TOKEN=${shellQuote(cache.token)}`, + `export OS_FLEET_BOT_LOGIN=${shellQuote(cache.bot.login)}`, + `export OS_FLEET_BOT_USER_ID=${shellQuote(String(cache.bot.id))}`, + `export OS_FLEET_TOKEN_EXPIRES_AT=${shellQuote(cache.expires_at)}`, + ]; + if (cache.author && cache.author.login) { + lines.push( + `export OS_FLEET_GIT_AUTHOR_NAME=${shellQuote(cache.author.name || cache.author.login)}`, + `export OS_FLEET_GIT_AUTHOR_EMAIL=${shellQuote(`${cache.author.id}+${cache.author.login}@users.noreply.github.com`)}`, + ); + } + return `${lines.join('\n')}\n`; +} + +/** `--status`: everything about the cache EXCEPT the token. */ +export function statusText(cache, nowMs, file) { + if (!cache) return [`fleet-token --status`, ` cache : ${file} — absent or unreadable; the next --print / --export mints.`].join('\n'); + const exp = Date.parse(cache.expires_at); + const left = Number.isFinite(exp) ? exp - nowMs : NaN; + const perms = cache.permissions && typeof cache.permissions === 'object' ? Object.entries(cache.permissions).map(([k, v]) => `${k}:${v}`).join(' ') : '(unknown)'; + return [ + 'fleet-token --status', + ` cache : ${file}`, + ` token : ${redact(cache.token)} (⛔ never printed here — --print / --export are the delivery modes)`, + ` expires : ${cache.expires_at ?? '?'}${Number.isFinite(left) ? ` (${left > 0 ? `in ${Math.round(left / 60000)}m` : 'EXPIRED'}; refreshed ${Math.round(REFRESH_MARGIN_MS / 60000)}m early)` : ''}`, + ` identity : ${cache.bot?.login ?? '?'} (user id ${cache.bot?.id ?? '?'}) — App ${cache.app_id ?? '?'}, installation ${cache.installation_id ?? '?'}`, + ` author : ${cache.author?.login ? `${cache.author.login} (user id ${cache.author.id}) — commits will be authored by this login, committed by the bot` : 'the bot (set OS_FLEET_GIT_AUTHOR_LOGIN to record a real login as author)'}`, + ` permissions : ${perms}`, + ` selection : ${cache.repository_selection ?? '?'}`, + ` minted : ${cache.minted_at ?? '?'}`, + ].join('\n'); +} + +// --------------------------------------------------------------------------- +// The live path — one POST (paced, leased) and three GETs, all through an +// injectable `fetch` so the self-test drives every branch offline. +// --------------------------------------------------------------------------- + +/** The platform's remaining-quota header as `classifyHttp` wants it: a number, or `null` when absent. */ +function rateRemainingOf(headers) { + const raw = headers?.get?.('x-ratelimit-remaining') ?? null; + return raw === null || String(raw).trim() === '' ? null : Number(raw); +} + +function exitForStatus(status, headers) { + const verdict = classifyHttp({ status, rateRemaining: rateRemainingOf(headers) }); + if (verdict === 'prerequisite' || verdict === 'ratelimit') return EXIT_PREREQUISITE; + if (status >= 500 || status === 0) return EXIT_PREREQUISITE; + return EXIT_PLATFORM_REFUSAL; +} + +function platformSentence(json) { + if (json && typeof json === 'object' && typeof json.message === 'string') return json.message; + return ''; +} + +/** + * Mint an installation token and resolve the identity behind it. Throws a + * `FleetTokenError` carrying the exit code; every message it throws or logs is + * scrubbed of the JWT and the token. + */ +export async function mintInstallationToken(inputs, deps = {}) { + const fetchImpl = deps.fetch ?? globalThis.fetch; + const now = deps.now ?? (() => Date.now()); + const log = deps.log ?? ((line) => console.error(line)); + const file = deps.file ?? cacheFilePath(deps.env ?? process.env, deps.home ?? homedir()); + const paceDeps = { ...(deps.pace ?? {}) }; + if (!paceDeps.exit) { + paceDeps.exit = (code) => { + throw new FleetTokenError('the write throttle refused the mint — its prescription is above', code); + }; + } + const paceFile = paceDeps.file ?? paceFilePath(paceDeps.env ?? process.env, paceDeps.home ?? homedir()); + const paceToken = `app:${inputs.appId}`; + + const { key, form } = readPrivateKey(inputs.privateKey); + const { jwt } = buildAppJwt({ appId: inputs.appId, key, nowS: Math.floor(now() / 1000) }); + const secrets = [jwt]; + const headers = (bearer) => ({ accept: 'application/vnd.github+json', 'x-github-api-version': '2022-11-28', authorization: `Bearer ${bearer}` }); + const readJson = async (res) => { + try { + return await res.json(); + } catch { + return null; + } + }; + const get = async (path, bearer, what) => { + let res; + try { + res = await fetchImpl(`${inputs.api}${path}`, { method: 'GET', headers: headers(bearer) }); + } catch (e) { + throw new FleetTokenError(`GET ${path} (${what}): the platform could not be reached — ${scrub(e?.message ?? 'fetch threw', secrets)}`, EXIT_PREREQUISITE); + } + const json = await readJson(res); + if (res.status !== 200) { + throw new FleetTokenError(`GET ${path} (${what}) → HTTP ${res.status} ${scrub(platformSentence(json), secrets)}`.trim(), exitForStatus(res.status, res.headers)); + } + return json; + }; + + // ⏱ The one write verb this file issues, paced and leased like every other. + const mintPath = `/app/installations/${inputs.installationId}/access_tokens`; + const mintMethod = 'POST'; + if (isWriteMethod(mintMethod)) await paceWrite({ token: paceToken, kind: 'fleet-token POST' }, paceDeps); + + // Under the lease: a sibling that waited on the same lease may have minted. + if (deps.recheck) { + const sibling = deps.recheck(); + if (!needsRefresh(sibling, now(), { installationId: inputs.installationId })) { + releaseWriteLease(paceFile); + log(`fleet-token: a sibling minted ${redact(sibling.token)} while this process waited — using it, no second mint.`); + return { ...sibling, fresh: false, file }; + } + } + + let res; + try { + res = await fetchImpl(`${inputs.api}${mintPath}`, { method: 'POST', headers: headers(jwt) }); + } catch (e) { + releaseWriteLease(paceFile); + throw new FleetTokenError(`POST ${mintPath}: the platform could not be reached — ${scrub(e?.message ?? 'fetch threw', secrets)}`, EXIT_PREREQUISITE); + } + const minted = await readJson(res); + noteResponse( + { + token: paceToken, + status: res.status, + headers: res.headers, + body: minted, + verdict: classifyHttp({ status: res.status, rateRemaining: rateRemainingOf(res.headers) }), + }, + paceDeps, + ); + if (res.status !== 201 || !minted || typeof minted.token !== 'string' || !minted.token) { + throw new FleetTokenError( + `POST ${mintPath} → HTTP ${res.status} ${scrub(platformSentence(minted), secrets)}`.trim() + + (res.status === 401 ? ' — the JWT was refused: check OS_FLEET_APP_ID and the private key belong to the same App, and the host clock' : '') + + (res.status === 404 ? ' — the installation was not found under this App: check OS_FLEET_INSTALLATION_ID' : ''), + exitForStatus(res.status, res.headers), + ); + } + secrets.push(minted.token); + + // The identity behind the token: the App's slug (JWT), then the bot user + // that slug names (installation token) — its numeric id is what a noreply + // address needs, and it is NOT the App id. + const app = await get('/app', jwt, 'the App'); + const slug = typeof app?.slug === 'string' && app.slug ? app.slug : null; + if (!slug) throw new FleetTokenError('GET /app answered without a slug — cannot name the bot user', EXIT_PLATFORM_REFUSAL); + const botLogin = `${slug}[bot]`; + const bot = await get(`/users/${encodeURIComponent(botLogin)}`, minted.token, 'the bot user'); + if (!Number.isInteger(Number(bot?.id)) || bot?.login !== botLogin) { + throw new FleetTokenError(`GET /users/${botLogin} answered login ${JSON.stringify(bot?.login ?? null)} and id ${JSON.stringify(bot?.id ?? null)} — not the bot user`, EXIT_PLATFORM_REFUSAL); + } + let author = null; + if (inputs.authorLogin) { + const user = await get(`/users/${encodeURIComponent(inputs.authorLogin)}`, minted.token, 'the author login'); + if (!Number.isInteger(Number(user?.id))) throw new FleetTokenError(`GET /users/${inputs.authorLogin} answered without a numeric id`, EXIT_PLATFORM_REFUSAL); + author = { login: String(user.login), id: Number(user.id), name: typeof user.name === 'string' && user.name ? user.name : String(user.login) }; + } + + const cache = { + token: minted.token, + expires_at: minted.expires_at, + permissions: minted.permissions ?? null, + repository_selection: minted.repository_selection ?? null, + app_id: inputs.appId, + installation_id: inputs.installationId, + api: inputs.api, + bot: { login: botLogin, id: Number(bot.id) }, + author, + key_form: form, + minted_at: new Date(now()).toISOString(), + }; + try { + writeCache(file, cache); + } catch (e) { + throw new FleetTokenError(`the cache at ${file} cannot be written (${scrub(e?.message ?? 'write failed', secrets)}) — point OS_FLEET_TOKEN_CACHE_FILE at a writable path; the minted token was discarded`, EXIT_PREREQUISITE); + } + log( + `fleet-token: minted ${redact(minted.token)} for ${botLogin} (App ${inputs.appId}, installation ${inputs.installationId}, key given as ${form}), ` + + `expires ${minted.expires_at}; cached at ${file} (mode 0600).`, + ); + return { ...cache, fresh: true, file }; +} + +/** + * The importable entry: a fresh cached token, or a newly minted one. Throws + * `FleetTokenError` (with `exitCode`) rather than exiting, so an importer keeps + * its own process. + */ +export async function getFleetToken({ force = false } = {}, deps = {}) { + const env = deps.env ?? process.env; + const now = deps.now ?? (() => Date.now()); + const file = deps.file ?? cacheFilePath(env, deps.home ?? homedir()); + const cached = force ? null : readCache(file); + const probe = readInputs(env, { mint: false }); + if (!force && !needsRefresh(cached, now(), { installationId: probe.installationId })) return { ...cached, fresh: false, file }; + const inputs = readInputs(env, { mint: true }); + return mintInstallationToken(inputs, { ...deps, env, file, recheck: force ? null : () => readCache(file) }); +} + +// --------------------------------------------------------------------------- +// Self-test — OFFLINE. A throwaway RSA pair, a fake platform, a temp cache. +// The battery roster is the floor (AGENTS.md, "Writing a --self-test"). +// --------------------------------------------------------------------------- + +const SELF_TEST_BATTERIES = Object.freeze({ + 'the JWT: RS256 over node crypto, the claims the platform reads, no library': 9, + 'the key: PEM, PEM with literal \\n, base64 of the PEM — one key out of three spellings': 7, + 'the cache: 0600, refreshed five minutes early, keyed to the installation': 8, + 'the mint: what a fake platform answers, and what this tool does with it': 11, + 'redaction: a known token and a known key fed through every output path never come back out': 12, + 'the CLI: --print prints the token alone, --export prints shell, --status prints neither': 8, + 'the wiring: the one POST is paced and leased, and the throttle roster names this file': 4, +}); +const SELF_TEST_BATTERY_FLOOR = 7; +const UNATTRIBUTED_BATTERY = '(unattributed)'; + +const batteryCases = new Map(); +let openBattery = null; +const battery = (name) => { + openBattery = name; +}; + +// Set as `selfTest()`'s LAST statement, after the success line prints, and read +// at the dispatch — an exit code is not a handshake. +let selfTestReachedVerdict = false; + +export async function selfTest() { + const cases = []; + const t = (name, actual, expected = true, detail) => { + const bucket = openBattery ?? UNATTRIBUTED_BATTERY; + batteryCases.set(bucket, (batteryCases.get(bucket) ?? 0) + 1); + const ok = JSON.stringify(actual) === JSON.stringify(expected); + cases.push({ name, ok, detail: ok ? '' : `${detail ? `${detail} — ` : ''}got ${JSON.stringify(actual)}, want ${JSON.stringify(expected)}` }); + }; + + const { privateKey, publicKey } = generateKeyPairSync('rsa', { modulusLength: 2048 }); + const PEM = privateKey.export({ type: 'pkcs1', format: 'pem' }); + const PEM_BODY = PEM.split('\n').filter((l) => l && !l.startsWith('-----'))[1]; + const TOKEN = 'ghs_FixtureTokenNotRealAtAll0000000000000'; + const NOW = Date.UTC(2026, 8, 22, 9, 0, 0); + const inputs = { appId: '5028251', installationId: '163654544', api: 'https://api.example.test', authorLogin: null, privateKey: PEM }; + + // ── the JWT ─────────────────────────────────────────────────────────────── + battery('the JWT: RS256 over node crypto, the claims the platform reads, no library'); + { + const nowS = Math.floor(NOW / 1000); + const { jwt, header, payload } = buildAppJwt({ appId: inputs.appId, key: privateKey, nowS }); + t('three base64url segments', jwt.split('.').length, 3); + t('…with no padding, plus or slash anywhere', /[=+/]/.test(jwt), false); + t('the header is RS256 / JWT', header, { alg: 'RS256', typ: 'JWT' }); + t('iat is backdated 60 s for clock drift', payload.iat, nowS - 60); + t('exp is 600 s ahead — the platform\'s ceiling, never over it', payload.exp, nowS + 600); + t('iss is the App id', payload.iss, inputs.appId); + t('⛔ a lifetime over the ceiling is refused here, before the platform refuses it', (() => { + try { + buildAppJwt({ appId: inputs.appId, key: privateKey, nowS, ttlS: 601 }); + return 'built'; + } catch (e) { + return e instanceof RangeError ? 'refused' : 'other'; + } + })(), 'refused'); + t('the signature VERIFIES with the public half', verifyJwt(jwt, publicKey)); + t('…and a tampered payload does not', verifyJwt(`${jwt.split('.')[0]}.${base64url('{"iat":1,"exp":2,"iss":"x"}')}.${jwt.split('.')[2]}`, publicKey), false); + } + + // ── the key ─────────────────────────────────────────────────────────────── + battery('the key: PEM, PEM with literal \\n, base64 of the PEM — one key out of three spellings'); + { + const asPem = readPrivateKey(PEM); + const asEscaped = readPrivateKey(PEM.replace(/\n/g, '\\n')); + const asB64 = readPrivateKey(Buffer.from(PEM, 'utf8').toString('base64')); + const fingerprint = (k) => k.export({ type: 'pkcs1', format: 'der' }).toString('hex').slice(0, 32); + t('PEM text is read as pem', asPem.form, 'pem'); + t('PEM with literal \\n is read as pem-escaped', asEscaped.form, 'pem-escaped'); + t('base64 of the PEM is read as base64', asB64.form, 'base64'); + t('⛔ all three are the SAME key', [fingerprint(asEscaped.key), fingerprint(asB64.key)], [fingerprint(asPem.key), fingerprint(asPem.key)]); + const refused = (raw) => { + try { + readPrivateKey(raw); + return 'accepted'; + } catch (e) { + return e instanceof FleetTokenError ? e.exitCode : 'other'; + } + }; + t('an empty key is a prerequisite failure (exit 3)', refused(''), EXIT_PREREQUISITE); + t('a string that is neither PEM nor base64 of one is too', refused('not-a-key'), EXIT_PREREQUISITE); + const ec = generateKeyPairSync('ec', { namedCurve: 'P-256' }).privateKey.export({ type: 'pkcs8', format: 'pem' }); + t('a non-RSA key is refused — RS256 needs RSA', refused(ec), EXIT_PREREQUISITE); + } + + const dir = mkdtempSync(join(tmpdir(), 'fleet-token-')); + try { + // ── the cache ─────────────────────────────────────────────────────────── + battery('the cache: 0600, refreshed five minutes early, keyed to the installation'); + { + const file = join(dir, 'nested', 'fleet-token.json'); + const fresh = { token: TOKEN, expires_at: new Date(NOW + 60 * 60 * 1000).toISOString(), bot: { login: 'objectstack-fleet[bot]', id: 332303061 }, installation_id: inputs.installationId }; + t('absent → refresh', needsRefresh(null, NOW), true); + t('an hour left → no refresh', needsRefresh(fresh, NOW, { installationId: inputs.installationId }), false); + t('five minutes left → refresh (the margin)', needsRefresh({ ...fresh, expires_at: new Date(NOW + REFRESH_MARGIN_MS).toISOString() }, NOW), true); + t('six minutes left → not yet', needsRefresh({ ...fresh, expires_at: new Date(NOW + REFRESH_MARGIN_MS + 60_000).toISOString() }, NOW), false); + t('⛔ a cache for ANOTHER installation is refreshed, whatever its expiry', needsRefresh(fresh, NOW, { installationId: '1' }), true); + t('a cache without the bot identity is refreshed — the wrapper needs it', needsRefresh({ ...fresh, bot: null }, NOW), true); + writeCache(file, fresh); + t('the file is written at mode 0600', (statSync(file).mode & 0o777).toString(8), '600'); + t('…and reads back whole', readCache(file).token, TOKEN); + } + + // ── the mint ──────────────────────────────────────────────────────────── + battery('the mint: what a fake platform answers, and what this tool does with it'); + const platform = (answers, seen) => async (url, init) => { + const u = new URL(url); + const call = `${init?.method ?? 'GET'} ${u.pathname}`; + seen.push({ call, auth: init?.headers?.authorization ?? '' }); + const a = answers[call] ?? { status: 404, json: { message: 'Not Found' } }; + if (a.throws) throw new Error(a.throws); + // `echoBearer` makes the fake platform quote the credential it was + // handed — the JWT on the mint, the token on the identity reads — which + // is the shape a real refusal or proxy error can take. + const json = a.echoBearer ? { ...a.json, message: `${a.json?.message ?? ''} ${init?.headers?.authorization ?? ''}`.trim() } : a.json; + return { status: a.status, headers: new Headers(a.headers ?? {}), json: async () => json }; + }; + const happy = { + 'POST /app/installations/163654544/access_tokens': { status: 201, json: { token: TOKEN, expires_at: new Date(NOW + 3600_000).toISOString(), permissions: { contents: 'write', issues: 'write' }, repository_selection: 'all' } }, + 'GET /app': { status: 200, json: { id: 5028251, slug: 'objectstack-fleet' } }, + 'GET /users/objectstack-fleet%5Bbot%5D': { status: 200, json: { login: 'objectstack-fleet[bot]', id: 332303061, type: 'Bot' } }, + 'GET /users/someone': { status: 200, json: { login: 'someone', id: 42, name: 'Some One' } }, + }; + const paceFile = join(dir, 'pace.jsonl'); + const paceEnv = { OS_PM_WRITE_MIN_GAP_MS: '0' }; + const mintWith = async (answers, extra = {}) => { + const seen = []; + const logs = []; + const file = extra.file ?? join(dir, `cache-${cases.length}.json`); + let result = null; + let error = null; + try { + result = await mintInstallationToken({ ...inputs, ...(extra.inputs ?? {}) }, { + fetch: platform(answers, seen), + now: () => NOW, + log: (l) => logs.push(l), + file, + pace: { file: paceFile, env: paceEnv, log: (l) => logs.push(l) }, + recheck: extra.recheck ?? null, + }); + } catch (e) { + error = e; + } + return { seen, logs, result, error, file }; + }; + { + const m = await mintWith(happy); + t('a 201 yields the token, the expiry and the permissions', [m.result?.token, m.result?.permissions?.contents, m.result?.repository_selection], [TOKEN, 'write', 'all']); + t('the mint is authenticated with the JWT, the identity reads with the token', [m.seen[0].auth.startsWith('Bearer ey'), m.seen[2].auth], [true, `Bearer ${TOKEN}`]); + t('the calls, in order: mint, the App, the bot user', m.seen.map((s) => s.call), ['POST /app/installations/163654544/access_tokens', 'GET /app', 'GET /users/objectstack-fleet%5Bbot%5D']); + t('the bot identity is the slug plus [bot], with the bot USER id (not the App id)', m.result?.bot, { login: 'objectstack-fleet[bot]', id: 332303061 }); + t('…and it is cached, whole, at 0600', [readCache(m.file)?.bot?.id, (statSync(m.file).mode & 0o777).toString(8)], [332303061, '600']); + t('the log names the identity and the redacted token, and says which key form arrived', m.logs.some((l) => l.includes('objectstack-fleet[bot]') && l.includes(redact(TOKEN)) && l.includes('key given as pem'))); + const withAuthor = await mintWith(happy, { inputs: { authorLogin: 'someone' } }); + t('an author login is resolved to its numeric id for the noreply address', withAuthor.result?.author, { login: 'someone', id: 42, name: 'Some One' }); + const jwtRefused = await mintWith({ ...happy, 'POST /app/installations/163654544/access_tokens': { status: 401, json: { message: 'A JSON web token could not be decoded' } } }); + t('a 401 on the JWT is a prerequisite failure that names what to check', [jwtRefused.error?.exitCode, jwtRefused.error?.message.includes('OS_FLEET_APP_ID')], [EXIT_PREREQUISITE, true]); + const notFound = await mintWith({ ...happy, 'POST /app/installations/163654544/access_tokens': { status: 404, json: { message: 'Not Found' } } }); + t('a 404 on the installation is a platform refusal (exit 5) that names the installation id', [notFound.error?.exitCode, notFound.error?.message.includes('OS_FLEET_INSTALLATION_ID')], [EXIT_PLATFORM_REFUSAL, true]); + const down = await mintWith({ ...happy, 'POST /app/installations/163654544/access_tokens': { throws: 'getaddrinfo ENOTFOUND api.example.test' } }); + t('an unreachable platform is a prerequisite failure, and the mint left no cache', [down.error?.exitCode, existsSync(down.file)], [EXIT_PREREQUISITE, false]); + const sibling = { token: 'ghs_SiblingMintedFirst00000000000000000000', expires_at: new Date(NOW + 3600_000).toISOString(), bot: { login: 'objectstack-fleet[bot]', id: 332303061 }, installation_id: inputs.installationId }; + const reused = await mintWith(happy, { recheck: () => sibling }); + t('⛔ a sibling\'s fresh mint, found after the lease was granted, is used and no second POST leaves', [reused.result?.token, reused.seen.length], [sibling.token, 0]); + } + + // ── redaction ─────────────────────────────────────────────────────────── + battery('redaction: a known token and a known key fed through every output path never come back out'); + { + writeFileSync(join(dir, 'blocker'), 'x', 'utf8'); // a FILE where a cache directory would have to be + const outputs = []; + const ok = await mintWith(happy); + outputs.push(...ok.logs, statusText(ok.result, NOW, ok.file)); + const bad401 = await mintWith({ ...happy, 'POST /app/installations/163654544/access_tokens': { status: 401, echoBearer: true, json: { message: `bad JWT, and by the way ${TOKEN}` } } }); + outputs.push(bad401.error.message, String(bad401.error.stack)); + const badUser = await mintWith({ ...happy, 'GET /users/objectstack-fleet%5Bbot%5D': { status: 403, echoBearer: true, json: { message: `refused for ${TOKEN}` } } }); + outputs.push(badUser.error.message, String(badUser.error.stack)); + const jwtLeak = await mintWith({ ...happy, 'GET /app': { throws: 'proxy said: authorization: Bearer ' } }); + outputs.push(jwtLeak.error.message); + const throwing = await mintWith({ ...happy, 'GET /users/objectstack-fleet%5Bbot%5D': { throws: `socket hung up while sending ${TOKEN}` } }); + outputs.push(throwing.error.message, String(throwing.error.stack)); + const unwritable = await mintWith(happy, { file: join(dir, 'blocker', 'x.json') }); + outputs.push(String(unwritable.error?.message ?? ''), String(unwritable.error?.stack ?? '')); + t('an unwritable cache path is a prerequisite failure naming the override, and the minted token is discarded', [unwritable.error?.exitCode, unwritable.error?.message.includes('OS_FLEET_TOKEN_CACHE_FILE'), existsSync(unwritable.file)], [EXIT_PREREQUISITE, true, false]); + const joined = outputs.join('\n'); + t('⛔ THE case: the token appears in NO log line, status report, error message or stack', joined.includes(TOKEN), false, joined.slice(0, 400)); + t('…and neither does the private key body', joined.includes(PEM_BODY), false); + t('the redacted form is what appears instead', joined.includes(redact(TOKEN))); + t('a platform sentence that echoed the JWT it was handed is scrubbed before it is re-thrown', bad401.error.message.includes('') && !bad401.error.message.includes('eyJ')); + t('…and one that echoed the token is scrubbed too, on the identity read', badUser.error.message.includes('') && !badUser.error.message.includes(TOKEN)); + t('a transport error that echoed the token is scrubbed too', throwing.error.message.includes('') && !throwing.error.message.includes(TOKEN)); + t('a token-SHAPED run this process never saw is scrubbed by shape', scrub('proxy log: ghs_SomeOtherToken0000000000000000000 and eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE3MDAwMDAwMDAsImV4cCI6MTcwMDAwMDYwMH0.c2lnbmF0dXJlLXNpZ25hdHVyZQ'), 'proxy log: and '); + t('`scrub` leaves short strings alone rather than blanking every "e"', scrub('the eel', ['e']), 'the eel'); + t('`redact` shows four characters and the length', redact(TOKEN), `ghs_…(${TOKEN.length} chars)`); + t('…and says (empty) for nothing, rather than crashing', redact(''), '(empty)'); + const cacheText = readFileSync(ok.file, 'utf8'); + t('the cache file — and only it — carries the token', cacheText.includes(TOKEN)); + } + + // ── the CLI ───────────────────────────────────────────────────────────── + battery('the CLI: --print prints the token alone, --export prints shell, --status prints neither'); + { + const file = join(dir, 'cli-cache.json'); + writeCache(file, { + token: TOKEN, + expires_at: new Date(Date.now() + 3600_000).toISOString(), + bot: { login: 'objectstack-fleet[bot]', id: 332303061 }, + author: { login: 'someone', id: 42, name: 'Some One' }, + app_id: inputs.appId, + installation_id: inputs.installationId, + permissions: { contents: 'write' }, + repository_selection: 'all', + minted_at: new Date().toISOString(), + }); + const base = { ...process.env, OS_FLEET_TOKEN_CACHE_FILE: file, OS_FLEET_APP_ID: inputs.appId, OS_FLEET_INSTALLATION_ID: inputs.installationId, OS_PM_WRITE_PACE_FILE: paceFile, OS_FLEET_PRIVATE_KEY: '', HTTPS_PROXY: '', https_proxy: '' }; + const run = (args, env = base) => spawnSync(process.execPath, [SELF_PATH, ...args], { encoding: 'utf8', env }); + const print = run(['--print']); + t('--print prints exactly the token and a newline, at exit 0, with nothing on stderr', [print.status, print.stdout, print.stderr], [0, `${TOKEN}\n`, '']); + const exp = run(['--export']); + t('--export prints the token as GITHUB_TOKEN and GH_TOKEN, single-quoted', [exp.status, exp.stdout.includes(`export GITHUB_TOKEN='${TOKEN}'`), exp.stdout.includes(`export GH_TOKEN='${TOKEN}'`)], [0, true, true]); + t('…with the bot identity and the resolved author beside it', exp.stdout.includes("export OS_FLEET_BOT_USER_ID='332303061'") && exp.stdout.includes("export OS_FLEET_GIT_AUTHOR_EMAIL='42+someone@users.noreply.github.com'")); + t('…and every line is a shell export a shell can eval', exp.stdout.trim().split('\n').every((l) => /^export [A-Z_]+='.*'$/.test(l))); + const status = run(['--status']); + t('--status prints the identity, the expiry and the permissions, and ⛔ not the token', [status.status, status.stdout.includes('objectstack-fleet[bot]'), status.stdout.includes(TOKEN)], [0, true, false]); + t("a value with a quote in it survives eval's quoting", shellQuote("it's"), "'it'\\''s'"); + const missing = run(['--print'], { ...base, OS_FLEET_APP_ID: '', OS_FLEET_TOKEN_CACHE_FILE: join(dir, 'absent.json') }); + t('without the inputs and without a cache, --print exits 3 naming the variables and prints no token', [missing.status, missing.stderr.includes('OS_FLEET_APP_ID'), missing.stdout], [EXIT_PREREQUISITE, true, '']); + t('an unrecognised flag is usage, ⛔ never a silent pass', run(['--pritn']).status, EXIT_USAGE); + } + + // ── the wiring ────────────────────────────────────────────────────────── + battery('the wiring: the one POST is paced and leased, and the throttle roster names this file'); + { + const { WIRED_WRITE_TOOLS } = await import('./write-pace.mjs'); + const own = readFileSync(SELF_PATH, 'utf8'); + t('write-pace lists this file among the wired write tools', WIRED_WRITE_TOOLS.includes('fleet-token.mjs')); + t('this file calls both halves around its POST', own.includes('paceWrite(') && own.includes('noteResponse(') && own.includes('isWriteMethod(')); + const records = readFileSync(paceFile, 'utf8'); + t('the mints above were recorded by the throttle under the App key, ⛔ not under any token', records.includes('fleet-token POST') && !records.includes(TOKEN)); + t('…and the lease was released after each', existsSync(`${paceFile}.lease`), false); + } + } finally { + rmSync(dir, { recursive: true, force: true }); + } + + // ── the floor, BEFORE the verdict ───────────────────────────────────────── + const declared = Object.keys(SELF_TEST_BATTERIES); + const floor = []; + if (declared.length < SELF_TEST_BATTERY_FLOOR) { + floor.push(`the battery ledger declares ${declared.length} batteries, below its floor of ${SELF_TEST_BATTERY_FLOOR} — a section that stopped being declared is a section nothing floors.`); + } + for (const [name, count] of batteryCases) { + if (name in SELF_TEST_BATTERIES) continue; + floor.push(`self-test battery "${name}" registered ${count} case(s) but is not declared in SELF_TEST_BATTERIES — an assertion attributed to no declared battery is one nothing floors.`); + } + for (const name of declared) { + const count = batteryCases.get(name) ?? 0; + if (count >= SELF_TEST_BATTERIES[name]) continue; + floor.push( + count === 0 + ? `self-test battery "${name}" DID NOT RUN — 0 cases registered, ${SELF_TEST_BATTERIES[name]} pinned. The verdict below would have claimed those cases hold.` + : `self-test battery "${name}" registered ${count} case(s), below its pinned floor of ${SELF_TEST_BATTERIES[name]} — cases that used to run no longer do.`, + ); + } + for (const message of floor) cases.push({ name: message, ok: false, detail: '' }); + + const failed = cases.filter((c) => !c.ok); + for (const c of failed) console.error(` ✗ ${c.name}${c.detail ? ` — ${c.detail}` : ''}`); + if (failed.length) { + console.error(`✗ fleet-token self-test: ${failed.length} of ${cases.length} case(s) failed.`); + selfTestReachedVerdict = true; + return 1; + } + console.log( + `✓ fleet-token self-test: ${cases.length} cases pass across ${declared.length} batteries — an RS256 JWT built on node crypto and ` + + 'verified with the public half, three spellings of one key, a 0600 cache refreshed five minutes early, a fake platform ' + + "through every branch of the mint, and a known token that came back out of NO log, status, error or stack.", + ); + selfTestReachedVerdict = true; + return 0; +} + +// --------------------------------------------------------------------------- +// Dispatch +// --------------------------------------------------------------------------- + +export const KNOWN_FLAGS = Object.freeze(['--export', '--print', '--status', '--refresh', '--self-test', '--help', '-h']); + +const USAGE = [ + 'usage:', + ' node scripts/pm/fleet-token.mjs --export export GITHUB_TOKEN / GH_TOKEN and the bot identity, for eval "$(…)"', + ' node scripts/pm/fleet-token.mjs --print the token alone on stdout', + ' node scripts/pm/fleet-token.mjs --status the cache, redacted', + ' node scripts/pm/fleet-token.mjs --refresh mint now (combine with --print / --export)', + ' node scripts/pm/fleet-token.mjs --self-test offline: throwaway key, fake platform', + '', + ' Inputs: OS_FLEET_APP_ID · OS_FLEET_INSTALLATION_ID · OS_FLEET_PRIVATE_KEY (PEM, PEM with literal \\n, or base64)', + ' optional OS_FLEET_API_URL · OS_FLEET_TOKEN_CACHE_FILE · OS_FLEET_GIT_AUTHOR_LOGIN', + ` Exits: 0 ok · ${EXIT_USAGE} usage · ${EXIT_PREREQUISITE} prerequisite not met · ${EXIT_PLATFORM_REFUSAL} platform refused · ${EXIT_WRITE_PACE_REFUSED} the write throttle refused the mint`, +].join('\n'); + +/** Route this process through the session proxy when one is configured — label-write's pattern, this file's guard. */ +function rearmThroughProxy(args) { + const plan = proxyRearmPlan({ + env: process.env, + execArgv: process.execArgv, + flagSupported: process.allowedNodeEnvironmentFlags.has(PROXY_FLAG), + guard: PROXY_REARM_GUARD, + }); + if (plan.hint) { + console.error(`ℹ️ ${plan.reason}. A refusal below may be about the route, not this container.`); + return null; + } + if (!plan.rearm) return null; + console.error(`ℹ️ re-exec with ${plan.flag}: ${plan.reason}.`); + const quiet = process.allowedNodeEnvironmentFlags.has('--disable-warning') ? ['--disable-warning=UNDICI-EHPA'] : []; + const child = spawnSync(process.execPath, [plan.flag, ...quiet, SELF_PATH, ...args], { + stdio: 'inherit', + env: { ...process.env, [PROXY_REARM_GUARD]: '1' }, + }); + if (typeof child.status === 'number') return child.status; + console.error(`⚠️ could not re-exec with ${plan.flag} (${child.error?.message ?? 'no exit status'}); continuing in-process — the mint will bypass the proxy.`); + return null; +} + +export async function main(argv) { + if (argv.includes('--help') || argv.includes('-h')) { + console.log(USAGE); + return EXIT_OK; + } + if (argv.includes('--self-test')) return selfTest(); + const unknown = argv.filter((a) => !KNOWN_FLAGS.includes(a)); + if (unknown.length) { + console.error(`fleet-token: unrecognised option ${unknown.map((u) => `\`${u}\``).join(', ')}\n`); + console.error(USAGE); + return EXIT_USAGE; + } + const modes = argv.filter((a) => ['--export', '--print', '--status'].includes(a)); + if (modes.length !== 1) { + console.error('fleet-token: exactly one of --export, --print, --status\n'); + console.error(USAGE); + return EXIT_USAGE; + } + const mode = modes[0]; + const file = cacheFilePath(); + if (mode === '--status') { + console.log(statusText(readCache(file), Date.now(), file)); + return EXIT_OK; + } + const rearmed = rearmThroughProxy(argv); + if (rearmed !== null) return rearmed; + let cache; + try { + cache = await getFleetToken({ force: argv.includes('--refresh') }); + } catch (e) { + if (e instanceof FleetTokenError) { + console.error(`✗ fleet-token: ${e.message}`); + return e.exitCode ?? EXIT_PREREQUISITE; + } + console.error(`✗ fleet-token: ${scrub(e?.message ?? String(e), [])}`); + return EXIT_PREREQUISITE; + } + if (mode === '--print') process.stdout.write(`${cache.token}\n`); + else process.stdout.write(exportLines(cache)); + return EXIT_OK; +} + +if (isEntrypoint(import.meta.url)) { + const code = await main(process.argv.slice(2)); + if (process.argv.includes('--self-test') && !selfTestReachedVerdict) { + console.error( + '\n✗ fleet-token self-test: selfTest() returned without reaching its verdict, so no success line was\n' + + 'printed. Exiting 0 here would report a self-test that never finished as one that passed.\n', + ); + process.exit(1); + } + process.exit(code); +} diff --git a/scripts/pm/issue-create.mjs b/scripts/pm/issue-create.mjs new file mode 100644 index 00000000000..802f259459d --- /dev/null +++ b/scripts/pm/issue-create.mjs @@ -0,0 +1,581 @@ +#!/usr/bin/env node +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * issue-create — the one door a NEW card leaves through. + * + * node scripts/pm/issue-create.mjs --repo owner/name --title-file title.txt --body-file body.md [--label L]… [--assignee A]… [--json] + * node scripts/pm/issue-create.mjs --title 'A short title' --body-file body.md --dry-run + * node scripts/pm/issue-create.mjs --self-test # offline, a fake platform, no network at all + * + * ## Why this file exists + * + * Labels had `label-write.mjs`, comments and bodies had `post-stamped.mjs`, + * closures had `close-cards.mjs` — CREATION had nothing. So a seat creating a + * batch of cards reached for a bare `curl` loop, and a loop in which each + * process paced itself and none paced the fleet is exactly the burst that got + * an account restricted (`write-pace.mjs`'s header carries the reading). This + * file is the door: one POST, through the throttle's lease and gap, read back, + * and reported — and a batch of N cards is N calls of it behind one + * `write-pace.mjs --announce-batch N`, never a loop of anything else. + * + * ## Prose comes from FILES, never from argv + * + * A title typed into a shell command is interpolated by that shell before this + * program sees it: a backticked identifier in a card title once posted as the + * OUTPUT of the command it named. `--body-file` is the only way to give a body. + * `--title-file` is the way to give a title; `--title` exists for the plain + * case and is REFUSED when it carries a backtick or a dollar sign, because by + * then the shell has already had its turn. + * + * ## What it refuses, before any request leaves + * + * - an empty title or body; both title sources, or neither; + * - a repo not shaped `owner/name` (the default is the board the sweep + * tooling resolves, so a card never lands on a repo nobody named); + * - a body carrying `{{NOW}}` / `{{WAS:…}}` — those are `post-stamped.mjs`'s + * contract for comments and body EDITS; a new card is dated by the platform. + * + * ## Read-back + * + * After a 201 the card is fetched again and its title compared. A mismatch is + * exit 4 — the one exit that means the board now holds something nobody asked + * for — and the number is printed either way, so nothing is created twice. + * + * ## Exit codes — capture them BEFORE any pipe (label-write's ladder) + * + * 0 created, and the read-back matched. The number and URL are printed; + * `--json` adds one JSON line on stdout. + * 2 usage, or a refusal above. + * 3 PREREQUISITE NOT MET — no token, the platform unreachable, or the + * credential rate-limit exhausted. Nothing was created. + * 4 created, and the READ-BACK DISAGREES. The number is printed. + * 5 the platform refused (403 / 404 / 422 …). Its own sentence is printed. + * 10 the write throttle refused (a stop marker, no turn on the lease, the + * hourly budget). Nothing was sent. + */ + +import { spawnSync } from 'node:child_process'; +import { readFileSync } from 'node:fs'; +import process from 'node:process'; +import { fileURLToPath } from 'node:url'; + +import { isEntrypoint } from '../invoked-as.mjs'; +import { EXIT_PREREQUISITE_NOT_MET, PROXY_FLAG, proxyRearmPlan, resolveSweepRepo } from './check-half-states.mjs'; +import { classifyHttp } from './label-write.mjs'; +import { EXIT_WRITE_PACE_REFUSED, isWriteMethod, noteResponse, paceWrite, releaseWriteLease } from './write-pace.mjs'; + +const SELF_PATH = fileURLToPath(import.meta.url); +const API = 'https://api.github.com'; +const TOKEN = process.env.GITHUB_TOKEN ?? process.env.GH_TOKEN ?? ''; +const PROXY_REARM_GUARD = 'OS_ISSUE_CREATE_PROXY_REARMED'; + +export const EXIT_OK = 0; +export const EXIT_USAGE = 2; +export const EXIT_PREREQUISITE = EXIT_PREREQUISITE_NOT_MET; +export const EXIT_READ_BACK_MISMATCH = 4; +export const EXIT_PLATFORM_REFUSAL = 5; + +export const REPO_SHAPE = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/; +const STAMP_TOKEN = /\{\{(?:NOW|WAS:)/; + +// --------------------------------------------------------------------------- +// The pure core — arguments, the plan, the payload, the verdict on a status. +// --------------------------------------------------------------------------- + +export function parseArgs(argv) { + const opts = { repo: null, title: null, titleFile: null, bodyFile: null, labels: [], assignees: [], json: false, dryRun: false, selfTest: false, help: false, unknown: [], errors: [] }; + const args = [...argv]; + const value = (flag) => { + const v = args.shift(); + if (v === undefined || v.startsWith('--')) { + opts.errors.push(`${flag} needs a value`); + return null; + } + return v; + }; + while (args.length) { + const a = args.shift(); + if (a === '--help' || a === '-h') opts.help = true; + else if (a === '--self-test') opts.selfTest = true; + else if (a === '--json') opts.json = true; + else if (a === '--dry-run') opts.dryRun = true; + else if (a === '--repo') opts.repo = value(a); + else if (a === '--title') opts.title = value(a); + else if (a === '--title-file') opts.titleFile = value(a); + else if (a === '--body-file') opts.bodyFile = value(a); + else if (a === '--label') { + const v = value(a); + if (v !== null) opts.labels.push(v); + } else if (a === '--assignee') { + const v = value(a); + if (v !== null) opts.assignees.push(v); + } else if (a.startsWith('--') && a.includes('=')) { + // `--title=x` is accepted for the flags that take a value, so a caller + // used to the other tools' spelling is not refused for it. + const [k, ...rest] = a.split('='); + args.unshift(k, rest.join('=')); + } else opts.unknown.push(a); + } + return opts; +} + +/** Order-preserving de-duplication of non-empty strings. */ +function dedupe(values) { + const out = []; + for (const v of values) { + const s = String(v ?? '').trim(); + if (s && !out.includes(s)) out.push(s); + } + return out; +} + +/** + * The plan: what will be sent, to which board, or why not. `read` is injected + * so the self-test never touches a real file for its refusals. + */ +export function planFrom(opts, { read = (p) => readFileSync(p, 'utf8'), env = process.env } = {}) { + const errors = []; + const resolved = opts.repo ? { repo: String(opts.repo).trim(), source: '--repo' } : resolveSweepRepo(env); + const repo = resolved.repo; + if (!REPO_SHAPE.test(repo)) errors.push(`the repo must be owner/name; got ${JSON.stringify(repo)} (from ${resolved.source})`); + + let title = null; + if (opts.title !== null && opts.titleFile !== null) errors.push('give the title ONCE: --title or --title-file, not both'); + else if (opts.title === null && opts.titleFile === null) errors.push('a title is required: --title-file (recommended) or --title '); + else if (opts.titleFile !== null) { + try { + title = read(opts.titleFile); + } catch (e) { + errors.push(`--title-file ${opts.titleFile} cannot be read (${e?.message ?? 'unreadable'})`); + } + } else { + title = opts.title; + if (/[`$]/.test(title)) { + errors.push('--title carries a backtick or a dollar sign — the shell has already had its turn on it; put the title in a file and pass --title-file'); + } + } + if (title !== null) { + title = String(title).replace(/\r?\n/g, ' ').trim(); + if (!title) errors.push('the title is empty'); + } + + let body = null; + if (opts.bodyFile === null) errors.push('a body is required: --body-file — a body never comes from argv'); + else { + try { + body = read(opts.bodyFile); + } catch (e) { + errors.push(`--body-file ${opts.bodyFile} cannot be read (${e?.message ?? 'unreadable'})`); + } + } + if (body !== null) { + body = String(body).replace(/\r\n/g, '\n').trim(); + if (!body) errors.push('the body is empty — a card names its evidence'); + else if (STAMP_TOKEN.test(body)) errors.push('the body carries a {{NOW}} / {{WAS:…}} token — those are post-stamped.mjs\'s contract for comments; a new card is dated by the platform'); + } + + const labels = dedupe(opts.labels); + const assignees = dedupe(opts.assignees); + const payload = { title: title ?? '', body: body ?? '' }; + if (labels.length) payload.labels = labels; + if (assignees.length) payload.assignees = assignees; + return { ok: errors.length === 0, errors, repo, payload }; +} + +/** What `--dry-run` prints: the whole request, nothing sent. */ +export function dryRunText(plan) { + return [ + `issue-create --dry-run — NOTHING was sent.`, + ` POST /repos/${plan.repo}/issues`, + ` title : ${plan.payload.title}`, + ` labels : ${plan.payload.labels?.join(', ') ?? '(none)'}`, + ` assignees : ${plan.payload.assignees?.join(', ') ?? '(none)'}`, + ` body : ${plan.payload.body.length} chars, ${plan.payload.body.split('\n').length} line(s)`, + ].join('\n'); +} + +/** The exit a transport verdict maps to. `null` means "carry on". */ +export function exitForVerdict(verdict) { + if (verdict === 'ok') return null; + if (verdict === 'prerequisite' || verdict === 'ratelimit') return EXIT_PREREQUISITE; + return EXIT_PLATFORM_REFUSAL; +} + +// --------------------------------------------------------------------------- +// Transport — the one shape, with both halves of the throttle around the one +// write verb. ⛔ Nothing here throws on an HTTP status. +// --------------------------------------------------------------------------- + +async function rest(path, { method = 'GET', body = null } = {}, deps = {}) { + const fetchImpl = deps.fetch ?? globalThis.fetch; + const token = deps.token ?? TOKEN; + const paceDeps = deps.pace ?? {}; + // ⏱ The throttle, on the write verb only — the POST that creates the card. + const paced = isWriteMethod(method); + if (paced) await paceWrite({ token, kind: `issue-create ${method}` }, paceDeps); + let res; + try { + res = await fetchImpl(`${API}${path}`, { + method, + headers: { + accept: 'application/vnd.github+json', + 'x-github-api-version': '2022-11-28', + ...(token ? { authorization: `Bearer ${token}` } : {}), + ...(body ? { 'content-type': 'application/json' } : {}), + }, + ...(body ? { body: JSON.stringify(body) } : {}), + }); + } catch (e) { + if (paced) releaseWriteLease(paceDeps.file); // ⏱ rule ④: no response will come, so the fleet's turn ends here + return { status: 0, rateRemaining: null, json: null, detail: e?.message ?? 'fetch threw', call: `${method} ${path}` }; + } + const rateRemaining = res.headers.get('x-ratelimit-remaining'); + let json = null; + if (res.status !== 204) { + try { + json = await res.json(); + } catch { + json = null; + } + } + // ⏱ …and the other half, with the verdict `classifyHttp` already reached. + if (paced) { + noteResponse( + { + token, + status: res.status, + headers: res.headers, + body: json, + verdict: classifyHttp({ status: res.status, rateRemaining: rateRemaining === null ? null : Number(rateRemaining) }), + }, + paceDeps, + ); + } + return { + status: res.status, + rateRemaining: rateRemaining === null ? null : Number(rateRemaining), + json, + detail: typeof json?.message === 'string' ? json.message : '', + call: `${method} ${path}`, + }; +} + +/** + * Create the card the plan describes, read it back, and say what happened. + * Returns `{ exitCode, number, url, author, lines }`; never throws on a status. + */ +export async function createIssue(plan, deps = {}) { + const lines = []; + const token = deps.token ?? TOKEN; + if (!token) { + lines.push('✗ issue-create: no GITHUB_TOKEN / GH_TOKEN in the environment — nothing was sent. Run it through scripts/pm/with-fleet.sh, which mints the fleet identity.'); + return { exitCode: EXIT_PREREQUISITE, number: null, url: null, author: null, lines }; + } + const created = await rest(`/repos/${plan.repo}/issues`, { method: 'POST', body: plan.payload }, deps); + const verdict = classifyHttp({ status: created.status, rateRemaining: created.rateRemaining }); + const bad = exitForVerdict(verdict); + if (bad !== null || !Number.isInteger(created.json?.number)) { + lines.push(`✗ issue-create: ${created.call} → HTTP ${created.status}${created.detail ? ` — ${created.detail}` : ''} (${verdict}). Nothing was created.`); + if (verdict === 'ratelimit') lines.push(' The credential is rate-limit exhausted: this binds the IDENTITY, so switching tools or tokens to keep writing is the same act as retrying. ⛔ Do not.'); + return { exitCode: bad ?? EXIT_PLATFORM_REFUSAL, number: null, url: null, author: null, lines }; + } + const number = created.json.number; + const url = created.json.html_url ?? null; + const author = created.json.user?.login ?? null; + lines.push(`✓ issue-create: created #${number}${url ? ` ${url}` : ''}${author ? ` (as ${author})` : ''}`); + + const back = await rest(`/repos/${plan.repo}/issues/${number}`, {}, deps); + if (back.status !== 200 || !back.json) { + lines.push(`✗ issue-create: the read-back ${back.call} → HTTP ${back.status}${back.detail ? ` — ${back.detail}` : ''}; #${number} exists but could not be verified.`); + return { exitCode: EXIT_READ_BACK_MISMATCH, number, url, author, lines }; + } + const gotTitle = String(back.json.title ?? '').trim(); + if (gotTitle !== plan.payload.title) { + lines.push(`✗ issue-create: read-back of #${number} disagrees — title ${JSON.stringify(gotTitle)}, wanted ${JSON.stringify(plan.payload.title)}.`); + return { exitCode: EXIT_READ_BACK_MISMATCH, number, url, author, lines }; + } + lines.push(` read-back: #${number} title matches; state ${back.json.state ?? '?'}; labels ${(back.json.labels ?? []).map((l) => l?.name ?? l).join(', ') || '(none)'}.`); + return { exitCode: EXIT_OK, number, url, author, lines }; +} + +// --------------------------------------------------------------------------- +// Self-test — offline: a fake platform, injected file reads, no network. +// --------------------------------------------------------------------------- + +const SELF_TEST_BATTERIES = Object.freeze({ + 'the arguments: files not argv for prose, exactly one title source, a repo shape': 10, + 'the payload: title trimmed to one line, labels and assignees de-duplicated, nothing invented': 5, + 'the transport: a fake platform, and what each answer does to the exit code': 9, + 'dry-run: no request leaves, and the plan is printed': 3, + 'the wiring: both halves around the one POST, on the write verb only': 4, +}); +const SELF_TEST_BATTERY_FLOOR = 5; +const UNATTRIBUTED_BATTERY = '(unattributed)'; + +const batteryCases = new Map(); +let openBattery = null; +const battery = (name) => { + openBattery = name; +}; + +let selfTestReachedVerdict = false; + +export async function selfTest() { + const cases = []; + const t = (name, actual, expected = true, detail) => { + const bucket = openBattery ?? UNATTRIBUTED_BATTERY; + batteryCases.set(bucket, (batteryCases.get(bucket) ?? 0) + 1); + const ok = JSON.stringify(actual) === JSON.stringify(expected); + cases.push({ name, ok, detail: ok ? '' : `${detail ? `${detail} — ` : ''}got ${JSON.stringify(actual)}, want ${JSON.stringify(expected)}` }); + }; + const { mkdtempSync, rmSync, writeFileSync, readFileSync: readReal, existsSync } = await import('node:fs'); + const { tmpdir } = await import('node:os'); + const { join } = await import('node:path'); + + const files = { 'title.txt': ' A card with `backticks` and $HOME in it \n', 'body.md': 'Evidence: a repro.\n\n- step one\n', 'empty.md': ' \n', 'stamped.md': 'Reading time {{NOW}}\n' }; + const read = (p) => { + if (!(p in files)) throw new Error('ENOENT'); + return files[p]; + }; + const env = { PM_SWEEP_REPO: 'objectstack-ai/objectstack' }; + + // ── the arguments ───────────────────────────────────────────────────────── + battery('the arguments: files not argv for prose, exactly one title source, a repo shape'); + { + const good = planFrom(parseArgs(['--title-file', 'title.txt', '--body-file', 'body.md']), { read, env }); + t('a title file and a body file make a plan', good.ok, true, good.errors.join(' | ')); + t('…on the board the environment resolves when --repo is absent', good.repo, 'objectstack-ai/objectstack'); + t('--repo overrides it', planFrom(parseArgs(['--repo', 'o/r', '--title', 'x', '--body-file', 'body.md']), { read, env }).repo, 'o/r'); + t('a repo that is not owner/name is refused', planFrom(parseArgs(['--repo', 'nope', '--title', 'x', '--body-file', 'body.md']), { read, env }).errors.some((e) => e.includes('owner/name'))); + t('both title sources are refused', planFrom(parseArgs(['--title', 'x', '--title-file', 'title.txt', '--body-file', 'body.md']), { read, env }).errors.some((e) => e.includes('ONCE'))); + t('neither is refused', planFrom(parseArgs(['--body-file', 'body.md']), { read, env }).errors.some((e) => e.includes('a title is required'))); + t('⛔ a --title carrying a backtick or a dollar sign is refused — the shell already had its turn', planFrom(parseArgs(['--title', 'the `id` field', '--body-file', 'body.md']), { read, env }).errors.some((e) => e.includes('backtick'))); + t('…while the same title from a FILE is accepted verbatim', good.payload.title, 'A card with `backticks` and $HOME in it'); + t('a body never comes from argv: --body-file is required', planFrom(parseArgs(['--title', 'x']), { read, env }).errors.some((e) => e.includes('--body-file'))); + t('an unreadable file is a refusal, not a crash', planFrom(parseArgs(['--title', 'x', '--body-file', 'missing.md']), { read, env }).errors.some((e) => e.includes('cannot be read'))); + t('a flag without its value is a usage error', parseArgs(['--title']).errors, ['--title needs a value']); + t('an unknown flag is reported, ⛔ never silently dropped', parseArgs(['--tilte', 'x']).unknown, ['--tilte', 'x']); + } + + // ── the payload ─────────────────────────────────────────────────────────── + battery('the payload: title trimmed to one line, labels and assignees de-duplicated, nothing invented'); + { + const p = planFrom(parseArgs(['--title', 'x', '--body-file', 'body.md', '--label', 'a', '--label', 'b', '--label', 'a', '--assignee', 'u', '--assignee', ' u ']), { read, env }); + t('labels are de-duplicated in order', p.payload.labels, ['a', 'b']); + t('assignees too, trimmed', p.payload.assignees, ['u']); + t('no labels ⇒ no labels key at all, nothing invented', 'labels' in planFrom(parseArgs(['--title', 'x', '--body-file', 'body.md']), { read, env }).payload, false); + t('an empty body is refused', planFrom(parseArgs(['--title', 'x', '--body-file', 'empty.md']), { read, env }).errors.some((e) => e.includes('body is empty'))); + t('a body carrying a stamp token is refused — that is post-stamped\'s contract', planFrom(parseArgs(['--title', 'x', '--body-file', 'stamped.md']), { read, env }).errors.some((e) => e.includes('{{NOW}}'))); + } + + const dir = mkdtempSync(join(tmpdir(), 'issue-create-')); + try { + // One pace file PER CASE: a stop marker one answer writes must not refuse + // the next case's POST — except in the case that pins exactly that. + let paceCase = 0; + const paceFile = join(dir, 'pace-0.jsonl'); + const paceFor = (file) => ({ + file, + env: { OS_PM_WRITE_MIN_GAP_MS: '0' }, + log: () => {}, + exit: (code) => { + throw Object.assign(new Error(`throttle refused with exit ${code}`), { throttleExit: code }); + }, + }); + const TOKEN_FIXTURE = 'ghs_FixtureTokenNotRealAtAll0000000000000'; + const plan = planFrom(parseArgs(['--repo', 'o/r', '--title-file', 'title.txt', '--body-file', 'body.md', '--label', 'pm:queue']), { read, env }); + const platform = (answers, seen) => async (url, init) => { + const u = new URL(url); + const call = `${init?.method ?? 'GET'} ${u.pathname}`; + seen.push({ call, body: init?.body ? JSON.parse(init.body) : null, auth: init?.headers?.authorization ?? '' }); + const a = answers[call] ?? { status: 404, json: { message: 'Not Found' } }; + if (a.throws) throw new Error(a.throws); + // The platform sends the quota header on every answer; an answer that + // omits it is what `classifyHttp` reads as "exhausted", so the fake + // sends a live quota unless the case says otherwise. + return { status: a.status, headers: new Headers({ 'x-ratelimit-remaining': '4999', ...(a.headers ?? {}) }), json: async () => a.json }; + }; + const happy = { + 'POST /repos/o/r/issues': { status: 201, json: { number: 12, html_url: 'https://github.test/o/r/issues/12', user: { login: 'objectstack-fleet[bot]' } } }, + 'GET /repos/o/r/issues/12': { status: 200, json: { number: 12, title: plan.payload.title, state: 'open', labels: [{ name: 'pm:queue' }] } }, + }; + const drive = async (answers, { file } = {}) => { + const seen = []; + const pace = paceFor(file ?? join(dir, `pace-${paceCase++}.jsonl`)); + try { + const r = await createIssue(plan, { fetch: platform(answers, seen), token: TOKEN_FIXTURE, pace }); + return { ...r, seen, pace }; + } catch (e) { + if (e?.throttleExit === undefined) throw e; + return { exitCode: e.throttleExit, number: null, url: null, author: null, lines: [], seen, pace, throttled: true }; + } + }; + + // ── the transport ─────────────────────────────────────────────────────── + battery('the transport: a fake platform, and what each answer does to the exit code'); + { + const ok = await drive(happy, { file: paceFile }); + t('a 201 and a matching read-back is exit 0, and the number, URL and actor are printed', [ok.exitCode, ok.number, ok.lines[0].includes('#12') && ok.lines[0].includes('objectstack-fleet[bot]')], [EXIT_OK, 12, true]); + t('the POST carries the payload the plan built, and the bearer token', [ok.seen[0].body, ok.seen[0].auth], [plan.payload, `Bearer ${TOKEN_FIXTURE}`]); + t('…then exactly one read-back GET', ok.seen.map((s) => s.call), ['POST /repos/o/r/issues', 'GET /repos/o/r/issues/12']); + const mismatch = await drive({ ...happy, 'GET /repos/o/r/issues/12': { status: 200, json: { number: 12, title: 'something else' } } }); + t('a read-back that disagrees is exit 4, with the number still printed', [mismatch.exitCode, mismatch.number], [EXIT_READ_BACK_MISMATCH, 12]); + const refused = await drive({ ...happy, 'POST /repos/o/r/issues': { status: 403, json: { message: 'Resource not accessible by integration' } } }); + t('a 403 is a platform refusal (exit 5) carrying the platform\'s own sentence', [refused.exitCode, refused.lines[0].includes('Resource not accessible')], [EXIT_PLATFORM_REFUSAL, true]); + const exhausted = await drive({ ...happy, 'POST /repos/o/r/issues': { status: 403, headers: { 'x-ratelimit-remaining': '0' }, json: { message: 'API rate limit exceeded' } } }); + t('a 403 with the quota exhausted is a PREREQUISITE failure (exit 3) that binds the identity', [exhausted.exitCode, exhausted.lines.some((l) => l.includes('binds the IDENTITY'))], [EXIT_PREREQUISITE, true]); + const afterMarker = await drive(happy, { file: exhausted.pace.file }); + t('…and the stop marker that answer wrote refuses the NEXT create before it leaves (exit 10, no request)', [afterMarker.exitCode, afterMarker.throttled, afterMarker.seen.length], [EXIT_WRITE_PACE_REFUSED, true, 0]); + const unprocessable = await drive({ ...happy, 'POST /repos/o/r/issues': { status: 422, json: { message: 'Validation Failed' } } }); + t('a 422 is a platform refusal too', unprocessable.exitCode, EXIT_PLATFORM_REFUSAL); + const down = await drive({ ...happy, 'POST /repos/o/r/issues': { throws: 'ECONNRESET' } }); + t('an unreachable platform is exit 3, and the lease it held was released on the way out', [down.exitCode, existsSync(`${down.pace.file}.lease`)], [EXIT_PREREQUISITE, false]); + const noToken = await createIssue(plan, { fetch: platform(happy, []), token: '', pace: paceFor(join(dir, 'pace-none.jsonl')) }); + t('no token is exit 3 before any request, naming with-fleet.sh', [noToken.exitCode, noToken.lines[0].includes('with-fleet.sh')], [EXIT_PREREQUISITE, true]); + } + + // ── dry-run ───────────────────────────────────────────────────────────── + battery('dry-run: no request leaves, and the plan is printed'); + { + writeFileSync(join(dir, 'b.md'), 'A body.\n', 'utf8'); + const spawned = spawnSync(process.execPath, [SELF_PATH, '--dry-run', '--repo', 'o/r', '--title', 'Dry', '--body-file', join(dir, 'b.md')], { + encoding: 'utf8', + env: { ...process.env, OS_PM_WRITE_PACE_FILE: join(dir, 'dry-pace.jsonl'), GITHUB_TOKEN: TOKEN_FIXTURE, GH_TOKEN: '', HTTPS_PROXY: '', https_proxy: '' }, + }); + t('--dry-run exits 0 and prints the request it did not send', [spawned.status, spawned.stdout.includes('NOTHING was sent') && spawned.stdout.includes('POST /repos/o/r/issues')], [0, true], spawned.stderr.slice(-300)); + t('…and the throttle recorded nothing: a dry run makes no write', existsSync(join(dir, 'dry-pace.jsonl')), false); + t('a refused plan is usage, printed, and nothing is sent', spawnSync(process.execPath, [SELF_PATH, '--dry-run', '--repo', 'o/r', '--title', 'x'], { encoding: 'utf8', env: { ...process.env, HTTPS_PROXY: '', https_proxy: '' } }).status, EXIT_USAGE); + } + + // ── the wiring ────────────────────────────────────────────────────────── + battery('the wiring: both halves around the one POST, on the write verb only'); + { + const { WIRED_WRITE_TOOLS } = await import('./write-pace.mjs'); + const own = readReal(SELF_PATH, 'utf8'); + t('write-pace lists this file among the wired write tools', WIRED_WRITE_TOOLS.includes('issue-create.mjs')); + t('this file calls both halves, guarded by the write-verb predicate', own.includes('paceWrite(') && own.includes('noteResponse(') && own.includes('isWriteMethod(')); + const records = readReal(paceFile, 'utf8'); + t('the POSTs above were paced; the read-backs were not', [records.includes('issue-create POST'), records.includes('issue-create GET')], [true, false]); + t('⛔ and the token never reached the throttle\'s log', records.includes(TOKEN_FIXTURE), false); + } + } finally { + rmSync(dir, { recursive: true, force: true }); + } + + // ── the floor, BEFORE the verdict ───────────────────────────────────────── + const declared = Object.keys(SELF_TEST_BATTERIES); + const floor = []; + if (declared.length < SELF_TEST_BATTERY_FLOOR) { + floor.push(`the battery ledger declares ${declared.length} batteries, below its floor of ${SELF_TEST_BATTERY_FLOOR} — a section that stopped being declared is a section nothing floors.`); + } + for (const [name, count] of batteryCases) { + if (name in SELF_TEST_BATTERIES) continue; + floor.push(`self-test battery "${name}" registered ${count} case(s) but is not declared in SELF_TEST_BATTERIES — an assertion attributed to no declared battery is one nothing floors.`); + } + for (const name of declared) { + const count = batteryCases.get(name) ?? 0; + if (count >= SELF_TEST_BATTERIES[name]) continue; + floor.push( + count === 0 + ? `self-test battery "${name}" DID NOT RUN — 0 cases registered, ${SELF_TEST_BATTERIES[name]} pinned. The verdict below would have claimed those cases hold.` + : `self-test battery "${name}" registered ${count} case(s), below its pinned floor of ${SELF_TEST_BATTERIES[name]} — cases that used to run no longer do.`, + ); + } + for (const message of floor) cases.push({ name: message, ok: false, detail: '' }); + + const failed = cases.filter((c) => !c.ok); + for (const c of failed) console.error(` ✗ ${c.name}${c.detail ? ` — ${c.detail}` : ''}`); + if (failed.length) { + console.error(`✗ issue-create self-test: ${failed.length} of ${cases.length} case(s) failed.`); + selfTestReachedVerdict = true; + return 1; + } + console.log( + `✓ issue-create self-test: ${cases.length} cases pass across ${declared.length} batteries — prose from files and never argv, ` + + 'one title source, a fake platform through every exit code, a dry run that sends nothing, and both halves of the throttle around the one POST.', + ); + selfTestReachedVerdict = true; + return 0; +} + +// --------------------------------------------------------------------------- +// Dispatch +// --------------------------------------------------------------------------- + +const USAGE = [ + 'usage:', + ' node scripts/pm/issue-create.mjs [--repo owner/name] (--title-file | --title ) --body-file ', + ' [--label ]… [--assignee ]… [--json] [--dry-run]', + ' node scripts/pm/issue-create.mjs --self-test', + '', + ' The body comes from a file, always; the title from a file by preference. A batch of N ≥ 5 cards is', + ' announced first: node scripts/pm/write-pace.mjs --announce-batch N --kind "issue-create POST"', + ` Exits: 0 created and read back · ${EXIT_USAGE} usage · ${EXIT_PREREQUISITE} prerequisite · ${EXIT_READ_BACK_MISMATCH} read-back mismatch · ${EXIT_PLATFORM_REFUSAL} platform refused · ${EXIT_WRITE_PACE_REFUSED} throttle refused`, +].join('\n'); + +function rearmThroughProxy(args) { + const plan = proxyRearmPlan({ + env: process.env, + execArgv: process.execArgv, + flagSupported: process.allowedNodeEnvironmentFlags.has(PROXY_FLAG), + guard: PROXY_REARM_GUARD, + }); + if (plan.hint) { + console.error(`ℹ️ ${plan.reason}. A refusal below may be about the route, not this container.`); + return null; + } + if (!plan.rearm) return null; + console.error(`ℹ️ re-exec with ${plan.flag}: ${plan.reason}.`); + const quiet = process.allowedNodeEnvironmentFlags.has('--disable-warning') ? ['--disable-warning=UNDICI-EHPA'] : []; + const child = spawnSync(process.execPath, [plan.flag, ...quiet, SELF_PATH, ...args], { + stdio: 'inherit', + env: { ...process.env, [PROXY_REARM_GUARD]: '1' }, + }); + if (typeof child.status === 'number') return child.status; + console.error(`⚠️ could not re-exec with ${plan.flag} (${child.error?.message ?? 'no exit status'}); continuing in-process — the request will bypass the proxy.`); + return null; +} + +export async function main(argv) { + const opts = parseArgs(argv); + if (opts.help) { + console.log(USAGE); + return EXIT_OK; + } + if (opts.selfTest) return selfTest(); + if (opts.unknown.length || opts.errors.length) { + for (const e of opts.errors) console.error(`issue-create: ${e}`); + if (opts.unknown.length) console.error(`issue-create: unrecognised argument ${opts.unknown.map((u) => `\`${u}\``).join(', ')}`); + console.error(`\n${USAGE}`); + return EXIT_USAGE; + } + const plan = planFrom(opts); + if (!plan.ok) { + for (const e of plan.errors) console.error(`✗ issue-create: ${e}`); + console.error(' Nothing was sent.'); + return EXIT_USAGE; + } + if (opts.dryRun) { + console.log(dryRunText(plan)); + return EXIT_OK; + } + const rearmed = rearmThroughProxy(argv); + if (rearmed !== null) return rearmed; + const result = await createIssue(plan); + for (const line of result.lines) console.error(line); + if (opts.json && result.number !== null) console.log(JSON.stringify({ number: result.number, html_url: result.url, author: result.author, repo: plan.repo })); + return result.exitCode; +} + +if (isEntrypoint(import.meta.url)) { + const code = await main(process.argv.slice(2)); + if (process.argv.includes('--self-test') && !selfTestReachedVerdict) { + console.error( + '\n✗ issue-create self-test: selfTest() returned without reaching its verdict, so no success line was\n' + + 'printed. Exiting 0 here would report a self-test that never finished as one that passed.\n', + ); + process.exit(1); + } + process.exit(code); +} diff --git a/scripts/pm/label-write.mjs b/scripts/pm/label-write.mjs index 5da5ab0da01..850f7e40c5d 100644 --- a/scripts/pm/label-write.mjs +++ b/scripts/pm/label-write.mjs @@ -103,7 +103,7 @@ import { readFileSync } from 'node:fs'; import { fileURLToPath } from 'node:url'; import { isEntrypoint } from '../invoked-as.mjs'; -import { isWriteMethod, noteResponse, paceWrite } from './write-pace.mjs'; +import { isWriteMethod, noteResponse, paceWrite, releaseWriteLease } from './write-pace.mjs'; import { EXIT_PREREQUISITE_NOT_MET, PM_EXCLUSIVE_STATE_LABELS, @@ -345,6 +345,7 @@ async function rest(path, { method = 'GET', body = null } = {}) { ...(body ? { body: JSON.stringify(body) } : {}), }); } catch (e) { + if (paced) releaseWriteLease(); // ⏱ rule ④: no response will come, so the fleet's turn ends here return { status: 0, rateRemaining: null, json: null, detail: e?.message ?? 'fetch threw', call: `${method} ${path}` }; } const rateRemaining = res.headers.get('x-ratelimit-remaining'); diff --git a/scripts/pm/with-fleet.sh b/scripts/pm/with-fleet.sh new file mode 100755 index 00000000000..6cd98d9bcde --- /dev/null +++ b/scripts/pm/with-fleet.sh @@ -0,0 +1,278 @@ +#!/usr/bin/env bash +# with-fleet.sh — run ONE command as the fleet's GitHub identity, behind the +# fleet-wide write gate. +# +# scripts/pm/with-fleet.sh -- gh api -X POST /repos/o/r/pulls/12/ready_for_review +# scripts/pm/with-fleet.sh --kind 'git push' -- git push origin HEAD +# scripts/pm/with-fleet.sh --read -- gh api /rate_limit # a read: identity only, no gate +# scripts/pm/with-fleet.sh --batch 17 --kind 'gh api POST' -- … # rule ⑤ announced for this token +# scripts/pm/with-fleet.sh --self-test # offline: a fixture cache, no network +# +# What it does, in order: +# +# ① `fleet-token.mjs --export` — the App's installation token (cached at +# mode 0600, minted when stale, serialised across processes by the write +# lease), evaluated into THIS shell: GITHUB_TOKEN and GH_TOKEN for `gh` +# and for every tool under scripts/pm that reads +# `process.env.GITHUB_TOKEN ?? process.env.GH_TOKEN` — which is how no +# business line in those tools had to change. +# ② the git identity, from the environment only: the COMMITTER is always +# `` <`+@users.noreply.github.com`>; +# the AUTHOR is the same unless `OS_FLEET_GIT_AUTHOR_LOGIN` named a real +# login, which `fleet-token.mjs` resolved to its numeric id — so a commit +# can read "someone authored, objectstack-fleet[bot] committed" while the +# actor of the push stays the bot. +# ③ git credentials, from the environment only: `GIT_CONFIG_COUNT` pairs +# that RESET the credential-helper list (the host's keychain would answer +# first with a person's token) and add `fleet-git-credential.sh`, which +# reads the token from `GITHUB_TOKEN` when git asks. Nothing lands in any +# config file, no remote URL carries a token, and `git remote -v` is +# unchanged — stronger than a masked URL, because there is nothing to mask. +# ④ `write-pace.mjs --run` — the lease (one write in flight, fleet-wide), the +# gap, the batch gap when announced, the stop marker — around the command, +# with inherited stdio; `--read` skips ④ because a read is never gated. +# +# Exit codes: the command's own, passed through. Before the command runs: +# 2 usage · 3 / 5 / 10 exactly as `fleet-token.mjs` and `write-pace.mjs` +# define them (prerequisite · platform refused · throttle refused), with +# their prescriptions already printed. +# +# ⛔ The token is never printed by this script, never placed in an argument, +# and never written anywhere but the minter's 0600 cache. `set -x` in a +# CALLING shell would echo the eval'd exports — do not trace this script. + +set -euo pipefail + +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +SELF="${HERE}/$(basename "${BASH_SOURCE[0]}")" # absolute: the self-test cd's into a throwaway repo +EXIT_USAGE=2 + +usage() { + cat >&2 << 'USAGE' +usage: + scripts/pm/with-fleet.sh [--read] [--kind