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,76 @@
|
||||
import { NextResponse } from "next/server"
|
||||
import { and, eq } from "drizzle-orm"
|
||||
import { z } from "zod"
|
||||
import { db } from "@/lib/db"
|
||||
import { maintenance_requests } from "@/lib/db/schema"
|
||||
import { maintenanceSchema } from "@/lib/validations"
|
||||
import { ownsProperty, ownsUnit, ownsTenant } from "@/lib/db/ownership"
|
||||
import { resolveApiRequest } from "@/lib/api-auth"
|
||||
import { emitWebhookEvent } from "@/lib/webhooks/emit"
|
||||
|
||||
// Public REST API (v1) — update a single maintenance request. Bearer API-key
|
||||
// auth. Owner-scoped by id; mirrors the internal PATCH schema.
|
||||
|
||||
const unauthorized = () =>
|
||||
NextResponse.json({ error: { code: 401, message: "Unauthorized" } }, { status: 401 })
|
||||
const forbidden = () =>
|
||||
NextResponse.json({ error: { code: 403, message: "Forbidden" } }, { status: 403 })
|
||||
|
||||
const maintenancePatchSchema = maintenanceSchema.partial().extend({
|
||||
status: z.enum(["open", "in_progress", "resolved", "closed"]).optional(),
|
||||
resolution_notes: z.string().optional(),
|
||||
actual_cost: z.number().positive().optional(),
|
||||
resolved_at: z.string().optional(),
|
||||
})
|
||||
|
||||
export async function PATCH(request: Request, { params }: { params: Promise<{ id: string }> }) {
|
||||
const ctx = await resolveApiRequest(request)
|
||||
if (!ctx) return unauthorized()
|
||||
if (!ctx.canWrite) return forbidden()
|
||||
|
||||
const { id } = await params
|
||||
const body = await request.json().catch(() => null)
|
||||
const parsed = maintenancePatchSchema.safeParse(body)
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json(
|
||||
{ error: { code: 400, message: parsed.error.flatten() } },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
// If any FK is being changed, ensure the caller owns the referenced rows.
|
||||
if (
|
||||
!(await ownsProperty(ctx.ownerId, parsed.data.property_id)) ||
|
||||
!(await ownsUnit(ctx.ownerId, parsed.data.unit_id)) ||
|
||||
!(await ownsTenant(ctx.ownerId, parsed.data.tenant_id))
|
||||
) {
|
||||
return forbidden()
|
||||
}
|
||||
|
||||
const updateData: Record<string, unknown> = { ...parsed.data }
|
||||
|
||||
// Auto-stamp resolved_at when transitioning to resolved.
|
||||
if (parsed.data.status === "resolved" && !parsed.data.resolved_at) {
|
||||
updateData.resolved_at = new Date().toISOString()
|
||||
}
|
||||
|
||||
const [data] = await db
|
||||
.update(maintenance_requests)
|
||||
.set(updateData)
|
||||
.where(and(eq(maintenance_requests.id, id), eq(maintenance_requests.user_id, ctx.ownerId)))
|
||||
.returning()
|
||||
|
||||
if (!data) {
|
||||
return NextResponse.json({ error: { code: 404, message: "Not found" } }, { status: 404 })
|
||||
}
|
||||
|
||||
if (parsed.data.status) {
|
||||
await emitWebhookEvent({
|
||||
ownerId: ctx.ownerId,
|
||||
event: "maintenance.updated",
|
||||
data: { maintenance: data },
|
||||
})
|
||||
}
|
||||
|
||||
return NextResponse.json({ data })
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import { NextResponse } from "next/server"
|
||||
import { and, desc, eq } from "drizzle-orm"
|
||||
import { db } from "@/lib/db"
|
||||
import { maintenance_requests } from "@/lib/db/schema"
|
||||
import { maintenanceSchema } from "@/lib/validations"
|
||||
import { ownsProperty, ownsUnit, ownsTenant } from "@/lib/db/ownership"
|
||||
import { resolveApiRequest } from "@/lib/api-auth"
|
||||
import { emitWebhookEvent } from "@/lib/webhooks/emit"
|
||||
|
||||
// Public REST API (v1) — maintenance requests. Bearer API-key auth.
|
||||
// Scoped by the resolved owner id.
|
||||
|
||||
const unauthorized = () =>
|
||||
NextResponse.json({ error: { code: 401, message: "Unauthorized" } }, { status: 401 })
|
||||
const forbidden = () =>
|
||||
NextResponse.json({ error: { code: 403, message: "Forbidden" } }, { status: 403 })
|
||||
|
||||
const VALID_STATUSES = ["open", "in_progress", "resolved", "closed"]
|
||||
const VALID_PRIORITIES = ["low", "medium", "high", "emergency"]
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const ctx = await resolveApiRequest(request)
|
||||
if (!ctx) return unauthorized()
|
||||
|
||||
const { searchParams } = new URL(request.url)
|
||||
const status = searchParams.get("status")
|
||||
const priority = searchParams.get("priority")
|
||||
const propertyId = searchParams.get("property_id")
|
||||
|
||||
if (status && !VALID_STATUSES.includes(status)) {
|
||||
return NextResponse.json({ error: { code: 400, message: "Invalid status" } }, { status: 400 })
|
||||
}
|
||||
if (priority && !VALID_PRIORITIES.includes(priority)) {
|
||||
return NextResponse.json({ error: { code: 400, message: "Invalid priority" } }, { status: 400 })
|
||||
}
|
||||
|
||||
const data = await db.query.maintenance_requests.findMany({
|
||||
where: and(
|
||||
eq(maintenance_requests.user_id, ctx.ownerId),
|
||||
status ? eq(maintenance_requests.status, status as typeof maintenance_requests.$inferSelect.status) : undefined,
|
||||
priority ? eq(maintenance_requests.priority, priority as typeof maintenance_requests.$inferSelect.priority) : undefined,
|
||||
propertyId ? eq(maintenance_requests.property_id, propertyId) : undefined
|
||||
),
|
||||
with: {
|
||||
property: { columns: { name: true } },
|
||||
unit: { columns: { unit_number: true } },
|
||||
tenant: { columns: { first_name: true, last_name: true } },
|
||||
},
|
||||
orderBy: desc(maintenance_requests.created_at),
|
||||
})
|
||||
|
||||
return NextResponse.json({ data, count: data.length })
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const ctx = await resolveApiRequest(request)
|
||||
if (!ctx) return unauthorized()
|
||||
if (!ctx.canWrite) return forbidden()
|
||||
|
||||
const body = await request.json().catch(() => null)
|
||||
const parsed = maintenanceSchema.safeParse(body)
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json(
|
||||
{ error: { code: 400, message: parsed.error.flatten() } },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
if (
|
||||
!(await ownsProperty(ctx.ownerId, parsed.data.property_id)) ||
|
||||
!(await ownsUnit(ctx.ownerId, parsed.data.unit_id)) ||
|
||||
!(await ownsTenant(ctx.ownerId, parsed.data.tenant_id))
|
||||
) {
|
||||
return forbidden()
|
||||
}
|
||||
|
||||
const [data] = await db
|
||||
.insert(maintenance_requests)
|
||||
.values({ ...parsed.data, user_id: ctx.ownerId, status: "open" })
|
||||
.returning()
|
||||
|
||||
await emitWebhookEvent({
|
||||
ownerId: ctx.ownerId,
|
||||
event: "maintenance.created",
|
||||
data: { maintenance: data },
|
||||
})
|
||||
|
||||
return NextResponse.json({ data }, { status: 201 })
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { NextResponse } from "next/server"
|
||||
import { and, desc, eq, gte, lte } from "drizzle-orm"
|
||||
import { db } from "@/lib/db"
|
||||
import { rent_payments } from "@/lib/db/schema"
|
||||
import { rentPaymentSchema } from "@/lib/validations"
|
||||
import { ownsProperty, ownsUnit, ownsTenant } from "@/lib/db/ownership"
|
||||
import { resolveApiRequest } from "@/lib/api-auth"
|
||||
import { emitWebhookEvent } from "@/lib/webhooks/emit"
|
||||
|
||||
// Public REST API (v1) — rent payments. Bearer API-key auth. Maps to the
|
||||
// rent_payments table / internal /api/rent logic. Scoped by resolved owner id.
|
||||
|
||||
const unauthorized = () =>
|
||||
NextResponse.json({ error: { code: 401, message: "Unauthorized" } }, { status: 401 })
|
||||
const forbidden = () =>
|
||||
NextResponse.json({ error: { code: 403, message: "Forbidden" } }, { status: 403 })
|
||||
|
||||
const VALID_STATUSES = ["pending", "paid", "overdue", "partial", "waived"]
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const ctx = await resolveApiRequest(request)
|
||||
if (!ctx) return unauthorized()
|
||||
|
||||
const { searchParams } = new URL(request.url)
|
||||
const status = searchParams.get("status")
|
||||
const tenantId = searchParams.get("tenant_id")
|
||||
// Date-range filter on the payment's due_date ("YYYY-MM-DD").
|
||||
const from = searchParams.get("from")
|
||||
const to = searchParams.get("to")
|
||||
|
||||
if (status && !VALID_STATUSES.includes(status)) {
|
||||
return NextResponse.json(
|
||||
{ error: { code: 400, message: "Invalid status" } },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
const data = await db.query.rent_payments.findMany({
|
||||
where: and(
|
||||
eq(rent_payments.user_id, ctx.ownerId),
|
||||
status ? eq(rent_payments.status, status as typeof rent_payments.$inferSelect.status) : undefined,
|
||||
tenantId ? eq(rent_payments.tenant_id, tenantId) : undefined,
|
||||
from ? gte(rent_payments.due_date, from) : undefined,
|
||||
to ? lte(rent_payments.due_date, to) : undefined
|
||||
),
|
||||
with: {
|
||||
tenant: { columns: { first_name: true, last_name: true, email: true } },
|
||||
property: { columns: { name: true } },
|
||||
unit: { columns: { unit_number: true } },
|
||||
},
|
||||
orderBy: desc(rent_payments.due_date),
|
||||
})
|
||||
|
||||
return NextResponse.json({ data, count: data.length })
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const ctx = await resolveApiRequest(request)
|
||||
if (!ctx) return unauthorized()
|
||||
if (!ctx.canWrite) return forbidden()
|
||||
|
||||
const body = await request.json().catch(() => null)
|
||||
const parsed = rentPaymentSchema.safeParse(body)
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json(
|
||||
{ error: { code: 400, message: parsed.error.flatten() } },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
if (
|
||||
!(await ownsProperty(ctx.ownerId, parsed.data.property_id)) ||
|
||||
!(await ownsUnit(ctx.ownerId, parsed.data.unit_id)) ||
|
||||
!(await ownsTenant(ctx.ownerId, parsed.data.tenant_id))
|
||||
) {
|
||||
return forbidden()
|
||||
}
|
||||
|
||||
const [data] = await db
|
||||
.insert(rent_payments)
|
||||
.values({ ...parsed.data, user_id: ctx.ownerId })
|
||||
.returning()
|
||||
|
||||
await emitWebhookEvent({ ownerId: ctx.ownerId, event: "payment.recorded", data: { payment: data } })
|
||||
if (data.status === "paid") {
|
||||
await emitWebhookEvent({ ownerId: ctx.ownerId, event: "payment.paid", data: { payment: data } })
|
||||
}
|
||||
|
||||
return NextResponse.json({ data }, { status: 201 })
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { NextResponse } from "next/server"
|
||||
import { desc, eq } from "drizzle-orm"
|
||||
import { db } from "@/lib/db"
|
||||
import { properties } from "@/lib/db/schema"
|
||||
import { propertySchema } from "@/lib/validations"
|
||||
import { resolveApiRequest } from "@/lib/api-auth"
|
||||
import { emitWebhookEvent } from "@/lib/webhooks/emit"
|
||||
import { geocodeAddress } from "@/lib/geocoding"
|
||||
|
||||
// Public REST API (v1) — Bearer API-key auth. All data is scoped by the
|
||||
// resolved account owner id (team-aware), never the raw session user.
|
||||
|
||||
const unauthorized = () =>
|
||||
NextResponse.json({ error: { code: 401, message: "Unauthorized" } }, { status: 401 })
|
||||
const forbidden = () =>
|
||||
NextResponse.json({ error: { code: 403, message: "Forbidden" } }, { status: 403 })
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const ctx = await resolveApiRequest(request)
|
||||
if (!ctx) return unauthorized()
|
||||
|
||||
const data = await db.query.properties.findMany({
|
||||
where: eq(properties.user_id, ctx.ownerId),
|
||||
with: { units: { columns: { id: true, status: true } } },
|
||||
orderBy: desc(properties.created_at),
|
||||
})
|
||||
|
||||
return NextResponse.json({ data, count: data.length })
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const ctx = await resolveApiRequest(request)
|
||||
if (!ctx) return unauthorized()
|
||||
if (!ctx.canWrite) return forbidden()
|
||||
|
||||
const body = await request.json().catch(() => null)
|
||||
const parsed = propertySchema.safeParse(body)
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json(
|
||||
{ error: { code: 400, message: parsed.error.flatten() } },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
const coords = await geocodeAddress(parsed.data)
|
||||
|
||||
const [data] = await db
|
||||
.insert(properties)
|
||||
.values({ ...parsed.data, user_id: ctx.ownerId, ...(coords ?? {}) })
|
||||
.returning()
|
||||
|
||||
await emitWebhookEvent({ ownerId: ctx.ownerId, event: "property.created", data: { property: data } })
|
||||
|
||||
return NextResponse.json({ data }, { status: 201 })
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { NextResponse } from "next/server"
|
||||
import { and, desc, eq } from "drizzle-orm"
|
||||
import { db } from "@/lib/db"
|
||||
import { tenants } from "@/lib/db/schema"
|
||||
import { resolveApiRequest } from "@/lib/api-auth"
|
||||
|
||||
// Public REST API (v1) — Bearer API-key auth. Scoped by the resolved owner id.
|
||||
|
||||
const unauthorized = () =>
|
||||
NextResponse.json({ error: { code: 401, message: "Unauthorized" } }, { status: 401 })
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const ctx = await resolveApiRequest(request)
|
||||
if (!ctx) return unauthorized()
|
||||
|
||||
const { searchParams } = new URL(request.url)
|
||||
const propertyId = searchParams.get("property_id")
|
||||
const status = searchParams.get("status")
|
||||
|
||||
const validStatuses = ["active", "moved_out", "evicted"]
|
||||
if (status && !validStatuses.includes(status)) {
|
||||
return NextResponse.json(
|
||||
{ error: { code: 400, message: "Invalid status" } },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
// Include unit + lease status so consumers can see each tenant's lease state,
|
||||
// mirroring the internal /api/tenants route's enriched shape.
|
||||
const data = await db.query.tenants.findMany({
|
||||
where: and(
|
||||
eq(tenants.user_id, ctx.ownerId),
|
||||
status ? eq(tenants.status, status as typeof tenants.$inferSelect.status) : undefined,
|
||||
propertyId ? eq(tenants.property_id, propertyId) : undefined
|
||||
),
|
||||
with: {
|
||||
unit: { columns: { unit_number: true, rent_amount: true, status: true } },
|
||||
property: { columns: { name: true } },
|
||||
leases: { columns: { id: true, status: true, lease_start: true, lease_end: true } },
|
||||
},
|
||||
orderBy: desc(tenants.created_at),
|
||||
})
|
||||
|
||||
return NextResponse.json({ data, count: data.length })
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import { NextResponse } from "next/server"
|
||||
import { and, eq } from "drizzle-orm"
|
||||
import { db } from "@/lib/db"
|
||||
import { webhook_endpoints } from "@/lib/db/schema"
|
||||
import { resolveApiRequest } from "@/lib/api-auth"
|
||||
import { webhookEndpointSchema } from "@/lib/validations"
|
||||
import { isWebhookEvent } from "@/lib/webhooks/events"
|
||||
import { assertSafeWebhookUrl, WebhookUrlError } from "@/lib/webhooks/ssrf"
|
||||
|
||||
// Public REST API (v1) — read/update/delete a single webhook subscription.
|
||||
// DELETE is what Zapier's REST-hook unsubscribe calls. Owner-scoped by id.
|
||||
|
||||
const unauthorized = () =>
|
||||
NextResponse.json({ error: { code: 401, message: "Unauthorized" } }, { status: 401 })
|
||||
const forbidden = () =>
|
||||
NextResponse.json({ error: { code: 403, message: "Forbidden" } }, { status: 403 })
|
||||
const notFound = () =>
|
||||
NextResponse.json({ error: { code: 404, message: "Not found" } }, { status: 404 })
|
||||
|
||||
// Fields returned to API consumers (never the signing secret).
|
||||
const RETURN_COLUMNS = {
|
||||
id: webhook_endpoints.id,
|
||||
url: webhook_endpoints.url,
|
||||
description: webhook_endpoints.description,
|
||||
events: webhook_endpoints.events,
|
||||
status: webhook_endpoints.status,
|
||||
source: webhook_endpoints.source,
|
||||
created_at: webhook_endpoints.created_at,
|
||||
}
|
||||
|
||||
export async function GET(request: Request, { params }: { params: Promise<{ id: string }> }) {
|
||||
const ctx = await resolveApiRequest(request)
|
||||
if (!ctx) return unauthorized()
|
||||
|
||||
const { id } = await params
|
||||
const data = await db.query.webhook_endpoints.findFirst({
|
||||
where: and(eq(webhook_endpoints.id, id), eq(webhook_endpoints.user_id, ctx.ownerId)),
|
||||
columns: { secret: false },
|
||||
})
|
||||
if (!data) return notFound()
|
||||
return NextResponse.json({ data })
|
||||
}
|
||||
|
||||
export async function PATCH(request: Request, { params }: { params: Promise<{ id: string }> }) {
|
||||
const ctx = await resolveApiRequest(request)
|
||||
if (!ctx) return unauthorized()
|
||||
if (!ctx.canWrite) return forbidden()
|
||||
|
||||
const { id } = await params
|
||||
const body = (await request.json().catch(() => null)) as Record<string, unknown> | null
|
||||
|
||||
const parsed = webhookEndpointSchema.partial().safeParse(body ?? {})
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json(
|
||||
{ error: { code: 400, message: parsed.error.flatten() } },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
const patch: Partial<typeof webhook_endpoints.$inferInsert> = {}
|
||||
if (parsed.data.url !== undefined) {
|
||||
try {
|
||||
await assertSafeWebhookUrl(parsed.data.url)
|
||||
} catch (e) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: 400,
|
||||
message: e instanceof WebhookUrlError ? e.message : "Invalid webhook URL",
|
||||
},
|
||||
},
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
patch.url = parsed.data.url
|
||||
}
|
||||
if (parsed.data.events !== undefined) {
|
||||
patch.events = Array.from(new Set(parsed.data.events.filter(isWebhookEvent)))
|
||||
}
|
||||
if (parsed.data.description !== undefined) patch.description = parsed.data.description || null
|
||||
if (body?.status === "active" || body?.status === "disabled") patch.status = body.status
|
||||
|
||||
const [data] = await db
|
||||
.update(webhook_endpoints)
|
||||
.set(patch)
|
||||
.where(and(eq(webhook_endpoints.id, id), eq(webhook_endpoints.user_id, ctx.ownerId)))
|
||||
.returning(RETURN_COLUMNS)
|
||||
|
||||
if (!data) return notFound()
|
||||
return NextResponse.json({ data })
|
||||
}
|
||||
|
||||
export async function DELETE(request: Request, { params }: { params: Promise<{ id: string }> }) {
|
||||
const ctx = await resolveApiRequest(request)
|
||||
if (!ctx) return unauthorized()
|
||||
if (!ctx.canWrite) return forbidden()
|
||||
|
||||
const { id } = await params
|
||||
const [deleted] = await db
|
||||
.delete(webhook_endpoints)
|
||||
.where(and(eq(webhook_endpoints.id, id), eq(webhook_endpoints.user_id, ctx.ownerId)))
|
||||
.returning({ id: webhook_endpoints.id })
|
||||
|
||||
if (!deleted) return notFound()
|
||||
return NextResponse.json({ data: { id: deleted.id, deleted: true } })
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import { NextResponse } from "next/server"
|
||||
import { desc, eq } from "drizzle-orm"
|
||||
import { db } from "@/lib/db"
|
||||
import { webhook_endpoints } from "@/lib/db/schema"
|
||||
import { resolveApiRequest } from "@/lib/api-auth"
|
||||
import { webhookEndpointSchema } from "@/lib/validations"
|
||||
import { isWebhookEvent } from "@/lib/webhooks/events"
|
||||
import { assertSafeWebhookUrl, WebhookUrlError } from "@/lib/webhooks/ssrf"
|
||||
import { generateWebhookSecret } from "@/lib/webhooks/deliver"
|
||||
|
||||
// Public REST API (v1) — outbound webhook subscriptions. Bearer API-key auth.
|
||||
// This is the surface Zapier's REST Hooks use: POST here to subscribe, DELETE
|
||||
// /:id to unsubscribe. Scoped by the resolved account owner id.
|
||||
|
||||
const unauthorized = () =>
|
||||
NextResponse.json({ error: { code: 401, message: "Unauthorized" } }, { status: 401 })
|
||||
const forbidden = () =>
|
||||
NextResponse.json({ error: { code: 403, message: "Forbidden" } }, { status: 403 })
|
||||
const badRequest = (message: unknown) =>
|
||||
NextResponse.json({ error: { code: 400, message } }, { status: 400 })
|
||||
|
||||
// The signing secret is not returned on list/read (only at creation & rotation).
|
||||
const PUBLIC_COLUMNS = {
|
||||
id: webhook_endpoints.id,
|
||||
url: webhook_endpoints.url,
|
||||
description: webhook_endpoints.description,
|
||||
events: webhook_endpoints.events,
|
||||
status: webhook_endpoints.status,
|
||||
source: webhook_endpoints.source,
|
||||
last_success_at: webhook_endpoints.last_success_at,
|
||||
last_error_at: webhook_endpoints.last_error_at,
|
||||
failure_count: webhook_endpoints.failure_count,
|
||||
created_at: webhook_endpoints.created_at,
|
||||
}
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const ctx = await resolveApiRequest(request)
|
||||
if (!ctx) return unauthorized()
|
||||
|
||||
const data = await db
|
||||
.select(PUBLIC_COLUMNS)
|
||||
.from(webhook_endpoints)
|
||||
.where(eq(webhook_endpoints.user_id, ctx.ownerId))
|
||||
.orderBy(desc(webhook_endpoints.created_at))
|
||||
|
||||
return NextResponse.json({ data, count: data.length })
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const ctx = await resolveApiRequest(request)
|
||||
if (!ctx) return unauthorized()
|
||||
if (!ctx.canWrite) return forbidden()
|
||||
|
||||
const body = await request.json().catch(() => null)
|
||||
const parsed = webhookEndpointSchema.safeParse(body)
|
||||
if (!parsed.success) return badRequest(parsed.error.flatten())
|
||||
|
||||
try {
|
||||
await assertSafeWebhookUrl(parsed.data.url)
|
||||
} catch (e) {
|
||||
return badRequest(e instanceof WebhookUrlError ? e.message : "Invalid webhook URL")
|
||||
}
|
||||
|
||||
// Requests coming through Zapier's REST-hook subscribe carry a Zapier UA.
|
||||
const ua = request.headers.get("user-agent") ?? ""
|
||||
const source = /zapier/i.test(ua) ? "zapier" : "api"
|
||||
|
||||
const [data] = await db
|
||||
.insert(webhook_endpoints)
|
||||
.values({
|
||||
user_id: ctx.ownerId,
|
||||
url: parsed.data.url,
|
||||
description: parsed.data.description || null,
|
||||
events: Array.from(new Set(parsed.data.events.filter(isWebhookEvent))),
|
||||
secret: generateWebhookSecret(),
|
||||
source,
|
||||
})
|
||||
.returning()
|
||||
|
||||
// Return the secret exactly once, at creation, so the subscriber can verify signatures.
|
||||
return NextResponse.json({ data }, { status: 201 })
|
||||
}
|
||||
Reference in New Issue
Block a user