Skip to content

Commit 30cbeae

Browse files
fix(server): an unimplemented API route must 404, not return the SPA (#64)
MEASURED 2026-09-15 while previewing the card editor (#185485/#185506): GET /iris/item/185442/share Accept: application/json -> 200 <!doctype html>... The route is not implemented. The UI handler is mounted as router.add("*", "/*"), so everything no API router claimed lands on it and is answered with index.html. For a browser NAVIGATION that is exactly right — the SPA owns its own paths and index.html boots it. For an API call it is a lie with a real cost: the caller asked for JSON and got a web page with a 200, so a route that does not exist is indistinguishable from one that does. What that cost, precisely: the client ran JSON.parse on the page, threw `SyntaxError: Unexpected token '<', "<!doctype "... is not valid JSON`, and the error boundary took down the ENTIRE session view. Not the one section that had no backend — the whole app, needing a Restart. #185506 expected unwired sections to read "Not connected"; nothing ever got far enough to render that, so the ticket's own description of the symptom was wrong, and every section it lists would have failed the same way as it was built. Two rules, because either alone leaves a hole: - a path under an API root never falls back, whatever the caller sends. No static asset lives under /iris/, so this is unambiguous. - any request that ASKED for JSON gets the 404 instead of index.html. This catches fetches under roots nobody has added to the list yet, which is the failure mode the list itself has. The Accept rule is applied only at the FALLBACK, after the exact-file lookup. My first cut checked it up front, which would have 404'd a real asset fetched with Accept: application/json — a regression traded for a fix. An exact file is an exact file whatever the header says; only the step that turns "no such path" into "here is a web page, status 200" is refused. Same hole fixed on the dev-proxy path, where vite also answers an unknown path with index.html, judged on the response's content-type because upstream is the only thing that knows whether the path was real. Verified against a server built from this source, beside the unpatched one: /iris/item/185442/share (json) before: 200 <!doctype after: 404 {"error":…} / (html) after: 200 <!doctype Tests: 5, mutation-verified against a no-op guard. Two of them exist for what must KEEP working — a browser navigation still gets the SPA, and a real asset is still served whatever its Accept header says. NOT verified: the end-to-end click-through. A server from this source would not render the session I had open, so I never clicked a card on it. res.json() on {"error":"Not Found"} cannot throw a SyntaxError, but that is reasoning, not a measurement, and the two are not the same thing. The shape, which is the transferable part: a catch-all that serves documents was answering for an API surface, so "not built yet" and "working" returned the same status and the same body. Same family as a 405 with no GET registered reading as an empty field, and as #185493, where one address for an outcome was guarded and another was not. Claude-Session: https://claude.ai/code/session_01JwiqN8M84qimu1TjZGSsdQ Co-authored-by: Claude Opus 5 <[email protected]>
1 parent aacb307 commit 30cbeae

2 files changed

Lines changed: 109 additions & 2 deletions

File tree

‎packages/opencode/src/server/shared/ui.ts‎

Lines changed: 55 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,24 @@ function notFound() {
5252
return HttpServerResponse.jsonUnsafe({ error: "Not Found" }, { status: 404 })
5353
}
5454

55+
/**
56+
* Path prefixes that are API surface and never documents.
57+
*
58+
* Anything under one of these that reaches the UI catch-all matched no route, and the only
59+
* honest answer is 404. Add a prefix here when you add an API root; a missing entry does not
60+
* break a working route, it only lets a MISSING one keep pretending to exist.
61+
*/
62+
const API_ROOTS = ["/iris/"] as const
63+
64+
export function isApiPath(path: string) {
65+
return API_ROOTS.some((root) => path.startsWith(root))
66+
}
67+
68+
/** Did the caller ask for JSON? Then index.html is never a valid answer to give it. */
69+
function acceptsJson(request: HttpServerRequest.HttpServerRequest) {
70+
return (request.headers["accept"] ?? "").includes("application/json")
71+
}
72+
5573
function embeddedUIResponse(file: string, body: Uint8Array) {
5674
const mime = FSUtil.mimeType(file)
5775
const headers = new Headers({ "content-type": mime })
@@ -65,8 +83,15 @@ export function serveEmbeddedUIEffect(
6583
requestPath: string,
6684
fs: FSUtil.Interface,
6785
embeddedWebUI: Record<string, string>,
86+
wantsJson = false,
6887
) {
69-
const file = embeddedWebUI[requestPath.replace(/^\//, "")] ?? embeddedWebUI["index.html"] ?? null
88+
// An EXACT file is served whatever the caller's Accept header says — a real asset is a real
89+
// asset. Only the index.html FALLBACK is refused for a JSON caller, because that fallback is
90+
// the step that turns "no such path" into "here is a web page, status 200".
91+
const exact = embeddedWebUI[requestPath.replace(/^\//, "")]
92+
if (!exact && wantsJson) return Effect.succeed(notFound())
93+
94+
const file = exact ?? embeddedWebUI["index.html"] ?? null
7095
if (!file) return Effect.succeed(notFound())
7196

7297
return fs.readFile(file).pipe(
@@ -83,7 +108,28 @@ export function serveUIEffect(
83108
const embeddedWebUI = yield* Effect.promise(() => embeddedUI(services.disableEmbeddedWebUi))
84109
const path = new URL(request.url, "http://localhost").pathname
85110

86-
if (embeddedWebUI) return yield* serveEmbeddedUIEffect(path, services.fs, embeddedWebUI)
111+
/*
112+
* AN UNIMPLEMENTED API ROUTE MUST 404, NOT RETURN A WEB PAGE.
113+
*
114+
* This handler is mounted as router.add("*", "/*"), so every request no API router claimed
115+
* lands here and is answered with index.html. For a browser NAVIGATION that is exactly
116+
* right — the SPA owns its own paths and index.html boots it. For an API call it is a lie
117+
* with real cost: the caller asked for JSON and got 200 plus a web page, so a route that
118+
* does not exist is indistinguishable from one that does.
119+
*
120+
* Measured 2026-09-15 on the card editor (#185485/#185506): GET /iris/item/185442/share is
121+
* not implemented, returned 200 and `<!doctype html>`, the client ran JSON.parse on it and
122+
* threw `SyntaxError: Unexpected token '<'`, and the error boundary took down the ENTIRE
123+
* session view. Not the one section — the app. The ticket expected unwired sections to read
124+
* "Not connected"; nothing got far enough to render that.
125+
*
126+
* Both halves of the condition matter. The prefix catches our own API whatever the caller
127+
* sends, and the Accept header catches every other fetch that wanted JSON, including ones
128+
* under roots nobody has listed yet.
129+
*/
130+
if (isApiPath(path)) return notFound()
131+
132+
if (embeddedWebUI) return yield* serveEmbeddedUIEffect(path, services.fs, embeddedWebUI, acceptsJson(request))
87133

88134
const response = yield* services.client.execute(
89135
HttpClientRequest.make(request.method)(upstreamURL(path), {
@@ -93,6 +139,13 @@ export function serveUIEffect(
93139
)
94140
const headers = proxyResponseHeaders(response.headers)
95141

142+
// Same hole on the dev path: vite also answers an unknown path with index.html, so a JSON
143+
// caller proxied upstream gets the same 200-and-a-web-page. Judged on the way back because
144+
// upstream is the only thing that knows whether the path was real.
145+
if (acceptsJson(request) && response.headers["content-type"]?.includes("text/html")) {
146+
return notFound()
147+
}
148+
96149
if (response.headers["content-type"]?.includes("text/html")) {
97150
const body = yield* response.text
98151
headers.set("Content-Security-Policy", cspForHtml(body))
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import { describe, expect, test } from "bun:test"
2+
import { Effect } from "effect"
3+
import { isApiPath, serveEmbeddedUIEffect } from "../../src/server/shared/ui"
4+
5+
/**
6+
* An unimplemented API route must 404, not return the SPA (#185485/#185506).
7+
*
8+
* The UI handler is mounted as router.add("*", "/*"), so everything no API router claimed
9+
* lands on it and used to be answered with index.html — 200, text/html. A JSON caller then
10+
* ran JSON.parse on a web page and threw `SyntaxError: Unexpected token '<'`, which the
11+
* client's error boundary escalated from one dead section to the whole app.
12+
*
13+
* The tests that matter most here are the two that must KEEP working: a browser navigation
14+
* still gets the SPA, and a real asset is still served whatever the caller's Accept says.
15+
*/
16+
17+
const html = new TextEncoder().encode("<!doctype html><title>spa</title>")
18+
const fakeFs = { readFile: () => Effect.succeed(html) } as any
19+
const bundle = { "index.html": "/dist/index.html", "assets/app.js": "/dist/assets/app.js" }
20+
21+
const run = (path: string, wantsJson: boolean) =>
22+
Effect.runSync(serveEmbeddedUIEffect(path, fakeFs, bundle, wantsJson))
23+
24+
describe("API paths never fall back to the SPA", () => {
25+
test("an API root is recognised whatever follows it", () => {
26+
expect(isApiPath("/iris/item/185442/share")).toBe(true)
27+
expect(isApiPath("/iris/bloqs")).toBe(true)
28+
})
29+
30+
test("an app path is NOT an API path — the SPA owns its own routes", () => {
31+
expect(isApiPath("/session/ses_123")).toBe(false)
32+
expect(isApiPath("/")).toBe(false)
33+
// Near-misses: the prefix is "/iris/", so neither of these is API surface.
34+
expect(isApiPath("/irisology")).toBe(false)
35+
expect(isApiPath("/x/iris/y")).toBe(false)
36+
})
37+
38+
test("a JSON caller asking for a path that does not exist gets 404, not a web page", () => {
39+
const res = run("/iris/item/1/share", true)
40+
expect(res.status).toBe(404)
41+
})
42+
43+
/** MUST KEEP WORKING: a navigation to an unknown path boots the SPA, which owns that route. */
44+
test("a browser navigation still gets index.html", () => {
45+
const res = run("/session/ses_123", false)
46+
expect(res.status).toBe(200)
47+
})
48+
49+
/** MUST KEEP WORKING: a real file is a real file, whatever the Accept header says. */
50+
test("an exact asset is served even when the caller asked for JSON", () => {
51+
const res = run("/assets/app.js", true)
52+
expect(res.status).toBe(200)
53+
})
54+
})

0 commit comments

Comments
 (0)