Open-source status page, incident response and uptime monitoring
TypeScript alertingincident-managementmcpmcp-servermonitoringmonitoring-as-codeobservabilityon-callopen-sourcesrestatus-pagestatuspagesynthetic-monitoringterraformtinybirdtursouptimeuptime-checkeruptime-monitor
Fix test para (#2463)
Thibault Le Ouaybaa46b270115
diff --git a/.github/workflows/test.yml b/.github/workflows/test.ymlindex 915d6aa7e..9e5c5fac7 100644--- a/.github/workflows/test.yml+++ b/.github/workflows/test.yml@@ -7,18 +7,49 @@ on:pull_request:branches: [main]+permissions:+ contents: read+jobs:- tests:- name: π§ͺ Tests+ # Every DB-touching package gets its own job, and therefore its own sqld+ # container. Sharing one database across turbo tasks let suites clobber each+ # other's rows (see docs/adr/0008-isolated-test-databases.md).+ test:+ name: π§ͺ ${{ matrix.name }}runs-on: ubuntu-latesttimeout-minutes: 15+ strategy:+ fail-fast: false+ matrix:+ include:+ - name: services+ filter: "--filter=@openstatus/services"+ database: true+ - name: server+ filter: "--filter=@openstatus/server"+ database: true+ - name: api+ filter: "--filter=@openstatus/api"+ database: true+ - name: workflows+ filter: "--filter=@openstatus/workflows"+ database: true+ - name: subscriptions+ filter: "--filter=@openstatus/subscriptions"+ database: true+ - name: rest+ filter: >-+ --filter=!@openstatus/services+ --filter=!@openstatus/server+ --filter=!@openstatus/api+ --filter=!@openstatus/workflows+ --filter=!@openstatus/subscriptions+ database: falseservices:sqld:image: ghcr.io/tursodatabase/libsql-server:e4beacaports:- 8080:8080- # env:- # SQLD_HTTP_AUTH: "basic:token"env:TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}@@ -47,12 +78,29 @@ jobs:run: pnpm install- name: ποΈ Run migrations+ if: matrix.databaserun: pnpm migrateworking-directory: ./packages/db- - name: π½ Seed database+ - name: π½ Seed database+ if: matrix.databaserun: pnpm seedworking-directory: ./packages/db- name: π§ͺ Tests- run: pnpm test+ run: pnpm turbo run test ${{ matrix.filter }}++ # Single required status check, so branch protection does not need to list+ # every matrix leg.+ tests:+ name: π§ͺ Tests+ runs-on: ubuntu-latest+ needs: test+ if: always()+ steps:+ - name: Check matrix result+ run: |+ if [ "${{ needs.test.result }}" != "success" ]; then+ echo "One or more test jobs failed."+ exit 1+ fidiff --git a/apps/server/package.json b/apps/server/package.jsonindex 5dce51fb5..ea95d9a9d 100644--- a/apps/server/package.json+++ b/apps/server/package.json@@ -8,7 +8,7 @@"env": "deno run -A env.ts","dev": "deno run -A --watch --sloppy-imports src/serve.ts","start": "NODE_ENV=production deno run -A --sloppy-imports src/serve.ts",- "test": "deno test --parallel -A --no-check --sloppy-imports --env-file=.env.test --import-map=test.importmap.json --ignore=src/routes/slack && deno test -A --no-check --sloppy-imports --env-file=.env.test --import-map=test.importmap.json src/routes/slack",+ "test": "deno test --parallel -A --no-check --sloppy-imports --env-file=.env.test --import-map=test.importmap.json","check": "deno check --sloppy-imports src/serve.ts","eval:mcp": "deno run -A --sloppy-imports src/routes/mcp/evals/run.ts"},diff --git a/apps/server/src/libs/test/slack-config.ts b/apps/server/src/libs/test/slack-config.tsnew file mode 100644index 000000000..fbaa6188a--- /dev/null+++ b/apps/server/src/libs/test/slack-config.ts@@ -0,0 +1,28 @@+import type { Hono } from "hono";++import type { SlackConfig, SlackEnv } from "@/routes/slack/config";++export const TEST_SIGNING_SECRET = "test-signing-secret";++export const TEST_SLACK_CONFIG: SlackConfig = {+ signingSecret: TEST_SIGNING_SECRET,+ clientId: "test-client-id",+ clientSecret: "test-client-secret",+ aiGatewayApiKey: "test-key",+ dashboardUrl: "http://localhost:3000",+};++/**+ * Put the slack config on the context, the way `createSlackRoute`'s middleware+ * does, for suites that mount individual handlers instead of the whole route.+ */+export function withSlackConfig<T extends Hono<SlackEnv>>(+ app: T,+ overrides: Partial<SlackConfig> = {},+): T {+ app.use("*", async (c, next) => {+ c.set("slackConfig", { ...TEST_SLACK_CONFIG, ...overrides });+ await next();+ });+ return app;+}diff --git a/apps/server/src/routes/mcp/tools/tools.test.ts b/apps/server/src/routes/mcp/tools/tools.test.tsindex 34e5bde65..c3b38ac9b 100644--- a/apps/server/src/routes/mcp/tools/tools.test.ts+++ b/apps/server/src/routes/mcp/tools/tools.test.ts@@ -10,13 +10,10 @@ import {} from "@openstatus/db/src/schema";import type { Scope, Workspace } from "@openstatus/db/src/schema";import type { ServiceContext } from "@openstatus/services";-import {- SEEDED_WORKSPACE_FREE_ID,- SEEDED_WORKSPACE_TEAM_ID,-} from "@openstatus/services/test/fixtures";+import { SEEDED_WORKSPACE_FREE_ID } from "@openstatus/services/test/fixtures";import {expectAuditRow,- loadSeededWorkspace,+ createWorkspaceFixture,readAuditLog,withTestTransaction,} from "@openstatus/services/test/helpers";@@ -65,7 +62,7 @@ let testPageId: number;let testPageComponentId: number;beforeAll(async () => {- teamWorkspace = await loadSeededWorkspace(SEEDED_WORKSPACE_TEAM_ID);+ teamWorkspace = (await createWorkspaceFixture("team")).workspace;const pageRow = await db.insert(page).values({diff --git a/apps/server/src/routes/rpc/adapter.test.ts b/apps/server/src/routes/rpc/adapter.test.tsindex 381bfa331..7ca83d40c 100644--- a/apps/server/src/routes/rpc/adapter.test.ts+++ b/apps/server/src/routes/rpc/adapter.test.ts@@ -7,9 +7,8 @@ import {ValidationError,} from "@openstatus/services";import { createApiKey } from "@openstatus/services/api-key";-import { SEEDED_WORKSPACE_TEAM_ID } from "@openstatus/services/test/fixtures";import {- loadSeededWorkspace,+ createWorkspaceFixture,withTestTransaction,} from "@openstatus/services/test/helpers";import { expect } from "@std/expect";@@ -119,7 +118,7 @@ describe("RPC runtime β read-only key on a write service verb", () => {let teamWorkspace: Workspace;beforeAll(async () => {- teamWorkspace = await loadSeededWorkspace(SEEDED_WORKSPACE_TEAM_ID);+ teamWorkspace = (await createWorkspaceFixture("team")).workspace;});test("throws ForbiddenError β ConnectError(PermissionDenied)", async () => {diff --git a/apps/server/src/routes/rpc/handlers/maintenance/__tests__/maintenance.test.ts b/apps/server/src/routes/rpc/handlers/maintenance/__tests__/maintenance.test.tsindex bfedbb0de..5f8f6f0df 100644--- a/apps/server/src/routes/rpc/handlers/maintenance/__tests__/maintenance.test.ts+++ b/apps/server/src/routes/rpc/handlers/maintenance/__tests__/maintenance.test.ts@@ -7,6 +7,7 @@ import {pageSubscriber,workspace,} from "@openstatus/db/src/schema";+import { createTestWorkspace } from "@openstatus/db/src/test/factories";import { mock } from "@openstatus/test-utils";import { expect } from "@std/expect";import { afterAll, beforeAll, describe, test } from "@std/testing/bdd";@@ -61,7 +62,14 @@ let testSubscriberId: number;let testPage2Id: number;let testPage2ComponentId: number;+// A second, free-plan workspace: used both for cross-workspace isolation+// assertions and for the plan-limit rejections. Private to this suite because+// sibling suites assert the seeded free workspace owns nothing.+let OTHER_WORKSPACE_ID: number;+beforeAll(async () => {+ OTHER_WORKSPACE_ID = (await createTestWorkspace({ plan: "free" })).workspace+ .id;const ws = await db.insert(workspace).values({@@ -689,7 +697,7 @@ describe("MaintenanceService.GetMaintenance", () => {const otherRecord = await db.insert(maintenance).values({- workspaceId: 2,+ workspaceId: OTHER_WORKSPACE_ID,title: `${TEST_PREFIX}-other-workspace`,message: "Other workspace maintenance",from: new Date(Date.now() + 24 * 60 * 60 * 1000),@@ -845,7 +853,7 @@ describe("MaintenanceService.ListMaintenances", () => {const otherRecord = await db.insert(maintenance).values({- workspaceId: 2,+ workspaceId: OTHER_WORKSPACE_ID,title: `${TEST_PREFIX}-other-workspace-list`,message: "Other workspace maintenance",from: new Date(Date.now() + 24 * 60 * 60 * 1000),@@ -984,7 +992,7 @@ describe("MaintenanceService.UpdateMaintenance", () => {const otherRecord = await db.insert(maintenance).values({- workspaceId: 2,+ workspaceId: OTHER_WORKSPACE_ID,title: `${TEST_PREFIX}-other-workspace-update`,message: "Other workspace maintenance",from: new Date(Date.now() + 24 * 60 * 60 * 1000),@@ -1300,7 +1308,7 @@ describe("MaintenanceService.DeleteMaintenance", () => {const otherRecord = await db.insert(maintenance).values({- workspaceId: 2,+ workspaceId: OTHER_WORKSPACE_ID,title: `${TEST_PREFIX}-other-workspace-delete`,message: "Other workspace maintenance",from: new Date(Date.now() + 24 * 60 * 60 * 1000),diff --git a/apps/server/src/routes/rpc/handlers/monitor/__tests__/monitor.test.ts b/apps/server/src/routes/rpc/handlers/monitor/__tests__/monitor.test.tsindex 494bf93f0..098e2e804 100644--- a/apps/server/src/routes/rpc/handlers/monitor/__tests__/monitor.test.ts+++ b/apps/server/src/routes/rpc/handlers/monitor/__tests__/monitor.test.ts@@ -8,6 +8,7 @@ import {workspace,} from "@openstatus/db/src/schema";import { monitorStatusTable } from "@openstatus/db/src/schema/monitor_status/monitor_status";+import { createTestWorkspace } from "@openstatus/db/src/test/factories";import {createMonitor,createWorkspace,@@ -43,7 +44,7 @@ async function connectRequest(}const TEST_PREFIX = "rpc-monitor-test";-const FREE_PLAN_KEY = "2";+let FREE_PLAN_KEY: string;let testHttpMonitorId: number;let testTcpMonitorId: number;let testDnsMonitorId: number;@@ -105,7 +106,15 @@ beforeEach(() => {calls.httpGetBiweekly = [];});+// A second, free-plan workspace: used both for cross-workspace isolation+// assertions and for the plan-limit rejections. Private to this suite because+// sibling suites assert the seeded free workspace owns nothing.+let OTHER_WORKSPACE_ID: number;+beforeAll(async () => {+ OTHER_WORKSPACE_ID = (await createTestWorkspace({ plan: "free" })).workspace+ .id;+ FREE_PLAN_KEY = String(OTHER_WORKSPACE_ID);// Clean up any existing test dataawait db.delete(monitor).where(eq(monitor.name, `${TEST_PREFIX}-http`));await db.delete(monitor).where(eq(monitor.name, `${TEST_PREFIX}-tcp`));@@ -423,7 +432,7 @@ describe("MonitorService.ListMonitors", () => {const otherWorkspaceMon = await db.insert(monitor).values({- workspaceId: 2,+ workspaceId: OTHER_WORKSPACE_ID,name: `${TEST_PREFIX}-other-workspace`,url: "https://other-workspace.example.com",periodicity: "1m",@@ -1748,7 +1757,6 @@ describe("MonitorService - Default Values", () => {});describe("MonitorService - Limits", () => {- // Workspace 2 has free plan with limited periodicity (10m, 30m, 1h) and max 6 regionstest("returns error when periodicity is not allowed by plan", async () => {// Free plan only allows 10m, 30m, 1h - PERIODICITY_30S is not allowedconst res = await connectRequest(@@ -1868,7 +1876,7 @@ describe("MonitorService - Limits", () => {return db.insert(monitor).values({- workspaceId: 2,+ workspaceId: OTHER_WORKSPACE_ID,name: `${TEST_PREFIX}-at-cap-${suffix}`,url: `https://at-cap-${suffix}.example.com`,periodicity: "10m",@@ -2209,7 +2217,7 @@ describe("MonitorService.GetMonitorStatus", () => {const otherWorkspaceMon = await db.insert(monitor).values({- workspaceId: 2,+ workspaceId: OTHER_WORKSPACE_ID,name: `${TEST_PREFIX}-status-other-ws`,url: "https://other-ws-status.example.com",periodicity: "1m",@@ -2355,7 +2363,7 @@ describe("MonitorService.GetMonitor", () => {const otherWorkspaceMon = await db.insert(monitor).values({- workspaceId: 2,+ workspaceId: OTHER_WORKSPACE_ID,name: `${TEST_PREFIX}-get-other-ws`,url: "https://other-ws-get.example.com",periodicity: "1m",@@ -2699,7 +2707,7 @@ describe("MonitorService.GetMonitorSummary", () => {const otherWorkspaceMon = await db.insert(monitor).values({- workspaceId: 2,+ workspaceId: OTHER_WORKSPACE_ID,name: `${TEST_PREFIX}-summary-other-ws`,url: "https://other-ws-summary.example.com",periodicity: "1m",@@ -2812,7 +2820,7 @@ describe("MonitorService.ListMonitorHTTPResponseLogs", () => {const otherWorkspaceMon = await db.insert(monitor).values({- workspaceId: 2,+ workspaceId: OTHER_WORKSPACE_ID,name: `${TEST_PREFIX}-response-logs-other-ws`,url: "https://other-ws-response-logs.example.com",periodicity: "1m",@@ -2921,7 +2929,7 @@ describe("MonitorService.GetMonitorHTTPResponseLog", () => {const otherWorkspaceMon = await db.insert(monitor).values({- workspaceId: 2,+ workspaceId: OTHER_WORKSPACE_ID,name: `${TEST_PREFIX}-response-log-detail-other-ws`,url: "https://other-ws-response-log-detail.example.com",periodicity: "1m",diff --git a/apps/server/src/routes/rpc/handlers/notification/__tests__/notification.test.ts b/apps/server/src/routes/rpc/handlers/notification/__tests__/notification.test.tsindex bf640a35a..856b43e61 100644--- a/apps/server/src/routes/rpc/handlers/notification/__tests__/notification.test.ts+++ b/apps/server/src/routes/rpc/handlers/notification/__tests__/notification.test.ts@@ -3,6 +3,7 @@ import {notification,notificationsToMonitors,} from "@openstatus/db/src/schema";+import { createTestWorkspace } from "@openstatus/db/src/test/factories";import { expect } from "@std/expect";import { afterAll, beforeAll, describe, test } from "@std/testing/bdd";@@ -35,7 +36,14 @@ let testNotificationId: number;let testNotificationToDeleteId: number;let testNotificationToUpdateId: number;+// A second, free-plan workspace: used both for cross-workspace isolation+// assertions and for the plan-limit rejections. Private to this suite because+// sibling suites assert the seeded free workspace owns nothing.+let OTHER_WORKSPACE_ID: number;+beforeAll(async () => {+ OTHER_WORKSPACE_ID = (await createTestWorkspace({ plan: "free" })).workspace+ .id;// Clean up any existing test dataawait db.delete(notification)@@ -347,7 +355,7 @@ describe("NotificationService.GetNotification", () => {const otherRecord = await db.insert(notification).values({- workspaceId: 2,+ workspaceId: OTHER_WORKSPACE_ID,name: `${TEST_PREFIX}-other-workspace`,provider: "email",data: JSON.stringify({ email: "[email protected]" }),@@ -475,7 +483,7 @@ describe("NotificationService.ListNotifications", () => {const otherRecord = await db.insert(notification).values({- workspaceId: 2,+ workspaceId: OTHER_WORKSPACE_ID,name: `${TEST_PREFIX}-other-workspace-list`,provider: "email",data: JSON.stringify({ email: "[email protected]" }),@@ -597,7 +605,7 @@ describe("NotificationService.UpdateNotification", () => {const otherRecord = await db.insert(notification).values({- workspaceId: 2,+ workspaceId: OTHER_WORKSPACE_ID,name: `${TEST_PREFIX}-other-workspace-update`,provider: "email",data: JSON.stringify({ email: "[email protected]" }),@@ -754,7 +762,7 @@ describe("NotificationService.DeleteNotification", () => {const otherRecord = await db.insert(notification).values({- workspaceId: 2,+ workspaceId: OTHER_WORKSPACE_ID,name: `${TEST_PREFIX}-other-workspace-delete`,provider: "email",data: JSON.stringify({ email: "[email protected]" }),diff --git a/apps/server/src/routes/rpc/handlers/status-page/__tests__/status-page.test.ts b/apps/server/src/routes/rpc/handlers/status-page/__tests__/status-page.test.tsindex 20799f045..136eab79a 100644--- a/apps/server/src/routes/rpc/handlers/status-page/__tests__/status-page.test.ts+++ b/apps/server/src/routes/rpc/handlers/status-page/__tests__/status-page.test.ts@@ -9,6 +9,7 @@ import {statusReport,statusReportsToPageComponents,} from "@openstatus/db/src/schema";+import { createTestWorkspace } from "@openstatus/db/src/test/factories";import { mock } from "@openstatus/test-utils";import { expect } from "@std/expect";import { afterAll, beforeAll, describe, test } from "@std/testing/bdd";@@ -53,7 +54,14 @@ let testSubscriberId: number;let testPasswordPageId: number;let testPasswordPageSlug: string;+// A second, free-plan workspace: used both for cross-workspace isolation+// assertions and for the plan-limit rejections. Private to this suite because+// sibling suites assert the seeded free workspace owns nothing.+let OTHER_WORKSPACE_ID: number;+beforeAll(async () => {+ OTHER_WORKSPACE_ID = (await createTestWorkspace({ plan: "free" })).workspace+ .id;// Enable plan features needed for testsawait db.run(sql`UPDATE workspace SET limits = json_set(COALESCE(limits, '{}'), '$."email-domain-protection"', json('true')) WHERE id = 1`,@@ -395,12 +403,11 @@ describe("StatusPageService.CreateStatusPage", () => {});test("returns 403 when status page limit is exceeded", async () => {- // Workspace 2 is on free plan with status-pages limit of 1// First, create a page for workspace 2 to hit the limitconst firstPage = await db.insert(page).values({- workspaceId: 2,+ workspaceId: OTHER_WORKSPACE_ID,title: `${TEST_PREFIX}-limit-test`,slug: `${TEST_PREFIX}-limit-test-slug`,description: "First page for limit test",@@ -418,7 +425,7 @@ describe("StatusPageService.CreateStatusPage", () => {description: "Should fail due to limit",slug: `${TEST_PREFIX}-limit-exceeded-slug`,},- { "x-openstatus-key": "2" },+ { "x-openstatus-key": String(OTHER_WORKSPACE_ID) },);expect(res.status).toBe(403); // PermissionDenied@@ -461,7 +468,7 @@ describe("StatusPageService.CreateStatusPage", () => {slug: `${TEST_PREFIX}-custom-theme-denied-slug`,customTheme: { light: { "--primary": "red" } },},- { "x-openstatus-key": "2" },+ { "x-openstatus-key": String(OTHER_WORKSPACE_ID) },);expect(res.status).toBe(403);@@ -520,7 +527,7 @@ describe("StatusPageService.GetStatusPage", () => {const otherPage = await db.insert(page).values({- workspaceId: 2,+ workspaceId: OTHER_WORKSPACE_ID,title: `${TEST_PREFIX}-other-workspace`,slug: `${TEST_PREFIX}-other-workspace-slug`,description: "Other workspace page",@@ -596,7 +603,7 @@ describe("StatusPageService.GetPageComponent", () => {const otherPage = await db.insert(page).values({- workspaceId: 2,+ workspaceId: OTHER_WORKSPACE_ID,title: `${TEST_PREFIX}-other-workspace-component`,slug: `${TEST_PREFIX}-other-workspace-component-slug`,description: "Other workspace page",@@ -608,7 +615,7 @@ describe("StatusPageService.GetPageComponent", () => {const otherComponent = await db.insert(pageComponent).values({- workspaceId: 2,+ workspaceId: OTHER_WORKSPACE_ID,pageId: otherPage.id,type: "static",name: `${TEST_PREFIX}-other-workspace-component`,@@ -1021,7 +1028,7 @@ describe("StatusPageService.UpdateStatusPage", () => {const freePage = await db.insert(page).values({- workspaceId: 2,+ workspaceId: OTHER_WORKSPACE_ID,title: `${TEST_PREFIX}-free-theme`,slug: `${TEST_PREFIX}-free-theme-slug`,description: "",@@ -1037,7 +1044,7 @@ describe("StatusPageService.UpdateStatusPage", () => {id: String(freePage.id),customTheme: { light: { "--primary": "red" } },},- { "x-openstatus-key": "2" },+ { "x-openstatus-key": String(OTHER_WORKSPACE_ID) },);expect(res.status).toBe(403);@@ -1312,7 +1319,7 @@ describe("StatusPageService i18n plan limits", () => {slug: `${TEST_PREFIX}-i18n-limit-create-slug`,defaultLocale: "LOCALE_DE",},- { "x-openstatus-key": "2" },+ { "x-openstatus-key": String(OTHER_WORKSPACE_ID) },);expect(res.status).toBe(403);@@ -1329,7 +1336,7 @@ describe("StatusPageService i18n plan limits", () => {slug: `${TEST_PREFIX}-i18n-limit-create-slug`,locales: ["LOCALE_EN", "LOCALE_FR"],},- { "x-openstatus-key": "2" },+ { "x-openstatus-key": String(OTHER_WORKSPACE_ID) },);expect(res.status).toBe(403);@@ -1343,7 +1350,7 @@ describe("StatusPageService i18n plan limits", () => {const testPage = await db.insert(page).values({- workspaceId: 2,+ workspaceId: OTHER_WORKSPACE_ID,title: `${TEST_PREFIX}-i18n-limit-update`,slug: `${TEST_PREFIX}-i18n-limit-update-slug`,description: "",@@ -1359,7 +1366,7 @@ describe("StatusPageService i18n plan limits", () => {id: String(testPage.id),defaultLocale: "LOCALE_FR",},- { "x-openstatus-key": "2" },+ { "x-openstatus-key": String(OTHER_WORKSPACE_ID) },);expect(res.status).toBe(403);@@ -1376,7 +1383,7 @@ describe("StatusPageService i18n plan limits", () => {const testPage = await db.insert(page).values({- workspaceId: 2,+ workspaceId: OTHER_WORKSPACE_ID,title: `${TEST_PREFIX}-i18n-limit-update`,slug: `${TEST_PREFIX}-i18n-limit-update-slug`,description: "",@@ -1392,7 +1399,7 @@ describe("StatusPageService i18n plan limits", () => {id: String(testPage.id),locales: ["LOCALE_EN", "LOCALE_FR"],},- { "x-openstatus-key": "2" },+ { "x-openstatus-key": String(OTHER_WORKSPACE_ID) },);expect(res.status).toBe(403);@@ -1585,7 +1592,7 @@ describe("StatusPageService.AddMonitorComponent", () => {const limitTestPage = await db.insert(page).values({- workspaceId: 2,+ workspaceId: OTHER_WORKSPACE_ID,title: `${TEST_PREFIX}-component-limit-test`,slug: `${TEST_PREFIX}-component-limit-test-slug`,description: "Page for component limit test",@@ -1598,7 +1605,7 @@ describe("StatusPageService.AddMonitorComponent", () => {const limitTestMonitor = await db.insert(monitor).values({- workspaceId: 2,+ workspaceId: OTHER_WORKSPACE_ID,name: `${TEST_PREFIX}-limit-monitor`,url: "https://example.com",periodicity: "1m",@@ -1614,7 +1621,7 @@ describe("StatusPageService.AddMonitorComponent", () => {const component = await db.insert(pageComponent).values({- workspaceId: 2,+ workspaceId: OTHER_WORKSPACE_ID,pageId: limitTestPage.id,type: "static",name: `${TEST_PREFIX}-limit-component-${i}`,@@ -1634,7 +1641,7 @@ describe("StatusPageService.AddMonitorComponent", () => {monitorId: String(limitTestMonitor.id),name: `${TEST_PREFIX}-limit-exceeded-component`,},- { "x-openstatus-key": "2" },+ { "x-openstatus-key": String(OTHER_WORKSPACE_ID) },);expect(res.status).toBe(403); // PermissionDenied@@ -1707,7 +1714,7 @@ describe("StatusPageService.AddStaticComponent", () => {const limitTestPage = await db.insert(page).values({- workspaceId: 2,+ workspaceId: OTHER_WORKSPACE_ID,title: `${TEST_PREFIX}-static-limit-test`,slug: `${TEST_PREFIX}-static-limit-test-slug`,description: "Page for static component limit test",@@ -1722,7 +1729,7 @@ describe("StatusPageService.AddStaticComponent", () => {const component = await db.insert(pageComponent).values({- workspaceId: 2,+ workspaceId: OTHER_WORKSPACE_ID,pageId: limitTestPage.id,type: "static",name: `${TEST_PREFIX}-static-limit-component-${i}`,@@ -1742,7 +1749,7 @@ describe("StatusPageService.AddStaticComponent", () => {name: `${TEST_PREFIX}-static-limit-exceeded`,description: "Should fail due to limit",},- { "x-openstatus-key": "2" },+ { "x-openstatus-key": String(OTHER_WORKSPACE_ID) },);expect(res.status).toBe(403); // PermissionDenied@@ -2326,7 +2333,7 @@ describe("StatusPageService.SubscribeToPage", () => {pageId: "1",email: "[email protected]",},- { "x-openstatus-key": "2" },+ { "x-openstatus-key": String(OTHER_WORKSPACE_ID) },);expect(res.status).toBe(403);@@ -2744,7 +2751,7 @@ describe("StatusPageService.CreatePageSubscription", () => {const freePage = await db.insert(page).values({- workspaceId: 2,+ workspaceId: OTHER_WORKSPACE_ID,title: `${TEST_PREFIX}-plan-gate`,slug: `${TEST_PREFIX}-plan-gate`,description: "Test page for plan gate",@@ -2761,7 +2768,7 @@ describe("StatusPageService.CreatePageSubscription", () => {email: `${TEST_PREFIX}[email protected]`,},},- { "x-openstatus-key": "2" },+ { "x-openstatus-key": String(OTHER_WORKSPACE_ID) },);expect(res.status).toBe(403);} finally {@@ -3329,7 +3336,7 @@ describe("StatusPageService.GetStatusPageOverview", () => {const otherPage = await db.insert(page).values({- workspaceId: 2,+ workspaceId: OTHER_WORKSPACE_ID,title: `${TEST_PREFIX}-overview-other-ws`,slug: `${TEST_PREFIX}-overview-other-ws-slug`,description: "",@@ -3903,7 +3910,7 @@ describe("StatusPageService β new fields limit enforcement (workspace 2 / freeslug: `${TEST_PREFIX}-limit-ws2-slug`,customDomain: "status.freeplan.com",},- { "x-openstatus-key": "2" },+ { "x-openstatus-key": String(OTHER_WORKSPACE_ID) },);expect(res.status).toBe(403);@@ -3918,7 +3925,7 @@ describe("StatusPageService β new fields limit enforcement (workspace 2 / freeaccessType: "PAGE_ACCESS_TYPE_PASSWORD_PROTECTED",password: "secret",},- { "x-openstatus-key": "2" },+ { "x-openstatus-key": String(OTHER_WORKSPACE_ID) },);expect(res.status).toBe(403);@@ -3933,7 +3940,7 @@ describe("StatusPageService β new fields limit enforcement (workspace 2 / freeaccessType: "PAGE_ACCESS_TYPE_AUTHENTICATED",authEmailDomains: ["example.com"],},- { "x-openstatus-key": "2" },+ { "x-openstatus-key": String(OTHER_WORKSPACE_ID) },);expect(res.status).toBe(403);@@ -3948,7 +3955,7 @@ describe("StatusPageService β new fields limit enforcement (workspace 2 / freeconst ws2Page = await db.insert(page).values({- workspaceId: 2,+ workspaceId: OTHER_WORKSPACE_ID,title: `${TEST_PREFIX}-limit-update-ws2-cd`,slug: `${TEST_PREFIX}-limit-update-ws2-cd-slug`,description: "Free plan page",@@ -3963,7 +3970,7 @@ describe("StatusPageService β new fields limit enforcement (workspace 2 / freeid: String(ws2Page.id),customDomain: "status.freeplan.com",},- { "x-openstatus-key": "2" },+ { "x-openstatus-key": String(OTHER_WORKSPACE_ID) },);expect(res.status).toBe(403);@@ -3975,7 +3982,7 @@ describe("StatusPageService β new fields limit enforcement (workspace 2 / freeconst ws2Page = await db.insert(page).values({- workspaceId: 2,+ workspaceId: OTHER_WORKSPACE_ID,title: `${TEST_PREFIX}-limit-update-ws2-pw`,slug: `${TEST_PREFIX}-limit-update-ws2-pw-slug`,description: "Free plan page",@@ -3991,7 +3998,7 @@ describe("StatusPageService β new fields limit enforcement (workspace 2 / freeaccessType: "PAGE_ACCESS_TYPE_PASSWORD_PROTECTED",password: "secret",},- { "x-openstatus-key": "2" },+ { "x-openstatus-key": String(OTHER_WORKSPACE_ID) },);expect(res.status).toBe(403);@@ -4003,7 +4010,7 @@ describe("StatusPageService β new fields limit enforcement (workspace 2 / freeconst ws2Page = await db.insert(page).values({- workspaceId: 2,+ workspaceId: OTHER_WORKSPACE_ID,title: `${TEST_PREFIX}-limit-update-ws2-auth`,slug: `${TEST_PREFIX}-limit-update-ws2-auth-slug`,description: "Free plan page",@@ -4019,7 +4026,7 @@ describe("StatusPageService β new fields limit enforcement (workspace 2 / freeaccessType: "PAGE_ACCESS_TYPE_AUTHENTICATED",authEmailDomains: ["example.com"],},- { "x-openstatus-key": "2" },+ { "x-openstatus-key": String(OTHER_WORKSPACE_ID) },);expect(res.status).toBe(403);@@ -4306,7 +4313,7 @@ describe("StatusPageService β allow_index", () => {const freePage = await db.insert(page).values({- workspaceId: 2,+ workspaceId: OTHER_WORKSPACE_ID,title: `${TEST_PREFIX}-no-index`,slug: `${TEST_PREFIX}-no-index`,description: "Test page for no-index gate",@@ -4321,7 +4328,7 @@ describe("StatusPageService β allow_index", () => {id: String(freePage.id),allowIndex: false,},- { "x-openstatus-key": "2" },+ { "x-openstatus-key": String(OTHER_WORKSPACE_ID) },);expect(res.status).not.toBe(200);@@ -4582,7 +4589,7 @@ describe("StatusPageService β IP restriction limit enforcement (workspace 2 /accessType: "PAGE_ACCESS_TYPE_IP_RESTRICTED",allowedIpRanges: "10.0.0.0/8",},- { "x-openstatus-key": "2" },+ { "x-openstatus-key": String(OTHER_WORKSPACE_ID) },);expect(res.status).toBe(403);@@ -4592,7 +4599,7 @@ describe("StatusPageService β IP restriction limit enforcement (workspace 2 /const ws2Page = await db.insert(page).values({- workspaceId: 2,+ workspaceId: OTHER_WORKSPACE_ID,title: `${TEST_PREFIX}-ip-limit-update-ws2`,slug: `${TEST_PREFIX}-ip-limit-ws2-slug`,description: "Free plan page",@@ -4608,7 +4615,7 @@ describe("StatusPageService β IP restriction limit enforcement (workspace 2 /accessType: "PAGE_ACCESS_TYPE_IP_RESTRICTED",allowedIpRanges: "10.0.0.0/8",},- { "x-openstatus-key": "2" },+ { "x-openstatus-key": String(OTHER_WORKSPACE_ID) },);expect(res.status).toBe(403);diff --git a/apps/server/src/routes/rpc/handlers/status-report/__tests__/status-report.test.ts b/apps/server/src/routes/rpc/handlers/status-report/__tests__/status-report.test.tsindex 8e7477f42..17d66d80f 100644--- a/apps/server/src/routes/rpc/handlers/status-report/__tests__/status-report.test.ts+++ b/apps/server/src/routes/rpc/handlers/status-report/__tests__/status-report.test.ts@@ -9,6 +9,7 @@ import {statusReportsToPageComponents,workspace,} from "@openstatus/db/src/schema";+import { createTestWorkspace } from "@openstatus/db/src/test/factories";import { createWorkspace } from "@openstatus/db/src/test/factories";import {PageComponentImpact,@@ -64,7 +65,14 @@ let testSubscriberId: number;let testPage2Id: number;let testPage2ComponentId: number;+// A second, free-plan workspace: used both for cross-workspace isolation+// assertions and for the plan-limit rejections. Private to this suite because+// sibling suites assert the seeded free workspace owns nothing.+let OTHER_WORKSPACE_ID: number;+beforeAll(async () => {+ OTHER_WORKSPACE_ID = (await createTestWorkspace({ plan: "free" })).workspace+ .id;// Clean up any existing test dataawait db.delete(statusReport)@@ -732,7 +740,7 @@ describe("StatusReportService.GetStatusReport", () => {const otherReport = await db.insert(statusReport).values({- workspaceId: 2,+ workspaceId: OTHER_WORKSPACE_ID,title: `${TEST_PREFIX}-other-workspace`,status: "investigating",})@@ -914,7 +922,7 @@ describe("StatusReportService.ListStatusReports", () => {const otherReport = await db.insert(statusReport).values({- workspaceId: 2,+ workspaceId: OTHER_WORKSPACE_ID,title: `${TEST_PREFIX}-other-workspace-list`,status: "investigating",})@@ -1119,7 +1127,7 @@ describe("StatusReportService.UpdateStatusReport", () => {const otherReport = await db.insert(statusReport).values({- workspaceId: 2,+ workspaceId: OTHER_WORKSPACE_ID,title: `${TEST_PREFIX}-other-workspace-update`,status: "investigating",})@@ -1441,7 +1449,7 @@ describe("StatusReportService.DeleteStatusReport", () => {const otherReport = await db.insert(statusReport).values({- workspaceId: 2,+ workspaceId: OTHER_WORKSPACE_ID,title: `${TEST_PREFIX}-other-workspace-delete`,status: "investigating",})@@ -1586,7 +1594,7 @@ describe("StatusReportService.AddStatusReportUpdate", () => {const otherReport = await db.insert(statusReport).values({- workspaceId: 2,+ workspaceId: OTHER_WORKSPACE_ID,title: `${TEST_PREFIX}-other-workspace-add-update`,status: "investigating",})diff --git a/apps/server/src/routes/slack/config.ts b/apps/server/src/routes/slack/config.tsnew file mode 100644index 000000000..d5a68aca6--- /dev/null+++ b/apps/server/src/routes/slack/config.ts@@ -0,0 +1,41 @@+import { env } from "@/env";++/**+ * Slack credentials and derived settings, resolved once when the route is+ * built and carried on the request context.+ *+ * Handlers read this instead of `env` directly so tests can construct a route+ * with explicit config. Mutating `process.env` per-test is not viable: Deno's+ * `--parallel` runs test files in workers that share one process environment,+ * so concurrent files clobber each other's settings.+ */+export type SlackConfig = {+ signingSecret?: string;+ clientId?: string;+ clientSecret?: string;+ redirectUri?: string;+ aiGatewayApiKey?: string;+ dashboardUrl: string;+};++export type SlackEnv = {+ Variables: {+ slackBody: unknown;+ event: Record<string, unknown>;+ slackConfig: SlackConfig;+ };+};++export function slackConfigFromEnv(): SlackConfig {+ return {+ signingSecret: env.SLACK_SIGNING_SECRET,+ clientId: env.SLACK_CLIENT_ID,+ clientSecret: env.SLACK_CLIENT_SECRET,+ redirectUri: env.SLACK_REDIRECT_URI,+ aiGatewayApiKey: env.AI_GATEWAY_API_KEY,+ dashboardUrl:+ env.NODE_ENV === "production"+ ? "https://app.openstatus.dev"+ : "http://localhost:3000",+ };+}diff --git a/apps/server/src/routes/slack/handler.test.ts b/apps/server/src/routes/slack/handler.test.tsindex feca71bcc..5c6d46359 100644--- a/apps/server/src/routes/slack/handler.test.ts+++ b/apps/server/src/routes/slack/handler.test.ts@@ -6,17 +6,17 @@ import { Hono } from "hono";// workspace-resolver / @slack/web-api / agent are swapped for doubles via the// test import map; behavior is driven through this shared mutable state.import { slackTestState } from "@/libs/test/doubles/slack-test-state";+import {+ TEST_SIGNING_SECRET as SIGNING_SECRET,+ withSlackConfig,+} from "@/libs/test/slack-config";+import type { SlackEnv } from "./config";import { handleSlackEvent } from "./handler";import { verifySlackSignature } from "./verify";-const SIGNING_SECRET = "test-signing-secret";--process.env.SLACK_SIGNING_SECRET = SIGNING_SECRET;-process.env.AI_GATEWAY_API_KEY = "test-key";-function createTestApp() {- const app = new Hono<{ Variables: { slackBody: unknown } }>();+ const app = withSlackConfig(new Hono<SlackEnv>());app.post("/slack/events", verifySlackSignature, handleSlackEvent);return app;}diff --git a/apps/server/src/routes/slack/index.test.ts b/apps/server/src/routes/slack/index.test.tsindex 89c34b80b..cadf7d6a4 100644--- a/apps/server/src/routes/slack/index.test.ts+++ b/apps/server/src/routes/slack/index.test.ts@@ -1,9 +1,12 @@import crypto from "node:crypto";import { expect } from "@std/expect";-import { beforeEach, describe, test } from "@std/testing/bdd";+import { describe, test } from "@std/testing/bdd";import { Hono } from "hono";+import type { SlackConfig } from "./config";+import { createSlackRoute } from "./index";+const SIGNING_SECRET = "test-signing-secret";function signRequest(body: string, timestamp: number): string {@@ -24,19 +27,22 @@ function makeInstallToken(workspaceId: number): string {return Buffer.from(`${payload}.${sig}`).toString("base64url");}-describe("slack route middleware", () => {- beforeEach(() => {- process.env.SLACK_SIGNING_SECRET = SIGNING_SECRET;- process.env.AI_GATEWAY_API_KEY = "test-key";- process.env.SLACK_CLIENT_ID = "test-client-id";- });+const BASE_CONFIG: SlackConfig = {+ signingSecret: SIGNING_SECRET,+ clientId: "test-client-id",+ aiGatewayApiKey: "test-key",+ dashboardUrl: "http://localhost:3000",+};++function makeApp(overrides: Partial<SlackConfig> = {}) {+ const app = new Hono();+ app.route("/slack", createSlackRoute({ ...BASE_CONFIG, ...overrides }));+ return app;+}+describe("slack route middleware", () => {test("returns 503 when SLACK_SIGNING_SECRET is missing", async () => {- process.env.SLACK_SIGNING_SECRET = "";-- const { slackRoute } = await import("./index");- const app = new Hono();- app.route("/slack", slackRoute);+ const app = makeApp({ signingSecret: "" });const res = await app.request("/slack/install?token=invalid");@@ -46,11 +52,7 @@ describe("slack route middleware", () => {});test("returns 503 when AI_GATEWAY_API_KEY is missing", async () => {- process.env.AI_GATEWAY_API_KEY = "";-- const { slackRoute } = await import("./index");- const app = new Hono();- app.route("/slack", slackRoute);+ const app = makeApp({ aiGatewayApiKey: "" });const res = await app.request("/slack/install?token=invalid");@@ -58,9 +60,7 @@ describe("slack route middleware", () => {});test("GET /install is accessible with valid token", async () => {- const { slackRoute } = await import("./index");- const app = new Hono();- app.route("/slack", slackRoute);+ const app = makeApp();const token = makeInstallToken(1);const res = await app.request(`/slack/install?token=${token}`);@@ -69,18 +69,14 @@ describe("slack route middleware", () => {});test("GET /install rejects invalid token", async () => {- const { slackRoute } = await import("./index");- const app = new Hono();- app.route("/slack", slackRoute);+ const app = makeApp();const res = await app.request("/slack/install?token=invalid");expect(res.status).toBe(403);});test("POST /events requires signature verification", async () => {- const { slackRoute } = await import("./index");- const app = new Hono();- app.route("/slack", slackRoute);+ const app = makeApp();// POST without signature headers should failconst res = await app.request("/slack/events", {@@ -93,9 +89,7 @@ describe("slack route middleware", () => {});test("POST /events accepts valid signed request", async () => {- const { slackRoute } = await import("./index");- const app = new Hono();- app.route("/slack", slackRoute);+ const app = makeApp();const body = JSON.stringify({type: "url_verification",@@ -120,9 +114,7 @@ describe("slack route middleware", () => {});test("POST /interactions requires signature verification", async () => {- const { slackRoute } = await import("./index");- const app = new Hono();- app.route("/slack", slackRoute);+ const app = makeApp();const res = await app.request("/slack/interactions", {method: "POST",diff --git a/apps/server/src/routes/slack/index.ts b/apps/server/src/routes/slack/index.tsindex 050b687d4..9dd3cd453 100644--- a/apps/server/src/routes/slack/index.ts+++ b/apps/server/src/routes/slack/index.ts@@ -1,34 +1,31 @@import { Hono } from "hono";-import { env } from "@/env";-import { handleSlackCommand } from "./commands";+import { type SlackConfig, type SlackEnv, slackConfigFromEnv } from "./config";import { handleSlackEvent } from "./handler";import { handleSlackInteraction } from "./interactions";import { handleSlackInstall, handleSlackOAuthCallback } from "./oauth";import { verifySlackSignature } from "./verify";-type SlackEnv = {- Variables: {- slackBody: unknown;- event: Record<string, unknown>;- };-};+export function createSlackRoute(config: SlackConfig) {+ const slack = new Hono<SlackEnv>();-const slack = new Hono<SlackEnv>();+ slack.use("*", async (c, next) => {+ c.set("slackConfig", config);+ if (!config.signingSecret || !config.aiGatewayApiKey) {+ return c.json({ error: "Slack agent not configured" }, 503);+ }+ await next();+ });-slack.use("*", async (c, next) => {- if (!env.SLACK_SIGNING_SECRET || !env.AI_GATEWAY_API_KEY) {- return c.json({ error: "Slack agent not configured" }, 503);- }- await next();-});+ slack.get("/install", handleSlackInstall);+ slack.get("/oauth/callback", handleSlackOAuthCallback);-slack.get("/install", handleSlackInstall);-slack.get("/oauth/callback", handleSlackOAuthCallback);+ slack.post("/events", verifySlackSignature, handleSlackEvent);+ slack.post("/interactions", verifySlackSignature, handleSlackInteraction);+ slack.post("/commands", verifySlackSignature, handleSlackCommand);-slack.post("/events", verifySlackSignature, handleSlackEvent);-slack.post("/interactions", verifySlackSignature, handleSlackInteraction);-slack.post("/commands", verifySlackSignature, handleSlackCommand);+ return slack;+}-export { slack as slackRoute };+export const slackRoute = createSlackRoute(slackConfigFromEnv());diff --git a/apps/server/src/routes/slack/interactions.test.ts b/apps/server/src/routes/slack/interactions.test.tsindex 98be8198a..401c77d12 100644--- a/apps/server/src/routes/slack/interactions.test.ts+++ b/apps/server/src/routes/slack/interactions.test.ts@@ -6,15 +6,15 @@ import { Hono } from "hono";// workspace-resolver / @slack/web-api are swapped for doubles via the test// import map; behavior is driven through this shared mutable state.import { slackTestState } from "@/libs/test/doubles/slack-test-state";+import {+ TEST_SIGNING_SECRET as SIGNING_SECRET,+ withSlackConfig,+} from "@/libs/test/slack-config";+import type { SlackEnv } from "./config";import { handleSlackInteraction } from "./interactions";import { verifySlackSignature } from "./verify";-const SIGNING_SECRET = "test-signing-secret";--process.env.SLACK_SIGNING_SECRET = SIGNING_SECRET;-process.env.AI_GATEWAY_API_KEY = "test-key";-const redisStore = (globalThis as Record<string, unknown>).__testRedisStore as Map<string, string>;@@ -38,7 +38,7 @@ function configureSlackDoubles() {}function createTestApp() {- const app = new Hono<{ Variables: { slackBody: unknown } }>();+ const app = withSlackConfig(new Hono<SlackEnv>());app.post("/slack/interactions", verifySlackSignature, handleSlackInteraction);return app;}diff --git a/apps/server/src/routes/slack/oauth.test.ts b/apps/server/src/routes/slack/oauth.test.tsindex cb99f2650..1e3f7872c 100644--- a/apps/server/src/routes/slack/oauth.test.ts+++ b/apps/server/src/routes/slack/oauth.test.ts@@ -4,18 +4,16 @@ import { expect } from "@std/expect";import { describe, test } from "@std/testing/bdd";import { Hono } from "hono";-import { handleSlackInstall, handleSlackOAuthCallback } from "./oauth";--const SIGNING_SECRET =- process.env.SLACK_SIGNING_SECRET ?? "test-signing-secret";+import {+ TEST_SIGNING_SECRET as SIGNING_SECRET,+ withSlackConfig,+} from "@/libs/test/slack-config";-process.env.SLACK_SIGNING_SECRET = SIGNING_SECRET;-process.env.SLACK_CLIENT_ID = "test-client-id";-process.env.SLACK_CLIENT_SECRET = "test-client-secret";-process.env.NODE_ENV = "development";+import type { SlackEnv } from "./config";+import { handleSlackInstall, handleSlackOAuthCallback } from "./oauth";function createTestApp() {- const app = new Hono();+ const app = withSlackConfig(new Hono<SlackEnv>());app.get("/slack/install", handleSlackInstall);app.get("/slack/oauth/callback", handleSlackOAuthCallback);return app;diff --git a/apps/server/src/routes/slack/oauth.ts b/apps/server/src/routes/slack/oauth.tsindex 9faaa2aeb..407848c10 100644--- a/apps/server/src/routes/slack/oauth.ts+++ b/apps/server/src/routes/slack/oauth.ts@@ -9,7 +9,7 @@ import {import { installSlackAgent } from "@openstatus/services/integration";import type { Context } from "hono";-import { env } from "@/env";+import type { SlackConfig, SlackEnv } from "./config";const logger = getLogger(["api-server", "slack", "oauth"]);@@ -48,29 +48,30 @@ interface SlackOAuthResponse {enterprise?: { id: string; name: string } | null;}-export async function handleSlackInstall(c: Context) {+export async function handleSlackInstall(c: Context<SlackEnv>) {+ const config = c.get("slackConfig");const token = c.req.query("token");if (!token) {return c.json({ error: "token is required" }, 400);}- const installPayload = verifyInstallToken(token);+ const installPayload = verifyInstallToken(config, token);if (!installPayload) {return c.json({ error: "Invalid or expired token" }, 403);}- if (!env.SLACK_CLIENT_ID) {+ if (!config.clientId) {return c.json({ error: "Slack OAuth not configured" }, 503);}- const state = encodeState({+ const state = encodeState(config, {workspaceId: installPayload.workspaceId,userId: installPayload.userId,ts: Date.now(),});const params = new URLSearchParams({- client_id: env.SLACK_CLIENT_ID,+ client_id: config.clientId,scope: BOT_SCOPES,redirect_uri: getRedirectUri(c),state,@@ -79,25 +80,28 @@ export async function handleSlackInstall(c: Context) {return c.redirect(`${SLACK_OAUTH_URL}?${params.toString()}`);}-export async function handleSlackOAuthCallback(c: Context) {+export async function handleSlackOAuthCallback(c: Context<SlackEnv>) {+ const config = c.get("slackConfig");const code = c.req.query("code");const stateParam = c.req.query("state");const error = c.req.query("error");if (error) {- return c.redirect(`${getDashboardUrl()}/settings/integrations?slack=error`);+ return c.redirect(+ `${config.dashboardUrl}/settings/integrations?slack=error`,+ );}if (!code || !stateParam) {return c.json({ error: "Missing code or state" }, 400);}- const state = decodeState(stateParam);+ const state = decodeState(config, stateParam);if (!state || Date.now() - state.ts > 10 * 60 * 1000) {return c.json({ error: "Invalid or expired state" }, 400);}- if (!env.SLACK_CLIENT_ID || !env.SLACK_CLIENT_SECRET) {+ if (!config.clientId || !config.clientSecret) {return c.json({ error: "Slack OAuth not configured" }, 503);}@@ -105,8 +109,8 @@ export async function handleSlackOAuthCallback(c: Context) {method: "POST",headers: { "Content-Type": "application/x-www-form-urlencoded" },body: new URLSearchParams({- client_id: env.SLACK_CLIENT_ID,- client_secret: env.SLACK_CLIENT_SECRET,+ client_id: config.clientId,+ client_secret: config.clientSecret,code,redirect_uri: getRedirectUri(c),}),@@ -115,7 +119,9 @@ export async function handleSlackOAuthCallback(c: Context) {const tokenData = (await tokenRes.json()) as SlackOAuthResponse;if (!tokenData.ok) {logger.error("token exchange failed", { error: tokenData.error });- return c.redirect(`${getDashboardUrl()}/settings/integrations?slack=error`);+ return c.redirect(+ `${config.dashboardUrl}/settings/integrations?slack=error`,+ );}const workspaceRow = await db@@ -127,7 +133,9 @@ export async function handleSlackOAuthCallback(c: Context) {logger.error("workspace not found at callback", {workspaceId: state.workspaceId,});- return c.redirect(`${getDashboardUrl()}/settings/integrations?slack=error`);+ return c.redirect(+ `${config.dashboardUrl}/settings/integrations?slack=error`,+ );}const workspaceParsed = selectWorkspaceSchema.safeParse(workspaceRow);@@ -136,7 +144,9 @@ export async function handleSlackOAuthCallback(c: Context) {workspaceId: state.workspaceId,issues: workspaceParsed.error.issues,});- return c.redirect(`${getDashboardUrl()}/settings/integrations?slack=error`);+ return c.redirect(+ `${config.dashboardUrl}/settings/integrations?slack=error`,+ );}try {@@ -170,31 +180,30 @@ export async function handleSlackOAuthCallback(c: Context) {workspaceId: state.workspaceId,err: err instanceof Error ? err.message : String(err),});- return c.redirect(`${getDashboardUrl()}/settings/integrations?slack=error`);+ return c.redirect(+ `${config.dashboardUrl}/settings/integrations?slack=error`,+ );}- return c.redirect(`${getDashboardUrl()}/settings/integrations?slack=success`);+ return c.redirect(+ `${config.dashboardUrl}/settings/integrations?slack=success`,+ );}-function getRedirectUri(c: Context): string {- if (env.SLACK_REDIRECT_URI) return env.SLACK_REDIRECT_URI;+function getRedirectUri(c: Context<SlackEnv>): string {+ const configured = c.get("slackConfig").redirectUri;+ if (configured) return configured;const url = new URL(c.req.url);return `${url.origin}/slack/oauth/callback`;}-function getDashboardUrl(): string {- return env.NODE_ENV === "production"- ? "https://app.openstatus.dev"- : "http://localhost:3000";-}--function encodeState(state: OAuthState): string {+function encodeState(config: SlackConfig, state: OAuthState): string {const payload = JSON.stringify(state);- const signature = computeHmac(payload);+ const signature = computeHmac(config, payload);return Buffer.from(`${payload}.${signature}`).toString("base64url");}-function decodeState(encoded: string): OAuthState | null {+function decodeState(config: SlackConfig, encoded: string): OAuthState | null {try {const decoded = Buffer.from(encoded, "base64url").toString();const dotIdx = decoded.lastIndexOf(".");@@ -203,7 +212,7 @@ function decodeState(encoded: string): OAuthState | null {const payload = decoded.slice(0, dotIdx);const signature = decoded.slice(dotIdx + 1);- if (!verifyHmac(payload, signature)) return null;+ if (!verifyHmac(config, payload, signature)) return null;return JSON.parse(payload) as OAuthState;} catch {@@ -211,14 +220,18 @@ function decodeState(encoded: string): OAuthState | null {}}-function computeHmac(payload: string): string {- const secret = env.SLACK_SIGNING_SECRET;+function computeHmac(config: SlackConfig, payload: string): string {+ const secret = config.signingSecret;if (!secret) throw new Error("Slack signing secret not configured");return crypto.createHmac("sha256", secret).update(payload).digest("hex");}-function verifyHmac(payload: string, signature: string): boolean {- const expected = computeHmac(payload);+function verifyHmac(+ config: SlackConfig,+ payload: string,+ signature: string,+): boolean {+ const expected = computeHmac(config, payload);if (expected.length !== signature.length) return false;return crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(signature));}@@ -226,6 +239,7 @@ function verifyHmac(payload: string, signature: string): boolean {const INSTALL_TOKEN_TTL_MS = 5 * 60 * 1000;function verifyInstallToken(+ config: SlackConfig,token: string,): { workspaceId: number; userId?: number } | null {try {@@ -236,7 +250,7 @@ function verifyInstallToken(const payload = decoded.slice(0, dotIdx);const signature = decoded.slice(dotIdx + 1);- if (!verifyHmac(payload, signature)) return null;+ if (!verifyHmac(config, payload, signature)) return null;const data = JSON.parse(payload) as {workspaceId: number;diff --git a/apps/server/src/routes/slack/verify.test.ts b/apps/server/src/routes/slack/verify.test.tsindex 4640216ee..14240ee68 100644--- a/apps/server/src/routes/slack/verify.test.ts+++ b/apps/server/src/routes/slack/verify.test.ts@@ -4,10 +4,13 @@ import { expect } from "@std/expect";import { describe, test } from "@std/testing/bdd";import { Hono } from "hono";-import { verifySlackSignature } from "./verify";+import {+ TEST_SIGNING_SECRET as SIGNING_SECRET,+ withSlackConfig,+} from "@/libs/test/slack-config";-const SIGNING_SECRET = "test-signing-secret";-process.env.SLACK_SIGNING_SECRET = SIGNING_SECRET;+import type { SlackEnv } from "./config";+import { verifySlackSignature } from "./verify";function signRequest(body: string, timestamp: number): string {const basestring = `v0:${timestamp}:${body}`;@@ -19,7 +22,7 @@ function signRequest(body: string, timestamp: number): string {}function createTestApp() {- const app = new Hono<{ Variables: { slackBody: unknown } }>();+ const app = withSlackConfig(new Hono<SlackEnv>());app.post("/test", verifySlackSignature, (c) => {return c.json({ body: c.get("slackBody") });});diff --git a/apps/server/src/routes/slack/verify.ts b/apps/server/src/routes/slack/verify.tsindex 569d30f7e..6fd0045f9 100644--- a/apps/server/src/routes/slack/verify.ts+++ b/apps/server/src/routes/slack/verify.ts@@ -1,71 +1,75 @@import { createMiddleware } from "hono/factory";-import { env } from "@/env";+import type { SlackEnv } from "./config";-export const verifySlackSignature = createMiddleware<{- Variables: { slackBody: unknown };-}>(async (c, next) => {- const signingSecret = env.SLACK_SIGNING_SECRET;+export const verifySlackSignature = createMiddleware<SlackEnv>(+ async (c, next) => {+ const signingSecret = c.get("slackConfig")?.signingSecret;- if (!signingSecret) {- return c.json({ error: "Slack not configured" }, 503);- }+ if (!signingSecret) {+ return c.json({ error: "Slack not configured" }, 503);+ }- const timestamp = c.req.header("x-slack-request-timestamp");- const signature = c.req.header("x-slack-signature");+ const timestamp = c.req.header("x-slack-request-timestamp");+ const signature = c.req.header("x-slack-signature");- if (!timestamp || !signature) {- return c.json({ error: "Missing Slack headers" }, 401);- }+ if (!timestamp || !signature) {+ return c.json({ error: "Missing Slack headers" }, 401);+ }- const now = Math.floor(Date.now() / 1000);- if (Math.abs(now - Number(timestamp)) > 300) {- return c.json({ error: "Request too old" }, 401);- }+ const now = Math.floor(Date.now() / 1000);+ if (Math.abs(now - Number(timestamp)) > 300) {+ return c.json({ error: "Request too old" }, 401);+ }- const rawBody = await c.req.text();+ const rawBody = await c.req.text();- const encoder = new TextEncoder();- const basestring = `v0:${timestamp}:${rawBody}`;- const key = await crypto.subtle.importKey(- "raw",- encoder.encode(signingSecret),- { name: "HMAC", hash: "SHA-256" },- false,- ["sign"],- );- const sig = await crypto.subtle.sign("HMAC", key, encoder.encode(basestring));- const computed = `v0=${Array.from(new Uint8Array(sig))- .map((b) => b.toString(16).padStart(2, "0"))- .join("")}`;+ const encoder = new TextEncoder();+ const basestring = `v0:${timestamp}:${rawBody}`;+ const key = await crypto.subtle.importKey(+ "raw",+ encoder.encode(signingSecret),+ { name: "HMAC", hash: "SHA-256" },+ false,+ ["sign"],+ );+ const sig = await crypto.subtle.sign(+ "HMAC",+ key,+ encoder.encode(basestring),+ );+ const computed = `v0=${Array.from(new Uint8Array(sig))+ .map((b) => b.toString(16).padStart(2, "0"))+ .join("")}`;- if (computed.length !== signature.length) {- return c.json({ error: "Invalid signature" }, 401);- }+ if (computed.length !== signature.length) {+ return c.json({ error: "Invalid signature" }, 401);+ }- const a = encoder.encode(computed);- const b = encoder.encode(signature);- let mismatch = 0;- for (let i = 0; i < a.length; i++) {- mismatch |= a[i] ^ b[i];- }- if (mismatch !== 0) {- return c.json({ error: "Invalid signature" }, 401);- }+ const a = encoder.encode(computed);+ const b = encoder.encode(signature);+ let mismatch = 0;+ for (let i = 0; i < a.length; i++) {+ mismatch |= a[i] ^ b[i];+ }+ if (mismatch !== 0) {+ return c.json({ error: "Invalid signature" }, 401);+ }- const contentType = c.req.header("content-type") ?? "";- if (contentType.includes("application/json")) {- c.set("slackBody", JSON.parse(rawBody));- } else if (contentType.includes("application/x-www-form-urlencoded")) {- const params = new URLSearchParams(rawBody);- const payload = params.get("payload");- // Interactions arrive as a `payload` field; slash commands arrive as the- // flat form fields themselves.- c.set(- "slackBody",- payload ? JSON.parse(payload) : Object.fromEntries(params),- );- }+ const contentType = c.req.header("content-type") ?? "";+ if (contentType.includes("application/json")) {+ c.set("slackBody", JSON.parse(rawBody));+ } else if (contentType.includes("application/x-www-form-urlencoded")) {+ const params = new URLSearchParams(rawBody);+ const payload = params.get("payload");+ // Interactions arrive as a `payload` field; slash commands arrive as the+ // flat form fields themselves.+ c.set(+ "slackBody",+ payload ? JSON.parse(payload) : Object.fromEntries(params),+ );+ }- await next();-});+ await next();+ },+);diff --git a/apps/workflows/package.json b/apps/workflows/package.jsonindex 2c38880fa..208c23020 100644--- a/apps/workflows/package.json+++ b/apps/workflows/package.json@@ -4,7 +4,7 @@"check": "deno check --sloppy-imports src/serve.ts","dev": "NODE_ENV=development deno run -A --watch src/serve.ts","start": "NODE_ENV=production deno run -A src/serve.ts",- "test": "NODE_ENV=test RESEND_API_KEY=test-key CRON_SECRET=test-secret deno test -A --no-check --sloppy-imports"+ "test": "NODE_ENV=test RESEND_API_KEY=test-key CRON_SECRET=test-secret deno test --parallel -A --no-check --sloppy-imports"},"dependencies": {"@google-cloud/tasks": "catalog:",diff --git a/apps/workflows/src/checker/alerting.test.ts b/apps/workflows/src/checker/alerting.test.tsindex e69ab6c94..d07bb5e55 100644--- a/apps/workflows/src/checker/alerting.test.ts+++ b/apps/workflows/src/checker/alerting.test.ts@@ -4,10 +4,17 @@ import {notificationTrigger,notificationsToMonitors,} from "@openstatus/db/src/schema";+import {+ createMonitor,+ createNotification,+ createTestWorkspace,+ linkNotificationToMonitor,+} from "@openstatus/db/src/test/factories";import {afterAll,afterEach,assertSpyCalls,+ beforeAll,beforeEach,describe,expect,@@ -46,8 +53,13 @@ let mockDiscordSendAlert: AnyStub;let mockDiscordSendRecovery: AnyStub;let mockDiscordSendDegraded: AnyStub;-// Seed data has: monitor 1 (workspace 1) linked to notification 1 (email provider)-// We use unique cronTimestamp per test to avoid unique constraint conflicts+// Own workspace + monitors: asserting on "how many notifications fired for this+// monitor" only holds if no other suite can attach one.+// Unique cronTimestamp per test avoids unique-constraint conflicts.+let workspaceId: number;+let emailMonitorId: number;+let emailNotificationId: number;+let noNotifMonitorId: number;beforeEach(() => {stubs = [];@@ -71,20 +83,27 @@ afterEach(() => {stubs = [];});-describe("triggerNotifications", () => {- afterAll(async () => {- // Clean up notification triggers created during tests- await db- .delete(notificationTrigger)- .where(eq(notificationTrigger.monitorId, 1))- .run();- });+beforeAll(async () => {+ const { workspace } = await createTestWorkspace();+ workspaceId = workspace.id;+ emailMonitorId = (await createMonitor(workspaceId)).id;+ noNotifMonitorId = (await createMonitor(workspaceId)).id;+ emailNotificationId = (+ await createNotification(workspaceId, {+ name: "sample test notification",+ provider: "email",+ data: JSON.stringify({ email: "[email protected]" }),+ })+ ).id;+ await linkNotificationToMonitor(emailNotificationId, emailMonitorId);+});+await describe("triggerNotifications", async () => {test("should send alert notification and return triggered list", async () => {const cronTimestamp = 9000001;const result = await triggerNotifications({- monitorId: "1",+ monitorId: String(emailMonitorId),statusCode: 500,message: "Internal Server Error",notifType: "alert",@@ -97,7 +116,7 @@ describe("triggerNotifications", () => {assertSpyCalls(mockEmailSendAlert, 1);expect(result).toHaveLength(1);expect(result[0]).toEqual({- notificationId: 1,+ notificationId: emailNotificationId,provider: "email",});});@@ -106,7 +125,7 @@ describe("triggerNotifications", () => {const cronTimestamp = 9000002;const result = await triggerNotifications({- monitorId: "1",+ monitorId: String(emailMonitorId),statusCode: 200,notifType: "recovery",cronTimestamp,@@ -116,7 +135,7 @@ describe("triggerNotifications", () => {assertSpyCalls(mockEmailSendRecovery, 1);expect(result).toHaveLength(1);expect(result[0]).toEqual({- notificationId: 1,+ notificationId: emailNotificationId,provider: "email",});});@@ -125,7 +144,7 @@ describe("triggerNotifications", () => {const cronTimestamp = 9000003;const result = await triggerNotifications({- monitorId: "1",+ monitorId: String(emailMonitorId),statusCode: 200,notifType: "degraded",cronTimestamp,@@ -136,7 +155,7 @@ describe("triggerNotifications", () => {assertSpyCalls(mockEmailSendDegraded, 1);expect(result).toHaveLength(1);expect(result[0]).toEqual({- notificationId: 1,+ notificationId: emailNotificationId,provider: "email",});});@@ -146,7 +165,7 @@ describe("triggerNotifications", () => {// Monitor 2 has no notifications linked in seed dataconst result = await triggerNotifications({- monitorId: "2",+ monitorId: String(noNotifMonitorId),statusCode: 500,notifType: "alert",cronTimestamp,@@ -160,7 +179,7 @@ describe("triggerNotifications", () => {const cronTimestamp = 9000005;const first = await triggerNotifications({- monitorId: "1",+ monitorId: String(emailMonitorId),statusCode: 500,notifType: "alert",cronTimestamp,@@ -171,7 +190,7 @@ describe("triggerNotifications", () => {// Same cronTimestamp should be skipped due to unique constraintconst second = await triggerNotifications({- monitorId: "1",+ monitorId: String(emailMonitorId),statusCode: 500,notifType: "alert",cronTimestamp,@@ -186,9 +205,11 @@ describe("triggerNotifications", () => {describe("triggerNotifications with multiple providers", () => {const testNotificationIds: number[] = [];- // Monitor 3 (workspace 1) exists in seed but has no notifications.- // We link slack and discord notifications to it for this test suite.- const testMonitorId = 3;+ let testMonitorId: number;++ beforeAll(async () => {+ testMonitorId = (await createMonitor(workspaceId)).id;+ });afterAll(async () => {// Clean up notification triggers@@ -220,7 +241,7 @@ describe("triggerNotifications with multiple providers", () => {name: "test-slack",provider: "slack",data: '{"slack":"https://hooks.slack.com/test"}',- workspaceId: 1,+ workspaceId,}).returning();@@ -231,7 +252,7 @@ describe("triggerNotifications with multiple providers", () => {name: "test-discord",provider: "discord",data: '{"discord":"https://discord.com/api/webhooks/test"}',- workspaceId: 1,+ workspaceId,}).returning();diff --git a/apps/workflows/src/checker/private-location.test.ts b/apps/workflows/src/checker/private-location.test.tsindex 8ded0d160..527cefcbf 100644--- a/apps/workflows/src/checker/private-location.test.ts+++ b/apps/workflows/src/checker/private-location.test.ts@@ -8,6 +8,7 @@ import {privateLocationMonitorStatus,privateLocationToMonitors,} from "@openstatus/db/src/schema";+import { createTestWorkspace } from "@openstatus/db/src/test/factories";import {afterAll,afterEach,@@ -32,6 +33,7 @@ type AnyStub = Stub<any>;// Dedicated fixtures, not seed monitor 1: other suites (api/server maintenance// tests) put seed monitor 1 under active maintenance on the shared CI database,// which makes updateStatusPrivate suppress notifications and drop the write.+let workspaceId: number;const TEST_MONITOR_ID = 9101;const INACTIVE_MONITOR_ID = 9102;const TEST_NOTIFICATION_ID = 9101;@@ -81,12 +83,13 @@ describe("updateStatusPrivate", () => {let mockEmailSendDegraded: AnyStub;beforeAll(async () => {+ workspaceId = (await createTestWorkspace()).workspace.id;await db.insert(monitor).values([{id: TEST_MONITOR_ID,- workspaceId: 1,+ workspaceId,active: true,url: "https://private-location.test",name: "Private Location Test Monitor",@@ -95,7 +98,7 @@ describe("updateStatusPrivate", () => {},{id: INACTIVE_MONITOR_ID,- workspaceId: 1,+ workspaceId,active: false,url: "https://private-location-inactive.test",name: "Private Location Inactive Monitor",@@ -112,7 +115,7 @@ describe("updateStatusPrivate", () => {provider: "email",name: "private location test notification",data: '{"email":"[email protected]"}',- workspaceId: 1,+ workspaceId,}).onConflictDoNothing().run();@@ -130,7 +133,7 @@ describe("updateStatusPrivate", () => {id: TEST_LOCATION_ID,name: "Test Office",token: "test-private-location-token",- workspaceId: 1,+ workspaceId,createdAt: new Date(),}).onConflictDoNothing()diff --git a/apps/workflows/src/cron/private-location-health.test.ts b/apps/workflows/src/cron/private-location-health.test.tsindex 01aa47c86..701a14999 100644--- a/apps/workflows/src/cron/private-location-health.test.ts+++ b/apps/workflows/src/cron/private-location-health.test.ts@@ -1,8 +1,10 @@import { db, eq } from "@openstatus/db";import { auditLog, privateLocation } from "@openstatus/db/src/schema";+import { createTestWorkspace } from "@openstatus/db/src/test/factories";import {afterEach,assertSpyCalls,+ beforeAll,beforeEach,describe,expect,@@ -18,7 +20,7 @@ import {} from "./private-location-health";const TEST_LOCATION_ID = 9301;-const TEST_WORKSPACE_ID = 1;+let TEST_WORKSPACE_ID: number;const NOW = new Date("2026-07-23T12:00:00Z");const FRESH = new Date(NOW.getTime() - 60 * 1000);const STALE = new Date(NOW.getTime() - STALE_THRESHOLD_MS - 60 * 1000);@@ -58,6 +60,10 @@ function readStatus() {describe("runPrivateLocationHealth", () => {let mockEmail: AnyStub;+ beforeAll(async () => {+ TEST_WORKSPACE_ID = (await createTestWorkspace()).workspace.id;+ });+beforeEach(() => {mockEmail = stub(emailClient, "sendPrivateLocationAlert", () =>Promise.resolve(),diff --git a/docs/adr/0008-isolated-test-databases.md b/docs/adr/0008-isolated-test-databases.mdnew file mode 100644index 000000000..97ccb3557--- /dev/null+++ b/docs/adr/0008-isolated-test-databases.md@@ -0,0 +1,118 @@+---+status: "accepted"+date: 2026-07-27+decision-makers: openstatus maintainers+---++# One test database per package, one workspace per suite, injected route config++## Context and Problem Statement++`pnpm test` runs every package's `test` task through turbo, concurrently, and+most of those tasks run `deno test --parallel`, which runs test *files*+concurrently too. All of them pointed at a single `libsql-server` container and a+single seeded fixture set: workspace 1 (team), workspace 2 (free), monitors 1-5,+page 1.++That made roughly 74 DB-touching test files, spread across five packages, share+one mutable dataset with no isolation at any level. The `Tests` workflow failed+on about 22% of runs, never on the same test twice.++Two concrete examples from CI:++- `apps/workflows` asserted that seeded monitor 1 had exactly one notification.+ `apps/server`'s notification suite attaches two more to the same monitor in its+ `beforeAll`. When the two turbo tasks overlapped, the assertion saw 3.+- 14 `packages/services` suites called `clearAuditLog(1)` in `beforeAll`. Under+ `--parallel`, one suite's wipe lands inside another's assertion window, so+ "an audit row was written" and "no audit row was written" both fail at random.++The suites had accumulated defensive workarounds for this β save-and-restore of+the seeded owner's role, `cleanQuotaGatedTables`, comments explaining which+sibling suite a given wipe was racing. The workarounds narrowed the window; they+could not close it.++## Decision Drivers++- Shared mutable fixtures and parallel execution are fundamentally incompatible;+ any fix that keeps both is a narrower race, not a fix.+- A flaky suite that is re-run until green trains people to ignore red CI.+- Serializing the tasks (the previous arrangement) hides the coupling and makes+ the suite slow enough that someone will eventually remove the serialization+ again.+- The fix has to be reachable incrementally β ~74 files cannot be rewritten in+ one step.++## Decision++Three independent layers, one per axis of shared state: the database, the+dataset inside it, and the process environment.++**Isolate at the process boundary: one database per package.** `test.yml` is a+job matrix with one leg per DB-touching package (`services`, `server`, `api`,+`workflows`, `subscriptions`) plus one leg for everything else. Each leg is a+separate runner with its own `libsql-server` service container, migrated and+seeded independently. Cross-package interference becomes impossible by+construction rather than by convention, and the legs run concurrently, so total+wall-clock is the slowest package rather than the sum.++**Isolate at the data boundary: one workspace per suite.** `createTestWorkspace`+in `packages/db/src/test/factories.ts` mints a workspace (plus an owner user) with+a unique slug on every call, alongside factories for the entities that hang off+it β monitors, pages, page components, notifications. `packages/services` exposes+it to suites as `createWorkspaceFixture(plan)`. Suites call it in `beforeAll`+instead of loading a seeded workspace, so `clearAuditLog(ctx.workspace.id)`,+plan-quota state, and exact row counts are all private to the suite that owns+them.++A `team` fixture carries the same limits override the seeded team workspace has+(`packages/db/src/seed/limits.ts`, now shared by the seed and the factory) so+suites keep the headroom they were written against. A `free` fixture keeps the+stock plan defaults, because the quota-rejection tests need to hit the caps.++**Isolate at the process environment: inject the slack route's config.** The+slack route read its credentials from `env` (a proxy over `process.env`) at+request time, and its suites drove the "not configured" branches by assigning to+`process.env` mid-test. Deno's `--parallel` runs test files in workers that share+one process environment, so those assignments leaked across files β the suite had+to run as a serial second pass.++`createSlackRoute(config)` now takes a `SlackConfig` and puts it on the request+context; `verify.ts` and `oauth.ts` read `c.get("slackConfig")` instead of `env`.+Production still calls `slackConfigFromEnv()` at module scope. Tests build a route+with explicit config, so "signing secret missing" is a value passed in rather than+a global mutated, and the 9 slack files join the parallel pass.++## Consequences++- `loadSeededWorkspace` is gone. Suites that reached for a seeded workspace now+ own one.+- Test workspaces are not torn down. `onDelete: "cascade"` is set on only 10 of+ the 21 workspace-scoped tables, so a blanket delete fails on the rest. Test+ databases are ephemeral β a fresh container per CI job, and `pnpm seed` wipes+ every table locally β so the rows are harmless. Adding a workspace-scoped table+ does not require touching test teardown.+- `apps/workflows` and `packages/subscriptions` gained `--parallel`; they were+ serial only because their fixtures were shared. `apps/server` collapsed from+ two commands to one, since the slack carve-out is no longer needed. Every+ package now runs its test files in parallel.+- Reading config at request time from a live `process.env` proxy is what made the+ slack route untestable in parallel. New routes should resolve config once and+ pass it in.+- The seeded dataset still exists and is still what local development and the+ dashboard run against. Tests no longer depend on its *contents* β only+ `with-transaction` and `with-test-transaction`, which exercise the transaction+ helpers themselves, still reference workspace 1, and only to satisfy a foreign+ key inside a rolled-back transaction.+- Six CI legs each run `pnpm install`, which the setup-node pnpm cache absorbs.+- Branch protection keeps a single required check: an aggregate `π§ͺ Tests` job+ that fails if any matrix leg fails.++### What this does not fix++`external_service` and its children are a global, non-workspace-scoped directory+of third-party status pages. Those suites isolate by unique slug prefix instead,+and their `beforeAll` cleanup deletes parents before children, so a suite aborted+mid-run can leave rows that make the *next* run fail on a foreign key. That is+survivable because CI databases are fresh per job, but it will bite anyone+re-running those suites locally against a dirty database; reseed to recover.diff --git a/packages/api/src/router/import.test.ts b/packages/api/src/router/import.test.tsindex ddb77b232..9cb9869ad 100644--- a/packages/api/src/router/import.test.ts+++ b/packages/api/src/router/import.test.ts@@ -11,6 +11,10 @@ import {} from "@openstatus/db/src/schema";import { allPlans } from "@openstatus/db/src/schema/plan/config";import type { Limits } from "@openstatus/db/src/schema/plan/schema";+import {+ createPage,+ createTestWorkspace,+} from "@openstatus/db/src/test/factories";import {MOCK_COMPONENTS,MOCK_COMPONENT_GROUPS,@@ -69,7 +73,16 @@ function restoreFetch() {globalThis.fetch = originalFetch;}-function makeCaller(limitsOverride?: Partial<Limits>, workspaceId = 1) {+// Own workspace + page: the import assertions count page components, which+// only holds if no sibling suite writes to the same page.+let TEST_WORKSPACE_ID: number;+let OTHER_WORKSPACE_ID: number;+let TEST_PAGE_ID: number;++function makeCaller(+ limitsOverride?: Partial<Limits>,+ workspaceId = TEST_WORKSPACE_ID,+) {const limits = { ...allPlans.starter.limits, ...limitsOverride };const ctx = createInnerTRPCContext({req: undefined,@@ -251,8 +264,14 @@ function trackCreatedIds(summary: {// Tests// ----------------------------------------------------------------------------beforeAll(() => {+let caller: ReturnType<typeof makeCaller>;++beforeAll(async () => {mockStatuspageFetch();+ TEST_WORKSPACE_ID = (await createTestWorkspace()).workspace.id;+ OTHER_WORKSPACE_ID = (await createTestWorkspace()).workspace.id;+ TEST_PAGE_ID = (await createPage(TEST_WORKSPACE_ID)).id;+ caller = makeCaller();});afterAll(async () => {@@ -260,8 +279,6 @@ afterAll(async () => {await cleanup();});-const caller = makeCaller();-test("preview returns mapped data without DB writes", async () => {const result = await caller.import.preview({provider: "statuspage",@@ -317,7 +334,7 @@ test("run creates page, components, and groups in DB", async () => {if (!dbPage)throw new Error("Expected page to be created with slug 'acmecorp'");expect(dbPage.title).toBe("Acme Corp Status");- expect(dbPage.workspaceId).toBe(1);+ expect(dbPage.workspaceId).toBe(TEST_WORKSPACE_ID);// Components should be createdconst dbComponents = await db@@ -347,7 +364,7 @@ test("run with existing pageId imports into that page", async () => {const result = await caller.import.run({provider: "statuspage",apiKey: "test-key",- pageId: 1,+ pageId: TEST_PAGE_ID,options: { includeStatusReports: false, includeSubscribers: false },});@@ -358,13 +375,13 @@ test("run with existing pageId imports into that page", async () => {// Page phase should show "skipped" since we used an existing pageconst pagePhase = result.phases.find((p) => p.phase === "page");expect(pagePhase?.resources[0]?.status).toBe("skipped");- expect(pagePhase?.resources[0]?.openstatusId).toBe(1);+ expect(pagePhase?.resources[0]?.openstatusId).toBe(TEST_PAGE_ID);// Components should be created under page 1const dbComponents = await db.select().from(pageComponent)- .where(eq(pageComponent.pageId, 1))+ .where(eq(pageComponent.pageId, TEST_PAGE_ID)).all();// At least the components we imported should existconst importedCompNames = MOCK_COMPONENTS.map((c) => c.name);@@ -476,7 +493,10 @@ test("preview shows component limit warning on free plan", async () => {// starts at 0 β workspace 1 has 2 seeded page components from the// shared seed, which would make `remaining = 1` instead of 3 and// change the warning wording.- const c = makeCaller({ ...freeLimits, "page-components": 3 }, 2);+ const c = makeCaller(+ { ...freeLimits, "page-components": 3 },+ OTHER_WORKSPACE_ID,+ );const result = await c.import.preview({provider: "statuspage",apiKey: "test-key",@@ -534,7 +554,7 @@ test("run enforces component limit by truncating", async () => {const [testPage] = await db.insert(page).values({- workspaceId: 1,+ workspaceId: TEST_WORKSPACE_ID,title: "Truncation Test Page",description: "",slug: "truncation-test",diff --git a/packages/db/env.mjs b/packages/db/env.mjsindex 2c6f37283..069a71f54 100644--- a/packages/db/env.mjs+++ b/packages/db/env.mjs@@ -10,11 +10,11 @@ export const env = createEnv({CLICKHOUSE_PASSWORD: z.string(),},runtimeEnv: {+ // Tests fall back to the conventional local sqld port, but an explicit+ // DATABASE_URL always wins so each suite can target its own database.DATABASE_URL:- // FIXME: This is a hack to get the tests to run- process.env.NODE_ENV === "test"- ? "http://127.0.0.1:8080"- : process.env.DATABASE_URL,+ process.env.DATABASE_URL ??+ (process.env.NODE_ENV === "test" ? "http://127.0.0.1:8080" : undefined),DATABASE_AUTH_TOKEN: process.env.DATABASE_AUTH_TOKEN,CLICKHOUSE_URL: process.env.CLICKHOUSE_URL,CLICKHOUSE_USERNAME: process.env.CLICKHOUSE_USERNAME,diff --git a/packages/db/src/seed.mts b/packages/db/src/seed.mtsindex 8e1264716..0bc173736 100644--- a/packages/db/src/seed.mts+++ b/packages/db/src/seed.mts@@ -22,6 +22,7 @@ import {workspace,} from "./schema";import { externalServicesSeed } from "./seed/external-services";+import { TEAM_WORKSPACE_LIMITS } from "./seed/limits";async function main() {if (@@ -66,8 +67,7 @@ async function main() {plan: "team",endsAt: null,paidUntil: null,- limits:- '{"monitors":50,"synthetic-checks":150000,"periodicity":["30s","1m","5m","10m","30m","1h"],"multi-region":true,"max-regions":35,"data-retention":"24 months","status-pages":20,"maintenance":true,"status-subscribers":true,"custom-domain":true,"password-protection":true,"email-domain-protection":true,"white-label":true,"notifications":true,"sms":true,"pagerduty":true,"notification-channels":50,"members":"Unlimited","audit-log":true,"regions":["ams","arn","atl","bog","bom","bos","cdg","den","dfw","ewr","eze","fra","gdl","gig","gru","hkg","iad","jnb","lax","lhr","mad","mia","nrt","ord","otp","phx","qro","scl","sea","sin","sjc","syd","waw","yul","yyz"]}',+ limits: TEAM_WORKSPACE_LIMITS,},{id: 2,diff --git a/packages/db/src/seed/limits.ts b/packages/db/src/seed/limits.tsnew file mode 100644index 000000000..b485be88d--- /dev/null+++ b/packages/db/src/seed/limits.ts@@ -0,0 +1,64 @@+// Limits override for the seeded `team` workspace and for team workspaces built+// by the test factories. Looser than the stock team plan (more status pages,+// notification channels and regions) so suites can create fixtures freely+// without tripping a quota check.+//+// Stored as a string because `workspace.limits` is a TEXT column holding JSON.+export const TEAM_WORKSPACE_LIMITS = JSON.stringify({+ monitors: 50,+ "synthetic-checks": 150000,+ periodicity: ["30s", "1m", "5m", "10m", "30m", "1h"],+ "multi-region": true,+ "max-regions": 35,+ "data-retention": "24 months",+ "status-pages": 20,+ maintenance: true,+ "status-subscribers": true,+ "custom-domain": true,+ "password-protection": true,+ "email-domain-protection": true,+ "white-label": true,+ notifications: true,+ sms: true,+ pagerduty: true,+ "notification-channels": 50,+ members: "Unlimited",+ "audit-log": true,+ regions: [+ "ams",+ "arn",+ "atl",+ "bog",+ "bom",+ "bos",+ "cdg",+ "den",+ "dfw",+ "ewr",+ "eze",+ "fra",+ "gdl",+ "gig",+ "gru",+ "hkg",+ "iad",+ "jnb",+ "lax",+ "lhr",+ "mad",+ "mia",+ "nrt",+ "ord",+ "otp",+ "phx",+ "qro",+ "scl",+ "sea",+ "sin",+ "sjc",+ "syd",+ "waw",+ "yul",+ "yyz",+ ],+});diff --git a/packages/db/src/test/factories.ts b/packages/db/src/test/factories.tsindex 72b4d2d20..b252f2d4f 100644--- a/packages/db/src/test/factories.ts+++ b/packages/db/src/test/factories.ts@@ -1,16 +1,30 @@// Test data factories: create fresh, uniquely-identified resources so suites// don't collide on shared seed IDs (workspace 1, monitors 1-3, β¦). Each call// inserts a row with an auto-increment id and unique slug/name, then returns-// it β scope the test to the returned id and clean up in afterAll.+// it β scope the test to the returned id.//// Pass a transaction as the last arg to scope creation to it (e.g. inside a// rolled-back `withTestTransaction`); omit it to commit to the shared db.import { db as defaultDb } from "../db";-import { monitor, workspace } from "../schema";+import {+ monitor,+ notification,+ notificationsToMonitors,+ page,+ pageComponent,+ user,+ usersToWorkspaces,+ workspace,+} from "../schema";+import { TEAM_WORKSPACE_LIMITS } from "../seed/limits";type Db = typeof defaultDb;type WorkspaceInsert = typeof workspace.$inferInsert;type MonitorInsert = typeof monitor.$inferInsert;+type UserInsert = typeof user.$inferInsert;+type PageInsert = typeof page.$inferInsert;+type PageComponentInsert = typeof pageComponent.$inferInsert;+type NotificationInsert = typeof notification.$inferInsert;const unique = () => crypto.randomUUID().slice(0, 8);@@ -29,6 +43,7 @@ export async function createWorkspace(...overrides,}).returning();+ if (!row) throw new Error("factory insert returned no row");return row;}@@ -46,5 +61,148 @@ export async function createMonitor(...overrides,}).returning();+ if (!row) throw new Error("factory insert returned no row");return row;}++export async function createUser(+ overrides: Partial<UserInsert> = {},+ db: Db = defaultDb,+) {+ const u = unique();+ const [row] = await db+ .insert(user)+ .values({+ tenantId: `test-tenant-${u}`,+ firstName: "Test",+ lastName: "User",+ email: `test-${u}@openstatus.dev`,+ photoUrl: "",+ ...overrides,+ })+ .returning();+ if (!row) throw new Error("factory insert returned no row");+ return row;+}++export async function addUserToWorkspace(+ userId: number,+ workspaceId: number,+ role: "owner" | "member" = "owner",+ db: Db = defaultDb,+) {+ const [row] = await db+ .insert(usersToWorkspaces)+ .values({ userId, workspaceId, role })+ .returning();+ if (!row) throw new Error("factory insert returned no row");+ return row;+}++export async function createPage(+ workspaceId: number,+ overrides: Partial<PageInsert> = {},+ db: Db = defaultDb,+) {+ const [row] = await db+ .insert(page)+ .values({+ workspaceId,+ title: "Test Page",+ description: "Test page description",+ // `slug` is globally unique, not per-workspace.+ slug: `test-page-${unique()}`,+ customDomain: "",+ published: true,+ ...overrides,+ })+ .returning();+ if (!row) throw new Error("factory insert returned no row");+ return row;+}++export async function createPageComponent(+ workspaceId: number,+ pageId: number,+ overrides: Partial<PageComponentInsert> = {},+ db: Db = defaultDb,+) {+ const [row] = await db+ .insert(pageComponent)+ .values({+ workspaceId,+ pageId,+ type: "static",+ name: `test-component-${unique()}`,+ order: 0,+ ...overrides,+ })+ .returning();+ if (!row) throw new Error("factory insert returned no row");+ return row;+}++export async function createNotification(+ workspaceId: number,+ overrides: Partial<NotificationInsert> = {},+ db: Db = defaultDb,+) {+ const [row] = await db+ .insert(notification)+ .values({+ workspaceId,+ name: `test-notification-${unique()}`,+ provider: "email",+ data: JSON.stringify({ email: `test-${unique()}@openstatus.dev` }),+ ...overrides,+ })+ .returning();+ if (!row) throw new Error("factory insert returned no row");+ return row;+}++export async function linkNotificationToMonitor(+ notificationId: number,+ monitorId: number,+ db: Db = defaultDb,+) {+ const [row] = await db+ .insert(notificationsToMonitors)+ .values({ notificationId, monitorId })+ .returning();+ if (!row) throw new Error("factory insert returned no row");+ return row;+}++export type TestWorkspaceFixture = {+ workspace: Awaited<ReturnType<typeof createWorkspace>>;+ user: Awaited<ReturnType<typeof createUser>>;+};++/**+ * A workspace with an owner, isolated from the seed fixtures and from every+ * other suite. Prefer this over the seeded workspaces so suites can assert on+ * exact counts and on workspace-scoped side effects like `audit_log`.+ *+ * Not torn down: `onDelete: "cascade"` is set on only some workspace-scoped+ * tables, so a delete would fail on the rest. Test databases are ephemeral.+ */+export async function createTestWorkspace(+ overrides: Partial<WorkspaceInsert> = {},+ db: Db = defaultDb,+): Promise<TestWorkspaceFixture> {+ const plan = overrides.plan ?? "team";+ const ws = await createWorkspace(+ {+ // Match the seeded team workspace's looser caps; `free` keeps plan defaults+ // so quota-rejection tests still hit their limits.+ limits: plan === "team" ? TEAM_WORKSPACE_LIMITS : "{}",+ ...overrides,+ plan,+ },+ db,+ );+ const owner = await createUser({}, db);+ await addUserToWorkspace(owner.id, ws.id, "owner", db);+ return { workspace: ws, user: owner };+}diff --git a/packages/services/src/__tests__/with-transaction.test.ts b/packages/services/src/__tests__/with-transaction.test.tsindex aa86f019f..cf6a9d3d9 100644--- a/packages/services/src/__tests__/with-transaction.test.ts+++ b/packages/services/src/__tests__/with-transaction.test.ts@@ -1,8 +1,7 @@import { expect } from "@std/expect";import { beforeAll, describe, test } from "@std/testing/bdd";-import { SEEDED_WORKSPACE_TEAM_ID } from "../../test/fixtures";-import { loadSeededWorkspace } from "../../test/helpers";+import { createWorkspaceFixture } from "../../test/helpers";import type { DB, ServiceContext } from "../context";import { isTx, withTransaction } from "../context";@@ -10,7 +9,7 @@ describe("withTransaction", () => {let ctx: ServiceContext;beforeAll(async () => {- const workspace = await loadSeededWorkspace(SEEDED_WORKSPACE_TEAM_ID);+ const workspace = (await createWorkspaceFixture("team")).workspace;ctx = {workspace,actor: { type: "user", userId: 1 },diff --git a/packages/services/src/agent-tools/__tests__/shape-equivalence.test.ts b/packages/services/src/agent-tools/__tests__/shape-equivalence.test.tsindex ae1a50e68..947a0a46f 100644--- a/packages/services/src/agent-tools/__tests__/shape-equivalence.test.ts+++ b/packages/services/src/agent-tools/__tests__/shape-equivalence.test.ts@@ -1,17 +1,20 @@+import { createMonitor } from "@openstatus/db/src/test/factories";import { expect } from "@std/expect";import { beforeAll, describe, test } from "@std/testing/bdd";-import { SEEDED_WORKSPACE_TEAM_ID } from "../../../test/fixtures";-import { loadSeededWorkspace, makeUserCtx } from "../../../test/helpers";+import { createWorkspaceFixture, makeUserCtx } from "../../../test/helpers";import type { ServiceContext } from "../../context";import { agentTools } from "../index";import type { AnyAgentTool } from "../types";let teamCtx: ServiceContext;+let monitorId: number;beforeAll(async () => {- const team = await loadSeededWorkspace(SEEDED_WORKSPACE_TEAM_ID);- teamCtx = makeUserCtx(team, { userId: 1 });+ const { workspace, userId } = await createWorkspaceFixture("team");+ teamCtx = makeUserCtx(workspace, { userId });+ const monitor = await createMonitor(workspace.id);+ monitorId = monitor.id;});describe("agent-tool shape equivalence", () => {@@ -69,15 +72,11 @@ describe("agent-tool shape equivalence", () => {expect(parsed.success, parsed.error?.message).toBe(true);});- // Monitor-bound reads need an actual monitor id. The seeded team- // workspace has monitor #1 (`OpenStatus`) β see packages/db/src/seed.mts.- const SEEDED_TEAM_MONITOR_ID = 1;-test("get_monitor output matches schema", async () => {const tool = agentTools.get_monitor;const result = await tool.run({ctx: teamCtx,- input: { monitorId: SEEDED_TEAM_MONITOR_ID },+ input: { monitorId },});const parsed = tool.outputSchema.safeParse(result);expect(parsed.success, parsed.error?.message).toBe(true);@@ -87,7 +86,7 @@ describe("agent-tool shape equivalence", () => {const tool = agentTools.get_monitor_status;const result = await tool.run({ctx: teamCtx,- input: { monitorId: SEEDED_TEAM_MONITOR_ID },+ input: { monitorId },});const parsed = tool.outputSchema.safeParse(result);expect(parsed.success, parsed.error?.message).toBe(true);@@ -97,7 +96,7 @@ describe("agent-tool shape equivalence", () => {const tool = agentTools.get_monitor_summary;const result = await tool.run({ctx: teamCtx,- input: { monitorId: SEEDED_TEAM_MONITOR_ID, timeRange: "1d" },+ input: { monitorId, timeRange: "1d" },});const parsed = tool.outputSchema.safeParse(result);expect(parsed.success, parsed.error?.message).toBe(true);@@ -108,7 +107,7 @@ describe("agent-tool shape equivalence", () => {const result = await tool.run({ctx: teamCtx,input: {- monitorId: SEEDED_TEAM_MONITOR_ID,+ monitorId,timeRange: "1d",limit: 10,offset: 0,diff --git a/packages/services/src/agent-tools/__tests__/status-report-impacts.test.ts b/packages/services/src/agent-tools/__tests__/status-report-impacts.test.tsindex cb0f7c38d..409636b77 100644--- a/packages/services/src/agent-tools/__tests__/status-report-impacts.test.ts+++ b/packages/services/src/agent-tools/__tests__/status-report-impacts.test.ts@@ -2,9 +2,8 @@ import { page, pageComponent } from "@openstatus/db/src/schema";import { expect } from "@std/expect";import { beforeAll, describe, test } from "@std/testing/bdd";-import { SEEDED_WORKSPACE_TEAM_ID } from "../../../test/fixtures";import {- loadSeededWorkspace,+ createWorkspaceFixture,makeUserCtx,withTestTransaction,} from "../../../test/helpers";@@ -20,7 +19,7 @@ const TEST_PREFIX = "agent-tools-impacts-test";let teamCtx: ServiceContext;beforeAll(async () => {- const team = await loadSeededWorkspace(SEEDED_WORKSPACE_TEAM_ID);+ const team = (await createWorkspaceFixture("team")).workspace;teamCtx = makeUserCtx(team, { userId: 1 });});diff --git a/packages/services/src/api-key/__tests__/api-key.test.ts b/packages/services/src/api-key/__tests__/api-key.test.tsindex 7a199c8b7..0c50123fa 100644--- a/packages/services/src/api-key/__tests__/api-key.test.ts+++ b/packages/services/src/api-key/__tests__/api-key.test.ts@@ -3,10 +3,9 @@ import { apiKey } from "@openstatus/db/src/schema";import { expect } from "@std/expect";import { beforeAll, describe, test } from "@std/testing/bdd";-import { SEEDED_WORKSPACE_TEAM_ID } from "../../../test/fixtures";import {+ createWorkspaceFixture,expectAuditRow,- loadSeededWorkspace,makeApiKeyCtx,makeUserCtx,readAuditLog,@@ -27,7 +26,7 @@ const TEST_PREFIX = "svc-apikey-test";let teamCtx: ServiceContext;beforeAll(async () => {- const team = await loadSeededWorkspace(SEEDED_WORKSPACE_TEAM_ID);+ const team = (await createWorkspaceFixture("team")).workspace;teamCtx = makeUserCtx(team, { userId: 1 });});@@ -41,7 +40,7 @@ describe("createApiKey", () => {});expect(token).toMatch(/^os_[a-f0-9]{32}$/);- expect(key.workspaceId).toBe(SEEDED_WORKSPACE_TEAM_ID);+ expect(key.workspaceId).toBe(teamCtx.workspace.id);const stored = await tx.select({ hashedToken: apiKey.hashedToken })@@ -111,9 +110,8 @@ describe("createApiKey", () => {test("rejects read-only actor", async () => {await withTestTransaction(async (tx) => {- const team = await loadSeededWorkspace(SEEDED_WORKSPACE_TEAM_ID);const readOnlyCtx = {- ...makeApiKeyCtx(team, {+ ...makeApiKeyCtx(teamCtx.workspace, {keyId: "k-read",userId: 1,scopes: ["read"],@@ -173,7 +171,6 @@ describe("revokeApiKey", () => {test("self-revoke carve-out: read-only key can revoke itself", async () => {await withTestTransaction(async (tx) => {- const team = await loadSeededWorkspace(SEEDED_WORKSPACE_TEAM_ID);// Create the key as a user so we get a real row id back.const { key } = await createApiKey({ctx: { ...teamCtx, db: tx },@@ -182,7 +179,7 @@ describe("revokeApiKey", () => {// Now revoke as the read-only key itself β should succeed.const selfCtx = {- ...makeApiKeyCtx(team, {+ ...makeApiKeyCtx(teamCtx.workspace, {keyId: String(key.id),userId: 1,scopes: ["read"],@@ -244,7 +241,6 @@ describe("revokeApiKey", () => {test("read-only actor cannot revoke a different key", async () => {await withTestTransaction(async (tx) => {- const team = await loadSeededWorkspace(SEEDED_WORKSPACE_TEAM_ID);const { key } = await createApiKey({ctx: { ...teamCtx, db: tx },input: { name: `${TEST_PREFIX}-other-key` },@@ -252,7 +248,7 @@ describe("revokeApiKey", () => {// Read-only actor with a different keyId tries to revoke `key`.const otherCtx = {- ...makeApiKeyCtx(team, {+ ...makeApiKeyCtx(teamCtx.workspace, {keyId: "different-key-id",userId: 1,scopes: ["read"],diff --git a/packages/services/src/audit/__tests__/audit.test.ts b/packages/services/src/audit/__tests__/audit.test.tsindex de082c72f..6296e1096 100644--- a/packages/services/src/audit/__tests__/audit.test.ts+++ b/packages/services/src/audit/__tests__/audit.test.ts@@ -4,13 +4,9 @@ import type { AuditEntry } from "@openstatus/db/src/schema";import { expect } from "@std/expect";import { afterAll, beforeAll, describe, test } from "@std/testing/bdd";-import {- SEEDED_WORKSPACE_FREE_ID,- SEEDED_WORKSPACE_TEAM_ID,-} from "../../../test/fixtures";import {clearAuditLog,- loadSeededWorkspace,+ createWorkspaceFixture,makeApiKeyCtx,makeSlackCtx,makeSystemCtx,@@ -40,17 +36,25 @@ async function emitLoose(}let teamCtx: ServiceContext;+let teamUserId: number;+let otherCtx: ServiceContext;beforeAll(async () => {- const team = await loadSeededWorkspace(SEEDED_WORKSPACE_TEAM_ID);- teamCtx = makeUserCtx(team, { userId: 1 });+ const team = await createWorkspaceFixture("team");+ teamUserId = team.userId;+ teamCtx = makeUserCtx(team.workspace, { userId: teamUserId });+ // Built here rather than inside a test: `withTestTransaction` holds an open+ // transaction on the shared connection, and a committed write mid-stream+ // aborts it.+ const other = await createWorkspaceFixture("free");+ otherCtx = makeUserCtx(other.workspace, { userId: other.userId });// Wipe rows from prior aborted runs β the fail-closed test below runs// outside `withTestTransaction` and could leak on a botched prior run.await clearAuditLog(teamCtx.workspace.id);});afterAll(async () => {- await clearAuditLog(SEEDED_WORKSPACE_TEAM_ID);+ await clearAuditLog(teamCtx.workspace.id);});describe("diffTopLevel", () => {@@ -155,8 +159,8 @@ describe("emitAudit β row persistence", () => {expect(row.entityType).toBe("monitor");expect(row.entityId).toBe("9001");expect(row.actorType).toBe("user");- expect(row.actorId).toBe("1");- expect(row.actorUserId).toBe(1);+ expect(row.actorId).toBe(String(teamUserId));+ expect(row.actorUserId).toBe(teamUserId);expect(row.metadata).toEqual({jobType: "http",url: "https://example.com",@@ -366,8 +370,8 @@ describe("emitAudit β actor derivation", () => {db: tx,});expect(row?.actorType).toBe("user");- expect(row?.actorId).toBe("1");- expect(row?.actorUserId).toBe(1);+ expect(row?.actorId).toBe(String(teamUserId));+ expect(row?.actorUserId).toBe(teamUserId);});});@@ -604,7 +608,7 @@ describe("getAuditLog", () => {expect(row.entityType).toBe("monitor");expect(row.entityId).toBe("9800");expect(row.changedFields).toEqual(["name"]);- expect(row.user?.id).toBe(1);+ expect(row.user?.id).toBe(teamUserId);});});@@ -624,11 +628,6 @@ describe("getAuditLog", () => {});if (!inserted) throw new Error("unreachable");- const otherWorkspace = await loadSeededWorkspace(- SEEDED_WORKSPACE_FREE_ID,- );- const otherCtx = makeUserCtx(otherWorkspace, { userId: 1 });-let caught: unknown;try {await getAuditLog({diff --git a/packages/services/src/frozen-uptime/__tests__/freeze.test.ts b/packages/services/src/frozen-uptime/__tests__/freeze.test.tsindex 7f2416a83..5f20f598f 100644--- a/packages/services/src/frozen-uptime/__tests__/freeze.test.ts+++ b/packages/services/src/frozen-uptime/__tests__/freeze.test.ts@@ -7,9 +7,8 @@ import {import { expect } from "@std/expect";import { beforeAll, describe, test } from "@std/testing/bdd";-import { SEEDED_WORKSPACE_TEAM_ID } from "../../../test/fixtures";import {- loadSeededWorkspace,+ createWorkspaceFixture,makeApiKeyCtx,makeSystemCtx,readAuditLog,@@ -22,13 +21,15 @@ import type { FreezeMonitorMonthInput } from "../schemas";let systemCtx: ServiceContext;let readOnlyCtx: ServiceContext;+let teamWorkspaceId: number;beforeAll(async () => {- const team = await loadSeededWorkspace(SEEDED_WORKSPACE_TEAM_ID);- systemCtx = makeSystemCtx(team, { job: "uptime-freeze" });- readOnlyCtx = makeApiKeyCtx(team, {+ const team = await createWorkspaceFixture("team");+ teamWorkspaceId = team.workspace.id;+ systemCtx = makeSystemCtx(team.workspace, { job: "uptime-freeze" });+ readOnlyCtx = makeApiKeyCtx(team.workspace, {keyId: "k",- userId: 1,+ userId: team.userId,scopes: ["read"],});});@@ -37,7 +38,7 @@ async function insertTestMonitor(tx: NonNullable<ServiceContext["db"]>) {return tx.insert(monitor).values({- workspaceId: SEEDED_WORKSPACE_TEAM_ID,+ workspaceId: teamWorkspaceId,active: true,url: "https://example.com",name: "svc-frozen-uptime-monitor",@@ -72,7 +73,7 @@ describe("freezeMonitorMonth", () => {const row = await freezeMonitorMonth({ ctx, input });expect(row).not.toBeNull();- expect(row?.workspaceId).toBe(SEEDED_WORKSPACE_TEAM_ID);+ expect(row?.workspaceId).toBe(teamWorkspaceId);expect(row?.month).toBe("2026-06-01");expect(row?.days).toEqual(input.days);@@ -84,7 +85,7 @@ describe("freezeMonitorMonth", () => {expect(persisted.length).toBe(1);const auditRows = await readAuditLog({- workspaceId: SEEDED_WORKSPACE_TEAM_ID,+ workspaceId: teamWorkspaceId,entityType: "frozen_monitor_uptime",db: tx,});@@ -120,7 +121,7 @@ describe("freezeMonitorMonth", () => {expect(persisted[0].days[0].ok).toBe(42);const auditRows = await readAuditLog({- workspaceId: SEEDED_WORKSPACE_TEAM_ID,+ workspaceId: teamWorkspaceId,entityType: "frozen_monitor_uptime",db: tx,});diff --git a/packages/services/src/frozen-uptime/__tests__/get-history.test.ts b/packages/services/src/frozen-uptime/__tests__/get-history.test.tsindex d4ec0b7be..021789068 100644--- a/packages/services/src/frozen-uptime/__tests__/get-history.test.ts+++ b/packages/services/src/frozen-uptime/__tests__/get-history.test.ts@@ -14,11 +14,7 @@ import { expect } from "@std/expect";import { beforeAll, describe, test } from "@std/testing/bdd";import {- SEEDED_WORKSPACE_FREE_ID,- SEEDED_WORKSPACE_TEAM_ID,-} from "../../../test/fixtures";-import {- loadSeededWorkspace,+ createWorkspaceFixture,makeUserCtx,withTestTransaction,} from "../../../test/helpers";@@ -34,12 +30,14 @@ const noSleep = () => Promise.resolve();let userCtx: ServiceContext;let freeCtx: ServiceContext;+let teamWorkspaceId: number;beforeAll(async () => {- userCtx = makeUserCtx(await loadSeededWorkspace(SEEDED_WORKSPACE_TEAM_ID));- freeCtx = makeUserCtx(await loadSeededWorkspace(SEEDED_WORKSPACE_FREE_ID), {- userId: 2,- });+ const team = await createWorkspaceFixture("team");+ teamWorkspaceId = team.workspace.id;+ userCtx = makeUserCtx(team.workspace, { userId: team.userId });+ const free = await createWorkspaceFixture("free");+ freeCtx = makeUserCtx(free.workspace, { userId: free.userId });});// tests anchor months to the real clock: getEvents filters against `new@@ -98,7 +96,7 @@ async function insertPage(return tx.insert(page).values({- workspaceId: SEEDED_WORKSPACE_TEAM_ID,+ workspaceId: teamWorkspaceId,title: "svc-history-page",description: "",slug: `svc-history-${Date.now()}-${slugCounter++}`,@@ -113,7 +111,7 @@ async function insertMonitor(tx: Tx) {return tx.insert(monitor).values({- workspaceId: SEEDED_WORKSPACE_TEAM_ID,+ workspaceId: teamWorkspaceId,active: true,url: "https://example.com",name: "svc-history-monitor",@@ -138,7 +136,7 @@ async function insertComponent(return tx.insert(pageComponent).values({- workspaceId: SEEDED_WORKSPACE_TEAM_ID,+ workspaceId: teamWorkspaceId,pageId: args.pageId,type: args.monitorId ? "monitor" : "static",monitorId: args.monitorId ?? null,@@ -155,7 +153,7 @@ async function insertFrozen() {return tx.insert(frozenMonitorUptime)- .values({ workspaceId: SEEDED_WORKSPACE_TEAM_ID, ...args })+ .values({ workspaceId: teamWorkspaceId, ...args }).returning().get();}@@ -174,7 +172,7 @@ async function insertImpactReport(const report = await tx.insert(statusReport).values({- workspaceId: SEEDED_WORKSPACE_TEAM_ID,+ workspaceId: teamWorkspaceId,pageId: args.pageId,status: "resolved",title: "svc-history-report",@@ -231,7 +229,7 @@ async function insertLegacyReport(const report = await tx.insert(statusReport).values({- workspaceId: SEEDED_WORKSPACE_TEAM_ID,+ workspaceId: teamWorkspaceId,pageId: args.pageId,status: "resolved",title: "svc-history-legacy-report",@@ -534,7 +532,7 @@ describe("getUptimeHistory", () => {const twoHours = 2 * 3_600_000;// incident and major report describe the same 2h outage β merged onceawait tx.insert(incidentTable).values({- workspaceId: SEEDED_WORKSPACE_TEAM_ID,+ workspaceId: teamWorkspaceId,monitorId: testMonitor.id,startedAt: new Date(base),createdAt: new Date(base),@@ -657,7 +655,7 @@ describe("getUptimeHistory", () => {]);const twoHours = 2 * 3_600_000;await tx.insert(incidentTable).values({- workspaceId: SEEDED_WORKSPACE_TEAM_ID,+ workspaceId: teamWorkspaceId,monitorId: testMonitor.id,startedAt: new Date(start + twoHours),createdAt: new Date(start + twoHours),diff --git a/packages/services/src/import/__tests__/incidents-phase.test.ts b/packages/services/src/import/__tests__/incidents-phase.test.tsindex 64d2b6d6a..77e3514ff 100644--- a/packages/services/src/import/__tests__/incidents-phase.test.ts+++ b/packages/services/src/import/__tests__/incidents-phase.test.ts@@ -11,9 +11,8 @@ import type { PhaseResult } from "@openstatus/importers";import { expect } from "@std/expect";import { beforeAll, describe, test } from "@std/testing/bdd";-import { SEEDED_WORKSPACE_TEAM_ID } from "../../../test/fixtures";import {- loadSeededWorkspace,+ createWorkspaceFixture,makeUserCtx,withTestTransaction,} from "../../../test/helpers";@@ -25,7 +24,7 @@ const TEST_PREFIX = "svc-import-incidents-test";let teamCtx: ServiceContext;beforeAll(async () => {- const team = await loadSeededWorkspace(SEEDED_WORKSPACE_TEAM_ID);+ const team = (await createWorkspaceFixture("team")).workspace;teamCtx = makeUserCtx(team, { userId: 1 });});diff --git a/packages/services/src/incident/__tests__/incident.test.ts b/packages/services/src/incident/__tests__/incident.test.tsindex ae0eec54d..db0028beb 100644--- a/packages/services/src/incident/__tests__/incident.test.ts+++ b/packages/services/src/incident/__tests__/incident.test.ts@@ -3,13 +3,9 @@ import { incidentTable, monitor } from "@openstatus/db/src/schema";import { expect } from "@std/expect";import { afterAll, beforeAll, describe, test } from "@std/testing/bdd";-import {- SEEDED_WORKSPACE_FREE_ID,- SEEDED_WORKSPACE_TEAM_ID,-} from "../../../test/fixtures";import {expectAuditRow,- loadSeededWorkspace,+ createWorkspaceFixture,makeApiKeyCtx,makeUserCtx,withTestTransaction,@@ -28,8 +24,8 @@ let freeCtx: ServiceContext;let testMonitorId: number;beforeAll(async () => {- const team = await loadSeededWorkspace(SEEDED_WORKSPACE_TEAM_ID);- const free = await loadSeededWorkspace(SEEDED_WORKSPACE_FREE_ID);+ const team = (await createWorkspaceFixture("team")).workspace;+ const free = (await createWorkspaceFixture("free")).workspace;teamCtx = makeUserCtx(team, { userId: 1 });freeCtx = makeUserCtx(free, { userId: 2 });diff --git a/packages/services/src/integration/__tests__/install-slack-agent.test.ts b/packages/services/src/integration/__tests__/install-slack-agent.test.tsindex ddbfa8771..83420f683 100644--- a/packages/services/src/integration/__tests__/install-slack-agent.test.ts+++ b/packages/services/src/integration/__tests__/install-slack-agent.test.ts@@ -1,12 +1,11 @@-import { and, db, desc, eq } from "@openstatus/db";+import { and, desc, eq } from "@openstatus/db";import { integration } from "@openstatus/db/src/schema";import { expect } from "@std/expect";-import { afterAll, beforeAll, describe, test } from "@std/testing/bdd";+import { beforeAll, describe, test } from "@std/testing/bdd";-import { SEEDED_WORKSPACE_TEAM_ID } from "../../../test/fixtures";import {clearAuditLog,- loadSeededWorkspace,+ createWorkspaceFixture,makeApiKeyCtx,makeSlackCtx,readAuditLog,@@ -21,30 +20,12 @@ const SLACK_USER_ID = "U_FIXTURE";let ctx: ServiceContext;-async function clearSlackAgentRows() {- await db- .delete(integration)- .where(- and(- eq(integration.workspaceId, SEEDED_WORKSPACE_TEAM_ID),- eq(integration.name, "slack-agent"),- ),- )- .catch(() => undefined);-}-beforeAll(async () => {- const team = await loadSeededWorkspace(SEEDED_WORKSPACE_TEAM_ID);- ctx = makeSlackCtx(team, { teamId: TEAM_ID, slackUserId: SLACK_USER_ID });- // Wipe leftover slack-agent rows from prior aborted runs β a stale- // committed row would block fresh installs (one slack-agent per workspace).- await clearSlackAgentRows();- await clearAuditLog(SEEDED_WORKSPACE_TEAM_ID);-});--afterAll(async () => {- await clearSlackAgentRows();- await clearAuditLog(SEEDED_WORKSPACE_TEAM_ID);+ const team = await createWorkspaceFixture("team");+ ctx = makeSlackCtx(team.workspace, {+ teamId: TEAM_ID,+ slackUserId: SLACK_USER_ID,+ });});const baseInput = {@@ -68,11 +49,11 @@ describe("installSlackAgent", () => {});expect(created.name).toBe("slack-agent");- expect(created.workspaceId).toBe(SEEDED_WORKSPACE_TEAM_ID);+ expect(created.workspaceId).toBe(ctx.workspace.id);expect(created.externalId).toBe(TEAM_ID);const rows = await readAuditLog({- workspaceId: SEEDED_WORKSPACE_TEAM_ID,+ workspaceId: ctx.workspace.id,entityType: "integration",entityId: created.id,db: tx,@@ -92,7 +73,7 @@ describe("installSlackAgent", () => {await withTestTransaction(async (tx) => {const ctxTx = { ...ctx, db: tx };const created = await installSlackAgent({ ctx: ctxTx, input: baseInput });- await clearAuditLog(SEEDED_WORKSPACE_TEAM_ID, { db: tx });+ await clearAuditLog(ctx.workspace.id, { db: tx });const reinstalled = await installSlackAgent({ctx: ctxTx,@@ -106,7 +87,7 @@ describe("installSlackAgent", () => {expect(reinstalled.id).toBe(created.id);const rows = await readAuditLog({- workspaceId: SEEDED_WORKSPACE_TEAM_ID,+ workspaceId: ctx.workspace.id,entityType: "integration",entityId: created.id,db: tx,@@ -125,7 +106,7 @@ describe("installSlackAgent", () => {await withTestTransaction(async (tx) => {const ctxTx = { ...ctx, db: tx };const created = await installSlackAgent({ ctx: ctxTx, input: baseInput });- await clearAuditLog(SEEDED_WORKSPACE_TEAM_ID, { db: tx });+ await clearAuditLog(ctx.workspace.id, { db: tx });await installSlackAgent({ctx: ctxTx,@@ -136,7 +117,7 @@ describe("installSlackAgent", () => {});const rows = await readAuditLog({- workspaceId: SEEDED_WORKSPACE_TEAM_ID,+ workspaceId: ctx.workspace.id,entityType: "integration",entityId: created.id,db: tx,@@ -151,12 +132,12 @@ describe("installSlackAgent", () => {await withTestTransaction(async (tx) => {const ctxTx = { ...ctx, db: tx };const created = await installSlackAgent({ ctx: ctxTx, input: baseInput });- await clearAuditLog(SEEDED_WORKSPACE_TEAM_ID, { db: tx });+ await clearAuditLog(ctx.workspace.id, { db: tx });await installSlackAgent({ ctx: ctxTx, input: baseInput });const rows = await readAuditLog({- workspaceId: SEEDED_WORKSPACE_TEAM_ID,+ workspaceId: ctx.workspace.id,entityType: "integration",entityId: created.id,db: tx,@@ -190,7 +171,7 @@ describe("installSlackAgent", () => {.insert(integration).values({name: "slack-agent",- workspaceId: SEEDED_WORKSPACE_TEAM_ID,+ workspaceId: ctx.workspace.id,externalId: "T_OLD_1",credential: { botToken: "xoxb-old-1", botUserId: "B_OLD_1" },data: { ...baseInput.data, teamId: "T_OLD_1" },@@ -200,13 +181,13 @@ describe("installSlackAgent", () => {.insert(integration).values({name: "slack-agent",- workspaceId: SEEDED_WORKSPACE_TEAM_ID,+ workspaceId: ctx.workspace.id,externalId: "T_OLD_2",credential: { botToken: "xoxb-old-2", botUserId: "B_OLD_2" },data: { ...baseInput.data, teamId: "T_OLD_2" },}).returning();- await clearAuditLog(SEEDED_WORKSPACE_TEAM_ID, { db: tx });+ await clearAuditLog(ctx.workspace.id, { db: tx });await installSlackAgent({ ctx: ctxTx, input: baseInput });@@ -216,7 +197,7 @@ describe("installSlackAgent", () => {.where(and(eq(integration.name, "slack-agent"),- eq(integration.workspaceId, SEEDED_WORKSPACE_TEAM_ID),+ eq(integration.workspaceId, ctx.workspace.id),),).orderBy(desc(integration.id))@@ -225,7 +206,7 @@ describe("installSlackAgent", () => {expect(remaining[0].id).toBe(second.id);const all = await readAuditLog({- workspaceId: SEEDED_WORKSPACE_TEAM_ID,+ workspaceId: ctx.workspace.id,entityType: "integration",db: tx,});@@ -280,7 +261,7 @@ describe("installSlackAgent", () => {});const rows = await readAuditLog({- workspaceId: SEEDED_WORKSPACE_TEAM_ID,+ workspaceId: ctx.workspace.id,entityType: "integration",entityId: created.id,db: tx,diff --git a/packages/services/src/invitation/__tests__/invitation.test.ts b/packages/services/src/invitation/__tests__/invitation.test.tsindex 58ff31328..5d6f4a8a6 100644--- a/packages/services/src/invitation/__tests__/invitation.test.ts+++ b/packages/services/src/invitation/__tests__/invitation.test.ts@@ -1,15 +1,12 @@-import { db, eq } from "@openstatus/db";-import { invitation, user, usersToWorkspaces } from "@openstatus/db/src/schema";+import { eq } from "@openstatus/db";+import { invitation, usersToWorkspaces } from "@openstatus/db/src/schema";+import { createUser } from "@openstatus/db/src/test/factories";import { expect } from "@std/expect";-import { afterAll, beforeAll, describe, test } from "@std/testing/bdd";+import { beforeAll, describe, test } from "@std/testing/bdd";import {- SEEDED_WORKSPACE_FREE_ID,- SEEDED_WORKSPACE_TEAM_ID,-} from "../../../test/fixtures";-import {+ createWorkspaceFixture,expectAuditRow,- loadSeededWorkspace,makeApiKeyCtx,makeUserCtx,withTestTransaction,@@ -31,63 +28,23 @@ import {const TEST_PREFIX = "svc-inv-test";let teamCtx: ServiceContext;+let teamUserId: number;let freeCtx: ServiceContext;+let acceptingUserId: number;beforeAll(async () => {- const team = await loadSeededWorkspace(SEEDED_WORKSPACE_TEAM_ID);- const free = await loadSeededWorkspace(SEEDED_WORKSPACE_FREE_ID);- teamCtx = makeUserCtx(team, { userId: 1 });- freeCtx = makeUserCtx(free, { userId: 2 });-- // Seed membership for the free workspace so the `members: 1` cap- // can actually be reached by a subsequent `createInvitation` β the- // shared DB seed only adds a row for workspace 1 (team). Without- // this, the members-cap assertion below passes against `0 < 1` and- // never reaches the LimitExceededError branch.- //- // `userId: 1` instead of `2` β only user 1 is in the shared seed,- // and the `user_id` FK on `users_to_workspaces` rejects unknown- // ids. The cap check just counts rows by `workspace_id`, so which- // user occupies the slot doesn't matter.- await db- .insert(usersToWorkspaces)- .values({ workspaceId: SEEDED_WORKSPACE_FREE_ID, userId: 1 })- .onConflictDoNothing();-- // Seed the accepting user for the `acceptInvitation` test below.- // The test accepts as `userId: 3` and the ensuing- // `users_to_workspaces` insert has an FK on `user.id` β without a- // seeded row the insert blows up with a `SQLITE_CONSTRAINT`- // surfacing as a hook-timeout in the suite. Tear it down in- // `afterAll` alongside the membership.- await db- .insert(user)- .values({- id: 3,- tenantId: "invitation-test-3",- firstName: "Accept",- lastName: "Tester",- email: "[email protected]",- photoUrl: "",- })- .onConflictDoNothing();-});--afterAll(async () => {- await db- .delete(usersToWorkspaces)- .where(eq(usersToWorkspaces.workspaceId, SEEDED_WORKSPACE_FREE_ID))- .catch(() => undefined);- // `acceptInvitation` test seeded user 3 as the accepting user β- // clean up membership and the user row itself.- await db- .delete(usersToWorkspaces)- .where(eq(usersToWorkspaces.userId, 3))- .catch(() => undefined);- await db- .delete(user)- .where(eq(user.id, 3))- .catch(() => undefined);+ const team = await createWorkspaceFixture("team");+ teamUserId = team.userId;+ teamCtx = makeUserCtx(team.workspace, { userId: teamUserId });++ // The free workspace's owner membership already occupies its single+ // `members: 1` slot, so `createInvitation` reaches the cap.+ const free = await createWorkspaceFixture("free");+ freeCtx = makeUserCtx(free.workspace, { userId: free.userId });++ // `acceptInvitation` inserts a `users_to_workspaces` row, which has an FK+ // on `user.id`.+ acceptingUserId = (await createUser()).id;});describe("createInvitation", () => {@@ -101,7 +58,7 @@ describe("createInvitation", () => {});expect(row.email).toBe(email);- expect(row.workspaceId).toBe(SEEDED_WORKSPACE_TEAM_ID);+ expect(row.workspaceId).toBe(teamCtx.workspace.id);expect(row.token).toBeDefined();expect(row.expiresAt.getTime()).toBeGreaterThan(Date.now());@@ -120,7 +77,7 @@ describe("createInvitation", () => {const readOnlyCtx = {...makeApiKeyCtx(teamCtx.workspace, {keyId: "k-read",- userId: 1,+ userId: teamUserId,scopes: ["read"],}),db: tx,@@ -183,7 +140,7 @@ describe("getInvitationByToken", () => {input: { token: created.token, email },});expect(row.id).toBe(created.id);- expect(row.workspace.id).toBe(SEEDED_WORKSPACE_TEAM_ID);+ expect(row.workspace.id).toBe(teamCtx.workspace.id);});});@@ -236,7 +193,6 @@ describe("acceptInvitation", () => {await withTestTransaction(async (tx) => {// The user id comes from `ctx.actor`, not from input β so we build// a ctx scoped to the accepting user rather than passing an id.- const acceptingUserId = 3;const email = `${TEST_PREFIX}-accept-${acceptingUserId}-${Date.now()}@example.com`;const created = await createInvitation({ctx: { ...teamCtx, db: tx },@@ -251,7 +207,7 @@ describe("acceptInvitation", () => {ctx: acceptingCtx,input: { id: created.id, email },});- expect(workspaceRow.id).toBe(SEEDED_WORKSPACE_TEAM_ID);+ expect(workspaceRow.id).toBe(teamCtx.workspace.id);const updated = await tx.select()@@ -265,7 +221,7 @@ describe("acceptInvitation", () => {.from(usersToWorkspaces).where(eq(usersToWorkspaces.userId, acceptingUserId)).get();- expect(membership?.workspaceId).toBe(SEEDED_WORKSPACE_TEAM_ID);+ expect(membership?.workspaceId).toBe(teamCtx.workspace.id);});});diff --git a/packages/services/src/maintenance/__tests__/maintenance.test.ts b/packages/services/src/maintenance/__tests__/maintenance.test.tsindex 32afbbba2..3b48ae006 100644--- a/packages/services/src/maintenance/__tests__/maintenance.test.ts+++ b/packages/services/src/maintenance/__tests__/maintenance.test.ts@@ -13,13 +13,9 @@ import {test,} from "@std/testing/bdd";-import {- SEEDED_WORKSPACE_FREE_ID,- SEEDED_WORKSPACE_TEAM_ID,-} from "../../../test/fixtures";import {expectAuditRow,- loadSeededWorkspace,+ createWorkspaceFixture,makeApiKeyCtx,makeSlackCtx,makeUserCtx,@@ -55,8 +51,8 @@ let otherPageId: number;let otherPageComponentId: number;beforeAll(async () => {- const team = await loadSeededWorkspace(SEEDED_WORKSPACE_TEAM_ID);- const free = await loadSeededWorkspace(SEEDED_WORKSPACE_FREE_ID);+ const team = (await createWorkspaceFixture("team")).workspace;+ const free = (await createWorkspaceFixture("free")).workspace;teamCtx = makeUserCtx(team, { userId: 1 });freeCtx = makeUserCtx(free, { userId: 2 });diff --git a/packages/services/src/member/__tests__/member.test.ts b/packages/services/src/member/__tests__/member.test.tsindex 305d8885c..ce1c1953f 100644--- a/packages/services/src/member/__tests__/member.test.ts+++ b/packages/services/src/member/__tests__/member.test.ts@@ -1,15 +1,15 @@-import { and, db, eq } from "@openstatus/db";-import { user, usersToWorkspaces } from "@openstatus/db/src/schema";+import { and, eq } from "@openstatus/db";+import { usersToWorkspaces } from "@openstatus/db/src/schema";+import {+ addUserToWorkspace,+ createUser,+} from "@openstatus/db/src/test/factories";import { expect } from "@std/expect";-import { afterAll, beforeAll, describe, test } from "@std/testing/bdd";+import { beforeAll, describe, test } from "@std/testing/bdd";import {- SEEDED_WORKSPACE_FREE_ID,- SEEDED_WORKSPACE_TEAM_ID,-} from "../../../test/fixtures";-import {+ createWorkspaceFixture,expectAuditRow,- loadSeededWorkspace,makeApiKeyCtx,makeSystemCtx,makeUserCtx,@@ -24,140 +24,28 @@ import {} from "../../errors";import { deleteMember, listMembers } from "../index.ts";-const OWNER_USER_ID = 1;-const VICTIM_USER_ID = 4242;-const NON_OWNER_USER_ID = 4243;-let teamCtx: ServiceContext;-// Captured so we can restore the seeded owner row in afterAll. The seed-// owns user 1's role for workspace 1; mutating it in place would leak-// into other suites that share the team workspace.-let ownerRoleBefore: "owner" | "admin" | "member" | null = null;+let freeWorkspace: ServiceContext["workspace"];+let OWNER_USER_ID: number;+let VICTIM_USER_ID: number;+let NON_OWNER_USER_ID: number;beforeAll(async () => {- const team = await loadSeededWorkspace(SEEDED_WORKSPACE_TEAM_ID);- teamCtx = makeUserCtx(team, { userId: OWNER_USER_ID });-- // Two synthetic users + memberships scoped to the team workspace.- // The seed only carries user 1; we need a victim and a non-owner- // distinct from the caller for the role-check branches.- await db- .insert(user)- .values([- {- id: VICTIM_USER_ID,- tenantId: "member-test-victim",- firstName: "Victim",- lastName: "Member",- email: "[email protected]",- photoUrl: "",- },- {- id: NON_OWNER_USER_ID,- tenantId: "member-test-nonowner",- firstName: "NonOwner",- lastName: "Member",- email: "[email protected]",- photoUrl: "",- },- ])- .onConflictDoNothing();-- const existingOwner = await db- .select({ role: usersToWorkspaces.role })- .from(usersToWorkspaces)- .where(- and(- eq(usersToWorkspaces.workspaceId, SEEDED_WORKSPACE_TEAM_ID),- eq(usersToWorkspaces.userId, OWNER_USER_ID),- ),- )- .get();- ownerRoleBefore = existingOwner?.role ?? null;-- // Caller (owner) β already in seed for workspace 1, but the seed's- // `users_to_workspaces` row may have a non-owner role; force `owner`.- await db- .insert(usersToWorkspaces)- .values({- workspaceId: SEEDED_WORKSPACE_TEAM_ID,- userId: OWNER_USER_ID,- role: "owner",- })- .onConflictDoUpdate({- target: [usersToWorkspaces.userId, usersToWorkspaces.workspaceId],- set: { role: "owner" },- });-- await db- .insert(usersToWorkspaces)- .values([- {- workspaceId: SEEDED_WORKSPACE_TEAM_ID,- userId: VICTIM_USER_ID,- role: "member",- },- {- workspaceId: SEEDED_WORKSPACE_TEAM_ID,- userId: NON_OWNER_USER_ID,- role: "member",- },- ])- .onConflictDoNothing();-});--afterAll(async () => {- await db- .delete(usersToWorkspaces)- .where(- and(- eq(usersToWorkspaces.workspaceId, SEEDED_WORKSPACE_TEAM_ID),- eq(usersToWorkspaces.userId, VICTIM_USER_ID),- ),- )- .catch(() => undefined);- await db- .delete(usersToWorkspaces)- .where(- and(- eq(usersToWorkspaces.workspaceId, SEEDED_WORKSPACE_TEAM_ID),- eq(usersToWorkspaces.userId, NON_OWNER_USER_ID),- ),- )- .catch(() => undefined);- await db- .delete(user)- .where(eq(user.id, VICTIM_USER_ID))- .catch(() => undefined);- await db- .delete(user)- .where(eq(user.id, NON_OWNER_USER_ID))- .catch(() => undefined);-- // Restore the seeded owner row to whatever it was before this suite β- // forcing `owner` in beforeAll otherwise pollutes shared fixtures.- if (ownerRoleBefore !== null) {- await db- .update(usersToWorkspaces)- .set({ role: ownerRoleBefore })- .where(- and(- eq(usersToWorkspaces.workspaceId, SEEDED_WORKSPACE_TEAM_ID),- eq(usersToWorkspaces.userId, OWNER_USER_ID),- ),- )- .catch(() => undefined);- } else {- await db- .delete(usersToWorkspaces)- .where(- and(- eq(usersToWorkspaces.workspaceId, SEEDED_WORKSPACE_TEAM_ID),- eq(usersToWorkspaces.userId, OWNER_USER_ID),- ),- )- .catch(() => undefined);- }+ const team = await createWorkspaceFixture("team");+ OWNER_USER_ID = team.userId;+ teamCtx = makeUserCtx(team.workspace, { userId: OWNER_USER_ID });++ const victim = await createUser();+ const nonOwner = await createUser();+ VICTIM_USER_ID = victim.id;+ NON_OWNER_USER_ID = nonOwner.id;+ await addUserToWorkspace(VICTIM_USER_ID, team.workspace.id, "member");+ await addUserToWorkspace(NON_OWNER_USER_ID, team.workspace.id, "member");++ // Built here, not inside a test: `withTestTransaction` holds an open+ // transaction on the shared connection and a committed write mid-stream+ // aborts it.+ freeWorkspace = (await createWorkspaceFixture("free")).workspace;});describe("listMembers", () => {@@ -184,7 +72,7 @@ describe("deleteMember", () => {.from(usersToWorkspaces).where(and(- eq(usersToWorkspaces.workspaceId, SEEDED_WORKSPACE_TEAM_ID),+ eq(usersToWorkspaces.workspaceId, teamCtx.workspace.id),eq(usersToWorkspaces.userId, VICTIM_USER_ID),),)@@ -192,7 +80,7 @@ describe("deleteMember", () => {expect(stillThere).toBeUndefined();await expectAuditRow({- workspaceId: SEEDED_WORKSPACE_TEAM_ID,+ workspaceId: teamCtx.workspace.id,action: "member.delete",entityType: "member",entityId: VICTIM_USER_ID,@@ -206,7 +94,7 @@ describe("deleteMember", () => {const readOnlyCtx = {...makeApiKeyCtx(teamCtx.workspace, {keyId: "k-read",- userId: 1,+ userId: OWNER_USER_ID,scopes: ["read"],}),db: tx,@@ -275,7 +163,7 @@ describe("deleteMember", () => {test("caller with no membership row in target workspace surfaces NOT_FOUND", async () => {await withTestTransaction(async (tx) => {- const free = await loadSeededWorkspace(SEEDED_WORKSPACE_FREE_ID);+ const free = freeWorkspace;// Pretend caller belongs to free workspace but actually doesn't β// the membership lookup will miss and throw NotFoundError.const stranger = {@@ -306,7 +194,7 @@ describe("deleteMember", () => {});const rows = await readAuditLog({- workspaceId: SEEDED_WORKSPACE_TEAM_ID,+ workspaceId: teamCtx.workspace.id,entityType: "member",entityId: NEVER_MEMBER_USER_ID,db: tx,@@ -320,7 +208,7 @@ describe("deleteMember", () => {// VICTIM is in the team workspace. Caller is owner of free workspace.// The delete WHERE filters by ctx.workspace.id, so the team-workspace// row is never matched β verifies the workspace scope on the DELETE.- const free = await loadSeededWorkspace(SEEDED_WORKSPACE_FREE_ID);+ const free = freeWorkspace;await tx.insert(usersToWorkspaces).values({@@ -343,7 +231,7 @@ describe("deleteMember", () => {.from(usersToWorkspaces).where(and(- eq(usersToWorkspaces.workspaceId, SEEDED_WORKSPACE_TEAM_ID),+ eq(usersToWorkspaces.workspaceId, teamCtx.workspace.id),eq(usersToWorkspaces.userId, VICTIM_USER_ID),),)diff --git a/packages/services/src/monitor-tag/__tests__/monitor-tag.test.ts b/packages/services/src/monitor-tag/__tests__/monitor-tag.test.tsindex 121cbe4a9..47361a40c 100644--- a/packages/services/src/monitor-tag/__tests__/monitor-tag.test.ts+++ b/packages/services/src/monitor-tag/__tests__/monitor-tag.test.ts@@ -1,12 +1,11 @@-import { db, eq } from "@openstatus/db";+import { eq } from "@openstatus/db";import { monitorTag } from "@openstatus/db/src/schema";import { expect } from "@std/expect";-import { afterAll, beforeAll, describe, test } from "@std/testing/bdd";+import { beforeAll, describe, test } from "@std/testing/bdd";-import { SEEDED_WORKSPACE_TEAM_ID } from "../../../test/fixtures";import {clearAuditLog,- loadSeededWorkspace,+ createWorkspaceFixture,makeApiKeyCtx,makeUserCtx,readAuditLog,@@ -18,23 +17,9 @@ import { listMonitorTags, syncMonitorTags } from "../index.ts";let teamCtx: ServiceContext;-async function clearWorkspaceTags() {- await db- .delete(monitorTag)- .where(eq(monitorTag.workspaceId, SEEDED_WORKSPACE_TEAM_ID))- .catch(() => undefined);-}-beforeAll(async () => {- const team = await loadSeededWorkspace(SEEDED_WORKSPACE_TEAM_ID);- teamCtx = makeUserCtx(team, { userId: 1 });- // Wipe rows from prior aborted runs so tests can assert exact counts.- await clearWorkspaceTags();- await clearAuditLog(SEEDED_WORKSPACE_TEAM_ID);-});--afterAll(async () => {- await clearWorkspaceTags();+ const team = await createWorkspaceFixture("team");+ teamCtx = makeUserCtx(team.workspace, { userId: team.userId });});describe("syncMonitorTags", () => {@@ -55,7 +40,7 @@ describe("syncMonitorTags", () => {expect(result.map((r) => r.name).sort()).toEqual(["alpha", "beta"]);const auditRows = await readAuditLog({- workspaceId: SEEDED_WORKSPACE_TEAM_ID,+ workspaceId: teamCtx.workspace.id,entityType: "monitor_tag",db: tx,});@@ -73,7 +58,7 @@ describe("syncMonitorTags", () => {ctx,input: { tags: [{ name: "alpha", color: "red" }] },});- await clearAuditLog(SEEDED_WORKSPACE_TEAM_ID, { db: tx });+ await clearAuditLog(teamCtx.workspace.id, { db: tx });await syncMonitorTags({ctx,@@ -90,7 +75,7 @@ describe("syncMonitorTags", () => {expect(row?.name).toBe("alpha-renamed");const auditRows = await readAuditLog({- workspaceId: SEEDED_WORKSPACE_TEAM_ID,+ workspaceId: teamCtx.workspace.id,entityType: "monitor_tag",entityId: existingId,db: tx,@@ -109,7 +94,7 @@ describe("syncMonitorTags", () => {ctx,input: { tags: [{ name: "alpha", color: "red" }] },});- await clearAuditLog(SEEDED_WORKSPACE_TEAM_ID, { db: tx });+ await clearAuditLog(teamCtx.workspace.id, { db: tx });await syncMonitorTags({ctx,@@ -117,7 +102,7 @@ describe("syncMonitorTags", () => {});const auditRows = await readAuditLog({- workspaceId: SEEDED_WORKSPACE_TEAM_ID,+ workspaceId: teamCtx.workspace.id,entityType: "monitor_tag",entityId: existingId,db: tx,@@ -143,7 +128,7 @@ describe("syncMonitorTags", () => {],},});- await clearAuditLog(SEEDED_WORKSPACE_TEAM_ID, { db: tx });+ await clearAuditLog(teamCtx.workspace.id, { db: tx });const keep = created.find((t) => t.name === "alpha");if (!keep) throw new Error("seed setup failed");@@ -157,7 +142,7 @@ describe("syncMonitorTags", () => {expect(remaining.map((r) => r.name)).toEqual(["alpha"]);const auditRows = await readAuditLog({- workspaceId: SEEDED_WORKSPACE_TEAM_ID,+ workspaceId: teamCtx.workspace.id,entityType: "monitor_tag",db: tx,});@@ -199,7 +184,7 @@ describe("syncMonitorTags", () => {],},});- await clearAuditLog(SEEDED_WORKSPACE_TEAM_ID, { db: tx });+ await clearAuditLog(teamCtx.workspace.id, { db: tx });const stays = seed.find((t) => t.name === "stays");if (!stays) throw new Error("seed setup failed");@@ -215,7 +200,7 @@ describe("syncMonitorTags", () => {});const auditRows = await readAuditLog({- workspaceId: SEEDED_WORKSPACE_TEAM_ID,+ workspaceId: teamCtx.workspace.id,entityType: "monitor_tag",db: tx,});diff --git a/packages/services/src/monitor/__tests__/reads.test.ts b/packages/services/src/monitor/__tests__/reads.test.tsindex 0b872a5b6..3c7705116 100644--- a/packages/services/src/monitor/__tests__/reads.test.ts+++ b/packages/services/src/monitor/__tests__/reads.test.ts@@ -9,11 +9,7 @@ import { expect } from "@std/expect";import { beforeAll, describe, test } from "@std/testing/bdd";import {- SEEDED_WORKSPACE_FREE_ID,- SEEDED_WORKSPACE_TEAM_ID,-} from "../../../test/fixtures";-import {- loadSeededWorkspace,+ createWorkspaceFixture,makeUserCtx,withTestTransaction,} from "../../../test/helpers";@@ -33,8 +29,8 @@ let teamCtx: ServiceContext;let freeCtx: ServiceContext;beforeAll(async () => {- const team = await loadSeededWorkspace(SEEDED_WORKSPACE_TEAM_ID);- const free = await loadSeededWorkspace(SEEDED_WORKSPACE_FREE_ID);+ const team = (await createWorkspaceFixture("team")).workspace;+ const free = (await createWorkspaceFixture("free")).workspace;teamCtx = makeUserCtx(team, { userId: 1 });freeCtx = makeUserCtx(free, { userId: 2 });});diff --git a/packages/services/src/monitor/__tests__/stream-monitor-preview.test.ts b/packages/services/src/monitor/__tests__/stream-monitor-preview.test.tsindex 0a54da729..7e777e13e 100644--- a/packages/services/src/monitor/__tests__/stream-monitor-preview.test.ts+++ b/packages/services/src/monitor/__tests__/stream-monitor-preview.test.ts@@ -1,9 +1,8 @@import { expect } from "@std/expect";import { afterAll, beforeAll, describe, test } from "@std/testing/bdd";-import { SEEDED_WORKSPACE_TEAM_ID } from "../../../test/fixtures";import {- loadSeededWorkspace,+ createWorkspaceFixture,makeUserCtx,withTestTransaction,} from "../../../test/helpers";@@ -58,7 +57,7 @@ describe("streamMonitorPreview", () => {test("throws NotFoundError when monitor belongs to a different workspace", async () => {await withTestTransaction(async (tx) => {- const ws = await loadSeededWorkspace(SEEDED_WORKSPACE_TEAM_ID);+ const ws = (await createWorkspaceFixture("team")).workspace;const ctx = { ...makeUserCtx(ws), db: tx };// Use a monitor id that does not exist for this workspace.@@ -79,7 +78,7 @@ describe("streamMonitorPreview", () => {test("yields one result per region for an owned monitor", async () => {await withTestTransaction(async (tx) => {- const ws = await loadSeededWorkspace(SEEDED_WORKSPACE_TEAM_ID);+ const ws = (await createWorkspaceFixture("team")).workspace;const ctx = { ...makeUserCtx(ws), db: tx };const created = await createMonitor({ctx,diff --git a/packages/services/src/notification/__tests__/notification.test.ts b/packages/services/src/notification/__tests__/notification.test.tsindex e0d1fea72..0d6775059 100644--- a/packages/services/src/notification/__tests__/notification.test.ts+++ b/packages/services/src/notification/__tests__/notification.test.ts@@ -10,10 +10,9 @@ import { getLimits } from "@openstatus/db/src/schema/plan/utils";import { expect } from "@std/expect";import { afterAll, beforeAll, describe, test } from "@std/testing/bdd";-import { SEEDED_WORKSPACE_TEAM_ID } from "../../../test/fixtures";import {expectAuditRow,- loadSeededWorkspace,+ createWorkspaceFixture,makeApiKeyCtx,makeUserCtx,withTestTransaction,@@ -46,7 +45,7 @@ let teamMonitorId: number;const FREE_WS_SLUG = `${TEST_PREFIX}-free-ws`;beforeAll(async () => {- const team = await loadSeededWorkspace(SEEDED_WORKSPACE_TEAM_ID);+ const team = (await createWorkspaceFixture("team")).workspace;teamCtx = makeUserCtx(team, { userId: 1 });await dbdiff --git a/packages/services/src/page-component/__tests__/get-daily-summary.test.ts b/packages/services/src/page-component/__tests__/get-daily-summary.test.tsindex 10a2f0887..9f10c94a0 100644--- a/packages/services/src/page-component/__tests__/get-daily-summary.test.ts+++ b/packages/services/src/page-component/__tests__/get-daily-summary.test.ts@@ -12,9 +12,8 @@ import {import { expect } from "@std/expect";import { beforeAll, describe, test } from "@std/testing/bdd";-import { SEEDED_WORKSPACE_TEAM_ID } from "../../../test/fixtures";import {- loadSeededWorkspace,+ createWorkspaceFixture,makeUserCtx,withTestTransaction,} from "../../../test/helpers";@@ -28,7 +27,7 @@ let teamCtx: ServiceContext;let workspaceId: number;beforeAll(async () => {- const team = await loadSeededWorkspace(SEEDED_WORKSPACE_TEAM_ID);+ const team = (await createWorkspaceFixture("team")).workspace;teamCtx = makeUserCtx(team, { userId: 1 });workspaceId = team.id;});diff --git a/packages/services/src/page-component/__tests__/page-component.test.ts b/packages/services/src/page-component/__tests__/page-component.test.tsindex 447099d21..380d92351 100644--- a/packages/services/src/page-component/__tests__/page-component.test.ts+++ b/packages/services/src/page-component/__tests__/page-component.test.ts@@ -8,13 +8,9 @@ import {import { expect } from "@std/expect";import { afterAll, beforeAll, describe, test } from "@std/testing/bdd";-import {- SEEDED_WORKSPACE_FREE_ID,- SEEDED_WORKSPACE_TEAM_ID,-} from "../../../test/fixtures";import {expectAuditRow,- loadSeededWorkspace,+ createWorkspaceFixture,makeApiKeyCtx,makeUserCtx,withTestTransaction,@@ -34,8 +30,8 @@ let teamMonitorId: number;let freeMonitorId: number;beforeAll(async () => {- const team = await loadSeededWorkspace(SEEDED_WORKSPACE_TEAM_ID);- const free = await loadSeededWorkspace(SEEDED_WORKSPACE_FREE_ID);+ const team = (await createWorkspaceFixture("team")).workspace;+ const free = (await createWorkspaceFixture("free")).workspace;teamCtx = makeUserCtx(team, { userId: 1 });freeCtx = makeUserCtx(free, { userId: 2 });diff --git a/packages/services/src/page-subscriber/__tests__/page-subscriber.test.ts b/packages/services/src/page-subscriber/__tests__/page-subscriber.test.tsindex 58f2a1fe3..a00a5bcab 100644--- a/packages/services/src/page-subscriber/__tests__/page-subscriber.test.ts+++ b/packages/services/src/page-subscriber/__tests__/page-subscriber.test.ts@@ -5,6 +5,10 @@ import {pageSubscriber,pageSubscriberToPageComponent,} from "@openstatus/db/src/schema";+import {+ createPage,+ createPageComponent,+} from "@openstatus/db/src/test/factories";import { expect } from "@std/expect";import {afterAll,@@ -15,14 +19,10 @@ import {test,} from "@std/testing/bdd";-import {- SEEDED_WORKSPACE_FREE_ID,- SEEDED_WORKSPACE_TEAM_ID,-} from "../../../test/fixtures";import {clearAuditLog,+ createWorkspaceFixture,expectAuditRow,- loadSeededWorkspace,makeApiKeyCtx,readAuditLog,withTestTransaction,@@ -38,13 +38,14 @@ import {verifySelfSignupSubscriber,} from "../index.ts";-// Seeded data we lean on (see packages/db/src/seed.mts):-// workspace 1 = team plan, has status-subscribers=true-// page 1 = slug "status", workspaceId 1, components 1 & 2-const PAGE_ID = 1;-const PAGE_SLUG = "status";-const COMPONENT_1 = 1;-const COMPONENT_2 = 2;+// Built in `beforeAll` β this suite owns its workspace, page and components so+// its committed rows and audit trail can't be observed or wiped by siblings.+let WORKSPACE_ID: number;+let FREE_WORKSPACE_ID: number;+let PAGE_ID: number;+let PAGE_SLUG: string;+let COMPONENT_1: number;+let COMPONENT_2: number;// Each describe block owns its own email so suites are independent.const EMAILS = {@@ -67,10 +68,23 @@ async function cleanAll() {for (const email of Object.values(EMAILS)) {await db.delete(pageSubscriber).where(eq(pageSubscriber.email, email));}- await clearAuditLog(SEEDED_WORKSPACE_TEAM_ID);+ await clearAuditLog(WORKSPACE_ID);}-beforeAll(cleanAll);+beforeAll(async () => {+ const team = await createWorkspaceFixture("team");+ WORKSPACE_ID = team.workspace.id;+ FREE_WORKSPACE_ID = (await createWorkspaceFixture("free")).workspace.id;++ const p = await createPage(WORKSPACE_ID);+ PAGE_ID = p.id;+ PAGE_SLUG = p.slug;+ COMPONENT_1 = (await createPageComponent(WORKSPACE_ID, PAGE_ID)).id;+ COMPONENT_2 = (await createPageComponent(WORKSPACE_ID, PAGE_ID, { order: 1 }))+ .id;++ await cleanAll();+});afterAll(cleanAll);// βββ upsertSelfSignupSubscriber ββββββββββββββββββββββββββββββββββββββββββββββ@@ -80,7 +94,7 @@ describe("upsertSelfSignupSubscriber", () => {beforeAll(async () => {await db.delete(pageSubscriber).where(eq(pageSubscriber.email, email));- await clearAuditLog(SEEDED_WORKSPACE_TEAM_ID);+ await clearAuditLog(WORKSPACE_ID);});test("creates a new subscription for an unknown email", async () => {@@ -96,7 +110,7 @@ describe("upsertSelfSignupSubscriber", () => {// Audit row written, attributed to the subscriber (not a workspace user).await expectAuditRow({- workspaceId: SEEDED_WORKSPACE_TEAM_ID,+ workspaceId: WORKSPACE_ID,action: "page_subscriber.create",entityType: "page_subscriber",entityId: result.id,@@ -113,7 +127,7 @@ describe("upsertSelfSignupSubscriber", () => {});const rows = await readAuditLog({- workspaceId: SEEDED_WORKSPACE_TEAM_ID,+ workspaceId: WORKSPACE_ID,entityType: "page_subscriber",entityId: result.id,});@@ -143,7 +157,7 @@ describe("upsertSelfSignupSubscriber", () => {// Component-merge path emits an `update` audit row.await expectAuditRow({- workspaceId: SEEDED_WORKSPACE_TEAM_ID,+ workspaceId: WORKSPACE_ID,action: "page_subscriber.update",entityType: "page_subscriber",entityId: result.id,@@ -153,7 +167,7 @@ describe("upsertSelfSignupSubscriber", () => {// Metadata records the merged component-id set so the change isn't// dropped by the empty-diff guard in `emitAudit`.const rows = await readAuditLog({- workspaceId: SEEDED_WORKSPACE_TEAM_ID,+ workspaceId: WORKSPACE_ID,entityType: "page_subscriber",entityId: result.id,});@@ -252,7 +266,7 @@ describe("upsertSelfSignupSubscriber", () => {.delete(auditLog).where(and(- eq(auditLog.workspaceId, SEEDED_WORKSPACE_TEAM_ID),+ eq(auditLog.workspaceId, WORKSPACE_ID),eq(auditLog.entityId, String(initial.id)),),);@@ -264,7 +278,7 @@ describe("upsertSelfSignupSubscriber", () => {expect(result.acceptedAt).not.toBeNull();const rows = await readAuditLog({- workspaceId: SEEDED_WORKSPACE_TEAM_ID,+ workspaceId: WORKSPACE_ID,entityType: "page_subscriber",entityId: initial.id,});@@ -297,7 +311,7 @@ describe("upsertSelfSignupSubscriber", () => {const freePage = await tx.insert(page).values({- workspaceId: SEEDED_WORKSPACE_FREE_ID,+ workspaceId: FREE_WORKSPACE_ID,title: "plan-gate",description: "plan-gate",slug: `plan-gate-${Date.now()}`,@@ -354,7 +368,7 @@ describe("verifySelfSignupSubscriber", () => {expect(result?.acceptedAt).toBeDefined();await expectAuditRow({- workspaceId: SEEDED_WORKSPACE_TEAM_ID,+ workspaceId: WORKSPACE_ID,action: "page_subscriber.update",entityType: "page_subscriber",entityId: pendingId,@@ -368,7 +382,7 @@ describe("verifySelfSignupSubscriber", () => {.delete(auditLog).where(and(- eq(auditLog.workspaceId, SEEDED_WORKSPACE_TEAM_ID),+ eq(auditLog.workspaceId, WORKSPACE_ID),eq(auditLog.entityId, String(pendingId)),),);@@ -380,7 +394,7 @@ describe("verifySelfSignupSubscriber", () => {expect(result?.acceptedAt).toBeDefined();const rows = await readAuditLog({- workspaceId: SEEDED_WORKSPACE_TEAM_ID,+ workspaceId: WORKSPACE_ID,entityType: "page_subscriber",entityId: pendingId,});@@ -458,12 +472,10 @@ describe("getSubscriberByToken", () => {});test("never emits an audit row (read-only)", async () => {- await db- .delete(auditLog)- .where(eq(auditLog.workspaceId, SEEDED_WORKSPACE_TEAM_ID));+ await db.delete(auditLog).where(eq(auditLog.workspaceId, WORKSPACE_ID));await getSubscriberByToken({ input: { token, domain: PAGE_SLUG } });const rows = await readAuditLog({- workspaceId: SEEDED_WORKSPACE_TEAM_ID,+ workspaceId: WORKSPACE_ID,entityType: "page_subscriber",});expect(rows).toHaveLength(0);@@ -493,7 +505,7 @@ describe("updateSubscriberScope", () => {.delete(auditLog).where(and(- eq(auditLog.workspaceId, SEEDED_WORKSPACE_TEAM_ID),+ eq(auditLog.workspaceId, WORKSPACE_ID),eq(auditLog.entityId, String(subscriberId)),),);@@ -554,7 +566,7 @@ describe("updateSubscriberScope", () => {expect(rowsAfter.map((r) => r.pageComponentId)).toEqual([COMPONENT_2]);const auditRows = await readAuditLog({- workspaceId: SEEDED_WORKSPACE_TEAM_ID,+ workspaceId: WORKSPACE_ID,entityType: "page_subscriber",entityId: subscriberId,});@@ -626,7 +638,7 @@ describe("unsubscribeSubscriber", () => {.delete(auditLog).where(and(- eq(auditLog.workspaceId, SEEDED_WORKSPACE_TEAM_ID),+ eq(auditLog.workspaceId, WORKSPACE_ID),eq(auditLog.entityId, String(subscriberId)),),);@@ -641,7 +653,7 @@ describe("unsubscribeSubscriber", () => {expect(row?.unsubscribedAt).toBeDefined();await expectAuditRow({- workspaceId: SEEDED_WORKSPACE_TEAM_ID,+ workspaceId: WORKSPACE_ID,action: "page_subscriber.update",entityType: "page_subscriber",entityId: subscriberId,@@ -654,7 +666,7 @@ describe("unsubscribeSubscriber", () => {.delete(auditLog).where(and(- eq(auditLog.workspaceId, SEEDED_WORKSPACE_TEAM_ID),+ eq(auditLog.workspaceId, WORKSPACE_ID),eq(auditLog.entityId, String(subscriberId)),),);@@ -664,7 +676,7 @@ describe("unsubscribeSubscriber", () => {).resolves.toBeUndefined();const rows = await readAuditLog({- workspaceId: SEEDED_WORKSPACE_TEAM_ID,+ workspaceId: WORKSPACE_ID,entityType: "page_subscriber",entityId: subscriberId,});@@ -756,7 +768,7 @@ describe("hasPendingSubscriber", () => {describe("createPageSubscriber", () => {test("rejects read-only actor", async () => {await withTestTransaction(async (tx) => {- const team = await loadSeededWorkspace(SEEDED_WORKSPACE_TEAM_ID);+ const team = (await createWorkspaceFixture("team")).workspace;const readOnlyCtx = {...makeApiKeyCtx(team, {keyId: "k-read",diff --git a/packages/services/src/page-subscriber/__tests__/slack.test.ts b/packages/services/src/page-subscriber/__tests__/slack.test.tsindex 84e61bc18..d34beb14b 100644--- a/packages/services/src/page-subscriber/__tests__/slack.test.ts+++ b/packages/services/src/page-subscriber/__tests__/slack.test.ts@@ -1,18 +1,20 @@import { db, eq, inArray } from "@openstatus/db";import { pageSubscriber } from "@openstatus/db/src/schema";+import { createPage } from "@openstatus/db/src/test/factories";import { expect } from "@std/expect";import { afterAll, beforeAll, describe, test } from "@std/testing/bdd";-import { SEEDED_WORKSPACE_TEAM_ID } from "../../../test/fixtures";-import { expectAuditRow } from "../../../test/helpers";+import { createWorkspaceFixture, expectAuditRow } from "../../../test/helpers";import {createSlackSubscriber,listSlackSubscribersForChannel,removeSlackSubscriber,} from "../index";-// page 1 = slug "status", workspace 1 (team plan, status-subscribers=true).-const PAGE_ID = 1;+// Own workspace + page: this suite writes committed rows and asserts on the+// workspace's audit trail, which siblings would otherwise clear.+let PAGE_ID: number;+let WORKSPACE_ID: number;const TEAM_ID = "T_SLACK_TEST";const CHANNELS = {create: "C_SLACK_CREATE",@@ -22,17 +24,18 @@ const CHANNELS = {list: "C_SLACK_LIST",};-// Scope cleanup to this suite's own slack channels. A workspace-wide-// clearAuditLog would race sibling suites that share workspace 1 under-// `deno test --parallel`; our assertions filter by unique entityId, so-// stale audit rows can't match anyway.async function cleanAll() {await db.delete(pageSubscriber).where(inArray(pageSubscriber.slackChannelId, Object.values(CHANNELS)));}-beforeAll(cleanAll);+beforeAll(async () => {+ const team = await createWorkspaceFixture("team");+ WORKSPACE_ID = team.workspace.id;+ PAGE_ID = (await createPage(WORKSPACE_ID)).id;+ await cleanAll();+});afterAll(cleanAll);describe("createSlackSubscriber", () => {@@ -59,7 +62,7 @@ describe("createSlackSubscriber", () => {expect(row?.name).toBe("#incidents");await expectAuditRow({- workspaceId: SEEDED_WORKSPACE_TEAM_ID,+ workspaceId: WORKSPACE_ID,action: "page_subscriber.create",entityType: "page_subscriber",entityId: result.id,@@ -132,7 +135,7 @@ describe("removeSlackSubscriber", () => {expect(row?.unsubscribedAt).not.toBeNull();await expectAuditRow({- workspaceId: SEEDED_WORKSPACE_TEAM_ID,+ workspaceId: WORKSPACE_ID,action: "page_subscriber.update",entityType: "page_subscriber",entityId: created.id,diff --git a/packages/services/src/page/__tests__/page.test.ts b/packages/services/src/page/__tests__/page.test.tsindex fa7af6cad..fd1a5b7c8 100644--- a/packages/services/src/page/__tests__/page.test.ts+++ b/packages/services/src/page/__tests__/page.test.ts@@ -10,10 +10,9 @@ import { getLimits } from "@openstatus/db/src/schema/plan/utils";import { expect } from "@std/expect";import { afterAll, beforeAll, describe, test } from "@std/testing/bdd";-import { SEEDED_WORKSPACE_TEAM_ID } from "../../../test/fixtures";import {expectAuditRow,- loadSeededWorkspace,+ createWorkspaceFixture,makeApiKeyCtx,makeUserCtx,withTestTransaction,@@ -51,7 +50,7 @@ let teamMonitorId: number;const FREE_WS_SLUG = `${TEST_PREFIX}-free-ws`;beforeAll(async () => {- const team = await loadSeededWorkspace(SEEDED_WORKSPACE_TEAM_ID);+ const team = (await createWorkspaceFixture("team")).workspace;teamCtx = makeUserCtx(team, { userId: 1 });await db@@ -157,7 +156,7 @@ describe("createPage (full form)", () => {slug,description: "desc",customDomain: "",- workspaceId: SEEDED_WORKSPACE_TEAM_ID,+ workspaceId: teamCtx.workspace.id,monitors: [{ monitorId: teamMonitorId }],},});diff --git a/packages/services/src/private-location/__tests__/private-location.test.ts b/packages/services/src/private-location/__tests__/private-location.test.tsindex 08c0fd585..a23f9bc17 100644--- a/packages/services/src/private-location/__tests__/private-location.test.ts+++ b/packages/services/src/private-location/__tests__/private-location.test.ts@@ -10,10 +10,9 @@ import { getLimits } from "@openstatus/db/src/schema/plan/utils";import { expect } from "@std/expect";import { afterAll, beforeAll, describe, test } from "@std/testing/bdd";-import { SEEDED_WORKSPACE_TEAM_ID } from "../../../test/fixtures";import {expectAuditRow,- loadSeededWorkspace,+ createWorkspaceFixture,makeApiKeyCtx,makeUserCtx,readAuditLog,@@ -40,7 +39,7 @@ let otherWorkspaceId: number;const OTHER_WS_SLUG = `${TEST_PREFIX}-other-ws`;beforeAll(async () => {- const team = await loadSeededWorkspace(SEEDED_WORKSPACE_TEAM_ID);+ const team = (await createWorkspaceFixture("team")).workspace;teamCtx = makeUserCtx(team, { userId: 1 });const mk = async (name: string, workspaceId: number, deleted?: boolean) => {diff --git a/packages/services/src/status-report/__tests__/derive-status.test.ts b/packages/services/src/status-report/__tests__/derive-status.test.tsindex 7d5bbf1e1..16cc40ea9 100644--- a/packages/services/src/status-report/__tests__/derive-status.test.ts+++ b/packages/services/src/status-report/__tests__/derive-status.test.ts@@ -7,9 +7,8 @@ import {import { expect } from "@std/expect";import { afterAll, beforeAll, describe, test } from "@std/testing/bdd";-import { SEEDED_WORKSPACE_TEAM_ID } from "../../../test/fixtures";import {- loadSeededWorkspace,+ createWorkspaceFixture,makeUserCtx,readAuditLog,withTestTransaction,@@ -30,7 +29,7 @@ let testPageId: number;// inserting it inside each one lengthens the write lock and starves the// other suites running in parallel (SQLITE_BUSY)beforeAll(async () => {- const team = await loadSeededWorkspace(SEEDED_WORKSPACE_TEAM_ID);+ const team = (await createWorkspaceFixture("team")).workspace;teamCtx = makeUserCtx(team, { userId: 1 });const pageRow = await dbdiff --git a/packages/services/src/status-report/__tests__/status-report.test.ts b/packages/services/src/status-report/__tests__/status-report.test.tsindex 7104b8d13..571cf47fc 100644--- a/packages/services/src/status-report/__tests__/status-report.test.ts+++ b/packages/services/src/status-report/__tests__/status-report.test.ts@@ -17,13 +17,9 @@ import {test,} from "@std/testing/bdd";-import {- SEEDED_WORKSPACE_FREE_ID,- SEEDED_WORKSPACE_TEAM_ID,-} from "../../../test/fixtures";import {expectAuditRow,- loadSeededWorkspace,+ createWorkspaceFixture,makeApiKeyCtx,makeSlackCtx,makeUserCtx,@@ -69,8 +65,8 @@ let otherPageId: number;let otherPageComponentId: number;beforeAll(async () => {- const team = await loadSeededWorkspace(SEEDED_WORKSPACE_TEAM_ID);- const free = await loadSeededWorkspace(SEEDED_WORKSPACE_FREE_ID);+ const team = (await createWorkspaceFixture("team")).workspace;+ const free = (await createWorkspaceFixture("free")).workspace;teamCtx = makeUserCtx(team, { userId: 1 });freeCtx = makeUserCtx(free, { userId: 2 });diff --git a/packages/services/src/workspace/__tests__/workspace.test.ts b/packages/services/src/workspace/__tests__/workspace.test.tsindex 667735208..cebd7c9d3 100644--- a/packages/services/src/workspace/__tests__/workspace.test.ts+++ b/packages/services/src/workspace/__tests__/workspace.test.ts@@ -8,10 +8,9 @@ import { getLimits } from "@openstatus/db/src/schema/plan/utils";import { expect } from "@std/expect";import { beforeAll, describe, test } from "@std/testing/bdd";-import { SEEDED_WORKSPACE_TEAM_ID } from "../../../test/fixtures";import {+ createWorkspaceFixture,expectAuditRow,- loadSeededWorkspace,makeApiKeyCtx,makeSystemCtx,makeUserCtx,@@ -30,17 +29,19 @@ import {} from "../index.ts";let teamCtx: ServiceContext;+let teamUserId: number;beforeAll(async () => {- const team = await loadSeededWorkspace(SEEDED_WORKSPACE_TEAM_ID);- teamCtx = makeUserCtx(team, { userId: 1 });+ const team = await createWorkspaceFixture("team");+ teamUserId = team.userId;+ teamCtx = makeUserCtx(team.workspace, { userId: teamUserId });});describe("getWorkspace", () => {test("returns the caller's workspace", async () => {await withTestTransaction(async (tx) => {const result = await getWorkspace({ ctx: { ...teamCtx, db: tx } });- expect(result.id).toBe(SEEDED_WORKSPACE_TEAM_ID);+ expect(result.id).toBe(teamCtx.workspace.id);expect(typeof result.limits).toBe("object");});});@@ -52,7 +53,7 @@ describe("getWorkspaceWithUsage", () => {const result = await getWorkspaceWithUsage({ctx: { ...teamCtx, db: tx },});- expect(result.id).toBe(SEEDED_WORKSPACE_TEAM_ID);+ expect(result.id).toBe(teamCtx.workspace.id);// Iterate the usage object *before* any `toMatchObject` call β// the `toMatchObject` implementation mutates the received@@ -82,7 +83,7 @@ describe("getWorkspaceWithUsage", () => {test("counts workspace-scoped status reports", async () => {await withTestTransaction(async (tx) => {await tx.insert(statusReport).values({- workspaceId: SEEDED_WORKSPACE_TEAM_ID,+ workspaceId: teamCtx.workspace.id,status: "investigating",title: "svc-ws-test-status-report",});@@ -99,10 +100,10 @@ describe("listWorkspaces", () => {await withTestTransaction(async (tx) => {const rows = await listWorkspaces({ctx: { ...teamCtx, db: tx },- input: { userId: 1 },+ input: { userId: teamUserId },});const ids = rows.map((r) => r.id);- expect(ids).toContain(SEEDED_WORKSPACE_TEAM_ID);+ expect(ids).toContain(teamCtx.workspace.id);});});@@ -149,7 +150,7 @@ describe("updateWorkspaceName", () => {const row = await tx.select().from(workspace)- .where(eq(workspace.id, SEEDED_WORKSPACE_TEAM_ID))+ .where(eq(workspace.id, teamCtx.workspace.id)).get();expect(row?.name).toBe(nextName);@@ -157,7 +158,7 @@ describe("updateWorkspaceName", () => {workspaceId: teamCtx.workspace.id,action: "workspace.update",entityType: "workspace",- entityId: SEEDED_WORKSPACE_TEAM_ID,+ entityId: teamCtx.workspace.id,actorType: "user",db: tx,});diff --git a/packages/services/test/helpers.ts b/packages/services/test/helpers.tsindex 688bdf151..f54b10bce 100644--- a/packages/services/test/helpers.ts+++ b/packages/services/test/helpers.ts@@ -2,12 +2,9 @@ import { and, db, desc, eq, inArray } from "@openstatus/db";import {type Scope,auditLog,- notification,- page,- pageComponent,selectWorkspaceSchema,- workspace as workspaceTable,} from "@openstatus/db/src/schema";+import { createTestWorkspace } from "@openstatus/db/src/test/factories";import { expect } from "@std/expect";import type { Actor, DB, DrizzleTx, ServiceContext } from "../src/context";@@ -49,44 +46,6 @@ export async function withTestTransaction<T>(return result;}-/**- * Clear leftover quota-gated rows on a workspace so tests that rely on- * a specific cap state (e.g. `free` plan has `status-pages: 1`,- * `notification-channels: 1`) can run regardless of what prior tests- * or aborted runs left behind.- *- * Intended for `beforeAll` of suites that exercise the `free`- * workspace β the tight-plan negative tests break randomly otherwise- * because cumulative state trips a quota check before the test can- * hit its intended assertion. Scoped to the two tables that have bit- * us repeatedly in CI; extend when a new quota-gated table surfaces.- */-export async function cleanQuotaGatedTables(- workspaceId: number,-): Promise<void> {- // Pages β delete dependent pageComponents first to satisfy FKs.- const pages = await db- .select({ id: page.id })- .from(page)- .where(eq(page.workspaceId, workspaceId))- .all();- const pageIds = pages.map((p) => p.id);- if (pageIds.length > 0) {- await db- .delete(pageComponent)- .where(inArray(pageComponent.pageId, pageIds))- .catch(() => undefined);- await db- .delete(page)- .where(inArray(page.id, pageIds))- .catch(() => undefined);- }- await db- .delete(notification)- .where(eq(notification.workspaceId, workspaceId))- .catch(() => undefined);-}-/** Wipe audit_log rows for a workspace. Call in `beforeEach` / `afterEach`. */export async function clearAuditLog(workspaceId: number,@@ -130,23 +89,28 @@ export async function clearAuditLogFor(args: {.catch(() => undefined);}+export type WorkspaceFixture = {+ workspace: Workspace;+ /** Owner of the workspace β pass to `makeUserCtx` for a member-of-workspace actor. */+ userId: number;+};+/**- * Load a seeded workspace by id (defaults to id=1, the `team` plan fixture).- * Tests that need a fresh workspace should insert one explicitly and clean up;- * isolating every test with its own workspace is the prevailing convention.+ * A workspace owned by this suite alone, on the given plan.+ *+ * Call this in `beforeAll` instead of reaching for a seeded workspace. Suites+ * that share workspace 1 race each other over `audit_log`, plan quotas and+ * row counts once test files run in parallel β a private workspace makes those+ * assertions deterministic.*/-export async function loadSeededWorkspace(id = 1): Promise<Workspace> {- const row = await db- .select()- .from(workspaceTable)- .where(eq(workspaceTable.id, id))- .get();- if (!row) {- throw new Error(- `loadSeededWorkspace(${id}): workspace not found. Did you seed the db?`,- );- }- return selectWorkspaceSchema.parse(row);+export async function createWorkspaceFixture(+ plan: "team" | "free" = "team",+): Promise<WorkspaceFixture> {+ const { workspace, user } = await createTestWorkspace({ plan });+ return {+ workspace: selectWorkspaceSchema.parse(workspace),+ userId: user.id,+ };}export function makeUserCtx(diff --git a/packages/subscriptions/package.json b/packages/subscriptions/package.jsonindex 1a3537a49..d56467ba1 100644--- a/packages/subscriptions/package.json+++ b/packages/subscriptions/package.json@@ -16,7 +16,7 @@},"scripts": {"check": "deno check --sloppy-imports .",- "test": "deno test -A --no-check --sloppy-imports"+ "test": "deno test --parallel -A --no-check --sloppy-imports"},"dependencies": {"@openstatus/db": "workspace:*",diff --git a/packages/subscriptions/src/dispatcher.test.ts b/packages/subscriptions/src/dispatcher.test.tsindex 691a84af6..999fa835f 100644--- a/packages/subscriptions/src/dispatcher.test.ts+++ b/packages/subscriptions/src/dispatcher.test.ts@@ -4,6 +4,11 @@ import {pageSubscriber,pageSubscriberToPageComponent,} from "@openstatus/db/src/schema";+import {+ createPage,+ createPageComponent,+ createTestWorkspace,+} from "@openstatus/db/src/test/factories";import { EmailClient } from "@openstatus/emails";import { expect } from "@std/expect";import {@@ -25,10 +30,11 @@ import type { PageUpdate } from "./types";let sendStatusReportUpdateMock: Stub<EmailClient>;let rejectNextSend: Error | null = null;-// IDs present in the seeded database-const PAGE_ID = 1; // slug: "status"-const COMPONENT_1 = 1;-const COMPONENT_2 = 2;+// Built in `beforeAll` β a private page keeps the subscriber set this suite+// dispatches to independent of anything else running against the database.+let PAGE_ID: number;+let COMPONENT_1: number;+let COMPONENT_2: number;const EMAILS = {entirePage: "[email protected]",@@ -62,6 +68,12 @@ async function cleanAll() {}beforeAll(async () => {+ const { workspace } = await createTestWorkspace();+ PAGE_ID = (await createPage(workspace.id)).id;+ COMPONENT_1 = (await createPageComponent(workspace.id, PAGE_ID)).id;+ COMPONENT_2 = (await createPageComponent(workspace.id, PAGE_ID, { order: 1 }))+ .id;+await cleanAll();const insertAccepted = async (email: string) => {diff --git a/turbo.json b/turbo.jsonindex e6a28cd2b..9c4d16099 100644--- a/turbo.json+++ b/turbo.json@@ -47,7 +47,17 @@"cache": false},"test": {- "cache": false+ "cache": false,+ // Strict env mode would drop these, and packages/db then silently falls+ // back to the default local sqld URL β pointing tests at whatever+ // database happens to be on port 8080.+ "env": [+ "DATABASE_URL",+ "DATABASE_AUTH_TOKEN",+ "NODE_ENV",+ "RESEND_API_KEY",+ "CRON_SECRET"+ ]},"dx": {"cache": false,