Public Beta
Not set

Experience

Changes how pages explain things, never what you can do.

More

Experience

Changes how pages explain things, never what you can do.

Sign inGet started

SEO Audit v0.2.2 · generic

Archive SHA-256 109f4761de0a26b245d7d86d6ae9babc99632b143ee421ef5617c75c818fd6aa · 44.1 KB · built Nov 27, 2026

src/index.js

// SEO Audit — AgentRove native agent (MIT). Audits HTML you supply; the optional fetch tool only reaches
// https URLs on hosts you list in `owned_hosts`, enforced through the SDK network allowlist (extraHosts).
import { defineAgent, AgentError, runCli, runMcpStdio, handleMcpMessage, validateManifest } from "../sdk/index.js";
import { readFileSync } from "node:fs";
import { auditPages } from "./audit.js";
import { checkOwnedHosts, nonPublicHosts, pinnedFetch } from "./hosts.js";

const manifest = JSON.parse(readFileSync(new URL("../agent.json", import.meta.url), "utf8"));
const HOST_RE = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)+$/;
const MAX_REDIRECTS = 5;
const USER_AGENT = "AgentRove-SEO-Audit/0.2 (owner-requested on-page audit)";

function ownedSet(input) {
  return new Set(input.owned_hosts.map((h) => h.toLowerCase()));
}

// Validates a URL against the owner's host list: https only, exact host match, no embedded credentials.
function checkOwned(rawUrl, owned) {
  let u;
  try { u = new URL(rawUrl); } catch { return { ok: false, reason: `Not a valid URL: ${rawUrl}` }; }
  if (u.protocol !== "https:") return { ok: false, reason: `Only https URLs are fetched: ${rawUrl}` };
  if (u.username || u.password) return { ok: false, reason: `URLs with embedded credentials are not fetched: ${u.hostname}` };
  if (!owned.has(u.hostname.toLowerCase())) return { ok: false, reason: `Host ${u.hostname} is not in owned_hosts` };
  return { ok: true, url: u };
}

async function readCapped(res, maxBytes) {
  const reader = res.body?.getReader?.();
  if (!reader) {
    const t = await res.text();
    return { bytes: Buffer.from(t), truncated: false };
  }
  const chunks = [];
  let total = 0;
  let truncated = false;
  for (;;) {
    const { done, value } = await reader.read();
    if (done) break;
    total += value.byteLength;
    if (total > maxBytes) {
      chunks.push(value.subarray(0, value.byteLength - (total - maxBytes)));
      truncated = true;
      await reader.cancel().catch(() => {});
      break;
    }
    chunks.push(value);
  }
  return { bytes: Buffer.concat(chunks.map((c) => Buffer.from(c))), truncated };
}

function decodeBody(bytes, contentType) {
  const cs = /charset=["']?([\w.:-]+)/i.exec(contentType ?? "")?.[1] ?? "utf-8";
  try { return new TextDecoder(cs).decode(bytes); } catch { return new TextDecoder("utf-8").decode(bytes); }
}

async function fetchOne(url, owned, ctx, maxBytes) {
  const rec = { url, redirects: [] };
  let current = url;
  for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
    let res;
    try {
      // ctx.fetch enforces the SDK allowlist (manifest network + extraHosts = owned_hosts) on every hop;
      // redirects are followed manually so each Location is re-checked before it is requested.
      res = await ctx.fetch(current, { method: "GET", redirect: "manual", headers: { "user-agent": USER_AGENT, accept: "text/html,application/xhtml+xml" } });
    } catch (e) {
      rec.error = e?.code === "network_denied" ? e.message : `Request failed: ${e?.name === "TimeoutError" ? "timed out" : e?.message ?? String(e)}`;
      return rec;
    }
    rec.status = res.status;
    if ([301, 302, 303, 307, 308].includes(res.status)) {
      const loc = res.headers.get("location");
      if (!loc) { rec.error = `HTTP ${res.status} without a Location header`; return rec; }
      let next;
      try { next = new URL(loc, current).href; } catch { rec.error = `Invalid redirect Location: ${loc.slice(0, 200)}`; return rec; }
      const chk = checkOwned(next, owned);
      if (!chk.ok) { rec.redirects.push(next); rec.error = `Redirect blocked: ${chk.reason}`; return rec; }
      rec.redirects.push(next);
      current = next;
      await res.body?.cancel?.().catch(() => {});
      continue;
    }
    rec.final_url = current;
    const ct = res.headers.get("content-type") ?? "";
    rec.content_type = ct;
    if (res.status < 200 || res.status > 299) { rec.error = `HTTP ${res.status}`; await res.body?.cancel?.().catch(() => {}); return rec; }
    if (!/html/i.test(ct)) { rec.error = `Not an HTML page (content-type: ${ct || "none"})`; await res.body?.cancel?.().catch(() => {}); return rec; }
    const { bytes, truncated } = await readCapped(res, maxBytes);
    rec.bytes = bytes.byteLength;
    if (truncated) rec.truncated = true;
    const xrt = res.headers.get("x-robots-tag");
    return { rec, html: decodeBody(bytes, ct), xRobotsTag: xrt };
  }
  rec.error = `More than ${MAX_REDIRECTS} redirects`;
  return rec;
}

