Open-source status page, incident response and uptime monitoring
TypeScript alertingincident-managementmcpmcp-servermonitoringmonitoring-as-codeobservabilityon-callopen-sourcesrestatus-pagestatuspagesynthetic-monitoringterraformtinybirdtursouptimeuptime-checkeruptime-monitor
feat: services audit-logs (#2118)
Maximilian Kaske19226c7b7d42
diff --git a/CLAUDE.md b/CLAUDE.mdindex bf4be0c3b..c37fce5ec 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -104,3 +104,23 @@ pnpm test- **Linting and Formatting:** The project uses Biome for linting and formatting. The configuration can be found in the `biome.jsonc` file.- **Code Generation:** The project uses `drizzle-kit` for database schema migrations.- **API:** The backend API is built using Hono and tRPC. The API is documented using OpenAPI.++## Services & Audit Log Pattern++All workspace-scoped business logic lives in `packages/services` — **not** in tRPC routers. Routers stay thin: validate input, call a service verb, map errors. This keeps logic reusable across tRPC, Hono, and background jobs, and keeps it Edge-safe (the dashboard runs tRPC on Next.js Edge, so service code must avoid `node:*` imports).++Conventions for any new mutation:++- **One file per verb** under `packages/services/src/<entity>/` (e.g. `create.ts`, `update.ts`, `remove.ts`), re-exported from the entity's `index.ts`. Routers import from `@openstatus/services/<entity>`.+- **Standard signature:** `async function verbEntity(args: { ctx: ServiceContext; input: VerbInput }): Promise<...>`. `ctx` carries `workspace`, `actor`, and an optional `db`/transaction. Parse input with the schema at the top of the function.+- **Wrap mutations in `withTransaction(ctx, async (tx) => { ... })`** — it reuses an outer tx if present, otherwise opens one. Always pass `tx` (not `defaultDb`) to writes inside the block.+- **Workspace scoping is mandatory.** Every read/write filters by `ctx.workspace.id`. Use the `getXInWorkspace` helpers in `internal.ts` for fetch-or-throw.+- **Throw `ServiceError` subclasses** (`NotFoundError`, `ForbiddenError`, etc. from `./errors`). Routers convert them via `toTRPCError`.+- **Emit an audit row for every mutation** via `emitAudit(tx, ctx, entry)` inside the same transaction. Fail-closed: a failed audit insert rolls back the mutation. See `packages/services/src/audit/emit.ts`.+ - For updates, pass both `before` (pre-mutation snapshot) and `after` (post-`.returning()` row). `changed_fields` is auto-diffed; no-op updates are skipped.+ - For creates/deletes, pass only `after` or only `before`.+ - **Strip secrets** from snapshots before emitting (e.g. `credential`, bot tokens, raw API keys) — see `integration/remove.ts` for the pattern.+ - Action names follow `{entity}.{verb}` (`monitor.update`, `integration.delete`). Add new variants to the discriminated union in `@openstatus/db/src/schema/audit_logs/validation.ts`.+- **Tests live in `packages/services/src/<entity>/__tests__/`** and use `expectAuditRow({ workspaceId, action, entityId, ... })` from `packages/services/test/helpers.ts` to assert the audit side-effect. Each suite scopes to its own workspace and clears `audit_log` between cases.++When adding a router endpoint, the default answer is "write the service verb first, then call it from the router." Inline DB access in routers is a smell — it bypasses the audit log and the Edge-safety guarantee.diff --git a/apps/dashboard/src/app/(dashboard)/audit-logs/breadcrumb.tsx b/apps/dashboard/src/app/(dashboard)/audit-logs/breadcrumb.tsxnew file mode 100644index 000000000..e5d2e4179--- /dev/null+++ b/apps/dashboard/src/app/(dashboard)/audit-logs/breadcrumb.tsx@@ -0,0 +1,12 @@+"use client";++import { NavBreadcrumb } from "@/components/nav/nav-breadcrumb";+import { ScanEye } from "lucide-react";++export function Breadcrumb() {+ return (+ <NavBreadcrumb+ items={[{ type: "page", label: "Audit Logs", icon: ScanEye }]}+ />+ );+}diff --git a/apps/dashboard/src/app/(dashboard)/audit-logs/client.tsx b/apps/dashboard/src/app/(dashboard)/audit-logs/client.tsxnew file mode 100644index 000000000..f491a95f7--- /dev/null+++ b/apps/dashboard/src/app/(dashboard)/audit-logs/client.tsx@@ -0,0 +1,176 @@+"use client";++import { Link } from "@/components/common/link";+import {+ BillingOverlay,+ BillingOverlayButton,+ BillingOverlayContainer,+ BillingOverlayDescription,+} from "@/components/content/billing-overlay";+import {+ EmptyStateContainer,+ EmptyStateDescription,+ EmptyStateTitle,+} from "@/components/content/empty-state";+import {+ Section,+ SectionDescription,+ SectionGroup,+ SectionHeader,+ SectionTitle,+} 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 { UpgradeDialog } from "@/components/dialogs/upgrade";+import { DataTable } from "@/components/ui/data-table/data-table";+import { DataTablePaginationSimple } from "@/components/ui/data-table/data-table-pagination";+import { useTRPC } from "@/lib/trpc/client";+import type { RouterOutputs } from "@openstatus/api";+import { useQuery } from "@tanstack/react-query";+import { Lock } from "lucide-react";+import { useState } from "react";++type AuditLog = RouterOutputs["auditLog"]["list"]["items"][number];++const EXAMPLES = [+ {+ id: 1,+ workspaceId: 1,+ actorType: "user",+ actorId: "42",+ actorUserId: 42,+ action: "monitor.update",+ entityType: "monitor",+ entityId: "101",+ before: null,+ after: null,+ metadata: null,+ changedFields: ["name", "url"],+ createdAt: new Date("2026-04-24T10:00:00Z"),+ user: {+ id: 42,+ name: "Max Kaske",+ email: "[email protected]",+ photoUrl: null,+ },+ },+ {+ id: 2,+ workspaceId: 1,+ actorType: "user",+ actorId: "42",+ actorUserId: 42,+ action: "page.create",+ entityType: "page",+ entityId: "7",+ before: null,+ after: null,+ metadata: null,+ changedFields: null,+ createdAt: new Date("2026-04-23T16:30:00Z"),+ user: {+ id: 42,+ name: "Max Kaske",+ email: "[email protected]",+ photoUrl: null,+ },+ },+ {+ id: 3,+ workspaceId: 1,+ actorType: "apiKey",+ actorId: "k_abc123",+ actorUserId: null,+ action: "notification.delete",+ entityType: "notification",+ 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,+ },+ },+] satisfies AuditLog[];++export function Client() {+ const trpc = useTRPC();+ const [openDialog, setOpenDialog] = useState(false);+ const { data: workspace } = useQuery(trpc.workspace.get.queryOptions());+ const { data: auditLogs } = useQuery(trpc.auditLog.list.queryOptions({}));++ if (!workspace) return null;++ const isLimited = workspace.limits["audit-log"] === false;++ return (+ <SectionGroup>+ <SectionHeader>+ <SectionTitle>Audit Logs</SectionTitle>+ <SectionDescription>+ Track mutating actions taken against your workspace from the last 14+ days.+ </SectionDescription>+ </SectionHeader>+ <Section>+ {isLimited ? (+ <BillingOverlayContainer>+ <DataTable+ columns={columns}+ data={[...EXAMPLES, ...EXAMPLES, ...EXAMPLES]}+ rowComponent={({ row }) => (+ <DataTableRowDetails row={row.original} />+ )}+ />+ <BillingOverlay>+ <BillingOverlayButton onClick={() => setOpenDialog(true)}>+ <Lock />+ Upgrade+ </BillingOverlayButton>+ <BillingOverlayDescription>+ Keep a verifiable history of every change in your workspace.{" "}+ <Link+ href="https://docs.openstatus.dev/"+ rel="noreferrer"+ target="_blank"+ >+ Learn more+ </Link>+ .+ </BillingOverlayDescription>+ </BillingOverlay>+ <UpgradeDialog+ open={openDialog}+ onOpenChange={setOpenDialog}+ limit="audit-log"+ />+ </BillingOverlayContainer>+ ) : auditLogs?.items.length ? (+ <DataTable+ columns={columns}+ data={auditLogs.items}+ onRowClick={(row) =>+ row.getCanExpand() ? row.toggleExpanded() : undefined+ }+ rowComponent={({ row }) => (+ <DataTableRowDetails row={row.original} />+ )}+ paginationComponent={DataTablePaginationSimple}+ />+ ) : (+ <EmptyStateContainer>+ <EmptyStateTitle>No audit logs</EmptyStateTitle>+ <EmptyStateDescription>+ Actions taken in this workspace will appear here.+ </EmptyStateDescription>+ </EmptyStateContainer>+ )}+ </Section>+ </SectionGroup>+ );+}diff --git a/apps/dashboard/src/app/(dashboard)/audit-logs/layout.tsx b/apps/dashboard/src/app/(dashboard)/audit-logs/layout.tsxnew file mode 100644index 000000000..d4a94ac8f--- /dev/null+++ b/apps/dashboard/src/app/(dashboard)/audit-logs/layout.tsx@@ -0,0 +1,32 @@+import {+ AppHeader,+ AppHeaderActions,+ AppHeaderContent,+} from "@/components/nav/app-header";+import { AppSidebarTrigger } from "@/components/nav/app-sidebar";+import { HydrateClient, getQueryClient, trpc } from "@/lib/trpc/server";+import { Breadcrumb } from "./breadcrumb";+import { NavActions } from "./nav-actions";++export default async function Layout({+ children,+}: {+ children: React.ReactNode;+}) {+ const queryClient = getQueryClient();+ await queryClient.prefetchQuery(trpc.auditLog.list.queryOptions({}));+ return (+ <HydrateClient>+ <AppHeader>+ <AppHeaderContent>+ <AppSidebarTrigger />+ <Breadcrumb />+ </AppHeaderContent>+ <AppHeaderActions>+ <NavActions />+ </AppHeaderActions>+ </AppHeader>+ <main className="w-full flex-1">{children}</main>+ </HydrateClient>+ );+}diff --git a/apps/dashboard/src/app/(dashboard)/audit-logs/nav-actions.tsx b/apps/dashboard/src/app/(dashboard)/audit-logs/nav-actions.tsxnew file mode 100644index 000000000..768c5c97f--- /dev/null+++ b/apps/dashboard/src/app/(dashboard)/audit-logs/nav-actions.tsx@@ -0,0 +1,9 @@+import { NavFeedback } from "@/components/nav/nav-feedback";++export function NavActions() {+ return (+ <div className="flex items-center gap-2 text-sm">+ <NavFeedback />+ </div>+ );+}diff --git a/apps/dashboard/src/app/(dashboard)/audit-logs/page.tsx b/apps/dashboard/src/app/(dashboard)/audit-logs/page.tsxnew file mode 100644index 000000000..e3dc7ede6--- /dev/null+++ b/apps/dashboard/src/app/(dashboard)/audit-logs/page.tsx@@ -0,0 +1,5 @@+import { Client } from "./client";++export default function Page() {+ return <Client />;+}diff --git a/apps/dashboard/src/components/common/copy-row.tsx b/apps/dashboard/src/components/common/copy-row.tsxnew file mode 100644index 000000000..8b23829a7--- /dev/null+++ b/apps/dashboard/src/components/common/copy-row.tsx@@ -0,0 +1,42 @@+"use client";++import { cn } from "@/lib/utils";+import { useCopyToClipboard } from "@openstatus/ui/hooks/use-copy-to-clipboard";+import { Check, Copy } from "lucide-react";++export function CopyRow({+ label,+ value,+ className,+}: {+ label: string;+ value: string;+ className?: string;+}) {+ const { copy, isCopied } = useCopyToClipboard();++ return (+ <div+ className={cn(+ "group flex items-center justify-between gap-4 text-sm",+ className,+ )}+ onClick={(e) => {+ e.stopPropagation();+ copy(value, {});+ }}+ >+ <dt className="text-muted-foreground">{label}</dt>+ <dd className="flex items-center gap-1 truncate font-mono">+ <span className="invisible group-hover:visible">+ {!isCopied ? (+ <Copy className="h-3 w-3" />+ ) : (+ <Check className="h-3 w-3" />+ )}+ </span>+ <span className="truncate">{value}</span>+ </dd>+ </div>+ );+}diff --git a/apps/dashboard/src/components/common/hover-card-timestamp.tsx b/apps/dashboard/src/components/common/hover-card-timestamp.tsxindex d538cf66b..ac0cf15e4 100644--- a/apps/dashboard/src/components/common/hover-card-timestamp.tsx+++ b/apps/dashboard/src/components/common/hover-card-timestamp.tsx@@ -6,11 +6,9 @@ import {HoverCardContent,HoverCardTrigger,} from "@openstatus/ui/components/ui/hover-card";-import { useCopyToClipboard } from "@openstatus/ui/hooks/use-copy-to-clipboard";import { format, formatDistanceToNowStrict } from "date-fns";-import { Copy } from "lucide-react";-import { Check } from "lucide-react";import type { ComponentPropsWithoutRef } from "react";+import { CopyRow } from "./copy-row";// TODO: move to TableCellDate?@@ -43,13 +41,16 @@ export function HoverCardTimestamp({{...{ side, align, alignOffset, sideOffset }}><dl className="flex flex-col gap-1">- <Row value={String(date.getTime())} label="Timestamp" />- <Row+ <CopyRow value={String(date.getTime())} label="Timestamp" />+ <CopyRowvalue={format(new UTCDate(date), "LLL dd, y HH:mm:ss")}label="UTC"/>- <Row value={format(date, "LLL dd, y HH:mm:ss")} label={timezone} />- <Row+ <CopyRow+ value={format(date, "LLL dd, y HH:mm:ss")}+ label={timezone}+ />+ <CopyRowvalue={formatDistanceToNowStrict(date, { addSuffix: true })}label="Relative"/>@@ -58,29 +59,3 @@ export function HoverCardTimestamp({</HoverCard>);}--function Row({ value, label }: { value: string; label: string }) {- const { copy, isCopied } = useCopyToClipboard();-- return (- <div- className="group flex items-center justify-between gap-4 text-sm"- onClick={(e) => {- e.stopPropagation();- copy(value, {});- }}- >- <dt className="text-muted-foreground">{label}</dt>- <dd className="flex items-center gap-1 truncate font-mono">- <span className="invisible group-hover:visible">- {!isCopied ? (- <Copy className="h-3 w-3" />- ) : (- <Check className="h-3 w-3" />- )}- </span>- {value}- </dd>- </div>- );-}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.tsxnew file mode 100644index 000000000..6269e7239--- /dev/null+++ b/apps/dashboard/src/components/data-table/audit-logs-workspace/columns.tsx@@ -0,0 +1,106 @@+"use client";++import { cn } from "@/lib/utils";+import type { RouterOutputs } from "@openstatus/api";+import {+ Avatar,+ AvatarFallback,+ AvatarImage,+} from "@openstatus/ui/components/ui/avatar";+import { Badge } from "@openstatus/ui/components/ui/badge";+import type { ColumnDef } from "@tanstack/react-table";+import { TableCellDate } from "../table-cell-date";++type AuditLog = RouterOutputs["auditLog"]["list"]["items"][number];++/**+ * djb2 — tiny deterministic string hash. Used to derive a stable avatar+ * seed from the user's email without shipping the email itself to+ * dicebear's URL. Not cryptographic (nothing about the avatar needs to+ * be secret), just non-leaking: the third-party service receives an+ * opaque slug, not a workspace member's address.+ */+function hashEmailSeed(email: string): string {+ let hash = 5381;+ for (let i = 0; i < email.length; i++) {+ hash = (hash * 33) ^ email.charCodeAt(i);+ }+ return (hash >>> 0).toString(36);+}++function getActionBadgeColor(action: string) {+ if (action.endsWith(".create"))+ return "bg-success/10 text-success border-success/20";+ if (action.endsWith(".update")) return "bg-info/10 text-info border-info/20";+ if (action.endsWith(".delete"))+ return "bg-destructive/10 text-destructive border-destructive/20";+ return "bg-muted/10 text-muted-foreground border-muted/20";+}++export const columns: ColumnDef<AuditLog>[] = [+ {+ accessorKey: "user",+ header: "Actor",+ enableSorting: false,+ enableHiding: false,+ cell: ({ row }) => {+ const user = row.original.user;+ if (!user) return <span className="text-muted-foreground">-</span>;+ const imgSrc =+ user.photoUrl ||+ // Seed with a hash of the email — dicebear logs request+ // URLs, so shipping raw emails as query params would+ // leak workspace member PII to a third party on every+ // audit-log render. Hashing keeps the avatar stable per+ // user without exposing the address.+ `https://api.dicebear.com/9.x/glass/svg?seed=${user.email ? hashEmailSeed(user.email) : user.id}`;+ return (+ <div className="flex items-center gap-2">+ <Avatar className="size-6 rounded-md">+ <AvatarImage src={imgSrc} />+ <AvatarFallback className="rounded-lg uppercase">+ {user?.name?.slice(0, 2)}+ </AvatarFallback>+ </Avatar>+ <span className="truncate font-commit-mono text-xs tracking-tight">+ {user.name ?? user.email ?? "—"}+ </span>+ </div>+ );+ },+ meta: {+ cellClassName: "max-w-[200px] truncate max-w-auto",+ },+ },+ {+ accessorKey: "action",+ header: "Action",+ enableSorting: false,+ enableHiding: false,+ cell: ({ row }) => {+ const value = row.getValue("action") as string;+ return (+ <Badge+ variant="outline"+ className={cn("font-mono text-xs", getActionBadgeColor(value))}+ >+ {value}+ </Badge>+ );+ },+ },+ {+ accessorKey: "createdAt",+ header: "Timestamp",+ enableSorting: false,+ enableHiding: false,+ cell: ({ row }) => {+ const value = row.getValue("createdAt");+ return <TableCellDate value={value} className="font-mono" />;+ },+ meta: {+ headerClassName: "text-right",+ cellClassName: "text-right",+ },+ },+];diff --git a/apps/dashboard/src/components/data-table/audit-logs-workspace/data-table-row-details.tsx b/apps/dashboard/src/components/data-table/audit-logs-workspace/data-table-row-details.tsxnew file mode 100644index 000000000..2b00a76e3--- /dev/null+++ b/apps/dashboard/src/components/data-table/audit-logs-workspace/data-table-row-details.tsx@@ -0,0 +1,175 @@+"use client";++import { CopyRow } from "@/components/common/copy-row";+import { cn } from "@/lib/utils";+import type { RouterOutputs } from "@openstatus/api";++type AuditLog = RouterOutputs["auditLog"]["list"]["items"][number];++type ChangeRow = {+ field: string;+ before?: unknown;+ after?: unknown;+};++/**+ * Fields we never surface in the CHANGES view.+ *+ * `createdAt`/`updatedAt`/`deletedAt` are churny bookkeeping — already+ * filtered from `changedFields` by `diffTopLevel` in the services+ * package, but they still show up on create/delete snapshots.+ *+ * `workspaceId` is implied by the workspace scope of the audit log+ * itself — noise, not signal.+ *+ * `id` stays visible: with per-entity audit rows, the entity id tells+ * the reader *which* component / group / monitor this row refers to.+ *+ * This is a display-side belt-and-braces only. Proper secret/PII+ * redaction (webhook URLs with tokens, hashed api keys, etc.) is the+ * server-side redaction PR's job — don't treat this list as a security+ * boundary.+ */+const HIDDEN_FIELDS = new Set([+ "workspaceId",+ "createdAt",+ "updatedAt",+ "deletedAt",+]);++/**+ * Build a field-level diff from `before`/`after`/`changedFields`.+ *+ * - update: both snapshots present → only rows for keys in `changedFields`.+ * - create: only `after` present → every top-level key as an addition.+ * - delete: only `before` present → every top-level key as a removal.+ *+ * Returns an empty array when there's nothing structured to show (e.g. a+ * metadata-only action emitted without snapshots).+ */+function buildChanges(row: AuditLog): ChangeRow[] {+ const { before, after, changedFields } = row;++ if (before && after) {+ if (!changedFields?.length) return [];+ return changedFields+ .filter((field) => !HIDDEN_FIELDS.has(field))+ .map((field) => ({+ field,+ before: (before as Record<string, unknown>)[field],+ after: (after as Record<string, unknown>)[field],+ }));+ }++ if (after) {+ return Object.keys(after)+ .filter((field) => !HIDDEN_FIELDS.has(field))+ .map((field) => ({+ field,+ after: (after as Record<string, unknown>)[field],+ }));+ }++ if (before) {+ return Object.keys(before)+ .filter((field) => !HIDDEN_FIELDS.has(field))+ .map((field) => ({+ field,+ before: (before as Record<string, unknown>)[field],+ }));+ }++ return [];+}++function formatValue(value: unknown): string {+ if (value === null || value === undefined) return "—";+ if (value instanceof Date) return value.toISOString();+ if (typeof value === "string") return value === "" ? "—" : value;+ if (typeof value === "number" || typeof value === "boolean") {+ return String(value);+ }+ if (Array.isArray(value) && value.length === 0) return "—";+ return JSON.stringify(value);+}++export function DataTableRowDetails({ row }: { row: AuditLog }) {+ const changes = buildChanges(row);++ return (+ <div className="bg-muted/30 p-4">+ {changes.length ? (+ <div className="grid grid-cols-1 gap-4 md:grid-cols-3">+ <div className="col-span-2 flex flex-col gap-2">+ <div className="font-medium text-muted-foreground text-xs uppercase tracking-wider">+ Changes+ </div>+ <div className="overflow-hidden rounded-md border bg-background text-sm">+ {changes.map((change, idx) => (+ <div+ key={change.field}+ className={cn(+ "grid grid-cols-1 md:grid-cols-4",+ idx > 0 && "border-t",+ )}+ >+ <div className="truncate border-r bg-muted/40 px-3 py-2 font-mono text-muted-foreground md:col-span-1">+ {change.field}+ </div>+ <div className="grid truncate md:col-span-3">+ {"before" in change ? (+ <DiffLine kind="removed" value={change.before} />+ ) : null}+ {"after" in change ? (+ <DiffLine kind="added" value={change.after} />+ ) : null}+ </div>+ </div>+ ))}+ </div>+ </div>+ <div className="flex flex-col gap-2">+ <div className="font-medium text-muted-foreground text-xs uppercase tracking-wider">+ Entry+ </div>+ <dl className="flex flex-col gap-1.5">+ <CopyRow label="Entity Type" value={row.entityType} />+ <CopyRow label="Entity ID" value={row.entityId} />+ <CopyRow label="Actor Type" value={row.actorType} />+ <CopyRow label="Actor ID" value={row.actorId} />+ {row.user?.name ? (+ <CopyRow label="User Name" value={row.user.name} />+ ) : null}+ {row.user?.email ? (+ <CopyRow label="User Email" value={row.user.email} />+ ) : null}+ </dl>+ </div>+ </div>+ ) : null}+ </div>+ );+}++function DiffLine({+ kind,+ value,+}: {+ kind: "added" | "removed";+ value: unknown;+}) {+ const sign = kind === "added" ? "+" : "-";+ return (+ <div+ className="group flex items-start gap-2 px-3 py-2 font-mono has-[+[data-kind=added]]:pb-0"+ data-kind={kind}+ >+ <span className="select-none text-muted-foreground group-data-[kind=added]:text-success group-data-[kind=removed]:text-destructive">+ {sign}+ </span>+ <span className="whitespace-pre-wrap break-all group-data-[kind=added]:text-foreground group-data-[kind=removed]:text-muted-foreground group-data-[kind=removed]:line-through">+ {formatValue(value)}+ </span>+ </div>+ );+}diff --git a/apps/dashboard/src/components/forms/components/update.tsx b/apps/dashboard/src/components/forms/components/update.tsxindex 2055371b5..9bdc6f5a4 100644--- a/apps/dashboard/src/components/forms/components/update.tsx+++ b/apps/dashboard/src/components/forms/components/update.tsx@@ -27,9 +27,15 @@ export function FormComponentsUpdate() {const updateComponentsMutation = useMutation(trpc.pageComponent.updateOrder.mutationOptions({- onSuccess: () => {- refetch();- refetchComponents();+ onSuccess: async () => {+ // Remount the form after save. Newly-added components/groups get+ // `Date.now()` placeholder ids (see `form-components.tsx`). The+ // server returns real ids, but RHF only reads `defaultValues` on+ // mount — without a remount the next save would round-trip the+ // placeholders, causing the server's diff to treat real rows as+ // "removed" (delete) and placeholders as "new" (create).+ await Promise.all([refetch(), refetchComponents()]);+ setFormKey((k) => k + 1);},}),);@@ -109,7 +115,7 @@ export function FormComponentsUpdate() {await updateComponentsMutation.mutateAsync({pageId: Number.parseInt(id),components: values.components,- groups: values.groups.map(({ id: _groupId, ...rest }) => rest),+ groups: values.groups,});}}/>diff --git a/apps/dashboard/src/components/nav/app-sidebar.tsx b/apps/dashboard/src/components/nav/app-sidebar.tsxindex 01f108ad1..c404b6c78 100644--- a/apps/dashboard/src/components/nav/app-sidebar.tsx+++ b/apps/dashboard/src/components/nav/app-sidebar.tsx@@ -8,6 +8,7 @@ import {Globe,LayoutGrid,PanelTop,+ ScanEye,Terminal,} from "lucide-react";import * as React from "react";@@ -76,6 +77,11 @@ const data = {url: "/private-locations",icon: Globe,},+ {+ name: "Audit Logs",+ url: "/audit-logs",+ icon: ScanEye,+ },{name: "Agents",url: "/agents",diff --git a/apps/dashboard/src/data/plans.ts b/apps/dashboard/src/data/plans.tsindex 2c707ae47..1a6f99a42 100644--- a/apps/dashboard/src/data/plans.ts+++ b/apps/dashboard/src/data/plans.ts@@ -141,7 +141,6 @@ export const config: Record<{value: "audit-log",label: "Audit log",- badge: "Planned",},],},diff --git a/apps/web/src/content/pages/unrelated/pricing.mdx b/apps/web/src/content/pages/unrelated/pricing.mdxindex 6dbdee4a8..cf7f6a4a2 100644--- a/apps/web/src/content/pages/unrelated/pricing.mdx+++ b/apps/web/src/content/pages/unrelated/pricing.mdx@@ -60,6 +60,7 @@ faq:| Number of notification channels | 1 | 10 | 20 || **Collaboration** | | | || Team members | 1 | Unlimited | Unlimited |+| Audit log | | | + |All paid plans are available with **monthly** or **annual** billing. Choose annual billing to get **2 months free** — that's Starter at $300/year ($25/mo) and Pro at $1,000/year (~$83/mo).diff --git a/packages/api/src/edge.ts b/packages/api/src/edge.tsindex 753dbf84b..5acebe3d9 100644--- a/packages/api/src/edge.ts+++ b/packages/api/src/edge.ts@@ -1,3 +1,4 @@+import { auditLogRouter } from "./router/auditLog";import { checkerRouter } from "./router/checker";import { domainRouter } from "./router/domain";import { feedbackRouter } from "./router/feedback";@@ -42,4 +43,5 @@ export const edgeRouter = createTRPCRouter({statusPage: statusPageRouter,privateLocation: privateLocationRouter,import: importRouter,+ auditLog: auditLogRouter,});diff --git a/packages/api/src/router/auditLog.ts b/packages/api/src/router/auditLog.tsnew file mode 100644index 000000000..d76cfdcf3--- /dev/null+++ b/packages/api/src/router/auditLog.ts@@ -0,0 +1,12 @@+import { ListAuditLogsInput, listAuditLogs } from "@openstatus/services/audit";++import { toServiceCtx } from "../service-adapter";+import { createTRPCRouter, protectedProcedure } from "../trpc";++export const auditLogRouter = createTRPCRouter({+ list: protectedProcedure+ .input(ListAuditLogsInput)+ .query(async ({ ctx, input }) =>+ listAuditLogs({ ctx: toServiceCtx(ctx), input }),+ ),+});diff --git a/packages/db/drizzle/0065_stiff_hiroim.sql b/packages/db/drizzle/0065_stiff_hiroim.sqlnew file mode 100644index 000000000..2ac7f5d70--- /dev/null+++ b/packages/db/drizzle/0065_stiff_hiroim.sql@@ -0,0 +1,18 @@+CREATE TABLE `audit_log` (+ `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,+ `workspace_id` integer NOT NULL,+ `actor_type` text NOT NULL,+ `actor_id` text NOT NULL,+ `actor_user_id` integer,+ `action` text NOT NULL,+ `entity_type` text NOT NULL,+ `entity_id` text NOT NULL,+ `before` text,+ `after` text,+ `metadata` text,+ `changed_fields` text,+ `created_at` integer NOT NULL+);+--> statement-breakpoint+CREATE INDEX `audit_log_workspace_created_idx` ON `audit_log` (`workspace_id`,`created_at`);--> statement-breakpoint+CREATE INDEX `audit_log_entity_idx` ON `audit_log` (`workspace_id`,`entity_type`,`entity_id`,`created_at`);\ No newline at end of filediff --git a/packages/db/drizzle/meta/0065_snapshot.json b/packages/db/drizzle/meta/0065_snapshot.jsonnew file mode 100644index 000000000..e611960c0--- /dev/null+++ b/packages/db/drizzle/meta/0065_snapshot.json@@ -0,0 +1,3638 @@+{+ "version": "6",+ "dialect": "sqlite",+ "id": "084142ea-4cb4-497c-a08a-140f2dd5942e",+ "prevId": "d778c674-ca9a-4b20-8d38-a262f28d922c",+ "tables": {+ "workspace": {+ "name": "workspace",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "slug": {+ "name": "slug",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "stripe_id": {+ "name": "stripe_id",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "subscription_id": {+ "name": "subscription_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "plan": {+ "name": "plan",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "ends_at": {+ "name": "ends_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "paid_until": {+ "name": "paid_until",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "limits": {+ "name": "limits",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'{}'"+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "dsn": {+ "name": "dsn",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "workspace_slug_unique": {+ "name": "workspace_slug_unique",+ "columns": [+ "slug"+ ],+ "isUnique": true+ },+ "workspace_stripe_id_unique": {+ "name": "workspace_stripe_id_unique",+ "columns": [+ "stripe_id"+ ],+ "isUnique": true+ },+ "workspace_id_dsn_unique": {+ "name": "workspace_id_dsn_unique",+ "columns": [+ "id",+ "dsn"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "account": {+ "name": "account",+ "columns": {+ "user_id": {+ "name": "user_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "provider_account_id": {+ "name": "provider_account_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "refresh_token": {+ "name": "refresh_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "access_token": {+ "name": "access_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "token_type": {+ "name": "token_type",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "scope": {+ "name": "scope",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "id_token": {+ "name": "id_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "session_state": {+ "name": "session_state",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "account_user_id_user_id_fk": {+ "name": "account_user_id_user_id_fk",+ "tableFrom": "account",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "account_provider_provider_account_id_pk": {+ "columns": [+ "provider",+ "provider_account_id"+ ],+ "name": "account_provider_provider_account_id_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "session": {+ "name": "session",+ "columns": {+ "session_token": {+ "name": "session_token",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "expires": {+ "name": "expires",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "session_user_id_user_id_fk": {+ "name": "session_user_id_user_id_fk",+ "tableFrom": "session",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "user": {+ "name": "user",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "tenant_id": {+ "name": "tenant_id",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "first_name": {+ "name": "first_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "''"+ },+ "last_name": {+ "name": "last_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "''"+ },+ "photo_url": {+ "name": "photo_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "''"+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "''"+ },+ "emailVerified": {+ "name": "emailVerified",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "deleted_at": {+ "name": "deleted_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "user_tenant_id_unique": {+ "name": "user_tenant_id_unique",+ "columns": [+ "tenant_id"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "users_to_workspaces": {+ "name": "users_to_workspaces",+ "columns": {+ "user_id": {+ "name": "user_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'member'"+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "users_to_workspaces_user_id_user_id_fk": {+ "name": "users_to_workspaces_user_id_user_id_fk",+ "tableFrom": "users_to_workspaces",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "users_to_workspaces_workspace_id_workspace_id_fk": {+ "name": "users_to_workspaces_workspace_id_workspace_id_fk",+ "tableFrom": "users_to_workspaces",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "users_to_workspaces_user_id_workspace_id_pk": {+ "columns": [+ "user_id",+ "workspace_id"+ ],+ "name": "users_to_workspaces_user_id_workspace_id_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "verification_token": {+ "name": "verification_token",+ "columns": {+ "identifier": {+ "name": "identifier",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "expires": {+ "name": "expires",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "verification_token_identifier_token_pk": {+ "columns": [+ "identifier",+ "token"+ ],+ "name": "verification_token_identifier_token_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "status_report": {+ "name": "status_report",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "page_id": {+ "name": "page_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "status_report_workspace_id_workspace_id_fk": {+ "name": "status_report_workspace_id_workspace_id_fk",+ "tableFrom": "status_report",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "status_report_page_id_page_id_fk": {+ "name": "status_report_page_id_page_id_fk",+ "tableFrom": "status_report",+ "tableTo": "page",+ "columnsFrom": [+ "page_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "status_report_update": {+ "name": "status_report_update",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "date": {+ "name": "date",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "message": {+ "name": "message",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status_report_id": {+ "name": "status_report_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "status_report_update_status_report_id_status_report_id_fk": {+ "name": "status_report_update_status_report_id_status_report_id_fk",+ "tableFrom": "status_report_update",+ "tableTo": "status_report",+ "columnsFrom": [+ "status_report_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "integration": {+ "name": "integration",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "credential": {+ "name": "credential",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "external_id": {+ "name": "external_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "data": {+ "name": "data",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "integration_workspace_id_workspace_id_fk": {+ "name": "integration_workspace_id_workspace_id_fk",+ "tableFrom": "integration",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "page": {+ "name": "page",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "icon": {+ "name": "icon",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "''"+ },+ "slug": {+ "name": "slug",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "custom_domain": {+ "name": "custom_domain",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "published": {+ "name": "published",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": false+ },+ "force_theme": {+ "name": "force_theme",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'system'"+ },+ "password": {+ "name": "password",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "password_protected": {+ "name": "password_protected",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": false+ },+ "access_type": {+ "name": "access_type",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "'public'"+ },+ "auth_email_domains": {+ "name": "auth_email_domains",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "allowed_ip_ranges": {+ "name": "allowed_ip_ranges",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "homepage_url": {+ "name": "homepage_url",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "contact_url": {+ "name": "contact_url",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "default_locale": {+ "name": "default_locale",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'en'"+ },+ "locales": {+ "name": "locales",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "legacy_page": {+ "name": "legacy_page",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": true+ },+ "configuration": {+ "name": "configuration",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "allow_index": {+ "name": "allow_index",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": true+ },+ "show_monitor_values": {+ "name": "show_monitor_values",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": true+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "page_slug_unique": {+ "name": "page_slug_unique",+ "columns": [+ "slug"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "page_workspace_id_workspace_id_fk": {+ "name": "page_workspace_id_workspace_id_fk",+ "tableFrom": "page",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "monitor": {+ "name": "monitor",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "job_type": {+ "name": "job_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'http'"+ },+ "periodicity": {+ "name": "periodicity",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'other'"+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'active'"+ },+ "active": {+ "name": "active",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": false+ },+ "regions": {+ "name": "regions",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "url": {+ "name": "url",+ "type": "text(2048)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "external_name": {+ "name": "external_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "headers": {+ "name": "headers",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "''"+ },+ "body": {+ "name": "body",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "''"+ },+ "method": {+ "name": "method",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "'GET'"+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "timeout": {+ "name": "timeout",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 45000+ },+ "degraded_after": {+ "name": "degraded_after",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "assertions": {+ "name": "assertions",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "otel_endpoint": {+ "name": "otel_endpoint",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "otel_headers": {+ "name": "otel_headers",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "public": {+ "name": "public",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": false+ },+ "retry": {+ "name": "retry",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": 3+ },+ "follow_redirects": {+ "name": "follow_redirects",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": true+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "deleted_at": {+ "name": "deleted_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "monitor_workspace_id_workspace_id_fk": {+ "name": "monitor_workspace_id_workspace_id_fk",+ "tableFrom": "monitor",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "page_subscriber": {+ "name": "page_subscriber",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "page_id": {+ "name": "page_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "channel_type": {+ "name": "channel_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'email'"+ },+ "webhook_url": {+ "name": "webhook_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "channel_config": {+ "name": "channel_config",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "source": {+ "name": "source",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'self_signup'"+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "accepted_at": {+ "name": "accepted_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "unsubscribed_at": {+ "name": "unsubscribed_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "idx_page_subscriber_email_page_active": {+ "name": "idx_page_subscriber_email_page_active",+ "columns": [+ "LOWER(\"email\")",+ "page_id"+ ],+ "isUnique": true,+ "where": "\"page_subscriber\".\"unsubscribed_at\" IS NULL AND \"page_subscriber\".\"channel_type\" = 'email'"+ },+ "idx_page_subscriber_webhook_page_active": {+ "name": "idx_page_subscriber_webhook_page_active",+ "columns": [+ "LOWER(\"webhook_url\")",+ "page_id"+ ],+ "isUnique": true,+ "where": "\"page_subscriber\".\"unsubscribed_at\" IS NULL AND \"page_subscriber\".\"channel_type\" = 'webhook'"+ }+ },+ "foreignKeys": {+ "page_subscriber_page_id_page_id_fk": {+ "name": "page_subscriber_page_id_page_id_fk",+ "tableFrom": "page_subscriber",+ "tableTo": "page",+ "columnsFrom": [+ "page_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {+ "page_subscriber_channel_check": {+ "name": "page_subscriber_channel_check",+ "value": "(\"page_subscriber\".\"channel_type\" = 'email' AND \"page_subscriber\".\"email\" IS NOT NULL AND \"page_subscriber\".\"webhook_url\" IS NULL) OR (\"page_subscriber\".\"channel_type\" = 'webhook' AND \"page_subscriber\".\"webhook_url\" IS NOT NULL AND \"page_subscriber\".\"email\" IS NULL)"+ }+ }+ },+ "page_subscriber_to_page_component": {+ "name": "page_subscriber_to_page_component",+ "columns": {+ "page_subscriber_id": {+ "name": "page_subscriber_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "page_component_id": {+ "name": "page_component_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "page_subscriber_to_page_component_page_subscriber_id_page_subscriber_id_fk": {+ "name": "page_subscriber_to_page_component_page_subscriber_id_page_subscriber_id_fk",+ "tableFrom": "page_subscriber_to_page_component",+ "tableTo": "page_subscriber",+ "columnsFrom": [+ "page_subscriber_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "page_subscriber_to_page_component_page_component_id_page_component_id_fk": {+ "name": "page_subscriber_to_page_component_page_component_id_page_component_id_fk",+ "tableFrom": "page_subscriber_to_page_component",+ "tableTo": "page_component",+ "columnsFrom": [+ "page_component_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "page_subscriber_to_page_component_page_subscriber_id_page_component_id_pk": {+ "columns": [+ "page_subscriber_id",+ "page_component_id"+ ],+ "name": "page_subscriber_to_page_component_page_subscriber_id_page_component_id_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "notification": {+ "name": "notification",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "data": {+ "name": "data",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "'{}'"+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "notification_workspace_id_workspace_id_fk": {+ "name": "notification_workspace_id_workspace_id_fk",+ "tableFrom": "notification",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "notification_trigger": {+ "name": "notification_trigger",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "monitor_id": {+ "name": "monitor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "notification_id": {+ "name": "notification_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "cron_timestamp": {+ "name": "cron_timestamp",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "notification_id_monitor_id_crontimestampe": {+ "name": "notification_id_monitor_id_crontimestampe",+ "columns": [+ "notification_id",+ "monitor_id",+ "cron_timestamp"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "notification_trigger_monitor_id_monitor_id_fk": {+ "name": "notification_trigger_monitor_id_monitor_id_fk",+ "tableFrom": "notification_trigger",+ "tableTo": "monitor",+ "columnsFrom": [+ "monitor_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "notification_trigger_notification_id_notification_id_fk": {+ "name": "notification_trigger_notification_id_notification_id_fk",+ "tableFrom": "notification_trigger",+ "tableTo": "notification",+ "columnsFrom": [+ "notification_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "notifications_to_monitors": {+ "name": "notifications_to_monitors",+ "columns": {+ "monitor_id": {+ "name": "monitor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "notification_id": {+ "name": "notification_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "notifications_to_monitors_monitor_id_monitor_id_fk": {+ "name": "notifications_to_monitors_monitor_id_monitor_id_fk",+ "tableFrom": "notifications_to_monitors",+ "tableTo": "monitor",+ "columnsFrom": [+ "monitor_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "notifications_to_monitors_notification_id_notification_id_fk": {+ "name": "notifications_to_monitors_notification_id_notification_id_fk",+ "tableFrom": "notifications_to_monitors",+ "tableTo": "notification",+ "columnsFrom": [+ "notification_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "notifications_to_monitors_monitor_id_notification_id_pk": {+ "columns": [+ "monitor_id",+ "notification_id"+ ],+ "name": "notifications_to_monitors_monitor_id_notification_id_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "monitor_status": {+ "name": "monitor_status",+ "columns": {+ "monitor_id": {+ "name": "monitor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "region": {+ "name": "region",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'active'"+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "monitor_status_idx": {+ "name": "monitor_status_idx",+ "columns": [+ "monitor_id",+ "region"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "monitor_status_monitor_id_monitor_id_fk": {+ "name": "monitor_status_monitor_id_monitor_id_fk",+ "tableFrom": "monitor_status",+ "tableTo": "monitor",+ "columnsFrom": [+ "monitor_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "monitor_status_monitor_id_region_pk": {+ "columns": [+ "monitor_id",+ "region"+ ],+ "name": "monitor_status_monitor_id_region_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "invitation": {+ "name": "invitation",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'member'"+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "accepted_at": {+ "name": "accepted_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "incident": {+ "name": "incident",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "summary": {+ "name": "summary",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'triage'"+ },+ "monitor_id": {+ "name": "monitor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "started_at": {+ "name": "started_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "acknowledged_at": {+ "name": "acknowledged_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "acknowledged_by": {+ "name": "acknowledged_by",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "resolved_at": {+ "name": "resolved_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "resolved_by": {+ "name": "resolved_by",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "incident_screenshot_url": {+ "name": "incident_screenshot_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "recovery_screenshot_url": {+ "name": "recovery_screenshot_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "auto_resolved": {+ "name": "auto_resolved",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "incident_monitor_id_started_at_unique": {+ "name": "incident_monitor_id_started_at_unique",+ "columns": [+ "monitor_id",+ "started_at"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "incident_monitor_id_monitor_id_fk": {+ "name": "incident_monitor_id_monitor_id_fk",+ "tableFrom": "incident",+ "tableTo": "monitor",+ "columnsFrom": [+ "monitor_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set default",+ "onUpdate": "no action"+ },+ "incident_workspace_id_workspace_id_fk": {+ "name": "incident_workspace_id_workspace_id_fk",+ "tableFrom": "incident",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "incident_acknowledged_by_user_id_fk": {+ "name": "incident_acknowledged_by_user_id_fk",+ "tableFrom": "incident",+ "tableTo": "user",+ "columnsFrom": [+ "acknowledged_by"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "incident_resolved_by_user_id_fk": {+ "name": "incident_resolved_by_user_id_fk",+ "tableFrom": "incident",+ "tableTo": "user",+ "columnsFrom": [+ "resolved_by"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "monitor_tag": {+ "name": "monitor_tag",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "monitor_tag_workspace_id_workspace_id_fk": {+ "name": "monitor_tag_workspace_id_workspace_id_fk",+ "tableFrom": "monitor_tag",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "monitor_tag_to_monitor": {+ "name": "monitor_tag_to_monitor",+ "columns": {+ "monitor_id": {+ "name": "monitor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "monitor_tag_id": {+ "name": "monitor_tag_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "monitor_tag_to_monitor_monitor_id_monitor_id_fk": {+ "name": "monitor_tag_to_monitor_monitor_id_monitor_id_fk",+ "tableFrom": "monitor_tag_to_monitor",+ "tableTo": "monitor",+ "columnsFrom": [+ "monitor_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "monitor_tag_to_monitor_monitor_tag_id_monitor_tag_id_fk": {+ "name": "monitor_tag_to_monitor_monitor_tag_id_monitor_tag_id_fk",+ "tableFrom": "monitor_tag_to_monitor",+ "tableTo": "monitor_tag",+ "columnsFrom": [+ "monitor_tag_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "monitor_tag_to_monitor_monitor_id_monitor_tag_id_pk": {+ "columns": [+ "monitor_id",+ "monitor_tag_id"+ ],+ "name": "monitor_tag_to_monitor_monitor_id_monitor_tag_id_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "application": {+ "name": "application",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "dsn": {+ "name": "dsn",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "application_dsn_unique": {+ "name": "application_dsn_unique",+ "columns": [+ "dsn"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "application_workspace_id_workspace_id_fk": {+ "name": "application_workspace_id_workspace_id_fk",+ "tableFrom": "application",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "maintenance": {+ "name": "maintenance",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "message": {+ "name": "message",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "from": {+ "name": "from",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "to": {+ "name": "to",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "page_id": {+ "name": "page_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "maintenance_workspace_id_workspace_id_fk": {+ "name": "maintenance_workspace_id_workspace_id_fk",+ "tableFrom": "maintenance",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "maintenance_page_id_page_id_fk": {+ "name": "maintenance_page_id_page_id_fk",+ "tableFrom": "maintenance",+ "tableTo": "page",+ "columnsFrom": [+ "page_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "check": {+ "name": "check",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": true+ },+ "regions": {+ "name": "regions",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "url": {+ "name": "url",+ "type": "text(4096)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "headers": {+ "name": "headers",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "''"+ },+ "body": {+ "name": "body",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "''"+ },+ "method": {+ "name": "method",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "'GET'"+ },+ "count_requests": {+ "name": "count_requests",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": 1+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "check_workspace_id_workspace_id_fk": {+ "name": "check_workspace_id_workspace_id_fk",+ "tableFrom": "check",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "monitor_run": {+ "name": "monitor_run",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "monitor_id": {+ "name": "monitor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "runned_at": {+ "name": "runned_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "monitor_run_workspace_id_workspace_id_fk": {+ "name": "monitor_run_workspace_id_workspace_id_fk",+ "tableFrom": "monitor_run",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "monitor_run_monitor_id_monitor_id_fk": {+ "name": "monitor_run_monitor_id_monitor_id_fk",+ "tableFrom": "monitor_run",+ "tableTo": "monitor",+ "columnsFrom": [+ "monitor_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "private_location": {+ "name": "private_location",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "last_seen_at": {+ "name": "last_seen_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "private_location_workspace_id_workspace_id_fk": {+ "name": "private_location_workspace_id_workspace_id_fk",+ "tableFrom": "private_location",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "private_location_to_monitor": {+ "name": "private_location_to_monitor",+ "columns": {+ "private_location_id": {+ "name": "private_location_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "monitor_id": {+ "name": "monitor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "deleted_at": {+ "name": "deleted_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "private_location_to_monitor_private_location_id_private_location_id_fk": {+ "name": "private_location_to_monitor_private_location_id_private_location_id_fk",+ "tableFrom": "private_location_to_monitor",+ "tableTo": "private_location",+ "columnsFrom": [+ "private_location_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "private_location_to_monitor_monitor_id_monitor_id_fk": {+ "name": "private_location_to_monitor_monitor_id_monitor_id_fk",+ "tableFrom": "private_location_to_monitor",+ "tableTo": "monitor",+ "columnsFrom": [+ "monitor_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "monitor_group": {+ "name": "monitor_group",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "page_id": {+ "name": "page_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "monitor_group_workspace_id_workspace_id_fk": {+ "name": "monitor_group_workspace_id_workspace_id_fk",+ "tableFrom": "monitor_group",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "monitor_group_page_id_page_id_fk": {+ "name": "monitor_group_page_id_page_id_fk",+ "tableFrom": "monitor_group",+ "tableTo": "page",+ "columnsFrom": [+ "page_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "viewer": {+ "name": "viewer",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "emailVerified": {+ "name": "emailVerified",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "image": {+ "name": "image",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "viewer_email_unique": {+ "name": "viewer_email_unique",+ "columns": [+ "email"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "viewer_accounts": {+ "name": "viewer_accounts",+ "columns": {+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "providerAccountId": {+ "name": "providerAccountId",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "refresh_token": {+ "name": "refresh_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "access_token": {+ "name": "access_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "token_type": {+ "name": "token_type",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "scope": {+ "name": "scope",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "id_token": {+ "name": "id_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "session_state": {+ "name": "session_state",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "viewer_accounts_user_id_viewer_id_fk": {+ "name": "viewer_accounts_user_id_viewer_id_fk",+ "tableFrom": "viewer_accounts",+ "tableTo": "viewer",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "viewer_accounts_provider_providerAccountId_pk": {+ "columns": [+ "provider",+ "providerAccountId"+ ],+ "name": "viewer_accounts_provider_providerAccountId_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "viewer_session": {+ "name": "viewer_session",+ "columns": {+ "session_token": {+ "name": "session_token",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "expires": {+ "name": "expires",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "viewer_session_user_id_viewer_id_fk": {+ "name": "viewer_session_user_id_viewer_id_fk",+ "tableFrom": "viewer_session",+ "tableTo": "viewer",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "api_key": {+ "name": "api_key",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "prefix": {+ "name": "prefix",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "hashed_token": {+ "name": "hashed_token",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_by_id": {+ "name": "created_by_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_used_at": {+ "name": "last_used_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "api_key_prefix_unique": {+ "name": "api_key_prefix_unique",+ "columns": [+ "prefix"+ ],+ "isUnique": true+ },+ "api_key_hashed_token_unique": {+ "name": "api_key_hashed_token_unique",+ "columns": [+ "hashed_token"+ ],+ "isUnique": true+ },+ "api_key_prefix_idx": {+ "name": "api_key_prefix_idx",+ "columns": [+ "prefix"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "api_key_workspace_id_workspace_id_fk": {+ "name": "api_key_workspace_id_workspace_id_fk",+ "tableFrom": "api_key",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "api_key_created_by_id_user_id_fk": {+ "name": "api_key_created_by_id_user_id_fk",+ "tableFrom": "api_key",+ "tableTo": "user",+ "columnsFrom": [+ "created_by_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "maintenance_to_page_component": {+ "name": "maintenance_to_page_component",+ "columns": {+ "maintenance_id": {+ "name": "maintenance_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "page_component_id": {+ "name": "page_component_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "maintenance_to_page_component_maintenance_id_maintenance_id_fk": {+ "name": "maintenance_to_page_component_maintenance_id_maintenance_id_fk",+ "tableFrom": "maintenance_to_page_component",+ "tableTo": "maintenance",+ "columnsFrom": [+ "maintenance_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "maintenance_to_page_component_page_component_id_page_component_id_fk": {+ "name": "maintenance_to_page_component_page_component_id_page_component_id_fk",+ "tableFrom": "maintenance_to_page_component",+ "tableTo": "page_component",+ "columnsFrom": [+ "page_component_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "maintenance_to_page_component_maintenance_id_page_component_id_pk": {+ "columns": [+ "maintenance_id",+ "page_component_id"+ ],+ "name": "maintenance_to_page_component_maintenance_id_page_component_id_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "page_component": {+ "name": "page_component",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "page_id": {+ "name": "page_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'monitor'"+ },+ "monitor_id": {+ "name": "monitor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "order": {+ "name": "order",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": 0+ },+ "group_id": {+ "name": "group_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "group_order": {+ "name": "group_order",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "page_component_page_id_monitor_id_unique": {+ "name": "page_component_page_id_monitor_id_unique",+ "columns": [+ "page_id",+ "monitor_id"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "page_component_workspace_id_workspace_id_fk": {+ "name": "page_component_workspace_id_workspace_id_fk",+ "tableFrom": "page_component",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "page_component_page_id_page_id_fk": {+ "name": "page_component_page_id_page_id_fk",+ "tableFrom": "page_component",+ "tableTo": "page",+ "columnsFrom": [+ "page_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "page_component_monitor_id_monitor_id_fk": {+ "name": "page_component_monitor_id_monitor_id_fk",+ "tableFrom": "page_component",+ "tableTo": "monitor",+ "columnsFrom": [+ "monitor_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "page_component_group_id_page_component_groups_id_fk": {+ "name": "page_component_group_id_page_component_groups_id_fk",+ "tableFrom": "page_component",+ "tableTo": "page_component_groups",+ "columnsFrom": [+ "group_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {+ "page_component_type_check": {+ "name": "page_component_type_check",+ "value": "\"page_component\".\"type\" = 'monitor' AND \"page_component\".\"monitor_id\" IS NOT NULL OR \"page_component\".\"type\" = 'static' AND \"page_component\".\"monitor_id\" IS NULL"+ }+ }+ },+ "status_report_to_page_component": {+ "name": "status_report_to_page_component",+ "columns": {+ "status_report_id": {+ "name": "status_report_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "page_component_id": {+ "name": "page_component_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "status_report_to_page_component_status_report_id_status_report_id_fk": {+ "name": "status_report_to_page_component_status_report_id_status_report_id_fk",+ "tableFrom": "status_report_to_page_component",+ "tableTo": "status_report",+ "columnsFrom": [+ "status_report_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "status_report_to_page_component_page_component_id_page_component_id_fk": {+ "name": "status_report_to_page_component_page_component_id_page_component_id_fk",+ "tableFrom": "status_report_to_page_component",+ "tableTo": "page_component",+ "columnsFrom": [+ "page_component_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "status_report_to_page_component_status_report_id_page_component_id_pk": {+ "columns": [+ "status_report_id",+ "page_component_id"+ ],+ "name": "status_report_to_page_component_status_report_id_page_component_id_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "page_component_groups": {+ "name": "page_component_groups",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "page_id": {+ "name": "page_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "default_open": {+ "name": "default_open",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "page_component_groups_workspace_id_workspace_id_fk": {+ "name": "page_component_groups_workspace_id_workspace_id_fk",+ "tableFrom": "page_component_groups",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "page_component_groups_page_id_page_id_fk": {+ "name": "page_component_groups_page_id_page_id_fk",+ "tableFrom": "page_component_groups",+ "tableTo": "page",+ "columnsFrom": [+ "page_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "feedback": {+ "name": "feedback",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "source": {+ "name": "source",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "message": {+ "name": "message",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "blocker": {+ "name": "blocker",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "path": {+ "name": "path",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "feedback_workspace_id_workspace_id_fk": {+ "name": "feedback_workspace_id_workspace_id_fk",+ "tableFrom": "feedback",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "feedback_user_id_user_id_fk": {+ "name": "feedback_user_id_user_id_fk",+ "tableFrom": "feedback",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "audit_log": {+ "name": "audit_log",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "actor_type": {+ "name": "actor_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "actor_id": {+ "name": "actor_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "actor_user_id": {+ "name": "actor_user_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "action": {+ "name": "action",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "entity_type": {+ "name": "entity_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "entity_id": {+ "name": "entity_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "before": {+ "name": "before",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "after": {+ "name": "after",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "changed_fields": {+ "name": "changed_fields",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "audit_log_workspace_created_idx": {+ "name": "audit_log_workspace_created_idx",+ "columns": [+ "workspace_id",+ "created_at"+ ],+ "isUnique": false+ },+ "audit_log_entity_idx": {+ "name": "audit_log_entity_idx",+ "columns": [+ "workspace_id",+ "entity_type",+ "entity_id",+ "created_at"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ }+ },+ "views": {},+ "enums": {},+ "_meta": {+ "schemas": {},+ "tables": {},+ "columns": {}+ },+ "internal": {+ "indexes": {+ "idx_page_subscriber_email_page_active": {+ "columns": {+ "LOWER(\"email\")": {+ "isExpression": true+ }+ }+ },+ "idx_page_subscriber_webhook_page_active": {+ "columns": {+ "LOWER(\"webhook_url\")": {+ "isExpression": true+ }+ }+ }+ }+ }+}\ No newline at end of filediff --git a/packages/db/drizzle/meta/_journal.json b/packages/db/drizzle/meta/_journal.jsonindex abf115b29..6214d5456 100644--- a/packages/db/drizzle/meta/_journal.json+++ b/packages/db/drizzle/meta/_journal.json@@ -456,6 +456,13 @@"when": 1776753844046,"tag": "0064_dusty_sunfire","breakpoints": true+ },+ {+ "idx": 65,+ "version": "6",+ "when": 1777044904253,+ "tag": "0065_stiff_hiroim",+ "breakpoints": true}]}\ No newline at end of filediff --git a/packages/db/src/schema/audit_logs/audit_log.ts b/packages/db/src/schema/audit_logs/audit_log.tsnew file mode 100644index 000000000..b6579da1f--- /dev/null+++ b/packages/db/src/schema/audit_logs/audit_log.ts@@ -0,0 +1,51 @@+import { index, integer, sqliteTable, text } from "drizzle-orm/sqlite-core";++/**+ * Append-only log of mutating actions taken against the workspace.+ *+ * No foreign keys: rows outlive their subjects (workspace / user / monitor+ * deletions must not cascade-remove audit history, and a soft-deleted+ * user must not block inserts). References on columns are informational+ * and enforced in application code.+ *+ * Reads must sort by `(created_at DESC, id DESC)` — bulk operations emit+ * multiple rows in the same millisecond; the autoincrement id gives a+ * deterministic tiebreaker.+ */+export const auditLog = sqliteTable(+ "audit_log",+ {+ id: integer("id").primaryKey({ autoIncrement: true }),+ workspaceId: integer("workspace_id").notNull(),+ actorType: text("actor_type").notNull(),+ actorId: text("actor_id").notNull(),+ actorUserId: integer("actor_user_id"),+ action: text("action").notNull(),+ entityType: text("entity_type").notNull(),+ entityId: text("entity_id").notNull(),+ before: text("before", { mode: "json" }).$type<Record<string, unknown>>(),+ after: text("after", { mode: "json" }).$type<Record<string, unknown>>(),+ metadata: text("metadata", {+ mode: "json",+ }).$type<Record<string, unknown>>(),+ changedFields: text("changed_fields", { mode: "json" }).$type<string[]>(),+ createdAt: integer("created_at", { mode: "timestamp_ms" })+ .notNull()+ .$defaultFn(() => new Date()),+ },+ (t) => ({+ workspaceCreatedIdx: index("audit_log_workspace_created_idx").on(+ t.workspaceId,+ t.createdAt,+ ),+ entityIdx: index("audit_log_entity_idx").on(+ t.workspaceId,+ t.entityType,+ t.entityId,+ t.createdAt,+ ),+ }),+);++export type AuditLog = typeof auditLog.$inferSelect;+export type NewAuditLog = typeof auditLog.$inferInsert;diff --git a/packages/db/src/schema/audit_logs/index.ts b/packages/db/src/schema/audit_logs/index.tsnew file mode 100644index 000000000..a1b526473--- /dev/null+++ b/packages/db/src/schema/audit_logs/index.ts@@ -0,0 +1,2 @@+export * from "./audit_log";+export * from "./validation";diff --git a/packages/db/src/schema/audit_logs/validation.ts b/packages/db/src/schema/audit_logs/validation.tsnew file mode 100644index 000000000..2cb074624--- /dev/null+++ b/packages/db/src/schema/audit_logs/validation.ts@@ -0,0 +1,202 @@+import { createInsertSchema, createSelectSchema } from "drizzle-zod";+import { z } from "zod";++import { auditLog } from "./audit_log";++/**+ * Runtime schema + discriminated-union type for every audit action+ * services emit. Paired with `emitAudit` in `@openstatus/services`,+ * which calls `AuditEntrySchema.parse(...)` before writing the row.+ *+ * Every entity gets at most three verbs: `create`, `update`, `delete`.+ * Operation-specific semantics (acknowledge, resolve, accept, revoke,+ * rename, bulk-set) collapse into whichever of the three they+ * structurally are; readers recover the specific intent by inspecting+ * `changed_fields` on the row.+ *+ * `metadata` is reserved for side-channel context that is *not*+ * derivable from the entity snapshot — e.g. `clonedFromMonitorId`,+ * `statusReportId` on a status-report update. Fields that change on the+ * entity itself belong in `before`/`after`.+ *+ * Adding a new emit site requires adding a variant here — there is no+ * escape hatch. If a new operation isn't a create/update/delete, it+ * probably shouldn't be in the audit log.+ */++const metadataSchema = z.record(z.string(), z.unknown());+const snapshotSchema = z.record(z.string(), z.unknown());++// Small helper so every variant reads the same — keeps the discriminated+// union legible when skimming.+function action<A extends string, E extends string, I extends z.ZodTypeAny>(+ action: A,+ entityType: E,+ entityIdSchema: I,+ opts: { optionalMetadata?: boolean } = {},+) {+ return z.object({+ action: z.literal(action),+ entityType: z.literal(entityType),+ entityId: entityIdSchema,+ ...(opts.optionalMetadata ? { metadata: metadataSchema.optional() } : {}),+ });+}++const intId = z.number().int();++const monitorActions = [+ action("monitor.create", "monitor", intId, { optionalMetadata: true }),+ action("monitor.update", "monitor", intId),+ action("monitor.delete", "monitor", intId),+] as const;++const pageActions = [+ action("page.create", "page", intId, { optionalMetadata: true }),+ action("page.update", "page", intId),+ action("page.delete", "page", intId),+] as const;++const pageComponentActions = [+ action("page_component.create", "page_component", intId, {+ optionalMetadata: true,+ }),+ action("page_component.update", "page_component", intId),+ action("page_component.delete", "page_component", intId),+] as const;++const pageComponentGroupActions = [+ action("page_component_group.create", "page_component_group", intId, {+ optionalMetadata: true,+ }),+ action("page_component_group.update", "page_component_group", intId),+ action("page_component_group.delete", "page_component_group", intId),+] as const;++const pageSubscriberActions = [+ action("page_subscriber.create", "page_subscriber", intId, {+ optionalMetadata: true,+ }),+] as const;++const apiKeyActions = [+ action("api_key.create", "api_key", intId, { optionalMetadata: true }),+ action("api_key.delete", "api_key", intId),+] as const;++const notificationActions = [+ action("notification.create", "notification", intId),+ action("notification.update", "notification", intId),+ action("notification.delete", "notification", intId),+] as const;++const userActions = [action("user.delete", "user", intId)] as const;++const workspaceActions = [+ action("workspace.update", "workspace", intId),+] as const;++const maintenanceActions = [+ action("maintenance.create", "maintenance", intId, {+ optionalMetadata: true,+ }),+ action("maintenance.update", "maintenance", intId),+ action("maintenance.delete", "maintenance", intId),+] as const;++const incidentActions = [+ action("incident.update", "incident", intId),+ action("incident.delete", "incident", intId),+] as const;++const statusReportActions = [+ action("status_report.create", "status_report", intId, {+ optionalMetadata: true,+ }),+ action("status_report.update", "status_report", intId),+ action("status_report.delete", "status_report", intId),+] as const;++const statusReportUpdateActions = [+ action("status_report_update.create", "status_report_update", intId, {+ optionalMetadata: true,+ }),+ action("status_report_update.update", "status_report_update", intId),+ action("status_report_update.delete", "status_report_update", intId),+] as const;++const invitationActions = [+ action("invitation.create", "invitation", intId, { optionalMetadata: true }),+ action("invitation.update", "invitation", intId),+ action("invitation.delete", "invitation", intId),+] as const;++export const auditActionSchema = z.discriminatedUnion("action", [+ ...monitorActions,+ ...pageActions,+ ...pageComponentActions,+ ...pageComponentGroupActions,+ ...pageSubscriberActions,+ ...apiKeyActions,+ ...notificationActions,+ ...userActions,+ ...workspaceActions,+ ...maintenanceActions,+ ...incidentActions,+ ...statusReportActions,+ ...statusReportUpdateActions,+ ...invitationActions,+]);++/**+ * Audit-entry input schema — the action/entityType/entityId+metadata+ * discriminant plus optional `before`/`after` snapshots.+ *+ * Derived from `auditActionSchema` via `.and()` so the variant list+ * stays single-sourced — adding a new action here would otherwise+ * require two parallel edits.+ *+ * The `before`/`after` snapshots are intentionally loose at runtime+ * (`Record<string, unknown>`): their shapes mirror the underlying+ * entity tables and binding them to this schema would force a cycle+ * with every column definition. Shape *presence* is enforced in+ * TypeScript via the `AuditEntry` type below, keyed off the action+ * verb suffix.+ */+export const auditEntrySchema = auditActionSchema.and(+ z.object({+ before: snapshotSchema.optional(),+ after: snapshotSchema.optional(),+ }),+);++export const insertAuditLogSchema = createInsertSchema(auditLog);+export const selectAuditLogSchema = createSelectSchema(auditLog);++export type AuditAction = z.infer<typeof auditActionSchema>;++type Snapshot = Record<string, unknown>;++/**+ * Snapshot presence is derived from the action's verb suffix:+ *+ * - `*.create` — `after` required, `before` forbidden.+ * - `*.delete` — `before` required, `after` forbidden.+ * - `*.update` — both `before` and `after` required.+ *+ * Enforced at the `emitAudit` call site via the parameter type; Zod+ * stays loose at runtime so the schema file doesn't need to know each+ * entity's column list.+ */+export type AuditEntry = AuditAction extends infer A+ ? A extends { action: `${string}.create` }+ ? A & { after: Snapshot; before?: never }+ : A extends { action: `${string}.delete` }+ ? A & { before: Snapshot; after?: never }+ : A extends { action: `${string}.update` }+ ? A & { before: Snapshot; after: Snapshot }+ : A & { before?: Snapshot; after?: Snapshot }+ : never;++export type AuditActionName = AuditAction["action"];+export type AuditEntityType = AuditAction["entityType"];diff --git a/packages/db/src/schema/index.ts b/packages/db/src/schema/index.tsindex 60c2fcb34..f85ab9315 100644--- a/packages/db/src/schema/index.ts+++ b/packages/db/src/schema/index.ts@@ -22,3 +22,4 @@ export * from "./api-keys";export * from "./page_components";export * from "./page_component_groups";export * from "./feedbacks";+export * from "./audit_logs";diff --git a/packages/services/package.json b/packages/services/package.jsonindex e9c8c565d..1663836eb 100644--- a/packages/services/package.json+++ b/packages/services/package.json@@ -56,13 +56,16 @@"./import": {"import": "./src/import/index.ts","types": "./src/import/index.ts"+ },+ "./audit": {+ "import": "./src/audit/index.ts",+ "types": "./src/audit/index.ts"}},"scripts": {"test": "bun test"},"dependencies": {- "@logtape/logtape": "2.0.1","@openstatus/assertions": "workspace:*","@openstatus/db": "workspace:*","@openstatus/importers": "workspace:*",diff --git a/packages/services/src/api-key/__tests__/api-key.test.ts b/packages/services/src/api-key/__tests__/api-key.test.tsindex 1b7de6465..59c7ccb98 100644--- a/packages/services/src/api-key/__tests__/api-key.test.ts+++ b/packages/services/src/api-key/__tests__/api-key.test.ts@@ -1,6 +1,5 @@import {afterAll,- afterEach,beforeAll,beforeEach,describe,@@ -19,20 +18,17 @@ import {} from "..";import { SEEDED_WORKSPACE_TEAM_ID } from "../../../test/fixtures";import {+ clearAuditLog,expectAuditRow,loadSeededWorkspace,makeUserCtx,- withAuditBuffer,} from "../../../test/helpers";-import type { AuditLogRecord } from "../../audit";import type { ServiceContext } from "../../context";import { NotFoundError } from "../../errors";const TEST_PREFIX = "svc-apikey-test";let teamCtx: ServiceContext;-let auditBuffer: AuditLogRecord[];-let auditReset: () => void;const createdKeyIds: number[] = [];beforeAll(async () => {@@ -46,12 +42,9 @@ afterAll(async () => {}});-beforeEach(() => {- const session = withAuditBuffer();- auditBuffer = session.buffer;- auditReset = session.reset;+beforeEach(async () => {+ await clearAuditLog(teamCtx.workspace.id);});-afterEach(() => auditReset());describe("createApiKey", () => {test("returns plaintext token once and stores a bcrypt hash", async () => {@@ -77,7 +70,8 @@ describe("createApiKey", () => {.get();expect(stored?.hashedToken).toMatch(/^\$2[aby]\$/);- await expectAuditRow(auditBuffer, {+ await expectAuditRow({+ workspaceId: teamCtx.workspace.id,action: "api_key.create",entityType: "api_key",entityId: key.id,diff --git a/packages/services/src/api-key/create.ts b/packages/services/src/api-key/create.tsindex 1407202a0..74ef1252a 100644--- a/packages/services/src/api-key/create.ts+++ b/packages/services/src/api-key/create.ts@@ -57,11 +57,21 @@ export async function createApiKey(args: {throw new InternalServiceError("Failed to create API key");}+ // Narrow snapshot: `hashedToken` is a secret (bcrypt hash), and+ // `workspaceId`/`createdById`/timestamps are already derivable from+ // the row header or the actor. Keep the audit payload to the fields+ // a reader actually needs to identify which key this was.await emitAudit(tx, ctx, {action: "api_key.create",entityType: "api_key",entityId: key.id,- metadata: { name: input.name },+ after: {+ id: key.id,+ name: key.name,+ description: key.description,+ prefix: key.prefix,+ expiresAt: key.expiresAt,+ },});// Strip `hashedToken` before returning — callers only need thediff --git a/packages/services/src/api-key/list.ts b/packages/services/src/api-key/list.tsindex 239200211..fbc84b6ae 100644--- a/packages/services/src/api-key/list.ts+++ b/packages/services/src/api-key/list.ts@@ -1,10 +1,19 @@import { db as defaultDb, eq, inArray } from "@openstatus/db";-import { apiKey, user } from "@openstatus/db/src/schema";+import { apiKey, selectApiKeySchema, user } from "@openstatus/db/src/schema";import type { ServiceContext } from "../context";import type { ApiKey } from "../types";import type { ListApiKeysInput } from "./schemas";+/**+ * Public projection schema — derived from `selectApiKeySchema` so column /+ * default changes flow through. Stripping `hashedToken` here means the+ * bcrypt hash never reaches a list response, even by accident.+ */+const selectPublicApiKeySchema = selectApiKeySchema.omit({+ hashedToken: true,+});+export type ApiKeyCreator = {id: number;email: string | null;@@ -58,27 +67,7 @@ export async function listApiKeys(args: {if (keys.length === 0) return [];- // Filter out any null `createdById` — the new `createApiKey` enforces- // a non-null creator, but legacy rows (or backfills from before the- // services migration) may have null. SQL's `x IN (NULL)` is `UNKNOWN`- // rather than a match, so passing a nullable list wouldn't cause a- // false positive — but drizzle's types model the array as `number[]`,- // so sanitising upfront keeps the type honest and avoids surprises.- const creatorIds = Array.from(- new Set(- keys.map((k) => k.createdById).filter((id): id is number => id != null),- ),- );- // Skip the creator lookup entirely when every key pre-dates the- // services migration (all `createdById` are null). Drizzle throws- // `"At least one value must be provided"` for an empty `inArray`,- // which would crash `listApiKeys` for those workspaces.- if (creatorIds.length === 0) {- return keys.map((key) => ({- ...(key as PublicApiKey),- createdBy: undefined,- }));- }+ const creatorIds = Array.from(new Set(keys.map((k) => k.createdById)));const creators = await db.select({id: user.id,@@ -93,7 +82,7 @@ export async function listApiKeys(args: {const creatorsById = new Map(creators.map((c) => [c.id, c]));return keys.map((key) => ({- ...(key as PublicApiKey),+ ...selectPublicApiKeySchema.parse(key),createdBy: creatorsById.get(key.createdById),}));}diff --git a/packages/services/src/api-key/revoke.ts b/packages/services/src/api-key/revoke.tsindex 398ba69c2..c9b12ba30 100644--- a/packages/services/src/api-key/revoke.ts+++ b/packages/services/src/api-key/revoke.ts@@ -20,8 +20,17 @@ export async function revokeApiKey(args: {const input = RevokeApiKeyInput.parse(args.input);await withTransaction(ctx, async (tx) => {+ // Narrow select: matches the fields we put in the audit `before`+ // snapshot. `hashedToken` stays off the wire even within the tx,+ // and `workspaceId` is implied by the WHERE clause.const row = await tx- .select({ id: apiKey.id })+ .select({+ id: apiKey.id,+ name: apiKey.name,+ description: apiKey.description,+ prefix: apiKey.prefix,+ expiresAt: apiKey.expiresAt,+ }).from(apiKey).where(and(eq(apiKey.id, input.id), eq(apiKey.workspaceId, ctx.workspace.id)),@@ -33,9 +42,10 @@ export async function revokeApiKey(args: {await tx.delete(apiKey).where(eq(apiKey.id, input.id));await emitAudit(tx, ctx, {- action: "api_key.revoke",+ action: "api_key.delete",entityType: "api_key",entityId: input.id,+ before: row,});});}diff --git a/packages/services/src/api-key/verify.ts b/packages/services/src/api-key/verify.tsindex a3b4a636c..5605e6a8f 100644--- a/packages/services/src/api-key/verify.ts+++ b/packages/services/src/api-key/verify.ts@@ -1,5 +1,5 @@import { db as defaultDb, eq } from "@openstatus/db";-import { apiKey } from "@openstatus/db/src/schema";+import { apiKey, selectApiKeySchema } from "@openstatus/db/src/schema";import {shouldUpdateLastUsed as checkShouldUpdateLastUsed,verifyApiKeyHash,@@ -42,7 +42,7 @@ export async function verifyApiKey(if (!(await verifyApiKeyHash(parsed.token, key.hashedToken))) return null;if (key.expiresAt && key.expiresAt < new Date()) return null;- return key as ApiKey;+ return selectApiKeySchema.parse(key);}/**diff --git a/packages/services/src/audit.ts b/packages/services/src/audit.tsdeleted file mode 100644index 566c824aa..000000000--- a/packages/services/src/audit.ts+++ /dev/null@@ -1,74 +0,0 @@-import { getLogger } from "@logtape/logtape";--import {- type Actor,- type DB,- type ServiceContext,- extractActorId,-} from "./context";--const logger = getLogger(["services", "audit"]);--export type AuditEntry = {- /** Canonical action identifier, e.g. "status_report.create". */- action: string;- /** Entity type the action targets, e.g. "status_report". */- entityType: string;- entityId: number | string;- /**- * Accepted at the call site for audit log v2 (dedicated table with scrub/redact- * policy) but dropped before writing in v1 — logs are not the right place for- * PII-bearing payloads. Callers still emit full entries so v2 only needs to- * change emitAudit's body, not the ~200 future emitter sites.- */- before?: unknown;- after?: unknown;- metadata?: Record<string, unknown>;-};--export type AuditLogRecord = {- workspaceId: number;- actorType: Actor["type"];- actorId: string;- action: string;- entityType: string;- entityId: string;- requestId: string | undefined;-};--// Test-only audit buffer. Tests opt in via installTestAuditBuffer(); when-// active, emitAudit pushes records into the buffer so tests can assert against-// them without parsing logs.-let testBuffer: AuditLogRecord[] | null = null;--export function installTestAuditBuffer(): AuditLogRecord[] {- const buffer: AuditLogRecord[] = [];- testBuffer = buffer;- return buffer;-}--export function uninstallTestAuditBuffer(): void {- testBuffer = null;-}--export async function emitAudit(- // `tx` is unused in v1 but part of the contract: audit rows will be written- // inside the caller's transaction in v2. Signature stays stable.- _tx: DB,- ctx: ServiceContext,- entry: AuditEntry,-): Promise<void> {- const record: AuditLogRecord = {- workspaceId: ctx.workspace.id,- actorType: ctx.actor.type,- actorId: extractActorId(ctx.actor),- action: entry.action,- entityType: entry.entityType,- entityId: String(entry.entityId),- requestId: ctx.requestId,- };-- if (testBuffer) testBuffer.push(record);-- logger.info(`audit: ${record.action}`, { audit: true, ...record });-}diff --git a/packages/services/src/audit/__tests__/audit.test.ts b/packages/services/src/audit/__tests__/audit.test.tsnew file mode 100644index 000000000..29faea7c8--- /dev/null+++ b/packages/services/src/audit/__tests__/audit.test.ts@@ -0,0 +1,531 @@+import {+ afterAll,+ beforeAll,+ beforeEach,+ describe,+ expect,+ test,+} from "bun:test";+import { db, eq } from "@openstatus/db";+import { auditLog } from "@openstatus/db/src/schema";++import type { AuditEntry } from "@openstatus/db/src/schema";+import { SEEDED_WORKSPACE_TEAM_ID } from "../../../test/fixtures";+import {+ clearAuditLog,+ loadSeededWorkspace,+ makeApiKeyCtx,+ makeSlackCtx,+ makeSystemCtx,+ makeUserCtx,+ readAuditLog,+} from "../../../test/helpers";+import type { ServiceContext } from "../../context";++import { diffTopLevel, emitAudit } from "../emit";++/**+ * Test-only escape hatch around `emitAudit`'s compile-time snapshot+ * contract (`.create` requires `after`, `.delete` requires `before`,+ * `.update` requires both). Several tests here intentionally pass+ * bare entries to exercise the runtime path — column persistence,+ * actor derivation, ordering — without caring about snapshot shape.+ * Real call sites must satisfy the full type.+ */+async function emitLoose(+ tx: Parameters<typeof emitAudit>[0],+ ctx: ServiceContext,+ entry: unknown,+) {+ return emitAudit(tx, ctx, entry as AuditEntry);+}++let teamCtx: ServiceContext;++beforeAll(async () => {+ const team = await loadSeededWorkspace(SEEDED_WORKSPACE_TEAM_ID);+ teamCtx = makeUserCtx(team, { userId: 1 });+});++beforeEach(async () => {+ await clearAuditLog(teamCtx.workspace.id);+});++afterAll(async () => {+ await clearAuditLog(SEEDED_WORKSPACE_TEAM_ID);+});++describe("diffTopLevel", () => {+ test("empty when objects are equal", () => {+ const result = diffTopLevel(+ { name: "a", count: 1 },+ { name: "a", count: 1 },+ );+ expect(result).toEqual([]);+ });++ test("reports top-level keys that differ", () => {+ const result = diffTopLevel(+ { name: "a", count: 1 },+ { name: "b", count: 1 },+ );+ expect(result).toEqual(["name"]);+ });++ test("reports additions and removals as changed", () => {+ const added = diffTopLevel({ name: "a" }, { name: "a", extra: "x" });+ expect(added).toEqual(["extra"]);+ const removed = diffTopLevel({ name: "a", extra: "x" }, { name: "a" });+ expect(removed).toEqual(["extra"]);+ });++ test("ignores updatedAt and createdAt", () => {+ const before = {+ name: "a",+ createdAt: new Date("2025-01-01"),+ updatedAt: new Date("2025-01-01"),+ };+ const after = {+ name: "a",+ createdAt: new Date("2025-06-01"),+ updatedAt: new Date("2025-06-01"),+ };+ expect(diffTopLevel(before, after)).toEqual([]);+ });++ test("reports non-ignored changes alongside ignored ones", () => {+ const before = {+ name: "a",+ updatedAt: new Date("2025-01-01"),+ };+ const after = {+ name: "b",+ updatedAt: new Date("2025-06-01"),+ };+ expect(diffTopLevel(before, after)).toEqual(["name"]);+ });++ test("treats null and undefined as absent — both absent means unchanged", () => {+ expect(diffTopLevel({ a: null }, { a: undefined })).toEqual([]);+ expect(diffTopLevel({ a: undefined }, { a: null })).toEqual([]);+ expect(diffTopLevel({}, { a: null })).toEqual([]);+ expect(diffTopLevel({ a: null }, {})).toEqual([]);+ });++ test("treats null → value as changed", () => {+ expect(diffTopLevel({ a: null }, { a: "x" })).toEqual(["a"]);+ expect(diffTopLevel({ a: "x" }, { a: null })).toEqual(["a"]);+ });++ test("top-level only — nested object changes report the parent key", () => {+ const before = { headers: { Authorization: "old" }, name: "a" };+ const after = { headers: { Authorization: "new" }, name: "a" };+ expect(diffTopLevel(before, after)).toEqual(["headers"]);+ });++ test("array equality is deep, not reference-based", () => {+ const before = { tags: [1, 2, 3] };+ const after = { tags: [1, 2, 3] };+ expect(diffTopLevel(before, after)).toEqual([]);+ const changed = diffTopLevel({ tags: [1, 2] }, { tags: [1, 2, 3] });+ expect(changed).toEqual(["tags"]);+ });+});++describe("emitAudit — row persistence", () => {+ test("inserts a row with the expected columns", async () => {+ await db.transaction(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",+ });+ 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 emitLoose(tx, teamCtx, {+ action: "page.delete",+ entityType: "page",+ entityId: 42,+ });+ });+ const [row] = await readAuditLog({+ workspaceId: teamCtx.workspace.id,+ entityType: "page",+ entityId: 42,+ });+ expect(row?.entityId).toBe("42");+ });++ test("fail-closed: insert error rolls the enclosing tx back", async () => {+ let threw = false;+ try {+ await db.transaction(async (tx) => {+ await emitLoose(tx, teamCtx, {+ action: "monitor.create",+ entityType: "monitor",+ entityId: 9002,+ });+ throw new Error("simulated downstream failure");+ });+ } catch {+ threw = true;+ }+ expect(threw).toBe(true);+ const rows = await readAuditLog({+ workspaceId: teamCtx.workspace.id,+ entityType: "monitor",+ entityId: 9002,+ });+ expect(rows).toHaveLength(0);+ });+});++describe("emitAudit — changed_fields derivation", () => {+ test("null when only after is supplied (create-shape)", async () => {+ await db.transaction(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,+ });+ expect(row?.changedFields).toBeNull();+ });++ test("null when only before is supplied (delete-shape)", async () => {+ await db.transaction(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,+ });+ expect(row?.changedFields).toBeNull();+ });++ test("no-op update (before === after) skips the insert entirely", async () => {+ await db.transaction(async (tx) => {+ await emitAudit(tx, teamCtx, {+ action: "monitor.update",+ entityType: "monitor",+ entityId: 9102,+ before: { name: "same", url: "https://x" },+ after: { name: "same", url: "https://x" },+ });+ });+ 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 emitAudit(tx, teamCtx, {+ action: "monitor.update",+ entityType: "monitor",+ entityId: 9105,+ 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,+ });+ expect(rows).toHaveLength(0);+ });++ test("populated with the changed top-level keys", async () => {+ await db.transaction(async (tx) => {+ await emitAudit(tx, teamCtx, {+ action: "monitor.update",+ entityType: "monitor",+ entityId: 9103,+ 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,+ });+ 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 emitAudit(tx, teamCtx, {+ action: "monitor.update",+ entityType: "monitor",+ entityId: 9104,+ 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,+ });+ 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 emitLoose(tx, teamCtx, {+ action: "workspace.update",+ entityType: "workspace",+ entityId: teamCtx.workspace.id,+ });+ });+ 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 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,+ });+ 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 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,+ });+ 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 emitLoose(tx, ctx, {+ action: "maintenance.update",+ entityType: "maintenance",+ entityId: 9300,+ });+ });+ 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 emitLoose(tx, ctx, {+ action: "monitor.delete",+ entityType: "monitor",+ entityId: 9400,+ });+ });+ 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) => {+ for (let i = 0; i < 5; i++) {+ await emitLoose(tx, teamCtx, {+ action: "monitor.update",+ entityType: "monitor",+ entityId: 9500 + i,+ });+ }+ });+ 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 emitLoose(tx, teamCtx, {+ action: "monitor.update",+ entityType: "monitor",+ entityId: 9600,+ });+ });+ 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 emitAudit(tx, teamCtx, {+ // Cast through unknown — the runtime check is exactly the+ // point being tested; at compile time this would be a TS error.+ action: "monitor.bogus",+ 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,+ });+ expect(rows).toHaveLength(0);+ });++ test("rejects a mismatched entityType for a known action", async () => {+ let threw = false;+ try {+ await db.transaction(async (tx) => {+ await emitAudit(tx, teamCtx, {+ action: "monitor.create",+ // `monitor.create` is bound to entityType: "monitor"; this should+ // fail the discriminator.+ entityType: "page",+ entityId: 9701,+ } as unknown as AuditEntry);+ });+ } catch {+ threw = true;+ }+ expect(threw).toBe(true);+ });++ test("rejects a non-integer entityId", async () => {+ let threw = false;+ try {+ await db.transaction(async (tx) => {+ 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);+ });+});diff --git a/packages/services/src/audit/emit.ts b/packages/services/src/audit/emit.tsnew file mode 100644index 000000000..a4caf57a2--- /dev/null+++ b/packages/services/src/audit/emit.ts@@ -0,0 +1,141 @@+import { auditLog } from "@openstatus/db/src/schema";+import { type AuditEntry, auditEntrySchema } from "@openstatus/db/src/schema";++import {+ type DB,+ type ServiceContext,+ extractActorId,+ tryGetActorUserId,+} from "../context";++/** Keys excluded from the top-level diff — always churny, never informative. */+const DIFF_IGNORE = new Set(["updatedAt", "createdAt"]);++/**+ * Deep equality for audit snapshots. Order-independent for object keys,+ * order-sensitive for arrays. Dates compare by `.getTime()`.+ *+ * Hand-rolled on purpose — this package is consumed from the dashboard's+ * tRPC handlers, which run on the Next.js Edge runtime. Node built-ins+ * like `node:util` aren't available on Edge (surfaced as+ * `isDeepStrictEqual is not a function` via Turbopack). The local copy+ * covers the shapes we actually store in `before`/`after` (primitives,+ * arrays, plain objects, Dates) and keeps the services package Edge-safe.+ */+export function deepEqual(a: unknown, b: unknown): boolean {+ if (a === b) return true;+ if (a === null || b === null || a === undefined || b === undefined) {+ return false;+ }+ if (typeof a !== typeof b) return false;+ if (typeof a !== "object") return false;++ if (a instanceof Date || b instanceof Date) {+ return (+ a instanceof Date && b instanceof Date && a.getTime() === b.getTime()+ );+ }++ const aIsArr = Array.isArray(a);+ const bIsArr = Array.isArray(b);+ if (aIsArr !== bIsArr) return false;+ if (aIsArr && bIsArr) {+ if (a.length !== b.length) return false;+ for (let i = 0; i < a.length; i++) {+ if (!deepEqual(a[i], b[i])) return false;+ }+ return true;+ }++ const aObj = a as Record<string, unknown>;+ const bObj = b as Record<string, unknown>;+ const aKeys = Object.keys(aObj);+ const bKeys = Object.keys(bObj);+ if (aKeys.length !== bKeys.length) return false;+ for (const k of aKeys) {+ if (!Object.prototype.hasOwnProperty.call(bObj, k)) return false;+ if (!deepEqual(aObj[k], bObj[k])) return false;+ }+ return true;+}++/**+ * Shallow diff between two entity snapshots. Reports top-level keys that+ * differ. Nested JSON columns (headers, locales, configuration) report as+ * a single top-level key — the UI is responsible for deeper diffs.+ */+export function diffTopLevel(+ before: Record<string, unknown>,+ after: Record<string, unknown>,+): string[] {+ const keys = new Set([...Object.keys(before), ...Object.keys(after)]);+ const changed: string[] = [];+ for (const k of keys) {+ if (DIFF_IGNORE.has(k)) continue;+ const b = before[k];+ const a = after[k];+ // Treat `undefined` and `null` as absent so a nullable column reading+ // back as `null` from one source and `undefined` from another doesn't+ // register as a change.+ const bAbsent = b === undefined || b === null;+ const aAbsent = a === undefined || a === null;+ if (bAbsent && aAbsent) continue;+ if (bAbsent !== aAbsent) {+ changed.push(k);+ continue;+ }+ if (!deepEqual(b, a)) changed.push(k);+ }+ return changed;+}++/**+ * Write an audit row inside the caller's transaction. Fail-closed:+ * `auditEntrySchema.parse` throws a `ZodError` on invalid input,+ * propagating and rolling back the enclosing mutation.+ *+ * `changed_fields` is auto-computed when both `before` and `after` are+ * supplied. If either is missing (e.g. creates, deletes), the column is+ * `null`. An empty array means "both supplied, nothing changed" —+ * distinct from null.+ */+export async function emitAudit(+ tx: DB,+ ctx: ServiceContext,+ entry: AuditEntry,+): Promise<void> {+ const parsed = auditEntrySchema.parse(entry);++ const before = parsed.before;+ const after = parsed.after;+ const metadata = "metadata" in parsed ? parsed.metadata : undefined;++ const changedFields =+ before !== undefined && after !== undefined+ ? diffTopLevel(before, after)+ : null;++ // No-op update: caller passed both snapshots and nothing changed.+ // 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;++ const row = {+ workspaceId: ctx.workspace.id,+ actorType: ctx.actor.type,+ actorId: extractActorId(ctx.actor),+ actorUserId: tryGetActorUserId(ctx.actor),+ action: parsed.action,+ entityType: parsed.entityType,+ entityId: String(parsed.entityId),+ before: (before ?? null) as Record<string, unknown> | null,+ after: (after ?? null) as Record<string, unknown> | null,+ metadata: (metadata ?? null) as Record<string, unknown> | null,+ changedFields,+ };++ await tx.insert(auditLog).values(row);+}diff --git a/packages/services/src/audit/index.ts b/packages/services/src/audit/index.tsnew file mode 100644index 000000000..6a8a69298--- /dev/null+++ b/packages/services/src/audit/index.ts@@ -0,0 +1,15 @@+export {+ type AuditAction,+ type AuditActionName,+ auditActionSchema,+ type AuditEntityType,+ type AuditEntry,+ auditEntrySchema,+} from "@openstatus/db/src/schema";+export { diffTopLevel, emitAudit } from "./emit";+export {+ type AuditLogListItem,+ type ListAuditLogsResult,+ listAuditLogs,+} from "./list";+export { ListAuditLogsInput } from "./schemas";diff --git a/packages/services/src/audit/list.ts b/packages/services/src/audit/list.tsnew file mode 100644index 000000000..a7d707182--- /dev/null+++ b/packages/services/src/audit/list.ts@@ -0,0 +1,115 @@+import {+ type SQL,+ and,+ db as defaultDb,+ desc,+ eq,+ gte,+ isNull,+ sql,+} from "@openstatus/db";+import { auditLog, user } from "@openstatus/db/src/schema";++import type { ServiceContext } from "../context";+import { ListAuditLogsInput } from "./schemas";++/**+ * Fixed read window for the dashboard audit-log viewer.+ *+ * Keeps payloads bounded without a configurable limit, and caps what a+ * leaked/compromised session can exfiltrate from the table. Retention+ * policy is a separate lever (PR 3+); this is the *read* cap.+ */+const READ_WINDOW_DAYS = 14;++export type AuditLogListItem = typeof auditLog.$inferSelect & {+ user: {+ id: number;+ name: string | null;+ email: string | null;+ photoUrl: string | null;+ } | null;+};++export type ListAuditLogsResult = {+ items: AuditLogListItem[];+ totalSize: number;+};++/**+ * List audit-log rows for the caller's workspace, optionally scoped+ * to a single entity. Bounded to the last `READ_WINDOW_DAYS`.+ *+ * `audit_log` has no FK to `user` (rows outlive their subjects), so we+ * use a left join — rows whose `actorUserId` is null (system / webhook+ * / unlinked api-key actors) or whose user has been soft-deleted still+ * come back with `user: null`.+ *+ * Sort is `(createdAt DESC, id DESC)` — bulk operations emit multiple+ * rows in the same millisecond; the autoincrement id gives a+ * deterministic tiebreaker.+ */+export async function listAuditLogs(args: {+ ctx: ServiceContext;+ input?: ListAuditLogsInput;+}): Promise<ListAuditLogsResult> {+ const { ctx } = args;+ const input = ListAuditLogsInput.parse(args.input);+ const db = ctx.db ?? defaultDb;++ const since = new Date(Date.now() - READ_WINDOW_DAYS * 24 * 60 * 60 * 1000);++ const conditions: SQL[] = [+ eq(auditLog.workspaceId, ctx.workspace.id),+ gte(auditLog.createdAt, since),+ ];+ if (input.entityType) {+ conditions.push(eq(auditLog.entityType, input.entityType));+ }+ if (input.entityId) {+ conditions.push(eq(auditLog.entityId, input.entityId));+ }+ const whereClause = and(...conditions);++ // Count and page queries run in parallel outside a transaction — a+ // concurrent insert between them can leave `totalSize` one off from the+ // returned page. Best-effort is fine for list pagination.+ const [countRow, rows] = await Promise.all([+ db+ .select({ count: sql<number>`count(*)` })+ .from(auditLog)+ .where(whereClause)+ .get(),+ db+ .select({+ auditLog,+ user: {+ id: user.id,+ name: user.name,+ email: user.email,+ photoUrl: user.photoUrl,+ },+ })+ .from(auditLog)+ // Narrow the join so soft-deleted users don't surface as actors.+ // `deleteAccount` preserves the row (deletedAt + PII wipe), which+ // a bare `eq(user.id, actorUserId)` would still match, returning a+ // user object with blanked fields instead of `user: null`. Readers+ // can't distinguish that from a real actor without the `isNull`.+ .leftJoin(+ user,+ and(eq(user.id, auditLog.actorUserId), isNull(user.deletedAt)),+ )+ .where(whereClause)+ .orderBy(desc(auditLog.createdAt), desc(auditLog.id))+ .limit(input.limit)+ .offset(input.offset)+ .all(),+ ]);++ const items = rows.map((row) => ({+ ...row.auditLog,+ user: row.user?.id != null ? row.user : null,+ }));+ return { items, totalSize: countRow?.count ?? 0 };+}diff --git a/packages/services/src/audit/schemas.ts b/packages/services/src/audit/schemas.tsnew file mode 100644index 000000000..3fa047c58--- /dev/null+++ b/packages/services/src/audit/schemas.ts@@ -0,0 +1,17 @@+import { z } from "zod";++/**+ * Scope a list query to an entity. Both `entityType`/`entityId` are+ * optional — omitting them returns the whole workspace log within the+ * fixed read window. `limit` is hard-capped at 5,000 to bound the response+ * size; the time window alone doesn't (a busy workspace can emit tens of+ * thousands of rows in 14 days).+ */+export const ListAuditLogsInput = z.object({+ entityType: z.string().optional(),+ entityId: z.string().optional(),+ limit: z.number().int().min(1).default(5_000),+ offset: z.number().int().min(0).default(0),+});++export type ListAuditLogsInput = z.infer<typeof ListAuditLogsInput>;diff --git a/packages/services/src/import/phase-writers.ts b/packages/services/src/import/phase-writers.tsindex 5831aee1a..29a25a63e 100644--- a/packages/services/src/import/phase-writers.ts+++ b/packages/services/src/import/phase-writers.ts@@ -139,7 +139,7 @@ export async function writePagePhase(published: data.published,icon: data.icon,})- .returning({ id: page.id });+ .returning();if (!inserted) throw new Error("Failed to insert page");@@ -152,6 +152,7 @@ export async function writePagePhase(entityType: "page",entityId: inserted.id,metadata: auditMeta(pc, { sourceId: resource.sourceId, slug: data.slug }),+ after: inserted,});return inserted.id;@@ -195,7 +196,7 @@ export async function writeComponentGroupsPhase(const [inserted] = await tx.insert(pageComponentGroup).values({ workspaceId, pageId, name: data.name })- .returning({ id: pageComponentGroup.id });+ .returning();if (!inserted) {resource.status = "failed";@@ -211,6 +212,7 @@ export async function writeComponentGroupsPhase(action: "page_component_group.create",entityType: "page_component_group",entityId: inserted.id,+ after: inserted,metadata: auditMeta(pc, {sourceId: resource.sourceId,pageId,@@ -308,7 +310,7 @@ export async function writeComponentsPhase(order: data.order,groupId: resolvedGroupId,})- .returning({ id: pageComponent.id });+ .returning();if (!inserted) {resource.status = "failed";@@ -329,6 +331,7 @@ export async function writeComponentsPhase(pageId,type: data.type,}),+ after: inserted,});} catch (err) {resource.status = "failed";@@ -417,7 +420,7 @@ export async function writeIncidentsPhase(workspaceId,pageId,})- .returning({ id: statusReport.id });+ .returning();if (!insertedReport) {resource.status = "failed";@@ -434,6 +437,7 @@ export async function writeIncidentsPhase(pageId,title: data.report.title,}),+ after: insertedReport,});// Batch the update rows with `.returning()` so per-update audit can@@ -449,17 +453,18 @@ export async function writeIncidentsPhase(statusReportId: insertedReport.id,})),)- .returning({ id: statusReportUpdate.id });+ .returning();for (const row of insertedUpdates) {await emitAudit(tx, ctx, {- action: "status_report.add_update",+ action: "status_report_update.create",entityType: "status_report_update",entityId: row.id,metadata: auditMeta(pc, {sourceId: resource.sourceId,statusReportId: insertedReport.id,}),+ after: row,});}}@@ -567,7 +572,7 @@ export async function writeMaintenancesPhase(workspaceId,pageId,})- .returning({ id: maintenance.id });+ .returning();if (!inserted) {resource.status = "failed";@@ -604,6 +609,7 @@ export async function writeMaintenancesPhase(pageId,title: data.title,}),+ after: inserted,});} catch (err) {resource.status = "failed";@@ -731,7 +737,7 @@ export async function writeMonitorsPhase(| "OPTIONS",timeout: data.timeout,})- .returning({ id: monitor.id });+ .returning();if (!inserted) {resource.status = "failed";@@ -753,6 +759,7 @@ export async function writeMonitorsPhase(url: data.url,jobType: data.jobType,}),+ after: inserted,});} catch (err) {resource.status = "failed";@@ -829,7 +836,7 @@ export async function writeSubscribersPhase(token: crypto.randomUUID(),acceptedAt: data.confirmed ? new Date() : undefined,})- .returning({ id: pageSubscriber.id });+ .returning();if (!inserted) {resource.status = "failed";@@ -857,6 +864,9 @@ export async function writeSubscribersPhase(resource.openstatusId = inserted.id;resource.status = "created";+ // Strip `token` — it's the unsubscribe / management capability+ // link. Everything else on the row is fine to audit.+ const { token: _token, ...safe } = inserted;await emitAudit(tx, ctx, {action: "page_subscriber.create",entityType: "page_subscriber",@@ -866,6 +876,7 @@ export async function writeSubscribersPhase(pageId,email,}),+ after: safe,});} catch (err) {resource.status = "failed";diff --git a/packages/services/src/import/run.ts b/packages/services/src/import/run.tsindex 22051dbad..27c3e18ab 100644--- a/packages/services/src/import/run.ts+++ b/packages/services/src/import/run.ts@@ -2,7 +2,6 @@ import { and, count, db as defaultDb, eq } from "@openstatus/db";import { page, pageComponent } from "@openstatus/db/src/schema";import type { ImportSummary } from "@openstatus/importers";-import { emitAudit } from "../audit";import type { ServiceContext } from "../context";import { NotFoundError, ValidationError } from "../errors";import { addLimitWarnings } from "./limits";@@ -29,15 +28,12 @@ import { RunImportInput } from "./schemas";* failing phase aborts subsequent phases but preserves earlier phases'* writes.*- * Audit emission is two-layered:- * - Each phase writer emits per-resource rows (`page.create`,- * `monitor.create`, etc.) for every resource it actually creates,- * matching what the domain services would have emitted for normal- * CRUD. Skipped rows have their original create audit already;- * failed rows have nothing to attribute.- * - One final `import.run` row captures the rollup (status + provider)- * so a half-broken import still shows up as a single event without- * having to scan per-resource audit.+ * Audit emission: each phase writer emits per-resource rows+ * (`page.create`, `monitor.create`, etc.) for every resource it+ * actually creates, matching what the domain services would emit for+ * normal CRUD. Skipped rows have their original create audit already;+ * failed rows have nothing to attribute. No rollup row — the action+ * union only allows create/update/delete verbs per entity.*/export async function runImport(args: {ctx: ServiceContext;@@ -247,41 +243,5 @@ export async function runImport(args: {: "partial";summary.completedAt = new Date();- // Rollup audit: per-resource rows live inside each phase writer; this- // row summarises the whole run so partial/failed imports still fire- // the observability signal without scanning the full summary blob.- //- // Entity attribution matches what the run actually touched. When a- // page was created or reused (`targetPageId` is set) the row points- // at it; when the page phase failed early and no page is in play we- // fall back to the workspace so the audit never carries a ghost- // `page 0` reference that breaks downstream "find audits for this- // entity" queries.- await emitAudit(- tx,- ctx,- targetPageId- ? {- action: "import.run",- entityType: "page",- entityId: targetPageId,- metadata: {- provider: input.provider,- status: summary.status,- pageId: targetPageId,- },- }- : {- action: "import.run",- entityType: "workspace",- entityId: ctx.workspace.id,- metadata: {- provider: input.provider,- status: summary.status,- pageId: null,- },- },- );-return summary;}diff --git a/packages/services/src/incident/__tests__/incident.test.ts b/packages/services/src/incident/__tests__/incident.test.tsindex a850370ec..55b10466e 100644--- a/packages/services/src/incident/__tests__/incident.test.ts+++ b/packages/services/src/incident/__tests__/incident.test.ts@@ -1,6 +1,5 @@import {afterAll,- afterEach,beforeAll,beforeEach,describe,@@ -15,12 +14,11 @@ import {SEEDED_WORKSPACE_TEAM_ID,} from "../../../test/fixtures";import {+ clearAuditLog,expectAuditRow,loadSeededWorkspace,makeUserCtx,- withAuditBuffer,} from "../../../test/helpers";-import type { AuditLogRecord } from "../../audit";import type { ServiceContext } from "../../context";import { ConflictError, NotFoundError } from "../../errors";import { acknowledgeIncident } from "../acknowledge";@@ -33,8 +31,6 @@ const TEST_PREFIX = "svc-incident-test";let teamCtx: ServiceContext;let freeCtx: ServiceContext;let testMonitorId: number;-let auditBuffer: AuditLogRecord[];-let auditReset: () => void;beforeAll(async () => {const team = await loadSeededWorkspace(SEEDED_WORKSPACE_TEAM_ID);@@ -65,14 +61,9 @@ afterAll(async () => {.catch(() => undefined);});-beforeEach(() => {- const hooks = withAuditBuffer();- auditBuffer = hooks.buffer;- auditReset = hooks.reset;-});--afterEach(() => {- auditReset();+beforeEach(async () => {+ await clearAuditLog(teamCtx.workspace.id);+ await clearAuditLog(freeCtx.workspace.id);});let nextStartedAtOffset = 0;@@ -114,8 +105,9 @@ describe("acknowledgeIncident", () => {expect(updated.acknowledgedAt).toBeInstanceOf(Date);expect(updated.acknowledgedBy).toBe(1);- await expectAuditRow(auditBuffer, {- action: "incident.acknowledge",+ await expectAuditRow({+ workspaceId: teamCtx.workspace.id,+ action: "incident.update",entityType: "incident",entityId: incident.id,});@@ -212,7 +204,8 @@ describe("deleteIncident", () => {.all();expect(remaining).toHaveLength(0);- await expectAuditRow(auditBuffer, {+ await expectAuditRow({+ workspaceId: teamCtx.workspace.id,action: "incident.delete",entityType: "incident",entityId: incident.id,diff --git a/packages/services/src/incident/acknowledge.ts b/packages/services/src/incident/acknowledge.tsindex 65f4aa0b4..f5985fb26 100644--- a/packages/services/src/incident/acknowledge.ts+++ b/packages/services/src/incident/acknowledge.ts@@ -54,7 +54,7 @@ export async function acknowledgeIncident(args: {}await emitAudit(tx, ctx, {- action: "incident.acknowledge",+ action: "incident.update",entityType: "incident",entityId: updated.id,before: existing,diff --git a/packages/services/src/incident/resolve.ts b/packages/services/src/incident/resolve.tsindex 08dcfb557..c0f3ffa12 100644--- a/packages/services/src/incident/resolve.ts+++ b/packages/services/src/incident/resolve.ts@@ -53,7 +53,7 @@ export async function resolveIncident(args: {}await emitAudit(tx, ctx, {- action: "incident.resolve",+ action: "incident.update",entityType: "incident",entityId: updated.id,before: existing,diff --git a/packages/services/src/index.ts b/packages/services/src/index.tsindex de22cef5c..0902cf78e 100644--- a/packages/services/src/index.ts+++ b/packages/services/src/index.ts@@ -24,11 +24,14 @@ export {} from "./errors";export {+ type AuditAction,+ type AuditActionName,+ auditActionSchema,+ type AuditEntityType,type AuditEntry,- type AuditLogRecord,+ auditEntrySchema,+ diffTopLevel,emitAudit,- installTestAuditBuffer,- uninstallTestAuditBuffer,} from "./audit";export {diff --git a/packages/services/src/invitation/__tests__/invitation.test.ts b/packages/services/src/invitation/__tests__/invitation.test.tsindex f6b47cd3e..fc73d4e7a 100644--- a/packages/services/src/invitation/__tests__/invitation.test.ts+++ b/packages/services/src/invitation/__tests__/invitation.test.ts@@ -1,6 +1,5 @@import {afterAll,- afterEach,beforeAll,beforeEach,describe,@@ -22,12 +21,11 @@ import {SEEDED_WORKSPACE_TEAM_ID,} from "../../../test/fixtures";import {+ clearAuditLog,expectAuditRow,loadSeededWorkspace,makeUserCtx,- withAuditBuffer,} from "../../../test/helpers";-import type { AuditLogRecord } from "../../audit";import type { ServiceContext } from "../../context";import { LimitExceededError, NotFoundError } from "../../errors";@@ -35,8 +33,6 @@ const TEST_PREFIX = "svc-inv-test";let teamCtx: ServiceContext;let freeCtx: ServiceContext;-let auditBuffer: AuditLogRecord[];-let auditReset: () => void;const createdInvitationIds: number[] = [];beforeAll(async () => {@@ -102,12 +98,10 @@ afterAll(async () => {.catch(() => undefined);});-beforeEach(() => {- const session = withAuditBuffer();- auditBuffer = session.buffer;- auditReset = session.reset;+beforeEach(async () => {+ await clearAuditLog(teamCtx.workspace.id);+ await clearAuditLog(freeCtx.workspace.id);});-afterEach(() => auditReset());describe("createInvitation", () => {test("creates an invitation scoped to the caller's workspace", async () => {@@ -123,7 +117,8 @@ describe("createInvitation", () => {expect(row.token).toBeDefined();expect(row.expiresAt.getTime()).toBeGreaterThan(Date.now());- await expectAuditRow(auditBuffer, {+ await expectAuditRow({+ workspaceId: teamCtx.workspace.id,action: "invitation.create",entityType: "invitation",entityId: row.id,diff --git a/packages/services/src/invitation/accept.ts b/packages/services/src/invitation/accept.tsindex 84aa3cc92..daf00b85f 100644--- a/packages/services/src/invitation/accept.ts+++ b/packages/services/src/invitation/accept.ts@@ -72,9 +72,10 @@ export async function acceptInvitation(args: {// re-asserted here to close a TOCTOU gap: without it, an invitation// whose expiry is exactly the moment between the read and the write// can be silently accepted past the deadline.+ const acceptedAt = new Date();const claimed = await tx.update(invitation)- .set({ acceptedAt: new Date() })+ .set({ acceptedAt }).where(and(eq(invitation.id, input.id),@@ -108,11 +109,15 @@ export async function acceptInvitation(args: {throw new NotFoundError("workspace", existing.workspaceId);}+ // Strip `token` (email-link capability) from the snapshot; construct the snapshots from the pre-fetched row+ // to avoid a second SELECT after the UPDATE.+ const { token: _token, ...before } = existing;await emitAudit(tx, ctx, {- action: "invitation.accept",+ action: "invitation.update",entityType: "invitation",entityId: input.id,- metadata: { workspaceId: existing.workspaceId, role: existing.role },+ before,+ after: { ...before, acceptedAt },});return selectWorkspaceSchema.parse(existing.workspace);diff --git a/packages/services/src/invitation/create.ts b/packages/services/src/invitation/create.tsindex b86a8fce1..1c8fbc7dc 100644--- a/packages/services/src/invitation/create.ts+++ b/packages/services/src/invitation/create.ts@@ -1,5 +1,9 @@import { and, eq, gte, isNull } from "@openstatus/db";-import { invitation, usersToWorkspaces } from "@openstatus/db/src/schema";+import {+ invitation,+ selectInvitationSchema,+ usersToWorkspaces,+} from "@openstatus/db/src/schema";import { emitAudit } from "../audit";import { type ServiceContext, withTransaction } from "../context";@@ -85,13 +89,16 @@ export async function createInvitation(args: {);}+ // Strip `token` — it's the email-link capability, never audit it.+ // Everything else on the row is fine as an `after` snapshot.+ const { token: _token, ...safe } = row;await emitAudit(tx, ctx, {action: "invitation.create",entityType: "invitation",entityId: row.id,- metadata: { email: input.email },+ after: safe,});- return row as Invitation;+ return selectInvitationSchema.parse(row);});}diff --git a/packages/services/src/invitation/delete.ts b/packages/services/src/invitation/delete.tsindex 01cbed3cc..a2bf82e39 100644--- a/packages/services/src/invitation/delete.ts+++ b/packages/services/src/invitation/delete.ts@@ -28,7 +28,10 @@ export async function deleteInvitation(args: {const input = DeleteInvitationInput.parse(args.input);await withTransaction(ctx, async (tx) => {- const deleted = await tx+ // `.returning()` the full row so we don't need a separate SELECT+ // for the audit snapshot. `token` (email-link capability) is+ // stripped before emitting; everything else is safe.+ const [deleted] = await tx.delete(invitation).where(and(@@ -37,14 +40,16 @@ export async function deleteInvitation(args: {isNull(invitation.acceptedAt),),)- .returning({ id: invitation.id });+ .returning();- if (deleted.length === 0) return;+ if (!deleted) return;+ const { token: _token, ...before } = deleted;await emitAudit(tx, ctx, {action: "invitation.delete",entityType: "invitation",entityId: input.id,+ before,});});}diff --git a/packages/services/src/invitation/list.ts b/packages/services/src/invitation/list.tsindex 5090d96ae..ae607b670 100644--- a/packages/services/src/invitation/list.ts+++ b/packages/services/src/invitation/list.ts@@ -32,7 +32,7 @@ export async function listInvitations(args: {),});- return rows as Invitation[];+ return rows.map((r) => selectInvitationSchema.parse(r));}export type InvitationWithWorkspace = Invitation & { workspace: Workspace };@@ -68,5 +68,5 @@ export async function getInvitationByToken(args: {return selectInvitationSchema.extend({ workspace: selectWorkspaceSchema })- .parse(result) as InvitationWithWorkspace;+ .parse(result);}diff --git a/packages/services/src/maintenance/__tests__/maintenance.test.ts b/packages/services/src/maintenance/__tests__/maintenance.test.tsindex 680b23bd3..087575a1e 100644--- a/packages/services/src/maintenance/__tests__/maintenance.test.ts+++ b/packages/services/src/maintenance/__tests__/maintenance.test.ts@@ -20,13 +20,12 @@ import {SEEDED_WORKSPACE_TEAM_ID,} from "../../../test/fixtures";import {+ clearAuditLog,expectAuditRow,loadSeededWorkspace,makeSlackCtx,makeUserCtx,- withAuditBuffer,} from "../../../test/helpers";-import type { AuditLogRecord } from "../../audit";import type { ServiceContext } from "../../context";import { ConflictError, ForbiddenError, NotFoundError } from "../../errors";import { createMaintenance } from "../create";@@ -55,8 +54,6 @@ let testPageComponentId: number;// "all components must share a page" ConflictError branch.let otherPageId: number;let otherPageComponentId: number;-let auditBuffer: AuditLogRecord[];-let auditReset: () => void;/*** Tests push created maintenance ids here instead of issuing an inline@@ -137,15 +134,13 @@ afterAll(async () => {.catch(() => undefined);});-beforeEach(() => {- const hooks = withAuditBuffer();- auditBuffer = hooks.buffer;- auditReset = hooks.reset;+beforeEach(async () => {+ await clearAuditLog(teamCtx.workspace.id);+ await clearAuditLog(freeCtx.workspace.id);subscriptionSpies?.dispatchMaintenanceUpdate.mockClear();});afterEach(async () => {- auditReset();if (createdMaintenanceIds.length > 0) {await db.delete(maintenance)@@ -187,7 +182,8 @@ describe("createMaintenance", () => {.all();expect(assoc.map((a) => a.pageComponentId)).toEqual([testPageComponentId]);- await expectAuditRow(auditBuffer, {+ await expectAuditRow({+ workspaceId: teamCtx.workspace.id,action: "maintenance.create",entityType: "maintenance",entityId: record.id,@@ -502,7 +498,8 @@ describe("slack actor path", () => {pageComponentIds: [],},});- await expectAuditRow(auditBuffer, {+ await expectAuditRow({+ workspaceId: teamCtx.workspace.id,action: "maintenance.create",entityType: "maintenance",entityId: record.id,diff --git a/packages/services/src/maintenance/list.ts b/packages/services/src/maintenance/list.tsindex aab0231c0..c1454e809 100644--- a/packages/services/src/maintenance/list.ts+++ b/packages/services/src/maintenance/list.ts@@ -13,6 +13,7 @@ import {maintenance,maintenancesToPageComponents,pageComponent,+ selectPageComponentSchema,} from "@openstatus/db/src/schema";import type { DB, ServiceContext } from "../context";@@ -59,8 +60,15 @@ async function enrichMaintenancesBatch(if (rows.length === 0) return [];const ids = rows.map((r) => r.id);+ // Explicit column selection (not `select()`) keeps the row shape in our+ // hands instead of relying on drizzle's auto-derived `row.<table_name>`+ // keys, which are named after the JS variable and silently break on+ // schema rename.const assocRows = await db- .select()+ .select({+ maintenanceId: maintenancesToPageComponents.maintenanceId,+ component: pageComponent,+ }).from(pageComponent).innerJoin(maintenancesToPageComponents,@@ -71,12 +79,10 @@ async function enrichMaintenancesBatch(const componentsByMaintenance = new Map<number, PageComponent[]>();for (const row of assocRows) {- const mId = (row.maintenance_to_page_component as { maintenanceId: number })- .maintenanceId;- const component = row.page_component as unknown as PageComponent;- const arr = componentsByMaintenance.get(mId);+ const component = selectPageComponentSchema.parse(row.component);+ const arr = componentsByMaintenance.get(row.maintenanceId);if (arr) arr.push(component);- else componentsByMaintenance.set(mId, [component]);+ else componentsByMaintenance.set(row.maintenanceId, [component]);}return rows.map((r) => {diff --git a/packages/services/src/maintenance/notify.ts b/packages/services/src/maintenance/notify.tsindex f088cde04..8abd446d6 100644--- a/packages/services/src/maintenance/notify.ts+++ b/packages/services/src/maintenance/notify.ts@@ -2,7 +2,6 @@ import { db as defaultDb, eq } from "@openstatus/db";import { maintenance } from "@openstatus/db/src/schema";import { dispatchMaintenanceUpdate } from "@openstatus/subscriptions";-import { emitAudit } from "../audit";import type { ServiceContext } from "../context";import { ForbiddenError, NotFoundError } from "../errors";import { NotifyMaintenanceInput } from "./schemas";@@ -42,10 +41,4 @@ export async function notifyMaintenance(args: {}await dispatchMaintenanceUpdate(input.maintenanceId);-- await emitAudit(db, ctx, {- action: "maintenance.notify",- entityType: "maintenance",- entityId: input.maintenanceId,- });}diff --git a/packages/services/src/monitor/__tests__/monitor.test.ts b/packages/services/src/monitor/__tests__/monitor.test.tsindex 9a1c797a8..ee04acece 100644--- a/packages/services/src/monitor/__tests__/monitor.test.ts+++ b/packages/services/src/monitor/__tests__/monitor.test.ts@@ -1,6 +1,5 @@import {afterAll,- afterEach,beforeAll,beforeEach,describe,@@ -21,12 +20,11 @@ import {SEEDED_WORKSPACE_TEAM_ID,} from "../../../test/fixtures";import {+ clearAuditLog,expectAuditRow,loadSeededWorkspace,makeUserCtx,- withAuditBuffer,} from "../../../test/helpers";-import type { AuditLogRecord } from "../../audit";import type { ServiceContext } from "../../context";import { ForbiddenError, NotFoundError } from "../../errors";import { cloneMonitor } from "../clone";@@ -42,8 +40,6 @@ let teamCtx: ServiceContext;let freeCtx: ServiceContext;let testTagId: number;let testNotificationId: number;-let auditBuffer: AuditLogRecord[];-let auditReset: () => void;const createdMonitorIds: number[] = [];beforeAll(async () => {@@ -93,14 +89,9 @@ afterAll(async () => {.catch(() => undefined);});-beforeEach(() => {- const hooks = withAuditBuffer();- auditBuffer = hooks.buffer;- auditReset = hooks.reset;-});--afterEach(() => {- auditReset();+beforeEach(async () => {+ await clearAuditLog(teamCtx.workspace.id);+ await clearAuditLog(freeCtx.workspace.id);});function track(id: number) {@@ -128,7 +119,8 @@ describe("createMonitor", () => {expect(row.url).toBe("https://example.com");expect(row.regions.length).toBeGreaterThan(0);- await expectAuditRow(auditBuffer, {+ await expectAuditRow({+ workspaceId: teamCtx.workspace.id,action: "monitor.create",entityType: "monitor",entityId: row.id,@@ -548,8 +540,9 @@ describe("updateMonitorGeneral", () => {expect(updated.name).toBe(`${TEST_PREFIX}-gen-renamed`);expect(updated.url).toBe("https://example.org");expect(updated.method).toBe("POST");- await expectAuditRow(auditBuffer, {- action: "monitor.update_general",+ await expectAuditRow({+ workspaceId: teamCtx.workspace.id,+ action: "monitor.update",entityType: "monitor",entityId: row.id,});diff --git a/packages/services/src/monitor/clone.ts b/packages/services/src/monitor/clone.tsindex 7b59ab445..35db6643d 100644--- a/packages/services/src/monitor/clone.ts+++ b/packages/services/src/monitor/clone.ts@@ -49,10 +49,11 @@ export async function cloneMonitor(args: {}await emitAudit(tx, ctx, {- action: "monitor.clone",+ action: "monitor.create",entityType: "monitor",entityId: row.id,- metadata: { sourceMonitorId: source.id },+ after: row,+ metadata: { clonedFromMonitorId: source.id },});return selectMonitorSchema.parse(row);diff --git a/packages/services/src/monitor/list.ts b/packages/services/src/monitor/list.tsindex 49ac53ed5..23f9fd637 100644--- a/packages/services/src/monitor/list.ts+++ b/packages/services/src/monitor/list.ts@@ -18,7 +18,11 @@ import {notificationsToMonitors,privateLocation,privateLocationToMonitors,+ selectIncidentSchema,selectMonitorSchema,+ selectMonitorTagSchema,+ selectNotificationSchema,+ selectPrivateLocationSchema,} from "@openstatus/db/src/schema";import type { DB, ServiceContext } from "../context";@@ -64,9 +68,16 @@ async function enrichMonitorsBatch(if (rows.length === 0) return [];const ids = rows.map((r) => r.id);+ // Explicit column selection (not `select()`) keeps the join row shape in+ // our hands instead of relying on drizzle's auto-derived `row.<table_name>`+ // keys, which are named after the JS variable and silently break on+ // schema rename.const [tagRows, incidentRows, notifRows, locRows] = await Promise.all([db- .select()+ .select({+ monitorId: monitorTagsToMonitors.monitorId,+ tag: monitorTag,+ }).from(monitorTag).innerJoin(monitorTagsToMonitors,@@ -94,7 +105,10 @@ async function enrichMonitorsBatch(.all(),include.notifications? db- .select()+ .select({+ monitorId: notificationsToMonitors.monitorId,+ notification,+ }).from(notification).innerJoin(notificationsToMonitors,@@ -107,10 +121,13 @@ async function enrichMonitorsBatch(),).all()- : Promise.resolve([] as never[]),+ : Promise.resolve([]),include.privateLocations? db- .select()+ .select({+ monitorId: privateLocationToMonitors.monitorId,+ location: privateLocation,+ }).from(privateLocation).innerJoin(privateLocationToMonitors,@@ -123,48 +140,41 @@ async function enrichMonitorsBatch(),).all()- : Promise.resolve([] as never[]),+ : Promise.resolve([]),]);const tagsByMonitor = new Map<number, MonitorTag[]>();- for (const row of tagRows as Array<{- monitor_tag: MonitorTag;- monitor_tag_to_monitor: { monitorId: number };- }>) {- const mId = row.monitor_tag_to_monitor.monitorId;- const arr = tagsByMonitor.get(mId);- if (arr) arr.push(row.monitor_tag);- else tagsByMonitor.set(mId, [row.monitor_tag]);+ for (const row of tagRows) {+ const tag = selectMonitorTagSchema.parse(row.tag);+ const arr = tagsByMonitor.get(row.monitorId);+ if (arr) arr.push(tag);+ else tagsByMonitor.set(row.monitorId, [tag]);}const incidentsByMonitor = new Map<number, Incident[]>();- for (const row of incidentRows as Incident[]) {+ for (const row of incidentRows) {if (row.monitorId == null) continue;+ const incident = selectIncidentSchema.parse(row);const arr = incidentsByMonitor.get(row.monitorId);- if (arr) arr.push(row);- else incidentsByMonitor.set(row.monitorId, [row]);+ if (arr) arr.push(incident);+ else incidentsByMonitor.set(row.monitorId, [incident]);}const notifsByMonitor = new Map<number, Notification[]>();- for (const row of notifRows as Array<{- notification: Notification;- notifications_to_monitors: { monitorId: number };- }>) {- const mId = row.notifications_to_monitors.monitorId;- const arr = notifsByMonitor.get(mId);- if (arr) arr.push(row.notification);- else notifsByMonitor.set(mId, [row.notification]);+ for (const row of notifRows) {+ const parsed = selectNotificationSchema.parse(row.notification);+ const arr = notifsByMonitor.get(row.monitorId);+ if (arr) arr.push(parsed);+ else notifsByMonitor.set(row.monitorId, [parsed]);}const locsByMonitor = new Map<number, PrivateLocation[]>();- for (const row of locRows as Array<{- private_location: PrivateLocation;- private_location_to_monitor: { monitorId: number };- }>) {- const mId = row.private_location_to_monitor.monitorId;- const arr = locsByMonitor.get(mId);- if (arr) arr.push(row.private_location);- else locsByMonitor.set(mId, [row.private_location]);+ for (const row of locRows) {+ if (row.monitorId == null) continue;+ const parsed = selectPrivateLocationSchema.parse(row.location);+ const arr = locsByMonitor.get(row.monitorId);+ if (arr) arr.push(parsed);+ else locsByMonitor.set(row.monitorId, [parsed]);}return rows.map((r) => ({diff --git a/packages/services/src/monitor/relations.ts b/packages/services/src/monitor/relations.tsindex ebfb565e7..1ecfc858f 100644--- a/packages/services/src/monitor/relations.ts+++ b/packages/services/src/monitor/relations.ts@@ -62,14 +62,16 @@ export async function updateMonitorSchedulingRegions(args: {privateLocationIds: input.privateLocations,});- await tx+ const updated = await tx.update(monitor).set({regions: input.regions.join(","),periodicity: input.periodicity,updatedAt: new Date(),})- .where(eq(monitor.id, existing.id));+ .where(eq(monitor.id, existing.id))+ .returning()+ .get();await tx.delete(privateLocationToMonitors)@@ -83,15 +85,15 @@ export async function updateMonitorSchedulingRegions(args: {);}+ // `before`/`after` carry the `regions` + `periodicity` diff.+ // Private-location membership lives in a join table and isn't+ // reflected in the snapshot — documented gap, not a bug.await emitAudit(tx, ctx, {- action: "monitor.update_scheduling_regions",+ action: "monitor.update",entityType: "monitor",entityId: existing.id,- metadata: {- regions: input.regions,- periodicity: input.periodicity,- privateLocationIds: validatedLocations,- },+ before: existing,+ after: updated,});});}@@ -116,6 +118,17 @@ export async function updateMonitorTags(args: {tagIds: input.tags,});+ // Capture the pre-mutation tag set *before* the delete — tag+ // membership lives on the join table so the "before" snapshot must+ // be read while the old rows still exist.+ const existingTagIds = (+ await tx+ .select({ tagId: monitorTagsToMonitors.monitorTagId })+ .from(monitorTagsToMonitors)+ .where(eq(monitorTagsToMonitors.monitorId, existing.id))+ .all()+ ).map((r) => r.tagId);+await tx.delete(monitorTagsToMonitors).where(eq(monitorTagsToMonitors.monitorId, existing.id));@@ -129,10 +142,11 @@ export async function updateMonitorTags(args: {}await emitAudit(tx, ctx, {- action: "monitor.update_tags",+ action: "monitor.update",entityType: "monitor",entityId: existing.id,- metadata: { tagIds: validatedTags },+ before: { tagIds: [...existingTagIds].sort() },+ after: { tagIds: [...validatedTags].sort() },});});}@@ -157,6 +171,17 @@ export async function updateMonitorNotifiers(args: {notificationIds: input.notifiers,});+ // Capture the pre-mutation notifier set *before* the delete — the+ // relation lives on the join table so reading it after we'd wipe+ // the old rows would record the new state as the "before".+ const existingNotifierIds = (+ await tx+ .select({ notificationId: notificationsToMonitors.notificationId })+ .from(notificationsToMonitors)+ .where(eq(notificationsToMonitors.monitorId, existing.id))+ .all()+ ).map((r) => r.notificationId);+await tx.delete(notificationsToMonitors).where(eq(notificationsToMonitors.monitorId, existing.id));@@ -170,10 +195,11 @@ export async function updateMonitorNotifiers(args: {}await emitAudit(tx, ctx, {- action: "monitor.update_notifiers",+ action: "monitor.update",entityType: "monitor",entityId: existing.id,- metadata: { notificationIds: validatedNotifiers },+ before: { notificationIds: [...existingNotifierIds].sort() },+ after: { notificationIds: [...validatedNotifiers].sort() },});});}diff --git a/packages/services/src/monitor/update.ts b/packages/services/src/monitor/update.tsindex 018ce2237..e2ffb608c 100644--- a/packages/services/src/monitor/update.ts+++ b/packages/services/src/monitor/update.ts@@ -57,7 +57,7 @@ export async function updateMonitorGeneral(args: {.get();await emitAudit(tx, ctx, {- action: "monitor.update_general",+ action: "monitor.update",entityType: "monitor",entityId: existing.id,before: existing,@@ -80,16 +80,18 @@ export async function updateMonitorRetry(args: {id: input.id,workspaceId: ctx.workspace.id,});- await tx+ const updated = await tx.update(monitor).set({ retry: input.retry, updatedAt: new Date() }).where(eq(monitor.id, existing.id))- .run();+ .returning()+ .get();await emitAudit(tx, ctx, {- action: "monitor.update_retry",+ action: "monitor.update",entityType: "monitor",entityId: existing.id,- metadata: { retry: input.retry },+ before: existing,+ after: updated,});});}@@ -106,16 +108,18 @@ export async function updateMonitorFollowRedirects(args: {id: input.id,workspaceId: ctx.workspace.id,});- await tx+ const updated = await tx.update(monitor).set({ followRedirects: input.followRedirects, updatedAt: new Date() }).where(eq(monitor.id, existing.id))- .run();+ .returning()+ .get();await emitAudit(tx, ctx, {- action: "monitor.update_follow_redirects",+ action: "monitor.update",entityType: "monitor",entityId: existing.id,- metadata: { followRedirects: input.followRedirects },+ before: existing,+ after: updated,});});}@@ -132,7 +136,7 @@ export async function updateMonitorOtel(args: {id: input.id,workspaceId: ctx.workspace.id,});- await tx+ const updated = await tx.update(monitor).set({otelEndpoint: input.otelEndpoint,@@ -140,11 +144,14 @@ export async function updateMonitorOtel(args: {updatedAt: new Date(),}).where(eq(monitor.id, existing.id))- .run();+ .returning()+ .get();await emitAudit(tx, ctx, {- action: "monitor.update_otel",+ action: "monitor.update",entityType: "monitor",entityId: existing.id,+ before: existing,+ after: updated,});});}@@ -161,16 +168,18 @@ export async function updateMonitorPublic(args: {id: input.id,workspaceId: ctx.workspace.id,});- await tx+ const updated = await tx.update(monitor).set({ public: input.public, updatedAt: new Date() }).where(eq(monitor.id, existing.id))- .run();+ .returning()+ .get();await emitAudit(tx, ctx, {- action: "monitor.update_public",+ action: "monitor.update",entityType: "monitor",entityId: existing.id,- metadata: { public: input.public },+ before: existing,+ after: updated,});});}@@ -187,7 +196,7 @@ export async function updateMonitorResponseTime(args: {id: input.id,workspaceId: ctx.workspace.id,});- await tx+ const updated = await tx.update(monitor).set({timeout: input.timeout,@@ -195,11 +204,14 @@ export async function updateMonitorResponseTime(args: {updatedAt: new Date(),}).where(eq(monitor.id, existing.id))- .run();+ .returning()+ .get();await emitAudit(tx, ctx, {- action: "monitor.update_response_time",+ action: "monitor.update",entityType: "monitor",entityId: existing.id,+ before: existing,+ after: updated,});});}@@ -219,38 +231,59 @@ export async function bulkUpdateMonitors(args: {if (input.public === undefined && input.active === undefined) return;await withTransaction(ctx, async (tx) => {+ // Fetch current rows so per-monitor audit entries carry a real+ // `before` snapshot — the diff is the only way readers can tell+ // which flag actually flipped for each row.+ const existingRows = await tx+ .select()+ .from(monitor)+ .where(+ and(+ inArray(monitor.id, input.ids),+ eq(monitor.workspaceId, ctx.workspace.id),+ isNull(monitor.deletedAt),+ ),+ )+ .all();+ if (existingRows.length === 0) return;+const set: Record<string, unknown> = { updatedAt: new Date() };if (input.public !== undefined) set.public = input.public;if (input.active !== undefined) set.active = input.active;- // `.returning()` the ids that actually matched so the audit loop- // below can attribute only what we wrote. Looping over- // `input.ids` directly emitted `monitor.bulk_update` rows for ids- // the WHERE clause silently dropped (wrong workspace, already- // soft-deleted) — that's a new audit-log pollution, not a- // preserved legacy behaviour (the pre-migration code had no audit- // trail at all).- const updated = await tx+ // `.returning()` the full rows that actually matched so the audit+ // loop below attributes only what we wrote and carries the new+ // snapshot for each monitor.+ const updatedRows = await tx.update(monitor).set(set).where(and(- inArray(monitor.id, input.ids),+ inArray(+ monitor.id,+ existingRows.map((r) => r.id),+ ),eq(monitor.workspaceId, ctx.workspace.id),isNull(monitor.deletedAt),),)- .returning({ id: monitor.id });+ .returning()+ .all();- for (const { id } of updated) {+ const existingById = new Map(existingRows.map((r) => [r.id, r]));+ for (const updated of updatedRows) {+ // `updatedRows` is a strict subset of `existingRows` (same WHERE+ // + ids derived from `existingRows`), so the lookup always hits.+ // If it ever doesn't, the update violated that invariant and we+ // shouldn't emit an audit row at all.+ const before = existingById.get(updated.id);+ if (!before) continue;await emitAudit(tx, ctx, {- action: "monitor.bulk_update",+ action: "monitor.update",entityType: "monitor",- entityId: id,- metadata: {- public: input.public,- active: input.active,- },+ entityId: updated.id,+ before,+ after: updated,});}});diff --git a/packages/services/src/notification/__tests__/notification.test.ts b/packages/services/src/notification/__tests__/notification.test.tsindex cc65cc32a..fd8fda671 100644--- a/packages/services/src/notification/__tests__/notification.test.ts+++ b/packages/services/src/notification/__tests__/notification.test.ts@@ -1,6 +1,5 @@import {afterAll,- afterEach,beforeAll,beforeEach,describe,@@ -20,12 +19,11 @@ import {} from "../../../test/fixtures";import {cleanQuotaGatedTables,+ clearAuditLog,expectAuditRow,loadSeededWorkspace,makeUserCtx,- withAuditBuffer,} from "../../../test/helpers";-import type { AuditLogRecord } from "../../audit";import type { ServiceContext } from "../../context";import {ForbiddenError,@@ -43,8 +41,6 @@ const TEST_PREFIX = "svc-notification-test";let teamCtx: ServiceContext;let freeCtx: ServiceContext;let teamMonitorId: number;-let auditBuffer: AuditLogRecord[];-let auditReset: () => void;const createdNotificationIds: number[] = [];beforeAll(async () => {@@ -88,14 +84,9 @@ afterAll(async () => {.catch(() => undefined);});-beforeEach(() => {- const hooks = withAuditBuffer();- auditBuffer = hooks.buffer;- auditReset = hooks.reset;-});--afterEach(() => {- auditReset();+beforeEach(async () => {+ await clearAuditLog(teamCtx.workspace.id);+ await clearAuditLog(freeCtx.workspace.id);});function track(id: number) {@@ -124,7 +115,8 @@ describe("createNotification", () => {.all();expect(assoc.map((a) => a.monitorId)).toEqual([teamMonitorId]);- await expectAuditRow(auditBuffer, {+ await expectAuditRow({+ workspaceId: teamCtx.workspace.id,action: "notification.create",entityType: "notification",entityId: row.id,@@ -294,11 +286,8 @@ describe("updateNotification", () => {},});- // `provider` is attached to the audit entry's `metadata` but the v1- // buffered `AuditLogRecord` shape drops it (logs, not PII-bearing- // structured data). Assert the action/entity signals fire; metadata- // coverage lands with the v2 audit-table move.- await expectAuditRow(auditBuffer, {+ await expectAuditRow({+ workspaceId: teamCtx.workspace.id,action: "notification.update",entityType: "notification",entityId: row.id,diff --git a/packages/services/src/notification/create.ts b/packages/services/src/notification/create.tsindex d15524ea9..0a980e81d 100644--- a/packages/services/src/notification/create.ts+++ b/packages/services/src/notification/create.ts@@ -76,7 +76,6 @@ export async function createNotification(args: {entityType: "notification",entityId: row.id,after: row,- metadata: { provider: input.provider },});return selectNotificationSchema.parse(row);diff --git a/packages/services/src/notification/list.ts b/packages/services/src/notification/list.tsindex 081cd3629..f3712564b 100644--- a/packages/services/src/notification/list.ts+++ b/packages/services/src/notification/list.ts@@ -43,8 +43,14 @@ async function enrichNotificationsBatch(if (rows.length === 0) return [];const ids = rows.map((r) => r.id);+ // Explicit column selection on the join — keeps the row shape in our+ // hands instead of relying on drizzle's auto-derived `row.<table_name>`+ // keys (named after the JS variable, fragile to schema renames).const assocRows = await db- .select()+ .select({+ notificationId: notificationsToMonitors.notificationId,+ monitor,+ }).from(monitor).innerJoin(notificationsToMonitors,@@ -60,15 +66,11 @@ async function enrichNotificationsBatch(.all();const monitorsByNotification = new Map<number, Monitor[]>();- for (const row of assocRows as Array<{- monitor: typeof monitor.$inferSelect;- notifications_to_monitors: { notificationId: number };- }>) {- const nId = row.notifications_to_monitors.notificationId;+ for (const row of assocRows) {const parsed = selectMonitorSchema.parse(row.monitor);- const arr = monitorsByNotification.get(nId);+ const arr = monitorsByNotification.get(row.notificationId);if (arr) arr.push(parsed);- else monitorsByNotification.set(nId, [parsed]);+ else monitorsByNotification.set(row.notificationId, [parsed]);}return rows.map((r) => ({diff --git a/packages/services/src/notification/update.ts b/packages/services/src/notification/update.tsindex 4f06491b8..ded716f15 100644--- a/packages/services/src/notification/update.ts+++ b/packages/services/src/notification/update.ts@@ -72,7 +72,6 @@ export async function updateNotification(args: {entityId: existing.id,before: existing,after: updated,- metadata: { provider: existing.provider },});return selectNotificationSchema.parse(updated);diff --git a/packages/services/src/page-component/__tests__/page-component.test.ts b/packages/services/src/page-component/__tests__/page-component.test.tsindex 7354a4dd5..f3db909ce 100644--- a/packages/services/src/page-component/__tests__/page-component.test.ts+++ b/packages/services/src/page-component/__tests__/page-component.test.ts@@ -1,6 +1,5 @@import {afterAll,- afterEach,beforeAll,beforeEach,describe,@@ -20,12 +19,11 @@ import {SEEDED_WORKSPACE_TEAM_ID,} from "../../../test/fixtures";import {+ clearAuditLog,expectAuditRow,loadSeededWorkspace,makeUserCtx,- withAuditBuffer,} from "../../../test/helpers";-import type { AuditLogRecord } from "../../audit";import type { ServiceContext } from "../../context";import { ForbiddenError, NotFoundError } from "../../errors";import { deletePageComponent } from "../delete";@@ -39,8 +37,6 @@ let freeCtx: ServiceContext;let testPageId: number;let teamMonitorId: number;let freeMonitorId: number;-let auditBuffer: AuditLogRecord[];-let auditReset: () => void;const createdComponentIds: number[] = [];beforeAll(async () => {@@ -118,14 +114,9 @@ afterAll(async () => {.catch(() => undefined);});-beforeEach(() => {- const hooks = withAuditBuffer();- auditBuffer = hooks.buffer;- auditReset = hooks.reset;-});--afterEach(() => {- auditReset();+beforeEach(async () => {+ await clearAuditLog(teamCtx.workspace.id);+ await clearAuditLog(freeCtx.workspace.id);});describe("updatePageComponentOrder", () => {@@ -178,10 +169,27 @@ describe("updatePageComponentOrder", () => {expect(components).toHaveLength(3);expect(groups).toHaveLength(1);- await expectAuditRow(auditBuffer, {- action: "page_component.update_order",- entityType: "page",- entityId: testPageId,+ // 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,+ });++ 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,});});diff --git a/packages/services/src/page-component/list.ts b/packages/services/src/page-component/list.tsindex 1987577e2..d12288d3e 100644--- a/packages/services/src/page-component/list.ts+++ b/packages/services/src/page-component/list.ts@@ -89,8 +89,15 @@ async function enrichPageComponentsBatch().all(): Promise.resolve([] as never[]),+ // Explicit column selection on join queries — keeps the row shape+ // in our hands instead of relying on drizzle's auto-derived+ // `row.<table_name>` keys (named after the JS variable, fragile to+ // schema renames).db- .select()+ .select({+ pageComponentId: statusReportsToPageComponents.pageComponentId,+ report: statusReport,+ }).from(statusReport).innerJoin(statusReportsToPageComponents,@@ -104,7 +111,10 @@ async function enrichPageComponentsBatch().all(),db- .select()+ .select({+ pageComponentId: maintenancesToPageComponents.pageComponentId,+ maintenance,+ }).from(maintenance).innerJoin(maintenancesToPageComponents,@@ -120,43 +130,29 @@ async function enrichPageComponentsBatch(]);const monitorById = new Map<number, Monitor>();- for (const m of monitorRows as Array<typeof monitor.$inferSelect>) {+ for (const m of monitorRows) {monitorById.set(m.id, selectMonitorSchema.parse(m));}const groupById = new Map<number, PageComponentGroupRow>();- for (const g of groupRows as PageComponentGroupRow[]) {+ for (const g of groupRows) {groupById.set(g.id, selectPageComponentGroupSchema.parse(g));}const statusReportsByComponent = new Map<number, StatusReport[]>();- for (const row of statusReportRows as Array<{- status_report: typeof statusReport.$inferSelect;- status_report_to_page_component: {- pageComponentId: number;- createdAt: Date | null;- };- }>) {- const cId = row.status_report_to_page_component.pageComponentId;- const parsed = selectStatusReportSchema.parse(row.status_report);- const arr = statusReportsByComponent.get(cId);+ for (const row of statusReportRows) {+ const parsed = selectStatusReportSchema.parse(row.report);+ const arr = statusReportsByComponent.get(row.pageComponentId);if (arr) arr.push(parsed);- else statusReportsByComponent.set(cId, [parsed]);+ else statusReportsByComponent.set(row.pageComponentId, [parsed]);}const maintenancesByComponent = new Map<number, Maintenance[]>();- for (const row of maintenanceRows as Array<{- maintenance: typeof maintenance.$inferSelect;- maintenance_to_page_component: {- pageComponentId: number;- createdAt: Date | null;- };- }>) {- const cId = row.maintenance_to_page_component.pageComponentId;+ for (const row of maintenanceRows) {const parsed = selectMaintenanceSchema.parse(row.maintenance);- const arr = maintenancesByComponent.get(cId);+ const arr = maintenancesByComponent.get(row.pageComponentId);if (arr) arr.push(parsed);- else maintenancesByComponent.set(cId, [parsed]);+ else maintenancesByComponent.set(row.pageComponentId, [parsed]);}return rows.map((r) => ({diff --git a/packages/services/src/page-component/schemas.ts b/packages/services/src/page-component/schemas.tsindex aedb60376..466092ba6 100644--- a/packages/services/src/page-component/schemas.ts+++ b/packages/services/src/page-component/schemas.ts@@ -31,6 +31,11 @@ const componentInput = z);const groupInput = z.object({+ // `id` is required to round-trip existing groups. Omitting it flags the+ // group as new → gets INSERTed and a fresh id. Without this, every+ // reorder deletes and recreates groups, cascading their FKs (component+ // assignments, subscriber scopes) off a cliff.+ id: z.number().int().optional(),order: z.number().int(),name: z.string(),defaultOpen: z.boolean().optional().default(false),diff --git a/packages/services/src/page-component/update-order.ts b/packages/services/src/page-component/update-order.tsindex 826220886..8643dcbbf 100644--- a/packages/services/src/page-component/update-order.ts+++ b/packages/services/src/page-component/update-order.ts@@ -3,7 +3,7 @@ import { pageComponent, pageComponentGroup } from "@openstatus/db/src/schema";import { emitAudit } from "../audit";import { type ServiceContext, withTransaction } from "../context";-import { LimitExceededError } from "../errors";+import { LimitExceededError, ValidationError } from "../errors";import { assertPageInWorkspace, validateMonitorIds } from "./internal";import { UpdatePageComponentOrderInput } from "./schemas";@@ -29,6 +29,18 @@ export async function updatePageComponentOrder(args: {const { ctx } = args;const input = UpdatePageComponentOrderInput.parse(args.input);+ // Reject duplicate group ids up front — otherwise the diff loop+ // UPDATEs the same row twice (each iteration clobbering the previous+ // write) and silently collapses two input groups' components into one+ // persisted group. A rare client bug, but the failure mode is data+ // loss on the association side.+ const inputGroupIds = input.groups+ .map((g) => g.id)+ .filter((id): id is number => id != null);+ if (new Set(inputGroupIds).size !== inputGroupIds.length) {+ throw new ValidationError("Duplicate group id in input.");+ }+await withTransaction(ctx, async (tx) => {await assertPageInWorkspace({tx,@@ -84,8 +96,6 @@ export async function updatePageComponentOrder(args: {).all();- const existingGroupIds = existingGroups.map((g) => g.id);-// `schemas.ts` enforces the `type === "monitor" → monitorId != null`// invariant via `.refine`, but the refined type is still flat so we// keep the defensive `&& c.monitorId` guard to narrow@@ -119,6 +129,32 @@ export async function updatePageComponentOrder(args: {),] as number[];+ // Guardrail against mass-delete via id-loss. If the input has any+ // static components *and* none of them carry ids, the diff below+ // treats every existing static as "removed" and cascades through+ // `statusReportsToPageComponents`, `maintenancesToPageComponents`,+ // and `pageSubscriberToPageComponent`. Reject the call instead.+ //+ // The legitimate "delete all statics" intent is an input with zero+ // static entries, which still runs through the normal diff — this+ // guard only catches the ambiguous "new statics alongside existing+ // ones, but the client forgot to round-trip the existing ids" case.+ const inputHasAnyStatic =+ input.components.some((c) => c.type === "static") ||+ input.groups.some((g) => g.components.some((c) => c.type === "static"));+ const hasExistingStatics = existingComponents.some(+ (c) => c.type === "static",+ );+ if (+ inputHasAnyStatic &&+ inputStaticComponentIds.length === 0 &&+ hasExistingStatics+ ) {+ throw new ValidationError(+ "Existing static components must round-trip their ids.",+ );+ }+// Remove monitor components whose monitorId isn't in the new input.const removedMonitorComponents = existingComponents.filter((c) =>@@ -127,28 +163,29 @@ export async function updatePageComponentOrder(args: {!inputMonitorIds.includes(c.monitorId),);- // Static component removal: if any input static components carry ids- // we keep those and drop the rest; otherwise drop all existing static- // components. Matches the pre-migration semantics for the "recreate- // from scratch" flow the dashboard uses.+ // Static component removal: drop existing statics whose ids aren't+ // round-tripped by the input. Components with matching ids take the+ // UPDATE branch below, new statics (no id) get INSERTed.//- // Simplified from a previous two-step guard that branched on- // `hasStaticComponentsInInput` first — both "input has static with- // no ids" and "input has no static at all" collapsed to the same- // "drop all" action, so the outer check was dead weight.- const removedStaticComponents = existingComponents.filter((c) => {- if (c.type !== "static") return false;- if (inputStaticComponentIds.length > 0) {- return !inputStaticComponentIds.includes(c.id);- }- return true;- });+ // The previous "if input has no ids, drop all" fallback was a+ // footgun: `pageSubscriberToPageComponent`, `maintenancesToPageComponents`,+ // and `statusReportsToPageComponents` all FK to `page_component.id`+ // with `ON DELETE CASCADE`, so recreate-on-each-save would wipe every+ // subscriber scope / active maintenance / status-report association+ // the moment a static came in without its id.+ const removedStaticComponents = existingComponents.filter(+ (c) => c.type === "static" && !inputStaticComponentIds.includes(c.id),+ );const removedComponentIds = [...removedMonitorComponents.map((c) => c.id),...removedStaticComponents.map((c) => c.id),];+ const removedComponents = [+ ...removedMonitorComponents,+ ...removedStaticComponents,+ ];if (removedComponentIds.length > 0) {await tx.delete(pageComponent)@@ -159,10 +196,39 @@ export async function updatePageComponentOrder(args: {inArray(pageComponent.id, removedComponentIds),),);++ for (const row of removedComponents) {+ await emitAudit(tx, ctx, {+ action: "page_component.delete",+ entityType: "page_component",+ entityId: row.id,+ before: row,+ });+ }}- // Clear `groupId` before deleting groups — otherwise the FK blocks us.- if (existingGroupIds.length > 0) {+ // Groups: diff-and-reconcile by id instead of delete-and-recreate.+ //+ // Every FK pointing at a page-component or group has `ON DELETE`+ // semantics that matter on the dashboard flow — subscribers,+ // maintenances, and status reports FK to component ids with CASCADE;+ // components FK to group ids with SET NULL. Blindly dropping groups+ // on every save would flatten nested components out into the top+ // level. Preserving ids keeps those associations intact.+ const existingGroupById = new Map(existingGroups.map((g) => [g.id, g]));+ const inputGroupIdSet = new Set(+ input.groups.map((g) => g.id).filter((id): id is number => id != null),+ );+ const groupsToDelete = existingGroups.filter(+ (g) => !inputGroupIdSet.has(g.id),+ );++ // `page_component.group_id` is `ON DELETE SET NULL`, so we could let+ // the FK null out orphaned refs. Clearing explicitly here is cheaper+ // than surfacing a half-broken layout in the (rare) case the cascade+ // misfires, and keeps behavior identical to the pre-refactor flow.+ if (groupsToDelete.length > 0) {+ const idsToDelete = groupsToDelete.map((g) => g.id);await tx.update(pageComponent).set({ groupId: null })@@ -170,47 +236,87 @@ export async function updatePageComponentOrder(args: {and(eq(pageComponent.pageId, input.pageId),eq(pageComponent.workspaceId, ctx.workspace.id),- inArray(pageComponent.groupId, existingGroupIds),+ inArray(pageComponent.groupId, idsToDelete),),);- }-- if (existingGroupIds.length > 0) {await tx.delete(pageComponentGroup).where(and(eq(pageComponentGroup.pageId, input.pageId),eq(pageComponentGroup.workspaceId, ctx.workspace.id),+ inArray(pageComponentGroup.id, idsToDelete),),);++ for (const g of groupsToDelete) {+ await emitAudit(tx, ctx, {+ action: "page_component_group.delete",+ entityType: "page_component_group",+ entityId: g.id,+ before: g,+ });+ }}- // Sequential inserts instead of a bulk `.values([...]).returning()`.- // The previous bulk call relied on Drizzle/SQLite returning rows in- // the same order as they were inserted to line up `newGroups[i]`- // with `input.groups[i]` when the component mapping below runs.- // Turso/libSQL happens to preserve that order today, but it's an- // implicit coupling — any future driver change, batch split, or- // sort side-effect would silently land components in the wrong- // group with no error signal. Inserting one at a time is trivial- // cost for a small set (groups on a status page are capped) and- // makes the index alignment a guarantee rather than an assumption.+ // Walk input.groups in order so `newGroups[i]` lines up with+ // `input.groups[i]` for the component mapping below. Each slot+ // resolves to an existing group id (UPDATE path) or a freshly+ // inserted one (CREATE path).const newGroups: Array<{ id: number; name: string }> = [];for (const g of input.groups) {- const [created] = await tx- .insert(pageComponentGroup)- .values({- pageId: input.pageId,- workspaceId: ctx.workspace.id,- name: g.name,- defaultOpen: g.defaultOpen,- })- .returning();- if (!created) {- throw new Error("Failed to insert page component group");+ const existing = g.id != null ? existingGroupById.get(g.id) : undefined;++ if (existing) {+ const [updated] = await tx+ .update(pageComponentGroup)+ .set({+ name: g.name,+ defaultOpen: g.defaultOpen,+ updatedAt: new Date(),+ })+ .where(+ and(+ eq(pageComponentGroup.id, existing.id),+ eq(pageComponentGroup.pageId, input.pageId),+ eq(pageComponentGroup.workspaceId, ctx.workspace.id),+ ),+ )+ .returning();+ if (!updated) {+ throw new Error("Failed to update page component group");+ }+ newGroups.push({ id: updated.id, name: updated.name });++ await emitAudit(tx, ctx, {+ action: "page_component_group.update",+ entityType: "page_component_group",+ entityId: updated.id,+ before: existing,+ after: updated,+ });+ } else {+ const [created] = await tx+ .insert(pageComponentGroup)+ .values({+ pageId: input.pageId,+ workspaceId: ctx.workspace.id,+ name: g.name,+ defaultOpen: g.defaultOpen,+ })+ .returning();+ if (!created) {+ throw new Error("Failed to insert page component group");+ }+ newGroups.push({ id: created.id, name: created.name });++ await emitAudit(tx, ctx, {+ action: "page_component_group.create",+ entityType: "page_component_group",+ entityId: created.id,+ after: created,+ });}- newGroups.push(created);}const groupComponentValues = input.groups.flatMap((g, i) =>@@ -254,10 +360,30 @@ export async function updatePageComponentOrder(args: {);// Use the `(pageId, monitorId)` unique constraint to preserve ids.+ // Pre-classify create vs update by looking up each input monitorId in+ // the pre-upsert snapshot, so we can emit the right audit action per+ // row regardless of which branch the upsert takes for that row.+ const existingByMonitorId = new Map(+ existingComponents+ .filter(+ (c): c is typeof c & { monitorId: number } =>+ c.type === "monitor" && c.monitorId != null,+ )+ .map((c) => [c.monitorId, c]),+ );+if (monitorComponents.length > 0) {- await tx+ // Strip the client-supplied `id` before insert. The dashboard sends+ // `Date.now()` as a placeholder for newly-added components; on a+ // non-conflicting INSERT SQLite would persist that timestamp as the+ // rowid. The `onConflictDoUpdate` SET clause doesn't touch `id`, so+ // existing rows keep their real ids either way.+ const monitorInsertValues = monitorComponents.map(+ ({ id: _id, ...rest }) => rest,+ );+ const upserted = await tx.insert(pageComponent)- .values(monitorComponents)+ .values(monitorInsertValues).onConflictDoUpdate({target: [pageComponent.pageId, pageComponent.monitorId],set: {@@ -268,7 +394,29 @@ export async function updatePageComponentOrder(args: {groupOrder: sql.raw("excluded.`group_order`"),updatedAt: sql`(strftime('%s', 'now'))`,},- });+ })+ .returning();++ for (const after of upserted) {+ if (after.monitorId == null) continue;+ const before = existingByMonitorId.get(after.monitorId);+ if (before) {+ await emitAudit(tx, ctx, {+ action: "page_component.update",+ entityType: "page_component",+ entityId: after.id,+ before,+ after,+ });+ } else {+ await emitAudit(tx, ctx, {+ action: "page_component.create",+ entityType: "page_component",+ entityId: after.id,+ after,+ });+ }+ }}// Restrict the "take update path" set to ids that (a) still exist@@ -279,15 +427,16 @@ export async function updatePageComponentOrder(args: {// on the stale pre-delete snapshot, take the UPDATE branch, and// silently no-op — the new static never gets inserted.const removedIdSet = new Set(removedComponentIds);- const existingStaticComponentIds = new Set(+ const existingStaticById = new Map(existingComponents.filter((c) => c.type === "static" && !removedIdSet.has(c.id))- .map((c) => c.id),+ .map((c) => [c.id, c]),);for (const c of staticComponents) {- if (c.id && existingStaticComponentIds.has(c.id)) {- await tx+ const before = c.id ? existingStaticById.get(c.id) : undefined;+ if (before) {+ const [after] = await tx.update(pageComponent).set({name: c.name,@@ -301,34 +450,49 @@ export async function updatePageComponentOrder(args: {}).where(and(- eq(pageComponent.id, c.id),+ eq(pageComponent.id, before.id),eq(pageComponent.pageId, input.pageId),eq(pageComponent.workspaceId, ctx.workspace.id),),- );+ )+ .returning();+ if (!after) {+ throw new Error("Failed to update static component");+ }++ await emitAudit(tx, ctx, {+ action: "page_component.update",+ entityType: "page_component",+ entityId: after.id,+ before,+ after,+ });} else {- await tx.insert(pageComponent).values({- pageId: c.pageId,- workspaceId: c.workspaceId,- name: c.name,- description: c.description,- type: c.type,- monitorId: c.monitorId,- order: c.order,- groupId: c.groupId,- groupOrder: c.groupOrder,+ const [created] = await tx+ .insert(pageComponent)+ .values({+ pageId: c.pageId,+ workspaceId: c.workspaceId,+ name: c.name,+ description: c.description,+ type: c.type,+ monitorId: c.monitorId,+ order: c.order,+ groupId: c.groupId,+ groupOrder: c.groupOrder,+ })+ .returning();+ if (!created) {+ throw new Error("Failed to insert static component");+ }++ await emitAudit(tx, ctx, {+ action: "page_component.create",+ entityType: "page_component",+ entityId: created.id,+ after: created,});}}-- await emitAudit(tx, ctx, {- action: "page_component.update_order",- entityType: "page",- entityId: input.pageId,- metadata: {- componentCount: inputComponentCount,- groupCount: input.groups.length,- },- });});}diff --git a/packages/services/src/page/__tests__/page.test.ts b/packages/services/src/page/__tests__/page.test.tsindex bb1c4f68c..5170b46b9 100644--- a/packages/services/src/page/__tests__/page.test.ts+++ b/packages/services/src/page/__tests__/page.test.ts@@ -1,6 +1,5 @@import {afterAll,- afterEach,beforeAll,beforeEach,describe,@@ -16,12 +15,11 @@ import {} from "../../../test/fixtures";import {cleanQuotaGatedTables,+ clearAuditLog,expectAuditRow,loadSeededWorkspace,makeUserCtx,- withAuditBuffer,} from "../../../test/helpers";-import type { AuditLogRecord } from "../../audit";import type { ServiceContext } from "../../context";import {ConflictError,@@ -39,8 +37,6 @@ const TEST_PREFIX = "svc-page-test";let teamCtx: ServiceContext;let freeCtx: ServiceContext;let teamMonitorId: number;-let auditBuffer: AuditLogRecord[];-let auditReset: () => void;const createdPageIds: number[] = [];beforeAll(async () => {@@ -88,14 +84,9 @@ afterAll(async () => {.catch(() => undefined);});-beforeEach(() => {- const hooks = withAuditBuffer();- auditBuffer = hooks.buffer;- auditReset = hooks.reset;-});--afterEach(() => {- auditReset();+beforeEach(async () => {+ await clearAuditLog(teamCtx.workspace.id);+ await clearAuditLog(freeCtx.workspace.id);});function track(id: number) {@@ -115,7 +106,8 @@ describe("newPage", () => {});track(row.id);expect(row.slug).toBe(slug);- await expectAuditRow(auditBuffer, {+ await expectAuditRow({+ workspaceId: teamCtx.workspace.id,action: "page.create",entityType: "page",entityId: row.id,@@ -145,6 +137,16 @@ describe("newPage", () => {});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@@ -236,6 +238,13 @@ describe("updatePageGeneral", () => {});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: falseconst p = await newPage({diff --git a/packages/services/src/page/update.ts b/packages/services/src/page/update.tsindex a9b59c439..be15fe7ee 100644--- a/packages/services/src/page/update.ts+++ b/packages/services/src/page/update.ts@@ -41,7 +41,7 @@ export async function updatePageGeneral(args: {});}- await tx+ const updated = await tx.update(page).set({title: input.title,@@ -50,30 +50,24 @@ export async function updatePageGeneral(args: {icon: input.icon ?? "",updatedAt: new Date(),})- .where(eq(page.id, existing.id));+ .where(eq(page.id, existing.id))+ .returning()+ .get();await emitAudit(tx, ctx, {- action: "page.update_general",+ action: "page.update",entityType: "page",entityId: existing.id,before: existing,+ after: updated,});});}-/**- * Only persists the `customDomain` change. External integration (Vercel- * add/remove) is the caller's responsibility — services don't reach out- * to third-party APIs. The tRPC / Connect adapter calls the Vercel API- * around the service call.- *- * Returns `{ existingDomain }` so the caller can diff without another- * read.- */export async function updatePageCustomDomain(args: {ctx: ServiceContext;input: UpdatePageCustomDomainInput;-}): Promise<{ existingDomain: string }> {+}): Promise<{ existingDomain: string | null }> {const { ctx } = args;const input = UpdatePageCustomDomainInput.parse(args.input);@@ -84,19 +78,19 @@ export async function updatePageCustomDomain(args: {workspaceId: ctx.workspace.id,});- await tx+ const updated = await tx.update(page).set({ customDomain: input.customDomain, updatedAt: new Date() })- .where(eq(page.id, existing.id));+ .where(eq(page.id, existing.id))+ .returning()+ .get();await emitAudit(tx, ctx, {- action: "page.update_custom_domain",+ action: "page.update",entityType: "page",entityId: existing.id,- metadata: {- from: existing.customDomain,- to: input.customDomain,- },+ before: existing,+ after: updated,});return { existingDomain: existing.customDomain };@@ -133,7 +127,7 @@ export async function updatePagePasswordProtection(args: {workspaceId: ctx.workspace.id,});- await tx+ const updated = await tx.update(page).set({accessType: input.accessType,@@ -151,13 +145,16 @@ export async function updatePagePasswordProtection(args: {...(input.allowIndex !== undefined && { allowIndex: input.allowIndex }),updatedAt: new Date(),})- .where(eq(page.id, existing.id));+ .where(eq(page.id, existing.id))+ .returning()+ .get();await emitAudit(tx, ctx, {- action: "page.update_password_protection",+ action: "page.update",entityType: "page",entityId: existing.id,- metadata: { accessType: input.accessType },+ before: existing,+ after: updated,});});}@@ -182,7 +179,7 @@ export async function updatePageAppearance(args: {? (existing.configuration as Record<string, unknown>): {};- await tx+ const updated = await tx.update(page).set({forceTheme: input.forceTheme,@@ -192,12 +189,16 @@ export async function updatePageAppearance(args: {},updatedAt: new Date(),})- .where(eq(page.id, existing.id));+ .where(eq(page.id, existing.id))+ .returning()+ .get();await emitAudit(tx, ctx, {- action: "page.update_appearance",+ action: "page.update",entityType: "page",entityId: existing.id,+ before: existing,+ after: updated,});});}@@ -215,19 +216,23 @@ export async function updatePageLinks(args: {id: input.id,workspaceId: ctx.workspace.id,});- await tx+ const updated = await tx.update(page).set({homepageUrl: input.homepageUrl,contactUrl: input.contactUrl,updatedAt: new Date(),})- .where(eq(page.id, existing.id));+ .where(eq(page.id, existing.id))+ .returning()+ .get();await emitAudit(tx, ctx, {- action: "page.update_links",+ action: "page.update",entityType: "page",entityId: existing.id,+ before: existing,+ after: updated,});});}@@ -250,19 +255,23 @@ export async function updatePageLocales(args: {workspaceId: ctx.workspace.id,});- await tx+ const updated = await tx.update(page).set({defaultLocale: input.defaultLocale,locales: input.locales,updatedAt: new Date(),})- .where(eq(page.id, existing.id));+ .where(eq(page.id, existing.id))+ .returning()+ .get();await emitAudit(tx, ctx, {- action: "page.update_locales",+ action: "page.update",entityType: "page",entityId: existing.id,+ before: existing,+ after: updated,});});}@@ -287,7 +296,7 @@ export async function updatePageConfiguration(args: {? (existing.configuration as Record<string, unknown>): {};- await tx+ const updated = await tx.update(page).set({configuration: {@@ -296,12 +305,16 @@ export async function updatePageConfiguration(args: {},updatedAt: new Date(),})- .where(eq(page.id, existing.id));+ .where(eq(page.id, existing.id))+ .returning()+ .get();await emitAudit(tx, ctx, {- action: "page.update_configuration",+ action: "page.update",entityType: "page",entityId: existing.id,+ before: existing,+ after: updated,});});}diff --git a/packages/services/src/status-report/__tests__/status-report.test.ts b/packages/services/src/status-report/__tests__/status-report.test.tsindex 9c3aeba13..c26e40359 100644--- a/packages/services/src/status-report/__tests__/status-report.test.ts+++ b/packages/services/src/status-report/__tests__/status-report.test.ts@@ -22,13 +22,12 @@ import {SEEDED_WORKSPACE_TEAM_ID,} from "../../../test/fixtures";import {+ clearAuditLog,expectAuditRow,loadSeededWorkspace,makeSlackCtx,makeUserCtx,- withAuditBuffer,} from "../../../test/helpers";-import type { AuditLogRecord } from "../../audit";import type { ServiceContext } from "../../context";import { ForbiddenError, NotFoundError } from "../../errors";import { addStatusReportUpdate } from "../add-update";@@ -62,8 +61,6 @@ let teamCtx: ServiceContext;let freeCtx: ServiceContext;let testPageId: number;let testPageComponentId: number;-let auditBuffer: AuditLogRecord[];-let auditReset: () => void;/*** Tests push created statusReport ids here instead of issuing an inline@@ -122,15 +119,13 @@ afterAll(async () => {.catch(() => undefined);});-beforeEach(() => {- const hooks = withAuditBuffer();- auditBuffer = hooks.buffer;- auditReset = hooks.reset;+beforeEach(async () => {+ await clearAuditLog(teamCtx.workspace.id);+ await clearAuditLog(freeCtx.workspace.id);subscriptionSpies?.dispatchStatusReportUpdate.mockClear();});afterEach(async () => {- auditReset();if (createdReportIds.length > 0) {await db.delete(statusReport)@@ -167,7 +162,8 @@ describe("createStatusReport", () => {.all();expect(assoc.map((a) => a.pageComponentId)).toEqual([testPageComponentId]);- await expectAuditRow(auditBuffer, {+ await expectAuditRow({+ workspaceId: teamCtx.workspace.id,action: "status_report.create",entityType: "status_report",entityId: report.id,@@ -221,8 +217,9 @@ describe("addStatusReportUpdate", () => {expect(newUpdate.status).toBe("monitoring");expect(newUpdate.statusReportId).toBe(report.id);- await expectAuditRow(auditBuffer, {- action: "status_report.add_update",+ await expectAuditRow({+ workspaceId: teamCtx.workspace.id,+ action: "status_report_update.create",entityType: "status_report_update",entityId: newUpdate.id,});@@ -558,7 +555,8 @@ describe("slack actor path", () => {pageComponentIds: [],},});- await expectAuditRow(auditBuffer, {+ await expectAuditRow({+ workspaceId: teamCtx.workspace.id,action: "status_report.create",entityType: "status_report",entityId: report.id,diff --git a/packages/services/src/status-report/add-update.ts b/packages/services/src/status-report/add-update.tsindex a75020982..b9cd05ee3 100644--- a/packages/services/src/status-report/add-update.ts+++ b/packages/services/src/status-report/add-update.ts@@ -54,11 +54,11 @@ export async function addStatusReportUpdate(args: {}await emitAudit(tx, ctx, {- action: "status_report.add_update",+ action: "status_report_update.create",entityType: "status_report_update",entityId: newUpdate.id,after: newUpdate,- metadata: { statusReportId: report.id, status: input.status },+ metadata: { statusReportId: report.id },});return { statusReport: updatedReport, statusReportUpdate: newUpdate };diff --git a/packages/services/src/status-report/delete.ts b/packages/services/src/status-report/delete.tsindex c5d75c2fb..b1849d8a8 100644--- a/packages/services/src/status-report/delete.ts+++ b/packages/services/src/status-report/delete.ts@@ -58,7 +58,7 @@ export async function deleteStatusReportUpdate(args: {.where(eq(statusReportUpdate.id, existing.id));await emitAudit(tx, ctx, {- action: "status_report.delete_update",+ action: "status_report_update.delete",entityType: "status_report_update",entityId: existing.id,before: existing,diff --git a/packages/services/src/status-report/list.ts b/packages/services/src/status-report/list.tsindex 07710d609..78bc663ed 100644--- a/packages/services/src/status-report/list.ts+++ b/packages/services/src/status-report/list.ts@@ -12,6 +12,7 @@ import {import {pageComponent,page as pageTable,+ selectPageComponentSchema,selectPageSchema,statusReport,statusReportUpdate,@@ -112,7 +113,7 @@ async function enrichReportsBatch(.all();const componentsByReport = new Map<number, PageComponent[]>();for (const row of assocRows) {- const component = row.component as unknown as PageComponent;+ const component = selectPageComponentSchema.parse(row.component);const arr = componentsByReport.get(row.reportId);if (arr) arr.push(component);else componentsByReport.set(row.reportId, [component]);@@ -135,9 +136,10 @@ async function enrichReportsBatch(]);const siblingsByPageId = new Map<number, PageComponent[]>();for (const c of pageSiblings) {- const arr = siblingsByPageId.get(c.pageId);- if (arr) arr.push(c as unknown as PageComponent);- else siblingsByPageId.set(c.pageId, [c as unknown as PageComponent]);+ const parsed = selectPageComponentSchema.parse(c);+ const arr = siblingsByPageId.get(parsed.pageId);+ if (arr) arr.push(parsed);+ else siblingsByPageId.set(parsed.pageId, [parsed]);}for (const p of pageRows) {pageById.set(p.id, {diff --git a/packages/services/src/status-report/notify.ts b/packages/services/src/status-report/notify.tsindex 1f3ec1c45..bac528567 100644--- a/packages/services/src/status-report/notify.ts+++ b/packages/services/src/status-report/notify.ts@@ -2,7 +2,6 @@ import { db as defaultDb, eq } from "@openstatus/db";import { statusReport, statusReportUpdate } from "@openstatus/db/src/schema";import { dispatchStatusReportUpdate } from "@openstatus/subscriptions";-import { emitAudit } from "../audit";import type { ServiceContext } from "../context";import { ForbiddenError, NotFoundError } from "../errors";import { NotifyStatusReportInput } from "./schemas";@@ -54,10 +53,4 @@ export async function notifyStatusReport(args: {}await dispatchStatusReportUpdate(input.statusReportUpdateId);-- await emitAudit(db, ctx, {- action: "status_report.notify",- entityType: "status_report_update",- entityId: input.statusReportUpdateId,- });}diff --git a/packages/services/src/status-report/resolve.ts b/packages/services/src/status-report/resolve.tsindex 727c3286c..1fcd6abbf 100644--- a/packages/services/src/status-report/resolve.ts+++ b/packages/services/src/status-report/resolve.ts@@ -8,7 +8,7 @@ import { ResolveStatusReportInput } from "./schemas";/*** Convenience over addStatusReportUpdate with status="resolved". Exists so* Slack's `resolveStatusReport` action has a named call site with matching- * intent; audit action is still `status_report.add_update` (same db path).+ * intent; audit action is still `status_report_update.create` (same db path).*/export async function resolveStatusReport(args: {ctx: ServiceContext;diff --git a/packages/services/src/status-report/update.ts b/packages/services/src/status-report/update.tsindex cdcad1213..1cf558b8c 100644--- a/packages/services/src/status-report/update.ts+++ b/packages/services/src/status-report/update.ts@@ -126,7 +126,7 @@ export async function updateStatusReportUpdate(args: {}await emitAudit(tx, ctx, {- action: "status_report.update_update",+ action: "status_report_update.update",entityType: "status_report_update",entityId: updated.id,before: existing,diff --git a/packages/services/src/user/delete.ts b/packages/services/src/user/delete.tsindex 66a1caae1..b3507983a 100644--- a/packages/services/src/user/delete.ts+++ b/packages/services/src/user/delete.ts@@ -12,7 +12,11 @@ import {tryGetActorUserId,withTransaction,} from "../context";-import { PreconditionFailedError, UnauthorizedError } from "../errors";+import {+ NotFoundError,+ PreconditionFailedError,+ UnauthorizedError,+} from "../errors";import { DeleteAccountInput } from "./schemas";/**@@ -56,6 +60,14 @@ export async function deleteAccount(args: {}await withTransaction(ctx, async (tx) => {+ const existing = await tx.query.user.findFirst({+ where: eq(user.id, userId),+ });++ // Actor's user id resolved to nothing — anomalous, don't proceed+ // silently and don't emit an audit row for a phantom delete.+ if (!existing) throw new NotFoundError("user", userId);+const ownedRows = await tx.query.usersToWorkspaces.findMany({where: and(eq(usersToWorkspaces.userId, userId),@@ -106,9 +118,10 @@ export async function deleteAccount(args: {.where(eq(user.id, userId));await emitAudit(tx, ctx, {- action: "user.delete_account",+ action: "user.delete",entityType: "user",entityId: userId,+ before: existing,});});}diff --git a/packages/services/src/workspace/__tests__/workspace.test.ts b/packages/services/src/workspace/__tests__/workspace.test.tsindex ca4ed3051..3dae7b6b5 100644--- a/packages/services/src/workspace/__tests__/workspace.test.ts+++ b/packages/services/src/workspace/__tests__/workspace.test.ts@@ -1,6 +1,5 @@import {afterAll,- afterEach,beforeAll,beforeEach,describe,@@ -18,18 +17,15 @@ import {} from "..";import { SEEDED_WORKSPACE_TEAM_ID } from "../../../test/fixtures";import {+ clearAuditLog,expectAuditRow,loadSeededWorkspace,makeUserCtx,- withAuditBuffer,} from "../../../test/helpers";-import type { AuditLogRecord } from "../../audit";import type { ServiceContext } from "../../context";let teamCtx: ServiceContext;let originalName: string | null = null;-let auditBuffer: AuditLogRecord[];-let auditReset: () => void;beforeAll(async () => {const team = await loadSeededWorkspace(SEEDED_WORKSPACE_TEAM_ID);@@ -46,12 +42,9 @@ afterAll(async () => {}});-beforeEach(() => {- const session = withAuditBuffer();- auditBuffer = session.buffer;- auditReset = session.reset;+beforeEach(async () => {+ await clearAuditLog(teamCtx.workspace.id);});-afterEach(() => auditReset());describe("getWorkspace", () => {test("returns the caller's workspace", async () => {@@ -124,8 +117,9 @@ describe("updateWorkspaceName", () => {.get();expect(row?.name).toBe(nextName);- await expectAuditRow(auditBuffer, {- action: "workspace.update_name",+ await expectAuditRow({+ workspaceId: teamCtx.workspace.id,+ action: "workspace.update",entityType: "workspace",entityId: SEEDED_WORKSPACE_TEAM_ID,actorType: "user",diff --git a/packages/services/src/workspace/update.ts b/packages/services/src/workspace/update.tsindex 858fa581e..3bf0e1ff4 100644--- a/packages/services/src/workspace/update.ts+++ b/packages/services/src/workspace/update.ts@@ -3,6 +3,7 @@ import { workspace } from "@openstatus/db/src/schema";import { emitAudit } from "../audit";import { type ServiceContext, withTransaction } from "../context";+import { NotFoundError } from "../errors";import { UpdateWorkspaceNameInput } from "./schemas";/**@@ -17,16 +18,29 @@ export async function updateWorkspaceName(args: {const input = UpdateWorkspaceNameInput.parse(args.input);await withTransaction(ctx, async (tx) => {- await tx+ const existing = await tx+ .select()+ .from(workspace)+ .where(eq(workspace.id, ctx.workspace.id))+ .get();+ // Workspace is derived from `ctx.workspace`, so absence here is a+ // state anomaly (concurrent delete?). Fail closed rather than emit+ // an audit row without a `before` snapshot.+ if (!existing) throw new NotFoundError("workspace", ctx.workspace.id);++ const updated = await tx.update(workspace).set({ name: input.name, updatedAt: new Date() })- .where(eq(workspace.id, ctx.workspace.id));+ .where(eq(workspace.id, ctx.workspace.id))+ .returning()+ .get();await emitAudit(tx, ctx, {- action: "workspace.update_name",+ action: "workspace.update",entityType: "workspace",entityId: ctx.workspace.id,- metadata: { name: input.name },+ before: existing,+ after: updated,});});}diff --git a/packages/services/test/helpers.ts b/packages/services/test/helpers.tsindex bae584635..6a8c97c13 100644--- a/packages/services/test/helpers.ts+++ b/packages/services/test/helpers.ts@@ -1,6 +1,7 @@import { expect } from "bun:test";-import { db, eq, inArray } from "@openstatus/db";+import { and, db, desc, eq, inArray } from "@openstatus/db";import {+ auditLog,notification,page,pageComponent,@@ -8,8 +9,6 @@ import {workspace as workspaceTable,} from "@openstatus/db/src/schema";-import type { AuditLogRecord } from "../src/audit";-import { installTestAuditBuffer, uninstallTestAuditBuffer } from "../src/audit";import type { Actor, ServiceContext } from "../src/context";import type { Workspace } from "../src/types";@@ -51,6 +50,14 @@ export async function cleanQuotaGatedTables(.catch(() => undefined);}+/** Wipe audit_log rows for a workspace. Call in `beforeEach` / `afterEach`. */+export async function clearAuditLog(workspaceId: number): Promise<void> {+ await db+ .delete(auditLog)+ .where(eq(auditLog.workspaceId, workspaceId))+ .catch(() => undefined);+}+/*** Load a seeded workspace by id (defaults to id=1, the `team` plan fixture).* Tests that need a fresh workspace should insert one explicitly and clean up;@@ -129,43 +136,53 @@ export function makeSystemCtx(}/**- * Install the audit buffer for the scope of a test. Returns the live buffer- * plus a cleanup fn — use in beforeEach / afterEach or with { using } semantics.+ * Read audit rows for a workspace, optionally filtered by entity.+ * Sort is `(id DESC)` — the autoincrement id is monotonic within the+ * test DB and gives deterministic order even for rows written in the+ * same millisecond.*/-export function withAuditBuffer(): {- buffer: AuditLogRecord[];- reset: () => void;-} {- const buffer = installTestAuditBuffer();- return {- buffer,- reset: () => {- uninstallTestAuditBuffer();- },- };+export async function readAuditLog(filter: {+ workspaceId: number;+ entityType?: string;+ entityId?: string | number;+}): Promise<(typeof auditLog.$inferSelect)[]> {+ const clauses = [eq(auditLog.workspaceId, filter.workspaceId)];+ if (filter.entityType !== undefined) {+ clauses.push(eq(auditLog.entityType, filter.entityType));+ }+ if (filter.entityId !== undefined) {+ clauses.push(eq(auditLog.entityId, String(filter.entityId)));+ }+ return db+ .select()+ .from(auditLog)+ .where(and(...clauses))+ .orderBy(desc(auditLog.id))+ .all();}/*** Assert an audit row matching `match` was recorded during the test.- * Requires an active audit buffer (installTestAuditBuffer / withAuditBuffer).- * In v1 this scans the in-memory buffer; in v2 it will query the audit_log- * table. Call sites do not change.+ * Queries the real `audit_log` table — ensure tests clean rows per+ * workspace (see `clearAuditLog`) or rely on fresh entity ids to+ * avoid cross-test matches.*/-export async function expectAuditRow(- buffer: AuditLogRecord[],- match: {- action: string;- entityType: string;- entityId: string | number;- actorType?: Actor["type"];- },-): Promise<void> {+export async function expectAuditRow(match: {+ workspaceId: number;+ action: string;+ entityType: string;+ entityId: string | number;+ actorType?: Actor["type"];+}): Promise<void> {const expectedEntityId = String(match.entityId);- const hit = buffer.find(+ const rows = await readAuditLog({+ workspaceId: match.workspaceId,+ entityType: match.entityType,+ entityId: expectedEntityId,+ });+ const hit = rows.find((row) =>row.action === match.action &&- row.entityType === match.entityType &&- row.entityId === expectedEntityId &&(match.actorType === undefined || row.actorType === match.actorType),);expect(diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 3ef2d421b..420202706 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -725,7 +725,7 @@ importers:version: 5.0.0-beta.29([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected])next-intl:specifier: ^4.8.3- version: 4.8.3(@swc/[email protected])([email protected](@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected])+ version: 4.8.3(@swc/[email protected])([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected])next-plausible:specifier: 3.12.5version: 3.12.5([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])@@ -2026,9 +2026,6 @@ importers:packages/services:dependencies:- '@logtape/logtape':- specifier: 2.0.1- version: 2.0.1'@openstatus/assertions':specifier: workspace:*version: link:../assertions@@ -21685,7 +21682,7 @@ snapshots:- [email protected](@swc/[email protected])([email protected](@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]):+ [email protected](@swc/[email protected])([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]):dependencies:'@formatjs/intl-localematcher': 0.8.1'@parcel/watcher': 2.5.1