Dev.to WebDev 🛠 Dev 👁 0 📖 3 min read

Writing a Cookie AutoDelete-Compatible Domain Rule Parser in Vanilla JS

When users migrate away from legacy Manifest V2 cookie managers, the hardest part isn't writing chrome.cookies.remove() — it's honoring the keep-list rules they've spent years curating. If someone exported *.github.com

When users migrate away from legacy Manifest V2 cookie managers, the hardest part isn't writing chrome.cookies.remove() — it's honoring the keep-list rules they've spent years curating.

If someone exported *.github.com as WHITE, accounts.google.com as GREY (clear on browser restart, keep while open), or /^staging\./ as a regex rule in Cookie AutoDelete (CAD), breaking subtle matching semantics silently logs them out of every session.

While building Lark Cookie Sweep (MIT on GitHub, live on Microsoft Edge Add-ons), we isolated all rule parsing and import/export logic into two zero-dependency ES modules (src/lib/rules.js and src/lib/cad-import.js) so every rule edge case can be unit-tested in Node before touching a browser.

1. Normalizing Hosts Without Breaking IPv6 or Subdomains

Cookies and tab URLs arrive in inconsistent shapes (https://www.Example.COM., [::1], .github.com). Normalizing both sides first keeps downstream matching deterministic:

export function normalizeHost(host) {
  if (typeof host !== "string") return "";
  let h = host.trim().toLowerCase().replace(/^\.+/, "").replace(/\.+$/, "");
  if (h.startsWith("[") && h.endsWith("]")) h = h.slice(1, -1);
  return h.replace(/^www[a-z0-9]?\./, "");
}

Stripping www. (and variants like www2.) matches CAD's convention so a rule for example.com covers www.example.com without forcing users to maintain duplicate entries.

2. Compiling *.example.com, Exact Hosts, and /regex/ Safely

In CAD syntax:

  • example.com matches example.com exactly (ignoring www.)
  • *.example.com matches both example.com and any nested subdomain (gist.github.com, a.b.example.com)
  • /regex/ compiles a regular expression tested against the hostname
  • sub*.example.com treats * as a wildcard
export function globToRegExpSource(glob) {
  const g = String(glob).trim();
  if (g.length > 2 && g.startsWith("/") && g.endsWith("/")) return g.slice(1, -1);
  const wildStart = g.startsWith("*.");
  const body = normalizeHost(wildStart ? g.slice(2) : g)
    .replace(/[.+?^${}()|[\]\\/]/g, "\\$&")
    .replace(/\*/g, ".*");
  return `${wildStart ? "(^|\\.)" : "^"}${body}$`;
}

Notice why wildStart uses (^|\.) instead of ^.*\.: ^.*\.github\.com$ would fail to match the root domain github.com itself, whereas (^|\.)github\.com$ matches both github.com and api.github.com.

When resolving ties between multiple matching rules in the same cookie jar (storeId):

  1. Exact rules beat wildcards/regex — so a GREY rule on preview.example.com can still override a WHITE wildcard on *.example.com.
  2. On equal specificity, WHITE beats GREY — never delete what the user explicitly marked to keep.

3. Mapping Cookie Jars (storeId) Across Chrome, Edge, and Firefox

Chrome and Edge use "0" for the default profile and "1" for Incognito; Firefox uses "firefox-default", "firefox-private", and "firefox-container-N" for Multi-Account Containers.

export function storeKey(storeId) {
  if (!storeId || storeId === "0" || storeId === "1" || storeId === "firefox-default" || storeId === "firefox-private") {
    return "default";
  }
  return String(storeId);
}

Mapping normal/incognito stores to "default" means your main keep-list protects tabs consistently while open-tab protection still inspects cookies per actual storeId so closing an incognito tab sweeps incognito cookies without touching your normal session.

4. Importing Expressions.json, Full Exports, and Plain-Text Lists

Users bring rules in three formats: CAD's "Export Expressions" JSON ({ "<storeId>": [...] }), CAD's full settings JSON ({ lists: { ... } }), or plain text (example.com,GREY with # comments).

export function parseImport(text) {
  const errors = [];
  if (typeof text !== "string" || !text.trim()) return { format: "text", rules: [], errors: ["file is empty"] };
  let data = null;
  const t = text.trim().replace(/^\uFEFF/, "");
  if (t.startsWith("{") || t.startsWith("[")) {
    try { data = JSON.parse(t); } catch (e) { return { format: "cad", rules: [], errors: [`invalid JSON: ${e.message}`] }; }
  }
  let rules;
  let format = "cad";
  if (data && !Array.isArray(data) && typeof data === "object") {
    const lists = data.lists && typeof data.lists === "object" && !Array.isArray(data.lists) ? data.lists : data;
    rules = fromCadLists(lists, errors);
  } else if (Array.isArray(data)) {
    rules = fromCadLists({ default: data }, errors);
  } else {
    format = "text";
    rules = fromText(t, errors);
  }
  if (rules.length > 5000) { errors.push("only the first 5000 rules were imported"); rules = rules.slice(0, 5000); }
  return { format, rules, errors };
}

Stripping a leading UTF-8 BOM (\uFEFF), validating every expression before saving, capping imports at 5,000 rules, and exporting back in CAD's JSON shape keeps migrations lossless and reversible.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.