From 3ec0b9ddf35f1c81c96d36b841f35f713fb6a8af Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Fri, 4 Dec 2026 09:06:50 +1300 Subject: [PATCH] journeys: an MCP client connects through OAuth end to end; the credit override reminder asks for a reply once --- app/src/notify/render.rs | 27 ++++-- app/tests/emails.rs | 13 +++ scripts/screenshots/journeys.mjs | 151 ++++++++++++++++++++++++++++++- 3 files changed, 180 insertions(+), 11 deletions(-) diff --git a/app/src/notify/render.rs b/app/src/notify/render.rs index 596f4876..db25cc07 100644 --- a/app/src/notify/render.rs +++ b/app/src/notify/render.rs @@ -182,8 +182,9 @@ const COPY: &str = "copy:"; /// The one-line setup prompt for a coding agent, as the app shows it. pub const AGENT_PROMPT: &str = "Fetch https://visualci.com/install.md and follow it"; -/// The email's HTML: its paragraphs and one button, in a plain single column. -fn html(paragraphs: &[String], button: (&str, &str)) -> String { +/// The email's HTML: its paragraphs and one button, in a plain single column, and with `footer` the "Questions? Reply +/// to this email." line under it. +fn html(paragraphs: &[String], button: (&str, &str), footer: bool) -> String { let body: String = paragraphs .iter() .map(|p| match p.strip_prefix(COPY) { @@ -198,6 +199,12 @@ fn html(paragraphs: &[String], button: (&str, &str)) -> String { } }) .collect(); + let footer = if footer { + "

Questions? Reply to this email.

