🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
test: expand client and server coverage (#1153)
Goldflagefd3e80c3ee0
diff --git a/client/src/api/gsc/gscDateRange.test.ts b/client/src/api/gsc/gscDateRange.test.tsnew file mode 100644index 000000000..cb9063a63--- /dev/null+++ b/client/src/api/gsc/gscDateRange.test.ts@@ -0,0 +1,80 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { Time } from "../../components/DateSelector/types";+import { getGSCDateRange } from "./gscDateRange";++describe("getGSCDateRange", () => {+ beforeEach(() => {+ vi.useFakeTimers();+ // March 1 in UTC is still late on February 28 in New York.+ vi.setSystemTime(new Date("2026-03-01T04:30:00.000Z"));+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it("uses the requested timezone when resolving a live past-minutes window", () => {+ const time: Time = { mode: "past-minutes", pastMinutesStart: 120, pastMinutesEnd: 0 };++ expect(getGSCDateRange(time, "America/New_York")).toEqual({+ startDate: "2026-02-28",+ endDate: "2026-02-28",+ });+ expect(getGSCDateRange(time, "UTC")).toEqual({+ startDate: "2026-03-01",+ endDate: "2026-03-01",+ });+ });++ it("widens a short sub-day window across the local midnight it crosses", () => {+ vi.setSystemTime(new Date("2026-03-01T05:30:00.000Z"));++ expect(+ getGSCDateRange({ mode: "past-minutes", pastMinutesStart: 120, pastMinutesEnd: 0 }, "America/New_York")+ ).toEqual({ startDate: "2026-02-28", endDate: "2026-03-01" });+ });++ it("keeps both edges of a stepped-back past-minutes window", () => {+ expect(+ getGSCDateRange(+ { mode: "past-minutes", pastMinutesStart: 3 * 24 * 60, pastMinutesEnd: 2 * 24 * 60 },+ "America/New_York"+ )+ ).toEqual({ startDate: "2026-02-25", endDate: "2026-02-26" });+ });++ it("clamps all-time to sixteen calendar months ending today", () => {+ expect(getGSCDateRange({ mode: "all-time" }, "America/New_York")).toEqual({+ startDate: "2024-10-28",+ endDate: "2026-02-28",+ });+ });++ it.each([+ [{ mode: "day", day: "2026-02-14" } satisfies Time, { startDate: "2026-02-14", endDate: "2026-02-14" }],+ [+ { mode: "range", startDate: "2026-02-01", endDate: "2026-02-14" } satisfies Time,+ { startDate: "2026-02-01", endDate: "2026-02-14" },+ ],+ [{ mode: "week", week: "2026-02-23" } satisfies Time, { startDate: "2026-02-23", endDate: "2026-03-01" }],+ [{ mode: "month", month: "2024-02-01" } satisfies Time, { startDate: "2024-02-01", endDate: "2024-02-29" }],+ [{ mode: "year", year: "2024-01-01" } satisfies Time, { startDate: "2024-01-01", endDate: "2024-12-31" }],+ ])("maps %s to its whole-day boundaries", (time, expected) => {+ expect(getGSCDateRange(time, "America/New_York")).toEqual(expected);+ });++ it("treats midnight as the exclusive edge of an exact datetime range", () => {+ expect(+ getGSCDateRange(+ {+ mode: "range",+ startDate: "2026-02-25",+ startTime: "09:00",+ endDate: "2026-02-28",+ endTime: "00:00",+ },+ "America/New_York"+ )+ ).toEqual({ startDate: "2026-02-25", endDate: "2026-02-27" });+ });+});diff --git a/client/src/api/utils.test.ts b/client/src/api/utils.test.tsnew file mode 100644index 000000000..e3949e8c2--- /dev/null+++ b/client/src/api/utils.test.ts@@ -0,0 +1,124 @@+import axios, { AxiosRequestConfig } from "axios";+import { afterEach, describe, expect, it, vi } from "vitest";+import { BACKEND_URL } from "../lib/const";+import { setPrivateKeyResolver } from "./requestContext";+import { authedFetch } from "./utils";++vi.mock("axios", () => ({ default: vi.fn() }));++const axiosMock = vi.mocked(axios);++const lastRequest = () => axiosMock.mock.calls.at(-1)?.[0] as AxiosRequestConfig;++afterEach(() => {+ axiosMock.mockReset();+ setPrivateKeyResolver(() => null);+});++describe("authedFetch", () => {+ it("prefixes relative API paths, sends credentials, and returns response data", async () => {+ const payload = { sites: [{ id: 7 }] };+ axiosMock.mockResolvedValue({ data: payload });++ await expect(authedFetch("/sites")).resolves.toBe(payload);+ expect(lastRequest()).toEqual({+ url: `${BACKEND_URL}/sites`,+ params: undefined,+ withCredentials: true,+ headers: {},+ });+ });++ it("leaves absolute URLs unchanged", async () => {+ axiosMock.mockResolvedValue({ data: "ok" });++ await authedFetch("https://example.test/report");++ expect(lastRequest().url).toBe("https://example.test/report");+ });++ it("JSON-encodes top-level array parameters without mutating the caller's object", async () => {+ axiosMock.mockResolvedValue({ data: "ok" });+ const params = {+ filters: [{ parameter: "browser", type: "equals", value: ["Chrome"] }],+ tags: ["one", "two"],+ page: 2,+ options: { includeBots: false },+ };++ await authedFetch("/report", params);++ expect(lastRequest().params).toEqual({+ filters: JSON.stringify(params.filters),+ tags: '["one","two"]',+ page: 2,+ options: { includeBots: false },+ });+ expect(lastRequest().params).not.toBe(params);+ expect(params.tags).toEqual(["one", "two"]);+ expect(params.filters).toEqual([{ parameter: "browser", type: "equals", value: ["Chrome"] }]);+ });++ it("passes method and body configuration through to axios", async () => {+ axiosMock.mockResolvedValue({ data: { saved: true } });+ const data = { name: "Weekly report" };++ await authedFetch("/reports", { notify: true }, { method: "POST", data, timeout: 5_000 });++ expect(lastRequest()).toMatchObject({+ method: "POST",+ data,+ timeout: 5_000,+ params: { notify: true },+ withCredentials: true,+ });+ });++ it("combines caller headers with the current shared-dashboard private key", async () => {+ axiosMock.mockResolvedValue({ data: "ok" });+ let privateKey: string | null = "abcdef123456";+ setPrivateKeyResolver(() => privateKey);++ await authedFetch("/sites/42/overview", undefined, {+ headers: { "x-client": "dashboard", "x-private-key": "stale-key" },+ });++ expect(lastRequest().headers).toEqual({+ "x-client": "dashboard",+ "x-private-key": "abcdef123456",+ });++ privateKey = "123456abcdef";+ await authedFetch("/sites/42/sessions");+ expect(lastRequest().headers).toEqual({ "x-private-key": "123456abcdef" });+ });++ it("does not send a private-key header outside a shared dashboard", async () => {+ axiosMock.mockResolvedValue({ data: "ok" });+ setPrivateKeyResolver(() => null);++ await authedFetch("/sites/42/overview", undefined, { headers: { Accept: "application/json" } });++ expect(lastRequest().headers).toEqual({ Accept: "application/json" });+ expect(lastRequest().headers).not.toHaveProperty("x-private-key");+ });++ it("surfaces the backend's public error message", async () => {+ axiosMock.mockRejectedValue({+ response: { data: { error: "You do not have access to this site" } },+ });++ await expect(authedFetch("/sites/42")).rejects.toThrow("You do not have access to this site");+ });++ it("rethrows transport and malformed-response failures unchanged", async () => {+ const networkError = new Error("socket closed");+ axiosMock.mockRejectedValue(networkError);++ await expect(authedFetch("/sites")).rejects.toBe(networkError);++ const malformedError = { response: { data: { message: "unexpected payload" } } };+ axiosMock.mockRejectedValue(malformedError);+ await expect(authedFetch("/sites")).rejects.toBe(malformedError);+ });+});diff --git a/client/src/lib/export.test.ts b/client/src/lib/export.test.tsnew file mode 100644index 000000000..e63c8ac41--- /dev/null+++ b/client/src/lib/export.test.ts@@ -0,0 +1,98 @@+import Papa from "papaparse";+import { describe, expect, it } from "vitest";+import { formatDateForFilename, generateCSV, generateCSVWithColumns } from "./export";++const parseCSV = (csv: string) =>+ Papa.parse<Record<string, string>>(csv, {+ header: true,+ skipEmptyLines: true,+ });++describe("generateCSV", () => {+ it("returns an empty document when there are no rows", () => {+ expect(generateCSV([])).toBe("");+ });++ it("emits headers and values from ordinary records", () => {+ const parsed = parseCSV(+ generateCSV([+ { page: "/", visitors: 20 },+ { page: "/pricing", visitors: 7 },+ ])+ );++ expect(parsed.meta.fields).toEqual(["page", "visitors"]);+ expect(parsed.data).toEqual([+ { page: "/", visitors: "20" },+ { page: "/pricing", visitors: "7" },+ ]);+ expect(parsed.errors).toEqual([]);+ });++ it("round-trips commas, quotes, and line breaks as CSV data", () => {+ const data = [{ page: "/docs,getting-started", title: 'Read "this"\nfirst' }];++ expect(parseCSV(generateCSV(data)).data).toEqual(data);+ });+});++describe("generateCSVWithColumns", () => {+ it("uses the requested column order and excludes unselected fields", () => {+ const csv = generateCSVWithColumns([{ browser: "Firefox", visitors: 12, internalId: 99 }], ["visitors", "browser"]);+ const parsed = parseCSV(csv);++ expect(parsed.meta.fields).toEqual(["visitors", "browser"]);+ expect(parsed.data).toEqual([{ visitors: "12", browser: "Firefox" }]);+ expect(csv).not.toContain("internalId");+ });++ it("normalizes missing and null values to empty cells", () => {+ const parsed = parseCSV(+ generateCSVWithColumns(+ [+ { page: "/one", title: null },+ { page: "/two", title: undefined },+ ],+ ["page", "title"]+ )+ );++ expect(parsed.data).toEqual([+ { page: "/one", title: "" },+ { page: "/two", title: "" },+ ]);+ });++ it("serializes object and array cells as JSON instead of losing their structure", () => {+ const parsed = parseCSV(+ generateCSVWithColumns(+ [{ properties: { plan: "pro", seats: 3 }, tags: ["trial", "annual"] }],+ ["properties", "tags"]+ )+ );++ expect(parsed.data).toEqual([+ {+ properties: '{"plan":"pro","seats":3}',+ tags: '["trial","annual"]',+ },+ ]);+ });++ it("can emit a header-only export for a known schema", () => {+ const csv = generateCSVWithColumns([], ["timestamp", "pathname"]);++ expect(csv).toBe("timestamp,pathname\r\n");+ expect(Papa.parse(csv, { header: true }).meta.fields).toEqual(["timestamp", "pathname"]);+ });++ it("returns an empty document only when both rows and columns are absent", () => {+ expect(generateCSVWithColumns([], [])).toBe("");+ });+});++describe("formatDateForFilename", () => {+ it("formats the UTC calendar date independent of the local timezone", () => {+ expect(formatDateForFilename(new Date("2026-01-02T23:59:59.999-08:00"))).toBe("2026-01-03");+ });+});diff --git a/client/src/lib/siteRoute.test.ts b/client/src/lib/siteRoute.test.tsnew file mode 100644index 000000000..53288d0fc--- /dev/null+++ b/client/src/lib/siteRoute.test.ts@@ -0,0 +1,98 @@+import { describe, expect, it } from "vitest";+import {+ getMainDashboardPath,+ getSiteRouteContext,+ isSyncedAnalyticsRoute,+ PRIVATE_KEY_PATTERN,+ SYNCED_ANALYTICS_ROUTES,+} from "./siteRoute";++describe("getSiteRouteContext", () => {+ it("reads a normal site route", () => {+ expect(getSiteRouteContext("/42/sessions")).toEqual({+ siteId: "42",+ privateKey: null,+ route: "sessions",+ });+ });++ it("reads a shared-dashboard route and preserves the supplied key", () => {+ expect(getSiteRouteContext("/42/ABCDEF123456/performance")).toEqual({+ siteId: "42",+ privateKey: "ABCDEF123456",+ route: "performance",+ });+ });++ it("does not mistake an ordinary 12-character route for a private key", () => {+ expect(getSiteRouteContext("/42/session-list/details")).toEqual({+ siteId: "42",+ privateKey: null,+ route: "session-list",+ });+ });++ it("normalizes repeated and trailing slashes", () => {+ expect(getSiteRouteContext("//42//abcdef123456//events//")).toEqual({+ siteId: "42",+ privateKey: "abcdef123456",+ route: "events",+ });+ });++ it("returns null fields for a missing pathname", () => {+ expect(getSiteRouteContext(undefined)).toEqual({ siteId: null, privateKey: null, route: null });+ expect(getSiteRouteContext(null)).toEqual({ siteId: null, privateKey: null, route: null });+ expect(getSiteRouteContext("/")).toEqual({ siteId: null, privateKey: null, route: null });+ });++ it("leaves the route null at the root of either site URL shape", () => {+ expect(getSiteRouteContext("/42")).toEqual({ siteId: "42", privateKey: null, route: null });+ expect(getSiteRouteContext("/42/abcdef123456")).toEqual({+ siteId: "42",+ privateKey: "abcdef123456",+ route: null,+ });+ });+});++describe("private-key recognition", () => {+ it("requires exactly 12 hexadecimal characters", () => {+ expect(PRIVATE_KEY_PATTERN.test("abcdef123456")).toBe(true);+ expect(PRIVATE_KEY_PATTERN.test("ABCDEF123456")).toBe(true);+ expect(PRIVATE_KEY_PATTERN.test("abcdef12345")).toBe(false);+ expect(PRIVATE_KEY_PATTERN.test("abcdef1234567")).toBe(false);+ expect(PRIVATE_KEY_PATTERN.test("ghijkl123456")).toBe(false);+ });+});++describe("isSyncedAnalyticsRoute", () => {+ it("accepts every declared synchronized route", () => {+ for (const route of SYNCED_ANALYTICS_ROUTES) {+ expect(isSyncedAnalyticsRoute(route), route).toBe(true);+ }+ });++ it("rejects absent, unrelated, and differently-cased routes", () => {+ expect(isSyncedAnalyticsRoute(null)).toBe(false);+ expect(isSyncedAnalyticsRoute(undefined)).toBe(false);+ expect(isSyncedAnalyticsRoute("settings")).toBe(false);+ expect(isSyncedAnalyticsRoute("Sessions")).toBe(false);+ });+});++describe("getMainDashboardPath", () => {+ it("builds main paths for normal and shared dashboards", () => {+ expect(getMainDashboardPath("/42/events")).toBe("/42/main");+ expect(getMainDashboardPath("/42/abcdef123456/events")).toBe("/42/abcdef123456/main");+ });++ it("keeps the site identifier exactly as represented in the URL", () => {+ expect(getMainDashboardPath("/0042/users")).toBe("/0042/main");+ });++ it("rejects missing and non-numeric site identifiers", () => {+ expect(getMainDashboardPath(undefined)).toBeNull();+ expect(getMainDashboardPath("/settings/account")).toBeNull();+ });+});diff --git a/client/src/lib/store.test.tsx b/client/src/lib/store.test.tsxnew file mode 100644index 000000000..d1179d220--- /dev/null+++ b/client/src/lib/store.test.tsx@@ -0,0 +1,153 @@+// The .tsx suffix selects Vitest's jsdom project for localStorage and window.history coverage.+import { Filter } from "@rybbit/shared";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { DEFAULT_COMPARISON } from "../components/DateSelector/types";+import { addFilter, getFilteredFilters, getTimezone, removeFilter, updateFilter, useStore } from "./store";++const chrome: Filter = { parameter: "browser", type: "equals", value: ["Chrome"] };+const firefox: Filter = { parameter: "browser", type: "equals", value: ["Firefox"] };+const canada: Filter = { parameter: "country", type: "equals", value: ["CA"] };++beforeEach(() => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date("2026-08-29T16:00:00.000Z"));+ localStorage.clear();+ window.history.replaceState({}, "", "/42/main");+ useStore.setState({+ site: "",+ privateKey: null,+ time: { mode: "day", day: "2026-08-14" },+ previousTime: { mode: "day", day: "2026-08-13" },+ comparison: DEFAULT_COMPARISON,+ bucket: "hour",+ selectedStat: "users",+ filters: [],+ timezone: "UTC",+ });+});++afterEach(() => {+ vi.useRealTimers();+ localStorage.clear();+});++describe("filter state", () => {+ it("adds a filter and replaces an existing parameter/operator pair", () => {+ addFilter(chrome);+ addFilter(firefox);++ expect(useStore.getState().filters).toEqual([firefox]);+ });++ it("keeps filters with different parameters or operators distinct", () => {+ const notChrome: Filter = { parameter: "browser", type: "not_equals", value: ["Chrome"] };++ addFilter(chrome);+ addFilter(notChrome);+ addFilter(canada);++ expect(useStore.getState().filters).toEqual([chrome, notChrome, canada]);+ });++ it("updates and removes filters while preserving the remaining order", () => {+ useStore.getState().setFilters([chrome, canada]);++ updateFilter(firefox, 0);+ expect(useStore.getState().filters).toEqual([firefox, canada]);++ removeFilter(firefox);+ expect(useStore.getState().filters).toEqual([canada]);+ });++ it("selects only the filter dimensions a page supports", () => {+ useStore.getState().setFilters([chrome, canada]);++ expect(getFilteredFilters(["country"])).toEqual([canada]);+ expect(getFilteredFilters(["browser", "country"])).toEqual([chrome, canada]);+ expect(getFilteredFilters([])).toEqual([]);+ });+});++describe("time and comparison state", () => {+ it("derives the comparison window and bucket whenever time changes", () => {+ useStore.getState().setTime({ mode: "range", startDate: "2026-08-01", endDate: "2026-08-07" });++ expect(useStore.getState()).toMatchObject({+ time: { mode: "range", startDate: "2026-08-01", endDate: "2026-08-07" },+ previousTime: { mode: "range", startDate: "2026-07-25", endDate: "2026-07-31" },+ bucket: "day",+ });+ });++ it("can change time without replacing a manually selected bucket", () => {+ useStore.getState().setBucket("month");+ useStore.getState().setTime({ mode: "day", day: "2026-08-20" }, false);++ expect(useStore.getState()).toMatchObject({+ time: { mode: "day", day: "2026-08-20" },+ previousTime: { mode: "day", day: "2026-08-19" },+ bucket: "month",+ });+ });++ it("keeps comparison disabled as the selected period changes", () => {+ useStore.getState().setComparison({ mode: "none" });+ expect(useStore.getState().previousTime).toBeNull();++ useStore.getState().setTime({ mode: "month", month: "2026-07-01" });+ expect(useStore.getState()).toMatchObject({ comparison: { mode: "none" }, previousTime: null });+ });++ it("resolves explicit and system timezones through the public helper", () => {+ useStore.getState().setTimezone("America/Los_Angeles");+ expect(getTimezone()).toBe("America/Los_Angeles");++ useStore.getState().setTimezone("system");+ expect(getTimezone()).toBe(Intl.DateTimeFormat().resolvedOptions().timeZone);+ });+});++describe("site context", () => {+ it("resets dashboard selections to defaults when the new URL has no state", () => {+ useStore.setState({+ selectedStat: "bounce_rate",+ filters: [chrome],+ bucket: "month",+ comparison: { mode: "none" },+ });++ useStore.getState().setSiteContext("84", "abcdef123456");++ const state = useStore.getState();+ expect(state.site).toBe("84");+ expect(state.privateKey).toBe("abcdef123456");+ expect(state.selectedStat).toBe("users");+ expect(state.filters).toEqual([]);+ expect(state.time.wellKnown).toBe("today");+ expect(state.comparison).toEqual(DEFAULT_COMPARISON);+ });++ it("preserves selections whose URL parameters are waiting to hydrate", () => {+ window.history.replaceState({}, "", "/84/main?timeMode=day&bucket=month&stat=bounce_rate&filters=%5B%5D");+ useStore.setState({+ time: { mode: "day", day: "2026-08-14" },+ previousTime: null,+ selectedStat: "bounce_rate",+ filters: [chrome],+ bucket: "month",+ comparison: { mode: "none" },+ });++ useStore.getState().setSite("84");++ expect(useStore.getState()).toMatchObject({+ site: "84",+ time: { mode: "day", day: "2026-08-14" },+ previousTime: null,+ selectedStat: "bounce_rate",+ filters: [chrome],+ bucket: "month",+ comparison: { mode: "none" },+ });+ });+});diff --git a/server/src/api/memberAccess/updateMemberSiteAccess.test.ts b/server/src/api/memberAccess/updateMemberSiteAccess.test.tsnew file mode 100644index 000000000..acb3247d1--- /dev/null+++ b/server/src/api/memberAccess/updateMemberSiteAccess.test.ts@@ -0,0 +1,296 @@+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ invalidateSitesAccessCache: vi.fn(),+}));++vi.mock("../../db/postgres/postgres.js", async () => {+ const { PGlite } = await import("@electric-sql/pglite");+ const { drizzle } = await import("drizzle-orm/pglite");+ const schema = await import("../../db/postgres/schema.js");+ const client = new PGlite();+ return { db: drizzle(client, { schema }), sql: client };+});++vi.mock("../../lib/auth-utils.js", () => ({+ invalidateSitesAccessCache: mocks.invalidateSitesAccessCache,+}));++import { db, sql as pgClient } from "../../db/postgres/postgres.js";+import { updateMemberSiteAccess } from "./updateMemberSiteAccess.js";++const DDL = `+CREATE TABLE "organization" (+ "id" text PRIMARY KEY,+ "name" text NOT NULL,+ "slug" text NOT NULL,+ "createdAt" timestamp NOT NULL+);+CREATE TABLE "user" (+ "id" text PRIMARY KEY,+ "name" text NOT NULL,+ "email" text NOT NULL+);+CREATE TABLE "sites" (+ "site_id" serial PRIMARY KEY,+ "name" text NOT NULL,+ "domain" text NOT NULL,+ "organization_id" text REFERENCES "organization"("id")+);+CREATE TABLE "member" (+ "id" text PRIMARY KEY,+ "organizationId" text NOT NULL REFERENCES "organization"("id"),+ "userId" text NOT NULL REFERENCES "user"("id") ON DELETE CASCADE,+ "role" text NOT NULL,+ "createdAt" timestamp NOT NULL,+ "has_restricted_site_access" boolean NOT NULL DEFAULT false+);+CREATE TABLE "member_site_access" (+ "id" serial PRIMARY KEY,+ "member_id" text NOT NULL REFERENCES "member"("id") ON DELETE CASCADE,+ "site_id" integer NOT NULL REFERENCES "sites"("site_id") ON DELETE CASCADE,+ "created_at" timestamp NOT NULL DEFAULT now(),+ "created_by" text REFERENCES "user"("id") ON DELETE SET NULL,+ UNIQUE ("member_id", "site_id")+);+`;++function replyStub() {+ const reply: any = { statusCode: 200 };+ reply.status = (code: number) => {+ reply.statusCode = code;+ return reply;+ };+ reply.send = (body: unknown) => {+ reply.body = body;+ return reply;+ };+ return reply;+}++function requestStub(overrides: Record<string, unknown> = {}) {+ return {+ params: { organizationId: "org_1", memberId: "membership_member" },+ body: { hasRestrictedSiteAccess: true, siteIds: [1] },+ user: { id: "admin" },+ log: { error: vi.fn() },+ ...overrides,+ } as any;+}++async function rows(query: string) {+ return (await (pgClient as any).query(query)).rows;+}++beforeAll(async () => {+ await (pgClient as any).exec(DDL);+});++afterAll(async () => {+ await (pgClient as any).close();+});++beforeEach(async () => {+ vi.restoreAllMocks();+ vi.clearAllMocks();++ await (pgClient as any).exec(`+ TRUNCATE "member_site_access", "member", "sites", "user", "organization" RESTART IDENTITY;+ INSERT INTO "organization" ("id", "name", "slug", "createdAt") VALUES+ ('org_1', 'One', 'one', '2026-01-01'),+ ('org_2', 'Two', 'two', '2026-01-01');+ INSERT INTO "user" ("id", "name", "email") VALUES+ ('admin', 'Admin', '[email protected]'),+ ('member_user', 'Member', '[email protected]'),+ ('admin_user', 'Another Admin', '[email protected]'),+ ('owner_user', 'Owner', '[email protected]'),+ ('other_user', 'Other Member', '[email protected]');+ INSERT INTO "member" ("id", "organizationId", "userId", "role", "createdAt", "has_restricted_site_access") VALUES+ ('membership_admin_actor', 'org_1', 'admin', 'admin', '2026-01-01', false),+ ('membership_member', 'org_1', 'member_user', 'member', '2026-01-01', true),+ ('membership_admin', 'org_1', 'admin_user', 'admin', '2026-01-01', false),+ ('membership_owner', 'org_1', 'owner_user', 'owner', '2026-01-01', false),+ ('membership_other', 'org_2', 'other_user', 'member', '2026-01-01', false);+ INSERT INTO "sites" ("name", "domain", "organization_id") VALUES+ ('One A', 'a.example.com', 'org_1'),+ ('One B', 'b.example.com', 'org_1'),+ ('Other', 'other.example.com', 'org_2');+ INSERT INTO "member_site_access" ("member_id", "site_id", "created_by")+ VALUES ('membership_member', 1, 'admin');+ `);+});++describe("updateMemberSiteAccess", () => {+ it("replaces grants, records the acting user, and returns site metadata", async () => {+ const reply = replyStub();++ await updateMemberSiteAccess(requestStub({ body: { hasRestrictedSiteAccess: true, siteIds: [2] } }), reply);++ expect(reply.statusCode).toBe(200);+ expect(reply.body).toEqual({+ memberId: "membership_member",+ hasRestrictedSiteAccess: true,+ siteAccess: [{ siteId: 2, name: "One B", domain: "b.example.com" }],+ });+ expect(await rows(`SELECT has_restricted_site_access FROM member WHERE id = 'membership_member'`)).toEqual([+ { has_restricted_site_access: true },+ ]);+ expect(await rows(`SELECT site_id, created_by FROM member_site_access`)).toEqual([+ { site_id: 2, created_by: "admin" },+ ]);+ expect(mocks.invalidateSitesAccessCache).toHaveBeenCalledOnce();+ expect(mocks.invalidateSitesAccessCache).toHaveBeenCalledWith("member_user");+ });++ it("supports multiple same-organization grants", async () => {+ const reply = replyStub();++ await updateMemberSiteAccess(requestStub({ body: { hasRestrictedSiteAccess: true, siteIds: [1, 2] } }), reply);++ expect(reply.body.siteAccess).toEqual([+ { siteId: 1, name: "One A", domain: "a.example.com" },+ { siteId: 2, name: "One B", domain: "b.example.com" },+ ]);+ expect(await rows(`SELECT site_id FROM member_site_access ORDER BY site_id`)).toEqual([+ { site_id: 1 },+ { site_id: 2 },+ ]);+ });++ it("can restrict a member to no sites", async () => {+ const reply = replyStub();++ await updateMemberSiteAccess(requestStub({ body: { hasRestrictedSiteAccess: true, siteIds: [] } }), reply);++ expect(reply.statusCode).toBe(200);+ expect(reply.body).toEqual({+ memberId: "membership_member",+ hasRestrictedSiteAccess: true,+ siteAccess: [],+ });+ expect(await rows(`SELECT * FROM member_site_access`)).toEqual([]);+ expect(mocks.invalidateSitesAccessCache).toHaveBeenCalledWith("member_user");+ });++ it("unrestricts a member and clears every prior explicit grant", async () => {+ const reply = replyStub();++ await updateMemberSiteAccess(requestStub({ body: { hasRestrictedSiteAccess: false, siteIds: [] } }), reply);++ expect(reply.statusCode).toBe(200);+ expect(reply.body.siteAccess).toEqual([]);+ expect(await rows(`SELECT has_restricted_site_access FROM member WHERE id = 'membership_member'`)).toEqual([+ { has_restricted_site_access: false },+ ]);+ expect(await rows(`SELECT * FROM member_site_access`)).toEqual([]);+ });++ it("stores null audit attribution when authentication did not populate request.user", async () => {+ const reply = replyStub();++ await updateMemberSiteAccess(+ requestStub({ user: undefined, body: { hasRestrictedSiteAccess: true, siteIds: [2] } }),+ reply+ );++ expect(reply.statusCode).toBe(200);+ expect(await rows(`SELECT site_id, created_by FROM member_site_access`)).toEqual([+ { site_id: 2, created_by: null },+ ]);+ });++ it("returns 404 for an unknown member or a member in another organization", async () => {+ for (const params of [+ { organizationId: "org_1", memberId: "missing" },+ { organizationId: "org_1", memberId: "membership_other" },+ { organizationId: "org_2", memberId: "membership_member" },+ ]) {+ const reply = replyStub();+ await updateMemberSiteAccess(requestStub({ params }), reply);++ expect(reply.statusCode).toBe(404);+ expect(reply.body).toEqual({ error: "Member not found" });+ }+ expect(mocks.invalidateSitesAccessCache).not.toHaveBeenCalled();+ });++ it("rejects restricting admins and owners without changing their records", async () => {+ for (const memberId of ["membership_admin", "membership_owner"]) {+ const reply = replyStub();+ await updateMemberSiteAccess(requestStub({ params: { organizationId: "org_1", memberId } }), reply);++ expect(reply.statusCode).toBe(400);+ expect(reply.body).toEqual({ error: "Cannot restrict site access for admin or owner roles" });+ }+ expect(+ await rows(`SELECT id, has_restricted_site_access FROM member WHERE role IN ('admin', 'owner') ORDER BY id`)+ ).toEqual([+ { id: "membership_admin", has_restricted_site_access: false },+ { id: "membership_admin_actor", has_restricted_site_access: false },+ { id: "membership_owner", has_restricted_site_access: false },+ ]);+ expect(mocks.invalidateSitesAccessCache).not.toHaveBeenCalled();+ });++ it("rejects foreign and nonexistent site IDs without changing existing access", async () => {+ const reply = replyStub();+ await (pgClient as any).exec(`UPDATE member SET has_restricted_site_access = false WHERE id = 'membership_member'`);++ await updateMemberSiteAccess(requestStub({ body: { hasRestrictedSiteAccess: true, siteIds: [1, 3, 99] } }), reply);++ expect(reply.statusCode).toBe(400);+ expect(reply.body).toEqual({+ error: "Invalid site IDs: 3, 99. Sites must belong to this organization.",+ });+ expect(await rows(`SELECT has_restricted_site_access FROM member WHERE id = 'membership_member'`)).toEqual([+ { has_restricted_site_access: false },+ ]);+ expect(await rows(`SELECT site_id FROM member_site_access`)).toEqual([{ site_id: 1 }]);+ expect(mocks.invalidateSitesAccessCache).not.toHaveBeenCalled();+ });++ it("rolls back the flag and grants when replacement insertion fails", async () => {+ const request = requestStub({+ user: { id: "missing-actor" },+ body: { hasRestrictedSiteAccess: true, siteIds: [2] },+ });+ const reply = replyStub();+ await (pgClient as any).exec(`UPDATE member SET has_restricted_site_access = false WHERE id = 'membership_member'`);++ await updateMemberSiteAccess(request, reply);++ expect(reply.statusCode).toBe(500);+ expect(await rows(`SELECT has_restricted_site_access FROM member WHERE id = 'membership_member'`)).toEqual([+ { has_restricted_site_access: false },+ ]);+ expect(await rows(`SELECT site_id, created_by FROM member_site_access`)).toEqual([+ { site_id: 1, created_by: "admin" },+ ]);+ expect(mocks.invalidateSitesAccessCache).not.toHaveBeenCalled();+ });++ it("does not retain submitted site IDs when switching to unrestricted access", async () => {+ const reply = replyStub();++ await updateMemberSiteAccess(requestStub({ body: { hasRestrictedSiteAccess: false, siteIds: [1] } }), reply);++ expect(reply.statusCode).toBe(200);+ expect(reply.body.siteAccess).toEqual([]);+ expect(await rows(`SELECT * FROM member_site_access`)).toEqual([]);+ });++ it("returns 500 and logs database failures", async () => {+ const request = requestStub();+ const reply = replyStub();+ vi.spyOn(db, "select").mockImplementationOnce(() => {+ throw new Error("database offline");+ });++ await updateMemberSiteAccess(request, reply);++ expect(reply.statusCode).toBe(500);+ expect(reply.body).toEqual({ error: "Failed to update member site access" });+ expect(request.log.error).toHaveBeenCalledWith({ err: expect.any(Error) }, "Error updating member site access");+ expect(mocks.invalidateSitesAccessCache).not.toHaveBeenCalled();+ });+});diff --git a/server/src/api/memberAccess/updateMemberSiteAccess.ts b/server/src/api/memberAccess/updateMemberSiteAccess.tsindex 523822d83..12b59f829 100644--- a/server/src/api/memberAccess/updateMemberSiteAccess.ts+++ b/server/src/api/memberAccess/updateMemberSiteAccess.ts@@ -65,22 +65,20 @@ export async function updateMemberSiteAccess(}}- // Update member's hasRestrictedSiteAccess flag- await db.update(member).set({ hasRestrictedSiteAccess }).where(eq(member.id, memberId));-- // Delete existing site access entries- await db.delete(memberSiteAccess).where(eq(memberSiteAccess.memberId, memberId));-- // Insert new site access entries if restricted and has site IDs- if (hasRestrictedSiteAccess && siteIds && siteIds.length > 0) {- await db.insert(memberSiteAccess).values(- siteIds.map(siteId => ({- memberId: memberId,- siteId: siteId,- createdBy: currentUserId || null,- }))- );- }+ await db.transaction(async tx => {+ await tx.update(member).set({ hasRestrictedSiteAccess }).where(eq(member.id, memberId));+ await tx.delete(memberSiteAccess).where(eq(memberSiteAccess.memberId, memberId));++ if (hasRestrictedSiteAccess && siteIds && siteIds.length > 0) {+ await tx.insert(memberSiteAccess).values(+ siteIds.map(siteId => ({+ memberId,+ siteId,+ createdBy: currentUserId || null,+ }))+ );+ }+ });// Invalidate the cache for this userinvalidateSitesAccessCache(memberData.userId);diff --git a/server/src/api/teams/teams.test.ts b/server/src/api/teams/teams.test.tsnew file mode 100644index 000000000..5d0c45f26--- /dev/null+++ b/server/src/api/teams/teams.test.ts@@ -0,0 +1,479 @@+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ getUserIdFromRequest: vi.fn(),+ invalidateSitesAccessCache: vi.fn(),+}));++vi.mock("../../db/postgres/postgres.js", async () => {+ const { PGlite } = await import("@electric-sql/pglite");+ const { drizzle } = await import("drizzle-orm/pglite");+ const schema = await import("../../db/postgres/schema.js");+ const client = new PGlite();+ return { db: drizzle(client, { schema }), sql: client };+});++vi.mock("../../lib/auth-utils.js", () => ({+ getUserIdFromRequest: mocks.getUserIdFromRequest,+ invalidateSitesAccessCache: mocks.invalidateSitesAccessCache,+}));++import { db, sql as pgClient } from "../../db/postgres/postgres.js";+import { createTeam } from "./createTeam.js";+import { deleteTeam } from "./deleteTeam.js";+import { listTeams } from "./listTeams.js";+import { updateTeam } from "./updateTeam.js";++const DDL = `+CREATE TABLE "organization" (+ "id" text PRIMARY KEY,+ "name" text NOT NULL,+ "slug" text NOT NULL,+ "createdAt" timestamp NOT NULL+);+CREATE TABLE "user" (+ "id" text PRIMARY KEY,+ "name" text NOT NULL,+ "email" text NOT NULL+);+CREATE TABLE "sites" (+ "site_id" serial PRIMARY KEY,+ "name" text NOT NULL,+ "domain" text NOT NULL,+ "organization_id" text REFERENCES "organization"("id")+);+CREATE TABLE "member" (+ "id" text PRIMARY KEY,+ "organizationId" text NOT NULL REFERENCES "organization"("id"),+ "userId" text NOT NULL REFERENCES "user"("id") ON DELETE CASCADE,+ "role" text NOT NULL,+ "createdAt" timestamp NOT NULL,+ "has_restricted_site_access" boolean NOT NULL DEFAULT false+);+CREATE TABLE "team" (+ "id" text PRIMARY KEY,+ "name" text NOT NULL,+ "organizationId" text NOT NULL REFERENCES "organization"("id") ON DELETE CASCADE,+ "createdAt" timestamp NOT NULL,+ "updatedAt" timestamp+);+CREATE TABLE "teamMember" (+ "id" text PRIMARY KEY,+ "teamId" text NOT NULL REFERENCES "team"("id") ON DELETE CASCADE,+ "userId" text NOT NULL REFERENCES "user"("id") ON DELETE CASCADE,+ "createdAt" timestamp+);+CREATE TABLE "team_site_access" (+ "id" serial PRIMARY KEY,+ "team_id" text NOT NULL REFERENCES "team"("id") ON DELETE CASCADE,+ "site_id" integer NOT NULL REFERENCES "sites"("site_id") ON DELETE CASCADE,+ "created_at" timestamp NOT NULL DEFAULT now(),+ UNIQUE ("team_id", "site_id")+);+`;++function replyStub() {+ const reply: any = { statusCode: 200 };+ reply.status = (code: number) => {+ reply.statusCode = code;+ return reply;+ };+ reply.send = (body: unknown) => {+ reply.body = body;+ return reply;+ };+ return reply;+}++function requestStub(overrides: Record<string, unknown> = {}) {+ return {+ params: { organizationId: "org_1" },+ body: {},+ user: { id: "owner" },+ log: { error: vi.fn() },+ ...overrides,+ } as any;+}++async function rows(query: string) {+ return (await (pgClient as any).query(query)).rows;+}++beforeAll(async () => {+ await (pgClient as any).exec(DDL);+});++afterAll(async () => {+ await (pgClient as any).close();+});++beforeEach(async () => {+ vi.restoreAllMocks();+ vi.clearAllMocks();+ mocks.getUserIdFromRequest.mockResolvedValue("member_1");++ await (pgClient as any).exec(`+ TRUNCATE "team_site_access", "teamMember", "team", "member", "sites", "user", "organization" RESTART IDENTITY;+ INSERT INTO "organization" ("id", "name", "slug", "createdAt") VALUES+ ('org_1', 'One', 'one', '2026-01-01'),+ ('org_2', 'Two', 'two', '2026-01-01');+ INSERT INTO "user" ("id", "name", "email") VALUES+ ('owner', 'Owner', '[email protected]'),+ ('member_1', 'Member One', '[email protected]'),+ ('member_2', 'Member Two', '[email protected]'),+ ('outsider', 'Outsider', '[email protected]');+ INSERT INTO "member" ("id", "organizationId", "userId", "role", "createdAt") VALUES+ ('membership_owner', 'org_1', 'owner', 'owner', '2026-01-01'),+ ('membership_1', 'org_1', 'member_1', 'member', '2026-01-01'),+ ('membership_2', 'org_1', 'member_2', 'member', '2026-01-01'),+ ('membership_outsider', 'org_2', 'outsider', 'owner', '2026-01-01');+ INSERT INTO "sites" ("name", "domain", "organization_id") VALUES+ ('One A', 'a.example.com', 'org_1'),+ ('One B', 'b.example.com', 'org_1'),+ ('Other', 'other.example.com', 'org_2');+ `);+});++describe("createTeam", () => {+ it("creates a trimmed team, its members, and site grants atomically", async () => {+ const reply = replyStub();++ await createTeam(+ requestStub({+ body: { name: " Product ", memberUserIds: ["member_1", "member_2"], siteIds: [1, 2] },+ }),+ reply+ );++ expect(reply.statusCode).toBe(201);+ expect(reply.body).toMatchObject({+ id: expect.any(String),+ name: "Product",+ organizationId: "org_1",+ members: ["member_1", "member_2"],+ siteIds: [1, 2],+ });+ expect(await rows(`SELECT name, "organizationId" FROM team`)).toEqual([+ { name: "Product", organizationId: "org_1" },+ ]);+ expect(await rows(`SELECT "userId" FROM "teamMember" ORDER BY "userId"`)).toEqual([+ { userId: "member_1" },+ { userId: "member_2" },+ ]);+ expect(await rows(`SELECT site_id FROM team_site_access ORDER BY site_id`)).toEqual([+ { site_id: 1 },+ { site_id: 2 },+ ]);+ expect(mocks.invalidateSitesAccessCache.mock.calls).toEqual([["member_1"], ["member_2"]]);+ });++ it("rejects blank names before querying or writing", async () => {+ const reply = replyStub();+ const selectSpy = vi.spyOn(db, "select");++ await createTeam(requestStub({ body: { name: " ", memberUserIds: ["member_1"] } }), reply);++ expect(reply.statusCode).toBe(400);+ expect(reply.body).toEqual({ error: "Team name is required" });+ expect(selectSpy).not.toHaveBeenCalled();+ expect(await rows(`SELECT * FROM team`)).toEqual([]);+ });++ it("rejects users outside the organization without partially creating a team", async () => {+ const reply = replyStub();++ await createTeam(+ requestStub({ body: { name: "Product", memberUserIds: ["member_1", "outsider", "missing"] } }),+ reply+ );++ expect(reply.statusCode).toBe(400);+ expect(reply.body).toEqual({ error: "Users not in organization: outsider, missing" });+ expect(await rows(`SELECT * FROM team`)).toEqual([]);+ expect(mocks.invalidateSitesAccessCache).not.toHaveBeenCalled();+ });++ it("rejects sites outside the organization without partially creating a team", async () => {+ const reply = replyStub();++ await createTeam(+ requestStub({ body: { name: "Product", memberUserIds: ["member_1"], siteIds: [1, 3, 99] } }),+ reply+ );++ expect(reply.statusCode).toBe(400);+ expect(reply.body).toEqual({ error: "Sites not in organization: 3, 99" });+ expect(await rows(`SELECT * FROM team`)).toEqual([]);+ expect(mocks.invalidateSitesAccessCache).not.toHaveBeenCalled();+ });++ it("returns 500 and logs database failures", async () => {+ const request = requestStub({ body: { name: "Product", memberUserIds: ["member_1"] } });+ const reply = replyStub();+ vi.spyOn(db, "select").mockImplementationOnce(() => {+ throw new Error("database offline");+ });++ await createTeam(request, reply);++ expect(reply.statusCode).toBe(500);+ expect(reply.body).toEqual({ error: "Failed to create team" });+ expect(request.log.error).toHaveBeenCalledWith({ err: expect.any(Error) }, "Error creating team");+ });+});++describe("listTeams", () => {+ beforeEach(async () => {+ await (pgClient as any).exec(`+ INSERT INTO "team" ("id", "name", "organizationId", "createdAt", "updatedAt") VALUES+ ('team_a', 'Alpha', 'org_1', '2026-01-01', '2026-01-02'),+ ('team_b', 'Beta', 'org_1', '2026-02-01', '2026-02-02'),+ ('team_other', 'Other', 'org_2', '2026-03-01', '2026-03-02');+ INSERT INTO "teamMember" ("id", "teamId", "userId", "createdAt") VALUES+ ('tm_1', 'team_a', 'member_1', '2026-01-01'),+ ('tm_2', 'team_a', 'member_2', '2026-01-01'),+ ('tm_3', 'team_b', 'member_2', '2026-01-01'),+ ('tm_4', 'team_other', 'outsider', '2026-01-01');+ INSERT INTO "team_site_access" ("team_id", "site_id") VALUES+ ('team_a', 1), ('team_a', 2), ('team_other', 3);+ `);+ });++ it("returns every organization team with populated member and site details to owners", async () => {+ const reply = replyStub();++ await listTeams(requestStub(), reply);++ expect(reply.statusCode).toBe(200);+ expect(reply.body.teams).toHaveLength(2);+ expect(reply.body.teams).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ id: "team_a",+ name: "Alpha",+ members: expect.arrayContaining([+ { userId: "member_1", userName: "Member One", userEmail: "[email protected]" },+ { userId: "member_2", userName: "Member Two", userEmail: "[email protected]" },+ ]),+ sites: expect.arrayContaining([+ { siteId: 1, domain: "a.example.com", name: "One A" },+ { siteId: 2, domain: "b.example.com", name: "One B" },+ ]),+ }),+ expect.objectContaining({+ id: "team_b",+ name: "Beta",+ members: [expect.objectContaining({ userId: "member_2" })],+ sites: [],+ }),+ ])+ );+ const alpha = reply.body.teams.find((entry: { id: string }) => entry.id === "team_a");+ expect(alpha.members).toHaveLength(2);+ expect(alpha.sites).toHaveLength(2);+ });++ it("limits ordinary members to their own teams", async () => {+ const reply = replyStub();++ await listTeams(requestStub({ user: { id: "member_1" } }), reply);++ expect(reply.body.teams).toHaveLength(1);+ expect(reply.body.teams[0]).toMatchObject({ id: "team_a", name: "Alpha" });+ });++ it("uses credential-derived identity when request.user is absent", async () => {+ const reply = replyStub();++ await listTeams(requestStub({ user: undefined }), reply);++ expect(mocks.getUserIdFromRequest).toHaveBeenCalledOnce();+ expect(reply.body.teams.map((entry: { id: string }) => entry.id)).toEqual(["team_a"]);+ });++ it("returns an empty collection when the member has no teams in the organization", async () => {+ const reply = replyStub();++ await listTeams(requestStub({ user: { id: "member_2" }, params: { organizationId: "org_2" } }), reply);++ expect(reply.body).toEqual({ teams: [] });+ });++ it("returns 500 and logs database failures", async () => {+ const request = requestStub();+ const reply = replyStub();+ vi.spyOn(db, "select").mockImplementationOnce(() => {+ throw new Error("database offline");+ });++ await listTeams(request, reply);++ expect(reply.statusCode).toBe(500);+ expect(reply.body).toEqual({ error: "Failed to list teams" });+ expect(request.log.error).toHaveBeenCalledWith({ err: expect.any(Error) }, "Error listing teams");+ });+});++describe("updateTeam", () => {+ beforeEach(async () => {+ await (pgClient as any).exec(`+ INSERT INTO "team" ("id", "name", "organizationId", "createdAt", "updatedAt")+ VALUES ('team_a', 'Alpha', 'org_1', '2026-01-01', '2026-01-02');+ INSERT INTO "teamMember" ("id", "teamId", "userId", "createdAt")+ VALUES ('tm_old', 'team_a', 'member_1', '2026-01-01');+ INSERT INTO "team_site_access" ("team_id", "site_id") VALUES ('team_a', 1);+ `);+ });++ it("replaces supplied fields and invalidates both removed and added members", async () => {+ const reply = replyStub();++ await updateTeam(+ requestStub({+ params: { organizationId: "org_1", teamId: "team_a" },+ body: { name: " Renamed ", memberUserIds: ["member_2"], siteIds: [2] },+ }),+ reply+ );++ expect(reply.statusCode).toBe(200);+ expect(reply.body).toEqual({ success: true });+ expect(await rows(`SELECT name FROM team WHERE id = 'team_a'`)).toEqual([{ name: "Renamed" }]);+ expect(await rows(`SELECT "userId" FROM "teamMember" WHERE "teamId" = 'team_a'`)).toEqual([{ userId: "member_2" }]);+ expect(await rows(`SELECT site_id FROM team_site_access WHERE team_id = 'team_a'`)).toEqual([{ site_id: 2 }]);+ expect(mocks.invalidateSitesAccessCache).toHaveBeenCalledTimes(2);+ expect(mocks.invalidateSitesAccessCache.mock.calls).toEqual(expect.arrayContaining([["member_1"], ["member_2"]]));+ });++ it("preserves members and sites when those fields are omitted", async () => {+ const reply = replyStub();++ await updateTeam(+ requestStub({ params: { organizationId: "org_1", teamId: "team_a" }, body: { name: "Renamed" } }),+ reply+ );++ expect(await rows(`SELECT "userId" FROM "teamMember"`)).toEqual([{ userId: "member_1" }]);+ expect(await rows(`SELECT site_id FROM team_site_access`)).toEqual([{ site_id: 1 }]);+ expect(mocks.invalidateSitesAccessCache).toHaveBeenCalledOnce();+ expect(mocks.invalidateSitesAccessCache).toHaveBeenCalledWith("member_1");+ });++ it("clears members and sites when supplied empty arrays", async () => {+ const reply = replyStub();++ await updateTeam(+ requestStub({+ params: { organizationId: "org_1", teamId: "team_a" },+ body: { memberUserIds: [], siteIds: [] },+ }),+ reply+ );++ expect(await rows(`SELECT * FROM "teamMember"`)).toEqual([]);+ expect(await rows(`SELECT * FROM team_site_access`)).toEqual([]);+ expect(mocks.invalidateSitesAccessCache).toHaveBeenCalledWith("member_1");+ });++ it("returns 404 for a missing team or a team in another organization", async () => {+ for (const params of [+ { organizationId: "org_1", teamId: "missing" },+ { organizationId: "org_2", teamId: "team_a" },+ ]) {+ const reply = replyStub();+ await updateTeam(requestStub({ params, body: { name: "Nope" } }), reply);+ expect(reply.statusCode).toBe(404);+ expect(reply.body).toEqual({ error: "Team not found" });+ }+ expect(await rows(`SELECT name FROM team WHERE id = 'team_a'`)).toEqual([{ name: "Alpha" }]);+ });++ it("rejects members and sites outside the organization without mutating the team", async () => {+ const memberReply = replyStub();+ await updateTeam(+ requestStub({+ params: { organizationId: "org_1", teamId: "team_a" },+ body: { name: "Nope", memberUserIds: ["outsider"] },+ }),+ memberReply+ );+ expect(memberReply.statusCode).toBe(400);+ expect(memberReply.body).toEqual({ error: "Users not in organization: outsider" });++ const siteReply = replyStub();+ await updateTeam(+ requestStub({+ params: { organizationId: "org_1", teamId: "team_a" },+ body: { name: "Nope", siteIds: [3] },+ }),+ siteReply+ );+ expect(siteReply.statusCode).toBe(400);+ expect(siteReply.body).toEqual({ error: "Sites not in organization: 3" });+ expect(await rows(`SELECT name FROM team WHERE id = 'team_a'`)).toEqual([{ name: "Alpha" }]);+ });++ it("returns 500 and logs database failures", async () => {+ const request = requestStub({ params: { organizationId: "org_1", teamId: "team_a" } });+ const reply = replyStub();+ vi.spyOn(db, "select").mockImplementationOnce(() => {+ throw new Error("database offline");+ });++ await updateTeam(request, reply);++ expect(reply.statusCode).toBe(500);+ expect(reply.body).toEqual({ error: "Failed to update team" });+ expect(request.log.error).toHaveBeenCalledWith({ err: expect.any(Error) }, "Error updating team");+ });+});++describe("deleteTeam", () => {+ beforeEach(async () => {+ await (pgClient as any).exec(`+ INSERT INTO "team" ("id", "name", "organizationId", "createdAt")+ VALUES ('team_a', 'Alpha', 'org_1', '2026-01-01');+ INSERT INTO "teamMember" ("id", "teamId", "userId") VALUES+ ('tm_1', 'team_a', 'member_1'), ('tm_2', 'team_a', 'member_2');+ INSERT INTO "team_site_access" ("team_id", "site_id") VALUES ('team_a', 1);+ `);+ });++ it("deletes the team with cascading relationships and invalidates affected users", async () => {+ const reply = replyStub();++ await deleteTeam(requestStub({ params: { organizationId: "org_1", teamId: "team_a" } }), reply);++ expect(reply.statusCode).toBe(200);+ expect(reply.body).toEqual({ success: true });+ expect(await rows(`SELECT * FROM team`)).toEqual([]);+ expect(await rows(`SELECT * FROM "teamMember"`)).toEqual([]);+ expect(await rows(`SELECT * FROM team_site_access`)).toEqual([]);+ expect(mocks.invalidateSitesAccessCache.mock.calls).toEqual([["member_1"], ["member_2"]]);+ });++ it("does not expose or delete a team through the wrong organization", async () => {+ const reply = replyStub();++ await deleteTeam(requestStub({ params: { organizationId: "org_2", teamId: "team_a" } }), reply);++ expect(reply.statusCode).toBe(404);+ expect(reply.body).toEqual({ error: "Team not found" });+ expect(await rows(`SELECT id FROM team`)).toEqual([{ id: "team_a" }]);+ expect(mocks.invalidateSitesAccessCache).not.toHaveBeenCalled();+ });++ it("returns 500 and logs database failures", async () => {+ const request = requestStub({ params: { organizationId: "org_1", teamId: "team_a" } });+ const reply = replyStub();+ vi.spyOn(db, "select").mockImplementationOnce(() => {+ throw new Error("database offline");+ });++ await deleteTeam(request, reply);++ expect(reply.statusCode).toBe(500);+ expect(reply.body).toEqual({ error: "Failed to delete team" });+ expect(request.log.error).toHaveBeenCalledWith({ err: expect.any(Error) }, "Error deleting team");+ });+});diff --git a/server/src/services/onboardingTips/onboardingTipsService.test.ts b/server/src/services/onboardingTips/onboardingTipsService.test.tsnew file mode 100644index 000000000..4acce3251--- /dev/null+++ b/server/src/services/onboardingTips/onboardingTipsService.test.ts@@ -0,0 +1,117 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { ONBOARDING_TIPS } from "./onboardingTipsContent.js";++const mocks = vi.hoisted(() => ({+ schedule: vi.fn(),+ cancel: vi.fn(),+}));++vi.mock("../../lib/email/email.js", () => ({+ scheduleOnboardingTipEmail: mocks.schedule,+ cancelScheduledEmail: mocks.cancel,+}));++import { onboardingTipsService } from "./onboardingTipsService.js";++beforeEach(() => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date("2026-08-29T15:45:30.123Z"));+ mocks.schedule.mockReset();+ mocks.cancel.mockReset();+});++afterEach(() => {+ vi.useRealTimers();+});++describe("onboardingTipsService.scheduleOnboardingEmails", () => {+ it("schedules every configured tip for 9am UTC on its signup-relative day", async () => {+ mocks.schedule.mockImplementation(async (_email, _name, tip) => `email-day-${tip.day}`);++ await expect(onboardingTipsService.scheduleOnboardingEmails("[email protected]", "Ada")).resolves.toEqual(+ ONBOARDING_TIPS.map(tip => `email-day-${tip.day}`)+ );++ expect(mocks.schedule).toHaveBeenCalledTimes(ONBOARDING_TIPS.length);+ const expectedSchedule = [+ "2026-08-30T09:00:00.000Z",+ "2026-08-31T09:00:00.000Z",+ "2026-09-01T09:00:00.000Z",+ "2026-09-02T09:00:00.000Z",+ "2026-09-03T09:00:00.000Z",+ ];+ for (const [index, tip] of ONBOARDING_TIPS.entries()) {+ expect(mocks.schedule).toHaveBeenNthCalledWith(+ index + 1,+ "[email protected]",+ "Ada",+ tip,+ expectedSchedule[index]+ );+ }+ });++ it("passes an empty display name and omits provider calls that return no id", async () => {+ mocks.schedule+ .mockResolvedValueOnce("email-1")+ .mockResolvedValueOnce(null)+ .mockResolvedValueOnce("email-3")+ .mockResolvedValue(null);++ await expect(onboardingTipsService.scheduleOnboardingEmails("[email protected]")).resolves.toEqual([+ "email-1",+ "email-3",+ ]);+ expect(mocks.schedule.mock.calls.every(call => call[1] === "")).toBe(true);+ expect(mocks.schedule).toHaveBeenCalledTimes(ONBOARDING_TIPS.length);+ });++ it("propagates a scheduling failure and does not schedule later tips", async () => {+ const providerError = new Error("provider unavailable");+ mocks.schedule.mockResolvedValueOnce("email-1").mockRejectedValueOnce(providerError);++ await expect(onboardingTipsService.scheduleOnboardingEmails("[email protected]", "Ada")).rejects.toBe(+ providerError+ );+ expect(mocks.schedule).toHaveBeenCalledTimes(2);+ });++ it("keeps results isolated across overlapping scheduling requests", async () => {+ mocks.schedule.mockImplementation(async (email, _name, tip) => `${email}:day-${tip.day}`);++ const [adaIds, graceIds] = await Promise.all([+ onboardingTipsService.scheduleOnboardingEmails("[email protected]", "Ada"),+ onboardingTipsService.scheduleOnboardingEmails("[email protected]", "Grace"),+ ]);++ expect(adaIds).toEqual(ONBOARDING_TIPS.map(tip => `[email protected]:day-${tip.day}`));+ expect(graceIds).toEqual(ONBOARDING_TIPS.map(tip => `[email protected]:day-${tip.day}`));+ });+});++describe("onboardingTipsService.cancelScheduledEmails", () => {+ it("cancels each provider id in order", async () => {+ mocks.cancel.mockResolvedValue(undefined);++ await expect(+ onboardingTipsService.cancelScheduledEmails(["email-1", "email-2", "email-3"])+ ).resolves.toBeUndefined();++ expect(mocks.cancel.mock.calls).toEqual([["email-1"], ["email-2"], ["email-3"]]);+ });++ it("does nothing for an empty id list", async () => {+ await expect(onboardingTipsService.cancelScheduledEmails([])).resolves.toBeUndefined();+ expect(mocks.cancel).not.toHaveBeenCalled();+ });++ it("stops after the first cancellation failure", async () => {+ const providerError = new Error("cancellation failed");+ mocks.cancel.mockResolvedValueOnce(undefined).mockRejectedValueOnce(providerError);++ await expect(onboardingTipsService.cancelScheduledEmails(["email-1", "email-2", "email-3"])).rejects.toBe(+ providerError+ );+ expect(mocks.cancel.mock.calls).toEqual([["email-1"], ["email-2"]]);+ });+});diff --git a/server/src/services/onboardingTips/onboardingTipsService.ts b/server/src/services/onboardingTips/onboardingTipsService.tsindex 5c328c43b..9405c3515 100644--- a/server/src/services/onboardingTips/onboardingTipsService.ts+++ b/server/src/services/onboardingTips/onboardingTipsService.ts@@ -13,7 +13,7 @@ class OnboardingTipsService {for (const tip of ONBOARDING_TIPS) {// Schedule email for day N at 9am UTC- const scheduledAt = now.plus({ days: tip.day }).set({ hour: 9, minute: 0, second: 0 }).toISO();+ const scheduledAt = now.plus({ days: tip.day }).set({ hour: 9, minute: 0, second: 0, millisecond: 0 }).toISO();if (!scheduledAt) continue;diff --git a/server/src/services/storage/r2StorageService.test.ts b/server/src/services/storage/r2StorageService.test.tsnew file mode 100644index 000000000..b3cd04f25--- /dev/null+++ b/server/src/services/storage/r2StorageService.test.ts@@ -0,0 +1,335 @@+import { gzipSync } from "node:zlib";+import { Readable } from "node:stream";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const state = vi.hoisted(() => ({+ isCloud: true,+}));++const mocks = vi.hoisted(() => ({+ clientConfigs: [] as Record<string, any>[],+ send: vi.fn(),+ httpHandle: vi.fn(),+ compress: vi.fn(),+ decompress: vi.fn(),+ logger: {+ debug: vi.fn(),+ info: vi.fn(),+ },+}));++vi.mock("@aws-sdk/client-s3", () => {+ class Command {+ constructor(public input: Record<string, unknown>) {}+ }++ return {+ S3Client: class {+ send = mocks.send;++ constructor(config: Record<string, any>) {+ mocks.clientConfigs.push(config);+ }+ },+ PutObjectCommand: class extends Command {},+ GetObjectCommand: class extends Command {},+ DeleteObjectCommand: class extends Command {},+ };+});++vi.mock("@smithy/node-http-handler", () => ({+ NodeHttpHandler: class {+ handle = mocks.httpHandle;+ },+}));++vi.mock("@mongodb-js/zstd", () => ({+ compress: mocks.compress,+ decompress: mocks.decompress,+}));++vi.mock("../../lib/const.js", () => ({+ get IS_CLOUD() {+ return state.isCloud;+ },+}));++vi.mock("../../lib/logger/logger.js", () => ({+ createServiceLogger: () => mocks.logger,+}));++async function loadStorage(options: { cloud?: boolean; accessKey?: string; secretKey?: string; bucket?: string } = {}) {+ state.isCloud = options.cloud ?? true;+ vi.stubEnv("R2_ACCOUNT_ID", "account-123");+ vi.stubEnv("R2_ACCESS_KEY_ID", options.accessKey ?? "access-key");+ vi.stubEnv("R2_SECRET_ACCESS_KEY", options.secretKey ?? "secret-key");+ vi.stubEnv("R2_BUCKET_NAME", options.bucket ?? "test-bucket");+ vi.resetModules();++ const { r2Storage } = await import("./r2StorageService.js");+ return r2Storage;+}++function sentInput(call = 0): Record<string, any> {+ return mocks.send.mock.calls[call][0].input;+}++beforeEach(() => {+ state.isCloud = true;+ mocks.clientConfigs.length = 0;+ mocks.send.mockReset();+ mocks.httpHandle.mockReset();+ mocks.compress.mockReset();+ mocks.decompress.mockReset();+ mocks.logger.debug.mockReset();+ mocks.logger.info.mockReset();+ mocks.compress.mockImplementation(async (input: Buffer) => Buffer.concat([Buffer.from("zstd:"), input]));+ mocks.decompress.mockImplementation(async (input: Buffer) => input.subarray("zstd:".length));+ vi.spyOn(console, "error").mockImplementation(() => {});+});++afterEach(() => {+ vi.restoreAllMocks();+ vi.unstubAllEnvs();+});++describe("r2Storage initialization", () => {+ it("stays disabled outside cloud and performs no storage I/O", async () => {+ const storage = await loadStorage({ cloud: false });++ expect(storage.isEnabled()).toBe(false);+ await expect(storage.storeBatch(1, "session", [{ type: "pageview" }])).resolves.toBeNull();+ await expect(storage.getBatch("1/session/batch.json.zst")).rejects.toThrow("R2 storage is not enabled");+ await expect(storage.deleteBatch("1/session/batch.json.zst")).resolves.toBeUndefined();+ expect(mocks.clientConfigs).toHaveLength(0);+ expect(mocks.send).not.toHaveBeenCalled();+ });++ it.each([+ { missing: "access key", accessKey: "", secretKey: "secret-key" },+ { missing: "secret key", accessKey: "access-key", secretKey: "" },+ { missing: "both credentials", accessKey: "", secretKey: "" },+ ])("stays disabled when $missing is missing", async ({ accessKey, secretKey }) => {+ const storage = await loadStorage({ accessKey, secretKey });++ expect(storage.isEnabled()).toBe(false);+ expect(mocks.clientConfigs).toHaveLength(0);+ });++ it("configures the R2 endpoint, credentials, path-style requests, and bucket", async () => {+ const storage = await loadStorage({ bucket: "replay-batches" });++ expect(storage.isEnabled()).toBe(true);+ expect(mocks.clientConfigs).toHaveLength(1);+ expect(mocks.clientConfigs[0]).toMatchObject({+ region: "auto",+ endpoint: "https://account-123.r2.cloudflarestorage.com",+ credentials: { accessKeyId: "access-key", secretAccessKey: "secret-key" },+ forcePathStyle: true,+ });+ expect(mocks.logger.info).toHaveBeenCalledWith({ bucket: "replay-batches" }, "R2Storage initialized");+ });++ it("strips checksum response headers without discarding other handler output", async () => {+ mocks.httpHandle.mockResolvedValue({+ response: {+ statusCode: 200,+ headers: {+ etag: "batch-etag",+ "x-amz-checksum-crc32": "checksum",+ "X-Custom-Checksum": "also-a-checksum",+ },+ },+ output: "preserved",+ });+ await loadStorage();++ const handler = mocks.clientConfigs[0].requestHandler;+ const result = await handler.handle({ method: "GET" }, { requestTimeout: 1_000 });++ expect(mocks.httpHandle).toHaveBeenCalledWith({ method: "GET" }, { requestTimeout: 1_000 });+ expect(result).toEqual({+ response: { statusCode: 200, headers: { etag: "batch-etag" } },+ output: "preserved",+ });+ });+});++describe("r2Storage.storeBatch", () => {+ it("compresses JSON and stores it with a deterministic key and retrieval metadata", async () => {+ vi.spyOn(Date, "now").mockReturnValue(1_725_000_123_456);+ mocks.send.mockResolvedValue({});+ const storage = await loadStorage();+ const events = [+ { type: "pageview", path: "/" },+ { type: "custom_event", name: "signup" },+ ];++ await expect(storage.storeBatch(42, "session/with spaces", events)).resolves.toBe(+ "42/session/with spaces/1725000123456.json.zst"+ );++ expect(mocks.compress).toHaveBeenCalledOnce();+ expect(mocks.compress.mock.calls[0][0].toString()).toBe(JSON.stringify(events));+ expect(mocks.compress.mock.calls[0][1]).toBe(3);+ expect(sentInput()).toMatchObject({+ Bucket: "test-bucket",+ Key: "42/session/with spaces/1725000123456.json.zst",+ ContentType: "application/octet-stream",+ Metadata: {+ siteId: "42",+ sessionId: "session/with spaces",+ eventCount: "2",+ compression: "zstd",+ },+ });+ expect(sentInput().Body).toEqual(Buffer.from(`zstd:${JSON.stringify(events)}`));+ });++ it("supports empty batches and records a zero event count", async () => {+ vi.spyOn(Date, "now").mockReturnValue(100);+ mocks.send.mockResolvedValue({});+ const storage = await loadStorage();++ await expect(storage.storeBatch(0, "empty", [])).resolves.toBe("0/empty/100.json.zst");+ expect(sentInput().Metadata.eventCount).toBe("0");+ });++ it("propagates compression failures without issuing a put", async () => {+ const compressionError = new Error("zstd worker failed");+ mocks.compress.mockRejectedValue(compressionError);+ const storage = await loadStorage();++ await expect(storage.storeBatch(1, "session", [{}])).rejects.toBe(compressionError);+ expect(mocks.send).not.toHaveBeenCalled();+ expect(console.error).toHaveBeenCalledWith("[R2Storage] Failed to store batch:", compressionError);+ });++ it("propagates object-store failures after compression", async () => {+ const putError = new Error("R2 unavailable");+ mocks.send.mockRejectedValue(putError);+ const storage = await loadStorage();++ await expect(storage.storeBatch(1, "session", [{}])).rejects.toBe(putError);+ expect(mocks.compress).toHaveBeenCalledOnce();+ expect(console.error).toHaveBeenCalledWith("[R2Storage] Failed to store batch:", putError);+ });++ it("allows independent stores to progress concurrently", async () => {+ vi.spyOn(Date, "now").mockReturnValue(500);+ let releaseFirst!: (value: Buffer) => void;+ const firstCompression = new Promise<Buffer>(resolve => {+ releaseFirst = resolve;+ });+ mocks.compress.mockImplementationOnce(() => firstCompression).mockResolvedValueOnce(Buffer.from("second"));+ mocks.send.mockResolvedValue({});+ const storage = await loadStorage();++ const first = storage.storeBatch(1, "first", [{ sequence: 1 }]);+ const second = storage.storeBatch(2, "second", [{ sequence: 2 }]);++ await expect(second).resolves.toBe("2/second/500.json.zst");+ expect(mocks.send).toHaveBeenCalledOnce();+ expect(sentInput().Key).toBe("2/second/500.json.zst");++ releaseFirst(Buffer.from("first"));+ await expect(first).resolves.toBe("1/first/500.json.zst");+ expect(mocks.send).toHaveBeenCalledTimes(2);+ });+});++describe("r2Storage.getBatch", () => {+ it("reads already-decompressed JSON streams without invoking a codec", async () => {+ mocks.send.mockResolvedValue({ Body: Readable.from([Buffer.from(" ["), Buffer.from('{"type":"pageview"}]')]) });+ const storage = await loadStorage();++ await expect(storage.getBatch("1/session/batch.json.zst")).resolves.toEqual([{ type: "pageview" }]);+ expect(sentInput()).toEqual({ Bucket: "test-bucket", Key: "1/session/batch.json.zst" });+ expect(mocks.decompress).not.toHaveBeenCalled();+ });++ it("decompresses zstd objects assembled from multiple stream chunks", async () => {+ const compressed = Buffer.from('zstd:[{"type":"identify"}]');+ mocks.send.mockResolvedValue({ Body: Readable.from([compressed.subarray(0, 7), compressed.subarray(7)]) });+ const storage = await loadStorage();++ await expect(storage.getBatch("1/session/batch.json.zst")).resolves.toEqual([{ type: "identify" }]);+ expect(mocks.decompress).toHaveBeenCalledWith(compressed);+ });++ it("uses gzip decompression for legacy .gz objects", async () => {+ const events = [{ type: "pageview", pathname: "/legacy" }];+ mocks.send.mockResolvedValue({ Body: Readable.from([gzipSync(JSON.stringify(events))]) });+ const storage = await loadStorage();++ await expect(storage.getBatch("1/session/legacy.json.gz")).resolves.toEqual(events);+ expect(mocks.decompress).not.toHaveBeenCalled();+ });++ it("defaults unknown extensions to zstd decompression", async () => {+ const compressed = Buffer.from('zstd:[{"type":"custom_event"}]');+ mocks.send.mockResolvedValue({ Body: Readable.from([compressed]) });+ const storage = await loadStorage();++ await expect(storage.getBatch("1/session/batch.bin")).resolves.toEqual([{ type: "custom_event" }]);+ expect(mocks.decompress).toHaveBeenCalledWith(compressed);+ });++ it("falls through from JSON-looking but invalid bytes to decompression", async () => {+ const bytes = Buffer.from("[compressed-zstd-payload");+ mocks.send.mockResolvedValue({ Body: Readable.from([bytes]) });+ mocks.decompress.mockResolvedValue(Buffer.from('[{"recovered":true}]'));+ const storage = await loadStorage();++ await expect(storage.getBatch("1/session/batch.json.zst")).resolves.toEqual([{ recovered: true }]);+ expect(mocks.decompress).toHaveBeenCalledWith(bytes);+ });++ it("rejects empty responses and preserves the retrieval context in the log", async () => {+ mocks.send.mockResolvedValue({});+ const storage = await loadStorage();++ await expect(storage.getBatch("missing.json.zst")).rejects.toThrow("Empty response body");+ expect(console.error).toHaveBeenCalledWith(+ "[R2Storage] Failed to retrieve batch:",+ expect.objectContaining({ message: "Empty response body" })+ );+ });++ it("rethrows the codec error for irrecoverably corrupted objects", async () => {+ const codecError = new Error("invalid zstd frame");+ mocks.send.mockResolvedValue({ Body: Readable.from([Buffer.from("not-json-or-zstd")]) });+ mocks.decompress.mockRejectedValue(codecError);+ const storage = await loadStorage();++ await expect(storage.getBatch("corrupt.json.zst")).rejects.toBe(codecError);+ expect(console.error).toHaveBeenCalledWith("[R2Storage] Failed to retrieve batch:", codecError);+ });++ it("propagates object-store read failures", async () => {+ const getError = new Error("read denied");+ mocks.send.mockRejectedValue(getError);+ const storage = await loadStorage();++ await expect(storage.getBatch("private.json.zst")).rejects.toBe(getError);+ });+});++describe("r2Storage.deleteBatch", () => {+ it("deletes an enabled object's exact key", async () => {+ mocks.send.mockResolvedValue({});+ const storage = await loadStorage();++ await expect(storage.deleteBatch("1/session/batch.json.zst")).resolves.toBeUndefined();+ expect(sentInput()).toEqual({ Bucket: "test-bucket", Key: "1/session/batch.json.zst" });+ });++ it("logs and suppresses cleanup failures", async () => {+ const deleteError = new Error("temporary delete failure");+ mocks.send.mockRejectedValue(deleteError);+ const storage = await loadStorage();++ await expect(storage.deleteBatch("1/session/batch.json.zst")).resolves.toBeUndefined();+ expect(console.error).toHaveBeenCalledWith("[R2Storage] Failed to delete batch:", deleteError);+ });+});