Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

13.6 KB
Raw Blame

Typed Webhook Events

Status: In Progress — all six migration steps built on spree/spree#14773, awaiting review Target: Spree 6.0 Depends on: 6.0-admin-api.md (webhook endpoints and deliveries are Admin API resources), the Zod schemas for every SDK (shipped 2026-09-29, spree/spree#14763) Author: Damian Legawiec (design driven with Claude) Last updated: 2026-09-30 Tracking: Linear V-3728 · GitHub spree/spree#14770

Summary

Spree publishes about 110 webhook events, but nothing declares them. Event names are string literals spread across models, workflows and controllers; the dashboard keeps its own hand-copied list (WEBHOOK_EVENT_GROUPS) that already drifts from the server; and @spree/sdk/webhooks types every payload as WebhookEvent<unknown>, so each consumer guesses which record arrives. This plan declares every event once in Ruby — its name and the serializer that builds its payload — and generates everything else from that declaration: a typed event map and a verified, narrowed constructWebhookEvent in @spree/sdk/webhooks, Zod schemas for runtime checks, and an Admin API endpoint the dashboard reads its event picker from.

Key Decisions (do not deviate without discussion)

  • Payloads use the Store API shape (2026-09-29). It is the customer-facing representation already shipped, it carries no back-office fields (internal notes, IP addresses, card-check results, login attempts), and it is what Spree::Publishable#event_payload builds today. It is not free of personal data — orders carry email and addresses — so the endpoint still has to be trusted with customer data, as today.
  • Back-office data is fetched, not pushed (2026-09-29). Every payload carries prefixed IDs; an integration that needs admin fields calls the Admin API with a scoped secret key. Access to sensitive fields then passes the same scope check as any other read, and the data is current rather than a snapshot. This is the Stripe "thin event" and Medusa model; Saleor and Shopify reach the same bound by limiting payloads to what the receiver may read.
  • Webhook endpoint scopes are out of scope (2026-09-29). Limiting which events an endpoint may subscribe to by scope was considered and deliberately left out of this plan.
  • Types live in @spree/sdk/webhooks (2026-09-29). Next to the existing verifyWebhookSignature, generated from the Store serializers the payloads actually use.
  • The catalog is the single source of truth. Generated TypeScript types, Zod schemas, the dashboard picker and the documentation event reference all read it; nothing re-lists events by hand.
  • Events are declared on the model whose record is the payload (2026-09-29). publishes_events / publishes_event sit next to publishes_lifecycle_events, so adding an event and declaring it happen in one file, and extensions use the same macro. A single central registry file was rejected: every new event would be edited in two places and the file would become a merge-conflict hotspot. Accepted cost: the full list is spread over roughly 30 model files; the Admin API endpoint and the generated types are where it is read as a whole.
  • Undeclared events raise in development and test, warn in production (2026-09-29). A forgotten declaration fails the spec that publishes the event, so it cannot ship unnoticed, while a live store never breaks over it. Accepted cost: extensions must declare their events before their own specs pass.
  • Deprecated aliases stay typed and visible, marked deprecated (2026-09-29). order.completed and shipment.shipped keep their payload types with a @deprecated note naming the replacement and the 6.1 removal, and the picker shows a "deprecated" badge. Hiding them would strip types from subscribers who still use them. Both names stay listed until 6.1.
  • Extra facts about an event travel in metadata, never in data (2026-09-30). notify_customer on order.placed, order.canceled and order_group.completed, and the store and requester on customer.anonymized, moved there instead of into per-event serializers such as the OrderCanceledEventSerializer sketched below: data then stays exactly the record's Store shape, one type per record. Accepted cost: subscribers that read payload['notify_customer'] change to metadata['notify_customer'] (noted in the 6.0 upgrade guide).
  • A credential event names the permission it needs (2026-09-30). credential: takes a permission key (write_customers for customer.password_reset_requested) rather than true, and subscribing an endpoint to the event requires it.
  • Some events never reach a webhook (2026-09-30). admin_user.password_reset_requested and seller_user.password_reset_requested carry reset tokens and have no external consumer — core sends those emails — so they are declared webhook: false. The webhook subscriber refuses them whatever an endpoint subscribes to, including an endpoint naming them outright, and they are left out of the Admin API list, the dashboard picker and the generated types. This moves the subscriber's old NON_DELIVERABLE_EVENTS list into the catalog; the rule itself is unchanged from 5.x.
  • Event serializers may not inherit a back-office shape (2026-09-30). The purchase order, stock receipt, supplier and shipping label event serializers were subclasses of their Admin serializers, so their webhooks pushed costs, notes, contact details and staff names. They are now thin Store-level shapes (status, related IDs, timestamps), and the type generator refuses any event serializer with an Admin or Seller ancestor. The product submission shape moved from the Seller namespace to the Store level for the same reason.
  • Runtime validation takes the schemas as an argument (2026-09-30). constructWebhookEvent(body, headers, secret, { schemas: webhookEventSchemas }) rather than { validate: true }, so @spree/sdk/webhooks does not bundle Zod for receivers that only need the types.
  • Extension events are typed by declaration merging (2026-09-29). WebhookEventMap is an interface; an extension adds its events in a type file and they narrow like core events, the same convention the SDK types already follow. An untyped fallback was rejected because it pushes casts onto every extension consumer.

