fix(run-local): serve HTTPS by default with an auto-generated self-signed cert

Root cause of the wallet balance stuck at '--' and every other mini-app
write silently failing: @noble/ed25519's signing needs crypto.subtle,
which every browser restricts to a secure context (https://, or
http://localhost). A plain http://<lan-ip>:port origin - exactly what a
second device on the same network needs to reach this - is NOT a secure
context, so crypto.subtle is undefined there and init()'s promise
rejects with no .catch(), leaving accountId stuck at undefined forever.

Reproduced directly against the live deployment with a real headless
browser: confirmed 'crypto.subtle must be defined, consider polyfill'
in the console, isSecureContext: false. Fixed by generating a
self-signed cert (openssl, auto-generated on first run, reused after,
SANs cover localhost/127.0.0.1/every detected LAN IPv4) and serving
HTTPS by default - verified end to end: hasSubtle: true,
isSecureContext: true, wallet balance resolves to a real value instead
of '--'. HTTP_ONLY=1 opts back into plain HTTP for same-machine-only
testing, where http://localhost is already a secure context on its own.
This commit is contained in:
OmO Orchestrator committed 2026-11-20 23:43:06 -05:00
1 parent 033db1bfd1
commit 972f578584
1 file changed
+78 -7
+78 -7
View File
@@ -5,15 +5,72 @@
// auto-picked free port. Ctrl+C (or `kill <pid>`) stops it; nothing it does // auto-picked free port. Ctrl+C (or `kill <pid>`) stops it; nothing it does
// persists after the process exits except the SQLite files under // persists after the process exits except the SQLite files under
// COMMONS_DATA_DIR (default: ./.data next to wherever this runs). // COMMONS_DATA_DIR (default: ./.data next to wherever this runs).
import { createServer } from "node:http"; //
// HTTPS by default (self-signed, auto-generated): the Web Crypto API this
// app's Ed25519 identity/signing relies on (crypto.subtle) is restricted by
// every browser to a SECURE CONTEXT - https://, or http://localhost. A
// plain http://<lan-ip>:port origin (exactly what a second device on the
// same network needs to reach this) is NOT a secure context, so
// crypto.subtle is undefined there and every sign() call throws - the
// observed symptom is a wallet balance stuck at "--" forever (accountId
// never resolves) and every mini-app write silently failing the same way.
// A self-signed cert makes the origin secure-context-eligible on every
// browser (Chrome/Firefox/Safari, desktop and mobile) once the one-time
// "not secure, proceed anyway" warning is accepted - unlike the
// Chrome-only insecure-origin flag, which iOS Safari has no equivalent for.
// Set HTTP_ONLY=1 to opt back into plain HTTP (e.g. testing from the same
// machine only, where http://localhost is already a secure context).
import { createServer as createHttpServer } from "node:http";
import { createServer as createHttpsServer } from "node:https";
import { createServer as createNetServer } from "node:net"; import { createServer as createNetServer } from "node:net";
import { readFile } from "node:fs/promises"; import { readFile, writeFile, mkdir as mkdirFs } from "node:fs/promises";
import { existsSync } from "node:fs";
import { extname, join, dirname } from "node:path"; import { extname, join, dirname } from "node:path";
import { fileURLToPath } from "node:url"; import { fileURLToPath } from "node:url";
import { networkInterfaces } from "node:os";
import { execFileSync } from "node:child_process";
const ROOT = dirname(dirname(fileURLToPath(import.meta.url))); const ROOT = dirname(dirname(fileURLToPath(import.meta.url)));
const DIST_DIR = join(ROOT, "dist"); const DIST_DIR = join(ROOT, "dist");
function detectLanIPs() {
const ips = [];
for (const addrs of Object.values(networkInterfaces())) {
for (const a of addrs ?? []) {
if (a.family === "IPv4" && !a.internal) ips.push(a.address);
}
}
return ips;
}
/**
* Reuses an existing cert under dataDir/certs if present; otherwise shells
* out to openssl (present on NixOS and virtually every Linux distro by
* default - no extra Nix input needed) to generate a fresh self-signed
* cert covering localhost/127.0.0.1/::1 plus every detected non-internal
* LAN IPv4 address as a Subject Alternative Name, so whichever address a
* second device actually types in still matches the cert's SANs (a
* mismatch would make most browsers refuse it even past the self-signed
* warning).
*/
async function getOrCreateCert(dataDir) {
const certDir = join(dataDir, "certs");
const keyPath = join(certDir, "key.pem");
const certPath = join(certDir, "cert.pem");
if (existsSync(keyPath) && existsSync(certPath)) {
return { key: await readFile(keyPath), cert: await readFile(certPath) };
}
await mkdirFs(certDir, { recursive: true });
const sanEntries = ["DNS:localhost", "IP:127.0.0.1", "IP:::1", ...detectLanIPs().map((ip) => `IP:${ip}`)];
execFileSync("openssl", [
"req", "-x509", "-newkey", "rsa:2048", "-nodes",
"-keyout", keyPath, "-out", certPath,
"-days", "825", "-subj", "/CN=the-commons-local",
"-addext", `subjectAltName=${sanEntries.join(",")}`,
], { stdio: "ignore" });
return { key: await readFile(keyPath), cert: await readFile(certPath) };
}
// ROOT (dist/, api/, this script itself) is the built package's own // ROOT (dist/, api/, this script itself) is the built package's own
// install path - under `nix run`, that's an immutable Nix store path, so // install path - under `nix run`, that's an immutable Nix store path, so
// it can NEVER be the data directory's default (mkdir there fails with // it can NEVER be the data directory's default (mkdir there fails with
@@ -76,7 +133,7 @@ function findFreePort(preferred) {
}); });
} }
const server = createServer(async (req, res) => { const requestHandler = async (req, res) => {
const pathname = new URL(req.url ?? "/", "http://localhost").pathname; const pathname = new URL(req.url ?? "/", "http://localhost").pathname;
try { try {
if (pathname === "/api/sync") return void (await postSync(req, res)); if (pathname === "/api/sync") return void (await postSync(req, res));
@@ -87,12 +144,26 @@ const server = createServer(async (req, res) => {
} catch (err) { } catch (err) {
sendJson(res, 500, { error: "internal error", detail: err.message }); sendJson(res, 500, { error: "internal error", detail: err.message });
} }
}); };
const preferredPort = Number(process.env.PORT ?? 3001); const finalServer = process.env.HTTP_ONLY === "1"
? createHttpServer(requestHandler)
: createHttpsServer(await getOrCreateCert(DATA_DIR), requestHandler);
const httpOnly = process.env.HTTP_ONLY === "1";
const preferredPort = Number(process.env.PORT ?? (httpOnly ? 3001 : 3443));
const port = await findFreePort(preferredPort); const port = await findFreePort(preferredPort);
server.listen(port, () => { const scheme = httpOnly ? "http" : "https";
console.log(`THE COMMONS running at http://localhost:${port}`);
finalServer.listen(port, () => {
console.log(`THE COMMONS running at ${scheme}://localhost:${port}`);
const lanIPs = detectLanIPs();
if (lanIPs.length > 0) {
console.log(`Reachable from other devices on this network at: ${lanIPs.map((ip) => `${scheme}://${ip}:${port}`).join(", ")}`);
}
if (!httpOnly) {
console.log("Self-signed certificate: your browser will warn 'not secure' the first time - this is expected for a LAN cert with no public CA; click through (Advanced -> Proceed) once per device.");
}
console.log(`Data stored in ${dirname(process.env.BLOB_DB_PATH)}`); console.log(`Data stored in ${dirname(process.env.BLOB_DB_PATH)}`);
console.log("Press Ctrl+C to stop."); console.log("Press Ctrl+C to stop.");
}); });