diff --git a/bin/broker-register.mjs b/bin/broker-register.mjs index c587061..cc983b5 100755 --- a/bin/broker-register.mjs +++ b/bin/broker-register.mjs @@ -17,6 +17,7 @@ import os from "node:os"; import path from "node:path"; import readline from "node:readline"; import { webcrypto } from "node:crypto"; +import { pathToFileURL } from "node:url"; const { subtle } = webcrypto; @@ -602,6 +603,27 @@ export async function runRegistration({ }; } +export function isMainModule(moduleUrl = import.meta.url, argv1 = process.argv[1]) { + if (!argv1) return false; + + let argvUrl = ""; + let argvRealUrl = ""; + + try { + argvUrl = pathToFileURL(path.resolve(argv1)).href; + } catch { + argvUrl = ""; + } + + try { + argvRealUrl = pathToFileURL(fs.realpathSync(argv1)).href; + } catch { + argvRealUrl = ""; + } + + return moduleUrl === argvUrl || (argvRealUrl !== "" && moduleUrl === argvRealUrl); +} + export async function main(argv = process.argv.slice(2)) { const parsed = parseArgs(argv); @@ -650,7 +672,7 @@ export async function main(argv = process.argv.slice(2)) { return 0; } -if (import.meta.url === `file://${process.argv[1]}`) { +if (isMainModule()) { main().catch((err) => { const message = err instanceof Error ? err.message : String(err); console.error(`❌ ${message}`); diff --git a/bin/broker-register.test.mjs b/bin/broker-register.test.mjs index d0972d2..09cfc00 100644 --- a/bin/broker-register.test.mjs +++ b/bin/broker-register.test.mjs @@ -1,6 +1,10 @@ import test from "node:test"; import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; import { createServer } from "node:http"; +import { pathToFileURL } from "node:url"; import { parseArgs, normalizeBrokerUrl, @@ -9,6 +13,7 @@ import { registerWithBroker, upsertEnvContent, runRegistration, + isMainModule, } from "./broker-register.mjs"; const FIXTURE_SERVER_KEYS = { @@ -53,6 +58,24 @@ test("parseArgs sets verbose=true for -v and --verbose", () => { assert.equal(long.verbose, true); }); +test("isMainModule handles symlink argv path", () => { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "broker-register-main-")); + const realFile = path.join(tempDir, "real.mjs"); + const symlinkFile = path.join(tempDir, "link.mjs"); + + try { + fs.writeFileSync(realFile, "export default 1;\n", "utf8"); + fs.symlinkSync(realFile, symlinkFile); + + const moduleUrl = pathToFileURL(fs.realpathSync(realFile)).href; + assert.equal(isMainModule(moduleUrl, symlinkFile), true); + } finally { + try { fs.unlinkSync(symlinkFile); } catch {} + try { fs.unlinkSync(realFile); } catch {} + try { fs.rmdirSync(tempDir); } catch {} + } +}); + test("parseArgs accepts registration token", () => { const parsed = parseArgs(["--registration-token", "token-123"]); assert.equal(parsed.registrationToken, "token-123");