trails/apps/journal/app/routes/api.sync.webhook.$provider.test.ts
Ullrich Schäfer 4de6c86d41
fix(journal): architectural audit omnibus
Addresses 8 issues from the Journal architecture audit:

1. DB indexes on routes.ownerId + activities.ownerId. Listing queries on
   these tables were full table scans; adds composite indexes matching
   the order-by columns (updatedAt/startedAt/createdAt).
2. Zod validation on /api/auth/register body. Previously the action
   destructured request.json() with zero schema validation.
3. N+1 GeoJSON batch fetch collapsed to a single ANY($1::text[]) query
   in both routes.server and activities.server.
4. Webhook envelope validation in /api/sync/webhook/:provider.
5. AbortSignal.timeout(30s) on all external fetches (Komoot, Wahoo) via
   a new fetchWithTimeout helper in lib/http.server.ts.
6. .limit(100) on listPublicRoutesForOwner / listPublicActivitiesForOwner.
9. Welcome email moved off fire-and-forget onto a pg-boss job with
   retryLimit: 3 (send-welcome-email).
10. process.env.ORIGIN ?? "http://localhost:3000" centralized into
    lib/config.server.ts::getOrigin() across 14 call sites.

Issues 7 (centralized apiError/auth guards across 60+ route files) and
8 (split .server.ts boundaries across 20+ route files) intentionally
deferred — both are pure refactors that would balloon this PR past
reviewability and warrant their own focused PRs.

Tests added:
- lib/config.server.test.ts (2 cases)
- lib/http.server.test.ts (3 cases — timeout abort, success passthrough,
  caller-signal composition)
- routes/api.sync.webhook.$provider.test.ts (6 cases)
- routes/api.auth.register.test.ts (7 cases — schema rejection paths +
  the new welcome-email enqueue assertion)

Full repo: pnpm typecheck, pnpm lint, pnpm test all green.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-24 10:28:33 +02:00

93 lines
3 KiB
TypeScript

import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
const mocks = vi.hoisted(() => ({
parseWebhook: vi.fn(),
handle: vi.fn(),
}));
const { parseWebhook, handle } = mocks;
vi.mock("~/lib/connected-services", () => ({
getManifest: (id: string) =>
id === "test"
? {
id: "test",
webhookReceiver: { parseWebhook: mocks.parseWebhook, handle: mocks.handle },
}
: null,
}));
import { action } from "./api.sync.webhook.$provider.ts";
function makeRequest(body: string | object, method = "POST"): Request {
const init: RequestInit = { method, headers: { "content-type": "application/json" } };
if (method !== "GET" && method !== "HEAD") {
init.body = typeof body === "string" ? body : JSON.stringify(body);
}
return new Request("http://test.local/api/sync/webhook/test", init);
}
describe("POST /api/sync/webhook/:provider", () => {
beforeEach(() => {
parseWebhook.mockReset();
handle.mockReset();
parseWebhook.mockReturnValue(null);
vi.unstubAllEnvs();
});
afterEach(() => {
vi.unstubAllEnvs();
});
function statusOf(result: unknown): number {
if (result instanceof Response) return result.status;
const init = (result as { init?: { status?: number } } | undefined)?.init;
return init?.status ?? 200;
}
async function call(body: string | object, opts: { method?: string; provider?: string } = {}) {
return action({
request: makeRequest(body, opts.method ?? "POST"),
params: { provider: opts.provider ?? "test" },
context: {} as unknown,
} as never);
}
it("returns 405 for non-POST", async () => {
const res = await call({}, { method: "GET" });
expect(statusOf(res)).toBe(405);
});
it("returns 200 silently for unknown provider", async () => {
const res = await call({}, { provider: "no-such-provider" });
expect(statusOf(res)).toBe(200);
expect(parseWebhook).not.toHaveBeenCalled();
});
it("returns 200 silently and does not invoke parseWebhook on malformed JSON", async () => {
const res = await call("not-json{");
expect(statusOf(res)).toBe(200);
expect(parseWebhook).not.toHaveBeenCalled();
});
it("returns 200 silently and does not invoke parseWebhook on a non-object body", async () => {
const res = await call("42");
expect(statusOf(res)).toBe(200);
expect(parseWebhook).not.toHaveBeenCalled();
});
it("rejects when webhook_token does not match", async () => {
vi.stubEnv("TEST_WEBHOOK_TOKEN", "expected");
const res = await call({ webhook_token: "wrong" });
expect(statusOf(res)).toBe(200);
expect(parseWebhook).not.toHaveBeenCalled();
});
it("invokes parseWebhook with a valid object body", async () => {
parseWebhook.mockReturnValue({ eventType: "x", providerUserId: "1", workoutId: "9" });
handle.mockResolvedValue(undefined);
const res = await call({ event_type: "x" });
expect(statusOf(res)).toBe(200);
expect(parseWebhook).toHaveBeenCalledTimes(1);
expect(handle).toHaveBeenCalledTimes(1);
});
});