Skip to content

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

feat(apps): opt-in HTTPS for managed apps via Upgrade to TLS

Adam Eivy75f313919a51
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 27c80ad631..e716f55691 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -1,5 +1,7 @@
## Added
+- **Opt-in HTTPS for managed apps via PortOS "Upgrade to TLS" action** — PortOS's own HTTPS+loopback-HTTP setup (previously inlined in `server/index.js`) is now a zero-dep helper module at `lib/tailscale-https.js` exporting `createTailscaleServers`, `watchCertReload`, and `hasTailscaleCert`. PortOS itself now uses the helper (dogfood). App schema gains an optional `tlsPort` field — when set, the Launch button on the app grid and detail view opens `https://<host>:<tlsPort>/` as the primary action (with plain HTTP demoted to a muted secondary button, and Dev UI still reachable when `devUiPort` is set). The PortOS baseline app auto-reflects `tlsPort: PORTS.API` whenever a cert is present on disk, so the Launch button targets the correct scheme out of the box. New app-manager action **Edit → Upgrade to TLS**: pick a TLS port (defaults to `uiPort + 1000`), PortOS copies `lib/tailscale-https.js` into the target app's repo at `<repoPath>/lib/tailscale-https.js` and records the `tlsPort` in `apps.json`; backend refuses overwrite unless the user clicks the "Overwrite existing" button that surfaces on collision. The response returns a preformatted snippet (with a copy button) showing how to wire the helper into the app's server entry — the wire-up is deliberately left to the user to avoid mis-patching arbitrary server files. The helper is zero-dep by design: apps that adopt it stay self-contained and runnable without PortOS. To share the single Tailscale Let's Encrypt cert across apps, each app points `CERT_DIR` at (or symlinks) `data/certs` in the PortOS install. New backend route `POST /api/apps/:id/upgrade-tls { tlsPort, force }` (409 `ALREADY_EXISTS` when a helper already lives in the target). Client launch URLs consolidated into `client/src/services/appUrls.js` (`getLaunchUrls`, `getPrimaryLaunchUrl`) so tile and detail views build URLs through one function. `apiCore.request()` now enriches thrown errors with `err.code` + `err.status` so callers can branch on server error codes.
+
- **Cyber Muse CoS avatar — GLB-backed holographic head** — new `muse` option in Settings → CoS → Appearance. Rather than assembling sphere primitives into a face (uncanny) or displacing a sphere point cloud (unreadable silhouette), the avatar loads a user-supplied `data/avatar/model.glb` through a new `/api/avatar/model.glb` route (`server/routes/avatar.js`, HEAD + GET, 404 when missing, `model/gltf-binary` when present) and renders it with a holographic material treatment: dark base + state-colored emissive glow that pulses per CoS state (sleeping/thinking/coding/investigating/ideating) and sync-bobs when the CoS is speaking. Bounding-box auto-fit means any model scale/origin works — drop in a ~4MB Ready Player Me export, a Sketchfab head bust, or a Mixamo-rigged character and it centers + sizes itself. When no GLB is present, renders a clean empty-state card pointing at the target path. Piggybacks on `useGLTF` (drei) and reuses the existing Sparkles/halo/ground-glow chrome. Zod enum for `avatarStyle` gained `'muse'` in `server/routes/cosStatusRoutes.js`.
- **Loopback HTTP mirror on port 5553 when HTTPS is active** — Tailscale's Let's Encrypt cert only covers `<machine>.<tailnet>.ts.net`, so `https://localhost:5555` always tripped a cert warning. When HTTPS is active the server now also spins up a plain HTTP listener bound to `127.0.0.1:5553` that attaches to the same Express app and Socket.IO instance — `http://localhost:5553` works without cert warnings and Chrome still treats it as a secure context (so getUserMedia / mic access continues to work). Override the port via `PORTOS_HTTP_PORT`. Documented in `docs/PORTS.md`.
- **Voice agent — universal accessibility-mode DOM driving** — the voice Chief-of-Staff can now navigate to any page and operate any control by voice. New `ui_navigate` tool with a 100+ entry named-page enum ("take me to tasks" / "chief of staff agents" / "calendar" all route correctly instead of defaulting to Daily Log). New accessibility layer: a client-side DOM indexer (`client/src/services/domIndex.js`) walks `<main>` for interactable elements (tabs, buttons, links, inputs, selects, textareas, checkboxes, radios), resolves labels via the standard aria → `<label for>` → wrapping label → text → placeholder → title chain, stamps stable `data-voice-ref` refs, and caps at 200 elements. `useVoiceUiSync` hook (debounced MutationObserver scoped to `<main>`, change-detection via content signature) pushes the index to the server whenever it actually changes. Server stores the index on per-socket state and — for UI-driving user turns (verb-gated by regex to keep the 80% of turns that don't need it cheap) — injects a compact page summary into the LLM's system prompt. New tools: `ui_click` (tab/button/link by label with optional kind hint), `ui_fill` (text inputs + textareas, uses React-safe native value setter so `onChange` fires), `ui_select` (dropdowns with fuzzy option matching), `ui_check` (checkboxes + radios), `ui_list_interactables` (deep-dive fallback). Misses return a helpful `available` list to the LLM so it can self-correct instead of silently failing. **In-turn chained flows**: after a ui_* action fires, the server pauses briefly for the client to push the post-action DOM index, then attaches the fresh summary to the tool result — so multi-step flows like "create a task named Foo with description Bar" can complete in a single turn (ui_click New Task → see the modal → ui_fill Name → ui_fill Description → ui_click Save).
diff --git a/client/src/components/AppTile.jsx b/client/src/components/AppTile.jsx
index a568aa70f7..adc5b4a869 100644
--- a/client/src/components/AppTile.jsx
+++ b/client/src/components/AppTile.jsx
@@ -3,27 +3,12 @@ import { Link } from 'react-router-dom';
import StatusBadge from './StatusBadge';
import AppIcon from './AppIcon';
import * as api from '../services/api';
-import { PORTOS_APP_ID } from '../services/apiCore';
-
-// Construct app URL using current hostname (works with Tailscale)
-function getAppUrl(app) {
- if (app.uiUrl) return app.uiUrl;
- // Self-app: launch at the current origin so the scheme matches the active
- // session (HTTPS on 5555 vs HTTP loopback on 5553) instead of hard-coding
- // uiPort, which only accepts HTTPS.
- if (app.id === PORTOS_APP_ID) return window.location.origin;
- if (app.uiPort) {
- const protocol = window.location.protocol;
- const hostname = window.location.hostname;
- return `${protocol}//${hostname}:${app.uiPort}`;
- }
- return null;
-}
+import { getPrimaryLaunchUrl } from '../services/appUrls';
// Memoized component to prevent re-renders when parent polls for updates
const AppTile = memo(function AppTile({ app, onUpdate }) {
const [loading, setLoading] = useState(null);
- const appUrl = getAppUrl(app);
+ const appUrl = getPrimaryLaunchUrl(app);
const handleAction = async (action) => {
setLoading(action);
diff --git a/client/src/components/apps/AppDetailView.jsx b/client/src/components/apps/AppDetailView.jsx
index 324b42da84..96f3e9b195 100644
--- a/client/src/components/apps/AppDetailView.jsx
+++ b/client/src/components/apps/AppDetailView.jsx
@@ -6,7 +6,7 @@ import toast from '../ui/Toast';
import BrailleSpinner from '../BrailleSpinner';
import StatusBadge from '../StatusBadge';
import * as api from '../../services/api';
-import { PORTOS_APP_ID } from '../../services/apiCore';
+import { getLaunchUrls } from '../../services/appUrls';
import socket from '../../services/socket';
import { APP_DETAIL_TABS, NON_PM2_TYPES, getAppTypeLabel } from './constants';
import OverviewTab from './tabs/OverviewTab';
@@ -203,32 +203,48 @@ export default function AppDetailView() {
)}
</div>
)}
- {/* Launch UI — self-app uses current origin so the scheme matches the
- active session (HTTPS on 5555 vs HTTP loopback on 5553); uiPort alone
- hard-codes the HTTPS-only port and breaks from the HTTP mirror. */}
- {app.uiPort && app.overallStatus === 'online' && (
- <button
- onClick={() => window.open(
- app.id === PORTOS_APP_ID
- ? window.location.origin
- : `${window.location.protocol}//${window.location.hostname}:${app.uiPort}`,
- '_blank'
- )}
- className="px-2 py-1 bg-port-accent/20 text-port-accent hover:bg-port-accent/30 transition-colors rounded-lg border border-port-border flex items-center gap-1"
- >
- <ExternalLink size={14} />
- <span className="text-xs">Launch</span>
- </button>
- )}
- {app.devUiPort && app.overallStatus === 'online' && (
- <button
- onClick={() => window.open(`${window.location.protocol}//${window.location.hostname}:${app.devUiPort}`, '_blank')}
- className="px-2 py-1 bg-port-warning/20 text-port-warning hover:bg-port-warning/30 transition-colors rounded-lg border border-port-border flex items-center gap-1"
- >
- <ExternalLink size={14} />
- <span className="text-xs">Dev UI</span>
- </button>
- )}
+ {/* Launch buttons. When https is present, it's primary and http becomes a
+ muted sibling. Self-app uses current origin to avoid scheme mismatch. */}
+ {(() => {
+ if (app.overallStatus !== 'online') return null;
+ const { https, http, dev } = getLaunchUrls(app);
+ const httpIsSecondary = Boolean(https);
+ return (
+ <>
+ {https && (
+ <button
+ onClick={() => window.open(https, '_blank')}
+ className="px-2 py-1 bg-port-accent/20 text-port-accent hover:bg-port-accent/30 transition-colors rounded-lg border border-port-border flex items-center gap-1"
+ >
+ <ExternalLink size={14} />
+ <span className="text-xs">Launch (HTTPS)</span>
+ </button>
+ )}
+ {http && (
+ <button
+ onClick={() => window.open(http, '_blank')}
+ className={`px-2 py-1 transition-colors rounded-lg border border-port-border flex items-center gap-1 ${
+ httpIsSecondary
+ ? 'bg-port-border/30 text-gray-300 hover:bg-port-border/50'
+ : 'bg-port-accent/20 text-port-accent hover:bg-port-accent/30'
+ }`}
+ >
+ <ExternalLink size={14} />
+ <span className="text-xs">{httpIsSecondary ? 'HTTP' : 'Launch'}</span>
+ </button>
+ )}
+ {dev && (
+ <button
+ onClick={() => window.open(dev, '_blank')}
+ className="px-2 py-1 bg-port-warning/20 text-port-warning hover:bg-port-warning/30 transition-colors rounded-lg border border-port-border flex items-center gap-1"
+ >
+ <ExternalLink size={14} />
+ <span className="text-xs">Dev UI</span>
+ </button>
+ )}
+ </>
+ );
+ })()}
{app.buildCommand && (
<button
onClick={handleBuild}
diff --git a/client/src/components/apps/EditAppModal.jsx b/client/src/components/apps/EditAppModal.jsx
index 29d2e46a92..d6e47f69f2 100644
--- a/client/src/components/apps/EditAppModal.jsx
+++ b/client/src/components/apps/EditAppModal.jsx
@@ -1,8 +1,10 @@
import { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
-import { ChevronDown, ChevronUp, GitBranch, GitPullRequest } from 'lucide-react';
+import { ChevronDown, ChevronUp, GitBranch, GitPullRequest, Lock, Copy } from 'lucide-react';
import IconPicker from '../IconPicker';
import * as api from '../../services/api';
+import { PORTOS_APP_ID } from '../../services/apiCore';
+import toast from '../ui/Toast';
export default function EditAppModal({ app, onClose, onSave }) {
const [formData, setFormData] = useState({
@@ -12,6 +14,7 @@ export default function EditAppModal({ app, onClose, onSave }) {
uiPort: app.uiPort || '',
devUiPort: app.devUiPort || '',
apiPort: app.apiPort || '',
+ tlsPort: app.tlsPort || '',
buildCommand: app.buildCommand || '',
startCommands: (app.startCommands || []).join('\n'),
pm2ProcessNames: (app.pm2ProcessNames || []).join(', '),
@@ -34,6 +37,38 @@ export default function EditAppModal({ app, onClose, onSave }) {
});
const [saving, setSaving] = useState(false);
const [error, setError] = useState(null);
+ const [tlsUpgrading, setTlsUpgrading] = useState(false);
+ const [tlsResult, setTlsResult] = useState(null);
+ const [tlsError, setTlsError] = useState(null);
+ const tlsNeedsForce = tlsError?.code === 'ALREADY_EXISTS';
+
+ const handleUpgradeTls = async (force = false) => {
+ const port = formData.tlsPort ? parseInt(formData.tlsPort, 10)
+ : (formData.uiPort ? parseInt(formData.uiPort, 10) + 1000 : null);
+ if (!port) {
+ toast.error('Set a TLS Port first (or a UI Port to derive one)');
+ return;
+ }
+ setTlsUpgrading(true);
+ setTlsError(null);
+ try {
+ const result = await api.upgradeAppTls(app.id, { tlsPort: port, force });
+ setTlsResult(result);
+ setFormData(prev => ({ ...prev, tlsPort: String(port) }));
+ toast.success(result.overwrote
+ ? `Overwrote lib/tailscale-https.js in ${app.name}`
+ : `Copied lib/tailscale-https.js into ${app.name}`);
+ } catch (err) {
+ setTlsError(err);
+ if (err?.code === 'ALREADY_EXISTS') {
+ toast.error('lib/tailscale-https.js already exists — use "Overwrite existing" to replace');
+ } else {
+ toast.error(err?.message || 'Upgrade failed');
+ }
+ } finally {
+ setTlsUpgrading(false);
+ }
+ };
const [jiraExpanded, setJiraExpanded] = useState(app.jira?.enabled || false);
const [jiraInstances, setJiraInstances] = useState([]);
const [datadogExpanded, setDatadogExpanded] = useState(app.datadog?.enabled || false);
@@ -85,6 +120,7 @@ export default function EditAppModal({ app, onClose, onSave }) {
uiPort: formData.uiPort ? parseInt(formData.uiPort, 10) : null,
devUiPort: formData.devUiPort ? parseInt(formData.devUiPort, 10) : null,
apiPort: formData.apiPort ? parseInt(formData.apiPort, 10) : null,
+ tlsPort: formData.tlsPort ? parseInt(formData.tlsPort, 10) : null,
buildCommand: formData.buildCommand || undefined,
startCommands: formData.startCommands.split('\n').filter(Boolean),
pm2ProcessNames: formData.pm2ProcessNames
@@ -199,6 +235,70 @@ export default function EditAppModal({ app, onClose, onSave }) {
</div>
</div>
+ {app.id !== PORTOS_APP_ID && (
+ <div className="bg-port-bg/50 border border-port-border rounded-lg p-3 space-y-2">
+ <div className="flex items-center gap-2 flex-wrap">
+ <Lock size={14} className="text-port-accent" />
+ <label className="text-sm text-gray-300">TLS Port (HTTPS)</label>
+ <button
+ type="button"
+ onClick={() => handleUpgradeTls(false)}
+ disabled={tlsUpgrading}
+ className="ml-auto text-xs px-2 py-1 bg-port-accent/20 text-port-accent hover:bg-port-accent/30 rounded disabled:opacity-50"
+ >
+ {tlsUpgrading ? 'Copying helper…' : 'Upgrade to TLS'}
+ </button>
+ {tlsNeedsForce && (
+ <button
+ type="button"
+ onClick={() => handleUpgradeTls(true)}
+ disabled={tlsUpgrading}
+ className="text-xs px-2 py-1 bg-port-warning/20 text-port-warning hover:bg-port-warning/30 rounded disabled:opacity-50"
+ >
+ Overwrite existing
+ </button>
+ )}
+ </div>
+ <div className="flex gap-2 items-center">
+ <input
+ type="number"
+ value={formData.tlsPort}
+ onChange={e => {
+ setFormData({ ...formData, tlsPort: e.target.value });
+ setTlsResult(null); // snippet bakes port at upgrade time; stale once user edits
+ }}
+ className="w-32 px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden"
+ placeholder={formData.uiPort ? String(parseInt(formData.uiPort, 10) + 1000) : '4001'}
+ />
+ <span className="text-xs text-gray-500">
+ Defaults to uiPort + 1000. Leave blank to disable HTTPS launch.
+ </span>
+ </div>
+ {tlsResult && (
+ <div className="bg-port-bg border border-port-border rounded p-2 text-xs">
+ <div className="text-gray-400 mb-1">
+ Copied helper to <code className="text-port-accent">{tlsResult.helperPath}</code>.
+ Wire it up in your server entry:
+ </div>
+ <div className="relative">
+ <pre className="bg-black/40 text-gray-200 p-2 rounded overflow-x-auto font-mono text-[11px] leading-tight">{tlsResult.snippet}</pre>
+ <button
+ type="button"
+ onClick={() => { navigator.clipboard.writeText(tlsResult.snippet); toast.success('Snippet copied'); }}
+ className="absolute top-1 right-1 p-1 bg-port-border/60 hover:bg-port-border rounded"
+ aria-label="Copy snippet"
+ >
+ <Copy size={12} />
+ </button>
+ </div>
+ <div className="text-gray-500 mt-2">
+ Point <code>CERT_DIR</code> at <code>{tlsResult.certDirHint}</code> (or symlink it) to share the Tailscale cert across apps.
+ </div>
+ </div>
+ )}
+ </div>
+ )}
+
<div>
<label className="block text-sm text-gray-400 mb-1">Start Commands (one per line)</label>
<textarea
diff --git a/client/src/services/apiApps.js b/client/src/services/apiApps.js
index 35a138d611..dc177e6e8c 100644
--- a/client/src/services/apiApps.js
+++ b/client/src/services/apiApps.js
@@ -18,6 +18,11 @@ export const deleteApp = (id) => request(`/apps/${id}`, { method: 'DELETE' });
export const startApp = (id) => request(`/apps/${id}/start`, { method: 'POST' });
export const stopApp = (id) => request(`/apps/${id}/stop`, { method: 'POST' });
export const restartApp = (id) => request(`/apps/${id}/restart`, { method: 'POST' });
+export const upgradeAppTls = (id, body) => request(`/apps/${id}/upgrade-tls`, {
+ method: 'POST',
+ body: JSON.stringify(body),
+ silent: true // caller shows custom toasts (ALREADY_EXISTS steers to overwrite button)
+});
/**
* Handle PortOS self-restart: show a loading toast, poll for server recovery, then reload.
diff --git a/client/src/services/apiCore.js b/client/src/services/apiCore.js
index 54e21cb4ea..12705421ec 100644
--- a/client/src/services/apiCore.js
+++ b/client/src/services/apiCore.js
@@ -34,7 +34,10 @@ export async function request(endpoint, options = {}) {
toast.error(errorMessage);
}
}
- throw new Error(errorMessage);
+ const err = new Error(errorMessage);
+ err.code = error?.code;
+ err.status = response.status;
+ throw err;
}
// Handle 204 No Content
diff --git a/client/src/services/appUrls.js b/client/src/services/appUrls.js
new file mode 100644
index 0000000000..ab5cd96beb
--- /dev/null
+++ b/client/src/services/appUrls.js
@@ -0,0 +1,34 @@
+import { PORTOS_APP_ID } from './apiCore';
+
+/**
+ * Compute possible launch URLs for an app based on current page context.
+ * Returns `{ https, http, dev }` — any may be null. Callers pick whichever
+ * fits (tile uses the first non-null; detail view renders buttons for each).
+ *
+ * Self-app (`portos-default`) returns `{ http: origin }` only: the active
+ * session's URL already has the correct scheme and port, so rewriting would
+ * point at the wrong listener (HTTPS-only 5555 vs loopback-HTTP 5553).
+ */
+export function getLaunchUrls(app) {
+ if (!app) return { https: null, http: null, dev: null };
+ if (app.uiUrl) return { https: null, http: app.uiUrl, dev: null };
+ const hostname = window.location.hostname;
+ const protocol = window.location.protocol;
+ const dev = app.devUiPort ? `${protocol}//${hostname}:${app.devUiPort}` : null;
+ // Self-app: primary URL is the active origin (right scheme + port); dev still
+ // reflects the Vite dev server on a separate port.
+ if (app.id === PORTOS_APP_ID) {
+ return { https: null, http: window.location.origin, dev };
+ }
+ return {
+ https: app.tlsPort ? `https://${hostname}:${app.tlsPort}` : null,
+ http: app.uiPort ? `${protocol}//${hostname}:${app.uiPort}` : null,
+ dev
+ };
+}
+
+/** Pick the single best URL (HTTPS > HTTP > null) — for tile-style single-click launch. */
+export function getPrimaryLaunchUrl(app) {
+ const { https, http } = getLaunchUrls(app);
+ return https || http;
+}
diff --git a/lib/tailscale-https.js b/lib/tailscale-https.js
new file mode 100644
index 0000000000..845b70fbbc
--- /dev/null
+++ b/lib/tailscale-https.js
@@ -0,0 +1,125 @@
+/**
+ * tailscale-https — zero-dep helper that boots a Node server with HTTPS when a
+ * Tailscale (or any other) cert is present, plain HTTP otherwise, and an
+ * optional loopback-only HTTP mirror so http://localhost:<mirror> works
+ * without the cert warning you get on a Tailscale IP.
+ *
+ * Canonical source: PortOS (atomantic/PortOS:lib/tailscale-https.js).
+ * PortOS's "Upgrade to TLS" action copies this file verbatim into a managed
+ * app's repo, so apps stay self-contained and can run without PortOS.
+ *
+ * Usage:
+ * import { createTailscaleServers, watchCertReload } from './lib/tailscale-https.js';
+ *
+ * const { server, mirror, httpsEnabled } = createTailscaleServers(app, {
+ * certDir: join(DATA_DIR, 'certs')
+ * });
+ * io.attach(server);
+ * if (mirror) io.attach(mirror);
+ * server.listen(PORT, HOST, () => console.log(`up on :${PORT}`));
+ * if (mirror) mirror.listen(MIRROR_PORT, '127.0.0.1');
+ * if (httpsEnabled) watchCertReload(server, CERT_DIR);
+ *
+ * No side effects at import time — safe to require in any Node project.
+ */
+import { createServer as createHttpServer } from 'http';
+import { createServer as createHttpsServer } from 'https';
+import { existsSync, readFileSync, watch } from 'fs';
+import { join } from 'path';
+
+function loadCert(certDir) {
+ if (!certDir) return null;
+ const certPath = join(certDir, 'cert.pem');
+ const keyPath = join(certDir, 'key.pem');
+ if (!existsSync(certPath) || !existsSync(keyPath)) return null;
+ return {
+ cert: readFileSync(certPath),
+ key: readFileSync(keyPath),
+ certPath,
+ keyPath
+ };
+}
+
+/**
+ * Create the listener(s) for a Node HTTP request handler (express/koa/http).
+ * Does NOT call .listen() — the caller wires up Socket.IO / error handlers
+ * first, then listens when ready.
+ *
+ * @param {import('http').RequestListener} handler - express app or plain handler
+ * @param {object} [opts]
+ * @param {string} [opts.certDir] - dir containing cert.pem + key.pem
+ * @param {boolean} [opts.httpMirror] - when HTTPS is active, also create a plain-HTTP
+ * sibling server bound to 127.0.0.1 for local dev without cert warnings.
+ * Defaults to true when HTTPS is active.
+ * @returns {{ server: import('http').Server, mirror: import('http').Server|null, httpsEnabled: boolean }}
+ */
+export function createTailscaleServers(handler, opts = {}) {
+ const { certDir, httpMirror = true } = opts;
+ const credentials = loadCert(certDir);
+ const httpsEnabled = Boolean(credentials);
+
+ const server = httpsEnabled
+ ? createHttpsServer({ cert: credentials.cert, key: credentials.key }, handler)
+ : createHttpServer(handler);
+
+ const mirror = httpsEnabled && httpMirror ? createHttpServer(handler) : null;
+
+ return { server, mirror, httpsEnabled };
+}
+
+/**
+ * Watch the cert + key files and hot-swap the HTTPS server's SecureContext
+ * when they change. Use this when an external process (Tailscale CLI, certbot,
+ * ACME client) rotates the cert — new TLS handshakes pick up the renewed cert
+ * without a restart. Returns an unsubscribe fn.
+ *
+ * @param {import('https').Server} httpsServer
+ * @param {string} certDir
+ * @param {object} [opts]
+ * @param {(msg: string) => void} [opts.log=console.log]
+ * @returns {() => void} stop — cancels the watchers
+ */
+export function watchCertReload(httpsServer, certDir, opts = {}) {
+ const log = opts.log || console.log;
+ if (!httpsServer || typeof httpsServer.setSecureContext !== 'function') {
+ return () => {};
+ }
+ const certPath = join(certDir, 'cert.pem');
+ const keyPath = join(certDir, 'key.pem');
+
+ let pending = null;
+ const reload = () => {
+ clearTimeout(pending);
+ pending = setTimeout(() => {
+ if (!existsSync(certPath) || !existsSync(keyPath)) return;
+ try {
+ httpsServer.setSecureContext({
+ cert: readFileSync(certPath),
+ key: readFileSync(keyPath)
+ });
+ log(`🔒 cert hot-reloaded from ${certDir}`);
+ } catch (err) {
+ log(`⚠️ cert reload failed: ${err.message}`);
+ }
+ }, 500);
+ };
+
+ // fs.watch debounced — Tailscale rewrites both files, we get a burst of events
+ const watchers = [
+ watch(certPath, reload),
+ watch(keyPath, reload)
+ ];
+
+ return () => {
+ clearTimeout(pending);
+ watchers.forEach(w => w.close());
+ };
+}
+
+/**
+ * True when `certDir` contains a usable cert+key pair.
+ * @param {string} certDir
+ */
+export function hasTailscaleCert(certDir) {
+ return Boolean(loadCert(certDir));
+}
diff --git a/server/index.js b/server/index.js
index f9fdd500f3..0ac3c6edf0 100644
--- a/server/index.js
+++ b/server/index.js
@@ -1,13 +1,12 @@
import express from 'express';
-import { createServer as createHttpServer } from 'http';
-import { createServer as createHttpsServer } from 'https';
import { Server } from 'socket.io';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import { PATHS } from './lib/fileUtils.js';
import { PORTS } from './lib/ports.js';
-import { existsSync, readFileSync } from 'fs';
+import { existsSync } from 'fs';
import { readFile, unlink } from 'fs/promises';
+import { createTailscaleServers } from '../lib/tailscale-https.js';
import alertsRoutes from './routes/alerts.js';
import appleHealthRoutes from './routes/appleHealth.js';
@@ -115,15 +114,10 @@ const app = express();
const PORT = process.env.PORT || 5555;
const HOST = process.env.HOST || '0.0.0.0';
-// Self-signed TLS: if cert files exist (generated by scripts/setup-cert.js),
-// serve HTTPS so getUserMedia and other secure-context APIs work over the
-// Tailscale IP. Otherwise fall back to plain HTTP.
-const CERT_PATH = join(PATHS.data, 'certs', 'cert.pem');
-const KEY_PATH = join(PATHS.data, 'certs', 'key.pem');
-const httpsEnabled = existsSync(CERT_PATH) && existsSync(KEY_PATH);
-const httpServer = httpsEnabled
- ? createHttpsServer({ cert: readFileSync(CERT_PATH), key: readFileSync(KEY_PATH) }, app)
- : createHttpServer(app);
+// Delegates HTTPS / HTTP-mirror wiring to lib/tailscale-https.js — see there.
+const CERT_DIR = join(PATHS.data, 'certs');
+const { server: httpServer, mirror: localHttpServer, httpsEnabled } =
+ createTailscaleServers(app, { certDir: CERT_DIR });
const scheme = httpsEnabled ? 'https' : 'http';
// Socket.IO with relative path support for Tailscale
@@ -420,21 +414,18 @@ ensureSelf()
console.log(`⚠️ HTTP only — getUserMedia (mic) will not work over Tailscale IP. Run "npm run setup:cert" to enable HTTPS.`);
} else {
initCertRenewer(httpServer);
- // Tailscale's Let's Encrypt cert only covers <machine>.<tailnet>.ts.net,
- // so https://localhost:PORT fails the cert check. Spin up a loopback-
- // only HTTP listener on a sibling port for local dev/debugging —
- // Chrome treats http://localhost as a secure context so getUserMedia
- // still works. Same Express app + same Socket.IO instance (via
- // io.attach), so routes and websocket events are identical.
+ // Loopback-HTTP mirror (created by createTailscaleServers) — attach
+ // Socket.IO to the same instance so websocket events are identical.
const localHttpPort = Number(process.env.PORTOS_HTTP_PORT) || PORTS.API_LOCAL;
- const localServer = createHttpServer(app);
- io.attach(localServer);
- localServer.listen(localHttpPort, '127.0.0.1', () => {
- console.log(`🔓 Local HTTP also at http://localhost:${localHttpPort} (loopback only, no cert warnings)`);
- });
- localServer.on('error', (err) => {
- console.warn(`⚠️ Local HTTP fallback on :${localHttpPort} failed: ${err.message} — Tailscale HTTPS still active`);
- });
+ if (localHttpServer) {
+ io.attach(localHttpServer);
+ localHttpServer.listen(localHttpPort, '127.0.0.1', () => {
+ console.log(`🔓 Local HTTP also at http://localhost:${localHttpPort} (loopback only, no cert warnings)`);
+ });
+ localHttpServer.on('error', (err) => {
+ console.warn(`⚠️ Local HTTP fallback on :${localHttpPort} failed: ${err.message} — Tailscale HTTPS still active`);
+ });
+ }
}
// Set up process error handlers with io instance
diff --git a/server/lib/validation.js b/server/lib/validation.js
index a5ff4145c7..1ca8c182c1 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -180,6 +180,10 @@ export const appSchema = z.object({
uiPort: z.number().int().min(1).max(65535).nullable().optional(),
devUiPort: z.number().int().min(1).max(65535).nullable().optional(),
apiPort: z.number().int().min(1).max(65535).nullable().optional(),
+ // Optional HTTPS port — set by the "Upgrade to TLS" action. When present,
+ // the Launch button prefers `https://<host>:<tlsPort>/` over the plain
+ // uiPort. See lib/tailscale-https.js for the helper apps use.
+ tlsPort: z.number().int().min(1).max(65535).nullable().optional(),
buildCommand: z.string().max(200).optional(),
uiUrl: z.string().url().optional(),
startCommands: z.array(z.string()).optional(),
diff --git a/server/routes/apps.js b/server/routes/apps.js
index 144f7991e0..e5980048f9 100644
--- a/server/routes/apps.js
+++ b/server/routes/apps.js
@@ -1,7 +1,8 @@
import { Router } from 'express';
import { spawn } from 'child_process';
-import { readFile, writeFile, stat, access } from 'fs/promises';
+import { readFile, writeFile, stat, access, mkdir } from 'fs/promises';
import { join, resolve } from 'path';
+import { PATHS } from '../lib/fileUtils.js';
import * as appsService from '../services/apps.js';
import { notifyAppsChanged, PORTOS_APP_ID } from '../services/apps.js';
import * as pm2Service from '../services/pm2.js';
@@ -208,6 +209,70 @@ router.post('/:id/xcode-scripts/install', loadApp, asyncHandler(async (req, res)
res.json(result);
}));
+// POST /api/apps/:id/upgrade-tls - Copy the tailscale-https helper into the target app's
+// repo and record tlsPort in apps.json so the Launch button prefers HTTPS. The app still
+// needs to be edited manually to call createTailscaleServers() — we return an example
+// snippet in the response so the frontend can surface it. Refuse to overwrite an existing
+// helper unless `force: true` is set; this way a user who has customized their copy keeps it.
+const upgradeTlsSchema = z.object({
+ tlsPort: z.number().int().min(1).max(65535),
+ force: z.boolean().optional()
+});
+router.post('/:id/upgrade-tls', loadApp, asyncHandler(async (req, res) => {
+ const { tlsPort, force } = validateRequest(upgradeTlsSchema, req.body);
+ const app = req.loadedApp;
+ if (app.id === PORTOS_APP_ID) {
+ throw new ServerError('PortOS itself already uses the helper — nothing to upgrade', {
+ status: 400, code: 'ALREADY_UPGRADED'
+ });
+ }
+ if (!app.repoPath || !await pathExists(app.repoPath)) {
+ throw new ServerError('App repository path not found', { status: 400, code: 'PATH_NOT_FOUND' });
+ }
+ const sourcePath = join(PATHS.root, 'lib', 'tailscale-https.js');
+ const targetDir = join(app.repoPath, 'lib');
+ const targetPath = join(targetDir, 'tailscale-https.js');
+
+ const alreadyExists = await pathExists(targetPath);
+ if (alreadyExists && !force) {
+ throw new ServerError(
+ 'A tailscale-https.js already exists in the target app. Pass force:true to overwrite.',
+ { status: 409, code: 'ALREADY_EXISTS' }
+ );
+ }
+
+ const [helperSource] = await Promise.all([
+ readFile(sourcePath, 'utf-8'),
+ mkdir(targetDir, { recursive: true })
+ ]);
+ await writeFile(targetPath, helperSource);
+
+ await appsService.updateApp(app.id, { tlsPort });
+
+ const snippet = [
+ `// In your server entry, replace the direct http.createServer(app).listen(...) with:`,
+ `import { createTailscaleServers, watchCertReload } from './lib/tailscale-https.js';`,
+ ``,
+ `const CERT_DIR = process.env.CERT_DIR || '/path/to/data/certs'; // shared with PortOS`,
+ `const { server, mirror, httpsEnabled } = createTailscaleServers(app, { certDir: CERT_DIR });`,
+ `// io.attach(server); if (mirror) io.attach(mirror); // when using Socket.IO`,
+ `server.listen(${tlsPort}, '0.0.0.0');`,
+ `// Optional: bind the HTTP mirror on a port of your choosing (127.0.0.1 only).`,
+ `// if (mirror) mirror.listen(<your-mirror-port>, '127.0.0.1');`,
+ `if (httpsEnabled) watchCertReload(server, CERT_DIR);`
+ ].join('\n');
+
+ res.json({
+ ok: true,
+ helperPath: targetPath,
+ overwrote: alreadyExists,
+ tlsPort,
+ snippet,
+ certDirHint: join(PATHS.data, 'certs'),
+ note: 'Point your app at the PortOS cert dir (or symlink it) so apps share the single Tailscale cert.'
+ });
+}));
+
// GET /api/apps/:id/icon - Serve the app's detected icon image
router.get('/:id/icon', loadApp, asyncHandler(async (req, res) => {
const app = req.loadedApp;
diff --git a/server/services/apps.js b/server/services/apps.js
index 00d5d76f4b..45e43eeac0 100644
--- a/server/services/apps.js
+++ b/server/services/apps.js
@@ -7,6 +7,7 @@ import { NON_PM2_TYPES } from './streamingDetect.js';
import { SELF_IMPROVEMENT_TASK_TYPES } from './taskSchedule.js';
import { sanitizeTaskMetadata } from '../lib/validation.js';
import { PORTS } from '../lib/ports.js';
+import { hasTailscaleCert } from '../../lib/tailscale-https.js';
const DATA_DIR = PATHS.data;
const APPS_FILE = join(DATA_DIR, 'apps.json');
@@ -18,6 +19,9 @@ export const PORTOS_APP_ID = 'portos-default';
* Build the baseline PortOS app entry with repoPath resolved to the actual project root.
*/
function buildPortosApp() {
+ // tlsPort reflects whether the Tailscale cert is actually on disk; if not,
+ // don't advertise HTTPS so the Launch button doesn't target a broken scheme.
+ const certPresent = hasTailscaleCert(join(PATHS.data, 'certs'));
return {
name: 'PortOS',
description: 'Local App OS portal for dev machines',
@@ -26,6 +30,7 @@ function buildPortosApp() {
uiPort: PORTS.API,
devUiPort: PORTS.UI,
apiPort: PORTS.API,
+ tlsPort: certPresent ? PORTS.API : null,
buildCommand: 'npm run build',
startCommands: ['npm start'],
pm2ProcessNames: [
@@ -100,7 +105,7 @@ async function loadApps() {
}
}
// Force-sync specific fields that should always match the code definition
- const forceSync = ['uiPort', 'devUiPort', 'apiPort', 'buildCommand', 'startCommands', 'processes', 'pm2ProcessNames'];
+ const forceSync = ['uiPort', 'devUiPort', 'apiPort', 'tlsPort', 'buildCommand', 'startCommands', 'processes', 'pm2ProcessNames'];
for (const key of forceSync) {
if (JSON.stringify(data.apps[PORTOS_APP_ID][key]) !== JSON.stringify(baseline[key])) {
data.apps[PORTOS_APP_ID][key] = baseline[key];