Skip to content

Commit 9862e06

Browse files
authored
Add MCP avatar upload sessions (#47)
## Summary - add short-lived MCP avatar upload sessions bound to the live grant, exact human account, and target agent - keep avatar bytes out of MCP JSON/model context and route the browser directly to Orbit - reuse the existing avatar quarantine, digest, MIME, Images normalization, quota, R2, D1, and media-idempotency pipeline - add a noindex Orbit upload page with browser-side SHA-256, size/type validation, CSRF, and direct raw upload - make the upload URL a selector rather than a bearer credential: unauthenticated and wrong-account access is rejected, and revocation/expiry/authority are revalidated on every request - exclude the private upload handoff page from sitemap output - remove the nonessential blob-image preview after CodeQL flagged that DOM flow; the final CodeQL gate is clean ## Safety and replay - session TTL: 15 minutes - PNG/JPEG/WebP only, max 5 MiB - same session + same bytes safely replays the normalized result - same session + different bytes conflicts - bad digest, wrong MIME, oversized payload, expired session, wrong human account, and revoked grant fail closed ## Validation - `npm run check`: 0 errors / 0 warnings / 2 pre-existing hints - Slice 5: 28/28 tests passed, including the full new MCP avatar transport chain - production-live Worker dry-run passed - production Astro build emits `/mcp/avatar-upload/` - sitemap exclusion verified directly - CodeQL / Analyze / foundation / verify all pass - `git diff --check` clean
1 parent aaf14f3 commit 9862e06

11 files changed

Lines changed: 864 additions & 2 deletions

‎astro.config.mjs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,5 +6,5 @@ export default defineConfig({
66
devToolbar: {
77
enabled: false,
88
},
9-
integrations: [sitemap({ filter: (page) => !page.includes('/orbit-runtime/') && !page.includes('/projects') })],
9+
integrations: [sitemap({ filter: (page) => !page.includes('/orbit-runtime/') && !page.includes('/projects') && !page.includes('/mcp/avatar-upload') })],
1010
});

‎astro.worker.config.mjs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,5 +25,5 @@ export default defineConfig({
2525
devToolbar: {
2626
enabled: false,
2727
},
28-
integrations: [sitemap({ filter: (page) => !page.includes('/orbit-runtime/') && !page.includes('/projects') })],
28+
integrations: [sitemap({ filter: (page) => !page.includes('/orbit-runtime/') && !page.includes('/projects') && !page.includes('/mcp/avatar-upload') })],
2929
});
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
CREATE TABLE mcp_avatar_upload_sessions (
2+
id TEXT PRIMARY KEY,
3+
grant_id TEXT NOT NULL REFERENCES mcp_authorization_grants(id),
4+
account_id TEXT NOT NULL REFERENCES accounts(id),
5+
agent_id TEXT NOT NULL REFERENCES agents(id),
6+
key_digest TEXT NOT NULL,
7+
created_at INTEGER NOT NULL,
8+
expires_at INTEGER NOT NULL CHECK (expires_at > created_at),
9+
completed_at INTEGER,
10+
UNIQUE (grant_id, key_digest)
11+
);
12+
13+
CREATE INDEX mcp_avatar_upload_sessions_expiry_idx
14+
ON mcp_avatar_upload_sessions (expires_at);
15+
16+
CREATE TRIGGER mcp_avatar_upload_sessions_identity_validate
17+
BEFORE INSERT ON mcp_avatar_upload_sessions
18+
BEGIN
19+
SELECT RAISE(ABORT, 'mcp_avatar_upload_session_identity_mismatch')
20+
WHERE NOT EXISTS (
21+
SELECT 1
22+
FROM mcp_authorization_grants grant_row
23+
WHERE grant_row.id = NEW.grant_id
24+
AND grant_row.account_id = NEW.account_id
25+
AND grant_row.agent_id = NEW.agent_id
26+
AND grant_row.revoked_at IS NULL
27+
AND (grant_row.expires_at IS NULL OR grant_row.expires_at > NEW.created_at)
28+
);
29+
END;
30+
31+
CREATE TRIGGER mcp_avatar_upload_sessions_completed_once
32+
BEFORE UPDATE OF completed_at ON mcp_avatar_upload_sessions
33+
WHEN OLD.completed_at IS NOT NULL AND NEW.completed_at <> OLD.completed_at
34+
BEGIN
35+
SELECT RAISE(ABORT, 'mcp_avatar_upload_session_already_completed');
36+
END;
37+
38+
CREATE TRIGGER mcp_avatar_upload_sessions_identity_immutable
39+
BEFORE UPDATE OF grant_id, account_id, agent_id, key_digest, created_at, expires_at ON mcp_avatar_upload_sessions
40+
BEGIN
41+
SELECT RAISE(ABORT, 'mcp_avatar_upload_session_identity_immutable');
42+
END;

‎scripts/orbit-slice1-test-worker.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -394,6 +394,42 @@ async function testRoute(request: Request, env: TestEnv): Promise<Response | nul
394394
return Response.json({ ok: true });
395395
}
396396

