Skip to content

Open-source SEO, GEO, and marketing skills for AI agents.

fix(upgrade): make in-app npm updates restart safely

Yuting Zhongd57dd170e790
diff --git a/notfair/src/app/api/restart/route.test.ts b/notfair/src/app/api/restart/route.test.ts
new file mode 100644
index 00000000..86ecb4d4
--- /dev/null
+++ b/notfair/src/app/api/restart/route.test.ts
@@ -0,0 +1,57 @@
+import { EventEmitter } from "node:events";
+import { homedir } from "node:os";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ spawn: vi.fn(),
+}));
+
+vi.mock("node:child_process", () => ({ spawn: mocks.spawn }));
+
+import { POST } from "./route";
+
+function fakeChild() {
+ const child = new EventEmitter() as EventEmitter & {
+ stdout: EventEmitter;
+ };
+ child.stdout = new EventEmitter();
+ return child;
+}
+
+describe("POST /api/restart", () => {
+ const originalManaged = process.env.NOTFAIR_MANAGED;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ process.env.NOTFAIR_MANAGED = "daemon";
+ });
+
+ afterEach(() => {
+ if (originalManaged === undefined) {
+ delete process.env.NOTFAIR_MANAGED;
+ } else {
+ process.env.NOTFAIR_MANAGED = originalManaged;
+ }
+ });
+
+ it("looks up the global CLI from the stable home directory", async () => {
+ const child = fakeChild();
+ mocks.spawn.mockReturnValue(child);
+
+ const responsePromise = POST();
+
+ expect(mocks.spawn).toHaveBeenCalledWith(
+ "npm",
+ ["root", "-g"],
+ expect.objectContaining({ cwd: homedir() }),
+ );
+
+ child.emit("close", 1);
+ const response = await responsePromise;
+ expect(response.status).toBe(409);
+ await expect(response.json()).resolves.toMatchObject({
+ ok: false,
+ error: "Could not locate the globally-installed notfair CLI.",
+ });
+ });
+});
diff --git a/notfair/src/app/api/restart/route.ts b/notfair/src/app/api/restart/route.ts
index 6b2cf6ae..2a92b205 100644
--- a/notfair/src/app/api/restart/route.ts
+++ b/notfair/src/app/api/restart/route.ts
@@ -1,5 +1,6 @@
import { spawn } from "node:child_process";
import { existsSync } from "node:fs";
+import { homedir } from "node:os";
import { join } from "node:path";
import { NextResponse } from "next/server";
@@ -63,7 +64,7 @@ export async function POST() {
spawn(
process.execPath,
["-e", waiter, String(process.pid), cli, port, dataDir],
- { detached: true, stdio: "ignore" },
+ { cwd: homedir(), detached: true, stdio: "ignore" },
).unref();
scheduleExit();
return NextResponse.json({ ok: true, note: "Restarting…" });
@@ -89,7 +90,10 @@ async function globalCliPath(): Promise<string | null> {
let out = "";
let child;
try {
- child = spawn("npm", ["root", "-g"], { stdio: ["ignore", "pipe", "ignore"] });
+ child = spawn("npm", ["root", "-g"], {
+ cwd: homedir(),
+ stdio: ["ignore", "pipe", "ignore"],
+ });
} catch {
resolve(null);
return;
diff --git a/notfair/src/app/api/upgrade/route.test.ts b/notfair/src/app/api/upgrade/route.test.ts
new file mode 100644
index 00000000..d13afb53
--- /dev/null
+++ b/notfair/src/app/api/upgrade/route.test.ts
@@ -0,0 +1,104 @@
+import { EventEmitter } from "node:events";
+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { homedir, tmpdir } from "node:os";
+import { join } from "node:path";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ spawn: vi.fn(),
+}));
+
+vi.mock("node:child_process", () => ({ spawn: mocks.spawn }));
+vi.mock("@/server/version", () => ({
+ _resetLatestCache: vi.fn(),
+ getCurrentVersion: vi.fn(() => "0.9.7"),
+ getLatestVersion: vi.fn(async () => "0.9.8"),
+}));
+
+import { POST, syncInstalledNativeBindings } from "./route";
+
+function fakeChild() {
+ const child = new EventEmitter() as EventEmitter & {
+ stdout: EventEmitter;
+ stderr: EventEmitter;
+ kill: ReturnType<typeof vi.fn>;
+ };
+ child.stdout = new EventEmitter();
+ child.stderr = new EventEmitter();
+ child.kill = vi.fn();
+ return child;
+}
+
+describe("POST /api/upgrade", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("starts npm from the stable home directory instead of the server cwd", async () => {
+ const child = fakeChild();
+ mocks.spawn.mockReturnValue(child);
+
+ const responsePromise = POST();
+
+ expect(mocks.spawn).toHaveBeenCalledWith(
+ "npm",
+ ["i", "-g", "notfair@latest"],
+ expect.objectContaining({ cwd: homedir() }),
+ );
+
+ child.emit("exit", 7);
+ const response = await responsePromise;
+ expect(response.status).toBe(500);
+ await expect(response.json()).resolves.toMatchObject({
+ ok: false,
+ error: "npm exited with code 7",
+ });
+ });
+
+ it("replaces standalone native bindings with npm's runtime-compatible copy", async () => {
+ const packageRoot = await mkdtemp(join(tmpdir(), "notfair-upgrade-"));
+ const runtimeDir = join(packageRoot, "node_modules", "better-sqlite3", "build", "Release");
+ const tracedDir = join(
+ packageRoot,
+ ".next",
+ "standalone",
+ ".next",
+ "node_modules",
+ "better-sqlite3-build-copy",
+ "build",
+ "Release",
+ );
+ const nestedDir = join(
+ packageRoot,
+ ".next",
+ "standalone",
+ "node_modules",
+ "better-sqlite3",
+ "build",
+ "Release",
+ );
+
+ try {
+ await Promise.all([
+ mkdir(runtimeDir, { recursive: true }),
+ mkdir(tracedDir, { recursive: true }),
+ mkdir(nestedDir, { recursive: true }),
+ ]);
+ await writeFile(join(runtimeDir, "better_sqlite3.node"), "node-25-binding");
+ await Promise.all([
+ writeFile(join(tracedDir, "better_sqlite3.node"), "node-24-binding"),
+ writeFile(join(nestedDir, "better_sqlite3.node"), "node-24-binding"),
+ ]);
+
+ await expect(syncInstalledNativeBindings(packageRoot)).resolves.toBe(2);
+ await expect(readFile(join(tracedDir, "better_sqlite3.node"), "utf8")).resolves.toBe(
+ "node-25-binding",
+ );
+ await expect(readFile(join(nestedDir, "better_sqlite3.node"), "utf8")).resolves.toBe(
+ "node-25-binding",
+ );
+ } finally {
+ await rm(packageRoot, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/notfair/src/app/api/upgrade/route.ts b/notfair/src/app/api/upgrade/route.ts
index 04d52c20..925ccfb9 100644
--- a/notfair/src/app/api/upgrade/route.ts
+++ b/notfair/src/app/api/upgrade/route.ts
@@ -1,4 +1,7 @@
import { spawn } from "node:child_process";
+import { copyFile, readdir } from "node:fs/promises";
+import { homedir } from "node:os";
+import { join } from "node:path";
import { NextResponse } from "next/server";
import { _resetLatestCache, getCurrentVersion, getLatestVersion } from "@/server/version";
@@ -22,13 +25,16 @@ const TAIL_BYTES = 4_000;
* the client can show the copyable command instead.
*/
export async function POST() {
- // Use a login shell so the npm install runs against the user's actual
- // PATH (Homebrew Node etc.). `-l` ensures their shell profile is read.
+ // A running standalone bundle can be replaced by a source rebuild or by
+ // the upgrade itself. Never let npm inherit that now-missing directory:
+ // Node aborts in process.cwd() with ENOENT (`npm` exit code 7) before the
+ // install even starts. The user's home directory is stable across both.
return new Promise<Response>((resolve) => {
const startedAt = Date.now();
const child = spawn("npm", ["i", "-g", "notfair@latest"], {
stdio: ["ignore", "pipe", "pipe"],
env: process.env,
+ cwd: homedir(),
});
let stdout = "";
@@ -72,6 +78,22 @@ export async function POST() {
clearTimeout(killTimer);
const elapsed_ms = Date.now() - startedAt;
if (code === 0) {
+ try {
+ await syncGlobalNativeBindings();
+ } catch (error) {
+ resolve(
+ NextResponse.json(
+ {
+ ok: false,
+ error: "NotFair was installed, but its native database module could not be prepared for this Node.js version.",
+ hint: error instanceof Error ? error.message : String(error),
+ command: "npm i -g notfair@latest",
+ },
+ { status: 500 },
+ ),
+ );
+ return;
+ }
_resetLatestCache();
// Confirm by refreshing the version snapshot. The current version
// is still the old one (we're still running) — but `latest` from
@@ -112,3 +134,68 @@ export async function POST() {
});
});
}
+
+async function syncGlobalNativeBindings() {
+ const root = await npmGlobalRoot();
+ await syncInstalledNativeBindings(join(root, "notfair"));
+}
+
+async function npmGlobalRoot(): Promise<string> {
+ return new Promise((resolve, reject) => {
+ let stdout = "";
+ const child = spawn("npm", ["root", "-g"], {
+ stdio: ["ignore", "pipe", "pipe"],
+ env: process.env,
+ cwd: homedir(),
+ });
+ child.stdout?.on("data", (chunk: Buffer) => {
+ stdout += chunk.toString("utf8");
+ });
+ child.on("error", reject);
+ child.on("exit", (code) => {
+ const root = stdout.trim();
+ if (code === 0 && root) {
+ resolve(root);
+ } else {
+ reject(new Error(`Could not locate npm's global package directory (exit ${code}).`));
+ }
+ });
+ });
+}
+
+/**
+ * Next.js standalone output contains a traced copy of better-sqlite3. That
+ * copy was compiled on the release builder, while npm installs the package's
+ * top-level dependency for the user's current Node ABI. Replace every traced
+ * native binding with that runtime-correct copy before restarting the server.
+ */
+export async function syncInstalledNativeBindings(packageRoot: string) {
+ const runtimeBinding = join(
+ packageRoot,
+ "node_modules",
+ "better-sqlite3",
+ "build",
+ "Release",
+ "better_sqlite3.node",
+ );
+ const standaloneRoot = join(packageRoot, ".next", "standalone");
+ const targets = await findNativeBindings(standaloneRoot);
+
+ if (targets.length === 0) return 0;
+
+ await Promise.all(targets.map((target) => copyFile(runtimeBinding, target)));
+ return targets.length;
+}
+
+async function findNativeBindings(directory: string): Promise<string[]> {
+ const entries = await readdir(directory, { withFileTypes: true });
+ const nested = await Promise.all(
+ entries.map(async (entry): Promise<string[]> => {
+ const path = join(directory, entry.name);
+ if (entry.isDirectory()) return findNativeBindings(path);
+ if (entry.isFile() && entry.name === "better_sqlite3.node") return [path];
+ return [];
+ }),
+ );
+ return nested.flat();
+}