Signatures

Two kinds of signature travel between your servers and Lemak. Your requests to us may carry one, which you choose to require. Every webhook we send you carries two, and you should check one of them before you act on it. This page is the whole of both, with test values you can check your code against.

DirectionHeaderSchemesRequired
Your request to usX-SignatureHMAC-SHA256 (v1), Ed25519 (v2)Only if you set signature_scheme
Our webhook to youX-Webhook-SignatureHMAC-SHA256 (v1) and Ed25519 (v2), both on every deliveryCheck at least one

Signing your requests

A bearer key alone means a stolen key is a working key. You can require that every request also carries a signature your servers alone can produce. Choose the scheme under Settings, signature_scheme:

none
The default. The headers below are ignored.
hmac_sha256
Every request carries X-Timestamp and X-Signature: v1=…, an HMAC-SHA256 under a per-account secret.
ed25519
Every request carries X-Timestamp, X-Key-Id and X-Signature: v2=…, an Ed25519 signature under a key pair you generate. Only the public half ever reaches us.

The scheme is a floor. Once ed25519 is set, an unsigned request and an HMAC-signed request are both refused. Set the scheme after your client signs, not before. We recommend ed25519: we never hold anything that can sign as you, and each key can be revoked on its own.

What is signed

Both schemes sign the same string, four lines joined by \n with no trailing newline:

<X-Timestamp>
<METHOD>
<path and query, as sent>
<hex SHA-256 of the body>
  • X-Timestamp is a Unix time in seconds. A request more than 300 seconds from our clock, either way, is refused.
  • The method is upper case. The path is the request target including the query string, exactly as it goes on the wire: /v1/payment_intents?limit=10.
  • The body hash is the lower-case hex SHA-256 of the body bytes. A request with no body hashes the empty string: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.
  • The signature value is standard base64 with padding, with no whitespace. One signature has one spelling; any other spelling is refused.

Every /v1 request is checked, GET included. A failure of any kind, missing, malformed, wrong, stale or already used, answers 401 invalid_signature with param: "X-Signature".

Replay protection, and why a retry must re-sign

We record every accepted (timestamp, signature) pair for the length of its window. A second request with the same pair is refused as a replay, even with a valid signature. Therefore a retry must take a fresh X-Timestamp and compute a fresh signature, while it keeps the same Idempotency-Key, which is what makes the retry safe. If the replay store cannot answer, the request is refused with 503 service_unavailable rather than accepted unchecked; retry it.

Ed25519

Generate an Ed25519 key pair. Register the public key, 32 raw bytes in base64, in the dashboard under Developers. The answer carries an id of the form key_…; send it as X-Key-Id. Several keys may be live at once, so a rotation is: register the new key, switch the client, revoke the old key. Revocation takes effect at once, which is the answer to a leaked private key.

import { createHash, sign } from "node:crypto";

// privateKey: a KeyObject for your Ed25519 private key. keyId: the key_… id you were given.
async function signedFetch(method, path, body, { apiKey, keyId, privateKey, idempotencyKey }) {
  const bytes = body === undefined ? Buffer.alloc(0) : Buffer.from(JSON.stringify(body));
  const ts = Math.floor(Date.now() / 1000).toString();     // fresh on every attempt
  const canonical = [ts, method, path, createHash("sha256").update(bytes).digest("hex")].join("\n");
  const signature = sign(null, Buffer.from(canonical), privateKey).toString("base64");

  return fetch("https://api.lemak.cash" + path, {
    method,
    headers: {
      "Authorization": "Bearer " + apiKey,
      "Content-Type": "application/json",
      "X-Timestamp": ts,
      "X-Key-Id": keyId,
      "X-Signature": "v2=" + signature,
      ...(idempotencyKey && { "Idempotency-Key": idempotencyKey }),
    },
    body: body === undefined ? undefined : bytes,
  });
}

Send the same bytes you hashed. A client that hashes one serialisation and sends another fails every request.

HMAC-SHA256

The signature is v1= plus the base64 HMAC-SHA256 of the canonical string under your account's signing secret, with no X-Key-Id:

import { createHmac } from "node:crypto";
// secret: the 64 hex characters the dashboard shows. The key is the 32 bytes they encode.
const signature = createHmac("sha256", Buffer.from(secret, "hex")).update(canonical).digest("base64");
// X-Signature: "v1=" + signature

Reveal the secret in the dashboard under Developers, on the signing keys tab, with the one-time code of your authenticator app. It needs the owner, admin or developer role. Every reveal is written to the audit log, without the value, and you can reveal it again at any time. One secret serves your test and live keys alike. The secret cannot be rotated yet; if you think it has leaked, move to ed25519.

Verifying our webhooks

One header carries two signatures over the same bytes:

X-Webhook-Signature: t=1760602449,v1=<hex HMAC-SHA256>,v2=<base64 Ed25519>,v1_kid=1,v2_kid=key_…

