-
Notifications
You must be signed in to change notification settings - Fork 0
feat(super-admin): Platform Webhooks console — inbound + outbound #273
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
146 changes: 146 additions & 0 deletions
146
nextjs_space/app/api/super-admin/webhooks/inbound/route.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,146 @@ | ||
| import { NextResponse } from "next/server"; | ||
| import { z } from "zod"; | ||
| import { withSuperAdmin } from "@/lib/api-auth"; | ||
| import { prisma } from "@/lib/db"; | ||
| import { apiError, apiValidationError } from "@/lib/api-error"; | ||
| import { requireSameOrigin } from "@/lib/security/require-same-origin"; | ||
| import { AUDIT_ACTIONS, createAuditLog, getClientInfo } from "@/lib/audit-log"; | ||
| import { | ||
| DRGREEN_CHANNEL, | ||
| getInboundWebhookStatus, | ||
| saveInboundWebhookSecret, | ||
| setInboundWebhookEnabled, | ||
| } from "@/lib/drgreen/inbound-webhook-config"; | ||
|
|
||
| /** | ||
| * Inbound partner-webhook channel (Dr Green → BudStacks), PLATFORM scope. | ||
| * SUPER_ADMIN only — this secret authenticates events for every tenant, so it | ||
| * must never be reachable from tenant-admin. | ||
| * | ||
| * GET → status + recent deliveries (never the secret itself) | ||
| * PUT → rotate the secret / enable-disable the channel | ||
| * | ||
| * There is no URL to configure here: the receiving endpoint is ours and fixed | ||
| * in code (/api/webhooks/drgreen/status). What an operator manages is the | ||
| * verification secret, the on/off switch, and visibility of what arrived. | ||
| */ | ||
|
|
||
| const ROUTE_GET = "GET /api/super-admin/webhooks/inbound"; | ||
| const ROUTE_PUT = "PUT /api/super-admin/webhooks/inbound"; | ||
|
|
||
| /** How many recent deliveries the console shows. */ | ||
| const RECENT_LIMIT = 25; | ||
|
|
||
| export const GET = withSuperAdmin(async () => { | ||
| try { | ||
| const status = await getInboundWebhookStatus(); | ||
|
|
||
| // Delivery history is best-effort: the console must still render (and | ||
| // still let an operator set the secret) if this query fails. | ||
| let recent: Array<Record<string, unknown>> = []; | ||
| let stats = { total: 0, processed: 0, failed: 0 }; | ||
| try { | ||
| const [rows, total, processed, failed] = await Promise.all([ | ||
| prisma.drgreen_webhook_logs.findMany({ | ||
| where: { webhookType: "status" }, | ||
| orderBy: { createdAt: "desc" }, | ||
| take: RECENT_LIMIT, | ||
| select: { | ||
| id: true, | ||
| tenantId: true, | ||
| drGreenClientId: true, | ||
| processed: true, | ||
| error: true, | ||
| createdAt: true, | ||
| payload: true, | ||
| }, | ||
| }), | ||
| prisma.drgreen_webhook_logs.count({ where: { webhookType: "status" } }), | ||
| prisma.drgreen_webhook_logs.count({ where: { webhookType: "status", processed: true } }), | ||
| prisma.drgreen_webhook_logs.count({ | ||
| where: { webhookType: "status", error: { not: null } }, | ||
| }), | ||
| ]); | ||
| stats = { total, processed, failed }; | ||
| recent = rows.map((row: any) => ({ | ||
| id: row.id, | ||
| tenantId: row.tenantId, | ||
| clientId: row.drGreenClientId, | ||
| // The payload is already PII-redacted on write (sanitizeForLogging); | ||
| // only the event name is surfaced here. | ||
| event: typeof row.payload?.event === "string" ? row.payload.event : "unknown", | ||
| processed: row.processed, | ||
| error: row.error, | ||
| createdAt: row.createdAt.toISOString(), | ||
| })); | ||
| } catch { | ||
| // Leave recent/stats empty — status still renders. | ||
| } | ||
|
|
||
| return NextResponse.json({ | ||
| channel: DRGREEN_CHANNEL, | ||
| // The endpoint Dr Green must POST to. Shown for copy/paste; not editable. | ||
| receivingPath: "/api/webhooks/drgreen/status", | ||
| status, | ||
| stats, | ||
| recent, | ||
| }); | ||
| } catch (error) { | ||
| return apiError(error, { route: ROUTE_GET, safeMessage: "Failed to load webhook status" }); | ||
| } | ||
| }); | ||
|
|
||
| const updateSchema = z | ||
| .object({ | ||
| // Min length is a weak-secret guard, not a format requirement — it must | ||
| // match whatever Dr Green signs with byte for byte. | ||
| secret: z.string().min(16).max(512).optional(), | ||
| isEnabled: z.boolean().optional(), | ||
| }) | ||
| .refine((v) => v.secret !== undefined || v.isEnabled !== undefined, { | ||
| message: "Provide a secret to rotate, an isEnabled flag, or both", | ||
| }); | ||
|
|
||
| export const PUT = withSuperAdmin(async (req, { user }) => { | ||
| const originError = requireSameOrigin(req); | ||
| if (originError) return originError; | ||
|
|
||
| const body = await req.json().catch(() => null); | ||
| const parsed = updateSchema.safeParse(body); | ||
| if (!parsed.success) { | ||
| return apiValidationError(parsed.error.errors[0]?.message ?? "Invalid request", ROUTE_PUT); | ||
| } | ||
|
|
||
| try { | ||
| const actor = user.email ?? user.id; | ||
|
|
||
| if (parsed.data.secret !== undefined) { | ||
| await saveInboundWebhookSecret({ secret: parsed.data.secret, updatedBy: actor }); | ||
| } | ||
| if (parsed.data.isEnabled !== undefined) { | ||
| await setInboundWebhookEnabled({ isEnabled: parsed.data.isEnabled, updatedBy: actor }); | ||
| } | ||
|
|
||
| await createAuditLog({ | ||
| action: AUDIT_ACTIONS.PLATFORM_WEBHOOK_CONFIG_UPDATED, | ||
| entityType: "PlatformWebhookConfig", | ||
| entityId: DRGREEN_CHANNEL, | ||
| userId: user.id, | ||
| userEmail: user.email ?? undefined, | ||
| // Records THAT the secret rotated, never the value. | ||
| metadata: { | ||
| secretRotated: parsed.data.secret !== undefined, | ||
| ...(parsed.data.isEnabled !== undefined ? { isEnabled: parsed.data.isEnabled } : {}), | ||
| }, | ||
| ...getClientInfo(req.headers), | ||
| }); | ||
|
|
||
| return NextResponse.json({ success: true, status: await getInboundWebhookStatus() }); | ||
| } catch (error) { | ||
| return apiError(error, { | ||
| route: ROUTE_PUT, | ||
| safeMessage: | ||
| "Failed to save webhook settings. If this persists, the platform_webhook_config table may not be provisioned yet.", | ||
| }); | ||
| } | ||
| }); |
51 changes: 51 additions & 0 deletions
51
nextjs_space/app/api/super-admin/webhooks/outbound/[id]/route.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,51 @@ | ||
| import { NextResponse } from "next/server"; | ||
| import { withSuperAdminParams } from "@/lib/api-auth"; | ||
| import { prisma } from "@/lib/db"; | ||
| import { apiError } from "@/lib/api-error"; | ||
| import { requireSameOrigin } from "@/lib/security/require-same-origin"; | ||
| import { parseUuid } from "@/lib/validation/parse-uuid"; | ||
| import { AUDIT_ACTIONS, createAuditLog, getClientInfo } from "@/lib/audit-log"; | ||
|
|
||
| /** | ||
| * DELETE a PLATFORM outbound webhook (`webhooks` row with `tenantId: null`). | ||
| * | ||
| * The tenantId predicate is the authorization boundary, not a filter: without | ||
| * it this route would delete any tenant's endpoint by id. | ||
| */ | ||
| export const DELETE = withSuperAdminParams(async (req, { user }, params) => { | ||
| const originError = requireSameOrigin(req); | ||
| if (originError) return originError; | ||
|
|
||
| const id = parseUuid(params.id); | ||
|
|
||
| try { | ||
| const result = await prisma.webhooks.deleteMany({ | ||
| where: { id, tenantId: null }, | ||
| }); | ||
|
|
||
| if (result.count === 0) { | ||
| return apiError(new Error("Platform webhook not found"), { | ||
| route: "DELETE /api/super-admin/webhooks/outbound/[id]", | ||
| status: 404, | ||
| safeMessage: "Webhook not found", | ||
| }); | ||
| } | ||
|
|
||
| await createAuditLog({ | ||
| action: AUDIT_ACTIONS.WEBHOOK_DELETED, | ||
| entityType: "Webhook", | ||
| entityId: id, | ||
| userId: user.id, | ||
| userEmail: user.email || undefined, | ||
| metadata: { scope: "platform" }, | ||
| ...getClientInfo(req.headers), | ||
| }); | ||
|
|
||
| return NextResponse.json({ success: true }); | ||
| } catch (error) { | ||
| return apiError(error, { | ||
| route: "DELETE /api/super-admin/webhooks/outbound/[id]", | ||
| safeMessage: "Failed to delete webhook", | ||
| }); | ||
| } | ||
| }); |
104 changes: 104 additions & 0 deletions
104
nextjs_space/app/api/super-admin/webhooks/outbound/route.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,104 @@ | ||
| import { NextResponse } from "next/server"; | ||
| import { z } from "zod"; | ||
| import crypto from "crypto"; | ||
| import { withSuperAdmin } from "@/lib/api-auth"; | ||
| import { prisma } from "@/lib/db"; | ||
| import { apiError, apiValidationError } from "@/lib/api-error"; | ||
| import { requireSameOrigin } from "@/lib/security/require-same-origin"; | ||
| import { parseJsonBody } from "@/lib/validation/body"; | ||
| import { assertSafeWebhookUrl } from "@/lib/integrations/webhook-ssrf"; | ||
| import { AUDIT_ACTIONS, createAuditLog, getClientInfo } from "@/lib/audit-log"; | ||
|
|
||
| /** | ||
| * PLATFORM-scope outbound webhooks — rows in `webhooks` with `tenantId: null`. | ||
| * | ||
| * The tenant-admin page manages a tenant's own destinations; this manages the | ||
| * platform's. Same table, same delivery machinery (`triggerWebhook` selects on | ||
| * `tenantId: tenantId || null`), which is why no migration is needed — the | ||
| * column has always been nullable. | ||
| * | ||
| * Scope note for operators: a platform webhook fires on PLATFORM-level events | ||
| * only, not on every tenant's activity. | ||
| */ | ||
|
|
||
| const ROUTE = "/api/super-admin/webhooks/outbound"; | ||
|
|
||
| const createSchema = z | ||
| .object({ | ||
| url: z.string().url().max(2000), | ||
| events: z.array(z.string().min(1).max(100)).min(1).max(50), | ||
| description: z.string().max(1000).optional(), | ||
| }) | ||
| .strict(); | ||
|
|
||
| export const GET = withSuperAdmin(async () => { | ||
| try { | ||
| const webhooks = await prisma.webhooks.findMany({ | ||
| where: { tenantId: null }, | ||
| include: { _count: { select: { webhook_deliveries: true } } }, | ||
| orderBy: { createdAt: "desc" }, | ||
| }); | ||
|
|
||
| return NextResponse.json({ | ||
| webhooks: webhooks.map(({ _count, secret, ...webhook }: any) => ({ | ||
| ...webhook, | ||
| // Signing secret is shown once at creation; never re-served on list. | ||
| secretPreview: `${String(secret).slice(0, 6)}…`, | ||
| _count: { deliveries: _count.webhook_deliveries }, | ||
| })), | ||
| }); | ||
| } catch (error) { | ||
| return apiError(error, { route: `GET ${ROUTE}`, safeMessage: "Failed to fetch webhooks" }); | ||
| } | ||
| }); | ||
|
|
||
| export const POST = withSuperAdmin(async (req, { user }) => { | ||
| const originError = requireSameOrigin(req); | ||
| if (originError) return originError; | ||
|
|
||
| try { | ||
| const { url, events, description } = await parseJsonBody(req, createSchema); | ||
|
|
||
| // SSRF egress guard — same rule as the tenant route: public HTTPS only, | ||
| // never an internal/private-resolving address. | ||
| try { | ||
| await assertSafeWebhookUrl(url); | ||
| } catch { | ||
| return apiValidationError( | ||
| "Webhook URL is not allowed. Use a public HTTPS endpoint.", | ||
| ROUTE, | ||
| ); | ||
| } | ||
|
|
||
| const secret = crypto.randomBytes(32).toString("hex"); | ||
| const webhook = await prisma.webhooks.create({ | ||
| data: { | ||
| // `webhooks.id` carries no DB default — set it explicitly. | ||
| id: crypto.randomUUID(), | ||
| tenantId: null, | ||
| url, | ||
| events, | ||
| secret, | ||
| description: description || "", | ||
| isActive: true, | ||
| updatedAt: new Date(), | ||
| }, | ||
| }); | ||
|
|
||
| await createAuditLog({ | ||
| action: AUDIT_ACTIONS.WEBHOOK_CREATED, | ||
| entityType: "Webhook", | ||
| entityId: webhook.id, | ||
| userId: user.id, | ||
| userEmail: user.email || undefined, | ||
| metadata: { url, events, scope: "platform" }, | ||
| ...getClientInfo(req.headers), | ||
| }); | ||
|
|
||
| // Only response that ever carries the secret — the operator copies it into | ||
| // the receiving system now or rotates by recreating the endpoint. | ||
| return NextResponse.json({ webhook: { ...webhook, secret } }, { status: 201 }); | ||
| } catch (error) { | ||
| return apiError(error, { route: `POST ${ROUTE}`, safeMessage: "Failed to create webhook" }); | ||
| } | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🔒 Security & Privacy | 🟡 Minor | ⚡ Quick win
Do not return or display a signing-secret preview after creation.
The API exposes the first six characters of each signing secret on every list request. The console then renders that value. This conflicts with the stated one-time secret display contract.
nextjs_space/app/api/super-admin/webhooks/outbound/route.ts#L43-L46: omitsecretPreviewand do not derive any value fromsecretin GET responses.nextjs_space/app/super-admin/webhooks/page.tsx#L434-L436: remove the signing-secret preview from the endpoint list and its client type.📍 Affects 2 files
nextjs_space/app/api/super-admin/webhooks/outbound/route.ts#L43-L46(this comment)nextjs_space/app/super-admin/webhooks/page.tsx#L434-L436🤖 Prompt for AI Agents