Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - exercises the real native runner and local HTTP collector.
2import * as NodeChildProcess from "node:child_process";
3import * as NodeFSP from "node:fs/promises";
4import * as NodeHttp from "node:http";
5import * as NodeOS from "node:os";
6import * as NodePath from "node:path";
7import { expect, it } from "vite-plus/test";
8
9it("uses one machine hook across fresh worktrees without modifying Vite+", async () => {
10 const root = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "task-cache-hook-"));
11 const unrelated = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "unrelated-project-"));
12 const reports: { authorization: string | undefined; body: string }[] = [];
13 let firstExit!: () => void;
14 const firstExited = new Promise<void>((resolve) => {
15 firstExit = resolve;
16 });
17 let completedReports = 0;
18 let notified: (() => void) | undefined;
19 let firstDisconnected = false;
20 const report = (count: number) =>
21 completedReports >= count
22 ? Promise.resolve()
23 : new Promise<void>((resolve) => {
24 notified = resolve;
25 });
26 const server = NodeHttp.createServer(async (request, response) => {
27 if (!request.url?.endsWith("/telemetry")) {
28 response.writeHead(404).end();
29 return;
30 }
31 let body = "";
32 for await (const chunk of request) body += chunk;
33 reports.push({ authorization: request.headers.authorization, body });
34 if (reports.length === 1) {
35 await firstExited;
36 firstDisconnected = response.destroyed;
37 }
38 response.writeHead(204).end();
39 completedReports++;
40 notified?.();
41 notified = undefined;
42 });
43 try {
44 await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
45 const address = server.address();
46 if (!address || typeof address === "string") throw new Error("Missing HTTP address");
47 const runner = NodePath.join(root, "vite-plus");
48 const distribution = await NodeFSP.realpath(
49 NodePath.resolve(import.meta.dirname, "../../../node_modules/vite-plus/dist"),
50 );
51 await NodeFSP.cp(distribution, NodePath.join(runner, "dist"), { recursive: true });
52 await NodeFSP.copyFile(
53 NodePath.join(distribution, "../package.json"),
54 NodePath.join(runner, "package.json"),
55 );
56 await NodeFSP.symlink(
57 NodePath.resolve(distribution, "../binding"),
58 NodePath.join(runner, "binding"),
59 );
60 await NodeFSP.symlink(
61 NodePath.resolve(distribution, "../.."),
62 NodePath.join(runner, "node_modules"),
63 );
64 const entrypoint = NodePath.join(runner, "dist/bin.js");
65 await NodeFSP.writeFile(
66 NodePath.join(unrelated, "package.json"),
67 JSON.stringify({ name: "unrelated", scripts: { build: 'node -e "console.log(7)"' } }),
68 );
69 const nested = NodePath.join(root, "nested");
70 await NodeFSP.mkdir(nested);
71 await NodeFSP.writeFile(
72 NodePath.join(nested, "package.json"),
73 JSON.stringify({ name: "nested", scripts: { build: 'node -e "console.log(8)"' } }),
74 );
75 await NodeFSP.writeFile(NodePath.join(nested, "pnpm-workspace.yaml"), "packages: []\n");
76 const endpoint = `http://127.0.0.1:${address.port}/projects/test`;
77 await NodeFSP.writeFile(NodePath.join(root, ".task-cache.json"), JSON.stringify({ endpoint }));
78 await NodeFSP.writeFile(
79 NodePath.join(root, "package.json"),
80 JSON.stringify({
81 name: "hook-fixture",
82 private: true,
83 scripts: {
84 build: `node build.cjs ${JSON.stringify(entrypoint)} ${JSON.stringify(unrelated)}`,
85 fail: 'node -e "process.exit(7)"',
86 nested: `node ${JSON.stringify(entrypoint)} -C ${JSON.stringify(nested)} run --no-cache build`,
87 },
88 }),
89 );
90 await NodeFSP.writeFile(
91 NodePath.join(root, "build.cjs"),
92 'require("node:fs").writeFileSync("environment.json", JSON.stringify({url: process.env.VP_REMOTE_CACHE_URL ?? null, mode: process.env.VP_REMOTE_CACHE ?? null})); console.log(42); try {for (const cwd of process.argv.slice(3)) require("node:child_process").execFileSync(process.execPath, [process.argv[2], "run", "--no-cache", "build"], {cwd, encoding:"utf8"})} catch (error) { throw new Error(error.stdout + error.stderr) }',
93 );
94 await NodeFSP.writeFile(
95 NodePath.join(root, "vite.config.ts"),
96 `import { remoteCacheUrl } from ${JSON.stringify(new URL("./remoteCache.ts", import.meta.url).href)}; export default {run:{cache:{scripts:true,remote:{url:remoteCacheUrl(import.meta.dirname)}}}};`,
97 );
98 await NodeFSP.mkdir(NodePath.join(root, ".config/t3-task-cache"), { recursive: true });
99 await NodeFSP.writeFile(
100 NodePath.join(root, ".config/t3-task-cache/credentials.json"),
101 JSON.stringify({ [endpoint]: { name: "maria", token: "secret" } }),
102 );
103 const configDirectory = NodePath.join(root, ".config/vite-plus");
104 await NodeFSP.mkdir(configDirectory, { recursive: true });
105 await NodeFSP.writeFile(
106 NodePath.join(configDirectory, "run-hook.json"),
107 JSON.stringify({
108 rootMarker: ".task-cache.json",
109 module: NodePath.join(import.meta.dirname, "runHook.ts"),
110 }),
111 );
112 const originalEntrypoint = await NodeFSP.readFile(entrypoint, "utf8");
113 const run = (task: string, cwd = root, ci = false, cache = "--cache") =>
114 new Promise<number | null>((resolve, reject) => {
115 const child = NodeChildProcess.spawn(
116 process.execPath,
117 [entrypoint, "run", ...(task === "--last-details" ? [] : [cache]), task],
118 {
119 cwd,
120 env: {
121 ...process.env,
122 HOME: root,
123 GITHUB_ACTIONS: ci ? "true" : undefined,
124 T3_TASK_CACHE_TELEMETRY: undefined,
125 T3_TASK_CACHE_HOST: undefined,
126 VITE_CACHE_PATH: undefined,
127 ACTIONS_ID_TOKEN_REQUEST_URL: undefined,
128 ACTIONS_ID_TOKEN_REQUEST_TOKEN: undefined,
129 NODE_OPTIONS: `--import=${new URL("./preload.mjs", import.meta.url).href}`,
130 VP_REMOTE_CACHE: undefined,
131 VP_REMOTE_CACHE_URL: undefined,
132 },
133 stdio: ["ignore", "ignore", "pipe"],
134 },
135 );
136 let stderr = "";
137 child.stderr.on("data", (chunk) => {
138 stderr += chunk;
139 });
140 child.once("error", reject);
141 child.once("close", (code) => {
142 firstExit();
143 if (code !== 0 && task !== "fail") reject(new Error(stderr));
144 else resolve(code);
145 });
146 });
147 expect(await run("build")).toBe(0);
148 await report(1);
149 expect(await run("--last-details")).toBe(0);
150 expect(
151 JSON.parse(await NodeFSP.readFile(NodePath.join(root, "environment.json"), "utf8")),
152 ).toMatchObject({ url: null });
153 expect(firstDisconnected).toBe(false);
154 expect(await run("build")).toBe(0);
155 await report(2);
156 expect(await run("fail")).toBe(7);
157 await report(3);
158 const secondWorktree = NodePath.join(root, "second-worktree");
159 await NodeFSP.mkdir(secondWorktree);
160 for (const file of ["package.json", ".task-cache.json", "vite.config.ts", "build.cjs"])
161 await NodeFSP.copyFile(NodePath.join(root, file), NodePath.join(secondWorktree, file));
162 expect(await run("build", secondWorktree)).toBe(0);
163 await report(4);
164 expect(await run("build", secondWorktree, true)).toBe(0);
165 await report(5);
166 expect(await NodeFSP.readFile(entrypoint, "utf8")).toBe(originalEntrypoint);
167 expect(await run("nested", root, false, "--no-cache")).toBe(0);
168 expect(await run("build", nested)).toBe(0);
169 expect(reports).toHaveLength(5);
170 expect(
171 reports.every(
172 (report) =>
173 report.authorization === `Basic ${Buffer.from("maria:secret").toString("base64")}`,
174 ),
175 ).toBe(true);
176 const events = reports.map((report) => JSON.parse(report.body));
177 expect(events[0].tasks[0].source).toBe("executed");
178 expect(events[1].tasks[0].source).toBe("local");
179 expect(events[3].tasks[0].source).toBe("executed");
180 expect(new Set(events.map((event) => event.id)).size).toBe(5);
181 } finally {
182 await new Promise<void>((resolve, reject) =>
183 server.close((error) => (error ? reject(error) : resolve())),
184 );
185 await NodeFSP.rm(root, { recursive: true, force: true });
186 await NodeFSP.rm(unrelated, { recursive: true, force: true });
187 }
188});
189
190it("rejects invalid setup credentials before installing anything and never prints the token", async () => {
191 const home = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "task-cache-setup-"));
192 const token = "private-credential-that-must-not-appear-in-output";
193 const server = NodeHttp.createServer((_request, response) => response.writeHead(401).end());
194 try {
195 await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
196 const address = server.address();
197 if (!address || typeof address === "string") throw new Error("Missing HTTP address");
198 const result = await new Promise<{ code: number | null; output: string }>((resolve, reject) => {
199 const child = NodeChildProcess.spawn(
200 process.execPath,
201 [NodePath.join(import.meta.dirname, "../scripts/install.ts"), "--non-interactive"],
202 {
203 env: {
204 ...process.env,
205 HOME: home,
206 T3_CACHE_SETUP_URL: `http://127.0.0.1:${address.port}/projects/test`,
207 T3_CACHE_SETUP_NAME: "maria",
208 T3_CACHE_SETUP_TOKEN: token,
209 },
210 stdio: ["ignore", "pipe", "pipe"],
211 },
212 );
213 let output = "";
214 child.stdout.on("data", (chunk) => {
215 output += chunk;
216 });
217 child.stderr.on("data", (chunk) => {
218 output += chunk;
219 });
220 child.once("error", reject);
221 child.once("close", (code) => resolve({ code, output }));
222 });
223 expect(result.code).not.toBe(0);
224 expect(result.output).toContain("Credential verification failed (401)");
225 expect(result.output).not.toContain(token);
226 expect(await NodeFSP.readdir(home)).toEqual([]);
227 } finally {
228 await new Promise<void>((resolve, reject) =>
229 server.close((error) => (error ? reject(error) : resolve())),
230 );
231 await NodeFSP.rm(home, { recursive: true, force: true });
232 }
233});
234
235it("does not start telemetry or create local state without cache credentials", async () => {
236 const root = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "task-cache-unconfigured-"));
237 try {
238 await NodeFSP.writeFile(
239 NodePath.join(root, ".task-cache.json"),
240 JSON.stringify({ endpoint: "https://cache.invalid/projects/test" }),
241 );
242 const hook = new URL("./runHook.ts", import.meta.url).href;
243 const output = await new Promise<string>((resolve, reject) => {
244 const child = NodeChildProcess.spawn(
245 process.execPath,
246 [
247 "--input-type=module",
248 "-e",
249 `import start from ${JSON.stringify(hook)}; const finish = start({ root: process.cwd() }); if (finish !== undefined) process.exit(1);`,
250 ],
251 {
252 cwd: root,
253 env: { ...process.env, HOME: root, VP_REMOTE_CACHE_URL: "" },
254 stdio: ["ignore", "pipe", "pipe"],
255 },
256 );
257 let output = "";
258 child.stdout.on("data", (chunk) => {
259 output += chunk;
260 });
261 child.stderr.on("data", (chunk) => {
262 output += chunk;
263 });
264 child.once("error", reject);
265 child.once("close", (code) =>
266 code === 0 ? resolve(output) : reject(new Error(output || `Exited ${code}`)),
267 );
268 });
269 expect(output).toBe("");
270 expect(await NodeFSP.readdir(root)).toEqual([".task-cache.json"]);
271 } finally {
272 await NodeFSP.rm(root, { recursive: true, force: true });
273 }
274});
275
276it("installs without masking .profile and configures CI through bash", async () => {
277 const home = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "task-cache-login-"));
278 const server = NodeHttp.createServer((_request, response) => response.writeHead(204).end());
279 const run = (args: string[], env: NodeJS.ProcessEnv) =>
280 new Promise<string>((resolve, reject) => {
281 const child = NodeChildProcess.spawn(args[0]!, args.slice(1), {
282 env: { ...process.env, ...env, HOME: home, NODE_OPTIONS: "" },
283 stdio: ["ignore", "pipe", "pipe"],
284 });
285 let output = "";
286 child.stdout.on("data", (chunk) => {
287 output += chunk;
288 });
289 child.stderr.on("data", (chunk) => {
290 output += chunk;
291 });
292 child.once("error", reject);
293 child.once("close", (code) => (code === 0 ? resolve(output) : reject(new Error(output))));
294 });
295 try {
296 await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
297 const address = server.address();
298 if (!address || typeof address === "string") throw new Error("Missing HTTP address");
299 await NodeFSP.writeFile(NodePath.join(home, ".profile"), "export EXISTING_PROFILE=preserved\n");
300 await NodeFSP.mkdir(NodePath.join(home, ".config/t3-task-cache"), { recursive: true });
301 await NodeFSP.writeFile(
302 NodePath.join(home, ".config/t3-task-cache/credentials.json"),
303 "{partial",
304 );
305 await run(
306 [
307 process.execPath,
308 NodePath.join(import.meta.dirname, "../scripts/install.ts"),
309 "--non-interactive",
310 ],
311 {
312 T3_CACHE_SETUP_URL: `http://127.0.0.1:${address.port}/projects/test`,
313 T3_CACHE_SETUP_NAME: "maria",
314 T3_CACHE_SETUP_TOKEN: "test-credential-for-isolated-http-server",
315 },
316 );
317 expect(await NodeFSP.readdir(home)).not.toContain(".bash_profile");
318 expect(await NodeFSP.readFile(NodePath.join(home, ".profile"), "utf8")).toContain(
319 "EXISTING_PROFILE=preserved",
320 );
321 const githubEnv = NodePath.join(home, "github-env");
322 await run([process.execPath, NodePath.join(import.meta.dirname, "../scripts/install-ci.ts")], {
323 T3_TASK_CACHE_READ_TOKEN: "read-only-fixture-token-01234567890123456789",
324 GITHUB_REPOSITORY: "pingdotgg/t3code",
325 GITHUB_ACTIONS: "true",
326 GITHUB_ENV: githubEnv,
327 RUNNER_TEMP: home,
328 });
329 const values = await NodeFSP.readFile(githubEnv, "utf8");
330 expect(values).not.toContain("\nNODE_OPTIONS=");
331 const bashEnv = values
332 .split("\n")
333 .find((line) => line.startsWith("BASH_ENV="))
334 ?.slice(9);
335 const output = await run(["bash", "-c", 'printf "%s" "$NODE_OPTIONS"'], { BASH_ENV: bashEnv });
336 expect(output).toContain("--import=file:");
337 expect(output).toContain("/infra/task-cache/src/preload.mjs");
338 await NodeFSP.rm(NodePath.join(home, ".local/share/t3-task-cache/preload.mjs"));
339 const missing = await run(["bash", "-c", `node -e 'console.log("missing preload is safe")'`], {
340 BASH_ENV: NodePath.join(home, ".config/t3-task-cache/env"),
341 });
342 expect(missing).toContain("missing preload is safe");
343
344 await NodeFSP.writeFile(
345 NodePath.join(home, ".bash_profile"),
346 '. "$HOME/.config/t3-task-cache/env"\n',
347 );
348 await run(
349 [
350 process.execPath,
351 NodePath.join(import.meta.dirname, "../scripts/install.ts"),
352 "--uninstall",
353 ],
354 {},
355 );
356 expect(await NodeFSP.readdir(home)).not.toContain(".bash_profile");
357 expect(await NodeFSP.readdir(NodePath.join(home, ".local/share/t3-task-cache"))).toEqual([
358 "preload.mjs",
359 ]);
360 expect(await NodeFSP.readFile(NodePath.join(home, ".profile"), "utf8")).not.toContain(
361 "t3-task-cache/env",
362 );
363 expect(await NodeFSP.readdir(NodePath.join(home, ".config/t3-task-cache"))).not.toContain(
364 "credentials.json",
365 );
366 const remaining = await run(
367 [
368 process.execPath,
369 "--import",
370 NodePath.join(home, ".local/share/t3-task-cache/preload.mjs"),
371 "-e",
372 'console.log("node survives uninstall")',
373 ],
374 {},
375 );
376 expect(remaining).toContain("node survives uninstall");
377 } finally {
378 await new Promise<void>((resolve, reject) =>
379 server.close((error) => (error ? reject(error) : resolve())),
380 );
381 await NodeFSP.rm(home, { recursive: true, force: true });
382 }
383});
384
385it("does not send an old endpoint's token after changing the URL interactively", async () => {
386 const root = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "task-cache-endpoint-"));
387 const requests: string[] = [];
388 const server = NodeHttp.createServer((request, response) => {
389 requests.push(request.headers.authorization || "");
390 response.writeHead(401).end();
391 });
392 try {
393 await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
394 const address = server.address();
395 if (!address || typeof address === "string") throw new Error("Missing HTTP address");
396 const nested = NodePath.join(root, "nested");
397 await NodeFSP.mkdir(nested);
398 await NodeFSP.writeFile(
399 NodePath.join(nested, "package.json"),
400 JSON.stringify({ name: "nested", scripts: { build: 'node -e "console.log(8)"' } }),
401 );
402 await NodeFSP.writeFile(NodePath.join(nested, "pnpm-workspace.yaml"), "packages: []\n");
403 const endpoint = `http://127.0.0.1:${address.port}/projects/test`;
404 const scripts = NodePath.join(root, "infra/task-cache/scripts");
405 await NodeFSP.mkdir(scripts, { recursive: true });
406 await NodeFSP.mkdir(NodePath.join(root, "infra/task-cache/src"));
407 await NodeFSP.writeFile(NodePath.join(root, "package.json"), '{"type":"module"}');
408 await NodeFSP.writeFile(NodePath.join(root, ".task-cache.json"), JSON.stringify({ endpoint }));
409 await NodeFSP.copyFile(
410 NodePath.join(import.meta.dirname, "../scripts/install.ts"),
411 NodePath.join(scripts, "install.ts"),
412 );
413 await NodeFSP.copyFile(
414 NodePath.join(import.meta.dirname, "nativeHook.js"),
415 NodePath.join(root, "infra/task-cache/src/nativeHook.js"),
416 );
417 await NodeFSP.mkdir(NodePath.join(root, ".config/t3-task-cache"), { recursive: true });
418 await NodeFSP.writeFile(
419 NodePath.join(root, ".config/t3-task-cache/credentials.json"),
420 JSON.stringify({
421 [endpoint]: { name: "maria", token: "different-saved-endpoint-credential" },
422 }),
423 );
424 const result = await new Promise<{ code: number | null; output: string }>((resolve, reject) => {
425 const child = NodeChildProcess.spawn(
426 process.execPath,
427 [NodePath.join(scripts, "install.ts")],
428 {
429 env: {
430 ...process.env,
431 HOME: root,
432 NODE_OPTIONS: "",
433 T3_CACHE_SETUP_URL: "https://old.example",
434 T3_CACHE_SETUP_NAME: "maria",
435 T3_CACHE_SETUP_TOKEN: "old-endpoint-token-must-not-be-forwarded",
436 },
437 stdio: ["pipe", "pipe", "pipe"],
438 },
439 );
440 let output = "";
441 let sentUrl = false;
442 let sentName = false;
443 child.stdout.on("data", (chunk) => {
444 output += chunk;
445 if (!sentUrl && output.includes("Cache URL")) {
446 sentUrl = true;
447 child.stdin.write(endpoint + "\n");
448 }
449 if (!sentName && output.includes("Developer name")) {
450 sentName = true;
451 child.stdin.write("\n");
452 }
453 });
454 child.stderr.on("data", (chunk) => {
455 output += chunk;
456 });
457 child.once("error", reject);
458 child.once("close", (code) => resolve({ code, output }));
459 });
460 expect(result.code).not.toBe(0);
461 expect(result.output).toContain("Use T3_CACHE_SETUP_TOKEN");
462 expect(requests).toEqual([]);
463 } finally {
464 await new Promise<void>((resolve, reject) =>
465 server.close((error) => (error ? reject(error) : resolve())),
466 );
467 await NodeFSP.rm(root, { recursive: true, force: true });
468 }
469});
470
471it("rejects non-loopback HTTP before transmitting a setup credential", async () => {
472 const home = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "task-cache-http-"));
473 try {
474 const output = await new Promise<string>((resolve) => {
475 NodeChildProcess.execFile(
476 process.execPath,
477 [NodePath.join(import.meta.dirname, "../scripts/install.ts"), "--non-interactive"],
478 {
479 env: {
480 ...process.env,
481 HOME: home,
482 NODE_OPTIONS: "",
483 T3_CACHE_SETUP_URL: "http://cache.invalid/projects/test",
484 T3_CACHE_SETUP_NAME: "maria",
485 T3_CACHE_SETUP_TOKEN: "test-credential-that-must-not-be-transmitted",
486 },
487 },
488 (_error, stdout, stderr) => resolve(stdout + stderr),
489 );
490 });
491 expect(output).toContain("Use an HTTPS cache endpoint");
492 expect(await NodeFSP.readdir(home)).toEqual([]);
493 } finally {
494 await NodeFSP.rm(home, { recursive: true, force: true });
495 }
496});