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(instances): add one-click "Enable HTTPS" button to Tailnet banner

Adam Eivyb2133f2a690a
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
new file mode 100644
index 0000000000..af504d6932
--- /dev/null
+++ b/.changelog/NEXT.md
@@ -0,0 +1,5 @@
+# Next Release
+
+## Added
+
+- **One-click "Enable HTTPS" button on the Instances tab.** The Tailnet DNS & trusted HTTPS explainer used to instruct users to drop into a shell and run `npm run setup:cert`. New button on the same banner runs the same flow at runtime via a new `POST /api/instances/provision-cert` endpoint, which calls `tailscale cert` for the local MagicDNS hostname, writes `data/certs/{cert,key}.pem`, and updates `meta.json`. Failure modes (Tailscale not installed, not running, no MagicDNS hostname, HTTPS Certificates feature disabled in the tailnet admin) surface as toasts with actionable guidance. Because the HTTPS listener type is decided at server boot in `lib/tailscale-https.js`, the response includes `requiresRestart: true` whenever PortOS is currently running over HTTP — the UI then prompts the user to restart so the new cert actually takes effect; if HTTPS was already running, the existing `certRenewer` hot-swap path picks up the renewed cert without a restart. The button is disabled until MagicDNS is detected, mirroring what the underlying CLI requires. Files: `server/services/certProvisioner.js` (new), `server/routes/instances.js`, `client/src/services/apiSystem.js`, `client/src/pages/Instances.jsx`.
diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsx
index f845ce108a..515ba83e91 100644
--- a/client/src/pages/Instances.jsx
+++ b/client/src/pages/Instances.jsx
@@ -13,7 +13,7 @@ import toast from '../components/ui/Toast';
import socket from '../services/socket';
import {
getInstances, updateSelfInstance, addPeer, updatePeer,
- removePeer, connectPeer, probePeer, getTailnetInfo
+ removePeer, connectPeer, probePeer, getTailnetInfo, provisionTailnetCert
} from '../services/api';
import PeerAppsList from '../components/instances/PeerAppsList';
import PeerAgentsSection from '../components/instances/PeerAgentsSection';
@@ -84,12 +84,26 @@ function TailnetHelpBanner({ tailnetInfo }) {
const [collapsed, setCollapsed] = useState(() => {
return localStorage.getItem('portos-tailnet-help-collapsed') === '1';
});
+ const [provisioning, setProvisioning] = useState(false);
+ const [provisionResult, setProvisionResult] = useState(null);
+
const toggle = () => {
const next = !collapsed;
setCollapsed(next);
localStorage.setItem('portos-tailnet-help-collapsed', next ? '1' : '0');
};
+ const provision = async (e) => {
+ e.stopPropagation();
+ setProvisioning(true);
+ setProvisionResult(null);
+ const result = await provisionTailnetCert().catch(() => null);
+ setProvisioning(false);
+ if (!result?.ok) return; // request() already toasted the error
+ setProvisionResult(result);
+ toast.success(result.message);
+ };
+
const status = tailnetInfo === null
? { label: 'Tailscale DNS not detected', tone: 'warn', detail: 'Install Tailscale and enable MagicDNS in your tailnet admin to auto-suggest peer DNS names.' }
: tailnetInfo?.suffix
@@ -99,6 +113,11 @@ function TailnetHelpBanner({ tailnetInfo }) {
const ToneIcon = status.tone === 'ok' ? CheckCircle2 : AlertCircle;
const toneClass = status.tone === 'ok' ? 'text-port-success' : 'text-port-warning';
+ // Only offer the one-click provision button when Tailscale is actually
+ // detected and we have a MagicDNS hostname for this instance — otherwise
+ // the API call will fail with the same "enable MagicDNS first" guidance.
+ const canProvision = !!tailnetInfo?.self;
+
return (
<div className="bg-port-card border border-port-border rounded-xl">
<button
@@ -132,9 +151,33 @@ function TailnetHelpBanner({ tailnetInfo }) {
</p>
<ol className="list-decimal list-inside space-y-1 text-gray-500">
<li>On each instance, enable MagicDNS + HTTPS Certificates in your tailnet admin (<span className="font-mono">login.tailscale.com/admin/dns</span>).</li>
- <li>Run <span className="font-mono text-gray-300">npm run setup:cert</span> on each instance to fetch the cert.</li>
+ <li>
+ Click <span className="text-port-accent">Enable HTTPS</span> below to fetch the cert via Tailscale
+ (or run <span className="font-mono text-gray-300">npm run setup:cert</span> from a shell).
+ </li>
<li>Below, click <span className="text-port-accent">use {`<host>`}</span> on each peer to switch the link to HTTPS. Or click <span className="text-gray-400">use IP only</span> to revert.</li>
</ol>
+ <div className="flex items-center gap-2 flex-wrap pt-1">
+ <button
+ onClick={provision}
+ disabled={provisioning || !canProvision}
+ title={canProvision
+ ? `Run \`tailscale cert\` for ${tailnetInfo.self} and write data/certs/{cert,key}.pem`
+ : 'Enable MagicDNS in your tailnet admin first, then reload this page'}
+ className="inline-flex items-center gap-1.5 bg-port-accent hover:bg-port-accent/80 disabled:opacity-40 disabled:cursor-not-allowed text-white px-3 py-1.5 rounded text-xs font-medium transition-colors min-h-[40px] sm:min-h-0"
+ >
+ <Lock size={12} />
+ {provisioning ? 'Provisioning…' : 'Enable HTTPS'}
+ </button>
+ {provisionResult?.ok && (
+ <span className="inline-flex items-center gap-1 text-[11px] text-port-success">
+ <CheckCircle2 size={11} />
+ {provisionResult.requiresRestart
+ ? 'Cert installed — restart PortOS to activate HTTPS'
+ : 'Cert installed and live'}
+ </span>
+ )}
+ </div>
</div>
)}
</div>
diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.js
index 05b36536ca..4add2d4ea1 100644
--- a/client/src/services/apiSystem.js
+++ b/client/src/services/apiSystem.js
@@ -111,6 +111,7 @@ export const connectPeer = (id) => request(`/instances/peers/${id}/connect`, { m
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');
+export const provisionTailnetCert = () => request('/instances/provision-cert', { method: 'POST' });
// Image Generation
export const getImageGenStatus = () => request('/image-gen/status');
diff --git a/server/routes/instances.js b/server/routes/instances.js
index 4b5c28ea35..6d4ca14769 100644
--- a/server/routes/instances.js
+++ b/server/routes/instances.js
@@ -10,6 +10,7 @@ import { execFile } from 'child_process';
import { promisify } from 'util';
import * as instances from '../services/instances.js';
import { getSyncStatus } from '../services/syncOrchestrator.js';
+import { provisionTailscaleCert } from '../services/certProvisioner.js';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { DEFAULT_PEER_PORT } from '../lib/ports.js';
import { findTailscale } from '../lib/tailscale.js';
@@ -111,6 +112,18 @@ 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.
+router.post('/provision-cert', asyncHandler(async (req, res) => {
+ const result = await provisionTailscaleCert();
+ if (!result.ok) {
+ // Map to apiCore.js error envelope so the client auto-toasts the message.
+ return res.status(400).json({ error: result.message, code: result.reason });
+ }
+ res.json(result);
+}));
+
// GET /api/instances/self — get this instance's identity
router.get('/self', asyncHandler(async (req, res) => {
const self = await instances.getSelf();
diff --git a/server/services/certProvisioner.js b/server/services/certProvisioner.js
new file mode 100644
index 0000000000..3e5a39146e
--- /dev/null
+++ b/server/services/certProvisioner.js
@@ -0,0 +1,134 @@
+/**
+ * Cert provisioner — runtime equivalent of `npm run setup:cert`.
+ *
+ * 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.
+ *
+ * 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.
+ */
+import { execFile } from 'child_process';
+import { existsSync, mkdirSync, writeFileSync, 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);
+
+const CERT_DIR = join(PATHS.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');
+
+async function tailscaleStatus(bin) {
+ const { stdout } = await execFileAsync(bin, ['status', '--json'], { timeout: 5000 });
+ return JSON.parse(stdout);
+}
+
+/**
+ * Run `tailscale cert` for the local MagicDNS hostname. Returns a result
+ * object describing what happened. Never throws — all known failure modes
+ * surface as `{ ok: false, reason, message }` so the UI can render an
+ * actionable toast.
+ */
+export async function provisionTailscaleCert() {
+ const bin = findTailscale();
+ if (!bin) {
+ return {
+ ok: false,
+ reason: 'tailscale-not-installed',
+ message: 'Tailscale CLI not found. Install Tailscale first.'
+ };
+ }
+
+ const status = await tailscaleStatus(bin).catch(err => ({ _err: err.message }));
+ if (status?._err) {
+ return {
+ ok: false,
+ reason: 'tailscale-status-failed',
+ message: `tailscale status failed: ${status._err}`
+ };
+ }
+
+ if (status?.BackendState !== 'Running') {
+ return {
+ ok: false,
+ reason: 'tailscale-not-running',
+ message: `Tailscale is ${status?.BackendState || 'not running'}. Start the Tailscale app, then try again.`
+ };
+ }
+
+ const hostname = (status?.Self?.DNSName || '').replace(/\.$/, '');
+ if (!hostname) {
+ return {
+ ok: false,
+ reason: 'no-magic-dns',
+ message: 'No MagicDNS hostname for this device. Enable MagicDNS at login.tailscale.com/admin/dns.'
+ };
+ }
+
+ // 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;
+
+ const certResult = await execFileAsync(bin, [
+ 'cert',
+ `--cert-file=${CERT_PATH}`,
+ `--key-file=${KEY_PATH}`,
+ hostname
+ ], { timeout: 60_000 }).catch(err => ({ _err: err.stderr?.toString() || err.message }));
+
+ if (certResult?._err) {
+ const stderr = certResult._err.trim();
+ const httpsHint = /HTTPS.*not.*enabled|invalid request/i.test(stderr)
+ ? ' Enable "HTTPS Certificates" at login.tailscale.com/admin/dns and retry.'
+ : '';
+ return {
+ ok: false,
+ reason: 'tailscale-cert-failed',
+ message: `tailscale cert failed: ${stderr.split('\n')[0]}.${httpsHint}`
+ };
+ }
+
+ if (!existsSync(CERT_PATH) || !existsSync(KEY_PATH)) {
+ return {
+ ok: false,
+ reason: 'cert-files-missing',
+ message: 'tailscale cert returned success but cert files are missing.'
+ };
+ }
+
+ const afterMtime = statSync(CERT_PATH).mtimeMs;
+ const wroteNew = afterMtime > beforeMtime;
+
+ writeFileSync(META_PATH, JSON.stringify({
+ mode: 'tailscale',
+ hostname,
+ issuedAt: new Date().toISOString(),
+ certMtime: afterMtime
+ }, null, 2));
+
+ console.log(`🔒 Provisioned Tailscale cert for ${hostname} (new=${wroteNew}, restart=${httpAtBoot})`);
+
+ const restartHint = httpAtBoot
+ ? ' Restart PortOS (npm start) to enable HTTPS on :5555.'
+ : '';
+
+ return {
+ ok: true,
+ mode: 'tailscale',
+ hostname,
+ wroteNew,
+ requiresRestart: httpAtBoot,
+ message: `Cert installed for ${hostname}.${restartHint}`
+ };
+}