397+
if (url.pathname === '/__test/seed-mcp-grant') {
398+
await env.DB.prepare(`
399+
INSERT INTO mcp_authorization_grants (
400+
id, account_id, agent_id, scopes, oauth_client_id,
401+
oauth_client_label, created_at, expires_at
402+
) VALUES (?, ?, ?, ?, 'test-chatgpt-client', 'ChatGPT test client', ?, NULL)
403+
`).bind(
404+
String(body.grantId),
405+
String(body.accountId),
406+
String(body.agentId),
407+
String(body.scopes ?? 'feed:read posts:write replies:write messages:read messages:write'),
408+
Number(body.now ?? Date.now()),
409+
).run();
410+
return Response.json({ ok: true });
411+
}
412+
413+
if (url.pathname === '/__test/seed-account') {
414+
await env.DB.prepare(`
415+
INSERT INTO accounts (
416+
id, handle, handle_normalized, display_name, avatar_url,
417+
status, created_at, updated_at, last_login_at,
418+
announcement_emails_enabled, terms_accepted_at, terms_version
419+
) VALUES (?, ?, ?, ?, NULL, 'active', ?, ?, ?, 1, ?, '2026-08-08')
420+
`).bind(
421+
String(body.accountId),
422+
String(body.handle),
423+
String(body.handle).toLowerCase(),
424+
String(body.displayName ?? body.handle),
425+
Number(body.now ?? Date.now()),
426+
Number(body.now ?? Date.now()),
427+
Number(body.now ?? Date.now()),
428+
Number(body.now ?? Date.now()),
429+
).run();
430+
return Response.json({ ok: true });
431+
}
432+
397433
if (url.pathname === '/__test/seed-human-session') {
398434
await env.DB.prepare(`
399435
INSERT INTO sessions (

‎scripts/orbit-slice5-tests.ts‎

Lines changed: 221 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@ const NOW = Date.parse('2026-07-16T10:00:00Z');
2727
const AGENT_PEPPER = 'test-agent-pepper-at-least-32-bytes-long';
2828
const SESSION_PEPPER = 'test-session-pepper-at-least-32-bytes-long';
2929
const CSRF_PEPPER = 'test-csrf-pepper-at-least-32-bytes-long';
30+
const MCP_SERVICE_SECRET = 'test-mcp-service-secret-at-least-32-bytes-long';
31+
const MCP_AVATAR_GRANT_ID = '019f64d2-0a00-7000-8000-000000000001';
3032

3133
let persistDirectory = '';
3234
let baseUrl = '';
@@ -148,6 +150,41 @@ async function ownerImage(pathname: string, bytes: Uint8Array, type = 'image/png
148150
});
149151
}
150152

153+
async function mcpServicePost(pathname: string, body: Record<string, unknown>, now = NOW): Promise<Response> {
154+
return await fetch(`${baseUrl}${pathname}`, {
155+
method: 'POST',
156+
headers: {
157+
authorization: `Bearer ${MCP_SERVICE_SECRET}`,
158+
'content-type': 'application/json',
159+
'x-test-now': String(now),
160+
},
161+
body: JSON.stringify(body),
162+
});
163+
}
164+
165+
async function mcpAvatarSessionImage(
166+
sessionId: string,
167+
bytes: Uint8Array,
168+
type = 'image/png',
169+
now = NOW,
170+
digest = undefined as string | undefined,
171+
declaredLength = bytes.byteLength,
172+
): Promise<Response> {
173+
return await fetch(`${baseUrl}/v1/mcp/avatar-upload-sessions/${encodeURIComponent(sessionId)}/upload`, {
174+
method: 'POST',
175+
headers: {
176+
cookie: ownerCookie,
177+
origin: 'http://localhost:4321',
178+
'x-orbit-csrf': ownerCsrf,
179+
'x-test-now': String(now),
180+
'content-type': type,
181+
'x-orbit-content-sha256': digest ?? await imageDigest(bytes),
182+
'x-orbit-upload-length': String(declaredLength),
183+
},
184+
body: Uint8Array.from(bytes),
185+
});
186+
}
187+
151188
async function seedAgent(
152189
handle: string,
153190
role = '',
@@ -256,6 +293,13 @@ before(async () => {
256293
await seedAgent('slice5-pending', '', 'approval_required');
257294
await seedAgent('slice5-media-concurrent');
258295
await seedAgent('slice5-onboarding', '', 'approval_required', 'pending');
296+
const mcpAvatarAgent = await seedAgent('slice5-mcp-avatar');
297+
assert.equal((await testPost('/__test/seed-mcp-grant', {
298+
grantId: MCP_AVATAR_GRANT_ID,
299+
accountId: OWNER_ID,
300+
agentId: mcpAvatarAgent.id,
301+
now: NOW,
302+
})).status, 200);
259303
});
260304

261305
after(async () => {
@@ -316,6 +360,183 @@ describe('Orbit V6 Slice 5 dashboard and platform core', { concurrency: false },
316360
assert.equal((await fetch(`${baseUrl}/v1/agents/${agent.handle}`)).status, 200);
317361
});
318362

363+
test('MCP avatar upload sessions keep bytes out of tool JSON and preserve media safety', async () => {
364+
const agent = agents.get('slice5-mcp-avatar')!;
365+
const createPath = `/v1/mcp/grants/${encodeURIComponent(MCP_AVATAR_GRANT_ID)}/agent/avatar-upload-session`;
366+
const created = await mcpServicePost(createPath, { idempotencyKey: 'slice5-avatar-session-main' }, NOW + 100);
367+
assert.equal(created.status, 201, await created.clone().text());
368+
const createdText = await created.text();
369+
assert.ok(!createdText.includes(MCP_AVATAR_GRANT_ID));
370+
assert.ok(!createdText.includes(agent.id));
371+
assert.ok(!createdText.includes(OWNER_ID));
372+
const createdBody = JSON.parse(createdText) as {
373+
session: {
374+
uploadUrl: string;
375+
expiresAt: number;
376+
acceptedTypes: string[];
377+
maximumBytes: number;
378+
replayed: boolean;
379+
};
380+
};
381+
assert.equal(createdBody.session.replayed, false);
382+
assert.deepEqual(createdBody.session.acceptedTypes, ['image/png', 'image/jpeg', 'image/webp']);
383+
assert.equal(createdBody.session.maximumBytes, 5 * 1024 * 1024);
384+
const sessionUrl = new URL(createdBody.session.uploadUrl);
385+
assert.equal(sessionUrl.origin, 'http://localhost:4321');
386+
assert.equal(sessionUrl.pathname, '/mcp/avatar-upload/');
387+
const sessionId = sessionUrl.searchParams.get('session');
388+
assert.ok(sessionId);
389+
390+
const replay = await mcpServicePost(createPath, { idempotencyKey: 'slice5-avatar-session-main' }, NOW + 101);
391+
assert.equal(replay.status, 200, await replay.clone().text());
392+
const replayBody = await replay.json() as { session: { uploadUrl: string; replayed: boolean } };
393+
assert.equal(replayBody.session.replayed, true);
394+
assert.equal(replayBody.session.uploadUrl, createdBody.session.uploadUrl);
395+
396+
const unauthenticated = await fetch(`${baseUrl}/v1/mcp/avatar-upload-sessions/${encodeURIComponent(sessionId)}`, {
397+
headers: { 'x-test-now': String(NOW + 102) },
398+
});
399+
assert.equal(unauthenticated.status, 401, await unauthenticated.clone().text());
400+
401+
const strangerAccountId = '019f64d2-0a00-7000-8000-000000000099';
402+
assert.equal((await testPost('/__test/seed-account', {
403+
accountId: strangerAccountId,
404+
handle: 'slice5-stranger',
405+
displayName: 'Slice 5 Stranger',
406+
now: NOW + 102,
407+
})).status, 200);
408+
const strangerSession = await createOpaqueToken('session', SESSION_PEPPER);
409+
const strangerCsrf = randomBase64Url(32);
410+
const strangerCsrfDigest = await hmacDigest(
411+
`orbit:csrf:v1:${strangerSession.selector}:${strangerCsrf}`,
412+
CSRF_PEPPER,
413+
);
414+
assert.equal((await testPost('/__test/seed-human-session', {
415+
sessionId: strangerSession.selector,
416+
secretDigest: strangerSession.digest,
417+
csrfDigest: strangerCsrfDigest,
418+
accountId: strangerAccountId,
419+
now: NOW + 102,
420+
})).status, 200);
421+
const stranger = await fetch(`${baseUrl}/v1/mcp/avatar-upload-sessions/${encodeURIComponent(sessionId)}`, {
422+
headers: {
423+
cookie: `__Host-orbit_session=${strangerSession.token}; __Host-orbit_csrf=${strangerCsrf}`,
424+
'x-test-now': String(NOW + 102),
425+
},
426+
});
427+
assert.equal(stranger.status, 404, await stranger.clone().text());
428+
429+
const pending = await ownerRequest(
430+
`/v1/mcp/avatar-upload-sessions/${encodeURIComponent(sessionId)}`,
431+
'GET',
432+
undefined,
433+
undefined,
434+
NOW + 103,
435+
);
436+
assert.equal(pending.status, 200, await pending.clone().text());
437+
assert.deepEqual(await pending.json(), {
438+
session: {
439+
status: 'pending',
440+
expiresAt: createdBody.session.expiresAt,
441+
acceptedTypes: ['image/png', 'image/jpeg', 'image/webp'],
442+
maximumBytes: 5 * 1024 * 1024,
443+
agent: { handle: 'slice5-mcp-avatar', avatarAsset: 'agents/nyx.webp' },
444+
},
445+
});
446+
447+
const png = new Uint8Array(await sharp({
448+
create: { width: 840, height: 620, channels: 4, background: '#6f63e8' },
449+
}).png().toBuffer());
450+
const uploaded = await mcpAvatarSessionImage(sessionId, png, 'image/png', NOW + 104);
451+
assert.equal(uploaded.status, 201, await uploaded.clone().text());
452+
const uploadedBody = await uploaded.json() as { media: { id: string; width: number; height: number } };
453+
assert.deepEqual([uploadedBody.media.width, uploadedBody.media.height], [512, 512]);
454+
455+
const completed = await ownerRequest(
456+
`/v1/mcp/avatar-upload-sessions/${encodeURIComponent(sessionId)}`,
457+
'GET',
458+
undefined,
459+
undefined,
460+
NOW + 105,
461+
);
462+
assert.equal(completed.status, 200, await completed.clone().text());
463+
const completedBody = await completed.json() as { session: { status: string; agent: { avatarAsset: string } } };
464+
assert.equal(completedBody.session.status, 'completed');
465+
assert.match(completedBody.session.agent.avatarAsset, /^\/v1\/media\//u);
466+
467+
const sameFileReplay = await mcpAvatarSessionImage(sessionId, png, 'image/png', NOW + 106);
468+
assert.equal(sameFileReplay.status, 201, await sameFileReplay.clone().text());
469+
assert.equal(sameFileReplay.headers.get('idempotency-replayed'), 'true');
470+
assert.equal((await sameFileReplay.json() as { media: { id: string } }).media.id, uploadedBody.media.id);
471+
472+
const differentPng = new Uint8Array(await sharp({
473+
create: { width: 840, height: 620, channels: 4, background: '#ff4fd8' },
474+
}).png().toBuffer());
475+
const conflict = await mcpAvatarSessionImage(sessionId, differentPng, 'image/png', NOW + 107);
476+
assert.equal(conflict.status, 409, await conflict.clone().text());
477+
478+
const invalidDigestSession = await mcpServicePost(createPath, { idempotencyKey: 'slice5-avatar-session-bad-digest' }, NOW + 108);
479+
assert.equal(invalidDigestSession.status, 201, await invalidDigestSession.clone().text());
480+
const invalidDigestUrl = new URL((await invalidDigestSession.json() as { session: { uploadUrl: string } }).session.uploadUrl);
481+
const invalidDigestId = invalidDigestUrl.searchParams.get('session');
482+
assert.ok(invalidDigestId);
483+
const invalidDigest = await mcpAvatarSessionImage(
484+
invalidDigestId,
485+
png,
486+
'image/png',
487+
NOW + 109,
488+
randomBase64Url(32),
489+
);
490+
assert.equal(invalidDigest.status, 400, await invalidDigest.clone().text());
491+
492+
const wrongTypeSession = await mcpServicePost(createPath, { idempotencyKey: 'slice5-avatar-session-wrong-type' }, NOW + 110);
493+
assert.equal(wrongTypeSession.status, 201, await wrongTypeSession.clone().text());
494+
const wrongTypeId = new URL((await wrongTypeSession.json() as { session: { uploadUrl: string } }).session.uploadUrl).searchParams.get('session');
495+
assert.ok(wrongTypeId);
496+
assert.equal((await mcpAvatarSessionImage(wrongTypeId, png, 'image/gif', NOW + 111)).status, 415);
497+
498+
const oversizedSession = await mcpServicePost(createPath, { idempotencyKey: 'slice5-avatar-session-oversized' }, NOW + 112);
499+
assert.equal(oversizedSession.status, 201, await oversizedSession.clone().text());
500+
const oversizedId = new URL((await oversizedSession.json() as { session: { uploadUrl: string } }).session.uploadUrl).searchParams.get('session');
501+
assert.ok(oversizedId);
502+
assert.equal((await mcpAvatarSessionImage(oversizedId, png, 'image/png', NOW + 113, undefined, 5 * 1024 * 1024 + 1)).status, 413);
503+
504+
const expiredSession = await mcpServicePost(createPath, { idempotencyKey: 'slice5-avatar-session-expired' }, NOW + 114);
505+
assert.equal(expiredSession.status, 201, await expiredSession.clone().text());
506+
const expiredBody = await expiredSession.json() as { session: { uploadUrl: string; expiresAt: number } };
507+
const expiredId = new URL(expiredBody.session.uploadUrl).searchParams.get('session');
508+
assert.ok(expiredId);
509+
const expired = await ownerRequest(
510+
`/v1/mcp/avatar-upload-sessions/${encodeURIComponent(expiredId)}`,
511+
'GET',
512+
undefined,
513+
undefined,
514+
expiredBody.session.expiresAt + 1,
515+
);
516+
assert.equal(expired.status, 410, await expired.clone().text());
517+
518+
const revokedSession = await mcpServicePost(createPath, { idempotencyKey: 'slice5-avatar-session-revoked' }, NOW + 115);
519+
assert.equal(revokedSession.status, 201, await revokedSession.clone().text());
520+
const revokedId = new URL((await revokedSession.json() as { session: { uploadUrl: string } }).session.uploadUrl).searchParams.get('session');
521+
assert.ok(revokedId);
522+
const revoked = await ownerRequest(
523+
`/v1/mcp/authorizations/${encodeURIComponent(MCP_AVATAR_GRANT_ID)}/revoke`,
524+
'POST',
525+
{},
526+
undefined,
527+
NOW + 116,
528+
);
529+
assert.equal(revoked.status, 200, await revoked.clone().text());
530+
const afterRevoke = await ownerRequest(
531+
`/v1/mcp/avatar-upload-sessions/${encodeURIComponent(revokedId)}`,
532+
'GET',
533+
undefined,
534+
undefined,
535+
NOW + 117,
536+
);
537+
assert.equal(afterRevoke.status, 401, await afterRevoke.clone().text());
538+
});
539+
319540
/* Medyanın tek kapsamı burası. Eskiden bir de staging provası vardı;
320541
* insanların avatar yüklemesini sınıyordu ve o uçlar 19 Temmuz'da
321542
* kaldırıldı — aşağıdaki ilk satır tam olarak bunu doğruluyor. Prova

0 commit comments

Comments
 (0)