|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +import { createHmac } from 'node:crypto'; |
| 4 | + |
| 5 | +/** |
| 6 | + * The outbound HTTP signature scheme — the ONE definition every ObjectStack |
| 7 | + * sender signs with and every receiver verifies against. |
| 8 | + * |
| 9 | + * A request carries {@link HTTP_SIGNATURE_HEADER} whose value is |
| 10 | + * {@link signHttpBody} of the exact bytes of its body under the shared secret: |
| 11 | + * `sha256=` followed by the lowercase hex HMAC-SHA256. A request with no body is |
| 12 | + * signed over the empty string, which is what its receiver reads. |
| 13 | + * |
| 14 | + * It lives in `@objectstack/core` because two senders that cannot import each |
| 15 | + * other at runtime both sign with it: `@objectstack/service-messaging`'s durable |
| 16 | + * HTTP outbox (which signs at enqueue) and `@objectstack/service-automation`'s |
| 17 | + * flow `http` node, whose inline arm — and its durable arm's fallback when no |
| 18 | + * outbox is wired — calls `fetch` itself. `service-messaging` re-exports both |
| 19 | + * names unchanged, so its published surface still carries them. ⛔ Never a |
| 20 | + * second copy of this HMAC input anywhere: two copies are how one key comes to |
| 21 | + * mean two things on two arms. |
| 22 | + * |
| 23 | + * What the scheme does NOT own is WHICH bytes are the body — each sender signs |
| 24 | + * the serialization it actually sends. |
| 25 | + */ |
| 26 | + |
| 27 | +/** Header carrying the HMAC-SHA256 signature of the request body. */ |
| 28 | +export const HTTP_SIGNATURE_HEADER = 'X-Objectstack-Signature'; |
| 29 | + |
| 30 | +/** |
| 31 | + * Compute the {@link HTTP_SIGNATURE_HEADER} value for a body: `sha256=<hex>` of |
| 32 | + * `HMAC-SHA256(body, secret)`. |
| 33 | + * |
| 34 | + * The output is safe to persist (it is handed to the receiver on the wire |
| 35 | + * anyway); the `secret` argument is NOT. |
| 36 | + */ |
| 37 | +export function signHttpBody(body: string, secret: string): string { |
| 38 | + return `sha256=${createHmac('sha256', secret).update(body).digest('hex')}`; |
| 39 | +} |
0 commit comments