@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, 04:45 UTC

main
ts 264 lines 8.93 KB
Raw
1 import { expect } from "bun:test";
2 /**
3 * The example, end to end: a user signs up with Better Auth, creates a
4 * repository through the app's API, mints an API key, and pushes with it.
5 * A second user can read the public repository but cannot push to it, and
6 * an unknown key is anonymous. Run with `bun test` from this directory.
7 */
8 import * as Cloudflare from "@alchemy.run/cloudflare";
9 import * as Test from "@alchemy.run/test/Bun";
10 import * as Effect from "effect/Effect";
11 import * as FileSystem from "effect/FileSystem";
12 import * as Path from "effect/Path";
13 import * as Schedule from "effect/Schedule";
14 import Stack from "../alchemy.run.ts";
15
16 const { test, beforeAll, afterAll, deploy, destroy } = Test.make({
17 providers: Cloudflare.providers(),
18 state: Cloudflare.state(),
19 stage: "test",
20 });
21
22 const stack = beforeAll(deploy(Stack), { timeout: 600_000 });
23
24 afterAll.skipIf(!!process.env.NO_DESTROY)(destroy(Stack), {
25 timeout: 600_000,
26 });
27
28 interface JsonResponse {
29 readonly status: number;
30 readonly json: any;
31 readonly cookie: string;
32 }
33
34 /** A JSON request that carries and captures the session cookie. */
35 const call = (
36 url: string,
37 path: string,
38 options: {
39 readonly method?: string;
40 readonly body?: unknown;
41 readonly cookie?: string;
42 } = {},
43 ) =>
44 Effect.tryPromise(async (signal): Promise<JsonResponse> => {
45 const response = await fetch(`${url}${path}`, {
46 method: options.method ?? (options.body === undefined ? "GET" : "POST"),
47 signal,
48 headers: {
49 // Browsers send Origin on every request; Better Auth requires it on
50 // cookie-authenticated writes (CSRF).
51 origin: url,
52 ...(options.body !== undefined ? { "content-type": "application/json" } : {}),
53 ...(options.cookie ? { cookie: options.cookie } : {}),
54 },
55 body: options.body !== undefined ? JSON.stringify(options.body) : undefined,
56 });
57 const text = await response.text();
58 let json: unknown = null;
59 try {
60 json = text.length === 0 ? null : JSON.parse(text);
61 } catch {
62 json = text;
63 }
64 const cookie = response.headers
65 .getSetCookie()
66 .map((c) => c.split(";")[0]!)
67 .join("; ");
68 return {
69 status: response.status,
70 json,
71 cookie: cookie || (options.cookie ?? ""),
72 };
73 }).pipe(
74 // A fresh workers.dev rollout may answer before the request reaches the app.
75 // Retry only Cloudflare's own missing-route response, including for POSTs.
76 Effect.repeat({
77 while: (response) =>
78 typeof response.json === "string" &&
79 ((response.status === 404 && response.json.includes("<title>Page not found</title>")) ||
80 response.json.trim() === "error code: 1042"),
81 schedule: Schedule.spaced("2 seconds"),
82 times: 5,
83 }),
84 );
85
86 /** Sign a user up (or in, when the account survived a NO_DESTROY run) and return the session cookie. */
87 const signIn = Effect.fn(function* (
88 url: string,
89 user: { name: string; email: string; password: string },
90 ) {
91 const up = yield* call(url, "/api/auth/sign-up/email", { body: user });
92 const session =
93 up.status === 200
94 ? up
95 : yield* call(url, "/api/auth/sign-in/email", {
96 body: { email: user.email, password: user.password },
97 });
98 expect(session.status).toBe(200);
99 // Owner names are lowercased by the host; a Better Auth id is mixed-case.
100 return {
101 cookie: session.cookie,
102 id: (session.json.user.id as string).toLowerCase(),
103 };
104 });
105
106 class GitError extends Error {
107 constructor(
108 readonly args: string[],
109 readonly code: number,
110 readonly stderr: string,
111 ) {
112 super(`git ${args.join(" ")} exited ${code}: ${stderr}`);
113 }
114 }
115
116 /** Run git with a hermetic identity; fails with the exit code and stderr. */
117 const git = (cwd: string, ...args: string[]) =>
118 Effect.tryPromise({
119 try: async () => {
120 const proc = Bun.spawn(["git", ...args], {
121 cwd,
122 stdout: "pipe",
123 stderr: "pipe",
124 env: {
125 ...process.env,
126 GIT_TERMINAL_PROMPT: "0",
127 GIT_CONFIG_NOSYSTEM: "1",
128 GIT_TRACE_CURL: process.env.GIT_TRACE_CURL ?? "",
129 GIT_AUTHOR_NAME: "integ",
130 GIT_AUTHOR_EMAIL: "integ@example.com",
131 GIT_COMMITTER_NAME: "integ",
132 GIT_COMMITTER_EMAIL: "integ@example.com",
133 },
134 });
135 const [stdout, stderr, code] = await Promise.all([
136 new Response(proc.stdout).text(),
137 new Response(proc.stderr).text(),
138 proc.exited,
139 ]);
140 if (code !== 0) throw new GitError(args, code, stderr);
141 return stdout;
142 },
143 catch: (cause) => (cause instanceof GitError ? cause : new GitError(args, -1, String(cause))),
144 });
145
146 const remoteWith = (url: string, key: string, owner: string, name: string) =>
147 url.replace("://", `://x:${key}@`) + `/${owner}/${name}.git`;
148
149 test(
150 "sign up, create a repository, push with an API key; a stranger reads but cannot push",
151 Effect.gen(function* () {
152 const { webUrl } = yield* stack;
153 const url = webUrl.replace(/\/+$/, "");
154 const fs = yield* FileSystem.FileSystem;
155 const path = yield* Path.Path;
156
157 // The front door forwards /api/** to the host; wait for it to answer
158 // (anonymous listing is the middleware's 401).
159 yield* call(url, "/api/v1/repos").pipe(
160 Effect.filterOrFail(
161 (r) => r.status === 200 || r.status === 401,
162 () => new Error("not ready"),
163 ),
164 Effect.retry({ schedule: Schedule.spaced("2 seconds"), times: 60 }),
165 );
166
167 const owner = yield* signIn(url, {
168 name: "Dana",
169 email: "dana@example.com",
170 password: "correct-horse-battery",
171 });
172
173 // Create a public repository under the owner's id. A previous run
174 // (NO_DESTROY) may have left one: delete it and wait for the purge.
175 const name = "web";
176 yield* call(url, `/api/v1/repos/${owner.id}/${name}`, {
177 method: "DELETE",
178 cookie: owner.cookie,
179 });
180 yield* call(url, `/api/v1/repos/${owner.id}/${name}`, {
181 cookie: owner.cookie,
182 }).pipe(
183 Effect.filterOrFail(
184 (r) => r.status === 404,
185 () => new Error("draining"),
186 ),
187 Effect.retry({ schedule: Schedule.spaced("2 seconds"), times: 60 }),
188 );
189 const created = yield* call(url, "/api/v1/repos", {
190 body: { owner: owner.id, name, public: true },
191 cookie: owner.cookie,
192 });
193 expect(created.status).toBe(200);
194 expect(created.json.repo.owner).toBe(owner.id);
195
196 // Mint an API key: the password of the git remote.
197 const minted = yield* call(url, "/api/auth/api-key/create", {
198 body: { name: "laptop" },
199 cookie: owner.cookie,
200 });
201 expect(minted.status, JSON.stringify(minted.json)).toBe(200);
202 const key: string = minted.json.key;
203 expect(key.length).toBeGreaterThan(10);
204
205 // Push with it.
206 const tmp = yield* fs.makeTempDirectory({ prefix: "git-example-" });
207 const work = path.join(tmp, "work");
208 yield* fs.makeDirectory(work);
209 yield* git(work, "init", "-q", "-b", "main");
210 yield* fs.writeFileString(path.join(work, "README.md"), "# hello\n");
211 yield* git(work, "add", "-A");
212 yield* git(work, "commit", "-qm", "first");
213 yield* git(work, "push", "-q", remoteWith(url, key, owner.id, name), "main");
214
215 // The owner's session sees the branch through the API.
216 const refs = yield* call(url, `/api/v1/repos/${owner.id}/${name}/refs`, {
217 cookie: owner.cookie,
218 });
219 expect(refs.status).toBe(200);
220 expect(refs.json.refs.some((r: { name: string }) => r.name === "refs/heads/main")).toBe(true);
221
222 // Anonymous clone of a public repository needs no credential.
223 const anon = path.join(tmp, "anon");
224 yield* git(tmp, "clone", "-q", `${url}/${owner.id}/${name}.git`, "anon");
225 yield* git(anon, "fsck", "--strict");
226
227 // A stranger: reads, cannot push.
228 const stranger = yield* signIn(url, {
229 name: "Alex",
230 email: "alex@example.com",
231 password: "correct-horse-battery",
232 });
233 const strangerKey = yield* call(url, "/api/auth/api-key/create", {
234 body: { name: "laptop" },
235 cookie: stranger.cookie,
236 });
237 yield* fs.writeFileString(path.join(anon, "README.md"), "# nope\n");
238 yield* git(anon, "commit", "-qam", "nope");
239 const denied = yield* git(
240 anon,
241 "push",
242 "-q",
243 remoteWith(url, strangerKey.json.key, owner.id, name),
244 "main",
245 ).pipe(Effect.result);
246 expect(denied._tag).toBe("Failure");
247
248 // An unknown key is anonymous: the private setting turns reads off too.
249 yield* call(url, `/api/v1/repos/${owner.id}/${name}`, {
250 method: "PATCH",
251 body: { public: false },
252 cookie: owner.cookie,
253 });
254 const hidden = yield* call(url, `/api/v1/repos/${owner.id}/${name}`);
255 expect(hidden.status).toBe(401);
256 // A private repository answers 401 to anyone but its owner, signed
257 // in or not, so its existence is not confirmed.
258 const strangerRead = yield* call(url, `/api/v1/repos/${owner.id}/${name}`, {
259 cookie: stranger.cookie,
260 });
261 expect(strangerRead.status).toBe(401);
262 }),
263 { timeout: 300_000 },
264 );