-
Notifications
You must be signed in to change notification settings - Fork 0
test(shared): add web<->server contract fixtures + tests for /api/me #1591
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,193 @@ | ||
| import { describe, it, expect, beforeEach, afterAll, vi } from "vitest"; | ||
| import request from "supertest"; | ||
| import { | ||
| meFixtures, | ||
| type MeFixtureCase, | ||
| type MeResponse, | ||
| } from "@sergeant/shared"; | ||
|
|
||
| /** | ||
| * Producer-side contract test for `GET /api/me` / `GET /api/v1/me`. | ||
| * | ||
| * **Goal:** prove that the route's response builder, given a typical | ||
| * Better Auth session-user shape, emits the same wire JSON as the | ||
| * canonical fixtures in `@sergeant/shared/contract-fixtures/me`. The | ||
| * matching consumer test lives in | ||
| * `apps/web/src/test/contract/me.contract.test.ts`. | ||
| * | ||
| * Together these two files form the minimum viable contract: | ||
| * | ||
| * server-user-row → route serializer → fixture | ||
| * fixture → api-client → typed UI value | ||
| * | ||
| * If the schema gets a new required field, BOTH tests must update — | ||
| * consumer test fails on missing field in the fixture, producer test | ||
| * fails on missing field in the response. | ||
| * | ||
| * Closes diagnostic §7.4 (`docs/diagnostics/2026-05-03-web-deep-dive/04-security-observability-testing-devx.md`). | ||
| */ | ||
|
|
||
| const { mockPool, queryMock, getSessionUserMock } = vi.hoisted(() => { | ||
| const queryMock = vi.fn().mockResolvedValue({ rows: [{ "?column?": 1 }] }); | ||
| const mockPool = { | ||
| query: queryMock, | ||
| connect: vi.fn(), | ||
| on: vi.fn(), | ||
| totalCount: 0, | ||
| idleCount: 0, | ||
| waitingCount: 0, | ||
| }; | ||
| const getSessionUserMock = vi.fn().mockResolvedValue(null); | ||
| return { mockPool, queryMock, getSessionUserMock }; | ||
| }); | ||
|
|
||
| vi.mock("./../db.js", () => ({ | ||
| default: mockPool, | ||
| pool: mockPool, | ||
| query: queryMock, | ||
| ensureSchema: vi.fn().mockResolvedValue(undefined), | ||
| })); | ||
|
|
||
| vi.mock("./../auth.js", () => ({ | ||
| auth: { handler: async () => new Response(null, { status: 404 }) }, | ||
| getSessionUser: getSessionUserMock, | ||
| getSessionUserSoft: vi.fn().mockResolvedValue(null), | ||
| })); | ||
|
|
||
| import { createApp } from "./../app.js"; | ||
|
|
||
| const ENV_KEYS = ["VAPID_PUBLIC_KEY", "VAPID_PRIVATE_KEY", "VAPID_EMAIL"]; | ||
| const savedEnv: Record<string, string | undefined> = {}; | ||
| for (const k of ENV_KEYS) savedEnv[k] = process.env[k]; | ||
|
|
||
| beforeEach(() => { | ||
| queryMock.mockReset(); | ||
| queryMock.mockResolvedValue({ rows: [{ "?column?": 1 }] }); | ||
| getSessionUserMock.mockReset(); | ||
| getSessionUserMock.mockResolvedValue(null); | ||
| for (const k of ENV_KEYS) delete process.env[k]; | ||
| }); | ||
|
|
||
| afterAll(() => { | ||
| for (const k of ENV_KEYS) { | ||
| if (savedEnv[k] === undefined) delete process.env[k]; | ||
| else process.env[k] = savedEnv[k]; | ||
| } | ||
| }); | ||
|
|
||
| /** | ||
| * Translate a contract fixture into the shape Better Auth's | ||
| * `getSessionUser()` would return for the same user. The route's job is | ||
| * to flatten that into the canonical fixture; this helper is what the | ||
| * test feeds the auth mock. | ||
| * | ||
| * `createdAt` from Better Auth comes as a `Date` (or sometimes a | ||
| * stringified ISO when the adapter has already serialised it). We | ||
| * exercise both paths: numbered fixtures alternate between Date and | ||
| * string. | ||
| */ | ||
| function authedUserFromFixture( | ||
| fixture: MeResponse, | ||
| variant: "date" | "string" | "missing", | ||
| ): Record<string, unknown> { | ||
| const { user } = fixture; | ||
| const base: Record<string, unknown> = { | ||
| id: user.id, | ||
| email: user.email, | ||
| name: user.name, | ||
| image: user.image, | ||
| emailVerified: user.emailVerified, | ||
| }; | ||
| if (variant === "missing" || user.createdAt === null) { | ||
| return base; | ||
| } | ||
| if (variant === "string") { | ||
| base.createdAt = user.createdAt; | ||
| } else { | ||
| base.createdAt = new Date(user.createdAt); | ||
| } | ||
| return base; | ||
| } | ||
|
|
||
| const NAMES: readonly MeFixtureCase[] = [ | ||
| "minimal", | ||
| "full", | ||
| "legacyNoCreatedAt", | ||
| "unverified", | ||
| ] as const; | ||
|
|
||
| describe("contract producer: GET /api/v1/me", () => { | ||
| it.each(NAMES)( | ||
| "fixture %s — Date `createdAt` round-trips through the route", | ||
| async (name) => { | ||
| const fixture = meFixtures[name]; | ||
| const authed = authedUserFromFixture(fixture, "date"); | ||
| getSessionUserMock.mockResolvedValueOnce(authed); | ||
|
|
||
| const app = createApp(); | ||
| const res = await request(app) | ||
| .get("/api/v1/me") | ||
| .set("Authorization", "Bearer contract-stub"); | ||
|
|
||
| expect(res.status).toBe(200); | ||
| expect(res.body).toEqual(fixture); | ||
| }, | ||
| ); | ||
|
|
||
| it.each(NAMES)( | ||
| "fixture %s — string `createdAt` round-trips through the route", | ||
| async (name) => { | ||
| const fixture = meFixtures[name]; | ||
| const authed = authedUserFromFixture(fixture, "string"); | ||
| getSessionUserMock.mockResolvedValueOnce(authed); | ||
|
|
||
| const app = createApp(); | ||
| const res = await request(app) | ||
| .get("/api/v1/me") | ||
| .set("Authorization", "Bearer contract-stub"); | ||
|
|
||
| expect(res.status).toBe(200); | ||
| expect(res.body).toEqual(fixture); | ||
| }, | ||
| ); | ||
|
|
||
| it("legacyNoCreatedAt — missing field on the auth user → null on the wire", async () => { | ||
| // Older accounts may not have `createdAt` at all in the auth row. | ||
| // The route normalises this to `null`, matching the | ||
| // `legacyNoCreatedAt` fixture exactly. | ||
| const fixture = meFixtures.legacyNoCreatedAt; | ||
| const authed = authedUserFromFixture(fixture, "missing"); | ||
| getSessionUserMock.mockResolvedValueOnce(authed); | ||
|
|
||
| const app = createApp(); | ||
| const res = await request(app) | ||
| .get("/api/v1/me") | ||
| .set("Authorization", "Bearer contract-stub"); | ||
|
|
||
| expect(res.status).toBe(200); | ||
| expect(res.body).toEqual(fixture); | ||
| expect(res.body.user.createdAt).toBeNull(); | ||
| }); | ||
|
|
||
| it("response is byte-stable between /api/me and /api/v1/me for the same fixture", async () => { | ||
| // Hard Rule: legacy and v1 prefixes must emit IDENTICAL bodies. If | ||
| // they ever diverge, downstream code split between the two paths | ||
| // would silently misbehave. | ||
| const fixture = meFixtures.full; | ||
| const authed = authedUserFromFixture(fixture, "date"); | ||
| getSessionUserMock.mockResolvedValue(authed); | ||
|
|
||
| const app = createApp(); | ||
| const legacy = await request(app) | ||
| .get("/api/me") | ||
| .set("Authorization", "Bearer x"); | ||
| const v1 = await request(app) | ||
| .get("/api/v1/me") | ||
| .set("Authorization", "Bearer x"); | ||
|
|
||
| expect(legacy.status).toBe(200); | ||
| expect(v1.status).toBe(200); | ||
| expect(v1.body).toEqual(legacy.body); | ||
| expect(v1.body).toEqual(fixture); | ||
| }); | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,123 @@ | ||
| /** | ||
| * Contract test for `GET /api/me` / `GET /api/v1/me`. | ||
| * | ||
| * **Goal:** prove that the canonical wire-shape fixtures in | ||
| * `@sergeant/shared/contract-fixtures/me` are accepted by the | ||
| * api-client consumer side **byte-for-byte**, so any future drift | ||
| * between the schema (`MeResponseSchema`) and either the fixture or | ||
| * the consumer's parser fails CI here — not in production. | ||
| * | ||
| * Closes diagnostic | ||
| * [`docs/diagnostics/2026-05-03-web-deep-dive/04-security-observability-testing-devx.md`](../../../../../docs/diagnostics/2026-05-03-web-deep-dive/04-security-observability-testing-devx.md) §7.4 | ||
| * (web↔server contract gap). | ||
| * | ||
| * The matching producer-side test lives in | ||
| * `apps/server/src/routes/me.contract.test.ts`. Together they form the | ||
| * minimal viable contract for `/api/me`. New endpoints follow the same | ||
| * 2-file pattern (consumer + producer over a shared fixture). | ||
| */ | ||
|
|
||
| import { describe, expect, it, beforeEach, afterEach, vi } from "vitest"; | ||
| import { | ||
| meFixtures, | ||
| meRawFixtures, | ||
| assertMeFixturesValid, | ||
| MeResponseSchema, | ||
| type MeFixtureCase, | ||
| } from "@sergeant/shared"; | ||
| import { createHttpClient } from "@sergeant/api-client"; | ||
| import { createMeEndpoints } from "@sergeant/api-client"; | ||
|
|
||
| const FIXTURE_NAMES: readonly MeFixtureCase[] = [ | ||
| "minimal", | ||
| "full", | ||
| "legacyNoCreatedAt", | ||
| "unverified", | ||
| ] as const; | ||
|
|
||
| function jsonResponse(body: unknown, init: ResponseInit = {}): Response { | ||
| return new Response(JSON.stringify(body), { | ||
| status: 200, | ||
| headers: { "content-type": "application/json" }, | ||
| ...init, | ||
| }); | ||
| } | ||
|
|
||
| let originalFetch: typeof fetch; | ||
|
|
||
| beforeEach(() => { | ||
| originalFetch = globalThis.fetch; | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| globalThis.fetch = originalFetch; | ||
| vi.restoreAllMocks(); | ||
| }); | ||
|
|
||
| describe("contract: /api/me", () => { | ||
| it("every named fixture parses through MeResponseSchema (sanity)", () => { | ||
| // assertMeFixturesValid throws on the first fixture that no longer | ||
| // matches the schema. Keep it cheap so this whole test file can be | ||
| // a quick CI gate. | ||
| expect(() => assertMeFixturesValid()).not.toThrow(); | ||
| }); | ||
|
|
||
| it.each(FIXTURE_NAMES)( | ||
| "fixture %s round-trips through the api-client consumer", | ||
| async (name) => { | ||
| const fixture = meRawFixtures[name]; | ||
|
|
||
| // Mock the network so the api-client receives the canonical JSON | ||
| // verbatim. If the schema gets stricter or the fixture loses a | ||
| // required field, `MeResponseSchema.parse()` inside `me.get()` | ||
| // throws a ZodError — and CI fails here, not in browser logs. | ||
| const fetchMock = vi.fn(async () => jsonResponse(fixture)); | ||
| globalThis.fetch = fetchMock as unknown as typeof fetch; | ||
|
|
||
| const http = createHttpClient({ baseUrl: "http://contract.test" }); | ||
| const me = createMeEndpoints(http); | ||
|
|
||
| const result = await me.get(); | ||
|
|
||
| // Deep-equal: api-client must NOT silently strip unknown fields, | ||
| // remap nullables, or coerce strings to numbers without explicit | ||
| // schema support. | ||
| expect(result).toEqual(meFixtures[name]); | ||
| expect(fetchMock).toHaveBeenCalledOnce(); | ||
| }, | ||
| ); | ||
|
|
||
| it("rejects a payload missing a required field (drift detection)", async () => { | ||
| // Drop `emailVerified` to simulate a server regression where the | ||
| // serializer forgets a Hard Rule #3 update. The api-client must | ||
| // refuse the response — masking it would silently drop the | ||
| // verification banner in the UI. | ||
| const broken = { | ||
| user: { | ||
| id: "user_broken_001", | ||
| email: "broken@example.com", | ||
| name: null, | ||
| image: null, | ||
| // emailVerified missing on purpose. | ||
| createdAt: "2026-01-01T00:00:00.000Z", | ||
| }, | ||
| }; | ||
| globalThis.fetch = vi.fn( | ||
| async () => jsonResponse(broken), | ||
| ) as unknown as typeof fetch; | ||
|
|
||
| const http = createHttpClient({ baseUrl: "http://contract.test" }); | ||
| const me = createMeEndpoints(http); | ||
|
|
||
| await expect(me.get()).rejects.toThrow(); | ||
| }); | ||
|
|
||
| it("`MeResponseSchema` accepts every fixture as `unknown` JSON", () => { | ||
| // This is the producer-side guarantee mirrored on the consumer: | ||
| // the same schema accepts the same fixtures from both directions. | ||
| for (const name of FIXTURE_NAMES) { | ||
| const parsed = MeResponseSchema.parse(meRawFixtures[name]); | ||
| expect(parsed).toEqual(meFixtures[name]); | ||
| } | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win
Switch new test-module imports/mocks to path aliases.
Please avoid new relative module paths here and use the repo’s configured aliases for consistency with import policy.
As per coding guidelines:
Use path aliases (@shared/*,@finyk/*, etc.) instead of relative imports like ../../../.🤖 Prompt for AI Agents