Skip to content

feat(broker): service tokens for apps (TZ-5, part 1) - #312

Merged
delpher merged 2 commits into
masterfrom
feat/service-tokens-core
Dec 1, 2026
Merged

delpher merged 2 commits into
masterfrom
feat/service-tokens-core

Conversation

@delpher

@delpher delpher commented Dec 1, 2026

Copy link
Copy Markdown
Owner

TZ-5 v2 (project note #244), section 2, part 1: the core of the broker.

What changes

  • App.service?: string: the outside service an app works with on its callers' behalf (github next). Checked at start: ^[a-z0-9-]+$, no two apps with the same service.
  • AppTool.run(me, args, call): may return a Promise. call.serviceToken() takes no parameter: the token of the app's own service from the header X-Service-Token-<service> of the current /mcp request, or null. A call the app keeps answers null once the call has ended.
  • Masking: if the token shows up in a tool's answer (anywhere in the result) or in an error's text, it is replaced with [service token].
  • callTool is async and takes CallContext { headers }; mcp.ts passes extra.requestInfo?.headers, and tools_call passes them on. Everything else (preflight, tests) has no headers, so no token.
  • The core's tools and app tools without a token stay synchronous (settle/dispatch). Tests use callToolNow, which throws on a tool that answers later.
  • src/broker/service-tokens.ts: header parsing with the same rules as src/adapters/core/serviceTokens.mjs (feat(adapters): shared service-token core #308): trimmed, printable ASCII without spaces, ≤1024. An empty value counts as no header ({file:} in OpenCode gives exactly that when the file is missing).

Tests (service-tokens.test.ts, through a real /mcp)

  • only the app of that service gets the token; another service's app and an app with no service get null; without a header, null
  • masking in the answer and in an error; tools_call carries the header; a kept call gives null after the call
  • guard: a broker on a file DB with every call path exercised (app tools, tools_call, a message, a status, a note). Afterwards the fake token is looked for in every file of the data folder and every log line, and is not found.

npm test locally: 672 tests, 666 pass. The 5 failures are updater.test under Git Bash (tar takes C: for a host), the environment and unrelated to this change; CI will run them properly.

Next (part 2): src/apps/github, GET /api/services, POST /api/services/<id>/check.

🤖 Generated with Claude Code

An app may declare `service: "<id>"`; its tools get the caller's token to
that service from the /mcp request header `X-Service-Token-<id>` through
`call.serviceToken()` - its own service only, only while the call runs.
No header, no token (fail closed). The token is masked in answers and
errors and kept nowhere: a guard test looks for a fake token in every file
of the data folder and every log line.

- AppTool.run may return a Promise; callTool is async, the core's tools
  and apps without a token still answer synchronously
- tools_call passes the request's headers on
- callToolNow: the synchronous form for tests
- service ids: ^[a-z0-9-]+$, one app per service; token: printable ASCII,
  no spaces, up to 1024, trimmed - the same rules as adapters/core

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

delpher commented Dec 1, 2026

Copy link
Copy Markdown
Owner Author

Перевірив гілку локально (не лише diff): переключив клон на feat/service-tokens-core, tsc чисто, dist/test/service-tokens.test.js — 4/4 pass. Плюс прочитав усі місця, де callTool викликається в продакшн-коді: тільки mcp.ts (async-хендлер) і preflight.ts (await) — тобто жодного забутого синхронного виклику, який проковтнув би Promise.

Логіка мені подобається: синхронний шлях справді лишається синхронним (settle), «свій сервіс, лише під час виклику» тримається на замиканні live, і serviceTokenFrom відкидає рівно те, що не може бути значенням заголовка — та сама перевірка, що в adapters/core, тож контракт не розʼїдеться.

Блокерів немає. Три дрібниці, всі — «варто, але не зараз»:

  1. Тест-сторож може пройти «вхолосту». Він перевіряє, що aichat.db є серед файлів, але не перевіряє, що в ній справді щось записалося. Якщо колись зламається запис повідомлення, тест усе одно позеленіє — бо шукатиме токен у порожньому файлі. Один рядок: після send_message прочитати БД (або файл) і впевнитись, що там є hello. Тоді «токена немає» означає «токена немає в даних, які точно записались».

  2. maskResult серіалізує весь результат, навіть коли токен туди потрапити не міг. Для pr_files з diff на сотні кілобайт це два зайві повні проходи на кожен виклик. Дешевше маскувати лише content[].text (решта — base64-картинки, де токена не буде), а JSON.parse лишати як запасний шлях.

  3. callToolNow лежить у продакшн-модулі, хоч потрібен лише тестам. Зараз його ніхто, крім тестів, не кличе — але якщо колись покличе, отримає throw уже після того, як інструмент почав роботу (у тесті це нормально, у продакшн-шляху — втрачений виклик). Або перенести в test/helpers, або позначити коментарем «лише для тестів», щоб це було видно з сигнатури.

Питання одне, не блокер: serviceTokenFrom свідомо не приймає Headers-обʼєкт, бо SDK віддає Record<string, string | string[] | undefined> (types.d.ts:7949) — це правильно, просто зафіксуй у коментарі, що тип перевірено, інакше наступний читач вирішить, що .get() забули.

З мого боку (ТЗ-5, кроки 3–5) усе готове до інтеграції: serviceTokens у ядрі адаптерів змерджено, менеджер пише токени й AICHAT_SERVICE_TOKENS для claude. Чекаю на GET /api/services і POST /api/services/<id>/check, щоб доробити сторінку.

…338)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@delpher
delpher merged commit b9d4680 into master Dec 1, 2026
3 checks passed
@delpher
delpher deleted the feat/service-tokens-core branch December 1, 2026 19:42
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