About


/*
 BREADCRUMB — ANGEL LEWIS TESTER
 Version 1.3.1
 Stage 9.6.4

 Cloudflare Worker:
 breadcrumb-angel-tester

 Required bindings:
 ANGEL_FILES       R2
 ANGEL_TEST_TOKEN  Secret
 CF_ACCOUNT_ID     Text or Secret
 CF_BROWSER_TOKEN  Secret

 Features:
 - Desktop and mobile browser testing
 - Browser Run rate-limit handling
 - HTML structural checks
 - Accessibility tree collection
 - Horizontal overflow diagnostics
 - Broken image diagnostics
 - Unlabelled control diagnostics
 - Screenshot storage in R2
 - Protected testing reports

 No automatic repair or publishing.
*/

const VERSION = "1.3.1";

const PREVIEW_HOST =
  "breadcrumb-angel-preview.lewistafadzwat.workers.dev";

const DEVICES = {
  desktop: {
    width: 1440,
    height: 900
  },
  mobile: {
    width: 390,
    height: 844
  }
};

const FILES = [
  "index.html",
  "style.css",
  "app.js"
];

const SPACING_MS = 11000;

const HEADERS = {
  "Cache-Control": "no-store",
  "X-Content-Type-Options": "nosniff",
  "Referrer-Policy": "no-referrer"
};

function json(data, status = 200) {
  return new Response(
    JSON.stringify(data, null, 2),
    {
      status,
      headers: {
        ...HEADERS,
        "Content-Type": "application/json"
      }
    }
  );
}

const sleep = ms =>
  new Promise(resolve => setTimeout(resolve, ms));

class BrowserError extends Error {
  constructor(message, limited = false, daily = false) {
    super(message);
    this.name = "BrowserError";
    this.limited = limited;
    this.daily = daily;
  }
}

// =====================================
// PRIVATE TOKEN AUTHENTICATION
// =====================================

function authorized(request, env) {
  const expected = env.ANGEL_TEST_TOKEN;

  const header =
    request.headers.get("Authorization") || "";

  if (
    typeof expected !== "string" ||
    expected.length < 24 ||
    !header.startsWith("Bearer ")
  ) {
    return false;
  }

  const supplied = header.slice(7);

  if (supplied.length !== expected.length) {
    return false;
  }

  let mismatch = 0;

  for (let i = 0; i < expected.length; i++) {
    mismatch |=
      expected.charCodeAt(i) ^
      supplied.charCodeAt(i);
  }

  return mismatch === 0;
}

// =====================================
// VALIDATE PREVIEW URL
// =====================================

function parsePreview(value) {
  if (typeof value !== "string") return null;

  try {
    const url = new URL(value);

    if (
      url.protocol !== "https:" ||
      url.hostname !== PREVIEW_HOST ||
      url.port ||
      url.username ||
      url.password ||
      url.search ||
      url.hash
    ) {
      return null;
    }

    const match =
      /^\/p\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\/index\.html$/
        .exec(url.pathname);

    if (!match) return null;

    return {
      id: match[1],
      url: url.href
    };

  } catch {
    return null;
  }
}

// =====================================
// VERIFY PREVIEW FILES IN R2
// =====================================

async function verifyPreview(env, id) {
  const prefix =
    "angel-previews/" + id + "/";

  const manifestFile = await env.ANGEL_FILES.get(
    prefix + "manifest.json"
  );

  if (!manifestFile) {
    throw Error(
      "Preview not found. Create a fresh preview."
    );
  }

  const manifest = await manifestFile.json();

  if (manifest.id && manifest.id !== id) {
    throw Error("Preview manifest ID mismatch.");
  }

  if (manifest.expiresAt == null) {
    throw Error("Preview expiry is missing.");
  }

  const raw = manifest.expiresAt;

  const expiry =
    typeof raw === "number"
      ? raw < 1e11 ? raw * 1000 : raw
      : Date.parse(raw);

  if (
    !Number.isFinite(expiry) ||
    Date.now() >= expiry
  ) {
    throw Error(
      "Preview expired. Create a fresh preview."
    );
  }

  const files = [];

  for (const name of FILES) {
    const file = await env.ANGEL_FILES.head(
      prefix + name
    );

    if (!file || file.size === 0) {
      throw Error(
        "Missing or empty preview file: " + name
      );
    }

    files.push({
      name,
      bytes: file.size,
      status: "present"
    });
  }

  return files;
}

