Add webhooks

Signed-off-by: Sacha Al Himdani <sacha@getprobo.com>
This commit is contained in:
Sacha Al Himdani
2026-02-11 09:34:06 +01:00
parent 4945c022a1
commit f9de9c4834
34 changed files with 5932 additions and 4 deletions

View File

@@ -0,0 +1,265 @@
/**
* @generated SignedSource<<ddaaa2d60cc045e841daaa3be6428cf2>>
* @lightSyntaxTransform
* @nogrep
*/
/* tslint:disable */
/* eslint-disable */
// @ts-nocheck
import { ConcreteRequest } from 'relay-runtime';
export type WebhookEventType = "MEETING_CREATED" | "MEETING_DELETED" | "MEETING_UPDATED" | "VENDOR_CREATED" | "VENDOR_DELETED" | "VENDOR_UPDATED";
export type WebhooksSettingsPageQuery$variables = {
organizationId: string;
};
export type WebhooksSettingsPageQuery$data = {
readonly organization: {
readonly __typename: "Organization";
readonly id: string;
readonly webhookConfigurations: {
readonly edges: ReadonlyArray<{
readonly node: {
readonly endpointUrl: string;
readonly id: string;
readonly selectedEvents: ReadonlyArray<WebhookEventType>;
};
}>;
};
} | {
// This will never be '%other', but we need some
// value in case none of the concrete values match.
readonly __typename: "%other";
};
};
export type WebhooksSettingsPageQuery = {
response: WebhooksSettingsPageQuery$data;
variables: WebhooksSettingsPageQuery$variables;
};
const node: ConcreteRequest = (function(){
var v0 = [
{
"defaultValue": null,
"kind": "LocalArgument",
"name": "organizationId"
}
],
v1 = [
{
"kind": "Variable",
"name": "id",
"variableName": "organizationId"
}
],
v2 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "__typename",
"storageKey": null
},
v3 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "id",
"storageKey": null
},
v4 = [
{
"alias": null,
"args": null,
"concreteType": "WebhookConfigurationEdge",
"kind": "LinkedField",
"name": "edges",
"plural": true,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "WebhookConfiguration",
"kind": "LinkedField",
"name": "node",
"plural": false,
"selections": [
(v3/*: any*/),
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "endpointUrl",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "selectedEvents",
"storageKey": null
},
(v2/*: any*/)
],
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "cursor",
"storageKey": null
}
],
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "PageInfo",
"kind": "LinkedField",
"name": "pageInfo",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "endCursor",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "hasNextPage",
"storageKey": null
}
],
"storageKey": null
}
],
v5 = [
{
"kind": "Literal",
"name": "first",
"value": 50
}
];
return {
"fragment": {
"argumentDefinitions": (v0/*: any*/),
"kind": "Fragment",
"metadata": null,
"name": "WebhooksSettingsPageQuery",
"selections": [
{
"kind": "RequiredField",
"field": {
"alias": "organization",
"args": (v1/*: any*/),
"concreteType": null,
"kind": "LinkedField",
"name": "node",
"plural": false,
"selections": [
(v2/*: any*/),
{
"kind": "InlineFragment",
"selections": [
(v3/*: any*/),
{
"alias": "webhookConfigurations",
"args": null,
"concreteType": "WebhookConfigurationConnection",
"kind": "LinkedField",
"name": "__WebhooksSettingsPage_webhookConfigurations_connection",
"plural": false,
"selections": (v4/*: any*/),
"storageKey": null
}
],
"type": "Organization",
"abstractKey": null
}
],
"storageKey": null
},
"action": "THROW"
}
],
"type": "Query",
"abstractKey": null
},
"kind": "Request",
"operation": {
"argumentDefinitions": (v0/*: any*/),
"kind": "Operation",
"name": "WebhooksSettingsPageQuery",
"selections": [
{
"alias": "organization",
"args": (v1/*: any*/),
"concreteType": null,
"kind": "LinkedField",
"name": "node",
"plural": false,
"selections": [
(v2/*: any*/),
(v3/*: any*/),
{
"kind": "InlineFragment",
"selections": [
{
"alias": null,
"args": (v5/*: any*/),
"concreteType": "WebhookConfigurationConnection",
"kind": "LinkedField",
"name": "webhookConfigurations",
"plural": false,
"selections": (v4/*: any*/),
"storageKey": "webhookConfigurations(first:50)"
},
{
"alias": null,
"args": (v5/*: any*/),
"filters": null,
"handle": "connection",
"key": "WebhooksSettingsPage_webhookConfigurations",
"kind": "LinkedHandle",
"name": "webhookConfigurations"
}
],
"type": "Organization",
"abstractKey": null
}
],
"storageKey": null
}
]
},
"params": {
"cacheID": "e6aa5c6b8142b654e2a3b7bebec59f83",
"id": null,
"metadata": {
"connection": [
{
"count": null,
"cursor": null,
"direction": "forward",
"path": [
"organization",
"webhookConfigurations"
]
}
]
},
"name": "WebhooksSettingsPageQuery",
"operationKind": "query",
"text": "query WebhooksSettingsPageQuery(\n $organizationId: ID!\n) {\n organization: node(id: $organizationId) {\n __typename\n ... on Organization {\n id\n webhookConfigurations(first: 50) {\n edges {\n node {\n id\n endpointUrl\n selectedEvents\n __typename\n }\n cursor\n }\n pageInfo {\n endCursor\n hasNextPage\n }\n }\n }\n id\n }\n}\n"
}
};
})();
(node as any).hash = "2a68dcb3a875a982b7d8300aa72c012b";
export default node;

View File

@@ -0,0 +1,177 @@
/**
* @generated SignedSource<<56bfc2d1746edae72b0da44526fab12f>>
* @lightSyntaxTransform
* @nogrep
*/
/* tslint:disable */
/* eslint-disable */
// @ts-nocheck
import { ConcreteRequest } from 'relay-runtime';
export type WebhookEventType = "MEETING_CREATED" | "MEETING_DELETED" | "MEETING_UPDATED" | "VENDOR_CREATED" | "VENDOR_DELETED" | "VENDOR_UPDATED";
export type CreateWebhookConfigurationInput = {
endpointUrl: string;
organizationId: string;
selectedEvents: ReadonlyArray<WebhookEventType>;
};
export type WebhooksSettingsPage_createMutation$variables = {
connections: ReadonlyArray<string>;
input: CreateWebhookConfigurationInput;
};
export type WebhooksSettingsPage_createMutation$data = {
readonly createWebhookConfiguration: {
readonly webhookConfigurationEdge: {
readonly node: {
readonly endpointUrl: string;
readonly id: string;
readonly selectedEvents: ReadonlyArray<WebhookEventType>;
};
};
};
};
export type WebhooksSettingsPage_createMutation = {
response: WebhooksSettingsPage_createMutation$data;
variables: WebhooksSettingsPage_createMutation$variables;
};
const node: ConcreteRequest = (function(){
var v0 = {
"defaultValue": null,
"kind": "LocalArgument",
"name": "connections"
},
v1 = {
"defaultValue": null,
"kind": "LocalArgument",
"name": "input"
},
v2 = [
{
"kind": "Variable",
"name": "input",
"variableName": "input"
}
],
v3 = {
"alias": null,
"args": null,
"concreteType": "WebhookConfigurationEdge",
"kind": "LinkedField",
"name": "webhookConfigurationEdge",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "WebhookConfiguration",
"kind": "LinkedField",
"name": "node",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "id",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "endpointUrl",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "selectedEvents",
"storageKey": null
}
],
"storageKey": null
}
],
"storageKey": null
};
return {
"fragment": {
"argumentDefinitions": [
(v0/*: any*/),
(v1/*: any*/)
],
"kind": "Fragment",
"metadata": null,
"name": "WebhooksSettingsPage_createMutation",
"selections": [
{
"alias": null,
"args": (v2/*: any*/),
"concreteType": "CreateWebhookConfigurationPayload",
"kind": "LinkedField",
"name": "createWebhookConfiguration",
"plural": false,
"selections": [
(v3/*: any*/)
],
"storageKey": null
}
],
"type": "Mutation",
"abstractKey": null
},
"kind": "Request",
"operation": {
"argumentDefinitions": [
(v1/*: any*/),
(v0/*: any*/)
],
"kind": "Operation",
"name": "WebhooksSettingsPage_createMutation",
"selections": [
{
"alias": null,
"args": (v2/*: any*/),
"concreteType": "CreateWebhookConfigurationPayload",
"kind": "LinkedField",
"name": "createWebhookConfiguration",
"plural": false,
"selections": [
(v3/*: any*/),
{
"alias": null,
"args": null,
"filters": null,
"handle": "prependEdge",
"key": "",
"kind": "LinkedHandle",
"name": "webhookConfigurationEdge",
"handleArgs": [
{
"kind": "Variable",
"name": "connections",
"variableName": "connections"
}
]
}
],
"storageKey": null
}
]
},
"params": {
"cacheID": "0e88932f635b8f16e41f730abf9e05ff",
"id": null,
"metadata": {},
"name": "WebhooksSettingsPage_createMutation",
"operationKind": "mutation",
"text": "mutation WebhooksSettingsPage_createMutation(\n $input: CreateWebhookConfigurationInput!\n) {\n createWebhookConfiguration(input: $input) {\n webhookConfigurationEdge {\n node {\n id\n endpointUrl\n selectedEvents\n }\n }\n }\n}\n"
}
};
})();
(node as any).hash = "4e1a7692c83c4dda0c2fc557f15d669d";
export default node;

View File

@@ -0,0 +1,132 @@
/**
* @generated SignedSource<<86d94ecf595a0048971276541e185905>>
* @lightSyntaxTransform
* @nogrep
*/
/* tslint:disable */
/* eslint-disable */
// @ts-nocheck
import { ConcreteRequest } from 'relay-runtime';
export type DeleteWebhookConfigurationInput = {
webhookConfigurationId: string;
};
export type WebhooksSettingsPage_deleteMutation$variables = {
connections: ReadonlyArray<string>;
input: DeleteWebhookConfigurationInput;
};
export type WebhooksSettingsPage_deleteMutation$data = {
readonly deleteWebhookConfiguration: {
readonly deletedWebhookConfigurationId: string;
};
};
export type WebhooksSettingsPage_deleteMutation = {
response: WebhooksSettingsPage_deleteMutation$data;
variables: WebhooksSettingsPage_deleteMutation$variables;
};
const node: ConcreteRequest = (function(){
var v0 = {
"defaultValue": null,
"kind": "LocalArgument",
"name": "connections"
},
v1 = {
"defaultValue": null,
"kind": "LocalArgument",
"name": "input"
},
v2 = [
{
"kind": "Variable",
"name": "input",
"variableName": "input"
}
],
v3 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "deletedWebhookConfigurationId",
"storageKey": null
};
return {
"fragment": {
"argumentDefinitions": [
(v0/*: any*/),
(v1/*: any*/)
],
"kind": "Fragment",
"metadata": null,
"name": "WebhooksSettingsPage_deleteMutation",
"selections": [
{
"alias": null,
"args": (v2/*: any*/),
"concreteType": "DeleteWebhookConfigurationPayload",
"kind": "LinkedField",
"name": "deleteWebhookConfiguration",
"plural": false,
"selections": [
(v3/*: any*/)
],
"storageKey": null
}
],
"type": "Mutation",
"abstractKey": null
},
"kind": "Request",
"operation": {
"argumentDefinitions": [
(v1/*: any*/),
(v0/*: any*/)
],
"kind": "Operation",
"name": "WebhooksSettingsPage_deleteMutation",
"selections": [
{
"alias": null,
"args": (v2/*: any*/),
"concreteType": "DeleteWebhookConfigurationPayload",
"kind": "LinkedField",
"name": "deleteWebhookConfiguration",
"plural": false,
"selections": [
(v3/*: any*/),
{
"alias": null,
"args": null,
"filters": null,
"handle": "deleteEdge",
"key": "",
"kind": "ScalarHandle",
"name": "deletedWebhookConfigurationId",
"handleArgs": [
{
"kind": "Variable",
"name": "connections",
"variableName": "connections"
}
]
}
],
"storageKey": null
}
]
},
"params": {
"cacheID": "ae53fa4e16e4491720c1fdfc52301c09",
"id": null,
"metadata": {},
"name": "WebhooksSettingsPage_deleteMutation",
"operationKind": "mutation",
"text": "mutation WebhooksSettingsPage_deleteMutation(\n $input: DeleteWebhookConfigurationInput!\n) {\n deleteWebhookConfiguration(input: $input) {\n deletedWebhookConfigurationId\n }\n}\n"
}
};
})();
(node as any).hash = "632fce2d89360bed2d857dd3feb90b9d";
export default node;

View File

