Sirv webhooks: Studio receiver handoff
Studio's receiver matches webhooks-agent on headers, HMAC signing, batch limits and event types. Before we enable webhooks in Studio production, we need one signed test delivery against next.sirv.studio, two P0 additions on Sirv's side (file identity and order keys on events, plus fileId on GET /v2/files/stat), and a rollout plan for hosts and billing plans.
1. Contract check
Verified webhooks-agent on origin/master and origin/dev against Studio's webhook receiver.
| Surface | webhooks-agent (Sirv) |
Sirv AI Studio | Result |
|---|---|---|---|
| Signature header | X-Sirv-Signature: sha256=<64 hex> |
Same format, timingSafeEqual |
Matches |
| Timestamp header | X-Sirv-Timestamp, Unix ms (Date.now()) |
Unix ms, 5 min tolerance | Matches |
| Signed text | HMAC-SHA256 of {timestamp}.{body} (deliver.js:192) |
Same text and digest | Needs 1 live test |
| Body envelope | timestamp (ISO) + events[] (id, event, data) |
Reads events[], ignores top-level timestamp |
Matches |
| Batch limits | Up to 100 events or 64 KB (from backlog only) | Up to 100 events, 256 KB body cap | Matches |
| Event types | new, change, replace, delete, rename (trash mapped to delete/new) |
Handles new, replace, delete, rename; skips change |
Matches |
Event id |
Deterministic sha256(topic:partition:offset|webhookId|type).slice(0,24) (deliver.js:214) |
Deduped per event.id |
Matches |
| Concurrency & retries | 5 parallel requests per account per agent instance; retries timeout (>5s), network error, 408, 429 (Retry-After <= 10s), 5xx |
Returns 202 fast; 1 sync run per workspace at a time |
Order gap |
| Rollout state | Enabled on dev-1 (19 Nov, 16697de67f) and c1-fireball-1.sirv.com (20 Nov, a889d570d8). Stats line on dev (#5586). Zero billing plans grant features.webhooks. |
Enabled on next.sirv.studio only, off in production |
Staging only |
2. Ordering gaps
deliver.js:214 hashes the Kafka position into event.id, which makes it solid for deduplication and unsortable for ordering. Two mechanics in webhooks-agent can reverse arrival order on the wire:
controller.jsadmits up to 5 concurrent HTTP deliveries per account per agent instance, including back-to-back events on the same file.- A delivery that hits a 5s timeout,
408,429or5xxsleeps 5s then 10s while newer events for the same file arrive first.
Two upstream facts in riakfs and Kafka also shape what an order key can promise:
- Directories have no file ID.
riakfs@2.6.3creates directory records withctime,mtimeandisDirectoryonly (files getid: uid2(32)). Incore/riakfs.js, passingstats.file.idsends folder events with a falsy partition key to a round-robin partition (core/pubsub.js:228-230), so folder events have no partition ordering at intake. - Kafka offsets are best-effort, not global truth. Producer batching on
-fsholds events up to 1500 ms per process (config/sirv.js:219-222), so two ops on one file from two backend processes can land with inverted offsets, and a topic repartition changescrc32(fileId) % partitionCount(core/kafka2.js:127).
| Customer action in Sirv | Reversed arrival at receiver | Wrong state |
|---|---|---|
Delete /a, then restore /a |
new /a, then delete /a |
File is live in Sirv, receiver trashes it |
Rename /a to /b, then /b to /a |
/b to /a, then /a to /b |
File is at /a, receiver points to /b |
Rename /a to /b, then delete /b |
delete /b, then /a to /b |
File is deleted in Sirv, receiver keeps it live at /b |
Rename /a to /b, then /b to /c |
/b to /c, then /a to /b |
File is at /c, receiver points to /b |
3. Asks for Sirv
P0Add fileId, seq and occurredAt to each event
controller.js (line 950 on origin/dev, line 882 on origin/master) slims each event down to ['type', 'filename', 'old', 'new', 'arrived'], dropping identity and timestamp fields already present on the Kafka message.
fileId(string | null, fromstats.file.id ?? null): present on files, explicitlynullon directories. Lets receivers follow one file across chained renames (/a -> /b -> /c) and ignore stale events for a replaced file.seq(string, fromString(m.offset), omitted whenfileIdisnull): must be a string becausem.offsetis abigint(core/kafka2.js:1925) andJSON.stringifythrows onbigintatcontroller.js:479anddeliver.js:388. Receivers compareseqonly within the samefileId.occurredAt(Unix ms fromstats.mtime, falling back to emit time on hard delete):core/riakfs.jsevents carry no timestamp and Kafka send time includes up to 1500 ms of batching.riakfsupdatesstats.mtimeon write close and rename, which lets receivers compare two differentfileIds colliding on the same path (delete/athen upload a new/a) and order folder renames.ready(optional boolean, already computed atcore/riakfs.js:203,232): tells receivers onnewandreplacewhether exiftool metadata is already written or still running async (see section 4).
{
"id": "3f1c9a0b7d2e4c5a6b8f0e1d",
"event": "rename",
"occurredAt": 1795472400123,
"seq": "4829104",
"data": {
"fileId": "a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6",
"old": "/Products/old.jpg",
"new": "/Products/new.jpg"
}
}
Touch points: webhooks-agent/app.js (pass String(m.offset)), webhooks-agent/controller.js (slimEvent, bump EVENT_ENVELOPE_BYTES), webhooks-agent/deliver.js:69,237 (PAYLOAD_FIELDS and buildPayload).
P0Return fileId from GET /v2/files/stat
rest-api/handlers/files.js:421-428 returns mtime, ctime, contentType, size, isDirectory and meta, with no file ID. Without fileId in /v2/files/stat, Studio cannot attach fileId to assets already linked before webhooks turn on. stat.file.id is already on the stat object returned by app.fs(accountId).call('stat', filename).
Touch points: rest-api/handlers/files.js:421-428, rest-api/routes/files.js:738-746.
P1Public REST webhook CRUD (/v2/webhooks)
POST /api2/webhooks/create (PR #5249, on both dev and master) sits under frontend/api/src/routes/private/webhooks/ behind private-routes.ts (dashboard Passport session + MFA). It does not accept JWT bearer tokens from POST /v2/token, and rest-api/ has no webhook routes.
- Storage lives in
api/services/webhooks.js, while the feature gate, role check and deliverable-URL check live infrontend/api/src/application/use-cases/webhooks/webhook-base.use-case.ts:69-76,125-155. Moving or sharing those checks avoids duplicating SSRF and feature validation inrest-api/. - Public scopes live in
api/services/rest_clients.js:15(PUBLIC_SCOPES). Every scope added there also becomes available to sub-account clients (rest-api/routes/account.js:10), and existing API clients will need the new scope granted before auto-registration works.
P1Per-webhook serialization (optional)
controller.js:936-937 notes that true per-file serialization is out of scope. Per-file locks would touch deliveryTask, shedOldest, discardBacklog, the probe path and batch tracking, and still would not hold across rebalances, restarts or folders. With the P0 payload fields in place, receivers can reorder without serialization on Sirv's side. If simpler in-order delivery is ever wanted for low-volume endpoints, capping in-flight deliveries at 1 per webhook (letting bursts batch) is much simpler than per-file locks.
P2Discussion: test ping and echo suppression
- Test ping: a Settings test button would surface 401/403 setup errors (which currently log as
rejectedwithout tripping the breaker). Synchronous feedback requires outbound HTTP from dashboard hosts with the same SSRF guard. Sending a signed POST withevents: []verifies URL, TLS and HMAC without introducing a new event type. - Echo suppression:
lib/riakfsWrapper.jsstampsriakfsUserId(rest:<clientId>) intometa.history, though multiple apps can share one Sirv account, history shapes vary across callers (jobs/fetch/controller.js:49), anddeliver.js:65-69keeps the allowlist tight against leaking internal IDs. Worth discussing later whether an opt-in correlation ID or origin tag makes sense for API integrations.
4. Confirmed caveat on replace and GET /v2/files/stat
rest-api/handlers/files.js:416 returns meta: _.pick(stat.file.meta, ['width', 'height', 'duration']), with EXIF orientations 5 through 8 swapped in lib/exiftool.js:319-321 (extraction loop at :298). Two paths can still return stale dimensions right after a replace event:
- Async exiftool paths (FTP, REST tus, legacy image editor): FTP (
ftpd/login.js:73onorigin/devreturns a rawapp.fshandle), REST tus uploads (rest-api/handlers/files.js:759-763viasirvcdn-uploads/app.js:96, no exiftool) andfrontend-api/controllers/protected/imageEditor/downloadPromise.js:14write without inline exiftool.core/riakfs.js:234publishes the Kafka event before queueing asyncexiftool:identify(jobs/exiftool/controller.js), and the latersetMetaemits only a metadatachangeevent. - Inline exiftool paths (REST upload, S3, fetch, dashboard when
frontend.spawnExiftoolis true atconfig/sirv.js:117): usually fresh immediately viaapi/services/files.js(exports.upload). However, if exiftool fails on a replace,riakfsmerges old metadata on overwrite andapi/services/files.js:228-249still stamps_fileversion, leaving the previous version's dimensions attached to the new file.
Do not filter on _fileversion in /v2/files/stat: _fileversion was added in Nov 2018 (b3b23d2083), so older files lack it, copies inherit source metadata, and failed inline exiftool runs still stamp it. The clean fix is clearing old width/height on content overwrite before merging new exiftool metadata, plus surfacing ready (already computed at core/riakfs.js:203,232) on replace.
5. Live test plan on next.sirv.studio
Webhooks stay off in Studio production and are on for testing on next.sirv.studio only. Cloudflare Access allows unauthenticated POSTs on the webhook path only, Studio verifies the HMAC signature, and Cloudflare public IPs pass webhooks-agent/ssrf.js.
- Studio creates a webhook in Settings → Sirv on
next.sirv.studioand sends you the URL (https://next.sirv.studio/api/integrations/sirv/webhooks/<id>) and signing secret. - Add them on a
dev-1account (or a test account onc1-fireball-1.sirv.com) withfeatures.webhooks: true, subscribed tonew,replace,deleteandrename. - Run one short sequence on a test image: upload, replace, rename, move to trash, restore from trash.
- Studio checks logs:
202proves signature and schema passed (401means signature or timestamp failed,400means schema failed).
6. Open decisions needed from Sirv
- Test delivery: ready whenever you want the
next.sirv.studioURL and secret. - P0 scope: can we land
fileId,seq(string),occurredAt(stats.mtime) and optionalreadyon webhook events, plusfileIdonGET /v2/files/stat? - Rollout and plans: which hosts beyond
c1-fireball-1.sirv.comwill runwebhooks-agent, when, and which billing plans inconfig/billing/getfeatures.webhooks: true? - Public REST CRUD: rough timeline for
/v2/webhooks(with shared validation and scope decision)?