diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 09ff177c..1ff1e241 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -29,4 +29,10 @@ jobs: - run: pnpm format:check - run: pnpm test - run: pnpm test:smoke + - name: Install browser prerequisites + run: | + sudo apt-get update + sudo apt-get install -y libnss3-tools + - run: pnpm exec playwright install --with-deps firefox + - run: pnpm test:cross-host - run: node scripts/package-smoke.mjs diff --git a/README.md b/README.md index 1987eaed..a83cd1e0 100644 --- a/README.md +++ b/README.md @@ -27,6 +27,8 @@ Both servers use local synthetic credentials. The private App key stays in the d If another local application already uses `127.0.0.1:3005`, choose another available loopback address while keeping the demo on port 3005: `DEMO_HOST=127.0.0.98 pnpm demo`. +Use the [cross-host installation proof](docs/cross-host-installation.md) to reproduce an HTTPS application starting OAuth on one host while the App's `setup_url` returns to another. `pnpm test:cross-host` drives the browser through account and repository selection, observes the missing host-only cookie, and verifies its return after a redirect to the initiating host. + ## Run the emulator by itself ```bash diff --git a/docs/cross-host-installation.md b/docs/cross-host-installation.md new file mode 100644 index 00000000..84d19561 --- /dev/null +++ b/docs/cross-host-installation.md @@ -0,0 +1,61 @@ +# Reproduce an installation return across hosts + +An application can start OAuth at `https://aictrl.dev` while its GitHub App's configured setup callback returns to `https://app.aictrl.dev/api/github-app/setup`. A host-only correlation cookie belongs to the initiating host. Validating it at the other host rejects the installation return because the browser doesn't send it there. + +The emulator already redirects to the full configured `apps[].setup_url`, including its host. This proof exercises that behavior through the OAuth user picker and GitHub App installation form. Both application listeners stay on port 3005: + +| Role | Local origin | +| --- | --- | +| Initiating application | `https://127.0.0.98:3005` | +| Configured setup callback | `https://127.0.0.99:3005` | +| GitHub emulator | `http://127.0.0.100:4200` | + +These separate loopback IP hosts require no DNS or hosts-file changes. A second port on the same host wouldn't test host-only cookie isolation. + +## Run the browser proof + +Use Node 24, pnpm 11, OpenSSL, and `certutil` from `libnss3-tools`. On Debian or Ubuntu, install the last prerequisite with `sudo apt install libnss3-tools`. If the binary is outside `PATH`, set `CERTUTIL_PATH` to its absolute path. + +From the repository root: + +```bash +pnpm install --frozen-lockfile +pnpm build +pnpm exec playwright install --with-deps firefox +pnpm test:cross-host +``` + +The test generates a temporary CA and a server certificate for both loopback hosts. It imports that CA into a temporary Firefox profile, starts the HTTPS listeners, and keeps browser certificate verification enabled. It removes the profile and certificates and closes the listeners afterward. The user's browser profile and system trust store remain unchanged. + +The browser runs two flows. Each starts OAuth on the initiating host, chooses **octocat**, chooses **Install on example-org**, selects **Only select repositories**, checks **Select repository: example-org/selected**, and submits **Install**. + +1. The first return stays on the configured callback host. The server receives no `__Host-emulator_oauth_correlation` cookie and reports `Missing host-only OAuth cookie`. +2. The second return verifies the fixture's signed state, redirects to the initiating host's same callback path, then validates the correlation cookie there. The browser supplies the cookie, and the fixture exchanges an App JWT for an installation token. `/installation/repositories` returns only `example-org/selected`. + +The assertions check the emulator's installation response redirects to the configured host, the cookie's `Secure`, `HttpOnly`, `SameSite=Lax`, and `Path=/` attributes, and its absence from the other host. They also check the opaque `state`, `installation_id`, `setup_action=install`, and existing query parameters. The bounce preserves the entire callback query, including repeated parameters and encoded values. Requests use browser-managed cookies throughout. + +## Run the demonstration interactively + +Provide a PEM key and certificate whose subject alternative names include `127.0.0.98` and `127.0.0.99`, signed by a CA your browser trusts. The browser test's temporary trust applies only to its own Firefox profile. + +```bash +CROSS_HOST_TLS_KEY=/path/to/server.key \ +CROSS_HOST_TLS_CERT=/path/to/server.crt \ +pnpm demo:cross-host +``` + +Open `https://127.0.0.98:3005`. Choose **Reproduce missing callback cookie** or **Return to the initiating host**, then complete the user, account, and repository choices. The callback displays the result as JSON. `/observations` on either application origin exposes the callback host, synthetic fixture state, raw query, and whether the request carried the correlation cookie. + +The demonstration creates an installation on the selected account. Restart it before installing the same App on that account again. Stop it with Ctrl+C. + +## Reuse the fixture in an application regression + +[`examples/lib/local-https.mjs`](../examples/lib/local-https.mjs) exports: + +- `createLocalTls(hostnames)` accepts IP addresses, creates temporary CA/server PEM files, and returns `{ ca, directory, tls, close }`. Its defaults are `127.0.0.98` and `127.0.0.99`. +- `launchTrustedFirefox(firefox, certificates, { headless })` imports the CA into an isolated profile and returns a Playwright browser context with HTTPS verification enabled. +- `startHttpsOrigins({ tls, handler, appPort, sourceHostname, callbackHostname })` binds two HTTPS listeners and returns `{ sourceOrigin, callbackOrigin, close }`. The handler receives Node request/response objects and both origins. The default application port is 3005. + +[`startCrossHostDemo`](../examples/cross-host-demo.mjs) combines these origins with a seeded emulator. It returns `sourceOrigin`, `callbackOrigin`, `emulatorUrl`, `observations`, `reset()`, and `close()`. Its optional asynchronous `setupHandler` receives `{ request, response, url, sourceOrigin, callbackOrigin, observation }`. Return `true` after handling a setup callback, or return a false value to use the demonstration handler. `reset()` clears observations and resets emulator state between browser cases. + +For an application's own handler, reuse the HTTPS and trusted-browser helpers, configure the emulator's `setup_url` to the callback origin, and route both HTTPS listeners to the application. Initiate OAuth through its normal route. Keep the negative assertion at the callback host and assert that the successful return reaches the initiating host with the original query and browser correlation cookie. The fixture's HMAC/state implementation illustrates the redirect order; the application must run its own state verification and correlation checks. diff --git a/docs/github-app-installation.md b/docs/github-app-installation.md index 01903e31..3a420acc 100644 --- a/docs/github-app-installation.md +++ b/docs/github-app-installation.md @@ -33,6 +33,8 @@ The standalone wrapper generates omitted App keys. Direct `seedFromConfig` calle Installation forms expire after 10 minutes, are bound to their user, App, and account, and can be submitted once. Pending forms are limited to 32 per user across accounts and 1024 per emulator instance. Reaching either limit evicts the oldest applicable form. Reopen the installation page after expiry or eviction. The server rechecks membership and repository ownership at submission, rejects empty selected sets and cross-account IDs with `422`, and rejects a duplicate App/account installation with `409`. Form sessions and pending forms are in memory and reset with the emulator. +The configured `setup_url` can use a different host from the application that started OAuth. The emulator retains that host. Use the [cross-host installation proof](cross-host-installation.md) to observe a secure, host-only application cookie missing at the setup host and returning after a browser redirect to the initiating host. + ## Discover memberships and installed repositories `GET /user/memberships/orgs?state=active&per_page=100` requires a user token with `read:org`, `write:org`, or `admin:org`. Responses include `state: "active"`, `role: "admin" | "member"`, and organization metadata. The emulator has active memberships only; requesting `state=pending` returns an empty list. Installation tokens cannot call this endpoint. OAuth-authenticated `GET /user` and `PATCH /user` report the token's granted scopes in `X-OAuth-Scopes`. diff --git a/examples/cross-host-demo.mjs b/examples/cross-host-demo.mjs new file mode 100644 index 00000000..c26041b9 --- /dev/null +++ b/examples/cross-host-demo.mjs @@ -0,0 +1,250 @@ +import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto"; +import { readFile } from "node:fs/promises"; +import { pathToFileURL } from "node:url"; +import { createGitHubEmulator } from "../packages/github-emulator/dist/index.js"; +import { renderCardPage } from "../packages/@emulators/core/dist/index.js"; +import { getAppPrivateKey, mintAppJwt } from "./lib/github-app.mjs"; +import { json, redirect } from "./lib/http.mjs"; +import { startHttpsOrigins } from "./lib/local-https.mjs"; + +export const correlationCookie = "__Host-emulator_oauth_correlation"; +const clientId = "cross-host-client"; +const clientSecret = "cross-host-local-secret"; +const appId = 12345; +const hashNonce = (nonce) => createHash("sha256").update(nonce).digest("hex"); +const cookieFor = (request) => + request.headers.cookie + ?.split(/;\s*/) + .find((part) => part.startsWith(`${correlationCookie}=`)) + ?.slice(correlationCookie.length + 1); +const matchesCorrelation = (claims, request) => { + const nonce = cookieFor(request); + if (!nonce || typeof claims.nonceHash !== "string") return false; + const actual = Buffer.from(hashNonce(nonce)); + const expected = Buffer.from(claims.nonceHash); + return actual.length === expected.length && timingSafeEqual(actual, expected); +}; + +export async function startCrossHostDemo({ + tls, + appPort = 3005, + sourceHostname = "127.0.0.98", + callbackHostname = "127.0.0.99", + emulatorHostname = "127.0.0.100", + emulatorPort = 4200, + setupHandler, +} = {}) { + let emulator; + const observations = []; + const stateKey = randomBytes(32); + const mac = (body) => createHmac("sha256", stateKey).update(body).digest("base64url"); + const verifyState = (state) => { + const index = state.lastIndexOf("."); + if (index < 0) return undefined; + const body = state.slice(0, index); + const actual = Buffer.from(state.slice(index + 1)); + const expected = Buffer.from(mac(body)); + if (actual.length !== expected.length || !timingSafeEqual(actual, expected)) return undefined; + try { + return JSON.parse(body); + } catch { + return undefined; + } + }; + const origins = await startHttpsOrigins({ + tls, + appPort, + sourceHostname, + callbackHostname, + handler: async (request, response, { sourceOrigin, callbackOrigin }) => { + const origin = `https://${request.headers.host}`; + if (![sourceOrigin, callbackOrigin].includes(origin)) { + json(response, 400, { error: "Unexpected host" }); + return; + } + const url = new URL(request.url, origin); + if (request.method !== "GET") { + json(response, 405, { error: "Use GET" }); + return; + } + if (url.pathname === "/") { + response.writeHead(200, { "content-type": "text/html; charset=utf-8" }); + response.end( + renderCardPage( + "Cross-host GitHub installation", + "Observe a host-only OAuth cookie across the configured setup callback.", + '

Reproduce missing callback cookie

Return to the initiating host

', + "GitHub", + ), + ); + return; + } + if (url.pathname === "/login" && origin === sourceOrigin) { + const nonce = randomBytes(24).toString("base64url"); + const body = JSON.stringify({ + origin, + nonceHash: hashNonce(nonce), + bounce: url.searchParams.get("mode") === "bounce", + note: "opaque + /?&=%#return", + }); + const state = `${body}.${mac(body)}`; + response.setHeader("set-cookie", `${correlationCookie}=${nonce}; HttpOnly; Secure; SameSite=Lax; Path=/`); + redirect( + response, + `${emulator.url}/login/oauth/authorize?${new URLSearchParams({ client_id: clientId, redirect_uri: `${sourceOrigin}/oauth/callback`, scope: "repo read:org", state })}`, + ); + return; + } + if (url.pathname === "/oauth/callback" && origin === sourceOrigin) { + const state = url.searchParams.get("state") ?? ""; + const claims = verifyState(state); + if (claims?.origin !== sourceOrigin || !matchesCorrelation(claims, request)) { + json(response, 400, { error: "Invalid OAuth correlation" }); + return; + } + const exchanged = await fetch(`${emulator.url}/login/oauth/access_token`, { + method: "POST", + headers: { "content-type": "application/json", accept: "application/json" }, + body: JSON.stringify({ + code: url.searchParams.get("code"), + client_id: clientId, + client_secret: clientSecret, + redirect_uri: `${sourceOrigin}/oauth/callback`, + }), + }); + const result = await exchanged.json(); + if (!exchanged.ok || !result.access_token) throw new Error("OAuth exchange failed"); + redirect(response, `${emulator.url}/apps/cross-host-proof/installations/new?${new URLSearchParams({ state })}`); + return; + } + if (url.pathname === "/api/github-app/setup") { + const state = url.searchParams.get("state") ?? ""; + const claims = verifyState(state); + const observation = { + origin, + path: url.pathname, + search: url.search, + state, + installationId: url.searchParams.get("installation_id"), + setupAction: url.searchParams.get("setup_action"), + hasCorrelationCookie: cookieFor(request) !== undefined, + }; + observations.push(observation); + if (setupHandler && (await setupHandler({ request, response, url, sourceOrigin, callbackOrigin, observation }))) + return; + if ( + claims?.origin !== sourceOrigin || + !/^\d+$/.test(observation.installationId ?? "") || + observation.setupAction !== "install" + ) { + json(response, 400, { error: "Invalid installation callback" }); + return; + } + if (origin !== claims.origin && claims.bounce) { + // Copy the original callback query before correlating the initiating host's cookie. + redirect(response, `${claims.origin}${url.pathname}${url.search}`); + return; + } + if (!matchesCorrelation(claims, request)) { + json(response, 400, { error: "Missing host-only OAuth cookie", observation }); + return; + } + const jwt = mintAppJwt(getAppPrivateKey(emulator), appId); + const minted = await fetch(`${emulator.url}/app/installations/${observation.installationId}/access_tokens`, { + method: "POST", + headers: { authorization: `Bearer ${jwt}` }, + }); + const credentials = await minted.json(); + if (!minted.ok || !credentials.token) throw new Error("Installation token exchange failed"); + const repositories = await fetch(`${emulator.url}/installation/repositories`, { + headers: { authorization: `Bearer ${credentials.token}` }, + }); + if (!repositories.ok) throw new Error("Installation repositories request failed"); + json(response, 200, { + complete: true, + observation, + repositories: (await repositories.json()).repositories.map((repo) => repo.full_name), + }); + return; + } + if (url.pathname === "/observations") { + json(response, 200, observations); + return; + } + json(response, 404, { error: "Not found" }); + }, + }); + try { + emulator = await createGitHubEmulator({ + port: emulatorPort, + hostname: emulatorHostname, + seed: { + users: [{ login: "octocat", name: "Local developer" }], + orgs: [{ login: "example-org", members: [{ login: "octocat", role: "admin" }] }], + repos: [ + { owner: "example-org", name: "selected", private: true }, + { owner: "example-org", name: "unselected", private: true }, + ], + oauth_apps: [ + { + client_id: clientId, + client_secret: clientSecret, + name: "Cross-host proof", + redirect_uris: [`${origins.sourceOrigin}/oauth/callback`], + }, + ], + apps: [ + { + app_id: appId, + slug: "cross-host-proof", + name: "Cross-host proof", + setup_url: `${origins.callbackOrigin}/api/github-app/setup?marker=keep%2Bencoded&extra=first&extra=second`, + permissions: { contents: "read" }, + events: [], + installations: [], + }, + ], + }, + }); + return { + ...origins, + emulatorUrl: emulator.url, + observations, + reset() { + observations.length = 0; + emulator.reset(); + }, + close: () => Promise.all([origins.close(), emulator.close()]), + }; + } catch (error) { + await origins.close(); + throw error; + } +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + try { + if (!process.env.CROSS_HOST_TLS_KEY || !process.env.CROSS_HOST_TLS_CERT) + throw new Error("Set CROSS_HOST_TLS_KEY and CROSS_HOST_TLS_CERT to trusted local PEM files"); + const demo = await startCrossHostDemo({ + tls: { + key: await readFile(process.env.CROSS_HOST_TLS_KEY), + cert: await readFile(process.env.CROSS_HOST_TLS_CERT), + }, + }); + console.log( + `Initiating application: ${demo.sourceOrigin}\nConfigured setup host: ${demo.callbackOrigin}\nGitHub emulator: ${demo.emulatorUrl}`, + ); + const stop = () => { + void demo.close().catch((error) => { + console.error(error.message); + process.exitCode = 1; + }); + }; + process.once("SIGINT", stop); + process.once("SIGTERM", stop); + } catch (error) { + console.error(error.message); + process.exitCode = 1; + } +} diff --git a/examples/cross-host.test.mjs b/examples/cross-host.test.mjs new file mode 100644 index 00000000..f9bbacb1 --- /dev/null +++ b/examples/cross-host.test.mjs @@ -0,0 +1,113 @@ +import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; +import { test } from "node:test"; +import { firefox } from "playwright"; +import { correlationCookie, startCrossHostDemo } from "./cross-host-demo.mjs"; +import { createLocalTls, launchTrustedFirefox } from "./lib/local-https.mjs"; + +test( + "GitHub installation preserves setup_url host, then a source-host bounce restores the host-only cookie", + { timeout: 90_000 }, + async (t) => { + const certificates = await createLocalTls(); + let context; + let demo; + try { + context = await launchTrustedFirefox(firefox, certificates); + demo = await startCrossHostDemo({ tls: certificates.tls }); + const page = await context.newPage(); + for (const mode of ["reject", "bounce"]) { + demo.reset(); + await context.clearCookies(); + await page.goto(`${demo.sourceOrigin}/login?mode=${mode}`); + await page.locator('form:has(input[name="login"][value="octocat"]) button').click(); + await page.getByRole("link", { name: "Install on example-org", exact: true }).click(); + await page.getByRole("radio", { name: "Only select repositories", exact: true }).check(); + await page.getByRole("checkbox", { name: "Select repository: example-org/selected", exact: true }).check(); + assert.equal( + await page + .getByRole("checkbox", { name: "Select repository: example-org/unselected", exact: true }) + .isChecked(), + false, + ); + const initialState = new URL(page.url()).searchParams.get("state"); + assert.ok(initialState.includes("opaque + /?&=%#return")); + const installationResponse = page.waitForResponse( + (response) => + response.request().method() === "POST" && + new URL(response.url()).pathname === "/apps/cross-host-proof/installations/new", + ); + const finalOrigin = mode === "bounce" ? demo.sourceOrigin : demo.callbackOrigin; + const callbackResponse = page.waitForResponse( + (response) => + new URL(response.url()).origin === finalOrigin && + new URL(response.url()).pathname === "/api/github-app/setup" && + response.status() !== 302, + ); + await page.getByRole("button", { name: "Install", exact: true }).click(); + const redirect = await installationResponse; + assert.equal(redirect.status(), 302); + assert.equal(new URL((await redirect.allHeaders()).location).origin, demo.callbackOrigin); + await page.waitForURL( + (url) => + url.origin === (mode === "bounce" ? demo.sourceOrigin : demo.callbackOrigin) && + url.pathname === "/api/github-app/setup", + ); + const result = JSON.parse(await page.locator("body").innerText()); + const cookies = await context.cookies(demo.sourceOrigin); + const correlation = cookies.find((cookie) => cookie.name === correlationCookie); + assert.ok(correlation); + const claims = JSON.parse(initialState.slice(0, initialState.lastIndexOf("."))); + assert.equal(claims.nonceHash, createHash("sha256").update(correlation.value).digest("hex")); + assert.equal(Object.hasOwn(claims, "nonce"), false); + assert.equal(initialState.includes(correlation.value), false); + assert.equal(correlation.domain, new URL(demo.sourceOrigin).hostname); + assert.equal(correlation.secure, true); + assert.equal(correlation.httpOnly, true); + assert.equal(correlation.sameSite, "Lax"); + assert.equal(correlation.path, "/"); + assert.equal( + (await context.cookies(demo.callbackOrigin)).some((cookie) => cookie.name === correlationCookie), + false, + ); + assert.equal(demo.observations[0].origin, demo.callbackOrigin); + assert.equal(demo.observations[0].hasCorrelationCookie, false); + assert.equal(demo.observations[0].state, initialState); + assert.equal(demo.observations[0].setupAction, "install"); + assert.ok(/^\d+$/.test(demo.observations[0].installationId)); + const callback = new URL(`${demo.callbackOrigin}${demo.observations[0].path}${demo.observations[0].search}`); + assert.equal(callback.searchParams.get("marker"), "keep+encoded"); + assert.deepEqual(callback.searchParams.getAll("extra"), ["first", "second"]); + if (mode === "reject") { + assert.equal((await callbackResponse).status(), 400); + assert.equal(result.error, "Missing host-only OAuth cookie"); + assert.equal(demo.observations.length, 1); + t.diagnostic(`${demo.callbackOrigin}: correlation cookie absent, callback rejected with HTTP 400`); + } else { + assert.equal((await callbackResponse).status(), 200); + assert.equal(result.complete, true); + assert.deepEqual(result.repositories, ["example-org/selected"]); + assert.equal(demo.observations.length, 2); + assert.equal(demo.observations[1].origin, demo.sourceOrigin); + assert.equal(demo.observations[1].hasCorrelationCookie, true); + assert.equal(demo.observations[1].path, demo.observations[0].path); + assert.equal(demo.observations[1].search, demo.observations[0].search); + assert.equal(demo.observations[1].state, initialState); + t.diagnostic( + `${demo.callbackOrigin}: cookie absent; ${demo.sourceOrigin}: cookie restored, query preserved, selected repository verified with HTTP 200`, + ); + } + } + } finally { + try { + await context?.close(); + } finally { + try { + await demo?.close(); + } finally { + await certificates.close(); + } + } + } + }, +); diff --git a/examples/demo.mjs b/examples/demo.mjs index e88e9980..d4cb091f 100644 --- a/examples/demo.mjs +++ b/examples/demo.mjs @@ -1,20 +1,15 @@ import { createServer } from "node:http"; -import { createHmac, randomBytes, sign, timingSafeEqual } from "node:crypto"; +import { createHmac, randomBytes, timingSafeEqual } from "node:crypto"; import { pathToFileURL } from "node:url"; import { createGitHubEmulator } from "../packages/github-emulator/dist/index.js"; import { escapeHtml, renderCardPage } from "../packages/@emulators/core/dist/index.js"; +import { getAppPrivateKey, mintAppJwt } from "./lib/github-app.mjs"; +import { closeServer, json, redirect } from "./lib/http.mjs"; const clientId = "local-client"; const clientSecret = "local-secret"; const webhookSecret = "local-webhook-secret"; -function closeServer(server) { - return new Promise((resolve, reject) => { - server.close((error) => error && error.code !== "ERR_SERVER_NOT_RUNNING" ? reject(error) : resolve()); - server.closeAllConnections(); - }); -} - async function readBody(request) { const chunks = []; let length = 0; @@ -26,16 +21,6 @@ async function readBody(request) { return Buffer.concat(chunks); } -function json(response, status, body) { - response.writeHead(status, { "content-type": "application/json" }); - response.end(JSON.stringify(body)); -} - -function redirect(response, location) { - response.writeHead(302, { location }); - response.end(); -} - export async function startDemo({ appPort = 3005, emulatorPort = 4200, hostname = "127.0.0.1" } = {}) { let handler; const app = createServer((request, response) => { @@ -77,7 +62,7 @@ export async function startDemo({ appPort = 3005, emulatorPort = 4200, hostname const sessions = new Map(); const events = []; const waiters = new Set(); - const appKey = emulator.generatedSecrets.find((secret) => secret.kind === "github.app_private_key").value; + const appKey = getAppPrivateKey(emulator); const api = (path, options) => fetch(`${emulator.url}${path}`, { ...options, signal: AbortSignal.timeout(8000) }); const sessionFor = (request) => { const match = /(?:^|;\s*)demo_session=([A-Za-z0-9_-]+)/.exec(request.headers.cookie ?? ""); @@ -136,9 +121,7 @@ export async function startDemo({ appPort = 3005, emulatorPort = 4200, hostname } if (request.method === "POST" && url.pathname === "/issues") { if (!session?.token) { json(response, 401, { error: "Sign in first" }); return; } - const now = Math.floor(Date.now() / 1000); - const unsigned = [{ alg: "RS256", typ: "JWT" }, { iss: "1234", iat: now - 60, exp: now + 300 }].map((part) => Buffer.from(JSON.stringify(part)).toString("base64url")).join("."); - const jwt = `${unsigned}.${sign("RSA-SHA256", Buffer.from(unsigned), appKey).toString("base64url")}`; + const jwt = mintAppJwt(appKey, 1234); const minted = await api("/app/installations/100/access_tokens", { method: "POST", headers: { authorization: `Bearer ${jwt}` } }); const credentials = await minted.json(); if (!minted.ok || !credentials.token) throw new Error(`App token exchange failed: ${minted.status}`); diff --git a/examples/lib/github-app.mjs b/examples/lib/github-app.mjs new file mode 100644 index 00000000..3ae80ec0 --- /dev/null +++ b/examples/lib/github-app.mjs @@ -0,0 +1,18 @@ +import { sign } from "node:crypto"; + +export function getAppPrivateKey(emulator) { + const secret = emulator.generatedSecrets.find((secret) => secret.kind === "github.app_private_key"); + if (!secret) throw new Error("Emulator did not generate a GitHub App private key"); + return secret.value; +} + +export function mintAppJwt(key, appId) { + const now = Math.floor(Date.now() / 1000); + const unsigned = [ + { alg: "RS256", typ: "JWT" }, + { iss: String(appId), iat: now - 60, exp: now + 300 }, + ] + .map((part) => Buffer.from(JSON.stringify(part)).toString("base64url")) + .join("."); + return `${unsigned}.${sign("RSA-SHA256", Buffer.from(unsigned), key).toString("base64url")}`; +} diff --git a/examples/lib/http.mjs b/examples/lib/http.mjs new file mode 100644 index 00000000..12023928 --- /dev/null +++ b/examples/lib/http.mjs @@ -0,0 +1,16 @@ +export function closeServer(server) { + return new Promise((resolve, reject) => { + server.close((error) => (error && error.code !== "ERR_SERVER_NOT_RUNNING" ? reject(error) : resolve())); + server.closeAllConnections(); + }); +} + +export function json(response, status, body) { + response.writeHead(status, { "content-type": "application/json" }); + response.end(JSON.stringify(body)); +} + +export function redirect(response, location) { + response.writeHead(302, { location }); + response.end(); +} diff --git a/examples/lib/local-https.mjs b/examples/lib/local-https.mjs new file mode 100644 index 00000000..648bd5a5 --- /dev/null +++ b/examples/lib/local-https.mjs @@ -0,0 +1,143 @@ +import { execFileSync } from "node:child_process"; +import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises"; +import { createServer } from "node:https"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { closeServer } from "./http.mjs"; + +export async function createLocalTls(hostnames = ["127.0.0.98", "127.0.0.99"]) { + const directory = await mkdtemp(join(tmpdir(), "github-emulator-https-")); + const rootKey = join(directory, "root.key"); + const ca = join(directory, "root.crt"); + const key = join(directory, "server.key"); + const cert = join(directory, "server.crt"); + const csr = join(directory, "server.csr"); + const extensions = join(directory, "server.ext"); + const openssl = (args) => execFileSync("openssl", args, { stdio: "pipe" }); + try { + openssl([ + "req", + "-x509", + "-newkey", + "rsa:2048", + "-nodes", + "-days", + "2", + "-subj", + "/CN=GitHub emulator local test CA", + "-addext", + "basicConstraints=critical,CA:TRUE", + "-addext", + "keyUsage=critical,keyCertSign,cRLSign", + "-keyout", + rootKey, + "-out", + ca, + ]); + openssl([ + "req", + "-new", + "-newkey", + "rsa:2048", + "-nodes", + "-subj", + `/CN=${hostnames[0]}`, + "-keyout", + key, + "-out", + csr, + ]); + await writeFile( + extensions, + `basicConstraints=critical,CA:FALSE\nkeyUsage=critical,digitalSignature,keyEncipherment\nextendedKeyUsage=serverAuth\nsubjectAltName=${hostnames.map((host) => `IP:${host}`).join(",")}\n`, + ); + openssl([ + "x509", + "-req", + "-in", + csr, + "-CA", + ca, + "-CAkey", + rootKey, + "-CAcreateserial", + "-days", + "2", + "-extfile", + extensions, + "-out", + cert, + ]); + return { + ca, + directory, + tls: { key: await readFile(key), cert: await readFile(cert) }, + close: () => rm(directory, { recursive: true, force: true }), + }; + } catch (error) { + await rm(directory, { recursive: true, force: true }); + throw error; + } +} + +// Firefox reads trusted roots from this profile, leaving the user's trust store unchanged. +export async function launchTrustedFirefox(firefox, certificates, { headless = true } = {}) { + const profile = join(certificates.directory, "firefox"); + await mkdir(profile); + const certutil = process.env.CERTUTIL_PATH ?? "certutil"; + try { + execFileSync(certutil, ["-N", "-d", `sql:${profile}`, "--empty-password"], { stdio: "pipe" }); + execFileSync( + certutil, + ["-A", "-d", `sql:${profile}`, "-n", "github-emulator-local-test", "-t", "C,,", "-i", certificates.ca], + { stdio: "pipe" }, + ); + } catch (error) { + throw new Error( + "Local browser trust requires certutil from libnss3-tools. Set CERTUTIL_PATH to its binary if needed.", + { cause: error }, + ); + } + return firefox.launchPersistentContext(profile, { headless, ignoreHTTPSErrors: false }); +} + +export async function startHttpsOrigins({ + tls, + handler, + appPort = 3005, + sourceHostname = "127.0.0.98", + callbackHostname = "127.0.0.99", +}) { + if (sourceHostname === callbackHostname) throw new Error("Use different source and callback hosts"); + const sourceOrigin = `https://${sourceHostname}:${appPort}`; + const callbackOrigin = `https://${callbackHostname}:${appPort}`; + const servers = []; + const close = () => Promise.all(servers.map(closeServer)); + try { + for (const hostname of [sourceHostname, callbackHostname]) { + const server = createServer(tls, (request, response) => { + void Promise.resolve() + .then(() => handler(request, response, { sourceOrigin, callbackOrigin })) + .catch((error) => { + if (response.headersSent) response.destroy(error); + else { + response.writeHead(500); + response.end(error.message); + } + }); + }); + servers.push(server); + await new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(appPort, hostname, () => { + server.off("error", reject); + resolve(); + }); + }); + } + return { sourceOrigin, callbackOrigin, close }; + } catch (error) { + await close(); + throw error; + } +} diff --git a/package.json b/package.json index ceaeed97..7091c658 100644 --- a/package.json +++ b/package.json @@ -11,13 +11,16 @@ "format:check": "prettier --check \"**/*.{ts,tsx}\"", "start": "node packages/github-emulator/dist/cli.js", "demo": "node examples/demo.mjs", + "demo:cross-host": "node examples/cross-host-demo.mjs", "test:smoke": "node examples/smoke.mjs", + "test:cross-host": "node --test examples/cross-host.test.mjs", "pack:standalone": "pnpm --filter @aictrl/github-emulator pack --pack-destination artifacts" }, "devDependencies": { "@types/node": "^22", "eslint": "^9.39.4", "eslint-config-prettier": "^10.1.8", + "playwright": "^1.64.1", "prettier": "^3.8.1", "typescript": "^5.7", "typescript-eslint": "^8.58.0", diff --git a/packages/github-emulator/README.md b/packages/github-emulator/README.md index 2d6182c1..cc42874b 100644 --- a/packages/github-emulator/README.md +++ b/packages/github-emulator/README.md @@ -24,4 +24,6 @@ After installing the tarball, `npx github-emulator --help` lists CLI options. It Browser App installation supports the OAuth session, account and repository selection, a configured setup callback, and signed `installation.created` webhooks. Pending forms expire after 10 minutes and are limited to 32 per user and 1024 per instance. Invalid callback configuration uses the installation's local settings URL. See [installation configuration](../../docs/github-app-installation.md). +The source checkout includes a [cross-host browser proof](../../docs/cross-host-installation.md) with local HTTPS origins and a temporary trusted browser profile. It verifies that `setup_url` preserves its configured host and that the initiating host's `__Host-` cookie returns only after a redirect back to that host. + Current limitations include GitHub App user-token refresh, native Git clone/push, and guaranteed cancellation of in-flight webhooks during reset. The baseline uses upstream's typed in-memory state; SQLite is a planned iteration. See the repository roadmap for the supported proof flows and contribution plan. diff --git a/packages/github-emulator/src/cli.ts b/packages/github-emulator/src/cli.ts index 7c08a77b..74331bc4 100644 --- a/packages/github-emulator/src/cli.ts +++ b/packages/github-emulator/src/cli.ts @@ -15,6 +15,7 @@ Usage: github-emulator [options] Source checkout: pnpm start --config examples/github.json Demo application: pnpm demo (http://127.0.0.1:3005) +Cross-host browser proof (source checkout): pnpm test:cross-host Installation forms expire after 10 minutes (32 per user, 1024 per instance). App setup callbacks must use HTTP(S); invalid values use local settings. `; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 4f8aee65..084336c0 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -17,6 +17,9 @@ importers: eslint-config-prettier: specifier: ^10.1.8 version: 10.1.8(eslint@9.39.4) + playwright: + specifier: ^1.64.1 + version: 1.64.1 prettier: specifier: ^3.8.1 version: 3.8.1 @@ -1135,6 +1138,16 @@ packages: pkg-types@1.3.1: resolution: {integrity: sha512-/Jm5M4RvtBFVkKWRu2BLUTNP8/M2a+UwuAX+ae4770q1qVGtfjG+WTCupoZixokjmHiry8uI+dlY8KXYV5HVVQ==} + playwright-core@1.64.1: + resolution: {integrity: sha512-BC4s8y6SEVA6Q1rSxZTto8hI1KUI3xXlHGZgvGqP4IqPdI/a6FX9H29IDNz7vKo9l21b6LfYosScPL6M3xxyDQ==} + engines: {node: '>=20'} + hasBin: true + + playwright@1.64.1: + resolution: {integrity: sha512-HCrVhHr5QQuwYoswEUGTb7gGp522yflbv/ST8nF4sFWGuLjQCt17Q/EubpGGSNKYn1tsTCPZxqHhHCfVURu7UA==} + engines: {node: '>=20'} + hasBin: true + postcss-load-config@6.0.1: resolution: {integrity: sha512-oPtTM4oerL+UXmx+93ytZVN82RrlY/wPUV8IeDxFrzIjXOLF1pN+EmKPLbubvKHT2HC20xXsCAH2Z+CKV6Oz/g==} engines: {node: '>= 18'} @@ -2304,6 +2317,12 @@ snapshots: mlly: 1.8.2 pathe: 2.0.3 + playwright-core@1.64.1: {} + + playwright@1.64.1: + dependencies: + playwright-core: 1.64.1 + postcss-load-config@6.0.1(postcss@8.5.23): dependencies: lilconfig: 3.1.3 diff --git a/skills/github/SKILL.md b/skills/github/SKILL.md index 6ea31b0f..d2fd9009 100644 --- a/skills/github/SKILL.md +++ b/skills/github/SKILL.md @@ -41,6 +41,8 @@ Use an App JWT for `/repositories/:id/installation`, then exchange it for an ins Pending installation forms expire after 10 minutes. The emulator retains at most 32 forms per user and 1024 per instance, evicting the oldest when a limit is reached. Reopen the installation page if a form has expired or been evicted. Setup callbacks must be absolute HTTP(S) URLs; omitted, malformed, relative, and non-HTTP(S) values use the installation's local settings URL. +For application hosts that differ from the App's configured setup host, run `pnpm test:cross-host` after the prerequisites in `docs/cross-host-installation.md`. The browser proof uses local HTTPS on port 3005, selects a repository through the installation form, and observes host-only cookie delivery before and after a return to the initiating host. Reuse `examples/lib/local-https.mjs` for certificate generation, a trusted Firefox profile, and two HTTPS listeners. Keep TLS verification enabled and let the browser supply cookies. + ## Iteration boundary Full user authorization/refresh remains outside the verified subset. SQLite remains planned; upstream's typed store is retained initially. Keep source changes and regression tests for protocol behavior in their own commits under the upstream package paths. See `docs/upstream-workflow.md` before preparing an upstream PR. Do not publish npm releases during the baseline.