# mod\_websub

Source: https://zotonic.com/docs/2703/mod_websub

URI: https://zotonic.com/id/2703

Language: en



WebSub keeps imported resources up to date when their source changes. A publishing site notifies subscribers instead of requiring them to poll for every update. `mod_websub` provides both publication and subscription for Zotonic resources, using the WebSub protocol.

When to use it
--------------

Use this module to synchronize resources between sites while preserving their original identity and applying the importing editor's permissions and options. Changes to collections can also update membership and order. Subscribing to a collection does not, by itself, keep every member's content up to date.

Both sites need reachable URLs for subscription verification and delivery; use HTTPS for deployment. Enable `mod_websub` on both sites when both run Zotonic. Other WebSub subscribers and hubs can participate, but Zotonic's resource importer requires its resource-export JSON schema. This module does not import arbitrary RSS, Atom or HTML documents as resources.

Getting started
---------------

1. Enable `mod_websub` on the publishing and importing Zotonic sites.
2. On the importing site, import the original resource and explicitly select automatic updates in the import dialog.
3. Choose how deeply to import connections. Select **Also subscribe to connected resources** if those resources should receive their own updates as well.
4. Check the imported resource's automatic-update status. A subscription becomes active only after the publisher verifies the callback, not merely after it accepts the request.

Use the resource editor's controls to start or stop updates. Stopping disables local automatic imports immediately and schedules remote unsubscription. **Content → WebSub subscriptions** provides an overview of incoming subscribers and outgoing subscriptions, including errors and a retry action.

Configuration and usage
-----------------------

Settings are per site under `mod_websub` in module configuration:

| Key                          | Default             | Valid range (seconds) | Purpose                                                                          |
| ---------------------------- | ------------------- | --------------------- | -------------------------------------------------------------------------------- |
| `subscription_retry_timeout` | `604800` (one week) | 1–2147483647          | Overall retry budget for subscription discovery, verification and unsubscription. |
| `push_quiet_seconds`         | `10`                | 0–86400               | Quiet period after changes before publishing.                                    |
| `push_deadline_seconds`      | `300`               | 1–86400               | Maximum batching delay from the first queued update.                             |

Missing or invalid settings use their defaults. For example:

```erlang
m_config:set_value(mod_websub, push_quiet_seconds, 10, Context).
```

Newer changes restart the quiet period, but not the original batching deadline. Each delivery contains the latest complete resource. These settings bound batching, not network delivery time or retry delays. When `mod_presence` is active, fresh editing heartbeats can defer publication within the same deadline; without it, ordinary quiet-time batching applies.

### Permissions and administration

Subscribers must be allowed to view the original resource. Public resources permit anonymous subscriptions; private subscriptions require explicit HTTP authorization and current resource access. Browser login cookies alone are insufficient. A private subscription authorizes delivery of the full JSON content to the verified callback.

`use mod_websub` controls access to the subscription overview. Local status, start and stop operations require resource edit permission. The overview can filter by direction, local resource ID, remote hostname, state and errors. It exposes no callback URLs, secrets or tokens. Resource edit pages show incoming subscriber counts and automatic-update controls. See `m_websub` for the model and Erlang APIs.

### Collections and connected resources

The saved connection depth and filters control which edges are synchronized. Publisher edge insertion, deletion and reordering trigger updates even without a resource edit. Newly referenced resources are imported after commit; existing imported members are reused rather than refreshed by a collection delivery.

The optional `is_subscribe_connections` setting defaults to false. When enabled, connected resources across all predicates receive independent subscriptions within the saved depth, including later additions. Removing a connection or stopping the parent does not stop those subscriptions. Stop them on the individual resources. Manual deletions remain respected unless the saved import options explicitly allow re-importing deleted resources. The README describes the full collection lifecycle.

Subscription and delivery behavior
----------------------------------

The subscriber discovers the source's hub and JSON topic, records intent, and requests a subscription. The publisher verifies a unique callback before activating it. Deliveries carry the full JSON representation with an HMAC-SHA256 signature. The receiver validates the callback and signature, queues import work, and acknowledges promptly. Public imports consume the signed export; credentialed imports refetch with the editor's source credentials. Source identity and current permissions are checked again inside the import transaction.

