From 06ced51ddd081c998349fb41d85ac6b040fe9872 Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Wed, 11 Nov 2026 03:09:37 +0000 Subject: [PATCH] Prove browser proxy HTTPS pairing --- .../gen-2826-browser-proxy-https-pairing.md | 29 +++ .../fixtures/https-pairing/localhost-cert.pem | 19 ++ .../fixtures/https-pairing/localhost-key.pem | 28 +++ .../app/test/https-pairing.browser.test.mjs | 183 ++++++++++++++++++ 4 files changed, 259 insertions(+) create mode 100644 docs/decisions/gen-2826-browser-proxy-https-pairing.md create mode 100644 packages/app/test/fixtures/https-pairing/localhost-cert.pem create mode 100644 packages/app/test/fixtures/https-pairing/localhost-key.pem create mode 100644 packages/app/test/https-pairing.browser.test.mjs diff --git a/docs/decisions/gen-2826-browser-proxy-https-pairing.md b/docs/decisions/gen-2826-browser-proxy-https-pairing.md new file mode 100644 index 00000000..99f4b7d1 --- /dev/null +++ b/docs/decisions/gen-2826-browser-proxy-https-pairing.md @@ -0,0 +1,29 @@ +# GEN-2826: Browser to credential proxy HTTPS and identity pairing + +## Decision + +Provision one credential proxy for the Factorize owner. Factorize trusts the new proxy identity while provisioning it and stores an immutable pairing tuple: Factorize proxy ID, Fly app/Machine identity, canonical public HTTPS origin, and the proxy SSH host public-key fingerprint. Store an identity generation with the tuple. The canonical origin is the Fly app's `*.fly.dev` name for the initial deployment; a customer domain can be added later only after its DNS ownership and Fly certificate are validated. Do not discover or silently adopt a new origin or host key at runtime. + +### HTTPS route and certificate ownership + +Use the proxy's public Fly app hostname as the browser URL. Fly Proxy accepts HTTPS on port 443 and performs its documented built-in TLS termination at the edge; route the decrypted request to the credential-proxy service on a private Fly network listener. The guest listener is reachable only through the app's Fly service and does not expose a public HTTP port. This explicitly trusts Fly's TLS termination and private-network boundary; browser TLS does not continue to the guest. The browser still gets normal Web PKI hostname and chain validation for the Fly app hostname. + +For a later customer hostname, its owner controls DNS and authorizes Fly's certificate issuance. Attach it with documented `fly certs add ` and publish the DNS challenge/records Fly reports; verify it with `fly certs check ` before making it the canonical origin. Fly provisions and renews the edge certificate. Do not issue a production certificate or deploy as part of this proof. The fixture uses a local self-signed certificate, so a live domain, production DNS, and ACME issuance remain deployment prerequisites, not test prerequisites. References: [Fly custom domains](https://fly.io/docs/networking/custom-domain/) and [Fly TLS support](https://fly.io/docs/networking/tls/). + +### Browser unlock capability and CORS + +After normal Factorize owner authentication and CSRF/origin checks, Factorize returns a short-lived (60 seconds maximum), one-use Ed25519-signed capability for `POST /unlock`. Its signed claims contain issuer, audience equal to the paired proxy ID, action, owner ID, pairing generation, exact Factorize web origin, expiry, and random `jti`. The proxy has the Factorize verification public key; the signing private key never goes to Fly. The browser calls the canonical proxy HTTPS origin directly and sends this capability in `Authorization` plus the unlock key in the JSON body. The Factorize endpoint receives no unlock key and returns only the capability/status metadata. The proxy consumes `jti` atomically, rejects expired, replayed, wrong-audience, wrong-action, or stale-generation capabilities, and keeps the unlock key only in process memory. + +On the proxy, require a non-null `Origin` exactly equal to the Factorize app origin for both preflight and actual requests. Allow only `POST`, `Content-Type`, and `Authorization`; answer a valid preflight with that one origin and `Vary: Origin`. Reject foreign/missing origins and invalid preflights without CORS permission. Never use `*`, reflect an arbitrary origin, allow credentialed cookies, or treat CORS as authentication; the capability is mandatory even for an allowed origin. Do not log request bodies, authorization, or unlock material. Bound the request body and reject redirects at the browser client. + +### Identity binding and replacement + +Browsers cannot directly pin or inspect the agent's SSH host key. The browser authenticates the HTTPS hostname and certificate through Web PKI, then authenticates the proxy's logical identity by requiring the Factorize-signed capability audience and generation to match the already paired proxy. Factorize's provisioning record binds that logical proxy ID to its Fly app/Machine and SSH host fingerprint. Enrollment authorization delivered to an agent names the same proxy ID, Fly identity, generation, and SSH fingerprint; the agent's SSH client verifies the fingerprint before its one authenticated, restricted integration-transport connection. Thus HTTPS identity and SSH identity meet at the Factorize-trusted pairing tuple, not by pretending the browser validates SSH. + +Unexpected app/Machine identity, hostname, certificate origin, generation, or SSH fingerprint changes fail closed and revoke outstanding capabilities/enrollments. Recovery requires an authenticated owner to review and explicitly approve the proposed replacement identity in Factorize. Approval increments the pairing generation, replaces the tuple, and invalidates prior capabilities and enrollments; it is never inferred from DNS, a new TLS certificate for the same hostname, a restarted Machine, or a successful SSH connection. A stable proxy identity may persist across stop/restart. The unlock key and decrypted credentials never persist across process restart. + +## Proof fixture + +`packages/app/test/https-pairing.browser.test.mjs` starts local HTTPS origins with the test-only localhost certificate and a mock Factorize capability issuer. Chromium verifies allowed-origin unlock, foreign-origin preflight denial, expired and wrong-proxy capability rejection, identity replacement rejection until explicit approval, and that the Factorize backend never receives the unlock body. It uses ephemeral ports and closes browser/server resources. Run it with `npm run test --workspace=factorize-app`. + +This is a protocol/decision proof, not a production proxy implementation or live Fly certificate check. A production implementation must keep its Fly service/private listener and certificate configuration consistent with the termination boundary above. diff --git a/packages/app/test/fixtures/https-pairing/localhost-cert.pem b/packages/app/test/fixtures/https-pairing/localhost-cert.pem new file mode 100644 index 00000000..abbc8d3b --- /dev/null +++ b/packages/app/test/fixtures/https-pairing/localhost-cert.pem @@ -0,0 +1,19 @@ +-----BEGIN CERTIFICATE----- +MIIDHzCCAgegAwIBAgIUZMPYR05Hs5LuxQ2AM5c32pJB9mgwDQYJKoZIhvcNAQEL +BQAwFDESMBAGA1UEAwwJbG9jYWxob3N0MB4XDTI2MTExMTAyNTg0NFoXDTM2MTEw +ODAyNTg0NFowFDESMBAGA1UEAwwJbG9jYWxob3N0MIIBIjANBgkqhkiG9w0BAQEF +AAOCAQ8AMIIBCgKCAQEAr7vXBbWHlF173uIYhm3w3qBgp5ZmHGYVgKqbYLgMQ5Bx +PwtUhVNIgslKUh2ViZ9WfTonVo/FIgT9RiiKNzXwFK2gkiby6rd3MwwUIJ025DES +oVt8jTp6UqfVBWvcVJpUOVnOHj1Z08KkrTx+PY80BB0ITKYfGp08LGNI7xAuPmfV +stC6WTtnSrCkl5N5bhDWFzUk595ekf6h5Za0Bn5EULv60a7i3B6p33NW5cG10qBj +Eqa1+tkyS/pYbpXHro++YCsuSf0jmtDEg5EcqFSuqSLVkUPV4Wo0YkfinAlZyPjH +gB7eXNJeooPQT0xM1LzIZR99BElmH0ZIYkEn2Oe+PwIDAQABo2kwZzAdBgNVHQ4E +FgQUyLJDL1E5jgsOKvoHI66fgnMZt+EwHwYDVR0jBBgwFoAUyLJDL1E5jgsOKvoH +I66fgnMZt+EwDwYDVR0TAQH/BAUwAwEB/zAUBgNVHREEDTALgglsb2NhbGhvc3Qw +DQYJKoZIhvcNAQELBQADggEBAFOkHPf2vUv9dVPOvaakKXChwpO5A6mCjxKZ/NHV +fQB3TH+nmMq18p4L5zvlBUyCPmj1m9KYxgpGoFE3JrQKDE3sszw2g1xztiNsFu5X +S2EVolmb0zIeLlDYnte+0wCmtwmITc0Icn65GYDEhxE4UL4NmgAzPm7cA7S4qz7i +0MJul5f8A5ahop91j9u/lfkJMeAGV8ldylPXFNwlbbeQ4HTtnbwoQs21fo+AFLwD +7q0/8ljfTEwsElPLXQvMqAyfC5s6CTuaKgjxJqSpeM5r9ZKkcw0VaDBIziBadl10 +hpa3kS6UrsvuWdZh3XF3KkmALL0Bfd8qqYU8WFfmhvZLdS0= +-----END CERTIFICATE----- diff --git a/packages/app/test/fixtures/https-pairing/localhost-key.pem b/packages/app/test/fixtures/https-pairing/localhost-key.pem new file mode 100644 index 00000000..d38f352e --- /dev/null +++ b/packages/app/test/fixtures/https-pairing/localhost-key.pem @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCvu9cFtYeUXXve +4hiGbfDeoGCnlmYcZhWAqptguAxDkHE/C1SFU0iCyUpSHZWJn1Z9OidWj8UiBP1G +KIo3NfAUraCSJvLqt3czDBQgnTbkMRKhW3yNOnpSp9UFa9xUmlQ5Wc4ePVnTwqSt +PH49jzQEHQhMph8anTwsY0jvEC4+Z9Wy0LpZO2dKsKSXk3luENYXNSTn3l6R/qHl +lrQGfkRQu/rRruLcHqnfc1blwbXSoGMSprX62TJL+lhulceuj75gKy5J/SOa0MSD +kRyoVK6pItWRQ9XhajRiR+KcCVnI+MeAHt5c0l6ig9BPTEzUvMhlH30ESWYfRkhi +QSfY574/AgMBAAECggEAHRPbtFohIO+G+441uKigXnXzCEfehXxuumeAZjSN8vAH +jQL27Uimit17qrKyd58h1H6225/WYpaowd8bX59RJlrEYuqG70eENbId8neRCZkF +GCXnKgcvDlYu7UK3plgS75pofKByKJPgY7nKuazkUnnrUaN7KhAyULXs74Gh5TlK +9HGOsGp701WyTC+UdgjFTUmqvCcr1Mq3DSiareKMXeDreiexP46ispDeJVlnT8se +Hq5MS2VfDOWwL2f6nQ32d7ZoydYiOD0VY36RI6OezJewuOmF/ZZkS8vnz26LxvD8 +7fsukSPv6q2HQh0lW93TTKus0o77TWv3h9yFq4mwAQKBgQDWotbeix03dc+fvETs +b1TGxC8diqfobb+ACKukdWPeB3iEsT19y/wnvT+yJJuiIMK0Nxvw2/magW95belt +/xIoswPzIjx7efzGkg/LkVKZS2sPd6xlBG4mcuJYOHFFyFUCbCFpyLkZBNzaniQv +Cq85kjFfPDnzGy5urLHaRW6mAQKBgQDRmbzIZoAa62luku3WzSE1zZ4/4oDHQgbC +3ogaFY9AOITelpg4OfhW2zNX7jPZHq++rewm0NW25kmYJ3rqbCX2/ogClfpaKtqo +eHJhwH4DOwDU6Ujmo3e2oUxWR34g54DVcFcOffFlwTfdPjnJiKHVNbptha48nV7W +4V/EvtTkPwKBgEtdel1CM8wZjgHktb7fiMESegjBexveDXQDl2Fz5tE7hlHxekoF +qlC53vfKauuO3U8yWplEZGygLmhQ87ov6kxoL2bcCqjAuMVw3CL6sCorlTglKV9/ +Ir5VcKzRhNSf91mWZlUiqfvi/Tm2dbYe5lAsyTFLkH2Qecla0kh2QNgBAoGBAIB2 +UE0m/WcCV6ksplbbfHpEXrRa94CoiApRZ2tNQXIj8dOWyw7TANEDIhHHbcGp3B7q +6+zSW9nwhLSbpesdg5tBX0zubPVshH1y7O/akaEbPaRAoqyxDcNCUs4inTw/hyfJ +5aF9MUGjTcDszXAmrMFHX86WezatYR4kHZUxPLvzAoGBANUsvKfvV3QzkE+tiF9n +EDjLVivoMUV08nEXLjv4ewOzUCmr0RcoA97LOCz2pRmdngr6/6gwnRF576XBfR0c +MLKVZWQoctI1q5Ie16hEPryVm8856ZjhWZFEi/+6uBqGSzLBnjrZrbtZ4NO9S1rJ +2ngWPAPtAueZLSq3b/0TXkpX +-----END PRIVATE KEY----- diff --git a/packages/app/test/https-pairing.browser.test.mjs b/packages/app/test/https-pairing.browser.test.mjs new file mode 100644 index 00000000..381e49e8 --- /dev/null +++ b/packages/app/test/https-pairing.browser.test.mjs @@ -0,0 +1,183 @@ +import assert from "node:assert/strict"; +import { readFile } from "node:fs/promises"; +import { createServer as createHttpsServer } from "node:https"; +import { createPrivateKey, createPublicKey, generateKeyPairSync, sign, verify } from "node:crypto"; +import { once } from "node:events"; +import { after, before, test } from "node:test"; +import { chromium } from "playwright"; + +const fixture = new URL("./fixtures/https-pairing/", import.meta.url); +const [key, cert] = await Promise.all([ + readFile(new URL("localhost-key.pem", fixture)), + readFile(new URL("localhost-cert.pem", fixture)), +]); +const proxyId = "proxy-expected"; +const ownerId = "owner-fixture"; +const generation = 4; +let capabilitySequence = 0; +const nowSeconds = () => Math.floor(Date.now() / 1000); +const { publicKey, privateKey } = generateKeyPairSync("ed25519"); +const trustedPublicKey = createPublicKey(publicKey.export({ type: "spki", format: "pem" })); +const signingKey = createPrivateKey(privateKey.export({ type: "pkcs8", format: "pem" })); +const pageHtml = ``; + +function makeCapability({ aud = proxyId, exp = nowSeconds() + 30, gen = generation } = {}) { + const header = Buffer.from(JSON.stringify({ alg: "EdDSA", typ: "JWT" })).toString("base64url"); + const payload = Buffer.from(JSON.stringify({ iss: "factorize", aud, sub: ownerId, action: "proxy:unlock", origin: appOrigin, generation: gen, exp, jti: `jti-${++capabilitySequence}` })).toString("base64url"); + const signingInput = `${header}.${payload}`; + return `${signingInput}.${sign(null, Buffer.from(signingInput), signingKey).toString("base64url")}`; +} + +function checkCapability(token) { + const [header, payload, signature, extra] = token.split("."); + if (!header || !payload || !signature || extra) return false; + const input = `${header}.${payload}`; + try { + const claims = JSON.parse(Buffer.from(payload, "base64url").toString()); + return verify(null, Buffer.from(input), trustedPublicKey, Buffer.from(signature, "base64url")) + && claims.iss === "factorize" && claims.aud === proxyId && claims.action === "proxy:unlock" + && claims.sub === ownerId && claims.origin === appOrigin && claims.generation === generation + && claims.exp > nowSeconds(); + } catch { return false; } +} + +function pairIdentity(current, candidate, approve = false) { + if (JSON.stringify(current) === JSON.stringify(candidate)) return current; + if (!approve) throw new Error("proxy identity replacement requires explicit owner approval"); + return { ...candidate, generation: current.generation + 1 }; +} + +let appServer; +let proxyServer; +let evilServer; +let browser; +let appOrigin; +let localProxyOrigin; +let evilOrigin; +let factorizeBodies; +let unlockedKeys; +let preflightOrigins; +let directPostOrigins; + +function listen(server) { + server.listen(0, "127.0.0.1"); + return once(server, "listening"); +} + +function originOf(server) { + return `https://localhost:${server.address().port}`; +} + +function readBody(request) { + return new Promise((resolve, reject) => { + const chunks = []; + request.on("data", chunk => chunks.push(chunk)); + request.on("end", () => resolve(Buffer.concat(chunks))); + request.on("error", reject); + }); +} + +before(async () => { + factorizeBodies = []; + unlockedKeys = []; + preflightOrigins = []; + directPostOrigins = []; + appServer = createHttpsServer({ key, cert }, async (request, response) => { + if (request.url === "/") { + response.writeHead(200, { "Content-Type": "text/html" }).end(pageHtml); + return; + } + if (request.url === "/api/v1/proxy-unlock-capability" && request.method === "POST") { + factorizeBodies.push(await readBody(request)); + response.writeHead(200, { "Content-Type": "application/json" }).end(JSON.stringify({ capability: makeCapability() })); + return; + } + response.writeHead(404).end(); + }); + proxyServer = createHttpsServer({ key, cert }, async (request, response) => { + const origin = request.headers.origin; + if (request.method === "OPTIONS") { + preflightOrigins.push(origin); + if (origin !== appOrigin || request.headers["access-control-request-method"] !== "POST" + || request.headers["access-control-request-headers"]?.split(",").map(value => value.trim().toLowerCase()).sort().join(",") !== "authorization,content-type") { + response.writeHead(403).end(); + return; + } + response.writeHead(204, { "Access-Control-Allow-Origin": appOrigin, "Access-Control-Allow-Methods": "POST", "Access-Control-Allow-Headers": "Authorization, Content-Type", Vary: "Origin" }).end(); + return; + } + directPostOrigins.push(origin); + if (origin !== appOrigin) { response.writeHead(403).end(); return; } + response.setHeader("Access-Control-Allow-Origin", appOrigin); + response.setHeader("Vary", "Origin"); + const token = request.headers.authorization?.replace(/^Bearer /, ""); + if (request.method !== "POST" || request.url !== "/unlock" || !token || !checkCapability(token)) { + response.writeHead(401, { "Content-Type": "application/json" }).end('{"error":"invalid capability"}'); + return; + } + const body = JSON.parse((await readBody(request)).toString()); + if (typeof body.key !== "string" || !body.key) { response.writeHead(400).end(); return; } + unlockedKeys.push(body.key); + response.writeHead(200, { "Content-Type": "application/json" }).end('{"unlocked":true}'); + }); + evilServer = createHttpsServer({ key, cert }, (_request, response) => response.writeHead(200, { "Content-Type": "text/html" }).end(pageHtml)); + await Promise.all([listen(appServer), listen(proxyServer), listen(evilServer)]); + appOrigin = originOf(appServer); + localProxyOrigin = originOf(proxyServer); + evilOrigin = originOf(evilServer); + browser = await chromium.launch({ headless: true }); +}); + +after(async () => { + await browser?.close(); + await Promise.all([appServer, proxyServer, evilServer].filter(Boolean).map(server => new Promise(resolve => server.close(resolve)))); +}); + +test("direct HTTPS unlock enforces origin, capability and paired identity", async () => { + const context = await browser.newContext({ ignoreHTTPSErrors: true }); + try { + const appPage = await context.newPage(); + await appPage.goto(appOrigin, { waitUntil: "domcontentloaded", timeout: 5_000 }); + const capability = await appPage.evaluate(async () => { + const response = await fetch("/api/v1/proxy-unlock-capability", { method: "POST" }); + return (await response.json()).capability; + }); + const success = await appPage.evaluate(({ origin, token }) => window.unlock(origin, token, "unlock-fixture-key"), { origin: localProxyOrigin, token: capability }); + assert.equal(success.status, 200); + assert.deepEqual(unlockedKeys, ["unlock-fixture-key"]); + assert.equal(factorizeBodies.length, 1); + assert.equal(factorizeBodies[0].length, 0, "Factorize capability issuer must not receive an unlock body"); + + const expired = makeCapability({ exp: nowSeconds() - 1 }); + const expiredResult = await appPage.evaluate(({ origin, token }) => window.unlock(origin, token, "must-not-unlock"), { origin: localProxyOrigin, token: expired }); + assert.equal(expiredResult.status, 401); + const wrongProxy = makeCapability({ aud: "different-proxy" }); + const wrongProxyResult = await appPage.evaluate(({ origin, token }) => window.unlock(origin, token, "must-not-unlock"), { origin: localProxyOrigin, token: wrongProxy }); + assert.equal(wrongProxyResult.status, 401); + assert.deepEqual(unlockedKeys, ["unlock-fixture-key"]); + + const foreignPage = await context.newPage(); + await foreignPage.goto(evilOrigin, { waitUntil: "domcontentloaded", timeout: 5_000 }); + const beforeForeign = directPostOrigins.length; + const foreignResult = await foreignPage.evaluate(({ origin, token }) => window.unlock(origin, token, "foreign-origin-key").then(() => "unexpected success", () => "cors-blocked"), { origin: localProxyOrigin, token: capability }); + assert.equal(foreignResult, "cors-blocked"); + assert.equal(preflightOrigins.at(-1), evilOrigin); + assert.equal(directPostOrigins.length, beforeForeign, "foreign preflight must prevent the unlock POST"); + + const current = { proxyId, flyMachineId: "machine-a", sshFingerprint: "SHA256:old", generation }; + const replacement = { proxyId, flyMachineId: "machine-b", sshFingerprint: "SHA256:new", generation }; + assert.throws(() => pairIdentity(current, replacement), /explicit owner approval/); + assert.deepEqual(pairIdentity(current, replacement, true), { ...replacement, generation: generation + 1 }); + } finally { + await context.close(); + } +});