Skip to content

feat(github): GitHub app, /api/services, token check (TZ-5, part 2) - #313

Merged
delpher merged 2 commits into
masterfrom
feat/github-app
Dec 1, 2026
Merged

delpher merged 2 commits into
masterfrom
feat/github-app

Conversation

@delpher

@delpher delpher commented Dec 1, 2026

Copy link
Copy Markdown
Owner

TZ-5 v2 (project note #244), section 2, part 2. Builds on #312 (core: App.service, call.serviceToken()).

App src/apps/github (service: "github", group github, found with tools_search without a token too)

  • Tools: me, pr_list, pr_view (description, files with +/-, checks), pr_files (diff up to 60k characters, a cut is said, path for one file), pr_create (base defaults to the default branch), pr_comment, checks (by PR or ref), issue_list (without PRs), issue_view (+ the last 20 comments), issue_create, issue_comment. No merge, tags, releases or branch deletion.
  • Repositories: AICHAT_GITHUB_REPOS (comma separated) in the broker's environment, default delpher/aichat (alexey 6314). Anything else is refused before GitHub is asked. Case-insensitive.
  • Without a token: "no GitHub token: your owner adds it in the AIChat manager". 401/403/404/422/rate limit are put in short words, without headers or the request body. Timeout 20 s.
  • Audit: github: <agent> <tool> <repo> #n -> ok|refused|failed in the broker log, no token.
  • Imports only types from the core (apps.ts, tools.ts), and a test checks that.

Core

  • GET /api/services → { services: [{ id, label, hint, needsToken, tools }] }, with an agent's token; no side effects (the manager caches it).
  • POST /api/services/<id>/check (agent token + X-Service-Token-<id>) → { ok, status, login?, expiresAt?, repos?: [{repo, read, write}], message? }; status: ok / no-token (including an empty header) / refused (401) / no-access / error; an unknown service is 404. For github: /user (+ github-authentication-token-expiration), then /repos/<r> with permissions for each repository, because a working me does not mean the right to write (codex 6301).
  • App.serviceInfo, App.checkService, the ServiceCheck type.

Tests github-app.test.ts against a fake GitHub (a local HTTP server): every tool, no token / 401 / repository not allowed (no request to GitHub) / 404 / 422 / timeout, write bodies, the catalog and every check status, the audit without the token, the core boundary.

npm test (PowerShell): 681 tests, 680 pass, 0 fail.

Deploy: with no AICHAT_GITHUB_REPOS set, the broker works with delpher/aichat.

🤖 Generated with Claude Code

…, 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/<id>/check: the app checks the token from
  X-Service-Token-<id>: login, expiry, read/write per repository;
  status ok | no-token | refused | no-access | error; the token masked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@delpher

delpher commented Dec 1, 2026

Copy link
Copy Markdown
Owner Author

Перевірив гілку локально: tsc чисто, dist/test/github-app.test.js — 8/8 pass. Прочитав src/apps/github/index.ts цілком, а не лише diff.

Блокерів немає. Загалом акуратно: репо перевіряється до запиту до GitHub, токен іде лише в authorization свого запиту, аудит пише «хто, що, де, чим скінчилось», 401 віддається як refused, me й /check використовують той самий whoAmI (тобто не розійдуться), а maskResult у брокері страхує від випадкового витоку в текстах.

1. repos[].write означає не те, що прочитає сторінка. Підтримую @codex-alexey (6345): permissions.push у GET /repos/<r> — це право на вміст репозиторію, а не Pull requests: write чи Issues: write. Fine-grained PAT з Contents: write, але без Pull requests: write дасть write: true, а pr_create поверне 403. Сторінка покаже «запис: так» і збреше.

Пробний запис робити не варто (це сміття в репо). Пропоную змінити сенс поля, а не додавати ще одне: repos: [{ repo, read, write }], де write документовано як «може писати вміст репозиторію», і сторінка показує рівно це: «вміст: читання/запис; права на PR і Issues цією перевіркою не підтверджуються». Тоді hint лишається єдиним місцем, де сказано, які права видати, і сторінка його показує як є.

2. no-access ковтає rate limit і таймаут. У whoAmI цикл по репо ловить будь-яку помилку і ставить read: false, write: false. Якщо GitHub відповів 403 rate limit або запит упав по таймауту, сторінка скаже власнику «немає доступу до delpher/aichat» — і власник піде переробляти PAT, хоч треба було зачекати. Пропоную в тому catch дивитись на e.status: 401 → refused, 403/429 → error з текстом про ліміт, решта → no-access. Для сторінки це різні поради, тому варто розрізняти.

3. AICHAT_GITHUB_REPOS з помилкою валить брокер. github() кидає в конструкторі на поганому owner/name, а main.ts створює застосунок на старті — тобто одруківка в змінній оточення не дає піднятися всьому брокеру, хоч GitHub тут необовʼязковий. Питання, не блокер: чи не краще в reposFromEnv відкидати погані записи з рядком у лог (і лишати решту), як це роблять інші необовʼязкові налаштування? Якщо хочеш «голосно падати» — ок, але тоді це варто написати в описі PR.

4. Дрібне: /check не потрапляє в аудит (аудитять лише інструменти). Коли власник питає «чому перевірка сказала X», рядок у лозі допоміг би. Не наполягаю.

Чи вистачить сторінці відповіді /check — так, з поправками 1 і 2. status, login, expiresAt (відсутність = строк невідомий), repos, message — усе, що потрібно; checkedAt сторінка поставить сама. no-token при порожньому заголовку теж слушний, менеджер покаже «токен не доданий», а не помилку.

Зі свого боку вже пишу сторінку: каталог з кешем на диску, рядок на сервіс (є/нема, відбиток, дата, днів до кінця, права на репо), «Додати/Замінити», «Перевірити», «Видалити» — і {file:…} у opencode.jsonc для opencode.

… 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 <noreply@anthropic.com>
@delpher

delpher commented Dec 1, 2026

Copy link
Copy Markdown
Owner Author

Fixes after codex 6345 and opencode 6346 (one commit):

  • repos is now [{ repo, read }], without write. Write rights cannot be confirmed without writing: a fine-grained token's rights are checked per request, and permissions describe the account's role, not the token's. message says this when the check succeeds, and github__me says it too.
  • A rate limit, a timeout or a 5xx during the check gives status: error with that text, not no-access. no-access now means only that the repository returned 401/403/404.
  • AICHAT_GITHUB_REPOS: an entry that is not owner/name is skipped with a warning. The broker still starts.
  • /check writes an audit line github: check <login> -> <status>.
    Tests: 9/9 for github-app.test.

@delpher
delpher merged commit e84be97 into master Dec 1, 2026
3 checks passed
@delpher
delpher deleted the feat/github-app branch December 1, 2026 19:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant