Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
✨ Add webhooks settings page (#3329)
Luke Vella0d748580dd94
diff --git a/apps/web/.env.test b/apps/web/.env.testindex c1e7953e4..b27f0fabd 100644--- a/apps/web/.env.test+++ b/apps/web/.env.test@@ -17,3 +17,4 @@ SMTP_PORT=1025SMTP_REJECT_UNAUTHORIZED=falseWEBHOOK_ALLOW_PRIVATE_URLS=true+WEBHOOKS_ENABLED=truediff --git a/apps/web/public/locales/en/app.json b/apps/web/public/locales/en/app.jsonindex 90863eb41..c2a073621 100644--- a/apps/web/public/locales/en/app.json+++ b/apps/web/public/locales/en/app.json@@ -27,6 +27,8 @@"activity": "Activity","addComment": "Add comment","addDescription": "Add description",+ "addEndpoint": "Add endpoint",+ "addEndpointDescription": "Send a signed request to your server whenever one of these events happens","addLicenseKey": "Add license key","addParticipant": "Add participant","address": "Address",@@ -34,6 +36,7 @@"addSeats": "{count, plural, one {Add # seat} other {Add # seats}}","addTimeOption": "Add time option","addToCalendar": "Add to calendar",+ "addWebhook": "Add webhook","admin": "Admin","adminAccessRequired": "Administrator access required","adminAccessRequiredDescription": "You need administrator access to view this page.",@@ -233,6 +236,8 @@"deleteAccountUpcomingEvents": "{count, plural, one {# upcoming event} other {# upcoming events}}","deleteDate": "Delete date","deletedSpaceSuccess": "Space has been permanently deleted",+ "deleteEndpoint": "Delete endpoint",+ "deleteEndpointConfirmation": "Are you sure you want to delete {url}? Rallly will stop sending events to it immediately.","deleteEventTypeDescription": "<b>{name}</b> will be hidden from creation pickers. This cannot be undone.","deleteEventTypeError": "Failed to delete event type","deleteEventTypeTitle": "Delete event type?",@@ -300,6 +305,10 @@"emailPlaceholder": "[email protected]","enabled": "Enabled","endOfList": "You've reached the end of the list",+ "endpointAdded": "Endpoint added",+ "endpointAddedDescription": "Copy your signing secret now. You won't be able to see it again.",+ "endpointDeleted": "Endpoint deleted",+ "endpointUrl": "Endpoint URL","errorBackToHome": "Back to home","errorDescription": "An unexpected error occurred. Please try again or visit one of the pages below.","errorLabel": "Error",@@ -563,6 +572,7 @@"noChanges": "No changes","noDatesSelected": "No dates selected","noDatesSelectedDescription": "Click on a date to add a time slot",+ "noDeliveriesYet": "No deliveries yet","noKeepCurrentTimezone": "No, keep the current time zone","noLicenseKey": "No license key found","noLicenseKeyDescription": "This instance doesn’t have a license key yet.",@@ -622,6 +632,8 @@"noUsers": "No users found","noUsersDescription": "Try adjusting your search","noVotes": "No one has voted for this option",+ "noWebhooks": "No endpoints found",+ "noWebhooksDescription": "Add an endpoint to be notified when your polls change","oidcAutoSignInDescription": "You are being redirected to the login page...","openPollCount": "{count, plural, other {# open}}","optional": "(optional)",@@ -690,6 +702,7 @@"planProDescription": "For professionals and power users","planRenewsOn": "Renews on {date}","planResumedToast": "Your plan will renew",+ "poll": "Poll","pollAutoClosedBadge": "Automatically closed","pollAutoClosedDescription": "This poll was closed automatically because all of its dates have passed. No more responses are being accepted.","pollAutoClosedTooltip": "This poll was closed automatically because all of its dates have passed. You can reopen it at any time.",@@ -862,6 +875,7 @@"shrink": "Shrink","signedInAs": "You're signed in as:","signIn": "Sign in",+ "signingSecret": "Signing secret","signOut": "Sign out","skipToContent": "Skip to main content","space": "Space",@@ -976,6 +990,21 @@"voteSummaryAvailable": "{availableCount} of {total} available","voteSummaryIfNeedBe": "{count} if need be","voteSummaryNotAvailable": "You're not available",+ "webhookDocs": "Webhook docs",+ "webhookEventCount": "{count, plural, one {# event} other {# events}}",+ "webhookEventPollClosed": "A poll stopped accepting responses",+ "webhookEventPollReopened": "A closed poll started accepting responses again",+ "webhookEventPollScheduled": "A poll was booked on one of its options",+ "webhookLastDeliveryFailed": "Failed {date}",+ "webhookLastDeliveryFailedWithStatus": "Failed {date} with {status}",+ "webhookLastDeliverySucceeded": "Delivered {date}",+ "webhookLimitReached": "You've reached the maximum number of endpoints. Delete one before adding another.",+ "webhooks": "Webhooks",+ "webhooksDescription": "Send poll events to your own endpoints",+ "webhookSecretSecurityWarning": "Store this secret securely. Use it to verify that deliveries came from Rallly.",+ "webhooksSettingsDescription": "Send poll events to your own endpoints with signed, retried deliveries.",+ "webhooksUpgradeDescription": "Get notified at your own endpoint when a poll is closed, reopened or scheduled. Included with Pro.",+ "webhooksUpgradeTitle": "Upgrade for webhooks","weekView": "Week view","whiteLabelAddon": "White Label Add-on","whiteLabelAddonDescription": "This add-on allows you to brand Rallly with your own logo and colors.",diff --git a/apps/web/src/app/[locale]/(space)/settings/components/sidebar.tsx b/apps/web/src/app/[locale]/(space)/settings/components/sidebar.tsxindex ac04c1e1a..25bb6bb2b 100644--- a/apps/web/src/app/[locale]/(space)/settings/components/sidebar.tsx+++ b/apps/web/src/app/[locale]/(space)/settings/components/sidebar.tsx@@ -22,6 +22,7 @@ import {ShapesIcon,UserIcon,UsersIcon,+ WebhookIcon,} from "lucide-react";import { usePathname } from "next/navigation";import type React from "react";@@ -190,9 +191,11 @@ export function DeveloperSidebarMenu() {const isSpaceOwner = space.ownerId === user.id;const pathname = usePathname();const isApiEnabled = useFeatureFlag("api");+ const isWebhooksEnabled = useFeatureFlag("webhooks");- // Owner only: a member has no self-serve path to API keys. A free space- // sees the entry with a Pro badge; the page itself offers the upgrade.+ // Owner only: a member has no self-serve path to the developer surface. A+ // free space sees the entries with a Pro badge; each page offers the+ // upgrade.if (!isSpaceOwner || !isApiEnabled) {return null;}@@ -219,6 +222,23 @@ export function DeveloperSidebarMenu() {{space.tier !== "pro" ? <ProBadge className="ml-auto" /> : null}</SidebarMenuButton></SidebarMenuItem>+ {isWebhooksEnabled ? (+ <SidebarMenuItem>+ <SidebarMenuButton+ render={+ <HoverPrefetchLink+ href="/settings/webhooks"+ className="flex items-center gap-x-2"+ />+ }+ isActive={pathname.startsWith("/settings/webhooks")}+ >+ <WebhookIcon />+ <Trans i18nKey="webhooks" defaults="Webhooks" />+ {space.tier !== "pro" ? <ProBadge className="ml-auto" /> : null}+ </SidebarMenuButton>+ </SidebarMenuItem>+ ) : null}</SidebarMenu></SidebarGroupContent></SidebarGroup>diff --git a/apps/web/src/app/[locale]/(space)/settings/webhooks/page.tsx b/apps/web/src/app/[locale]/(space)/settings/webhooks/page.tsxnew file mode 100644index 000000000..1809b4cd8--- /dev/null+++ b/apps/web/src/app/[locale]/(space)/settings/webhooks/page.tsx@@ -0,0 +1,88 @@+import type { Metadata } from "next";+import { notFound } from "next/navigation";+import {+ PageSection,+ PageSectionContent,+ PageSectionGroup,+} from "@/components/page-layout";+import {+ SettingsPage,+ SettingsPageAction,+ SettingsPageContent,+ SettingsPageDescription,+ SettingsPageHeader,+ SettingsPageTitle,+} from "@/components/settings-layout";+import { CreateWebhookButton } from "@/features/webhook/components/create-webhook-button";+import { WebhooksList } from "@/features/webhook/components/webhooks-list";+import { WebhooksUpgrade } from "@/features/webhook/components/webhooks-upgrade";+import {+ loadSpaceWebhooks,+ loadWebhookAccess,+} from "@/features/webhook/loaders";+import { Trans } from "@/i18n/client";+import { getTranslation } from "@/i18n/server";++export default async function WebhooksSettingsPage() {+ const access = await loadWebhookAccess();++ // Only a space that could fix this by paying gets the upgrade screen;+ // every other denial (self-hosted, not the owner) is a 404, since a pay+ // wall would offer something buying Pro would not deliver.+ if (access === "denied") {+ notFound();+ }++ const enabled = access === "allowed";++ return (+ <SettingsPage>+ <SettingsPageHeader>+ <SettingsPageTitle>+ <Trans i18nKey="webhooks" defaults="Webhooks" />+ </SettingsPageTitle>+ <SettingsPageDescription>+ <Trans+ i18nKey="webhooksDescription"+ defaults="Send poll events to your own endpoints"+ />+ </SettingsPageDescription>+ {enabled ? (+ <SettingsPageAction>+ <CreateWebhookButton />+ </SettingsPageAction>+ ) : null}+ </SettingsPageHeader>+ <SettingsPageContent>+ {enabled ? <WebhooksContent /> : <WebhooksUpgrade />}+ </SettingsPageContent>+ </SettingsPage>+ );+}++async function WebhooksContent() {+ const webhooks = await loadSpaceWebhooks();++ return (+ <PageSectionGroup>+ <PageSection>+ <PageSectionContent>+ <WebhooksList webhooks={webhooks} />+ </PageSectionContent>+ </PageSection>+ </PageSectionGroup>+ );+}++export async function generateMetadata(): Promise<Metadata> {+ const { t } = await getTranslation();+ return {+ title: t("webhooks", {+ defaultValue: "Webhooks",+ }),+ description: t("webhooksSettingsDescription", {+ defaultValue:+ "Send poll events to your own endpoints with signed, retried deliveries.",+ }),+ };+}diff --git a/apps/web/src/features/billing/client.tsx b/apps/web/src/features/billing/client.tsxindex 67b499d0b..e6a07567b 100644--- a/apps/web/src/features/billing/client.tsx+++ b/apps/web/src/features/billing/client.tsx@@ -40,6 +40,7 @@ export type PayWallTrigger = {| "manage-poll"| "custom-branding"| "api-keys"+ | "webhooks"| "space-members"| "space-collaboration"| "billing-settings"diff --git a/apps/web/src/features/webhook/ability.ts b/apps/web/src/features/webhook/ability.tsnew file mode 100644index 000000000..cfc909800--- /dev/null+++ b/apps/web/src/features/webhook/ability.ts@@ -0,0 +1,24 @@+import type { PureAbility } from "@casl/ability";+import { AbilityBuilder } from "@casl/ability";+import type { PrismaQuery, Subjects } from "@casl/prisma";+import { createPrismaAbility } from "@casl/prisma";++type Action = "update" | "delete";+type Subject = Subjects<{+ Webhook: {+ spaceId: string;+ };+}>;++export type WebhookAbility = PureAbility<[Action, Subject], PrismaQuery>;++export function defineAbilityForWebhooks(context: { spaceId: string }) {+ const { can, build } = new AbilityBuilder<WebhookAbility>(+ createPrismaAbility,+ );++ // An endpoint can only be managed from within the space that owns it.+ can(["update", "delete"], "Webhook", { spaceId: context.spaceId });++ return build();+}diff --git a/apps/web/src/features/webhook/actions.ts b/apps/web/src/features/webhook/actions.tsnew file mode 100644index 000000000..6e1a24fdf--- /dev/null+++ b/apps/web/src/features/webhook/actions.ts@@ -0,0 +1,110 @@+"use server";++import { getActiveSpaceForUser } from "@/features/space/data";+import { getCurrentUser } from "@/features/user/loaders";+import { AppError } from "@/lib/errors/app-error";+import { track } from "@/lib/posthog";+import { authActionClient } from "@/lib/safe-action/server";+import { getWebhookAccess } from "./data";+import { createWebhook, deleteWebhook, setWebhookEnabled } from "./mutations";+import {+ createWebhookInputSchema,+ deleteWebhookSchema,+ setWebhookEnabledSchema,+} from "./schema";++// The UI never offers these actions to users without webhook access, so a+// failed gate is unexpected here — throw for the global error handler.+async function requireWebhookAccess() {+ const user = await getCurrentUser();++ if (!user) {+ throw new AppError({+ code: "UNAUTHORIZED",+ message: "You are not authenticated.",+ });+ }++ const space = await getActiveSpaceForUser(user.id);++ if (!space) {+ throw new AppError({+ code: "NOT_FOUND",+ message: "Space not found",+ });+ }++ if (getWebhookAccess(user, space) !== "allowed") {+ throw new AppError({+ code: "FORBIDDEN",+ message: "Webhooks are not enabled for this user or space",+ });+ }++ return { user, space };+}++export const createWebhookAction = authActionClient+ .metadata({ actionName: "create_webhook" })+ .inputSchema(createWebhookInputSchema)+ .action(async ({ ctx, parsedInput }) => {+ const { space } = await requireWebhookAccess();++ const result = await createWebhook({+ spaceId: space.id,+ url: parsedInput.url,+ events: parsedInput.events,+ });++ if (result.ok) {+ track(ctx.user, {+ event: "developer:webhook_create",+ groups: {+ space: space.id,+ },+ });+ }++ return result;+ });++export const setWebhookEnabledAction = authActionClient+ .metadata({ actionName: "set_webhook_enabled" })+ .inputSchema(setWebhookEnabledSchema)+ .action(async ({ ctx, parsedInput }) => {+ const { space } = await requireWebhookAccess();++ await setWebhookEnabled({+ spaceId: space.id,+ webhookId: parsedInput.webhookId,+ enabled: parsedInput.enabled,+ });++ track(ctx.user, {+ event: parsedInput.enabled+ ? "developer:webhook_enable"+ : "developer:webhook_disable",+ groups: {+ space: space.id,+ },+ });+ });++export const deleteWebhookAction = authActionClient+ .metadata({ actionName: "delete_webhook" })+ .inputSchema(deleteWebhookSchema)+ .action(async ({ ctx, parsedInput }) => {+ const { space } = await requireWebhookAccess();++ await deleteWebhook({+ spaceId: space.id,+ webhookId: parsedInput.webhookId,+ });++ track(ctx.user, {+ event: "developer:webhook_delete",+ groups: {+ space: space.id,+ },+ });+ });diff --git a/apps/web/src/features/webhook/components/create-webhook-button.tsx b/apps/web/src/features/webhook/components/create-webhook-button.tsxnew file mode 100644index 000000000..954669d03--- /dev/null+++ b/apps/web/src/features/webhook/components/create-webhook-button.tsx@@ -0,0 +1,288 @@+"use client";++import { zodResolver } from "@hookform/resolvers/zod";+import { passwordManagerIgnoreProps } from "@rallly/ui";+import { Alert, AlertDescription } from "@rallly/ui/alert";+import { Button } from "@rallly/ui/button";+import { Checkbox } from "@rallly/ui/checkbox";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ useDialog,+} from "@rallly/ui/dialog";+import {+ Form,+ FormControl,+ FormField,+ FormItem,+ FormLabel,+ FormMessage,+} from "@rallly/ui/form";+import { Input } from "@rallly/ui/input";+import { toast } from "@rallly/ui/sonner";+import { AlertTriangleIcon, CheckIcon, CopyIcon, PlusIcon } from "lucide-react";+import React from "react";+import { useForm } from "react-hook-form";+import { useCopyToClipboard } from "react-use";+import { Trans, useTranslation } from "@/i18n/client";+import { useSafeAction } from "@/lib/safe-action/client";+import { createWebhookAction } from "../actions";+import { createWebhookInputSchema, WEBHOOK_EVENT_TYPES } from "../schema";+import { groupWebhookEventTypes } from "../utils";+import { WebhookEventGroupLabel } from "./webhook-event-group-label";+import { WebhookEventLabel } from "./webhook-event-label";++export function CreateWebhookButton() {+ const { t } = useTranslation();+ const dialog = useDialog();+ const [createdSecret, setCreatedSecret] = React.useState<string | null>(null);+ const createWebhook = useSafeAction(createWebhookAction);+ const [, copy] = useCopyToClipboard();+ const [didCopy, setDidCopy] = React.useState(false);++ const form = useForm({+ resolver: zodResolver(createWebhookInputSchema),+ defaultValues: {+ url: "",+ events: [...WEBHOOK_EVENT_TYPES],+ },+ });++ const handleClose = () => {+ dialog.dismiss();+ setCreatedSecret(null);+ form.reset();+ };++ const handleCopy = () => {+ if (createdSecret) {+ copy(createdSecret);+ setDidCopy(true);+ setTimeout(() => setDidCopy(false), 2000);+ toast.success(+ t("copiedToClipboard", {+ defaultValue: "Copied to clipboard",+ }),+ );+ }+ };++ return (+ <>+ <Button onClick={() => dialog.trigger()}>+ <PlusIcon data-icon="inline-start" />+ <Trans i18nKey="addEndpoint" defaults="Add endpoint" />+ </Button>+ <Dialog {...dialog.dialogProps} onOpenChange={handleClose}>+ <DialogContent>+ {createdSecret ? (+ <>+ <DialogHeader>+ <DialogTitle>+ <Trans i18nKey="endpointAdded" defaults="Endpoint added" />+ </DialogTitle>+ <DialogDescription>+ <Trans+ i18nKey="endpointAddedDescription"+ defaults="Copy your signing secret now. You won't be able to see it again."+ />+ </DialogDescription>+ </DialogHeader>+ <div className="space-y-4">+ <Alert variant="warning">+ <AlertTriangleIcon />+ <AlertDescription>+ <Trans+ i18nKey="webhookSecretSecurityWarning"+ defaults="Store this secret securely. Use it to verify that deliveries came from Rallly."+ />+ </AlertDescription>+ </Alert>+ <div className="space-y-2">+ <label+ htmlFor="created-webhook-secret"+ className="font-medium text-sm"+ >+ <Trans i18nKey="signingSecret" defaults="Signing secret" />+ </label>+ <div className="flex gap-2">+ <Input+ id="created-webhook-secret"+ value={createdSecret}+ readOnly+ className="font-mono text-sm"+ {...passwordManagerIgnoreProps}+ />+ <Button+ aria-label={t("copy", { defaultValue: "Copy" })}+ variant="ghost"+ size="icon"+ onClick={handleCopy}+ type="button"+ >+ {didCopy ? <CheckIcon /> : <CopyIcon />}+ </Button>+ </div>+ </div>+ </div>+ <DialogFooter>+ <Button onClick={handleClose}>+ <Trans i18nKey="done" defaults="Done" />+ </Button>+ </DialogFooter>+ </>+ ) : (+ <>+ <DialogHeader>+ <DialogTitle>+ <Trans i18nKey="addEndpoint" defaults="Add endpoint" />+ </DialogTitle>+ <DialogDescription>+ <Trans+ i18nKey="addEndpointDescription"+ defaults="Send a signed request to your server whenever one of these events happens"+ />+ </DialogDescription>+ </DialogHeader>+ <Form {...form}>+ <form+ onSubmit={form.handleSubmit(async (data) => {+ const result = await createWebhook.executeAsync(data);+ if (result?.data?.ok) {+ setCreatedSecret(result.data.secret);+ form.reset();+ } else if (+ result?.data?.reason === "max_webhooks_exceeded"+ ) {+ toast.error(+ t("webhookLimitReached", {+ defaultValue:+ "You've reached the maximum number of endpoints. Delete one before adding another.",+ }),+ );+ }+ })}+ >+ <div className="space-y-4">+ <FormField+ control={form.control}+ name="url"+ render={({ field }) => (+ <FormItem>+ <FormLabel>+ <Trans+ i18nKey="endpointUrl"+ defaults="Endpoint URL"+ />+ </FormLabel>+ <FormControl>+ <Input+ {...field}+ type="url"+ inputMode="url"+ placeholder="https://"+ autoFocus+ {...passwordManagerIgnoreProps}+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ <FormField+ control={form.control}+ name="events"+ render={({ field }) => (+ // gap-1 is sized for a label over a single input; a+ // label over a grouped list needs more air.+ <FormItem className="gap-2">+ <FormLabel>+ <Trans i18nKey="events" defaults="Events" />+ </FormLabel>+ {/* Three spacing levels, largest to smallest:+ between groups, between rows in a group, and+ between an event and its description. */}+ <div className="space-y-5">+ {groupWebhookEventTypes(WEBHOOK_EVENT_TYPES).map(+ ([resource, eventTypes]) => (+ <div key={resource}>+ <div className="mb-2 font-medium text-sm">+ <WebhookEventGroupLabel+ resource={resource}+ />+ </div>+ <div className="space-y-3">+ {eventTypes.map((eventType) => {+ const checkboxId = `webhook-event-${eventType}`;+ return (+ <div+ key={eventType}+ className="flex items-start gap-2.5"+ >+ <Checkbox+ id={checkboxId}+ className="mt-0.5"+ checked={field.value.includes(+ eventType,+ )}+ onCheckedChange={(checked) => {+ field.onChange(+ checked+ ? [...field.value, eventType]+ : field.value.filter(+ (value) =>+ value !== eventType,+ ),+ );+ }}+ onBlur={field.onBlur}+ />+ <label+ htmlFor={checkboxId}+ className="cursor-pointer"+ >+ <span className="block font-medium font-mono text-sm leading-none">+ {eventType}+ </span>+ <span className="mt-1 block text-muted-foreground text-xs leading-snug">+ <WebhookEventLabel+ eventType={eventType}+ />+ </span>+ </label>+ </div>+ );+ })}+ </div>+ </div>+ ),+ )}+ </div>+ <FormMessage />+ </FormItem>+ )}+ />+ </div>+ <DialogFooter className="mt-6">+ <Button+ variant="primary"+ type="submit"+ disabled={createWebhook.isExecuting}+ loading={createWebhook.isExecuting}+ >+ <Trans i18nKey="addWebhook" defaults="Add webhook" />+ </Button>+ </DialogFooter>+ </form>+ </Form>+ </>+ )}+ </DialogContent>+ </Dialog>+ </>+ );+}diff --git a/apps/web/src/features/webhook/components/webhook-actions.tsx b/apps/web/src/features/webhook/components/webhook-actions.tsxnew file mode 100644index 000000000..658ef5c36--- /dev/null+++ b/apps/web/src/features/webhook/components/webhook-actions.tsx@@ -0,0 +1,115 @@+"use client";++import { Button } from "@rallly/ui/button";+import {+ Dialog,+ DialogClose,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ useDialog,+} from "@rallly/ui/dialog";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@rallly/ui/dropdown-menu";+import { toast } from "@rallly/ui/sonner";+import { Switch } from "@rallly/ui/switch";+import { MoreVerticalIcon, Trash2Icon } from "lucide-react";+import { Trans, useTranslation } from "@/i18n/client";+import { useSafeAction } from "@/lib/safe-action/client";+import { deleteWebhookAction, setWebhookEnabledAction } from "../actions";++export function WebhookActions({+ webhookId,+ webhookUrl,+ enabled,+}: {+ webhookId: string;+ webhookUrl: string;+ enabled: boolean;+}) {+ const { t } = useTranslation();+ const deleteDialog = useDialog();++ const setEnabled = useSafeAction(setWebhookEnabledAction);+ const deleteWebhook = useSafeAction(deleteWebhookAction, {+ onSuccess: () => {+ toast.success(t("endpointDeleted", { defaultValue: "Endpoint deleted" }));+ },+ onSettled: () => {+ deleteDialog.dismiss();+ },+ });++ return (+ <>+ <Switch+ checked={enabled}+ disabled={setEnabled.isExecuting}+ aria-label={t("enabled", { defaultValue: "Enabled" })}+ onCheckedChange={(checked) => {+ setEnabled.execute({ webhookId, enabled: checked });+ }}+ />+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button+ aria-label={t("moreOptions", { defaultValue: "More options" })}+ variant="ghost"+ size="icon"+ />+ }+ >+ <MoreVerticalIcon className="text-muted-foreground" />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuItem+ onClick={() => {+ deleteDialog.trigger();+ }}+ variant="destructive"+ >+ <Trash2Icon />+ <Trans i18nKey="delete" defaults="Delete" />+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ <Dialog {...deleteDialog.dialogProps}>+ <DialogContent size="sm">+ <DialogHeader>+ <DialogTitle>+ <Trans i18nKey="deleteEndpoint" defaults="Delete endpoint" />+ </DialogTitle>+ <DialogDescription>+ <Trans+ i18nKey="deleteEndpointConfirmation"+ defaults="Are you sure you want to delete {url}? Rallly will stop sending events to it immediately."+ values={{ url: webhookUrl }}+ />+ </DialogDescription>+ </DialogHeader>+ <DialogFooter>+ <Button+ variant="destructive"+ loading={deleteWebhook.isExecuting}+ onClick={() => {+ deleteWebhook.execute({ webhookId });+ }}+ >+ <Trans i18nKey="delete" defaults="Delete" />+ </Button>+ <DialogClose render={<Button />}>+ <Trans i18nKey="cancel" defaults="Cancel" />+ </DialogClose>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </>+ );+}diff --git a/apps/web/src/features/webhook/components/webhook-event-group-label.tsx b/apps/web/src/features/webhook/components/webhook-event-group-label.tsxnew file mode 100644index 000000000..91f70a478--- /dev/null+++ b/apps/web/src/features/webhook/components/webhook-event-group-label.tsx@@ -0,0 +1,19 @@+"use client";++import { Trans } from "@/i18n/client";+import type { WebhookEventResource } from "../utils";++/**+ * A switch rather than a lookup keyed by resource: i18n keys must be+ * literals so the scanner can find them.+ */+export function WebhookEventGroupLabel({+ resource,+}: {+ resource: WebhookEventResource;+}) {+ switch (resource) {+ case "poll":+ return <Trans i18nKey="poll" defaults="Poll" />;+ }+}diff --git a/apps/web/src/features/webhook/components/webhook-event-label.tsx b/apps/web/src/features/webhook/components/webhook-event-label.tsxnew file mode 100644index 000000000..a499eab65--- /dev/null+++ b/apps/web/src/features/webhook/components/webhook-event-label.tsx@@ -0,0 +1,38 @@+"use client";++import { Trans } from "@/i18n/client";+import type { WebhookEventType } from "../schema";++/**+ * A switch rather than a lookup keyed by event type: i18n keys must be+ * literals so the scanner can find them.+ */+export function WebhookEventLabel({+ eventType,+}: {+ eventType: WebhookEventType;+}) {+ switch (eventType) {+ case "poll.closed":+ return (+ <Trans+ i18nKey="webhookEventPollClosed"+ defaults="A poll stopped accepting responses"+ />+ );+ case "poll.reopened":+ return (+ <Trans+ i18nKey="webhookEventPollReopened"+ defaults="A closed poll started accepting responses again"+ />+ );+ case "poll.scheduled":+ return (+ <Trans+ i18nKey="webhookEventPollScheduled"+ defaults="A poll was booked on one of its options"+ />+ );+ }+}diff --git a/apps/web/src/features/webhook/components/webhook-last-delivery.tsx b/apps/web/src/features/webhook/components/webhook-last-delivery.tsxnew file mode 100644index 000000000..6258bce78--- /dev/null+++ b/apps/web/src/features/webhook/components/webhook-last-delivery.tsx@@ -0,0 +1,63 @@+"use client";++import { CircleCheckIcon, CircleXIcon } from "lucide-react";+import { Trans } from "@/i18n/client";+import { useDateTime } from "@/lib/datetime/client";++/**+ * Outcome of the endpoint's last attempted delivery. An icon and its own+ * words carry the state; the color only reinforces it.+ */+export function WebhookLastDelivery({+ delivery,+}: {+ delivery?: {+ status: "succeeded" | "failed" | "exhausted" | "pending" | "in_flight";+ lastResponseStatus: number | null;+ updatedAt: Date;+ };+}) {+ const { toRelativeTime } = useDateTime();++ if (!delivery) {+ return (+ <div className="text-muted-foreground text-sm">+ <Trans i18nKey="noDeliveriesYet" defaults="No deliveries yet" />+ </div>+ );+ }++ const when = toRelativeTime(delivery.updatedAt);++ if (delivery.status === "succeeded") {+ return (+ <div className="flex items-center gap-1.5 text-muted-foreground text-sm">+ <CircleCheckIcon className="size-4 shrink-0 text-green-600" />+ <Trans+ i18nKey="webhookLastDeliverySucceeded"+ defaults="Delivered {date}"+ values={{ date: when }}+ />+ </div>+ );+ }++ return (+ <div className="flex items-center gap-1.5 text-muted-foreground text-sm">+ <CircleXIcon className="size-4 shrink-0 text-destructive" />+ {delivery.lastResponseStatus ? (+ <Trans+ i18nKey="webhookLastDeliveryFailedWithStatus"+ defaults="Failed {date} with {status}"+ values={{ date: when, status: delivery.lastResponseStatus }}+ />+ ) : (+ <Trans+ i18nKey="webhookLastDeliveryFailed"+ defaults="Failed {date}"+ values={{ date: when }}+ />+ )}+ </div>+ );+}diff --git a/apps/web/src/features/webhook/components/webhooks-list.tsx b/apps/web/src/features/webhook/components/webhooks-list.tsxnew file mode 100644index 000000000..c977d0a5a--- /dev/null+++ b/apps/web/src/features/webhook/components/webhooks-list.tsx@@ -0,0 +1,71 @@+"use client";++import { WebhookIcon } from "lucide-react";+import {+ EmptyState,+ EmptyStateDescription,+ EmptyStateIcon,+ EmptyStateTitle,+} from "@/components/empty-state";+import { StackedList, StackedListItem } from "@/components/stacked-list";+import { Trans } from "@/i18n/client";+import type { getSpaceWebhooks } from "../data";+import { WebhookActions } from "./webhook-actions";+import { WebhookLastDelivery } from "./webhook-last-delivery";++type Webhook = Awaited<ReturnType<typeof getSpaceWebhooks>>[number];++export function WebhooksList({ webhooks }: { webhooks: Webhook[] }) {+ if (webhooks.length === 0) {+ return (+ <EmptyState>+ <EmptyStateIcon>+ <WebhookIcon />+ </EmptyStateIcon>+ <EmptyStateTitle>+ <Trans i18nKey="noWebhooks" defaults="No endpoints found" />+ </EmptyStateTitle>+ <EmptyStateDescription>+ <Trans+ i18nKey="noWebhooksDescription"+ defaults="Add an endpoint to be notified when your polls change"+ />+ </EmptyStateDescription>+ </EmptyState>+ );+ }++ return (+ <StackedList>+ {webhooks.map((webhook) => (+ <StackedListItem key={webhook.id}>+ <div className="flex min-w-0 flex-1 items-center gap-4">+ <div className="flex size-10 shrink-0 items-center justify-center rounded-lg border bg-card-accent">+ <WebhookIcon className="size-4 shrink-0 text-muted-foreground" />+ </div>+ <div className="min-w-0">+ {/* The switch is the enabled state; a badge repeating it would+ be two controls for one fact. */}+ <div className="truncate font-semibold text-sm">+ {webhook.url}+ </div>+ <div className="truncate text-muted-foreground text-sm">+ <Trans+ i18nKey="webhookEventCount"+ defaults="{count, plural, one {# event} other {# events}}"+ values={{ count: webhook.events.length }}+ />+ </div>+ </div>+ </div>+ <WebhookLastDelivery delivery={webhook.deliveries[0]} />+ <WebhookActions+ webhookId={webhook.id}+ webhookUrl={webhook.url}+ enabled={webhook.enabled}+ />+ </StackedListItem>+ ))}+ </StackedList>+ );+}diff --git a/apps/web/src/features/webhook/components/webhooks-upgrade.tsx b/apps/web/src/features/webhook/components/webhooks-upgrade.tsxnew file mode 100644index 000000000..1bfe23109--- /dev/null+++ b/apps/web/src/features/webhook/components/webhooks-upgrade.tsx@@ -0,0 +1,54 @@+"use client";++import { buttonVariants } from "@rallly/ui";+import { Button } from "@rallly/ui/button";+import { ArrowUpRightIcon, WebhookIcon } from "lucide-react";+import {+ EmptyState,+ EmptyStateDescription,+ EmptyStateFooter,+ EmptyStateIcon,+ EmptyStateTitle,+} from "@/components/empty-state";+import { Link } from "@/components/link";+import { showPayWall } from "@/features/billing/client";+import { Trans } from "@/i18n/client";+import { getWebhookDocsPath } from "../constants";++export function WebhooksUpgrade() {+ return (+ <EmptyState>+ <EmptyStateIcon>+ <WebhookIcon />+ </EmptyStateIcon>+ <EmptyStateTitle>+ <Trans i18nKey="webhooksUpgradeTitle" defaults="Upgrade for webhooks" />+ </EmptyStateTitle>+ <EmptyStateDescription>+ <Trans+ i18nKey="webhooksUpgradeDescription"+ defaults="Get notified at your own endpoint when a poll is closed, reopened or scheduled. Included with Pro."+ />+ </EmptyStateDescription>+ <EmptyStateFooter className="flex flex-wrap justify-center gap-2">+ <Button+ variant="primary"+ onClick={() => {+ showPayWall({ from: "webhooks" });+ }}+ >+ <Trans i18nKey="upgradeToPro" defaults="Upgrade to Pro" />+ </Button>+ <Link+ href={getWebhookDocsPath()}+ target="_blank"+ rel="noopener noreferrer"+ className={buttonVariants()}+ >+ <Trans i18nKey="webhookDocs" defaults="Webhook docs" />+ <ArrowUpRightIcon className="size-4" />+ </Link>+ </EmptyStateFooter>+ </EmptyState>+ );+}diff --git a/apps/web/src/features/webhook/constants.ts b/apps/web/src/features/webhook/constants.tsindex b5f7004a2..6b8f34358 100644--- a/apps/web/src/features/webhook/constants.ts+++ b/apps/web/src/features/webhook/constants.ts@@ -1,3 +1,13 @@+import { isSelfHosted } from "@/lib/constants";++/**+ * Webhooks ride on the API capability (cloud only) but stay behind their own+ * switch until the docs page that defines the payload contract is published.+ * Off by default, so production is dark until the switch is flipped.+ */+export const isWebhooksEnabled =+ !isSelfHosted && process.env.WEBHOOKS_ENABLED === "true";+/*** Retry schedule indexed by the number of attempts already made: after the* first failure wait 1 minute, after the second 5 minutes, and so on. A@@ -43,3 +53,53 @@ export const IN_FLIGHT_TIMEOUT_MS = 2 * 60_000;/** Exhausted deliveries in a row before the endpoint is disabled. */export const MAX_CONSECUTIVE_FAILURES = 20;++/**+ * Webhook reference in the docs site: event payloads, headers and how to+ * verify a signature. Same home as the API reference.+ */+export const getWebhookDocsPath = () =>+ "https://support.rallly.co/api-reference/webhooks";++/**+ * The payload contract deliveries are built against, sent both in the body+ * and as `X-Rallly-Webhook-Version`. Date-based rather than `v1`: webhooks+ * are called at an address the receiver owns, so there is no URL to version+ * on the way `/api/v1` does, and a date sidesteps deciding what counts as a+ * major bump.+ *+ * There is deliberately no per-endpoint pinning: with one version it would+ * be a column, a branch and a UI row all carrying the same value. The+ * envelope is additive-only instead — new fields, new event types and new+ * enum members keep this version, and receivers are documented to ignore+ * what they don't recognise.+ *+ * A change that could break a receiver (a renamed or removed field, a+ * changed shape) requires pinning to land first, in the same change:+ *+ * 1. nullable `version` on SpaceWebhook, defaulted to this constant at+ * creation and backfilled to the value below for existing rows — safe+ * because every endpoint created before that migration was, by+ * definition, built against it;+ * 2. `buildWebhookPayload` takes the endpoint's version and branches, so+ * existing endpoints keep the shape they were written for while new+ * ones default to the new version;+ * 3. an explicit upgrade action on an existing endpoint, keeping its URL+ * and signing secret. Without one, moving version means deleting and+ * recreating, which mints a new secret and forces a redeploy — so the+ * oldest integrations would stay pinned forever and every old branch+ * would have to be carried indefinitely;+ * 4. the settings list surfaces the version, which only earns its place+ * once endpoints genuinely differ.+ *+ * Note that an upgrade is never instantaneous: payloads are frozen at+ * fan-out, so already-queued deliveries carry the old shape while new ones+ * carry the new. That is why the version travels in the body and not only+ * in the header — a receiver has to branch per payload, not per deploy.+ *+ * That migration stays available only as long as this rule holds. Shipping+ * a breaking change *without* pinning is the one thing that forecloses it:+ * existing endpoints would then have no recorded version and no way to+ * reconstruct which contract they were written against.+ */+export const WEBHOOK_VERSION = "2026-09-20";diff --git a/apps/web/src/features/webhook/data.ts b/apps/web/src/features/webhook/data.tsindex a52345105..d305a8885 100644--- a/apps/web/src/features/webhook/data.ts+++ b/apps/web/src/features/webhook/data.ts@@ -1,12 +1,76 @@import "server-only";import { prisma } from "@rallly/database";+import type { SpaceTier } from "@/features/space/schema";+import type { AuthorizedSpaceId } from "@/features/space/types";+import { isFeatureEnabled } from "@/lib/feature-flags/server";import { WEBHOOK_ACTIVITY_TYPES } from "./utils";+export type WebhookAccess = "allowed" | "needs_upgrade" | "denied";++/**+ * Webhooks ride on the same capability as the rest of the developer surface:+ * a Pro capability of cloud hosted spaces, managed by the space owner.+ *+ * The three outcomes are distinguished because they need different+ * presentations: only a space whose *sole* missing condition is the tier can+ * fix this by paying, so only that case earns the upgrade screen. An+ * instance without the capability, or a member who could never manage+ * endpoints, must not be shown a pay wall for something buying Pro would not+ * give them.+ */+export function getWebhookAccess(+ user: { id: string },+ space: { tier: SpaceTier; ownerId: string },+): WebhookAccess {+ if (!isFeatureEnabled("webhooks") || space.ownerId !== user.id) {+ return "denied";+ }++ return space.tier === "pro" ? "allowed" : "needs_upgrade";+}++/**+ * A space's endpoints for the settings list. The last attempt's outcome comes+ * from the most recent delivery that was actually attempted, so an endpoint+ * with a queue of pending rows still shows the result the owner last saw.+ */+export async function getSpaceWebhooks({+ spaceId,+}: {+ spaceId: AuthorizedSpaceId;+}) {+ return prisma.spaceWebhook.findMany({+ where: { spaceId },+ select: {+ id: true,+ url: true,+ events: true,+ enabled: true,+ createdAt: true,+ deliveries: {+ where: { status: { in: ["succeeded", "failed", "exhausted"] } },+ select: {+ status: true,+ lastResponseStatus: true,+ updatedAt: true,+ },+ orderBy: { updatedAt: "desc" },+ take: 1,+ },+ },+ orderBy: { createdAt: "desc" },+ });+}++export function countSpaceWebhooks({ spaceId }: { spaceId: string }) {+ return prisma.spaceWebhook.count({ where: { spaceId } });+}+/**- * System-context reads for the dispatcher cron. Scope here is proven by the+ * The reads below serve the dispatcher cron. Scope there is proven by the* webhook row itself — its spaceId was authorized when the endpoint was- * created — not by a session, so these take plain ids.+ * created — not by a session, so they take plain ids.*/export async function listEnabledWebhooks() {diff --git a/apps/web/src/features/webhook/loaders.ts b/apps/web/src/features/webhook/loaders.tsnew file mode 100644index 000000000..dcac98814--- /dev/null+++ b/apps/web/src/features/webhook/loaders.ts@@ -0,0 +1,20 @@+import "server-only";++import { cache } from "react";+import { getActiveSpace } from "@/features/space/loaders";+import { requireUser } from "@/features/user/loaders";+import { getSpaceWebhooks, getWebhookAccess } from "./data";++/**+ * Whether the signed-in user may manage webhooks in their active space, and+ * when they may not, whether upgrading would change that.+ */+export const loadWebhookAccess = cache(async () => {+ const [user, space] = await Promise.all([requireUser(), getActiveSpace()]);+ return getWebhookAccess(user, space);+});++export const loadSpaceWebhooks = cache(async () => {+ const space = await getActiveSpace();+ return getSpaceWebhooks({ spaceId: space.id });+});diff --git a/apps/web/src/features/webhook/mutations.ts b/apps/web/src/features/webhook/mutations.tsindex 09cda667b..e354e7567 100644--- a/apps/web/src/features/webhook/mutations.ts+++ b/apps/web/src/features/webhook/mutations.ts@@ -1,9 +1,13 @@import "server-only";+import { randomBytes } from "node:crypto";+import { subject } from "@casl/ability";import type { Prisma } from "@rallly/database";import { prisma } from "@rallly/database";-import { decrypt } from "@rallly/utils/encryption";+import { decrypt, encrypt } from "@rallly/utils/encryption";import { env } from "@/env";+import { AppError } from "@/lib/errors/app-error";+import { defineAbilityForWebhooks } from "./ability";import {DELIVERY_CLAIM_BATCH_SIZE,DELIVERY_CONCURRENCY,@@ -20,6 +24,7 @@ import {listWebhookActivities,} from "./data";import type { WebhookEventType } from "./schema";+import { MAX_WEBHOOKS_PER_SPACE } from "./schema";import type { WebhookSendResult } from "./service";import { sendWebhook } from "./service";import {@@ -279,11 +284,22 @@ async function attemptDelivery(delivery: {error: "Could not decrypt the endpoint secret",};}+ // From the stored payload, not the current constant: the body is frozen at+ // fan-out, so the header has to describe the shape actually being sent.+ const version =+ delivery.payload &&+ typeof delivery.payload === "object" &&+ !Array.isArray(delivery.payload) &&+ typeof delivery.payload.version === "string"+ ? delivery.payload.version+ : null;+return sendWebhook({url: delivery.webhook.url,secret,deliveryId: delivery.id,eventType: delivery.eventType as WebhookEventType,+ version,body: JSON.stringify(delivery.payload),});}@@ -350,3 +366,115 @@ export async function deliverWebhooks({return summary;}++/**+ * Endpoint management for the settings page. Scope is proven by the caller's+ * action gate: the spaceId passed here is the actor's own space, and CASL+ * re-checks the target row against it before any write.+ */++/**+ * Signing secret shown once at creation. 32 random bytes, prefixed so it is+ * recognisable in a receiver's config, and stored encrypted — the dispatcher+ * needs the plaintext to sign with, so this cannot be a one-way hash.+ */+function generateWebhookSecret() {+ return `whsec_${randomBytes(32).toString("base64url")}`;+}++export async function createWebhook({+ spaceId,+ url,+ events,+}: {+ spaceId: string;+ url: string;+ events: WebhookEventType[];+}) {+ const count = await prisma.spaceWebhook.count({ where: { spaceId } });++ // Expected outcome the caller handles specifically, so it's part of the+ // return value; thrown errors are reserved for the global error handler.+ if (count >= MAX_WEBHOOKS_PER_SPACE) {+ return { ok: false, reason: "max_webhooks_exceeded" } as const;+ }++ const secret = generateWebhookSecret();++ const webhook = await prisma.spaceWebhook.create({+ data: {+ spaceId,+ url,+ events,+ secret: encrypt(secret, env.SECRET_PASSWORD),+ },+ select: { id: true },+ });++ return { ok: true, webhookId: webhook.id, secret } as const;+}++async function authorizeWebhook({+ spaceId,+ webhookId,+ action,+}: {+ spaceId: string;+ webhookId: string;+ action: "update" | "delete";+}) {+ const webhook = await prisma.spaceWebhook.findUnique({+ where: { id: webhookId },+ select: { spaceId: true },+ });++ if (!webhook) {+ throw new AppError({ code: "NOT_FOUND", message: "Webhook not found" });+ }++ const ability = defineAbilityForWebhooks({ spaceId });++ if (ability.cannot(action, subject("Webhook", webhook))) {+ throw new AppError({+ code: "FORBIDDEN",+ message: "You do not have permission to manage this webhook",+ });+ }+}++/**+ * Re-enabling clears the failure count and moves the cursor to now: an+ * endpoint is usually disabled after a long outage, and replaying everything+ * that happened while it was dark is not what the owner asked for.+ */+export async function setWebhookEnabled({+ spaceId,+ webhookId,+ enabled,+}: {+ spaceId: string;+ webhookId: string;+ enabled: boolean;+}) {+ await authorizeWebhook({ spaceId, webhookId, action: "update" });++ await prisma.spaceWebhook.update({+ where: { id: webhookId },+ data: enabled+ ? { enabled: true, consecutiveFailures: 0, cursor: new Date() }+ : { enabled: false },+ });+}++export async function deleteWebhook({+ spaceId,+ webhookId,+}: {+ spaceId: string;+ webhookId: string;+}) {+ await authorizeWebhook({ spaceId, webhookId, action: "delete" });++ // Deliveries cascade with the endpoint.+ await prisma.spaceWebhook.delete({ where: { id: webhookId } });+}diff --git a/apps/web/src/features/webhook/schema.test.ts b/apps/web/src/features/webhook/schema.test.tsindex ea1073418..2a2916cbf 100644--- a/apps/web/src/features/webhook/schema.test.ts+++ b/apps/web/src/features/webhook/schema.test.ts@@ -27,4 +27,20 @@ describe("webhookUrlSchema", () => {])("rejects %s", (_label, url) => {expect(webhookUrlSchema.safeParse(url).success).toBe(false);});++ // A form resolver surfaces only the first issue, so the first issue has to+ // be the one that names the actual problem.+ it.each([+ ["http://example.com/hook", "Webhook URLs must use https"],+ ["https://localhost/hook", "Webhook URLs must point at a public host"],+ ["https://127.0.0.1/hook", "Webhook URLs must point at a public host"],+ [+ "https://user:[email protected]/hook",+ "Webhook URLs must not contain credentials",+ ],+ ])("reports %s as %s", (url, message) => {+ const result = webhookUrlSchema.safeParse(url);+ expect(result.success).toBe(false);+ expect(result.error?.issues[0]?.message).toBe(message);+ });});diff --git a/apps/web/src/features/webhook/schema.ts b/apps/web/src/features/webhook/schema.tsindex 8686ed8ff..b36eb2ef4 100644--- a/apps/web/src/features/webhook/schema.ts+++ b/apps/web/src/features/webhook/schema.ts@@ -1,5 +1,6 @@import * as z from "zod";import { pollClosedReasonSchema } from "@/features/poll/schema";+import { WEBHOOK_VERSION } from "./constants";import { getWebhookUrlRejection } from "./utils";export const webhookEventTypeSchema = z@@ -35,6 +36,11 @@ const webhookPollSchema = (status: "open" | "closed" | "scheduled") =>.meta({ id: `WebhookPoll${status[0]?.toUpperCase()}${status.slice(1)}` });const envelope = {+ version: z.string().meta({+ description:+ "The payload contract this event was built against. Also sent as the `X-Rallly-Webhook-Version` header.",+ example: WEBHOOK_VERSION,+ }),id: z.string().meta({description:"Stable event id. Retries of the same event carry the same id, so receivers can deduplicate on it.",@@ -113,8 +119,14 @@ const rejectionMessages = {private_host: "Webhook URLs must point at a public host",} as const;+/**+ * The scheme is judged by the refinement below, not by `z.url`'s own+ * `protocol` option: a failing built-in check adds its generic "Invalid URL"+ * issue ahead of the specific one, and a form resolver shows only the first.+ * One source of verdicts means the field always names the actual problem.+ */export const webhookUrlSchema = z- .url({ protocol: /^https$/ })+ .url().max(2048).superRefine((value, ctx) => {const rejection = URL.canParse(value)@@ -125,6 +137,11 @@ export const webhookUrlSchema = z}});+// Cap on endpoints per space. Not a security control — the dispatcher fans+// out to every enabled endpoint, so this bounds the work one space can add+// to a run, and keeps the list readable.+export const MAX_WEBHOOKS_PER_SPACE = 5;+export const createWebhookInputSchema = z.object({url: webhookUrlSchema,events: z.array(webhookEventTypeSchema).min(1),@@ -140,3 +157,12 @@ export const updateWebhookInputSchema = z.object({});export type UpdateWebhookInput = z.infer<typeof updateWebhookInputSchema>;++export const setWebhookEnabledSchema = z.object({+ webhookId: z.string(),+ enabled: z.boolean(),+});++export const deleteWebhookSchema = z.object({+ webhookId: z.string(),+});diff --git a/apps/web/src/features/webhook/service.test.ts b/apps/web/src/features/webhook/service.test.tsindex 36a10353f..faa7c88b5 100644--- a/apps/web/src/features/webhook/service.test.ts+++ b/apps/web/src/features/webhook/service.test.ts@@ -70,6 +70,7 @@ describe("sendWebhook", () => {secret: "whsec_test",deliveryId: "d_1",eventType: "poll.closed",+ version: "2026-09-20",body: "{}",});diff --git a/apps/web/src/features/webhook/service.ts b/apps/web/src/features/webhook/service.tsindex fcf5df5fd..115d6394f 100644--- a/apps/web/src/features/webhook/service.ts+++ b/apps/web/src/features/webhook/service.ts@@ -113,12 +113,21 @@ export async function sendWebhook({secret,deliveryId,eventType,+ version,body,}: {url: string;secret: string;deliveryId: string;eventType: string;+ /**+ * The version the body was built against, read from the stored payload+ * rather than the current constant: payloads are frozen at fan-out, so a+ * delivery retried after a version change must keep advertising the+ * contract its body actually follows. Absent on deliveries fanned out+ * before the version existed, which are sent without the header.+ */+ version: string | null;body: string;}): Promise<WebhookSendResult> {let target: URL;@@ -142,6 +151,7 @@ export async function sendWebhook({"Content-Type": "application/json","User-Agent": "Rallly-Webhooks/1.0","X-Rallly-Event": eventType,+ ...(version ? { "X-Rallly-Webhook-Version": version } : {}),"X-Rallly-Delivery": deliveryId,"X-Rallly-Signature": signature,},diff --git a/apps/web/src/features/webhook/utils.ts b/apps/web/src/features/webhook/utils.tsindex 65983d9a7..a77bbf719 100644--- a/apps/web/src/features/webhook/utils.ts+++ b/apps/web/src/features/webhook/utils.ts@@ -1,8 +1,40 @@import { absoluteUrl, shortUrl } from "@rallly/utils/absolute-url";import { pollActivitySchema } from "@/features/poll/activity/schema";-import { RETRY_DELAYS_MS } from "./constants";+import { RETRY_DELAYS_MS, WEBHOOK_VERSION } from "./constants";import type { WebhookEvent, WebhookEventType } from "./schema";+/**+ * The resource half of an event name (`poll` in `poll.closed`). Event names+ * are `<resource>.<transition>` by construction, so the grouping the picker+ * renders falls out of the name and a new resource needs no second list.+ */+export type WebhookEventResource =+ WebhookEventType extends `${infer R}.${string}` ? R : never;++export function getWebhookEventResource(eventType: WebhookEventType) {+ return eventType.split(".")[0] as WebhookEventResource;+}++/**+ * Event types bucketed by resource, each bucket keeping the order of the+ * source list so the picker is stable.+ */+export function groupWebhookEventTypes(+ eventTypes: readonly WebhookEventType[],+) {+ const groups = new Map<WebhookEventResource, WebhookEventType[]>();+ for (const eventType of eventTypes) {+ const resource = getWebhookEventResource(eventType);+ const group = groups.get(resource);+ if (group) {+ group.push(eventType);+ } else {+ groups.set(resource, [eventType]);+ }+ }+ return [...groups];+}+/*** Stripe-style signature: `t=<unix seconds>,v1=<hex hmac-sha256>` over* `${t}.${body}`. Including the timestamp in the signed string lets a@@ -108,6 +140,7 @@ export function buildWebhookPayload({const event = parsed.data;const base = {+ version: WEBHOOK_VERSION,id: activity.id,createdAt: activity.createdAt.toISOString(),};diff --git a/apps/web/src/lib/feature-flags/config.ts b/apps/web/src/lib/feature-flags/config.tsindex 64ecb2550..fe1302cd0 100644--- a/apps/web/src/lib/feature-flags/config.ts+++ b/apps/web/src/lib/feature-flags/config.ts@@ -5,6 +5,7 @@ import { isCalendarsEnabled } from "@/features/calendars/constants";import { isEventTypesEnabled } from "@/features/event-types/constants";import { isFeedbackEnabled } from "@/features/feedback/constants";import { isQuickCreateEnabled } from "@/features/quick-create/constants";+import { isWebhooksEnabled } from "@/features/webhook/constants";import { isSelfHosted } from "@/lib/constants";import type { FeatureFlagConfig } from "@/lib/feature-flags/types";import { isStorageEnabled } from "@/lib/storage";@@ -38,4 +39,5 @@ export const featureFlagConfig: FeatureFlagConfig = {// The API launches cloud first; self-hosted gets it once the release// channel carries the API host and its docs.api: !isSelfHosted,+ webhooks: isWebhooksEnabled,};diff --git a/apps/web/src/lib/feature-flags/types.ts b/apps/web/src/lib/feature-flags/types.tsindex 926a62a7c..fdff2a2ce 100644--- a/apps/web/src/lib/feature-flags/types.ts+++ b/apps/web/src/lib/feature-flags/types.ts@@ -12,6 +12,7 @@ export interface FeatureFlagConfig {inProcessRateLimit: boolean;nonprofitDiscount: boolean;api: boolean;+ webhooks: boolean;}export type Feature = keyof FeatureFlagConfig;diff --git a/apps/web/tests/webhooks-settings.spec.ts b/apps/web/tests/webhooks-settings.spec.tsnew file mode 100644index 000000000..96a5fe8dc--- /dev/null+++ b/apps/web/tests/webhooks-settings.spec.ts@@ -0,0 +1,287 @@+import type { Page } from "@playwright/test";+import { expect, test } from "@playwright/test";+import { prisma } from "@rallly/database";+import { decrypt, encrypt } from "@rallly/utils/encryption";+import {+ createUserInDb,+ loginWithEmail,+ upgradeSpaceToPro,+} from "./test-utils";++/**+ * The webhooks settings page: adding an endpoint and revealing its signing+ * secret once, disabling one, deleting one, and the two states that deny+ * access — a member of the space, and a space still on the hobby tier.+ */++const runId = Date.now().toString(36);+const createdUserIds: string[] = [];+const SECRET_PASSWORD = process.env.SECRET_PASSWORD as string;++// After a page load, React briefly keeps a second hidden copy of the+// streamed page content in a staging <div hidden> under <body>. Text+// locators strict-fail against it, so page text assertions scope to+// #main-content, which only ever holds the live copy.+function mainContent(page: Page) {+ return page.locator("#main-content");+}++async function createOwner(name: string, { pro }: { pro: boolean }) {+ const email = `${name}-${runId}@example.com`;+ const user = await createUserInDb({ email, name });+ createdUserIds.push(user.id);++ const space = await prisma.space.findFirstOrThrow({+ where: { ownerId: user.id },+ });++ if (pro) {+ await upgradeSpaceToPro({ spaceId: space.id, userId: user.id, seats: 1 });+ }++ return { user, space, email };+}++async function createWebhookInDb({+ spaceId,+ url,+}: {+ spaceId: string;+ url: string;+}) {+ return prisma.spaceWebhook.create({+ data: {+ spaceId,+ url,+ secret: encrypt("whsec_settings_test", SECRET_PASSWORD),+ events: ["poll.closed", "poll.reopened", "poll.scheduled"],+ },+ });+}++function decryptSecret(stored: string) {+ return decrypt(stored, SECRET_PASSWORD);+}++async function gotoWebhooks(page: Page, email: string) {+ await loginWithEmail(page, { email });+ await page.goto("/settings/webhooks");+}++function endpointRow(page: Page, url: string) {+ return page.getByRole("listitem").filter({ hasText: url });+}++test.afterAll(async () => {+ if (createdUserIds.length > 0) {+ await prisma.user.deleteMany({+ where: { id: { in: createdUserIds } },+ });+ }+});++test.describe("Webhooks settings", () => {+ test("adds an endpoint and reveals the signing secret once", async ({+ page,+ }) => {+ const { space, email } = await createOwner("webhooks-create", {+ pro: true,+ });+ await gotoWebhooks(page, email);++ await expect(+ mainContent(page).getByText("No endpoints found"),+ ).toBeVisible();++ await page.getByRole("button", { name: "Add endpoint" }).click();+ const url = "https://example.com/hooks/rallly";+ await page.getByLabel("Endpoint URL").fill(url);+ await page+ .getByRole("dialog")+ .getByRole("button", { name: "Add webhook" })+ .click();++ // The secret is shown once, and it is the real one: what the dialog+ // displays must decrypt back out of the row the dispatcher signs with.+ const secretField = page.getByLabel("Signing secret");+ await expect(secretField).toBeVisible();+ const revealed = await secretField.inputValue();+ expect(revealed).toMatch(/^whsec_/);++ const webhook = await prisma.spaceWebhook.findFirstOrThrow({+ where: { spaceId: space.id },+ });+ expect(webhook.url).toBe(url);+ expect(webhook.enabled).toBe(true);+ expect(webhook.events.sort()).toEqual([+ "poll.closed",+ "poll.reopened",+ "poll.scheduled",+ ]);+ expect(decryptSecret(webhook.secret)).toBe(revealed);+ // Never replays history: a new endpoint starts at now.+ expect(webhook.cursor.getTime()).toBeGreaterThan(Date.now() - 60_000);++ await page.getByRole("button", { name: "Done" }).click();++ const row = endpointRow(page, url);+ await expect(row).toBeVisible();+ // The row summarises the subscription rather than listing it.+ await expect(row.getByText("3 events")).toBeVisible();+ // Closing the reveal is the only chance to copy it — reloading must not+ // surface the secret again.+ await page.reload();+ await expect(mainContent(page).getByText(revealed)).toHaveCount(0);+ });++ test("rejects an endpoint that is not a public https URL", async ({+ page,+ }) => {+ const { space, email } = await createOwner("webhooks-invalid", {+ pro: true,+ });+ await gotoWebhooks(page, email);++ await page.getByRole("button", { name: "Add endpoint" }).click();+ await page.getByLabel("Endpoint URL").fill("http://localhost:3000/hook");+ await page+ .getByRole("dialog")+ .getByRole("button", { name: "Add webhook" })+ .click();++ await expect(page.getByText("Webhook URLs must use https")).toBeVisible();+ expect(+ await prisma.spaceWebhook.count({ where: { spaceId: space.id } }),+ ).toBe(0);+ });++ test("disables an endpoint", async ({ page }) => {+ const { space, email } = await createOwner("webhooks-disable", {+ pro: true,+ });+ const url = "https://example.com/hooks/disable";+ const webhook = await createWebhookInDb({ spaceId: space.id, url });++ await gotoWebhooks(page, email);++ const row = endpointRow(page, url);+ const toggle = row.getByRole("switch", { name: "Enabled" });+ await expect(toggle).toBeChecked();+ await toggle.click();++ await expect(toggle).not.toBeChecked();+ expect(+ (+ await prisma.spaceWebhook.findUniqueOrThrow({+ where: { id: webhook.id },+ })+ ).enabled,+ ).toBe(false);+ });++ test("deletes an endpoint", async ({ page }) => {+ const { space, email } = await createOwner("webhooks-delete", {+ pro: true,+ });+ const url = "https://example.com/hooks/delete";+ await createWebhookInDb({ spaceId: space.id, url });++ await gotoWebhooks(page, email);++ const row = endpointRow(page, url);+ await row.getByRole("button", { name: "More options" }).click();+ await page.getByRole("menuitem", { name: "Delete" }).click();+ await page+ .getByRole("dialog")+ .getByRole("button", { name: "Delete" })+ .click();++ await expect(+ mainContent(page).getByText("No endpoints found"),+ ).toBeVisible();+ expect(+ await prisma.spaceWebhook.count({ where: { spaceId: space.id } }),+ ).toBe(0);+ });++ test("shows the last delivery result for an endpoint", async ({ page }) => {+ const { space, email } = await createOwner("webhooks-delivery", {+ pro: true,+ });+ const url = "https://example.com/hooks/delivery";+ const webhook = await createWebhookInDb({ spaceId: space.id, url });+ await prisma.webhookDelivery.create({+ data: {+ webhookId: webhook.id,+ activityId: `webhooks-settings-${runId}`,+ eventType: "poll.closed",+ payload: { type: "poll.closed" },+ status: "failed",+ attempts: 1,+ lastResponseStatus: 500,+ },+ });++ await gotoWebhooks(page, email);++ await expect(+ endpointRow(page, url).getByText(/Failed .* with 500/),+ ).toBeVisible();+ });++ test("a member of the space cannot reach the page", async ({ page }) => {+ const { space } = await createOwner("webhooks-owner", { pro: true });+ const memberEmail = `webhooks-member-${runId}@example.com`;+ const member = await createUserInDb({+ email: memberEmail,+ name: "webhooks-member",+ });+ createdUserIds.push(member.id);+ await prisma.spaceMember.create({+ data: { spaceId: space.id, userId: member.id, role: "MEMBER" },+ });+ // The active space is the membership selected most recently, and both+ // default to now — back-date the member's own space so the pro one wins+ // deterministically.+ await prisma.spaceMember.updateMany({+ where: { userId: member.id, spaceId: { not: space.id } },+ data: { lastSelectedAt: new Date(Date.now() - 60_000) },+ });++ await loginWithEmail(page, { email: memberEmail });+ // The nav entry is owner-only, so the member has to arrive by deep link.+ await expect(page.getByRole("link", { name: "Webhooks" })).toHaveCount(0);++ await page.goto("/settings/webhooks");++ // A member has no self-serve path to webhooks, so this is a denial, not+ // an upsell — the pay wall would tell them to buy something the space+ // already has. Asserted on the rendered body rather than the HTTP+ // status: the shell streams before notFound() resolves, so the response+ // is a 200 carrying the 404 page.+ await expect(mainContent(page).getByText("Page not found")).toBeVisible();+ await expect(+ mainContent(page).getByText("Upgrade for webhooks"),+ ).toHaveCount(0);+ await expect(+ page.getByRole("button", { name: "Add endpoint" }),+ ).toHaveCount(0);+ });++ test("a hobby space sees the pay wall instead of the list", async ({+ page,+ }) => {+ const { email } = await createOwner("webhooks-hobby", { pro: false });+ await gotoWebhooks(page, email);++ await expect(+ mainContent(page).getByText("Upgrade for webhooks"),+ ).toBeVisible();+ await expect(+ page.getByRole("button", { name: "Add endpoint" }),+ ).toHaveCount(0);++ await page.getByRole("button", { name: "Upgrade to Pro" }).click();+ await expect(page.getByRole("dialog")).toBeVisible();+ });+});diff --git a/apps/web/tests/webhooks.spec.ts b/apps/web/tests/webhooks.spec.tsindex 3ec8aa0dc..c35160b79 100644--- a/apps/web/tests/webhooks.spec.ts+++ b/apps/web/tests/webhooks.spec.ts@@ -6,6 +6,7 @@ import type { APIRequestContext } from "@playwright/test";import { expect, test } from "@playwright/test";import { prisma } from "@rallly/database";import { encrypt } from "@rallly/utils/encryption";+import { WEBHOOK_VERSION } from "@/features/webhook/constants";import { createUserInDb } from "./test-utils";/**@@ -178,11 +179,13 @@ test.describe("Webhook delivery", () => {const [received] = receiver.requests;expect(received?.headers["x-rallly-event"]).toBe("poll.closed");expect(received?.headers["content-type"]).toBe("application/json");+ expect(received?.headers["x-rallly-webhook-version"]).toBe(WEBHOOK_VERSION);const signature = received?.headers["x-rallly-signature"] as string;expect(verifySignature(signature, received?.body ?? "")).toBe(true);const body = JSON.parse(received?.body ?? "{}");expect(body).toMatchObject({+ version: WEBHOOK_VERSION,id: activity.id,type: "poll.closed",createdAt: activity.createdAt.toISOString(),@@ -449,6 +452,30 @@ test.describe("Webhook delivery", () => {expect(updated.enabled).toBe(false);});+ test("keeps a retry's header on the version its frozen body carries", async ({+ request,+ }) => {+ // The body is frozen at fan-out, so a delivery written before the+ // version existed must not be advertised as the current one.+ const webhook = await createWebhook();+ await prisma.webhookDelivery.create({+ data: {+ webhookId: webhook.id,+ activityId: `webhook-delivery-legacy-${Date.now()}`,+ eventType: "poll.closed",+ payload: { id: "legacy", type: "poll.closed" },+ nextAttemptAt: secondsAgo(1),+ },+ });++ await runCron(request);++ expect(receiver.requests).toHaveLength(1);+ expect(+ receiver.requests[0]?.headers["x-rallly-webhook-version"],+ ).toBeUndefined();+ });+test("a success resets the consecutive failure count", async ({request,}) => {