ochk.app · Webhooks
Every event your project records is delivered to your registered endpoints as its receipt, signed with me.ochk.io's Ed25519 webhook key. Verify the signature against the raw request body — frameworks that re-serialize before your handler will produce a different byte sequence and the signature will not validate.
The key set is at
https://me.ochk.io/api/dev-jwks (opens in a new tab) (the path
is historical; it is the production key). It is not the sign-in key set at
ochk.io/.well-known/jwks.json: that one signs session tokens, and a webhook
checked against it always fails with an unknown kid. Both SDKs fetch the right
one and cache it for an hour.
Reception · Node + ExpressLink to this section
import { oc } from '@orangecheck/me-client';
import express from 'express';
declare function onOcEvent(envelope: unknown): Promise<void>; // your handler
const app = express();
app.use(express.text({ type: 'application/json' })); // raw body!
app.post('/api/oc/webhook', async (req, res) => {
const result = await oc.webhook.verify(
req.body,
req.header('OC-Signature'),
req.header('OC-Key-Id')
);
if (!result.ok) return res.status(401).end(result.reason);
const envelope = JSON.parse(req.body);
// envelope.kind === 'oc-billable-event' | 'oc-system-event'
// envelope.subtype === 'session_creation' | 'connect.claimed' | …
// A billable event's id is in the signed body; a system notice has none,
// only the OC-Envelope-Id header. Deduplicate on whichever it has.
await onOcEvent(envelope);
res.status(200).end();
});
Reception · PythonLink to this section
orangecheck 2.3 or later (pip install orangecheck). verify_webhook takes
the request headers and the raw body, and returns the parsed event or raises
InvalidWebhook with a one-word reason.
from fastapi import FastAPI, HTTPException, Request
from orangecheck import InvalidWebhook, verify_webhook
app = FastAPI()
seen: set[str] = set() # use your database in production
def on_oc_event(event: dict) -> None: ... # your handler
@app.post("/api/oc/webhook")
async def oc_webhook(request: Request):
raw = await request.body() # the bytes as sent, never the parsed JSON
try:
event = verify_webhook(request.headers, raw)
except InvalidWebhook as err:
raise HTTPException(401, err.reason)
# A billable event's id is in the signed body. A system notice
# (connect.claimed, escrow.low, …) has none: its id is the OC-Envelope-Id header.
event_id = event.get("id") or request.headers.get("OC-Envelope-Id")
if event_id in seen: # deliveries can repeat
return {}
if event_id:
seen.add(event_id)
on_oc_event(event)
return {}
In Flask, pass request.headers and request.get_data(); in Django,
request.headers and request.body.
Reception · Rust + AxumLink to this section
use axum::{extract::State, http::StatusCode, response::IntoResponse};
use ed25519_dalek::{Signature, Verifier, VerifyingKey};
async fn webhook(
State(pub_key): State<VerifyingKey>,
headers: axum::http::HeaderMap,
body: bytes::Bytes,
) -> impl IntoResponse {
let sig_hex = headers.get("OC-Signature").and_then(|v| v.to_str().ok()).unwrap_or("");
let sig_bytes = hex::decode(sig_hex).unwrap_or_default();
let Ok(sig) = Signature::from_slice(&sig_bytes) else {
return StatusCode::UNAUTHORIZED;
};
if pub_key.verify(&body, &sig).is_err() {
return StatusCode::UNAUTHORIZED;
}
let envelope: serde_json::Value = serde_json::from_slice(&body).unwrap();
process_event(envelope).await;
StatusCode::OK
}
Headers OC sendsLink to this section
| Header | Meaning |
|---|---|
OC- | Ed25519 signature, hex-encoded, computed over the raw body |
OC- | kid of the OC public JWK that signed the event |
OC- | The event's id for a billable event; for a system notice, which has no id in its body, the delivery's own id. Not signed |
OC- | Event subtype, copied for routing convenience |
OC- | A · B · C: One-time, Per action, Per session · system for project notices |
OC- | 1-based attempt counter, updated on each retry (the signature is unchanged) |
Content- | application/ |
What the body carriesLink to this section
A billable event arrives as the event itself plus three fields:
| Field | Meaning |
|---|---|
kind | oc- |
sub | The person, as a pairwise id for your project only. It is not their did_; the response to the event you fired carries it too. |
scopes | Fields the person agreed to share with you, when there are any |
id, subtype, … | The event: id, occurred_, class, subtype, site, the fee split, context, verify_ |
A project notice (OC-Class: system) is
{ kind: 'oc-system-event', subtype, project_key, … } with no id. It names no
person, except connect.claimed, which carries the did_oc your Connect app
was given and the person's sub for your project. A webhook gets every notice
through *, or only the ones it names in subscribed:
| Subtype | When |
|---|---|
escrow. | Your balance fell below its floor |
escrow. | Billing paused: your available balance is under the last refused event's fee, or under 1 sat when none stands |
escrow. | Your balance is back above its floor |
drop. | A drop window closed: see Drops |
connect. | A person claimed the account your Connect app made for them |
federation. | Your project's federation is being replaced. Top-ups pause now; events and sign-in carry on. The project and its balance move no sooner than flip_. successor names the new federation, its threshold, charter and guardian keys |
federation. | That move is off, and top-ups work again |
The three escrow notices come once for each change of state. escrow.depleted
says billing is paused. An event is refused with 402 escrow_depleted as soon
as the available balance can't cover its fee, and from then on the project
counts as depleted while the balance stays under that fee. The fee stands for an
hour after the last refusal, each refusal renewing it. Money paid into the
balance clears it: a top-up, a refund, an adjustment or preview credit, but not
a per-event rebate. With no refused fee standing, depleted means under 1 sat.
escrow.low means the available balance is under its floor, and
escrow.recovered that it is back above it. The state is checked after an
event's debit settles, and, since no debit settles while events are refused,
after a refused event too, at most once a minute per project. When events
arriving together see different states, the later state is announced too, not
only the first. The project's owner sees each change in their ochk.app
notifications, and escrow.depleted also by email when their account has a
verified one, unless they turned notification emails off. When some balance is
left, the depleted notice names what is spendable against what the refused event
needed, and says billable events costing more than that are paused.
Both federation notices carry migration_id, from and to. The project's
owner also sees each one in their ochk.app notifications, and by email when
their account has one, unless they turned notification emails off. The
unsubscribe link in any such email turns them off for the whole account,
accounts merged into it included.
@orangecheck/me-client 0.41.0 or later types both:
FederationMigratingWebhookPayload (with flip_not_before, an ISO time, and
successor: slug, name, threshold, network, charter_hash, and the
seats' operator keys as guardians) and
FederationMigrationCancelledWebhookPayload.
import type {
FederationMigratingWebhookPayload,
SystemWebhookPayload,
} from '@orangecheck/me-client';
declare const body: string; // the raw body, verified
const notice = JSON.parse(body) as SystemWebhookPayload;
if (notice.subtype === 'federation.migrating') {
const move = notice as FederationMigratingWebhookPayload;
console.log(
`top-ups pause; ${move.from} moves to ${move.successor.name} no sooner than ${move.flip_not_before}`
);
}
Delivery semanticsLink to this section
| Guarantee | At-least-once. Deduplicate a billable event on its id, from the signed body: the signature has no timestamp, so that is also your replay protection. A system notice has no id in its body; deduplicate it on OC-, which is not signed, and handle it so a repeat changes nothing. |
| Ack | Any 2xx within 8 seconds. A redirect is not followed or retried: register the final URL. |
| Retry schedule | 6 attempts: at once, then 30 s, 5 min, 30 min, 2 h and 12 h after each failure. Retries are picked up by an hourly sweep, so each can run up to an hour after it is due. |
| After that | The delivery is dead-lettered: listed with your webhooks for 30 days, where you can requeue it, and the project's owner gets a webhook. notice in their ochk.app notifications. A failed delivery whose retry cannot be queued is dead-lettered at once, with the same notice. System notices take the same path. If neither can be written, the delivery is lost; orangecheck counts each one for its operators (webhooks.). The endpoint is not muted, and the event stays at /. |
The raw-body trapLink to this section
Verify against the raw bytes, not the parsed JSON.
JSON.parse(body) then JSON.stringify(value) produces a different byte
sequence — different key order, different whitespace, different number
formatting. The signature is computed over the original bytes; re-serialized
bytes will not match.
| Framework | The fix |
|---|---|
| Express | app. — accept body as a raw string. |
| Next.js Pages API | export const config = { api: { bodyParser: false } } — disable body parsing, then read the stream into a Buffer. |
| Fastify | Use a preParsing hook to capture the raw body before parsing. |
| Hono | c. to get the raw string. |
| Rust + Axum | body: bytes: extractor, never Json<…>. |
Test with a real deliveryLink to this section
On your project, Send a test event fires a sample event under your project key. It is stored with your project's events and delivered to every webhook you registered, signed like any other delivery, so your receiver should accept it. Deliveries that run out of retries are listed with your webhooks, where you can requeue them.
Handler patterns we recommendLink to this section
import { oc } from '@orangecheck/me-client';
import express from 'express';
import { LRUCache } from 'lru-cache';
declare function onOcEvent(envelope: unknown): Promise<void>; // your handler
const app = express();
app.use(express.text({ type: 'application/json' })); // raw body!
// Idempotency · keep a small cache of recently seen envelope ids.
const seen = new LRUCache<string, true>({ max: 10_000 });
app.post('/api/oc/webhook', async (req, res) => {
const result = await oc.webhook.verify(
req.body,
req.header('OC-Signature'),
req.header('OC-Key-Id')
);
if (!result.ok) return res.status(401).end(result.reason);
const envelope = JSON.parse(req.body);
// A system notice has no id in its body; its id is the OC-Envelope-Id header.
const id: string | undefined = envelope.id ?? req.header('OC-Envelope-Id');
if (id && seen.has(id)) return res.status(200).end(); // already processed
if (id) seen.set(id, true);
try {
await onOcEvent(envelope);
res.status(200).end();
} catch (err) {
// Don't 5xx unless you actually want the retry; otherwise log + 200.
console.error(err);
res.status(500).end();
}
});