Skip to content

Commit e2507cf

Browse files
authored
Merge pull request #430 from Bearmancer/feat/alibaba-bun-shim-through-node
fix(alibaba): run bun's global bl.exe shim through node so quota checks stop opening visible consoles
2 parents 19eacac + 486699e commit e2507cf

2 files changed

Lines changed: 294 additions & 13 deletions

File tree

‎src/lib/alibaba.ts‎

Lines changed: 53 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -344,18 +344,14 @@ async function isRegularFile(file: string): Promise<boolean> {
344344
}
345345
}
346346

347-
/** Read what an npm `bl.cmd` shim wraps instead of running it: the package manifest declares its
348-
* bin, so the `.cmd` text is never needed. Failures stay silent, since a parse error would leak
349-
* file contents. */
350-
async function resolveNodeShim(
347+
/** Read what a shim wraps instead of running it: the package manifest declares its bin, so the
348+
* shim text is never needed. Failures stay silent, since a parse error would leak file contents. */
349+
async function resolveShimEntry(
351350
paths: path.PlatformPath,
352-
shimFile: string,
353-
packageName: string,
351+
packageRoot: string,
352+
shimCommand: string,
354353
projectFolders: readonly string[],
355354
): Promise<string | null> {
356-
const packageRoot = paths.join(paths.dirname(shimFile), "node_modules", packageName);
357-
const shimCommand = paths.basename(shimFile, paths.extname(shimFile)).toLowerCase();
358-
359355
let contents: string;
360356
try {
361357
contents = await readFile(paths.join(packageRoot, "package.json"), "utf8");
@@ -393,6 +389,40 @@ async function resolveNodeShim(
393389
return real;
394390
}
395391

392+
/** npm's global layout: the wrapped package sits in `node_modules` beside its shims. */
393+
async function resolveNodeShim(
394+
paths: path.PlatformPath,
395+
shimFile: string,
396+
packageName: string,
397+
projectFolders: readonly string[],
398+
): Promise<string | null> {
399+
const packageRoot = paths.join(paths.dirname(shimFile), "node_modules", packageName);
400+
const shimCommand = paths.basename(shimFile, paths.extname(shimFile)).toLowerCase();
401+
return await resolveShimEntry(paths, packageRoot, shimCommand, projectFolders);
402+
}
403+
404+
/** bun's global layout: `<prefix>\bin\<name>.exe` with a `<name>.bunx` marker beside it and the
405+
* package under `<prefix>\install\global\node_modules`. The marker is bun's own binary format, so
406+
* it is never parsed — its presence beside the launcher is the flag that the launcher spawns
407+
* `node` itself, and that grandchild escapes `windowsHide`: with a GUI parent (a service) every
408+
* check opens a fresh visible `node.exe` console. The entry comes from the manifest, as for npm. */
409+
async function resolveBunShimEntry(
410+
paths: path.PlatformPath,
411+
shimFile: string,
412+
packageName: string,
413+
projectFolders: readonly string[],
414+
): Promise<string | null> {
415+
const shimCommand = paths.basename(shimFile, paths.extname(shimFile)).toLowerCase();
416+
const marker = paths.join(paths.dirname(shimFile), `${shimCommand}.bunx`);
417+
if (!(await isRegularFile(marker))) return null;
418+
const prefix = paths.dirname(paths.dirname(shimFile));
419+
// A bin folder right under a drive root (`C:\bin`) would put the package at the root, where any
420+
// local user can create folders, so that layout is never read.
421+
if (paths.parse(prefix).root === prefix) return null;
422+
const packageRoot = paths.join(prefix, "install", "global", "node_modules", packageName);
423+
return await resolveShimEntry(paths, packageRoot, shimCommand, projectFolders);
424+
}
425+
396426
/** The node that runs a shim's entry: resolved as `bl` is, so `bl` and node come from one install.
397427
* No fallback to `process.execPath`: inside OpenCode that is OpenCode's own binary, not node. */
398428
async function resolveNodeExecutable(
@@ -456,6 +486,20 @@ export async function resolveAlibabaTokenPlanExecutable(params: {
456486
if (isInsideProject(paths, projectFolders, resolved)) {
457487
return fail("workspace_path_rejected");
458488
}
489+
if (platform === "win32" && paths.basename(resolved).toLowerCase() === "bl.exe") {
490+
// bun's global `bl.exe` is a launcher that spawns `node` itself, and that grandchild opens
491+
// a visible console per check when the parent has none. Run node on the entry directly,
492+
// like the npm `.cmd` route. No marker, package, entry or node: the file runs as before.
493+
const entry = await resolveBunShimEntry(
494+
paths,
495+
candidate,
496+
SHIM_PACKAGE_NAME,
497+
projectFolders,
498+
);
499+
const node =
500+
entry === null ? null : await resolveNodeExecutable(paths, trusted, projectFolders);
501+
if (entry !== null && node !== null) return { ok: true, file: node, args: [entry] };
502+
}
459503
return { ok: true, file: resolved };
460504
}
461505
}

‎tests/lib.alibaba.test.ts‎

Lines changed: 241 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -200,22 +200,28 @@ async function mockExecutable(file = "/trusted/bin/bl", target = file): Promise<
200200
);
201201
}
202202

203-
/** Fake win32 filesystem; `path.win32` keys keep these cases runnable on a POSIX runner too.
203+
/** Fake case-insensitive win32 filesystem; `path.win32` keys keep these cases runnable on a POSIX runner too.
204204
* `links` maps a path to the real path a link or junction resolves it to. */
205205
async function mockWin32Files(
206206
files: Record<string, string>,
207207
links: Record<string, string> = {},
208208
): Promise<void> {
209209
const stats = await stat(process.execPath);
210+
const contentsByPath = new Map(
211+
Object.entries(files).map(([file, text]) => [file.toLowerCase(), text]),
212+
);
213+
const targetsByPath = new Map(
214+
Object.entries(links).map(([file, target]) => [file.toLowerCase(), target]),
215+
);
210216
vi.mocked(stat).mockImplementation(async (candidate) => {
211-
if (String(candidate) in files) return stats;
217+
if (contentsByPath.has(String(candidate).toLowerCase())) return stats;
212218
throw new Error("File does not exist");
213219
});
214220
vi.mocked(realpath).mockImplementation(
215-
async (candidate) => links[String(candidate)] ?? String(candidate),
221+
async (candidate) => targetsByPath.get(String(candidate).toLowerCase()) ?? String(candidate),
216222
);
217223
vi.mocked(readFile).mockImplementation(async (candidate) => {
218-
const contents = files[String(candidate)];
224+
const contents = contentsByPath.get(String(candidate).toLowerCase());
219225
if (contents === undefined) throw Object.assign(new Error("ENOENT"), { code: "ENOENT" });
220226
return contents;
221227
});
@@ -619,6 +625,28 @@ describe("alibaba token plan executable resolution", () => {
619625
).toEqual({ ok: true, file });
620626
});
621627

628+
it.each(["linux", "darwin"] as const)(
629+
"runs bl directly on %s even with a stray bl.bunx marker",
630+
async (platform) => {
631+
const file = "/trusted/bin/bl";
632+
const marker = "/trusted/bin/bl.bunx";
633+
await mockExecutable(file);
634+
const stats = await stat(file);
635+
vi.mocked(stat).mockImplementation(async (candidate) => {
636+
if (candidate === file || candidate === marker) return stats;
637+
throw new Error("File does not exist");
638+
});
639+
expect(
640+
await resolveAlibabaTokenPlanExecutable({
641+
platform,
642+
cwd: "/workspace",
643+
pathEnv: "/trusted/bin",
644+
}),
645+
).toEqual({ ok: true, file });
646+
expect(readFile).not.toHaveBeenCalled();
647+
},
648+
);
649+
622650
it.each(["aix", "freebsd"] as const)("rejects %s instead of probing PATH", async (platform) => {
623651
const expected = { ok: false, error: { kind: "unsupported_platform" } };
624652
const params = { platform, cwd: "/workspace", pathEnv: "/usr/bin" };
@@ -758,6 +786,215 @@ describe("alibaba token plan Windows resolution", () => {
758786
expect(requests[0]?.cwd).toBe(SAFE_TMP);
759787
});
760788

789+
// bun's global shim layout: `<prefix>\bin\bl.exe` and its `bl.bunx` marker, with the package at
790+
// `<prefix>\install\global\node_modules\bailian-cli\`. The launcher spawns `node` itself, and
791+
// that grandchild opens a visible console per check when the parent has none (a GUI service).
792+
const BUN_EXE = W.join(TRUSTED_BIN, "bl.exe");
793+
const BUN_MARKER = W.join(TRUSTED_BIN, "bl.bunx");
794+
const BUN_PACKAGE_ROOT = W.join(
795+
"C:\\",
796+
"trusted",
797+
"install",
798+
"global",
799+
"node_modules",
800+
"bailian-cli",
801+
);
802+
const BUN_MANIFEST = W.join(BUN_PACKAGE_ROOT, "package.json");
803+
const BUN_ENTRY = W.join(BUN_PACKAGE_ROOT, "dist", "bailian.mjs");
804+
805+
it("resolves bun's global bl.exe shim to the package entry through node", async () => {
806+
await mockWin32Files({
807+
[BUN_EXE]: "bl",
808+
[BUN_MARKER]: "bunx",
809+
[NODE]: "node",
810+
[BUN_MANIFEST]: manifest({ bailian: "dist/bailian.mjs", bl: "dist/bailian.mjs" }),
811+
[BUN_ENTRY]: "cli",
812+
});
813+
expect(
814+
await resolveAlibabaTokenPlanExecutable({
815+
platform: "win32",
816+
cwd: WORKSPACE,
817+
homedir: HOME,
818+
pathEnv: TRUSTED_BIN,
819+
}),
820+
).toEqual({ ok: true, file: NODE, args: [BUN_ENTRY] });
821+
});
822+
823+
it("runs the bun shim entry with the fixed argv, no shell, and ignored stdin", async () => {
824+
await mockWin32Files({
825+
[BUN_EXE]: "bl",
826+
[BUN_MARKER]: "bunx",
827+
[NODE]: "node",
828+
[BUN_MANIFEST]: manifest({ bl: "dist/bailian.mjs" }),
829+
[BUN_ENTRY]: "cli",
830+
});
831+
const requests: AlibabaTokenPlanSpawnRequest[] = [];
832+
const result = await queryTokenPlanUsage({
833+
runtime: {
834+
platform: "win32",
835+
cwd: WORKSPACE,
836+
homedir: HOME,
837+
pathEnv: TRUSTED_BIN,
838+
tmpdir: SAFE_TMP,
839+
spawn: capturedSpawn(requests),
840+
},
841+
});
842+
expect(result.ok).toBe(true);
843+
expect(requests[0]?.file).toBe(NODE);
844+
expect(requests[0]?.args).toEqual([BUN_ENTRY, ...BL_ARGS]);
845+
expect(requests[0]?.shell).toBe(false);
846+
expect(requests[0]?.stdin).toBe("ignore");
847+
expect(requests[0]?.cwd).toBe(SAFE_TMP);
848+
});
849+
850+
it("runs bl.exe itself when the bun marker names no usable package", async () => {
851+
// No manifest under the bun layout: the marker alone changes nothing, and a bun install that
852+
// works today keeps working if the layout ever moves.
853+
await mockWin32Files({ [BUN_EXE]: "bl", [BUN_MARKER]: "bunx", [NODE]: "node" });
854+
expect(
855+
await resolveAlibabaTokenPlanExecutable({
856+
platform: "win32",
857+
cwd: WORKSPACE,
858+
homedir: HOME,
859+
pathEnv: TRUSTED_BIN,
860+
}),
861+
).toEqual({ ok: true, file: BUN_EXE });
862+
});
863+
864+
it("runs bl.exe itself when bun's bin folder sits right under a drive root", async () => {
865+
// `C:\bin\bl.exe` would put the bun package at `C:\install`, which any local user can create.
866+
const rootBin = W.join("C:\\", "bin");
867+
const rootExe = W.join(rootBin, "bl.exe");
868+
const rootPackage = W.join("C:\\", "install", "global", "node_modules", "bailian-cli");
869+
await mockWin32Files({
870+
[rootExe]: "bl",
871+
[W.join(rootBin, "bl.bunx")]: "bunx",
872+
[W.join(rootBin, "node.exe")]: "node",
873+
[W.join(rootPackage, "package.json")]: manifest({ bl: "dist/bailian.mjs" }),
874+
[W.join(rootPackage, "dist", "bailian.mjs")]: "cli",
875+
});
876+
expect(
877+
await resolveAlibabaTokenPlanExecutable({
878+
platform: "win32",
879+
cwd: WORKSPACE,
880+
homedir: HOME,
881+
pathEnv: rootBin,
882+
}),
883+
).toEqual({ ok: true, file: rootExe });
884+
});
885+
886+
it.each([
887+
{ name: "no node.exe on the trusted PATH", missing: NODE },
888+
{ name: "no bl.bunx marker beside the launcher", missing: BUN_MARKER },
889+
{
890+
name: "a manifest entry escaping the package root with ..",
891+
bin: "../outside.mjs",
892+
entry: W.join(BUN_PACKAGE_ROOT, "..", "outside.mjs"),
893+
},
894+
{
895+
name: "an entry linking into the project",
896+
links: { [BUN_ENTRY]: W.join(WORKSPACE, "planted", "bailian.mjs") },
897+
},
898+
{
899+
name: "a node.exe linking into the project",
900+
links: { [NODE]: W.join(WORKSPACE, "planted", "node.exe") },
901+
},
902+
{
903+
name: "an entry inside a project whose cwd is a junction",
904+
cwd: W.join("C:\\", "alias"),
905+
links: {
906+
[W.join("C:\\", "alias")]: WORKSPACE,
907+
[BUN_ENTRY]: W.join(WORKSPACE, "planted", "bailian.mjs"),
908+
},
909+
},
910+
])("runs bl.exe itself with $name", async ({ missing, bin, entry, links, cwd }) => {
911+
const files = {
912+
[BUN_EXE]: "bl",
913+
[BUN_MARKER]: "bunx",
914+
[NODE]: "node",
915+
[BUN_MANIFEST]: manifest({ bl: bin ?? "dist/bailian.mjs" }),
916+
[entry ?? BUN_ENTRY]: "cli",
917+
};
918+
if (missing) delete files[missing];
919+
await mockWin32Files(files, links);
920+
expect(
921+
await resolveAlibabaTokenPlanExecutable({
922+
platform: "win32",
923+
cwd: cwd ?? WORKSPACE,
924+
homedir: HOME,
925+
pathEnv: TRUSTED_BIN,
926+
}),
927+
).toEqual({ ok: true, file: BUN_EXE });
928+
});
929+
930+
it("runs bl.exe itself when node.exe is only on a project PATH entry", async () => {
931+
const projectBin = W.join(WORKSPACE, "bin");
932+
await mockWin32Files({
933+
[BUN_EXE]: "bl",
934+
[BUN_MARKER]: "bunx",
935+
[W.join(projectBin, "node.exe")]: "node",
936+
[BUN_MANIFEST]: manifest({ bl: "dist/bailian.mjs" }),
937+
[BUN_ENTRY]: "cli",
938+
});
939+
expect(
940+
await resolveAlibabaTokenPlanExecutable({
941+
platform: "win32",
942+
cwd: WORKSPACE,
943+
homedir: HOME,
944+
pathEnv: [projectBin, ".", "relative", TRUSTED_BIN].join(";"),
945+
}),
946+
).toEqual({ ok: true, file: BUN_EXE });
947+
});
948+
949+
it("rejects a bun launcher whose realpath is inside the project", async () => {
950+
await mockWin32Files(
951+
{
952+
[BUN_EXE]: "bl",
953+
[BUN_MARKER]: "bunx",
954+
[NODE]: "node",
955+
[BUN_MANIFEST]: manifest({ bl: "dist/bailian.mjs" }),
956+
[BUN_ENTRY]: "cli",
957+
},
958+
{ [BUN_EXE]: W.join(WORKSPACE, "bin", "bl.exe") },
959+
);
960+
expect(
961+
await resolveAlibabaTokenPlanExecutable({
962+
platform: "win32",
963+
cwd: WORKSPACE,
964+
homedir: HOME,
965+
pathEnv: TRUSTED_BIN,
966+
}),
967+
).toMatchObject({ ok: false, error: { kind: "workspace_path_rejected" } });
968+
});
969+
970+
it.each([
971+
{ name: "npm", shim: SHIM, packageManifest: MANIFEST, entry: ENTRY },
972+
{ name: "bun", shim: BUN_EXE, packageManifest: BUN_MANIFEST, entry: BUN_ENTRY },
973+
])(
974+
"resolves the $name shim with case-insensitive Windows filenames",
975+
async ({ shim, packageManifest, entry }) => {
976+
const uppercaseShim = shim.toUpperCase();
977+
await mockWin32Files(
978+
{
979+
[uppercaseShim]: "shim",
980+
[W.join(TRUSTED_BIN, "BL.bunx")]: "bunx",
981+
[NODE.toUpperCase()]: "node",
982+
[packageManifest.toUpperCase()]: manifest({ bl: "dist/bailian.mjs" }),
983+
[entry.toUpperCase()]: "cli",
984+
},
985+
{ [shim]: uppercaseShim },
986+
);
987+
expect(
988+
await resolveAlibabaTokenPlanExecutable({
989+
platform: "win32",
990+
cwd: WORKSPACE,
991+
homedir: HOME,
992+
pathEnv: TRUSTED_BIN,
993+
}),
994+
).toEqual({ ok: true, file: NODE, args: [entry] });
995+
},
996+
);
997+
761998
it.each([
762999
{
7631000
name: "a manifest whose bin does not declare bl",

0 commit comments

Comments
 (0)