Skip to content

Commit 1bb219a

Browse files
authored
Add MCP dashboard consent and revocation (#34)
## Summary - add a dedicated Orbit dashboard consent surface for OAuth MCP connections - capture signed authorization tickets from the URL fragment, remove them from the address bar immediately and keep them only in session storage during login - show the requesting OAuth client, fixed `feed:read` scope and active agents the current account may manage - create a one-time delegation and return it to the fixed Remote MCP callback - list existing MCP connections in the dashboard and allow immediate revocation - reject authorization and later private use when an agent is suspended, retired or not fully onboarded - include active manageable agents in ticket inspection without broadening the general `/v1/me` contract - apply pending production D1 migrations before deployment and require both MCP production secrets in the verified deploy workflow ## Security boundary - no agent API credential enters the browser, callback, grant row or MCP Worker - the browser cannot change OAuth client identity or scope; both are signed in the short-lived ticket - ticket fragments are removed before network navigation and never written to local storage - grant creation remains CSRF-protected and server-authorized - private use revalidates account authority, grant status and agent availability on every call - users can revoke their own active MCP grants from the dashboard - the production deploy fails closed when MCP secrets are absent ## Verification - `npm run check` — 0 diagnostics - `npm run test:d1` — 122/122 passed - `npm run build` — complete D1, content, client, site and browser regression passed - site integrity — 1,879 assertions - Chromium regression — 401 assertions, including anonymous login and owner consent callback flows - Wrangler D1 CI behavior and deploy secret preservation verified against current Cloudflare documentation
1 parent f0688f3 commit 1bb219a

7 files changed

Lines changed: 474 additions & 10 deletions

File tree

‎.github/workflows/deploy-production.yml‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -252,20 +252,33 @@ jobs:
252252
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
253253
ORBIT_LIVE_OAUTH_CLIENT_ID: ${{ secrets.ORBIT_LIVE_OAUTH_CLIENT_ID }}
254254
ORBIT_LIVE_OAUTH_CLIENT_SECRET: ${{ secrets.ORBIT_LIVE_OAUTH_CLIENT_SECRET }}
255+
ORBIT_MCP_SERVICE_SECRET_V1: ${{ secrets.ORBIT_MCP_SERVICE_SECRET_V1 }}
256+
ORBIT_MCP_DELEGATION_PEPPER_V1: ${{ secrets.ORBIT_MCP_DELEGATION_PEPPER_V1 }}
255257
run: |
256258
if [[ -z "$ORBIT_LIVE_OAUTH_CLIENT_ID" || -z "$ORBIT_LIVE_OAUTH_CLIENT_SECRET" ]]; then
257259
echo 'Live GitHub OAuth deployment secrets are missing.' >&2
258260
exit 1
259261
fi
262+
if [[ -z "$ORBIT_MCP_SERVICE_SECRET_V1" || -z "$ORBIT_MCP_DELEGATION_PEPPER_V1" ]]; then
263+
echo 'Orbit MCP production secrets are missing.' >&2
264+
exit 1
265+
fi
260266
261267
oauth_secrets_file="$(mktemp)"
262268
trap 'rm -f "$oauth_secrets_file"' EXIT
263269
chmod 600 "$oauth_secrets_file"
264270
jq -n '{
265271
GITHUB_OAUTH_CLIENT_ID: env.ORBIT_LIVE_OAUTH_CLIENT_ID,
266-
GITHUB_OAUTH_CLIENT_SECRET: env.ORBIT_LIVE_OAUTH_CLIENT_SECRET
272+
GITHUB_OAUTH_CLIENT_SECRET: env.ORBIT_LIVE_OAUTH_CLIENT_SECRET,
273+
ORBIT_MCP_SERVICE_SECRET_V1: env.ORBIT_MCP_SERVICE_SECRET_V1,
274+
ORBIT_MCP_DELEGATION_PEPPER_V1: env.ORBIT_MCP_DELEGATION_PEPPER_V1
267275
}' > "$oauth_secrets_file"
268276
unset ORBIT_LIVE_OAUTH_CLIENT_ID ORBIT_LIVE_OAUTH_CLIENT_SECRET
277+
unset ORBIT_MCP_SERVICE_SECRET_V1 ORBIT_MCP_DELEGATION_PEPPER_V1
278+
279+
npx wrangler d1 migrations apply DB \
280+
--remote \
281+
--config wrangler.production.live.jsonc
269282
270283
short_sha="${GITHUB_SHA::12}"
271284
npx wrangler deploy \

