| 1 | import { expect, test } from "bun:test"; |
| 2 | |
| 3 | const baseURL = process.env.BETTER_AUTH_TEST_URL; |
| 4 | |
| 5 | test.skipIf(!baseURL)( |
| 6 | "same-origin authentication lifecycle", |
| 7 | async () => { |
| 8 | const origin = new URL(baseURL!).origin; |
| 9 | const cookies = new Map<string, string>(); |
| 10 | const request = async (path: string, body?: object) => { |
| 11 | const response = await fetch(new URL(path, origin), { |
| 12 | method: body ? "POST" : "GET", |
| 13 | headers: { |
| 14 | origin, |
| 15 | "content-type": "application/json", |
| 16 | cookie: [...cookies] |
| 17 | .map(([name, value]) => `${name}=${value}`) |
| 18 | .join("; "), |
| 19 | }, |
| 20 | body: body ? JSON.stringify(body) : undefined, |
| 21 | signal: AbortSignal.timeout(10_000), |
| 22 | }); |
| 23 | for (const cookie of response.headers.getSetCookie()) { |
| 24 | const pair = cookie.split(";", 1)[0]!; |
| 25 | const separator = pair.indexOf("="); |
| 26 | cookies.set(pair.slice(0, separator), pair.slice(separator + 1)); |
| 27 | } |
| 28 | return response; |
| 29 | }; |
| 30 | |
| 31 | expect(await (await request("/api/health")).json()).toEqual({ ok: true }); |
| 32 | expect((await request("/")).status).toBe(200); |
| 33 | expect((await request("/ui.js")).status).toBe(200); |
| 34 | expect((await request("/api/providers")).status).toBe(200); |
| 35 | expect((await request("/api/auth-not-a-route")).status).toBe(404); |
| 36 | expect((await request("/api/me")).status).toBe(401); |
| 37 | |
| 38 | const user = { |
| 39 | name: "Local Example User", |
| 40 | email: `example-${crypto.randomUUID()}@example.com`, |
| 41 | password: "local-example-password-123", |
| 42 | }; |
| 43 | const signup = await request("/api/auth/sign-up/email", user); |
| 44 | expect(signup.status).toBe(200); |
| 45 | expect(cookies.size).toBeGreaterThan(0); |
| 46 | const me = await request("/api/me"); |
| 47 | expect(me.status).toBe(200); |
| 48 | expect(await me.json()).toMatchObject({ |
| 49 | name: user.name, |
| 50 | email: user.email, |
| 51 | }); |
| 52 | const session = await request("/api/auth/get-session"); |
| 53 | expect(session.status).toBe(200); |
| 54 | expect(await session.json()).toMatchObject({ user: { email: user.email } }); |
| 55 | |
| 56 | expect((await request("/api/auth/sign-out", {})).status).toBe(200); |
| 57 | expect((await request("/api/me")).status).toBe(401); |
| 58 | expect(await (await request("/api/auth/get-session")).json()).toBeNull(); |
| 59 | expect((await request("/api/health")).status).toBe(200); |
| 60 | |
| 61 | expect((await request("/api/auth/sign-in/email", user)).status).toBe(200); |
| 62 | expect((await request("/api/me")).status).toBe(200); |
| 63 | expect((await request("/api/auth/sign-out", {})).status).toBe(200); |
| 64 | expect((await request("/api/me")).status).toBe(401); |
| 65 | }, |
| 66 | 45_000, |
| 67 | ); |