Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -800,7 +800,15 @@ as the desired state:
- `internal/webhook`: enqueues `booking.created` / `.cancelled` / `.rescheduled`
plus the notetaker events `recording.completed` / `transcript.ready` / `notes.ready`
(reference payloads — booking-shaped, keyed by id; consumers fetch the artifact body
via REST/MCP). There is **no** `booking.reminder` webhook event. Deliveries are signed
via REST/MCP). **`booking.reminder`** fires from the `reminder.send` job, once per
configured `hours_before`, so an external SMS/push sender stays stateless: Calnode keeps
owning scheduling, reschedules and cancellations, the receiver only delivers. It passes
the same gates as the reminder email (booking still `confirmed`, host's
`notify_reminder` on) and carries `hours_before` in `data` whatever the webhook's field
selection. It is enqueued **before** the email with `EnqueueOnce`: the delivery ID is
derived from (webhook, booking, `hours_before`, `start_at`) and inserted with
`INSERT OR IGNORE`, so a job retried after a failed email collapses instead of
delivering twice, while a reschedule (new `start_at`) gets its own event. Deliveries are signed
**HMAC-SHA256**, header `X-Calnode-Signature` (+ `X-Calnode-Event`/`-Delivery`),
secret stored encrypted. The worker's HTTP client is **SSRF-guarded** (resolves
DNS, blocks private/loopback/CGNAT/ULA IPs, dials the resolved IP to avoid
Expand Down
1 change: 1 addition & 0 deletions frontend/src/routes/webhooks/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
'booking.cancelled',
'booking.rescheduled',
'booking.rsvp',
'booking.reminder',
'recording.completed',
'transcript.ready',
'notes.ready'
Expand Down
2 changes: 1 addition & 1 deletion internal/handler/webhook_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import (
)

var validWebhookEvents = []string{
"booking.created", "booking.cancelled", "booking.rescheduled", "booking.rsvp",
"booking.created", "booking.cancelled", "booking.rescheduled", "booking.rsvp", "booking.reminder",
"recording.completed", "transcript.ready", "notes.ready",
}

Expand Down
13 changes: 13 additions & 0 deletions internal/handler/webhook_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,19 @@ func TestCreateWebhook_bothEvents(t *testing.T) {
}
}

func TestCreateWebhook_bookingReminderEvent(t *testing.T) {
h, apiKey, _ := setupWorkspace(t)

req := authReq(http.MethodPost, "/v1/webhooks",
`{"url":"https://example.com/hook","events":["booking.reminder"]}`, apiKey)
rec := httptest.NewRecorder()
h.RequireAuth(h.CreateWebhook)(rec, req)

if rec.Code != http.StatusCreated {
t.Fatalf("status = %d; want 201 — %s", rec.Code, rec.Body.String())
}
}