// =====================================
// BROWSER-ONLY DIAGNOSTIC SCRIPT
//
// This is deliberately a string.
// It runs inside the webpage, not inside
// the Cloudflare Worker.
//
// Fixes all 10 editor type-check errors.
// =====================================

const AUDIT_SCRIPT = String.raw`
(function () {
  try {
    var root = document.documentElement;
    var pageWidth = window.innerWidth;

    var bodyWidth = document.body
      ? document.body.scrollWidth
      : 0;

    var documentWidth = Math.max(
      root.scrollWidth,
      bodyWidth
    );

    var overflowPx = Math.max(
      0,
      documentWidth - pageWidth
    );

    var escaped = [];

    var elements = document.querySelectorAll(
      "body *"
    );

    for (var i = 0; i < elements.length; i++) {
      if (escaped.length >= 10) break;

      var el = elements[i];

      if (
        el.tagName === "SCRIPT" ||
        el.tagName === "STYLE" ||
        el.tagName === "SVG"
      ) {
        continue;
      }

      var style = window.getComputedStyle(el);

      if (
        style.display === "none" ||
        style.visibility === "hidden" ||
        style.position === "fixed" ||
        style.position === "absolute"
      ) {
        continue;
      }

      var rect = el.getBoundingClientRect();

      if (
        rect.width > 0 &&
        rect.height > 0 &&
        (
          rect.left < -8 ||
          rect.right > pageWidth + 8
        )
      ) {
        escaped.push({
          element: el.tagName.toLowerCase(),
          id: String(el.id || "").slice(0, 60),
          left: Math.round(rect.left),
          right: Math.round(rect.right)
        });
      }
    }

    var brokenImages = [];

    var images = document.images;

    for (var j = 0; j < images.length; j++) {
      var img = images[j];

      if (
        img.getAttribute("src") &&
        img.complete &&
        img.naturalWidth === 0
      ) {
        brokenImages.push(
          String(img.getAttribute("src")).slice(
            0, 160
          )
        );
      }

      if (brokenImages.length >= 10) break;
    }

    var unlabelledControls = [];

    var controls = document.querySelectorAll(
      "button,input,select,textarea,[role='button']"
    );

    for (var k = 0; k < controls.length; k++) {
      var control = controls[k];

      if (
        control.matches("input[type='hidden']")
      ) {
        continue;
      }

      var cs = window.getComputedStyle(control);

      if (
        cs.display === "none" ||
        cs.visibility === "hidden"
      ) {
        continue;
      }

      var label =
        control.getAttribute("aria-label") ||
        control.getAttribute("title") ||
        control.innerText ||
        control.value ||
        "";

      var labelledBy =
        control.getAttribute("aria-labelledby");

      if (
        !String(label).trim() &&
        !labelledBy
      ) {
        unlabelledControls.push({
          element: control.tagName.toLowerCase(),
          id: String(control.id || "").slice(0, 60)
        });
      }

      if (unlabelledControls.length >= 10) {
        break;
      }
    }

    var result = {
      viewportWidth: pageWidth,
      documentWidth: documentWidth,
      horizontalOverflowPx: overflowPx,
      overflowElements: escaped,
      brokenImages: brokenImages,
      unlabelledControls: unlabelledControls,
      buttonCount:
        document.querySelectorAll("button").length
    };

    root.setAttribute(
      "data-angel-audit",
      encodeURIComponent(JSON.stringify(result))
    );

  } catch (error) {
    document.documentElement.setAttribute(
      "data-angel-audit-error",
      String(error).slice(0, 180)
    );
  }
})();
`;

// =====================================
// EXTRACT DIAGNOSTICS FROM HTML
// =====================================

function extractAudit(html) {
  const match =
    /<html\b[^>]*\bdata-angel-audit="([^"]+)"/i
      .exec(html || "");

  if (!match) return null;

  try {
    return JSON.parse(
      decodeURIComponent(
        match[1].replace(/&amp;/g, "&")
      )
    );
  } catch {
    return null;
  }
}

function extractAuditError(html) {
  const match =
    /<html\b[^>]*\bdata-angel-audit-error="([^"]+)"/i
      .exec(html || "");

  return match
    ? match[1].slice(0, 180)
    : null;
}

// =====================================
// STRUCTURAL CHECKS
// =====================================