The signed message is the t value as sent, one dot, and the request body exactly as it arrived on the wire. Read the body as bytes and sign those bytes; a body that has been parsed and re-encoded will not match.

  • t is a Unix timestamp in seconds. Reject a delivery whose t is more than 300 seconds from your clock, in either direction, however good the signature is. A captured body is otherwise a replay for ever.
  • v1 is HMAC-SHA256 under the endpoint secret, hex encoded. Compare in constant time. v1_kid is the version of the endpoint secret that signed it.
  • v2 is an Ed25519 signature under our platform key, standard base64. The public keys are published at GET /v1/webhook_public_keys: each is {id, algorithm: "ed25519", public_key}, with public_key the raw 32 bytes in base64. v2_kid is the id of the key that signed, so verify with that key. Fetch the list at start-up and again when you meet a v2_kid you do not hold, because a rotation publishes a new key here first.

Ignore any field you do not know: a field may be added to this header, as the two key ids were. Checking either signature is enough. v1 proves the delivery was made to this endpoint; v2 proves it came from us and needs nothing you have to keep secret.

import { createHmac, createPublicKey, timingSafeEqual, verify } from "node:crypto";

// Ed25519 raw public key to a Node KeyObject: prepend the fixed SPKI header.
const SPKI_ED25519 = Buffer.from("302a300506032b6570032100", "hex");
const rawToKey = (b64) =>
  createPublicKey({ key: Buffer.concat([SPKI_ED25519, Buffer.from(b64, "base64")]), format: "der", type: "spki" });

function parse(header) {
  return Object.fromEntries(header.split(",").map((f) => {
    const i = f.indexOf("=");                    // base64 ends in "=", so no split("=")
    return [f.slice(0, i).trim(), f.slice(i + 1)];
  }));
}

// body: Buffer of the raw request body. secret: the endpoint secret (hex), or null to skip v1.
// publicKeys: GET /v1/webhook_public_keys as a map of id to public_key, or {} to skip v2.
export function verifyWebhook(header, body, { secret = null, publicKeys = {} }, now = Date.now() / 1000) {
  const f = parse(header);
  if (!/^\d+$/.test(f.t ?? "") || Math.abs(now - Number(f.t)) > 300) return false;
  const msg = Buffer.concat([Buffer.from(f.t + "."), body]);

  if (secret !== null) {
    const want = Buffer.from(f.v1 ?? "", "hex");
    const got = createHmac("sha256", Buffer.from(secret, "hex")).update(msg).digest();
    return want.length === got.length && timingSafeEqual(want, got);
  }
  const pk = publicKeys[f.v2_kid];
  return pk !== undefined && verify(null, msg, rawToKey(pk), Buffer.from(f.v2 ?? "", "base64"));
}

A handler answers a bad signature with a 4xx and does nothing else. It never logs the body of a request it could not verify as if it were ours.

Test values

Run your code on these inputs before you call us. Each output is exact; if yours differs, compare the intermediate values in order. The secret and the key below are examples, never real ones.

Timestamp
1760602449
Request
POST /v1/payment_intents
Body
{"amount":10000,"currency":"THB","merchant_order_id":"order-1001"}
Body hash
f35eb072aef5980a6d03ca6db9b19428b5bffdec3e57b9cb10e6e5023feabdbd
HMAC secret
00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff
Request v1
Ia6LQ2Xe0u0szkQp0JYNXmJGBHgU82x1dg1U47lN2fM=
Ed25519 seed
32 bytes, each 0x07. Its public key is 6kpsY+KcUgq+9VB7Ey7F+ZVHdq6+vnuSQh7qaRRG0iw=.
Request v2
AeqPDl9vlfQhWArvf0RrCEA73V0x/ECMIJaLiXq6bq/teOufBBsqQ5ZcpM2wUuaR7PLwgLzxjz3/U7DWCuKZCg==
Webhook body
{"id":"evt_TEST","type":"payment_intent.succeeded"}, with t=1760602449 and the same secret as the endpoint secret
Webhook v1
b44e45bc2c128fafd1116f706988e8c7df221ff5507aca68a07b4b67125410b5

When a signature does not match

  • The body changed between hashing and sending. Serialise once, hash those bytes, send those bytes. On a webhook, read the raw body before any JSON middleware parses it.
  • The path is not what went on the wire. Sign the path and query exactly as sent, including the leading /v1 and the query string.
  • The secret is used as text. Both secrets are hex. The key is the 32 bytes the hex encodes, not the 64 characters.
  • A retry reused the signature. A request signature is accepted once. Re-sign with a fresh timestamp and keep the Idempotency-Key.
  • The clock is off. More than 300 seconds either way fails. Keep your servers on NTP.
  • The encoding is wrong. A request signature is base64 with padding. A webhook v1 is hex; its v2 is base64.