Lifecycle events and reliable integrations
v0.5 adds a durable lifecycle feed, signed webhooks, and application recovery examples. The runtime publishes committed facts through both transports with the same event IDs and payload schema. The example application stores pending audit records with its business changes. Its lifecycle consumer stores receipt before acknowledgment and processes cleanup through a local transaction.
Start the reference deployment
Run
npm ci.Run
npm run build.Start the deployment:
docker compose -f compose.yaml -f deployments/compose.administration.yaml -f deployments/compose.events.yaml up -d --build --waitOpen the application.
Select Recovery owner sign-in.
Enter
recoveryanddev-only-recovery-owner-password.Select Application integrations.
Copy the displayed webhook endpoint.
Open administration from the application.
Open Webhook subscriptions.
Create a subscription with that endpoint and the displayed user event types.
Copy its one-time signing secret.
Return to Application integrations.
Install the signing secret.
The runtime reaches the consumer at http://event-consumer:3020/webhooks/org_events inside Compose.
Port 3020 also exposes the consumer on the local machine for development tests.
The example's signing-secret input stores an encrypted value in its application database.
The runtime stores its own encrypted signing key separately.
No commercial service is required.
All included credentials are public development fixtures.
Existing PostgreSQL volumes require these databases before startup:
docker compose exec postgres createdb -U enterprise enterprise_events
docker compose exec postgres createdb -U enterprise enterprise_example_events
docker compose exec postgres createdb -U enterprise enterprise_portal_eventsThe fixture prepares dedicated oe-v05-idp and oe-v05-broker realms.
The upstream Alice account uses alice and dev-only-saml-alice-password.
Provision her through /scim/v2/customer-directory with externalId: employee-alice before login.
The development directory credential is dev-only-events-directory-key-change-me.
SSO, password verification, and MFA retain the existing identity-provider boundaries.
Event envelope and schemas
A lifecycle event uses the CloudEvents structured JSON envelope:
{
"specversion": "1.0",
"id": "evt_example",
"source": "urn:open-enterprise:lifecycle",
"type": "user.deactivated",
"time": "2026-11-08T12:00:00+00:00",
"datacontenttype": "application/json",
"organizationid": "org_events",
"actorid": "directory:customer-directory",
"resourcetype": "user",
"resourceid": "usr_example",
"schemaversion": 1,
"resourceversion": 4,
"sequence": 27,
"data": {"user_id": "usr_example", "active": false, "deleted": false}
}Envelope version and payload schema version have separate meanings.
specversion describes the CloudEvents representation; schemaversion describes this lifecycle payload contract.
Event IDs remain stable across transport retries, process restarts, and authorized replay.
Delivery and attempt IDs identify delivery operations separately.
Resource versions increase within each organization, resource type, and resource ID.
Version zero identifies an imported reconciliation baseline.
The schema-one catalog contains these families:
| Event types | Resource and payload |
|---|---|
organization.created, organization.updated |
Organization ID, name, and slug |
user.provisioned, user.updated, user.activated, user.suspended, user.deactivated |
Canonical user ID and effective active state |
membership.created, membership.updated, membership.deleted |
Canonical membership, user, role, status, and provisioning source |
group.created, group.updated, group.deleted |
Group ID and local or directory identity |
group_membership.added, group_membership.removed |
Group ID and canonical user or local principal reference |
role.created, role.updated, role.deleted |
Role name and permission names |
role_assignment.created, role_assignment.updated, role_assignment.deleted |
Assignment ID, principal, role, scope, and inheritance |
resource.created, resource.updated, resource.deleted |
Registered resource and parent references |
resource_grant.created, resource_grant.updated, resource_grant.revoked |
Grant ID, principal, resource, actions, and inheritance |
relationship.created, relationship.updated, relationship.deleted |
Relationship ID, endpoints, and relation |
policy.activated |
Active portable policy version |
session.created, session.revoked |
Session ID, canonical user, expiration, and revocation state |
directory.created, directory.updated |
Directory ID, login connection, default role, and group mappings |
directory.credential_created, directory.credential_revoked |
Credential and directory IDs; no credential value |
configuration.drafted, configuration.tested, configuration.activation_requested, configuration.failed |
Configuration version ID and lifecycle status |
configuration.activated |
Active organization configuration version, including the selected SSO configuration |
configuration.certificate_expiring |
Connection ID, active configuration version, certificate SHA-256, expiry time, and notice_days (90, 60 or 30) |
oauth_grant.created, oauth_grant.revoked |
Grant ID, canonical user, internal and OAuth client IDs, resource, scopes, offline flag, expiration, and revocation reason |
oauth_client.blocked, oauth_client.allowed |
Internal client ID and the organization's block state |
Deleted resources include a deletion marker.
User active reflects the effective membership and directory gate, including a local suspension.
The event type identifies the source operation; consumers use the supplied state and resource version when applying it.
Session expiration remains governed by expires_at; it does not require an asynchronous event.
An OAuth grant event appears when a grant for the organization becomes usable and when it is revoked.
Suspension, directory deactivation, and client blocks end grants through synchronous gates, so consumers also see user.* and oauth_client.* events for those changes, not a revocation of each grant.
Payloads exclude passwords, bearer credentials, signing secrets, raw SAML metadata, and trusted attribute values. Events do not mirror arbitrary audit submissions or external audit data. Use authorized resource APIs when an integration needs additional profile or policy information. The catalog endpoint provides the exact types supported by the deployed runtime.
Transactional publication and ordering
PostgreSQL captures lifecycle facts in the same transaction as their source changes. Deferred capture reads the final transaction state and coalesces changes to the same resource. A rolled-back state change leaves no event or resource-version update. A publication failure also prevents the source transaction from committing.
Each organization has a transaction-bound sequence counter. A later writer cannot commit a larger sequence before the earlier writer releases that counter. The publisher moves outbox records into the retained log in sequence order through another atomic transaction. It creates matching initial webhook deliveries in that same publication transaction. Publisher restarts resume the pending outbox.
The Events API orders by publication sequence within one organization. It does not promise a total order across organizations. Webhook arrival order does not establish resource-version order. Consumers store the newest applied version and reject older versions for that resource.
Publication can lag a source commit. Access revocation continues through the existing synchronous session, directory, and permission gates. An unavailable consumer or webhook endpoint cannot keep Alice authorized.
Poll the Events API
The backend credential needs an explicit organization and event-read authority.
events:read permits all lifecycle types for that organization.
A scope such as events:read:user.deactivated restricts a service to that type.
Multiple type scopes form the permitted set.
An omitted filter uses that set; an explicit filter cannot expand it.
User and portal access uses the current events:read permission and the portal's original operation scope.
const batch = await enterprise.events.list("org_events", {
types: ["user.activated", "user.deactivated"],
cursor: savedCursor,
limit: 100,
});
await applicationDatabase.transaction(async (tx) => {
for (const event of batch.items) {
await insertDurableInbox(tx, event); // Unique organization and event ID.
}
await saveCheckpoint(tx, batch.next_cursor);
});Process the durable inbox separately.
A cursor advances only after every preceding returned event enters durable processing.
Empty pages can advance across events excluded by the filter.
The page reports has_more, retention, the page limit, and retained/head cursors.
Reusing a retained cursor replays its subsequent events.
Cursors bind the organization, lifecycle feed, effective filters, and format version.
Changed filters or a different organization reject the cursor.
A type-scope reduction also changes the effective filter.
Expired cursors return HTTP 410 with code cursor_expired.
The runtime never silently resets an expired checkpoint.
Recover an expired cursor
- Pause the consumer's normal processing.
- Create a snapshot through
enterprise.events.snapshots.create(org, types). - Fetch every page with the same organization and types.
- Replace the integration's materialized resource state with the complete snapshot.
- Store each resource's version.
- Save the snapshot's checkpoint in that same application transaction.
- Resume polling from that checkpoint.
Snapshots capture minimal canonical resource state and a consistent committed sequence. The checkpoint can include events whose outbox publication is still pending. The feed accepts that checkpoint and waits for subsequent events without moving it backward. Later deliveries with older resource versions cannot overwrite the applied snapshot.
A snapshot expires after ten minutes and permits pages of 100 resources. The implementation limits one snapshot to 10,000 resources. Partition requested event types when that limit applies. If any page expires or fails, discard the partial result and create a new snapshot. Do not advance the checkpoint after a partial replacement.
The reference consumer implements this procedure through Reconcile retained state. It marks expired feeds as requiring reconciliation instead of dropping changes. Hydrate extra fields through the appropriate authorized resource APIs; the lifecycle snapshot deliberately excludes sensitive values.
Read every organization with one cursor
GET /v1/events reads the feed across every organization the calling service may act on: its configured organizations and, with created_organizations, the ones it created through POST /v1/organizations or self-service onboarding.
It takes the same cursor, types and limit parameters and returns the same page.
Events of one organization keep their order, and events of different organizations interleave in publication order.
Each event still carries its organization's sequence and its resource's resourceversion.
The service needs events:read, or events:read:<type> scopes that limit it the same way as the organization feed.
A vendor-wide cursor binds the service and the filter, so it does not work in an organization's feed, and an organization cursor does not work here.
The vendor-wide feed reads the same event log and follows retention_days.
A cursor older than the oldest retained event returns HTTP 410 cursor_expired.
User profiles
Add profile=true to put a profile object into the data of user events: user_id, external_id, email, email_verified and display_name.
It needs the profiles:read service scope, because it is personal data.
The runtime adds the user's current profile when it serves the page, so every page carries profiles at least as new as the page before.
A user who left the organization (deleted: true) gets no profile.
A change to a user's email, display name or external ID, or a confirmed sign-in email, is a user.updated in every organization the user belongs to.
email_verified is true for a local account's address once its owner confirmed it, and for an address that an organization's identity provider or directory asserted.
Current state
GET /v1/events/state lists the current state of the service's resources for first setup and for recovery after cursor_expired.
It has no size limit: pass each page's next_page_token until it is absent.
types selects resource types the way snapshot types do, limit takes up to 1000, and profile=true adds profiles to user resources.
Every page returns the same checkpoint, a vendor-wide cursor taken before the listing started.
Once the last page is stored, poll GET /v1/events from the checkpoint with the same types.
Changes made during the listing come again from the feed, so apply an event only when its resourceversion is newer than the stored version.
Webhooks that say when to poll
POST /v1/event-subscriptions registers an endpoint with a service key.
It needs the subscriptions:write and events:read scopes and returns the Standard Webhooks signing secret once.
When the service's organizations have new events, the runtime sends a signed notice of type events.available, at most about once a second.
The notice carries no events: poll the vendor-wide feed when it arrives.
A failed notice is retried with the same backoff as event deliveries, and the next success covers everything since the last one.
GET /v1/event-subscriptions lists the service's subscriptions with their last status, and DELETE /v1/event-subscriptions/{id} revokes one.
The runtime audits both in the deployment audit log.
Send one organization's changes to a webhook
POST /v1/organizations/{org}/event-subscriptions sends every event of the chosen types to an endpoint.
This covers directory changes: user.provisioned, user.updated, user.deactivated, membership.* and group_membership.* arrive as SCIM requests change the directory.
Administrators create subscriptions in the admin portal.
An application backend can create them too, with a service key that holds subscriptions:write for the organization.
A service may choose only event types it can read, through events:read or the matching events:read:<type> scopes, and the audit log names it as service:<id>.
The service manages the subscription with the same update, revoke, rotation and replay calls as an administrator.
Set include_profile: true to add the user's profile to user events, with the fields described in user profiles.
A service needs profiles:read to turn it on.
The runtime reads the profile when it sends each attempt, so a retry or replay carries the profile as it is then, under the same event ID.
The stored event, the feed and the delivery history keep the body as published.
Verify and acknowledge webhooks
Requests use the Standard Webhooks HMAC scheme over the event ID, delivery timestamp, and exact body.
The headers are webhook-id, webhook-timestamp, and webhook-signature.
webhook-delivery-id identifies the individual attempt.
Successful acknowledgment requires an HTTP 2xx response after durable receipt.
import { verifyWebhook } from "@open-enterprise/sdk/webhooks";
const event = await verifyWebhook({
payload: rawRequestBody,
headers: request.headers,
secrets: configuredSigningSecrets,
});
await applicationDatabase.transaction(async (tx) => {
await insertDurableInbox(tx, event);
});
response.status(202).end();Supply raw bytes before JSON parsing or reserialization. The SDK checks the signature, event identity, supported envelope, and timestamp tolerance. The default tolerance is five minutes. A valid signature does not provide deduplication; the application's unique event key provides that protection.
The reference receiver checks the URL organization against the authenticated event organization. It compares duplicate payloads as JSON values because feed and webhook JSON formatting can differ. Reusing an event ID with different content returns a conflict. The processing worker commits the processed-event record, resource version, and cached-view cleanup together. Its cleanup deletes only demonstration cache entries. Application authorization remains in the runtime.
Delivery limits and recovery
The default delivery configuration uses eight attempts, a five-second HTTP timeout, and one request per subscription endpoint per second. The reference fixture uses a shorter interval and retry base for reproducible tests. Backoff doubles from its configured base, adds bounded jitter, and stops at one hour per delay. The dispatcher allows eight concurrent jobs per runtime process and one live lease per subscription. The database preserves subscription pacing across processes. Each claim expires after 30 seconds.
A worker interruption leaves its delivery recoverable after the lease expires. A replacement worker records the interrupted attempt and uses a new attempt ID. An old claim cannot acknowledge a replacement claim's work. The event ID remains unchanged, and so does the body unless the subscription adds profiles. All non-2xx responses, including redirects, count as failures. Responses and transport errors expose bounded diagnostic codes rather than response bodies or credentials.
Exhausted deliveries remain failed until an authorized administrator replays the retained event. Replay creates a new delivery record with the original event ID and payload. A new subscription receives future changes after its creation; retained history requires explicit replay or polling. Pausing a subscription preserves queued work. Revoking a subscription cancels pending work and prevents future scheduling. A request already in flight can complete after a configuration change.
The portal requires current subscriptions:read, subscriptions:write, or events:replay authority for the corresponding operation.
Secret rotation supports an overlap from zero to 86,400 seconds.
Requests during overlap contain signatures from the current and previous key.
Only two unexpired keys are supported.
Another overlapping rotation requires the previous overlap to end; zero overlap explicitly revokes earlier keys.
Update the consumer's accepted keys within the same bounded window.
Egress and stored secrets
Production webhook destinations require public HTTPS addresses. The adapter rejects private, loopback, link-local, and encoded private network destinations. Encoded destinations include IPv4-mapped, NAT64, and 6to4 IPv6 addresses that carry a private IPv4 address, and all Teredo addresses. It checks the actual connection's DNS results, disables implicit proxies, and never follows redirects. An optional exact-origin allowlist further restricts delivery. Development mode requires an explicit allowlist for local HTTP fixtures.
EVENTS_SECRET_KEY contains 32 random bytes encoded as unpadded base64url.
It encrypts stored signing keys.
Feed cursors use a separate HMAC key that the runtime derives from it with HKDF.
Protect it separately from database backups.
The portal returns a new signing secret once and never lists stored plaintext.
The reference application encrypts its consumer copy with its own server secret and organization binding.
To rotate the master key, set secret_key_env to the new key and add the old key's variable to previous_secret_key_envs.
The runtime encrypts new signing keys with the new key.
It still decrypts signing keys and accepts feed cursors that a previous key protects.
For a rolling deployment, first add the new key as a previous key on every replica, then make it current.
Then run enterprise-runtime reencrypt to seal every stored signing key with the new key; see rotate master keys.
Removing a key invalidates the cursors it signed.
Create new reconciliation snapshots after that change; do not silently reset application checkpoints.
Cursors from earlier releases, which the master key signed directly, stay valid while that key is configured.
Retention and disabled modules
Event retention is independent of audit retention. The default is 90 days; the reference events deployment uses seven days. Retention uses capture time and advances an explicit organization retention floor. It prunes expired feed records, unpublished outbox records, related delivery history, and old tombstone payloads. Minimal resource IDs and version counters remain, so recreating a resource cannot reset its version. Expired tombstones are excluded from reconciliation snapshots. Current resource state remains available for reconciliation. Retention runs periodically, so removal can lag the configured period.
Canonical state changes retain transactional capture even when the HTTP events module is disabled. Delivery remains disabled without event configuration. The ordinary maintenance task then applies the 90-day default to pending capture records. Re-enabling events publishes the retained backlog and preserves the retention floor.
Application audit outbox
The reference application's project, document, invoice, and approval changes enqueue audit input in the same application transaction. The input contains a stable event ID, occurrence time, actor, and resource reference. A separate worker calls the existing idempotent audit ingestion API. A failed or interrupted acknowledgment leaves the original input available for retry.
The example uses 30-second worker leases, at most 20 attempts, and a 23-hour submission window. Failed entries remain visible for investigation instead of disappearing. The original payload and event identity must remain unchanged during recovery. Keep the runtime's audit retention longer than this retry window. Acknowledged entries belong to the application's own retention and archival policy. The example retains them for inspection and does not automatically discard failed business evidence.
Application transactions and runtime transactions remain independent.
The outbox closes the business-to-audit durability gap without a distributed transaction.
Other applications must implement their own outbox alongside their business database.
The exported AuditInput type supports their persisted delivery input.
Verification
bash scripts/test.sh
npm run test:e2e:eventsThe browser test provisions Alice through real SCIM and signs in through a real SAML broker. It stops the consumer, deactivates Alice, verifies access denial, and restarts the runtime and consumer. It verifies durable delivery attempts, duplicate receipt, cleanup once, portal replay, secret rotation, and subscription revocation. The second flow pauses audit submission, commits a project, and recovers one audit record with the original event ID. Database and SDK tests cover rollback, concurrent commits, cursor expiration, snapshot recovery, stale versions, egress, and retry exhaustion.
References: CloudEvents 1.0.2, Standard Webhooks.