Skip to content

Open-source status page, incident response and uptime monitoring

login: sso (#2477)

Thibault Le Ouaye2f3c70d5529
diff --git a/CLAUDE.md b/CLAUDE.md
index df5e32e01..a621d75cf 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -128,7 +128,9 @@ A scattered `as never` is usually a missing helper.
## Services & Audit Log Pattern
-All workspace-scoped business logic lives in `packages/services` — **not** in tRPC routers. Routers stay thin: validate input, call a service verb, map errors. This keeps logic reusable across tRPC, Hono, and background jobs, and keeps it Edge-safe (the dashboard runs tRPC on Next.js Edge, so service code must avoid `node:*` imports).
+All workspace-scoped business logic lives in `packages/services` — **not** in tRPC routers. Routers stay thin: validate input, call a service verb, map errors. This keeps logic reusable across tRPC, Hono, and background jobs.
+
+Note on runtimes: the dashboard's tRPC handler runs on the **Node.js** runtime (see the comment in `apps/dashboard/src/app/api/trpc/lambda/[trpc]/route.ts` — several routers pull Node-only deps), and no Edge route imports `@openstatus/services`. Node-only dependencies in services are therefore acceptable. What *is* enforced: `apps/workflows` runs on Deno and imports services, so `pnpm check` (`deno check --sloppy-imports`) must pass in both packages.
Conventions for any new mutation:
@@ -144,7 +146,7 @@ Conventions for any new mutation:
- Action names follow `{entity}.{verb}` (`monitor.update`, `integration.delete`). Add new variants to the discriminated union in `@openstatus/db/src/schema/audit_logs/validation.ts`.
- **Tests live in `packages/services/src/<entity>/__tests__/`** and use `expectAuditRow({ workspaceId, action, entityId, ... })` from `packages/services/test/helpers.ts` to assert the audit side-effect. Each suite scopes to its own workspace and clears `audit_log` between cases.
-When adding a router endpoint, the default answer is "write the service verb first, then call it from the router." Inline DB access in routers is a smell — it bypasses the audit log and the Edge-safety guarantee.
+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.
## Scope Enforcement (API key RBAC)
diff --git a/apps/dashboard/.env.example b/apps/dashboard/.env.example
index 538f94973..7795fea4d 100644
--- a/apps/dashboard/.env.example
+++ b/apps/dashboard/.env.example
@@ -70,6 +70,12 @@ AUTH_OIDC_ID=
AUTH_OIDC_SECRET=
AUTH_OIDC_NAME=
+# Multi-tenant SAML SSO via WorkOS (cloud). Leave unset to hide SSO entirely.
+AUTH_WORKOS_ID=
+AUTH_WORKOS_SECRET=
+WORKOS_API_KEY=
+WORKOS_WEBHOOK_SECRET=
+
PAGERDUTY_APP_ID=
SLACK_SUPPORT_WEBHOOK_URL=
diff --git a/apps/dashboard/src/app/(dashboard)/settings/billing/client.tsx b/apps/dashboard/src/app/(dashboard)/settings/billing/client.tsx
index 7d35cd48b..0c86f1240 100644
--- a/apps/dashboard/src/app/(dashboard)/settings/billing/client.tsx
+++ b/apps/dashboard/src/app/(dashboard)/settings/billing/client.tsx
@@ -228,6 +228,14 @@ export function Client() {
workspace={workspace}
/>
) : null}
+ {planAddons.sso ? (
+ <BillingAddons
+ label={planAddons.sso.title}
+ description={planAddons.sso.description}
+ addon="sso"
+ workspace={workspace}
+ />
+ ) : null}
{Object.keys(planAddons).length === 0 ? (
<EmptyStateContainer>
<EmptyStateTitle>No add-ons available</EmptyStateTitle>
diff --git a/apps/dashboard/src/app/(dashboard)/settings/sso/breadcrumb.tsx b/apps/dashboard/src/app/(dashboard)/settings/sso/breadcrumb.tsx
new file mode 100644
index 000000000..0301e03fb
--- /dev/null
+++ b/apps/dashboard/src/app/(dashboard)/settings/sso/breadcrumb.tsx
@@ -0,0 +1,21 @@
+"use client";
+
+import { Settings, Shield } from "@openstatus/icons";
+
+import { NavBreadcrumb } from "@/components/nav/nav-breadcrumb";
+
+export function Breadcrumb() {
+ return (
+ <NavBreadcrumb
+ items={[
+ {
+ type: "link",
+ label: "Settings",
+ icon: Settings,
+ href: "/settings/general",
+ },
+ { type: "page", label: "SSO", icon: Shield },
+ ]}
+ />
+ );
+}
diff --git a/apps/dashboard/src/app/(dashboard)/settings/sso/layout.tsx b/apps/dashboard/src/app/(dashboard)/settings/sso/layout.tsx
new file mode 100644
index 000000000..36b8d7cb4
--- /dev/null
+++ b/apps/dashboard/src/app/(dashboard)/settings/sso/layout.tsx
@@ -0,0 +1,38 @@
+import {
+ AppHeader,
+ AppHeaderActions,
+ AppHeaderContent,
+} from "@/components/nav/app-header";
+import { AppSidebarTrigger } from "@/components/nav/app-sidebar";
+import { HydrateClient, getQueryClient, trpc } from "@/lib/trpc/server";
+
+import { Tabs } from "../tabs";
+import { Breadcrumb } from "./breadcrumb";
+import { NavActions } from "./nav-actions";
+
+export default async function Layout({
+ children,
+}: {
+ children: React.ReactNode;
+}) {
+ const queryClient = getQueryClient();
+ await queryClient.prefetchQuery(trpc.workspace.get.queryOptions());
+
+ return (
+ <HydrateClient>
+ <div>
+ <AppHeader>
+ <AppHeaderContent>
+ <AppSidebarTrigger />
+ <Breadcrumb />
+ </AppHeaderContent>
+ <AppHeaderActions>
+ <NavActions />
+ </AppHeaderActions>
+ </AppHeader>
+ <Tabs />
+ <main className="w-full flex-1">{children}</main>
+ </div>
+ </HydrateClient>
+ );
+}
diff --git a/apps/dashboard/src/app/(dashboard)/settings/sso/nav-actions.tsx b/apps/dashboard/src/app/(dashboard)/settings/sso/nav-actions.tsx
new file mode 100644
index 000000000..a47a85970
--- /dev/null
+++ b/apps/dashboard/src/app/(dashboard)/settings/sso/nav-actions.tsx
@@ -0,0 +1,11 @@
+"use client";
+
+import { NavFeedback } from "@/components/nav/nav-feedback";
+
+export function NavActions() {
+ return (
+ <div className="flex items-center gap-2 text-sm">
+ <NavFeedback />
+ </div>
+ );
+}
diff --git a/apps/dashboard/src/app/(dashboard)/settings/sso/page.tsx b/apps/dashboard/src/app/(dashboard)/settings/sso/page.tsx
new file mode 100644
index 000000000..a1bd5c4f8
--- /dev/null
+++ b/apps/dashboard/src/app/(dashboard)/settings/sso/page.tsx
@@ -0,0 +1,320 @@
+"use client";
+
+import { allPlans } from "@openstatus/db/src/schema/plan/config";
+import { Check, Shield } from "@openstatus/icons";
+import { Badge } from "@openstatus/ui/components/ui/badge";
+import { Button } from "@openstatus/ui/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@openstatus/ui/components/ui/dialog";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { useState } from "react";
+import { toast } from "sonner";
+
+import {
+ Section,
+ SectionDescription,
+ SectionGroup,
+ SectionHeader,
+ SectionTitle,
+} from "@/components/content/section";
+import { UpgradeDialog } from "@/components/dialogs/upgrade";
+import {
+ FormCard,
+ FormCardContent,
+ FormCardDescription,
+ FormCardFooter,
+ FormCardFooterInfo,
+ FormCardGroup,
+ FormCardHeader,
+ FormCardTitle,
+} from "@/components/forms/form-card";
+import { useTRPC } from "@/lib/trpc/client";
+
+const RETURN_PATH = "/settings/sso";
+
+function StepBadge({ done, index }: { done: boolean; index: number }) {
+ return (
+ <Badge variant={done ? "default" : "outline"} className="size-6 p-0">
+ {done ? <Check className="size-3" /> : index}
+ </Badge>
+ );
+}
+
+export default function Page() {
+ const trpc = useTRPC();
+ const queryClient = useQueryClient();
+ const [upgradeOpen, setUpgradeOpen] = useState(false);
+ const [disableOpen, setDisableOpen] = useState(false);
+
+ const { data: workspace } = useQuery(trpc.workspace.get.queryOptions());
+ const { data: user } = useQuery(trpc.user.get.queryOptions());
+ const { data: members } = useQuery(trpc.member.list.queryOptions());
+ const { data: sso, isPending } = useQuery(trpc.sso.get.queryOptions());
+
+ const invalidate = () =>
+ queryClient.invalidateQueries({ queryKey: trpc.sso.get.queryKey() });
+
+ const enableMutation = useMutation(
+ trpc.sso.enable.mutationOptions({
+ onSuccess: () => invalidate(),
+ onError: (error) => toast.error(error.message),
+ }),
+ );
+ const disableMutation = useMutation(
+ trpc.sso.disable.mutationOptions({
+ onSuccess: () => {
+ setDisableOpen(false);
+ invalidate();
+ },
+ onError: (error) => toast.error(error.message),
+ }),
+ );
+ const portalLinkMutation = useMutation(
+ trpc.sso.portalLink.mutationOptions({
+ onError: (error) => toast.error(error.message),
+ }),
+ );
+
+ if (!workspace || !user || !members) return null;
+
+ const isOwner =
+ members.find((member) => member.user.id === user.id)?.role === "owner";
+
+ if (!isOwner) {
+ return (
+ <SectionGroup>
+ <Section>
+ <SectionHeader>
+ <SectionTitle>Single Sign-On</SectionTitle>
+ <SectionDescription>
+ Only workspace owners can manage SSO.
+ </SectionDescription>
+ </SectionHeader>
+ </Section>
+ </SectionGroup>
+ );
+ }
+
+ const allowed = workspace.limits.sso;
+ // SSO is a paid add-on on every plan, never bundled — the free plan carries no
+ // addons at all, so those workspaces have to move up a plan before buying it.
+ const ssoAddon = allPlans[workspace.plan].addons.sso;
+
+ async function openPortal(intent: "sso" | "domain_verification") {
+ const result = await portalLinkMutation.mutateAsync({
+ intent,
+ returnUrl: `${window.location.origin}${RETURN_PATH}`,
+ });
+ if (result?.link) window.location.href = result.link;
+ }
+
+ const configured = Boolean(sso?.configured);
+ const hasVerifiedDomain = Boolean(
+ sso?.domains.some((entry) => entry.verifiedAt !== null),
+ );
+ const connectionActive = sso?.connection === "active";
+
+ return (
+ <SectionGroup>
+ <Section>
+ <SectionHeader>
+ <SectionTitle>Single Sign-On</SectionTitle>
+ <SectionDescription>
+ Let your team sign in through your identity provider with SAML.
+ GitHub and Google stay available for everyone.
+ </SectionDescription>
+ </SectionHeader>
+
+ {!allowed ? (
+ <FormCardGroup>
+ <FormCard>
+ <FormCardHeader>
+ <FormCardTitle>Available as an add-on</FormCardTitle>
+ <FormCardDescription>
+ {ssoAddon
+ ? "SAML single sign-on is a paid add-on for your plan."
+ : "SAML single sign-on is a paid add-on, available on any paid plan."}
+ </FormCardDescription>
+ </FormCardHeader>
+ <FormCardFooter>
+ <FormCardFooterInfo>
+ {ssoAddon
+ ? "Add it to connect Okta, Entra ID, or any SAML provider."
+ : "Upgrade to connect Okta, Entra ID, or any SAML provider."}
+ </FormCardFooterInfo>
+ <Button size="sm" onClick={() => setUpgradeOpen(true)}>
+ {ssoAddon ? "Add SSO" : "Upgrade"}
+ </Button>
+ </FormCardFooter>
+ </FormCard>
+ </FormCardGroup>
+ ) : (
+ <FormCardGroup>
+ <FormCard>
+ <FormCardHeader>
+ <FormCardTitle>
+ <span className="flex items-center gap-2">
+ <StepBadge done={configured} index={1} />
+ Enable SSO
+ </span>
+ </FormCardTitle>
+ <FormCardDescription>
+ Creates the organization that holds your connection and
+ domains.
+ </FormCardDescription>
+ </FormCardHeader>
+ <FormCardFooter>
+ <FormCardFooterInfo>
+ {configured
+ ? `Organization ${sso?.organizationId}`
+ : "Not enabled yet."}
+ </FormCardFooterInfo>
+ {configured ? (
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={() => setDisableOpen(true)}
+ >
+ Disable SSO
+ </Button>
+ ) : (
+ <Button
+ size="sm"
+ disabled={enableMutation.isPending || isPending}
+ onClick={() => enableMutation.mutate(undefined)}
+ >
+ Enable SSO
+ </Button>
+ )}
+ </FormCardFooter>
+ </FormCard>
+
+ <FormCard>
+ <FormCardHeader>
+ <FormCardTitle>
+ <span className="flex items-center gap-2">
+ <StepBadge done={hasVerifiedDomain} index={2} />
+ Verify your domain
+ </span>
+ </FormCardTitle>
+ <FormCardDescription>
+ Users can only sign in with SSO from a domain you have
+ verified.
+ </FormCardDescription>
+ </FormCardHeader>
+ <FormCardContent>
+ {sso?.domains.length ? (
+ <ul className="flex flex-col gap-2">
+ {sso.domains.map((entry) => (
+ <li
+ key={entry.domain}
+ className="flex items-center justify-between text-sm"
+ >
+ <span className="font-commit-mono">{entry.domain}</span>
+ <Badge
+ variant={entry.verifiedAt ? "default" : "outline"}
+ >
+ {entry.verifiedAt ? "Verified" : "Pending"}
+ </Badge>
+ </li>
+ ))}
+ </ul>
+ ) : (
+ <p className="text-muted-foreground text-sm">
+ No domains yet. Until one is verified, SSO sign-in will be
+ refused.
+ </p>
+ )}
+ </FormCardContent>
+ <FormCardFooter>
+ <FormCardFooterInfo>
+ Domain ownership is proven with a DNS record.
+ </FormCardFooterInfo>
+ <Button
+ size="sm"
+ variant="outline"
+ disabled={!configured || portalLinkMutation.isPending}
+ onClick={() => openPortal("domain_verification")}
+ >
+ Verify a domain
+ </Button>
+ </FormCardFooter>
+ </FormCard>
+
+ <FormCard>
+ <FormCardHeader>
+ <FormCardTitle>
+ <span className="flex items-center gap-2">
+ <StepBadge done={connectionActive} index={3} />
+ Connect your identity provider
+ </span>
+ </FormCardTitle>
+ <FormCardDescription>
+ Configure SAML in Okta, Entra ID, or any supported provider.
+ </FormCardDescription>
+ </FormCardHeader>
+ <FormCardFooter>
+ <FormCardFooterInfo>
+ {sso?.ready ? (
+ <span className="flex items-center gap-1">
+ <Shield className="size-3" />
+ Ready — your team can sign in with SSO.
+ </span>
+ ) : (
+ `Connection: ${sso?.connection ?? "none"}`
+ )}
+ </FormCardFooterInfo>
+ <Button
+ size="sm"
+ variant="outline"
+ disabled={!configured || portalLinkMutation.isPending}
+ onClick={() => openPortal("sso")}
+ >
+ Configure in WorkOS
+ </Button>
+ </FormCardFooter>
+ </FormCard>
+ </FormCardGroup>
+ )}
+ </Section>
+
+ <UpgradeDialog
+ open={upgradeOpen}
+ onOpenChange={setUpgradeOpen}
+ limit="sso"
+ />
+
+ <Dialog open={disableOpen} onOpenChange={setDisableOpen}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>Disable SSO?</DialogTitle>
+ <DialogDescription>
+ Your team will no longer be able to sign in through your identity
+ provider. Nobody loses access to the workspace — existing members
+ keep signing in with GitHub or Google, and your provider
+ configuration is kept so you can re-enable it later.
+ </DialogDescription>
+ </DialogHeader>
+ <DialogFooter>
+ <Button variant="outline" onClick={() => setDisableOpen(false)}>
+ Cancel
+ </Button>
+ <Button
+ variant="destructive"
+ disabled={disableMutation.isPending}
+ onClick={() => disableMutation.mutate(undefined)}
+ >
+ Disable SSO
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ </SectionGroup>
+ );
+}
diff --git a/apps/dashboard/src/app/api/sso/idp/route.ts b/apps/dashboard/src/app/api/sso/idp/route.ts
new file mode 100644
index 000000000..c2469a0b5
--- /dev/null
+++ b/apps/dashboard/src/app/api/sso/idp/route.ts
@@ -0,0 +1,68 @@
+import { db } from "@openstatus/db";
+import {
+ getWorkspaceByWorkosOrganization,
+ isWorkOSConfigured,
+ resolveWorkOS,
+} from "@openstatus/services/sso";
+import { cookies } from "next/headers";
+import type { NextRequest } from "next/server";
+import { NextResponse } from "next/server";
+
+import { signIn } from "@/lib/auth";
+import { SSO_ORG_COOKIE } from "@/lib/sso-cookie";
+
+function denied(req: NextRequest) {
+ const url = new URL("/login", req.nextUrl.origin);
+ url.searchParams.set("error", "AccessDenied");
+ return NextResponse.redirect(url);
+}
+
+/**
+ * Registered as the *default* redirect URI in WorkOS, which is only used for
+ * IdP-initiated logins — SP-initiated flows send their own `redirect_uri` and
+ * go straight to the Auth.js callback.
+ *
+ * IdP-initiated logins cannot traverse the Auth.js callback: it requires a PKCE
+ * cookie that only exists when the flow started here. WorkOS's guidance is to
+ * disable IdP-initiated SSO and restart as SP-initiated, which is what this
+ * route does.
+ */
+export async function GET(req: NextRequest) {
+ if (!isWorkOSConfigured()) return denied(req);
+
+ const error = req.nextUrl.searchParams.get("error");
+ const connectionId = req.nextUrl.searchParams.get("connection_id");
+ if (error !== "idp_initiated_sso_disabled" || !connectionId) {
+ return denied(req);
+ }
+
+ const connection = await resolveWorkOS(undefined)
+ .sso.getConnection(connectionId)
+ .catch(() => null);
+
+ const organizationId = connection?.organizationId;
+ if (!organizationId) return denied(req);
+
+ const workspace = await getWorkspaceByWorkosOrganization(
+ db,
+ organizationId,
+ ).catch(() => null);
+ if (!workspace?.ssoEnabled) return denied(req);
+
+ const cookieStore = await cookies();
+ cookieStore.set(SSO_ORG_COOKIE, organizationId, {
+ httpOnly: true,
+ secure: process.env.NODE_ENV === "production",
+ sameSite: "lax",
+ maxAge: 60 * 10,
+ path: "/",
+ });
+
+ await signIn(
+ "workos",
+ { redirectTo: "/overview" },
+ { organization: organizationId },
+ );
+
+ return denied(req);
+}
diff --git a/apps/dashboard/src/app/api/webhooks/workos/route.ts b/apps/dashboard/src/app/api/webhooks/workos/route.ts
new file mode 100644
index 000000000..d95d8b93a
--- /dev/null
+++ b/apps/dashboard/src/app/api/webhooks/workos/route.ts
@@ -0,0 +1,63 @@
+import { db } from "@openstatus/db";
+import type { ServiceContext } from "@openstatus/services";
+import { NotFoundError } from "@openstatus/services";
+import {
+ getWorkspaceByWorkosOrganization,
+ isWorkOSConfigured,
+ removeSsoDomain,
+ syncSsoDomain,
+ verifyWorkOSWebhook,
+} from "@openstatus/services/sso";
+import type { NextRequest } from "next/server";
+
+export async function POST(req: NextRequest) {
+ const secret = process.env.WORKOS_WEBHOOK_SECRET;
+ if (!isWorkOSConfigured() || !secret) {
+ return new Response("Not found", { status: 404 });
+ }
+
+ const sigHeader = req.headers.get("workos-signature");
+ if (!sigHeader) return new Response("No signature", { status: 400 });
+
+ const payload = await req.text();
+
+ const event = await verifyWorkOSWebhook({
+ payload,
+ sigHeader,
+ secret,
+ }).catch(() => null);
+
+ if (!event) return new Response("Invalid signature", { status: 400 });
+ if (event.type === "ignored") return new Response("OK", { status: 200 });
+
+ const { organizationId, domain } = event;
+
+ try {
+ const workspace = await getWorkspaceByWorkosOrganization(
+ db,
+ organizationId,
+ );
+ const ctx: ServiceContext = {
+ workspace,
+ actor: { type: "system", job: "workos-webhook" },
+ };
+
+ if (event.type === "domain.verified") {
+ await syncSsoDomain({
+ ctx,
+ input: { organizationId, domain, verifiedAt: new Date() },
+ });
+ } else {
+ await removeSsoDomain({ ctx, input: { organizationId, domain } });
+ }
+ } catch (error) {
+ // An organization with no mapped workspace is not worth retrying:
+ // acknowledge so WorkOS stops redelivering.
+ if (error instanceof NotFoundError) {
+ return new Response("OK", { status: 200 });
+ }
+ throw error;
+ }
+
+ return new Response("OK", { status: 200 });
+}
diff --git a/apps/dashboard/src/app/login/_components/actions.ts b/apps/dashboard/src/app/login/_components/actions.ts
index a90659b51..face7a3fc 100644
--- a/apps/dashboard/src/app/login/_components/actions.ts
+++ b/apps/dashboard/src/app/login/_components/actions.ts
@@ -1,6 +1,11 @@
"use server";
+import { getWorkspaceByVerifiedSsoDomain } from "@openstatus/services/sso";
+import { cookies, headers } from "next/headers";
+
import { signIn } from "@/lib/auth";
+import { ssoLookupRateLimit } from "@/lib/rate-limit/sso-lookup";
+import { SSO_ORG_COOKIE } from "@/lib/sso-cookie";
export async function signInWithResendAction(formData: FormData) {
try {
@@ -9,3 +14,50 @@ export async function signInWithResendAction(formData: FormData) {
console.error(e);
}
}
+
+export type SsoFormState = { error?: string };
+
+// Deliberately identical for "no such domain", "SSO disabled" and "rate
+// limited": a specific message would tell an unauthenticated caller which
+// companies use openstatus and which of them have SSO.
+const GENERIC_ERROR =
+ "We couldn't start SSO for that email. Try GitHub or Google.";
+
+export async function startSsoSignIn(
+ _prevState: SsoFormState,
+ formData: FormData,
+): Promise<SsoFormState> {
+ const email = String(formData.get("email") ?? "");
+ const redirectToRaw = String(formData.get("redirectTo") ?? "");
+ const redirectTo =
+ redirectToRaw.startsWith("/") && !redirectToRaw.startsWith("//")
+ ? redirectToRaw
+ : "/overview";
+
+ if (!email.includes("@")) return { error: GENERIC_ERROR };
+
+ const headerList = await headers();
+ const ip =
+ headerList.get("x-forwarded-for")?.split(",")[0]?.trim() ?? "unknown";
+ if (!(await ssoLookupRateLimit(ip))) return { error: GENERIC_ERROR };
+
+ const workspace = await getWorkspaceByVerifiedSsoDomain(email);
+ if (!workspace?.workosOrganizationId) return { error: GENERIC_ERROR };
+
+ const cookieStore = await cookies();
+ cookieStore.set(SSO_ORG_COOKIE, workspace.workosOrganizationId, {
+ httpOnly: true,
+ secure: process.env.NODE_ENV === "production",
+ sameSite: "lax",
+ maxAge: 60 * 10,
+ path: "/",
+ });
+
+ await signIn(
+ "workos",
+ { redirectTo },
+ { organization: workspace.workosOrganizationId },
+ );
+
+ return {};
+}
diff --git a/apps/dashboard/src/app/login/_components/sso-form.tsx b/apps/dashboard/src/app/login/_components/sso-form.tsx
new file mode 100644
index 000000000..d63e2f923
--- /dev/null
+++ b/apps/dashboard/src/app/login/_components/sso-form.tsx
@@ -0,0 +1,51 @@
+"use client";
+
+import { Button } from "@openstatus/ui/components/ui/button";
+import { Input } from "@openstatus/ui/components/ui/input";
+import { useActionState, useState } from "react";
+
+import { type SsoFormState, startSsoSignIn } from "./actions";
+import { LoginButton } from "./login-button";
+
+const initialState: SsoFormState = {};
+
+export function SsoForm({ redirectTo }: { redirectTo?: string }) {
+ const [expanded, setExpanded] = useState(false);
+ const [state, formAction, isPending] = useActionState(
+ startSsoSignIn,
+ initialState,
+ );
+
+ if (!expanded) {
+ return (
+ <LoginButton
+ type="button"
+ provider="oidc"
+ onClick={() => setExpanded(true)}
+ >
+ Sign in with SSO
+ </LoginButton>
+ );
+ }
+
+ return (
+ <form action={formAction} className="grid w-full gap-2">
+ <input type="hidden" name="redirectTo" value={redirectTo ?? ""} />
+ <Input
+ name="email"
+ type="email"
+ required
+ autoFocus
+ placeholder="[email protected]"
+ aria-label="Work email"
+ aria-invalid={state.error ? true : undefined}
+ />
+ {state.error ? (
+ <p className="text-destructive text-xs">{state.error}</p>
+ ) : null}
+ <Button type="submit" disabled={isPending} className="w-full">
+ {isPending ? "Redirecting…" : "Continue with SSO"}
+ </Button>
+ </form>
+ );
+}
diff --git a/apps/dashboard/src/app/login/page.tsx b/apps/dashboard/src/app/login/page.tsx
index 1a8f0fce2..51d6b14fc 100644
--- a/apps/dashboard/src/app/login/page.tsx
+++ b/apps/dashboard/src/app/login/page.tsx
@@ -9,8 +9,13 @@ import { signIn } from "@/lib/auth";
import { LoginButton } from "./_components/login-button";
import MagicLinkForm from "./_components/magic-link-form";
+import { SsoForm } from "./_components/sso-form";
import { searchParamsCache } from "./search-params";
+const hasWorkOS = Boolean(
+ process.env.AUTH_WORKOS_ID && process.env.AUTH_WORKOS_SECRET,
+);
+
export const metadata: Metadata = {
title: "Sign In",
description:
@@ -28,7 +33,7 @@ export default async function Page(props: {
searchParams: Promise<SearchParams>;
}) {
const searchParams = await props.searchParams;
- const { redirectTo } = searchParamsCache.parse(searchParams);
+ const { redirectTo, error } = searchParamsCache.parse(searchParams);
return (
<div className="my-16 grid w-full max-w-lg gap-6">
@@ -38,6 +43,12 @@ export default async function Page(props: {
Get started now. No credit card required.
</p>
</div>
+ {error === "AccessDenied" ? (
+ <p className="text-destructive mx-auto max-w-md px-8 text-center text-sm text-pretty">
+ Your SSO login isn&apos;t linked to a workspace yet. Contact your
+ workspace admin.
+ </p>
+ ) : null}
<div className="grid gap-4 p-4">
{process.env.NODE_ENV === "development" ||
process.env.SELF_HOST === "true" ? (
@@ -81,6 +92,7 @@ export default async function Page(props: {
</LoginButton>
</form>
) : null}
+ {hasWorkOS ? <SsoForm redirectTo={redirectTo ?? undefined} /> : null}
</div>
<p className="text-muted-foreground mx-auto max-w-md px-8 text-center text-xs text-pretty">
By clicking continue, you agree to our{" "}
diff --git a/apps/dashboard/src/app/login/search-params.ts b/apps/dashboard/src/app/login/search-params.ts
index 474d2ffa5..52017afcf 100644
--- a/apps/dashboard/src/app/login/search-params.ts
+++ b/apps/dashboard/src/app/login/search-params.ts
@@ -2,6 +2,7 @@ import { createSearchParamsCache, parseAsString } from "nuqs/server";
export const searchParamsParsers = {
redirectTo: parseAsString,
+ error: parseAsString,
};
export const searchParamsCache = createSearchParamsCache(searchParamsParsers);
diff --git a/apps/dashboard/src/components/data-table/settings/members/data-table.tsx b/apps/dashboard/src/components/data-table/settings/members/data-table.tsx
index 1950d1b05..058ec2a55 100644
--- a/apps/dashboard/src/components/data-table/settings/members/data-table.tsx
+++ b/apps/dashboard/src/components/data-table/settings/members/data-table.tsx
@@ -15,6 +15,7 @@ import { useTRPC } from "@/lib/trpc/client";
export function DataTable() {
const trpc = useTRPC();
const { data: members, refetch } = useQuery(trpc.member.list.queryOptions());
+ const { data: workspace } = useQuery(trpc.workspace.get.queryOptions());
const deleteMemberMutation = useMutation(
trpc.member.delete.mutationOptions({
onSuccess: () => refetch(),
@@ -54,6 +55,9 @@ export function DataTable() {
<QuickActions
deleteAction={{
confirmationValue: item.user.email ?? "user",
+ description: workspace?.ssoEnabled
+ ? "This workspace uses SSO. They can sign in again and rejoin automatically unless you also remove them from your identity provider."
+ : undefined,
// FIXME: when deleting myself, throws an error, should have been caught by the toast.error
submitAction: async () =>
await deleteMemberMutation.mutateAsync({
diff --git a/apps/dashboard/src/components/dropdowns/quick-actions.tsx b/apps/dashboard/src/components/dropdowns/quick-actions.tsx
index 38bec9345..f1dc26b14 100644
--- a/apps/dashboard/src/components/dropdowns/quick-actions.tsx
+++ b/apps/dashboard/src/components/dropdowns/quick-actions.tsx
@@ -46,6 +46,7 @@ interface QuickActionsProps extends React.ComponentProps<typeof Button> {
* If omitted, no type-to-confirm step is shown.
*/
confirmationValue?: string;
+ description?: React.ReactNode;
submitAction?: () => Promise<void>;
};
}
@@ -152,8 +153,8 @@ export function QuickActions({
: "Are you sure?"}
</AlertDialogTitle>
<AlertDialogDescription>
- This action cannot be undone. This will permanently remove the entry
- from the database.
+ {deleteAction?.description ??
+ "This action cannot be undone. This will permanently remove the entry from the database."}
</AlertDialogDescription>
</AlertDialogHeader>
{deleteAction?.confirmationValue ? (
diff --git a/apps/dashboard/src/config/settings.ts b/apps/dashboard/src/config/settings.ts
index 4d591cb20..78b629188 100644
--- a/apps/dashboard/src/config/settings.ts
+++ b/apps/dashboard/src/config/settings.ts
@@ -6,6 +6,7 @@ import {
type IconType,
Integrations,
Settings,
+ Shield,
} from "@openstatus/icons";
export type SettingsTab = {
@@ -53,6 +54,13 @@ export const SETTINGS_TABS = [
href: "/settings/private-locations",
keywords: ["probes", "regions"],
},
+ {
+ value: "sso",
+ label: "SSO",
+ icon: Shield,
+ href: "/settings/sso",
+ keywords: ["saml", "single sign-on", "okta", "identity"],
+ },
{
value: "audit-logs",
label: "Audit Logs",
diff --git a/apps/dashboard/src/data/plans.ts b/apps/dashboard/src/data/plans.ts
index 06adcf0cc..72a27bc18 100644
--- a/apps/dashboard/src/data/plans.ts
+++ b/apps/dashboard/src/data/plans.ts
@@ -150,6 +150,10 @@ export const config: Record<
value: "audit-log",
label: "Audit log",
},
+ {
+ value: "sso",
+ label: "SAML single sign-on",
+ },
],
},
};
diff --git a/apps/dashboard/src/lib/auth/index.ts b/apps/dashboard/src/lib/auth/index.ts
index 8a46f4f2f..169e69dc6 100644
--- a/apps/dashboard/src/lib/auth/index.ts
+++ b/apps/dashboard/src/lib/auth/index.ts
@@ -12,7 +12,17 @@ import {
GoogleProvider,
OIDCProvider,
ResendProvider,
+ WorkOSProvider,
} from "./providers";
+import {
+ authorizeSsoSignIn,
+ joinWorkspaceViaSso,
+ readWorkOSProfile,
+} from "./sso";
+
+const hasWorkOS = Boolean(
+ process.env.AUTH_WORKOS_ID && process.env.AUTH_WORKOS_SECRET,
+);
export type { DefaultSession };
@@ -39,6 +49,7 @@ export const { handlers, signIn, signOut, auth } = NextAuth({
GitHubProvider,
GoogleProvider,
...(process.env.AUTH_OIDC_ISSUER ? [OIDCProvider] : []),
+ ...(hasWorkOS ? [WorkOSProvider] : []),
...(process.env.NODE_ENV === "development" ||
process.env.SELF_HOST === "true"
? [ResendProvider]
@@ -107,6 +118,10 @@ export const { handlers, signIn, signOut, auth } = NextAuth({
});
}
+ if (params.account?.provider === "workos") {
+ return authorizeSsoSignIn(readWorkOSProfile(params.profile));
+ }
+
// REMINDER: only used in dev mode
if (params.account?.provider === "resend") {
if (Number.isNaN(Number(params.user.id))) return true;
@@ -151,6 +166,16 @@ export const { handlers, signIn, signOut, auth } = NextAuth({
},
async signIn(params) {
+ if (params.account?.provider === "workos") {
+ const { organization_id: organizationId } = readWorkOSProfile(
+ params.profile,
+ );
+ const userId = Number(params.user.id);
+ if (organizationId && !Number.isNaN(userId)) {
+ await joinWorkspaceViaSso({ organizationId, userId });
+ }
+ }
+
if (params.isNewUser) return;
if (!params.user.id || !params.user.email) return;
diff --git a/apps/dashboard/src/lib/auth/providers.ts b/apps/dashboard/src/lib/auth/providers.ts
index 7ad88a9f2..d25b5d1c2 100644
--- a/apps/dashboard/src/lib/auth/providers.ts
+++ b/apps/dashboard/src/lib/auth/providers.ts
@@ -3,6 +3,7 @@ import type { OIDCConfig } from "next-auth/providers";
import GitHub from "next-auth/providers/github";
import Google from "next-auth/providers/google";
import Resend from "next-auth/providers/resend";
+import WorkOS from "next-auth/providers/workos";
export const GitHubProvider = GitHub({
allowDangerousEmailAccountLinking: true,
@@ -29,6 +30,16 @@ export const OIDCProvider: OIDCConfig<Profile> = {
clientSecret: process.env.AUTH_OIDC_SECRET,
};
+// The stock provider bakes an empty `connection=` into the authorize URL, and
+// WorkOS requires exactly one of connection/organization/provider — so the
+// empty one collides with the per-request `organization` we pass at signIn.
+export const WorkOSProvider = WorkOS({
+ clientId: process.env.AUTH_WORKOS_ID,
+ clientSecret: process.env.AUTH_WORKOS_SECRET,
+ authorization: { url: "https://api.workos.com/sso/authorize", params: {} },
+ allowDangerousEmailAccountLinking: true,
+});
+
export const ResendProvider = Resend({
apiKey: undefined, // REMINDER: keep undefined to avoid sending emails
async sendVerificationRequest(params) {
diff --git a/apps/dashboard/src/lib/auth/sso.ts b/apps/dashboard/src/lib/auth/sso.ts
new file mode 100644
index 000000000..7d7774be7
--- /dev/null
+++ b/apps/dashboard/src/lib/auth/sso.ts
@@ -0,0 +1,70 @@
+import { db } from "@openstatus/db";
+import {
+ getWorkspaceByWorkosOrganization,
+ isEmailAllowedForWorkspace,
+ joinSsoWorkspace,
+} from "@openstatus/services/sso";
+
+export type WorkOSSsoProfile = {
+ organization_id?: string;
+ email?: string;
+};
+
+export function readWorkOSProfile(profile: unknown): WorkOSSsoProfile {
+ if (typeof profile !== "object" || profile === null) return {};
+ const record: Record<string, unknown> = { ...profile };
+ return {
+ organization_id:
+ typeof record.organization_id === "string"
+ ? record.organization_id
+ : undefined,
+ email: typeof record.email === "string" ? record.email : undefined,
+ };
+}
+
+/**
+ * Authorize an SSO sign-in. The IdP controls the asserted email attribute, so
+ * an address outside the workspace's verified domains must never mint a
+ * session — otherwise one customer's IdP admin could reach any account.
+ */
+export async function authorizeSsoSignIn(
+ profile: WorkOSSsoProfile,
+): Promise<boolean> {
+ const { organization_id: organizationId, email } = profile;
+ if (!organizationId || !email) return false;
+
+ const workspace = await getWorkspaceByWorkosOrganization(
+ db,
+ organizationId,
+ ).catch(() => null);
+
+ if (!workspace || !workspace.ssoEnabled) return false;
+
+ return isEmailAllowedForWorkspace(workspace.id, email, db);
+}
+
+/**
+ * Add the user to the SSO workspace. Runs from `events.signIn`, the first point
+ * where `user.id` is a real row id.
+ *
+ * The organization is re-resolved here rather than carried over from the
+ * authorize step. The membership write itself lives in `joinSsoWorkspace` so it
+ * lands in the audit log; the actor is the signing-in user, matching how
+ * invitation acceptance attributes its own membership row.
+ */
+export async function joinWorkspaceViaSso(args: {
+ organizationId: string;
+ userId: number;
+}): Promise<void> {
+ const workspace = await getWorkspaceByWorkosOrganization(
+ db,
+ args.organizationId,
+ ).catch(() => null);
+
+ if (!workspace) return;
+
+ await joinSsoWorkspace({
+ ctx: { workspace, actor: { type: "user", userId: args.userId } },
+ input: { userId: args.userId },
+ });
+}
diff --git a/apps/dashboard/src/lib/rate-limit/sso-lookup.ts b/apps/dashboard/src/lib/rate-limit/sso-lookup.ts
new file mode 100644
index 000000000..81e988f6d
--- /dev/null
+++ b/apps/dashboard/src/lib/rate-limit/sso-lookup.ts
@@ -0,0 +1,33 @@
+import { redis } from "@openstatus/upstash";
+
+const WINDOW_SECONDS = 60 * 10;
+const MAX_ATTEMPTS = 10;
+
+// INCR + conditional EXPIRE in one round-trip so a crash between the two can't
+// leave a TTL-less key. Mirrors `rate-limit/chat.ts`.
+const INCR_WITH_TTL = `
+ local count = redis.call('INCR', KEYS[1])
+ if count == 1 then
+ redis.call('EXPIRE', KEYS[1], tonumber(ARGV[1]))
+ end
+ return count
+`;
+
+/**
+ * Throttle unauthenticated SSO domain lookups — without this the login form is
+ * a free oracle for enumerating which companies have SSO configured.
+ */
+export async function ssoLookupRateLimit(ip: string): Promise<boolean> {
+ try {
+ const count = await redis.eval<[number], number>(
+ INCR_WITH_TTL,
+ [`ratelimit:sso-lookup:${ip}`],
+ [WINDOW_SECONDS],
+ );
+ return count <= MAX_ATTEMPTS;
+ } catch {
+ // Redis unavailable: allow the lookup rather than locking everyone out of
+ // SSO. The verified-domain check downstream is the real security boundary.
+ return true;
+ }
+}
diff --git a/apps/dashboard/src/lib/sso-cookie.ts b/apps/dashboard/src/lib/sso-cookie.ts
new file mode 100644
index 000000000..810f66d75
--- /dev/null
+++ b/apps/dashboard/src/lib/sso-cookie.ts
@@ -0,0 +1,3 @@
+// Kept dependency-free: the proxy reads this constant, and importing it from
+// `lib/auth/sso` would pull the WorkOS SDK into the proxy bundle.
+export const SSO_ORG_COOKIE = "sso-org";
diff --git a/apps/dashboard/src/proxy.ts b/apps/dashboard/src/proxy.ts
index 1a00a9df0..9eaf567c6 100644
--- a/apps/dashboard/src/proxy.ts
+++ b/apps/dashboard/src/proxy.ts
@@ -1,9 +1,10 @@
-import { db, eq } from "@openstatus/db";
+import { asc, db, eq } from "@openstatus/db";
import { user, usersToWorkspaces, workspace } from "@openstatus/db/src/schema";
import { getCurrency } from "@openstatus/db/src/schema/plan/utils";
import { NextResponse } from "next/server";
import { auth } from "@/lib/auth";
+import { SSO_ORG_COOKIE } from "@/lib/sso-cookie";
import { WORKSPACE_SLUG_COOKIE } from "@/lib/workspace-cookie";
export default auth(async (req) => {
@@ -76,21 +77,34 @@ export default auth(async (req) => {
}
const hasWorkspaceSlug = req.cookies.has(WORKSPACE_SLUG_COOKIE);
+ const ssoOrg = req.cookies.get(SSO_ORG_COOKIE)?.value;
- if (req.auth?.user?.id && !hasWorkspaceSlug) {
- const [query] = await db
+ if (req.auth?.user?.id && (!hasWorkspaceSlug || ssoOrg)) {
+ const rows = await db
.select()
.from(usersToWorkspaces)
.innerJoin(user, eq(user.id, usersToWorkspaces.userId))
.innerJoin(workspace, eq(workspace.id, usersToWorkspaces.workspaceId))
.where(eq(user.id, Number.parseInt(req.auth.user.id)))
+ .orderBy(asc(usersToWorkspaces.createdAt))
.all();
+ // The cookie only *selects* among workspaces the user already belongs to —
+ // it can never grant access, so a forged value is inert.
+ const target = ssoOrg
+ ? rows.find((row) => row.workspace.workosOrganizationId === ssoOrg)
+ : undefined;
+ const query = target ?? rows[0];
+
if (!query) {
console.error(">> Should not happen, no workspace found for user");
+ } else if (target || !hasWorkspaceSlug) {
+ response.cookies.set(WORKSPACE_SLUG_COOKIE, query.workspace.slug);
}
+ }
- response.cookies.set(WORKSPACE_SLUG_COOKIE, query.workspace.slug);
+ if (ssoOrg) {
+ response.cookies.delete(SSO_ORG_COOKIE);
}
if (!req.auth && hasWorkspaceSlug) {
diff --git a/apps/web/src/content/docs.config.ts b/apps/web/src/content/docs.config.ts
index cb3e3112b..528f82c5e 100644
--- a/apps/web/src/content/docs.config.ts
+++ b/apps/web/src/content/docs.config.ts
@@ -168,6 +168,10 @@ export const docsNav: DocsNavSection[] = [
slug: "guides/how-to-deploy-probes-cloudflare-containers",
label: "How to Deploy a Private Probe on Cloudflare Containers",
},
+ {
+ slug: "guides/how-to-set-up-saml-sso",
+ label: "How to Set Up SAML Single Sign-On",
+ },
{
slug: "guides/self-hosting-openstatus",
label: "How to Self-Host openstatus",
diff --git a/apps/web/src/content/pages/docs/guides/how-to-set-up-saml-sso.mdx b/apps/web/src/content/pages/docs/guides/how-to-set-up-saml-sso.mdx
new file mode 100644
index 000000000..705cbf7a0
--- /dev/null
+++ b/apps/web/src/content/pages/docs/guides/how-to-set-up-saml-sso.mdx
@@ -0,0 +1,54 @@
+---
+category: Guides
+title: Set up SAML single sign-on
+description: "Let your team sign in to openstatus through Okta, Entra ID, or any SAML identity provider"
+---
+
+
+| | |
+|---|---|
+| **Time** | ~20 minutes, plus DNS propagation |
+| **Level** | Advanced |
+| **Prerequisites** | A workspace on the **Scale** plan, workspace **owner** access, and permission to add a DNS TXT record for your domain |
+
+SAML single sign-on lets your team sign in to openstatus through your own identity provider. GitHub and Google stay available — SSO is an additional way in, not a replacement.
+
+<Aside>SSO is available on the **Scale** plan. If your subscription ends, SSO is switched off automatically and your team keeps access through GitHub and Google. Your provider configuration is retained, so re-subscribing restores it without reconnecting.</Aside>
+
+## Step 1: enable SSO
+
+Go to **Settings → SSO** and select **Enable SSO**. This creates the organization that holds your connection and verified domains.
+
+Only workspace owners can see and manage this page.
+
+## Step 2: verify your domain
+
+Select **Verify a domain** and follow the steps to add the DNS TXT record you're given.
+
+This step is not optional. openstatus only allows an SSO sign-in when the email address your identity provider asserts belongs to a domain you have verified. Until at least one domain is verified, every SSO sign-in is refused — this is what stops another organisation's identity provider from asserting one of your users' email addresses.
+
+DNS changes can take a while to propagate. The domain shows as **Pending** until verification completes, then flips to **Verified** on its own.
+
+## Step 3: connect your identity provider
+
+Select **Configure in WorkOS** and follow the setup for your provider — Okta, Entra ID, Google Workspace, OneLogin, and generic SAML are all supported.
+
+When the connection goes live, the SSO page shows **Ready — your team can sign in with SSO**.
+
+## Signing in
+
+On the login page your team selects **Sign in with SSO** and enters their work email. The domain is matched against your verified domains and they're redirected to your identity provider.
+
+Users signing in this way are added to your workspace automatically as **members** on first login. Someone who already has an openstatus account with the same email keeps that account, along with any role they already hold — an existing owner stays an owner.
+
+Signing in from your identity provider's app tile also works.
+
+## Removing access
+
+Because membership is granted by your identity provider, removing someone from the openstatus workspace alone is not enough — they can sign in again and rejoin. Remove them in your identity provider.
+
+<Aside type="caution">SCIM directory sync is not supported yet, so deprovisioning is not automatic. Removing a user from your identity provider prevents future sign-ins, but does not remove their existing workspace membership.</Aside>
+
+## Turning SSO off
+
+**Disable SSO** on the settings page stops SSO sign-ins. Nobody loses access to the workspace and no memberships are removed — everyone continues with GitHub or Google.
diff --git a/apps/web/src/content/pages/unrelated/pricing.mdx b/apps/web/src/content/pages/unrelated/pricing.mdx
index dcf4582df..fddb736e6 100644
--- a/apps/web/src/content/pages/unrelated/pricing.mdx
+++ b/apps/web/src/content/pages/unrelated/pricing.mdx
@@ -71,6 +71,7 @@ faq:
| **Collaboration** | | | |
| Team members | Unlimited | Unlimited | Unlimited |
| Audit log | | + | + |
+| SSO/SAML | $250/mo. | $250/mo. | $250/mo. |
## Enterprise
diff --git a/packages/api/src/lambda.ts b/packages/api/src/lambda.ts
index 489a31052..a74efbfee 100644
--- a/packages/api/src/lambda.ts
+++ b/packages/api/src/lambda.ts
@@ -2,6 +2,7 @@ import { apiKeyRouter } from "./router/apiKey";
import { blobRouter } from "./router/blob";
import { emailRouter } from "./router/email";
import { integrationRouter } from "./router/integration";
+import { ssoRouter } from "./router/sso";
import { stripeRouter } from "./router/stripe";
import { subscriberNotificationRouter } from "./router/subscriber-notification";
import { createTRPCRouter } from "./trpc";
@@ -13,6 +14,7 @@ export const lambdaRouter = createTRPCRouter({
integrationRouter: integrationRouter,
blob: blobRouter,
subscriberNotification: subscriberNotificationRouter,
+ sso: ssoRouter,
});
export { stripe } from "./router/stripe/shared";
diff --git a/packages/api/src/router/sso.ts b/packages/api/src/router/sso.ts
new file mode 100644
index 000000000..e198707b9
--- /dev/null
+++ b/packages/api/src/router/sso.ts
@@ -0,0 +1,48 @@
+import {
+ CreateSsoPortalLinkInput,
+ createSsoPortalLink,
+ disableSso,
+ enableSso,
+ getSsoConfig,
+} from "@openstatus/services/sso";
+
+import { toServiceCtx, toTRPCError } from "../service-adapter";
+import { createTRPCRouter, protectedProcedure } from "../trpc";
+
+export const ssoRouter = createTRPCRouter({
+ get: protectedProcedure.query(async ({ ctx }) => {
+ try {
+ return await getSsoConfig({ ctx: toServiceCtx(ctx) });
+ } catch (err) {
+ toTRPCError(err);
+ }
+ }),
+
+ enable: protectedProcedure.mutation(async ({ ctx }) => {
+ try {
+ return await enableSso({ ctx: toServiceCtx(ctx) });
+ } catch (err) {
+ toTRPCError(err);
+ }
+ }),
+
+ disable: protectedProcedure.mutation(async ({ ctx }) => {
+ try {
+ await disableSso({ ctx: toServiceCtx(ctx) });
+ } catch (err) {
+ toTRPCError(err);
+ }
+ }),
+
+ // A mutation rather than a query: portal links expire five minutes after
+ // creation, so they must not be prefetched or cached.
+ portalLink: protectedProcedure
+ .input(CreateSsoPortalLinkInput)
+ .mutation(async ({ ctx, input }) => {
+ try {
+ return await createSsoPortalLink({ ctx: toServiceCtx(ctx), input });
+ } catch (err) {
+ toTRPCError(err);
+ }
+ }),
+});
diff --git a/packages/api/src/router/stripe/utils.ts b/packages/api/src/router/stripe/utils.ts
index 10031183f..5e0c410a7 100644
--- a/packages/api/src/router/stripe/utils.ts
+++ b/packages/api/src/router/stripe/utils.ts
@@ -201,6 +201,17 @@ export const FEATURES = [
},
},
},
+ {
+ feature: "sso",
+ price: {
+ monthly: {
+ priceIds: {
+ test: "price_1TySGYBXJcTfzsyJQFVFJi6N",
+ production: "price_1TySGYBXJcTfzsyJQFVFJi6N",
+ },
+ },
+ },
+ },
] satisfies Array<{
feature: keyof Addons;
price: {
diff --git a/packages/api/src/router/stripe/webhook.ts b/packages/api/src/router/stripe/webhook.ts
index c41d93b87..4367be2e0 100644
--- a/packages/api/src/router/stripe/webhook.ts
+++ b/packages/api/src/router/stripe/webhook.ts
@@ -1,6 +1,7 @@
import { Events, setupAnalytics } from "@openstatus/analytics";
-import { eq } from "@openstatus/db";
-import { user } from "@openstatus/db/src/schema";
+import { and, eq } from "@openstatus/db";
+import { user, usersToWorkspaces } from "@openstatus/db/src/schema";
+import { SsoDisabledEmail, sendEmail } from "@openstatus/emails";
import type { ServiceContext } from "@openstatus/services";
import {
downgradeWorkspaceToFree,
@@ -250,7 +251,42 @@ export const webhookRouter = createTRPCRouter({
db: opts.ctx.db,
};
- const { customDomains } = await downgradeWorkspaceToFree({ ctx });
+ const { customDomains, ssoDisabled } = await downgradeWorkspaceToFree({
+ ctx,
+ });
+
+ // Best-effort after commit: owners must know SSO stopped working, but a
+ // mail failure must not fail the webhook into Stripe retries.
+ if (ssoDisabled) {
+ try {
+ const owners = await opts.ctx.db
+ .select({ email: user.email })
+ .from(usersToWorkspaces)
+ .innerJoin(user, eq(user.id, usersToWorkspaces.userId))
+ .where(
+ and(
+ eq(usersToWorkspaces.workspaceId, ws.id),
+ eq(usersToWorkspaces.role, "owner"),
+ ),
+ )
+ .all();
+
+ const to = owners
+ .map((owner) => owner.email)
+ .filter((email): email is string => Boolean(email));
+
+ if (to.length > 0) {
+ await sendEmail({
+ from: "Thibault from OpenStatus <[email protected]>",
+ subject: "SSO has been disabled for your workspace",
+ to,
+ react: SsoDisabledEmail(),
+ });
+ }
+ } catch (err) {
+ console.error("Failed to notify owners about SSO being disabled:", err);
+ }
+ }
// Free plan has no custom-domain feature — release each domain on Vercel
// unless another workspace's page still holds it. Best-effort after
diff --git a/packages/db/drizzle/0083_wide_otto_octavius.sql b/packages/db/drizzle/0083_wide_otto_octavius.sql
new file mode 100644
index 000000000..3b761aedc
--- /dev/null
+++ b/packages/db/drizzle/0083_wide_otto_octavius.sql
@@ -0,0 +1,14 @@
+CREATE TABLE `workspace_sso_domain` (
+ `id` integer PRIMARY KEY NOT NULL,
+ `workspace_id` integer NOT NULL,
+ `domain` text NOT NULL,
+ `verified_at` integer,
+ `created_at` integer DEFAULT (strftime('%s', 'now')),
+ FOREIGN KEY (`workspace_id`) REFERENCES `workspace`(`id`) ON UPDATE no action ON DELETE cascade
+);
+--> statement-breakpoint
+CREATE UNIQUE INDEX `workspace_sso_domain_domain_unique` ON `workspace_sso_domain` (`domain`);--> statement-breakpoint
+CREATE INDEX `workspace_sso_domain_workspace_id_idx` ON `workspace_sso_domain` (`workspace_id`);--> statement-breakpoint
+ALTER TABLE `workspace` ADD `workos_organization_id` text;--> statement-breakpoint
+ALTER TABLE `workspace` ADD `sso_enabled` integer DEFAULT false NOT NULL;--> statement-breakpoint
+CREATE UNIQUE INDEX `workspace_workos_organization_id_unique` ON `workspace` (`workos_organization_id`);
\ No newline at end of file
diff --git a/packages/db/drizzle/meta/0083_snapshot.json b/packages/db/drizzle/meta/0083_snapshot.json
new file mode 100644
index 000000000..e830fb205
--- /dev/null
+++ b/packages/db/drizzle/meta/0083_snapshot.json
@@ -0,0 +1,4961 @@
+{
+ "version": "6",
+ "dialect": "sqlite",
+ "id": "6d3f5d66-7abe-46a6-bb0e-8db6c9f3b401",
+ "prevId": "caa00b22-b38f-4715-8522-f19de553d90a",
+ "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": "'{}'"
+ },
+ "workos_organization_id": {
+ "name": "workos_organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "sso_enabled": {
+ "name": "sso_enabled",
+ "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'))"
+ },
+ "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_workos_organization_id_unique": {
+ "name": "workspace_workos_organization_id_unique",
+ "columns": [
+ "workos_organization_id"
+ ],
+ "isUnique": true
+ },
+ "workspace_id_dsn_unique": {
+ "name": "workspace_id_dsn_unique",
+ "columns": [
+ "id",
+ "dsn"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "workspace_sso_domain": {
+ "name": "workspace_sso_domain",
+ "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
+ },
+ "domain": {
+ "name": "domain",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "verified_at": {
+ "name": "verified_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": {
+ "workspace_sso_domain_domain_unique": {
+ "name": "workspace_sso_domain_domain_unique",
+ "columns": [
+ "domain"
+ ],
+ "isUnique": true
+ },
+ "workspace_sso_domain_workspace_id_idx": {
+ "name": "workspace_sso_domain_workspace_id_idx",
+ "columns": [
+ "workspace_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "workspace_sso_domain_workspace_id_workspace_id_fk": {
+ "name": "workspace_sso_domain_workspace_id_workspace_id_fk",
+ "tableFrom": "workspace_sso_domain",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "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": {
+ "session_user_id_idx": {
+ "name": "session_user_id_idx",
+ "columns": [
+ "user_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "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
+ },
+ "user_email_idx": {
+ "name": "user_email_idx",
+ "columns": [
+ "email"
+ ],
+ "isUnique": false
+ }
+ },
+ "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'"
+ },
+ "custom_theme": {
+ "name": "custom_theme",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "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
+ },
+ "slack_channel_id": {
+ "name": "slack_channel_id",
+ "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": {
+ "page_subscriber_page_id_idx": {
+ "name": "page_subscriber_page_id_idx",
+ "columns": [
+ "page_id"
+ ],
+ "isUnique": false
+ },
+ "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'"
+ },
+ "idx_page_subscriber_slack_channel_page_active": {
+ "name": "idx_page_subscriber_slack_channel_page_active",
+ "columns": [
+ "slack_channel_id",
+ "page_id"
+ ],
+ "isUnique": true,
+ "where": "\"page_subscriber\".\"unsubscribed_at\" IS NULL AND \"page_subscriber\".\"channel_type\" = 'slack'"
+ }
+ },
+ "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) OR (\"page_subscriber\".\"channel_type\" = 'slack' AND \"page_subscriber\".\"slack_channel_id\" IS NOT NULL AND \"page_subscriber\".\"email\" IS NULL AND \"page_subscriber\".\"webhook_url\" 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_started_at_idx": {
+ "name": "incident_workspace_id_started_at_idx",
+ "columns": [
+ "workspace_id",
+ "started_at"
+ ],
+ "isUnique": false
+ },
+ "incident_open_idx": {
+ "name": "incident_open_idx",
+ "columns": [
+ "monitor_id"
+ ],
+ "isUnique": false,
+ "where": "\"incident\".\"resolved_at\" IS NULL"
+ },
+ "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_created_at_idx": {
+ "name": "monitor_run_workspace_id_created_at_idx",
+ "columns": [
+ "workspace_id",
+ "created_at"
+ ],
+ "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_monitor_status": {
+ "name": "private_location_monitor_status",
+ "columns": {
+ "monitor_id": {
+ "name": "monitor_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "private_location_id": {
+ "name": "private_location_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'active'"
+ },
+ "cron_timestamp": {
+ "name": "cron_timestamp",
+ "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": {
+ "private_location_monitor_status_pl_id_idx": {
+ "name": "private_location_monitor_status_pl_id_idx",
+ "columns": [
+ "private_location_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "private_location_monitor_status_monitor_id_monitor_id_fk": {
+ "name": "private_location_monitor_status_monitor_id_monitor_id_fk",
+ "tableFrom": "private_location_monitor_status",
+ "tableTo": "monitor",
+ "columnsFrom": [
+ "monitor_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "private_location_monitor_status_private_location_id_private_location_id_fk": {
+ "name": "private_location_monitor_status_private_location_id_private_location_id_fk",
+ "tableFrom": "private_location_monitor_status",
+ "tableTo": "private_location",
+ "columnsFrom": [
+ "private_location_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "private_location_monitor_status_monitor_id_private_location_id_pk": {
+ "columns": [
+ "monitor_id",
+ "private_location_id"
+ ],
+ "name": "private_location_monitor_status_monitor_id_private_location_id_pk"
+ }
+ },
+ "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
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'error'"
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "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_update_to_page_component": {
+ "name": "status_report_update_to_page_component",
+ "columns": {
+ "status_report_update_id": {
+ "name": "status_report_update_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "page_component_id": {
+ "name": "page_component_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "impact": {
+ "name": "impact",
+ "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'))"
+ }
+ },
+ "indexes": {
+ "status_report_update_to_page_component_page_component_id_idx": {
+ "name": "status_report_update_to_page_component_page_component_id_idx",
+ "columns": [
+ "page_component_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "status_report_update_to_page_component_status_report_update_id_status_report_update_id_fk": {
+ "name": "status_report_update_to_page_component_status_report_update_id_status_report_update_id_fk",
+ "tableFrom": "status_report_update_to_page_component",
+ "tableTo": "status_report_update",
+ "columnsFrom": [
+ "status_report_update_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "status_report_update_to_page_component_page_component_id_page_component_id_fk": {
+ "name": "status_report_update_to_page_component_page_component_id_page_component_id_fk",
+ "tableFrom": "status_report_update_to_page_component",
+ "tableTo": "page_component",
+ "columnsFrom": [
+ "page_component_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "status_report_update_to_page_component_status_report_update_id_page_component_id_pk": {
+ "columns": [
+ "status_report_update_id",
+ "page_component_id"
+ ],
+ "name": "status_report_update_to_page_component_status_report_update_id_page_component_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "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": {}
+ },
+ "external_service": {
+ "name": "external_service",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "slug": {
+ "name": "slug",
+ "type": "text(64)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "aliases": {
+ "name": "aliases",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(json_array())"
+ },
+ "name": {
+ "name": "name",
+ "type": "text(256)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "url": {
+ "name": "url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status_page_url": {
+ "name": "status_page_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "industry": {
+ "name": "industry",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "api_config": {
+ "name": "api_config",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "deleted_at": {
+ "name": "deleted_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": {
+ "external_service_slug_unique": {
+ "name": "external_service_slug_unique",
+ "columns": [
+ "slug"
+ ],
+ "isUnique": true
+ },
+ "external_service_deleted_at_idx": {
+ "name": "external_service_deleted_at_idx",
+ "columns": [
+ "deleted_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "external_service_component": {
+ "name": "external_service_component",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "external_service_id": {
+ "name": "external_service_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "upstream_component_id": {
+ "name": "upstream_component_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "slug": {
+ "name": "slug",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "aliases": {
+ "name": "aliases",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(json_array())"
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "group_name": {
+ "name": "group_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "position": {
+ "name": "position",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "indicator": {
+ "name": "indicator",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "first_seen_at": {
+ "name": "first_seen_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {
+ "external_service_component_unique_idx": {
+ "name": "external_service_component_unique_idx",
+ "columns": [
+ "external_service_id",
+ "upstream_component_id"
+ ],
+ "isUnique": true
+ },
+ "external_service_component_slug_unique_idx": {
+ "name": "external_service_component_slug_unique_idx",
+ "columns": [
+ "external_service_id",
+ "slug"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "external_service_component_external_service_id_external_service_id_fk": {
+ "name": "external_service_component_external_service_id_external_service_id_fk",
+ "tableFrom": "external_service_component",
+ "tableTo": "external_service",
+ "columnsFrom": [
+ "external_service_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "external_service_incident": {
+ "name": "external_service_incident",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "external_service_id": {
+ "name": "external_service_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "provider_incident_id": {
+ "name": "provider_incident_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "impact": {
+ "name": "impact",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "shortlink": {
+ "name": "shortlink",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "resolved_at": {
+ "name": "resolved_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "affected_component_ids": {
+ "name": "affected_component_ids",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "raw_payload": {
+ "name": "raw_payload",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "raw_payload_purged_at": {
+ "name": "raw_payload_purged_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "first_seen_at": {
+ "name": "first_seen_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {
+ "external_service_incident_unique_idx": {
+ "name": "external_service_incident_unique_idx",
+ "columns": [
+ "external_service_id",
+ "provider_incident_id"
+ ],
+ "isUnique": true
+ },
+ "external_service_incident_started_at_idx": {
+ "name": "external_service_incident_started_at_idx",
+ "columns": [
+ "external_service_id",
+ "started_at"
+ ],
+ "isUnique": false
+ },
+ "external_service_incident_resolved_at_idx": {
+ "name": "external_service_incident_resolved_at_idx",
+ "columns": [
+ "resolved_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "external_service_incident_external_service_id_external_service_id_fk": {
+ "name": "external_service_incident_external_service_id_external_service_id_fk",
+ "tableFrom": "external_service_incident",
+ "tableTo": "external_service",
+ "columnsFrom": [
+ "external_service_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "external_service_report": {
+ "name": "external_service_report",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "external_service_id": {
+ "name": "external_service_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "external_service_component_id": {
+ "name": "external_service_component_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "reporter_hash": {
+ "name": "reporter_hash",
+ "type": "text(64)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "country": {
+ "name": "country",
+ "type": "text(2)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {
+ "external_service_report_service_idx": {
+ "name": "external_service_report_service_idx",
+ "columns": [
+ "external_service_id",
+ "created_at"
+ ],
+ "isUnique": false
+ },
+ "external_service_report_component_idx": {
+ "name": "external_service_report_component_idx",
+ "columns": [
+ "external_service_component_id",
+ "created_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "external_service_report_external_service_id_external_service_id_fk": {
+ "name": "external_service_report_external_service_id_external_service_id_fk",
+ "tableFrom": "external_service_report",
+ "tableTo": "external_service",
+ "columnsFrom": [
+ "external_service_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "external_service_report_external_service_component_id_external_service_component_id_fk": {
+ "name": "external_service_report_external_service_component_id_external_service_component_id_fk",
+ "tableFrom": "external_service_report",
+ "tableTo": "external_service_component",
+ "columnsFrom": [
+ "external_service_component_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "chat_session": {
+ "name": "chat_session",
+ "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
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "messages": {
+ "name": "messages",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "chat_session_workspace_user_updated_idx": {
+ "name": "chat_session_workspace_user_updated_idx",
+ "columns": [
+ "workspace_id",
+ "user_id",
+ "updated_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "chat_session_workspace_id_workspace_id_fk": {
+ "name": "chat_session_workspace_id_workspace_id_fk",
+ "tableFrom": "chat_session",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "chat_session_user_id_user_id_fk": {
+ "name": "chat_session_user_id_user_id_fk",
+ "tableFrom": "chat_session",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "frozen_monitor_uptime": {
+ "name": "frozen_monitor_uptime",
+ "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
+ },
+ "monitor_id": {
+ "name": "monitor_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "month": {
+ "name": "month",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "days": {
+ "name": "days",
+ "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'))"
+ }
+ },
+ "indexes": {
+ "frozen_monitor_uptime_workspace_id_idx": {
+ "name": "frozen_monitor_uptime_workspace_id_idx",
+ "columns": [
+ "workspace_id"
+ ],
+ "isUnique": false
+ },
+ "frozen_monitor_uptime_monitor_id_month_unique": {
+ "name": "frozen_monitor_uptime_monitor_id_month_unique",
+ "columns": [
+ "monitor_id",
+ "month"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "frozen_monitor_uptime_workspace_id_workspace_id_fk": {
+ "name": "frozen_monitor_uptime_workspace_id_workspace_id_fk",
+ "tableFrom": "frozen_monitor_uptime",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "frozen_monitor_uptime_monitor_id_monitor_id_fk": {
+ "name": "frozen_monitor_uptime_monitor_id_monitor_id_fk",
+ "tableFrom": "frozen_monitor_uptime",
+ "tableTo": "monitor",
+ "columnsFrom": [
+ "monitor_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "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 file
diff --git a/packages/db/drizzle/meta/_journal.json b/packages/db/drizzle/meta/_journal.json
index 37d90431a..e586f1179 100644
--- a/packages/db/drizzle/meta/_journal.json
+++ b/packages/db/drizzle/meta/_journal.json
@@ -582,6 +582,13 @@
"when": 1785225964591,
"tag": "0082_cooing_karma",
"breakpoints": true
+ },
+ {
+ "idx": 83,
+ "version": "6",
+ "when": 1785227235369,
+ "tag": "0083_wide_otto_octavius",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/packages/db/src/schema/audit_logs/validation.ts b/packages/db/src/schema/audit_logs/validation.ts
index a2779e33e..aefc03d83 100644
--- a/packages/db/src/schema/audit_logs/validation.ts
+++ b/packages/db/src/schema/audit_logs/validation.ts
@@ -143,15 +143,19 @@ const invitationActions = [
// Several entities below carry only a subset of the create/update/delete
// triplet. This is intentional, not an oversight:
-// - `member`: rows are created via `invitation.accept`, not directly.
+// - `member`: invitation-driven joins are recorded as `invitation.update`
+// (the acceptance stamp), so `member.create` covers only the paths that
+// mint a membership with no invitation behind it — today, SSO JIT
+// provisioning.
// - `incident`: rows originate from the checker pipeline, not user
// mutations.
// When those write paths migrate to the service layer, add the missing
// verbs alongside.
const memberActions = [
- // `entityId` is the removed user's id. Member rows have no surrogate key —
+ // `entityId` is the affected user's id. Member rows have no surrogate key —
// they're (userId, workspaceId) composite — so the user id is the most
// useful identifier to fix on in the audit log.
+ action("member.create", "member", intId, { optionalMetadata: true }),
action("member.delete", "member", intId),
] as const;
@@ -179,6 +183,22 @@ const privateLocationActions = [
action("private_location.delete", "private_location", intId),
] as const;
+// `entityId` is the workspace id — SSO config has no surrogate key of its own.
+// Verified-domain rows fold into the same entity, distinguished by
+// `metadata.domain`; `delete` therefore means "a domain was dropped", never
+// "SSO was turned off" (that's an `update` on the `ssoEnabled` switch).
+const ssoActions = [
+ action("workspace_sso.create", "workspace_sso", intId, {
+ optionalMetadata: true,
+ }),
+ action("workspace_sso.update", "workspace_sso", intId, {
+ optionalMetadata: true,
+ }),
+ action("workspace_sso.delete", "workspace_sso", intId, {
+ optionalMetadata: true,
+ }),
+] as const;
+
export const auditActionSchema = z.discriminatedUnion("action", [
...monitorActions,
...pageActions,
@@ -198,6 +218,7 @@ export const auditActionSchema = z.discriminatedUnion("action", [
...integrationActions,
...monitorTagActions,
...privateLocationActions,
+ ...ssoActions,
]);
/**
diff --git a/packages/db/src/schema/plan/config.ts b/packages/db/src/schema/plan/config.ts
index 5dd321ff1..9dad7b549 100644
--- a/packages/db/src/schema/plan/config.ts
+++ b/packages/db/src/schema/plan/config.ts
@@ -64,6 +64,7 @@ export const allPlans: Record<WorkspacePlan, PlanConfig> = {
"notification-channels": 1,
members: 1,
"audit-log": false,
+ sso: false,
regions: [...FREE_FLY_REGIONS],
"private-locations": false,
"slack-agent": false,
@@ -121,6 +122,15 @@ export const allPlans: Record<WorkspacePlan, PlanConfig> = {
EUR: 20,
},
},
+ sso: {
+ title: "SAML Single Sign-On",
+ description:
+ "Let your team sign in through your identity provider with SAML SSO.",
+ price: {
+ USD: 250,
+ EUR: 250,
+ },
+ },
},
limits: {
version: undefined,
@@ -157,6 +167,7 @@ export const allPlans: Record<WorkspacePlan, PlanConfig> = {
"notification-channels": 10,
members: "Unlimited",
"audit-log": false,
+ sso: false,
regions: [...AVAILABLE_REGIONS],
"private-locations": false,
"slack-agent": true,
@@ -206,6 +217,15 @@ export const allPlans: Record<WorkspacePlan, PlanConfig> = {
EUR: 20,
},
},
+ sso: {
+ title: "SAML Single Sign-On",
+ description:
+ "Let your team sign in through your identity provider with SAML SSO.",
+ price: {
+ USD: 250,
+ EUR: 250,
+ },
+ },
},
limits: {
version: undefined,
@@ -242,6 +262,7 @@ export const allPlans: Record<WorkspacePlan, PlanConfig> = {
"notification-channels": 20,
members: "Unlimited",
"audit-log": true,
+ sso: false,
regions: [...AVAILABLE_REGIONS],
"private-locations": true,
"slack-agent": true,
@@ -264,6 +285,15 @@ export const allPlans: Record<WorkspacePlan, PlanConfig> = {
EUR: 20,
},
},
+ sso: {
+ title: "SAML Single Sign-On",
+ description:
+ "Let your team sign in through your identity provider with SAML SSO.",
+ price: {
+ USD: 250,
+ EUR: 250,
+ },
+ },
},
limits: {
version: undefined,
@@ -300,6 +330,7 @@ export const allPlans: Record<WorkspacePlan, PlanConfig> = {
"notification-channels": 20,
members: "Unlimited",
"audit-log": true,
+ sso: false,
regions: [...AVAILABLE_REGIONS],
"private-locations": true,
"slack-agent": true,
diff --git a/packages/db/src/schema/plan/schema.ts b/packages/db/src/schema/plan/schema.ts
index 386ffa73c..00050b375 100644
--- a/packages/db/src/schema/plan/schema.ts
+++ b/packages/db/src/schema/plan/schema.ts
@@ -59,6 +59,7 @@ export const limitsSchema = z.object({
*/
members: z.literal("Unlimited").or(z.number()).prefault(1),
"audit-log": z.boolean().prefault(false),
+ sso: z.boolean().prefault(false), // add-on but required in limits
/**
* Other limits
@@ -93,6 +94,7 @@ export const addons = [
"white-label",
"custom-theme",
"status-pages",
+ "sso",
] as const satisfies Partial<keyof Limits>[];
export const addonsSchema = z.partialRecord(
diff --git a/packages/db/src/schema/plan/utils.ts b/packages/db/src/schema/plan/utils.ts
index 610209c4a..3b4d9b8bb 100644
--- a/packages/db/src/schema/plan/utils.ts
+++ b/packages/db/src/schema/plan/utils.ts
@@ -96,9 +96,10 @@ export function getPlansForLimit(
return availablePlans.filter((plan) => {
const planLimitValue = allPlans[plan].limits[limit];
- // For boolean limits, only show plans where the feature is enabled
+ // For boolean limits, only show plans where the feature is enabled — either
+ // bundled or purchasable as an addon (e.g. SSO on every paid plan).
if (typeof currentLimitValue === "boolean") {
- return planLimitValue === true;
+ return planLimitValue === true || limit in allPlans[plan].addons;
}
// For numeric limits, show plans with higher values
diff --git a/packages/db/src/schema/workspaces/index.ts b/packages/db/src/schema/workspaces/index.ts
index 4a40d9955..c38146485 100644
--- a/packages/db/src/schema/workspaces/index.ts
+++ b/packages/db/src/schema/workspaces/index.ts
@@ -1,4 +1,5 @@
export * from "./constants";
export * from "./workspace";
+export * from "./sso_domain";
export * from "./validation";
export type * from "./validation";
diff --git a/packages/db/src/schema/workspaces/sso_domain.ts b/packages/db/src/schema/workspaces/sso_domain.ts
new file mode 100644
index 000000000..8d410fdf9
--- /dev/null
+++ b/packages/db/src/schema/workspaces/sso_domain.ts
@@ -0,0 +1,45 @@
+import { relations, sql } from "drizzle-orm";
+import { index, integer, sqliteTable, text } from "drizzle-orm/sqlite-core";
+import { createInsertSchema, createSelectSchema } from "drizzle-zod";
+import type { z } from "zod";
+
+import { workspace } from "./workspace";
+
+export const workspaceSsoDomain = sqliteTable(
+ "workspace_sso_domain",
+ {
+ id: integer("id").primaryKey(),
+ workspaceId: integer("workspace_id")
+ .notNull()
+ .references(() => workspace.id, { onDelete: "cascade" }),
+ // Globally unique: two workspaces claiming the same domain would make the
+ // login-time lookup ambiguous, which is an account-takeover vector.
+ domain: text("domain").notNull().unique(),
+ // Only ever written from the `organization_domain.verified` webhook.
+ verifiedAt: integer("verified_at", { mode: "timestamp" }),
+ createdAt: integer("created_at", { mode: "timestamp" }).default(
+ sql`(strftime('%s', 'now'))`,
+ ),
+ },
+ (t) => [index("workspace_sso_domain_workspace_id_idx").on(t.workspaceId)],
+);
+
+export const workspaceSsoDomainRelations = relations(
+ workspaceSsoDomain,
+ ({ one }) => ({
+ workspace: one(workspace, {
+ fields: [workspaceSsoDomain.workspaceId],
+ references: [workspace.id],
+ }),
+ }),
+);
+
+export const insertWorkspaceSsoDomainSchema =
+ createInsertSchema(workspaceSsoDomain);
+export const selectWorkspaceSsoDomainSchema =
+ createSelectSchema(workspaceSsoDomain);
+
+export type WorkspaceSsoDomain = z.infer<typeof selectWorkspaceSsoDomainSchema>;
+export type InsertWorkspaceSsoDomain = z.infer<
+ typeof insertWorkspaceSsoDomainSchema
+>;
diff --git a/packages/db/src/schema/workspaces/workspace.ts b/packages/db/src/schema/workspaces/workspace.ts
index e9269b8ea..e8413a328 100644
--- a/packages/db/src/schema/workspaces/workspace.ts
+++ b/packages/db/src/schema/workspaces/workspace.ts
@@ -7,6 +7,7 @@ import { page } from "../pages";
import { statusReport } from "../status_reports";
import { usersToWorkspaces } from "../users";
import { workspacePlans } from "./constants";
+import { workspaceSsoDomain } from "./sso_domain";
export const workspace = sqliteTable(
"workspace",
@@ -21,6 +22,14 @@ export const workspace = sqliteTable(
endsAt: integer("ends_at", { mode: "timestamp" }),
paidUntil: integer("paid_until", { mode: "timestamp" }),
limits: text("limits").default("{}").notNull(),
+
+ workosOrganizationId: text("workos_organization_id").unique(),
+ // Our own permission switch, never mirrored from WorkOS: the downgrade
+ // cascade clears it, and a later connection webhook must not resurrect it.
+ ssoEnabled: integer("sso_enabled", { mode: "boolean" })
+ .default(false)
+ .notNull(),
+
createdAt: integer("created_at", { mode: "timestamp" }).default(
sql`(strftime('%s', 'now'))`,
),
@@ -37,6 +46,7 @@ export const workspace = sqliteTable(
export const workspaceRelations = relations(workspace, ({ many }) => ({
usersToWorkspaces: many(usersToWorkspaces),
+ ssoDomains: many(workspaceSsoDomain),
pages: many(page),
monitors: many(monitor),
notifications: many(notification),
diff --git a/packages/emails/emails/sso-disabled.tsx b/packages/emails/emails/sso-disabled.tsx
new file mode 100644
index 000000000..a47d64845
--- /dev/null
+++ b/packages/emails/emails/sso-disabled.tsx
@@ -0,0 +1,41 @@
+/** @jsxRuntime automatic @jsxImportSource react */
+
+import { Body, Button, Head, Html, Preview, Text } from "react-email";
+
+import { Layout } from "./_components/layout";
+import { styles } from "./_components/styles";
+
+const SsoDisabledEmail = () => {
+ return (
+ <Html>
+ <Head />
+ <Preview>Single sign-on has been turned off for your workspace</Preview>
+ <Body style={styles.main}>
+ <Layout>
+ <Text>Hello 👋</Text>
+ <Text>
+ Your subscription ended, so SAML single sign-on has been turned off
+ for your workspace. SSO is part of the Scale plan.
+ </Text>
+ <Text>
+ Nobody has lost access — everyone can still sign in with GitHub or
+ Google. Your identity provider configuration has been kept, so
+ re-subscribing to Scale restores SSO without reconnecting it.
+ </Text>
+ <Text style={{ textAlign: "center" }}>
+ <Button
+ style={styles.button}
+ href="https://app.openstatus.dev/settings/billing"
+ >
+ View billing
+ </Button>
+ </Text>
+ <Text>If you have any questions, please reply to this email.</Text>
+ <Text>Thibault</Text>
+ </Layout>
+ </Body>
+ </Html>
+ );
+};
+
+export default SsoDisabledEmail;
diff --git a/packages/emails/src/index.ts b/packages/emails/src/index.ts
index b77c282c0..9573f28a7 100644
--- a/packages/emails/src/index.ts
+++ b/packages/emails/src/index.ts
@@ -9,6 +9,7 @@ export { default as MonitorPausedEmail } from "../emails/monitor-paused";
export { default as MonitorDeactivationEmail } from "../emails/monitor-deactivation";
export { default as PrivateLocationAlertEmail } from "../emails/private-location-alert";
export { default as StatusPageMagicLinkEmail } from "../emails/status-page-magic-link";
+export { default as SsoDisabledEmail } from "../emails/sso-disabled";
export { monitorDeactivationEmail } from "../hotfix/monitor-deactivation";
export { monitorPausedEmail } from "../hotfix/monitor-paused";
diff --git a/packages/services/package.json b/packages/services/package.json
index c353cc42d..676c26836 100644
--- a/packages/services/package.json
+++ b/packages/services/package.json
@@ -89,6 +89,10 @@
"import": "./src/member/index.ts",
"types": "./src/member/index.ts"
},
+ "./sso": {
+ "import": "./src/sso/index.ts",
+ "types": "./src/sso/index.ts"
+ },
"./monitor-tag": {
"import": "./src/monitor-tag/index.ts",
"types": "./src/monitor-tag/index.ts"
@@ -145,6 +149,7 @@
"@openstatus/theme-store": "workspace:*",
"@openstatus/tinybird": "workspace:*",
"@openstatus/utils": "workspace:*",
+ "@workos-inc/node": "catalog:",
"effect": "catalog:",
"zod": "catalog:"
},
diff --git a/packages/services/src/context.ts b/packages/services/src/context.ts
index 4ae3227e3..8a4bc6f4d 100644
--- a/packages/services/src/context.ts
+++ b/packages/services/src/context.ts
@@ -3,6 +3,7 @@ import type { Scope, Workspace } from "@openstatus/db/src/schema";
import { OSTinybird } from "@openstatus/tinybird";
import { withBusyRetry } from "./retry";
+import type { WorkOSClient } from "./sso/client";
// `@openstatus/db` does not export named DrizzleClient / DrizzleTx types today,
// so we derive them from the db export and re-export from here.
@@ -28,6 +29,7 @@ export type ServiceContext = {
span?: unknown;
db?: DB;
tb?: OSTinybird;
+ workos?: WorkOSClient;
};
// Fallback for callers with no app env to read from (scripts, tests). Request
diff --git a/packages/services/src/sso/__tests__/sso.test.ts b/packages/services/src/sso/__tests__/sso.test.ts
new file mode 100644
index 000000000..686f6fe0c
--- /dev/null
+++ b/packages/services/src/sso/__tests__/sso.test.ts
@@ -0,0 +1,681 @@
+import { and, eq } from "@openstatus/db";
+import {
+ usersToWorkspaces,
+ workspace,
+ workspaceSsoDomain,
+} from "@openstatus/db/src/schema";
+import {
+ addUserToWorkspace,
+ createUser,
+} from "@openstatus/db/src/test/factories";
+import { expect } from "@std/expect";
+import { beforeAll, describe, test } from "@std/testing/bdd";
+
+import {
+ createWorkspaceFixture,
+ expectAuditRow,
+ makeApiKeyCtx,
+ makeSystemCtx,
+ makeUserCtx,
+ readAuditLog,
+ withTestTransaction,
+} from "../../../test/helpers";
+import type { DB, ServiceContext } from "../../context";
+import { ForbiddenError, PreconditionFailedError } from "../../errors";
+import type { Workspace } from "../../types";
+import type { WorkOSClient } from "../client";
+import { disableSso } from "../disable";
+import { enableSso } from "../enable";
+import { joinSsoWorkspace } from "../join";
+import {
+ getWorkspaceByVerifiedSsoDomain,
+ isEmailAllowedForWorkspace,
+ normalizeSsoDomain,
+} from "../lookup";
+import { createSsoPortalLink } from "../portal-link";
+import {
+ reconcileSsoDomains,
+ removeSsoDomain,
+ syncSsoDomain,
+} from "../sync-domains";
+
+let scaleCtx: ServiceContext;
+let freeCtx: ServiceContext;
+let unpurchasedScale: { workspace: Workspace; userId: number };
+let SCALE_OWNER_ID: number;
+let SCALE_MEMBER_ID: number;
+
+function fakeWorkOS(
+ overrides: {
+ organizationId?: string;
+ domains?: { domain: string; state: string }[];
+ } = {},
+): WorkOSClient {
+ const organizationId = overrides.organizationId ?? "org_test_1";
+ return {
+ organizations: {
+ createOrganization: () => Promise.resolve({ id: organizationId }),
+ getOrganization: () =>
+ Promise.resolve({ domains: overrides.domains ?? [] }),
+ },
+ adminPortal: {
+ generateLink: () =>
+ Promise.resolve({ link: "https://portal.workos.test/abc" }),
+ },
+ sso: {
+ listConnections: () =>
+ Promise.resolve({ data: [{ state: "active" as const }] }),
+ getConnection: () => Promise.resolve({ organizationId }),
+ },
+ };
+}
+
+beforeAll(async () => {
+ // SSO is an add-on on every paid plan, not a bundled plan feature — the
+ // purchased flag lives as a workspace-level override on top of the plan.
+ const scale = await createWorkspaceFixture("scale", {
+ limits: JSON.stringify({ sso: true }),
+ });
+ SCALE_OWNER_ID = scale.userId;
+ scaleCtx = makeUserCtx(scale.workspace, { userId: SCALE_OWNER_ID });
+
+ const member = await createUser();
+ SCALE_MEMBER_ID = member.id;
+ await addUserToWorkspace(SCALE_MEMBER_ID, scale.workspace.id, "member");
+
+ freeCtx = makeUserCtx((await createWorkspaceFixture("free")).workspace, {
+ userId: (await createUser()).id,
+ });
+
+ unpurchasedScale = await createWorkspaceFixture("scale");
+});
+
+/** An owner-linked api key that only holds `read` — every write verb must refuse it. */
+function readOnlyCtx(): ServiceContext {
+ return makeApiKeyCtx(scaleCtx.workspace, {
+ keyId: "k",
+ userId: SCALE_OWNER_ID,
+ scopes: ["read"],
+ });
+}
+
+describe("enableSso", () => {
+ test("owner enables SSO on scale, org persisted, audit row written", async () => {
+ await withTestTransaction(async (tx) => {
+ const result = await enableSso({
+ ctx: { ...scaleCtx, db: tx, workos: fakeWorkOS() },
+ });
+
+ expect(result.organizationId).toBe("org_test_1");
+
+ const row = await tx
+ .select()
+ .from(workspace)
+ .where(eq(workspace.id, scaleCtx.workspace.id))
+ .get();
+ expect(row?.ssoEnabled).toBe(true);
+ expect(row?.workosOrganizationId).toBe("org_test_1");
+
+ await expectAuditRow({
+ workspaceId: scaleCtx.workspace.id,
+ action: "workspace_sso.create",
+ entityType: "workspace_sso",
+ entityId: scaleCtx.workspace.id,
+ db: tx,
+ });
+ });
+ });
+
+ test("rejects a workspace without the sso add-on", async () => {
+ await withTestTransaction(async (tx) => {
+ await expect(
+ enableSso({ ctx: { ...freeCtx, db: tx, workos: fakeWorkOS() } }),
+ ).rejects.toBeInstanceOf(PreconditionFailedError);
+ });
+ });
+
+ test("rejects a paid plan that has not purchased the add-on", async () => {
+ await withTestTransaction(async (tx) => {
+ const ctx = makeUserCtx(unpurchasedScale.workspace, {
+ userId: unpurchasedScale.userId,
+ });
+ await expect(
+ enableSso({ ctx: { ...ctx, db: tx, workos: fakeWorkOS() } }),
+ ).rejects.toBeInstanceOf(PreconditionFailedError);
+ });
+ });
+
+ test("rejects a non-owner member", async () => {
+ await withTestTransaction(async (tx) => {
+ const memberCtx = makeUserCtx(scaleCtx.workspace, {
+ userId: SCALE_MEMBER_ID,
+ });
+ await expect(
+ enableSso({ ctx: { ...memberCtx, db: tx, workos: fakeWorkOS() } }),
+ ).rejects.toBeInstanceOf(ForbiddenError);
+ });
+ });
+
+ test("rejects read-only actor", async () => {
+ await withTestTransaction(async (tx) => {
+ await expect(
+ enableSso({ ctx: { ...readOnlyCtx(), db: tx, workos: fakeWorkOS() } }),
+ ).rejects.toBeInstanceOf(ForbiddenError);
+ });
+ });
+
+ test("re-enabling reuses the existing organization", async () => {
+ await withTestTransaction(async (tx) => {
+ await enableSso({ ctx: { ...scaleCtx, db: tx, workos: fakeWorkOS() } });
+ await disableSso({ ctx: { ...scaleCtx, db: tx } });
+
+ const again = await enableSso({
+ ctx: {
+ ...scaleCtx,
+ db: tx,
+ workos: fakeWorkOS({ organizationId: "org_should_not_be_used" }),
+ },
+ });
+
+ expect(again.organizationId).toBe("org_test_1");
+ });
+ });
+});
+
+describe("disableSso", () => {
+ test("clears the switch but keeps memberships", async () => {
+ await withTestTransaction(async (tx) => {
+ await enableSso({ ctx: { ...scaleCtx, db: tx, workos: fakeWorkOS() } });
+ await disableSso({ ctx: { ...scaleCtx, db: tx } });
+
+ const row = await tx
+ .select()
+ .from(workspace)
+ .where(eq(workspace.id, scaleCtx.workspace.id))
+ .get();
+ expect(row?.ssoEnabled).toBe(false);
+ // The organization link survives so a re-upgrade keeps the IdP config.
+ expect(row?.workosOrganizationId).toBe("org_test_1");
+
+ const members = await tx.query.usersToWorkspaces.findMany({
+ where: (t, { eq: equals }) =>
+ equals(t.workspaceId, scaleCtx.workspace.id),
+ });
+ expect(members.length).toBeGreaterThanOrEqual(2);
+ });
+ });
+
+ test("is a no-op when already disabled", async () => {
+ await withTestTransaction(async (tx) => {
+ await disableSso({ ctx: { ...scaleCtx, db: tx } });
+ const row = await tx
+ .select()
+ .from(workspace)
+ .where(eq(workspace.id, scaleCtx.workspace.id))
+ .get();
+ expect(row?.ssoEnabled).toBe(false);
+ });
+ });
+
+ test("rejects read-only actor", async () => {
+ await withTestTransaction(async (tx) => {
+ await enableSso({ ctx: { ...scaleCtx, db: tx, workos: fakeWorkOS() } });
+
+ await expect(
+ disableSso({ ctx: { ...readOnlyCtx(), db: tx } }),
+ ).rejects.toBeInstanceOf(ForbiddenError);
+
+ const row = await tx
+ .select()
+ .from(workspace)
+ .where(eq(workspace.id, scaleCtx.workspace.id))
+ .get();
+ expect(row?.ssoEnabled).toBe(true);
+ });
+ });
+});
+
+describe("createSsoPortalLink", () => {
+ test("throws when SSO has not been set up", async () => {
+ await withTestTransaction(async (tx) => {
+ await expect(
+ createSsoPortalLink({
+ ctx: { ...scaleCtx, db: tx, workos: fakeWorkOS() },
+ input: { intent: "sso", returnUrl: "https://app.test/settings/sso" },
+ }),
+ ).rejects.toBeInstanceOf(PreconditionFailedError);
+ });
+ });
+
+ // A portal link is a capability to reconfigure the IdP, so it counts as a
+ // write even though the verb itself touches no row.
+ test("rejects read-only actor", async () => {
+ await withTestTransaction(async (tx) => {
+ await expect(
+ createSsoPortalLink({
+ ctx: { ...readOnlyCtx(), db: tx, workos: fakeWorkOS() },
+ input: { intent: "sso", returnUrl: "https://app.test/settings/sso" },
+ }),
+ ).rejects.toBeInstanceOf(ForbiddenError);
+ });
+ });
+});
+
+describe("syncSsoDomain", () => {
+ test("inserts a verified domain and is idempotent on replay", async () => {
+ await withTestTransaction(async (tx) => {
+ await enableSso({ ctx: { ...scaleCtx, db: tx, workos: fakeWorkOS() } });
+
+ const systemCtx = makeSystemCtx(scaleCtx.workspace, {
+ job: "workos-webhook",
+ });
+ const verifiedAt = new Date(1_700_000_000_000);
+
+ await syncSsoDomain({
+ ctx: { ...systemCtx, db: tx },
+ input: {
+ organizationId: "org_test_1",
+ domain: "acme.test",
+ verifiedAt,
+ },
+ });
+ await syncSsoDomain({
+ ctx: { ...systemCtx, db: tx },
+ input: {
+ organizationId: "org_test_1",
+ domain: "acme.test",
+ verifiedAt,
+ },
+ });
+
+ const rows = await tx
+ .select()
+ .from(workspaceSsoDomain)
+ .where(eq(workspaceSsoDomain.workspaceId, scaleCtx.workspace.id))
+ .all();
+ expect(rows.length).toBe(1);
+ expect(rows[0].verifiedAt?.getTime()).toBe(verifiedAt.getTime());
+ });
+ });
+
+ test("removeSsoDomain deletes the row", async () => {
+ await withTestTransaction(async (tx) => {
+ await enableSso({ ctx: { ...scaleCtx, db: tx, workos: fakeWorkOS() } });
+ const systemCtx = makeSystemCtx(scaleCtx.workspace, {
+ job: "workos-webhook",
+ });
+
+ await syncSsoDomain({
+ ctx: { ...systemCtx, db: tx },
+ input: {
+ organizationId: "org_test_1",
+ domain: "acme.test",
+ verifiedAt: new Date(),
+ },
+ });
+ await removeSsoDomain({
+ ctx: { ...systemCtx, db: tx },
+ input: { organizationId: "org_test_1", domain: "acme.test" },
+ });
+
+ const rows = await tx
+ .select()
+ .from(workspaceSsoDomain)
+ .where(eq(workspaceSsoDomain.workspaceId, scaleCtx.workspace.id))
+ .all();
+ expect(rows.length).toBe(0);
+
+ const [audited] = await readAuditLog({
+ workspaceId: scaleCtx.workspace.id,
+ entityType: "workspace_sso",
+ entityId: scaleCtx.workspace.id,
+ db: tx,
+ });
+ expect(audited?.action).toBe("workspace_sso.delete");
+ expect(audited?.metadata).toEqual({ domain: "acme.test" });
+ expect(audited?.after).toBe(null);
+ });
+ });
+
+ test("rejects read-only actor", async () => {
+ await withTestTransaction(async (tx) => {
+ await enableSso({ ctx: { ...scaleCtx, db: tx, workos: fakeWorkOS() } });
+
+ await expect(
+ syncSsoDomain({
+ ctx: { ...readOnlyCtx(), db: tx },
+ input: {
+ organizationId: "org_test_1",
+ domain: "acme.test",
+ verifiedAt: new Date(),
+ },
+ }),
+ ).rejects.toBeInstanceOf(ForbiddenError);
+
+ const rows = await tx
+ .select()
+ .from(workspaceSsoDomain)
+ .where(eq(workspaceSsoDomain.workspaceId, scaleCtx.workspace.id))
+ .all();
+ expect(rows.length).toBe(0);
+ });
+ });
+
+ test("removeSsoDomain rejects read-only actor", async () => {
+ await withTestTransaction(async (tx) => {
+ await enableSso({ ctx: { ...scaleCtx, db: tx, workos: fakeWorkOS() } });
+ const systemCtx = makeSystemCtx(scaleCtx.workspace, {
+ job: "workos-webhook",
+ });
+ await syncSsoDomain({
+ ctx: { ...systemCtx, db: tx },
+ input: {
+ organizationId: "org_test_1",
+ domain: "acme.test",
+ verifiedAt: new Date(),
+ },
+ });
+
+ await expect(
+ removeSsoDomain({
+ ctx: { ...readOnlyCtx(), db: tx },
+ input: { organizationId: "org_test_1", domain: "acme.test" },
+ }),
+ ).rejects.toBeInstanceOf(ForbiddenError);
+
+ const rows = await tx
+ .select()
+ .from(workspaceSsoDomain)
+ .where(eq(workspaceSsoDomain.workspaceId, scaleCtx.workspace.id))
+ .all();
+ expect(rows.length).toBe(1);
+ });
+ });
+});
+
+describe("reconcileSsoDomains", () => {
+ test("mirrors a domain the webhook never delivered", async () => {
+ await withTestTransaction(async (tx) => {
+ await enableSso({ ctx: { ...scaleCtx, db: tx, workos: fakeWorkOS() } });
+
+ const domains = await reconcileSsoDomains({
+ ctx: { ...scaleCtx, db: tx },
+ organizationId: "org_test_1",
+ workos: fakeWorkOS({
+ domains: [
+ { domain: "acme.test", state: "verified" },
+ { domain: "later.test", state: "pending" },
+ ],
+ }),
+ local: [],
+ });
+
+ expect(domains.length).toBe(2);
+ expect(
+ domains.find((entry) => entry.domain === "acme.test")?.verifiedAt,
+ ).toBeInstanceOf(Date);
+ expect(
+ domains.find((entry) => entry.domain === "later.test")?.verifiedAt,
+ ).toBe(null);
+
+ const allowed = await isEmailAllowedForWorkspace(
+ scaleCtx.workspace.id,
+ tx,
+ );
+ expect(allowed).toBe(true);
+ });
+ });
+
+ test("keeps the first verification timestamp and drops removed domains", async () => {
+ await withTestTransaction(async (tx) => {
+ await enableSso({ ctx: { ...scaleCtx, db: tx, workos: fakeWorkOS() } });
+ const verifiedAt = new Date(1_700_000_000_000);
+
+ await syncSsoDomain({
+ ctx: {
+ ...makeSystemCtx(scaleCtx.workspace, { job: "workos-webhook" }),
+ db: tx,
+ },
+ input: {
+ organizationId: "org_test_1",
+ domain: "acme.test",
+ verifiedAt,
+ },
+ });
+
+ const domains = await reconcileSsoDomains({
+ ctx: { ...scaleCtx, db: tx },
+ organizationId: "org_test_1",
+ workos: fakeWorkOS({
+ domains: [{ domain: "acme.test", state: "verified" }],
+ }),
+ local: [
+ { domain: "acme.test", verifiedAt },
+ { domain: "gone.test", verifiedAt },
+ ],
+ });
+
+ expect(domains.length).toBe(1);
+ expect(domains[0].domain).toBe("acme.test");
+ expect(domains[0].verifiedAt?.getTime()).toBe(verifiedAt.getTime());
+ });
+ });
+});
+
+describe("domain lookup", () => {
+ test("normalizeSsoDomain accepts an email or a bare domain", () => {
+ expect(normalizeSsoDomain("[email protected]")).toBe("acme.test");
+ expect(normalizeSsoDomain(" acme.test ")).toBe("acme.test");
+ expect(normalizeSsoDomain("")).toBe(null);
+ });
+
+ test("unverified domains never resolve", async () => {
+ await withTestTransaction(async (tx) => {
+ await enableSso({ ctx: { ...scaleCtx, db: tx, workos: fakeWorkOS() } });
+ const systemCtx = makeSystemCtx(scaleCtx.workspace, {
+ job: "workos-webhook",
+ });
+
+ await syncSsoDomain({
+ ctx: { ...systemCtx, db: tx },
+ input: {
+ organizationId: "org_test_1",
+ domain: "pending.test",
+ verifiedAt: null,
+ },
+ });
+
+ const found = await getWorkspaceByVerifiedSsoDomain(
+ tx,
+ );
+ expect(found).toBe(null);
+
+ const allowed = await isEmailAllowedForWorkspace(
+ scaleCtx.workspace.id,
+ tx,
+ );
+ expect(allowed).toBe(false);
+ });
+ });
+
+ test("verified domain resolves to the workspace and allows the email", async () => {
+ await withTestTransaction(async (tx) => {
+ await enableSso({ ctx: { ...scaleCtx, db: tx, workos: fakeWorkOS() } });
+ const systemCtx = makeSystemCtx(scaleCtx.workspace, {
+ job: "workos-webhook",
+ });
+
+ await syncSsoDomain({
+ ctx: { ...systemCtx, db: tx },
+ input: {
+ organizationId: "org_test_1",
+ domain: "acme.test",
+ verifiedAt: new Date(),
+ },
+ });
+
+ const found = await getWorkspaceByVerifiedSsoDomain("[email protected]", tx);
+ expect(found?.id).toBe(scaleCtx.workspace.id);
+
+ const allowed = await isEmailAllowedForWorkspace(
+ scaleCtx.workspace.id,
+ tx,
+ );
+ expect(allowed).toBe(true);
+
+ const foreign = await isEmailAllowedForWorkspace(
+ scaleCtx.workspace.id,
+ tx,
+ );
+ expect(foreign).toBe(false);
+ });
+ });
+
+ test("a disabled workspace does not resolve", async () => {
+ await withTestTransaction(async (tx) => {
+ await enableSso({ ctx: { ...scaleCtx, db: tx, workos: fakeWorkOS() } });
+ const systemCtx = makeSystemCtx(scaleCtx.workspace, {
+ job: "workos-webhook",
+ });
+ await syncSsoDomain({
+ ctx: { ...systemCtx, db: tx },
+ input: {
+ organizationId: "org_test_1",
+ domain: "acme.test",
+ verifiedAt: new Date(),
+ },
+ });
+ await disableSso({ ctx: { ...scaleCtx, db: tx } });
+
+ const found = await getWorkspaceByVerifiedSsoDomain("[email protected]", tx);
+ expect(found).toBe(null);
+ });
+ });
+});
+
+describe("joinSsoWorkspace", () => {
+ /** Flip the switch on the row itself — the verb reads the DB, not the ctx snapshot. */
+ function enableSsoOn(tx: DB) {
+ return enableSso({ ctx: { ...scaleCtx, db: tx, workos: fakeWorkOS() } });
+ }
+
+ function staleEnabledCtx(base: ServiceContext): ServiceContext {
+ return { ...base, workspace: { ...base.workspace, ssoEnabled: true } };
+ }
+
+ test("provisions the member and audits the join", async () => {
+ await withTestTransaction(async (tx) => {
+ // `createUser` writes on the default db — do it before the test tx takes
+ // a write lock, or the two deadlock.
+ const newcomer = await createUser();
+ await enableSsoOn(tx);
+ const ctx = makeUserCtx(scaleCtx.workspace, { userId: newcomer.id });
+
+ await joinSsoWorkspace({
+ ctx: { ...ctx, db: tx },
+ input: { userId: newcomer.id },
+ });
+
+ const membership = await tx.query.usersToWorkspaces.findFirst({
+ where: and(
+ eq(usersToWorkspaces.userId, newcomer.id),
+ eq(usersToWorkspaces.workspaceId, scaleCtx.workspace.id),
+ ),
+ });
+ expect(membership?.role).toBe("member");
+
+ await expectAuditRow({
+ workspaceId: scaleCtx.workspace.id,
+ action: "member.create",
+ entityType: "member",
+ entityId: newcomer.id,
+ actorType: "user",
+ db: tx,
+ });
+ });
+ });
+
+ test("a repeat login keeps the existing role and emits no second row", async () => {
+ await withTestTransaction(async (tx) => {
+ await enableSsoOn(tx);
+
+ await joinSsoWorkspace({
+ ctx: { ...scaleCtx, db: tx },
+ input: { userId: SCALE_OWNER_ID },
+ });
+
+ const membership = await tx.query.usersToWorkspaces.findFirst({
+ where: and(
+ eq(usersToWorkspaces.userId, SCALE_OWNER_ID),
+ eq(usersToWorkspaces.workspaceId, scaleCtx.workspace.id),
+ ),
+ });
+ expect(membership?.role).toBe("owner");
+
+ const rows = await readAuditLog({
+ workspaceId: scaleCtx.workspace.id,
+ entityType: "member",
+ entityId: SCALE_OWNER_ID,
+ db: tx,
+ });
+ expect(rows.length).toBe(0);
+ });
+ });
+
+ test("rejects a workspace with sso switched off", async () => {
+ await withTestTransaction(async (tx) => {
+ const newcomer = await createUser();
+ await expect(
+ joinSsoWorkspace({
+ ctx: { ...scaleCtx, db: tx },
+ input: { userId: newcomer.id },
+ }),
+ ).rejects.toBeInstanceOf(ForbiddenError);
+ });
+ });
+
+ test("a sign-in that overlaps disableSso does not provision", async () => {
+ await withTestTransaction(async (tx) => {
+ const newcomer = await createUser();
+ await enableSsoOn(tx);
+ // The ctx snapshot was taken while SSO was on; the owner turns it off
+ // before the callback lands.
+ const ctx = staleEnabledCtx(
+ makeUserCtx(scaleCtx.workspace, { userId: newcomer.id }),
+ );
+ await disableSso({ ctx: { ...scaleCtx, db: tx } });
+
+ await expect(
+ joinSsoWorkspace({
+ ctx: { ...ctx, db: tx },
+ input: { userId: newcomer.id },
+ }),
+ ).rejects.toBeInstanceOf(ForbiddenError);
+
+ const membership = await tx.query.usersToWorkspaces.findFirst({
+ where: and(
+ eq(usersToWorkspaces.userId, newcomer.id),
+ eq(usersToWorkspaces.workspaceId, scaleCtx.workspace.id),
+ ),
+ });
+ expect(membership).toBe(undefined);
+ });
+ });
+
+ test("rejects read-only actor", async () => {
+ await withTestTransaction(async (tx) => {
+ await enableSsoOn(tx);
+ await expect(
+ joinSsoWorkspace({
+ ctx: { ...readOnlyCtx(), db: tx },
+ input: { userId: SCALE_MEMBER_ID },
+ }),
+ ).rejects.toBeInstanceOf(ForbiddenError);
+ });
+ });
+});
diff --git a/packages/services/src/sso/client.ts b/packages/services/src/sso/client.ts
new file mode 100644
index 000000000..8d921e3d2
--- /dev/null
+++ b/packages/services/src/sso/client.ts
@@ -0,0 +1,66 @@
+import { WorkOS } from "@workos-inc/node";
+
+import { PreconditionFailedError } from "../errors";
+
+export type WorkOSConnectionState =
+ | "draft"
+ | "active"
+ | "inactive"
+ | "validating";
+
+/**
+ * Structural port covering only the calls we make. Defined by our needs rather
+ * than `Pick<WorkOS, …>` so tests can supply a plain object without casting
+ * past the SDK's class-private members.
+ */
+export type WorkOSClient = {
+ organizations: {
+ createOrganization(payload: { name: string }): Promise<{ id: string }>;
+ getOrganization(id: string): Promise<{
+ domains: { domain: string; state: string }[];
+ }>;
+ };
+ adminPortal: {
+ generateLink(options: {
+ intent: "sso" | "domain_verification";
+ organization: string;
+ returnUrl?: string;
+ }): Promise<{ link: string }>;
+ };
+ sso: {
+ listConnections(options: {
+ organizationId?: string;
+ limit?: number;
+ }): Promise<{ data: { state: WorkOSConnectionState }[] }>;
+ getConnection(id: string): Promise<{ organizationId?: string }>;
+ };
+};
+
+let cached: WorkOS | undefined;
+
+export function isWorkOSConfigured(): boolean {
+ return Boolean(process.env.WORKOS_API_KEY);
+}
+
+// Constructed lazily: instantiating at module scope would throw on boot for
+// self-hosted instances that never set WORKOS_API_KEY.
+export function getRawWorkOS(): WorkOS {
+ if (!cached) {
+ const apiKey = process.env.WORKOS_API_KEY;
+ if (!apiKey) {
+ throw new PreconditionFailedError(
+ "SSO is not configured on this instance",
+ );
+ }
+ cached = new WorkOS(apiKey, { clientId: process.env.AUTH_WORKOS_ID });
+ }
+ return cached;
+}
+
+export function getDefaultWorkOS(): WorkOSClient {
+ return getRawWorkOS();
+}
+
+export function resolveWorkOS(client: WorkOSClient | undefined): WorkOSClient {
+ return client ?? getDefaultWorkOS();
+}
diff --git a/packages/services/src/sso/disable.ts b/packages/services/src/sso/disable.ts
new file mode 100644
index 000000000..b5b7a5d76
--- /dev/null
+++ b/packages/services/src/sso/disable.ts
@@ -0,0 +1,52 @@
+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 { requireOwner } from "./internal";
+import { DisableSsoInput } from "./schemas";
+
+/**
+ * Turn SSO off for the workspace. Deliberately leaves `usersToWorkspaces`
+ * untouched — this is a configuration change, not deprovisioning, and members
+ * keep access through GitHub / Google.
+ */
+export async function disableSso(args: {
+ ctx: ServiceContext;
+ input?: DisableSsoInput;
+}): Promise<void> {
+ const { ctx } = args;
+ requireScope(ctx, "write");
+ const input = DisableSsoInput.parse(args.input ?? {});
+
+ await withTransaction(ctx, async (tx) => {
+ await requireOwner(tx, ctx);
+
+ const existing = await tx
+ .select()
+ .from(workspace)
+ .where(eq(workspace.id, ctx.workspace.id))
+ .get();
+ if (!existing) throw new NotFoundError("workspace", ctx.workspace.id);
+
+ if (!existing.ssoEnabled) return;
+
+ const updated = await tx
+ .update(workspace)
+ .set({ ssoEnabled: false, updatedAt: new Date() })
+ .where(eq(workspace.id, ctx.workspace.id))
+ .returning()
+ .get();
+
+ await emitAudit(tx, ctx, {
+ action: "workspace_sso.update",
+ entityType: "workspace_sso",
+ entityId: ctx.workspace.id,
+ before: existing,
+ after: updated,
+ ...(input.reason ? { metadata: { reason: input.reason } } : {}),
+ });
+ });
+}
diff --git a/packages/services/src/sso/enable.ts b/packages/services/src/sso/enable.ts
new file mode 100644
index 000000000..39af01993
--- /dev/null
+++ b/packages/services/src/sso/enable.ts
@@ -0,0 +1,75 @@
+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, PreconditionFailedError } from "../errors";
+import { resolveWorkOS } from "./client";
+import { requireOwner } from "./internal";
+
+export async function enableSso(args: {
+ ctx: ServiceContext;
+}): Promise<{ organizationId: string }> {
+ const { ctx } = args;
+ requireScope(ctx, "write");
+
+ if (!ctx.workspace.limits.sso) {
+ throw new PreconditionFailedError(
+ "SSO has not been added to this workspace",
+ );
+ }
+
+ const workos = resolveWorkOS(ctx.workos);
+
+ return withTransaction(ctx, async (tx) => {
+ await requireOwner(tx, ctx);
+
+ const existing = await tx
+ .select()
+ .from(workspace)
+ .where(eq(workspace.id, ctx.workspace.id))
+ .get();
+ if (!existing) throw new NotFoundError("workspace", ctx.workspace.id);
+
+ // Reuse the organization across enable/disable cycles so a workspace that
+ // re-upgrades keeps its already-configured IdP connection and domains.
+ const organizationId =
+ existing.workosOrganizationId ??
+ (
+ await workos.organizations.createOrganization({
+ name: existing.name || existing.slug,
+ })
+ ).id;
+
+ const updated = await tx
+ .update(workspace)
+ .set({
+ workosOrganizationId: organizationId,
+ ssoEnabled: true,
+ updatedAt: new Date(),
+ })
+ .where(eq(workspace.id, ctx.workspace.id))
+ .returning()
+ .get();
+
+ if (existing.workosOrganizationId) {
+ await emitAudit(tx, ctx, {
+ action: "workspace_sso.update",
+ entityType: "workspace_sso",
+ entityId: ctx.workspace.id,
+ before: existing,
+ after: updated,
+ });
+ } else {
+ await emitAudit(tx, ctx, {
+ action: "workspace_sso.create",
+ entityType: "workspace_sso",
+ entityId: ctx.workspace.id,
+ after: updated,
+ });
+ }
+
+ return { organizationId };
+ });
+}
diff --git a/packages/services/src/sso/get.ts b/packages/services/src/sso/get.ts
new file mode 100644
index 000000000..c747f392e
--- /dev/null
+++ b/packages/services/src/sso/get.ts
@@ -0,0 +1,74 @@
+import type { ServiceContext } from "../context";
+import { resolveWorkOS } from "./client";
+import { isWorkOSConfigured } from "./client";
+import { listSsoDomains } from "./internal";
+import { reconcileSsoDomains } from "./sync-domains";
+
+export type SsoConnectionState = "none" | "pending" | "active" | "inactive";
+
+export type SsoConfig = {
+ configured: boolean;
+ enabled: boolean;
+ organizationId: string | null;
+ connection: SsoConnectionState;
+ domains: {
+ domain: string;
+ verifiedAt: Date | null;
+ }[];
+ ready: boolean;
+};
+
+/**
+ * Connection state is read live from WorkOS rather than mirrored; domain rows
+ * are mirrored, so this read also reconciles them against WorkOS.
+ */
+export async function getSsoConfig(args: {
+ ctx: ServiceContext;
+}): Promise<SsoConfig> {
+ const { ctx } = args;
+
+ const rows = await listSsoDomains(ctx);
+ let domains = rows.map((row) => ({
+ domain: row.domain,
+ verifiedAt: row.verifiedAt,
+ }));
+
+ const organizationId = ctx.workspace.workosOrganizationId ?? null;
+
+ let connection: SsoConnectionState = "none";
+ if (organizationId && isWorkOSConfigured()) {
+ const workos = resolveWorkOS(ctx.workos);
+ domains = await reconcileSsoDomains({
+ ctx,
+ organizationId,
+ workos,
+ local: domains,
+ });
+ const list = await workos.sso.listConnections({
+ organizationId,
+ limit: 1,
+ });
+ const first = list.data[0];
+ if (!first) {
+ connection = "pending";
+ } else if (first.state === "active") {
+ connection = "active";
+ } else if (first.state === "inactive") {
+ connection = "inactive";
+ } else {
+ connection = "pending";
+ }
+ }
+
+ const hasVerifiedDomain = domains.some((entry) => entry.verifiedAt !== null);
+
+ return {
+ configured: Boolean(organizationId),
+ enabled: ctx.workspace.ssoEnabled,
+ organizationId,
+ connection,
+ domains,
+ ready:
+ ctx.workspace.ssoEnabled && connection === "active" && hasVerifiedDomain,
+ };
+}
diff --git a/packages/services/src/sso/index.ts b/packages/services/src/sso/index.ts
new file mode 100644
index 000000000..3636e85c6
--- /dev/null
+++ b/packages/services/src/sso/index.ts
@@ -0,0 +1,29 @@
+export { isWorkOSConfigured, resolveWorkOS } from "./client";
+export type { WorkOSClient } from "./client";
+export { verifyWorkOSWebhook } from "./webhook";
+export type { SsoWebhookEvent } from "./webhook";
+export { disableSso } from "./disable";
+export { enableSso } from "./enable";
+export { getSsoConfig } from "./get";
+export type { SsoConfig, SsoConnectionState } from "./get";
+export { getWorkspaceByWorkosOrganization } from "./internal";
+export { joinSsoWorkspace } from "./join";
+export {
+ getWorkspaceByVerifiedSsoDomain,
+ isEmailAllowedForWorkspace,
+ normalizeSsoDomain,
+} from "./lookup";
+export { createSsoPortalLink } from "./portal-link";
+export {
+ reconcileSsoDomains,
+ removeSsoDomain,
+ syncSsoDomain,
+} from "./sync-domains";
+export {
+ CreateSsoPortalLinkInput,
+ DisableSsoInput,
+ JoinSsoWorkspaceInput,
+ PortalIntent,
+ RemoveSsoDomainInput,
+ SyncSsoDomainInput,
+} from "./schemas";
diff --git a/packages/services/src/sso/internal.ts b/packages/services/src/sso/internal.ts
new file mode 100644
index 000000000..45efdb553
--- /dev/null
+++ b/packages/services/src/sso/internal.ts
@@ -0,0 +1,77 @@
+import { and, eq, isNotNull } from "@openstatus/db";
+import {
+ selectWorkspaceSchema,
+ usersToWorkspaces,
+ workspace,
+ workspaceSsoDomain,
+} from "@openstatus/db/src/schema";
+
+import {
+ type DB,
+ type ServiceContext,
+ getReadDb,
+ tryGetActorUserId,
+} from "../context";
+import { ForbiddenError, NotFoundError } from "../errors";
+import type { Workspace } from "../types";
+
+export async function requireOwner(tx: DB, ctx: ServiceContext): Promise<void> {
+ if (ctx.actor.type === "system") return;
+
+ const userId = tryGetActorUserId(ctx.actor);
+ if (userId == null) {
+ throw new ForbiddenError("Only workspace owners can manage SSO");
+ }
+
+ const membership = await tx.query.usersToWorkspaces.findFirst({
+ where: and(
+ eq(usersToWorkspaces.userId, userId),
+ eq(usersToWorkspaces.workspaceId, ctx.workspace.id),
+ ),
+ });
+
+ if (!membership || membership.role !== "owner") {
+ throw new ForbiddenError("Only workspace owners can manage SSO");
+ }
+}
+
+export async function getWorkspaceByWorkosOrganization(
+ db: DB,
+ organizationId: string,
+): Promise<Workspace> {
+ const row = await db
+ .select()
+ .from(workspace)
+ .where(eq(workspace.workosOrganizationId, organizationId))
+ .get();
+
+ if (!row) throw new NotFoundError("workspace", organizationId);
+
+ return selectWorkspaceSchema.parse(row);
+}
+
+export async function listSsoDomains(ctx: ServiceContext) {
+ return getReadDb(ctx)
+ .select()
+ .from(workspaceSsoDomain)
+ .where(eq(workspaceSsoDomain.workspaceId, ctx.workspace.id))
+ .all();
+}
+
+export async function hasVerifiedDomain(
+ db: DB,
+ workspaceId: number,
+): Promise<boolean> {
+ const row = await db
+ .select({ id: workspaceSsoDomain.id })
+ .from(workspaceSsoDomain)
+ .where(
+ and(
+ eq(workspaceSsoDomain.workspaceId, workspaceId),
+ isNotNull(workspaceSsoDomain.verifiedAt),
+ ),
+ )
+ .get();
+
+ return Boolean(row);
+}
diff --git a/packages/services/src/sso/join.ts b/packages/services/src/sso/join.ts
new file mode 100644
index 000000000..98a8b225c
--- /dev/null
+++ b/packages/services/src/sso/join.ts
@@ -0,0 +1,66 @@
+import { eq } from "@openstatus/db";
+import { usersToWorkspaces, workspace } from "@openstatus/db/src/schema";
+
+import { emitAudit } from "../audit";
+import { requireScope } from "../auth";
+import { type ServiceContext, withTransaction } from "../context";
+import { ForbiddenError, NotFoundError } from "../errors";
+import { memberRowSnapshot } from "../member/internal";
+import { JoinSsoWorkspaceInput } from "./schemas";
+
+/**
+ * Just-in-time provisioning for an SSO sign-in: add the asserted user to the
+ * workspace as a `member`.
+ *
+ * The caller must already have authorized the sign-in — this verb only
+ * re-asserts that the workspace still has SSO switched on, so a workspace that
+ * disabled SSO between the IdP callback and this write can't be joined.
+ *
+ * `onConflictDoNothing` on the `(userId, workspaceId)` unique constraint keeps
+ * repeat logins idempotent, which also means SSO never demotes an existing
+ * owner. The audit row is emitted only when a membership was actually created,
+ * so routine logins don't flood the log.
+ */
+export async function joinSsoWorkspace(args: {
+ ctx: ServiceContext;
+ input: JoinSsoWorkspaceInput;
+}): Promise<void> {
+ const { ctx } = args;
+ requireScope(ctx, "write");
+ const input = JoinSsoWorkspaceInput.parse(args.input);
+
+ await withTransaction(ctx, async (tx) => {
+ // Read the switch in the same transaction as the write: `ctx.workspace` is
+ // a snapshot taken before the IdP round-trip, so a sign-in overlapping a
+ // `disableSso` would otherwise join on stale configuration.
+ const current = await tx
+ .select({ ssoEnabled: workspace.ssoEnabled })
+ .from(workspace)
+ .where(eq(workspace.id, ctx.workspace.id))
+ .get();
+ if (!current) throw new NotFoundError("workspace", ctx.workspace.id);
+ if (!current.ssoEnabled) {
+ throw new ForbiddenError("SSO is not enabled for this workspace");
+ }
+
+ const [created] = await tx
+ .insert(usersToWorkspaces)
+ .values({
+ userId: input.userId,
+ workspaceId: ctx.workspace.id,
+ role: "member",
+ })
+ .onConflictDoNothing()
+ .returning();
+
+ if (!created) return;
+
+ await emitAudit(tx, ctx, {
+ action: "member.create",
+ entityType: "member",
+ entityId: input.userId,
+ after: memberRowSnapshot.parse(created),
+ metadata: { provisionedVia: "sso" },
+ });
+ });
+}
diff --git a/packages/services/src/sso/lookup.ts b/packages/services/src/sso/lookup.ts
new file mode 100644
index 000000000..32755c071
--- /dev/null
+++ b/packages/services/src/sso/lookup.ts
@@ -0,0 +1,79 @@
+import { and, db as defaultDb, eq, isNotNull } from "@openstatus/db";
+import {
+ selectWorkspaceSchema,
+ workspace,
+ workspaceSsoDomain,
+} from "@openstatus/db/src/schema";
+
+import type { DB } from "../context";
+import type { Workspace } from "../types";
+
+export function normalizeSsoDomain(input: string): string | null {
+ const trimmed = input.trim().toLowerCase();
+ if (!trimmed) return null;
+ const domain = trimmed.includes("@")
+ ? trimmed.slice(trimmed.lastIndexOf("@") + 1)
+ : trimmed;
+ return domain.length > 0 ? domain : null;
+}
+
+/**
+ * Resolve the SSO-enabled workspace that owns a *verified* domain.
+ *
+ * Unverified rows are never matched: `verifiedAt` mirrors WorkOS's verified
+ * state, and that DNS proof is what stops one workspace claiming another's
+ * domain.
+ */
+export async function getWorkspaceByVerifiedSsoDomain(
+ emailOrDomain: string,
+ db: DB = defaultDb,
+): Promise<Workspace | null> {
+ const domain = normalizeSsoDomain(emailOrDomain);
+ if (!domain) return null;
+
+ const row = await db
+ .select({ workspace })
+ .from(workspaceSsoDomain)
+ .innerJoin(workspace, eq(workspace.id, workspaceSsoDomain.workspaceId))
+ .where(
+ and(
+ eq(workspaceSsoDomain.domain, domain),
+ isNotNull(workspaceSsoDomain.verifiedAt),
+ eq(workspace.ssoEnabled, true),
+ isNotNull(workspace.workosOrganizationId),
+ ),
+ )
+ .get();
+
+ if (!row) return null;
+
+ return selectWorkspaceSchema.parse(row.workspace);
+}
+
+/**
+ * Authorization check for an SSO callback: the IdP controls the asserted email
+ * attribute, so an address outside the workspace's verified domains must be
+ * rejected before a session is created.
+ */
+export async function isEmailAllowedForWorkspace(
+ workspaceId: number,
+ email: string,
+ db: DB = defaultDb,
+): Promise<boolean> {
+ const domain = normalizeSsoDomain(email);
+ if (!domain) return false;
+
+ const row = await db
+ .select({ id: workspaceSsoDomain.id })
+ .from(workspaceSsoDomain)
+ .where(
+ and(
+ eq(workspaceSsoDomain.workspaceId, workspaceId),
+ eq(workspaceSsoDomain.domain, domain),
+ isNotNull(workspaceSsoDomain.verifiedAt),
+ ),
+ )
+ .get();
+
+ return Boolean(row);
+}
diff --git a/packages/services/src/sso/portal-link.ts b/packages/services/src/sso/portal-link.ts
new file mode 100644
index 000000000..1a0ceb5f4
--- /dev/null
+++ b/packages/services/src/sso/portal-link.ts
@@ -0,0 +1,35 @@
+import { requireScope } from "../auth";
+import { type ServiceContext, getReadDb } from "../context";
+import { PreconditionFailedError } from "../errors";
+import { resolveWorkOS } from "./client";
+import { requireOwner } from "./internal";
+import { CreateSsoPortalLinkInput } from "./schemas";
+
+/**
+ * WorkOS portal links expire five minutes after creation, so callers must
+ * redirect immediately rather than rendering the link into a page.
+ */
+export async function createSsoPortalLink(args: {
+ ctx: ServiceContext;
+ input: CreateSsoPortalLinkInput;
+}): Promise<{ link: string }> {
+ const { ctx } = args;
+ requireScope(ctx, "write");
+ const input = CreateSsoPortalLinkInput.parse(args.input);
+
+ await requireOwner(getReadDb(ctx), ctx);
+
+ const organizationId = ctx.workspace.workosOrganizationId;
+ if (!organizationId) {
+ throw new PreconditionFailedError("SSO is not set up for this workspace");
+ }
+
+ const workos = resolveWorkOS(ctx.workos);
+ const { link } = await workos.adminPortal.generateLink({
+ intent: input.intent,
+ organization: organizationId,
+ returnUrl: input.returnUrl,
+ });
+
+ return { link };
+}
diff --git a/packages/services/src/sso/schemas.ts b/packages/services/src/sso/schemas.ts
new file mode 100644
index 000000000..555d29519
--- /dev/null
+++ b/packages/services/src/sso/schemas.ts
@@ -0,0 +1,42 @@
+import { z } from "zod";
+
+export const PortalIntent = z.enum(["sso", "domain_verification"]);
+export type PortalIntent = z.infer<typeof PortalIntent>;
+
+export const CreateSsoPortalLinkInput = z.object({
+ intent: PortalIntent,
+ returnUrl: z.url(),
+});
+export type CreateSsoPortalLinkInput = z.infer<typeof CreateSsoPortalLinkInput>;
+
+export const DisableSsoInput = z.object({
+ reason: z.string().optional(),
+});
+export type DisableSsoInput = z.infer<typeof DisableSsoInput>;
+
+const domainSchema = z
+ .string()
+ .trim()
+ .toLowerCase()
+ .min(1)
+ .refine((value) => !value.includes("@"), {
+ message: "Expected a bare domain, not an email address",
+ });
+
+export const SyncSsoDomainInput = z.object({
+ organizationId: z.string().min(1),
+ domain: domainSchema,
+ verifiedAt: z.date().nullable(),
+});
+export type SyncSsoDomainInput = z.infer<typeof SyncSsoDomainInput>;
+
+export const RemoveSsoDomainInput = z.object({
+ organizationId: z.string().min(1),
+ domain: domainSchema,
+});
+export type RemoveSsoDomainInput = z.infer<typeof RemoveSsoDomainInput>;
+
+export const JoinSsoWorkspaceInput = z.object({
+ userId: z.number().int(),
+});
+export type JoinSsoWorkspaceInput = z.infer<typeof JoinSsoWorkspaceInput>;
diff --git a/packages/services/src/sso/sync-domains.ts b/packages/services/src/sso/sync-domains.ts
new file mode 100644
index 000000000..3d01d4f14
--- /dev/null
+++ b/packages/services/src/sso/sync-domains.ts
@@ -0,0 +1,190 @@
+import { and, eq } from "@openstatus/db";
+import { workspaceSsoDomain } from "@openstatus/db/src/schema";
+
+import { emitAudit } from "../audit";
+import { requireScope } from "../auth";
+import { type ServiceContext, withTransaction } from "../context";
+import type { WorkOSClient } from "./client";
+import { getWorkspaceByWorkosOrganization, listSsoDomains } from "./internal";
+import { RemoveSsoDomainInput, SyncSsoDomainInput } from "./schemas";
+
+/**
+ * Mirror a WorkOS organization domain into our table. Idempotent: WorkOS
+ * retries webhook deliveries, and replaying an event must not double-insert.
+ */
+export async function syncSsoDomain(args: {
+ ctx: ServiceContext;
+ input: SyncSsoDomainInput;
+}): Promise<void> {
+ const { ctx } = args;
+ requireScope(ctx, "write");
+ const input = SyncSsoDomainInput.parse(args.input);
+
+ await withTransaction(ctx, async (tx) => {
+ const ws = await getWorkspaceByWorkosOrganization(tx, input.organizationId);
+ const scopedCtx: ServiceContext = { ...ctx, workspace: ws, db: tx };
+
+ const existing = await tx
+ .select()
+ .from(workspaceSsoDomain)
+ .where(eq(workspaceSsoDomain.domain, input.domain))
+ .get();
+
+ if (existing) {
+ // A domain already claimed by a different workspace is not ours to move:
+ // the global unique on `domain` is what keeps login lookups unambiguous.
+ if (existing.workspaceId !== ws.id) return;
+ if (
+ existing.verifiedAt?.getTime() === input.verifiedAt?.getTime() ||
+ (existing.verifiedAt === null && input.verifiedAt === null)
+ ) {
+ return;
+ }
+
+ const updated = await tx
+ .update(workspaceSsoDomain)
+ .set({ verifiedAt: input.verifiedAt })
+ .where(eq(workspaceSsoDomain.id, existing.id))
+ .returning()
+ .get();
+
+ await emitAudit(tx, scopedCtx, {
+ action: "workspace_sso.update",
+ entityType: "workspace_sso",
+ entityId: ws.id,
+ before: existing,
+ after: updated,
+ metadata: { domain: input.domain },
+ });
+ return;
+ }
+
+ const inserted = await tx
+ .insert(workspaceSsoDomain)
+ .values({
+ workspaceId: ws.id,
+ domain: input.domain,
+ verifiedAt: input.verifiedAt,
+ })
+ .returning()
+ .get();
+
+ await emitAudit(tx, scopedCtx, {
+ action: "workspace_sso.create",
+ entityType: "workspace_sso",
+ entityId: ws.id,
+ after: inserted,
+ metadata: { domain: input.domain },
+ });
+ });
+}
+
+export type SsoDomainState = {
+ domain: string;
+ verifiedAt: Date | null;
+};
+
+/**
+ * Re-mirror WorkOS domains onto our rows. The webhook is the fast path but it
+ * can be unconfigured or dropped, and a domain that never lands here is a
+ * domain nobody can sign in from — so reads reconcile what it missed.
+ */
+export async function reconcileSsoDomains(args: {
+ ctx: ServiceContext;
+ organizationId: string;
+ workos: WorkOSClient;
+ local: SsoDomainState[];
+}): Promise<SsoDomainState[]> {
+ const { ctx, organizationId, workos, local } = args;
+
+ const organization =
+ await workos.organizations.getOrganization(organizationId);
+ const remote = organization.domains.map((entry) => ({
+ domain: entry.domain.trim().toLowerCase(),
+ verified: entry.state === "verified",
+ }));
+
+ const systemCtx: ServiceContext = {
+ ...ctx,
+ actor: { type: "system", job: "workos-reconcile" },
+ };
+ const byDomain = new Map(local.map((row) => [row.domain, row]));
+ const remoteDomains = new Set(remote.map((entry) => entry.domain));
+ let changed = false;
+
+ for (const entry of remote) {
+ const existing = byDomain.get(entry.domain);
+ // WorkOS exposes no verification timestamp, so keep the one we first saw.
+ const verifiedAt = entry.verified
+ ? (existing?.verifiedAt ?? new Date())
+ : null;
+
+ if (existing && existing.verifiedAt?.getTime() === verifiedAt?.getTime()) {
+ continue;
+ }
+
+ changed = true;
+ await syncSsoDomain({
+ ctx: systemCtx,
+ input: { organizationId, domain: entry.domain, verifiedAt },
+ });
+ }
+
+ for (const row of local) {
+ if (remoteDomains.has(row.domain)) continue;
+ changed = true;
+ await removeSsoDomain({
+ ctx: systemCtx,
+ input: { organizationId, domain: row.domain },
+ });
+ }
+
+ if (!changed) return local;
+
+ // Re-read rather than trust `remote`: a domain already claimed by another
+ // workspace is rejected by the sync, and must not be reported as ours.
+ const rows = await listSsoDomains(ctx);
+ return rows.map((row) => ({
+ domain: row.domain,
+ verifiedAt: row.verifiedAt,
+ }));
+}
+
+export async function removeSsoDomain(args: {
+ ctx: ServiceContext;
+ input: RemoveSsoDomainInput;
+}): Promise<void> {
+ const { ctx } = args;
+ requireScope(ctx, "write");
+ const input = RemoveSsoDomainInput.parse(args.input);
+
+ await withTransaction(ctx, async (tx) => {
+ const ws = await getWorkspaceByWorkosOrganization(tx, input.organizationId);
+ const scopedCtx: ServiceContext = { ...ctx, workspace: ws, db: tx };
+
+ const existing = await tx
+ .select()
+ .from(workspaceSsoDomain)
+ .where(
+ and(
+ eq(workspaceSsoDomain.domain, input.domain),
+ eq(workspaceSsoDomain.workspaceId, ws.id),
+ ),
+ )
+ .get();
+
+ if (!existing) return;
+
+ await tx
+ .delete(workspaceSsoDomain)
+ .where(eq(workspaceSsoDomain.id, existing.id));
+
+ await emitAudit(tx, scopedCtx, {
+ action: "workspace_sso.delete",
+ entityType: "workspace_sso",
+ entityId: ws.id,
+ before: existing,
+ metadata: { domain: input.domain },
+ });
+ });
+}
diff --git a/packages/services/src/sso/webhook.ts b/packages/services/src/sso/webhook.ts
new file mode 100644
index 000000000..ae09a40e2
--- /dev/null
+++ b/packages/services/src/sso/webhook.ts
@@ -0,0 +1,41 @@
+import { getRawWorkOS } from "./client";
+
+export type SsoWebhookEvent =
+ | { type: "domain.verified"; organizationId: string; domain: string }
+ | { type: "domain.deleted"; organizationId: string; domain: string }
+ | { type: "ignored" };
+
+/**
+ * Verify a WorkOS webhook signature and narrow it to the two domain events we
+ * act on. Returns `ignored` for everything else so callers can 200 and stop
+ * WorkOS retrying. Throws when the signature does not verify.
+ */
+export async function verifyWorkOSWebhook(args: {
+ payload: string;
+ sigHeader: string;
+ secret: string;
+}): Promise<SsoWebhookEvent> {
+ const event = await getRawWorkOS().webhooks.constructEvent({
+ payload: JSON.parse(args.payload),
+ sigHeader: args.sigHeader,
+ secret: args.secret,
+ });
+
+ if (event.event === "organization_domain.verified") {
+ return {
+ type: "domain.verified",
+ organizationId: event.data.organizationId,
+ domain: event.data.domain,
+ };
+ }
+
+ if (event.event === "organization_domain.deleted") {
+ return {
+ type: "domain.deleted",
+ organizationId: event.data.organizationId,
+ domain: event.data.domain,
+ };
+ }
+
+ return { type: "ignored" };
+}
diff --git a/packages/services/src/workspace/__tests__/downgrade.test.ts b/packages/services/src/workspace/__tests__/downgrade.test.ts
index ebc361d2c..3dbe8b70b 100644
--- a/packages/services/src/workspace/__tests__/downgrade.test.ts
+++ b/packages/services/src/workspace/__tests__/downgrade.test.ts
@@ -427,4 +427,43 @@ describe("downgradeWorkspaceToFree", () => {
);
});
});
+
+ test("disables SSO so JIT cannot re-add the trimmed members", async () => {
+ await withTestTransaction(async (tx) => {
+ const s = await seedTeamWorkspace(tx);
+
+ const withSso = await tx
+ .update(workspace)
+ .set({ workosOrganizationId: "org_downgrade_test", ssoEnabled: true })
+ .where(eq(workspace.id, s.ws.id))
+ .returning()
+ .get();
+
+ const ctx: ServiceContext = {
+ workspace: selectWorkspaceSchema.parse(withSso),
+ actor: { type: "system", job: "stripe-subscription-deleted" },
+ db: tx,
+ };
+
+ const result = await downgradeWorkspaceToFree({ ctx });
+ expect(result.ssoDisabled).toBe(true);
+
+ const after = await tx
+ .select()
+ .from(workspace)
+ .where(eq(workspace.id, s.ws.id))
+ .get();
+ expect(after?.ssoEnabled).toBe(false);
+ // Organization link is kept so a re-upgrade doesn't require reconnecting.
+ expect(after?.workosOrganizationId).toBe("org_downgrade_test");
+
+ await expectAuditRow({
+ workspaceId: s.ws.id,
+ action: "workspace_sso.update",
+ entityType: "workspace_sso",
+ entityId: s.ws.id,
+ db: tx,
+ });
+ });
+ });
});
diff --git a/packages/services/src/workspace/downgrade.ts b/packages/services/src/workspace/downgrade.ts
index 3c724f058..010df2021 100644
--- a/packages/services/src/workspace/downgrade.ts
+++ b/packages/services/src/workspace/downgrade.ts
@@ -19,6 +19,7 @@ import {
updatePageCustomDomain,
updatePagePasswordProtection,
} from "../page";
+import { disableSso } from "../sso";
import { updateWorkspacePlan } from "./update";
/**
@@ -44,7 +45,7 @@ import { updateWorkspacePlan } from "./update";
*/
export async function downgradeWorkspaceToFree(args: {
ctx: ServiceContext;
-}): Promise<{ customDomains: string[] }> {
+}): Promise<{ customDomains: string[]; ssoDisabled: boolean }> {
const { ctx } = args;
requireScope(ctx, "write");
const workspaceId = ctx.workspace.id;
@@ -64,6 +65,16 @@ export async function downgradeWorkspaceToFree(args: {
},
});
+ // Must happen here, not via the WorkOS webhook: JIT provisioning would
+ // otherwise re-add the members this downgrade is about to trim.
+ const ssoWasEnabled = ctx.workspace.ssoEnabled;
+ if (ssoWasEnabled) {
+ await disableSso({
+ ctx: txCtx,
+ input: { reason: "subscription_deleted" },
+ });
+ }
+
const activeMonitors = await tx
.select({ id: monitor.id })
.from(monitor)
@@ -167,6 +178,6 @@ export async function downgradeWorkspaceToFree(args: {
await deleteInvitation({ ctx: txCtx, input: { id: inv.id } });
}
- return { customDomains };
+ return { customDomains, ssoDisabled: ssoWasEnabled };
});
}
diff --git a/packages/services/test/helpers.ts b/packages/services/test/helpers.ts
index f54b10bce..d20810588 100644
--- a/packages/services/test/helpers.ts
+++ b/packages/services/test/helpers.ts
@@ -102,11 +102,15 @@ export type WorkspaceFixture = {
* that share workspace 1 race each other over `audit_log`, plan quotas and
* row counts once test files run in parallel — a private workspace makes those
* assertions deterministic.
+ *
+ * `overrides` reaches the workspace row directly — pass `limits` to model a
+ * purchased add-on, which is stored as an override on top of the plan defaults.
*/
export async function createWorkspaceFixture(
- plan: "team" | "free" = "team",
+ plan: "team" | "free" | "scale" = "team",
+ overrides: { limits?: string; ssoEnabled?: boolean } = {},
): Promise<WorkspaceFixture> {
- const { workspace, user } = await createTestWorkspace({ plan });
+ const { workspace, user } = await createTestWorkspace({ plan, ...overrides });
return {
workspace: selectWorkspaceSchema.parse(workspace),
userId: user.id,
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index c2039a711..189e28762 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -288,6 +288,9 @@ catalogs:
'@vercel/blob':
specifier: 0.23.4
version: 0.23.4
+ '@workos-inc/node':
+ specifier: 10.8.0
+ version: 10.8.0
ai:
specifier: 6.0.188
version: 6.0.188
@@ -2687,6 +2690,9 @@ importers:
'@openstatus/utils':
specifier: workspace:*
version: link:../utils
+ '@workos-inc/node':
+ specifier: 'catalog:'
+ version: 10.8.0
effect:
specifier: 'catalog:'
version: 3.21.2
@@ -7325,6 +7331,10 @@ packages:
'@webassemblyjs/[email protected]':
resolution: {integrity: sha512-kPSSXE6De1XOR820C90RIo2ogvZG+c3KiHzqUoO/F34Y2shGzesfqv7o57xrxovZJH/MetF5UjroJ/R/3isoiw==}
+ '@workos-inc/[email protected]':
+ resolution: {integrity: sha512-BmKwxaouV4hYhoJ9K0UPLC9LTpVfvnayvAy3lG9ELbZBoEWeaKkXoYn4W+d3vK7SZQ4qj/8PE7ve7sUKXnpRDA==}
+ engines: {node: '>=22.11.0'}
+
'@xstate/[email protected]':
resolution: {integrity: sha512-b5o1I6aLNeYlU/3CPlj/Z91ybk1gUsKT+5NAJI+2W4UjvS5KLG28K9v5UvNoFVjHV8PajVZ00RH3vnjyQO7ZAw==}
@@ -15662,6 +15672,8 @@ snapshots:
'@webassemblyjs/ast': 1.14.1
'@xtuc/long': 4.2.2
+ '@workos-inc/[email protected]': {}
+
'@xstate/[email protected]': {}
'@xtuc/[email protected]': {}
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index a70285300..f1829159a 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -16,6 +16,12 @@ allowBuilds:
protobufjs: true
sharp: true
autoInstallPeers: true
+overrides:
+ next: 16.2.11
+# `turbo` is deliberately pinned literally in package.json rather than listed
+# here: Vercel can't read a version through `catalog:`, and on failing to infer
+# it disables corepack and falls back to pnpm 9 — which ignores the `overrides`
+# above and fails the frozen install.
catalog:
"@ai-sdk/anthropic": 1.2.12
"@ai-sdk/openai-compatible": 2.0.54
@@ -121,6 +127,7 @@ catalog:
"@upstash/qstash": 2.11.0
"@upstash/redis": 1.38.0
"@vercel/blob": 0.23.4
+ "@workos-inc/node": 10.8.0
ai: 6.0.188
astro: 5.18.1
bcryptjs: 3.0.3
@@ -206,8 +213,3 @@ catalog:
validator: 13.15.35
vaul: 1.1.2
zod: 4.1.13
-
-# next 16.2.6 has critical CVEs; force transitive copies (react-email preview)
-# onto the patched release too
-overrides:
- next: 16.2.11
diff --git a/turbo.json b/turbo.json
index 9c4d16099..deed2942b 100644
--- a/turbo.json
+++ b/turbo.json
@@ -1,6 +1,10 @@
{
"$schema": "https://turbo.build/schema.json",
"globalDependencies": ["**/.env.*local"],
+ // Vercel disables corepack unless it can confirm turbo >= 2.1.3 or sees this
+ // passthrough; without corepack it falls back to pnpm 9, which can't read
+ // `overrides` from pnpm-workspace.yaml and fails the frozen install.
+ "globalPassThroughEnv": ["COREPACK_HOME"],
"tasks": {
"registry:build": {
"outputs": ["public/r/**"]