@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 253 lines 9.95 KB
Raw
1 import { describe, expect, it } from "@alchemy.run/test";
2 import * as BunFileSystem from "@effect/platform-bun/BunFileSystem";
3 import { AlchemyContext, RuntimeContext } from "alchemy";
4 import { organization } from "better-auth/plugins/organization";
5 import * as Effect from "effect/Effect";
6 import * as FileSystem from "effect/FileSystem";
7 import * as Result from "effect/Result";
8 import { BetterAuth, BetterAuthMigrationError, Database } from "@/index.ts";
9 import { applyMigrations, schemaFingerprint } from "@/Migrate.ts";
10 import { SQLite } from "@/SQLite.ts";
11
12 const baseOptions = {
13 baseURL: "http://localhost:3000",
14 emailAndPassword: { enabled: true },
15 secret: "test-secret-test-secret-test-secret",
16 } as const;
17
18 const provideTestEnv = <A, E, R>(
19 effect: Effect.Effect<A, E, R>,
20 ): Effect.Effect<A, E, Exclude<R, RuntimeContext | FileSystem.FileSystem>> =>
21 effect.pipe(
22 Effect.provide(BunFileSystem.layer),
23 Effect.provide(RuntimeContext.phantom),
24 ) as Effect.Effect<A, E, Exclude<R, RuntimeContext | FileSystem.FileSystem>>;
25
26 const tempSqlitePath = Effect.gen(function* () {
27 const fs = yield* FileSystem.FileSystem;
28 const dir = yield* fs.makeTempDirectory({ prefix: "better-auth-sqlite" });
29 return `${dir}/auth.sqlite`;
30 });
31
32 describe("BetterAuth (bun:sqlite)", { tags: ["unit", "local"] }, () => {
33 it.live("uses the configured runtime directory unless a filename is supplied", () =>
34 Effect.gen(function* () {
35 const fs = yield* FileSystem.FileSystem;
36 const root = yield* fs.makeTempDirectoryScoped();
37 yield* Effect.gen(function* () {
38 for (const filename of [undefined, `${root}/explicit.sqlite`]) {
39 const expected = filename ?? `${root}/better-auth.sqlite`;
40 const db = yield* Database.pipe(Effect.provide(SQLite(filename)));
41 yield* applyMigrations(db.migrate!, baseOptions);
42 expect(yield* fs.exists(expected)).toBe(true);
43 }
44 }).pipe(
45 Effect.provideService(AlchemyContext, { dotAlchemy: root, dev: false, adopt: false }),
46 );
47 }).pipe(Effect.scoped, provideTestEnv),
48 );
49
50 it.live("applies schema migrations idempotently", () =>
51 Effect.gen(function* () {
52 const path = yield* tempSqlitePath;
53 const db = yield* Database.pipe(Effect.provide(SQLite(path)));
54 expect(db.migrate).toBeDefined();
55
56 const first = yield* applyMigrations(db.migrate!, baseOptions);
57 expect(first.tablesCreated).toBeGreaterThan(0);
58
59 // re-running against an up-to-date database is a no-op
60 const second = yield* applyMigrations(db.migrate!, baseOptions);
61 expect(second.tablesCreated).toBe(0);
62 expect(second.tablesAltered).toBe(0);
63 expect(second.indexesCreated).toBe(0);
64
65 // verify the core tables actually exist in the file
66 const { Database: BunSqlite } = yield* Effect.promise(() => import("bun:sqlite"));
67 const raw = new BunSqlite(path);
68 const tables = (
69 raw.query("SELECT name FROM sqlite_master WHERE type = 'table'").all() as { name: string }[]
70 ).map((row) => row.name);
71 raw.close();
72 for (const table of ["user", "session", "account", "verification"]) {
73 expect(tables).toContain(table);
74 }
75 }).pipe(provideTestEnv),
76 );
77
78 it.live("runs the full auth flow against the migrated database", () =>
79 Effect.gen(function* () {
80 const path = yield* tempSqlitePath;
81 const layer = SQLite(path);
82 const db = yield* Database.pipe(Effect.provide(layer));
83 yield* applyMigrations(db.migrate!, baseOptions);
84
85 const auth = yield* BetterAuth(baseOptions).pipe(
86 // layer is path-parameterized per test — provided here rather than
87 // on the outer test effect
88 Effect.provide(layer),
89 );
90 const signUp = yield* auth.api.signUpEmail({
91 body: { email: "sqlite@example.com", password: "password1234", name: "SQLite User" },
92 });
93 expect(signUp.user.email).toBe("sqlite@example.com");
94
95 const signIn = yield* auth.api.signInEmail({
96 body: { email: "sqlite@example.com", password: "password1234" },
97 });
98 expect(signIn.user.email).toBe("sqlite@example.com");
99 expect(signIn.token).toBeDefined();
100
101 const session = yield* auth.api.getSession({
102 headers: new Headers({ authorization: `Bearer ${signIn.token}` }),
103 });
104 // sqlite persisted the user — a fresh read sees it
105 expect(signUp.user.id).toBeDefined();
106 void session;
107 }).pipe(provideTestEnv),
108 );
109
110 it.live("upgrades a populated 1.6 database without rewriting account identities", () =>
111 Effect.gen(function* () {
112 const path = yield* tempSqlitePath;
113 const { Database: BunSqlite } = yield* Effect.promise(() => import("bun:sqlite"));
114 const { betterAuth: betterAuth16 } = yield* Effect.promise(() => import("better-auth-1.6"));
115 const { getMigrations } = yield* Effect.promise(() => import("better-auth-1.6/db/migration"));
116 const legacy = yield* Effect.gen(function* () {
117 const database = yield* Effect.acquireRelease(
118 Effect.sync(() => new BunSqlite(path)),
119 (database) => Effect.sync(() => database.close()),
120 );
121 const migrations = yield* Effect.promise(() => getMigrations({ ...baseOptions, database }));
122 yield* Effect.promise(() => migrations.runMigrations());
123 const auth = yield* Effect.sync(() => betterAuth16({ ...baseOptions, database }));
124 const user = yield* Effect.promise(() =>
125 auth.api.signUpEmail({
126 body: {
127 email: "existing@example.com",
128 password: "password1234",
129 name: "Existing User",
130 },
131 }),
132 );
133 const signIn = yield* Effect.promise(() =>
134 auth.api.signInEmail({
135 body: { email: "existing@example.com", password: "password1234" },
136 asResponse: true,
137 }),
138 );
139 const accounts = yield* Effect.sync(() =>
140 database
141 .query("SELECT id, accountId, providerId, userId, password FROM account ORDER BY id")
142 .all(),
143 );
144 return {
145 userId: user.user.id,
146 accounts,
147 cookie: signIn.headers
148 .getSetCookie()
149 .map((cookie) => cookie.split(";")[0])
150 .join("; "),
151 };
152 }).pipe(Effect.scoped);
153
154 const layer = SQLite(path);
155 const database = yield* Database.pipe(Effect.provide(layer));
156 yield* applyMigrations(database.migrate!, baseOptions);
157 const auth = yield* BetterAuth(baseOptions).pipe(Effect.provide(layer));
158 const session = yield* auth.api.getSession({
159 headers: new Headers({ cookie: legacy.cookie }),
160 });
161 expect(session?.user.id).toBe(legacy.userId);
162 const signIn = yield* auth.api.signInEmail({
163 body: { email: "existing@example.com", password: "password1234" },
164 });
165 expect(signIn.user.id).toBe(legacy.userId);
166
167 yield* Effect.gen(function* () {
168 const raw = yield* Effect.acquireRelease(
169 Effect.sync(() => new BunSqlite(path)),
170 (raw) => Effect.sync(() => raw.close()),
171 );
172 const accounts = yield* Effect.sync(() =>
173 raw
174 .query("SELECT id, accountId, providerId, userId, password FROM account ORDER BY id")
175 .all(),
176 );
177 expect(accounts).toEqual(legacy.accounts);
178 const columns = yield* Effect.sync(() =>
179 raw.query<{ name: string }, []>("PRAGMA table_info(account)").all(),
180 );
181 expect(columns.map((column) => column.name)).not.toContain("issuer");
182 }).pipe(Effect.scoped);
183
184 const signUp = yield* auth.api.signUpEmail({
185 body: { email: "new@example.com", password: "password1234", name: "New User" },
186 });
187 expect(signUp.user.id).not.toBe(legacy.userId);
188 expect(yield* applyMigrations(database.migrate!, baseOptions)).toEqual({
189 tablesCreated: 0,
190 tablesAltered: 0,
191 indexesCreated: 0,
192 });
193 }).pipe(provideTestEnv),
194 );
195
196 it.live("reports unsafe populated-table changes as migration errors", () =>
197 Effect.gen(function* () {
198 const path = yield* tempSqlitePath;
199 const layer = SQLite(path);
200 const database = yield* Database.pipe(Effect.provide(layer));
201 yield* applyMigrations(database.migrate!, baseOptions);
202 const auth = yield* BetterAuth(baseOptions).pipe(Effect.provide(layer));
203 yield* auth.api.signUpEmail({
204 body: { email: "unsafe@example.com", password: "password1234", name: "Existing User" },
205 });
206 const result = yield* Effect.result(
207 applyMigrations(database.migrate!, {
208 ...baseOptions,
209 user: { additionalFields: { team: { type: "string", required: true } } },
210 }),
211 );
212 expect(Result.isFailure(result)).toBe(true);
213 if (Result.isFailure(result)) {
214 expect(result.failure).toBeInstanceOf(BetterAuthMigrationError);
215 expect(result.failure.message).toContain("team");
216 }
217 }).pipe(provideTestEnv),
218 );
219
220 it.live("schema fingerprint changes when only a table index changes", () =>
221 Effect.gen(function* () {
222 const withIndex = (unique: boolean) => ({
223 ...baseOptions,
224 plugins: [
225 {
226 id: "account-index",
227 schema: {
228 account: {
229 fields: {},
230 indexes: [
231 { name: "provider_account", fields: ["providerId", "accountId"], unique },
232 ],
233 },
234 },
235 },
236 ],
237 });
238 expect(yield* schemaFingerprint(withIndex(false))).not.toBe(
239 yield* schemaFingerprint(withIndex(true)),
240 );
241 }).pipe(provideTestEnv),
242 );
243
244 it.live("schema fingerprint is stable and plugin-sensitive", () =>
245 Effect.gen(function* () {
246 const a = yield* schemaFingerprint(baseOptions);
247 const b = yield* schemaFingerprint(baseOptions);
248 expect(a).toBe(b);
249 const withPlugin = yield* schemaFingerprint({ ...baseOptions, plugins: [organization()] });
250 expect(withPlugin).not.toBe(a);
251 }).pipe(provideTestEnv),
252 );
253 });