Repository navigation
refactor(api): move the ws-* proxy out of index.ts (L2, pure move) - #2714
Conversation
Pure move of the workspace-subdomain proxy middleware (index.ts lines 258-732 on main) into routes/workspace-subdomain-proxy.ts and routes/workspace-port-access.ts, mounted at the same position in the middleware chain. No behaviour change. index.ts drops from 1,040 to 543 lines and leaves the file-size exemption list. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Important Review skippedAuto reviews are limited based on label configuration. 🏷️ Required labels (at least one): 1
Please check the settings in the CodeRabbit UI or the
|
|
@coderabbitai review |
Action not completed
|
Coordinator review (self-host coordinator, task 01M7AF82KG9C78WAABTG3V1MN1)Reviewed head What I checked myself, independently of the author's script:
Relied on, not re-run by me: CI run 43507669855 (functional jobs green), the author's staging evidence (workspace chat and terminal, port token to cookie flow, public port on and off, the 401 page byte-identical to production, Instant path, cleanup), and the three specialist reviews. Merge decision: Raphaël's, requested in the coordinator chat on 2026-11-14. |
|
Merge approved by Raphaël on November 14, 2026 (about 13:16 UTC), in his own words: "Regarding PR2714, yeah, go ahead and merge it." Source: chat session a6bd681e-26f2-4ea3-9483-7188edcf27d7, message 01M7D5HFP5QSME6GJ08CFAF811, which I read directly. In the same message he lifted the per-PR approval for slices that only reorganize code with identical behaviour ("if code is just being reorganized and functionality remains exactly the same, then I don't want to be bothered by that"); slices that change behaviour still go to him. Head is unchanged since my review ( |
|
Coordinator: branch updated with main ( Re-checked at the new head: |
|
|
CI run 43603231157 on |



Summary
Self-host landing plan, slice L2 (idea
01M72M9AEB933ZY8269D376DKC, "LANDING PLAN (part 5 of 7)"): move the workspace-subdomain (ws-{id}.*,ws-{id}--{port}.*) proxy out ofapps/api/src/index.ts. Pure move, no behaviour change.apps/api/src/routes/workspace-subdomain-proxy.ts:workspaceSubdomainProxy(c, next), the former anonymousapp.use('*', …)middleware (main'sindex.tslines 258-732).apps/api/src/routes/workspace-port-access.ts:resolveWorkspacePortAccess(c, url, workspaceId, targetPort), the former inline port-access block (sam_port_accesscookie,?port_token=→ 302 +Set-Cookie, public-ports lookup, 401 "Session expired" page). It returns the 302 to the caller, which still sends it only after the D1 ownership check, as before.index.tsmountsapp.use('*', workspaceSubdomainProxy)at the same position and drops the imports only the block used.index.ts: 1,040 → 543 lines (under the 800-line limit), so it leaves theEXEMPT_FILESlist inscripts/quality/check-file-sizes.ts(that list's own comment says to remove split files).sam/selfhost-pass-2, so later slices (L6 and the reverse-tunnel/gateway work) apply as small diffs. The bodies are main's current code, not the integration branch's.Middleware order (unchanged)
app.onError(handleAppError)→ interactive-preview hostapp.use→ Pages proxyapp.use→ ws- proxy* (app.use('*', workspaceSubdomainProxy)) →requestLoggingMiddleware()→analyticsMiddleware()→apiCors→ routes →/mcp/*CORS overrides. The ws-* proxy is still the thirdapp.use('*'), before request logging, analytics, CORS and every auth middleware, exactly as on main. Tests that reach the proxy through the Worker entry (worker.default.fetch) were not touched and pass.Pure-move proof
.tmp/l2/verify_pure_move.py(scratch, not committed: the repository has no home for one-off verification scripts) takes the ws-* block fromgit show origin/main:apps/api/src/index.ts, takes the two new files, re-inlinesresolveWorkspacePortAccess's body in place of its four-line call site, and compares after stripping indentation and blank lines (import/export lines are outside the compared bodies). Run against main6d79731d5:NOand the body comparison toFalse.The only non-identical lines are the expected ones: the
export async functionwrappers,PortAccessResultand thereturn { userId, portAccessRedirect, publicPortAccess }, the four-line delegation in the caller (const access = await resolveWorkspacePortAccess(…),if (access instanceof Response) return access;, the destructuring assignment, one comment), import/export lines, theapp.use('*', workspaceSubdomainProxy)registration and its one-line comment, and the new files' header doc comments.Import mapping (25 symbols)
SAM_PROXIED_REQUEST_HEADER./services/vm-agent-container../services/vm-agent-containerWorkspaceStatus@simple-agent-manager/shared@simple-agent-manager/sharedanddrizzle-ormdrizzle-ormassertSessionUserApproved./services/signup-approval../services/signup-approvalassertTerminalTokenSessionLive./services/terminal-token-liveness../services/terminal-token-livenesscreateAuth./auth../authdrizzledrizzle-orm/d1drizzle-orm/d1eqdrizzle-ormdrizzle-ormfetchVmAgentContainer./services/vm-agent-container../services/vm-agent-containergetNodeBackendBaseUrl./services/node-agent-readiness../services/node-agent-readinessgetVmAgentContainerConfig./services/vm-agent-container../services/vm-agent-containerisExpectedWorkspacePortsUpstreamUnavailable./routes/workspaces/ports-readiness./workspaces/ports-readinessisPastHardExpiry./services/agent-sign-in/session-cap../services/agent-sign-in/session-capisWorkspacePortsListRequest./routes/workspaces/ports-readiness./workspaces/ports-readinesslog./lib/logger../lib/loggerparseWorkspaceSubdomain./lib/workspace-subdomain../lib/workspace-subdomainrecordNodeRoutingMetric./services/telemetry../services/telemetryschema./db/schema../db/schemaserializeError./lib/logger../lib/loggersignTerminalToken./services/jwt../services/jwtstripPreviewAuthCookies./lib/preview-cookies../lib/preview-cookiesverifyPortAccessToken./services/jwt../services/jwtverifyTerminalToken./services/jwt../services/jwtworkspacePortsReadinessPayload./routes/workspaces/ports-readiness./workspaces/ports-readinessworkspacePortsStateForStatus./routes/workspaces/ports-readiness./workspaces/ports-readinessIntentionally NOT included (input for slice L6 and the self-host transport slices)
The integration branch's
workspace-subdomain-proxy.tsdiffers from this PR only in:redirect: 'manual'unconditionally on both proxied fetches (main keepstargetPort !== null ? 'manual' : c.req.raw.redirect), plan item C4 / slice L6.readNodeAgentRouteRow/nodeAgentRouteFromRow/NodeAgentRouteError(one read for runtime + transport + lease port), with a new503 NODE_UNREACHABLEand anode_route_unavailableports payload.vmUrl(nodeRoute.kind === 'reverse-tunnel').isGatewayAuthorizationRequest,gatewayUnsupportedRuntimeResponse(cf-container),gatewayDecisionResponse.headers.delete('x-sam-gateway-secret')on both the container and VM paths.workspace-port-access.tson the integration branch is byte-identical to this PR's except the header comment.Validation
pnpm lint(viapnpm check:fast, exit 0)pnpm typecheck(api; rebuilt dependencies in order on main6d79731d5)pnpm test: fullapps/apivitest run, JSON reporter: success, 3,368 files, 15,022 tests, 15,018 passed, 4 skipped, 0 failed (on based65360dcd; the rebase onto6d79731d5touched no file in this diff, and the proxy tests were re-run there: 67/67)quality:file-sizesexit 0 (index.ts543 lines);quality:ast-checks0 errors and no warnings in touched files;quality:source-contract-testspass;check-file-sizes.test.ts9/9; Workers-runtime entry testsworkspace-preview-websocket,signup-approval-gate,d1-request-session,instant-sleeping-deletion-guard: 88/88Test edits are file-path only:
tests/unit/ws-proxy.test.tsand the first case oftests/unit/cf-container-runtime-contract.test.tsnow readsrc/routes/workspace-subdomain-proxy.ts.tests/integration/multi-workspace-nodes.test.tschecksws_proxy_routein the new file and adds one assertion thatindex.tsstill containsapp.use('*', workspaceSubdomainProxy), so a deleted registration still fails a test. No assertion was rewritten. No outbound-fetch inventory exists on main, so there was nothing to re-key.Staging Verification (REQUIRED for all code changes — merge-blocking)
0d75915a53b62c424b659131b4cc5fa13c98e04c; no D1 migrations applied (both databases "No migrations to apply")app.sammy.partyas the staging smoke user (token-login againstapi.sammy.party), desktop 1280x800 and mobile 375x667Staging Verification Evidence
Window granted by the PR Shepherd (feature.pr-shepherd-deps-20261111), 23:08-23:45Z. Smoke user, project Potato (
01KWHD8XS7MQ7R6KWXJYRHDVH4), default placement, no pool/credential/default changes.Unauthenticated, before vs after deploy vs production (byte comparison, sha256 prefix):
ws-<id>--3000no cookietext/html,8ea5a2d35df2, 478 Btext/html,8ea5a2d35df2, 478 B,no-store,nosniff8ea5a2d35df2, 478 Bws-<id>--3000/?port_token=bogus8ea5a2d35df28ea5a2d35df28ea5a2d35df2ws-<id>no authAuthentication required)ws-bad,ws-<id>--abcVM runtime (task
01M7BKNKNKF8K8X571W8GJBTXB, workspace01M7BKVJAZ7RRC2853K8K6163G, node01M7BKNWT0Z18462KPQSXDZWH8, Hetzner cx33 fsn1; running 23:29:08Z):READYreply.wss://ws-<id>.sammy.party/terminal/ws/multi(122 frames): prompt, keystroke echo, session reattach on reload.ws-<id>--3000(Python listener started from that terminal):/api/workspaces/:id/port-accesstoken URL →302to the bare host withSet-Cookie: sam_port_access=…; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=14400,Cache-Control: no-store,Referrer-Policy: no-referrer; then200 l2-port-okwith the cookie.sam_port_accesscookie →401page, sha8ea5a2d35df2(identical to production).PATCH ports-public {enabled:true}→ anonymous200 l2-port-ok;{enabled:false}→ anonymous401, sha8ea5a2d35df2.Instant runtime (task
01M7BM7SJTR24W1NSJX3AB21W4, workspace01M7BM7T42T712NQNYCCGZ3DA0, container node01M7BM7SY33QH7DHXGN91CZS5N; running 23:35:39Z):python3; a Node listener was used).502 {"error":"port proxy error: dial tcp 127.0.0.1:3000: connect…"}), so routing and the injected port-proxy token were accepted.302+ cookie, cookie →200 l2-port-ok, public on → anonymous200, public off →401sha8ea5a2d35df2.Cleanup: both tasks closed (workspaces removed; explicit DELETE then 404), VM node
DELETE200. D1 audit 23:38:57Z: VM node row finalized/absent, Instant nodedeleted, both workspace rows absent, both taskscompleted, zero non-deleted nodes on staging. Late audit 23:44:35Z: unchanged, zero non-deleted nodes. Staging FREE published 23:45Z.UI Compliance Checklist (Required for UI changes)
N/A: no UI changes (
apps/web,packages/ui,packages/terminaluntouched).UI Screenshot Evidence
N/A: no UI changes.
End-to-End Verification (Required for multi-component changes)
ws-*host →index.tsmiddleware chain →workspaceSubdomainProxy(routes/workspace-subdomain-proxy.ts) →resolveWorkspacePortAccess(routes/workspace-port-access.ts) for port hosts → D1 ownership (workspaces) and runtime (nodes) lookups →fetchVmAgentContainer(Instant) orfetch(getNodeBackendBaseUrl(...))(VM)workspace-proxy-ownership,workspace-proxy-port-access,workspace-proxy-cf-container-reserved-port,routes/workspace-local-forward, Workersworkspace-preview-websocket(all unchanged, passing)Data Flow Trace
See the first checkbox above; unchanged from main, only the file boundary moved.
Untested Gaps
Not exercised on staging: the Instant reserved-port
403 PORT_RESERVEDbranch and thecreating-status boot-log WebSocket exception (both moved byte-identically and covered through the Worker entry byworkspace-proxy-cf-container-reserved-port.test.tsandworkspace-proxy-ownership.test.ts). Hetzner-side absence of the deleted VM was not read directly (no provider token); D1 shows the node finalized.Post-Mortem (Required for bug fix PRs)
N/A: not a bug fix.
What broke
N/A
Root cause
N/A
Class of bug
N/A
Why it wasn't caught
N/A
Process fix included in this PR
N/A
Post-mortem file
N/A
Specialist Review Evidence (Required for agent-authored PRs)
needs-human-reviewlabel added and merge deferred to human: N/A, every reviewer completed. The label was only the marker of the owner's hold and was removed when he approved../repo-hosting-wiringfirst). LOW: the comment "Return the 302 redirect after we confirm the DB lookup passes below" inworkspace-port-access.tsnow reads oddly; kept verbatim to match main and the integration branch (pure-move rule).routes/matchesinteractive-preview-host.ts; split coherent; names/signatures match the integration branch; no scope creep. LOW:index.tsat 543 lines is a 500-800 warning (out of scope); exemption removal correct.CodeRabbit Review Evidence (Required for agent-authored PRs)
CodeRabbit Notes
Requested 2026-11-13 23:45:04Z through the trusted
coderabbit-bot-review.ymlworkflow dispatch frommain(run 43529417059, success); the label path does not fire on drafts. CodeRabbit answered at 23:45:15Z with "Action not completed — Review rate limited" (it had already posted "Review limit reached" when the draft opened at 21:06Z). No review arrived by 00:00:32Z. Outcome: no CodeRabbit review; not re-triggered. SonarCloud quality gate: passed.Exceptions (If any)
needs-human-reviewuntil the owner approved it on November 14, 2026; the task file lives on this branch instead of a direct-to-main task commit.Agent Preflight (Required)
Classification
External References
N/A: no external API or library behaviour involved; Hono middleware semantics (
app.usewith a named async handler) are unchanged from main's inline handler.Codebase Impact Analysis
apps/api/src/index.ts(block removed, imports pruned, registration added); newapps/api/src/routes/workspace-subdomain-proxy.tsandapps/api/src/routes/workspace-port-access.ts;scripts/quality/check-file-sizes.ts(exemption removed); three source-contract tests underapps/api/tests/. Every request to aws-*host passes through the moved code; requests to other hosts callnext()exactly as before. Open PRs touchingindex.ts(#2605, #2308) change only import lines and route registrations, not this block.Documentation & Specs
N/A: no docs, rules or specs cite the proxy's location in
index.ts(searchedapps/www/src/content/docs,docs/,.claude/rules,apps/api/.claude,AGENTS.md,CLAUDE.md).Constitution & Risk Check
Principle X (simplicity): pure move, no new abstraction beyond the integration branch's two functions. Principle XI: no values added or changed. Risk: every workspace request; mitigated by the mechanical body comparison, unchanged middleware order, unchanged entry-level tests, and (pending) staging parity with production for the 401 page.
Head at creation:
0d75915a53b62c424b659131b4cc5fa13c98e04c.🤖 Generated with Claude Code