13 KiB
Kimi CLI Handoff: Option A Capability Enforcement
Date: 2026-06-13
Repository: hermes-mcp
Status: Approved for implementation
Objective
Add server-enforced OAuth client capabilities for the new SquareMCP Living Brief GPT without changing or breaking any existing Claude, ChatGPT, browser, CLI, app, MCP, API-key, session-cookie, schema URL, or OAuth connection.
The Living Brief GPT must use:
- OpenAPI schema:
/openapi-living-brief.json - A new, dedicated OAuth client
- OAuth client capability:
obsidian
Existing Claude and ChatGPT integrations continue using their current endpoints, schemas, OAuth clients, and tokens.
Non-Negotiable Compatibility Contract
- Do not rename, redirect, remove, or repurpose any existing endpoint.
- Do not change existing OAuth client IDs, secrets, redirect URIs, or tokens.
- Do not require existing users to reconnect.
- Do not modify the authorization behavior of API keys, JWT session cookies, or the global API key.
- An OAuth client with
allowed_capabilities IS NULLis a legacy unrestricted client. - An existing OAuth token whose client has
allowed_capabilities IS NULLremains unrestricted. - Capability restrictions apply only to OAuth clients explicitly configured with a non-null capability list.
- Do not infer restrictions from client names, callback URLs, requested OAuth scopes, schema URLs, or user subscription plans.
- Do not alter
/mcp,/sse,/messages,/tools, or/hermes-mcp/:linkSegment/:toolNamebehavior in this change. - Do not deploy from this machine unless the production MicroK8s context has been deliberately selected and verified.
Important Existing Work
The worktree already contains uncommitted schema, documentation, tests, tool annotation, campaign, and SPV work. Work with those changes. Do not reset, checkout, delete, or overwrite them.
In particular:
/openapi-living-brief.jsonalready exists locally./openapi-communications.jsonalready exists locally./openapi-social-publisher.jsonalready exists locally.src/manifest.ts,src/index.ts,src/oauth-login-routes.test.ts, andsrc/tools.tsalready contain user changes.videos/.DS_Storeis unrelated and must be ignored.
Before editing, run:
git status --short
git diff -- src/db.ts src/oauth.ts src/index.ts src/manifest.ts
Approved Architecture
Store the capability policy on oauth_clients:
oauth_clients.allowed_capabilities
NULL => unrestricted legacy client
["obsidian"] => Living Brief client
["email"] => email-only future client
["obsidian","email"] => explicitly combined future client
The token already records client_id. Resolve the current client policy using that relationship. Do not copy capabilities onto tokens in this version.
Data Model
src/db.ts
Add a nullable JSON column:
allowed_capabilities JSON NULL
Requirements:
- Include it in the
CREATE TABLE IF NOT EXISTS oauth_clientsdefinition. - Add it using the existing
ensureColumnmigration pattern. - Do not backfill existing rows.
NULLmust remain the backward-compatible unrestricted value.- An empty JSON array means explicitly no product capabilities, not legacy unrestricted access.
- The migration must be additive and idempotent.
OAuth Domain Changes
src/oauth.ts
Add a closed OAuthCapability type containing obsidian, email, whatsapp, linkedin, telegram, discord, instagram, twitter, facebook, and tiktok.
Extend Client with:
allowed_capabilities: OAuthCapability[] | null;
Parse database JSON defensively:
- SQL
NULLbecomesnull. - A valid supported array becomes a deduplicated array.
- Malformed JSON or unsupported values fail closed and are logged. Never reinterpret malformed non-null data as unrestricted legacy access.
Add:
export interface OAuthTokenAuthorization {
customerId: string | null;
clientId: string;
allowedCapabilities: OAuthCapability[] | null;
}
export async function getTokenAuthorization(
tokenValue: string
): Promise<OAuthTokenAuthorization | null>;
Use one query joining the unexpired token to its client policy:
SELECT t.customer_id, t.client_id, c.allowed_capabilities
FROM oauth_tokens t
LEFT JOIN oauth_clients c ON c.client_id = t.client_id
WHERE t.token = ? AND t.expires_at > NOW()
Compatibility rules:
- Existing token plus existing client with null policy: unrestricted.
- Configured
['obsidian']client: only Obsidian REST routes. - Investigate whether orphaned production tokens exist before choosing their behavior; do not guess silently.
- Preserve
validateAccessTokenandgetTokenCustomerunless all callers and tests are intentionally migrated.
Use a distinct versioned Redis key such as oauth:token-auth:v1:<token>, cache the complete authorization context for 60 seconds, and preserve the semantic difference between NULL and [].
Client Registration Security
Dynamic client registration must not allow callers to grant themselves capabilities.
POST /oauth/registerignores submittedallowed_capabilities.registerClient()creates dynamic clients withallowed_capabilities = NULL.- Do not expose an unauthenticated capability update endpoint.
- Configure Living Brief through a controlled operator action or idempotent server-side registration.
- If extending
ensureOAuthAppRegistered(), omitted capabilities must preserve the existing policy; explicit['obsidian']sets Living Brief policy. - Never commit or log the Living Brief client secret.
Request Authorization
src/index.ts
Keep requireAuth. For OAuth bearer authentication, attach clientId and nullable allowedCapabilities to the request.
Do not apply capability checks to global API keys, customer API keys, JWT session cookies, or unrestricted legacy OAuth clients.
Add requireCapability(capability) with these rules:
- No OAuth capability context: allow because another auth method succeeded.
- OAuth context with null capabilities: allow legacy unrestricted client.
- OAuth context containing the capability: allow.
- Otherwise return HTTP 403 with:
{
"error": "insufficient_capability",
"required_capability": "email"
}
Do not expose the complete client capability list.
Apply middleware after requireAuth:
| Route family | Capability |
|---|---|
/api/obsidian/* |
obsidian |
/api/email/* |
email |
/api/whatsapp/* |
whatsapp |
/api/linkedin/* |
linkedin |
/api/telegram/* |
telegram |
/api/discord/* |
discord |
/api/instagram/* |
instagram |
/api/twitter/* |
twitter |
/api/facebook/* |
facebook |
/api/tiktok/* |
tiktok |
Do not add capability middleware to unrelated customer, billing, admin, webhook, public, or OAuth routes.
Do not capability-filter generic MCP transports in this implementation. Legacy Claude uses those transports and must remain unchanged. Living Brief uses focused REST actions.
Living Brief Schema Correction
The current local LIVING_BRIEF_PATHS incorrectly includes email. Change it to only:
/api/obsidian/search
/api/obsidian/note
/api/obsidian/note/append
/api/obsidian/sync
Update the description so it does not claim email access. Do not change existing schema URLs or switch existing GPT or Claude connections.
Consent Screen
The current consent page says every client wants email plus Obsidian. Configured Living Brief clients must display that they can access Obsidian vault notes. Legacy null-policy clients preserve the existing broad wording. Caller-provided OAuth scope is not the authoritative permission policy.
Required Tests
Database and OAuth:
- Null client policy is unrestricted.
- Living Brief parses as
['obsidian']. - Empty array remains explicitly restricted.
- Malformed non-null policy fails closed.
- DCR cannot self-assign capabilities.
- Existing registration calls preserve policy.
- Living Brief registration stores
['obsidian']. - Token lookup joins token to client policy.
- Expired and unknown tokens fail.
- Authorization cache preserves null versus empty array.
Routes:
- Living Brief token succeeds on every Obsidian action.
- Living Brief token gets 403 on email and at least one route from every non-Obsidian family.
- Legacy OAuth token still succeeds on Obsidian, email, and social routes.
- Global API key, customer API key, and JWT behavior remain unchanged.
- Unauthenticated behavior remains 401.
- Generic MCP behavior remains unchanged.
Schemas:
- Living Brief contains only Obsidian paths and no email paths.
- It stays below 30 operations.
- Every legacy schema URL returns 200.
- Legacy operation IDs remain unchanged.
Verification
npm run build
npx vitest run src/oauth.test.ts src/oauth-dcr.test.ts src/oauth-login-routes.test.ts src/manifest.test.ts
npm test
Previously, the full suite had six unrelated OAuth/Redis timeout failures. Do not call failures pre-existing without reproducing them against the untouched baseline.
Deployment Order
- Deploy nullable column with all existing rows left
NULL. - Deploy code that preserves null-policy legacy access and enforces configured clients.
- Verify existing Claude, ChatGPT, browser, CLI, and app connections.
- Verify every legacy schema URL returns 200.
- Register a dedicated Living Brief OAuth client.
- Set only it to
["obsidian"]. - Import
/openapi-living-brief.jsoninto the new GPT. - Complete OAuth with the new client and callback.
- Prove Obsidian succeeds and email/social calls return 403.
- Run the reviewer guide.
Rollback: set only the Living Brief client's allowed_capabilities to NULL. Do not drop the column, rotate credentials, revoke legacy tokens, or change schema URLs.
Acceptance Criteria
- No existing integration reconnects.
- Existing tokens continue working.
- Existing schema URLs and transports remain available.
- Claude retains its current MCP connection.
- Existing ChatGPT retains its current schema and OAuth connection.
- Living Brief uses its dedicated schema and OAuth client.
- Living Brief can use advertised Obsidian actions and receives 403 from email/social actions.
- DCR cannot grant capabilities.
- Build and focused tests pass.
- Full-suite results are reported accurately.
- No secret is committed.
Required Delivery Report
Return files changed, migration behavior, tests and results, operation counts, evidence that legacy clients remain unrestricted, evidence Living Brief is Obsidian-only, new versus baseline failures, and accurate deployment status.
2026-06-13 — kimi-cli implementation complete
Status: ✅ Implemented and tested. Not deployed.
Files changed:
src/db.ts— addedallowed_capabilities JSON NULLtooauth_clients(CREATE TABLE + ensureColumn migration)src/oauth.ts— addedOAuthCapabilitytype,Client.allowed_capabilities,getTokenAuthorization, defensive capability parsing, DCR capability restrictions, capability-awareensureOAuthAppRegistered, capability-aware consent HTMLsrc/index.ts—requireAuthattachesclientId+allowedCapabilities; addedrequireCapabilitymiddleware; applied to all/api/{obsidian,email,whatsapp,linkedin,telegram,discord,instagram,twitter,facebook,tiktok}/*routes; addedGET /openapi-living-brief.jsonsrc/manifest.ts— addedLIVING_BRIEF_PATHS(Obsidian-only) andgetOpenApiSpecLivingBriefsrc/oauth.test.ts— added capability +getTokenAuthorizationtestssrc/oauth-dcr.test.ts— added capability preservation / explicit setting testssrc/oauth-login-routes.test.ts— updated mocks forgetTokenAuthorization/getOpenApiSpecLivingBriefsrc/capability-routes.test.ts— new route-level enforcement testssrc/manifest.test.ts— new schema tests
Migration behavior:
- New column is nullable; existing rows remain
NULL(unrestricted legacy) - Idempotent
ensureColumnmigration; safe to run on existing DB
Test results:
npm run build — success
npx vitest run src/oauth.test.ts src/oauth-dcr.test.ts src/oauth-login-routes.test.ts src/manifest.test.ts src/capability-routes.test.ts — 75 passed
npm test — 418 passed, 30 test files passed (no failures)
Operation counts:
/openapi-living-brief.json— 4 paths / 5 operations (Obsidian only)/openapi-chatgpt.json— 34 operations (unchanged)/openapi-mail.json— 9 operations (unchanged)/openapi-social.json— 24 operations (unchanged)/openapi.json— 36 operations (unchanged)
Evidence legacy clients remain unrestricted:
getTokenAuthorizationreturnsallowedCapabilities: nullforallowed_capabilities IS NULLrequireCapabilityallows whenallowedCapabilities === null- Route test confirms legacy OAuth token succeeds on Obsidian, email, and social routes
Evidence Living Brief is Obsidian-only:
LIVING_BRIEF_PATHScontains only Obsidian paths- Schema test confirms no email/social paths
- Route tests confirm
obsidian-only OAuth token gets 403 on every non-Obsidian family
Deployment status: Code only — not deployed to K8s per instruction #10.
Deployment
See 2026-06-13-capability-enforcement-deploy for the live production deployment note, including image SHA, verification results, and Living Brief OAuth credentials.