" + } else { + "" + }; format!( "\
String {

VisualCI

{body}\

\ - {label}

\ -

\ - Questions? Reply to this email.

", + {label}

{footer}", url = escape(button.1), label = escape(button.0), ) } -fn text(paragraphs: &[String], button: (&str, &str)) -> String { +fn text(paragraphs: &[String], button: (&str, &str), footer: bool) -> String { let lines: Vec<&str> = paragraphs.iter().map(|p| p.strip_prefix(COPY).unwrap_or(p)).collect(); let mut out = lines.join("\n\n"); - out.push_str(&format!("\n\n{}: {}\n\nQuestions? Reply to this email.\n", button.0, button.1)); + out.push_str(&format!("\n\n{}: {}\n", button.0, button.1)); + if footer { + out.push_str("\nQuestions? Reply to this email.\n"); + } out } @@ -228,6 +235,8 @@ pub fn render(kind: &Kind, about: &About<'_>) -> Rendered { let html = format!("
{}
", escape(text)); return Rendered { subject: subject.clone(), text: text.clone(), html }; } + // The credit override's reminder already asks for a reply in its body + let footer = !matches!(kind, Kind::CreditOverrideEnding { .. }); let org = about.org_name; let billing = format!("{}/{}/billing", about.app_url, about.org_slug); let (subject, paragraphs, button): (String, Vec, (String, String)) = match kind { @@ -403,7 +412,7 @@ pub fn render(kind: &Kind, about: &About<'_>) -> Rendered { ), }; let button = (button.0.as_str(), button.1.as_str()); - Rendered { text: text(¶graphs, button), html: html(¶graphs, button), subject } + Rendered { text: text(¶graphs, button, footer), html: html(¶graphs, button, footer), subject } } /// "Its repository is private." as part of a sentence: "its repository is private". diff --git a/app/tests/emails.rs b/app/tests/emails.rs index 0830b544..050149d6 100644 --- a/app/tests/emails.rs +++ b/app/tests/emails.rs @@ -18,6 +18,19 @@ fn every_email_renders() { write_the_emails_for_visualcis_own_review(); } +/// The credit override's reminder asks for a reply in its body, so it doesn't repeat it as a footer; the others do. +#[test] +fn the_credit_override_reminder_asks_for_a_reply_once() { + let about = notify::About { org_name: "Acme", org_slug: "acme", app_url: "https://app.visualci.test" }; + for (label, kind) in notify::render::samples() { + let r = notify::render(&kind, &about); + let footer = !matches!(kind, Kind::CreditOverrideEnding { .. }); + for (part, body) in [("text", &r.text), ("html", &r.html)] { + assert_eq!(body.contains("Questions? Reply to this email."), footer, "{label}, {part}"); + } + } +} + /// With `VISUALCI_EMAIL_SNAPSHOTS=` (VisualCI's own CI), every email as HTML and text, for its visual job. fn write_the_emails_for_visualcis_own_review() { let Ok(dir) = std::env::var("VISUALCI_EMAIL_SNAPSHOTS") else { return }; diff --git a/scripts/screenshots/journeys.mjs b/scripts/screenshots/journeys.mjs index f867689e..1f0c62da 100644 --- a/scripts/screenshots/journeys.mjs +++ b/scripts/screenshots/journeys.mjs @@ -2,8 +2,10 @@ // hosts, each step screenshotted. Each journey is a bug that reached production on 3 Dec 2026, written to fail // on it. // node journeys.mjs --out +import { createHash, randomBytes } from 'node:crypto' import { mkdir } from 'node:fs/promises' -import { chromium } from 'playwright' +import { createServer } from 'node:http' +import { chromium, request } from 'playwright' const arg = (name, fallback) => { const i = process.argv.indexOf(`--${name}`) @@ -156,7 +158,152 @@ await journey('mcp-on-its-own-host', async ({ page }) => { expect(app.status() === 404, `the app's host answered /mcp with ${app.status()}`) }) -// 6. With sign-ups closed (VISUALCI_WAITLIST=true, as production runs until launch), someone new signing in from the +// 6. An MCP client connecting through OAuth, as Claude Code or Cursor does: discovery on the MCP host, dynamic +// registration, the consent page on the app host (signing in through GitHub first), the code for tokens, then +// /mcp with the access token. Its token is for /mcp alone, and its refresh token gets a new one that works. +// (/mcp refused every `vca_` OAuth access token until PR #145.) +await journey('mcp-client-connects-with-oauth', async ({ page, shot }) => { + // The client's own HTTP calls: no browser cookies, so /mcp sees the bearer token alone + const api = await request.newContext({ ignoreHTTPSErrors: true }) + let listener + try { + const json = async (response, what) => { + const text = await response.text() + expect(response.ok(), `${what} answered ${response.status()}: ${text.slice(0, 300)}`) + return JSON.parse(text) + } + + // Discover: /mcp names its authorization server, which names its endpoints + const challenge = await api.post(`${MCP}/mcp`, { data: {}, headers: { accept: 'application/json, text/event-stream' } }) + expect(challenge.status() === 401, `signed out, /mcp answered ${challenge.status()}`) + const resource = await json(await api.get(`${MCP}/.well-known/oauth-protected-resource/mcp`), 'the resource metadata') + expect(resource.resource === `${MCP}/mcp`, `the resource metadata names ${resource.resource}`) + expect(resource.authorization_servers?.includes(MCP), `its authorization servers: ${resource.authorization_servers}`) + const server = await json(await api.get(`${MCP}/.well-known/oauth-authorization-server`), 'the server metadata') + expect(server.authorization_endpoint === `${APP}/oauth/authorize`, `consent at ${server.authorization_endpoint}`) + expect(server.token_endpoint === `${MCP}/oauth/token`, `tokens at ${server.token_endpoint}`) + expect(server.code_challenge_methods_supported?.includes('S256'), 'the server offers no S256 PKCE') + + // Register, with a loopback redirect as a desktop client does + const redirect = 'http://127.0.0.1:33418/callback' + const client = await json( + await api.post(server.registration_endpoint, { + data: { client_name: 'Journeys MCP Client', redirect_uris: [redirect], token_endpoint_auth_method: 'none' }, + }), + 'registration', + ) + expect(client.client_id, 'registration returned no client_id') + + // Authorize: PKCE (S256), signed out, so through GitHub first, then the consent page + const verifier = randomBytes(32).toString('base64url') + const challengeS256 = createHash('sha256').update(verifier).digest('base64url') + const state = randomBytes(8).toString('hex') + const authorize = new URL(server.authorization_endpoint) + for (const [k, v] of Object.entries({ + response_type: 'code', + client_id: client.client_id, + redirect_uri: redirect, + code_challenge: challengeS256, + code_challenge_method: 'S256', + scope: 'mcp', + resource: `${MCP}/mcp`, + state, + })) + authorize.searchParams.set(k, v) + // The client's loopback listener, as a desktop client runs one: it takes the code from the redirect + listener = createServer((req, res) => { + res.writeHead(200, { 'content-type': 'text/html' }) + res.end('

Connected. You can close this tab.

') + }) + await new Promise((resolve, reject) => listener.once('error', reject).listen(33418, '127.0.0.1', resolve)) + await page.goto(authorize.toString()) + expect(path(page) === '/login', `signed out, the consent page went to ${page.url()}, not the sign-in page`) + await shot('sign-in') + await page.getByRole('link', { name: 'Sign in with GitHub' }).click() + await page.waitForURL((url) => url.host === 'app.visualci.test' && url.pathname === '/oauth/authorize', { timeout: 15000 }) + await page.getByRole('button', { name: 'Allow' }).waitFor() + const consent = await page.locator('body').innerText() + expect(consent.includes('Journeys MCP Client'), `the consent page doesn't name the client: ${consent.slice(0, 300)}`) + expect(consent.includes('ada@journeys.test'), `the consent page doesn't say who's signed in: ${consent.slice(0, 300)}`) + await shot('consent') + await page.getByRole('button', { name: 'Allow' }).click() + await page.waitForURL((url) => url.href.startsWith(redirect), { timeout: 15000 }) + const back = new URL(page.url()) + expect(back.searchParams.get('state') === state, `the redirect's state is ${back.searchParams.get('state')}`) + const code = back.searchParams.get('code') + expect(code, `no code in the redirect: ${page.url()}`) + + // Token: the code and the verifier for an access token (vca_) and a refresh token (vcr_) + const tokens = await json( + await api.post(server.token_endpoint, { + form: { + grant_type: 'authorization_code', + code, + code_verifier: verifier, + client_id: client.client_id, + redirect_uri: redirect, + resource: `${MCP}/mcp`, + }, + }), + 'the token exchange', + ) + expect(tokens.access_token?.startsWith('vca_'), `the access token isn't a vca_ token: ${tokens.access_token?.slice(0, 4)}`) + expect(tokens.refresh_token?.startsWith('vcr_'), `the refresh token isn't a vcr_ token: ${tokens.refresh_token?.slice(0, 4)}`) + + // Use: initialize, tools/list and whoami on /mcp with the access token + const rpc = async (token, method, params = {}, at = '/mcp') => + api.post(`${MCP}${at}`, { + data: { jsonrpc: '2.0', id: 1, method, params }, + headers: { authorization: `Bearer ${token}`, accept: 'application/json, text/event-stream' }, + failOnStatusCode: false, + }) + const result = async (response, what) => { + const body = await json(response, what) + expect(!body.error, `${what}: ${JSON.stringify(body.error)}`) + return body.result + } + const init = { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'journeys', version: '1' } } + const initialized = await result(await rpc(tokens.access_token, 'initialize', init), 'initialize') + expect(initialized.serverInfo, `initialize returned no serverInfo: ${JSON.stringify(initialized)}`) + const listed = await result(await rpc(tokens.access_token, 'tools/list'), 'tools/list') + const names = listed.tools.map((t) => t.name) + for (const tool of ['whoami', 'list_builds', 'get_build']) + expect(names.includes(tool), `tools/list has no ${tool}: ${names.join(', ')}`) + const whoami = await result( + await rpc(tokens.access_token, 'tools/call', { name: 'whoami', arguments: {} }), + 'whoami', + ) + const me = whoami.structuredContent + expect(me?.email === 'ada@journeys.test', `whoami is ${me?.email}, not the signed-in person`) + expect(me?.via?.source === 'oauth', `whoami says it came through ${JSON.stringify(me?.via)}`) + + // The token is for /mcp alone: the admin endpoint refuses it (scope mcp, and Ada isn't staff) + const admin = await rpc(tokens.access_token, 'tools/list', {}, '/mcp/admin') + expect([401, 403].includes(admin.status()), `/mcp/admin answered the mcp token with ${admin.status()}`) + + // Refresh: a new access token, which works on /mcp + const refreshed = await json( + await api.post(server.token_endpoint, { + form: { + grant_type: 'refresh_token', + refresh_token: tokens.refresh_token, + client_id: client.client_id, + resource: `${MCP}/mcp`, + }, + }), + 'the refresh', + ) + expect(refreshed.access_token?.startsWith('vca_'), 'the refresh gave no vca_ token') + expect(refreshed.access_token !== tokens.access_token, 'the refresh gave the same access token') + const again = await result(await rpc(refreshed.access_token, 'tools/list'), 'tools/list with the refreshed token') + expect(again.tools.some((t) => t.name === 'whoami'), 'the refreshed token lists no whoami') + } finally { + await api.dispose() + listener?.close() + } +}) + +// 7. With sign-ups closed (VISUALCI_WAITLIST=true, as production runs until launch), someone new signing in from the // site lands on the waitlist page, never in the app. await journey('waitlist-keeps-new-people-out', async ({ page, shot }) => { const set = await page.request.post(`${GITHUB}/_stub/person`, {