|
| 1 | +import { describe, it, expect, beforeEach, afterAll, vi } from "vitest"; |
| 2 | +import request from "supertest"; |
| 3 | +import { |
| 4 | + meFixtures, |
| 5 | + type MeFixtureCase, |
| 6 | + type MeResponse, |
| 7 | +} from "@sergeant/shared"; |
| 8 | + |
| 9 | +/** |
| 10 | + * Producer-side contract test for `GET /api/me` / `GET /api/v1/me`. |
| 11 | + * |
| 12 | + * **Goal:** prove that the route's response builder, given a typical |
| 13 | + * Better Auth session-user shape, emits the same wire JSON as the |
| 14 | + * canonical fixtures in `@sergeant/shared/contract-fixtures/me`. The |
| 15 | + * matching consumer test lives in |
| 16 | + * `apps/web/src/test/contract/me.contract.test.ts`. |
| 17 | + * |
| 18 | + * Together these two files form the minimum viable contract: |
| 19 | + * |
| 20 | + * server-user-row → route serializer → fixture |
| 21 | + * fixture → api-client → typed UI value |
| 22 | + * |
| 23 | + * If the schema gets a new required field, BOTH tests must update — |
| 24 | + * consumer test fails on missing field in the fixture, producer test |
| 25 | + * fails on missing field in the response. |
| 26 | + * |
| 27 | + * Closes diagnostic §7.4 (`docs/diagnostics/2026-05-03-web-deep-dive/04-security-observability-testing-devx.md`). |
| 28 | + */ |
| 29 | + |
| 30 | +const { mockPool, queryMock, getSessionUserMock } = vi.hoisted(() => { |
| 31 | + const queryMock = vi.fn().mockResolvedValue({ rows: [{ "?column?": 1 }] }); |
| 32 | + const mockPool = { |
| 33 | + query: queryMock, |
| 34 | + connect: vi.fn(), |
| 35 | + on: vi.fn(), |
| 36 | + totalCount: 0, |
| 37 | + idleCount: 0, |
| 38 | + waitingCount: 0, |
| 39 | + }; |
| 40 | + const getSessionUserMock = vi.fn().mockResolvedValue(null); |
| 41 | + return { mockPool, queryMock, getSessionUserMock }; |
| 42 | +}); |
| 43 | + |
| 44 | +vi.mock("./../db.js", () => ({ |
| 45 | + default: mockPool, |
| 46 | + pool: mockPool, |
| 47 | + query: queryMock, |
| 48 | + ensureSchema: vi.fn().mockResolvedValue(undefined), |
| 49 | +})); |
| 50 | + |
| 51 | +vi.mock("./../auth.js", () => ({ |
| 52 | + auth: { handler: async () => new Response(null, { status: 404 }) }, |
| 53 | + getSessionUser: getSessionUserMock, |
| 54 | + getSessionUserSoft: vi.fn().mockResolvedValue(null), |
| 55 | +})); |
| 56 | + |
| 57 | +import { createApp } from "./../app.js"; |
| 58 | + |
| 59 | +const ENV_KEYS = ["VAPID_PUBLIC_KEY", "VAPID_PRIVATE_KEY", "VAPID_EMAIL"]; |
| 60 | +const savedEnv: Record<string, string | undefined> = {}; |
| 61 | +for (const k of ENV_KEYS) savedEnv[k] = process.env[k]; |
| 62 | + |
| 63 | +beforeEach(() => { |
| 64 | + queryMock.mockReset(); |
| 65 | + queryMock.mockResolvedValue({ rows: [{ "?column?": 1 }] }); |
| 66 | + getSessionUserMock.mockReset(); |
| 67 | + getSessionUserMock.mockResolvedValue(null); |
| 68 | + for (const k of ENV_KEYS) delete process.env[k]; |
| 69 | +}); |
| 70 | + |
| 71 | +afterAll(() => { |
| 72 | + for (const k of ENV_KEYS) { |
| 73 | + if (savedEnv[k] === undefined) delete process.env[k]; |
| 74 | + else process.env[k] = savedEnv[k]; |
| 75 | + } |
| 76 | +}); |
| 77 | + |
| 78 | +/** |
| 79 | + * Translate a contract fixture into the shape Better Auth's |
| 80 | + * `getSessionUser()` would return for the same user. The route's job is |
| 81 | + * to flatten that into the canonical fixture; this helper is what the |
| 82 | + * test feeds the auth mock. |
| 83 | + * |
| 84 | + * `createdAt` from Better Auth comes as a `Date` (or sometimes a |
| 85 | + * stringified ISO when the adapter has already serialised it). We |
| 86 | + * exercise both paths: numbered fixtures alternate between Date and |
| 87 | + * string. |
| 88 | + */ |
| 89 | +function authedUserFromFixture( |
| 90 | + fixture: MeResponse, |
| 91 | + variant: "date" | "string" | "missing", |
| 92 | +): Record<string, unknown> { |
| 93 | + const { user } = fixture; |
| 94 | + const base: Record<string, unknown> = { |
| 95 | + id: user.id, |
| 96 | + email: user.email, |
| 97 | + name: user.name, |
| 98 | + image: user.image, |
| 99 | + emailVerified: user.emailVerified, |
| 100 | + }; |
| 101 | + if (variant === "missing" || user.createdAt === null) { |
| 102 | + return base; |
| 103 | + } |
| 104 | + if (variant === "string") { |
| 105 | + base.createdAt = user.createdAt; |
| 106 | + } else { |
| 107 | + base.createdAt = new Date(user.createdAt); |
| 108 | + } |
| 109 | + return base; |
| 110 | +} |
| 111 | + |
| 112 | +const NAMES: readonly MeFixtureCase[] = [ |
| 113 | + "minimal", |
| 114 | + "full", |
| 115 | + "legacyNoCreatedAt", |
| 116 | + "unverified", |
| 117 | +] as const; |
| 118 | + |
| 119 | +describe("contract producer: GET /api/v1/me", () => { |
| 120 | + it.each(NAMES)( |
| 121 | + "fixture %s — Date `createdAt` round-trips through the route", |
| 122 | + async (name) => { |
| 123 | + const fixture = meFixtures[name]; |
| 124 | + const authed = authedUserFromFixture(fixture, "date"); |
| 125 | + getSessionUserMock.mockResolvedValueOnce(authed); |
| 126 | + |
| 127 | + const app = createApp(); |
| 128 | + const res = await request(app) |
| 129 | + .get("/api/v1/me") |
| 130 | + .set("Authorization", "Bearer contract-stub"); |
| 131 | + |
| 132 | + expect(res.status).toBe(200); |
| 133 | + expect(res.body).toEqual(fixture); |
| 134 | + }, |
| 135 | + ); |
| 136 | + |
| 137 | + it.each(NAMES)( |
| 138 | + "fixture %s — string `createdAt` round-trips through the route", |
| 139 | + async (name) => { |
| 140 | + const fixture = meFixtures[name]; |
| 141 | + const authed = authedUserFromFixture(fixture, "string"); |
| 142 | + getSessionUserMock.mockResolvedValueOnce(authed); |
| 143 | + |
| 144 | + const app = createApp(); |
| 145 | + const res = await request(app) |
| 146 | + .get("/api/v1/me") |
| 147 | + .set("Authorization", "Bearer contract-stub"); |
| 148 | + |
| 149 | + expect(res.status).toBe(200); |
| 150 | + expect(res.body).toEqual(fixture); |
| 151 | + }, |
| 152 | + ); |
| 153 | + |
| 154 | + it("legacyNoCreatedAt — missing field on the auth user → null on the wire", async () => { |
| 155 | + // Older accounts may not have `createdAt` at all in the auth row. |
| 156 | + // The route normalises this to `null`, matching the |
| 157 | + // `legacyNoCreatedAt` fixture exactly. |
| 158 | + const fixture = meFixtures.legacyNoCreatedAt; |
| 159 | + const authed = authedUserFromFixture(fixture, "missing"); |
| 160 | + getSessionUserMock.mockResolvedValueOnce(authed); |
| 161 | + |
| 162 | + const app = createApp(); |
| 163 | + const res = await request(app) |
| 164 | + .get("/api/v1/me") |
| 165 | + .set("Authorization", "Bearer contract-stub"); |
| 166 | + |
| 167 | + expect(res.status).toBe(200); |
| 168 | + expect(res.body).toEqual(fixture); |
| 169 | + expect(res.body.user.createdAt).toBeNull(); |
| 170 | + }); |
| 171 | + |
| 172 | + it("response is byte-stable between /api/me and /api/v1/me for the same fixture", async () => { |
| 173 | + // Hard Rule: legacy and v1 prefixes must emit IDENTICAL bodies. If |
| 174 | + // they ever diverge, downstream code split between the two paths |
| 175 | + // would silently misbehave. |
| 176 | + const fixture = meFixtures.full; |
| 177 | + const authed = authedUserFromFixture(fixture, "date"); |
| 178 | + getSessionUserMock.mockResolvedValue(authed); |
| 179 | + |
| 180 | + const app = createApp(); |
| 181 | + const legacy = await request(app) |
| 182 | + .get("/api/me") |
| 183 | + .set("Authorization", "Bearer x"); |
| 184 | + const v1 = await request(app) |
| 185 | + .get("/api/v1/me") |
| 186 | + .set("Authorization", "Bearer x"); |
| 187 | + |
| 188 | + expect(legacy.status).toBe(200); |
| 189 | + expect(v1.status).toBe(200); |
| 190 | + expect(v1.body).toEqual(legacy.body); |
| 191 | + expect(v1.body).toEqual(fixture); |
| 192 | + }); |
| 193 | +}); |
0 commit comments