Trust center  /  Install script

Read the install script before you install it

This is the complete source of the current SafeScript install script, exactly as our server sends it to browsers. It is plain, commented code. The fingerprint below is what your install line carries, so you can check that the file you read here is the file your visitors run.

Pinned release

Current version 0f75c9ce72bd

Released 2026-11-27Size 74,029 bytesLines 1,270

File address

https://safescript.app/g/v/0f75c9ce72bd/guard.js

Integrity (SHA-384)

sha384-D3XJznK9AXScAMWrgUm1yk1zBEPLvZWQVeCO1LSxphmuOZx3pRjXuJ9zBQk7ak3z

The install line it belongs to

Your dashboard gives you this line with your own site key in place of YOUR_SITE_KEY:

<script src="https://safescript.app/g/v/0f75c9ce72bd/guard.js" integrity="sha384-D3XJznK9AXScAMWrgUm1yk1zBEPLvZWQVeCO1LSxphmuOZx3pRjXuJ9zBQk7ak3z" crossorigin="anonymous" data-key="YOUR_SITE_KEY"></script>

The browser downloads the file, computes its SHA-384 fingerprint and runs it only if the result equals the integrity value. A released file is never changed or removed, so this line keeps loading the same bytes until you replace it.

Verify

Verify it yourself

Download the file and compute its fingerprint. On macOS, Linux or Windows with Git Bash, run:

curl -s https://safescript.app/g/v/0f75c9ce72bd/guard.js | openssl dgst -sha384 -binary | openssl base64 -A

The output should be the integrity value above without its sha384- prefix. Our server also checks this before it serves a file: a released file whose bytes do not match its version name is never sent.

Or let your browser do it now: it downloads the file and computes the fingerprint on your device.

Every released version is also listed as data at /g/v/versions.json.

Source

Full source

Read-only. Byte for byte the released file, shown as text.

