> [Agent navigation index](/llms.txt)

# Brix service signatures

A Brix service signature proves that a request came from another of your services, one holding a shared key: an edge calling its Lambda origin, a CMS sending events to a pipeline, or one Node service calling another. Brix signs and verifies the [Brix service signature profile](https://github.com/eberrydigital/brix/blob/main/service-signatures/README.md), a strict profile of [RFC 9421 HTTP Message Signatures](https://www.rfc-editor.org/rfc/rfc9421) with an [RFC 9530 `Content-Digest`](https://www.rfc-editor.org/rfc/rfc9530) for the body. Every Brix framework implements the same profile, so a signature made by one verifies in any other. Brix passes the profile's known-answer vectors, through its verifier and through the generated Lambda handler with real routing. An independent RFC 9421 library also verifies the valid vectors, which shows they are ordinary RFC 9421 signatures and nothing more: it knows none of the profile's restrictions.

`brix/service-signatures` is server-only and framework-free. It uses WebCrypto (`crypto.subtle`), so it runs on Node, Lambda, and worker runtimes without Brix's server.

## Service signatures and brix-auth

Service signatures and [brix-auth](/docs/server-brix-auth.md) are two layers, not alternatives:

- **Service signatures are the front door.** They prove that a request came through your own infrastructure, such as an edge calling its origin, and arrived unmodified. They are never a login and carry no identity: `getServiceSignature(c)` tells a route which boundary the request crossed, never who sent it.
- **brix-auth says who.** People, CI jobs, e2e runs and other services are brix-auth principals with tokens and roles, checked once, at the edge or at the origin with `brix/auth/server`, whose verified identity routes read with `c.get("auth")`.

To call a Lambda behind the edge, call the public edge URL with a brix-auth Bearer token, from `brix-auth token <service>` or `brix-auth curl`. The edge forwards the request signed and passes the user's access token to the origin as `Authorization: Bearer`, which a route with `auth: true` verifies. The generated Lambda handler checks the signature before the application runs, so a request without a valid signature never reaches the auth middleware. Never give a service key to a person or a CI job, and never treat a valid signature as a signed-in principal.

## What a signature covers

A signed request carries `Signature-Input`, `Signature`, and, when the body is not empty, `Content-Digest`:

```http
Content-Digest: sha-256=:fL0TfxMw59sMfDZtWZryRg5CMhuqpyPFP2+qGYF/rug=:
Signature-Input: brix=("@method" "@authority" "@path" "@query" "content-digest" "content-type");created=1799999980;keyid="sZfug8vP";nonce="evt-42";alg="hmac-sha256";tag="lnl/ssg-event"
Signature: brix=:31Y7151xkjNpqNbKT9oIarkLdKgMnxFY6XvMnVY3AyU=:

```

- The method exactly as sent, the host the request is sent to (`@authority`, from the `Host` header: a host name of letters, digits and inner hyphens, or an IPv4 address, with at most one port from 1 to 65535), the raw path and the raw query are always covered. A non-empty body adds its digest and then, when present, `Content-Type` and `Content-Encoding`, in that order, immediately after the digest and never without it. Then come any headers the signer vouches for, such as `x-original-host`; `Host`, `Content-Type` and `Content-Encoding` are never among them. A signature covers at most 24 components.
- The **purpose**, which RFC 9421 carries as the `tag` parameter, names the boundary, such as `brix/edge-origin` or `lnl/ssg-event`, and every key belongs to one purpose. A purpose is `owner/name`: 3–128 characters, an owner of `a-z 0-9 . -` and one or more `/`-separated parts of `a-z 0-9 . _ -`, each part starting with a letter or digit, exactly `^[a-z0-9][a-z0-9.-]*(/[a-z0-9][a-z0-9._-]*)+$`. A key never contains `/`, so a purpose can never be mistaken for a key. A `Signature-Input` with any other purpose, such as `edge-origin` or `Brix/edge-origin`, is `malformed`, and signers refuse it. A receiver accepts only the purposes it is configured with and looks the key up only among that purpose's keys, so a key for one boundary cannot sign for another.
- `created` limits replay: a receiver rejects signatures more than 5 seconds in the future or older than its maximum age (30 seconds by default), counting in whole seconds. There is no replay cache. When an operation must not run twice, sign a `nonce`, such as an event id, and refuse one you have already processed.
- The path must be visible ASCII starting with `/`, with no `\` and no `.` or `..` segment in any spelling (`%2e`, `.%2E`, with `;` parameters as in `..;`, or between encoded slashes or backslashes as in `/doc/..%2F..%2Fetc` and `/public/..%5Cadmin`), because routers and route parameters resolve those differently from the bytes that were signed. Covered header values must be visible ASCII, spaces and tabs, and not empty: HTTP stacks drop an empty header before the application sees it.
- A path has exactly one spelling. Every `%` starts a two-digit **uppercase** hex escape, and:
  - spaces, non-ASCII characters and ``" # < > \ ^ ` { }`` are always encoded, as browsers and `fetch` encode them (a literal `#` would end the path for most receivers);
  - the escapes of non-ASCII bytes spell valid UTF-8, so `/%FF`, a truncated sequence such as `/s%C3k` and an overlong one such as `/%C0%AF` are `malformed`;
  - the separators `$ & + , / : ; = @` may be written either way: URL decoders keep them encoded, and they route differently, so neither spelling stands for the other. `%`, `?` and `#` appear only encoded, as `%25`, `%3F` and `%23`;
  - no path carries a control character or DEL, even encoded: `%00` to `%1F` and `%7F` are `malformed`;
  - every other visible ASCII character is written as itself.

  So a URL as a browser or `fetch` sends it is already canonical, `/admin` cannot be sent as `/%61dmin`, and `/s%C3%B6k` cannot be sent as `/s%c3%b6k`. A path in any other form, such as `/a{b}` or `/admin#/x`, is `malformed`, and signers refuse it. Decoding a signed path therefore never turns it into another signed path, and an edge rule that blocks `/internal/` cannot be sidestepped with `/%69nternal/`.

## Keys

A key is a string of at least 43 characters from the base64url alphabet (`A-Z a-z 0-9 - _`), that is at least 32 random bytes encoded, such as the output of `brix sign-request --new-key`. Anything else is refused. Its 8-character key id is derived from the key, so nothing else is configured. Use a separate key per boundary and per environment, and never reuse a secret from another scheme.

```sh
brix sign-request --new-key

```

Import keys once, at startup:

`src/edge-keys.server.ts`

```ts
"use server";

import { importServiceSigningKeys } from "brix/service-signatures";

export const signingKeys = await importServiceSigningKeys(process.env.BRIX_SERVICE_SIGNING_KEYS);

```

`importServiceKey(secret)` imports a single key as a `ServiceKey` with its `keyid`, and `keyidOf(secret)` derives the id alone. To rotate, add the new key to every receiver, switch the signers to it, then remove the old key from the receivers.

### Key names

Every Brix framework reads keys from the same names in the service's secret configuration, so a key is provisioned the same way wherever it is used:

- `BRIX_SERVICE_SIGNING_KEYS`: a signer's keys, a JSON object from purpose to key, such as `{"brix/edge-origin":"…"}`. A signer has one key per purpose. `importServiceSigningKeys` reads it.
- `BRIX_SERVICE_VERIFY_KEYS`: a receiver's keys, a JSON object from purpose to a list of keys, such as `{"brix/edge-origin":["…"]}`, with two keys while rotating. `importServiceVerifyKeys` reads it.

They are the only `BRIX_` names an application may declare in its [environment schema](/docs/environment-schema.md); Brix reserves every other `BRIX_` name. They must be declared `@sensitive`: Brix refuses a schema or resolved environment that declares them otherwise, a deployment binding of either name, and a CI literal export of either. Both functions accept the JSON string or the parsed object, and refuse a configuration with no purposes, a purpose given twice in the JSON, a purpose that is not `owner/name`, a purpose with no keys, or an invalid key. A configuration written the wrong way round, with a key where a purpose belongs (`{"<key>":["<key>"]}`), is refused with an error saying so. Their errors name entries by position (`BRIX_SERVICE_VERIFY_KEYS entry 2, key 1: …`) and never repeat a purpose or a key, so a misplaced key does not reach a startup log. Which purposes a service accepts is not secret and is configured in code.

## Sign a request

`signServiceRequest` takes a `Request` and returns a new signed `Request`, or takes a method, URL, headers and body and returns the `RequestInit` that sends exactly that request with `fetch(url, init)`. A signature is only ever sent to the host it was made for, so it never follows a redirect: both forms have `redirect: "manual"`, and a redirect comes back as the response:

```ts
import { signServiceRequest } from "brix/service-signatures";
import { signingKeys } from "./edge-keys.server.ts";

const request = await signServiceRequest(
  new Request("https://abc123.lambda-url.eu-west-1.on.aws/rooms/sea-view"),
  {
    key: signingKeys["brix/edge-origin"],
    purpose: "brix/edge-origin",
    headers: { "x-original-host": "www.example.com" },
  },
);
const response = await fetch(request);

const url = "https://pipeline.example/events";
const init = await signServiceRequest(
  {
    method: "POST",
    url,
    headers: { "content-type": "application/json" },
    body: JSON.stringify(event),
  },
  { key: signingKeys["lnl/ssg-event"], purpose: "lnl/ssg-event", nonce: event.id },
);
await fetch(url, init);

```

Options are `key`, `purpose` (`owner/name`), optional `nonce`, optional `headers` to vouch for, optional `created` (Unix seconds), and optional `maxBodyBytes`.

- The signer covers the URL's host and path as `fetch` sends them, so sign the URL you send to. It replaces `Signature`, `Signature-Input` and `Content-Digest` only on the request it signs. It refuses a `Host` header that differs from the URL and a host that is not a host name or IPv4 address.
- `headers` maps each lowercase header name the signer vouches for to its value. The signer removes any copy of those headers the request already carried and sets the given value, so it never signs a value it did not choose. It refuses `host`, `content-type` and `content-encoding` as vouched names: the body headers are covered by the profile's own rule whenever there is a body.
- The returned `RequestInit` carries the method as `fetch` sends it (`post` becomes `POST`, as `fetch` uppercases `DELETE`, `GET`, `HEAD`, `OPTIONS`, `POST` and `PUT`), the signed headers, a copy of the signed body bytes and `redirect: "manual"`. Send it unchanged: a different method, body or set of headers no longer matches the signature. A method `fetch` never sends, such as `TRACE`, is refused.
- The body is a string, an `ArrayBuffer` or an `ArrayBufferView`. Any other body, such as `URLSearchParams`, `Blob`, `FormData` or a stream, is refused rather than signed as empty; sign a `Request` built with it instead.
- A string body without a `Content-Type` is signed with `text/plain;charset=UTF-8`, the type `fetch` adds when it sends one, so the signature still covers what is sent.
- The path must be in its one canonical spelling (see above); `signServiceRequest` refuses `/%61dmin` or `/s%c3%b6k` rather than signing a path receivers refuse.
- Sign as the last step before sending, so time spent waiting for a connection does not age the signature.

### Signing body limit

The signer reads the whole body to digest it, up to `maxBodyBytes`: **1 MiB (1048576 bytes) by default**, configurable per call. A larger body, a `Content-Length` over the limit, or a stream that fails before it ends rejects the call, cancels the body stream, and nothing is signed. A service calling another with small payloads can lower it; an edge forwarding uploads needs to raise it. `brix sign-request` signs bodies of at most 1 MiB.

## Verify a request

`verifyServiceRequest` checks a neutral view of the request as it arrived: the method, the `Host` header, the raw path, the raw query, the headers, and the body bytes. Build the view from a Lambda Function URL or API Gateway HTTP API v2 event, or from a `Request`:

```ts
import {
  importServiceVerifyKeys,
  serviceRequestViewFromLambdaEvent,
  verifyServiceRequest,
} from "brix/service-signatures";

const keys = await importServiceVerifyKeys(process.env.BRIX_SERVICE_VERIFY_KEYS);

const result = await verifyServiceRequest(serviceRequestViewFromLambdaEvent(event), {
  keys: { "brix/edge-origin": keys["brix/edge-origin"] },
  maxAge: 30,
  require: ["x-original-host"],
});
if (!result.ok) {
  console.warn("Service signature rejected", result.error);
  return { statusCode: 401, body: "Unauthorized" };
}
result.headers["x-original-host"];

```

`keys` maps each purpose the route accepts to the keys that may sign for it, so pass only the purposes this route accepts. `require` lists vouched headers every accepted signature must cover, such as the public host or client address an edge passes on; it never names `host`, `content-type`, `content-encoding`, the signature fields or a derived component, which the profile covers by its own rules. An empty key configuration, a purpose without keys, or an invalid `require` name throws.

On success the result carries `purpose`, `keyid`, `created`, `nonce` (or `null`), and the trimmed values of the covered headers in `headers`, and is frozen. On failure `error` is the first failed check, in this order:

1. `malformed`: `Signature-Input` or `Signature` is not an RFC 8941 Dictionary.
1. `missing`: neither field has a `brix` member.
1. `malformed`: one field has no `brix` member or either has several; the member is not in the profile's exact serialization (parameter order, no leading zeros, canonical standard base64); its components are missing, out of order, repeated or not allowed; or the method, host, path or query is not valid. A request without exactly one `Host` is `malformed`.
1. `wrong_purpose`, then `unknown_key`: the purpose is not accepted, or none of that purpose's keys has the `keyid`.
1. `missing_header`: a covered header is absent or repeated, or a required header is not covered. A covered header value that is empty or not valid is then `malformed`.
1. `bad_signature`, `from_the_future`, `expired`.
1. `unsigned_body`: the body is not empty and `content-digest`, or a present `Content-Type` or `Content-Encoding`, is not covered.
1. `bad_digest`: `content-digest` is covered and the body is empty, or the body is not the one signed.

A view from `serviceRequestViewFromRequest` whose body is larger than its `maxBodyBytes` is refused as `body_too_large` when the body is read, in place of `unsigned_body` and `bad_digest`. It is Brix's own code, not one of the profile's: answer it with `413`, or `401` like any other refusal.

Every check before `unsigned_body` uses headers alone, and the body is read only once they have all passed, so an unsigned or badly signed request never makes a receiver buffer its body. A view's `body` may therefore be a function that reads it; `verifyServiceRequest` calls it at most once, after the header checks.

Log the code, answer 401, and do not tell the caller which check failed. Trust a header such as `x-original-host` only when it appears in `result.headers`. Never log, reflect or return `Signature` or `Signature-Input`.

Signatures cover the path and query **exactly as sent**, so never verify against a parsed URL: the URL parser resolves dot segments and re-encodes characters, which either breaks valid signatures or makes two different targets look alike. Route and authorize on exactly the path you verified, or on its decoded form: every escape decoded except `%23 %24 %25 %26 %2B %2C %2F %3A %3B %3D %3F %40`, which is `decodeURI` with `%25` kept encoded, as Hono routes. Canonical encoding makes that form one-to-one. Keeping `%25` encoded matters when route parameters are decoded again, as Hono's are: otherwise `/doc/%252E%252E%252Fetc` would hand `../etc` to `/doc/:name`.

- `serviceRequestViewFromLambdaEvent` reads `rawPath`, `rawQueryString`, the `host` header, `cookies`, and the body with `isBase64Encoded`, decoding the body only when verification asks for it. It never falls back to `requestContext.domainName`. Lambda joins a repeated header into one comma-separated line, so a covered header sent twice fails there as `bad_signature` rather than `missing_header`.
- `serviceRequestViewFromRequest(request, { target, authority, maxBodyBytes })` serves other servers. Pass the request target as received, such as Node's `IncomingMessage.url`; without `target` it falls back to `request.url`, which is already parsed. It reads `@authority` from the `Host` header, or from `authority` for an HTTP/2 request without one. It clones the request and reads the clone's body, up to `maxBodyBytes` (1 MiB by default), only when verification asks for it; a larger body, or a `Content-Length` over the limit, is refused as `body_too_large`, and `verifyServiceRequest` throws when the body cannot be read completely. Call it before anything reads the request body.

A view's `headers` is a `Headers` object or a record whose values are strings or arrays, where an array is the header's repeated field lines in order. `Signature-Input` and `Signature` are read across all their lines, and members with labels other than `brix` are ignored. Header names and the host are lowercased in ASCII only.

## Verify in a Brix Lambda application

The generated HTTP Lambda handler can verify every request before the application sees it. It is off by default:

`vite.config.ts`

```ts
import { defineBrixConfig } from "brix/vite";

export default defineBrixConfig({
  platform: "lambda",
  serviceSignatures: {
    purposes: ["brix/edge-origin"],
    maxAge: 30,
    require: ["x-original-host"],
  },
});

```

- `purposes` lists the purposes the application accepts, `["brix/edge-origin"]` by default. A purpose that is not `owner/name` fails the build. The first is the default purpose, which every route accepts. Any further purpose, such as `brix/operator` for people reaching the origin directly as a [break-glass measure](#call-a-protected-service-by-hand), reaches only routes that opt in with [`requireServicePurpose`](#accept-another-purpose-on-a-route).
- `maxAge` is the maximum age in seconds, 30 by default.
- `require` lists vouched headers every accepted signature must cover, none by default. Naming `host`, `content-type`, `content-encoding`, `content-digest`, `signature` or `signature-input` fails the build, because no signer vouches for them.
- `serviceSignatures: true` takes all three defaults.

Keys always come from `BRIX_SERVICE_VERIFY_KEYS`, the [standard name](#key-names) every Brix framework reads. The option requires `platform: "lambda"` with the generated handler; custom Lambda handlers verify with `brix/service-signatures` directly.

Declare the keys as a sensitive string in the [environment schema](/docs/environment-schema.md) and resolve them like any other secret, so they travel in the application's exact [AWS snapshot](/docs/environment-secrets.md) rather than in plain Lambda configuration:

`env/.env.schema`

```dotenv
# @type=string @sensitive @required
BRIX_SERVICE_VERIFY_KEYS=op("op://Storefront/Production/verify-keys")

```

The value is a JSON string holding an object from purpose to a list of keys, such as `{"brix/edge-origin":["<current key>","<previous key>"]}`, read as text so that a purpose given twice is refused. Every accepted purpose needs at least one key. Keys for purposes the application does not accept are ignored, and requests signed for those purposes fail as `wrong_purpose`.

The handler loads and checks the keys when the Lambda starts, before it serves anything: missing or invalid keys, a repeated purpose, a purpose that is not `owner/name` (including a configuration with a key where a purpose belongs), or an accepted purpose without keys fail the function's initialization, and the error names the entry by position without repeating any value. (`brix build` loads the bundle once to prove it initializes; it does so without keys and the handler it builds then serves nothing.)

For each request, the handler:

1. refuses the request as `malformed`, without verifying it, when the path Hono routes on (the application's routing path of the request the adapter builds) is neither the raw path nor its [decoded form](#exact-routing), or when the raw path is not UTF-8 once decoded, because URL parsing can resolve or re-encode a path and a custom `getPath` can decode `%2F`; a request is never routed to a path other than the one signed;
1. decides which purposes the route that will answer accepts (see [Accept another purpose on a route](#accept-another-purpose-on-a-route)), so a signature with any other purpose is `wrong_purpose` from its headers alone, before the body is read or anything runs for the route;
1. verifies the raw event before applying [`BRIX_PUBLIC_ORIGIN`](/docs/deployment-node-aws.md), so `@authority` is the Function URL or API Gateway host the edge signed, and reads the body only once every header check has passed;
1. removes the `brix` members of `Signature` and `Signature-Input` whatever the outcome, and a field they leave empty, so neither request logging nor the application ever sees them; members with other labels, and fields without a `brix` member, belong to other signature schemes and reach the application untouched;
1. on failure, drops the body without decoding it, answers `401` with `{"error":"Unauthorized"}` before cross-origin checks, assets, and routes run, and adds `failure: "service_signature"` and `service_signature: "<error code>"` to the request's [log records](/docs/server-runtime.md);
1. on success, passes on the request with exactly the body bytes that were verified.

The handler sets no body limit of its own: it checks the whole body the event delivered, which Lambda caps at 6 MB.

The verification belongs to that one request: it is bound to the URL the adapter built and consumed when the application first sees it. Once the handler is created, the application refuses every request that did not pass through it as `missing`: a sub-request the application makes with `app.fetch(request, c.env)`, and any other server that calls `app.fetch` with the built application, get `401`. Call another route's code directly instead of dispatching a sub-request. `brix start` refuses to serve a build with `serviceSignatures`, which only its Lambda handler verifies; run it locally with `brix dev`, which does not verify.

Hono answers a `HEAD` request with the `GET` route, so a signed `HEAD` (whose signature covers `@method: HEAD`) runs the `GET` handler and its guard, and the response has no body.

### Exact routing

With `serviceSignatures`, routing is exact: a route matches only its own path, trailing slash included, so a signature for `/admin/` never reaches a route for `/admin`. Routes match the signed path decoded as Hono decodes it: `decodeURI` of the path, which keeps the separators `# $ & + , / : ; = ? @` percent-encoded, with `%25` kept encoded too, and decodes everything else, `%5C` included. Canonical encoding makes that decoding one-to-one (non-ASCII and the always-encoded characters have one spelling, and no literal `%`, `?` or `#` exists), so `/s%C3%B6k` reaches a fixed route written `/sök` and no other signed path can, and `c.req.path` is the decoded path, such as `/search/sök`. `%2F` stays encoded, so `/a%2Fb` is one segment, and `c.req.param()` decodes each value once, so `/search/:term` receives `sök` for `/search/s%C3%B6k`, `100%` for `/search/100%25`, and `/` for `%2F` in a parameter (which is why `..%2F` is refused). `%5C` decodes to `\`, so `/public/a%5Cb` reaches `/public/*` with `c.req.path` `/public/a\b`; that is harmless because no dot segment may sit beside `%5C`, so `/doc/..%5C..%5Cx` is `malformed`. A path whose escapes are not UTF-8, such as `/s%FF`, is `malformed`. Without `serviceSignatures`, Hono routes on the same decoded path and ignores one trailing slash. Brix route paths are authored without a trailing slash (`/startsida`, `/admin`), so under signatures a fixed route serves only that spelling and `/admin/` is `404`. A wildcard route such as `/*` or `/sv/*` matches both spellings: `c.req.path` and the wildcard parameter keep the trailing slash. A site whose public URLs end in `/`, such as `/startsida/`, serves them through a wildcard page route and reads the path from `new URL(c.req.url).pathname`; Brix has no trailing-slash redirect. Development servers route the same way, so a route that works under `brix dev` works when deployed.

### Accept another purpose on a route

Each route accepts only the purposes it lists, and a route without a guard accepts only the default purpose. Opt a route in to other configured purposes with `requireServicePurpose` from `brix/server`, in a Brix route's `middleware` or as the first handler of a Hono route:

```ts
import { requireServicePurpose } from "brix/server";

export const purgeResponseRoute = brixServer.createResponseRoute(purgeContract, {
  middleware: [requireServicePurpose("brix/edge-origin", "brix/operator")],
  handler: async (c) => c.json(await purge(c)),
});

app.use("/operations/*", requireServicePurpose("brix/operator"));
app.get("/operations/queue", (c) => c.json(queue()));

```

The purpose is decided for the route that will actually answer the request, before the body is read and before anything else runs for that route:

- Brix routes (pages, API, response, fragment and Markdown index routes) accept the purposes their guards list, wherever the guards are in `middleware`; with several guards, the purposes every one of them lists.
- For Hono routes registered in `src/app.ts`, Hono runs every matching handler in registration order, and the route that answers is the first matching handler after Brix's own middleware and the `middleware` given to `defineBrixServer`. It accepts another purpose only when that handler is a guard listing it. A guard registered after a route that answers first protects nothing, so it accepts nothing either: with `app.get("/ops/users", users)` followed by `app.use("/ops/*", requireServicePurpose("brix/operator"))`, an operator request to `/ops/users` is `wrong_purpose`. Register the guard first, as above. Hono middleware registered with `app.use("*", …)` in `src/app.ts` comes before every later route too; put application-wide middleware in `defineBrixServer`'s `middleware`.
- A guard in a sub-application added with `app.route()` counts the same way, also when the sub-application has its own `onError`.
- A guard anywhere else is invisible to this decision, so it refuses every request in a production build: in an application added with `app.mount()` (which hands the request to another application, so its guard never sees the verified signature), or inside `every` or `some` from `hono/combine`, even when it lists the default purpose. A refusal inside an `app.mount()`ed application cannot reach the request's log record, so Brix writes it as a `console.warn` line with its error code instead. Use `app.route()` for a Hono sub-application, and register a guard directly.
- Static assets are not served to a request with a purpose other than the default; it reaches the route that accepted it.

A route with a guard accepts exactly the purposes it lists, so `requireServicePurpose("brix/operator")` alone refuses the default purpose. A request signed with a purpose other than the default fails as `wrong_purpose` at any route that does not accept it, and an unmatched path accepts only the default purpose. `requireServicePurpose` throws where it is called when a purpose is not `owner/name`, so a route module with such a guard fails when the application loads, which `brix build` checks.

Where requests are not verified (`brix dev`, the route harness), the guard lets every request through. A production build that registers `requireServicePurpose` on a route without `serviceSignatures` fails instead of shipping a guard that protects nothing: Node and Lambda builds fail their initialization check, and Fastly and Cloudflare applications fail when they load. Wherever else such a build reaches a guard, such as in an `app.mount()`ed application, the guard refuses the request.

Read the verified signature in a route with `getServiceSignature(c)` from `brix/server`:

```ts
import { getServiceSignature } from "brix/server";

const signature = getServiceSignature(c);
const publicHost = signature?.headers["x-original-host"];

```

It returns `undefined` when the request was not verified by the Lambda handler, including under `brix dev` and the route harness, which do not verify signatures. The result belongs to the framework: it is frozen, and application code cannot attach or replace it. Any event other than an API Gateway HTTP API v2 or Function URL event is refused.

## Next to brix-compute and brix-lambda

The Rust frameworks, `brix-compute` on Fastly Compute and `brix-lambda`, sign and verify the same profile, so a Brix service in either language calls the other directly. They differ from Brix here in deliberate ways, which matter when an application is split across both:

- **Routing.** They route a signed request on its path byte for byte, never on its decoded form. A route this guide writes as `/sök` is registered there as `/s%C3%B6k`. Both route strictly: `/admin/` never reaches `/admin`.
- **Purposes.** They have no default purpose: every `Auth::signature` layer lists the purposes it accepts, where Brix has one default purpose and `requireServicePurpose` guards.
- **Body limits.** A Compute signer reads up to 32 MiB of body and fails a larger send with a `413`, so an edge on Compute can forward bodies the 1 MiB `maxBodyBytes` default here refuses. A Compute receiver refuses a body over 32 MiB as `body_too_large`, and `brix-lambda` checks the whole event body, as the generated handler here does.
- **Refusals.** They answer `401` with `{"error":"unauthorized"}` and log the code as `extra.auth.service_signature`, including their own `body_too_large`, `unreadable_body`, `manual_check`, `hop_expired` and `hop_mismatch`.

`brix sign-request` works against either: it signs one request for any receiver of the profile.

## Call a protected service by hand

For everyday calls, do not sign anything yourself. Call the public edge URL with a brix-auth token, as [above](#service-signatures-and-brix-auth): `brix-auth token <service>` prints a Bearer token and `brix-auth curl` sends a request with one. The edge signs the request it forwards.

### Break-glass: reach an origin directly

Signing by hand is for break-glass only: reaching an origin directly while the edge is down or under investigation. A receiver refuses unsigned requests, so `curl` against a protected origin needs a fresh signature. People do not use a service's keys: a receiver that allows it accepts a separate operator purpose, such as `brix/operator`, with keys issued per person. `brix sign-request` prints the signature headers for exactly one request as a curl config, and curl reads it from standard input with `-K -`.

The signature only gets the request past the front door. A route with `auth: true` still needs a brix-auth token, which curl sends as an ordinary header next to the signature:

```sh
url="https://abc123.lambda-url.eu-west-1.on.aws/rooms/?page=2"
op read "op://Operators/me/operator-key" \
  | brix sign-request --key-stdin --purpose brix/operator "$url" \
  | curl -K - --path-as-is -H "Authorization: Bearer $(brix-auth token rooms)" "$url"

op read "op://Operators/me/operator-key" \
  | brix sign-request --key-stdin --purpose brix/operator -X POST --data-binary @event.json "$url" \
  | curl -K - --path-as-is -X POST --data-binary @event.json "$url"

```

```sh
brix sign-request --purpose <purpose> (--key-file <path> | --key-stdin) [-X <method>] [--data-binary @file|<string>] [-H 'Name: value']... [--sign-header <name>]... [--nonce <n>] <url>
brix sign-request --new-key

```

- The key comes from the file named by `--key-file` or from standard input with `--key-stdin`, without one trailing newline, and never from an environment variable. Invalid keys are refused, and the key is never printed. `--new-key` prints a fresh key of 32 random bytes in base64url.
- `--purpose` is required and must be `owner/name`. The output is only `header = "…"` lines for `Content-Digest` (only when there is a body), `Signature-Input` and `Signature`, never a URL, so curl sends exactly one request. Curl config values keep header values whole, which matters because `Signature-Input` contains quotes.
- Pass curl the same URL, `-X`, `--data-binary` and `-H` options you passed `brix sign-request`, plus `--path-as-is` so curl sends the path that was signed. Send a body with `--data-binary`, which sends the bytes unchanged. The method defaults to `POST` with a body and `GET` without, as in curl.
- With a body, curl sends `Content-Type: application/x-www-form-urlencoded` unless `-H` sets one, and `brix sign-request` signs the content type curl will send.
- `--sign-header <name>` covers a header given with `-H`, such as `x-original-host`; it must be given exactly once. It refuses `host`, `content-type` and `content-encoding`, which are covered by the profile's own rules. A `-H 'Host: …'` must name the URL's host (case aside), which is the signed `@authority`; any other `Host` is refused, as `signServiceRequest` refuses it. To reach a different address, such as a load balancer or `127.0.0.1`, put the signed host in the URL and tell curl where to connect with `--connect-to` or `--resolve`: `--connect-to origin.example:443:127.0.0.1:8443`. `Host`, `Content-Type` and `Content-Encoding` may each be given at most once. `--nonce` signs a nonce.
- Never add `-L` (or `--location`) to curl: curl would send the signature on to the host a redirect names.

`brix sign-request` signs the path and query exactly as curl sends them, and refuses a URL whose path the profile refuses or that curl would send differently: `.` and `..` path segments in any spelling (including `..;`, `..%2F` and `..%5C`), escapes of control characters (`%00` to `%1F`, `%7F`), escapes that are not valid UTF-8, a host that URL parsers rewrite (such as `127.1` for `127.0.0.1`; write the host as they give it), a path that is not percent-encoded canonically (`%61`, lowercase hex such as `%c3`, or a bare `%`), spaces and non-ASCII characters (curl encodes or rejects them), `[ ]` and `{ }` outside an IPv6 host (curl expands them as URL globs), IPv6 hosts, and other characters that are not allowed in a path or query. Percent-encode such characters yourself. An empty path is signed as `/`, which curl sends, and a `#fragment` is not sent or signed. A body must be a regular file or a string of at most 1 MiB, read whole. `--data-binary @-` is refused because curl reads the config from standard input.

Local development servers do not verify, so plain `curl` works there; going through the edge works anywhere, because the edge signs.
