Files
conversation-history/SquareMCP/2026-06-13-option-a-capability-enforcement-kimi-handoff.md
T

332 lines
13 KiB
Markdown

# 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
1. Do not rename, redirect, remove, or repurpose any existing endpoint.
2. Do not change existing OAuth client IDs, secrets, redirect URIs, or tokens.
3. Do not require existing users to reconnect.
4. Do not modify the authorization behavior of API keys, JWT session cookies, or the global API key.
5. An OAuth client with `allowed_capabilities IS NULL` is a legacy unrestricted client.
6. An existing OAuth token whose client has `allowed_capabilities IS NULL` remains unrestricted.
7. Capability restrictions apply only to OAuth clients explicitly configured with a non-null capability list.
8. Do not infer restrictions from client names, callback URLs, requested OAuth scopes, schema URLs, or user subscription plans.
9. Do not alter `/mcp`, `/sse`, `/messages`, `/tools`, or `/hermes-mcp/:linkSegment/:toolName` behavior in this change.
10. 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.json` already exists locally.
- `/openapi-communications.json` already exists locally.
- `/openapi-social-publisher.json` already exists locally.
- `src/manifest.ts`, `src/index.ts`, `src/oauth-login-routes.test.ts`, and `src/tools.ts` already contain user changes.
- `videos/.DS_Store` is unrelated and must be ignored.
Before editing, run:
```bash
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`:
```text
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:
```sql
allowed_capabilities JSON NULL
```
Requirements:
- Include it in the `CREATE TABLE IF NOT EXISTS oauth_clients` definition.
- Add it using the existing `ensureColumn` migration pattern.
- Do not backfill existing rows.
- `NULL` must 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:
```ts
allowed_capabilities: OAuthCapability[] | null;
```
Parse database JSON defensively:
- SQL `NULL` becomes `null`.
- 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:
```ts
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:
```sql
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 `validateAccessToken` and `getTokenCustomer` unless 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/register` ignores submitted `allowed_capabilities`.
- `registerClient()` creates dynamic clients with `allowed_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:
```json
{
"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:
```text
/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:
1. Null client policy is unrestricted.
2. Living Brief parses as `['obsidian']`.
3. Empty array remains explicitly restricted.
4. Malformed non-null policy fails closed.
5. DCR cannot self-assign capabilities.
6. Existing registration calls preserve policy.
7. Living Brief registration stores `['obsidian']`.
8. Token lookup joins token to client policy.
9. Expired and unknown tokens fail.
10. 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
```bash
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
1. Deploy nullable column with all existing rows left `NULL`.
2. Deploy code that preserves null-policy legacy access and enforces configured clients.
3. Verify existing Claude, ChatGPT, browser, CLI, and app connections.
4. Verify every legacy schema URL returns 200.
5. Register a dedicated Living Brief OAuth client.
6. Set only it to `["obsidian"]`.
7. Import `/openapi-living-brief.json` into the new GPT.
8. Complete OAuth with the new client and callback.
9. Prove Obsidian succeeds and email/social calls return 403.
10. 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` — added `allowed_capabilities JSON NULL` to `oauth_clients` (CREATE TABLE + ensureColumn migration)
- `src/oauth.ts` — added `OAuthCapability` type, `Client.allowed_capabilities`, `getTokenAuthorization`, defensive capability parsing, DCR capability restrictions, capability-aware `ensureOAuthAppRegistered`, capability-aware consent HTML
- `src/index.ts` — `requireAuth` attaches `clientId` + `allowedCapabilities`; added `requireCapability` middleware; applied to all `/api/{obsidian,email,whatsapp,linkedin,telegram,discord,instagram,twitter,facebook,tiktok}/*` routes; added `GET /openapi-living-brief.json`
- `src/manifest.ts` — added `LIVING_BRIEF_PATHS` (Obsidian-only) and `getOpenApiSpecLivingBrief`
- `src/oauth.test.ts` — added capability + `getTokenAuthorization` tests
- `src/oauth-dcr.test.ts` — added capability preservation / explicit setting tests
- `src/oauth-login-routes.test.ts` — updated mocks for `getTokenAuthorization` / `getOpenApiSpecLivingBrief`
- `src/capability-routes.test.ts` — new route-level enforcement tests
- `src/manifest.test.ts` — new schema tests
**Migration behavior:**
- New column is nullable; existing rows remain `NULL` (unrestricted legacy)
- Idempotent `ensureColumn` migration; 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:**
- `getTokenAuthorization` returns `allowedCapabilities: null` for `allowed_capabilities IS NULL`
- `requireCapability` allows when `allowedCapabilities === null`
- Route test confirms legacy OAuth token succeeds on Obsidian, email, and social routes
**Evidence Living Brief is Obsidian-only:**
- `LIVING_BRIEF_PATHS` contains 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.