Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

server-runtime-smoke.ts

211 lines7.4 KB

1// @effect-diagnostics nodeBuiltinImport:off
2// @effect-diagnostics globalTimers:off -- Plain Node script; the ready deadline and kill escalation are wall-clock timers.
3import * as NodeChildProcess from "node:child_process";
4import * as NodeFS from "node:fs";
5import * as NodeHttp from "node:http";
6import * as NodeNet from "node:net";
7import * as NodeOS from "node:os";
8import * as NodePath from "node:path";
9import * as NodeURL from "node:url";
10import * as NodeZlib from "node:zlib";
11import * as Console from "effect/Console";
12import * as Effect from "effect/Effect";
13import * as Schema from "effect/Schema";
14​
15// Runs the built CLI under Bun and checks the headers Effect attaches through
16// its pre-response handler. The in-process suite runs on Node and cannot see a
17// bundle that loads a second `effect` under Bun, causing the affected CORS,
18// compression, and pairing-cookie mutations to be omitted (#8878, #7756).
19​
20const distDir = NodePath.resolve(
21 NodePath.dirname(NodeURL.fileURLToPath(import.meta.url)),
22 "../apps/server/dist",
23);
24type Response = { status: number; headers: NodeHttp.IncomingHttpHeaders; body: Buffer };
25const decodeSession = Schema.decodeUnknownSync(
26 Schema.fromJsonString(
27 Schema.Struct({
28 authenticated: Schema.Boolean,
29 auth: Schema.Struct({ sessionCookieName: Schema.NonEmptyString }),
30 }),
31 ),
32);
33const decodeAuthenticated = Schema.decodeUnknownSync(
34 Schema.fromJsonString(Schema.Struct({ authenticated: Schema.Boolean })),
35);
36​
37const freePort = (): Promise<number> =>
38 new Promise((resolve, reject) => {
39 const probe = NodeNet.createServer().listen(0, "127.0.0.1", () => {
40 const address = probe.address();
41 if (address === null || typeof address === "string") {
42 probe.close();
43 reject(new Error("Could not allocate a TCP port."));
44 return;
45 }
46 probe.close((error) => (error ? reject(error) : resolve(address.port)));
47 });
48 probe.once("error", reject);
49 });
50​
51const request = (
52 port: number,
53 method: string,
54 path: string,
55 headers: Record<string, string>,
56 body?: string,
57) =>
58 new Promise<Response>((resolve, reject) => {
59 const client = NodeHttp.request(
60 { host: "127.0.0.1", port, method, path, headers, agent: false },
61 (response) => {
62 const chunks: Array<Buffer> = [];
63 response.on("data", (chunk: Buffer) => chunks.push(chunk));
64 response.on("end", () =>
65 resolve({
66 status: response.statusCode ?? 0,
67 headers: response.headers,
68 body: Buffer.concat(chunks),
69 }),
70 );
71 },
72 );
73 client.on("response", (response) => response.on("error", reject));
74 client.on("error", reject);
75 client.setTimeout(5_000, () => client.destroy(new Error(`${path} timed out.`)));
76 client.end(body);
77 });
78​
79const expectHeader = (response: Response, name: string, expected: string, what: string) => {
80 if (response.status !== 200 || response.headers[name] !== expected) {
81 throw new Error(
82 `${what}: expected 200 with ${name} "${expected}", got ${response.status} with ${JSON.stringify(response.headers[name] ?? null)}.`,
83 );
84 }
85};
86​
87const env = Object.fromEntries(
88 Object.entries(process.env).filter(
89 ([key]) =>
90 key !== "VITE_DEV_SERVER_URL" &&
91 key !== "T3_SERVICE_LAUNCHER_CONTEXT" &&
92 !key.startsWith("T3CODE_"),
93 ),
94);
95const port = await freePort();
96const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-bun-smoke-"));
97const args = [
98 "serve",
99 "--mode",
100 "web",
101 "--host",
102 "127.0.0.1",
103 "--port",
104 String(port),
105 "--base-dir",
106 baseDir,
107 "--no-browser",
108];
109const child = NodeChildProcess.spawn("bun", [NodePath.join(distDir, "bin.mjs"), ...args], {
110 cwd: distDir,
111 env,
112 stdio: ["ignore", "pipe", "pipe"],
113});
114const exited = new Promise<void>((resolve) => {
115 child.once("exit", () => resolve());
116 child.once("error", () => resolve());
117});
118let stdout = "";
119let stderr = "";
120child.stdout.on("data", (chunk: Buffer) => (stdout += chunk.toString()));
121child.stderr.on("data", (chunk: Buffer) => (stderr += chunk.toString()));
122try {
123 const token = await new Promise<string>((resolve, reject) => {
124 const deadline = setTimeout(
125 () => reject(new Error("Server was not ready within 60 seconds.")),
126 60_000,
127 );
128 child.once("error", (error) => {
129 clearTimeout(deadline);
130 reject(error);
131 });
132 child.once("exit", (code, signal) => {
133 clearTimeout(deadline);
134 reject(new Error(`Server exited early (${code ?? signal}).`));
135 });
136 child.stdout.on("data", () => {
137 const match = /^Token: (\S+)$/mu.exec(stdout);
138 if (match?.[1] && stdout.includes("T3 Code server is ready.")) {
139 clearTimeout(deadline);
140 resolve(match[1]);
141 }
142 });
143 });
144 const descriptor = await request(port, "GET", "/.well-known/t3/environment", {
145 origin: "https://app.t3.codes",
146 });
147 expectHeader(
148 descriptor,
149 "access-control-allow-origin",
150 "*",
151 "CORS on the environment descriptor",
152 );
153 const session = await request(port, "GET", "/api/auth/session", {});
154 const sessionBody = decodeSession(session.body.toString());
155 const { sessionCookieName } = sessionBody.auth;
156 if (session.status !== 200 || sessionBody.authenticated) {
157 throw new Error("Expected an unauthenticated session before pairing.");
158 }
159 const compressed = await request(port, "GET", "/", { "accept-encoding": "gzip" });
160 expectHeader(compressed, "content-encoding", "gzip", "Compression on the web client");
161 const uncompressed = await request(port, "GET", "/", {});
162 if (
163 uncompressed.status !== 200 ||
164 !NodeZlib.gunzipSync(compressed.body).equals(uncompressed.body)
165 ) {
166 throw new Error("Gzip response did not decode to the web client.");
167 }
168 const pairing = await request(
169 port,
170 "POST",
171 "/api/auth/browser-session",
172 { "content-type": "application/json" },
173 JSON.stringify({ credential: token }),
174 );
175 const cookies = ([] as Array<string>).concat(pairing.headers["set-cookie"] ?? []);
176 const authenticated =
177 pairing.status === 200 && decodeAuthenticated(pairing.body.toString()).authenticated;
178 if (!authenticated || !cookies.some((cookie) => cookie.startsWith(`${sessionCookieName}=`))) {
179 throw new Error(
180 `Pairing: expected 200, authenticated: true, and a session cookie; got ${pairing.status}.`,
181 );
182 }
183 const replay = await request(port, "GET", "/api/auth/session", {
184 cookie: cookies.map((cookie) => cookie.split(";")[0]).join("; "),
185 });
186 if (replay.status !== 200 || !decodeAuthenticated(replay.body.toString()).authenticated) {
187 throw new Error("The pairing cookie did not authenticate a subsequent request.");
188 }
189 Effect.runSync(
190 Console.log("Bun runtime smoke passed: CORS, compression, and the pairing cookie are present."),
191 );
192} catch (error) {
193 const tail = stderr.split("\n").slice(-20).join("\n");
194 // Startup failures are logged to stdout; stop before the credential/QR output.
195 const startup = stdout.split("T3 Code server is ready.")[0]?.split("\n").slice(-20).join("\n");
196 Effect.runSync(
197 Console.error(
198 `${error instanceof Error ? error.message : String(error)}\n--- server startup ---\n${startup}\n--- server stderr ---\n${tail}`,
199 ),
200 );
201 process.exitCode = 1;
202} finally {
203 if (child.exitCode === null && child.signalCode === null) {
204 const forceKill = setTimeout(() => child.kill("SIGKILL"), 5_000);
205 forceKill.unref();
206 child.kill("SIGTERM");
207 await exited;
208 clearTimeout(forceKill);
209 }
210 NodeFS.rmSync(baseDir, { recursive: true, force: true });