Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
add Vite Dev-UI host guard with auto + AI allowedHosts remediation
[._.]/ Adam Eivydd5fc1e2f581
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex e9f38438d8..f3a9d2f47f 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -8,6 +8,7 @@- Editorial Checks page now has an AI provider + model selector that configures the editorial pass. Leave it on "Default provider" to use the active/stage provider, or pick a specific provider/model to override the LLM-backed checks for that run.- App **Automation** tabs now show a banner when scheduled automation is globally paused, with a one-click **Resume**. Manually clicking **Run** on a task now bypasses the global pause — the pause only stops scheduled/autonomous spawning, not explicit user triggers.+- **Vite Dev-UI host guard.** Launching a managed app's Dev UI over Tailscale used to fail with Vite's "Blocked request. This host (…) is not allowed" because Vite ≥5 rejects unknown hosts. The app detail view now checks each online Vite app's config against the host PortOS is served under and shows a warning banner when it would be blocked, with two one-click fixes: **Allow all hosts (auto)** deterministically rewrites the app's `vite.config` to `server.allowedHosts: true` (safe on a private Tailscale network), and **Fix with AI** queues a CoS agent to edit (or create) the app's `vite.config` in its own repo for configs too unusual to auto-edit. Launching by IP/localhost already works since Vite never blocks those.## Fixeddiff --git a/client/src/components/apps/AppDetailView.jsx b/client/src/components/apps/AppDetailView.jsxindex b7666cf898..ca07b647f2 100644--- a/client/src/components/apps/AppDetailView.jsx+++ b/client/src/components/apps/AppDetailView.jsx@@ -1,6 +1,6 @@import { useState, useEffect, useCallback, useMemo } from 'react';import { Link, useParams, useNavigate } from 'react-router-dom';-import { ArrowLeft, Play, Square, RotateCcw, ExternalLink, Hammer, RefreshCw, Pencil } from 'lucide-react';+import { ArrowLeft, Play, Square, RotateCcw, ExternalLink, Hammer, RefreshCw, Pencil, AlertTriangle, Sparkles } from 'lucide-react';import DeployPanel from './DeployPanel';import EditAppDrawer from './EditAppDrawer';import toast from '../ui/Toast';@@ -32,6 +32,11 @@ export default function AppDetailView() {const [actionLoading, setActionLoading] = useState(null);const [buildLoading, setBuildLoading] = useState(false);const [editing, setEditing] = useState(false);+ // Vite Dev-UI host guard: when an online app exposes a Vite dev server, check+ // whether its config allows the Tailscale/IP host PortOS is served under+ // (Vite ≥5 blocks unknown hosts). `null` = not yet checked.+ const [viteHostStatus, setViteHostStatus] = useState(null);+ const [viteFixing, setViteFixing] = useState(null); // 'allow-all' | 'ai' while a fix is in flightconst fetchApp = useCallback(async () => {const data = await api.getApp(appId).catch(() => null);@@ -102,6 +107,37 @@ export default function AppDetailView() {}};+ // Re-check the Vite host guard whenever the app, its dev port, or its online+ // status changes. Skip the self-app (PortOS already allow-lists `.ts.net`).+ const devUiPort = app?.devUiPort;+ const isOnline = app?.overallStatus === 'online';+ useEffect(() => {+ if (!devUiPort || !isOnline || appId === api.PORTOS_APP_ID) {+ setViteHostStatus(null);+ return;+ }+ let cancelled = false;+ api.getAppViteHostStatus(appId, window.location.hostname)+ .then((status) => { if (!cancelled) setViteHostStatus(status); })+ .catch(() => { if (!cancelled) setViteHostStatus(null); });+ return () => { cancelled = true; };+ }, [appId, devUiPort, isOnline]);++ const handleFixViteHosts = async (mode) => {+ setViteFixing(mode);+ const result = await api.fixAppViteHosts(appId, { mode, host: window.location.hostname })+ .catch((err) => { toast.error(`Host fix failed: ${err.message}`); return null; });+ setViteFixing(null);+ if (!result) return;+ if (mode === 'ai') {+ toast.success(`AI remediation task queued for ${app.name} — review it in the CoS plan`);+ return;+ }+ toast.success(`${app.name}: ${result.filename} now allows this host — restart the dev server`);+ // Optimistically clear the warning; a restart picks up the change.+ setViteHostStatus((prev) => prev ? { ...prev, hostAllowed: true } : prev);+ };+const visibleTabs = useMemo(() =>APP_DETAIL_TABS.filter(t => {if (t.id === 'update') return app?.id === api.PORTOS_APP_ID;@@ -313,6 +349,49 @@ export default function AppDetailView() {<span className="text-xs">Edit</span></button></div>+ {/* Vite Dev-UI host guard — the app's dev server would block this host. */}+ {viteHostStatus && !viteHostStatus.hostAllowed && (+ <div className="mt-3 w-full rounded-lg border border-port-warning/40 bg-port-warning/10 p-3">+ <div className="flex items-start gap-2">+ <AlertTriangle size={16} className="text-port-warning mt-0.5 shrink-0" />+ <div className="flex-1 min-w-0">+ <p className="text-sm text-port-warning font-medium">+ Dev UI will be blocked on <span className="font-mono">{window.location.hostname}</span>+ </p>+ <p className="text-xs text-gray-400 mt-1">+ {viteHostStatus.hasViteConfig+ ? <>This app's Vite dev server ({viteHostStatus.filename}) doesn't allow this host, so opening the Dev UI shows a "Blocked request… not allowed" error.</>+ : <>This app exposes a Vite dev server but no <span className="font-mono">vite.config</span> was found to allow this host, so the Dev UI will be blocked.</>}+ {' '}It runs on a private Tailscale network — allowing all hosts is safe.+ </p>+ <div className="flex flex-wrap gap-2 mt-2">+ {viteHostStatus.canAutoFix && (+ <button+ onClick={() => handleFixViteHosts('allow-all')}+ disabled={Boolean(viteFixing)}+ className="px-2 py-1 bg-port-accent/20 text-port-accent enabled:hover:bg-port-accent/30 transition-colors rounded flex items-center gap-1 disabled:opacity-50 text-xs"+ >+ {viteFixing === 'allow-all' ? 'Allowing…' : 'Allow all hosts (auto)'}+ </button>+ )}+ <button+ onClick={() => handleFixViteHosts('ai')}+ disabled={Boolean(viteFixing)}+ className="px-2 py-1 bg-port-border/40 text-gray-200 enabled:hover:bg-port-border/60 transition-colors rounded flex items-center gap-1 disabled:opacity-50 text-xs"+ >+ <Sparkles size={12} />+ {viteFixing === 'ai' ? 'Queuing…' : 'Fix with AI'}+ </button>+ </div>+ {!viteHostStatus.canAutoFix && viteHostStatus.hasViteConfig && (+ <p className="text-[11px] text-gray-500 mt-1.5">+ Auto-fix can't safely edit this config shape — use AI remediation.+ </p>+ )}+ </div>+ </div>+ </div>+ )}</div>{/* Tab Bar */}diff --git a/client/src/services/apiApps.js b/client/src/services/apiApps.jsindex e6421d76ca..d11bb311e2 100644--- a/client/src/services/apiApps.js+++ b/client/src/services/apiApps.js@@ -49,6 +49,16 @@ export function handleSelfRestart() {};poll();}+// Vite Dev-UI host check / remediation. Read-only status check is silent (the+// detail view owns its own inline warning UI); the fix call's caller shows+// custom success/error toasts.+export const getAppViteHostStatus = (id, host) =>+ request(`/apps/${id}/vite-host-check?host=${encodeURIComponent(host || '')}`, { silent: true });+export const fixAppViteHosts = (id, body) => request(`/apps/${id}/fix-vite-hosts`, {+ method: 'POST',+ body: JSON.stringify(body),+ silent: true+});export const archiveApp = (id) => request(`/apps/${id}/archive`, { method: 'POST' });export const unarchiveApp = (id) => request(`/apps/${id}/unarchive`, { method: 'POST' });export const openAppInEditor = (id) => request(`/apps/${id}/open-editor`, { method: 'POST' });diff --git a/server/lib/README.md b/server/lib/README.mdindex ecb9ef3aeb..b9e0ad202a 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -210,6 +210,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `ports.js` | Canonical PORTS object (re-exported from `ecosystem.config.cjs`). || `platform.js` | Platform/OS detection helpers. || `timezone.js` | Timezone utilities for scheduling. |+| `viteAllowedHosts.js` | Detect and remediate a managed app's Vite `server.allowedHosts`. `findViteConfig(repoPath)` locates the config; `parseAllowedHosts(src)` / `hostIsAllowed(parsed, host)` decide whether a Tailscale/IP host would be accepted (mirrors Vite's localhost+IP-always-allowed and leading-dot-suffix rules); `rewriteAllowedHosts(src)` deterministically injects `allowedHosts: true` (or bails `ok:false` on ambiguous shapes so the caller can fall back to an LLM fix); `checkViteHost(repoPath, host)` is the one-shot status used by `GET /api/apps/:id/vite-host-check`. || `buildId.js` | Build-ID derived from the built client bundle. |## General utilitiesdiff --git a/server/lib/index.js b/server/lib/index.jsindex 1cf7c56d98..7329d08e78 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -184,6 +184,7 @@ export * from './pgTools.js';export * from './platform.js';export * from './ports.js';export * from './timezone.js';+export * from './viteAllowedHosts.js';// === General utilities ===export * from './apiRegistry.js';diff --git a/server/lib/viteAllowedHosts.js b/server/lib/viteAllowedHosts.jsnew file mode 100644index 0000000000..b649e074f2--- /dev/null+++ b/server/lib/viteAllowedHosts.js@@ -0,0 +1,226 @@+/**+ * viteAllowedHosts — detect and remediate Vite's `server.allowedHosts` block in a+ * managed app's config.+ *+ * Why this exists: PortOS is served over a Tailscale MagicDNS name (e.g.+ * `box.taile8179.ts.net`). When a managed app's Dev UI is launched, the browser+ * hits the app's Vite dev server at that same hostname — and Vite ≥5 rejects it+ * with "Blocked request. This host ("…") is not allowed. … add it to+ * server.allowedHosts in vite.config.js" unless the host is allow-listed.+ *+ * These pure helpers locate the app's vite config, read its current+ * `allowedHosts` setting, decide whether a given hostname would be accepted, and+ * deterministically rewrite the config to allow all hosts. When the config shape+ * is too unusual to rewrite safely the rewrite bails (`ok: false`) so the caller+ * can fall back to an LLM-assisted fix instead of corrupting the file.+ */+import { join } from 'path';+import { tryReadFile } from './fileUtils.js';++// Vite resolves its config from any of these (TS variants included). Order+// mirrors Vite's own resolution preference (js/mjs/ts first).+export const VITE_CONFIG_FILENAMES = [+ 'vite.config.js',+ 'vite.config.mjs',+ 'vite.config.ts',+ 'vite.config.mts',+ 'vite.config.cjs',+ 'vite.config.cts'+];++/**+ * Strip `//` line and `/* *\/` block comments so detection/rewrite logic never+ * matches a commented-out `allowedHosts`. Intentionally simple — it does not+ * parse strings, so a `//` inside a string literal would be over-stripped; that+ * only ever makes detection MORE conservative (we treat the host as not-allowed+ * and offer remediation), never less safe.+ */+function stripComments(source) {+ return String(source ?? '')+ .replace(/\/\*[\s\S]*?\*\//g, '')+ .replace(/(^|[^:])\/\/[^\n]*/g, '$1');+}++const ALLOWED_HOSTS_VALUE_RE =+ /allowedHosts\s*:\s*(true|false|'all'|"all"|`all`|\[[^\]]*\])/;++/**+ * Parse the current `server.allowedHosts` value out of a vite config source.+ * Returns `{ present, allowsAll, hosts, raw }`:+ * - present — an `allowedHosts:` key was found+ * - allowsAll — value is `true` or the `'all'` sentinel (every host accepted)+ * - hosts — string entries when the value is an array literal+ */+export function parseAllowedHosts(source) {+ const code = stripComments(source);+ const m = code.match(ALLOWED_HOSTS_VALUE_RE);+ if (!m) return { present: false, allowsAll: false, hosts: [] };+ const raw = m[1];+ if (raw === 'true') return { present: true, allowsAll: true, hosts: [], raw };+ if (raw === 'false') return { present: true, allowsAll: false, hosts: [], raw };+ if (/^['"`]all['"`]$/.test(raw)) return { present: true, allowsAll: true, hosts: [], raw };+ const hosts = [...raw.matchAll(/['"`]([^'"`]+)['"`]/g)].map((x) => x[1]);+ return { present: true, allowsAll: false, hosts, raw };+}++/** True when `hostname` is an IPv4/IPv6 literal or bracketed IPv6. */+function isIpLiteral(hostname) {+ const h = hostname.replace(/^\[|\]$/g, '');+ if (/^\d{1,3}(\.\d{1,3}){3}$/.test(h)) return true; // IPv4+ if (h.includes(':') && /^[0-9a-f:]+$/i.test(h)) return true; // IPv6+ return false;+}++/**+ * Decide whether Vite would accept a request for `hostname` given a parsed+ * allowedHosts setting. Mirrors Vite's own host-check rules:+ * - `localhost` and IP literals are always accepted (Vite never blocks them);+ * - `allowedHosts: true` / `'all'` accepts everything;+ * - an exact match in the array accepts that host;+ * - a leading-dot entry (`.ts.net`) accepts the bare domain and any subdomain.+ */+export function hostIsAllowed(parsed, hostname) {+ if (!hostname) return false;+ const h = String(hostname).toLowerCase();+ // Vite always allows loopback/IP hosts regardless of allowedHosts — this is+ // why "launch by IP" is a valid escape hatch for the user.+ if (h === 'localhost' || h.endsWith('.localhost') || isIpLiteral(h)) return true;+ if (parsed.allowsAll) return true;+ return (parsed.hosts || []).some((entry) => {+ const e = String(entry).toLowerCase();+ if (e === h) return true;+ if (e.startsWith('.')) return h === e.slice(1) || h.endsWith(e);+ return false;+ });+}++// Common locations a vite config sits in relative to an app's repo root. Many+// PortOS-managed apps are monorepos whose Vite client lives under `client/`+// (PortOS itself does), so the repo root alone misses them.+const VITE_CONFIG_SUBDIRS = ['', 'client', 'frontend', 'web', 'app', 'ui', 'apps/web', 'packages/client'];++/**+ * Locate an app's vite config on disk. Returns `{ path, filename, content, dir }`+ * for the first match, or `null` when no vite config is found (a non-Vite app,+ * or one whose Dev UI launches a different dev server).+ *+ * Searches `extraDirs` first (e.g. the cwd of the app's detected Vite process),+ * then the repo root and a set of common subdirectories.+ */+export async function findViteConfig(repoPath, { extraDirs = [] } = {}) {+ const dirs = [];+ for (const d of extraDirs) if (d && !dirs.includes(d)) dirs.push(d);+ if (repoPath) {+ for (const sub of VITE_CONFIG_SUBDIRS) {+ const d = sub ? join(repoPath, sub) : repoPath;+ if (!dirs.includes(d)) dirs.push(d);+ }+ }+ for (const dir of dirs) {+ for (const filename of VITE_CONFIG_FILENAMES) {+ const path = join(dir, filename);+ const content = await tryReadFile(path);+ if (content != null) return { path, filename, content, dir };+ }+ }+ return null;+}++/**+ * Deterministically rewrite a vite config so every host is allowed+ * (`server.allowedHosts: true`). Handles the three common shapes:+ * 1. An existing `allowedHosts:` value → replace it with `true`.+ * 2. An existing `server: { … }` block → inject `allowedHosts: true,`.+ * 3. A `defineConfig({ … })` / `defineConfig(() => ({ … }))` object with no+ * `server` block → inject `server: { allowedHosts: true },`.+ *+ * Bails with `{ ok: false, reason }` when the shape is ambiguous (multiple+ * `allowedHosts`/`server` blocks) or unrecognized, so the caller falls back to+ * an LLM fix rather than risk corrupting the config.+ */+export function rewriteAllowedHosts(source) {+ const original = String(source ?? '');+ const code = stripComments(original);++ // Case 1: an allowedHosts key already exists. Replace its value in the+ // ORIGINAL text (preserving comments) — but only when unambiguous.+ const allowedHostsCount = (code.match(/allowedHosts\s*:/g) || []).length;+ if (allowedHostsCount > 1) {+ return { ok: false, reason: 'multiple allowedHosts entries — ambiguous to rewrite safely' };+ }+ if (allowedHostsCount === 1) {+ if (/allowedHosts\s*:\s*(?:true|'all'|"all"|`all`)/.test(code)) {+ return { ok: false, reason: 'already allows all hosts' };+ }+ const content = original.replace(ALLOWED_HOSTS_VALUE_RE, 'allowedHosts: true');+ if (content === original) {+ return { ok: false, reason: 'allowedHosts present in an unrecognized form' };+ }+ return { ok: true, content, strategy: 'replace-value' };+ }++ // Case 2: a single server: { … } block exists — inject the key after `{`.+ const serverBlockCount = (code.match(/\bserver\s*:\s*\{/g) || []).length;+ if (serverBlockCount > 1) {+ return { ok: false, reason: 'multiple server blocks — ambiguous to rewrite safely' };+ }+ if (serverBlockCount === 1) {+ const content = original.replace(+ /(\bserver\s*:\s*\{)/,+ '$1\n allowedHosts: true,'+ );+ return { ok: true, content, strategy: 'inject-into-server' };+ }++ // Case 3: a defineConfig({ … }) object (literal or arrow-returned) with no+ // server block — add one. Matches `defineConfig({`, `defineConfig(() => ({`,+ // and `defineConfig(async ({ mode }) => ({`.+ const objectStart = code.match(+ /defineConfig\s*\(\s*(?:async\s*)?(?:\([^)]*\)\s*=>\s*)?\(?\s*\{/+ );+ if (objectStart) {+ const content = original.replace(+ /(defineConfig\s*\(\s*(?:async\s*)?(?:\([^)]*\)\s*=>\s*)?\(?\s*\{)/,+ '$1\n server: { allowedHosts: true },'+ );+ if (content !== original) {+ return { ok: true, content, strategy: 'inject-server-block' };+ }+ }++ return { ok: false, reason: 'could not locate a config object to edit' };+}++/**+ * One-shot status for a repo + hostname: locate the vite config, parse its+ * allowedHosts, and report whether `hostname` would be accepted plus whether a+ * deterministic auto-fix is possible. Pure aside from the config read.+ */+export async function checkViteHost(repoPath, hostname, { extraDirs = [] } = {}) {+ const config = await findViteConfig(repoPath, { extraDirs });+ if (!config) {+ return {+ hasViteConfig: false,+ configPath: null,+ filename: null,+ allowedHostsPresent: false,+ allowsAll: false,+ hosts: [],+ hostAllowed: false,+ canAutoFix: false+ };+ }+ const parsed = parseAllowedHosts(config.content);+ const hostAllowed = hostIsAllowed(parsed, hostname);+ const rewrite = hostAllowed ? { ok: false } : rewriteAllowedHosts(config.content);+ return {+ hasViteConfig: true,+ configPath: config.path,+ filename: config.filename,+ allowedHostsPresent: parsed.present,+ allowsAll: parsed.allowsAll,+ hosts: parsed.hosts,+ hostAllowed,+ canAutoFix: !hostAllowed && rewrite.ok === true+ };+}diff --git a/server/lib/viteAllowedHosts.test.js b/server/lib/viteAllowedHosts.test.jsnew file mode 100644index 0000000000..003d783f83--- /dev/null+++ b/server/lib/viteAllowedHosts.test.js@@ -0,0 +1,158 @@+import { describe, it, expect } from 'vitest';+import {+ parseAllowedHosts,+ hostIsAllowed,+ rewriteAllowedHosts+} from './viteAllowedHosts.js';++describe('parseAllowedHosts', () => {+ it('reports absent when there is no allowedHosts key', () => {+ const p = parseAllowedHosts('export default defineConfig({ server: { port: 5173 } })');+ expect(p).toMatchObject({ present: false, allowsAll: false, hosts: [] });+ });++ it('detects allowedHosts: true as allow-all', () => {+ const p = parseAllowedHosts('server: { allowedHosts: true }');+ expect(p).toMatchObject({ present: true, allowsAll: true });+ });++ it("detects the 'all' string sentinel", () => {+ const p = parseAllowedHosts("server: { allowedHosts: 'all' }");+ expect(p.allowsAll).toBe(true);+ });++ it('extracts array entries', () => {+ const p = parseAllowedHosts("server: { allowedHosts: ['.ts.net', 'localhost'] }");+ expect(p).toMatchObject({ present: true, allowsAll: false, hosts: ['.ts.net', 'localhost'] });+ });++ it('ignores a commented-out allowedHosts', () => {+ const src = `server: {+ // allowedHosts: true,+ port: 5173+ }`;+ expect(parseAllowedHosts(src).present).toBe(false);+ });++ it('ignores a block-commented allowedHosts', () => {+ const src = 'server: { /* allowedHosts: true */ port: 5173 }';+ expect(parseAllowedHosts(src).present).toBe(false);+ });+});++describe('hostIsAllowed', () => {+ const all = { allowsAll: true, hosts: [] };+ const none = { allowsAll: false, hosts: [] };+ const tailnet = { allowsAll: false, hosts: ['.ts.net'] };++ it('blocks an unknown host when allowedHosts is empty', () => {+ expect(hostIsAllowed(none, 'box.taile8179.ts.net')).toBe(false);+ });++ it('allows everything when allowsAll', () => {+ expect(hostIsAllowed(all, 'null.taile8179.ts.net')).toBe(true);+ });++ it('always allows localhost regardless of config', () => {+ expect(hostIsAllowed(none, 'localhost')).toBe(true);+ });++ it('always allows IPv4 literals (the launch-by-IP escape hatch)', () => {+ expect(hostIsAllowed(none, '100.64.0.1')).toBe(true);+ });++ it('allows an IPv6 literal', () => {+ expect(hostIsAllowed(none, 'fd7a:115c:a1e0::1')).toBe(true);+ });++ it('matches a leading-dot suffix entry against subdomains', () => {+ expect(hostIsAllowed(tailnet, 'box.taile8179.ts.net')).toBe(true);+ expect(hostIsAllowed(tailnet, 'null.taile8179.ts.net')).toBe(true);+ });++ it('matches a leading-dot entry against the bare domain', () => {+ expect(hostIsAllowed(tailnet, 'ts.net')).toBe(true);+ });++ it('does not match an unrelated domain', () => {+ expect(hostIsAllowed(tailnet, 'evil.example.com')).toBe(false);+ });++ it('matches an exact array entry', () => {+ expect(hostIsAllowed({ allowsAll: false, hosts: ['box.taile8179.ts.net'] }, 'box.taile8179.ts.net')).toBe(true);+ });++ it('returns false for an empty hostname', () => {+ expect(hostIsAllowed(all, '')).toBe(false);+ });+});++describe('rewriteAllowedHosts', () => {+ it('replaces an existing array value with true', () => {+ const src = "export default defineConfig({ server: { allowedHosts: ['localhost'] } })";+ const out = rewriteAllowedHosts(src);+ expect(out.ok).toBe(true);+ expect(out.strategy).toBe('replace-value');+ expect(out.content).toContain('allowedHosts: true');+ expect(out.content).not.toContain("['localhost']");+ });++ it('replaces allowedHosts: false with true', () => {+ const out = rewriteAllowedHosts('server: { allowedHosts: false }');+ expect(out.ok).toBe(true);+ expect(out.content).toContain('allowedHosts: true');+ });++ it('bails when the config already allows all hosts', () => {+ const out = rewriteAllowedHosts('server: { allowedHosts: true }');+ expect(out.ok).toBe(false);+ expect(out.reason).toMatch(/already allows all/);+ });++ it('injects allowedHosts into an existing server block', () => {+ const src = `import { defineConfig } from 'vite';+export default defineConfig({+ server: {+ port: 5173,+ },+});`;+ const out = rewriteAllowedHosts(src);+ expect(out.ok).toBe(true);+ expect(out.strategy).toBe('inject-into-server');+ expect(out.content).toContain('allowedHosts: true,');+ expect(out.content).toContain('port: 5173');+ });++ it('injects a server block into a defineConfig object literal', () => {+ const src = `import { defineConfig } from 'vite';+export default defineConfig({+ plugins: [],+});`;+ const out = rewriteAllowedHosts(src);+ expect(out.ok).toBe(true);+ expect(out.strategy).toBe('inject-server-block');+ expect(out.content).toContain('server: { allowedHosts: true }');+ });++ it('injects a server block into an arrow-returned config object', () => {+ const src = `import { defineConfig } from 'vite';+export default defineConfig(({ mode }) => ({+ plugins: [],+}));`;+ const out = rewriteAllowedHosts(src);+ expect(out.ok).toBe(true);+ expect(out.content).toContain('server: { allowedHosts: true }');+ });++ it('bails on multiple server blocks as ambiguous', () => {+ const src = `defineConfig({ server: { port: 1 }, test: { server: { port: 2 } } })`;+ const out = rewriteAllowedHosts(src);+ expect(out.ok).toBe(false);+ expect(out.reason).toMatch(/multiple server blocks/);+ });++ it('bails when it cannot find a config object', () => {+ const out = rewriteAllowedHosts('const x = 1; module.exports = x;');+ expect(out.ok).toBe(false);+ });+});diff --git a/server/routes/apps.js b/server/routes/apps.jsindex e9e3d74f31..17eefb2bc8 100644--- a/server/routes/apps.js+++ b/server/routes/apps.js@@ -16,6 +16,7 @@ import * as git from '../services/git.js';import { parseCronToNextRun } from '../services/eventScheduler.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { parseEcosystemFromPath, usesPm2, writeEcosystemPorts } from '../services/streamingDetect.js';+import { checkViteHost, findViteConfig, rewriteAllowedHosts } from '../lib/viteAllowedHosts.js';import { detectAppIcon, getIconContentType, isUsableSvg } from '../services/appIconDetect.js';import { hasDeployScript } from '../services/appDeployer.js';import { checkScripts, installScripts, XCODE_SCRIPT_NAMES } from '../services/xcodeScripts.js';@@ -303,6 +304,91 @@ router.post('/:id/upgrade-tls', loadApp, asyncHandler(async (req, res) => {});}));+// GET /api/apps/:id/vite-host-check?host=<hostname> - Report whether the app's+// Vite dev server would accept requests for `host` (the Tailscale MagicDNS / IP+// name PortOS is served under). Vite ≥5 blocks unknown hosts, so launching an+// app's Dev UI over Tailscale fails until that host is allow-listed. This drives+// the Dev-UI launch guard and the remediation UI in the app detail view.+router.get('/:id/vite-host-check', loadApp, asyncHandler(async (req, res) => {+ const app = req.loadedApp;+ const host = typeof req.query.host === 'string' ? req.query.host.trim() : '';+ const extraDirs = (app.processes || []).map((p) => p.cwd).filter(Boolean);+ const status = await checkViteHost(app.repoPath, host, { extraDirs });+ res.json({ host, ...status });+}));++// POST /api/apps/:id/fix-vite-hosts - Remediate the Vite allowedHosts block.+// mode 'allow-all' (default): deterministically rewrite the app's vite.config+// to `server.allowedHosts: true`. Safe for a private Tailscale network and+// the most reliable fix; bails (422) when the config shape is too unusual to+// edit without risking corruption, steering the user to the AI path.+// mode 'ai': spawn a CoS agent that edits the app's vite.config in its OWN+// repo (honoring the Scope Boundary) — handles arbitrary config shapes and+// can create a vite.config when none exists.+const fixViteHostsSchema = z.object({+ mode: z.enum(['allow-all', 'ai']).default('allow-all'),+ host: z.string().trim().optional()+});+router.post('/:id/fix-vite-hosts', loadApp, asyncHandler(async (req, res) => {+ const { mode, host } = validateRequest(fixViteHostsSchema, req.body);+ const app = req.loadedApp;+ if (!app.repoPath || !await pathExists(app.repoPath)) {+ throw new ServerError('App repository path not found', { status: 400, code: 'PATH_NOT_FOUND' });+ }+ const extraDirs = (app.processes || []).map((p) => p.cwd).filter(Boolean);+ const config = await findViteConfig(app.repoPath, { extraDirs });++ if (mode === 'ai') {+ if (!cos.isRunning()) {+ throw new ServerError(+ 'CoS is not running — start it to use AI remediation, or use the automatic fix.',+ { status: 409, code: 'COS_NOT_RUNNING' }+ );+ }+ const where = config ? config.path : `${app.repoPath} (no vite.config found — create one)`;+ const task = await cos.addTask({+ description: `Allow the Tailscale host in ${app.name}'s Vite config so its Dev UI loads`,+ priority: 'MEDIUM',+ app: app.id,+ approvalRequired: true,+ context: [+ `The app "${app.name}" is launched through PortOS over a Tailscale MagicDNS hostname` ++ (host ? ` ("${host}")` : '') + '.',+ 'Launching its Vite Dev UI fails with: "Blocked request. This host is not allowed."',+ `Fix: edit ${where} so the dev server's \`server.allowedHosts\` accepts that host.`,+ 'Prefer `server.allowedHosts: true` (allow all — this app runs only on a private Tailscale network),',+ 'or add the specific host plus a leading-dot `.ts.net` suffix entry. Leave the rest of the config intact.',+ 'If no vite config exists, create a minimal vite.config.js that sets server.allowedHosts.'+ ].join('\n')+ }, 'internal');+ return res.json({ ok: true, mode: 'ai', taskId: task.id, configPath: config?.path || null });+ }++ // mode === 'allow-all': deterministic rewrite.+ if (!config) {+ throw new ServerError(+ 'No vite.config found to edit automatically — use AI remediation, which can create one.',+ { status: 422, code: 'NO_VITE_CONFIG' }+ );+ }+ const rewrite = rewriteAllowedHosts(config.content);+ if (!rewrite.ok) {+ throw new ServerError(+ `Could not safely auto-edit ${config.filename}: ${rewrite.reason}. Use AI remediation instead.`,+ { status: 422, code: 'AUTO_FIX_UNSAFE' }+ );+ }+ await atomicWrite(config.path, rewrite.content);+ res.json({+ ok: true,+ mode: 'allow-all',+ configPath: config.path,+ filename: config.filename,+ strategy: rewrite.strategy,+ note: 'Restart the app (or its Vite dev server) for the change to take effect.'+ });+}));+// GET /api/apps/:id/icon - Serve the app's detected icon imagerouter.get('/:id/icon', loadApp, asyncHandler(async (req, res) => {const app = req.loadedApp;diff --git a/server/routes/apps.test.js b/server/routes/apps.test.jsindex 4d103a611a..aa3fc52bf4 100644--- a/server/routes/apps.test.js+++ b/server/routes/apps.test.js@@ -53,7 +53,9 @@ vi.mock('../services/appIconDetect.js', () => ({vi.mock('../services/cos.js', () => ({getAgents: vi.fn().mockResolvedValue([]),getAgentDates: vi.fn().mockResolvedValue([]),- getAgentsByDate: vi.fn().mockResolvedValue([])+ getAgentsByDate: vi.fn().mockResolvedValue([]),+ isRunning: vi.fn().mockReturnValue(true),+ addTask: vi.fn().mockResolvedValue({ id: 'task-vite-1' })}));vi.mock('../services/git.js', () => ({@@ -80,9 +82,10 @@ import * as appsService from '../services/apps.js';import * as pm2Service from '../services/pm2.js';import * as history from '../services/history.js';import * as streamingDetect from '../services/streamingDetect.js';+import * as cos from '../services/cos.js';import { detectAppIcon, getIconContentType, isUsableSvg } from '../services/appIconDetect.js';import { installScripts } from '../services/xcodeScripts.js';-import { writeFileSync, mkdirSync, rmSync } from 'fs';+import { writeFileSync, readFileSync, mkdirSync, rmSync } from 'fs';import { join } from 'path';import { tmpdir } from 'os';@@ -924,4 +927,118 @@ describe('Apps Routes', () => {expect(response.body.code).toBe('PATH_NOT_FOUND');});});++ describe('Vite Dev-UI host guard', () => {+ let repoDir;++ beforeEach(() => {+ repoDir = join(tmpdir(), `vite-host-${Math.random().toString(36).slice(2)}`);+ mkdirSync(repoDir, { recursive: true });+ });++ afterAll(() => {+ // best-effort cleanup of any straggler temp dirs is handled per-test below+ });++ const writeViteConfig = (content) =>+ writeFileSync(join(repoDir, 'vite.config.js'), content);++ describe('GET /:id/vite-host-check', () => {+ it('reports hostAllowed=false + canAutoFix for a Vite app missing the host', async () => {+ writeViteConfig("export default { server: { port: 5173 } };");+ appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'A', repoPath: repoDir });++ const response = await request(app)+ .get('/api/apps/app-001/vite-host-check?host=null.taile8179.ts.net');++ expect(response.status).toBe(200);+ expect(response.body.hasViteConfig).toBe(true);+ expect(response.body.hostAllowed).toBe(false);+ expect(response.body.canAutoFix).toBe(true);+ rmSync(repoDir, { recursive: true, force: true });+ });++ it('reports hostAllowed=true when the config already allows the tailnet', async () => {+ writeViteConfig("export default { server: { allowedHosts: ['.ts.net'] } };");+ appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'A', repoPath: repoDir });++ const response = await request(app)+ .get('/api/apps/app-001/vite-host-check?host=box.taile8179.ts.net');++ expect(response.status).toBe(200);+ expect(response.body.hostAllowed).toBe(true);+ rmSync(repoDir, { recursive: true, force: true });+ });++ it('reports hasViteConfig=false when the app has no vite config', async () => {+ appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'A', repoPath: repoDir });++ const response = await request(app)+ .get('/api/apps/app-001/vite-host-check?host=box.taile8179.ts.net');++ expect(response.status).toBe(200);+ expect(response.body.hasViteConfig).toBe(false);+ rmSync(repoDir, { recursive: true, force: true });+ });+ });++ describe('POST /:id/fix-vite-hosts', () => {+ it('allow-all rewrites the config to allowedHosts: true', async () => {+ writeViteConfig("export default { server: { port: 5173 } };");+ appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'A', repoPath: repoDir });++ const response = await request(app)+ .post('/api/apps/app-001/fix-vite-hosts')+ .send({ mode: 'allow-all', host: 'null.taile8179.ts.net' });++ expect(response.status).toBe(200);+ expect(response.body.strategy).toBe('inject-into-server');+ const written = readFileSync(join(repoDir, 'vite.config.js'), 'utf-8');+ expect(written).toContain('allowedHosts: true');+ rmSync(repoDir, { recursive: true, force: true });+ });++ it('allow-all returns 422 when no vite config exists', async () => {+ appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'A', repoPath: repoDir });++ const response = await request(app)+ .post('/api/apps/app-001/fix-vite-hosts')+ .send({ mode: 'allow-all' });++ expect(response.status).toBe(422);+ expect(response.body.code).toBe('NO_VITE_CONFIG');+ rmSync(repoDir, { recursive: true, force: true });+ });++ it('ai mode queues a CoS task targeting the app', async () => {+ appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'A', repoPath: repoDir });+ cos.isRunning.mockReturnValue(true);++ const response = await request(app)+ .post('/api/apps/app-001/fix-vite-hosts')+ .send({ mode: 'ai', host: 'null.taile8179.ts.net' });++ expect(response.status).toBe(200);+ expect(response.body.taskId).toBe('task-vite-1');+ expect(cos.addTask).toHaveBeenCalledWith(+ expect.objectContaining({ app: 'app-001', approvalRequired: true }),+ 'internal'+ );+ rmSync(repoDir, { recursive: true, force: true });+ });++ it('ai mode returns 409 when CoS is not running', async () => {+ appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'A', repoPath: repoDir });+ cos.isRunning.mockReturnValue(false);++ const response = await request(app)+ .post('/api/apps/app-001/fix-vite-hosts')+ .send({ mode: 'ai' });++ expect(response.status).toBe(409);+ expect(response.body.code).toBe('COS_NOT_RUNNING');+ rmSync(repoDir, { recursive: true, force: true });+ });+ });+ });});