@@ -0,0 +1,124 @@
/**
* @generated SignedSource<<af555c91779a2fbceaae3666d5bae667>>
* @lightSyntaxTransform
* @nogrep
*/
/* tslint:disable */
/* eslint-disable */
// @ts-nocheck
import { ConcreteRequest } from 'relay-runtime';
export type WebhooksSettingsPage_signingSecretQuery$variables = {
webhookConfigurationId: string;
};
export type WebhooksSettingsPage_signingSecretQuery$data = {
readonly node: {
readonly signingSecret?: string;
};
};
export type WebhooksSettingsPage_signingSecretQuery = {
response: WebhooksSettingsPage_signingSecretQuery$data;
variables: WebhooksSettingsPage_signingSecretQuery$variables;
};
const node: ConcreteRequest = (function(){
var v0 = [
{
"defaultValue": null,
"kind": "LocalArgument",
"name": "webhookConfigurationId"
}
],
v1 = [
{
"kind": "Variable",
"name": "id",
"variableName": "webhookConfigurationId"
}
],
v2 = {
"kind": "InlineFragment",
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "signingSecret",
"storageKey": null
}
],
"type": "WebhookConfiguration",
"abstractKey": null
};
return {
"fragment": {
"argumentDefinitions": (v0/*: any*/),
"kind": "Fragment",
"metadata": null,
"name": "WebhooksSettingsPage_signingSecretQuery",
"selections": [
{
"alias": null,
"args": (v1/*: any*/),
"concreteType": null,
"kind": "LinkedField",
"name": "node",
"plural": false,
"selections": [
(v2/*: any*/)
],
"storageKey": null
}
],
"type": "Query",
"abstractKey": null
},
"kind": "Request",
"operation": {
"argumentDefinitions": (v0/*: any*/),
"kind": "Operation",
"name": "WebhooksSettingsPage_signingSecretQuery",
"selections": [
{
"alias": null,
"args": (v1/*: any*/),
"concreteType": null,
"kind": "LinkedField",
"name": "node",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "__typename",
"storageKey": null
},
(v2/*: any*/),
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "id",
"storageKey": null
}
],
"storageKey": null
}
]
},
"params": {
"cacheID": "266c1519da14eb09ed28e26cc6394f23",
"id": null,
"metadata": {},
"name": "WebhooksSettingsPage_signingSecretQuery",
"operationKind": "query",
"text": "query WebhooksSettingsPage_signingSecretQuery(\n $webhookConfigurationId: ID!\n) {\n node(id: $webhookConfigurationId) {\n __typename\n ... on WebhookConfiguration {\n signingSecret\n }\n id\n }\n}\n"
}
};
})();
(node as any).hash = "9d981d1a353a82f234e7ce79edb6d5d9";
export default node;

View File

@@ -0,0 +1,132 @@
/**
* @generated SignedSource<<3331839e2cc81d14ac1b2fcfe3fd84f1>>
* @lightSyntaxTransform
* @nogrep
*/
/* tslint:disable */
/* eslint-disable */
// @ts-nocheck
import { ConcreteRequest } from 'relay-runtime';
export type WebhookEventType = "MEETING_CREATED" | "MEETING_DELETED" | "MEETING_UPDATED" | "VENDOR_CREATED" | "VENDOR_DELETED" | "VENDOR_UPDATED";
export type UpdateWebhookConfigurationInput = {
endpointUrl?: string | null | undefined;
id: string;
selectedEvents?: ReadonlyArray<WebhookEventType> | null | undefined;
};
export type WebhooksSettingsPage_updateMutation$variables = {
input: UpdateWebhookConfigurationInput;
};
export type WebhooksSettingsPage_updateMutation$data = {
readonly updateWebhookConfiguration: {
readonly webhookConfiguration: {
readonly endpointUrl: string;
readonly id: string;
readonly selectedEvents: ReadonlyArray<WebhookEventType>;
readonly updatedAt: string;
};
};
};
export type WebhooksSettingsPage_updateMutation = {
response: WebhooksSettingsPage_updateMutation$data;
variables: WebhooksSettingsPage_updateMutation$variables;
};
const node: ConcreteRequest = (function(){
var v0 = [
{
"defaultValue": null,
"kind": "LocalArgument",
"name": "input"
}
],
v1 = [
{
"alias": null,
"args": [
{
"kind": "Variable",
"name": "input",
"variableName": "input"
}
],
"concreteType": "UpdateWebhookConfigurationPayload",
"kind": "LinkedField",
"name": "updateWebhookConfiguration",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "WebhookConfiguration",
"kind": "LinkedField",
"name": "webhookConfiguration",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "id",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "endpointUrl",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "selectedEvents",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "updatedAt",
"storageKey": null
}
],
"storageKey": null
}
],
"storageKey": null
}
];
return {
"fragment": {
"argumentDefinitions": (v0/*: any*/),
"kind": "Fragment",
"metadata": null,
"name": "WebhooksSettingsPage_updateMutation",
"selections": (v1/*: any*/),
"type": "Mutation",
"abstractKey": null
},
"kind": "Request",
"operation": {
"argumentDefinitions": (v0/*: any*/),
"kind": "Operation",
"name": "WebhooksSettingsPage_updateMutation",
"selections": (v1/*: any*/)
},
"params": {
"cacheID": "399a35c005f10dd321784a7533fb4f80",
"id": null,
"metadata": {},
"name": "WebhooksSettingsPage_updateMutation",
"operationKind": "mutation",
"text": "mutation WebhooksSettingsPage_updateMutation(\n $input: UpdateWebhookConfigurationInput!\n) {\n updateWebhookConfiguration(input: $input) {\n webhookConfiguration {\n id\n endpointUrl\n selectedEvents\n updatedAt\n }\n }\n}\n"
}
};
})();
(node as any).hash = "f974aae43d0ad8b5fe3cab60bd07a3ff";
export default node;

View File

