Skip to content
brix.v2.15.0+b120c49

Search documentation

Loading search…

    Documentation menu
    On this page

    Sign in with brix-auth

    Sign people and service accounts into a Brix application through the brix-auth authorization server, with tokens kept on the server, and serve MCP endpoints that MCP clients reach as those people.

    brix/auth/server is a Backend-for-Frontend (RFC 10017) client of brix-auth. The server runs the OAuth 2.1 flow with pushed authorization requests (PAR), PKCE S256, and private_key_jwt client authentication, verifies access tokens locally, and keeps tokens in encrypted HttpOnly cookies. Browser code never sees a token. It plugs into the same route auth option described in authentication and security.

    Its behaviour follows brix-auth's normative middleware specification (docs/middleware.md) and passes the shared conformance vectors. It is identical to the brix-auth feature of brix-compute, and the two read each other's cookies when they share a cookieSecret and an origin.

    Start with a working brixServer from server foundations and a service registered in brix-auth. The finished application should send an anonymous visitor through the brix-auth sign-in, render the protected page with the signed-in identity, and answer 401 to an anonymous API call.

    Register the service

    #

    To register an app or service with brix-auth (create the service, its domains, client keys, service accounts and API keys) don't use the dashboard: read https://auth.strawberrylabs.dev/llms.txt and use the brix-auth CLI it describes.

    In brix-auth, the service id is the OAuth client id and the audience of its access tokens. For each domain the application runs on, register the exact redirect URI https://<domain>/auth/callback (http://localhost:<port>/auth/callback for local development). The same registration lets brix-auth's signed-out page link back to the application; see sign out. Register the public half of an EC P-256 key pair as the service's client key and keep the private JWK, with its kid, as an application secret.

    Declare four environment values in env/.env.schema. Mark the key and the cookie secret sensitive:

    • AUTH_ISSUER: the brix-auth origin, such as https://auth.example.com. It must be https and have no path or trailing slash; http is accepted only for localhost and 127.0.0.1.
    • AUTH_CLIENT_ID: the service id.
    • AUTH_CLIENT_KEY: the private JWK as JSON.
    • AUTH_COOKIE_SECRET: unpadded base64url that decodes to at least 32 random bytes, used only for cookie encryption. Generate one with openssl rand -base64 32 | tr '+/' '-_' | tr -d '='. Padding, whitespace, or standard base64 characters are rejected. Rotating the secret signs every user out.

    A malformed setting is a configuration error: static strings throw when createBrixAuth runs, and callback settings answer 500 on the first request that reads them.

    Configure the server

    #
    src/brix.server.ts
    "use server";
    
    import { createBrixAuth } from "brix/auth/server";
    import { defineBrixServer } from "brix/server";
    import type { Context } from "brix/hono";
    import { brix } from "./brix.ts";
    import { env } from "./env.server.ts";
    import type { CoercedEnvSchema } from "./env.generated.d.ts";
    
    type ServerContext = Context<{ Bindings: Readonly<CoercedEnvSchema> }>;
    
    export const brixAuth = createBrixAuth<ServerContext>({
      issuer: (c) => c.env.AUTH_ISSUER,
      clientId: (c) => c.env.AUTH_CLIENT_ID,
      clientKey: (c) => c.env.AUTH_CLIENT_KEY,
      cookieSecret: (c) => c.env.AUTH_COOKIE_SECRET,
    });
    
    export const brixServer = defineBrixServer(brix, {
      env,
      auth: brixAuth.auth,
      integrations: [brixAuth.integration],
    });
    

    Keep the generated route-factory exports below this definition. auth is the route policy, and integration mounts GET /auth/login, GET /auth/callback, and POST /auth/logout, plus the MCP resource metadata and every check on the MCP path when mcp is set. issuer, clientId, clientKey, and cookieSecret each accept a string or a request callback.

    Optional settings:

    • requireRoles: roles every protected route requires, all of them; a missing one answers 403.
    • callbackPath (default /auth/callback): the path of the registered redirect URI.
    • loginPath (default /auth/login): the route that starts a sign-in; see sign in from a public page.
    • logoutPath (default /auth/logout): the logout form target.
    • logoutRedirect (default brix-auth's signed-out page): a same-origin path the browser lands on after logout instead. Point it at a page that does not require a session; see sign out.
    • mcp ({ path, resourceName, origin?, allowedOrigins? }): serves a Model Context Protocol endpoint that MCP clients sign people in to through brix-auth. See serve an MCP server.
    • backend: the Fastly Compute backend for calls to brix-auth. See platform behaviour.
    • fetch (default global fetch): a replacement fetch for calls to brix-auth.
    • timeoutMs (default and maximum 5000): the deadline for each call to brix-auth.

    Use the public origin

    #

    The redirect URI is the request origin plus callbackPath, and the same origin is the one cookie-authenticated mutations must come from. Brix never reads X-Forwarded-Host or X-Forwarded-Proto. Wherever the server sees a different scheme or host than the browser, set BRIX_PUBLIC_ORIGIN to the public HTTPS origin:

    • brix start behind a TLS-terminating proxy or load balancer, where the server otherwise sees http:// and the internal host;
    • Lambda behind CloudFront or another proxy whose hostname differs from API Gateway's.

    Without it, the redirect URI names the internal origin, brix-auth rejects the PAR request because that URI is not registered, and every sign-in answers 500 with a brix.auth.rejected error log for /par. Sign-out and other cookie-authenticated form posts also fail the same-origin check with 403, and the signed-out page cannot link back to the application. An MCP endpoint needs a pinned origin too and answers 500 without one. See Node and Lambda deployment.

    Develop locally

    #

    The cookies are Secure with the __Host- prefix. Chrome and Firefox keep such cookies from http://localhost, so local development works without TLS in those browsers. Safari does not keep Secure cookies from plain http, even on localhost, so sign-in never completes there; use Chrome or Firefox for local development, or serve the application over HTTPS. Other plain-HTTP origins cannot keep a session in any browser.

    Protect routes

    #
    export const dashboardPageRoute = createPageRoute(dashboardPageContract, {
      auth: brixAuth.page,
      component: Dashboard,
      load: (c) => ({ email: c.get("auth").email ?? "", roles: c.get("auth").roles }),
    });
    
    export const meApiRoute = createApiRoute(meApiContract, {
      auth: true,
      handler: (c) => ({ sub: c.get("auth").sub }),
    });
    

    Routes authenticate in one of two modes:

    • Page mode: page routes and fragments given auth: brixAuth.page or auth: { redirectUrl: (c) => "/reports" }. An anonymous GET that is a document navigation starts a sign-in with a 302 to brix-auth. Other requests answer 401 and never start one. Failures are HTML pages.
    • API mode: API routes, response routes, and pages or fragments with auth: true. They never redirect: without a session they answer 401 with WWW-Authenticate: Bearer. Failures are JSON {"error": "<code>"} with unauthorized, forbidden, server_error, or temporarily_unavailable.

    A GET counts as a document navigation when its Sec-Fetch-Mode header is absent or navigate and it has no Sec-Purpose header. Everything else gets the page-mode 401 HTML page with WWW-Authenticate: Bearer, sets no login cookie, and never calls brix-auth:

    • subresources such as /favicon.ico and images (Sec-Fetch-Mode: no-cors);
    • fetch() and XMLHttpRequest calls (cors or same-origin);
    • prefetches and prerenders (any Sec-Purpose, even on a navigation);
    • HEAD, POST, and every other method.

    So a protected page that a browser prefetches, or an anonymous fetch() to a page route, never starts a login in the background or piles up login cookies. A fragment in page mode starts a sign-in only when the browser navigates to it. A deferred fragment fetched by script gets the 401 instead, so give such fragments auth: true for a JSON 401 and let the enclosing page sign the visitor in.

    brixAuth.page returns the visitor to the same path and query afterwards; { redirectUrl } chooses another return path. The return path must start with a single / and contain no backslash. Absolute, protocol-relative, and backslash targets become /. A return path longer than 2048 characters drops its query, and becomes / if the path alone is still too long.

    c.get("auth") holds sub (user:<id> or sa:<service>/<name>), kind ("user" or "service"), email and name when present, roles, sid (the session id), and clientId. A token that a service account minted for a person also holds actor, { sub: "sa:<service>/<name>" }; see act for people.

    clientId is your service's id, except on a token that one of its native apps (its CLI or desktop app, registered with brix-auth native-client add) got for a person: there it is <service>/<name>, such as billing-admin/cli. Such a token is otherwise the person's own token, so every protected route accepts it; check clientId on a route that only the app, or only the browser, may call.

    Roles come from the access token, which lives at most 10 minutes, so grant changes apply at the next refresh. requireRoles on createBrixAuth applies to every protected route. Inside a handler or loader:

    • brixAuth.requireRoles(c, "admin", "billing") throws a 403 unless the identity holds every listed role;
    • brixAuth.requireAnyRole(c, "admin", "support") throws a 403 unless it holds at least one.

    The identity says who is signed in and which roles they hold on this service. Still check in each handler whether that identity may act on the requested record.

    Sign in from a public page

    #

    A public page links to GET /auth/login to offer a sign-in:

    <a href="/auth/login?returnTo=%2Fdashboard">Sign in</a>
    
    • returnTo (optional, default /) is where the visitor lands afterwards. It follows the return path rules above, so an absolute, protocol-relative, or backslash value becomes /.
    • prompt=select_account (optional) makes Google show its account chooser, so the visitor can sign in as someone else. No other prompt value is accepted.
    • A visitor who is already signed in is sent straight to returnTo with 303; with prompt=select_account a new sign-in starts anyway.
    • Otherwise the route starts a sign-in exactly as a protected page does, with a 302 to brix-auth.
    • Like a protected page, it starts a sign-in only for a document navigation. A fetch(), prefetch, or prerender gets the page-mode 401 and starts nothing.
    • A repeated returnTo or prompt, or another prompt value, answers a 400 page. Other methods answer 405 with Allow: GET.

    Sign out

    #

    Sign out with a same-origin form. Logout revokes the refresh token at brix-auth (best effort, so logout still completes while brix-auth is unreachable), expires __Host-brix_at and __Host-brix_rt, and sends the browser to the logout redirect. Other methods answer 405.

    <form method="post" action="/auth/logout">
      <button type="submit">Sign out</button>
    </form>
    

    Sign-out ends this application's session only; the person stays signed in to Google. By default the browser lands on brix-auth's signed-out page:

    <issuer>/signed-out?client_id=<clientId>&login=<public origin>/auth/login
    

    Logout does not redirect there with a 303. Browsers apply a page's CSP form-action to redirects after a form submission, and Brix's default form-action 'self' would silently block a redirect to brix-auth's origin, leaving the person on the page. So when the logout redirect is on another origin, logout answers 200 with a small page that moves on with a <meta http-equiv="refresh"> and a visible Continue link, runs no script, and sends its own restrictive CSP in place of the application's. A logout redirect on the application's own origin, such as a logoutRedirect path, answers 303.

    The signed-out page says "You're signed out of" the service's name and offers two actions:

    • Sign in again opens the application's /auth/login. Google's SSO usually completes it without a prompt.
    • Use a different account opens /auth/login?prompt=select_account, so Google shows its account chooser.

    The login URL is built from the public origin, as the redirect URI is, and loginPath. brix-auth links to it only when its origin is one of the service's registered redirect origins; otherwise it shows a generic signed-out page.

    To land on a page of your own instead, set logoutRedirect to a same-origin path that does not require a session, such as a public home page. If the redirect lands on a protected page, that navigation starts a new sign-in, Google's silent SSO completes it without a prompt, and the person is signed straight back in, so sign-out appears to do nothing.

    How requests are authenticated

    #

    An Authorization: Bearer header is a header credential: the token is verified on its own, and the request never refreshes, redirects, or falls back to cookies. A rejected token answers 401 with WWW-Authenticate: Bearer error="invalid_token" and {"error": "invalid_token"}, so service accounts and agents get predictable failures. Authorization: DPoP is a header credential too, but DPoP-bound tokens are not supported yet, so it always answers 401 with {"error": "unauthorized"} and the bare challenge WWW-Authenticate: Bearer, without an error code. Any other scheme, such as Basic, is ignored and the cookies decide.

    Otherwise the session cookies decide:

    • Valid access cookie: the request continues.
    • Access cookie missing or invalid, with a refresh cookie: Brix refreshes, replaces both cookies on the response, and continues.
    • Refresh answers invalid_grant: the presented cookies are expired, then the request is treated as having no usable session.
    • No usable session: in page mode a document navigation starts a sign-in and every other request answers 401; in API mode the answer is 401 with WWW-Authenticate: Bearer.
    • Missing required role: 403.
    • brix-auth unreachable, past timeoutMs, or answering 5xx, 408, or 429: 503 with Retry-After: 5. The cookies are kept, so the session resumes once brix-auth recovers.
    • brix-auth answers PAR or refresh with any other 4xx: 500, and the OAuth error code is logged as brix.auth.rejected.

    Only cookies that were presented and rejected are expired: a request that carries only an expired access cookie never expires the refresh cookie. A cookie that fails to decrypt counts as absent and is expired.

    Refreshed cookies are added to whatever the handler returns, including a raw Response. brix-auth keeps a refresh token usable until its successor has been used, so parallel requests that refresh at the same moment all succeed.

    Every response the middleware generates carries Cache-Control: no-store. Its logs carry endpoint names, HTTP statuses, and OAuth error codes, never tokens, codes, cookie values, or secrets.

    Access tokens are verified locally. A token is valid only when all of these hold:

    • three base64url segments; the header has alg: ES256 and typ: at+jwt exactly, a kid found in the JWKS, and no crit; the raw r||s ES256 signature verifies;
    • iss equals the issuer, aud is a string equal to the client id (an array is rejected), and client_id is a string;
    • sub and sid are non-empty strings, kind is user or service, and roles is an array of strings;
    • iat and exp are numbers, exp is later than 60 seconds ago, and iat and any nbf are at most 60 seconds ahead;
    • there is no cnf claim;
    • act, when present, is an object whose sub is a non-empty string. Any other act, including null, a string, or an array, rejects the token rather than being ignored, so an agent's token can never pass for the person's own.

    Act for people

    #

    Some work runs for a person long after their browser request: a coding agent, a scheduled job, a queue consumer. Instead of holding a credential that can act as anyone and naming the person in a header, the service asks brix-auth for a delegated token: an ordinary access token for the service whose sub, email, name, and roles are the person's current ones, and whose RFC 8693 act claim names the service account doing the work.

    A service account may act only for people who hold a role on its own service, only once a service owner allows it in brix-auth, and only with the roles the owner chose. It authenticates with a signing key: brix-auth refuses API keys for this, because a leaked API key would act for every member until it expired, while a signing key's private half never leaves the service and each request carries a fresh, single-use assertion.

    brix-auth sa create <service> agent --roles member --description "Agent acting for people"
    brix-auth sa delegate <service> agent on --roles member
    brix-auth signing-key create <service> agent --store 1password --stage <stage>
    

    The token carries the person's current roles that are also among the account's --roles; a person holding none of them is refused. signing-key create stores the private JWK, with kid set to the key id, as BRIX_AUTH_SIGNING_KEY.

    Mint tokens on the server with createBrixAuthDelegation, using that signing key. Create it once per process and reuse it, because it caches tokens; pass it the validated environment (c.env in a request, or the configuration a Lambda handler factory receives):

    // src/delegation.server.ts
    "use server";
    
    import { createBrixAuthDelegation, type BrixAuthDelegation } from "brix/auth/server";
    import type { CoercedEnvSchema } from "./env.generated.d.ts";
    
    let delegation: BrixAuthDelegation | undefined;
    
    export function delegationFor(
      env: Pick<CoercedEnvSchema, "AUTH_ISSUER" | "BRIX_AUTH_SIGNING_KEY">,
    ) {
      delegation ??= createBrixAuthDelegation({
        issuer: env.AUTH_ISSUER,
        service: "blox",
        signingKey: env.BRIX_AUTH_SIGNING_KEY, // private JWK; its kid is the brix-auth key id
      });
      return delegation;
    }
    
    // Later, for the person who scheduled the work: their `c.get("auth").sub` at the time.
    const token = await delegationFor(env).token(run.ownerSub);
    await fetch("https://blox.example.com/api/runs", {
      method: "POST",
      headers: { Authorization: `Bearer ${token}` },
    });
    

    Mark BRIX_AUTH_SIGNING_KEY sensitive in env/.env.schema.

    • token(subject) takes the person's sub (user:<id>), never an email address, and rejects anything else before calling brix-auth. It sends one RFC 8693 token exchange per person, authenticated by a fresh private_key_jwt client assertion signed with the key (iss and sub the key id, aud the issuer, 60 seconds, a unique jti): the service account is the actor, and the subject names the person. There is no actor_token and no refresh token.
    • Tokens are cached per person until a minute before they expire (brix-auth issues them for at most 10 minutes), concurrent calls for one person share one request, failures are never cached, and at most 1000 people are cached at once. forget(subject) drops one person's token, and forget() drops all of them.
    • issuer, service, signingKey (a private EC P-256 JWK in JSON) and keyId (the 20-hex brix-auth key id; defaults to the JWK's kid) are validated when the factory runs, and the key is never part of an error message. fetch, the Fastly backend, and timeoutMs (default and maximum 5000) work as on createBrixAuth. Keep the signing key out of anything a model or a person's workload can read: the process that holds it can act for every person with an allowed role on the service. Hand the short-lived token to that workload instead.
    • A refusal throws BrixAuthDelegationError with brix-auth's code, the HTTP status, its description, and retryable. unauthorized_client means the service account isn't allowed to act for people (brix-auth sa delegate) or the key isn't a signing key; invalid_request with a description means this person can't be acted for now, for example because they have no role on the service any more or must sign in again (brix-auth needs a browser sign-in within 30 days, so scheduled work pauses for people who haven't signed in that long), or they hold none of the roles the account may carry; invalid_client means the key is wrong, expired, or revoked. Stop the work and tell the person rather than retrying. temporarily_unavailable (retryable: true) means brix-auth was unreachable, timed out, or answered 5xx, 408, or 429; try again later. invalid_response means brix-auth answered 200 with a malformed body.

    The receiving routes need no change: a delegated token is a user token, verified and role-checked like the person's own. Check c.get("auth").actor where the difference matters, for example to refuse an action people must take themselves:

    import { HTTPException } from "brix/hono/http-exception";
    
    export const approveApiRoute = createApiRoute(approveApiContract, {
      auth: true,
      handler: (c) => {
        if (c.get("auth").actor) throw new HTTPException(403, { message: "People approve this" });
        return approve(c.get("auth").sub);
      },
    });
    

    brix-auth records every delegated token in the service's audit log, naming the service account and the person.

    Serve an MCP server

    #

    People use internal tools from MCP clients such as Claude Code, claude.ai, Cursor, VS Code, and T3 Code. An application can serve a Model Context Protocol endpoint (streamable HTTP) that those clients reach as the signed-in person, without an OAuth server of its own. Following the MCP authorization specification, the client discovers brix-auth from the application (RFC 9728), identifies itself to brix-auth with a Client ID Metadata Document or through dynamic client registration, and signs the person in there. The application only verifies the access tokens brix-auth issues for the endpoint. If the application runs its own OAuth endpoints for MCP clients, delete them. This needs a brix-auth with MCP client support.

    Name the endpoint's path and its display name in createBrixAuth:

    src/brix.server.ts
    export const brixAuth = createBrixAuth<ServerContext>({
      issuer: (c) => c.env.AUTH_ISSUER,
      clientId: (c) => c.env.AUTH_CLIENT_ID,
      clientKey: (c) => c.env.AUTH_CLIENT_KEY,
      cookieSecret: (c) => c.env.AUTH_COOKIE_SECRET,
      mcp: {
        path: "/mcp",
        resourceName: "Billing admin",
        origin: (c) => c.env.PUBLIC_ORIGIN,
      },
    });
    
    • path is a same-origin path such as /mcp: one or more /-separated segments, each non-empty, not . or .., and made only of A–Z a–z 0–9 - . _ ~ ! $ & ' ( ) + , ; = : @ %. So it starts with a single /, is not /, does not end with /, and has no *. URL parsing must leave it unchanged, so percent-encoded dot segments such as %2e or .%2E are refused too. It must differ from callbackPath, logoutPath, and loginPath. Requests match it exactly as received, percent-encoding and case included; a request the router would still hand to the MCP route under another spelling, such as /mcp/, /%6Dcp, or /tools/7 for /tools/:id, answers 404.
    • resourceName (required) is the display name MCP clients show people, resource_name in the metadata. It may not contain control characters, line or paragraph separators, or invisible format characters such as zero-width spaces and bidirectional controls; the zero width joiner and tag characters of emoji sequences, and variation selectors, are allowed. After trimming it must be 1 to 100 grapheme clusters (user-perceived characters), and the trimmed name is served.
    • origin is the endpoint's public origin, such as https://billing.example.com: an exact https origin, or http://localhost:<port> or http://127.0.0.1:<port> for development and tests, as a string or a request callback. It, or BRIX_PUBLIC_ORIGIN, is required. See pin the public origin.
    • allowedOrigins (optional) lists the exact origins (scheme://host[:port] with http or https, no path, no trailing slash, no wildcard) whose browser pages may call the endpoint. See browser-based MCP clients.
    • Anything else throws when createBrixAuth runs.

    The integration then serves the protected resource metadata at /.well-known/oauth-protected-resource/mcp (the well-known segment inserted before the path), for GET and HEAD, with Cache-Control: public, max-age=300 and Access-Control-Allow-Origin: * so browser-based clients can read it. OPTIONS is a CORS preflight, because MCP SDKs send an MCP-Protocol-Version header: 204 with Access-Control-Allow-Origin: *, Access-Control-Allow-Methods: GET, HEAD, Access-Control-Allow-Headers: *, and Access-Control-Max-Age: 600. Other methods answer 405 with Allow: GET, HEAD, OPTIONS, from other sites too. No metadata is served at the bare /.well-known/oauth-protected-resource. The body is compact JSON with its members in this order:

    {
      "resource": "https://billing.example.com/mcp",
      "authorization_servers": ["https://auth.example.com"],
      "bearer_methods_supported": ["header"],
      "resource_name": "Billing admin"
    }
    

    The resource is the public origin plus the path. It is also the audience of the endpoint's tokens. There is no scopes_supported: brix-auth tokens carry the person's roles, not OAuth scopes, so there is nothing to request and no insufficient_scope step-up challenge.

    Serve the MCP server from a response route with auth: true and hand the request to an MCP server transport. This sketch uses the official TypeScript SDK's web-standard streamable HTTP transport, statelessly; the application adds @modelcontextprotocol/sdk as its own dependency:

    src/features/mcp/responses/mcp/route.ts
    import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
    import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
    import { createResponseRoute } from "#brix/server";
    import { mcpResponseContract } from "./contract.ts";
    
    export const mcpResponseRoute = createResponseRoute(mcpResponseContract, {
      auth: true,
      handler: async (c) => {
        const person = c.get("auth");
        const server = new McpServer({ name: "billing", version: "1.0.0" });
        server.registerTool("whoami", { description: "Who the tools act for" }, () => ({
          content: [{ type: "text", text: person.email ?? person.sub }],
        }));
        const transport = new WebStandardStreamableHTTPServerTransport({
          sessionIdGenerator: undefined,
          enableJsonResponse: true,
        });
        await server.connect(transport);
        const response = await transport.handleRequest(c.req.raw);
        return response.body ? c.body(response.body, response) : c.body(null, response);
      },
    });
    

    The contract is { method: "POST", path: "/mcp" }. Streamable HTTP in MCP 2026-07-28 has no server-sent event stream on GET and no sessions to end with DELETE, and a server that speaks only that revision answers both with 405. Clients that still speak 2025-11-25 may GET the path to open a stream or DELETE it to end a session, and accept 405 as "no stream" and "no session". Answer GET /mcp and DELETE /mcp from two more response routes, with the contracts { method: "GET", path: "/mcp" } and { method: "DELETE", path: "/mcp" }:

    src/features/mcp/responses/mcp-get/route.ts
    export const mcpGetResponseRoute = createResponseRoute(mcpGetResponseContract, {
      handler: (c) => c.body(null, 405, { Allow: "POST" }),
    });
    

    The integration checks the credential itself, before the route is chosen, for every request to the MCP path other than OPTIONS, whatever the route's auth says. A request without a valid token never reaches a handler, so these 405 routes need no auth, and a method with no route answers 401 rather than 404 without a token. auth: true on the POST route types c.get("auth") and is otherwise a no-op there. defineBrixServer throws when its auth is brixAuth.auth but brixAuth.integration is missing from integrations. If the route is reached without the integration anyway, for example through an auth that wraps brixAuth.auth, it answers 500 {"error":"server_error"} and logs brix.auth.mcp_integration_missing instead of serving tools.

    Pin the public origin

    #

    The endpoint's resource URL, the metadata URL in the challenge, the audience its tokens must carry, and the origin that counts as same-origin all come from configuration, never from the request's Host or URL, which a caller can choose. Set mcp.origin, or BRIX_PUBLIC_ORIGIN (see use the public origin); mcp.origin wins when both are set. mcp.origin must be in exact form, such as https://billing.example.com, without a trailing slash or default port. BRIX_PUBLIC_ORIGIN is read as everywhere else in Brix, an https URL reduced to its origin, so https://Billing.example.com/ means https://billing.example.com. On Fastly Compute and other platforms without process environment variables, use mcp.origin:

    mcp: {
      path: "/mcp",
      resourceName: "Billing admin",
      origin: (c) => c.env.PUBLIC_ORIGIN,
    },
    

    With neither, the MCP path and its metadata path answer 500 {"error":"server_error"} with Cache-Control: no-store to every request and log brix.auth.mcp_origin_missing; other routes keep working. A value that is invalid when a request reads it, such as an origin callback that returns https://billing.example.com/ or throws, answers the same and logs brix.auth.mcp_origin_invalid with source (mcp.origin or BRIX_PUBLIC_ORIGIN). There is no fallback to the request origin, under brix dev either: for local development set origin to the local origin MCP clients call, such as http://localhost:3000, and register that endpoint URL with brix-auth.

    Requests to the MCP path

    #

    Requests to the MCP path, with any method, are checked by the integration in this order, before application middleware and before the route is chosen:

    1. Origin. This is streamable HTTP's defence against DNS rebinding. A request without Origin, or whose Origin is the public origin, continues. One whose Origin is in allowedOrigins continues as a cross-origin request. Any other Origin, including null, answers 403 {"error":"forbidden"} without CORS headers, before any credential is looked at.
    2. Preflight. OPTIONS answers 204 with no body and no authentication, and never reaches the route. It carries CORS headers only for an allowed cross-origin request.
    3. Credentials. Every method but OPTIONS needs one, with or without a route for it. Only Authorization header credentials count:
      • Cookies are never read there: no session cookie is opened, refreshed, or expired, no sign-in starts, and the cookie same-origin check does not apply.
      • Without a Bearer credential, DPoP and any other scheme included, the answer is 401 {"error":"unauthorized"} with WWW-Authenticate: Bearer resource_metadata="https://billing.example.com/.well-known/oauth-protected-resource/mcp". That challenge is how an MCP client finds brix-auth.
      • A malformed, expired, or badly signed Bearer token answers 401 {"error":"invalid_token"} with WWW-Authenticate: Bearer error="invalid_token", resource_metadata="…". So does any token whose aud is not exactly the endpoint URL (https://billing.example.com/mcp): the service's own tokens, whose aud is the service id, delegated tokens, tokens for another MCP endpoint or origin, an aud array, and an aud that differs only in case or a trailing slash. So does a token whose service claim is not this service's clientId: brix-auth names the service that registered the resource there, so a resource URL another service registered cannot carry its roles into this one.
      • A valid token continues to the route as on any other route: requireRoles, requireAnyRole, actor, 403 for a missing role, 503 when brix-auth is unreachable, and 500 when it refuses the key set behave the same. Every 401, 403, 500, and 503 here has Cache-Control: no-store and sets no cookie.
    4. Response headers. Every response from the MCP path gets Origin appended to Vary, unless Vary already lists it or is *. A route's response without Cache-Control gets private. Every response to an allowed cross-origin request, the 401s, 403s, 500s, and 503s included, carries the CORS headers described below.

    The tokens are the person's, for this endpoint only: aud is the endpoint URL, never the service id, c.get("auth") is the person with their current roles, and c.get("auth").clientId is the MCP client's id (its Client ID Metadata Document URL, or the mcp_… id brix-auth gave a registered client), not this service's. They last 10 minutes. On every other route aud must still be the service id, so an MCP token there gets the ordinary 401 with WWW-Authenticate: Bearer error="invalid_token".

    Browser-based MCP clients

    #

    Clients that run outside a browser, such as Claude Code, send no Origin, and hosted clients such as claude.ai call the endpoint from their own servers. A browser page on another origin that calls the endpoint directly needs its origin in allowedOrigins:

    mcp: {
      path: "/mcp",
      resourceName: "Billing admin",
      allowedOrigins: ["https://agents.example.com"],
    },
    

    For an allowed origin:

    • The preflight carries Access-Control-Allow-Origin: <origin>, Vary: Origin, Access-Control-Allow-Methods: GET, POST, DELETE, Access-Control-Max-Age: 600, and Access-Control-Allow-Headers with exactly Authorization, Content-Type, Accept, MCP-Protocol-Version, Mcp-Method, Mcp-Name, Mcp-Session-Id, Last-Event-ID, followed by each Mcp-Param-<name> header the preflight's Access-Control-Request-Headers asked for, where <name> is one or more HTTP token characters: lowercased, each name once, in request order. Other requested headers are not allowed. Mcp-Session-Id and Last-Event-ID are no longer part of streamable HTTP in MCP 2026-07-28, but stay allowed for clients that still speak 2025-11-25.
    • Every response, the 401s, 403s, 500s, and 503s included, carries Access-Control-Allow-Origin: <origin> and Access-Control-Expose-Headers: WWW-Authenticate, Mcp-Session-Id, so the client can read the resource_metadata challenge.
    • Access-Control-Allow-Credentials is never sent. No cookie is read on the MCP path, so the client always sends its token in Authorization.

    The MCP path needs no csrf entry and no CORS middleware of its own. The brix-auth integration handles the MCP and metadata paths before application middleware runs, and replaces any Access-Control-* header another middleware set, so an application-wide cors() from brix/hono/cors, even one with credentials: true, neither answers their preflights nor adds credentials to their responses. It exempts exactly those two paths from Brix's cross-origin mutation guard, because its own Origin check is stricter and no cookie is read there. Every other route, the login, callback, and logout routes included, keeps the guard.

    On the brix-auth side, a browser-based client also calls brix-auth's token endpoint, which accepts it only from the origin of one of that client's https redirect URIs that brix-auth permits, or a loopback page on one of its loopback redirect hosts.

    Register the endpoint with brix-auth

    #

    Register the endpoint's URL as an MCP resource of the service:

    brix-auth mcp-resource add <service> https://billing.example.com/mcp
    

    Register it before you deploy the endpoint: until brix-auth issues tokens for it, the middleware refuses every MCP token. The URL must be exactly the metadata's resource, https (or http://localhost:<port> for local development), and on the origin of one of the service's redirect URIs. An origin belongs to the first service that registers an MCP resource there: brix-auth refuses another service's resource on it unless a brix-auth platform admin shares the origin (--share-origin), and refuses any resource on a host that publishes a trusted or used MCP client's metadata document. The first MCP resource on an origin where another service signs people in needs a brix-auth platform admin. Loopback origins (http://localhost:<port> and http://127.0.0.1:<port>) are never claimed, so several services can develop on the same one. brix-auth issues tokens for the URL whose aud is that URL and whose service is the service. Without it, no MCP client can get a token for the service.

    MCP clients identify themselves to brix-auth in one of two ways:

    • With a Client ID Metadata Document: the client id is an https URL, and brix-auth fetches the client's name, redirect URIs, and keys from it. No registration is needed.
    • Through dynamic client registration, for clients that do not publish a metadata document. brix-auth gives them an mcp_… id.

    Clients on the person's computer, such as Claude Code and VS Code, receive the sign-in on http://localhost or http://127.0.0.1, which is always allowed. A brix-auth platform admin decides which hosted clients may return elsewhere:

    • brix-auth mcp-trust add <client-id-url-or-host> trusts a metadata-document client, such as claude.ai, so it may return to https addresses on its own host.
    • brix-auth mcp-redirect add <uri> allow-lists an exact https or app-scheme callback, such as cursor://anysphere.cursor-mcp/oauth/callback. Registered clients need it for every non-loopback callback; metadata-document clients need trust as well for an app scheme.

    People approve each MCP client on a brix-auth consent screen, which names the client's host and the endpoint. Every MCP client asks at every authorization. People revoke a client under My access or with brix-auth mcp-access revoke <client-id> <service> --yes. Service owners see who allowed which client with brix-auth mcp-access list <service>, or on the dashboard's Sessions page (MCP access), and withdraw a client for everyone with brix-auth mcp-access revoke-client <client-id> <service> --yes.

    Check the setup:

    curl -i https://billing.example.com/mcp -X POST
    # 401 with WWW-Authenticate: Bearer resource_metadata="…/.well-known/oauth-protected-resource/mcp"
    curl https://billing.example.com/.well-known/oauth-protected-resource/mcp
    claude mcp add --transport http billing https://billing.example.com/mcp
    

    Then run /mcp in Claude Code and choose the server to authenticate: the browser opens brix-auth, and after sign-in and consent the tools act as you.

    Service signatures and brix-auth

    #

    Service signatures and brix-auth are two layers, not alternatives:

    • Service signatures are the front door. They prove that a request came through your own infrastructure, edge to origin, unmodified. They are never a login and carry no identity.
    • 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 here at the origin.

    On a Lambda origin with serviceSignatures, the generated handler verifies the signature before the application runs. A refused request answers 401 with {"error":"Unauthorized"} and no WWW-Authenticate, and never reaches this middleware: nothing calls brix-auth and no cookie changes. A request that passes reaches the route's auth as usual. getServiceSignature(c) and c.get("auth") are independent: the first names the boundary the request crossed, the second the principal.

    • To call such a service, call the public edge URL with a brix-auth Bearer token for it, from brix-auth token <service> or brix-auth curl; its audience must be this application's clientId. The edge forwards the request signed and passes the access token to the origin as Authorization: Bearer, which routes with auth: true verify as a header credential.
    • Set BRIX_PUBLIC_ORIGIN to the public origin, as in use the public origin. The signature is verified against the host the edge called, before that rewrite; the redirect URI and the same-origin checks use the public origin after it.
    • Signing a request with an operator key and brix sign-request is break-glass only, for reaching the origin directly while the edge is down or under investigation, and a route with auth: true still needs a token. See call a protected service by hand.

    Cookies and request forgery

    #

    All cookies are Secure, HttpOnly, Path=/, without Domain, and use the __Host- prefix, so no sibling subdomain can set or read them:

    • __Host-brix_at: the access token, SameSite=Lax, for the access token's lifetime.
    • __Host-brix_rt: the refresh token, SameSite=Strict, for 24 hours.
    • __Host-brix_login_<id>: one per pending login, holding the state, PKCE verifier, return path, and start time, SameSite=Lax, for 10 minutes. <id> is the first 16 characters of the base64url SHA-256 of the login's state.

    Values are v1. followed by the base64url of a 12-byte random nonce and the AES-256-GCM ciphertext. The key is derived from the decoded cookieSecret with HKDF-SHA256, salt brix-auth-cookie-v1, and the purpose (access, refresh, or login) as info, and the full cookie name is the additional authenticated data, so a value cannot move to another cookie.

    Each login has its own cookie, found again from the callback's state, so logins started in several tabs all complete. At most five are kept; starting a sixth expires the oldest first. Logout expires the session cookies explicitly and never sends Clear-Site-Data, which would clear every site on the registrable domain.

    Sibling subdomains share the registrable domain, so SameSite=Lax does not separate them. Beyond the application-wide cross-origin mutation guard, a cookie-authenticated request with any method other than GET, HEAD, or OPTIONS must carry Sec-Fetch-Site: same-origin, or no Sec-Fetch-Site and an Origin equal to the request origin. Everything else, including Sec-Fetch-Site: none, receives 403 even when csrf.trustedOrigins admits the origin. Cross-origin callers authenticate with bearer tokens instead. The logout route applies the same rule.

    The callback

    #

    GET /auth/callback answers every other method, HEAD included, with 405. It sends Cache-Control: no-store and Referrer-Policy: no-referrer, as does the redirect that starts a sign-in, and its pages never echo text from the query string. In order:

    1. A repeated code, state, iss, or error parameter answers 400.
    2. iss must equal the issuer (RFC 9207). Otherwise the answer is 400 and the login cookie is kept, so a forged response cannot cancel a real sign-in.
    3. The login cookie named after state must decrypt, match state, and be at most 600 seconds old. Otherwise a browser that already has a valid access cookie is sent on with 303 to the login's return path, or /; anyone else gets a 400 "Sign-in expired" page.
    4. error=access_denied answers a 400 "Sign-in was cancelled" page, and any other error a 400 "Sign-in failed" page. Both expire the login cookie.
    5. The code is exchanged. invalid_grant answers a 400 "Sign-in expired" page, another 4xx answers 500, and an unavailable brix-auth answers 503 with Retry-After: 5, keeping the login cookie.
    6. On success both session cookies are set, the login cookie is expired, and the browser is sent to the return path with 303.

    Platform behaviour

    #

    Verification uses Web Crypto only, so it runs on Node, Lambda, Cloudflare Workers, and Fastly Compute. Calls to brix-auth time out after timeoutMs, at most 5 seconds.

    Signing keys come from brix-auth's /.well-known/jwks.json, which brix-auth serves with Cache-Control: public, max-age=300, stale-if-error=86400. Where they are cached depends on the platform:

    • Node, brix start, and Lambda cache the keys in process memory per issuer, for the response max-age (300 seconds when absent, at most an hour). While brix-auth is unreachable, the cached keys stay usable for 24 hours after they expire, so existing access tokens keep working. A token with an unknown kid forces at most one refetch every 30 seconds per issuer and process. Each new process or Lambda container starts with an empty cache.
    • Fastly Compute keeps no memory between requests. Pass backend: the JWKS request then goes through Fastly's HTTP cache, which stores it according to brix-auth's Cache-Control, so most requests never reach brix-auth. The one-hour cap and the default lifetime above do not apply there; the response header decides. Whether a stale key set is served during an outage depends on Fastly applying stale-if-error to that response; without a cached copy, protected requests answer 503. An unknown kid refetches /.well-known/jwks.json?brix_refetch=<window>, a cache entry per 30-second window, so each window reaches brix-auth at most once per Fastly POP. Viceroy, the local Fastly server, has no HTTP cache, so local development fetches the keys on every request that needs them.
    • Cloudflare Workers cache the keys in isolate memory as on Node. An isolate can be discarded at any time, so treat that cache as best effort.

    Test the boundary

    #

    Use the route harness with the production app, and let MSW stand in for brix-auth's /.well-known/jwks.json, /par, /token, and /revoke. Generate an ES256 key pair in the test, serve its public key in the JWKS, and sign access tokens with it, including every claim listed above. For routes where the login itself is not under test, pass such a token as Authorization: Bearer:

    const res = await testApi(meApiRoute, {
      headers: { Authorization: `Bearer ${accessToken}` },
    });
    expect(res.status).toBe(200);
    

    Cover the anonymous case too: a navigation to a page with brixAuth.page or to /auth/login answers 302 to the brix-auth /authorize URL, the same request with Sec-Fetch-Mode: cors or a Sec-Purpose header answers 401, and an API route answers 401. Then continue to middleware, errors, and logging.