From e15f65d7973be02236e0d39c3a4ad89e61a7ce75 Mon Sep 17 00:00:00 2001 From: Onashchuk Oleksii Date: Tue, 1 Dec 2026 21:45:59 +0200 Subject: [PATCH 1/2] feat(github): the GitHub app, /api/services and the token check (TZ-5, part 2) - src/apps/github: me, pr_list, pr_view, pr_files (diff up to 60k chars), pr_create, pr_comment, checks, issue_list, issue_view, issue_create, issue_comment - with the caller's own token; no merge, tags or releases. Repositories from AICHAT_GITHUB_REPOS (default delpher/aichat), refused before GitHub is asked; 20 s timeout; GitHub's refusals in a few words; an audit line per call without the token. - GET /api/services: the catalog of services from the apps (id, label, hint, tools), no side effects. - POST /api/services//check: the app checks the token from X-Service-Token-: login, expiry, read/write per repository; status ok | no-token | refused | no-access | error; the token masked. Co-Authored-By: Claude Opus 5.5 --- src/apps/github/index.ts | 458 ++++++++++++++++++++++++++++++++++++ src/broker/apps.ts | 24 ++ src/broker/broker.ts | 42 +++- src/broker/main.ts | 4 +- src/test/github-app.test.ts | 228 ++++++++++++++++++ 5 files changed, 753 insertions(+), 3 deletions(-) create mode 100644 src/apps/github/index.ts create mode 100644 src/test/github-app.test.ts diff --git a/src/apps/github/index.ts b/src/apps/github/index.ts new file mode 100644 index 00000000..4f23de6f --- /dev/null +++ b/src/apps/github/index.ts @@ -0,0 +1,458 @@ +// GitHub as an app (TZ-5, 2; AIChat #244 v2): narrow tools over the GitHub API, called with the caller's own token, +// which its adapter sends with the /mcp request (`X-Service-Token-github`) and the broker hands over for the length +// of one call. The app keeps no token, writes none to a log or an answer, and works only in the repositories its +// configuration allows; what a token may do there is GitHub's to decide (the PAT's rights and the repository rules). +// No merge, tags, releases or branch deletion: people do those (TZ-5, 2). +import type { App, AppCall, AppHost, AppTool, ServiceCheck } from "../../broker/apps.js"; +import type { ToolResult } from "../../broker/tools.js"; + +export const GITHUB_SERVICE = "github"; +/** How long one request to GitHub may take before the tool gives up: a stuck GitHub must not hold /mcp. */ +export const GITHUB_TIMEOUT_MS = 20_000; +/** The longest diff pr_files gives in one answer; the rest is named, and read with a local `git fetch`. */ +export const MAX_DIFF_CHARS = 60_000; +/** The longest text of a PR or an issue a view shows. */ +const MAX_BODY = 6_000; +const MAX_COMMENT = 1_500; +const MAX_TITLE = 256; +const MAX_TEXT = 65_000; + +export interface GithubOptions { + /** The repositories the tools work in, `owner/name`; anything else is refused before GitHub is asked. */ + repos: string[]; + /** The API root; GitHub's unless a test or GitHub Enterprise says otherwise. */ + apiBase?: string; + fetch?: typeof fetch; + timeoutMs?: number; +} + +/** The repositories from `AICHAT_GITHUB_REPOS` (comma separated), or the pilot's one (alexey 6314: delpher/aichat). */ +export function reposFromEnv(v = process.env.AICHAT_GITHUB_REPOS): string[] { + const list = (v ?? "").split(",").map((s) => s.trim()).filter(Boolean); + return list.length ? list : ["delpher/aichat"]; +} + +const REPO_RE = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/; +const BRANCH_RE = /^[A-Za-z0-9._/-]{1,200}$/; + +const text = (t: string): ToolResult => ({ content: [{ type: "text", text: t }] }); +const cut = (s: string, max: number) => (s.length > max ? `${s.slice(0, max)}\n… (${s.length - max} more characters)` : s); +const day = (iso: unknown) => (typeof iso === "string" ? iso.slice(0, 16).replace("T", " ") : "?"); + +/** An error the model reads as it is: GitHub's answer put in a few words, without headers or the request. */ +class GithubError extends Error { + constructor(message: string, readonly status = 0) { + super(message); + } +} + +function str(v: unknown, field: string, max: number, required = true): string { + if (v == null || v === "") { + if (required) throw new GithubError(`${field} is required`); + return ""; + } + if (typeof v !== "string") throw new GithubError(`${field} must be a string`); + const t = v.trim(); + if (required && !t) throw new GithubError(`${field} is required`); + if (t.length > max) throw new GithubError(`${field} is longer than ${max} characters`); + return t; +} + +function num(v: unknown, field: string): number { + const n = Number(v); + if (!Number.isSafeInteger(n) || n <= 0) throw new GithubError(`${field} must be a positive whole number`); + return n; +} + +function state(v: unknown): "open" | "closed" | "all" { + if (v == null || v === "") return "open"; + if (v === "open" || v === "closed" || v === "all") return v; + throw new GithubError("state must be open, closed or all"); +} + +type Json = Record; +const obj = (v: unknown): Json => (v && typeof v === "object" ? (v as Json) : {}); +const login = (v: unknown) => String(obj(v).login ?? "?"); + +export function github(opts: GithubOptions): App { + const allowed = new Map(opts.repos.map((r) => [r.toLowerCase(), r])); + for (const r of opts.repos) if (!REPO_RE.test(r)) throw new Error(`github: repository ${r} is not owner/name`); + const apiBase = (opts.apiBase ?? "https://api.github.com").replace(/\/+$/, ""); + const doFetch = opts.fetch ?? fetch; + const timeoutMs = opts.timeoutMs ?? GITHUB_TIMEOUT_MS; + let host: AppHost | undefined; + + /** The repository argument, as one of the allowed. */ + function repoArg(v: unknown): string { + const r = str(v, "repo", 200); + const known = allowed.get(r.toLowerCase()); + if (!known) throw new GithubError(`repository ${r} is not open to AIChat's GitHub tools (allowed: ${opts.repos.join(", ")})`); + return known; + } + + /** One call to GitHub with the caller's token: the parsed answer and its headers, or a GithubError in a few words. */ + async function api(call: AppCall, method: string, path: string, body?: unknown): Promise<{ data: unknown; headers: Headers }> { + const token = call.serviceToken(); + if (!token) throw new GithubError("no GitHub token: your owner adds it in the AIChat manager (agent card, service tokens)"); + let res: Response; + try { + res = await doFetch(`${apiBase}${path}`, { + method, + headers: { + accept: "application/vnd.github+json", + authorization: `Bearer ${token}`, + "user-agent": "aichat-broker", + "x-github-api-version": "2022-11-28", + ...(body === undefined ? {} : { "content-type": "application/json" }), + }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }), + signal: AbortSignal.timeout(timeoutMs), + }); + } catch (e) { + const name = (e as Error)?.name; + if (name === "TimeoutError" || name === "AbortError") throw new GithubError(`GitHub did not answer in ${Math.round(timeoutMs / 1000)} s`); + throw new GithubError("GitHub cannot be reached from the broker"); + } + const raw = await res.text(); + let data: unknown = null; + try { + data = raw ? JSON.parse(raw) : null; + } catch { + data = null; + } + if (res.ok) return { data, headers: res.headers }; + throw new GithubError(describe(res, data), res.status); + } + + /** GitHub's refusal as the model reads it. */ + function describe(res: Response, data: unknown): string { + const said = typeof obj(data).message === "string" ? String(obj(data).message).slice(0, 200) : ""; + const details = Array.isArray(obj(data).errors) + ? (obj(data).errors as unknown[]) + .map((e) => (typeof e === "string" ? e : String(obj(e).message ?? obj(e).code ?? ""))) + .filter(Boolean) + .join("; ") + .slice(0, 300) + : ""; + if (res.status === 401) return "GitHub refused the token (401): it is wrong or expired; your owner replaces it in the AIChat manager"; + if (res.status === 403 || res.status === 429) { + if (res.headers.get("x-ratelimit-remaining") === "0" || res.status === 429) { + const reset = Number(res.headers.get("x-ratelimit-reset")); + return `GitHub's rate limit is spent${reset ? `, until ${new Date(reset * 1000).toISOString().slice(11, 16)} UTC` : ""}`; + } + return `GitHub forbids this (403)${said ? `: ${said}` : ""}: the token lacks the right for it`; + } + if (res.status === 404) return "not found on GitHub (404), or the token cannot see it"; + if (res.status === 422) return `GitHub did not accept it (422)${said ? `: ${said}` : ""}${details ? ` (${details})` : ""}`; + return `GitHub answered ${res.status}${said ? `: ${said}` : ""}`; + } + + /** Writes a line of the audit (TZ-5, 2): who did what where, never a token. */ + function audit(me: string, tool: string, repo: string, what: string, outcome: string) { + host?.log(`github: ${me} ${tool} ${repo}${what ? ` ${what}` : ""} -> ${outcome}`); + } + + /** A tool that asks GitHub: arguments checked, the call audited, a refusal read by the model. */ + function tool( + name: string, + description: string, + properties: Record>, + required: string[], + run: (call: AppCall, a: Record, me: string) => Promise<{ text: string; repo: string; what?: string }>, + ): AppTool { + return { + name, + description, + inputSchema: { type: "object", properties, required }, + async run(me, a, call) { + try { + const r = await run(call, a, me); + audit(me, name, r.repo, r.what ?? "", "ok"); + return text(r.text); + } catch (e) { + const repo = typeof a.repo === "string" ? a.repo.slice(0, 100) : "?"; + audit(me, name, repo, "", e instanceof GithubError ? "refused" : "failed"); + throw e; + } + }, + }; + } + + const REPO = { type: "string", description: "owner/name, e.g. delpher/aichat" }; + const NUMBER = (what: string) => ({ type: "number", description: `The ${what}'s number` }); + const STATE = { type: "string", enum: ["open", "closed", "all"], description: "open (default), closed or all" }; + + async function checksOf(call: AppCall, repo: string, ref: string): Promise { + const { data } = await api(call, "GET", `/repos/${repo}/commits/${encodeURIComponent(ref)}/check-runs?per_page=50`); + const runs = Array.isArray(obj(data).check_runs) ? (obj(data).check_runs as unknown[]) : []; + return runs.map((r) => { + const c = obj(r); + return `${c.name}: ${c.status === "completed" ? c.conclusion : c.status}`; + }); + } + + async function prFiles(call: AppCall, repo: string, n: number): Promise { + const out: Json[] = []; + for (let page = 1; page <= 3; page++) { + const { data } = await api(call, "GET", `/repos/${repo}/pulls/${n}/files?per_page=100&page=${page}`); + const list = Array.isArray(data) ? (data as unknown[]).map(obj) : []; + out.push(...list); + if (list.length < 100) break; + } + return out; + } + + /** The caller's GitHub login, the token's end and its rights in each allowed repository. */ + async function whoAmI(call: AppCall): Promise { + const { data, headers } = await api(call, "GET", "/user"); + const expires = headers.get("github-authentication-token-expiration"); + const repos: ServiceCheck["repos"] = []; + for (const repo of opts.repos) { + try { + const p = obj(obj((await api(call, "GET", `/repos/${repo}`)).data).permissions); + repos.push({ repo, read: p.pull === true, write: p.push === true }); + } catch { + repos.push({ repo, read: false, write: false }); + } + } + const expiresAt = expires ? new Date(expires.replace(" UTC", "Z").replace(" ", "T").replace(/ ([+-]\d{2})(\d{2})$/, "$1:$2")) : null; + const allRead = repos.every((r) => r.read); + return { + ok: allRead, + status: allRead ? "ok" : "no-access", + login: login(data), + ...(expiresAt && !Number.isNaN(expiresAt.getTime()) ? { expiresAt: expiresAt.toISOString() } : {}), + repos, + ...(allRead ? {} : { message: "the token cannot read every allowed repository" }), + }; + } + + const tools: AppTool[] = [ + tool("me", "Who you are on GitHub with your token: login, when the token ends, and what it may do in each repository open to these tools.", {}, [], async (call) => { + const c = await whoAmI(call); + const lines = [ + `GitHub login: ${c.login}`, + `token ends: ${c.expiresAt ?? "not said (no end, or a classic token)"}`, + ...(c.repos ?? []).map((r) => `${r.repo}: ${r.write ? "read and write" : r.read ? "read only" : "no access"}`), + ]; + return { text: lines.join("\n"), repo: opts.repos.join(",") }; + }), + tool( + "pr_list", + "Pull requests of a repository: number, title, state, branches, author, last update.", + { repo: REPO, state: STATE }, + ["repo"], + async (call, a) => { + const repo = repoArg(a.repo); + const { data } = await api(call, "GET", `/repos/${repo}/pulls?state=${state(a.state)}&per_page=30&sort=updated&direction=desc`); + const list = Array.isArray(data) ? (data as unknown[]).map(obj) : []; + const lines = list.map( + (p) => + `#${p.number} ${p.title} [${p.merged_at ? "merged" : p.state}${p.draft ? ", draft" : ""}] ${obj(p.head).ref} -> ${obj(p.base).ref} by ${login(p.user)}, ${day(p.updated_at)}`, + ); + return { text: lines.length ? lines.join("\n") : `no ${state(a.state)} pull requests in ${repo}`, repo }; + }, + ), + tool( + "pr_view", + "One pull request: its text, state, branches, the files it changes (with +/- lines) and its checks. The diff itself is pr_files.", + { repo: REPO, number: NUMBER("pull request") }, + ["repo", "number"], + async (call, a) => { + const repo = repoArg(a.repo); + const n = num(a.number, "number"); + const p = obj((await api(call, "GET", `/repos/${repo}/pulls/${n}`)).data); + const files = await prFiles(call, repo, n); + const checks = await checksOf(call, repo, String(obj(p.head).sha ?? "")).catch(() => ["(checks could not be read)"]); + const lines = [ + `#${n} ${p.title}`, + `state: ${p.merged_at ? `merged ${day(p.merged_at)}` : p.state}${p.draft ? ", draft" : ""}; mergeable: ${p.mergeable ?? "unknown"}`, + `${obj(p.head).ref} -> ${obj(p.base).ref}, by ${login(p.user)}, opened ${day(p.created_at)}, updated ${day(p.updated_at)}`, + `url: ${p.html_url}`, + "", + cut(String(p.body ?? "(no description)"), MAX_BODY), + "", + `files (${files.length}, +${p.additions ?? "?"} -${p.deletions ?? "?"}):`, + ...files.map((f) => ` ${f.status} ${f.filename} +${f.additions} -${f.deletions}`), + "", + `checks: ${checks.length ? "" : "none"}`, + ...checks.map((c) => ` ${c}`), + ]; + return { text: lines.join("\n"), repo, what: `#${n}` }; + }, + ), + tool( + "pr_files", + `The diff of a pull request, file by file, up to ${MAX_DIFF_CHARS} characters; a cut is said. Give path to read one file. For more, fetch the branch with git.`, + { repo: REPO, number: NUMBER("pull request"), path: { type: "string", description: "Only this file" } }, + ["repo", "number"], + async (call, a) => { + const repo = repoArg(a.repo); + const n = num(a.number, "number"); + const only = str(a.path, "path", 500, false); + const files = (await prFiles(call, repo, n)).filter((f) => !only || f.filename === only); + if (only && !files.length) throw new GithubError(`#${n} does not change ${only}`); + let out = ""; + const left: string[] = []; + for (const f of files) { + const part = `--- ${f.filename} (${f.status}, +${f.additions} -${f.deletions})\n${typeof f.patch === "string" ? f.patch : "(no text diff: binary or too large)"}\n\n`; + if (out.length + part.length > MAX_DIFF_CHARS) left.push(String(f.filename)); + else out += part; + } + if (left.length) out += `… not shown (over ${MAX_DIFF_CHARS} characters): ${left.join(", ")}`; + return { text: out || "no files", repo, what: `#${n}` }; + }, + ), + tool( + "pr_create", + "Opens a pull request from a branch you pushed. base defaults to the repository's default branch.", + { + repo: REPO, + title: { type: "string" }, + head: { type: "string", description: "The branch with your commits" }, + base: { type: "string", description: "The branch to merge into (default: the repository's default)" }, + body: { type: "string", description: "The description (Markdown)" }, + draft: { type: "boolean" }, + }, + ["repo", "title", "head"], + async (call, a) => { + const repo = repoArg(a.repo); + const title = str(a.title, "title", MAX_TITLE); + const head = str(a.head, "head", 200); + if (!BRANCH_RE.test(head)) throw new GithubError("head must be a branch name"); + let base = str(a.base, "base", 200, false); + if (base && !BRANCH_RE.test(base)) throw new GithubError("base must be a branch name"); + if (!base) base = String(obj((await api(call, "GET", `/repos/${repo}`)).data).default_branch ?? "master"); + const body = str(a.body, "body", MAX_TEXT, false); + const p = obj((await api(call, "POST", `/repos/${repo}/pulls`, { title, head, base, body, draft: a.draft === true })).data); + return { text: `opened #${p.number} ${p.title} (${head} -> ${base}): ${p.html_url}`, repo, what: `#${p.number}` }; + }, + ), + tool( + "pr_comment", + "Writes a comment on a pull request (a review verdict, an answer).", + { repo: REPO, number: NUMBER("pull request"), body: { type: "string", description: "The comment (Markdown)" } }, + ["repo", "number", "body"], + async (call, a) => { + const repo = repoArg(a.repo); + const n = num(a.number, "number"); + const c = obj((await api(call, "POST", `/repos/${repo}/issues/${n}/comments`, { body: str(a.body, "body", MAX_TEXT) })).data); + return { text: `commented on #${n}: ${c.html_url}`, repo, what: `#${n}` }; + }, + ), + tool( + "checks", + "The checks (CI) of a pull request or of a branch, tag or commit.", + { repo: REPO, number: NUMBER("pull request"), ref: { type: "string", description: "A branch, tag or commit, instead of number" } }, + ["repo"], + async (call, a) => { + const repo = repoArg(a.repo); + let ref = str(a.ref, "ref", 200, false); + let what = ref; + if (a.number != null && a.number !== "") { + const n = num(a.number, "number"); + ref = String(obj(obj((await api(call, "GET", `/repos/${repo}/pulls/${n}`)).data).head).sha ?? ""); + what = `#${n}`; + } + if (!ref) throw new GithubError("give number or ref"); + const checks = await checksOf(call, repo, ref); + return { text: checks.length ? checks.join("\n") : `no checks on ${what}`, repo, what }; + }, + ), + tool( + "issue_list", + "Issues of a repository (pull requests left out): number, title, state, labels, author, last update.", + { repo: REPO, state: STATE }, + ["repo"], + async (call, a) => { + const repo = repoArg(a.repo); + const { data } = await api(call, "GET", `/repos/${repo}/issues?state=${state(a.state)}&per_page=30&sort=updated&direction=desc`); + const list = (Array.isArray(data) ? (data as unknown[]).map(obj) : []).filter((i) => !i.pull_request); + const lines = list.map((i) => { + const labels = Array.isArray(i.labels) ? (i.labels as unknown[]).map((l) => String(obj(l).name ?? l)).join(", ") : ""; + return `#${i.number} ${i.title} [${i.state}]${labels ? ` {${labels}}` : ""} by ${login(i.user)}, ${day(i.updated_at)}`; + }); + return { text: lines.length ? lines.join("\n") : `no ${state(a.state)} issues in ${repo}`, repo }; + }, + ), + tool( + "issue_view", + "One issue with its text and its last comments.", + { repo: REPO, number: NUMBER("issue") }, + ["repo", "number"], + async (call, a) => { + const repo = repoArg(a.repo); + const n = num(a.number, "number"); + const i = obj((await api(call, "GET", `/repos/${repo}/issues/${n}`)).data); + const { data } = await api(call, "GET", `/repos/${repo}/issues/${n}/comments?per_page=100`); + const comments = (Array.isArray(data) ? (data as unknown[]).map(obj) : []).slice(-20); + const lines = [ + `#${n} ${i.title} [${i.state}]${i.pull_request ? " (a pull request: see pr_view)" : ""}`, + `by ${login(i.user)}, opened ${day(i.created_at)}, updated ${day(i.updated_at)}; url: ${i.html_url}`, + "", + cut(String(i.body ?? "(no description)"), MAX_BODY), + ...comments.flatMap((c) => ["", `— ${login(c.user)}, ${day(c.created_at)}:`, cut(String(c.body ?? ""), MAX_COMMENT)]), + ]; + return { text: lines.join("\n"), repo, what: `#${n}` }; + }, + ), + tool( + "issue_create", + "Opens an issue.", + { + repo: REPO, + title: { type: "string" }, + body: { type: "string", description: "The text (Markdown)" }, + labels: { type: "array", items: { type: "string" }, description: "Labels that exist in the repository" }, + }, + ["repo", "title"], + async (call, a) => { + const repo = repoArg(a.repo); + const labels = Array.isArray(a.labels) ? a.labels.filter((l): l is string => typeof l === "string").slice(0, 10) : []; + const i = obj( + (await api(call, "POST", `/repos/${repo}/issues`, { title: str(a.title, "title", MAX_TITLE), body: str(a.body, "body", MAX_TEXT, false), ...(labels.length ? { labels } : {}) })).data, + ); + return { text: `opened issue #${i.number} ${i.title}: ${i.html_url}`, repo, what: `#${i.number}` }; + }, + ), + tool( + "issue_comment", + "Writes a comment on an issue.", + { repo: REPO, number: NUMBER("issue"), body: { type: "string", description: "The comment (Markdown)" } }, + ["repo", "number", "body"], + async (call, a) => { + const repo = repoArg(a.repo); + const n = num(a.number, "number"); + const c = obj((await api(call, "POST", `/repos/${repo}/issues/${n}/comments`, { body: str(a.body, "body", MAX_TEXT) })).data); + return { text: `commented on #${n}: ${c.html_url}`, repo, what: `#${n}` }; + }, + ), + ]; + + return { + name: "github", + service: GITHUB_SERVICE, + title: "GitHub", + description: + `Pull requests, checks and issues on GitHub with your own token (your owner adds it in the AIChat manager). Repositories: ${opts.repos.join(", ")}. ` + + "No merge, tags or releases: people do those.", + serviceInfo: { + label: "GitHub", + hint: + `A fine-grained personal access token for ${opts.repos.join(", ")}: Contents read/write, Pull requests read/write, ` + + "Issues read/write, Checks read, Metadata read. github.com → Settings → Developer settings → Fine-grained tokens.", + }, + tools, + async checkService(call) { + try { + return await whoAmI(call); + } catch (e) { + if (!(e instanceof GithubError)) throw e; + return { ok: false, status: e.status === 401 ? "refused" : "error", message: e.message }; + } + }, + start(h) { + host = h; + }, + }; +} diff --git a/src/broker/apps.ts b/src/broker/apps.ts index 030334c7..e6fc6b70 100644 --- a/src/broker/apps.ts +++ b/src/broker/apps.ts @@ -195,6 +195,20 @@ export interface AppTool { run(me: string, args: Record, call: AppCall): ToolResult | Promise; } +/** What a check of a service token found (TZ-5, 2): what the manager shows in the token's line. */ +export interface ServiceCheck { + ok: boolean; + /** ok, no-token (none was sent), refused (the service did not take it), no-access (taken, but not for what is needed), error. */ + status: "ok" | "no-token" | "refused" | "no-access" | "error"; + /** Who the token belongs to at the service. */ + login?: string; + /** When the token stops working, ISO, if the service says. */ + expiresAt?: string; + /** What it may do where the app works (GitHub: each allowed repository). */ + repos?: { repo: string; read: boolean; write: boolean }[]; + message?: string; +} + /** What an app's tool knows of the call at hand (TZ-5, 2). */ export interface AppCall { /** @@ -236,6 +250,16 @@ export interface App { * it (`X-Service-Token-`) and no other. One app per service. */ service?: string; + /** + * What the catalog of services says of its `service` (TZ-5, GET /api/services): a name for people and where to get + * a token with which rights. Without it the catalog shows the service by its id. + */ + serviceInfo?: { label: string; hint: string }; + /** + * Checks the caller's token to its `service` for the manager's "check" (POST /api/services//check): whether the + * service took it, and what it may do with it. Called only with a token; the broker masks it in the answer. + */ + checkService?(call: AppCall): Promise; /** Its tool group as tools_search shows it. */ title?: string; description?: string; diff --git a/src/broker/broker.ts b/src/broker/broker.ts index 47f0905e..4b4dfce8 100644 --- a/src/broker/broker.ts +++ b/src/broker/broker.ts @@ -21,8 +21,8 @@ import { import { Updater, UpdateError } from "./updater.js"; import { buildSetup, TOKEN_PLACEHOLDER } from "./setup.js"; import { agentGuide } from "./agent-guide.js"; -import { APP_NAME_RE, APP_TOOL_RE, APP_TOOL_SEP, CORE_GROUPS_FOR_APPS, CORE_KIND_GROUP, type App, type AppHost, type AppTool } from "./apps.js"; -import { maskResult, maskToken, SERVICE_ID_RE, serviceTokenFrom } from "./service-tokens.js"; +import { APP_NAME_RE, APP_TOOL_RE, APP_TOOL_SEP, CORE_GROUPS_FOR_APPS, CORE_KIND_GROUP, type App, type AppHost, type AppTool, type ServiceCheck } from "./apps.js"; +import { maskResult, maskToken, SERVICE_ID_RE, serviceTokenFrom, serviceTokenHeader } from "./service-tokens.js"; import { NoteNotFound, notesIntoNotebooks, NOTEBOOK_PREFIX } from "./notebooks/index.js"; import { migrate037 } from "./migration-0.37.js"; import { adapterRefusal } from "./adapter-version.js"; @@ -573,6 +573,40 @@ export class Broker { } } + /** The catalog of services (TZ-5, GET /api/services): one line per app that declares a service, no tokens in it. */ + services(): { id: string; label: string; hint: string; needsToken: true; tools: string[] }[] { + const tools = this.appTools(); + return this.apps + .filter((a): a is App & { service: string } => !!a.service) + .map((a) => ({ + id: a.service, + label: a.serviceInfo?.label ?? a.service, + hint: a.serviceInfo?.hint ?? "", + needsToken: true as const, + tools: tools.filter((t) => (a.groups ?? [a.name]).includes(t.group)).map((t) => t.name), + })); + } + + /** + * POST /api/services//check (TZ-5): the app of service `id` checks the caller's token from this request's + * `X-Service-Token-` header. The token goes no further than that call, and the answer has it masked. + */ + async checkService(id: string, headers: Record): Promise { + const app = this.apps.find((a) => a.service === id); + if (!app) throw new BrokerError(`no such service: ${id}`, 404); + const token = serviceTokenFrom(headers, id); + if (!token) return { ok: false, status: "no-token", message: `no ${serviceTokenHeader(id)} header with a usable token` }; + if (!app.checkService) return { ok: false, status: "error", message: `${id} cannot check a token` }; + let live = true; + try { + return maskResult(await app.checkService({ serviceToken: () => (live ? token : null) }), token); + } catch (e) { + return { ok: false, status: "error", message: maskToken((e as Error)?.message ?? String(e), token) }; + } finally { + live = false; + } + } + /** The conversations as a brick: its refs are the keys, and a hand-over keeps id, key and history. */ private conversationsBrick(): Brick { return { @@ -2265,6 +2299,10 @@ export class Broker { return reply(200, body); } if (route === "GET /api/tools") return reply(200, { tools: toolCatalog(this) }); + // TZ-5: the services the broker's apps work with, and a check of the caller's token to one of them + if (route === "GET /api/services") return reply(200, { services: this.services() }); + const check = /^\/api\/services\/([^/]+)\/check$/.exec(url.pathname); + if (check && req.method === "POST") return reply(200, await this.checkService(decodeURIComponent(check[1]), req.headers)); if (url.pathname.startsWith("/api/notebooks/")) return await this.onNotebookRequest(req, url, me, reply); if (route === "GET /api/overview") return reply(200, this.overview(agent)); if (route === "GET /api/agents") return reply(200, { agents: this.agents() }); diff --git a/src/broker/main.ts b/src/broker/main.ts index f924b4ac..59598eb6 100644 --- a/src/broker/main.ts +++ b/src/broker/main.ts @@ -6,6 +6,7 @@ import { Broker } from "./broker.js"; import { chat } from "../apps/chat/index.js"; import { minigames } from "../apps/minigames/index.js"; import { adoptFromEnv, projects } from "../apps/projects/index.js"; +import { github, reposFromEnv } from "../apps/github/index.js"; import { ConfigFile, type BrokerConfig } from "./config.js"; import { VERSION } from "../version.js"; import { RESTART_EXIT_CODE } from "../updates/layout.js"; @@ -55,7 +56,8 @@ broker = new Broker({ updater, // the apps this broker hosts (spec #3, 3.5): the core knows none of them // the migration of 0.37 hands a room over to a project only where AICHAT_ADOPT_037 says which (spec #4, 3.7) - apps: [chat(), minigames(), projects({ adopt: adoptFromEnv() })], + // GitHub with each agent's own token (TZ-5): the repositories it works in come from AICHAT_GITHUB_REPOS + apps: [chat(), minigames(), projects({ adopt: adoptFromEnv() }), github({ repos: reposFromEnv() })], config: () => withEnv(config.get()), editConfig: (fn) => withEnv(config.edit(fn)), // Where the bundled adapters already are when the broker runs from this checkout. Inside Docker the diff --git a/src/test/github-app.test.ts b/src/test/github-app.test.ts new file mode 100644 index 00000000..078344a1 --- /dev/null +++ b/src/test/github-app.test.ts @@ -0,0 +1,228 @@ +// TZ-5, 2: the github app against a fake GitHub (a local HTTP server). Every tool: an answer, a refused token, no +// token, a repository not allowed; the catalog of services and the token check; and the token stays out of answers, +// errors and the log. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { createServer, type IncomingMessage, type Server } from "node:http"; +import { readdirSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import { github, reposFromEnv } from "../apps/github/index.js"; +import { callTool } from "../broker/tools.js"; +import { startBroker, tok } from "./helpers.js"; +import type { Broker } from "../broker/broker.js"; + +const TOKEN = "github_pat_FAKEtz5appTOKEN0123456789"; +const REPO = "delpher/aichat"; + +interface Seen { + method: string; + path: string; + auth: string | undefined; + body: unknown; +} + +/** A fake GitHub: answers by method and path; `TOKEN` is the only token it takes. */ +async function fakeGithub(opts: { slow?: boolean } = {}): Promise<{ server: Server; url: string; seen: Seen[] }> { + const seen: Seen[] = []; + const pr = { + number: 7, + title: "feat: things", + state: "open", + draft: false, + merged_at: null, + mergeable: true, + head: { ref: "feat/x", sha: "abc123" }, + base: { ref: "master" }, + user: { login: "delpher" }, + created_at: "2026-12-01T10:00:00Z", + updated_at: "2026-12-01T11:00:00Z", + html_url: "https://github.com/delpher/aichat/pull/7", + body: "Does things.", + additions: 3, + deletions: 1, + }; + const server = createServer(async (req: IncomingMessage, res) => { + let raw = ""; + for await (const c of req) raw += c; + const url = new URL(req.url ?? "/", "http://x"); + seen.push({ method: req.method ?? "", path: url.pathname + url.search, auth: req.headers.authorization, body: raw ? JSON.parse(raw) : undefined }); + const send = (status: number, body: unknown, headers: Record = {}) => { + res.writeHead(status, { "content-type": "application/json", ...headers }); + res.end(JSON.stringify(body)); + }; + if (opts.slow) return; // never answers + if (req.headers.authorization !== `Bearer ${TOKEN}`) return send(401, { message: "Bad credentials" }); + const p = url.pathname; + const r = `/repos/${REPO}`; + if (p === "/user") return send(200, { login: "delpher" }, { "github-authentication-token-expiration": "2027-01-15 10:00:00 UTC" }); + if (p === r) return send(200, { default_branch: "master", permissions: { pull: true, push: true } }); + if (p === `${r}/pulls` && req.method === "GET") return send(200, [pr]); + if (p === `${r}/pulls` && req.method === "POST") { + const b = JSON.parse(raw) as { title: string; head: string }; + if (b.head === "nope") return send(422, { message: "Validation Failed", errors: [{ message: "No commits between master and nope" }] }); + return send(201, { ...pr, number: 8, title: b.title, html_url: "https://github.com/delpher/aichat/pull/8" }); + } + if (p === `${r}/pulls/7`) return send(200, pr); + if (p === `${r}/pulls/7/files`) + return send(200, [ + { filename: "src/a.ts", status: "modified", additions: 2, deletions: 1, patch: "@@ -1 +1,2 @@\n-a\n+b\n+c" }, + { filename: "img.png", status: "added", additions: 0, deletions: 0 }, + ]); + if (p === `${r}/pulls/404`) return send(404, { message: "Not Found" }); + if (p === `${r}/commits/abc123/check-runs`) + return send(200, { check_runs: [{ name: "Build and test (Node 22)", status: "completed", conclusion: "success" }, { name: "Docker image", status: "in_progress" }] }); + if (p === `${r}/issues` && req.method === "GET") + return send(200, [ + { number: 3, title: "bug", state: "open", labels: [{ name: "bug" }], user: { login: "delpher" }, updated_at: "2026-12-01T09:00:00Z" }, + { number: 7, title: "a PR", state: "open", pull_request: {}, user: { login: "delpher" } }, + ]); + if (p === `${r}/issues` && req.method === "POST") return send(201, { number: 9, title: (JSON.parse(raw) as { title: string }).title, html_url: "https://github.com/delpher/aichat/issues/9" }); + if (p === `${r}/issues/3`) return send(200, { number: 3, title: "bug", state: "open", body: "It breaks.", user: { login: "delpher" }, html_url: "u" }); + if (p === `${r}/issues/3/comments` && req.method === "GET") return send(200, [{ user: { login: "codex" }, created_at: "2026-12-01T09:30:00Z", body: "seen" }]); + if (/\/issues\/\d+\/comments$/.test(p) && req.method === "POST") return send(201, { html_url: "https://github.com/delpher/aichat/pull/7#c1" }); + if (p === "/rate") return send(403, { message: "API rate limit exceeded" }, { "x-ratelimit-remaining": "0", "x-ratelimit-reset": "1800000000" }); + return send(404, { message: "Not Found" }); + }); + await new Promise((ok) => server.listen(0, "127.0.0.1", ok)); + const port = (server.address() as { port: number }).port; + return { server, url: `http://127.0.0.1:${port}`, seen }; +} + +async function setup(t: { after: (fn: () => unknown) => void }, ghOpts: { slow?: boolean; timeoutMs?: number } = {}) { + const gh = await fakeGithub(ghOpts); + const lines: string[] = []; + const { broker, http } = await startBroker([{ name: "a" }], {}, { apps: [github({ repos: [REPO], apiBase: gh.url, timeoutMs: ghOpts.timeoutMs })] }); + (broker as unknown as { log: (m: string) => void }).log = (m) => lines.push(m); + t.after(async () => { + await broker.close(); + gh.server.closeAllConnections(); + gh.server.close(); + }); + const call = async (name: string, args: Record, token: string | null = TOKEN) => { + const r = await callTool("a", `github__${name}`, args, broker, token === null ? {} : { headers: { "x-service-token-github": token } }); + return { text: r.content.map((c) => c.text).join("\n"), isError: !!r.isError }; + }; + return { broker: broker as Broker, http, gh, call, lines }; +} + +test("github: reposFromEnv - a comma list, or the pilot's one", () => { + assert.deepEqual(reposFromEnv(undefined), ["delpher/aichat"]); + assert.deepEqual(reposFromEnv(" a/b , c/d ,"), ["a/b", "c/d"]); + assert.throws(() => github({ repos: ["no-slash"] }), /not owner\/name/); +}); + +test("github: the read tools answer from GitHub with the caller's token", async (t) => { + const { call, gh } = await setup(t); + assert.match((await call("me", {})).text, /GitHub login: delpher\ntoken ends: 2027-01-15T10:00:00.000Z\ndelpher\/aichat: read and write/); + assert.match((await call("pr_list", { repo: REPO })).text, /^#7 feat: things \[open\] feat\/x -> master by delpher, 2026-12-01 11:00$/); + const view = (await call("pr_view", { repo: REPO, number: 7 })).text; + assert.match(view, /#7 feat: things/); + assert.match(view, /modified src\/a\.ts \+2 -1/); + assert.match(view, /Build and test \(Node 22\): success/); + assert.match(view, /Docker image: in_progress/); + const files = (await call("pr_files", { repo: REPO, number: 7 })).text; + assert.match(files, /--- src\/a\.ts \(modified, \+2 -1\)\n@@ -1 \+1,2 @@/); + assert.match(files, /--- img\.png \(added, \+0 -0\)\n\(no text diff/); + assert.match((await call("pr_files", { repo: REPO, number: 7, path: "img.png" })).text, /^--- img\.png/); + assert.match((await call("checks", { repo: REPO, number: 7 })).text, /Build and test \(Node 22\): success/); + assert.match((await call("checks", { repo: REPO, ref: "abc123" })).text, /Docker image/); + const issues = (await call("issue_list", { repo: REPO })).text; + assert.equal(issues, "#3 bug [open] {bug} by delpher, 2026-12-01 09:00", "pull requests are left out of issues"); + assert.match((await call("issue_view", { repo: REPO, number: 3 })).text, /It breaks\.[\s\S]*— codex, 2026-12-01 09:30:\nseen/); + // every request carried the caller's token, and nothing else did + assert.ok(gh.seen.length > 0 && gh.seen.every((s) => s.auth === `Bearer ${TOKEN}`)); +}); + +test("github: the write tools send what they should; base defaults to the default branch", async (t) => { + const { call, gh } = await setup(t); + assert.equal((await call("pr_create", { repo: REPO, title: "feat: y", head: "feat/y", body: "why" })).text, "opened #8 feat: y (feat/y -> master): https://github.com/delpher/aichat/pull/8"); + assert.deepEqual(gh.seen.find((s) => s.method === "POST" && s.path.endsWith("/pulls"))!.body, { title: "feat: y", head: "feat/y", base: "master", body: "why", draft: false }); + const refused = await call("pr_create", { repo: REPO, title: "x", head: "nope", base: "master" }); + assert.equal(refused.isError, true); + assert.match(refused.text, /GitHub did not accept it \(422\): Validation Failed \(No commits between master and nope\)/); + assert.match((await call("pr_create", { repo: REPO, title: "x", head: "bad branch name" })).text, /head must be a branch name/); + assert.match((await call("pr_comment", { repo: REPO, number: 7, body: "LGTM" })).text, /^commented on #7/); + assert.match((await call("issue_create", { repo: REPO, title: "new", labels: ["bug"] })).text, /^opened issue #9 new/); + assert.deepEqual(gh.seen.find((s) => s.method === "POST" && s.path.endsWith("/issues"))!.body, { title: "new", body: "", labels: ["bug"] }); + assert.match((await call("issue_comment", { repo: REPO, number: 3, body: "on it" })).text, /^commented on #3/); +}); + +test("github: no token, a refused token, a repository not allowed, 404 and a stuck GitHub", async (t) => { + const { call, gh } = await setup(t); + const none = await call("pr_list", { repo: REPO }, null); + assert.equal(none.isError, true); + assert.match(none.text, /no GitHub token: your owner adds it in the AIChat manager/); + const wrong = await call("pr_list", { repo: REPO }, "github_pat_WRONG"); + assert.match(wrong.text, /GitHub refused the token \(401\)/); + const before = gh.seen.length; + const other = await call("pr_list", { repo: "someone/else" }); + assert.match(other.text, /repository someone\/else is not open to AIChat's GitHub tools \(allowed: delpher\/aichat\)/); + assert.equal(gh.seen.length, before, "a repository not allowed is refused before GitHub is asked"); + assert.match((await call("pr_list", { repo: "DELPHER/AICHAT" })).text, /#7/, "the owner/name is matched without case"); + assert.match((await call("pr_view", { repo: REPO, number: 404 })).text, /not found on GitHub \(404\), or the token cannot see it/); + assert.match((await call("pr_view", { repo: REPO, number: -1 })).text, /number must be a positive whole number/); + assert.match((await call("pr_list", { repo: REPO, state: "weird" })).text, /state must be open, closed or all/); + + const slow = await setup(t, { slow: true, timeoutMs: 200 }); + assert.match((await slow.call("pr_list", { repo: REPO })).text, /GitHub did not answer in 0 s/); +}); + +test("github: the tools are found without a token, and only a call fails (TZ-5, 1)", async (t) => { + const { broker } = await setup(t); + const found = await callTool("a", "tools_search", { group: "github" }, broker); + const listed = found.content[0].text; + for (const n of ["me", "pr_list", "pr_view", "pr_files", "pr_create", "pr_comment", "checks", "issue_list", "issue_view", "issue_create", "issue_comment"]) + assert.match(listed, new RegExp(`github__${n}\\b`)); + assert.doesNotMatch(listed, /github__\w*(merge|release|tag)/i, "no merge, releases or tags in v1"); +}); + +test("github: GET /api/services lists the service, POST /check checks the token and never shows it", async (t) => { + const { http, lines } = await setup(t); + const auth = { authorization: `Bearer ${tok("a")}` }; + const cat = (await (await fetch(`${http}/api/services`, { headers: auth })).json()) as { services: { id: string; label: string; hint: string; needsToken: boolean; tools: string[] }[] }; + assert.equal(cat.services.length, 1); + assert.equal(cat.services[0].id, "github"); + assert.equal(cat.services[0].label, "GitHub"); + assert.match(cat.services[0].hint, /fine-grained .*delpher\/aichat.*Pull requests read\/write/); + assert.ok(cat.services[0].tools.includes("github__pr_create")); + assert.equal((await fetch(`${http}/api/services`)).status, 401, "the catalog needs an agent's token"); + + const check = async (token?: string) => { + const r = await fetch(`${http}/api/services/github/check`, { method: "POST", headers: { ...auth, ...(token ? { "x-service-token-github": token } : {}) } }); + return { status: r.status, body: (await r.json()) as Record, raw: "" }; + }; + const ok = await check(TOKEN); + assert.equal(ok.status, 200); + assert.deepEqual(ok.body, { ok: true, status: "ok", login: "delpher", expiresAt: "2027-01-15T10:00:00.000Z", repos: [{ repo: REPO, read: true, write: true }] }); + assert.deepEqual((await check()).body.status, "no-token"); + assert.deepEqual((await check("")).body.status, "no-token", "an empty header (OpenCode's {file:} on a missing file) is no token"); + const refused = await check("github_pat_WRONG"); + assert.equal(refused.body.status, "refused"); + assert.equal(refused.body.ok, false); + const none = await fetch(`${http}/api/services/gitlab/check`, { method: "POST", headers: auth }); + assert.equal(none.status, 404); + + // the check is no tool call: it writes no audit line, and the token is in no line + for (const l of lines) assert.ok(!l.includes(TOKEN), l); +}); + +test("github: the audit writes who, what and where, and the token nowhere (answers, errors, log)", async (t) => { + const { call, lines } = await setup(t); + await call("pr_view", { repo: REPO, number: 7 }); + await call("pr_view", { repo: REPO, number: 404 }); + await call("pr_list", { repo: "someone/else" }); + assert.ok(lines.includes("github: a pr_view delpher/aichat #7 -> ok"), lines.join("\n")); + assert.ok(lines.includes("github: a pr_view delpher/aichat -> refused"), lines.join("\n")); + assert.ok(lines.includes("github: a pr_list someone/else -> refused"), lines.join("\n")); + for (const l of lines) assert.ok(!l.includes(TOKEN), l); +}); + +test("github: the app imports nothing of the core but its door (apps.ts) and types", () => { + const dir = join("src", "apps", "github"); + for (const f of readdirSync(dir)) { + const src = readFileSync(join(dir, f), "utf8"); + const imports = [...src.matchAll(/from "([^"]+)"/g)].map((m) => m[1]).filter((m) => m.includes("broker/")); + for (const m of imports) assert.match(m, /broker\/(apps|tools)\.js$/, `${f} imports ${m}`); + assert.ok([...src.matchAll(/^import (?!type)[^;]*broker\//gm)].length === 0, `${f}: only type imports from the core`); + } +}); From 454db3544f111dc0f0dd16a5ee102d579a2dcad9 Mon Sep 17 00:00:00 2001 From: Onashchuk Oleksii Date: Tue, 1 Dec 2026 21:50:25 +0200 Subject: [PATCH 2/2] fix(github): no write claim, a limit is no "no access", a typo starts the broker (codex 6345, opencode 6346) - /check and github__me report only whether the token reads each allowed repository; write rights are not known before a write (a fine-grained token's rights are per request, `permissions` tell the account's role) - a spent rate limit, a timeout or a 5xx while checking is an error, not "no access" - AICHAT_GITHUB_REPOS: a name that is not owner/name is left out with a warning instead of stopping the broker - /check writes an audit line Co-Authored-By: Claude Opus 5.5 --- src/apps/github/index.ts | 61 ++++++++++++++++++++++++++----------- src/broker/apps.ts | 7 +++-- src/test/github-app.test.ts | 26 +++++++++++++--- 3 files changed, 70 insertions(+), 24 deletions(-) diff --git a/src/apps/github/index.ts b/src/apps/github/index.ts index 4f23de6f..11e8ed63 100644 --- a/src/apps/github/index.ts +++ b/src/apps/github/index.ts @@ -26,13 +26,20 @@ export interface GithubOptions { timeoutMs?: number; } -/** The repositories from `AICHAT_GITHUB_REPOS` (comma separated), or the pilot's one (alexey 6314: delpher/aichat). */ -export function reposFromEnv(v = process.env.AICHAT_GITHUB_REPOS): string[] { +const REPO_RE = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/; + +/** + * The repositories from `AICHAT_GITHUB_REPOS` (comma separated), or the pilot's one (alexey 6314: delpher/aichat). A + * name that is not owner/name is left out with a line in `warn`: a typo there must not keep the broker from starting + * (opencode 6346); with nothing left, the tools refuse every repository. + */ +export function reposFromEnv(v = process.env.AICHAT_GITHUB_REPOS, warn: (m: string) => void = (m) => console.error(m)): string[] { const list = (v ?? "").split(",").map((s) => s.trim()).filter(Boolean); - return list.length ? list : ["delpher/aichat"]; + if (!list.length) return ["delpher/aichat"]; + const good = list.filter((r) => REPO_RE.test(r)); + for (const r of list) if (!REPO_RE.test(r)) warn(`AICHAT_GITHUB_REPOS: ${JSON.stringify(r)} is not owner/name, left out`); + return good; } - -const REPO_RE = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/; const BRANCH_RE = /^[A-Za-z0-9._/-]{1,200}$/; const text = (t: string): ToolResult => ({ content: [{ type: "text", text: t }] }); @@ -41,7 +48,11 @@ const day = (iso: unknown) => (typeof iso === "string" ? iso.slice(0, 16).replac /** An error the model reads as it is: GitHub's answer put in a few words, without headers or the request. */ class GithubError extends Error { - constructor(message: string, readonly status = 0) { + /** + * `status` is GitHub's (0: no answer); `passing` marks what says nothing about the token - a spent rate limit, a + * timeout, GitHub out of reach - so a check does not read it as "no access" (opencode 6346). + */ + constructor(message: string, readonly status = 0, readonly passing = false) { super(message); } } @@ -110,8 +121,8 @@ export function github(opts: GithubOptions): App { }); } catch (e) { const name = (e as Error)?.name; - if (name === "TimeoutError" || name === "AbortError") throw new GithubError(`GitHub did not answer in ${Math.round(timeoutMs / 1000)} s`); - throw new GithubError("GitHub cannot be reached from the broker"); + if (name === "TimeoutError" || name === "AbortError") throw new GithubError(`GitHub did not answer in ${Math.round(timeoutMs / 1000)} s`, 0, true); + throw new GithubError("GitHub cannot be reached from the broker", 0, true); } const raw = await res.text(); let data: unknown = null; @@ -121,7 +132,8 @@ export function github(opts: GithubOptions): App { data = null; } if (res.ok) return { data, headers: res.headers }; - throw new GithubError(describe(res, data), res.status); + const limited = res.status === 429 || (res.status === 403 && res.headers.get("x-ratelimit-remaining") === "0"); + throw new GithubError(describe(res, data), res.status, limited || res.status >= 500); } /** GitHub's refusal as the model reads it. */ @@ -202,17 +214,23 @@ export function github(opts: GithubOptions): App { return out; } - /** The caller's GitHub login, the token's end and its rights in each allowed repository. */ + /** + * The caller's GitHub login, the token's end, and whether it reads each allowed repository. Whether it may write + * there is not known before a write: a fine-grained token's rights are checked by GitHub for each kind of request, + * and `permissions` of a repository tell the account's role, not the token's (codex 6345). + */ async function whoAmI(call: AppCall): Promise { const { data, headers } = await api(call, "GET", "/user"); const expires = headers.get("github-authentication-token-expiration"); const repos: ServiceCheck["repos"] = []; for (const repo of opts.repos) { try { - const p = obj(obj((await api(call, "GET", `/repos/${repo}`)).data).permissions); - repos.push({ repo, read: p.pull === true, write: p.push === true }); - } catch { - repos.push({ repo, read: false, write: false }); + await api(call, "GET", `/repos/${repo}`); + repos.push({ repo, read: true }); + } catch (e) { + // a limit or a timeout says nothing of the token: the check fails as an error, not as "no access" + if (!(e instanceof GithubError) || e.passing) throw e; + repos.push({ repo, read: false }); } } const expiresAt = expires ? new Date(expires.replace(" UTC", "Z").replace(" ", "T").replace(/ ([+-]\d{2})(\d{2})$/, "$1:$2")) : null; @@ -223,7 +241,9 @@ export function github(opts: GithubOptions): App { login: login(data), ...(expiresAt && !Number.isNaN(expiresAt.getTime()) ? { expiresAt: expiresAt.toISOString() } : {}), repos, - ...(allRead ? {} : { message: "the token cannot read every allowed repository" }), + message: allRead + ? "write rights are not checked: a write the token lacks is answered 403" + : "the token cannot read every allowed repository", }; } @@ -233,7 +253,8 @@ export function github(opts: GithubOptions): App { const lines = [ `GitHub login: ${c.login}`, `token ends: ${c.expiresAt ?? "not said (no end, or a classic token)"}`, - ...(c.repos ?? []).map((r) => `${r.repo}: ${r.write ? "read and write" : r.read ? "read only" : "no access"}`), + ...(c.repos ?? []).map((r) => `${r.repo}: ${r.read ? "readable" : "not readable with this token"}`), + "write rights are not checked before a write: a missing one is answered 403", ]; return { text: lines.join("\n"), repo: opts.repos.join(",") }; }), @@ -444,12 +465,16 @@ export function github(opts: GithubOptions): App { }, tools, async checkService(call) { + let r: ServiceCheck; try { - return await whoAmI(call); + r = await whoAmI(call); } catch (e) { if (!(e instanceof GithubError)) throw e; - return { ok: false, status: e.status === 401 ? "refused" : "error", message: e.message }; + r = { ok: false, status: e.status === 401 ? "refused" : "error", message: e.message }; } + // a check is audited like a call (opencode 6346): who it was for is the caller of /check, the manager's agent + host?.log(`github: check ${r.login ?? "?"} -> ${r.status}`); + return r; }, start(h) { host = h; diff --git a/src/broker/apps.ts b/src/broker/apps.ts index e6fc6b70..9180934a 100644 --- a/src/broker/apps.ts +++ b/src/broker/apps.ts @@ -204,8 +204,11 @@ export interface ServiceCheck { login?: string; /** When the token stops working, ISO, if the service says. */ expiresAt?: string; - /** What it may do where the app works (GitHub: each allowed repository). */ - repos?: { repo: string; read: boolean; write: boolean }[]; + /** + * Whether it reads each place the app works in (GitHub: each allowed repository). Write rights are not in it: a + * service tells them only by answering a write (codex 6345). + */ + repos?: { repo: string; read: boolean }[]; message?: string; } diff --git a/src/test/github-app.test.ts b/src/test/github-app.test.ts index 078344a1..dd853956 100644 --- a/src/test/github-app.test.ts +++ b/src/test/github-app.test.ts @@ -80,6 +80,7 @@ async function fakeGithub(opts: { slow?: boolean } = {}): Promise<{ server: Serv if (p === `${r}/issues/3`) return send(200, { number: 3, title: "bug", state: "open", body: "It breaks.", user: { login: "delpher" }, html_url: "u" }); if (p === `${r}/issues/3/comments` && req.method === "GET") return send(200, [{ user: { login: "codex" }, created_at: "2026-12-01T09:30:00Z", body: "seen" }]); if (/\/issues\/\d+\/comments$/.test(p) && req.method === "POST") return send(201, { html_url: "https://github.com/delpher/aichat/pull/7#c1" }); + if (p === "/repos/delpher/limited") return send(403, { message: "API rate limit exceeded" }, { "x-ratelimit-remaining": "0" }); if (p === "/rate") return send(403, { message: "API rate limit exceeded" }, { "x-ratelimit-remaining": "0", "x-ratelimit-reset": "1800000000" }); return send(404, { message: "Not Found" }); }); @@ -88,10 +89,10 @@ async function fakeGithub(opts: { slow?: boolean } = {}): Promise<{ server: Serv return { server, url: `http://127.0.0.1:${port}`, seen }; } -async function setup(t: { after: (fn: () => unknown) => void }, ghOpts: { slow?: boolean; timeoutMs?: number } = {}) { +async function setup(t: { after: (fn: () => unknown) => void }, ghOpts: { slow?: boolean; timeoutMs?: number; repos?: string[] } = {}) { const gh = await fakeGithub(ghOpts); const lines: string[] = []; - const { broker, http } = await startBroker([{ name: "a" }], {}, { apps: [github({ repos: [REPO], apiBase: gh.url, timeoutMs: ghOpts.timeoutMs })] }); + const { broker, http } = await startBroker([{ name: "a" }], {}, { apps: [github({ repos: ghOpts.repos ?? [REPO], apiBase: gh.url, timeoutMs: ghOpts.timeoutMs })] }); (broker as unknown as { log: (m: string) => void }).log = (m) => lines.push(m); t.after(async () => { await broker.close(); @@ -108,12 +109,15 @@ async function setup(t: { after: (fn: () => unknown) => void }, ghOpts: { slow?: test("github: reposFromEnv - a comma list, or the pilot's one", () => { assert.deepEqual(reposFromEnv(undefined), ["delpher/aichat"]); assert.deepEqual(reposFromEnv(" a/b , c/d ,"), ["a/b", "c/d"]); + const warned: string[] = []; + assert.deepEqual(reposFromEnv("a/b, typo", (m) => warned.push(m)), ["a/b"], "a typo is left out, the broker still starts"); + assert.match(warned[0], /"typo" is not owner\/name/); assert.throws(() => github({ repos: ["no-slash"] }), /not owner\/name/); }); test("github: the read tools answer from GitHub with the caller's token", async (t) => { const { call, gh } = await setup(t); - assert.match((await call("me", {})).text, /GitHub login: delpher\ntoken ends: 2027-01-15T10:00:00.000Z\ndelpher\/aichat: read and write/); + assert.match((await call("me", {})).text, /GitHub login: delpher\ntoken ends: 2027-01-15T10:00:00.000Z\ndelpher\/aichat: readable\nwrite rights are not checked/); assert.match((await call("pr_list", { repo: REPO })).text, /^#7 feat: things \[open\] feat\/x -> master by delpher, 2026-12-01 11:00$/); const view = (await call("pr_view", { repo: REPO, number: 7 })).text; assert.match(view, /#7 feat: things/); @@ -193,7 +197,7 @@ test("github: GET /api/services lists the service, POST /check checks the token }; const ok = await check(TOKEN); assert.equal(ok.status, 200); - assert.deepEqual(ok.body, { ok: true, status: "ok", login: "delpher", expiresAt: "2027-01-15T10:00:00.000Z", repos: [{ repo: REPO, read: true, write: true }] }); + assert.deepEqual(ok.body, { ok: true, status: "ok", login: "delpher", expiresAt: "2027-01-15T10:00:00.000Z", repos: [{ repo: REPO, read: true }], message: "write rights are not checked: a write the token lacks is answered 403" }); assert.deepEqual((await check()).body.status, "no-token"); assert.deepEqual((await check("")).body.status, "no-token", "an empty header (OpenCode's {file:} on a missing file) is no token"); const refused = await check("github_pat_WRONG"); @@ -226,3 +230,17 @@ test("github: the app imports nothing of the core but its door (apps.ts) and typ assert.ok([...src.matchAll(/^import (?!type)[^;]*broker\//gm)].length === 0, `${f}: only type imports from the core`); } }); + +test("github: the check tells no access from a spent limit (opencode 6346)", async (t) => { + const { http } = await setup(t, { repos: [REPO, "delpher/hidden"] }); + const auth = { authorization: `Bearer ${tok("a")}`, "x-service-token-github": TOKEN }; + const hidden = (await (await fetch(`${http}/api/services/github/check`, { method: "POST", headers: auth })).json()) as Record; + assert.equal(hidden.status, "no-access", "a repository the token cannot see (404) is no access"); + assert.deepEqual(hidden.repos, [{ repo: REPO, read: true }, { repo: "delpher/hidden", read: false }]); + + const limited = await setup(t, { repos: [REPO, "delpher/limited"] }); + const r = (await (await fetch(`${limited.http}/api/services/github/check`, { method: "POST", headers: auth })).json()) as Record; + assert.equal(r.status, "error", "a spent rate limit says nothing of the token"); + assert.match(String(r.message), /rate limit/); + assert.ok(limited.lines.includes("github: check ? -> error"), limited.lines.join("\n")); +});