Skip to content

Commit 664230b

Browse files
committed
merge(es-app): include reviewed API auth challenge containment (anomalyco#99)
2 parents 8bcb81e + ef89554 commit 664230b

5 files changed

Lines changed: 282 additions & 11 deletions

File tree

‎PAPERCUTS.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,3 +10,4 @@
1010
- 2026-09-16: Initial modes activation can lose old es-app drafts because the already-loaded client has no persistence yet. Serve the new build on a separate port until old tabs are checkpointed; daemon reconnect alone does not require a frontend reload (#93).
1111
- 2026-09-16: A spawned #97 lane lacked dependencies, and its no-production-install constraint was interpreted as forbidding lane-local dependency installation. Clarify dispatch scope and use a frozen lane-local install instead of links that can resolve foreign workspace source (#93).
1212
- 2026-09-16: Running the es-app Vite/Playwright harness directly with Bun hung before browser startup; the package's documented Node runner completed. Use `node test/*.browser.mjs`, not `bun`, for these harnesses.
13+
- 2026-09-16: Playwright's isolated Firefox installation stalled after download, leaving a bundle missing `libmozglue.dylib`. Extracting the same CDN archive with macOS `ditto` completed the test runtime; the user's Firefox profile was not involved.

‎packages/es-app/api-proxy.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import type { ProxyOptions } from "vite"
2+
3+
export const apiProxy = (target: string, prefix: string): ProxyOptions => ({
4+
target,
5+
changeOrigin: true,
6+
rewrite: (path) => path.slice(prefix.length),
7+
configure(proxy) {
8+
proxy.on("proxyRes", (response) => {
9+
// API/SSE failures belong in the app, not the browser's HTTP login dialog.
10+
if (response.statusCode === 401) delete response.headers["www-authenticate"]
11+
})
12+
},
13+
})
Lines changed: 188 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,188 @@
1+
import http from "node:http"
2+
import { createRequire } from "node:module"
3+
import { fileURLToPath } from "node:url"
4+
import { randomBytes } from "node:crypto"
5+
import { mkdtemp, rm } from "node:fs/promises"
6+
import { tmpdir } from "node:os"
7+
import path from "node:path"
8+
import { build, createServer, preview } from "vite"
9+
import { createFixture, directory } from "./composer-fixture.mjs"
10+
11+
const { chromium, firefox, expect } = createRequire(new URL("../../app/package.json", import.meta.url))(
12+
"@playwright/test",
13+
)
14+
const cleanups = []
15+
try {
16+
const fixture = await createFixture()
17+
cleanups.push(() => fixture.close())
18+
const credential = `Basic ${Buffer.from(`fixture:${randomBytes(24).toString("hex")}`).toString("base64")}`
19+
const denied = JSON.stringify({ error: "Authentication required" })
20+
const upstream = http.createServer((request, response) => {
21+
const pathname = new URL(request.url, fixture.url).pathname
22+
if (["/session/ses_a", "/event", "/api/state"].includes(pathname) && request.headers.authorization !== credential) {
23+
response.writeHead(401, {
24+
"www-authenticate": 'Basic realm="fixture"',
25+
"content-type": "application/json",
26+
"x-fixture": "protected",
27+
})
28+
response.end(denied)
29+
return
30+
}
31+
if (pathname === "/forbidden") {
32+
response.writeHead(403, { "content-type": "application/json" })
33+
response.end(JSON.stringify({ error: "Forbidden" }))
34+
return
35+
}
36+
const proxy = http.request(
37+
new URL(request.url, fixture.url),
38+
{ method: request.method, headers: request.headers },
39+
(result) => {
40+
response.writeHead(result.statusCode, result.headers)
41+
result.pipe(response)
42+
response.on("close", () => result.destroy())
43+
},
44+
)
45+
proxy.on("error", () => {
46+
if (!response.headersSent) response.writeHead(502)
47+
response.end()
48+
})
49+
request.pipe(proxy)
50+
})
51+
cleanups.push(
52+
() =>
53+
new Promise((resolve) => {
54+
upstream.closeAllConnections()
55+
upstream.close(() => resolve())
56+
}),
57+
)
58+
await new Promise((resolve) => upstream.listen(0, "127.0.0.1", resolve))
59+
const upstreamURL = `http://127.0.0.1:${upstream.address().port}`
60+
process.env.OPENCODE_URL = process.env.ES_DASHBOARD_URL = upstreamURL
61+
const root = fileURLToPath(new URL("..", import.meta.url))
62+
const scratch = await mkdtemp(path.join(tmpdir(), "opencode-auth-proxy-"))
63+
cleanups.push(() => rm(scratch, { recursive: true, force: true }))
64+
const dev = await createServer({ root, server: { host: "127.0.0.1", port: 0 } })
65+
cleanups.push(() => dev.close())
66+
await dev.listen()
67+
await build({ root, logLevel: "error", build: { outDir: path.join(scratch, "dist") } })
68+
const built = await preview({
69+
root,
70+
build: { outDir: path.join(scratch, "dist") },
71+
preview: { host: "127.0.0.1", port: 0 },
72+
})
73+
cleanups.push(
74+
() =>
75+
new Promise((resolve) => {
76+
built.httpServer.closeAllConnections()
77+
built.httpServer.close(() => resolve())
78+
}),
79+
)
80+
const origins = [
81+
["dev", `http://127.0.0.1:${dev.httpServer.address().port}`],
82+
["preview", `http://127.0.0.1:${built.httpServer.address().port}`],
83+
]
84+
if (process.argv.includes("--serve")) {
85+
console.log(
86+
JSON.stringify({
87+
preview: `${origins[1][1]}/session/ses_a?directory=${encodeURIComponent(directory)}`,
88+
scenario: "Synthetic protected upstream; expected HTTP 401 application error",
89+
}),
90+
)
91+
await new Promise((resolve) => {
92+
const stop = () => {
93+
process.off("SIGINT", stop)
94+
process.off("SIGTERM", stop)
95+
resolve()
96+
}
97+
process.once("SIGINT", stop)
98+
process.once("SIGTERM", stop)
99+
})
100+
} else {
101+
const browser = await (process.env.AUTH_BROWSER === "firefox"
102+
? firefox.launch({ headless: true })
103+
: chromium.launch({ headless: true, channel: "chrome" }))
104+
cleanups.push(() => browser.close())
105+
const baseline = process.env.AUTH_EXPECT_CHALLENGE === "1"
106+
const direct = await fetch(`${upstreamURL}/session/ses_a`)
107+
expect(direct.status).toBe(401)
108+
expect(/^Basic\b/.test(direct.headers.get("www-authenticate") ?? "")).toBe(true)
109+
await direct.body?.cancel()
110+
for (const [mode, origin] of origins) {
111+
for (const pathname of ["/oc/session/ses_a", "/oc/event", "/es/api/state"]) {
112+
const response = await fetch(`${origin}${pathname}`)
113+
console.log(
114+
JSON.stringify({
115+
mode,
116+
path: pathname,
117+
status: response.status,
118+
challengePresent: response.headers.has("www-authenticate"),
119+
}),
120+
)
121+
expect(response.status).toBe(401)
122+
expect(response.headers.has("www-authenticate")).toBe(baseline)
123+
expect(response.headers.get("x-fixture")).toBe("protected")
124+
expect(await response.text()).toBe(denied)
125+
const authorized = await fetch(`${origin}${pathname}`, { headers: { Authorization: credential } })
126+
expect(authorized.status).toBe(200)
127+
await authorized.body?.cancel()
128+
}
129+
const forbidden = await fetch(`${origin}/oc/forbidden`)
130+
expect(forbidden.status).toBe(403)
131+
await forbidden.body?.cancel()
132+
const context = await browser.newContext()
133+
try {
134+
if (process.env.AUTH_BROWSER === "firefox")
135+
await context.route("**/*", (route) =>
136+
new URL(route.request().url()).origin === origin ? route.continue() : route.abort(),
137+
)
138+
const page = await context.newPage()
139+
const challenges = []
140+
const cdp = process.env.AUTH_BROWSER === "firefox" ? undefined : await context.newCDPSession(page)
141+
if (cdp) {
142+
cdp.on(
143+
"Fetch.requestPaused",
144+
(event) =>
145+
void (new URL(event.request.url).origin === origin
146+
? cdp.send("Fetch.continueRequest", { requestId: event.requestId })
147+
: cdp.send("Fetch.failRequest", { requestId: event.requestId, errorReason: "BlockedByClient" })),
148+
)
149+
cdp.on("Fetch.authRequired", (event) => {
150+
challenges.push({ path: new URL(event.request.url).pathname, scheme: event.authChallenge.scheme })
151+
void cdp.send("Fetch.continueWithAuth", {
152+
requestId: event.requestId,
153+
authChallengeResponse: { response: "CancelAuth" },
154+
})
155+
})
156+
await cdp.send("Fetch.enable", { handleAuthRequests: true })
157+
}
158+
const responses = ["/oc/session/ses_a", "/oc/event", "/es/api/state"].map((pathname) =>
159+
page.waitForResponse(
160+
(response) => new URL(response.url()).pathname === pathname && response.status() === 401,
161+
),
162+
)
163+
await Promise.all([
164+
page.goto(`${origin}/session/ses_a?directory=${encodeURIComponent(directory)}`),
165+
...responses,
166+
])
167+
await expect(page.getByRole("alert").filter({ hasText: "HTTP 401" }).first()).toBeVisible({ timeout: 30000 })
168+
if (cdp)
169+
expect([...new Set(challenges.map((challenge) => challenge.path))].sort()).toEqual(
170+
baseline ? ["/es/api/state", "/oc/event", "/oc/session/ses_a"] : [],
171+
)
172+
console.log(
173+
JSON.stringify({
174+
mode,
175+
browser: browser.browserType().name(),
176+
applicationError: 401,
177+
authenticationChallenges: cdp ? challenges : null,
178+
}),
179+
)
180+
} finally {
181+
await context.close()
182+
}
183+
}
184+
}
185+
} finally {
186+
const results = await Promise.allSettled(cleanups.map((close) => Promise.resolve().then(close)))
187+
if (results.some((result) => result.status === "rejected")) throw new Error("Auth proxy fixture cleanup failed")
188+
}

‎packages/es-app/vite.config.ts‎

Lines changed: 3 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import tailwindcss from "@tailwindcss/vite"
22
import { defineConfig, type Plugin } from "vite"
33
import solid from "vite-plugin-solid"
4+
import { apiProxy } from "./api-proxy"
45

56
// Firefox loads worker scripts through the HTTP cache even on hard reload; a
67
// poisoned (empty) cache entry revived by vite's 304 revalidation yields
@@ -29,17 +30,8 @@ export default defineConfig({
2930
// spike: proxy the daemon so the browser stays same-origin (CORS check
3031
// against :4096 direct is a later step)
3132
proxy: {
32-
"/oc": {
33-
target: process.env.OPENCODE_URL ?? "http://127.0.0.1:4096",
34-
changeOrigin: true,
35-
rewrite: (path) => path.replace(/^\/oc/, ""),
36-
},
37-
"/es": {
38-
// ES_DASHBOARD_URL lets a dev instance point at its own dashboard
39-
target: process.env.ES_DASHBOARD_URL ?? "http://127.0.0.1:7777",
40-
changeOrigin: true,
41-
rewrite: (path) => path.replace(/^\/es/, ""),
42-
},
33+
"/oc": apiProxy(process.env.OPENCODE_URL ?? "http://127.0.0.1:4096", "/oc"),
34+
"/es": apiProxy(process.env.ES_DASHBOARD_URL ?? "http://127.0.0.1:7777", "/es"),
4335
},
4436
},
4537
build: {

‎perf/basic-auth-popups.md‎

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
# es-app Basic Auth Popups (#99)
2+
3+
## Finding
4+
5+
A backend `401` carrying `WWW-Authenticate: Basic` passes through both es-app API proxies unchanged. Browser authentication handling runs before application error handling; a background fetch or EventSource can therefore produce native login UI. This is a reproduced proxy behavior, not evidence of a Firefox defect.
6+
7+
The specific request behind the user's historical popup remains unidentified. Current live observations did not reproduce a challenge.
8+
9+
## Live Observation: 2026-09-16
10+
11+
Read-only, no credentials supplied, no response bodies recorded:
12+
13+
| Listener | Observed paths | Result |
14+
| --- | --- | --- |
15+
| 4096 daemon | `/global/health`, `/session/status` in an existing warm directory, `/global/event` | 200, no challenge |
16+
| 7777 dashboard | `/api/editspaces`, `/api/notifications`, `/api/state`, `/api/events` | 200, no challenge |
17+
| 3100 old es-app | `/`, the above paths through `/oc` and `/es` | 200, no challenge |
18+
| 3181 modes es-app | `/`, the above paths through `/oc` and `/es` | 200, no challenge |
19+
| Both es-app listeners | `/favicon.ico` | 404, no challenge |
20+
21+
- SSE bodies were cancelled immediately after response headers.
22+
- Process inspection confirmed 3100 is Vite dev and 3181 is Vite preview. Current inspected process metadata contained no `OPENCODE_SERVER_PASSWORD` environment assignment; secret values were never printed. This does not establish historical configuration.
23+
- The modes preview log contained no `401`, `WWW-Authenticate`, or `Unauthorized` match. It is not a complete access log and cannot identify the earlier request.
24+
- These were bounded path probes, not a HAR from the user's tab. They do not rule out other background resources or earlier authentication state.
25+
26+
## Source Trace
27+
28+
- `packages/opencode/src/server/routes/instance/httpapi/middleware/authorization.ts`: configured-auth failures produce a 401 with a Basic challenge for typed APIs, raw UI/documentation, and relevant PTY requests.
29+
- `packages/server/src/middleware/authorization.ts`: V2 API auth failures also produce Basic challenges.
30+
- Workspace proxy and hosted-UI fallback can preserve an upstream challenge; not every challenge must originate in the local password checker.
31+
- `packages/es-app/vite.config.ts`: `/oc` strips its prefix and targets OpenCode; `/es` targets the dashboard. Vite preview inherits `server.proxy`. Both previously forwarded upstream challenge headers.
32+
33+
## Isolated Reproduction
34+
35+
Real Vite dev and a freshly built Vite preview proxy to a loopback authentication fixture. It protects session metadata, EventSource, and dashboard state. The browser runs the actual es-app in a separate profile; no user tabs or real prompts are involved.
36+
37+
| Browser-observed request | Before | After |
38+
| --- | --- | --- |
39+
| `/oc/session/ses_a` | 401 + Basic challenge | 401, challenge absent |
40+
| `/oc/event` | 401 + Basic challenge | 401, challenge absent |
41+
| `/es/api/state` | 401 + Basic challenge | 401, challenge absent |
42+
43+
- Chrome CDP `Fetch.authRequired`: all three paths before; none after, in both dev and preview. The baseline probe cancels the synthetic challenges so automation can continue.
44+
- Firefox: dev and preview pass header checks and show the application HTTP 401 error. Native challenge events are not instrumented in Firefox; no claim of capturing the user's Firefox dialog.
45+
- All three browser responses are awaited before assertions, avoiding early success while background requests remain pending.
46+
- Default regression fails on the old behavior (`challengePresent: true`); passes after restoring the filter.
47+
48+
## Fix and Auth Contract
49+
50+
`api-proxy.ts` removes `www-authenticate` only from upstream 401 responses at the `/oc` and `/es` proxies. HTTP status, response body, other headers, and request credentials are preserved. This intentionally suppresses challenge-based negotiation at these application API proxies, including non-Basic challenge values.
51+
52+
Unauthorized clients still receive 401. Correct synthetic credentials still produce 200 through both proxies; 403 remains 403. Direct upstream access still returns its Basic challenge. Daemon authentication, plugin/permission policy, listeners, and exposure are not changed. The existing app error handling presents HTTP 401; this does not add an in-app credential-entry flow.
53+
54+
## Verification and Walkthrough
55+
56+
From `packages/es-app`:
57+
58+
```sh
59+
node test/auth-proxy.browser.mjs
60+
AUTH_BROWSER=firefox node test/auth-proxy.browser.mjs
61+
node test/auth-proxy.browser.mjs --serve
62+
bun test --conditions=browser ./src
63+
bun typecheck
64+
```
65+
66+
Use `PLAYWRIGHT_BROWSERS_PATH` for a lane-local Firefox installation when needed. Chrome uses the existing local Chrome channel. `--serve` prints a spare loopback preview URL whose protected synthetic upstream intentionally produces a visible application HTTP 401 error. Ctrl-C/SIGTERM closes the fixture and removes its temporary build.
67+
68+
- Chrome and Firefox proxy/browser runs passed dev and fresh preview modes.
69+
- es-app: 131 unit tests passed; typecheck passed. The browser harness builds the current app into a temporary directory.
70+
- `packages/opencode`: `bun test --timeout 30000 test/server/httpapi-authorization.test.ts` — 9 tests passed, including genuine auth rejection/challenges and authorized behavior.
71+
- Review findings corrected: wait for every protected browser request; register cleanup before setup can fail, and clean up serve mode on termination.
72+
73+
## Remaining Evidence Needed
74+
75+
If the real popup recurs, record its timestamp and triggering request's origin/path, status, and challenge scheme only. Do not share Authorization, cookies, password/token values, or query strings containing credentials. That distinguishes this reproduced proxy edge from an unrelated resource challenge.
76+
77+
No live restart, global install, deployment, push, landing, or permission change. Earlier parked `tuymo` and `vkqol` revisions are preserved.

0 commit comments

Comments
 (0)