Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(local): enable hostname HTTPS for the local stack and Vite (#6429)
Wolf Mermelsteincce67b3588df
diff --git a/.claude/skills/live-debug/SKILL.md b/.claude/skills/live-debug/SKILL.mdindex 3ffdd0fadc..75f5096ec3 100644--- a/.claude/skills/live-debug/SKILL.md+++ b/.claude/skills/live-debug/SKILL.md@@ -86,7 +86,7 @@ work. State (cookies, login) persists across agent sessions until thecontainer restarts.- The container uses host networking, so plain localhost URLs work: the app- is **http://localhost:3000/app**, the proxy `http://localhost:8090` (named+ is **http://localhost:3000/app**, the proxy `https://localhost:8090` (namedinstances remap these ports; read the stack summary).- A human can watch the browser live at **http://localhost:6080/vnc.html**(noVNC over the Xvfb display) — work in the visible window, not isolateddiff --git a/.cursor/frontend.sh b/.cursor/frontend.shindex 1d9aa2c0e9..859e24f1f1 100755--- a/.cursor/frontend.sh+++ b/.cursor/frontend.sh@@ -19,7 +19,7 @@ if ! in_pinned_nix_shell; thenfiFRONTEND_PORT=3000-PROXY_ORIGIN='http://localhost:8090'+PROXY_ORIGIN='https://localhost:8090'DEV_URL="http://localhost:${FRONTEND_PORT}/app"PID_FILE="${LOG_DIR}/frontend-dev.pid"DEV_LOG="${LOG_DIR}/frontend-dev.log"@@ -41,20 +41,28 @@ if curl -fsS --max-time 2 "${DEV_URL}" >/dev/null 2>&1; thenexit 0fi-if ! curl -fsS --max-time 3 "${PROXY_ORIGIN}/auth/health" >/dev/null 2>&1; then+if ! curl -fsS --cacert "${WORKSPACE_ROOT}/infra/local/certs/ca.pem" --max-time 3 "${PROXY_ORIGIN}/auth/health" >/dev/null 2>&1; thenecho "cursor-cloud frontend: stack is not running — run: bash .cursor/stack.sh" >&2exit 1fi: >"${DEV_LOG}"+\cd "${WORKSPACE_ROOT}"+BACKEND_ROUTES="$(cargo x frontend-proxy-routes)"+just ensure-cache-wasm+just ensure-agent-fold-wasm\cd "${WORKSPACE_ROOT}/apps/web"setsid env \PORT="${FRONTEND_PORT}" \+ NODE_EXTRA_CA_CERTS="${WORKSPACE_ROOT}/infra/local/certs/ca.pem" \+ MACRO_LOCAL_HOSTNAME="$(hostname)" \VITE_LOCAL_SERVERS=ALL \VITE_LOCAL_BACKEND_ORIGIN="same-origin" \MACRO_LOCAL_BACKEND_PROXY="${PROXY_ORIGIN}" \+ MACRO_LOCAL_BACKEND_ROUTES="${BACKEND_ROUTES}" \VITE_AI_EDITING_WORKER_URL="/ai-editing" \- bun run --bun dev >>"${DEV_LOG}" 2>&1 </dev/null &+ python3 -c 'import subprocess; child = subprocess.Popen(["node", "../../node_modules/vite/bin/vite.js", "-c", "vite.config.ts"], stdin=subprocess.PIPE); raise SystemExit(child.wait())' \+ >>"${DEV_LOG}" 2>&1 </dev/null &echo "$!" >"${PID_FILE}"# Cold starts build wasm packages before Vite binds; be patient once.diff --git a/.cursor/stack.sh b/.cursor/stack.shindex eb01c26eec..91cdc057da 100755--- a/.cursor/stack.sh+++ b/.cursor/stack.sh@@ -24,7 +24,7 @@ fi\cd "${WORKSPACE_ROOT}"if [ "${1:-}" != "--fresh" ] \- && curl -fsS --max-time 3 http://localhost:8090/auth/health >/dev/null 2>&1; then+ && curl -fsS --cacert "${WORKSPACE_ROOT}/infra/local/certs/ca.pem" --max-time 3 https://localhost:8090/auth/health >/dev/null 2>&1; thenecho "cursor-cloud stack: backend already running"elsebuild_local_stack_binariesdiff --git a/Cargo.lock b/Cargo.lockindex cffaf85c71..5156e6c63d 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -10424,6 +10424,7 @@ dependencies = ["futures","local_e2e_test_support","reqwest 0.13.4",+ "rustls 0.23.45","serde","serde_json","sqlx",diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.mdindex d8618a5371..8a67155dbc 100644--- a/apps/web/AGENTS.md+++ b/apps/web/AGENTS.md@@ -17,7 +17,7 @@ A frontend dev server runs against the **dev** backend, so this needs no local scd apps/web && PORT=3003 bun run dev # any free port in 3000-3009```-`import.meta.env.MODE === 'development'` resolves the service clients to `https://dev.macro.com` and the browser's existing dev cookies authenticate, so `http://localhost:<port>/app` loads the real workspace. Notes:+`import.meta.env.MODE === 'development'` resolves the service clients to `https://dev.macro.com` through Vite’s same-origin development proxy. Sign in on the development hostname; existing `.macro.com` cookies are separate. Vite prints `https://<hostname>:<port>/app/`; `https://localhost:<port>/app/` also works. Trust `infra/local/certs/ca.pem` once in the visiting browser (see `infra/local/certs/README.md`). `MACRO_DEV_HTTPS=false` restores HTTP for workflows that require it. Notes:- Never assume port 3000 or 3002 is yours. Check with `lsof -nP -iTCP:<port> -sTCP:LISTEN -t` and confirm the owner's worktree via `lsof -p <pid> | awk '$4=="cwd"'`. Take a free port instead of killing another session's server, and reuse one only if its cwd is this worktree.- The `.cursor/*.sh` scripts and the `run-app` skill are **Cursor Cloud** entry points. On a local machine they prompt for sudo and are the wrong tool. Only backend (Rust) changes need the local stack.diff --git a/apps/web/playwright.config.ts b/apps/web/playwright.config.tsindex 9c8f74af6e..6e4f6fc1c7 100644--- a/apps/web/playwright.config.ts+++ b/apps/web/playwright.config.ts@@ -156,6 +156,8 @@ export default defineConfig({baseURL: localE2EBaseURL ?? `http://localhost:${localE2EPort}/app`,/* Only retain traces on the failed test. See https://playwright.dev/docs/trace-viewer */trace: 'retain-on-failure',+ // Local stack proxy is HTTPS with the checked-in self-signed CA.+ ignoreHTTPSErrors: isLocalE2E,},// One set of snapshots for all platformssnapshotPathTemplate:diff --git a/apps/web/scripts/dev-https.test.ts b/apps/web/scripts/dev-https.test.tsnew file mode 100644index 0000000000..54b8fc4312--- /dev/null+++ b/apps/web/scripts/dev-https.test.ts@@ -0,0 +1,121 @@+import { execFileSync } from 'node:child_process';+import { readFileSync } from 'node:fs';+import { get, request } from 'node:https';+import { createServer, resolveConfig } from 'vite';+import { expect, it } from 'vitest';+import { devHttps } from './dev-https';++const ca = readFileSync(+ new URL('../../../infra/local/certs/ca.pem', import.meta.url)+);++it('serves HTTPS and HMR with the existing CA and detected hostname', async () => {+ const hostname = execFileSync('hostname', { encoding: 'utf8' })+ .trim()+ .toLowerCase();+ const vite = await createServer({+ configFile: false,+ appType: 'custom',+ logLevel: 'silent',+ plugins: [devHttps({})],+ optimizeDeps: { noDiscovery: true, include: [] },+ server: { host: '127.0.0.1', port: 0 },+ });+ try {+ vite.middlewares.use((_req, res) => res.end('frontend'));+ await vite.listen();+ const address = vite.httpServer?.address();+ if (!address || typeof address === 'string')+ throw new Error('Vite has no TCP listener');+ const options = { hostname: '127.0.0.1', port: address.port, ca };+ const fetchPage = (servername: string, trusted = true) =>+ new Promise<string>((resolve, reject) => {+ get(+ {+ ...options,+ servername,+ ca: trusted ? ca : [],+ path: '/app/',+ },+ (res) => {+ let body = '';+ res.setEncoding('utf8');+ res.on('data', (chunk) => {+ body += chunk;+ });+ res.on('end', () => resolve(body));+ res.on('error', reject);+ }+ ).on('error', reject);+ });+ expect(await fetchPage(hostname)).toBe('frontend');+ expect(await fetchPage('localhost')).toBe('frontend');+ await expect(fetchPage('unrelated.example')).rejects.toMatchObject({+ code: 'ERR_TLS_CERT_ALTNAME_INVALID',+ });+ await expect(fetchPage(hostname, false)).rejects.toThrow();++ // A real TLS WebSocket upgrade with Vite's browser origin/token checks.+ const protocol = await new Promise<string | undefined>(+ (resolve, reject) => {+ const req = request({+ ...options,+ servername: hostname,+ path: `/?token=${vite.config.webSocketToken}`,+ headers: {+ host: `${hostname}:${address.port}`,+ origin: `https://${hostname}:${address.port}`,+ connection: 'Upgrade',+ upgrade: 'websocket',+ 'sec-websocket-version': '13',+ 'sec-websocket-key': 'dGhlIHNhbXBsZSBub25jZQ==',+ 'sec-websocket-protocol': 'vite-hmr',+ },+ });+ req.setTimeout(3000, () =>+ req.destroy(new Error('HMR upgrade timeout'))+ );+ req.on('error', reject);+ req.on('response', (res) => {+ res.resume();+ reject(new Error(`HMR returned ${res.statusCode}`));+ });+ req.on('upgrade', (res, socket) => {+ socket.destroy();+ resolve(res.headers['sec-websocket-protocol']);+ });+ req.end();+ }+ );+ expect(protocol).toBe('vite-hmr');+ } finally {+ await vite.close();+ }+});++it.each([+ { TAURI_ENV_PLATFORM: 'linux' },+ { TAURI_DEV_HOST: '192.168.1.2' },+ { MACRO_LOCAL_BACKEND_PROXY: 'https://localhost:8090' },+ { MACRO_DEV_HTTPS: 'false' },+])('preserves HTTP for %j', async (env) => {+ const config = await resolveConfig(+ { configFile: false, plugins: [devHttps(env)] },+ 'serve'+ );+ expect(config.server.https).toBeUndefined();+});++it.each(['build', 'preview'] as const)(+ 'does not issue certificates for %s',+ async (command) => {+ const config = await resolveConfig(+ { configFile: false, plugins: [devHttps({})] },+ command === 'preview' ? 'serve' : 'build',+ 'development',+ 'development',+ command === 'preview'+ );+ expect(config.server.https).toBeUndefined();+ }+);diff --git a/apps/web/scripts/dev-https.ts b/apps/web/scripts/dev-https.tsnew file mode 100644index 0000000000..2c38f22c09--- /dev/null+++ b/apps/web/scripts/dev-https.ts@@ -0,0 +1,61 @@+import { execFileSync } from 'node:child_process';+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { fileURLToPath } from 'node:url';+import type { Plugin } from 'vite';++/** Standalone browser development shares the local stack's stable CA. */+export function devHttps(+ env: Record<string, string | undefined> = process.env+): Plugin {+ let hostname: string;+ const caDir = fileURLToPath(+ new URL('../../../infra/local/certs/', import.meta.url)+ );++ return {+ name: 'macro-dev-https',+ apply: (_config, { command, isPreview }) =>+ command === 'serve' &&+ !isPreview &&+ !env.MACRO_LOCAL_BACKEND_PROXY &&+ !env.TAURI_ENV_PLATFORM &&+ !env.TAURI_DEV_HOST &&+ env.MACRO_DEV_HTTPS !== 'false',+ config() {+ hostname = execFileSync('hostname', { encoding: 'utf8' })+ .trim()+ .toLowerCase();+ const directory = mkdtempSync(join(tmpdir(), 'macro-vite-tls-'));+ try {+ execFileSync('bash', [+ join(caDir, 'issue-host.sh'),+ directory,+ hostname,+ ]);+ return {+ server: {+ https: {+ cert: readFileSync(join(directory, 'server.pem')),+ key: readFileSync(join(directory, 'server-key.pem')),+ },+ allowedHosts: [hostname],+ },+ };+ } finally {+ rmSync(directory, { recursive: true, force: true });+ }+ },+ configureServer(server) {+ server.httpServer?.once('listening', () => {+ const address = server.httpServer?.address();+ if (!address || typeof address === 'string') return;+ server.config.logger.info(+ `\n App: https://${hostname}:${address.port}/app/\n` ++ ` Trust ${join(caDir, 'ca.pem')} once in the visiting browser.\n`+ );+ });+ },+ };+}diff --git a/apps/web/scripts/hosted-dev-proxy.test.ts b/apps/web/scripts/hosted-dev-proxy.test.tsnew file mode 100644index 0000000000..7c911e2c71--- /dev/null+++ b/apps/web/scripts/hosted-dev-proxy.test.ts@@ -0,0 +1,210 @@+import { createHash } from 'node:crypto';+import { readFileSync } from 'node:fs';+import { createServer as createHttpServer } from 'node:http';+import { get, request } from 'node:https';+import type { AddressInfo, Socket } from 'node:net';+import { createServer, resolveConfig } from 'vite';+import { afterEach, expect, it, vi } from 'vitest';+import { developmentProxyUrl } from '../src/lib/core/constant/developmentProxy';+import { devHttps } from './dev-https';+import { hostedDevProxy } from './hosted-dev-proxy';++afterEach(() => {+ vi.unstubAllEnvs();+ vi.unstubAllGlobals();+});++it('maps dev HTTP and WebSocket URLs while preserving production and OAuth hosts', () => {+ vi.stubEnv('VITE_DEV_PROXY', 'true');+ vi.stubGlobal('location', { origin: 'https://coworker:5122' });+ expect(developmentProxyUrl('https://dev-gateway.macro.com/auth')).toBe(+ 'https://coworker:5122/__macro_dev/gateway/auth'+ );+ expect(+ developmentProxyUrl('wss://services-dev.macro.com?token=fixture')+ ).toBe('wss://coworker:5122/__macro_dev/websocket?token=fixture');+ expect(+ developmentProxyUrl('https://sync-service-dev3.macroverse.workers.dev/doc')+ ).toBe('https://coworker:5122/__macro_dev/sync/doc');+ for (const url of [+ 'https://gateway.macro.com/auth',+ 'https://fusionauth-dev.macro.com/oauth2/logout',+ ]) {+ expect(developmentProxyUrl(url)).toBe(url);+ }+ vi.stubEnv('VITE_DEV_PROXY', 'false');+ expect(developmentProxyUrl('https://dev-gateway.macro.com/auth')).toBe(+ 'https://dev-gateway.macro.com/auth'+ );+});++it('forwards authenticated HTTP and WS over HTTPS, rewrites cookies, and rejects other origins', async () => {+ const sockets = new Set<Socket>();+ const upgrades: { cookie: string | undefined; path: string | undefined }[] =+ [];+ let requests = 0;+ const backend = createHttpServer((req, res) => {+ requests++;+ res.setHeader('Content-Type', 'application/json');+ res.setHeader(+ 'Set-Cookie',+ 'dev-macro-access-token=fixture; Domain=macro.com; Path=/; Secure; HttpOnly; SameSite=None'+ );+ res.end(+ JSON.stringify({+ path: req.url,+ cookie: req.headers.cookie,+ host: req.headers.host,+ })+ );+ });+ backend.on('connection', (socket) => {+ sockets.add(socket);+ socket.on('close', () => sockets.delete(socket));+ });+ backend.on('upgrade', (req, socket) => {+ upgrades.push({ cookie: req.headers.cookie, path: req.url });+ const accept = createHash('sha1')+ .update(+ `${req.headers['sec-websocket-key']}258EAFA5-E914-47DA-95CA-C5AB0DC85B11`+ )+ .digest('base64');+ socket.write(+ `HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: websocket\r\nSec-WebSocket-Accept: ${accept}\r\n\r\n`+ );+ });+ await new Promise<void>((resolve) => backend.listen(0, '127.0.0.1', resolve));+ const upstream = `http://127.0.0.1:${(backend.address() as AddressInfo).port}`;+ const vite = await createServer({+ configFile: false,+ appType: 'custom',+ logLevel: 'silent',+ plugins: [devHttps({}), hostedDevProxy({}, { gateway: upstream })],+ optimizeDeps: { noDiscovery: true, include: [] },+ server: { host: '127.0.0.1', port: 0 },+ });+ try {+ vite.middlewares.use((_req, res) => res.end('frontend'));+ await vite.listen();+ const address = vite.httpServer?.address();+ if (!address || typeof address === 'string')+ throw new Error('No Vite listener');+ const origin = `https://localhost:${address.port}`;+ const options = {+ hostname: '127.0.0.1',+ port: address.port,+ servername: 'localhost',+ ca: readFileSync(+ new URL('../../../infra/local/certs/ca.pem', import.meta.url)+ ),+ };+ const cookie = 'dev-macro-access-token=fixture';+ const fetchPage = (path: string, requestOrigin = origin) =>+ new Promise<{+ status: number | undefined;+ body: string;+ cookies: string[];+ }>((resolve, reject) => {+ get(+ {+ ...options,+ path,+ headers: {+ host: new URL(origin).host,+ origin: requestOrigin,+ cookie,+ },+ },+ (res) => {+ let body = '';+ res.setEncoding('utf8');+ res.on('data', (chunk) => {+ body += chunk;+ });+ res.on('end', () =>+ resolve({+ status: res.statusCode,+ body,+ cookies: res.headers['set-cookie'] ?? [],+ })+ );+ res.on('error', reject);+ }+ ).on('error', reject);+ });+ const response = await fetchPage(+ '/__macro_dev/gateway/auth/user/me?check=1'+ );+ expect(response.status).toBe(200);+ expect(JSON.parse(response.body)).toEqual({+ path: '/auth/user/me?check=1',+ cookie,+ host: new URL(upstream).host,+ });+ expect(response.cookies).toEqual([+ `${cookie}; Path=/; Secure; HttpOnly; SameSite=None`,+ ]);+ expect((await fetchPage('/__macro_dev/gatewayish/auth')).body).toBe(+ 'frontend'+ );+ const before = requests;+ expect(+ (+ await fetchPage(+ '/__macro_dev/gateway/auth',+ 'https://unrelated.example'+ )+ ).status+ ).toBe(403);+ expect(requests).toBe(before);++ const connect = (requestOrigin: string) =>+ new Promise<void>((resolve, reject) => {+ const req = request({+ ...options,+ path: '/__macro_dev/gateway/connection-gateway?check=1',+ headers: {+ host: new URL(origin).host,+ origin: requestOrigin,+ cookie,+ connection: 'Upgrade',+ upgrade: 'websocket',+ 'sec-websocket-version': '13',+ 'sec-websocket-key': 'dGhlIHNhbXBsZSBub25jZQ==',+ },+ });+ req.setTimeout(3000, () => req.destroy(new Error('WS timeout')));+ req.on('error', reject);+ req.on('response', (res) => {+ res.resume();+ reject(new Error(`WS status ${res.statusCode}`));+ });+ req.on('upgrade', (_res, socket) => {+ socket.destroy();+ resolve();+ });+ req.end();+ });+ await connect(origin);+ expect(upgrades).toEqual([{ cookie, path: '/connection-gateway?check=1' }]);+ await expect(connect('https://unrelated.example')).rejects.toThrow();+ expect(upgrades).toHaveLength(1);+ } finally {+ for (const socket of sockets) socket.destroy();+ await vite.close();+ await new Promise<void>((resolve) => backend.close(() => resolve()));+ }+});++it.each([+ { TAURI_ENV_PLATFORM: 'linux' },+ { MACRO_LOCAL_BACKEND_PROXY: 'https://localhost:8090' },+ { MACRO_DEV_PROXY: 'false' },+])('keeps the existing backend selection for %j', async (env) => {+ const config = await resolveConfig(+ { configFile: false, plugins: [hostedDevProxy(env)] },+ 'serve'+ );+ expect(config.server.proxy).toBeUndefined();+ expect(config.define?.['import.meta.env.VITE_DEV_PROXY']).toBeUndefined();+});diff --git a/apps/web/scripts/hosted-dev-proxy.ts b/apps/web/scripts/hosted-dev-proxy.tsnew file mode 100644index 0000000000..b3b2688504--- /dev/null+++ b/apps/web/scripts/hosted-dev-proxy.ts@@ -0,0 +1,76 @@+import type { IncomingMessage } from 'node:http';+import type { Plugin, ProxyOptions } from 'vite';+import {+ DEVELOPMENT_PROXY_PREFIX,+ DEVELOPMENT_PROXY_TARGETS,+} from '../src/lib/core/constant/developmentProxy';++/** Keep dev credentials on this hostname while forwarding to fixed hosted APIs. */+export function hostedDevProxy(+ env: Record<string, string | undefined> = process.env,+ targets: Record<string, string> = DEVELOPMENT_PROXY_TARGETS+): Plugin {+ let protocol = 'https';+ const isCrossOrigin = (req: IncomingMessage) =>+ req.headers['sec-fetch-site'] === 'cross-site' ||+ (req.headers.origin !== undefined &&+ req.headers.origin !== `${protocol}://${req.headers.host}`);++ return {+ name: 'macro-hosted-dev-proxy',+ apply: (_config, { command, mode, isPreview }) =>+ command === 'serve' &&+ (env.MODE ?? mode) === 'development' &&+ !isPreview &&+ !env.MACRO_LOCAL_BACKEND_PROXY &&+ !env.TAURI_ENV_PLATFORM &&+ !env.TAURI_DEV_HOST &&+ env.MACRO_DEV_PROXY !== 'false',+ config() {+ return {+ define: { 'import.meta.env.VITE_DEV_PROXY': true },+ server: {+ proxy: Object.fromEntries(+ Object.entries(targets).map(([name, target]) => {+ const prefix = `${DEVELOPMENT_PROXY_PREFIX}/${name}`;+ const options: ProxyOptions = {+ target,+ changeOrigin: true,+ ws: true,+ // Hosted auth cookies have Domain=macro.com. Keep Secure and+ // HttpOnly, but scope them to the visiting development host.+ cookieDomainRewrite: '',+ rewrite: (path) => {+ const rest = path.slice(prefix.length);+ return rest.startsWith('/') ? rest : `/${rest}`;+ },+ configure(proxy) {+ proxy.on('proxyReqWs', (request, req, socket) => {+ if (!isCrossOrigin(req)) return;+ request.destroy();+ socket.destroy();+ });+ },+ };+ return [`^${prefix}(?:/|\\?|$)`, options];+ })+ ),+ },+ };+ },+ configureServer(server) {+ protocol = server.config.server.https ? 'https' : 'http';+ server.middlewares.use((req, res, next) => {+ if (+ req.url?.startsWith(`${DEVELOPMENT_PROXY_PREFIX}/`) &&+ isCrossOrigin(req)+ ) {+ res.statusCode = 403;+ res.end('Cross-origin development proxy requests are not allowed');+ return;+ }+ next();+ });+ },+ };+}diff --git a/apps/web/scripts/keep-import-meta-dev.test.ts b/apps/web/scripts/keep-import-meta-dev.test.tsindex b5c191a57a..7b825c4baa 100644--- a/apps/web/scripts/keep-import-meta-dev.test.ts+++ b/apps/web/scripts/keep-import-meta-dev.test.ts@@ -27,7 +27,7 @@ describe('keepImportMetaDev', () => {keepImportMetaDev({command: 'serve',mode: 'development',- localBackendOrigin: 'http://localhost:8090',+ localBackendOrigin: 'https://localhost:8090',})).toBe(false);});diff --git a/apps/web/scripts/local-dev-server.integration.test.ts b/apps/web/scripts/local-dev-server.integration.test.tsindex 008d438adf..c506952e74 100644--- a/apps/web/scripts/local-dev-server.integration.test.ts+++ b/apps/web/scripts/local-dev-server.integration.test.ts@@ -1,5 +1,5 @@import { createHash } from 'node:crypto';-import { createServer as createHttpServer } from 'node:http';+import { createServer as createHttpServer, get as httpGet } from 'node:http';import type { AddressInfo, Socket } from 'node:net';import { createServer } from 'vite';import { expect, it } from 'vitest';@@ -15,6 +15,8 @@ it('proxies real HTTP and WebSocket requests through Vite without rewriting pathurl: req.url,method: req.method,cookie: req.headers.cookie,+ host: req.headers.host,+ forwardedHost: req.headers['x-forwarded-host'],}));});@@ -46,6 +48,7 @@ it('proxies real HTTP and WebSocket requests through Vite without rewriting pathport: 0,...localDevServer({MACRO_LOCAL_BACKEND_PROXY: target,+ MACRO_LOCAL_HOSTNAME: 'Wolf-Macro-Google',MACRO_LOCAL_BACKEND_ROUTES: '/auth,/connection-gateway,/i',}),},@@ -64,8 +67,39 @@ it('proxies real HTTP and WebSocket requests through Vite without rewriting pathurl: '/auth/health?check=1',method: 'GET',cookie: 'session=test',+ host: new URL(target).host,+ forwardedHost: new URL(origin).host,});expect(response.headers.get('set-cookie')).toContain('proxy-test=ok');+ // Use Node HTTP: fetch does not reliably preserve an explicit Host header.+ for (const host of ['wolf-macro-google', 'arbitrary-host.example']) {+ const request = (path: string) =>+ new Promise<{ status: number | undefined; body: string }>(+ (resolve, reject) => {+ httpGet(`${origin}${path}`, { headers: { host } }, (res) => {+ let body = '';+ res.setEncoding('utf8');+ res.on('data', (chunk) => {+ body += chunk;+ });+ res.on('end', () => resolve({ status: res.statusCode, body }));+ res.on('error', reject);+ }).on('error', reject);+ }+ );+ if (host === 'arbitrary-host.example') {+ expect((await request('/app/')).status).toBe(403);+ expect((await request('/auth/health')).status).toBe(403);+ continue;+ }+ expect(await request('/app/')).toEqual({ status: 200, body: 'frontend' });+ const proxied = await request('/auth/health');+ expect(proxied.status).toBe(200);+ expect(JSON.parse(proxied.body)).toMatchObject({+ host: new URL(target).host,+ forwardedHost: host,+ });+ }const telemetry = await fetch(`${origin}/i/otlp/v1/traces`, {method: 'POST',body: 'fixture',diff --git a/apps/web/scripts/local-dev-server.test.ts b/apps/web/scripts/local-dev-server.test.tsindex 5b946ef39d..d3e25f8dba 100644--- a/apps/web/scripts/local-dev-server.test.ts+++ b/apps/web/scripts/local-dev-server.test.ts@@ -17,6 +17,7 @@ describe('localDevServer', () => {const target = 'http://localhost:20109';const config = localDevServer({MACRO_LOCAL_BACKEND_PROXY: target,+ MACRO_LOCAL_HOSTNAME: 'Coworker-Dev',MACRO_LOCAL_BACKEND_ROUTES:'/auth,/connection-gateway,/websocket,/sync,/ai-editing,/i,/static-file',});@@ -49,9 +50,15 @@ describe('localDevServer', () => {).toBe(false);}for (const options of Object.values(config.proxy ?? {})) {- expect(options).toEqual({ target, ws: true, xfwd: true });+ expect(options).toEqual({+ target,+ ws: true,+ xfwd: true,+ changeOrigin: true,+ });}expect(config.hmr).toBeUndefined();+ expect(config.allowedHosts).toEqual(['coworker-dev']);});it('rejects missing or malformed routing metadata instead of proxying everything', () => {diff --git a/apps/web/scripts/local-dev-server.ts b/apps/web/scripts/local-dev-server.tsindex 0f34ae9542..037ca13972 100644--- a/apps/web/scripts/local-dev-server.ts+++ b/apps/web/scripts/local-dev-server.ts@@ -3,7 +3,7 @@ import type { ServerOptions } from 'vite';/** The stack's backend address is server-only; browsers use the Vite origin. */export function localDevServer(env: Record<string, string | undefined>-): Pick<ServerOptions, 'hmr' | 'proxy'> {+): Pick<ServerOptions, 'hmr' | 'proxy' | 'allowedHosts'> {// Browser dev follows the page's host, port and ws/wss protocol, including// reverse proxies. Native development can still supply its device host.const hmr: ServerOptions['hmr'] = env.TAURI_DEV_HOST@@ -24,11 +24,17 @@ export function localDevServer(return {hmr,+ // The launcher calls hostname; localhost and IPs remain Vite defaults.+ allowedHosts: env.MACRO_LOCAL_HOSTNAME+ ? [env.MACRO_LOCAL_HOSTNAME.toLowerCase()]+ : [],proxy: Object.fromEntries(routes.map((route) => [// Include bare WebSocket paths, but not /authentic or /sync-other.`^${route}(?:/|\\?|$)`,- { target, ws: true, xfwd: true },+ // Use the backend hostname for TLS SNI/certificate verification;+ // xfwd still records the browser's original host.+ { target, ws: true, xfwd: true, changeOrigin: true },])),};diff --git a/apps/web/src/features/auth/EmailForm.tsx b/apps/web/src/features/auth/EmailForm.tsxindex be583f6018..d3ee11cdb3 100644--- a/apps/web/src/features/auth/EmailForm.tsx+++ b/apps/web/src/features/auth/EmailForm.tsx@@ -6,9 +6,7 @@ import { Stage } from './Shared';// Construct the redirect uri to use for passwordless login.// This will send us back to the application after clicking the magic link.-// in "dev" (local) we use http otherwise https-const protocol = import.meta.hot ? 'http' : 'https';-const REDIRECT_URI = `${protocol}://${window.location.host}/app`;+const REDIRECT_URI = `${window.location.origin}/app`;async function isPasswordLogin(email?: string | null) {if (!email) return false;diff --git a/apps/web/src/features/auth/useSsoLogin.ts b/apps/web/src/features/auth/useSsoLogin.tsindex e36d1f76b9..fba9763240 100644--- a/apps/web/src/features/auth/useSsoLogin.ts+++ b/apps/web/src/features/auth/useSsoLogin.ts@@ -11,6 +11,7 @@ import { invalidateAllAfterLogin } from '@queries/auth/user-info';import { authServiceClient } from '@service-auth/client';import { useLocation } from '@solidjs/router';import { invoke } from '@tauri-apps/api/core';+import { DEVELOPMENT_PROXY_PREFIX } from '../../lib/core/constant/developmentProxy';export function useSsoLogin(opts?: { signupMode?: boolean }) {const analytics = useAnalytics();@@ -35,7 +36,12 @@ export function useSsoLogin(opts?: { signupMode?: boolean }) {if (referral_code) authUrl.searchParams.set('referral_code', referral_code);- if (isNativeMobilePlatform()) {+ // The hosted OAuth callback sets cookies on macro.com. A proxied browser+ // needs the existing session-code handoff to establish cookies locally.+ if (+ isNativeMobilePlatform() ||+ authUrl.pathname.startsWith(`${DEVELOPMENT_PROXY_PREFIX}/`)+ ) {authUrl.searchParams.set('is_mobile', 'true');}diff --git a/apps/web/src/lib/core/constant/developmentProxy.ts b/apps/web/src/lib/core/constant/developmentProxy.tsnew file mode 100644index 0000000000..cb3ec6e002--- /dev/null+++ b/apps/web/src/lib/core/constant/developmentProxy.ts@@ -0,0 +1,32 @@+/** Fixed upstreams for the standalone Vite development proxy. */+export const DEVELOPMENT_PROXY_TARGETS = {+ gateway: 'https://dev-gateway.macro.com',+ websocket: 'https://services-dev.macro.com',+ static: 'https://static-file-service-dev.macro.com',+ pdf: 'https://pdf-service-dev.macro.com',+ sync: 'https://sync-service-dev3.macroverse.workers.dev',+ editing: 'https://ai-editing-worker-dev.macroverse.workers.dev',+} as const;++export const DEVELOPMENT_PROXY_PREFIX = '/__macro_dev';++/** Keep hosted development APIs on the page origin, including workers and WS. */+export function developmentProxyUrl(url: string): string {+ if (+ (import.meta.env.VITE_DEV_PROXY !== true &&+ import.meta.env.VITE_DEV_PROXY !== 'true') ||+ !globalThis.location?.origin+ )+ return url;+ const parsed = new URL(url);+ const httpOrigin = parsed.origin.replace(/^ws/, 'http');+ const target = Object.entries(DEVELOPMENT_PROXY_TARGETS).find(+ ([, origin]) => origin === httpOrigin+ );+ if (!target) return url;+ const pageOrigin = parsed.protocol.startsWith('ws')+ ? globalThis.location.origin.replace(/^http/, 'ws')+ : globalThis.location.origin;+ const path = parsed.pathname === '/' ? '' : parsed.pathname;+ return `${pageOrigin}${DEVELOPMENT_PROXY_PREFIX}/${target[0]}${path}${parsed.search}${parsed.hash}`;+}diff --git a/apps/web/src/lib/core/constant/servers.ts b/apps/web/src/lib/core/constant/servers.tsindex 3470722f7c..a2c94434f1 100644--- a/apps/web/src/lib/core/constant/servers.ts+++ b/apps/web/src/lib/core/constant/servers.ts@@ -1,3 +1,5 @@+import { developmentProxyUrl } from './developmentProxy';+const serverHostLocal: Servers = {'auth-service': 'http://localhost:8080','auth-logout': 'http://localhost:3000', // TODO: make work with local fusionauth later@@ -33,7 +35,7 @@ const authLogoutUrl =? 'https://fusionauth-dev.macro.com/oauth2/logout?client_id=eb75fe7a-0ef1-4186-96d9-cc62cfb1d10c&tenantId=5e13f524-8d32-0454-81f8-061936256aa4': 'https://auth.macro.com/oauth2/logout?client_id=75409999-7dc4-4241-b73b-a51818c3a71c&tenantId=a3e53c3d-8d6a-3e92-d64c-fa3bf30a60be';-const serverHostRemote = {+const directServerHostRemote = {'auth-service': `${gatewayHost}/auth`,'auth-logout': authLogoutUrl,'pdf-service': `https://pdf-service${devServerSuffix}.macro.com`,@@ -53,7 +55,14 @@ const serverHostRemote = {preview: `${gatewayHost}/preview`,} as const;-type Servers = Record<keyof typeof serverHostRemote, string>;+type Servers = Record<keyof typeof directServerHostRemote, string>;++const serverHostRemote = Object.fromEntries(+ Object.entries(directServerHostRemote).map(([name, url]) => [+ name,+ developmentProxyUrl(url),+ ])+) as Servers;// Single-origin local backend: when the xtask orchestrator's reverse proxy is// in use it sets VITE_LOCAL_BACKEND_ORIGIN to the proxy origin, and the whole@@ -169,8 +178,12 @@ const syncServiceHostLocal = {} as const;const syncServiceHostRemote = {- worker: `https://sync-service${syncServiceSuffix}.macroverse.workers.dev`,- ws: `wss://sync-service${syncServiceSuffix}.macroverse.workers.dev`,+ worker: developmentProxyUrl(+ `https://sync-service${syncServiceSuffix}.macroverse.workers.dev`+ ),+ ws: developmentProxyUrl(+ `wss://sync-service${syncServiceSuffix}.macroverse.workers.dev`+ ),} as const;function selectSyncServiceHost():diff --git a/apps/web/src/lib/service-clients/ai-editing-worker/client.ts b/apps/web/src/lib/service-clients/ai-editing-worker/client.tsindex 0fa1f18273..99bffe6ed3 100644--- a/apps/web/src/lib/service-clients/ai-editing-worker/client.ts+++ b/apps/web/src/lib/service-clients/ai-editing-worker/client.ts@@ -5,6 +5,7 @@ import { MACRO_AGENT_NAME } from '@core/constant/macroAgent';import { Telemetry } from '@macro-inc/observability';import { getDocumentPermissionToken } from '@service-storage/client';import { createSignal } from 'solid-js';+import { developmentProxyUrl } from '../../core/constant/developmentProxy';// Full-URL override (scheme included) for pointing at a local wrangler dev// worker, e.g. VITE_AI_EDITING_WORKER_URL=http://localhost:8788 bun run dev@@ -13,9 +14,11 @@ const overrideUrl: string | undefined = import.meta.envconst AI_EDITING_WORKER_HOST =overrideUrl?.replace(/\/$/, '') ??- (import.meta.env.MODE === 'development'- ? 'https://ai-editing-worker-dev.macroverse.workers.dev'- : 'https://ai-editing-worker.macroverse.workers.dev');+ developmentProxyUrl(+ import.meta.env.MODE === 'development'+ ? 'https://ai-editing-worker-dev.macroverse.workers.dev'+ : 'https://ai-editing-worker.macroverse.workers.dev'+ );/*** Model fallback chains per worker role. Mirrors the chains the backenddiff --git a/apps/web/vite.base.ts b/apps/web/vite.base.tsindex 3d8c077e48..d732e6ddb1 100644--- a/apps/web/vite.base.ts+++ b/apps/web/vite.base.ts@@ -10,6 +10,8 @@ import wasm from 'vite-plugin-wasm';import tsconfigpaths from 'vite-tsconfig-paths';// @ts-ignoreimport { version } from './package.json';+import { devHttps } from './scripts/dev-https';+import { hostedDevProxy } from './scripts/hosted-dev-proxy';import { keepImportMetaDev } from './scripts/keep-import-meta-dev';import { localDevServer } from './scripts/local-dev-server';@@ -84,6 +86,8 @@ export const createAppViteConfig = (): UserConfigFn => {},},plugins: [+ devHttps(),+ hostedDevProxy(),// solidDevtools({ autoname: true }),solid(),wasm(),diff --git a/crates/agent_preview/src/domain/service.rs b/crates/agent_preview/src/domain/service.rsindex eee1b6b241..0eb03ce1a8 100644--- a/crates/agent_preview/src/domain/service.rs+++ b/crates/agent_preview/src/domain/service.rs@@ -121,8 +121,8 @@ impl Settings {let key: Vec<_> = self.host_key.split_whitespace().collect();let app = url::Url::parse(&self.app_origin).map_err(|_| PreviewError::Invalid)?;let app_host = app.host_str().ok_or(PreviewError::Invalid)?;- let local =- self.domain == "preview.localhost" && app.scheme() == "http" && app_host == "localhost";+ let local = self.domain == "preview.localhost"+ && (app.scheme() == "https" || (app.scheme() == "http" && app_host == "localhost"));if !host(&self.domain)|| !host(&self.ssh_host)|| self.ssh_port == 0@@ -133,8 +133,8 @@ impl Settings {// Neither may sit under the other: every non-gateway cookie is// forwarded upstream, so a shared parent hands the app's cookies to// agent-controlled code. The local stack is the deliberate exception- // (`preview.localhost` under `localhost`), where the app origin is- // cleartext loopback and sets nothing worth stealing.+ // (`preview.localhost` under `localhost`), including the development+ // CA's HTTPS listener. Local stacks may also use a machine hostname.|| app_host.ends_with(&format!(".{}", self.domain))|| (!local && self.domain.ends_with(&format!(".{app_host}")))|| (app.scheme() != "https" && !local)diff --git a/crates/agent_preview/src/domain/service/test.rs b/crates/agent_preview/src/domain/service/test.rsindex 9ad11fd70e..3fab21839d 100644--- a/crates/agent_preview/src/domain/service/test.rs+++ b/crates/agent_preview/src/domain/service/test.rs@@ -189,15 +189,30 @@ async fn stopping_a_preview_does_not_bypass_the_creation_interval() {service.share(identity(), 3000).await.unwrap();}#[test]-fn only_local_stack_accepts_loopback_http_handoff_and_docker_ssh_fallback() {+fn local_stack_accepts_https_handoff_and_loopback_http_with_docker_ssh_fallback() {let (service, _, _) = fixture(2222);let mut settings = service.settings().clone();settings.domain = "preview.localhost".into();- settings.app_origin = "http://localhost:3000".into();settings.local_ssh_fallback = true;- assert!(settings.validate().is_ok());- settings.app_origin = "http://macro.test".into();- assert!(settings.validate().is_err());- settings.app_origin = "https://macro.test".into();+ for origin in [+ "http://localhost:3000",+ "https://localhost:8090",+ "https://coworker-dev:23109",+ "https://coworker-dev.local:23109",+ ] {+ settings.app_origin = origin.into();+ assert!(settings.validate().is_ok(), "{origin}");+ }+ for origin in [+ "http://coworker-dev:3000",+ "https://Coworker-Dev:23109",+ "https://preview.localhost:8090",+ "https://app.preview.localhost:8090",+ ] {+ settings.app_origin = origin.into();+ assert!(settings.validate().is_err(), "{origin}");+ }+ settings.app_origin = "https://coworker-dev:23109".into();+ settings.domain = "preview.example.test".into();assert!(settings.validate().is_err());}diff --git a/crates/integration_tests/local_e2e/Cargo.toml b/crates/integration_tests/local_e2e/Cargo.tomlindex 7f63ec9d28..af2f8e84fc 100644--- a/crates/integration_tests/local_e2e/Cargo.toml+++ b/crates/integration_tests/local_e2e/Cargo.toml@@ -10,6 +10,7 @@ bot_token = { path = "../../bot_token" }futures = { workspace = true }local_e2e_test_support = { path = "../../local_e2e_test_support" }reqwest = { workspace = true }+rustls = { workspace = true }serde = { workspace = true }serde_json = { workspace = true }tokio = { workspace = true, features = ["time"] }diff --git a/crates/integration_tests/local_e2e/tests/bot_entity_access.rs b/crates/integration_tests/local_e2e/tests/bot_entity_access.rsindex f9622161e8..fbc9b0a6b5 100644--- a/crates/integration_tests/local_e2e/tests/bot_entity_access.rs+++ b/crates/integration_tests/local_e2e/tests/bot_entity_access.rs@@ -1,3 +1,6 @@+#[path = "support/http.rs"]+mod http;+use anyhow::{Context, ensure};use local_e2e_test_support::{LocalE2eConfig, LocalE2eServices};use reqwest::{Client, StatusCode};@@ -245,7 +248,7 @@ impl ScopedBotFixture {Ok(Self {pool,services,- http: Client::new(),+ http: http::http_client()?,macro_user_uuid,acting_user_id,fusion_user_id,diff --git a/crates/integration_tests/local_e2e/tests/channel_mutations.rs b/crates/integration_tests/local_e2e/tests/channel_mutations.rsindex 26a5dd30df..ba8669f912 100644--- a/crates/integration_tests/local_e2e/tests/channel_mutations.rs+++ b/crates/integration_tests/local_e2e/tests/channel_mutations.rs@@ -1,3 +1,6 @@+#[path = "support/http.rs"]+mod http;+use std::time::Duration;use anyhow::{Context, ensure};@@ -13,11 +16,14 @@ use reqwest::{Client, Method, Response};use serde::Deserialize;use serde_json::{Value, json};use sqlx::{PgPool, postgres::PgPoolOptions};+#[path = "support/websocket.rs"]+mod websocket;use tokio::net::TcpStream;use tokio::time::{Instant, timeout};use tokio_tungstenite::tungstenite::{Error as WebsocketError, Message as WebsocketMessage};-use tokio_tungstenite::{MaybeTlsStream, WebSocketStream, connect_async};+use tokio_tungstenite::{MaybeTlsStream, WebSocketStream};use uuid::Uuid;+use websocket::connect_async;const WEBSOCKET_TIMEOUT: Duration = Duration::from_secs(10);const NOTIFICATION_TIMEOUT: Duration = Duration::from_secs(30);@@ -138,7 +144,7 @@ impl ChannelContractContext {async fn load() -> anyhow::Result<Self> {let world = TestWorld::load()?;let api = ChannelApiClient::from_config(&world.config, &world.services);- let http = Client::new();+ let http = http::http_client()?;let pool = connect_db(&world.config).await?;let actor = world.seed.smoke_user()?.clone();let actor_token = world.token_for(&actor)?;diff --git a/crates/integration_tests/local_e2e/tests/channel_websocket.rs b/crates/integration_tests/local_e2e/tests/channel_websocket.rsindex fb9889c481..191771a9cd 100644--- a/crates/integration_tests/local_e2e/tests/channel_websocket.rs+++ b/crates/integration_tests/local_e2e/tests/channel_websocket.rs@@ -1,3 +1,6 @@+#[path = "support/http.rs"]+mod http;+use std::time::Duration;use anyhow::{Context, ensure};@@ -7,9 +10,11 @@ use local_e2e_test_support::{};use serde::Deserialize;use serde_json::{Value, json};+#[path = "support/websocket.rs"]+mod websocket;use tokio::time::{Instant, timeout};-use tokio_tungstenite::connect_async;use tokio_tungstenite::tungstenite::{Error as WebsocketError, Message as WebsocketMessage};+use websocket::connect_async;const WEBSOCKET_TIMEOUT: Duration = Duration::from_secs(10);@@ -39,7 +44,7 @@ async fn channel_message_posts_to_http_and_delivers_to_websocket() -> anyhow::Relet nonce = format!("rust-local-e2e-{}", uuid_like_nonce());let content = format!("Rust local E2E websocket delivery {nonce}");- let http = reqwest::Client::new();+ let http = http::http_client()?;let post_response = http.post(services.post_channel_message_url(&channel.channel_id)).bearer_auth(&token)diff --git a/crates/integration_tests/local_e2e/tests/support/http.rs b/crates/integration_tests/local_e2e/tests/support/http.rsnew file mode 100644index 0000000000..b4bdcef89c--- /dev/null+++ b/crates/integration_tests/local_e2e/tests/support/http.rs@@ -0,0 +1,7 @@+const LOCAL_CA: &[u8] = include_bytes!("../../../../../infra/local/certs/ca.pem");++pub fn http_client() -> anyhow::Result<reqwest::Client> {+ Ok(reqwest::Client::builder()+ .add_root_certificate(reqwest::Certificate::from_pem(LOCAL_CA)?)+ .build()?)+}diff --git a/crates/integration_tests/local_e2e/tests/support/websocket.rs b/crates/integration_tests/local_e2e/tests/support/websocket.rsnew file mode 100644index 0000000000..5557c44d1b--- /dev/null+++ b/crates/integration_tests/local_e2e/tests/support/websocket.rs@@ -0,0 +1,30 @@+use std::sync::Arc;++use rustls::pki_types::{CertificateDer, pem::PemObject};+use tokio::net::TcpStream;+use tokio_tungstenite::{Connector, MaybeTlsStream, WebSocketStream};++pub async fn connect_async(+ url: &str,+) -> anyhow::Result<(+ WebSocketStream<MaybeTlsStream<TcpStream>>,+ tokio_tungstenite::tungstenite::handshake::client::Response,+)> {+ let mut roots = rustls::RootCertStore::empty();+ roots.add(CertificateDer::from_pem_slice(include_bytes!(+ "../../../../../infra/local/certs/ca.pem"+ ))?)?;+ let config = rustls::ClientConfig::builder_with_provider(+ rustls::crypto::aws_lc_rs::default_provider().into(),+ )+ .with_safe_default_protocol_versions()?+ .with_root_certificates(roots)+ .with_no_client_auth();+ Ok(tokio_tungstenite::connect_async_tls_with_config(+ url,+ None,+ false,+ Some(Connector::Rustls(Arc::new(config))),+ )+ .await?)+}diff --git a/crates/lexical_client/src/lib.rs b/crates/lexical_client/src/lib.rsindex 5a14244dec..4d00456c90 100644--- a/crates/lexical_client/src/lib.rs+++ b/crates/lexical_client/src/lib.rs@@ -14,11 +14,26 @@ impl LexicalClient {let mut headers = reqwest::header::HeaderMap::new();headers.insert(INTERNAL_ACCESS_HEADER, internal_auth_key.parse().unwrap());- let client = reqwest::Client::builder()- .default_headers(headers)- .build()- .unwrap();+ let client = {+ let mut builder = reqwest::Client::builder().default_headers(headers);+ if is_local_https(&url) {+ let ca = reqwest::Certificate::from_pem(include_bytes!(+ "../../../infra/local/certs/ca.pem"+ ))+ .expect("checked-in local CA must be valid PEM");+ builder = builder.add_root_certificate(ca);+ }+ builder.build().unwrap()+ };Self { url, client }}}++fn is_local_https(url: &str) -> bool {+ url.starts_with("https://localhost:")+ || url.starts_with("https://localhost/")+ || url == "https://localhost"+ || url.starts_with("https://127.0.0.1:")+ || url.starts_with("https://127.0.0.1/")+}diff --git a/crates/sync_service_client/src/lib.rs b/crates/sync_service_client/src/lib.rsindex a3729a42e4..f402d151e7 100644--- a/crates/sync_service_client/src/lib.rs+++ b/crates/sync_service_client/src/lib.rs@@ -21,11 +21,26 @@ impl SyncServiceClient {let mut headers = reqwest::header::HeaderMap::new();headers.insert(INTERNAL_ACCESS_HEADER, internal_auth_key.parse().unwrap());- let client = reqwest::Client::builder()- .default_headers(headers)- .build()- .unwrap();+ let client = {+ let mut builder = reqwest::Client::builder().default_headers(headers);+ if is_local_https(&url) {+ let ca = reqwest::Certificate::from_pem(include_bytes!(+ "../../../infra/local/certs/ca.pem"+ ))+ .expect("checked-in local CA must be valid PEM");+ builder = builder.add_root_certificate(ca);+ }+ builder.build().unwrap()+ };Self { url, client }}}++fn is_local_https(url: &str) -> bool {+ url.starts_with("https://localhost:")+ || url.starts_with("https://localhost/")+ || url == "https://localhost"+ || url.starts_with("https://127.0.0.1:")+ || url.starts_with("https://127.0.0.1/")+}diff --git a/docs/AGENT_GUIDE/README.md b/docs/AGENT_GUIDE/README.mdindex caea37a962..823e533f8e 100644--- a/docs/AGENT_GUIDE/README.md+++ b/docs/AGENT_GUIDE/README.md@@ -18,5 +18,21 @@ verified live against a local stack (`just run_local`).| [observability.md](observability.md) | Correlating a UI action to backend traces/logs with the Grafana MCP |Local stack conventions used in examples: frontend `http://localhost:<fe>/app`, backend proxy-`http://localhost:<be>`, Mailpit `http://localhost:<mp>` (ports come from the `--instance`;+`https://localhost:<be>` (checked-in self-signed cert; trust `infra/local/certs/ca.pem`), Mailpit `http://localhost:<mp>` (ports come from the `--instance`;e.g. the `lgtm` instance uses 27910 / 27909 / 27908).++For remote browser testing, trust `infra/local/certs/ca.pem` and open the+printed `https://<hostname>:<proxy-port>/app/` URL. The launcher calls `hostname`+and includes it in both the generated certificate and Vite's allowed hosts.+Caddy forwards frontend assets and HMR to Vite while routing API and backend+WebSockets directly. No Tailscale setup is required; the browser needs network+access to that hostname and port. Plain HTTP on a remote hostname cannot retain+secure login cookies.++Standalone `bun run dev` uses the same CA and serves HTTPS directly through+Vite. Hosted dev API and WebSocket requests use `/__macro_dev/` on the page+origin, with auth cookies scoped to that hostname. Use email-code sign-in; the+hosted Google/SSO redirect allowlist does not include arbitrary hostnames.+Email magic links retain the page's HTTP or HTTPS scheme and port.+On allowed OAuth origins such as `https://localhost`, standalone Vite uses the+session-code handoff to establish cookies on the local hostname after SSO.diff --git a/docs/CURSOR_CLOUD.md b/docs/CURSOR_CLOUD.mdindex 912b98ea28..1ec8b12e97 100644--- a/docs/CURSOR_CLOUD.md+++ b/docs/CURSOR_CLOUD.md@@ -32,7 +32,8 @@ initial database and test envs; apply new migrations as needed. UseFollow the [run-app skill](../.claude/skills/run-app/SKILL.md) for the full browserwalkthrough, frontend restarts, and login troubleshooting.-- App: <http://localhost:3000/app>; backend proxy: <http://localhost:8090>.+- App: <http://localhost:3000/app>; backend proxy: <https://localhost:8090>+ (self-signed; trust `infra/local/certs/ca.pem`).These URLs are inside the VM, not reachable from the user's laptop.- `stack.sh` leaves a healthy backend running. After Rust edits, use `rebuild.sh`:it builds Nix binaries and remounts them via `just stack update --binaries-dir`,diff --git a/docs/RUNNING_LOCALLY.md b/docs/RUNNING_LOCALLY.mdindex c15638aa9a..354d450337 100644--- a/docs/RUNNING_LOCALLY.md+++ b/docs/RUNNING_LOCALLY.md@@ -66,7 +66,24 @@ cd apps/webbun run dev```-The first run, or a run after a wasm version change, may build wasm packages. Vite prints a local URL when it is ready.+The first run, or a run after a wasm version change, may build wasm packages.+Vite detects your hostname and prints `https://<hostname>:3000/app/` when ready+(`PORT` overrides the port). It generates a certificate with the same stable+development CA as `just local`; trust `infra/local/certs/ca.pem` once on the+machine running the browser. See the [certificate README](../infra/local/certs/README.md).+The visiting machine must resolve the hostname and reach that port. No Docker+proxy or Tailscale is needed. Vite forwards hosted development API and WebSocket+requests through `/__macro_dev/` on this same origin, so arbitrary machine+hostnames do not need to be added to the deployed CORS allowlist. Authentication+cookies are scoped to the visiting hostname; sign in with an email code on that+hostname rather than relying on an existing `.macro.com` cookie. Google/SSO+redirects still use the hosted authentication service’s redirect allowlist, which+does not currently include arbitrary development hostnames.++Use `MACRO_DEV_HTTPS=false bun run dev` for an HTTP-only workflow. Tauri and the+local stack's internal Vite server keep using HTTP automatically; the stack+provides HTTPS through its proxy. Builds and preview servers are unchanged.+`MACRO_DEV_PROXY=false` opts out of the hosted API proxy.## Run the local stack@@ -113,6 +130,8 @@ This command:When startup finishes, the command prints the frontend URL and the important service URLs.+The reverse proxy is HTTPS at `https://localhost:8090` (or the instance's proxy port) using a generated machine certificate signed by the checked-in development CA. Trust `infra/local/certs/ca.pem` once so the browser accepts it; see that directory's README. Local Caddy also reflects any `Origin` (wildcard CORS) so `https://` and `*.localhost` frontends can call the proxy.+Open the frontend URL in your browser.The local environment supplies both `LOCAL_AWS_URL` (the container endpoint)@@ -122,6 +141,11 @@ upload attempts `localhost:4566` on a named instance, rebuild the service andreload its generated environment; named instances publish storage on their ownport.+If LocalStack loses its temporary resources after a restart, restore missing+buckets, queues, tables, and keys without resetting Postgres or volumes:+`cargo x localstack-provision --instance <name>`. Include `--port-base` if the+instance uses an explicit port base. This restores resources, not lost objects.+The stack does not create accounts in advance. Passwordless login creates a useron demand. Register with any email address. FusionAuth sends you a one-time codeby email. That email lands in **Mailpit** at http://localhost:8025, not in a real@@ -250,12 +274,32 @@ infra/local/generated/<instance>### Access a remote dev server through one URL-`run_local` and `run_dev` serve API requests and backend WebSockets through Vite,-so the browser needs only the frontend port. For example, forward a remote-instance's frontend with `ssh -N -L 3000:127.0.0.1:20110 your-dev-host`, then open-`http://localhost:3000/app/`. A WebSocket-capable reverse proxy can instead expose-that frontend under a different hostname/port, including HTTPS. Vite HMR follows-the page's origin; no separate HMR or backend port forward is needed.+`just local` (the `run_local` alias) and `run_dev` call `hostname`, add that+name to Vite's allowed hosts, and issue a certificate for it using the stable+CA in `infra/local/certs`. Startup prints `https://<hostname>:<proxy-port>/app/`.+Caddy serves backend routes directly and forwards frontend assets and HMR to+Vite, so the browser only needs the HTTPS proxy port.+Login fallback redirects, Pipedream origins, MCP callbacks, and file permalinks+use that same HTTPS origin for attached local stacks.+If your host firewall blocks Docker-to-host traffic, allow the instance's+Docker network to reach the Vite port through `host.docker.internal`.+Startup verifies `/app/` through the HTTPS proxy before printing “ready”;+a listening Vite port alone is insufficient. A 502 with a proxy log such as+`dial tcp <host-gateway>:<vite-port>: i/o timeout` indicates this firewall path+is blocked. Firewall rules must cover the current instance's Docker network+and frontend port, which can differ between instances.++Trust `infra/local/certs/ca.pem` in the visiting browser once (see the+[certificate README](../infra/local/certs/README.md)), then open that URL.+The visiting machine must resolve the hostname and reach the proxy port over+your network. Tailscale is not required. The generated certificate also covers+`localhost`, `*.localhost`, `127.0.0.1`, and `::1`. Other aliases require a+matching certificate and a Vite allowlist entry; arbitrary names are not+accepted automatically.++An SSH forward to the HTTP Vite port still works for localhost-only access:+`ssh -N -L 3000:127.0.0.1:20110 your-dev-host`, then open+`http://localhost:3000/app/`. HMR follows the page's host, port, and protocol.The launcher sets `VITE_LOCAL_BACKEND_ORIGIN=same-origin` and supplies Vite'sserver-only `MACRO_LOCAL_BACKEND_PROXY` and `MACRO_LOCAL_BACKEND_ROUTES` from the@@ -266,6 +310,10 @@ these variables still uses hosted services; `TAURI_DEV_HOST` remains an explicitnative HMR override. Keep local dev stacks private: same-origin routing does notadd authentication or make passwordless local login safe to publish.+The launcher sets `NODE_EXTRA_CA_CERTS` for Vite so its HTTP and WebSocket+forwarding verifies the backend certificate. Plain HTTP on a remote hostname+cannot retain the app's secure login cookies; use the printed HTTPS URL.+The stack launches Vite directly with Node (available in the Nix shell), becauseBun's Node HTTP compatibility currently hangs on Vite's proxied WebSocketupgrades. Bun is still used for dependency installation and builds.diff --git a/infra/local/certs/README.md b/infra/local/certs/README.mdnew file mode 100644index 0000000000..8963ad5214--- /dev/null+++ b/infra/local/certs/README.md@@ -0,0 +1,53 @@+# Local TLS materials++Development certificate authority and localhost fixtures for the local proxy.+`just local` / `just stack up` call `hostname` and generate a leaf certificate+under `infra/local/generated/<instance>/proxy/certs/`. Caddy mounts that directory+and serves `server.pem` + `server-key.pem`. The certificate covers the detected+hostname, `localhost`, `*.localhost`, and loopback IPs. The CA stays unchanged+between starts, so coworkers only need to trust it once; Tailscale is optional.++Standalone `bun run dev` in `apps/web` uses this same CA and certificate+generator. Vite serves HTTPS directly and prints the hostname URL. Its leaf+certificate is generated in a temporary directory, loaded into memory, and+removed from disk; restarting Vite does not require trusting a new CA.++These keys are not secrets. Anyone with the repo can mint a matching cert;+do not reuse them outside local development.++## Trust the CA (once per machine)++Trust the CA on the machine running the browser:++```bash+# macOS+sudo security add-trusted-cert -d -r trustRoot \+ -k /Library/Keychains/System.keychain infra/local/certs/ca.pem++# Linux (Debian/Ubuntu)+sudo cp infra/local/certs/ca.pem /usr/local/share/ca-certificates/macro-local-ca.crt+sudo update-ca-certificates+```++Firefox may use its own certificate store: Settings → Privacy & Security →+Certificates → View Certificates → Authorities → Import `ca.pem`, then enable+trust for identifying websites. Restart the browser after changing trust.++`curl` against the proxy can pass `--cacert infra/local/certs/ca.pem` instead.++## Issue a leaf manually++```bash+bash infra/local/certs/issue-host.sh /tmp/macro-certs "$(hostname)"+```++This preserves the CA. The generated directory contains the certificate and key.++## Regenerate the CA and localhost fixtures++This replaces the CA; everyone who trusted the previous CA must import it again.+Normal stack startup does not run this command.++```bash+bash infra/local/certs/generate.sh+```diff --git a/infra/local/certs/ca-key.pem b/infra/local/certs/ca-key.pemnew file mode 100644index 0000000000..78524ca1b9--- /dev/null+++ b/infra/local/certs/ca-key.pem@@ -0,0 +1,5 @@+-----BEGIN PRIVATE KEY-----+MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgXhPNC1D41f3EIJmU+ZN2WyWMYMY2xeTIITk19BRLUkEmhRANCAAT7MkEVKMS5Vuq1XE8+spfR4irZo7fR+9DkH5idOBPw4wCgha4OHBmt6owoWqgENQuHOGAqb14j2mUiUrvx/anxr+-----END PRIVATE KEY-----diff --git a/infra/local/certs/ca.pem b/infra/local/certs/ca.pemnew file mode 100644index 0000000000..8a0e91a764--- /dev/null+++ b/infra/local/certs/ca.pem@@ -0,0 +1,11 @@+-----BEGIN CERTIFICATE-----+MIIBlzCCAT2gAwIBAgIURgeGiABpfbvWllxTTVIJlSQYhlYwCgYIKoZIzj0EAwIw+GTEXMBUGA1UEAwwOTWFjcm8gTG9jYWwgQ0EwHhcNMjYwOTE1MTg1NDA4WhcNMzYw+OTEyMTg1NDA4WjAZMRcwFQYDVQQDDA5NYWNybyBMb2NhbCBDQTBZMBMGByqGSM49+AgEGCCqGSM49AwEHA0IABPsyQRUoxLlW6rVcTz6yl9HiKtmjt9H0OQfmJ04E/DjA+KCFrg4cGa3qjChaqAQ1C4c4YCpvXiPaZSJSu/H9qfGujYzBhMB0GA1UdDgQWBBQI+tS4N4AWuKnLNfNdsrnYyOD1ZsDAfBgNVHSMEGDAWgBQItS4N4AWuKnLNfNdsrnYy+OD1ZsDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAKBggqhkjOPQQD+AgNIADBFAiEA5LBE8x7as/CnEEwy6V+l1QtmlBvbqxOYDhGerE4ZpywCIGRJM9PA+mKyz+QSwPQeeXOGbeDk/AeiQ+Gyhf4sk2Pl5+-----END CERTIFICATE-----diff --git a/infra/local/certs/generate.sh b/infra/local/certs/generate.shnew file mode 100755index 0000000000..68f5b853d7--- /dev/null+++ b/infra/local/certs/generate.sh@@ -0,0 +1,30 @@+#!/usr/bin/env bash+# Regenerate the local-dev CA and the localhost server certificate.+# These materials are dummy, checked-in secrets for `just run_local` only.+set -euo pipefail++cd "$(dirname "$0")"++openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 -out ca-key.pem+openssl req -new -x509 -key ca-key.pem -out ca.pem -days 3650 \+ -subj "/CN=Macro Local CA" \+ -addext "basicConstraints=critical,CA:TRUE" \+ -addext "keyUsage=critical,keyCertSign,cRLSign"++openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 -out localhost-key.pem+openssl req -new -key localhost-key.pem -out localhost.csr \+ -subj "/CN=localhost"++openssl x509 -req -in localhost.csr -CA ca.pem -CAkey ca-key.pem \+ -out localhost-leaf.pem -days 3650 \+ -extfile <(printf '%s\n' \+ 'subjectAltName=DNS:localhost,DNS:*.localhost,IP:127.0.0.1,IP:::1' \+ 'extendedKeyUsage=serverAuth')++# Serve the leaf plus the CA so clients that do not have the CA yet still+# see a complete chain; trusting `ca.pem` is what makes browsers happy.+cat localhost-leaf.pem ca.pem > localhost.pem+rm -f localhost.csr localhost-leaf.pem ca.srl++chmod 644 ca.pem ca-key.pem localhost.pem localhost-key.pem+echo "wrote CA and localhost cert in $(pwd)"diff --git a/infra/local/certs/issue-host.sh b/infra/local/certs/issue-host.shnew file mode 100644index 0000000000..b5aec19aac--- /dev/null+++ b/infra/local/certs/issue-host.sh@@ -0,0 +1,27 @@+#!/usr/bin/env bash+# Issue a machine certificate without replacing the development CA.+set -euo pipefail+certs_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+output_dir="${1:?output directory required}"+host="${2:?hostname required}"+if [[ ! "$host" =~ ^[a-zA-Z0-9][a-zA-Z0-9.-]*$ ]]; then+ echo "Invalid development hostname: $host" >&2+ exit 1+fi+mkdir -p "$output_dir"+openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 \+ -out "$output_dir/server-key.pem"+openssl req -new -key "$output_dir/server-key.pem" \+ -out "$output_dir/server.csr" -subj "/CN=$host"+openssl x509 -req -in "$output_dir/server.csr" \+ -CA "$certs_dir/ca.pem" -CAkey "$certs_dir/ca-key.pem" \+ -set_serial "0x$(openssl rand -hex 16)" -days 365 \+ -out "$output_dir/server-leaf.pem" \+ -extfile <(printf '%s\n' \+ "subjectAltName=DNS:localhost,DNS:*.localhost,DNS:$host,IP:127.0.0.1,IP:::1" \+ 'basicConstraints=critical,CA:FALSE' \+ 'keyUsage=critical,digitalSignature' \+ 'extendedKeyUsage=serverAuth')+cat "$output_dir/server-leaf.pem" "$certs_dir/ca.pem" > "$output_dir/server.pem"+chmod 600 "$output_dir/server-key.pem"+rm -f "$output_dir/server.csr" "$output_dir/server-leaf.pem"diff --git a/infra/local/certs/localhost-key.pem b/infra/local/certs/localhost-key.pemnew file mode 100644index 0000000000..56610b4212--- /dev/null+++ b/infra/local/certs/localhost-key.pem@@ -0,0 +1,5 @@+-----BEGIN PRIVATE KEY-----+MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQglX7J8D1NXOpCp64P+rZg3c3lxIVX/lw1bbYp3xL9rqwWhRANCAARihGogjl8jwh8ZI/Ui/ccA7H/f8HSx+gUw73AEjSWdwGHxXdbuf7C1sogIapMw//TVxiqbhJA3OasdS/IFVt3Sc+-----END PRIVATE KEY-----diff --git a/infra/local/certs/localhost.pem b/infra/local/certs/localhost.pemnew file mode 100644index 0000000000..f596b0bc7a--- /dev/null+++ b/infra/local/certs/localhost.pem@@ -0,0 +1,23 @@+-----BEGIN CERTIFICATE-----+MIIBwjCCAWmgAwIBAgIUDKu43QXezzxaRsdX56EyFJtRipwwCgYIKoZIzj0EAwIw+GTEXMBUGA1UEAwwOTWFjcm8gTG9jYWwgQ0EwHhcNMjYwOTE1MTg1NDA4WhcNMzYw+OTEyMTg1NDA4WjAUMRIwEAYDVQQDDAlsb2NhbGhvc3QwWTATBgcqhkjOPQIBBggq+hkjOPQMBBwNCAARihGogjl8jwh8ZI/Ui/ccA7H/f8HSxgUw73AEjSWdwGHxXdbuf+7C1sogIapMw//TVxiqbhJA3OasdS/IFVt3Sco4GTMIGQMDkGA1UdEQQyMDCCCWxv+Y2FsaG9zdIILKi5sb2NhbGhvc3SHBH8AAAGHEAAAAAAAAAAAAAAAAAAAAAEwEwYD+VR0lBAwwCgYIKwYBBQUHAwEwHQYDVR0OBBYEFHx1HWBqINBKghcSM24GvkYbZw2V+MB8GA1UdIwQYMBaAFAi1Lg3gBa4qcs1812yudjI4PVmwMAoGCCqGSM49BAMCA0cA+MEQCIAJ4KGHjbmUMg7mhf1ax2VS43LtvXkko891AzqDU71oCAiBMNvZEjF4mzDLs+hNYpY+4nxgLrCiCTFXrAcdcy4tpXbg==+-----END CERTIFICATE-----+-----BEGIN CERTIFICATE-----+MIIBlzCCAT2gAwIBAgIURgeGiABpfbvWllxTTVIJlSQYhlYwCgYIKoZIzj0EAwIw+GTEXMBUGA1UEAwwOTWFjcm8gTG9jYWwgQ0EwHhcNMjYwOTE1MTg1NDA4WhcNMzYw+OTEyMTg1NDA4WjAZMRcwFQYDVQQDDA5NYWNybyBMb2NhbCBDQTBZMBMGByqGSM49+AgEGCCqGSM49AwEHA0IABPsyQRUoxLlW6rVcTz6yl9HiKtmjt9H0OQfmJ04E/DjA+KCFrg4cGa3qjChaqAQ1C4c4YCpvXiPaZSJSu/H9qfGujYzBhMB0GA1UdDgQWBBQI+tS4N4AWuKnLNfNdsrnYyOD1ZsDAfBgNVHSMEGDAWgBQItS4N4AWuKnLNfNdsrnYy+OD1ZsDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAKBggqhkjOPQQD+AgNIADBFAiEA5LBE8x7as/CnEEwy6V+l1QtmlBvbqxOYDhGerE4ZpywCIGRJM9PA+mKyz+QSwPQeeXOGbeDk/AeiQ+Gyhf4sk2Pl5+-----END CERTIFICATE-----diff --git a/nix/cloud-storage.nix b/nix/cloud-storage.nixindex b707f8b743..de9ca38068 100644--- a/nix/cloud-storage.nix+++ b/nix/cloud-storage.nix@@ -55,10 +55,13 @@# `.sh` is required so `include_str!` of# `crates/agent_harness/container/ensure_ready.sh` survives the prune.assetFilter = path: _type: builtins.match ".*\\.(md|html|txt|json|canvas|sql|sh)$" path != null;+ # Rust local HTTP clients embed only the public proxy CA, never its keys.+ localCaFilter = path: _type: pkgs.lib.hasSuffix "/infra/local/certs/ca.pem" (toString path);binFilter = path: _type: builtins.match ".*\\.bin$" path != null;srcFilter =path: type:(sqlxFilter path type)+ || (localCaFilter path type)|| (pdfiumFilter path type)|| (assetFilter path type)|| (binFilter path type)@@ -117,7 +120,11 @@letrel = pkgs.lib.removePrefix ((toString ../.) + "/") (toString path);in- (rel == ".sqlx")+ (rel == "infra")+ || (rel == "infra/local")+ || (rel == "infra/local/certs")+ || (localCaFilter path type)+ || (rel == ".sqlx")|| (pkgs.lib.hasPrefix ".sqlx/" rel)|| (rel == "static_assets")|| (pkgs.lib.hasPrefix "static_assets/" rel)diff --git a/services/authentication_service/src/api/utils.rs b/services/authentication_service/src/api/utils.rsindex 7b69f2049e..9184ff6560 100644--- a/services/authentication_service/src/api/utils.rs+++ b/services/authentication_service/src/api/utils.rs@@ -9,6 +9,7 @@ use url::Url;maybe_env_vars! {struct FrontendPort;+ struct FrontendOrigin;}/// Generates a random 25 character session code@@ -50,6 +51,11 @@ pub fn generate_session_code() -> String {pub fn default_redirect_url() -> Url {match Environment::new_or_prod() {Environment::Local => {+ if let Some(origin) = FrontendOrigin::new() {+ return origin.parse().unwrap_or_else(|_| {+ panic!("FRONTEND_ORIGIN must be a URL, got {}", origin.as_ref())+ });+ }let port = FrontendPort::new().map(|port| port.to_string()).unwrap_or_else(|| "3000".to_string());diff --git a/tooling/just/xtask.just b/tooling/just/xtask.justindex 8569190825..71e70bdcab 100644--- a/tooling/just/xtask.just+++ b/tooling/just/xtask.just@@ -5,6 +5,9 @@# run-local needs.xtask := "cargo run --quiet --manifest-path Cargo.toml -p xtask_local --features local-stack --"+# Short name for the fully local development stack.+alias local := run_local+# Start a fully local stack (xtask: zigbuild + runtime image + infra + proxy + frontend).# just run_local # default instance# just run_local --instance agent-a # isolated, concurrent instancediff --git a/tooling/seed_cli/src/entity/gmail.rs b/tooling/seed_cli/src/entity/gmail.rsindex 5b18ded58b..98ceb35960 100644--- a/tooling/seed_cli/src/entity/gmail.rs+++ b/tooling/seed_cli/src/entity/gmail.rs@@ -13,6 +13,7 @@//! justfile pulls all three from AWS Secrets Manager.use std::collections::BTreeMap;+use std::path::PathBuf;use std::time::{Duration, Instant};use anyhow::{Context, bail};@@ -62,9 +63,9 @@ pub enum GmailCommand {#[derive(Debug, Args)]pub struct ForwardArgs {/// The local email-service webhook to deliver notifications to, through- /// the instance proxy (e.g. http://localhost:50009/email/gmail/webhook- /// for `--instance 2634`)- #[arg(long, default_value = "http://localhost:8090/email/gmail/webhook")]+ /// the instance proxy (e.g. https://localhost:50009/email/gmail/webhook+ /// for `--instance 2634`). Local HTTPS uses `infra/local/certs/ca.pem`.+ #[arg(long, default_value = "https://localhost:8090/email/gmail/webhook")]target: String,/// The Pub/Sub pull subscription attached to the Gmail watch topic#[arg(@@ -138,6 +139,58 @@ fn http_client() -> anyhow::Result<reqwest::Client> {.context("building the HTTP client")}+/// Client for the local-stack webhook only. Google calls stay on+/// [`http_client`] so public TLS verification is unchanged. Local HTTPS+/// (the host default, through the reverse proxy) adds the checked-in CA;+/// rustls does not honor `SSL_CERT_FILE`.+fn webhook_client(target: &str) -> anyhow::Result<reqwest::Client> {+ let mut builder = reqwest::Client::builder().timeout(Duration::from_secs(120));+ if is_local_https(target) {+ let cert = local_proxy_ca().with_context(|| {+ format!(+ "local HTTPS webhook {target} needs infra/local/certs/ca.pem \+ (run from the repo, or pass --target http://…)"+ )+ })?;+ builder = builder.add_root_certificate(cert);+ }+ builder.build().context("building the webhook HTTP client")+}++fn is_local_https(url: &str) -> bool {+ url.starts_with("https://localhost:")+ || url.starts_with("https://localhost/")+ || url == "https://localhost"+ || url.starts_with("https://127.0.0.1:")+ || url.starts_with("https://127.0.0.1/")+}++fn local_proxy_ca() -> Option<reqwest::Certificate> {+ local_proxy_ca_pem().and_then(|pem| reqwest::Certificate::from_pem(&pem).ok())+}++fn local_proxy_ca_pem() -> Option<Vec<u8>> {+ local_proxy_ca_paths()+ .into_iter()+ .find(|path| path.is_file())+ .and_then(|path| std::fs::read(path).ok())+}++fn local_proxy_ca_paths() -> Vec<PathBuf> {+ const REL: &str = "infra/local/certs/ca.pem";+ let mut paths = Vec::new();+ if let Ok(mut dir) = std::env::current_dir() {+ loop {+ paths.push(dir.join(REL));+ if !dir.pop() {+ break;+ }+ }+ }+ paths.push(PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../infra/local/certs/ca.pem"));+ paths+}+fn require_test_account(email: &str) -> anyhow::Result<()> {if !email.ends_with(TEST_DOMAIN) {bail!("refusing to touch {email}: only {TEST_DOMAIN} test accounts are allowed");@@ -808,6 +861,7 @@ async fn ensure_subscription(/// them, so a stack that is down redelivers instead of losing sync events.async fn forward(args: ForwardArgs) -> anyhow::Result<()> {let http = http_client()?;+ let webhook = webhook_client(&args.target)?;let mut sa = SaToken::from_env(http.clone()).await?;ensure_subscription(&http, &mut sa, &args.subscription, &args.topic).await?;let pull_url = format!(@@ -878,7 +932,7 @@ async fn forward(args: ForwardArgs) -> anyhow::Result<()> {"subscription": args.subscription,});let webhook_token = sa.webhook_bearer(&args.webhook_audience).await?.to_string();- match http+ match webhook.post(&args.target).bearer_auth(webhook_token).json(&envelope)diff --git a/tooling/seed_cli/src/entity/gmail/test.rs b/tooling/seed_cli/src/entity/gmail/test.rsindex 5f252fd3de..fa4e2d8d05 100644--- a/tooling/seed_cli/src/entity/gmail/test.rs+++ b/tooling/seed_cli/src/entity/gmail/test.rs@@ -1,5 +1,49 @@use super::*;+#[test]+fn default_forward_target_is_local_https() {+ assert!(is_local_https("https://localhost:8090/email/gmail/webhook"));+ assert!(is_local_https("https://127.0.0.1:8090/email/gmail/webhook"));+ assert!(!is_local_https("http://email-service:8080/gmail/webhook"));+ assert!(!is_local_https("https://pubsub.googleapis.com/v1/x"));+}++#[test]+fn local_proxy_ca_loads_the_checked_in_pem() {+ let pem = local_proxy_ca_pem().expect("infra/local/certs/ca.pem must be readable");+ assert!(+ std::str::from_utf8(&pem)+ .unwrap_or_default()+ .contains("BEGIN CERTIFICATE"),+ "checked-in CA is not a PEM"+ );+ assert!(+ local_proxy_ca().is_some(),+ "reqwest must parse the local CA"+ );+}++#[test]+fn webhook_client_builds_for_the_default_https_target() {+ webhook_client("https://localhost:8090/email/gmail/webhook")+ .expect("webhook client should trust the checked-in CA");+}++#[tokio::test]+#[ignore = "requires a running local HTTPS proxy; set LOCAL_E2E_BACKEND_ORIGIN for a named instance"]+async fn webhook_client_verifies_local_https_when_the_proxy_is_up() {+ let origin = macro_env_var::maybe_read_env("LOCAL_E2E_BACKEND_ORIGIN")+ .unwrap_or_else(|| "https://localhost:8090".to_owned());+ let url = format!("{origin}/auth/health");+ let client = webhook_client(&url).expect("webhook client should trust the checked-in CA");+ let response = client+ .get(url)+ .send()+ .await+ .expect("local HTTPS webhook client must verify TLS and reach the proxy");+ assert!(response.status().is_success(), "proxy health should be 2xx");+}+#[test]fn plan_is_deterministic_and_never_future_dated() {let now = Utc::now();diff --git a/tooling/xtask/crates/xtask_local/src/local.rs b/tooling/xtask/crates/xtask_local/src/local.rsindex fa49e626b1..562c581ffe 100644--- a/tooling/xtask/crates/xtask_local/src/local.rs+++ b/tooling/xtask/crates/xtask_local/src/local.rs@@ -45,6 +45,7 @@ pub mod stack;pub mod stage;pub mod status;pub mod summary;+pub mod tls;pub mod validate;#[cfg(test)]@@ -442,7 +443,7 @@ pub fn run_stack(mode: Mode, args: &cli::RunArgs) -> Result<()> {mode,&instance,&env,- &frontend::url(&instance),+ &frontend::https_url(&instance)?,&mailpit_url,shared_app_url.as_deref(),);@@ -1225,8 +1226,14 @@ fn ensure_external_resources(stage: &Stage, instance: &Instance) -> Result<()> {}fn wait_http(stage: &Stage, label: &str, url: &str) -> Result<()> {+ let ca = proxy::curl_ca_args(url);+ let ca_flags = ca+ .iter()+ .map(|arg| format!("'{arg}'"))+ .collect::<Vec<_>>()+ .join(" ");let script = format!(- "for i in $(seq 1 600); do curl -fsS --max-time 3 {url} >/dev/null 2>&1 && exit 0; sleep 0.2; done; echo 'not ready: {url}'; exit 1"+ "for i in $(seq 1 600); do curl -fsS {ca_flags} --max-time 3 {url} >/dev/null 2>&1 && exit 0; sleep 0.2; done; echo 'not ready: {url}'; exit 1");let mut cmd = Command::new("bash");cmd.arg("-lc").arg(script);diff --git a/tooling/xtask/crates/xtask_local/src/local/cf_tunnel.rs b/tooling/xtask/crates/xtask_local/src/local/cf_tunnel.rsindex 86e31ad2e2..d3ac10ef10 100644--- a/tooling/xtask/crates/xtask_local/src/local/cf_tunnel.rs+++ b/tooling/xtask/crates/xtask_local/src/local/cf_tunnel.rs@@ -85,7 +85,8 @@ fn pid_path(instance: &Instance, name: &str) -> PathBuf {/// Reaps a same-named tunnel leaked by a previous run first, so at most one/// per (instance, name) exists.pub fn open(instance: &Instance, name: &str, port: u16) -> Result<QuickTunnel> {- open_origin(instance, name, &format!("http://localhost:{port}"))+ let scheme = if name == "app" { "https" } else { "http" };+ open_origin(instance, name, &format!("{scheme}://localhost:{port}"))}/// Open a quick tunnel whose origin is a raw TCP service rather than a web@@ -102,8 +103,14 @@ pub fn open_tcp(instance: &Instance, name: &str, port: u16) -> Result<QuickTunnefn open_origin(instance: &Instance, name: &str, origin: &str) -> Result<QuickTunnel> {reap_stale(instance, name);- let mut child = Command::new("cloudflared")- .args(["tunnel", "--no-autoupdate", "--url", origin])+ let mut cmd = Command::new("cloudflared");+ cmd.args(["tunnel", "--no-autoupdate"]);+ if origin.starts_with("https://") {+ // Trust only the checked-in CA for the tunnel's local HTTPS origin.+ cmd.arg("--origin-ca-pool").arg(super::proxy::ca_pem());+ }+ cmd.args(["--url", origin]);+ let mut child = cmd.stdout(Stdio::null()).stderr(Stdio::piped()).spawn()diff --git a/tooling/xtask/crates/xtask_local/src/local/cli.rs b/tooling/xtask/crates/xtask_local/src/local/cli.rsindex 67b223f047..009bf01b0b 100644--- a/tooling/xtask/crates/xtask_local/src/local/cli.rs+++ b/tooling/xtask/crates/xtask_local/src/local/cli.rs@@ -29,12 +29,16 @@ enum Cmd {RuntimeImage(ForceArg),/// Render the per-instance compose override and print its path.GenCompose(InstanceArgs),+ /// Print the inventoried backend path prefixes for an external Vite launcher.+ FrontendProxyRoutes,/// Render merged compose and assert the no-build / runtime-image invariants.ValidateLocalCompose(InstanceArgs),/// Resolve env layers and assert mode-appropriate invariants.ValidateLocalEnv(ValidateEnvArgs),/// Create the declared Kafka event topics on the instance's local broker.KafkaProvision(InstanceArgs),+ /// Restore missing local AWS resources without resetting databases or volumes.+ LocalstackProvision(InstanceArgs),/// Preflight checks (docker, toolchain, ports, env sources, images).DoctorLocal(InstanceArgs),/// Show an instance's endpoints and container states without starting anything.@@ -250,6 +254,10 @@ fn run(cli: Cli) -> Result<()> {Cmd::Zigbuild => super::zigbuild_only(),Cmd::RuntimeImage(a) => super::runtime_image_only(a.force),Cmd::GenCompose(a) => super::gen_compose_only(&a),+ Cmd::FrontendProxyRoutes => {+ println!("{}", super::proxy::frontend_path_prefixes().join(","));+ Ok(())+ }Cmd::ValidateLocalCompose(a) => {let instance = super::instance::Instance::derive(a.instance.as_deref(), a.port_base)?;super::validate::local_compose(&instance, Mode::Local)@@ -267,6 +275,10 @@ fn run(cli: Cli) -> Result<()> {let instance = super::instance::Instance::derive(a.instance.as_deref(), a.port_base)?;super::kafka::provision(&instance)}+ Cmd::LocalstackProvision(a) => {+ let instance = super::instance::Instance::derive(a.instance.as_deref(), a.port_base)?;+ super::localstack::provision(&instance)+ }Cmd::DoctorLocal(a) => super::doctor::run(&a),Cmd::StatusLocal(a) => {let instance = super::instance::Instance::derive(a.instance.as_deref(), a.port_base)?;diff --git a/tooling/xtask/crates/xtask_local/src/local/e2e.rs b/tooling/xtask/crates/xtask_local/src/local/e2e.rsindex b379d7a148..e85c64f5d4 100644--- a/tooling/xtask/crates/xtask_local/src/local/e2e.rs+++ b/tooling/xtask/crates/xtask_local/src/local/e2e.rs@@ -68,10 +68,7 @@ impl Endpoints {),fusionauth_url: format!("http://localhost:{}", instance.port(Port::FusionAuth)),localstack_url: format!("http://localhost:{}", instance.port(Port::LocalStack)),- connection_gateway_ws_url: format!(- "ws://localhost:{}/connection-gateway",- instance.port(Port::Proxy)- ),+ connection_gateway_ws_url: format!("{}/connection-gateway", proxy::ws_url(instance)),generated_env: instance.artifact_dir().join("local.generated.env"),}}diff --git a/tooling/xtask/crates/xtask_local/src/local/e2e/test.rs b/tooling/xtask/crates/xtask_local/src/local/e2e/test.rsindex 7255615453..3fa4cb27a4 100644--- a/tooling/xtask/crates/xtask_local/src/local/e2e/test.rs+++ b/tooling/xtask/crates/xtask_local/src/local/e2e/test.rs@@ -5,7 +5,7 @@ fn derives_host_endpoints_and_test_environment_from_the_instance() {let instance = Instance::derive(Some("e2e-test"), Some(31_000)).unwrap();let endpoints = Endpoints::for_instance(&instance);- assert_eq!(endpoints.proxy_url, "http://localhost:31009");+ assert_eq!(endpoints.proxy_url, "https://localhost:31009");assert_eq!(endpoints.frontend_url, "http://localhost:31010/app");assert_eq!(endpoints.postgres_url,@@ -15,14 +15,14 @@ fn derives_host_endpoints_and_test_environment_from_the_instance() {assert_eq!(endpoints.localstack_url, "http://localhost:31006");assert_eq!(endpoints.connection_gateway_ws_url,- "ws://localhost:31009/connection-gateway"+ "wss://localhost:31009/connection-gateway");let env = endpoints.test_env();assert_eq!(env["LOCAL_E2E_BACKEND_ORIGIN"], endpoints.proxy_url);assert_eq!(env["LOCAL_E2E_CONNECTION_GATEWAY_WS_URL"],- "ws://localhost:31009/connection-gateway"+ "wss://localhost:31009/connection-gateway");assert_eq!(env["DATABASE_URL"], endpoints.postgres_url);assert_eq!(diff --git a/tooling/xtask/crates/xtask_local/src/local/env_layer.rs b/tooling/xtask/crates/xtask_local/src/local/env_layer.rsindex 11b9e35526..6ebe7d2988 100644--- a/tooling/xtask/crates/xtask_local/src/local/env_layer.rs+++ b/tooling/xtask/crates/xtask_local/src/local/env_layer.rs@@ -59,7 +59,8 @@ pub fn resolve(let spec = mode.spec();let local = spec.overlay_local_env- .then(|| local_env::LocalEnv::for_instance(mode, instance, static_frontend, tunnels));+ .then(|| local_env::LocalEnv::for_instance(mode, instance, static_frontend, tunnels))+ .transpose()?;let mut env = BTreeMap::new();// Boot stubs go in FIRST so Doppler overrides them: they only exist to keep// a `--no-doppler` stack's config loaders satisfied, never to replace adiff --git a/tooling/xtask/crates/xtask_local/src/local/frontend.rs b/tooling/xtask/crates/xtask_local/src/local/frontend.rsindex 4ae401fe1a..88f64699a0 100644--- a/tooling/xtask/crates/xtask_local/src/local/frontend.rs+++ b/tooling/xtask/crates/xtask_local/src/local/frontend.rs@@ -23,6 +23,20 @@ pub fn url(instance: &Instance) -> String {format!("http://localhost:{}/app", instance.port(Port::Frontend))}+/// Browser-facing origin for development redirects and integration callbacks.+pub fn https_origin(instance: &Instance) -> Result<String> {+ Ok(format!(+ "https://{}:{}",+ super::tls::hostname()?,+ instance.port(Port::Proxy)+ ))+}++/// Browser-facing development URL, using the machine certificate and proxy.+pub fn https_url(instance: &Instance) -> Result<String> {+ Ok(format!("{}/app/", https_origin(instance)?))+}+/// Frontend URL when the proxy serves the static bundle (headless stacks): the/// app lives on the single proxy origin, not a dev-server port.pub fn static_url(instance: &Instance) -> String {@@ -106,13 +120,18 @@ fn dev_env(mode: Mode,traces_enabled: bool,enable_onboarding: bool,-) -> Vec<(String, String)> {+) -> Result<Vec<(String, String)>> {let mut env = vec![("PORT".to_string(),instance.port(Port::Frontend).to_string(),),("VITE_LOCAL_SERVERS".to_string(), "ALL".to_string()),+ ("MACRO_LOCAL_HOSTNAME".to_string(), super::tls::hostname()?),+ (+ "NODE_EXTRA_CA_CERTS".to_string(),+ proxy::ca_pem().display().to_string(),+ ),("VITE_LOCAL_BACKEND_ORIGIN".to_string(),"same-origin".to_string(),@@ -155,20 +174,58 @@ fn dev_env("VITE_ENABLE_ONBOARDING_V4".to_string(),enable_onboarding.to_string(),));- env+ Ok(env)}/// Poll the backend (auth health, through the proxy) until ready.pub fn wait_backend_ready(stage: &Stage, instance: &Instance) -> Result<()> {let url = format!("{}/auth/health", proxy::url(instance));+ let cacert = proxy::ca_pem();let script = format!(- "for i in $(seq 1 600); do curl -fsS --max-time 3 {url} >/dev/null 2>&1 && exit 0; sleep 0.2; done; echo 'backend not ready'; exit 1"+ "for i in $(seq 1 600); do curl -fsS --cacert '{cacert}' --max-time 3 {url} >/dev/null 2>&1 && exit 0; sleep 0.2; done; echo 'backend not ready'; exit 1",+ cacert = cacert.display());let mut cmd = Command::new("bash");cmd.arg("-lc").arg(script);stage.run("Waiting for backend (proxy /auth/health)", &mut cmd)}+/// A listening Vite port does not prove the containerized proxy can reach it.+/// Verify the browser's route before announcing that the stack is ready.+fn wait_frontend_proxy_ready(stage: &Stage, instance: &Instance) -> Result<()> {+ let mut cmd = Command::new("curl");+ cmd.args([+ "--fail",+ "--silent",+ "--show-error",+ "--retry",+ "8",+ "--retry-connrefused",+ "--retry-delay",+ "1",+ "--retry-max-time",+ "45",+ "--max-time",+ "5",+ "--output",+ "/dev/null",+ "--cacert",+ ])+ .arg(proxy::ca_pem())+ .arg(format!("{}/app/", proxy::url(instance)));+ stage+ .run("Checking frontend through HTTPS proxy", &mut cmd)+ .with_context(|| {+ format!(+ "HTTPS proxy could not serve the frontend. Check proxy logs and Docker-to-host \+ firewall access to host.docker.internal:{} (Vite's port). \+ Direct Vite URL: {}",+ instance.port(Port::Frontend),+ url(instance)+ )+ })+}+/// A running frontend dev server plus its captured output, so an unexpected/// exit can be explained (the output is otherwise suppressed).pub struct Frontend {@@ -310,10 +367,11 @@ pub fn start(.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped());- for (k, v) in dev_env(instance, mode, traces_enabled, enable_onboarding) {+ for (k, v) in dev_env(instance, mode, traces_enabled, enable_onboarding)? {cmd.env(k, v);}let process = spawn(stage, &mut cmd, port)?;+ wait_frontend_proxy_ready(stage, instance)?;Ok(Some(Frontend {process,command: cmd,diff --git a/tooling/xtask/crates/xtask_local/src/local/frontend/test.rs b/tooling/xtask/crates/xtask_local/src/local/frontend/test.rsindex a3fcc72724..06d7a25a6a 100644--- a/tooling/xtask/crates/xtask_local/src/local/frontend/test.rs+++ b/tooling/xtask/crates/xtask_local/src/local/frontend/test.rs@@ -10,9 +10,19 @@ fn stack_frontend_uses_same_origin_with_an_instance_specific_server_target() {Instance::derive(Some("other-dev"), Some(20300)).unwrap(),] {for mode in [Mode::Local, Mode::Dev] {- let env: std::collections::HashMap<_, _> =- dev_env(&instance, mode, true, false).into_iter().collect();+ let env: std::collections::HashMap<_, _> = dev_env(&instance, mode, true, false)+ .unwrap()+ .into_iter()+ .collect();+ assert_eq!(+ env["MACRO_LOCAL_HOSTNAME"],+ super::super::tls::hostname().unwrap()+ );assert_eq!(env["VITE_LOCAL_BACKEND_ORIGIN"], "same-origin");+ assert_eq!(+ env["NODE_EXTRA_CA_CERTS"],+ proxy::ca_pem().display().to_string()+ );assert_eq!(env["MACRO_LOCAL_BACKEND_PROXY"], proxy::url(&instance));assert_eq!(env["MACRO_LOCAL_BACKEND_ROUTES"],@@ -26,6 +36,7 @@ fn stack_frontend_uses_same_origin_with_an_instance_specific_server_target() {}}let env: std::collections::HashMap<_, _> = dev_env(&instance, Mode::Local, false, false)+ .unwrap().into_iter().collect();assert_eq!(env["VITE_ENABLE_BROWSER_OTEL"], "false");diff --git a/tooling/xtask/crates/xtask_local/src/local/gen_compose.rs b/tooling/xtask/crates/xtask_local/src/local/gen_compose.rsindex 8fbe5cbea8..775ac9bfed 100644--- a/tooling/xtask/crates/xtask_local/src/local/gen_compose.rs+++ b/tooling/xtask/crates/xtask_local/src/local/gen_compose.rs@@ -60,6 +60,11 @@ pub fn caddyfile_path(instance: &Instance) -> PathBuf {instance.artifact_dir().join("proxy/Caddyfile")}+/// Checked-in development CA and localhost fixtures.+pub fn tls_certs_dir() -> PathBuf {+ repo_root().join("infra/local/certs")+}+/// Build the override (typed model), apply the merge tags, and write it./// `static_frontend` mounts the staged app bundle into the proxy (headless/// stacks serve the frontend from Caddy instead of a dev server).@@ -70,6 +75,7 @@ pub fn generate(static_frontend: bool,gmail_forwarder: bool,) -> Result<PathBuf> {+ super::tls::issue(instance)?;let mut services: IndexMap<String, Option<dct::Service>> = IndexMap::new();let mounts = binaries.compose_mounts();@@ -287,10 +293,16 @@ fn add_proxy_service(previews: bool,) {let proxy_port = instance.port(Port::Proxy);- let mut volumes = vec![dct::Volumes::Simple(format!(- "{}:/etc/caddy/Caddyfile:ro",- caddyfile_path(instance).display()- ))];+ let mut volumes = vec![+ dct::Volumes::Simple(format!(+ "{}:/etc/caddy/Caddyfile:ro",+ caddyfile_path(instance).display()+ )),+ dct::Volumes::Simple(format!(+ "{}:/etc/caddy/certs:ro",+ super::tls::certs_dir(instance).display()+ )),+ ];if static_frontend {volumes.push(dct::Volumes::Simple(format!("{}:/srv/frontend:ro",@@ -309,7 +321,11 @@ fn add_proxy_service("proxy".to_string(),Some(dct::Service {image: Some(CADDY_IMAGE.to_string()),- environment: kv(&[("PROXY_PORT", &proxy_port.to_string())]),+ environment: kv(&[+ ("PROXY_PORT", &proxy_port.to_string()),+ ("VITE_PORT", &instance.port(Port::Frontend).to_string()),+ ]),+ extra_hosts: vec!["host.docker.internal:host-gateway".to_string()],ports: dct::Ports::Short(ports),volumes,networks: dct::Networks::Simple(vec!["services".to_string(), "databases".to_string()]),diff --git a/tooling/xtask/crates/xtask_local/src/local/local_env.rs b/tooling/xtask/crates/xtask_local/src/local/local_env.rsindex 55d2331b7f..36f49e3e25 100644--- a/tooling/xtask/crates/xtask_local/src/local/local_env.rs+++ b/tooling/xtask/crates/xtask_local/src/local/local_env.rs@@ -16,8 +16,10 @@use std::collections::BTreeMap;+use anyhow::Result;+use super::instance::{Instance, Port};-use super::{Mode, identity, resources};+use super::{Mode, frontend, identity, proxy, resources};/// The public hostnames `--with-cf-tunnel` minted for this run.///@@ -38,16 +40,17 @@ pub struct Tunnels<'a> {pub struct LocalEnv {environment: &'static str,project_name: String,- /// Where the browser-facing app lives: the proxy (static bundle at- /// `/app`) or the bun dev server. `default_redirect_url()` in- /// authentication_service sends post-login browsers to- /// `http://localhost:{FRONTEND_PORT}`, so this must track the serving- /// mode or every OAuth signup dead-ends on an unused port.+ /// Legacy localhost fallback port. `FRONTEND_ORIGIN` is authoritative for+ /// browser redirects and points at the HTTPS proxy in both serving modes.frontend_port: u16,external_egress_url: String,preview_ssh_proxy_host: Option<String>,preview_ssh_port: u16,preview_https_port: u16,+ preview_control_hosts: String,+ /// Browser-facing origin for post-login redirects and Pipedream CORS.+ /// Both attached and headless frontends are exposed through HTTPS.+ frontend_origin: String,/// Browser-facing route to document cognition's MCP OAuth callback.mcp_public_url: String,/// Browser-facing base the static file service stamps into permalinks.@@ -82,17 +85,30 @@ impl LocalEnv {instance: &Instance,static_frontend: bool,tunnels: Tunnels<'_>,- ) -> Self {+ ) -> Result<Self> {let name = instance.name();- LocalEnv {+ let frontend_port = if static_frontend {+ instance.port(Port::Proxy)+ } else {+ instance.port(Port::Frontend)+ };+ let frontend_origin = if static_frontend {+ proxy::url(instance)+ } else {+ frontend::https_origin(instance)?+ };+ Ok(LocalEnv {// Both local flavors run against local infra (`local` env defaults).environment: mode.environment_var(),project_name: instance.project_name().to_string(),- frontend_port: if static_frontend {- instance.port(Port::Proxy)- } else {- instance.port(Port::Frontend)- },+ frontend_port,+ mcp_public_url: format!("{frontend_origin}/cognition"),+ static_file_public_url: format!("{frontend_origin}/static-file"),+ frontend_origin,+ preview_control_hosts: format!(+ "localhost,127.0.0.1,preview-gateway,{}",+ super::tls::hostname()?+ ),external_egress_url: tunnels.egress.map(str::to_owned).unwrap_or_else(|| {format!("http://localhost:{}",@@ -102,11 +118,6 @@ impl LocalEnv {preview_ssh_proxy_host: tunnels.preview_ssh.map(str::to_owned),preview_ssh_port: instance.port(Port::PreviewSsh),preview_https_port: instance.port(Port::PreviewHttps),- mcp_public_url: format!("http://localhost:{}/cognition", instance.port(Port::Proxy)),- static_file_public_url: format!(- "http://localhost:{}/static-file",- instance.port(Port::Proxy)- ),infra: InfraEnv::local(instance),storage: StorageEnv::local(),queues: QueueEnv::local(),@@ -115,7 +126,7 @@ impl LocalEnv {service_auth: ServiceAuthEnv::for_instance(name),fusionauth: FusionAuthEnv::for_instance(instance),boot_stubs: BootStubEnv,- }+ })}/// Flatten to the env map services receive. The single struct→env boundary.@@ -125,6 +136,7 @@ impl LocalEnv {env.insert("COMPOSE_PROJECT_NAME".into(), self.project_name.clone());env.insert("PORT".into(), "8080".into());env.insert("FRONTEND_PORT".into(), self.frontend_port.to_string());+ env.insert("FRONTEND_ORIGIN".into(), self.frontend_origin.clone());env.insert("MCP_PUBLIC_URL".into(), self.mcp_public_url.clone());env.insert("STATIC_FILE_SERVICE_URL".into(),@@ -136,7 +148,7 @@ impl LocalEnv {// port, so connecting an app there would fail at the consent popup.env.insert("PIPEDREAM_ALLOWED_ORIGINS".into(),- format!("http://localhost:{}", self.frontend_port),+ self.frontend_origin.clone(),);// Calendar ingestion/sync ships dark (both flags default off in// deployed envs); local stacks keep it on for development.@@ -169,13 +181,10 @@ impl LocalEnv {"PREVIEW_HTTPS_PORT".into(),self.preview_https_port.to_string(),);- env.insert(- "PREVIEW_APP_ORIGIN".into(),- format!("http://localhost:{}", self.frontend_port),- );+ env.insert("PREVIEW_APP_ORIGIN".into(), self.frontend_origin.clone());env.insert("PREVIEW_CONTROL_HOSTS".into(),- "localhost,127.0.0.1,preview-gateway".into(),+ self.preview_control_hosts.clone(),);self.infra.write(&mut env);self.storage.write(&mut env);diff --git a/tooling/xtask/crates/xtask_local/src/local/local_env/test.rs b/tooling/xtask/crates/xtask_local/src/local/local_env/test.rsindex 5964e1d7ae..9a70eec331 100644--- a/tooling/xtask/crates/xtask_local/src/local/local_env/test.rs+++ b/tooling/xtask/crates/xtask_local/src/local/local_env/test.rs@@ -6,7 +6,7 @@ use crate::local::instance::{Instance, Port};/// authoritative local env on top (mirrors `env_layer::resolve`).fn local_env() -> BTreeMap<String, String> {let instance = Instance::derive(None, None).expect("default instance derives");- let local = LocalEnv::for_instance(Mode::Local, &instance, true, Tunnels::default());+ let local = LocalEnv::for_instance(Mode::Local, &instance, true, Tunnels::default()).unwrap();let mut env = local.boot_stub_env();env.extend(local.to_env());env@@ -20,6 +20,8 @@ fn emits_required_keys() {for key in ["ENVIRONMENT","PORT",+ "FRONTEND_PORT",+ "FRONTEND_ORIGIN","BASE_URL","DATABASE_URL","DATABASE_URL_READONLY",@@ -110,7 +112,7 @@ fn emits_required_keys() {#[test]fn boot_stubs_do_not_overlap_authoritative_env() {let instance = Instance::derive(None, None).expect("default instance derives");- let local = LocalEnv::for_instance(Mode::Local, &instance, true, Tunnels::default());+ let local = LocalEnv::for_instance(Mode::Local, &instance, true, Tunnels::default()).unwrap();let authoritative = local.to_env();for key in local.boot_stub_env().keys() {assert!(@@ -159,6 +161,7 @@ fn internal_auth_values_are_authoritative_local_env() {true,Tunnels::default(),)+ .unwrap().to_env();let expected = env.get("INTERNAL_API_SECRET_KEY");@@ -247,7 +250,7 @@ fn static_file_permalinks_go_through_the_instance_proxy() {.get("STATIC_FILE_SERVICE_URL").expect("static file permalink base");assert!(- permalink_base.starts_with("http://localhost:"),+ permalink_base.starts_with("https://localhost:"),"{permalink_base}");assert!(permalink_base.ends_with("/static-file"), "{permalink_base}");@@ -286,8 +289,12 @@ fn aws_creds_are_dummy() {fn instance_secrets_are_scoped_but_identity_is_fixed() {let default = Instance::derive(None, None).unwrap();let agent_a = Instance::derive(Some("agent-a"), None).unwrap();- let a = LocalEnv::for_instance(Mode::Local, &default, true, Tunnels::default()).to_env();- let b = LocalEnv::for_instance(Mode::Local, &agent_a, true, Tunnels::default()).to_env();+ let a = LocalEnv::for_instance(Mode::Local, &default, true, Tunnels::default())+ .unwrap()+ .to_env();+ let b = LocalEnv::for_instance(Mode::Local, &agent_a, true, Tunnels::default())+ .unwrap()+ .to_env();assert_ne!(a.get("SERVICE_INTERNAL_AUTH_KEY"),@@ -305,9 +312,12 @@ fn instance_secrets_are_scoped_but_identity_is_fixed() {fn fusionauth_public_url_uses_the_instance_host_port() {let default = Instance::derive(None, None).unwrap();let named = Instance::derive(Some("2508"), None).unwrap();- let default_env =- LocalEnv::for_instance(Mode::Local, &default, true, Tunnels::default()).to_env();- let named_env = LocalEnv::for_instance(Mode::Local, &named, true, Tunnels::default()).to_env();+ let default_env = LocalEnv::for_instance(Mode::Local, &default, true, Tunnels::default())+ .unwrap()+ .to_env();+ let named_env = LocalEnv::for_instance(Mode::Local, &named, true, Tunnels::default())+ .unwrap()+ .to_env();let named_public_url = format!("http://localhost:{}", named.port(Port::FusionAuth));assert_eq!(@@ -356,8 +366,11 @@ fn local_sandboxes_join_the_instances_compose_network() {true,Tunnels::default(),)+ .unwrap().to_env();- let named_env = LocalEnv::for_instance(Mode::Local, &named, true, Tunnels::default()).to_env();+ let named_env = LocalEnv::for_instance(Mode::Local, &named, true, Tunnels::default())+ .unwrap()+ .to_env();assert_eq!(default_env@@ -379,14 +392,17 @@ fn local_sandboxes_join_the_instances_compose_network() {fn mcp_public_url_uses_the_proxy_cognition_route() {let default = Instance::derive(None, None).unwrap();let named = Instance::derive(Some("2508"), None).unwrap();- let default_env =- LocalEnv::for_instance(Mode::Local, &default, true, Tunnels::default()).to_env();- let named_env = LocalEnv::for_instance(Mode::Local, &named, true, Tunnels::default()).to_env();- let named_public_url = format!("http://localhost:{}/cognition", named.port(Port::Proxy));+ let default_env = LocalEnv::for_instance(Mode::Local, &default, true, Tunnels::default())+ .unwrap()+ .to_env();+ let named_env = LocalEnv::for_instance(Mode::Local, &named, true, Tunnels::default())+ .unwrap()+ .to_env();+ let named_public_url = format!("https://localhost:{}/cognition", named.port(Port::Proxy));assert_eq!(default_env.get("MCP_PUBLIC_URL").map(String::as_str),- Some("http://localhost:8090/cognition")+ Some("https://localhost:8090/cognition"));assert_eq!(named_env.get("MCP_PUBLIC_URL").map(String::as_str),@@ -394,6 +410,43 @@ fn mcp_public_url_uses_the_proxy_cognition_route() {);}+#[test]+fn frontend_origin_tracks_how_the_app_is_served() {+ for instance in [+ Instance::derive(None, None).unwrap(),+ Instance::derive(Some("remote-dev"), Some(20100)).unwrap(),+ ] {+ for static_frontend in [true, false] {+ let env =+ LocalEnv::for_instance(Mode::Local, &instance, static_frontend, Tunnels::default())+ .unwrap()+ .to_env();+ let origin = if static_frontend {+ proxy::url(&instance)+ } else {+ frontend::https_origin(&instance).unwrap()+ };+ for key in [+ "FRONTEND_ORIGIN",+ "PIPEDREAM_ALLOWED_ORIGINS",+ "PREVIEW_APP_ORIGIN",+ ] {+ assert_eq!(env[key], origin, "{key}");+ }+ assert_eq!(env["MCP_PUBLIC_URL"], format!("{origin}/cognition"));+ assert_eq!(+ env["STATIC_FILE_SERVICE_URL"],+ format!("{origin}/static-file")+ );+ assert!(+ env["PREVIEW_CONTROL_HOSTS"]+ .split(',')+ .any(|host| host == super::super::tls::hostname().unwrap())+ );+ }+ }+}+/// In-network address, not localhost: a sandbox's localhost is its own. The/// host is hyphenated because a sandbox's git percent-encodes `_` before/// matching `credential.<url>.helper`, so the compose service name would leave@@ -401,7 +454,9 @@ fn mcp_public_url_uses_the_proxy_cognition_route() {#[test]fn the_egress_url_override_is_the_hyphenated_in_network_alias() {let named = Instance::derive(Some("2508"), None).unwrap();- let named_env = LocalEnv::for_instance(Mode::Local, &named, true, Tunnels::default()).to_env();+ let named_env = LocalEnv::for_instance(Mode::Local, &named, true, Tunnels::default())+ .unwrap()+ .to_env();assert_eq!(named_env@@ -435,6 +490,7 @@ fn the_public_tunnel_overrides_the_egress_service_url() {..Tunnels::default()},)+ .unwrap().to_env();assert_eq!(@@ -448,7 +504,9 @@ fn the_public_tunnel_overrides_the_egress_service_url() {#[test]fn named_instance_separates_browser_and_container_aws_endpoints() {let instance = Instance::derive(Some("image"), None).expect("named instance derives");- let env = LocalEnv::for_instance(Mode::Local, &instance, false, Tunnels::default()).to_env();+ let env = LocalEnv::for_instance(Mode::Local, &instance, false, Tunnels::default())+ .unwrap()+ .to_env();assert_eq!(env["LOCAL_AWS_URL"], "http://localstack:4566");assert_eq!(env["LOCAL_AWS_PUBLIC_URL"],@@ -459,7 +517,9 @@ fn named_instance_separates_browser_and_container_aws_endpoints() {#[test]fn external_runtime_egress_respects_instance_host_ports_and_public_tunnels() {let instance = Instance::derive(Some("preview"), None).unwrap();- let env = LocalEnv::for_instance(Mode::Local, &instance, false, Tunnels::default()).to_env();+ let env = LocalEnv::for_instance(Mode::Local, &instance, false, Tunnels::default())+ .unwrap()+ .to_env();assert_eq!(env["EXTERNAL_EGRESS_BASE_URL"],format!(@@ -480,6 +540,7 @@ fn external_runtime_egress_respects_instance_host_ports_and_public_tunnels() {..Tunnels::default()},)+ .unwrap().to_env();assert_eq!(env["EXTERNAL_EGRESS_BASE_URL"],@@ -494,7 +555,9 @@ fn external_runtime_egress_respects_instance_host_ports_and_public_tunnels() {#[test]fn the_preview_ssh_proxy_host_is_empty_without_a_published_tunnel() {let instance = Instance::derive(Some("preview"), None).unwrap();- let env = LocalEnv::for_instance(Mode::Local, &instance, false, Tunnels::default()).to_env();+ let env = LocalEnv::for_instance(Mode::Local, &instance, false, Tunnels::default())+ .unwrap()+ .to_env();assert_eq!(env["PREVIEW_SSH_HOST"], "localhost");assert_eq!(env["PREVIEW_SSH_PROXY_HOST"], "");@@ -507,6 +570,7 @@ fn the_preview_ssh_proxy_host_is_empty_without_a_published_tunnel() {..Tunnels::default()},)+ .unwrap().to_env();assert_eq!(env["PREVIEW_SSH_PROXY_HOST"],diff --git a/tooling/xtask/crates/xtask_local/src/local/proxy.rs b/tooling/xtask/crates/xtask_local/src/local/proxy.rsindex e609ebc261..749bc2ac22 100644--- a/tooling/xtask/crates/xtask_local/src/local/proxy.rs+++ b/tooling/xtask/crates/xtask_local/src/local/proxy.rs@@ -5,18 +5,44 @@//! `reverse_proxy` upgrades WebSockets transparently (connection-gateway,//! websocket-service, sync-service). The `/static-file/*` block reproduces the//! nginx CDN fan-out (S3 via LocalStack + the static-file service).+//!+//! The host-facing listener is HTTPS using a machine certificate signed by+//! the development CA in `infra/local/certs`. Local mode also stamps wildcard CORS on the generated+//! Caddyfile so any browser origin (`https://`, `*.localhost`, tunnels) can+//! call the proxy without updating every service allowlist.use std::path::PathBuf;use anyhow::{Context, Result};-use super::gen_compose::caddyfile_path;+use super::gen_compose::{caddyfile_path, tls_certs_dir};use super::instance::{Instance, Port};use super::{Mode, inventory};-/// The host-facing proxy origin.+/// The host-facing proxy origin. The local reverse proxy speaks HTTPS using+/// a machine certificate signed by the checked-in development CA.pub fn url(instance: &Instance) -> String {- format!("http://localhost:{}", instance.port(Port::Proxy))+ format!("https://localhost:{}", instance.port(Port::Proxy))+}++/// WebSocket origin for the same proxy.+pub fn ws_url(instance: &Instance) -> String {+ format!("wss://localhost:{}", instance.port(Port::Proxy))+}++/// Path to the checked-in local CA. Pass to `curl --cacert` when probing the+/// proxy so health checks verify TLS instead of skipping it.+pub fn ca_pem() -> PathBuf {+ tls_certs_dir().join("ca.pem")+}++/// Extra curl arguments that trust the local proxy CA. Empty for `http://`.+pub fn curl_ca_args(url: &str) -> Vec<String> {+ if url.starts_with("https://") {+ vec!["--cacert".into(), ca_pem().display().to_string()]+ } else {+ Vec::new()+ }}/// Vite forwards only backend routes, leaving assets, SPA navigation and HMR@@ -55,9 +81,10 @@ pub fn write_caddyfile(instance: &Instance, mode: Mode, static_frontend: bool) -Ok(path)}-/// Assemble the Caddyfile: the listener head, the generated per-service routes-/// (from the inventory), the special non-inventory routes, the mode's-/// static-file block, the optional static-frontend block, then the tail.+/// Assemble the Caddyfile: the listener head (HTTPS + optional local CORS),+/// the generated per-service routes (from the inventory), the special+/// non-inventory routes, the mode's static-file block, the optional+/// static-frontend block, then the tail.fn caddyfile(mode: Mode, static_frontend: bool) -> String {let static_block = if mode.spec().static_files_via_localstack {STATIC_FILE_LOCAL@@ -69,14 +96,23 @@ fn caddyfile(mode: Mode, static_frontend: bool) -> String {} else {""};- let frontend_block = if static_frontend { FRONTEND_STATIC } else { "" };+ let frontend_block = if static_frontend {+ FRONTEND_STATIC.to_owned()+ } else {+ FRONTEND_VITE.replace("BACKEND_PREFIXES", &frontend_path_prefixes().join(" "))+ };let preview_block = if mode.spec().runs_local_infra {"\nhttps://*.preview.localhost:8443 {\n tls internal\n reverse_proxy preview_gateway:8111\n}\n"} else {""};+ // Wildcard CORS is a local-stack overlay: `run_local` / `stack up` stamp+ // it on Caddy so HTTPS and `*.localhost` origins work without touching+ // every service allowlist. `run_dev` still fans out to the shared-dev+ // gateway, so it keeps service CORS as-is.+ let cors_block = if mode == Mode::Local { LOCAL_CORS } else { "" };format!(- "{CADDY_HEAD}{routes}{SPECIAL_ROUTES}{mailpit_block}{static_block}{frontend_block}{CADDY_TAIL}{preview_block}",+ "{CADDY_HEAD}{cors_block}{routes}{SPECIAL_ROUTES}{mailpit_block}{static_block}{frontend_block}{CADDY_TAIL}{preview_block}",routes = service_routes(mode))}@@ -149,10 +185,11 @@ fn matcher_name(prefix: &str) -> String {format!("@{}", prefix.trim_start_matches('/').replace('-', "_"))}-/// Caddy listens on `{$PROXY_PORT}` (set in the compose service env). Static-/// content, plaintext HTTP, automatic WebSocket upgrade. The per-service routes-/// (generated from the inventory), the special routes, the static-file block,-/// and the closing brace follow.+/// Caddy listens on `{$PROXY_PORT}` (set in the compose service env) with the+/// generated machine certificate. Automatic HTTP→HTTPS redirects stay off —+/// this port is HTTPS-only. The per-service routes (generated from the+/// inventory), the special routes, the static-file block, and the closing+/// brace follow.const CADDY_HEAD: &str = r#"# GENERATED by `cargo x` — do not edit.{auto_https disable_redirects@@ -160,9 +197,42 @@ const CADDY_HEAD: &str = r#"# GENERATED by `cargo x` — do not edit.}:{$PROXY_PORT} {+ tls /etc/caddy/certs/server.pem /etc/caddy/certs/server-key.pem# Caddy requires the block body on its own lines (no single-line `{ ... }`)."#;+/// Reflect any `Origin` on the local proxy. Preflight is answered here so+/// OPTIONS never depends on a service CORS layer.+///+/// Do not `header { -Access-Control-* }` at site scope: Caddy's `-Field`+/// is a deferred delete of the final response, so it also strips the+/// headers this overlay sets. `defer` applies our replacements after+/// `reverse_proxy` copies upstream CORS, overwriting them.+/// Leave exposed headers to the upstream service: `*` is not a wildcard+/// for credentialed requests and would hide headers such as `Retry-After`.+const LOCAL_CORS: &str = r#" @cors header Origin *+ header @cors {+ Access-Control-Allow-Origin "{http.request.header.Origin}"+ Access-Control-Allow-Credentials true+ Access-Control-Max-Age 86400+ Vary Origin+ defer+ }+ @cors_preflight {+ method OPTIONS+ header Origin *+ }+ handle @cors_preflight {+ header Access-Control-Allow-Origin "{http.request.header.Origin}"+ header Access-Control-Allow-Credentials true+ header Access-Control-Allow-Methods "GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS"+ header Access-Control-Allow-Headers "{http.request.header.Access-Control-Request-Headers}"+ header Access-Control-Max-Age 86400+ header Vary Origin+ respond 204+ }+"#;+/// Routes for services that aren't in the Rust inventory (external / base-compose/// services on their own ports), so they can't be generated from it. The/// WebSocket routes match the bare prefix too (the frontend connects without a@@ -206,12 +276,14 @@ const MAILPIT_ROUTE: &str = r#" # Mailpit serves itself under /mailpit (MP_WE/// Local: /api and /internal go to the service, everything else to the S3 bucket/// via LocalStack (mirrors infra/local/nginx/static-file-cdn.conf).-const STATIC_FILE_LOCAL: &str = r#" route /static-file/* {- uri strip_prefix /static-file- @svc path /api/* /internal/*- reverse_proxy @svc static-file-service:8080- rewrite * /static-file-storage{uri}- reverse_proxy localstack:4566+const STATIC_FILE_LOCAL: &str = r#" handle_path /static-file/* {+ # Keep service dispatch before the S3 rewrite inside this exclusive handle.+ route {+ @svc path /api/* /internal/*+ reverse_proxy @svc static-file-service:8080+ rewrite * /static-file-storage{uri}+ reverse_proxy localstack:4566+ }}"#;@@ -237,9 +309,19 @@ const FRONTEND_STATIC: &str = r#" redir / "/app/?{query}" 302"#;const CADDY_TAIL: &str = r#"- respond "macro local proxy" 200}"#;+/// Catch only non-backend paths, including Vite assets and HMR upgrades.+/// Forward the original Host so Vite enforces the detected machine allowlist.+const FRONTEND_VITE: &str = r#" handle {+ # Bare HTTP service prefixes have no handler. Do not send them to+ # Vite, whose backend proxy would send them straight back here.+ @backend_root path BACKEND_PREFIXES+ respond @backend_root 404+ reverse_proxy host.docker.internal:{$VITE_PORT}+ }+"#;+#[cfg(test)]mod test;diff --git a/tooling/xtask/crates/xtask_local/src/local/proxy/test.rs b/tooling/xtask/crates/xtask_local/src/local/proxy/test.rsindex cf24a8c508..a146875716 100644--- a/tooling/xtask/crates/xtask_local/src/local/proxy/test.rs+++ b/tooling/xtask/crates/xtask_local/src/local/proxy/test.rs@@ -127,7 +127,11 @@ fn document_content_services_are_available_through_the_proxy() {/// fan-out locally, the dev-pointed service in dev.#[test]fn static_file_block_is_mode_specific() {- assert!(caddyfile(Mode::Local, false).contains("/static-file-storage"));+ let local = caddyfile(Mode::Local, false);+ assert!(local.contains("/static-file-storage"));+ // A route at site scope sorts after the Vite catch-all handle and loops.+ assert!(local.contains("handle_path /static-file/*"));+ assert!(!local.contains("route /static-file/*"));assert!(caddyfile(Mode::Dev, false).contains("handle_path /static-file/*"));assert!(!caddyfile(Mode::Dev, false).contains("/static-file-storage"));}@@ -158,7 +162,7 @@ fn frontend_wires_every_inventory_prefix() {/// The static-frontend block only appears in headless mode, and serves the/// mounted bundle under `/app` with an SPA fallback. Attached `run_local` keeps-/// the dev server as the frontend origin and must not grow the block.+/// forwards frontend requests to Vite instead of serving a bundle.#[test]fn static_frontend_block_is_opt_in() {let headless = caddyfile(Mode::Local, true);@@ -170,9 +174,56 @@ fn static_frontend_block_is_opt_in() {let attached = caddyfile(Mode::Local, false);assert!(!attached.contains("/srv/frontend"));+ assert!(attached.contains("reverse_proxy host.docker.internal:{$VITE_PORT}"));+ assert!(attached.contains(&format!(+ "@backend_root path {}",+ frontend_path_prefixes().join(" ")+ )));+ assert!(attached.contains("respond @backend_root 404"));+ assert!(!headless.contains("host.docker.internal"));assert!(!attached.contains("redir / /app/ 302"));assert!(!attached.contains("handle /mailpit/*"));let headless_dev = caddyfile(Mode::Dev, true);assert!(!headless_dev.contains("handle /mailpit/*"));}++/// Local Caddy speaks HTTPS with a machine certificate and stamps wildcard CORS+/// on every response. Dev still uses TLS (same proxy) but does not overlay+/// CORS, because it fans out to the shared-dev gateway.+#[test]+fn local_proxy_uses_tls_and_wildcard_cors() {+ let local = caddyfile(Mode::Local, false);+ assert!(local.contains("tls /etc/caddy/certs/server.pem /etc/caddy/certs/server-key.pem"));+ // Keep main's internal certificates for the separate preview listener.+ assert!(local.contains("auto_https disable_redirects"));+ assert!(local.contains("https://*.preview.localhost:8443"));+ assert!(local.contains("@cors header Origin *"));+ assert!(local.contains("@cors_preflight"));+ assert!(local.contains("Access-Control-Allow-Origin \"{http.request.header.Origin}\""));+ assert!(+ local.contains("defer"),+ "CORS overlay must defer so reverse_proxy cannot overwrite the reflected Origin"+ );+ assert!(+ !local.contains("-Access-Control-Allow-Origin"),+ "deferred -Access-Control-* deletes strip the CORS headers this overlay sets"+ );++ let dev = caddyfile(Mode::Dev, false);+ assert!(dev.contains("tls /etc/caddy/certs/server.pem /etc/caddy/certs/server-key.pem"));+ assert!(!dev.contains("@cors header Origin *"));+ assert!(!dev.contains("@cors_preflight"));+}++#[test]+fn proxy_origin_is_https() {+ let instance = crate::local::instance::Instance::derive(None, None).unwrap();+ assert_eq!(url(&instance), "https://localhost:8090");+ assert_eq!(ws_url(&instance), "wss://localhost:8090");+ assert!(+ ca_pem().is_file(),+ "checked-in CA is missing at {}",+ ca_pem().display()+ );+}diff --git a/tooling/xtask/crates/xtask_local/src/local/seed_env.rs b/tooling/xtask/crates/xtask_local/src/local/seed_env.rsindex 61b7fbd980..86c0d587ae 100644--- a/tooling/xtask/crates/xtask_local/src/local/seed_env.rs+++ b/tooling/xtask/crates/xtask_local/src/local/seed_env.rs@@ -67,8 +67,8 @@ fn values(instance: &Instance) -> Vec<(&'static str, String)> {} else {let proxy = instance.port(Port::Proxy);(- format!("http://localhost:{proxy}/sync"),- format!("http://localhost:{proxy}/lexical"),+ format!("https://localhost:{proxy}/sync"),+ format!("https://localhost:{proxy}/lexical"),)};diff --git a/tooling/xtask/crates/xtask_local/src/local/seed_env/test.rs b/tooling/xtask/crates/xtask_local/src/local/seed_env/test.rsindex 1ea76002ca..695baacd85 100644--- a/tooling/xtask/crates/xtask_local/src/local/seed_env/test.rs+++ b/tooling/xtask/crates/xtask_local/src/local/seed_env/test.rs@@ -53,11 +53,11 @@ fn named_instance_shifts_into_its_port_window() {assert_ne!(instance.port(Port::FusionAuth), 9011);let proxy = instance.port(Port::Proxy);assert!(- render(&instance).contains(&format!("http://localhost:{proxy}/sync")),+ render(&instance).contains(&format!("https://localhost:{proxy}/sync")),"sync-service should use the named instance proxy");assert!(- render(&instance).contains(&format!("http://localhost:{proxy}/lexical")),+ render(&instance).contains(&format!("https://localhost:{proxy}/lexical")),"lexical-service should use the named instance proxy");}diff --git a/tooling/xtask/crates/xtask_local/src/local/stack.rs b/tooling/xtask/crates/xtask_local/src/local/stack.rsindex bee78b802d..74e3f5c6bd 100644--- a/tooling/xtask/crates/xtask_local/src/local/stack.rs+++ b/tooling/xtask/crates/xtask_local/src/local/stack.rs@@ -104,9 +104,7 @@ fn write_state(instance: &Instance, state: &StackState) -> Result<()> {.with_context(|| format!("writing {}", path.display()))}-/// Whether the recorded stack serves the frontend as the static bundle on the-/// proxy (headless `stack up`) rather than the dev server. False when no-/// stack state exists (interactive `run_local`, which owns the dev server).+/// Whether the recorded stack serves a headless bundle from the proxy.pub(super) fn frontend_is_static(instance: &Instance) -> bool {read_state(instance).is_some_and(|state| state.frontend == "static")}@@ -634,11 +632,11 @@ fn str_field(v: &serde_json::Value, key: &str) -> String {/// One quick `curl` probe (the tooling already leans on curl for readiness).fn probe(url: &str) -> bool {- Command::new("curl")- .args(["-fsS", "-m", "3", "-o", "/dev/null", url])- .status()- .map(|s| s.success())- .unwrap_or(false)+ let mut cmd = Command::new("curl");+ cmd.args(["-fsS", "-m", "3", "-o", "/dev/null"]);+ cmd.args(super::proxy::curl_ca_args(url));+ cmd.arg(url);+ cmd.status().map(|s| s.success()).unwrap_or(false)}fn mode_from_label(label: &str) -> Result<Mode> {diff --git a/tooling/xtask/crates/xtask_local/src/local/summary.rs b/tooling/xtask/crates/xtask_local/src/local/summary.rsindex f9840f8179..1375b46155 100644--- a/tooling/xtask/crates/xtask_local/src/local/summary.rs+++ b/tooling/xtask/crates/xtask_local/src/local/summary.rs@@ -11,13 +11,13 @@ use super::{Mode, frontend, mailpit, proxy, sdk_webhook};/// The host-facing endpoints of an instance: (label, url, host port)./// Shared by the startup summary and `status-local`.pub fn endpoint_rows(instance: &Instance) -> Vec<(&'static str, String, u16)> {- // Headless stacks serve the app from the proxy origin; showing the- // dev-server URL there reads as "frontend down" when nothing is wrong.- let (frontend_url, frontend_port) = if super::stack::frontend_is_static(instance) {- (frontend::static_url(instance), instance.port(Port::Proxy))+ // Both attached and headless stacks expose the app through HTTPS.+ let frontend_url = if super::stack::frontend_is_static(instance) {+ frontend::static_url(instance)} else {- (frontend::url(instance), instance.port(Port::Frontend))+ frontend::https_url(instance).unwrap_or_else(|_| frontend::static_url(instance))};+ let frontend_port = instance.port(Port::Proxy);vec![("frontend", frontend_url, frontend_port),("proxy", proxy::url(instance), instance.port(Port::Proxy)),@@ -83,9 +83,8 @@ pub fn stop_command(instance: &Instance) -> String {}/// Print the mode/instance/endpoints block after a successful startup.-/// `frontend_url` differs by flow: the dev-server origin for `run_local`, the-/// proxy-served bundle for headless `stack up`; `mailpit_url` follows the same-/// direct-versus-single-origin distinction. `shared_app_url` is the public+/// `frontend_url` is the HTTPS app URL; `mailpit_url` differs between attached+/// and headless flows. `shared_app_url` is the public/// app tunnel when `--with-cf-tunnel` opened one — passed explicitly because,/// unlike the egress tunnel, it is not written into the env.pub fn print(diff --git a/tooling/xtask/crates/xtask_local/src/local/tls.rs b/tooling/xtask/crates/xtask_local/src/local/tls.rsnew file mode 100644index 0000000000..b7a1861b23--- /dev/null+++ b/tooling/xtask/crates/xtask_local/src/local/tls.rs@@ -0,0 +1,51 @@+//! Machine-specific leaf certificates signed by the stable development CA.++use std::path::PathBuf;+use std::process::Command;++use anyhow::{Context, Result, ensure};++use super::{instance::Instance, repo_root};++/// Ask the host OS for the name used by Vite and the development certificate.+pub fn hostname() -> Result<String> {+ let output = Command::new("hostname")+ .output()+ .context("running hostname")?;+ ensure!(output.status.success(), "hostname command failed");+ let hostname = String::from_utf8(output.stdout)?+ .trim()+ .to_ascii_lowercase();+ ensure!(+ !hostname.is_empty()+ && hostname+ .bytes()+ .all(|c| c.is_ascii_alphanumeric() || c == b'-' || c == b'.'),+ "hostname is not a valid DNS name: {hostname}"+ );+ Ok(hostname)+}++/// Untracked, per-instance server key and certificate directory.+pub fn certs_dir(instance: &Instance) -> PathBuf {+ instance.artifact_dir().join("proxy/certs")+}++/// Issue a leaf for this machine, keeping the checked-in CA unchanged.+pub fn issue(instance: &Instance) -> Result<()> {+ let output = Command::new("bash")+ .arg(repo_root().join("infra/local/certs/issue-host.sh"))+ .arg(certs_dir(instance))+ .arg(hostname()?)+ .output()+ .context("issuing local HTTPS certificate")?;+ ensure!(+ output.status.success(),+ "issuing local HTTPS certificate: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ Ok(())+}++#[cfg(test)]+mod test;diff --git a/tooling/xtask/crates/xtask_local/src/local/tls/test.rs b/tooling/xtask/crates/xtask_local/src/local/tls/test.rsnew file mode 100644index 0000000000..3160d0be70--- /dev/null+++ b/tooling/xtask/crates/xtask_local/src/local/tls/test.rs@@ -0,0 +1,47 @@+use super::*;++#[test]+fn machine_certificate_verifies_with_existing_ca_and_rejects_other_hosts() {+ let unique = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_nanos();+ let dir = std::env::temp_dir().join(format!("macro-tls-{unique}"));+ let ca = super::super::proxy::ca_pem();+ let ca_before = std::fs::read(&ca).unwrap();+ let status = Command::new("bash")+ .arg(repo_root().join("infra/local/certs/issue-host.sh"))+ .arg(&dir)+ .arg("coworker-dev")+ .output()+ .unwrap();+ assert!(+ status.status.success(),+ "{}",+ String::from_utf8_lossy(&status.stderr)+ );+ for host in ["coworker-dev", "localhost"] {+ let result = Command::new("openssl")+ .args(["verify", "-CAfile"])+ .arg(&ca)+ .args(["-verify_hostname", host])+ .arg(dir.join("server.pem"))+ .output()+ .unwrap();+ assert!(+ result.status.success(),+ "{host}: {}",+ String::from_utf8_lossy(&result.stderr)+ );+ }+ let wrong = Command::new("openssl")+ .args(["verify", "-CAfile"])+ .arg(&ca)+ .args(["-verify_hostname", "another-machine"])+ .arg(dir.join("server.pem"))+ .output()+ .unwrap();+ assert!(!wrong.status.success());+ assert_eq!(std::fs::read(&ca).unwrap(), ca_before);+ std::fs::remove_dir_all(dir).unwrap();+}diff --git a/tooling/xtask/crates/xtask_local/src/local/validate.rs b/tooling/xtask/crates/xtask_local/src/local/validate.rsindex 58effc7da5..8c0b4aca9c 100644--- a/tooling/xtask/crates/xtask_local/src/local/validate.rs+++ b/tooling/xtask/crates/xtask_local/src/local/validate.rs@@ -11,7 +11,7 @@ use super::build::{BinariesDir, RUNTIME_IMAGE_TAG};use super::instance::Port;use super::inventory::services_for_mode;use super::local_env::Tunnels;-use super::{Mode, arch, env_layer, gen_compose, instance::Instance, workspace_root};+use super::{Mode, arch, env_layer, gen_compose, instance::Instance, proxy, workspace_root};/// Required non-Rust services that must be present in the rendered local/// compose.@@ -241,7 +241,7 @@ fn local_env_flavor(}}// The post-login redirect must point at where this flavor- // actually serves the app (proxy for static, dev server port+ // actually serves the app (localhost for static, machine hostname// otherwise) — the exact drift this per-flavor pass exists to// catch.let expected_frontend_port = if static_frontend {@@ -256,6 +256,18 @@ fn local_env_flavor(flavor_label(static_frontend),));}+ let expected_frontend_origin = if static_frontend {+ proxy::url(instance)+ } else {+ super::frontend::https_origin(instance)?+ };+ if env.get("FRONTEND_ORIGIN") != Some(&expected_frontend_origin) {+ failures.push(format!(+ "FRONTEND_ORIGIN={:?} does not match the {} origin {expected_frontend_origin}",+ env.get("FRONTEND_ORIGIN"),+ flavor_label(static_frontend),+ ));+ }}Mode::Dev => {// run-dev runs as macro_env `local` *on purpose*: dev_personal ships