Skip to content

Open-source status page, incident response and uptime monitoring

refactor: more services (#2119)

Maximilian Kaske512437e43199
diff --git a/apps/dashboard/src/app/(dashboard)/audit-logs/client.tsx b/apps/dashboard/src/app/(dashboard)/audit-logs/client.tsx
index f491a95f7..f74254fba 100644
--- a/apps/dashboard/src/app/(dashboard)/audit-logs/client.tsx
+++ b/apps/dashboard/src/app/(dashboard)/audit-logs/client.tsx
@@ -21,6 +21,7 @@ import {
} from "@/components/content/section";
import { columns } from "@/components/data-table/audit-logs-workspace/columns";
import { DataTableRowDetails } from "@/components/data-table/audit-logs-workspace/data-table-row-details";
+import { AuditLogsDataTableToolbar } from "@/components/data-table/audit-logs-workspace/data-table-toolbar";
import { UpgradeDialog } from "@/components/dialogs/upgrade";
import { DataTable } from "@/components/ui/data-table/data-table";
import { DataTablePaginationSimple } from "@/components/ui/data-table/data-table-pagination";
@@ -49,7 +50,7 @@ const EXAMPLES = [
createdAt: new Date("2026-04-24T10:00:00Z"),
user: {
id: 42,
- name: "Max Kaske",
+ name: "Maximilian Kaske",
photoUrl: null,
},
@@ -70,31 +71,26 @@ const EXAMPLES = [
createdAt: new Date("2026-04-23T16:30:00Z"),
user: {
id: 42,
- name: "Max Kaske",
- email: "[email protected]",
+ name: "Thibault Le Ouay Ducasse",
+ email: "[email protected]",
photoUrl: null,
},
},
{
id: 3,
workspaceId: 1,
- actorType: "apiKey",
+ actorType: "slack",
actorId: "k_abc123",
actorUserId: null,
- action: "notification.delete",
- entityType: "notification",
+ action: "status_report.create",
+ entityType: "status_report",
entityId: "12",
before: null,
after: null,
metadata: null,
changedFields: null,
createdAt: new Date("2026-04-22T09:15:00Z"),
- user: {
- id: 42,
- name: "Thibault Le Ouay Ducasse",
- email: "[email protected]",
- photoUrl: null,
- },
+ user: null,
},
] satisfies AuditLog[];
@@ -123,6 +119,11 @@ export function Client() {
<DataTable
columns={columns}
data={[...EXAMPLES, ...EXAMPLES, ...EXAMPLES]}
+ defaultColumnVisibility={{
+ actorType: false,
+ entityType: false,
+ }}
+ toolbarComponent={AuditLogsDataTableToolbar}
rowComponent={({ row }) => (
<DataTableRowDetails row={row.original} />
)}
@@ -154,6 +155,11 @@ export function Client() {
<DataTable
columns={columns}
data={auditLogs.items}
+ defaultColumnVisibility={{
+ actorType: false,
+ entityType: false,
+ }}
+ toolbarComponent={AuditLogsDataTableToolbar}
onRowClick={(row) =>
row.getCanExpand() ? row.toggleExpanded() : undefined
}
diff --git a/apps/dashboard/src/app/(dashboard)/status-pages/[id]/subscribers/page.tsx b/apps/dashboard/src/app/(dashboard)/status-pages/[id]/subscribers/page.tsx
index 342af994d..5b687452f 100644
--- a/apps/dashboard/src/app/(dashboard)/status-pages/[id]/subscribers/page.tsx
+++ b/apps/dashboard/src/app/(dashboard)/status-pages/[id]/subscribers/page.tsx
@@ -154,6 +154,7 @@ export default function Page() {
<BillingOverlayContainer>
<DataTable
columns={columns}
+ toolbarComponent={SubscribersDataTableToolbar}
data={[...EXAMPLES, ...EXAMPLES, ...EXAMPLES]}
/>
<BillingOverlay>
diff --git a/apps/dashboard/src/components/data-table/audit-logs-workspace/columns.tsx b/apps/dashboard/src/components/data-table/audit-logs-workspace/columns.tsx
index 6269e7239..32c893764 100644
--- a/apps/dashboard/src/components/data-table/audit-logs-workspace/columns.tsx
+++ b/apps/dashboard/src/components/data-table/audit-logs-workspace/columns.tsx
@@ -2,6 +2,7 @@
import { cn } from "@/lib/utils";
import type { RouterOutputs } from "@openstatus/api";
+import { SlackIcon } from "@openstatus/icons";
import {
Avatar,
AvatarFallback,
@@ -9,6 +10,7 @@ import {
} from "@openstatus/ui/components/ui/avatar";
import { Badge } from "@openstatus/ui/components/ui/badge";
import type { ColumnDef } from "@tanstack/react-table";
+import { KeyIcon, MailIcon, ServerIcon } from "lucide-react";
import { TableCellDate } from "../table-cell-date";
type AuditLog = RouterOutputs["auditLog"]["list"]["items"][number];
@@ -45,7 +47,50 @@ export const columns: ColumnDef<AuditLog>[] = [
enableHiding: false,
cell: ({ row }) => {
const user = row.original.user;
- if (!user) return <span className="text-muted-foreground">-</span>;
+ const type = row.original.actorType;
+ if (!user) {
+ if (type === "apiKey") {
+ return (
+ <div className="flex items-center gap-2">
+ <div className="flex size-6 items-center justify-center rounded-md bg-muted-foreground/10">
+ <KeyIcon className="size-4 text-muted-foreground" />
+ </div>
+ <span className="text-muted-foreground">API Key</span>
+ </div>
+ );
+ }
+ if (type === "slack") {
+ return (
+ <div className="flex items-center gap-2">
+ <div className="flex size-6 items-center justify-center rounded-md bg-muted-foreground/10">
+ <SlackIcon className="size-4 text-muted-foreground" />
+ </div>
+ <span className="text-muted-foreground">Slack</span>
+ </div>
+ );
+ }
+ if (type === "system") {
+ return (
+ <div className="flex items-center gap-2">
+ <div className="flex size-6 items-center justify-center rounded-md bg-muted-foreground/10">
+ <ServerIcon className="size-4 text-muted-foreground" />
+ </div>
+ <span className="text-muted-foreground">System</span>
+ </div>
+ );
+ }
+ if (type === "subscriber") {
+ return (
+ <div className="flex items-center gap-2">
+ <div className="flex size-6 items-center justify-center rounded-md bg-muted-foreground/10">
+ <MailIcon className="size-4 text-muted-foreground" />
+ </div>
+ <span className="text-muted-foreground">Subscriber</span>
+ </div>
+ );
+ }
+ return <span className="text-muted-foreground">-</span>;
+ }
const imgSrc =
user.photoUrl ||
// Seed with a hash of the email — dicebear logs request
@@ -77,6 +122,10 @@ export const columns: ColumnDef<AuditLog>[] = [
header: "Action",
enableSorting: false,
enableHiding: false,
+ filterFn: (row, id, filterValue: string[]) => {
+ if (!filterValue?.length) return true;
+ return filterValue.includes(row.getValue(id) as string);
+ },
cell: ({ row }) => {
const value = row.getValue("action") as string;
return (
@@ -89,6 +138,26 @@ export const columns: ColumnDef<AuditLog>[] = [
);
},
},
+ {
+ accessorKey: "actorType",
+ header: () => null,
+ cell: () => null,
+ enableHiding: true,
+ filterFn: (row, id, filterValue: string[]) => {
+ if (!filterValue?.length) return true;
+ return filterValue.includes(row.getValue(id) as string);
+ },
+ },
+ {
+ accessorKey: "entityType",
+ header: () => null,
+ cell: () => null,
+ enableHiding: true,
+ filterFn: (row, id, filterValue: string[]) => {
+ if (!filterValue?.length) return true;
+ return filterValue.includes(row.getValue(id) as string);
+ },
+ },
{
accessorKey: "createdAt",
header: "Timestamp",
diff --git a/apps/dashboard/src/components/data-table/audit-logs-workspace/data-table-toolbar.tsx b/apps/dashboard/src/components/data-table/audit-logs-workspace/data-table-toolbar.tsx
new file mode 100644
index 000000000..ee52344ae
--- /dev/null
+++ b/apps/dashboard/src/components/data-table/audit-logs-workspace/data-table-toolbar.tsx
@@ -0,0 +1,85 @@
+"use client";
+
+import { DataTableFacetedFilter } from "@/components/ui/data-table/data-table-faceted-filter";
+import type { RouterOutputs } from "@openstatus/api";
+import { Button } from "@openstatus/ui/components/ui/button";
+import type { Table } from "@tanstack/react-table";
+import { X } from "lucide-react";
+
+type AuditLog = RouterOutputs["auditLog"]["list"]["items"][number];
+
+const ACTOR_TYPE_LABELS: Record<string, string> = {
+ user: "User",
+ apiKey: "API Key",
+ slack: "Slack",
+ system: "System",
+ subscriber: "Subscriber",
+};
+
+function toOptions(values: Iterable<string>, labels?: Record<string, string>) {
+ return Array.from(new Set(values))
+ .filter(Boolean)
+ .sort()
+ .map((value) => ({ label: labels?.[value] ?? value, value }));
+}
+
+export function AuditLogsDataTableToolbar({
+ table,
+}: {
+ table: Table<AuditLog>;
+}) {
+ const isFiltered = table.getState().columnFilters.length > 0;
+
+ const actionFacets = table.getColumn("action")?.getFacetedUniqueValues();
+ const actorTypeFacets = table
+ .getColumn("actorType")
+ ?.getFacetedUniqueValues();
+ const entityTypeFacets = table
+ .getColumn("entityType")
+ ?.getFacetedUniqueValues();
+
+ const actionOptions = toOptions(actionFacets?.keys() ?? []);
+ const actorTypeOptions = toOptions(
+ actorTypeFacets?.keys() ?? [],
+ ACTOR_TYPE_LABELS,
+ );
+ const entityTypeOptions = toOptions(entityTypeFacets?.keys() ?? []);
+
+ return (
+ <div className="flex items-center justify-between">
+ <div className="flex flex-1 flex-wrap items-center gap-2">
+ {table.getColumn("action") && actionOptions.length > 0 && (
+ <DataTableFacetedFilter
+ column={table.getColumn("action")}
+ title="Action"
+ options={actionOptions}
+ />
+ )}
+ {table.getColumn("actorType") && actorTypeOptions.length > 0 && (
+ <DataTableFacetedFilter
+ column={table.getColumn("actorType")}
+ title="Actor type"
+ options={actorTypeOptions}
+ />
+ )}
+ {table.getColumn("entityType") && entityTypeOptions.length > 0 && (
+ <DataTableFacetedFilter
+ column={table.getColumn("entityType")}
+ title="Entity type"
+ options={entityTypeOptions}
+ />
+ )}
+ {isFiltered && (
+ <Button
+ variant="ghost"
+ onClick={() => table.resetColumnFilters()}
+ className="h-8 px-2 lg:px-3"
+ >
+ Reset
+ <X />
+ </Button>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/apps/dashboard/src/components/ui/data-table/data-table-faceted-filter.tsx b/apps/dashboard/src/components/ui/data-table/data-table-faceted-filter.tsx
index 5773eaa2e..d40c0eecf 100644
--- a/apps/dashboard/src/components/ui/data-table/data-table-faceted-filter.tsx
+++ b/apps/dashboard/src/components/ui/data-table/data-table-faceted-filter.tsx
@@ -122,7 +122,7 @@ export function DataTableFacetedFilter<TData, TValue>({
{option.icon && (
<option.icon className="mr-2 h-4 w-4 text-muted-foreground" />
)}
- <span>{option.label}</span>
+ <span className="truncate">{option.label}</span>
{facets?.get(option.value) && (
<span className="ml-auto flex h-4 w-4 items-center justify-center font-mono text-xs">
{facets.get(option.value)}
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.ts
index 0cb860c67..0184faff6 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
@@ -1,6 +1,12 @@
import { afterAll, beforeAll, describe, expect, test } from "bun:test";
-import { db, eq } from "@openstatus/db";
-import { monitor, pageComponent } from "@openstatus/db/src/schema";
+import { and, db, eq } from "@openstatus/db";
+import {
+ auditLog,
+ monitor,
+ pageComponent,
+ privateLocation,
+ privateLocationToMonitors,
+} from "@openstatus/db/src/schema";
import { monitorStatusTable } from "@openstatus/db/src/schema/monitor_status/monitor_status";
import { app } from "@/index";
@@ -469,6 +475,111 @@ describe("MonitorService.DeleteMonitor", () => {
}
});
+ test("clears privateLocationToMonitors join row", async () => {
+ // Insert a private location and join it to a fresh monitor. The pre-
+ // service implementation only stripped tag/notification/component
+ // joins, leaving this row pointing at a tombstoned monitor — the
+ // service-routed delete must clear it as well.
+ const mon = await db
+ .insert(monitor)
+ .values({
+ workspaceId: 1,
+ name: `${TEST_PREFIX}-delete-with-private-location`,
+ url: "https://pl.example.com",
+ periodicity: "1m",
+ active: true,
+ regions: "ams",
+ jobType: "http",
+ })
+ .returning()
+ .get();
+
+ const pl = await db
+ .insert(privateLocation)
+ .values({
+ workspaceId: 1,
+ name: `${TEST_PREFIX}-pl`,
+ token: `${TEST_PREFIX}-pl-token-${mon.id}`,
+ })
+ .returning()
+ .get();
+
+ await db
+ .insert(privateLocationToMonitors)
+ .values({ privateLocationId: pl.id, monitorId: mon.id });
+
+ try {
+ const res = await connectRequest(
+ "DeleteMonitor",
+ { id: String(mon.id) },
+ { "x-openstatus-key": "1" },
+ );
+ expect(res.status).toBe(200);
+
+ const join = await db
+ .select()
+ .from(privateLocationToMonitors)
+ .where(eq(privateLocationToMonitors.monitorId, mon.id))
+ .get();
+ expect(join).toBeUndefined();
+ } finally {
+ await db
+ .delete(privateLocationToMonitors)
+ .where(eq(privateLocationToMonitors.privateLocationId, pl.id));
+ await db.delete(privateLocation).where(eq(privateLocation.id, pl.id));
+ await db.delete(monitor).where(eq(monitor.id, mon.id));
+ }
+ });
+
+ test("emits a monitor.delete audit row", async () => {
+ const mon = await db
+ .insert(monitor)
+ .values({
+ workspaceId: 1,
+ name: `${TEST_PREFIX}-delete-audit`,
+ url: "https://audit.example.com",
+ periodicity: "1m",
+ active: true,
+ regions: "ams",
+ jobType: "http",
+ })
+ .returning()
+ .get();
+
+ try {
+ const res = await connectRequest(
+ "DeleteMonitor",
+ { id: String(mon.id) },
+ { "x-openstatus-key": "1" },
+ );
+ expect(res.status).toBe(200);
+
+ const row = await db
+ .select()
+ .from(auditLog)
+ .where(
+ and(
+ eq(auditLog.workspaceId, 1),
+ eq(auditLog.entityType, "monitor"),
+ eq(auditLog.entityId, String(mon.id)),
+ eq(auditLog.action, "monitor.delete"),
+ ),
+ )
+ .get();
+ expect(row).toBeDefined();
+ } finally {
+ await db
+ .delete(auditLog)
+ .where(
+ and(
+ eq(auditLog.entityType, "monitor"),
+ eq(auditLog.entityId, String(mon.id)),
+ ),
+ );
+ await db.delete(monitor).where(eq(monitor.id, mon.id));
+ }
+ });
+
test("deleting a monitor removes its page components", async () => {
// Create a monitor
const mon = await db
diff --git a/apps/server/src/routes/rpc/handlers/monitor/index.ts b/apps/server/src/routes/rpc/handlers/monitor/index.ts
index 870d218c9..b50821d44 100644
--- a/apps/server/src/routes/rpc/handlers/monitor/index.ts
+++ b/apps/server/src/routes/rpc/handlers/monitor/index.ts
@@ -3,13 +3,7 @@ import { getCheckerPayload, getCheckerUrl } from "@/libs/checker";
import { tb } from "@/libs/clients";
import type { ServiceImpl } from "@connectrpc/connect";
import { and, db, eq, gte, inArray, isNull, sql } from "@openstatus/db";
-import {
- monitor,
- monitorRun,
- monitorTagsToMonitors,
- notificationsToMonitors,
- pageComponent,
-} from "@openstatus/db/src/schema";
+import { monitor, monitorRun } from "@openstatus/db/src/schema";
import { monitorStatusTable } from "@openstatus/db/src/schema/monitor_status/monitor_status";
import { selectMonitorSchema } from "@openstatus/db/src/schema/monitors/validation";
import type {
@@ -23,7 +17,10 @@ import type {
TCPMonitor,
} from "@openstatus/proto/monitor/v1";
import { TimeRange } from "@openstatus/proto/monitor/v1";
+import { NotFoundError } from "@openstatus/services";
+import { deleteMonitor } from "@openstatus/services/monitor";
+import { toConnectError, toServiceCtx } from "../../adapter";
import { getRpcContext } from "../../interceptors";
import {
MONITOR_DEFAULTS,
@@ -561,34 +558,19 @@ export const monitorServiceImpl: ServiceImpl<typeof MonitorService> = {
async deleteMonitor(req, ctx) {
const rpcCtx = getRpcContext(ctx);
- const workspaceId = rpcCtx.workspace.id;
-
- const dbMon = await getMonitorById(Number(req.id), workspaceId);
- if (!dbMon) {
- throw monitorNotFoundError(req.id);
+ try {
+ await deleteMonitor({
+ ctx: toServiceCtx(rpcCtx),
+ input: { id: Number(req.id) },
+ });
+ } catch (err) {
+ if (err instanceof NotFoundError) {
+ throw monitorNotFoundError(req.id);
+ }
+ toConnectError(err);
}
- // Soft delete and clean up related rows atomically
- await db.transaction(async (tx) => {
- await tx
- .update(monitor)
- .set({
- active: false,
- deletedAt: new Date(),
- })
- .where(eq(monitor.id, dbMon.id));
- await tx
- .delete(monitorTagsToMonitors)
- .where(eq(monitorTagsToMonitors.monitorId, dbMon.id));
- await tx
- .delete(notificationsToMonitors)
- .where(eq(notificationsToMonitors.monitorId, dbMon.id));
- await tx
- .delete(pageComponent)
- .where(eq(pageComponent.monitorId, dbMon.id));
- });
-
return { success: true };
},
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.ts
index 376eff2d7..98331043c 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
@@ -1,6 +1,7 @@
import { afterAll, beforeAll, describe, expect, test } from "bun:test";
import { and, db, eq, isNull, sql } from "@openstatus/db";
import {
+ auditLog,
monitor,
page,
pageComponent,
@@ -1384,6 +1385,56 @@ describe("StatusPageService.RemoveComponent", () => {
expect(res.status).toBe(404);
});
+
+ test("emits a page_component.delete audit row", async () => {
+ // Routing through `deletePageComponent` is what wires the audit row
+ // — the previous inline `db.delete(pageComponent)` skipped it.
+ const component = await db
+ .insert(pageComponent)
+ .values({
+ workspaceId: 1,
+ pageId: testPageId,
+ type: "static",
+ monitorId: null,
+ name: `${TEST_PREFIX}-component-audit`,
+ order: 0,
+ })
+ .returning()
+ .get();
+
+ try {
+ const res = await connectRequest(
+ "RemoveComponent",
+ { id: String(component.id) },
+ { "x-openstatus-key": "1" },
+ );
+ expect(res.status).toBe(200);
+
+ const row = await db
+ .select()
+ .from(auditLog)
+ .where(
+ and(
+ eq(auditLog.workspaceId, 1),
+ eq(auditLog.entityType, "page_component"),
+ eq(auditLog.entityId, String(component.id)),
+ eq(auditLog.action, "page_component.delete"),
+ ),
+ )
+ .get();
+ expect(row).toBeDefined();
+ } finally {
+ await db
+ .delete(auditLog)
+ .where(
+ and(
+ eq(auditLog.entityType, "page_component"),
+ eq(auditLog.entityId, String(component.id)),
+ ),
+ );
+ await db.delete(pageComponent).where(eq(pageComponent.id, component.id));
+ }
+ });
});
describe("StatusPageService.UpdateComponent", () => {
diff --git a/apps/server/src/routes/rpc/handlers/status-page/index.ts b/apps/server/src/routes/rpc/handlers/status-page/index.ts
index 661c02aec..8a38a2071 100644
--- a/apps/server/src/routes/rpc/handlers/status-page/index.ts
+++ b/apps/server/src/routes/rpc/handlers/status-page/index.ts
@@ -32,12 +32,14 @@ import {
ConflictError,
LimitExceededError,
NotFoundError,
+ ServiceError,
withTransaction,
} from "@openstatus/services";
import {
createPage,
deletePage,
getPage,
+ getPageBySlug,
listPages,
updatePageAppearance,
updatePageCustomDomain,
@@ -46,18 +48,17 @@ import {
updatePageLocales,
updatePagePasswordProtection,
} from "@openstatus/services/page";
+import { deletePageComponent } from "@openstatus/services/page-component";
import {
- createSubscription as createSubscriptionService,
- detectWebhookFlavor,
- getChannel,
- upsertEmailSubscription,
-} from "@openstatus/subscriptions";
+ createPageSubscriber,
+ upsertSelfSignupSubscriber,
+} from "@openstatus/services/page-subscriber";
+import { getChannel } from "@openstatus/subscriptions";
import { THEME_KEYS, type ThemeKey } from "@openstatus/theme-store";
import { toConnectError, toServiceCtx } from "../../adapter";
import { getRpcContext } from "../../interceptors";
import {
- type DBPageSubscriber,
dbComponentToProto,
dbGroupToProto,
dbPageToProto,
@@ -137,15 +138,6 @@ async function getPageById(id: number, workspaceId: number) {
.get();
}
-/**
- * Helper to get a status page by slug.
- * Normalizes the slug to lowercase before querying.
- */
-async function getPageBySlug(slug: string) {
- const normalizedSlug = slug.toLowerCase();
- return db.select().from(page).where(eq(page.slug, normalizedSlug)).get();
-}
-
/**
* Validates public access to a status page.
* Checks that the page is published and has public access type.
@@ -306,7 +298,7 @@ export const statusPageServiceImpl: ServiceImpl<typeof StatusPageService> = {
// Slug uniqueness — preserved at handler to keep the granular
// `slugAlreadyExistsError(slug)` (AlreadyExists + metadata) rather
// than the service's generic ConflictError → InvalidArgument mapping.
- const existingPage = await getPageBySlug(req.slug);
+ const existingPage = await getPageBySlug({ input: { slug: req.slug } });
if (existingPage) {
throw slugAlreadyExistsError(req.slug);
}
@@ -533,7 +525,7 @@ export const statusPageServiceImpl: ServiceImpl<typeof StatusPageService> = {
// Slug uniqueness — pre-check at handler to preserve the granular
// `slugAlreadyExistsError(slug)` (AlreadyExists + metadata).
if (req.slug && req.slug !== existing.slug) {
- const slugRow = await getPageBySlug(req.slug);
+ const slugRow = await getPageBySlug({ input: { slug: req.slug } });
if (slugRow && slugRow.id !== existing.id) {
throw slugAlreadyExistsError(req.slug);
}
@@ -891,21 +883,22 @@ export const statusPageServiceImpl: ServiceImpl<typeof StatusPageService> = {
async removeComponent(req, ctx) {
const rpcCtx = getRpcContext(ctx);
- const workspaceId = rpcCtx.workspace.id;
+ const sCtx = toServiceCtx(rpcCtx);
const id = req.id?.trim();
if (!id) {
throw pageComponentNotFoundError(req.id);
}
- const component = await getComponentById(Number(id), workspaceId);
- if (!component) {
- throw pageComponentNotFoundError(id);
+ try {
+ await deletePageComponent({ ctx: sCtx, input: { id: Number(id) } });
+ } catch (err) {
+ if (err instanceof NotFoundError) {
+ throw pageComponentNotFoundError(id);
+ }
+ toConnectError(err);
}
- // Delete the component
- await db.delete(pageComponent).where(eq(pageComponent.id, component.id));
-
return { success: true };
},
@@ -1085,9 +1078,11 @@ export const statusPageServiceImpl: ServiceImpl<typeof StatusPageService> = {
throw statusPageNotFoundError(req.pageId);
}
- const result = await upsertEmailSubscription({
- email: req.email,
- pageId: pageData.id,
+ const result = await upsertSelfSignupSubscriber({
+ input: {
+ email: req.email,
+ pageId: pageData.id,
+ },
});
const row = await db
@@ -1135,82 +1130,65 @@ export const statusPageServiceImpl: ServiceImpl<typeof StatusPageService> = {
async createPageSubscription(req, ctx) {
const rpcCtx = getRpcContext(ctx);
- const workspaceId = rpcCtx.workspace.id;
+ const sCtx = toServiceCtx(rpcCtx);
- if (!rpcCtx.workspace.limits["status-subscribers"]) {
+ const pageId = Number(req.pageId);
+ const componentIds = (req.componentIds ?? []).map((id) => Number(id));
+ const name = req.name ?? null;
+
+ if (
+ req.channel.case !== "emailChannel" &&
+ req.channel.case !== "webhookChannel"
+ ) {
throw new ConnectError(
- "Upgrade to use status subscribers",
- Code.PermissionDenied,
+ "channel oneof must be set to email_channel or webhook_channel",
+ Code.InvalidArgument,
);
}
- const pageData = await getPageById(Number(req.pageId), workspaceId);
- if (!pageData) {
- throw statusPageNotFoundError(req.pageId);
- }
-
- const componentIds = (req.componentIds ?? []).map((id) => Number(id));
- const name = req.name ?? null;
-
- let subscriberRow: DBPageSubscriber | undefined;
+ let result: Awaited<ReturnType<typeof createPageSubscriber>>;
try {
if (req.channel.case === "emailChannel") {
- const created = await createSubscriptionService({
- pageId: pageData.id,
- channelType: "email",
- email: req.channel.value.email,
- name,
- componentIds,
+ result = await createPageSubscriber({
+ ctx: sCtx,
+ input: {
+ pageId,
+ channelType: "email",
+ email: req.channel.value.email,
+ name,
+ componentIds,
+ },
});
- subscriberRow = await db
- .select()
- .from(pageSubscriber)
- .where(eq(pageSubscriber.id, created.id))
- .get();
- } else if (req.channel.case === "webhookChannel") {
- const webhookUrl = req.channel.value.webhookUrl;
- if (detectWebhookFlavor(webhookUrl) === "generic") {
- throw new ConnectError(
- "Only Slack and Discord webhook URLs are supported.",
- Code.InvalidArgument,
- );
- }
- const headers = protoHeadersToPlain(req.channel.value.headers);
- const created = await createSubscriptionService({
- pageId: pageData.id,
- channelType: "webhook",
- webhookUrl,
- name,
- channelConfig: headers.length > 0 ? { headers } : undefined,
- componentIds,
- });
- subscriberRow = await db
- .select()
- .from(pageSubscriber)
- .where(eq(pageSubscriber.id, created.id))
- .get();
} else {
- throw new ConnectError(
- "channel oneof must be set to email_channel or webhook_channel",
- Code.InvalidArgument,
- );
+ result = await createPageSubscriber({
+ ctx: sCtx,
+ input: {
+ pageId,
+ channelType: "webhook",
+ webhookUrl: req.channel.value.webhookUrl,
+ name,
+ headers: protoHeadersToPlain(req.channel.value.headers),
+ componentIds,
+ },
+ });
}
} catch (error) {
if (error instanceof ConnectError) throw error;
- // Don't echo raw service-layer error messages to RPC clients; they may
- // contain details that shouldn't be exposed. Log server-side for debugging.
+ // Service-layer ServiceErrors map cleanly via toConnectError
+ // (NotFound → NotFound, Conflict/Validation → InvalidArgument,
+ // Forbidden → PermissionDenied, etc). Anything else surfaces as
+ // Internal — don't echo raw messages to RPC clients.
+ if (error instanceof ServiceError) {
+ toConnectError(error);
+ }
console.error("createPageSubscription failed:", error);
throw subscriberCreateFailedError();
}
- if (!subscriberRow) {
- throw subscriberCreateFailedError();
- }
-
return {
subscriber: dbSubscriberToProto({
- ...subscriberRow,
- componentIds,
+ ...result.row,
+ componentIds: result.componentIds,
}),
};
},
@@ -1342,7 +1320,7 @@ export const statusPageServiceImpl: ServiceImpl<typeof StatusPageService> = {
pageData = await getPageById(Number(identifierValue), workspaceId);
} else if (req.identifier.case === "slug") {
identifierValue = req.identifier.value;
- pageData = await getPageBySlug(identifierValue);
+ pageData = await getPageBySlug({ input: { slug: identifierValue } });
isPublicAccess = true;
} else {
throw statusPageIdRequiredError();
@@ -1519,7 +1497,7 @@ export const statusPageServiceImpl: ServiceImpl<typeof StatusPageService> = {
pageData = await getPageById(Number(identifierValue), workspaceId);
} else if (req.identifier.case === "slug") {
identifierValue = req.identifier.value;
- pageData = await getPageBySlug(identifierValue);
+ pageData = await getPageBySlug({ input: { slug: identifierValue } });
isPublicAccess = true;
} else {
throw statusPageIdRequiredError();
diff --git a/apps/server/src/routes/slack/oauth.ts b/apps/server/src/routes/slack/oauth.ts
index cf2d15fd3..761003e58 100644
--- a/apps/server/src/routes/slack/oauth.ts
+++ b/apps/server/src/routes/slack/oauth.ts
@@ -1,9 +1,16 @@
import crypto from "node:crypto";
import { env } from "@/env";
-import { and, db, eq } from "@openstatus/db";
-import { integration } from "@openstatus/db/src/schema";
+import { getLogger } from "@logtape/logtape";
+import { db, eq } from "@openstatus/db";
+import {
+ selectWorkspaceSchema,
+ workspace as workspaceTable,
+} from "@openstatus/db/src/schema";
+import { installSlackAgent } from "@openstatus/services/integration";
import type { Context } from "hono";
+const logger = getLogger(["api-server", "slack", "oauth"]);
+
const SLACK_OAUTH_URL = "https://slack.com/oauth/v2/authorize";
const SLACK_TOKEN_URL = "https://slack.com/api/oauth.v2.access";
@@ -22,6 +29,9 @@ const BOT_SCOPES = [
interface OAuthState {
workspaceId: number;
+ // The openstatus user who initiated the install. Optional so in-flight
+ // installs that started before this field was added still parse.
+ userId?: number;
ts: number;
}
@@ -55,6 +65,7 @@ export async function handleSlackInstall(c: Context) {
const state = encodeState({
workspaceId: installPayload.workspaceId,
+ userId: installPayload.userId,
ts: Date.now(),
});
@@ -103,52 +114,63 @@ export async function handleSlackOAuthCallback(c: Context) {
const tokenData = (await tokenRes.json()) as SlackOAuthResponse;
if (!tokenData.ok) {
- console.error("[slack oauth] token exchange failed:", tokenData.error);
+ logger.error("token exchange failed", { error: tokenData.error });
return c.redirect(`${getDashboardUrl()}/settings/integrations?slack=error`);
}
- const credential = {
- botToken: tokenData.access_token,
- botUserId: tokenData.bot_user_id,
- };
-
- const data = {
- teamId: tokenData.team.id,
- teamName: tokenData.team.name,
- appId: tokenData.app_id,
- scopes: tokenData.scope,
- installedBy: tokenData.authed_user.id,
- };
-
- const existing = await db
+ const workspaceRow = await db
.select()
- .from(integration)
- .where(
- and(
- eq(integration.name, "slack-agent"),
- eq(integration.workspaceId, state.workspaceId),
- ),
- )
+ .from(workspaceTable)
+ .where(eq(workspaceTable.id, state.workspaceId))
.get();
+ if (!workspaceRow) {
+ logger.error("workspace not found at callback", {
+ workspaceId: state.workspaceId,
+ });
+ return c.redirect(`${getDashboardUrl()}/settings/integrations?slack=error`);
+ }
- if (existing) {
- await db
- .update(integration)
- .set({
+ const workspaceParsed = selectWorkspaceSchema.safeParse(workspaceRow);
+ if (!workspaceParsed.success) {
+ logger.error("workspace row failed schema parse", {
+ workspaceId: state.workspaceId,
+ issues: workspaceParsed.error.issues,
+ });
+ return c.redirect(`${getDashboardUrl()}/settings/integrations?slack=error`);
+ }
+
+ try {
+ await installSlackAgent({
+ ctx: {
+ workspace: workspaceParsed.data,
+ actor: {
+ type: "slack",
+ teamId: tokenData.team.id,
+ slackUserId: tokenData.authed_user.id,
+ userId: state.userId,
+ },
+ },
+ input: {
externalId: tokenData.team.id,
- credential,
- data,
- updatedAt: new Date(),
- })
- .where(eq(integration.id, existing.id));
- } else {
- await db.insert(integration).values({
- name: "slack-agent",
+ credential: {
+ botToken: tokenData.access_token,
+ botUserId: tokenData.bot_user_id,
+ },
+ data: {
+ teamId: tokenData.team.id,
+ teamName: tokenData.team.name,
+ appId: tokenData.app_id,
+ scopes: tokenData.scope,
+ installedBy: tokenData.authed_user.id,
+ },
+ },
+ });
+ } catch (err) {
+ logger.error("installSlackAgent failed", {
workspaceId: state.workspaceId,
- externalId: tokenData.team.id,
- credential,
- data,
+ err: err instanceof Error ? err.message : String(err),
});
+ return c.redirect(`${getDashboardUrl()}/settings/integrations?slack=error`);
}
return c.redirect(`${getDashboardUrl()}/settings/integrations?slack=success`);
@@ -203,7 +225,9 @@ function verifyHmac(payload: string, signature: string): boolean {
const INSTALL_TOKEN_TTL_MS = 5 * 60 * 1000;
-function verifyInstallToken(token: string): { workspaceId: number } | null {
+function verifyInstallToken(
+ token: string,
+): { workspaceId: number; userId?: number } | null {
try {
const decoded = Buffer.from(token, "base64url").toString();
const dotIdx = decoded.lastIndexOf(".");
@@ -214,10 +238,14 @@ function verifyInstallToken(token: string): { workspaceId: number } | null {
if (!verifyHmac(payload, signature)) return null;
- const data = JSON.parse(payload) as { workspaceId: number; ts: number };
+ const data = JSON.parse(payload) as {
+ workspaceId: number;
+ userId?: number;
+ ts: number;
+ };
if (Date.now() - data.ts > INSTALL_TOKEN_TTL_MS) return null;
- return { workspaceId: data.workspaceId };
+ return { workspaceId: data.workspaceId, userId: data.userId };
} catch {
return null;
}
diff --git a/packages/api/src/router/integration.ts b/packages/api/src/router/integration.ts
index 348f96a2c..f6ba301ef 100644
--- a/packages/api/src/router/integration.ts
+++ b/packages/api/src/router/integration.ts
@@ -1,90 +1,60 @@
// biome-ignore lint/style/useNodejsImportProtocol: some error with build
import crypto from "crypto";
+import {
+ deleteIntegration,
+ listIntegrations,
+} from "@openstatus/services/integration";
import { z } from "zod";
-import { and, eq, sql } from "@openstatus/db";
-import { integration } from "@openstatus/db/src/schema";
-
+import { toServiceCtx, toTRPCError } from "../service-adapter";
import { createTRPCRouter, protectedProcedure } from "../trpc";
-function signInstallToken(workspaceId: number, ts: number): string {
+/**
+ * Slack install-token generation stays router-local: no DB work, no
+ * workspace-scoped business rule — it's just HMAC plumbing against an env
+ * secret and better kept alongside the Slack OAuth surface than inflated
+ * into a service verb.
+ */
+function signInstallToken(args: {
+ workspaceId: number;
+ userId: number;
+ ts: number;
+}): string {
const secret = process.env.SLACK_SIGNING_SECRET;
if (!secret) throw new Error("Slack not configured");
- const payload = JSON.stringify({ workspaceId, ts });
+ const payload = JSON.stringify(args);
const sig = crypto.createHmac("sha256", secret).update(payload).digest("hex");
return Buffer.from(`${payload}.${sig}`).toString("base64url");
}
-function safeJsonParse(value: string | null): Record<string, unknown> {
- if (!value) return {};
- try {
- return JSON.parse(value) as Record<string, unknown>;
- } catch {
- return {};
- }
-}
-
export const integrationRouter = createTRPCRouter({
- list: protectedProcedure.query(async (opts) => {
- const rows = await opts.ctx.db
- .select({
- id: integration.id,
- name: integration.name,
- externalId: integration.externalId,
- rawData: sql<string>`${integration.data}`,
- createdAt: integration.createdAt,
- })
- .from(integration)
- .where(eq(integration.workspaceId, opts.ctx.workspace.id))
- .all();
-
- return rows.map((row) => ({
- id: row.id,
- name: row.name,
- externalId: row.externalId,
- data: safeJsonParse(row.rawData),
- createdAt: row.createdAt,
- }));
+ list: protectedProcedure.query(async ({ ctx }) => {
+ try {
+ return await listIntegrations({ ctx: toServiceCtx(ctx) });
+ } catch (err) {
+ toTRPCError(err);
+ }
}),
- generateInstallToken: protectedProcedure.mutation(async (opts) => {
- const token = signInstallToken(opts.ctx.workspace.id, Date.now());
+ generateInstallToken: protectedProcedure.mutation(async ({ ctx }) => {
+ const token = signInstallToken({
+ workspaceId: ctx.workspace.id,
+ userId: ctx.user.id,
+ ts: Date.now(),
+ });
return { token };
}),
deleteIntegration: protectedProcedure
.input(z.object({ integrationId: z.number() }))
- .mutation(async (opts) => {
- const existing = await opts.ctx.db
- .select()
- .from(integration)
- .where(
- and(
- eq(integration.id, opts.input.integrationId),
- eq(integration.workspaceId, opts.ctx.workspace.id),
- ),
- )
- .get();
-
- if (!existing) return;
-
- const cred = existing.credential as { botToken?: string } | null;
- if (cred?.botToken) {
- try {
- await fetch("https://slack.com/api/auth.revoke", {
- method: "POST",
- headers: {
- Authorization: `Bearer ${cred.botToken}`,
- "Content-Type": "application/x-www-form-urlencoded",
- },
- });
- } catch {
- // Token may already be invalid
- }
+ .mutation(async ({ ctx, input }) => {
+ try {
+ await deleteIntegration({
+ ctx: toServiceCtx(ctx),
+ input: { id: input.integrationId },
+ });
+ } catch (err) {
+ toTRPCError(err);
}
-
- await opts.ctx.db
- .delete(integration)
- .where(eq(integration.id, existing.id));
}),
});
diff --git a/packages/api/src/router/member.ts b/packages/api/src/router/member.ts
index b7dcc3702..964339940 100644
--- a/packages/api/src/router/member.ts
+++ b/packages/api/src/router/member.ts
@@ -1,69 +1,36 @@
-import { z } from "zod";
-
import { Events } from "@openstatus/analytics";
-import { and, eq } from "@openstatus/db";
import {
- selectUserSchema,
- usersToWorkspaces,
- workspaceRole,
-} from "@openstatus/db/src/schema";
+ ListMembersInput,
+ deleteMember,
+ listMembers,
+} from "@openstatus/services/member";
+import { z } from "zod";
-import { TRPCError } from "@trpc/server";
+import { toServiceCtx, toTRPCError } from "../service-adapter";
import { createTRPCRouter, protectedProcedure } from "../trpc";
export const memberRouter = createTRPCRouter({
- list: protectedProcedure.query(async (opts) => {
- const result = await opts.ctx.db.query.usersToWorkspaces.findMany({
- where: eq(usersToWorkspaces.workspaceId, opts.ctx.workspace.id),
- with: {
- user: true,
- },
- });
-
- return z
- .object({
- role: z.enum(workspaceRole),
- createdAt: z.coerce.date(),
- user: selectUserSchema,
- })
- .array()
- .parse(result);
- }),
+ list: protectedProcedure
+ .input(ListMembersInput.optional())
+ .query(async ({ ctx, input }) => {
+ try {
+ return await listMembers({ ctx: toServiceCtx(ctx), input });
+ } catch (err) {
+ toTRPCError(err);
+ }
+ }),
delete: protectedProcedure
.meta({ track: Events.RemoveUser })
.input(z.object({ id: z.number() }))
- .mutation(async (opts) => {
- const currentUser = await opts.ctx.db.query.usersToWorkspaces.findFirst({
- where: and(
- eq(usersToWorkspaces.userId, opts.ctx.user.id),
- eq(usersToWorkspaces.workspaceId, opts.ctx.workspace.id),
- ),
- });
-
- if (!currentUser) throw new Error("No user to workspace found");
-
- if (!["owner"].includes(currentUser.role)) {
- throw new TRPCError({
- code: "PRECONDITION_FAILED",
- message: "Not authorized to remove user from workspace",
- });
- }
-
- if (opts.input.id === opts.ctx.user.id) {
- throw new TRPCError({
- code: "PRECONDITION_FAILED",
- message: "Cannot remove yourself from workspace",
+ .mutation(async ({ ctx, input }) => {
+ try {
+ await deleteMember({
+ ctx: toServiceCtx(ctx),
+ input: { userId: input.id },
});
+ } catch (err) {
+ toTRPCError(err);
}
-
- await opts.ctx.db
- .delete(usersToWorkspaces)
- .where(
- and(
- eq(usersToWorkspaces.workspaceId, opts.ctx.workspace.id),
- eq(usersToWorkspaces.userId, opts.input.id),
- ),
- );
}),
});
diff --git a/packages/api/src/router/monitorTag.ts b/packages/api/src/router/monitorTag.ts
index 702462675..44a2b2905 100644
--- a/packages/api/src/router/monitorTag.ts
+++ b/packages/api/src/router/monitorTag.ts
@@ -1,8 +1,11 @@
+import {
+ ListMonitorTagsInput,
+ listMonitorTags,
+ syncMonitorTags,
+} from "@openstatus/services/monitor-tag";
import { z } from "zod";
-import { and, eq, inArray } from "@openstatus/db";
-import { monitorTag } from "@openstatus/db/src/schema";
-
+import { toServiceCtx, toTRPCError } from "../service-adapter";
import { createTRPCRouter, protectedProcedure } from "../trpc";
const tagSchema = z.object({
@@ -12,88 +15,26 @@ const tagSchema = z.object({
});
export const monitorTagRouter = createTRPCRouter({
- list: protectedProcedure.query(async (opts) => {
- return opts.ctx.db.query.monitorTag.findMany({
- where: eq(monitorTag.workspaceId, opts.ctx.workspace.id),
- with: { monitor: true },
- });
- }),
+ list: protectedProcedure
+ .input(ListMonitorTagsInput.optional())
+ .query(async ({ ctx, input }) => {
+ try {
+ return await listMonitorTags({ ctx: toServiceCtx(ctx), input });
+ } catch (err) {
+ toTRPCError(err);
+ }
+ }),
syncTags: protectedProcedure
.input(z.array(tagSchema))
- .mutation(async (opts) => {
- const { ctx } = opts;
- const workspaceId = ctx.workspace.id;
-
- return await ctx.db.transaction(async (tx) => {
- // Get all existing tags for this workspace
- const existingTags = await tx.query.monitorTag.findMany({
- where: eq(monitorTag.workspaceId, workspaceId),
+ .mutation(async ({ ctx, input }) => {
+ try {
+ return await syncMonitorTags({
+ ctx: toServiceCtx(ctx),
+ input: { tags: input },
});
-
- // Get IDs of tags that should be kept (have an ID in the input)
- const keepTagIds = new Set(
- opts.input
- .map((tag) => tag.id)
- .filter((id): id is number => id !== undefined),
- );
-
- // Delete tags that are not in the input
- const tagsToDelete = existingTags.filter(
- (tag) => !keepTagIds.has(tag.id),
- );
- if (tagsToDelete.length > 0) {
- await tx
- .delete(monitorTag)
- .where(
- and(
- eq(monitorTag.workspaceId, workspaceId),
- inArray(
- monitorTag.id,
- tagsToDelete.map((t) => t.id),
- ),
- ),
- )
- .run();
- }
-
- // Update or create tags
- const results = await Promise.all(
- opts.input.map(async (tag) => {
- if (tag.id) {
- // Update existing tag
- return tx
- .update(monitorTag)
- .set({
- name: tag.name,
- color: tag.color,
- updatedAt: new Date(),
- })
- .where(
- and(
- eq(monitorTag.workspaceId, workspaceId),
- eq(monitorTag.id, tag.id),
- ),
- )
- .returning()
- .get();
- }
- // Create new tag
- return tx
- .insert(monitorTag)
- .values({
- name: tag.name,
- color: tag.color,
- workspaceId,
- })
- .returning()
- .get();
- }),
- );
-
- console.error(results);
-
- return results;
- });
+ } catch (err) {
+ toTRPCError(err);
+ }
}),
});
diff --git a/packages/api/src/router/pageSubscriber.ts b/packages/api/src/router/pageSubscriber.ts
index 6b5297164..9af4c3cab 100644
--- a/packages/api/src/router/pageSubscriber.ts
+++ b/packages/api/src/router/pageSubscriber.ts
@@ -1,25 +1,23 @@
import { Events } from "@openstatus/analytics";
-import { and, db, eq } from "@openstatus/db";
import {
- page,
- pageSubscriber,
- selectWorkspaceSchema,
-} from "@openstatus/db/src/schema";
-import {
- createSubscription,
- detectWebhookFlavor,
- getSubscriptionByToken,
- hasPendingUnexpiredSubscription,
- sendTestWebhook,
- unsubscribe,
- updateChannel,
- updateSubscriptionScope,
- upsertEmailSubscription,
- verifySubscription,
-} from "@openstatus/subscriptions";
+ SAFE_SUBSCRIPTION_MESSAGES,
+ createPageSubscriber,
+ deletePageSubscriber,
+ getSubscriberByToken,
+ hasPendingSubscriber,
+ listPageSubscribers,
+ sendPageSubscriberTestWebhook,
+ unsubscribeSubscriber,
+ updatePageSubscriberChannel,
+ updateSubscriberScope,
+ upsertSelfSignupSubscriber,
+ verifySelfSignupSubscriber,
+} from "@openstatus/services/page-subscriber";
+import { detectWebhookFlavor } from "@openstatus/subscriptions";
import { TRPCError } from "@trpc/server";
import { z } from "zod";
+import { toServiceCtx, toTRPCError } from "../service-adapter";
import { createTRPCRouter, protectedProcedure, publicProcedure } from "../trpc";
const webhookHeadersSchema = z
@@ -38,68 +36,24 @@ const supportedWebhookUrlSchema = z
message: "Only Slack and Discord webhook URLs are supported.",
});
-async function assertPageInWorkspace(pageId: number, workspaceId: number) {
- const _page = await db.query.page.findFirst({
- where: and(eq(page.workspaceId, workspaceId), eq(page.id, pageId)),
- with: { workspace: true },
- });
- if (!_page) {
- throw new TRPCError({ code: "NOT_FOUND", message: "Page not found" });
- }
- return _page;
-}
-
-// Explicit allow-list of service-layer messages that are safe to surface to
-// clients. Anything else — including new paths added to the service later —
-// is logged server-side and replaced with the procedure's fallback, so we
-// can't accidentally leak IDs, emails, or raw SQL through an unvetted code
-// path.
-const SAFE_SERVICE_MESSAGES = new Set<string>([
- "Page not found",
- "Some components do not belong to this page",
- "A subscriber with this email already exists for this page.",
- "A subscriber with this webhook URL already exists for this page.",
- "Only Slack and Discord webhook URLs are supported.",
- "Subscriber not found",
- "Subscriber is not a webhook channel",
- "Self-signup subscribers manage their own subscription; use the unsubscribe action instead.",
- "Email subscribers do not have webhook fields to edit.",
- "Only vendor-added webhook subscribers support test dispatch.",
- "Subscription not found",
- "Subscription not yet verified",
- "Subscription is unsubscribed",
- "Verification token expired",
-]);
-
+// Public (status-page-facing) procedures use the same allow-list as
+// the protected procedures going through `toTRPCError`. Single source
+// of truth lives in `@openstatus/services/page-subscriber` so a new
+// subscriptions error message only needs adding in one place.
function throwFromException(error: unknown, fallback: string): never {
if (error instanceof TRPCError) throw error;
console.error("pageSubscriber router error:", error);
- if (error instanceof Error && SAFE_SERVICE_MESSAGES.has(error.message)) {
+ if (error instanceof Error && SAFE_SUBSCRIPTION_MESSAGES.has(error.message)) {
throw new TRPCError({ code: "BAD_REQUEST", message: error.message });
}
throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: fallback });
}
-/**
- * Reduce a webhook URL to its origin so the secret path isn't exposed.
- * Used when the row isn't owned by the vendor (self-signup / import).
- */
-function webhookUrlForList(
- source: string,
- webhookUrl: string | null,
-): string | null {
- if (!webhookUrl) return null;
- if (source === "vendor") return webhookUrl;
- try {
- return new URL(webhookUrl).origin;
- } catch {
- return null;
- }
-}
-
export const pageSubscriberRouter = createTRPCRouter({
/**
- * PUBLIC: Subscribe to a status page (or update existing subscription)
+ * PUBLIC: Subscribe to a status page (or update existing subscription).
+ * Lives outside the service layer — status-page self-signup is not
+ * dashboard-owned.
*/
upsert: publicProcedure
.input(
@@ -110,11 +64,9 @@ export const pageSubscriberRouter = createTRPCRouter({
}),
)
.mutation(async (opts) => {
- // Guard against email spam: reject if a pending (unverified, unexpired) subscription exists
- const isPending = await hasPendingUnexpiredSubscription(
- opts.input.email,
- opts.input.pageId,
- );
+ const isPending = await hasPendingSubscriber({
+ input: { email: opts.input.email, pageId: opts.input.pageId },
+ });
if (isPending) {
throw new TRPCError({
code: "BAD_REQUEST",
@@ -124,10 +76,12 @@ export const pageSubscriberRouter = createTRPCRouter({
}
try {
- const subscription = await upsertEmailSubscription({
- email: opts.input.email,
- pageId: opts.input.pageId,
- componentIds: opts.input.componentIds,
+ const subscription = await upsertSelfSignupSubscriber({
+ input: {
+ email: opts.input.email,
+ pageId: opts.input.pageId,
+ componentIds: opts.input.componentIds,
+ },
});
return {
@@ -155,10 +109,9 @@ export const pageSubscriberRouter = createTRPCRouter({
)
.mutation(async (opts) => {
try {
- const subscription = await verifySubscription(
- opts.input.token,
- opts.input.domain,
- );
+ const subscription = await verifySelfSignupSubscriber({
+ input: { token: opts.input.token, domain: opts.input.domain },
+ });
if (!subscription) {
throw new TRPCError({
@@ -193,29 +146,32 @@ export const pageSubscriberRouter = createTRPCRouter({
}),
)
.query(async (opts) => {
- const subscription = await getSubscriptionByToken(
- opts.input.token,
- opts.input.domain,
- );
-
- if (!subscription) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "Subscription not found",
+ try {
+ const subscription = await getSubscriberByToken({
+ input: { token: opts.input.token, domain: opts.input.domain },
});
- }
- return {
- id: subscription.id,
- email: subscription.email,
- pageName: subscription.pageName,
- pageSlug: subscription.pageSlug,
- customDomain: subscription.customDomain,
- channelType: subscription.channelType,
- componentIds: subscription.componentIds,
- acceptedAt: subscription.acceptedAt,
- unsubscribedAt: subscription.unsubscribedAt,
- };
+ if (!subscription) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Subscription not found",
+ });
+ }
+
+ return {
+ id: subscription.id,
+ email: subscription.email,
+ pageName: subscription.pageName,
+ pageSlug: subscription.pageSlug,
+ customDomain: subscription.customDomain,
+ channelType: subscription.channelType,
+ componentIds: subscription.componentIds,
+ acceptedAt: subscription.acceptedAt,
+ unsubscribedAt: subscription.unsubscribedAt,
+ };
+ } catch (error) {
+ throwFromException(error, "Failed to load subscription");
+ }
}),
/**
@@ -231,17 +187,18 @@ export const pageSubscriberRouter = createTRPCRouter({
)
.mutation(async (opts) => {
try {
- const subscription = await updateSubscriptionScope({
- token: opts.input.token,
- componentIds: opts.input.componentIds,
- domain: opts.input.domain,
+ await updateSubscriberScope({
+ input: {
+ token: opts.input.token,
+ componentIds: opts.input.componentIds,
+ domain: opts.input.domain,
+ },
});
return {
success: true,
subscription: {
- id: subscription.id,
- componentIds: subscription.componentIds,
+ componentIds: opts.input.componentIds,
},
};
} catch (error) {
@@ -261,8 +218,9 @@ export const pageSubscriberRouter = createTRPCRouter({
)
.mutation(async (opts) => {
try {
- await unsubscribe(opts.input.token, opts.input.domain);
-
+ await unsubscribeSubscriber({
+ input: { token: opts.input.token, domain: opts.input.domain },
+ });
return { success: true };
} catch (error) {
throwFromException(error, "Failed to unsubscribe");
@@ -279,71 +237,19 @@ export const pageSubscriberRouter = createTRPCRouter({
order: z.enum(["asc", "desc"]).optional(),
}),
)
- .query(async (opts) => {
- const data = await opts.ctx.db.transaction(async (tx) => {
- const _page = await tx.query.page.findFirst({
- where: and(
- eq(page.workspaceId, opts.ctx.workspace.id),
- eq(page.id, opts.input.pageId),
- ),
- });
-
- if (!_page) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "Page not found",
- });
- }
-
- const subscriptions = await tx.query.pageSubscriber.findMany({
- where: eq(pageSubscriber.pageId, _page.id),
- with: {
- components: {
- with: {
- pageComponent: true,
- },
- },
- },
- orderBy: (subs, { desc, asc }) =>
- opts.input.order === "asc"
- ? asc(subs.createdAt)
- : desc(subs.createdAt),
- });
-
- return subscriptions.map((sub) => {
- const isVendor = sub.source === "vendor";
- return {
- id: sub.id,
- channelType: sub.channelType,
- email: sub.email,
- // Vendor rows own the URL + config; other sources only expose the
- // origin (no credential-bearing path) and no channelConfig.
- webhookUrl: webhookUrlForList(sub.source, sub.webhookUrl),
- channelConfig: isVendor ? sub.channelConfig : null,
- source: sub.source,
- name: sub.name,
- acceptedAt: sub.acceptedAt,
- unsubscribedAt: sub.unsubscribedAt,
- createdAt: sub.createdAt,
- components: sub.components.map((c) => ({
- id: c.pageComponent.id,
- name: c.pageComponent.name,
- })),
- isEntirePage: sub.components.length === 0,
- pageId: sub.pageId,
- };
+ .query(async ({ ctx, input }) => {
+ try {
+ return await listPageSubscribers({
+ ctx: toServiceCtx(ctx),
+ input,
});
- });
-
- return data;
+ } catch (err) {
+ toTRPCError(err);
+ }
}),
/**
* PROTECTED: Create a vendor-added subscription (email or webhook).
- *
- * Skips the verification flow — partner starts receiving notifications
- * immediately. `token` is still generated so the partner can self-manage
- * via the existing `/manage/{token}` and `/unsubscribe/{token}` routes.
*/
createSubscription: protectedProcedure
.meta({ track: Events.SubscribePage })
@@ -372,57 +278,20 @@ export const pageSubscriberRouter = createTRPCRouter({
}),
]),
)
- .mutation(async (opts) => {
- const _page = await assertPageInWorkspace(
- opts.input.pageId,
- opts.ctx.workspace.id,
- );
-
- const workspace = selectWorkspaceSchema.safeParse(_page.workspace);
- if (!workspace.success) {
- throw new TRPCError({
- code: "BAD_REQUEST",
- message: "Workspace data is invalid",
- });
- }
- if (!workspace.data.limits["status-subscribers"]) {
- throw new TRPCError({
- code: "FORBIDDEN",
- message: "Upgrade to use status subscribers",
- });
- }
-
+ .mutation(async ({ ctx, input }) => {
try {
- if (opts.input.channelType === "email") {
- const sub = await createSubscription({
- pageId: opts.input.pageId,
- channelType: "email",
- email: opts.input.email,
- name: opts.input.name ?? null,
- componentIds: opts.input.componentIds,
- });
- return { success: true, id: sub.id };
- }
-
- const sub = await createSubscription({
- pageId: opts.input.pageId,
- channelType: "webhook",
- webhookUrl: opts.input.webhookUrl,
- name: opts.input.name ?? null,
- channelConfig: opts.input.headers
- ? { headers: opts.input.headers }
- : undefined,
- componentIds: opts.input.componentIds,
+ const { id } = await createPageSubscriber({
+ ctx: toServiceCtx(ctx),
+ input,
});
- return { success: true, id: sub.id };
- } catch (error) {
- throwFromException(error, "Failed to create subscription");
+ return { success: true, id };
+ } catch (err) {
+ toTRPCError(err);
}
}),
/**
* PROTECTED: Update a vendor-added subscription's channel config / scope.
- * Self-signup rows are rejected — they self-manage via token.
*/
updateChannel: protectedProcedure
.input(
@@ -435,24 +304,15 @@ export const pageSubscriberRouter = createTRPCRouter({
componentIds: z.array(z.number().int().positive()).max(500).optional(),
}),
)
- .mutation(async (opts) => {
- await assertPageInWorkspace(opts.input.pageId, opts.ctx.workspace.id);
-
+ .mutation(async ({ ctx, input }) => {
try {
- await updateChannel({
- subscriberId: opts.input.subscriberId,
- pageId: opts.input.pageId,
- name: opts.input.name === undefined ? undefined : opts.input.name,
- webhookUrl: opts.input.webhookUrl,
- channelConfig:
- opts.input.headers !== undefined
- ? { headers: opts.input.headers }
- : undefined,
- componentIds: opts.input.componentIds,
+ await updatePageSubscriberChannel({
+ ctx: toServiceCtx(ctx),
+ input,
});
return { success: true };
- } catch (error) {
- throwFromException(error, "Failed to update subscription");
+ } catch (err) {
+ toTRPCError(err);
}
}),
@@ -466,14 +326,15 @@ export const pageSubscriberRouter = createTRPCRouter({
pageId: z.number().int().positive(),
}),
)
- .mutation(async (opts) => {
- await assertPageInWorkspace(opts.input.pageId, opts.ctx.workspace.id);
-
+ .mutation(async ({ ctx, input }) => {
try {
- await sendTestWebhook(opts.input.subscriberId, opts.input.pageId);
+ await sendPageSubscriberTestWebhook({
+ ctx: toServiceCtx(ctx),
+ input,
+ });
return { success: true };
- } catch (error) {
- throwFromException(error, "Failed to send test webhook");
+ } catch (err) {
+ toTRPCError(err);
}
}),
@@ -482,41 +343,15 @@ export const pageSubscriberRouter = createTRPCRouter({
*/
delete: protectedProcedure
.input(z.object({ id: z.number(), pageId: z.number() }))
- .mutation(async (opts) => {
- await opts.ctx.db.transaction(async (tx) => {
- const _page = await tx.query.page.findFirst({
- where: and(
- eq(page.workspaceId, opts.ctx.workspace.id),
- eq(page.id, opts.input.pageId),
- ),
- });
-
- if (!_page) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "Page not found",
- });
- }
-
- const subscriber = await tx.query.pageSubscriber.findFirst({
- where: and(
- eq(pageSubscriber.id, opts.input.id),
- eq(pageSubscriber.pageId, opts.input.pageId),
- ),
+ .mutation(async ({ ctx, input }) => {
+ try {
+ await deletePageSubscriber({
+ ctx: toServiceCtx(ctx),
+ input,
});
-
- if (!subscriber) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "Subscriber not found",
- });
- }
-
- return await tx
- .delete(pageSubscriber)
- .where(eq(pageSubscriber.id, opts.input.id));
- });
-
- return { success: true };
+ return { success: true };
+ } catch (err) {
+ toTRPCError(err);
+ }
}),
});
diff --git a/packages/api/src/router/privateLocation.ts b/packages/api/src/router/privateLocation.ts
index a94e390ef..b21a35049 100644
--- a/packages/api/src/router/privateLocation.ts
+++ b/packages/api/src/router/privateLocation.ts
@@ -1,34 +1,26 @@
-import { and, eq, inArray } from "@openstatus/db";
import {
- monitor,
- privateLocation,
- privateLocationToMonitors,
-} from "@openstatus/db/src/schema";
-import { TRPCError } from "@trpc/server";
+ ListPrivateLocationsInput,
+ createPrivateLocation,
+ deletePrivateLocation,
+ listPrivateLocations,
+ updatePrivateLocation,
+} from "@openstatus/services/private-location";
import { z } from "zod";
+import { toServiceCtx, toTRPCError } from "../service-adapter";
import { createTRPCRouter, protectedProcedure } from "../trpc";
export const privateLocationRouter = createTRPCRouter({
- list: protectedProcedure.query(async (opts) => {
- const privateLocations = await opts.ctx.db.transaction(async (tx) => {
- return await tx.query.privateLocation.findMany({
- where: eq(privateLocation.workspaceId, opts.ctx.workspace.id),
- with: {
- privateLocationToMonitors: {
- with: { monitor: true },
- },
- },
- });
- });
- const result = privateLocations.map((privateLocation) => ({
- ...privateLocation,
- monitors: privateLocation.privateLocationToMonitors
- .map((m) => m.monitor)
- .filter((m) => m !== null),
- }));
- return result;
- }),
+ list: protectedProcedure
+ .input(ListPrivateLocationsInput.optional())
+ .query(async ({ ctx, input }) => {
+ try {
+ return await listPrivateLocations({ ctx: toServiceCtx(ctx), input });
+ } catch (err) {
+ toTRPCError(err);
+ }
+ }),
+
new: protectedProcedure
.input(
z.object({
@@ -37,44 +29,21 @@ export const privateLocationRouter = createTRPCRouter({
token: z.string(),
}),
)
- .mutation(async (opts) => {
- if (opts.input.monitors.length) {
- const validMonitors = await opts.ctx.db.query.monitor.findMany({
- where: and(
- eq(monitor.workspaceId, opts.ctx.workspace.id),
- inArray(monitor.id, opts.input.monitors),
- ),
+ .mutation(async ({ ctx, input }) => {
+ try {
+ return await createPrivateLocation({
+ ctx: toServiceCtx(ctx),
+ input: {
+ name: input.name,
+ token: input.token,
+ monitors: input.monitors,
+ },
});
- if (validMonitors.length !== opts.input.monitors.length) {
- throw new TRPCError({
- code: "FORBIDDEN",
- message: "Invalid monitor IDs.",
- });
- }
+ } catch (err) {
+ toTRPCError(err);
}
-
- return await opts.ctx.db.transaction(async (tx) => {
- const _privateLocation = await tx
- .insert(privateLocation)
- .values({
- name: opts.input.name,
- token: opts.input.token,
- workspaceId: opts.ctx.workspace.id,
- })
- .returning()
- .get();
-
- if (opts.input.monitors.length) {
- await tx.insert(privateLocationToMonitors).values(
- opts.input.monitors.map((monitorId) => ({
- privateLocationId: _privateLocation.id,
- monitorId,
- })),
- );
- }
- return _privateLocation;
- });
}),
+
update: protectedProcedure
.input(
z.object({
@@ -83,83 +52,27 @@ export const privateLocationRouter = createTRPCRouter({
monitors: z.array(z.number()),
}),
)
- .mutation(async (opts) => {
- const existing = await opts.ctx.db.query.privateLocation.findFirst({
- where: and(
- eq(privateLocation.id, opts.input.id),
- eq(privateLocation.workspaceId, opts.ctx.workspace.id),
- ),
- });
-
- if (!existing) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "Private location not found",
+ .mutation(async ({ ctx, input }) => {
+ try {
+ return await updatePrivateLocation({
+ ctx: toServiceCtx(ctx),
+ input,
});
+ } catch (err) {
+ toTRPCError(err);
}
-
- if (opts.input.monitors.length) {
- const validMonitors = await opts.ctx.db.query.monitor.findMany({
- where: and(
- eq(monitor.workspaceId, opts.ctx.workspace.id),
- inArray(monitor.id, opts.input.monitors),
- ),
- });
- if (validMonitors.length !== opts.input.monitors.length) {
- throw new TRPCError({
- code: "FORBIDDEN",
- message: "Invalid monitor IDs.",
- });
- }
- }
-
- return await opts.ctx.db.transaction(async (tx) => {
- const _privateLocation = await tx
- .update(privateLocation)
- .set({ name: opts.input.name, updatedAt: new Date() })
- .where(
- and(
- eq(privateLocation.id, opts.input.id),
- eq(privateLocation.workspaceId, opts.ctx.workspace.id),
- ),
- )
- .returning()
- .get();
-
- await tx
- .delete(privateLocationToMonitors)
- .where(
- eq(
- privateLocationToMonitors.privateLocationId,
- _privateLocation.id,
- ),
- );
-
- if (opts.input.monitors.length) {
- await tx.insert(privateLocationToMonitors).values(
- opts.input.monitors.map((monitorId) => ({
- privateLocationId: _privateLocation.id,
- monitorId,
- })),
- );
- }
-
- return _privateLocation;
- });
}),
+
delete: protectedProcedure
.input(z.object({ id: z.number() }))
- .mutation(async (opts) => {
- console.log("delete private location", opts.input.id);
- return await opts.ctx.db.transaction(async (tx) => {
- await tx
- .delete(privateLocation)
- .where(
- and(
- eq(privateLocation.id, opts.input.id),
- eq(privateLocation.workspaceId, opts.ctx.workspace.id),
- ),
- );
- });
+ .mutation(async ({ ctx, input }) => {
+ try {
+ await deletePrivateLocation({
+ ctx: toServiceCtx(ctx),
+ input,
+ });
+ } catch (err) {
+ toTRPCError(err);
+ }
}),
});
diff --git a/packages/api/src/router/statusPage.ts b/packages/api/src/router/statusPage.ts
index 051095a58..e92f0f1fe 100644
--- a/packages/api/src/router/statusPage.ts
+++ b/packages/api/src/router/statusPage.ts
@@ -16,13 +16,13 @@ import {
statusReport,
} from "@openstatus/db/src/schema";
import {
- getSubscriptionByToken,
- hasPendingUnexpiredSubscription,
- unsubscribe,
- updateSubscriptionScope,
- upsertEmailSubscription,
- verifySubscription,
-} from "@openstatus/subscriptions";
+ getSubscriberByToken,
+ hasPendingSubscriber,
+ unsubscribeSubscriber,
+ updateSubscriberScope,
+ upsertSelfSignupSubscriber,
+ verifySelfSignupSubscriber,
+} from "@openstatus/services/page-subscriber";
import { Events } from "@openstatus/analytics";
import { TRPCError } from "@trpc/server";
@@ -1056,10 +1056,9 @@ export const statusPageRouter = createTRPCRouter({
}
// Guard against email spam: reject if a pending (unverified, unexpired) subscription exists
- const isPending = await hasPendingUnexpiredSubscription(
- opts.input.email,
- _page.id,
- );
+ const isPending = await hasPendingSubscriber({
+ input: { email: opts.input.email, pageId: _page.id },
+ });
if (isPending) {
throw new TRPCError({
code: "BAD_REQUEST",
@@ -1068,12 +1067,14 @@ export const statusPageRouter = createTRPCRouter({
});
}
- const subscription = await upsertEmailSubscription({
- email: opts.input.email,
- pageId: _page.id,
- componentIds: opts.input.subscribeComponents
- ? opts.input.pageComponents
- : [],
+ const subscription = await upsertSelfSignupSubscriber({
+ input: {
+ email: opts.input.email,
+ pageId: _page.id,
+ componentIds: opts.input.subscribeComponents
+ ? opts.input.pageComponents
+ : [],
+ },
});
// Already verified — no need to send another verification email
@@ -1092,10 +1093,9 @@ export const statusPageRouter = createTRPCRouter({
.query(async (opts) => {
if (!opts.input.slug) return null;
- const subscription = await getSubscriptionByToken(
- opts.input.token,
- opts.input.slug,
- );
+ const subscription = await getSubscriberByToken({
+ input: { token: opts.input.token, domain: opts.input.slug },
+ });
if (!subscription) {
throw new TRPCError({
@@ -1120,12 +1120,14 @@ export const statusPageRouter = createTRPCRouter({
if (!opts.input.slug) return null;
try {
- await updateSubscriptionScope({
- token: opts.input.token,
- componentIds: opts.input.subscribeComponents
- ? opts.input.pageComponents
- : [],
- domain: opts.input.slug,
+ await updateSubscriberScope({
+ input: {
+ token: opts.input.token,
+ componentIds: opts.input.subscribeComponents
+ ? opts.input.pageComponents
+ : [],
+ domain: opts.input.slug,
+ },
});
} catch (error) {
if (error instanceof Error) {
@@ -1188,10 +1190,9 @@ export const statusPageRouter = createTRPCRouter({
if (!opts.input.slug) return null;
try {
- const subscription = await verifySubscription(
- opts.input.token,
- opts.input.slug,
- );
+ const subscription = await verifySelfSignupSubscriber({
+ input: { token: opts.input.token, domain: opts.input.slug },
+ });
if (!subscription) {
throw new TRPCError({
@@ -1246,10 +1247,9 @@ export const statusPageRouter = createTRPCRouter({
getSubscriberByToken: publicProcedure
.input(z.object({ token: z.uuid(), domain: z.string().toLowerCase() }))
.query(async (opts) => {
- const subscription = await getSubscriptionByToken(
- opts.input.token,
- opts.input.domain,
- );
+ const subscription = await getSubscriberByToken({
+ input: { token: opts.input.token, domain: opts.input.domain },
+ });
if (
!subscription ||
@@ -1269,7 +1269,9 @@ export const statusPageRouter = createTRPCRouter({
.input(z.object({ token: z.uuid(), domain: z.string().toLowerCase() }))
.mutation(async (opts) => {
try {
- await unsubscribe(opts.input.token, opts.input.domain);
+ await unsubscribeSubscriber({
+ input: { token: opts.input.token, domain: opts.input.domain },
+ });
return { success: true };
} catch (error) {
if (error instanceof Error) {
diff --git a/packages/api/src/service-adapter.ts b/packages/api/src/service-adapter.ts
index 737e5fce9..e865d47be 100644
--- a/packages/api/src/service-adapter.ts
+++ b/packages/api/src/service-adapter.ts
@@ -76,10 +76,12 @@ export function toTRPCError(err: unknown): never {
});
}
}
- const message = err instanceof Error ? err.message : "Unknown error";
+ // Unknown errors: never surface raw `err.message` to clients — it can
+ // leak DB strings, stack-trace fragments, third-party SDK internals.
+ // Keep the original on `cause` for Sentry/log redaction.
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
- message,
+ message: "Internal server error",
cause: err,
});
}
diff --git a/packages/db/src/schema/audit_logs/validation.ts b/packages/db/src/schema/audit_logs/validation.ts
index 2cb074624..8220a2f00 100644
--- a/packages/db/src/schema/audit_logs/validation.ts
+++ b/packages/db/src/schema/audit_logs/validation.ts
@@ -77,6 +77,12 @@ const pageSubscriberActions = [
action("page_subscriber.create", "page_subscriber", intId, {
optionalMetadata: true,
}),
+ action("page_subscriber.update", "page_subscriber", intId, {
+ optionalMetadata: true,
+ }),
+ action("page_subscriber.delete", "page_subscriber", intId, {
+ optionalMetadata: true,
+ }),
] as const;
const apiKeyActions = [
@@ -131,6 +137,44 @@ const invitationActions = [
action("invitation.delete", "invitation", intId),
] as const;
+// Several entities below carry only a subset of the create/update/delete
+// triplet. This is intentional, not an oversight:
+// - `member`: rows are created via `invitation.accept`, not directly.
+// - `incident`: rows originate from the checker pipeline, not user
+// mutations.
+// When those write paths migrate to the service layer, add the missing
+// verbs alongside.
+const memberActions = [
+ // `entityId` is the removed user's id. Member rows have no surrogate key —
+ // they're (userId, workspaceId) composite — so the user id is the most
+ // useful identifier to fix on in the audit log.
+ action("member.delete", "member", intId),
+] as const;
+
+const integrationActions = [
+ action("integration.create", "integration", intId, {
+ optionalMetadata: true,
+ }),
+ action("integration.update", "integration", intId),
+ action("integration.delete", "integration", intId),
+] as const;
+
+const monitorTagActions = [
+ action("monitor_tag.create", "monitor_tag", intId, {
+ optionalMetadata: true,
+ }),
+ action("monitor_tag.update", "monitor_tag", intId),
+ action("monitor_tag.delete", "monitor_tag", intId),
+] as const;
+
+const privateLocationActions = [
+ action("private_location.create", "private_location", intId, {
+ optionalMetadata: true,
+ }),
+ action("private_location.update", "private_location", intId),
+ action("private_location.delete", "private_location", intId),
+] as const;
+
export const auditActionSchema = z.discriminatedUnion("action", [
...monitorActions,
...pageActions,
@@ -146,6 +190,10 @@ export const auditActionSchema = z.discriminatedUnion("action", [
...statusReportActions,
...statusReportUpdateActions,
...invitationActions,
+ ...memberActions,
+ ...integrationActions,
+ ...monitorTagActions,
+ ...privateLocationActions,
]);
/**
diff --git a/packages/db/src/schema/integration.ts b/packages/db/src/schema/integration.ts
index 3c3eacda5..39836a396 100644
--- a/packages/db/src/schema/integration.ts
+++ b/packages/db/src/schema/integration.ts
@@ -1,6 +1,7 @@
import { sql } from "drizzle-orm";
import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core";
-import { createInsertSchema } from "drizzle-zod";
+import { createInsertSchema, createSelectSchema } from "drizzle-zod";
+import type { z } from "zod";
import { workspace } from "./workspaces";
@@ -26,3 +27,6 @@ export const integration = sqliteTable("integration", {
});
export const insertIntegrationSchema = createInsertSchema(integration);
+export const selectIntegrationSchema = createSelectSchema(integration);
+
+export type Integration = z.infer<typeof selectIntegrationSchema>;
diff --git a/packages/services/package.json b/packages/services/package.json
index 1663836eb..a0201f894 100644
--- a/packages/services/package.json
+++ b/packages/services/package.json
@@ -60,6 +60,26 @@
"./audit": {
"import": "./src/audit/index.ts",
"types": "./src/audit/index.ts"
+ },
+ "./member": {
+ "import": "./src/member/index.ts",
+ "types": "./src/member/index.ts"
+ },
+ "./monitor-tag": {
+ "import": "./src/monitor-tag/index.ts",
+ "types": "./src/monitor-tag/index.ts"
+ },
+ "./integration": {
+ "import": "./src/integration/index.ts",
+ "types": "./src/integration/index.ts"
+ },
+ "./private-location": {
+ "import": "./src/private-location/index.ts",
+ "types": "./src/private-location/index.ts"
+ },
+ "./page-subscriber": {
+ "import": "./src/page-subscriber/index.ts",
+ "types": "./src/page-subscriber/index.ts"
}
},
"scripts": {
@@ -73,6 +93,7 @@
"@openstatus/regions": "workspace:*",
"@openstatus/subscriptions": "workspace:*",
"@openstatus/theme-store": "workspace:*",
+ "@openstatus/utils": "workspace:*",
"zod": "4.1.13"
},
"devDependencies": {
diff --git a/packages/services/src/__tests__/with-test-transaction.test.ts b/packages/services/src/__tests__/with-test-transaction.test.ts
new file mode 100644
index 000000000..782ed6605
--- /dev/null
+++ b/packages/services/src/__tests__/with-test-transaction.test.ts
@@ -0,0 +1,62 @@
+import { afterAll, describe, expect, test } from "bun:test";
+import { db, eq } from "@openstatus/db";
+import { auditLog } from "@openstatus/db/src/schema";
+
+import { SEEDED_WORKSPACE_TEAM_ID } from "../../test/fixtures";
+import { withTestTransaction } from "../../test/helpers";
+
+const SENTINEL_ENTITY_ID = `with-test-transaction-sanity-${Date.now()}`;
+
+describe("withTestTransaction", () => {
+ afterAll(async () => {
+ // Defensive: if the rollback failed, the inserted row would leak.
+ // Clean it up so a regression doesn't pollute future runs.
+ await db
+ .delete(auditLog)
+ .where(eq(auditLog.entityId, SENTINEL_ENTITY_ID))
+ .catch(() => undefined);
+ });
+
+ test("rolls back inserts so they never reach committed db", async () => {
+ let visibleInsideTx = false;
+
+ await withTestTransaction(async (tx) => {
+ await tx.insert(auditLog).values({
+ workspaceId: SEEDED_WORKSPACE_TEAM_ID,
+ actorType: "system",
+ actorId: "with-test-transaction-sanity",
+ action: "monitor.create",
+ entityType: "monitor",
+ entityId: SENTINEL_ENTITY_ID,
+ });
+
+ const inTxRows = await tx
+ .select()
+ .from(auditLog)
+ .where(eq(auditLog.entityId, SENTINEL_ENTITY_ID))
+ .all();
+ visibleInsideTx = inTxRows.length === 1;
+ });
+
+ expect(visibleInsideTx).toBe(true);
+
+ const committedRows = await db
+ .select()
+ .from(auditLog)
+ .where(eq(auditLog.entityId, SENTINEL_ENTITY_ID))
+ .all();
+ expect(committedRows).toHaveLength(0);
+ });
+
+ test("propagates non-sentinel errors thrown inside the callback", async () => {
+ const promise = withTestTransaction(async () => {
+ throw new Error("boom");
+ });
+ await expect(promise).rejects.toThrow("boom");
+ });
+
+ test("returns the callback's return value", async () => {
+ const value = await withTestTransaction(async () => 42);
+ expect(value).toBe(42);
+ });
+});
diff --git a/packages/services/src/api-key/__tests__/api-key.test.ts b/packages/services/src/api-key/__tests__/api-key.test.ts
index 59c7ccb98..e529ae12d 100644
--- a/packages/services/src/api-key/__tests__/api-key.test.ts
+++ b/packages/services/src/api-key/__tests__/api-key.test.ts
@@ -1,12 +1,5 @@
-import {
- afterAll,
- beforeAll,
- beforeEach,
- describe,
- expect,
- test,
-} from "bun:test";
-import { db, eq, inArray } from "@openstatus/db";
+import { beforeAll, describe, expect, test } from "bun:test";
+import { eq } from "@openstatus/db";
import { apiKey } from "@openstatus/db/src/schema";
import {
@@ -18,10 +11,10 @@ import {
} from "..";
import { SEEDED_WORKSPACE_TEAM_ID } from "../../../test/fixtures";
import {
- clearAuditLog,
expectAuditRow,
loadSeededWorkspace,
makeUserCtx,
+ withTestTransaction,
} from "../../../test/helpers";
import type { ServiceContext } from "../../context";
import { NotFoundError } from "../../errors";
@@ -29,156 +22,158 @@ import { NotFoundError } from "../../errors";
const TEST_PREFIX = "svc-apikey-test";
let teamCtx: ServiceContext;
-const createdKeyIds: number[] = [];
beforeAll(async () => {
const team = await loadSeededWorkspace(SEEDED_WORKSPACE_TEAM_ID);
teamCtx = makeUserCtx(team, { userId: 1 });
});
-afterAll(async () => {
- if (createdKeyIds.length > 0) {
- await db.delete(apiKey).where(inArray(apiKey.id, createdKeyIds));
- }
-});
-
-beforeEach(async () => {
- await clearAuditLog(teamCtx.workspace.id);
-});
-
describe("createApiKey", () => {
test("returns plaintext token once and stores a bcrypt hash", async () => {
- const { token, key } = await createApiKey({
- ctx: teamCtx,
- input: {
- name: `${TEST_PREFIX}-create`,
- },
- });
- createdKeyIds.push(key.id);
-
- expect(token).toMatch(/^os_[a-f0-9]{32}$/);
- expect(key.workspaceId).toBe(SEEDED_WORKSPACE_TEAM_ID);
-
- // `hashedToken` is stripped from the service response (see
- // `api-key/create.ts` — the caller only needs the plaintext
- // `token` once). Verify the bcrypt hash is actually persisted by
- // reading the row back from the db.
- const stored = await db
- .select({ hashedToken: apiKey.hashedToken })
- .from(apiKey)
- .where(eq(apiKey.id, key.id))
- .get();
- expect(stored?.hashedToken).toMatch(/^\$2[aby]\$/);
-
- await expectAuditRow({
- workspaceId: teamCtx.workspace.id,
- action: "api_key.create",
- entityType: "api_key",
- entityId: key.id,
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ const { token, key } = await createApiKey({
+ ctx,
+ input: { name: `${TEST_PREFIX}-create` },
+ });
+
+ expect(token).toMatch(/^os_[a-f0-9]{32}$/);
+ expect(key.workspaceId).toBe(SEEDED_WORKSPACE_TEAM_ID);
+
+ const stored = await tx
+ .select({ hashedToken: apiKey.hashedToken })
+ .from(apiKey)
+ .where(eq(apiKey.id, key.id))
+ .get();
+ expect(stored?.hashedToken).toMatch(/^\$2[aby]\$/);
+
+ await expectAuditRow({
+ workspaceId: ctx.workspace.id,
+ action: "api_key.create",
+ entityType: "api_key",
+ entityId: key.id,
+ db: tx,
+ });
});
});
});
describe("listApiKeys", () => {
test("enriches each key with creator info", async () => {
- const { key } = await createApiKey({
- ctx: teamCtx,
- input: { name: `${TEST_PREFIX}-list` },
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ const { key } = await createApiKey({
+ ctx,
+ input: { name: `${TEST_PREFIX}-list` },
+ });
+
+ const rows = await listApiKeys({ ctx });
+ const found = rows.find((r) => r.id === key.id);
+ expect(found).toBeDefined();
+ expect(found?.createdBy?.id).toBe(1);
});
- createdKeyIds.push(key.id);
-
- const rows = await listApiKeys({ ctx: teamCtx });
- const found = rows.find((r) => r.id === key.id);
- expect(found).toBeDefined();
- expect(found?.createdBy?.id).toBe(1);
});
});
describe("revokeApiKey", () => {
test("deletes the key and throws NotFoundError for unknown ids", async () => {
- const { key } = await createApiKey({
- ctx: teamCtx,
- input: { name: `${TEST_PREFIX}-revoke` },
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ const { key } = await createApiKey({
+ ctx,
+ input: { name: `${TEST_PREFIX}-revoke` },
+ });
+
+ await revokeApiKey({ ctx, input: { id: key.id } });
+
+ const row = await tx
+ .select({ id: apiKey.id })
+ .from(apiKey)
+ .where(eq(apiKey.id, key.id))
+ .get();
+ expect(row).toBeUndefined();
+
+ await expect(
+ revokeApiKey({ ctx, input: { id: 999_999_999 } }),
+ ).rejects.toBeInstanceOf(NotFoundError);
});
-
- await revokeApiKey({ ctx: teamCtx, input: { id: key.id } });
-
- const row = await db
- .select({ id: apiKey.id })
- .from(apiKey)
- .where(eq(apiKey.id, key.id))
- .get();
- expect(row).toBeUndefined();
-
- await expect(
- revokeApiKey({ ctx: teamCtx, input: { id: 999_999_999 } }),
- ).rejects.toBeInstanceOf(NotFoundError);
});
});
describe("verifyApiKey", () => {
test("resolves the stored row for a valid token", async () => {
- const { token, key } = await createApiKey({
- ctx: teamCtx,
- input: { name: `${TEST_PREFIX}-verify` },
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ const { token, key } = await createApiKey({
+ ctx,
+ input: { name: `${TEST_PREFIX}-verify` },
+ });
+
+ const row = await verifyApiKey({ token }, { db: tx });
+ expect(row?.id).toBe(key.id);
});
- createdKeyIds.push(key.id);
-
- const row = await verifyApiKey({ token });
- expect(row?.id).toBe(key.id);
});
test("returns null for malformed tokens", async () => {
- const row = await verifyApiKey({ token: "not-an-os-key" });
- expect(row).toBeNull();
+ await withTestTransaction(async (tx) => {
+ const row = await verifyApiKey({ token: "not-an-os-key" }, { db: tx });
+ expect(row).toBeNull();
+ });
});
test("returns null for a prefix-match with wrong body", async () => {
- const { token, key } = await createApiKey({
- ctx: teamCtx,
- input: { name: `${TEST_PREFIX}-verify-wrong` },
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ const { token } = await createApiKey({
+ ctx,
+ input: { name: `${TEST_PREFIX}-verify-wrong` },
+ });
+
+ const wrong = `${token.slice(0, 11)}${"f".repeat(24)}`;
+ const row = await verifyApiKey({ token: wrong }, { db: tx });
+ expect(row).toBeNull();
});
- createdKeyIds.push(key.id);
-
- // Swap the body after the prefix with another random hex sequence so
- // prefix hits but hash comparison fails.
- const wrong = `${token.slice(0, 11)}${"f".repeat(24)}`;
- const row = await verifyApiKey({ token: wrong });
- expect(row).toBeNull();
});
});
describe("updateApiKeyLastUsed", () => {
test("skips the write when lastUsedAt is recent", async () => {
- const { key } = await createApiKey({
- ctx: teamCtx,
- input: { name: `${TEST_PREFIX}-lastused` },
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ const { key } = await createApiKey({
+ ctx,
+ input: { name: `${TEST_PREFIX}-lastused` },
+ });
+
+ const now = new Date();
+ const wrote = await updateApiKeyLastUsed(
+ { id: key.id, lastUsedAt: now },
+ { db: tx },
+ );
+ expect(wrote).toBe(false);
});
- createdKeyIds.push(key.id);
-
- const now = new Date();
- const wrote = await updateApiKeyLastUsed({
- id: key.id,
- lastUsedAt: now,
- });
- expect(wrote).toBe(false);
});
test("writes when lastUsedAt is null or past the debounce window", async () => {
- const { key } = await createApiKey({
- ctx: teamCtx,
- input: { name: `${TEST_PREFIX}-lastused-null` },
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ const { key } = await createApiKey({
+ ctx,
+ input: { name: `${TEST_PREFIX}-lastused-null` },
+ });
+
+ const wrote = await updateApiKeyLastUsed(
+ { id: key.id, lastUsedAt: null },
+ { db: tx },
+ );
+ expect(wrote).toBe(true);
+
+ const row = await tx
+ .select({ lastUsedAt: apiKey.lastUsedAt })
+ .from(apiKey)
+ .where(eq(apiKey.id, key.id))
+ .get();
+ expect(row?.lastUsedAt).toBeInstanceOf(Date);
});
- createdKeyIds.push(key.id);
-
- const wrote = await updateApiKeyLastUsed({ id: key.id, lastUsedAt: null });
- expect(wrote).toBe(true);
-
- const row = await db
- .select({ lastUsedAt: apiKey.lastUsedAt })
- .from(apiKey)
- .where(eq(apiKey.id, key.id))
- .get();
- expect(row?.lastUsedAt).toBeInstanceOf(Date);
});
});
diff --git a/packages/services/src/audit/__tests__/audit.test.ts b/packages/services/src/audit/__tests__/audit.test.ts
index 29faea7c8..603f0b9bd 100644
--- a/packages/services/src/audit/__tests__/audit.test.ts
+++ b/packages/services/src/audit/__tests__/audit.test.ts
@@ -1,11 +1,4 @@
-import {
- afterAll,
- beforeAll,
- beforeEach,
- describe,
- expect,
- test,
-} from "bun:test";
+import { afterAll, beforeAll, describe, expect, test } from "bun:test";
import { db, eq } from "@openstatus/db";
import { auditLog } from "@openstatus/db/src/schema";
@@ -19,6 +12,7 @@ import {
makeSystemCtx,
makeUserCtx,
readAuditLog,
+ withTestTransaction,
} from "../../../test/helpers";
import type { ServiceContext } from "../../context";
@@ -45,9 +39,8 @@ let teamCtx: ServiceContext;
beforeAll(async () => {
const team = await loadSeededWorkspace(SEEDED_WORKSPACE_TEAM_ID);
teamCtx = makeUserCtx(team, { userId: 1 });
-});
-
-beforeEach(async () => {
+ // 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);
});
@@ -134,57 +127,63 @@ describe("diffTopLevel", () => {
describe("emitAudit — row persistence", () => {
test("inserts a row with the expected columns", async () => {
- await db.transaction(async (tx) => {
+ await withTestTransaction(async (tx) => {
await emitLoose(tx, teamCtx, {
action: "monitor.create",
entityType: "monitor",
entityId: 9001,
metadata: { jobType: "http", url: "https://example.com" },
});
- });
- const rows = await readAuditLog({
- workspaceId: teamCtx.workspace.id,
- entityType: "monitor",
- entityId: 9001,
- });
- expect(rows).toHaveLength(1);
- const row = rows[0];
- expect(row).toBeDefined();
- if (!row) throw new Error("unreachable");
- expect(row.workspaceId).toBe(teamCtx.workspace.id);
- expect(row.action).toBe("monitor.create");
- 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.metadata).toEqual({
- jobType: "http",
- url: "https://example.com",
+ const rows = await readAuditLog({
+ workspaceId: teamCtx.workspace.id,
+ entityType: "monitor",
+ entityId: 9001,
+ db: tx,
+ });
+ expect(rows).toHaveLength(1);
+ const row = rows[0];
+ expect(row).toBeDefined();
+ if (!row) throw new Error("unreachable");
+ expect(row.workspaceId).toBe(teamCtx.workspace.id);
+ expect(row.action).toBe("monitor.create");
+ 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.metadata).toEqual({
+ jobType: "http",
+ url: "https://example.com",
+ });
+ expect(row.before).toBeNull();
+ expect(row.after).toBeNull();
+ expect(row.changedFields).toBeNull();
+ expect(row.createdAt).toBeInstanceOf(Date);
});
- expect(row.before).toBeNull();
- expect(row.after).toBeNull();
- expect(row.changedFields).toBeNull();
- expect(row.createdAt).toBeInstanceOf(Date);
});
test("stringifies numeric entityIds", async () => {
- await db.transaction(async (tx) => {
+ await withTestTransaction(async (tx) => {
await emitLoose(tx, teamCtx, {
action: "page.delete",
entityType: "page",
entityId: 42,
});
+ const [row] = await readAuditLog({
+ workspaceId: teamCtx.workspace.id,
+ entityType: "page",
+ entityId: 42,
+ db: tx,
+ });
+ expect(row?.entityId).toBe("42");
});
- const [row] = await readAuditLog({
- workspaceId: teamCtx.workspace.id,
- entityType: "page",
- entityId: 42,
- });
- expect(row?.entityId).toBe("42");
});
+ // This test intentionally runs OUTSIDE `withTestTransaction`. Its whole
+ // point is to verify that a real outer transaction rolls back when an
+ // emit-bearing block throws — wrapping it in another tx would assert
+ // against the wrapping tx instead of the committed db.
test("fail-closed: insert error rolls the enclosing tx back", async () => {
let threw = false;
try {
@@ -211,41 +210,43 @@ describe("emitAudit — row persistence", () => {
describe("emitAudit — changed_fields derivation", () => {
test("null when only after is supplied (create-shape)", async () => {
- await db.transaction(async (tx) => {
+ await withTestTransaction(async (tx) => {
await emitAudit(tx, teamCtx, {
action: "monitor.create",
entityType: "monitor",
entityId: 9100,
after: { name: "fresh" },
});
+ const [row] = await readAuditLog({
+ workspaceId: teamCtx.workspace.id,
+ entityType: "monitor",
+ entityId: 9100,
+ db: tx,
+ });
+ expect(row?.changedFields).toBeNull();
});
- const [row] = await readAuditLog({
- workspaceId: teamCtx.workspace.id,
- entityType: "monitor",
- entityId: 9100,
- });
- expect(row?.changedFields).toBeNull();
});
test("null when only before is supplied (delete-shape)", async () => {
- await db.transaction(async (tx) => {
+ await withTestTransaction(async (tx) => {
await emitAudit(tx, teamCtx, {
action: "monitor.delete",
entityType: "monitor",
entityId: 9101,
before: { name: "going" },
});
+ const [row] = await readAuditLog({
+ workspaceId: teamCtx.workspace.id,
+ entityType: "monitor",
+ entityId: 9101,
+ db: tx,
+ });
+ expect(row?.changedFields).toBeNull();
});
- const [row] = await readAuditLog({
- workspaceId: teamCtx.workspace.id,
- entityType: "monitor",
- entityId: 9101,
- });
- expect(row?.changedFields).toBeNull();
});
test("no-op update (before === after) skips the insert entirely", async () => {
- await db.transaction(async (tx) => {
+ await withTestTransaction(async (tx) => {
await emitAudit(tx, teamCtx, {
action: "monitor.update",
entityType: "monitor",
@@ -253,17 +254,18 @@ describe("emitAudit — changed_fields derivation", () => {
before: { name: "same", url: "https://x" },
after: { name: "same", url: "https://x" },
});
+ const rows = await readAuditLog({
+ workspaceId: teamCtx.workspace.id,
+ entityType: "monitor",
+ entityId: 9102,
+ db: tx,
+ });
+ expect(rows).toHaveLength(0);
});
- const rows = await readAuditLog({
- workspaceId: teamCtx.workspace.id,
- entityType: "monitor",
- entityId: 9102,
- });
- expect(rows).toHaveLength(0);
});
test("ignoring updatedAt/createdAt only → still a no-op, still skipped", async () => {
- await db.transaction(async (tx) => {
+ await withTestTransaction(async (tx) => {
await emitAudit(tx, teamCtx, {
action: "monitor.update",
entityType: "monitor",
@@ -271,17 +273,43 @@ describe("emitAudit — changed_fields derivation", () => {
before: { name: "a", updatedAt: new Date("2025-01-01") },
after: { name: "a", updatedAt: new Date("2025-06-01") },
});
+ const rows = await readAuditLog({
+ workspaceId: teamCtx.workspace.id,
+ entityType: "monitor",
+ entityId: 9105,
+ db: tx,
+ });
+ expect(rows).toHaveLength(0);
});
- const rows = await readAuditLog({
- workspaceId: teamCtx.workspace.id,
- entityType: "monitor",
- entityId: 9105,
+ });
+
+ test("metadata-only update with empty row diff still lands", async () => {
+ // Off-row mutations (e.g. component-scope edits on `page_subscriber`)
+ // change a join table, not the row itself — `before === after` for
+ // every column. The metadata is the signal, so the row must land.
+ await withTestTransaction(async (tx) => {
+ await emitLoose(tx, teamCtx, {
+ action: "page_subscriber.update",
+ entityType: "page_subscriber",
+ entityId: 9106,
+ before: { name: "same" },
+ after: { name: "same" },
+ metadata: { componentIds: [1, 2] },
+ });
+ const rows = await readAuditLog({
+ workspaceId: teamCtx.workspace.id,
+ entityType: "page_subscriber",
+ entityId: 9106,
+ db: tx,
+ });
+ expect(rows).toHaveLength(1);
+ expect(rows[0]?.changedFields).toEqual([]);
+ expect(rows[0]?.metadata).toEqual({ componentIds: [1, 2] });
});
- expect(rows).toHaveLength(0);
});
test("populated with the changed top-level keys", async () => {
- await db.transaction(async (tx) => {
+ await withTestTransaction(async (tx) => {
await emitAudit(tx, teamCtx, {
action: "monitor.update",
entityType: "monitor",
@@ -289,17 +317,18 @@ describe("emitAudit — changed_fields derivation", () => {
before: { name: "old", url: "https://a", method: "GET" },
after: { name: "new", url: "https://b", method: "GET" },
});
+ const [row] = await readAuditLog({
+ workspaceId: teamCtx.workspace.id,
+ entityType: "monitor",
+ entityId: 9103,
+ db: tx,
+ });
+ expect(row?.changedFields?.sort()).toEqual(["name", "url"]);
});
- const [row] = await readAuditLog({
- workspaceId: teamCtx.workspace.id,
- entityType: "monitor",
- entityId: 9103,
- });
- expect(row?.changedFields?.sort()).toEqual(["name", "url"]);
});
test("ignores updatedAt when computing the diff — a real change still records only the real key", async () => {
- await db.transaction(async (tx) => {
+ await withTestTransaction(async (tx) => {
await emitAudit(tx, teamCtx, {
action: "monitor.update",
entityType: "monitor",
@@ -307,121 +336,127 @@ describe("emitAudit — changed_fields derivation", () => {
before: { name: "old", updatedAt: new Date("2025-01-01") },
after: { name: "new", updatedAt: new Date("2025-06-01") },
});
+ const [row] = await readAuditLog({
+ workspaceId: teamCtx.workspace.id,
+ entityType: "monitor",
+ entityId: 9104,
+ db: tx,
+ });
+ expect(row?.changedFields).toEqual(["name"]);
});
- const [row] = await readAuditLog({
- workspaceId: teamCtx.workspace.id,
- entityType: "monitor",
- entityId: 9104,
- });
- expect(row?.changedFields).toEqual(["name"]);
});
});
describe("emitAudit — actor derivation", () => {
test("user actor → actorId and actorUserId are the same id", async () => {
- await db.transaction(async (tx) => {
+ await withTestTransaction(async (tx) => {
await emitLoose(tx, teamCtx, {
action: "workspace.update",
entityType: "workspace",
entityId: teamCtx.workspace.id,
});
+ const [row] = await readAuditLog({
+ workspaceId: teamCtx.workspace.id,
+ entityType: "workspace",
+ db: tx,
+ });
+ expect(row?.actorType).toBe("user");
+ expect(row?.actorId).toBe("1");
+ expect(row?.actorUserId).toBe(1);
});
- const [row] = await readAuditLog({
- workspaceId: teamCtx.workspace.id,
- entityType: "workspace",
- });
- expect(row?.actorType).toBe("user");
- expect(row?.actorId).toBe("1");
- expect(row?.actorUserId).toBe(1);
});
test("apiKey actor without linked user → actorUserId null", async () => {
- const ctx = makeApiKeyCtx(teamCtx.workspace, { keyId: "k_anon" });
- await db.transaction(async (tx) => {
+ await withTestTransaction(async (tx) => {
+ const ctx = makeApiKeyCtx(teamCtx.workspace, { keyId: "k_anon" });
await emitLoose(tx, ctx, {
action: "api_key.delete",
entityType: "api_key",
entityId: 9200,
});
+ const [row] = await readAuditLog({
+ workspaceId: teamCtx.workspace.id,
+ entityType: "api_key",
+ entityId: 9200,
+ db: tx,
+ });
+ expect(row?.actorType).toBe("apiKey");
+ expect(row?.actorId).toBe("k_anon");
+ expect(row?.actorUserId).toBeNull();
});
- const [row] = await readAuditLog({
- workspaceId: teamCtx.workspace.id,
- entityType: "api_key",
- entityId: 9200,
- });
- expect(row?.actorType).toBe("apiKey");
- expect(row?.actorId).toBe("k_anon");
- expect(row?.actorUserId).toBeNull();
});
test("apiKey actor with linked user → actorUserId populated", async () => {
- const ctx = makeApiKeyCtx(teamCtx.workspace, {
- keyId: "k_linked",
- userId: 42,
- });
- await db.transaction(async (tx) => {
+ await withTestTransaction(async (tx) => {
+ const ctx = makeApiKeyCtx(teamCtx.workspace, {
+ keyId: "k_linked",
+ userId: 42,
+ });
await emitLoose(tx, ctx, {
action: "api_key.delete",
entityType: "api_key",
entityId: 9201,
});
+ const [row] = await readAuditLog({
+ workspaceId: teamCtx.workspace.id,
+ entityType: "api_key",
+ entityId: 9201,
+ db: tx,
+ });
+ expect(row?.actorType).toBe("apiKey");
+ expect(row?.actorId).toBe("k_linked");
+ expect(row?.actorUserId).toBe(42);
});
- const [row] = await readAuditLog({
- workspaceId: teamCtx.workspace.id,
- entityType: "api_key",
- entityId: 9201,
- });
- expect(row?.actorType).toBe("apiKey");
- expect(row?.actorId).toBe("k_linked");
- expect(row?.actorUserId).toBe(42);
});
test("slack actor → actorId is slackUserId", async () => {
- const ctx = makeSlackCtx(teamCtx.workspace, {
- teamId: "T1",
- slackUserId: "U9",
- userId: 7,
- });
- await db.transaction(async (tx) => {
+ await withTestTransaction(async (tx) => {
+ const ctx = makeSlackCtx(teamCtx.workspace, {
+ teamId: "T1",
+ slackUserId: "U9",
+ userId: 7,
+ });
await emitLoose(tx, ctx, {
action: "maintenance.update",
entityType: "maintenance",
entityId: 9300,
});
+ const [row] = await readAuditLog({
+ workspaceId: teamCtx.workspace.id,
+ entityType: "maintenance",
+ entityId: 9300,
+ db: tx,
+ });
+ expect(row?.actorType).toBe("slack");
+ expect(row?.actorId).toBe("U9");
+ expect(row?.actorUserId).toBe(7);
});
- const [row] = await readAuditLog({
- workspaceId: teamCtx.workspace.id,
- entityType: "maintenance",
- entityId: 9300,
- });
- expect(row?.actorType).toBe("slack");
- expect(row?.actorId).toBe("U9");
- expect(row?.actorUserId).toBe(7);
});
test("system actor → actorId is the job name, actorUserId null", async () => {
- const ctx = makeSystemCtx(teamCtx.workspace, { job: "cleanup-job" });
- await db.transaction(async (tx) => {
+ await withTestTransaction(async (tx) => {
+ const ctx = makeSystemCtx(teamCtx.workspace, { job: "cleanup-job" });
await emitLoose(tx, ctx, {
action: "monitor.delete",
entityType: "monitor",
entityId: 9400,
});
+ const [row] = await readAuditLog({
+ workspaceId: teamCtx.workspace.id,
+ entityType: "monitor",
+ entityId: 9400,
+ db: tx,
+ });
+ expect(row?.actorType).toBe("system");
+ expect(row?.actorId).toBe("cleanup-job");
+ expect(row?.actorUserId).toBeNull();
});
- const [row] = await readAuditLog({
- workspaceId: teamCtx.workspace.id,
- entityType: "monitor",
- entityId: 9400,
- });
- expect(row?.actorType).toBe("system");
- expect(row?.actorId).toBe("cleanup-job");
- expect(row?.actorUserId).toBeNull();
});
});
describe("emitAudit — ordering", () => {
test("autoincrement id provides a stable tiebreaker within the same ms", async () => {
- await db.transaction(async (tx) => {
+ await withTestTransaction(async (tx) => {
for (let i = 0; i < 5; i++) {
await emitLoose(tx, teamCtx, {
action: "monitor.update",
@@ -429,51 +464,57 @@ describe("emitAudit — ordering", () => {
entityId: 9500 + i,
});
}
+ const rows = await tx
+ .select()
+ .from(auditLog)
+ .where(eq(auditLog.workspaceId, teamCtx.workspace.id))
+ .orderBy(auditLog.id)
+ .all();
+ const emitted = rows.filter(
+ (r) =>
+ r.action === "monitor.update" &&
+ Number(r.entityId) >= 9500 &&
+ Number(r.entityId) < 9505,
+ );
+ expect(emitted).toHaveLength(5);
+ const ids = emitted.map((r) => Number(r.entityId));
+ expect(ids).toEqual([9500, 9501, 9502, 9503, 9504]);
+ // Ids are monotonically increasing → reads ordered by (createdAt DESC, id DESC)
+ // get a deterministic order even when createdAt collides.
+ for (let i = 1; i < emitted.length; i++) {
+ const prev = emitted[i - 1];
+ const curr = emitted[i];
+ if (!prev || !curr) throw new Error("unreachable");
+ expect(curr.id).toBeGreaterThan(prev.id);
+ }
});
- const rows = await db
- .select()
- .from(auditLog)
- .where(eq(auditLog.workspaceId, teamCtx.workspace.id))
- .orderBy(auditLog.id)
- .all();
- const emitted = rows.filter((r) => r.action === "monitor.update");
- expect(emitted).toHaveLength(5);
- const ids = emitted.map((r) => Number(r.entityId));
- expect(ids).toEqual([9500, 9501, 9502, 9503, 9504]);
- // Ids are monotonically increasing → reads ordered by (createdAt DESC, id DESC)
- // get a deterministic order even when createdAt collides.
- for (let i = 1; i < emitted.length; i++) {
- const prev = emitted[i - 1];
- const curr = emitted[i];
- if (!prev || !curr) throw new Error("unreachable");
- expect(curr.id).toBeGreaterThan(prev.id);
- }
});
});
describe("emitAudit — entry-shape regressions", () => {
test("entry without metadata serializes null to the metadata column", async () => {
- await db.transaction(async (tx) => {
+ await withTestTransaction(async (tx) => {
await emitLoose(tx, teamCtx, {
action: "monitor.update",
entityType: "monitor",
entityId: 9600,
});
+ const [row] = await readAuditLog({
+ workspaceId: teamCtx.workspace.id,
+ entityType: "monitor",
+ entityId: 9600,
+ db: tx,
+ });
+ expect(row?.metadata).toBeNull();
});
- const [row] = await readAuditLog({
- workspaceId: teamCtx.workspace.id,
- entityType: "monitor",
- entityId: 9600,
- });
- expect(row?.metadata).toBeNull();
});
});
describe("emitAudit — runtime Zod validation", () => {
test("rejects an unknown action string", async () => {
- let threw = false;
- try {
- await db.transaction(async (tx) => {
+ await withTestTransaction(async (tx) => {
+ let threw = false;
+ try {
await emitAudit(tx, teamCtx, {
// Cast through unknown — the runtime check is exactly the
// point being tested; at compile time this would be a TS error.
@@ -481,23 +522,24 @@ describe("emitAudit — runtime Zod validation", () => {
entityType: "monitor",
entityId: 9700,
} as unknown as AuditEntry);
+ } catch {
+ threw = true;
+ }
+ expect(threw).toBe(true);
+ const rows = await readAuditLog({
+ workspaceId: teamCtx.workspace.id,
+ entityType: "monitor",
+ entityId: 9700,
+ db: tx,
});
- } catch {
- threw = true;
- }
- expect(threw).toBe(true);
- const rows = await readAuditLog({
- workspaceId: teamCtx.workspace.id,
- entityType: "monitor",
- entityId: 9700,
+ expect(rows).toHaveLength(0);
});
- expect(rows).toHaveLength(0);
});
test("rejects a mismatched entityType for a known action", async () => {
- let threw = false;
- try {
- await db.transaction(async (tx) => {
+ await withTestTransaction(async (tx) => {
+ let threw = false;
+ try {
await emitAudit(tx, teamCtx, {
action: "monitor.create",
// `monitor.create` is bound to entityType: "monitor"; this should
@@ -505,27 +547,27 @@ describe("emitAudit — runtime Zod validation", () => {
entityType: "page",
entityId: 9701,
} as unknown as AuditEntry);
- });
- } catch {
- threw = true;
- }
- expect(threw).toBe(true);
+ } catch {
+ threw = true;
+ }
+ expect(threw).toBe(true);
+ });
});
test("rejects a non-integer entityId", async () => {
- let threw = false;
- try {
- await db.transaction(async (tx) => {
+ await withTestTransaction(async (tx) => {
+ let threw = false;
+ try {
await emitAudit(tx, teamCtx, {
action: "monitor.delete",
entityType: "monitor",
// The schema requires `intId`; floats should fail.
entityId: 1.5,
} as unknown as AuditEntry);
- });
- } catch {
- threw = true;
- }
- expect(threw).toBe(true);
+ } catch {
+ threw = true;
+ }
+ expect(threw).toBe(true);
+ });
});
});
diff --git a/packages/services/src/audit/emit.ts b/packages/services/src/audit/emit.ts
index a4caf57a2..4d8bec3c5 100644
--- a/packages/services/src/audit/emit.ts
+++ b/packages/services/src/audit/emit.ts
@@ -119,9 +119,17 @@ export async function emitAudit(
// Skip the insert — an empty-diff row has no informational value
// (the action name alone doesn't tell us what the user tried to
// change, and `before === after` duplicates the live entity state).
- // Creates / deletes / metadata-only updates still land because
- // `changedFields` is `null` in those cases, not `[]`.
- if (changedFields !== null && changedFields.length === 0) return;
+ // Exception: when `metadata` is present, the change lives outside
+ // the row (e.g. component-scope edits on `page_subscriber` mutate
+ // a join table, not the row itself). The metadata is the signal,
+ // so the row still lands. Pure no-ops (no diff, no metadata) drop.
+ if (
+ changedFields !== null &&
+ changedFields.length === 0 &&
+ metadata === undefined
+ ) {
+ return;
+ }
const row = {
workspaceId: ctx.workspace.id,
diff --git a/packages/services/src/audit/list.ts b/packages/services/src/audit/list.ts
index a7d707182..32ddd4d64 100644
--- a/packages/services/src/audit/list.ts
+++ b/packages/services/src/audit/list.ts
@@ -1,16 +1,12 @@
+import { type SQL, and, desc, eq, gte, isNull, sql } from "@openstatus/db";
import {
- type SQL,
- and,
- db as defaultDb,
- desc,
- eq,
- gte,
- isNull,
- sql,
-} from "@openstatus/db";
-import { auditLog, user } from "@openstatus/db/src/schema";
+ auditLog,
+ selectAuditLogSchema,
+ user,
+} from "@openstatus/db/src/schema";
+import type { z } from "zod";
-import type { ServiceContext } from "../context";
+import { type ServiceContext, getReadDb } from "../context";
import { ListAuditLogsInput } from "./schemas";
/**
@@ -22,7 +18,7 @@ import { ListAuditLogsInput } from "./schemas";
*/
const READ_WINDOW_DAYS = 14;
-export type AuditLogListItem = typeof auditLog.$inferSelect & {
+export type AuditLogListItem = z.infer<typeof selectAuditLogSchema> & {
user: {
id: number;
name: string | null;
@@ -55,7 +51,7 @@ export async function listAuditLogs(args: {
}): Promise<ListAuditLogsResult> {
const { ctx } = args;
const input = ListAuditLogsInput.parse(args.input);
- const db = ctx.db ?? defaultDb;
+ const db = getReadDb(ctx);
const since = new Date(Date.now() - READ_WINDOW_DAYS * 24 * 60 * 60 * 1000);
@@ -108,7 +104,7 @@ export async function listAuditLogs(args: {
]);
const items = rows.map((row) => ({
- ...row.auditLog,
+ ...selectAuditLogSchema.parse(row.auditLog),
user: row.user?.id != null ? row.user : null,
}));
return { items, totalSize: countRow?.count ?? 0 };
diff --git a/packages/services/src/context.ts b/packages/services/src/context.ts
index 631bd612e..b3f73f4c3 100644
--- a/packages/services/src/context.ts
+++ b/packages/services/src/context.ts
@@ -14,7 +14,8 @@ export type Actor =
| { type: "apiKey"; keyId: string; userId?: number }
| { type: "slack"; teamId: string; slackUserId: string; userId?: number }
| { type: "system"; job: string }
- | { type: "webhook"; source: string; externalId?: string };
+ | { type: "webhook"; source: string; externalId?: string }
+ | { type: "subscriber"; subscriberId: number };
export type ServiceContext = {
workspace: Workspace;
@@ -40,6 +41,17 @@ export async function withTransaction<T>(
return (db as DrizzleClient).transaction(fn);
}
+/**
+ * Read-side DB resolver for list / get verbs. Use the caller's tx if one
+ * was threaded through `ctx.db` (so reads observe in-flight writes), else
+ * fall back to the default client. Equivalent to the inlined
+ * `ctx.db ?? defaultDb` pattern, kept as a helper so service files don't
+ * import `defaultDb` just to write the same expression.
+ */
+export function getReadDb(ctx: ServiceContext): DB {
+ return ctx.db ?? defaultDb;
+}
+
export function extractActorId(actor: Actor): string {
switch (actor.type) {
case "user":
@@ -52,6 +64,8 @@ export function extractActorId(actor: Actor): string {
return actor.job;
case "webhook":
return actor.externalId ?? actor.source;
+ case "subscriber":
+ return String(actor.subscriberId);
}
}
@@ -70,6 +84,7 @@ export function tryGetActorUserId(actor: Actor): number | null {
return actor.userId ?? null;
case "system":
case "webhook":
+ case "subscriber":
return null;
}
}
diff --git a/packages/services/src/errors.ts b/packages/services/src/errors.ts
index ca1e8d9d7..1c904422e 100644
--- a/packages/services/src/errors.ts
+++ b/packages/services/src/errors.ts
@@ -20,8 +20,11 @@ export class ServiceError extends Error {
}
export class NotFoundError extends ServiceError {
- constructor(entity: string, id: string | number) {
- super("NOT_FOUND", `${entity} ${id} not found`);
+ constructor(entity: string, id?: string | number) {
+ super(
+ "NOT_FOUND",
+ id !== undefined ? `${entity} ${id} not found` : `${entity} not found`,
+ );
}
}
diff --git a/packages/services/src/import/__tests__/unit.test.ts b/packages/services/src/import/__tests__/unit.test.ts
index 699f8db26..ab4ae5c2d 100644
--- a/packages/services/src/import/__tests__/unit.test.ts
+++ b/packages/services/src/import/__tests__/unit.test.ts
@@ -1,8 +1,11 @@
-import { describe, expect, test } from "bun:test";
+import { beforeAll, describe, expect, test } from "bun:test";
+import { db, eq } from "@openstatus/db";
+import { monitor, pageComponent } 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 type { ImportSummary } from "@openstatus/importers";
import { addLimitWarnings, clampPeriodicity, computePhaseStatus } from "../";
+import { withTestTransaction } from "../../../test/helpers";
function makeSummary(overrides?: Partial<ImportSummary>): ImportSummary {
return {
@@ -20,118 +23,322 @@ function makeLimits(overrides?: Partial<Limits>): Limits {
return { ...allPlans.free.limits, ...overrides };
}
+// `addLimitWarnings` issues real `count(*)` queries against
+// `pageComponent` and `monitor`. The expectations below assume an empty
+// workspace, so wipe rows other suites' `beforeAll` blocks may have
+// committed in workspace 2 once before any test runs. Per-test writes
+// from this file all live inside `withTestTransaction` and roll back.
+const TEST_WORKSPACE_ID = 2;
+
describe("addLimitWarnings", () => {
+ beforeAll(async () => {
+ await db
+ .delete(pageComponent)
+ .where(eq(pageComponent.workspaceId, TEST_WORKSPACE_ID));
+ await db.delete(monitor).where(eq(monitor.workspaceId, TEST_WORKSPACE_ID));
+ });
+
// -------------------------------------------------------------------------
// Component limits
// -------------------------------------------------------------------------
describe("component limits", () => {
test("no warning when under limit", async () => {
- const summary = makeSummary({
- phases: [
- {
- phase: "components",
- status: "completed",
- resources: [
- { sourceId: "1", name: "A", status: "created" },
- { sourceId: "2", name: "B", status: "created" },
- ],
- },
- ],
- });
+ await withTestTransaction(async (tx) => {
+ const summary = makeSummary({
+ phases: [
+ {
+ phase: "components",
+ status: "completed",
+ resources: [
+ { sourceId: "1", name: "A", status: "created" },
+ { sourceId: "2", name: "B", status: "created" },
+ ],
+ },
+ ],
+ });
- await addLimitWarnings(summary, {
- limits: makeLimits({ "page-components": 20 }),
- workspaceId: 2,
- });
+ await addLimitWarnings(summary, {
+ limits: makeLimits({ "page-components": 20 }),
+ workspaceId: 2,
+ db: tx,
+ });
- expect(summary.errors).toEqual([]);
+ expect(summary.errors).toEqual([]);
+ });
});
test("no warning when exactly at limit", async () => {
- const summary = makeSummary({
- phases: [
- {
- phase: "components",
- status: "completed",
- resources: [
- { sourceId: "1", name: "A", status: "created" },
- { sourceId: "2", name: "B", status: "created" },
- { sourceId: "3", name: "C", status: "created" },
- ],
- },
- ],
- });
+ await withTestTransaction(async (tx) => {
+ const summary = makeSummary({
+ phases: [
+ {
+ phase: "components",
+ status: "completed",
+ resources: [
+ { sourceId: "1", name: "A", status: "created" },
+ { sourceId: "2", name: "B", status: "created" },
+ { sourceId: "3", name: "C", status: "created" },
+ ],
+ },
+ ],
+ });
- await addLimitWarnings(summary, {
- limits: makeLimits({ "page-components": 3 }),
- workspaceId: 2,
- });
+ await addLimitWarnings(summary, {
+ limits: makeLimits({ "page-components": 3 }),
+ workspaceId: 2,
+ db: tx,
+ });
- expect(summary.errors).toEqual([]);
+ expect(summary.errors).toEqual([]);
+ });
});
test("warns when import exceeds limit (no existing components)", async () => {
- const summary = makeSummary({
- phases: [
- {
- phase: "components",
- status: "completed",
- resources: [
- { sourceId: "1", name: "A", status: "created" },
- { sourceId: "2", name: "B", status: "created" },
- { sourceId: "3", name: "C", status: "created" },
- { sourceId: "4", name: "D", status: "created" },
- ],
- },
- ],
+ await withTestTransaction(async (tx) => {
+ const summary = makeSummary({
+ phases: [
+ {
+ phase: "components",
+ status: "completed",
+ resources: [
+ { sourceId: "1", name: "A", status: "created" },
+ { sourceId: "2", name: "B", status: "created" },
+ { sourceId: "3", name: "C", status: "created" },
+ { sourceId: "4", name: "D", status: "created" },
+ ],
+ },
+ ],
+ });
+
+ await addLimitWarnings(summary, {
+ limits: makeLimits({ "page-components": 3 }),
+ workspaceId: 2,
+ db: tx,
+ });
+
+ expect(summary.errors.length).toBe(1);
+ // Wording: "Only 3 new components may be created … 4 in the import".
+ // Both numbers land in the message — assert on the salient
+ // fragments instead of the exact string so future phrasing tweaks
+ // don't churn the assertion.
+ expect(summary.errors[0]).toContain("3 new component");
+ expect(summary.errors[0]).toContain("4 in the import");
});
+ });
- await addLimitWarnings(summary, {
- limits: makeLimits({ "page-components": 3 }),
- workspaceId: 2,
+ test("no warning when components phase is empty", async () => {
+ await withTestTransaction(async (tx) => {
+ const summary = makeSummary({
+ phases: [{ phase: "components", status: "completed", resources: [] }],
+ });
+
+ await addLimitWarnings(summary, {
+ limits: makeLimits({ "page-components": 3 }),
+ workspaceId: 2,
+ db: tx,
+ });
+
+ expect(summary.errors).toEqual([]);
});
+ });
- expect(summary.errors.length).toBe(1);
- // Wording: "Only 3 new components may be created … 4 in the import".
- // Both numbers land in the message — assert on the salient
- // fragments instead of the exact string so future phrasing tweaks
- // don't churn the assertion.
- expect(summary.errors[0]).toContain("3 new component");
- expect(summary.errors[0]).toContain("4 in the import");
+ test("no warning when components phase is missing", async () => {
+ await withTestTransaction(async (tx) => {
+ const summary = makeSummary({
+ phases: [{ phase: "page", status: "completed", resources: [] }],
+ });
+
+ await addLimitWarnings(summary, {
+ limits: makeLimits({ "page-components": 3 }),
+ workspaceId: 2,
+ db: tx,
+ });
+
+ expect(summary.errors).toEqual([]);
+ });
});
+ });
- test("no warning when components phase is empty", async () => {
- const summary = makeSummary({
- phases: [{ phase: "components", status: "completed", resources: [] }],
+ // -------------------------------------------------------------------------
+ // Custom domain
+ // -------------------------------------------------------------------------
+ describe("custom domain", () => {
+ test("warns when custom domain present on free plan", async () => {
+ await withTestTransaction(async (tx) => {
+ const summary = makeSummary({
+ phases: [
+ {
+ phase: "page",
+ status: "completed",
+ resources: [
+ {
+ sourceId: "p1",
+ name: "My Page",
+ status: "created",
+ data: { customDomain: "status.example.com" },
+ },
+ ],
+ },
+ ],
+ });
+
+ await addLimitWarnings(summary, {
+ limits: makeLimits({ "custom-domain": false }),
+ workspaceId: 2,
+ db: tx,
+ });
+
+ expect(summary.errors.length).toBe(1);
+ expect(summary.errors[0]).toContain("Custom domain");
});
+ });
- await addLimitWarnings(summary, {
- limits: makeLimits({ "page-components": 3 }),
- workspaceId: 2,
+ test("no warning when custom domain is empty", async () => {
+ await withTestTransaction(async (tx) => {
+ const summary = makeSummary({
+ phases: [
+ {
+ phase: "page",
+ status: "completed",
+ resources: [
+ {
+ sourceId: "p1",
+ name: "My Page",
+ status: "created",
+ data: { customDomain: "" },
+ },
+ ],
+ },
+ ],
+ });
+
+ await addLimitWarnings(summary, {
+ limits: makeLimits({ "custom-domain": false }),
+ workspaceId: 2,
+ db: tx,
+ });
+
+ expect(summary.errors).toEqual([]);
});
+ });
- expect(summary.errors).toEqual([]);
+ test("no warning on paid plan with custom domain", async () => {
+ await withTestTransaction(async (tx) => {
+ const summary = makeSummary({
+ phases: [
+ {
+ phase: "page",
+ status: "completed",
+ resources: [
+ {
+ sourceId: "p1",
+ name: "My Page",
+ status: "created",
+ data: { customDomain: "status.example.com" },
+ },
+ ],
+ },
+ ],
+ });
+
+ await addLimitWarnings(summary, {
+ limits: makeLimits({ "custom-domain": true }),
+ workspaceId: 2,
+ db: tx,
+ });
+
+ expect(summary.errors).toEqual([]);
+ });
});
+ });
- test("no warning when components phase is missing", async () => {
- const summary = makeSummary({
- phases: [{ phase: "page", status: "completed", resources: [] }],
+ // -------------------------------------------------------------------------
+ // Subscribers
+ // -------------------------------------------------------------------------
+ describe("subscribers", () => {
+ test("warns when subscribers present on free plan", async () => {
+ await withTestTransaction(async (tx) => {
+ const summary = makeSummary({
+ phases: [
+ {
+ phase: "subscribers",
+ status: "completed",
+ resources: [
+ { sourceId: "s1", name: "[email protected]", status: "created" },
+ { sourceId: "s2", name: "[email protected]", status: "created" },
+ ],
+ },
+ ],
+ });
+
+ // `addLimitWarnings` gates subscribers warnings on
+ // `options.includeSubscribers` (Cubic P2 — otherwise users who
+ // aren't importing subscribers get a noise warning). Default
+ // matches `ImportOptions` (`false`), so the warning only fires
+ // when the caller explicitly opts in. Tests that want to exercise
+ // the warning pass `options.includeSubscribers: true`.
+ await addLimitWarnings(summary, {
+ limits: makeLimits({ "status-subscribers": false }),
+ workspaceId: 2,
+ db: tx,
+ options: { includeSubscribers: true },
+ });
+
+ expect(summary.errors.length).toBe(1);
+ expect(summary.errors[0]).toContain("Subscribers");
});
+ });
- await addLimitWarnings(summary, {
- limits: makeLimits({ "page-components": 3 }),
- workspaceId: 2,
+ test("no warning when subscribers phase is empty", async () => {
+ await withTestTransaction(async (tx) => {
+ const summary = makeSummary({
+ phases: [
+ { phase: "subscribers", status: "completed", resources: [] },
+ ],
+ });
+
+ await addLimitWarnings(summary, {
+ limits: makeLimits({ "status-subscribers": false }),
+ workspaceId: 2,
+ db: tx,
+ options: { includeSubscribers: true },
+ });
+
+ expect(summary.errors).toEqual([]);
});
+ });
- expect(summary.errors).toEqual([]);
+ test("no warning on paid plan with subscribers", async () => {
+ await withTestTransaction(async (tx) => {
+ const summary = makeSummary({
+ phases: [
+ {
+ phase: "subscribers",
+ status: "completed",
+ resources: [
+ { sourceId: "s1", name: "[email protected]", status: "created" },
+ ],
+ },
+ ],
+ });
+
+ await addLimitWarnings(summary, {
+ limits: makeLimits({ "status-subscribers": true }),
+ workspaceId: 2,
+ db: tx,
+ options: { includeSubscribers: true },
+ });
+
+ expect(summary.errors).toEqual([]);
+ });
});
});
// -------------------------------------------------------------------------
- // Custom domain
+ // Combined
// -------------------------------------------------------------------------
- describe("custom domain", () => {
- test("warns when custom domain present on free plan", async () => {
+ test("reports multiple warnings at once", async () => {
+ await withTestTransaction(async (tx) => {
const summary = makeSummary({
phases: [
{
@@ -140,51 +347,55 @@ describe("addLimitWarnings", () => {
resources: [
{
sourceId: "p1",
- name: "My Page",
+ name: "Page",
status: "created",
data: { customDomain: "status.example.com" },
},
],
},
- ],
- });
-
- await addLimitWarnings(summary, {
- limits: makeLimits({ "custom-domain": false }),
- workspaceId: 2,
- });
-
- expect(summary.errors.length).toBe(1);
- expect(summary.errors[0]).toContain("Custom domain");
- });
-
- test("no warning when custom domain is empty", async () => {
- const summary = makeSummary({
- phases: [
{
- phase: "page",
+ phase: "components",
status: "completed",
resources: [
- {
- sourceId: "p1",
- name: "My Page",
- status: "created",
- data: { customDomain: "" },
- },
+ { sourceId: "1", name: "A", status: "created" },
+ { sourceId: "2", name: "B", status: "created" },
+ { sourceId: "3", name: "C", status: "created" },
+ { sourceId: "4", name: "D", status: "created" },
+ ],
+ },
+ {
+ phase: "subscribers",
+ status: "completed",
+ resources: [
+ { sourceId: "s1", name: "[email protected]", status: "created" },
],
},
],
});
+ // Free plan: page-components=3, custom-domain=false, status-subscribers=false
+ // Opt in to subscribers so the subscribers-disallowed warning fires
+ // (default `includeSubscribers` is `false` → warning silent).
await addLimitWarnings(summary, {
- limits: makeLimits({ "custom-domain": false }),
+ limits: makeLimits(),
workspaceId: 2,
+ db: tx,
+ options: { includeSubscribers: true },
});
- expect(summary.errors).toEqual([]);
+ expect(summary.errors.length).toBe(3);
+ expect(summary.errors.some((e) => e.includes("3 new component"))).toBe(
+ true,
+ );
+ expect(summary.errors.some((e) => e.includes("Custom domain"))).toBe(
+ true,
+ );
+ expect(summary.errors.some((e) => e.includes("Subscribers"))).toBe(true);
});
+ });
- test("no warning on paid plan with custom domain", async () => {
+ test("no warnings on starter plan within limits", async () => {
+ await withTestTransaction(async (tx) => {
const summary = makeSummary({
phases: [
{
@@ -193,75 +404,22 @@ describe("addLimitWarnings", () => {
resources: [
{
sourceId: "p1",
- name: "My Page",
+ name: "Page",
status: "created",
data: { customDomain: "status.example.com" },
},
],
},
- ],
- });
-
- await addLimitWarnings(summary, {
- limits: makeLimits({ "custom-domain": true }),
- workspaceId: 2,
- });
-
- expect(summary.errors).toEqual([]);
- });
- });
-
- // -------------------------------------------------------------------------
- // Subscribers
- // -------------------------------------------------------------------------
- describe("subscribers", () => {
- test("warns when subscribers present on free plan", async () => {
- const summary = makeSummary({
- phases: [
{
- phase: "subscribers",
+ phase: "components",
status: "completed",
resources: [
- { sourceId: "s1", name: "[email protected]", status: "created" },
- { sourceId: "s2", name: "[email protected]", status: "created" },
+ { sourceId: "1", name: "A", status: "created" },
+ { sourceId: "2", name: "B", status: "created" },
+ { sourceId: "3", name: "C", status: "created" },
+ { sourceId: "4", name: "D", status: "created" },
],
},
- ],
- });
-
- // `addLimitWarnings` gates subscribers warnings on
- // `options.includeSubscribers` (Cubic P2 — otherwise users who
- // aren't importing subscribers get a noise warning). Default
- // matches `ImportOptions` (`false`), so the warning only fires
- // when the caller explicitly opts in. Tests that want to exercise
- // the warning pass `options.includeSubscribers: true`.
- await addLimitWarnings(summary, {
- limits: makeLimits({ "status-subscribers": false }),
- workspaceId: 2,
- options: { includeSubscribers: true },
- });
-
- expect(summary.errors.length).toBe(1);
- expect(summary.errors[0]).toContain("Subscribers");
- });
-
- test("no warning when subscribers phase is empty", async () => {
- const summary = makeSummary({
- phases: [{ phase: "subscribers", status: "completed", resources: [] }],
- });
-
- await addLimitWarnings(summary, {
- limits: makeLimits({ "status-subscribers": false }),
- workspaceId: 2,
- options: { includeSubscribers: true },
- });
-
- expect(summary.errors).toEqual([]);
- });
-
- test("no warning on paid plan with subscribers", async () => {
- const summary = makeSummary({
- phases: [
{
phase: "subscribers",
status: "completed",
@@ -273,112 +431,14 @@ describe("addLimitWarnings", () => {
});
await addLimitWarnings(summary, {
- limits: makeLimits({ "status-subscribers": true }),
+ limits: { ...allPlans.starter.limits },
workspaceId: 2,
- options: { includeSubscribers: true },
+ db: tx,
});
expect(summary.errors).toEqual([]);
});
});
-
- // -------------------------------------------------------------------------
- // Combined
- // -------------------------------------------------------------------------
- test("reports multiple warnings at once", async () => {
- const summary = makeSummary({
- phases: [
- {
- phase: "page",
- status: "completed",
- resources: [
- {
- sourceId: "p1",
- name: "Page",
- status: "created",
- data: { customDomain: "status.example.com" },
- },
- ],
- },
- {
- phase: "components",
- status: "completed",
- resources: [
- { sourceId: "1", name: "A", status: "created" },
- { sourceId: "2", name: "B", status: "created" },
- { sourceId: "3", name: "C", status: "created" },
- { sourceId: "4", name: "D", status: "created" },
- ],
- },
- {
- phase: "subscribers",
- status: "completed",
- resources: [
- { sourceId: "s1", name: "[email protected]", status: "created" },
- ],
- },
- ],
- });
-
- // Free plan: page-components=3, custom-domain=false, status-subscribers=false
- // Opt in to subscribers so the subscribers-disallowed warning fires
- // (default `includeSubscribers` is `false` → warning silent).
- await addLimitWarnings(summary, {
- limits: makeLimits(),
- workspaceId: 2,
- options: { includeSubscribers: true },
- });
-
- expect(summary.errors.length).toBe(3);
- expect(summary.errors.some((e) => e.includes("3 new component"))).toBe(
- true,
- );
- expect(summary.errors.some((e) => e.includes("Custom domain"))).toBe(true);
- expect(summary.errors.some((e) => e.includes("Subscribers"))).toBe(true);
- });
-
- test("no warnings on starter plan within limits", async () => {
- const summary = makeSummary({
- phases: [
- {
- phase: "page",
- status: "completed",
- resources: [
- {
- sourceId: "p1",
- name: "Page",
- status: "created",
- data: { customDomain: "status.example.com" },
- },
- ],
- },
- {
- phase: "components",
- status: "completed",
- resources: [
- { sourceId: "1", name: "A", status: "created" },
- { sourceId: "2", name: "B", status: "created" },
- { sourceId: "3", name: "C", status: "created" },
- { sourceId: "4", name: "D", status: "created" },
- ],
- },
- {
- phase: "subscribers",
- status: "completed",
- resources: [
- { sourceId: "s1", name: "[email protected]", status: "created" },
- ],
- },
- ],
- });
-
- await addLimitWarnings(summary, {
- limits: { ...allPlans.starter.limits },
- workspaceId: 2,
- });
-
- expect(summary.errors).toEqual([]);
- });
});
describe("computePhaseStatus", () => {
diff --git a/packages/services/src/incident/__tests__/incident.test.ts b/packages/services/src/incident/__tests__/incident.test.ts
index 55b10466e..738211d2f 100644
--- a/packages/services/src/incident/__tests__/incident.test.ts
+++ b/packages/services/src/incident/__tests__/incident.test.ts
@@ -1,11 +1,4 @@
-import {
- afterAll,
- beforeAll,
- beforeEach,
- describe,
- expect,
- test,
-} from "bun:test";
+import { afterAll, beforeAll, describe, expect, test } from "bun:test";
import { db, eq } from "@openstatus/db";
import { incidentTable, monitor } from "@openstatus/db/src/schema";
@@ -14,12 +7,12 @@ import {
SEEDED_WORKSPACE_TEAM_ID,
} from "../../../test/fixtures";
import {
- clearAuditLog,
expectAuditRow,
loadSeededWorkspace,
makeUserCtx,
+ withTestTransaction,
} from "../../../test/helpers";
-import type { ServiceContext } from "../../context";
+import type { DrizzleTx, ServiceContext } from "../../context";
import { ConflictError, NotFoundError } from "../../errors";
import { acknowledgeIncident } from "../acknowledge";
import { deleteIncident } from "../delete";
@@ -61,22 +54,20 @@ afterAll(async () => {
.catch(() => undefined);
});
-beforeEach(async () => {
- await clearAuditLog(teamCtx.workspace.id);
- await clearAuditLog(freeCtx.workspace.id);
-});
-
let nextStartedAtOffset = 0;
-async function insertIncident(opts: {
- workspaceId: number;
- monitorId: number;
- acknowledgedAt?: Date;
- resolvedAt?: Date;
-}) {
- // Unique `(monitor_id, started_at)` constraint means we bump per-test.
+async function insertIncident(
+ tx: DrizzleTx,
+ opts: {
+ workspaceId: number;
+ monitorId: number;
+ acknowledgedAt?: Date;
+ resolvedAt?: Date;
+ },
+) {
+ // Unique `(monitor_id, started_at)` constraint means we bump per-call.
nextStartedAtOffset += 1;
const startedAt = new Date(Date.now() - nextStartedAtOffset * 60 * 1000);
- const row = await db
+ const row = await tx
.insert(incidentTable)
.values({
workspaceId: opts.workspaceId,
@@ -92,204 +83,218 @@ async function insertIncident(opts: {
describe("acknowledgeIncident", () => {
test("stamps acknowledgedAt + acknowledgedBy and emits audit", async () => {
- const incident = await insertIncident({
- workspaceId: teamCtx.workspace.id,
- monitorId: testMonitorId,
- });
-
- const updated = await acknowledgeIncident({
- ctx: teamCtx,
- input: { id: incident.id },
- });
-
- expect(updated.acknowledgedAt).toBeInstanceOf(Date);
- expect(updated.acknowledgedBy).toBe(1);
-
- await expectAuditRow({
- workspaceId: teamCtx.workspace.id,
- action: "incident.update",
- entityType: "incident",
- entityId: incident.id,
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ const incident = await insertIncident(tx, {
+ workspaceId: teamCtx.workspace.id,
+ monitorId: testMonitorId,
+ });
+
+ const updated = await acknowledgeIncident({
+ ctx,
+ input: { id: incident.id },
+ });
+
+ expect(updated.acknowledgedAt).toBeInstanceOf(Date);
+ expect(updated.acknowledgedBy).toBe(1);
+
+ await expectAuditRow({
+ workspaceId: teamCtx.workspace.id,
+ action: "incident.update",
+ entityType: "incident",
+ entityId: incident.id,
+ db: tx,
+ });
});
-
- await db.delete(incidentTable).where(eq(incidentTable.id, incident.id));
});
test("throws ConflictError when already acknowledged", async () => {
- const incident = await insertIncident({
- workspaceId: teamCtx.workspace.id,
- monitorId: testMonitorId,
- acknowledgedAt: new Date(),
- });
-
- await expect(
- acknowledgeIncident({ ctx: teamCtx, input: { id: incident.id } }),
- ).rejects.toBeInstanceOf(ConflictError);
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ const incident = await insertIncident(tx, {
+ workspaceId: teamCtx.workspace.id,
+ monitorId: testMonitorId,
+ acknowledgedAt: new Date(),
+ });
- await db.delete(incidentTable).where(eq(incidentTable.id, incident.id));
+ await expect(
+ acknowledgeIncident({ ctx, input: { id: incident.id } }),
+ ).rejects.toBeInstanceOf(ConflictError);
+ });
});
test("throws NotFoundError for a cross-workspace incident", async () => {
- const incident = await insertIncident({
- workspaceId: teamCtx.workspace.id,
- monitorId: testMonitorId,
+ await withTestTransaction(async (tx) => {
+ const incident = await insertIncident(tx, {
+ workspaceId: teamCtx.workspace.id,
+ monitorId: testMonitorId,
+ });
+
+ await expect(
+ acknowledgeIncident({
+ ctx: { ...freeCtx, db: tx },
+ input: { id: incident.id },
+ }),
+ ).rejects.toBeInstanceOf(NotFoundError);
});
-
- await expect(
- acknowledgeIncident({ ctx: freeCtx, input: { id: incident.id } }),
- ).rejects.toBeInstanceOf(NotFoundError);
-
- await db.delete(incidentTable).where(eq(incidentTable.id, incident.id));
});
});
describe("resolveIncident", () => {
test("stamps resolvedAt + resolvedBy", async () => {
- const incident = await insertIncident({
- workspaceId: teamCtx.workspace.id,
- monitorId: testMonitorId,
- });
-
- const updated = await resolveIncident({
- ctx: teamCtx,
- input: { id: incident.id },
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ const incident = await insertIncident(tx, {
+ workspaceId: teamCtx.workspace.id,
+ monitorId: testMonitorId,
+ });
+
+ const updated = await resolveIncident({
+ ctx,
+ input: { id: incident.id },
+ });
+ expect(updated.resolvedAt).toBeInstanceOf(Date);
+ expect(updated.resolvedBy).toBe(1);
});
- expect(updated.resolvedAt).toBeInstanceOf(Date);
- expect(updated.resolvedBy).toBe(1);
-
- await db.delete(incidentTable).where(eq(incidentTable.id, incident.id));
});
test("throws ConflictError when already resolved", async () => {
- const incident = await insertIncident({
- workspaceId: teamCtx.workspace.id,
- monitorId: testMonitorId,
- resolvedAt: new Date(),
- });
-
- await expect(
- resolveIncident({ ctx: teamCtx, input: { id: incident.id } }),
- ).rejects.toBeInstanceOf(ConflictError);
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ const incident = await insertIncident(tx, {
+ workspaceId: teamCtx.workspace.id,
+ monitorId: testMonitorId,
+ resolvedAt: new Date(),
+ });
- await db.delete(incidentTable).where(eq(incidentTable.id, incident.id));
+ await expect(
+ resolveIncident({ ctx, input: { id: incident.id } }),
+ ).rejects.toBeInstanceOf(ConflictError);
+ });
});
test("throws NotFoundError for a cross-workspace incident", async () => {
- const incident = await insertIncident({
- workspaceId: teamCtx.workspace.id,
- monitorId: testMonitorId,
+ await withTestTransaction(async (tx) => {
+ const incident = await insertIncident(tx, {
+ workspaceId: teamCtx.workspace.id,
+ monitorId: testMonitorId,
+ });
+
+ await expect(
+ resolveIncident({
+ ctx: { ...freeCtx, db: tx },
+ input: { id: incident.id },
+ }),
+ ).rejects.toBeInstanceOf(NotFoundError);
});
-
- await expect(
- resolveIncident({ ctx: freeCtx, input: { id: incident.id } }),
- ).rejects.toBeInstanceOf(NotFoundError);
-
- await db.delete(incidentTable).where(eq(incidentTable.id, incident.id));
});
});
describe("deleteIncident", () => {
test("removes the row and emits audit", async () => {
- const incident = await insertIncident({
- workspaceId: teamCtx.workspace.id,
- monitorId: testMonitorId,
- });
-
- await deleteIncident({ ctx: teamCtx, input: { id: incident.id } });
-
- const remaining = await db
- .select()
- .from(incidentTable)
- .where(eq(incidentTable.id, incident.id))
- .all();
- expect(remaining).toHaveLength(0);
-
- await expectAuditRow({
- workspaceId: teamCtx.workspace.id,
- action: "incident.delete",
- entityType: "incident",
- entityId: incident.id,
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ const incident = await insertIncident(tx, {
+ workspaceId: teamCtx.workspace.id,
+ monitorId: testMonitorId,
+ });
+
+ await deleteIncident({ ctx, input: { id: incident.id } });
+
+ const remaining = await tx
+ .select()
+ .from(incidentTable)
+ .where(eq(incidentTable.id, incident.id))
+ .all();
+ expect(remaining).toHaveLength(0);
+
+ await expectAuditRow({
+ workspaceId: teamCtx.workspace.id,
+ action: "incident.delete",
+ entityType: "incident",
+ entityId: incident.id,
+ db: tx,
+ });
});
});
test("throws NotFoundError for cross-workspace delete", async () => {
- const incident = await insertIncident({
- workspaceId: teamCtx.workspace.id,
- monitorId: testMonitorId,
+ await withTestTransaction(async (tx) => {
+ const incident = await insertIncident(tx, {
+ workspaceId: teamCtx.workspace.id,
+ monitorId: testMonitorId,
+ });
+
+ await expect(
+ deleteIncident({
+ ctx: { ...freeCtx, db: tx },
+ input: { id: incident.id },
+ }),
+ ).rejects.toBeInstanceOf(NotFoundError);
});
-
- await expect(
- deleteIncident({ ctx: freeCtx, input: { id: incident.id } }),
- ).rejects.toBeInstanceOf(NotFoundError);
-
- await db.delete(incidentTable).where(eq(incidentTable.id, incident.id));
});
});
describe("list / get", () => {
test("respects workspace isolation and enriches monitor", async () => {
- const incident = await insertIncident({
- workspaceId: teamCtx.workspace.id,
- monitorId: testMonitorId,
- });
-
- const full = await getIncident({
- ctx: teamCtx,
- input: { id: incident.id },
- });
- expect(full.monitor?.id).toBe(testMonitorId);
-
- await expect(
- getIncident({ ctx: freeCtx, input: { id: incident.id } }),
- ).rejects.toBeInstanceOf(NotFoundError);
-
- const { items } = await listIncidents({
- ctx: freeCtx,
- input: {
- limit: 100,
- offset: 0,
- order: "desc",
- },
+ await withTestTransaction(async (tx) => {
+ const teamCtxTx = { ...teamCtx, db: tx };
+ const freeCtxTx = { ...freeCtx, db: tx };
+ const incident = await insertIncident(tx, {
+ workspaceId: teamCtx.workspace.id,
+ monitorId: testMonitorId,
+ });
+
+ const full = await getIncident({
+ ctx: teamCtxTx,
+ input: { id: incident.id },
+ });
+ expect(full.monitor?.id).toBe(testMonitorId);
+
+ await expect(
+ getIncident({ ctx: freeCtxTx, input: { id: incident.id } }),
+ ).rejects.toBeInstanceOf(NotFoundError);
+
+ const { items } = await listIncidents({
+ ctx: freeCtxTx,
+ input: {
+ limit: 100,
+ offset: 0,
+ order: "desc",
+ },
+ });
+ expect(items.find((r) => r.id === incident.id)).toBeUndefined();
});
- expect(items.find((r) => r.id === incident.id)).toBeUndefined();
-
- await db.delete(incidentTable).where(eq(incidentTable.id, incident.id));
});
test("list batch-enriches monitors without duplication", async () => {
- const a = await insertIncident({
- workspaceId: teamCtx.workspace.id,
- monitorId: testMonitorId,
- });
- const b = await insertIncident({
- workspaceId: teamCtx.workspace.id,
- monitorId: testMonitorId,
- });
-
- const { items } = await listIncidents({
- ctx: teamCtx,
- input: {
- limit: 100,
- offset: 0,
- order: "desc",
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ const a = await insertIncident(tx, {
+ workspaceId: teamCtx.workspace.id,
monitorId: testMonitorId,
- },
+ });
+ const b = await insertIncident(tx, {
+ workspaceId: teamCtx.workspace.id,
+ monitorId: testMonitorId,
+ });
+
+ const { items } = await listIncidents({
+ ctx,
+ input: {
+ limit: 100,
+ offset: 0,
+ order: "desc",
+ monitorId: testMonitorId,
+ },
+ });
+
+ // Both incidents share the monitor — they should share the same enriched
+ // Monitor object (same-pageId dedup logic in the batch loader).
+ const ours = items.filter((i) => i.id === a.id || i.id === b.id);
+ expect(ours).toHaveLength(2);
+ expect(ours[0]?.monitor?.id).toBe(testMonitorId);
+ expect(ours[1]?.monitor?.id).toBe(testMonitorId);
});
-
- // Both incidents share the monitor — they should share the same enriched
- // Monitor object (same-pageId dedup logic in the batch loader).
- const ours = items.filter((i) => i.id === a.id || i.id === b.id);
- expect(ours).toHaveLength(2);
- expect(ours[0]?.monitor?.id).toBe(testMonitorId);
- expect(ours[1]?.monitor?.id).toBe(testMonitorId);
-
- await db
- .delete(incidentTable)
- .where(eq(incidentTable.id, a.id))
- .catch(() => undefined);
- await db
- .delete(incidentTable)
- .where(eq(incidentTable.id, b.id))
- .catch(() => undefined);
});
});
diff --git a/packages/services/src/integration/__tests__/install-slack-agent.test.ts b/packages/services/src/integration/__tests__/install-slack-agent.test.ts
new file mode 100644
index 000000000..b82a1f53b
--- /dev/null
+++ b/packages/services/src/integration/__tests__/install-slack-agent.test.ts
@@ -0,0 +1,273 @@
+import { afterAll, beforeAll, describe, expect, test } from "bun:test";
+import { and, db, desc, eq } from "@openstatus/db";
+import { integration } from "@openstatus/db/src/schema";
+
+import { SEEDED_WORKSPACE_TEAM_ID } from "../../../test/fixtures";
+import {
+ clearAuditLog,
+ loadSeededWorkspace,
+ makeSlackCtx,
+ readAuditLog,
+ withTestTransaction,
+} from "../../../test/helpers";
+import type { ServiceContext } from "../../context";
+import { installSlackAgent } from "../install-slack-agent";
+
+const TEAM_ID = "T_FIXTURE";
+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 baseInput = {
+ externalId: TEAM_ID,
+ credential: { botToken: "xoxb-secret", botUserId: "B_BOT" },
+ data: {
+ teamId: TEAM_ID,
+ teamName: "Fixture Team",
+ appId: "A_APP",
+ scopes: "chat:write,channels:history",
+ installedBy: SLACK_USER_ID,
+ },
+};
+
+describe("installSlackAgent", () => {
+ test("first install inserts row and emits integration.create", async () => {
+ await withTestTransaction(async (tx) => {
+ const created = await installSlackAgent({
+ ctx: { ...ctx, db: tx },
+ input: baseInput,
+ });
+
+ expect(created.name).toBe("slack-agent");
+ expect(created.workspaceId).toBe(SEEDED_WORKSPACE_TEAM_ID);
+ expect(created.externalId).toBe(TEAM_ID);
+
+ const rows = await readAuditLog({
+ workspaceId: SEEDED_WORKSPACE_TEAM_ID,
+ entityType: "integration",
+ entityId: created.id,
+ db: tx,
+ });
+ expect(rows).toHaveLength(1);
+ const [row] = rows;
+ expect(row.action).toBe("integration.create");
+ expect(row.actorType).toBe("slack");
+ expect(row.before).toBeNull();
+ // Bot token must never appear in the snapshot.
+ expect(JSON.stringify(row.after)).not.toContain("xoxb-secret");
+ expect((row.after as Record<string, unknown>).credential).toBeUndefined();
+ });
+ });
+
+ test("reinstall updates row and emits integration.update with credential diff", async () => {
+ 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 });
+
+ const reinstalled = await installSlackAgent({
+ ctx: ctxTx,
+ input: {
+ ...baseInput,
+ credential: { botToken: "xoxb-rotated", botUserId: "B_BOT" },
+ data: { ...baseInput.data, scopes: "chat:write" },
+ },
+ });
+
+ expect(reinstalled.id).toBe(created.id);
+
+ const rows = await readAuditLog({
+ workspaceId: SEEDED_WORKSPACE_TEAM_ID,
+ entityType: "integration",
+ entityId: created.id,
+ db: tx,
+ });
+ expect(rows).toHaveLength(1);
+ const [row] = rows;
+ expect(row.action).toBe("integration.update");
+ expect(row.changedFields).toContain("data");
+ expect(row.changedFields).toContain("credentialFingerprint");
+ expect(JSON.stringify(row.before)).not.toContain("xoxb-secret");
+ expect(JSON.stringify(row.after)).not.toContain("xoxb-rotated");
+ });
+ });
+
+ test("token-only rotation still emits an audit row via the fingerprint", async () => {
+ 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 installSlackAgent({
+ ctx: ctxTx,
+ input: {
+ ...baseInput,
+ credential: { botToken: "xoxb-rotated", botUserId: "B_BOT" },
+ },
+ });
+
+ const rows = await readAuditLog({
+ workspaceId: SEEDED_WORKSPACE_TEAM_ID,
+ entityType: "integration",
+ entityId: created.id,
+ db: tx,
+ });
+ expect(rows).toHaveLength(1);
+ expect(rows[0].action).toBe("integration.update");
+ expect(rows[0].changedFields).toEqual(["credentialFingerprint"]);
+ });
+ });
+
+ test("identical reinstall is a no-op and does not emit an audit row", async () => {
+ 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 installSlackAgent({ ctx: ctxTx, input: baseInput });
+
+ const rows = await readAuditLog({
+ workspaceId: SEEDED_WORKSPACE_TEAM_ID,
+ entityType: "integration",
+ entityId: created.id,
+ db: tx,
+ });
+ expect(rows).toHaveLength(0);
+ });
+ });
+
+ test("rejects empty bot token at the schema boundary", async () => {
+ await withTestTransaction(async (tx) => {
+ await expect(
+ installSlackAgent({
+ ctx: { ...ctx, db: tx },
+ input: {
+ ...baseInput,
+ credential: { botToken: "", botUserId: "B" },
+ },
+ }),
+ ).rejects.toThrow();
+ });
+ });
+
+ test("consolidates duplicate slack-agent rows in the same workspace", async () => {
+ await withTestTransaction(async (tx) => {
+ const ctxTx = { ...ctx, db: tx };
+ // Simulate legacy data: two `slack-agent` rows for the same workspace.
+ // Insert directly to bypass the service guard. The DB has no
+ // `UNIQUE (workspace_id, name)` index, so the service does the
+ // consolidation in code.
+ const [first] = await tx
+ .insert(integration)
+ .values({
+ name: "slack-agent",
+ workspaceId: SEEDED_WORKSPACE_TEAM_ID,
+ externalId: "T_OLD_1",
+ credential: { botToken: "xoxb-old-1", botUserId: "B_OLD_1" },
+ data: { ...baseInput.data, teamId: "T_OLD_1" },
+ })
+ .returning();
+ const [second] = await tx
+ .insert(integration)
+ .values({
+ name: "slack-agent",
+ workspaceId: SEEDED_WORKSPACE_TEAM_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 installSlackAgent({ ctx: ctxTx, input: baseInput });
+
+ const remaining = await tx
+ .select()
+ .from(integration)
+ .where(
+ and(
+ eq(integration.name, "slack-agent"),
+ eq(integration.workspaceId, SEEDED_WORKSPACE_TEAM_ID),
+ ),
+ )
+ .orderBy(desc(integration.id))
+ .all();
+ expect(remaining).toHaveLength(1);
+ expect(remaining[0].id).toBe(second.id);
+
+ const all = await readAuditLog({
+ workspaceId: SEEDED_WORKSPACE_TEAM_ID,
+ entityType: "integration",
+ db: tx,
+ });
+ expect(all.find((r) => r.action === "integration.delete")?.entityId).toBe(
+ String(first.id),
+ );
+ const updateRow = all.find((r) => r.action === "integration.update");
+ expect(updateRow?.entityId).toBe(String(second.id));
+ // The deleted sibling's snapshot must carry the fingerprint, same
+ // shape as create/update — proves delete-path symmetry.
+ const deleteRow = all.find((r) => r.action === "integration.delete");
+ expect(
+ (deleteRow?.before as Record<string, unknown> | null)
+ ?.credentialFingerprint,
+ ).toBeTypeOf("string");
+ });
+ });
+
+ test("propagates the openstatus userId from the slack actor", async () => {
+ await withTestTransaction(async (tx) => {
+ const ATTRIBUTED_USER_ID = 1;
+ const attributedCtx: ServiceContext = {
+ ...ctx,
+ actor: {
+ type: "slack",
+ teamId: TEAM_ID,
+ slackUserId: SLACK_USER_ID,
+ userId: ATTRIBUTED_USER_ID,
+ },
+ db: tx,
+ };
+
+ const created = await installSlackAgent({
+ ctx: attributedCtx,
+ input: baseInput,
+ });
+
+ const rows = await readAuditLog({
+ workspaceId: SEEDED_WORKSPACE_TEAM_ID,
+ entityType: "integration",
+ entityId: created.id,
+ db: tx,
+ });
+ expect(rows).toHaveLength(1);
+ expect(rows[0].actorUserId).toBe(ATTRIBUTED_USER_ID);
+ });
+ });
+});
diff --git a/packages/services/src/integration/delete.ts b/packages/services/src/integration/delete.ts
new file mode 100644
index 000000000..2cf3a0174
--- /dev/null
+++ b/packages/services/src/integration/delete.ts
@@ -0,0 +1,83 @@
+import { and, eq } from "@openstatus/db";
+import { integration } from "@openstatus/db/src/schema";
+
+import { emitAudit } from "../audit";
+import { type ServiceContext, withTransaction } from "../context";
+import { DeleteIntegrationInput } from "./schemas";
+import { snapshotIntegration } from "./snapshot";
+
+/**
+ * Best-effort revoke of a Slack bot token before deleting the row.
+ *
+ * Hard 3s timeout: this runs on Next.js Edge via tRPC, and the router-era
+ * call had no timeout, which meant a flapping Slack API could tie up a
+ * request for ~15s. A missing or invalid token surfaces as a silent
+ * failure on Slack's side — we don't block the delete on the outcome.
+ */
+async function revokeSlackToken(botToken: string): Promise<void> {
+ try {
+ await fetch("https://slack.com/api/auth.revoke", {
+ method: "POST",
+ headers: {
+ Authorization: `Bearer ${botToken}`,
+ "Content-Type": "application/x-www-form-urlencoded",
+ },
+ signal: AbortSignal.timeout(3_000),
+ });
+ } catch {
+ // Token may already be invalid, or Slack may be unreachable — not our
+ // problem once the local row is about to disappear.
+ }
+}
+
+/**
+ * Delete an integration scoped to the caller's workspace. Idempotent —
+ * missing rows succeed silently. When the row carries a Slack bot token,
+ * attempts to revoke it via `auth.revoke` *after* a successful delete;
+ * failure there does not roll the delete back.
+ *
+ * Order matters: revoking before the transaction would leave a row with
+ * an already-invalidated token if the delete then fails. Revoking after
+ * the commit means the worst case is a token left valid on Slack's side
+ * with no local row referencing it — preferable to broken persisted state.
+ *
+ * The audit snapshot is taken from the post-delete `RETURNING` row inside
+ * the tx so it reflects exactly what was removed.
+ */
+export async function deleteIntegration(args: {
+ ctx: ServiceContext;
+ input: DeleteIntegrationInput;
+}): Promise<void> {
+ const { ctx } = args;
+ const input = DeleteIntegrationInput.parse(args.input);
+
+ let revokeBotToken: string | undefined;
+
+ await withTransaction(ctx, async (tx) => {
+ const [deleted] = await tx
+ .delete(integration)
+ .where(
+ and(
+ eq(integration.id, input.id),
+ eq(integration.workspaceId, ctx.workspace.id),
+ ),
+ )
+ .returning();
+
+ if (!deleted) return;
+
+ const credential = deleted.credential as { botToken?: string } | null;
+ if (credential?.botToken) revokeBotToken = credential.botToken;
+
+ await emitAudit(tx, ctx, {
+ action: "integration.delete",
+ entityType: "integration",
+ entityId: deleted.id,
+ before: await snapshotIntegration(deleted),
+ });
+ });
+
+ if (revokeBotToken) {
+ await revokeSlackToken(revokeBotToken);
+ }
+}
diff --git a/packages/services/src/integration/index.ts b/packages/services/src/integration/index.ts
new file mode 100644
index 000000000..f6819105f
--- /dev/null
+++ b/packages/services/src/integration/index.ts
@@ -0,0 +1,9 @@
+export { deleteIntegration } from "./delete";
+export { installSlackAgent } from "./install-slack-agent";
+export { listIntegrations, type IntegrationSummary } from "./list";
+export {
+ DeleteIntegrationInput,
+ InstallSlackAgentInputSchema,
+ type InstallSlackAgentInput,
+ ListIntegrationsInput,
+} from "./schemas";
diff --git a/packages/services/src/integration/install-slack-agent.ts b/packages/services/src/integration/install-slack-agent.ts
new file mode 100644
index 000000000..0f0d7416a
--- /dev/null
+++ b/packages/services/src/integration/install-slack-agent.ts
@@ -0,0 +1,119 @@
+import { and, desc, eq } from "@openstatus/db";
+import { integration } from "@openstatus/db/src/schema";
+
+import { emitAudit } from "../audit";
+import { type ServiceContext, withTransaction } from "../context";
+import { InternalServiceError, NotFoundError } from "../errors";
+import {
+ type InstallSlackAgentInput,
+ InstallSlackAgentInputSchema,
+} from "./schemas";
+import { snapshotIntegration } from "./snapshot";
+
+const SLACK_AGENT_NAME = "slack-agent";
+
+/**
+ * Upsert the workspace's Slack agent integration after a successful OAuth
+ * callback. Emits `integration.create` on first install, `integration.update`
+ * on reinstall (token rotation, re-scoping, bot change). Bot tokens never
+ * enter the audit log — a SHA-256 fingerprint is recorded instead so
+ * rotations are still visible in `changed_fields`.
+ */
+export async function installSlackAgent(args: {
+ ctx: ServiceContext;
+ input: InstallSlackAgentInput;
+}) {
+ const { ctx } = args;
+ const input = InstallSlackAgentInputSchema.parse(args.input);
+
+ return withTransaction(ctx, async (tx) => {
+ // The DB has no `UNIQUE (workspace_id, name)` constraint, so a race
+ // or legacy data could leave more than one `slack-agent` row for a
+ // workspace. Use `.all()` + ordered pick instead of `.get()` so we
+ // (a) deterministically operate on the most recent row and (b) clean
+ // up any older siblings in the same transaction. This is the
+ // service-level enforcement of the "one per workspace" invariant.
+ const existingRows = await tx
+ .select()
+ .from(integration)
+ .where(
+ and(
+ eq(integration.name, SLACK_AGENT_NAME),
+ eq(integration.workspaceId, ctx.workspace.id),
+ ),
+ )
+ .orderBy(desc(integration.id))
+ .all();
+
+ const [existing, ...stale] = existingRows;
+
+ if (stale.length > 0) {
+ console.warn("found duplicate slack-agent rows; consolidating", {
+ workspaceId: ctx.workspace.id,
+ keepId: existing?.id,
+ dropIds: stale.map((r) => r.id),
+ });
+ for (const row of stale) {
+ const [deleted] = await tx
+ .delete(integration)
+ .where(eq(integration.id, row.id))
+ .returning();
+ if (deleted) {
+ await emitAudit(tx, ctx, {
+ action: "integration.delete",
+ entityType: "integration",
+ entityId: deleted.id,
+ before: await snapshotIntegration(deleted),
+ });
+ }
+ }
+ }
+
+ if (existing) {
+ const [updated] = await tx
+ .update(integration)
+ .set({
+ externalId: input.externalId,
+ credential: input.credential,
+ data: input.data,
+ updatedAt: new Date(),
+ })
+ .where(eq(integration.id, existing.id))
+ .returning();
+ if (!updated) throw new NotFoundError("integration", existing.id);
+
+ await emitAudit(tx, ctx, {
+ action: "integration.update",
+ entityType: "integration",
+ entityId: updated.id,
+ before: await snapshotIntegration(existing),
+ after: await snapshotIntegration(updated),
+ });
+ return updated;
+ }
+
+ const [created] = await tx
+ .insert(integration)
+ .values({
+ name: SLACK_AGENT_NAME,
+ workspaceId: ctx.workspace.id,
+ externalId: input.externalId,
+ credential: input.credential,
+ data: input.data,
+ })
+ .returning();
+ if (!created) {
+ throw new InternalServiceError(
+ "Failed to insert slack-agent integration",
+ );
+ }
+
+ await emitAudit(tx, ctx, {
+ action: "integration.create",
+ entityType: "integration",
+ entityId: created.id,
+ after: await snapshotIntegration(created),
+ });
+ return created;
+ });
+}
diff --git a/packages/services/src/integration/list.ts b/packages/services/src/integration/list.ts
new file mode 100644
index 000000000..d6da96693
--- /dev/null
+++ b/packages/services/src/integration/list.ts
@@ -0,0 +1,79 @@
+import { eq, sql } from "@openstatus/db";
+import { integration } from "@openstatus/db/src/schema";
+import { z } from "zod";
+
+import { type ServiceContext, getReadDb } from "../context";
+import { ListIntegrationsInput } from "./schemas";
+
+const integrationSummarySchema = z.object({
+ id: z.number(),
+ name: z.string(),
+ externalId: z.string(),
+ data: z.record(z.string(), z.unknown()),
+ createdAt: z.coerce.date().nullable(),
+});
+
+export type IntegrationSummary = z.infer<typeof integrationSummarySchema>;
+
+function safeJsonParse(
+ rowId: number,
+ value: string | null,
+): Record<string, unknown> {
+ if (!value) return {};
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(value);
+ } catch (cause) {
+ console.warn("integration row has malformed `data` JSON", {
+ integrationId: rowId,
+ cause: cause instanceof Error ? cause.message : "unknown",
+ });
+ return {};
+ }
+ // Valid JSON but wrong shape (string, number, array, null) would fail
+ // the row-level `z.record` check and crash the whole list.
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
+ console.warn("integration row has non-object `data` JSON", {
+ integrationId: rowId,
+ });
+ return {};
+ }
+ return parsed as Record<string, unknown>;
+}
+
+/**
+ * List integrations for the caller's workspace. `data` is stored as a
+ * JSON-mode text column; we force-cast to raw text with `sql<string>` so
+ * malformed rows don't break the whole list (fall back to `{}`). The
+ * `credential` column is never selected — it carries secrets and is not
+ * part of the list contract.
+ */
+export async function listIntegrations(args: {
+ ctx: ServiceContext;
+ input?: ListIntegrationsInput;
+}): Promise<IntegrationSummary[]> {
+ ListIntegrationsInput.parse(args.input ?? {});
+ const db = getReadDb(args.ctx);
+
+ const rows = await db
+ .select({
+ id: integration.id,
+ name: integration.name,
+ externalId: integration.externalId,
+ rawData: sql<string>`${integration.data}`,
+ createdAt: integration.createdAt,
+ })
+ .from(integration)
+ .where(eq(integration.workspaceId, args.ctx.workspace.id))
+ .all();
+
+ return integrationSummarySchema.array().parse(
+ rows.map((row) => ({
+ id: row.id,
+ name: row.name,
+ externalId: row.externalId,
+ data: safeJsonParse(row.id, row.rawData),
+ createdAt: row.createdAt,
+ })),
+ );
+}
diff --git a/packages/services/src/integration/schemas.ts b/packages/services/src/integration/schemas.ts
new file mode 100644
index 000000000..5bc815619
--- /dev/null
+++ b/packages/services/src/integration/schemas.ts
@@ -0,0 +1,25 @@
+import { z } from "zod";
+
+export const ListIntegrationsInput = z.object({}).strict();
+export type ListIntegrationsInput = z.infer<typeof ListIntegrationsInput>;
+
+export const DeleteIntegrationInput = z.object({ id: z.number().int() });
+export type DeleteIntegrationInput = z.infer<typeof DeleteIntegrationInput>;
+
+export const InstallSlackAgentInputSchema = z.object({
+ externalId: z.string().min(1),
+ credential: z.object({
+ botToken: z.string().min(1),
+ botUserId: z.string().min(1),
+ }),
+ data: z.object({
+ teamId: z.string().min(1),
+ teamName: z.string().min(1),
+ appId: z.string().min(1),
+ scopes: z.string(),
+ installedBy: z.string().min(1),
+ }),
+});
+export type InstallSlackAgentInput = z.infer<
+ typeof InstallSlackAgentInputSchema
+>;
diff --git a/packages/services/src/integration/snapshot.ts b/packages/services/src/integration/snapshot.ts
new file mode 100644
index 000000000..c07c3491b
--- /dev/null
+++ b/packages/services/src/integration/snapshot.ts
@@ -0,0 +1,59 @@
+import type { integration } from "@openstatus/db/src/schema";
+
+// Drizzle's inferred row type — JSON columns surface as `unknown` here,
+// vs the zod-derived `Integration` type which narrows them to `Json`.
+// We keep the looser shape so this helper accepts whatever `tx.select()`
+// or `.returning()` actually produces, including historical rows that
+// pre-date the current zod schema.
+type IntegrationRow = typeof integration.$inferSelect;
+
+/**
+ * Stable, irreversible fingerprint of a Slack bot credential. Lets the
+ * audit log show that a token rotated without ever storing the token
+ * itself. Keyed on `botToken` because that's the field that actually
+ * rotates on reinstall; `botUserId` is folded in so a re-install with
+ * a different bot also surfaces.
+ *
+ * Uses Web Crypto (`crypto.subtle.digest`) instead of `node:crypto` so
+ * this module is Edge-safe — the dashboard's tRPC bundles
+ * `deleteIntegration` (which transitively imports this file) and runs
+ * it on Next.js Edge, where `node:*` imports break the build.
+ */
+async function fingerprintCredential(c: {
+ botToken: string;
+ botUserId: string;
+}) {
+ const data = new TextEncoder().encode(`${c.botUserId}:${c.botToken}`);
+ const hash = await crypto.subtle.digest("SHA-256", data);
+ return Array.from(new Uint8Array(hash))
+ .map((b) => b.toString(16).padStart(2, "0"))
+ .join("")
+ .slice(0, 16);
+}
+
+/**
+ * Audit-safe view of an integration row. Strips `credential` (raw bot
+ * token) and replaces it with a non-reversible fingerprint so token
+ * rotations register in `changed_fields` even when nothing else
+ * changes. Both `installSlackAgent` and `deleteIntegration` go through
+ * this helper so create/update/delete audit rows have the same shape —
+ * a viewer diffing successive rows can rely on `credentialFingerprint`
+ * being present at every step.
+ *
+ * Async because the underlying digest is async on Edge runtime.
+ */
+export async function snapshotIntegration(row: IntegrationRow) {
+ const { credential, ...rest } = row;
+ const fingerprint =
+ credential &&
+ typeof credential === "object" &&
+ "botToken" in credential &&
+ typeof (credential as { botToken: unknown }).botToken === "string" &&
+ "botUserId" in credential &&
+ typeof (credential as { botUserId: unknown }).botUserId === "string"
+ ? await fingerprintCredential(
+ credential as { botToken: string; botUserId: string },
+ )
+ : null;
+ return { ...rest, credentialFingerprint: fingerprint };
+}
diff --git a/packages/services/src/invitation/__tests__/invitation.test.ts b/packages/services/src/invitation/__tests__/invitation.test.ts
index fc73d4e7a..a0277c16d 100644
--- a/packages/services/src/invitation/__tests__/invitation.test.ts
+++ b/packages/services/src/invitation/__tests__/invitation.test.ts
@@ -1,12 +1,5 @@
-import {
- afterAll,
- beforeAll,
- beforeEach,
- describe,
- expect,
- test,
-} from "bun:test";
-import { db, eq, inArray } from "@openstatus/db";
+import { afterAll, beforeAll, describe, expect, test } from "bun:test";
+import { db, eq } from "@openstatus/db";
import { invitation, user, usersToWorkspaces } from "@openstatus/db/src/schema";
import {
@@ -21,10 +14,10 @@ import {
SEEDED_WORKSPACE_TEAM_ID,
} from "../../../test/fixtures";
import {
- clearAuditLog,
expectAuditRow,
loadSeededWorkspace,
makeUserCtx,
+ withTestTransaction,
} from "../../../test/helpers";
import type { ServiceContext } from "../../context";
import { LimitExceededError, NotFoundError } from "../../errors";
@@ -33,7 +26,6 @@ const TEST_PREFIX = "svc-inv-test";
let teamCtx: ServiceContext;
let freeCtx: ServiceContext;
-const createdInvitationIds: number[] = [];
beforeAll(async () => {
const team = await loadSeededWorkspace(SEEDED_WORKSPACE_TEAM_ID);
@@ -76,18 +68,12 @@ beforeAll(async () => {
});
afterAll(async () => {
- if (createdInvitationIds.length > 0) {
- await db
- .delete(invitation)
- .where(inArray(invitation.id, createdInvitationIds));
- }
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 (test does this in-test, but harmless to
- // re-run) and the user row itself.
+ // clean up membership and the user row itself.
await db
.delete(usersToWorkspaces)
.where(eq(usersToWorkspaces.userId, 3))
@@ -98,166 +84,174 @@ afterAll(async () => {
.catch(() => undefined);
});
-beforeEach(async () => {
- await clearAuditLog(teamCtx.workspace.id);
- await clearAuditLog(freeCtx.workspace.id);
-});
-
describe("createInvitation", () => {
test("creates an invitation scoped to the caller's workspace", async () => {
- const email = `${TEST_PREFIX}-${Date.now()}@example.com`;
- const row = await createInvitation({
- ctx: teamCtx,
- input: { email },
- });
- createdInvitationIds.push(row.id);
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ const email = `${TEST_PREFIX}-${Date.now()}@example.com`;
+ const row = await createInvitation({
+ ctx,
+ input: { email },
+ });
- expect(row.email).toBe(email);
- expect(row.workspaceId).toBe(SEEDED_WORKSPACE_TEAM_ID);
- expect(row.token).toBeDefined();
- expect(row.expiresAt.getTime()).toBeGreaterThan(Date.now());
+ expect(row.email).toBe(email);
+ expect(row.workspaceId).toBe(SEEDED_WORKSPACE_TEAM_ID);
+ expect(row.token).toBeDefined();
+ expect(row.expiresAt.getTime()).toBeGreaterThan(Date.now());
- await expectAuditRow({
- workspaceId: teamCtx.workspace.id,
- action: "invitation.create",
- entityType: "invitation",
- entityId: row.id,
+ await expectAuditRow({
+ workspaceId: teamCtx.workspace.id,
+ action: "invitation.create",
+ entityType: "invitation",
+ entityId: row.id,
+ db: tx,
+ });
});
});
test("enforces the members plan cap on free workspace", async () => {
- // Free plan has `members: 1` — the owner already occupies that slot.
- await expect(
- createInvitation({
- ctx: freeCtx,
- input: { email: `${TEST_PREFIX}[email protected]` },
- }),
- ).rejects.toBeInstanceOf(LimitExceededError);
+ await withTestTransaction(async (tx) => {
+ // Free plan has `members: 1` — the owner already occupies that slot.
+ await expect(
+ createInvitation({
+ ctx: { ...freeCtx, db: tx },
+ input: { email: `${TEST_PREFIX}[email protected]` },
+ }),
+ ).rejects.toBeInstanceOf(LimitExceededError);
+ });
});
});
describe("listInvitations", () => {
test("returns pending invitations for the workspace only", async () => {
- const email = `${TEST_PREFIX}-list-${Date.now()}@example.com`;
- const created = await createInvitation({
- ctx: teamCtx,
- input: { email },
- });
- createdInvitationIds.push(created.id);
+ await withTestTransaction(async (tx) => {
+ const teamCtxTx = { ...teamCtx, db: tx };
+ const freeCtxTx = { ...freeCtx, db: tx };
+ const email = `${TEST_PREFIX}-list-${Date.now()}@example.com`;
+ const created = await createInvitation({
+ ctx: teamCtxTx,
+ input: { email },
+ });
- const rows = await listInvitations({ ctx: teamCtx });
- const ids = rows.map((r) => r.id);
- expect(ids).toContain(created.id);
+ const rows = await listInvitations({ ctx: teamCtxTx });
+ const ids = rows.map((r) => r.id);
+ expect(ids).toContain(created.id);
- const freeRows = await listInvitations({ ctx: freeCtx });
- expect(freeRows.map((r) => r.id)).not.toContain(created.id);
+ const freeRows = await listInvitations({ ctx: freeCtxTx });
+ expect(freeRows.map((r) => r.id)).not.toContain(created.id);
+ });
});
});
describe("getInvitationByToken", () => {
test("resolves by token + email", async () => {
- const email = `${TEST_PREFIX}-token-${Date.now()}@example.com`;
- const created = await createInvitation({
- ctx: teamCtx,
- input: { email },
- });
- createdInvitationIds.push(created.id);
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ const email = `${TEST_PREFIX}-token-${Date.now()}@example.com`;
+ const created = await createInvitation({
+ ctx,
+ input: { email },
+ });
- const row = await getInvitationByToken({
- ctx: teamCtx,
- input: { token: created.token, email },
+ const row = await getInvitationByToken({
+ ctx,
+ input: { token: created.token, email },
+ });
+ expect(row.id).toBe(created.id);
+ expect(row.workspace.id).toBe(SEEDED_WORKSPACE_TEAM_ID);
});
- expect(row.id).toBe(created.id);
- expect(row.workspace.id).toBe(SEEDED_WORKSPACE_TEAM_ID);
});
test("rejects a valid token for the wrong email", async () => {
- const email = `${TEST_PREFIX}-mismatch-${Date.now()}@example.com`;
- const created = await createInvitation({
- ctx: teamCtx,
- input: { email },
- });
- createdInvitationIds.push(created.id);
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ const email = `${TEST_PREFIX}-mismatch-${Date.now()}@example.com`;
+ const created = await createInvitation({
+ ctx,
+ input: { email },
+ });
- await expect(
- getInvitationByToken({
- ctx: teamCtx,
- input: {
- token: created.token,
- email: `other-${email}`,
- },
- }),
- ).rejects.toBeInstanceOf(NotFoundError);
+ await expect(
+ getInvitationByToken({
+ ctx,
+ input: {
+ token: created.token,
+ email: `other-${email}`,
+ },
+ }),
+ ).rejects.toBeInstanceOf(NotFoundError);
+ });
});
});
describe("deleteInvitation", () => {
test("removes the row and is scoped to the caller's workspace", async () => {
- const email = `${TEST_PREFIX}-delete-${Date.now()}@example.com`;
- const created = await createInvitation({
- ctx: teamCtx,
- input: { email },
- });
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ const email = `${TEST_PREFIX}-delete-${Date.now()}@example.com`;
+ const created = await createInvitation({
+ ctx,
+ input: { email },
+ });
- await deleteInvitation({ ctx: teamCtx, input: { id: created.id } });
+ await deleteInvitation({ ctx, input: { id: created.id } });
- const row = await db
- .select({ id: invitation.id })
- .from(invitation)
- .where(eq(invitation.id, created.id))
- .get();
- expect(row).toBeUndefined();
+ const row = await tx
+ .select({ id: invitation.id })
+ .from(invitation)
+ .where(eq(invitation.id, created.id))
+ .get();
+ expect(row).toBeUndefined();
+ });
});
});
describe("acceptInvitation", () => {
test("stamps acceptedAt and inserts a workspace membership", async () => {
- // 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,
- input: { email },
- });
- createdInvitationIds.push(created.id);
- const acceptingCtx = makeUserCtx(teamCtx.workspace, {
- userId: acceptingUserId,
- });
+ 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 },
+ input: { email },
+ });
+ const acceptingCtx = {
+ ...makeUserCtx(teamCtx.workspace, { userId: acceptingUserId }),
+ db: tx,
+ };
- try {
const workspaceRow = await acceptInvitation({
ctx: acceptingCtx,
input: { id: created.id, email },
});
expect(workspaceRow.id).toBe(SEEDED_WORKSPACE_TEAM_ID);
- const updated = await db
+ const updated = await tx
.select()
.from(invitation)
.where(eq(invitation.id, created.id))
.get();
expect(updated?.acceptedAt).not.toBeNull();
- const membership = await db
+ const membership = await tx
.select()
.from(usersToWorkspaces)
.where(eq(usersToWorkspaces.userId, acceptingUserId))
.get();
expect(membership?.workspaceId).toBe(SEEDED_WORKSPACE_TEAM_ID);
- } finally {
- await db
- .delete(usersToWorkspaces)
- .where(eq(usersToWorkspaces.userId, acceptingUserId));
- }
+ });
});
test("throws NotFoundError for an unknown or wrong-email invitation", async () => {
- await expect(
- acceptInvitation({
- ctx: teamCtx,
- input: { id: 999_999, email: "[email protected]" },
- }),
- ).rejects.toBeInstanceOf(NotFoundError);
+ await withTestTransaction(async (tx) => {
+ await expect(
+ acceptInvitation({
+ ctx: { ...teamCtx, db: tx },
+ input: { id: 999_999, email: "[email protected]" },
+ }),
+ ).rejects.toBeInstanceOf(NotFoundError);
+ });
});
});
diff --git a/packages/services/src/maintenance/__tests__/maintenance.test.ts b/packages/services/src/maintenance/__tests__/maintenance.test.ts
index 087575a1e..14a189131 100644
--- a/packages/services/src/maintenance/__tests__/maintenance.test.ts
+++ b/packages/services/src/maintenance/__tests__/maintenance.test.ts
@@ -1,6 +1,5 @@
import {
afterAll,
- afterEach,
beforeAll,
beforeEach,
describe,
@@ -9,7 +8,6 @@ import {
} from "bun:test";
import { db, eq, inArray } from "@openstatus/db";
import {
- maintenance,
maintenancesToPageComponents,
page,
pageComponent,
@@ -20,11 +18,11 @@ import {
SEEDED_WORKSPACE_TEAM_ID,
} from "../../../test/fixtures";
import {
- clearAuditLog,
expectAuditRow,
loadSeededWorkspace,
makeSlackCtx,
makeUserCtx,
+ withTestTransaction,
} from "../../../test/helpers";
import type { ServiceContext } from "../../context";
import { ConflictError, ForbiddenError, NotFoundError } from "../../errors";
@@ -55,15 +53,6 @@ let testPageComponentId: number;
let otherPageId: number;
let otherPageComponentId: number;
-/**
- * Tests push created maintenance ids here instead of issuing an inline
- * `db.delete()` at the end of their body. `afterEach` drains the array,
- * so cleanup runs even when an assertion throws midway through a test —
- * otherwise a failing assertion leaves orphans that flake subsequent
- * runs.
- */
-const createdMaintenanceIds: number[] = [];
-
beforeAll(async () => {
const team = await loadSeededWorkspace(SEEDED_WORKSPACE_TEAM_ID);
const free = await loadSeededWorkspace(SEEDED_WORKSPACE_FREE_ID);
@@ -134,22 +123,10 @@ afterAll(async () => {
.catch(() => undefined);
});
-beforeEach(async () => {
- await clearAuditLog(teamCtx.workspace.id);
- await clearAuditLog(freeCtx.workspace.id);
+beforeEach(() => {
subscriptionSpies?.dispatchMaintenanceUpdate.mockClear();
});
-afterEach(async () => {
- if (createdMaintenanceIds.length > 0) {
- await db
- .delete(maintenance)
- .where(inArray(maintenance.id, createdMaintenanceIds))
- .catch(() => undefined);
- createdMaintenanceIds.length = 0;
- }
-});
-
function futureRange(startIn = 60 * 60 * 1000) {
const now = Date.now();
return {
@@ -160,351 +137,371 @@ function futureRange(startIn = 60 * 60 * 1000) {
describe("createMaintenance", () => {
test("creates + associations + audit", async () => {
- const range = futureRange();
- const record = await createMaintenance({
- ctx: teamCtx,
- input: {
- title: `${TEST_PREFIX}-happy`,
- message: "planned work",
- ...range,
- pageId: testPageId,
- pageComponentIds: [testPageComponentId],
- },
- });
-
- expect(record.title).toBe(`${TEST_PREFIX}-happy`);
- expect(record.pageId).toBe(testPageId);
-
- const assoc = await db
- .select()
- .from(maintenancesToPageComponents)
- .where(eq(maintenancesToPageComponents.maintenanceId, record.id))
- .all();
- expect(assoc.map((a) => a.pageComponentId)).toEqual([testPageComponentId]);
-
- await expectAuditRow({
- workspaceId: teamCtx.workspace.id,
- action: "maintenance.create",
- entityType: "maintenance",
- entityId: record.id,
- });
-
- createdMaintenanceIds.push(record.id);
- });
-
- test("throws when page is in another workspace", async () => {
- const range = futureRange();
- await expect(
- createMaintenance({
- ctx: freeCtx,
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ const range = futureRange();
+ const record = await createMaintenance({
+ ctx,
input: {
- title: `${TEST_PREFIX}-cross-ws`,
- message: "m",
+ title: `${TEST_PREFIX}-happy`,
+ message: "planned work",
...range,
pageId: testPageId,
- pageComponentIds: [],
+ pageComponentIds: [testPageComponentId],
},
- }),
- ).rejects.toBeInstanceOf(NotFoundError);
+ });
+
+ expect(record.title).toBe(`${TEST_PREFIX}-happy`);
+ expect(record.pageId).toBe(testPageId);
+
+ const assoc = await tx
+ .select()
+ .from(maintenancesToPageComponents)
+ .where(eq(maintenancesToPageComponents.maintenanceId, record.id))
+ .all();
+ expect(assoc.map((a) => a.pageComponentId)).toEqual([
+ testPageComponentId,
+ ]);
+
+ await expectAuditRow({
+ workspaceId: teamCtx.workspace.id,
+ action: "maintenance.create",
+ entityType: "maintenance",
+ entityId: record.id,
+ db: tx,
+ });
+ });
});
- test("throws ZodError when from >= to", async () => {
- const now = new Date();
- await expect(
- createMaintenance({
- ctx: teamCtx,
- input: {
- title: `${TEST_PREFIX}-range`,
- message: "m",
- from: now,
- to: now,
- pageId: testPageId,
- pageComponentIds: [],
- },
- }),
- ).rejects.toThrow();
+ test("throws when page is in another workspace", async () => {
+ await withTestTransaction(async (tx) => {
+ const range = futureRange();
+ await expect(
+ createMaintenance({
+ ctx: { ...freeCtx, db: tx },
+ input: {
+ title: `${TEST_PREFIX}-cross-ws`,
+ message: "m",
+ ...range,
+ pageId: testPageId,
+ pageComponentIds: [],
+ },
+ }),
+ ).rejects.toBeInstanceOf(NotFoundError);
+ });
});
- test("deduplicates pageComponentIds", async () => {
- // Duplicate ids in the input would violate the composite PK on
- // `maintenances_to_page_components` if not deduped. Guard against a
- // regression where the `Set` in `validatePageComponentIds` is dropped.
- const record = await createMaintenance({
- ctx: teamCtx,
- input: {
- title: `${TEST_PREFIX}-dedupe`,
- message: "m",
- ...futureRange(),
- pageId: testPageId,
- pageComponentIds: [testPageComponentId, testPageComponentId],
- },
+ test("throws ZodError when from >= to", async () => {
+ await withTestTransaction(async (tx) => {
+ const now = new Date();
+ await expect(
+ createMaintenance({
+ ctx: { ...teamCtx, db: tx },
+ input: {
+ title: `${TEST_PREFIX}-range`,
+ message: "m",
+ from: now,
+ to: now,
+ pageId: testPageId,
+ pageComponentIds: [],
+ },
+ }),
+ ).rejects.toThrow();
});
-
- const assoc = await db
- .select()
- .from(maintenancesToPageComponents)
- .where(eq(maintenancesToPageComponents.maintenanceId, record.id))
- .all();
- expect(assoc).toHaveLength(1);
- expect(assoc[0].pageComponentId).toBe(testPageComponentId);
-
- createdMaintenanceIds.push(record.id);
});
- test("throws ConflictError when components span multiple pages", async () => {
- await expect(
- createMaintenance({
- ctx: teamCtx,
+ test("deduplicates pageComponentIds", async () => {
+ await withTestTransaction(async (tx) => {
+ // Duplicate ids in the input would violate the composite PK on
+ // `maintenances_to_page_components` if not deduped. Guard against a
+ // regression where the `Set` in `validatePageComponentIds` is dropped.
+ const record = await createMaintenance({
+ ctx: { ...teamCtx, db: tx },
input: {
- title: `${TEST_PREFIX}-mixed-pages`,
+ title: `${TEST_PREFIX}-dedupe`,
message: "m",
...futureRange(),
pageId: testPageId,
- pageComponentIds: [testPageComponentId, otherPageComponentId],
+ pageComponentIds: [testPageComponentId, testPageComponentId],
},
- }),
- ).rejects.toBeInstanceOf(ConflictError);
+ });
+
+ const assoc = await tx
+ .select()
+ .from(maintenancesToPageComponents)
+ .where(eq(maintenancesToPageComponents.maintenanceId, record.id))
+ .all();
+ expect(assoc).toHaveLength(1);
+ expect(assoc[0].pageComponentId).toBe(testPageComponentId);
+ });
+ });
+
+ test("throws ConflictError when components span multiple pages", async () => {
+ await withTestTransaction(async (tx) => {
+ await expect(
+ createMaintenance({
+ ctx: { ...teamCtx, db: tx },
+ input: {
+ title: `${TEST_PREFIX}-mixed-pages`,
+ message: "m",
+ ...futureRange(),
+ pageId: testPageId,
+ pageComponentIds: [testPageComponentId, otherPageComponentId],
+ },
+ }),
+ ).rejects.toBeInstanceOf(ConflictError);
+ });
});
});
describe("updateMaintenance", () => {
test("updates title + replaces associations", async () => {
- const record = await createMaintenance({
- ctx: teamCtx,
- input: {
- title: `${TEST_PREFIX}-update`,
- message: "m",
- ...futureRange(),
- pageId: testPageId,
- pageComponentIds: [testPageComponentId],
- },
- });
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ const record = await createMaintenance({
+ ctx,
+ input: {
+ title: `${TEST_PREFIX}-update`,
+ message: "m",
+ ...futureRange(),
+ pageId: testPageId,
+ pageComponentIds: [testPageComponentId],
+ },
+ });
- const updated = await updateMaintenance({
- ctx: teamCtx,
- input: {
- id: record.id,
- title: `${TEST_PREFIX}-update-renamed`,
- pageComponentIds: [],
- },
+ const updated = await updateMaintenance({
+ ctx,
+ input: {
+ id: record.id,
+ title: `${TEST_PREFIX}-update-renamed`,
+ pageComponentIds: [],
+ },
+ });
+ expect(updated.title).toBe(`${TEST_PREFIX}-update-renamed`);
+
+ const assoc = await tx
+ .select()
+ .from(maintenancesToPageComponents)
+ .where(eq(maintenancesToPageComponents.maintenanceId, record.id))
+ .all();
+ expect(assoc).toHaveLength(0);
});
- expect(updated.title).toBe(`${TEST_PREFIX}-update-renamed`);
-
- const assoc = await db
- .select()
- .from(maintenancesToPageComponents)
- .where(eq(maintenancesToPageComponents.maintenanceId, record.id))
- .all();
- expect(assoc).toHaveLength(0);
-
- createdMaintenanceIds.push(record.id);
});
test("throws NotFoundError for cross-workspace update", async () => {
- const record = await createMaintenance({
- ctx: teamCtx,
- input: {
- title: `${TEST_PREFIX}-cross-ws-update`,
- message: "m",
- ...futureRange(),
- pageId: testPageId,
- pageComponentIds: [],
- },
+ await withTestTransaction(async (tx) => {
+ const record = await createMaintenance({
+ ctx: { ...teamCtx, db: tx },
+ input: {
+ title: `${TEST_PREFIX}-cross-ws-update`,
+ message: "m",
+ ...futureRange(),
+ pageId: testPageId,
+ pageComponentIds: [],
+ },
+ });
+
+ await expect(
+ updateMaintenance({
+ ctx: { ...freeCtx, db: tx },
+ input: { id: record.id, title: "blocked" },
+ }),
+ ).rejects.toBeInstanceOf(NotFoundError);
});
-
- await expect(
- updateMaintenance({
- ctx: freeCtx,
- input: { id: record.id, title: "blocked" },
- }),
- ).rejects.toBeInstanceOf(NotFoundError);
-
- createdMaintenanceIds.push(record.id);
});
test("rejects partial update that crosses the from/to invariant", async () => {
- // The Zod refine on CreateMaintenanceInput only catches simultaneous
- // `{from, to}` submissions. A partial update that moves only `to`
- // earlier than the stored `from` has to be rejected by the service's
- // own effective-range check. Regression guard for that code path.
- const record = await createMaintenance({
- ctx: teamCtx,
- input: {
- title: `${TEST_PREFIX}-range-update`,
- message: "m",
- ...futureRange(60 * 60 * 1000),
- pageId: testPageId,
- pageComponentIds: [],
- },
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ // The Zod refine on CreateMaintenanceInput only catches simultaneous
+ // `{from, to}` submissions. A partial update that moves only `to`
+ // earlier than the stored `from` has to be rejected by the service's
+ // own effective-range check. Regression guard for that code path.
+ const record = await createMaintenance({
+ ctx,
+ input: {
+ title: `${TEST_PREFIX}-range-update`,
+ message: "m",
+ ...futureRange(60 * 60 * 1000),
+ pageId: testPageId,
+ pageComponentIds: [],
+ },
+ });
+
+ await expect(
+ updateMaintenance({
+ ctx,
+ input: { id: record.id, to: new Date(Date.now() - 60 * 60 * 1000) },
+ }),
+ ).rejects.toBeInstanceOf(ConflictError);
});
-
- await expect(
- updateMaintenance({
- ctx: teamCtx,
- input: { id: record.id, to: new Date(Date.now() - 60 * 60 * 1000) },
- }),
- ).rejects.toBeInstanceOf(ConflictError);
-
- createdMaintenanceIds.push(record.id);
});
test("throws ConflictError when pageComponentIds span multiple pages", async () => {
- const record = await createMaintenance({
- ctx: teamCtx,
- input: {
- title: `${TEST_PREFIX}-update-mixed-pages`,
- message: "m",
- ...futureRange(),
- pageId: testPageId,
- pageComponentIds: [testPageComponentId],
- },
- });
-
- await expect(
- updateMaintenance({
- ctx: teamCtx,
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ const record = await createMaintenance({
+ ctx,
input: {
- id: record.id,
- pageComponentIds: [testPageComponentId, otherPageComponentId],
+ title: `${TEST_PREFIX}-update-mixed-pages`,
+ message: "m",
+ ...futureRange(),
+ pageId: testPageId,
+ pageComponentIds: [testPageComponentId],
},
- }),
- ).rejects.toBeInstanceOf(ConflictError);
-
- createdMaintenanceIds.push(record.id);
+ });
+
+ await expect(
+ updateMaintenance({
+ ctx,
+ input: {
+ id: record.id,
+ pageComponentIds: [testPageComponentId, otherPageComponentId],
+ },
+ }),
+ ).rejects.toBeInstanceOf(ConflictError);
+ });
});
});
describe("deleteMaintenance", () => {
test("cascades associations", async () => {
- const record = await createMaintenance({
- ctx: teamCtx,
- input: {
- title: `${TEST_PREFIX}-delete`,
- message: "m",
- ...futureRange(),
- pageId: testPageId,
- pageComponentIds: [testPageComponentId],
- },
- });
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ const record = await createMaintenance({
+ ctx,
+ input: {
+ title: `${TEST_PREFIX}-delete`,
+ message: "m",
+ ...futureRange(),
+ pageId: testPageId,
+ pageComponentIds: [testPageComponentId],
+ },
+ });
+
+ await deleteMaintenance({ ctx, input: { id: record.id } });
- await deleteMaintenance({ ctx: teamCtx, input: { id: record.id } });
-
- const remaining = await db
- .select()
- .from(maintenance)
- .where(eq(maintenance.id, record.id))
- .all();
- const remainingAssoc = await db
- .select()
- .from(maintenancesToPageComponents)
- .where(eq(maintenancesToPageComponents.maintenanceId, record.id))
- .all();
- expect(remaining).toHaveLength(0);
- expect(remainingAssoc).toHaveLength(0);
+ const remainingAssoc = await tx
+ .select()
+ .from(maintenancesToPageComponents)
+ .where(eq(maintenancesToPageComponents.maintenanceId, record.id))
+ .all();
+ expect(remainingAssoc).toHaveLength(0);
+ });
});
});
describe("list / get", () => {
test("respects workspace isolation", async () => {
- const record = await createMaintenance({
- ctx: teamCtx,
- input: {
- title: `${TEST_PREFIX}-isolation`,
- message: "m",
- ...futureRange(),
- pageId: testPageId,
- pageComponentIds: [],
- },
- });
+ await withTestTransaction(async (tx) => {
+ const teamCtxTx = { ...teamCtx, db: tx };
+ const freeCtxTx = { ...freeCtx, db: tx };
+ const record = await createMaintenance({
+ ctx: teamCtxTx,
+ input: {
+ title: `${TEST_PREFIX}-isolation`,
+ message: "m",
+ ...futureRange(),
+ pageId: testPageId,
+ pageComponentIds: [],
+ },
+ });
- await expect(
- getMaintenance({ ctx: freeCtx, input: { id: record.id } }),
- ).rejects.toBeInstanceOf(NotFoundError);
-
- const { items } = await listMaintenances({
- ctx: freeCtx,
- input: {
- limit: 100,
- offset: 0,
- pageId: testPageId,
- order: "desc",
- },
- });
- expect(items.find((m) => m.id === record.id)).toBeUndefined();
+ await expect(
+ getMaintenance({ ctx: freeCtxTx, input: { id: record.id } }),
+ ).rejects.toBeInstanceOf(NotFoundError);
- createdMaintenanceIds.push(record.id);
+ const { items } = await listMaintenances({
+ ctx: freeCtxTx,
+ input: {
+ limit: 100,
+ offset: 0,
+ pageId: testPageId,
+ order: "desc",
+ },
+ });
+ expect(items.find((m) => m.id === record.id)).toBeUndefined();
+ });
});
test("list returns totalSize and enriched relations", async () => {
- const record = await createMaintenance({
- ctx: teamCtx,
- input: {
- title: `${TEST_PREFIX}-list-enrich`,
- message: "m",
- ...futureRange(),
- pageId: testPageId,
- pageComponentIds: [testPageComponentId],
- },
- });
-
- const full = await getMaintenance({
- ctx: teamCtx,
- input: { id: record.id },
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ const record = await createMaintenance({
+ ctx,
+ input: {
+ title: `${TEST_PREFIX}-list-enrich`,
+ message: "m",
+ ...futureRange(),
+ pageId: testPageId,
+ pageComponentIds: [testPageComponentId],
+ },
+ });
+
+ const full = await getMaintenance({
+ ctx,
+ input: { id: record.id },
+ });
+ expect(full.pageComponents.map((c) => c.id)).toEqual([
+ testPageComponentId,
+ ]);
+ expect(full.pageComponentIds).toEqual([testPageComponentId]);
});
- expect(full.pageComponents.map((c) => c.id)).toEqual([testPageComponentId]);
- expect(full.pageComponentIds).toEqual([testPageComponentId]);
-
- createdMaintenanceIds.push(record.id);
});
});
describe("notifyMaintenance", () => {
test("throws when maintenance belongs to another workspace", async () => {
- const record = await createMaintenance({
- ctx: teamCtx,
- input: {
- title: `${TEST_PREFIX}-notify-cross-ws`,
- message: "m",
- ...futureRange(),
- pageId: testPageId,
- pageComponentIds: [],
- },
+ await withTestTransaction(async (tx) => {
+ const record = await createMaintenance({
+ ctx: { ...teamCtx, db: tx },
+ input: {
+ title: `${TEST_PREFIX}-notify-cross-ws`,
+ message: "m",
+ ...futureRange(),
+ pageId: testPageId,
+ pageComponentIds: [],
+ },
+ });
+
+ await expect(
+ notifyMaintenance({
+ ctx: { ...freeCtx, db: tx },
+ input: { maintenanceId: record.id },
+ }),
+ ).rejects.toBeInstanceOf(ForbiddenError);
});
-
- await expect(
- notifyMaintenance({
- ctx: freeCtx,
- input: { maintenanceId: record.id },
- }),
- ).rejects.toBeInstanceOf(ForbiddenError);
-
- createdMaintenanceIds.push(record.id);
});
});
describe("slack actor path", () => {
test("createMaintenance succeeds with a slack actor", async () => {
- const ctx = makeSlackCtx(teamCtx.workspace, {
- teamId: "T123",
- slackUserId: "U123",
- });
- const record = await createMaintenance({
- ctx,
- input: {
- title: `${TEST_PREFIX}-slack`,
- message: "scheduled via slack",
- ...futureRange(),
- pageId: testPageId,
- pageComponentIds: [],
- },
- });
- await expectAuditRow({
- workspaceId: teamCtx.workspace.id,
- action: "maintenance.create",
- entityType: "maintenance",
- entityId: record.id,
- actorType: "slack",
+ await withTestTransaction(async (tx) => {
+ const ctx = {
+ ...makeSlackCtx(teamCtx.workspace, {
+ teamId: "T123",
+ slackUserId: "U123",
+ }),
+ db: tx,
+ };
+ const record = await createMaintenance({
+ ctx,
+ input: {
+ title: `${TEST_PREFIX}-slack`,
+ message: "scheduled via slack",
+ ...futureRange(),
+ pageId: testPageId,
+ pageComponentIds: [],
+ },
+ });
+ await expectAuditRow({
+ workspaceId: teamCtx.workspace.id,
+ action: "maintenance.create",
+ entityType: "maintenance",
+ entityId: record.id,
+ actorType: "slack",
+ db: tx,
+ });
});
- createdMaintenanceIds.push(record.id);
});
});
diff --git a/packages/services/src/member/__tests__/member.test.ts b/packages/services/src/member/__tests__/member.test.ts
new file mode 100644
index 000000000..46e13b160
--- /dev/null
+++ b/packages/services/src/member/__tests__/member.test.ts
@@ -0,0 +1,329 @@
+import { afterAll, beforeAll, describe, expect, test } from "bun:test";
+import { and, db, eq } from "@openstatus/db";
+import { user, usersToWorkspaces } from "@openstatus/db/src/schema";
+
+import { deleteMember, listMembers } from "..";
+import {
+ SEEDED_WORKSPACE_FREE_ID,
+ SEEDED_WORKSPACE_TEAM_ID,
+} from "../../../test/fixtures";
+import {
+ expectAuditRow,
+ loadSeededWorkspace,
+ makeSystemCtx,
+ makeUserCtx,
+ readAuditLog,
+ withTestTransaction,
+} from "../../../test/helpers";
+import type { ServiceContext } from "../../context";
+import { NotFoundError, PreconditionFailedError } from "../../errors";
+
+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;
+
+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);
+ }
+});
+
+describe("listMembers", () => {
+ test("returns parsed rows with user + role", async () => {
+ await withTestTransaction(async (tx) => {
+ const rows = await listMembers({ ctx: { ...teamCtx, db: tx } });
+ const ids = rows.map((r) => r.user.id);
+ expect(ids).toContain(OWNER_USER_ID);
+ expect(rows.find((r) => r.user.id === OWNER_USER_ID)?.role).toBe("owner");
+ });
+ });
+});
+
+describe("deleteMember", () => {
+ test("owner removes another member, audit row written", async () => {
+ await withTestTransaction(async (tx) => {
+ await deleteMember({
+ ctx: { ...teamCtx, db: tx },
+ input: { userId: VICTIM_USER_ID },
+ });
+
+ const stillThere = await tx
+ .select()
+ .from(usersToWorkspaces)
+ .where(
+ and(
+ eq(usersToWorkspaces.workspaceId, SEEDED_WORKSPACE_TEAM_ID),
+ eq(usersToWorkspaces.userId, VICTIM_USER_ID),
+ ),
+ )
+ .get();
+ expect(stillThere).toBeUndefined();
+
+ await expectAuditRow({
+ workspaceId: SEEDED_WORKSPACE_TEAM_ID,
+ action: "member.delete",
+ entityType: "member",
+ entityId: VICTIM_USER_ID,
+ db: tx,
+ });
+ });
+ });
+
+ test("non-owner caller is rejected with PRECONDITION_FAILED", async () => {
+ await withTestTransaction(async (tx) => {
+ const nonOwnerCtx = {
+ ...makeUserCtx(teamCtx.workspace, { userId: NON_OWNER_USER_ID }),
+ db: tx,
+ };
+ let thrown: unknown;
+ try {
+ await deleteMember({
+ ctx: nonOwnerCtx,
+ input: { userId: VICTIM_USER_ID },
+ });
+ } catch (e) {
+ thrown = e;
+ }
+ expect(thrown).toBeInstanceOf(PreconditionFailedError);
+ });
+ });
+
+ test("self-removal is rejected", async () => {
+ await withTestTransaction(async (tx) => {
+ let thrown: unknown;
+ try {
+ await deleteMember({
+ ctx: { ...teamCtx, db: tx },
+ input: { userId: OWNER_USER_ID },
+ });
+ } catch (e) {
+ thrown = e;
+ }
+ expect(thrown).toBeInstanceOf(PreconditionFailedError);
+ });
+ });
+
+ test("system actor cannot remove members", async () => {
+ await withTestTransaction(async (tx) => {
+ const sysCtx = {
+ ...makeSystemCtx(teamCtx.workspace, { job: "test" }),
+ db: tx,
+ };
+ let thrown: unknown;
+ try {
+ await deleteMember({
+ ctx: sysCtx,
+ input: { userId: VICTIM_USER_ID },
+ });
+ } catch (e) {
+ thrown = e;
+ }
+ expect(thrown).toBeInstanceOf(PreconditionFailedError);
+ });
+ });
+
+ 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);
+ // Pretend caller belongs to free workspace but actually doesn't —
+ // the membership lookup will miss and throw NotFoundError.
+ const stranger = {
+ ...makeUserCtx(free, { userId: 9_999_999 }),
+ db: tx,
+ };
+ let thrown: unknown;
+ try {
+ await deleteMember({
+ ctx: stranger,
+ input: { userId: VICTIM_USER_ID },
+ });
+ } catch (e) {
+ thrown = e;
+ }
+ expect(thrown).toBeInstanceOf(NotFoundError);
+ });
+ });
+
+ test("target userId with no membership in workspace is a silent no-op", async () => {
+ await withTestTransaction(async (tx) => {
+ // Owner caller, but the target has no users_to_workspaces row at all.
+ // DELETE matches nothing → no throw, no audit row.
+ const NEVER_MEMBER_USER_ID = 9_876_543;
+ await deleteMember({
+ ctx: { ...teamCtx, db: tx },
+ input: { userId: NEVER_MEMBER_USER_ID },
+ });
+
+ const rows = await readAuditLog({
+ workspaceId: SEEDED_WORKSPACE_TEAM_ID,
+ entityType: "member",
+ entityId: NEVER_MEMBER_USER_ID,
+ db: tx,
+ });
+ expect(rows).toHaveLength(0);
+ });
+ });
+
+ test("target user in another workspace is a silent no-op (workspace-scoped DELETE)", async () => {
+ await withTestTransaction(async (tx) => {
+ // 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);
+ await tx
+ .insert(usersToWorkspaces)
+ .values({
+ workspaceId: free.id,
+ userId: OWNER_USER_ID,
+ role: "owner",
+ })
+ .onConflictDoUpdate({
+ target: [usersToWorkspaces.userId, usersToWorkspaces.workspaceId],
+ set: { role: "owner" },
+ });
+
+ await deleteMember({
+ ctx: { ...makeUserCtx(free, { userId: OWNER_USER_ID }), db: tx },
+ input: { userId: VICTIM_USER_ID },
+ });
+
+ const stillThere = await tx
+ .select()
+ .from(usersToWorkspaces)
+ .where(
+ and(
+ eq(usersToWorkspaces.workspaceId, SEEDED_WORKSPACE_TEAM_ID),
+ eq(usersToWorkspaces.userId, VICTIM_USER_ID),
+ ),
+ )
+ .get();
+ expect(stillThere).toBeDefined();
+ });
+ });
+});
diff --git a/packages/services/src/member/delete.ts b/packages/services/src/member/delete.ts
new file mode 100644
index 000000000..48e64d9e5
--- /dev/null
+++ b/packages/services/src/member/delete.ts
@@ -0,0 +1,97 @@
+import { and, eq } from "@openstatus/db";
+import { usersToWorkspaces } from "@openstatus/db/src/schema";
+import { z } from "zod";
+
+import { emitAudit } from "../audit";
+import { type ServiceContext, withTransaction } from "../context";
+import { NotFoundError, PreconditionFailedError } from "../errors";
+import { DeleteMemberInput } from "./schemas";
+
+// Composite-PK rows: drizzle's createSelectSchema would flatten the join,
+// but the membership row has no auto-generated columns we'd want to drop
+// from a snapshot. Inline parser keeps the audit `before` shape stable
+// even if a column is added to `users_to_workspaces` later.
+const memberRowSnapshot = z.object({
+ userId: z.number(),
+ workspaceId: z.number(),
+ role: z.string(),
+ createdAt: z.coerce.date().nullable(),
+});
+
+/**
+ * Delete a member's workspace association. Idempotent on the target row —
+ * if the target user has no membership in the caller's workspace (wrong id,
+ * already removed, or scoped to a different workspace), the call succeeds
+ * silently and no audit row is emitted. This matches the workspace-filtered
+ * DELETE semantics inherited from the legacy router.
+ *
+ * Authorization rules preserved from the legacy router:
+ * - only the caller's own membership row is consulted; the `owner` role is
+ * required to remove anyone else;
+ * - an owner cannot remove themselves (would orphan the workspace).
+ *
+ * Both role-failure and self-removal surface as `PRECONDITION_FAILED` to
+ * match the existing tRPC contract — these are state-based rejections, not
+ * authz failures in the sense of "you lack any access to this workspace."
+ *
+ * Only fires when the actor is an openstatus user: removing another user is
+ * not something a system / apiKey / webhook actor should do today.
+ */
+export async function deleteMember(args: {
+ ctx: ServiceContext;
+ input: DeleteMemberInput;
+}): Promise<void> {
+ const { ctx } = args;
+ const input = DeleteMemberInput.parse(args.input);
+
+ if (ctx.actor.type !== "user") {
+ throw new PreconditionFailedError(
+ "Only user actors can remove workspace members",
+ );
+ }
+ const callerId = ctx.actor.userId;
+
+ await withTransaction(ctx, async (tx) => {
+ const caller = await tx.query.usersToWorkspaces.findFirst({
+ where: and(
+ eq(usersToWorkspaces.userId, callerId),
+ eq(usersToWorkspaces.workspaceId, ctx.workspace.id),
+ ),
+ });
+
+ if (!caller) {
+ throw new NotFoundError("membership", callerId);
+ }
+
+ if (caller.role !== "owner") {
+ throw new PreconditionFailedError(
+ "Not authorized to remove user from workspace",
+ );
+ }
+
+ if (input.userId === callerId) {
+ throw new PreconditionFailedError(
+ "Cannot remove yourself from workspace",
+ );
+ }
+
+ const [removed] = await tx
+ .delete(usersToWorkspaces)
+ .where(
+ and(
+ eq(usersToWorkspaces.workspaceId, ctx.workspace.id),
+ eq(usersToWorkspaces.userId, input.userId),
+ ),
+ )
+ .returning();
+
+ if (!removed) return;
+
+ await emitAudit(tx, ctx, {
+ action: "member.delete",
+ entityType: "member",
+ entityId: input.userId,
+ before: memberRowSnapshot.parse(removed),
+ });
+ });
+}
diff --git a/packages/services/src/member/index.ts b/packages/services/src/member/index.ts
new file mode 100644
index 000000000..1eb9ab8bd
--- /dev/null
+++ b/packages/services/src/member/index.ts
@@ -0,0 +1,3 @@
+export { deleteMember } from "./delete";
+export { listMembers, type Member } from "./list";
+export { DeleteMemberInput, ListMembersInput } from "./schemas";
diff --git a/packages/services/src/member/list.ts b/packages/services/src/member/list.ts
new file mode 100644
index 000000000..09d65c88d
--- /dev/null
+++ b/packages/services/src/member/list.ts
@@ -0,0 +1,35 @@
+import { eq } from "@openstatus/db";
+import {
+ selectUserSchema,
+ usersToWorkspaces,
+ workspaceRole,
+} from "@openstatus/db/src/schema";
+import { z } from "zod";
+
+import { type ServiceContext, getReadDb } from "../context";
+import type { ListMembersInput } from "./schemas";
+
+const memberRowSchema = z.object({
+ role: z.enum(workspaceRole),
+ createdAt: z.coerce.date(),
+ user: selectUserSchema,
+});
+
+export type Member = z.infer<typeof memberRowSchema>;
+
+export async function listMembers(args: {
+ ctx: ServiceContext;
+ input?: ListMembersInput;
+}): Promise<Member[]> {
+ const db = getReadDb(args.ctx);
+
+ const rows = await db.query.usersToWorkspaces.findMany({
+ where: eq(usersToWorkspaces.workspaceId, args.ctx.workspace.id),
+ with: { user: true },
+ });
+
+ // Preserve the router-era contract: parse each row so callers receive the
+ // same `createdAt`/`role`/`user` shape they've always consumed, and any
+ // unexpected drift in the join surfaces here rather than downstream.
+ return memberRowSchema.array().parse(rows);
+}
diff --git a/packages/services/src/member/schemas.ts b/packages/services/src/member/schemas.ts
new file mode 100644
index 000000000..7f5e6f2c7
--- /dev/null
+++ b/packages/services/src/member/schemas.ts
@@ -0,0 +1,7 @@
+import { z } from "zod";
+
+export const ListMembersInput = z.object({}).strict();
+export type ListMembersInput = z.infer<typeof ListMembersInput>;
+
+export const DeleteMemberInput = z.object({ userId: z.number().int() });
+export type DeleteMemberInput = z.infer<typeof DeleteMemberInput>;
diff --git a/packages/services/src/monitor-tag/__tests__/monitor-tag.test.ts b/packages/services/src/monitor-tag/__tests__/monitor-tag.test.ts
new file mode 100644
index 000000000..efd4c3718
--- /dev/null
+++ b/packages/services/src/monitor-tag/__tests__/monitor-tag.test.ts
@@ -0,0 +1,209 @@
+import { afterAll, beforeAll, describe, expect, test } from "bun:test";
+import { db, eq } from "@openstatus/db";
+import { monitorTag } from "@openstatus/db/src/schema";
+
+import { listMonitorTags, syncMonitorTags } from "..";
+import { SEEDED_WORKSPACE_TEAM_ID } from "../../../test/fixtures";
+import {
+ clearAuditLog,
+ loadSeededWorkspace,
+ makeUserCtx,
+ readAuditLog,
+ withTestTransaction,
+} from "../../../test/helpers";
+import type { ServiceContext } from "../../context";
+
+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();
+});
+
+describe("syncMonitorTags", () => {
+ test("creates new tags when input has no ids; emits monitor_tag.create per row", async () => {
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ const result = await syncMonitorTags({
+ ctx,
+ input: {
+ tags: [
+ { name: "alpha", color: "red" },
+ { name: "beta", color: "blue" },
+ ],
+ },
+ });
+
+ expect(result).toHaveLength(2);
+ expect(result.map((r) => r.name).sort()).toEqual(["alpha", "beta"]);
+
+ const auditRows = await readAuditLog({
+ workspaceId: SEEDED_WORKSPACE_TEAM_ID,
+ entityType: "monitor_tag",
+ db: tx,
+ });
+ const creates = auditRows.filter(
+ (r) => r.action === "monitor_tag.create",
+ );
+ expect(creates).toHaveLength(2);
+ });
+ });
+
+ test("updates an existing tag in place when id present and value changes", async () => {
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ const [{ id: existingId }] = await syncMonitorTags({
+ ctx,
+ input: { tags: [{ name: "alpha", color: "red" }] },
+ });
+ await clearAuditLog(SEEDED_WORKSPACE_TEAM_ID, { db: tx });
+
+ await syncMonitorTags({
+ ctx,
+ input: {
+ tags: [{ id: existingId, name: "alpha-renamed", color: "red" }],
+ },
+ });
+
+ const row = await tx
+ .select()
+ .from(monitorTag)
+ .where(eq(monitorTag.id, existingId))
+ .get();
+ expect(row?.name).toBe("alpha-renamed");
+
+ const auditRows = await readAuditLog({
+ workspaceId: SEEDED_WORKSPACE_TEAM_ID,
+ entityType: "monitor_tag",
+ entityId: existingId,
+ db: tx,
+ });
+ const updates = auditRows.filter(
+ (r) => r.action === "monitor_tag.update",
+ );
+ expect(updates).toHaveLength(1);
+ });
+ });
+
+ test("no-op update (same name + color) doesn't write a redundant audit row", async () => {
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ const [{ id: existingId }] = await syncMonitorTags({
+ ctx,
+ input: { tags: [{ name: "alpha", color: "red" }] },
+ });
+ await clearAuditLog(SEEDED_WORKSPACE_TEAM_ID, { db: tx });
+
+ await syncMonitorTags({
+ ctx,
+ input: { tags: [{ id: existingId, name: "alpha", color: "red" }] },
+ });
+
+ const auditRows = await readAuditLog({
+ workspaceId: SEEDED_WORKSPACE_TEAM_ID,
+ entityType: "monitor_tag",
+ entityId: existingId,
+ db: tx,
+ });
+ // emitAudit suppresses empty-diff updates — only the original
+ // create row should remain (cleared above), so zero update rows.
+ const updates = auditRows.filter(
+ (r) => r.action === "monitor_tag.update",
+ );
+ expect(updates).toHaveLength(0);
+ });
+ });
+
+ test("removes tags that aren't in the input; emits monitor_tag.delete per row", async () => {
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ const created = await syncMonitorTags({
+ ctx,
+ input: {
+ tags: [
+ { name: "alpha", color: "red" },
+ { name: "beta", color: "blue" },
+ ],
+ },
+ });
+ await clearAuditLog(SEEDED_WORKSPACE_TEAM_ID, { db: tx });
+
+ const keep = created.find((t) => t.name === "alpha");
+ if (!keep) throw new Error("seed setup failed");
+
+ await syncMonitorTags({
+ ctx,
+ input: { tags: [{ id: keep.id, name: "alpha", color: "red" }] },
+ });
+
+ const remaining = await listMonitorTags({ ctx });
+ expect(remaining.map((r) => r.name)).toEqual(["alpha"]);
+
+ const auditRows = await readAuditLog({
+ workspaceId: SEEDED_WORKSPACE_TEAM_ID,
+ entityType: "monitor_tag",
+ db: tx,
+ });
+ const deletes = auditRows.filter(
+ (r) => r.action === "monitor_tag.delete",
+ );
+ expect(deletes).toHaveLength(1);
+ });
+ });
+
+ test("create / update / delete all in one sync call", async () => {
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ const seed = await syncMonitorTags({
+ ctx,
+ input: {
+ tags: [
+ { name: "stays", color: "gray" },
+ { name: "drops", color: "gray" },
+ ],
+ },
+ });
+ await clearAuditLog(SEEDED_WORKSPACE_TEAM_ID, { db: tx });
+
+ const stays = seed.find((t) => t.name === "stays");
+ if (!stays) throw new Error("seed setup failed");
+
+ await syncMonitorTags({
+ ctx,
+ input: {
+ tags: [
+ { id: stays.id, name: "stays-renamed", color: "gray" },
+ { name: "added", color: "green" },
+ ],
+ },
+ });
+
+ const auditRows = await readAuditLog({
+ workspaceId: SEEDED_WORKSPACE_TEAM_ID,
+ entityType: "monitor_tag",
+ db: tx,
+ });
+ const byAction = auditRows.reduce<Record<string, number>>((acc, row) => {
+ acc[row.action] = (acc[row.action] ?? 0) + 1;
+ return acc;
+ }, {});
+ expect(byAction["monitor_tag.create"]).toBe(1);
+ expect(byAction["monitor_tag.update"]).toBe(1);
+ expect(byAction["monitor_tag.delete"]).toBe(1);
+ });
+ });
+});
diff --git a/packages/services/src/monitor-tag/index.ts b/packages/services/src/monitor-tag/index.ts
new file mode 100644
index 000000000..336bf7ea2
--- /dev/null
+++ b/packages/services/src/monitor-tag/index.ts
@@ -0,0 +1,3 @@
+export { listMonitorTags } from "./list";
+export { syncMonitorTags } from "./sync";
+export { ListMonitorTagsInput, SyncMonitorTagsInput } from "./schemas";
diff --git a/packages/services/src/monitor-tag/list.ts b/packages/services/src/monitor-tag/list.ts
new file mode 100644
index 000000000..a68bedd6d
--- /dev/null
+++ b/packages/services/src/monitor-tag/list.ts
@@ -0,0 +1,31 @@
+import { eq } from "@openstatus/db";
+import { monitorTag } from "@openstatus/db/src/schema";
+
+import { type DrizzleClient, type ServiceContext, getReadDb } from "../context";
+import { ListMonitorTagsInput } from "./schemas";
+
+/**
+ * List tags for the caller's workspace, with the join rows linking each
+ * tag to its monitors. Return type is drizzle's relational inference —
+ * the join target is `monitor_tag_to_monitor`, which has no exported
+ * select schema, so re-parsing through Zod here would only mirror the
+ * Drizzle inference at the cost of an extra round-trip. Flat-row services
+ * (e.g. invitation, member) do parse via `selectXSchema`; this list is
+ * deliberately the relational-query exception.
+ */
+export async function listMonitorTags(args: {
+ ctx: ServiceContext;
+ input?: ListMonitorTagsInput;
+}) {
+ ListMonitorTagsInput.parse(args.input ?? {});
+ // Cast through `DrizzleClient` so the relational `query` API preserves
+ // its inferred return type. `DB = DrizzleClient | DrizzleTx` widens
+ // the call result to `unknown` under the union; runtime is identical
+ // (both expose the same `.query.<table>.findMany` shape).
+ const db = getReadDb(args.ctx) as DrizzleClient;
+
+ return db.query.monitorTag.findMany({
+ where: eq(monitorTag.workspaceId, args.ctx.workspace.id),
+ with: { monitor: true },
+ });
+}
diff --git a/packages/services/src/monitor-tag/schemas.ts b/packages/services/src/monitor-tag/schemas.ts
new file mode 100644
index 000000000..466b47824
--- /dev/null
+++ b/packages/services/src/monitor-tag/schemas.ts
@@ -0,0 +1,15 @@
+import { z } from "zod";
+
+export const ListMonitorTagsInput = z.object({}).strict();
+export type ListMonitorTagsInput = z.infer<typeof ListMonitorTagsInput>;
+
+const tagInput = z.object({
+ id: z.number().int().optional(),
+ name: z.string(),
+ color: z.string(),
+});
+
+export const SyncMonitorTagsInput = z.object({
+ tags: z.array(tagInput),
+});
+export type SyncMonitorTagsInput = z.infer<typeof SyncMonitorTagsInput>;
diff --git a/packages/services/src/monitor-tag/sync.ts b/packages/services/src/monitor-tag/sync.ts
new file mode 100644
index 000000000..232905538
--- /dev/null
+++ b/packages/services/src/monitor-tag/sync.ts
@@ -0,0 +1,134 @@
+import { and, eq, inArray } from "@openstatus/db";
+import { monitorTag, selectMonitorTagSchema } from "@openstatus/db/src/schema";
+
+import { emitAudit } from "../audit";
+import { type ServiceContext, withTransaction } from "../context";
+import { ForbiddenError } from "../errors";
+import type { MonitorTag } from "../types";
+import { SyncMonitorTagsInput } from "./schemas";
+
+/**
+ * Reconcile the workspace's tag set with the provided list.
+ *
+ * Semantics preserved from the legacy router:
+ * - tags not present in the input (by id) are deleted;
+ * - tags with an id are updated in place (`name` + `color`);
+ * - tags without an id are inserted.
+ *
+ * Audit is emitted per row inside the same transaction — `monitor_tag`
+ * has its own create/update/delete variants in the audit union, and the
+ * `update` emit is suppressed by `emitAudit` when the diff is empty (so
+ * round-trips that re-save unchanged tags don't pollute the log).
+ */
+export async function syncMonitorTags(args: {
+ ctx: ServiceContext;
+ input: SyncMonitorTagsInput;
+}): Promise<MonitorTag[]> {
+ const { ctx } = args;
+ const { tags } = SyncMonitorTagsInput.parse(args.input);
+ const workspaceId = ctx.workspace.id;
+
+ return withTransaction(ctx, async (tx) => {
+ const existing = await tx.query.monitorTag.findMany({
+ where: eq(monitorTag.workspaceId, workspaceId),
+ });
+
+ const keepIds = new Set(
+ tags.map((t) => t.id).filter((id): id is number => id !== undefined),
+ );
+ const existingById = new Map(existing.map((t) => [t.id, t]));
+
+ const toRemove = existing.filter((t) => !keepIds.has(t.id));
+
+ if (toRemove.length > 0) {
+ await tx
+ .delete(monitorTag)
+ .where(
+ and(
+ eq(monitorTag.workspaceId, workspaceId),
+ inArray(
+ monitorTag.id,
+ toRemove.map((t) => t.id),
+ ),
+ ),
+ )
+ .run();
+
+ for (const removed of toRemove) {
+ await emitAudit(tx, ctx, {
+ action: "monitor_tag.delete",
+ entityType: "monitor_tag",
+ entityId: removed.id,
+ before: selectMonitorTagSchema.parse(removed),
+ });
+ }
+ }
+
+ const results: MonitorTag[] = [];
+ for (const tag of tags) {
+ if (tag.id !== undefined) {
+ const before = existingById.get(tag.id);
+
+ // Caller passed an id that doesn't belong to this workspace.
+ // Fail-closed: throwing rolls back the surrounding transaction
+ // (including the earlier deletions), rather than letting a
+ // partial sync commit when the input is malformed.
+ if (!before) {
+ throw new ForbiddenError("Invalid monitor tag IDs.");
+ }
+
+ const updated = await tx
+ .update(monitorTag)
+ .set({
+ name: tag.name,
+ color: tag.color,
+ updatedAt: new Date(),
+ })
+ .where(
+ and(
+ eq(monitorTag.workspaceId, workspaceId),
+ eq(monitorTag.id, tag.id),
+ ),
+ )
+ .returning()
+ .get();
+
+ // libSQL's HTTP transport can omit RETURNING rows when the UPDATE
+ // doesn't change any column values; ownership was already proven
+ // via `before`, so fall back to it for the post-image.
+ const parsed = selectMonitorTagSchema.parse(updated ?? before);
+ results.push(parsed);
+
+ await emitAudit(tx, ctx, {
+ action: "monitor_tag.update",
+ entityType: "monitor_tag",
+ entityId: parsed.id,
+ before: selectMonitorTagSchema.parse(before),
+ after: parsed,
+ });
+ } else {
+ const created = await tx
+ .insert(monitorTag)
+ .values({
+ name: tag.name,
+ color: tag.color,
+ workspaceId,
+ })
+ .returning()
+ .get();
+
+ const parsed = selectMonitorTagSchema.parse(created);
+ results.push(parsed);
+
+ await emitAudit(tx, ctx, {
+ action: "monitor_tag.create",
+ entityType: "monitor_tag",
+ entityId: parsed.id,
+ after: parsed,
+ });
+ }
+ }
+
+ return results;
+ });
+}
diff --git a/packages/services/src/monitor/__tests__/monitor.test.ts b/packages/services/src/monitor/__tests__/monitor.test.ts
index ee04acece..9c6697a62 100644
--- a/packages/services/src/monitor/__tests__/monitor.test.ts
+++ b/packages/services/src/monitor/__tests__/monitor.test.ts
@@ -1,11 +1,4 @@
-import {
- afterAll,
- beforeAll,
- beforeEach,
- describe,
- expect,
- test,
-} from "bun:test";
+import { afterAll, beforeAll, describe, expect, test } from "bun:test";
import { db, eq, inArray } from "@openstatus/db";
import {
monitor,
@@ -20,10 +13,10 @@ import {
SEEDED_WORKSPACE_TEAM_ID,
} from "../../../test/fixtures";
import {
- clearAuditLog,
expectAuditRow,
loadSeededWorkspace,
makeUserCtx,
+ withTestTransaction,
} from "../../../test/helpers";
import type { ServiceContext } from "../../context";
import { ForbiddenError, NotFoundError } from "../../errors";
@@ -40,7 +33,6 @@ let teamCtx: ServiceContext;
let freeCtx: ServiceContext;
let testTagId: number;
let testNotificationId: number;
-const createdMonitorIds: number[] = [];
beforeAll(async () => {
const team = await loadSeededWorkspace(SEEDED_WORKSPACE_TEAM_ID);
@@ -73,12 +65,6 @@ beforeAll(async () => {
});
afterAll(async () => {
- if (createdMonitorIds.length > 0) {
- await db
- .delete(monitor)
- .where(inArray(monitor.id, createdMonitorIds))
- .catch(() => undefined);
- }
await db
.delete(monitorTag)
.where(eq(monitorTag.id, testTagId))
@@ -89,462 +75,478 @@ afterAll(async () => {
.catch(() => undefined);
});
-beforeEach(async () => {
- await clearAuditLog(teamCtx.workspace.id);
- await clearAuditLog(freeCtx.workspace.id);
-});
-
-function track(id: number) {
- createdMonitorIds.push(id);
- return id;
-}
-
describe("createMonitor", () => {
test("http happy path — stores defaults + emits audit", async () => {
- const row = await createMonitor({
- ctx: teamCtx,
- input: {
- name: `${TEST_PREFIX}-http`,
- jobType: "http",
- url: "https://example.com",
- method: "GET",
- headers: [],
- assertions: [],
- active: false,
- },
- });
- track(row.id);
-
- expect(row.jobType).toBe("http");
- expect(row.url).toBe("https://example.com");
- expect(row.regions.length).toBeGreaterThan(0);
-
- await expectAuditRow({
- workspaceId: teamCtx.workspace.id,
- action: "monitor.create",
- entityType: "monitor",
- entityId: row.id,
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ const row = await createMonitor({
+ ctx,
+ input: {
+ name: `${TEST_PREFIX}-http`,
+ jobType: "http",
+ url: "https://example.com",
+ method: "GET",
+ headers: [],
+ assertions: [],
+ active: false,
+ },
+ });
+
+ expect(row.jobType).toBe("http");
+ expect(row.url).toBe("https://example.com");
+ expect(row.regions.length).toBeGreaterThan(0);
+
+ await expectAuditRow({
+ workspaceId: teamCtx.workspace.id,
+ action: "monitor.create",
+ entityType: "monitor",
+ entityId: row.id,
+ db: tx,
+ });
});
});
test("tcp happy path", async () => {
- const row = await createMonitor({
- ctx: teamCtx,
- input: {
- name: `${TEST_PREFIX}-tcp`,
- jobType: "tcp",
- url: "example.com:443",
- method: "GET",
- headers: [],
- assertions: [],
- active: false,
- },
+ await withTestTransaction(async (tx) => {
+ const row = await createMonitor({
+ ctx: { ...teamCtx, db: tx },
+ input: {
+ name: `${TEST_PREFIX}-tcp`,
+ jobType: "tcp",
+ url: "example.com:443",
+ method: "GET",
+ headers: [],
+ assertions: [],
+ active: false,
+ },
+ });
+ expect(row.jobType).toBe("tcp");
});
- track(row.id);
- expect(row.jobType).toBe("tcp");
});
test("dns happy path", async () => {
- const row = await createMonitor({
- ctx: teamCtx,
- input: {
- name: `${TEST_PREFIX}-dns`,
- jobType: "dns",
- url: "example.com",
- method: "GET",
- headers: [],
- assertions: [
- {
- version: "v1",
- type: "dnsRecord",
- key: "A",
- compare: "eq",
- target: "1.1.1.1",
- },
- ],
- active: false,
- },
+ await withTestTransaction(async (tx) => {
+ const row = await createMonitor({
+ ctx: { ...teamCtx, db: tx },
+ input: {
+ name: `${TEST_PREFIX}-dns`,
+ jobType: "dns",
+ url: "example.com",
+ method: "GET",
+ headers: [],
+ assertions: [
+ {
+ version: "v1",
+ type: "dnsRecord",
+ key: "A",
+ compare: "eq",
+ target: "1.1.1.1",
+ },
+ ],
+ active: false,
+ },
+ });
+ expect(row.jobType).toBe("dns");
});
- track(row.id);
- expect(row.jobType).toBe("dns");
});
});
describe("deleteMonitor", () => {
test("soft-deletes + removes tag / notifier associations", async () => {
- const row = await createMonitor({
- ctx: teamCtx,
- input: {
- name: `${TEST_PREFIX}-delete`,
- jobType: "http",
- url: "https://example.com",
- method: "GET",
- headers: [],
- assertions: [],
- active: false,
- },
- });
- track(row.id);
- // Attach relations.
- await db
- .insert(monitorTagsToMonitors)
- .values({ monitorId: row.id, monitorTagId: testTagId });
- await db.insert(notificationsToMonitors).values({
- monitorId: row.id,
- notificationId: testNotificationId,
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ const row = await createMonitor({
+ ctx,
+ input: {
+ name: `${TEST_PREFIX}-delete`,
+ jobType: "http",
+ url: "https://example.com",
+ method: "GET",
+ headers: [],
+ assertions: [],
+ active: false,
+ },
+ });
+ // Attach relations.
+ await tx
+ .insert(monitorTagsToMonitors)
+ .values({ monitorId: row.id, monitorTagId: testTagId });
+ await tx.insert(notificationsToMonitors).values({
+ monitorId: row.id,
+ notificationId: testNotificationId,
+ });
+
+ await deleteMonitor({ ctx, input: { id: row.id } });
+
+ const after = await tx
+ .select()
+ .from(monitor)
+ .where(eq(monitor.id, row.id))
+ .get();
+ expect(after?.deletedAt).toBeInstanceOf(Date);
+ expect(after?.active).toBe(false);
+
+ const tagAssoc = await tx
+ .select()
+ .from(monitorTagsToMonitors)
+ .where(eq(monitorTagsToMonitors.monitorId, row.id))
+ .all();
+ const notifAssoc = await tx
+ .select()
+ .from(notificationsToMonitors)
+ .where(eq(notificationsToMonitors.monitorId, row.id))
+ .all();
+ expect(tagAssoc).toHaveLength(0);
+ expect(notifAssoc).toHaveLength(0);
});
-
- await deleteMonitor({ ctx: teamCtx, input: { id: row.id } });
-
- const after = await db
- .select()
- .from(monitor)
- .where(eq(monitor.id, row.id))
- .get();
- expect(after?.deletedAt).toBeInstanceOf(Date);
- expect(after?.active).toBe(false);
-
- const tagAssoc = await db
- .select()
- .from(monitorTagsToMonitors)
- .where(eq(monitorTagsToMonitors.monitorId, row.id))
- .all();
- const notifAssoc = await db
- .select()
- .from(notificationsToMonitors)
- .where(eq(notificationsToMonitors.monitorId, row.id))
- .all();
- expect(tagAssoc).toHaveLength(0);
- expect(notifAssoc).toHaveLength(0);
});
test("throws NotFoundError for cross-workspace delete", async () => {
- const row = await createMonitor({
- ctx: teamCtx,
- input: {
- name: `${TEST_PREFIX}-cross-ws-delete`,
- jobType: "http",
- url: "https://example.com",
- method: "GET",
- headers: [],
- assertions: [],
- active: false,
- },
+ await withTestTransaction(async (tx) => {
+ const row = await createMonitor({
+ ctx: { ...teamCtx, db: tx },
+ input: {
+ name: `${TEST_PREFIX}-cross-ws-delete`,
+ jobType: "http",
+ url: "https://example.com",
+ method: "GET",
+ headers: [],
+ assertions: [],
+ active: false,
+ },
+ });
+ await expect(
+ deleteMonitor({ ctx: { ...freeCtx, db: tx }, input: { id: row.id } }),
+ ).rejects.toBeInstanceOf(NotFoundError);
});
- track(row.id);
- await expect(
- deleteMonitor({ ctx: freeCtx, input: { id: row.id } }),
- ).rejects.toBeInstanceOf(NotFoundError);
});
test("second delete returns NotFoundError (idempotency guard)", async () => {
- // Regression for the Cubic P2 fix: `getMonitorInWorkspace` filters
- // by `isNull(deletedAt)`, so a second `deleteMonitor` on the same
- // id should throw `NotFoundError` rather than silently re-running
- // the soft-delete / cascade / audit sequence on a tombstoned row.
- const row = await createMonitor({
- ctx: teamCtx,
- input: {
- name: `${TEST_PREFIX}-double-delete`,
- jobType: "http",
- url: "https://example.com",
- method: "GET",
- headers: [],
- assertions: [],
- active: false,
- },
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ // Regression for the Cubic P2 fix: `getMonitorInWorkspace` filters
+ // by `isNull(deletedAt)`, so a second `deleteMonitor` on the same
+ // id should throw `NotFoundError` rather than silently re-running
+ // the soft-delete / cascade / audit sequence on a tombstoned row.
+ const row = await createMonitor({
+ ctx,
+ input: {
+ name: `${TEST_PREFIX}-double-delete`,
+ jobType: "http",
+ url: "https://example.com",
+ method: "GET",
+ headers: [],
+ assertions: [],
+ active: false,
+ },
+ });
+ await deleteMonitor({ ctx, input: { id: row.id } });
+ await expect(
+ deleteMonitor({ ctx, input: { id: row.id } }),
+ ).rejects.toBeInstanceOf(NotFoundError);
});
- track(row.id);
- await deleteMonitor({ ctx: teamCtx, input: { id: row.id } });
- await expect(
- deleteMonitor({ ctx: teamCtx, input: { id: row.id } }),
- ).rejects.toBeInstanceOf(NotFoundError);
});
});
describe("deleteMonitors (bulk)", () => {
test("soft-deletes all ids and strips associations", async () => {
- const a = await createMonitor({
- ctx: teamCtx,
- input: {
- name: `${TEST_PREFIX}-bulk-a`,
- jobType: "http",
- url: "https://a.example.com",
- method: "GET",
- headers: [],
- assertions: [],
- active: false,
- },
- });
- const b = await createMonitor({
- ctx: teamCtx,
- input: {
- name: `${TEST_PREFIX}-bulk-b`,
- jobType: "http",
- url: "https://b.example.com",
- method: "GET",
- headers: [],
- assertions: [],
- active: false,
- },
- });
- track(a.id);
- track(b.id);
-
- await deleteMonitors({
- ctx: teamCtx,
- input: { ids: [a.id, b.id] },
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ const a = await createMonitor({
+ ctx,
+ input: {
+ name: `${TEST_PREFIX}-bulk-a`,
+ jobType: "http",
+ url: "https://a.example.com",
+ method: "GET",
+ headers: [],
+ assertions: [],
+ active: false,
+ },
+ });
+ const b = await createMonitor({
+ ctx,
+ input: {
+ name: `${TEST_PREFIX}-bulk-b`,
+ jobType: "http",
+ url: "https://b.example.com",
+ method: "GET",
+ headers: [],
+ assertions: [],
+ active: false,
+ },
+ });
+
+ await deleteMonitors({
+ ctx,
+ input: { ids: [a.id, b.id] },
+ });
+
+ const rows = await tx
+ .select({ id: monitor.id, deletedAt: monitor.deletedAt })
+ .from(monitor)
+ .where(inArray(monitor.id, [a.id, b.id]))
+ .all();
+ expect(rows).toHaveLength(2);
+ for (const r of rows) expect(r.deletedAt).toBeInstanceOf(Date);
});
-
- const rows = await db
- .select({ id: monitor.id, deletedAt: monitor.deletedAt })
- .from(monitor)
- .where(inArray(monitor.id, [a.id, b.id]))
- .all();
- expect(rows).toHaveLength(2);
- for (const r of rows) expect(r.deletedAt).toBeInstanceOf(Date);
});
});
describe("cloneMonitor", () => {
test("duplicates the row with a `(Copy)` name", async () => {
- const source = await createMonitor({
- ctx: teamCtx,
- input: {
- name: `${TEST_PREFIX}-source`,
- jobType: "http",
- url: "https://example.com",
- method: "GET",
- headers: [],
- assertions: [],
- active: false,
- },
- });
- track(source.id);
-
- const clone = await cloneMonitor({
- ctx: teamCtx,
- input: { id: source.id },
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ const source = await createMonitor({
+ ctx,
+ input: {
+ name: `${TEST_PREFIX}-source`,
+ jobType: "http",
+ url: "https://example.com",
+ method: "GET",
+ headers: [],
+ assertions: [],
+ active: false,
+ },
+ });
+
+ const clone = await cloneMonitor({
+ ctx,
+ input: { id: source.id },
+ });
+
+ expect(clone.id).not.toBe(source.id);
+ expect(clone.name).toBe(`${source.name} (Copy)`);
+ expect(clone.url).toBe(source.url);
});
- track(clone.id);
-
- expect(clone.id).not.toBe(source.id);
- expect(clone.name).toBe(`${source.name} (Copy)`);
- expect(clone.url).toBe(source.url);
});
test("resets status to active even when source is degraded/error", async () => {
- // Regression for the Cubic P2 fix: `clone.ts` destructures
- // `status` out of the source row before spreading, so a clone
- // always starts in `"active"` state rather than inheriting the
- // source's stale health. Flipping the source's status via a
- // direct db update — `createMonitor` doesn't accept `status`
- // input, and `"active"` is the insert default.
- const source = await createMonitor({
- ctx: teamCtx,
- input: {
- name: `${TEST_PREFIX}-clone-status-reset`,
- jobType: "http",
- url: "https://example.com",
- method: "GET",
- headers: [],
- assertions: [],
- active: false,
- },
- });
- track(source.id);
- await db
- .update(monitor)
- .set({ status: "error" })
- .where(eq(monitor.id, source.id));
-
- const clone = await cloneMonitor({
- ctx: teamCtx,
- input: { id: source.id },
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ // Regression for the Cubic P2 fix: `clone.ts` destructures
+ // `status` out of the source row before spreading, so a clone
+ // always starts in `"active"` state rather than inheriting the
+ // source's stale health. Flipping the source's status via a
+ // direct db update — `createMonitor` doesn't accept `status`
+ // input, and `"active"` is the insert default.
+ const source = await createMonitor({
+ ctx,
+ input: {
+ name: `${TEST_PREFIX}-clone-status-reset`,
+ jobType: "http",
+ url: "https://example.com",
+ method: "GET",
+ headers: [],
+ assertions: [],
+ active: false,
+ },
+ });
+ await tx
+ .update(monitor)
+ .set({ status: "error" })
+ .where(eq(monitor.id, source.id));
+
+ const clone = await cloneMonitor({
+ ctx,
+ input: { id: source.id },
+ });
+
+ expect(clone.status).toBe("active");
});
- track(clone.id);
-
- expect(clone.status).toBe("active");
});
});
describe("updateMonitorTags / updateMonitorNotifiers", () => {
test("replaces the full tag set with deduped ids", async () => {
- const row = await createMonitor({
- ctx: teamCtx,
- input: {
- name: `${TEST_PREFIX}-tags`,
- jobType: "http",
- url: "https://example.com",
- method: "GET",
- headers: [],
- assertions: [],
- active: false,
- },
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ const row = await createMonitor({
+ ctx,
+ input: {
+ name: `${TEST_PREFIX}-tags`,
+ jobType: "http",
+ url: "https://example.com",
+ method: "GET",
+ headers: [],
+ assertions: [],
+ active: false,
+ },
+ });
+
+ await updateMonitorTags({
+ ctx,
+ input: { id: row.id, tags: [testTagId, testTagId] },
+ });
+ const assoc = await tx
+ .select()
+ .from(monitorTagsToMonitors)
+ .where(eq(monitorTagsToMonitors.monitorId, row.id))
+ .all();
+ expect(assoc).toHaveLength(1);
});
- track(row.id);
-
- await updateMonitorTags({
- ctx: teamCtx,
- input: { id: row.id, tags: [testTagId, testTagId] },
- });
- const assoc = await db
- .select()
- .from(monitorTagsToMonitors)
- .where(eq(monitorTagsToMonitors.monitorId, row.id))
- .all();
- expect(assoc).toHaveLength(1);
});
test("throws ForbiddenError when tag is in another workspace", async () => {
- const row = await createMonitor({
- ctx: teamCtx,
- input: {
- name: `${TEST_PREFIX}-tag-forbidden`,
- jobType: "http",
- url: "https://example.com",
- method: "GET",
- headers: [],
- assertions: [],
- active: false,
- },
+ await withTestTransaction(async (tx) => {
+ const row = await createMonitor({
+ ctx: { ...teamCtx, db: tx },
+ input: {
+ name: `${TEST_PREFIX}-tag-forbidden`,
+ jobType: "http",
+ url: "https://example.com",
+ method: "GET",
+ headers: [],
+ assertions: [],
+ active: false,
+ },
+ });
+ await expect(
+ updateMonitorTags({
+ ctx: { ...freeCtx, db: tx },
+ input: { id: row.id, tags: [testTagId] },
+ }),
+ ).rejects.toBeInstanceOf(NotFoundError); // monitor is in another ws
});
- track(row.id);
- await expect(
- updateMonitorTags({
- ctx: freeCtx,
- input: { id: row.id, tags: [testTagId] },
- }),
- ).rejects.toBeInstanceOf(NotFoundError); // monitor is in another ws
});
test("replaces the full notifier set", async () => {
- const row = await createMonitor({
- ctx: teamCtx,
- input: {
- name: `${TEST_PREFIX}-notif`,
- jobType: "http",
- url: "https://example.com",
- method: "GET",
- headers: [],
- assertions: [],
- active: false,
- },
- });
- track(row.id);
- await updateMonitorNotifiers({
- ctx: teamCtx,
- input: { id: row.id, notifiers: [testNotificationId] },
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ const row = await createMonitor({
+ ctx,
+ input: {
+ name: `${TEST_PREFIX}-notif`,
+ jobType: "http",
+ url: "https://example.com",
+ method: "GET",
+ headers: [],
+ assertions: [],
+ active: false,
+ },
+ });
+ await updateMonitorNotifiers({
+ ctx,
+ input: { id: row.id, notifiers: [testNotificationId] },
+ });
+ const assoc = await tx
+ .select()
+ .from(notificationsToMonitors)
+ .where(eq(notificationsToMonitors.monitorId, row.id))
+ .all();
+ expect(assoc).toHaveLength(1);
});
- const assoc = await db
- .select()
- .from(notificationsToMonitors)
- .where(eq(notificationsToMonitors.monitorId, row.id))
- .all();
- expect(assoc).toHaveLength(1);
});
test("throws ForbiddenError when notifier is in another workspace", async () => {
- // free ctx owns its own monitor; pass team's notificationId (which is in
- // team's workspace) into the update under free ctx → the monitor lookup
- // would fail first (NotFoundError), so we build an in-free monitor and
- // try to attach team's notifier.
- const freeMonitor = await createMonitor({
- ctx: freeCtx,
- input: {
- name: `${TEST_PREFIX}-free-notif`,
- jobType: "http",
- url: "https://example.com",
- method: "GET",
- headers: [],
- assertions: [],
- active: false,
- },
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...freeCtx, db: tx };
+ // free ctx owns its own monitor; pass team's notificationId (which is in
+ // team's workspace) into the update under free ctx → the monitor lookup
+ // would fail first (NotFoundError), so we build an in-free monitor and
+ // try to attach team's notifier.
+ const freeMonitor = await createMonitor({
+ ctx,
+ input: {
+ name: `${TEST_PREFIX}-free-notif`,
+ jobType: "http",
+ url: "https://example.com",
+ method: "GET",
+ headers: [],
+ assertions: [],
+ active: false,
+ },
+ });
+ await expect(
+ updateMonitorNotifiers({
+ ctx,
+ input: { id: freeMonitor.id, notifiers: [testNotificationId] },
+ }),
+ ).rejects.toBeInstanceOf(ForbiddenError);
});
- track(freeMonitor.id);
- await expect(
- updateMonitorNotifiers({
- ctx: freeCtx,
- input: { id: freeMonitor.id, notifiers: [testNotificationId] },
- }),
- ).rejects.toBeInstanceOf(ForbiddenError);
});
});
describe("list / get", () => {
test("respects workspace isolation + soft-delete", async () => {
- const row = await createMonitor({
- ctx: teamCtx,
- input: {
- name: `${TEST_PREFIX}-list`,
- jobType: "http",
- url: "https://example.com",
- method: "GET",
- headers: [],
- assertions: [],
- active: true,
- },
- });
- track(row.id);
-
- await expect(
- getMonitor({ ctx: freeCtx, input: { id: row.id } }),
- ).rejects.toBeInstanceOf(NotFoundError);
-
- const { items } = await listMonitors({
- ctx: freeCtx,
- input: { limit: 100, offset: 0, order: "desc" },
- });
- expect(items.find((m) => m.id === row.id)).toBeUndefined();
-
- // Soft-delete, then verify it disappears from the team list too.
- await deleteMonitor({ ctx: teamCtx, input: { id: row.id } });
- const { items: teamItems } = await listMonitors({
- ctx: teamCtx,
- input: { limit: 1000, offset: 0, order: "desc" },
+ await withTestTransaction(async (tx) => {
+ const teamCtxTx = { ...teamCtx, db: tx };
+ const freeCtxTx = { ...freeCtx, db: tx };
+ const row = await createMonitor({
+ ctx: teamCtxTx,
+ input: {
+ name: `${TEST_PREFIX}-list`,
+ jobType: "http",
+ url: "https://example.com",
+ method: "GET",
+ headers: [],
+ assertions: [],
+ active: true,
+ },
+ });
+
+ await expect(
+ getMonitor({ ctx: freeCtxTx, input: { id: row.id } }),
+ ).rejects.toBeInstanceOf(NotFoundError);
+
+ const { items } = await listMonitors({
+ ctx: freeCtxTx,
+ input: { limit: 100, offset: 0, order: "desc" },
+ });
+ expect(items.find((m) => m.id === row.id)).toBeUndefined();
+
+ // Soft-delete, then verify it disappears from the team list too.
+ await deleteMonitor({ ctx: teamCtxTx, input: { id: row.id } });
+ const { items: teamItems } = await listMonitors({
+ ctx: teamCtxTx,
+ input: { limit: 1000, offset: 0, order: "desc" },
+ });
+ expect(teamItems.find((m) => m.id === row.id)).toBeUndefined();
});
- expect(teamItems.find((m) => m.id === row.id)).toBeUndefined();
});
});
describe("updateMonitorGeneral", () => {
test("updates name / url / assertions and audits", async () => {
- const row = await createMonitor({
- ctx: teamCtx,
- input: {
- name: `${TEST_PREFIX}-gen`,
- jobType: "http",
- url: "https://example.com",
- method: "GET",
- headers: [],
- assertions: [],
- active: false,
- },
- });
- track(row.id);
-
- const updated = await updateMonitorGeneral({
- ctx: teamCtx,
- input: {
- id: row.id,
- name: `${TEST_PREFIX}-gen-renamed`,
- jobType: "http",
- url: "https://example.org",
- method: "POST",
- headers: [{ key: "X-Test", value: "yes" }],
- assertions: [],
- active: true,
- },
- });
-
- expect(updated.name).toBe(`${TEST_PREFIX}-gen-renamed`);
- expect(updated.url).toBe("https://example.org");
- expect(updated.method).toBe("POST");
- await expectAuditRow({
- workspaceId: teamCtx.workspace.id,
- action: "monitor.update",
- entityType: "monitor",
- entityId: row.id,
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ const row = await createMonitor({
+ ctx,
+ input: {
+ name: `${TEST_PREFIX}-gen`,
+ jobType: "http",
+ url: "https://example.com",
+ method: "GET",
+ headers: [],
+ assertions: [],
+ active: false,
+ },
+ });
+
+ const updated = await updateMonitorGeneral({
+ ctx,
+ input: {
+ id: row.id,
+ name: `${TEST_PREFIX}-gen-renamed`,
+ jobType: "http",
+ url: "https://example.org",
+ method: "POST",
+ headers: [{ key: "X-Test", value: "yes" }],
+ assertions: [],
+ active: true,
+ },
+ });
+
+ expect(updated.name).toBe(`${TEST_PREFIX}-gen-renamed`);
+ expect(updated.url).toBe("https://example.org");
+ expect(updated.method).toBe("POST");
+ await expectAuditRow({
+ workspaceId: teamCtx.workspace.id,
+ action: "monitor.update",
+ entityType: "monitor",
+ entityId: row.id,
+ db: tx,
+ });
});
});
});
diff --git a/packages/services/src/notification/__tests__/notification.test.ts b/packages/services/src/notification/__tests__/notification.test.ts
index fd8fda671..2ac2d3a31 100644
--- a/packages/services/src/notification/__tests__/notification.test.ts
+++ b/packages/services/src/notification/__tests__/notification.test.ts
@@ -1,12 +1,5 @@
-import {
- afterAll,
- beforeAll,
- beforeEach,
- describe,
- expect,
- test,
-} from "bun:test";
-import { db, eq, inArray } from "@openstatus/db";
+import { afterAll, beforeAll, describe, expect, test } from "bun:test";
+import { db, eq } from "@openstatus/db";
import {
monitor,
notification,
@@ -19,10 +12,10 @@ import {
} from "../../../test/fixtures";
import {
cleanQuotaGatedTables,
- clearAuditLog,
expectAuditRow,
loadSeededWorkspace,
makeUserCtx,
+ withTestTransaction,
} from "../../../test/helpers";
import type { ServiceContext } from "../../context";
import {
@@ -41,7 +34,6 @@ const TEST_PREFIX = "svc-notification-test";
let teamCtx: ServiceContext;
let freeCtx: ServiceContext;
let teamMonitorId: number;
-const createdNotificationIds: number[] = [];
beforeAll(async () => {
const team = await loadSeededWorkspace(SEEDED_WORKSPACE_TEAM_ID);
@@ -72,320 +64,329 @@ beforeAll(async () => {
});
afterAll(async () => {
- if (createdNotificationIds.length > 0) {
- await db
- .delete(notification)
- .where(inArray(notification.id, createdNotificationIds))
- .catch(() => undefined);
- }
await db
.delete(monitor)
.where(eq(monitor.id, teamMonitorId))
.catch(() => undefined);
});
-beforeEach(async () => {
- await clearAuditLog(teamCtx.workspace.id);
- await clearAuditLog(freeCtx.workspace.id);
-});
-
-function track(id: number) {
- createdNotificationIds.push(id);
- return id;
-}
-
describe("createNotification", () => {
test("creates a discord channel with monitors + audits", async () => {
- const row = await createNotification({
- ctx: teamCtx,
- input: {
- name: `${TEST_PREFIX}-discord`,
- provider: "discord",
- data: { discord: "https://discord.com/api/webhooks/1/abc" },
- monitors: [teamMonitorId],
- },
- });
- track(row.id);
- expect(row.provider).toBe("discord");
-
- const assoc = await db
- .select()
- .from(notificationsToMonitors)
- .where(eq(notificationsToMonitors.notificationId, row.id))
- .all();
- expect(assoc.map((a) => a.monitorId)).toEqual([teamMonitorId]);
-
- await expectAuditRow({
- workspaceId: teamCtx.workspace.id,
- action: "notification.create",
- entityType: "notification",
- entityId: row.id,
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ const row = await createNotification({
+ ctx,
+ input: {
+ name: `${TEST_PREFIX}-discord`,
+ provider: "discord",
+ data: { discord: "https://discord.com/api/webhooks/1/abc" },
+ monitors: [teamMonitorId],
+ },
+ });
+ expect(row.provider).toBe("discord");
+
+ const assoc = await tx
+ .select()
+ .from(notificationsToMonitors)
+ .where(eq(notificationsToMonitors.notificationId, row.id))
+ .all();
+ expect(assoc.map((a) => a.monitorId)).toEqual([teamMonitorId]);
+
+ await expectAuditRow({
+ workspaceId: teamCtx.workspace.id,
+ action: "notification.create",
+ entityType: "notification",
+ entityId: row.id,
+ db: tx,
+ });
});
});
test("throws ValidationError for malformed data", async () => {
- await expect(
- createNotification({
- ctx: teamCtx,
- input: {
- name: `${TEST_PREFIX}-bad`,
- provider: "discord",
- // missing the required `discord` key
- data: {},
- monitors: [],
- },
- }),
- ).rejects.toBeInstanceOf(ValidationError);
+ await withTestTransaction(async (tx) => {
+ await expect(
+ createNotification({
+ ctx: { ...teamCtx, db: tx },
+ input: {
+ name: `${TEST_PREFIX}-bad`,
+ provider: "discord",
+ // missing the required `discord` key
+ data: {},
+ monitors: [],
+ },
+ }),
+ ).rejects.toBeInstanceOf(ValidationError);
+ });
});
test("throws ValidationError when data payload key doesn't match provider", async () => {
- await expect(
- createNotification({
- ctx: teamCtx,
- input: {
- name: `${TEST_PREFIX}-mismatch`,
- provider: "discord",
- // Valid slack payload, but provider is discord → rejected.
- data: { slack: "https://hooks.slack.com/services/x/y/z" },
- monitors: [],
- },
- }),
- ).rejects.toBeInstanceOf(ValidationError);
+ await withTestTransaction(async (tx) => {
+ await expect(
+ createNotification({
+ ctx: { ...teamCtx, db: tx },
+ input: {
+ name: `${TEST_PREFIX}-mismatch`,
+ provider: "discord",
+ // Valid slack payload, but provider is discord → rejected.
+ data: { slack: "https://hooks.slack.com/services/x/y/z" },
+ monitors: [],
+ },
+ }),
+ ).rejects.toBeInstanceOf(ValidationError);
+ });
});
test("throws ValidationError when provider payload is malformed but another provider's is valid", async () => {
- // The canonical data schema for the selected provider must match.
- // A plain key-presence check would have missed this: `discord: "not-a-url"`
- // fails `urlSchema`, but a valid `slack` field could've hidden it.
- await expect(
- createNotification({
- ctx: teamCtx,
- input: {
- name: `${TEST_PREFIX}-invalid-payload`,
- provider: "discord",
- data: {
- discord: "not-a-url",
- slack: "https://hooks.slack.com/services/x/y/z",
+ await withTestTransaction(async (tx) => {
+ // The canonical data schema for the selected provider must match.
+ // A plain key-presence check would have missed this: `discord: "not-a-url"`
+ // fails `urlSchema`, but a valid `slack` field could've hidden it.
+ await expect(
+ createNotification({
+ ctx: { ...teamCtx, db: tx },
+ input: {
+ name: `${TEST_PREFIX}-invalid-payload`,
+ provider: "discord",
+ data: {
+ discord: "not-a-url",
+ slack: "https://hooks.slack.com/services/x/y/z",
+ },
+ monitors: [],
},
- monitors: [],
- },
- }),
- ).rejects.toBeInstanceOf(ValidationError);
+ }),
+ ).rejects.toBeInstanceOf(ValidationError);
+ });
});
test("throws LimitExceededError when plan blocks the provider", async () => {
- // free plan has `pagerduty: false`.
- await expect(
- createNotification({
- ctx: freeCtx,
- input: {
- name: `${TEST_PREFIX}-gated`,
- provider: "pagerduty",
- data: {
- pagerduty: JSON.stringify({
- integration_keys: [{ id: "k1", integration_key: "x" }],
- }),
+ await withTestTransaction(async (tx) => {
+ // free plan has `pagerduty: false`.
+ await expect(
+ createNotification({
+ ctx: { ...freeCtx, db: tx },
+ input: {
+ name: `${TEST_PREFIX}-gated`,
+ provider: "pagerduty",
+ data: {
+ pagerduty: JSON.stringify({
+ integration_keys: [{ id: "k1", integration_key: "x" }],
+ }),
+ },
+ monitors: [],
},
- monitors: [],
- },
- }),
- ).rejects.toBeInstanceOf(LimitExceededError);
+ }),
+ ).rejects.toBeInstanceOf(LimitExceededError);
+ });
});
test("throws ForbiddenError for cross-workspace monitor", async () => {
- await expect(
- createNotification({
- ctx: freeCtx,
- input: {
- name: `${TEST_PREFIX}-cross-ws`,
- provider: "discord",
- data: { discord: "https://discord.com/api/webhooks/1/abc" },
- monitors: [teamMonitorId], // team's monitor
- },
- }),
- ).rejects.toBeInstanceOf(ForbiddenError);
+ await withTestTransaction(async (tx) => {
+ await expect(
+ createNotification({
+ ctx: { ...freeCtx, db: tx },
+ input: {
+ name: `${TEST_PREFIX}-cross-ws`,
+ provider: "discord",
+ data: { discord: "https://discord.com/api/webhooks/1/abc" },
+ monitors: [teamMonitorId], // team's monitor
+ },
+ }),
+ ).rejects.toBeInstanceOf(ForbiddenError);
+ });
});
});
describe("updateNotification", () => {
test("replaces name / data / monitor associations", async () => {
- const row = await createNotification({
- ctx: teamCtx,
- input: {
- name: `${TEST_PREFIX}-update`,
- provider: "discord",
- data: { discord: "https://discord.com/api/webhooks/1/abc" },
- monitors: [teamMonitorId],
- },
- });
- track(row.id);
-
- const updated = await updateNotification({
- ctx: teamCtx,
- input: {
- id: row.id,
- name: `${TEST_PREFIX}-update-renamed`,
- data: { discord: "https://discord.com/api/webhooks/2/def" },
- monitors: [],
- },
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ const row = await createNotification({
+ ctx,
+ input: {
+ name: `${TEST_PREFIX}-update`,
+ provider: "discord",
+ data: { discord: "https://discord.com/api/webhooks/1/abc" },
+ monitors: [teamMonitorId],
+ },
+ });
+
+ const updated = await updateNotification({
+ ctx,
+ input: {
+ id: row.id,
+ name: `${TEST_PREFIX}-update-renamed`,
+ data: { discord: "https://discord.com/api/webhooks/2/def" },
+ monitors: [],
+ },
+ });
+ expect(updated.name).toBe(`${TEST_PREFIX}-update-renamed`);
+
+ const assoc = await tx
+ .select()
+ .from(notificationsToMonitors)
+ .where(eq(notificationsToMonitors.notificationId, row.id))
+ .all();
+ expect(assoc).toHaveLength(0);
});
- expect(updated.name).toBe(`${TEST_PREFIX}-update-renamed`);
-
- const assoc = await db
- .select()
- .from(notificationsToMonitors)
- .where(eq(notificationsToMonitors.notificationId, row.id))
- .all();
- expect(assoc).toHaveLength(0);
});
test("throws NotFoundError for cross-workspace update", async () => {
- const row = await createNotification({
- ctx: teamCtx,
- input: {
- name: `${TEST_PREFIX}-cross-ws-update`,
- provider: "discord",
- data: { discord: "https://discord.com/api/webhooks/1/abc" },
- monitors: [],
- },
- });
- track(row.id);
-
- await expect(
- updateNotification({
- ctx: freeCtx,
+ await withTestTransaction(async (tx) => {
+ const row = await createNotification({
+ ctx: { ...teamCtx, db: tx },
input: {
- id: row.id,
- name: "blocked",
- data: { discord: "https://discord.com/api/webhooks/x/y" },
+ name: `${TEST_PREFIX}-cross-ws-update`,
+ provider: "discord",
+ data: { discord: "https://discord.com/api/webhooks/1/abc" },
monitors: [],
},
- }),
- ).rejects.toBeInstanceOf(NotFoundError);
+ });
+
+ await expect(
+ updateNotification({
+ ctx: { ...freeCtx, db: tx },
+ input: {
+ id: row.id,
+ name: "blocked",
+ data: { discord: "https://discord.com/api/webhooks/x/y" },
+ monitors: [],
+ },
+ }),
+ ).rejects.toBeInstanceOf(NotFoundError);
+ });
});
test("emits a notification.update audit row", async () => {
- const row = await createNotification({
- ctx: teamCtx,
- input: {
- name: `${TEST_PREFIX}-update-audit`,
- provider: "discord",
- data: { discord: "https://discord.com/api/webhooks/1/abc" },
- monitors: [],
- },
- });
- track(row.id);
-
- await updateNotification({
- ctx: teamCtx,
- input: {
- id: row.id,
- name: `${TEST_PREFIX}-update-audit-renamed`,
- data: { discord: "https://discord.com/api/webhooks/2/def" },
- monitors: [],
- },
- });
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ const row = await createNotification({
+ ctx,
+ input: {
+ name: `${TEST_PREFIX}-update-audit`,
+ provider: "discord",
+ data: { discord: "https://discord.com/api/webhooks/1/abc" },
+ monitors: [],
+ },
+ });
- await expectAuditRow({
- workspaceId: teamCtx.workspace.id,
- action: "notification.update",
- entityType: "notification",
- entityId: row.id,
+ await updateNotification({
+ ctx,
+ input: {
+ id: row.id,
+ name: `${TEST_PREFIX}-update-audit-renamed`,
+ data: { discord: "https://discord.com/api/webhooks/2/def" },
+ monitors: [],
+ },
+ });
+
+ await expectAuditRow({
+ workspaceId: teamCtx.workspace.id,
+ action: "notification.update",
+ entityType: "notification",
+ entityId: row.id,
+ db: tx,
+ });
});
});
test("throws LimitExceededError when plan gate blocks update", async () => {
- // Regression for the post-downgrade case: the row was created on a
- // plan that allowed pagerduty, but the current workspace no longer
- // does. The pre-fix update flow never re-checked the gate, so an
- // editable form field remained open to channels the plan had since
- // revoked. Simulate it by bypassing the create-time gate with a
- // direct db insert bound to the free workspace.
- const [inserted] = await db
- .insert(notification)
- .values({
- workspaceId: SEEDED_WORKSPACE_FREE_ID,
- name: `${TEST_PREFIX}-downgrade-gate`,
- provider: "pagerduty",
- data: JSON.stringify({
- pagerduty: JSON.stringify({
- integration_keys: [{ id: "k1", integration_key: "x" }],
- }),
- }),
- })
- .returning();
- if (!inserted) throw new Error("direct insert failed");
- track(inserted.id);
-
- await expect(
- updateNotification({
- ctx: freeCtx,
- input: {
- id: inserted.id,
- name: "would-be-rename",
- data: {
+ await withTestTransaction(async (tx) => {
+ // Regression for the post-downgrade case: the row was created on a
+ // plan that allowed pagerduty, but the current workspace no longer
+ // does. The pre-fix update flow never re-checked the gate, so an
+ // editable form field remained open to channels the plan had since
+ // revoked. Simulate it by bypassing the create-time gate with a
+ // direct db insert bound to the free workspace.
+ const [inserted] = await tx
+ .insert(notification)
+ .values({
+ workspaceId: SEEDED_WORKSPACE_FREE_ID,
+ name: `${TEST_PREFIX}-downgrade-gate`,
+ provider: "pagerduty",
+ data: JSON.stringify({
pagerduty: JSON.stringify({
- integration_keys: [{ id: "k1", integration_key: "y" }],
+ integration_keys: [{ id: "k1", integration_key: "x" }],
}),
+ }),
+ })
+ .returning();
+ if (!inserted) throw new Error("direct insert failed");
+
+ await expect(
+ updateNotification({
+ ctx: { ...freeCtx, db: tx },
+ input: {
+ id: inserted.id,
+ name: "would-be-rename",
+ data: {
+ pagerduty: JSON.stringify({
+ integration_keys: [{ id: "k1", integration_key: "y" }],
+ }),
+ },
+ monitors: [],
},
- monitors: [],
- },
- }),
- ).rejects.toBeInstanceOf(LimitExceededError);
+ }),
+ ).rejects.toBeInstanceOf(LimitExceededError);
+ });
});
});
describe("deleteNotification", () => {
test("removes the row", async () => {
- const row = await createNotification({
- ctx: teamCtx,
- input: {
- name: `${TEST_PREFIX}-delete`,
- provider: "discord",
- data: { discord: "https://discord.com/api/webhooks/1/abc" },
- monitors: [],
- },
- });
- track(row.id);
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ const row = await createNotification({
+ ctx,
+ input: {
+ name: `${TEST_PREFIX}-delete`,
+ provider: "discord",
+ data: { discord: "https://discord.com/api/webhooks/1/abc" },
+ monitors: [],
+ },
+ });
- await deleteNotification({ ctx: teamCtx, input: { id: row.id } });
+ await deleteNotification({ ctx, input: { id: row.id } });
- const remaining = await db
- .select()
- .from(notification)
- .where(eq(notification.id, row.id))
- .all();
- expect(remaining).toHaveLength(0);
+ const remaining = await tx
+ .select()
+ .from(notification)
+ .where(eq(notification.id, row.id))
+ .all();
+ expect(remaining).toHaveLength(0);
+ });
});
});
describe("list / get", () => {
test("list returns enriched monitors scoped to the workspace", async () => {
- const row = await createNotification({
- ctx: teamCtx,
- input: {
- name: `${TEST_PREFIX}-enrich`,
- provider: "discord",
- data: { discord: "https://discord.com/api/webhooks/1/abc" },
- monitors: [teamMonitorId],
- },
- });
- track(row.id);
-
- const full = await getNotification({
- ctx: teamCtx,
- input: { id: row.id },
- });
- expect(full.monitors.map((m) => m.id)).toEqual([teamMonitorId]);
-
- await expect(
- getNotification({ ctx: freeCtx, input: { id: row.id } }),
- ).rejects.toBeInstanceOf(NotFoundError);
-
- const { items: freeItems } = await listNotifications({
- ctx: freeCtx,
- input: { limit: 100, offset: 0, order: "desc" },
+ await withTestTransaction(async (tx) => {
+ const teamCtxTx = { ...teamCtx, db: tx };
+ const freeCtxTx = { ...freeCtx, db: tx };
+ const row = await createNotification({
+ ctx: teamCtxTx,
+ input: {
+ name: `${TEST_PREFIX}-enrich`,
+ provider: "discord",
+ data: { discord: "https://discord.com/api/webhooks/1/abc" },
+ monitors: [teamMonitorId],
+ },
+ });
+
+ const full = await getNotification({
+ ctx: teamCtxTx,
+ input: { id: row.id },
+ });
+ expect(full.monitors.map((m) => m.id)).toEqual([teamMonitorId]);
+
+ await expect(
+ getNotification({ ctx: freeCtxTx, input: { id: row.id } }),
+ ).rejects.toBeInstanceOf(NotFoundError);
+
+ const { items: freeItems } = await listNotifications({
+ ctx: freeCtxTx,
+ input: { limit: 100, offset: 0, order: "desc" },
+ });
+ expect(freeItems.find((n) => n.id === row.id)).toBeUndefined();
});
- expect(freeItems.find((n) => n.id === row.id)).toBeUndefined();
});
});
diff --git a/packages/services/src/page-component/__tests__/page-component.test.ts b/packages/services/src/page-component/__tests__/page-component.test.ts
index f3db909ce..66bd942ba 100644
--- a/packages/services/src/page-component/__tests__/page-component.test.ts
+++ b/packages/services/src/page-component/__tests__/page-component.test.ts
@@ -1,11 +1,4 @@
-import {
- afterAll,
- beforeAll,
- beforeEach,
- describe,
- expect,
- test,
-} from "bun:test";
+import { afterAll, beforeAll, describe, expect, test } from "bun:test";
import { and, db, eq, inArray } from "@openstatus/db";
import {
monitor,
@@ -19,10 +12,10 @@ import {
SEEDED_WORKSPACE_TEAM_ID,
} from "../../../test/fixtures";
import {
- clearAuditLog,
expectAuditRow,
loadSeededWorkspace,
makeUserCtx,
+ withTestTransaction,
} from "../../../test/helpers";
import type { ServiceContext } from "../../context";
import { ForbiddenError, NotFoundError } from "../../errors";
@@ -37,7 +30,6 @@ let freeCtx: ServiceContext;
let testPageId: number;
let teamMonitorId: number;
let freeMonitorId: number;
-const createdComponentIds: number[] = [];
beforeAll(async () => {
const team = await loadSeededWorkspace(SEEDED_WORKSPACE_TEAM_ID);
@@ -90,12 +82,6 @@ beforeAll(async () => {
});
afterAll(async () => {
- if (createdComponentIds.length > 0) {
- await db
- .delete(pageComponent)
- .where(inArray(pageComponent.id, createdComponentIds))
- .catch(() => undefined);
- }
await db
.delete(pageComponent)
.where(eq(pageComponent.pageId, testPageId))
@@ -114,205 +100,250 @@ afterAll(async () => {
.catch(() => undefined);
});
-beforeEach(async () => {
- await clearAuditLog(teamCtx.workspace.id);
- await clearAuditLog(freeCtx.workspace.id);
-});
-
describe("updatePageComponentOrder", () => {
test("creates monitor + static components and a group", async () => {
- await updatePageComponentOrder({
- ctx: teamCtx,
- input: {
- pageId: testPageId,
- components: [
- {
- order: 0,
- name: `${TEST_PREFIX}-monitor-cmp`,
- type: "monitor",
- monitorId: teamMonitorId,
- },
- {
- order: 1,
- name: `${TEST_PREFIX}-static-cmp`,
- type: "static",
- },
- ],
- groups: [
- {
- order: 2,
- name: `${TEST_PREFIX}-group`,
- defaultOpen: false,
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ await updatePageComponentOrder({
+ ctx,
+ input: {
+ pageId: testPageId,
+ components: [
+ {
+ order: 0,
+ name: `${TEST_PREFIX}-monitor-cmp`,
+ type: "monitor",
+ monitorId: teamMonitorId,
+ },
+ {
+ order: 1,
+ name: `${TEST_PREFIX}-static-cmp`,
+ type: "static",
+ },
+ ],
+ groups: [
+ {
+ order: 2,
+ name: `${TEST_PREFIX}-group`,
+ defaultOpen: false,
+ components: [
+ {
+ order: 0,
+ name: `${TEST_PREFIX}-grouped-static`,
+ type: "static",
+ },
+ ],
+ },
+ ],
+ },
+ });
+
+ const components = await tx
+ .select()
+ .from(pageComponent)
+ .where(eq(pageComponent.pageId, testPageId))
+ .all();
+ const groups = await tx
+ .select()
+ .from(pageComponentGroup)
+ .where(eq(pageComponentGroup.pageId, testPageId))
+ .all();
+ expect(components).toHaveLength(3);
+ expect(groups).toHaveLength(1);
+
+ // Per-entity audit emits — assert one representative of each kind.
+ // The service writes one row per component / group, so every id in
+ // `components` + `groups` should appear, not a single page-level row.
+ const monitorComponent = components.find((c) => c.type === "monitor");
+ expect(monitorComponent).toBeDefined();
+ if (!monitorComponent) throw new Error("unreachable");
+ await expectAuditRow({
+ workspaceId: teamCtx.workspace.id,
+ action: "page_component.create",
+ entityType: "page_component",
+ entityId: monitorComponent.id,
+ db: tx,
+ });
+
+ const group = groups[0];
+ expect(group).toBeDefined();
+ if (!group) throw new Error("unreachable");
+ await expectAuditRow({
+ workspaceId: teamCtx.workspace.id,
+ action: "page_component_group.create",
+ entityType: "page_component_group",
+ entityId: group.id,
+ db: tx,
+ });
+ });
+ });
+
+ test("rejects cross-workspace monitorId with ForbiddenError", async () => {
+ await withTestTransaction(async (tx) => {
+ await expect(
+ updatePageComponentOrder({
+ ctx: { ...teamCtx, db: tx },
+ input: {
+ pageId: testPageId,
components: [
{
order: 0,
- name: `${TEST_PREFIX}-grouped-static`,
- type: "static",
+ name: `${TEST_PREFIX}-cross-ws`,
+ type: "monitor",
+ monitorId: freeMonitorId,
},
],
+ groups: [],
},
- ],
- },
- });
-
- const components = await db
- .select()
- .from(pageComponent)
- .where(eq(pageComponent.pageId, testPageId))
- .all();
- for (const c of components) createdComponentIds.push(c.id);
- const groups = await db
- .select()
- .from(pageComponentGroup)
- .where(eq(pageComponentGroup.pageId, testPageId))
- .all();
- expect(components).toHaveLength(3);
- expect(groups).toHaveLength(1);
-
- // Per-entity audit emits — assert one representative of each kind.
- // The service writes one row per component / group, so every id in
- // `components` + `groups` should appear, not a single page-level row.
- const monitorComponent = components.find((c) => c.type === "monitor");
- expect(monitorComponent).toBeDefined();
- if (!monitorComponent) throw new Error("unreachable");
- await expectAuditRow({
- workspaceId: teamCtx.workspace.id,
- action: "page_component.create",
- entityType: "page_component",
- entityId: monitorComponent.id,
+ }),
+ ).rejects.toBeInstanceOf(ForbiddenError);
});
+ });
- const group = groups[0];
- expect(group).toBeDefined();
- if (!group) throw new Error("unreachable");
- await expectAuditRow({
- workspaceId: teamCtx.workspace.id,
- action: "page_component_group.create",
- entityType: "page_component_group",
- entityId: group.id,
+ test("rejects cross-workspace pageId with ForbiddenError", async () => {
+ await withTestTransaction(async (tx) => {
+ await expect(
+ updatePageComponentOrder({
+ ctx: { ...freeCtx, db: tx },
+ input: {
+ pageId: testPageId, // team's page
+ components: [],
+ groups: [],
+ },
+ }),
+ ).rejects.toBeInstanceOf(ForbiddenError);
});
});
- test("rejects cross-workspace monitorId with ForbiddenError", async () => {
- await expect(
- updatePageComponentOrder({
- ctx: teamCtx,
+ test("upserts monitor components without creating duplicates", async () => {
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ // The `(pageId, monitorId)` unique constraint + `onConflictDoUpdate`
+ // is the riskiest path in this service: a regression here would
+ // silently insert duplicate rows on every re-invocation. Run the
+ // service twice with the same `monitorId` — expect exactly one
+ // row, with the second call's values winning the update.
+ await updatePageComponentOrder({
+ ctx,
input: {
pageId: testPageId,
components: [
{
order: 0,
- name: `${TEST_PREFIX}-cross-ws`,
+ name: `${TEST_PREFIX}-upsert-initial`,
type: "monitor",
- monitorId: freeMonitorId,
+ monitorId: teamMonitorId,
},
],
groups: [],
},
- }),
- ).rejects.toBeInstanceOf(ForbiddenError);
- });
-
- test("rejects cross-workspace pageId with ForbiddenError", async () => {
- await expect(
- updatePageComponentOrder({
- ctx: freeCtx,
+ });
+ await updatePageComponentOrder({
+ ctx,
input: {
- pageId: testPageId, // team's page
- components: [],
+ pageId: testPageId,
+ components: [
+ {
+ order: 5,
+ name: `${TEST_PREFIX}-upsert-renamed`,
+ type: "monitor",
+ monitorId: teamMonitorId,
+ },
+ ],
groups: [],
},
- }),
- ).rejects.toBeInstanceOf(ForbiddenError);
- });
+ });
- test("upserts monitor components without creating duplicates", async () => {
- // The `(pageId, monitorId)` unique constraint + `onConflictDoUpdate`
- // is the riskiest path in this service: a regression here would
- // silently insert duplicate rows on every re-invocation. Run the
- // service twice with the same `monitorId` — expect exactly one
- // row, with the second call's values winning the update.
- await updatePageComponentOrder({
- ctx: teamCtx,
- input: {
- pageId: testPageId,
- components: [
- {
- order: 0,
- name: `${TEST_PREFIX}-upsert-initial`,
- type: "monitor",
- monitorId: teamMonitorId,
- },
- ],
- groups: [],
- },
+ const rows = await tx
+ .select()
+ .from(pageComponent)
+ .where(
+ and(
+ eq(pageComponent.pageId, testPageId),
+ eq(pageComponent.type, "monitor"),
+ eq(pageComponent.monitorId, teamMonitorId),
+ ),
+ )
+ .all();
+ expect(rows).toHaveLength(1);
+ expect(rows[0]?.name).toBe(`${TEST_PREFIX}-upsert-renamed`);
+ expect(rows[0]?.order).toBe(5);
});
- await updatePageComponentOrder({
- ctx: teamCtx,
- input: {
- pageId: testPageId,
- components: [
- {
- order: 5,
- name: `${TEST_PREFIX}-upsert-renamed`,
- type: "monitor",
- monitorId: teamMonitorId,
- },
- ],
- groups: [],
- },
- });
-
- const rows = await db
- .select()
- .from(pageComponent)
- .where(
- and(
- eq(pageComponent.pageId, testPageId),
- eq(pageComponent.type, "monitor"),
- eq(pageComponent.monitorId, teamMonitorId),
- ),
- )
- .all();
- for (const r of rows) createdComponentIds.push(r.id);
- expect(rows).toHaveLength(1);
- expect(rows[0]?.name).toBe(`${TEST_PREFIX}-upsert-renamed`);
- expect(rows[0]?.order).toBe(5);
});
});
describe("listPageComponents", () => {
test("respects workspace isolation", async () => {
- const teamResult = await listPageComponents({
- ctx: teamCtx,
- input: { pageId: testPageId, order: "asc" },
- });
- expect(teamResult.length).toBeGreaterThan(0);
+ await withTestTransaction(async (tx) => {
+ const teamCtxTx = { ...teamCtx, db: tx };
+ const freeCtxTx = { ...freeCtx, db: tx };
+ // Seed at least one component on the team's page so the team-side
+ // listing has something to return.
+ await updatePageComponentOrder({
+ ctx: teamCtxTx,
+ input: {
+ pageId: testPageId,
+ components: [
+ {
+ order: 0,
+ name: `${TEST_PREFIX}-list-cmp`,
+ type: "static",
+ },
+ ],
+ groups: [],
+ },
+ });
+
+ const teamResult = await listPageComponents({
+ ctx: teamCtxTx,
+ input: { pageId: testPageId, order: "asc" },
+ });
+ expect(teamResult.length).toBeGreaterThan(0);
- const freeResult = await listPageComponents({
- ctx: freeCtx,
- input: { pageId: testPageId, order: "asc" },
+ const freeResult = await listPageComponents({
+ ctx: freeCtxTx,
+ input: { pageId: testPageId, order: "asc" },
+ });
+ expect(freeResult).toHaveLength(0);
});
- expect(freeResult).toHaveLength(0);
});
});
describe("deletePageComponent", () => {
test("throws NotFoundError for cross-workspace id", async () => {
- const [anyComponent] = await db
- .select()
- .from(pageComponent)
- .where(eq(pageComponent.pageId, testPageId))
- .all();
- if (!anyComponent) {
- throw new Error("test setup broken: no components present");
- }
+ await withTestTransaction(async (tx) => {
+ const teamCtxTx = { ...teamCtx, db: tx };
+ // Seed a component on the team page so the cross-workspace delete
+ // has a real target id rather than asserting against an empty page.
+ await updatePageComponentOrder({
+ ctx: teamCtxTx,
+ input: {
+ pageId: testPageId,
+ components: [
+ {
+ order: 0,
+ name: `${TEST_PREFIX}-delete-target`,
+ type: "static",
+ },
+ ],
+ groups: [],
+ },
+ });
+ const [anyComponent] = await tx
+ .select()
+ .from(pageComponent)
+ .where(eq(pageComponent.pageId, testPageId))
+ .all();
+ if (!anyComponent) {
+ throw new Error("test setup broken: no components present");
+ }
- await expect(
- deletePageComponent({
- ctx: freeCtx,
- input: { id: anyComponent.id },
- }),
- ).rejects.toBeInstanceOf(NotFoundError);
+ await expect(
+ deletePageComponent({
+ ctx: { ...freeCtx, db: tx },
+ input: { id: anyComponent.id },
+ }),
+ ).rejects.toBeInstanceOf(NotFoundError);
+ });
});
});
diff --git a/packages/services/src/page-subscriber/__tests__/page-subscriber.test.ts b/packages/services/src/page-subscriber/__tests__/page-subscriber.test.ts
new file mode 100644
index 000000000..c93b93840
--- /dev/null
+++ b/packages/services/src/page-subscriber/__tests__/page-subscriber.test.ts
@@ -0,0 +1,738 @@
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ beforeEach,
+ describe,
+ expect,
+ test,
+} from "bun:test";
+import { and, db, eq, sql } from "@openstatus/db";
+import {
+ auditLog,
+ pageSubscriber,
+ pageSubscriberToPageComponent,
+} from "@openstatus/db/src/schema";
+
+import {
+ getSubscriberByToken,
+ hasPendingSubscriber,
+ unsubscribeSubscriber,
+ updateSubscriberScope,
+ upsertSelfSignupSubscriber,
+ verifySelfSignupSubscriber,
+} from "..";
+import { SEEDED_WORKSPACE_TEAM_ID } from "../../../test/fixtures";
+import {
+ clearAuditLog,
+ expectAuditRow,
+ readAuditLog,
+} from "../../../test/helpers";
+
+// 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;
+
+// Each describe block owns its own email so suites are independent.
+const EMAILS = {
+ upsert: "[email protected]",
+ upsertCase: "[email protected]",
+ upsertReactivate: "[email protected]",
+ upsertPendingThenUnsub: "[email protected]",
+ planGate: "[email protected]",
+ verify: "[email protected]",
+ verifyExpired: "[email protected]",
+ getByToken: "[email protected]",
+ scope: "[email protected]",
+ scopeUnverified: "[email protected]",
+ scopeUnsubbed: "[email protected]",
+ unsub: "[email protected]",
+ hasPending: "[email protected]",
+};
+
+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);
+}
+
+beforeAll(cleanAll);
+afterAll(cleanAll);
+
+// ─── upsertSelfSignupSubscriber ──────────────────────────────────────────────
+
+describe("upsertSelfSignupSubscriber", () => {
+ const email = EMAILS.upsert;
+
+ beforeAll(async () => {
+ await db.delete(pageSubscriber).where(eq(pageSubscriber.email, email));
+ await clearAuditLog(SEEDED_WORKSPACE_TEAM_ID);
+ });
+
+ test("creates a new subscription for an unknown email", async () => {
+ const result = await upsertSelfSignupSubscriber({
+ input: { email, pageId: PAGE_ID },
+ });
+
+ expect(result.email).toBe(email);
+ expect(result.pageId).toBe(PAGE_ID);
+ expect(result.token).toBeDefined();
+ expect(result.acceptedAt).toBeNull();
+ expect(result.componentIds).toEqual([]);
+
+ // Audit row written, attributed to the subscriber (not a workspace user).
+ await expectAuditRow({
+ workspaceId: SEEDED_WORKSPACE_TEAM_ID,
+ action: "page_subscriber.create",
+ entityType: "page_subscriber",
+ entityId: result.id,
+ actorType: "subscriber",
+ });
+ });
+
+ test("token is stripped from the audit snapshot", async () => {
+ const fresh = "[email protected]";
+ await db.delete(pageSubscriber).where(eq(pageSubscriber.email, fresh));
+
+ const result = await upsertSelfSignupSubscriber({
+ input: { email: fresh, pageId: PAGE_ID },
+ });
+
+ const rows = await readAuditLog({
+ workspaceId: SEEDED_WORKSPACE_TEAM_ID,
+ entityType: "page_subscriber",
+ entityId: result.id,
+ });
+ const row = rows[0];
+ expect(row).toBeDefined();
+ // `after` is a JSON column — the schema parser hands us an object.
+ const after = row?.after as Record<string, unknown> | null;
+ expect(after).not.toBeNull();
+ expect(after).not.toHaveProperty("token");
+
+ await db.delete(pageSubscriber).where(eq(pageSubscriber.email, fresh));
+ });
+
+ test("does not create a duplicate row when called again", async () => {
+ await upsertSelfSignupSubscriber({ input: { email, pageId: PAGE_ID } });
+ const rows = await db.query.pageSubscriber.findMany({
+ where: eq(pageSubscriber.email, email),
+ });
+ expect(rows).toHaveLength(1);
+ });
+
+ test("merges new components into an existing pending subscription", async () => {
+ const result = await upsertSelfSignupSubscriber({
+ input: { email, pageId: PAGE_ID, componentIds: [COMPONENT_1] },
+ });
+ expect(result.componentIds).toContain(COMPONENT_1);
+
+ // Component-merge path emits an `update` audit row.
+ await expectAuditRow({
+ workspaceId: SEEDED_WORKSPACE_TEAM_ID,
+ action: "page_subscriber.update",
+ entityType: "page_subscriber",
+ entityId: result.id,
+ actorType: "subscriber",
+ });
+
+ // 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,
+ entityType: "page_subscriber",
+ entityId: result.id,
+ });
+ const updateRow = rows.find((r) => r.action === "page_subscriber.update");
+ const metadata = updateRow?.metadata as
+ | { componentIds?: number[] }
+ | null
+ | undefined;
+ expect(metadata?.componentIds).toContain(COMPONENT_1);
+ });
+
+ test("refreshes expiresAt for a still-pending subscription", async () => {
+ const before = new Date();
+ await upsertSelfSignupSubscriber({ input: { email, pageId: PAGE_ID } });
+ const row = await db.query.pageSubscriber.findFirst({
+ where: eq(pageSubscriber.email, email),
+ });
+ expect(row?.expiresAt?.getTime()).toBeGreaterThan(before.getTime());
+ });
+
+ test("stores email in lowercase regardless of input casing", async () => {
+ const fresh = EMAILS.upsertCase;
+ await db.delete(pageSubscriber).where(eq(pageSubscriber.email, fresh));
+ const result = await upsertSelfSignupSubscriber({
+ input: { email: fresh.toUpperCase(), pageId: PAGE_ID },
+ });
+ expect(result.email).toBe(fresh);
+ });
+
+ test("creates a new row (does not reactivate) when email was previously unsubscribed and accepted", async () => {
+ const fresh = EMAILS.upsertReactivate;
+ await db.delete(pageSubscriber).where(eq(pageSubscriber.email, fresh));
+ const initial = await upsertSelfSignupSubscriber({
+ input: { email: fresh, pageId: PAGE_ID },
+ });
+ await db
+ .update(pageSubscriber)
+ .set({ acceptedAt: new Date(), unsubscribedAt: new Date() })
+ .where(eq(pageSubscriber.id, initial.id))
+ .run();
+
+ const result = await upsertSelfSignupSubscriber({
+ input: { email: fresh, pageId: PAGE_ID, componentIds: [COMPONENT_1] },
+ });
+
+ expect(result.id).not.toBe(initial.id);
+ expect(result.acceptedAt).toBeNull();
+ expect(result.componentIds).toEqual([COMPONENT_1]);
+
+ const oldRow = await db.query.pageSubscriber.findFirst({
+ where: eq(pageSubscriber.id, initial.id),
+ });
+ expect(oldRow?.unsubscribedAt).toBeDefined();
+ });
+
+ test("creates a new row when previously unsubscribed before ever verifying", async () => {
+ const fresh = EMAILS.upsertPendingThenUnsub;
+ await db.delete(pageSubscriber).where(eq(pageSubscriber.email, fresh));
+ const pending = await upsertSelfSignupSubscriber({
+ input: { email: fresh, pageId: PAGE_ID },
+ });
+ await db
+ .update(pageSubscriber)
+ .set({ unsubscribedAt: new Date() })
+ .where(eq(pageSubscriber.id, pending.id))
+ .run();
+
+ const result = await upsertSelfSignupSubscriber({
+ input: { email: fresh, pageId: PAGE_ID },
+ });
+
+ expect(result.id).not.toBe(pending.id);
+ expect(result.acceptedAt).toBeNull();
+
+ const oldRow = await db.query.pageSubscriber.findFirst({
+ where: eq(pageSubscriber.id, pending.id),
+ });
+ expect(oldRow?.unsubscribedAt).toBeDefined();
+ expect(oldRow?.acceptedAt).toBeNull();
+ });
+
+ test("returns already-verified row without writing an audit row", async () => {
+ const fresh = "[email protected]";
+ await db.delete(pageSubscriber).where(eq(pageSubscriber.email, fresh));
+ const initial = await upsertSelfSignupSubscriber({
+ input: { email: fresh, pageId: PAGE_ID },
+ });
+ await db
+ .update(pageSubscriber)
+ .set({ acceptedAt: new Date() })
+ .where(eq(pageSubscriber.id, initial.id))
+ .run();
+
+ // Capture audit count before, then call upsert again.
+ await db
+ .delete(auditLog)
+ .where(
+ and(
+ eq(auditLog.workspaceId, SEEDED_WORKSPACE_TEAM_ID),
+ eq(auditLog.entityId, String(initial.id)),
+ ),
+ );
+
+ const result = await upsertSelfSignupSubscriber({
+ input: { email: fresh, pageId: PAGE_ID },
+ });
+ expect(result.id).toBe(initial.id);
+ expect(result.acceptedAt).not.toBeNull();
+
+ const rows = await readAuditLog({
+ workspaceId: SEEDED_WORKSPACE_TEAM_ID,
+ entityType: "page_subscriber",
+ entityId: initial.id,
+ });
+ expect(rows).toHaveLength(0);
+
+ await db.delete(pageSubscriber).where(eq(pageSubscriber.email, fresh));
+ });
+
+ test("throws for component IDs that do not belong to this page", async () => {
+ await expect(
+ upsertSelfSignupSubscriber({
+ input: { email, pageId: PAGE_ID, componentIds: [9999] },
+ }),
+ ).rejects.toThrow("Some components do not belong to this page");
+ });
+
+ test("throws for a page ID that does not exist", async () => {
+ await expect(
+ upsertSelfSignupSubscriber({
+ input: { email, pageId: 99999 },
+ }),
+ ).rejects.toThrow();
+ });
+
+ // Plan-gate: temporarily flip workspace 1's `status-subscribers` to
+ // false, hit the function, then restore. Mirrors the pattern in
+ // `apps/server/.../status-page.test.ts`.
+ test("rejects when the workspace plan disables status-subscribers", async () => {
+ await db.run(
+ sql`UPDATE workspace SET limits = json_set(COALESCE(limits, '{}'), '$."status-subscribers"', json('false')) WHERE id = ${SEEDED_WORKSPACE_TEAM_ID}`,
+ );
+ try {
+ await expect(
+ upsertSelfSignupSubscriber({
+ input: { email: EMAILS.planGate, pageId: PAGE_ID },
+ }),
+ ).rejects.toThrow("Upgrade to use status subscribers");
+ } finally {
+ await db.run(
+ sql`UPDATE workspace SET limits = json_set(COALESCE(limits, '{}'), '$."status-subscribers"', json('true')) WHERE id = ${SEEDED_WORKSPACE_TEAM_ID}`,
+ );
+ }
+ });
+});
+
+// ─── verifySelfSignupSubscriber ──────────────────────────────────────────────
+
+describe("verifySelfSignupSubscriber", () => {
+ const email = EMAILS.verify;
+ let pendingToken: string;
+ let pendingId: number;
+
+ beforeAll(async () => {
+ await db.delete(pageSubscriber).where(eq(pageSubscriber.email, email));
+ const sub = await upsertSelfSignupSubscriber({
+ input: { email, pageId: PAGE_ID },
+ });
+ if (!sub.token) throw new Error("Token is undefined");
+ pendingToken = sub.token;
+ pendingId = sub.id;
+ });
+
+ test("returns null for an unknown token", async () => {
+ const result = await verifySelfSignupSubscriber({
+ input: { token: "non-existent-token-xyz" },
+ });
+ expect(result).toBeNull();
+ });
+
+ test("returns null when domain does not match page slug", async () => {
+ const result = await verifySelfSignupSubscriber({
+ input: { token: pendingToken, domain: "wrong-domain" },
+ });
+ expect(result).toBeNull();
+ });
+
+ test("marks the subscription as accepted on first verification + emits audit row", async () => {
+ const result = await verifySelfSignupSubscriber({
+ input: { token: pendingToken, domain: PAGE_SLUG },
+ });
+ expect(result).not.toBeNull();
+ expect(result?.acceptedAt).toBeDefined();
+
+ await expectAuditRow({
+ workspaceId: SEEDED_WORKSPACE_TEAM_ID,
+ action: "page_subscriber.update",
+ entityType: "page_subscriber",
+ entityId: pendingId,
+ actorType: "subscriber",
+ });
+ });
+
+ test("returns an already-accepted subscription idempotently and does not double-audit", async () => {
+ // Clear audit rows for this entity, then call verify again.
+ await db
+ .delete(auditLog)
+ .where(
+ and(
+ eq(auditLog.workspaceId, SEEDED_WORKSPACE_TEAM_ID),
+ eq(auditLog.entityId, String(pendingId)),
+ ),
+ );
+
+ const result = await verifySelfSignupSubscriber({
+ input: { token: pendingToken, domain: PAGE_SLUG },
+ });
+ expect(result).not.toBeNull();
+ expect(result?.acceptedAt).toBeDefined();
+
+ const rows = await readAuditLog({
+ workspaceId: SEEDED_WORKSPACE_TEAM_ID,
+ entityType: "page_subscriber",
+ entityId: pendingId,
+ });
+ expect(rows).toHaveLength(0);
+ });
+
+ test("throws for a token with an expired expiresAt", async () => {
+ const expiredEmail = EMAILS.verifyExpired;
+ await db
+ .delete(pageSubscriber)
+ .where(eq(pageSubscriber.email, expiredEmail));
+
+ await db
+ .insert(pageSubscriber)
+ .values({
+ channelType: "email",
+ email: expiredEmail,
+ pageId: PAGE_ID,
+ token: "expired-token-xyz",
+ expiresAt: new Date(Date.now() - 1000),
+ })
+ .run();
+
+ await expect(
+ verifySelfSignupSubscriber({
+ input: { token: "expired-token-xyz" },
+ }),
+ ).rejects.toThrow("Verification token expired");
+ });
+});
+
+// ─── getSubscriberByToken ────────────────────────────────────────────────────
+
+describe("getSubscriberByToken", () => {
+ const email = EMAILS.getByToken;
+ let token: string;
+
+ beforeAll(async () => {
+ await db.delete(pageSubscriber).where(eq(pageSubscriber.email, email));
+ const sub = await upsertSelfSignupSubscriber({
+ input: { email, pageId: PAGE_ID },
+ });
+ if (!sub.token) throw new Error("Token is undefined");
+ token = sub.token;
+ });
+
+ test("returns null for an unknown token", async () => {
+ const result = await getSubscriberByToken({
+ input: { token: "unknown-token-xyz" },
+ });
+ expect(result).toBeNull();
+ });
+
+ test("returns null when domain does not match", async () => {
+ const result = await getSubscriberByToken({
+ input: { token, domain: "wrong-domain" },
+ });
+ expect(result).toBeNull();
+ });
+
+ test('masks the email address as "x***@domain"', async () => {
+ const result = await getSubscriberByToken({ input: { token } });
+ expect(result).not.toBeNull();
+ expect(result?.email).toMatch(/^s\*\*\*@example\.com$/);
+ expect(result?.email).not.toBe(email);
+ });
+
+ test("returns subscription data for a valid token and matching domain", async () => {
+ const result = await getSubscriberByToken({
+ input: { token, domain: PAGE_SLUG },
+ });
+ expect(result).not.toBeNull();
+ expect(result?.pageId).toBe(PAGE_ID);
+ expect(result?.pageSlug).toBe(PAGE_SLUG);
+ });
+
+ test("never emits an audit row (read-only)", async () => {
+ await db
+ .delete(auditLog)
+ .where(eq(auditLog.workspaceId, SEEDED_WORKSPACE_TEAM_ID));
+ await getSubscriberByToken({ input: { token, domain: PAGE_SLUG } });
+ const rows = await readAuditLog({
+ workspaceId: SEEDED_WORKSPACE_TEAM_ID,
+ entityType: "page_subscriber",
+ });
+ expect(rows).toHaveLength(0);
+ });
+});
+
+// ─── updateSubscriberScope ───────────────────────────────────────────────────
+
+describe("updateSubscriberScope", () => {
+ const email = EMAILS.scope;
+ let token: string;
+ let subscriberId: number;
+
+ beforeAll(async () => {
+ await db.delete(pageSubscriber).where(eq(pageSubscriber.email, email));
+ const sub = await upsertSelfSignupSubscriber({
+ input: { email, pageId: PAGE_ID, componentIds: [COMPONENT_1] },
+ });
+ if (!sub.token) throw new Error("Token is undefined");
+ token = sub.token;
+ subscriberId = sub.id;
+ await verifySelfSignupSubscriber({ input: { token } });
+ });
+
+ beforeEach(async () => {
+ await db
+ .delete(auditLog)
+ .where(
+ and(
+ eq(auditLog.workspaceId, SEEDED_WORKSPACE_TEAM_ID),
+ eq(auditLog.entityId, String(subscriberId)),
+ ),
+ );
+ });
+
+ test("throws for an unknown token", async () => {
+ await expect(
+ updateSubscriberScope({
+ input: { token: "unknown-token-xyz", componentIds: [] },
+ }),
+ ).rejects.toThrow();
+ });
+
+ test("throws when subscription is not yet verified", async () => {
+ await db
+ .delete(pageSubscriber)
+ .where(eq(pageSubscriber.email, EMAILS.scopeUnverified));
+ const sub = await upsertSelfSignupSubscriber({
+ input: { email: EMAILS.scopeUnverified, pageId: PAGE_ID },
+ });
+ if (!sub.token) throw new Error("Token is undefined");
+
+ await expect(
+ updateSubscriberScope({
+ input: { token: sub.token, componentIds: [] },
+ }),
+ ).rejects.toThrow("Subscription not yet verified");
+ });
+
+ test("throws when subscription is unsubscribed", async () => {
+ await db
+ .delete(pageSubscriber)
+ .where(eq(pageSubscriber.email, EMAILS.scopeUnsubbed));
+ const sub = await upsertSelfSignupSubscriber({
+ input: { email: EMAILS.scopeUnsubbed, pageId: PAGE_ID },
+ });
+ if (!sub.token) throw new Error("Token is undefined");
+ await verifySelfSignupSubscriber({ input: { token: sub.token } });
+ await unsubscribeSubscriber({ input: { token: sub.token } });
+
+ await expect(
+ updateSubscriberScope({
+ input: { token: sub.token, componentIds: [] },
+ }),
+ ).rejects.toThrow("Subscription is unsubscribed");
+ });
+
+ test("replaces existing component scope and emits an audit row with metadata", async () => {
+ await updateSubscriberScope({
+ input: { token, componentIds: [COMPONENT_2] },
+ });
+
+ const rowsAfter = await db
+ .select()
+ .from(pageSubscriberToPageComponent)
+ .where(eq(pageSubscriberToPageComponent.pageSubscriberId, subscriberId))
+ .all();
+ expect(rowsAfter.map((r) => r.pageComponentId)).toEqual([COMPONENT_2]);
+
+ const auditRows = await readAuditLog({
+ workspaceId: SEEDED_WORKSPACE_TEAM_ID,
+ entityType: "page_subscriber",
+ entityId: subscriberId,
+ });
+ const updateRow = auditRows.find(
+ (r) => r.action === "page_subscriber.update",
+ );
+ expect(updateRow).toBeDefined();
+ expect(updateRow?.actorType).toBe("subscriber");
+ const metadata = updateRow?.metadata as
+ | { componentIds?: number[]; previousComponentIds?: number[] }
+ | null
+ | undefined;
+ expect(metadata?.componentIds).toEqual([COMPONENT_2]);
+ expect(metadata?.previousComponentIds).toEqual([COMPONENT_1]);
+ });
+
+ test("can clear all components (entire-page scope)", async () => {
+ await updateSubscriberScope({ input: { token, componentIds: [] } });
+ const rowsAfter = await db
+ .select()
+ .from(pageSubscriberToPageComponent)
+ .where(eq(pageSubscriberToPageComponent.pageSubscriberId, subscriberId))
+ .all();
+ expect(rowsAfter).toHaveLength(0);
+ });
+
+ test("throws when a component does not belong to this page", async () => {
+ await expect(
+ updateSubscriberScope({
+ input: { token, componentIds: [9999] },
+ }),
+ ).rejects.toThrow("Some components do not belong to this page");
+ });
+});
+
+// ─── unsubscribeSubscriber ───────────────────────────────────────────────────
+
+describe("unsubscribeSubscriber", () => {
+ const email = EMAILS.unsub;
+ let token: string;
+ let subscriberId: number;
+
+ beforeAll(async () => {
+ await db.delete(pageSubscriber).where(eq(pageSubscriber.email, email));
+ const sub = await upsertSelfSignupSubscriber({
+ input: { email, pageId: PAGE_ID },
+ });
+ if (!sub.token) throw new Error("Token is undefined");
+ token = sub.token;
+ subscriberId = sub.id;
+ });
+
+ test("throws for an unknown token", async () => {
+ await expect(
+ unsubscribeSubscriber({ input: { token: "unknown-token-xyz" } }),
+ ).rejects.toThrow();
+ });
+
+ test("throws when the domain does not match", async () => {
+ await expect(
+ unsubscribeSubscriber({
+ input: { token, domain: "wrong-domain" },
+ }),
+ ).rejects.toThrow();
+ });
+
+ test("sets unsubscribedAt and emits an audit row", async () => {
+ await db
+ .delete(auditLog)
+ .where(
+ and(
+ eq(auditLog.workspaceId, SEEDED_WORKSPACE_TEAM_ID),
+ eq(auditLog.entityId, String(subscriberId)),
+ ),
+ );
+
+ await expect(
+ unsubscribeSubscriber({ input: { token, domain: PAGE_SLUG } }),
+ ).resolves.toBeUndefined();
+
+ const row = await db.query.pageSubscriber.findFirst({
+ where: eq(pageSubscriber.token, token),
+ });
+ expect(row?.unsubscribedAt).toBeDefined();
+
+ await expectAuditRow({
+ workspaceId: SEEDED_WORKSPACE_TEAM_ID,
+ action: "page_subscriber.update",
+ entityType: "page_subscriber",
+ entityId: subscriberId,
+ actorType: "subscriber",
+ });
+ });
+
+ test("is idempotent — second call does not emit a second audit row", async () => {
+ await db
+ .delete(auditLog)
+ .where(
+ and(
+ eq(auditLog.workspaceId, SEEDED_WORKSPACE_TEAM_ID),
+ eq(auditLog.entityId, String(subscriberId)),
+ ),
+ );
+
+ await expect(
+ unsubscribeSubscriber({ input: { token } }),
+ ).resolves.toBeUndefined();
+
+ const rows = await readAuditLog({
+ workspaceId: SEEDED_WORKSPACE_TEAM_ID,
+ entityType: "page_subscriber",
+ entityId: subscriberId,
+ });
+ expect(rows).toHaveLength(0);
+ });
+});
+
+// ─── hasPendingSubscriber ────────────────────────────────────────────────────
+
+describe("hasPendingSubscriber", () => {
+ const email = EMAILS.hasPending;
+
+ beforeAll(async () => {
+ await db.delete(pageSubscriber).where(eq(pageSubscriber.email, email));
+ });
+
+ afterEach(async () => {
+ await db.delete(pageSubscriber).where(eq(pageSubscriber.email, email));
+ });
+
+ test("returns false when no row exists", async () => {
+ const result = await hasPendingSubscriber({
+ input: { email, pageId: PAGE_ID },
+ });
+ expect(result).toBe(false);
+ });
+
+ test("returns true for a pending unexpired row", async () => {
+ await upsertSelfSignupSubscriber({
+ input: { email, pageId: PAGE_ID },
+ });
+ const result = await hasPendingSubscriber({
+ input: { email, pageId: PAGE_ID },
+ });
+ expect(result).toBe(true);
+ });
+
+ test("returns false for a pending row whose expiresAt has passed", async () => {
+ const sub = await upsertSelfSignupSubscriber({
+ input: { email, pageId: PAGE_ID },
+ });
+ await db
+ .update(pageSubscriber)
+ .set({ expiresAt: new Date(Date.now() - 1000) })
+ .where(eq(pageSubscriber.id, sub.id))
+ .run();
+
+ const result = await hasPendingSubscriber({
+ input: { email, pageId: PAGE_ID },
+ });
+ expect(result).toBe(false);
+ });
+
+ test("returns false for an already-verified (accepted) row", async () => {
+ const sub = await upsertSelfSignupSubscriber({
+ input: { email, pageId: PAGE_ID },
+ });
+ await db
+ .update(pageSubscriber)
+ .set({ acceptedAt: new Date() })
+ .where(eq(pageSubscriber.id, sub.id))
+ .run();
+
+ const result = await hasPendingSubscriber({
+ input: { email, pageId: PAGE_ID },
+ });
+ expect(result).toBe(false);
+ });
+
+ test("returns false for an unsubscribed row", async () => {
+ const sub = await upsertSelfSignupSubscriber({
+ input: { email, pageId: PAGE_ID },
+ });
+ await db
+ .update(pageSubscriber)
+ .set({ unsubscribedAt: new Date() })
+ .where(eq(pageSubscriber.id, sub.id))
+ .run();
+
+ const result = await hasPendingSubscriber({
+ input: { email, pageId: PAGE_ID },
+ });
+ expect(result).toBe(false);
+ });
+});
diff --git a/packages/services/src/page-subscriber/create.ts b/packages/services/src/page-subscriber/create.ts
new file mode 100644
index 000000000..1190f070e
--- /dev/null
+++ b/packages/services/src/page-subscriber/create.ts
@@ -0,0 +1,183 @@
+import { and, eq, inArray, isNull, sql } from "@openstatus/db";
+import {
+ pageComponent,
+ pageSubscriber,
+ pageSubscriberToPageComponent,
+ selectPageSubscriberSchema,
+} from "@openstatus/db/src/schema";
+import { detectWebhookFlavor } from "@openstatus/subscriptions";
+import { assertSafeUrl } from "@openstatus/utils";
+
+import { emitAudit } from "../audit";
+import { type ServiceContext, withTransaction } from "../context";
+import { ConflictError, ValidationError } from "../errors";
+import {
+ assertSubscribersAllowed,
+ loadPageForWorkspace,
+ parseWorkspaceForContext,
+} from "./internal";
+import { CreatePageSubscriberInput } from "./schemas";
+
+export type CreatePageSubscriberResult = {
+ id: number;
+ row: typeof pageSubscriber.$inferSelect;
+ componentIds: number[];
+};
+
+/**
+ * Create a **vendor-added** page subscriber — a workspace member adds
+ * someone (typically a partner) from the dashboard / RPC. Always
+ * inserts with `source: "vendor"`, skips the verification flow, stamps
+ * `acceptedAt` immediately. A `token` is still generated so the
+ * partner can self-manage via `/manage/{token}` and
+ * `/unsubscribe/{token}`.
+ *
+ * NOT for self-serve subscriptions originating from the public status
+ * page — those go through `upsertEmailSubscription` in
+ * `@openstatus/subscriptions`, which inserts with the default
+ * `source: "self_signup"`, runs the email verification flow, and
+ * intentionally emits no audit row (visitor action, not a workspace
+ * mutation).
+ *
+ * The dedup queries below are deliberately source-agnostic: an active
+ * row of *either* source for the same (page, email|webhookUrl) blocks
+ * the vendor add. That prevents duplicate notification fanout when a
+ * visitor self-subscribed before the vendor add.
+ *
+ * Single transaction: plan-gate, dedup, INSERT, join inserts, and the
+ * audit emit all run in one `withTransaction` block. A failed audit
+ * row rolls the subscriber back — fail-closed audit guarantee from
+ * CLAUDE.md is preserved.
+ */
+export async function createPageSubscriber(args: {
+ ctx: ServiceContext;
+ input: CreatePageSubscriberInput;
+}): Promise<CreatePageSubscriberResult> {
+ const { ctx } = args;
+ const input = CreatePageSubscriberInput.parse(args.input);
+ const componentIds = input.componentIds ?? [];
+
+ // Webhook URL pre-checks happen outside the tx. `assertSafeUrl` does
+ // a DNS resolution to block private/internal targets — keeping it
+ // outside avoids holding the SQLite write lock across a network call.
+ if (input.channelType === "webhook") {
+ await assertSafeUrl(input.webhookUrl);
+ if (detectWebhookFlavor(input.webhookUrl) === "generic") {
+ throw new ValidationError(
+ "Only Slack and Discord webhook URLs are supported.",
+ );
+ }
+ }
+
+ return withTransaction(ctx, async (tx) => {
+ const pageWithWorkspace = await loadPageForWorkspace({
+ tx,
+ pageId: input.pageId,
+ workspaceId: ctx.workspace.id,
+ });
+ assertSubscribersAllowed(
+ parseWorkspaceForContext(pageWithWorkspace.workspace),
+ );
+
+ if (componentIds.length > 0) {
+ const valid = await tx
+ .select({ id: pageComponent.id })
+ .from(pageComponent)
+ .where(
+ and(
+ eq(pageComponent.pageId, input.pageId),
+ inArray(pageComponent.id, componentIds),
+ ),
+ )
+ .all();
+ if (valid.length !== componentIds.length) {
+ throw new ValidationError("Some components do not belong to this page");
+ }
+ }
+
+ let emailLower: string | null = null;
+ let webhookUrl: string | null = null;
+ let channelConfig: string | null = null;
+
+ if (input.channelType === "email") {
+ emailLower = input.email.toLowerCase();
+ const dup = await tx.query.pageSubscriber.findFirst({
+ where: and(
+ eq(pageSubscriber.pageId, input.pageId),
+ eq(pageSubscriber.email, emailLower),
+ eq(pageSubscriber.channelType, "email"),
+ isNull(pageSubscriber.unsubscribedAt),
+ ),
+ });
+ if (dup) {
+ throw new ConflictError(
+ "A subscriber with this email already exists for this page.",
+ );
+ }
+ } else {
+ webhookUrl = input.webhookUrl;
+ const dup = await tx.query.pageSubscriber.findFirst({
+ where: and(
+ eq(pageSubscriber.pageId, input.pageId),
+ sql`LOWER(${pageSubscriber.webhookUrl}) = ${webhookUrl.toLowerCase()}`,
+ eq(pageSubscriber.channelType, "webhook"),
+ isNull(pageSubscriber.unsubscribedAt),
+ ),
+ });
+ if (dup) {
+ throw new ConflictError(
+ "A subscriber with this webhook URL already exists for this page.",
+ );
+ }
+ // Empty array is truthy in JS, so check `length > 0` — otherwise
+ // we'd persist `{"headers":[]}` instead of leaving the column null.
+ channelConfig =
+ input.headers && input.headers.length > 0
+ ? JSON.stringify({ headers: input.headers })
+ : null;
+ }
+
+ const row = await tx
+ .insert(pageSubscriber)
+ .values({
+ channelType: input.channelType,
+ email: emailLower,
+ webhookUrl,
+ channelConfig,
+ pageId: input.pageId,
+ source: "vendor",
+ name: input.name ?? null,
+ token: crypto.randomUUID(),
+ acceptedAt: new Date(),
+ expiresAt: null,
+ })
+ .returning()
+ .get();
+
+ if (componentIds.length > 0) {
+ await tx
+ .insert(pageSubscriberToPageComponent)
+ .values(
+ componentIds.map((compId) => ({
+ pageSubscriberId: row.id,
+ pageComponentId: compId,
+ })),
+ )
+ .run();
+ }
+
+ // Strip the management `token` — capability for the self-manage /
+ // unsubscribe URLs, must never land in the audit log.
+ const parsed = selectPageSubscriberSchema.parse(row);
+ const { token: _token, ...after } = parsed;
+ await emitAudit(tx, ctx, {
+ action: "page_subscriber.create",
+ entityType: "page_subscriber",
+ entityId: parsed.id,
+ after,
+ metadata: componentIds.length ? { componentIds } : undefined,
+ });
+
+ return { id: row.id, row, componentIds };
+ });
+}
diff --git a/packages/services/src/page-subscriber/delete.ts b/packages/services/src/page-subscriber/delete.ts
new file mode 100644
index 000000000..aaad1ca38
--- /dev/null
+++ b/packages/services/src/page-subscriber/delete.ts
@@ -0,0 +1,55 @@
+import { and, eq } from "@openstatus/db";
+import {
+ pageSubscriber,
+ selectPageSubscriberSchema,
+} from "@openstatus/db/src/schema";
+
+import { emitAudit } from "../audit";
+import { type ServiceContext, withTransaction } from "../context";
+import { NotFoundError } from "../errors";
+import { loadPageForWorkspace } from "./internal";
+import { DeletePageSubscriberInput } from "./schemas";
+
+/**
+ * Hard-delete a subscriber row from the dashboard. Page must belong to
+ * the caller's workspace and the subscriber must belong to that page;
+ * both are strict (no silent success), matching the legacy router.
+ */
+export async function deletePageSubscriber(args: {
+ ctx: ServiceContext;
+ input: DeletePageSubscriberInput;
+}): Promise<void> {
+ const { ctx } = args;
+ const input = DeletePageSubscriberInput.parse(args.input);
+
+ await withTransaction(ctx, async (tx) => {
+ await loadPageForWorkspace({
+ tx,
+ pageId: input.pageId,
+ workspaceId: ctx.workspace.id,
+ });
+
+ const [deleted] = await tx
+ .delete(pageSubscriber)
+ .where(
+ and(
+ eq(pageSubscriber.id, input.id),
+ eq(pageSubscriber.pageId, input.pageId),
+ ),
+ )
+ .returning();
+
+ if (!deleted) {
+ throw new NotFoundError("page_subscriber", input.id);
+ }
+
+ const parsed = selectPageSubscriberSchema.parse(deleted);
+ const { token: _token, ...before } = parsed;
+ await emitAudit(tx, ctx, {
+ action: "page_subscriber.delete",
+ entityType: "page_subscriber",
+ entityId: parsed.id,
+ before,
+ });
+ });
+}
diff --git a/packages/services/src/page-subscriber/get-by-token.ts b/packages/services/src/page-subscriber/get-by-token.ts
new file mode 100644
index 000000000..62088614b
--- /dev/null
+++ b/packages/services/src/page-subscriber/get-by-token.ts
@@ -0,0 +1,66 @@
+import type { DB } from "../context";
+import { resolveSubscriberByToken } from "./internal";
+import { GetSubscriberByTokenInput } from "./schemas";
+
+function maskEmail(email: string): string {
+ const [local, domain] = email.split("@");
+ if (!domain) return email;
+ const masked = local.length > 0 ? `${local[0]}***` : "***";
+ return `${masked}@${domain}`;
+}
+
+function maskWebhookUrl(webhookUrl: string): string {
+ try {
+ return `${new URL(webhookUrl).origin}***`;
+ } catch {
+ return "<malformed>";
+ }
+}
+
+export type SubscriberByTokenResult = {
+ id: number;
+ pageId: number;
+ pageName: string;
+ pageSlug: string;
+ customDomain: string | null;
+ channelType: "email" | "webhook";
+ email?: string;
+ webhookUrl?: string;
+ acceptedAt: Date | null;
+ unsubscribedAt: Date | null;
+ componentIds: number[];
+};
+
+/**
+ * Public, token-addressed read for the management UI. Email and
+ * webhook URL are masked: the token is a low-trust capability and the
+ * URL itself can carry credentials in its path (Slack/Discord webhooks).
+ * Read-only — no audit emit.
+ */
+export async function getSubscriberByToken(args: {
+ input: GetSubscriberByTokenInput;
+ db?: DB;
+}): Promise<SubscriberByTokenResult | null> {
+ const input = GetSubscriberByTokenInput.parse(args.input);
+ const resolved = await resolveSubscriberByToken({
+ db: args.db,
+ token: input.token,
+ domain: input.domain,
+ });
+ if (!resolved) return null;
+ const { row, pageData, components } = resolved;
+
+ return {
+ id: row.id,
+ pageId: row.pageId,
+ pageName: pageData.title,
+ pageSlug: pageData.slug,
+ customDomain: pageData.customDomain,
+ channelType: row.channelType,
+ email: row.email ? maskEmail(row.email) : undefined,
+ webhookUrl: row.webhookUrl ? maskWebhookUrl(row.webhookUrl) : undefined,
+ acceptedAt: row.acceptedAt,
+ unsubscribedAt: row.unsubscribedAt,
+ componentIds: components,
+ };
+}
diff --git a/packages/services/src/page-subscriber/has-pending.ts b/packages/services/src/page-subscriber/has-pending.ts
new file mode 100644
index 000000000..b65d9d8d2
--- /dev/null
+++ b/packages/services/src/page-subscriber/has-pending.ts
@@ -0,0 +1,30 @@
+import { and, eq, isNull } from "@openstatus/db";
+import { pageSubscriber } from "@openstatus/db/src/schema";
+
+import { type DB, type ServiceContext, getReadDb } from "../context";
+import { HasPendingSubscriberInput } from "./schemas";
+
+/**
+ * Anti-spam check used by the public subscribe flow: returns `true`
+ * when an unverified, unexpired self-signup row already exists for
+ * (email, page). Lets the router reject duplicate verification-email
+ * sends without round-tripping through `upsertSelfSignupSubscriber`.
+ */
+export async function hasPendingSubscriber(args: {
+ input: HasPendingSubscriberInput;
+ db?: DB;
+}): Promise<boolean> {
+ const input = HasPendingSubscriberInput.parse(args.input);
+ const db = getReadDb({ db: args.db } as ServiceContext);
+
+ const existing = await db.query.pageSubscriber.findFirst({
+ where: and(
+ eq(pageSubscriber.email, input.email.toLowerCase()),
+ eq(pageSubscriber.pageId, input.pageId),
+ eq(pageSubscriber.channelType, "email"),
+ isNull(pageSubscriber.unsubscribedAt),
+ isNull(pageSubscriber.acceptedAt),
+ ),
+ });
+ return !!(existing?.expiresAt && existing.expiresAt > new Date());
+}
diff --git a/packages/services/src/page-subscriber/index.ts b/packages/services/src/page-subscriber/index.ts
new file mode 100644
index 000000000..de18cb568
--- /dev/null
+++ b/packages/services/src/page-subscriber/index.ts
@@ -0,0 +1,39 @@
+export {
+ createPageSubscriber,
+ type CreatePageSubscriberResult,
+} from "./create";
+export { deletePageSubscriber } from "./delete";
+export {
+ type SubscriberByTokenResult,
+ getSubscriberByToken,
+} from "./get-by-token";
+export { hasPendingSubscriber } from "./has-pending";
+export {
+ listPageSubscribers,
+ type PageSubscriberListItem,
+} from "./list";
+export { sendPageSubscriberTestWebhook } from "./send-test-webhook";
+export { unsubscribeSubscriber } from "./unsubscribe";
+export { updatePageSubscriberChannel } from "./update";
+export { updateSubscriberScope } from "./update-scope";
+export {
+ type UpsertSelfSignupResult,
+ upsertSelfSignupSubscriber,
+} from "./upsert";
+export { type VerifyResult, verifySelfSignupSubscriber } from "./verify";
+export {
+ CreatePageSubscriberInput,
+ DeletePageSubscriberInput,
+ GetSubscriberByTokenInput,
+ HasPendingSubscriberInput,
+ ListPageSubscribersInput,
+ SendPageSubscriberTestWebhookInput,
+ UnsubscribeSubscriberInput,
+ UpdatePageSubscriberChannelInput,
+ UpdateSubscriberScopeInput,
+ UpsertSelfSignupSubscriberInput,
+ VerifySelfSignupSubscriberInput,
+} from "./schemas";
+// Exposed so the (router-side) public procedures can use the same
+// allow-list as the protected procedures going through `toTRPCError`.
+export { SAFE_SUBSCRIPTION_MESSAGES } from "./internal";
diff --git a/packages/services/src/page-subscriber/internal.ts b/packages/services/src/page-subscriber/internal.ts
new file mode 100644
index 000000000..c98c6bd99
--- /dev/null
+++ b/packages/services/src/page-subscriber/internal.ts
@@ -0,0 +1,160 @@
+import { and, eq } from "@openstatus/db";
+import {
+ type Workspace,
+ page,
+ pageSubscriber,
+ selectWorkspaceSchema,
+} from "@openstatus/db/src/schema";
+
+import { type DB, type ServiceContext, getReadDb } from "../context";
+import { ForbiddenError, NotFoundError, ValidationError } from "../errors";
+
+/**
+ * Page-in-workspace guard with the owning workspace eagerly loaded — so
+ * callers that need to plan-gate off `workspace.limits` don't have to
+ * issue a second query.
+ */
+export async function loadPageForWorkspace(args: {
+ tx: DB;
+ pageId: number;
+ workspaceId: number;
+}) {
+ const row = await args.tx.query.page.findFirst({
+ where: and(
+ eq(page.workspaceId, args.workspaceId),
+ eq(page.id, args.pageId),
+ ),
+ with: { workspace: true },
+ });
+ if (!row) {
+ throw new NotFoundError("page", args.pageId);
+ }
+ return row;
+}
+
+/**
+ * Plan-gate: enterprise / Pro plans have `status-subscribers: true`; free
+ * plan is `false`. Preserves the legacy FORBIDDEN semantics (not 429) —
+ * it's not a rate limit, the feature is a tier upsell.
+ */
+export function assertSubscribersAllowed(workspace: Workspace): void {
+ if (!workspace.limits["status-subscribers"]) {
+ throw new ForbiddenError("Upgrade to use status subscribers");
+ }
+}
+
+/**
+ * Parse a `workspace` row (from a drizzle relational `with: { workspace: true }`
+ * fetch) into the schema-validated `Workspace` shape that `ServiceContext`
+ * expects. The raw row carries `limits` as a JSON string; the schema parses
+ * it into the structured limits object.
+ */
+export function parseWorkspaceForContext(workspaceRow: unknown): Workspace {
+ const parsed = selectWorkspaceSchema.safeParse(workspaceRow);
+ if (!parsed.success) {
+ throw new ValidationError("Workspace data is invalid");
+ }
+ return parsed.data;
+}
+
+export type ResolvedSubscriber = {
+ row: typeof pageSubscriber.$inferSelect;
+ pageData: {
+ id: number;
+ title: string;
+ slug: string;
+ customDomain: string | null;
+ workspace: Workspace;
+ };
+ components: number[];
+};
+
+/**
+ * Token-addressed lookup used by every public-facing subscriber verb
+ * (`verify`, `getByToken`, `updateScope`, `unsubscribe`). Returns the
+ * subscriber row, the parsed page+workspace (so callers can build a
+ * `ServiceContext` for audit emission), and the current component-id
+ * scope. Returns `null` if the token doesn't resolve, or if the
+ * optional `domain` doesn't match the page slug or its custom domain —
+ * we don't distinguish those two failures (no leak of which pages exist
+ * for a given token).
+ */
+export async function resolveSubscriberByToken(args: {
+ db?: DB;
+ token: string;
+ domain?: string;
+}): Promise<ResolvedSubscriber | null> {
+ const readDb = getReadDb({ db: args.db } as ServiceContext);
+ const subscription = await readDb.query.pageSubscriber.findFirst({
+ where: eq(pageSubscriber.token, args.token),
+ with: {
+ page: { with: { workspace: true } },
+ components: true,
+ },
+ });
+ if (!subscription) return null;
+
+ if (args.domain) {
+ const domainLower = args.domain.toLowerCase();
+ const pageSlugLower = subscription.page.slug.toLowerCase();
+ const customDomainLower = subscription.page.customDomain?.toLowerCase();
+ if (domainLower !== pageSlugLower && domainLower !== customDomainLower) {
+ return null;
+ }
+ }
+
+ const workspace = parseWorkspaceForContext(subscription.page.workspace);
+ const { components, page: pageRow, ...row } = subscription;
+ return {
+ row,
+ pageData: {
+ id: pageRow.id,
+ title: pageRow.title,
+ slug: pageRow.slug,
+ customDomain: pageRow.customDomain,
+ workspace,
+ },
+ components: components.map((c) => c.pageComponentId),
+ };
+}
+
+/**
+ * Messages thrown by `@openstatus/subscriptions` that represent caller-
+ * facing validation rather than internal failure. Surfacing the message
+ * verbatim is safe (verified by review when each variant is added); any
+ * other thrown message should bubble as INTERNAL so we never leak row
+ * ids, raw SQL, or unvetted strings.
+ *
+ * Single source of truth for both the protected (dashboard) procedures —
+ * which go through this file — and the public (status-page) procedures,
+ * which import the set via `SAFE_SUBSCRIPTION_MESSAGES`.
+ */
+export const SAFE_SUBSCRIPTION_MESSAGES = new Set<string>([
+ "Page not found",
+ "Some components do not belong to this page",
+ "A subscriber with this email already exists for this page.",
+ "A subscriber with this webhook URL already exists for this page.",
+ "Only Slack and Discord webhook URLs are supported.",
+ "Subscriber not found",
+ "Subscriber is not a webhook channel",
+ "Self-signup subscribers manage their own subscription; use the unsubscribe action instead.",
+ "Email subscribers do not have webhook fields to edit.",
+ "Only vendor-added webhook subscribers support test dispatch.",
+ "Subscription not found",
+ "Subscription not yet verified",
+ "Subscription is unsubscribed",
+ "Verification token expired",
+]);
+
+/**
+ * Rethrow a `subscriptions` error either as a `ValidationError` (for the
+ * allow-listed message set) or as the original error — the outer adapter
+ * maps anything non-ServiceError to `INTERNAL_SERVER_ERROR`, so unknown
+ * messages don't leak to clients.
+ */
+export function rethrowSubscriptionError(error: unknown): never {
+ if (error instanceof Error && SAFE_SUBSCRIPTION_MESSAGES.has(error.message)) {
+ throw new ValidationError(error.message);
+ }
+ throw error;
+}
diff --git a/packages/services/src/page-subscriber/list.ts b/packages/services/src/page-subscriber/list.ts
new file mode 100644
index 000000000..2e4343128
--- /dev/null
+++ b/packages/services/src/page-subscriber/list.ts
@@ -0,0 +1,105 @@
+import { and, eq } from "@openstatus/db";
+import { page, pageSubscriber } from "@openstatus/db/src/schema";
+
+import { type ServiceContext, getReadDb } from "../context";
+import { NotFoundError } from "../errors";
+import { ListPageSubscribersInput } from "./schemas";
+
+/**
+ * Reduce a webhook URL to its origin for non-vendor rows so the secret
+ * path isn't exposed back through the dashboard list. Vendor rows own the
+ * full URL + channelConfig and get it verbatim.
+ *
+ * Malformed URLs surface as a `<malformed>` sentinel + a warning log
+ * rather than `null`. `null` would silently drop the row's destination
+ * from the dashboard, hiding a row that needs operator attention.
+ */
+function webhookUrlForList(
+ subscriberId: number,
+ source: string,
+ webhookUrl: string | null,
+): string | null {
+ if (!webhookUrl) return null;
+ if (source === "vendor") return webhookUrl;
+ try {
+ return new URL(webhookUrl).origin;
+ } catch {
+ console.warn("page_subscriber row has a malformed webhook URL", {
+ subscriberId,
+ source,
+ });
+ return "<malformed>";
+ }
+}
+
+export type PageSubscriberListItem = {
+ id: number;
+ channelType: "email" | "webhook";
+ email: string | null;
+ webhookUrl: string | null;
+ channelConfig: string | null;
+ source: "self_signup" | "vendor" | "import";
+ name: string | null;
+ acceptedAt: Date | null;
+ unsubscribedAt: Date | null;
+ createdAt: Date | null;
+ components: { id: number; name: string }[];
+ isEntirePage: boolean;
+ pageId: number;
+};
+
+/**
+ * List all subscribers for a page owned by the caller's workspace.
+ * Order defaults to `desc` (newest first) — matches the router default.
+ */
+export async function listPageSubscribers(args: {
+ ctx: ServiceContext;
+ input: ListPageSubscribersInput;
+}): Promise<PageSubscriberListItem[]> {
+ const { ctx } = args;
+ const input = ListPageSubscribersInput.parse(args.input);
+ const db = getReadDb(ctx);
+
+ const pageRow = await db.query.page.findFirst({
+ where: and(
+ eq(page.workspaceId, ctx.workspace.id),
+ eq(page.id, input.pageId),
+ ),
+ });
+ if (!pageRow) {
+ throw new NotFoundError("page", input.pageId);
+ }
+
+ const subscriptions = await db.query.pageSubscriber.findMany({
+ where: eq(pageSubscriber.pageId, pageRow.id),
+ with: {
+ components: {
+ with: { pageComponent: true },
+ },
+ },
+ orderBy: (subs, { desc, asc }) =>
+ input.order === "asc" ? asc(subs.createdAt) : desc(subs.createdAt),
+ });
+
+ return subscriptions.map((sub) => {
+ const isVendor = sub.source === "vendor";
+ return {
+ id: sub.id,
+ channelType: sub.channelType,
+ email: sub.email,
+ webhookUrl: webhookUrlForList(sub.id, sub.source, sub.webhookUrl),
+ channelConfig: isVendor ? sub.channelConfig : null,
+ source: sub.source,
+ name: sub.name,
+ acceptedAt: sub.acceptedAt,
+ unsubscribedAt: sub.unsubscribedAt,
+ createdAt: sub.createdAt,
+ components: sub.components.map((c) => ({
+ id: c.pageComponent.id,
+ name: c.pageComponent.name,
+ })),
+ isEntirePage: sub.components.length === 0,
+ pageId: sub.pageId,
+ };
+ });
+}
diff --git a/packages/services/src/page-subscriber/schemas.ts b/packages/services/src/page-subscriber/schemas.ts
new file mode 100644
index 000000000..da196c5ea
--- /dev/null
+++ b/packages/services/src/page-subscriber/schemas.ts
@@ -0,0 +1,119 @@
+import { z } from "zod";
+
+const componentIdList = z.array(z.number().int().positive()).max(500);
+
+const webhookHeaders = z
+ .array(
+ z.object({
+ key: z.string().min(1).max(256),
+ value: z.string().max(4096),
+ }),
+ )
+ .max(20);
+
+export const ListPageSubscribersInput = z.object({
+ pageId: z.number().int().positive(),
+ order: z.enum(["asc", "desc"]).optional(),
+});
+export type ListPageSubscribersInput = z.infer<typeof ListPageSubscribersInput>;
+
+export const CreatePageSubscriberInput = z.discriminatedUnion("channelType", [
+ z.object({
+ pageId: z.number().int().positive(),
+ channelType: z.literal("email"),
+ email: z.email(),
+ name: z.string().max(255).nullish(),
+ componentIds: componentIdList.optional(),
+ }),
+ z.object({
+ pageId: z.number().int().positive(),
+ channelType: z.literal("webhook"),
+ webhookUrl: z.url(),
+ name: z.string().max(255).nullish(),
+ headers: webhookHeaders.optional(),
+ componentIds: componentIdList.optional(),
+ }),
+]);
+export type CreatePageSubscriberInput = z.infer<
+ typeof CreatePageSubscriberInput
+>;
+
+export const UpdatePageSubscriberChannelInput = z.object({
+ subscriberId: z.number().int().positive(),
+ pageId: z.number().int().positive(),
+ name: z.string().max(255).nullish(),
+ webhookUrl: z.url().optional(),
+ headers: webhookHeaders.optional(),
+ componentIds: componentIdList.optional(),
+});
+export type UpdatePageSubscriberChannelInput = z.infer<
+ typeof UpdatePageSubscriberChannelInput
+>;
+
+export const SendPageSubscriberTestWebhookInput = z.object({
+ subscriberId: z.number().int().positive(),
+ pageId: z.number().int().positive(),
+});
+export type SendPageSubscriberTestWebhookInput = z.infer<
+ typeof SendPageSubscriberTestWebhookInput
+>;
+
+export const DeletePageSubscriberInput = z.object({
+ id: z.number().int().positive(),
+ pageId: z.number().int().positive(),
+});
+export type DeletePageSubscriberInput = z.infer<
+ typeof DeletePageSubscriberInput
+>;
+
+// ===== Self-signup (visitor-driven) =====
+
+export const UpsertSelfSignupSubscriberInput = z.object({
+ email: z.email(),
+ pageId: z.number().int().positive(),
+ componentIds: componentIdList.optional(),
+});
+export type UpsertSelfSignupSubscriberInput = z.infer<
+ typeof UpsertSelfSignupSubscriberInput
+>;
+
+export const VerifySelfSignupSubscriberInput = z.object({
+ token: z.string(),
+ domain: z.string().toLowerCase().optional(),
+});
+export type VerifySelfSignupSubscriberInput = z.infer<
+ typeof VerifySelfSignupSubscriberInput
+>;
+
+export const GetSubscriberByTokenInput = z.object({
+ token: z.string(),
+ domain: z.string().toLowerCase().optional(),
+});
+export type GetSubscriberByTokenInput = z.infer<
+ typeof GetSubscriberByTokenInput
+>;
+
+export const HasPendingSubscriberInput = z.object({
+ email: z.email(),
+ pageId: z.number().int().positive(),
+});
+export type HasPendingSubscriberInput = z.infer<
+ typeof HasPendingSubscriberInput
+>;
+
+export const UpdateSubscriberScopeInput = z.object({
+ token: z.string(),
+ componentIds: componentIdList,
+ domain: z.string().toLowerCase().optional(),
+});
+export type UpdateSubscriberScopeInput = z.infer<
+ typeof UpdateSubscriberScopeInput
+>;
+
+export const UnsubscribeSubscriberInput = z.object({
+ token: z.string(),
+ domain: z.string().toLowerCase().optional(),
+});
+export type UnsubscribeSubscriberInput = z.infer<
+ typeof UnsubscribeSubscriberInput
+>;
diff --git a/packages/services/src/page-subscriber/send-test-webhook.ts b/packages/services/src/page-subscriber/send-test-webhook.ts
new file mode 100644
index 000000000..2c62f3391
--- /dev/null
+++ b/packages/services/src/page-subscriber/send-test-webhook.ts
@@ -0,0 +1,80 @@
+import { and, eq } from "@openstatus/db";
+import { pageSubscriber } from "@openstatus/db/src/schema";
+import {
+ detectWebhookFlavor,
+ sendTestWebhookRequest,
+} from "@openstatus/subscriptions";
+
+import { type ServiceContext, withTransaction } from "../context";
+import { NotFoundError, ValidationError } from "../errors";
+import { loadPageForWorkspace } from "./internal";
+import { SendPageSubscriberTestWebhookInput } from "./schemas";
+
+/**
+ * Send a test payload to a vendor-added webhook subscriber.
+ *
+ * No audit emit — a test dispatch has no effect on the entity's durable
+ * state. If we add "last-tested-at" bookkeeping later, we'd revisit.
+ */
+export async function sendPageSubscriberTestWebhook(args: {
+ ctx: ServiceContext;
+ input: SendPageSubscriberTestWebhookInput;
+}): Promise<void> {
+ const { ctx } = args;
+ const input = SendPageSubscriberTestWebhookInput.parse(args.input);
+
+ const existing = await withTransaction(ctx, async (tx) => {
+ await loadPageForWorkspace({
+ tx,
+ pageId: input.pageId,
+ workspaceId: ctx.workspace.id,
+ });
+ return tx.query.pageSubscriber.findFirst({
+ where: and(
+ eq(pageSubscriber.id, input.subscriberId),
+ eq(pageSubscriber.pageId, input.pageId),
+ ),
+ });
+ });
+
+ if (!existing) {
+ throw new NotFoundError("page_subscriber", input.subscriberId);
+ }
+ if (existing.source !== "vendor") {
+ throw new ValidationError(
+ "Only vendor-added webhook subscribers support test dispatch.",
+ );
+ }
+ if (existing.channelType !== "webhook" || !existing.webhookUrl) {
+ throw new ValidationError("Subscriber is not a webhook channel");
+ }
+ if (existing.unsubscribedAt) {
+ throw new ValidationError("Subscriber is unsubscribed");
+ }
+
+ const flavor = detectWebhookFlavor(existing.webhookUrl);
+ const headers = parseWebhookHeaders(existing.channelConfig);
+ await sendTestWebhookRequest({
+ url: existing.webhookUrl,
+ flavor,
+ headers,
+ });
+}
+
+function parseWebhookHeaders(
+ channelConfig: string | null,
+): Record<string, string> {
+ if (!channelConfig) return {};
+ try {
+ const config = JSON.parse(channelConfig) as {
+ headers?: { key: string; value: string }[];
+ };
+ const headers: Record<string, string> = {};
+ for (const h of config.headers ?? []) {
+ headers[h.key] = h.value;
+ }
+ return headers;
+ } catch {
+ return {};
+ }
+}
diff --git a/packages/services/src/page-subscriber/unsubscribe.ts b/packages/services/src/page-subscriber/unsubscribe.ts
new file mode 100644
index 000000000..d5cc93ff3
--- /dev/null
+++ b/packages/services/src/page-subscriber/unsubscribe.ts
@@ -0,0 +1,61 @@
+import { eq } from "@openstatus/db";
+import {
+ pageSubscriber,
+ selectPageSubscriberSchema,
+} from "@openstatus/db/src/schema";
+
+import { emitAudit } from "../audit";
+import { type DB, type ServiceContext, withTransaction } from "../context";
+import { NotFoundError } from "../errors";
+import { resolveSubscriberByToken } from "./internal";
+import { UnsubscribeSubscriberInput } from "./schemas";
+
+/**
+ * Token-addressed unsubscribe, both for self-signup and vendor-added
+ * rows (the action is the same — set `unsubscribedAt`). Idempotent: a
+ * second call on an already-unsubscribed row returns silently with no
+ * audit emit.
+ */
+export async function unsubscribeSubscriber(args: {
+ input: UnsubscribeSubscriberInput;
+ db?: DB;
+}): Promise<void> {
+ const input = UnsubscribeSubscriberInput.parse(args.input);
+
+ const resolved = await resolveSubscriberByToken({
+ db: args.db,
+ token: input.token,
+ domain: input.domain,
+ });
+ if (!resolved) throw new NotFoundError("page_subscriber");
+ const { row, pageData } = resolved;
+
+ // Idempotent — no row, no audit on the second call.
+ if (row.unsubscribedAt) return;
+
+ await withTransaction({ db: args.db } as ServiceContext, async (tx) => {
+ const before = selectPageSubscriberSchema.parse(row);
+ const updated = await tx
+ .update(pageSubscriber)
+ .set({ unsubscribedAt: new Date(), updatedAt: new Date() })
+ .where(eq(pageSubscriber.id, row.id))
+ .returning()
+ .get();
+ const after = selectPageSubscriberSchema.parse(updated ?? row);
+
+ const auditCtx: ServiceContext = {
+ workspace: pageData.workspace,
+ actor: { type: "subscriber", subscriberId: row.id },
+ db: tx,
+ };
+ const { token: _bt, ...beforeSnap } = before;
+ const { token: _at, ...afterSnap } = after;
+ await emitAudit(tx, auditCtx, {
+ action: "page_subscriber.update",
+ entityType: "page_subscriber",
+ entityId: row.id,
+ before: beforeSnap,
+ after: afterSnap,
+ });
+ });
+}
diff --git a/packages/services/src/page-subscriber/update-scope.ts b/packages/services/src/page-subscriber/update-scope.ts
new file mode 100644
index 000000000..42f571f15
--- /dev/null
+++ b/packages/services/src/page-subscriber/update-scope.ts
@@ -0,0 +1,117 @@
+import { and, eq, inArray } from "@openstatus/db";
+import {
+ pageComponent,
+ pageSubscriber,
+ pageSubscriberToPageComponent,
+ selectPageSubscriberSchema,
+} from "@openstatus/db/src/schema";
+
+import { emitAudit } from "../audit";
+import { type DB, type ServiceContext, withTransaction } from "../context";
+import { NotFoundError, ValidationError } from "../errors";
+import { resolveSubscriberByToken } from "./internal";
+import { UpdateSubscriberScopeInput } from "./schemas";
+
+/**
+ * Replace a self-signup subscriber's component scope (the set of
+ * components they receive notifications for). Token-addressed; the
+ * subscriber acts on themselves, so the audit row is attributed to
+ * `subscriber:{id}`.
+ *
+ * Component-only changes don't show up in `selectPageSubscriberSchema`
+ * — `componentIds` is on the join table, not the row — so we surface
+ * them via `metadata` to keep the audit row from being dropped by the
+ * empty-diff guard in `emitAudit`.
+ */
+export async function updateSubscriberScope(args: {
+ input: UpdateSubscriberScopeInput;
+ db?: DB;
+}): Promise<void> {
+ const input = UpdateSubscriberScopeInput.parse(args.input);
+
+ const resolved = await resolveSubscriberByToken({
+ db: args.db,
+ token: input.token,
+ domain: input.domain,
+ });
+ if (!resolved) throw new NotFoundError("page_subscriber");
+ const { row, pageData, components: currentIds } = resolved;
+
+ if (!row.acceptedAt) {
+ throw new ValidationError("Subscription not yet verified");
+ }
+ if (row.unsubscribedAt) {
+ throw new ValidationError("Subscription is unsubscribed");
+ }
+
+ await withTransaction({ db: args.db } as ServiceContext, async (tx) => {
+ if (input.componentIds.length > 0) {
+ const valid = await tx
+ .select({ id: pageComponent.id })
+ .from(pageComponent)
+ .where(
+ and(
+ eq(pageComponent.pageId, row.pageId),
+ inArray(pageComponent.id, input.componentIds),
+ ),
+ )
+ .all();
+ if (valid.length !== input.componentIds.length) {
+ throw new ValidationError("Some components do not belong to this page");
+ }
+ }
+
+ await tx
+ .delete(pageSubscriberToPageComponent)
+ .where(eq(pageSubscriberToPageComponent.pageSubscriberId, row.id))
+ .run();
+
+ if (input.componentIds.length > 0) {
+ await tx
+ .insert(pageSubscriberToPageComponent)
+ .values(
+ input.componentIds.map((id) => ({
+ pageSubscriberId: row.id,
+ pageComponentId: id,
+ })),
+ )
+ .run();
+ }
+
+ const before = selectPageSubscriberSchema.parse(row);
+ const updated = await tx
+ .update(pageSubscriber)
+ .set({ updatedAt: new Date() })
+ .where(eq(pageSubscriber.id, row.id))
+ .returning()
+ .get();
+ const after = selectPageSubscriberSchema.parse(updated ?? row);
+
+ const auditCtx: ServiceContext = {
+ workspace: pageData.workspace,
+ actor: { type: "subscriber", subscriberId: row.id },
+ db: tx,
+ };
+ const { token: _bt, ...beforeSnap } = before;
+ const { token: _at, ...afterSnap } = after;
+
+ // Sort defensively — the diff is order-sensitive for arrays, but the
+ // semantic identity of the scope is set-equality, not list order.
+ const previous = [...currentIds].sort((a, b) => a - b);
+ const next = [...input.componentIds].sort((a, b) => a - b);
+ const changed =
+ previous.length !== next.length ||
+ previous.some((id, i) => id !== next[i]);
+
+ await emitAudit(tx, auditCtx, {
+ action: "page_subscriber.update",
+ entityType: "page_subscriber",
+ entityId: row.id,
+ before: beforeSnap,
+ after: afterSnap,
+ ...(changed
+ ? { metadata: { previousComponentIds: previous, componentIds: next } }
+ : {}),
+ });
+ });
+}
diff --git a/packages/services/src/page-subscriber/update.ts b/packages/services/src/page-subscriber/update.ts
new file mode 100644
index 000000000..5d1fd323c
--- /dev/null
+++ b/packages/services/src/page-subscriber/update.ts
@@ -0,0 +1,187 @@
+import { and, eq, inArray, isNull, ne, sql } from "@openstatus/db";
+import {
+ page,
+ pageComponent,
+ pageSubscriber,
+ pageSubscriberToPageComponent,
+ selectPageSubscriberSchema,
+} from "@openstatus/db/src/schema";
+import { detectWebhookFlavor } from "@openstatus/subscriptions";
+import { assertSafeUrl } from "@openstatus/utils";
+
+import { emitAudit } from "../audit";
+import { type ServiceContext, withTransaction } from "../context";
+import { ConflictError, NotFoundError, ValidationError } from "../errors";
+import { UpdatePageSubscriberChannelInput } from "./schemas";
+
+/**
+ * Update a vendor-added subscription's name / webhook URL / headers /
+ * component scope. Page ownership is enforced by joining the subscriber
+ * fetch to `page` — a single SELECT that confirms (subscriber, page,
+ * workspace) all line up.
+ *
+ * The auth check, channel write, and audit emit run in one transaction:
+ * a failed audit insert rolls the channel write back, and there's no
+ * race window between ownership confirmation and mutation.
+ *
+ * Row-level eligibility (vendor vs self-signup, email vs webhook) is
+ * enforced inline below — the legacy `updateChannel` helper in
+ * `@openstatus/subscriptions` opened its own DB handle so it couldn't
+ * share the caller's tx; the logic now lives here instead.
+ */
+export async function updatePageSubscriberChannel(args: {
+ ctx: ServiceContext;
+ input: UpdatePageSubscriberChannelInput;
+}): Promise<void> {
+ const { ctx } = args;
+ const input = UpdatePageSubscriberChannelInput.parse(args.input);
+
+ // `assertSafeUrl` does a DNS lookup to block private/internal targets;
+ // keep it outside the tx so we don't hold the SQLite write lock across
+ // a network call. Flavor check is pure and stays here for symmetry.
+ if (input.webhookUrl !== undefined) {
+ await assertSafeUrl(input.webhookUrl);
+ if (detectWebhookFlavor(input.webhookUrl) === "generic") {
+ throw new ValidationError(
+ "Only Slack and Discord webhook URLs are supported.",
+ );
+ }
+ }
+
+ await withTransaction(ctx, async (tx) => {
+ // One query confirms the subscriber exists, that it's attached to the
+ // supplied page, and that the page belongs to the caller's workspace.
+ // Any miss surfaces as 404 — we don't distinguish "wrong page" from
+ // "wrong workspace" to avoid leaking cross-workspace existence.
+ const beforeJoined = await tx
+ .select({ subscriber: pageSubscriber })
+ .from(pageSubscriber)
+ .innerJoin(page, eq(pageSubscriber.pageId, page.id))
+ .where(
+ and(
+ eq(pageSubscriber.id, input.subscriberId),
+ eq(pageSubscriber.pageId, input.pageId),
+ eq(page.workspaceId, ctx.workspace.id),
+ ),
+ )
+ .get();
+
+ if (!beforeJoined) {
+ throw new NotFoundError("page_subscriber", input.subscriberId);
+ }
+
+ const existing = beforeJoined.subscriber;
+
+ if (existing.source !== "vendor") {
+ throw new ValidationError(
+ "Self-signup subscribers manage their own subscription; use the unsubscribe action instead.",
+ );
+ }
+
+ if (existing.channelType === "email") {
+ if (input.webhookUrl !== undefined || input.headers !== undefined) {
+ throw new ValidationError(
+ "Email subscribers do not have webhook fields to edit.",
+ );
+ }
+ }
+
+ const updateFields: Record<string, unknown> = { updatedAt: new Date() };
+ if (input.name !== undefined) updateFields.name = input.name;
+
+ if (existing.channelType === "webhook") {
+ if (
+ input.webhookUrl !== undefined &&
+ input.webhookUrl !== existing.webhookUrl
+ ) {
+ const duplicate = await tx.query.pageSubscriber.findFirst({
+ where: and(
+ eq(pageSubscriber.pageId, input.pageId),
+ sql`LOWER(${pageSubscriber.webhookUrl}) = ${input.webhookUrl.toLowerCase()}`,
+ eq(pageSubscriber.channelType, "webhook"),
+ isNull(pageSubscriber.unsubscribedAt),
+ ne(pageSubscriber.id, input.subscriberId),
+ ),
+ });
+ if (duplicate) {
+ throw new ConflictError(
+ "A subscriber with this webhook URL already exists for this page.",
+ );
+ }
+ updateFields.webhookUrl = input.webhookUrl;
+ }
+ if (input.headers !== undefined) {
+ // Empty array is truthy in JS, so check `length > 0` — otherwise
+ // we'd persist `{"headers":[]}` instead of nulling the column.
+ updateFields.channelConfig =
+ input.headers.length > 0
+ ? JSON.stringify({ headers: input.headers })
+ : null;
+ }
+ }
+
+ if (input.componentIds !== undefined && input.componentIds.length > 0) {
+ const valid = await tx
+ .select({ id: pageComponent.id })
+ .from(pageComponent)
+ .where(
+ and(
+ eq(pageComponent.pageId, input.pageId),
+ inArray(pageComponent.id, input.componentIds),
+ ),
+ )
+ .all();
+ if (valid.length !== input.componentIds.length) {
+ throw new ValidationError("Some components do not belong to this page");
+ }
+ }
+
+ const updated = await tx
+ .update(pageSubscriber)
+ .set(updateFields)
+ .where(eq(pageSubscriber.id, input.subscriberId))
+ .returning()
+ .get();
+
+ if (input.componentIds !== undefined) {
+ await tx
+ .delete(pageSubscriberToPageComponent)
+ .where(
+ eq(
+ pageSubscriberToPageComponent.pageSubscriberId,
+ input.subscriberId,
+ ),
+ )
+ .run();
+
+ if (input.componentIds.length > 0) {
+ await tx
+ .insert(pageSubscriberToPageComponent)
+ .values(
+ input.componentIds.map((compId) => ({
+ pageSubscriberId: input.subscriberId,
+ pageComponentId: compId,
+ })),
+ )
+ .run();
+ }
+ }
+
+ // libSQL HTTP can omit RETURNING rows from a no-op UPDATE; ownership
+ // was already proven via `beforeJoined`, so fall back to the pre-image.
+ const before = selectPageSubscriberSchema.parse(existing);
+ const after = selectPageSubscriberSchema.parse(updated ?? existing);
+
+ // `token` is the self-manage / unsubscribe capability; never audit it.
+ const { token: _beforeToken, ...beforeSnap } = before;
+ const { token: _afterToken, ...afterSnap } = after;
+
+ await emitAudit(tx, ctx, {
+ action: "page_subscriber.update",
+ entityType: "page_subscriber",
+ entityId: input.subscriberId,
+ before: beforeSnap,
+ after: afterSnap,
+ });
+ });
+}
diff --git a/packages/services/src/page-subscriber/upsert.ts b/packages/services/src/page-subscriber/upsert.ts
new file mode 100644
index 000000000..1d291d9c9
--- /dev/null
+++ b/packages/services/src/page-subscriber/upsert.ts
@@ -0,0 +1,239 @@
+import { and, eq, inArray, isNull } from "@openstatus/db";
+import {
+ page,
+ pageComponent,
+ pageSubscriber,
+ pageSubscriberToPageComponent,
+ selectPageSubscriberSchema,
+} from "@openstatus/db/src/schema";
+
+import { emitAudit } from "../audit";
+import {
+ type DB,
+ type ServiceContext,
+ getReadDb,
+ withTransaction,
+} from "../context";
+import { NotFoundError, ValidationError } from "../errors";
+import { assertSubscribersAllowed, parseWorkspaceForContext } from "./internal";
+import { UpsertSelfSignupSubscriberInput } from "./schemas";
+
+const VERIFICATION_EXPIRY_MS = 7 * 24 * 60 * 60 * 1000;
+
+export type UpsertSelfSignupResult = {
+ id: number;
+ pageId: number;
+ pageName: string;
+ pageSlug: string;
+ customDomain: string | null;
+ channelType: "email" | "webhook";
+ email: string;
+ token: string | null;
+ acceptedAt: Date | null;
+ unsubscribedAt?: Date | null;
+ componentIds: number[];
+};
+
+/**
+ * Self-signup entry point: a visitor on a public status page subscribes
+ * by email. There is no authenticated actor and no `ctx.workspace` at
+ * the call site — both are resolved from the page row inside this
+ * function so audit emission still happens with a `subscriber` actor
+ * attributable to the resulting `pageSubscriber.id`.
+ *
+ * Audit emission rules:
+ * - new row inserted → `page_subscriber.create`
+ * - pending row, scope merged → `page_subscriber.update` with
+ * `metadata: { componentIds: merged }`
+ * (otherwise diffTopLevel would skip a
+ * components-only change)
+ * - already verified row → no audit (no-op return)
+ */
+export async function upsertSelfSignupSubscriber(args: {
+ input: UpsertSelfSignupSubscriberInput;
+ db?: DB;
+}): Promise<UpsertSelfSignupResult> {
+ const input = UpsertSelfSignupSubscriberInput.parse(args.input);
+ const componentIds = input.componentIds ?? [];
+
+ const readDb = getReadDb({ db: args.db } as ServiceContext);
+ const pageData = await readDb.query.page.findFirst({
+ where: eq(page.id, input.pageId),
+ with: { workspace: true },
+ });
+ if (!pageData) {
+ throw new NotFoundError("page", input.pageId);
+ }
+ const workspace = parseWorkspaceForContext(pageData.workspace);
+ // Plan-gate before any DB writes — same upsell semantics as the
+ // dashboard `createPageSubscriber` path. Free-plan pages don't
+ // accept self-signups; the row never exists.
+ assertSubscribersAllowed(workspace);
+
+ const emailLower = input.email.toLowerCase();
+
+ return withTransaction({ db: args.db } as ServiceContext, async (tx) => {
+ if (componentIds.length > 0) {
+ const valid = await tx
+ .select({ id: pageComponent.id })
+ .from(pageComponent)
+ .where(
+ and(
+ eq(pageComponent.pageId, input.pageId),
+ inArray(pageComponent.id, componentIds),
+ ),
+ )
+ .all();
+ if (valid.length !== componentIds.length) {
+ throw new ValidationError("Some components do not belong to this page");
+ }
+ }
+
+ const existing = await tx.query.pageSubscriber.findFirst({
+ where: and(
+ eq(pageSubscriber.email, emailLower),
+ eq(pageSubscriber.pageId, input.pageId),
+ eq(pageSubscriber.channelType, "email"),
+ isNull(pageSubscriber.unsubscribedAt),
+ ),
+ with: { components: true },
+ });
+
+ if (existing?.acceptedAt) {
+ // Already verified — return as-is. Caller decides whether to surface
+ // "already subscribed" to the visitor; no durable change here, no audit.
+ return {
+ id: existing.id,
+ pageId: existing.pageId,
+ pageName: pageData.title,
+ pageSlug: pageData.slug,
+ customDomain: pageData.customDomain,
+ channelType: existing.channelType,
+ email: existing.email ?? emailLower,
+ token: existing.token,
+ acceptedAt: existing.acceptedAt,
+ componentIds: existing.components.map((c) => c.pageComponentId),
+ };
+ }
+
+ if (existing) {
+ // Pending row — merge components, refresh expiry.
+ const currentIds = existing.components.map((c) => c.pageComponentId);
+ const mergedIds = [...new Set([...currentIds, ...componentIds])];
+ const newIds = mergedIds.filter((id) => !currentIds.includes(id));
+
+ if (newIds.length > 0) {
+ await tx
+ .insert(pageSubscriberToPageComponent)
+ .values(
+ newIds.map((compId) => ({
+ pageSubscriberId: existing.id,
+ pageComponentId: compId,
+ })),
+ )
+ .onConflictDoNothing()
+ .run();
+ }
+
+ const newExpiresAt = new Date(Date.now() + VERIFICATION_EXPIRY_MS);
+ const beforeRow = selectPageSubscriberSchema.parse(existing);
+ const updatedRow = await tx
+ .update(pageSubscriber)
+ .set({ expiresAt: newExpiresAt, updatedAt: new Date() })
+ .where(eq(pageSubscriber.id, existing.id))
+ .returning()
+ .get();
+ const afterRow = selectPageSubscriberSchema.parse(updatedRow ?? existing);
+
+ const auditCtx: ServiceContext = {
+ workspace,
+ actor: { type: "subscriber", subscriberId: existing.id },
+ db: tx,
+ };
+
+ // Strip token (capability for self-manage / unsubscribe URLs).
+ // Component scope changes don't show in the row diff — surface
+ // them via metadata so the audit row carries actual signal.
+ const { token: _bt, ...beforeSnap } = beforeRow;
+ const { token: _at, ...afterSnap } = afterRow;
+ await emitAudit(tx, auditCtx, {
+ action: "page_subscriber.update",
+ entityType: "page_subscriber",
+ entityId: existing.id,
+ before: beforeSnap,
+ after: afterSnap,
+ ...(newIds.length > 0 ? { metadata: { componentIds: mergedIds } } : {}),
+ });
+
+ return {
+ id: existing.id,
+ pageId: existing.pageId,
+ pageName: pageData.title,
+ pageSlug: pageData.slug,
+ customDomain: pageData.customDomain,
+ channelType: existing.channelType,
+ email: existing.email ?? emailLower,
+ token: existing.token,
+ acceptedAt: null,
+ componentIds: mergedIds,
+ };
+ }
+
+ // No existing row — create.
+ const token = crypto.randomUUID();
+ const expiresAt = new Date(Date.now() + VERIFICATION_EXPIRY_MS);
+ const inserted = await tx
+ .insert(pageSubscriber)
+ .values({
+ channelType: "email",
+ email: emailLower,
+ webhookUrl: null,
+ pageId: input.pageId,
+ source: "self_signup",
+ token,
+ expiresAt,
+ })
+ .returning()
+ .get();
+
+ if (componentIds.length > 0) {
+ await tx
+ .insert(pageSubscriberToPageComponent)
+ .values(
+ componentIds.map((compId) => ({
+ pageSubscriberId: inserted.id,
+ pageComponentId: compId,
+ })),
+ )
+ .run();
+ }
+
+ const auditCtx: ServiceContext = {
+ workspace,
+ actor: { type: "subscriber", subscriberId: inserted.id },
+ db: tx,
+ };
+ const { token: _t, ...after } = selectPageSubscriberSchema.parse(inserted);
+ await emitAudit(tx, auditCtx, {
+ action: "page_subscriber.create",
+ entityType: "page_subscriber",
+ entityId: inserted.id,
+ after,
+ ...(componentIds.length > 0 ? { metadata: { componentIds } } : {}),
+ });
+
+ return {
+ id: inserted.id,
+ pageId: inserted.pageId,
+ pageName: pageData.title,
+ pageSlug: pageData.slug,
+ customDomain: pageData.customDomain,
+ channelType: "email" as const,
+ email: inserted.email ?? emailLower,
+ token: inserted.token,
+ acceptedAt: inserted.acceptedAt ?? null,
+ unsubscribedAt: inserted.unsubscribedAt ?? null,
+ componentIds,
+ };
+ });
+}
diff --git a/packages/services/src/page-subscriber/verify.ts b/packages/services/src/page-subscriber/verify.ts
new file mode 100644
index 000000000..7fa885b7f
--- /dev/null
+++ b/packages/services/src/page-subscriber/verify.ts
@@ -0,0 +1,109 @@
+import { eq } from "@openstatus/db";
+import {
+ pageSubscriber,
+ selectPageSubscriberSchema,
+} from "@openstatus/db/src/schema";
+
+import { emitAudit } from "../audit";
+import { type DB, type ServiceContext, withTransaction } from "../context";
+import { ValidationError } from "../errors";
+import { resolveSubscriberByToken } from "./internal";
+import { VerifySelfSignupSubscriberInput } from "./schemas";
+
+export type VerifyResult = {
+ id: number;
+ pageId: number;
+ pageName: string;
+ pageSlug: string;
+ customDomain: string | null;
+ channelType: "email" | "webhook";
+ email: string | null;
+ webhookUrl?: string | null;
+ token: string | null;
+ acceptedAt: Date | null;
+ componentIds: number[];
+} | null;
+
+/**
+ * Verify a self-signup subscription by its emailed token. Returns `null`
+ * when the token doesn't resolve (or the optional `domain` doesn't
+ * match) — callers map that to `NOT_FOUND`. Already-accepted rows
+ * short-circuit without re-emitting; first-time acceptance flips
+ * `acceptedAt` and writes one `page_subscriber.update` audit row with
+ * actor `subscriber:{id}`.
+ */
+export async function verifySelfSignupSubscriber(args: {
+ input: VerifySelfSignupSubscriberInput;
+ db?: DB;
+}): Promise<VerifyResult> {
+ const input = VerifySelfSignupSubscriberInput.parse(args.input);
+
+ const resolved = await resolveSubscriberByToken({
+ db: args.db,
+ token: input.token,
+ domain: input.domain,
+ });
+ if (!resolved) return null;
+ const { row, pageData, components } = resolved;
+
+ // Already accepted — surface the row without writing.
+ if (row.acceptedAt) {
+ return {
+ id: row.id,
+ pageId: row.pageId,
+ pageName: pageData.title,
+ pageSlug: pageData.slug,
+ customDomain: pageData.customDomain,
+ channelType: row.channelType,
+ email: row.email,
+ webhookUrl: row.webhookUrl,
+ token: row.token,
+ acceptedAt: row.acceptedAt,
+ componentIds: components,
+ };
+ }
+
+ if (row.expiresAt && row.expiresAt < new Date()) {
+ throw new ValidationError("Verification token expired");
+ }
+
+ return withTransaction({ db: args.db } as ServiceContext, async (tx) => {
+ const before = selectPageSubscriberSchema.parse(row);
+ const updated = await tx
+ .update(pageSubscriber)
+ .set({ acceptedAt: new Date(), updatedAt: new Date() })
+ .where(eq(pageSubscriber.id, row.id))
+ .returning()
+ .get();
+ const after = selectPageSubscriberSchema.parse(updated ?? row);
+
+ const auditCtx: ServiceContext = {
+ workspace: pageData.workspace,
+ actor: { type: "subscriber", subscriberId: row.id },
+ db: tx,
+ };
+ const { token: _bt, ...beforeSnap } = before;
+ const { token: _at, ...afterSnap } = after;
+ await emitAudit(tx, auditCtx, {
+ action: "page_subscriber.update",
+ entityType: "page_subscriber",
+ entityId: row.id,
+ before: beforeSnap,
+ after: afterSnap,
+ });
+
+ return {
+ id: row.id,
+ pageId: row.pageId,
+ pageName: pageData.title,
+ pageSlug: pageData.slug,
+ customDomain: pageData.customDomain,
+ channelType: updated?.channelType ?? row.channelType,
+ email: updated?.email ?? row.email,
+ webhookUrl: updated?.webhookUrl ?? row.webhookUrl,
+ token: updated?.token ?? row.token,
+ acceptedAt: updated?.acceptedAt ?? new Date(),
+ componentIds: components,
+ };
+ });
+}
diff --git a/packages/services/src/page/__tests__/page.test.ts b/packages/services/src/page/__tests__/page.test.ts
index 5170b46b9..85d849cda 100644
--- a/packages/services/src/page/__tests__/page.test.ts
+++ b/packages/services/src/page/__tests__/page.test.ts
@@ -1,13 +1,6 @@
-import {
- afterAll,
- beforeAll,
- beforeEach,
- describe,
- expect,
- test,
-} from "bun:test";
-import { db, eq, inArray } from "@openstatus/db";
-import { monitor, page, pageComponent } from "@openstatus/db/src/schema";
+import { afterAll, beforeAll, describe, expect, test } from "bun:test";
+import { db, eq } from "@openstatus/db";
+import { monitor, pageComponent } from "@openstatus/db/src/schema";
import {
SEEDED_WORKSPACE_FREE_ID,
@@ -15,10 +8,10 @@ import {
} from "../../../test/fixtures";
import {
cleanQuotaGatedTables,
- clearAuditLog,
expectAuditRow,
loadSeededWorkspace,
makeUserCtx,
+ withTestTransaction,
} from "../../../test/helpers";
import type { ServiceContext } from "../../context";
import {
@@ -29,7 +22,7 @@ import {
} from "../../errors";
import { createPage, newPage } from "../create";
import { deletePage } from "../delete";
-import { getPage, getSlugAvailable, listPages } from "../list";
+import { getPage, getPageBySlug, getSlugAvailable, listPages } from "../list";
import { updatePageGeneral, updatePageLocales } from "../update";
const TEST_PREFIX = "svc-page-test";
@@ -37,7 +30,6 @@ const TEST_PREFIX = "svc-page-test";
let teamCtx: ServiceContext;
let freeCtx: ServiceContext;
let teamMonitorId: number;
-const createdPageIds: number[] = [];
beforeAll(async () => {
const team = await loadSeededWorkspace(SEEDED_WORKSPACE_TEAM_ID);
@@ -68,262 +60,299 @@ beforeAll(async () => {
});
afterAll(async () => {
- if (createdPageIds.length > 0) {
- await db
- .delete(pageComponent)
- .where(inArray(pageComponent.pageId, createdPageIds))
- .catch(() => undefined);
- await db
- .delete(page)
- .where(inArray(page.id, createdPageIds))
- .catch(() => undefined);
- }
await db
.delete(monitor)
.where(eq(monitor.id, teamMonitorId))
.catch(() => undefined);
});
-beforeEach(async () => {
- await clearAuditLog(teamCtx.workspace.id);
- await clearAuditLog(freeCtx.workspace.id);
-});
-
-function track(id: number) {
- createdPageIds.push(id);
- return id;
-}
-
let slugCounter = 0;
const uniqueSlug = (tag: string) => `${TEST_PREFIX}-${tag}-${++slugCounter}`;
describe("newPage", () => {
test("happy path + audit", async () => {
- const slug = uniqueSlug("new");
- const row = await newPage({
- ctx: teamCtx,
- input: { title: "Test", slug },
- });
- track(row.id);
- expect(row.slug).toBe(slug);
- await expectAuditRow({
- workspaceId: teamCtx.workspace.id,
- action: "page.create",
- entityType: "page",
- entityId: row.id,
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ const slug = uniqueSlug("new");
+ const row = await newPage({
+ ctx,
+ input: { title: "Test", slug },
+ });
+ expect(row.slug).toBe(slug);
+ await expectAuditRow({
+ workspaceId: teamCtx.workspace.id,
+ action: "page.create",
+ entityType: "page",
+ entityId: row.id,
+ db: tx,
+ });
});
});
test("rejects reserved subdomain", async () => {
- await expect(
- newPage({
- ctx: teamCtx,
- input: { title: "Test", slug: "api" },
- }),
- ).rejects.toBeInstanceOf(ConflictError);
+ await withTestTransaction(async (tx) => {
+ await expect(
+ newPage({
+ ctx: { ...teamCtx, db: tx },
+ input: { title: "Test", slug: "api" },
+ }),
+ ).rejects.toBeInstanceOf(ConflictError);
+ });
});
test("rejects duplicate slug", async () => {
- const slug = uniqueSlug("dup");
- const first = await newPage({
- ctx: teamCtx,
- input: { title: "First", slug },
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ const slug = uniqueSlug("dup");
+ await newPage({
+ ctx,
+ input: { title: "First", slug },
+ });
+ await expect(
+ newPage({ ctx, input: { title: "Second", slug } }),
+ ).rejects.toBeInstanceOf(ConflictError);
});
- track(first.id);
- await expect(
- newPage({ ctx: teamCtx, input: { title: "Second", slug } }),
- ).rejects.toBeInstanceOf(ConflictError);
});
});
describe("createPage (full form)", () => {
- // Re-clear the free workspace before each test in this block — the
- // `beforeAll` cleanup races against other test files (bun runs files
- // in parallel workers against the shared turso dev DB), and the
- // `rejects cross-workspace monitor` case needs free at 0 pages so
- // `assertStatusPageQuota` doesn't trip before the cross-workspace
- // monitor check runs.
- beforeEach(async () => {
- await cleanQuotaGatedTables(SEEDED_WORKSPACE_FREE_ID);
- });
-
- // `CreatePageInput` re-exports the drizzle `insertPageSchema`, which
- // requires `workspaceId` at parse time. The service strips the input
- // value and uses `ctx.workspace.id` when persisting (so the input
- // value is informational only), but parse-time validation still
- // fails without the field. Passing `ctx.workspace.id` satisfies the
- // schema and matches what the router does.
test("attaches monitors as pageComponents", async () => {
- const slug = uniqueSlug("full");
- const row = await createPage({
- ctx: teamCtx,
- input: {
- title: "Full Create",
- slug,
- description: "desc",
- customDomain: "",
- workspaceId: SEEDED_WORKSPACE_TEAM_ID,
- monitors: [{ monitorId: teamMonitorId }],
- },
- });
- track(row.id);
- const components = await db
- .select()
- .from(pageComponent)
- .where(eq(pageComponent.pageId, row.id))
- .all();
- expect(components.map((c) => c.monitorId)).toEqual([teamMonitorId]);
- });
-
- test("rejects cross-workspace monitor", async () => {
- const slug = uniqueSlug("cross-ws");
- await expect(
- createPage({
- ctx: freeCtx,
+ await withTestTransaction(async (tx) => {
+ const slug = uniqueSlug("full");
+ const row = await createPage({
+ ctx: { ...teamCtx, db: tx },
input: {
- title: "Cross",
+ title: "Full Create",
slug,
- description: "",
+ description: "desc",
customDomain: "",
- workspaceId: SEEDED_WORKSPACE_FREE_ID,
+ workspaceId: SEEDED_WORKSPACE_TEAM_ID,
monitors: [{ monitorId: teamMonitorId }],
},
- }),
- ).rejects.toBeInstanceOf(ForbiddenError);
+ });
+ const components = await tx
+ .select()
+ .from(pageComponent)
+ .where(eq(pageComponent.pageId, row.id))
+ .all();
+ expect(components.map((c) => c.monitorId)).toEqual([teamMonitorId]);
+ });
+ });
+
+ test("rejects cross-workspace monitor", async () => {
+ await withTestTransaction(async (tx) => {
+ const slug = uniqueSlug("cross-ws");
+ await expect(
+ createPage({
+ ctx: { ...freeCtx, db: tx },
+ input: {
+ title: "Cross",
+ slug,
+ description: "",
+ customDomain: "",
+ workspaceId: SEEDED_WORKSPACE_FREE_ID,
+ monitors: [{ monitorId: teamMonitorId }],
+ },
+ }),
+ ).rejects.toBeInstanceOf(ForbiddenError);
+ });
});
});
describe("updatePageGeneral", () => {
test("updates title + slug; rejects duplicate slug", async () => {
- const a = await newPage({
- ctx: teamCtx,
- input: { title: "A", slug: uniqueSlug("a") },
- });
- const b = await newPage({
- ctx: teamCtx,
- input: { title: "B", slug: uniqueSlug("b") },
- });
- track(a.id);
- track(b.id);
-
- // Rename A to a new slug — fine.
- const newSlug = uniqueSlug("a-renamed");
- await updatePageGeneral({
- ctx: teamCtx,
- input: { id: a.id, title: "A Renamed", slug: newSlug },
- });
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ const a = await newPage({
+ ctx,
+ input: { title: "A", slug: uniqueSlug("a") },
+ });
+ const b = await newPage({
+ ctx,
+ input: { title: "B", slug: uniqueSlug("b") },
+ });
- // Rename A to B's slug — conflict.
- await expect(
- updatePageGeneral({
- ctx: teamCtx,
- input: { id: a.id, title: "A", slug: b.slug },
- }),
- ).rejects.toBeInstanceOf(ConflictError);
+ // Rename A to a new slug — fine.
+ const newSlug = uniqueSlug("a-renamed");
+ await updatePageGeneral({
+ ctx,
+ input: { id: a.id, title: "A Renamed", slug: newSlug },
+ });
+
+ // Rename A to B's slug — conflict.
+ await expect(
+ updatePageGeneral({
+ ctx,
+ input: { id: a.id, title: "A", slug: b.slug },
+ }),
+ ).rejects.toBeInstanceOf(ConflictError);
+ });
});
test("cross-workspace → NotFoundError", async () => {
- const p = await newPage({
- ctx: teamCtx,
- input: { title: "Team", slug: uniqueSlug("ws-iso") },
+ await withTestTransaction(async (tx) => {
+ const p = await newPage({
+ ctx: { ...teamCtx, db: tx },
+ input: { title: "Team", slug: uniqueSlug("ws-iso") },
+ });
+ await expect(
+ updatePageGeneral({
+ ctx: { ...freeCtx, db: tx },
+ input: { id: p.id, title: "Hacked", slug: uniqueSlug("hack") },
+ }),
+ ).rejects.toBeInstanceOf(NotFoundError);
});
- track(p.id);
- await expect(
- updatePageGeneral({
- ctx: freeCtx,
- input: { id: p.id, title: "Hacked", slug: uniqueSlug("hack") },
- }),
- ).rejects.toBeInstanceOf(NotFoundError);
});
});
describe("updatePageLocales", () => {
- // Same reason as `createPage (full form)` — the i18n test creates a
- // page in the free workspace as setup, so we need to guarantee free
- // is at 0 pages right before it runs, not just at suite start.
- beforeEach(async () => {
- await cleanQuotaGatedTables(SEEDED_WORKSPACE_FREE_ID);
- });
-
test("rejects when plan lacks i18n", async () => {
- // free plan has i18n: false
- const p = await newPage({
- ctx: freeCtx,
- input: { title: "Free", slug: uniqueSlug("free") },
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...freeCtx, db: tx };
+ // free plan has i18n: false
+ const p = await newPage({
+ ctx,
+ input: { title: "Free", slug: uniqueSlug("free") },
+ });
+ await expect(
+ updatePageLocales({
+ ctx,
+ input: { id: p.id, defaultLocale: "en", locales: ["en"] },
+ }),
+ ).rejects.toBeInstanceOf(LimitExceededError);
});
- track(p.id);
- await expect(
- updatePageLocales({
- ctx: freeCtx,
- input: { id: p.id, defaultLocale: "en", locales: ["en"] },
- }),
- ).rejects.toBeInstanceOf(LimitExceededError);
});
});
describe("list / get / getSlugAvailable", () => {
test("list respects workspace isolation", async () => {
- const p = await newPage({
- ctx: teamCtx,
- input: { title: "List Test", slug: uniqueSlug("list") },
- });
- track(p.id);
+ await withTestTransaction(async (tx) => {
+ const teamCtxTx = { ...teamCtx, db: tx };
+ const freeCtxTx = { ...freeCtx, db: tx };
+ const p = await newPage({
+ ctx: teamCtxTx,
+ input: { title: "List Test", slug: uniqueSlug("list") },
+ });
- const teamItems = await listPages({
- ctx: teamCtx,
- input: { order: "desc" },
- });
- expect(teamItems.find((x) => x.id === p.id)).toBeDefined();
+ const teamItems = await listPages({
+ ctx: teamCtxTx,
+ input: { order: "desc" },
+ });
+ expect(teamItems.find((x) => x.id === p.id)).toBeDefined();
- const freeItems = await listPages({
- ctx: freeCtx,
- input: { order: "desc" },
+ const freeItems = await listPages({
+ ctx: freeCtxTx,
+ input: { order: "desc" },
+ });
+ expect(freeItems.find((x) => x.id === p.id)).toBeUndefined();
});
- expect(freeItems.find((x) => x.id === p.id)).toBeUndefined();
});
test("get cross-workspace → NotFoundError", async () => {
- const p = await newPage({
- ctx: teamCtx,
- input: { title: "Get", slug: uniqueSlug("get") },
+ await withTestTransaction(async (tx) => {
+ const p = await newPage({
+ ctx: { ...teamCtx, db: tx },
+ input: { title: "Get", slug: uniqueSlug("get") },
+ });
+ await expect(
+ getPage({ ctx: { ...freeCtx, db: tx }, input: { id: p.id } }),
+ ).rejects.toBeInstanceOf(NotFoundError);
});
- track(p.id);
- await expect(
- getPage({ ctx: freeCtx, input: { id: p.id } }),
- ).rejects.toBeInstanceOf(NotFoundError);
});
test("getSlugAvailable handles reserved + taken", async () => {
- const p = await newPage({
- ctx: teamCtx,
- input: { title: "Slug", slug: uniqueSlug("slug") },
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ const p = await newPage({
+ ctx,
+ input: { title: "Slug", slug: uniqueSlug("slug") },
+ });
+
+ expect(await getSlugAvailable({ ctx, input: { slug: p.slug } })).toBe(
+ false,
+ );
+ expect(await getSlugAvailable({ ctx, input: { slug: "api" } })).toBe(
+ false,
+ );
+ expect(
+ await getSlugAvailable({
+ ctx,
+ input: { slug: uniqueSlug("free-slug") },
+ }),
+ ).toBe(true);
+ });
+ });
+});
+
+describe("getPageBySlug", () => {
+ test("returns the row when slug exists", async () => {
+ await withTestTransaction(async (tx) => {
+ const p = await newPage({
+ ctx: { ...teamCtx, db: tx },
+ input: { title: "BySlug", slug: uniqueSlug("by-slug") },
+ });
+
+ const row = await getPageBySlug({ input: { slug: p.slug } }, { db: tx });
+ expect(row?.id).toBe(p.id);
+ expect(row?.slug).toBe(p.slug);
+ });
+ });
+
+ test("normalizes slug casing", async () => {
+ await withTestTransaction(async (tx) => {
+ const slug = uniqueSlug("case");
+ const p = await newPage({
+ ctx: { ...teamCtx, db: tx },
+ input: { title: "Case", slug },
+ });
+
+ const upper = await getPageBySlug(
+ { input: { slug: slug.toUpperCase() } },
+ { db: tx },
+ );
+ expect(upper?.id).toBe(p.id);
+ });
+ });
+
+ test("returns undefined when slug is missing", async () => {
+ await withTestTransaction(async (tx) => {
+ const row = await getPageBySlug(
+ { input: { slug: `${TEST_PREFIX}-missing-${Date.now()}` } },
+ { db: tx },
+ );
+ expect(row).toBeUndefined();
+ });
+ });
+
+ test("ignores workspace scope (cross-workspace lookup)", async () => {
+ await withTestTransaction(async (tx) => {
+ // Page lives in the team workspace; querying without any ctx still
+ // resolves it — this is the contract that lets the public status-page
+ // render path resolve a slug for unauthenticated visitors.
+ const p = await newPage({
+ ctx: { ...teamCtx, db: tx },
+ input: { title: "Cross", slug: uniqueSlug("cross") },
+ });
+
+ const row = await getPageBySlug({ input: { slug: p.slug } }, { db: tx });
+ expect(row?.workspaceId).toBe(teamCtx.workspace.id);
+ // (No `ctx` passed → confirms the helper does not rely on
+ // workspace scoping; `db: tx` only routes the read through our
+ // wrapping test tx so it sees the row created above.)
});
- track(p.id);
-
- expect(
- await getSlugAvailable({ ctx: teamCtx, input: { slug: p.slug } }),
- ).toBe(false);
- expect(
- await getSlugAvailable({ ctx: teamCtx, input: { slug: "api" } }),
- ).toBe(false);
- expect(
- await getSlugAvailable({
- ctx: teamCtx,
- input: { slug: uniqueSlug("free-slug") },
- }),
- ).toBe(true);
});
});
describe("deletePage", () => {
test("cross-workspace → NotFoundError", async () => {
- const p = await newPage({
- ctx: teamCtx,
- input: { title: "Delete", slug: uniqueSlug("del") },
+ await withTestTransaction(async (tx) => {
+ const p = await newPage({
+ ctx: { ...teamCtx, db: tx },
+ input: { title: "Delete", slug: uniqueSlug("del") },
+ });
+ await expect(
+ deletePage({ ctx: { ...freeCtx, db: tx }, input: { id: p.id } }),
+ ).rejects.toBeInstanceOf(NotFoundError);
});
- track(p.id);
- await expect(
- deletePage({ ctx: freeCtx, input: { id: p.id } }),
- ).rejects.toBeInstanceOf(NotFoundError);
});
});
diff --git a/packages/services/src/page/index.ts b/packages/services/src/page/index.ts
index 3adbe75b6..89600cf6d 100644
--- a/packages/services/src/page/index.ts
+++ b/packages/services/src/page/index.ts
@@ -2,6 +2,7 @@ export { createPage, newPage } from "./create";
export { deletePage } from "./delete";
export {
getPage,
+ getPageBySlug,
getPageCustomDomain,
getSlugAvailable,
listPages,
diff --git a/packages/services/src/page/list.ts b/packages/services/src/page/list.ts
index 42e7c729f..a14de2771 100644
--- a/packages/services/src/page/list.ts
+++ b/packages/services/src/page/list.ts
@@ -21,7 +21,7 @@ import {
} from "@openstatus/db/src/schema";
import { subdomainSafeList } from "@openstatus/db/src/schema/pages/constants";
-import type { ServiceContext } from "../context";
+import { type DB, type ServiceContext, getReadDb } from "../context";
import { NotFoundError } from "../errors";
import type { Maintenance, Page, PageComponent, StatusReport } from "../types";
import { getPageInWorkspace } from "./internal";
@@ -45,7 +45,7 @@ export async function listPages(args: {
}): Promise<PageListItem[]> {
const { ctx } = args;
const input = ListPagesInput.parse(args.input);
- const db = ctx.db ?? defaultDb;
+ const db = getReadDb(ctx);
const pageRows = await db
.select()
@@ -89,7 +89,7 @@ export async function getPage(args: {
}): Promise<PageWithRelations> {
const { ctx } = args;
const input = GetPageInput.parse(args.input);
- const db = ctx.db ?? defaultDb;
+ const db = getReadDb(ctx);
const record = await getPageInWorkspace({
tx: db,
@@ -159,7 +159,7 @@ export async function getPageCustomDomain(args: {
}): Promise<string> {
const { ctx } = args;
const input = GetPageInput.parse(args.input);
- const db = ctx.db ?? defaultDb;
+ const db = getReadDb(ctx);
const row = await db
.select({ customDomain: page.customDomain })
@@ -171,6 +171,23 @@ export async function getPageCustomDomain(args: {
return row.customDomain;
}
+/**
+ * Cross-workspace lookup of a page by slug. Returns the raw row (not parsed
+ * via `selectPageSchema`) because callers in the public status-page render
+ * path expect the DB shape (`authEmailDomains` / `allowedIpRanges` as
+ * comma-joined strings rather than arrays). Workspace scoping is the
+ * caller's responsibility — slugs are globally unique, so the lookup
+ * intentionally ignores `ctx.workspace`.
+ */
+export async function getPageBySlug(
+ args: { input: { slug: string } },
+ opts: { db?: DB } = {},
+): Promise<typeof page.$inferSelect | undefined> {
+ const slug = args.input.slug.toLowerCase();
+ const db = opts.db ?? defaultDb;
+ return db.select().from(page).where(eq(page.slug, slug)).get();
+}
+
/** Returns `true` when the slug is free (not reserved, not taken). */
export async function getSlugAvailable(args: {
ctx: ServiceContext;
@@ -178,7 +195,7 @@ export async function getSlugAvailable(args: {
}): Promise<boolean> {
const { ctx } = args;
const input = GetSlugAvailableInput.parse(args.input);
- const db = ctx.db ?? defaultDb;
+ const db = getReadDb(ctx);
if (subdomainSafeList.includes(input.slug)) return false;
const rows = await db
diff --git a/packages/services/src/private-location/create.ts b/packages/services/src/private-location/create.ts
new file mode 100644
index 000000000..b748933fb
--- /dev/null
+++ b/packages/services/src/private-location/create.ts
@@ -0,0 +1,70 @@
+import {
+ privateLocation,
+ privateLocationToMonitors,
+ selectPrivateLocationSchema,
+} from "@openstatus/db/src/schema";
+
+import { emitAudit } from "../audit";
+import { type ServiceContext, withTransaction } from "../context";
+import type { PrivateLocation } from "../types";
+import { assertMonitorsInWorkspace } from "./internal";
+import { CreatePrivateLocationInput } from "./schemas";
+
+/**
+ * Create a private location and attach it to the given monitors.
+ *
+ * `token` is audited as part of the `after` snapshot because private-
+ * location tokens are workspace-scoped agent credentials visible in the
+ * dashboard UI — treating them as "secret" in the audit log but plain-text
+ * in the settings screen would be inconsistent. If that ever changes,
+ * strip it here the way invitation tokens are stripped.
+ */
+export async function createPrivateLocation(args: {
+ ctx: ServiceContext;
+ input: CreatePrivateLocationInput;
+}): Promise<PrivateLocation> {
+ const { ctx } = args;
+ const input = CreatePrivateLocationInput.parse(args.input);
+
+ // The pivot table has no UNIQUE (private_location_id, monitor_id)
+ // constraint, so duplicate input ids would silently produce duplicate
+ // FK rows. Dedupe before insert; the audit snapshot follows suit.
+ const monitorIds = Array.from(new Set(input.monitors));
+
+ return withTransaction(ctx, async (tx) => {
+ await assertMonitorsInWorkspace({
+ tx,
+ workspaceId: ctx.workspace.id,
+ monitorIds,
+ });
+
+ const row = await tx
+ .insert(privateLocation)
+ .values({
+ name: input.name,
+ token: input.token,
+ workspaceId: ctx.workspace.id,
+ })
+ .returning()
+ .get();
+
+ if (monitorIds.length > 0) {
+ await tx.insert(privateLocationToMonitors).values(
+ monitorIds.map((monitorId) => ({
+ privateLocationId: row.id,
+ monitorId,
+ })),
+ );
+ }
+
+ const parsed = selectPrivateLocationSchema.parse(row);
+ await emitAudit(tx, ctx, {
+ action: "private_location.create",
+ entityType: "private_location",
+ entityId: parsed.id,
+ after: { ...parsed, monitorIds },
+ });
+
+ return parsed;
+ });
+}
diff --git a/packages/services/src/private-location/delete.ts b/packages/services/src/private-location/delete.ts
new file mode 100644
index 000000000..b04cb89c8
--- /dev/null
+++ b/packages/services/src/private-location/delete.ts
@@ -0,0 +1,47 @@
+import { and, eq } from "@openstatus/db";
+import {
+ privateLocation,
+ selectPrivateLocationSchema,
+} from "@openstatus/db/src/schema";
+
+import { emitAudit } from "../audit";
+import { type ServiceContext, withTransaction } from "../context";
+import { DeletePrivateLocationInput } from "./schemas";
+
+/**
+ * Delete a private location. Idempotent — missing rows (wrong id, wrong
+ * workspace, already deleted) succeed silently, matching the legacy
+ * router's transactional DELETE-without-SELECT behaviour.
+ *
+ * `private_location_to_monitor` has ON DELETE CASCADE, so the join rows
+ * drop automatically.
+ */
+export async function deletePrivateLocation(args: {
+ ctx: ServiceContext;
+ input: DeletePrivateLocationInput;
+}): Promise<void> {
+ const { ctx } = args;
+ const input = DeletePrivateLocationInput.parse(args.input);
+
+ await withTransaction(ctx, async (tx) => {
+ const [deleted] = await tx
+ .delete(privateLocation)
+ .where(
+ and(
+ eq(privateLocation.id, input.id),
+ eq(privateLocation.workspaceId, ctx.workspace.id),
+ ),
+ )
+ .returning();
+
+ if (!deleted) return;
+
+ const parsed = selectPrivateLocationSchema.parse(deleted);
+ await emitAudit(tx, ctx, {
+ action: "private_location.delete",
+ entityType: "private_location",
+ entityId: parsed.id,
+ before: parsed,
+ });
+ });
+}
diff --git a/packages/services/src/private-location/index.ts b/packages/services/src/private-location/index.ts
new file mode 100644
index 000000000..c74e86825
--- /dev/null
+++ b/packages/services/src/private-location/index.ts
@@ -0,0 +1,10 @@
+export { createPrivateLocation } from "./create";
+export { deletePrivateLocation } from "./delete";
+export { listPrivateLocations } from "./list";
+export { updatePrivateLocation } from "./update";
+export {
+ CreatePrivateLocationInput,
+ DeletePrivateLocationInput,
+ ListPrivateLocationsInput,
+ UpdatePrivateLocationInput,
+} from "./schemas";
diff --git a/packages/services/src/private-location/internal.ts b/packages/services/src/private-location/internal.ts
new file mode 100644
index 000000000..9407f5466
--- /dev/null
+++ b/packages/services/src/private-location/internal.ts
@@ -0,0 +1,32 @@
+import { and, eq, inArray } from "@openstatus/db";
+import { monitor } from "@openstatus/db/src/schema";
+
+import type { DB } from "../context";
+import { ForbiddenError } from "../errors";
+
+/**
+ * Ensure every id in `monitorIds` belongs to the given workspace. No-op
+ * when the list is empty. Throws `ForbiddenError` (not `NotFound`) to
+ * match the legacy router's `FORBIDDEN` response — surfacing "this id
+ * doesn't exist" vs. "this id isn't yours" would leak workspace state.
+ */
+export async function assertMonitorsInWorkspace(args: {
+ tx: DB;
+ workspaceId: number;
+ monitorIds: number[];
+}): Promise<void> {
+ const { tx, workspaceId, monitorIds } = args;
+ if (monitorIds.length === 0) return;
+
+ const uniqueIds = Array.from(new Set(monitorIds));
+
+ const valid = await tx.query.monitor.findMany({
+ where: and(
+ eq(monitor.workspaceId, workspaceId),
+ inArray(monitor.id, uniqueIds),
+ ),
+ });
+ if (valid.length !== uniqueIds.length) {
+ throw new ForbiddenError("Invalid monitor IDs.");
+ }
+}
diff --git a/packages/services/src/private-location/list.ts b/packages/services/src/private-location/list.ts
new file mode 100644
index 000000000..8a5b73a4a
--- /dev/null
+++ b/packages/services/src/private-location/list.ts
@@ -0,0 +1,39 @@
+import { eq } from "@openstatus/db";
+import { privateLocation } from "@openstatus/db/src/schema";
+
+import { type ServiceContext, getReadDb } from "../context";
+import { ListPrivateLocationsInput } from "./schemas";
+
+/**
+ * List private locations in the caller's workspace, each one flattened to
+ * include the monitors it's attached to (the relational join's `monitor`
+ * link lifted onto `monitors`, filtered to non-null).
+ *
+ * Return type is deliberately inferred from drizzle's relational query
+ * rather than annotated: pulling the shape out of `@openstatus/db`'s
+ * `selectMonitorSchema` narrows columns (e.g. `regions`) in ways the raw
+ * row doesn't, producing a false-positive type mismatch.
+ */
+export async function listPrivateLocations(args: {
+ ctx: ServiceContext;
+ input?: ListPrivateLocationsInput;
+}) {
+ ListPrivateLocationsInput.parse(args.input ?? {});
+ const db = getReadDb(args.ctx);
+
+ const rows = await db.query.privateLocation.findMany({
+ where: eq(privateLocation.workspaceId, args.ctx.workspace.id),
+ with: {
+ privateLocationToMonitors: {
+ with: { monitor: true },
+ },
+ },
+ });
+
+ return rows.map((row) => ({
+ ...row,
+ monitors: row.privateLocationToMonitors
+ .map((link) => link.monitor)
+ .filter((m) => m !== null),
+ }));
+}
diff --git a/packages/services/src/private-location/schemas.ts b/packages/services/src/private-location/schemas.ts
new file mode 100644
index 000000000..5b308103e
--- /dev/null
+++ b/packages/services/src/private-location/schemas.ts
@@ -0,0 +1,31 @@
+import { z } from "zod";
+
+export const ListPrivateLocationsInput = z.object({}).strict();
+export type ListPrivateLocationsInput = z.infer<
+ typeof ListPrivateLocationsInput
+>;
+
+const monitorIds = z.array(z.number().int().positive());
+
+export const CreatePrivateLocationInput = z.object({
+ name: z.string().min(1),
+ token: z.string().min(1),
+ monitors: monitorIds,
+});
+export type CreatePrivateLocationInput = z.infer<
+ typeof CreatePrivateLocationInput
+>;
+
+export const UpdatePrivateLocationInput = z.object({
+ id: z.number().int(),
+ name: z.string().min(1),
+ monitors: monitorIds,
+});
+export type UpdatePrivateLocationInput = z.infer<
+ typeof UpdatePrivateLocationInput
+>;
+
+export const DeletePrivateLocationInput = z.object({ id: z.number().int() });
+export type DeletePrivateLocationInput = z.infer<
+ typeof DeletePrivateLocationInput
+>;
diff --git a/packages/services/src/private-location/update.ts b/packages/services/src/private-location/update.ts
new file mode 100644
index 000000000..4aec80365
--- /dev/null
+++ b/packages/services/src/private-location/update.ts
@@ -0,0 +1,111 @@
+import { and, eq } from "@openstatus/db";
+import {
+ privateLocation,
+ privateLocationToMonitors,
+ selectPrivateLocationSchema,
+} from "@openstatus/db/src/schema";
+
+import { emitAudit } from "../audit";
+import { type ServiceContext, withTransaction } from "../context";
+import { NotFoundError } from "../errors";
+import type { PrivateLocation } from "../types";
+import { assertMonitorsInWorkspace } from "./internal";
+import { UpdatePrivateLocationInput } from "./schemas";
+
+/**
+ * Replace the name and monitor associations of a private location.
+ *
+ * `updatedAt` is set explicitly — same as the legacy router.
+ * Associations are bulk-replaced: delete-all followed by insert-all for
+ * the new set. The delete is unconditional inside the workspace-scoped
+ * tx, so there's no opportunity for a stale row to leak through.
+ */
+export async function updatePrivateLocation(args: {
+ ctx: ServiceContext;
+ input: UpdatePrivateLocationInput;
+}): Promise<PrivateLocation> {
+ const { ctx } = args;
+ const input = UpdatePrivateLocationInput.parse(args.input);
+
+ // The pivot table has no UNIQUE (private_location_id, monitor_id)
+ // constraint, so duplicate input ids would silently produce duplicate
+ // FK rows. Dedupe before insert; the audit snapshot follows suit.
+ const monitorIds = Array.from(new Set(input.monitors));
+
+ return withTransaction(ctx, async (tx) => {
+ const existing = await tx.query.privateLocation.findFirst({
+ where: and(
+ eq(privateLocation.id, input.id),
+ eq(privateLocation.workspaceId, ctx.workspace.id),
+ ),
+ with: {
+ privateLocationToMonitors: true,
+ },
+ });
+
+ if (!existing) {
+ throw new NotFoundError("private_location", input.id);
+ }
+
+ await assertMonitorsInWorkspace({
+ tx,
+ workspaceId: ctx.workspace.id,
+ monitorIds,
+ });
+
+ const row = await tx
+ .update(privateLocation)
+ .set({ name: input.name, updatedAt: new Date() })
+ .where(
+ and(
+ eq(privateLocation.id, input.id),
+ eq(privateLocation.workspaceId, ctx.workspace.id),
+ ),
+ )
+ .returning()
+ .get();
+
+ // Drizzle's `.returning().get()` is typed `T | undefined`. The
+ // `findFirst` above guarantees the row exists in this tx, but a
+ // future change to the WHERE could silently drop the row and the
+ // next line would crash with `Cannot read property 'id' of
+ // undefined`. Re-throw NotFound so the failure mode stays sane.
+ if (!row) throw new NotFoundError("private_location", input.id);
+
+ await tx
+ .delete(privateLocationToMonitors)
+ .where(eq(privateLocationToMonitors.privateLocationId, row.id));
+
+ if (monitorIds.length > 0) {
+ await tx.insert(privateLocationToMonitors).values(
+ monitorIds.map((monitorId) => ({
+ privateLocationId: row.id,
+ monitorId,
+ })),
+ );
+ }
+
+ const { privateLocationToMonitors: beforeLinks, ...beforeRow } = existing;
+ const beforeParsed = selectPrivateLocationSchema.parse(beforeRow);
+ const afterParsed = selectPrivateLocationSchema.parse(row);
+
+ await emitAudit(tx, ctx, {
+ action: "private_location.update",
+ entityType: "private_location",
+ entityId: afterParsed.id,
+ before: {
+ ...beforeParsed,
+ monitorIds: beforeLinks
+ .map((l) => l.monitorId)
+ .filter((id): id is number => id !== null)
+ .sort((a, b) => a - b),
+ },
+ after: {
+ ...afterParsed,
+ monitorIds: [...monitorIds].sort((a, b) => a - b),
+ },
+ });
+
+ return afterParsed;
+ });
+}
diff --git a/packages/services/src/status-report/__tests__/status-report.test.ts b/packages/services/src/status-report/__tests__/status-report.test.ts
index c26e40359..ef3451aae 100644
--- a/packages/services/src/status-report/__tests__/status-report.test.ts
+++ b/packages/services/src/status-report/__tests__/status-report.test.ts
@@ -1,13 +1,12 @@
import {
afterAll,
- afterEach,
beforeAll,
beforeEach,
describe,
expect,
test,
} from "bun:test";
-import { db, eq, inArray } from "@openstatus/db";
+import { db, eq } from "@openstatus/db";
import {
page,
pageComponent,
@@ -22,11 +21,11 @@ import {
SEEDED_WORKSPACE_TEAM_ID,
} from "../../../test/fixtures";
import {
- clearAuditLog,
expectAuditRow,
loadSeededWorkspace,
makeSlackCtx,
makeUserCtx,
+ withTestTransaction,
} from "../../../test/helpers";
import type { ServiceContext } from "../../context";
import { ForbiddenError, NotFoundError } from "../../errors";
@@ -62,16 +61,6 @@ let freeCtx: ServiceContext;
let testPageId: number;
let testPageComponentId: number;
-/**
- * Tests push created statusReport ids here instead of issuing an inline
- * `db.delete()` at the end of their body. `afterEach` drains the array,
- * so cleanup runs even when an assertion throws midway through a test —
- * otherwise a failing assertion leaves orphans that flake subsequent
- * runs. Individual tests can still push additional ids mid-test if they
- * create multiple reports.
- */
-const createdReportIds: number[] = [];
-
beforeAll(async () => {
const team = await loadSeededWorkspace(SEEDED_WORKSPACE_TEAM_ID);
const free = await loadSeededWorkspace(SEEDED_WORKSPACE_FREE_ID);
@@ -119,449 +108,474 @@ afterAll(async () => {
.catch(() => undefined);
});
-beforeEach(async () => {
- await clearAuditLog(teamCtx.workspace.id);
- await clearAuditLog(freeCtx.workspace.id);
+beforeEach(() => {
subscriptionSpies?.dispatchStatusReportUpdate.mockClear();
});
-afterEach(async () => {
- if (createdReportIds.length > 0) {
- await db
- .delete(statusReport)
- .where(inArray(statusReport.id, createdReportIds))
- .catch(() => undefined);
- createdReportIds.length = 0;
- }
-});
-
describe("createStatusReport", () => {
test("creates report + initial update + associations and emits audit", async () => {
- const { statusReport: report, initialUpdate } = await createStatusReport({
- ctx: teamCtx,
- input: {
- title: `${TEST_PREFIX}-create-happy`,
- status: "investigating",
- message: "starting investigation",
- date: new Date(),
- pageId: testPageId,
- pageComponentIds: [testPageComponentId],
- },
- });
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ const { statusReport: report, initialUpdate } = await createStatusReport({
+ ctx,
+ input: {
+ title: `${TEST_PREFIX}-create-happy`,
+ status: "investigating",
+ message: "starting investigation",
+ date: new Date(),
+ pageId: testPageId,
+ pageComponentIds: [testPageComponentId],
+ },
+ });
- expect(report.id).toBeGreaterThan(0);
- expect(report.title).toBe(`${TEST_PREFIX}-create-happy`);
- expect(report.pageId).toBe(testPageId);
- expect(initialUpdate.statusReportId).toBe(report.id);
- expect(initialUpdate.message).toBe("starting investigation");
-
- const assoc = await db
- .select()
- .from(statusReportsToPageComponents)
- .where(eq(statusReportsToPageComponents.statusReportId, report.id))
- .all();
- expect(assoc.map((a) => a.pageComponentId)).toEqual([testPageComponentId]);
-
- await expectAuditRow({
- workspaceId: teamCtx.workspace.id,
- action: "status_report.create",
- entityType: "status_report",
- entityId: report.id,
- });
+ expect(report.id).toBeGreaterThan(0);
+ expect(report.title).toBe(`${TEST_PREFIX}-create-happy`);
+ expect(report.pageId).toBe(testPageId);
+ expect(initialUpdate.statusReportId).toBe(report.id);
+ expect(initialUpdate.message).toBe("starting investigation");
+
+ const assoc = await tx
+ .select()
+ .from(statusReportsToPageComponents)
+ .where(eq(statusReportsToPageComponents.statusReportId, report.id))
+ .all();
+ expect(assoc.map((a) => a.pageComponentId)).toEqual([
+ testPageComponentId,
+ ]);
+
+ await expectAuditRow({
+ workspaceId: teamCtx.workspace.id,
+ action: "status_report.create",
+ entityType: "status_report",
+ entityId: report.id,
+ db: tx,
+ });
- createdReportIds.push(report.id);
+ await expectAuditRow({
+ workspaceId: teamCtx.workspace.id,
+ action: "status_report_update.create",
+ entityType: "status_report_update",
+ entityId: initialUpdate.id,
+ db: tx,
+ });
+ });
});
test("throws NotFoundError when the page is not in the workspace", async () => {
- await expect(
- createStatusReport({
- ctx: freeCtx,
- input: {
- title: `${TEST_PREFIX}-create-cross-ws`,
- status: "investigating",
- message: "should fail",
- date: new Date(),
- pageId: testPageId, // page belongs to team workspace
- pageComponentIds: [],
- },
- }),
- ).rejects.toBeInstanceOf(NotFoundError);
+ await withTestTransaction(async (tx) => {
+ await expect(
+ createStatusReport({
+ ctx: { ...freeCtx, db: tx },
+ input: {
+ title: `${TEST_PREFIX}-create-cross-ws`,
+ status: "investigating",
+ message: "should fail",
+ date: new Date(),
+ pageId: testPageId, // page belongs to team workspace
+ pageComponentIds: [],
+ },
+ }),
+ ).rejects.toBeInstanceOf(NotFoundError);
+ });
});
});
describe("addStatusReportUpdate", () => {
test("appends an update and bumps parent status", async () => {
- const { statusReport: report } = await createStatusReport({
- ctx: teamCtx,
- input: {
- title: `${TEST_PREFIX}-add-update`,
- status: "investigating",
- message: "initial",
- date: new Date(),
- pageId: testPageId,
- pageComponentIds: [],
- },
- });
-
- const { statusReport: bumped, statusReportUpdate: newUpdate } =
- await addStatusReportUpdate({
- ctx: teamCtx,
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ const { statusReport: report } = await createStatusReport({
+ ctx,
input: {
- statusReportId: report.id,
- status: "monitoring",
- message: "moved to monitoring",
+ title: `${TEST_PREFIX}-add-update`,
+ status: "investigating",
+ message: "initial",
+ date: new Date(),
+ pageId: testPageId,
+ pageComponentIds: [],
},
});
- expect(bumped.status).toBe("monitoring");
- expect(newUpdate.status).toBe("monitoring");
- expect(newUpdate.statusReportId).toBe(report.id);
-
- await expectAuditRow({
- workspaceId: teamCtx.workspace.id,
- action: "status_report_update.create",
- entityType: "status_report_update",
- entityId: newUpdate.id,
+ const { statusReport: bumped, statusReportUpdate: newUpdate } =
+ await addStatusReportUpdate({
+ ctx,
+ input: {
+ statusReportId: report.id,
+ status: "monitoring",
+ message: "moved to monitoring",
+ },
+ });
+
+ expect(bumped.status).toBe("monitoring");
+ expect(newUpdate.status).toBe("monitoring");
+ expect(newUpdate.statusReportId).toBe(report.id);
+
+ await expectAuditRow({
+ workspaceId: teamCtx.workspace.id,
+ action: "status_report_update.create",
+ entityType: "status_report_update",
+ entityId: newUpdate.id,
+ db: tx,
+ });
});
-
- createdReportIds.push(report.id);
});
test("throws NotFoundError for a status report in another workspace", async () => {
- const { statusReport: report } = await createStatusReport({
- ctx: teamCtx,
- input: {
- title: `${TEST_PREFIX}-cross-ws-add`,
- status: "investigating",
- message: "m",
- date: new Date(),
- pageId: testPageId,
- pageComponentIds: [],
- },
- });
-
- await expect(
- addStatusReportUpdate({
- ctx: freeCtx,
+ await withTestTransaction(async (tx) => {
+ const { statusReport: report } = await createStatusReport({
+ ctx: { ...teamCtx, db: tx },
input: {
- statusReportId: report.id,
- status: "monitoring",
- message: "cross-ws",
+ title: `${TEST_PREFIX}-cross-ws-add`,
+ status: "investigating",
+ message: "m",
+ date: new Date(),
+ pageId: testPageId,
+ pageComponentIds: [],
},
- }),
- ).rejects.toBeInstanceOf(NotFoundError);
+ });
- createdReportIds.push(report.id);
+ await expect(
+ addStatusReportUpdate({
+ ctx: { ...freeCtx, db: tx },
+ input: {
+ statusReportId: report.id,
+ status: "monitoring",
+ message: "cross-ws",
+ },
+ }),
+ ).rejects.toBeInstanceOf(NotFoundError);
+ });
});
});
describe("resolveStatusReport", () => {
test("appends a resolved update and flips parent status", async () => {
- const { statusReport: report } = await createStatusReport({
- ctx: teamCtx,
- input: {
- title: `${TEST_PREFIX}-resolve`,
- status: "investigating",
- message: "oops",
- date: new Date(),
- pageId: testPageId,
- pageComponentIds: [],
- },
- });
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ const { statusReport: report } = await createStatusReport({
+ ctx,
+ input: {
+ title: `${TEST_PREFIX}-resolve`,
+ status: "investigating",
+ message: "oops",
+ date: new Date(),
+ pageId: testPageId,
+ pageComponentIds: [],
+ },
+ });
- const { statusReport: resolved } = await resolveStatusReport({
- ctx: teamCtx,
- input: { statusReportId: report.id, message: "all clear" },
+ const { statusReport: resolved } = await resolveStatusReport({
+ ctx,
+ input: { statusReportId: report.id, message: "all clear" },
+ });
+ expect(resolved.status).toBe("resolved");
});
- expect(resolved.status).toBe("resolved");
- createdReportIds.push(report.id);
});
});
describe("updateStatusReport", () => {
test("updates title and replaces associations", async () => {
- const { statusReport: report } = await createStatusReport({
- ctx: teamCtx,
- input: {
- title: `${TEST_PREFIX}-update`,
- status: "investigating",
- message: "m",
- date: new Date(),
- pageId: testPageId,
- pageComponentIds: [testPageComponentId],
- },
- });
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ const { statusReport: report } = await createStatusReport({
+ ctx,
+ input: {
+ title: `${TEST_PREFIX}-update`,
+ status: "investigating",
+ message: "m",
+ date: new Date(),
+ pageId: testPageId,
+ pageComponentIds: [testPageComponentId],
+ },
+ });
- const updated = await updateStatusReport({
- ctx: teamCtx,
- input: {
- id: report.id,
- title: `${TEST_PREFIX}-update-renamed`,
- pageComponentIds: [],
- },
+ const updated = await updateStatusReport({
+ ctx,
+ input: {
+ id: report.id,
+ title: `${TEST_PREFIX}-update-renamed`,
+ pageComponentIds: [],
+ },
+ });
+ expect(updated.title).toBe(`${TEST_PREFIX}-update-renamed`);
+
+ const assoc = await tx
+ .select()
+ .from(statusReportsToPageComponents)
+ .where(eq(statusReportsToPageComponents.statusReportId, report.id))
+ .all();
+ expect(assoc).toHaveLength(0);
});
- expect(updated.title).toBe(`${TEST_PREFIX}-update-renamed`);
-
- const assoc = await db
- .select()
- .from(statusReportsToPageComponents)
- .where(eq(statusReportsToPageComponents.statusReportId, report.id))
- .all();
- expect(assoc).toHaveLength(0);
-
- createdReportIds.push(report.id);
});
});
describe("deleteStatusReport", () => {
test("cascades updates + associations", async () => {
- const { statusReport: report, initialUpdate } = await createStatusReport({
- ctx: teamCtx,
- input: {
- title: `${TEST_PREFIX}-delete`,
- status: "investigating",
- message: "m",
- date: new Date(),
- pageId: testPageId,
- pageComponentIds: [testPageComponentId],
- },
- });
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ const { statusReport: report, initialUpdate } = await createStatusReport({
+ ctx,
+ input: {
+ title: `${TEST_PREFIX}-delete`,
+ status: "investigating",
+ message: "m",
+ date: new Date(),
+ pageId: testPageId,
+ pageComponentIds: [testPageComponentId],
+ },
+ });
- await deleteStatusReport({ ctx: teamCtx, input: { id: report.id } });
-
- const remainingReport = await db
- .select()
- .from(statusReport)
- .where(eq(statusReport.id, report.id))
- .all();
- const remainingUpdate = await db
- .select()
- .from(statusReportUpdate)
- .where(eq(statusReportUpdate.id, initialUpdate.id))
- .all();
- const remainingAssoc = await db
- .select()
- .from(statusReportsToPageComponents)
- .where(eq(statusReportsToPageComponents.statusReportId, report.id))
- .all();
- expect(remainingReport).toHaveLength(0);
- expect(remainingUpdate).toHaveLength(0);
- expect(remainingAssoc).toHaveLength(0);
+ await deleteStatusReport({ ctx, input: { id: report.id } });
+
+ const remainingReport = await tx
+ .select()
+ .from(statusReport)
+ .where(eq(statusReport.id, report.id))
+ .all();
+ const remainingUpdate = await tx
+ .select()
+ .from(statusReportUpdate)
+ .where(eq(statusReportUpdate.id, initialUpdate.id))
+ .all();
+ const remainingAssoc = await tx
+ .select()
+ .from(statusReportsToPageComponents)
+ .where(eq(statusReportsToPageComponents.statusReportId, report.id))
+ .all();
+ expect(remainingReport).toHaveLength(0);
+ expect(remainingUpdate).toHaveLength(0);
+ expect(remainingAssoc).toHaveLength(0);
+ });
});
test("throws NotFoundError for cross-workspace delete", async () => {
- const { statusReport: report } = await createStatusReport({
- ctx: teamCtx,
- input: {
- title: `${TEST_PREFIX}-cross-ws-delete`,
- status: "investigating",
- message: "m",
- date: new Date(),
- pageId: testPageId,
- pageComponentIds: [],
- },
- });
-
- await expect(
- deleteStatusReport({ ctx: freeCtx, input: { id: report.id } }),
- ).rejects.toBeInstanceOf(NotFoundError);
+ await withTestTransaction(async (tx) => {
+ const { statusReport: report } = await createStatusReport({
+ ctx: { ...teamCtx, db: tx },
+ input: {
+ title: `${TEST_PREFIX}-cross-ws-delete`,
+ status: "investigating",
+ message: "m",
+ date: new Date(),
+ pageId: testPageId,
+ pageComponentIds: [],
+ },
+ });
- createdReportIds.push(report.id);
+ await expect(
+ deleteStatusReport({
+ ctx: { ...freeCtx, db: tx },
+ input: { id: report.id },
+ }),
+ ).rejects.toBeInstanceOf(NotFoundError);
+ });
});
});
describe("deleteStatusReportUpdate", () => {
test("removes a single update and emits audit", async () => {
- const { statusReport: report } = await createStatusReport({
- ctx: teamCtx,
- input: {
- title: `${TEST_PREFIX}-delete-update`,
- status: "investigating",
- message: "m",
- date: new Date(),
- pageId: testPageId,
- pageComponentIds: [],
- },
- });
- const { statusReportUpdate: newUpdate } = await addStatusReportUpdate({
- ctx: teamCtx,
- input: {
- statusReportId: report.id,
- status: "monitoring",
- message: "to be deleted",
- },
- });
-
- await deleteStatusReportUpdate({
- ctx: teamCtx,
- input: { id: newUpdate.id },
- });
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ const { statusReport: report } = await createStatusReport({
+ ctx,
+ input: {
+ title: `${TEST_PREFIX}-delete-update`,
+ status: "investigating",
+ message: "m",
+ date: new Date(),
+ pageId: testPageId,
+ pageComponentIds: [],
+ },
+ });
+ const { statusReportUpdate: newUpdate } = await addStatusReportUpdate({
+ ctx,
+ input: {
+ statusReportId: report.id,
+ status: "monitoring",
+ message: "to be deleted",
+ },
+ });
- const remaining = await db
- .select()
- .from(statusReportUpdate)
- .where(eq(statusReportUpdate.id, newUpdate.id))
- .all();
- expect(remaining).toHaveLength(0);
+ await deleteStatusReportUpdate({
+ ctx,
+ input: { id: newUpdate.id },
+ });
- createdReportIds.push(report.id);
+ const remaining = await tx
+ .select()
+ .from(statusReportUpdate)
+ .where(eq(statusReportUpdate.id, newUpdate.id))
+ .all();
+ expect(remaining).toHaveLength(0);
+ });
});
});
describe("updateStatusReportUpdate", () => {
test("edits message + date; returns updated row", async () => {
- const { statusReport: report, initialUpdate } = await createStatusReport({
- ctx: teamCtx,
- input: {
- title: `${TEST_PREFIX}-edit-update`,
- status: "investigating",
- message: "before",
- date: new Date(),
- pageId: testPageId,
- pageComponentIds: [],
- },
- });
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ const { initialUpdate } = await createStatusReport({
+ ctx,
+ input: {
+ title: `${TEST_PREFIX}-edit-update`,
+ status: "investigating",
+ message: "before",
+ date: new Date(),
+ pageId: testPageId,
+ pageComponentIds: [],
+ },
+ });
- const edited = await updateStatusReportUpdate({
- ctx: teamCtx,
- input: { id: initialUpdate.id, message: "after" },
+ const edited = await updateStatusReportUpdate({
+ ctx,
+ input: { id: initialUpdate.id, message: "after" },
+ });
+ expect(edited.message).toBe("after");
});
- expect(edited.message).toBe("after");
-
- createdReportIds.push(report.id);
});
test("throws ForbiddenError for cross-workspace edit", async () => {
- const { statusReport: report, initialUpdate } = await createStatusReport({
- ctx: teamCtx,
- input: {
- title: `${TEST_PREFIX}-cross-ws-edit`,
- status: "investigating",
- message: "m",
- date: new Date(),
- pageId: testPageId,
- pageComponentIds: [],
- },
- });
-
- await expect(
- updateStatusReportUpdate({
- ctx: freeCtx,
- input: { id: initialUpdate.id, message: "blocked" },
- }),
- ).rejects.toBeInstanceOf(ForbiddenError);
+ await withTestTransaction(async (tx) => {
+ const { initialUpdate } = await createStatusReport({
+ ctx: { ...teamCtx, db: tx },
+ input: {
+ title: `${TEST_PREFIX}-cross-ws-edit`,
+ status: "investigating",
+ message: "m",
+ date: new Date(),
+ pageId: testPageId,
+ pageComponentIds: [],
+ },
+ });
- createdReportIds.push(report.id);
+ await expect(
+ updateStatusReportUpdate({
+ ctx: { ...freeCtx, db: tx },
+ input: { id: initialUpdate.id, message: "blocked" },
+ }),
+ ).rejects.toBeInstanceOf(ForbiddenError);
+ });
});
});
describe("listStatusReports / getStatusReport", () => {
test("respects workspace isolation", async () => {
- const { statusReport: report } = await createStatusReport({
- ctx: teamCtx,
- input: {
- title: `${TEST_PREFIX}-isolation`,
- status: "investigating",
- message: "m",
- date: new Date(),
- pageId: testPageId,
- pageComponentIds: [],
- },
- });
+ await withTestTransaction(async (tx) => {
+ const teamCtxTx = { ...teamCtx, db: tx };
+ const freeCtxTx = { ...freeCtx, db: tx };
+ const { statusReport: report } = await createStatusReport({
+ ctx: teamCtxTx,
+ input: {
+ title: `${TEST_PREFIX}-isolation`,
+ status: "investigating",
+ message: "m",
+ date: new Date(),
+ pageId: testPageId,
+ pageComponentIds: [],
+ },
+ });
- await expect(
- getStatusReport({ ctx: freeCtx, input: { id: report.id } }),
- ).rejects.toBeInstanceOf(NotFoundError);
-
- const { items: freeItems } = await listStatusReports({
- ctx: freeCtx,
- input: {
- limit: 100,
- offset: 0,
- statuses: [],
- order: "desc",
- pageId: testPageId,
- },
- });
- expect(freeItems.find((r) => r.id === report.id)).toBeUndefined();
+ await expect(
+ getStatusReport({ ctx: freeCtxTx, input: { id: report.id } }),
+ ).rejects.toBeInstanceOf(NotFoundError);
- createdReportIds.push(report.id);
+ const { items: freeItems } = await listStatusReports({
+ ctx: freeCtxTx,
+ input: {
+ limit: 100,
+ offset: 0,
+ statuses: [],
+ order: "desc",
+ pageId: testPageId,
+ },
+ });
+ expect(freeItems.find((r) => r.id === report.id)).toBeUndefined();
+ });
});
test("returns totalSize and enriched relations", async () => {
- const { statusReport: report } = await createStatusReport({
- ctx: teamCtx,
- input: {
- title: `${TEST_PREFIX}-list-enrich`,
- status: "investigating",
- message: "m",
- date: new Date(),
- pageId: testPageId,
- pageComponentIds: [testPageComponentId],
- },
- });
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ const { statusReport: report } = await createStatusReport({
+ ctx,
+ input: {
+ title: `${TEST_PREFIX}-list-enrich`,
+ status: "investigating",
+ message: "m",
+ date: new Date(),
+ pageId: testPageId,
+ pageComponentIds: [testPageComponentId],
+ },
+ });
- const full = await getStatusReport({
- ctx: teamCtx,
- input: { id: report.id },
+ const full = await getStatusReport({
+ ctx,
+ input: { id: report.id },
+ });
+ expect(full.updates).toHaveLength(1);
+ expect(full.pageComponents.map((c) => c.id)).toEqual([
+ testPageComponentId,
+ ]);
+ expect(full.page?.id).toBe(testPageId);
});
- expect(full.updates).toHaveLength(1);
- expect(full.pageComponents.map((c) => c.id)).toEqual([testPageComponentId]);
- expect(full.page?.id).toBe(testPageId);
-
- createdReportIds.push(report.id);
});
});
describe("notifyStatusReport", () => {
test("throws when update belongs to another workspace", async () => {
- const { statusReport: report, initialUpdate } = await createStatusReport({
- ctx: teamCtx,
- input: {
- title: `${TEST_PREFIX}-notify-cross-ws`,
- status: "investigating",
- message: "m",
- date: new Date(),
- pageId: testPageId,
- pageComponentIds: [],
- },
- });
-
- await expect(
- notifyStatusReport({
- ctx: freeCtx,
- input: { statusReportUpdateId: initialUpdate.id },
- }),
- ).rejects.toBeInstanceOf(ForbiddenError);
+ await withTestTransaction(async (tx) => {
+ const { initialUpdate } = await createStatusReport({
+ ctx: { ...teamCtx, db: tx },
+ input: {
+ title: `${TEST_PREFIX}-notify-cross-ws`,
+ status: "investigating",
+ message: "m",
+ date: new Date(),
+ pageId: testPageId,
+ pageComponentIds: [],
+ },
+ });
- createdReportIds.push(report.id);
+ await expect(
+ notifyStatusReport({
+ ctx: { ...freeCtx, db: tx },
+ input: { statusReportUpdateId: initialUpdate.id },
+ }),
+ ).rejects.toBeInstanceOf(ForbiddenError);
+ });
});
});
describe("slack actor path", () => {
test("createStatusReport succeeds with a slack actor", async () => {
- const ctx = makeSlackCtx(teamCtx.workspace, {
- teamId: "T123",
- slackUserId: "U123",
- });
- const { statusReport: report } = await createStatusReport({
- ctx,
- input: {
- title: `${TEST_PREFIX}-slack`,
- status: "investigating",
- message: "via slack",
- date: new Date(),
- pageId: testPageId,
- pageComponentIds: [],
- },
- });
- await expectAuditRow({
- workspaceId: teamCtx.workspace.id,
- action: "status_report.create",
- entityType: "status_report",
- entityId: report.id,
- actorType: "slack",
+ await withTestTransaction(async (tx) => {
+ const ctx = {
+ ...makeSlackCtx(teamCtx.workspace, {
+ teamId: "T123",
+ slackUserId: "U123",
+ }),
+ db: tx,
+ };
+ const { statusReport: report } = await createStatusReport({
+ ctx,
+ input: {
+ title: `${TEST_PREFIX}-slack`,
+ status: "investigating",
+ message: "via slack",
+ date: new Date(),
+ pageId: testPageId,
+ pageComponentIds: [],
+ },
+ });
+ await expectAuditRow({
+ workspaceId: teamCtx.workspace.id,
+ action: "status_report.create",
+ entityType: "status_report",
+ entityId: report.id,
+ actorType: "slack",
+ db: tx,
+ });
});
- createdReportIds.push(report.id);
});
});
diff --git a/packages/services/src/status-report/create.ts b/packages/services/src/status-report/create.ts
index 320e43f29..7e297be5b 100644
--- a/packages/services/src/status-report/create.ts
+++ b/packages/services/src/status-report/create.ts
@@ -84,6 +84,14 @@ export async function createStatusReport(args: {
after: newReport,
});
+ await emitAudit(tx, ctx, {
+ action: "status_report_update.create",
+ entityType: "status_report_update",
+ entityId: initialUpdate.id,
+ after: initialUpdate,
+ metadata: { statusReportId: newReport.id },
+ });
+
return { statusReport: newReport, initialUpdate };
});
}
diff --git a/packages/services/src/types.ts b/packages/services/src/types.ts
index b88b434b8..9937d1dda 100644
--- a/packages/services/src/types.ts
+++ b/packages/services/src/types.ts
@@ -29,6 +29,7 @@ export type { Incident, Monitor } from "@openstatus/db/src/schema";
export type {
MonitorTag,
Notification,
+ PageSubscriber,
PrivateLocation,
} from "@openstatus/db/src/schema";
diff --git a/packages/services/src/workspace/__tests__/workspace.test.ts b/packages/services/src/workspace/__tests__/workspace.test.ts
index 3dae7b6b5..c3d895356 100644
--- a/packages/services/src/workspace/__tests__/workspace.test.ts
+++ b/packages/services/src/workspace/__tests__/workspace.test.ts
@@ -1,12 +1,5 @@
-import {
- afterAll,
- beforeAll,
- beforeEach,
- describe,
- expect,
- test,
-} from "bun:test";
-import { db, eq } from "@openstatus/db";
+import { beforeAll, describe, expect, test } from "bun:test";
+import { eq } from "@openstatus/db";
import { workspace } from "@openstatus/db/src/schema";
import {
@@ -17,112 +10,111 @@ import {
} from "..";
import { SEEDED_WORKSPACE_TEAM_ID } from "../../../test/fixtures";
import {
- clearAuditLog,
expectAuditRow,
loadSeededWorkspace,
makeUserCtx,
+ withTestTransaction,
} from "../../../test/helpers";
import type { ServiceContext } from "../../context";
let teamCtx: ServiceContext;
-let originalName: string | null = null;
beforeAll(async () => {
const team = await loadSeededWorkspace(SEEDED_WORKSPACE_TEAM_ID);
teamCtx = makeUserCtx(team, { userId: 1 });
- originalName = team.name;
-});
-
-afterAll(async () => {
- if (originalName !== null) {
- await db
- .update(workspace)
- .set({ name: originalName })
- .where(eq(workspace.id, SEEDED_WORKSPACE_TEAM_ID));
- }
-});
-
-beforeEach(async () => {
- await clearAuditLog(teamCtx.workspace.id);
});
describe("getWorkspace", () => {
test("returns the caller's workspace", async () => {
- const result = await getWorkspace({ ctx: teamCtx });
- expect(result.id).toBe(SEEDED_WORKSPACE_TEAM_ID);
- expect(typeof result.limits).toBe("object");
+ await withTestTransaction(async (tx) => {
+ const result = await getWorkspace({ ctx: { ...teamCtx, db: tx } });
+ expect(result.id).toBe(SEEDED_WORKSPACE_TEAM_ID);
+ expect(typeof result.limits).toBe("object");
+ });
});
});
describe("getWorkspaceWithUsage", () => {
test("attaches a zero-or-positive usage block", async () => {
- const result = await getWorkspaceWithUsage({ ctx: teamCtx });
- expect(result.id).toBe(SEEDED_WORKSPACE_TEAM_ID);
+ await withTestTransaction(async (tx) => {
+ const result = await getWorkspaceWithUsage({
+ ctx: { ...teamCtx, db: tx },
+ });
+ expect(result.id).toBe(SEEDED_WORKSPACE_TEAM_ID);
- // Iterate the usage object *before* any `toMatchObject` call —
- // bun:test's `toMatchObject` implementation mutates the received
- // object in place, replacing number fields with the
- // `expect.any(Number)` asymmetric-matcher stub on the expected
- // side. Subsequent reads of `result.usage.<key>` then return the
- // matcher object (typeof "object"), not the original count. Do
- // the value-shape + non-negative check first.
- for (const key of [
- "monitors",
- "notifications",
- "pages",
- "pageComponents",
- "checks",
- ] as const) {
- const value = result.usage[key];
- expect(typeof value).toBe("number");
- if (typeof value === "number") {
- expect(value).toBeGreaterThanOrEqual(0);
+ // Iterate the usage object *before* any `toMatchObject` call —
+ // bun:test's `toMatchObject` implementation mutates the received
+ // object in place, replacing number fields with the
+ // `expect.any(Number)` asymmetric-matcher stub on the expected
+ // side. Subsequent reads of `result.usage.<key>` then return the
+ // matcher object (typeof "object"), not the original count. Do
+ // the value-shape + non-negative check first.
+ for (const key of [
+ "monitors",
+ "notifications",
+ "pages",
+ "pageComponents",
+ "checks",
+ ] as const) {
+ const value = result.usage[key];
+ expect(typeof value).toBe("number");
+ if (typeof value === "number") {
+ expect(value).toBeGreaterThanOrEqual(0);
+ }
}
- }
- expect(result.usage.checks).toBe(0);
+ expect(result.usage.checks).toBe(0);
+ });
});
});
describe("listWorkspaces", () => {
test("returns every workspace a user belongs to", async () => {
- const rows = await listWorkspaces({
- ctx: teamCtx,
- input: { userId: 1 },
+ await withTestTransaction(async (tx) => {
+ const rows = await listWorkspaces({
+ ctx: { ...teamCtx, db: tx },
+ input: { userId: 1 },
+ });
+ const ids = rows.map((r) => r.id);
+ expect(ids).toContain(SEEDED_WORKSPACE_TEAM_ID);
});
- const ids = rows.map((r) => r.id);
- expect(ids).toContain(SEEDED_WORKSPACE_TEAM_ID);
});
test("returns an empty list for a user with no memberships", async () => {
- const rows = await listWorkspaces({
- ctx: teamCtx,
- input: { userId: 999_999 },
+ await withTestTransaction(async (tx) => {
+ const rows = await listWorkspaces({
+ ctx: { ...teamCtx, db: tx },
+ input: { userId: 999_999 },
+ });
+ expect(rows).toEqual([]);
});
- expect(rows).toEqual([]);
});
});
describe("updateWorkspaceName", () => {
test("renames the workspace and emits an audit row", async () => {
- const nextName = `svc-ws-test-${Date.now()}`;
- await updateWorkspaceName({
- ctx: teamCtx,
- input: { name: nextName },
- });
+ await withTestTransaction(async (tx) => {
+ const ctx = { ...teamCtx, db: tx };
+ const nextName = `svc-ws-test-${Date.now()}`;
+ await updateWorkspaceName({
+ ctx,
+ input: { name: nextName },
+ });
- const row = await db
- .select()
- .from(workspace)
- .where(eq(workspace.id, SEEDED_WORKSPACE_TEAM_ID))
- .get();
- expect(row?.name).toBe(nextName);
+ const row = await tx
+ .select()
+ .from(workspace)
+ .where(eq(workspace.id, SEEDED_WORKSPACE_TEAM_ID))
+ .get();
+ expect(row?.name).toBe(nextName);
- await expectAuditRow({
- workspaceId: teamCtx.workspace.id,
- action: "workspace.update",
- entityType: "workspace",
- entityId: SEEDED_WORKSPACE_TEAM_ID,
- actorType: "user",
+ await expectAuditRow({
+ workspaceId: teamCtx.workspace.id,
+ action: "workspace.update",
+ entityType: "workspace",
+ entityId: SEEDED_WORKSPACE_TEAM_ID,
+ actorType: "user",
+ db: tx,
+ });
});
});
});
diff --git a/packages/services/test/helpers.ts b/packages/services/test/helpers.ts
index 6a8c97c13..b1c1cc752 100644
--- a/packages/services/test/helpers.ts
+++ b/packages/services/test/helpers.ts
@@ -9,9 +9,45 @@ import {
workspace as workspaceTable,
} from "@openstatus/db/src/schema";
-import type { Actor, ServiceContext } from "../src/context";
+import type { Actor, DB, DrizzleTx, ServiceContext } from "../src/context";
import type { Workspace } from "../src/types";
+class RollbackSignal extends Error {}
+
+/**
+ * Wrap a test body in a transaction that always rolls back, so per-test
+ * writes (rows, audit log entries, etc.) never reach the committed db.
+ *
+ * Usage:
+ * await withTestTransaction(async (tx) => {
+ * const ctx = { ...makeUserCtx(workspace), db: tx };
+ * await createPage({ ctx, input });
+ * await expectAuditRow({ ..., db: tx });
+ * });
+ *
+ * Constraints:
+ * - Top-level test wrapper only. Don't call inside service code or
+ * nest two `withTestTransaction` calls — libsql HTTP doesn't
+ * support savepoints.
+ * - Inside the callback, replace any `db.select(...)` /
+ * `db.insert(...)` / `db.delete(...)` with the same call on `tx`.
+ * Reads via committed `db` will not see the in-tx writes.
+ */
+export async function withTestTransaction<T>(
+ fn: (tx: DrizzleTx) => Promise<T>,
+): Promise<T> {
+ let result!: T;
+ try {
+ await db.transaction(async (tx) => {
+ result = await fn(tx);
+ throw new RollbackSignal();
+ });
+ } catch (e) {
+ if (!(e instanceof RollbackSignal)) throw e;
+ }
+ 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`,
@@ -51,8 +87,12 @@ export async function cleanQuotaGatedTables(
}
/** Wipe audit_log rows for a workspace. Call in `beforeEach` / `afterEach`. */
-export async function clearAuditLog(workspaceId: number): Promise<void> {
- await db
+export async function clearAuditLog(
+ workspaceId: number,
+ opts: { db?: DB } = {},
+): Promise<void> {
+ const conn = opts.db ?? db;
+ await conn
.delete(auditLog)
.where(eq(auditLog.workspaceId, workspaceId))
.catch(() => undefined);
@@ -145,7 +185,9 @@ export async function readAuditLog(filter: {
workspaceId: number;
entityType?: string;
entityId?: string | number;
+ db?: DB;
}): Promise<(typeof auditLog.$inferSelect)[]> {
+ const conn = filter.db ?? db;
const clauses = [eq(auditLog.workspaceId, filter.workspaceId)];
if (filter.entityType !== undefined) {
clauses.push(eq(auditLog.entityType, filter.entityType));
@@ -153,7 +195,7 @@ export async function readAuditLog(filter: {
if (filter.entityId !== undefined) {
clauses.push(eq(auditLog.entityId, String(filter.entityId)));
}
- return db
+ return conn
.select()
.from(auditLog)
.where(and(...clauses))
@@ -173,12 +215,14 @@ export async function expectAuditRow(match: {
entityType: string;
entityId: string | number;
actorType?: Actor["type"];
+ db?: DB;
}): Promise<void> {
const expectedEntityId = String(match.entityId);
const rows = await readAuditLog({
workspaceId: match.workspaceId,
entityType: match.entityType,
entityId: expectedEntityId,
+ db: match.db,
});
const hit = rows.find(
(row) =>
diff --git a/packages/subscriptions/src/index.ts b/packages/subscriptions/src/index.ts
index 09caf18b5..b161ad005 100644
--- a/packages/subscriptions/src/index.ts
+++ b/packages/subscriptions/src/index.ts
@@ -22,22 +22,9 @@ export {
dispatchPageUpdate,
} from "./dispatcher";
-// Export service functions
-export {
- createSubscription,
- upsertEmailSubscription,
- hasPendingUnexpiredSubscription,
- verifySubscription,
- getSubscriptionByToken,
- sendTestWebhook,
- updateChannel,
- updateSubscriptionScope,
- unsubscribe,
-} from "./service";
-export type {
- CreateSubscriptionInput,
- UpdateChannelInput,
-} from "./service";
+// Subscription CRUD lives in `@openstatus/services/page-subscriber` —
+// this package now only ships the channel + dispatcher primitives that
+// the service layer composes on top of.
// Export types
export type { Subscription, PageUpdate, SubscriptionChannel } from "./types";
diff --git a/packages/subscriptions/src/service.test.ts b/packages/subscriptions/src/service.test.ts
deleted file mode 100644
index 5e0216ae3..000000000
--- a/packages/subscriptions/src/service.test.ts
+++ /dev/null
@@ -1,397 +0,0 @@
-import { afterAll, beforeAll, describe, expect, test } from "bun:test";
-import { and, db, eq, isNull } from "@openstatus/db";
-import { pageSubscriber } from "@openstatus/db/src/schema";
-import {
- getSubscriptionByToken,
- unsubscribe,
- updateSubscriptionScope,
- upsertEmailSubscription,
- verifySubscription,
-} from "./service";
-
-// IDs present in the seeded database
-const PAGE_ID = 1; // slug: "status", customDomain: ""
-const COMPONENT_1 = 1;
-const COMPONENT_2 = 2;
-
-// One email per describe block to keep them fully independent
-const EMAILS = {
- upsert: "[email protected]",
- verify: "[email protected]",
- verifyExpired: "[email protected]",
- getByToken: "[email protected]",
- scope: "[email protected]",
- scopeUnverified: "[email protected]",
- scopeUnsubbed: "[email protected]",
- unsub: "[email protected]",
-};
-
-async function cleanAll() {
- for (const email of Object.values(EMAILS)) {
- await db.delete(pageSubscriber).where(eq(pageSubscriber.email, email));
- }
-}
-
-beforeAll(cleanAll);
-afterAll(cleanAll);
-
-// ─── upsertEmailSubscription ──────────────────────────────────────────────────
-
-describe("upsertEmailSubscription", () => {
- const email = EMAILS.upsert;
-
- beforeAll(async () => {
- await db.delete(pageSubscriber).where(eq(pageSubscriber.email, email));
- });
-
- test("creates a new subscription for an unknown email", async () => {
- const result = await upsertEmailSubscription({ email, pageId: PAGE_ID });
-
- expect(result.email).toBe(email);
- expect(result.pageId).toBe(PAGE_ID);
- expect(result.token).toBeDefined();
- expect(result.acceptedAt).toBeUndefined();
- expect(result.componentIds).toEqual([]);
- });
-
- test("does not create a duplicate row when called again", async () => {
- await upsertEmailSubscription({ email, pageId: PAGE_ID });
-
- const rows = await db.query.pageSubscriber.findMany({
- where: eq(pageSubscriber.email, email),
- });
-
- expect(rows).toHaveLength(1);
- });
-
- test("merges new components into an existing subscription", async () => {
- const result = await upsertEmailSubscription({
- email,
- pageId: PAGE_ID,
- componentIds: [COMPONENT_1],
- });
-
- expect(result.componentIds).toContain(COMPONENT_1);
- });
-
- test("refreshes expiresAt for a still-pending subscription", async () => {
- const before = new Date();
- await upsertEmailSubscription({ email, pageId: PAGE_ID });
-
- const row = await db.query.pageSubscriber.findFirst({
- where: eq(pageSubscriber.email, email),
- });
-
- expect(row?.expiresAt?.getTime()).toBeGreaterThan(before.getTime());
- });
-
- test("stores email in lowercase regardless of input casing", async () => {
- await db.delete(pageSubscriber).where(eq(pageSubscriber.email, email));
-
- const result = await upsertEmailSubscription({
- email: email.toUpperCase(),
- pageId: PAGE_ID,
- });
-
- expect(result.email).toBe(email);
- });
-
- test("creates a new row (does not reactivate) when email was previously unsubscribed", async () => {
- const existing = await db.query.pageSubscriber.findFirst({
- where: eq(pageSubscriber.email, email),
- });
-
- if (!existing) {
- throw new Error("Existing subscriber not found");
- }
-
- await db
- .update(pageSubscriber)
- .set({ acceptedAt: new Date(), unsubscribedAt: new Date() })
- .where(eq(pageSubscriber.id, existing.id))
- .run();
-
- const result = await upsertEmailSubscription({
- email,
- pageId: PAGE_ID,
- componentIds: [COMPONENT_1],
- });
-
- // A brand-new row — not a mutation of the old one
- expect(result.id).not.toBe(existing.id);
- expect(result.acceptedAt).toBeUndefined(); // requires re-verification
- expect(result.componentIds).toEqual([COMPONENT_1]);
-
- // Old row is preserved with its unsubscribedAt intact
- const oldRow = await db.query.pageSubscriber.findFirst({
- where: eq(pageSubscriber.id, existing.id),
- });
- expect(oldRow?.unsubscribedAt).toBeDefined();
- });
-
- test("creates a new row when email was unsubscribed before ever verifying", async () => {
- // Find the currently active (pending, never verified) row left by the previous test
- const pending = await db.query.pageSubscriber.findFirst({
- where: and(
- eq(pageSubscriber.email, email),
- isNull(pageSubscriber.unsubscribedAt),
- ),
- });
- if (!pending) throw new Error("Pending subscriber not found");
- expect(pending.acceptedAt).toBeNull(); // confirm it was never verified
-
- await db
- .update(pageSubscriber)
- .set({ unsubscribedAt: new Date() })
- .where(eq(pageSubscriber.id, pending.id))
- .run();
-
- const result = await upsertEmailSubscription({ email, pageId: PAGE_ID });
-
- expect(result.id).not.toBe(pending.id);
- expect(result.acceptedAt).toBeUndefined();
-
- // Old unverified+unsubscribed row still has both fields set correctly
- const oldRow = await db.query.pageSubscriber.findFirst({
- where: eq(pageSubscriber.id, pending.id),
- });
- expect(oldRow?.unsubscribedAt).toBeDefined();
- expect(oldRow?.acceptedAt).toBeNull();
- });
-
- test("throws for component IDs that do not belong to this page", async () => {
- await expect(
- upsertEmailSubscription({ email, pageId: PAGE_ID, componentIds: [9999] }),
- ).rejects.toThrow("Some components do not belong to this page");
- });
-
- test("throws for a page ID that does not exist", async () => {
- await expect(
- upsertEmailSubscription({ email, pageId: 99999 }),
- ).rejects.toThrow("Page not found");
- });
-});
-
-// ─── verifySubscription ───────────────────────────────────────────────────────
-
-describe("verifySubscription", () => {
- const email = EMAILS.verify;
- let pendingToken: string;
-
- beforeAll(async () => {
- await db.delete(pageSubscriber).where(eq(pageSubscriber.email, email));
- const sub = await upsertEmailSubscription({ email, pageId: PAGE_ID });
- if (!sub.token) {
- throw new Error("Token is undefined");
- }
- pendingToken = sub.token;
- });
-
- test("returns null for an unknown token", async () => {
- const result = await verifySubscription("non-existent-token-xyz");
- expect(result).toBeNull();
- });
-
- test("returns null when domain does not match page slug", async () => {
- const result = await verifySubscription(pendingToken, "wrong-domain");
- expect(result).toBeNull();
- });
-
- test("marks the subscription as accepted on first verification", async () => {
- const result = await verifySubscription(pendingToken, "status");
- expect(result).not.toBeNull();
- expect(result?.acceptedAt).toBeDefined();
- });
-
- test("returns an already-accepted subscription idempotently", async () => {
- // pendingToken now points to an accepted subscription from the previous test
- const result = await verifySubscription(pendingToken, "status");
- expect(result).not.toBeNull();
- expect(result?.acceptedAt).toBeDefined();
- });
-
- test("throws for a token with an expired expiresAt", async () => {
- const expiredEmail = EMAILS.verifyExpired;
- await db
- .delete(pageSubscriber)
- .where(eq(pageSubscriber.email, expiredEmail));
-
- await db
- .insert(pageSubscriber)
- .values({
- channelType: "email",
- email: expiredEmail,
- pageId: PAGE_ID,
- token: "expired-token-xyz",
- expiresAt: new Date(Date.now() - 1000), // 1 second in the past
- })
- .run();
-
- await expect(verifySubscription("expired-token-xyz")).rejects.toThrow(
- "Verification token expired",
- );
- });
-});
-
-// ─── getSubscriptionByToken ───────────────────────────────────────────────────
-
-describe("getSubscriptionByToken", () => {
- const email = EMAILS.getByToken;
- let token: string;
-
- beforeAll(async () => {
- await db.delete(pageSubscriber).where(eq(pageSubscriber.email, email));
- const sub = await upsertEmailSubscription({ email, pageId: PAGE_ID });
- if (!sub.token) {
- throw new Error("Token is undefined");
- }
- token = sub.token;
- });
-
- test("returns null for an unknown token", async () => {
- const result = await getSubscriptionByToken("unknown-token-xyz");
- expect(result).toBeNull();
- });
-
- test("returns null when domain does not match", async () => {
- const result = await getSubscriptionByToken(token, "wrong-domain");
- expect(result).toBeNull();
- });
-
- test('masks the email address as "x***@domain"', async () => {
- const result = await getSubscriptionByToken(token);
- expect(result).not.toBeNull();
- // "[email protected]" → "s***@example.com"
- expect(result?.email).toMatch(/^s\*\*\*@example\.com$/);
- expect(result?.email).not.toBe(email);
- });
-
- test("returns subscription data for a valid token and matching domain", async () => {
- const result = await getSubscriptionByToken(token, "status");
- expect(result).not.toBeNull();
- expect(result?.pageId).toBe(PAGE_ID);
- expect(result?.pageSlug).toBe("status");
- });
-});
-
-// ─── updateSubscriptionScope ──────────────────────────────────────────────────
-
-describe("updateSubscriptionScope", () => {
- const email = EMAILS.scope;
- let token: string;
-
- beforeAll(async () => {
- await db.delete(pageSubscriber).where(eq(pageSubscriber.email, email));
- const sub = await upsertEmailSubscription({
- email,
- pageId: PAGE_ID,
- componentIds: [COMPONENT_1],
- });
- if (!sub.token) {
- throw new Error("Token is undefined");
- }
- token = sub.token;
- // Verify so acceptedAt is set — required by the guard added to updateSubscriptionScope
- await verifySubscription(token);
- });
-
- test("throws for an unknown token", async () => {
- await expect(
- updateSubscriptionScope({ token: "unknown-token-xyz", componentIds: [] }),
- ).rejects.toThrow("Subscription not found");
- });
-
- test("throws when subscription is not yet verified", async () => {
- await db
- .delete(pageSubscriber)
- .where(eq(pageSubscriber.email, EMAILS.scopeUnverified));
- const sub = await upsertEmailSubscription({
- email: EMAILS.scopeUnverified,
- pageId: PAGE_ID,
- });
- if (!sub.token) throw new Error("Token is undefined");
-
- await expect(
- updateSubscriptionScope({ token: sub.token, componentIds: [] }),
- ).rejects.toThrow("Subscription not yet verified");
- });
-
- test("throws when subscription is unsubscribed", async () => {
- await db
- .delete(pageSubscriber)
- .where(eq(pageSubscriber.email, EMAILS.scopeUnsubbed));
- const sub = await upsertEmailSubscription({
- email: EMAILS.scopeUnsubbed,
- pageId: PAGE_ID,
- });
- if (!sub.token) throw new Error("Token is undefined");
- await verifySubscription(sub.token);
- await unsubscribe(sub.token);
-
- await expect(
- updateSubscriptionScope({ token: sub.token, componentIds: [] }),
- ).rejects.toThrow("Subscription is unsubscribed");
- });
-
- test("replaces existing component scope with new ones", async () => {
- const result = await updateSubscriptionScope({
- token,
- componentIds: [COMPONENT_2],
- });
-
- expect(result.componentIds).toEqual([COMPONENT_2]);
- expect(result.componentIds).not.toContain(COMPONENT_1);
- });
-
- test("can clear all components (switches to entire-page scope)", async () => {
- const result = await updateSubscriptionScope({ token, componentIds: [] });
- expect(result.componentIds).toEqual([]);
- });
-
- test("throws when a component does not belong to this page", async () => {
- await expect(
- updateSubscriptionScope({ token, componentIds: [9999] }),
- ).rejects.toThrow("Some components do not belong to this page");
- });
-});
-
-// ─── unsubscribe ──────────────────────────────────────────────────────────────
-
-describe("unsubscribe", () => {
- const email = EMAILS.unsub;
- let token: string;
-
- beforeAll(async () => {
- await db.delete(pageSubscriber).where(eq(pageSubscriber.email, email));
- const sub = await upsertEmailSubscription({ email, pageId: PAGE_ID });
- if (!sub.token) {
- throw new Error("Token is undefined");
- }
- token = sub.token;
- });
-
- test("throws for an unknown token", async () => {
- await expect(unsubscribe("unknown-token-xyz")).rejects.toThrow(
- "Subscription not found",
- );
- });
-
- test("throws when the domain does not match", async () => {
- await expect(unsubscribe(token, "wrong-domain")).rejects.toThrow(
- "Subscription not found",
- );
- });
-
- test("sets unsubscribedAt on a valid token", async () => {
- await expect(unsubscribe(token, "status")).resolves.toBeUndefined();
-
- const row = await db.query.pageSubscriber.findFirst({
- where: eq(pageSubscriber.token, token),
- });
- expect(row?.unsubscribedAt).toBeDefined();
- });
-
- test("resolves silently if the subscription is already unsubscribed", async () => {
- await expect(unsubscribe(token)).resolves.toBeUndefined();
- });
-});
diff --git a/packages/subscriptions/src/service.ts b/packages/subscriptions/src/service.ts
deleted file mode 100644
index d23e0dcfa..000000000
--- a/packages/subscriptions/src/service.ts
+++ /dev/null
@@ -1,825 +0,0 @@
-import { and, db, eq, inArray, isNull, ne, sql } from "@openstatus/db";
-import {
- page,
- pageComponent,
- pageSubscriber,
- pageSubscriberToPageComponent,
-} from "@openstatus/db/src/schema";
-import { assertSafeUrl } from "@openstatus/utils";
-import {
- detectWebhookFlavor,
- sendTestWebhookRequest,
-} from "./channels/webhook";
-
-/**
- * Subscription Service Layer
- * Handles all subscription CRUD operations
- */
-
-// Verification token expiry configuration
-const VERIFICATION_EXPIRY_DAYS = 7;
-const VERIFICATION_EXPIRY_MS = VERIFICATION_EXPIRY_DAYS * 24 * 60 * 60 * 1000;
-
-/**
- * Mask email address for privacy (e.g., "[email protected]" -> "j***@example.com")
- */
-function maskEmail(email: string): string {
- const [localPart, domain] = email.split("@");
- if (!domain) return email;
-
- const masked = localPart.length > 0 ? `${localPart[0]}***` : "***";
- return `${masked}@${domain}`;
-}
-
-function maskWebhookUrl(webhookUrl: string): string {
- const url = new URL(webhookUrl);
- return `${url.origin}***`;
-}
-
-interface UpsertEmailSubscriptionInput {
- email: string;
- pageId: number;
- componentIds?: number[]; // Empty = entire page
-}
-
-interface UpdateSubscriptionScopeInput {
- token: string;
- componentIds: number[]; // New scope (replaces current)
- domain?: string; // Optional domain validation
-}
-
-/**
- * Create or update email subscription (ADD behavior)
- *
- * - If no subscription exists (or only unsubscribed ones): creates new subscription
- * - If pending subscription exists: merges components and refreshes expiry
- * - If verified subscription exists: returns as-is (caller handles "already subscribed")
- */
-export async function upsertEmailSubscription(
- input: UpsertEmailSubscriptionInput,
-) {
- const { email, pageId, componentIds = [] } = input;
-
- const pageData = await db.query.page.findFirst({
- where: eq(page.id, pageId),
- });
-
- if (!pageData) {
- throw new Error("Page not found");
- }
-
- // Validate component IDs belong to this page
- if (componentIds.length > 0) {
- const validComponents = await db
- .select({ id: pageComponent.id })
- .from(pageComponent)
- .where(
- and(
- eq(pageComponent.pageId, pageId),
- inArray(pageComponent.id, componentIds),
- ),
- )
- .all();
-
- if (validComponents.length !== componentIds.length) {
- throw new Error("Some components do not belong to this page");
- }
- }
-
- // Check for active subscription
- const existing = await db.query.pageSubscriber.findFirst({
- where: and(
- eq(pageSubscriber.email, email.toLowerCase()),
- eq(pageSubscriber.pageId, pageId),
- eq(pageSubscriber.channelType, "email"),
- isNull(pageSubscriber.unsubscribedAt),
- ),
- with: {
- components: true,
- },
- });
-
- if (existing) {
- // Already verified — return as-is without merging components.
- // The caller (tRPC subscribe) will throw "Email already subscribed" on acceptedAt.
- if (existing.acceptedAt) {
- return {
- id: existing.id,
- pageId: existing.pageId,
- pageName: pageData.title,
- pageSlug: pageData.slug,
- customDomain: pageData.customDomain,
- channelType: existing.channelType,
- email: existing.email ?? undefined,
- token: existing.token,
- acceptedAt: existing.acceptedAt,
- componentIds: existing.components.map((c) => c.pageComponentId),
- };
- }
-
- // Pending — merge new components and refresh expiry
- const currentIds = existing.components.map((c) => c.pageComponentId);
- const mergedIds = [...new Set([...currentIds, ...componentIds])];
-
- const newIds = mergedIds.filter((id) => !currentIds.includes(id));
- if (newIds.length > 0) {
- await db
- .insert(pageSubscriberToPageComponent)
- .values(
- newIds.map((compId) => ({
- pageSubscriberId: existing.id,
- pageComponentId: compId,
- })),
- )
- .onConflictDoNothing()
- .run();
- }
-
- const newExpiresAt = new Date(Date.now() + VERIFICATION_EXPIRY_MS);
- await db
- .update(pageSubscriber)
- .set({ expiresAt: newExpiresAt, updatedAt: new Date() })
- .where(eq(pageSubscriber.id, existing.id))
- .run();
-
- return {
- id: existing.id,
- pageId: existing.pageId,
- pageName: pageData.title,
- pageSlug: pageData.slug,
- customDomain: pageData.customDomain,
- channelType: existing.channelType,
- email: existing.email ?? undefined,
- token: existing.token,
- acceptedAt: undefined,
- componentIds: mergedIds,
- };
- }
-
- // No existing subscription — create new one
- const token = crypto.randomUUID();
- const expiresAt = new Date(Date.now() + VERIFICATION_EXPIRY_MS);
-
- const subscription = await db.transaction(async (tx) => {
- const sub = await tx
- .insert(pageSubscriber)
- .values({
- channelType: "email",
- email: email.toLowerCase(),
- webhookUrl: null,
- pageId,
- token,
- expiresAt,
- })
- .returning()
- .get();
-
- if (componentIds.length > 0) {
- await tx
- .insert(pageSubscriberToPageComponent)
- .values(
- componentIds.map((compId) => ({
- pageSubscriberId: sub.id,
- pageComponentId: compId,
- })),
- )
- .run();
- }
-
- return sub;
- });
-
- return {
- id: subscription.id,
- pageId: subscription.pageId,
- pageName: pageData.title,
- pageSlug: pageData.slug,
- customDomain: pageData.customDomain,
- channelType: "email" as const,
- email: subscription.email ?? undefined,
- token: subscription.token,
- acceptedAt: subscription.acceptedAt ?? undefined,
- unsubscribedAt: subscription.unsubscribedAt ?? undefined,
- componentIds,
- };
-}
-
-/**
- * Verify a subscription by token
- */
-export async function verifySubscription(token: string, domain?: string) {
- const subscription = await db.query.pageSubscriber.findFirst({
- where: eq(pageSubscriber.token, token),
- with: {
- page: true,
- components: true,
- },
- });
-
- if (!subscription) {
- return null;
- }
-
- // Validate domain if provided
- if (domain) {
- const domainLower = domain.toLowerCase();
- const pageSlugLower = subscription.page.slug.toLowerCase();
- const customDomainLower = subscription.page.customDomain?.toLowerCase();
-
- if (domainLower !== pageSlugLower && domainLower !== customDomainLower) {
- return null;
- }
- }
-
- // Already accepted
- if (subscription.acceptedAt) {
- return {
- id: subscription.id,
- pageId: subscription.pageId,
- pageName: subscription.page.title,
- pageSlug: subscription.page.slug,
- customDomain: subscription.page.customDomain,
- channelType: subscription.channelType as "email" | "webhook",
- email: subscription.email ?? undefined,
- webhookUrl: subscription.webhookUrl ?? undefined,
- token: subscription.token,
- acceptedAt: subscription.acceptedAt ?? undefined,
- unsubscribedAt: subscription.unsubscribedAt ?? undefined,
- componentIds: subscription.components.map((c) => c.pageComponentId),
- };
- }
-
- // Check if expired
- if (subscription.expiresAt && subscription.expiresAt < new Date()) {
- throw new Error("Verification token expired");
- }
-
- // Mark as accepted
- const updated = await db
- .update(pageSubscriber)
- .set({ acceptedAt: new Date(), updatedAt: new Date() })
- .where(eq(pageSubscriber.id, subscription.id))
- .returning()
- .get();
-
- return {
- id: updated.id,
- pageId: updated.pageId,
- pageName: subscription.page.title,
- pageSlug: subscription.page.slug,
- customDomain: subscription.page.customDomain,
- channelType: updated.channelType as "email" | "webhook",
- email: updated.email ?? undefined,
- webhookUrl: updated.webhookUrl ?? undefined,
- token: updated.token,
- acceptedAt: updated.acceptedAt ?? undefined,
- componentIds: subscription.components.map((c) => c.pageComponentId),
- };
-}
-
-/**
- * Get subscription by token (for management UI)
- */
-export async function getSubscriptionByToken(token: string, domain?: string) {
- const subscription = await db.query.pageSubscriber.findFirst({
- where: eq(pageSubscriber.token, token),
- with: {
- page: true,
- components: true,
- },
- });
-
- if (!subscription) {
- return null;
- }
-
- if (domain) {
- const domainLower = domain.toLowerCase();
- const pageSlugLower = subscription.page.slug.toLowerCase();
- const customDomainLower = subscription.page.customDomain?.toLowerCase();
-
- if (domainLower !== pageSlugLower && domainLower !== customDomainLower) {
- return null;
- }
- }
-
- // Intentionally omitting webhookUrl/channelConfig — this is a public,
- // token-addressed endpoint and webhook URLs embed credential-bearing
- // paths that shouldn't leave the server.
- return {
- id: subscription.id,
- pageId: subscription.pageId,
- pageName: subscription.page.title,
- pageSlug: subscription.page.slug,
- customDomain: subscription.page.customDomain,
- channelType: subscription.channelType as "email" | "webhook",
- email: subscription.email ? maskEmail(subscription.email) : undefined,
- webhookUrl: subscription.webhookUrl
- ? maskWebhookUrl(subscription.webhookUrl)
- : undefined,
- acceptedAt: subscription.acceptedAt ?? undefined,
- unsubscribedAt: subscription.unsubscribedAt ?? undefined,
- componentIds: subscription.components.map((c) => c.pageComponentId),
- };
-}
-
-/**
- * Check whether an email already has a pending (unverified, unexpired) subscription for a page.
- * Used to prevent re-sending verification emails for already-pending subscriptions.
- */
-export async function hasPendingUnexpiredSubscription(
- email: string,
- pageId: number,
-): Promise<boolean> {
- const existing = await db.query.pageSubscriber.findFirst({
- where: and(
- eq(pageSubscriber.email, email.toLowerCase()),
- eq(pageSubscriber.pageId, pageId),
- eq(pageSubscriber.channelType, "email"),
- isNull(pageSubscriber.unsubscribedAt),
- isNull(pageSubscriber.acceptedAt),
- ),
- });
- return !!(existing?.expiresAt && existing.expiresAt > new Date());
-}
-
-/**
- * Update subscription scope (replace all components)
- */
-export async function updateSubscriptionScope(
- input: UpdateSubscriptionScopeInput,
-) {
- const { token, componentIds, domain } = input;
-
- const subscription = await db.query.pageSubscriber.findFirst({
- where: eq(pageSubscriber.token, token),
- with: {
- page: true,
- components: true,
- },
- });
-
- if (!subscription) {
- throw new Error("Subscription not found");
- }
-
- if (domain) {
- const domainLower = domain.toLowerCase();
- const pageSlugLower = subscription.page.slug.toLowerCase();
- const customDomainLower = subscription.page.customDomain?.toLowerCase();
-
- if (domainLower !== pageSlugLower && domainLower !== customDomainLower) {
- throw new Error("Subscription not found");
- }
- }
-
- if (!subscription.acceptedAt) {
- throw new Error("Subscription not yet verified");
- }
-
- if (subscription.unsubscribedAt) {
- throw new Error("Subscription is unsubscribed");
- }
-
- if (componentIds.length > 0) {
- const validComponents = await db
- .select({ id: pageComponent.id })
- .from(pageComponent)
- .where(
- and(
- eq(pageComponent.pageId, subscription.pageId),
- inArray(pageComponent.id, componentIds),
- ),
- )
- .all();
-
- if (validComponents.length !== componentIds.length) {
- throw new Error("Some components do not belong to this page");
- }
- }
-
- await db.transaction(async (tx) => {
- await tx
- .delete(pageSubscriberToPageComponent)
- .where(
- eq(pageSubscriberToPageComponent.pageSubscriberId, subscription.id),
- )
- .run();
-
- if (componentIds.length > 0) {
- await tx
- .insert(pageSubscriberToPageComponent)
- .values(
- componentIds.map((id) => ({
- pageSubscriberId: subscription.id,
- pageComponentId: id,
- })),
- )
- .run();
- }
-
- await tx
- .update(pageSubscriber)
- .set({ updatedAt: new Date() })
- .where(eq(pageSubscriber.id, subscription.id))
- .run();
- });
-
- return {
- id: subscription.id,
- pageId: subscription.pageId,
- pageName: subscription.page.title,
- pageSlug: subscription.page.slug,
- customDomain: subscription.page.customDomain,
- channelType: subscription.channelType as "email" | "webhook",
- email: subscription.email ?? undefined,
- token: subscription.token,
- acceptedAt: subscription.acceptedAt ?? undefined,
- componentIds,
- };
-}
-
-/**
- * Create a vendor-added subscription (channel-agnostic).
- *
- * Skips the verification flow: `source = "vendor"`, `acceptedAt`
- * stamped at creation, `expiresAt = null`. Token is still generated so the
- * partner can self-manage via the existing `/manage/{token}` and
- * `/unsubscribe/{token}` routes.
- */
-export type CreateSubscriptionInput =
- | {
- pageId: number;
- channelType: "email";
- email: string;
- name?: string | null;
- componentIds?: number[];
- }
- | {
- pageId: number;
- channelType: "webhook";
- webhookUrl: string;
- name?: string | null;
- channelConfig?: unknown;
- componentIds?: number[];
- };
-
-export async function createSubscription(input: CreateSubscriptionInput) {
- const { pageId, channelType, name, componentIds = [] } = input;
-
- const pageData = await db.query.page.findFirst({
- where: eq(page.id, pageId),
- });
-
- if (!pageData) {
- throw new Error("Page not found");
- }
-
- if (componentIds.length > 0) {
- const validComponents = await db
- .select({ id: pageComponent.id })
- .from(pageComponent)
- .where(
- and(
- eq(pageComponent.pageId, pageId),
- inArray(pageComponent.id, componentIds),
- ),
- )
- .all();
-
- if (validComponents.length !== componentIds.length) {
- throw new Error("Some components do not belong to this page");
- }
- }
-
- let emailLower: string | null = null;
- let webhookUrl: string | null = null;
- let channelConfig: string | null = null;
-
- if (channelType === "email") {
- emailLower = input.email.toLowerCase();
-
- const duplicate = await db.query.pageSubscriber.findFirst({
- where: and(
- eq(pageSubscriber.pageId, pageId),
- eq(pageSubscriber.email, emailLower),
- eq(pageSubscriber.channelType, "email"),
- isNull(pageSubscriber.unsubscribedAt),
- ),
- });
-
- if (duplicate) {
- throw new Error(
- "A subscriber with this email already exists for this page.",
- );
- }
- } else {
- webhookUrl = input.webhookUrl;
- await assertSafeUrl(webhookUrl);
-
- if (detectWebhookFlavor(webhookUrl) === "generic") {
- throw new Error("Only Slack and Discord webhook URLs are supported.");
- }
-
- const duplicate = await db.query.pageSubscriber.findFirst({
- where: and(
- eq(pageSubscriber.pageId, pageId),
- sql`LOWER(${pageSubscriber.webhookUrl}) = ${webhookUrl.toLowerCase()}`,
- eq(pageSubscriber.channelType, "webhook"),
- isNull(pageSubscriber.unsubscribedAt),
- ),
- });
-
- if (duplicate) {
- throw new Error(
- "A subscriber with this webhook URL already exists for this page.",
- );
- }
-
- channelConfig = input.channelConfig
- ? JSON.stringify(input.channelConfig)
- : null;
- }
-
- const token = crypto.randomUUID();
- const now = new Date();
-
- const subscription = await db.transaction(async (tx) => {
- const sub = await tx
- .insert(pageSubscriber)
- .values({
- channelType,
- email: emailLower,
- webhookUrl,
- channelConfig,
- pageId,
- source: "vendor",
- name: name ?? null,
- token,
- acceptedAt: now,
- expiresAt: null,
- })
- .returning()
- .get();
-
- if (componentIds.length > 0) {
- await tx
- .insert(pageSubscriberToPageComponent)
- .values(
- componentIds.map((compId) => ({
- pageSubscriberId: sub.id,
- pageComponentId: compId,
- })),
- )
- .run();
- }
-
- return sub;
- });
-
- return {
- id: subscription.id,
- pageId: subscription.pageId,
- channelType: subscription.channelType as "email" | "webhook",
- email: subscription.email ?? undefined,
- webhookUrl: subscription.webhookUrl ?? undefined,
- channelConfig: subscription.channelConfig ?? undefined,
- source: subscription.source as "self_signup" | "vendor",
- name: subscription.name ?? undefined,
- token: subscription.token,
- acceptedAt: subscription.acceptedAt ?? undefined,
- componentIds,
- };
-}
-
-/**
- * Update a vendor-added subscription's channel config, name, or component scope.
- *
- * Self-signup rows are subscriber-owned (managed via token) and rejected here.
- * Email rows reject `webhookUrl`/`channelConfig` (no webhook fields to edit).
- * Webhook rows accept URL/headers/name/scope. Email / webhook identity keys
- * (email, webhookUrl) are immutable on email rows; webhook URL is mutable.
- *
- * componentIds semantics:
- * - `undefined` → do not touch scope (existing component links preserved).
- * - `[]` → reset scope to "entire page" (all existing links removed).
- * - `[a, b, …]` → replace scope with exactly these components. All IDs must
- * belong to the target page or the update is rejected.
- */
-export type UpdateChannelInput = {
- subscriberId: number;
- pageId: number;
- name?: string | null;
- webhookUrl?: string;
- channelConfig?: unknown;
- componentIds?: number[];
-};
-
-export async function updateChannel(input: UpdateChannelInput) {
- const {
- subscriberId,
- pageId,
- name,
- webhookUrl,
- channelConfig,
- componentIds,
- } = input;
-
- const existing = await db.query.pageSubscriber.findFirst({
- where: and(
- eq(pageSubscriber.id, subscriberId),
- eq(pageSubscriber.pageId, pageId),
- ),
- });
-
- if (!existing) {
- throw new Error("Subscriber not found");
- }
-
- if (existing.source !== "vendor") {
- throw new Error(
- "Self-signup subscribers manage their own subscription; use the unsubscribe action instead.",
- );
- }
-
- if (existing.channelType === "email") {
- if (webhookUrl !== undefined || channelConfig !== undefined) {
- throw new Error("Email subscribers do not have webhook fields to edit.");
- }
- }
-
- const updateFields: Record<string, unknown> = { updatedAt: new Date() };
- if (name !== undefined) updateFields.name = name;
-
- if (existing.channelType === "webhook") {
- if (webhookUrl !== undefined && webhookUrl !== existing.webhookUrl) {
- await assertSafeUrl(webhookUrl);
- if (detectWebhookFlavor(webhookUrl) === "generic") {
- throw new Error("Only Slack and Discord webhook URLs are supported.");
- }
-
- const duplicate = await db.query.pageSubscriber.findFirst({
- where: and(
- eq(pageSubscriber.pageId, pageId),
- sql`LOWER(${pageSubscriber.webhookUrl}) = ${webhookUrl.toLowerCase()}`,
- eq(pageSubscriber.channelType, "webhook"),
- isNull(pageSubscriber.unsubscribedAt),
- ne(pageSubscriber.id, subscriberId),
- ),
- });
-
- if (duplicate) {
- throw new Error(
- "A subscriber with this webhook URL already exists for this page.",
- );
- }
-
- updateFields.webhookUrl = webhookUrl;
- }
- if (channelConfig !== undefined) {
- updateFields.channelConfig = channelConfig
- ? JSON.stringify(channelConfig)
- : null;
- }
- }
-
- if (componentIds !== undefined && componentIds.length > 0) {
- const validComponents = await db
- .select({ id: pageComponent.id })
- .from(pageComponent)
- .where(
- and(
- eq(pageComponent.pageId, pageId),
- inArray(pageComponent.id, componentIds),
- ),
- )
- .all();
-
- if (validComponents.length !== componentIds.length) {
- throw new Error("Some components do not belong to this page");
- }
- }
-
- await db.transaction(async (tx) => {
- await tx
- .update(pageSubscriber)
- .set(updateFields)
- .where(eq(pageSubscriber.id, subscriberId))
- .run();
-
- if (componentIds !== undefined) {
- await tx
- .delete(pageSubscriberToPageComponent)
- .where(eq(pageSubscriberToPageComponent.pageSubscriberId, subscriberId))
- .run();
-
- if (componentIds.length > 0) {
- await tx
- .insert(pageSubscriberToPageComponent)
- .values(
- componentIds.map((compId) => ({
- pageSubscriberId: subscriberId,
- pageComponentId: compId,
- })),
- )
- .run();
- }
- }
- });
-
- return { id: subscriberId };
-}
-
-/**
- * Send a test payload to a vendor-added webhook subscriber.
- * Shape is flavor-aware (Slack blocks / Discord embed / generic JSON).
- */
-export async function sendTestWebhook(subscriberId: number, pageId: number) {
- const existing = await db.query.pageSubscriber.findFirst({
- where: and(
- eq(pageSubscriber.id, subscriberId),
- eq(pageSubscriber.pageId, pageId),
- ),
- });
-
- if (!existing) {
- throw new Error("Subscriber not found");
- }
-
- if (existing.source !== "vendor") {
- throw new Error(
- "Only vendor-added webhook subscribers support test dispatch.",
- );
- }
-
- if (existing.channelType !== "webhook" || !existing.webhookUrl) {
- throw new Error("Subscriber is not a webhook channel");
- }
-
- if (existing.unsubscribedAt) {
- throw new Error("Subscriber is unsubscribed");
- }
-
- const flavor = detectWebhookFlavor(existing.webhookUrl);
- const headers = parseWebhookHeaders(existing.channelConfig);
-
- await sendTestWebhookRequest({
- url: existing.webhookUrl,
- flavor,
- headers,
- });
-}
-
-function parseWebhookHeaders(
- channelConfig: string | null,
-): Record<string, string> {
- if (!channelConfig) return {};
- try {
- const config = JSON.parse(channelConfig) as {
- headers?: { key: string; value: string }[];
- };
- const headers: Record<string, string> = {};
- for (const h of config.headers ?? []) {
- headers[h.key] = h.value;
- }
- return headers;
- } catch {
- return {};
- }
-}
-
-/**
- * Unsubscribe by token
- */
-export async function unsubscribe(token: string, domain?: string) {
- const subscription = await db.query.pageSubscriber.findFirst({
- where: eq(pageSubscriber.token, token),
- with: {
- page: true,
- },
- });
-
- if (!subscription) {
- throw new Error("Subscription not found");
- }
-
- if (domain) {
- const domainLower = domain.toLowerCase();
- const pageSlugLower = subscription.page.slug.toLowerCase();
- const customDomainLower = subscription.page.customDomain?.toLowerCase();
-
- if (domainLower !== pageSlugLower && domainLower !== customDomainLower) {
- throw new Error("Subscription not found");
- }
- }
-
- if (subscription.unsubscribedAt) {
- return;
- }
-
- await db
- .update(pageSubscriber)
- .set({ unsubscribedAt: new Date(), updatedAt: new Date() })
- .where(eq(pageSubscriber.id, subscription.id))
- .run();
-}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 420202706..19cac92e5 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -725,7 +725,7 @@ importers:
next-intl:
specifier: ^4.8.3
next-plausible:
specifier: 3.12.5
@@ -2047,6 +2047,9 @@ importers:
'@openstatus/theme-store':
specifier: workspace:*
version: link:../theme-store
+ '@openstatus/utils':
+ specifier: workspace:*
+ version: link:../utils
zod:
specifier: 4.1.13
version: 4.1.13
@@ -21682,7 +21685,7 @@ snapshots:
dependencies:
'@formatjs/intl-localematcher': 0.8.1
'@parcel/watcher': 2.5.1