@@ -2,6 +2,7 @@ import { useTranslate } from "@probo/i18n";
import {
IconKey,
IconLock,
IconSend,
IconSettingsGear2,
PageHeader,
TabLink,
@@ -32,6 +33,10 @@ export default function SettingsLayout() {
<IconKey size={20} />
{__("SCIM")}
</TabLink>
<TabLink to={`/organizations/${organizationId}/settings/webhooks`}>
<IconSend size={20} />
{__("Webhooks")}
</TabLink>
</Tabs>
<Outlet />

View File

@@ -0,0 +1,37 @@
import { useEffect } from "react";
import { useQueryLoader } from "react-relay";
import type { WebhooksSettingsPageQuery } from "#/__generated__/core/WebhooksSettingsPageQuery.graphql";
import { useOrganizationId } from "#/hooks/useOrganizationId";
import {
WebhooksSettingsPage,
webhooksSettingsPageQuery,
} from "#/pages/organizations/settings/WebhooksSettingsPage";
import { CoreRelayProvider } from "#/providers/CoreRelayProvider";
function WebhooksSettingsPageQueryLoader() {
const organizationId = useOrganizationId();
const [queryRef, loadQuery] = useQueryLoader<WebhooksSettingsPageQuery>(
webhooksSettingsPageQuery,
);
useEffect(() => {
loadQuery({
organizationId,
});
}, [loadQuery, organizationId]);
if (!queryRef) {
return null;
}
return <WebhooksSettingsPage queryRef={queryRef} />;
}
export default function WebhooksSettingsPageLoader() {
return (
<CoreRelayProvider>
<WebhooksSettingsPageQueryLoader />
</CoreRelayProvider>
);
}

View File

@@ -0,0 +1,567 @@
import { useTranslate } from "@probo/i18n";
import {
Button,
Card,
Checkbox,
Dialog,
DialogContent,
DialogFooter,
Field,
IconPencil,
IconPlusLarge,
IconSquareBehindSquare2,
IconTrashCan,
Input,
Label,
Spinner,
useDialogRef,
useToast,
} from "@probo/ui";
import { useCallback, useState } from "react";
import { type PreloadedQuery, usePreloadedQuery, useRelayEnvironment } from "react-relay";
import { ConnectionHandler, fetchQuery, graphql } from "relay-runtime";
import { z } from "zod";
import type { WebhooksSettingsPage_createMutation } from "#/__generated__/core/WebhooksSettingsPage_createMutation.graphql";
import type { WebhooksSettingsPage_deleteMutation } from "#/__generated__/core/WebhooksSettingsPage_deleteMutation.graphql";
import type { WebhooksSettingsPage_signingSecretQuery } from "#/__generated__/core/WebhooksSettingsPage_signingSecretQuery.graphql";
import type { WebhooksSettingsPage_updateMutation } from "#/__generated__/core/WebhooksSettingsPage_updateMutation.graphql";
import type { WebhooksSettingsPageQuery } from "#/__generated__/core/WebhooksSettingsPageQuery.graphql";
import { useFormWithSchema } from "#/hooks/useFormWithSchema";
import { useMutationWithToasts } from "#/hooks/useMutationWithToasts";
export const webhooksSettingsPageQuery = graphql`
query WebhooksSettingsPageQuery($organizationId: ID!) {
organization: node(id: $organizationId) @required(action: THROW) {
__typename
... on Organization {
id
webhookConfigurations(first: 50)
@connection(key: "WebhooksSettingsPage_webhookConfigurations") {
edges {
node {
id
endpointUrl
selectedEvents
}
}
}
}
}
}
`;
const createWebhookConfigurationMutation = graphql`
mutation WebhooksSettingsPage_createMutation(
$input: CreateWebhookConfigurationInput!
$connections: [ID!]!
) {
createWebhookConfiguration(input: $input) {
webhookConfigurationEdge @prependEdge(connections: $connections) {
node {
id
endpointUrl
selectedEvents
}
}
}
}
`;
const updateWebhookConfigurationMutation = graphql`
mutation WebhooksSettingsPage_updateMutation(
$input: UpdateWebhookConfigurationInput!
) {
updateWebhookConfiguration(input: $input) {
webhookConfiguration {
id
endpointUrl
selectedEvents
updatedAt
}
}
}
`;
const signingSecretQuery = graphql`
query WebhooksSettingsPage_signingSecretQuery($webhookConfigurationId: ID!) {
node(id: $webhookConfigurationId) {
... on WebhookConfiguration {
signingSecret
}
}
}
`;
const deleteWebhookConfigurationMutation = graphql`
mutation WebhooksSettingsPage_deleteMutation(
$input: DeleteWebhookConfigurationInput!
$connections: [ID!]!
) {
deleteWebhookConfiguration(input: $input) {
deletedWebhookConfigurationId @deleteEdge(connections: $connections)
}
}
`;
const EVENT_TYPES = [
{ value: "MEETING_CREATED", label: "meeting:created" },
{ value: "MEETING_UPDATED", label: "meeting:updated" },
{ value: "MEETING_DELETED", label: "meeting:deleted" },
{ value: "VENDOR_CREATED", label: "vendor:created" },
{ value: "VENDOR_UPDATED", label: "vendor:updated" },
{ value: "VENDOR_DELETED", label: "vendor:deleted" },
] as const;
type WebhookEventType = (typeof EVENT_TYPES)[number]["value"];
const WEBHOOK_EVENT_VALUES = EVENT_TYPES.map(e => e.value) as [
WebhookEventType,
...WebhookEventType[],
];
const webhookFormSchema = z.object({
endpointUrl: z
.string()
.min(1, "Endpoint URL is required")
.url("Please enter a valid URL")
.refine(
(val) => {
try {
const url = new URL(val);
return url.protocol === "http:" || url.protocol === "https:";
} catch {
return false;
}
},
"URL must use http:// or https://",
),
selectedEvents: z
.array(z.enum(WEBHOOK_EVENT_VALUES))
.min(1, "At least one event must be selected"),
});
type WebhookFormData = z.infer<typeof webhookFormSchema>;
function WebhookFormDialog({
mode,
initialValues,
onSubmit,
isSubmitting,
trigger,
}: {
mode: "create" | "edit";
initialValues?: WebhookFormData;
onSubmit: (values: WebhookFormData) => void;
isSubmitting: boolean;
trigger: React.ReactNode;
}) {
const { __ } = useTranslate();
const dialogRef = useDialogRef();
const { register, handleSubmit, formState, setValue, watch, reset }
= useFormWithSchema(webhookFormSchema, {
defaultValues: {
endpointUrl: initialValues?.endpointUrl ?? "",
selectedEvents: initialValues?.selectedEvents ?? [],
},
});
const selectedEvents = watch("selectedEvents");
const handleToggleEvent = (event: WebhookEventType) => {
const current = selectedEvents ?? [];
const next = current.includes(event)
? current.filter(e => e !== event)
: [...current, event];
setValue("selectedEvents", next, { shouldValidate: formState.isSubmitted });
};
const onFormSubmit = (data: WebhookFormData) => {
onSubmit(data);
dialogRef.current?.close();
reset(data);
};
return (
<Dialog
ref={dialogRef}
trigger={trigger}
title={
mode === "create"
? __("Add Webhook Configuration")
: __("Edit Webhook Configuration")
}
className="max-w-lg"
>
<form onSubmit={e => void handleSubmit(onFormSubmit)(e)}>
<DialogContent padded>
<div className="space-y-4">
<Field
label={__("Endpoint URL")}
error={formState.errors.endpointUrl?.message}
required
>
<Input
{...register("endpointUrl")}
type="url"
placeholder={__("https://example.com/webhook")}
/>
</Field>
<div>
<Label>{__("Events")}</Label>
<p className="text-sm text-txt-tertiary mb-2">
{__("Select the events that will trigger this webhook.")}
</p>
<div className="space-y-2">
{EVENT_TYPES.map(event => (
<label
key={event.value}
className="flex items-center gap-2 cursor-pointer"
>
<Checkbox
checked={selectedEvents?.includes(event.value) ?? false}
onChange={() => handleToggleEvent(event.value)}
/>
<span className="text-sm font-mono">{event.label}</span>
</label>
))}
</div>
{formState.errors.selectedEvents?.message && (
<p className="text-xs text-red-600 mt-1">
{formState.errors.selectedEvents.message}
</p>
)}
</div>
</div>
</DialogContent>
<DialogFooter>
<Button
type="submit"
disabled={isSubmitting}
>
{isSubmitting
? <Spinner size={16} />
: mode === "create"
? __("Create")
: __("Save")}
</Button>
</DialogFooter>
</form>
</Dialog>
);
}
export function WebhooksSettingsPage(props: {
queryRef: PreloadedQuery<WebhooksSettingsPageQuery>;
}) {
const { queryRef } = props;
const { __ } = useTranslate();
const { toast } = useToast();
const environment = useRelayEnvironment();
const deleteDialogRef = useDialogRef();
const [deletingId, setDeletingId] = useState<string | null>(null);
const [revealedSecrets, setRevealedSecrets] = useState<Record<string, string>>({});
const [loadingSecrets, setLoadingSecrets] = useState<Set<string>>(new Set());
const fetchSigningSecret = useCallback(
async (webhookConfigurationId: string): Promise<string | null> => {
// Return cached secret if already fetched
if (revealedSecrets[webhookConfigurationId]) {
return revealedSecrets[webhookConfigurationId];
}
setLoadingSecrets(prev => new Set(prev).add(webhookConfigurationId));
try {
const data = await fetchQuery<WebhooksSettingsPage_signingSecretQuery>(
environment,
signingSecretQuery,
{ webhookConfigurationId },
).toPromise();
const secret = data?.node?.signingSecret;
if (secret) {
setRevealedSecrets(prev => ({ ...prev, [webhookConfigurationId]: secret }));
return secret;
}
return null;
} catch {
toast({
title: __("Error"),
description: __("Failed to load signing secret."),
variant: "error",
});
return null;
} finally {
setLoadingSecrets((prev) => {
const next = new Set(prev);
next.delete(webhookConfigurationId);
return next;
});
}
},
[environment, revealedSecrets, toast, __],
);
const toggleRevealSecret = (id: string) => {
if (revealedSecrets[id]) {
setRevealedSecrets((prev) => {
const next = { ...prev };
delete next[id];
return next;
});
} else {
void fetchSigningSecret(id);
}
};
const copyToClipboard = async (webhookConfigurationId: string, label: string) => {
const secret = await fetchSigningSecret(webhookConfigurationId);
if (secret) {
void navigator.clipboard.writeText(secret);
toast({
title: __("Copied to clipboard"),
description: label,
variant: "success",
});
}
};
const { organization } = usePreloadedQuery<WebhooksSettingsPageQuery>(
webhooksSettingsPageQuery,
queryRef,
);
if (organization.__typename === "%other") {
throw new Error("Relay node is not an organization");
}
const [createWebhook, isCreating]
= useMutationWithToasts<WebhooksSettingsPage_createMutation>(
createWebhookConfigurationMutation,
{
successMessage: __("Webhook created successfully"),
errorMessage: __("Failed to create webhook"),
},
);
const [updateWebhook, isUpdating]
= useMutationWithToasts<WebhooksSettingsPage_updateMutation>(
updateWebhookConfigurationMutation,
{
successMessage: __("Webhook updated successfully"),
errorMessage: __("Failed to update webhook"),
},
);
const [deleteWebhook, isDeleting]
= useMutationWithToasts<WebhooksSettingsPage_deleteMutation>(
deleteWebhookConfigurationMutation,
{
successMessage: __("Webhook deleted successfully"),
errorMessage: __("Failed to delete webhook"),
},
);
const webhooks = organization.webhookConfigurations?.edges ?? [];
const connectionId = ConnectionHandler.getConnectionID(
organization.id,
"WebhooksSettingsPage_webhookConfigurations",
);
const handleCreate = (values: WebhookFormData) => {
void createWebhook({
variables: {
input: {
organizationId: organization.id,
endpointUrl: values.endpointUrl,
selectedEvents: values.selectedEvents,
},
connections: [connectionId],
},
});
};
const handleUpdate = (id: string, values: WebhookFormData) => {
void updateWebhook({
variables: {
input: {
id,
endpointUrl: values.endpointUrl,
selectedEvents: values.selectedEvents,
},
},
});
};
const handleDelete = (id: string) => {
void deleteWebhook({
variables: {
input: {
webhookConfigurationId: id,
},
connections: [connectionId],
},
onSuccess: () => {
setDeletingId(null);
deleteDialogRef.current?.close();
},
});
};
return (
<div className="space-y-4">
<div className="flex items-center justify-between">
<div>
<h2 className="text-base font-medium">{__("Webhook Configurations")}</h2>
<p className="text-sm text-txt-tertiary">
{__(
"Configure webhooks to receive notifications when events occur in your organization.",
)}
</p>
</div>
<WebhookFormDialog
mode="create"
onSubmit={handleCreate}
isSubmitting={isCreating}
trigger={(
<Button icon={IconPlusLarge}>
{__("Add Webhook Configuration")}
</Button>
)}
/>
</div>
{webhooks.length === 0
? (
<Card padded>
<div className="text-center py-8">
<p className="text-sm text-txt-tertiary">
{__("No webhook configurations yet. Add one to get started.")}
</p>
</div>
</Card>
)
: (
<div className="space-y-3">
{webhooks.map(({ node: webhook }) => (
<Card key={webhook.id} padded>
<div className="flex items-start justify-between gap-4">
<div className="flex-1 min-w-0 space-y-2">
<div>
<Label>{__("Endpoint URL")}</Label>
<p className="text-sm font-mono text-txt-secondary truncate">
{webhook.endpointUrl}
</p>
</div>
<div>
<Label>{__("Signing Secret")}</Label>
<div className="flex items-center gap-2 mt-1">
<code className="flex-1 bg-subtle p-2 rounded text-sm font-mono break-all">
{revealedSecrets[webhook.id]
? revealedSecrets[webhook.id]
: "••••••••••••••••••••••••••••••••"}
</code>
<Button
variant="secondary"
onClick={() => toggleRevealSecret(webhook.id)}
disabled={loadingSecrets.has(webhook.id)}
>
{loadingSecrets.has(webhook.id)
? <Spinner size={16} />
: revealedSecrets[webhook.id]
? __("Hide")
: __("Show")}
</Button>
<Button
variant="secondary"
onClick={() => void copyToClipboard(webhook.id, __("Signing Secret"))}
disabled={loadingSecrets.has(webhook.id)}
icon={IconSquareBehindSquare2}
aria-label={__("Copy signing secret")}
/>
</div>
</div>
<div>
<Label>{__("Events")}</Label>
<div className="flex flex-wrap gap-1.5 mt-1">
{webhook.selectedEvents.map((event) => {
const eventLabel
= EVENT_TYPES.find(e => e.value === event)?.label ?? event;
return (
<span
key={event}
className="inline-flex items-center rounded-md bg-surface-secondary px-2 py-0.5 text-xs font-mono text-txt-secondary border border-border-solid"
>
{eventLabel}
</span>
);
})}
</div>
</div>
</div>
<div className="flex items-center gap-1 shrink-0">
<WebhookFormDialog
mode="edit"
initialValues={{
endpointUrl: webhook.endpointUrl,
selectedEvents: webhook.selectedEvents as WebhookEventType[],
}}
onSubmit={values => handleUpdate(webhook.id, values)}
isSubmitting={isUpdating}
trigger={(
<Button
variant="secondary"
icon={IconPencil}
aria-label={__("Edit webhook")}
/>
)}
/>
<Button
variant="quaternary"
icon={IconTrashCan}
aria-label={__("Delete webhook")}
className="text-red-600 hover:text-red-700"
onClick={() => {
setDeletingId(webhook.id);
deleteDialogRef.current?.open();
}}
/>
</div>
</div>
</Card>
))}
</div>
)}
<Dialog
ref={deleteDialogRef}
title={__("Delete Webhook")}
className="max-w-md"
>
<DialogContent padded>
<p className="text-txt-secondary">
{__(
"Are you sure you want to delete this webhook configuration?",
)}
</p>
<p className="text-txt-secondary mt-2">
{__("This action cannot be undone.")}
</p>
</DialogContent>
<DialogFooter>
<Button
variant="danger"
onClick={() => deletingId && handleDelete(deletingId)}
disabled={isDeleting}
icon={isDeleting ? Spinner : IconTrashCan}
>
{isDeleting
? __("Deleting...")
: __("Delete")}
</Button>
</DialogFooter>
</Dialog>
</div>
);
}

View File

@@ -205,6 +205,13 @@ const routes = [
import("./pages/iam/organizations/settings/SCIMSettingsPageLoader"),
),
},
{
path: "webhooks",
Component: lazy(
() =>
import("./pages/iam/organizations/settings/WebhooksSettingsPageLoader"),
),
},
],
},
...peopleRoutes,

View File

