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: HTTPS via Tailscale Let's Encrypt cert with daily hot-swap renewal
Adam Eivyfc27517b23b4
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 5e80397405..6c076cc7c1 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -1,5 +1,6 @@## Added+- **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.- **Daily Log — voice-dictatable diary in the Brain section** — new `Brain → Daily Log` tab at `/brain/daily-log` for free-form typed or dictated daily entries. One entry per date, stored in `data/brain/journals.json` with per-segment source metadata (`text` vs `voice`). Five voice tools land in the CoS: `daily_log_open` ("open my daily log" — navigates + optionally starts dictation), `daily_log_start_dictation` / `daily_log_stop_dictation`, `daily_log_append` (one-shot append without dictation mode), and `daily_log_read` (reads the entry verbatim via TTS). Dictation mode short-circuits the LLM at the server — every voice utterance appends straight to the log until the user says "stop dictation" — so the CoS stops talking back while you ramble. Tools can now emit client-side side effects (`voice:navigate`, `voice:dictation`); the Voice widget listens and routes the browser + surfaces a "Dictating to Daily Log" chip. Optional Obsidian mirror: each entry auto-writes to `<vault>/<folder>/<YYYY-MM-DD>.md` when a vault is configured in the tab's settings panel (reuses the existing Notes vault registry), picking up iCloud backup for free. Entries flow through `brainMemoryBridge.js` (new `journals` brain type, `daily-log` category) so the CoS memory system vector-embeds each day and agents can semantically search across the log history. New routes: `GET/PUT/DELETE /api/brain/daily-log/:date`, `POST /api/brain/daily-log/:date/append`, `GET/PUT /api/brain/daily-log/settings`, `POST /api/brain/daily-log/sync-obsidian`.diff --git a/package.json b/package.jsonindex 244eb9f1a5..c8a2e14225 100644--- a/package.json+++ b/package.json@@ -10,7 +10,7 @@"dev": "node scripts/dev-start.js","dev:stop": "node ./node_modules/pm2/bin/pm2 stop ecosystem.config.cjs","build": "npm run build --prefix client",- "start": "node scripts/ensure-deps.js && npm run build && node scripts/setup-db.js && (node ./node_modules/pm2/bin/pm2 delete ecosystem.config.cjs --silent || echo pm2 delete skipped) && node ./node_modules/pm2/bin/pm2 start ecosystem.config.cjs && node ./node_modules/pm2/bin/pm2 save",+ "start": "node scripts/ensure-deps.js && npm run build && node scripts/setup-db.js && node scripts/setup-cert.js && (node ./node_modules/pm2/bin/pm2 delete ecosystem.config.cjs --silent || echo pm2 delete skipped) && node ./node_modules/pm2/bin/pm2 start ecosystem.config.cjs && node ./node_modules/pm2/bin/pm2 save","pm2:start": "node ./node_modules/pm2/bin/pm2 start ecosystem.config.cjs","pm2:stop": "node ./node_modules/pm2/bin/pm2 stop ecosystem.config.cjs","pm2:restart": "node ./node_modules/pm2/bin/pm2 restart ecosystem.config.cjs",@@ -24,6 +24,7 @@"setup:data": "node scripts/setup-data.js","setup:db": "node scripts/setup-db.js","setup:browser": "node scripts/setup-browser.js",+ "setup:cert": "node scripts/setup-cert.js","setup:ghostty": "node scripts/setup-ghostty.js","setup:hooks": "bash scripts/setup-git-hooks.sh","update": "node -e \"const{spawnSync:s}=require('child_process');const w=process.platform==='win32';const r=s(w?'powershell':'bash',w?['-NoProfile','-ExecutionPolicy','Bypass','-File','update.ps1']:['update.sh'],{stdio:'inherit'});process.exit(r.status??1)\"",diff --git a/scripts/setup-cert.js b/scripts/setup-cert.jsnew file mode 100644index 0000000000..e598d200f1--- /dev/null+++ b/scripts/setup-cert.js@@ -0,0 +1,260 @@+#!/usr/bin/env node+/**+ * Provisions a TLS cert for PortOS at data/certs/{cert,key}.pem.+ *+ * Prefers a real Let's Encrypt cert via `tailscale cert` (browsers trust it,+ * no click-through). Falls back to a self-signed cert covering localhost ++ * every non-internal IPv4 on the host (including the Tailscale IP) when+ * Tailscale HTTPS isn't available.+ *+ * Why we prefer Tailscale: Let's Encrypt does not issue certs for bare IPs.+ * Tailscale owns `ts.net` and provisions LE certs against your tailnet's+ * `<machine>.<tailnet>.ts.net` hostname via DNS-01. MagicDNS resolves that+ * name to the 100.x Tailscale IP, so `https://<host>.ts.net` hits the same+ * server as `https://100.x.y.z` — but with a trusted cert.+ *+ * Renewal: the LE cert lives ~90 days. `tailscale cert` is a no-op when the+ * cached cert has >1/3 lifetime remaining and fetches a fresh one otherwise.+ * `server/services/certRenewer.js` calls it daily and hot-swaps the running+ * HTTPS server's SecureContext without a restart.+ *+ * Flags:+ * --force regenerate even if meta says nothing changed+ * --self-signed skip Tailscale attempt and go straight to self-signed+ */+import { execFileSync } from 'child_process';+import { existsSync, mkdirSync, readFileSync, writeFileSync, statSync } from 'fs';+import { networkInterfaces } from 'os';+import { join, dirname } from 'path';+import { fileURLToPath } from 'url';++const __dirname = dirname(fileURLToPath(import.meta.url));+const ROOT = join(__dirname, '..');+const CERT_DIR = join(ROOT, 'data', 'certs');+const KEY_PATH = join(CERT_DIR, 'key.pem');+const CERT_PATH = join(CERT_DIR, 'cert.pem');+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());+}++function tailscaleHostname(status) {+ const raw = status?.Self?.DNSName;+ if (!raw) return null;+ return raw.replace(/\.$/, '');+}++function runTailscaleCert(bin, hostname) {+ mkdirSync(CERT_DIR, { recursive: true });+ execFileSync(bin, [+ 'cert',+ `--cert-file=${CERT_PATH}`,+ `--key-file=${KEY_PATH}`,+ hostname+ ], { stdio: 'inherit' });+}++// ---- Self-signed path ----------------------------------------------------++function detectIPs() {+ const ips = new Set(['127.0.0.1']);+ const nets = networkInterfaces();+ for (const name of Object.keys(nets)) {+ for (const iface of nets[name] || []) {+ if (iface.family === 'IPv4' && !iface.internal) ips.add(iface.address);+ }+ }+ return [...ips].sort();+}++function buildSANs(ips) {+ const dns = ['localhost'];+ const lines = [+ ...dns.map((d, i) => `DNS.${i + 1} = ${d}`),+ ...ips.map((ip, i) => `IP.${i + 1} = ${ip}`)+ ];+ return lines.join('\n');+}++function generateSelfSigned(ips) {+ mkdirSync(CERT_DIR, { recursive: true });++ const cnf = `+[req]+default_bits = 2048+prompt = no+default_md = sha256+distinguished_name = dn+req_extensions = v3_req+x509_extensions = v3_req++[dn]+CN = PortOS++[v3_req]+basicConstraints = CA:FALSE+keyUsage = digitalSignature, keyEncipherment+extendedKeyUsage = serverAuth+subjectAltName = @alt_names++[alt_names]+${buildSANs(ips)}+`;++ const cnfPath = join(CERT_DIR, 'openssl.cnf');+ writeFileSync(cnfPath, cnf);++ execFileSync('openssl', [+ 'req', '-x509', '-newkey', 'rsa:2048', '-nodes',+ '-keyout', KEY_PATH,+ '-out', CERT_PATH,+ '-days', '3650',+ '-config', cnfPath,+ '-extensions', 'v3_req'+ ], { stdio: ['ignore', 'ignore', 'inherit'] });++ writeFileSync(META_PATH, JSON.stringify({+ mode: 'self-signed',+ ips,+ generatedAt: new Date().toISOString()+ }, null, 2));+ console.log(`🔒 Generated self-signed cert for ${ips.join(', ')}`);+}++// ---- Regeneration logic --------------------------------------------------++function readMeta() {+ if (!existsSync(META_PATH)) return null;+ return JSON.parse(readFileSync(META_PATH, 'utf-8'));+}++function certExpiresAt() {+ if (!existsSync(CERT_PATH)) return null;+ const out = execFileSync('openssl', ['x509', '-in', CERT_PATH, '-noout', '-enddate']).toString();+ const match = out.match(/notAfter=(.+)/);+ return match ? new Date(match[1]) : null;+}++function daysUntil(date) {+ return (date.getTime() - Date.now()) / 86400000;+}++function shouldRegenTailscale(hostname) {+ if (FORCE) return true;+ if (!existsSync(CERT_PATH) || !existsSync(KEY_PATH)) return true;+ const meta = readMeta();+ if (!meta || meta.mode !== 'tailscale' || meta.hostname !== hostname) return true;+ const expiry = certExpiresAt();+ if (!expiry) return true;+ // Renew when <30 days remain (LE issues 90-day certs; tailscale cert no-ops+ // when >1/3 lifetime remains, so we lean on the CLI's own cache window)+ return daysUntil(expiry) < 30;+}++function shouldRegenSelfSigned(ips) {+ if (FORCE) return true;+ if (!existsSync(CERT_PATH) || !existsSync(KEY_PATH)) return true;+ const meta = readMeta();+ if (!meta || meta.mode !== 'self-signed') return true;+ const prev = (meta.ips || []).slice().sort().join(',');+ const curr = ips.slice().sort().join(',');+ return prev !== curr;+}++// ---- Main ----------------------------------------------------------------++function trySelfSigned() {+ const ips = detectIPs();+ if (shouldRegenSelfSigned(ips)) {+ generateSelfSigned(ips);+ } else {+ console.log(`🔒 Self-signed cert still valid for ${ips.join(', ')} (use --force to regenerate)`);+ }+}++if (SELF_SIGNED_ONLY) {+ trySelfSigned();+ process.exit(0);+}++const bin = findTailscale();+if (!bin) {+ console.log(`ℹ️ Tailscale CLI not found — falling back to self-signed cert.`);+ trySelfSigned();+ process.exit(0);+}++let status;+try {+ status = tailscaleStatus(bin);+} catch (err) {+ console.log(`ℹ️ tailscale status failed (${err.message}) — falling back to self-signed cert.`);+ trySelfSigned();+ process.exit(0);+}++const hostname = tailscaleHostname(status);+if (!hostname || status.BackendState !== 'Running') {+ console.log(`ℹ️ Tailscale not running or no DNSName — falling back to self-signed cert.`);+ trySelfSigned();+ process.exit(0);+}++if (!shouldRegenTailscale(hostname)) {+ const expiry = certExpiresAt();+ const days = expiry ? Math.floor(daysUntil(expiry)) : '?';+ console.log(`🔒 Tailscale cert for ${hostname} still valid (${days}d remaining)`);+ process.exit(0);+}++console.log(`🔒 Fetching Let's Encrypt cert for ${hostname} via Tailscale...`);+try {+ runTailscaleCert(bin, hostname);+} catch (err) {+ console.log(`⚠️ tailscale cert failed (${err.message}) — falling back to self-signed cert.`);+ console.log(` (Common cause: HTTPS Certificates not enabled in the tailnet admin console at login.tailscale.com/admin/dns)`);+ trySelfSigned();+ process.exit(0);+}++if (!existsSync(CERT_PATH) || !existsSync(KEY_PATH)) {+ console.log(`⚠️ tailscale cert returned success but files missing — falling back to self-signed.`);+ trySelfSigned();+ process.exit(0);+}++const expiry = certExpiresAt();+writeFileSync(META_PATH, JSON.stringify({+ mode: 'tailscale',+ hostname,+ issuedAt: new Date().toISOString(),+ expiresAt: expiry?.toISOString() ?? null,+ certMtime: statSync(CERT_PATH).mtimeMs+}, null, 2));+console.log(`✅ Tailscale cert installed for ${hostname} (expires ${expiry?.toISOString() ?? 'unknown'})`);diff --git a/server/index.js b/server/index.jsindex 3f122d0298..43092efe52 100644--- a/server/index.js+++ b/server/index.js@@ -1,10 +1,11 @@import express from 'express';-import { createServer } from 'http';+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 { existsSync } from 'fs';+import { existsSync, readFileSync } from 'fs';import { readFile, unlink } from 'fs/promises';import alertsRoutes from './routes/alerts.js';@@ -80,6 +81,7 @@ import { initSyncOrchestrator } from './services/syncOrchestrator.js';import { initSocket } from './services/socket.js';import { errorMiddleware, setupProcessErrorHandlers, asyncHandler } from './lib/errorHandler.js';import { initAutoFixer } from './services/autoFixer.js';+import { initCertRenewer } from './services/certRenewer.js';import { initTaskLearning } from './services/taskLearning.js';import { recordSession, recordMessages } from './services/usage.js';import { errorEvents } from './lib/errorHandler.js';@@ -108,10 +110,20 @@ const __filename = fileURLToPath(import.meta.url);const __dirname = dirname(__filename);const app = express();-const httpServer = createServer(app);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);+const scheme = httpsEnabled ? 'https' : 'http';+// Socket.IO with relative path support for Tailscaleconst io = new Server(httpServer, {cors: {@@ -400,7 +412,12 @@ ensureSelf().then(() => {// Start server only after sync log is initializedhttpServer.listen(PORT, HOST, () => {- console.log(`🚀 PortOS server running at http://${HOST}:${PORT}`);+ console.log(`🚀 PortOS server running at ${scheme}://${HOST}:${PORT}`);+ if (!httpsEnabled) {+ console.log(`⚠️ HTTP only — getUserMedia (mic) will not work over Tailscale IP. Run "npm run setup:cert" to enable HTTPS.`);+ } else {+ initCertRenewer(httpServer);+ }// Set up process error handlers with io instancesetupProcessErrorHandlers(io);diff --git a/server/services/certRenewer.js b/server/services/certRenewer.jsnew file mode 100644index 0000000000..2b2a21186e--- /dev/null+++ b/server/services/certRenewer.js@@ -0,0 +1,91 @@+/**+ * Daily TLS cert renewer.+ *+ * When `data/certs/meta.json` indicates a Tailscale-issued cert, this service+ * re-runs `tailscale cert` every 24h. The CLI is a no-op when the cached cert+ * has >1/3 lifetime remaining (~60 days for a 90-day LE cert), and fetches a+ * fresh one otherwise. If the cert file's mtime changes after the run, we+ * hot-swap the live HTTPS server's SecureContext so new TLS handshakes pick+ * up the new cert without a process restart.+ *+ * Self-signed certs don't renew (the script issues 10-year certs for local+ * use); the renewer is a no-op in that mode.+ */+import { execFile } from 'child_process';+import { existsSync, readFileSync, statSync } from 'fs';+import { join } from 'path';+import { promisify } from 'util';+import { PATHS } from '../lib/fileUtils.js';++const execFileAsync = promisify(execFile);++const CERT_DIR = join(PATHS.data, 'certs');+const CERT_PATH = join(CERT_DIR, 'cert.pem');+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'));+}++async function renewOnce(httpsServer) {+ const meta = readMeta();+ if (!meta || meta.mode !== 'tailscale' || !meta.hostname) return;++ const bin = findTailscale();+ if (!bin) {+ console.log(`⚠️ cert renewer: tailscale CLI not found, skipping renewal`);+ return;+ }++ const mtimeBefore = existsSync(CERT_PATH) ? statSync(CERT_PATH).mtimeMs : 0;++ const { stderr } = await execFileAsync(bin, [+ 'cert',+ `--cert-file=${CERT_PATH}`,+ `--key-file=${KEY_PATH}`,+ meta.hostname+ ]).catch(err => ({ stderr: err.message }));++ if (stderr && !/Wrote (public|private)/.test(stderr)) {+ console.log(`⚠️ cert renewer: tailscale cert stderr: ${stderr.trim().split('\n')[0]}`);+ }++ const mtimeAfter = existsSync(CERT_PATH) ? statSync(CERT_PATH).mtimeMs : 0;+ if (mtimeAfter > mtimeBefore) {+ httpsServer.setSecureContext({+ cert: readFileSync(CERT_PATH),+ key: readFileSync(KEY_PATH)+ });+ console.log(`🔒 cert renewer: hot-swapped renewed cert for ${meta.hostname}`);+ }+}++export function initCertRenewer(httpsServer) {+ if (!httpsServer || typeof httpsServer.setSecureContext !== 'function') return;+ const meta = readMeta();+ if (!meta || meta.mode !== 'tailscale') return;++ renewOnce(httpsServer).catch(err => console.error(`❌ cert renewer initial run: ${err.message}`));+ setInterval(() => {+ renewOnce(httpsServer).catch(err => console.error(`❌ cert renewer: ${err.message}`));+ }, RENEW_INTERVAL_MS).unref();++ console.log(`🔒 cert renewer: scheduled daily renewal for ${meta.hostname}`);+}