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

main
ts 184 lines 6.43 KB
Raw
1 import { describe, expect, it } from "@alchemy.run/test";
2 import { RuntimeContext } from "alchemy";
3 import { APIError } from "better-auth/api";
4 import { anonymous } from "better-auth/plugins/anonymous";
5 import * as Effect from "effect/Effect";
6 import * as HttpServerRequest from "effect/http/HttpServerRequest";
7 import * as HttpServerResponse from "effect/http/HttpServerResponse";
8 import {
9 BetterAuth,
10 BetterAuthApiError,
11 isAPIErrorLike,
12 Memory,
13 mergeAPIErrorHeaders,
14 } from "@/index.ts";
15
16 const baseOptions = {
17 baseURL: "http://localhost:3000",
18 emailAndPassword: { enabled: true },
19 secret: "test-secret-test-secret-test-secret",
20 } as const;
21
22 /** Serve one web Request through the instance's `fetch` HttpEffect. */
23 const serve = (
24 fetch: Effect.Effect<
25 HttpServerResponse.HttpServerResponse,
26 unknown,
27 RuntimeContext | HttpServerRequest.HttpServerRequest | import("effect/Scope").Scope
28 >,
29 request: Request,
30 ) =>
31 fetch.pipe(
32 Effect.provideService(HttpServerRequest.HttpServerRequest, HttpServerRequest.fromWeb(request)),
33 Effect.flatMap((response) => Effect.sync(() => HttpServerResponse.toWeb(response))),
34 Effect.orDie,
35 );
36
37 const provideTestEnv = <A, E, R>(
38 effect: Effect.Effect<A, E, R>,
39 ): Effect.Effect<A, E, Exclude<R, RuntimeContext>> =>
40 effect.pipe(Effect.provide(RuntimeContext.phantom)) as Effect.Effect<
41 A,
42 E,
43 Exclude<R, RuntimeContext>
44 >;
45
46 describe("BetterAuth (memory)", { tags: ["unit", "local"] }, () => {
47 it.live("signs up, signs in over HTTP, reads the session", () =>
48 Effect.gen(function* () {
49 const auth = yield* BetterAuth({
50 ...baseOptions,
51 basePath: "/auth",
52 });
53
54 // sign up through the effectified api proxy
55 const signUp = yield* auth.api.signUpEmail({
56 body: {
57 email: "user@example.com",
58 password: "password1234",
59 name: "Test User",
60 },
61 });
62 expect(signUp.user.email).toBe("user@example.com");
63
64 // sign in over the HTTP surface to capture the session cookie
65 const signInResponse = yield* serve(
66 auth.fetch,
67 new Request("http://localhost:3000/auth/sign-in/email", {
68 method: "POST",
69 headers: {
70 "content-type": "application/json",
71 "x-forwarded-for": "192.0.2.1",
72 },
73 body: JSON.stringify({
74 email: "user@example.com",
75 password: "password1234",
76 }),
77 }),
78 );
79 expect(signInResponse.status).toBe(200);
80 const setCookies = signInResponse.headers.getSetCookie();
81 expect(setCookies.length).toBeGreaterThan(0);
82 const cookie = setCookies.map((c) => c.split(";")[0]).join("; ");
83
84 // read the session back with explicit headers
85 const session = yield* auth.getSession(new Headers({ cookie }));
86 expect(session).not.toBeNull();
87 expect(session!.user.email).toBe("user@example.com");
88
89 // and via the ambient request overload
90 const ambient = yield* auth.getSession().pipe(
91 Effect.provideService(
92 HttpServerRequest.HttpServerRequest,
93 HttpServerRequest.fromWeb(
94 new Request("http://localhost:3000/anything", {
95 headers: { cookie },
96 }),
97 ),
98 ),
99 );
100 expect(ambient?.user.email).toBe("user@example.com");
101 }).pipe(Effect.provide(Memory()), provideTestEnv),
102 );
103
104 it.live("maps APIError to BetterAuthApiError with typed fields", () =>
105 Effect.gen(function* () {
106 const auth = yield* BetterAuth(baseOptions);
107 yield* auth.api.signUpEmail({
108 body: {
109 email: "wrong-pass@example.com",
110 password: "password1234",
111 name: "Wrong Pass",
112 },
113 });
114 const error = yield* auth.api
115 .signInEmail({
116 body: {
117 email: "wrong-pass@example.com",
118 password: "not-the-password",
119 },
120 })
121 .pipe(Effect.flip);
122 expect(error).toBeInstanceOf(BetterAuthApiError);
123 expect(error._tag).toBe("BetterAuthApiError");
124 expect(error.statusCode).toBe(401);
125 expect(error.status).toBe("UNAUTHORIZED");
126 expect(error.body?.code).toBeDefined();
127 expect(error.headers).toBeInstanceOf(Headers);
128 }).pipe(Effect.provide(Memory()), provideTestEnv),
129 );
130
131 it.live("plugin endpoints surface on the typed api proxy", () =>
132 Effect.gen(function* () {
133 const auth = yield* BetterAuth({
134 ...baseOptions,
135 plugins: [anonymous()],
136 });
137 // `signInAnonymous` only exists because the anonymous() plugin is in
138 // the options — this call type-checks AND runs through the proxy.
139 const result = yield* auth.api.signInAnonymous({});
140 expect(result?.user.isAnonymous).toBe(true);
141 }).pipe(Effect.provide(Memory()), provideTestEnv),
142 );
143
144 it("api proxy is not a thenable and caches wrappers", () => {
145 const program = Effect.gen(function* () {
146 const auth = yield* BetterAuth(baseOptions);
147 const api = auth.api as Record<string, unknown>;
148 expect(api.then).toBeUndefined();
149 expect(api.getSession).toBe(api.getSession);
150 expect(typeof api.getSession).toBe("function");
151 }).pipe(Effect.provide(Memory()), provideTestEnv, Effect.scoped);
152 return Effect.runPromise(program as Effect.Effect<void>);
153 });
154
155 it("mergeAPIErrorHeaders preserves symbol-carried set-cookie headers", () => {
156 const error = new APIError(
157 "UNAUTHORIZED",
158 { message: "nope", code: "INVALID_EMAIL_OR_PASSWORD" },
159 { "x-visible": "yes" },
160 );
161 const hidden = new Headers();
162 hidden.append("set-cookie", "a=1; Path=/");
163 hidden.append("set-cookie", "b=2; Path=/");
164 hidden.set("x-hidden", "also");
165 (error as unknown as Record<symbol, unknown>)[Symbol.for("better-call:api-error-headers")] =
166 hidden;
167
168 expect(isAPIErrorLike(error)).toBe(true);
169 const merged = mergeAPIErrorHeaders(error);
170 expect(merged.get("x-visible")).toBe("yes");
171 expect(merged.get("x-hidden")).toBe("also");
172 expect(merged.getSetCookie()).toEqual(["a=1; Path=/", "b=2; Path=/"]);
173
174 const wrapped = BetterAuthApiError.fromAPIError(error);
175 expect(wrapped.statusCode).toBe(401);
176 expect(wrapped.headers.getSetCookie()).toEqual(["a=1; Path=/", "b=2; Path=/"]);
177 });
178
179 it("isAPIErrorLike rejects non-APIError values", () => {
180 expect(isAPIErrorLike(new Error("plain"))).toBe(false);
181 expect(isAPIErrorLike({ name: "APIError", statusCode: 401 })).toBe(false);
182 expect(isAPIErrorLike(null)).toBe(false);
183 });
184 });