func TestCreateWebhook_missingURL_returns400(t *testing.T) {
h, apiKey, _ := setupWorkspace(t)

Expand Down
144 changes: 144 additions & 0 deletions internal/webhook/enqueue_once_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
package webhook_test

import (
"context"
"encoding/json"
"regexp"
"testing"

"github.com/calnode/calnode/internal/webhook"
)

func reminderPayload() webhook.BookingPayload {
return webhook.BookingPayload{
EventTypeSlug: "30-min",
HostID: testUserID,
StartAt: "2026-06-15T09:00:00Z",
EndAt: "2026-06-15T09:30:00Z",
Status: "confirmed",
CreatedAt: "2026-06-14T15:00:00Z",
HoursBefore: 2,
}
}

func countRows(t *testing.T, e *env, query string, args ...any) int {
t.Helper()
var n int
if err := e.db.QueryRowContext(context.Background(), query, args...).Scan(&n); err != nil {
t.Fatalf("count: %v", err)
}
return n
}

// A retried reminder job calls EnqueueOnce again with the same key: it must not
// produce a second delivery or a second webhook.deliver job.
func TestEnqueueOnce_sameKeyCollapses(t *testing.T) {
e := newEnv(t)
ctx := context.Background()
wh, _, _ := e.svc.Create(ctx, testUserID, "https://example.com/hook", []string{"booking.reminder"})

for i := 0; i < 3; i++ {
if err := e.svc.EnqueueOnce(ctx, "booking.reminder", reminderPayload(), "k1"); err != nil {
t.Fatalf("EnqueueOnce #%d: %v", i+1, err)
}
}
if n := countRows(t, e, `SELECT COUNT(*) FROM webhook_deliveries WHERE webhook_id = ?`, wh.ID); n != 1 {
t.Errorf("deliveries = %d; want 1", n)
}
if n := countRows(t, e, `SELECT COUNT(*) FROM jobs WHERE type = 'webhook.deliver'`); n != 1 {
t.Errorf("webhook.deliver jobs = %d; want 1", n)
}

// Still collapsed after the delivery finished and its job is no longer live,
// which is where the jobs table's own (type, payload) guard stops helping.
e.db.ExecContext(ctx, `UPDATE jobs SET status = 'done' WHERE type = 'webhook.deliver'`)
e.db.ExecContext(ctx, `UPDATE webhook_deliveries SET status = 'success'`)
if err := e.svc.EnqueueOnce(ctx, "booking.reminder", reminderPayload(), "k1"); err != nil {
t.Fatalf("EnqueueOnce after success: %v", err)
}
if n := countRows(t, e, `SELECT COUNT(*) FROM webhook_deliveries`); n != 1 {
t.Errorf("deliveries after success = %d; want 1", n)
}
if n := countRows(t, e, `SELECT COUNT(*) FROM jobs WHERE type = 'webhook.deliver'`); n != 1 {
t.Errorf("jobs after success = %d; want 1", n)
}
}

func TestEnqueueOnce_differentKeyOrWebhookGetsOwnDelivery(t *testing.T) {
e := newEnv(t)
ctx := context.Background()
e.svc.Create(ctx, testUserID, "https://example.com/a", []string{"booking.reminder"})
e.svc.Create(ctx, testUserID, "https://example.com/b", []string{"booking.reminder"})

if err := e.svc.EnqueueOnce(ctx, "booking.reminder", reminderPayload(), "k1"); err != nil {
t.Fatal(err)
}
if err := e.svc.EnqueueOnce(ctx, "booking.reminder", reminderPayload(), "k2"); err != nil {
t.Fatal(err)
}
// Two webhooks × two keys.
if n := countRows(t, e, `SELECT COUNT(*) FROM webhook_deliveries`); n != 4 {
t.Errorf("deliveries = %d; want 4", n)
}

uuid := regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$`)
rows, _ := e.db.QueryContext(ctx, `SELECT id FROM webhook_deliveries`)
defer rows.Close()
for rows.Next() {
var id string
rows.Scan(&id)
if !uuid.MatchString(id) {
t.Errorf("delivery id %q is not UUID-shaped", id)
}
}
}

func TestEnqueueOnce_requiresKey(t *testing.T) {
e := newEnv(t)
if err := e.svc.EnqueueOnce(context.Background(), "booking.reminder", reminderPayload(), ""); err == nil {
t.Fatal("EnqueueOnce with empty key: want error")
}
}

// hours_before is part of the event, not a selectable booking field: it is sent even
// when the webhook narrowed its fields, and never on other events.
func TestEnqueue_hoursBeforeAlwaysSentWithReminder(t *testing.T) {
e := newEnv(t)
ctx := context.Background()
wh, _, _ := e.svc.Create(ctx, testUserID, "https://example.com/hook",
[]string{"booking.reminder", "booking.created"})
e.db.ExecContext(ctx, `UPDATE webhooks SET fields = '["id"]' WHERE id = ?`, wh.ID)

if err := e.svc.EnqueueOnce(ctx, "booking.reminder", reminderPayload(), "k1"); err != nil {
t.Fatal(err)
}
created := reminderPayload()
created.HoursBefore = 0
if err := e.svc.Enqueue(ctx, "booking.created", created); err != nil {
t.Fatal(err)
}

data := map[string]map[string]any{}
rows, _ := e.db.QueryContext(ctx, `SELECT event, payload FROM webhook_deliveries`)
defer rows.Close()
for rows.Next() {
var event, payload string
rows.Scan(&event, &payload)
var env struct {
Data map[string]any `json:"data"`
}
if err := json.Unmarshal([]byte(payload), &env); err != nil {
t.Fatalf("payload: %v", err)
}
data[event] = env.Data
}
if got := data["booking.reminder"]["hours_before"]; got != float64(2) {
t.Errorf("booking.reminder hours_before = %v; want 2", got)
}
if _, ok := data["booking.reminder"]["start_at"]; ok {
t.Error("booking.reminder carries start_at although the webhook selected only id")
}
if _, ok := data["booking.created"]["hours_before"]; ok {
t.Error("booking.created carries hours_before")
}
}
53 changes: 49 additions & 4 deletions internal/webhook/webhook.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,10 @@ const (
FieldInviteDelivery = "invite_delivery"
)

// FieldHoursBefore is not selectable: it describes the event (which reminder fired)
// rather than the booking, so booking.reminder always carries it and nothing else does.
const FieldHoursBefore = "hours_before"

// AllFields is every selectable field, in payload order. Used to validate config
// and (UI) to render the checkbox list.
var AllFields = []string{
Expand Down Expand Up @@ -133,6 +137,10 @@ type BookingPayload struct {
// RSVPStatus is the booker's answer to a Calnode-sent invite (accepted, declined,
// tentative); set on booking.rsvp only.
RSVPStatus string `json:"rsvp_status,omitempty"`
// HoursBefore is which configured reminder fired (the event type's hours_before);
// set on booking.reminder only, and always sent with it whatever the webhook's field
// selection, since a sender that fires at 24h and 2h has to tell them apart.
HoursBefore int `json:"hours_before,omitempty"`
}

type Service struct {
Expand Down Expand Up @@ -370,13 +378,42 @@ func buildData(bd enrichedBooking, fields []string) map[string]any {
out[f] = bd.core.AmountPaidCents
}
}
if bd.core.HoursBefore > 0 {
out[FieldHoursBefore] = bd.core.HoursBefore
}
return out
}

// Enqueue finds all active webhooks for p.HostID that subscribe to event,
// and creates a webhook_deliveries + jobs row pair for each. Failures are
// soft-errors (caller logs; a booking is already committed).
func (s *Service) Enqueue(ctx context.Context, event string, p BookingPayload) error {
return s.enqueue(ctx, event, p, "")
}

// EnqueueOnce is Enqueue for an event that a retried job may raise more than once.
// Each delivery's ID is derived from the webhook ID and key instead of being random, and
// is inserted with INSERT OR IGNORE, so a second call with the same key creates neither
// a delivery nor a job for a webhook that already has one. The ID is also what receivers
// see in X-Calnode-Delivery, so it stays stable for them too.
func (s *Service) EnqueueOnce(ctx context.Context, event string, p BookingPayload, key string) error {
if key == "" {
return errors.New("webhook: EnqueueOnce needs a key")
}
return s.enqueue(ctx, event, p, key)
}

// deliveryIDFor derives a UUID-shaped delivery ID (version 5 bits, SHA-256 based) from
// the webhook and the caller's key, so it fits wherever a random delivery ID does.
func deliveryIDFor(webhookID, key string) string {
sum := sha256.Sum256([]byte(webhookID + "\x00" + key))
b := sum[:16]
b[6] = (b[6] & 0x0f) | 0x50
b[8] = (b[8] & 0x3f) | 0x80
return fmt.Sprintf("%08x-%04x-%04x-%04x-%012x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:16])
}

func (s *Service) enqueue(ctx context.Context, event string, p BookingPayload, key string) error {
rows, err := s.db.QueryContext(ctx, `
SELECT id, events, fields FROM webhooks
WHERE user_id = ? AND is_active = 1`, p.HostID)
Expand Down Expand Up @@ -456,13 +493,21 @@ func (s *Service) Enqueue(ctx context.Context, event string, p BookingPayload) e
}

deliveryID := uid.New()
insert := `INSERT INTO webhook_deliveries (id, webhook_id, booking_id, event, payload, status)
VALUES (?, ?, ?, ?, ?, 'pending')`
if key != "" {
deliveryID = deliveryIDFor(wh.id, key)
insert = `INSERT OR IGNORE INTO webhook_deliveries (id, webhook_id, booking_id, event, payload, status)
VALUES (?, ?, ?, ?, ?, 'pending')`
}
jobID := uid.New()
if _, err := tx.ExecContext(ctx, `
INSERT INTO webhook_deliveries (id, webhook_id, booking_id, event, payload, status)
VALUES (?, ?, ?, ?, ?, 'pending')`,
deliveryID, wh.id, bookingIDArg, event, string(payloadBytes)); err != nil {
res, err := tx.ExecContext(ctx, insert, deliveryID, wh.id, bookingIDArg, event, string(payloadBytes))
if err != nil {
return fmt.Errorf("webhook: insert delivery: %w", err)
}
if n, err := res.RowsAffected(); err == nil && n == 0 {
continue // EnqueueOnce: this webhook already has the delivery for key
}
jobPayload, _ := json.Marshal(map[string]string{"webhook_delivery_id": deliveryID})
if _, err := tx.ExecContext(ctx, `
INSERT INTO jobs (id, type, payload, run_at)
Expand Down
Loading
Loading