qiick / laravel-outbound
SSRF-safe outbound HTTP and Standard Webhooks signing for qiick Laravel products.
Requires
- php: ^8.3
- ext-curl: *
- ext-intl: *
- ext-mbstring: *
- guzzlehttp/guzzle: ^7.15.2 || ^8.0.1
- illuminate/contracts: ^12.71.0 || ^13.40.0
- illuminate/database: ^12.71.0 || ^13.40.0
- illuminate/http: ^12.71.0 || ^13.40.0
- illuminate/notifications: ^12.71.0 || ^13.40.0
- illuminate/support: ^12.71.0 || ^13.40.0
Requires (Dev)
- larastan/larastan: ^3.3.1
- laravel/pint: ^1.30.4 <1.31.0 || ^1.0.0
- nunomaduro/collision: ^8.5
- orchestra/testbench: ^10.0 || ^11.0
- pestphp/pest: ^4.0
- pestphp/pest-plugin-mutate: ^4.0
- phpstan/phpstan: ^2.1.11
Suggests
None
Provides
None
Conflicts
- illuminate/mail: <12.71.0 || >=13.0.0,<13.40.0
- league/commonmark: <2.10.2
- paragonie/random_compat: <2.0
- symfony/http-foundation: <6.4.50 || >=7.0.0,<7.4.23 || >=8.0.0,<8.1.11
- symfony/http-kernel: <6.4.51 || >=7.0.0,<7.4.24 || >=8.0.0,<8.1.12
- symfony/mailer: <6.4.40 || >=7.0.0,<7.4.24 || >=8.0.0,<8.1.12
- symfony/mime: <6.4.49 || >=7.0.0,<7.4.22 || >=8.0.0,<8.1.10
- symfony/polyfill-intl-idn: <1.38.1
Replaces
None
This package is auto-updated.
Last update: 2026-12-04 17:40:22 UTC
README
qiick/laravel-outbound
PHPStan at max and the existing CI checks cover PHP. CodeQL covers GitHub Actions and JavaScript/TypeScript.
Status:
0.2.0-beta.4. Pre-1.0: minor versions may break. Prefer a tagged release overdev-develop. See CHANGELOG Upgrade notes.
SSRF-safe outbound HTTP and Standard Webhooks signing for qiick Laravel products.
Status
Released as 0.2.0-beta.4 against the approved design
(projects/qiick/packages/laravel-outbound-design.md in the qiick knowledge
base). Public APIs, evaluation order and security properties follow SemVer;
before 1.0.0, a minor may break.
Purpose
One canonical path for:
-
SSRF-safe outbound HTTP — curl-style IPv4 reading, metadata blocking (including Alibaba/Oracle even when private hosts are allowed), resolve-all DNS checks, and
CURLOPT_CONNECT_TOpinning (neverCURLOPT_RESOLVEalone). -
Standard Webhooks — symmetric
v1signing and verification over the exact raw body bytes, multi-secret rotation bounds, and pure retry schedules. -
Webhook delivery storage — the five delivery tables ship as package migrations, so every product stores endpoints, secrets, subscriptions, deliveries and attempts in one shape (see Webhook tables).
-
Webhook delivery — fan-out to subscribed endpoints, signed attempts through the pinned client, the Standard Webhooks retry schedule with
Retry-After, and per-endpoint concurrency (see Webhook delivery).
Non-goals for v1: asymmetric Standard Webhooks (v2a; its columns are
reserved), global helpers, a hard dependency on laravel/framework. The
rest of the delivery layer required before 1.0 (the egress proxy) lands in a following pull request.
Threat model
Attackers who control a destination URL (webhook endpoint, IdP discovery URL, user-supplied fetch target) must not reach:
- Cloud metadata (
169.254.169.254,fd00:ec2::254,100.100.100.200,192.0.0.192,metadata/metadata.google.internal) - Loopback, private, CGNAT, link-local, ULA, or unspecified addresses when private hosts are disallowed
- Transition prefixes that re-embed IPv4 (NAT64, 6to4, Teredo)
- DNS-rebinding races (pin the checked address with
CURLOPT_CONNECT_TOon every hop; redirects never use transport auto-follow) - Signature forgery on inbound Standard Webhooks (exact raw body, integer
timestamps, tolerance window,
hash_equals); consumers must also dedupewebhook-idwithin the tolerance window
WebhookDeliveryCoordinator enforces per-endpoint concurrency, the webhook
timeout, Retry-After, 410 and auto-disable after repeated failures.
Requirements
- PHP ^8.3 with
ext-curl,ext-intl, andext-mbstring - illuminate/contracts, illuminate/http, illuminate/support ^12 or ^13
- guzzlehttp/guzzle ^7.15.2 or ^8.0.1
Install
composer require qiick/laravel-outbound:^0.1 php artisan vendor:publish --tag=outbound-config
The service provider is auto-discovered.
Run php artisan outbound:check in the deploy pipeline (fleet convention F2):
it exits 1, one line per problem, when the webhook tables or the
configured users table are missing, when a webhook table still has the
columns of an older beta, or when the cache cannot atomically
release a webhook id claim by its owner. It also flags schedules
that still use the removed beta name outbound:webhooks:work or
outbound:webhooks:prune, with the replacement. A config value of the wrong type already
stops the boot, naming the key.
Public API
SSRF
use Qiick\Outbound\Ssrf\RemoteUrlGuard; use Qiick\Outbound\Ssrf\UrlGuardOptions; use Qiick\Outbound\Testing\FakeHostResolver; $guard = new RemoteUrlGuard(new FakeHostResolver(['example.test' => ['93.184.216.34']])); $destination = $guard->authorize('https://example.test/hook'); // $destination->guzzleCurlOptions() → CURLOPT_CONNECT_TO pin only
assertBrowserUrlIsSafe() checks scheme and credentials for URLs the server
never connects to (browser redirects).
A product adds metadata or control-plane hosts of its own platform to the ones
the guard always refuses, also with private hosts allowed, by binding a
Contracts\MetadataPolicyContract. The guard normalises
each entry (a lowercased name without its trailing dot, a canonical IP) and
takes the union with its own list, so a policy can never unblock a host.
$this->app->instance(MetadataPolicyContract::class, new class implements MetadataPolicyContract { public function additionalMetadataHosts(): array { return ['metadata.platform.internal', '10.255.0.1']; } });
Pinned HTTP client
use Qiick\Outbound\Http\HttpRequestOptions; use Qiick\Outbound\Http\OutboundRequest; use Qiick\Outbound\Http\PinnedHttpClient; $client = app(PinnedHttpClient::class); $response = $client->send( 'POST', 'https://example.test/hook', function (OutboundRequest $request): void { $request->asJson(['event' => 'created'])->accept('application/json'); }, new HttpRequestOptions(followRedirects: true, maxRedirects: 3), );
The configure callable receives a package-owned {@see OutboundRequest} only
(headers, query on the authorised URL, raw/json/form/multipart body, Accept /
Content-Type). It never sees Laravel's PendingRequest, so it cannot change
the URI, timeouts, proxy, pin, redirects, verify, or stream. Transport settings
are re-applied by wrapping the curl handler.
Transport never auto-follows; when followRedirects is on, each Location is
resolved, SSRF-checked, and re-pinned. Cross-origin redirects are off by
default; when opted in, only 301/302/303 are allowed (body dropped) — cross-origin
307/308 are always refused, and only Accept / Accept-Language / User-Agent /
Content-Type (when a body is kept) are forwarded. Caller query values apply to
the first hop only. OutboundRequest refuses Host / X-Host / X-Original-Host and routing headers (X-Forwarded-*, Forwarded, X-Original-URL, X-Rewrite-URL). The
client uses a private HTTP factory so shared Http::globalOptions(['handler'])
cannot bypass the pin. Environment proxies are disabled so they cannot bypass
CONNECT_TO. Timeout caps and the total redirect deadline come from
outbound.http.* config and cannot be raised per call.
A transport failure throws OutboundHttpException with a fixed message and
transportErrorKind(): timeout (curl or the chain deadline), tls, dns
or connection, read from the curl errno. Neither the message nor the
exception chain names the host, the pinned address or the URL. Refusals the
client makes itself (response size, redirect rules) have no kind.
Egress proxy. Set outbound.http.egress_proxy (OUTBOUND_EGRESS_PROXY,
for example http://user:secret@egress.internal:3128) to send every request
through a filtering forward proxy, as Standard Webhooks "Server side request
forgery (SSRF)" recommends. It is deployment config, never set per endpoint
or per call. Null sends directly. The supported Guzzle floors (7.15.2 and
8.0.1) keep the HTTP(S)_PROXY and NO_PROXY environment variables out of
both paths. Any value other than an HTTP(S) proxy URL, null or an empty string
stops the boot.
- The guard still authorises and pins every destination, so the proxy adds a
network-layer control without replacing the application one. curl is
forced into tunnel mode, also for plain
http://: the proxy receivesCONNECT <guard-approved address>:<port>, never a URL or a host name to resolve, so it cannot be steered to an internal address the guard refused. A refused destination never reaches the proxy. - Only
http://andhttps://proxies with a host and nothing after the port are accepted, checked at boot; a SOCKS proxy could resolve names itself. The proxy's own address is trusted infrastructure, not checked by the guard. Name the port: without one, libcurl uses 1080 for anhttp://proxy and 443 for anhttps://one. EgressProxykeeps the credentials out of string casts, dumps (dump(),dd(),var_export()), serialization, exception messages and exception traces; a proxy refusal surfaces as a transport error with the fixed messages above.
Isolated policies and testing
Use OutboundHttpStackData::make($hostResolver, limits: $limits) for an
isolated guard and client. The default requires HTTPS and refuses private
addresses. Set allowPrivateHosts and httpsOnly explicitly when the
integration has a different trusted deployment policy.
Http::fake() and Http::globalOptions() on the shared facade factory do not
reach PinnedHttpClient when the service provider binds a private factory. Each
transfer also strips a request-level handler from factory global options so a
poisoned factory cannot bypass CONNECT_TO on Guzzle 7. In tests, pass
Qiick\Outbound\Testing\FakeOutboundHttpFactory::fake([...]) as the
httpFactory argument to OutboundHttpStackData::make().
Standard Webhooks
use Qiick\Outbound\Webhooks\StandardWebhookSigner; use Qiick\Outbound\Webhooks\StandardWebhookVerifier; use Qiick\Outbound\Webhooks\WebhookSecret; $secret = WebhookSecret::parse('whsec_…'); // 24–64 raw bytes after base64 $signer = app(StandardWebhookSigner::class); $signed = $signer->sign($msgId, $unixSeconds, $rawBody, [$secret]); $verifier = app(StandardWebhookVerifier::class); // cache-backed webhook-id dedupe $claim = $verifier->verify( $rawBody, $signed->headers['webhook-id'], $signed->headers['webhook-timestamp'], $signed->headers['webhook-signature'], [$secret], new DateTimeImmutable('now'), // Required: identifies the secret or endpoint, never shared by tenants. dedupeScope: 'orders-webhook', );
Signing uses exact raw body bytes (msg_id.timestamp.body). Multi-secret
rotation emits space-separated v1,<base64> signatures. Verification fails
closed on non-integer timestamps, skew outside the tolerance window (both
directions), oversize payloads, too many signatures/secrets, and uses
hash_equals against every candidate (no early return). Timestamp tolerance
alone is not replay protection: after a signature match the verifier
atomically claims (scope, webhook-id) until timestamp + tolerance + 1
(covers sender skew and holds through the last accepted second). The
seen-id store supports Laravel database and Redis owner-checked locks,
with keys under the versioned prefix outbound:whid:v1:.
With the database driver, apply Laravel's cache and cache-lock migrations.
Array locks are available in tests. outbound:check reports an unsupported
driver. Resolving the default SeenWebhookIdStoreContract with that driver throws
UnsupportedWebhookIdCacheStoreException. Catch the typed duplicate,
storage and invalid-signature exceptions in the receiver.
verify() requires a dedupe store and returns the WebhookIdClaim it won. A
consumer whose processing fails after that gives it back with
SeenWebhookIdStoreContract::release($claim), so the sender's retry or redelivery
(same webhook-id) is processed instead of being dropped as a duplicate.
Release compares the owner token and deletes in one storage operation.
A replacement owner keeps its lock if the previous owner releases after
expiry. A store failure throws WebhookIdStoreFailedException.
The signer and the verifier refuse a webhook-id that is empty, holds a .
(it separates the signed fields) or a control character. WebhookMessage
checks the same at construction, plus at most 191 bytes of valid UTF-8 (the
stored event_id), and requires the event type to be at most 191 bytes of
dot-separated segments of letters, digits and underscores (invoice.paid,
Standard Webhooks "Event types").
Two events carry no secret and no body: WebhookSignedEvent (webhook id,
timestamp, signature count, body length) after each signing, and
OutboundRequestBlockedEvent (host and the guard's reason, never the path
or query) when PinnedHttpClient's guard refuses a destination, for
alerting on attempts to reach internal addresses.
Both are dispatched synchronously, before the refusal is thrown or the
signature returned, so their listeners must not throw: make them
ShouldQueue or catch inside. A listener that throws replaces the
UnsafeUrlException or WebhookException a direct caller expects (the request still
fails closed and nothing is sent), and in the delivery coordinator the
attempt is recorded as internal_error instead of its real outcome. The
host in OutboundRequestBlockedEvent comes from parse_url(), not from the
guard's own parse: rely on it for alerting, not for decisions.
WebhookSecret::parse() requires the whsec_ prefix. Secrets use
#[\SensitiveParameter] and are redacted in __debugInfo / string casts.
Do not serialize / var_export / (array) a WebhookSecret — persist a
reference (secret id) or the canonical whsec_ string from serialized().
(var_export / (array) dumps cannot be prevented by magic methods.)
Official vectors: tests/Fixtures/StandardWebhooks/ (standard-webhooks
@ 3d65b1824b6697f05a5a4584e7062bd23512fc8e).
Secret rotation
An endpoint signs with its signing set: the primary secret plus the
non-revoked secrets whose expires_at is still in the future, primary first,
at most outbound.webhooks.max_secrets (4). SecretRotator keeps exactly one
primary per endpoint, under a row lock on the endpoint:
use Qiick\Outbound\Webhooks\SecretRotator; use Qiick\Outbound\Webhooks\WebhookSecretResolverContract; $rotator = app(SecretRotator::class); $secret = $rotator->issue($endpoint); // first primary $secret = $rotator->rotate($endpoint); // old primary signs 24 h more $secret = $rotator->rotate($endpoint, graceSeconds: 0); // leaked: old key stops now $rotator->revoke($oldSecret); // a grace secret stops now $secret->secret; // the whsec_ string: show it once, never again $signingSet = app(WebhookSecretResolverContract::class)->signingSetFor($endpoint); $signer->sign($msgId, $unixSeconds, $rawBody, $signingSet->secrets()); $signingSet->secretPublicIds(); // record which secrets signed, never their bytes
max_secrets is a hard limit of 1–4: a larger value is refused when the
application boots. An issue or a rotation that would push the set past it is
refused: revoke an old secret first. The primary cannot be revoked; rotate
with a zero grace period instead. A deleted endpoint gets no new secret, but
its old secrets can still be revoked. Grace periods are measured in UTC: the
package models store and read every date as UTC whatever app.timezone is,
so a daylight-saving change never stretches or cuts one. The resolver fails closed when an endpoint has no active
primary or more than one. Only v1 rows with a valid whsec_ secret sign. The v2a scheme is reserved. A product that keeps its secrets elsewhere binds its own WebhookSecretResolverContract.
Webhook delivery
use Qiick\Outbound\Delivery\WebhookDeliveryCoordinator; use Qiick\Outbound\Webhooks\WebhookMessage; app(WebhookDeliveryCoordinator::class)->dispatch( new WebhookMessage('msg_'.Str::ulid(), 'invoice.paid', now()->toDateTimeImmutable(), ['invoice' => $invoice->public_id]), scope: $project->public_id, // the product's scope column value; omit for instance scope subjectPublicId: $customer->public_id, // the person the event is about, if any (see Erasure) ); // routes/console.php Schedule::command('outbound:work-deliveries')->everyFiveSeconds();
dispatch() stores one pending delivery per active endpoint subscribed to the
type (or to *), with the exact body every attempt signs; dispatching the same
message again creates nothing. outbound:work-deliveries takes up to --limit
(50) due deliveries, and with --max-seconds starts no attempt once that
long has passed (an attempt on the wire finishes, so a run can overrun by one
send); it leases each delivery on its own right before its send, signs
each attempt with the endpoint's signing set
and a fresh webhook-timestamp, and POSTs it through PinnedHttpClient
only: SSRF guard, pinned address, no proxy, never a redirect. Retries are
driven by next_attempt_at, so the first retry is as punctual as the
schedule above, and a retry 24 h away survives a queue loss.
- Timeout:
outbound.webhooks.timeout_seconds(15 s, Standard Webhooks "Request timeouts"); an endpoint'stimeout_secondsoverrides it, never abovehttp.max_timeout_seconds, and the 30 s chain deadline still applies. Other outbound calls keephttp.timeout_seconds(5 s). - Failures: every non-2xx answer (3xx included: redirects are never
followed), timeout and connection error is retried on the schedule: the
endpoint's
retry_presetor the configured one,max_attempts(10 forstandard: 75 h 35 min) snapshotted at dispatch. A guard or signer refusal is recorded asrefusedand retried the same way, and so is an endpoint row the request cannot be built from (internal_error). 410 Gone stops the delivery at once (exhausted,gone) and disables the endpoint (see Auto-disable). - Retry-After (429, 502, 503, 504): jitter is applied to the schedule
first, then the retry never comes before the header's delay, plus up to
min(jitter, delay / 2). A delay above
retry_after_cap_seconds(24 h) stops automatic retries (exhausted,retry_after_exceeds_cap) instead of being shortened; values above 30 days read as 30 days, so a cap above that is never reached. Only the firstRetry-Aftercounts. All three HTTP-date formats are read (RetryAfter::parse()). - Concurrency and fairness: at most the endpoint's
max_concurrency(default_max_concurrency, 2) attempts in flight per endpoint, across workers. Each delivery is leased atomically just before its send, for the chain deadline plus a minute, so overlapping runs never send one twice, and a crashed worker's lease simply expires. A run takes at most each endpoint's concurrency from its backlog, so one busy endpoint (or tenant) cannot starve the others. - Throttle: an endpoint's
rate_limit_per_minute(null or 0: no limit; set by the product's code, not mass-assignable) caps the attempts started for it in a fixed one-minute window; a delivery over the limit stays due and goes out in a later run. After a 429, 502, 503 or 504 the endpoint's concurrency is halved (at least 1) until its next success. Both are decided under the same endpoint row lock as the concurrency, so parallel workers agree. - Private hosts:
ssrf.allow_private_hostsis the ceiling, and an endpoint reaches private hosts only when itsallow_private_hostsistruetoo. The column is never null and defaults tofalse, so turning the global setting on opens no endpoint by itself; it is not mass-assignable. - Records: each attempt row keeps the status, HTTP status, error code
(
http_status,gone,timeout,tls,dns,connection,transportfor a client refusal without a transport kind such as a response overmax_response_bytes,ssrf_refused,signing,request_refused,internal_error), sanitised message, the secrets that signed, duration,Retry-After, and only thecontent-type,retry-after,x-request-idanddateresponse headers, as valid UTF-8 without control characters, at most 255 characters each. The receiver'sX-Request-Idis stored inreceiver_request_id(string(128), token charactersA-Z a-z 0-9 . _ : -only): it is sanitised to that alphabet, then stored whole or null; it is never silently truncated. The response body is never stored. If the database still refuses the receiver's text, the attempt is stored without it: a delivered webhook is never sent again because of it. The endpoint's failure streak (consecutive_failures,failing_since,last_success_at) moves with every attempt.
Auto-disable
On by default: an endpoint that answers 410 Gone is
disabled at once; otherwise it is disabled after 5 days without a
successful attempt and at least 10 failed attempts in a row. Five days is
longer than one full 75 h schedule, so at least one delivery has used every
retry first. Thresholds below 1 are refused when the application boots. An
endpoint's auto_disable (null = inherit) overrides
outbound.webhooks.auto_disable.enabled; like created_by, it is not
mass-assignable, so only the product's own code sets it, never a request.
Only the receiver's failures count (an HTTP error or a transport error): a
refusal on the package's side (signing, the SSRF guard, an internal error)
leaves the streak as it is. A success another worker records while a
disable is being decided cancels it.
A disabled endpoint gets no new deliveries and its pending ones wait. Each
disable fires WebhookEndpointDisabledEvent (public id, reason, time) once,
so a product can add its own channels. The package also emails the
endpoint's created_by user, loaded with auth.providers.users.model
(WebhookEndpointDisabledNotification, queued), for automatic disables only;
turn that off with outbound.webhooks.auto_disable.notify_owner. To email
someone else (a team, an operations address), bind a
Contracts\WebhookEndpointNoticeRecipientsContract whose recipientsFor()
returns the notifiables, users or Notification::route('mail', ...); an
empty list sends nothing. The mail
carries no text a tenant wrote: a free-form name could hold a bare URL that
mail clients turn into a link. It names the endpoint by its host (a valid
host name or IP literal, else "an unknown host"; WebhookEndpoint::displayHost()
gives the same to a product's own notices) and its public id, never
its URL, and its only link is the product's own endpoint page,
outbound.webhooks.auto_disable.endpoint_url with {endpoint} replaced by
the public id (no link when unset).
$coordinator = app(WebhookDeliveryCoordinator::class); $coordinator->disableEndpoint($endpoint); // reason "manual", no email $coordinator->enableEndpoint($endpoint); // clean failure streak; pending deliveries resume
enableEndpoint() is the only supported way back: setting is_active by
hand leaves disabled_at, disabled_reason and the failure streak behind.
A delivered webhook (a 2xx) fires WebhookDeliveredEvent once the attempt
is stored and committed: the delivery's public id, the webhook id
(event_id), the endpoint's public id, the attempt number and the time, so a
product records the outcome without querying the tables. A transaction the
product wraps around the run that rolls back announces nothing.
An attempt that leaves a delivery exhausted (every attempt used, a
Retry-After above the cap, or 410 Gone) fires WebhookDeliveryFailedEvent
once, after the attempt is stored: the delivery's and the endpoint's public
ids, the event type, the reason, the attempt count and the time.
A body pruned while its delivery was still pending exhausts it
without an attempt and without the event.
Every event of the package is dispatched synchronously (the
WebhookDeliveredEvent after the commit), so no listener may throw: make it
ShouldQueue or catch inside. A listener that throws on a delivery event
is reported through the exception handler after the attempt is stored, and
the run carries on; on WebhookSignedEvent and OutboundRequestBlockedEvent
see above. Events carry public ids, never a secret or a body;
WebhookRedeliveryRequestedEvent::$triggeredBy is the asking user's public id
(or null), never the internal bigint left in the delivery columns.
An attempt records the status, duration, transport error kind,
receiver_request_id (128 characters at most) and allowlisted response headers
(each capped at 255 characters). Receiver bodies and excerpts are excluded from
the attempt record because they may contain receiver or customer data, and
relaying a raw response would turn a blind SSRF into a readable one.
Redelivery
$coordinator = app(WebhookDeliveryCoordinator::class); $coordinator->redeliver($delivery, triggeredBy: auth()->id()); $coordinator->redeliverRange($endpoint, $from, $until, [WebhookDeliveryStatusEnum::Exhausted], auth()->id()); // "Redeliver failed since…"
The methods still take the user's internal id for the delivery and attempt
columns; the event publishes their public id instead. The package reads
public_id from outbound.webhooks.users_table, checking for the column once
per process; bind UserPublicIdResolverContract when a product keeps public
ids somewhere else.
A redelivery is sent by the next outbound:work-deliveries run with the same
webhook-id (the delivery's event id), a fresh webhook-timestamp and fresh
signatures (Standard Webhooks "Webhook metadata" keeps the id across
retries). A consumer that already processed it deduplicates it. A
consumer that verifies with this package and fails after claiming the id
drops the redelivery as a duplicate until the claim expires;
unless it gives the claim back with SeenWebhookIdStoreContract::release(). The attempt records trigger = manual|bulk and triggered_by.
- A settled delivery (delivered, exhausted, refused, cancelled) gets exactly one more attempt: if it fails, it is exhausted again. A pending one is sent now and keeps its schedule.
redeliverRange()takes the endpoint's deliveries created in [$from,$until) with the given statuses; deliveries whose body has been pruned are skipped. A large range does not starve other endpoints.- Both refuse a disabled or deleted endpoint (enable it first) and a
cancelled delivery: the product withdrew it, for good. A pruned body
differs:
redeliver()refuses its one delivery, whileredeliverRange()skips pruned deliveries and schedules the rest, so one old delivery does not block a range. Both fireWebhookRedeliveryRequestedEvent(endpoint public id, count, trigger, asking user's public id) for a product's audit log. - Asking twice before the worker runs sends the delivery once, for the latest request. A request made while the delivery is being sent is kept, even from the same user (each request is counted): that attempt is recorded as it went, then the delivery is sent again.
- A redelivery goes to the endpoint's current URL (through the SSRF guard)
with the current signing secrets, whatever the subscriptions are now:
allow it only to users who may edit the endpoint. Redelivering a pending
delivery sends it now, before any
Retry-Afterthe receiver asked for. exhausted_reasonis cleared when a redelivery is scheduled;delivered_atkeeps the time of the last successful delivery until a new one replaces it.
Body retention
The package schedules outbound:prune-deliveries daily, on one server and
without overlapping (fleet convention F9). Set outbound.webhooks.schedule
(OUTBOUND_WEBHOOK_SCHEDULE) to false to schedule it yourself.
onOneServer() needs a cache all scheduler hosts share (database, Redis,
Memcached or DynamoDB): with a node-local file cache, two hosts both run it,
which is harmless (each block is its own transaction) but doubles the work.
--dry-run reports what it would clear and delete and changes nothing.
A delivery's body is the exact payload every attempt signs, encrypted at rest
(versioned encrypted cast). It is kept until payload_expires_at: 30 days after
dispatch by default (outbound.webhooks.payload_retention_days, from 1 to
30, the boot fails outside; the maintainer's decision of 2026-11-22 and the
fleet erasure decision). A delivery about a person named at dispatch
(subjectPublicId) keeps it until its longest possible retry plan ends, plus
an hour, if that is later; one about nobody named never longer than the
retention, because the eraser cannot find it: prune exhausts it
(payload_expired) even mid-schedule. The plan counts
every retry at its delay plus the most jitter, or at the Retry-After cap
when Retry-After is honoured, so a receiver that keeps answering 503 with
a long Retry-After, or an endpoint with a higher max_attempts, never loses
its body mid-schedule.
outbound:prune-deliveries then clears the body and keeps payload_hash and
payload_bytes, so the delivery log still proves what was sent. It also
deletes settled deliveries created outbound.webhooks.delivery_retention_days
ago (90, at least the payload retention), with their attempts, once their
body has expired too; pending ones are kept. It works in blocks of 500, each in its own short transaction.
- A body that has expired, pruned or not, cannot be redelivered.
- A pending delivery whose body expires (an endpoint disabled for weeks) is
exhausted (
payload_expired); one a worker is sending keeps its body until its lease ends.
Erasure
use Qiick\Outbound\Erasure\OutboundEraser; $report = app(OutboundEraser::class)->erase( userId: (string) $user->id, userPublicId: $user->public_id, mode: OutboundEraser::DELETE, // or ANONYMISE: outbound does the same in both publicIds: $principalAndApiKeyPublicIds, identifiers: [$user->email, $user->name], dryRun: false, );
OutboundEraser is the package's step of the qiick fleet erasure standard
(.qiick/standards/erasure.md); a product calls it only through its erasure
orchestrator, after collecting the Art. 19 recipients (the endpoints of the
person's delivered deliveries). Endpoints and the delivery log are the
organisation's, so nothing is deleted. In one transaction it:
- cancels every pending delivery whose
subject_public_idis the person's public id or one of$publicIds(compared in lower case, asdispatch()stores it), and drops the payload, its hash and the reference of every delivery about them, delivered ones included (the erasure report is the evidence that remains); - clears receiver diagnostics (
response_headersandreceiver_request_id) on every attempt of those deliveries, whoever triggered it; - nulls
created_by,next_attempt_triggered_byandtriggered_bywhere they point at the person (a non-numeric$userIdmatches none of them).
A worker that claimed a delivery before the cancel reads the row again after
DNS, right before the transport, and sends nothing when the delivery was
cancelled or its body expired (an expired body is never claimed either). An
attempt on the wire records the asker the claim stored in
claimed_triggered_by, which the eraser nulls too, so an unlinked asker is
never written back. Known limit: a cancel committed after that last read,
while the request is being written, does not stop it; a request on the wire
cannot be recalled, and its attempt is not recorded. A deadlock is
rethrown as WebhookDeliveryConcurrencyException, other database errors as
a RuntimeException, both without the query's bindings.
It returns an ErasureReport with counts only and, after the commit,
dispatches Events\SubjectErasedEvent; a dry run writes and dispatches
nothing. With organisationId, only that organisation's rows change: its
endpoints (organisation_id), the deliveries whose organisation snapshot is
it, and those deliveries' attempts; the export narrows the same way.
A delivery is attributable only if the product passed subjectPublicId to
dispatch(). A delivery queued without it keeps its encrypted payload for
the payload retention only (30 days at most, whatever its retry plan), then
only the hash: pass it for every event about a person.
Personal-data export uses OutboundExporter, the read-only counterpart of the
eraser:
use Qiick\Outbound\Export\OutboundExporter; $export = app(OutboundExporter::class)->export( userId: (string) $user->id, userPublicId: $user->public_id, publicIds: $principalAndApiKeyPublicIds, organisationId: $organisation?->public_id, );
It mirrors the eraser's stores and selection and returns a JSON-encodable array
keyed by store with the conservative basis: 'observed' and rows. A mixed
store adds a scalar row-level basis (provided or observed) that overrides
the store floor: webhook_endpoints marks the endpoint reference observed
and person-configured headers and webhook secrets provided. A row about the
person as subject is exported in full. A record they only created or acted on
for somebody else is reference-only: type, public_id, action and at,
with no other person's data. Person-configured secrets appear only as presence
rows with value: null and secret: true; internal signing material and
receiver response headers are omitted, and no secret value is exported. The
export reads no cache and has no cleanup side effects. A product calls it from
its export orchestrator next to the eraser.
Retry schedule and delivery records
use Qiick\Outbound\Delivery\DeliveryAttempt; use Qiick\Outbound\Enums\WebhookDeliveryStatusEnum; use Qiick\Outbound\Retry\RetrySchedule; use Qiick\Outbound\Retry\SystemRandomizer; $delays = match (config('outbound.webhooks.retry_preset')) { 'short' => RetrySchedule::shortDelays(), default => RetrySchedule::standardDelays(), }; // Each delay is measured from the previous attempt, not from the first send. $wait = RetrySchedule::withJitter( $delays[0], (int) config('outbound.webhooks.retry_jitter_seconds'), new SystemRandomizer, ); $attempt = new DeliveryAttempt( eventId: $msgId, eventType: 'order.created', attempt: 1, status: WebhookDeliveryStatusEnum::Failed, httpStatus: 503, errorMessage: 'upstream unavailable', at: new DateTimeImmutable, nextAttemptAt: new DateTimeImmutable('+'.$wait.' seconds'), );
Prefer standard delays (5s, 5m, 30m, 2h, 5h, 10h, 14h, 20h, 24h — about
75.6 hours end-to-end); each entry is the wait from the previous attempt.
Bound short ([10, 30, 60]) to a migration window. Jitter is capped
(configured and ±floor(delay/2)) so a positive delay is never immediate.
DeliveryAttempt strips control characters and caps errorMessage length.
These pieces are what WebhookDeliveryCoordinator uses; call them directly
only for a delivery loop of your own.
Webhook tables
The package owns five tables with fixed, standard names (the names are not configurable):
| Table | One row per |
|---|---|
webhook_endpoints |
destination URL, with its policy overrides and failure streak |
webhook_endpoint_secrets |
signing secret (up to 4 during a rotation), encrypted at rest |
webhook_subscriptions |
endpoint and event type (* for every type) |
webhook_deliveries |
endpoint and event, with the retry state and the encrypted body |
webhook_delivery_attempts |
HTTP attempt, append-only |
They are mandatory, so the service provider loads the migrations itself:
php artisan migrate creates them. A product that wants the files in its own
database/migrations publishes them and turns loading off:
php artisan vendor:publish --tag=outbound-migrations OUTBOUND_MIGRATIONS_LOAD=false
Do both or neither. Publishing with loading still on registers each table twice:
migratethen fails on the secondcreatewith "table already exists". SetOUTBOUND_MIGRATIONS_LOAD=falsein every environment (and in.env.example) in the same change that commits the published files.
Eloquent models live in Qiick\Outbound\Models (WebhookEndpoint,
WebhookEndpointSecret, WebhookSubscription, WebhookDelivery,
WebhookDeliveryAttempt). Each has a UUID v7 public_id, which is its route
key and the only id that leaves the database; the bigint id, foreign keys,
secret, payload and the endpoint's custom headers (often a token) are
hidden from arrays and JSON. Those three are encrypted in a versioned
envelope (see "Encryption at rest and key rotation" below). payload_hash
(sha256:<hex>, the unkeyed digest of the body, to deduplicate and verify
with WebhookDelivery::payloadMatches()) is hidden too. A failed WebhookDelivery::save()
throws WebhookDeliveryStorageException (DuplicateWebhookDeliveryException
for a unique key) with only the SQLSTATE, and a deadlock or serialization
failure throws WebhookDeliveryConcurrencyException (a DeadlockException,
so DB::transaction(..., attempts: n) still retries it), never Laravel's
exception with its bindings. Query recorders (Telescope, Debugbar, Flare with
query bindings, DB::listen loggers) still see the hash of every write: a
short, guessable body can be found from it. created_by and triggered_by reference
outbound.webhooks.users_table (users) with null-on-delete, as foreignId
columns: the users table must have an unsigned bigint id (Laravel's
default). A product with UUID or ULID user ids sets
OUTBOUND_WEBHOOK_USERS_TABLE empty: the columns stay, nullable and without
a foreign key, and the product leaves them null.
Organisation. webhook_endpoints.organisation_id is the fleet's standard
tenant column: a lowercase UUID, null for an instance-level endpoint, with no
foreign key (the product owns its organisations table). Set it in product code
($endpoint->forceFill(['organisation_id' => $organisation->public_id])); it is
never mass-assignable. dispatch(..., organisationId: $organisation->public_id)
reaches only that organisation's endpoints, and a dispatch without one reaches
only instance-level endpoints, so an event never fans out across organisations.
Each delivery stores the endpoint's organisation as a snapshot in
webhook_deliveries.organisation_id, so it stays in its organisation when the
endpoint moves or is deleted; erasure and export by organisation read it
(decision docs/decisions/2026-12-01-organisation-id.md).
Scope column. For a scope of its own inside an organisation (a project), a
product adds its own foreign key to webhook_endpoints with its own
migration, indexed with is_active, and names it in
outbound.webhooks.scope_column:
Schema::table('webhook_endpoints', function (Blueprint $table): void { $table->foreignId('project_id')->nullable()->after('public_id')->constrained()->cascadeOnDelete(); $table->index(['project_id', 'is_active']); }); // .env: OUTBOUND_WEBHOOK_SCOPE_COLUMN=project_id
The scope column is never mass-assignable, since it decides the tenant: set
it in the product's own code ($endpoint->forceFill(['project_id' => $project->id])),
never from request input. Null (the default) means one instance-wide scope. A product may add other
columns the same way; the package reads only the scope column.
The tables have no generic schema_version column: payload_version on
endpoints and deliveries, and scheme on secrets, are the version fields, and
no consumer reads a generic row-format value. Every date column is dateTime
(including created_at, updated_at and deleted_at), written in UTC;
created_at and updated_at are explicit non-null columns with no database
default, deleted_at stays nullable for soft deletes, and attempted_at
keeps milliseconds.
Encryption at rest and key rotation
Every stored secret names its own format, so a key rotation or an algorithm change needs no table migration and old rows keep reading during the move:
| Column | Stored as |
|---|---|
webhook_endpoint_secrets.secret, webhook_endpoints.headers, webhook_deliveries.payload |
v1:<cipher>:<key id>:<Laravel payload> |
webhook_deliveries.payload_hash |
sha256:<hex> (VARCHAR(160)) |
v1 is the envelope version, <cipher> the app.cipher the row was written
with, and <key id> a 16-hex one-way fingerprint of the APP_KEY that wrote
it. Reads pick the key from APP_KEY and APP_PREVIOUS_KEYS by that id and
the cipher from the row, so both a key rotation and an app.cipher change
leave old rows readable. A value without the envelope is a bare Laravel
payload from before it, read with app.cipher, APP_KEY and
APP_PREVIOUS_KEYS; a bare 64-hex payload_hash is a SHA-256. An unknown
envelope version, cipher or digest algorithm, or a key id that no configured
key matches, fails closed (DecryptException / UnexpectedValueException).
Rotating APP_KEY:
- Move the old key into
APP_PREVIOUS_KEYSand set the newAPP_KEY; deploy. New writes use the new key, old rows still read. php artisan outbound:reencrypt --dry-runcounts the rows still under an old key, cipher or the bare legacy format;php artisan outbound:reencryptrewrites them (only a row still holding the value it read, so a concurrent write is never overwritten). It decrypts every row, current ones included, and exits1and names the table and column, never a value, when a row cannot be decrypted. A delivery whose body no longer decrypts is refused and reported to the exception handler, never sent.- Once a second dry run reports
0everywhere, drop the old key fromAPP_PREVIOUS_KEYS. A database backup taken before step 2 still needs the old key to be restored: keep it with the backup.
Changing app.cipher: run outbound:reencrypt first so no bare legacy
payload is left (a bare payload names no cipher and is read with the current
app.cipher), then change the cipher (with a key of the length it needs) and run
outbound:reencrypt again. When the key changes too, keep the old key in
APP_PREVIOUS_KEYS if it has the length the new cipher needs; for a change of
key size (AES-256 to AES-128 or back), Laravel refuses it there, so put it in
OUTBOUND_PREVIOUS_KEYS (comma-separated, base64: as in APP_KEY) instead,
which only this package reads, until outbound:reencrypt reports no stale
rows.
A new envelope or digest version is added as a reader first, released,
and only then made the writer, so a rollback still reads every row. The
replay claims of CacheSeenWebhookIdStore (outbound:whid:v1: + SHA-256 of
scope and webhook id) are a cache with no key to rotate: a new key format must
claim under both namespaces for one signature tolerance window, or wait that
long after draining receivers, so a webhook id claimed under the old key can
never be claimed again under the new one.
The in-place upgrade from 0.2.0-beta.5 also runs through php artisan migrate.
See UPGRADING.md for organisation attribution on existing rows
and the steps for products that publish migrations. From 1.0.0 the migrations
are frozen and change only additively.
Configuration
| Config key | Env | Default |
|---|---|---|
outbound.migrations.load |
OUTBOUND_MIGRATIONS_LOAD |
true |
outbound.ssrf.allow_private_hosts |
OUTBOUND_ALLOW_PRIVATE_HOSTS |
false |
outbound.ssrf.https_only |
OUTBOUND_HTTPS_ONLY |
false |
outbound.http.timeout_seconds |
OUTBOUND_TIMEOUT_SECONDS |
5 |
outbound.http.connect_timeout_seconds |
OUTBOUND_CONNECT_TIMEOUT_SECONDS |
3 |
outbound.http.max_timeout_seconds |
OUTBOUND_MAX_TIMEOUT_SECONDS |
60 |
outbound.http.max_connect_timeout_seconds |
OUTBOUND_MAX_CONNECT_TIMEOUT_SECONDS |
30 |
outbound.http.total_deadline_seconds |
OUTBOUND_TOTAL_DEADLINE_SECONDS |
30 |
outbound.http.max_response_bytes |
OUTBOUND_MAX_RESPONSE_BYTES |
1048576 |
outbound.http.max_redirects |
OUTBOUND_MAX_REDIRECTS |
0 |
outbound.http.egress_proxy |
OUTBOUND_EGRESS_PROXY |
null |
outbound.webhooks.replay_tolerance_seconds |
OUTBOUND_WEBHOOK_TOLERANCE_SECONDS |
300 |
outbound.webhooks.max_payload_bytes |
OUTBOUND_WEBHOOK_MAX_PAYLOAD_BYTES |
1048576 |
outbound.webhooks.max_signatures |
OUTBOUND_WEBHOOK_MAX_SIGNATURES |
8 |
outbound.webhooks.max_secrets |
OUTBOUND_WEBHOOK_MAX_SECRETS |
4 |
outbound.webhooks.secret_rotation_grace_seconds |
OUTBOUND_WEBHOOK_SECRET_ROTATION_GRACE_SECONDS |
86400 |
outbound.webhooks.retry_preset |
OUTBOUND_WEBHOOK_RETRY_PRESET |
standard |
outbound.webhooks.retry_jitter_seconds |
OUTBOUND_WEBHOOK_RETRY_JITTER |
30 |
outbound.webhooks.timeout_seconds |
OUTBOUND_WEBHOOK_TIMEOUT_SECONDS |
15 |
outbound.webhooks.respect_retry_after |
OUTBOUND_WEBHOOK_RESPECT_RETRY_AFTER |
true |
outbound.webhooks.retry_after_cap_seconds |
OUTBOUND_WEBHOOK_RETRY_AFTER_CAP_SECONDS |
86400 |
outbound.webhooks.default_max_concurrency |
OUTBOUND_WEBHOOK_DEFAULT_MAX_CONCURRENCY |
2 |
outbound.webhooks.payload_retention_days |
OUTBOUND_WEBHOOK_PAYLOAD_RETENTION_DAYS |
30 |
outbound.webhooks.delivery_retention_days |
OUTBOUND_WEBHOOK_DELIVERY_RETENTION_DAYS |
90 |
outbound.webhooks.schedule |
OUTBOUND_WEBHOOK_SCHEDULE |
true |
outbound.webhooks.auto_disable.enabled |
OUTBOUND_WEBHOOK_AUTO_DISABLE |
true |
outbound.webhooks.auto_disable.no_success_days |
OUTBOUND_WEBHOOK_AUTO_DISABLE_NO_SUCCESS_DAYS |
5 |
outbound.webhooks.auto_disable.min_consecutive_failures |
OUTBOUND_WEBHOOK_AUTO_DISABLE_MIN_CONSECUTIVE_FAILURES |
10 |
outbound.webhooks.auto_disable.notify_owner |
OUTBOUND_WEBHOOK_AUTO_DISABLE_NOTIFY_OWNER |
true |
outbound.webhooks.auto_disable.endpoint_url |
OUTBOUND_WEBHOOK_AUTO_DISABLE_ENDPOINT_URL |
null |
outbound.webhooks.scope_column |
OUTBOUND_WEBHOOK_SCOPE_COLUMN |
null |
outbound.webhooks.users_table |
OUTBOUND_WEBHOOK_USERS_TABLE |
users |
Development
composer update composer test # Pest composer lint # Pint composer analyse # PHPStan level max
Mutation (CI): bash scripts/mutate-per-class.sh — every listed class must
score ≥95% without --covered-only, and src/ has no @pest-mutate-ignore.
A constant's line has no coverage, so values mutation testing must check live
in methods.
The suite runs on in-memory SQLite by default; CI also runs it on PostgreSQL,
MySQL and MariaDB. Point it at a server with the usual DB_* variables
(DB_CONNECTION=pgsql DB_DATABASE=laravel_outbound vendor/bin/pest).
Tests are deterministic: no live network. DNS and HTTP use injectable fakes; clock and randomizer are fixed in tests.
Licence
MIT. See LICENSE.
Security
See SECURITY.md. Use GitHub private vulnerability reporting; do not open a public issue for security findings.