Skip to content

Open-source status page, incident response and uptime monitoring

Extract Vercel domain helpers to dedicated module (#2362)

Maximilian Kaske9b27caaba17e
diff --git a/packages/api/src/lib/vercel.ts b/packages/api/src/lib/vercel.ts
new file mode 100644
index 000000000..a380f38c5
--- /dev/null
+++ b/packages/api/src/lib/vercel.ts
@@ -0,0 +1,117 @@
+import { and, db as defaultDb, ne, sql } from "@openstatus/db";
+import { page } from "@openstatus/db/src/schema";
+import { TRPCError } from "@trpc/server";
+
+import { env } from "../env";
+
+// Vercel domain helpers — transport-layer external integrations that
+// don't belong in the service layer.
+export async function vercelFetch(path: string, init?: RequestInit) {
+ return fetch(`https://api.vercel.com${path}`, {
+ ...init,
+ headers: {
+ Authorization: `Bearer ${env.VERCEL_AUTH_BEARER_TOKEN}`,
+ "Content-Type": "application/json",
+ ...init?.headers,
+ },
+ });
+}
+
+export async function addDomainToVercel(domain: string) {
+ const response = await vercelFetch(
+ `/v9/projects/${env.PROJECT_ID_VERCEL}/domains?teamId=${env.TEAM_ID_VERCEL}`,
+ {
+ body: JSON.stringify({ name: domain }),
+ method: "POST",
+ },
+ );
+
+ if (!response.ok) {
+ const error = await response.json().catch(() => ({}));
+ const code = error?.error?.code;
+ console.error("Failed to add domain to Vercel:", { domain, error });
+ throw toDomainError(domain, code);
+ }
+
+ return response.json();
+}
+
+// Vercel messages leak internal project details, so map known codes to our own copy.
+function toDomainError(domain: string, code?: string): TRPCError {
+ switch (code) {
+ case "domain_already_in_use":
+ return new TRPCError({
+ code: "CONFLICT",
+ message: `The domain '${domain}' is already in use by another status page. Remove it there first or contact support.`,
+ });
+ case "invalid_domain":
+ case "not_found":
+ return new TRPCError({
+ code: "BAD_REQUEST",
+ message: `The domain '${domain}' is invalid.`,
+ });
+ case "forbidden":
+ case "domain_taken":
+ return new TRPCError({
+ code: "FORBIDDEN",
+ message: `The domain '${domain}' belongs to another team on our hosting provider. Contact support if you own it.`,
+ });
+ default:
+ return new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message:
+ "Failed to add custom domain. Please try again. If it continues, contact support.",
+ });
+ }
+}
+
+// customDomain has no unique constraint, so another workspace's page may
+// hold the same domain — detaching it from Vercel would take their status
+// page down. Only remove once no page row (minus excludePageId) references it.
+export async function removeDomainFromVercelIfUnused(
+ db: typeof defaultDb,
+ domain: string,
+ opts?: { excludePageId?: number },
+) {
+ const holder = await db
+ .select({ id: page.id })
+ .from(page)
+ .where(
+ and(
+ sql`lower(${page.customDomain}) = ${domain.toLowerCase()}`,
+ opts?.excludePageId !== undefined
+ ? ne(page.id, opts.excludePageId)
+ : undefined,
+ ),
+ )
+ .get();
+
+ if (holder) {
+ console.warn("Skipping Vercel domain removal, still in use:", {
+ domain,
+ pageId: holder.id,
+ });
+ return null;
+ }
+
+ return removeDomainFromVercel(domain);
+}
+
+export async function removeDomainFromVercel(domain: string) {
+ const response = await vercelFetch(
+ `/v9/projects/${env.PROJECT_ID_VERCEL}/domains/${encodeURIComponent(domain)}?teamId=${env.TEAM_ID_VERCEL}`,
+ { method: "DELETE" },
+ );
+
+ if (!response.ok) {
+ const error = await response.json().catch(() => ({}));
+ console.error("Failed to remove domain from Vercel:", { domain, error });
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message:
+ "Failed to remove custom domain. Please try again. If it continues, contact support.",
+ });
+ }
+
+ return response.json();
+}
diff --git a/packages/api/src/router/domain.ts b/packages/api/src/router/domain.ts
index 6533d89d8..6b8d27736 100644
--- a/packages/api/src/router/domain.ts
+++ b/packages/api/src/router/domain.ts
@@ -1,6 +1,7 @@
import { z } from "zod";
import { env } from "../env";
+import { vercelFetch } from "../lib/vercel";
import { createTRPCRouter, protectedProcedure } from "../trpc";
export const domainConfigResponseSchema = z.object({
@@ -57,15 +58,8 @@ export const domainRouter = createTRPCRouter({
if (!opts.input.domain) {
return null;
}
- const data = await fetch(
- `https://api.vercel.com/v9/projects/${env.PROJECT_ID_VERCEL}/domains/${opts.input.domain}?teamId=${env.TEAM_ID_VERCEL}`,
- {
- method: "GET",
- headers: {
- Authorization: `Bearer ${env.VERCEL_AUTH_BEARER_TOKEN}`,
- "Content-Type": "application/json",
- },
- },
+ const data = await vercelFetch(
+ `/v9/projects/${env.PROJECT_ID_VERCEL}/domains/${opts.input.domain}?teamId=${env.TEAM_ID_VERCEL}`,
);
const json = await data.json();
const result = domainResponseSchema
@@ -87,15 +81,8 @@ export const domainRouter = createTRPCRouter({
if (!opts.input.domain) {
return null;
}
- const data = await fetch(
- `https://api.vercel.com/v6/domains/${opts.input.domain}/config?teamId=${env.TEAM_ID_VERCEL}`,
- {
- method: "GET",
- headers: {
- Authorization: `Bearer ${env.VERCEL_AUTH_BEARER_TOKEN}`,
- "Content-Type": "application/json",
- },
- },
+ const data = await vercelFetch(
+ `/v6/domains/${opts.input.domain}/config?teamId=${env.TEAM_ID_VERCEL}`,
);
const json = await data.json();
const result = domainConfigResponseSchema.parse(json);
@@ -107,15 +94,9 @@ export const domainRouter = createTRPCRouter({
if (!opts.input.domain) {
return null;
}
- const data = await fetch(
- `https://api.vercel.com/v9/projects/${env.PROJECT_ID_VERCEL}/domains/${opts.input.domain}/verify?teamId=${env.TEAM_ID_VERCEL}`,
- {
- method: "POST",
- headers: {
- Authorization: `Bearer ${env.VERCEL_AUTH_BEARER_TOKEN}`,
- "Content-Type": "application/json",
- },
- },
+ const data = await vercelFetch(
+ `/v9/projects/${env.PROJECT_ID_VERCEL}/domains/${opts.input.domain}/verify?teamId=${env.TEAM_ID_VERCEL}`,
+ { method: "POST" },
);
const json = await data.json();
const result = domainResponseSchema.parse(json);
diff --git a/packages/api/src/router/page.ts b/packages/api/src/router/page.ts
index 9dff33a8c..6566567ec 100644
--- a/packages/api/src/router/page.ts
+++ b/packages/api/src/router/page.ts
@@ -31,88 +31,13 @@ import {
import { TRPCError } from "@trpc/server";
import { z } from "zod";
-import { env } from "../env";
+import {
+ addDomainToVercel,
+ removeDomainFromVercelIfUnused,
+} from "../lib/vercel";
import { toServiceCtx, toTRPCError } from "../service-adapter";
import { createTRPCRouter, protectedProcedure } from "../trpc";
-// Vercel domain helpers — transport-layer external integrations that
-// don't belong in the service layer.
-async function addDomainToVercel(domain: string) {
- const response = await fetch(
- `https://api.vercel.com/v9/projects/${env.PROJECT_ID_VERCEL}/domains?teamId=${env.TEAM_ID_VERCEL}`,
- {
- body: JSON.stringify({ name: domain }),
- headers: {
- Authorization: `Bearer ${env.VERCEL_AUTH_BEARER_TOKEN}`,
- "Content-Type": "application/json",
- },
- method: "POST",
- },
- );
-
- if (!response.ok) {
- const error = await response.json().catch(() => ({}));
- const code = error?.error?.code;
- console.error("Failed to add domain to Vercel:", { domain, error });
- throw toDomainError(domain, code);
- }
-
- return response.json();
-}
-
-// Vercel messages leak internal project details, so map known codes to our own copy.
-function toDomainError(domain: string, code?: string): TRPCError {
- switch (code) {
- case "domain_already_in_use":
- return new TRPCError({
- code: "CONFLICT",
- message: `The domain '${domain}' is already in use by another status page. Remove it there first or contact support.`,
- });
- case "invalid_domain":
- case "not_found":
- return new TRPCError({
- code: "BAD_REQUEST",
- message: `The domain '${domain}' is invalid.`,
- });
- case "forbidden":
- case "domain_taken":
- return new TRPCError({
- code: "FORBIDDEN",
- message: `The domain '${domain}' belongs to another team on our hosting provider. Contact support if you own it.`,
- });
- default:
- return new TRPCError({
- code: "INTERNAL_SERVER_ERROR",
- message:
- "Failed to add custom domain. Please try again. If it continues, contact support.",
- });
- }
-}
-
-async function removeDomainFromVercel(domain: string) {
- const response = await fetch(
- `https://api.vercel.com/v9/projects/${env.PROJECT_ID_VERCEL}/domains/${domain}?teamId=${env.TEAM_ID_VERCEL}`,
- {
- headers: {
- Authorization: `Bearer ${env.VERCEL_AUTH_BEARER_TOKEN}`,
- },
- method: "DELETE",
- },
- );
-
- if (!response.ok) {
- const error = await response.json().catch(() => ({}));
- console.error("Failed to remove domain from Vercel:", { domain, error });
- throw new TRPCError({
- code: "INTERNAL_SERVER_ERROR",
- message:
- "Failed to remove custom domain. Please try again. If it continues, contact support.",
- });
- }
-
- return response.json();
-}
-
export const pageRouter = createTRPCRouter({
create: protectedProcedure
.meta({ track: Events.CreatePage, trackProps: ["slug"] })
@@ -133,10 +58,27 @@ export const pageRouter = createTRPCRouter({
.input(z.object({ id: z.number() }))
.mutation(async ({ ctx, input }) => {
try {
+ const sCtx = toServiceCtx(ctx);
+ const customDomain = await getPageCustomDomain({
+ ctx: sCtx,
+ input: { id: input.id },
+ });
await deletePage({
- ctx: toServiceCtx(ctx),
+ ctx: sCtx,
input: { id: input.id },
});
+ // best-effort: the page is gone either way, a leaked Vercel
+ // attachment is recoverable while a failed delete is not
+ if (customDomain) {
+ try {
+ await removeDomainFromVercelIfUnused(ctx.db, customDomain);
+ } catch (err) {
+ console.error("Failed to release domain from Vercel:", {
+ domain: customDomain,
+ error: err,
+ });
+ }
+ }
} catch (err) {
if (err instanceof NotFoundError) return;
toTRPCError(err);
@@ -280,14 +222,20 @@ export const pageRouter = createTRPCRouter({
});
const newDomain = input.customDomain;
- // unchanged saves must be a no-op — re-adding an existing domain fails on Vercel
- if (newDomain === oldDomain) return;
+ // unchanged saves must be a no-op — re-adding an existing domain
+ // fails on Vercel; case-insensitive since DNS is and the schema
+ // doesn't lowercase, so a case-only re-save must not re-add either
+ if (newDomain.toLowerCase() === oldDomain.toLowerCase()) return;
if (newDomain) {
await addDomainToVercel(newDomain);
}
if (oldDomain) {
- await removeDomainFromVercel(oldDomain);
+ // this page's row still holds oldDomain until the update below,
+ // so exclude it — any other holder keeps the domain on Vercel
+ await removeDomainFromVercelIfUnused(ctx.db, oldDomain, {
+ excludePageId: input.id,
+ });
}
await updatePageCustomDomain({
diff --git a/packages/api/src/router/stripe/webhook.ts b/packages/api/src/router/stripe/webhook.ts
index 192f5e5cc..8eac89de6 100644
--- a/packages/api/src/router/stripe/webhook.ts
+++ b/packages/api/src/router/stripe/webhook.ts
@@ -15,6 +15,7 @@ import { TRPCError } from "@trpc/server";
import type Stripe from "stripe";
import { z } from "zod";
+import { removeDomainFromVercelIfUnused } from "../../lib/vercel";
import { createTRPCRouter, publicProcedure } from "../../trpc";
import { stripe } from "./shared";
import { buildLimitsFromSubscription } from "./utils";
@@ -223,115 +224,139 @@ export const webhookRouter = createTRPCRouter({
return;
}
- const _workspace = await opts.ctx.db.transaction(async (tx) => {
- const _workspace = await tx
- .update(workspace)
- .set({
- subscriptionId: null,
- plan: "free",
- paidUntil: null,
- endsAt: null,
- limits: JSON.stringify(getLimits("free")),
- })
- .where(eq(workspace.stripeId, customerId))
- .returning();
-
- if (!_workspace.length) {
- throw new TRPCError({
- code: "BAD_REQUEST",
- message: "Workspace not found",
- });
- }
-
- const workspaceId = _workspace[0].id;
-
- const activeMonitors = await tx
- .select({ id: monitor.id })
- .from(monitor)
- .where(
- and(
- eq(monitor.workspaceId, workspaceId),
- eq(monitor.active, true),
- isNull(monitor.deletedAt),
+ const { workspaces, customDomains } = await opts.ctx.db.transaction(
+ async (tx) => {
+ const _workspace = await tx
+ .update(workspace)
+ .set({
+ subscriptionId: null,
+ plan: "free",
+ paidUntil: null,
+ endsAt: null,
+ limits: JSON.stringify(getLimits("free")),
+ })
+ .where(eq(workspace.stripeId, customerId))
+ .returning();
+
+ if (!_workspace.length) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: "Workspace not found",
+ });
+ }
+
+ const workspaceId = _workspace[0].id;
+
+ const activeMonitors = await tx
+ .select({ id: monitor.id })
+ .from(monitor)
+ .where(
+ and(
+ eq(monitor.workspaceId, workspaceId),
+ eq(monitor.active, true),
+ isNull(monitor.deletedAt),
+ ),
+ )
+ .orderBy(asc(monitor.createdAt));
+
+ for (const m of activeMonitors.slice(1)) {
+ await tx
+ .update(monitor)
+ .set({ active: false, updatedAt: new Date() })
+ .where(eq(monitor.id, m.id))
+ .run();
+ }
+
+ const statusPages = await tx
+ .select({ id: page.id, customDomain: page.customDomain })
+ .from(page)
+ .where(eq(page.workspaceId, workspaceId))
+ .orderBy(asc(page.createdAt));
+
+ const customDomains = [
+ ...new Set(
+ statusPages
+ .map((p) => p.customDomain)
+ .filter((domain) => domain !== ""),
),
- )
- .orderBy(asc(monitor.createdAt));
-
- for (const m of activeMonitors.slice(1)) {
+ ];
+
+ for (const p of statusPages.slice(1)) {
+ await tx.delete(page).where(eq(page.id, p.id)).run();
+ }
+
+ if (statusPages.length > 0) {
+ await tx
+ .update(page)
+ .set({
+ customDomain: "",
+ password: null,
+ accessType: "public",
+ authEmailDomains: null,
+ updatedAt: new Date(),
+ })
+ .where(eq(page.id, statusPages[0].id))
+ .run();
+ }
+
+ const notifications = await tx
+ .select({ id: notification.id, provider: notification.provider })
+ .from(notification)
+ .where(eq(notification.workspaceId, workspaceId))
+ .orderBy(asc(notification.createdAt));
+
+ const keepNotification =
+ notifications.find((n) => n.provider === "email") ?? notifications[0];
+
+ for (const n of notifications.filter(
+ (n) => n.id !== keepNotification?.id,
+ )) {
+ await tx.delete(notification).where(eq(notification.id, n.id)).run();
+ }
+
+ // Remove all non-owner members from the workspace
await tx
- .update(monitor)
- .set({ active: false, updatedAt: new Date() })
- .where(eq(monitor.id, m.id))
+ .delete(usersToWorkspaces)
+ .where(
+ and(
+ eq(usersToWorkspaces.workspaceId, workspaceId),
+ ne(usersToWorkspaces.role, "owner"),
+ ),
+ )
.run();
- }
-
- const statusPages = await tx
- .select({ id: page.id })
- .from(page)
- .where(eq(page.workspaceId, workspaceId))
- .orderBy(asc(page.createdAt));
-
- for (const p of statusPages.slice(1)) {
- await tx.delete(page).where(eq(page.id, p.id)).run();
- }
- if (statusPages.length > 0) {
+ // Remove all pending invitations for the workspace
await tx
- .update(page)
- .set({
- customDomain: "",
- password: null,
- accessType: "public",
- authEmailDomains: null,
- updatedAt: new Date(),
- })
- .where(eq(page.id, statusPages[0].id))
+ .delete(invitation)
+ .where(eq(invitation.workspaceId, workspaceId))
.run();
- }
- const notifications = await tx
- .select({ id: notification.id, provider: notification.provider })
- .from(notification)
- .where(eq(notification.workspaceId, workspaceId))
- .orderBy(asc(notification.createdAt));
-
- const keepNotification =
- notifications.find((n) => n.provider === "email") ?? notifications[0];
-
- for (const n of notifications.filter(
- (n) => n.id !== keepNotification?.id,
- )) {
- await tx.delete(notification).where(eq(notification.id, n.id)).run();
- }
-
- // Remove all non-owner members from the workspace
- await tx
- .delete(usersToWorkspaces)
- .where(
- and(
- eq(usersToWorkspaces.workspaceId, workspaceId),
- ne(usersToWorkspaces.role, "owner"),
- ),
- )
- .run();
-
- // Remove all pending invitations for the workspace
- await tx
- .delete(invitation)
- .where(eq(invitation.workspaceId, workspaceId))
- .run();
-
- return _workspace;
- });
+ return { workspaces: _workspace, customDomains };
+ },
+ );
- if (!_workspace[0]) {
+ if (!workspaces[0]) {
throw new TRPCError({
code: "BAD_REQUEST",
message: "Workspace not found",
});
}
- const workspaceId = _workspace[0].id;
+ // Free plan has no custom-domain feature — release each domain on Vercel
+ // unless another workspace's page still holds it. Best-effort after
+ // commit: a Vercel error must not fail the webhook into Stripe retries.
+ for (const domain of customDomains) {
+ try {
+ await removeDomainFromVercelIfUnused(opts.ctx.db, domain);
+ } catch (err) {
+ console.error("Failed to release domain from Vercel:", {
+ domain,
+ error: err,
+ });
+ }
+ }
+
+ const workspaceId = workspaces[0].id;
const customer = await stripe.customers.retrieve(customerId);
if (!customer.deleted && customer.email) {
diff --git a/packages/services/src/notification/create.ts b/packages/services/src/notification/create.ts
index f6c51a304..ce91935c7 100644
--- a/packages/services/src/notification/create.ts
+++ b/packages/services/src/notification/create.ts
@@ -26,6 +26,14 @@ export async function createNotification(args: {
const input = CreateNotificationInput.parse(args.input);
return withTransaction(ctx, async (tx) => {
+ // Ownership before quota: a cross-workspace monitor must fail with
+ // ForbiddenError regardless of the workspace's notification count.
+ const validatedMonitors = await validateMonitorIds({
+ tx,
+ workspaceId: ctx.workspace.id,
+ monitorIds: input.monitors,
+ });
+
// Plan gate on notification count.
const existing = await tx
.select({ count: count() })
@@ -47,12 +55,6 @@ export async function createNotification(args: {
validateNotificationData(input.provider, input.data);
- const validatedMonitors = await validateMonitorIds({
- tx,
- workspaceId: ctx.workspace.id,
- monitorIds: input.monitors,
- });
-
const row = await tx
.insert(notification)
.values({
diff --git a/packages/services/src/page/list.ts b/packages/services/src/page/list.ts
index fc4711e7c..d7edce8ca 100644
--- a/packages/services/src/page/list.ts
+++ b/packages/services/src/page/list.ts
@@ -47,11 +47,13 @@ export async function listPages(args: {
const input = ListPagesInput.parse(args.input);
const db = getReadDb(ctx);
+ const dir = input.order === "asc" ? asc : desc;
const pageRows = await db
.select()
.from(page)
.where(eq(page.workspaceId, ctx.workspace.id))
- .orderBy(input.order === "asc" ? asc(page.createdAt) : desc(page.createdAt))
+ // id tiebreaker: createdAt ties would make offset pagination unstable
+ .orderBy(dir(page.createdAt), dir(page.id))
.all();
if (pageRows.length === 0) return [];