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.
170 lines
7.5 KiB
JavaScript
170 lines
7.5 KiB
JavaScript
#!/usr/bin/env node
|
|
// Ad-hoc local runner for `nix run` - no system service, no global config.
|
|
// Serves the built static frontend (dist/) and the api/* handlers (blob
|
|
// store + signed-event relay + admin aggregate) from ONE process on ONE
|
|
// auto-picked free port. Ctrl+C (or `kill <pid>`) stops it; nothing it does
|
|
// persists after the process exits except the SQLite files under
|
|
// COMMONS_DATA_DIR (default: ./.data next to wherever this runs).
|
|
//
|
|
// 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 { readFile, writeFile, mkdir as mkdirFs } from "node:fs/promises";
|
|
import { existsSync } from "node:fs";
|
|
import { extname, join, dirname } from "node:path";
|
|
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 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
|
|
// 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
|
|
// ENOENT/EACCES, Nix store paths are read-only by design). The data dir
|
|
// must default to somewhere always writable regardless of how this
|
|
// script is invoked: the directory the user is actually running from.
|
|
const DATA_DIR = process.env.COMMONS_DATA_DIR ?? join(process.cwd(), ".data");
|
|
process.env.BLOB_DB_PATH ??= join(DATA_DIR, "blobs.sqlite3");
|
|
process.env.EVENT_DB_PATH ??= join(DATA_DIR, "events.sqlite3");
|
|
await import("node:fs/promises").then((fs) =>
|
|
fs.mkdir(dirname(process.env.BLOB_DB_PATH), { recursive: true }),
|
|
);
|
|
|
|
const { default: postBlob } = await import("../api/blob/index.ts");
|
|
const { default: getBlob } = await import("../api/blob/[id].ts");
|
|
const { default: postSync } = await import("../api/sync/index.ts");
|
|
const { default: getAggregate } = await import("../api/admin/aggregate.ts");
|
|
const { sendJson } = await import("../api/_lib/httpUtils.ts");
|
|
|
|
const MIME = {
|
|
".html": "text/html", ".js": "text/javascript", ".css": "text/css",
|
|
".json": "application/json", ".svg": "image/svg+xml", ".png": "image/png",
|
|
".ico": "image/x-icon", ".webmanifest": "application/manifest+json",
|
|
};
|
|
|
|
async function serveStatic(pathname, res) {
|
|
let filePath = join(DIST_DIR, pathname === "/" ? "index.html" : pathname);
|
|
try {
|
|
const data = await readFile(filePath);
|
|
res.writeHead(200, { "Content-Type": MIME[extname(filePath)] ?? "application/octet-stream" });
|
|
res.end(data);
|
|
} catch {
|
|
// SPA fallback, matching the nginx `tryFiles $uri /index.html` behavior
|
|
// the NixOS module's vhost config uses.
|
|
try {
|
|
const data = await readFile(join(DIST_DIR, "index.html"));
|
|
res.writeHead(200, { "Content-Type": "text/html" });
|
|
res.end(data);
|
|
} catch {
|
|
sendJson(res, 404, { error: "not found - did you run `npm run build` first?" });
|
|
}
|
|
}
|
|
}
|
|
|
|
function findFreePort(preferred) {
|
|
return new Promise((resolve, reject) => {
|
|
const probe = createNetServer();
|
|
probe.unref();
|
|
probe.on("error", (err) => {
|
|
if (err.code === "EADDRINUSE") {
|
|
probe.close(() => findFreePort(0).then(resolve, reject));
|
|
} else {
|
|
reject(err);
|
|
}
|
|
});
|
|
probe.listen(preferred, "0.0.0.0", () => {
|
|
const { port } = probe.address();
|
|
probe.close(() => resolve(port));
|
|
});
|
|
});
|
|
}
|
|
|
|
const requestHandler = async (req, res) => {
|
|
const pathname = new URL(req.url ?? "/", "http://localhost").pathname;
|
|
try {
|
|
if (pathname === "/api/sync") return void (await postSync(req, res));
|
|
if (pathname === "/api/admin/aggregate") return void (await getAggregate(req, res));
|
|
if (pathname === "/api/blob") return void (await postBlob(req, res));
|
|
if (pathname.startsWith("/api/blob/")) return void (await getBlob(req, res));
|
|
await serveStatic(pathname, res);
|
|
} catch (err) {
|
|
sendJson(res, 500, { error: "internal error", detail: err.message });
|
|
}
|
|
};
|
|
|
|
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 scheme = httpOnly ? "http" : "https";
|
|
|
|
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("Press Ctrl+C to stop.");
|
|
});
|