@@ -79,6 +79,9 @@ const (
SCIMEventEntityType uint16 = 53
TokenEntityType uint16 = 54
SCIMBridgeEntityType uint16 = 55
WebhookConfigurationEntityType uint16 = 56
WebhookEventEntityType uint16 = 57
WebhookCallEntityType uint16 = 58
)
func NewEntityFromID(id gid.GID) (any, bool) {
@@ -191,6 +194,12 @@ func NewEntityFromID(id gid.GID) (any, bool) {
return &Token{ID: id}, true
case SCIMBridgeEntityType:
return &SCIMBridge{ID: id}, true
case WebhookConfigurationEntityType:
return &WebhookConfiguration{ID: id}, true
case WebhookEventEntityType:
return &WebhookEvent{ID: id}, true
case WebhookCallEntityType:
return &WebhookCall{ID: id}, true
default:
return nil, false
}

View File

@@ -0,0 +1,52 @@
CREATE TYPE webhook_event_type AS ENUM (
'meeting:created',
'meeting:updated',
'meeting:deleted',
'vendor:created',
'vendor:updated',
'vendor:deleted'
);
CREATE TABLE webhook_configurations (
id TEXT PRIMARY KEY,
tenant_id TEXT NOT NULL,
organization_id TEXT NOT NULL REFERENCES organizations(id) ON UPDATE CASCADE ON DELETE CASCADE,
endpoint_url TEXT NOT NULL,
selected_events webhook_event_type[] NOT NULL,
encrypted_signing_secret BYTEA NOT NULL,
created_at TIMESTAMP WITH TIME ZONE NOT NULL,
updated_at TIMESTAMP WITH TIME ZONE NOT NULL
);
CREATE TYPE webhook_event_status AS ENUM (
'PENDING',
'PROCESSING',
'DELIVERED'
);
CREATE TABLE webhook_events (
id TEXT PRIMARY KEY,
tenant_id TEXT NOT NULL,
organization_id TEXT NOT NULL REFERENCES organizations(id) ON UPDATE CASCADE ON DELETE CASCADE,
event_type webhook_event_type NOT NULL,
status webhook_event_status NOT NULL,
data JSONB NOT NULL,
created_at TIMESTAMP WITH TIME ZONE NOT NULL,
processed_at TIMESTAMP WITH TIME ZONE
);
CREATE TYPE webhook_call_status AS ENUM (
'SUCCEEDED',
'FAILED'
);
CREATE TABLE webhook_calls (
id TEXT PRIMARY KEY,
tenant_id TEXT NOT NULL,
webhook_event_id TEXT NOT NULL REFERENCES webhook_events(id) ON UPDATE CASCADE ON DELETE CASCADE,
webhook_configuration_id TEXT NOT NULL REFERENCES webhook_configurations(id) ON UPDATE CASCADE ON DELETE CASCADE,
endpoint_url TEXT NOT NULL,
status webhook_call_status NOT NULL,
response JSONB,
created_at TIMESTAMP WITH TIME ZONE NOT NULL
);

View File

@@ -0,0 +1,87 @@
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package coredata
import (
"context"
"encoding/json"
"fmt"
"time"
"github.com/jackc/pgx/v5"
"go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid"
)
type (
WebhookCall struct {
ID gid.GID `db:"id"`
WebhookEventID gid.GID `db:"webhook_event_id"`
WebhookConfigurationID gid.GID `db:"webhook_configuration_id"`
EndpointURL string `db:"endpoint_url"`
Status WebhookCallStatus `db:"status"`
Response json.RawMessage `db:"response"`
CreatedAt time.Time `db:"created_at"`
}
WebhookCalls []*WebhookCall
)
func (w *WebhookCall) Insert(
ctx context.Context,
conn pg.Conn,
scope Scoper,
) error {
q := `
INSERT INTO webhook_calls (
id,
tenant_id,
webhook_event_id,
webhook_configuration_id,
endpoint_url,
status,
response,
created_at
)
VALUES (
@id,
@tenant_id,
@webhook_event_id,
@webhook_configuration_id,
@endpoint_url,
@status,
@response,
@created_at
)
`
args := pgx.StrictNamedArgs{
"id": w.ID,
"tenant_id": scope.GetTenantID(),
"webhook_event_id": w.WebhookEventID,
"webhook_configuration_id": w.WebhookConfigurationID,
"endpoint_url": w.EndpointURL,
"status": w.Status,
"response": w.Response,
"created_at": w.CreatedAt,
}
_, err := conn.Exec(ctx, q, args)
if err != nil {
return fmt.Errorf("cannot insert webhook call: %w", err)
}
return nil
}

View File

@@ -0,0 +1,64 @@
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package coredata
import (
"database/sql/driver"
"fmt"
)
type WebhookCallStatus string
const (
WebhookCallStatusSucceeded WebhookCallStatus = "SUCCEEDED"
WebhookCallStatusFailed WebhookCallStatus = "FAILED"
)
func (s WebhookCallStatus) String() string {
return string(s)
}
func (s WebhookCallStatus) IsValid() bool {
switch s {
case WebhookCallStatusSucceeded, WebhookCallStatusFailed:
return true
}
return false
}
func (s WebhookCallStatus) MarshalText() ([]byte, error) {
return []byte(s.String()), nil
}
func (s *WebhookCallStatus) UnmarshalText(text []byte) error {
*s = WebhookCallStatus(text)
if !s.IsValid() {
return fmt.Errorf("%s is not a valid WebhookCallStatus", string(text))
}
return nil
}
func (s *WebhookCallStatus) Scan(value any) error {
str, ok := value.(string)
if !ok {
return fmt.Errorf("unsupported type for WebhookCallStatus: %T", value)
}
return s.UnmarshalText([]byte(str))
}
func (s WebhookCallStatus) Value() (driver.Value, error) {
return s.String(), nil
}

View File

@@ -0,0 +1,411 @@
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package coredata
import (
"context"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"maps"
"time"
"github.com/jackc/pgx/v5"
"go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/crypto/cipher"
"go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/page"
)
type (
WebhookConfiguration struct {
ID gid.GID `db:"id"`
OrganizationID gid.GID `db:"organization_id"`
EndpointURL string `db:"endpoint_url"`
SelectedEvents WebhookEventTypes `db:"selected_events"`
EncryptedSigningSecret []byte `db:"encrypted_signing_secret"`
CreatedAt time.Time `db:"created_at"`
UpdatedAt time.Time `db:"updated_at"`
}
WebhookConfigurations []*WebhookConfiguration
)
func (w *WebhookConfiguration) GenerateSigningSecret(encryptionKey cipher.EncryptionKey) (string, error) {
secret := make([]byte, 32)
if _, err := rand.Read(secret); err != nil {
return "", fmt.Errorf("cannot generate signing secret: %w", err)
}
signingSecret := "whsec_" + hex.EncodeToString(secret)
encrypted, err := cipher.Encrypt([]byte(signingSecret), encryptionKey)
if err != nil {
return "", fmt.Errorf("cannot encrypt signing secret: %w", err)
}
w.EncryptedSigningSecret = encrypted
return signingSecret, nil
}
func (w *WebhookConfiguration) DecryptSigningSecret(encryptionKey cipher.EncryptionKey) (string, error) {
if len(w.EncryptedSigningSecret) == 0 {
return "", fmt.Errorf("no encrypted signing secret")
}
plaintext, err := cipher.Decrypt(w.EncryptedSigningSecret, encryptionKey)
if err != nil {
return "", fmt.Errorf("cannot decrypt signing secret: %w", err)
}
return string(plaintext), nil
}
func (w WebhookConfiguration) CursorKey(orderBy WebhookConfigurationOrderField) page.CursorKey {
switch orderBy {
case WebhookConfigurationOrderFieldCreatedAt:
return page.NewCursorKey(w.ID, w.CreatedAt)
}
panic(fmt.Sprintf("unsupported order by: %s", orderBy))
}
// AuthorizationAttributes returns the authorization attributes for policy evaluation.
func (w *WebhookConfiguration) AuthorizationAttributes(ctx context.Context, conn pg.Conn) (map[string]string, error) {
q := `SELECT organization_id FROM webhook_configurations WHERE id = $1 LIMIT 1;`
var organizationID gid.GID
if err := conn.QueryRow(ctx, q, w.ID).Scan(&organizationID); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
}
return nil, fmt.Errorf("cannot query webhook configuration authorization attributes: %w", err)
}
return map[string]string{"organization_id": organizationID.String()}, nil
}
func (w *WebhookConfiguration) LoadByID(
ctx context.Context,
conn pg.Conn,
scope Scoper,
webhookConfigurationID gid.GID,
) error {
q := `
SELECT
id,
organization_id,
endpoint_url,
selected_events,
encrypted_signing_secret,
created_at,
updated_at
FROM
webhook_configurations
WHERE
%s
AND id = @webhook_configuration_id
LIMIT 1;
`
q = fmt.Sprintf(q, scope.SQLFragment())
args := pgx.StrictNamedArgs{"webhook_configuration_id": webhookConfigurationID}
maps.Copy(args, scope.SQLArguments())
rows, err := conn.Query(ctx, q, args)
if err != nil {
return fmt.Errorf("cannot query webhook configurations: %w", err)
}
wc, err := pgx.CollectExactlyOneRow(rows, pgx.RowToStructByName[WebhookConfiguration])
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return ErrResourceNotFound
}
return fmt.Errorf("cannot collect webhook configuration: %w", err)
}
*w = wc
return nil
}
func (w *WebhookConfigurations) LoadByOrganizationID(
ctx context.Context,
conn pg.Conn,
scope Scoper,
organizationID gid.GID,
cursor *page.Cursor[WebhookConfigurationOrderField],
) error {
q := `
SELECT
id,
organization_id,
endpoint_url,
selected_events,
encrypted_signing_secret,
created_at,
updated_at
FROM
webhook_configurations
WHERE
%s
AND organization_id = @organization_id
AND %s
`
q = fmt.Sprintf(q, scope.SQLFragment(), cursor.SQLFragment())
args := pgx.NamedArgs{"organization_id": organizationID}
maps.Copy(args, scope.SQLArguments())
maps.Copy(args, cursor.SQLArguments())
rows, err := conn.Query(ctx, q, args)
if err != nil {
return fmt.Errorf("cannot query webhook configurations: %w", err)
}
configurations, err := pgx.CollectRows(rows, pgx.RowToAddrOfStructByName[WebhookConfiguration])
if err != nil {
return fmt.Errorf("cannot collect webhook configurations: %w", err)
}
*w = configurations
return nil
}
func (w *WebhookConfigurations) CountByOrganizationID(
ctx context.Context,
conn pg.Conn,
scope Scoper,
organizationID gid.GID,
) (int, error) {
q := `
SELECT
COUNT(*)
FROM
webhook_configurations
WHERE
%s
AND organization_id = @organization_id
`
q = fmt.Sprintf(q, scope.SQLFragment())
args := pgx.StrictNamedArgs{
"organization_id": organizationID,
}
maps.Copy(args, scope.SQLArguments())
row := conn.QueryRow(ctx, q, args)
var count int
if err := row.Scan(&count); err != nil {
return 0, fmt.Errorf("cannot count webhook configurations: %w", err)
}
return count, nil
}
func (w *WebhookConfigurations) ExistsByOrganizationIDAndEventType(
ctx context.Context,
conn pg.Conn,
scope Scoper,
organizationID gid.GID,
eventType WebhookEventType,
) (bool, error) {
q := `
SELECT EXISTS (
SELECT 1
FROM webhook_configurations
WHERE %s
AND organization_id = @organization_id
AND @event_type = ANY(selected_events)
)
`
q = fmt.Sprintf(q, scope.SQLFragment())
args := pgx.StrictNamedArgs{
"organization_id": organizationID,
"event_type": eventType.String(),
}
maps.Copy(args, scope.SQLArguments())
var exists bool
if err := conn.QueryRow(ctx, q, args).Scan(&exists); err != nil {
return false, fmt.Errorf("cannot check webhook configuration existence: %w", err)
}
return exists, nil
}
func (w *WebhookConfiguration) Insert(
ctx context.Context,
conn pg.Conn,
scope Scoper,
) error {
q := `
INSERT INTO
webhook_configurations (
tenant_id,
id,
organization_id,
endpoint_url,
selected_events,
encrypted_signing_secret,
created_at,
updated_at
)
VALUES (
@tenant_id,
@webhook_configuration_id,
@organization_id,
@endpoint_url,
@selected_events,
@encrypted_signing_secret,
@created_at,
@updated_at
);
`
args := pgx.StrictNamedArgs{
"tenant_id": scope.GetTenantID(),
"webhook_configuration_id": w.ID,
"organization_id": w.OrganizationID,
"endpoint_url": w.EndpointURL,
"selected_events": w.SelectedEvents,
"encrypted_signing_secret": w.EncryptedSigningSecret,
"created_at": w.CreatedAt,
"updated_at": w.UpdatedAt,
}
_, err := conn.Exec(ctx, q, args)
if err != nil {
return fmt.Errorf("cannot insert webhook configuration: %w", err)
}
return nil
}
func (w *WebhookConfiguration) Update(
ctx context.Context,
conn pg.Conn,
scope Scoper,
) error {
q := `
UPDATE webhook_configurations
SET
endpoint_url = @endpoint_url,
selected_events = @selected_events,
updated_at = @updated_at
WHERE %s
AND id = @webhook_configuration_id
`
q = fmt.Sprintf(q, scope.SQLFragment())
args := pgx.StrictNamedArgs{
"webhook_configuration_id": w.ID,
"endpoint_url": w.EndpointURL,
"selected_events": w.SelectedEvents,
"updated_at": w.UpdatedAt,
}
maps.Copy(args, scope.SQLArguments())
result, err := conn.Exec(ctx, q, args)
if err != nil {
return fmt.Errorf("cannot update webhook configuration: %w", err)
}
if result.RowsAffected() == 0 {
return ErrResourceNotFound
}
return nil
}
func (w *WebhookConfigurations) LoadMatchingByOrganizationIDAndEventType(
ctx context.Context,
conn pg.Conn,
scope Scoper,
organizationID gid.GID,
eventType WebhookEventType,
) error {
q := `
SELECT
id,
organization_id,
endpoint_url,
selected_events,
encrypted_signing_secret,
created_at,
updated_at
FROM
webhook_configurations
WHERE
%s
AND organization_id = @organization_id
AND @event_type = ANY(selected_events)
`
q = fmt.Sprintf(q, scope.SQLFragment())
args := pgx.StrictNamedArgs{
"organization_id": organizationID,
"event_type": eventType.String(),
}
maps.Copy(args, scope.SQLArguments())
rows, err := conn.Query(ctx, q, args)
if err != nil {
return fmt.Errorf("cannot query matching webhook configurations: %w", err)
}
configurations, err := pgx.CollectRows(rows, pgx.RowToAddrOfStructByName[WebhookConfiguration])
if err != nil {
return fmt.Errorf("cannot collect matching webhook configurations: %w", err)
}
*w = configurations
return nil
}
func (w *WebhookConfiguration) Delete(
ctx context.Context,
conn pg.Conn,
scope Scoper,
) error {
q := `
DELETE FROM webhook_configurations
WHERE %s
AND id = @webhook_configuration_id
`
q = fmt.Sprintf(q, scope.SQLFragment())
args := pgx.StrictNamedArgs{
"webhook_configuration_id": w.ID,
}
maps.Copy(args, scope.SQLArguments())
result, err := conn.Exec(ctx, q, args)
if err != nil {
return fmt.Errorf("cannot delete webhook configuration: %w", err)
}
if result.RowsAffected() == 0 {
return ErrResourceNotFound
}
return nil
}

View File

@@ -0,0 +1,55 @@
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package coredata
import (
"fmt"
)
type (
WebhookConfigurationOrderField string
)
const (
WebhookConfigurationOrderFieldCreatedAt WebhookConfigurationOrderField = "CREATED_AT"
)
func (p WebhookConfigurationOrderField) Column() string {
return string(p)
}
func (p WebhookConfigurationOrderField) String() string {
return string(p)
}
func (p WebhookConfigurationOrderField) IsValid() bool {
switch p {
case WebhookConfigurationOrderFieldCreatedAt:
return true
}
return false
}
func (p WebhookConfigurationOrderField) MarshalText() ([]byte, error) {
return []byte(p.String()), nil
}
func (p *WebhookConfigurationOrderField) UnmarshalText(text []byte) error {
*p = WebhookConfigurationOrderField(text)
if !p.IsValid() {
return fmt.Errorf("%s is not a valid WebhookConfigurationOrderField", string(text))
}
return nil
}

View File