‎scripts/orbit-browser-tests.mjs‎

Lines changed: 153 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,19 @@ const seleneEditorialCount = searchIndex.items.filter((item) => (
119119
normalizeSearchText(item.searchText).includes('selene') && item.topics.includes('editoryal')
120120
)).length;
121121
const agentTopicRecordCount = searchIndex.items.filter((item) => item.entity === 'record' && item.topics.includes('ajanlar')).length;
122+
const browserMcpTicket = 'orb_mcp_auth_v1.browser-payload.browser-signature';
123+
const browserMcpAuthorizationRequestId = '550e8400-e29b-41d4-a716-446655440000';
124+
const browserMcpDelegationCode = 'orb_mcp_v1_browser_selector_browser_secret';
125+
const browserMcpAuthorizationBodies = [];
126+
127+
const readRequestJson = (request) => new Promise((resolve, reject) => {
128+
let value = '';
129+
request.on('data', (chunk) => { value += chunk; });
130+
request.on('end', () => {
131+
try { resolve(value ? JSON.parse(value) : {}); } catch (error) { reject(error); }
132+
});
133+
request.on('error', reject);
134+
});
122135

123136
if (errors.length === 0) {
124137
const server = http.createServer((request, response) => {
@@ -167,10 +180,70 @@ if (errors.length === 0) {
167180
'content-type': 'application/json; charset=utf-8',
168181
});
169182
response.end(JSON.stringify(owner
170-
? { account: { roles: ['platform_owner'] } }
183+
? {
184+
account: {
185+
roles: ['platform_owner'],
186+
agentQuota: -1,
187+
displayName: 'Orbit Owner',
188+
handle: 'orbit-owner',
189+
avatarUrl: null,
190+
},
191+
sponsoredAgents: browserAgents,
192+
}
171193
: { error: { code: 'authentication_required', message: 'A valid session is required.' } }));
172194
return;
173195
}
196+
if (request.method === 'POST' && pathname === '/v1/mcp/authorization-tickets/inspect') {
197+
readRequestJson(request).then((body) => {
198+
const valid = request.headers.cookie?.includes('orbit-owner-test=1')
199+
&& body.ticket === browserMcpTicket;
200+
response.writeHead(valid ? 200 : 401, {
201+
'cache-control': 'no-store',
202+
'content-type': 'application/json; charset=utf-8',
203+
});
204+
response.end(JSON.stringify(valid ? {
205+
authorizationRequest: {
206+
id: browserMcpAuthorizationRequestId,
207+
oauthClient: { id: 'chatgpt-browser-client', label: 'ChatGPT' },
208+
scopes: ['feed:read'],
209+
issuedAt: Date.now(),
210+
expiresAt: Date.now() + 10 * 60 * 1000,
211+
},
212+
manageableAgents: browserAgents.map((agent) => ({
213+
...agent,
214+
displayName: agent.handle[0].toUpperCase() + agent.handle.slice(1),
215+
publicationMode: 'direct_publish',
216+
status: 'active',
217+
onboardingState: 'active',
218+
})),
219+
} : { error: { code: 'authentication_required', message: 'A valid session is required.' } }));
220+
}).catch(() => {
221+
response.writeHead(400, { 'content-type': 'application/json; charset=utf-8' });
222+
response.end(JSON.stringify({ error: { code: 'invalid_json', message: 'Invalid JSON.' } }));
223+
});
224+
return;
225+
}
226+
if (request.method === 'POST' && pathname === '/v1/mcp/authorizations') {
227+
readRequestJson(request).then((body) => {
228+
browserMcpAuthorizationBodies.push(body);
229+
response.writeHead(201, {
230+
'cache-control': 'no-store',
231+
'content-type': 'application/json; charset=utf-8',
232+
});
233+
response.end(JSON.stringify({
234+
authorization: { id: 'grant-browser', status: 'active' },
235+
delegation: {
236+
code: browserMcpDelegationCode,
237+
authorizationRequestId: browserMcpAuthorizationRequestId,
238+
expiresAt: Date.now() + 5 * 60 * 1000,
239+
},
240+
}));
241+
}).catch(() => {
242+
response.writeHead(400, { 'content-type': 'application/json; charset=utf-8' });
243+
response.end(JSON.stringify({ error: { code: 'invalid_json', message: 'Invalid JSON.' } }));
244+
});
245+
return;
246+
}
174247
if (request.method === 'POST' && /^\/v1\/manage\/records\/[^/]+\/delete$/u.test(pathname)) {
175248
response.writeHead(200, { 'cache-control': 'no-store', 'content-type': 'application/json; charset=utf-8' });
176249
response.end(JSON.stringify({
@@ -569,6 +642,85 @@ if (errors.length === 0) {
569642
await context.close();
570643
}));
571644

645+
{
646+
const context = await browser.newContext({ viewport: { width: 390, height: 844 }, colorScheme: 'light' });
647+
const page = await context.newPage();
648+
const pageErrors = [];
649+
page.on('pageerror', (error) => pageErrors.push(error.message));
650+
await page.goto(
651+
`${baseUrl}/dashboard#mcp_authorization=${encodeURIComponent(browserMcpTicket)}`,
652+
{ waitUntil: 'load' },
653+
);
654+
await page.waitForSelector('#login:not(.hidden)');
655+
const anonymousConsent = await page.evaluate((storageKey) => ({
656+
hash: location.hash,
657+
ticket: sessionStorage.getItem(storageKey),
658+
title: document.querySelector('#login-title')?.textContent?.trim(),
659+
consentVisible: !document.querySelector('#mcp-consent')?.classList.contains('hidden'),
660+
}), 'orbit_mcp_authorization_ticket_v1');
661+
check(anonymousConsent.hash === '', 'MCP anonim girişinde ticket URL fragmentından temizlenmedi.');
662+
check(anonymousConsent.ticket === browserMcpTicket, 'MCP anonim girişinde ticket sekme oturumunda korunmadı.');
663+
check(anonymousConsent.title === 'Bağlantıyı onaylamak için giriş yap.', 'MCP anonim giriş açıklaması gösterilmedi.');
664+
check(anonymousConsent.consentVisible === false, 'MCP consent oturum açılmadan görünür oldu.');
665+
check(pageErrors.length === 0, `MCP anonim girişinde sayfa hatası: ${pageErrors.join(' | ')}`);
666+
await context.close();
667+
}
668+
669+
{
670+
const context = await browser.newContext({ viewport: { width: 1440, height: 900 }, colorScheme: 'light' });
671+
await context.addCookies([{
672+
name: 'orbit-owner-test',
673+
value: '1',
674+
url: baseUrl,
675+
}]);
676+
await context.route('https://mcp.orbit.sametbasbug.dev/**', async (route) => {
677+
await route.fulfill({
678+
status: 200,
679+
contentType: 'text/html; charset=utf-8',
680+
body: '<!doctype html><title>Orbit MCP callback</title>',
681+
});
682+
});
683+
const page = await context.newPage();
684+
const pageErrors = [];
685+
page.on('pageerror', (error) => pageErrors.push(error.message));
686+
await page.goto(
687+
`${baseUrl}/dashboard#mcp_authorization=${encodeURIComponent(browserMcpTicket)}`,
688+
{ waitUntil: 'load' },
689+
);
690+
await page.waitForSelector('#mcp-consent:not(.hidden)');
691+
const consentState = await page.evaluate(() => ({
692+
hash: location.hash,
693+
client: document.querySelector('#mcp-client-summary')?.textContent?.trim(),
694+
scope: document.querySelector('#mcp-scope-summary')?.textContent?.trim(),
695+
options: [...document.querySelectorAll('#mcp-agent-select option')].map((option) => ({
696+
value: option.value,
697+
label: option.textContent?.trim(),
698+
})),
699+
approveDisabled: document.querySelector('#mcp-approve')?.disabled,
700+
}));
701+
check(consentState.hash === '', 'MCP owner consentinde ticket URL fragmentından temizlenmedi.');
702+
check(consentState.client?.includes('ChatGPT'), 'MCP consent istemci adını göstermiyor.');
703+
check(consentState.scope?.includes('feed:read'), 'MCP consent least-privilege kapsamını göstermiyor.');
704+
check(consentState.options.length === browserAgents.length, 'MCP consent yönetilebilir ajan listesini eksik gösteriyor.');
705+
check(consentState.options.some((option) => option.value === 'agent-selene'), 'MCP consent Selene seçimini sunmuyor.');
706+
check(consentState.approveDisabled === false, 'MCP consent onay düğmesi kullanılabilir değil.');
707+
708+
await page.locator('#mcp-agent-select').selectOption('agent-selene');
709+
await page.locator('#mcp-approve').click();
710+
await page.waitForURL((url) => (
711+
url.origin === 'https://mcp.orbit.sametbasbug.dev'
712+
&& url.pathname === '/oauth/orbit/callback'
713+
));
714+
const callback = new URL(page.url());
715+
check(callback.searchParams.get('code') === browserMcpDelegationCode, 'MCP consent callback tek kullanımlık kodu taşımıyor.');
716+
check(callback.searchParams.get('authorization_request_id') === browserMcpAuthorizationRequestId, 'MCP consent callback istek kimliğini taşımıyor.');
717+
check(browserMcpAuthorizationBodies.length === 1, 'MCP consent grant isteğini tam bir kez göndermedi.');
718+
check(browserMcpAuthorizationBodies[0]?.agentId === 'agent-selene', 'MCP consent seçilen ajanı grant isteğine bağlamadı.');
719+
check(browserMcpAuthorizationBodies[0]?.ticket === browserMcpTicket, 'MCP consent imzalı ticketı grant isteğine taşımadı.');
720+
check(pageErrors.length === 0, `MCP owner consentinde sayfa hatası: ${pageErrors.join(' | ')}`);
721+
await context.close();
722+
}
723+
572724
for (const viewport of [{ width: 390, height: 844 }, { width: 1440, height: 900 }]) {
573725
const label = `${viewport.width}x${viewport.height} owner`;
574726
const context = await browser.newContext({ viewport, colorScheme: 'light' });

‎scripts/orbit-site-tests.mjs‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,13 +152,31 @@ if (fs.existsSync(dashboardFile)) {
152152
check(dashboardHtml.includes('public profilinde “İnsanı” olarak görünür'), 'Dashboard GitHub insan bağlantısının public olacağını açıklamıyor.');
153153
check(dashboardHtml.includes('Yayın incelemeleri'), 'Dashboard moderator yayın kuyruğunu taşımıyor.');
154154
check(dashboardHtml.includes('Metin değiştirilemez'), 'Dashboard moderatorün içeriği düzenleyemeyeceğini açıklamıyor.');
155+
check(dashboardHtml.includes('Bağlantıyı onayla'), 'Dashboard MCP yetkilendirme ekranını taşımıyor.');
156+
check(dashboardHtml.includes('id="mcp-agent-select"'), 'Dashboard MCP ajan seçimini taşımıyor.');
157+
check(dashboardHtml.includes('uzun ömürlü API anahtarı'), 'Dashboard MCP credential güvenlik sınırını açıklamıyor.');
158+
check(dashboardHtml.includes('Bağlı uygulamalar'), 'Dashboard MCP grant yönetim kartını taşımıyor.');
159+
check(dashboardHtml.includes('id="mcp-authorizations"'), 'Dashboard MCP grant listesini taşımıyor.');
155160
check(!dashboardHtml.includes('orb_agent_v1_'), 'Dashboard build çıktısı ajan credential kalıbı içeriyor.');
156161
}
157162
const dashboardScript = fs.readFileSync(path.join(ROOT, 'src', 'scripts', 'dashboard.js'), 'utf8');
158163
check(dashboardScript.includes("roles.includes('moderator')"), 'Dashboard moderator rolünü yayın incelemesine bağlamıyor.');
159164
check(dashboardScript.includes("loadApprovals()"), 'Dashboard moderator yayın kuyruğunu yüklemiyor.');
160165
check(dashboardScript.includes("review-approve').addEventListener"), 'Dashboard yayın onay düğmesini bağlamıyor.');
161166
check(dashboardScript.includes("review-reject').addEventListener"), 'Dashboard yayın ret düğmesini bağlamıyor.');
167+
check(dashboardScript.includes("history.replaceState"), 'Dashboard MCP ticket fragmentını adres çubuğundan temizlemiyor.');
168+
check(dashboardScript.includes("sessionStorage.setItem(MCP_TICKET_STORAGE_KEY"), 'Dashboard MCP ticketını yalnız sekme oturumunda korumuyor.');
169+
check(!dashboardScript.includes("localStorage.setItem(MCP_TICKET_STORAGE_KEY"), 'Dashboard MCP ticketını kalıcı depolamaya yazıyor.');
170+
check(dashboardScript.includes("/v1/mcp/authorization-tickets/inspect"), 'Dashboard imzalı MCP ticketını doğrulamıyor.');
171+
check(dashboardScript.includes("/v1/mcp/authorizations"), 'Dashboard MCP grant oluşturma ucuna bağlanmıyor.');
172+
check(
173+
/^const MCP_CALLBACK_URL = 'https:\/\/mcp\.orbit\.sametbasbug\.dev\/oauth\/orbit\/callback';$/mu.test(dashboardScript),
174+
'Dashboard sabit MCP callback hedefine bağlı değil.',
175+
);
176+
check(dashboardScript.includes("mcp-approve').addEventListener"), 'Dashboard MCP onay düğmesini bağlamıyor.');
177+
check(dashboardScript.includes("mcp-deny').addEventListener"), 'Dashboard MCP ret düğmesini bağlamıyor.');
178+
check(dashboardScript.includes("loadMcpAuthorizations()"), 'Dashboard MCP grant listesini yüklemiyor.');
179+
check(dashboardScript.includes("/v1/mcp/authorizations/${encodeURIComponent(authorization.id)}/revoke"), 'Dashboard MCP grant iptal ucuna bağlanmıyor.');
162180
check(!fs.existsSync(path.join(DIST_DIR, 'projects', 'index.html')), 'Kaldırılan Projeler rotası build çıktısında kaldı.');
163181
check(fs.existsSync(path.join(DIST_DIR, 'topics', 'index.html')), 'Konular rotası build çıktısında yok.');
164182
for (const topic of ['orbit', 'ajanlar', 'editoryal', 'sistemler']) {

‎scripts/orbit-slice1-tests.ts‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -531,10 +531,23 @@ let firstCredentialToken = '';
531531
assert.equal(inspected.status, 200, await inspected.clone().text());
532532
const inspectedBody = await inspected.json() as {
533533
authorizationRequest: { id: string; oauthClient: { label: string }; scopes: string[] };
534+
manageableAgents: Array<{
535+
id: string;
536+
handle: string;
537+
status: string;
538+
onboardingState: string;
539+
}>;
534540
};
535541
assert.equal(inspectedBody.authorizationRequest.id, mcpAuthorizationRequestId);
536542
assert.equal(inspectedBody.authorizationRequest.oauthClient.label, 'ChatGPT');
537543
assert.deepEqual(inspectedBody.authorizationRequest.scopes, ['feed:read']);
544+
assert.deepEqual(
545+
inspectedBody.manageableAgents.map((agent) => agent.id),
546+
[sponsoredAgentId],
547+
);
548+
assert.equal(inspectedBody.manageableAgents[0]?.handle, 'selene-test-agent');
549+
assert.equal(inspectedBody.manageableAgents[0]?.status, 'active');
550+
assert.equal(inspectedBody.manageableAgents[0]?.onboardingState, 'active');
538551

539552
const tamperedTicket = `${ticketBody.ticket.slice(0, -1)}${ticketBody.ticket.endsWith('A') ? 'B' : 'A'}`;
540553
const tamperedInspect = await postJson(
@@ -701,6 +714,22 @@ let firstCredentialToken = '';
701714
assert.equal(privateStateBody.recordCounts.total, 0);
702715
assert.equal(privateStateBody.recordCounts.pendingReview, 0);
703716

717+
await postJson('/__test/set-agent-status', {
718+
handle: 'selene-test-agent',
719+
status: 'suspended',
720+
}, {}, NOW + 56);
721+
const stateWhileSuspended = await postJson(
722+
`/v1/mcp/grants/${encodeURIComponent(mcpGrantId)}/agent/state`,
723+
{},
724+
{ authorization: `Bearer ${MCP_SERVICE_SECRET}` },
725+
NOW + 56,
726+
);
727+
assert.equal(stateWhileSuspended.status, 401);
728+
await postJson('/__test/set-agent-status', {
729+
handle: 'selene-test-agent',
730+
status: 'active',
731+
}, {}, NOW + 56);
732+
704733
const revokeNoCsrf = await postJson(
705734
`/v1/mcp/authorizations/${encodeURIComponent(mcpGrantId)}/revoke`,
706735
{},

0 commit comments

Comments
 (0)