// SafeScript guard. Runs first in <head> on a customer's site, in every visitor's browser.
// It stops scripts, frames and data requests to addresses the site owner has not approved,
// reports what it saw to SafeScript, and turns the footer link into a live badge.
// Two ways to install it, same code:
//   classic: /g/KEY.js, where worker/guard.js puts the site's settings in self.__SAFESCRIPT__ in front of this file;
//   pinned:  /g/v/VERSION/guard.js with integrity and data-key="KEY". This file is then identical for every
//            site, and the settings are read as data from /g/KEY.json (below).
// Rule: nothing in here may throw into the site's own code. Every patch keeps the original path.
(function () {
  "use strict";
  if (window.__safescriptGuard) return;
  var me = document.currentScript, pinnedKey = me && me.getAttribute ? me.getAttribute("data-key") : null;
  var C = pinnedKey != null ? pinnedSettings(me, pinnedKey) : self.__SAFESCRIPT__;
  if (!C) return;
  window.__safescriptGuard = 1;
  // A protection test token in the address fragment (see "protection test" below), read and taken out of the
  // address before the site's own code runs.
  var TEST_TOKEN = testToken(), TEST = null;

  // Pinned install: the settings come from the address this file was loaded from, read before anything
  // else on the page runs (a synchronous request, so the page waits exactly as it waits for this file).
  // They are parsed with JSON.parse and never run. Settings that do not load, do not parse or name another
  // key mean the guard does nothing, as when the classic file fails to load. Reports and the badge use
  // this file's own address, never one named in the settings.
  function pinnedSettings(script, key) {
    try {
      if (!/^[a-z0-9]{8,40}$/i.test(key)) return null;
      var u = new URL(script.src);
      if (u.protocol !== "https:" && u.protocol !== "http:") return null;
      var x = new XMLHttpRequest();
      x.open("GET", u.origin + "/g/" + key + ".json", false);
      x.send(null);
      if (x.status !== 200) return null;
      var c = JSON.parse(x.responseText);
      if (!c || typeof c !== "object" || c.key !== key) return null;
      c.api = u.origin;
      return c;
    } catch (e) { return null; }
  }

  // Browser policy, enforce mode: the site's policy as a <meta> tag, first, so the browser applies it to
  // every later load. A <meta> policy cannot carry report-uri; violations come back through the listener below.
  if (C.cspMode === "enforce" && C.policy && C.mode !== "paused") {
    try {
      var meta = document.createElement("meta"), head = document.head || document.getElementsByTagName("head")[0];
      meta.httpEquiv = "Content-Security-Policy";
      meta.content = C.policy;
      if (head) head.insertBefore(meta, head.firstChild);
    } catch (e) {}
  }

  var W = window, D = document, N = navigator, P = W.performance;
  var MODE = C.mode, HOST = String(C.host || "").toLowerCase(), API = C.api || "https://safescript.app";
  var SELF = String((D.currentScript && D.currentScript.src) || "").split(/[?#]/)[0];
  var clock = function () { return P && P.now ? P.now() : Date.now(); };
  var later = function (fn) { setTimeout(function () { try { fn(); } catch (e) {} }, 0); };
  var log = [], queue = [], seen = {}, timer = 0;
  var origFetch = W.fetch, origBeacon = N.sendBeacon;
  var getAttr = Element.prototype.getAttribute, setAttr = Element.prototype.setAttribute;
  var ua = N.userAgent || "";
  var DEVICE = /iPhone|iPad|iPod/.test(ua) || (/Macintosh/.test(ua) && N.maxTouchPoints > 1) ? "ios"
    : /Android/.test(ua) ? "android" : /Mobi|Tablet/.test(ua) ? "other" : "desktop";

  // ---------- this tab ----------
  // A random id per browser tab (sessionStorage, never a cookie), so SafeScript can count how many visits
  // saw a page change, each once. The server stores only a hash of it.
  function store(k, v) {
    try { if (v === undefined) return W.sessionStorage.getItem(k); W.sessionStorage.setItem(k, v); } catch (e) {}
    return null;
  }
  function rand() {
    var a = new Uint8Array(12), s = "", i;
    try { W.crypto.getRandomValues(a); } catch (e) { for (i = 0; i < 12; i++) a[i] = Math.random() * 256 | 0; }
    for (i = 0; i < 12; i++) s += (a[i] + 256).toString(16).slice(1);
    return s;
  }
  var SID = store("safescript:s") || "";
  if (!/^[a-z0-9]{16,40}$/.test(SID)) { SID = rand(); store("safescript:s", SID); }
  // What this tab already sent (page structures, load chains), so a visit that opens ten pages sends
  // each fact once. Short hashes only.
  function hashStr(s) { var h = 5381; for (var i = 0; i < s.length; i++) h = ((h << 5) + h + s.charCodeAt(i)) | 0; return (h >>> 0).toString(36); }
  var SENT_KEY = "safescript:sent:" + C.key, sent = {};
  String(store(SENT_KEY) || "").split(",").forEach(function (h) { if (h) sent[h] = 1; });
  function once(id) {
    var h = hashStr(id);
    if (sent[h]) return false;
    sent[h] = 1;
    var keys = Object.keys(sent);
    store(SENT_KEY, keys.slice(-400).join(","));
    return true;
  }

  // ---------- deciding ----------
  var FREE = /^(data|blob|about|javascript|chrome-extension|moz-extension|safari-web-extension):$/;
  function parse(raw) { try { return new URL(String(raw), D.baseURI); } catch (e) { return null; } }
  function originOf(u) {
    var s = u.protocol === "ws:" ? "http:" : u.protocol === "wss:" ? "https:" : u.protocol;
    return s + "//" + u.host;
  }
  function siteHost(h) {
    h = String(h).toLowerCase();
    return h === HOST || h.slice(-HOST.length - 1) === "." + HOST;
  }
  // The page's own host always counts as the site, even on a host the record does not cover.
  function ownHost(h) { return siteHost(h) || String(h).toLowerCase() === location.hostname; }
  var apiUrl = parse(API), API_ORIGIN = apiUrl ? originOf(apiUrl) : "";
  function trusted(u) {
    if (FREE.test(u.protocol)) return true;
    var o = originOf(u);
    return ownHost(u.hostname) || o === API_ORIGIN || o === "https://safescript.app";
  }
  // An entry is an origin ("https://cdn.example") or a wildcard ("https://*.example.com").
  function listed(list, o) {
    for (var i = 0; list && i < list.length; i++) {
      var e = list[i], m = /^([a-z]+:\/\/)\*(\..+)$/.exec(e);
      if (e === o) return true;
      if (m && o.indexOf(m[1]) === 0 && ("." + o.slice(m[1].length)).slice(-m[2].length) === m[2]) return true;
    }
    return false;
  }
  // An image address that can carry data: a query, a fragment or a long path segment.
  function carriesData(u) { return !!(u.search || u.hash || /\/[^/]{48,}/.test(u.pathname)); }

  var EVENT = { script: "blocked_script", frame: "blocked_frame", connect: "blocked_request", worker: "blocked_worker" };
  // Single script files the site blocks (a public breach report, or the owner), even from an approved source.
  var FILES = {};
  (C.blockedFiles || []).forEach(function (f) { var u = parse(f); if (u) FILES[u.protocol + "//" + u.host + u.pathname] = 1; });

  // Decides one load or request. Returns null to let it go ahead, or an event that the caller
  // finishes with done() once the load has been refused (so ms covers the whole refusal).
  // soft: an image whose address carries no data is only reported, never refused.
  function gate(kind, raw, how, soft) {
    try {
      if (MODE === "paused") return null;
      var t0 = clock(), u = parse(raw);
      if (!u || trusted(u)) return null;
      // A service worker is only ever allowed from the site itself, never from an approved address.
      var o = originOf(u), list = kind === "worker" ? "script" : kind;
      var fileBlocked = list === "script" && FILES[u.protocol + "//" + u.host + u.pathname] === 1;
      if (kind !== "worker" && !fileBlocked && listed(C.approved && C.approved[list], o)) { testNote(o, "approved"); return null; }
      var ownerBlocked = fileBlocked || listed(C.blocked && C.blocked[list], o);
      if ((MODE === "block" || ownerBlocked) && !(soft && !carriesData(u))) {
        return { t: EVENT[kind], o: o, x: how + " " + u.pathname.slice(0, 120), t0: t0 };
      }
      testNote(o, "reported");
      report({ t: "new_origin", o: o, x: list });
      return null;
    } catch (e) { return null; }
  }
  function done(ev) {
    ev.ms = Math.round((clock() - ev.t0) * 1000) / 1000;
    delete ev.t0;
    testNote(ev.o, "blocked", ev.ms);
    report(ev);
  }

  // ---------- reporting ----------
  // quiet: shown in this page (SafeScript.events) but not sent, because this tab already sent it.
  function report(ev, quiet) {
    if (ev.t === "new_origin" || ev.t === "field_read" || ev.t === "csp" || ev.t === "integrity") {
      var key = ev.t + ev.o + ev.x;
      if (seen[key]) return;
      seen[key] = 1;
    }
    var pub = Object.freeze({ t: ev.t, o: ev.o || "", x: ev.x || "", ms: ev.ms == null ? null : ev.ms, at: Date.now() });
    if (log.length < 500) log.push(pub);
    // Anything about SafeScript's test address during a protection test goes back with the test's own report,
    // never the normal way, so it never counts as a real block or a new source.
    if (testOwn(ev.o)) return;
    later(function () { W.dispatchEvent(new CustomEvent("safescript:event", { detail: pub })); });
    if (quiet) return;
    for (var i = 0; i < queue.length; i++) {
      var q = queue[i];
      if (q.t === ev.t && q.o === ev.o && q.x === ev.x) { q.n = (q.n || 1) + 1; q.ms = ev.ms; return; }
    }
    queue.push({ t: ev.t, o: ev.o || "", p: location.pathname, ms: ev.ms, x: ev.x || "" });
    if (!timer) timer = setTimeout(flush, 2000);
  }
  function flush() {
    timer = 0;
    try {
      while (queue.length) {
        // Up to 40 events and about 12 KB per request (the server takes 16 KB).
        var batch = [], size = 0;
        while (queue.length && batch.length < 40) {
          var len = JSON.stringify(queue[0]).length;
          if (batch.length && size + len > 12000) break;
          batch.push(queue.shift());
          size += len + 1;
        }
        var body = JSON.stringify({ k: C.key, v: 2, d: DEVICE, s: SID, e: batch });
        var sent = false;
        try { sent = origBeacon ? origBeacon.call(N, API + "/api/collect", body) : false; } catch (e) {}
        if (!sent && origFetch) {
          origFetch.call(W, API + "/api/collect", { method: "POST", body: body, keepalive: true, mode: "no-cors", credentials: "omit",
            headers: { "content-type": "text/plain" } }).catch(function () {});
        }
      }
    } catch (e) {}
  }
  function heartbeat() {
    var k = "safescript:hb:" + C.key, t = Date.now(), last = 0;
    try { last = +W.sessionStorage.getItem(k) || 0; } catch (e) {}
    if (t - last < 600000) return;
    try { W.sessionStorage.setItem(k, String(t)); } catch (e) {}
    report({ t: "heartbeat", x: MODE });
  }

  // ---------- script load chain ----------
  // Which file put a script on the page: the script running right now (document.currentScript), else the
  // nearest script address in the call stack, else "page" (the page's own HTML or inline code).
  function bare(u) { return u.protocol + "//" + u.host + u.pathname; }
  var HERE = function () { return location.protocol + "//" + location.host + location.pathname; };
  function parentOf() {
    try {
      var cs = D.currentScript, u = cs && cs.src ? parse(cs.src) : null;
      if (u && /^https?:$/.test(u.protocol) && bare(u) !== SELF) return bare(u);
      var stack = String(new Error().stack || ""), re = /(https?:\/\/[^\s'"()@]+):\d+:\d+/g, m;
      while ((m = re.exec(stack))) {
        var b = m[1].split(/[?#]/)[0];
        if (b === SELF) continue;
        return b === HERE() ? "page" : b;
      }
    } catch (e) {}
    return "page";
  }
  var chained = {}, chains = 0;
  function chain(raw, parent) {
    try {
      var u = parse(raw);
      if (!u || !/^https?:$/.test(u.protocol)) return;
      var child = bare(u), id = child + " " + parent;
      if (child === SELF || chained[id] || chains >= 100) return;
      chained[id] = 1;
      chains++;
      report({ t: "chain", o: child.slice(0, 300), x: parent.slice(0, 300) }, !once("c " + location.pathname + " " + id));
    } catch (e) {}
  }

  // ---------- file integrity ----------
  // Pinned files: guard.js adds the fingerprint (integrity) and crossorigin="anonymous" to a script it
  // inserts or intercepts before it loads, so the browser itself refuses a changed file.
  var PINS = {};
  (C.pins || []).forEach(function (p) { var u = p && p.integrity ? parse(p.url) : null; if (u) PINS[bare(u)] = String(p.integrity); });
  function pin(el, raw) {
    try {
      var u = parse(raw), want = u && PINS[bare(u)];
      if (!want || el.__ssPinned) return;
      el.__ssPinned = 1;
      if (!getAttr.call(el, "integrity")) setAttr.call(el, "integrity", want);
      if (!el.hasAttribute("crossorigin")) setAttr.call(el, "crossorigin", "anonymous");
      // The browser gives no reason for a refusal: a changed file and a server that does not allow
      // cross-site reads (CORS) look the same here.
      el.addEventListener("error", function () {
        if (getAttr.call(el, "data-safescript") !== "blocked") report({ t: "integrity", o: originOf(u), x: bare(u).slice(0, 300) });
      });
    } catch (e) {}
  }

  // ---------- scripts and frames in the page ----------
  var JS = /^(text\/javascript|application\/javascript|module|text\/ecmascript|application\/ecmascript|text\/jscript)?$/i;
  var checked = new WeakMap();
  function refuseScript(el, ev) {
    setAttr.call(el, "type", "javascript/blocked");
    setAttr.call(el, "data-safescript", "blocked");
    done(ev);
    later(function () { el.dispatchEvent(new Event("error")); });
  }
  // Returns true when it refused the element.
  function screenEl(el, how) {
    var tag = el.tagName, src, ev;
    if (tag !== "SCRIPT" && tag !== "IFRAME" && tag !== "FRAME") return false;
    src = getAttr.call(el, "src");
    if (!src || checked.get(el) === src) return false;
    checked.set(el, src);
    if (tag === "SCRIPT") {
      if (!JS.test(String(getAttr.call(el, "type") || "").trim())) return false;
      chain(src, how === "page" ? "page" : parentOf());
      ev = gate("script", src, how);
      if (ev) { refuseScript(el, ev); return true; }
      pin(el, src);
    } else {
      ev = gate("frame", src, how);
      if (ev) {
        setAttr.call(el, "data-safescript", "blocked");
        setAttr.call(el, "src", "about:blank");
        checked.set(el, "about:blank");
        done(ev);
        return true;
      }
    }
    return false;
  }
  function screen(node, how) {
    if (!node || (node.nodeType !== 1 && node.nodeType !== 11)) return;
    if (node.nodeType === 1) screenEl(node, how);
    if (node.firstElementChild && node.querySelectorAll) {
      var list = node.querySelectorAll("script[src],iframe[src],frame[src]");
      for (var i = 0; i < list.length; i++) screenEl(list[i], how);
    }
  }
  // Scripts inserted by other scripts: checked before they are attached, so they never load.
  function wrapInsert(proto, name) {
    var orig = proto && proto[name];
    if (typeof orig !== "function") return;
    proto[name] = function () {
      for (var i = 0; i < arguments.length; i++) { try { screen(arguments[i], "insert"); } catch (e) {} }
      return orig.apply(this, arguments);
    };
  }
  // src set on a script or frame already in the page, or on any image (images load at once).
  function srcOk(el, kind, v) {
    try {
      var ev;
      if (kind === "image") ev = gate("connect", v, "image", true);
      else if (!el.isConnected) return true;
      else if (kind === "script" && !JS.test(String(getAttr.call(el, "type") || "").trim())) return true;
      else {
        if (kind === "script") chain(v, parentOf());
        ev = gate(kind, v, "src");
      }
      if (!ev) { if (kind === "script") pin(el, v); return true; }
      if (kind === "script") refuseScript(el, ev);
      else { done(ev); if (kind === "image") later(function () { el.dispatchEvent(new Event("error")); }); }
      return false;
    } catch (e) { return true; }
  }
  function wrapSrc(Ctor, kind) {
    var proto = Ctor && Ctor.prototype, d = proto && Object.getOwnPropertyDescriptor(proto, "src");
    if (!d || !d.set) return;
    Object.defineProperty(proto, "src", {
      configurable: true, enumerable: d.enumerable, get: d.get,
      set: function (v) { if (srcOk(this, kind, v)) d.set.call(this, v); },
    });
  }
  function kindOf(el) {
    return el instanceof HTMLScriptElement ? "script" : el instanceof HTMLIFrameElement ? "frame"
      : el instanceof HTMLImageElement ? "image" : "";
  }

  // ---------- reads of password and card fields ----------
  function fieldKind(el) {
    if (el.type === "password") return "password";
    var ac = String(el.autocomplete || ""), nm = String(el.name || "") + " " + String(el.id || "");
    if (/cc-(number|csc|exp)/.test(ac) || /card.?num|cc.?num|cvv|cvc|csc/i.test(nm)) return "card";
    return "";
  }
  function whoRead(kind) {
    var stack = String(new Error().stack || ""), re = /(https?:\/\/[^\s'"()@]+):\d+:\d+/g, m;
    while ((m = re.exec(stack))) {
      if (m[1].split(/[?#]/)[0] === SELF) continue;
      var u = parse(m[1]);
      if (!u || trusted(u)) return; // the nearest caller is the site itself
      report({ t: "field_read", o: originOf(u), x: kind });
      return;
    }
  }

  // ---------- page changes ----------
  // The structure of the page: forms (method, where they post), fields (type, name, autocomplete hint,
  // which form) and frames (where they come from). Never what anyone typed. Sent once when the page has
  // loaded and again (2 seconds after the last change, at most 3 more times) when forms, fields or frames
  // are added or removed.
  function formSig(f) {
    var a = getAttr.call(f, "action"), u = a ? parse(a) : null;
    var t = !u || FREE.test(u.protocol) || ownHost(u.hostname) ? "self" : originOf(u).toLowerCase();
    var m = String(getAttr.call(f, "method") || "get").toLowerCase();
    return (m === "post" || m === "dialog" ? m : "get") + "@" + t;
  }
  function word(s) { return String(s || "").replace(/[|\s]/g, "").replace(/[0-9a-f]{12,}|\d{4,}/gi, "#").slice(0, 40).toLowerCase(); }
  function shapeOf() {
    var set = {}, list, i, el, src, u, tg;
    list = D.forms;
    for (i = 0; i < list.length && i < 50; i++) set["form|" + formSig(list[i]).replace("@", "|")] = 1;
    list = D.querySelectorAll("input,select,textarea");
    for (i = 0; i < list.length && i < 400; i++) {
      el = list[i];
      tg = el.tagName === "INPUT" ? String(getAttr.call(el, "type") || "text").toLowerCase().replace(/[^a-z-]/g, "").slice(0, 20) || "text" : el.tagName.toLowerCase();
      if (/^(hidden|submit|button|reset|image)$/.test(tg)) continue;
      set["input|" + tg + "|" + word(getAttr.call(el, "name") || el.id) + "|" +
        String(getAttr.call(el, "autocomplete") || "").toLowerCase().replace(/[^a-z0-9 -]/g, "").replace(/\s+/g, " ").trim().slice(0, 40) + "|" +
        (el.form ? formSig(el.form) : "-")] = 1;
    }
    list = D.querySelectorAll("iframe,frame");
    for (i = 0; i < list.length && i < 50; i++) {
      src = getAttr.call(list[i], "src");
      u = src ? parse(src) : null;
      if (!u || u.protocol === "about:" || u.protocol === "javascript:") continue;
      set["frame|" + (u.protocol === "data:" || u.protocol === "blob:" ? u.protocol : ownHost(u.hostname) ? "self" : originOf(u).toLowerCase())] = 1;
    }
    return Object.keys(set).sort().slice(0, 60);
  }
  var shapes = 0, shapeTimer = 0, shapeReady = false, lastShape = "";
  function sendShape() {
    shapeTimer = 0;
    // A protection test adds a hidden card field to this tab's page: its layout is not the site's real layout.
    if (shapes >= 4 || TEST) return;
    var x = JSON.stringify(shapeOf());
    if (x === lastShape) return;
    lastShape = x;
    shapes++;
    report({ t: "shape", x: x }, !once("s " + location.pathname + " " + x));
  }
  function shapeSoon() {
    if (shapeReady && !shapeTimer && shapes < 4) shapeTimer = setTimeout(function () { try { sendShape(); } catch (e) {} }, 2000);
  }
  function shapeStart() {
    if (shapeReady) return;
    shapeReady = true;
    try { sendShape(); } catch (e) {}
  }
  var SHAPE_TAGS = /^(FORM|INPUT|SELECT|TEXTAREA|IFRAME|FRAME)$/;
  function touchesShape(n) {
    if (!n || n.nodeType !== 1) return false;
    if (SHAPE_TAGS.test(n.tagName)) return true;
    return !!(n.firstElementChild && n.querySelector && n.querySelector("form,input,select,textarea,iframe,frame"));
  }
  function watchShape(r) {
    if (!shapeReady || shapeTimer || shapes >= 4) return;
    if (r.type === "attributes") { if (SHAPE_TAGS.test(r.target.tagName)) shapeSoon(); return; }
    var i;
    for (i = 0; i < r.addedNodes.length; i++) if (touchesShape(r.addedNodes[i])) return shapeSoon();
    for (i = 0; i < r.removedNodes.length; i++) if (touchesShape(r.removedNodes[i])) return shapeSoon();
  }

  // ---------- browser policy reports ----------
  // Violations the browser shows to the page. A policy with report-uri or report-to sends its own reports
  // to SafeScript (/api/csp/KEY), so those are skipped here to count each one once.
  function cspListen() {
    D.addEventListener("securitypolicyviolation", function (e) {
      try {
        if (/(^|;)\s*report-(uri|to)\s/i.test(String(e.originalPolicy || ""))) return;
        var b = String(e.blockedURI || ""), u = /^(https?|wss?):/i.test(b) ? parse(b) : null;
        var o = u ? originOf(u) : (b.split(":")[0] || "inline").toLowerCase();
        var dir = String(e.effectiveDirective || e.violatedDirective || "").split(" ")[0].replace(/-(elem|attr)$/, "");
        report({ t: "csp", o: o, x: dir + " " + (e.disposition === "report" ? "report" : "enforce") });
      } catch (x) {}
    }, true);
  }

  // ---------- install ----------
  function install() {
    // Parser-inserted <script src> and <iframe src>: the observer runs before the parser
    // executes the script, so a changed type stops it. Same technique as the yett library.
    new MutationObserver(function (records) {
      for (var i = 0; i < records.length; i++) {
        var added = records[i].addedNodes;
        for (var j = 0; j < added.length; j++) {
          try {
            var n = added[j];
            if (TEST && TEST.field === n) testFieldSeen();
            if (n.nodeType === 1 && screenEl(n, "page") && n.tagName === "SCRIPT" && n.parentNode) n.parentNode.removeChild(n);
            else screen(n, "page");
          } catch (e) {}
        }
        try { watchShape(records[i]); } catch (e) {}
      }
    }).observe(D.documentElement, { childList: true, subtree: true, attributes: true, attributeFilter: ["action", "method", "type", "name", "autocomplete", "src"] });
    // Scripts already in the page before guard.js (when it is not first in <head>).
    try { for (var s = 0; s < D.scripts.length; s++) if (D.scripts[s].src) chain(D.scripts[s].src, "page"); } catch (e) {}
    if (C.cspMode === "report" || C.cspMode === "enforce") cspListen();
    W.addEventListener("load", function () { setTimeout(shapeStart, 300); });
    D.addEventListener("DOMContentLoaded", function () { setTimeout(shapeStart, 2000); });
    if (D.readyState !== "loading") setTimeout(shapeStart, D.readyState === "complete" ? 300 : 2000);
    D.addEventListener("beforescriptexecute", function (e) {
      try { if (getAttr.call(e.target, "type") === "javascript/blocked") e.preventDefault(); } catch (x) {}
    }, true);

    ["appendChild", "insertBefore", "replaceChild"].forEach(function (n) { wrapInsert(Node.prototype, n); });
    ["append", "prepend", "before", "after", "replaceWith", "replaceChildren", "insertAdjacentElement"]
      .forEach(function (n) { wrapInsert(Element.prototype, n); });
    if (W.Range) wrapInsert(Range.prototype, "insertNode");
    wrapSrc(W.HTMLScriptElement, "script");
    wrapSrc(W.HTMLIFrameElement, "frame");
    wrapSrc(W.HTMLImageElement, "image");
    Element.prototype.setAttribute = function (name) {
      try {
        if (String(name).toLowerCase() === "src") {
          var k = kindOf(this);
          if (k && !srcOk(this, k, arguments[1])) return;
        }
      } catch (e) {}
      return setAttr.apply(this, arguments);
    };

    // Outbound data.
    if (origFetch) W.fetch = function (input) {
      var ev = gate("connect", input && typeof input === "object" && "url" in input ? input.url : input, "fetch");
      if (ev) { done(ev); return Promise.reject(new TypeError("Failed to fetch")); }
      return origFetch.apply(this, arguments);
    };
    var XP = W.XMLHttpRequest && XMLHttpRequest.prototype;
    if (XP) {
      var xOpen = XP.open, xSend = XP.send, xUrl = new WeakMap();
      XP.open = function (m, u) { try { xUrl.set(this, u); } catch (e) {} return xOpen.apply(this, arguments); };
      XP.send = function () {
        var x = this, ev = xUrl.has(x) ? gate("connect", xUrl.get(x), "xhr") : null;
        if (!ev) return xSend.apply(this, arguments);
        done(ev);
        later(function () { x.dispatchEvent(new ProgressEvent("error")); x.dispatchEvent(new ProgressEvent("loadend")); });
      };
    }
    if (origBeacon && W.Navigator) Navigator.prototype.sendBeacon = function (u) {
      var ev = gate("connect", u, "beacon");
      if (ev) { done(ev); return false; }
      return origBeacon.apply(this, arguments);
    };
    ["WebSocket", "EventSource"].forEach(function (name) {
      var O = W[name];
      if (!O) return;
      var F = function (u) {
        var ev = gate("connect", u, name.toLowerCase());
        if (ev) { done(ev); throw new DOMException("SafeScript: this address is not approved for this site.", "SecurityError"); }
        return arguments.length > 1 ? new O(u, arguments[1]) : new O(u);
      };
      F.prototype = O.prototype;
      ["CONNECTING", "OPEN", "CLOSING", "CLOSED"].forEach(function (k) { if (k in O) F[k] = O[k]; });
      W[name] = F;
    });
    var FP = W.HTMLFormElement && HTMLFormElement.prototype, fSubmit = FP && FP.submit;
    if (fSubmit) FP.submit = function () {
      var ev = gate("connect", getAttr.call(this, "action") || "", "form");
      if (ev) { done(ev); return; }
      return fSubmit.apply(this, arguments);
    };
    W.addEventListener("submit", function (e) {
      var b = e.submitter, ev = gate("connect", (b && getAttr.call(b, "formaction")) || getAttr.call(e.target, "action") || "", "form");
      if (ev) { e.preventDefault(); done(ev); }
    }, true);
    var SW = W.ServiceWorkerContainer && ServiceWorkerContainer.prototype, swReg = SW && SW.register;
    if (swReg) SW.register = function (u) {
      var ev = gate("worker", u, "serviceworker");
      if (ev) { done(ev); return Promise.reject(new DOMException("SafeScript: service worker from another site.", "SecurityError")); }
      return swReg.apply(this, arguments);
    };

    // Field reads: report only, never change what the caller gets.
    var vd = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value");
    if (vd && vd.get) Object.defineProperty(HTMLInputElement.prototype, "value", {
      configurable: true, enumerable: vd.enumerable, set: vd.set,
      get: function () {
        var v = vd.get.call(this);
        try { if (v) { var k = fieldKind(this); if (k) whoRead(k); } } catch (e) {}
        return v;
      },
    });

    W.addEventListener("pagehide", flush);
    D.addEventListener("visibilitychange", function () { if (D.visibilityState === "hidden") flush(); });
    heartbeat();
  }

  // ---------- protection test ----------
  // "Test my protection" in the SafeScript dashboard opens this site with #safescript-test=TOKEN (a fragment is never
  // sent to the site's server). The token is taken out of the address at once, and nothing runs unless SafeScript's
  // API confirms it: one time, within 10 minutes, for this site. Then this tab, and only this tab, plays a harmless
  // skimmer against the guard: a script from SafeScript's test address, fake card data (the test number
  // 4242 4242 4242 4242) sent to that address with fetch, sendBeacon and an image, and a hidden card field. Each
  // attempt goes through the same page functions a real skimmer would use, so the guard decides exactly as it would
  // for one. The decisions and their timings go back marked as a test (worker/guard.js testReport), never as events.
  function testToken() {
    try {
      var m = /^#safescript-test=([0-9a-f]{64})$/.exec(location.hash || "");
      if (!m) return null;
      history.replaceState(history.state, "", location.pathname + location.search);
      return m[1];
    } catch (e) { return null; }
  }
  // Is this address SafeScript's test address, while a test runs in this tab?
  function testOwn(raw) {
    if (!TEST || !raw) return false;
    var u = parse(raw);
    return !!u && originOf(u) === TEST.origin;
  }
  // The guard's decision on the attempt running right now: blocked, reported (let through) or approved.
  function testNote(o, d, ms) {
    if (!TEST || !TEST.cur || o !== TEST.origin) return;
    TEST.cur.d = d;
    if (ms != null) TEST.cur.ms = ms;
  }
  // The page watcher saw the hidden card field: "noticed" when the page layout it records now has a card field
  // entry it didn't have before (the layout a real visit would send to SafeScript as a page change).
  function testFieldSeen() {
    var row = TEST.fieldRow;
    if (!row || row.d !== "unchecked") return;
    var ms = Math.round((clock() - TEST.fieldAt) * 1000) / 1000, now = shapeOf();
    for (var i = 0; i < now.length; i++) {
      if (/\|cc-number\|/.test(now[i]) && TEST.shapeBefore.indexOf(now[i]) < 0) { row.d = "noticed"; row.ms = ms; return; }
    }
  }
  function runTest(token) {
    if (!origFetch) return;
    origFetch.call(W, API + "/api/test/verify", { method: "POST", body: JSON.stringify({ k: C.key, t: token }), credentials: "omit",
      headers: { "content-type": "text/plain" } })
      .then(function (r) { return r.ok ? r.json() : null; })
      .then(function (v) {
        var s = v && v.ok && typeof v.script === "string" && typeof v.sink === "string" ? parse(v.script) : null, k = s && parse(v.sink);
        if (!s || !k || !/^https?:$/.test(s.protocol) || originOf(s) !== originOf(k) || ownHost(s.hostname)) return;
        TEST = { origin: originOf(s), script: s.href, sink: k.protocol + "//" + k.host + k.pathname, cur: null, out: [] };
        if (D.readyState === "loading") D.addEventListener("DOMContentLoaded", function () { try { playTest(token); } catch (e) {} });
        else playTest(token);
      })
      .catch(function () {});
  }
  function playTest(token) {
    var card = "4242424242424242";
    var data = JSON.stringify({ card: card, name: "Test Card", exp: "12/34", cvc: "123", note: "SafeScript protection test. Not a real card." });
    function attempt(a, fn) {
      var row = { a: a, d: "unchecked", ms: null };
      TEST.cur = row;
      try { fn(); } catch (e) {}
      TEST.cur = null;
      TEST.out.push(row);
      return row;
    }
    // (a) A script from an address the site never approved, inserted the way skimmers insert theirs.
    attempt("script", function () {
      var s = D.createElement("script");
      s.src = TEST.script;
      (D.head || D.documentElement).appendChild(s);
    });
    // (b) Fake card data sent out three ways.
    attempt("fetch", function () {
      var p = W.fetch(TEST.sink + "?via=fetch", { method: "POST", body: data, mode: "no-cors", credentials: "omit", keepalive: true });
      if (p && p.catch) p.catch(function () {});
    });
    attempt("beacon", function () { N.sendBeacon(TEST.sink + "?via=beacon", data); });
    attempt("image", function () { var img = new Image(); img.src = TEST.sink + "?via=image&card=" + card; });
    // (c) A hidden card field, as skimmers add to collect a second copy of the card number.
    TEST.fieldRow = attempt("field", function () {
      var f = D.createElement("input");
      f.type = "text";
      f.name = "cardnumber";
      f.autocomplete = "cc-number";
      f.tabIndex = -1;
      f.setAttribute("aria-hidden", "true");
      f.style.cssText = "position:absolute!important;left:-9999px!important;top:0!important;width:1px!important;height:1px!important;opacity:0!important";
      TEST.shapeBefore = shapeOf();
      TEST.field = f;
      TEST.fieldAt = clock();
      (D.body || D.documentElement).appendChild(f);
    });
    setTimeout(function () {
      try { if (TEST.field.parentNode) TEST.field.parentNode.removeChild(TEST.field); } catch (e) {}
      var body = JSON.stringify({ k: C.key, v: 2, test: token, m: MODE, r: TEST.out }), sent = false;
      try { sent = origBeacon ? origBeacon.call(N, API + "/api/collect", body) : false; } catch (e) {}
      if (!sent) origFetch.call(W, API + "/api/collect", { method: "POST", body: body, keepalive: true, mode: "no-cors", credentials: "omit",
        headers: { "content-type": "text/plain" } }).catch(function () {});
    }, 1000);
  }

  // ---------- badge and lightbox ----------
  // A visitor opened the badge details: one small count for the site's owner, at most once per tab every 30 minutes.
  // It carries the site key only: no page, device, tab id or anything else about the visitor.
  function badgeOpened() {
    var k = "safescript:bo:" + C.key, t = Date.now(), last = +store(k) || 0;
    if (t - last < 1800000) return;
    store(k, String(t));
    var body = JSON.stringify({ k: C.key, v: 2, e: [{ t: "badge_open" }] }), sent = false;
    try { sent = origBeacon ? origBeacon.call(N, API + "/api/collect", body) : false; } catch (e) {}
    if (!sent && origFetch) origFetch.call(W, API + "/api/collect", { method: "POST", body: body, keepalive: true, mode: "no-cors", credentials: "omit",
      headers: { "content-type": "text/plain" } }).catch(function () {});
  }
  var INK = "#11273F", SLATE = "#435B70", GREEN = "#167151", AMBER = "#975A18", MUTED = "#81A5B9", LINE = "#D9E1E7";
  var FONT = '"Source Sans 3",system-ui,-apple-system,"Segoe UI",Roboto,sans-serif';
  var RECORD = API + "/trust/" + encodeURIComponent(HOST);
  var status = null, state = "loading";

  function when(ms) {
    try { return new Intl.DateTimeFormat(undefined, { dateStyle: "long", timeStyle: "short" }).format(new Date(ms)); }
    catch (e) { return new Date(ms).toLocaleString(); }
  }
  function plural(n, one) { return n + " " + one + (n === 1 ? "" : "s"); }
  function stateFor(s) {
    if (!siteHost(location.hostname)) return "mismatch";
    if (!s) return "failed";
    return { verified: 1, learning: 1, pending: 1, unconfirmed: 1, paused: 1 }[s.status] ? s.status : "failed";
  }
  // [status colour, label, badge second part, statement]. The verified card has its own words per mode (card());
  // the other states show their statement under the status, and the time of the latest check is checkLine.
  function view(st, s) {
    var n = (s && s.scripts) || 0;
    return ({
      // Agency plan with a brand name: "Script monitoring active · {brand}" (copy doc, Agency branding).
      verified: C.brand ? [GREEN, "Script monitoring active", String(C.brand), ""]
        : [GREEN, "SafeScript Verified", n ? plural(n, "script") + " monitored" : "", ""],
      learning: [MUTED, "Monitoring setup in progress", "", "SafeScript is collecting the first observations. The site owner is reviewing which tools belong here."],
      pending: [MUTED, "Monitoring setup in progress", "", "SafeScript is installed and waiting for its first signal from a visitor's browser."],
      unconfirmed: [AMBER, "Latest check unconfirmed", "", "We can't confirm that all expected checks are current."],
      paused: [MUTED, "Monitoring paused", "", "Scheduled monitoring has stopped."],
      mismatch: [AMBER, "Domain mismatch", "", "This record belongs to " + HOST + ". We can't verify a badge on " + location.hostname + "."],
      failed: ["", "View monitoring record", "", "Current status is unavailable here. Open the hosted record for the latest available information."],
      loading: ["", "View monitoring record", "", ""],
    })[st];
  }
  // The lightbox's short meta line, only when a check has actually completed.
  function checkLine(st, s) {
    if (!s || !s.lastChecked || !{ verified: 1, learning: 1, pending: 1, unconfirmed: 1, paused: 1 }[st]) return "";
    return (st === "unconfirmed" ? "Last confirmed check · " : "Latest completed check · ") + when(s.lastChecked) + ".";
  }
  // "Just now" under a minute, then minutes, hours and days (public/scan/badge-copy.js ago()).
  function ago(ms) {
    var t = Math.max(0, Math.floor((Date.now() - ms) / 1000));
    if (t < 60) return "Just now";
    var unit = function (n, one) { return n + " " + one + (n === 1 ? "" : "s") + " ago"; };
    if (t < 3600) return unit(Math.floor(t / 60), "minute");
    if (t < 86400) return unit(Math.floor(t / 3600), "hour");
    return unit(Math.floor(t / 86400), "day");
  }
  // The verified card's words (Eugiene, 25 Nov 2026; the same strings as public/scan/badge-copy.js). Blocking claims
  // only in block mode; any other verified mode only says what monitoring does, never "protected" or "blocking".
  // Row 2 counts the outside tools (providers) of the live record; without a count it says "Every".
  function card(s) {
    var n = s.providers || 0, block = s.mode === "block";
    var tools = n > 1 ? "All " + n + " third-party tools on this site are verified and monitored 24/7."
      : n === 1 ? "The 1 third-party tool on this site is verified and monitored 24/7."
      : "Every third-party tool on this site is verified and monitored 24/7.";
    return block ? {
      pill: "Verified Protected", head: HOST + " is actively protected",
      line: "Continuous browser security is active on this site to block bad actors and keep your personal and payment details safe.",
      rows: [["Checkout and Form Shield", "Stops unapproved code from sending your card, password, or email details anywhere the store hasn't approved."],
        ["Approved Apps Only", tools],
        ["Real-Time Tamper Blocking", "Suspicious code changes or unapproved data transfers are stopped instantly."]],
      checked: "Last security check: Verified clean · ", domain: "Protected domain: " + HOST + " · Continuous monitoring active",
      foot: "Secured by SafeScript · ",
    } : {
      pill: "Verified", head: HOST + " is monitored by SafeScript",
      line: "Continuous script monitoring is active on this site, and the store is alerted to any change.",
      rows: [["Checkout and Form Shield", "Changes to checkout and sign-in forms are flagged to the store right away."],
        ["Approved Apps Only", tools],
        ["Real-Time Tamper Alerts", "Suspicious code changes or new data transfers are flagged to the store at once."]],
      checked: "Last security check · ", domain: "Monitored domain: " + HOST + " · Continuous monitoring active",
      foot: "Monitoring provided by SafeScript · ",
    };
  }
  // A green check in a circle for the card's rows, node by node like the symbol.
  function tick() {
    var NS = "http://www.w3.org/2000/svg", svg = D.createElementNS(NS, "svg");
    [["viewBox", "0 0 20 20"], ["width", "20"], ["height", "20"], ["aria-hidden", "true"], ["focusable", "false"]].forEach(function (p) { svg.setAttribute(p[0], p[1]); });
    var c = D.createElementNS(NS, "circle");
    [["cx", "10"], ["cy", "10"], ["r", "10"]].forEach(function (p) { c.setAttribute(p[0], p[1]); });
    c.style.fill = "#E4F3E8";
    c.style.stroke = "none";
    var p = D.createElementNS(NS, "path");
    p.setAttribute("d", "M6 10.4L8.7 13L14 7.4");
    p.style.cssText = "fill:none;stroke:" + GREEN + ";stroke-width:2;stroke-linecap:round;stroke-linejoin:round";
    svg.appendChild(c);
    svg.appendChild(p);
    return svg;
  }
  // The SafeScript symbol, built node by node (no innerHTML), so sites that enforce Trusted Types still get it.
  function symbol(color, w, h) {
    var NS = "http://www.w3.org/2000/svg", mark = D.createElementNS(NS, "svg");
    [["viewBox", "0 -1 80 72"], ["width", w], ["height", h], ["aria-hidden", "true"], ["focusable", "false"], ["fill", "none"],
      ["stroke", color], ["stroke-linecap", "round"], ["stroke-linejoin", "round"]].forEach(function (p) { mark.setAttribute(p[0], p[1]); });
    [["M21 7H15Q5 7 5 17V53Q5 63 15 63H21 M59 7H65Q75 7 75 17V53Q75 63 65 63H59", "7"], ["M23 36L34 47L57 23", "8"]].forEach(function (d) {
      var p = D.createElementNS(NS, "path");
      p.setAttribute("d", d[0]);
      p.setAttribute("stroke-width", d[1]);
      // Colours also as inline styles: a site's own CSS (for example "svg path { fill: currentColor }", or a dark
      // theme that recolours ink strokes) must never recolour the logo. Inline styles win over the site's rules.
      p.style.fill = "none";
      p.style.stroke = color;
      mark.appendChild(p);
    });
    return mark;
  }
  // The full logo (designs/logo/SafeScript-Humanist-SourceSans3.svg, the same paths and transforms), built node by
  // node like the symbol. Ink on light backgrounds; white only on a dark one (the checkout line on a dark store), the
  // one other colour the logo rules allow. Never any other recolour; status lives in the dot.
  var WORDMARK = [
    [0.000, "M277 -12Q212 -12 148.5 11.0Q85 34 34 83L117 185Q152 156 195.5 140.0Q239 124 281 124Q324 124 344.5 138.5Q365 153 365 180Q365 199 354.0 210.0Q343 221 322.5 230.5Q302 240 273 251L190 286Q156 301 126.0 325.0Q96 349 77.5 384.0Q59 419 59 466Q59 521 89.0 565.5Q119 610 172.5 636.5Q226 663 295 663Q354 663 409.5 642.0Q465 621 507 581L425 479Q392 503 359.0 515.5Q326 528 295 528Q260 528 239.0 514.5Q218 501 218 475Q218 457 230.5 445.0Q243 433 265.5 423.5Q288 414 316 403L398 370Q438 354 466.5 330.0Q495 306 510.5 272.0Q526 238 526 192Q526 138 497.0 91.5Q468 45 412.0 16.5Q356 -12 277 -12Z"],
    [52.945, "M189 -12Q143 -12 109.5 8.5Q76 29 58.0 63.5Q40 98 40 139Q40 219 105.5 263.0Q171 307 317 322Q315 342 307.0 356.0Q299 370 282.5 377.0Q266 384 242 384Q212 384 181.0 374.0Q150 364 112 343L57 444Q90 464 125.0 479.0Q160 494 196.5 502.0Q233 510 272 510Q336 510 381.0 485.5Q426 461 450.0 410.5Q474 360 474 281V0H346L335 50H331Q300 22 265.5 5.0Q231 -12 189 -12ZM243 110Q266 110 283.0 120.5Q300 131 317 148V226Q269 219 241.5 208.5Q214 198 202.0 183.5Q190 169 190 152Q190 131 204.5 120.5Q219 110 243 110Z"],
    [103.661, "M89 0V516Q89 569 107.0 613.0Q125 657 166.5 684.0Q208 711 278 711Q311 711 337.5 705.0Q364 699 380 693L350 581Q325 588 301 588Q275 588 260.5 572.5Q246 557 246 520V0ZM16 375V492L100 498H333V375Z"],
    [135.273, "M288 -12Q216 -12 158.5 19.0Q101 50 67.5 108.0Q34 166 34 249Q34 330 68.0 388.0Q102 446 156.5 478.0Q211 510 271 510Q343 510 390.5 478.0Q438 446 461.5 391.5Q485 337 485 270Q485 250 482.5 230.5Q480 211 478 201H157L155 307H350Q350 342 333.0 366.0Q316 390 274 390Q252 390 229.5 377.5Q207 365 193.0 334.0Q179 303 180 249Q182 193 201.0 162.5Q220 132 249.0 120.0Q278 108 310 108Q337 108 363.5 116.0Q390 124 416 139L467 44Q428 17 380.0 2.5Q332 -12 288 -12Z"],
    [184.533, "M277 -12Q212 -12 148.5 11.0Q85 34 34 83L117 185Q152 156 195.5 140.0Q239 124 281 124Q324 124 344.5 138.5Q365 153 365 180Q365 199 354.0 210.0Q343 221 322.5 230.5Q302 240 273 251L190 286Q156 301 126.0 325.0Q96 349 77.5 384.0Q59 419 59 466Q59 521 89.0 565.5Q119 610 172.5 636.5Q226 663 295 663Q354 663 409.5 642.0Q465 621 507 581L425 479Q392 503 359.0 515.5Q326 528 295 528Q260 528 239.0 514.5Q218 501 218 475Q218 457 230.5 445.0Q243 433 265.5 423.5Q288 414 316 403L398 370Q438 354 466.5 330.0Q495 306 510.5 272.0Q526 238 526 192Q526 138 497.0 91.5Q468 45 412.0 16.5Q356 -12 277 -12Z"],
    [237.576, "M286 -12Q214 -12 157.0 19.0Q100 50 67.0 108.0Q34 166 34 249Q34 331 71.0 389.5Q108 448 167.5 479.0Q227 510 297 510Q342 510 378.5 495.5Q415 481 442 457L369 360Q356 370 341.0 376.5Q326 383 306 383Q272 383 247.5 366.5Q223 350 209.0 320.0Q195 290 195 249Q195 208 209.0 177.5Q223 147 247.0 130.5Q271 114 302 114Q325 114 346.0 122.5Q367 131 386 145L447 49Q416 21 373.5 4.5Q331 -12 286 -12Z"],
    [282.279, "M62 0V498H190L201 411H205Q232 462 270.0 486.0Q308 510 346 510Q368 510 382.0 507.5Q396 505 407 500L377 366Q364 369 353.5 370.5Q343 372 326 372Q299 372 268.5 352.5Q238 333 219 284V0Z"],
    [321.164, "M62 0V498H219V0ZM140 566Q101 566 77.0 588.0Q53 610 53 647Q53 683 77.0 705.0Q101 727 140 727Q179 727 203.0 705.0Q227 683 227 647Q227 610 203.0 588.0Q179 566 140 566Z"],
    [348.315, "M62 -181V498H190L201 450H205Q234 476 270.0 493.0Q306 510 344 510Q404 510 447.5 478.5Q491 447 514.5 390.0Q538 333 538 257Q538 171 508.0 111.0Q478 51 430.5 19.5Q383 -12 329 -12Q298 -12 268.5 1.5Q239 15 214 39L219 -38V-181ZM292 116Q315 116 334.5 130.0Q354 144 365.5 174.5Q377 205 377 255Q377 298 368.0 326.0Q359 354 341.5 368.0Q324 382 297 382Q276 382 257.5 372.5Q239 363 219 340V145Q237 129 256.0 122.5Q275 116 292 116Z"],
    [400.970, "M259 -11Q165 -11 124.0 43.5Q83 98 83 186V375H16V492L92 498L110 649H240V498H357V375H240V188Q240 146 257.5 128.5Q275 111 302 111Q314 111 326.0 113.0Q338 115 348 118L373 9Q354 1 325.0 -5.0Q296 -11 259 -11Z"]
  ];
  function logo(height, white) {
    var NS = "http://www.w3.org/2000/svg", svg = D.createElementNS(NS, "svg"), ink = white ? "#FFFFFF" : INK;
    [["viewBox", "-2.26 1.503028 549.399698 98.048488"], ["height", String(height)], ["width", String(Math.round(height * 549.4 / 98.05))],
      ["role", "img"], ["focusable", "false"]].forEach(function (p) { svg.setAttribute(p[0], p[1]); });
    var title = D.createElementNS(NS, "title");
    title.textContent = "SafeScript";
    svg.appendChild(title);
    var mark = symbol(ink, "80", "72");
    var g = D.createElementNS(NS, "g");
    g.setAttribute("transform", "translate(1 4.83636265) scale(1.16)");
    ["fill", "stroke", "stroke-linecap", "stroke-linejoin"].forEach(function (k) { g.setAttribute(k, mark.getAttribute(k)); });
    while (mark.firstChild) g.appendChild(mark.firstChild);
    svg.appendChild(g);
    var words = D.createElementNS(NS, "g");
    words.setAttribute("transform", "translate(105 0)");
    words.setAttribute("fill", ink);
    WORDMARK.forEach(function (w) {
      var p = D.createElementNS(NS, "path");
      p.setAttribute("transform", "translate(" + w[0] + " 77) scale(0.0969697 -0.0969697)");
      p.setAttribute("d", w[1]);
      p.style.fill = ink;
      p.style.stroke = "none";
      words.appendChild(p);
    });
    svg.appendChild(words);
    return svg;
  }
  // The status dot. Only a verified record gets the calm radiating ring that says monitoring is active; it never
  // runs in any other state and stays still when the visitor asks for reduced motion.
  function statusDot(color, live) {
    var dot = el("span", "position:relative;display:block;flex:none;width:8px;height:8px;border-radius:50%;background:" + color);
    var still = false;
    try { still = W.matchMedia("(prefers-reduced-motion: reduce)").matches; } catch (e) {}
    if (live && !still && dot.animate) {
      var ring = el("span", "position:absolute;left:0;top:0;width:8px;height:8px;border-radius:50%;background:" + color + ";pointer-events:none");
      dot.appendChild(ring);
      // Scaled to the compact 32 px badge: the ring stays inside the pill's height.
      try { ring.animate([{ transform: "scale(1)", opacity: 0.5 }, { transform: "scale(2.6)", opacity: 0 }], { duration: 2400, iterations: Infinity, easing: "cubic-bezier(.2,.6,.3,1)" }); } catch (e) {}
    }
    return dot;
  }
  function el(tag, css, text) {
    var e = D.createElement(tag);
    if (css) e.style.cssText = css;
    if (text != null) e.textContent = text;
    return e;
  }
  function paint(a) {
    var v = view(state, status);
    // Compact (Eugiene, 25 Nov 2026): 32 px tall, tight padding, the full logo at its 120 px minimum width.
    if (!a.__ssStyled) a.style.cssText += ";display:inline-flex;align-items:center;gap:8px;min-height:32px;padding:3px 12px 3px 11px;border:1px solid " + LINE +
      ";border-radius:999px;background:#fff;color:" + INK + ";font:600 14px/1.2 " + FONT + ";text-decoration:none;white-space:nowrap;max-width:100%;box-sizing:border-box;vertical-align:middle";
    a.__ssStyled = 1;
    while (a.firstChild) a.removeChild(a.firstChild);
    // Badge: status dot, the full SafeScript logo and the status words. The whole badge is the link that opens the
    // details, so it carries no "View details" text (its accessible name says it). With an agency brand the symbol
    // stands in for the full logo and the brand name follows the words, as before.
    var verified = state === "verified";
    if (v[0]) a.appendChild(statusDot(v[0], verified));
    var mark = C.brand ? symbol(INK, "18", "16") : logo(21.5);
    mark.style.cssText = "display:block;flex:none";
    a.appendChild(mark);
    // The logo's title carries "SafeScript", so the badge's text still reads "SafeScript Verified".
    a.appendChild(D.createTextNode(" "));
    var label = a.appendChild(el("span", "", C.brand ? v[1] : v[1].replace(/^SafeScript /, "")));
    var extra = [];
    if (C.brand && v[2]) {
      extra = [el("span", "width:1px;height:14px;flex:none;background:" + LINE), el("span", "font-weight:400;color:" + SLATE, v[2])];
      extra.forEach(function (x) { a.appendChild(x); });
    }
    // A narrow footer: first the second part goes, then the symbol stands in for the full logo (which is never
    // shown below its 120 px minimum), then the words may wrap. Nothing spills out of the badge.
    later(function () {
      var over = function () { return a.scrollWidth > a.clientWidth + 1; };
      if (!over()) return;
      extra.forEach(function (x) { if (x.parentNode === a) a.removeChild(x); });
      if (!over() || C.brand) return;
      var small = symbol(INK, "18", "16");
      small.style.cssText = "display:block;flex:none";
      if (mark.parentNode === a) a.replaceChild(small, mark);
      label.textContent = v[1];
      if (over()) label.style.whiteSpace = "normal";
    });
    // The accessible name says what the badge does, now that the words "View details" are not shown.
    var opens = state !== "loading" && state !== "failed";
    a.setAttribute("aria-label", v[1] + (v[2] ? ", " + v[2] : "") + (opens ? ": view details" : ""));
    if (a.tagName === "A" && !getAttr.call(a, "href")) a.setAttribute("href", RECORD);
  }

  // The card (Eugiene, 25 Nov 2026): light, as on the approved mockup. Top row logo and status pill, headline, one line,
  // three check rows, the live lines, "Back to shopping", the record link, the small SafeScript footer.
  var CSS = ".bd{position:fixed;inset:0;background:rgba(17,39,63,.45);display:flex;align-items:center;justify-content:center;padding:16px;box-sizing:border-box;font-family:" + FONT + ";-webkit-font-smoothing:antialiased;animation:in .15s ease-out}" +
    "@media (prefers-reduced-motion:reduce){.bd{animation:none}}@keyframes in{from{opacity:0}}" +
    ".dlg{position:relative;background:#fff;color:" + SLATE + ";border:1px solid " + LINE + ";border-radius:10px;width:100%;max-width:420px;max-height:calc(100vh - 32px);overflow:auto;padding:24px 24px 0;box-sizing:border-box;font-size:16px;line-height:1.5;text-align:left;outline:0}" +
    ".top{display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:10px 12px;margin:0 0 22px}.top>svg{display:block;flex:none;width:auto;height:20px}" +
    ".pill{display:inline-flex;align-items:center;gap:7px;margin:0;padding:4px 11px;border-radius:999px;background:#F3F7F9;color:" + INK + ";font-size:13px;font-weight:600;line-height:1.3;white-space:nowrap}" +
    ".pill.ok{background:#E4F3E8;color:" + GREEN + "}.pill.warn{background:#FFF3D9;color:" + AMBER + "}.pill i{flex:none;width:7px;height:7px;border-radius:50%}" +
    "h2{margin:0 0 8px;color:" + INK + ";font-size:24px;line-height:1.2;font-weight:600;letter-spacing:-.01em;overflow-wrap:anywhere}" +
    "p{margin:0 0 12px}.lede{font-size:16px}" +
    "ul{list-style:none;margin:20px 0 0;padding:0;display:grid;gap:14px}li{display:grid;grid-template-columns:20px 1fr;gap:12px;align-items:start}li svg{display:block;margin-top:1px}" +
    "li b{display:block;color:" + INK + ";font-size:15px;font-weight:600;line-height:1.35}li span{display:block;margin-top:2px;font-size:14px;line-height:1.45}" +
    ".live{margin:20px 0 0;padding:14px 0 0;border-top:1px solid " + LINE + ";font-size:13px;line-height:1.5}.live p{margin:0 0 4px;display:flex;align-items:center;gap:8px;overflow-wrap:anywhere}" +
    ".live p:last-child{margin:0}.live p span{min-width:0}" +
    ".act{margin:20px 0 0;display:grid;justify-items:center;gap:10px}" +
    ".pri{display:flex;align-items:center;justify-content:center;width:100%;min-height:48px;padding:0 16px;border:1px solid " + INK + ";border-radius:6px;background:" + INK + ";color:#fff;font:600 16px " + FONT + ";cursor:pointer;box-sizing:border-box}.pri:hover{background:#1B3A5A}" +
    ".rec{padding:4px;color:#28577D;font-size:14px;font-weight:500;text-decoration:underline;text-underline-offset:3px}" +
    ".foot{margin:18px -24px 0;padding:12px 24px;border-top:1px solid " + LINE + ";font-size:13px;text-align:center}.foot a{color:#28577D;font-weight:500;white-space:nowrap}" +
    ".end{height:20px}:focus-visible{outline:2px solid #28577D;outline-offset:2px}" +
    "@media (max-width:400px){.dlg{padding:20px 18px 0}.foot{margin:18px -18px 0;padding:12px 18px}h2{font-size:22px}}";

  function lightbox(badge) {
    var v = view(state, status), s = status || {}, ok = state === "verified", k = ok ? card(s) : null;
    var host = el("div");
    host.style.cssText = "all:initial!important;position:fixed!important;inset:0!important;z-index:2147483647!important;display:block!important";
    var root = host.attachShadow({ mode: "closed" });
    var style = el("style", "", CSS), bd = el("div"), dlg = el("div");
    bd.className = "bd";
    dlg.className = "dlg";
    dlg.setAttribute("role", "dialog");
    dlg.setAttribute("aria-modal", "true");
    dlg.setAttribute("aria-labelledby", "ss-t");
    dlg.tabIndex = -1;
    // Top row: the full logo, ink as the logo rules ask, and the status pill, which carries the colour. Green only
    // while verified; every other state keeps its own status words and colour.
    var top = el("div");
    top.className = "top";
    top.appendChild(logo(20));
    var pill = el("p");
    pill.className = ok ? "pill ok" : v[0] === AMBER ? "pill warn" : "pill";
    if (v[0]) pill.appendChild(el("i", "background:" + v[0]));
    pill.appendChild(D.createTextNode(ok ? k.pill : v[1]));
    top.appendChild(pill);
    dlg.appendChild(top);
    var h = el("h2", "", ok ? k.head : "Script monitoring for " + HOST);
    h.id = "ss-t";
    dlg.appendChild(h);
    var line = ok ? k.line : v[3];
    if (line) dlg.appendChild(el("p", "", line)).className = "lede";
    if (ok) {
      var ul = el("ul");
      k.rows.forEach(function (r) {
        var li = el("li"), txt = el("div");
        li.appendChild(tick());
        txt.appendChild(el("b", "", r[0]));
        txt.appendChild(el("span", "", r[1]));
        li.appendChild(txt);
        ul.appendChild(li);
      });
      dlg.appendChild(ul);
    }
    // The live lines: the latest check as a relative time (only once one has completed), and the domain. Other
    // states keep their dated check line.
    var live = el("div"), meta = ok ? (s.lastChecked ? k.checked + ago(s.lastChecked) : "") : checkLine(state, status);
    live.className = "live";
    if (meta) {
      var m = el("p");
      if (ok) m.appendChild(statusDot(GREEN, true));
      m.appendChild(el("span", "", meta));
      live.appendChild(m);
    }
    if (ok) live.appendChild(el("p")).appendChild(el("span", "", k.domain));
    if (live.firstChild) dlg.appendChild(live);
    var act = el("div"), back = el("button", "", "Back to shopping"), rec = el("a", "", "See the full record");
    act.className = "act";
    back.type = "button";
    back.className = "pri";
    rec.className = "rec";
    rec.href = RECORD;
    rec.target = "_blank";
    rec.rel = "noopener";
    rec.setAttribute("aria-label", "See the full record (opens in a new tab)");
    act.appendChild(back);
    act.appendChild(rec);
    dlg.appendChild(act);
    // The SafeScript footer. Pro and Agency owners may turn it off (the settings then carry footer: false).
    var get = null;
    if (C.footer !== false) {
      var foot = el("p", "", ok ? k.foot : "Monitoring provided by SafeScript · ");
      get = el("a", "", "Protect your own website free →");
      foot.className = "foot";
      get.href = API + "/?ref=badge";
      get.target = "_blank";
      get.rel = "noopener";
      foot.appendChild(get);
      dlg.appendChild(foot);
    } else dlg.appendChild(el("div")).className = "end";
    bd.appendChild(dlg);
    root.appendChild(style);
    root.appendChild(bd);

    var focusables = get ? [back, rec, get] : [back, rec];
    function close() {
      D.removeEventListener("keydown", keys, true);
      if (host.parentNode) host.parentNode.removeChild(host);
      try { badge.focus(); } catch (e) {}
    }
    function keys(e) {
      if (e.key === "Escape") { e.preventDefault(); close(); return; }
      if (e.key !== "Tab") return;
      var i = focusables.indexOf(root.activeElement), next = i < 0 ? (e.shiftKey ? -1 : 0) : e.shiftKey ? i - 1 : i + 1;
      e.preventDefault();
      focusables[(next + focusables.length) % focusables.length].focus();
    }
    back.addEventListener("click", close);
    bd.addEventListener("click", function (e) { if (e.target === bd) close(); });
    D.addEventListener("keydown", keys, true);
    D.body.appendChild(host);
    // Focus starts on the dialog itself, so a screen reader reads its title and Enter doesn't close it at once.
    dlg.focus();
    try { badgeOpened(); } catch (e) {}
  }

  // The live status from /api/badge/HOST, asked for once per page and shared by the footer badge and the checkout line.
  var statusWait = [], statusAsked = false;
  function loadStatus(fn) {
    statusWait.push(fn);
    if (statusAsked) return;
    statusAsked = true;
    var f = origFetch ? origFetch.call(W, API + "/api/badge/" + encodeURIComponent(HOST), { credentials: "omit" }) : Promise.reject();
    f.then(function (r) { return r.ok ? r.json() : null; }).catch(function () { return null; }).then(function (s) {
      status = s;
      state = stateFor(s);
      statusWait.forEach(function (g) { try { g(); } catch (e) {} });
    });
  }

  function badges() {
    var found = D.querySelectorAll("#safescript-badge,[data-safescript-badge]");
    if (!found.length) return;
    var list = Array.prototype.slice.call(found);
    list.forEach(function (a) {
      paint(a);
      a.addEventListener("click", function (e) {
        if (e.button || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || state === "loading") return;
        e.preventDefault();
        try { lightbox(a); } catch (x) { location.href = getAttr.call(a, "href") || RECORD; }
      });
    });
    loadStatus(function () { list.forEach(function (a) { try { paint(a); } catch (e) {} }); });
  }

  // ---------- checkout line ----------
  // "SafeScript Secured" under the store's checkout button, on cart pages and in slide-out carts. Only when the owner
  // switched it on (the settings carry checkout: true), the live record is verified and SafeScript is blocking, both in
  // the record and in this tab's own settings. Learning, monitor, paused, unconfirmed, a failed status or another
  // domain: nothing is added. No checkout button found: nothing is added.

  // <checkout-finder> From here to </checkout-finder> uses only the DOM it is given: tests/checkout-finder.test.mjs runs this
  // exact text in a real browser on saved cart markup (tests/fixtures/checkout/).
  // Platform selectors, each seen on real stores' rendered carts (27 Nov 2026; trimmed copies in tests/fixtures/checkout/).
  var CHECKOUT_SEL = [
    // Shopify: the cart form's submit button is named "checkout" (Dawn, Horizon, Impulse, Prestige and custom Vue carts,
    // on the cart page and in the drawer).
    "button[name=checkout]", "input[name=checkout][type=submit]",
    // Shopify Dawn family class names, and a customised Dawn drawer whose button has only id="checkout" and no text.
    "button#checkout", "button#CartDrawer-Checkout", ".cart__checkout-button", "button.cart__checkout", ".cart-drawer__checkout",
    // Rebuy Smart Cart, a Shopify app drawer (type=button, no name, no form). 4 of 7 real Shopify stores checked had it.
    ".rebuy-cart__checkout-button",
    // WooCommerce: classic cart (the Modern Cart drawer reuses it), classic mini cart widget, Cart block, Mini-Cart block.
    ".wc-proceed-to-checkout a.checkout-button", ".woocommerce-mini-cart__buttons a.checkout", "a.wc-block-cart__submit-button",
    "a.wc-block-mini-cart__footer-checkout",
    // BigCommerce: Cornerstone cart page, preview dropdown and add-to-cart modal; Merchant cart page.
    "[data-primary-checkout-now-action]", "a.button-checkout",
    // Squarespace 7.1: cart page and mini cart.
    "a.cart-checkout-button", "button.commerce-mini-cart-checkout-button",
    // Wix Stores: cart page and side cart.
    "[data-hook='CheckoutButtonDataHook.button']", "[data-wix-checkout-button]",
    // Medusa (Next.js storefront).
    "[data-testid=checkout-button]"
  ].join(",");
  // The fallback, only when no platform selector found a visible button: a button or button-like link whose words are
  // "Check out", "Checkout", "Proceed to checkout", "Secure checkout" (a price may follow) and that points at checkout.
  var CHECKOUT_WORDS = /^(?:secure\s+|safe\s+)?(?:proceed\s+to\s+(?:secure\s+)?|go\s+to\s+|continue\s+to\s+)?check\s?-?\s?out(?![a-z])/i;
  // Never a checkout button, whatever its classes say: an empty cart's "Shop now", "View cart", Loop's "Continue without
  // Checkout+", wallet buttons (they are the payment provider's, not the store's checkout).
  var NOT_CHECKOUT = /\b(?:empty|shop now|continue shopping|keep shopping|view (?:cart|basket|bag)|without|learn more)\b|shop\s?pay|paypal|apple pay|google pay|amazon pay/i;
  function cbLabel(el) {
    var t = el.tagName === "INPUT" ? el.value : el.textContent;
    t = String(t || el.getAttribute("aria-label") || el.getAttribute("data-text") || "");
    return t.replace(/\s+/g, " ").replace(/^ | $/g, "").slice(0, 80);
  }
  function cbColor(c) {
    var m = /rgba?\(([^)]+)\)/.exec(c || ""), p = m ? m[1].split(/[\s,/]+/).filter(Boolean) : null;
    return p ? [+p[0], +p[1], +p[2], p.length > 3 ? (/%$/.test(p[3]) ? parseFloat(p[3]) / 100 : +p[3]) : 1] : null;
  }
  // Seen and on screen: a real box, not hidden, not see-through, and not parked off screen (closed drawers on real stores
  // are often full size and "visible", only moved outside the window).
  function cbShown(el, win) {
    var r = el.getBoundingClientRect(), vw = win.innerWidth || el.ownerDocument.documentElement.clientWidth, vh = win.innerHeight;
    if (r.width < 24 || r.height < 16 || r.right <= 0 || r.left >= vw) return false;
    for (var n = el, k = 0; n && n.nodeType === 1 && k < 40; n = n.parentElement, k++) {
      if (win.getComputedStyle(n).position === "fixed") { if (r.bottom <= 0 || r.top >= vh) return false; break; }
    }
    if (el.checkVisibility) return el.checkVisibility({ opacityProperty: true, visibilityProperty: true });
    var s = win.getComputedStyle(el);
    return s.display !== "none" && s.visibility !== "hidden" && +s.opacity > 0;
  }
  function cbGeneric(el, label, win) {
    if (label.length > 60 || !CHECKOUT_WORDS.test(label)) return false;
    // Menus, breadcrumbs and checkout steps link to checkout too; they are not the cart's button.
    if (el.closest("nav,[role=navigation],[role=menu],[class*=breadcrumb],[class*=steps]")) return false;
    var cls = typeof el.className === "string" ? el.className : "";
    var named = (el.getAttribute("name") || "") + " " + (el.id || "") + " " + (el.getAttribute("formaction") || "") + " " + cls;
    if (el.tagName === "A") {
      var href = el.getAttribute("href") || "";
      if (href.charAt(0) === "#" || !/checkout/i.test(href)) return false;
      var bg = cbColor(win.getComputedStyle(el).backgroundColor);
      return /\b(?:btn|button)/i.test(cls) || el.getAttribute("role") === "button" || !!(bg && bg[3] > 0);
    }
    if (/checkout/i.test(named)) return true;
    var f = el.form;
    return !!(f && el.type === "submit" && /checkout|\/cart\b/i.test(f.getAttribute("action") || ""));
  }
  // The visible checkout buttons in the page, in page order, at most three. One entry per button: a button inside
  // another match (a link wrapping a button) counts once.
  function checkoutButtons(doc, win) {
    var out = [];
    function take(list, generic) {
      for (var i = 0; i < list.length && out.length < 3; i++) {
        var el = list[i], tag = el.tagName, label, j;
        if (tag !== "A" && tag !== "BUTTON" && tag !== "INPUT" && el.getAttribute("role") !== "button") continue;
        if (el.disabled || el.getAttribute("aria-disabled") === "true" || el.closest("[aria-hidden=true],[inert]")) continue;
        label = cbLabel(el);
        if (NOT_CHECKOUT.test(label) || (generic && !cbGeneric(el, label, win)) || !cbShown(el, win)) continue;
        for (j = 0; j < out.length; j++) if (out[j].contains(el) || el.contains(out[j])) break;
        if (j === out.length) out.push(el);
      }
    }
    take(doc.querySelectorAll(CHECKOUT_SEL), false);
    if (!out.length) take(doc.querySelectorAll("a[href],button,input[type=submit],input[type=button]"), true);
    return out;
  }
  // Is the background behind the button dark? The first ancestor with a real background colour decides (the button's
  // own colour does not: the line sits beside it, on the container). Dark when white gives more contrast than ink,
  // which is below a relative luminance of about 0.22 (WCAG luminance; ink #11273F is 0.0198).
  function cbDark(el, win) {
    for (var n = el.parentElement; n; n = n.parentElement) {
      var c = cbColor(win.getComputedStyle(n).backgroundColor);
      if (!c || c[3] < 0.5) continue;
      var lin = function (v) { v /= 255; return v <= 0.04045 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4); };
      var L = 0.2126 * lin(c[0]) + 0.7152 * lin(c[1]) + 0.0722 * lin(c[2]);
      return 1.05 / (L + 0.05) > (L + 0.05) / 0.0698;
    }
    return false;
  }
  // Where the line goes: right after the button, or after the row that holds it when the button shares a horizontal row
  // (express pay buttons side by side, a flex row, a grid with more than one column), and never inside a link, button
  // or label (a click on the line must never press the store's control).
  function cbAnchor(btn, win) {
    var at = btn, up;
    for (var k = 0; k < 4 && at.parentElement; k++) {
      var p = at.parentElement, s = win.getComputedStyle(p);
      var row = /flex/.test(s.display) && !/column/.test(s.flexDirection);
      var grid = /grid/.test(s.display) && String(s.gridTemplateColumns).replace(/\[[^\]]*\]/g, "").split(/\s+/).filter(Boolean).length > 1;
      if (!row && !grid && s.display !== "inline" && s.display !== "contents") break;
      at = p;
    }
    while (at.parentElement && (up = at.parentElement.closest("a,button,label,summary"))) at = up;
    return at;
  }
  // </checkout-finder>

  var MARK_CSS = "button{all:unset;display:inline-flex;align-items:center;gap:7px;padding:4px 6px;border-radius:6px;cursor:pointer;" +
    "font:600 14px/1 " + FONT + ";color:" + GREEN + ";white-space:nowrap;box-sizing:border-box;-webkit-tap-highlight-color:transparent}" +
    "button:hover{background:rgba(17,39,63,.05)}button:focus-visible{outline:2px solid #28577D;outline-offset:2px}" +
    "svg{display:block;flex:none;width:auto;height:21.5px}" +
    ".i{display:inline-flex;align-items:center;justify-content:center;flex:none;width:16px;height:16px;border:1.5px solid " + SLATE +
    ";border-radius:50%;box-sizing:border-box;color:" + SLATE + ";font:italic 600 11px/1 Georgia,serif}" +
    ".dark{color:#7DD3A8}.dark .i{border-color:#C9D3DC;color:#C9D3DC}.dark:hover{background:rgba(255,255,255,.07)}" +
    ".dark:focus-visible{outline-color:#C9D3DC}";
  var lines = [], cbTimer = 0, cbFirst = 0, cbNoRoom = new WeakMap();
  function lineFor(btn) {
    for (var i = 0; i < lines.length; i++) if (lines[i].btn === btn) return lines[i];
    return null;
  }
  // The line in a closed shadow root, like the card, so the store's CSS cannot restyle it. Built node by node.
  function addLine(btn) {
    var dark = cbDark(btn, W), host = el("div"), root, b, i;
    host.style.cssText = "all:initial!important;display:block!important;position:static!important;margin:10px 0 0!important;padding:0!important;" +
      "align-self:stretch!important;justify-self:stretch!important;grid-column:1/-1!important;width:auto!important;text-align:left!important;line-height:0!important";
    host.__ssLine = 1;
    root = host.attachShadow({ mode: "closed" });
    b = el("button");
    b.type = "button";
    if (dark) b.className = "dark";
    b.setAttribute("aria-label", "SafeScript Secured: view details");
    b.setAttribute("aria-haspopup", "dialog");
    var mark = logo(21.5, dark);
    mark.setAttribute("aria-hidden", "true");
    b.appendChild(mark);
    b.appendChild(el("span", "", "Secured"));
    i = el("span", "", "i");
    i.className = "i";
    i.setAttribute("aria-hidden", "true");
    b.appendChild(i);
    // The whole line opens the same card as the footer badge. The click stays with SafeScript: the store's own handlers
    // (a drawer that closes on outside clicks, a form) never see it.
    b.addEventListener("click", function (e) {
      e.preventDefault();
      e.stopPropagation();
      try { lightbox(b); } catch (x) { W.open(RECORD, "_blank", "noopener"); }
    });
    root.appendChild(el("style", "", MARK_CSS));
    root.appendChild(b);
    // Never move or resize the store's button: if adding the line changes the button's size or its place across the
    // page, the line comes out again and this button gets none. (A drawer footer pinned to the bottom may grow upwards;
    // that is the drawer's own layout.)
    var at = cbAnchor(btn, W), r0 = btn.getBoundingClientRect();
    at.parentNode.insertBefore(host, at.nextSibling);
    var r1 = btn.getBoundingClientRect();
    if (Math.abs(r1.width - r0.width) > 1 || Math.abs(r1.height - r0.height) > 1 || Math.abs(r1.left - r0.left) > 1) {
      host.parentNode.removeChild(host);
      cbNoRoom.set(btn, 1);
      return;
    }
    var line = { btn: btn, host: host, b: b };
    lines.push(line);
    align(line);
  }
  // Centred under the button with about 10 px between them, whatever the container does.
  function align(l) {
    var hb = l.host.getBoundingClientRect(), bb = l.btn.getBoundingClientRect(), w = l.b.offsetWidth;
    if (!hb.width || !bb.width || !w) return;
    var x = Math.max(0, Math.min(bb.left - hb.left + bb.width / 2 - w / 2, hb.width - w));
    l.b.style.marginLeft = Math.round(x) + "px";
    var mt = parseFloat(l.host.style.marginTop) || 0, gap = hb.top - bb.bottom;
    if (gap > 11 || gap < 9) l.host.style.setProperty("margin-top", Math.max(0, Math.round(10 - (gap - mt))) + "px", "important");
  }
  function checkoutScan() {
    cbTimer = 0;
    cbFirst = 0;
    // A line whose button left the page goes too; a line the store's own re-render removed is forgotten, so the new
    // button gets one.
    lines = lines.filter(function (l) {
      if (l.btn.isConnected && l.host.isConnected) return true;
      if (l.host.parentNode) l.host.parentNode.removeChild(l.host);
      return false;
    });
    var found = checkoutButtons(D, W);
    for (var i = 0; i < found.length && lines.length < 3; i++) {
      if (!lineFor(found[i]) && !cbNoRoom.has(found[i])) addLine(found[i]);
    }
    lines.forEach(function (l) { try { align(l); } catch (e) {} });
  }
  // Re-checked when the page changes (a cart drawer rendered or opened later), a quarter second after the changes stop
  // and at most a second after the first one. Changes that are only SafeScript's own lines never start a check.
  function soon() {
    var t = Date.now();
    if (!cbFirst) cbFirst = t;
    clearTimeout(cbTimer);
    cbTimer = setTimeout(function () { try { checkoutScan(); } catch (e) {} }, t - cbFirst >= 1000 ? 0 : 250);
  }
  function oursOnly(r) {
    if (r.type !== "childList") return false;
    var i;
    for (i = 0; i < r.addedNodes.length; i++) if (!r.addedNodes[i].__ssLine) return false;
    for (i = 0; i < r.removedNodes.length; i++) if (!r.removedNodes[i].__ssLine) return false;
    return true;
  }
  function checkoutStart() {
    if (!C.checkout || !C.badge || MODE !== "block" || state !== "verified" || !status || status.mode !== "block") return;
    checkoutScan();
    new MutationObserver(function (records) {
      for (var i = 0; i < records.length; i++) if (!oursOnly(records[i])) return soon();
    }).observe(D.body || D.documentElement, { childList: true, subtree: true, attributes: true, attributeFilter: ["class", "hidden", "open", "aria-hidden", "inert"] });
    D.addEventListener("click", function () { setTimeout(soon, 350); }, true);
    W.addEventListener("resize", soon);
  }

  try {
    Object.defineProperty(W, "SafeScript", {
      value: Object.freeze({ version: 2, mode: MODE, host: HOST, get events() { return log.slice(); } }),
      configurable: false, writable: false,
    });
  } catch (e) {}
  try { if (MODE !== "paused") install(); } catch (e) {}
  if (C.badge) {
    var start = function () {
      try { badges(); } catch (e) {}
      if (C.checkout) try { loadStatus(checkoutStart); } catch (e) {}
    };
    if (D.readyState === "loading") D.addEventListener("DOMContentLoaded", start);
    else start();
  }
  // Paused too: the test then shows honestly that nothing was checked.
  if (TEST_TOKEN) try { runTest(TEST_TOKEN); } catch (e) {}
})();

History

Version history

Newest first. Every file stays available at its address for installs that use it.

VersionReleasedIntegrity (SHA-384)
0f75c9ce72bd (current)2026-11-27sha384-D3XJznK9AXScAMWrgUm1yk1zBEPLvZWQVeCO1LSxphmuOZx3pRjXuJ9zBQk7ak3z
2861a078fb5d2026-11-26sha384-KGGgePtdXv0aQYYdc3Xw/oO0Ul1zMh8aUsvkKS1Hvz3y9Dsz3D/4D8cIGIKJvcKu
ae7382052f2d2026-11-26sha384-rnOCBS8tbNCbuTjiUdmpPRYhUPzfZRqlw5NsFLS6mdTcmnoenZemzgkU1ZrLsNpg
9e649f5899d22026-11-26sha384-nmSfWJnSoIYJYfOEi+xuJccZ0BlO+bFodr4So6t/HWNuYt6D2BiYGxbsgZijuFsZ
d0765433400a2026-11-26sha384-0HZUM0AKuQ7Nd4O2gm2Y75HLJQtc9mERKpSgFrgIJyV/6lC08yaTTf3nFwLneu6r
2651ac2aee9e2026-11-25sha384-JlGsKu6ezmQ+GBhqx6L9+4Kt6CNLJaYNE/i1JL4vKQB0nY06kYZzXA4EJabggnUr
19447af428b82026-11-25sha384-GUR69Ci4Cmi6fLGVJpmHctOCEisx0We1fQN+mSJ6P1w7jVPv6+lHV+gy0QWwOx7q
aebbe87e59242026-11-25sha384-rrvoflkkkD48i/NudazjZq0IwX6hjuaNUMQZytT+6We6u3IRbvarJXEvPEZfGBIV
7ab048fec0762026-11-25sha384-erBI/sB2SVnsBgezh50RCO3mnfDwd6GGlN+mG63I0qhOvBZZZW4ZIobi2DbOVGwz