@@ -0,0 +1,160 @@
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package coredata
import (
"context"
"encoding/json"
"errors"
"fmt"
"maps"
"time"
"github.com/jackc/pgx/v5"
"go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid"
)
type (
WebhookEvent struct {
ID gid.GID `db:"id"`
OrganizationID gid.GID `db:"organization_id"`
EventType WebhookEventType `db:"event_type"`
Status WebhookEventStatus `db:"status"`
Data json.RawMessage `db:"data"`
CreatedAt time.Time `db:"created_at"`
ProcessedAt *time.Time `db:"processed_at"`
}
WebhookEvents []*WebhookEvent
)
func (w *WebhookEvent) Insert(
ctx context.Context,
conn pg.Conn,
scope Scoper,
) error {
q := `
INSERT INTO webhook_events (
id,
tenant_id,
organization_id,
event_type,
status,
data,
created_at
)
VALUES (
@id,
@tenant_id,
@organization_id,
@event_type,
@status,
@data,
@created_at
)
`
args := pgx.StrictNamedArgs{
"id": w.ID,
"tenant_id": scope.GetTenantID(),
"organization_id": w.OrganizationID,
"event_type": w.EventType,
"status": w.Status,
"data": w.Data,
"created_at": w.CreatedAt,
}
_, err := conn.Exec(ctx, q, args)
if err != nil {
return fmt.Errorf("cannot insert webhook event: %w", err)
}
return nil
}
func (w *WebhookEvent) LoadNextPendingForUpdate(
ctx context.Context,
conn pg.Conn,
) error {
q := `
SELECT
id,
organization_id,
event_type,
status,
data,
created_at,
processed_at
FROM webhook_events
WHERE status = 'PENDING'
ORDER BY created_at ASC
LIMIT 1
FOR UPDATE SKIP LOCKED
`
rows, err := conn.Query(ctx, q)
if err != nil {
return fmt.Errorf("cannot query pending webhook events: %w", err)
}
event, err := pgx.CollectExactlyOneRow(rows, pgx.RowToStructByName[WebhookEvent])
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return ErrResourceNotFound
}
return fmt.Errorf("cannot collect webhook event: %w", err)
}
*w = event
return nil
}
func (w *WebhookEvent) UpdateStatus(
ctx context.Context,
conn pg.Conn,
scope Scoper,
) error {
q := `
UPDATE webhook_events
SET
status = @status,
processed_at = @processed_at
WHERE %s
AND id = @id
`
q = fmt.Sprintf(q, scope.SQLFragment())
args := pgx.StrictNamedArgs{
"id": w.ID,
"status": w.Status.String(),
"processed_at": w.ProcessedAt,
}
maps.Copy(args, scope.SQLArguments())
result, err := conn.Exec(ctx, q, args)
if err != nil {
return fmt.Errorf("cannot update webhook event: %w", err)
}
if result.RowsAffected() == 0 {
return ErrResourceNotFound
}
return nil
}

View File

@@ -0,0 +1,65 @@
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package coredata
import (
"database/sql/driver"
"fmt"
)
type WebhookEventStatus string
const (
WebhookEventStatusPending WebhookEventStatus = "PENDING"
WebhookEventStatusProcessing WebhookEventStatus = "PROCESSING"
WebhookEventStatusDelivered WebhookEventStatus = "DELIVERED"
)
func (s WebhookEventStatus) String() string {
return string(s)
}
func (s WebhookEventStatus) IsValid() bool {
switch s {
case WebhookEventStatusPending, WebhookEventStatusProcessing, WebhookEventStatusDelivered:
return true
}
return false
}
func (s WebhookEventStatus) MarshalText() ([]byte, error) {
return []byte(s.String()), nil
}
func (s *WebhookEventStatus) UnmarshalText(text []byte) error {
*s = WebhookEventStatus(text)
if !s.IsValid() {
return fmt.Errorf("%s is not a valid WebhookEventStatus", string(text))
}
return nil
}
func (s *WebhookEventStatus) Scan(value any) error {
str, ok := value.(string)
if !ok {
return fmt.Errorf("unsupported type for WebhookEventStatus: %T", value)
}
return s.UnmarshalText([]byte(str))
}
func (s WebhookEventStatus) Value() (driver.Value, error) {
return s.String(), nil
}

View File

@@ -0,0 +1,133 @@
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package coredata
import (
"database/sql/driver"
"fmt"
"strings"
)
type WebhookEventType string
const (
WebhookEventTypeMeetingCreated WebhookEventType = "meeting:created"
WebhookEventTypeMeetingUpdated WebhookEventType = "meeting:updated"
WebhookEventTypeMeetingDeleted WebhookEventType = "meeting:deleted"
WebhookEventTypeVendorCreated WebhookEventType = "vendor:created"
WebhookEventTypeVendorUpdated WebhookEventType = "vendor:updated"
WebhookEventTypeVendorDeleted WebhookEventType = "vendor:deleted"
)
func (w WebhookEventType) String() string {
return string(w)
}
func (w WebhookEventType) IsValid() bool {
switch w {
case WebhookEventTypeMeetingCreated, WebhookEventTypeMeetingUpdated, WebhookEventTypeMeetingDeleted,
WebhookEventTypeVendorCreated, WebhookEventTypeVendorUpdated, WebhookEventTypeVendorDeleted:
return true
}
return false
}
func (w WebhookEventType) MarshalText() ([]byte, error) {
return []byte(w.String()), nil
}
func (w *WebhookEventType) UnmarshalText(text []byte) error {
*w = WebhookEventType(text)
if !w.IsValid() {
return fmt.Errorf("%s is not a valid WebhookEventType", string(text))
}
return nil
}
func (w *WebhookEventType) Scan(value any) error {
var s string
switch v := value.(type) {
case string:
s = v
case []byte:
s = string(v)
default:
return fmt.Errorf("unsupported type for WebhookEventType: %T", value)
}
return w.UnmarshalText([]byte(s))
}
func (w WebhookEventType) Value() (driver.Value, error) {
return w.String(), nil
}
type WebhookEventTypes []WebhookEventType
func (s *WebhookEventTypes) Scan(value any) error {
switch v := value.(type) {
case string:
return s.scanFromString(v)
case []byte:
return s.scanFromString(string(v))
default:
return fmt.Errorf("unsupported type for WebhookEventTypes: %T", value)
}
}
func (s *WebhookEventTypes) scanFromString(str string) error {
str = strings.TrimSpace(str)
if str == "{}" || str == "" {
*s = []WebhookEventType{}
return nil
}
if strings.HasPrefix(str, "{") && strings.HasSuffix(str, "}") {
str = str[1 : len(str)-1]
}
parts := strings.Split(str, ",")
result := make([]WebhookEventType, len(parts))
for i, part := range parts {
part = strings.TrimSpace(part)
if strings.HasPrefix(part, `"`) && strings.HasSuffix(part, `"`) {
part = part[1 : len(part)-1]
}
var et WebhookEventType
if err := et.Scan(part); err != nil {
return fmt.Errorf("invalid webhook event type in array: %s", part)
}
result[i] = et
}
*s = result
return nil
}
func (s WebhookEventTypes) Value() (driver.Value, error) {
if len(s) == 0 {
return "{}", nil
}
values := make([]string, len(s))
for i, et := range s {
values[i] = et.String()
}
return "{" + strings.Join(values, ",") + "}", nil
}

View File

@@ -316,4 +316,11 @@ const (
ActionApplicabilityStatementCreate = "core:applicability-statement:create"
ActionApplicabilityStatementUpdate = "core:applicability-statement:update"
ActionApplicabilityStatementDelete = "core:applicability-statement:delete"
// WebhookConfiguration actions
ActionWebhookConfigurationList = "core:webhook-configuration:list"
ActionWebhookConfigurationGet = "core:webhook-configuration:get"
ActionWebhookConfigurationCreate = "core:webhook-configuration:create"
ActionWebhookConfigurationUpdate = "core:webhook-configuration:update"
ActionWebhookConfigurationDelete = "core:webhook-configuration:delete"
)

View File

@@ -23,7 +23,9 @@ import (
"go.probo.inc/probo/pkg/coredata"
"go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/page"
"go.probo.inc/probo/pkg/server/api/console/v1/types"
"go.probo.inc/probo/pkg/validator"
"go.probo.inc/probo/pkg/webhook"
)
type MeetingService struct {
@@ -207,6 +209,10 @@ func (s MeetingService) Create(
}
}
if err := webhook.InsertEvent(ctx, conn, s.svc.scope, organization.ID, coredata.WebhookEventTypeMeetingCreated, types.NewMeeting(meeting)); err != nil {
return fmt.Errorf("cannot insert webhook event: %w", err)
}
return nil
},
)
@@ -283,6 +289,10 @@ func (s MeetingService) Update(
}
}
if err := webhook.InsertEvent(ctx, conn, s.svc.scope, meeting.OrganizationID, coredata.WebhookEventTypeMeetingUpdated, types.NewMeeting(meeting)); err != nil {
return fmt.Errorf("cannot insert webhook event: %w", err)
}
return nil
},
)
@@ -307,6 +317,10 @@ func (s MeetingService) Delete(
return fmt.Errorf("cannot load meeting: %w", err)
}
if err := webhook.InsertEvent(ctx, conn, s.svc.scope, meeting.OrganizationID, coredata.WebhookEventTypeMeetingDeleted, types.NewMeeting(meeting)); err != nil {
return fmt.Errorf("cannot insert webhook event: %w", err)
}
if err := meeting.Delete(ctx, conn, s.svc.scope); err != nil {
return fmt.Errorf("cannot delete meeting: %w", err)
}

View File

