diff --git a/.env.example b/.env.example index 8ef3c8ce..0c9d9bf1 100644 --- a/.env.example +++ b/.env.example @@ -44,6 +44,8 @@ GH_PAT= # Repository allowlist path REPOSITORY_ALLOWLIST_PATH=config/repositories.json +# true = só repos de config/repositories.json; false/ausente = todos os repos da instalação do App +REPOSITORY_ALLOWLIST_ENFORCE=false # ── Telegram Notifications ─────────────────────────────────────────────── diff --git a/ts/src/agents/core/repo-manager.ts b/ts/src/agents/core/repo-manager.ts index 3330219c..815cf995 100644 --- a/ts/src/agents/core/repo-manager.ts +++ b/ts/src/agents/core/repo-manager.ts @@ -14,8 +14,7 @@ export class RepositoryManager { const updatedAt = new Map(); try { for (const repo of await this.gh.getUserRepos({ limit: null })) { - if (repo.owner.login.trim().toLowerCase() !== this.targetOwner.trim().toLowerCase()) continue; - if (!enforce || this.allowlist.isAllowed(repo.full_name)) { + if (repo.owner.login.trim().toLowerCase() !== this.targetOwner.trim().toLowerCase()) continue; if (!enforce || this.allowlist.isAllowed(repo.full_name)) { all.add(repo.full_name); const u = Date.parse(repo.updated_at ?? repo.pushed_at ?? ""); if (!Number.isNaN(u)) updatedAt.set(repo.full_name.toLowerCase().trim(), u); diff --git a/ts/src/agents/registry.ts b/ts/src/agents/registry.ts index 40a7b87b..8306d615 100644 --- a/ts/src/agents/registry.ts +++ b/ts/src/agents/registry.ts @@ -19,7 +19,7 @@ export const registeredNames = () => [...AGENTS_BY_NAME.keys()]; export function createBaseDeps(s: Settings) { return { githubClient: new GithubClient(s.githubToken), - allowlist: new RepositoryAllowlist(s.repositoryAllowlistPath), + allowlist: new RepositoryAllowlist(s.repositoryAllowlistPath, process.env.REPOSITORY_ALLOWLIST_ENFORCE === "true"), telegram: new TelegramNotifier(s.telegramBotToken, s.telegramChatId), }; } diff --git a/ts/src/config/allowlist.ts b/ts/src/config/allowlist.ts index 54f60751..540b9570 100644 --- a/ts/src/config/allowlist.ts +++ b/ts/src/config/allowlist.ts @@ -9,7 +9,8 @@ const toSet = (xs: unknown) => new Set((Array.isArray(xs) ? xs : []).map(norm).f export class RepositoryAllowlist { private repos = new Set(); private users = new Set(); - constructor(public path = process.env.REPOSITORY_ALLOWLIST_PATH ?? "config/repositories.json") { this.load(); } + /** enforce=false: repo allowlist is off (every repo is allowed; owner scope still applies). Users list still loads. */ + constructor(public path = process.env.REPOSITORY_ALLOWLIST_PATH ?? "config/repositories.json", public enforce = true) { this.load(); } load(): void { try { @@ -31,6 +32,7 @@ export class RepositoryAllowlist { isAllowed(repository: string): boolean { const n = norm(repository); if (!n) return false; + if (!this.enforce) return n.includes("/"); if (this.repos.has(n)) return true; return n.includes("/") && this.users.has(n.split("/")[0]); } @@ -47,6 +49,6 @@ export class RepositoryAllowlist { addRepository(r: string) { return this.mutate(this.repos, r, true); } removeRepository(r: string) { return this.mutate(this.repos, r, false); } listUsers() { return [...this.users].sort(); } - listRepositories() { return [...this.repos].sort(); } + listRepositories() { return this.enforce ? [...this.repos].sort() : []; } clear() { this.repos.clear(); this.save(); } } diff --git a/ts/src/github/client.ts b/ts/src/github/client.ts index c2595e08..efadb550 100644 --- a/ts/src/github/client.ts +++ b/ts/src/github/client.ts @@ -75,7 +75,16 @@ export class GithubClient { getPull(repo: string, n: number): Promise { return this.get(`/repos/${repo}/pulls/${n}`); } /** Resolve a search-result issue to its PR. */ getPrFromIssue(issue: any): Promise { return this.get(issue.pull_request?.url ?? `/repos/${issue.repository_url.replace(/.*repos\//, "")}/pulls/${issue.number}`); } - getUserRepos(o: { sort?: string; direction?: string; limit?: number | null } = {}) { + /** App installation tokens cannot call /user/repos (403): list /installation/repositories first, fall back to /user/repos for PATs. */ + async getUserRepos(o: { sort?: string; direction?: string; limit?: number | null } = {}): Promise { + try { + const all = await this.paginate("/installation/repositories", { key: "repositories" }); + const field = o.sort === "created" ? "created_at" : o.sort === "pushed" ? "pushed_at" : "updated_at"; + const dir = o.direction === "asc" ? 1 : -1; + all.sort((a, b) => dir * String(a[field] ?? "").localeCompare(String(b[field] ?? ""))); + const limit = o.limit === undefined ? 10 : o.limit; + return limit ? all.slice(0, limit) : all; + } catch (e) { if (!(e instanceof GithubError) || ![401, 403, 404].includes(e.status)) throw e; } return this.paginate(`/user/repos?sort=${o.sort ?? "updated"}&direction=${o.direction ?? "desc"}`, { limit: o.limit === undefined ? 10 : o.limit ?? undefined }); } getIssueComments(repo: string, n: number) { return this.paginate(`/repos/${repo}/issues/${n}/comments`); } diff --git a/ts/tests/installation-repos.test.ts b/ts/tests/installation-repos.test.ts new file mode 100644 index 00000000..35d62d00 --- /dev/null +++ b/ts/tests/installation-repos.test.ts @@ -0,0 +1,44 @@ +import { expect, test } from "bun:test"; +import { join } from "node:path"; +import { tmpdir } from "node:os"; +import { GithubClient, GithubError } from "../src/github/client.ts"; +import { RepositoryAllowlist } from "../src/config/allowlist.ts"; + +const missing = join(tmpdir(), "no-such-allowlist.json"); + +test("allowlist desligada: qualquer owner/repo passa, lista de repos fica vazia", () => { + const a = new RepositoryAllowlist(missing, false); + expect(a.isAllowed("me/anything")).toBe(true); + expect(a.isAllowed("noslash")).toBe(false); + expect(a.listRepositories()).toEqual([]); +}); + +test("allowlist ligada continua restritiva", () => { + expect(new RepositoryAllowlist(missing, true).isAllowed("me/anything")).toBe(false); +}); + +function client(handler: (path: string) => any[] | Error) { + const c = new GithubClient("t") as any; + c.paginate = async (path: string) => { const r = handler(path); if (r instanceof Error) throw r; return r; }; + return c as GithubClient; +} + +test("getUserRepos usa /installation/repositories, ordena por updated desc e respeita limit", async () => { + const seen: string[] = []; + const c = client((p) => { seen.push(p); return [{ full_name: "a/old", updated_at: "2026-01-01" }, { full_name: "a/new", updated_at: "2026-03-01" }]; }); + const r = await c.getUserRepos({ limit: 1 }); + expect(seen).toEqual(["/installation/repositories"]); + expect(r.map((x: any) => x.full_name)).toEqual(["a/new"]); +}); + +test("getUserRepos cai para /user/repos quando o token nao e de instalacao (403)", async () => { + const seen: string[] = []; + const c = client((p) => { seen.push(p); return p.startsWith("/installation") ? new GithubError(403, "forbidden") : [{ full_name: "a/b" }]; }); + expect((await c.getUserRepos({ limit: null })).length).toBe(1); + expect(seen[1]).toStartWith("/user/repos"); +}); + +test("getUserRepos propaga erros que nao sao de autenticacao", async () => { + const c = client(() => new GithubError(500, "boom")); + await expect(c.getUserRepos({ limit: null })).rejects.toThrow("boom"); +});