const handlers = {
  async audit_html(input) {
    if (input.pages && input.html !== undefined) throw new AgentError("invalid_input", "Provide either pages or html, not both");
    if (!input.pages && input.html === undefined) throw new AgentError("invalid_input", "Provide pages (array of {url_or_path, html}) or html");
    const pages = input.pages ?? [{ url_or_path: input.url_or_path ?? "page", html: input.html }];
    const seen = new Set();
    for (const p of pages) {
      if (seen.has(p.url_or_path)) throw new AgentError("invalid_input", `Duplicate url_or_path: ${p.url_or_path}`);
      seen.add(p.url_or_path);
    }
    return auditPages(pages.map((p) => ({ url_or_path: p.url_or_path, html: p.html })), { thresholds: input.thresholds, siteHost: input.site_host?.toLowerCase() });
  },

  async fetch_pages(input, ctx) {
    const owned = ownedSet(input);
    // Refuse the whole request before any network traffic if a URL is outside the owner's hosts.
    const denied = input.urls.map((u) => checkOwned(u, owned)).filter((c) => !c.ok);
    if (denied.length) throw new AgentError("network_denied", `Refusing to fetch: ${denied.map((d) => d.reason).join("; ")}`);
    const maxBytes = input.max_bytes ?? 2000000;
    const fetched = [];
    const pages = [];
    for (const url of [...new Set(input.urls)]) {
      const r = await fetchOne(url, owned, ctx, maxBytes);
      if (r.rec) {
        fetched.push(r.rec);
        pages.push({ url_or_path: r.rec.final_url, html: r.html, ...(r.xRobotsTag ? { x_robots_tag: r.xRobotsTag } : {}) });
      } else fetched.push(r);
    }
    const out = { fetched };
    if (input.audit !== false) {
      // De-duplicate pages that redirected to the same final URL.
      const unique = [...new Map(pages.map((p) => [p.url_or_path, p])).values()];
      out.report = auditPages(unique, { thresholds: input.thresholds });
    } else {
      out.html = pages.map((p) => ({ url_or_path: p.url_or_path, html: p.html }));
    }
    return out;
  },
};

const agent = defineAgent(manifest, handlers);

// The SDK builds the network-guarded context before a handler runs, so the per-call owned_hosts must be
// passed in as ctx.extraHosts here. Only syntactically valid exact hostnames are added; anything else is
// left for input validation to reject. The handler re-checks every URL and redirect against owned_hosts.
// SSRF guard: IP literals and local/intranet names are refused, and on the real network (no injected
// fetch, or an injected resolver) every host must resolve only to public addresses before any request.
const baseCall = agent.call;
agent.call = async function call(name, input, ctxOverrides = {}) {
  if (name !== "fetch_pages") return baseCall.call(this, name, input, ctxOverrides);
  // On the real network (no injected fetch) requests go through pinnedFetch: the SDK still checks the
  // allowlist on every hop, and each TCP connection goes only to an address resolved and checked at
  // connect time, which closes the DNS-rebinding window after the pre-check below.
  const realNetwork = !ctxOverrides.fetch;
  const rest = { ...ctxOverrides };
  delete rest.lookup; // the resolver override is for the DNS checks only
  if (realNetwork) rest.fetch = pinnedFetch({ resolver: ctxOverrides.lookup });
  if (Array.isArray(input?.owned_hosts) && input.owned_hosts.every((h) => typeof h === "string" && HOST_RE.test(h))) {
    const hosts = checkOwnedHosts(input.owned_hosts);
    // URLs outside owned_hosts are refused by the handler without any network use, so resolve only when all are owned.
    const allOwned = Array.isArray(input.urls) && input.urls.every((u) => typeof u === "string" && checkOwned(u, new Set(hosts)).ok);
    if (allOwned && (ctxOverrides.lookup || realNetwork)) {
      const rejected = await nonPublicHosts(hosts, ctxOverrides.lookup);
      if (rejected.length) throw new AgentError("network_denied", `Refusing to fetch: ${rejected.join(", ")} did not resolve, or resolves to a private, loopback or link-local address.`);
    }
    rest.extraHosts = [...(rest.extraHosts ?? []), ...hosts];
  }
  return baseCall.call(this, name, input, rest);
};

export default agent;
export { manifest, runCli, runMcpStdio, handleMcpMessage, validateManifest };

Find an agent

Do not include passwords, keys, customer data or other confidential details.
Rule-based matching is free during the public beta (fair use).