Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

feat(cli): detect native binary platform from file header instead of dlopen

ardaaltinors69d28bec4d39
diff --git a/bin/omniroute.mjs b/bin/omniroute.mjs
index be0b624134..c2c11c0194 100755
--- a/bin/omniroute.mjs
+++ b/bin/omniroute.mjs
@@ -17,6 +17,7 @@ import { existsSync, readFileSync } from "node:fs";
import { join, dirname } from "node:path";
import { fileURLToPath } from "node:url";
import { homedir, platform } from "node:os";
+import { isNativeBinaryCompatible } from "../scripts/native-binary-compat.mjs";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
@@ -194,9 +195,9 @@ if (!existsSync(serverJs)) {
}
// ── Pre-flight: verify better-sqlite3 native binary ───────
-// The published binary targets linux-x64. Check both platform match AND
-// dlopen — on macOS, dlopen alone may succeed on an incompatible binary
-// (false positive), so we check platform first as the primary signal.
+// Verify the binary's actual target platform/arch before trusting dlopen.
+// This avoids the macOS false positive where a bundled linux-x64 addon can
+// appear to load even though the runtime will fail when better-sqlite3 starts.
const sqliteBinary = join(
APP_DIR,
"node_modules",
@@ -205,25 +206,15 @@ const sqliteBinary = join(
"Release",
"better_sqlite3.node"
);
-if (existsSync(sqliteBinary)) {
- let compatible = false;
- try {
- process.dlopen({ exports: {} }, sqliteBinary);
- compatible = true;
- } catch {
- // dlopen failed — definitely incompatible
- }
-
- if (!compatible) {
- console.error(
- "\x1b[31m✖ better-sqlite3 native module is incompatible with this platform.\x1b[0m"
- );
- console.error(` Run: cd ${APP_DIR} && npm rebuild better-sqlite3`);
- if (platform() === "darwin") {
- console.error(" If build tools are missing: xcode-select --install");
- }
- process.exit(1);
+if (existsSync(sqliteBinary) && !isNativeBinaryCompatible(sqliteBinary)) {
+ console.error(
+ "\x1b[31m✖ better-sqlite3 native module is incompatible with this platform.\x1b[0m"
+ );
+ console.error(` Run: cd ${APP_DIR} && npm rebuild better-sqlite3`);
+ if (platform() === "darwin") {
+ console.error(" If build tools are missing: xcode-select --install");
}
+ process.exit(1);
}
// ── Start server ───────────────────────────────────────────
diff --git a/scripts/native-binary-compat.mjs b/scripts/native-binary-compat.mjs
new file mode 100644
index 0000000000..74fa21adbc
--- /dev/null
+++ b/scripts/native-binary-compat.mjs
@@ -0,0 +1,158 @@
+import { existsSync, readFileSync } from "node:fs";
+
+export const PUBLISHED_BUILD_PLATFORM = "linux";
+export const PUBLISHED_BUILD_ARCH = "x64";
+
+function mapElfMachine(machine) {
+ switch (machine) {
+ case 62:
+ return "x64";
+ case 183:
+ return "arm64";
+ default:
+ return null;
+ }
+}
+
+function mapMachCpuType(cpuType) {
+ switch (cpuType) {
+ case 0x01000007:
+ return "x64";
+ case 0x0100000c:
+ return "arm64";
+ default:
+ return null;
+ }
+}
+
+function mapPeMachine(machine) {
+ switch (machine) {
+ case 0x8664:
+ return "x64";
+ case 0xaa64:
+ return "arm64";
+ default:
+ return null;
+ }
+}
+
+function readUInt16(buffer, offset, littleEndian) {
+ return littleEndian ? buffer.readUInt16LE(offset) : buffer.readUInt16BE(offset);
+}
+
+function readUInt32(buffer, offset, littleEndian) {
+ return littleEndian ? buffer.readUInt32LE(offset) : buffer.readUInt32BE(offset);
+}
+
+function detectElfTarget(buffer) {
+ if (buffer.length < 20) return null;
+ if (buffer[0] !== 0x7f || buffer[1] !== 0x45 || buffer[2] !== 0x4c || buffer[3] !== 0x46) {
+ return null;
+ }
+
+ const littleEndian = buffer[5] !== 2;
+ const arch = mapElfMachine(readUInt16(buffer, 18, littleEndian));
+ if (!arch) return null;
+
+ return { platform: "linux", architectures: [arch] };
+}
+
+function detectMachTarget(buffer) {
+ if (buffer.length < 8) return null;
+
+ const magic = buffer.readUInt32BE(0);
+ const thinMagic = new Map([
+ [0xfeedface, false],
+ [0xfeedfacf, false],
+ [0xcefaedfe, true],
+ [0xcffaedfe, true],
+ ]);
+ const fatMagic = new Map([
+ [0xcafebabe, false],
+ [0xcafebabf, false],
+ [0xbebafeca, true],
+ [0xbfbafeca, true],
+ ]);
+
+ if (thinMagic.has(magic)) {
+ const littleEndian = thinMagic.get(magic);
+ const arch = mapMachCpuType(readUInt32(buffer, 4, littleEndian));
+ if (!arch) return null;
+ return { platform: "darwin", architectures: [arch] };
+ }
+
+ if (!fatMagic.has(magic)) return null;
+
+ const littleEndian = fatMagic.get(magic);
+ const isFat64 = magic === 0xcafebabf || magic === 0xbfbafeca;
+ const archCount = readUInt32(buffer, 4, littleEndian);
+ const entrySize = isFat64 ? 32 : 20;
+ const architectures = new Set();
+
+ for (let index = 0; index < archCount; index += 1) {
+ const offset = 8 + index * entrySize;
+ if (offset + 4 > buffer.length) break;
+ const arch = mapMachCpuType(readUInt32(buffer, offset, littleEndian));
+ if (arch) architectures.add(arch);
+ }
+
+ if (architectures.size === 0) return null;
+ return { platform: "darwin", architectures: [...architectures] };
+}
+
+function detectPeTarget(buffer) {
+ if (buffer.length < 0x40) return null;
+ if (buffer[0] !== 0x4d || buffer[1] !== 0x5a) return null;
+
+ const peHeaderOffset = buffer.readUInt32LE(0x3c);
+ if (peHeaderOffset + 6 > buffer.length) return null;
+ if (
+ buffer[peHeaderOffset] !== 0x50 ||
+ buffer[peHeaderOffset + 1] !== 0x45 ||
+ buffer[peHeaderOffset + 2] !== 0x00 ||
+ buffer[peHeaderOffset + 3] !== 0x00
+ ) {
+ return null;
+ }
+
+ const arch = mapPeMachine(buffer.readUInt16LE(peHeaderOffset + 4));
+ if (!arch) return null;
+ return { platform: "win32", architectures: [arch] };
+}
+
+export function detectNativeBinaryTarget(buffer) {
+ return detectElfTarget(buffer) ?? detectMachTarget(buffer) ?? detectPeTarget(buffer) ?? null;
+}
+
+export function readNativeBinaryTarget(binaryPath) {
+ if (!existsSync(binaryPath)) return null;
+
+ try {
+ return detectNativeBinaryTarget(readFileSync(binaryPath));
+ } catch {
+ return null;
+ }
+}
+
+export function isNativeBinaryCompatible(
+ binaryPath,
+ { runtimePlatform = process.platform, runtimeArch = process.arch, dlopen = process.dlopen } = {}
+) {
+ const target = readNativeBinaryTarget(binaryPath);
+
+ if (target) {
+ if (target.platform !== runtimePlatform || !target.architectures.includes(runtimeArch)) {
+ return false;
+ }
+ } else if (runtimePlatform !== PUBLISHED_BUILD_PLATFORM || runtimeArch !== PUBLISHED_BUILD_ARCH) {
+ // Unknown binary layout on a non-build platform is too risky to treat as compatible.
+ return false;
+ }
+
+ try {
+ dlopen({ exports: {} }, binaryPath);
+ return true;
+ } catch {
+ return false;
+ }
+}
diff --git a/tests/unit/native-binary-compat.test.mjs b/tests/unit/native-binary-compat.test.mjs
new file mode 100644
index 0000000000..73d0a86bd7
--- /dev/null
+++ b/tests/unit/native-binary-compat.test.mjs
@@ -0,0 +1,143 @@
+import { describe, it } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { tmpdir } from "node:os";
+
+import {
+ detectNativeBinaryTarget,
+ isNativeBinaryCompatible,
+} from "../../scripts/native-binary-compat.mjs";
+
+function makeElfBinary(machine) {
+ const buffer = Buffer.alloc(64);
+ buffer[0] = 0x7f;
+ buffer[1] = 0x45;
+ buffer[2] = 0x4c;
+ buffer[3] = 0x46;
+ buffer[4] = 2;
+ buffer[5] = 1;
+ buffer.writeUInt16LE(machine, 18);
+ return buffer;
+}
+
+function makeMachBinary(cpuType) {
+ const buffer = Buffer.alloc(32);
+ buffer.writeUInt32BE(0xcffaedfe, 0);
+ buffer.writeUInt32LE(cpuType, 4);
+ return buffer;
+}
+
+function makePeBinary(machine) {
+ const buffer = Buffer.alloc(160);
+ buffer[0] = 0x4d;
+ buffer[1] = 0x5a;
+ buffer.writeUInt32LE(0x80, 0x3c);
+ buffer.write("PE\0\0", 0x80, "ascii");
+ buffer.writeUInt16LE(machine, 0x84);
+ return buffer;
+}
+
+describe("detectNativeBinaryTarget", () => {
+ it("detects linux x64 ELF binaries", () => {
+ assert.deepEqual(detectNativeBinaryTarget(makeElfBinary(62)), {
+ platform: "linux",
+ architectures: ["x64"],
+ });
+ });
+
+ it("detects darwin arm64 Mach-O binaries", () => {
+ assert.deepEqual(detectNativeBinaryTarget(makeMachBinary(0x0100000c)), {
+ platform: "darwin",
+ architectures: ["arm64"],
+ });
+ });
+
+ it("detects win32 x64 PE binaries", () => {
+ assert.deepEqual(detectNativeBinaryTarget(makePeBinary(0x8664)), {
+ platform: "win32",
+ architectures: ["x64"],
+ });
+ });
+});
+
+describe("isNativeBinaryCompatible", () => {
+ function withTempBinary(buffer, callback) {
+ const dir = mkdtempSync(join(tmpdir(), "omniroute-native-"));
+ const file = join(dir, "better_sqlite3.node");
+ writeFileSync(file, buffer);
+
+ try {
+ callback(file);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ }
+
+ it("accepts linux-x64 binaries when the target matches and dlopen succeeds", () => {
+ withTempBinary(makeElfBinary(62), (binaryPath) => {
+ assert.equal(
+ isNativeBinaryCompatible(binaryPath, {
+ runtimePlatform: "linux",
+ runtimeArch: "x64",
+ dlopen() {},
+ }),
+ true
+ );
+ });
+ });
+
+ it("rejects linux-x64 binaries when dlopen fails on the same platform", () => {
+ withTempBinary(makeElfBinary(62), (binaryPath) => {
+ assert.equal(
+ isNativeBinaryCompatible(binaryPath, {
+ runtimePlatform: "linux",
+ runtimeArch: "x64",
+ dlopen() {
+ throw new Error("abi mismatch");
+ },
+ }),
+ false
+ );
+ });
+ });
+
+ it("rejects macOS false positives for bundled linux binaries", () => {
+ withTempBinary(makeElfBinary(62), (binaryPath) => {
+ assert.equal(
+ isNativeBinaryCompatible(binaryPath, {
+ runtimePlatform: "darwin",
+ runtimeArch: "arm64",
+ dlopen() {},
+ }),
+ false
+ );
+ });
+ });
+
+ it("rejects Windows false positives for bundled linux binaries", () => {
+ withTempBinary(makeElfBinary(62), (binaryPath) => {
+ assert.equal(
+ isNativeBinaryCompatible(binaryPath, {
+ runtimePlatform: "win32",
+ runtimeArch: "x64",
+ dlopen() {},
+ }),
+ false
+ );
+ });
+ });
+
+ it("accepts copied darwin binaries after postinstall replacement", () => {
+ withTempBinary(makeMachBinary(0x0100000c), (binaryPath) => {
+ assert.equal(
+ isNativeBinaryCompatible(binaryPath, {
+ runtimePlatform: "darwin",
+ runtimeArch: "arm64",
+ dlopen() {},
+ }),
+ true
+ );
+ });
+ });
+});