Open-source status page, incident response and uptime monitoring
TypeScript alertingincident-managementmcpmcp-servermonitoringmonitoring-as-codeobservabilityon-callopen-sourcesrestatus-pagestatuspagesynthetic-monitoringterraformtinybirdtursouptimeuptime-checkeruptime-monitor
wip: statuspage magic link (#1669)
Maximilian Kaskea7b8aad3cfb8
diff --git a/apps/dashboard/next-env.d.ts b/apps/dashboard/next-env.d.tsindex 9edff1c7c..c4b7818fb 100644--- a/apps/dashboard/next-env.d.ts+++ b/apps/dashboard/next-env.d.ts@@ -1,6 +1,6 @@/// <reference types="next" />/// <reference types="next/image-types/global" />-import "./.next/types/routes.d.ts";+import "./.next/dev/types/routes.d.ts";// NOTE: This file should not be edited// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.diff --git a/apps/dashboard/src/app/(dashboard)/layout.tsx b/apps/dashboard/src/app/(dashboard)/layout.tsxindex c418d08c6..204ff0178 100644--- a/apps/dashboard/src/app/(dashboard)/layout.tsx+++ b/apps/dashboard/src/app/(dashboard)/layout.tsx@@ -1,9 +1,6 @@import { AppSidebar } from "@/components/nav/app-sidebar";import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar";-import { auth } from "@/lib/auth";-import { TRPCReactProvider } from "@/lib/trpc/client";import { HydrateClient, getQueryClient, trpc } from "@/lib/trpc/server";-import { SessionProvider } from "next-auth/react";import { cookies } from "next/headers";export default async function Layout({@@ -11,7 +8,6 @@ export default async function Layout({}: {children: React.ReactNode;}) {- const session = await auth();const cookieStore = await cookies();const hasState = cookieStore.has("sidebar_state");const defaultOpen = hasState@@ -19,16 +15,12 @@ export default async function Layout({: true;return (- <SessionProvider session={session}>- <TRPCReactProvider>- <HydrateSidebar>- <SidebarProvider defaultOpen={defaultOpen}>- <AppSidebar />- <SidebarInset>{children}</SidebarInset>- </SidebarProvider>- </HydrateSidebar>- </TRPCReactProvider>- </SessionProvider>+ <HydrateSidebar>+ <SidebarProvider defaultOpen={defaultOpen}>+ <AppSidebar />+ <SidebarInset>{children}</SidebarInset>+ </SidebarProvider>+ </HydrateSidebar>);}diff --git a/apps/dashboard/src/app/(dashboard)/settings/billing/client.tsx b/apps/dashboard/src/app/(dashboard)/settings/billing/client.tsxindex 41a80c84b..bcbac1d9f 100644--- a/apps/dashboard/src/app/(dashboard)/settings/billing/client.tsx+++ b/apps/dashboard/src/app/(dashboard)/settings/billing/client.tsx@@ -1,6 +1,11 @@"use client";+import { BillingAddons } from "@/components/content/billing-addons";import { BillingProgress } from "@/components/content/billing-progress";+import {+ EmptyStateContainer,+ EmptyStateTitle,+} from "@/components/content/empty-state";import {Section,SectionDescription,@@ -22,6 +27,7 @@ import {} from "@/components/forms/form-card";import { Button } from "@/components/ui/button";import { useTRPC } from "@/lib/trpc/client";+import { allPlans } from "@openstatus/db/src/schema/plan/config";import type { Limits } from "@openstatus/db/src/schema/plan/schema";import { useMutation, useQuery } from "@tanstack/react-query";import { useRouter } from "next/navigation";@@ -133,9 +139,9 @@ export function Client() {<FormCardGroup><FormCard><FormCardHeader>- <FormCardTitle>Limits</FormCardTitle>+ <FormCardTitle>Usage</FormCardTitle><FormCardDescription>- Overview of your current limits.+ Overview of your current usage, limits and addons.</FormCardDescription></FormCardHeader><FormCardContent>@@ -155,18 +161,37 @@ export function Client() {value={workspace.usage?.notifications ?? 0}max={workspace.limits["notification-channels"]}/>- </div>- </FormCardContent>- <FormCardSeparator />- <FormCardContent>- <div className="flex flex-col gap-2"><BillingProgress- label="Requests in the last 30 days"+ label="Total requests in the last 30 days"value={totalRequests}max={calculateTotalRequests(workspace.limits)}/></div></FormCardContent>+ <FormCardSeparator />+ <FormCardContent>+ <FormCardHeader className="col-span-full px-0 pt-0 pb-0">+ <FormCardTitle>Add-ons</FormCardTitle>+ <FormCardDescription>+ Extend your limits with additional features.+ </FormCardDescription>+ </FormCardHeader>+ <div className="flex flex-col gap-2 pt-4">+ {/* TODO: redirect to stripe product */}+ {allPlans[workspace.plan].addons["email-domain-protection"] ? (+ <BillingAddons+ label="Magic Link (Auth)"+ description="Only allow user with a given email domain to access the status page."+ addon="email-domain-protection"+ workspace={workspace}+ />+ ) : (+ <EmptyStateContainer>+ <EmptyStateTitle>No add-ons available</EmptyStateTitle>+ </EmptyStateContainer>+ )}+ </div>+ </FormCardContent><FormCardFooter><FormCardFooterInfo>Access your{" "}diff --git a/apps/dashboard/src/app/(dashboard)/status-pages/[id]/sidebar.tsx b/apps/dashboard/src/app/(dashboard)/status-pages/[id]/sidebar.tsxindex b07551949..318f05450 100644--- a/apps/dashboard/src/app/(dashboard)/status-pages/[id]/sidebar.tsx+++ b/apps/dashboard/src/app/(dashboard)/status-pages/[id]/sidebar.tsx@@ -1,7 +1,6 @@"use client";import { Link } from "@/components/common/link";-import { TableCellBoolean } from "@/components/data-table/table-cell-boolean";import { TableCellLink } from "@/components/data-table/table-cell-link";import { SidebarRight } from "@/components/nav/sidebar-right";import {@@ -49,6 +48,10 @@ export function Sidebar() {</Link>),},+ {+ label: "Access Type",+ value: statusPage.accessType,+ },{ label: "Domain", value: statusPage.customDomain || "-" },{label: "Favicon",@@ -89,40 +92,21 @@ export function Sidebar() {label: "Configuration",items: [{- label: "Legacy",- value: <TableCellBoolean value={statusPage.legacyPage} />,+ label: "Theme",+ value: statusPage.configuration?.theme ?? "-",+ },+ {+ label: "Bar Value",+ value: statusPage.configuration?.type ?? "-",+ },+ {+ label: "Card Value",+ value: statusPage.configuration?.value ?? "-",},{- label: "Protected",- value: <TableCellBoolean value={statusPage.passwordProtected} />,+ label: "Show Uptime",+ value: statusPage.configuration?.uptime ? "Yes" : "No",},- ...(statusPage.legacyPage- ? [- {- label: "Show values",- value: (- <TableCellBoolean value={statusPage.showMonitorValues} />- ),- },- ]- : [- {- label: "Theme",- value: statusPage.configuration?.theme ?? "-",- },- {- label: "Bar Value",- value: statusPage.configuration?.type ?? "-",- },- {- label: "Card Value",- value: statusPage.configuration?.value ?? "-",- },- {- label: "Show Uptime",- value: statusPage.configuration?.uptime ? "Yes" : "No",- },- ]),],},{diff --git a/apps/dashboard/src/app/api/trpc/edge/[trpc]/route.ts b/apps/dashboard/src/app/api/trpc/edge/[trpc]/route.tsindex 2c1fc5285..ee69b118c 100644--- a/apps/dashboard/src/app/api/trpc/edge/[trpc]/route.ts+++ b/apps/dashboard/src/app/api/trpc/edge/[trpc]/route.ts@@ -1,6 +1,7 @@import { fetchRequestHandler } from "@trpc/server/adapters/fetch";import type { NextRequest } from "next/server";+import { auth } from "@/lib/auth";import { createTRPCContext } from "@openstatus/api";import { edgeRouter } from "@openstatus/api/src/edge";@@ -11,7 +12,7 @@ const handler = (req: NextRequest) =>endpoint: "/api/trpc/edge",router: edgeRouter,req: req,- createContext: () => createTRPCContext({ req }),+ createContext: () => createTRPCContext({ req, auth }),onError: ({ error }) => {console.log("Error in tRPC handler (edge)");console.error(error);diff --git a/apps/dashboard/src/app/api/trpc/lambda/[trpc]/route.ts b/apps/dashboard/src/app/api/trpc/lambda/[trpc]/route.tsindex b36568088..1352dcf0c 100644--- a/apps/dashboard/src/app/api/trpc/lambda/[trpc]/route.ts+++ b/apps/dashboard/src/app/api/trpc/lambda/[trpc]/route.ts@@ -1,6 +1,7 @@import { fetchRequestHandler } from "@trpc/server/adapters/fetch";import type { NextRequest } from "next/server";+import { auth } from "@/lib/auth";import { createTRPCContext } from "@openstatus/api";import { lambdaRouter } from "@openstatus/api/src/lambda";@@ -12,7 +13,7 @@ const handler = (req: NextRequest) =>endpoint: "/api/trpc/lambda",router: lambdaRouter,req: req,- createContext: () => createTRPCContext({ req }),+ createContext: () => createTRPCContext({ req, auth }),onError: ({ error }) => {console.log("Error in tRPC handler (lambda)");console.error(error);diff --git a/apps/dashboard/src/app/layout.tsx b/apps/dashboard/src/app/layout.tsxindex 3df437414..b6ca28bed 100644--- a/apps/dashboard/src/app/layout.tsx+++ b/apps/dashboard/src/app/layout.tsx@@ -4,7 +4,10 @@ import "./globals.css";import { TailwindIndicator } from "@/components/tailwind-indicator";import { ThemeProvider } from "@/components/theme-provider";import { Toaster } from "@/components/ui/sonner";+import { auth } from "@/lib/auth";+import { TRPCReactProvider } from "@/lib/trpc/client";import { cn } from "@/lib/utils";+import { SessionProvider } from "next-auth/react";import LocalFont from "next/font/local";import { NuqsAdapter } from "nuqs/adapters/next/app";import { ogMetadata, twitterMetadata } from "./metadata";@@ -68,11 +71,13 @@ export const metadata: Metadata = {// export const dynamic = "error";-export default function RootLayout({+export default async function RootLayout({children,}: Readonly<{children: React.ReactNode;}>) {+ const session = await auth();+return (<html lang="en" suppressHydrationWarning><body@@ -85,18 +90,22 @@ export default function RootLayout({"font-sans antialiased ",)}>- <NuqsAdapter>- <ThemeProvider- attribute="class"- defaultTheme="system"- enableSystem- disableTransitionOnChange- >- {children}- <TailwindIndicator />- <Toaster richColors expand />- </ThemeProvider>- </NuqsAdapter>+ <SessionProvider session={session}>+ <TRPCReactProvider>+ <NuqsAdapter>+ <ThemeProvider+ attribute="class"+ defaultTheme="system"+ enableSystem+ disableTransitionOnChange+ >+ {children}+ <TailwindIndicator />+ <Toaster richColors expand />+ </ThemeProvider>+ </NuqsAdapter>+ </TRPCReactProvider>+ </SessionProvider></body></html>);diff --git a/apps/dashboard/src/app/(public)/login/_components/actions.ts b/apps/dashboard/src/app/login/_components/actions.tssimilarity index 100%rename from apps/dashboard/src/app/(public)/login/_components/actions.tsrename to apps/dashboard/src/app/login/_components/actions.tsdiff --git a/apps/dashboard/src/app/(public)/login/_components/magic-link-form.tsx b/apps/dashboard/src/app/login/_components/magic-link-form.tsxsimilarity index 100%rename from apps/dashboard/src/app/(public)/login/_components/magic-link-form.tsxrename to apps/dashboard/src/app/login/_components/magic-link-form.tsxdiff --git a/apps/dashboard/src/app/login/layout.tsx b/apps/dashboard/src/app/login/layout.tsxnew file mode 100644index 000000000..aa48f80d7--- /dev/null+++ b/apps/dashboard/src/app/login/layout.tsx@@ -0,0 +1,15 @@+import { redirect } from "next/navigation";++import { AuthLayout } from "@/components/layout/auth-layout";+import { auth } from "@/lib/auth";++export default async function Layout({+ children,+}: {+ children: React.ReactNode;+}) {+ const session = await auth();+ if (session) redirect("/");++ return <AuthLayout>{children}</AuthLayout>;+}diff --git a/apps/dashboard/src/app/(public)/login/page.tsx b/apps/dashboard/src/app/login/page.tsxsimilarity index 100%rename from apps/dashboard/src/app/(public)/login/page.tsxrename to apps/dashboard/src/app/login/page.tsxdiff --git a/apps/dashboard/src/app/(public)/login/search-params.ts b/apps/dashboard/src/app/login/search-params.tssimilarity index 100%rename from apps/dashboard/src/app/(public)/login/search-params.tsrename to apps/dashboard/src/app/login/search-params.tsdiff --git a/apps/dashboard/src/app/status-page/layout.tsx b/apps/dashboard/src/app/status-page/layout.tsxdeleted file mode 100644index f3b5ff718..000000000--- a/apps/dashboard/src/app/status-page/layout.tsx+++ /dev/null@@ -1,48 +0,0 @@-/**- * TODO:- * - add different header- * - add different chart/tracker- * - add subscription popover (choose which one you'd like to allow)- * - use the '@/components/status-page` for the components- */--import { Link } from "@/components/common/link";-import { Button } from "@/components/ui/button";-import NextLink from "next/link";--const nav = [- { label: "Status", href: "#" },- { label: "Events", href: "#" },- { label: "Monitors", href: "#" },-];--export default function Layout({ children }: { children: React.ReactNode }) {- return (- <div className="flex min-h-screen flex-col gap-4">- <header className="w-full border border-b px-3 py-2">- <nav className="mx-auto flex max-w-xl items-center justify-between">- <ul className="flex flex-row gap-2">- {nav.map((item) => (- <li key={item.label}>- <Button variant="ghost" asChild>- <NextLink href={item.href}>{item.label}</NextLink>- </Button>- </li>- ))}- </ul>- <div>{/* TODO: Popover */}</div>- </nav>- </header>- <main className="mx-auto w-full max-w-xl flex-1 px-3 py-2">- {children}- </main>- <footer className="w-full border border-t px-3 py-2">- <div className="mx-auto max-w-xl">- <p className="text-center text-muted-foreground">- Powered by <Link href="#">OpenStatus</Link>- </p>- </div>- </footer>- </div>- );-}diff --git a/apps/dashboard/src/app/status-page/page.tsx b/apps/dashboard/src/app/status-page/page.tsxdeleted file mode 100644index c4d2facd5..000000000--- a/apps/dashboard/src/app/status-page/page.tsx+++ /dev/null@@ -1,46 +0,0 @@-"use client";--import {- FloatingButton,- StatusPageProvider,- useStatusPage,-} from "@/components/status-page/floating-button";-import {- Status,- StatusBanner,- StatusContent,- StatusDescription,- StatusHeader,- StatusTitle,-} from "@/components/status-page/status";-import { StatusMonitor } from "@/components/status-page/status-monitor";--function StatusPageContent() {- const { variant, cardType } = useStatusPage();-- return (- <div className="grid gap-6">- <Status variant={variant}>- <StatusHeader>- <StatusTitle>Craft</StatusTitle>- <StatusDescription>- Stay informed about the stability- </StatusDescription>- </StatusHeader>- <StatusBanner />- <StatusContent>- <StatusMonitor variant={variant} type={cardType} />- </StatusContent>- </Status>- <FloatingButton />- </div>- );-}--export default function Page() {- return (- <StatusPageProvider defaultVariant="success">- <StatusPageContent />- </StatusPageProvider>- );-}diff --git a/apps/dashboard/src/components/content/billing-addons.tsx b/apps/dashboard/src/components/content/billing-addons.tsxnew file mode 100644index 000000000..5a0ef05bc--- /dev/null+++ b/apps/dashboard/src/components/content/billing-addons.tsx@@ -0,0 +1,168 @@+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+ AlertDialogTrigger,+} from "@/components/ui/alert-dialog";+import { Button } from "@/components/ui/button";+import { Label } from "@/components/ui/label";+import { useCookieState } from "@/hooks/use-cookie-state";++import { useTRPC } from "@/lib/trpc/client";+import type { RouterOutputs } from "@openstatus/api";+import type { Addons } from "@openstatus/db/src/schema/plan/schema";+import { getAddonPriceConfig } from "@openstatus/db/src/schema/plan/utils";+import { useMutation, useQueryClient } from "@tanstack/react-query";+import { isTRPCClientError } from "@trpc/client";+import { Check } from "lucide-react";+import { useState, useTransition } from "react";+import { toast } from "sonner";++const BASE_URL =+ process.env.NODE_ENV === "production"+ ? "https://app.openstatus.dev"+ : "http://localhost:3000";++type Workspace = RouterOutputs["workspace"]["get"];++interface BillingAddonsProps {+ label: string;+ description: React.ReactNode;+ addon: keyof Addons;+ workspace: Workspace;+}++export function BillingAddons({+ label,+ description,+ addon,+ workspace,+}: BillingAddonsProps) {+ const [open, setOpen] = useState(false);+ const [isPending, startTransition] = useTransition();+ const [currency] = useCookieState("x-currency", "USD");+ const trpc = useTRPC();+ const queryClient = useQueryClient();+ const checkoutSessionMutation = useMutation(+ trpc.stripeRouter.addAddon.mutationOptions({+ onSuccess: () => {+ queryClient.invalidateQueries({+ queryKey: trpc.workspace.get.queryKey(),+ });+ },+ }),+ );++ const plan = workspace.plan;+ const value = workspace.limits[addon];+ const price = getAddonPriceConfig(plan, addon, currency);++ function submitAction() {+ startTransition(async () => {+ try {+ const promise = checkoutSessionMutation.mutateAsync({+ workspaceSlug: workspace.slug,+ successUrl: `${BASE_URL}/settings/billing?success=true`,+ cancelUrl: `${BASE_URL}/settings/billing`,+ feature: addon,+ remove: value,+ });+ toast.promise(promise, {+ loading: "Updating...",+ success: () => {+ setOpen(false);+ return value ? "Removed" : "Added";+ },+ error: (error) => {+ if (isTRPCClientError(error)) {+ return error.message;+ }+ return "Failed to update";+ },+ });+ await promise;+ } catch (error) {+ console.error(error);+ }+ });+ }++ return (+ <div className="flex flex-col gap-2">+ <div className="flex flex-col justify-between gap-1.5 sm:flex-row">+ <div className="space-y-0.5 text-sm">+ <Label>{label}</Label>+ <div className="truncate text-muted-foreground">{description}</div>+ </div>+ <div className="flex items-center gap-2">+ {value ? <Check className="size-4 text-success" /> : null}+ <span className="font-mono text-foreground text-sm">+ {price+ ? new Intl.NumberFormat(price.locale, {+ style: "currency",+ currency: price.currency,+ }).format(price.value)+ : "N/A"}+ /mo.+ </span>+ <AlertDialog open={open} onOpenChange={setOpen}>+ <AlertDialogTrigger asChild>+ <Button size="sm" variant="secondary">+ {value ? "Remove" : "Add"}+ </Button>+ </AlertDialogTrigger>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>{label}</AlertDialogTitle>+ <AlertDialogDescription>+ {value ? (+ <>+ {label} will be removed from your subscription. You will+ save{" "}+ {price+ ? new Intl.NumberFormat(price.locale, {+ style: "currency",+ currency: price.currency,+ }).format(price.value)+ : "N/A"}+ /mo. on your next billing cycle.+ </>+ ) : (+ <>+ {label} will be added to your subscription. You will be+ charged an additional{" "}+ {price+ ? new Intl.NumberFormat(price.locale, {+ style: "currency",+ currency: price.currency,+ }).format(price.value)+ : "N/A"}+ /mo. on your next billing cycle.+ </>+ )}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>Cancel</AlertDialogCancel>+ <AlertDialogAction+ onClick={(e) => {+ e.preventDefault();+ submitAction();+ }}+ disabled={isPending}+ >+ {isPending ? "Updating..." : value ? "Remove" : "Add"}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </div>+ </div>+ </div>+ );+}diff --git a/apps/dashboard/src/components/content/billing-progress.tsx b/apps/dashboard/src/components/content/billing-progress.tsxindex c1729af29..84f0915a1 100644--- a/apps/dashboard/src/components/content/billing-progress.tsx+++ b/apps/dashboard/src/components/content/billing-progress.tsx@@ -13,7 +13,10 @@ export function BillingProgress({ label, value, max }: BillingProgressProps) {<div className="flex justify-between text-muted-foreground text-sm"><div className="font-medium">{label}</div><div className="font-mono">- <span className="text-foreground">{value}</span>/{max}+ <span className="text-foreground">+ {new Intl.NumberFormat("de-DE").format(value)}+ </span>+ /{new Intl.NumberFormat("de-DE").format(max)}</div></div><Progress value={(value / max) * 100} />diff --git a/apps/dashboard/src/components/data-table/billing/data-table.tsx b/apps/dashboard/src/components/data-table/billing/data-table.tsxindex d10395098..b6c270145 100644--- a/apps/dashboard/src/components/data-table/billing/data-table.tsx+++ b/apps/dashboard/src/components/data-table/billing/data-table.tsx@@ -14,13 +14,17 @@ import {TableRow,} from "@/components/ui/table";+import { Badge } from "@/components/ui/badge";import { config as featureGroups, plans } from "@/data/plans";import { useCookieState } from "@/hooks/use-cookie-state";import { getStripe } from "@/lib/stripe";import { useTRPC } from "@/lib/trpc/client";import { cn } from "@/lib/utils";import type { WorkspacePlan } from "@openstatus/db/src/schema";-import { getPriceConfig } from "@openstatus/db/src/schema/plan/utils";+import {+ getAddonPriceConfig,+ getPriceConfig,+} from "@openstatus/db/src/schema/plan/utils";import { useMutation, useQuery } from "@tanstack/react-query";const BASE_URL =@@ -80,13 +84,13 @@ export function DataTable({ restrictTo }: { restrictTo?: WorkspacePlan[] }) {</p></div><p className="text-right">- <span className="font-cal text-lg">+ <span className="font-mono text-lg">{new Intl.NumberFormat(price.locale, {style: "currency",currency: price.currency,}).format(price.value)}</span>- <span className="font-light text-muted-foreground text-sm">+ <span className="text-muted-foreground text-sm">/month</span></p>@@ -131,59 +135,90 @@ export function DataTable({ restrictTo }: { restrictTo?: WorkspacePlan[] }) {{label}</TableCell></TableRow>- {features.map(({ value, label: featureLabel, monthly }) => (- <TableRow key={groupKey + value}>- <TableCell>- <div className="flex items-center gap-2 text-wrap">- {featureLabel}- </div>- </TableCell>- {filteredPlans.map((plan) => {- const limitValue =- plan.limits[value as keyof typeof plan.limits];+ {features.map(+ ({ value, label: featureLabel, monthly, badge }) => (+ <TableRow key={groupKey + value}>+ <TableCell>+ <div className="flex items-center gap-2 text-wrap">+ {featureLabel}{" "}+ {badge ? (+ <Badge variant="outline">{badge}</Badge>+ ) : null}+ </div>+ </TableCell>+ {filteredPlans.map((plan) => {+ const limitValue =+ plan.limits[value as keyof typeof plan.limits];+ const isAddon = value in plan.addons;- function renderContent() {- if (typeof limitValue === "boolean") {- return limitValue ? (- <Check className="h-4 w-4 text-foreground" />- ) : (- <span className="text-muted-foreground/50">- ‐- </span>- );- }- if (typeof limitValue === "number") {- return new Intl.NumberFormat("us")- .format(limitValue)- .toString();- }+ function renderContent() {+ if (isAddon) {+ const price = getAddonPriceConfig(+ plan.id,+ value as keyof typeof plan.addons,+ currency,+ );+ if (!price) return null;+ return (+ <div>+ <span className="text-muted-foreground">+ add-on{" "}+ </span>+ <span>+ {new Intl.NumberFormat(price.locale, {+ style: "currency",+ currency: price.currency,+ }).format(price.value)}+ /mo.+ </span>+ </div>+ );+ }+ if (typeof limitValue === "boolean") {+ return limitValue ? (+ <Check className="h-4 w-4 text-foreground" />+ ) : (+ <span className="text-muted-foreground/50">+ ‐+ </span>+ );+ }+ if (typeof limitValue === "number") {+ return new Intl.NumberFormat("us")+ .format(limitValue)+ .toString();+ }- // TODO: create a format function for this in @data/plans- if (value === "regions" && Array.isArray(limitValue)) {- return limitValue?.length ?? 0;- }+ // TODO: create a format function for this in @data/plans+ if (value === "regions" && Array.isArray(limitValue)) {+ return limitValue?.length ?? 0;+ }- if (Array.isArray(limitValue) && limitValue.length > 0) {- return limitValue[0];+ if (+ Array.isArray(limitValue) &&+ limitValue.length > 0+ ) {+ return limitValue[0];+ }+ return limitValue;}- return limitValue;- }- return (- <TableCell- key={plan.id + value}- className={cn(- "font-mono",- plan.id === "starter" && "bg-muted/30",- )}- >- {renderContent()}- {monthly ? "/mo" : ""}- </TableCell>- );- })}- </TableRow>- ))}+ return (+ <TableCell+ key={plan.id + value}+ className={cn(+ "font-mono",+ plan.id === "starter" && "bg-muted/30",+ )}+ >+ {renderContent()}+ {monthly ? "/mo." : ""}+ </TableCell>+ );+ })}+ </TableRow>+ ),+ )}</Fragment>),)}diff --git a/apps/dashboard/src/components/forms/form-card.tsx b/apps/dashboard/src/components/forms/form-card.tsxindex 31e297b0b..c24e741a2 100644--- a/apps/dashboard/src/components/forms/form-card.tsx+++ b/apps/dashboard/src/components/forms/form-card.tsx@@ -82,6 +82,7 @@ export function FormCardContent({<CardContentclassName={cn("px-4 group-has-data-[slot=card-upgrade]:pointer-events-none group-has-data-[slot=card-upgrade]:opacity-50",+ "has-data-[slot=card-content-upgrade]:pointer-events-none has-data-[slot=card-content-upgrade]:opacity-50",className,)}{...props}@@ -177,6 +178,24 @@ export function FormCardUpgrade({);}+// NOTE; this is for a very specific case where we don't want to disable the whole content+// and instead disable specpfic card content (e.g. for add-ons)+export function FormCardContentUpgrade({+ children,+ className,+ ...props+}: React.ComponentProps<"div">) {+ return (+ <div+ data-slot="card-content-upgrade"+ className={cn("hidden", className)}+ {...props}+ >+ {children}+ </div>+ );+}+export function FormCardEmpty({children,className,diff --git a/apps/dashboard/src/components/forms/status-page/form-page-access.tsx b/apps/dashboard/src/components/forms/status-page/form-page-access.tsxnew file mode 100644index 000000000..1cf87eb4c--- /dev/null+++ b/apps/dashboard/src/components/forms/status-page/form-page-access.tsx@@ -0,0 +1,246 @@+"use client";++import { Link } from "@/components/common/link";+import {+ FormCard,+ FormCardContent,+ FormCardContentUpgrade,+ FormCardDescription,+ FormCardFooter,+ FormCardFooterInfo,+ FormCardHeader,+ FormCardSeparator,+ FormCardTitle,+} from "@/components/forms/form-card";+import { Button } from "@/components/ui/button";+import {+ Form,+ FormControl,+ FormDescription,+ FormField,+ FormItem,+ FormLabel,+ FormMessage,+} from "@/components/ui/form";+import { Input } from "@/components/ui/input";+import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";+import { cn } from "@/lib/utils";+import { zodResolver } from "@hookform/resolvers/zod";+import { isTRPCClientError } from "@trpc/client";+import { Key, Lock, LockOpen, ShieldUser } from "lucide-react";+import { useTransition } from "react";+import { useForm } from "react-hook-form";+import { toast } from "sonner";+import { z } from "zod";++const accessTypeSchema = z.enum(["public", "password", "email-domain"]);++const schema = z.object({+ accessType: accessTypeSchema,+ password: z.string().optional(),+ authEmailDomains: z+ .preprocess(+ (val: string[] | undefined) =>+ val+ ? String(val)+ .split(",")+ .map((domain) => domain.trim())+ .filter((domain) => domain.length > 0)+ : [],+ z.array(z.string()).optional(),+ )+ .optional(),+});++type FormValues = z.infer<typeof schema>;++export function FormPageAccess({+ lockedMap,+ defaultValues,+ onSubmit,+ ...props+}: Omit<React.ComponentProps<"form">, "onSubmit"> & {+ lockedMap?: Map<z.infer<typeof accessTypeSchema>, boolean>;+ defaultValues?: FormValues;+ onSubmit: (values: FormValues) => Promise<void>;+}) {+ const [isPending, startTransition] = useTransition();+ const form = useForm<FormValues>({+ resolver: zodResolver(schema),+ defaultValues: defaultValues ?? {+ accessType: "public",+ password: "",+ authEmailDomains: [],+ },+ });+ const watchAccessType = form.watch("accessType");+ const locked = lockedMap?.get(watchAccessType);++ function submitAction(values: FormValues) {+ if (isPending) return;++ startTransition(async () => {+ try {+ console.log(values);+ const promise = onSubmit(values);+ toast.promise(promise, {+ loading: "Saving...",+ success: "Saved",+ error: (error) => {+ if (isTRPCClientError(error)) {+ return error.message;+ }+ return "Failed to save";+ },+ });+ await promise;+ } catch (error) {+ console.error(error);+ }+ });+ }++ return (+ <Form {...form}>+ <form onSubmit={form.handleSubmit(submitAction)} {...props}>+ <FormCard>+ <FormCardHeader>+ <FormCardTitle>Page Access</FormCardTitle>+ <FormCardDescription>+ Enable protection for your status page. Choose between simple+ password or email domain authentication via magic link.+ </FormCardDescription>+ </FormCardHeader>+ <FormCardContent>+ <FormField+ control={form.control}+ name="accessType"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Protection Type</FormLabel>+ <FormControl>+ <RadioGroup+ onValueChange={field.onChange}+ defaultValue={field.value}+ className="grid grid-cols-2 gap-4 sm:grid-cols-4"+ >+ {[+ { value: "public", icon: LockOpen, label: "Public" },+ { value: "password", icon: Key, label: "Password" },+ {+ value: "email-domain",+ icon: ShieldUser,+ label: "Magic Link (Auth)",+ },+ ].map((type) => {+ return (+ <FormItem+ key={type.value}+ className={cn(+ "relative flex cursor-pointer flex-row items-center gap-3 rounded-md border border-input px-2 py-3 text-center shadow-xs outline-none transition-[color,box-shadow] has-aria-[invalid=true]:border-destructive has-data-[state=checked]:border-primary/50 has-focus-visible:border-ring has-focus-visible:ring-[3px] has-focus-visible:ring-ring/50",+ )}+ >+ <FormControl>+ <RadioGroupItem+ value={type.value}+ className="sr-only"+ />+ </FormControl>+ <type.icon+ className="shrink-0 text-muted-foreground"+ size={16}+ aria-hidden="true"+ />+ <FormLabel className="cursor-pointer font-medium text-foreground text-xs leading-none after:absolute after:inset-0">+ {type.label}+ </FormLabel>+ </FormItem>+ );+ })}+ </RadioGroup>+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ </FormCardContent>+ {watchAccessType && watchAccessType !== "public" ? (+ <FormCardSeparator />+ ) : null}+ {watchAccessType === "password" ? (+ <FormCardContent className="grid gap-4">+ {locked ? <FormCardContentUpgrade /> : null}+ <FormField+ control={form.control}+ name="password"+ disabled={locked}+ render={({ field }) => (+ <FormItem>+ <FormLabel>Password</FormLabel>+ <FormControl>+ <Input {...field} />+ </FormControl>+ <FormMessage />+ <FormDescription>+ Set a password to your status page to have a very basic+ protection.+ </FormDescription>+ </FormItem>+ )}+ />+ </FormCardContent>+ ) : null}+ {watchAccessType === "email-domain" ? (+ <FormCardContent className="grid gap-4">+ {locked ? <FormCardContentUpgrade /> : null}+ <FormField+ control={form.control}+ name="authEmailDomains"+ disabled={locked}+ render={({ field }) => (+ <FormItem>+ <FormLabel>Email Domains</FormLabel>+ <FormControl>+ <Input {...field} />+ </FormControl>+ <FormMessage />+ <FormDescription>+ Comma-separated list of email domains. Only emails from+ these domains will be authenticated to access the status+ page.+ </FormDescription>+ </FormItem>+ )}+ />+ </FormCardContent>+ ) : null}+ <FormCardFooter>+ <FormCardFooterInfo>+ Learn more about{" "}+ <Link+ href="https://docs.openstatus.dev/reference/status-page/#password"+ rel="noreferrer"+ target="_blank"+ >+ Protection+ </Link>+ .+ </FormCardFooterInfo>+ {locked ? (+ <Button type="button" asChild>+ <Link href="/settings/billing">+ <Lock />+ Upgrade+ </Link>+ </Button>+ ) : (+ <Button type="submit" disabled={isPending}>+ {isPending ? "Submitting..." : "Submit"}+ </Button>+ )}+ </FormCardFooter>+ </FormCard>+ </form>+ </Form>+ );+}diff --git a/apps/dashboard/src/components/forms/status-page/form-password-protection.tsx b/apps/dashboard/src/components/forms/status-page/form-password-protection.tsxdeleted file mode 100644index b92eb3a80..000000000--- a/apps/dashboard/src/components/forms/status-page/form-password-protection.tsx+++ /dev/null@@ -1,160 +0,0 @@-"use client";--import { Link } from "@/components/common/link";-import {- FormCard,- FormCardContent,- FormCardDescription,- FormCardFooter,- FormCardFooterInfo,- FormCardHeader,- FormCardTitle,- FormCardUpgrade,-} from "@/components/forms/form-card";-import { Button } from "@/components/ui/button";-import { Checkbox } from "@/components/ui/checkbox";-import {- Form,- FormControl,- FormDescription,- FormField,- FormItem,- FormLabel,- FormMessage,-} from "@/components/ui/form";-import { Input } from "@/components/ui/input";-import { zodResolver } from "@hookform/resolvers/zod";-import { isTRPCClientError } from "@trpc/client";-import { Lock } from "lucide-react";-import { useTransition } from "react";-import { useForm } from "react-hook-form";-import { toast } from "sonner";-import { z } from "zod";--const schema = z.object({- passwordProtected: z.boolean().optional(),- password: z.string().optional(),-});--type FormValues = z.infer<typeof schema>;--export function FormPasswordProtection({- locked,- defaultValues,- onSubmit,- ...props-}: Omit<React.ComponentProps<"form">, "onSubmit"> & {- locked?: boolean;- defaultValues?: FormValues;- onSubmit: (values: FormValues) => Promise<void>;-}) {- const [isPending, startTransition] = useTransition();- const form = useForm<FormValues>({- resolver: zodResolver(schema),- defaultValues: defaultValues ?? {- passwordProtected: false,- password: "",- },- });-- function submitAction(values: FormValues) {- if (isPending) return;-- startTransition(async () => {- try {- const promise = onSubmit(values);- toast.promise(promise, {- loading: "Saving...",- success: "Saved",- error: (error) => {- if (isTRPCClientError(error)) {- return error.message;- }- return "Failed to save";- },- });- await promise;- } catch (error) {- console.error(error);- }- });- }-- return (- <Form {...form}>- <form onSubmit={form.handleSubmit(submitAction)} {...props}>- <FormCard>- {locked ? <FormCardUpgrade /> : null}- <FormCardHeader>- <FormCardTitle>Password Protection</FormCardTitle>- <FormCardDescription>- Protect your status page with a password.- </FormCardDescription>- </FormCardHeader>- <FormCardContent className="grid gap-4">- <FormField- control={form.control}- disabled={locked}- name="passwordProtected"- render={({ field }) => (- <FormItem className="flex flex-row items-start">- <FormControl>- <Checkbox- checked={field.value}- onCheckedChange={field.onChange}- />- </FormControl>- <div className="space-y-1">- <FormLabel>Enable Password Protection</FormLabel>- <FormDescription>- Hide the page from the public- </FormDescription>- </div>- </FormItem>- )}- />- <FormField- control={form.control}- name="password"- disabled={locked}- render={({ field }) => (- <FormItem>- <FormLabel>Password</FormLabel>- <FormControl>- <Input {...field} />- </FormControl>- <FormMessage />- </FormItem>- )}- />- </FormCardContent>- <FormCardFooter>- <FormCardFooterInfo>- Learn more about{" "}- <Link- href="https://docs.openstatus.dev/reference/status-page/#password"- rel="noreferrer"- target="_blank"- >- Password Protection- </Link>- .- </FormCardFooterInfo>- {locked ? (- <Button type="button" asChild>- <Link href="/settings/billing">- <Lock />- Upgrade- </Link>- </Button>- ) : (- <Button type="submit" disabled={isPending}>- {isPending ? "Submitting..." : "Submit"}- </Button>- )}- </FormCardFooter>- </FormCard>- </form>- </Form>- );-}diff --git a/apps/dashboard/src/components/forms/status-page/update.tsx b/apps/dashboard/src/components/forms/status-page/update.tsxindex 14231efb6..81cf5fc55 100644--- a/apps/dashboard/src/components/forms/status-page/update.tsx+++ b/apps/dashboard/src/components/forms/status-page/update.tsx@@ -12,7 +12,7 @@ import { FormDangerZone } from "./form-danger-zone";import { FormGeneral } from "./form-general";import { FormLinks } from "./form-links";import { FormMonitors } from "./form-monitors";-import { FormPasswordProtection } from "./form-password-protection";+import { FormPageAccess } from "./form-page-access";export function FormStatusPageUpdate() {const { id } = useParams<{ id: string }>();@@ -224,17 +224,28 @@ export function FormStatusPageUpdate() {}}configLink={configLink}/>- <FormPasswordProtection- locked={workspace.limits["password-protection"] === false}+ <FormPageAccess+ lockedMap={+ new Map([+ ["public", false],+ ["password", workspace.limits["password-protection"] === false],+ [+ "email-domain",+ workspace.limits["email-domain-protection"] === false,+ ],+ ])+ }defaultValues={{- passwordProtected: statusPage.passwordProtected ?? false,+ accessType: statusPage.accessType,password: statusPage.password ?? undefined,+ authEmailDomains: statusPage.authEmailDomains ?? [],}}onSubmit={async (values) => {await updatePasswordProtectionMutation.mutateAsync({id: Number.parseInt(id),- passwordProtected: values.passwordProtected ?? false,+ accessType: values.accessType,password: values.password,+ authEmailDomains: values.authEmailDomains,});}}/>diff --git a/apps/dashboard/src/app/(public)/login/layout.tsx b/apps/dashboard/src/components/layout/auth-layout.tsxsimilarity index 87%rename from apps/dashboard/src/app/(public)/login/layout.tsxrename to apps/dashboard/src/components/layout/auth-layout.tsxindex 9d91d11d4..14e660a83 100644--- a/apps/dashboard/src/app/(public)/login/layout.tsx+++ b/apps/dashboard/src/components/layout/auth-layout.tsx@@ -1,16 +1,6 @@import Image from "next/image";-import { redirect } from "next/navigation";--import { auth } from "@/lib/auth";--export default async function AuthLayout({- children,-}: {- children: React.ReactNode;-}) {- const session = await auth();- if (session) redirect("/");+export function AuthLayout({ children }: { children: React.ReactNode }) {return (<div className="grid min-h-screen grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-5"><aside className="col-span-1 flex w-full flex-col gap-4 border border-border bg-sidebar p-4 backdrop-blur-[2px] md:p-8 xl:col-span-2">diff --git a/apps/dashboard/src/data/plans.ts b/apps/dashboard/src/data/plans.tsindex 94626857b..9c7f3b305 100644--- a/apps/dashboard/src/data/plans.ts+++ b/apps/dashboard/src/data/plans.ts@@ -67,9 +67,18 @@ export const config: Record<value: "custom-domain",label: "Custom domain",},+ ],+ },+ "status-page-audience": {+ label: "Status Page Audience",+ features: [{value: "password-protection",- label: "Password-protected",+ label: "Password Protection (Basic)",+ },+ {+ value: "email-domain-protection",+ label: "Magic Link (Auth)",},],},diff --git a/apps/docs/src/content/docs/reference/status-page.mdx b/apps/docs/src/content/docs/reference/status-page.mdxindex 3657504cf..32451b571 100644--- a/apps/docs/src/content/docs/reference/status-page.mdx+++ b/apps/docs/src/content/docs/reference/status-page.mdx@@ -14,14 +14,17 @@ You slug is a unique identifier for your status page. It is used in the URL of yYou can configure a custom domain for your status page. e.g `status.example.com` => `https://status.example.com`-### Password+### Password (basic auth)-You can add a password for your status page to protect a status page. If you are not authenticated, you will get redirected to the `/protected`.+You can add a password for your status page to protect a status page. If you are not authenticated, you will get redirected to the `/login`.-The password is stored in plain text in a `cookie`, so keep the password easy and fun. You can share any page by appending the password via the `pw` search param like: `https://custom.stpg.dev/?pw=my-secret-password` and we will automatically authenticate the user. This can be useful to authenticate to private RSS feeds.+The password is stored in plain text in a `cookie`, so keep the password easy and fun. You can share any page by appending the password via the `pw` search param like: `https://[slug].openstatus.dev/?pw=my-secret-password` and we will automatically authenticate the user. This can be useful to authenticate to private RSS feeds.-> If you need an email confirmed status page, e.g. by whitelisting domains for specific partners who would access the page with a magic link, please contact [email protected] - we have that on our backlog and are happy to prioritze it.+### Magic Link (session auth)+You can secure your status page by restricting access to users with approved email domains. Users will receive a magic link sent to their email and, upon clicking it, will be authenticated via a session token.++This feature is available as an add-on for paid plans and is not included by default.### Favicondiff --git a/apps/server/src/routes/public/status.ts b/apps/server/src/routes/public/status.tsindex 749194395..af5060794 100644--- a/apps/server/src/routes/public/status.ts+++ b/apps/server/src/routes/public/status.ts@@ -45,7 +45,7 @@ status.get("/:slug", async (c) => {return c.json({ status: Status.Unknown });}- if (currentPage.passwordProtected) {+ if (currentPage.accessType !== "public") {return c.json({ status: Status.Unknown });}diff --git a/apps/server/src/routes/v1/monitors/post.ts b/apps/server/src/routes/v1/monitors/post.tsindex 6f8e00472..0a37fc548 100644--- a/apps/server/src/routes/v1/monitors/post.ts+++ b/apps/server/src/routes/v1/monitors/post.ts@@ -104,6 +104,7 @@ export function registerPostMonitor(api: typeof monitorsApi) {...rest,workspaceId: workspaceId,regions: regions ? regions.join(",") : undefined,+ description: input.description ?? undefined,headers: input.headers ? JSON.stringify(input.headers) : undefined,assertions: assert.length > 0 ? serialize(assert) : undefined,timeout: input.timeout || 45000,diff --git a/apps/server/src/routes/v1/monitors/put.ts b/apps/server/src/routes/v1/monitors/put.tsindex 3be57ca3e..acf45b8d3 100644--- a/apps/server/src/routes/v1/monitors/put.ts+++ b/apps/server/src/routes/v1/monitors/put.ts@@ -109,6 +109,7 @@ export function registerPutMonitor(api: typeof monitorsApi) {.set({...rest,regions: regions ? regions.join(",") : undefined,+ description: input.description ?? undefined,headers: input.headers ? JSON.stringify(input.headers) : undefined,assertions: assert.length > 0 ? serialize(assert) : undefined,timeout: input.timeout || 45000,diff --git a/apps/server/src/routes/v1/pages/get.ts b/apps/server/src/routes/v1/pages/get.tsindex c59409273..d1fd97a5c 100644--- a/apps/server/src/routes/v1/pages/get.ts+++ b/apps/server/src/routes/v1/pages/get.ts@@ -5,7 +5,7 @@ import { and, eq } from "@openstatus/db";import { db } from "@openstatus/db/src/db";import { page } from "@openstatus/db/src/schema";import type { pagesApi } from "./index";-import { PageSchema, ParamsSchema } from "./schema";+import { PageSchema, ParamsSchema, transformPageData } from "./schema";const getRoute = createRoute({method: "get",@@ -46,7 +46,7 @@ export function registerGetPage(api: typeof pagesApi) {});}- const data = PageSchema.parse(_page);+ const data = transformPageData(PageSchema.parse(_page));return c.json(data, 200);});diff --git a/apps/server/src/routes/v1/pages/get_all.ts b/apps/server/src/routes/v1/pages/get_all.tsindex 4d4f4212e..68c83e7b0 100644--- a/apps/server/src/routes/v1/pages/get_all.ts+++ b/apps/server/src/routes/v1/pages/get_all.ts@@ -4,7 +4,7 @@ import { openApiErrorResponses } from "@/libs/errors";import { db, eq } from "@openstatus/db";import { page } from "@openstatus/db/src/schema";import type { pagesApi } from "./index";-import { PageSchema } from "./schema";+import { PageSchema, transformPageData } from "./schema";const getAllRoute = createRoute({method: "get",@@ -33,7 +33,9 @@ export function registerGetAllPages(api: typeof pagesApi) {.from(page).where(eq(page.workspaceId, workspaceId));- const data = PageSchema.array().parse(_pages);+ const data = PageSchema.array()+ .parse(_pages)+ .map((page) => transformPageData(page));return c.json(data, 200);});diff --git a/apps/server/src/routes/v1/pages/post.ts b/apps/server/src/routes/v1/pages/post.tsindex b43e14b3e..e877278e3 100644--- a/apps/server/src/routes/v1/pages/post.ts+++ b/apps/server/src/routes/v1/pages/post.ts@@ -14,7 +14,7 @@ import { trackMiddleware } from "@/libs/middlewares";import { Events } from "@openstatus/analytics";import { isNumberArray } from "../utils";import type { pagesApi } from "./index";-import { PageSchema } from "./schema";+import { PageSchema, transformPageData } from "./schema";const postRoute = createRoute({method: "post",@@ -90,6 +90,26 @@ export function registerPostPage(api: typeof pagesApi) {});}+ if (+ !limits["password-protection"] &&+ (input?.accessType === "password" || input?.password)+ ) {+ throw new OpenStatusApiError({+ code: "PAYMENT_REQUIRED",+ message: "Upgrade for password protection",+ });+ }++ if (+ !limits["email-domain-protection"] &&+ (input?.accessType === "email-domain" || input?.authEmailDomains?.length)+ ) {+ throw new OpenStatusApiError({+ code: "PAYMENT_REQUIRED",+ message: "Upgrade for email domain protection",+ });+ }+if (subdomainSafeList.includes(input.slug)) {throw new OpenStatusApiError({code: "BAD_REQUEST",@@ -145,6 +165,9 @@ export function registerPostPage(api: typeof pagesApi) {...rest,workspaceId: workspaceId,customDomain: rest.customDomain ?? "", // TODO: make database migration to allow null+ accessType:+ rest.accessType ?? (rest.passwordProtected ? "password" : "public"),+ authEmailDomains: rest.authEmailDomains?.join(","),}).returning().get();@@ -161,7 +184,7 @@ export function registerPostPage(api: typeof pagesApi) {.run();}}- const data = PageSchema.parse(_page);+ const data = transformPageData(PageSchema.parse(_page));return c.json(data, 200);});}diff --git a/apps/server/src/routes/v1/pages/put.ts b/apps/server/src/routes/v1/pages/put.tsindex f376dd7e0..e9a1717a2 100644--- a/apps/server/src/routes/v1/pages/put.ts+++ b/apps/server/src/routes/v1/pages/put.ts@@ -13,7 +13,7 @@ import {} from "@openstatus/db/src/schema";import { isNumberArray } from "../utils";import type { pagesApi } from "./index";-import { PageSchema, ParamsSchema } from "./schema";+import { PageSchema, ParamsSchema, transformPageData } from "./schema";const putRoute = createRoute({method: "put",@@ -76,6 +76,26 @@ export function registerPutPage(api: typeof pagesApi) {});}+ if (+ limits["email-domain-protection"] === false &&+ (input?.accessType === "email-domain" || input?.authEmailDomains?.length)+ ) {+ throw new OpenStatusApiError({+ code: "PAYMENT_REQUIRED",+ message: "Upgrade for email domain protection",+ });+ }++ if (+ limits["password-protection"] === false &&+ (input?.accessType === "password" || input?.password)+ ) {+ throw new OpenStatusApiError({+ code: "PAYMENT_REQUIRED",+ message: "Upgrade for password protection",+ });+ }+const _page = await db.select().from(page)@@ -147,6 +167,9 @@ export function registerPutPage(api: typeof pagesApi) {.set({...rest,customDomain: input.customDomain ?? "",+ accessType:+ rest.accessType ?? (rest.passwordProtected ? "password" : "public"),+ authEmailDomains: rest.authEmailDomains?.join(","),updatedAt: new Date(),}).where(eq(page.id, _page.id))@@ -188,10 +211,12 @@ export function registerPutPage(api: typeof pagesApi) {}}- const data = PageSchema.parse({- ...newPage,- monitors: monitors || currentMonitorsToPages,- });+ const data = transformPageData(+ PageSchema.parse({+ ...newPage,+ monitors: monitors || currentMonitorsToPages,+ }),+ );return c.json(data, 200);});diff --git a/apps/server/src/routes/v1/pages/schema.ts b/apps/server/src/routes/v1/pages/schema.tsindex 59f5b4fd3..3a4f043ee 100644--- a/apps/server/src/routes/v1/pages/schema.ts+++ b/apps/server/src/routes/v1/pages/schema.ts@@ -53,17 +53,34 @@ export const PageSchema = z}),passwordProtected: z.boolean().optional().prefault(false).openapi({description:- "Make the page password protected. Used with the 'passwordProtected' property.",+ "Deprecated in favor of `accessType`. Used to set the password protection type. Returns true if `accessType` is set to 'password' and false otherwise.",example: true,+ deprecated: true,}),+ accessType: z+ .enum(["public", "password", "email-domain"])+ .default("public")+ .openapi({+ description: "The access type of the page",+ example: "public",+ }),password: z.string().optional().nullish().openapi({description: "Your password to protect the page from the public",example: "hidden-password",}),+ authEmailDomains: z+ .array(z.string())+ .optional()+ .nullish()+ .openapi({+ description: "The email domains of the page",+ example: ["example.com", "example.org"],+ }),showMonitorValues: z.boolean().optional().nullish().prefault(true).openapi({description:- "Displays the total and failed request numbers for each monitor",+ "Displays the total and failed request numbers for each monitor. Deprecated and will be removed in the future in favor for `configuration` property.",example: true,+ deprecated: true,}),monitors: z.array(z.number())@@ -89,3 +106,19 @@ export const PageSchema = z.openapi("Page");export type PageSchema = z.infer<typeof PageSchema>;++/**+ * Transforms page data to ensure passwordProtected reflects accessType+ * This should be used when parsing page data for responses+ *+ * NOTE: cannot be used in `PageSchema` because `.omit` is not supported otherwise+ */+export function transformPageData<+ T extends { accessType?: string; passwordProtected?: boolean },+>(data: T): T & { passwordProtected: boolean } {+ return {+ ...data,+ passwordProtected:+ data.accessType === "password" ? true : data.passwordProtected ?? false,+ };+}diff --git a/apps/status-page/next-env.d.ts b/apps/status-page/next-env.d.tsindex 9edff1c7c..c4b7818fb 100644--- a/apps/status-page/next-env.d.ts+++ b/apps/status-page/next-env.d.ts@@ -1,6 +1,6 @@/// <reference types="next" />/// <reference types="next/image-types/global" />-import "./.next/types/routes.d.ts";+import "./.next/dev/types/routes.d.ts";// NOTE: This file should not be edited// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.diff --git a/apps/status-page/package.json b/apps/status-page/package.jsonindex 4f898d0a1..d081e2d47 100644--- a/apps/status-page/package.json+++ b/apps/status-page/package.json@@ -11,6 +11,8 @@"tsc": "tsc --noEmit"},"dependencies": {+ "@auth/core": "0.40.0",+ "@auth/drizzle-adapter": "1.10.0","@date-fns/tz": "1.2.0","@date-fns/utc": "2.1.0","@dnd-kit/core": "6.3.1",diff --git a/apps/status-page/src/app/(status-page)/[domain]/(private)/layout.tsx b/apps/status-page/src/app/(status-page)/[domain]/(auth)/layout.tsxsimilarity index 50%rename from apps/status-page/src/app/(status-page)/[domain]/(private)/layout.tsxrename to apps/status-page/src/app/(status-page)/[domain]/(auth)/layout.tsxindex 443a1fd9e..e94252f4a 100644--- a/apps/status-page/src/app/(status-page)/[domain]/(private)/layout.tsx+++ b/apps/status-page/src/app/(status-page)/[domain]/(auth)/layout.tsx@@ -1,7 +1,20 @@import { Footer } from "@/components/nav/footer";+import { getQueryClient, trpc } from "@/lib/trpc/server";import { Suspense } from "react";-export default function Layout({ children }: { children: React.ReactNode }) {+export default async function Layout({+ children,+ params,+}: {+ children: React.ReactNode;+ params: Promise<{ domain: string }>;+}) {+ const queryClient = getQueryClient();+ const { domain } = await params;+ await queryClient.prefetchQuery(+ trpc.statusPage.get.queryOptions({ slug: domain }),+ );+return (<Suspense><div className="flex min-h-screen flex-col gap-4">diff --git a/apps/status-page/src/app/(status-page)/[domain]/(auth)/login/_components/section-magic-link.tsx b/apps/status-page/src/app/(status-page)/[domain]/(auth)/login/_components/section-magic-link.tsxnew file mode 100644index 000000000..eb8fbaa9f--- /dev/null+++ b/apps/status-page/src/app/(status-page)/[domain]/(auth)/login/_components/section-magic-link.tsx@@ -0,0 +1,90 @@+"use client";++import {+ EmptyStateContainer,+ EmptyStateDescription,+ EmptyStateTitle,+} from "@/components/content/empty-state";+import {+ Section,+ SectionDescription,+ SectionHeader,+ SectionTitle,+} from "@/components/content/section";+import { FormEmail, type FormValues } from "@/components/forms/form-email";+import { Button } from "@/components/ui/button";+import { Inbox } from "lucide-react";+import { useParams } from "next/navigation";+import { useState } from "react";+import { flushSync } from "react-dom";+import { signInWithResendAction } from "../actions";++export function SectionMagicLink() {+ const { domain } = useParams<{ domain: string }>();+ const [state, setState] = useState<"idle" | "pending" | "success">("idle");++ async function submitAction(values: FormValues) {+ // NOTE: we can improve a bit if we use pathname instead of subdomain/hostname+ // like http://localhost:3000/hello, the redirectTo should be http://localhost:3000/hello+ // this only affects local development if not using chrome and subdomain+ const redirectTo =+ process.env.NODE_ENV === "development"+ ? `http://${window.location.hostname}:${window.location.port}`+ : `https://${window.location.hostname}`;++ const formData = new FormData();+ formData.append("redirectTo", redirectTo);+ formData.append("email", values.email);+ formData.append("domain", domain);++ // we need this because submitAction is called in a startTransition and we need to update the state immediately+ flushSync(() => setState("pending"));++ try {+ await new Promise((resolve) => setTimeout(resolve, 1000));+ await signInWithResendAction(formData);+ setState("success");+ } catch (error) {+ setState("idle");+ throw error;+ }+ }++ return (+ <Section className="m-auto w-full max-w-lg rounded-lg border bg-card p-4">+ <SectionHeader>+ <SectionTitle>Authenticate</SectionTitle>+ <SectionDescription>+ Enter your email to receive a magic link for accessing the status+ page. Note: Only emails from approved domains are accepted.+ </SectionDescription>+ </SectionHeader>+ {state !== "success" ? (+ <div className="flex flex-col gap-2">+ <FormEmail id="email-form" onSubmit={submitAction} />+ <Button+ type="submit"+ form="email-form"+ disabled={state === "pending"}+ >+ {state === "pending" ? "Submitting..." : "Submit"}+ </Button>+ </div>+ ) : (+ <SuccessState />+ )}+ </Section>+ );+}++function SuccessState() {+ return (+ <EmptyStateContainer>+ <Inbox className="size-4 shrink-0" />+ <EmptyStateTitle>Check your inbox!</EmptyStateTitle>+ <EmptyStateDescription>+ Access the status page by clicking the link in the email.+ </EmptyStateDescription>+ </EmptyStateContainer>+ );+}diff --git a/apps/status-page/src/app/(status-page)/[domain]/(private)/protected/page.tsx b/apps/status-page/src/app/(status-page)/[domain]/(auth)/login/_components/section-password.tsxsimilarity index 97%rename from apps/status-page/src/app/(status-page)/[domain]/(private)/protected/page.tsxrename to apps/status-page/src/app/(status-page)/[domain]/(auth)/login/_components/section-password.tsxindex d765517c2..fea4d1626 100644--- a/apps/status-page/src/app/(status-page)/[domain]/(private)/protected/page.tsx+++ b/apps/status-page/src/app/(status-page)/[domain]/(auth)/login/_components/section-password.tsx@@ -14,7 +14,7 @@ import { useTRPC } from "@/lib/trpc/client";import { useMutation } from "@tanstack/react-query";import { useParams, useRouter, useSearchParams } from "next/navigation";-export default function PrivatePage() {+export function SectionPassword() {const { domain } = useParams<{ domain: string }>();const searchParams = useSearchParams();const trpc = useTRPC();diff --git a/apps/status-page/src/app/(status-page)/[domain]/(auth)/login/actions.ts b/apps/status-page/src/app/(status-page)/[domain]/(auth)/login/actions.tsnew file mode 100644index 000000000..87c433fcc--- /dev/null+++ b/apps/status-page/src/app/(status-page)/[domain]/(auth)/login/actions.ts@@ -0,0 +1,37 @@+"use server";++import { signIn } from "@/lib/auth";+import { getQueryClient, trpc } from "@/lib/trpc/server";+import { AuthError } from "next-auth";+import { isRedirectError } from "next/dist/client/components/redirect-error";++export async function signInWithResendAction(formData: FormData) {+ try {+ const email = formData.get("email") as string;+ const redirectTo = formData.get("redirectTo") as string;+ const domain = formData.get("domain") as string;++ if (!email || !redirectTo) {+ throw new Error("Email and redirectTo are required");+ }++ const queryClient = getQueryClient();+ // NOTE: throws an error if the email domain is not allowed+ await queryClient.fetchQuery(+ trpc.statusPage.validateEmailDomain.queryOptions({ slug: domain, email }),+ );++ await signIn("resend", {+ email,+ redirectTo,+ });+ } catch (e) {+ // NOTE: https://github.com/nextauthjs/next-auth/discussions/9389+ if (isRedirectError(e)) return;+ console.error(e);+ if (e instanceof AuthError) {+ throw new Error(`Authentication error: ${e.type}`);+ }+ throw e;+ }+}diff --git a/apps/status-page/src/app/(status-page)/[domain]/(auth)/login/page.tsx b/apps/status-page/src/app/(status-page)/[domain]/(auth)/login/page.tsxnew file mode 100644index 000000000..2eeec81fb--- /dev/null+++ b/apps/status-page/src/app/(status-page)/[domain]/(auth)/login/page.tsx@@ -0,0 +1,25 @@+"use client";++import { useTRPC } from "@/lib/trpc/client";+import { useQuery } from "@tanstack/react-query";+import { notFound, useParams } from "next/navigation";+import { SectionMagicLink } from "./_components/section-magic-link";+import { SectionPassword } from "./_components/section-password";++export default function LoginPage() {+ const { domain } = useParams<{ domain: string }>();+ const trpc = useTRPC();+ const { data: page } = useQuery(+ trpc.statusPage.get.queryOptions({ slug: domain }),+ );++ if (page?.accessType === "password") {+ return <SectionPassword />;+ }++ if (page?.accessType === "email-domain") {+ return <SectionMagicLink />;+ }++ return notFound();+}diff --git a/apps/status-page/src/app/(status-page)/[domain]/(public)/feed/[type]/route.ts b/apps/status-page/src/app/(status-page)/[domain]/(public)/feed/[type]/route.tsindex 773f02fa6..be2bc2336 100644--- a/apps/status-page/src/app/(status-page)/[domain]/(public)/feed/[type]/route.ts+++ b/apps/status-page/src/app/(status-page)/[domain]/(public)/feed/[type]/route.ts@@ -1,3 +1,4 @@+import { auth } from "@/lib/auth";import { getBaseUrl } from "@/lib/base-url";import { getQueryClient, trpc } from "@/lib/trpc/server";import { Feed } from "feed";@@ -20,6 +21,7 @@ export async function GET(try {const queryClient = getQueryClient();const { domain, type } = await props.params;+if (!["rss", "atom"].includes(type)) return notFound();const page = await queryClient.fetchQuery(@@ -27,13 +29,22 @@ export async function GET();if (!page) return notFound();- if (page.passwordProtected) {+ if (page.accessType === "password") {const url = new URL(_request.url);const password = url.searchParams.get("pw");console.log({ url, page, password });if (password !== page.password) return unauthorized();}+ if (page.accessType === "email-domain") {+ const session = await auth();+ const user = session?.user;+ const allowedDomains = page.authEmailDomains ?? [];+ if (!user || !user.email) return unauthorized();+ if (!allowedDomains.includes(user.email.split("@")[1]))+ return unauthorized();+ }+const baseUrl = getBaseUrl({slug: page.slug,customDomain: page.customDomain,diff --git a/apps/status-page/src/app/(status-page)/[domain]/(public)/feed/json/route.ts b/apps/status-page/src/app/(status-page)/[domain]/(public)/feed/json/route.tsindex ab65b85d9..d8f6aaea2 100644--- a/apps/status-page/src/app/(status-page)/[domain]/(public)/feed/json/route.ts+++ b/apps/status-page/src/app/(status-page)/[domain]/(public)/feed/json/route.ts@@ -1,3 +1,4 @@+import { auth } from "@/lib/auth";import { getQueryClient, trpc } from "@/lib/trpc/server";import { notFound, unauthorized } from "next/navigation";@@ -25,13 +26,22 @@ export async function GET(if (!_page) return notFound();- if (_page.passwordProtected) {+ if (_page.accessType === "password") {const url = new URL(_request.url);const password = url.searchParams.get("pw");console.log({ url, _page, password });if (password !== _page.password) return unauthorized();}+ if (_page.accessType === "email-domain") {+ const session = await auth();+ const user = session?.user;+ const allowedDomains = _page.authEmailDomains ?? [];+ if (!user || !user.email) return unauthorized();+ if (!allowedDomains.includes(user.email.split("@")[1]))+ return unauthorized();+ }+const page = await queryClient.fetchQuery(trpc.statusPage.get.queryOptions({ slug: domain }),);diff --git a/apps/status-page/src/app/(status-page)/[domain]/layout.tsx b/apps/status-page/src/app/(status-page)/[domain]/layout.tsxindex 90c088799..144ad54dc 100644--- a/apps/status-page/src/app/(status-page)/[domain]/layout.tsx+++ b/apps/status-page/src/app/(status-page)/[domain]/layout.tsx@@ -114,17 +114,13 @@ export async function generateMetadata({},twitter: {...twitterMetadata,- images: [- `/api/og/page?slug=${page?.slug}&passwordProtected=${page?.passwordProtected}`,- ],+ images: [`/api/og/page?slug=${page?.slug}`],title: page?.title,description: page?.description,},openGraph: {...ogMetadata,- images: [- `/api/og/page?slug=${page?.slug}&passwordProtected=${page?.passwordProtected}`,- ],+ images: [`/api/og/page?slug=${page?.slug}`],title: page?.title,description: page?.description,},diff --git a/apps/web/src/app/api/auth/[...nextauth]/route.ts b/apps/status-page/src/app/api/auth/[...nextauth]/route.tssimilarity index 100%rename from apps/web/src/app/api/auth/[...nextauth]/route.tsrename to apps/status-page/src/app/api/auth/[...nextauth]/route.tsdiff --git a/apps/status-page/src/app/api/trpc/edge/[trpc]/route.ts b/apps/status-page/src/app/api/trpc/edge/[trpc]/route.tsindex 2c1fc5285..ee69b118c 100644--- a/apps/status-page/src/app/api/trpc/edge/[trpc]/route.ts+++ b/apps/status-page/src/app/api/trpc/edge/[trpc]/route.ts@@ -1,6 +1,7 @@import { fetchRequestHandler } from "@trpc/server/adapters/fetch";import type { NextRequest } from "next/server";+import { auth } from "@/lib/auth";import { createTRPCContext } from "@openstatus/api";import { edgeRouter } from "@openstatus/api/src/edge";@@ -11,7 +12,7 @@ const handler = (req: NextRequest) =>endpoint: "/api/trpc/edge",router: edgeRouter,req: req,- createContext: () => createTRPCContext({ req }),+ createContext: () => createTRPCContext({ req, auth }),onError: ({ error }) => {console.log("Error in tRPC handler (edge)");console.error(error);diff --git a/apps/status-page/src/app/api/trpc/lambda/[trpc]/route.ts b/apps/status-page/src/app/api/trpc/lambda/[trpc]/route.tsindex b36568088..1352dcf0c 100644--- a/apps/status-page/src/app/api/trpc/lambda/[trpc]/route.ts+++ b/apps/status-page/src/app/api/trpc/lambda/[trpc]/route.ts@@ -1,6 +1,7 @@import { fetchRequestHandler } from "@trpc/server/adapters/fetch";import type { NextRequest } from "next/server";+import { auth } from "@/lib/auth";import { createTRPCContext } from "@openstatus/api";import { lambdaRouter } from "@openstatus/api/src/lambda";@@ -12,7 +13,7 @@ const handler = (req: NextRequest) =>endpoint: "/api/trpc/lambda",router: lambdaRouter,req: req,- createContext: () => createTRPCContext({ req }),+ createContext: () => createTRPCContext({ req, auth }),onError: ({ error }) => {console.log("Error in tRPC handler (lambda)");console.error(error);diff --git a/apps/status-page/src/components/forms/form-email.tsx b/apps/status-page/src/components/forms/form-email.tsxnew file mode 100644index 000000000..7b4f206b1--- /dev/null+++ b/apps/status-page/src/components/forms/form-email.tsx@@ -0,0 +1,85 @@+"use client";++import { Form } from "@/components/ui/form";+import {+ FormControl,+ FormField,+ FormItem,+ FormLabel,+} from "@/components/ui/form";+import { Input } from "@/components/ui/input";+import { zodResolver } from "@hookform/resolvers/zod";+import { isTRPCClientError } from "@trpc/client";+import { useTransition } from "react";+import { useForm } from "react-hook-form";+import { toast } from "sonner";+import { z } from "zod";++const schema = z.object({+ email: z.string().email(),+});++export type FormValues = z.infer<typeof schema>;++export function FormEmail({+ onSubmit,+ ...props+}: Omit<React.ComponentProps<"form">, "onSubmit"> & {+ onSubmit: (values: FormValues) => Promise<void>;+}) {+ const form = useForm<FormValues>({+ resolver: zodResolver(schema),+ defaultValues: {+ email: "",+ },+ });+ const [isPending, startTransition] = useTransition();++ function submitAction(values: FormValues) {+ if (isPending) return;++ startTransition(async () => {+ try {+ const promise = onSubmit(values);+ toast.promise(promise, {+ loading: "Confirming...",+ success: "Confirmed",+ error: (error) => {+ console.error(error);+ if (isTRPCClientError(error)) {+ form.setError("email", { message: error.message });+ return error.message;+ }+ if (error instanceof Error) {+ form.setError("email", { message: error.message });+ return error.message;+ }+ return "Failed to confirm";+ },+ });+ await promise;+ } catch (error) {+ console.error(error);+ }+ });+ }++ return (+ <Form {...form}>+ <form onSubmit={form.handleSubmit(submitAction)} {...props}>+ <FormField+ control={form.control}+ name="email"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Email</FormLabel>+ <FormControl>+ <Input type="email" {...field} />+ </FormControl>+ </FormItem>+ )}+ />+ </form>+ </Form>+ );+}diff --git a/apps/status-page/src/components/nav/header.tsx b/apps/status-page/src/components/nav/header.tsxindex 7be819b6c..fd5b06a71 100644--- a/apps/status-page/src/components/nav/header.tsx+++ b/apps/status-page/src/components/nav/header.tsx@@ -1,7 +1,10 @@"use client";import { Link } from "@/components/common/link";-import { StatusUpdates } from "@/components/status-page/status-updates";+import {+ type StatusUpdateType,+ StatusUpdates,+} from "@/components/status-page/status-updates";import { Button } from "@/components/ui/button";import {Sheet,@@ -19,6 +22,7 @@ import {import { usePathnamePrefix } from "@/hooks/use-pathname-prefix";import { useTRPC } from "@/lib/trpc/client";import { cn } from "@/lib/utils";+import type { RouterOutputs } from "@openstatus/api";import { useMutation, useQuery } from "@tanstack/react-query";import { isTRPCClientError } from "@trpc/client";import { Menu, MessageCircleMore } from "lucide-react";@@ -27,6 +31,8 @@ import { useParams, usePathname } from "next/navigation";import { useState } from "react";import { toast } from "sonner";+type Page = RouterOutputs["statusPage"]["get"];+function useNav() {const pathname = usePathname();const prefix = usePathnamePrefix();@@ -50,6 +56,21 @@ function useNav() {];}+function getStatusUpdateTypes(page: Page): StatusUpdateType[] {+ if (!page) return [];++ // NOTE: rss or json are not supported because of authentication+ if (page?.accessType === "email-domain") {+ return ["email"] as const;+ }++ if (page?.workspacePlan === "free") {+ return ["slack", "rss", "json"] as const;+ }++ return ["email", "slack", "rss", "json"] as const;+}+export function Header(props: React.ComponentProps<"header">) {const trpc = useTRPC();const { domain } = useParams<{ domain: string }>();@@ -82,12 +103,6 @@ export function Header(props: React.ComponentProps<"header">) {}),);- const types = (- page?.workspacePlan === "free"- ? ["slack", "rss", "json"]- : ["email", "slack", "rss", "json"]- ) satisfies ("email" | "rss" | "ssh" | "json" | "slack")[];-return (<header {...props}><nav className="mx-auto flex max-w-2xl items-center justify-between gap-3 px-3 py-2">@@ -132,7 +147,7 @@ export function Header(props: React.ComponentProps<"header">) {<GetInTouch buttonType="icon" link={page.contactUrl} />) : null}<StatusUpdates- types={types}+ types={getStatusUpdateTypes(page)}onSubscribe={async (email) => {await subscribeMutation.mutateAsync({ slug: domain, email });}}diff --git a/apps/status-page/src/components/status-page/status-updates.tsx b/apps/status-page/src/components/status-page/status-updates.tsxindex 5e2e856c6..f4d83ffa4 100644--- a/apps/status-page/src/components/status-page/status-updates.tsx+++ b/apps/status-page/src/components/status-page/status-updates.tsx@@ -17,10 +17,21 @@ import type { RouterOutputs } from "@openstatus/api";import { Check, Copy, Inbox } from "lucide-react";import { useState } from "react";-type StatusUpdateType = "email" | "rss" | "ssh" | "json" | "slack";+export type StatusUpdateType = "email" | "rss" | "ssh" | "json" | "slack";type Page = NonNullable<RouterOutputs["statusPage"]["get"]>;+function getUpdateLink(type: "rss" | "json" | "atom", page?: Page | null) {+ const baseUrl = getBaseUrl({+ slug: page?.slug,+ customDomain: page?.customDomain,+ });++ return `${baseUrl}/feed/${type}${+ page?.accessType === "password" ? `?pw=${page?.password}` : ""+ }`;+}+// TODO: use domain instead of openstatus subdomain if availableinterface StatusUpdatesProps extends React.ComponentProps<typeof Button> {@@ -37,10 +48,8 @@ export function StatusUpdates({...props}: StatusUpdatesProps) {const [success, setSuccess] = useState(false);- const baseUrl = getBaseUrl({- slug: page?.slug,- customDomain: page?.customDomain,- });++ if (types.length === 0) return null;return (<Popover>@@ -55,7 +64,7 @@ export function StatusUpdates({</Button></PopoverTrigger><PopoverContent align="end" className="w-80 overflow-hidden p-0">- <Tabs defaultValue="email">+ <Tabs defaultValue={types[0]}><TabsList className="w-full rounded-none border-b">{types.includes("email") ? (<TabsTrigger value="email">Email</TabsTrigger>@@ -105,9 +114,7 @@ export function StatusUpdates({<CopyInputButtonclassName="w-full"id="rss"- value={`${baseUrl}/feed/rss${- page?.passwordProtected ? `?pw=${page?.password}` : ""- }`}+ value={getUpdateLink("rss", page)}/></div><Separator />@@ -116,9 +123,7 @@ export function StatusUpdates({<CopyInputButtonclassName="w-full"id="atom"- value={`${baseUrl}/feed/atom${- page?.passwordProtected ? `?pw=${page?.password}` : ""- }`}+ value={getUpdateLink("atom", page)}/></div></TabsContent>@@ -128,9 +133,7 @@ export function StatusUpdates({<CopyInputButtonclassName="w-full"id="json"- value={`${baseUrl}/feed/json${- page?.passwordProtected ? `?pw=${page?.password}` : ""- }`}+ value={getUpdateLink("json", page)}/></div></TabsContent>@@ -153,9 +156,7 @@ export function StatusUpdates({<CopyInputButtonclassName="w-full"id="slack"- value={`/feed subscribe ${baseUrl}/feed/rss${- page?.passwordProtected ? `?pw=${page?.password}` : ""- }`}+ value={`/feed subscribe ${getUpdateLink("rss", page)}`}/></div></TabsContent>diff --git a/apps/status-page/src/lib/auth/adapter.ts b/apps/status-page/src/lib/auth/adapter.tsnew file mode 100644index 000000000..170c4310d--- /dev/null+++ b/apps/status-page/src/lib/auth/adapter.ts@@ -0,0 +1,24 @@+import { DrizzleAdapter } from "@auth/drizzle-adapter";+import type { Adapter } from "next-auth/adapters";++import { db } from "@openstatus/db";+import {+ verificationToken,+ viewer,+ viewerAccounts,+ viewerSession,+} from "@openstatus/db/src/schema";++export const adapter: Adapter = {+ ...DrizzleAdapter(db, {+ // @ts-ignore+ usersTable: viewer,+ // NOTE: only need accounts for external providers+ // @ts-ignore+ accountsTable: viewerAccounts,+ // @ts-ignore+ sessionsTable: viewerSession,+ // @ts-ignore+ verificationTokensTable: verificationToken,+ }),+};diff --git a/apps/status-page/src/lib/auth/index.ts b/apps/status-page/src/lib/auth/index.tsnew file mode 100644index 000000000..de82813a4--- /dev/null+++ b/apps/status-page/src/lib/auth/index.ts@@ -0,0 +1,63 @@+import type { DefaultSession } from "next-auth";+import NextAuth, { AuthError } from "next-auth";++import { db, eq } from "@openstatus/db";+import { viewer } from "@openstatus/db/src/schema";++import { getValidCustomDomain } from "@/lib/domain";+import { getQueryClient, trpc } from "@/lib/trpc/server";+import { headers } from "next/headers";+import { adapter } from "./adapter";+import { ResendProvider } from "./providers";++export type { DefaultSession };++export const { handlers, signIn, signOut, auth } = NextAuth({+ debug: process.env.NODE_ENV === "development",+ adapter,+ providers: [ResendProvider],+ callbacks: {+ async signIn(params) {+ const _headers = await headers();+ const host = _headers.get("host");++ if (!host) throw new AuthError("No host found");++ const req = new Request(host, { headers: new Headers(_headers) });+ const { prefix } = getValidCustomDomain(req);++ if (!prefix || !params.user.email) return false;++ const queryClient = getQueryClient();+ // NOTE: throws an error if the email domain is not allowed+ const query = await queryClient.fetchQuery(+ trpc.statusPage.validateEmailDomain.queryOptions({+ slug: prefix,+ email: params.user.email,+ }),+ );++ if (!query) return false;++ if (params.account?.provider === "resend") {+ // if the user is new, the id is the verification_token and not the viewer id, so we cannot update the viewer+ if (Number.isNaN(Number(params.user.id))) return true;+ await db+ .update(viewer)+ .set({ updatedAt: new Date() })+ .where(eq(viewer.id, Number(params.user.id)))+ .run();++ return true;+ }++ return false;+ },+ redirect: async (params) => {+ return params.url;+ },+ async session(params) {+ return params.session;+ },+ },+});diff --git a/apps/status-page/src/lib/auth/providers.ts b/apps/status-page/src/lib/auth/providers.tsnew file mode 100644index 000000000..b18d3bbe1--- /dev/null+++ b/apps/status-page/src/lib/auth/providers.ts@@ -0,0 +1,33 @@+import { getQueryClient, trpc } from "@/lib/trpc/server";+import { EmailClient } from "@openstatus/emails";+import Resend from "next-auth/providers/resend";+import { getValidCustomDomain } from "../domain";++export const ResendProvider = Resend({+ apiKey: undefined,+ async sendVerificationRequest(params) {+ const url = params.url;+ const email = params.identifier;++ const emailClient = new EmailClient({+ apiKey: process.env.RESEND_API_KEY ?? "",+ });++ const { prefix } = getValidCustomDomain(params.request);++ if (!prefix) return;++ const queryClient = getQueryClient();+ const query = await queryClient.fetchQuery(+ trpc.statusPage.validateEmailDomain.queryOptions({ slug: prefix, email }),+ );++ if (!query) return;++ await emailClient.sendStatusPageMagicLink({+ page: query.page.title,+ link: url,+ to: params.identifier,+ });+ },+});diff --git a/apps/status-page/src/lib/domain.ts b/apps/status-page/src/lib/domain.tsnew file mode 100644index 000000000..cb5f06941--- /dev/null+++ b/apps/status-page/src/lib/domain.ts@@ -0,0 +1,86 @@+import type { NextRequest } from "next/server";++export const getValidSubdomain = (host?: string | null) => {+ let subdomain: string | null = null;+ if (!host && typeof window !== "undefined") {+ // On client side, get the host from window+ // biome-ignore lint: to fix later+ host = window.location.host;+ }++ // Exclude localhost and IP addresses from being treated as subdomains+ if (+ host?.match(/^(localhost|127\\.0\\.0\\.1|::1|\\d+\\.\\d+\\.\\d+\\.\\d+)/)+ ) {+ return null;+ }++ // Handle subdomains of localhost (e.g., hello.localhost:3000)+ if (host?.match(/^([^.]+)\.localhost(:\d+)?$/)) {+ const match = host.match(/^([^.]+)\.localhost(:\d+)?$/);+ return match?.[1] || null;+ }++ // we should improve here for custom vercel deploy page+ if (host?.includes(".") && !host.includes(".vercel.app")) {+ const candidate = host.split(".")[0];+ if (candidate && !candidate.includes("www")) {+ // Valid candidate+ subdomain = candidate;+ }+ }++ // In case the host is a custom domain+ if (+ host &&+ !(+ host?.includes("stpg.dev") ||+ host?.includes("openstatus.dev") ||+ host?.endsWith(".vercel.app")+ )+ ) {+ subdomain = host;+ }+ return subdomain;+};++export const getValidCustomDomain = (req: NextRequest | Request) => {+ const url = "nextUrl" in req ? req.nextUrl.clone() : new URL(req.url);+ const headers = req.headers;+ const host = headers.get("x-forwarded-host");++ let prefix = "";+ let type: "hostname" | "pathname";++ const hostnames = host?.split(/[.:]/) ?? url.host.split(/[.:]/);+ const pathnames = url.pathname.split("/");++ const subdomain = getValidSubdomain(url.host);+ console.log({+ hostnames,+ pathnames,+ host,+ urlHost: url.host,+ subdomain,+ });++ if (+ hostnames.length > 2 &&+ hostnames[0] !== "www" &&+ !url.host.endsWith(".vercel.app")+ ) {+ prefix = hostnames[0].toLowerCase();+ type = "hostname";+ } else {+ prefix = pathnames[1].toLowerCase();+ type = "pathname";+ }++ if (subdomain !== null) {+ prefix = subdomain.toLowerCase();+ }++ console.log({ type, prefix });++ return { type, prefix };+};diff --git a/apps/status-page/src/next-auth.d.ts b/apps/status-page/src/next-auth.d.tsindex 1b70e4384..66e0e36a0 100644--- a/apps/status-page/src/next-auth.d.ts+++ b/apps/status-page/src/next-auth.d.ts@@ -1,5 +1,5 @@-import type { User as DefaultUserSchema } from "@openstatus/db/src/schema";+import type { Viewer as DefaultViewerSchema } from "@openstatus/db/src/schema";declare module "next-auth" {- interface User extends DefaultUserSchema {}+ interface User extends DefaultViewerSchema {}}diff --git a/apps/status-page/src/proxy.ts b/apps/status-page/src/proxy.tsindex d43343ddc..9fc6ca8a9 100644--- a/apps/status-page/src/proxy.ts+++ b/apps/status-page/src/proxy.ts@@ -1,10 +1,13 @@-import { type NextRequest, NextResponse } from "next/server";+import { NextResponse } from "next/server";++import { auth } from "@/lib/auth";import { db, sql } from "@openstatus/db";-import { page } from "@openstatus/db/src/schema";+import { page, selectPageSchema } from "@openstatus/db/src/schema";+import { getValidSubdomain } from "./lib/domain";import { createProtectedCookieKey } from "./lib/protected";-export default async function _proxy1(req: NextRequest) {+export default auth(async (req) => {const url = req.nextUrl.clone();const response = NextResponse.next();const cookies = req.cookies;@@ -48,7 +51,7 @@ export default async function _proxy1(req: NextRequest) {return response;}- const _page = await db+ const query = await db.select().from(page).where(@@ -56,43 +59,45 @@ export default async function _proxy1(req: NextRequest) {).get();- console.log({ slug: _page?.slug, customDomain: _page?.customDomain });+ const validation = selectPageSchema.safeParse(query);- if (!_page) {- // return NextResponse.redirect(new URL("https://stpg.dev"));- // TODO: work on 404 page+ if (!validation.success) {return response;}- if (_page?.passwordProtected) {+ const _page = validation.data;++ console.log({ slug: _page?.slug, customDomain: _page?.customDomain });++ if (_page?.accessType === "password") {const protectedCookie = cookies.get(createProtectedCookieKey(_page.slug));const cookiePassword = protectedCookie ? protectedCookie.value : undefined;const queryPassword = url.searchParams.get("pw");const password = queryPassword || cookiePassword;- if (password !== _page.password && !url.pathname.endsWith("/protected")) {+ if (password !== _page.password && !url.pathname.endsWith("/login")) {const { pathname, origin } = req.nextUrl;// custom domain redirectif (_page.customDomain && host !== `${_page.slug}.stpg.dev`) {const redirect = pathname.replace(`/${_page.customDomain}`, "");const url = new URL(- `https://${- _page.customDomain- }/protected?redirect=${encodeURIComponent(redirect)}`,+ `https://${_page.customDomain}/login?redirect=${encodeURIComponent(+ redirect,+ )}`,);- console.log("redirect to /protected", url.toString());+ console.log("redirect to /login", url.toString());return NextResponse.redirect(url);}const url = new URL(`${origin}${type === "pathname" ? `/${prefix}` : ""- }/protected?redirect=${encodeURIComponent(pathname)}`,+ }/login?redirect=${encodeURIComponent(pathname)}`,);return NextResponse.redirect(url);}- if (password === _page.password && url.pathname.endsWith("/protected")) {+ if (password === _page.password && url.pathname.endsWith("/login")) {const redirect = url.searchParams.get("redirect");// custom domain redirect@@ -112,6 +117,31 @@ export default async function _proxy1(req: NextRequest) {}}+ if (_page.accessType === "email-domain") {+ const { origin, pathname } = req.nextUrl;+ const email = req.auth?.user?.email;+ const emailDomain = email?.split("@")[1];+ if (+ !pathname.endsWith("/login") &&+ (!emailDomain || !_page.authEmailDomains.includes(emailDomain))+ ) {+ const url = new URL(+ `${origin}${type === "pathname" ? `/${prefix}` : ""}/login`,+ );+ return NextResponse.redirect(url);+ }+ if (+ pathname.endsWith("/login") &&+ emailDomain &&+ _page.authEmailDomains.includes(emailDomain)+ ) {+ const url = new URL(+ `${origin}${type === "pathname" ? `/${prefix}` : ""}`,+ );+ return NextResponse.redirect(url);+ }+ }+const proxy = req.headers.get("x-proxy");console.log({ proxy });@@ -169,48 +199,10 @@ export default async function _proxy1(req: NextRequest) {return NextResponse.rewrite(rewriteUrl);}return response;-}+});export const config = {matcher: ["/((?!api|assets|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",],};--export const getValidSubdomain = (host?: string | null) => {- let subdomain: string | null = null;- if (!host && typeof window !== "undefined") {- // On client side, get the host from window- // biome-ignore lint: to fix later- host = window.location.host;- }-- // Exclude localhost and IP addresses from being treated as subdomains- if (- host?.match(/^(localhost|127\\.0\\.0\\.1|::1|\\d+\\.\\d+\\.\\d+\\.\\d+)/)- ) {- return null;- }-- // we should improve here for custom vercel deploy page- if (host?.includes(".") && !host.includes(".vercel.app")) {- const candidate = host.split(".")[0];- if (candidate && !candidate.includes("www")) {- // Valid candidate- subdomain = candidate;- }- }-- // In case the host is a custom domain- if (- host &&- !(- host?.includes("stpg.dev") ||- host?.includes("openstatus.dev") ||- host?.endsWith(".vercel.app")- )- ) {- subdomain = host;- }- return subdomain;-};diff --git a/apps/web/next-env.d.ts b/apps/web/next-env.d.tsindex 9edff1c7c..c4b7818fb 100644--- a/apps/web/next-env.d.ts+++ b/apps/web/next-env.d.ts@@ -1,6 +1,6 @@/// <reference types="next" />/// <reference types="next/image-types/global" />-import "./.next/types/routes.d.ts";+import "./.next/dev/types/routes.d.ts";// NOTE: This file should not be edited// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.diff --git a/apps/web/src/app/api/og/page/route.tsx b/apps/web/src/app/api/og/page/route.tsxindex 10f5fce9a..21777606e 100644--- a/apps/web/src/app/api/og/page/route.tsx+++ b/apps/web/src/app/api/og/page/route.tsx@@ -10,6 +10,8 @@ import { SIZE, calSemiBold, interLight, interRegular } from "../utils";export const runtime = "edge";+// TODO: legacy Tracker - use api.statusPage.get.query instead+export async function GET(req: Request) {const [interRegularData, interLightData, calSemiBoldData] = await Promise.all([interRegular, interLight, calSemiBold],@@ -18,19 +20,17 @@ export async function GET(req: Request) {const { searchParams } = new URL(req.url);const slug = searchParams.has("slug") ? searchParams.get("slug") : undefined;- const passwordProtected = searchParams.has("passwordProtected")- ? searchParams.get("passwordProtected") === "true" // FIXME: can we use Boolean("true") or Boolean("false")?- : undefined;const page = await api.page.getPageBySlug.query({ slug: slug || "" });+ const _protected = page?.accessType !== "public";const title = page ? page.title : TITLE;const description = page ? "" : DESCRIPTION;// REMINDER: if password protected, we keep the status 'operational' by default, hiding the actual statusconst tracker = new Tracker({- incidents: passwordProtected ? undefined : page?.incidents,- statusReports: passwordProtected ? undefined : page?.statusReports,- maintenances: passwordProtected ? undefined : page?.maintenances,+ incidents: _protected ? undefined : page?.incidents,+ statusReports: _protected ? undefined : page?.statusReports,+ maintenances: _protected ? undefined : page?.maintenances,});return new ImageResponse(diff --git a/apps/web/src/app/api/webhook/stripe/route.ts b/apps/web/src/app/api/webhook/stripe/route.tsindex c83dd3876..c2aaa0d90 100644--- a/apps/web/src/app/api/webhook/stripe/route.ts+++ b/apps/web/src/app/api/webhook/stripe/route.ts@@ -29,7 +29,12 @@ export async function POST(req: NextRequest) {case "checkout.session.completed":await caller.stripeRouter.webhooks.sessionCompleted({ event });break;-+ case "customer.subscription.updated":+ console.log(event);+ await caller.stripeRouter.webhooks.customerSubscriptionUpdated({+ event,+ });+ break;case "customer.subscription.deleted":await caller.stripeRouter.webhooks.customerSubscriptionDeleted({event,diff --git a/apps/web/src/content/pages/unrelated/pricing.mdx b/apps/web/src/content/pages/unrelated/pricing.mdxindex b3621e9a7..7d6f10ac4 100644--- a/apps/web/src/content/pages/unrelated/pricing.mdx+++ b/apps/web/src/content/pages/unrelated/pricing.mdx@@ -25,14 +25,16 @@ category: "Company"["Response logs", "", "+", "+"],[<a href="/private-locations">Private locations</a>, "", "", "+"],["OTel Exporter", "", "", "+"],- ["Number of on-demand checks", "30/mo", "100/mo", "300/mo"],+ ["Number of on-demand checks", "30/mo.", "100/mo.", "300/mo."],[<a href="/status-page"><strong>Status Pages</strong></a>, "", "", ""],["Number of status pages", "1", "1", "5"],["Maintenance status", "+", "+", "+"],["Toggle numbers visibility", "+", "+", "+"],["Subscribers", "", "+", "+"],["Custom domain", "", "+", "+"],- ["Password-protected", "", "+", "+"],+ [<strong>Audience</strong>, "", "", ""],+ ["Password Protection", "", "+", "+"],+ ["Email Authentification", "", "add-on $50/mo.", "add-on $50/mo."],[<strong>Alerts</strong>, "", "", ""],["Slack, Discord, Email, Webhook, ntfy.sh", "+", "+", "+"],["WhatsApp", "", "+", "+"],@@ -45,7 +47,7 @@ category: "Company"}}/>-We provide pricing parity and support **EUR**/**USD**/**INR** as currency. Contact us at [[email protected]](mailto:[email protected]) or [book a call](https://openstatus.dev/cal) if you have questions.+We provide pricing support for **EUR**/**USD**/**INR** as currency. Contact us at [[email protected]](mailto:[email protected]) or [book a call](https://openstatus.dev/cal) if you have questions.---diff --git a/apps/web/src/lib/auth/adapter.ts b/apps/web/src/lib/auth/adapter.tsdeleted file mode 100644index 26fdfcff2..000000000--- a/apps/web/src/lib/auth/adapter.ts+++ /dev/null@@ -1,42 +0,0 @@-import { DrizzleAdapter } from "@auth/drizzle-adapter";-import type { Adapter } from "next-auth/adapters";--import { db } from "@openstatus/db";-import {- account,- session,- user,- verificationToken,-} from "@openstatus/db/src/schema";--import { createUser, getUser } from "./helpers";--export const adapter: Adapter = {- ...DrizzleAdapter(db, {- // @ts-ignore- usersTable: user,- // @ts-ignore- accountsTable: account,- // @ts-ignore- sessionsTable: session,- // @ts-ignore- verificationTokensTable: verificationToken,- }),- createUser: async (data) => {- const user = await createUser(data);- return {- ...user,- id: user.id.toString(),- email: user.email || "",- };- },- getUser: async (id) => {- const user = await getUser(id);- if (!user) return null;- return {- ...user,- id: user.id.toString(),- email: user.email || "",- };- },-};diff --git a/apps/web/src/lib/auth/helpers.ts b/apps/web/src/lib/auth/helpers.tsdeleted file mode 100644index 66ff03237..000000000--- a/apps/web/src/lib/auth/helpers.ts+++ /dev/null@@ -1,65 +0,0 @@-import type { AdapterUser } from "next-auth/adapters";-import * as randomWordSlugs from "random-word-slugs";--import { db, eq } from "@openstatus/db";-import { user, usersToWorkspaces, workspace } from "@openstatus/db/src/schema";--export async function createUser(data: AdapterUser) {- const { id, ...rest } = data;-- const newUser = await db- .insert(user)- .values({- email: rest.email,- photoUrl: rest.image,- name: rest.name,- firstName: rest.firstName,- lastName: rest.lastName,- })- .returning()- .get();-- let slug: string | undefined = undefined;-- while (!slug) {- slug = randomWordSlugs.generateSlug(2);- const slugAlreadyExists = await db- .select()- .from(workspace)- .where(eq(workspace.slug, slug))- .get();-- if (slugAlreadyExists) {- console.log(`slug already exists: '${slug}'`);- slug = undefined;- }- }-- const newWorkspace = await db- .insert(workspace)- .values({ slug, name: "" })- .returning({ id: workspace.id })- .get();-- await db- .insert(usersToWorkspaces)- .values({- userId: newUser.id,- workspaceId: newWorkspace.id,- role: "owner",- })- .returning()- .get();-- return newUser;-}--export async function getUser(id: string) {- const _user = await db- .select()- .from(user)- .where(eq(user.id, Number(id)))- .get();-- return _user || null;-}diff --git a/apps/web/src/lib/auth/index.ts b/apps/web/src/lib/auth/index.tsdeleted file mode 100644index 904bc545f..000000000--- a/apps/web/src/lib/auth/index.ts+++ /dev/null@@ -1,124 +0,0 @@-import type { DefaultSession } from "next-auth";-import NextAuth from "next-auth";--import { Events, setupAnalytics } from "@openstatus/analytics";-import { db, eq } from "@openstatus/db";-import { user } from "@openstatus/db/src/schema";--import { WelcomeEmail, sendEmail } from "@openstatus/emails";-import { headers } from "next/headers";-import { adapter } from "./adapter";-import { GitHubProvider, GoogleProvider, ResendProvider } from "./providers";--export type { DefaultSession };--export const { handlers, signIn, signOut, auth } = NextAuth({- // debug: true,- adapter,- providers:- process.env.NODE_ENV === "development"- ? [GitHubProvider, GoogleProvider, ResendProvider]- : [GitHubProvider, GoogleProvider],- callbacks: {- async signIn(params) {- // We keep updating the user info when we loggin in-- if (params.account?.provider === "google") {- if (!params.profile) return true;- if (Number.isNaN(Number(params.user.id))) return true;-- await db- .update(user)- .set({- firstName: params.profile.given_name,- lastName: params.profile.family_name || "",- photoUrl: params.profile.picture,- // keep the name in sync- name: `${params.profile.given_name} ${- params.profile.family_name || ""- }`.trim(),- updatedAt: new Date(),- })- .where(eq(user.id, Number(params.user.id)))- .run();- }- if (params.account?.provider === "github") {- if (!params.profile) return true;- if (Number.isNaN(Number(params.user.id))) return true;-- await db- .update(user)- .set({- name: params.profile.name,- photoUrl: String(params.profile.avatar_url),- updatedAt: new Date(),- })- .where(eq(user.id, Number(params.user.id)))- .run();- }-- // REMINDER: only used in dev mode- if (params.account?.provider === "resend") {- if (Number.isNaN(Number(params.user.id))) return true;- await db- .update(user)- .set({ updatedAt: new Date() })- .where(eq(user.id, Number(params.user.id)))- .run();- }-- return true;- },- async session(params) {- return params.session;- },- },- events: {- // That should probably done in the callback method instead- async createUser(params) {- if (!params.user.id || !params.user.email) {- throw new Error("User id & email is required");- }-- // this means the user has already been created with clerk- if (params.user.tenantId) return;-- await sendEmail({- from: "Thibault from OpenStatus <[email protected]>",- reply_to: "Thibault from OpenStatus <[email protected]>",- subject: "Welcome to OpenStatus.",- to: [params.user.email],- react: WelcomeEmail(),- });-- const analytics = await setupAnalytics({- userId: `usr_${params.user.id}`,- email: params.user.email,- location: (await headers()).get("x-forwarded-for") ?? undefined,- userAgent: (await headers()).get("user-agent") ?? undefined,- });-- await analytics.track(Events.CreateUser);- },-- async signIn(params) {- if (params.isNewUser) return;- if (!params.user.id || !params.user.email) return;-- const analytics = await setupAnalytics({- userId: `usr_${params.user.id}`,- email: params.user.email,- location: (await headers()).get("x-forwarded-for") ?? undefined,- userAgent: (await headers()).get("user-agent") ?? undefined,- });-- await analytics.track(Events.SignInUser);- },- },- pages: {- signIn: "/app/login",- newUser: "/app/onboarding",- },- // basePath: "/api/auth", // default is `/api/auth`- // secret: process.env.AUTH_SECRET, // default is `AUTH_SECRET`-});diff --git a/apps/web/src/lib/auth/providers.ts b/apps/web/src/lib/auth/providers.tsdeleted file mode 100644index c990eaf60..000000000--- a/apps/web/src/lib/auth/providers.ts+++ /dev/null@@ -1,28 +0,0 @@-import GitHub from "next-auth/providers/github";-import Google from "next-auth/providers/google";-import Resend from "next-auth/providers/resend";--export const GitHubProvider = GitHub({- allowDangerousEmailAccountLinking: true,-});--export const GoogleProvider = Google({- allowDangerousEmailAccountLinking: true,- authorization: {- params: {- // See https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest- prompt: "select_account",- // scope:- // "https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email",- },- },-});--export const ResendProvider = Resend({- apiKey: undefined, // REMINDER: keep undefined to avoid sending emails- async sendVerificationRequest(params) {- console.log("");- console.log(`>>> Magic Link: ${params.url}`);- console.log("");- },-});diff --git a/apps/web/src/next-auth.d.ts b/apps/web/src/next-auth.d.tsdeleted file mode 100644index 1b70e4384..000000000--- a/apps/web/src/next-auth.d.ts+++ /dev/null@@ -1,5 +0,0 @@-import type { User as DefaultUserSchema } from "@openstatus/db/src/schema";--declare module "next-auth" {- interface User extends DefaultUserSchema {}-}diff --git a/apps/web/src/trpc/rq-server.ts b/apps/web/src/trpc/rq-server.tsindex 6bd68a472..fb51932f0 100644--- a/apps/web/src/trpc/rq-server.ts+++ b/apps/web/src/trpc/rq-server.ts@@ -1,6 +1,5 @@import "server-only";-import { auth } from "@/lib/auth";import { type AppRouter, appRouter, t } from "@openstatus/api";import type { Context } from "@openstatus/api/src/trpc";import { db } from "@openstatus/db";@@ -10,12 +9,10 @@ import { makeQueryClient } from "./query-client";const createContextCached = cache(async (..._args: unknown[]): Promise<Context> => {- const session = await auth();-return {req: undefined,db,- session,+ session: null,};},);diff --git a/packages/analytics/src/events.ts b/packages/analytics/src/events.tsindex c24a4cea2..df3b6b9c6 100644--- a/packages/analytics/src/events.ts+++ b/packages/analytics/src/events.ts@@ -68,6 +68,10 @@ export const Events = {name: "user_subscribe_verified",channel: "page",},+ ValidateEmailDomain: {+ name: "email_domain_validated",+ channel: "page",+ },CreateReport: {name: "report_created",channel: "report",@@ -160,6 +164,10 @@ export const Events = {name: "workspace_updated",channel: "workspace",},+ AddFeature: {+ name: "feature_added",+ channel: "billing",+ },UpgradeWorkspace: {name: "workspace_upgraded",channel: "billing",diff --git a/packages/api/src/router/page.ts b/packages/api/src/router/page.tsindex 94ae85ec6..c37177459 100644--- a/packages/api/src/router/page.ts+++ b/packages/api/src/router/page.ts@@ -21,6 +21,7 @@ import {monitorGroup,monitorsToPages,page,+ pageAccessTypes,selectMaintenanceSchema,selectMonitorGroupSchema,selectMonitorSchema,@@ -112,6 +113,7 @@ export const pageRouter = createTRPCRouter({workspaceId: opts.ctx.workspace.id,configuration: JSON.stringify(configuration),...pageProps,+ authEmailDomains: pageProps.authEmailDomains?.join(","),}).returning().get();@@ -187,7 +189,11 @@ export const pageRouter = createTRPCRouter({const currentPage = await opts.ctx.db.update(page)- .set({ ...pageInput, updatedAt: new Date() })+ .set({+ ...pageInput,+ updatedAt: new Date(),+ authEmailDomains: pageInput.authEmailDomains?.join(","),+ }).where(and(eq(page.id, pageInput.id),@@ -732,7 +738,8 @@ export const pageRouter = createTRPCRouter({.input(z.object({id: z.number(),- passwordProtected: z.boolean(),+ accessType: z.enum(pageAccessTypes),+ authEmailDomains: z.array(z.string()).nullish(),password: z.string().nullish(),}),)@@ -747,7 +754,7 @@ export const pageRouter = createTRPCRouter({// the user is not eligible for password protectionif (limit["password-protection"] === false &&- opts.input.passwordProtected === true+ opts.input.accessType === "password") {throw new TRPCError({code: "FORBIDDEN",@@ -756,10 +763,22 @@ export const pageRouter = createTRPCRouter({});}+ if (+ limit["email-domain-protection"] === false &&+ opts.input.accessType === "email-domain"+ ) {+ throw new TRPCError({+ code: "FORBIDDEN",+ message:+ "Email domain protection is not available for your current plan.",+ });+ }+await opts.ctx.db.update(page).set({- passwordProtected: opts.input.passwordProtected,+ accessType: opts.input.accessType,+ authEmailDomains: opts.input.authEmailDomains?.join(","),password: opts.input.password,updatedAt: new Date(),})diff --git a/packages/api/src/router/statusPage.ts b/packages/api/src/router/statusPage.tsindex 3be9e87e3..8d3e6bc80 100644--- a/packages/api/src/router/statusPage.ts+++ b/packages/api/src/router/statusPage.ts@@ -898,6 +898,47 @@ export const statusPageRouter = createTRPCRouter({return _pageSubscriber.id;}),+ validateEmailDomain: publicProcedure+ .meta({ track: Events.ValidateEmailDomain, trackProps: ["slug", "email"] })+ .input(z.object({ slug: z.string().toLowerCase(), email: z.string() }))+ .query(async (opts) => {+ if (!opts.input.slug) return null;++ const _page = await opts.ctx.db.query.page.findFirst({+ where: sql`lower(${page.slug}) = ${opts.input.slug} OR lower(${page.customDomain}) = ${opts.input.slug}`,+ });++ if (!_page) {+ throw new TRPCError({+ code: "NOT_FOUND",+ message: "Page not found",+ });+ }++ if (_page.accessType !== "email-domain") {+ throw new TRPCError({+ code: "BAD_REQUEST",+ message:+ "Page is not configured to allow email domain authentication",+ });+ }++ const allowedDomains = _page.authEmailDomains?.split(",") ?? [];++ if (!allowedDomains.includes(opts.input.email.split("@")[1])) {+ throw new TRPCError({+ code: "BAD_REQUEST",+ message: "Invalid email domain",+ });+ }++ return {+ email: opts.input.email,+ slug: opts.input.slug,+ page: _page,+ };+ }),+verifyEmail: publicProcedure.meta({ track: Events.VerifySubscribePage, trackProps: ["slug"] }).input(z.object({ slug: z.string().toLowerCase(), token: z.string() }))@@ -958,6 +999,13 @@ export const statusPageRouter = createTRPCRouter({});}+ if (_page.accessType !== "password") {+ throw new TRPCError({+ code: "BAD_REQUEST",+ message: "Page is not configured to allow password authentication",+ });+ }+if (_page.password !== opts.input.password) {throw new TRPCError({code: "BAD_REQUEST",diff --git a/packages/api/src/router/stripe/index.ts b/packages/api/src/router/stripe/index.tsindex 005310a68..d86cc9546 100644--- a/packages/api/src/router/stripe/index.ts+++ b/packages/api/src/router/stripe/index.ts@@ -2,15 +2,19 @@ import { z } from "zod";import { eq } from "@openstatus/db";import {+ selectWorkspaceSchema,user,usersToWorkspaces,workspace,workspacePlans,} from "@openstatus/db/src/schema";+import { updateAddonInLimits } from "@openstatus/db/src/schema/plan/utils";+import { TRPCError } from "@trpc/server";+import type { Stripe } from "stripe";import { createTRPCRouter, protectedProcedure } from "../../trpc";import { stripe } from "./shared";-import { getPriceIdForPlan } from "./utils";+import { getPriceIdForFeature, getPriceIdForPlan } from "./utils";import { webhookRouter } from "./webhook";const url =@@ -165,4 +169,96 @@ export const stripeRouter = createTRPCRouter({return session;}),++ addAddon: protectedProcedure+ .input(+ z.object({+ workspaceSlug: z.string(),+ feature: z.enum(["email-domain-protection"]),+ successUrl: z.string().optional(),+ cancelUrl: z.string().optional(),+ remove: z.boolean().optional(),+ }),+ )+ .mutation(async (opts) => {+ // The following code is duplicated we should extract it+ const result = await opts.ctx.db+ .select()+ .from(workspace)+ .where(eq(workspace.slug, opts.input.workspaceSlug))+ .get();++ if (!result) return;++ const ws = selectWorkspaceSchema.parse(result);++ const currentUser = opts.ctx.db+ .select()+ .from(user)+ .where(eq(user.id, opts.ctx.user.id))+ .as("currentUser");+ const userHasAccess = await opts.ctx.db+ .select()+ .from(usersToWorkspaces)+ .where(eq(usersToWorkspaces.workspaceId, result.id))+ .innerJoin(currentUser, eq(usersToWorkspaces.userId, currentUser.id))+ .get();++ if (!userHasAccess || !userHasAccess.users_to_workspaces) return;+ const stripeId = result.stripeId;+ if (!stripeId) {+ throw new TRPCError({+ code: "BAD_REQUEST",+ message: "Workspace has no Stripe ID",+ });+ }++ const sub = (await stripe.customers.retrieve(stripeId, {+ expand: ["subscriptions"],+ })) as Stripe.Customer;++ if (!sub) {+ return;+ }++ if (!sub.subscriptions?.data[0]?.id) {+ return;+ }++ const priceId = getPriceIdForFeature(opts.input.feature);++ if (opts.input.remove) {+ const items = await stripe.subscriptionItems.list({+ subscription: sub.subscriptions?.data[0]?.id,+ });+ const item = items.data.find((item) => item.price.id === priceId);+ if (item) {+ await stripe.subscriptionItems.del(item.id);+ }+ } else {+ await stripe.subscriptionItems.create({+ price: priceId,+ subscription: sub.subscriptions?.data[0]?.id,+ quantity: 1,+ });+ }++ // NOTE: update the limits based on the feature type++ const newLimits = updateAddonInLimits(+ ws.limits,+ opts.input.feature,+ opts.input.remove ? "remove" : "add",+ );++ await opts.ctx.db+ .update(workspace)+ .set({ limits: JSON.stringify(newLimits) })+ .where(eq(workspace.id, result.id))+ .run();++ // TODO: send email to user notifying about the change if not already from stripe++ return;+ }),});diff --git a/packages/api/src/router/stripe/utils.ts b/packages/api/src/router/stripe/utils.tsindex ba456c554..eb5dd4227 100644--- a/packages/api/src/router/stripe/utils.ts+++ b/packages/api/src/router/stripe/utils.ts@@ -1,6 +1,7 @@// Shamelessly stolen from dub.coimport type { WorkspacePlan } from "@openstatus/db/src/schema";+import type { Addons } from "@openstatus/db/src/schema/plan/schema";export const getPlanFromPriceId = (priceId: string) => {const env =@@ -8,11 +9,30 @@ export const getPlanFromPriceId = (priceId: string) => {return PLANS.find((plan) => plan.price.monthly.priceIds[env] === priceId);};+export const getFeatureFromPriceId = (priceId: string) => {+ const env =+ process.env.NEXT_PUBLIC_VERCEL_ENV === "production" ? "production" : "test";+ return FEATURES.find(+ (feature) => feature.price.monthly.priceIds[env] === priceId,+ );+};+export const getPriceIdForPlan = (plan: WorkspacePlan) => {const env =process.env.NEXT_PUBLIC_VERCEL_ENV === "production" ? "production" : "test";return PLANS.find((p) => p.plan === plan)?.price.monthly.priceIds[env];};++export const getPriceIdForFeature = (+ feature: "email-domain-protection" | "status-pages-whitelabel",+) => {+ const env =+ process.env.NEXT_PUBLIC_VERCEL_ENV === "production" ? "production" : "test";+ return FEATURES.find((f) => f.feature === feature)?.price.monthly.priceIds[+ env+ ];+};+export const PLANS = [{plan: "team",@@ -42,3 +62,22 @@ export const PLANS = [monthly: { priceIds: { test: string; production: string } };};}>;++export const FEATURES = [+ {+ feature: "email-domain-protection",+ price: {+ monthly: {+ priceIds: {+ test: "price_1Sl4xqBXJcTfzsyJlzpD1DDm",+ production: "price_1Sl6oqBXJcTfzsyJCxtzDIx5",+ },+ },+ },+ },+] satisfies Array<{+ feature: keyof Addons;+ price: {+ monthly: { priceIds: { test: string; production: string } };+ };+}>;diff --git a/packages/api/src/router/stripe/webhook.ts b/packages/api/src/router/stripe/webhook.tsindex 16a99313b..4389f9b46 100644--- a/packages/api/src/router/stripe/webhook.ts+++ b/packages/api/src/router/stripe/webhook.ts@@ -4,12 +4,19 @@ import { z } from "zod";import { Events, setupAnalytics } from "@openstatus/analytics";import { eq } from "@openstatus/db";-import { user, workspace } from "@openstatus/db/src/schema";+import {+ selectWorkspaceSchema,+ user,+ workspace,+} from "@openstatus/db/src/schema";-import { getLimits } from "@openstatus/db/src/schema/plan/utils";+import {+ getLimits,+ updateAddonInLimits,+} from "@openstatus/db/src/schema/plan/utils";import { createTRPCRouter, publicProcedure } from "../../trpc";import { stripe } from "./shared";-import { getPlanFromPriceId } from "./utils";+import { getFeatureFromPriceId, getPlanFromPriceId } from "./utils";const webhookProcedure = publicProcedure.input(z.object({@@ -27,21 +34,14 @@ const webhookProcedure = publicProcedure.input();export const webhookRouter = createTRPCRouter({- sessionCompleted: webhookProcedure.mutation(async (opts) => {- const session = opts.input.event.data.object as Stripe.Checkout.Session;- if (typeof session.subscription !== "string") {- throw new TRPCError({- code: "BAD_REQUEST",- message: "Missing or invalid subscription id",- });- }- const subscription = await stripe.subscriptions.retrieve(- session.subscription,- );+ customerSubscriptionUpdated: webhookProcedure.mutation(async (opts) => {+ const subscription = opts.input.event.data.object as Stripe.Subscription;+const customerId =typeof subscription.customer === "string"? subscription.customer: subscription.customer.id;+const result = await opts.ctx.db.select().from(workspace)@@ -53,25 +53,32 @@ export const webhookRouter = createTRPCRouter({message: "Workspace not found",});}- const plan = getPlanFromPriceId(subscription.items.data[0].price.id);- if (!plan) {- console.error("Invalid plan");- throw new TRPCError({- code: "BAD_REQUEST",- message: "Invalid plan",- });++ for (const item of subscription.items.data) {+ console.log(item);+ const feature = getFeatureFromPriceId(item.price.id);+ if (!feature) {+ continue;+ }+ const _ws = await opts.ctx.db+ .select()+ .from(workspace)+ .where(eq(workspace.stripeId, customerId))+ .get();++ const ws = selectWorkspaceSchema.parse(_ws);++ const newLimits = updateAddonInLimits(ws.limits, feature.feature, "add");++ await opts.ctx.db+ .update(workspace)+ .set({+ limits: JSON.stringify(newLimits),+ })+ .where(eq(workspace.id, result.id))+ .run();}- await opts.ctx.db- .update(workspace)- .set({- plan: plan.plan,- subscriptionId: subscription.id,- endsAt: new Date(subscription.current_period_end * 1000),- paidUntil: new Date(subscription.current_period_end * 1000),- limits: JSON.stringify(getLimits(plan.plan)),- })- .where(eq(workspace.id, result.id))- .run();+const customer = await stripe.customers.retrieve(customerId);if (!customer.deleted && customer.email) {const userResult = await opts.ctx.db@@ -85,9 +92,100 @@ export const webhookRouter = createTRPCRouter({userId: `usr_${userResult.id}`,email: userResult.email || undefined,workspaceId: String(result.id),- plan: plan.plan,});- await analytics.track(Events.UpgradeWorkspace);+ await analytics.track(Events.AddFeature);+ }+ }),+ sessionCompleted: webhookProcedure.mutation(async (opts) => {+ const session = opts.input.event.data.object as Stripe.Checkout.Session;+ if (typeof session.subscription !== "string") {+ throw new TRPCError({+ code: "BAD_REQUEST",+ message: "Missing or invalid subscription id",+ });+ }+ const subscription = await stripe.subscriptions.retrieve(+ session.subscription,+ );+ const customerId =+ typeof subscription.customer === "string"+ ? subscription.customer+ : subscription.customer.id;++ const result = await opts.ctx.db+ .select()+ .from(workspace)+ .where(eq(workspace.stripeId, customerId))+ .get();+ if (!result) {+ throw new TRPCError({+ code: "BAD_REQUEST",+ message: "Workspace not found",+ });+ }++ for (const item of subscription.items.data) {+ const plan = getPlanFromPriceId(item.price.id);+ if (!plan) {+ const feature = getFeatureFromPriceId(item.price.id);+ if (feature) {+ const _ws = await opts.ctx.db+ .select()+ .from(workspace)+ .where(eq(workspace.stripeId, customerId))+ .get();++ const ws = selectWorkspaceSchema.parse(_ws);++ const newLimits = updateAddonInLimits(+ ws.limits,+ feature.feature,+ "add",+ );++ await opts.ctx.db+ .update(workspace)+ .set({+ limits: JSON.stringify(newLimits),+ })+ .where(eq(workspace.id, result.id))+ .run();+ continue;+ }+ console.error("Invalid plan");+ throw new TRPCError({+ code: "BAD_REQUEST",+ message: "Invalid plan",+ });+ }+ await opts.ctx.db+ .update(workspace)+ .set({+ plan: plan.plan,+ subscriptionId: subscription.id,+ endsAt: new Date(subscription.current_period_end * 1000),+ paidUntil: new Date(subscription.current_period_end * 1000),+ limits: JSON.stringify(getLimits(plan.plan)),+ })+ .where(eq(workspace.id, result.id))+ .run();+ const customer = await stripe.customers.retrieve(customerId);+ if (!customer.deleted && customer.email) {+ const userResult = await opts.ctx.db+ .select()+ .from(user)+ .where(eq(user.email, customer.email))+ .get();+ if (!userResult) return;++ const analytics = await setupAnalytics({+ userId: `usr_${userResult.id}`,+ email: userResult.email || undefined,+ workspaceId: String(result.id),+ plan: plan.plan,+ });+ await analytics.track(Events.UpgradeWorkspace);+ }}}),customerSubscriptionDeleted: webhookProcedure.mutation(async (opts) => {diff --git a/packages/api/src/trpc.ts b/packages/api/src/trpc.tsindex cc469f74c..ba5401d6d 100644--- a/packages/api/src/trpc.ts+++ b/packages/api/src/trpc.ts@@ -12,11 +12,13 @@ import {import { db, eq, schema } from "@openstatus/db";import type { User, Workspace } from "@openstatus/db/src/schema";-// TODO: create a package for this-import {- type DefaultSession as Session,- auth,-} from "../../../apps/web/src/lib/auth";+// Generic session type that works with both User and Viewer+type Session = {+ user?: {+ id?: string | null;+ email?: string | null;+ } | null;+} | null;/*** 1. CONTEXT@@ -67,8 +69,10 @@ export const createInnerTRPCContext = (opts: CreateContextOptions) => {export const createTRPCContext = async (opts: {req: NextRequest;serverSideCall?: boolean;+ auth?: () => Promise<Session>;}) => {- const session = await auth();+ // Use provided auth function or return null session+ const session = opts.auth ? await opts.auth() : null;const workspace = null;const user = null;diff --git a/packages/db/drizzle/0051_fuzzy_red_hulk.sql b/packages/db/drizzle/0051_fuzzy_red_hulk.sqlnew file mode 100644index 000000000..c7549450d--- /dev/null+++ b/packages/db/drizzle/0051_fuzzy_red_hulk.sql@@ -0,0 +1,38 @@+CREATE TABLE `viewer` (+ `id` integer PRIMARY KEY NOT NULL,+ `name` text,+ `email` text,+ `emailVerified` integer,+ `image` text,+ `created_at` integer DEFAULT (strftime('%s', 'now')),+ `updated_at` integer DEFAULT (strftime('%s', 'now'))+);+--> statement-breakpoint+CREATE UNIQUE INDEX `viewer_email_unique` ON `viewer` (`email`);--> statement-breakpoint+CREATE TABLE `viewer_accounts` (+ `user_id` text NOT NULL,+ `type` text NOT NULL,+ `provider` text NOT NULL,+ `providerAccountId` text NOT NULL,+ `refresh_token` text,+ `access_token` text,+ `expires_at` integer,+ `token_type` text,+ `scope` text,+ `id_token` text,+ `session_state` text,+ PRIMARY KEY(`provider`, `providerAccountId`),+ FOREIGN KEY (`user_id`) REFERENCES `viewer`(`id`) ON UPDATE no action ON DELETE cascade+);+--> statement-breakpoint+CREATE TABLE `viewer_session` (+ `session_token` text PRIMARY KEY NOT NULL,+ `user_id` integer NOT NULL,+ `expires` integer NOT NULL,+ FOREIGN KEY (`user_id`) REFERENCES `viewer`(`id`) ON UPDATE no action ON DELETE cascade+);+--> statement-breakpoint+ALTER TABLE `page` ADD `access_type` text DEFAULT 'public';--> statement-breakpoint+ALTER TABLE `page` ADD `auth_email_domains` text;--> statement-breakpoint+-- NOTE: manual migration to set the access type based on the password column+UPDATE `page` SET `access_type` = 'password' WHERE `password` IS NOT NULL AND `password` != '' AND `password_protected` = 1;\ No newline at end of filediff --git a/packages/db/drizzle/meta/0051_snapshot.json b/packages/db/drizzle/meta/0051_snapshot.jsonnew file mode 100644index 000000000..77ac73e90--- /dev/null+++ b/packages/db/drizzle/meta/0051_snapshot.json@@ -0,0 +1,2941 @@+{+ "version": "6",+ "dialect": "sqlite",+ "id": "e8d9889c-8d28-4311-83e6-9fd28c840595",+ "prevId": "d7863fda-51fb-4d7c-b9e6-fd1943ad5d71",+ "tables": {+ "workspace": {+ "name": "workspace",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "slug": {+ "name": "slug",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "stripe_id": {+ "name": "stripe_id",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "subscription_id": {+ "name": "subscription_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "plan": {+ "name": "plan",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "ends_at": {+ "name": "ends_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "paid_until": {+ "name": "paid_until",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "limits": {+ "name": "limits",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'{}'"+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "dsn": {+ "name": "dsn",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "workspace_slug_unique": {+ "name": "workspace_slug_unique",+ "columns": [+ "slug"+ ],+ "isUnique": true+ },+ "workspace_stripe_id_unique": {+ "name": "workspace_stripe_id_unique",+ "columns": [+ "stripe_id"+ ],+ "isUnique": true+ },+ "workspace_id_dsn_unique": {+ "name": "workspace_id_dsn_unique",+ "columns": [+ "id",+ "dsn"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "account": {+ "name": "account",+ "columns": {+ "user_id": {+ "name": "user_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "provider_account_id": {+ "name": "provider_account_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "refresh_token": {+ "name": "refresh_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "access_token": {+ "name": "access_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "token_type": {+ "name": "token_type",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "scope": {+ "name": "scope",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "id_token": {+ "name": "id_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "session_state": {+ "name": "session_state",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "account_user_id_user_id_fk": {+ "name": "account_user_id_user_id_fk",+ "tableFrom": "account",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "account_provider_provider_account_id_pk": {+ "columns": [+ "provider",+ "provider_account_id"+ ],+ "name": "account_provider_provider_account_id_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "session": {+ "name": "session",+ "columns": {+ "session_token": {+ "name": "session_token",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "expires": {+ "name": "expires",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "session_user_id_user_id_fk": {+ "name": "session_user_id_user_id_fk",+ "tableFrom": "session",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "user": {+ "name": "user",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "tenant_id": {+ "name": "tenant_id",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "first_name": {+ "name": "first_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "''"+ },+ "last_name": {+ "name": "last_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "''"+ },+ "photo_url": {+ "name": "photo_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "''"+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "''"+ },+ "emailVerified": {+ "name": "emailVerified",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "user_tenant_id_unique": {+ "name": "user_tenant_id_unique",+ "columns": [+ "tenant_id"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "users_to_workspaces": {+ "name": "users_to_workspaces",+ "columns": {+ "user_id": {+ "name": "user_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'member'"+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "users_to_workspaces_user_id_user_id_fk": {+ "name": "users_to_workspaces_user_id_user_id_fk",+ "tableFrom": "users_to_workspaces",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "users_to_workspaces_workspace_id_workspace_id_fk": {+ "name": "users_to_workspaces_workspace_id_workspace_id_fk",+ "tableFrom": "users_to_workspaces",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "users_to_workspaces_user_id_workspace_id_pk": {+ "columns": [+ "user_id",+ "workspace_id"+ ],+ "name": "users_to_workspaces_user_id_workspace_id_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "verification_token": {+ "name": "verification_token",+ "columns": {+ "identifier": {+ "name": "identifier",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "expires": {+ "name": "expires",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "verification_token_identifier_token_pk": {+ "columns": [+ "identifier",+ "token"+ ],+ "name": "verification_token_identifier_token_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "status_report_to_monitors": {+ "name": "status_report_to_monitors",+ "columns": {+ "monitor_id": {+ "name": "monitor_id",+ "type": "integer",+ "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'))"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "status_report_to_monitors_monitor_id_monitor_id_fk": {+ "name": "status_report_to_monitors_monitor_id_monitor_id_fk",+ "tableFrom": "status_report_to_monitors",+ "tableTo": "monitor",+ "columnsFrom": [+ "monitor_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "status_report_to_monitors_status_report_id_status_report_id_fk": {+ "name": "status_report_to_monitors_status_report_id_status_report_id_fk",+ "tableFrom": "status_report_to_monitors",+ "tableTo": "status_report",+ "columnsFrom": [+ "status_report_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "status_report_to_monitors_monitor_id_status_report_id_pk": {+ "columns": [+ "monitor_id",+ "status_report_id"+ ],+ "name": "status_report_to_monitors_monitor_id_status_report_id_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "status_report": {+ "name": "status_report",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "page_id": {+ "name": "page_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "status_report_workspace_id_workspace_id_fk": {+ "name": "status_report_workspace_id_workspace_id_fk",+ "tableFrom": "status_report",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "status_report_page_id_page_id_fk": {+ "name": "status_report_page_id_page_id_fk",+ "tableFrom": "status_report",+ "tableTo": "page",+ "columnsFrom": [+ "page_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "status_report_update": {+ "name": "status_report_update",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "date": {+ "name": "date",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "message": {+ "name": "message",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status_report_id": {+ "name": "status_report_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "status_report_update_status_report_id_status_report_id_fk": {+ "name": "status_report_update_status_report_id_status_report_id_fk",+ "tableFrom": "status_report_update",+ "tableTo": "status_report",+ "columnsFrom": [+ "status_report_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "integration": {+ "name": "integration",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "credential": {+ "name": "credential",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "external_id": {+ "name": "external_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "data": {+ "name": "data",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "integration_workspace_id_workspace_id_fk": {+ "name": "integration_workspace_id_workspace_id_fk",+ "tableFrom": "integration",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "page": {+ "name": "page",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "icon": {+ "name": "icon",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "''"+ },+ "slug": {+ "name": "slug",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "custom_domain": {+ "name": "custom_domain",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "published": {+ "name": "published",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": false+ },+ "force_theme": {+ "name": "force_theme",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'system'"+ },+ "password": {+ "name": "password",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "password_protected": {+ "name": "password_protected",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": false+ },+ "access_type": {+ "name": "access_type",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "'public'"+ },+ "auth_email_domains": {+ "name": "auth_email_domains",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "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+ },+ "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+ },+ "show_monitor_values": {+ "name": "show_monitor_values",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": true+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "page_slug_unique": {+ "name": "page_slug_unique",+ "columns": [+ "slug"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "page_workspace_id_workspace_id_fk": {+ "name": "page_workspace_id_workspace_id_fk",+ "tableFrom": "page",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "monitor": {+ "name": "monitor",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "job_type": {+ "name": "job_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'http'"+ },+ "periodicity": {+ "name": "periodicity",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'other'"+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'active'"+ },+ "active": {+ "name": "active",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": false+ },+ "regions": {+ "name": "regions",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "url": {+ "name": "url",+ "type": "text(2048)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "external_name": {+ "name": "external_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "headers": {+ "name": "headers",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "''"+ },+ "body": {+ "name": "body",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "''"+ },+ "method": {+ "name": "method",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "'GET'"+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "timeout": {+ "name": "timeout",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 45000+ },+ "degraded_after": {+ "name": "degraded_after",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "assertions": {+ "name": "assertions",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "otel_endpoint": {+ "name": "otel_endpoint",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "otel_headers": {+ "name": "otel_headers",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "public": {+ "name": "public",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": false+ },+ "retry": {+ "name": "retry",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": 3+ },+ "follow_redirects": {+ "name": "follow_redirects",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": true+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "deleted_at": {+ "name": "deleted_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "monitor_workspace_id_workspace_id_fk": {+ "name": "monitor_workspace_id_workspace_id_fk",+ "tableFrom": "monitor",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "monitors_to_pages": {+ "name": "monitors_to_pages",+ "columns": {+ "monitor_id": {+ "name": "monitor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "page_id": {+ "name": "page_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'))"+ },+ "order": {+ "name": "order",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": 0+ },+ "monitor_group_id": {+ "name": "monitor_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+ }+ },+ "indexes": {},+ "foreignKeys": {+ "monitors_to_pages_monitor_id_monitor_id_fk": {+ "name": "monitors_to_pages_monitor_id_monitor_id_fk",+ "tableFrom": "monitors_to_pages",+ "tableTo": "monitor",+ "columnsFrom": [+ "monitor_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "monitors_to_pages_page_id_page_id_fk": {+ "name": "monitors_to_pages_page_id_page_id_fk",+ "tableFrom": "monitors_to_pages",+ "tableTo": "page",+ "columnsFrom": [+ "page_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "monitors_to_pages_monitor_group_id_monitor_group_id_fk": {+ "name": "monitors_to_pages_monitor_group_id_monitor_group_id_fk",+ "tableFrom": "monitors_to_pages",+ "tableTo": "monitor_group",+ "columnsFrom": [+ "monitor_group_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "monitors_to_pages_monitor_id_page_id_pk": {+ "columns": [+ "monitor_id",+ "page_id"+ ],+ "name": "monitors_to_pages_monitor_id_page_id_pk"+ }+ },+ "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": true,+ "autoincrement": false+ },+ "page_id": {+ "name": "page_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "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+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "page_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": {}+ },+ "notification": {+ "name": "notification",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "data": {+ "name": "data",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "'{}'"+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "notification_workspace_id_workspace_id_fk": {+ "name": "notification_workspace_id_workspace_id_fk",+ "tableFrom": "notification",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "notification_trigger": {+ "name": "notification_trigger",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "monitor_id": {+ "name": "monitor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "notification_id": {+ "name": "notification_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "cron_timestamp": {+ "name": "cron_timestamp",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "notification_id_monitor_id_crontimestampe": {+ "name": "notification_id_monitor_id_crontimestampe",+ "columns": [+ "notification_id",+ "monitor_id",+ "cron_timestamp"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "notification_trigger_monitor_id_monitor_id_fk": {+ "name": "notification_trigger_monitor_id_monitor_id_fk",+ "tableFrom": "notification_trigger",+ "tableTo": "monitor",+ "columnsFrom": [+ "monitor_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "notification_trigger_notification_id_notification_id_fk": {+ "name": "notification_trigger_notification_id_notification_id_fk",+ "tableFrom": "notification_trigger",+ "tableTo": "notification",+ "columnsFrom": [+ "notification_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "notifications_to_monitors": {+ "name": "notifications_to_monitors",+ "columns": {+ "monitor_id": {+ "name": "monitor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "notification_id": {+ "name": "notification_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "notifications_to_monitors_monitor_id_monitor_id_fk": {+ "name": "notifications_to_monitors_monitor_id_monitor_id_fk",+ "tableFrom": "notifications_to_monitors",+ "tableTo": "monitor",+ "columnsFrom": [+ "monitor_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "notifications_to_monitors_notification_id_notification_id_fk": {+ "name": "notifications_to_monitors_notification_id_notification_id_fk",+ "tableFrom": "notifications_to_monitors",+ "tableTo": "notification",+ "columnsFrom": [+ "notification_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "notifications_to_monitors_monitor_id_notification_id_pk": {+ "columns": [+ "monitor_id",+ "notification_id"+ ],+ "name": "notifications_to_monitors_monitor_id_notification_id_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "monitor_status": {+ "name": "monitor_status",+ "columns": {+ "monitor_id": {+ "name": "monitor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "region": {+ "name": "region",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'active'"+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "monitor_status_idx": {+ "name": "monitor_status_idx",+ "columns": [+ "monitor_id",+ "region"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "monitor_status_monitor_id_monitor_id_fk": {+ "name": "monitor_status_monitor_id_monitor_id_fk",+ "tableFrom": "monitor_status",+ "tableTo": "monitor",+ "columnsFrom": [+ "monitor_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "monitor_status_monitor_id_region_pk": {+ "columns": [+ "monitor_id",+ "region"+ ],+ "name": "monitor_status_monitor_id_region_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "invitation": {+ "name": "invitation",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'member'"+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "accepted_at": {+ "name": "accepted_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "incident": {+ "name": "incident",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "summary": {+ "name": "summary",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'triage'"+ },+ "monitor_id": {+ "name": "monitor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "started_at": {+ "name": "started_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "acknowledged_at": {+ "name": "acknowledged_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "acknowledged_by": {+ "name": "acknowledged_by",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "resolved_at": {+ "name": "resolved_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "resolved_by": {+ "name": "resolved_by",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "incident_screenshot_url": {+ "name": "incident_screenshot_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "recovery_screenshot_url": {+ "name": "recovery_screenshot_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "auto_resolved": {+ "name": "auto_resolved",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "incident_monitor_id_started_at_unique": {+ "name": "incident_monitor_id_started_at_unique",+ "columns": [+ "monitor_id",+ "started_at"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "incident_monitor_id_monitor_id_fk": {+ "name": "incident_monitor_id_monitor_id_fk",+ "tableFrom": "incident",+ "tableTo": "monitor",+ "columnsFrom": [+ "monitor_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set default",+ "onUpdate": "no action"+ },+ "incident_workspace_id_workspace_id_fk": {+ "name": "incident_workspace_id_workspace_id_fk",+ "tableFrom": "incident",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "incident_acknowledged_by_user_id_fk": {+ "name": "incident_acknowledged_by_user_id_fk",+ "tableFrom": "incident",+ "tableTo": "user",+ "columnsFrom": [+ "acknowledged_by"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "incident_resolved_by_user_id_fk": {+ "name": "incident_resolved_by_user_id_fk",+ "tableFrom": "incident",+ "tableTo": "user",+ "columnsFrom": [+ "resolved_by"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "monitor_tag": {+ "name": "monitor_tag",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "monitor_tag_workspace_id_workspace_id_fk": {+ "name": "monitor_tag_workspace_id_workspace_id_fk",+ "tableFrom": "monitor_tag",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "monitor_tag_to_monitor": {+ "name": "monitor_tag_to_monitor",+ "columns": {+ "monitor_id": {+ "name": "monitor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "monitor_tag_id": {+ "name": "monitor_tag_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "monitor_tag_to_monitor_monitor_id_monitor_id_fk": {+ "name": "monitor_tag_to_monitor_monitor_id_monitor_id_fk",+ "tableFrom": "monitor_tag_to_monitor",+ "tableTo": "monitor",+ "columnsFrom": [+ "monitor_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "monitor_tag_to_monitor_monitor_tag_id_monitor_tag_id_fk": {+ "name": "monitor_tag_to_monitor_monitor_tag_id_monitor_tag_id_fk",+ "tableFrom": "monitor_tag_to_monitor",+ "tableTo": "monitor_tag",+ "columnsFrom": [+ "monitor_tag_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "monitor_tag_to_monitor_monitor_id_monitor_tag_id_pk": {+ "columns": [+ "monitor_id",+ "monitor_tag_id"+ ],+ "name": "monitor_tag_to_monitor_monitor_id_monitor_tag_id_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "application": {+ "name": "application",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "dsn": {+ "name": "dsn",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "application_dsn_unique": {+ "name": "application_dsn_unique",+ "columns": [+ "dsn"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "application_workspace_id_workspace_id_fk": {+ "name": "application_workspace_id_workspace_id_fk",+ "tableFrom": "application",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "maintenance": {+ "name": "maintenance",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "text(256)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "message": {+ "name": "message",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "from": {+ "name": "from",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "to": {+ "name": "to",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "page_id": {+ "name": "page_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "maintenance_workspace_id_workspace_id_fk": {+ "name": "maintenance_workspace_id_workspace_id_fk",+ "tableFrom": "maintenance",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "maintenance_page_id_page_id_fk": {+ "name": "maintenance_page_id_page_id_fk",+ "tableFrom": "maintenance",+ "tableTo": "page",+ "columnsFrom": [+ "page_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "maintenance_to_monitor": {+ "name": "maintenance_to_monitor",+ "columns": {+ "maintenance_id": {+ "name": "maintenance_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "monitor_id": {+ "name": "monitor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "maintenance_to_monitor_maintenance_id_maintenance_id_fk": {+ "name": "maintenance_to_monitor_maintenance_id_maintenance_id_fk",+ "tableFrom": "maintenance_to_monitor",+ "tableTo": "maintenance",+ "columnsFrom": [+ "maintenance_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "maintenance_to_monitor_monitor_id_monitor_id_fk": {+ "name": "maintenance_to_monitor_monitor_id_monitor_id_fk",+ "tableFrom": "maintenance_to_monitor",+ "tableTo": "monitor",+ "columnsFrom": [+ "monitor_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "maintenance_to_monitor_maintenance_id_monitor_id_pk": {+ "columns": [+ "maintenance_id",+ "monitor_id"+ ],+ "name": "maintenance_to_monitor_maintenance_id_monitor_id_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "check": {+ "name": "check",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": true+ },+ "regions": {+ "name": "regions",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "url": {+ "name": "url",+ "type": "text(4096)",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "headers": {+ "name": "headers",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "''"+ },+ "body": {+ "name": "body",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "''"+ },+ "method": {+ "name": "method",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "'GET'"+ },+ "count_requests": {+ "name": "count_requests",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": 1+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "check_workspace_id_workspace_id_fk": {+ "name": "check_workspace_id_workspace_id_fk",+ "tableFrom": "check",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "monitor_run": {+ "name": "monitor_run",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "monitor_id": {+ "name": "monitor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "runned_at": {+ "name": "runned_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "monitor_run_workspace_id_workspace_id_fk": {+ "name": "monitor_run_workspace_id_workspace_id_fk",+ "tableFrom": "monitor_run",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "monitor_run_monitor_id_monitor_id_fk": {+ "name": "monitor_run_monitor_id_monitor_id_fk",+ "tableFrom": "monitor_run",+ "tableTo": "monitor",+ "columnsFrom": [+ "monitor_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "private_location": {+ "name": "private_location",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "last_seen_at": {+ "name": "last_seen_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "private_location_workspace_id_workspace_id_fk": {+ "name": "private_location_workspace_id_workspace_id_fk",+ "tableFrom": "private_location",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "private_location_to_monitor": {+ "name": "private_location_to_monitor",+ "columns": {+ "private_location_id": {+ "name": "private_location_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "monitor_id": {+ "name": "monitor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "deleted_at": {+ "name": "deleted_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "private_location_to_monitor_private_location_id_private_location_id_fk": {+ "name": "private_location_to_monitor_private_location_id_private_location_id_fk",+ "tableFrom": "private_location_to_monitor",+ "tableTo": "private_location",+ "columnsFrom": [+ "private_location_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "private_location_to_monitor_monitor_id_monitor_id_fk": {+ "name": "private_location_to_monitor_monitor_id_monitor_id_fk",+ "tableFrom": "private_location_to_monitor",+ "tableTo": "monitor",+ "columnsFrom": [+ "monitor_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "monitor_group": {+ "name": "monitor_group",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "page_id": {+ "name": "page_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "monitor_group_workspace_id_workspace_id_fk": {+ "name": "monitor_group_workspace_id_workspace_id_fk",+ "tableFrom": "monitor_group",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "monitor_group_page_id_page_id_fk": {+ "name": "monitor_group_page_id_page_id_fk",+ "tableFrom": "monitor_group",+ "tableTo": "page",+ "columnsFrom": [+ "page_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "viewer": {+ "name": "viewer",+ "columns": {+ "id": {+ "name": "id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "emailVerified": {+ "name": "emailVerified",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "image": {+ "name": "image",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "(strftime('%s', 'now'))"+ }+ },+ "indexes": {+ "viewer_email_unique": {+ "name": "viewer_email_unique",+ "columns": [+ "email"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "viewer_accounts": {+ "name": "viewer_accounts",+ "columns": {+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "providerAccountId": {+ "name": "providerAccountId",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "refresh_token": {+ "name": "refresh_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "access_token": {+ "name": "access_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "token_type": {+ "name": "token_type",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "scope": {+ "name": "scope",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "id_token": {+ "name": "id_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "session_state": {+ "name": "session_state",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "viewer_accounts_user_id_viewer_id_fk": {+ "name": "viewer_accounts_user_id_viewer_id_fk",+ "tableFrom": "viewer_accounts",+ "tableTo": "viewer",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "viewer_accounts_provider_providerAccountId_pk": {+ "columns": [+ "provider",+ "providerAccountId"+ ],+ "name": "viewer_accounts_provider_providerAccountId_pk"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "viewer_session": {+ "name": "viewer_session",+ "columns": {+ "session_token": {+ "name": "session_token",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "expires": {+ "name": "expires",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "viewer_session_user_id_viewer_id_fk": {+ "name": "viewer_session_user_id_viewer_id_fk",+ "tableFrom": "viewer_session",+ "tableTo": "viewer",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ }+ },+ "views": {},+ "enums": {},+ "_meta": {+ "schemas": {},+ "tables": {},+ "columns": {}+ },+ "internal": {+ "indexes": {}+ }+}\ No newline at end of filediff --git a/packages/db/drizzle/meta/_journal.json b/packages/db/drizzle/meta/_journal.jsonindex 35f7e78a3..394ef1375 100644--- a/packages/db/drizzle/meta/_journal.json+++ b/packages/db/drizzle/meta/_journal.json@@ -358,6 +358,13 @@"when": 1765567734101,"tag": "0050_damp_xorn","breakpoints": true+ },+ {+ "idx": 51,+ "version": "6",+ "when": 1767362130713,+ "tag": "0051_fuzzy_red_hulk",+ "breakpoints": true}]}\ No newline at end of filediff --git a/packages/db/src/schema/index.ts b/packages/db/src/schema/index.tsindex b76344a93..993cb5cb1 100644--- a/packages/db/src/schema/index.ts+++ b/packages/db/src/schema/index.ts@@ -17,3 +17,4 @@ export * from "./check";export * from "./monitor_run";export * from "./private_locations";export * from "./monitor_groups";+export * from "./viewers";diff --git a/packages/db/src/schema/pages/constants.ts b/packages/db/src/schema/pages/constants.tsindex ae3b8a4cd..7a3b202b8 100644--- a/packages/db/src/schema/pages/constants.ts+++ b/packages/db/src/schema/pages/constants.ts@@ -13,3 +13,5 @@ export const subdomainSafeList = ["ssh","themes",];++export const pageAccessTypes = ["public", "password", "email-domain"] as const;diff --git a/packages/db/src/schema/pages/page.ts b/packages/db/src/schema/pages/page.tsindex 6a1df6390..f8e6765de 100644--- a/packages/db/src/schema/pages/page.ts+++ b/packages/db/src/schema/pages/page.ts@@ -6,6 +6,7 @@ import { monitorsToPages } from "../monitors";import { pageSubscriber } from "../page_subscribers";import { statusReport } from "../status_reports";import { workspace } from "../workspaces";+import { pageAccessTypes } from "./constants";export const page = sqliteTable("page", {id: integer("id").primaryKey(),@@ -27,9 +28,12 @@ export const page = sqliteTable("page", {// Password protecting the status page - no specific restriction on passwordpassword: text("password", { length: 256 }),+ // @deprecated: instead, use accessTypepasswordProtected: integer("password_protected", { mode: "boolean" }).default(false,),+ accessType: text("access_type", { enum: pageAccessTypes }).default("public"),+ authEmailDomains: text("auth_email_domains", { mode: "text" }), // TODO: change to json// links and urlshomepageUrl: text("homepage_url", { length: 256 }),@@ -42,6 +46,7 @@ export const page = sqliteTable("page", {/*** Displays the total and failed request numbers for each monitor+ * TODO: remove this column - we moved into configuration*/showMonitorValues: integer("show_monitor_values", {mode: "boolean",diff --git a/packages/db/src/schema/pages/validation.ts b/packages/db/src/schema/pages/validation.tsindex 346ffd484..67b9825cb 100644--- a/packages/db/src/schema/pages/validation.ts+++ b/packages/db/src/schema/pages/validation.ts@@ -3,6 +3,7 @@ import { THEME_KEYS } from "@openstatus/theme-store";import { createInsertSchema, createSelectSchema } from "drizzle-zod";import { z } from "zod";+import { pageAccessTypes } from "./constants";import { page } from "./page";const slugSchema = z@@ -22,8 +23,16 @@ const customDomainSchema = z).or(z.enum([""]));+const stringToArray = z.preprocess((val) => {+ if (val && String(val).length > 0) {+ return String(val).split(",");+ }+ return [];+}, z.array(z.string()));+export const insertPageSchema = createInsertSchema(page, {customDomain: customDomainSchema.prefault(""),+ accessType: z.enum(pageAccessTypes).prefault("public"),icon: z.string().optional(),slug: slugSchema,}).extend({@@ -38,6 +47,7 @@ export const insertPageSchema = createInsertSchema(page, {).optional().prefault([]),+ authEmailDomains: z.array(z.string()).nullish(),});export const pageConfigurationSchema = z.object({@@ -56,6 +66,8 @@ export const pageConfigurationSchema = z.object({export const selectPageSchema = createSelectSchema(page).extend({password: z.string().optional().nullable().prefault(""),configuration: pageConfigurationSchema.nullish().prefault({}),+ accessType: z.enum(pageAccessTypes).prefault("public"),+ authEmailDomains: stringToArray.prefault([]),});export type InsertPage = z.infer<typeof insertPageSchema>;diff --git a/packages/db/src/schema/plan/config.ts b/packages/db/src/schema/plan/config.tsindex 619b8ef48..770a0e816 100644--- a/packages/db/src/schema/plan/config.ts+++ b/packages/db/src/schema/plan/config.ts@@ -1,22 +1,18 @@import { AVAILABLE_REGIONS, FREE_FLY_REGIONS } from "@openstatus/regions";import type { WorkspacePlan } from "../workspaces/validation";-import type { Limits } from "./schema";+import type { Addons, PlanLimits, Price } from "./schema";++type PlanConfig = {+ title: "Hobby" | "Starter" | "Pro";+ id: WorkspacePlan;+ description: string;+ price: Price;+ addons: Partial<Addons>;+ limits: PlanLimits;+};// TODO: rename to `planConfig`-export const allPlans: Record<- WorkspacePlan,- {- title: "Hobby" | "Starter" | "Pro";- id: WorkspacePlan;- description: string;- price: {- USD: number;- EUR: number;- INR: number;- };- limits: Limits;- }-> = {+export const allPlans: Record<WorkspacePlan, PlanConfig> = {free: {title: "Hobby",id: "free",@@ -26,6 +22,7 @@ export const allPlans: Record<EUR: 0,INR: 0,},+ addons: {},limits: {version: undefined,monitors: 1,@@ -43,18 +40,19 @@ export const allPlans: Record<"status-subscribers": false,"custom-domain": false,"password-protection": false,+ "email-domain-protection": false,"white-label": false,notifications: true,sms: false,"sms-limit": 0,pagerduty: false,opsgenie: false,+ whatsapp: false,"notification-channels": 1,members: 1,"audit-log": false,regions: [...FREE_FLY_REGIONS],"private-locations": false,- whatsapp: false,},},starter: {@@ -66,6 +64,15 @@ export const allPlans: Record<EUR: 30,INR: 3000,},+ addons: {+ "email-domain-protection": {+ price: {+ USD: 100,+ EUR: 100,+ INR: 10_000,+ },+ },+ },limits: {version: undefined,monitors: 20,@@ -83,10 +90,12 @@ export const allPlans: Record<"status-subscribers": true,"custom-domain": true,"password-protection": true,+ "email-domain-protection": false,"white-label": false,notifications: true,pagerduty: true,opsgenie: true,+ whatsapp: true,sms: true,"sms-limit": 50,"notification-channels": 10,@@ -94,7 +103,6 @@ export const allPlans: Record<"audit-log": false,regions: [...AVAILABLE_REGIONS],"private-locations": false,- whatsapp: true,},},team: {@@ -104,7 +112,16 @@ export const allPlans: Record<price: {USD: 100,EUR: 100,- INR: 10000,+ INR: 10_000,+ },+ addons: {+ "email-domain-protection": {+ price: {+ USD: 100,+ EUR: 100,+ INR: 10_000,+ },+ },},limits: {version: undefined,@@ -123,18 +140,19 @@ export const allPlans: Record<"status-subscribers": true,"custom-domain": true,"password-protection": true,+ "email-domain-protection": false,"white-label": false,notifications: true,sms: true,"sms-limit": 100,pagerduty: true,opsgenie: true,+ whatsapp: true,"notification-channels": 20,members: "Unlimited","audit-log": true,regions: [...AVAILABLE_REGIONS],"private-locations": true,- whatsapp: true,},},};diff --git a/packages/db/src/schema/plan/schema.ts b/packages/db/src/schema/plan/schema.tsindex f2c2ee54a..583a4b4d3 100644--- a/packages/db/src/schema/plan/schema.ts+++ b/packages/db/src/schema/plan/schema.ts@@ -32,6 +32,7 @@ export const limitsSchema = z.object({"status-subscribers": z.boolean().prefault(false),"custom-domain": z.boolean().prefault(false),"password-protection": z.boolean().prefault(false),+ "email-domain-protection": z.boolean().prefault(false), // add-on but required in limits"white-label": z.boolean().prefault(false),/*** Notification limits@@ -53,3 +54,38 @@ export const limitsSchema = z.object({});export type Limits = z.infer<typeof limitsSchema>;++//++const priceSchema = z.object({+ USD: z.number(),+ EUR: z.number(),+ INR: z.number(),+});++export type Price = z.infer<typeof priceSchema>;++export const addons = ["email-domain-protection"] as const satisfies Partial<+ keyof Limits+>[];++export const addonsSchema = z.partialRecord(+ z.enum(addons),+ z.object({+ price: priceSchema,+ }),+) satisfies z.ZodType<Partial<Record<keyof Limits, { price: Price }>>>;++export type Addons = z.infer<typeof addonsSchema>;++/**+ * Enforces that addon keys in Limits must be set to false in plan configs+ * (since addons can only be enabled by purchasing them)+ */+export type PlanLimits = {+ [K in keyof Limits]: K extends keyof Addons+ ? Limits[K] extends boolean+ ? false // Force addon boolean fields to false+ : Limits[K] // Non-boolean fields stay as-is+ : Limits[K]; // Non-addon fields stay as-is+};diff --git a/packages/db/src/schema/plan/utils.ts b/packages/db/src/schema/plan/utils.tsindex b749a83d3..d241781bf 100644--- a/packages/db/src/schema/plan/utils.ts+++ b/packages/db/src/schema/plan/utils.ts@@ -1,6 +1,6 @@import type { WorkspacePlan } from "../workspaces/validation";import { allPlans } from "./config";-import type { Limits } from "./schema";+import { type Addons, type Limits, limitsSchema } from "./schema";export function getLimit<T extends keyof Limits>(limits: Limits, limit: T) {return limits[limit] || allPlans.free.limits[limit];@@ -30,17 +30,48 @@ export function getCurrency({return "USD";}+type PriceObject = {+ USD: number;+ EUR: number;+ INR: number;+};++type PriceConfig = {+ value: number;+ locale: string;+ currency: string;+};++function getLocaleForCurrency(currency: string): string {+ return currency === "EUR" ? "fr-FR" : "en-US";+}++function resolvePriceConfig(+ price: PriceObject,+ currency?: string,+): PriceConfig {+ const effectiveCurrency = currency && currency in price ? currency : "USD";+ const value = price[effectiveCurrency as keyof PriceObject];+ const locale = getLocaleForCurrency(effectiveCurrency);++ return { value, locale, currency: effectiveCurrency };+}+export function getPriceConfig(plan: WorkspacePlan, currency?: string) {const planConfig = allPlans[plan];- if (!currency) {- return { value: planConfig.price.USD, locale: "en-US", currency: "USD" };- }- if (currency in planConfig.price) {- const value = planConfig.price[currency as keyof typeof planConfig.price];- const locale = currency === "EUR" ? "fr-FR" : "en-US";- return { value, locale, currency };+ return resolvePriceConfig(planConfig.price, currency);+}++export function getAddonPriceConfig(+ plan: WorkspacePlan,+ addon: keyof Addons,+ currency?: string,+) {+ const addonConfig = allPlans[plan].addons[addon];+ if (!addonConfig) {+ return null;}- return { value: planConfig.price.USD, locale: "en-US", currency: "USD" };+ return resolvePriceConfig(addonConfig.price, currency);}export function getPlansForLimit(@@ -96,3 +127,36 @@ export function getPlansForLimit(return false;});}++/**+ * Add or remove an addon from limits+ * Automatically infers addon type (toggle/quantity) from the limit field type+ * @param limits - Current workspace limits+ * @param addon - Addon key to add/remove+ * @param action - "add" to enable/increment, "remove" to disable/decrement+ * @param quantity - Optional quantity for quantity-based addons (defaults to 1)+ * @returns Updated limits object+ */+export function updateAddonInLimits(+ limits: Limits,+ addon: keyof Addons,+ action: "add" | "remove",+ _quantity = 1,+): Limits {+ const currentValue = limits[addon];+ const newLimits = { ...limits };++ // Infer addon type from the limit field type+ if (typeof currentValue === "boolean") {+ // Toggle addon: boolean on/off+ newLimits[addon] = action === "add";+ } else if (typeof currentValue === "number") {+ // Quantity addon: increment/decrement+ // newLimits[addon] = Math.max(+ // 0,+ // currentValue + (action === "add" ? quantity : -quantity)+ // ); // Don't go below 0+ }++ return limitsSchema.parse(newLimits);+}diff --git a/packages/db/src/schema/viewers/index.ts b/packages/db/src/schema/viewers/index.tsnew file mode 100644index 000000000..0ca35a4ce--- /dev/null+++ b/packages/db/src/schema/viewers/index.ts@@ -0,0 +1,2 @@+export * from "./viewer";+export * from "./validation";diff --git a/packages/db/src/schema/viewers/validation.ts b/packages/db/src/schema/viewers/validation.tsnew file mode 100644index 000000000..ec5294396--- /dev/null+++ b/packages/db/src/schema/viewers/validation.ts@@ -0,0 +1,11 @@+import { createInsertSchema, createSelectSchema } from "drizzle-zod";+import type { z } from "zod";++import { viewer } from "./viewer";++export const insertViewerSchema = createInsertSchema(viewer);++export const selectViewerSchema = createSelectSchema(viewer);++export type InsertViewer = z.infer<typeof insertViewerSchema>;+export type Viewer = z.infer<typeof selectViewerSchema>;diff --git a/packages/db/src/schema/viewers/viewer.ts b/packages/db/src/schema/viewers/viewer.tsnew file mode 100644index 000000000..1c88e0bd5--- /dev/null+++ b/packages/db/src/schema/viewers/viewer.ts@@ -0,0 +1,55 @@+import { sql } from "drizzle-orm";+import {+ integer,+ primaryKey,+ sqliteTable,+ text,+} from "drizzle-orm/sqlite-core";++import type { AdapterAccountType } from "next-auth/adapters";++export const viewer = sqliteTable("viewer", {+ id: integer("id").primaryKey(),+ name: text("name"),+ email: text("email").unique(),+ emailVerified: integer("emailVerified", { mode: "timestamp" }),+ image: text("image"),+ createdAt: integer("created_at", { mode: "timestamp" }).default(+ sql`(strftime('%s', 'now'))`,+ ),+ updatedAt: integer("updated_at", { mode: "timestamp" }).default(+ sql`(strftime('%s', 'now'))`,+ ),+});++export const viewerSession = sqliteTable("viewer_session", {+ sessionToken: text("session_token").primaryKey(),+ userId: integer("user_id")+ .notNull()+ .references(() => viewer.id, { onDelete: "cascade" }),+ expires: integer("expires", { mode: "timestamp_ms" }).notNull(),+});++export const viewerAccounts = sqliteTable(+ "viewer_accounts",+ {+ userId: text("user_id")+ .notNull()+ .references(() => viewer.id, { onDelete: "cascade" }),+ type: text("type").$type<AdapterAccountType>().notNull(),+ provider: text("provider").notNull(),+ providerAccountId: text("providerAccountId").notNull(),+ refresh_token: text("refresh_token"),+ access_token: text("access_token"),+ expires_at: integer("expires_at"),+ token_type: text("token_type"),+ scope: text("scope"),+ id_token: text("id_token"),+ session_state: text("session_state"),+ },+ (account) => [+ primaryKey({+ columns: [account.provider, account.providerAccountId],+ }),+ ],+);diff --git a/packages/emails/emails/status-page-magic-link.tsx b/packages/emails/emails/status-page-magic-link.tsxnew file mode 100644index 000000000..dff098e05--- /dev/null+++ b/packages/emails/emails/status-page-magic-link.tsx@@ -0,0 +1,55 @@+/** @jsxImportSource react */++import {+ Body,+ Head,+ Heading,+ Html,+ Link,+ Preview,+ Text,+} from "@react-email/components";+import { Layout } from "./_components/layout";+import { styles } from "./_components/styles";++export interface StatusPageMagicLinkProps {+ page: string;+ link: string;+}++const StatusPageMagicLinkEmail = ({ page, link }: StatusPageMagicLinkProps) => {+ return (+ <Html>+ <Head>+ <title>Authenticate to "{page}" Status Page</title>+ </Head>+ <Preview>Authenticate to "{page}" Status Page</Preview>+ <Body>+ <Layout>+ <Heading as="h3">Access to "{page}" Status Page</Heading>+ <Text>+ You are receiving this email because you have requested access to+ the "{page}" Status Page.+ </Text>+ <Text>+ To authenticate, please click the link below. The link is valid for+ 24 hours. If you believe this is a mistake, please ignore this+ email.+ </Text>+ <Text>+ <Link style={styles.link} href={link}>+ Authenticate+ </Link>+ </Text>+ </Layout>+ </Body>+ </Html>+ );+};++StatusPageMagicLinkEmail.PreviewProps = {+ page: "OpenStatus",+ link: "https://slug.openstatus.dev/verify/token-xyz",+} satisfies StatusPageMagicLinkProps;++export default StatusPageMagicLinkEmail;diff --git a/packages/emails/src/client.tsx b/packages/emails/src/client.tsxindex 9bc0d63ea..3949609bc 100644--- a/packages/emails/src/client.tsx+++ b/packages/emails/src/client.tsx@@ -6,6 +6,8 @@ import FollowUpEmail from "../emails/followup";import type { MonitorAlertProps } from "../emails/monitor-alert";import PageSubscriptionEmail from "../emails/page-subscription";import type { PageSubscriptionProps } from "../emails/page-subscription";+import StatusPageMagicLinkEmail from "../emails/status-page-magic-link";+import type { StatusPageMagicLinkProps } from "../emails/status-page-magic-link";import StatusReportEmail from "../emails/status-report";import type { StatusReportProps } from "../emails/status-report";import TeamInvitationEmail from "../emails/team-invitation";@@ -212,4 +214,33 @@ export class EmailClient {console.error(`Error sending page subscription to ${req.to}`, err);}}++ public async sendStatusPageMagicLink(+ req: StatusPageMagicLinkProps & { to: string },+ ) {+ if (process.env.NODE_ENV === "development") {+ console.log(`Sending status page magic link email to ${req.to}`);+ console.log(`>>> Magic Link: ${req.link}`);+ return;+ }++ try {+ const html = await render(<StatusPageMagicLinkEmail {...req} />);+ const result = await this.client.emails.send({+ from: "Status Page <[email protected]>",+ subject: `Authenticate to ${req.page}`,+ to: req.to,+ html,+ });++ if (!result.error) {+ console.log(`Sent status page magic link email to ${req.to}`);+ return;+ }++ throw result.error;+ } catch (err) {+ console.error(`Error sending status page magic link to ${req.to}`, err);+ }+ }}diff --git a/packages/emails/src/index.ts b/packages/emails/src/index.tsindex 16e5327e2..bb21ddfa4 100644--- a/packages/emails/src/index.ts+++ b/packages/emails/src/index.ts@@ -4,6 +4,7 @@ export { default as WelcomeEmail } from "../emails/welcome";export { default as TeamInvitationEmail } from "../emails/team-invitation";export { default as MonitorPausedEmail } from "../emails/monitor-paused";export { default as MonitorDeactivationEmail } from "../emails/monitor-deactivation";+export { default as StatusPageMagicLinkEmail } from "../emails/status-page-magic-link";export { monitorDeactivationEmail } from "../hotfix/monitor-deactivation";export { monitorPausedEmail } from "../hotfix/monitor-paused";diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex dfd1ebd10..78e8fd285 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -534,6 +534,12 @@ importers:apps/status-page:dependencies:+ '@auth/core':+ specifier: 0.40.0+ version: 0.40.0+ '@auth/drizzle-adapter':+ specifier: 1.10.0+ version: 1.10.0'@date-fns/tz':specifier: 1.2.0version: 1.2.0@@ -1796,6 +1802,8 @@ importers:specifier: 5.9.3version: 5.9.3+ packages/react/dist: {}+packages/regions:dependencies:zod: