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
address review: atomic meta write, accurate restart hint, scope docs
Adam Eivy3b5c219d69cb
diff --git a/server/index.js b/server/index.jsindex a16ffc6cfb..9404ae287f 100644--- a/server/index.js+++ b/server/index.js@@ -91,6 +91,7 @@ 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 { setHttpsEnabledAtBoot } from './lib/httpsState.js';import { initTaskLearning } from './services/taskLearning.js';import { recordSession, recordMessages } from './services/usage.js';import { errorEvents } from './lib/errorHandler.js';@@ -127,6 +128,7 @@ const CERT_DIR = join(PATHS.data, 'certs');const { server: httpServer, mirror: localHttpServer, httpsEnabled } =createTailscaleServers(app, { certDir: CERT_DIR });const scheme = httpsEnabled ? 'https' : 'http';+setHttpsEnabledAtBoot(httpsEnabled);// Socket.IO with relative path support for Tailscaleconst io = new Server(httpServer, {diff --git a/server/lib/httpsState.js b/server/lib/httpsState.jsnew file mode 100644index 0000000000..2173ada44e--- /dev/null+++ b/server/lib/httpsState.js@@ -0,0 +1,24 @@+/**+ * Captures whether PortOS booted with HTTPS active. The decision is made once+ * at server start (see lib/tailscale-https.js) — `createTailscaleServers`+ * inspects cert presence and returns an http or https server accordingly.+ * After that, the listener type is frozen for the life of the process.+ *+ * Consumers (e.g. certProvisioner) need this signal to decide whether+ * provisioning a new cert at runtime requires a restart. Checking cert file+ * presence isn't enough — once cert files exist, every subsequent provision+ * call would falsely report "no restart needed" even though the process is+ * still serving HTTP.+ */++let httpsEnabledAtBoot = false;+let initialized = false;++export function setHttpsEnabledAtBoot(value) {+ httpsEnabledAtBoot = Boolean(value);+ initialized = true;+}++export function getHttpsEnabledAtBoot() {+ return { value: httpsEnabledAtBoot, initialized };+}diff --git a/server/routes/instances.js b/server/routes/instances.jsindex 6d4ca14769..8ea1fba171 100644--- a/server/routes/instances.js+++ b/server/routes/instances.js@@ -112,9 +112,11 @@ router.get('/tailnet-suffix', asyncHandler(async (req, res) => {res.json({ suffix, self: (status?.Self?.DNSName ?? '').replace(/\.$/, '') || null, peers });}));-// POST /api/instances/provision-cert — runtime equivalent of `npm run setup:cert`.-// Fetches a Let's Encrypt cert via `tailscale cert` for the local MagicDNS-// hostname so the user can enable trusted HTTPS without dropping to a shell.+// POST /api/instances/provision-cert — runtime helper for the Tailscale/MagicDNS+// certificate path from `npm run setup:cert` (not the script's self-signed fallback+// or regeneration logic). Fetches a Let's Encrypt cert via `tailscale cert` for+// the local MagicDNS hostname so the user can enable trusted HTTPS without dropping+// to a shell.router.post('/provision-cert', asyncHandler(async (req, res) => {const result = await provisionTailscaleCert();if (!result.ok) {diff --git a/server/services/certProvisioner.js b/server/services/certProvisioner.jsindex 3e5a39146e..690473f6b7 100644--- a/server/services/certProvisioner.js+++ b/server/services/certProvisioner.js@@ -1,21 +1,29 @@/**- * Cert provisioner — runtime equivalent of `npm run setup:cert`.+ * Cert provisioner — runtime equivalent of the Tailscale `setup:cert` path.** Invokes `tailscale cert` to fetch a Let's Encrypt cert for this instance's* MagicDNS hostname, writes it to data/certs/{cert,key}.pem, and updates* meta.json. Returns a structured result the API can surface to the UI.*+ * This service only handles Tailscale-backed certificate provisioning. It+ * does not generate self-signed certs or implement the regeneration/expiry+ * logic that exists in scripts/setup-cert.js.+ ** The HTTPS listener type is decided at server boot (lib/tailscale-https.js).- * If PortOS booted in HTTP mode (no cert present), the new cert only takes- * effect after a restart — the response sets requiresRestart=true so the UI- * can prompt the user.+ * If PortOS booted in HTTP mode, the new cert only takes effect after a+ * restart — the response sets requiresRestart=true so the UI can prompt the+ * user. This is keyed off the boot-time HTTPS state (httpsState.js), not+ * cert file presence, because cert files can exist on disk while the running+ * process is still serving HTTP (e.g. provision was run twice without a+ * restart in between).*/import { execFile } from 'child_process';-import { existsSync, mkdirSync, writeFileSync, statSync } from 'fs';+import { existsSync, mkdirSync, statSync } from 'fs';import { join } from 'path';import { promisify } from 'util';-import { PATHS } from '../lib/fileUtils.js';+import { PATHS, atomicWrite } from '../lib/fileUtils.js';import { findTailscale } from '../lib/tailscale.js';+import { getHttpsEnabledAtBoot } from '../lib/httpsState.js';const execFileAsync = promisify(execFile);@@ -71,11 +79,6 @@ export async function provisionTailscaleCert() {};}- // If cert files don't exist yet, PortOS booted in HTTP mode — restart is- // required to actually serve HTTPS. If they already exist, certRenewer's- // hot-swap path will pick up the new cert on its next tick.- const httpAtBoot = !existsSync(CERT_PATH) || !existsSync(KEY_PATH);-mkdirSync(CERT_DIR, { recursive: true });const beforeMtime = existsSync(CERT_PATH) ? statSync(CERT_PATH).mtimeMs : 0;@@ -110,17 +113,24 @@ export async function provisionTailscaleCert() {const afterMtime = statSync(CERT_PATH).mtimeMs;const wroteNew = afterMtime > beforeMtime;- writeFileSync(META_PATH, JSON.stringify({+ await atomicWrite(META_PATH, {mode: 'tailscale',hostname,issuedAt: new Date().toISOString(),certMtime: afterMtime- }, null, 2));+ });++ // requiresRestart is keyed off the boot-time HTTPS state, not cert file+ // presence. The listener type was frozen at boot — if PortOS started in+ // HTTP mode, no amount of subsequent provisioning can flip it without a+ // restart, even when the cert files now exist on disk.+ const httpsState = getHttpsEnabledAtBoot();+ const requiresRestart = !httpsState.value;- console.log(`🔒 Provisioned Tailscale cert for ${hostname} (new=${wroteNew}, restart=${httpAtBoot})`);+ console.log(`🔒 Provisioned Tailscale cert for ${hostname} (new=${wroteNew}, restart=${requiresRestart})`);- const restartHint = httpAtBoot- ? ' Restart PortOS (npm start) to enable HTTPS on :5555.'+ const restartHint = requiresRestart+ ? ' Restart PortOS to enable HTTPS on :5555.': '';return {@@ -128,7 +138,7 @@ export async function provisionTailscaleCert() {mode: 'tailscale',hostname,wroteNew,- requiresRestart: httpAtBoot,+ requiresRestart,message: `Cert installed for ${hostname}.${restartHint}`};}