Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(external-rest-api): pass ownerKind through the OAuth grants lane
Diego Zacarias00dad6a7dc9a
diff --git a/external-rest-api/package.json b/external-rest-api/package.jsonindex 6541f2d31..00d5f1326 100644--- a/external-rest-api/package.json+++ b/external-rest-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-external-rest-api",- "version": "0.1.82",+ "version": "0.1.83","description": "External REST API for profile, team management, and RPC token brokerage","main": "dist/main.js","engines": {diff --git a/external-rest-api/src/releaseManifest.ts b/external-rest-api/src/releaseManifest.tsindex 8e5935da1..9bd4de1c6 100644--- a/external-rest-api/src/releaseManifest.ts+++ b/external-rest-api/src/releaseManifest.ts@@ -8,7 +8,7 @@ export type ReleaseManifest = {export const releaseManifest: ReleaseManifest = {releaseId: 'v0.8.1',- externalRestApiVersion: '0.1.82',+ externalRestApiVersion: '0.1.83',rpcProxyVersion: '0.1.82',desktopVersion: '0.8.1',minimumDesktopVersion: '0.1.252',diff --git a/external-rest-api/src/routes/__tests__/oauthGrants.contract.test.ts b/external-rest-api/src/routes/__tests__/oauthGrants.contract.test.tsnew file mode 100644index 000000000..33d2aadd4--- /dev/null+++ b/external-rest-api/src/routes/__tests__/oauthGrants.contract.test.ts@@ -0,0 +1,102 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'+import express from 'express'+import request from 'supertest'++// Contract test for the PUBLIC wire shape of GET /api/v1/oauth/grants (spec 04+// U2). This anchors the EXACT key set the browser receives: the route projects+// through an explicit allowlist, so a new field added upstream by control-api+// must not silently leak here. If control-api's contract genuinely grows a+// field, this test is the deliberate gate that must be updated with it.+//+// T1 note: the real producer of this shape is control-api's+// `listUserOAuthGrants` → `/external/oauth/grants`, which is not stood up inside+// external-rest-api's unit env. The canonical key set below is therefore derived+// from control-api's `UserGrantSummary`/`GrantView` (owner-generalised in spec 04+// U1), and the fixture deliberately includes an EXTRA `accessToken`-like key to+// prove the allowlist strips anything the canonical set does not name.++// Auth is not the subject here — inject a passthrough so the route runs.+vi.mock('../../middleware/auth.js', () => ({+ requireAuth: (_req: express.Request, _res: express.Response, next: express.NextFunction) =>+ next(),+ extractAuthToken: () => 'SESSION_JWT',+}))++const serviceMock = vi.hoisted(() => ({+ listOauthGrants: vi.fn(),+ revokeOauthGrant: vi.fn(),+}))+vi.mock('../../services/oauthGrantsService.js', () => serviceMock)++const GRANT_VIEW_KEYS = [+ 'ownerKind',+ 'recipeNamespace',+ 'recipeName',+ 'oauthClientId',+ 'provider',+ 'background',+ 'updatedAt',+ 'mcpServerName',+].sort()++async function makeApp() {+ const { createOauthGrantsRouter } = await import('../oauthGrants.js')+ const app = express()+ app.use(express.json())+ app.use(createOauthGrantsRouter())+ return app+}++describe('GET /oauth/grants — public wire contract (allowlist)', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ })++ it('projects an mcpserver grant to EXACTLY the GrantView keys, dropping unknown fields', async () => {+ serviceMock.listOauthGrants.mockResolvedValue({+ grants: [+ {+ ownerKind: 'mcpserver',+ recipeNamespace: 'mcp-servers',+ recipeName: 'gdrive',+ oauthClientId: 'self://url',+ provider: 'remote',+ background: false,+ updatedAt: '2026-09-01T00:00:00.000Z',+ mcpServerName: 'gdrive',+ // Anything not on the allowlist must NOT reach the browser.+ accessToken: 'SECRET-SHOULD-NOT-LEAK',+ refreshToken: 'SECRET-SHOULD-NOT-LEAK',+ },+ ],+ })+ const res = await request(await makeApp()).get('/oauth/grants')+ expect(res.status).toBe(200)+ expect(res.body.grants).toHaveLength(1)+ expect(Object.keys(res.body.grants[0]).sort()).toEqual(GRANT_VIEW_KEYS)+ expect(res.body.grants[0].mcpServerName).toBe('gdrive')+ })++ it('omits mcpServerName for a recipe grant (7 keys) and drops unknown fields', async () => {+ serviceMock.listOauthGrants.mockResolvedValue({+ grants: [+ {+ ownerKind: 'recipe',+ recipeNamespace: 'sandbox-recipes',+ recipeName: 'leadforge',+ oauthClientId: 'google-gmail',+ provider: 'google',+ background: true,+ updatedAt: '2026-09-01T00:00:00.000Z',+ leakedInternalId: 'nope',+ },+ ],+ })+ const res = await request(await makeApp()).get('/oauth/grants')+ expect(res.status).toBe(200)+ const keys = Object.keys(res.body.grants[0]).sort()+ expect(keys).toEqual(GRANT_VIEW_KEYS.filter(k => k !== 'mcpServerName'))+ expect(res.body.grants[0]).not.toHaveProperty('mcpServerName')+ expect(res.body.grants[0]).not.toHaveProperty('leakedInternalId')+ })+})diff --git a/external-rest-api/src/routes/__tests__/oauthGrants.test.ts b/external-rest-api/src/routes/__tests__/oauthGrants.test.tsindex c8b1867ab..b0f8e5295 100644--- a/external-rest-api/src/routes/__tests__/oauthGrants.test.ts+++ b/external-rest-api/src/routes/__tests__/oauthGrants.test.ts@@ -1,4 +1,4 @@-import { describe, it, expect, vi } from 'vitest'+import { describe, expect, it, vi } from 'vitest'import * as client from '../../controlApiClient.js'describe('oauth grants proxy', () => {@@ -6,7 +6,9 @@ describe('oauth grants proxy', () => {const spy = vi.spyOn(client, 'controlApiRequest').mockResolvedValue({ grants: [] } as never)const { listOauthGrants } = await import('../../services/oauthGrantsService.js')await listOauthGrants('SESSION_JWT')- expect(spy).toHaveBeenCalledWith('GET', '/external/oauth/grants', { userSessionToken: 'SESSION_JWT' })+ expect(spy).toHaveBeenCalledWith('GET', '/external/oauth/grants', {+ userSessionToken: 'SESSION_JWT',+ })spy.mockRestore()})@@ -17,7 +19,19 @@ describe('oauth grants proxy', () => {expect(spy).toHaveBeenCalledWith('DELETE',`/external/oauth/grants/${encodeURIComponent('my namespace')}/${encodeURIComponent('my recipe')}/${encodeURIComponent('client/id')}`,- { userSessionToken: 'SESSION_JWT' }+ { userSessionToken: 'SESSION_JWT', query: undefined }+ )+ spy.mockRestore()+ })++ it('DELETE propagates ownerKind as a query param when supplied', async () => {+ const spy = vi.spyOn(client, 'controlApiRequestWithStatus').mockResolvedValue(null as never)+ const { revokeOauthGrant } = await import('../../services/oauthGrantsService.js')+ await revokeOauthGrant('SESSION_JWT', 'mcp-servers', 'gdrive', 'self://url', 'mcpserver')+ expect(spy).toHaveBeenCalledWith(+ 'DELETE',+ `/external/oauth/grants/${encodeURIComponent('mcp-servers')}/${encodeURIComponent('gdrive')}/${encodeURIComponent('self://url')}`,+ { userSessionToken: 'SESSION_JWT', query: { ownerKind: 'mcpserver' } })spy.mockRestore()})diff --git a/external-rest-api/src/routes/oauthGrants.ts b/external-rest-api/src/routes/oauthGrants.tsindex a989ccec9..bed64c9b4 100644--- a/external-rest-api/src/routes/oauthGrants.ts+++ b/external-rest-api/src/routes/oauthGrants.ts@@ -2,10 +2,34 @@ import type { NextFunction, Response } from 'express'import { Router } from 'express'import { ControlApiError } from '../controlApiClient.js'import { type AuthedRequest, extractAuthToken, requireAuth } from '../middleware/auth.js'-import { listOauthGrants, revokeOauthGrant } from '../services/oauthGrantsService.js'+import {+ type OauthGrantSummary,+ listOauthGrants,+ revokeOauthGrant,+} from '../services/oauthGrantsService.js'const PROPAGATED_STATUSES = new Set([400, 401, 403, 404, 409, 422])+/**+ * Project a control-api grant onto the exact public wire shape (spec 04 U2).+ * This is an explicit allowlist — NOT a blind spread — so a new field added to+ * control-api's response can never silently become public API here. The key set+ * is anchored by a contract test (`__tests__/oauthGrants.contract.test.ts`).+ */+function toGrantView(g: OauthGrantSummary): OauthGrantSummary {+ const view: OauthGrantSummary = {+ ownerKind: g.ownerKind,+ recipeNamespace: g.recipeNamespace,+ recipeName: g.recipeName,+ oauthClientId: g.oauthClientId,+ provider: g.provider,+ background: g.background,+ updatedAt: g.updatedAt,+ }+ if (g.mcpServerName !== undefined) view.mcpServerName = g.mcpServerName+ return view+}+function forwardControlApiError(error: unknown, res: Response, next: NextFunction): void {if (error instanceof ControlApiError && PROPAGATED_STATUSES.has(error.status)) {const body =@@ -21,7 +45,8 @@ export function createOauthGrantsRouter(): Router {router.get('/oauth/grants', requireAuth, async (req: AuthedRequest, res, next) => {try {- res.json(await listOauthGrants(extractAuthToken(req)))+ const { grants } = await listOauthGrants(extractAuthToken(req))+ res.json({ grants: grants.map(toGrantView) })} catch (err) {forwardControlApiError(err, res, next)}@@ -32,11 +57,14 @@ export function createOauthGrantsRouter(): Router {requireAuth,async (req: AuthedRequest, res, next) => {try {+ const ownerKind =+ req.query.ownerKind === undefined ? undefined : String(req.query.ownerKind)await revokeOauthGrant(extractAuthToken(req),String(req.params.recipeNamespace),String(req.params.recipeName),- String(req.params.oauthClientId)+ String(req.params.oauthClientId),+ ownerKind)res.status(204).send()} catch (err) {diff --git a/external-rest-api/src/services/oauthGrantsService.ts b/external-rest-api/src/services/oauthGrantsService.tsindex c776ac139..e90607645 100644--- a/external-rest-api/src/services/oauthGrantsService.ts+++ b/external-rest-api/src/services/oauthGrantsService.ts@@ -1,15 +1,19 @@import { controlApiRequest, controlApiRequestWithStatus } from '../controlApiClient.js'export interface OauthGrantSummary {+ ownerKind: 'recipe' | 'mcpserver'recipeNamespace: stringrecipeName: stringoauthClientId: stringprovider: stringbackground: booleanupdatedAt: string+ mcpServerName?: string}-export async function listOauthGrants(sessionToken: string): Promise<{ grants: OauthGrantSummary[] }> {+export async function listOauthGrants(+ sessionToken: string+): Promise<{ grants: OauthGrantSummary[] }> {return controlApiRequest('GET', '/external/oauth/grants', { userSessionToken: sessionToken })}@@ -17,12 +21,15 @@ export async function revokeOauthGrant(sessionToken: string,recipeNamespace: string,recipeName: string,- oauthClientId: string+ oauthClientId: string,+ ownerKind?: string): Promise<void> {const enc = encodeURIComponentawait controlApiRequestWithStatus<null>('DELETE',`/external/oauth/grants/${enc(recipeNamespace)}/${enc(recipeName)}/${enc(oauthClientId)}`,- { userSessionToken: sessionToken }+ // ownerKind is propagated verbatim; control-api validates it (400 on an+ // invalid value) and forces the owner namespace server-side.+ { userSessionToken: sessionToken, query: ownerKind ? { ownerKind } : undefined })}