Consolidate audit-fixes branch: webhooks, integrations, and deploy hardening
Batch commit of the pending working tree on security/audit-fixes-2026-07. Major areas: - Outbound webhooks / Zapier: schema + signed delivery with retries, public v1 API (REST-hook subscribe/unsubscribe), settings UI, cron drain. - Deploy hardening: email via SMTP2GO (Resend fully removed), verified DB TLS (DATABASE_SSL=require + DATABASE_CA), storage fails loud in production when Spaces is unconfigured instead of silently using ephemeral disk. - Integrations & features (concurrent work): accounting (QuickBooks/Xero), e-signature (DocuSign/Dropbox Sign), PayPal, geocoding/maps, onboarding, expanded legal pages. - DB migrations 0006–0009. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.8
parent
969d5d4c8a
commit
c9968531e4
@@ -0,0 +1,30 @@
|
||||
"use server"
|
||||
|
||||
import { revalidatePath } from "next/cache"
|
||||
import { getSessionUser } from "@/lib/session"
|
||||
import { getAccountContext } from "@/lib/account"
|
||||
import { disconnect, syncNow, getProvider, type Provider } from "@/lib/accounting"
|
||||
|
||||
async function ownerGuard() {
|
||||
const user = await getSessionUser()
|
||||
if (!user) throw new Error("Unauthorized")
|
||||
const ctx = await getAccountContext(user.id)
|
||||
if (!ctx.isOwner) throw new Error("Only the account owner can manage integrations")
|
||||
return ctx
|
||||
}
|
||||
|
||||
export async function disconnectAccounting(provider: string) {
|
||||
const ctx = await ownerGuard()
|
||||
if (!getProvider(provider)) throw new Error("Unknown provider")
|
||||
await disconnect(ctx.ownerId, provider as Provider)
|
||||
revalidatePath("/settings/integrations")
|
||||
return { ok: true }
|
||||
}
|
||||
|
||||
export async function syncAccountingNow(provider: string) {
|
||||
const ctx = await ownerGuard()
|
||||
if (!getProvider(provider)) throw new Error("Unknown provider")
|
||||
const result = await syncNow(ctx.ownerId, provider as Provider)
|
||||
revalidatePath("/settings/integrations")
|
||||
return { ok: true, ...result }
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import { eq } from "drizzle-orm"
|
||||
import { z } from "zod"
|
||||
import { getAdminSession } from "@/lib/session"
|
||||
import { logAdminAction } from "@/lib/admin/audit"
|
||||
import { setMaintenanceMode } from "@/lib/settings"
|
||||
import { auth } from "@/lib/auth"
|
||||
import { db } from "@/lib/db"
|
||||
import { profiles, user as userTable } from "@/lib/db/schema"
|
||||
@@ -137,3 +138,23 @@ export async function markEmailVerified(userId: string) {
|
||||
revalidatePath(`/admin/users/${userId}`)
|
||||
return { ok: true }
|
||||
}
|
||||
|
||||
// ── site maintenance mode ─────────────────────────────────────────────────────
|
||||
// Toggles the site-wide maintenance flag (persisted in app_settings). When on,
|
||||
// the marketing site and dashboard show a maintenance page to everyone except
|
||||
// admins. Revalidates the whole app so the change takes effect immediately.
|
||||
export async function setSiteMaintenance(enabled: boolean, message?: string) {
|
||||
const a = await guard()
|
||||
const trimmed = message?.trim() || null
|
||||
|
||||
await setMaintenanceMode({ enabled: Boolean(enabled), message: trimmed })
|
||||
|
||||
await logAdminAction({
|
||||
adminId: a.user.id,
|
||||
action: "maintenance_mode",
|
||||
metadata: { enabled: Boolean(enabled), message: trimmed },
|
||||
})
|
||||
|
||||
revalidatePath("/", "layout")
|
||||
return { ok: true }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
"use server"
|
||||
|
||||
import { revalidatePath } from "next/cache"
|
||||
import { and, eq } from "drizzle-orm"
|
||||
import { db } from "@/lib/db"
|
||||
import { api_keys } from "@/lib/db/schema"
|
||||
import { getSessionUser } from "@/lib/session"
|
||||
import { generateApiKey } from "@/lib/api-auth"
|
||||
|
||||
// ============================================================================
|
||||
// API key management (dashboard, session-authed — NOT api-key authed).
|
||||
//
|
||||
// We store ONLY the SHA-256 hash of each key; the plaintext is returned exactly
|
||||
// once from createApiKey and is never persisted. Every query is scoped to the
|
||||
// session user's id so one user can never touch another user's keys.
|
||||
// ============================================================================
|
||||
|
||||
const SETTINGS_PATH = "/settings/api-keys"
|
||||
|
||||
/**
|
||||
* Create a new API key for the signed-in user. Returns the one-time plaintext
|
||||
* (show it once, then it's gone) plus the non-secret display prefix.
|
||||
*/
|
||||
export async function createApiKey(
|
||||
name: string
|
||||
): Promise<{ plaintext: string; prefix: string }> {
|
||||
const user = await getSessionUser()
|
||||
if (!user) throw new Error("Unauthorized")
|
||||
|
||||
const trimmed = typeof name === "string" ? name.trim() : ""
|
||||
if (!trimmed) throw new Error("Key name is required")
|
||||
if (trimmed.length > 100) throw new Error("Key name must be 100 characters or fewer")
|
||||
|
||||
const { plaintext, hash, prefix } = generateApiKey()
|
||||
|
||||
await db.insert(api_keys).values({
|
||||
user_id: user.id,
|
||||
name: trimmed,
|
||||
key_hash: hash,
|
||||
key_prefix: prefix,
|
||||
})
|
||||
|
||||
revalidatePath(SETTINGS_PATH)
|
||||
return { plaintext, prefix }
|
||||
}
|
||||
|
||||
/**
|
||||
* Revoke one of the signed-in user's keys. Scoped by user_id so a user can
|
||||
* never revoke another user's key. Idempotent: re-revoking is a no-op.
|
||||
*/
|
||||
export async function revokeApiKey(id: string): Promise<void> {
|
||||
const user = await getSessionUser()
|
||||
if (!user) throw new Error("Unauthorized")
|
||||
|
||||
if (typeof id !== "string" || !id) throw new Error("Invalid key id")
|
||||
|
||||
await db
|
||||
.update(api_keys)
|
||||
.set({ revoked_at: new Date().toISOString() })
|
||||
.where(and(eq(api_keys.id, id), eq(api_keys.user_id, user.id)))
|
||||
|
||||
revalidatePath(SETTINGS_PATH)
|
||||
}
|
||||
+41
-6
@@ -4,42 +4,71 @@ import { redirect } from "next/navigation"
|
||||
import { headers } from "next/headers"
|
||||
import { APIError } from "better-auth/api"
|
||||
import { auth } from "@/lib/auth"
|
||||
import { verifyTurnstile } from "@/lib/turnstile"
|
||||
|
||||
const APP_URL = process.env.NEXT_PUBLIC_APP_URL ?? "http://localhost:3000"
|
||||
const CAPTCHA_ERROR = "Please complete the verification challenge and try again."
|
||||
|
||||
/** Post-auth destination — only same-site relative paths (blocks open redirects). */
|
||||
function safeNext(formData: FormData): string {
|
||||
const next = formData.get("next")
|
||||
if (typeof next === "string" && next.startsWith("/") && !next.startsWith("//") && !next.startsWith("/\\")) {
|
||||
return next
|
||||
}
|
||||
return "/dashboard"
|
||||
}
|
||||
|
||||
export async function signUp(formData: FormData) {
|
||||
const email = formData.get("email") as string
|
||||
const password = formData.get("password") as string
|
||||
const fullName = formData.get("full_name") as string
|
||||
const captchaToken = formData.get("cf-turnstile-response") as string | null
|
||||
|
||||
const h = await headers()
|
||||
if (!(await verifyTurnstile(captchaToken, h.get("x-forwarded-for")))) {
|
||||
redirect(`/signup?error=${encodeURIComponent(CAPTCHA_ERROR)}`)
|
||||
}
|
||||
|
||||
try {
|
||||
await auth.api.signUpEmail({
|
||||
body: { email, password, name: fullName },
|
||||
headers: await headers(),
|
||||
// callbackURL is where the verification link lands the user after confirming.
|
||||
body: { email, password, name: fullName, callbackURL: "/dashboard" },
|
||||
headers: h,
|
||||
})
|
||||
} catch (e) {
|
||||
const msg = e instanceof APIError ? e.message : "Sign up failed"
|
||||
redirect(`/signup?error=${encodeURIComponent(msg)}`)
|
||||
}
|
||||
|
||||
redirect("/dashboard")
|
||||
// When email verification is required, the account isn't usable until confirmed —
|
||||
// send the user to the "check your email" screen instead of the dashboard.
|
||||
if (process.env.REQUIRE_EMAIL_VERIFICATION === "true") {
|
||||
redirect("/signup?success=check-email")
|
||||
}
|
||||
redirect(safeNext(formData))
|
||||
}
|
||||
|
||||
export async function signIn(formData: FormData) {
|
||||
const email = formData.get("email") as string
|
||||
const password = formData.get("password") as string
|
||||
const captchaToken = formData.get("cf-turnstile-response") as string | null
|
||||
|
||||
const h = await headers()
|
||||
if (!(await verifyTurnstile(captchaToken, h.get("x-forwarded-for")))) {
|
||||
redirect(`/login?error=${encodeURIComponent(CAPTCHA_ERROR)}`)
|
||||
}
|
||||
|
||||
try {
|
||||
await auth.api.signInEmail({
|
||||
body: { email, password },
|
||||
headers: await headers(),
|
||||
headers: h,
|
||||
})
|
||||
} catch (e) {
|
||||
const msg = e instanceof APIError ? e.message : "Invalid email or password"
|
||||
redirect(`/login?error=${encodeURIComponent(msg)}`)
|
||||
}
|
||||
|
||||
redirect("/dashboard")
|
||||
redirect(safeNext(formData))
|
||||
}
|
||||
|
||||
export async function signInWithGoogle() {
|
||||
@@ -61,11 +90,17 @@ export async function signInWithGoogle() {
|
||||
|
||||
export async function resetPassword(formData: FormData) {
|
||||
const email = formData.get("email") as string
|
||||
const captchaToken = formData.get("cf-turnstile-response") as string | null
|
||||
|
||||
const h = await headers()
|
||||
if (!(await verifyTurnstile(captchaToken, h.get("x-forwarded-for")))) {
|
||||
redirect(`/forgot-password?error=${encodeURIComponent(CAPTCHA_ERROR)}`)
|
||||
}
|
||||
|
||||
try {
|
||||
await auth.api.requestPasswordReset({
|
||||
body: { email, redirectTo: `${APP_URL}/update-password` },
|
||||
headers: await headers(),
|
||||
headers: h,
|
||||
})
|
||||
} catch {
|
||||
// Always report success so we don't reveal whether an account exists.
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
"use server"
|
||||
|
||||
import { redirect } from "next/navigation"
|
||||
import { revalidatePath } from "next/cache"
|
||||
import { eq } from "drizzle-orm"
|
||||
import { db } from "@/lib/db"
|
||||
import { profiles } from "@/lib/db/schema"
|
||||
import { getSessionUser } from "@/lib/session"
|
||||
import { PLAN_LIMITS } from "@/lib/stripe/plans"
|
||||
import { normalizeHexColor } from "@/lib/branding"
|
||||
import type { Plan } from "@/types"
|
||||
|
||||
/**
|
||||
* Saves the current user's white-label branding (brand name, logo, accent color,
|
||||
* "Powered by" toggle). Only landlord/lifetime plans may edit branding — everyone
|
||||
* else is redirected to billing. Values are validated before persisting.
|
||||
*/
|
||||
export async function updateBranding(formData: FormData) {
|
||||
const user = await getSessionUser()
|
||||
if (!user) redirect("/login")
|
||||
|
||||
// Plan gate: white-label is landlord/lifetime only.
|
||||
const profile = await db.query.profiles.findFirst({
|
||||
where: eq(profiles.id, user.id),
|
||||
columns: { plan: true },
|
||||
})
|
||||
const plan = (profile?.plan ?? "starter") as Plan
|
||||
if (!PLAN_LIMITS[plan]?.hasWhiteLabel) {
|
||||
redirect("/settings/billing")
|
||||
}
|
||||
|
||||
// ── Validate inputs ──────────────────────────────────────────────────────
|
||||
const rawName = (formData.get("brand_name") as string | null)?.trim() ?? ""
|
||||
const brandName = rawName ? rawName.slice(0, 60) : null
|
||||
|
||||
const rawLogo = (formData.get("brand_logo_url") as string | null)?.trim() ?? ""
|
||||
// Only accept logo URLs served by our own gated files route.
|
||||
const brandLogoUrl = rawLogo && rawLogo.startsWith("/api/files/") ? rawLogo : null
|
||||
|
||||
const rawColor = (formData.get("brand_color") as string | null) ?? ""
|
||||
const brandColor = normalizeHexColor(rawColor)
|
||||
// If a color was supplied but is malformed, reject rather than silently drop it.
|
||||
if (rawColor.trim() && !brandColor) {
|
||||
throw new Error("Accent color must be a hex value like #4f46e5")
|
||||
}
|
||||
|
||||
const hidePoweredBy = formData.get("hide_powered_by") === "on"
|
||||
|
||||
await db
|
||||
.update(profiles)
|
||||
.set({
|
||||
brand_name: brandName,
|
||||
brand_logo_url: brandLogoUrl,
|
||||
brand_color: brandColor,
|
||||
hide_powered_by: hidePoweredBy,
|
||||
})
|
||||
.where(eq(profiles.id, user.id))
|
||||
|
||||
revalidatePath("/settings/branding")
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
"use server"
|
||||
|
||||
import { revalidatePath } from "next/cache"
|
||||
import { getSessionUser } from "@/lib/session"
|
||||
import { getAccountContext } from "@/lib/account"
|
||||
import { sendLeaseForSignature, getAdapter, type ESignProvider } from "@/lib/esign"
|
||||
|
||||
export async function sendLeaseForSignatureAction(leaseId: string, provider: string) {
|
||||
const user = await getSessionUser()
|
||||
if (!user) throw new Error("Unauthorized")
|
||||
const ctx = await getAccountContext(user.id)
|
||||
if (!ctx.canWrite) throw new Error("You don't have permission to do that")
|
||||
if (!getAdapter(provider)) throw new Error("Unknown provider")
|
||||
await sendLeaseForSignature(ctx.ownerId, leaseId, provider as ESignProvider)
|
||||
revalidatePath(`/leases/${leaseId}`)
|
||||
return { ok: true }
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
"use server"
|
||||
|
||||
import { redirect } from "next/navigation"
|
||||
import { eq } from "drizzle-orm"
|
||||
import { db } from "@/lib/db"
|
||||
import { profiles } from "@/lib/db/schema"
|
||||
import { getSessionUser } from "@/lib/session"
|
||||
|
||||
/** Marks onboarding as finished and sends the user to the dashboard. */
|
||||
export async function completeOnboarding() {
|
||||
const user = await getSessionUser()
|
||||
if (!user) redirect("/login")
|
||||
await db.update(profiles).set({ onboarding_completed: true }).where(eq(profiles.id, user.id))
|
||||
redirect("/dashboard")
|
||||
}
|
||||
@@ -13,14 +13,13 @@ import {
|
||||
expenses,
|
||||
profiles,
|
||||
} from "@/lib/db/schema"
|
||||
import { getSessionUser } from "@/lib/session"
|
||||
import { getSessionUser, isAdminUser } from "@/lib/session"
|
||||
import { redirect } from "next/navigation"
|
||||
|
||||
export async function seedDemoData() {
|
||||
if (process.env.NODE_ENV === "production") { throw new Error("Demo tools are disabled in production") }
|
||||
|
||||
const user = await getSessionUser()
|
||||
if (!user) redirect("/login")
|
||||
if (!isAdminUser(user)) throw new Error("Admin only")
|
||||
|
||||
const uid = user.id
|
||||
|
||||
@@ -370,10 +369,9 @@ export async function seedDemoData() {
|
||||
}
|
||||
|
||||
export async function setTestPlan(plan: "pro" | "landlord" | "lifetime" | "starter") {
|
||||
if (process.env.NODE_ENV === "production") { throw new Error("Demo tools are disabled in production") }
|
||||
|
||||
const user = await getSessionUser()
|
||||
if (!user) redirect("/login")
|
||||
if (!isAdminUser(user)) throw new Error("Admin only")
|
||||
|
||||
await db.update(profiles).set({ plan }).where(eq(profiles.id, user.id))
|
||||
|
||||
@@ -381,10 +379,9 @@ export async function setTestPlan(plan: "pro" | "landlord" | "lifetime" | "start
|
||||
}
|
||||
|
||||
export async function clearDemoData() {
|
||||
if (process.env.NODE_ENV === "production") { throw new Error("Demo tools are disabled in production") }
|
||||
|
||||
const user = await getSessionUser()
|
||||
if (!user) redirect("/login")
|
||||
if (!isAdminUser(user)) throw new Error("Admin only")
|
||||
|
||||
const uid = user.id
|
||||
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
"use server"
|
||||
|
||||
import { and, eq, ne } from "drizzle-orm"
|
||||
import { db } from "@/lib/db"
|
||||
import { account_members } from "@/lib/db/schema"
|
||||
import { getSessionUser } from "@/lib/session"
|
||||
|
||||
export type AcceptInviteResult =
|
||||
| { ok: true }
|
||||
| { ok: false; error: string }
|
||||
|
||||
/**
|
||||
* Accept a team invite by token.
|
||||
*
|
||||
* Requires an authenticated session (the page redirects to /login first).
|
||||
* On success sets member_id = current user, status='active', accepted_at=now.
|
||||
* A user can be an active member of at most one account, so we block if the
|
||||
* caller is already active somewhere else. Handles invalid / already-used /
|
||||
* revoked tokens gracefully.
|
||||
*/
|
||||
export async function acceptInvite(token: string): Promise<AcceptInviteResult> {
|
||||
const user = await getSessionUser()
|
||||
if (!user) return { ok: false, error: "You must be signed in to accept an invite." }
|
||||
|
||||
const invite = await db.query.account_members.findFirst({
|
||||
where: eq(account_members.invite_token, token),
|
||||
})
|
||||
|
||||
if (!invite) {
|
||||
return { ok: false, error: "This invite link is invalid or has expired." }
|
||||
}
|
||||
|
||||
if (invite.status === "revoked") {
|
||||
return { ok: false, error: "This invite has been revoked by the account owner." }
|
||||
}
|
||||
|
||||
// Already accepted — by this user (fine, treat as success) or someone else.
|
||||
if (invite.status === "active") {
|
||||
if (invite.member_id === user.id) return { ok: true }
|
||||
return { ok: false, error: "This invite has already been accepted." }
|
||||
}
|
||||
|
||||
// Can't be a member of your own account.
|
||||
if (invite.owner_id === user.id) {
|
||||
return { ok: false, error: "You can't accept an invite to your own account." }
|
||||
}
|
||||
|
||||
// A user may be an active member of at most one account.
|
||||
const existingMembership = await db.query.account_members.findFirst({
|
||||
where: and(
|
||||
eq(account_members.member_id, user.id),
|
||||
eq(account_members.status, "active"),
|
||||
ne(account_members.id, invite.id)
|
||||
),
|
||||
})
|
||||
if (existingMembership) {
|
||||
return {
|
||||
ok: false,
|
||||
error:
|
||||
"You're already an active member of another account. Leave it before joining a new one.",
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
// Guard the update on status='pending' so two concurrent accepts can't both win.
|
||||
const [updated] = await db
|
||||
.update(account_members)
|
||||
.set({
|
||||
member_id: user.id,
|
||||
status: "active",
|
||||
accepted_at: new Date().toISOString(),
|
||||
})
|
||||
.where(and(eq(account_members.id, invite.id), eq(account_members.status, "pending")))
|
||||
.returning({ id: account_members.id })
|
||||
|
||||
if (!updated) {
|
||||
return { ok: false, error: "This invite is no longer available." }
|
||||
}
|
||||
} catch {
|
||||
return { ok: false, error: "Something went wrong accepting the invite. Please try again." }
|
||||
}
|
||||
|
||||
return { ok: true }
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
"use server"
|
||||
|
||||
import { revalidatePath } from "next/cache"
|
||||
import { and, eq } from "drizzle-orm"
|
||||
import { db } from "@/lib/db"
|
||||
import { webhook_endpoints } from "@/lib/db/schema"
|
||||
import { getSessionUser } from "@/lib/session"
|
||||
import { getAccountContext } from "@/lib/account"
|
||||
import { webhookEndpointSchema } from "@/lib/validations"
|
||||
import { isWebhookEvent, type WebhookEvent } from "@/lib/webhooks/events"
|
||||
import { assertSafeWebhookUrl, WebhookUrlError } from "@/lib/webhooks/ssrf"
|
||||
import { generateWebhookSecret } from "@/lib/webhooks/deliver"
|
||||
import { deliverTestPing } from "@/lib/webhooks/emit"
|
||||
|
||||
// ============================================================================
|
||||
// Webhook endpoint management (dashboard, session-authed).
|
||||
//
|
||||
// Endpoints belong to the ACCOUNT OWNER (team-aware) so every event across the
|
||||
// portfolio is delivered. Writes require canWrite (viewers are read-only). The
|
||||
// signing secret is stored so it can be shown in the dashboard and used to sign
|
||||
// deliveries; it is not a bearer credential.
|
||||
// ============================================================================
|
||||
|
||||
const SETTINGS_PATH = "/settings/webhooks"
|
||||
|
||||
export type WebhookEndpointDTO = {
|
||||
id: string
|
||||
url: string
|
||||
description: string | null
|
||||
events: string[]
|
||||
secret: string
|
||||
status: "active" | "disabled"
|
||||
source: "dashboard" | "api" | "zapier"
|
||||
last_success_at: string | null
|
||||
last_error_at: string | null
|
||||
last_error: string | null
|
||||
failure_count: number
|
||||
created_at: string
|
||||
}
|
||||
|
||||
function toDTO(row: typeof webhook_endpoints.$inferSelect): WebhookEndpointDTO {
|
||||
return {
|
||||
id: row.id,
|
||||
url: row.url,
|
||||
description: row.description,
|
||||
events: row.events,
|
||||
secret: row.secret,
|
||||
status: row.status,
|
||||
source: row.source,
|
||||
last_success_at: row.last_success_at,
|
||||
last_error_at: row.last_error_at,
|
||||
last_error: row.last_error,
|
||||
failure_count: row.failure_count,
|
||||
created_at: row.created_at,
|
||||
}
|
||||
}
|
||||
|
||||
/** Resolve the writing account owner or throw a user-facing error. */
|
||||
async function requireWriter(): Promise<string> {
|
||||
const user = await getSessionUser()
|
||||
if (!user) throw new Error("Unauthorized")
|
||||
const ctx = await getAccountContext(user.id)
|
||||
if (!ctx.canWrite) throw new Error("You do not have permission to manage webhooks.")
|
||||
return ctx.ownerId
|
||||
}
|
||||
|
||||
function sanitizeEvents(events: unknown): WebhookEvent[] {
|
||||
if (!Array.isArray(events)) return []
|
||||
return Array.from(new Set(events.filter(isWebhookEvent)))
|
||||
}
|
||||
|
||||
export async function createWebhookEndpoint(input: {
|
||||
url: string
|
||||
events: string[]
|
||||
description?: string
|
||||
}): Promise<WebhookEndpointDTO> {
|
||||
const ownerId = await requireWriter()
|
||||
|
||||
const parsed = webhookEndpointSchema.safeParse(input)
|
||||
if (!parsed.success) {
|
||||
throw new Error(parsed.error.issues[0]?.message ?? "Invalid webhook configuration")
|
||||
}
|
||||
|
||||
try {
|
||||
await assertSafeWebhookUrl(parsed.data.url)
|
||||
} catch (e) {
|
||||
throw new Error(e instanceof WebhookUrlError ? e.message : "Invalid webhook URL")
|
||||
}
|
||||
|
||||
const [row] = await db
|
||||
.insert(webhook_endpoints)
|
||||
.values({
|
||||
user_id: ownerId,
|
||||
url: parsed.data.url,
|
||||
description: parsed.data.description || null,
|
||||
events: sanitizeEvents(parsed.data.events),
|
||||
secret: generateWebhookSecret(),
|
||||
source: "dashboard",
|
||||
})
|
||||
.returning()
|
||||
|
||||
revalidatePath(SETTINGS_PATH)
|
||||
return toDTO(row)
|
||||
}
|
||||
|
||||
export async function updateWebhookEndpoint(
|
||||
id: string,
|
||||
input: { url?: string; events?: string[]; description?: string; status?: "active" | "disabled" }
|
||||
): Promise<WebhookEndpointDTO> {
|
||||
const ownerId = await requireWriter()
|
||||
if (typeof id !== "string" || !id) throw new Error("Invalid endpoint id")
|
||||
|
||||
const existing = await db.query.webhook_endpoints.findFirst({
|
||||
where: and(eq(webhook_endpoints.id, id), eq(webhook_endpoints.user_id, ownerId)),
|
||||
})
|
||||
if (!existing) throw new Error("Webhook not found")
|
||||
|
||||
const patch: Partial<typeof webhook_endpoints.$inferInsert> = {}
|
||||
|
||||
if (input.url !== undefined) {
|
||||
const parsed = webhookEndpointSchema.shape.url.safeParse(input.url)
|
||||
if (!parsed.success) throw new Error(parsed.error.issues[0]?.message ?? "Invalid URL")
|
||||
try {
|
||||
await assertSafeWebhookUrl(parsed.data)
|
||||
} catch (e) {
|
||||
throw new Error(e instanceof WebhookUrlError ? e.message : "Invalid webhook URL")
|
||||
}
|
||||
patch.url = parsed.data
|
||||
}
|
||||
if (input.events !== undefined) patch.events = sanitizeEvents(input.events)
|
||||
if (input.description !== undefined) patch.description = input.description.slice(0, 200) || null
|
||||
if (input.status !== undefined) {
|
||||
if (input.status !== "active" && input.status !== "disabled") throw new Error("Invalid status")
|
||||
patch.status = input.status
|
||||
}
|
||||
|
||||
const [row] = await db
|
||||
.update(webhook_endpoints)
|
||||
.set(patch)
|
||||
.where(and(eq(webhook_endpoints.id, id), eq(webhook_endpoints.user_id, ownerId)))
|
||||
.returning()
|
||||
|
||||
revalidatePath(SETTINGS_PATH)
|
||||
return toDTO(row)
|
||||
}
|
||||
|
||||
export async function deleteWebhookEndpoint(id: string): Promise<void> {
|
||||
const ownerId = await requireWriter()
|
||||
if (typeof id !== "string" || !id) throw new Error("Invalid endpoint id")
|
||||
|
||||
await db
|
||||
.delete(webhook_endpoints)
|
||||
.where(and(eq(webhook_endpoints.id, id), eq(webhook_endpoints.user_id, ownerId)))
|
||||
|
||||
revalidatePath(SETTINGS_PATH)
|
||||
}
|
||||
|
||||
export async function rotateWebhookSecret(id: string): Promise<{ secret: string }> {
|
||||
const ownerId = await requireWriter()
|
||||
if (typeof id !== "string" || !id) throw new Error("Invalid endpoint id")
|
||||
|
||||
const secret = generateWebhookSecret()
|
||||
const [row] = await db
|
||||
.update(webhook_endpoints)
|
||||
.set({ secret })
|
||||
.where(and(eq(webhook_endpoints.id, id), eq(webhook_endpoints.user_id, ownerId)))
|
||||
.returning({ id: webhook_endpoints.id })
|
||||
if (!row) throw new Error("Webhook not found")
|
||||
|
||||
revalidatePath(SETTINGS_PATH)
|
||||
return { secret }
|
||||
}
|
||||
|
||||
export async function sendTestWebhook(
|
||||
id: string
|
||||
): Promise<{ ok: boolean; responseStatus: number | null; error: string | null }> {
|
||||
const ownerId = await requireWriter()
|
||||
if (typeof id !== "string" || !id) throw new Error("Invalid endpoint id")
|
||||
|
||||
const endpoint = await db.query.webhook_endpoints.findFirst({
|
||||
where: and(eq(webhook_endpoints.id, id), eq(webhook_endpoints.user_id, ownerId)),
|
||||
})
|
||||
if (!endpoint) throw new Error("Webhook not found")
|
||||
|
||||
const result = await deliverTestPing(endpoint)
|
||||
revalidatePath(SETTINGS_PATH)
|
||||
return result
|
||||
}
|
||||
Reference in New Issue
Block a user