function htmlChecks(html) {
  const checks = [
    {
      name: "HTML document",
      passed: /<html\b/i.test(html),
      critical: true
    },
    {
      name: "Body element",
      passed: /<body\b/i.test(html),
      critical: true
    },
    {
      name: "Page title",
      passed:
        /<title\b[^>]*>\s*[^<\s]/i.test(html)
    },
    {
      name: "Main heading",
      passed: /<h1\b/i.test(html)
    },
    {
      name: "Viewport metadata",
      passed:
        /<meta[^>]+name=["']viewport["']/i
          .test(html)
    },
    {
      name: "Page content",
      passed: html.length > 300
    }
  ];

  return checks.map(check => ({
    name: check.name,

    status: check.passed
      ? "pass"
      : check.critical
        ? "fail"
        : "warning"
  }));
}

// =====================================
// ADVANCED CHECKS
// =====================================

function advancedChecks(audit, tree, error) {
  const checks = [];

  if (audit) {
    const overflow = Number(
      audit.horizontalOverflowPx || 0
    );

    checks.push({
      name: "Horizontal overflow",
      status: overflow > 4 ? "fail" : "pass",
      detail: overflow + "px"
    });

    const escaped =
      audit.overflowElements || [];

    checks.push({
      name: "Elements outside viewport",
      status: escaped.length
        ? "warning"
        : "pass",
      items: escaped
    });

    const broken =
      audit.brokenImages || [];

    checks.push({
      name: "Broken loaded images",
      status: broken.length ? "fail" : "pass",
      items: broken
    });

    const unlabelled =
      audit.unlabelledControls || [];

    checks.push({
      name: "Unlabelled controls",
      status: unlabelled.length
        ? "warning"
        : "pass",
      items: unlabelled
    });

  } else {
    checks.push({
      name: "DOM diagnostics",
      status: "not_run",
      detail: error ||
        "The injected audit was unavailable. The preview CSP may block injected scripts."
    });
  }

  checks.push({
    name: "Accessibility tree",
    status: tree ? "pass" : "not_run"
  });

  return checks;
}

// =====================================
// CLOUDFLARE BROWSER RUN
// =====================================

function browserEndpoint(env) {
  if (
    !/^[a-f0-9]{32}$/i.test(
      env.CF_ACCOUNT_ID || ""
    )
  ) {
    throw Error(
      "Missing or invalid CF_ACCOUNT_ID."
    );
  }

  if (!env.CF_BROWSER_TOKEN) {
    throw Error("Missing CF_BROWSER_TOKEN.");
  }

  return (
    "https://api.cloudflare.com/client/v4/accounts/" +
    env.CF_ACCOUNT_ID +
    "/browser-run/snapshot?cacheTTL=0"
  );
}

function browserError(response, data) {
  const messages = Array.isArray(data.errors)
    ? data.errors
        .map(item => item.message)
        .filter(Boolean)
        .join("; ")
    : "";

  const message =
    messages ||
    data.error?.message ||
    data.message ||
    "HTTP " + response.status;

  const limited =
    response.status === 429 ||
    /rate limit|too many requests|time limit exceeded/i
      .test(message);

  const daily =
    /daily|for today|time limit exceeded/i
      .test(message);

  return new BrowserError(
    "Browser Run failed: " + message,
    limited,
    daily
  );
}

function retryDelay(response) {
  const value =
    response.headers.get("Retry-After");

  if (!value) return SPACING_MS;

  const seconds = Number(value);

  if (Number.isFinite(seconds)) {
    return Math.max(
      SPACING_MS,
      Math.min(30000, seconds * 1000)
    );
  }

  const date = Date.parse(value);

  if (Number.isFinite(date)) {
    return Math.max(
      SPACING_MS,
      Math.min(30000, date - Date.now())
    );
  }

  return SPACING_MS;
}

async function capture(env, previewUrl, device) {
  const payload = {
    url: previewUrl,

    formats: [
      "content",
      "screenshot",
      "accessibilityTree"
    ],

    viewport: {
      width: device.width,
      height: device.height,
      deviceScaleFactor: 1,
      isMobile: device.width < 500,
      hasTouch: device.width < 500
    },

    screenshotOptions: {
      type: "png",
      fullPage: false
    },

    gotoOptions: {
      waitUntil: "networkidle2",
      timeout: 30000
    },

    addScriptTag: [
      { content: AUDIT_SCRIPT }
    ]
  };

  for (let attempt = 0; attempt < 2; attempt++) {
    const response = await fetch(
      browserEndpoint(env),
      {
        method: "POST",
        headers: {
          Authorization:
            "Bearer " + env.CF_BROWSER_TOKEN,
          "Content-Type": "application/json"
        },
        body: JSON.stringify(payload)
      }
    );

    const data = await response.json()
      .catch(() => ({}));

    if (
      response.ok &&
      data.success !== false &&
      data.result
    ) {
      if (!data.result.screenshot) {
        throw Error(
          "Browser returned no screenshot."
        );
      }

      return data.result;
    }

    const error = browserError(response, data);

    if (
      error.limited &&
      !error.daily &&
      attempt === 0
    ) {
      await sleep(retryDelay(response));
      continue;
    }

    throw error;
  }

  throw Error("Browser attempts exhausted.");
}

// =====================================
// DECODE SCREENSHOT
// =====================================

function decodeImage(value) {
  if (typeof value !== "string") {
    throw Error("Invalid screenshot data.");
  }

  const raw = value.replace(
    /^data:image\/(?:png|jpeg|webp);base64,/,
    ""
  );

  const binary = atob(raw);

  if (binary.length > 8000000) {
    throw Error("Screenshot exceeds 8 MB.");
  }

  const bytes = new Uint8Array(
    binary.length
  );

  for (let i = 0; i < binary.length; i++) {
    bytes[i] = binary.charCodeAt(i);
  }

  return bytes;
}

// =====================================
// SUMMARIZE TEST RESULTS
// =====================================

function makeSummary(devices, requested) {
  const checks = devices.flatMap(
    device => device.checks || []
  );

  const count = status =>
    checks.filter(
      item => item.status === status
    ).length;

  const passed = count("pass");
  const failed = count("fail");
  const warnings = count("warning");
  const notRun = count("not_run");

  const completedDevices = devices.filter(
    item => item.status === "captured"
  ).length;

  const incomplete =
    completedDevices < requested;

  const result = incomplete
    ? "incomplete"
    : failed
      ? "failed"
      : warnings
        ? "needs_review"
        : notRun
          ? "partial_checks_only"
          : "checks_passed";

  return {
    passed,
    failed,
    warnings,
    notRun,
    requestedDevices: requested,
    completedDevices,
    result
  };
}

// =====================================
// RUN AUTOMATED TESTS
// =====================================

async function runTests(request, env) {
  let input;

  try {
    input = await request.json();
  } catch {
    return json({
      status: "error",
      message: "Invalid JSON body."
    }, 400);
  }

  const preview =
    parsePreview(input?.previewUrl);

  if (!preview) {
    return json({
      status: "error",
      message: "Invalid preview URL."
    }, 400);
  }

  const mode = input.device || "both";

  if (
    !["desktop", "mobile", "both"]
      .includes(mode)
  ) {
    return json({
      status: "error",
      message:
        "device must be desktop, mobile or both."
    }, 400);
  }

  const sourceFiles = await verifyPreview(
    env,
    preview.id
  );

  const selected = mode === "both"
    ? ["desktop", "mobile"]
    : [mode];

  const reportId = crypto.randomUUID();

  const devices = [];

  let lastRequest = 0;

  for (const name of selected) {
    if (lastRequest) {
      const remaining =
        SPACING_MS -
        (Date.now() - lastRequest);

      if (remaining > 0) {
        await sleep(remaining);
      }
    }

    lastRequest = Date.now();

    try {
      const result = await capture(
        env,
        preview.url,
        DEVICES[name]
      );

      const imageKey =
        "angel-tests/" +
        reportId +
        "/" +
        name +
        ".png";

      await env.ANGEL_FILES.put(
        imageKey,
        decodeImage(result.screenshot),
        {
          httpMetadata: {
            contentType: "image/png"
          }
        }
      );

      const html =
        typeof result.content === "string"
          ? result.content
          : "";

      const audit = extractAudit(html);

      const auditError =
        extractAuditError(html);

      const tree = result.accessibilityTree;

      devices.push({
        name,
        status: "captured",

        viewport: DEVICES[name],

        screenshotSaved: true,

        screenshotEndpoint:
          "/image?id=" +
          reportId +
          "&device=" +
          name,

        audit,

        checks: [
          ...htmlChecks(html),
          ...advancedChecks(
            audit,
            tree,
            auditError
          )
        ]
      });

    } catch (caught) {
      const message =
        caught instanceof Error
          ? caught.message
          : String(caught);

      const limited =
        caught instanceof BrowserError
          ? caught.limited
          : false;

      devices.push({
        name,
        status: "error",
        rateLimited: limited,
        message: message.slice(0, 300),
        checks: []
      });

      if (limited) break;
    }
  }

  const summary = makeSummary(
    devices,
    selected.length
  );

  const report = {
    status:
      summary.result === "incomplete"
        ? "partial"
        : "success",

    service: "Angel Lewis Tester",

    version: VERSION,

    reportId,

    previewId: preview.id,

    testedAt:
      new Date().toISOString(),

    requestedDevice: mode,

    summary,

    sourceFiles,

    devices,

    limitations: [
      "HTML checks are not a full functional test.",
      "Injected diagnostics may be blocked by CSP.",
      "Screenshots are not visually AI-graded.",
      "Buttons and forms are not clicked.",
      "JavaScript console history is not captured.",
      "No automatic code repair or publishing."
    ]
  };

  await env.ANGEL_FILES.put(
    "angel-tests/" +
    reportId +
    "/report.json",

    JSON.stringify(report, null, 2),

    {
      httpMetadata: {
        contentType: "application/json"
      }
    }
  );

  return json(
    report,
    summary.result === "incomplete"
      ? 207
      : 200
  );
}

// =====================================
// ACCESS SAVED REPORTS AND SCREENSHOTS
// =====================================

function validId(value) {
  return (
    typeof value === "string" &&
    /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/
      .test(value)
  );
}

async function readSaved(url, env, type) {
  const id =
    url.searchParams.get("id");

  const device =
    url.searchParams.get("device");

  if (
    !validId(id) ||
    (
      type === "image" &&
      !["desktop", "mobile"].includes(device)
    )
  ) {
    return json({
      error: "Invalid request."
    }, 400);
  }

  const key = type === "image"
    ? "angel-tests/" +
      id + "/" + device + ".png"
    : "angel-tests/" +
      id + "/report.json";

  const object =
    await env.ANGEL_FILES.get(key);

  if (!object) {
    return json({
      error: "Not found."
    }, 404);
  }

  return new Response(
    object.body,
    {
      headers: {
        ...HEADERS,
        "Content-Type":
          type === "image"
            ? "image/png"
            : "application/json"
      }
    }
  );
}

// =====================================
// MAIN WORKER
// =====================================

export default {
  async fetch(request, env) {
    const url = new URL(request.url);

    if (
      request.method === "GET" &&
      url.pathname === "/status"
    ) {
      return json({
        status: "online",
        service: "Angel Lewis Tester",
        version: VERSION,

        storageConnected:
          !!env.ANGEL_FILES,

        browserConfigured:
          !!(
            env.CF_ACCOUNT_ID &&
            env.CF_BROWSER_TOKEN
          ),

        securityConfigured:
          !!env.ANGEL_TEST_TOKEN,

        desktopTesting: true,
        mobileTesting: true,
        accessibilityTesting: true,
        domDiagnostics: true,
        rateLimitHandling: true,
        automaticPublishing: false
      });
    }

    if (!authorized(request, env)) {
      return json({
        status: "error",
        message: "Unauthorized."
      }, 401);
    }

    if (!env.ANGEL_FILES) {
      return json({
        status: "error",
        message: "ANGEL_FILES binding missing."
      }, 503);
    }

    try {
      if (
        request.method === "POST" &&
        url.pathname === "/run"
      ) {
        return await runTests(
          request,
          env
        );
      }

      if (
        request.method === "GET" &&
        url.pathname === "/report"
      ) {
        return await readSaved(
          url,
          env,
          "report"
        );
      }

      if (
        request.method === "GET" &&
        url.pathname === "/image"
      ) {
        return await readSaved(
          url,
          env,
          "image"
        );
      }

      return json({
        status: "error",
        message: "Endpoint not found."
      }, 404);

    } catch (caught) {
      const message =
        caught instanceof Error
          ? caught.message
          : String(caught);

      console.error(
        "Angel Lewis Tester:",
        message
      );

      return json({
        status: "error",
        service: "Angel Lewis Tester",
        version: VERSION,
        message: message.slice(0, 350)
      }, 500);
    }
  }
};