@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 03:37 UTC

main
ts 1,976 lines 78.2 KB
Raw
1 // @effect-diagnostics nodeBuiltinImport:off - Tests use Node's glob matcher to verify electron-builder exclusions.
2 import * as NodeCrypto from "node:crypto";
3 import * as NodePath from "node:path";
4
5 import * as NodeServices from "@effect/platform-node/NodeServices";
6 import { createPackageWithOptions, extractFile } from "@electron/asar";
7 import { assert, it } from "@effect/vitest";
8 import * as ConfigProvider from "effect/ConfigProvider";
9 import * as Deferred from "effect/Deferred";
10 import * as Fiber from "effect/Fiber";
11 import * as Exit from "effect/Exit";
12 import * as FileSystem from "effect/FileSystem";
13 import * as Effect from "effect/Effect";
14 import * as Layer from "effect/Layer";
15 import * as PlatformError from "effect/PlatformError";
16 import * as Option from "effect/Option";
17 import * as Path from "effect/Path";
18 import * as Sink from "effect/Sink";
19 import * as Schema from "effect/Schema";
20 import * as Stream from "effect/Stream";
21 import { ChildProcess, ChildProcessSpawner } from "effect/process";
22 import { fromYaml } from "@t3tools/shared/schemaYaml";
23
24 import {
25 buildDesktopBundles,
26 copyDesktopBuildArtifacts,
27 DesktopBuildManifestRestoreError,
28 BundleNotSelfContainedError,
29 BuildCommandFailedError,
30 parseWslRuntimeArchiveMembers,
31 readWorkspaceConfig,
32 createBuildConfig,
33 DESKTOP_FILE_EXCLUSIONS,
34 InvalidMacPasskeyRpDomainError,
35 InvalidMacPasskeyPublishableKeyError,
36 UnsupportedDesktopBuildArchitectureError,
37 MacPasskeySigningConfigurationResolutionError,
38 MissingMacPasskeyProvisioningProfileError,
39 packWindowsServerAsar,
40 preflightWindowsDesktopBuild,
41 renderMacPasskeyEntitlements,
42 resolveMacFileExclusions,
43 resolveMacWebAuthnEntitlements,
44 resolveMacPasskeySigningConfiguration,
45 resolveMergedStageDependencies,
46 resolveBuildOptions,
47 stageWslRuntimeArchive,
48 ancestorNodeModulesPaths,
49 copyDirectoryPreservingSymlinks,
50 LinuxBrowserSecretHostError,
51 LinuxPackagedAppMissingError,
52 MacPackagedAppMissingError,
53 stageBrowserSecret,
54 validateLinuxPackagedPayload,
55 validateMacPackagedPayload,
56 validateWindowsPackagedPayload,
57 verifyPackagedBundleIsSelfContained,
58 WindowsPrimaryNativeProbeError,
59 WindowsDesktopBuildPrerequisitesMissingError,
60 WindowsPackagedPayloadValidationError,
61 stageCursorSdkPlatformPackages,
62 WINDOWS_PACKAGED_PAYLOAD_FILE_LIMIT,
63 WINDOWS_SERVER_ASAR_IGNORE_GLOBS,
64 WINDOWS_SERVER_ASAR_RESOURCE,
65 WSL_RUNTIME_ARCHIVE_EXTRA_RESOURCE,
66 WSL_RUNTIME_ARCHIVE_HASH_EXTRA_RESOURCE,
67 WSL_RUNTIME_ARCHIVE_HASH_NAME,
68 WSL_RUNTIME_ARCHIVE_NAME,
69 wslRuntimeArchiveStem,
70 } from "./build-desktop-artifact.ts";
71 import {
72 ReleasePackageManifestError,
73 releasePackageFiles,
74 } from "./update-release-package-versions.ts";
75 import * as HostProcess from "@t3tools/shared/HostProcess";
76 import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
77
78 const encodeModuleUrl = Schema.encodeEffect(Schema.fromJsonString(Schema.String));
79 const decodePackageVersion = Schema.decodeUnknownEffect(
80 Schema.fromJsonString(Schema.Struct({ version: Schema.String })),
81 );
82
83 // Keeps pnpm from auto-installing TypeScript, a types-only peer, into the app.
84
85 const makeLinuxCliArchiveFixture = Effect.fn("test.makeLinuxCliArchiveFixture")(function* (input: {
86 readonly root: string;
87 readonly stem: string;
88 readonly extraMembers?: ReadonlyArray<string>;
89 readonly omitMembers?: ReadonlyArray<string>;
90 }) {
91 const fs = yield* FileSystem.FileSystem;
92 const path = yield* Path.Path;
93 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
94 const contentRoot = path.join(input.root, "content");
95 const members = [
96 `${input.stem}/t3`,
97 `${input.stem}/client/index.html`,
98 `${input.stem}/node_modules/node-pty/package.json`,
99 `${input.stem}/node_modules/node-pty/build/Release/pty.node`,
100 ...(input.extraMembers ?? []),
101 ].filter((member) => !(input.omitMembers ?? []).includes(member));
102 for (const member of members) {
103 const memberPath = path.join(contentRoot, member);
104 yield* fs.makeDirectory(path.dirname(memberPath), { recursive: true });
105 yield* fs.writeFileString(memberPath, member);
106 }
107 const archivePath = path.join(input.root, `${input.stem}.tar.gz`);
108 const tar = yield* spawner.spawn(
109 ChildProcess.make("tar", ["-czf", archivePath, "-C", contentRoot, "."], {
110 stdin: "ignore",
111 stdout: "ignore",
112 stderr: "pipe",
113 }),
114 );
115 assert.equal(Number(yield* tar.exitCode), 0);
116 return archivePath;
117 });
118
119 function mockProcess(exitCode: number, stdout = "") {
120 const encodedStdout = new TextEncoder().encode(stdout);
121 return ChildProcessSpawner.makeHandle({
122 pid: ChildProcessSpawner.ProcessId(1),
123 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(exitCode)),
124 isRunning: Effect.succeed(false),
125 kill: () => Effect.void,
126 unref: Effect.succeed(Effect.void),
127 stdin: Sink.drain,
128 stdout: stdout ? Stream.make(encodedStdout) : Stream.empty,
129 stderr: Stream.empty,
130 all: Stream.empty,
131 getInputFd: () => Sink.drain,
132 getOutputFd: () => Stream.empty,
133 });
134 }
135
136 const WINDOWS_PAYLOAD_FIXTURE_VERSION = "1.2.3";
137
138 const makeWindowsPayloadFixture = Effect.fn("test.makeWindowsPayloadFixture")(function* (input: {
139 readonly copyUnpackedNatives: boolean;
140 readonly serverEntrySource?: string;
141 readonly wslRuntime?: "valid" | "loose-server-tree" | "missing-pty" | "bad-digest";
142 readonly targetArch?: "x64" | "arm64";
143 readonly ptyPrebuildArch?: "x64" | "arm64";
144 }) {
145 const fs = yield* FileSystem.FileSystem;
146 const path = yield* Path.Path;
147 const tempDir = yield* fs.makeTempDirectoryScoped({
148 prefix: "t3-windows-payload-test-",
149 });
150 const sourceDir = path.join(tempDir, "server-source");
151 const serverEntryPath = path.join(sourceDir, "apps/server/dist/bin.mjs");
152 const nativePath = path.join(sourceDir, "node_modules/native/addon.node");
153 yield* fs.makeDirectory(path.dirname(serverEntryPath), { recursive: true });
154 yield* fs.makeDirectory(path.dirname(nativePath), { recursive: true });
155 yield* fs.writeFileString(serverEntryPath, input.serverEntrySource ?? "console.log('server');\n");
156 yield* fs.writeFileString(nativePath, "MZ native-binary");
157
158 const generatedAsarPath = path.join(tempDir, WINDOWS_SERVER_ASAR_RESOURCE);
159 yield* packWindowsServerAsar({ sourceDir, asarPath: generatedAsarPath, arch: "x64" });
160
161 const stageDistDir = path.join(tempDir, "dist");
162 const packagedAppDir = path.join(stageDistDir, "win-unpacked");
163 const resourcesDir = path.join(packagedAppDir, "resources");
164 yield* fs.makeDirectory(path.join(resourcesDir, "resource-monitor"), { recursive: true });
165 yield* fs.copyFile(generatedAsarPath, path.join(resourcesDir, WINDOWS_SERVER_ASAR_RESOURCE));
166 if (input.copyUnpackedNatives) {
167 yield* fs.copy(
168 `${generatedAsarPath}.unpacked`,
169 path.join(resourcesDir, `${WINDOWS_SERVER_ASAR_RESOURCE}.unpacked`),
170 );
171 }
172 yield* fs.writeFileString(
173 path.join(resourcesDir, "resource-monitor/t3-resource-monitor.exe"),
174 "monitor",
175 );
176 const appExecutableName = "t3code.exe";
177 yield* fs.writeFileString(path.join(packagedAppDir, appExecutableName), "electron");
178 yield* fs.writeFileString(path.join(packagedAppDir, "chrome_crashpad_handler.exe"), "crashpad");
179
180 if (input.wslRuntime !== undefined) {
181 const stem = wslRuntimeArchiveStem(WINDOWS_PAYLOAD_FIXTURE_VERSION, input.targetArch ?? "x64");
182 const sourceArchivePath =
183 input.wslRuntime === "loose-server-tree"
184 ? yield* makeLinuxCliArchiveFixture({
185 root: path.join(tempDir, "wsl-runtime"),
186 stem: "apps",
187 omitMembers: ["apps/t3", "apps/client/index.html"],
188 extraMembers: ["apps/server/dist/bin.mjs", "node_modules/node-pty/package.json"],
189 })
190 : yield* makeLinuxCliArchiveFixture({
191 root: path.join(tempDir, "wsl-runtime"),
192 stem,
193 ...(input.wslRuntime === "missing-pty" || input.ptyPrebuildArch !== undefined
194 ? { omitMembers: [`${stem}/node_modules/node-pty/build/Release/pty.node`] }
195 : {}),
196 ...(input.ptyPrebuildArch !== undefined
197 ? {
198 extraMembers: [
199 `${stem}/node_modules/node-pty/prebuilds/linux-${input.ptyPrebuildArch}/pty.node`,
200 ],
201 }
202 : {}),
203 });
204 const archivePath = path.join(resourcesDir, WSL_RUNTIME_ARCHIVE_NAME);
205 const hashPath = path.join(resourcesDir, WSL_RUNTIME_ARCHIVE_HASH_NAME);
206 yield* stageWslRuntimeArchive({ sourceArchivePath, archivePath, hashPath });
207 if (input.wslRuntime === "bad-digest") {
208 yield* fs.writeFileString(hashPath, `${"0".repeat(64)}\n`);
209 }
210 }
211
212 return {
213 stageDistDir,
214 packagedAppDir,
215 sourceDir,
216 generatedAsarPath,
217 appExecutableName,
218 } as const;
219 });
220
221 const makePackagedAppFixture = Effect.fn("test.makePackagedAppFixture")(function* (input: {
222 readonly serverEntrySource?: string;
223 readonly resourcesPath?: string;
224 }) {
225 const fs = yield* FileSystem.FileSystem;
226 const path = yield* Path.Path;
227 const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-mac-payload-test-" });
228 const sourceDir = path.join(tempDir, "app-source");
229 const serverEntryPath = path.join(sourceDir, "apps/server/dist/bin.mjs");
230 yield* fs.makeDirectory(path.dirname(serverEntryPath), { recursive: true });
231 yield* fs.writeFileString(serverEntryPath, input.serverEntrySource ?? "console.log('server');\n");
232
233 const stageDistDir = path.join(tempDir, "dist");
234 const resourcesDir = path.join(
235 stageDistDir,
236 input.resourcesPath ?? "mac-arm64/T3 Code.app/Contents/Resources",
237 );
238 yield* fs.makeDirectory(resourcesDir, { recursive: true });
239 yield* Effect.promise(() =>
240 createPackageWithOptions(sourceDir, path.join(resourcesDir, "app.asar"), {}),
241 );
242 return { stageDistDir } as const;
243 });
244
245 it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
246 it.effect("rejects overlapping builds from another process until restoration finishes", () =>
247 Effect.gen(function* () {
248 const fs = yield* FileSystem.FileSystem;
249 const path = yield* Path.Path;
250 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-concurrent-build-" });
251 yield* fs.writeFileString(
252 path.join(root, "package.json"),
253 '{ "scripts": { "build:desktop": "node build.cjs" } }',
254 );
255 const original = '{ "version": "0.0.42", "private": true }\n';
256 for (const relativePath of releasePackageFiles) {
257 const filePath = path.join(root, relativePath);
258 yield* fs.makeDirectory(path.dirname(filePath), { recursive: true });
259 yield* fs.writeFileString(filePath, original);
260 }
261 yield* fs.writeFileString(
262 path.join(root, "build.cjs"),
263 `require("node:fs").writeFileSync("version.txt", require("./apps/server/package.json").version);`,
264 );
265 const restoring = yield* Deferred.make<void>();
266 const resume = yield* Deferred.make<void>();
267 const contenderPath = path.join(root, "contender.mjs");
268 yield* fs.writeFileString(
269 contenderPath,
270 `import * as Effect from ${yield* encodeModuleUrl(import.meta.resolve("effect/Effect"))};
271 import * as NodeServices from ${yield* encodeModuleUrl(import.meta.resolve("@effect/platform-node/NodeServices"))};
272 import { buildDesktopBundles } from ${yield* encodeModuleUrl(import.meta.resolve("./build-desktop-artifact.ts"))};
273 const result = await Effect.runPromise(buildDesktopBundles(process.argv[2], "0.0.44", false).pipe(
274 Effect.as("success"), Effect.catch(error => Effect.succeed(error._tag)),
275 Effect.scoped, Effect.provide(NodeServices.layer)));
276 process.stdout.write(result);`,
277 );
278 const first = yield* Effect.forkChild(
279 Effect.exit(buildDesktopBundles(root, "0.0.43", false)).pipe(
280 Effect.provideService(FileSystem.FileSystem, {
281 ...fs,
282 writeFileString: (filePath, contents, options) =>
283 filePath === path.join(root, releasePackageFiles[0]) && contents === original
284 ? Deferred.succeed(restoring, undefined).pipe(
285 Effect.andThen(Deferred.await(resume)),
286 Effect.andThen(fs.writeFileString(filePath, contents, options)),
287 )
288 : fs.writeFileString(filePath, contents, options),
289 }),
290 ),
291 );
292 yield* Deferred.await(restoring);
293 yield* Effect.gen(function* () {
294 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
295 const child = yield* spawner.spawn(
296 ChildProcess.make(process.execPath, [contenderPath, root]),
297 );
298 const [stdout, stderr, exitCode] = yield* Effect.all(
299 [
300 child.stdout.pipe(Stream.decodeText, Stream.mkString),
301 child.stderr.pipe(Stream.decodeText, Stream.mkString),
302 child.exitCode,
303 ],
304 { concurrency: "unbounded" },
305 );
306 assert.equal(Number(exitCode), 0, stderr);
307 assert.equal(stdout, "DesktopBuildAlreadyRunningError");
308 }).pipe(Effect.ensuring(Deferred.succeed(resume, undefined)));
309 const firstExit = yield* Fiber.join(first);
310 assert.isTrue(Exit.isSuccess(firstExit));
311 assert.equal(yield* fs.readFileString(path.join(root, "version.txt")), "0.0.43");
312 for (const relativePath of releasePackageFiles) {
313 assert.equal(yield* fs.readFileString(path.join(root, relativePath)), original);
314 }
315 yield* buildDesktopBundles(root, "0.0.44", false);
316 assert.equal(yield* fs.readFileString(path.join(root, "version.txt")), "0.0.44");
317 for (const relativePath of releasePackageFiles) {
318 assert.equal(yield* fs.readFileString(path.join(root, relativePath)), original);
319 }
320 }),
321 );
322
323 it.effect("restores manifests and releases the checkout lock after interruption", () =>
324 Effect.gen(function* () {
325 const fs = yield* FileSystem.FileSystem;
326 const path = yield* Path.Path;
327 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-interrupted-build-" });
328 const original = '{ "version": "0.0.42", "private": true }\n';
329 for (const relativePath of releasePackageFiles) {
330 const filePath = path.join(root, relativePath);
331 yield* fs.makeDirectory(path.dirname(filePath), { recursive: true });
332 yield* fs.writeFileString(filePath, original);
333 }
334 const started = yield* Deferred.make<void>();
335 const childStopped = yield* Deferred.make<{ lockExists: boolean; version: string }>();
336 const build = yield* Effect.forkChild(
337 buildDesktopBundles(root, "0.0.43", false).pipe(
338 Effect.provideService(
339 ChildProcessSpawner.ChildProcessSpawner,
340 ChildProcessSpawner.make(() =>
341 Effect.acquireRelease(
342 Effect.succeed({ ...mockProcess(0), exitCode: Effect.never }).pipe(
343 Effect.tap(() => Deferred.succeed(started, undefined)),
344 ),
345 () =>
346 Effect.gen(function* () {
347 const lockExists = yield* fs.exists(path.join(root, ".desktop-build.lock"));
348 const manifest = yield* decodePackageVersion(
349 yield* fs.readFileString(path.join(root, releasePackageFiles[0])),
350 );
351 yield* Deferred.succeed(childStopped, {
352 lockExists,
353 version: manifest.version,
354 });
355 }).pipe(Effect.orDie),
356 ),
357 ),
358 ),
359 Effect.scoped,
360 ),
361 );
362 yield* Deferred.await(started);
363 const aligned = yield* decodePackageVersion(
364 yield* fs.readFileString(path.join(root, releasePackageFiles[0])),
365 );
366 assert.equal(aligned.version, "0.0.43");
367 yield* Fiber.interrupt(build);
368 assert.deepEqual(yield* Deferred.await(childStopped), {
369 lockExists: true,
370 version: "0.0.43",
371 });
372 assert.isFalse(yield* fs.exists(path.join(root, ".desktop-build.lock")));
373 for (const relativePath of releasePackageFiles) {
374 assert.equal(yield* fs.readFileString(path.join(root, relativePath)), original);
375 }
376 yield* buildDesktopBundles(root, "0.0.44", false).pipe(
377 Effect.provideService(
378 ChildProcessSpawner.ChildProcessSpawner,
379 ChildProcessSpawner.make(() => Effect.succeed(mockProcess(0))),
380 ),
381 );
382 assert.isFalse(yield* fs.exists(path.join(root, ".desktop-build.lock")));
383 }),
384 );
385
386 it.effect(
387 "builds web, server and desktop with the resolved version, restores changed manifests and preserves edits to matching ones",
388 () =>
389 Effect.gen(function* () {
390 const fs = yield* FileSystem.FileSystem;
391 const path = yield* Path.Path;
392 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-desktop-build-version-" });
393 const packageJson = `{
394 "name": "desktop-version-fixture",
395 "version": "0.0.42",
396 "scripts": { "build:desktop": "node build.cjs" }
397 }`;
398 yield* fs.writeFileString(path.join(root, "package.json"), packageJson);
399 const version = "0.0.43-nightly.20260920.2018";
400 const matchingPath = "packages/contracts/package.json";
401 const originals = releasePackageFiles.map((relativePath, index) => ({
402 relativePath,
403 contents: `{ "version": "${relativePath === matchingPath ? version : `0.0.${index + 1}`}", "name": "${relativePath}" }\r\n`,
404 }));
405 const afterBuild = originals.map(({ relativePath, contents }) => ({
406 relativePath,
407 contents:
408 relativePath === matchingPath
409 ? `${JSON.stringify({ version, name: matchingPath, description: "edited during compilation" })}\n`
410 : contents,
411 }));
412 for (const { relativePath, contents } of originals) {
413 const filePath = path.join(root, relativePath);
414 yield* fs.makeDirectory(path.dirname(filePath), { recursive: true });
415 yield* fs.writeFileString(filePath, contents);
416 }
417 yield* fs.writeFileString(
418 path.join(root, "build.cjs"),
419 `require("node:fs").writeFileSync("version.txt", [
420 process.env.APP_VERSION,
421 require("./apps/web/package.json").version,
422 require("./apps/server/package.json").version,
423 require("./apps/desktop/package.json").version
424 ].join("\\n"));
425 const manifest = require("./${matchingPath}");
426 manifest.description = "edited during compilation";
427 require("node:fs").writeFileSync("${matchingPath}", JSON.stringify(manifest) + "\\n");`,
428 );
429 yield* buildDesktopBundles(root, version, false);
430 assert.equal(
431 yield* fs.readFileString(path.join(root, "version.txt")),
432 [version, version, version, version].join("\n"),
433 );
434 for (const { relativePath, contents } of afterBuild) {
435 assert.equal(yield* fs.readFileString(path.join(root, relativePath)), contents);
436 }
437 assert.equal(yield* fs.readFileString(path.join(root, "package.json")), packageJson);
438 yield* fs.writeFileString(path.join(root, "build.cjs"), "process.exit(1);");
439 const failure = yield* Effect.flip(buildDesktopBundles(root, "0.0.44", false));
440 assert.instanceOf(failure, BuildCommandFailedError);
441 for (const { relativePath, contents } of afterBuild) {
442 assert.equal(yield* fs.readFileString(path.join(root, relativePath)), contents);
443 }
444 const invalidPath = releasePackageFiles[releasePackageFiles.length - 1]!;
445 yield* fs.writeFileString(path.join(root, invalidPath), "invalid manifest");
446 // A successful child would leave a marker if partial alignment accidentally starts it.
447 yield* fs.writeFileString(
448 path.join(root, "build.cjs"),
449 'require("node:fs").writeFileSync("unexpected-build.txt", "started");',
450 );
451 const alignmentFailure = yield* Effect.flip(buildDesktopBundles(root, "0.0.44", false));
452 assert.instanceOf(alignmentFailure, ReleasePackageManifestError);
453 for (const { relativePath, contents } of afterBuild) {
454 assert.equal(
455 yield* fs.readFileString(path.join(root, relativePath)),
456 relativePath === invalidPath ? "invalid manifest" : contents,
457 );
458 }
459 assert.isFalse(yield* fs.exists(path.join(root, "unexpected-build.txt")));
460 assert.isFalse(yield* fs.exists(path.join(root, ".desktop-build.lock")));
461 assert.equal(yield* fs.readFileString(path.join(root, "package.json")), packageJson);
462 }),
463 );
464
465 it.effect("reports a restore failure while still restoring the remaining manifests", () =>
466 Effect.gen(function* () {
467 const fs = yield* FileSystem.FileSystem;
468 const path = yield* Path.Path;
469 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-manifest-restore-failure-" });
470 yield* fs.writeFileString(
471 path.join(root, "package.json"),
472 `{
473 "name": "restore-fixture", "scripts": { "build:desktop": "node build.cjs" }
474 }`,
475 );
476 yield* fs.writeFileString(path.join(root, "build.cjs"), "process.exit(0);");
477 const original = '{ "version": "0.0.42" }\n';
478 for (const relativePath of releasePackageFiles) {
479 const filePath = path.join(root, relativePath);
480 yield* fs.makeDirectory(path.dirname(filePath), { recursive: true });
481 yield* fs.writeFileString(filePath, original);
482 }
483 const failedPath = path.join(root, releasePackageFiles[0]);
484 const writeFailure = PlatformError.systemError({
485 _tag: "PermissionDenied",
486 module: "FileSystem",
487 method: "writeFileString",
488 pathOrDescriptor: failedPath,
489 });
490 const failure = yield* Effect.flip(buildDesktopBundles(root, "0.0.43", false)).pipe(
491 Effect.provideService(FileSystem.FileSystem, {
492 ...fs,
493 writeFileString: (filePath, contents, options) =>
494 filePath === failedPath && contents === original
495 ? Effect.fail(writeFailure)
496 : fs.writeFileString(filePath, contents, options),
497 }),
498 );
499 assert.instanceOf(failure, DesktopBuildManifestRestoreError);
500 assert.notEqual(yield* fs.readFileString(failedPath), original);
501 for (const relativePath of releasePackageFiles.slice(1)) {
502 assert.equal(yield* fs.readFileString(path.join(root, relativePath)), original);
503 }
504 }),
505 );
506
507 it.effect("omits update feeds for pull request preview builds", () =>
508 Effect.gen(function* () {
509 const preview = yield* createBuildConfig(
510 "mac",
511 "dmg",
512 "0.0.33-pr.8182.1",
513 false,
514 false,
515 undefined,
516 undefined,
517 );
518 const release = yield* createBuildConfig(
519 "mac",
520 "dmg",
521 "0.0.33",
522 false,
523 false,
524 undefined,
525 undefined,
526 );
527
528 const previewChannel = yield* createBuildConfig(
529 "mac",
530 "dmg",
531 "0.0.41-preview.20260912.1589",
532 false,
533 false,
534 undefined,
535 undefined,
536 );
537
538 assert.isNull(preview.publish);
539 assert.isNull(previewChannel.publish);
540 assert.deepStrictEqual(release.publish, [
541 {
542 provider: "github",
543 owner: "pingdotgg",
544 repo: "t3code",
545 releaseType: "release",
546 },
547 ]);
548 }).pipe(
549 Effect.provide(
550 ConfigProvider.layer(
551 ConfigProvider.fromEnv({ env: { GITHUB_REPOSITORY: "pingdotgg/t3code" } }),
552 ),
553 ),
554 ),
555 );
556
557 it.effect("names the Electron window class in the Linux desktop entry", () =>
558 Effect.gen(function* () {
559 const linux = yield* createBuildConfig(
560 "linux",
561 "AppImage",
562 "0.0.33",
563 false,
564 false,
565 undefined,
566 undefined,
567 );
568
569 assert.nestedPropertyVal(linux, "linux.desktop.entry.StartupWMClass", "com.t3tools.T3Code");
570 }),
571 );
572
573 it.effect("names updatable AppImages without a version and apart per channel", () =>
574 Effect.gen(function* () {
575 const appImageName = (version: string) =>
576 createBuildConfig("linux", "AppImage", version, false, false, undefined, undefined).pipe(
577 Effect.map((config) => (config.appImage as { artifactName: string }).artifactName),
578 );
579
580 const stable = yield* appImageName("0.0.37");
581 const nightly = yield* appImageName("0.0.38-nightly.20261026.3740");
582
583 assert.notInclude(stable, "${version}");
584 assert.notInclude(nightly, "${version}");
585 assert.notEqual(stable, nightly);
586 }).pipe(
587 Effect.provide(
588 ConfigProvider.layer(
589 ConfigProvider.fromEnv({ env: { GITHUB_REPOSITORY: "pingdotgg/t3code" } }),
590 ),
591 ),
592 ),
593 );
594
595 it.effect("declares Calendar access for hosted commands in macOS builds", () =>
596 Effect.gen(function* () {
597 for (const version of ["0.1.0", "0.1.1-nightly.20261019.1"]) {
598 for (const signed of [false, true]) {
599 const config = yield* createBuildConfig(
600 "mac",
601 "dmg",
602 version,
603 signed,
604 false,
605 undefined,
606 undefined,
607 );
608 const mac = config.mac as { extendInfo: Record<string, unknown> };
609 for (const key of [
610 "NSCalendarsUsageDescription",
611 "NSCalendarsFullAccessUsageDescription",
612 "NSCalendarsWriteOnlyAccessUsageDescription",
613 ]) {
614 assert.isString(mac.extendInfo[key], `${version}, signed=${signed}: ${key}`);
615 assert.isNotEmpty(mac.extendInfo[key]);
616 }
617 }
618 }
619 }),
620 );
621
622 // pnpm writes "set this to true or false" placeholders into allowBuilds when a
623 // tarball changes. pnpm ignores them, but the release build decode rejects them.
624 it.effect("decodes the repo allowBuilds and every file: tarball it names exists", () =>
625 Effect.gen(function* () {
626 const fs = yield* FileSystem.FileSystem;
627 const path = yield* Path.Path;
628 const { allowBuilds = {} } = yield* readWorkspaceConfig();
629 const repoRoot = path.join(import.meta.dirname, "..");
630 for (const key of Object.keys(allowBuilds)) {
631 const tarball = key.split("@file:")[1]?.replace(/\(patch_hash=[a-f0-9]+\)$/, "");
632 if (tarball === undefined) continue;
633 assert.isTrue(
634 yield* fs.exists(path.join(repoRoot, tarball)),
635 `allowBuilds names a missing tarball: ${key}`,
636 );
637 }
638 }),
639 );
640
641 it("stages only the externals of both bundles in merged packages", () => {
642 assert.deepStrictEqual(
643 resolveMergedStageDependencies({
644 platform: "mac",
645 serverDependencies: {
646 "@cursor/sdk": "1.0.22",
647 "@anthropic-ai/claude-agent-sdk": "^0.3.170",
648 "@ff-labs/fff-node": "0.9.4",
649 "@opencode-ai/sdk": "^1.3.15",
650 "@pierre/diffs": "1.3.0",
651 "node-pty": "1.1.0",
652 },
653 desktopDependencies: {
654 "@napi-rs/keyring": "1.3.0",
655 "playwright-core": "1.60.0",
656 },
657 arch: "arm64",
658 fffNodeVersion: "0.9.4",
659 }),
660 {
661 "@cursor/sdk": "1.0.22",
662 "@ff-labs/fff-node": "0.9.4",
663 "node-pty": "1.1.0",
664 "@napi-rs/keyring": "1.3.0",
665 "playwright-core": "1.60.0",
666 "@ff-labs/fff-bin-darwin-arm64": "0.9.4",
667 },
668 );
669
670 assert.deepStrictEqual(
671 resolveMergedStageDependencies({
672 platform: "linux",
673 serverDependencies: { "@ff-labs/fff-node": "0.9.4", "node-pty": "1.1.0", effect: "4.0.0" },
674 desktopDependencies: { "@crowecawcaw/xa11y": "0.13.0" },
675 arch: "x64",
676 fffNodeVersion: "0.9.4",
677 }),
678 {
679 "@ff-labs/fff-node": "0.9.4",
680 "node-pty": "1.1.0",
681 "@crowecawcaw/xa11y": "0.13.0",
682 "@ff-labs/fff-bin-linux-x64-gnu": "0.9.4",
683 "@ff-labs/fff-bin-linux-x64-musl": "0.9.4",
684 },
685 );
686 });
687
688 it.effect("ships Cursor platform assets outside asar for spawning and native loading", () =>
689 Effect.scoped(
690 Effect.gen(function* () {
691 const fs = yield* FileSystem.FileSystem;
692 const path = yield* Path.Path;
693 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cursor-helpers-" });
694 const nodeModules = path.join(root, "node_modules");
695 const destination = path.join(root, "resources/node_modules/@cursor");
696 const cursorDirectory = symlinksSupported
697 ? path.join(root, "store/@cursor")
698 : path.join(nodeModules, "@cursor");
699 yield* fs.makeDirectory(path.join(cursorDirectory, "sdk"), { recursive: true });
700 if (symlinksSupported) {
701 yield* fs.makeDirectory(path.join(nodeModules, "@cursor"), { recursive: true });
702 yield* fs.symlink(
703 path.join(cursorDirectory, "sdk"),
704 path.join(nodeModules, "@cursor/sdk"),
705 );
706 }
707 const helpers = [
708 "sdk-darwin-arm64/bin/rg",
709 "sdk-darwin-arm64/bin/cursorsandbox",
710 "sdk-darwin-arm64/vendor/tree-sitter/index.js",
711 "sdk-darwin-arm64/vendor/tree-sitter/binding.node",
712 "sdk-darwin-arm64/vendor/tree-sitter-bash/binding.node",
713 "sdk-darwin-arm64/package.json",
714 "sdk-win32-x64/bin/rg.exe",
715 ];
716 for (const helper of helpers) {
717 const source = path.join(cursorDirectory, helper);
718 yield* fs.makeDirectory(path.dirname(source), { recursive: true });
719 yield* fs.writeFileString(source, "fixture helper", { mode: 0o755 });
720 }
721 yield* stageCursorSdkPlatformPackages(nodeModules, destination);
722 for (const helper of helpers) {
723 assert.equal(yield* fs.readFileString(path.join(destination, helper)), "fixture helper");
724 const packagedPath = `node_modules/@cursor/${helper}`;
725 assert.isTrue(
726 DESKTOP_FILE_EXCLUSIONS.some((glob) =>
727 NodePath.matchesGlob(packagedPath, glob.slice(1)),
728 ),
729 );
730 assert.isTrue(
731 WINDOWS_SERVER_ASAR_IGNORE_GLOBS.some((glob) =>
732 NodePath.matchesGlob(packagedPath, glob),
733 ),
734 );
735 }
736 }),
737 ),
738 );
739
740 it("drops the other architecture's Darwin prebuilds from single-architecture Mac builds", () => {
741 const excludes = (arch: "arm64" | "x64" | "universal", file: string) =>
742 resolveMacFileExclusions(arch).some((glob) => NodePath.matchesGlob(file, glob.slice(1)));
743 const x64 = [
744 "node_modules/node-pty/prebuilds/darwin-x64/pty.node",
745 "node_modules/objc-js/prebuilds/darwin-x64/node.napi.node",
746 ];
747 const arm64 = [
748 "node_modules/node-pty/prebuilds/darwin-arm64/pty.node",
749 "node_modules/objc-js/prebuilds/darwin-arm64/node.napi.armv8.node",
750 ];
751
752 for (const file of x64) {
753 assert.isTrue(excludes("arm64", file), file);
754 assert.isFalse(excludes("x64", file), file);
755 assert.isFalse(excludes("universal", file), file);
756 }
757 for (const file of arm64) {
758 assert.isTrue(excludes("x64", file), file);
759 assert.isFalse(excludes("arm64", file), file);
760 assert.isFalse(excludes("universal", file), file);
761 }
762 });
763
764 it.effect("unpacks target Windows natives while excluding the other architecture", () =>
765 Effect.scoped(
766 Effect.gen(function* () {
767 const fs = yield* FileSystem.FileSystem;
768 const path = yield* Path.Path;
769 const tempDir = yield* fs.makeTempDirectoryScoped({
770 prefix: "t3-windows-architecture-test-",
771 });
772 const sourceDir = path.join(tempDir, "server");
773 const nativeFiles = [
774 "node_modules/node-pty/prebuilds/win32-x64/conpty/OpenConsole.exe",
775 "node_modules/node-pty/prebuilds/win32-arm64/conpty/OpenConsole.exe",
776 "node_modules/node-pty/third_party/conpty/1.0.0/win10-x64/OpenConsole.exe",
777 "node_modules/node-pty/third_party/conpty/1.0.0/win10-arm64/OpenConsole.exe",
778 "node_modules/node-pty/prebuilds/win32-x64/pty.node",
779 "node_modules/node-pty/prebuilds/linux-x64/pty.node",
780 ];
781
782 for (const nativeFile of nativeFiles) {
783 const nativePath = path.join(sourceDir, nativeFile);
784 yield* fs.makeDirectory(path.dirname(nativePath), { recursive: true });
785 yield* fs.writeFileString(nativePath, nativeFile.includes("linux") ? "\x7fELF" : "MZ");
786 }
787
788 const asarPath = path.join(tempDir, "server.asar");
789 yield* packWindowsServerAsar({ sourceDir, asarPath, arch: "x64" });
790 const unpackedRoot = `${asarPath}.unpacked`;
791
792 assert.isTrue(
793 yield* fs.exists(
794 path.join(
795 unpackedRoot,
796 "node_modules/node-pty/prebuilds/win32-x64/conpty/OpenConsole.exe",
797 ),
798 ),
799 );
800 assert.isTrue(
801 yield* fs.exists(
802 path.join(unpackedRoot, "node_modules/node-pty/prebuilds/win32-x64/pty.node"),
803 ),
804 );
805 assert.isFalse(
806 yield* fs.exists(path.join(unpackedRoot, "node_modules/node-pty/prebuilds/linux-x64")),
807 );
808 assert.equal(
809 extractFile(
810 asarPath,
811 path.join("node_modules", "node-pty", "prebuilds", "linux-x64", "pty.node"),
812 ).toString(),
813 "\x7fELF",
814 );
815 assert.isFalse(
816 yield* fs.exists(path.join(unpackedRoot, "node_modules/node-pty/prebuilds/win32-arm64")),
817 );
818 assert.isFalse(
819 yield* fs.exists(
820 path.join(unpackedRoot, "node_modules/node-pty/third_party/conpty/1.0.0/win10-arm64"),
821 ),
822 );
823 }),
824 ),
825 );
826
827 it.effect("reports missing Windows toolchain capabilities before building", () =>
828 Effect.scoped(
829 Effect.gen(function* () {
830 const fs = yield* FileSystem.FileSystem;
831 const path = yield* Path.Path;
832 const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-windows-preflight-" });
833 const pythonPath = path.join(tempDir, "python.exe");
834 yield* fs.writeFileString(pythonPath, "python");
835 const spawner = Layer.succeed(
836 ChildProcessSpawner.ChildProcessSpawner,
837 ChildProcessSpawner.make((command) => {
838 const childProcess = command as unknown as { readonly command: string };
839 const fails =
840 childProcess.command === "rustc" ||
841 childProcess.command === "powershell.exe" ||
842 childProcess.command === pythonPath;
843 return Effect.succeed(mockProcess(fails ? 1 : 0));
844 }),
845 );
846 const error = yield* preflightWindowsDesktopBuild({
847 arch: "x64",
848 bundlesWslRuntime: true,
849 }).pipe(
850 Effect.provide(
851 Layer.merge(
852 spawner,
853 ConfigProvider.layer(
854 ConfigProvider.fromEnv({ env: { npm_config_python: pythonPath } }),
855 ),
856 ),
857 ),
858 Effect.flip,
859 );
860
861 assert.instanceOf(error, WindowsDesktopBuildPrerequisitesMissingError);
862 assert.deepStrictEqual(error.missing, ["rust", "python", "msvc"]);
863 assert.equal(error.rustTarget, "x86_64-pc-windows-msvc");
864 assert.include(error.message, "Visual Studio Build Tools components");
865 }),
866 ),
867 );
868
869 it.effect("does not require MSVC when reusing a prebuilt Windows resource monitor", () =>
870 Effect.scoped(
871 Effect.gen(function* () {
872 const fs = yield* FileSystem.FileSystem;
873 const path = yield* Path.Path;
874 const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-windows-preflight-" });
875 const pythonPath = path.join(tempDir, "python.exe");
876 yield* fs.writeFileString(pythonPath, "python");
877 const commands: string[] = [];
878 const spawner = Layer.succeed(
879 ChildProcessSpawner.ChildProcessSpawner,
880 ChildProcessSpawner.make((command) => {
881 const childProcess = command as unknown as { readonly command: string };
882 commands.push(childProcess.command);
883 return Effect.succeed(mockProcess(childProcess.command === "powershell.exe" ? 1 : 0));
884 }),
885 );
886
887 yield* preflightWindowsDesktopBuild({
888 arch: "x64",
889 bundlesWslRuntime: true,
890 }).pipe(
891 Effect.provide(
892 Layer.merge(
893 spawner,
894 ConfigProvider.layer(
895 ConfigProvider.fromEnv({
896 env: {
897 npm_config_python: pythonPath,
898 T3CODE_DESKTOP_REUSE_RESOURCE_MONITOR: "true",
899 },
900 }),
901 ),
902 ),
903 ),
904 );
905
906 assert.notInclude(commands, "powershell.exe");
907 }),
908 ),
909 );
910
911 it.effect("rejects a PATH-discovered Python executable that is not Python 3", () =>
912 Effect.scoped(
913 Effect.gen(function* () {
914 const fs = yield* FileSystem.FileSystem;
915 const path = yield* Path.Path;
916 const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-python2-preflight-" });
917 const pythonPath = path.join(tempDir, "python");
918 yield* fs.writeFileString(pythonPath, "python2");
919 const spawner = Layer.succeed(
920 ChildProcessSpawner.ChildProcessSpawner,
921 ChildProcessSpawner.make((command) => {
922 const childProcess = command as unknown as {
923 readonly command: string;
924 readonly args: ReadonlyArray<string>;
925 };
926 if (childProcess.command === "python") {
927 return Effect.succeed(mockProcess(0, `${pythonPath}\n`));
928 }
929 if (childProcess.command === pythonPath) {
930 return Effect.succeed(mockProcess(1));
931 }
932 return Effect.succeed(mockProcess(0));
933 }),
934 );
935 const error = yield* preflightWindowsDesktopBuild({
936 arch: "x64",
937 bundlesWslRuntime: false,
938 }).pipe(
939 Effect.provide(
940 Layer.merge(
941 spawner,
942 ConfigProvider.layer(
943 ConfigProvider.fromEnv({
944 env: { T3CODE_DESKTOP_REUSE_RESOURCE_MONITOR: "true" },
945 }),
946 ),
947 ),
948 ),
949 Effect.flip,
950 );
951
952 assert.instanceOf(error, WindowsDesktopBuildPrerequisitesMissingError);
953 assert.deepStrictEqual(error.missing, ["python"]);
954 }),
955 ),
956 );
957
958 // The fixture's t3code.exe is a text placeholder, not an executable. These
959 // cases reach the native-load probe, so pin only that host-platform check to
960 // Linux. Host-native paths and the real Windows tar/archive checks still run.
961 it.effect("validates every ASAR-unpacked native in the packaged Windows payload", () =>
962 Effect.scoped(
963 Effect.gen(function* () {
964 const fs = yield* FileSystem.FileSystem;
965 const path = yield* Path.Path;
966 const fixture = yield* makeWindowsPayloadFixture({ copyUnpackedNatives: true });
967 const result = yield* validateWindowsPackagedPayload({
968 stageDistDir: fixture.stageDistDir,
969 appExecutableName: fixture.appExecutableName,
970 targetArch: "x64",
971 appVersion: WINDOWS_PAYLOAD_FIXTURE_VERSION,
972 });
973
974 const secondAsarPath = path.join(path.dirname(fixture.generatedAsarPath), "second.asar");
975 yield* packWindowsServerAsar({
976 sourceDir: fixture.sourceDir,
977 asarPath: secondAsarPath,
978 arch: "x64",
979 });
980 const [firstAsar, secondAsar] = yield* Effect.all([
981 fs.readFile(fixture.generatedAsarPath),
982 fs.readFile(secondAsarPath),
983 ]);
984
985 assert.equal(result.packagedAppDir, fixture.packagedAppDir);
986 assert.deepStrictEqual(result.unpackedFiles, ["node_modules/native/addon.node"]);
987 assert.isBelow(result.fileCount, WINDOWS_PACKAGED_PAYLOAD_FILE_LIMIT);
988 assert.deepStrictEqual(secondAsar, firstAsar);
989 }),
990 ).pipe(Effect.provideService(HostProcess.Platform, "linux")),
991 );
992
993 it.effect.each(["x64", "arm64"] as const)(
994 "accepts an embedded archive with the Linux %s node-pty prebuild",
995 (targetArch) =>
996 Effect.scoped(
997 Effect.gen(function* () {
998 const fixture = yield* makeWindowsPayloadFixture({
999 copyUnpackedNatives: true,
1000 wslRuntime: "valid",
1001 targetArch,
1002 ptyPrebuildArch: targetArch,
1003 });
1004 const result = yield* validateWindowsPackagedPayload({
1005 stageDistDir: fixture.stageDistDir,
1006 appExecutableName: fixture.appExecutableName,
1007 targetArch,
1008 appVersion: WINDOWS_PAYLOAD_FIXTURE_VERSION,
1009 expectWslRuntime: true,
1010 });
1011
1012 assert.equal(result.packagedAppDir, fixture.packagedAppDir);
1013 }),
1014 ).pipe(Effect.provideService(HostProcess.Platform, "linux")),
1015 );
1016
1017 it.effect.each(["x64", "arm64"] as const)(
1018 "rejects a node-pty prebuild for the wrong architecture in a Linux %s archive",
1019 (targetArch) =>
1020 Effect.scoped(
1021 Effect.gen(function* () {
1022 const fixture = yield* makeWindowsPayloadFixture({
1023 copyUnpackedNatives: true,
1024 wslRuntime: "valid",
1025 targetArch,
1026 ptyPrebuildArch: targetArch === "x64" ? "arm64" : "x64",
1027 });
1028 const error = yield* validateWindowsPackagedPayload({
1029 stageDistDir: fixture.stageDistDir,
1030 appExecutableName: fixture.appExecutableName,
1031 targetArch,
1032 appVersion: WINDOWS_PAYLOAD_FIXTURE_VERSION,
1033 expectWslRuntime: true,
1034 }).pipe(Effect.flip);
1035
1036 assert.instanceOf(error, WindowsPackagedPayloadValidationError);
1037 assert.equal(error.reason, "wsl-runtime-invalid");
1038 }),
1039 ),
1040 );
1041
1042 it.effect("rejects an embedded archive built for a different release version", () =>
1043 Effect.scoped(
1044 Effect.gen(function* () {
1045 const fixture = yield* makeWindowsPayloadFixture({
1046 copyUnpackedNatives: true,
1047 wslRuntime: "valid",
1048 });
1049 const error = yield* validateWindowsPackagedPayload({
1050 stageDistDir: fixture.stageDistDir,
1051 appExecutableName: fixture.appExecutableName,
1052 targetArch: "x64",
1053 appVersion: "9.9.9",
1054 expectWslRuntime: true,
1055 }).pipe(Effect.flip);
1056
1057 assert.instanceOf(error, WindowsPackagedPayloadValidationError);
1058 assert.equal(error.reason, "wsl-runtime-invalid");
1059 }),
1060 ),
1061 );
1062
1063 it.effect("rejects a Windows package missing its expected WSL runtime", () =>
1064 Effect.scoped(
1065 Effect.gen(function* () {
1066 const fixture = yield* makeWindowsPayloadFixture({ copyUnpackedNatives: true });
1067 const error = yield* validateWindowsPackagedPayload({
1068 stageDistDir: fixture.stageDistDir,
1069 appExecutableName: fixture.appExecutableName,
1070 targetArch: "x64",
1071 appVersion: WINDOWS_PAYLOAD_FIXTURE_VERSION,
1072 expectWslRuntime: true,
1073 }).pipe(Effect.flip);
1074
1075 assert.instanceOf(error, WindowsPackagedPayloadValidationError);
1076 assert.equal(error.reason, "wsl-runtime-missing");
1077 }),
1078 ),
1079 );
1080
1081 it.effect("rejects an embedded archive without the Linux node-pty binary", () =>
1082 Effect.scoped(
1083 Effect.gen(function* () {
1084 const fixture = yield* makeWindowsPayloadFixture({
1085 copyUnpackedNatives: true,
1086 wslRuntime: "missing-pty",
1087 });
1088 const error = yield* validateWindowsPackagedPayload({
1089 stageDistDir: fixture.stageDistDir,
1090 appExecutableName: fixture.appExecutableName,
1091 targetArch: "x64",
1092 appVersion: WINDOWS_PAYLOAD_FIXTURE_VERSION,
1093 expectWslRuntime: true,
1094 }).pipe(Effect.flip);
1095
1096 assert.instanceOf(error, WindowsPackagedPayloadValidationError);
1097 assert.equal(error.reason, "wsl-runtime-invalid");
1098 assert.deepStrictEqual(error.missingFiles, [
1099 `${wslRuntimeArchiveStem(WINDOWS_PAYLOAD_FIXTURE_VERSION, "x64")}/node_modules/node-pty/build/Release/pty.node`,
1100 `${wslRuntimeArchiveStem(WINDOWS_PAYLOAD_FIXTURE_VERSION, "x64")}/node_modules/node-pty/prebuilds/linux-x64/pty.node`,
1101 ]);
1102 }),
1103 ),
1104 );
1105
1106 it.effect("rejects an emitted WSL archive whose sidecar digest does not match", () =>
1107 Effect.scoped(
1108 Effect.gen(function* () {
1109 const fixture = yield* makeWindowsPayloadFixture({
1110 copyUnpackedNatives: true,
1111 wslRuntime: "bad-digest",
1112 });
1113 const error = yield* validateWindowsPackagedPayload({
1114 stageDistDir: fixture.stageDistDir,
1115 appExecutableName: fixture.appExecutableName,
1116 targetArch: "x64",
1117 appVersion: WINDOWS_PAYLOAD_FIXTURE_VERSION,
1118 expectWslRuntime: true,
1119 }).pipe(Effect.flip);
1120
1121 assert.instanceOf(error, WindowsPackagedPayloadValidationError);
1122 assert.equal(error.reason, "wsl-runtime-invalid");
1123 }),
1124 ),
1125 );
1126
1127 it.effect("probes fff through the packaged Windows primary instead of helper executables", () => {
1128 const commands: Array<{
1129 readonly command: string;
1130 readonly args: ReadonlyArray<string>;
1131 readonly options: {
1132 readonly cwd?: string;
1133 readonly env?: Readonly<Record<string, string | undefined>>;
1134 };
1135 }> = [];
1136 const spawnerLayer = Layer.succeed(
1137 ChildProcessSpawner.ChildProcessSpawner,
1138 ChildProcessSpawner.make((command) => {
1139 commands.push(command as unknown as (typeof commands)[number]);
1140 return Effect.succeed(mockProcess(0));
1141 }),
1142 );
1143
1144 return Effect.scoped(
1145 Effect.gen(function* () {
1146 const path = yield* Path.Path;
1147 const fixture = yield* makeWindowsPayloadFixture({ copyUnpackedNatives: true });
1148 yield* validateWindowsPackagedPayload({
1149 stageDistDir: fixture.stageDistDir,
1150 appExecutableName: fixture.appExecutableName,
1151 targetArch: "x64",
1152 appVersion: WINDOWS_PAYLOAD_FIXTURE_VERSION,
1153 });
1154
1155 const primaryProbe = commands.find(
1156 (command) => command.options.env?.ELECTRON_RUN_AS_NODE === "1",
1157 );
1158 if (primaryProbe === undefined) return assert.fail("Windows primary probe was not spawned");
1159
1160 assert.equal(
1161 primaryProbe.command,
1162 path.join(fixture.packagedAppDir, fixture.appExecutableName),
1163 );
1164 assert.deepStrictEqual(primaryProbe.args.slice(0, 3), [
1165 "--no-global-search-paths",
1166 "--input-type=module",
1167 "--eval",
1168 ]);
1169 assert.include(primaryProbe.args[3], "FileFinder.create");
1170 assert.equal(
1171 primaryProbe.args[4],
1172 path.join(
1173 fixture.packagedAppDir,
1174 "resources/server.asar/node_modules/@ff-labs/fff-node/dist/index.js",
1175 ),
1176 );
1177 assert.equal(primaryProbe.options.cwd, fixture.packagedAppDir);
1178 assert.equal(primaryProbe.options.env?.NODE_PATH, "");
1179 }),
1180 ).pipe(
1181 Effect.provide(
1182 Layer.mergeAll(
1183 spawnerLayer,
1184 Layer.succeed(HostProcess.Platform, "win32"),
1185 Layer.succeed(HostProcess.Architecture, "x64"),
1186 ),
1187 ),
1188 );
1189 });
1190
1191 it.effect("refuses a Linux build on a host that cannot build the browser secret helper", () => {
1192 const commands: Array<{ readonly command: string }> = [];
1193 const spawnerLayer = Layer.succeed(
1194 ChildProcessSpawner.ChildProcessSpawner,
1195 ChildProcessSpawner.make((command) => {
1196 commands.push(command as unknown as (typeof commands)[number]);
1197 return Effect.succeed(mockProcess(0));
1198 }),
1199 );
1200
1201 return Effect.gen(function* () {
1202 const error = yield* stageBrowserSecret({
1203 repoRoot: "/repo",
1204 stageResourcesDir: "/stage/resources",
1205 platform: "linux",
1206 arch: "x64",
1207 verbose: false,
1208 }).pipe(Effect.flip);
1209 assert.instanceOf(error, LinuxBrowserSecretHostError);
1210 assert.equal(error.hostPlatform, "darwin");
1211 assert.include(error.message, "Linux host");
1212 assert.lengthOf(commands, 0);
1213 }).pipe(
1214 Effect.provide(
1215 Layer.mergeAll(
1216 spawnerLayer,
1217 Layer.succeed(HostProcess.Platform, "darwin"),
1218 Layer.succeed(HostProcess.Architecture, "arm64"),
1219 ),
1220 ),
1221 );
1222 });
1223
1224 it.effect("skips the primary native probe for cross-architecture Windows payloads", () => {
1225 const commands: Array<{
1226 readonly command: string;
1227 readonly options: {
1228 readonly env?: Readonly<Record<string, string | undefined>>;
1229 };
1230 }> = [];
1231 const spawnerLayer = Layer.succeed(
1232 ChildProcessSpawner.ChildProcessSpawner,
1233 ChildProcessSpawner.make((command) => {
1234 commands.push(command as unknown as (typeof commands)[number]);
1235 return Effect.succeed(mockProcess(0));
1236 }),
1237 );
1238
1239 return Effect.scoped(
1240 Effect.gen(function* () {
1241 const fixture = yield* makeWindowsPayloadFixture({ copyUnpackedNatives: true });
1242 yield* validateWindowsPackagedPayload({
1243 stageDistDir: fixture.stageDistDir,
1244 appExecutableName: fixture.appExecutableName,
1245 targetArch: "arm64",
1246 appVersion: WINDOWS_PAYLOAD_FIXTURE_VERSION,
1247 });
1248
1249 assert.isFalse(
1250 commands.some(
1251 (command) =>
1252 command.command === NodePath.join(fixture.packagedAppDir, fixture.appExecutableName),
1253 ),
1254 );
1255 assert.isTrue(
1256 commands.some(
1257 (command) =>
1258 command.command === process.execPath && command.options.env?.NODE_PATH === "",
1259 ),
1260 );
1261 }),
1262 ).pipe(
1263 Effect.provide(
1264 Layer.mergeAll(
1265 spawnerLayer,
1266 Layer.succeed(HostProcess.Platform, "win32"),
1267 Layer.succeed(HostProcess.Architecture, "x64"),
1268 ),
1269 ),
1270 );
1271 });
1272
1273 it.effect("rejects a cross-architecture Windows payload without its primary executable", () =>
1274 Effect.scoped(
1275 Effect.gen(function* () {
1276 const fs = yield* FileSystem.FileSystem;
1277 const path = yield* Path.Path;
1278 const fixture = yield* makeWindowsPayloadFixture({ copyUnpackedNatives: true });
1279 const executablePath = path.join(fixture.packagedAppDir, fixture.appExecutableName);
1280 yield* fs.remove(executablePath);
1281
1282 const error = yield* validateWindowsPackagedPayload({
1283 stageDistDir: fixture.stageDistDir,
1284 appExecutableName: fixture.appExecutableName,
1285 targetArch: "arm64",
1286 appVersion: WINDOWS_PAYLOAD_FIXTURE_VERSION,
1287 }).pipe(Effect.flip);
1288
1289 assert.instanceOf(error, WindowsPrimaryNativeProbeError);
1290 assert.equal(error.executablePath, executablePath);
1291 }),
1292 ).pipe(
1293 Effect.provide(
1294 Layer.mergeAll(
1295 Layer.succeed(HostProcess.Platform, "win32"),
1296 Layer.succeed(HostProcess.Architecture, "x64"),
1297 ),
1298 ),
1299 ),
1300 );
1301
1302 it.effect("rejects a packaged sidecar whose ASAR-unpacked native is missing", () =>
1303 Effect.scoped(
1304 Effect.gen(function* () {
1305 const fixture = yield* makeWindowsPayloadFixture({ copyUnpackedNatives: false });
1306 const error = yield* validateWindowsPackagedPayload({
1307 stageDistDir: fixture.stageDistDir,
1308 appExecutableName: fixture.appExecutableName,
1309 targetArch: "x64",
1310 appVersion: WINDOWS_PAYLOAD_FIXTURE_VERSION,
1311 }).pipe(Effect.flip);
1312
1313 assert.instanceOf(error, WindowsPackagedPayloadValidationError);
1314 assert.equal(error.reason, "unpacked-native-missing");
1315 assert.deepStrictEqual(error.missingFiles, [
1316 "server.asar.unpacked/node_modules/native/addon.node",
1317 ]);
1318 }),
1319 ),
1320 );
1321
1322 it.effect("rejects directories in place of packaged executable files", () =>
1323 Effect.scoped(
1324 Effect.gen(function* () {
1325 const fs = yield* FileSystem.FileSystem;
1326 const path = yield* Path.Path;
1327 const fixture = yield* makeWindowsPayloadFixture({ copyUnpackedNatives: true });
1328 const nativePath = path.join(
1329 fixture.packagedAppDir,
1330 "resources/server.asar.unpacked/node_modules/native/addon.node",
1331 );
1332 yield* fs.remove(nativePath);
1333 yield* fs.makeDirectory(nativePath);
1334
1335 const nativeError = yield* validateWindowsPackagedPayload({
1336 stageDistDir: fixture.stageDistDir,
1337 appExecutableName: fixture.appExecutableName,
1338 targetArch: "x64",
1339 appVersion: WINDOWS_PAYLOAD_FIXTURE_VERSION,
1340 }).pipe(Effect.flip);
1341 assert.instanceOf(nativeError, WindowsPackagedPayloadValidationError);
1342 assert.equal(nativeError.reason, "unpacked-native-missing");
1343 assert.deepStrictEqual(nativeError.missingFiles, [
1344 "server.asar.unpacked/node_modules/native/addon.node",
1345 ]);
1346
1347 yield* fs.remove(nativePath, { recursive: true });
1348 yield* fs.writeFileString(nativePath, "native-binary");
1349 const resourceMonitorPath = path.join(
1350 fixture.packagedAppDir,
1351 "resources/resource-monitor/t3-resource-monitor.exe",
1352 );
1353 yield* fs.remove(resourceMonitorPath);
1354 yield* fs.makeDirectory(resourceMonitorPath);
1355
1356 const resourceMonitorError = yield* validateWindowsPackagedPayload({
1357 stageDistDir: fixture.stageDistDir,
1358 appExecutableName: fixture.appExecutableName,
1359 targetArch: "x64",
1360 appVersion: WINDOWS_PAYLOAD_FIXTURE_VERSION,
1361 }).pipe(Effect.flip);
1362 assert.instanceOf(resourceMonitorError, WindowsPackagedPayloadValidationError);
1363 assert.equal(resourceMonitorError.reason, "resource-monitor-missing");
1364 assert.deepStrictEqual(resourceMonitorError.missingFiles, [
1365 "resource-monitor/t3-resource-monitor.exe",
1366 ]);
1367 }),
1368 ),
1369 );
1370
1371 it.effect("rejects a Windows payload that regresses above the file-count budget", () =>
1372 Effect.scoped(
1373 Effect.gen(function* () {
1374 const fixture = yield* makeWindowsPayloadFixture({ copyUnpackedNatives: true });
1375 const error = yield* validateWindowsPackagedPayload({
1376 stageDistDir: fixture.stageDistDir,
1377 appExecutableName: fixture.appExecutableName,
1378 targetArch: "x64",
1379 appVersion: WINDOWS_PAYLOAD_FIXTURE_VERSION,
1380 fileLimit: 2,
1381 }).pipe(Effect.flip);
1382
1383 assert.instanceOf(error, WindowsPackagedPayloadValidationError);
1384 assert.equal(error.reason, "file-limit-exceeded");
1385 assert.isAbove(error.fileCount ?? 0, 2);
1386 }),
1387 ),
1388 );
1389
1390 it.effect("rejects a sidecar whose extracted server bundle cannot resolve", () =>
1391 Effect.scoped(
1392 Effect.gen(function* () {
1393 const path = yield* Path.Path;
1394 const fixture = yield* makeWindowsPayloadFixture({
1395 copyUnpackedNatives: true,
1396 serverEntrySource: 'import "t3code-deliberately-missing-package";\n',
1397 });
1398 const error = yield* verifyPackagedBundleIsSelfContained({
1399 asarPath: path.join(fixture.packagedAppDir, "resources", WINDOWS_SERVER_ASAR_RESOURCE),
1400 verbose: false,
1401 }).pipe(Effect.flip);
1402
1403 assert.instanceOf(error, BundleNotSelfContainedError);
1404 assert.include(error.output, "t3code-deliberately-missing-package");
1405 }),
1406 ),
1407 );
1408
1409 it.effect("rejects a macOS app whose packaged server bundle cannot resolve", () =>
1410 Effect.scoped(
1411 Effect.gen(function* () {
1412 const fixture = yield* makePackagedAppFixture({
1413 serverEntrySource: 'import "t3code-deliberately-missing-package";\n',
1414 });
1415 const error = yield* validateMacPackagedPayload({
1416 stageDistDir: fixture.stageDistDir,
1417 }).pipe(Effect.flip);
1418
1419 assert.instanceOf(error, BundleNotSelfContainedError);
1420 assert.include(error.output, "t3code-deliberately-missing-package");
1421 }),
1422 ),
1423 );
1424
1425 it.effect("accepts a macOS app whose packaged server bundle resolves", () =>
1426 Effect.scoped(
1427 Effect.gen(function* () {
1428 const fixture = yield* makePackagedAppFixture({});
1429 yield* validateMacPackagedPayload({ stageDistDir: fixture.stageDistDir });
1430 }),
1431 ),
1432 );
1433
1434 it.effect("never runs an untrusted macOS bundle", () =>
1435 Effect.scoped(
1436 Effect.gen(function* () {
1437 const fs = yield* FileSystem.FileSystem;
1438 const path = yield* Path.Path;
1439 const marker = path.join(yield* fs.makeTempDirectoryScoped(), "ran");
1440 const fixture = yield* makePackagedAppFixture({
1441 serverEntrySource: `import { writeFileSync } from "node:fs";\nwriteFileSync(${JSON.stringify(marker)}, "");\n`,
1442 });
1443 yield* validateMacPackagedPayload({ stageDistDir: fixture.stageDistDir });
1444 assert.isFalse(yield* fs.exists(marker));
1445 }),
1446 ).pipe(
1447 Effect.provide(
1448 ConfigProvider.layer(
1449 ConfigProvider.fromEnv({ env: { T3CODE_DESKTOP_UNTRUSTED_BUNDLE: "true" } }),
1450 ),
1451 ),
1452 ),
1453 );
1454
1455 it.effect("packages the macOS preview's PR bundle as untrusted", () =>
1456 Effect.gen(function* () {
1457 const fs = yield* FileSystem.FileSystem;
1458 const path = yield* Path.Path;
1459 const workflow = yield* fs.readFileString(
1460 yield* path.fromFileUrl(
1461 new URL("../.github/workflows/desktop-macos-preview-publish.yml", import.meta.url),
1462 ),
1463 );
1464 const { jobs } = yield* Schema.decodeEffect(
1465 fromYaml(
1466 Schema.Struct({
1467 jobs: Schema.Record(
1468 Schema.String,
1469 Schema.Struct({
1470 uses: Schema.optional(Schema.String),
1471 with: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
1472 }),
1473 ),
1474 }),
1475 ),
1476 )(workflow);
1477 const packaging = Object.values(jobs).filter(
1478 (job) => job.uses === "./.github/workflows/release-desktop.yml",
1479 );
1480 assert.isNotEmpty(packaging);
1481 for (const job of packaging) assert.strictEqual(job.with?.untrusted_bundle, true);
1482 }),
1483 );
1484
1485 it.effect("rejects a macOS stage without a packaged app", () =>
1486 Effect.scoped(
1487 Effect.gen(function* () {
1488 const fs = yield* FileSystem.FileSystem;
1489 const stageDistDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-mac-payload-test-" });
1490 const error = yield* validateMacPackagedPayload({ stageDistDir }).pipe(Effect.flip);
1491
1492 assert.instanceOf(error, MacPackagedAppMissingError);
1493 }),
1494 ),
1495 );
1496
1497 it.effect("rejects a macOS app without app.asar", () =>
1498 Effect.scoped(
1499 Effect.gen(function* () {
1500 const fs = yield* FileSystem.FileSystem;
1501 const stageDistDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-mac-payload-test-" });
1502 yield* fs.makeDirectory(`${stageDistDir}/mac-arm64/T3 Code.app/Contents/Resources`, {
1503 recursive: true,
1504 });
1505 const error = yield* validateMacPackagedPayload({ stageDistDir }).pipe(Effect.flip);
1506
1507 assert.instanceOf(error, BundleNotSelfContainedError);
1508 }),
1509 ),
1510 );
1511
1512 it.effect("rejects a Linux app whose packaged server bundle cannot resolve", () =>
1513 Effect.scoped(
1514 Effect.gen(function* () {
1515 const fs = yield* FileSystem.FileSystem;
1516 const fixture = yield* makePackagedAppFixture({
1517 resourcesPath: "linux-arm64-unpacked/resources",
1518 serverEntrySource: 'import "t3code-deliberately-missing-package";\n',
1519 });
1520 const error = yield* validateLinuxPackagedPayload({
1521 stageDistDir: fixture.stageDistDir,
1522 }).pipe(Effect.flip);
1523 assert.instanceOf(error, BundleNotSelfContainedError);
1524 assert.include(error.output, "t3code-deliberately-missing-package");
1525
1526 const emptyStage = yield* fs.makeTempDirectoryScoped({ prefix: "t3-linux-payload-test-" });
1527 const missing = yield* validateLinuxPackagedPayload({ stageDistDir: emptyStage }).pipe(
1528 Effect.flip,
1529 );
1530 assert.instanceOf(missing, LinuxPackagedAppMissingError);
1531 }),
1532 ),
1533 );
1534
1535 it.effect("leaves the bundle self-check of a cross-built payload to the verify job", () =>
1536 Effect.scoped(
1537 Effect.gen(function* () {
1538 const fixture = yield* makeWindowsPayloadFixture({
1539 copyUnpackedNatives: true,
1540 serverEntrySource: 'import "t3code-deliberately-missing-package";\n',
1541 });
1542 yield* validateWindowsPackagedPayload({
1543 stageDistDir: fixture.stageDistDir,
1544 appExecutableName: fixture.appExecutableName,
1545 targetArch: "arm64",
1546 appVersion: WINDOWS_PAYLOAD_FIXTURE_VERSION,
1547 });
1548 }),
1549 ).pipe(
1550 Effect.provide(
1551 Layer.mergeAll(
1552 Layer.succeed(HostProcess.Platform, "linux"),
1553 Layer.succeed(HostProcess.Architecture, "x64"),
1554 ),
1555 ),
1556 ),
1557 );
1558
1559 it("derives macOS passkey signing configuration from the Clerk publishable key", () => {
1560 const configuration = resolveMacPasskeySigningConfiguration({
1561 T3CODE_APPLE_TEAM_ID: "abc1234567",
1562 T3CODE_MACOS_PROVISIONING_PROFILE: "/tmp/t3code.provisionprofile",
1563 T3CODE_CLERK_PUBLISHABLE_KEY: `pk_test_${btoa("example.clerk.accounts.dev$")}`,
1564 });
1565
1566 assert.deepStrictEqual(configuration, {
1567 appId: "com.t3tools.t3code",
1568 teamId: "ABC1234567",
1569 rpDomains: ["example.clerk.accounts.dev"],
1570 provisioningProfilePath: "/tmp/t3code.provisionprofile",
1571 });
1572 });
1573
1574 it("normalizes explicit macOS passkey RP domains and renders required entitlements", () => {
1575 const configuration = resolveMacPasskeySigningConfiguration({
1576 T3CODE_APPLE_TEAM_ID: "ABC1234567",
1577 T3CODE_MACOS_PROVISIONING_PROFILE: "/tmp/t3code.provisionprofile",
1578 T3CODE_CLERK_PASSKEY_RP_DOMAINS:
1579 " Clerk.Example.com,example.clerk.accounts.dev,clerk.example.com ",
1580 });
1581 const entitlements = renderMacPasskeyEntitlements(configuration, {
1582 touchIdKeychainAccessGroup: undefined,
1583 browserPasskeys: false,
1584 });
1585
1586 assert.deepStrictEqual(configuration.rpDomains, [
1587 "clerk.example.com",
1588 "example.clerk.accounts.dev",
1589 ]);
1590 assert.include(entitlements, "<string>ABC1234567.com.t3tools.t3code</string>");
1591 assert.include(entitlements, "<string>webcredentials:clerk.example.com</string>");
1592 assert.include(entitlements, "<string>webcredentials:example.clerk.accounts.dev</string>");
1593 assert.include(entitlements, "<key>com.apple.security.cs.allow-jit</key>");
1594 assert.match(entitlements, /<key>com\.apple\.security\.device\.camera<\/key>\s*<true\/>/u);
1595 assert.match(entitlements, /<key>com\.apple\.security\.device\.audio-input<\/key>\s*<true\/>/u);
1596 assert.notInclude(entitlements, "keychain-access-groups");
1597 assert.notInclude(entitlements, "com.apple.developer.web-browser.public-key-credential");
1598 });
1599
1600 it("grants in-app browser passkey entitlements only when the provisioning profile does", () => {
1601 const configuration = { appId: "com.t3tools.t3code", teamId: "ABC1234567" };
1602 const profile = (entitlements: string, outside = "") =>
1603 `0\x82\x1f\x9a\x06\t*\x86H<?xml version="1.0"?><plist version="1.0"><dict>${outside}<key>Entitlements</key><dict>${entitlements}</dict></dict></plist>\x00\x01`;
1604 const teamWildcardGroups = `<key>keychain-access-groups</key>
1605 <array>
1606 <string>ABC1234567.*</string>
1607 <string>com.apple.token</string>
1608 </array>`;
1609
1610 assert.deepStrictEqual(resolveMacWebAuthnEntitlements(profile(""), configuration), {
1611 touchIdKeychainAccessGroup: undefined,
1612 browserPasskeys: false,
1613 });
1614 assert.deepStrictEqual(
1615 resolveMacWebAuthnEntitlements(
1616 profile("<key>keychain-access-groups</key><array><string>OTHERTEAM1.*</string></array>"),
1617 configuration,
1618 ),
1619 { touchIdKeychainAccessGroup: undefined, browserPasskeys: false },
1620 );
1621 assert.deepStrictEqual(
1622 resolveMacWebAuthnEntitlements(
1623 profile(
1624 `<!-- ${teamWildcardGroups}
1625 <key>com.apple.developer.web-browser.public-key-credential</key><true/> -->
1626 <key>com.apple.developer.web-browser.public-key-credential</key><false/>`,
1627 teamWildcardGroups,
1628 ),
1629 configuration,
1630 ),
1631 { touchIdKeychainAccessGroup: undefined, browserPasskeys: false },
1632 );
1633 assert.deepStrictEqual(
1634 resolveMacWebAuthnEntitlements(
1635 profile(
1636 `${teamWildcardGroups}
1637 <key>com.apple.developer.web-browser.public-key-credential</key>
1638 <true/>`,
1639 ),
1640 configuration,
1641 ),
1642 {
1643 touchIdKeychainAccessGroup: "ABC1234567.com.t3tools.t3code.webauthn",
1644 browserPasskeys: true,
1645 },
1646 );
1647
1648 const entitlements = renderMacPasskeyEntitlements(
1649 { ...configuration, rpDomains: ["clerk.example.com"], provisioningProfilePath: "" },
1650 resolveMacWebAuthnEntitlements(
1651 profile(
1652 `${teamWildcardGroups}<key>com.apple.developer.web-browser.public-key-credential</key><true/>`,
1653 ),
1654 configuration,
1655 ),
1656 );
1657 assert.match(
1658 entitlements,
1659 /<key>keychain-access-groups<\/key>\s*<array>\s*<string>ABC1234567\.com\.t3tools\.t3code\.webauthn<\/string>\s*<\/array>/u,
1660 );
1661 assert.match(
1662 entitlements,
1663 /<key>com\.apple\.developer\.web-browser\.public-key-credential<\/key>\s*<true\/>/u,
1664 );
1665 });
1666
1667 it("rejects incomplete macOS passkey signing configuration", () => {
1668 const captureError = (env: Readonly<Record<string, string | undefined>>) => {
1669 try {
1670 resolveMacPasskeySigningConfiguration(env);
1671 } catch (error) {
1672 return error;
1673 }
1674 return assert.fail("Expected passkey signing configuration to fail.");
1675 };
1676
1677 const missingProfileError = captureError({
1678 T3CODE_APPLE_TEAM_ID: "ABC1234567",
1679 T3CODE_CLERK_PASSKEY_RP_DOMAINS: "example.clerk.accounts.dev",
1680 });
1681 assert.instanceOf(missingProfileError, MissingMacPasskeyProvisioningProfileError);
1682 assert.equal(
1683 missingProfileError.message,
1684 "T3CODE_MACOS_PROVISIONING_PROFILE must point to an Associated Domains provisioning profile.",
1685 );
1686
1687 const unsafeDomain =
1688 "https://domain-user:domain-secret@example.clerk.accounts.dev/path?token=query-secret";
1689 const invalidDomainError = captureError({
1690 T3CODE_APPLE_TEAM_ID: "ABC1234567",
1691 T3CODE_MACOS_PROVISIONING_PROFILE: "/tmp/t3code.provisionprofile",
1692 T3CODE_CLERK_PASSKEY_RP_DOMAINS: unsafeDomain,
1693 });
1694 assert.instanceOf(invalidDomainError, InvalidMacPasskeyRpDomainError);
1695 assert.equal(invalidDomainError.reason, "scheme-not-allowed");
1696 assert.equal(invalidDomainError.inputLength, unsafeDomain.length);
1697 assert.equal(invalidDomainError.message, "Invalid passkey RP domain (scheme-not-allowed).");
1698 assert.notProperty(invalidDomainError, "domain");
1699 assert.notProperty(invalidDomainError, "cause");
1700 const serializedInvalidDomainError = JSON.stringify(invalidDomainError);
1701 assert.notInclude(serializedInvalidDomainError, unsafeDomain);
1702 assert.notInclude(serializedInvalidDomainError, "domain-user");
1703 assert.notInclude(serializedInvalidDomainError, "domain-secret");
1704 assert.notInclude(serializedInvalidDomainError, "query-secret");
1705 assert.throws(
1706 () =>
1707 resolveMacPasskeySigningConfiguration({
1708 T3CODE_APPLE_TEAM_ID: "ABC1234567",
1709 T3CODE_MACOS_PROVISIONING_PROFILE: "/tmp/t3code.provisionprofile",
1710 T3CODE_CLERK_PASSKEY_RP_DOMAINS: "example.clerk.accounts.dev:8443",
1711 }),
1712 /Invalid passkey RP domain/u,
1713 );
1714 const invalidPublishableKeyError = captureError({
1715 T3CODE_APPLE_TEAM_ID: "ABC1234567",
1716 T3CODE_MACOS_PROVISIONING_PROFILE: "/tmp/t3code.provisionprofile",
1717 T3CODE_CLERK_PUBLISHABLE_KEY: "pk_test_%",
1718 });
1719 assert.instanceOf(invalidPublishableKeyError, InvalidMacPasskeyPublishableKeyError);
1720 assert.ok(invalidPublishableKeyError.cause);
1721 assert.equal(invalidPublishableKeyError.message, "T3CODE_CLERK_PUBLISHABLE_KEY is invalid.");
1722 assert.notProperty(invalidPublishableKeyError, "publishableKey");
1723 assert.notInclude(invalidPublishableKeyError.message, "pk_test_%");
1724 });
1725
1726 it("wraps unknown passkey signing configuration defects without copying cause text", () => {
1727 const secret = "pk_test_do-not-retain";
1728 const cause = new Error(secret);
1729 const error = MacPasskeySigningConfigurationResolutionError.fromCause(cause);
1730
1731 assert.instanceOf(error, MacPasskeySigningConfigurationResolutionError);
1732 assert.strictEqual(error.cause, cause);
1733 assert.equal(error.message, "Failed to resolve macOS passkey signing configuration.");
1734 assert.notInclude(error.message, secret);
1735 });
1736
1737 it.effect("signs Windows builds with signtool on Windows and the jsign hook elsewhere", () =>
1738 Effect.gen(function* () {
1739 const signedWinConfig = (hostPlatform: string) =>
1740 createBuildConfig("win", "nsis", "1.2.3", true, false, undefined, undefined).pipe(
1741 Effect.map((config) => config.win as Record<string, unknown>),
1742 Effect.provideService(HostProcess.Platform, hostPlatform),
1743 );
1744
1745 const onWindows = yield* signedWinConfig("win32");
1746 assert.equal((onWindows.azureSignOptions as Record<string, unknown>).publisherName, "T3");
1747 assert.notProperty(onWindows, "signtoolOptions");
1748
1749 const onLinux = yield* signedWinConfig("linux");
1750 assert.notProperty(onLinux, "azureSignOptions");
1751 const signtoolOptions = onLinux.signtoolOptions as Record<string, unknown>;
1752 assert.match(signtoolOptions.sign as string, /scripts[\\/]lib[\\/]windows-jsign\.ts$/);
1753 assert.deepStrictEqual(signtoolOptions.signingHashAlgorithms, ["sha256"]);
1754 assert.deepStrictEqual(signtoolOptions.publisherName, ["T3"]);
1755 }).pipe(
1756 Effect.provide(
1757 ConfigProvider.layer(
1758 ConfigProvider.fromEnv({
1759 env: {
1760 AZURE_TRUSTED_SIGNING_PUBLISHER_NAME: "T3",
1761 AZURE_TRUSTED_SIGNING_ENDPOINT: "https://eus.codesigning.azure.net/",
1762 AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME: "profile",
1763 AZURE_TRUSTED_SIGNING_ACCOUNT_NAME: "account",
1764 },
1765 }),
1766 ),
1767 ),
1768 ),
1769 );
1770
1771 it("parses Windows bsdtar member listings with CRLF line endings", () => {
1772 assert.deepStrictEqual(
1773 parseWslRuntimeArchiveMembers("./t3-1.2.3-linux-x64/t3\r\nt3-1.2.3-linux-x64/client/\r\n"),
1774 ["t3-1.2.3-linux-x64/t3", "t3-1.2.3-linux-x64/client"],
1775 );
1776 });
1777
1778 it.effect("stages the Linux CLI archive verbatim with its SHA-256 sidecar", () =>
1779 Effect.scoped(
1780 Effect.gen(function* () {
1781 const fs = yield* FileSystem.FileSystem;
1782 const path = yield* Path.Path;
1783 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-wsl-runtime-stage-" });
1784 const sourceArchivePath = yield* makeLinuxCliArchiveFixture({
1785 root,
1786 stem: "t3-1.2.3-linux-x64",
1787 });
1788 const stageAppDir = path.join(root, "app");
1789 const archivePath = path.join(stageAppDir, WSL_RUNTIME_ARCHIVE_EXTRA_RESOURCE.from);
1790 const hashPath = path.join(stageAppDir, WSL_RUNTIME_ARCHIVE_HASH_EXTRA_RESOURCE.from);
1791
1792 yield* stageWslRuntimeArchive({ sourceArchivePath, archivePath, hashPath });
1793
1794 const [source, staged] = yield* Effect.all([
1795 fs.readFile(sourceArchivePath),
1796 fs.readFile(archivePath),
1797 ]);
1798 assert.deepStrictEqual(staged, source);
1799 const hash = yield* fs.readFileString(hashPath);
1800 assert.equal(hash, `${NodeCrypto.createHash("sha256").update(source).digest("hex")}\n`);
1801 }),
1802 ),
1803 );
1804
1805 it.effect("rejects universal builds on Linux and Windows before staging binaries", () =>
1806 Effect.gen(function* () {
1807 for (const platform of ["linux", "win"] as const) {
1808 const error = yield* Effect.flip(
1809 resolveBuildOptions({
1810 platform: Option.some(platform),
1811 target: Option.none(),
1812 arch: Option.some("universal"),
1813 buildVersion: Option.none(),
1814 outputDir: Option.none(),
1815 skipBuild: Option.none(),
1816 keepStage: Option.none(),
1817 signed: Option.none(),
1818 verbose: Option.none(),
1819 mockUpdates: Option.none(),
1820 mockUpdateServerPort: Option.none(),
1821 wslRuntime: Option.none(),
1822 }),
1823 );
1824
1825 assert.instanceOf(error, UnsupportedDesktopBuildArchitectureError);
1826 assert.deepStrictEqual(error.supportedArchitectures, ["x64", "arm64"]);
1827 }
1828 }),
1829 );
1830
1831 it.effect("preserves explicit false boolean flags over true env defaults", () =>
1832 Effect.gen(function* () {
1833 const resolved = yield* resolveBuildOptions({
1834 platform: Option.some("mac"),
1835 target: Option.none(),
1836 arch: Option.some("arm64"),
1837 buildVersion: Option.none(),
1838 outputDir: Option.some("release-test"),
1839 skipBuild: Option.some(false),
1840 keepStage: Option.some(false),
1841 signed: Option.some(false),
1842 verbose: Option.some(false),
1843 mockUpdates: Option.some(false),
1844 mockUpdateServerPort: Option.none(),
1845 wslRuntime: Option.none(),
1846 }).pipe(
1847 Effect.provide(
1848 ConfigProvider.layer(
1849 ConfigProvider.fromEnv({
1850 env: {
1851 T3CODE_DESKTOP_SKIP_BUILD: "true",
1852 T3CODE_DESKTOP_KEEP_STAGE: "true",
1853 T3CODE_DESKTOP_SIGNED: "true",
1854 T3CODE_DESKTOP_VERBOSE: "true",
1855 T3CODE_DESKTOP_MOCK_UPDATES: "true",
1856 },
1857 }),
1858 ),
1859 ),
1860 );
1861
1862 assert.equal(resolved.skipBuild, false);
1863 assert.equal(resolved.keepStage, false);
1864 assert.equal(resolved.signed, false);
1865 assert.equal(resolved.verbose, false);
1866 assert.equal(resolved.mockUpdates, false);
1867 }),
1868 );
1869 });
1870
1871 it("keeps the prefix of a UNC path instead of going relative", () => {
1872 const paths = ancestorNodeModulesPaths("\\\\server\\share\\tmp\\app", "\\");
1873 for (const candidate of paths) {
1874 assert.ok(candidate.startsWith("\\\\server\\share"), candidate);
1875 }
1876 assert.deepStrictEqual(paths[0], "\\\\server\\share\\tmp\\node_modules");
1877 });
1878
1879 it.effect.skipIf(!symlinksSupported)("rebases packaged links into the isolated tree", () =>
1880 Effect.gen(function* () {
1881 const fs = yield* FileSystem.FileSystem;
1882 const path = yield* Path.Path;
1883 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-copy-symlinks-" });
1884 const source = path.join(root, "source");
1885 const destination = path.join(root, "destination");
1886 const packageDir = path.join(source, "node_modules/.pnpm/example@1/node_modules/example");
1887 const relativePackageLink = path.join(source, "node_modules/example-relative");
1888 const absolutePackageLink = path.join(source, "node_modules/example-absolute");
1889
1890 yield* fs.makeDirectory(packageDir, { recursive: true });
1891 yield* fs.writeFileString(path.join(packageDir, "index.js"), "module.exports = true;\n");
1892 yield* fs.symlink(
1893 path.join(".pnpm", "example@1", "node_modules", "example"),
1894 relativePackageLink,
1895 );
1896 yield* fs.symlink(packageDir, absolutePackageLink);
1897
1898 yield* copyDirectoryPreservingSymlinks(source, destination);
1899
1900 const copiedPackage = path.join(
1901 destination,
1902 "node_modules/.pnpm/example@1/node_modules/example",
1903 );
1904 const resolvedCopiedPackage = yield* fs.realPath(copiedPackage);
1905 assert.equal(
1906 yield* fs.readLink(path.join(destination, "node_modules/example-relative")),
1907 copiedPackage,
1908 );
1909 assert.equal(
1910 yield* fs.readLink(path.join(destination, "node_modules/example-absolute")),
1911 copiedPackage,
1912 );
1913 assert.equal(
1914 yield* fs.realPath(path.join(destination, "node_modules/example-relative")),
1915 resolvedCopiedPackage,
1916 );
1917 assert.equal(
1918 yield* fs.realPath(path.join(destination, "node_modules/example-absolute")),
1919 resolvedCopiedPackage,
1920 );
1921 }).pipe(Effect.provide(NodeServices.layer)),
1922 );
1923
1924 it.effect("preserves packaged app directories from the dir target", () =>
1925 Effect.gen(function* () {
1926 const fs = yield* FileSystem.FileSystem;
1927 const path = yield* Path.Path;
1928 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-dir-artifact-" });
1929 const stage = path.join(root, "stage");
1930 const output = path.join(root, "output");
1931 const app = path.join("mac-arm64", "T3 Code.app", "Contents");
1932 yield* fs.makeDirectory(path.join(stage, app), { recursive: true });
1933 yield* fs.writeFileString(path.join(stage, app, "Info.plist"), "built-app");
1934 yield* fs.writeFileString(path.join(stage, "builder-debug.yml"), "debug");
1935 const copied = yield* copyDesktopBuildArtifacts(stage, output, true);
1936 assert.include(copied, path.join(output, "mac-arm64"));
1937 assert.equal(yield* fs.readFileString(path.join(output, app, "Info.plist")), "built-app");
1938 assert.equal(yield* fs.readFileString(path.join(stage, app, "Info.plist")), "built-app");
1939 yield* fs.remove(path.join(stage, app, "Info.plist"));
1940 yield* fs.writeFileString(path.join(stage, app, "New.plist"), "rebuilt-app");
1941 yield* copyDesktopBuildArtifacts(stage, output, true);
1942 assert.isFalse(yield* fs.exists(path.join(output, app, "Info.plist")));
1943 assert.equal(yield* fs.readFileString(path.join(output, app, "New.plist")), "rebuilt-app");
1944 const filesOnly = yield* copyDesktopBuildArtifacts(stage, path.join(root, "files-only"));
1945 assert.deepEqual(filesOnly, [path.join(root, "files-only", "builder-debug.yml")]);
1946 assert.isFalse(yield* fs.exists(path.join(root, "files-only", "mac-arm64")));
1947 yield* fs.remove(path.join(stage, "mac-arm64"), { recursive: true });
1948 yield* fs.writeFileString(path.join(stage, "mac-arm64"), "flattened");
1949 yield* copyDesktopBuildArtifacts(stage, output, true);
1950 assert.equal(yield* fs.readFileString(path.join(output, "mac-arm64")), "flattened");
1951 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
1952 );
1953
1954 it.effect.skipIf(!symlinksSupported)("preserves relative links when replacing dir artifacts", () =>
1955 Effect.gen(function* () {
1956 const fs = yield* FileSystem.FileSystem;
1957 const path = yield* Path.Path;
1958 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-dir-artifact-links-" });
1959 const stage = path.join(root, "stage");
1960 const output = path.join(root, "output");
1961 const app = path.join("mac-arm64", "T3 Code.app", "Contents");
1962 yield* fs.makeDirectory(path.join(stage, app), { recursive: true });
1963 yield* fs.writeFileString(path.join(stage, app, "Info.plist"), "built-app");
1964 yield* fs.symlink("Info.plist", path.join(stage, app, "Current"));
1965 yield* copyDesktopBuildArtifacts(stage, output, true);
1966 assert.equal(yield* fs.readLink(path.join(output, app, "Current")), "Info.plist");
1967 assert.equal(yield* fs.readFileString(path.join(output, app, "Current")), "built-app");
1968
1969 yield* fs.remove(path.join(stage, app, "Current"));
1970 yield* fs.writeFileString(path.join(stage, app, "New.plist"), "rebuilt-app");
1971 yield* fs.symlink("New.plist", path.join(stage, app, "Current"));
1972 yield* copyDesktopBuildArtifacts(stage, output, true);
1973 assert.equal(yield* fs.readLink(path.join(output, app, "Current")), "New.plist");
1974 assert.equal(yield* fs.readFileString(path.join(output, app, "Current")), "rebuilt-app");
1975 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
1976 );