Signed requests, idempotent imports and webhooks that survive downtime
I'm a backend developer on Quikkred Collect, a network of vetted field agents who visit borrowers with overdue loans. Lenders hand their cases to the network through one public partner API (now published as the Fieldproo
I'm a backend developer on Quikkred Collect, a network of vetted field agents who visit borrowers with overdue loans. Lenders hand their cases to the network through one public partner API (now published as the Fieldproof Partner API), and I built most of that API and wrote its developer docs.
An API that moves loan cases and money has to answer three questions before a lender will trust it:
- Is this request really from that lender, and unchanged? (signing)
- What happens when the same request arrives twice? (idempotency)
- What happens when the lender's server is down? (webhook delivery)
Everything below matches the public docs. The code is simplified for the post.
1. Signing every request
Each lender gets a two-part credential: a key ID, sent as Authorization: Bearer <keyId>, and an HMAC secret that is shown once and never travels over the wire. Every request carries a timestamp and an HMAC-SHA256 signature over a canonical string:
signature = hex( HMAC-SHA256( METHOD + "\n" + PATH + "\n" + TIMESTAMP + "\n" + RAW_BODY, secret ) )
Each part is there for a reason:
- Method and path, so a valid signature for one endpoint can't be replayed against another. The path is exactly as sent, without the query string.
- The timestamp, inside the signed string, in milliseconds. The server rejects anything more than five minutes off, so a captured request goes stale quickly, and nobody can attach a fresh timestamp to an old signature.
- The raw body bytes. This is the mistake everyone makes once: parse the JSON, re-serialise it, sign that, and the key order or whitespace no longer matches what was sent.
Signing on the client is a few lines:
import { createHmac } from "node:crypto";
export function signedHeaders({ method, path, body = "", secret }) {
const timestamp = Date.now().toString(); // milliseconds
const canonical = [method.toUpperCase(), path, timestamp, body].join("\n");
return {
"X-Fieldproof-Timestamp": timestamp,
"X-Fieldproof-Signature": createHmac("sha256", secret).update(canonical).digest("hex"),
};
}
Verifying is the same computation plus two safety rules: a time window, and a constant-time comparison so response timing doesn't leak how much of a forged signature was right.
import { createHmac, timingSafeEqual } from "node:crypto";
const FIVE_MINUTES = 5 * 60 * 1000;
export function verify({ method, path, timestamp, signature, rawBody, secrets }) {
const ts = Number(timestamp);
if (!Number.isFinite(ts) || Math.abs(Date.now() - ts) > FIVE_MINUTES) return false;
const canonical = `${method}\n${path}\n${timestamp}\n${rawBody}`;
const given = Buffer.from(String(signature).toLowerCase(), "hex");
// A list of secrets, so rotating a key never breaks verification.
return secrets.some((secret) => {
const expected = createHmac("sha256", secret).update(canonical).digest();
return given.length === expected.length && timingSafeEqual(given, expected);
});
}
Two details worth copying:
-
A fixed order of checks. Missing headers, content type and body size are checked first, then the signature, and only then the payload schema. So a
401always means "your credentials", never "your payload". - Published test vectors. The docs list a secret, a timestamp and the expected signatures, so a lender can check their signing code offline before touching the network.
2. Idempotency in three layers
Networks retry, cron jobs retry, and people re-upload the same file. Re-sending a batch of cases must never open duplicate cases or move money twice. The push API stacks three layers:
| Layer | What it does |
|---|---|
| Batch content hash | Every committed batch is hashed. Re-sending an identical batch is a no-op that returns the original summary. |
Idempotency-Key header |
Optional, scoped to the organisation, kept for 24 hours. A repeat returns the original response verbatim with X-Idempotent-Replay: true. |
| Upsert on the loan number | A loan has at most one active case. A row for a loan that already has one updates it instead of opening a second. |
On the client, a retry after a timeout reuses the same key and checks the header:
const res = await fetch(`${BASE_URL}/api/v1/partner/cases`, {
method: "POST",
headers: {
Authorization: `Bearer ${KEY_ID}`,
"Content-Type": "application/json",
"Idempotency-Key": batchId, // the SAME key on every retry of this batch
...signedHeaders({ method: "POST", path: "/api/v1/partner/cases", body, secret }),
},
body,
});
if (res.headers.get("X-Idempotent-Replay") === "true") {
// We had already committed this batch; this is the original answer.
}
One design choice worth calling out: the key is not compared against the body. Some APIs reject a reused key that arrives with different data. Here, the loan-number upsert already makes a retry harmless even when it carries new data, so the key only has one job: making a network retry free.
There's also a dry-run mode: the same validation, nothing written, no events, so a lender can check a new file before committing it.
3. Webhooks that survive downtime
Lenders need to know when a case is visited, paid or closed. Calling their server from inside the request that changed the case is fragile: if they're down, the update is gone.
Instead, every business event is written to a durable event store right after the change it describes, and two independent paths read from that store:
-
Webhooks, delivered with a retry ladder of
0s β 30s β 2m β 10m β 1h β 6h β 24h: seven attempts over about 31 hours. Every attempt is recorded in a delivery log, and any event can be replayed for about 13 months. A circuit breaker pauses deliveries to an endpoint after 20 consecutive failures, probes it every 15 minutes, and drains the backlog oldest-first once it recovers. - A poll feed that serves the same event envelopes, for lenders who would rather not run a webhook endpoint at all.
To be precise: writing the event is not part of the same database transaction as the case change, so a crash in that tiny window could, very rarely, lose an event. The docs say so, and that's why a daily full snapshot and a per-case GET exist as the authoritative backstop.
Delivery is at-least-once, so duplicates are normal and the receiver deduplicates on the event ID. Order isn't guaranteed either (up to 25 deliveries can be in flight), so every event carries a per-case, monotonically increasing sequence: apply anything newer than what you've seen, and never wait for a gap to fill.
Outgoing webhooks are signed with the same scheme in reverse, so a lender verifies us with the code they already wrote to sign their own requests:
app.post("/webhooks/fieldproof", express.raw({ type: "application/json" }), async (req, res) => {
const ok = verify({
method: "POST",
path: "/webhooks/fieldproof", // the public path you registered
timestamp: req.get("X-Fieldproof-Timestamp"),
signature: req.get("X-Fieldproof-Signature"),
rawBody: req.body.toString("utf8"),
secrets: [CURRENT_SECRET, PREVIOUS_SECRET].filter(Boolean),
});
if (!ok) return res.sendStatus(401);
const eventId = req.get("X-Fieldproof-Delivery");
if (await alreadyProcessed(eventId)) return res.sendStatus(200); // a retry or a replay
await applyEvent(JSON.parse(req.body)); // gate case state on the per-case sequence
await markProcessed(eventId);
res.sendStatus(200);
});
Accepting a list of secrets matters more than it looks. After a key rotation, webhooks are signed with the new secret straight away, so a receiver that only knows the old one rejects every delivery until it's redeployed.
4. The docs are part of the API
Signing is the easiest part of an integration to get subtly wrong. So the docs carry the integration as far as they can: a quickstart that gets a first case through in about 15 minutes, signing and verification samples in Node, Python, Java, PHP, Go and C#, the offline test vectors, a sandbox-only endpoint that shows the canonical string the server computed when a signature fails, and a go-live checklist.
Try it
I put a small in-browser version of this flow on my portfolio: sign a request, replay it, tamper with it, or send a stale one, and see how the server responds. It uses the browser's real Web Crypto HMAC, and nothing leaves your browser. (The demo uses the stricter variant that rejects a reused key with a different body.) mohitpatel.org β Lab β Signed API
If you're building something similar, I'd love to compare notes in the comments.
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.