Design Details

What exists today

  • Spree::Publishable (spree/core/app/models/concerns/spree/publishable.rb) publishes <prefix>.created/updated/deleted for models with publishes_lifecycle_events, and publish_event(name, payload = nil, metadata = {}) for everything else. With no payload, the record's Store serializer (Spree::Api::V3::<Model>Serializer, walking up STI) builds it; with no serializer, { id, created_at, updated_at }.
  • The event name's prefix does not reliably name the payload type: customer.* and admin_user.* are published from password-reset controllers, shipment.* from the fulfillment, digital.* from DigitalAsset.
  • (Before this plan.) About a dozen events build their payload by hand — order.canceled and order_group.completed merge notify_customer into the serializer output, the three *.password_reset_requested events and the two newsletter request events send bespoke hashes. The rest pass extra facts through metadata (e.g. seller.approved's requirements_overridden).
  • The webhook envelope is { id, name, created_at, data, metadata: { spree_version, … } }, signed HMAC-SHA256(secret, "{timestamp}.{body}").
  • WebhookPayloadRedaction keeps credentials out of the stored delivery log; WebhookEndpoint::CREDENTIAL_EVENTS makes the password-reset event opt-in only.

The catalog (spree_core)

Each event is declared once, next to the model whose record is the payload:

# spree/core/app/models/spree/order.rb
publishes_lifecycle_events
publishes_events :placed, :paid, :approved, :canceled, :shipped, :delivered, :fulfilled,
                 :resend_confirmation_email, :resend_digital_links_email
publishes_event :completed, deprecated_alias_of: 'order.placed'
  • Spree::Events.catalog holds one entry per name: name, payload_serializer (a class name, resolved on use like every Spree registry), credential (the permission key an endpoint needs to receive an event carrying a live credential — replaces CREDENTIAL_EVENTS), deprecated_alias_of, and group for the picker.
  • Lifecycle events register themselves from publishes_lifecycle_events (honouring only:/except:).
  • An event whose prefix is not the model's (customer.password_reset_requested from the user model) declares its full name: publishes_event 'customer.password_reset_requested', serializer: …, credential: 'write_customers'.
  • Extensions declare their events the same way and appear in the catalog, the picker and (through declaration merging, below) their own typings.

Hand-built payloads become event serializers

Every payload the catalog cannot describe with a record's Store serializer gets its own event serializer under spree/api/app/serializers/spree/api/v3/ (the *EventSerializer convention already used by MediaEventSerializer): PasswordResetRequestedEventSerializer and NewsletterSubscriberRequestEventSerializer read the token from serializer params (record.event_payload_for(name, reset_token: …)), and SavedReportEventSerializer replaces the Admin shape saved reports used. Facts that are not part of the record go in metadata (see Key Decisions). publish_event keeps accepting an explicit payload for extensions, but core stops passing hashes.

Generated TypeScript (@spree/sdk/webhooks)

A generator step (run from typelizer:generate) writes packages/sdk/src/webhooks/generated/events.ts from the catalog:

export interface WebhookEventMap {
  'order.placed': Order
  'order.canceled': Order
  'fulfillment.delivered': Fulfillment
  // … one entry per catalog event
}

export type WebhookEventName = keyof WebhookEventMap
export type WebhookEvent<N extends WebhookEventName = WebhookEventName> = {
  [K in N]: { id: string; name: K; created_at: string; data: WebhookEventMap[K]; metadata: WebhookEventMetadata }
}[N]

WebhookEventMap is an interface, so extensions add their events by declaration merging — the same convention the SDK types already follow.

constructWebhookEvent(rawBody, headers, secret, { schemas? }) verifies the signature and timestamp (reusing verifyWebhookSignature), parses the body and returns a WebhookEvent; checking event.name narrows event.data. Passing webhookEventSchemas from @spree/sdk/zod (generated next to events.ts) validates data at runtime. WebhookEvent<Order> — a data type instead of event names — keeps compiling for 5.x code, marked deprecated.

Admin API: the catalog as a resource

GET /api/v3/admin/webhook_events lists the catalog — { name, group, credential, credential_permission, deprecated, replaced_by } — for the endpoint form. It is a read-only resource (no custom action), gated by read_webhooks. The dashboard drops WEBHOOK_EVENT_GROUPS and builds its picker from this list, badging credential events and showing a deprecated event only to an endpoint still subscribed to it; free-text entry stays for events published outside the catalog.

Enforcement

  • A spec walks the catalog and asserts every entry resolves a serializer that renders a real record.
  • Publishing a name that is not in the catalog raises in development and test and logs a warning in production, so a new publish_event without a declaration fails its own spec.
  • spree/api/spec/lib/spree/api/webhook_event_types_spec.rb fails when the committed events.ts / schemas.ts no longer match the catalog, and when an event serializer has a back-office ancestor.

Migration Path

  1. Add Spree::Events.catalog and the publishes_events / publishes_event declarations; register lifecycle events automatically. Warn (do not raise) on undeclared names.
  2. Declare every core event; add event serializers for the hand-built payloads and switch their call sites. Replace CREDENTIAL_EVENTS with the catalog's credential flag.
  3. Turn the undeclared-name warning into a raise in development and test.
  4. Generate events.ts and the Zod schemas; add constructWebhookEvent; extend the CI drift check.
  5. Add GET /api/v3/admin/webhook_events with an integration spec (regenerating admin.yaml), and move the dashboard picker onto it.
  6. Document the event reference in docs/developer from the catalog.

Constraints on Current Work

  • New events must be published with a record whose Store serializer is the payload, or with a dedicated event serializer — never a hand-built hash.
  • Extra facts that are not part of the record belong in metadata, not merged into data.
  • Do not add new events to WEBHOOK_EVENT_GROUPS; it is removed by step 5.
  • Webhook payloads must stay on Store serializers. Back-office fields reach integrations through the Admin API, not the payload.
  • Extensions that publish their own events must declare them with publishes_event; once step 3 lands, an undeclared event fails their specs.

Open Questions

None. Webhook endpoint scopes were deliberately left out (see Key Decisions) and would be their own plan if revisited.

References

  • spree/core/app/models/concerns/spree/publishable.rb, spree/core/lib/spree/events/
  • spree/api/app/subscribers/spree/webhook_event_subscriber.rb, spree/api/app/services/spree/webhooks/deliver_webhook.rb
  • spree/core/app/models/concerns/spree/webhook_payload_redaction.rb
  • packages/sdk/src/webhooks.ts, packages/dashboard/src/schemas/webhook-endpoint.ts
  • Zod schemas for every SDK: spree/spree#14763
  • Comparable designs: Saleor subscription webhooks, Stripe thin events, Shopify protected customer data