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
feat: per-peer DNS override on Instances page for trusted HTTPS links
Adam Eivyebec89828c3a
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex d005a7e7ff..76d01dbf3c 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -1,5 +1,6 @@## Added+- **Per-peer DNS override on the Instances page** — peer cards now expose an "edit host" control that lets you swap the raw Tailscale IP (`http://100.83.147.46:5555`) for a trusted HTTPS DNS name (`https://void.taile8179.ts.net:5555`). Once set, the server's probe, socket relay, sync orchestrator, and query proxy all route through `https://<host>` instead of `http://<ip>` — so app links in `PeerAppsList` also upgrade to HTTPS automatically. New `GET /api/instances/tailnet-suffix` endpoint shells out to the local `tailscale status --json` and returns the MagicDNS suffix + the full peer map, which the Instances UI uses to auto-suggest DNS names: match by Tailscale IP first (authoritative), fall back to `<peer.hostname>.<suffix>` composition. The UI's "use `<suggested>`" button applies the suggestion in one click. `updatePeer` now accepts an optional `host` field (validated as a DNS name; empty string clears); invalid hosts return 400 instead of silent no-ops. `addPeer` also accepts `host` for direct-DNS registration. Vite dev proxy auto-detects `data/certs/cert.pem` and flips its target to `https://localhost:5555` with `secure: false` when HTTPS is active, fixing "socket hang up" errors in dev mode. 44 tests (3 new) cover valid/invalid/cleared host handling.- **HTTPS with auto-renewing Let's Encrypt cert via Tailscale (self-signed fallback)** — Chrome refuses `getUserMedia` (mic) access over plain HTTP on a `100.x.x.x` Tailscale IP because the origin isn't a secure context. New `scripts/setup-cert.js` prefers a real Let's Encrypt cert via `tailscale cert <machine>.<tailnet>.ts.net` (Tailscale owns `ts.net` and solves the DNS-01 challenge for you — browsers trust the cert with zero click-through) and drops it into `data/certs/{cert,key}.pem`. If the Tailscale CLI is missing, the machine isn't logged in, or HTTPS Certificates aren't enabled in the tailnet admin, the script falls back to a self-signed cert with SANs for `localhost`, `127.0.0.1`, and every non-internal IPv4 (including the Tailscale IP). `server/index.js` picks `https.createServer` whenever `data/certs/{cert,key}.pem` exist and falls back to HTTP with a warning otherwise. New `server/services/certRenewer.js` runs daily on the server process, calls `tailscale cert` (no-op unless the LE cert is <2/3 lifetime remaining), and hot-swaps the live HTTPS server's `SecureContext` with the renewed cert — no restart needed. `npm start` runs the cert script before PM2 boot so fresh installs come up with HTTPS out of the box; `npm run setup:cert --force` regenerates on demand. Socket.IO auto-upgrades to WSS (same-origin relative paths). Access via `https://<machine>.<tailnet>.ts.net:5555` to get the trusted cert; the Tailscale IP still works but will show a cert mismatch.- **Blood Pressure tracking in MeatSpace → Body** — feature parity with the MortalLoom iOS/macOS companion app. New Blood Pressure card on the Body tab shows a systolic/diastolic trend chart (with AHA/ACC 2017 guideline reference lines), the latest reading, and its category + estimated life-expectancy impact. Readings are date-upserted so a HealthKit sync on the phone and a manual entry in PortOS on the same day merge into one row. Storage routes through the new `mlUpsertHealthMetricByDate` into MortalLoom's `healthMetrics[]` array when iCloud sync is enabled (same `bloodPressureSystolic`/`bloodPressureDiastolic` keys the Swift app writes), else falls back to `data/meatspace/health-metrics.json`. New endpoints: `GET /api/meatspace/blood-pressure`, `POST /api/meatspace/blood-pressure`. Apple Health XML ingest now maps `HKQuantityTypeIdentifierBloodPressureSystolic`/`Diastolic` → `blood_pressure_systolic`/`diastolic`, and those metrics are registered in the Core Vitals section of the Health tab so exported HK data shows trend lines there too. BP classification (normal / elevated / stage-1 / stage-2 / crisis) is ported from `CardioFitnessEngine.classifyBP` into `client/src/components/meatspace/bpClassification.js` so both sides report identical categories for the same reading.- **Hide voice widget per-browser** — the floating voice widget can now be dismissed entirely by clicking the new eye-off icon (next to the mobile FAB or in the desktop controls bar). The preference persists in `localStorage` under `portos.voice.hidden`, so iPhones/Safari sessions where the mic APIs don't work can stay clean while the desktop keeps the widget. Re-enable via **Settings → Voice → "Show floating voice widget"**; a custom `portos:voice:visibility` DOM event syncs the change live without a reload.diff --git a/client/src/components/instances/PeerAppsList.jsx b/client/src/components/instances/PeerAppsList.jsxindex 652c1c72b6..8c54a90ac9 100644--- a/client/src/components/instances/PeerAppsList.jsx+++ b/client/src/components/instances/PeerAppsList.jsx@@ -1,23 +1,29 @@import AppIcon from '../AppIcon';import StatusBadge from '../StatusBadge';-export default function PeerAppsList({ apps, peerAddress }) {+export default function PeerAppsList({ apps, peerAddress, peerHost }) {if (!apps || apps.length === 0) return null;+ // Prefer DNS hostname (HTTPS, trusted cert) over raw IP (HTTP).+ const linkBase = peerHost+ ? { scheme: 'https', host: peerHost }+ : { scheme: 'http', host: peerAddress };+ const label = `${linkBase.scheme}://${linkBase.host}`;+return (<div className="mt-3 border-t border-port-border pt-3">- <div className="text-xs text-gray-500 mb-1.5">Apps ({apps.length})</div>+ <div className="text-xs text-gray-500 mb-1.5">Apps ({apps.length}) <span className="text-gray-600 font-mono">— {label}</span></div><div className="space-y-1">{apps.map(app => (<div key={app.id} className="flex items-center gap-2 text-xs"><AppIcon icon={app.icon || 'package'} size={14} className="text-gray-400 shrink-0" />{app.uiPort && app.overallStatus === 'online' ? (<a- href={`http://${peerAddress}:${app.uiPort}`}+ href={`${linkBase.scheme}://${linkBase.host}:${app.uiPort}`}target="_blank"rel="noopener noreferrer"className="text-port-accent hover:underline truncate"- title={`Open ${app.name} on ${peerAddress}:${app.uiPort}`}+ title={`Open ${app.name} on ${linkBase.host}:${app.uiPort}`}>{app.name}</a>diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsxindex 775bac6c91..e234362e84 100644--- a/client/src/pages/Instances.jsx+++ b/client/src/pages/Instances.jsx@@ -1,4 +1,4 @@-import { useState, useEffect, useCallback } from 'react';+import { useState, useEffect, useCallback, useMemo } from 'react';import {Network, Plus, Trash2, RefreshCw, Edit3, Check, X,Wifi, WifiOff, CircleDot,@@ -12,7 +12,7 @@ import toast from '../components/ui/Toast';import socket from '../services/socket';import {getInstances, updateSelfInstance, addPeer, updatePeer,- removePeer, connectPeer, probePeer+ removePeer, connectPeer, probePeer, getTailnetInfo} from '../services/api';import PeerAppsList from '../components/instances/PeerAppsList';import PeerAgentsSection from '../components/instances/PeerAgentsSection';@@ -488,7 +488,92 @@ function SyncStatusSection({ peer, syncStatus }) {);}-function PeerCard({ peer, onRefresh, syncStatus }) {+function PeerHostEditor({ peer, onRefresh, tailnetInfo }) {+ const [editing, setEditing] = useState(false);+ const [value, setValue] = useState('');+ const [saving, setSaving] = useState(false);++ // Auto-detected DNS suggestion from the local tailscale status map:+ // match the peer by IP first (authoritative), fall back to composing+ // <hostname>.<tailnet-suffix> when the peer's hostname is a valid DNS label.+ const hostname = peer.lastHealth?.hostname;+ const suggestion = useMemo(() => {+ if (!tailnetInfo?.suffix) return null;+ const byIp = tailnetInfo.peers?.find(p => p.ips?.includes(peer.address));+ if (byIp?.dnsName) return byIp.dnsName;+ if (hostname && /^[a-z0-9][a-z0-9-]*$/i.test(hostname)) {+ return `${hostname}.${tailnetInfo.suffix}`.toLowerCase();+ }+ return null;+ }, [tailnetInfo, peer.address, hostname]);++ const startEdit = () => {+ setValue(peer.host || suggestion || '');+ setEditing(true);+ };++ const save = async () => {+ setSaving(true);+ const payload = { host: value.trim() === '' ? null : value.trim() };+ const result = await updatePeer(peer.id, payload).catch(() => null);+ setSaving(false);+ if (!result) return;+ onRefresh();+ setEditing(false);+ toast.success(payload.host ? `Host set to ${payload.host}` : 'Host cleared — reverting to IP');+ };++ const applySuggestion = () => setValue(suggestion);++ if (editing) {+ return (+ <div className="mt-1 flex items-center gap-1 flex-wrap">+ <input+ value={value}+ onChange={e => setValue(e.target.value)}+ onKeyDown={e => e.key === 'Enter' && save()}+ placeholder="host.tailnet.ts.net (empty to clear)"+ className="bg-port-bg border border-port-border rounded px-2 py-0.5 text-xs text-white font-mono focus:outline-hidden focus:border-port-accent flex-1 min-w-[180px]"+ autoFocus+ />+ <button onClick={save} disabled={saving} className="text-port-success hover:text-port-success/80 disabled:opacity-50"><Check size={14} /></button>+ <button onClick={() => setEditing(false)} className="text-gray-500 hover:text-white"><X size={14} /></button>+ {suggestion && suggestion !== value && (+ <button+ onClick={applySuggestion}+ className="text-[10px] text-port-accent hover:text-port-accent/80 underline"+ title={`Use detected DNS: ${suggestion}`}+ >+ use {suggestion}+ </button>+ )}+ </div>+ );+ }++ return (+ <div className="mt-0.5 flex items-center gap-1.5 flex-wrap">+ {peer.host ? (+ <span className="inline-flex items-center gap-1 text-[10px] text-port-success bg-port-success/10 rounded px-1.5 py-0.5 font-mono" title="Requests to this peer use https://<host>">+ <Wifi size={10} /> https://{peer.host}+ </span>+ ) : (+ <span className="inline-flex items-center gap-1 text-[10px] text-gray-500 bg-port-bg rounded px-1.5 py-0.5 font-mono" title="Requests use http://<ip> (no DNS set)">+ http only+ </span>+ )}+ <button+ onClick={startEdit}+ className="text-[10px] text-gray-500 hover:text-white underline"+ title={suggestion ? `Auto-detected: ${suggestion}` : 'Set a Tailscale DNS name for HTTPS'}+ >+ {peer.host ? 'edit' : (suggestion ? `use ${suggestion}` : 'set DNS')}+ </button>+ </div>+ );+}++function PeerCard({ peer, onRefresh, syncStatus, tailnetInfo }) {const [editingName, setEditingName] = useState(false);const [name, setName] = useState('');const [probing, setProbing] = useState(false);@@ -593,20 +678,23 @@ function PeerCard({ peer, onRefresh, syncStatus }) {</div></div>- <div className="flex items-center gap-2 mb-3">- <p className="text-xs text-gray-500 font-mono">{peer.address}:{peer.port}</p>- <DirectionBadge directions={peer.directions} />- {isInboundOnly && (- <button- onClick={handleConnect}- disabled={connecting}- className="inline-flex items-center gap-1 text-[10px] text-port-accent bg-port-accent/10 hover:bg-port-accent/20 rounded px-1.5 py-0.5 transition-colors disabled:opacity-50"- title="Connect back to make this mutual"- >- <ArrowLeftRight size={10} />- {connecting ? 'Connecting...' : 'Connect'}- </button>- )}+ <div className="mb-3">+ <div className="flex items-center gap-2 flex-wrap">+ <p className="text-xs text-gray-500 font-mono">{peer.address}:{peer.port}</p>+ <DirectionBadge directions={peer.directions} />+ {isInboundOnly && (+ <button+ onClick={handleConnect}+ disabled={connecting}+ className="inline-flex items-center gap-1 text-[10px] text-port-accent bg-port-accent/10 hover:bg-port-accent/20 rounded px-1.5 py-0.5 transition-colors disabled:opacity-50"+ title="Connect back to make this mutual"+ >+ <ArrowLeftRight size={10} />+ {connecting ? 'Connecting...' : 'Connect'}+ </button>+ )}+ </div>+ <PeerHostEditor peer={peer} onRefresh={onRefresh} tailnetInfo={tailnetInfo} /></div><HealthSummary health={peer.lastHealth} version={peer.version} />@@ -629,7 +717,7 @@ function PeerCard({ peer, onRefresh, syncStatus }) {<SyncStatusSection peer={peer} syncStatus={syncStatus} />- <PeerAppsList apps={peer.lastApps} peerAddress={peer.address} />+ <PeerAppsList apps={peer.lastApps} peerAddress={peer.address} peerHost={peer.host} />{peer.status === 'online' && (<PeerAgentsSection peerId={peer.id} peerName={peer.name} />)}@@ -641,6 +729,7 @@ export default function Instances() {const [self, setSelf] = useState(null);const [peers, setPeers] = useState([]);const [syncStatus, setSyncStatus] = useState(null);+ const [tailnetInfo, setTailnetInfo] = useState(null);const [loading, setLoading] = useState(true);const fetchData = useCallback(async () => {@@ -654,7 +743,13 @@ export default function Instances() {}, []);useEffect(() => {- fetchData();+ // Kick off both reads in parallel — the tailnet map is independent of+ // peer state, and fetching it sequentially added ~100-500ms to first paint+ // on machines where `tailscale status --json` is slow to respond.+ Promise.all([+ fetchData(),+ getTailnetInfo().then(setTailnetInfo).catch(() => setTailnetInfo(null))+ ]);socket.emit('instances:subscribe');const handlePeersUpdated = (updatedPeers) => {@@ -696,7 +791,7 @@ export default function Instances() {</h2><div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">{peers.map(peer => (- <PeerCard key={peer.id} peer={peer} onRefresh={fetchData} syncStatus={syncStatus} />+ <PeerCard key={peer.id} peer={peer} onRefresh={fetchData} syncStatus={syncStatus} tailnetInfo={tailnetInfo} />))}</div></div>diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.jsindex 61d119673e..05b36536ca 100644--- a/client/src/services/apiSystem.js+++ b/client/src/services/apiSystem.js@@ -110,6 +110,7 @@ export const removePeer = (id) => request(`/instances/peers/${id}`, { method: 'Dexport const connectPeer = (id) => request(`/instances/peers/${id}/connect`, { method: 'POST' });export const probePeer = (id) => request(`/instances/peers/${id}/probe`, { method: 'POST' });export const queryPeer = (id, path) => request(`/instances/peers/${id}/query?path=${encodeURIComponent(path)}`);+export const getTailnetInfo = () => request('/instances/tailnet-suffix');// Image Generationexport const getImageGenStatus = () => request('/image-gen/status');diff --git a/client/vite.config.js b/client/vite.config.jsindex c636c3bb18..a1e68ee05e 100644--- a/client/vite.config.js+++ b/client/vite.config.js@@ -1,14 +1,21 @@import { defineConfig, loadEnv } from 'vite';import react from '@vitejs/plugin-react';-import { readFileSync } from 'fs';+import { readFileSync, existsSync } from 'fs';import { resolve } from 'path';const rootPkg = JSON.parse(readFileSync(resolve(__dirname, '../package.json'), 'utf-8'));+// Dev proxy target: probe for the self-signed/LE cert under data/certs/. If the+// server is running HTTPS, the dev proxy must target HTTPS too (or requests+// through Vite return "socket hang up"). `secure: false` accepts the cert+// whether it's the trusted LE one or the self-signed fallback.+const CERT_PATH = resolve(__dirname, '..', 'data', 'certs', 'cert.pem');+const API_SCHEME = existsSync(CERT_PATH) ? 'https' : 'http';+export default defineConfig(({ mode }) => {const env = loadEnv(mode, process.cwd(), 'VITE_');const API_HOST = env.VITE_API_HOST || 'localhost';- const API_TARGET = `http://${API_HOST}:5555`;+ const API_TARGET = `${API_SCHEME}://${API_HOST}:5555`;return {define: {@@ -22,16 +29,19 @@ export default defineConfig(({ mode }) => {proxy: {'/api': {target: API_TARGET,- changeOrigin: true+ changeOrigin: true,+ secure: false},'/data': {target: API_TARGET,- changeOrigin: true+ changeOrigin: true,+ secure: false},'/socket.io': {target: API_TARGET,changeOrigin: true,- ws: true+ ws: true,+ secure: false}}},diff --git a/scripts/setup-cert.js b/scripts/setup-cert.jsindex e598d200f1..81f1fc14fd 100644--- a/scripts/setup-cert.js+++ b/scripts/setup-cert.js@@ -27,6 +27,7 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync, statSync } from 'fsimport { networkInterfaces } from 'os';import { join, dirname } from 'path';import { fileURLToPath } from 'url';+import { findTailscale } from '../server/lib/tailscale.js';const __dirname = dirname(fileURLToPath(import.meta.url));const ROOT = join(__dirname, '..');@@ -38,27 +39,6 @@ const META_PATH = join(CERT_DIR, 'meta.json');const FORCE = process.argv.includes('--force');const SELF_SIGNED_ONLY = process.argv.includes('--self-signed');-// ---- Tailscale CLI detection -----------------------------------------------const TAILSCALE_CANDIDATES = [- '/Applications/Tailscale.app/Contents/MacOS/Tailscale', // macOS GUI install- '/usr/local/bin/tailscale',- '/opt/homebrew/bin/tailscale',- '/usr/bin/tailscale'-];--function findTailscale() {- for (const p of TAILSCALE_CANDIDATES) {- if (existsSync(p)) return p;- }- const path = process.env.PATH || '';- for (const dir of path.split(':')) {- const p = join(dir, 'tailscale');- if (existsSync(p)) return p;- }- return null;-}-function tailscaleStatus(bin) {const out = execFileSync(bin, ['status', '--json'], { stdio: ['ignore', 'pipe', 'ignore'] });return JSON.parse(out.toString());diff --git a/server/lib/peerUrl.js b/server/lib/peerUrl.jsnew file mode 100644index 0000000000..b7ada43d06--- /dev/null+++ b/server/lib/peerUrl.js@@ -0,0 +1,11 @@+/**+ * Build the base URL for a peer.+ *+ * If `peer.host` is set, uses HTTPS with that DNS name (assumes a real cert —+ * e.g. a Tailscale-issued Let's Encrypt cert for `<host>.<tailnet>.ts.net`).+ * Otherwise falls back to plain HTTP on the peer's IP address.+ */+export function peerBaseUrl(peer) {+ if (peer.host) return `https://${peer.host}:${peer.port}`;+ return `http://${peer.address}:${peer.port}`;+}diff --git a/server/lib/tailscale.js b/server/lib/tailscale.jsnew file mode 100644index 0000000000..7f4406389d--- /dev/null+++ b/server/lib/tailscale.js@@ -0,0 +1,23 @@+import { existsSync } from 'fs';+import { join } from 'path';++// Paths where the Tailscale CLI binary is commonly found. On macOS the GUI app+// doesn't put the CLI in PATH by default; Homebrew installs to /usr/local/bin+// (Intel) or /opt/homebrew/bin (Apple Silicon); Linux packages land in /usr/bin.+const TAILSCALE_CANDIDATES = [+ '/Applications/Tailscale.app/Contents/MacOS/Tailscale',+ '/usr/local/bin/tailscale',+ '/opt/homebrew/bin/tailscale',+ '/usr/bin/tailscale'+];++export function findTailscale() {+ for (const p of TAILSCALE_CANDIDATES) {+ if (existsSync(p)) return p;+ }+ for (const dir of (process.env.PATH || '').split(':')) {+ const p = join(dir, 'tailscale');+ if (existsSync(p)) return p;+ }+ return null;+}diff --git a/server/routes/instances.js b/server/routes/instances.jsindex 0d604ec829..72cdc79639 100644--- a/server/routes/instances.js+++ b/server/routes/instances.js@@ -6,10 +6,15 @@import { Router } from 'express';import { z } from 'zod';+import { execFile } from 'child_process';+import { promisify } from 'util';import * as instances from '../services/instances.js';import { getSyncStatus } from '../services/syncOrchestrator.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { DEFAULT_PEER_PORT } from '../lib/ports.js';+import { findTailscale } from '../lib/tailscale.js';++const execFileAsync = promisify(execFile);const router = Router();@@ -19,7 +24,8 @@ const addPeerSchema = z.object({.regex(/^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/, 'Must be a valid IP address').refine(ip => !ip.startsWith('127.') && !ip.startsWith('169.254.'), 'Loopback and link-local addresses are not allowed'),port: z.number().int().min(1).max(65535).default(DEFAULT_PEER_PORT),- name: z.string().optional()+ name: z.string().optional(),+ host: z.string().optional()});const syncCategoriesSchema = z.object({@@ -35,7 +41,9 @@ const updatePeerSchema = z.object({name: z.string().optional(),enabled: z.boolean().optional(),syncEnabled: z.boolean().optional(),- syncCategories: syncCategoriesSchema+ syncCategories: syncCategoriesSchema,+ // Accept empty string to clear; any other string is validated/normalized in the service+ host: z.string().optional().nullable()});const announceSchema = z.object({@@ -68,6 +76,26 @@ router.get('/sync-status', asyncHandler(async (req, res) => {});}));+// GET /api/instances/tailnet-suffix — detect local Tailscale MagicDNS suffix+// so the UI can auto-suggest DNS names (e.g., `iphone181` + `.taile8179.ts.net`)+// for peers that currently use bare IP addresses.+router.get('/tailnet-suffix', asyncHandler(async (req, res) => {+ const bin = findTailscale();+ if (!bin) return res.json({ suffix: null, reason: 'tailscale-not-installed' });+ const { stdout } = await execFileAsync(bin, ['status', '--json']).catch(() => ({ stdout: null }));+ if (!stdout) return res.json({ suffix: null, reason: 'tailscale-not-running' });+ const status = JSON.parse(stdout);+ const suffix = status?.CurrentTailnet?.MagicDNSSuffix ?? status?.MagicDNSSuffix ?? null;+ // Also include the peer map so the UI can auto-match a peer's instanceId/hostname+ // to its tailnet DNS name without asking the peer.+ const peers = Object.values(status?.Peer ?? {}).map(p => ({+ dnsName: (p.DNSName ?? '').replace(/\.$/, ''),+ hostName: p.HostName ?? null,+ ips: p.TailscaleIPs ?? []+ }));+ res.json({ suffix, self: (status?.Self?.DNSName ?? '').replace(/\.$/, '') || null, peers });+}));+// GET /api/instances/self — get this instance's identityrouter.get('/self', asyncHandler(async (req, res) => {const self = await instances.getSelf();@@ -118,6 +146,12 @@ router.post('/peers', asyncHandler(async (req, res) => {// PUT /api/instances/peers/:id — update peerrouter.put('/peers/:id', asyncHandler(async (req, res) => {const data = updatePeerSchema.parse(req.body);+ // Reject invalid DNS names up front so the UI gets a clear error instead of a silent no-op.+ if (data.host !== undefined && data.host !== null && data.host !== '') {+ if (instances.validHost(data.host) === undefined) {+ throw new ServerError('Invalid DNS host — use a hostname like "machine.tailnet.ts.net"', { status: 400 });+ }+ }const peer = await instances.updatePeer(req.params.id, data);if (!peer) throw new ServerError('Peer not found', { status: 404 });res.json(peer);diff --git a/server/services/certRenewer.js b/server/services/certRenewer.jsindex 2b2a21186e..514bc82ddb 100644--- a/server/services/certRenewer.js+++ b/server/services/certRenewer.js@@ -16,6 +16,7 @@ import { existsSync, readFileSync, statSync } from 'fs';import { join } from 'path';import { promisify } from 'util';import { PATHS } from '../lib/fileUtils.js';+import { findTailscale } from '../lib/tailscale.js';const execFileAsync = promisify(execFile);@@ -25,20 +26,6 @@ const KEY_PATH = join(CERT_DIR, 'key.pem');const META_PATH = join(CERT_DIR, 'meta.json');const RENEW_INTERVAL_MS = 24 * 60 * 60 * 1000;-const TAILSCALE_CANDIDATES = [- '/Applications/Tailscale.app/Contents/MacOS/Tailscale',- '/usr/local/bin/tailscale',- '/opt/homebrew/bin/tailscale',- '/usr/bin/tailscale'-];--function findTailscale() {- for (const p of TAILSCALE_CANDIDATES) {- if (existsSync(p)) return p;- }- return null;-}-function readMeta() {if (!existsSync(META_PATH)) return null;return JSON.parse(readFileSync(META_PATH, 'utf-8'));diff --git a/server/services/instances.js b/server/services/instances.jsindex 8a29568abc..948d82f3db 100644--- a/server/services/instances.js+++ b/server/services/instances.js@@ -14,6 +14,7 @@ import { createMutex } from '../lib/asyncMutex.js';import { instanceEvents } from './instanceEvents.js';import { connectToPeer, disconnectFromPeer } from './peerSocketRelay.js';import { DEFAULT_PEER_PORT } from '../lib/ports.js';+import { peerBaseUrl } from '../lib/peerUrl.js';const INSTANCES_FILE = dataPath('instances.json');const PROBE_TIMEOUT_MS = 5000;@@ -119,6 +120,20 @@ function isIPAddress(str) {return net.isIP(str) !== 0;}+function validHost(str) {+ if (str === '' || str === null) return null; // explicit clear+ if (typeof str !== 'string') return undefined; // ignore+ const trimmed = str.trim();+ if (!trimmed) return null;+ // Accept DNS names: letters, digits, hyphens, dots. No scheme, no port, no path.+ if (!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i.test(trimmed)) {+ return undefined;+ }+ return trimmed.toLowerCase();+}++export { validHost };+// Default sync categories — all disabled until explicitly enabled per-peerconst DEFAULT_SYNC_CATEGORIES = {brain: false,@@ -131,13 +146,15 @@ const DEFAULT_SYNC_CATEGORIES = {export { DEFAULT_SYNC_CATEGORIES };-export async function addPeer({ address, port = DEFAULT_PEER_PORT, name }) {+export async function addPeer({ address, port = DEFAULT_PEER_PORT, name, host }) {const peer = await withData(async (data) => {+ const normalizedHost = validHost(host);const entry = {id: crypto.randomUUID(),address,+ host: normalizedHost || null,port,- name: validName(name, address),+ name: validName(name, normalizedHost || address),instanceId: null,addedAt: new Date().toISOString(),lastSeen: null,@@ -151,12 +168,11 @@ export async function addPeer({ address, port = DEFAULT_PEER_PORT, name }) {directions: ['outbound']};data.peers.push(entry);- console.log(`🌐 Peer added: ${entry.name} (${entry.address}:${entry.port})`);+ console.log(`🌐 Peer added: ${entry.name} (${peerBaseUrl(entry)})`);instanceEvents.emit('peers:updated', data.peers);return entry;});- // Announce ourselves to the remote peer (fire-and-forget)- announceSelf(peer.address, peer.port);+ announceSelf(peer);return peer;}@@ -173,8 +189,8 @@ export async function removePeer(id) {}export async function updatePeer(id, updates) {- if (updates.enabled === false) disconnectFromPeer(id);- return withData(async (data) => {+ let hostChanged = false;+ const result = await withData(async (data) => {const peer = data.peers.find(p => p.id === id);if (!peer) return null;if (updates.name !== undefined) peer.name = validName(updates.name, peer.name);@@ -183,15 +199,28 @@ export async function updatePeer(id, updates) {if (updates.syncCategories !== undefined) {peer.syncCategories = { ...(peer.syncCategories || DEFAULT_SYNC_CATEGORIES), ...updates.syncCategories };}+ if (updates.host !== undefined) {+ const normalized = validHost(updates.host);+ if (normalized !== undefined && normalized !== peer.host) {+ peer.host = normalized; // null clears, string sets+ hostChanged = true;+ console.log(`🌐 Peer host ${peer.host ? `set to ${peer.host}` : 'cleared'}: ${peer.name}`);+ }+ }instanceEvents.emit('peers:updated', data.peers);return peer;});+ // Tear down the socket relay only after a real state transition so it can+ // reconnect using the new URL on the next probe cycle. Invalid/no-op host+ // writes no longer disrupt an already-healthy connection.+ if (updates.enabled === false || hostChanged) disconnectFromPeer(id);+ return result;}// --- Probing ---export async function probePeer(peer) {- const baseUrl = `http://${peer.address}:${peer.port}`;+ const baseUrl = peerBaseUrl(peer);const controller = new AbortController();const timeout = setTimeout(() => controller.abort(), PROBE_TIMEOUT_MS);@@ -224,7 +253,7 @@ export async function probePeer(peer) {remoteSyncSeqs = await syncRes.json().catch(() => null);}} catch (err) {- console.log(`⚠️ Probe failed for ${peer.address}:${peer.port}: ${err.message}`);+ console.log(`⚠️ Probe failed for ${baseUrl}: ${err.message}`);status = 'offline';lastHealth = peer.lastHealth; // preserve last knownlastSeen = peer.lastSeen;@@ -276,7 +305,7 @@ export async function probePeer(peer) {// Announce ourselves only when peer transitions to online (not every poll cycle)if (status === 'online' && previousStatus !== 'online') {if (stored) {- announceSelf(peer.address, peer.port);+ announceSelf(stored);instanceEvents.emit('peer:online', stored);}}@@ -309,7 +338,7 @@ export async function queryPeer(id, apiPath) {const peer = data.peers.find(p => p.id === id);if (!peer) return { error: 'Peer not found' };- const url = `http://${peer.address}:${peer.port}${apiPath}`;+ const url = `${peerBaseUrl(peer)}${apiPath}`;const controller = new AbortController();const timeout = setTimeout(() => controller.abort(), PROBE_TIMEOUT_MS);@@ -387,12 +416,12 @@ export async function handleAnnounce({ address, port, instanceId, name }) {return result;}-async function announceSelf(address, port) {+async function announceSelf(peer) {const data = await loadData();if (!data.self) return;const selfPort = parseInt(process.env.PORT, 10) || DEFAULT_PEER_PORT;- const url = `http://${address}:${port}/api/instances/peers/announce`;+ const url = `${peerBaseUrl(peer)}/api/instances/peers/announce`;const controller = new AbortController();const timeout = setTimeout(() => controller.abort(), PROBE_TIMEOUT_MS);@@ -408,14 +437,13 @@ async function announceSelf(address, port) {signal: controller.signal});if (res.ok) {- console.log(`🌐 Announced self to ${address}:${port}`);- // Mark outbound direction on the local peer record- await markDirection(address, port, 'outbound');+ console.log(`🌐 Announced self to ${url}`);+ await markDirection(peer.id, 'outbound');} else {- console.log(`🌐 Announce to ${address}:${port} failed: HTTP ${res.status}`);+ console.log(`🌐 Announce to ${url} failed: HTTP ${res.status}`);}} catch (err) {- console.log(`🌐 Announce to ${address}:${port} unreachable: ${err.message}`);+ console.log(`🌐 Announce to ${url} unreachable: ${err.message}`);} finally {clearTimeout(timeout);}@@ -425,14 +453,14 @@ export async function connectPeer(id) {const data = await loadData();const peer = data.peers.find(p => p.id === id);if (!peer) return null;- await announceSelf(peer.address, peer.port);+ await announceSelf(peer);const probed = await probePeer(peer);return probed;}-async function markDirection(address, port, direction) {+async function markDirection(peerId, direction) {await withData(async (data) => {- const peer = data.peers.find(p => p.address === address && p.port === port);+ const peer = data.peers.find(p => p.id === peerId);if (!peer) return;peer.directions = peer.directions || [];if (!peer.directions.includes(direction)) {diff --git a/server/services/instances.test.js b/server/services/instances.test.jsindex 5c19bdc1d5..8731421476 100644--- a/server/services/instances.test.js+++ b/server/services/instances.test.js@@ -294,6 +294,45 @@ describe('instances.js', () => {expect(disconnectFromPeer).not.toHaveBeenCalled();});++ it('should set a valid DNS host and disconnect the relay so it reconnects via HTTPS', async () => {+ const peers = [{ id: 'peer-1', name: 'host', enabled: true, host: null }];+ readJSONFile.mockResolvedValue({ self: null, peers });++ const result = await updatePeer('peer-1', { host: 'void.taile8179.ts.net' });++ expect(result.host).toBe('void.taile8179.ts.net');+ expect(disconnectFromPeer).toHaveBeenCalledWith('peer-1');+ });++ it('should clear host when empty string is passed', async () => {+ const peers = [{ id: 'peer-1', name: 'host', enabled: true, host: 'old.example.com' }];+ readJSONFile.mockResolvedValue({ self: null, peers });++ const result = await updatePeer('peer-1', { host: '' });++ expect(result.host).toBeNull();+ });++ it('should ignore invalid host (leave unchanged)', async () => {+ const peers = [{ id: 'peer-1', name: 'host', enabled: true, host: 'good.example.com' }];+ readJSONFile.mockResolvedValue({ self: null, peers });++ const result = await updatePeer('peer-1', { host: 'bad!!host' });++ expect(result.host).toBe('good.example.com');+ });++ it('should not disconnect the relay when host is invalid or unchanged', async () => {+ const peers = [{ id: 'peer-1', name: 'host', enabled: true, host: 'same.example.com' }];+ readJSONFile.mockResolvedValue({ self: null, peers });++ await updatePeer('peer-1', { host: 'same.example.com' });+ expect(disconnectFromPeer).not.toHaveBeenCalled();++ await updatePeer('peer-1', { host: 'bad!!host' });+ expect(disconnectFromPeer).not.toHaveBeenCalled();+ });});// --- Probing ---diff --git a/server/services/peerSocketRelay.js b/server/services/peerSocketRelay.jsindex 6a24f02e8a..61289eded6 100644--- a/server/services/peerSocketRelay.js+++ b/server/services/peerSocketRelay.js@@ -7,6 +7,7 @@import { io } from 'socket.io-client';import { instanceEvents } from './instanceEvents.js';+import { peerBaseUrl } from '../lib/peerUrl.js';// Map<peerId, { socket, agents: Map<agentId, agent>, peer }>const peerConnections = new Map();@@ -19,7 +20,7 @@ const CONNECT_TIMEOUT_MS = 5000;export function connectToPeer(peer) {if (peerConnections.has(peer.id)) return;- const url = `http://${peer.address}:${peer.port}`;+ const url = peerBaseUrl(peer);const socket = io(url, {reconnection: true,reconnectionAttempts: 5,@@ -27,16 +28,17 @@ export function connectToPeer(peer) {timeout: CONNECT_TIMEOUT_MS});+ // `host` is required so fetchPeerAgents() can rebuild the HTTPS URL via peerBaseUrl()const conn = {socket,agents: new Map(),- peer: { id: peer.id, name: peer.name, address: peer.address, port: peer.port }+ peer: { id: peer.id, name: peer.name, address: peer.address, host: peer.host ?? null, port: peer.port }};peerConnections.set(peer.id, conn);socket.on('connect', () => {- console.log(`🔗 Peer relay connected: ${peer.name} (${peer.address}:${peer.port})`);+ console.log(`🔗 Peer relay connected: ${peer.name} (${url})`);socket.emit('cos:subscribe');// Fetch initial agent state via HTTP@@ -94,7 +96,7 @@ export function connectToPeer(peer) {*/async function fetchPeerAgents(conn) {const { peer } = conn;- const url = `http://${peer.address}:${peer.port}/api/cos/agents`;+ const url = `${peerBaseUrl(peer)}/api/cos/agents`;const controller = new AbortController();const timeout = setTimeout(() => controller.abort(), CONNECT_TIMEOUT_MS);diff --git a/server/services/syncOrchestrator.js b/server/services/syncOrchestrator.jsindex e798dda98f..e2af7fddd5 100644--- a/server/services/syncOrchestrator.js+++ b/server/services/syncOrchestrator.js@@ -12,6 +12,7 @@ import { readJSONFile, ensureDir, PATHS, dataPath } from '../lib/fileUtils.js';import { createMutex } from '../lib/asyncMutex.js';import { instanceEvents } from './instanceEvents.js';import { getPeers, DEFAULT_SYNC_CATEGORIES } from './instances.js';+import { peerBaseUrl } from '../lib/peerUrl.js';import * as brainSync from './brainSync.js';import * as brainSyncLog from './brainSyncLog.js';import * as memorySync from './memorySync.js';@@ -59,7 +60,7 @@ async function withCursors(fn) {// --- Peer fetch helper ---async function fetchPeer(peer, path) {- const url = `http://${peer.address}:${peer.port}${path}`;+ const url = `${peerBaseUrl(peer)}${path}`;const controller = new AbortController();const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);try {@@ -88,7 +89,7 @@ async function syncImageFromPeer(peer, avatarPath) {const exists = await access(localPath).then(() => true).catch(() => false);if (exists) return;- const url = `http://${peer.address}:${peer.port}${avatarPath}`;+ const url = `${peerBaseUrl(peer)}${avatarPath}`;const controller = new AbortController();const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);try {