Open-source status page, incident response and uptime monitoring
TypeScript alertingincident-managementmcpmcp-servermonitoringmonitoring-as-codeobservabilityon-callopen-sourcesrestatus-pagestatuspagesynthetic-monitoringterraformtinybirdtursouptimeuptime-checkeruptime-monitor
feat: api key scopes (#2141)
Maximilian Kaskea01958bf2443
diff --git a/CLAUDE.md b/CLAUDE.mdindex c37fce5ec..c11a24ddd 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -124,3 +124,15 @@ Conventions for any new mutation:- **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.++## Scope Enforcement (API key RBAC)++API keys carry **scopes** (`'read'` / `'write'`) that gate write access. See `packages/services/src/auth/`.++- **Call `requireScope(ctx, "write")` as the first line** of every write verb — before `Input.parse(...)` and `withTransaction`. Import from `../auth`.+- **"Write"** = any DB mutation **or** side-effecting external call (probes, webhooks, notifications). Everything else is read.+- No-op for `user` / `system` / `slack` / `webhook` / `subscriber` actors; active for `apiKey` and `mcp`. Throws `ForbiddenError` on denial.+- **Tests:** every entity's `__tests__/` includes a `'rejects read-only actor'` case via `makeApiKeyCtx(workspace, { keyId: "k", userId: 1, scopes: ["read"] })`. `requireScope` fires before DB lookup, so fake ids work for delete/update verbs.+- **MCP tools** declare `scope: 'read' | 'write'` and register via `registerScopedTool` — read-only keys never see write tools.++Treat a missing `requireScope` the same as a missing `emitAudit` — mandatory for every mutation.diff --git a/apps/dashboard/src/components/data-table/settings/api-key/data-table.tsx b/apps/dashboard/src/components/data-table/settings/api-key/data-table.tsxindex e26171589..7575e742c 100644--- a/apps/dashboard/src/components/data-table/settings/api-key/data-table.tsx+++ b/apps/dashboard/src/components/data-table/settings/api-key/data-table.tsx@@ -2,6 +2,7 @@ import { QuickActions } from "@/components/dropdowns/quick-actions";import { formatDate } from "@/lib/formatter";import { useTRPC } from "@/lib/trpc/client";import type { RouterOutputs } from "@openstatus/api";+import { Badge } from "@openstatus/ui/components/ui/badge";import {Table,TableBody,@@ -14,6 +15,28 @@ import { useMutation } from "@tanstack/react-query";type ApiKey = RouterOutputs["apiKeyRouter"]["getAll"][number];+/**+ * Map a key's `scopes` array to a single human label. v1 keys carry one+ * value (`['read']` or `['write']`); legacy rows backfilled to+ * `['write']` show as "Read & write." `'*'` is super-admin (synthesized+ * by middleware, never settable through any public API). Seeing it on+ * a row indicates someone hand-edited the DB or a bug bypassed the+ * input enum — surface drift instead of silently mislabeling it.+ */+function scopeLabel(scopes: ApiKey["scopes"]): string {+ if (scopes.includes("*")) {+ if (typeof console !== "undefined") {+ console.warn(+ "[api-key table] row carries '*' scope — should never happen via the public API",+ );+ }+ return "Admin";+ }+ if (scopes.includes("write")) return "Read & write";+ if (scopes.includes("read")) return "Read-only";+ return "Unknown";+}+export function DataTable({apiKeys,refetch,@@ -36,6 +59,7 @@ export function DataTable({<TableHead>Name</TableHead><TableHead>Description</TableHead><TableHead>Prefix</TableHead>+ <TableHead>Access</TableHead><TableHead>Expires</TableHead><TableHead><span className="sr-only">Actions</span>@@ -52,6 +76,9 @@ export function DataTable({<TableCell><code className="text-xs">{apiKey.prefix}...</code></TableCell>+ <TableCell>+ <Badge variant="secondary">{scopeLabel(apiKey.scopes)}</Badge>+ </TableCell><TableCell className="text-sm">{apiKey.expiresAt ? formatDate(apiKey.expiresAt) : "-"}</TableCell>diff --git a/apps/dashboard/src/components/forms/settings/form-api-key.tsx b/apps/dashboard/src/components/forms/settings/form-api-key.tsxindex d7bb9a440..579d91c5b 100644--- a/apps/dashboard/src/components/forms/settings/form-api-key.tsx+++ b/apps/dashboard/src/components/forms/settings/form-api-key.tsx@@ -51,12 +51,16 @@ import {PopoverContent,PopoverTrigger,} from "@openstatus/ui/components/ui/popover";+import {+ RadioGroup,+ RadioGroupItem,+} from "@openstatus/ui/components/ui/radio-group";import { Textarea } from "@openstatus/ui/components/ui/textarea";import { useCopyToClipboard } from "@openstatus/ui/hooks/use-copy-to-clipboard";import { cn } from "@openstatus/ui/lib/utils";import { useMutation, useQuery } from "@tanstack/react-query";import { isTRPCClientError } from "@trpc/client";-import { format } from "date-fns";+import { format, parse } from "date-fns";import { CalendarIcon, Check, Copy } from "lucide-react";import { useState, useTransition } from "react";import { useForm } from "react-hook-form";@@ -69,6 +73,19 @@ const schema = z.object({name: z.string().min(1, "Name is required"),description: z.string().optional(),expiresAt: z.string().optional(),+ // Single-value radio. The wire format on the create-key API is+ // an array (`scopes: Scope[]`) so per-resource scopes can land+ // additively later, but the v1 dashboard surface only ever picks+ // one of two options — flat enum here, lift to array on submit.+ //+ // Duplicates `apiKeySettableScopes` from `@openstatus/db` — the+ // dashboard's client bundle can't reach into the db package+ // (drizzle pulls in node-only deps via the schema barrel). The+ // services input schema validates whatever the form sends, so+ // drift here surfaces as a parse error on submit, not a silent+ // mismatch. Keep this list in sync with+ // `packages/db/src/schema/api-keys/constants.ts`.+ scope: z.enum(["read", "write"]),});type FormValues = z.infer<typeof schema>;@@ -89,6 +106,10 @@ export function FormApiKey() {name: "",description: "",expiresAt: "",+ // Default Read-only: AI agents are the most common new use+ // case for keys, and read-only is the safer starting point.+ // CI/CD users actively pick "Read & write."+ scope: "read",},});@@ -124,6 +145,7 @@ export function FormApiKey() {name: values.name.trim(),description: values.description?.trim() || undefined,expiresAt: values.expiresAt ? new Date(values.expiresAt) : undefined,+ scopes: [values.scope],});toast.promise(promise, {loading: "Creating...",@@ -179,19 +201,20 @@ export function FormApiKey() {<Button size="sm">Create</Button></DialogTrigger><DialogContent+ className="max-h-[80vh] overflow-y-auto"onCloseAutoFocus={(event) => {event.preventDefault();document.body.style.pointerEvents = "";}}>+ <DialogHeader>+ <DialogTitle>Create API Key</DialogTitle>+ <DialogDescription>+ Create a new API key to access your workspace data.+ </DialogDescription>+ </DialogHeader><Form {...form}><form onSubmit={form.handleSubmit(createAction)}>- <DialogHeader>- <DialogTitle>Create API Key</DialogTitle>- <DialogDescription>- Create a new API key to access your workspace data.- </DialogDescription>- </DialogHeader><div className="space-y-4"><FormFieldcontrol={form.control}@@ -223,13 +246,54 @@ export function FormApiKey() {</FormItem>)}/>+ <FormField+ control={form.control}+ name="scope"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Access</FormLabel>+ <FormControl>+ <RadioGroup+ value={field.value}+ onValueChange={field.onChange}+ className="gap-3 sm:grid-cols-2"+ >+ <label className="flex cursor-pointer items-start gap-3 rounded-md border p-3 hover:bg-muted/40 has-[[aria-checked=true]]:border-primary">+ <RadioGroupItem value="read" className="mt-1" />+ <div className="space-y-0.5">+ <div className="font-medium text-sm">+ Read-only+ </div>+ <div className="text-muted-foreground text-xs">+ Recommended for AI agents and read-only+ dashboards.+ </div>+ </div>+ </label>+ <label className="flex cursor-pointer items-start gap-3 rounded-md border p-3 hover:bg-muted/40 has-[[aria-checked=true]]:border-primary">+ <RadioGroupItem value="write" className="mt-1" />+ <div className="space-y-0.5">+ <div className="font-medium text-sm">+ Read & write+ </div>+ <div className="text-muted-foreground text-xs">+ Required for CI/CD and automation.+ </div>+ </div>+ </label>+ </RadioGroup>+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ /><FormFieldcontrol={form.control}name="expiresAt"render={({ field }) => (<FormItem className="flex flex-col"><FormLabel>Expiration Date</FormLabel>- <Popover>+ <Popover modal><FormControl><PopoverTrigger asChild><Button@@ -237,7 +301,7 @@ export function FormApiKey() {variant="outline"size="sm"className={cn(- "w-[240px] pl-3 text-left font-normal",+ "w-full pl-3 text-left font-normal",!field.value && "text-muted-foreground",)}>@@ -257,18 +321,16 @@ export function FormApiKey() {<Calendarmode="single"selected={- field.value ? new Date(field.value) : undefined+ field.value+ ? parse(field.value, "yyyy-MM-dd", new Date())+ : undefined}onSelect={(date) => {if (!date) {field.onChange("");return;}- // Convert to ISO string and take only the date part (YYYY-MM-DD)- const dateString = date- .toISOString()- .split("T")[0];- field.onChange(dateString);+ field.onChange(format(date, "yyyy-MM-dd"));}}disabled={(date) => {const today = new Date();diff --git a/apps/docs/src/content/docs/reference/mcp-server.mdx b/apps/docs/src/content/docs/reference/mcp-server.mdxindex c4bc03c20..498b6320d 100644--- a/apps/docs/src/content/docs/reference/mcp-server.mdx+++ b/apps/docs/src/content/docs/reference/mcp-server.mdx@@ -23,6 +23,17 @@ x-openstatus-key: os_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxGet a key from the dashboard's **Settings → API Tokens**.+### Scopes++Each API key carries a scope that controls what tools the MCP server exposes:++- **Read-only** — the server only registers `list_*` tools. Mutation tools (`create_*`, `update_*`, `add_*`, `resolve_*`) are not advertised in `tools/list` and cannot be called.+- **Read & write** — every tool is available.++Scope is set at key creation time and is **immutable**. To change a key's scope, revoke it and issue a new one.++For AI agents that should only observe state — health summaries, paging on-call, drafting communication — issue a **Read-only** key. The server gates writes at two layers (the `tools/list` filter is the visible UX; the service-layer scope check is the boundary), so a misconfigured client can't accidentally mutate.+## ToolsThe server exposes 8 tools, scoped to the workspace tied to your API key. Mutations write to the audit log with `metadata.transport = "mcp"`.diff --git a/apps/docs/src/content/docs/sdk/nodejs/authentication.mdx b/apps/docs/src/content/docs/sdk/nodejs/authentication.mdxindex d3621a26e..c09b7b476 100644--- a/apps/docs/src/content/docs/sdk/nodejs/authentication.mdx+++ b/apps/docs/src/content/docs/sdk/nodejs/authentication.mdx@@ -41,6 +41,32 @@ await openstatus.monitor.v1.MonitorService.listMonitors({}, { headers });Get your API key from the [openstatus dashboard](https://www.openstatus.dev/app).+## Scopes++Each API key carries a scope that controls what it can do:++- **Read-only** (`['read']`) — list/get endpoints only. Mutations return `403 Forbidden`. Recommended for AI agents and read-only dashboards.+- **Read & write** (`['write']`) — full workspace access. Required for CI/CD and automation.++Scope is set when the key is created and is **immutable** — to change it, revoke the key and issue a new one. Existing keys created before this feature shipped continue to work as Read & write.++`GET /v1/whoami` echoes the resolved actor's scopes back so a client can introspect what it's allowed to do without probe-and-fail:++```json+{+ "name": "Acme",+ "slug": "acme",+ "plan": "team",+ "actor": {+ "type": "apiKey",+ "keyId": "42",+ "scopes": ["read"]+ }+}+```++A read-only key can revoke itself via `DELETE /v1/api-key/{id}` (the only carve-out — without it, a leaked read-only key would have no rotation path other than the dashboard). Revoking a *different* key from a read-only actor returns `403 Forbidden`.+## Custom Base URLFor self-hosted instances or staging environments:diff --git a/apps/server/src/libs/middlewares/auth.ts b/apps/server/src/libs/middlewares/auth.tsindex 756567196..198d5bd65 100644--- a/apps/server/src/libs/middlewares/auth.ts+++ b/apps/server/src/libs/middlewares/auth.ts@@ -7,7 +7,11 @@ import { OpenStatusApiError } from "@/libs/errors";import type { Variables } from "@/types";import { getLogger } from "@logtape/logtape";import { db, eq } from "@openstatus/db";-import { selectWorkspaceSchema, workspace } from "@openstatus/db/src/schema";+import {+ type Scope,+ selectWorkspaceSchema,+ workspace,+} from "@openstatus/db/src/schema";import { apiKey } from "@openstatus/db/src/schema/api-keys";import {shouldUpdateLastUsed,@@ -111,6 +115,7 @@ export async function authMiddleware(c.set("apiKey", {id: result.keyId ?? `ws:${workspaceData.id}`,createdById: result.createdById,+ scopes: result.scopes ?? ["write"],});await next();@@ -135,6 +140,14 @@ export async function validateKey(key: string): Promise<{* `actor_user_id = NULL`.*/createdById?: number;+ /**+ * Access-control scopes for the resolved key. Custom keys: row+ * scopes. Unkey fallback: `['write']` (legacy posture — keys+ * minted before scopes existed kept full workspace access).+ * Super-admin / dev fallback: `['*']` so the matcher treats them+ * uniformly without a hardcoded bypass.+ */+ scopes?: Scope[];};error?: { message: string };}> {@@ -182,11 +195,15 @@ export async function validateKey(key: string): Promise<{authMethod: "custom_key",keyId: String(customKey.id),createdById: customKey.createdById,+ scopes: customKey.scopes,},};}- // 2. Fall back to Unkey (transition period)+ // 2. Fall back to Unkey (transition period). Unkey-validated+ // keys predate the scopes column, so they carry the legacy+ // posture (`write`). When/if Unkey gets RBAC metadata, plumb+ // it in here.const unkey = new UnkeyCore({ rootKey: env.UNKEY_TOKEN });const res = await keysVerifyKey(unkey, { key });if (!res.ok) {@@ -202,11 +219,13 @@ export async function validateKey(key: string): Promise<{ownerId: res.value.data.identity?.externalId,authMethod: "unkey",keyId: res.value.data.keyId,+ scopes: ["write"],},error: undefined,};}- // Special bypass for our workspace+ // Special bypass for our workspace. `'*'` is internal-only — never+ // settable via any public API.if (key.startsWith("sa_") && key === env.SUPER_ADMIN_TOKEN) {return {result: {@@ -214,6 +233,7 @@ export async function validateKey(key: string): Promise<{ownerId: "1",authMethod: "super_admin",keyId: "super_admin",+ scopes: ["*"],},};}@@ -226,8 +246,16 @@ export async function validateKey(key: string): Promise<{// In dev / test mode we can use the key as the ownerId. The same// string also stands in for the keyId — there is no separate- // identity record to reference.+ // identity record to reference. Dev keys get `'*'` so local testing+ // mirrors super-admin and isn't accidentally locked out by scope+ // checks.return {- result: { valid: true, ownerId: key, authMethod: "dev", keyId: key },+ result: {+ valid: true,+ ownerId: key,+ authMethod: "dev",+ keyId: key,+ scopes: ["*"],+ },};}diff --git a/apps/server/src/libs/middlewares/index.ts b/apps/server/src/libs/middlewares/index.tsindex c11d8d36a..9840dc3cc 100644--- a/apps/server/src/libs/middlewares/index.ts+++ b/apps/server/src/libs/middlewares/index.ts@@ -1,3 +1,4 @@export * from "./auth";+export * from "./require-scope";export * from "./track";export * from "./plan";diff --git a/apps/server/src/libs/middlewares/require-scope.test.ts b/apps/server/src/libs/middlewares/require-scope.test.tsnew file mode 100644index 000000000..7f5386866--- /dev/null+++ b/apps/server/src/libs/middlewares/require-scope.test.ts@@ -0,0 +1,84 @@+import { describe, expect, test } from "bun:test";+import { Hono } from "hono";++import type { Variables } from "@/types";+import type { Scope } from "@openstatus/db/src/schema";+import { requireWriteScope } from "./require-scope";++/**+ * Spin up a minimal Hono app, pre-populate `apiKey` (simulating+ * `authMiddleware` having already run), mount `requireWriteScope`,+ * and exercise it with a real `app.request`. Closer to the production+ * shape than calling the middleware function directly with a mock+ * context.+ */+function makeApp(scopes: Scope[] | undefined): Hono<{ Variables: Variables }> {+ const app = new Hono<{ Variables: Variables }>();+ app.use("*", async (c, next) => {+ if (scopes !== undefined) {+ c.set("apiKey", {+ id: "test-key",+ createdById: 1,+ scopes,+ });+ }+ await next();+ });+ app.use("*", requireWriteScope());+ app.get("/r", (c) => c.text("ok-get"));+ app.post("/r", (c) => c.text("ok-post"));+ app.put("/r", (c) => c.text("ok-put"));+ app.delete("/r", (c) => c.text("ok-delete"));+ return app;+}++describe("requireWriteScope", () => {+ test("GET passes for read-only key", async () => {+ const res = await makeApp(["read"]).request("/r", { method: "GET" });+ expect(res.status).toBe(200);+ });++ test("HEAD passes for read-only key", async () => {+ const res = await makeApp(["read"]).request("/r", { method: "HEAD" });+ expect(res.status).toBe(200);+ });++ test("POST returns 403 for read-only key", async () => {+ const res = await makeApp(["read"]).request("/r", { method: "POST" });+ expect(res.status).toBe(403);+ });++ test("PUT returns 403 for read-only key", async () => {+ const res = await makeApp(["read"]).request("/r", { method: "PUT" });+ expect(res.status).toBe(403);+ });++ test("DELETE returns 403 for read-only key", async () => {+ const res = await makeApp(["read"]).request("/r", { method: "DELETE" });+ expect(res.status).toBe(403);+ });++ test("POST passes for write key", async () => {+ const res = await makeApp(["write"]).request("/r", { method: "POST" });+ expect(res.status).toBe(200);+ });++ test("POST passes for super-admin '*' key", async () => {+ const res = await makeApp(["*"]).request("/r", { method: "POST" });+ expect(res.status).toBe(200);+ });++ test("POST returns 403 for empty scopes (fail-closed)", async () => {+ const res = await makeApp([]).request("/r", { method: "POST" });+ expect(res.status).toBe(403);+ });++ test("missing apiKey defers to upstream (no 403, would be 401 in prod)", async () => {+ // `requireWriteScope` is not the auth gate — when `apiKey` isn't+ // set, it must let the request flow on so `authMiddleware` (in+ // prod) can return its own 401 instead of this layer returning a+ // confusing 403.+ const res = await makeApp(undefined).request("/r", { method: "POST" });+ expect(res.status).toBe(200);+ });+});diff --git a/apps/server/src/libs/middlewares/require-scope.ts b/apps/server/src/libs/middlewares/require-scope.tsnew file mode 100644index 000000000..a6166648f--- /dev/null+++ b/apps/server/src/libs/middlewares/require-scope.ts@@ -0,0 +1,50 @@+import type { MiddlewareHandler } from "hono";+import { HTTPException } from "hono/http-exception";++import type { Variables } from "@/types";++/**+ * V1 REST middleware that enforces the `'write'` scope on any+ * non-read HTTP method. Mounted on the V1 router, chained after+ * `authMiddleware`.+ *+ * Why a transport-level check on V1 specifically: the V1 routes+ * predate the services-first convention and currently do inline+ * Drizzle queries (zero `@openstatus/services` imports). Service-level+ * `requireScope` would silently skip every V1 write handler. This+ * middleware closes the gap.+ *+ * The HTTP-method-to-scope mapping is correct for V1 because every+ * V1 write route is a `POST`/`PUT`/`PATCH`/`DELETE` and every read+ * route is `GET`/`HEAD`. Includes `POST /v1/check` (on-demand+ * probe) — POST is write per the plan's write-rule definition.+ *+ * After per-route migration to services, this stays as+ * defense-in-depth.+ */+export function requireWriteScope(): MiddlewareHandler<{+ Variables: Variables;+}> {+ return async (c, next) => {+ const method = c.req.method;+ if (method === "GET" || method === "HEAD") return next();++ const apiKey = c.get("apiKey");+ // `authMiddleware` runs first and rejects requests with no key.+ // If we still see a missing key here, defer to it — don't 403 a+ // request that's actually 401.+ if (!apiKey) return next();++ // `?? []` is belt-and-braces: the type says `scopes` is non-optional,+ // but if `authMiddleware` ever errors after partially populating+ // `apiKey` we want fail-closed (no scopes = no write), not a crash+ // on `.includes`.+ const scopes = apiKey.scopes ?? [];+ if (!scopes.includes("write") && !scopes.includes("*")) {+ throw new HTTPException(403, {+ message: "API key lacks write scope",+ });+ }+ return next();+ };+}diff --git a/apps/server/src/libs/middlewares/validate-key.test.ts b/apps/server/src/libs/middlewares/validate-key.test.tsnew file mode 100644index 000000000..28527fb19--- /dev/null+++ b/apps/server/src/libs/middlewares/validate-key.test.ts@@ -0,0 +1,32 @@+import { describe, expect, test } from "bun:test";++import { validateKey } from "./auth";++/**+ * `validateKey` has three production branches (custom DB key, Unkey+ * fallback, super-admin) and one dev fallback. Tests here cover the+ * dev fallback exhaustively. The production branches require flipping+ * `NODE_ENV` at module-load time, which reroutes other middleware in+ * this app (see `routes/mcp/handler.test.ts` for the same caveat) — a+ * dedicated production-mode test harness is out of scope.+ *+ * What we DO assert structurally even without that harness:+ * - dev fallback returns scopes `['*']` (so local dev mirrors super-+ * admin and isn't accidentally locked out by scope checks)+ * - the `keyId` round-trips so audit attribution holds+ */+describe("validateKey (dev fallback)", () => {+ test("returns scopes ['*'] so local dev mirrors super-admin", async () => {+ const { result, error } = await validateKey("anything");+ expect(error).toBeUndefined();+ expect(result.valid).toBe(true);+ expect(result.scopes).toEqual(["*"]);+ });++ test("uses the input string as both ownerId and keyId", async () => {+ const { result } = await validateKey("dev-key-42");+ expect(result.ownerId).toBe("dev-key-42");+ expect(result.keyId).toBe("dev-key-42");+ expect(result.authMethod).toBe("dev");+ });+});diff --git a/apps/server/src/routes/mcp/adapter.test.ts b/apps/server/src/routes/mcp/adapter.test.tsnew file mode 100644index 000000000..b59441890--- /dev/null+++ b/apps/server/src/routes/mcp/adapter.test.ts@@ -0,0 +1,54 @@+import { describe, expect, test } from "bun:test";++import type { Workspace } from "@openstatus/db/src/schema";+import { ForbiddenError, NotFoundError } from "@openstatus/services";++import { mapError, toServiceCtx } from "./adapter";++const workspace = { id: 1, slug: "ws", name: "ws" } as unknown as Workspace;++describe("toServiceCtx (MCP)", () => {+ test("propagates apiKey.scopes onto actor.scopes", () => {+ const ctx = toServiceCtx({+ workspace,+ apiKey: { id: "k1", createdById: 7, scopes: ["read"] },+ requestId: "req-1",+ });+ expect(ctx.actor.type).toBe("mcp");+ if (ctx.actor.type === "mcp") {+ expect(ctx.actor.scopes).toEqual(["read"]);+ expect(ctx.actor.keyId).toBe("k1");+ expect(ctx.actor.userId).toBe(7);+ }+ });++ test("propagates ['*'] super-admin scopes intact", () => {+ const ctx = toServiceCtx({+ workspace,+ apiKey: { id: "sa", scopes: ["*"] },+ requestId: "req-2",+ });+ if (ctx.actor.type === "mcp") {+ expect(ctx.actor.scopes).toEqual(["*"]);+ }+ });+});++describe("mapError", () => {+ test("ForbiddenError throws McpError (transport-level)", () => {+ // FORBIDDEN belongs to the unrecoverable bucket — it must escape+ // `mapError` as a thrown `McpError` rather than a recoverable+ // `CallToolResult`. The LLM has no input to retry; this is an+ // auth boundary failure.+ expect(() => mapError(new ForbiddenError("nope"))).toThrow();+ });++ test("NotFoundError returns recoverable CallToolResult", () => {+ // Sanity check that the existing recoverable branch still works+ // — proves the FORBIDDEN test above is meaningful (i.e. mapError+ // does discriminate, it's not always throwing).+ const result = mapError(new NotFoundError("page", 99));+ expect(result.isError).toBe(true);+ expect(Array.isArray(result.content)).toBe(true);+ });+});diff --git a/apps/server/src/routes/mcp/adapter.ts b/apps/server/src/routes/mcp/adapter.tsindex ff6c426cb..b19ede159 100644--- a/apps/server/src/routes/mcp/adapter.ts+++ b/apps/server/src/routes/mcp/adapter.ts@@ -1,6 +1,6 @@import { ErrorCode, McpError } from "@modelcontextprotocol/sdk/types.js";import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";-import type { Workspace } from "@openstatus/db/src/schema";+import type { Scope, Workspace } from "@openstatus/db/src/schema";import { type ServiceContext, ServiceError } from "@openstatus/services";import { ZodError } from "zod";@@ -19,7 +19,7 @@ import { ZodError } from "zod";*/export function toServiceCtx(args: {workspace: Workspace;- apiKey: { id: string; createdById?: number };+ apiKey: { id: string; createdById?: number; scopes: Scope[] };requestId?: string;}): ServiceContext {return {@@ -28,6 +28,7 @@ export function toServiceCtx(args: {type: "mcp",keyId: args.apiKey.id,userId: args.apiKey.createdById,+ scopes: args.apiKey.scopes,},requestId: args.requestId,};diff --git a/apps/server/src/routes/mcp/tools/maintenance.ts b/apps/server/src/routes/mcp/tools/maintenance.tsindex b3748b89b..8a8bb74d1 100644--- a/apps/server/src/routes/mcp/tools/maintenance.ts+++ b/apps/server/src/routes/mcp/tools/maintenance.ts@@ -12,6 +12,7 @@ import {import { z } from "zod";import { runTool } from "../adapter";+import { registerScopedTool } from "./register-scoped";const logger = getLogger("api-server");@@ -24,212 +25,217 @@ export function registerMaintenanceTools(): Map<string, RegisteredTool> {const registered = new Map<string, RegisteredTool>();- registered.set(+ const t_listMaintenances = registerScopedTool(+ server,+ ctx,"list_maintenances",- server.registerTool(- "list_maintenances",- {- description:- "List maintenance windows in this workspace, newest first. Paginated via `page` (1-indexed) and `perPage`. The response's `pagination` object carries `totalSize`, `totalPages`, `page`, and `perPage` so the LLM can decide whether to fetch the next page or warn the user that the result is paginated.",- annotations: { readOnlyHint: true, openWorldHint: false },- inputSchema: {- pageId: z- .number()- .int()- .optional()- .describe("If set, only maintenances attached to this page id."),- page: z- .number()- .int()- .min(1)- .default(1)- .describe("1-indexed page number (default 1)."),- perPage: z- .number()- .int()- .min(1)- .max(PER_PAGE_MAX)- .default(PER_PAGE_DEFAULT)- .describe(- `Items per page (default ${PER_PAGE_DEFAULT}, max ${PER_PAGE_MAX}).`,- ),- },- outputSchema: {- items: z.array(- z.object({- id: z.number().int(),- title: z.string(),- message: z.string(),- from: z.string(),- to: z.string(),- pageId: z.number().int().nullable(),- pageComponentIds: z.array(z.number().int()),- }),+ {+ scope: "read",+ description:+ "List maintenance windows in this workspace, newest first. Paginated via `page` (1-indexed) and `perPage`. The response's `pagination` object carries `totalSize`, `totalPages`, `page`, and `perPage` so the LLM can decide whether to fetch the next page or warn the user that the result is paginated.",+ annotations: { readOnlyHint: true, openWorldHint: false },+ inputSchema: {+ pageId: z+ .number()+ .int()+ .optional()+ .describe("If set, only maintenances attached to this page id."),+ page: z+ .number()+ .int()+ .min(1)+ .default(1)+ .describe("1-indexed page number (default 1)."),+ perPage: z+ .number()+ .int()+ .min(1)+ .max(PER_PAGE_MAX)+ .default(PER_PAGE_DEFAULT)+ .describe(+ `Items per page (default ${PER_PAGE_DEFAULT}, max ${PER_PAGE_MAX}).`,),- pagination: z.object({- page: z.number().int(),- perPage: z.number().int(),- totalSize: z.number().int(),- totalPages: z.number().int(),- }),- },},- async ({ pageId, page, perPage }) =>- runTool(- () =>- listMaintenances({- ctx,- input: {- limit: perPage ?? PER_PAGE_DEFAULT,- offset: ((page ?? 1) - 1) * (perPage ?? PER_PAGE_DEFAULT),- pageId,- order: "desc",- },- }),- ({ items, totalSize }) => {- const currentPage = page ?? 1;- const size = perPage ?? PER_PAGE_DEFAULT;- const summarised = items.map((m) => ({- id: m.id,- title: m.title,- message: m.message,- from: m.from.toISOString(),- to: m.to.toISOString(),- pageId: m.pageId,- pageComponentIds: m.pageComponentIds,- }));- const out = {- items: summarised,- pagination: {- page: currentPage,- perPage: size,- totalSize,- totalPages: Math.max(1, Math.ceil(totalSize / size)),- },- };- return {- content: [{ type: "text", text: JSON.stringify(out) }],- structuredContent: out,- };- },+ outputSchema: {+ items: z.array(+ z.object({+ id: z.number().int(),+ title: z.string(),+ message: z.string(),+ from: z.string(),+ to: z.string(),+ pageId: z.number().int().nullable(),+ pageComponentIds: z.array(z.number().int()),+ }),),- ),+ pagination: z.object({+ page: z.number().int(),+ perPage: z.number().int(),+ totalSize: z.number().int(),+ totalPages: z.number().int(),+ }),+ },+ },+ async ({ pageId, page, perPage }) =>+ runTool(+ () =>+ listMaintenances({+ ctx,+ input: {+ limit: perPage ?? PER_PAGE_DEFAULT,+ offset: ((page ?? 1) - 1) * (perPage ?? PER_PAGE_DEFAULT),+ pageId,+ order: "desc",+ },+ }),+ ({ items, totalSize }) => {+ const currentPage = page ?? 1;+ const size = perPage ?? PER_PAGE_DEFAULT;+ const summarised = items.map((m) => ({+ id: m.id,+ title: m.title,+ message: m.message,+ from: m.from.toISOString(),+ to: m.to.toISOString(),+ pageId: m.pageId,+ pageComponentIds: m.pageComponentIds,+ }));+ const out = {+ items: summarised,+ pagination: {+ page: currentPage,+ perPage: size,+ totalSize,+ totalPages: Math.max(1, Math.ceil(totalSize / size)),+ },+ };+ return {+ content: [{ type: "text", text: JSON.stringify(out) }],+ structuredContent: out,+ };+ },+ ),);+ if (t_listMaintenances)+ registered.set("list_maintenances", t_listMaintenances);- registered.set(+ const t_createMaintenance = registerScopedTool(+ server,+ ctx,"create_maintenance",- server.registerTool(- "create_maintenance",- {- description:- "Schedule a maintenance window on a status page. PUBLIC, AUDIT-LOGGED, AND POTENTIALLY NOTIFIES SUBSCRIBERS — irreversible side effects.\n\nMANDATORY workflow before calling:\n1. Draft the title, message, and time window (ISO 8601 from/to).\n2. Show the draft to the user for review.\n3. Ask explicitly: 'Should I notify subscribers (email + integrations) about this maintenance window? yes/no'.\n4. Only call this tool once the user has confirmed BOTH the content AND the notify decision.\n\nSubscriber notifications dispatch as part of this call only — you cannot notify retroactively for an existing window. There is NO separate notify tool. If notify is false here, this window will never reach subscribers. Note: the maintenance row persists even if the notify dispatch fails; the response's `notified` field reports whether subscribers were actually notified.\n\npageId MUST come from list_status_pages — never guess.",- annotations: {- destructiveHint: true,- idempotentHint: false,- openWorldHint: true,- },- inputSchema: {- title: z- .string()- .min(1)- .max(256)- .describe("Short, public-facing title for the maintenance window."),- message: z- .string()- .min(1)- .describe("Public message describing the work, shown on the page."),- from: z.iso- .datetime()- .describe("Start time, ISO 8601 (e.g. 2026-04-30T14:00:00Z)."),- to: z.iso- .datetime()- .describe(- "End time, ISO 8601. Must be strictly after `from` — service rejects otherwise.",- ),- pageId: z- .number()- .int()- .describe(- "Status page to attach the maintenance to. Resolve via list_status_pages — do not guess.",- ),- pageComponentIds: z- .array(z.number().int())- .default([])- .describe(- "Optional component ids affected by the maintenance. Must belong to pageId.",- ),- notify: z- .boolean()- .describe(- "REQUIRED. Whether to dispatch subscriber notifications for the new window. You MUST ask the user before deciding — do not infer. true = notify on creation. false = create silently; subscribers will NEVER be notified about this window (you cannot notify retroactively).",- ),- },- outputSchema: {- id: z.number().int(),- title: z.string(),- from: z.string(),- to: z.string(),- pageId: z.number().int().nullable(),- notified: z.boolean(),- },+ {+ scope: "write",+ description:+ "Schedule a maintenance window on a status page. PUBLIC, AUDIT-LOGGED, AND POTENTIALLY NOTIFIES SUBSCRIBERS — irreversible side effects.\n\nMANDATORY workflow before calling:\n1. Draft the title, message, and time window (ISO 8601 from/to).\n2. Show the draft to the user for review.\n3. Ask explicitly: 'Should I notify subscribers (email + integrations) about this maintenance window? yes/no'.\n4. Only call this tool once the user has confirmed BOTH the content AND the notify decision.\n\nSubscriber notifications dispatch as part of this call only — you cannot notify retroactively for an existing window. There is NO separate notify tool. If notify is false here, this window will never reach subscribers. Note: the maintenance row persists even if the notify dispatch fails; the response's `notified` field reports whether subscribers were actually notified.\n\npageId MUST come from list_status_pages — never guess.",+ annotations: {+ readOnlyHint: false,+ destructiveHint: true,+ idempotentHint: false,+ openWorldHint: true,},- async (input) =>- runTool(- async () => {- const record = await createMaintenance({- ctx,- input: {- title: input.title,- message: input.message,- from: new Date(input.from),- to: new Date(input.to),- pageId: input.pageId,- pageComponentIds: input.pageComponentIds ?? [],- },- });- // The maintenance row is already persisted; a notify- // dispatch failure must not propagate as a tool error.- // Otherwise the LLM treats the whole call as failed and- // may retry, double-publishing the window. Report- // partial success via `notified: false`.- let notified = false;- if (input.notify) {- try {- await notifyMaintenance({- ctx,- input: { maintenanceId: record.id },- });- notified = true;- } catch (err) {- logger.error(- "notifyMaintenance failed after create_maintenance {*}",- {- err,- workspaceId: ctx.workspace.id,- maintenanceId: record.id,- },- );- }+ inputSchema: {+ title: z+ .string()+ .min(1)+ .max(256)+ .describe("Short, public-facing title for the maintenance window."),+ message: z+ .string()+ .min(1)+ .describe("Public message describing the work, shown on the page."),+ from: z.iso+ .datetime()+ .describe("Start time, ISO 8601 (e.g. 2026-04-30T14:00:00Z)."),+ to: z.iso+ .datetime()+ .describe(+ "End time, ISO 8601. Must be strictly after `from` — service rejects otherwise.",+ ),+ pageId: z+ .number()+ .int()+ .describe(+ "Status page to attach the maintenance to. Resolve via list_status_pages — do not guess.",+ ),+ pageComponentIds: z+ .array(z.number().int())+ .default([])+ .describe(+ "Optional component ids affected by the maintenance. Must belong to pageId.",+ ),+ notify: z+ .boolean()+ .describe(+ "REQUIRED. Whether to dispatch subscriber notifications for the new window. You MUST ask the user before deciding — do not infer. true = notify on creation. false = create silently; subscribers will NEVER be notified about this window (you cannot notify retroactively).",+ ),+ },+ outputSchema: {+ id: z.number().int(),+ title: z.string(),+ from: z.string(),+ to: z.string(),+ pageId: z.number().int().nullable(),+ notified: z.boolean(),+ },+ },+ async (input) =>+ runTool(+ async () => {+ const record = await createMaintenance({+ ctx,+ input: {+ title: input.title,+ message: input.message,+ from: new Date(input.from),+ to: new Date(input.to),+ pageId: input.pageId,+ pageComponentIds: input.pageComponentIds ?? [],+ },+ });+ // The maintenance row is already persisted; a notify+ // dispatch failure must not propagate as a tool error.+ // Otherwise the LLM treats the whole call as failed and+ // may retry, double-publishing the window. Report+ // partial success via `notified: false`.+ let notified = false;+ if (input.notify) {+ try {+ await notifyMaintenance({+ ctx,+ input: { maintenanceId: record.id },+ });+ notified = true;+ } catch (err) {+ logger.error(+ "notifyMaintenance failed after create_maintenance {*}",+ {+ err,+ workspaceId: ctx.workspace.id,+ maintenanceId: record.id,+ },+ );}- return { record, notified };- },- ({ record, notified }) => {- const out = {- id: record.id,- title: record.title,- from: record.from.toISOString(),- to: record.to.toISOString(),- pageId: record.pageId,- notified,- };- return {- content: [{ type: "text", text: JSON.stringify(out) }],- structuredContent: out,- };- },- ),- ),+ }+ return { record, notified };+ },+ ({ record, notified }) => {+ const out = {+ id: record.id,+ title: record.title,+ from: record.from.toISOString(),+ to: record.to.toISOString(),+ pageId: record.pageId,+ notified,+ };+ return {+ content: [{ type: "text", text: JSON.stringify(out) }],+ structuredContent: out,+ };+ },+ ),);+ if (t_createMaintenance)+ registered.set("create_maintenance", t_createMaintenance);return registered;}diff --git a/apps/server/src/routes/mcp/tools/page.ts b/apps/server/src/routes/mcp/tools/page.tsindex bcb3879e4..fda77a249 100644--- a/apps/server/src/routes/mcp/tools/page.ts+++ b/apps/server/src/routes/mcp/tools/page.ts@@ -7,6 +7,7 @@ import { listPages } from "@openstatus/services/page";import { z } from "zod";import { runTool } from "../adapter";+import { registerScopedTool } from "./register-scoped";// Pages carry secrets (`password`, `customDomain` access controls) that// must never reach an LLM client. Output is a deliberately slim shape@@ -23,42 +24,43 @@ export function registerPageTools(): Map<string, RegisteredTool> {const registered = new Map<string, RegisteredTool>();- registered.set(+ const t_listStatusPages = registerScopedTool(+ server,+ ctx,"list_status_pages",- server.registerTool(- "list_status_pages",- {- description:- "List status pages in this workspace with their slug and ids. Use to discover the pageId required by create_status_report and create_maintenance.",- annotations: { readOnlyHint: true, openWorldHint: false },- inputSchema: {},- outputSchema: {- items: z.array(- z.object({- id: z.number().int(),- title: z.string(),- slug: z.string(),- }),- ),- },- },- async () =>- runTool(- () => listPages({ ctx, input: { order: "desc" } }),- (pages) => {- const items = pages.map((p) => ({- id: p.id,- title: p.title,- slug: p.slug,- }));- return {- content: [{ type: "text", text: JSON.stringify({ items }) }],- structuredContent: { items },- };- },+ {+ scope: "read",+ description:+ "List status pages in this workspace with their slug and ids. Use to discover the pageId required by create_status_report and create_maintenance.",+ annotations: { readOnlyHint: true, openWorldHint: false },+ inputSchema: {},+ outputSchema: {+ items: z.array(+ z.object({+ id: z.number().int(),+ title: z.string(),+ slug: z.string(),+ }),),- ),+ },+ },+ async () =>+ runTool(+ () => listPages({ ctx, input: { order: "desc" } }),+ (pages) => {+ const items = pages.map((p) => ({+ id: p.id,+ title: p.title,+ slug: p.slug,+ }));+ return {+ content: [{ type: "text", text: JSON.stringify({ items }) }],+ structuredContent: { items },+ };+ },+ ),);+ if (t_listStatusPages) registered.set("list_status_pages", t_listStatusPages);return registered;}diff --git a/apps/server/src/routes/mcp/tools/register-scoped.test.ts b/apps/server/src/routes/mcp/tools/register-scoped.test.tsnew file mode 100644index 000000000..dd8676882--- /dev/null+++ b/apps/server/src/routes/mcp/tools/register-scoped.test.ts@@ -0,0 +1,134 @@+import { describe, expect, test } from "bun:test";+import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";+import type { Workspace } from "@openstatus/db/src/schema";+import type { ServiceContext } from "@openstatus/services";++import { registerScopedTool } from "./register-scoped";++const wsStub = { id: 1, slug: "ws", name: "ws" } as unknown as Workspace;++function makeServer() {+ return new McpServer(+ { name: "test", version: "0.0.0" },+ { capabilities: { tools: { listChanged: false } } },+ );+}++function ctxWithScopes(+ scopes: ServiceContext["actor"] extends infer A+ ? A extends { scopes: infer S }+ ? S+ : never+ : never,+): ServiceContext {+ return {+ workspace: wsStub,+ actor: {+ type: "mcp",+ keyId: "k",+ scopes: scopes as never,+ },+ };+}++describe("registerScopedTool", () => {+ test("registers when actor scope satisfies tool scope", () => {+ const server = makeServer();+ const ctx = ctxWithScopes(["write"]);+ const result = registerScopedTool(+ server,+ ctx,+ "demo_write",+ {+ scope: "write",+ description: "demo",+ annotations: { readOnlyHint: false },+ inputSchema: {},+ },+ async () => ({ content: [{ type: "text", text: "ok" }] }),+ );+ expect(result).toBeDefined();+ });++ test("returns undefined (not registered) when actor scope is insufficient", () => {+ const server = makeServer();+ const ctx = ctxWithScopes(["read"]);+ const result = registerScopedTool(+ server,+ ctx,+ "demo_write_skipped",+ {+ scope: "write",+ description: "demo",+ annotations: { readOnlyHint: false },+ inputSchema: {},+ },+ async () => ({ content: [{ type: "text", text: "ok" }] }),+ );+ expect(result).toBeUndefined();+ });++ test("throws when readOnlyHint disagrees with scope (write tool, hint=true)", () => {+ // The disagreement guard is defense-in-depth: a write tool that+ // declares `readOnlyHint: true` would lie to MCP clients about+ // safe-to-call status. Catching it at registration means it can't+ // ship.+ const server = makeServer();+ const ctx = ctxWithScopes(["*"]);+ expect(() =>+ registerScopedTool(+ server,+ ctx,+ "lying_tool",+ {+ scope: "write",+ description: "writes but claims read-only",+ annotations: { readOnlyHint: true },+ inputSchema: {},+ },+ async () => ({ content: [{ type: "text", text: "ok" }] }),+ ),+ ).toThrow(/disagrees with annotations.readOnlyHint/);+ });++ test("throws when readOnlyHint disagrees with scope (read tool, hint=false)", () => {+ const server = makeServer();+ const ctx = ctxWithScopes(["*"]);+ expect(() =>+ registerScopedTool(+ server,+ ctx,+ "wrong_read_hint",+ {+ scope: "read",+ description: "reads but claims not read-only",+ annotations: { readOnlyHint: false },+ inputSchema: {},+ },+ async () => ({ content: [{ type: "text", text: "ok" }] }),+ ),+ ).toThrow(/disagrees with annotations.readOnlyHint/);+ });++ test("accepts a tool that omits readOnlyHint (no validation triggered)", () => {+ // The hint is recommended per the MCP spec, but optional. When+ // absent, the wrapper passes annotations through unchanged — the+ // SDK / client treats it as unspecified.+ const server = makeServer();+ const ctx = ctxWithScopes(["*"]);+ expect(() =>+ registerScopedTool(+ server,+ ctx,+ "no_hint",+ {+ scope: "read",+ description: "no hint declared",+ annotations: { openWorldHint: false },+ inputSchema: {},+ },+ async () => ({ content: [{ type: "text", text: "ok" }] }),+ ),+ ).not.toThrow();+ });+});diff --git a/apps/server/src/routes/mcp/tools/register-scoped.ts b/apps/server/src/routes/mcp/tools/register-scoped.tsnew file mode 100644index 000000000..5da506840--- /dev/null+++ b/apps/server/src/routes/mcp/tools/register-scoped.ts@@ -0,0 +1,108 @@+import type {+ McpServer,+ RegisteredTool,+ ToolCallback,+} from "@modelcontextprotocol/sdk/server/mcp.js";+import type { Scope } from "@openstatus/db/src/schema";+import type { ServiceContext } from "@openstatus/services";+import { matchesScope } from "@openstatus/services/auth";+import type { ZodRawShape } from "zod";++/**+ * Annotation hints carried through to the SDK. These are first-class+ * MCP-spec metadata that clients use for UX decisions (caching,+ * confirmation prompts, rendering). We mirror the standard fields.+ *+ * `readOnlyHint` is allowed alongside `scope` — they convey related+ * but distinct information (server-side access control vs.+ * client-facing hint), and external MCP clients (Claude Desktop,+ * Cursor) read the annotation, not our scope. The wrapper validates+ * that the two don't disagree (a write tool with `readOnlyHint: true`+ * would lie to clients).+ */+type ToolAnnotations = {+ readOnlyHint?: boolean;+ destructiveHint?: boolean;+ idempotentHint?: boolean;+ openWorldHint?: boolean;+ title?: string;+};++/**+ * Tool config layered on top of the MCP SDK's `registerTool` shape.+ * The new field is `scope`: a required read/write decision per tool.+ */+type ScopedToolDefinition<+ InputArgs extends ZodRawShape | undefined,+ OutputArgs extends ZodRawShape | undefined,+> = {+ scope: Scope;+ description: string;+ annotations?: ToolAnnotations;+ inputSchema?: InputArgs;+ outputSchema?: OutputArgs;+};++/**+ * Read the actor's scopes for tool gating. Per the plan, non-key+ * actors (today: nothing else hits MCP, but defense-in-depth) get+ * full access — they're already past their own auth boundary.+ */+function actorScopes(ctx: ServiceContext): Scope[] {+ if (ctx.actor.type === "apiKey" || ctx.actor.type === "mcp") {+ return ctx.actor.scopes;+ }+ return ["*"];+}++/**+ * Register an MCP tool only when the calling actor's scopes satisfy+ * `def.scope`. Read-only keys never see write tools in `tools/list`,+ * because skipped tools aren't registered with the server at all.+ *+ * Defense in depth: even if the filter has a bug, the underlying+ * service verb still calls `requireScope(ctx, 'write')` and throws+ * `ForbiddenError`. The filter is UX; the service check is correctness.+ *+ * Returns the `RegisteredTool` when registered, `undefined` when+ * filtered out (so callers can still maintain a `Map<name,+ * RegisteredTool>` for tests / debugging).+ */+export function registerScopedTool<+ // biome-ignore lint/suspicious/noExplicitAny: SDK uses `any` here too+ InputArgs extends ZodRawShape | undefined = any,+ // biome-ignore lint/suspicious/noExplicitAny: SDK uses `any` here too+ OutputArgs extends ZodRawShape | undefined = any,+>(+ server: McpServer,+ ctx: ServiceContext,+ name: string,+ def: ScopedToolDefinition<InputArgs, OutputArgs>,+ handler: ToolCallback<InputArgs extends ZodRawShape ? InputArgs : undefined>,+): RegisteredTool | undefined {+ if (!matchesScope(actorScopes(ctx), def.scope)) {+ return undefined;+ }++ const { scope, annotations, ...rest } = def;++ // Defense: a write tool with `readOnlyHint: true` would lie to MCP+ // clients (Claude Desktop, Cursor) about safe-to-call status. Catch+ // disagreement at registration so it can never ship.+ if (+ annotations?.readOnlyHint !== undefined &&+ annotations.readOnlyHint !== (scope === "read")+ ) {+ throw new Error(+ `MCP tool "${name}": scope="${scope}" disagrees with annotations.readOnlyHint=${annotations.readOnlyHint}`,+ );+ }++ const merged = { ...rest, annotations };+ // TODO(mcp-sdk): drop these casts when @modelcontextprotocol/sdk+ // exports the canonical config + handler types. The generic plumbing+ // around `registerTool` doesn't currently let us thread our narrowed+ // `ScopedToolDefinition` through without a cast at the boundary.+ // biome-ignore lint/suspicious/noExplicitAny: pass-through to SDK+ return server.registerTool(name, merged as any, handler as any);+}diff --git a/apps/server/src/routes/mcp/tools/status-report.ts b/apps/server/src/routes/mcp/tools/status-report.tsindex 45858612b..56f9e7316 100644--- a/apps/server/src/routes/mcp/tools/status-report.ts+++ b/apps/server/src/routes/mcp/tools/status-report.ts@@ -16,6 +16,7 @@ import {import { z } from "zod";import { runTool } from "../adapter";+import { registerScopedTool } from "./register-scoped";const logger = getLogger("api-server");@@ -37,507 +38,521 @@ export function registerStatusReportTools(): Map<string, RegisteredTool> {const registered = new Map<string, RegisteredTool>();- registered.set(+ const t_listStatusReports = registerScopedTool(+ server,+ ctx,"list_status_reports",- server.registerTool(- "list_status_reports",- {- description:- "List status reports in this workspace, newest first. Filter by status (e.g. exclude 'resolved' to see active incidents). Returns the most recent update per report so the LLM can see the current public message without a follow-up call. Paginated via `page` (1-indexed) and `perPage`. The response's `pagination` object carries `totalSize`, `totalPages`, `page`, and `perPage` so the LLM can decide whether to fetch the next page or warn the user.",- annotations: { readOnlyHint: true, openWorldHint: false },- inputSchema: {- filter: z- .enum(["active", "all"])- .default("active")- .describe(- "active = exclude resolved reports (default). all = every report regardless of status.",- ),- pageId: z- .number()- .int()- .optional()- .describe("If set, only reports attached to this page id."),- page: z- .number()- .int()- .min(1)- .default(1)- .describe("1-indexed page number (default 1)."),- perPage: z- .number()- .int()- .min(1)- .max(PER_PAGE_MAX)- .default(PER_PAGE_DEFAULT)- .describe(- `Items per page (default ${PER_PAGE_DEFAULT}, max ${PER_PAGE_MAX}).`,- ),- },- outputSchema: {- items: z.array(- z.object({- id: z.number().int(),- title: z.string(),- status: statusReportStatusSchema,- pageId: z.number().int().nullable(),- createdAt: z.string().nullable(),- updatedAt: z.string().nullable(),- latestUpdate: z- .object({- message: z.string(),- status: statusReportStatusSchema,- date: z.string().nullable(),- })- .nullable(),- }),+ {+ scope: "read",+ description:+ "List status reports in this workspace, newest first. Filter by status (e.g. exclude 'resolved' to see active incidents). Returns the most recent update per report so the LLM can see the current public message without a follow-up call. Paginated via `page` (1-indexed) and `perPage`. The response's `pagination` object carries `totalSize`, `totalPages`, `page`, and `perPage` so the LLM can decide whether to fetch the next page or warn the user.",+ annotations: { readOnlyHint: true, openWorldHint: false },+ inputSchema: {+ filter: z+ .enum(["active", "all"])+ .default("active")+ .describe(+ "active = exclude resolved reports (default). all = every report regardless of status.",),- pagination: z.object({- page: z.number().int(),- perPage: z.number().int(),- totalSize: z.number().int(),- totalPages: z.number().int(),- }),- },- },- async ({ filter, pageId, page, perPage }) =>- runTool(- () =>- listStatusReports({- ctx,- input: {- limit: perPage ?? PER_PAGE_DEFAULT,- offset: ((page ?? 1) - 1) * (perPage ?? PER_PAGE_DEFAULT),- statuses: filter === "active" ? ACTIVE_STATUSES : [],- pageId,- order: "desc",- },- }),- ({ items, totalSize }) => {- const currentPage = page ?? 1;- const size = perPage ?? PER_PAGE_DEFAULT;- const summarised = items.map((r) => {- const latestUpdate = r.updates[0] ?? null;- return {- id: r.id,- title: r.title,- status: r.status,- pageId: r.pageId,- createdAt: r.createdAt?.toISOString() ?? null,- updatedAt: r.updatedAt?.toISOString() ?? null,- latestUpdate: latestUpdate- ? {- message: latestUpdate.message,- status: latestUpdate.status,- date: latestUpdate.date?.toISOString() ?? null,- }- : null,- };- });- const out = {- items: summarised,- pagination: {- page: currentPage,- perPage: size,- totalSize,- totalPages: Math.max(1, Math.ceil(totalSize / size)),- },- };- return {- content: [- {- type: "text",- text: JSON.stringify(out),- },- ],- structuredContent: out,- };- },- ),- ),- );-- registered.set(- "create_status_report",- server.registerTool(- "create_status_report",- {- description:- "Create a new status report on a public status page. PUBLIC, AUDIT-LOGGED, AND POTENTIALLY NOTIFIES SUBSCRIBERS — irreversible side effects.\n\nMANDATORY workflow before calling:\n1. Draft the title, status, message, and affected components.\n2. Show the draft to the user for review.\n3. Ask explicitly: 'Should I notify subscribers (email + integrations) for this report? yes/no'.\n4. Only call this tool once the user has confirmed BOTH the content AND the notify decision.\n\nSubscriber notifications dispatch as part of this call only — you cannot notify retroactively for an existing update. There is NO separate notify tool. If notify is false here, that update will never reach subscribers. Note: the report persists even if the notify dispatch fails; the response's `notified` field reports whether subscribers were actually notified.\n\npageId MUST come from list_status_pages — never guess. pageComponentIds (if supplied) MUST belong to the same page.",- annotations: {- destructiveHint: true,- idempotentHint: false,- openWorldHint: true,- },- inputSchema: {- title: z- .string()- .min(1)- .max(256)- .describe("Short, public-facing title for the incident."),- status: statusReportStatusSchema.describe(- "Initial status for the report.",+ pageId: z+ .number()+ .int()+ .optional()+ .describe("If set, only reports attached to this page id."),+ page: z+ .number()+ .int()+ .min(1)+ .default(1)+ .describe("1-indexed page number (default 1)."),+ perPage: z+ .number()+ .int()+ .min(1)+ .max(PER_PAGE_MAX)+ .default(PER_PAGE_DEFAULT)+ .describe(+ `Items per page (default ${PER_PAGE_DEFAULT}, max ${PER_PAGE_MAX}).`,),- message: z- .string()- .min(1)- .describe(- "Initial public update message customers will see on the status page.",- ),- pageId: z- .number()- .int()- .describe(- "Status page to attach the report to. Resolve via list_status_pages — do not guess.",- ),- pageComponentIds: z- .array(z.number().int())- .default([])- .describe(- "Optional component ids affected by the incident. Must belong to pageId.",- ),- date: z.iso- .datetime()- .optional()- .describe(- "Override the initial update's date. Defaults to now if omitted.",- ),- notify: z- .boolean()- .describe(- "REQUIRED. Whether to dispatch subscriber notifications (email + integrations) for the initial update. You MUST ask the user before deciding — do not infer. true = notify on creation. false = create silently; subscribers will NEVER be notified about this update (you cannot notify retroactively). No-op if the workspace plan has subscriptions disabled.",- ),- },- outputSchema: {- statusReport: z.object({+ },+ outputSchema: {+ items: z.array(+ z.object({id: z.number().int(),title: z.string(),status: statusReportStatusSchema,pageId: z.number().int().nullable(),createdAt: z.string().nullable(),+ updatedAt: z.string().nullable(),+ latestUpdate: z+ .object({+ message: z.string(),+ status: statusReportStatusSchema,+ date: z.string().nullable(),+ })+ .nullable(),}),- initialUpdateId: z.number().int(),- notified: z.boolean(),- },+ ),+ pagination: z.object({+ page: z.number().int(),+ perPage: z.number().int(),+ totalSize: z.number().int(),+ totalPages: z.number().int(),+ }),},- async (input) =>- runTool(- async () => {- const result = await createStatusReport({- ctx,- input: {- title: input.title,- status: input.status,- message: input.message,- pageId: input.pageId,- pageComponentIds: input.pageComponentIds ?? [],- date: input.date ? new Date(input.date) : new Date(),- },- });- // Mutation succeeded; the row exists. A notify failure- // here must NOT propagate as a tool error — that would- // leave the LLM thinking the whole call failed and- // possibly retrying create, double-publishing the- // report. Report partial success via `notified: false`.- let notified = false;- if (input.notify) {- try {- await notifyStatusReport({- ctx,- input: { statusReportUpdateId: result.initialUpdate.id },- });- notified = true;- } catch (err) {- logger.error(- "notifyStatusReport failed after create_status_report {*}",- {- err,- workspaceId: ctx.workspace.id,- statusReportId: result.statusReport.id,- statusReportUpdateId: result.initialUpdate.id,- },- );- }- }- return { ...result, notified };- },- ({ statusReport, initialUpdate, notified }) => {- const out = {- statusReport: {- id: statusReport.id,- title: statusReport.title,- status: statusReport.status,- pageId: statusReport.pageId,- createdAt: statusReport.createdAt?.toISOString() ?? null,- },- initialUpdateId: initialUpdate.id,- notified,- };+ },+ async ({ filter, pageId, page, perPage }) =>+ runTool(+ () =>+ listStatusReports({+ ctx,+ input: {+ limit: perPage ?? PER_PAGE_DEFAULT,+ offset: ((page ?? 1) - 1) * (perPage ?? PER_PAGE_DEFAULT),+ statuses: filter === "active" ? ACTIVE_STATUSES : [],+ pageId,+ order: "desc",+ },+ }),+ ({ items, totalSize }) => {+ const currentPage = page ?? 1;+ const size = perPage ?? PER_PAGE_DEFAULT;+ const summarised = items.map((r) => {+ const latestUpdate = r.updates[0] ?? null;return {- content: [{ type: "text", text: JSON.stringify(out) }],- structuredContent: out,+ id: r.id,+ title: r.title,+ status: r.status,+ pageId: r.pageId,+ createdAt: r.createdAt?.toISOString() ?? null,+ updatedAt: r.updatedAt?.toISOString() ?? null,+ latestUpdate: latestUpdate+ ? {+ message: latestUpdate.message,+ status: latestUpdate.status,+ date: latestUpdate.date?.toISOString() ?? null,+ }+ : null,};- },- ),- ),+ });+ const out = {+ items: summarised,+ pagination: {+ page: currentPage,+ perPage: size,+ totalSize,+ totalPages: Math.max(1, Math.ceil(totalSize / size)),+ },+ };+ return {+ content: [+ {+ type: "text",+ text: JSON.stringify(out),+ },+ ],+ structuredContent: out,+ };+ },+ ),);+ if (t_listStatusReports)+ registered.set("list_status_reports", t_listStatusReports);- registered.set(- "add_status_report_update",- server.registerTool(- "add_status_report_update",- {- description:- "Append a new public update to an existing status report. PUBLIC, AUDIT-LOGGED, AND POTENTIALLY NOTIFIES SUBSCRIBERS — irreversible side effects. Sets the report's status to the new value (use resolve_status_report instead if the new status would be 'resolved').\n\nMANDATORY workflow before calling:\n1. Draft the new status and message.\n2. Show the draft to the user for review.\n3. Ask explicitly: 'Should I notify subscribers about this update? yes/no'.\n4. Only call this tool once the user has confirmed BOTH the content AND the notify decision.\n\nSubscriber notifications dispatch as part of this call only — you cannot notify retroactively. There is NO separate notify tool. If notify is false here, this update will never reach subscribers. Note: the update persists even if the notify dispatch fails; the response's `notified` field reports whether subscribers were actually notified.",- annotations: {- destructiveHint: true,- idempotentHint: false,- openWorldHint: true,- },- inputSchema: {- statusReportId: z- .number()- .int()- .describe(- "Status report to update. Resolve via list_status_reports — do not guess.",- ),- status: statusReportStatusSchema.describe(- "New status to set on the report. The update entry inherits this status.",+ const t_createStatusReport = registerScopedTool(+ server,+ ctx,+ "create_status_report",+ {+ scope: "write",+ description:+ "Create a new status report on a public status page. PUBLIC, AUDIT-LOGGED, AND POTENTIALLY NOTIFIES SUBSCRIBERS — irreversible side effects.\n\nMANDATORY workflow before calling:\n1. Draft the title, status, message, and affected components.\n2. Show the draft to the user for review.\n3. Ask explicitly: 'Should I notify subscribers (email + integrations) for this report? yes/no'.\n4. Only call this tool once the user has confirmed BOTH the content AND the notify decision.\n\nSubscriber notifications dispatch as part of this call only — you cannot notify retroactively for an existing update. There is NO separate notify tool. If notify is false here, that update will never reach subscribers. Note: the report persists even if the notify dispatch fails; the response's `notified` field reports whether subscribers were actually notified.\n\npageId MUST come from list_status_pages — never guess. pageComponentIds (if supplied) MUST belong to the same page.",+ annotations: {+ readOnlyHint: false,+ destructiveHint: true,+ idempotentHint: false,+ openWorldHint: true,+ },+ inputSchema: {+ title: z+ .string()+ .min(1)+ .max(256)+ .describe("Short, public-facing title for the incident."),+ status: statusReportStatusSchema.describe(+ "Initial status for the report.",+ ),+ message: z+ .string()+ .min(1)+ .describe(+ "Initial public update message customers will see on the status page.",+ ),+ pageId: z+ .number()+ .int()+ .describe(+ "Status page to attach the report to. Resolve via list_status_pages — do not guess.",+ ),+ pageComponentIds: z+ .array(z.number().int())+ .default([])+ .describe(+ "Optional component ids affected by the incident. Must belong to pageId.",+ ),+ date: z.iso+ .datetime()+ .optional()+ .describe(+ "Override the initial update's date. Defaults to now if omitted.",+ ),+ notify: z+ .boolean()+ .describe(+ "REQUIRED. Whether to dispatch subscriber notifications (email + integrations) for the initial update. You MUST ask the user before deciding — do not infer. true = notify on creation. false = create silently; subscribers will NEVER be notified about this update (you cannot notify retroactively). No-op if the workspace plan has subscriptions disabled.",),- message: z- .string()- .min(1)- .describe("Public update message customers will see."),- date: z.iso- .datetime()- .optional()- .describe("Override the update's date. Defaults to now."),- notify: z- .boolean()- .describe(- "REQUIRED. Whether to dispatch subscriber notifications for this update. You MUST ask the user before deciding — do not infer. true = notify now. false = append silently; subscribers will NEVER be notified about this update (you cannot notify retroactively).",- ),+ },+ outputSchema: {+ statusReport: z.object({+ id: z.number().int(),+ title: z.string(),+ status: statusReportStatusSchema,+ pageId: z.number().int().nullable(),+ createdAt: z.string().nullable(),+ }),+ initialUpdateId: z.number().int(),+ notified: z.boolean(),+ },+ },+ async (input) =>+ runTool(+ async () => {+ const result = await createStatusReport({+ ctx,+ input: {+ title: input.title,+ status: input.status,+ message: input.message,+ pageId: input.pageId,+ pageComponentIds: input.pageComponentIds ?? [],+ date: input.date ? new Date(input.date) : new Date(),+ },+ });+ // Mutation succeeded; the row exists. A notify failure+ // here must NOT propagate as a tool error — that would+ // leave the LLM thinking the whole call failed and+ // possibly retrying create, double-publishing the+ // report. Report partial success via `notified: false`.+ let notified = false;+ if (input.notify) {+ try {+ await notifyStatusReport({+ ctx,+ input: { statusReportUpdateId: result.initialUpdate.id },+ });+ notified = true;+ } catch (err) {+ logger.error(+ "notifyStatusReport failed after create_status_report {*}",+ {+ err,+ workspaceId: ctx.workspace.id,+ statusReportId: result.statusReport.id,+ statusReportUpdateId: result.initialUpdate.id,+ },+ );+ }+ }+ return { ...result, notified };},- outputSchema: {- statusReportUpdateId: z.number().int(),- notified: z.boolean(),+ ({ statusReport, initialUpdate, notified }) => {+ const out = {+ statusReport: {+ id: statusReport.id,+ title: statusReport.title,+ status: statusReport.status,+ pageId: statusReport.pageId,+ createdAt: statusReport.createdAt?.toISOString() ?? null,+ },+ initialUpdateId: initialUpdate.id,+ notified,+ };+ return {+ content: [{ type: "text", text: JSON.stringify(out) }],+ structuredContent: out,+ };},+ ),+ );+ if (t_createStatusReport)+ registered.set("create_status_report", t_createStatusReport);++ const t_addStatusReportUpdate = registerScopedTool(+ server,+ ctx,+ "add_status_report_update",+ {+ scope: "write",+ description:+ "Append a new public update to an existing status report. PUBLIC, AUDIT-LOGGED, AND POTENTIALLY NOTIFIES SUBSCRIBERS — irreversible side effects. Sets the report's status to the new value (use resolve_status_report instead if the new status would be 'resolved').\n\nMANDATORY workflow before calling:\n1. Draft the new status and message.\n2. Show the draft to the user for review.\n3. Ask explicitly: 'Should I notify subscribers about this update? yes/no'.\n4. Only call this tool once the user has confirmed BOTH the content AND the notify decision.\n\nSubscriber notifications dispatch as part of this call only — you cannot notify retroactively. There is NO separate notify tool. If notify is false here, this update will never reach subscribers. Note: the update persists even if the notify dispatch fails; the response's `notified` field reports whether subscribers were actually notified.",+ annotations: {+ readOnlyHint: false,+ destructiveHint: true,+ idempotentHint: false,+ openWorldHint: true,},- async (input) =>- runTool(- async () => {- const result = await addStatusReportUpdate({- ctx,- input: {- statusReportId: input.statusReportId,- status: input.status,- message: input.message,- date: input.date ? new Date(input.date) : undefined,- },- });- // See `create_status_report` for the rationale: the- // update is already persisted, so a notify dispatch- // failure must not propagate as a tool error.- let notified = false;- if (input.notify) {- try {- await notifyStatusReport({- ctx,- input: {- statusReportUpdateId: result.statusReportUpdate.id,- },- });- notified = true;- } catch (err) {- logger.error(- "notifyStatusReport failed after add_status_report_update {*}",- {- err,- workspaceId: ctx.workspace.id,- statusReportId: result.statusReport.id,- statusReportUpdateId: result.statusReportUpdate.id,- },- );- }- }- return { ...result, notified };- },- ({ statusReportUpdate, notified }) => {- const out = {- statusReportUpdateId: statusReportUpdate.id,- notified,- };- return {- content: [{ type: "text", text: JSON.stringify(out) }],- structuredContent: out,- };- },+ inputSchema: {+ statusReportId: z+ .number()+ .int()+ .describe(+ "Status report to update. Resolve via list_status_reports — do not guess.",+ ),+ status: statusReportStatusSchema.describe(+ "New status to set on the report. The update entry inherits this status.",),- ),+ message: z+ .string()+ .min(1)+ .describe("Public update message customers will see."),+ date: z.iso+ .datetime()+ .optional()+ .describe("Override the update's date. Defaults to now."),+ notify: z+ .boolean()+ .describe(+ "REQUIRED. Whether to dispatch subscriber notifications for this update. You MUST ask the user before deciding — do not infer. true = notify now. false = append silently; subscribers will NEVER be notified about this update (you cannot notify retroactively).",+ ),+ },+ outputSchema: {+ statusReportUpdateId: z.number().int(),+ notified: z.boolean(),+ },+ },+ async (input) =>+ runTool(+ async () => {+ const result = await addStatusReportUpdate({+ ctx,+ input: {+ statusReportId: input.statusReportId,+ status: input.status,+ message: input.message,+ date: input.date ? new Date(input.date) : undefined,+ },+ });+ // See `create_status_report` for the rationale: the+ // update is already persisted, so a notify dispatch+ // failure must not propagate as a tool error.+ let notified = false;+ if (input.notify) {+ try {+ await notifyStatusReport({+ ctx,+ input: {+ statusReportUpdateId: result.statusReportUpdate.id,+ },+ });+ notified = true;+ } catch (err) {+ logger.error(+ "notifyStatusReport failed after add_status_report_update {*}",+ {+ err,+ workspaceId: ctx.workspace.id,+ statusReportId: result.statusReport.id,+ statusReportUpdateId: result.statusReportUpdate.id,+ },+ );+ }+ }+ return { ...result, notified };+ },+ ({ statusReportUpdate, notified }) => {+ const out = {+ statusReportUpdateId: statusReportUpdate.id,+ notified,+ };+ return {+ content: [{ type: "text", text: JSON.stringify(out) }],+ structuredContent: out,+ };+ },+ ),);+ if (t_addStatusReportUpdate)+ registered.set("add_status_report_update", t_addStatusReportUpdate);- registered.set(+ const t_updateStatusReport = registerScopedTool(+ server,+ ctx,"update_status_report",- server.registerTool(- "update_status_report",- {- description:- "Edit metadata on an existing status report (title, status, affected components). Does NOT add a public update — use add_status_report_update for that. Does NOT and CANNOT notify subscribers — there is no notify path on this tool because metadata edits do not create a new update entry to dispatch. If subscribers need to hear about a change, use add_status_report_update instead with notify: true. Audit-logged.\n\nMANDATORY workflow: draft the change, show it to the user, confirm before calling.",- annotations: {- destructiveHint: true,- idempotentHint: true,- openWorldHint: false,- },- inputSchema: {- statusReportId: z- .number()- .int()- .describe("Report to edit. Resolve via list_status_reports."),- title: z.string().min(1).max(256).optional().describe("New title."),- // Guard against `status: "resolved"` — that would flip the- // report's status without publishing a resolution update,- // leaving the public page in a divergent state (status- // reads "resolved" but no resolution message). Force the- // LLM to use resolve_status_report (which appends the- // final update) instead. The tool description already- // says this; the refine is the runtime backstop.- status: statusReportStatusSchema- .refine((s) => s !== "resolved", {- error:- "update_status_report cannot set status to 'resolved' — use resolve_status_report instead, which also publishes a final resolution update.",- })- .optional()- .describe(- "New status (without appending a public update entry). Cannot be 'resolved' — use resolve_status_report for that.",- ),- pageComponentIds: z- .array(z.number().int())- .optional()- .describe(- "Replace the full set of associated component ids. Empty array clears the association.",- ),- },- outputSchema: {- id: z.number().int(),- title: z.string(),- status: statusReportStatusSchema,- },+ {+ scope: "write",+ description:+ "Edit metadata on an existing status report (title, status, affected components). Does NOT add a public update — use add_status_report_update for that. Does NOT and CANNOT notify subscribers — there is no notify path on this tool because metadata edits do not create a new update entry to dispatch. If subscribers need to hear about a change, use add_status_report_update instead with notify: true. Audit-logged.\n\nMANDATORY workflow: draft the change, show it to the user, confirm before calling.",+ annotations: {+ readOnlyHint: false,+ destructiveHint: true,+ idempotentHint: true,+ openWorldHint: false,},- async (input) =>- runTool(- () =>- updateStatusReport({- ctx,- input: {- id: input.statusReportId,- title: input.title,- status: input.status,- pageComponentIds: input.pageComponentIds,- },- }),- (report) => {- const out = {- id: report.id,- title: report.title,- status: report.status,- };- return {- content: [{ type: "text", text: JSON.stringify(out) }],- structuredContent: out,- };- },- ),- ),+ inputSchema: {+ statusReportId: z+ .number()+ .int()+ .describe("Report to edit. Resolve via list_status_reports."),+ title: z.string().min(1).max(256).optional().describe("New title."),+ // Guard against `status: "resolved"` — that would flip the+ // report's status without publishing a resolution update,+ // leaving the public page in a divergent state (status+ // reads "resolved" but no resolution message). Force the+ // LLM to use resolve_status_report (which appends the+ // final update) instead. The tool description already+ // says this; the refine is the runtime backstop.+ status: statusReportStatusSchema+ .refine((s) => s !== "resolved", {+ error:+ "update_status_report cannot set status to 'resolved' — use resolve_status_report instead, which also publishes a final resolution update.",+ })+ .optional()+ .describe(+ "New status (without appending a public update entry). Cannot be 'resolved' — use resolve_status_report for that.",+ ),+ pageComponentIds: z+ .array(z.number().int())+ .optional()+ .describe(+ "Replace the full set of associated component ids. Empty array clears the association.",+ ),+ },+ outputSchema: {+ id: z.number().int(),+ title: z.string(),+ status: statusReportStatusSchema,+ },+ },+ async (input) =>+ runTool(+ () =>+ updateStatusReport({+ ctx,+ input: {+ id: input.statusReportId,+ title: input.title,+ status: input.status,+ pageComponentIds: input.pageComponentIds,+ },+ }),+ (report) => {+ const out = {+ id: report.id,+ title: report.title,+ status: report.status,+ };+ return {+ content: [{ type: "text", text: JSON.stringify(out) }],+ structuredContent: out,+ };+ },+ ),);+ if (t_updateStatusReport)+ registered.set("update_status_report", t_updateStatusReport);- registered.set(+ const t_resolveStatusReport = registerScopedTool(+ server,+ ctx,"resolve_status_report",- server.registerTool(- "resolve_status_report",- {- description:- "Resolve an active status report. Appends a final public update with the supplied message and flips status to 'resolved'. PUBLIC, AUDIT-LOGGED, AND POTENTIALLY NOTIFIES SUBSCRIBERS — irreversible side effects.\n\nMANDATORY workflow before calling:\n1. Draft the resolution message.\n2. Show the draft to the user for review.\n3. Ask explicitly: 'Should I notify subscribers that this incident is resolved? yes/no'.\n4. Only call this tool once the user has confirmed BOTH the message AND the notify decision.\n\nSubscriber notifications dispatch as part of this call only — you cannot notify retroactively. There is NO separate notify tool. If notify is false here, the resolution will never reach subscribers. Note: the report flips to resolved even if the notify dispatch fails; the response's `notified` field reports whether subscribers were actually notified.",- annotations: {- destructiveHint: true,- idempotentHint: false,- openWorldHint: true,- },- inputSchema: {- statusReportId: z- .number()- .int()- .describe("Report to resolve. Resolve via list_status_reports."),- message: z- .string()- .min(1)- .describe(- "Resolution message customers will see explaining what was fixed.",- ),- date: z.iso- .datetime()- .optional()- .describe("Override the resolution date. Defaults to now."),- notify: z- .boolean()- .describe(- "REQUIRED. Whether to dispatch subscriber notifications for the resolution update. You MUST ask the user before deciding — do not infer. true = notify now. false = resolve silently; subscribers will NEVER hear about this resolution (you cannot notify retroactively).",- ),- },- outputSchema: {- statusReportUpdateId: z.number().int(),- notified: z.boolean(),- },+ {+ scope: "write",+ description:+ "Resolve an active status report. Appends a final public update with the supplied message and flips status to 'resolved'. PUBLIC, AUDIT-LOGGED, AND POTENTIALLY NOTIFIES SUBSCRIBERS — irreversible side effects.\n\nMANDATORY workflow before calling:\n1. Draft the resolution message.\n2. Show the draft to the user for review.\n3. Ask explicitly: 'Should I notify subscribers that this incident is resolved? yes/no'.\n4. Only call this tool once the user has confirmed BOTH the message AND the notify decision.\n\nSubscriber notifications dispatch as part of this call only — you cannot notify retroactively. There is NO separate notify tool. If notify is false here, the resolution will never reach subscribers. Note: the report flips to resolved even if the notify dispatch fails; the response's `notified` field reports whether subscribers were actually notified.",+ annotations: {+ readOnlyHint: false,+ destructiveHint: true,+ idempotentHint: false,+ openWorldHint: true,},- async (input) =>- runTool(- async () => {- const result = await resolveStatusReport({- ctx,- input: {- statusReportId: input.statusReportId,- message: input.message,- date: input.date ? new Date(input.date) : undefined,- },- });- // See `create_status_report` for the rationale: the- // resolution update is already persisted, so a notify- // dispatch failure must not propagate as a tool error.- let notified = false;- if (input.notify) {- try {- await notifyStatusReport({- ctx,- input: {- statusReportUpdateId: result.statusReportUpdate.id,- },- });- notified = true;- } catch (err) {- logger.error(- "notifyStatusReport failed after resolve_status_report {*}",- {- err,- workspaceId: ctx.workspace.id,- statusReportId: result.statusReport.id,- statusReportUpdateId: result.statusReportUpdate.id,- },- );- }+ inputSchema: {+ statusReportId: z+ .number()+ .int()+ .describe("Report to resolve. Resolve via list_status_reports."),+ message: z+ .string()+ .min(1)+ .describe(+ "Resolution message customers will see explaining what was fixed.",+ ),+ date: z.iso+ .datetime()+ .optional()+ .describe("Override the resolution date. Defaults to now."),+ notify: z+ .boolean()+ .describe(+ "REQUIRED. Whether to dispatch subscriber notifications for the resolution update. You MUST ask the user before deciding — do not infer. true = notify now. false = resolve silently; subscribers will NEVER hear about this resolution (you cannot notify retroactively).",+ ),+ },+ outputSchema: {+ statusReportUpdateId: z.number().int(),+ notified: z.boolean(),+ },+ },+ async (input) =>+ runTool(+ async () => {+ const result = await resolveStatusReport({+ ctx,+ input: {+ statusReportId: input.statusReportId,+ message: input.message,+ date: input.date ? new Date(input.date) : undefined,+ },+ });+ // See `create_status_report` for the rationale: the+ // resolution update is already persisted, so a notify+ // dispatch failure must not propagate as a tool error.+ let notified = false;+ if (input.notify) {+ try {+ await notifyStatusReport({+ ctx,+ input: {+ statusReportUpdateId: result.statusReportUpdate.id,+ },+ });+ notified = true;+ } catch (err) {+ logger.error(+ "notifyStatusReport failed after resolve_status_report {*}",+ {+ err,+ workspaceId: ctx.workspace.id,+ statusReportId: result.statusReport.id,+ statusReportUpdateId: result.statusReportUpdate.id,+ },+ );}- return { ...result, notified };- },- ({ statusReportUpdate, notified }) => {- const out = {- statusReportUpdateId: statusReportUpdate.id,- notified,- };- return {- content: [{ type: "text", text: JSON.stringify(out) }],- structuredContent: out,- };- },- ),- ),+ }+ return { ...result, notified };+ },+ ({ statusReportUpdate, notified }) => {+ const out = {+ statusReportUpdateId: statusReportUpdate.id,+ notified,+ };+ return {+ content: [{ type: "text", text: JSON.stringify(out) }],+ structuredContent: out,+ };+ },+ ),);+ if (t_resolveStatusReport)+ registered.set("resolve_status_report", t_resolveStatusReport);return registered;}diff --git a/apps/server/src/routes/mcp/tools/tools.test.ts b/apps/server/src/routes/mcp/tools/tools.test.tsindex 4e77c81d8..c0fe9b0b6 100644--- a/apps/server/src/routes/mcp/tools/tools.test.ts+++ b/apps/server/src/routes/mcp/tools/tools.test.ts@@ -9,7 +9,7 @@ import {statusReport,statusReportUpdate,} from "@openstatus/db/src/schema";-import type { Workspace } from "@openstatus/db/src/schema";+import type { Scope, Workspace } from "@openstatus/db/src/schema";import type { ServiceContext } from "@openstatus/services";import {SEEDED_WORKSPACE_FREE_ID,@@ -39,12 +39,17 @@ function makeMcpToolCtx(opts: {db?: ServiceContext["db"];createdById?: number;+ scopes?: Scope[];} = {},): ServiceContext {return {...toServiceCtx({workspace,- apiKey: { id: "test-key", createdById: opts.createdById },+ apiKey: {+ id: "test-key",+ createdById: opts.createdById,+ scopes: opts.scopes ?? ["write"],+ },requestId: "test-req",}),db: opts.db,@@ -577,3 +582,40 @@ describe("create_maintenance", () => {});});});++describe("scope filter", () => {+ test("read-only key sees read tools, no write tools", async () => {+ const ctx = makeMcpToolCtx(teamWorkspace, { scopes: ["read"] });+ const pageTools = registered("page", ctx);+ const reportTools = registered("status-report", ctx);+ const maintenanceTools = registered("maintenance", ctx);++ // Read-only is allowed:+ expect(pageTools.has("list_status_pages")).toBe(true);+ expect(reportTools.has("list_status_reports")).toBe(true);+ expect(maintenanceTools.has("list_maintenances")).toBe(true);++ // Write tools must be filtered out — registry doesn't carry them+ // and `tools/list` will see only the read tools.+ expect(reportTools.has("create_status_report")).toBe(false);+ expect(reportTools.has("add_status_report_update")).toBe(false);+ expect(reportTools.has("update_status_report")).toBe(false);+ expect(reportTools.has("resolve_status_report")).toBe(false);+ expect(maintenanceTools.has("create_maintenance")).toBe(false);+ });++ test("write key sees both read and write tools", () => {+ const ctx = makeMcpToolCtx(teamWorkspace, { scopes: ["write"] });+ const reportTools = registered("status-report", ctx);+ expect(reportTools.has("list_status_reports")).toBe(true);+ expect(reportTools.has("create_status_report")).toBe(true);+ });++ test("'*' (super-admin) key sees every tool", () => {+ const ctx = makeMcpToolCtx(teamWorkspace, { scopes: ["*"] });+ const reportTools = registered("status-report", ctx);+ expect(reportTools.has("list_status_reports")).toBe(true);+ expect(reportTools.has("create_status_report")).toBe(true);+ expect(reportTools.has("resolve_status_report")).toBe(true);+ });+});diff --git a/apps/server/src/routes/rpc/adapter.test.ts b/apps/server/src/routes/rpc/adapter.test.tsnew file mode 100644index 000000000..b65bc3a53--- /dev/null+++ b/apps/server/src/routes/rpc/adapter.test.ts@@ -0,0 +1,155 @@+import { beforeAll, describe, expect, test } from "bun:test";+import { Code, ConnectError } from "@connectrpc/connect";++import type { Workspace } from "@openstatus/db/src/schema";+import {+ ForbiddenError,+ NotFoundError,+ type ServiceContext,+ ValidationError,+} from "@openstatus/services";+import { createApiKey } from "@openstatus/services/api-key";+import { SEEDED_WORKSPACE_TEAM_ID } from "@openstatus/services/test/fixtures";+import {+ loadSeededWorkspace,+ withTestTransaction,+} from "@openstatus/services/test/helpers";++import { toConnectError, toServiceCtx } from "./adapter";++const wsStub = { id: 1, slug: "ws", name: "ws" } as unknown as Workspace;++describe("toServiceCtx (RPC)", () => {+ test("propagates apiKey.scopes onto actor.scopes", () => {+ const ctx = toServiceCtx({+ workspace: wsStub,+ requestId: "req-1",+ apiKey: { id: "k1", createdById: 7, scopes: ["read"] },+ });+ expect(ctx.actor.type).toBe("apiKey");+ if (ctx.actor.type === "apiKey") {+ expect(ctx.actor.scopes).toEqual(["read"]);+ expect(ctx.actor.keyId).toBe("k1");+ expect(ctx.actor.userId).toBe(7);+ }+ });++ test("propagates ['*'] super-admin scopes intact", () => {+ const ctx = toServiceCtx({+ workspace: wsStub,+ requestId: "req-2",+ apiKey: { id: "sa", scopes: ["*"] },+ });+ if (ctx.actor.type === "apiKey") {+ expect(ctx.actor.scopes).toEqual(["*"]);+ }+ });+});++/**+ * `toConnectError` is the only RPC-specific layer between a thrown+ * `ServiceError` and what the wire surfaces. The unique RBAC concern+ * here is the FORBIDDEN → PermissionDenied mapping; the other branches+ * are exercised below for sanity (so the FORBIDDEN test would catch a+ * future refactor that flattens every code into Internal).+ */+/**+ * `toConnectError` always throws — capture the thrown value and+ * assert on it. Avoids `expect.unreachable` (typed `never`, which+ * trips TS's unreachable-code analysis on the catch block).+ */+function captureThrow(fn: () => void): unknown {+ try {+ fn();+ } catch (err) {+ return err;+ }+ throw new Error("expected fn to throw, but it returned");+}++describe("toConnectError", () => {+ test("ForbiddenError → ConnectError(PermissionDenied)", () => {+ const err = captureThrow(() =>+ toConnectError(new ForbiddenError("API key lacks required scope: write")),+ );+ expect(err).toBeInstanceOf(ConnectError);+ expect((err as ConnectError).code).toBe(Code.PermissionDenied);+ expect((err as ConnectError).rawMessage).toContain(+ "API key lacks required scope",+ );+ });++ test("NotFoundError → ConnectError(NotFound)", () => {+ const err = captureThrow(() =>+ toConnectError(new NotFoundError("monitor", 42)),+ );+ expect((err as ConnectError).code).toBe(Code.NotFound);+ });++ test("ValidationError → ConnectError(InvalidArgument)", () => {+ const err = captureThrow(() =>+ toConnectError(new ValidationError("bad input")),+ );+ expect((err as ConnectError).code).toBe(Code.InvalidArgument);+ });++ test("re-throws an existing ConnectError unchanged", () => {+ const original = new ConnectError("custom", Code.Aborted);+ const err = captureThrow(() => toConnectError(original));+ expect(err).toBe(original);+ });+});++/**+ * RPC runtime sample (per the plan's test plan #8). End-to-end through+ * the layers a real request would hit:+ * 1. Build an apiKey-actor `ServiceContext` via the RPC adapter+ * (with `['read']` scopes) — the same shape `authInterceptor` would+ * produce for a read-only key.+ * 2. Invoke a service write verb (`createApiKey` is convenient — same+ * package, no foreign-key fixtures).+ * 3. Catch the `ForbiddenError` and pipe it through `toConnectError`,+ * assert the wire code is `PermissionDenied`.+ *+ * One representative method is enough — service-level enforcement+ * covers the rest, this test pins the *RPC translation* of the+ * denial.+ */+describe("RPC runtime — read-only key on a write service verb", () => {+ let teamWorkspace: Workspace;++ beforeAll(async () => {+ teamWorkspace = await loadSeededWorkspace(SEEDED_WORKSPACE_TEAM_ID);+ });++ test("throws ForbiddenError → ConnectError(PermissionDenied)", async () => {+ await withTestTransaction(async (tx) => {+ const ctx: ServiceContext = {+ ...toServiceCtx({+ workspace: teamWorkspace,+ requestId: "req-rpc-runtime",+ apiKey: { id: "read-only-key", createdById: 1, scopes: ["read"] },+ }),+ db: tx,+ };++ let captured: unknown;+ try {+ await createApiKey({+ ctx,+ input: { name: "rpc-runtime-test" },+ });+ } catch (err) {+ captured = err;+ }++ expect(captured).toBeInstanceOf(ForbiddenError);++ // Pipe the service error through the RPC mapper — the same+ // path the Connect handler in production takes.+ const mapped = captureThrow(() => toConnectError(captured));+ expect(mapped).toBeInstanceOf(ConnectError);+ expect((mapped as ConnectError).code).toBe(Code.PermissionDenied);+ });+ });+});diff --git a/apps/server/src/routes/rpc/adapter.ts b/apps/server/src/routes/rpc/adapter.tsindex b0c594663..7bf394f47 100644--- a/apps/server/src/routes/rpc/adapter.ts+++ b/apps/server/src/routes/rpc/adapter.ts@@ -16,6 +16,7 @@ export function toServiceCtx(rpcCtx: RpcContext): ServiceContext {type: "apiKey",keyId: rpcCtx.apiKey.id,userId: rpcCtx.apiKey.createdById,+ scopes: rpcCtx.apiKey.scopes,},requestId: rpcCtx.requestId,};diff --git a/apps/server/src/routes/rpc/interceptors/auth.ts b/apps/server/src/routes/rpc/interceptors/auth.tsindex 5f744a2aa..ef72d8a62 100644--- a/apps/server/src/routes/rpc/interceptors/auth.ts+++ b/apps/server/src/routes/rpc/interceptors/auth.ts@@ -4,7 +4,7 @@ import {type Interceptor,createContextKey,} from "@connectrpc/connect";-import type { Workspace } from "@openstatus/db/src/schema";+import type { Scope, Workspace } from "@openstatus/db/src/schema";import { nanoid } from "nanoid";import { lookupWorkspace, validateKey } from "@/libs/middlewares/auth";@@ -20,8 +20,10 @@ export interface RpcContext {* Resolved API key identity. `id` is the stable key identifier (audit* `actor_id`); `createdById` is the openstatus user who created the* key (`api_key.created_by_id`, audit `actor_user_id`).+ * `scopes` carries the access-control scopes for the resolved key —+ * `requireScope` reads them inside service write verbs.*/- apiKey: { id: string; createdById?: number };+ apiKey: { id: string; createdById?: number; scopes: Scope[] };}/**@@ -85,6 +87,7 @@ export function authInterceptor(): Interceptor {apiKey: {id: result.keyId ?? `ws:${workspace.id}`,createdById: result.createdById,+ scopes: result.scopes ?? ["write"],},};diff --git a/apps/server/src/routes/v1/index.ts b/apps/server/src/routes/v1/index.tsindex b357ae1e4..876778a9d 100644--- a/apps/server/src/routes/v1/index.ts+++ b/apps/server/src/routes/v1/index.ts@@ -4,8 +4,8 @@ import { cors } from "hono/cors";import type { RequestIdVariables } from "hono/request-id";import { handleZodError } from "@/libs/errors";-import { authMiddleware } from "@/libs/middlewares";-import type { Workspace } from "@openstatus/db/src/schema";+import { authMiddleware, requireWriteScope } from "@/libs/middlewares";+import type { Scope, Workspace } from "@openstatus/db/src/schema";import { checkApi } from "./check";import { incidentsApi } from "./incidents";import { maintenancesApi } from "./maintenances";@@ -19,6 +19,7 @@ import { whoamiApi } from "./whoami";export type Variables = RequestIdVariables & {workspace: Workspace;+ apiKey: { id: string; createdById?: number; scopes: Scope[] };};export const api = new OpenAPIHono<{ Variables: Variables }>({@@ -139,6 +140,11 @@ api.get(* Middlewares*/api.use("/*", authMiddleware);+// Primary scope enforcement for V1: routes here use inline Drizzle+// queries instead of `@openstatus/services`, so the service-level+// `requireScope` won't run. After per-route migration to services,+// this stays as defense-in-depth.+api.use("/*", requireWriteScope());/*** Routesdiff --git a/apps/server/src/routes/v1/whoami/get.ts b/apps/server/src/routes/v1/whoami/get.tsindex 3b605ed22..ddcec6959 100644--- a/apps/server/src/routes/v1/whoami/get.ts+++ b/apps/server/src/routes/v1/whoami/get.ts@@ -28,6 +28,7 @@ const getRoute = createRoute({export function registerGetWhoami(api: typeof whoamiApi) {return api.openapi(getRoute, async (c) => {const workspaceId = c.get("workspace").id;+ const apiKey = c.get("apiKey");const _workspace = await db.select()@@ -42,7 +43,21 @@ export function registerGetWhoami(api: typeof whoamiApi) {});}- const data = WorkspaceSchema.parse(_workspace);+ // Filter `'*'` out of the public response. The schema's enum would+ // otherwise reject the parse — we don't expose super-admin scope+ // even when the actor holds it.+ const publicScopes = apiKey.scopes.filter(+ (s): s is "read" | "write" => s === "read" || s === "write",+ );++ const data = WorkspaceSchema.parse({+ ..._workspace,+ actor: {+ type: "apiKey",+ keyId: apiKey.id,+ scopes: publicScopes,+ },+ });return c.json(data, 200);});}diff --git a/apps/server/src/routes/v1/whoami/schema.ts b/apps/server/src/routes/v1/whoami/schema.tsindex 9f35fe534..19b321ff4 100644--- a/apps/server/src/routes/v1/whoami/schema.ts+++ b/apps/server/src/routes/v1/whoami/schema.ts@@ -1,7 +1,33 @@import { z } from "@hono/zod-openapi";+import { apiKeySettableScopes } from "@openstatus/db/src/schema/api-keys/constants";import { workspacePlans } from "@openstatus/db/src/schema/workspaces/constants";+/**+ * Scope info echoed back to the caller. Public enum only — `'*'`+ * (super-admin / dev) is never exposed to clients; the response+ * validator rejects it loudly if it ever leaks into a row.+ */+const ActorScopeSchema = z.array(z.enum(apiKeySettableScopes)).openapi({+ description:+ "Scopes the API key holds. Lets clients introspect what they're allowed to do without probe-and-fail.",+});++// `type` is always `"apiKey"` for V1 — MCP traffic doesn't reach this+// endpoint. Narrowed deliberately so OpenAPI consumers don't have to+// branch on a value they'll never see.+const ActorSchema = z+ .object({+ type: z.literal("apiKey").openapi({+ description: "Transport surface that authenticated this request",+ }),+ keyId: z.string().openapi({+ description: "Stable identifier for the API key",+ }),+ scopes: ActorScopeSchema,+ })+ .openapi("WhoamiActor");+export const WorkspaceSchema = z.object({name: z@@ -12,6 +38,11 @@ export const WorkspaceSchema = zplan: z.enum(workspacePlans).nullable().prefault("free").openapi({description: "The current workspace plan",}),+ // Always populated. Unkey fallback keys synthesize `['write']` in+ // `validateKey`, so even pre-RBAC keys produce a real actor here.+ actor: ActorSchema.openapi({+ description: "Resolved API key actor for this request.",+ }),}).openapi("Workspace");diff --git a/apps/server/src/types/index.ts b/apps/server/src/types/index.tsindex bb76ad7d9..54d6c614b 100644--- a/apps/server/src/types/index.ts+++ b/apps/server/src/types/index.ts@@ -1,4 +1,4 @@-import type { Workspace } from "@openstatus/db/src/schema";+import type { Scope, Workspace } from "@openstatus/db/src/schema";import type { RequestIdVariables } from "hono/request-id";export type Variables = RequestIdVariables & {@@ -12,6 +12,11 @@ export type Variables = RequestIdVariables & {* openstatus user who created the key (`api_key.created_by_id`) —* propagated to `actor.userId` so `audit_log.actor_user_id` is* populated for custom keys.+ *+ * `scopes` carries the access-control scopes for the key — read by+ * the V1 `requireWriteScope` middleware and the service-level+ * `requireScope` helper. Custom keys: row scopes. Unkey fallback:+ * `['write']` (legacy posture). Super-admin / dev fallback: `['*']`.*/- apiKey: { id: string; createdById?: number };+ apiKey: { id: string; createdById?: number; scopes: Scope[] };};diff --git a/apps/web/public/assets/changelog/api-key-scopes.png b/apps/web/public/assets/changelog/api-key-scopes.pngnew file mode 100644index 000000000..e4854cda7Binary files /dev/null and b/apps/web/public/assets/changelog/api-key-scopes.png differdiff --git a/apps/web/src/content/pages/changelog/api-key-scopes.mdx b/apps/web/src/content/pages/changelog/api-key-scopes.mdxnew file mode 100644index 000000000..525e4988a--- /dev/null+++ b/apps/web/src/content/pages/changelog/api-key-scopes.mdx@@ -0,0 +1,12 @@+---+title: "API Key Scopes"+description: "Issue read-only or read-write API keys to keep agents and integrations on a tight leash."+image: "/assets/changelog/api-key-scopes.png"+publishedAt: "2026-05-08"+category: "company"+author: "openstatus"+---++API keys now carry a `read` or `write` scope. Read-only keys can list and inspect resources but cannot mutate anything — useful for dashboards, read replicas, and AI agents you don't fully trust.++Pick a scope when creating a key in `Settings → API Keys`. Existing keys keep full access; rotate them to scope down.diff --git a/packages/db/drizzle/0067_grey_hellfire_club.sql b/packages/db/drizzle/0067_grey_hellfire_club.sqlnew file mode 100644index 000000000..637a894e1--- /dev/null+++ b/packages/db/drizzle/0067_grey_hellfire_club.sql@@ -0,0 +1 @@+ALTER TABLE `api_key` ADD `scopes` text DEFAULT '["write"]' NOT NULL;\ No newline at end of filediff --git a/packages/db/drizzle/meta/0066_snapshot.json b/packages/db/drizzle/meta/0066_snapshot.jsonindex 31ad4eccc..abd1a66a3 100644--- a/packages/db/drizzle/meta/0066_snapshot.json+++ b/packages/db/drizzle/meta/0066_snapshot.json@@ -98,24 +98,17 @@"indexes": {"workspace_slug_unique": {"name": "workspace_slug_unique",- "columns": [- "slug"- ],+ "columns": ["slug"],"isUnique": true},"workspace_stripe_id_unique": {"name": "workspace_stripe_id_unique",- "columns": [- "stripe_id"- ],+ "columns": ["stripe_id"],"isUnique": true},"workspace_id_dsn_unique": {"name": "workspace_id_dsn_unique",- "columns": [- "id",- "dsn"- ],+ "columns": ["id", "dsn"],"isUnique": true}},@@ -211,22 +204,15 @@"name": "account_user_id_user_id_fk","tableFrom": "account","tableTo": "user",- "columnsFrom": [- "user_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],"onDelete": "cascade","onUpdate": "no action"}},"compositePrimaryKeys": {"account_provider_provider_account_id_pk": {- "columns": [- "provider",- "provider_account_id"- ],+ "columns": ["provider", "provider_account_id"],"name": "account_provider_provider_account_id_pk"}},@@ -264,12 +250,8 @@"name": "session_user_id_user_id_fk","tableFrom": "session","tableTo": "user",- "columnsFrom": [- "user_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],"onDelete": "cascade","onUpdate": "no action"}@@ -368,9 +350,7 @@"indexes": {"user_tenant_id_unique": {"name": "user_tenant_id_unique",- "columns": [- "tenant_id"- ],+ "columns": ["tenant_id"],"isUnique": true}},@@ -416,9 +396,7 @@"indexes": {"users_to_workspaces_workspace_id_idx": {"name": "users_to_workspaces_workspace_id_idx",- "columns": [- "workspace_id"- ],+ "columns": ["workspace_id"],"isUnique": false}},@@ -427,12 +405,8 @@"name": "users_to_workspaces_user_id_user_id_fk","tableFrom": "users_to_workspaces","tableTo": "user",- "columnsFrom": [- "user_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],"onDelete": "no action","onUpdate": "no action"},@@ -440,22 +414,15 @@"name": "users_to_workspaces_workspace_id_workspace_id_fk","tableFrom": "users_to_workspaces","tableTo": "workspace",- "columnsFrom": [- "workspace_id"- ],- "columnsTo": [- "id"- ],+ "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"- ],+ "columns": ["user_id", "workspace_id"],"name": "users_to_workspaces_user_id_workspace_id_pk"}},@@ -491,10 +458,7 @@"foreignKeys": {},"compositePrimaryKeys": {"verification_token_identifier_token_pk": {- "columns": [- "identifier",- "token"- ],+ "columns": ["identifier", "token"],"name": "verification_token_identifier_token_pk"}},@@ -559,17 +523,12 @@"indexes": {"status_report_workspace_created_idx": {"name": "status_report_workspace_created_idx",- "columns": [- "workspace_id",- "created_at"- ],+ "columns": ["workspace_id", "created_at"],"isUnique": false},"status_report_page_id_idx": {"name": "status_report_page_id_idx",- "columns": [- "page_id"- ],+ "columns": ["page_id"],"isUnique": false}},@@ -578,12 +537,8 @@"name": "status_report_workspace_id_workspace_id_fk","tableFrom": "status_report","tableTo": "workspace",- "columnsFrom": [- "workspace_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],"onDelete": "no action","onUpdate": "no action"},@@ -591,12 +546,8 @@"name": "status_report_page_id_page_id_fk","tableFrom": "status_report","tableTo": "page",- "columnsFrom": [- "page_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["page_id"],+ "columnsTo": ["id"],"onDelete": "cascade","onUpdate": "no action"}@@ -663,9 +614,7 @@"indexes": {"status_report_update_status_report_id_idx": {"name": "status_report_update_status_report_id_idx",- "columns": [- "status_report_id"- ],+ "columns": ["status_report_id"],"isUnique": false}},@@ -674,12 +623,8 @@"name": "status_report_update_status_report_id_status_report_id_fk","tableFrom": "status_report_update","tableTo": "status_report",- "columnsFrom": [- "status_report_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["status_report_id"],+ "columnsTo": ["id"],"onDelete": "cascade","onUpdate": "no action"}@@ -753,9 +698,7 @@"indexes": {"integration_workspace_id_idx": {"name": "integration_workspace_id_idx",- "columns": [- "workspace_id"- ],+ "columns": ["workspace_id"],"isUnique": false}},@@ -764,12 +707,8 @@"name": "integration_workspace_id_workspace_id_fk","tableFrom": "integration","tableTo": "workspace",- "columnsFrom": [- "workspace_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],"onDelete": "no action","onUpdate": "no action"}@@ -964,30 +903,22 @@"indexes": {"page_slug_unique": {"name": "page_slug_unique",- "columns": [- "slug"- ],+ "columns": ["slug"],"isUnique": true},"page_lower_slug_idx": {"name": "page_lower_slug_idx",- "columns": [- "LOWER(\"slug\")"- ],+ "columns": ["LOWER(\"slug\")"],"isUnique": false},"page_lower_custom_domain_idx": {"name": "page_lower_custom_domain_idx",- "columns": [- "LOWER(\"custom_domain\")"- ],+ "columns": ["LOWER(\"custom_domain\")"],"isUnique": false},"page_workspace_id_idx": {"name": "page_workspace_id_idx",- "columns": [- "workspace_id"- ],+ "columns": ["workspace_id"],"isUnique": false}},@@ -996,12 +927,8 @@"name": "page_workspace_id_workspace_id_fk","tableFrom": "page","tableTo": "workspace",- "columnsFrom": [- "workspace_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],"onDelete": "cascade","onUpdate": "no action"}@@ -1208,9 +1135,7 @@"indexes": {"monitor_workspace_id_active_idx": {"name": "monitor_workspace_id_active_idx",- "columns": [- "workspace_id"- ],+ "columns": ["workspace_id"],"isUnique": false,"where": "\"monitor\".\"deleted_at\" IS NULL"}@@ -1220,12 +1145,8 @@"name": "monitor_workspace_id_workspace_id_fk","tableFrom": "monitor","tableTo": "workspace",- "columnsFrom": [- "workspace_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],"onDelete": "no action","onUpdate": "no action"}@@ -1343,19 +1264,13 @@"indexes": {"idx_page_subscriber_email_page_active": {"name": "idx_page_subscriber_email_page_active",- "columns": [- "LOWER(\"email\")",- "page_id"- ],+ "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"- ],+ "columns": ["LOWER(\"webhook_url\")", "page_id"],"isUnique": true,"where": "\"page_subscriber\".\"unsubscribed_at\" IS NULL AND \"page_subscriber\".\"channel_type\" = 'webhook'"}@@ -1365,12 +1280,8 @@"name": "page_subscriber_page_id_page_id_fk","tableFrom": "page_subscriber","tableTo": "page",- "columnsFrom": [- "page_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["page_id"],+ "columnsTo": ["id"],"onDelete": "cascade","onUpdate": "no action"}@@ -1416,12 +1327,8 @@"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"- ],+ "columnsFrom": ["page_subscriber_id"],+ "columnsTo": ["id"],"onDelete": "cascade","onUpdate": "no action"},@@ -1429,22 +1336,15 @@"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"- ],+ "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"- ],+ "columns": ["page_subscriber_id", "page_component_id"],"name": "page_subscriber_to_page_component_page_subscriber_id_page_component_id_pk"}},@@ -1510,9 +1410,7 @@"indexes": {"notification_workspace_id_idx": {"name": "notification_workspace_id_idx",- "columns": [- "workspace_id"- ],+ "columns": ["workspace_id"],"isUnique": false}},@@ -1521,12 +1419,8 @@"name": "notification_workspace_id_workspace_id_fk","tableFrom": "notification","tableTo": "workspace",- "columnsFrom": [- "workspace_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],"onDelete": "no action","onUpdate": "no action"}@@ -1570,11 +1464,7 @@"indexes": {"notification_id_monitor_id_crontimestampe": {"name": "notification_id_monitor_id_crontimestampe",- "columns": [- "notification_id",- "monitor_id",- "cron_timestamp"- ],+ "columns": ["notification_id", "monitor_id", "cron_timestamp"],"isUnique": true}},@@ -1583,12 +1473,8 @@"name": "notification_trigger_monitor_id_monitor_id_fk","tableFrom": "notification_trigger","tableTo": "monitor",- "columnsFrom": [- "monitor_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["monitor_id"],+ "columnsTo": ["id"],"onDelete": "cascade","onUpdate": "no action"},@@ -1596,12 +1482,8 @@"name": "notification_trigger_notification_id_notification_id_fk","tableFrom": "notification_trigger","tableTo": "notification",- "columnsFrom": [- "notification_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["notification_id"],+ "columnsTo": ["id"],"onDelete": "cascade","onUpdate": "no action"}@@ -1639,9 +1521,7 @@"indexes": {"notifications_to_monitors_notification_id_idx": {"name": "notifications_to_monitors_notification_id_idx",- "columns": [- "notification_id"- ],+ "columns": ["notification_id"],"isUnique": false}},@@ -1650,12 +1530,8 @@"name": "notifications_to_monitors_monitor_id_monitor_id_fk","tableFrom": "notifications_to_monitors","tableTo": "monitor",- "columnsFrom": [- "monitor_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["monitor_id"],+ "columnsTo": ["id"],"onDelete": "cascade","onUpdate": "no action"},@@ -1663,22 +1539,15 @@"name": "notifications_to_monitors_notification_id_notification_id_fk","tableFrom": "notifications_to_monitors","tableTo": "notification",- "columnsFrom": [- "notification_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["notification_id"],+ "columnsTo": ["id"],"onDelete": "cascade","onUpdate": "no action"}},"compositePrimaryKeys": {"notifications_to_monitors_monitor_id_notification_id_pk": {- "columns": [- "monitor_id",- "notification_id"- ],+ "columns": ["monitor_id", "notification_id"],"name": "notifications_to_monitors_monitor_id_notification_id_pk"}},@@ -1731,10 +1600,7 @@"indexes": {"monitor_status_idx": {"name": "monitor_status_idx",- "columns": [- "monitor_id",- "region"- ],+ "columns": ["monitor_id", "region"],"isUnique": false}},@@ -1743,22 +1609,15 @@"name": "monitor_status_monitor_id_monitor_id_fk","tableFrom": "monitor_status","tableTo": "monitor",- "columnsFrom": [- "monitor_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["monitor_id"],+ "columnsTo": ["id"],"onDelete": "cascade","onUpdate": "no action"}},"compositePrimaryKeys": {"monitor_status_monitor_id_region_pk": {- "columns": [- "monitor_id",- "region"- ],+ "columns": ["monitor_id", "region"],"name": "monitor_status_monitor_id_region_pk"}},@@ -1830,9 +1689,7 @@"indexes": {"invitation_workspace_id_idx": {"name": "invitation_workspace_id_idx",- "columns": [- "workspace_id"- ],+ "columns": ["workspace_id"],"isUnique": false}},@@ -1967,17 +1824,12 @@"indexes": {"incident_workspace_id_idx": {"name": "incident_workspace_id_idx",- "columns": [- "workspace_id"- ],+ "columns": ["workspace_id"],"isUnique": false},"incident_monitor_id_started_at_unique": {"name": "incident_monitor_id_started_at_unique",- "columns": [- "monitor_id",- "started_at"- ],+ "columns": ["monitor_id", "started_at"],"isUnique": true}},@@ -1986,12 +1838,8 @@"name": "incident_monitor_id_monitor_id_fk","tableFrom": "incident","tableTo": "monitor",- "columnsFrom": [- "monitor_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["monitor_id"],+ "columnsTo": ["id"],"onDelete": "set default","onUpdate": "no action"},@@ -1999,12 +1847,8 @@"name": "incident_workspace_id_workspace_id_fk","tableFrom": "incident","tableTo": "workspace",- "columnsFrom": [- "workspace_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],"onDelete": "no action","onUpdate": "no action"},@@ -2012,12 +1856,8 @@"name": "incident_acknowledged_by_user_id_fk","tableFrom": "incident","tableTo": "user",- "columnsFrom": [- "acknowledged_by"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["acknowledged_by"],+ "columnsTo": ["id"],"onDelete": "no action","onUpdate": "no action"},@@ -2025,12 +1865,8 @@"name": "incident_resolved_by_user_id_fk","tableFrom": "incident","tableTo": "user",- "columnsFrom": [- "resolved_by"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["resolved_by"],+ "columnsTo": ["id"],"onDelete": "no action","onUpdate": "no action"}@@ -2090,9 +1926,7 @@"indexes": {"monitor_tag_workspace_id_idx": {"name": "monitor_tag_workspace_id_idx",- "columns": [- "workspace_id"- ],+ "columns": ["workspace_id"],"isUnique": false}},@@ -2101,12 +1935,8 @@"name": "monitor_tag_workspace_id_workspace_id_fk","tableFrom": "monitor_tag","tableTo": "workspace",- "columnsFrom": [- "workspace_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],"onDelete": "cascade","onUpdate": "no action"}@@ -2144,9 +1974,7 @@"indexes": {"monitor_tag_to_monitor_monitor_tag_id_idx": {"name": "monitor_tag_to_monitor_monitor_tag_id_idx",- "columns": [- "monitor_tag_id"- ],+ "columns": ["monitor_tag_id"],"isUnique": false}},@@ -2155,12 +1983,8 @@"name": "monitor_tag_to_monitor_monitor_id_monitor_id_fk","tableFrom": "monitor_tag_to_monitor","tableTo": "monitor",- "columnsFrom": [- "monitor_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["monitor_id"],+ "columnsTo": ["id"],"onDelete": "cascade","onUpdate": "no action"},@@ -2168,22 +1992,15 @@"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"- ],+ "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"- ],+ "columns": ["monitor_id", "monitor_tag_id"],"name": "monitor_tag_to_monitor_monitor_id_monitor_tag_id_pk"}},@@ -2241,16 +2058,12 @@"indexes": {"application_dsn_unique": {"name": "application_dsn_unique",- "columns": [- "dsn"- ],+ "columns": ["dsn"],"isUnique": true},"application_workspace_id_idx": {"name": "application_workspace_id_idx",- "columns": [- "workspace_id"- ],+ "columns": ["workspace_id"],"isUnique": false}},@@ -2259,12 +2072,8 @@"name": "application_workspace_id_workspace_id_fk","tableFrom": "application","tableTo": "workspace",- "columnsFrom": [- "workspace_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],"onDelete": "no action","onUpdate": "no action"}@@ -2345,16 +2154,12 @@"indexes": {"maintenance_page_id_idx": {"name": "maintenance_page_id_idx",- "columns": [- "page_id"- ],+ "columns": ["page_id"],"isUnique": false},"maintenance_workspace_id_idx": {"name": "maintenance_workspace_id_idx",- "columns": [- "workspace_id"- ],+ "columns": ["workspace_id"],"isUnique": false}},@@ -2363,12 +2168,8 @@"name": "maintenance_workspace_id_workspace_id_fk","tableFrom": "maintenance","tableTo": "workspace",- "columnsFrom": [- "workspace_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],"onDelete": "no action","onUpdate": "no action"},@@ -2376,12 +2177,8 @@"name": "maintenance_page_id_page_id_fk","tableFrom": "maintenance","tableTo": "page",- "columnsFrom": [- "page_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["page_id"],+ "columnsTo": ["id"],"onDelete": "cascade","onUpdate": "no action"}@@ -2466,9 +2263,7 @@"indexes": {"check_workspace_id_idx": {"name": "check_workspace_id_idx",- "columns": [- "workspace_id"- ],+ "columns": ["workspace_id"],"isUnique": false}},@@ -2477,12 +2272,8 @@"name": "check_workspace_id_workspace_id_fk","tableFrom": "check","tableTo": "workspace",- "columnsFrom": [- "workspace_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],"onDelete": "no action","onUpdate": "no action"}@@ -2534,16 +2325,12 @@"indexes": {"monitor_run_workspace_id_idx": {"name": "monitor_run_workspace_id_idx",- "columns": [- "workspace_id"- ],+ "columns": ["workspace_id"],"isUnique": false},"monitor_run_monitor_id_idx": {"name": "monitor_run_monitor_id_idx",- "columns": [- "monitor_id"- ],+ "columns": ["monitor_id"],"isUnique": false}},@@ -2552,12 +2339,8 @@"name": "monitor_run_workspace_id_workspace_id_fk","tableFrom": "monitor_run","tableTo": "workspace",- "columnsFrom": [- "workspace_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],"onDelete": "no action","onUpdate": "no action"},@@ -2565,12 +2348,8 @@"name": "monitor_run_monitor_id_monitor_id_fk","tableFrom": "monitor_run","tableTo": "monitor",- "columnsFrom": [- "monitor_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["monitor_id"],+ "columnsTo": ["id"],"onDelete": "no action","onUpdate": "no action"}@@ -2637,9 +2416,7 @@"indexes": {"private_location_workspace_id_idx": {"name": "private_location_workspace_id_idx",- "columns": [- "workspace_id"- ],+ "columns": ["workspace_id"],"isUnique": false}},@@ -2648,12 +2425,8 @@"name": "private_location_workspace_id_workspace_id_fk","tableFrom": "private_location","tableTo": "workspace",- "columnsFrom": [- "workspace_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],"onDelete": "no action","onUpdate": "no action"}@@ -2698,16 +2471,12 @@"indexes": {"private_location_to_monitor_private_location_id_idx": {"name": "private_location_to_monitor_private_location_id_idx",- "columns": [- "private_location_id"- ],+ "columns": ["private_location_id"],"isUnique": false},"private_location_to_monitor_monitor_id_idx": {"name": "private_location_to_monitor_monitor_id_idx",- "columns": [- "monitor_id"- ],+ "columns": ["monitor_id"],"isUnique": false}},@@ -2716,12 +2485,8 @@"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"- ],+ "columnsFrom": ["private_location_id"],+ "columnsTo": ["id"],"onDelete": "cascade","onUpdate": "no action"},@@ -2729,12 +2494,8 @@"name": "private_location_to_monitor_monitor_id_monitor_id_fk","tableFrom": "private_location_to_monitor","tableTo": "monitor",- "columnsFrom": [- "monitor_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["monitor_id"],+ "columnsTo": ["id"],"onDelete": "cascade","onUpdate": "no action"}@@ -2794,16 +2555,12 @@"indexes": {"monitor_group_workspace_id_idx": {"name": "monitor_group_workspace_id_idx",- "columns": [- "workspace_id"- ],+ "columns": ["workspace_id"],"isUnique": false},"monitor_group_page_id_idx": {"name": "monitor_group_page_id_idx",- "columns": [- "page_id"- ],+ "columns": ["page_id"],"isUnique": false}},@@ -2812,12 +2569,8 @@"name": "monitor_group_workspace_id_workspace_id_fk","tableFrom": "monitor_group","tableTo": "workspace",- "columnsFrom": [- "workspace_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],"onDelete": "cascade","onUpdate": "no action"},@@ -2825,12 +2578,8 @@"name": "monitor_group_page_id_page_id_fk","tableFrom": "monitor_group","tableTo": "page",- "columnsFrom": [- "page_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["page_id"],+ "columnsTo": ["id"],"onDelete": "cascade","onUpdate": "no action"}@@ -2897,9 +2646,7 @@"indexes": {"viewer_email_unique": {"name": "viewer_email_unique",- "columns": [- "email"- ],+ "columns": ["email"],"isUnique": true}},@@ -2995,22 +2742,15 @@"name": "viewer_accounts_user_id_viewer_id_fk","tableFrom": "viewer_accounts","tableTo": "viewer",- "columnsFrom": [- "user_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],"onDelete": "cascade","onUpdate": "no action"}},"compositePrimaryKeys": {"viewer_accounts_provider_providerAccountId_pk": {- "columns": [- "provider",- "providerAccountId"- ],+ "columns": ["provider", "providerAccountId"],"name": "viewer_accounts_provider_providerAccountId_pk"}},@@ -3048,12 +2788,8 @@"name": "viewer_session_user_id_viewer_id_fk","tableFrom": "viewer_session","tableTo": "viewer",- "columnsFrom": [- "user_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],"onDelete": "cascade","onUpdate": "no action"}@@ -3140,30 +2876,22 @@"indexes": {"api_key_prefix_unique": {"name": "api_key_prefix_unique",- "columns": [- "prefix"- ],+ "columns": ["prefix"],"isUnique": true},"api_key_hashed_token_unique": {"name": "api_key_hashed_token_unique",- "columns": [- "hashed_token"- ],+ "columns": ["hashed_token"],"isUnique": true},"api_key_prefix_idx": {"name": "api_key_prefix_idx",- "columns": [- "prefix"- ],+ "columns": ["prefix"],"isUnique": false},"api_key_workspace_id_idx": {"name": "api_key_workspace_id_idx",- "columns": [- "workspace_id"- ],+ "columns": ["workspace_id"],"isUnique": false}},@@ -3172,12 +2900,8 @@"name": "api_key_workspace_id_workspace_id_fk","tableFrom": "api_key","tableTo": "workspace",- "columnsFrom": [- "workspace_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],"onDelete": "cascade","onUpdate": "no action"},@@ -3185,12 +2909,8 @@"name": "api_key_created_by_id_user_id_fk","tableFrom": "api_key","tableTo": "user",- "columnsFrom": [- "created_by_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["created_by_id"],+ "columnsTo": ["id"],"onDelete": "cascade","onUpdate": "no action"}@@ -3228,9 +2948,7 @@"indexes": {"maintenance_to_page_component_page_component_id_idx": {"name": "maintenance_to_page_component_page_component_id_idx",- "columns": [- "page_component_id"- ],+ "columns": ["page_component_id"],"isUnique": false}},@@ -3239,12 +2957,8 @@"name": "maintenance_to_page_component_maintenance_id_maintenance_id_fk","tableFrom": "maintenance_to_page_component","tableTo": "maintenance",- "columnsFrom": [- "maintenance_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["maintenance_id"],+ "columnsTo": ["id"],"onDelete": "cascade","onUpdate": "no action"},@@ -3252,22 +2966,15 @@"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"- ],+ "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"- ],+ "columns": ["maintenance_id", "page_component_id"],"name": "maintenance_to_page_component_maintenance_id_page_component_id_pk"}},@@ -3370,17 +3077,12 @@"indexes": {"page_component_workspace_id_idx": {"name": "page_component_workspace_id_idx",- "columns": [- "workspace_id"- ],+ "columns": ["workspace_id"],"isUnique": false},"page_component_page_id_monitor_id_unique": {"name": "page_component_page_id_monitor_id_unique",- "columns": [- "page_id",- "monitor_id"- ],+ "columns": ["page_id", "monitor_id"],"isUnique": true}},@@ -3389,12 +3091,8 @@"name": "page_component_workspace_id_workspace_id_fk","tableFrom": "page_component","tableTo": "workspace",- "columnsFrom": [- "workspace_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],"onDelete": "cascade","onUpdate": "no action"},@@ -3402,12 +3100,8 @@"name": "page_component_page_id_page_id_fk","tableFrom": "page_component","tableTo": "page",- "columnsFrom": [- "page_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["page_id"],+ "columnsTo": ["id"],"onDelete": "cascade","onUpdate": "no action"},@@ -3415,12 +3109,8 @@"name": "page_component_monitor_id_monitor_id_fk","tableFrom": "page_component","tableTo": "monitor",- "columnsFrom": [- "monitor_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["monitor_id"],+ "columnsTo": ["id"],"onDelete": "cascade","onUpdate": "no action"},@@ -3428,12 +3118,8 @@"name": "page_component_group_id_page_component_groups_id_fk","tableFrom": "page_component","tableTo": "page_component_groups",- "columnsFrom": [- "group_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["group_id"],+ "columnsTo": ["id"],"onDelete": "set null","onUpdate": "no action"}@@ -3476,9 +3162,7 @@"indexes": {"status_report_to_page_component_page_component_id_idx": {"name": "status_report_to_page_component_page_component_id_idx",- "columns": [- "page_component_id"- ],+ "columns": ["page_component_id"],"isUnique": false}},@@ -3487,12 +3171,8 @@"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"- ],+ "columnsFrom": ["status_report_id"],+ "columnsTo": ["id"],"onDelete": "cascade","onUpdate": "no action"},@@ -3500,22 +3180,15 @@"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"- ],+ "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"- ],+ "columns": ["status_report_id", "page_component_id"],"name": "status_report_to_page_component_status_report_id_page_component_id_pk"}},@@ -3581,16 +3254,12 @@"indexes": {"page_component_groups_page_id_idx": {"name": "page_component_groups_page_id_idx",- "columns": [- "page_id"- ],+ "columns": ["page_id"],"isUnique": false},"page_component_groups_workspace_id_idx": {"name": "page_component_groups_workspace_id_idx",- "columns": [- "workspace_id"- ],+ "columns": ["workspace_id"],"isUnique": false}},@@ -3599,12 +3268,8 @@"name": "page_component_groups_workspace_id_workspace_id_fk","tableFrom": "page_component_groups","tableTo": "workspace",- "columnsFrom": [- "workspace_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],"onDelete": "cascade","onUpdate": "no action"},@@ -3612,12 +3277,8 @@"name": "page_component_groups_page_id_page_id_fk","tableFrom": "page_component_groups","tableTo": "page",- "columnsFrom": [- "page_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["page_id"],+ "columnsTo": ["id"],"onDelete": "cascade","onUpdate": "no action"}@@ -3704,9 +3365,7 @@"indexes": {"feedback_workspace_id_idx": {"name": "feedback_workspace_id_idx",- "columns": [- "workspace_id"- ],+ "columns": ["workspace_id"],"isUnique": false}},@@ -3715,12 +3374,8 @@"name": "feedback_workspace_id_workspace_id_fk","tableFrom": "feedback","tableTo": "workspace",- "columnsFrom": [- "workspace_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],"onDelete": "cascade","onUpdate": "no action"},@@ -3728,12 +3383,8 @@"name": "feedback_user_id_user_id_fk","tableFrom": "feedback","tableTo": "user",- "columnsFrom": [- "user_id"- ],- "columnsTo": [- "id"- ],+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],"onDelete": "cascade","onUpdate": "no action"}@@ -3840,20 +3491,12 @@"indexes": {"audit_log_workspace_created_idx": {"name": "audit_log_workspace_created_idx",- "columns": [- "workspace_id",- "created_at"- ],+ "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"- ],+ "columns": ["workspace_id", "entity_type", "entity_id", "created_at"],"isUnique": false}},@@ -3902,4 +3545,4 @@}}}-}\ No newline at end of file+}diff --git a/packages/db/drizzle/meta/0067_snapshot.json b/packages/db/drizzle/meta/0067_snapshot.jsonnew file mode 100644index 000000000..0743efdbe--- /dev/null+++ b/packages/db/drizzle/meta/0067_snapshot.json@@ -0,0 +1,3913 @@+{+ "version": "6",+ "dialect": "sqlite",+ "id": "0fb8640e-5483-4343-bef6-2982c5cbe88b",+ "prevId": "4a6c108d-d12a-4be4-84af-d4d970d84bb3",+ "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": {+ "users_to_workspaces_workspace_id_idx": {+ "name": "users_to_workspaces_workspace_id_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false+ }+ },+ "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": {+ "status_report_workspace_created_idx": {+ "name": "status_report_workspace_created_idx",+ "columns": [+ "workspace_id",+ "created_at"+ ],+ "isUnique": false+ },+ "status_report_page_id_idx": {+ "name": "status_report_page_id_idx",+ "columns": [+ "page_id"+ ],+ "isUnique": false+ }+ },+ "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": {+ "status_report_update_status_report_id_idx": {+ "name": "status_report_update_status_report_id_idx",+ "columns": [+ "status_report_id"+ ],+ "isUnique": false+ }+ },+ "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": {+ "integration_workspace_id_idx": {+ "name": "integration_workspace_id_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false+ }+ },+ "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+ },+ "page_lower_slug_idx": {+ "name": "page_lower_slug_idx",+ "columns": [+ "LOWER(\"slug\")"+ ],+ "isUnique": false+ },+ "page_lower_custom_domain_idx": {+ "name": "page_lower_custom_domain_idx",+ "columns": [+ "LOWER(\"custom_domain\")"+ ],+ "isUnique": false+ },+ "page_workspace_id_idx": {+ "name": "page_workspace_id_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false+ }+ },+ "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": {+ "monitor_workspace_id_active_idx": {+ "name": "monitor_workspace_id_active_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false,+ "where": "\"monitor\".\"deleted_at\" IS NULL"+ }+ },+ "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": {+ "notification_workspace_id_idx": {+ "name": "notification_workspace_id_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false+ }+ },+ "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": {+ "notifications_to_monitors_notification_id_idx": {+ "name": "notifications_to_monitors_notification_id_idx",+ "columns": [+ "notification_id"+ ],+ "isUnique": false+ }+ },+ "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": {+ "invitation_workspace_id_idx": {+ "name": "invitation_workspace_id_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false+ }+ },+ "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_workspace_id_idx": {+ "name": "incident_workspace_id_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false+ },+ "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": {+ "monitor_tag_workspace_id_idx": {+ "name": "monitor_tag_workspace_id_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false+ }+ },+ "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": {+ "monitor_tag_to_monitor_monitor_tag_id_idx": {+ "name": "monitor_tag_to_monitor_monitor_tag_id_idx",+ "columns": [+ "monitor_tag_id"+ ],+ "isUnique": false+ }+ },+ "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+ },+ "application_workspace_id_idx": {+ "name": "application_workspace_id_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false+ }+ },+ "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": {+ "maintenance_page_id_idx": {+ "name": "maintenance_page_id_idx",+ "columns": [+ "page_id"+ ],+ "isUnique": false+ },+ "maintenance_workspace_id_idx": {+ "name": "maintenance_workspace_id_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false+ }+ },+ "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": {+ "check_workspace_id_idx": {+ "name": "check_workspace_id_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false+ }+ },+ "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": {+ "monitor_run_workspace_id_idx": {+ "name": "monitor_run_workspace_id_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false+ },+ "monitor_run_monitor_id_idx": {+ "name": "monitor_run_monitor_id_idx",+ "columns": [+ "monitor_id"+ ],+ "isUnique": false+ }+ },+ "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": {+ "private_location_workspace_id_idx": {+ "name": "private_location_workspace_id_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false+ }+ },+ "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": {+ "private_location_to_monitor_private_location_id_idx": {+ "name": "private_location_to_monitor_private_location_id_idx",+ "columns": [+ "private_location_id"+ ],+ "isUnique": false+ },+ "private_location_to_monitor_monitor_id_idx": {+ "name": "private_location_to_monitor_monitor_id_idx",+ "columns": [+ "monitor_id"+ ],+ "isUnique": false+ }+ },+ "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": {+ "monitor_group_workspace_id_idx": {+ "name": "monitor_group_workspace_id_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false+ },+ "monitor_group_page_id_idx": {+ "name": "monitor_group_page_id_idx",+ "columns": [+ "page_id"+ ],+ "isUnique": false+ }+ },+ "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+ },+ "scopes": {+ "name": "scopes",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'[\"write\"]'"+ },+ "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+ },+ "api_key_workspace_id_idx": {+ "name": "api_key_workspace_id_idx",+ "columns": [+ "workspace_id"+ ],+ "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": {+ "maintenance_to_page_component_page_component_id_idx": {+ "name": "maintenance_to_page_component_page_component_id_idx",+ "columns": [+ "page_component_id"+ ],+ "isUnique": false+ }+ },+ "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_workspace_id_idx": {+ "name": "page_component_workspace_id_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false+ },+ "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": {+ "status_report_to_page_component_page_component_id_idx": {+ "name": "status_report_to_page_component_page_component_id_idx",+ "columns": [+ "page_component_id"+ ],+ "isUnique": false+ }+ },+ "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": {+ "page_component_groups_page_id_idx": {+ "name": "page_component_groups_page_id_idx",+ "columns": [+ "page_id"+ ],+ "isUnique": false+ },+ "page_component_groups_workspace_id_idx": {+ "name": "page_component_groups_workspace_id_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false+ }+ },+ "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": {+ "feedback_workspace_id_idx": {+ "name": "feedback_workspace_id_idx",+ "columns": [+ "workspace_id"+ ],+ "isUnique": false+ }+ },+ "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": {+ "page_lower_slug_idx": {+ "columns": {+ "LOWER(\"slug\")": {+ "isExpression": true+ }+ }+ },+ "page_lower_custom_domain_idx": {+ "columns": {+ "LOWER(\"custom_domain\")": {+ "isExpression": true+ }+ }+ },+ "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 22caec516..1ea75018a 100644--- a/packages/db/drizzle/meta/_journal.json+++ b/packages/db/drizzle/meta/_journal.json@@ -470,6 +470,13 @@"when": 1778177332398,"tag": "0066_adorable_matthew_murdock","breakpoints": true+ },+ {+ "idx": 67,+ "version": "6",+ "when": 1778179053701,+ "tag": "0067_grey_hellfire_club",+ "breakpoints": true}]}\ No newline at end of filediff --git a/packages/db/src/schema/api-keys/api_key.ts b/packages/db/src/schema/api-keys/api_key.tsindex 14b3c6897..62d7244d0 100644--- a/packages/db/src/schema/api-keys/api_key.ts+++ b/packages/db/src/schema/api-keys/api_key.ts@@ -3,6 +3,7 @@ import { index, integer, sqliteTable, text } from "drizzle-orm/sqlite-core";import { user } from "../users";import { workspace } from "../workspaces";+import type { Scope } from "./constants";export const apiKey = sqliteTable("api_key",@@ -18,6 +19,14 @@ export const apiKey = sqliteTable(createdById: integer("created_by_id").notNull().references(() => user.id, { onDelete: "cascade" }),+ // Stored as a JSON array so per-resource scopes (e.g. 'monitor.read')+ // can be added later without re-shaping the column. v1 stores a+ // single value: ['read'] or ['write']. Existing rows backfill to+ // ['write'] via the column default to preserve current behavior.+ scopes: text("scopes", { mode: "json" })+ .$type<Scope[]>()+ .notNull()+ .default(["write"]),createdAt: integer("created_at", { mode: "timestamp" }).default(sql`(strftime('%s', 'now'))`,),diff --git a/packages/db/src/schema/api-keys/constants.ts b/packages/db/src/schema/api-keys/constants.tsnew file mode 100644index 000000000..f92b3813b--- /dev/null+++ b/packages/db/src/schema/api-keys/constants.ts@@ -0,0 +1,21 @@+/**+ * API key scopes.+ *+ * `'read'` and `'write'` are the only values a public caller can set when+ * creating a key. `'*'` is internal-only — synthesized by middleware for+ * super-admin and dev fallbacks. The matcher treats it uniformly so there+ * is no hardcoded bypass anywhere else in the stack.+ *+ * The shape is JSON-array forward compatible: when per-resource scopes+ * land (`'monitor.read'`, `'page.write'`), they extend this union without+ * a column migration.+ */+export const apiKeyScopes = ["read", "write", "*"] as const;+export type Scope = (typeof apiKeyScopes)[number];++/**+ * The subset of scopes a caller may set via the create-key API. `'*'` is+ * filtered out at the parse boundary so it can never ride in on the wire.+ */+export const apiKeySettableScopes = ["read", "write"] as const;+export type SettableScope = (typeof apiKeySettableScopes)[number];diff --git a/packages/db/src/schema/api-keys/index.ts b/packages/db/src/schema/api-keys/index.tsindex 33288c277..cbf0170d4 100644--- a/packages/db/src/schema/api-keys/index.ts+++ b/packages/db/src/schema/api-keys/index.ts@@ -1,2 +1,3 @@export * from "./api_key";+export * from "./constants";export * from "./validation";diff --git a/packages/db/src/schema/api-keys/validation.ts b/packages/db/src/schema/api-keys/validation.tsindex 79938617c..3d45ba9d7 100644--- a/packages/db/src/schema/api-keys/validation.ts+++ b/packages/db/src/schema/api-keys/validation.ts@@ -2,19 +2,39 @@ import { createInsertSchema, createSelectSchema } from "drizzle-zod";import { z } from "zod";import { apiKey } from "./api_key";+import { apiKeyScopes, apiKeySettableScopes } from "./constants";++// Internal scope schema: includes '*' for the super-admin / dev-fallback+// path. Auth middleware reads raw rows and needs the full enum.+const internalScopesSchema = z+ .array(z.enum(apiKeyScopes))+ .min(1)+ .default(["write"]);++// Public scope schema: drops '*' so it can never ride in on the wire.+// Used by create-key input and any output schema that crosses a trust+// boundary.+export const publicScopesSchema = z+ .array(z.enum(apiKeySettableScopes))+ .min(1)+ .default(["write"]);export const insertApiKeySchema = createInsertSchema(apiKey, {name: z.string().min(1, "Name is required"),description: z.string().optional(),expiresAt: z.date().optional(),+ scopes: internalScopesSchema,});-export const selectApiKeySchema = createSelectSchema(apiKey);+export const selectApiKeySchema = createSelectSchema(apiKey, {+ scopes: internalScopesSchema,+});export const createApiKeySchema = z.object({name: z.string().min(1, "Name is required"),description: z.string().optional(),expiresAt: z.date().optional(),+ scopes: publicScopesSchema,});export type InsertApiKey = z.infer<typeof insertApiKeySchema>;diff --git a/packages/services/package.json b/packages/services/package.jsonindex c37aaec83..bfd8a9c45 100644--- a/packages/services/package.json+++ b/packages/services/package.json@@ -61,6 +61,10 @@"import": "./src/audit/index.ts","types": "./src/audit/index.ts"},+ "./auth": {+ "import": "./src/auth/index.ts",+ "types": "./src/auth/index.ts"+ },"./member": {"import": "./src/member/index.ts","types": "./src/member/index.ts"diff --git a/packages/services/src/api-key/__tests__/api-key.test.ts b/packages/services/src/api-key/__tests__/api-key.test.tsindex e529ae12d..663a2e3a7 100644--- a/packages/services/src/api-key/__tests__/api-key.test.ts+++ b/packages/services/src/api-key/__tests__/api-key.test.ts@@ -13,11 +13,13 @@ import { SEEDED_WORKSPACE_TEAM_ID } from "../../../test/fixtures";import {expectAuditRow,loadSeededWorkspace,+ makeApiKeyCtx,makeUserCtx,+ readAuditLog,withTestTransaction,} from "../../../test/helpers";import type { ServiceContext } from "../../context";-import { NotFoundError } from "../../errors";+import { ForbiddenError, NotFoundError } from "../../errors";const TEST_PREFIX = "svc-apikey-test";@@ -56,6 +58,76 @@ describe("createApiKey", () => {});});});++ test("defaults scopes to ['write'] when omitted", async () => {+ await withTestTransaction(async (tx) => {+ const ctx = { ...teamCtx, db: tx };+ const { key } = await createApiKey({+ ctx,+ input: { name: `${TEST_PREFIX}-default-scope` },+ });+ expect(key.scopes).toEqual(["write"]);+ });+ });++ test("persists ['read'] when explicitly set", async () => {+ await withTestTransaction(async (tx) => {+ const ctx = { ...teamCtx, db: tx };+ const { key } = await createApiKey({+ ctx,+ input: { name: `${TEST_PREFIX}-read-scope`, scopes: ["read"] },+ });+ expect(key.scopes).toEqual(["read"]);+ });+ });++ test("rejects '*' at the input boundary (privilege-escalation guard)", async () => {+ await withTestTransaction(async (tx) => {+ const ctx = { ...teamCtx, db: tx };+ await expect(+ createApiKey({+ ctx,+ input: {+ name: `${TEST_PREFIX}-star`,+ // biome-ignore lint/suspicious/noExplicitAny: testing the parse boundary+ scopes: ["*"] as any,+ },+ }),+ ).rejects.toThrow();+ });+ });++ test("rejects empty scopes []", async () => {+ await withTestTransaction(async (tx) => {+ const ctx = { ...teamCtx, db: tx };+ await expect(+ createApiKey({+ ctx,+ input: { name: `${TEST_PREFIX}-empty-scope`, scopes: [] },+ }),+ ).rejects.toThrow();+ });+ });++ test("rejects read-only actor", async () => {+ await withTestTransaction(async (tx) => {+ const team = await loadSeededWorkspace(SEEDED_WORKSPACE_TEAM_ID);+ const readOnlyCtx = {+ ...makeApiKeyCtx(team, {+ keyId: "k-read",+ userId: 1,+ scopes: ["read"],+ }),+ db: tx,+ };+ await expect(+ createApiKey({+ ctx: readOnlyCtx,+ input: { name: `${TEST_PREFIX}-rejects-read` },+ }),+ ).rejects.toBeInstanceOf(ForbiddenError);+ });+ });});describe("listApiKeys", () => {@@ -98,6 +170,100 @@ describe("revokeApiKey", () => {).rejects.toBeInstanceOf(NotFoundError);});});++ test("self-revoke carve-out: read-only key can revoke itself", async () => {+ await withTestTransaction(async (tx) => {+ const team = await loadSeededWorkspace(SEEDED_WORKSPACE_TEAM_ID);+ // Create the key as a user so we get a real row id back.+ const { key } = await createApiKey({+ ctx: { ...teamCtx, db: tx },+ input: { name: `${TEST_PREFIX}-self-revoke`, scopes: ["read"] },+ });++ // Now revoke as the read-only key itself — should succeed.+ const selfCtx = {+ ...makeApiKeyCtx(team, {+ keyId: String(key.id),+ userId: 1,+ scopes: ["read"],+ }),+ db: tx,+ };+ await revokeApiKey({ ctx: selfCtx, input: { id: key.id } });++ const row = await tx+ .select({ id: apiKey.id })+ .from(apiKey)+ .where(eq(apiKey.id, key.id))+ .get();+ expect(row).toBeUndefined();+ });+ });++ test("audit row captures scopes in `before` snapshot", async () => {+ // Create with a non-default scope, revoke, and confirm the audit+ // row's `before` snapshot carries it. Asserts the create/delete+ // pair stays symmetric — both sides should expose `scopes` so+ // reviewers can answer "what scope did this key have?" without+ // querying a deleted row.+ await withTestTransaction(async (tx) => {+ const ctx = { ...teamCtx, db: tx };+ const { key } = await createApiKey({+ ctx,+ input: { name: `${TEST_PREFIX}-audit-snap`, scopes: ["read"] },+ });+ await revokeApiKey({ ctx, input: { id: key.id } });++ const rows = await readAuditLog({+ workspaceId: ctx.workspace.id,+ entityType: "api_key",+ entityId: key.id,+ db: tx,+ });+ const deleteRow = rows.find((r) => r.action === "api_key.delete");+ const createRow = rows.find((r) => r.action === "api_key.create");++ expect(deleteRow?.before).toMatchObject({+ id: key.id,+ prefix: key.prefix,+ scopes: ["read"],+ });+ expect(createRow?.after).toMatchObject({+ id: key.id,+ prefix: key.prefix,+ scopes: ["read"],+ });+ // Symmetry: snapshots strip the same secret/header columns.+ const forbidden = ["hashedToken", "workspaceId", "createdById"];+ for (const k of forbidden) {+ expect(deleteRow?.before).not.toHaveProperty(k);+ expect(createRow?.after).not.toHaveProperty(k);+ }+ });+ });++ test("read-only actor cannot revoke a different key", async () => {+ await withTestTransaction(async (tx) => {+ const team = await loadSeededWorkspace(SEEDED_WORKSPACE_TEAM_ID);+ const { key } = await createApiKey({+ ctx: { ...teamCtx, db: tx },+ input: { name: `${TEST_PREFIX}-other-key` },+ });++ // Read-only actor with a different keyId tries to revoke `key`.+ const otherCtx = {+ ...makeApiKeyCtx(team, {+ keyId: "different-key-id",+ userId: 1,+ scopes: ["read"],+ }),+ db: tx,+ };+ await expect(+ revokeApiKey({ ctx: otherCtx, input: { id: key.id } }),+ ).rejects.toBeInstanceOf(ForbiddenError);+ });+ });});describe("verifyApiKey", () => {diff --git a/packages/services/src/api-key/create.ts b/packages/services/src/api-key/create.tsindex 74ef1252a..1ece1d931 100644--- a/packages/services/src/api-key/create.ts+++ b/packages/services/src/api-key/create.ts@@ -2,6 +2,7 @@ import { apiKey } from "@openstatus/db/src/schema";import { generateApiKey } from "@openstatus/db/src/utils/api-key";import { emitAudit } from "../audit";+import { requireScope } from "../auth";import {type ServiceContext,tryGetActorUserId,@@ -28,6 +29,7 @@ export async function createApiKey(args: {input: CreateApiKeyInput;}): Promise<{ token: string; key: PublicApiKey }> {const { ctx } = args;+ requireScope(ctx, "write");const input = CreateApiKeyInput.parse(args.input);const createdById = tryGetActorUserId(ctx.actor);@@ -50,6 +52,7 @@ export async function createApiKey(args: {workspaceId: ctx.workspace.id,createdById,expiresAt: input.expiresAt,+ scopes: input.scopes,}).returning();@@ -71,6 +74,7 @@ export async function createApiKey(args: {description: key.description,prefix: key.prefix,expiresAt: key.expiresAt,+ scopes: key.scopes,},});diff --git a/packages/services/src/api-key/list.ts b/packages/services/src/api-key/list.tsindex fbc84b6ae..9634f8f94 100644--- a/packages/services/src/api-key/list.ts+++ b/packages/services/src/api-key/list.ts@@ -57,6 +57,7 @@ export async function listApiKeys(args: {description: apiKey.description,prefix: apiKey.prefix,createdById: apiKey.createdById,+ scopes: apiKey.scopes,expiresAt: apiKey.expiresAt,lastUsedAt: apiKey.lastUsedAt,createdAt: apiKey.createdAt,diff --git a/packages/services/src/api-key/revoke.ts b/packages/services/src/api-key/revoke.tsindex c9b12ba30..2d90cdd3c 100644--- a/packages/services/src/api-key/revoke.ts+++ b/packages/services/src/api-key/revoke.ts@@ -2,6 +2,7 @@ import { and, eq } from "@openstatus/db";import { apiKey } from "@openstatus/db/src/schema";import { emitAudit } from "../audit";+import { requireScope } from "../auth";import { type ServiceContext, withTransaction } from "../context";import { NotFoundError } from "../errors";import { RevokeApiKeyInput } from "./schemas";@@ -11,6 +12,12 @@ import { RevokeApiKeyInput } from "./schemas";* existence check runs inside the tx so concurrent revokes don't race to* a false "not found". Throws `NotFoundError` when the key doesn't exist* in the workspace; surface adapters map that to their transport's 404.+ *+ * Self-revoke carve-out: a read-only key is allowed to revoke *itself*.+ * Without it, a leaked read-only key has no rotation path other than the+ * dashboard, which is a UX trap (users hit `DELETE /v1/api-key/{id}`,+ * get 403, get confused). The carve-out is narrow — only the actor's+ * own key — and the audit row still captures who revoked what.*/export async function revokeApiKey(args: {ctx: ServiceContext;@@ -19,10 +26,20 @@ export async function revokeApiKey(args: {const { ctx } = args;const input = RevokeApiKeyInput.parse(args.input);+ const isSelfRevoke =+ (ctx.actor.type === "apiKey" || ctx.actor.type === "mcp") &&+ String(input.id) === ctx.actor.keyId;+ if (!isSelfRevoke) requireScope(ctx, "write");+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.+ // Field order mirrors `createApiKey`'s `after` snapshot so a+ // reviewer eyeballing create/delete pairs can spot drift at a+ // glance. `hashedToken` (secret) and `workspaceId`/`createdById`/+ // timestamps (already on the row header or in the actor) stay+ // out by design.const row = await tx.select({id: apiKey.id,@@ -30,6 +47,7 @@ export async function revokeApiKey(args: {description: apiKey.description,prefix: apiKey.prefix,expiresAt: apiKey.expiresAt,+ scopes: apiKey.scopes,}).from(apiKey).where(diff --git a/packages/services/src/api-key/schemas.ts b/packages/services/src/api-key/schemas.tsindex dbbb7d7e0..edc2e4890 100644--- a/packages/services/src/api-key/schemas.ts+++ b/packages/services/src/api-key/schemas.ts@@ -1,11 +1,35 @@+import { apiKeySettableScopes } from "@openstatus/db/src/schema/api-keys/constants";import { z } from "zod";+/**+ * Public-facing scope enum: only `'read'` and `'write'` are settable+ * via the create-key API. `'*'` is internal-only (super-admin / dev+ * fallbacks) and intentionally rejected here so it cannot ride in on+ * the wire. Sourced from `apiKeySettableScopes` so an additive change+ * (e.g. per-resource scopes) flows through here without a sync edit.+ *+ * Optional with a `['write']` default — preserves current behavior+ * for any caller that doesn't pass it. The dashboard form sends+ * `scopes` explicitly, so the "deliberate decision" property is+ * enforced by the UI surface, not the input schema.+ */+export const apiKeyCreateScopesSchema = z+ .array(z.enum(apiKeySettableScopes))+ .min(1)+ .default(["write"]);+export const CreateApiKeyInput = z.object({name: z.string().min(1, "Name is required"),description: z.string().optional(),expiresAt: z.date().optional(),+ scopes: apiKeyCreateScopesSchema,});-export type CreateApiKeyInput = z.infer<typeof CreateApiKeyInput>;+// `z.input` so the `.default(['write'])` on `scopes` keeps the field+// optional for callers (tests, dashboard). The parsed output (used+// inside the verb) still has `scopes` populated. Without this, every+// existing caller would have to pass `scopes` explicitly, which is+// the breaking change the schema-side default exists to avoid.+export type CreateApiKeyInput = z.input<typeof CreateApiKeyInput>;export const RevokeApiKeyInput = z.object({ id: z.number().int() });export type RevokeApiKeyInput = z.infer<typeof RevokeApiKeyInput>;diff --git a/packages/services/src/auth/__tests__/matches-scope.test.ts b/packages/services/src/auth/__tests__/matches-scope.test.tsnew file mode 100644index 000000000..e8dd90a31--- /dev/null+++ b/packages/services/src/auth/__tests__/matches-scope.test.ts@@ -0,0 +1,97 @@+import { describe, expect, test } from "bun:test";+import type { Scope } from "@openstatus/db/src/schema";++import { matchesScope } from "../matches-scope";++describe("matchesScope", () => {+ // Table-driven sweep over the v1 hierarchy:+ // '*' ⊇ 'write' ⊇ 'read'+ const cases: ReadonlyArray<{+ name: string;+ held: Scope[];+ required: Scope;+ expected: boolean;+ }> = [+ {+ name: "* held → read required",+ held: ["*"],+ required: "read",+ expected: true,+ },+ {+ name: "* held → write required",+ held: ["*"],+ required: "write",+ expected: true,+ },+ { name: "* held → * required", held: ["*"], required: "*", expected: true },+ {+ name: "write held → read required",+ held: ["write"],+ required: "read",+ expected: true,+ },+ {+ name: "write held → write required",+ held: ["write"],+ required: "write",+ expected: true,+ },+ {+ name: "write held → * required",+ held: ["write"],+ required: "*",+ expected: false,+ },+ {+ name: "read held → read required",+ held: ["read"],+ required: "read",+ expected: true,+ },+ {+ name: "read held → write required",+ held: ["read"],+ required: "write",+ expected: false,+ },+ {+ name: "read held → * required",+ held: ["read"],+ required: "*",+ expected: false,+ },+ {+ name: "empty held matches nothing",+ held: [],+ required: "read",+ expected: false,+ },+ {+ name: "empty held matches nothing (write)",+ held: [],+ required: "write",+ expected: false,+ },+ {+ name: "multi-scope: ['read','write']",+ held: ["read", "write"],+ required: "write",+ expected: true,+ },+ ];++ for (const c of cases) {+ test(c.name, () => {+ expect(matchesScope(c.held, c.required)).toBe(c.expected);+ });+ }++ test("unknown scope strings match nothing (fail-closed)", () => {+ // Cast through unknown to bypass the type narrowing — simulates+ // a corrupt DB row or a future migration bug.+ const corrupt = ["bogus" as unknown as Scope];+ expect(matchesScope(corrupt, "read")).toBe(false);+ expect(matchesScope(corrupt, "write")).toBe(false);+ });+});diff --git a/packages/services/src/auth/__tests__/require-scope.test.ts b/packages/services/src/auth/__tests__/require-scope.test.tsnew file mode 100644index 000000000..0278626b1--- /dev/null+++ b/packages/services/src/auth/__tests__/require-scope.test.ts@@ -0,0 +1,105 @@+import { describe, expect, test } from "bun:test";++import type { Actor, ServiceContext } from "../../context";+import { ForbiddenError } from "../../errors";+import { requireScope } from "../require-scope";++const workspace = {+ id: 1,+ name: "test",+ slug: "test",+} as unknown as ServiceContext["workspace"];++function makeCtx(actor: Actor): ServiceContext {+ return { workspace, actor };+}++describe("requireScope", () => {+ test("read-only apiKey + 'write' requirement → ForbiddenError", () => {+ const ctx = makeCtx({+ type: "apiKey",+ keyId: "k1",+ scopes: ["read"],+ });+ expect(() => requireScope(ctx, "write")).toThrow(ForbiddenError);+ });++ test("read-only apiKey + 'read' requirement → passes", () => {+ const ctx = makeCtx({+ type: "apiKey",+ keyId: "k1",+ scopes: ["read"],+ });+ expect(() => requireScope(ctx, "read")).not.toThrow();+ });++ test("write apiKey passes 'read' and 'write'", () => {+ const ctx = makeCtx({+ type: "apiKey",+ keyId: "k1",+ scopes: ["write"],+ });+ expect(() => requireScope(ctx, "read")).not.toThrow();+ expect(() => requireScope(ctx, "write")).not.toThrow();+ });++ test("super-admin '*' apiKey passes any required", () => {+ const ctx = makeCtx({+ type: "apiKey",+ keyId: "k1",+ scopes: ["*"],+ });+ expect(() => requireScope(ctx, "read")).not.toThrow();+ expect(() => requireScope(ctx, "write")).not.toThrow();+ });++ test("read-only mcp actor enforced same as apiKey", () => {+ const ctx = makeCtx({+ type: "mcp",+ keyId: "k1",+ scopes: ["read"],+ });+ expect(() => requireScope(ctx, "write")).toThrow(ForbiddenError);+ expect(() => requireScope(ctx, "read")).not.toThrow();+ });++ test("user actor is no-op (member-role enforcement is a separate project)", () => {+ const ctx = makeCtx({ type: "user", userId: 42 });+ expect(() => requireScope(ctx, "write")).not.toThrow();+ expect(() => requireScope(ctx, "read")).not.toThrow();+ });++ test("system actor is no-op", () => {+ const ctx = makeCtx({ type: "system", job: "checker" });+ expect(() => requireScope(ctx, "write")).not.toThrow();+ });++ test("slack actor is no-op", () => {+ const ctx = makeCtx({+ type: "slack",+ teamId: "T1",+ slackUserId: "U1",+ });+ expect(() => requireScope(ctx, "write")).not.toThrow();+ });++ test("webhook actor is no-op", () => {+ const ctx = makeCtx({ type: "webhook", source: "stripe" });+ expect(() => requireScope(ctx, "write")).not.toThrow();+ });++ test("subscriber actor is no-op", () => {+ const ctx = makeCtx({ type: "subscriber", subscriberId: 7 });+ expect(() => requireScope(ctx, "write")).not.toThrow();+ });++ test("apiKey with empty scopes fails closed", () => {+ const ctx = makeCtx({+ type: "apiKey",+ keyId: "k1",+ scopes: [],+ });+ expect(() => requireScope(ctx, "read")).toThrow(ForbiddenError);+ expect(() => requireScope(ctx, "write")).toThrow(ForbiddenError);+ });+});diff --git a/packages/services/src/auth/index.ts b/packages/services/src/auth/index.tsnew file mode 100644index 000000000..45388ded2--- /dev/null+++ b/packages/services/src/auth/index.ts@@ -0,0 +1,2 @@+export { matchesScope } from "./matches-scope";+export { requireScope } from "./require-scope";diff --git a/packages/services/src/auth/matches-scope.ts b/packages/services/src/auth/matches-scope.tsnew file mode 100644index 000000000..2f49689a6--- /dev/null+++ b/packages/services/src/auth/matches-scope.ts@@ -0,0 +1,28 @@+import type { Scope } from "@openstatus/db/src/schema";++/**+ * Pure scope matcher. Returns true when `held` (the scopes carried by+ * the actor) satisfies `required` (the scope the verb demands).+ *+ * Hierarchy:+ *+ * '*' ⊇ 'write' ⊇ 'read'+ *+ * Forward-compatible: when per-resource scopes land+ * (`'monitor.write' ⊇ 'monitor.read'`, etc.) extend this matcher in+ * place. The actor-aware wrapper (`require-scope.ts`) is unaffected.+ *+ * Fail-closed: any unrecognized string in `held` matches nothing. A+ * corrupt row, manual SQL edit, or future migration bug results in+ * "no permission," not a permissive default.+ */+export function matchesScope(held: readonly Scope[], required: Scope): boolean {+ if (held.length === 0) return false;++ for (const h of held) {+ if (h === "*") return true;+ if (h === required) return true;+ if (required === "read" && h === "write") return true;+ }+ return false;+}diff --git a/packages/services/src/auth/require-scope.ts b/packages/services/src/auth/require-scope.tsnew file mode 100644index 000000000..bb9725785--- /dev/null+++ b/packages/services/src/auth/require-scope.ts@@ -0,0 +1,48 @@+import type { Scope } from "@openstatus/db/src/schema";++import type { ServiceContext } from "../context";+import { ForbiddenError } from "../errors";+import { matchesScope } from "./matches-scope";++/**+ * Assert that the current actor holds `required` scope. Throws+ * `ForbiddenError` on mismatch; returns silently on success.+ *+ * Behavior by actor type:+ *+ * | Actor | Behavior |+ * | ----------------------------------------- | ------------------------- |+ * | `apiKey`, `mcp` | Active — checks scopes |+ * | `user` | No-op (dashboard session) |+ * | `system`, `slack`, `webhook`, `subscriber`| No-op (own trust boundary)|+ *+ * Member-role enforcement for `user` actors is a separate project.+ *+ * Place this as the first line of a write verb, before `withTransaction`.+ * A failed check shouldn't open a tx just to roll it back, and the+ * check has no DB dependency.+ */+export function requireScope(ctx: ServiceContext, required: Scope): void {+ const { actor } = ctx;++ if (actor.type !== "apiKey" && actor.type !== "mcp") {+ return;+ }++ if (matchesScope(actor.scopes, required)) {+ return;+ }++ // Observability for denied attempts. Per the plan: no audit row,+ // console.warn flows through the existing log pipeline. `userId` is+ // included so a leaked-key incident response can pivot to the+ // creator without a separate join. Held scopes are joined as a+ // comma-list for friendlier rendering in log aggregators that strip+ // quotes from JSON-ish payloads.+ const heldStr = actor.scopes.length > 0 ? actor.scopes.join(",") : "(none)";+ console.warn(+ `[requireScope] denied: actor=${actor.type} keyId=${actor.keyId} userId=${actor.userId ?? "null"} workspaceId=${ctx.workspace.id} required=${required} held=${heldStr}`,+ );++ throw new ForbiddenError(`API key lacks required scope: ${required}`);+}diff --git a/packages/services/src/context.ts b/packages/services/src/context.tsindex f607e8b86..39d15f357 100644--- a/packages/services/src/context.ts+++ b/packages/services/src/context.ts@@ -1,5 +1,5 @@import { SQLiteTransaction, db as defaultDb, is } from "@openstatus/db";-import type { Workspace } from "@openstatus/db/src/schema";+import type { Scope, Workspace } from "@openstatus/db/src/schema";// `@openstatus/db` does not export named DrizzleClient / DrizzleTx types today,// so we derive them from the db export and re-export from here.@@ -11,8 +11,8 @@ export type DB = DrizzleClient | DrizzleTx;export type Actor =| { type: "user"; userId: number }- | { type: "apiKey"; keyId: string; userId?: number }- | { type: "mcp"; keyId: string; userId?: number }+ | { type: "apiKey"; keyId: string; userId?: number; scopes: Scope[] }+ | { type: "mcp"; keyId: string; userId?: number; scopes: Scope[] }| { type: "slack"; teamId: string; slackUserId: string; userId?: number }| { type: "system"; job: string }| { type: "webhook"; source: string; externalId?: string }diff --git a/packages/services/src/incident/__tests__/incident.test.ts b/packages/services/src/incident/__tests__/incident.test.tsindex 738211d2f..b60832c06 100644--- a/packages/services/src/incident/__tests__/incident.test.ts+++ b/packages/services/src/incident/__tests__/incident.test.ts@@ -9,11 +9,12 @@ import {import {expectAuditRow,loadSeededWorkspace,+ makeApiKeyCtx,makeUserCtx,withTestTransaction,} from "../../../test/helpers";import type { DrizzleTx, ServiceContext } from "../../context";-import { ConflictError, NotFoundError } from "../../errors";+import { ConflictError, ForbiddenError, NotFoundError } from "../../errors";import { acknowledgeIncident } from "../acknowledge";import { deleteIncident } from "../delete";import { getIncident, listIncidents } from "../list";@@ -138,6 +139,26 @@ describe("acknowledgeIncident", () => {).rejects.toBeInstanceOf(NotFoundError);});});++ test("rejects read-only actor", async () => {+ await withTestTransaction(async (tx) => {+ const incident = await insertIncident(tx, {+ workspaceId: teamCtx.workspace.id,+ monitorId: testMonitorId,+ });+ const ctx = {+ ...makeApiKeyCtx(teamCtx.workspace, {+ keyId: "k-read",+ userId: 1,+ scopes: ["read"],+ }),+ db: tx,+ };+ await expect(+ acknowledgeIncident({ ctx, input: { id: incident.id } }),+ ).rejects.toBeInstanceOf(ForbiddenError);+ });+ });});describe("resolveIncident", () => {diff --git a/packages/services/src/incident/acknowledge.ts b/packages/services/src/incident/acknowledge.tsindex f5985fb26..373911ecd 100644--- a/packages/services/src/incident/acknowledge.ts+++ b/packages/services/src/incident/acknowledge.ts@@ -2,6 +2,7 @@ import { and, eq, isNull } from "@openstatus/db";import { incidentTable } from "@openstatus/db/src/schema";import { emitAudit } from "../audit";+import { requireScope } from "../auth";import {type ServiceContext,tryGetActorUserId,@@ -17,6 +18,7 @@ export async function acknowledgeIncident(args: {input: AcknowledgeIncidentInput;}): Promise<Incident> {const { ctx } = args;+ requireScope(ctx, "write");const input = AcknowledgeIncidentInput.parse(args.input);return withTransaction(ctx, async (tx) => {diff --git a/packages/services/src/incident/delete.ts b/packages/services/src/incident/delete.tsindex 3d781f00d..113b4a161 100644--- a/packages/services/src/incident/delete.ts+++ b/packages/services/src/incident/delete.ts@@ -2,6 +2,7 @@ import { eq } from "@openstatus/db";import { incidentTable } from "@openstatus/db/src/schema";import { emitAudit } from "../audit";+import { requireScope } from "../auth";import { type ServiceContext, withTransaction } from "../context";import { getIncidentInWorkspace } from "./internal";import { DeleteIncidentInput } from "./schemas";@@ -11,6 +12,7 @@ export async function deleteIncident(args: {input: DeleteIncidentInput;}): Promise<void> {const { ctx } = args;+ requireScope(ctx, "write");const input = DeleteIncidentInput.parse(args.input);await withTransaction(ctx, async (tx) => {diff --git a/packages/services/src/incident/resolve.ts b/packages/services/src/incident/resolve.tsindex c0f3ffa12..2d4a7023e 100644--- a/packages/services/src/incident/resolve.ts+++ b/packages/services/src/incident/resolve.ts@@ -2,6 +2,7 @@ import { and, eq, isNull } from "@openstatus/db";import { incidentTable } from "@openstatus/db/src/schema";import { emitAudit } from "../audit";+import { requireScope } from "../auth";import {type ServiceContext,tryGetActorUserId,@@ -17,6 +18,7 @@ export async function resolveIncident(args: {input: ResolveIncidentInput;}): Promise<Incident> {const { ctx } = args;+ requireScope(ctx, "write");const input = ResolveIncidentInput.parse(args.input);return withTransaction(ctx, async (tx) => {diff --git a/packages/services/src/index.ts b/packages/services/src/index.tsindex 0902cf78e..a9c0655c2 100644--- a/packages/services/src/index.ts+++ b/packages/services/src/index.ts@@ -34,6 +34,8 @@ export {emitAudit,} from "./audit";+export { matchesScope, requireScope } from "./auth";+export {assertWithinLimit,getPlanLimits,diff --git a/packages/services/src/integration/__tests__/install-slack-agent.test.ts b/packages/services/src/integration/__tests__/install-slack-agent.test.tsindex b82a1f53b..b266d875d 100644--- a/packages/services/src/integration/__tests__/install-slack-agent.test.ts+++ b/packages/services/src/integration/__tests__/install-slack-agent.test.ts@@ -6,11 +6,13 @@ import { SEEDED_WORKSPACE_TEAM_ID } from "../../../test/fixtures";import {clearAuditLog,loadSeededWorkspace,+ makeApiKeyCtx,makeSlackCtx,readAuditLog,withTestTransaction,} from "../../../test/helpers";import type { ServiceContext } from "../../context";+import { ForbiddenError } from "../../errors";import { installSlackAgent } from "../install-slack-agent";const TEAM_ID = "T_FIXTURE";@@ -241,6 +243,22 @@ describe("installSlackAgent", () => {});});+ test("rejects read-only actor", async () => {+ await withTestTransaction(async (tx) => {+ const readOnlyCtx = {+ ...makeApiKeyCtx(ctx.workspace, {+ keyId: "k-read",+ userId: 1,+ scopes: ["read"],+ }),+ db: tx,+ };+ await expect(+ installSlackAgent({ ctx: readOnlyCtx, input: baseInput }),+ ).rejects.toBeInstanceOf(ForbiddenError);+ });+ });+test("propagates the openstatus userId from the slack actor", async () => {await withTestTransaction(async (tx) => {const ATTRIBUTED_USER_ID = 1;diff --git a/packages/services/src/integration/delete.ts b/packages/services/src/integration/delete.tsindex 2cf3a0174..ffc1a569d 100644--- a/packages/services/src/integration/delete.ts+++ b/packages/services/src/integration/delete.ts@@ -2,6 +2,7 @@ import { and, eq } from "@openstatus/db";import { integration } from "@openstatus/db/src/schema";import { emitAudit } from "../audit";+import { requireScope } from "../auth";import { type ServiceContext, withTransaction } from "../context";import { DeleteIntegrationInput } from "./schemas";import { snapshotIntegration } from "./snapshot";@@ -49,6 +50,7 @@ export async function deleteIntegration(args: {input: DeleteIntegrationInput;}): Promise<void> {const { ctx } = args;+ requireScope(ctx, "write");const input = DeleteIntegrationInput.parse(args.input);let revokeBotToken: string | undefined;diff --git a/packages/services/src/integration/install-slack-agent.ts b/packages/services/src/integration/install-slack-agent.tsindex 0f0d7416a..62961bfdf 100644--- a/packages/services/src/integration/install-slack-agent.ts+++ b/packages/services/src/integration/install-slack-agent.ts@@ -2,6 +2,7 @@ import { and, desc, eq } from "@openstatus/db";import { integration } from "@openstatus/db/src/schema";import { emitAudit } from "../audit";+import { requireScope } from "../auth";import { type ServiceContext, withTransaction } from "../context";import { InternalServiceError, NotFoundError } from "../errors";import {@@ -24,6 +25,7 @@ export async function installSlackAgent(args: {input: InstallSlackAgentInput;}) {const { ctx } = args;+ requireScope(ctx, "write");const input = InstallSlackAgentInputSchema.parse(args.input);return withTransaction(ctx, async (tx) => {diff --git a/packages/services/src/invitation/__tests__/invitation.test.ts b/packages/services/src/invitation/__tests__/invitation.test.tsindex a0277c16d..7e385fefa 100644--- a/packages/services/src/invitation/__tests__/invitation.test.ts+++ b/packages/services/src/invitation/__tests__/invitation.test.ts@@ -16,11 +16,16 @@ import {import {expectAuditRow,loadSeededWorkspace,+ makeApiKeyCtx,makeUserCtx,withTestTransaction,} from "../../../test/helpers";import type { ServiceContext } from "../../context";-import { LimitExceededError, NotFoundError } from "../../errors";+import {+ ForbiddenError,+ LimitExceededError,+ NotFoundError,+} from "../../errors";const TEST_PREFIX = "svc-inv-test";@@ -109,6 +114,25 @@ describe("createInvitation", () => {});});+ test("rejects read-only actor", async () => {+ await withTestTransaction(async (tx) => {+ const readOnlyCtx = {+ ...makeApiKeyCtx(teamCtx.workspace, {+ keyId: "k-read",+ userId: 1,+ scopes: ["read"],+ }),+ db: tx,+ };+ await expect(+ createInvitation({+ ctx: readOnlyCtx,+ input: { email: "[email protected]" },+ }),+ ).rejects.toBeInstanceOf(ForbiddenError);+ });+ });+test("enforces the members plan cap on free workspace", async () => {await withTestTransaction(async (tx) => {// Free plan has `members: 1` — the owner already occupies that slot.diff --git a/packages/services/src/invitation/accept.ts b/packages/services/src/invitation/accept.tsindex daf00b85f..ebb45d105 100644--- a/packages/services/src/invitation/accept.ts+++ b/packages/services/src/invitation/accept.ts@@ -6,6 +6,7 @@ import {} from "@openstatus/db/src/schema";import { emitAudit } from "../audit";+import { requireScope } from "../auth";import {type ServiceContext,tryGetActorUserId,@@ -37,6 +38,7 @@ export async function acceptInvitation(args: {input: AcceptInvitationInput;}): Promise<Workspace> {const { ctx } = args;+ requireScope(ctx, "write");const input = AcceptInvitationInput.parse(args.input);const userId = tryGetActorUserId(ctx.actor);diff --git a/packages/services/src/invitation/create.ts b/packages/services/src/invitation/create.tsindex 1c8fbc7dc..29eb7c470 100644--- a/packages/services/src/invitation/create.ts+++ b/packages/services/src/invitation/create.ts@@ -6,6 +6,7 @@ import {} from "@openstatus/db/src/schema";import { emitAudit } from "../audit";+import { requireScope } from "../auth";import { type ServiceContext, withTransaction } from "../context";import { LimitExceededError } from "../errors";import type { Invitation } from "../types";@@ -31,6 +32,7 @@ export async function createInvitation(args: {input: CreateInvitationInput;}): Promise<Invitation> {const { ctx } = args;+ requireScope(ctx, "write");const input = CreateInvitationInput.parse(args.input);return withTransaction(ctx, async (tx) => {diff --git a/packages/services/src/invitation/delete.ts b/packages/services/src/invitation/delete.tsindex a2bf82e39..01df25476 100644--- a/packages/services/src/invitation/delete.ts+++ b/packages/services/src/invitation/delete.ts@@ -2,6 +2,7 @@ import { and, eq, isNull } from "@openstatus/db";import { invitation } from "@openstatus/db/src/schema";import { emitAudit } from "../audit";+import { requireScope } from "../auth";import { type ServiceContext, withTransaction } from "../context";import { DeleteInvitationInput } from "./schemas";@@ -25,6 +26,7 @@ export async function deleteInvitation(args: {input: DeleteInvitationInput;}): Promise<void> {const { ctx } = args;+ requireScope(ctx, "write");const input = DeleteInvitationInput.parse(args.input);await withTransaction(ctx, async (tx) => {diff --git a/packages/services/src/maintenance/__tests__/maintenance.test.ts b/packages/services/src/maintenance/__tests__/maintenance.test.tsindex 14a189131..f7d69bdaf 100644--- a/packages/services/src/maintenance/__tests__/maintenance.test.ts+++ b/packages/services/src/maintenance/__tests__/maintenance.test.ts@@ -20,6 +20,7 @@ import {import {expectAuditRow,loadSeededWorkspace,+ makeApiKeyCtx,makeSlackCtx,makeUserCtx,withTestTransaction,@@ -236,6 +237,31 @@ describe("createMaintenance", () => {});});+ test("rejects read-only actor", async () => {+ await withTestTransaction(async (tx) => {+ const readOnlyCtx = {+ ...makeApiKeyCtx(teamCtx.workspace, {+ keyId: "k-read",+ userId: 1,+ scopes: ["read"],+ }),+ db: tx,+ };+ await expect(+ createMaintenance({+ ctx: readOnlyCtx,+ input: {+ title: `${TEST_PREFIX}-read-only`,+ message: "m",+ ...futureRange(),+ pageId: testPageId,+ pageComponentIds: [],+ },+ }),+ ).rejects.toBeInstanceOf(ForbiddenError);+ });+ });+test("throws ConflictError when components span multiple pages", async () => {await withTestTransaction(async (tx) => {await expect(diff --git a/packages/services/src/maintenance/create.ts b/packages/services/src/maintenance/create.tsindex b3acb957f..02ebdcc2f 100644--- a/packages/services/src/maintenance/create.ts+++ b/packages/services/src/maintenance/create.ts@@ -1,6 +1,7 @@import { maintenance } from "@openstatus/db/src/schema";import { emitAudit } from "../audit";+import { requireScope } from "../auth";import { type ServiceContext, withTransaction } from "../context";import { ConflictError } from "../errors";import type { Maintenance } from "../types";@@ -16,6 +17,7 @@ export async function createMaintenance(args: {input: CreateMaintenanceInput;}): Promise<Maintenance> {const { ctx } = args;+ requireScope(ctx, "write");const input = CreateMaintenanceInput.parse(args.input);return withTransaction(ctx, async (tx) => {diff --git a/packages/services/src/maintenance/delete.ts b/packages/services/src/maintenance/delete.tsindex 7d7b50dc8..8bee24b1d 100644--- a/packages/services/src/maintenance/delete.ts+++ b/packages/services/src/maintenance/delete.ts@@ -2,6 +2,7 @@ import { eq } from "@openstatus/db";import { maintenance } from "@openstatus/db/src/schema";import { emitAudit } from "../audit";+import { requireScope } from "../auth";import { type ServiceContext, withTransaction } from "../context";import { getMaintenanceInWorkspace } from "./internal";import { DeleteMaintenanceInput } from "./schemas";@@ -12,6 +13,7 @@ export async function deleteMaintenance(args: {input: DeleteMaintenanceInput;}): Promise<void> {const { ctx } = args;+ requireScope(ctx, "write");const input = DeleteMaintenanceInput.parse(args.input);await withTransaction(ctx, async (tx) => {diff --git a/packages/services/src/maintenance/notify.ts b/packages/services/src/maintenance/notify.tsindex 8abd446d6..054f09ad5 100644--- a/packages/services/src/maintenance/notify.ts+++ b/packages/services/src/maintenance/notify.ts@@ -2,6 +2,7 @@ import { db as defaultDb, eq } from "@openstatus/db";import { maintenance } from "@openstatus/db/src/schema";import { dispatchMaintenanceUpdate } from "@openstatus/subscriptions";+import { requireScope } from "../auth";import type { ServiceContext } from "../context";import { ForbiddenError, NotFoundError } from "../errors";import { NotifyMaintenanceInput } from "./schemas";@@ -20,6 +21,7 @@ export async function notifyMaintenance(args: {input: NotifyMaintenanceInput;}): Promise<void> {const { ctx } = args;+ requireScope(ctx, "write");const input = NotifyMaintenanceInput.parse(args.input);const db = ctx.db ?? defaultDb;diff --git a/packages/services/src/maintenance/update.ts b/packages/services/src/maintenance/update.tsindex f43db060c..47fa89f9d 100644--- a/packages/services/src/maintenance/update.ts+++ b/packages/services/src/maintenance/update.ts@@ -2,6 +2,7 @@ import { eq } from "@openstatus/db";import { maintenance } from "@openstatus/db/src/schema";import { emitAudit } from "../audit";+import { requireScope } from "../auth";import { type ServiceContext, withTransaction } from "../context";import { ConflictError, InternalServiceError } from "../errors";import type { Maintenance } from "../types";@@ -17,6 +18,7 @@ export async function updateMaintenance(args: {input: UpdateMaintenanceInput;}): Promise<Maintenance> {const { ctx } = args;+ requireScope(ctx, "write");const input = UpdateMaintenanceInput.parse(args.input);return withTransaction(ctx, async (tx) => {diff --git a/packages/services/src/member/__tests__/member.test.ts b/packages/services/src/member/__tests__/member.test.tsindex 46e13b160..75d7bd26e 100644--- a/packages/services/src/member/__tests__/member.test.ts+++ b/packages/services/src/member/__tests__/member.test.ts@@ -10,13 +10,18 @@ import {import {expectAuditRow,loadSeededWorkspace,+ makeApiKeyCtx,makeSystemCtx,makeUserCtx,readAuditLog,withTestTransaction,} from "../../../test/helpers";import type { ServiceContext } from "../../context";-import { NotFoundError, PreconditionFailedError } from "../../errors";+import {+ ForbiddenError,+ NotFoundError,+ PreconditionFailedError,+} from "../../errors";const OWNER_USER_ID = 1;const VICTIM_USER_ID = 4242;@@ -195,6 +200,25 @@ describe("deleteMember", () => {});});+ test("rejects read-only actor", async () => {+ await withTestTransaction(async (tx) => {+ const readOnlyCtx = {+ ...makeApiKeyCtx(teamCtx.workspace, {+ keyId: "k-read",+ userId: 1,+ scopes: ["read"],+ }),+ db: tx,+ };+ await expect(+ deleteMember({+ ctx: readOnlyCtx,+ input: { userId: 999_999_999 },+ }),+ ).rejects.toBeInstanceOf(ForbiddenError);+ });+ });+test("non-owner caller is rejected with PRECONDITION_FAILED", async () => {await withTestTransaction(async (tx) => {const nonOwnerCtx = {diff --git a/packages/services/src/member/delete.ts b/packages/services/src/member/delete.tsindex 48e64d9e5..7329c325c 100644--- a/packages/services/src/member/delete.ts+++ b/packages/services/src/member/delete.ts@@ -3,6 +3,7 @@ import { usersToWorkspaces } from "@openstatus/db/src/schema";import { z } from "zod";import { emitAudit } from "../audit";+import { requireScope } from "../auth";import { type ServiceContext, withTransaction } from "../context";import { NotFoundError, PreconditionFailedError } from "../errors";import { DeleteMemberInput } from "./schemas";@@ -42,6 +43,7 @@ export async function deleteMember(args: {input: DeleteMemberInput;}): Promise<void> {const { ctx } = args;+ requireScope(ctx, "write");const input = DeleteMemberInput.parse(args.input);if (ctx.actor.type !== "user") {diff --git a/packages/services/src/monitor-tag/__tests__/monitor-tag.test.ts b/packages/services/src/monitor-tag/__tests__/monitor-tag.test.tsindex efd4c3718..f3b57e90e 100644--- a/packages/services/src/monitor-tag/__tests__/monitor-tag.test.ts+++ b/packages/services/src/monitor-tag/__tests__/monitor-tag.test.ts@@ -7,11 +7,13 @@ import { SEEDED_WORKSPACE_TEAM_ID } from "../../../test/fixtures";import {clearAuditLog,loadSeededWorkspace,+ makeApiKeyCtx,makeUserCtx,readAuditLog,withTestTransaction,} from "../../../test/helpers";import type { ServiceContext } from "../../context";+import { ForbiddenError } from "../../errors";let teamCtx: ServiceContext;@@ -165,6 +167,25 @@ describe("syncMonitorTags", () => {});});+ test("rejects read-only actor", async () => {+ await withTestTransaction(async (tx) => {+ const readOnlyCtx = {+ ...makeApiKeyCtx(teamCtx.workspace, {+ keyId: "k-read",+ userId: 1,+ scopes: ["read"],+ }),+ db: tx,+ };+ await expect(+ syncMonitorTags({+ ctx: readOnlyCtx,+ input: { tags: [{ name: "alpha", color: "red" }] },+ }),+ ).rejects.toBeInstanceOf(ForbiddenError);+ });+ });+test("create / update / delete all in one sync call", async () => {await withTestTransaction(async (tx) => {const ctx = { ...teamCtx, db: tx };diff --git a/packages/services/src/monitor-tag/sync.ts b/packages/services/src/monitor-tag/sync.tsindex 232905538..8cb9ed3b9 100644--- a/packages/services/src/monitor-tag/sync.ts+++ b/packages/services/src/monitor-tag/sync.ts@@ -2,6 +2,7 @@ import { and, eq, inArray } from "@openstatus/db";import { monitorTag, selectMonitorTagSchema } from "@openstatus/db/src/schema";import { emitAudit } from "../audit";+import { requireScope } from "../auth";import { type ServiceContext, withTransaction } from "../context";import { ForbiddenError } from "../errors";import type { MonitorTag } from "../types";@@ -25,6 +26,7 @@ export async function syncMonitorTags(args: {input: SyncMonitorTagsInput;}): Promise<MonitorTag[]> {const { ctx } = args;+ requireScope(ctx, "write");const { tags } = SyncMonitorTagsInput.parse(args.input);const workspaceId = ctx.workspace.id;diff --git a/packages/services/src/monitor/__tests__/monitor.test.ts b/packages/services/src/monitor/__tests__/monitor.test.tsindex 9c6697a62..fdbd4f72a 100644--- a/packages/services/src/monitor/__tests__/monitor.test.ts+++ b/packages/services/src/monitor/__tests__/monitor.test.ts@@ -15,6 +15,7 @@ import {import {expectAuditRow,loadSeededWorkspace,+ makeApiKeyCtx,makeUserCtx,withTestTransaction,} from "../../../test/helpers";@@ -149,6 +150,33 @@ describe("createMonitor", () => {expect(row.jobType).toBe("dns");});});++ test("rejects read-only actor", async () => {+ await withTestTransaction(async (tx) => {+ const ctx = {+ ...makeApiKeyCtx(teamCtx.workspace, {+ keyId: "k-read",+ userId: 1,+ scopes: ["read"],+ }),+ db: tx,+ };+ await expect(+ createMonitor({+ ctx,+ input: {+ name: `${TEST_PREFIX}-read-only`,+ jobType: "http",+ url: "https://example.com",+ method: "GET",+ headers: [],+ assertions: [],+ active: false,+ },+ }),+ ).rejects.toBeInstanceOf(ForbiddenError);+ });+ });});describe("deleteMonitor", () => {diff --git a/packages/services/src/monitor/clone.ts b/packages/services/src/monitor/clone.tsindex 35db6643d..2b571561a 100644--- a/packages/services/src/monitor/clone.ts+++ b/packages/services/src/monitor/clone.ts@@ -1,6 +1,7 @@import { monitor, selectMonitorSchema } from "@openstatus/db/src/schema";import { emitAudit } from "../audit";+import { requireScope } from "../auth";import { type ServiceContext, withTransaction } from "../context";import { InternalServiceError, LimitExceededError } from "../errors";import type { Monitor } from "../types";@@ -16,6 +17,7 @@ export async function cloneMonitor(args: {input: CloneMonitorInput;}): Promise<Monitor> {const { ctx } = args;+ requireScope(ctx, "write");const input = CloneMonitorInput.parse(args.input);return withTransaction(ctx, async (tx) => {diff --git a/packages/services/src/monitor/create.ts b/packages/services/src/monitor/create.tsindex c8e46dfde..e79982205 100644--- a/packages/services/src/monitor/create.ts+++ b/packages/services/src/monitor/create.ts@@ -1,6 +1,7 @@import { monitor, selectMonitorSchema } from "@openstatus/db/src/schema";import { emitAudit } from "../audit";+import { requireScope } from "../auth";import { type ServiceContext, withTransaction } from "../context";import { LimitExceededError } from "../errors";import type { Monitor } from "../types";@@ -17,6 +18,7 @@ export async function createMonitor(args: {input: CreateMonitorInput;}): Promise<Monitor> {const { ctx } = args;+ requireScope(ctx, "write");const input = CreateMonitorInput.parse(args.input);return withTransaction(ctx, async (tx) => {diff --git a/packages/services/src/monitor/delete.ts b/packages/services/src/monitor/delete.tsindex 25adf404c..20079b0f7 100644--- a/packages/services/src/monitor/delete.ts+++ b/packages/services/src/monitor/delete.ts@@ -8,6 +8,7 @@ import {} from "@openstatus/db/src/schema";import { emitAudit } from "../audit";+import { requireScope } from "../auth";import { type ServiceContext, withTransaction } from "../context";import { NotFoundError } from "../errors";import { DeleteMonitorInput, DeleteMonitorsInput } from "./schemas";@@ -22,6 +23,7 @@ export async function deleteMonitor(args: {input: DeleteMonitorInput;}): Promise<void> {const { ctx } = args;+ requireScope(ctx, "write");const input = DeleteMonitorInput.parse(args.input);await withTransaction(ctx, async (tx) => {@@ -80,6 +82,7 @@ export async function deleteMonitors(args: {input: DeleteMonitorsInput;}): Promise<void> {const { ctx } = args;+ requireScope(ctx, "write");const input = DeleteMonitorsInput.parse(args.input);await withTransaction(ctx, async (tx) => {diff --git a/packages/services/src/monitor/update.ts b/packages/services/src/monitor/update.tsindex e2ffb608c..52b97aff7 100644--- a/packages/services/src/monitor/update.ts+++ b/packages/services/src/monitor/update.ts@@ -2,6 +2,7 @@ import { and, eq, inArray, isNull } from "@openstatus/db";import { monitor, selectMonitorSchema } from "@openstatus/db/src/schema";import { emitAudit } from "../audit";+import { requireScope } from "../auth";import { type ServiceContext, withTransaction } from "../context";import type { Monitor } from "../types";import {@@ -30,6 +31,7 @@ export async function updateMonitorGeneral(args: {input: UpdateMonitorGeneralInput;}): Promise<Monitor> {const { ctx } = args;+ requireScope(ctx, "write");const input = UpdateMonitorGeneralInput.parse(args.input);return withTransaction(ctx, async (tx) => {@@ -73,6 +75,7 @@ export async function updateMonitorRetry(args: {input: UpdateMonitorRetryInput;}): Promise<void> {const { ctx } = args;+ requireScope(ctx, "write");const input = UpdateMonitorRetryInput.parse(args.input);await withTransaction(ctx, async (tx) => {const existing = await getMonitorInWorkspace({@@ -101,6 +104,7 @@ export async function updateMonitorFollowRedirects(args: {input: UpdateMonitorFollowRedirectsInput;}): Promise<void> {const { ctx } = args;+ requireScope(ctx, "write");const input = UpdateMonitorFollowRedirectsInput.parse(args.input);await withTransaction(ctx, async (tx) => {const existing = await getMonitorInWorkspace({@@ -129,6 +133,7 @@ export async function updateMonitorOtel(args: {input: UpdateMonitorOtelInput;}): Promise<void> {const { ctx } = args;+ requireScope(ctx, "write");const input = UpdateMonitorOtelInput.parse(args.input);await withTransaction(ctx, async (tx) => {const existing = await getMonitorInWorkspace({@@ -161,6 +166,7 @@ export async function updateMonitorPublic(args: {input: UpdateMonitorPublicInput;}): Promise<void> {const { ctx } = args;+ requireScope(ctx, "write");const input = UpdateMonitorPublicInput.parse(args.input);await withTransaction(ctx, async (tx) => {const existing = await getMonitorInWorkspace({@@ -189,6 +195,7 @@ export async function updateMonitorResponseTime(args: {input: UpdateMonitorResponseTimeInput;}): Promise<void> {const { ctx } = args;+ requireScope(ctx, "write");const input = UpdateMonitorResponseTimeInput.parse(args.input);await withTransaction(ctx, async (tx) => {const existing = await getMonitorInWorkspace({@@ -227,6 +234,7 @@ export async function bulkUpdateMonitors(args: {input: BulkUpdateMonitorsInput;}): Promise<void> {const { ctx } = args;+ requireScope(ctx, "write");const input = BulkUpdateMonitorsInput.parse(args.input);if (input.public === undefined && input.active === undefined) return;diff --git a/packages/services/src/notification/__tests__/notification.test.ts b/packages/services/src/notification/__tests__/notification.test.tsindex 2ac2d3a31..a12ca8e3f 100644--- a/packages/services/src/notification/__tests__/notification.test.ts+++ b/packages/services/src/notification/__tests__/notification.test.ts@@ -14,6 +14,7 @@ import {cleanQuotaGatedTables,expectAuditRow,loadSeededWorkspace,+ makeApiKeyCtx,makeUserCtx,withTestTransaction,} from "../../../test/helpers";@@ -179,6 +180,30 @@ describe("createNotification", () => {});});+ test("rejects read-only actor", async () => {+ await withTestTransaction(async (tx) => {+ const readOnlyCtx = {+ ...makeApiKeyCtx(teamCtx.workspace, {+ keyId: "k-read",+ userId: 1,+ scopes: ["read"],+ }),+ db: tx,+ };+ await expect(+ createNotification({+ ctx: readOnlyCtx,+ input: {+ name: `${TEST_PREFIX}-read-only`,+ provider: "discord",+ data: { discord: "https://discord.com/api/webhooks/1/abc" },+ monitors: [],+ },+ }),+ ).rejects.toBeInstanceOf(ForbiddenError);+ });+ });+test("throws ForbiddenError for cross-workspace monitor", async () => {await withTestTransaction(async (tx) => {await expect(diff --git a/packages/services/src/notification/create.ts b/packages/services/src/notification/create.tsindex 0a980e81d..f6c51a304 100644--- a/packages/services/src/notification/create.ts+++ b/packages/services/src/notification/create.ts@@ -6,6 +6,7 @@ import {} from "@openstatus/db/src/schema";import { emitAudit } from "../audit";+import { requireScope } from "../auth";import { type ServiceContext, withTransaction } from "../context";import { LimitExceededError } from "../errors";import type { Notification } from "../types";@@ -21,6 +22,7 @@ export async function createNotification(args: {input: CreateNotificationInput;}): Promise<Notification> {const { ctx } = args;+ requireScope(ctx, "write");const input = CreateNotificationInput.parse(args.input);return withTransaction(ctx, async (tx) => {diff --git a/packages/services/src/notification/delete.ts b/packages/services/src/notification/delete.tsindex 9e664188a..21ec68792 100644--- a/packages/services/src/notification/delete.ts+++ b/packages/services/src/notification/delete.ts@@ -2,6 +2,7 @@ import { eq } from "@openstatus/db";import { notification } from "@openstatus/db/src/schema";import { emitAudit } from "../audit";+import { requireScope } from "../auth";import { type ServiceContext, withTransaction } from "../context";import { getNotificationInWorkspace } from "./internal";import { DeleteNotificationInput } from "./schemas";@@ -15,6 +16,7 @@ export async function deleteNotification(args: {input: DeleteNotificationInput;}): Promise<void> {const { ctx } = args;+ requireScope(ctx, "write");const input = DeleteNotificationInput.parse(args.input);await withTransaction(ctx, async (tx) => {diff --git a/packages/services/src/notification/update.ts b/packages/services/src/notification/update.tsindex ded716f15..9028c2b3e 100644--- a/packages/services/src/notification/update.ts+++ b/packages/services/src/notification/update.ts@@ -6,6 +6,7 @@ import {} from "@openstatus/db/src/schema";import { emitAudit } from "../audit";+import { requireScope } from "../auth";import { type ServiceContext, withTransaction } from "../context";import type { Notification } from "../types";import {@@ -21,6 +22,7 @@ export async function updateNotification(args: {input: UpdateNotificationInput;}): Promise<Notification> {const { ctx } = args;+ requireScope(ctx, "write");const input = UpdateNotificationInput.parse(args.input);return withTransaction(ctx, async (tx) => {diff --git a/packages/services/src/page-component/__tests__/page-component.test.ts b/packages/services/src/page-component/__tests__/page-component.test.tsindex 66bd942ba..7f6ad6661 100644--- a/packages/services/src/page-component/__tests__/page-component.test.ts+++ b/packages/services/src/page-component/__tests__/page-component.test.ts@@ -14,6 +14,7 @@ import {import {expectAuditRow,loadSeededWorkspace,+ makeApiKeyCtx,makeUserCtx,withTestTransaction,} from "../../../test/helpers";@@ -310,6 +311,25 @@ describe("listPageComponents", () => {});describe("deletePageComponent", () => {+ test("rejects read-only actor", async () => {+ await withTestTransaction(async (tx) => {+ const readOnlyCtx = {+ ...makeApiKeyCtx(teamCtx.workspace, {+ keyId: "k-read",+ userId: 1,+ scopes: ["read"],+ }),+ db: tx,+ };+ await expect(+ deletePageComponent({+ ctx: readOnlyCtx,+ input: { id: 999_999_999 },+ }),+ ).rejects.toBeInstanceOf(ForbiddenError);+ });+ });+test("throws NotFoundError for cross-workspace id", async () => {await withTestTransaction(async (tx) => {const teamCtxTx = { ...teamCtx, db: tx };diff --git a/packages/services/src/page-component/delete.ts b/packages/services/src/page-component/delete.tsindex 46ec66308..f1f01503f 100644--- a/packages/services/src/page-component/delete.ts+++ b/packages/services/src/page-component/delete.ts@@ -2,6 +2,7 @@ import { and, eq } from "@openstatus/db";import { pageComponent } from "@openstatus/db/src/schema";import { emitAudit } from "../audit";+import { requireScope } from "../auth";import { type ServiceContext, withTransaction } from "../context";import { NotFoundError } from "../errors";import { DeletePageComponentInput } from "./schemas";@@ -16,6 +17,7 @@ export async function deletePageComponent(args: {input: DeletePageComponentInput;}): Promise<void> {const { ctx } = args;+ requireScope(ctx, "write");const input = DeletePageComponentInput.parse(args.input);await withTransaction(ctx, async (tx) => {diff --git a/packages/services/src/page-component/update-order.ts b/packages/services/src/page-component/update-order.tsindex 8643dcbbf..7e5c54936 100644--- a/packages/services/src/page-component/update-order.ts+++ b/packages/services/src/page-component/update-order.ts@@ -2,6 +2,7 @@ import { and, eq, inArray, ne, sql } from "@openstatus/db";import { pageComponent, pageComponentGroup } from "@openstatus/db/src/schema";import { emitAudit } from "../audit";+import { requireScope } from "../auth";import { type ServiceContext, withTransaction } from "../context";import { LimitExceededError, ValidationError } from "../errors";import { assertPageInWorkspace, validateMonitorIds } from "./internal";@@ -27,6 +28,7 @@ export async function updatePageComponentOrder(args: {input: UpdatePageComponentOrderInput;}): Promise<void> {const { ctx } = args;+ requireScope(ctx, "write");const input = UpdatePageComponentOrderInput.parse(args.input);// Reject duplicate group ids up front — otherwise the diff loopdiff --git a/packages/services/src/page-subscriber/__tests__/page-subscriber.test.ts b/packages/services/src/page-subscriber/__tests__/page-subscriber.test.tsindex c93b93840..607db4ab3 100644--- a/packages/services/src/page-subscriber/__tests__/page-subscriber.test.ts+++ b/packages/services/src/page-subscriber/__tests__/page-subscriber.test.ts@@ -15,6 +15,7 @@ import {} from "@openstatus/db/src/schema";import {+ createPageSubscriber,getSubscriberByToken,hasPendingSubscriber,unsubscribeSubscriber,@@ -26,8 +27,12 @@ import { SEEDED_WORKSPACE_TEAM_ID } from "../../../test/fixtures";import {clearAuditLog,expectAuditRow,+ loadSeededWorkspace,+ makeApiKeyCtx,readAuditLog,+ withTestTransaction,} from "../../../test/helpers";+import { ForbiddenError } from "../../errors";// Seeded data we lean on (see packages/db/src/seed.mts):// workspace 1 = team plan, has status-subscribers=true@@ -736,3 +741,31 @@ describe("hasPendingSubscriber", () => {expect(result).toBe(false);});});++// ─── createPageSubscriber ────────────────────────────────────────────────────++describe("createPageSubscriber", () => {+ test("rejects read-only actor", async () => {+ await withTestTransaction(async (tx) => {+ const team = await loadSeededWorkspace(SEEDED_WORKSPACE_TEAM_ID);+ const readOnlyCtx = {+ ...makeApiKeyCtx(team, {+ keyId: "k-read",+ userId: 1,+ scopes: ["read"],+ }),+ db: tx,+ };+ await expect(+ createPageSubscriber({+ ctx: readOnlyCtx,+ input: {+ pageId: PAGE_ID,+ channelType: "email",+ email: "[email protected]",+ },+ }),+ ).rejects.toBeInstanceOf(ForbiddenError);+ });+ });+});diff --git a/packages/services/src/page-subscriber/create.ts b/packages/services/src/page-subscriber/create.tsindex 1190f070e..f845ec429 100644--- a/packages/services/src/page-subscriber/create.ts+++ b/packages/services/src/page-subscriber/create.ts@@ -9,6 +9,7 @@ import { detectWebhookFlavor } from "@openstatus/subscriptions";import { assertSafeUrl } from "@openstatus/utils";import { emitAudit } from "../audit";+import { requireScope } from "../auth";import { type ServiceContext, withTransaction } from "../context";import { ConflictError, ValidationError } from "../errors";import {@@ -54,6 +55,7 @@ export async function createPageSubscriber(args: {input: CreatePageSubscriberInput;}): Promise<CreatePageSubscriberResult> {const { ctx } = args;+ requireScope(ctx, "write");const input = CreatePageSubscriberInput.parse(args.input);const componentIds = input.componentIds ?? [];diff --git a/packages/services/src/page-subscriber/delete.ts b/packages/services/src/page-subscriber/delete.tsindex aaad1ca38..778d806e6 100644--- a/packages/services/src/page-subscriber/delete.ts+++ b/packages/services/src/page-subscriber/delete.ts@@ -5,6 +5,7 @@ import {} from "@openstatus/db/src/schema";import { emitAudit } from "../audit";+import { requireScope } from "../auth";import { type ServiceContext, withTransaction } from "../context";import { NotFoundError } from "../errors";import { loadPageForWorkspace } from "./internal";@@ -20,6 +21,7 @@ export async function deletePageSubscriber(args: {input: DeletePageSubscriberInput;}): Promise<void> {const { ctx } = args;+ requireScope(ctx, "write");const input = DeletePageSubscriberInput.parse(args.input);await withTransaction(ctx, async (tx) => {diff --git a/packages/services/src/page-subscriber/send-test-webhook.ts b/packages/services/src/page-subscriber/send-test-webhook.tsindex 2c62f3391..5990e708f 100644--- a/packages/services/src/page-subscriber/send-test-webhook.ts+++ b/packages/services/src/page-subscriber/send-test-webhook.ts@@ -5,6 +5,7 @@ import {sendTestWebhookRequest,} from "@openstatus/subscriptions";+import { requireScope } from "../auth";import { type ServiceContext, withTransaction } from "../context";import { NotFoundError, ValidationError } from "../errors";import { loadPageForWorkspace } from "./internal";@@ -21,6 +22,7 @@ export async function sendPageSubscriberTestWebhook(args: {input: SendPageSubscriberTestWebhookInput;}): Promise<void> {const { ctx } = args;+ requireScope(ctx, "write");const input = SendPageSubscriberTestWebhookInput.parse(args.input);const existing = await withTransaction(ctx, async (tx) => {diff --git a/packages/services/src/page-subscriber/update.ts b/packages/services/src/page-subscriber/update.tsindex 5d1fd323c..0f572abcd 100644--- a/packages/services/src/page-subscriber/update.ts+++ b/packages/services/src/page-subscriber/update.ts@@ -10,6 +10,7 @@ import { detectWebhookFlavor } from "@openstatus/subscriptions";import { assertSafeUrl } from "@openstatus/utils";import { emitAudit } from "../audit";+import { requireScope } from "../auth";import { type ServiceContext, withTransaction } from "../context";import { ConflictError, NotFoundError, ValidationError } from "../errors";import { UpdatePageSubscriberChannelInput } from "./schemas";@@ -34,6 +35,7 @@ export async function updatePageSubscriberChannel(args: {input: UpdatePageSubscriberChannelInput;}): Promise<void> {const { ctx } = args;+ requireScope(ctx, "write");const input = UpdatePageSubscriberChannelInput.parse(args.input);// `assertSafeUrl` does a DNS lookup to block private/internal targets;diff --git a/packages/services/src/page/__tests__/page.test.ts b/packages/services/src/page/__tests__/page.test.tsindex 85d849cda..c01e0f1c3 100644--- a/packages/services/src/page/__tests__/page.test.ts+++ b/packages/services/src/page/__tests__/page.test.ts@@ -10,6 +10,7 @@ import {cleanQuotaGatedTables,expectAuditRow,loadSeededWorkspace,+ makeApiKeyCtx,makeUserCtx,withTestTransaction,} from "../../../test/helpers";@@ -203,6 +204,33 @@ describe("updatePageGeneral", () => {).rejects.toBeInstanceOf(NotFoundError);});});++ test("rejects read-only actor", async () => {+ await withTestTransaction(async (tx) => {+ const p = await newPage({+ ctx: { ...teamCtx, db: tx },+ input: { title: "Team", slug: uniqueSlug("read-only") },+ });+ const readOnlyCtx = {+ ...makeApiKeyCtx(teamCtx.workspace, {+ keyId: "k-read",+ userId: 1,+ scopes: ["read"],+ }),+ db: tx,+ };+ await expect(+ updatePageGeneral({+ ctx: readOnlyCtx,+ input: {+ id: p.id,+ title: "Read-only Update",+ slug: uniqueSlug("read-only-update"),+ },+ }),+ ).rejects.toBeInstanceOf(ForbiddenError);+ });+ });});describe("updatePageLocales", () => {diff --git a/packages/services/src/page/create.ts b/packages/services/src/page/create.tsindex 1d6e3c9a9..028029f16 100644--- a/packages/services/src/page/create.ts+++ b/packages/services/src/page/create.ts@@ -5,6 +5,7 @@ import {} from "@openstatus/db/src/schema";import { emitAudit } from "../audit";+import { requireScope } from "../auth";import { type ServiceContext, withTransaction } from "../context";import type { Page } from "../types";import {@@ -21,6 +22,7 @@ export async function createPage(args: {input: CreatePageInput;}): Promise<Page> {const { ctx } = args;+ requireScope(ctx, "write");const input = CreatePageInput.parse(args.input);return withTransaction(ctx, async (tx) => {@@ -109,6 +111,7 @@ export async function newPage(args: {input: NewPageInput;}): Promise<Page> {const { ctx } = args;+ requireScope(ctx, "write");const input = NewPageInput.parse(args.input);return withTransaction(ctx, async (tx) => {diff --git a/packages/services/src/page/delete.ts b/packages/services/src/page/delete.tsindex 58a9de72e..aa8c5ffe5 100644--- a/packages/services/src/page/delete.ts+++ b/packages/services/src/page/delete.ts@@ -2,6 +2,7 @@ import { eq } from "@openstatus/db";import { page } from "@openstatus/db/src/schema";import { emitAudit } from "../audit";+import { requireScope } from "../auth";import { type ServiceContext, withTransaction } from "../context";import { getPageInWorkspace } from "./internal";import { DeletePageInput } from "./schemas";@@ -12,6 +13,7 @@ export async function deletePage(args: {input: DeletePageInput;}): Promise<void> {const { ctx } = args;+ requireScope(ctx, "write");const input = DeletePageInput.parse(args.input);await withTransaction(ctx, async (tx) => {diff --git a/packages/services/src/page/update.ts b/packages/services/src/page/update.tsindex be15fe7ee..673d4a969 100644--- a/packages/services/src/page/update.ts+++ b/packages/services/src/page/update.ts@@ -2,6 +2,7 @@ import { eq } from "@openstatus/db";import { page } from "@openstatus/db/src/schema";import { emitAudit } from "../audit";+import { requireScope } from "../auth";import { type ServiceContext, withTransaction } from "../context";import { LimitExceededError } from "../errors";import {@@ -24,6 +25,7 @@ export async function updatePageGeneral(args: {input: UpdatePageGeneralInput;}): Promise<void> {const { ctx } = args;+ requireScope(ctx, "write");const input = UpdatePageGeneralInput.parse(args.input);await withTransaction(ctx, async (tx) => {@@ -69,6 +71,7 @@ export async function updatePageCustomDomain(args: {input: UpdatePageCustomDomainInput;}): Promise<{ existingDomain: string | null }> {const { ctx } = args;+ requireScope(ctx, "write");const input = UpdatePageCustomDomainInput.parse(args.input);return withTransaction(ctx, async (tx) => {@@ -112,6 +115,7 @@ export async function updatePagePasswordProtection(args: {input: UpdatePagePasswordProtectionInput;}): Promise<void> {const { ctx } = args;+ requireScope(ctx, "write");const input = UpdatePagePasswordProtectionInput.parse(args.input);assertAccessTypeAllowed(ctx.workspace, {@@ -164,6 +168,7 @@ export async function updatePageAppearance(args: {input: UpdatePageAppearanceInput;}): Promise<void> {const { ctx } = args;+ requireScope(ctx, "write");const input = UpdatePageAppearanceInput.parse(args.input);await withTransaction(ctx, async (tx) => {@@ -208,6 +213,7 @@ export async function updatePageLinks(args: {input: UpdatePageLinksInput;}): Promise<void> {const { ctx } = args;+ requireScope(ctx, "write");const input = UpdatePageLinksInput.parse(args.input);await withTransaction(ctx, async (tx) => {@@ -242,6 +248,7 @@ export async function updatePageLocales(args: {input: UpdatePageLocalesInput;}): Promise<void> {const { ctx } = args;+ requireScope(ctx, "write");const input = UpdatePageLocalesInput.parse(args.input);if (!ctx.workspace.limits.i18n) {@@ -281,6 +288,7 @@ export async function updatePageConfiguration(args: {input: UpdatePageConfigurationInput;}): Promise<void> {const { ctx } = args;+ requireScope(ctx, "write");const input = UpdatePageConfigurationInput.parse(args.input);await withTransaction(ctx, async (tx) => {diff --git a/packages/services/src/private-location/create.ts b/packages/services/src/private-location/create.tsindex b748933fb..b590a3ea7 100644--- a/packages/services/src/private-location/create.ts+++ b/packages/services/src/private-location/create.ts@@ -5,6 +5,7 @@ import {} from "@openstatus/db/src/schema";import { emitAudit } from "../audit";+import { requireScope } from "../auth";import { type ServiceContext, withTransaction } from "../context";import type { PrivateLocation } from "../types";import { assertMonitorsInWorkspace } from "./internal";@@ -24,6 +25,7 @@ export async function createPrivateLocation(args: {input: CreatePrivateLocationInput;}): Promise<PrivateLocation> {const { ctx } = args;+ requireScope(ctx, "write");const input = CreatePrivateLocationInput.parse(args.input);// The pivot table has no UNIQUE (private_location_id, monitor_id)diff --git a/packages/services/src/private-location/delete.ts b/packages/services/src/private-location/delete.tsindex b04cb89c8..e50202f0b 100644--- a/packages/services/src/private-location/delete.ts+++ b/packages/services/src/private-location/delete.ts@@ -5,6 +5,7 @@ import {} from "@openstatus/db/src/schema";import { emitAudit } from "../audit";+import { requireScope } from "../auth";import { type ServiceContext, withTransaction } from "../context";import { DeletePrivateLocationInput } from "./schemas";@@ -21,6 +22,7 @@ export async function deletePrivateLocation(args: {input: DeletePrivateLocationInput;}): Promise<void> {const { ctx } = args;+ requireScope(ctx, "write");const input = DeletePrivateLocationInput.parse(args.input);await withTransaction(ctx, async (tx) => {diff --git a/packages/services/src/private-location/update.ts b/packages/services/src/private-location/update.tsindex 4aec80365..096177c95 100644--- a/packages/services/src/private-location/update.ts+++ b/packages/services/src/private-location/update.ts@@ -6,6 +6,7 @@ import {} from "@openstatus/db/src/schema";import { emitAudit } from "../audit";+import { requireScope } from "../auth";import { type ServiceContext, withTransaction } from "../context";import { NotFoundError } from "../errors";import type { PrivateLocation } from "../types";@@ -25,6 +26,7 @@ export async function updatePrivateLocation(args: {input: UpdatePrivateLocationInput;}): Promise<PrivateLocation> {const { ctx } = args;+ requireScope(ctx, "write");const input = UpdatePrivateLocationInput.parse(args.input);// The pivot table has no UNIQUE (private_location_id, monitor_id)diff --git a/packages/services/src/status-report/__tests__/status-report.test.ts b/packages/services/src/status-report/__tests__/status-report.test.tsindex ef3451aae..657515196 100644--- a/packages/services/src/status-report/__tests__/status-report.test.ts+++ b/packages/services/src/status-report/__tests__/status-report.test.ts@@ -23,6 +23,7 @@ import {import {expectAuditRow,loadSeededWorkspace,+ makeApiKeyCtx,makeSlackCtx,makeUserCtx,withTestTransaction,@@ -178,6 +179,32 @@ describe("createStatusReport", () => {).rejects.toBeInstanceOf(NotFoundError);});});++ test("rejects read-only actor", async () => {+ await withTestTransaction(async (tx) => {+ const ctx = {+ ...makeApiKeyCtx(teamCtx.workspace, {+ keyId: "k-read",+ userId: 1,+ scopes: ["read"],+ }),+ db: tx,+ };+ await expect(+ createStatusReport({+ ctx,+ input: {+ title: `${TEST_PREFIX}-read-only`,+ status: "investigating",+ message: "blocked",+ date: new Date(),+ pageId: testPageId,+ pageComponentIds: [],+ },+ }),+ ).rejects.toBeInstanceOf(ForbiddenError);+ });+ });});describe("addStatusReportUpdate", () => {diff --git a/packages/services/src/status-report/add-update.ts b/packages/services/src/status-report/add-update.tsindex b9cd05ee3..7424c5a5f 100644--- a/packages/services/src/status-report/add-update.ts+++ b/packages/services/src/status-report/add-update.ts@@ -2,6 +2,7 @@ import { eq } from "@openstatus/db";import { statusReport, statusReportUpdate } from "@openstatus/db/src/schema";import { emitAudit } from "../audit";+import { requireScope } from "../auth";import { type ServiceContext, withTransaction } from "../context";import { InternalServiceError } from "../errors";import type { StatusReport, StatusReportUpdate } from "../types";@@ -18,6 +19,7 @@ export async function addStatusReportUpdate(args: {input: AddStatusReportUpdateInput;}): Promise<AddStatusReportUpdateResult> {const { ctx } = args;+ requireScope(ctx, "write");const input = AddStatusReportUpdateInput.parse(args.input);return withTransaction(ctx, async (tx) => {diff --git a/packages/services/src/status-report/create.ts b/packages/services/src/status-report/create.tsindex 7e297be5b..c39a1ac47 100644--- a/packages/services/src/status-report/create.ts+++ b/packages/services/src/status-report/create.ts@@ -6,6 +6,7 @@ import {} from "@openstatus/db/src/schema";import { emitAudit } from "../audit";+import { requireScope } from "../auth";import { type ServiceContext, withTransaction } from "../context";import { ConflictError, NotFoundError } from "../errors";import type { StatusReport, StatusReportUpdate } from "../types";@@ -25,6 +26,7 @@ export async function createStatusReport(args: {input: CreateStatusReportInput;}): Promise<CreateStatusReportResult> {const { ctx } = args;+ requireScope(ctx, "write");const input = CreateStatusReportInput.parse(args.input);return withTransaction(ctx, async (tx) => {diff --git a/packages/services/src/status-report/delete.ts b/packages/services/src/status-report/delete.tsindex b1849d8a8..17264a9ba 100644--- a/packages/services/src/status-report/delete.ts+++ b/packages/services/src/status-report/delete.ts@@ -2,6 +2,7 @@ import { eq } from "@openstatus/db";import { statusReport, statusReportUpdate } from "@openstatus/db/src/schema";import { emitAudit } from "../audit";+import { requireScope } from "../auth";import { type ServiceContext, withTransaction } from "../context";import { getReportInWorkspace, getReportUpdateInWorkspace } from "./internal";import {@@ -18,6 +19,7 @@ export async function deleteStatusReport(args: {input: DeleteStatusReportInput;}): Promise<void> {const { ctx } = args;+ requireScope(ctx, "write");const input = DeleteStatusReportInput.parse(args.input);await withTransaction(ctx, async (tx) => {@@ -44,6 +46,7 @@ export async function deleteStatusReportUpdate(args: {input: DeleteStatusReportUpdateInput;}): Promise<void> {const { ctx } = args;+ requireScope(ctx, "write");const input = DeleteStatusReportUpdateInput.parse(args.input);await withTransaction(ctx, async (tx) => {diff --git a/packages/services/src/status-report/notify.ts b/packages/services/src/status-report/notify.tsindex bac528567..fcb2f4027 100644--- a/packages/services/src/status-report/notify.ts+++ b/packages/services/src/status-report/notify.ts@@ -2,6 +2,7 @@ import { db as defaultDb, eq } from "@openstatus/db";import { statusReport, statusReportUpdate } from "@openstatus/db/src/schema";import { dispatchStatusReportUpdate } from "@openstatus/subscriptions";+import { requireScope } from "../auth";import type { ServiceContext } from "../context";import { ForbiddenError, NotFoundError } from "../errors";import { NotifyStatusReportInput } from "./schemas";@@ -21,6 +22,7 @@ export async function notifyStatusReport(args: {input: NotifyStatusReportInput;}): Promise<void> {const { ctx } = args;+ requireScope(ctx, "write");const input = NotifyStatusReportInput.parse(args.input);const db = ctx.db ?? defaultDb;diff --git a/packages/services/src/status-report/resolve.ts b/packages/services/src/status-report/resolve.tsindex 1fcd6abbf..bef4b0df7 100644--- a/packages/services/src/status-report/resolve.ts+++ b/packages/services/src/status-report/resolve.ts@@ -9,6 +9,10 @@ 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_update.create` (same db path).+ *+ * No scope check here: the delegate (`addStatusReportUpdate`) enforces+ * `requireScope(ctx, 'write')` itself, and a wrapper double-check is+ * pure noise.*/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 1cf558b8c..fe1efd120 100644--- a/packages/services/src/status-report/update.ts+++ b/packages/services/src/status-report/update.ts@@ -2,6 +2,7 @@ import { eq } from "@openstatus/db";import { statusReport, statusReportUpdate } from "@openstatus/db/src/schema";import { emitAudit } from "../audit";+import { requireScope } from "../auth";import { type ServiceContext, withTransaction } from "../context";import { InternalServiceError } from "../errors";import type { StatusReport, StatusReportUpdate } from "../types";@@ -33,6 +34,7 @@ export async function updateStatusReport(args: {input: UpdateStatusReportInput;}): Promise<StatusReport> {const { ctx } = args;+ requireScope(ctx, "write");const input = UpdateStatusReportInput.parse(args.input);return withTransaction(ctx, async (tx) => {@@ -98,6 +100,7 @@ export async function updateStatusReportUpdate(args: {input: UpdateStatusReportUpdateInput;}): Promise<StatusReportUpdate> {const { ctx } = args;+ requireScope(ctx, "write");const input = UpdateStatusReportUpdateInput.parse(args.input);return withTransaction(ctx, async (tx) => {diff --git a/packages/services/src/user/delete.ts b/packages/services/src/user/delete.tsindex b3507983a..5d4d2b7da 100644--- a/packages/services/src/user/delete.ts+++ b/packages/services/src/user/delete.ts@@ -7,6 +7,7 @@ import {} from "@openstatus/db/src/schema";import { emitAudit } from "../audit";+import { requireScope } from "../auth";import {type ServiceContext,tryGetActorUserId,@@ -46,6 +47,7 @@ export async function deleteAccount(args: {input?: DeleteAccountInput;}): Promise<void> {const { ctx } = args;+ requireScope(ctx, "write");if (args.input !== undefined) DeleteAccountInput.parse(args.input);// `userId` is derived from `ctx.actor`, not input — account deletiondiff --git a/packages/services/src/workspace/__tests__/workspace.test.ts b/packages/services/src/workspace/__tests__/workspace.test.tsindex c3d895356..291d35a87 100644--- a/packages/services/src/workspace/__tests__/workspace.test.ts+++ b/packages/services/src/workspace/__tests__/workspace.test.ts@@ -12,10 +12,12 @@ import { SEEDED_WORKSPACE_TEAM_ID } from "../../../test/fixtures";import {expectAuditRow,loadSeededWorkspace,+ makeApiKeyCtx,makeUserCtx,withTestTransaction,} from "../../../test/helpers";import type { ServiceContext } from "../../context";+import { ForbiddenError } from "../../errors";let teamCtx: ServiceContext;@@ -91,6 +93,25 @@ describe("listWorkspaces", () => {});describe("updateWorkspaceName", () => {+ test("rejects read-only actor", async () => {+ await withTestTransaction(async (tx) => {+ const readOnlyCtx = {+ ...makeApiKeyCtx(teamCtx.workspace, {+ keyId: "k-read",+ userId: 1,+ scopes: ["read"],+ }),+ db: tx,+ };+ await expect(+ updateWorkspaceName({+ ctx: readOnlyCtx,+ input: { name: "blocked" },+ }),+ ).rejects.toBeInstanceOf(ForbiddenError);+ });+ });+test("renames the workspace and emits an audit row", async () => {await withTestTransaction(async (tx) => {const ctx = { ...teamCtx, db: tx };diff --git a/packages/services/src/workspace/update.ts b/packages/services/src/workspace/update.tsindex 3bf0e1ff4..6c670fd71 100644--- a/packages/services/src/workspace/update.ts+++ b/packages/services/src/workspace/update.ts@@ -2,6 +2,7 @@ import { eq } from "@openstatus/db";import { workspace } from "@openstatus/db/src/schema";import { emitAudit } from "../audit";+import { requireScope } from "../auth";import { type ServiceContext, withTransaction } from "../context";import { NotFoundError } from "../errors";import { UpdateWorkspaceNameInput } from "./schemas";@@ -15,6 +16,7 @@ export async function updateWorkspaceName(args: {input: UpdateWorkspaceNameInput;}): Promise<void> {const { ctx } = args;+ requireScope(ctx, "write");const input = UpdateWorkspaceNameInput.parse(args.input);await withTransaction(ctx, async (tx) => {diff --git a/packages/services/test/helpers.ts b/packages/services/test/helpers.tsindex 3112f1f97..eaf7cf1d4 100644--- a/packages/services/test/helpers.ts+++ b/packages/services/test/helpers.ts@@ -1,6 +1,7 @@import { expect } from "bun:test";import { and, db, desc, eq, inArray } from "@openstatus/db";import {+ type Scope,auditLog,notification,page,@@ -130,7 +131,12 @@ export function makeUserCtx(export function makeApiKeyCtx(workspace: Workspace,- opts: { keyId: string; userId?: number; requestId?: string },+ opts: {+ keyId: string;+ userId?: number;+ requestId?: string;+ scopes?: Scope[];+ },): ServiceContext {return {workspace,@@ -138,6 +144,7 @@ export function makeApiKeyCtx(type: "apiKey",keyId: opts.keyId,userId: opts.userId,+ scopes: opts.scopes ?? ["write"],},requestId: opts.requestId,};@@ -145,7 +152,12 @@ export function makeApiKeyCtx(export function makeMcpCtx(workspace: Workspace,- opts: { keyId: string; userId?: number; requestId?: string },+ opts: {+ keyId: string;+ userId?: number;+ requestId?: string;+ scopes?: Scope[];+ },): ServiceContext {return {workspace,@@ -153,6 +165,7 @@ export function makeMcpCtx(type: "mcp",keyId: opts.keyId,userId: opts.userId,+ scopes: opts.scopes ?? ["write"],},requestId: opts.requestId,};