Deliver to a custom site
On this page
Set it up #
Build the receiving endpoint below, on https, reachable from the internet. In Brenzuri open Connections, choose New connection, pick Webhook, name it, and enter the endpoint address. Leave the secret empty and Brenzuri makes one for you, shown once after saving; or enter your own. Press Test connection. It sends a signed ping; any 2xx answer is a pass. Attach the connection to a site from the site’s Setup. A connection serves one site and a site has one connection.
The address must be https, resolve to a public address, and is checked again on every delivery. Private and loopback addresses are refused. A secret Brenzuri makes starts whsec_. A secret you type is used exactly as typed, apart from whitespace and line breaks at either end, which are removed. Either way the whole secret, anywhsec_included, is the signing key.The two policies, Draft and Awaiting approval, differ in one thing for you, and only for a delivery a person starts by hand of a version no person has approved yet: statussaysdrafton Draft andawaiting_approvalon Awaiting approval.awaiting_approvalmeans exactly that: a person sent it, and no person has approved this version in Brenzuri. It always comes withhumanApproved: false. Once a person has approved the version being delivered,statusisdraftandhumanApprovedistrue, on either policy. Every delivery that follows an approval in Brenzuri, every delivery of a Beat, and everything a key or an agent sends hasstatusdraft, whichever policy the connection has. A retry, including the automatic one, decides again with the connection’s policy and the approval at the time of the retry (site deliveries are always drafts), and keepshumanApproved: truefor a delivery a person started.
Let your coding agent build it #
# Receive articles from Brenzuri on this site
You are working in the codebase of my website. Add an endpoint that receives articles from Brenzuri and stores each one as an unpublished draft in the place this site already keeps its posts. Pick a path that fits this codebase, for example `/brenzuri/articles`, and tell me the full https address when you are done.
Brenzuri (https://app.brenzuri.com) sends every article as a signed JSON POST. The whole contract is below; the full reference with live examples is https://app.brenzuri.com/docs/guides/custom-site.
## Before you write code
1. Find how this site stores and shows posts: framework, database or CMS, the post model, how drafts work, where images go. Use those; do not add a second store or a new server unless the site has no backend at all.
2. Map the delivery onto the existing post model: title, `deck` as the excerpt or standfirst, the article body, the picture and its alt text, the language.
3. Tell me in a few lines what you found and how you will map it, then build it.
## Rules
- **Draft only.** Brenzuri never asks you to publish. `status` is `draft` or `awaiting_approval`; store both as unpublished. A person on my side publishes. Read `humanApproved` and `approval.version`, not `status`, to show whether a person approved this exact version in Brenzuri: `awaiting_approval` only ever comes with `humanApproved: false`.
- **Verify before anything else.** Read the raw request body as bytes, before any JSON parsing. Refuse to start, or answer 500, when the secret is missing or empty.
- **Idempotent.** The same delivery can arrive more than once. Never create a second post for it.
- **Keep the sources.** The `html` field ends with an `<aside class="bz-sources">` listing the sources and whether a person reviewed the article. Keep it in the stored body, or render `sources` in its place. Do not drop it.
- Never log the secret, the signature or the picture address.
## Configuration
- `BRENZURI_CONNECTION_SECRET`: the connection secret, read from the environment or the site's secret store, never committed. A secret Brenzuri makes starts with `whsec_`; the prefix is part of the key.
- `BRENZURI_ORIGIN`: `https://app.brenzuri.com`. Pictures are downloaded only from this origin.
## The request
Headers:
- `Content-Type`: `application/json`.
- `X-Brenzuri-Event`: `article.delivered`, on every delivery.
- `X-Brenzuri-Delivery`: The id of this delivery, a lower-case UUID. It is the same on every retry of the delivery and equals the id in the delivery log in Brenzuri. The same value is in the signed body as `deliveryId`; the header is not signed, so read the body.
- `X-Brenzuri-Timestamp`: Unix seconds when this attempt was sent. It changes on every attempt.
- `X-Brenzuri-Signature`: Lower-case hex HMAC-SHA256 of `<timestamp>.<raw body>`, keyed with the whole connection secret, as UTF-8 bytes. A secret Brenzuri makes starts `whsec_`, and that prefix is part of the key. It covers the whole body, illustration included.
## Check the signature
1. `X-Brenzuri-Timestamp` must be all digits and within 300 seconds of your clock; otherwise answer 400.
2. `X-Brenzuri-Signature` must be exactly 64 lowercase hex characters; otherwise answer 401.
3. Compute HMAC-SHA256 of `<timestamp>.<raw body>` with the whole secret as the key, as lowercase hex, and compare it with the header in constant time (`crypto.timingSafeEqual`, `hmac.compare_digest`, `hash_equals`). On a mismatch answer 401.
## The test ping
Brenzuri's "Test connection" button sends `{"event":"connection.test"}`, signed the same way, with no `deliveryId` and no `articleId`. Verify it and answer 204 before you look for an article.
## The body
JSON with these fields:
- `event`: Always `article.exported`. It is the name this body had before the header `X-Brenzuri-Event` existed and it has not changed. Do not branch on it; the header says `article.delivered`.
- `title`: The article title. The same title is the `<h1>` at the top of `html`.
- `status`: `draft` or `awaiting_approval`. Brenzuri never sends `publish`. A delivery that follows an approval in Brenzuri, a delivery made by a key, an agent or a Beat, and one from a connection set to Draft are always `draft`, and so is a language version of an article a Beat wrote. `awaiting_approval` is sent only when a person delivers by hand, through a connection set to Awaiting approval, a version no person has approved, or when such a delivery is retried; it always comes with `humanApproved: false`. Once a person has approved the version delivered, `status` is `draft` and `humanApproved` is `true`. To decide whether a person on your side may publish, read `humanApproved` and `approval.version`, not `status`. Your site decides what to publish.
- `html`: The article as HTML: the `<h1>`, the text with a `<figure class="bz-figure">` and its credit for each figure that has a `url`, and an `<aside class="bz-sources">` with the sources and the line “Generated with sources · reviewed by a human: yes or no”. Every claim that is not corroborated (one source, one origin repeated, sources that disagree, or reported separately) has `<sup>†</sup>` after it where its text appears word for word in the article, whether or not a person kept its flag. When any claim has one, the sources paragraph adds “Claims marked † are not confirmed by two independent outlets.” Text is escaped.
- `deliveryId`: The id of this delivery, the same lower-case UUID as the header `X-Brenzuri-Delivery`. Unlike the header, it is inside the signed body, so it cannot be changed without breaking the signature. Deduplicate on this one.
- `articleId`: Lower-case UUID of the article.
- `version`: The version of the article that was delivered. `articleId` with `version` identifies what you received.
- `deck`: The standfirst. Only present when this version is approved and the article has one.
- `words`: Word count.
- `humanApproved`: True when this exact version was approved by a person and the delivery was made by a person, as approval in Brenzuri does. A delivery a key or an agent starts reports false even for an approved version; `approval` then still names the approval.
- `blocks`: The text as structured blocks, each with a `kind`: `paragraph` (`text`), `heading` (`level`, `text`), `list` (`ordered`, `items`), `table` (`headers`, `rows`) or `figure`. Text may contain `**bold**` markers. A `figure` is a photo from a source page, placed after the text that cites it, and appears only when this version is approved by a person: `photoId`, `alt`, `credit` (show it with the photo, linked to `pageUrl`), `pageUrl` (the https page it came from, absent when there is none), `origin`, and the image as `mime`, `sha256`, `bytes`, `width`, `height`, `url` and `urlExpiresAt` as for `illustration`. A figure carries `base64` only when this deployment has no delivery address configured, so there is no `url`; with a `url` it never carries `base64`, whatever the size.
- `claims`: Every claim: `text`, `state`, the `outlets` that carry it and `block`, the index into `blocks` where it sits.
- `sources`: Every source: `outlet`, `title`, `url`, `score` and `official`.
- `illustration`: The picture, only when the delivered version has a ready one. See the table below. Absent otherwise.
- `supersedes`: Lower-case UUID of the article this one replaces, when it is a rewrite. See Rewrites.
- `language`: The language code of this article, such as `es` or `hr`; an article stored as `bhs` keeps it. Only present when the article has language versions or is one. See Language versions.
- `primaryArticleId`: Lower-case UUID of the article this one is a language version of. Only present on a language version.
- `approval`: `{ by, version, at }`, present when the version has an approval.
- `plannedFor`: ISO 8601 time a person chose to publish this version when approving it. Present only on such a delivery, which arrives at that time.
- `seo`: `{ slug }` always, when the article has search fields; `metaDescription` and `tags` are added only when this version is approved. `slug` is lower-case ASCII words joined by hyphens, at most 60 characters, or the title’s own script when it has no Latin letters. Absent for an article written without the search step.
- `jsonLd`: A schema.org `BlogPosting` as a JSON string, ready to place unchanged inside `<script type="application/ld+json">`: `<`, `>` and `&` are escaped, so the string cannot close the element. It holds `headline`, `wordCount`, `inLanguage` when known, `citation` with each source’s title, address and outlet, and, only when this version is approved, `description` and `keywords` from `seo`. With an approved FAQ it becomes an `@graph` of the `BlogPosting` and an `FAQPage`. It names no author and no reviewer; add your own `author`, `publisher` and dates before you place it if you want them. Skip it if your SEO plugin already writes schema.
- `blog`: Only ever present for Brenzuri’s own blog. It is never sent to a customer. Ignore it.
Each of `claims`:
- `text`: The claim.
- `state`: `corroborated`, `singleSource`, `circular`, `disputed` or `parallel`.
- `outlets`: Outlets that carry it.
- `block`: Index into `blocks`.
Each of `sources`:
- `outlet`: The outlet or origin.
- `title`: Page title.
- `url`: Address of the page.
- `score`: The score the sourcing policy gives the outlet.
- `official`: Whether the origin is official for the subject.
`approval`:
- `by`: The person who approved.
- `version`: The approved version.
- `at`: ISO 8601 timestamp.
## Store it
1. If you have already stored this `deliveryId`, answer 200 with the same `{"url"}` as the first time and change nothing.
2. Upsert by `articleId`: create the post the first time, replace it when a higher `version` arrives, and keep yours when a lower `version` arrives late (still answer 200).
3. When `supersedes` is set, this article replaces the one with that `articleId`: replace that post, or redirect its address to the new one.
4. Language versions arrive as separate articles with `language` and `primaryArticleId`. Link them as translations if the site supports that.
## The picture
`illustration` is present only when there is one:
- `mime`: `image/png`, `image/jpeg` or `image/webp`.
- `sha256`: Lower-case hex SHA-256 of the raw image bytes. Check what you decoded or downloaded against it.
- `bytes`: The size of the raw image in bytes. Check the length of what you decoded or downloaded against it.
- `base64`: The image bytes, standard base64. Present only when `bytes` is at most 2,000,000. Absent above that, and then the picture is at `url`.
- `url`: An https address at Brenzuri that returns the raw image bytes, with no key and no cookie. Always present, unless this Brenzuri deployment has no delivery address configured; then `base64` is present whatever the size. It stops working at `urlExpiresAt`.
- `urlExpiresAt`: ISO 8601 time 48 hours after this delivery attempt. A retry of the same delivery has a new address and a new time. Present with `url`.
- `width`: Pixels. Absent if the size could not be read.
- `height`: Pixels. Absent if the size could not be read.
- `altText`: Alternative text for the picture.
- `caption`: The caption, with its plate number when the site’s style has one. Absent when empty.
- `label`: `AI-generated` for an illustration, `Photo` for a photo from a source page. Show the label, or a photo’s `credit`, with the picture.
- `styleLabel`: `House style`, `Abstract editorial`, or `Photo`.
- `credit`: A photo only. The credit to show with it, linked to `pageUrl`. A photo goes out only with a version a person approved; otherwise the illustration does.
- `pageUrl`: A photo only. The https page it was taken from.
- `origin`: A photo only. The site it was taken from, as `w3.org`.
- Decode `base64` when present; otherwise GET `url` only if it is https and its origin is exactly `BRENZURI_ORIGIN`, with no redirects, no credentials, a 15 second limit and a 5 MB cap.
- Check the length against `bytes`, the SHA-256 against `sha256`, and the first bytes against `mime` (PNG, JPEG or WebP). Store it under a name made from `sha256` and reuse it if it exists.
- Show `label` ("AI-generated") with the picture, with `altText` and `caption`.
- A picture that fails never fails the delivery: store the article without it, log why, and answer 200.
## Answer
- Answer 2xx within 20 seconds; do slow work after the article is stored. Accept request bodies of at least 5 MB.
- Answer JSON `{"url": "https://…"}` with the address of the post you made (its future public address, or its edit page in the admin). Brenzuri links to it from the article page.
- Answer 429 or 5xx only when you want Brenzuri to try again later. Any other 4xx or 3xx stops retries until a person retries by hand.
## Tests
Write tests that sign requests with a test secret and check that:
- a valid delivery is stored as a draft and answers 200 with `{"url"}`;
- the same delivery sent twice answers the same `url` and stores nothing twice;
- one changed byte in the body answers 401, and a timestamp ten minutes old answers 400;
- a lower `version` after a higher one keeps the higher one;
- the test ping answers 204;
- a delivery with a bad picture is stored without the picture.
## When you are done
Tell me the endpoint's https address and which environment variables to set. I will paste the address into Brenzuri, press "Test connection", and approve an article to see it arrive.
When you receive one #
A person approves an article of the site in Brenzuri. The approved version is delivered as a draft, once per version: at once, or at the publish time the person chose. A Beat writes an article for the site. It is delivered unapproved, as a draft. Someone delivers by hand: on the article page with Send to and the connection’s name, shown once a person has approved the article, or with the connection’s row under Preview, or with POST /articles/{id}/deliver. A person getsdraft, orawaiting_approvalon a connection set to Awaiting approval when no person has approved that version. A key or an agent can do this too and always getsdraft.A workspace rule can stop a delivery before it is made, for example when it requires approval and the version is not approved. The delivery log in Brenzuri then says so.
The request #
| Header | Value |
|---|---|
Content-Type | application/json. |
X-Brenzuri-Event | article.delivered, on every delivery. |
X-Brenzuri-Delivery | deliveryId; the header is not signed, so read the body. |
X-Brenzuri-Timestamp | |
X-Brenzuri-Signature | <timestamp>.<raw body>, keyed with the whole connection secret, as UTF-8 bytes. A secret Brenzuri makes starts whsec_, and that prefix is part of the key. It covers the whole body, illustration included. |
User-Agent. The body is JSON with sorted keys. Use the tabs to see a delivery of an approved article with its picture, one not yet approved, a rewrite, and a language version.
Payload explorer
The body a custom site receives when an article is delivered, with keys in the order the engine writes them (sorted). Hover, tap or focus a field to read what it means. Long strings are shortened on screen. The values are made up; the keys are checked against the engine.
- {
- },
- {
- },
- {
- },
- {
- }
- ],
- {
- },
- {
- },
- {
- }
- ],
- },
- },
- {
- },
- {
- }
- ],
- }
Hover, tap or focus a field to see what it is.
Body #
| Field | Meaning |
|---|---|
event | article.exported. It is the name this body had before the header X-Brenzuri-Event existed and it has not changed. Do not branch on it; the header says article.delivered. |
title | <h1> at the top of html. |
status | draft or awaiting_approval. Brenzuri never sends publish. A delivery that follows an approval in Brenzuri, a delivery made by a key, an agent or a Beat, and one from a connection set to Draft are always draft, and so is a language version of an article a Beat wrote. awaiting_approval is sent only when a person delivers by hand, through a connection set to Awaiting approval, a version no person has approved, or when such a delivery is retried; it always comes with humanApproved: false. Once a person has approved the version delivered, status is draft and humanApproved is true. To decide whether a person on your side may publish, read humanApproved and approval.version, not status. Your site decides what to publish. |
html | <h1>, the text with a <figure class="bz-figure"> and its credit for each figure that has a url, and an <aside class="bz-sources"> with the sources and the line “Generated with sources · reviewed by a human: yes or no”. Every claim that is not corroborated (one source, one origin repeated, sources that disagree, or reported separately) has <sup>†</sup> after it where its text appears word for word in the article, whether or not a person kept its flag. When any claim has one, the sources paragraph adds “Claims marked † are not confirmed by two independent outlets.” Text is escaped. |
deliveryId | X-Brenzuri-Delivery. Unlike the header, it is inside the signed body, so it cannot be changed without breaking the signature. Deduplicate on this one. |
articleId | |
version | articleId with version identifies what you received. |
deck | |
words | |
humanApproved | approval then still names the approval. |
blocks | kind: paragraph (text), heading (level, text), list (ordered, items), table (headers, rows) or figure. Text may contain **bold** markers. A figure is a photo from a source page, placed after the text that cites it, and appears only when this version is approved by a person: photoId, alt, credit (show it with the photo, linked to pageUrl), pageUrl (the https page it came from, absent when there is none), origin, and the image as mime, sha256, bytes, width, height, url and urlExpiresAt as for illustration. A figure carries base64 only when this deployment has no delivery address configured, so there is no url; with a url it never carries base64, whatever the size. |
claims | text, state, the outlets that carry it and block, the index into blocks where it sits. |
sources | outlet, title, url, score and official. |
illustration | |
supersedes | |
language | es or hr; an article stored as bhs keeps it. Only present when the article has language versions or is one. See Language versions. |
primaryArticleId | |
approval | { by, version, at }, present when the version has an approval. |
plannedFor | |
seo | { slug } always, when the article has search fields; metaDescription and tags are added only when this version is approved. slug is lower-case ASCII words joined by hyphens, at most 60 characters, or the title’s own script when it has no Latin letters. Absent for an article written without the search step. |
jsonLd | BlogPosting as a JSON string, ready to place unchanged inside <script type="application/ld+json">: <, > and & are escaped, so the string cannot close the element. It holds headline, wordCount, inLanguage when known, citation with each source’s title, address and outlet, and, only when this version is approved, description and keywords from seo. With an approved FAQ it becomes an @graph of the BlogPosting and an FAQPage. It names no author and no reviewer; add your own author, publisher and dates before you place it if you want them. Skip it if your SEO plugin already writes schema. |
blog |
claims #
| Field | Meaning |
|---|---|
text | |
state | corroborated, singleSource, circular, disputed or parallel. |
outlets | |
block | blocks. |
sources #
| Field | Meaning |
|---|---|
outlet | |
title | |
url | |
score | |
official |
approval #
| Field | Meaning |
|---|---|
by | |
version | |
at |
illustration #
url.
| Field | Meaning |
|---|---|
mime | image/png, image/jpeg or image/webp. |
sha256 | |
bytes | |
base64 | bytes is at most 2,000,000. Absent above that, and then the picture is at url. |
url | base64 is present whatever the size. It stops working at urlExpiresAt. |
urlExpiresAt | url. |
width | |
height | |
altText | |
caption | |
label | AI-generated for an illustration, Photo for a photo from a source page. Show the label, or a photo’s credit, with the picture. |
styleLabel | House style, Abstract editorial, or Photo. |
credit | pageUrl. A photo goes out only with a version a person approved; otherwise the illustration does. |
pageUrl | |
origin | w3.org. |
Get the bytes. If base64is present, decode it. Otherwise downloadurlwith a plainGETand no credentials. Then check that the length equalsbytes, that the SHA-256 equalssha256and that the first bytes are a PNG, a JPEG or a WebP, matchingmime. Store the file under a name made fromsha256, such asillustrations/<sha256>.png, and skip the upload when it already exists. Showlabelwith the picture: it is always an AI-generated illustration.Download only from Brenzuri. urlis signed, but it is still an address in a request you received. Fetch it only when it is https and its origin is exactly the address of your Brenzuri, which you set in your receiver (BRENZURI_ORIGIN). Follow no redirect, give up after 15 seconds, stop reading at 5 MB, and never send your own credentials to it.The picture never fails the delivery. If the download or a check fails, store the article without the picture, log the reason and answer 2xx. Brenzuri has no way to resend only the picture, and a retry would make the same request again. Why the bytes are not always in the body. A request body on Vercel can be at most 4.5 MB; a bigger one is refused with 413 FUNCTION_PAYLOAD_TOO_LARGEbefore your code runs. A generated picture of 2 to 4 MB is 2.7 to 5.4 MB as base64, before the text, the claims and the sources. Brenzuri therefore putsbase64in the body only up to 2,000,000 bytes, which keeps the whole body well under 4.5 MB, and always sendsurl.Body limit. When addresses are on, a body is at most a little over 2.7 MB plus the article, so a receiver needs to accept bodies of 4.5 MB, which is also all a Vercel function takes. The samples below accept 5 MB. Raise the limit to 8 MB only for a Brenzuri deployment that has no delivery secret (the next point). The address is public and short-lived. It needs no key and no cookie, and it works for anyone who has it until urlExpiresAt, 48 hours after the attempt that sent it, so download in your handler or soon after and do not log or pass it on. It returns the picture of that delivery only, 404 for anything else and no reason, and at most 60 requests a minute from one address. A retry of the same delivery carries a new address.A deployment with no delivery address. When the Brenzuri you use has no delivery secret configured, urlandurlExpiresAtare absent andbase64is present for every picture, whatever its size, up to about 5.4 MB. Only then must your endpoint accept bodies of at least 8 MB (nginxclient_max_body_size, PHPpost_max_sizeandmemory_limit, Express and Flask limits), and a host with a smaller limit, such as Vercel, cannot receive the largest pictures.Older receivers. The field tooLargeis no longer sent. A receiver that treated it as “no picture” should treat a missingbase64the same way, or downloadurl.An article with no picture has no illustrationkey at all, and so does a delivery whose picture could not be read.
Check the signature #
<timestamp>.<raw body> with the whole secret as the key, compare it to X-Brenzuri-Signature in constant time, and refuse a timestamp more than 300 seconds from your clock. Hash the bytes you received, not a JSON string you parsed and wrote again. Refuse to start, or answer 500, when the secret is missing or empty: an empty key would let anyone forge a signature. Require the header to be exactly 64 lowercase hex characters and the timestamp to be all digits. The signature widget is the same one used for developer webhooks.
Signature checker
Paste a secret, the X-Brenzuri-Timestamp header, the raw request body and the X-Brenzuri-Signature header. The HMAC-SHA256 is computed in this browser with WebCrypto. Nothing leaves this page: there is no request, no logging and no storage.
Fill in the secret, the timestamp and the body.
Answer #
Any 2xx is delivered. Answer within 20 seconds; Brenzuri reads at most 64 KB of the answer. Optionally answer JSON {"url": "https://…"}: the address of what you made. Brenzuri stores it, checks that it is https without credentials, and links to it from the article page. Anything else in the answer is ignored.Any other status is a failure. 429 and 5xx are retried; other 4xx and 3xx are held for a person, who retries from the delivery log once you have fixed the cause. Do slow work after you answer, or answer only once the article is stored.
Retries #
deliveryId.
| Attempt | 1→2 | 2→3 | 3→4 | 4→5 | 5→6 | 6→7 | 7→8 | 8→9 | 9→10 | 10→11 | 11→12 |
|---|---|---|---|---|---|---|---|---|---|---|---|
| What happened | Reason in the delivery log | Retried by Brenzuri |
|---|---|---|
A request that timed out while waiting for your answer may have been received. Your endpoint, not Brenzuri, decides whether it was: that is why the delivery waits for a person, and why deliveryIdmatters when they retry.After the attempts or the 24 hours the delivery stays held, with the last reason. A person can retry it by hand from the delivery log until it has had 12 attempts. After that the row offers Send again instead: it sends the article’s current version as a new delivery, with a new deliveryId, the same asPOST /articles/{id}/deliver. Once a person’s newer delivery or retry of the same article reaches the same connection, older held rows for it that have no planned time are closed ascancelled, with the reason that a newer delivery reached the destination, and retrying one is refused withreplaced. The log then stops counting them as held.A held delivery for an older version is not retried once a newer version exists; it says “A newer version exists; approve it to deliver.”
Receive the same article twice #
Deduplicate on `deliveryId`, from the signed body. It is the same on every retry of one delivery and is the id shown in the delivery log. The header X-Brenzuri-Deliverycarries the same value but is not under the signature, so use it only to find the delivery in the log. If you have already stored the id, answer 2xx again, with the sameurl, and store nothing.Upsert by `articleId`. A later version of the same article arrives with the same articleIdand a higherversion. Replace your record. If a lower version arrives after a higher one, because a retry was late, keep the higher one and still answer 2xx.Different deliveries are different ids: delivering the same version again by hand is a new delivery with the same articleIdandversion.
Language versions #
articleId, its own version and its own deliveryId. Two fields tie them together:
languageis the language code of that article. It is present on the article that was written from the brief only once it has language versions, and on every version.primaryArticleIdis the lower-casearticleIdof the article the version belongs to. It is present on a version only. Group by it on your side; Brenzuri does not link the records.A language version has no illustrationkey: it has no picture of its own.When a rewrite started with supersedeswrites language versions, each one hassupersedesset to the version of the same language that the earlier article had, if it had one.
Rewrites #
supersedes set to the earlier article. When it is delivered, supersedes holds the earlier article’s id. Replace your record of that article with the new one, or redirect the old address to it; Brenzuri cannot change anything on your site, so it cannot do it for you. Later versions of the new article arrive with the new articleId. A Beat that watches what its site published can propose a rewrite as an update; it is delivered only after a person approves it.
The test ping #
{"event":"connection.test"}, signed the same way, with a timestamp and a signature but without X-Brenzuri-Event or X-Brenzuri-Delivery, and with no deliveryId. Verify it and answer 2xx. It has no articleId, so handle it before you look for one.
A complete receiver #
deliveryId it has seen, keeps the highest version of an article, stores the HTML and the picture, and answers 200 with {"url"}. The picture is decoded from base64, or downloaded from url when base64 is absent, only from BRENZURI_ORIGIN, over https, without redirects, within 15 seconds and 5 MB, and is checked against bytes, sha256 and mime before it is stored under its hash. They keep their data in files to stay short; use your database. Set BRENZURI_CONNECTION_SECRET to the connection secret and BRENZURI_ORIGIN to the address of your Brenzuri, for example https://app.brenzuri.com.
import express from 'express';
import { createHash, createHmac, timingSafeEqual } from 'node:crypto';
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
const SECRET = process.env.BRENZURI_CONNECTION_SECRET;
if (!SECRET) {
console.error('BRENZURI_CONNECTION_SECRET is not set; refusing to start');
process.exit(1);
}
const PUBLIC_BASE = process.env.PUBLIC_BASE_URL ?? 'https://example.com';
const DATA = process.env.BRENZURI_DATA_DIR ?? './brenzuri-data';
const ORIGIN = httpsOrigin(process.env.BRENZURI_ORIGIN);
const TOLERANCE_SECONDS = 300;
const IMAGE_BYTES = 5 * 1024 * 1024;
const IMAGE_SECONDS = 15;
const EXTENSIONS = { 'image/png': 'png', 'image/jpeg': 'jpg', 'image/webp': 'webp' };
const MAGIC = {
'image/png': (b) => b.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])),
'image/jpeg': (b) => b.subarray(0, 3).equals(Buffer.from([0xff, 0xd8, 0xff])),
'image/webp': (b) => b.subarray(0, 4).toString('latin1') === 'RIFF' && b.subarray(8, 12).toString('latin1') === 'WEBP',
};
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
const HEX64 = /^[0-9a-f]{64}$/;
for (const dir of ['deliveries', 'articles', 'images']) mkdirSync(join(DATA, dir), { recursive: true });
function httpsOrigin(value) {
try {
const url = new URL(value ?? '');
return url.protocol === 'https:' ? url.origin : null;
} catch {
return null;
}
}
const sha256 = (bytes) => createHash('sha256').update(bytes).digest('hex');
async function download(address) {
const target = new URL(address);
if (!ORIGIN || target.origin !== ORIGIN || target.username || target.password) {
throw new Error('the picture address is not on BRENZURI_ORIGIN');
}
const stop = new AbortController();
let timer;
const expired = new Promise((_, reject) => {
timer = setTimeout(() => {
stop.abort();
reject(new Error('the picture took more than ' + IMAGE_SECONDS + ' s'));
}, IMAGE_SECONDS * 1000);
});
try {
return await Promise.race([readPicture(target, stop.signal), expired]);
} finally {
clearTimeout(timer);
}
}
async function readPicture(target, signal) {
const res = await fetch(target, { redirect: 'error', signal });
if (res.status !== 200 || !res.body) throw new Error('the picture answered ' + res.status);
const chunks = [];
let size = 0;
for await (const chunk of res.body) {
size += chunk.length;
if (size > IMAGE_BYTES) throw new Error('the picture is over 5 MB');
chunks.push(chunk);
}
return Buffer.concat(chunks);
}
async function pictureBytes(picture) {
try {
if (!EXTENSIONS[picture.mime]) throw new Error('unknown picture type');
const bytes = picture.base64 ? Buffer.from(picture.base64, 'base64') : await download(picture.url);
if (bytes.length !== picture.bytes) throw new Error('the picture has the wrong size');
if (sha256(bytes) !== picture.sha256) throw new Error('the picture does not match its sha256');
if (!MAGIC[picture.mime](bytes)) throw new Error('the picture is not a ' + picture.mime);
return bytes;
} catch (error) {
console.warn('delivered without the picture: ' + error.message);
return null;
}
}
const app = express();
app.post('/brenzuri/articles', express.raw({ type: 'application/json', limit: '5mb' }), async (req, res) => {
const body = req.body.toString('utf8');
const timestamp = req.get('X-Brenzuri-Timestamp') ?? '';
const given = req.get('X-Brenzuri-Signature') ?? '';
if (!/^\d+$/.test(timestamp) || Math.abs(Date.now() / 1000 - Number(timestamp)) > TOLERANCE_SECONDS) {
return res.sendStatus(400);
}
if (!HEX64.test(given)) return res.sendStatus(401);
const expected = createHmac('sha256', SECRET).update(timestamp + '.' + body).digest('hex');
if (!timingSafeEqual(Buffer.from(expected), Buffer.from(given))) {
return res.sendStatus(401);
}
let article;
try {
article = JSON.parse(body);
} catch {
return res.sendStatus(400);
}
if (article.event === 'connection.test') return res.sendStatus(204);
const deliveryId = article.deliveryId ?? '';
if (!UUID.test(deliveryId) || !UUID.test(article.articleId ?? '')) return res.sendStatus(400);
const done = join(DATA, 'deliveries', deliveryId + '.json');
if (existsSync(done)) return res.status(200).type('json').send(readFileSync(done));
const recordPath = join(DATA, 'articles', article.articleId + '.json');
const stored = existsSync(recordPath) ? JSON.parse(readFileSync(recordPath, 'utf8')) : null;
if (!stored || stored.version <= article.version) {
const record = {
articleId: article.articleId,
version: article.version,
title: article.title,
status: article.status,
html: article.html,
deck: article.deck ?? null,
supersedes: article.supersedes ?? null,
humanApproved: article.humanApproved,
image: null,
};
const picture = article.illustration;
const bytes = picture ? await pictureBytes(picture) : null;
if (bytes) {
const file = picture.sha256 + '.' + EXTENSIONS[picture.mime];
if (!existsSync(join(DATA, 'images', file))) writeFileSync(join(DATA, 'images', file), bytes);
record.image = { file, altText: picture.altText, caption: picture.caption ?? null, label: picture.label };
}
writeFileSync(recordPath, JSON.stringify(record));
}
const answer = JSON.stringify({ url: PUBLIC_BASE + '/articles/' + article.articleId });
writeFileSync(done, answer);
res.status(200).type('json').send(answer);
});
app.listen(3000);Test your endpoint #
Run the receiver locally and send the signed request below. It carries a complete delivery with a picture. You should get 200 and {"url": …}.Send the same request again. You should get 200 and the same url, and nothing stored twice.Change one character of the body and send it with the old signature. You should get 401. Send it with a timestamp from ten minutes ago. You should get 400. Send the test ping. You should get a 2xx. Put the endpoint on https, press Test connection in Brenzuri, then approve an article of the site and watch the delivery log.
SECRET="whsec_local_test"
TS=$(date +%s)
cat > body.json <<'JSON'
{"approval":{"at":"2026-10-06T12:31:40Z","by":"Maya Chen","version":1},"articleId":"9f3b1c2a-6d4e-4b7a-8c15-2e0a7d91b3f4","blocks":[{"kind":"paragraph","text":"Three ferry operators will publish one shared timetable for the northern route from 3 November, the harbour authority said."},{"kind":"heading","level":2,"text":"What changes for commuters"},{"kind":"paragraph","text":"Commuters will see 14 daily crossings instead of 9, and a single fare table applies on all of them."}],"claims":[{"block":0,"outlets":["harbour-authority.example","coast-gazette.example"],"state":"corroborated","text":"The shared timetable starts on 3 November."},{"block":2,"outlets":["harbour-authority.example"],"state":"singleSource","text":"The route will have 14 daily crossings instead of 9."},{"block":2,"outlets":["harbour-authority.example","coast-gazette.example"],"state":"corroborated","text":"A single fare table applies on all crossings."}],"deck":"The harbour authority says commuters get 14 daily crossings.","deliveryId":"0d4f6a18-93be-4c27-8a50-e1c2b7d9f346","event":"article.exported","html":"<h1>Ferry operators agree on a single timetable for the northern route</h1>\n<p>Three ferry operators will publish one shared timetable for the northern route from 3 November, the harbour authority said.</p>\n<h2>What changes for commuters</h2>\n<p>Commuters will see 14 daily crossings instead of 9, and a single fare table applies on all of them.</p>\n<aside class=\"bz-sources\">\n<h2>Sources</h2>\n<p>This article was written from the reporting below.</p>\n<ul>\n<li><a href=\"https://harbour-authority.example/news/northern-route-timetable\">harbour-authority.example — Northern route: one timetable from 3 November</a></li>\n<li><a href=\"https://coast-gazette.example/transport/ferries-share-timetable\">coast-gazette.example — Ferries to share a timetable</a></li>\n</ul>\n<p><small>Generated with sources · reviewed by a human: yes · Approved by Maya Chen, 6 Oct 2026 · <a href=\"https://brenzuri.com/source-policy\" rel=\"nofollow\">Sourcing policy</a></small></p>\n</aside>\n","humanApproved":true,"illustration":{"altText":"Flat shapes of a ferry crossing a calm blue strait under a pale sky.","base64":"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==","bytes":70,"caption":"Plate 4 - Ferry timetables","height":1,"label":"AI-generated","mime":"image/png","sha256":"6b7fa434f92a8b80aab02d9bf1a12e49ffcae424e4013a1c4f68b67e3d2bbcd0","styleLabel":"House style","url":"https://app.brenzuri.com/api/v1/delivered-illustrations/0d4f6a18-93be-4c27-8a50-e1c2b7d9f346?exp=1791462730&sig=6b5585fb8fc62e4631a8a11490bfdb305d7e7ad20a2e25dc520f06941457cad4","urlExpiresAt":"2026-10-08T12:32:10Z","width":1},"jsonLd":"{\"@context\":\"https://schema.org\",\"@type\":\"BlogPosting\",\"citation\":[{\"@type\":\"CreativeWork\",\"name\":\"Northern route: one timetable from 3 November\",\"publisher\":{\"@type\":\"Organization\",\"name\":\"harbour-authority.example\"},\"url\":\"https://harbour-authority.example/news/northern-route-timetable\"},{\"@type\":\"CreativeWork\",\"name\":\"Ferries to share a timetable\",\"publisher\":{\"@type\":\"Organization\",\"name\":\"coast-gazette.example\"},\"url\":\"https://coast-gazette.example/transport/ferries-share-timetable\"}],\"description\":\"The harbour authority adds 14 daily crossings from March; what changes for commuters, and what the new timetable leaves out.\",\"headline\":\"Ferry operators agree on a single timetable for the northern route\",\"keywords\":\"ferries, commuting, harbour\",\"wordCount\":412}","seo":{"metaDescription":"The harbour authority adds 14 daily crossings from March; what changes for commuters, and what the new timetable leaves out.","slug":"harbour-ferry-timetable-changes","tags":["ferries","commuting","harbour"]},"sources":[{"official":false,"outlet":"harbour-authority.example","score":75,"title":"Northern route: one timetable from 3 November","url":"https://harbour-authority.example/news/northern-route-timetable"},{"official":false,"outlet":"coast-gazette.example","score":75,"title":"Ferries to share a timetable","url":"https://coast-gazette.example/transport/ferries-share-timetable"}],"status":"draft","title":"Ferry operators agree on a single timetable for the northern route","version":1,"words":412}
JSON
SIG=$({ printf '%s.' "$TS"; cat body.json; } | openssl dgst -sha256 -hmac "$SECRET" -hex | sed 's/^.* //')
curl -i -X POST "http://localhost:3000/brenzuri/articles" \
-H "Content-Type: application/json" \
-H "X-Brenzuri-Event: article.delivered" \
-H "X-Brenzuri-Delivery: 0d4f6a18-93be-4c27-8a50-e1c2b7d9f346" \
-H "X-Brenzuri-Timestamp: $TS" \
-H "X-Brenzuri-Signature: $SIG" \
--data-binary @body.jsonSECRET="whsec_local_test"
TS=$(date +%s)
BODY='{"event":"connection.test"}'
SIG=$(printf '%s.%s' "$TS" "$BODY" | openssl dgst -sha256 -hmac "$SECRET" -hex | sed 's/^.* //')
curl -i -X POST "http://localhost:3000/brenzuri/articles" \
-H "Content-Type: application/json" \
-H "X-Brenzuri-Timestamp: $TS" \
-H "X-Brenzuri-Signature: $SIG" \
-d "$BODY"What you see in Brenzuri #
| Delivery status | Means |
|---|---|
delivered | |
retrying | |
held | |
cancelled |
POST /articles/{id}/deliver as a Delivery.
Limits #
One connection per site, and a connection serves one site. The body is signed but not encrypted beyond https. The signature has no replay protection beyond the timestamp; your deduplication provides the rest.