Repository navigation
feat(automations): Circleback trigger provider #6597
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
Show all changes
3 commits
Select commit
Hold shift + click to select a range
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
187 changes: 187 additions & 0 deletions
187
apps/api/src/app/api/integrations/circleback/webhook/[triggerId]/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,187 @@ | ||
| import { createHmac, timingSafeEqual } from "node:crypto"; | ||
| import { dbWs } from "@superset/db/client"; | ||
| import { automationEvents, automationTriggers } from "@superset/db/schema"; | ||
| import { and, eq } from "drizzle-orm"; | ||
| import { z } from "zod"; | ||
|
|
||
| import { dispatchMatchingTriggers } from "@/lib/automations/dispatchMatchingTriggers"; | ||
| import { stripNullChars } from "@/lib/strip-null-chars"; | ||
|
|
||
| export const dynamic = "force-dynamic"; | ||
|
|
||
| const EVENT_TYPE = "meeting.completed"; | ||
|
|
||
| /** | ||
| * The fields matching and the row need. Everything else — notes, action items, | ||
| * transcript, insights — rides along in `payload` for the prompt. | ||
| */ | ||
| const meetingSchema = z | ||
| .object({ | ||
| id: z.union([z.string().min(1), z.number()]).transform(String), | ||
| name: z.string().default(""), | ||
| tags: z.array(z.string()).default([]), | ||
| attendees: z | ||
| .array(z.object({ email: z.string().nullable().optional() })) | ||
| .default([]), | ||
| }) | ||
| .passthrough(); | ||
|
|
||
| /** | ||
| * Circleback signs the raw body with the secret it issued for the automation | ||
| * and puts the hex digest in `x-signature`. Compared in constant time on the | ||
| * bytes Circleback sent, before anything is parsed. | ||
| */ | ||
| function signatureValid( | ||
| body: string, | ||
| signature: string | null, | ||
| secret: string, | ||
| ): boolean { | ||
| if (!signature) return false; | ||
| const expected = createHmac("sha256", secret).update(body).digest("hex"); | ||
| const a = Buffer.from(expected, "utf8"); | ||
| const b = Buffer.from(signature.trim().toLowerCase(), "utf8"); | ||
| return a.length === b.length && timingSafeEqual(a, b); | ||
| } | ||
|
|
||
| /** | ||
| * One meeting, delivered by Circleback to the trigger named in the URL. | ||
| * | ||
| * Unlike GitHub, where one delivery is matched against every trigger in the | ||
| * organization, a Circleback delivery is addressed: the user configured this | ||
| * URL in Circleback, so only this trigger is evaluated. Two triggers wired to | ||
| * the same Circleback workspace each get their own delivery of the same | ||
| * meeting, which is why the dedupe key carries the trigger id. | ||
| */ | ||
| export async function POST( | ||
| request: Request, | ||
| { params }: { params: Promise<{ triggerId: string }> }, | ||
| ): Promise<Response> { | ||
| const { triggerId } = await params; | ||
| if (!z.string().uuid().safeParse(triggerId).success) { | ||
| return Response.json({ error: "Unknown trigger" }, { status: 404 }); | ||
| } | ||
|
|
||
| const [trigger] = await dbWs | ||
| .select({ | ||
| organizationId: automationTriggers.organizationId, | ||
| automationId: automationTriggers.automationId, | ||
| // For an HMAC provider the column holds the signing key itself — a | ||
| // hash could not verify a signature. | ||
| secret: automationTriggers.secretHash, | ||
| }) | ||
| .from(automationTriggers) | ||
| .where( | ||
| and( | ||
| eq(automationTriggers.id, triggerId), | ||
| eq(automationTriggers.kind, "circleback"), | ||
| ), | ||
| ) | ||
| .limit(1); | ||
|
|
||
| if (!trigger) { | ||
| return Response.json({ error: "Unknown trigger" }, { status: 404 }); | ||
| } | ||
|
|
||
| const body = await request.text(); | ||
|
|
||
| // A trigger with no secret yet cannot tell Circleback from anyone who has | ||
| // seen the URL, so it accepts nothing until one is pasted in. | ||
| const secret = trigger.secret; | ||
| if (!secret) { | ||
| console.warn( | ||
| "[circleback/webhook] No signing secret configured for trigger:", | ||
| triggerId, | ||
| ); | ||
| return Response.json( | ||
| { error: "Signing secret not configured" }, | ||
| { status: 401 }, | ||
| ); | ||
| } | ||
| if (!signatureValid(body, request.headers.get("x-signature"), secret)) { | ||
| console.warn( | ||
| "[circleback/webhook] Invalid signature for trigger:", | ||
| triggerId, | ||
| ); | ||
| return Response.json({ error: "Invalid signature" }, { status: 401 }); | ||
| } | ||
|
|
||
| let json: unknown; | ||
| try { | ||
| json = JSON.parse(body); | ||
| } catch { | ||
| return Response.json({ error: "Invalid JSON payload" }, { status: 400 }); | ||
| } | ||
| const parsed = meetingSchema.safeParse(json); | ||
| if (!parsed.success) { | ||
| console.error( | ||
| "[circleback/webhook] Unexpected payload shape", | ||
| parsed.error, | ||
| ); | ||
| return Response.json({ error: "Invalid payload" }, { status: 400 }); | ||
| } | ||
| const meeting = parsed.data; | ||
|
|
||
| const [inserted] = await dbWs | ||
| .insert(automationEvents) | ||
| .values({ | ||
| organizationId: trigger.organizationId, | ||
| integrationConnectionId: null, | ||
| provider: "circleback", | ||
| eventType: EVENT_TYPE, | ||
| // Per trigger: the same meeting legitimately reaches every trigger | ||
| // whose URL is configured in Circleback, and a redelivery to one of | ||
| // them is still a duplicate for that one. | ||
| externalEventId: `${triggerId}:${meeting.id}`, | ||
| resourceKey: `circleback:${meeting.id}`, | ||
| title: meeting.name || meeting.id, | ||
| url: `https://circleback.ai/meetings/${meeting.id}`, | ||
| payload: stripNullChars(json) as Record<string, unknown>, | ||
| }) | ||
| .onConflictDoNothing({ | ||
| target: [ | ||
| automationEvents.integrationConnectionId, | ||
| automationEvents.provider, | ||
| automationEvents.externalEventId, | ||
| ], | ||
| }) | ||
| .returning({ id: automationEvents.id }); | ||
|
|
||
| if (!inserted) { | ||
| return Response.json({ ok: true, duplicate: true }); | ||
| } | ||
|
|
||
| // The event is recorded either way; a failure past this point must not | ||
| // fail the delivery, since a redelivery would dedupe against the row and | ||
| // never get the run enqueued either. Same stance as the GitHub route. | ||
| try { | ||
| const result = await dispatchMatchingTriggers({ | ||
| organizationId: trigger.organizationId, | ||
| eventId: inserted.id, | ||
| // Addressed: Circleback was configured with this trigger's URL, so | ||
| // only this trigger is a candidate — every other Circleback trigger | ||
| // in the organization has its own URL and gets its own delivery. | ||
| automationId: trigger.automationId, | ||
| triggerId, | ||
| event: { | ||
| provider: "circleback", | ||
| eventType: EVENT_TYPE, | ||
| actorId: null, | ||
| actorLogin: null, | ||
| body: null, | ||
| name: meeting.name || null, | ||
| tags: meeting.tags, | ||
| attendeeEmails: meeting.attendees.flatMap((a) => | ||
| a.email ? [a.email] : [], | ||
| ), | ||
| }, | ||
| }); | ||
| console.log( | ||
| `[circleback/webhook] ${result.matched}/${result.considered} triggers matched:`, | ||
| inserted.id, | ||
| ); | ||
| return Response.json({ ok: true, matched: result.matched > 0 }); | ||
| } catch (error) { | ||
| console.error("[circleback/webhook] dispatch failed:", error); | ||
| return Response.json({ ok: true, dispatched: false }); | ||
| } | ||
| } | ||
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
101 changes: 101 additions & 0 deletions
101
...utes/_authenticated/_dashboard/automations/components/providers/circleback/circleback.tsx
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,101 @@ | ||
| import { LuMic } from "react-icons/lu"; | ||
| import { env } from "renderer/env.renderer"; | ||
| import { EndpointChip } from "../../TriggerSentence/components/EndpointChip"; | ||
| import { ScopeChip } from "../../TriggerSentence/components/ScopeChip"; | ||
| import { TextFilterChip } from "../../TriggerSentence/components/TextFilterChip"; | ||
| import type { SentenceContext, TriggerProvider } from "../types"; | ||
| import { SigningSecretChip } from "./components/SigningSecretChip"; | ||
| import { | ||
| CIRCLEBACK_MENU, | ||
| CIRCLEBACK_SENTENCE, | ||
| type CirclebackConfig, | ||
| type SentencePart, | ||
| } from "./grammar"; | ||
|
|
||
| export function circlebackWebhookUrl(triggerId: string): string { | ||
| return `${env.NEXT_PUBLIC_API_URL}/api/integrations/circleback/webhook/${triggerId}`; | ||
| } | ||
|
|
||
| function renderPart( | ||
| config: CirclebackConfig, | ||
| part: SentencePart, | ||
| index: number, | ||
| { set, disabled, triggerId }: SentenceContext, | ||
| ) { | ||
| if ("text" in part) { | ||
| return ( | ||
| <span key={index} className="text-[13px] text-muted-foreground"> | ||
| {part.text} | ||
| </span> | ||
| ); | ||
| } | ||
| switch (part.slot) { | ||
| case "tags": | ||
| return ( | ||
| <ScopeChip | ||
| key={index} | ||
| scope={config.tags} | ||
| // Clearing an optional filter means "any", not "none": the chip | ||
| // says "Any tag" either way, and null would make that a lie. | ||
| onChange={(v) => set({ tags: v ?? { mode: "any" } })} | ||
| options={[]} | ||
| emptyLabel="Any tag" | ||
| anyLabel="Any tag" | ||
| allowCustom={{ placeholder: "Type a tag, press Enter" }} | ||
| disabled={disabled} | ||
| /> | ||
| ); | ||
| case "attendees": | ||
| return ( | ||
| <ScopeChip | ||
| key={index} | ||
| scope={config.attendees} | ||
| onChange={(v) => set({ attendees: v ?? { mode: "any" } })} | ||
| options={[]} | ||
| emptyLabel="Any attendee" | ||
| anyLabel="Any attendee" | ||
| allowCustom={{ placeholder: "Type an email, press Enter" }} | ||
| disabled={disabled} | ||
| /> | ||
| ); | ||
| case "nameFilter": | ||
| return ( | ||
| <TextFilterChip | ||
| key={index} | ||
| value={config.nameFilter} | ||
| onChange={(v) => set({ nameFilter: v })} | ||
| emptyLabel="Any name" | ||
| placeholder="Contains this text..." | ||
| disabled={disabled} | ||
| /> | ||
| ); | ||
| case "endpoint": | ||
| // The URL carries the saved row's id, so a row that has not been | ||
| // saved yet has nothing to paste into Circleback. | ||
| return ( | ||
| <EndpointChip | ||
| key={index} | ||
| url={triggerId ? circlebackWebhookUrl(triggerId) : null} | ||
| /> | ||
| ); | ||
| case "signingSecret": | ||
| return ( | ||
| <SigningSecretChip | ||
| key={index} | ||
| triggerId={triggerId} | ||
| disabled={disabled} | ||
| /> | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| export const circlebackProvider: TriggerProvider<CirclebackConfig> = { | ||
| kind: "circleback", | ||
| label: "Circleback", | ||
| icon: LuMic, | ||
| menu: CIRCLEBACK_MENU, | ||
| renderSentence: (config, ctx) => | ||
| CIRCLEBACK_SENTENCE.map((part, index) => | ||
| renderPart(config, part, index, ctx), | ||
| ), | ||
| }; |
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 log the full Zod error for a rejected payload.
Zod 4 issues can include the received input. This payload carries attendee emails and meeting names, so the log can retain personal data. Log the issue paths and codes instead.
🛡️ Proposed fix
const parsed = meetingSchema.safeParse(json); if (!parsed.success) { console.error( "[circleback/webhook] Unexpected payload shape", - parsed.error, + parsed.error.issues.map((issue) => ({ + path: issue.path.join("."), + code: issue.code, + })), );📝 Committable suggestion
🤖 Prompt for AI Agents