@@ -79,6 +79,7 @@ var ViewerPolicy = policy.NewPolicy(
ActionRightsRequestGet, ActionRightsRequestList,
ActionStateOfApplicabilityGet, ActionStateOfApplicabilityList,
ActionApplicabilityStatementGet, ActionApplicabilityStatementList,
ActionWebhookConfigurationGet, ActionWebhookConfigurationList,
).WithSID("entity-read-access").When(organizationCondition),
policy.Allow(

View File

@@ -92,6 +92,7 @@ type (
Data *DatumService
Audits *AuditService
Meetings *MeetingService
WebhookConfigurations *WebhookConfigurationService
Reports *ReportService
TrustCenters *TrustCenterService
TrustCenterAccesses *TrustCenterAccessService
@@ -213,6 +214,7 @@ func (s *Service) WithTenant(tenantID gid.TenantID) *TenantService {
tenantService.Data = &DatumService{svc: tenantService}
tenantService.Audits = &AuditService{svc: tenantService}
tenantService.Meetings = &MeetingService{svc: tenantService}
tenantService.WebhookConfigurations = &WebhookConfigurationService{svc: tenantService}
tenantService.Reports = &ReportService{svc: tenantService}
tenantService.TrustCenters = &TrustCenterService{svc: tenantService}
tenantService.TrustCenterAccesses = &TrustCenterAccessService{svc: tenantService}

View File

@@ -23,7 +23,9 @@ import (
"go.probo.inc/probo/pkg/coredata"
"go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/page"
"go.probo.inc/probo/pkg/server/api/console/v1/types"
"go.probo.inc/probo/pkg/validator"
"go.probo.inc/probo/pkg/webhook"
)
type (
@@ -392,6 +394,10 @@ func (s VendorService) Update(
return fmt.Errorf("cannot update vendor: %w", err)
}
if err := webhook.InsertEvent(ctx, conn, s.svc.scope, vendor.OrganizationID, coredata.WebhookEventTypeVendorUpdated, types.NewVendor(vendor)); err != nil {
return fmt.Errorf("cannot insert webhook event: %w", err)
}
return nil
},
)
@@ -427,10 +433,19 @@ func (s VendorService) Delete(
ctx context.Context,
vendorID gid.GID,
) error {
vendor := coredata.Vendor{ID: vendorID}
return s.svc.pg.WithConn(
vendor := &coredata.Vendor{}
return s.svc.pg.WithTx(
ctx,
func(conn pg.Conn) error {
if err := vendor.LoadByID(ctx, conn, s.svc.scope, vendorID); err != nil {
return fmt.Errorf("cannot load vendor: %w", err)
}
if err := webhook.InsertEvent(ctx, conn, s.svc.scope, vendor.OrganizationID, coredata.WebhookEventTypeVendorDeleted, types.NewVendor(vendor)); err != nil {
return fmt.Errorf("cannot insert webhook event: %w", err)
}
return vendor.Delete(ctx, conn, s.svc.scope)
},
)
@@ -504,6 +519,10 @@ func (s VendorService) Create(
return fmt.Errorf("cannot insert vendor: %w", err)
}
if err := webhook.InsertEvent(ctx, conn, s.svc.scope, organization.ID, coredata.WebhookEventTypeVendorCreated, types.NewVendor(vendor)); err != nil {
return fmt.Errorf("cannot insert webhook event: %w", err)
}
return nil
},
)

View File

@@ -0,0 +1,290 @@
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package probo
import (
"context"
"fmt"
"time"
"go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/coredata"
"go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/page"
"go.probo.inc/probo/pkg/validator"
)
type WebhookConfigurationService struct {
svc *TenantService
}
type (
CreateWebhookConfigurationRequest struct {
OrganizationID gid.GID
EndpointURL string
SelectedEvents []coredata.WebhookEventType
}
UpdateWebhookConfigurationRequest struct {
WebhookConfigurationID gid.GID
EndpointURL *string
SelectedEvents []coredata.WebhookEventType
}
)
func (r *CreateWebhookConfigurationRequest) Validate() error {
v := validator.New()
v.Check(r.OrganizationID, "organization_id", validator.Required(), validator.GID(coredata.OrganizationEntityType))
v.Check(r.EndpointURL, "endpoint_url", validator.Required(), validator.URL())
return v.Error()
}
func (r *UpdateWebhookConfigurationRequest) Validate() error {
v := validator.New()
v.Check(r.WebhookConfigurationID, "webhook_configuration_id", validator.Required(), validator.GID(coredata.WebhookConfigurationEntityType))
v.Check(r.EndpointURL, "endpoint_url", validator.NotEmpty(), validator.URL())
return v.Error()
}
func (s WebhookConfigurationService) ListForOrganizationID(
ctx context.Context,
organizationID gid.GID,
cursor *page.Cursor[coredata.WebhookConfigurationOrderField],
) (*page.Page[*coredata.WebhookConfiguration, coredata.WebhookConfigurationOrderField], error) {
var configurations coredata.WebhookConfigurations
organization := &coredata.Organization{}
err := s.svc.pg.WithConn(
ctx,
func(conn pg.Conn) error {
if err := organization.LoadByID(ctx, conn, s.svc.scope, organizationID); err != nil {
return fmt.Errorf("cannot load organization: %w", err)
}
err := configurations.LoadByOrganizationID(
ctx,
conn,
s.svc.scope,
organization.ID,
cursor,
)
if err != nil {
return fmt.Errorf("cannot load webhook configurations: %w", err)
}
return nil
},
)
if err != nil {
return nil, err
}
return page.NewPage(configurations, cursor), nil
}
func (s WebhookConfigurationService) CountForOrganizationID(
ctx context.Context,
organizationID gid.GID,
) (int, error) {
var count int
err := s.svc.pg.WithConn(
ctx,
func(conn pg.Conn) (err error) {
configurations := &coredata.WebhookConfigurations{}
count, err = configurations.CountByOrganizationID(ctx, conn, s.svc.scope, organizationID)
if err != nil {
return fmt.Errorf("cannot count webhook configurations: %w", err)
}
return nil
},
)
if err != nil {
return 0, err
}
return count, nil
}
func (s WebhookConfigurationService) Get(
ctx context.Context,
webhookConfigurationID gid.GID,
) (*coredata.WebhookConfiguration, error) {
wc := &coredata.WebhookConfiguration{}
err := s.svc.pg.WithConn(
ctx,
func(conn pg.Conn) error {
if err := wc.LoadByID(ctx, conn, s.svc.scope, webhookConfigurationID); err != nil {
return fmt.Errorf("cannot load webhook configuration: %w", err)
}
return nil
},
)
if err != nil {
return nil, err
}
return wc, nil
}
func (s WebhookConfigurationService) Create(
ctx context.Context,
req CreateWebhookConfigurationRequest,
) (*coredata.WebhookConfiguration, error) {
if err := req.Validate(); err != nil {
return nil, err
}
now := time.Now()
var wc *coredata.WebhookConfiguration
organization := &coredata.Organization{}
err := s.svc.pg.WithTx(
ctx,
func(conn pg.Conn) error {
if err := organization.LoadByID(ctx, conn, s.svc.scope, req.OrganizationID); err != nil {
return fmt.Errorf("cannot load organization: %w", err)
}
wc = &coredata.WebhookConfiguration{
ID: gid.New(organization.ID.TenantID(), coredata.WebhookConfigurationEntityType),
OrganizationID: organization.ID,
EndpointURL: req.EndpointURL,
SelectedEvents: req.SelectedEvents,
CreatedAt: now,
UpdatedAt: now,
}
if _, err := wc.GenerateSigningSecret(s.svc.encryptionKey); err != nil {
return fmt.Errorf("cannot generate signing secret: %w", err)
}
if err := wc.Insert(ctx, conn, s.svc.scope); err != nil {
return fmt.Errorf("cannot insert webhook configuration: %w", err)
}
return nil
},
)
if err != nil {
return nil, err
}
return wc, nil
}
func (s WebhookConfigurationService) Update(
ctx context.Context,
req UpdateWebhookConfigurationRequest,
) (*coredata.WebhookConfiguration, error) {
if err := req.Validate(); err != nil {
return nil, err
}
wc := &coredata.WebhookConfiguration{}
err := s.svc.pg.WithTx(
ctx,
func(conn pg.Conn) error {
if err := wc.LoadByID(ctx, conn, s.svc.scope, req.WebhookConfigurationID); err != nil {
return fmt.Errorf("cannot load webhook configuration: %w", err)
}
if req.EndpointURL != nil {
wc.EndpointURL = *req.EndpointURL
}
if req.SelectedEvents != nil {
wc.SelectedEvents = req.SelectedEvents
}
wc.UpdatedAt = time.Now()
if err := wc.Update(ctx, conn, s.svc.scope); err != nil {
return fmt.Errorf("cannot update webhook configuration: %w", err)
}
return nil
},
)
if err != nil {
return nil, err
}
return wc, nil
}
func (s WebhookConfigurationService) GetSigningSecret(
ctx context.Context,
webhookConfigurationID gid.GID,
) (string, error) {
wc := &coredata.WebhookConfiguration{}
err := s.svc.pg.WithConn(
ctx,
func(conn pg.Conn) error {
if err := wc.LoadByID(ctx, conn, s.svc.scope, webhookConfigurationID); err != nil {
return fmt.Errorf("cannot load webhook configuration: %w", err)
}
return nil
},
)
if err != nil {
return "", err
}
return wc.DecryptSigningSecret(s.svc.encryptionKey)
}
func (s WebhookConfigurationService) Delete(
ctx context.Context,
webhookConfigurationID gid.GID,
) error {
wc := &coredata.WebhookConfiguration{ID: webhookConfigurationID}
err := s.svc.pg.WithTx(
ctx,
func(conn pg.Conn) error {
if err := wc.LoadByID(ctx, conn, s.svc.scope, webhookConfigurationID); err != nil {
return fmt.Errorf("cannot load webhook configuration: %w", err)
}
if err := wc.Delete(ctx, conn, s.svc.scope); err != nil {
return fmt.Errorf("cannot delete webhook configuration: %w", err)
}
return nil
},
)
if err != nil {
return err
}
return nil
}

View File

@@ -15,6 +15,11 @@
package probod
type notificationsConfig struct {
Mailer mailerConfig `json:"mailer"`
Slack slackConfig `json:"slack"`
Mailer mailerConfig `json:"mailer"`
Slack slackConfig `json:"slack"`
Webhook webhookConfig `json:"webhook"`
}
type webhookConfig struct {
SenderInterval int `json:"sender-interval"`
}

View File

@@ -60,6 +60,7 @@ import (
"go.probo.inc/probo/pkg/server"
"go.probo.inc/probo/pkg/slack"
"go.probo.inc/probo/pkg/trust"
"go.probo.inc/probo/pkg/webhook"
"golang.org/x/sync/errgroup"
)
@@ -154,6 +155,9 @@ func New() *Implm {
Slack: slackConfig{
SenderInterval: 60,
},
Webhook: webhookConfig{
SenderInterval: 5,
},
},
CustomDomains: customDomainsConfig{
RenewalInterval: 3600,
@@ -479,6 +483,19 @@ func (impl *Implm) Run(
},
)
webhookSenderCtx, stopWebhookSender := context.WithCancel(context.Background())
webhookSender := webhook.NewSender(pgClient, l.Named("webhook-sender"), webhook.Config{
Interval: time.Duration(impl.cfg.Notifications.Webhook.SenderInterval) * time.Second,
EncryptionKey: impl.cfg.EncryptionKey,
})
wg.Go(
func() {
if err := webhookSender.Run(webhookSenderCtx); err != nil {
cancel(fmt.Errorf("webhook sender crashed: %w", err))
}
},
)
exportJobExporterCtx, stopExportJobExporter := context.WithCancel(context.Background())
wg.Go(
func() {
@@ -511,6 +528,7 @@ func (impl *Implm) Run(
stopMailer()
stopSlackSender()
stopWebhookSender()
stopExportJobExporter()
stopIAMService()
stopApiServer()

View File

@@ -2654,6 +2654,7 @@ type Mutation {
updateSCIMBridge(
input: UpdateSCIMBridgeInput!
): UpdateSCIMBridgePayload @session(required: PRESENT)
}
type Identity implements Node {
@@ -3499,6 +3500,8 @@ type RegenerateSCIMTokenPayload {
type UpdateSCIMBridgePayload {
scimBridge: SCIMBridge!
}
`, BuiltIn: false},
{Name: "../../../../gqlutils/directives/session/schema.graphql", Input: `# Session directive for GraphQL APIs
# Include this schema in your gqlgen configuration to enable session-based access control.

View File

@@ -488,6 +488,16 @@ enum MeetingOrderField
)
}
enum WebhookConfigurationOrderField
@goModel(
model: "go.probo.inc/probo/pkg/coredata.WebhookConfigurationOrderField"
) {
CREATED_AT
@goEnum(
value: "go.probo.inc/probo/pkg/coredata.WebhookConfigurationOrderFieldCreatedAt"
)
}
enum RiskOrderField
@goModel(model: "go.probo.inc/probo/pkg/coredata.RiskOrderField") {
CREATED_AT
@@ -1345,6 +1355,14 @@ input MeetingOrder
field: MeetingOrderField!
}
input WebhookConfigurationOrder
@goModel(
model: "go.probo.inc/probo/pkg/server/api/console/v1/types.WebhookConfigurationOrderBy"
) {
direction: OrderDirection!
field: WebhookConfigurationOrderField!
}
input RiskOrder
@goModel(
model: "go.probo.inc/probo/pkg/server/api/console/v1/types.RiskOrderBy"
@@ -1817,6 +1835,14 @@ type Organization implements Node {
customDomain: CustomDomain @goField(forceResolver: true)
webhookConfigurations(
first: Int
after: CursorKey
last: Int
before: CursorKey
orderBy: WebhookConfigurationOrder
): WebhookConfigurationConnection! @goField(forceResolver: true)
createdAt: Datetime!
updatedAt: Datetime!
@@ -2242,6 +2268,48 @@ type Meeting implements Node {
permission(action: String!): Boolean! @goField(forceResolver: true)
}
enum WebhookEventType
@goModel(model: "go.probo.inc/probo/pkg/coredata.WebhookEventType") {
MEETING_CREATED
@goEnum(value: "go.probo.inc/probo/pkg/coredata.WebhookEventTypeMeetingCreated")
MEETING_UPDATED
@goEnum(value: "go.probo.inc/probo/pkg/coredata.WebhookEventTypeMeetingUpdated")
MEETING_DELETED
@goEnum(value: "go.probo.inc/probo/pkg/coredata.WebhookEventTypeMeetingDeleted")
VENDOR_CREATED
@goEnum(value: "go.probo.inc/probo/pkg/coredata.WebhookEventTypeVendorCreated")
VENDOR_UPDATED
@goEnum(value: "go.probo.inc/probo/pkg/coredata.WebhookEventTypeVendorUpdated")
VENDOR_DELETED
@goEnum(value: "go.probo.inc/probo/pkg/coredata.WebhookEventTypeVendorDeleted")
}
type WebhookConfiguration implements Node {
id: ID!
organization: Organization @goField(forceResolver: true)
endpointUrl: String!
signingSecret: String! @goField(forceResolver: true)
selectedEvents: [WebhookEventType!]!
createdAt: Datetime!
updatedAt: Datetime!
permission(action: String!): Boolean! @goField(forceResolver: true)
}
type WebhookConfigurationConnection
@goModel(
model: "go.probo.inc/probo/pkg/server/api/console/v1/types.WebhookConfigurationConnection"
) {
edges: [WebhookConfigurationEdge!]!
pageInfo: PageInfo!
totalCount: Int! @goField(forceResolver: true)
}
type WebhookConfigurationEdge {
cursor: CursorKey!
node: WebhookConfiguration!
}
type StateOfApplicability implements Node {
id: ID!
name: String!
@@ -3270,6 +3338,16 @@ type Mutation {
createMeeting(input: CreateMeetingInput!): CreateMeetingPayload!
updateMeeting(input: UpdateMeetingInput!): UpdateMeetingPayload!
deleteMeeting(input: DeleteMeetingInput!): DeleteMeetingPayload!
# WebhookConfiguration mutations
createWebhookConfiguration(
input: CreateWebhookConfigurationInput!
): CreateWebhookConfigurationPayload!
updateWebhookConfiguration(
input: UpdateWebhookConfigurationInput!
): UpdateWebhookConfigurationPayload!
deleteWebhookConfiguration(
input: DeleteWebhookConfigurationInput!
): DeleteWebhookConfigurationPayload!
# StateOfApplicability mutations
createStateOfApplicability(
input: CreateStateOfApplicabilityInput!
@@ -4621,6 +4699,34 @@ type DeleteMeetingPayload {
deletedMeetingId: ID!
}
input CreateWebhookConfigurationInput {
organizationId: ID!
endpointUrl: String!
selectedEvents: [WebhookEventType!]!
}
input UpdateWebhookConfigurationInput {
id: ID!
endpointUrl: String
selectedEvents: [WebhookEventType!]
}
input DeleteWebhookConfigurationInput {
webhookConfigurationId: ID!
}
type CreateWebhookConfigurationPayload {
webhookConfigurationEdge: WebhookConfigurationEdge!
}
type UpdateWebhookConfigurationPayload {
webhookConfiguration: WebhookConfiguration!
}
type DeleteWebhookConfigurationPayload {
deletedWebhookConfigurationId: ID!
}
type CreateStateOfApplicabilityPayload {
stateOfApplicabilityEdge: StateOfApplicabilityEdge!
}

File diff suppressed because it is too large Load Diff

View File

@@ -693,6 +693,16 @@ type CreateVendorServicePayload struct {
VendorServiceEdge *VendorServiceEdge `json:"vendorServiceEdge"`
}
type CreateWebhookConfigurationInput struct {
OrganizationID gid.GID `json:"organizationId"`
EndpointURL string `json:"endpointUrl"`
SelectedEvents []coredata.WebhookEventType `json:"selectedEvents"`
}
type CreateWebhookConfigurationPayload struct {
WebhookConfigurationEdge *WebhookConfigurationEdge `json:"webhookConfigurationEdge"`
}
type CustomDomain struct {
ID gid.GID `json:"id"`
Organization *Organization `json:"organization"`
@@ -1103,6 +1113,14 @@ type DeleteVendorServicePayload struct {
DeletedVendorServiceID gid.GID `json:"deletedVendorServiceId"`
}
type DeleteWebhookConfigurationInput struct {
WebhookConfigurationID gid.GID `json:"webhookConfigurationId"`
}
type DeleteWebhookConfigurationPayload struct {
DeletedWebhookConfigurationID gid.GID `json:"deletedWebhookConfigurationId"`
}
type Document struct {
ID gid.GID `json:"id"`
Title string `json:"title"`
@@ -1499,6 +1517,7 @@ type Organization struct {
TrustCenterFiles *TrustCenterFileConnection `json:"trustCenterFiles"`
TrustCenter *TrustCenter `json:"trustCenter,omitempty"`
CustomDomain *CustomDomain `json:"customDomain,omitempty"`
WebhookConfigurations *WebhookConfigurationConnection `json:"webhookConfigurations"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
Permission bool `json:"permission"`
@@ -2342,6 +2361,16 @@ type UpdateVendorServicePayload struct {
VendorService *VendorService `json:"vendorService"`
}
type UpdateWebhookConfigurationInput struct {
ID gid.GID `json:"id"`
EndpointURL *string `json:"endpointUrl,omitempty"`
SelectedEvents []coredata.WebhookEventType `json:"selectedEvents,omitempty"`
}
type UpdateWebhookConfigurationPayload struct {
WebhookConfiguration *WebhookConfiguration `json:"webhookConfiguration"`
}
type UploadAuditReportInput struct {
AuditID gid.GID `json:"auditId"`
File graphql.Upload `json:"file"`
@@ -2593,3 +2622,22 @@ type Viewer struct {
SignableDocuments *SignableDocumentConnection `json:"signableDocuments"`
SignableDocument *SignableDocument `json:"signableDocument,omitempty"`
}
type WebhookConfiguration struct {
ID gid.GID `json:"id"`
Organization *Organization `json:"organization,omitempty"`
EndpointURL string `json:"endpointUrl"`
SigningSecret string `json:"signingSecret"`
SelectedEvents []coredata.WebhookEventType `json:"selectedEvents"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
Permission bool `json:"permission"`
}
func (WebhookConfiguration) IsNode() {}
func (this WebhookConfiguration) GetID() gid.GID { return this.ID }
type WebhookConfigurationEdge struct {
Cursor page.CursorKey `json:"cursor"`
Node *WebhookConfiguration `json:"node"`
}

View File

@@ -0,0 +1,74 @@
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package types
import (
"go.probo.inc/probo/pkg/coredata"
"go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/page"
)
type (
WebhookConfigurationOrderBy OrderBy[coredata.WebhookConfigurationOrderField]
WebhookConfigurationConnection struct {
TotalCount int
Edges []*WebhookConfigurationEdge
PageInfo PageInfo
Resolver any
ParentID gid.GID
}
)
func NewWebhookConfigurationConnection(
p *page.Page[*coredata.WebhookConfiguration, coredata.WebhookConfigurationOrderField],
parentType any,
parentID gid.GID,
) *WebhookConfigurationConnection {
var edges = make([]*WebhookConfigurationEdge, len(p.Data))
for i := range edges {
edges[i] = NewWebhookConfigurationEdge(p.Data[i], p.Cursor.OrderBy.Field)
}
return &WebhookConfigurationConnection{
Edges: edges,
PageInfo: *NewPageInfo(p),
Resolver: parentType,
ParentID: parentID,
}
}
func NewWebhookConfigurationEdge(wc *coredata.WebhookConfiguration, orderBy coredata.WebhookConfigurationOrderField) *WebhookConfigurationEdge {
return &WebhookConfigurationEdge{
Cursor: wc.CursorKey(orderBy),
Node: NewWebhookConfiguration(wc),
}
}
func NewWebhookConfiguration(wc *coredata.WebhookConfiguration) *WebhookConfiguration {
return &WebhookConfiguration{
ID: wc.ID,
Organization: &Organization{
ID: wc.OrganizationID,
},
EndpointURL: wc.EndpointURL,
SelectedEvents: wc.SelectedEvents,
CreatedAt: wc.CreatedAt,
UpdatedAt: wc.UpdatedAt,
}
}

View File

@@ -3678,6 +3678,77 @@ func (r *mutationResolver) DeleteMeeting(ctx context.Context, input types.Delete
}, nil
}
// CreateWebhookConfiguration is the resolver for the createWebhookConfiguration field.
func (r *mutationResolver) CreateWebhookConfiguration(ctx context.Context, input types.CreateWebhookConfigurationInput) (*types.CreateWebhookConfigurationPayload, error) {
if err := r.authorize(ctx, input.OrganizationID, probo.ActionWebhookConfigurationCreate); err != nil {
return nil, err
}
prb := r.ProboService(ctx, input.OrganizationID.TenantID())
wc, err := prb.WebhookConfigurations.Create(
ctx,
probo.CreateWebhookConfigurationRequest{
OrganizationID: input.OrganizationID,
EndpointURL: input.EndpointURL,
SelectedEvents: input.SelectedEvents,
},
)
if err != nil {
r.logger.ErrorCtx(ctx, "cannot create webhook configuration", log.Error(err))
return nil, gqlutils.Internal(ctx)
}
return &types.CreateWebhookConfigurationPayload{
WebhookConfigurationEdge: types.NewWebhookConfigurationEdge(wc, coredata.WebhookConfigurationOrderFieldCreatedAt),
}, nil
}
// UpdateWebhookConfiguration is the resolver for the updateWebhookConfiguration field.
func (r *mutationResolver) UpdateWebhookConfiguration(ctx context.Context, input types.UpdateWebhookConfigurationInput) (*types.UpdateWebhookConfigurationPayload, error) {
if err := r.authorize(ctx, input.ID, probo.ActionWebhookConfigurationUpdate); err != nil {
return nil, err
}
prb := r.ProboService(ctx, input.ID.TenantID())
wc, err := prb.WebhookConfigurations.Update(
ctx,
probo.UpdateWebhookConfigurationRequest{
WebhookConfigurationID: input.ID,
EndpointURL: input.EndpointURL,
SelectedEvents: input.SelectedEvents,
},
)
if err != nil {
r.logger.ErrorCtx(ctx, "cannot update webhook configuration", log.Error(err))
return nil, gqlutils.Internal(ctx)
}
return &types.UpdateWebhookConfigurationPayload{
WebhookConfiguration: types.NewWebhookConfiguration(wc),
}, nil
}
// DeleteWebhookConfiguration is the resolver for the deleteWebhookConfiguration field.
func (r *mutationResolver) DeleteWebhookConfiguration(ctx context.Context, input types.DeleteWebhookConfigurationInput) (*types.DeleteWebhookConfigurationPayload, error) {
if err := r.authorize(ctx, input.WebhookConfigurationID, probo.ActionWebhookConfigurationDelete); err != nil {
return nil, err
}
prb := r.ProboService(ctx, input.WebhookConfigurationID.TenantID())
err := prb.WebhookConfigurations.Delete(ctx, input.WebhookConfigurationID)
if err != nil {
r.logger.ErrorCtx(ctx, "cannot delete webhook configuration", log.Error(err))
return nil, gqlutils.Internal(ctx)
}
return &types.DeleteWebhookConfigurationPayload{
DeletedWebhookConfigurationID: input.WebhookConfigurationID,
}, nil
}
// CreateStateOfApplicability is the resolver for the createStateOfApplicability field.
func (r *mutationResolver) CreateStateOfApplicability(ctx context.Context, input types.CreateStateOfApplicabilityInput) (*types.CreateStateOfApplicabilityPayload, error) {
if err := r.authorize(ctx, input.OrganizationID, probo.ActionStateOfApplicabilityCreate); err != nil {
@@ -6313,6 +6384,36 @@ func (r *organizationResolver) CustomDomain(ctx context.Context, obj *types.Orga
return types.NewCustomDomain(domain, r.customDomainCname), nil
}
// WebhookConfigurations is the resolver for the webhookConfigurations field.
func (r *organizationResolver) WebhookConfigurations(ctx context.Context, obj *types.Organization, first *int, after *page.CursorKey, last *int, before *page.CursorKey, orderBy *types.WebhookConfigurationOrderBy) (*types.WebhookConfigurationConnection, error) {
if err := r.authorize(ctx, obj.ID, probo.ActionWebhookConfigurationList); err != nil {
return nil, err
}
prb := r.ProboService(ctx, obj.ID.TenantID())
pageOrderBy := page.OrderBy[coredata.WebhookConfigurationOrderField]{
Field: coredata.WebhookConfigurationOrderFieldCreatedAt,
Direction: page.OrderDirectionDesc,
}
if orderBy != nil {
pageOrderBy = page.OrderBy[coredata.WebhookConfigurationOrderField]{
Field: orderBy.Field,
Direction: orderBy.Direction,
}
}
cursor := types.NewCursor(first, after, last, before, pageOrderBy)
page, err := prb.WebhookConfigurations.ListForOrganizationID(ctx, obj.ID, cursor)
if err != nil {
r.logger.ErrorCtx(ctx, "cannot list organization webhook configurations", log.Error(err))
return nil, gqlutils.Internal(ctx)
}
return types.NewWebhookConfigurationConnection(page, r, obj.ID), nil
}
// Permission is the resolver for the permission field.
func (r *organizationResolver) Permission(ctx context.Context, obj *types.Organization, action string) (bool, error) {
return r.Resolver.Permission(ctx, obj, action)
@@ -6761,6 +6862,15 @@ func (r *queryResolver) Node(ctx context.Context, id gid.GID) (types.Node, error
}
return types.NewStateOfApplicability(stateOfApplicability), nil
}
case coredata.WebhookConfigurationEntityType:
action = probo.ActionWebhookConfigurationGet
loadNode = func(ctx context.Context, id gid.GID) (types.Node, error) {
wc, err := prb.WebhookConfigurations.Get(ctx, id)
if err != nil {
return nil, err
}
return types.NewWebhookConfiguration(wc), nil
}
default:
}
@@ -8449,6 +8559,67 @@ func (r *viewerResolver) SignableDocument(ctx context.Context, obj *types.Viewer
}, nil
}
// Organization is the resolver for the organization field.
func (r *webhookConfigurationResolver) Organization(ctx context.Context, obj *types.WebhookConfiguration) (*types.Organization, error) {
if err := r.authorize(ctx, obj.ID, probo.ActionOrganizationGet); err != nil {
return nil, err
}
prb := r.ProboService(ctx, obj.ID.TenantID())
organization, err := prb.Organizations.Get(ctx, obj.Organization.ID)
if err != nil {
if errors.Is(err, coredata.ErrResourceNotFound) {
return nil, gqlutils.NotFound(ctx, err)
}
r.logger.ErrorCtx(ctx, "cannot load organization", log.Error(err))
return nil, gqlutils.Internal(ctx)
}
return types.NewOrganization(organization), nil
}
// SigningSecret is the resolver for the signingSecret field.
func (r *webhookConfigurationResolver) SigningSecret(ctx context.Context, obj *types.WebhookConfiguration) (string, error) {
prb := r.ProboService(ctx, obj.ID.TenantID())
signingSecret, err := prb.WebhookConfigurations.GetSigningSecret(ctx, obj.ID)
if err != nil {
r.logger.ErrorCtx(ctx, "cannot get signing secret", log.Error(err))
return "", gqlutils.Internal(ctx)
}
return signingSecret, nil
}
// Permission is the resolver for the permission field.
func (r *webhookConfigurationResolver) Permission(ctx context.Context, obj *types.WebhookConfiguration, action string) (bool, error) {
return r.Resolver.Permission(ctx, obj, action)
}
// TotalCount is the resolver for the totalCount field.
func (r *webhookConfigurationConnectionResolver) TotalCount(ctx context.Context, obj *types.WebhookConfigurationConnection) (int, error) {
if err := r.authorize(ctx, obj.ParentID, probo.ActionWebhookConfigurationList); err != nil {
return 0, err
}
prb := r.ProboService(ctx, obj.ParentID.TenantID())
switch obj.Resolver.(type) {
case *organizationResolver:
count, err := prb.WebhookConfigurations.CountForOrganizationID(ctx, obj.ParentID)
if err != nil {
r.logger.ErrorCtx(ctx, "cannot count webhook configurations", log.Error(err))
return 0, gqlutils.Internal(ctx)
}
return count, nil
}
r.logger.ErrorCtx(ctx, "unsupported resolver for webhook configuration connection", log.String("resolver", fmt.Sprintf("%T", obj.Resolver)))
return 0, gqlutils.Internal(ctx)
}
// ApplicabilityStatement returns schema.ApplicabilityStatementResolver implementation.
func (r *Resolver) ApplicabilityStatement() schema.ApplicabilityStatementResolver {
return &applicabilityStatementResolver{r}
@@ -8751,6 +8922,16 @@ func (r *Resolver) VendorService() schema.VendorServiceResolver { return &vendor
// Viewer returns schema.ViewerResolver implementation.
func (r *Resolver) Viewer() schema.ViewerResolver { return &viewerResolver{r} }
// WebhookConfiguration returns schema.WebhookConfigurationResolver implementation.
func (r *Resolver) WebhookConfiguration() schema.WebhookConfigurationResolver {
return &webhookConfigurationResolver{r}
}
// WebhookConfigurationConnection returns schema.WebhookConfigurationConnectionResolver implementation.
func (r *Resolver) WebhookConfigurationConnection() schema.WebhookConfigurationConnectionResolver {
return &webhookConfigurationConnectionResolver{r}
}
type applicabilityStatementResolver struct{ *Resolver }
type applicabilityStatementConnectionResolver struct{ *Resolver }
type assetResolver struct{ *Resolver }
@@ -8823,3 +9004,5 @@ type vendorDataPrivacyAgreementResolver struct{ *Resolver }
type vendorRiskAssessmentResolver struct{ *Resolver }
type vendorServiceResolver struct{ *Resolver }
type viewerResolver struct{ *Resolver }
type webhookConfigurationResolver struct{ *Resolver }
type webhookConfigurationConnectionResolver struct{ *Resolver }

153
pkg/webhook/data.go Normal file
View File

@@ -0,0 +1,153 @@
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package webhook
import (
"context"
"encoding"
"encoding/json"
"fmt"
"reflect"
"strings"
"time"
"go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/coredata"
"go.probo.inc/probo/pkg/gid"
)
var (
jsonMarshalerType = reflect.TypeOf((*json.Marshaler)(nil)).Elem()
textMarshalerType = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem()
)
func InsertEvent(
ctx context.Context,
conn pg.Conn,
scope coredata.Scoper,
organizationID gid.GID,
eventType coredata.WebhookEventType,
data any,
) error {
var configs coredata.WebhookConfigurations
exists, err := configs.ExistsByOrganizationIDAndEventType(ctx, conn, scope, organizationID, eventType)
if err != nil {
return fmt.Errorf("cannot check webhook configurations: %w", err)
}
if !exists {
return nil
}
raw, err := MarshalData(data)
if err != nil {
return fmt.Errorf("cannot marshal webhook event data: %w", err)
}
event := &coredata.WebhookEvent{
ID: gid.New(scope.GetTenantID(), coredata.WebhookEventEntityType),
OrganizationID: organizationID,
EventType: eventType,
Status: coredata.WebhookEventStatusPending,
Data: raw,
CreatedAt: time.Now(),
}
if err = event.Insert(ctx, conn, scope); err != nil {
return fmt.Errorf("cannot insert webhook event: %w", err)
}
return nil
}
func MarshalData(v any) (json.RawMessage, error) {
raw, err := json.Marshal(v)
if err != nil {
return nil, fmt.Errorf("cannot marshal webhook data: %w", err)
}
var m map[string]any
if err := json.Unmarshal(raw, &m); err != nil {
return nil, fmt.Errorf("cannot unmarshal webhook data: %w", err)
}
for _, key := range nestedFieldKeys(v) {
delete(m, key)
}
delete(m, "permission")
data, err := json.Marshal(m)
if err != nil {
return nil, fmt.Errorf("cannot re-marshal webhook data: %w", err)
}
return data, nil
}
func nestedFieldKeys(v any) []string {
t := reflect.TypeOf(v)
for t.Kind() == reflect.Pointer {
t = t.Elem()
}
if t.Kind() != reflect.Struct {
return nil
}
var keys []string
for i := range t.NumField() {
field := t.Field(i)
tag := field.Tag.Get("json")
if tag == "" || tag == "-" {
continue
}
jsonKey, _, _ := strings.Cut(tag, ",")
if isNestedType(field.Type) {
keys = append(keys, jsonKey)
}
}
return keys
}
func isNestedType(t reflect.Type) bool {
for t.Kind() == reflect.Pointer {
t = t.Elem()
}
if t.Kind() == reflect.Slice {
return isNestedType(t.Elem())
}
if t.Kind() != reflect.Struct {
return false
}
ptrType := reflect.PointerTo(t)
if t.Implements(jsonMarshalerType) || ptrType.Implements(jsonMarshalerType) {
return false
}
if t.Implements(textMarshalerType) || ptrType.Implements(textMarshalerType) {
return false
}
return true
}

352
pkg/webhook/sender.go Normal file
View File

@@ -0,0 +1,352 @@
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package webhook
import (
"bytes"
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strconv"
"sync"
"time"
"go.gearno.de/kit/httpclient"
"go.gearno.de/kit/log"
"go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/coredata"
"go.probo.inc/probo/pkg/crypto/cipher"
"go.probo.inc/probo/pkg/gid"
)
type (
Sender struct {
pg *pg.Client
logger *log.Logger
httpClient *http.Client
encryptionKey cipher.EncryptionKey
cache sync.Map
interval time.Duration
timeout time.Duration
}
Config struct {
Interval time.Duration
Timeout time.Duration
EncryptionKey cipher.EncryptionKey
}
)
const maxResponseBodySize = 64 * 1024 // 64KB
func NewSender(pg *pg.Client, logger *log.Logger, cfg Config) *Sender {
if cfg.Interval <= 0 {
cfg.Interval = 5 * time.Second
}
if cfg.Timeout <= 0 {
cfg.Timeout = 30 * time.Second
}
return &Sender{
pg: pg,
logger: logger,
httpClient: httpclient.DefaultPooledClient(httpclient.WithLogger(logger)),
encryptionKey: cfg.EncryptionKey,
interval: cfg.Interval,
timeout: cfg.Timeout,
}
}
func (s *Sender) Run(ctx context.Context) error {
for {
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(s.interval):
if err := s.processEvents(ctx); err != nil {
s.logger.ErrorCtx(ctx, "cannot process webhook events", log.Error(err))
}
}
}
}
func (s *Sender) processEvents(ctx context.Context) error {
for {
event, err := s.claimNextEvent(ctx)
if err != nil {
if errors.Is(err, coredata.ErrResourceNotFound) {
return nil
}
return err
}
s.processEvent(ctx, event)
}
}
func (s *Sender) claimNextEvent(ctx context.Context) (*coredata.WebhookEvent, error) {
var event coredata.WebhookEvent
err := s.pg.WithTx(ctx, func(tx pg.Conn) error {
if err := event.LoadNextPendingForUpdate(ctx, tx); err != nil {
return err
}
scope := coredata.NewScopeFromObjectID(event.ID)
event.Status = coredata.WebhookEventStatusProcessing
if err := event.UpdateStatus(ctx, tx, scope); err != nil {
return fmt.Errorf("cannot update webhook event to processing: %w", err)
}
return nil
})
if err != nil {
return nil, err
}
return &event, nil
}
func (s *Sender) processEvent(ctx context.Context, event *coredata.WebhookEvent) {
scope := coredata.NewScopeFromObjectID(event.ID)
var configs coredata.WebhookConfigurations
err := s.pg.WithConn(ctx, func(conn pg.Conn) error {
return configs.LoadMatchingByOrganizationIDAndEventType(
ctx, conn, scope, event.OrganizationID, event.EventType,
)
})
if err != nil {
s.logger.ErrorCtx(ctx, "cannot load matching webhook configurations",
log.Error(err),
log.String("event_id", event.ID.String()),
)
return
}
for _, config := range configs {
s.deliverToConfiguration(ctx, event, config, scope)
}
now := time.Now()
event.Status = coredata.WebhookEventStatusDelivered
event.ProcessedAt = &now
err = s.pg.WithConn(ctx, func(conn pg.Conn) error {
return event.UpdateStatus(ctx, conn, scope)
})
if err != nil {
s.logger.ErrorCtx(ctx, "cannot update webhook event to delivered",
log.Error(err),
log.String("event_id", event.ID.String()),
)
}
}
func (s *Sender) deliverToConfiguration(
ctx context.Context,
event *coredata.WebhookEvent,
config *coredata.WebhookConfiguration,
scope coredata.Scoper,
) {
callID := gid.New(event.ID.TenantID(), coredata.WebhookCallEntityType)
signingSecret, err := s.getSigningSecret(config.ID.String(), config.EncryptedSigningSecret)
if err != nil {
s.logger.ErrorCtx(ctx, "cannot get signing secret",
log.Error(err),
log.String("event_id", event.ID.String()),
log.String("configuration_id", config.ID.String()),
)
s.recordCall(ctx, callID, event, config, scope, coredata.WebhookCallStatusFailed, nil)
return
}
response, sendErr := s.doHTTPCall(ctx, callID, config.EndpointURL, event, config.ID, signingSecret)
callStatus := coredata.WebhookCallStatusSucceeded
if sendErr != nil {
callStatus = coredata.WebhookCallStatusFailed
s.logger.ErrorCtx(ctx, "error delivering webhook event",
log.Error(sendErr),
log.String("event_id", event.ID.String()),
log.String("endpoint_url", config.EndpointURL),
)
}
s.recordCall(ctx, callID, event, config, scope, callStatus, response)
}
func (s *Sender) getSigningSecret(webhookConfigurationID string, encryptedSigningSecret []byte) (string, error) {
if cached, ok := s.cache.Load(webhookConfigurationID); ok {
return cached.(string), nil
}
plaintext, err := cipher.Decrypt(encryptedSigningSecret, s.encryptionKey)
if err != nil {
return "", fmt.Errorf("cannot decrypt signing secret: %w", err)
}
signingSecret := string(plaintext)
s.cache.Store(webhookConfigurationID, signingSecret)
return signingSecret, nil
}
func (s *Sender) doHTTPCall(
ctx context.Context,
callID gid.GID,
endpointURL string,
event *coredata.WebhookEvent,
configurationID gid.GID,
signingSecret string,
) (json.RawMessage, error) {
payload := map[string]any{
"eventId": event.ID.String(),
"callId": callID.String(),
"configurationId": configurationID.String(),
"eventType": event.EventType.String(),
"createdAt": event.CreatedAt,
"data": event.Data,
}
body, err := json.Marshal(payload)
if err != nil {
return nil, fmt.Errorf("cannot marshal webhook payload: %w", err)
}
reqCtx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
req, err := http.NewRequestWithContext(reqCtx, http.MethodPost, endpointURL, bytes.NewReader(body))
if err != nil {
return nil, fmt.Errorf("cannot create request: %w", err)
}
timestamp := strconv.FormatInt(time.Now().Unix(), 10)
signature := computeSignature(signingSecret, timestamp, body)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Probo-Webhook-Event", event.EventType.String())
req.Header.Set("X-Probo-Webhook-Timestamp", timestamp)
req.Header.Set("X-Probo-Webhook-Signature", signature)
resp, err := s.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("cannot send request: %w", err)
}
defer func() { _ = resp.Body.Close() }()
respBody, _ := io.ReadAll(io.LimitReader(resp.Body, maxResponseBodySize))
response := buildResponseJSON(resp, respBody)
switch resp.StatusCode {
case http.StatusOK,
http.StatusCreated,
http.StatusAccepted,
http.StatusNoContent:
return response, nil
default:
return response, fmt.Errorf("webhook endpoint returned status %d", resp.StatusCode)
}
}
func (s *Sender) recordCall(
ctx context.Context,
callID gid.GID,
event *coredata.WebhookEvent,
config *coredata.WebhookConfiguration,
scope coredata.Scoper,
status coredata.WebhookCallStatus,
response json.RawMessage,
) {
call := coredata.WebhookCall{
ID: callID,
WebhookEventID: event.ID,
WebhookConfigurationID: config.ID,
EndpointURL: config.EndpointURL,
Status: status,
Response: response,
CreatedAt: time.Now(),
}
err := s.pg.WithConn(ctx, func(conn pg.Conn) error {
return call.Insert(ctx, conn, scope)
})
if err != nil {
s.logger.ErrorCtx(ctx, "cannot insert webhook call",
log.Error(err),
log.String("event_id", event.ID.String()),
log.String("configuration_id", config.ID.String()),
)
}
}
func buildResponseJSON(resp *http.Response, body []byte) json.RawMessage {
headers := make(map[string]any, len(resp.Header))
for k, v := range resp.Header {
if len(v) == 1 {
headers[k] = v[0]
} else {
headers[k] = v
}
}
var bodyValue any
if json.Valid(body) {
bodyValue = json.RawMessage(body)
} else {
bodyValue = string(body)
}
respObj := map[string]any{
"proto": resp.Proto,
"status_code": resp.StatusCode,
"headers": headers,
"body": bodyValue,
}
if len(resp.Trailer) > 0 {
trailers := make(map[string]any, len(resp.Trailer))
for k, v := range resp.Trailer {
if len(v) == 1 {
trailers[k] = v[0]
} else {
trailers[k] = v
}
}
respObj["trailers"] = trailers
}
data, _ := json.Marshal(respObj)
return data
}
func computeSignature(signingSecret, timestamp string, body []byte) string {
h := hmac.New(sha256.New, []byte(signingSecret))
_, _ = fmt.Fprintf(h, "%s:%s", timestamp, body)
return hex.EncodeToString(h.Sum(nil))
}