diff --git a/docker-compose.yml b/docker-compose.yml index 13be6e01..3736c5ac 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -30,6 +30,8 @@ services: # Optional: Ollama server + model for the "Local (Ollama)" provider WORKSHOP_LOCAL_LLM_URL: "${WORKSHOP_LOCAL_LLM_URL:-}" WORKSHOP_LOCAL_MODEL: "${WORKSHOP_LOCAL_MODEL:-}" + # Optional: base domain for per-session dev servers (needs wildcard DNS + TLS, see docs/docker.md) + WORKSHOP_DEV_DOMAIN: "${WORKSHOP_DEV_DOMAIN:-}" volumes: # Persistent Workshop state (SQLite db, auth-token, sessions, vault, sprites) - workshop-state:/config diff --git a/docs/docker.md b/docs/docker.md index 6bf48eec..0866eee2 100644 --- a/docs/docker.md +++ b/docs/docker.md @@ -83,6 +83,17 @@ No `sshd`, no `docker exec`, no Docker socket mount. The "Open in Terminal" butt in the pane header is a *host*-side launcher (iTerm/Konsole/Windows Terminal) and is only useful for native, non-Docker installs. +## Dev servers + +A track can run a per-session dev server behind its own hostname. + +1. In the track's settings, set **Dev server command** (e.g. `npm run dev -- --port $PORT`). The server must listen on `$PORT`. +2. Set `WORKSHOP_DEV_DOMAIN` (e.g. `beta.workshop.chu.zone`). The feature is off without it. Only one Workshop instance should set it. +3. Point wildcard DNS `*.` and a wildcard TLS cert at Workshop's port 3002, preserving the `Host` header (Nginx Proxy Manager, SWAG, or Caddy with Let's Encrypt DNS-01). Cloudflare's free cert covers only one level, so with Cloudflare use a domain one level under the zone, or a paid cert. +4. Click **Dev Server** on a session. The first load shows "Starting...". A failure shows the log with Retry. The server stops when the session is deleted. + +The proxy sends `Host: 127.0.0.1:`, so Vite's host check passes, but projects that hard-code `server.hmr.clientPort` must drop it. Apps that redirect to absolute `127.0.0.1` URLs won't work through the proxy. + ## Per-user editor paths "Open in Editor" hands `` to your local editor. If you SSH into diff --git a/docs/features.md b/docs/features.md index 1df9da41..d231fbf1 100644 --- a/docs/features.md +++ b/docs/features.md @@ -254,6 +254,7 @@ A visual representation of session activity above the terminal panel. - **Nix devshell** — `flake.nix` provides Node.js 24 and tmux; `direnv allow` activates automatically - **Dev + prod simultaneously** — Dev server (`:3001`/`:5173`) and prod server (`:3002`) can run at the same time against separate databases +- **Per-session dev servers** — A track's dev command runs per session, proxied at `-.` via the **Dev Server** button (see `docs/docker.md`) - **Hot module replacement** — Vite HMR for fast UI iteration - **TypeScript strict mode** — Throughout; ESM imports; no `any` drift - **Vitest** — Test suite for application and domain logic diff --git a/docs/plans/dev-server-router-review.md b/docs/plans/dev-server-router-review.md new file mode 100644 index 00000000..d6fe2523 --- /dev/null +++ b/docs/plans/dev-server-router-review.md @@ -0,0 +1,96 @@ +# Consolidated Review: Dev Server Router + +* **Target:** `docs/plans/dev-server-router.md` (commit `ac1aab2`, branch `workshop/dev-server-router`) +* **Mode:** Consolidated, all stages (5-9), with no edits to the document between stages +* **Context given to reviewers:** `docs/docker.md`, `src/server/code-server-proxy.ts`, `src/infrastructure/code-server/code-server.ts` +* **Stage reports:** `zoom_out_report.md`, `comprehension_report.md`, `critic_report.md`, `intermediate_zoom_out_report.md`, `implementation_readiness_report.md` + +## Verdict + +**Not ready to build.** +- The architecture holds: one wildcard hostname, routed inside Workshop, a tmux-run track command, opt-in through an environment variable. No reviewer argued for replacing it. +- What fails is the detail: + - Two decisions are still open. + - The process-supervision spec has a real exit-code bug. + - The plan misses a domain file and the Nix environment flags. + - The plan never says how the new manager reaches the code that needs it. + +The Stage 8 reviewer judged which of the earlier stages' proposed fixes were worth their cost. This report follows those judgments. Where Stage 9 asked for machinery that Stage 8 rejected, the item is listed under **Contested**. + +## Verified against the code (by the orchestrator, not a reviewer) + +* **Confirmed:** `src/server/websocket.ts:68-75` authenticates every WebSocket upgrade by token alone. It never checks `Origin`. With a shared `Domain=.workshop.chu.zone` cookie, any page served from a dev host is same-site, so the browser would attach the cookie. That page could then open Workshop's terminal WebSocket and run shell commands. This turns the shared-cookie option from a privacy risk into **remote shell access for any dev app's front-end code**. See B2. +* **Refuted:** IR#5's claims that the upgrade path has no auth and that `extractToken` needs an Express `Request`. The central gate at `websocket.ts:69-75` runs first, and `extractToken(req: IncomingMessage)` already works on upgrades. +* **Refuted:** `tmux -e` needing a version check. The image ships tmux 3.3a, and `-e` needs 3.2. + +## 🔴 Blockers + +| # | Action | Sources | +|---|--------|---------| +| B1 | Decide the edge (what terminates TLS and issues `*.`) and record the final hostname scheme. Treat the DNS/certificate setup as a precondition checked before merge. | ZO#1, IC#8, Comp#1-2, D#1, IR#1, CD#11, ZO8-C5 | +| B2 | Decide auth scope. The evidence points to **per-host handoff**: a stateless HMAC ticket of (sid, expiry) keyed on the existing token, swapped for a host-only cookie. No code store and no login redirect. Once decided, delete the other branch (item 6 or item 10). | ZO#2, IC#1, D#2-3, St#3, ZO8-A2/B2, verified above | +| B3 | Fix process supervision. Stage 8 proposes the smallest fix: drop `tee`, the `__EXIT:` line and the log file. Use tmux `remain-on-exit` + `#{pane_dead_status}` for the exit code and `capture-pane` for the log tail. Write the command to a script file and run `bash ' }); + const res = await get('/', cookie()); + expect(res.status).toBe(502); + expect(res.body).toContain('<script>'); + expect(res.body).toContain('/__workshop/retry'); + }); + + it('proxies running servers, including /api, without Workshop credentials', async () => { + ensure.mockResolvedValue({ state: 'running', port: (upstream.address() as AddressInfo).port }); + const res = await get(`/api/x?token=${process.env.WORKSHOP_AUTH_TOKEN}&keep=1`, { + cookie: `${cookie().cookie}; workshop_token=zzz; app=1`, + 'x-forwarded-host': 'evil', + }); + expect(res.body).toBe('upstream'); + expect(seen?.url).toBe('/api/x?keep=1'); + expect(seen?.headers.cookie).toBe('app=1'); + expect(seen?.headers.host).toMatch(/^127\.0\.0\.1:/); + expect(seen?.headers['x-forwarded-host']).toBe(HOST); + }); + + it("passes an app's own ?token= through", async () => { + ensure.mockResolvedValue({ state: 'running', port: (upstream.address() as AddressInfo).port }); + await get('/x?token=abc&a=1', cookie()); + expect(seen?.url).toBe('/x?token=abc&a=1'); + }); + + it('answers a // path with a 4xx and keeps serving', async () => { + const res = await get('//'); + expect(res.status).toBeGreaterThanOrEqual(400); + expect(res.status).toBeLessThan(500); + expect((await get('/', {}, 'workshop.example')).body).toBe('workshop'); + }); +}); diff --git a/tests/server/dev-server-routes.test.ts b/tests/server/dev-server-routes.test.ts new file mode 100644 index 00000000..1c5190c2 --- /dev/null +++ b/tests/server/dev-server-routes.test.ts @@ -0,0 +1,71 @@ +import { describe, it, expect, beforeAll, afterAll, afterEach } from 'vitest'; +import express from 'express'; +import type { Server } from 'node:http'; +import type { Session, Track } from '@foundation/types'; +import type { SessionRepository } from '@domain/session/repository'; +import type { TrackRepository } from '@domain/track/repository'; +import { createDevServerRoutes } from '@server/dev-server-routes.js'; +import { devSid } from '@foundation/dev-sid.js'; +import { verifyDevTicket } from '@server/dev-host.js'; + +const SESSION_ID = '12345678-90ab-cdef-1234-567890abcdef'; +let track: Partial; +let session: Partial | null; + +const sessions = { findById: () => session } as unknown as SessionRepository; +const tracks = { findById: () => track } as unknown as TrackRepository; + +describe('dev-server routes', () => { + let server: Server; + let base: string; + + beforeAll(async () => { + process.env.WORKSHOP_AUTH_TOKEN = 'test-token'; + const app = express(); + app.use(createDevServerRoutes({ sessions, tracks })); + await new Promise((resolve) => { server = app.listen(0, resolve); }); + const addr = server.address(); + base = `http://127.0.0.1:${typeof addr === 'object' && addr ? addr.port : 0}`; + }); + + afterAll(() => { server.close(); }); + afterEach(() => { delete process.env.WORKSHOP_DEV_DOMAIN; }); + + async function get(headers: Record = {}): Promise<{ url: string | null }> { + const res = await fetch(`${base}/sessions/${SESSION_ID}/dev-server`, { headers }); + return (await res.json()) as { url: string | null }; + } + + function setup(devCommand?: string, deletedAt?: string): void { + track = { name: 'My Track', devCommand }; + session = { id: SESSION_ID as Session['id'], deletedAt }; + } + + it('is null when the domain env is unset', async () => { + setup('npm run dev'); + expect((await get()).url).toBeNull(); + }); + + it('is null when the track has no devCommand', async () => { + process.env.WORKSHOP_DEV_DOMAIN = 'dev.example.com'; + setup(); + expect((await get()).url).toBeNull(); + }); + + it('is null for a deleted session', async () => { + process.env.WORKSHOP_DEV_DOMAIN = 'dev.example.com'; + setup('npm run dev', '2026-01-01'); + expect((await get()).url).toBeNull(); + }); + + it('returns a signed auth url', async () => { + process.env.WORKSHOP_DEV_DOMAIN = 'dev.example.com'; + setup('npm run dev'); + const { url } = await get({ 'x-forwarded-proto': 'https, http' }); + const parsed = new URL(url ?? ''); + expect(parsed.protocol).toBe('https:'); + expect(parsed.host).toBe(`my-track-${devSid(SESSION_ID)}.dev.example.com`); + expect(parsed.pathname).toBe('/__workshop/auth'); + expect(verifyDevTicket(parsed.searchParams.get('t'), devSid(SESSION_ID))).toBe(true); + }); +});