Dev.to AI πŸ€– Ai πŸ‘ 0 πŸ“– 7 min read

Verify Google-Agent Requests With Web Bot Auth: A Node.js Middleware in ~120 Lines

User-agent strings were never proof of anything. Anyone can send User-Agent: Google-Agent. Until recently the only real check was an IP lookup against a JSON file of ranges. That's changing. Google-Agent, the user-trigg

Verify Google-Agent Requests With Web Bot Auth: A Node.js Middleware in ~120 Lines

User-agent strings were never proof of anything. Anyone can send User-Agent: Google-Agent. Until recently the only real check was an IP lookup against a JSON file of ranges.

That's changing. Google-Agent, the user-triggered fetcher that Google's hosted agents (Project Mariner, for example) use to browse and act on a user's behalf, now signs a subset of its requests with Web Bot Auth, a profile of HTTP Message Signatures (RFC 9421). Google documents it as experimental. Cloudflare and AWS already verify these signatures at the edge.

If you're not behind one of those, or you want the check in your own code, here's how it works and a verifier you can drop into an Express app.

Verify flow

How Web Bot Auth works, in four headers

A signed request from Google-Agent carries:

User-Agent: ... Google-Agent ...
Signature-Agent: g="https://agent.bot.goog"
Signature-Input: g=("@authority" "signature-agent");created=1762950000;expires=1762950060;keyid="poqk...";alg="ed25519";tag="web-bot-auth"
Signature: g=:base64-signature-bytes:

(The exact covered components and parameters above are a representative example. Read them from the live request, not from this post.)

  • Signature-Agent says who is signing. Its value is an origin, and Google's is https://agent.bot.goog.
  • Signature-Input lists which parts of the request are signed (@authority is your hostname), when the signature was created, when it expires, and which key signed it.
  • Signature is the signature itself, under the same label (g).
  • The public keys live in a key directory at a well-known path on the signer's origin:
https://agent.bot.goog/.well-known/http-message-signatures-directory

The directory is a JSON Web Key Set. Each key is identified by its JWK thumbprint (RFC 7638), which is what keyid refers to.

Verification takes three steps: rebuild the exact string that was signed (the signature base), find the key, and check the Ed25519 signature.

Google's rules for verifying

From Google's Authenticate requests with Web Bot Auth (experimental) page:

  1. Fetch the key set from the directory above and cache it according to Cache-Control. Drop cached keys that disappear from the file, because they may be revoked.
  2. Find participating requests by Signature-Agent: g="https://agent.bot.goog".
  3. Verify Signature against Signature-Input per RFC 9421.
  4. Keep IP-based verification (IP ranges, reverse DNS, user agent), because not every request is signed. Google-Agent's ranges are published in a separate user-triggered-agents.json file, not the existing fetcher files.

There's also a note for latency-sensitive endpoints: you can respond first and check the signature afterwards, within its expiry window, then apply any penalty to the caller's later requests.

The verifier

Node 20+, no dependencies. Node's crypto module reads Ed25519 JWKs directly.

// web-bot-auth.mjs
import crypto from "node:crypto";

// Only fetch key directories for signers you choose to trust. Fetching whatever
// origin a request names in Signature-Agent would turn your server into an SSRF relay.
const TRUSTED_AGENTS = new Set(["https://agent.bot.goog"]);
const CLOCK_SKEW_S = 30;
const dirCache = new Map(); // origin -> { keys: Map(thumbprint -> KeyObject), expires }

// Split a structured-field dictionary on top-level commas (not inside quotes or parens).
function splitMembers(value = "") {
  const out = []; let cur = "", depth = 0, inStr = false;
  for (const ch of value) {
    if (ch === '"' && cur.at(-1) !== "\\") inStr = !inStr;
    if (!inStr && ch === "(") depth++;
    if (!inStr && ch === ")") depth--;
    if (!inStr && depth === 0 && ch === ",") { out.push(cur.trim()); cur = ""; continue; }
    cur += ch;
  }
  if (cur.trim()) out.push(cur.trim());
  return Object.fromEntries(out.map((m) => {
    const i = m.indexOf("=");
    return i === -1 ? [m, ""] : [m.slice(0, i).trim(), m.slice(i + 1).trim()];
  }));
}

