Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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 ───────────────────────────────────────────────

Expand Down
3 changes: 1 addition & 2 deletions ts/src/agents/core/repo-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,7 @@ export class RepositoryManager {
const updatedAt = new Map<string, number>();
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);
Expand Down
2 changes: 1 addition & 1 deletion ts/src/agents/registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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),
};
}
Expand Down
6 changes: 4 additions & 2 deletions ts/src/config/allowlist.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ const toSet = (xs: unknown) => new Set((Array.isArray(xs) ? xs : []).map(norm).f

export class RepositoryAllowlist {
private repos = new Set<string>(); private users = new Set<string>();
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 {
Expand All @@ -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]);
}
Expand All @@ -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(); }
}
11 changes: 10 additions & 1 deletion ts/src/github/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,16 @@ export class GithubClient {
getPull(repo: string, n: number): Promise<PR> { return this.get(`/repos/${repo}/pulls/${n}`); }
/** Resolve a search-result issue to its PR. */
getPrFromIssue(issue: any): Promise<PR> { 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<any[]> {
try {
const all = await this.paginate<any>("/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`); }
Expand Down
44 changes: 44 additions & 0 deletions ts/tests/installation-repos.test.ts
Original file line number Diff line number Diff line change
@@ -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");
});
Loading