Renewal rediscovers the source and rotates the callback and secret. The previous callback remains active until the replacement verifies. Confirmation schedules a catch-up fetch to recover missed updates. Stopping immediately disables local imports, even while remote unsubscription is pending.

Subscription failures and unanswered verification back off from 10 seconds to 12 hours within the configured retry budget. The budget survives restarts; renewal, unsubscription and explicit retries start a fresh budget. Exhausted attempts stop with `retry_timeout`; a previous confirmed lease remains valid until expiry. Settings are read when work runs, so changing the budget does not immediately wake sleeping retries or restart exhausted attempts.

Notification delivery has a separate, fixed retry window: one week from the first attempt, never beyond lease expiry. Delays are 5, 20, 45 minutes and so on, capped at 12 hours. Newer queued versions preserve that window. Exhaustion discards the notification and records `retry_timeout`, but preserves the lease; later resource updates can start a new delivery window. Import queues and feed polling are not controlled by `subscription_retry_timeout`.

Identity and interoperability
-----------------------------

A resource's identity remains its language-less `m_rsc:uri/2`, such as `/id/name`. Imports retain it as their resource `uri` and subscription `source_uri`. The fixed JSON WebSub topic is stored separately in `topic_url`; it never replaces the semantic identity.

Discovery links advertise the JSON topic as `rel=self` and the hub as `rel=hub`. Authoritative resource exports also include optional `websub.hub` and `websub.topic` JSON convenience fields. External peers can use standard discovery and form fields without those extensions. Deliveries are complete `application/json` representations, not private change notices. The delivery's `result.uri` identifies the resource; its Link self identifies the topic.

Only authoritative resources publish. Imported copies do not advertise a local hub or relay updates as a new source. For A → B → C, C should subscribe to A rather than B's imported copy. Local self-subscriptions are rejected. The README explains third-party interoperability, topic migration and circular-subscription boundaries.

Security and deployment
-----------------------

Outbound requests use verified TLS and explicit redirect handling. Destinations are checked on every hop; private, loopback, link-local and reserved addresses are rejected. Development `.test` peers may use loopback/private addresses and self-signed TLS. Other destinations retain the normal checks. HTTPS downgrades are refused, and cross-origin GET redirects drop credentials for the rest of the chain.

Subscriber callbacks must use DNS hostnames; IP literals are rejected by Zotonic's local policy. Callback verification and delivery are anonymous. `mod_oauth2` consumer tokens can authenticate source fetches and the source's same-origin hub, using the original HTTPS URL and subscribing user. Token lookup and renewal remain owned by `mod_oauth2`; current group restrictions are preserved for delivery access.

DNS validation is currently a preflight check, not connection-address pinning. DNS rebinding between validation and connection remains an open limitation.

Hub admission deduplicates pending requests and bounds each site to 120 new verification tasks per minute and 1000 queued tasks. Limits are serialized in the database across nodes; overload returns 503 before accepting work. Imports recheck identity and permissions under the resource lock, and disabled users cannot continue automatic subscription work.

Implementation and lifecycle
----------------------------

`controller_websub` handles hub requests, verification and deliveries; `controller_websub_topic` serves the fixed JSON representation. Resource-header and export observers advertise discovery links, import observers apply explicit subscription choices, and resource/edge observers queue publication.

`m_websub` provides checked APIs and queue processing. Subscription intent, leases, retry state and work queues persist in the database. A per-site server tracks a dirty flag and next due time; second ticks avoid database work while idle. A unique, monitored sidejob processes due work. Signals are sent after transaction commit, ten-minute scans reconcile persisted work, and daily maintenance cleans up records.

Separate export revisions advance for resource and edge changes without changing the resource's edit version for edge-only updates. Schema upgrades preserve queues and identity. The README contains wire examples, storage details, operational limits and regression-test commands.

License: 

Attribution: 

Related resources: https://zotonic.com/api/agent/related/2703?language=en


## API access

- [API help](<https://zotonic.com/api-help>)
- [OpenAPI specification](<https://zotonic.com/openapi.json>)
- [This resource as JSON](<https://zotonic.com/api/agent/resource/2703?language=en>)