function parseParams(str) {
  const params = {};
  for (const m of str.matchAll(/;([a-z0-9*_.-]+)(?:=("(?:[^"\\]|\\.)*"|[^;]+))?/gi)) {
    const v = m[2] ?? "true";
    params[m[1]] = v.startsWith('"') ? v.slice(1, -1) : /^-?\d+$/.test(v) ? Number(v) : v;
  }
  return params;
}

function parseSignatureInput(raw) {
  const close = raw.indexOf(")");
  const inner = raw.slice(1, close);
  const components = [...inner.matchAll(/"([^"]+)"((?:;[a-z0-9*_.-]+(?:=(?:"[^"]*"|[^;\s"]+))?)*)/gi)]
    .map((m) => ({ id: m[0], name: m[1].toLowerCase(), params: parseParams(m[2] || "") }));
  return { components, params: parseParams(raw.slice(close + 1)), raw };
}

function componentValue(c, req) {
  const host = (req.headers.host || "").toLowerCase();
  switch (c.name) {
    case "@authority": return host.replace(/:(80|443)$/, "");
    case "@method": return req.method.toUpperCase();
    case "@path": return new URL(req.originalUrl || req.url, "http://x").pathname;
    case "@query": return new URL(req.originalUrl || req.url, "http://x").search || "?";
    case "@target-uri": return `https://${host}${req.originalUrl || req.url}`;
  }
  const v = req.headers[c.name];
  if (v === undefined) throw new Error(`missing covered header ${c.name}`);
  const value = (Array.isArray(v) ? v.join(", ") : v).trim();
  if (c.params.key) { // ;key="g" means: use only that dictionary member's value
    const member = splitMembers(value)[c.params.key];
    if (member === undefined) throw new Error(`no member ${c.params.key} in ${c.name}`);
    return member;
  }
  return value;
}

function signatureBase(input, req) {
  const lines = input.components.map((c) => `${c.id}: ${componentValue(c, req)}`);
  lines.push(`"@signature-params": ${input.raw}`);
  return lines.join("\n");
}

function jwkThumbprint(jwk) { // RFC 7638 for OKP keys
  const json = JSON.stringify({ crv: jwk.crv, kty: jwk.kty, x: jwk.x });
  return crypto.createHash("sha256").update(json).digest("base64url");
}

async function getKeys(origin) {
  const hit = dirCache.get(origin);
  if (hit && hit.expires > Date.now()) return hit.keys;
  const res = await fetch(`${origin}/.well-known/http-message-signatures-directory`);
  if (!res.ok) throw new Error(`key directory HTTP ${res.status}`);
  const { keys = [] } = await res.json();
  const map = new Map();
  for (const jwk of keys) {
    if (jwk.kty !== "OKP" || jwk.crv !== "Ed25519") continue;
    const keyObj = crypto.createPublicKey({ key: jwk, format: "jwk" });
    map.set(jwkThumbprint(jwk), keyObj);
    if (jwk.kid) map.set(jwk.kid, keyObj);
  }
  const maxAge = Number(/max-age=(\d+)/.exec(res.headers.get("cache-control") || "")?.[1] ?? 300);
  dirCache.set(origin, { keys: map, expires: Date.now() + maxAge * 1000 });
  return map; // replacing the whole map also drops keys removed from the directory
}

export async function verifyWebBotAuth(req) {
  const agents = splitMembers(req.headers["signature-agent"]);
  const inputs = splitMembers(req.headers["signature-input"]);
  const sigs = splitMembers(req.headers["signature"]);

  for (const [label, rawInput] of Object.entries(inputs)) {
    const origin = agents[label]?.replace(/^"|"$/g, "");
    if (!origin || !TRUSTED_AGENTS.has(origin)) continue;

    const input = parseSignatureInput(rawInput);
    const { created, expires, keyid, alg, tag } = input.params;
    const now = Math.floor(Date.now() / 1000);
    if (tag !== "web-bot-auth") return { ok: false, reason: "wrong tag" };
    if (alg && alg !== "ed25519") return { ok: false, reason: `unsupported alg ${alg}` };
    if (!created || created > now + CLOCK_SKEW_S) return { ok: false, reason: "bad created" };
    if (!expires || expires < now - CLOCK_SKEW_S) return { ok: false, reason: "expired" };
    if (!input.components.some((c) => c.name === "@authority"))
      return { ok: false, reason: "@authority not covered" }; // else a signature could be replayed on any site

    const sigB64 = /^:(.*):$/.exec(sigs[label] || "")?.[1];
    if (!sigB64) return { ok: false, reason: "no signature for label" };

    const key = (await getKeys(origin)).get(keyid);
    if (!key) return { ok: false, reason: "unknown keyid" };

    const ok = crypto.verify(null, Buffer.from(signatureBase(input, req)), key, Buffer.from(sigB64, "base64"));
    return ok ? { ok: true, agent: origin, keyid } : { ok: false, reason: "signature mismatch" };
  }
  return { ok: false, reason: "no trusted signature" };
}

Wiring it into Express

Don't block on this. Most Google-Agent requests aren't signed yet, and the spec is still a draft. Annotate the request and let your existing bot rules decide.

// server.mjs
import express from "express";
import { verifyWebBotAuth } from "./web-bot-auth.mjs";

const app = express();
app.set("trust proxy", true);

app.use(async (req, res, next) => {
  if (!req.headers["signature-input"]) return next();
  try {
    req.webBotAuth = await verifyWebBotAuth(req);
  } catch (err) {
    req.webBotAuth = { ok: false, reason: err.message };
  }
  console.log(JSON.stringify({ path: req.path, ua: req.get("user-agent"), wba: req.webBotAuth }));
  next();
});

app.get("/", (req, res) => res.send(req.webBotAuth?.ok ? "hello, verified agent" : "hello"));
app.listen(3000);

Log the results for a couple of weeks before you build any policy on them.

Mistakes that make verification pass when it shouldn't

  • Fetching keys for any origin. If your verifier trusts whatever Signature-Agent says and fetches that origin's directory, an attacker just hosts their own directory and signs with their own key. A valid signature only proves the request came from whoever owns that origin. The allowlist is what makes the check mean something.
  • Not requiring @authority. If the hostname isn't covered, a signature captured on one site can be replayed against yours.
  • Ignoring expires. Without it, a signature captured once can be replayed forever.
  • Reading the host from the wrong place. Behind a proxy, check that req.headers.host is still the public hostname the agent signed. Some setups rewrite it to an internal one, which makes every signature fail.
  • Treating "verified" as "trusted". Web Bot Auth tells you who sent the request, not whether you want it. Whether to allow Google-Agent is still a policy decision. It's a user-triggered fetcher, and reporting says it doesn't follow robots.txt the way crawlers do.

Should you bother yet?

If you're behind Cloudflare or AWS bot management, the edge already does this, and you'll mostly see the result as a "verified bot" flag. Doing it yourself makes sense when:

  • you run your own reverse proxy or origin-level bot rules,
  • you want logs that tell verified Google-Agent apart from claims-to-be Google-Agent, or
  • you build agents yourself and want a reference verifier to test against (next post).

The draft is moving: draft-ietf-webbotauth-httpsig-protocol had revisions in September and October 2026. Before you rely on this code, compare it against the current draft and Cloudflare's reference implementations, which Google's page links to on GitHub.

Quick checklist

  • [ ] Allowlist signer origins, starting with https://agent.bot.goog
  • [ ] Cache the key directory per Cache-Control, and drop keys that disappear from it
  • [ ] Require @authority, created, expires and tag="web-bot-auth"
  • [ ] Log verified vs unverified for a few weeks before blocking anything
  • [ ] Keep IP verification as the fallback for unsigned requests
πŸ“° Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.