From b308af83ce1aaeda4b42d8f83359416de1a20b5e Mon Sep 17 00:00:00 2001 From: Darknode-Official Date: Fri, 27 Nov 2026 22:49:18 -0800 Subject: [PATCH] Watch domain registration and website security Two new server-side monitor types, both part of the Free one-domain watch: - domain-expiry: reads the registry's RDAP record (IANA bootstrap). Alerts before the registration expires (30 days by default), when it has lapsed or is not registered, when a transfer is pending, and when the transfer lock is off (gTLDs only). Subdomains are graded by their registrable domain. - web-posture: HTTPS and the HTTP redirect, HSTS, CSP, clickjacking, nosniff and cookie flags (same posture engine as the browser tool), plus an exposed /.git/HEAD or /.env, recognised from the first 2 KB and never stored. Once a domain has a baseline, a weaker header or registration alerts as drift. A watch set up before this gets an "Add the other checks" button under Monitors. Docs, Plans, landing and help copy updated. --- public/index.html | 2 +- public/js/check/first-run.js | 15 +-- public/js/core/entitlements.js | 2 +- public/js/deck-ui.js | 2 +- public/js/deck/monitor-client.js | 10 ++ public/js/deck/monitors.js | 64 +++++++--- public/js/docs.js | 6 +- public/js/landing.js | 2 +- public/js/ui/explain.js | 2 +- test/worker/monitor-do.test.mjs | 36 ++++++ test/worker/watch-checks.test.mjs | 175 ++++++++++++++++++++++++++ worker/alert-email.js | 31 +++++ worker/checks.js | 203 +++++++++++++++++++++++++++++- worker/free-watch.js | 10 +- worker/monitor.js | 19 ++- 15 files changed, 535 insertions(+), 44 deletions(-) create mode 100644 test/worker/watch-checks.test.mjs diff --git a/public/index.html b/public/index.html index 617c3a41..4a133a7a 100644 --- a/public/index.html +++ b/public/index.html @@ -28,7 +28,7 @@ - + diff --git a/public/js/check/first-run.js b/public/js/check/first-run.js index 1bb9f694..387c5e26 100644 --- a/public/js/check/first-run.js +++ b/public/js/check/first-run.js @@ -12,7 +12,7 @@ // never for a free-mail provider or a Test Mode / guest identity. // // Once a check has run, "Watch this domain" sets up the Free plan's one-domain watch: a -// certificate-expiry and an email/DNS monitor on that domain, checked once a day, alerting by +// certificate, domain-registration, email/DNS and website monitor on that domain, checked once a day, alerting by // email to the account's own verified address (the Worker takes the address from the sign-in // token and enforces the one-domain limit, worker/free-watch.js). @@ -63,8 +63,6 @@ function paint() { } // ---- "Watch this domain" ------------------------------------------------------------------- -const WATCH_TYPES = ["cert-expiry", "email-posture"]; -const DAY = 86400000; const isFree = () => { const t = S.ctx && S.ctx.tier; return !t || t === "free"; }; const hostsOf = (m) => ((m && m.config && m.config.domains) || []).map((d) => normalizeDomain(d)).filter(Boolean); const goBtn = (act, label) => ``; @@ -73,14 +71,14 @@ function watchHtml() { const d = S.res.domain, w = S.watch && S.watch.domain === d ? S.watch : null; if (!w || w.state === "busy") { const busy = !!w; - return `
Watch ${esc(d)}
Get an email when its certificate is close to expiry, or when an email or DNS record (SPF, DMARC, MX, CAA) is removed or weakened. Checked once a day${isFree() ? ". The Free plan watches one domain" : ""}.
+ return `
Watch ${esc(d)}
Get an email before its certificate or its domain registration expires, when an email or DNS record (SPF, DMARC, MX, CAA) is removed or weakened, and when the website loses a security header or exposes its .git or .env. Checked once a day${isFree() ? ". The Free plan watches one domain" : ""}.
`; } if (w.state === "on") { const where = w.to ? `Alerts go by email to ${esc(w.to)}, at most 5 emails a day.` : w.emailAll ? "Alerts go by email to your account address, at most 5 emails a day." : "Alerts go to the channels set on each monitor."; const head = w.paused ? `The watch on ${esc(d)} is turned off.` : (w.already ? "Already watching " : "Watching ") + esc(d) + "."; - const body = w.paused ? "Turn it back on under Monitors to check its certificate and email/DNS records once a day." - : `Its certificate (expiry within 21 days) and its email/DNS records (SPF, DMARC, MX, CAA) are checked once a day. ${where} Turn the watch off any time under Monitors.`; + const body = w.paused ? "Turn it back on under Monitors to check it once a day." + : `Its certificate (expiry within 21 days), its domain registration (expiry within 30 days, transfer lock), its email and DNS records (SPF, DMARC, MX, CAA) and its website (HTTPS, security headers, an exposed .git or .env) are checked once a day. ${where} Turn the watch off any time under Monitors.`; return `
${head} ${body}
${goBtn("monitors", "Open Monitors")}
`; } if (w.state === "guest") { @@ -103,7 +101,7 @@ async function watchDomain() { if (isTestIdentity(S.ctx && S.ctx.user)) return set({ state: "guest" }); set({ state: "busy" }); try { - const { monitorApi } = await import("/js/deck/monitor-client.js?v=1"); + const { monitorApi, WATCH_TYPES, watchMonitor } = await import("/js/deck/monitor-client.js?v=1"); // the Free watch lives in the caller's own workspace, whichever one is active const opts = { personal: free }; const mons = ((await monitorApi({ op: "list" }, opts)) || {}).monitors || []; @@ -115,8 +113,7 @@ async function watchDomain() { const made = []; for (const type of WATCH_TYPES) { if (mine.some((m) => m.type === type)) continue; - const monitor = { name: (type === "cert-expiry" ? "Certificate: " : "Email and DNS: ") + domain, type, config: type === "cert-expiry" ? { domains: [domain], warnDays: 21 } : { domains: [domain] }, intervalMs: DAY, channels: [{ type: "email" }] }; - const r = await monitorApi({ op: "upsert", monitor }, opts); + const r = await monitorApi({ op: "upsert", monitor: watchMonitor(type, domain) }, opts); if (r && r.monitor) made.push(r.monitor); } const all = mine.concat(made); diff --git a/public/js/core/entitlements.js b/public/js/core/entitlements.js index 736bd4bd..efadd91d 100644 --- a/public/js/core/entitlements.js +++ b/public/js/core/entitlements.js @@ -31,7 +31,7 @@ export const FEATURES = { export const LIMITS = { seats: { free: 1, pro: 1, team: 25, enterprise: -1 }, workspaces: { free: 1, pro: 1, team: 5, enterprise: -1 }, - // domains a Free account may watch for certificate expiry and email/DNS changes, with + // domains a Free account may watch for its certificate, registration, email/DNS records and website, with // alerts by email (worker/free-watch.js enforces it); Pro and above have no domain cap watchDomains: { free: 1, pro: -1, team: -1, enterprise: -1 }, }; diff --git a/public/js/deck-ui.js b/public/js/deck-ui.js index 83f2f52f..9036b099 100644 --- a/public/js/deck-ui.js +++ b/public/js/deck-ui.js @@ -4252,7 +4252,7 @@ export function renderDeck(host, opts) { const PLANS = [ { id: "free", name: "Free", price: "$0", unit: "forever", tag: "", a: "#2552c6", blurb: "Quick checks, the live feed and the assistant, for individuals and evaluation.", - feats: ["Free browser tools in the Tool Library", "Quick Checks: email security, headers, certificates, DNS, breaches, CVEs", "Personal space: domain, link, secret and data checks", "Live vulnerability feed (CVE and known-exploited)", "Local-only security graph & case files", "Watch 1 domain: certificate expiry and email/DNS changes, alerts by email", "Darknode AI assistant: 50 messages a day", "1 workspace, 1 seat"], + feats: ["Free browser tools in the Tool Library", "Quick Checks: email security, headers, certificates, DNS, breaches, CVEs", "Personal space: domain, link, secret and data checks", "Live vulnerability feed (CVE and known-exploited)", "Local-only security graph & case files", "Watch 1 domain: certificate, registration, email/DNS and website changes, alerts by email", "Darknode AI assistant: 50 messages a day", "1 workspace, 1 seat"], cta: "Current plan", cur: true }, { id: "pro", name: "Pro", price: "$29", unit: "per user / month", tag: "Recommended", a: "#2552c6", blurb: "For professionals who need history, exports and the strongest AI models.", diff --git a/public/js/deck/monitor-client.js b/public/js/deck/monitor-client.js index 8f854906..ae825c4d 100644 --- a/public/js/deck/monitor-client.js +++ b/public/js/deck/monitor-client.js @@ -28,3 +28,13 @@ export async function monitorApi(body, opts = {}) { if (!r.ok) throw Object.assign(new Error(j.error || ("Monitor request failed (" + r.status + ")")), { status: r.status, plan: j.plan === true }); return j; } + +// The domain watch: one daily monitor per check type, alerting by email. Free accounts get +// exactly this for one domain (worker/free-watch.js FREE_WATCH.types). +export const WATCH_TYPES = ["cert-expiry", "email-posture", "domain-expiry", "web-posture"]; +export const WATCH_NAME = { "cert-expiry": "Certificate", "email-posture": "Email and DNS", "domain-expiry": "Domain registration", "web-posture": "Website" }; +export const watchMonitor = (type, domain) => ({ + name: WATCH_NAME[type] + ": " + domain, type, + config: type === "cert-expiry" ? { domains: [domain], warnDays: 21 } : type === "domain-expiry" ? { domains: [domain], warnDays: 30 } : { domains: [domain] }, + intervalMs: 86400000, channels: [{ type: "email" }], +}); diff --git a/public/js/deck/monitors.js b/public/js/deck/monitors.js index d8c87d7a..f0fca639 100644 --- a/public/js/deck/monitors.js +++ b/public/js/deck/monitors.js @@ -4,11 +4,11 @@ // certificate expiry (real CT-log lookups graded by the posture engine); more are added // server-side as worker-safe engines are extracted. // -// On the Free plan the scene shows the one-domain watch (certificate expiry + email/DNS -// changes, alerts by email to the account's own address) in the caller's own workspace, with a +// On the Free plan the scene shows the one-domain watch (certificate, registration, email/DNS +// and website checks, alerts by email to the account's own address) in the caller's own workspace, with a // switch to turn it off. The Worker enforces the limits (worker/free-watch.js); this only hides // what the plan does not include. -import { monitorApi as api, monitoringAvailable } from "./monitor-client.js"; +import { monitorApi as api, monitoringAvailable, WATCH_TYPES, watchMonitor } from "./monitor-client.js"; const S = { ctx: null, el: null, data: null, adding: false, busy: false, seq: 0 }; // seq: a reply for a previous mount/workspace is dropped const E = (s) => (S.ctx && S.ctx.esc ? S.ctx.esc(s) : String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]))); @@ -20,7 +20,6 @@ const CHANNELS =[["email", "Email (your account address)"], ["slack", "Slack"], const isFree = () => !!(S.ctx && S.ctx.tier === "free"); // the Free watch lives in the caller's own workspace, so on Free every request goes there const monitorApi = (body) => api(body, { personal: isFree() }); -const WATCH_TYPES = ["cert-expiry", "email-posture"]; // The Free watch as the Worker counts it (free-watch.js freeAllowed): monitors of a watch type, // alerting by email only, on exactly one domain; the earliest-created one's domain is the watch. function freeWatch(mons) { @@ -30,7 +29,15 @@ function freeWatch(mons) { const domain = hostOf(fits[0].config.domains[0]) || fits[0].config.domains[0]; const list = fits.filter((m) => (hostOf(m.config.domains[0]) || m.config.domains[0]) === domain); const mail = list.flatMap((m) => m.channels || []).find((c) => c.type === "email" && c.to); - return { domain, list, paused: list.every((m) => m.paused), to: mail ? mail.to : "" }; + const missing = WATCH_TYPES.filter((t) => !list.some((m) => m.type === t)); + return { domain, list, missing, paused: list.every((m) => m.paused), to: mail ? mail.to : "" }; +} +const WATCH_PART = { "cert-expiry": "certificate expiry", "email-posture": "email/DNS records (SPF, DMARC, MX, CAA)", "domain-expiry": "domain registration", "web-posture": "website security (HTTPS, headers, exposed files)" }; +// "Certificate expiry, domain registration and ..." for the checks this watch holds +function watchList(fw) { + const parts = WATCH_TYPES.filter((t) => fw.list.some((m) => m.type === t)).map((t) => WATCH_PART[t]); + const s = parts.length > 1 ? parts.slice(0, -1).join(", ") + " and " + parts[parts.length - 1] : parts[0] || ""; + return s.charAt(0).toUpperCase() + s.slice(1); } const chanText = (chs) => !chs || !chs.length ? "no alert channel" : chs.map((c) => c.type === "email" ? "email" + (c.to ? " to " + c.to : "") : ((CHANNELS.find(([v]) => v === c.type) || [])[1] || c.type)).join(", "); @@ -91,7 +98,7 @@ async function load() { if (!monitoringAvailable()) { box.innerHTML = `
Monitoring is not available on this build — it needs the cloud proxy. Nothing to configure yet.
`; return; } // guest / Test Mode: monitors run on the server for an account and email it, so offer sign-up if (S.ctx && S.ctx.noAccount) { - box.innerHTML = `
Monitors need a free account
They run on Darknode's servers and email the account that set them up. A free account watches one domain for certificate expiry and email/DNS changes, checked once a day.
+ box.innerHTML = `
Monitors need a free account
They run on Darknode's servers and email the account that set them up. A free account watches one domain: its certificate, registration, email/DNS records and website, checked once a day.
`; box.querySelector("#monSignup").onclick = () => S.ctx.signup && S.ctx.signup(); return; @@ -126,21 +133,21 @@ function paint() {
`; - }).join("") : `
No monitors yet. Add a certificate monitor to get alerted before a cert expires.
`; + }).join("") : `
No monitors yet. Add a certificate, domain registration or website watch to hear about a problem before your visitors do.
`; const free = isFree(), fw = free ? freeWatch(mons) : null; const watchHtml = !free ? "" : fw ? `
Free plan watch: ${E(fw.domain)}${fw.paused ? " (turned off)" : ""}
${fw.paused ? "Turned off: nothing is checked and no alerts are sent until you turn it back on." - : `Certificate expiry and email/DNS changes (SPF, DMARC, MX, CAA), checked once a day. Alerts go by email to ${fw.to ? E(fw.to) : "your account address"}, at most 5 emails a day.`}
-
` - : `
Free plan: watch one domain
Certificate expiry and email/DNS changes, checked once a day, with alerts by email to your account address. Run a domain check on the Overview and choose Watch this domain, or add a monitor below.
+ : `${E(watchList(fw))}, checked once a day. Alerts go by email to ${fw.to ? E(fw.to) : "your account address"}, at most 5 emails a day.`}
+ ${fw.missing.length && !fw.paused ? '' : ""}` + : `
Free plan: watch one domain
Its certificate, registration, email/DNS records and website, checked once a day, with alerts by email to your account address. Run a domain check on the Overview and choose Watch this domain, or add a monitor below.
`; box.innerHTML = ` ${watchHtml}

${mons.length.toLocaleString()} monitor${mons.length === 1 ? "" : "s"}. Monitors run on the server's own schedule; alerts fire only when something changes.${free ? " More domains, known-exploited CVE watches and Slack, Teams or webhook alerts are part of Pro." : ""}

-
${free ? "" : ''}
+
${free ? "" : ''}
${monHtml} ${logPanel("Recent runs", (S.data.history || []).slice(0, 8), (h) => `${E((S.data.monitors.find((m) => m.id === h.id) || {}).name || h.id)} — ${h.error ? ("error: " + E(h.error)) : `${h.found} open, ${h.added} new, ${h.changed} changed, ${h.alerted} alerted${h.skipped ? `, ${h.skipped} could not be checked` : ""}${h.graphError ? ", not synced to Findings: " + E(h.graphError) : ""}`} · ${E(ago(h.at))}`)} @@ -150,8 +157,12 @@ function paint() { const kevBtn = box.querySelector("#monAddKev"), plansBtn = box.querySelector("#monPlans"), watchBtn = box.querySelector("#monWatchToggle"); if (plansBtn) plansBtn.onclick = () => { if (S.ctx && S.ctx.go) S.ctx.go("plans"); }; if (watchBtn) watchBtn.onclick = () => toggleWatch(fw); + const moreBtn = box.querySelector("#monWatchMore"); + if (moreBtn) moreBtn.onclick = () => addWatchChecks(fw); if (kevBtn) kevBtn.onclick = () => { const was = S.adding && S.kind === "kev-epss"; S.kind = "kev-epss"; S.adding = !was; renderForm(); }; - box.querySelector("#monAddMail").onclick = () => { const was = S.adding && S.kind === "email-posture"; S.kind = "email-posture"; S.adding = !was; renderForm(); }; + for (const [id, kind] of [["#monAddMail", "email-posture"], ["#monAddReg", "domain-expiry"], ["#monAddWeb", "web-posture"]]) { + box.querySelector(id).onclick = () => { const was = S.adding && S.kind === kind; S.kind = kind; S.adding = !was; renderForm(); }; + } if (S.adding) renderForm(); box.querySelectorAll(".mon-row").forEach((row) => row.querySelector(".mon-actions").onclick = (e) => { const b = e.target.closest("[data-act]"); if (!b) return; @@ -170,10 +181,16 @@ function logPanel(title, rows, fmt) { function renderForm() { const slot = S.el && S.el.querySelector("#monFormSlot"); if (!slot) return; if (!S.adding) { slot.innerHTML = ""; return; } - const kev = S.kind === "kev-epss", mail = S.kind === "email-posture", free = isFree(); + const kev = S.kind === "kev-epss", mail = S.kind === "email-posture", reg = S.kind === "domain-expiry", web = S.kind === "web-posture", free = isFree(); const one = free ? " The Free plan watches one domain." : ""; const domPh = free ? "example.com" : "one per line or comma-separated"; - const specific = mail + const domField = (hint) => `

${hint}${one}

`; + const specific = reg + ? domField("Domains to watch, e.g. example.com. The registry's RDAP record is read once per check: an alert goes out before the registration expires (30 days by default), when a transfer to another registrar is pending, and when the transfer lock is turned off. A subdomain is checked by its registered domain.") + ` +
` + : web + ? domField("Sites to watch, e.g. example.com. Each check loads the home page over HTTPS and HTTP and asks for /.git/HEAD and /.env, the same requests any visitor can make. Only the headers are kept, never page content. After the first check, any header that disappears or gets weaker raises an alert.") + : mail ? `

Domains to watch, e.g. example.com. SPF, DMARC, MX and CAA are read over public DNS-over-HTTPS; after the first run, any record that is removed or weakened raises an alert.${one}

` : kev ? `

A CVE in your graph alerts when it is in the CISA KEV catalogue, or its EPSS exploit-prediction score is at or above this floor. Nothing is sent anywhere; the match runs against the current feeds.

` @@ -184,8 +201,8 @@ function renderForm() { const EMAIL_HINT = "Alerts go to your account's verified email address, at most 5 alert emails a day."; const HOOK_HINT = "Slack, Teams and Discord use their own incoming-webhook URL. For a signed webhook you can add a shared secret below."; slot.innerHTML = `
-

${kev ? "New KEV / EPSS watch" : mail ? "New email & DNS watch" : "New certificate-expiry monitor"}

-
+

${kev ? "New KEV / EPSS watch" : mail ? "New email & DNS watch" : reg ? "New domain registration watch" : web ? "New website watch" : "New certificate-expiry monitor"}

+
${specific}
${free ? '

The Free plan checks once a day (1440 minutes).

' : ""}
@@ -233,6 +250,8 @@ function readForm(slot) { const domains = [], bad = []; for (const x of raw) { const h = hostOf(x); if (h) { if (!domains.includes(h)) domains.push(h); } else bad.push(x); } if (S.kind === "email-posture") return { bad, name: ($("#mfName").value || "").trim() || "Email and DNS watch", type: "email-posture", config: { domains }, intervalMs, channels }; + if (S.kind === "web-posture") return { bad, name: ($("#mfName").value || "").trim() || "Website watch", type: "web-posture", config: { domains }, intervalMs, channels }; + if (S.kind === "domain-expiry") return { bad, name: ($("#mfName").value || "").trim() || "Domain registration watch", type: "domain-expiry", config: { domains, warnDays: Math.max(1, Math.min(365, Number($("#mfWarn").value) || 30)) }, intervalMs, channels }; return { bad, name: ($("#mfName").value || "").trim() || "Certificate monitor", @@ -248,7 +267,7 @@ async function saveMonitor(slot) { const mon = readForm(slot); if (mon.bad && mon.bad.length) { toast("Not a domain name: " + mon.bad.slice(0, 3).join(", ") + (mon.bad.length > 3 ? " and " + (mon.bad.length - 3) + " more" : "") + ". Use hostnames such as test.darknode.ai.", "warn"); return; } delete mon.bad; - if ((mon.type === "cert-expiry" || mon.type === "email-posture") && !mon.config.domains.length) { toast("Add at least one domain.", "warn"); return; } + if (mon.type !== "kev-epss" && !mon.config.domains.length) { toast("Add at least one domain.", "warn"); return; } if (isFree() && mon.config.domains && mon.config.domains.length > 1) { toast("The Free plan watches one domain. Keep one domain, or request an upgrade under Plans to watch more.", "warn"); return; } if (mon.channels[0] && mon.channels[0].type !== "email" && mon.channels[0].type && !mon.channels[0].url) { toast("Add the incoming webhook URL for this channel.", "warn"); return; } S.busy = true; @@ -272,6 +291,17 @@ async function testChannel(slot) { } // Turn the Free watch off or on: pause or resume every monitor in it. +// A watch set up before a check type existed gets the missing ones, same domain, same email alerts. +async function addWatchChecks(fw) { + if (!fw || S.busy || !fw.missing.length) return; + S.busy = true; + try { + for (const t of fw.missing) await monitorApi({ op: "upsert", monitor: watchMonitor(t, fw.domain) }); + toast("Added to the watch on " + fw.domain + ". The first check runs within a few minutes.", "ok"); + } catch (e) { toast(e.message || "Could not add the checks.", "error"); } + finally { S.busy = false; await load(); } +} + async function toggleWatch(fw) { if (!fw || S.busy) return; const paused = !fw.paused; diff --git a/public/js/docs.js b/public/js/docs.js index c105edc9..65115308 100644 --- a/public/js/docs.js +++ b/public/js/docs.js @@ -32,7 +32,7 @@ const STANDOUT = [ ]; const CHANGELOG = [ - ["3.3.x", "Live integrations: Deck security integrations are connected only after a live key test, through a relay to fixed provider endpoints (VirusTotal, Shodan, AbuseIPDB, GreyNoise, OTX, urlscan, SecurityTrails, ipinfo, Have I Been Pwned, Hunter, Pulsedive, Hybrid Analysis, plus keyless NVD and CIRCL CVE). The Deck Assistant can run lookups on connected integrations, asking first each time unless you choose Always allow. Text boxes no longer refill from saved lists on reload; a Load saved list button brings them back on request. A full bug sweep fixed about 90 issues across the Deck, the business tools, the flagship tools and all 780 quick utilities, among them wrong file hashes for binary files, a strict CSP graded as broken, missed SQL injection and display-name spoofing, the ASN Explorer (moved from the retired BGPView to RIPEstat), and spreadsheet formula injection in CSV exports. Nexus background sessions (nexus bg / attach / sessions); signed-in Nexus and desktop app report version, OS and VM counts every 6 hours (/shareusage off, or Settings > Share app usage). Docs: the Nexus Commands tab lists every Nexus command, and Cost Saving shows /cheap before-and-after costs on each Claude model, measured on real sessions. A free domain check on the home page, with no sign-up, grades email authentication, HTTPS, certificate expiry (from certificate transparency logs), security headers, DNSSEC, CAA and security.txt and shows what each check is worth; a /check/your-domain link runs it again live, and a new Deck opens on the same check with each issue saved as a finding. The Free plan now watches one domain: after a check, Watch this domain checks its certificate expiry and its email/DNS records (SPF, DMARC, MX, CAA) once a day and emails your verified account address when something changes, with what changed, why it matters and the exact fix (at most 5 alert emails a day, each with a stop link). Monitors can also email your account address on Pro and above. Deadlines: a Deadlines page and an Overview block list the clocks your findings start, soonest first with the time left: a watched certificate's expiry and, only if you opt in, the Cyber Resilience Act Article 14 reporting clocks (early warning 24 hours and vulnerability notification 72 hours after you become aware of an actively exploited vulnerability in an asset you mark as shipped in a product, final report 14 days after a fix is available) and CISA BOD 22-01 due dates. Alerts go out when a clock starts and when a quarter of its time is left, and a certificate's last-week re-alert is now that reminder. A Copy early-warning facts panel lists the CVE, the product, when exploitation was confirmed, when you became aware, the Member States and the measures known. Darknode does not decide whether these rules apply and does not submit anything."], + ["3.3.x", "Live integrations: Deck security integrations are connected only after a live key test, through a relay to fixed provider endpoints (VirusTotal, Shodan, AbuseIPDB, GreyNoise, OTX, urlscan, SecurityTrails, ipinfo, Have I Been Pwned, Hunter, Pulsedive, Hybrid Analysis, plus keyless NVD and CIRCL CVE). The Deck Assistant can run lookups on connected integrations, asking first each time unless you choose Always allow. Text boxes no longer refill from saved lists on reload; a Load saved list button brings them back on request. A full bug sweep fixed about 90 issues across the Deck, the business tools, the flagship tools and all 780 quick utilities, among them wrong file hashes for binary files, a strict CSP graded as broken, missed SQL injection and display-name spoofing, the ASN Explorer (moved from the retired BGPView to RIPEstat), and spreadsheet formula injection in CSV exports. Nexus background sessions (nexus bg / attach / sessions); signed-in Nexus and desktop app report version, OS and VM counts every 6 hours (/shareusage off, or Settings > Share app usage). Docs: the Nexus Commands tab lists every Nexus command, and Cost Saving shows /cheap before-and-after costs on each Claude model, measured on real sessions. A free domain check on the home page, with no sign-up, grades email authentication, HTTPS, certificate expiry (from certificate transparency logs), security headers, DNSSEC, CAA and security.txt and shows what each check is worth; a /check/your-domain link runs it again live, and a new Deck opens on the same check with each issue saved as a finding. The Free plan now watches one domain: after a check, Watch this domain checks its certificate expiry and its email/DNS records (SPF, DMARC, MX, CAA) once a day and emails your verified account address when something changes, with what changed, why it matters and the exact fix (at most 5 alert emails a day, each with a stop link). Monitors can also email your account address on Pro and above. Deadlines: a Deadlines page and an Overview block list the clocks your findings start, soonest first with the time left: a watched certificate's expiry and, only if you opt in, the Cyber Resilience Act Article 14 reporting clocks (early warning 24 hours and vulnerability notification 72 hours after you become aware of an actively exploited vulnerability in an asset you mark as shipped in a product, final report 14 days after a fix is available) and CISA BOD 22-01 due dates. Alerts go out when a clock starts and when a quarter of its time is left, and a certificate's last-week re-alert is now that reminder. A Copy early-warning facts panel lists the CVE, the product, when exploitation was confirmed, when you became aware, the Member States and the measures known. Darknode does not decide whether these rules apply and does not submit anything. Two new monitors, also part of the Free watch: domain registration (expiry, a pending transfer and the transfer lock, read from the registry's RDAP record) and website security (HTTPS, security headers and cookie flags, and an exposed .git or .env). Once a site has been checked, a header that disappears or weakens alerts."], ["3.2.x", "Business security platform: the Darknode Deck with native Personal and Organization spaces (domain posture grading, certificate watch, link and email phishing checks, code-secret scanning, sensitive-data checks with redaction, domain portfolios and fleet views), a Web toolkit tab linking the hands-on web-security tools, plan-based tool availability, team workspaces, and removal of the off-topic financial tools."], ["3.1.x", "Web console line: flagship platforms (PHANTOM packet/network ops, CITADEL SOC console, ORACLE threat-intel engine, SPECTRE cloud posture, CRUCIBLE defensive wargaming, NAVARCH maritime defense), a platform-wide Security Graph that cross-links findings, the Sentinel Eye 3D threat globe, 125 security tools plus 780 quick utilities, the Professional theme, the Darknode assistant (Help button in the top bar), and Nexus AI integration."], ["2.29.x", "Nexus multi-engine agent: /cowork model tiering, /lean /effort /cheap /estimate, local RAG (/index), /race /ensemble /bench, /plan /watch /agents (worktree-isolated), /guard /secrets /scan /redact /offline, git checkpoints (/undo /redo /rewind), MCP + hooks, ~56 commands. NEXUS.md now reaches the Claude engine; plan mode is truly read-only."], @@ -121,7 +121,7 @@ node darknode.js nexus init # optional: scaffold .nexus/ project
Which tools do I get on my plan?

Tools are shown according to your plan; anything outside your plan is simply not listed. Free covers the Personal space and platform basics; Pro adds exposure, application-security and reporting tools; Team adds the Organization space, identity and security-operations tools and team workspaces; Enterprise adds risk and compliance tooling.

Do the checks touch my systems?

The domain and certificate checks read only public signals (HTTP headers, DNS, certificate transparency, security.txt). Secret and sensitive-data checks run entirely in your browser. The Web toolkit's API, WebSocket and fuzzing tools do send requests to the target you name, so use them only on systems you own or are authorized to test.

What does the free domain check on the home page look at?

Fifteen checks worth 100 points in total, read live from public DNS, HTTP responses and certificate transparency logs: email authentication (SPF 10, DMARC policy 12, DKIM 6, mail servers 4), HTTPS (HTTPS 10, HTTP to HTTPS redirect 7, certificate expiry 6), security headers (HSTS 8, Content-Security-Policy 7, frame protection 4, X-Content-Type-Options 4, Referrer-Policy 2), DNS hardening (DNSSEC 7, CAA 7) and security.txt (6). A pass earns a check's points, a warning half, a fail none. A check that could not run is shown as not checked and left out of the grade rather than counted as a pass or a zero, and the grade (A 90, B 80, C 65, D 50) says how many of the 100 points it covers. It needs no account and stores nothing: a /check/your-domain link runs the check again when it is opened. In the Deck the same check saves each issue as a finding and links the tool that fixes it. It runs once each time. To keep watching a domain, choose Watch this domain after a check in the Deck (see below).

-
What does the Free plan's domain watch do?

A Free account can watch one domain. After a domain check in the Deck, Watch this domain sets up two monitors on it: certificate expiry (from certificate transparency logs, warning 21 days ahead) and email/DNS changes (SPF, DMARC, MX and CAA, read over public DNS). They run on our servers once a day, also when the Deck is closed. When something changes, or a certificate is close to expiry, an email goes to your verified account address only, saying what changed, why it matters and the exact fix, with a link to Monitors in the Deck. The first check can also email you about a serious problem it finds straight away. A certificate close to expiry is also listed under Deadlines, and you get one reminder when a quarter of the time to expiry is left. You get at most 5 alert emails a day; anything after that is listed under Monitors. Turn the watch off under Monitors, or use the stop link in any alert email. Watching more domains, known-exploited CVE watches and Slack, Teams or webhook alerts are part of Pro.

+
What does the Free plan's domain watch do?

A Free account can watch one domain. After a domain check in the Deck, Watch this domain sets up four monitors on it: certificate expiry (from certificate transparency logs, warning 21 days ahead); domain registration (the registry's public RDAP record: expiry 30 days ahead, a pending transfer, the transfer lock turned off); email/DNS changes (SPF, DMARC, MX and CAA, read over public DNS); and the website (HTTPS and the HTTP redirect, HSTS, Content-Security-Policy, clickjacking and nosniff headers, cookie flags, and whether /.git or /.env can be downloaded). The website check makes the same few requests any visitor can make: the home page over HTTPS and HTTP, plus /.git/HEAD and /.env. Watch only sites you own or are allowed to check. A watch set up earlier can add the new checks with Add the other checks under Monitors. They run on our servers once a day, also when the Deck is closed. When something changes, or a certificate is close to expiry, an email goes to your verified account address only, saying what changed, why it matters and the exact fix, with a link to Monitors in the Deck. The first check can also email you about a serious problem it finds straight away. A certificate close to expiry is also listed under Deadlines, and you get one reminder when a quarter of the time to expiry is left. You get at most 5 alert emails a day; anything after that is listed under Monitors. Turn the watch off under Monitors, or use the stop link in any alert email. Watching more domains, known-exploited CVE watches and Slack, Teams or webhook alerts are part of Pro.

What are Deadlines, and does Darknode file Cyber Resilience Act reports?

Deadlines lists the clocks your findings start, soonest first, with the time left (overdue ones in red) and the steps for each. A certificate your monitors see expiring is one, on every plan: it is due when the certificate expires and closes by itself when the monitor sees the renewed one. On Pro, two opt-ins under Deadlines add more, and nothing is assumed without them. Cyber Resilience Act: tick "We make products with digital elements sold in the EU" and mark the assets or components (from your Security Graph, including SBOM imports) that are shipped in a product. When your known-exploited CVE monitor finds a CISA KEV vulnerability in one of them, three clocks start, from Regulation (EU) 2024/2847 Article 14(2): an early warning within 24 hours of becoming aware, a vulnerability notification within 72 hours, and a final report no later than 14 days after a fix or mitigation is available (that clock starts when you mark the fix available). Becoming aware starts as the time Darknode alerted you; you can correct it. Article 14 applies from 11 September 2026, and the notifications go to your coordinating CSIRT and ENISA through ENISA's single reporting platform. BOD 22-01: tick "We follow CISA BOD 22-01" and each known-exploited CVE in your inventory gets the KEV catalogue's due date. Alerts go to the monitor's channels when a clock starts and when a quarter of its time is left. Cyber Resilience Act alert emails do not count against the 5 a day for monitor alerts; they have their own limit of 20 a day. Darknode does not decide whether the Cyber Resilience Act or BOD 22-01 applies to you and does not submit anything: it tracks the clocks and prepares the facts (Copy early-warning facts), and you decide and file.

Do I need an API key for Nexus?

No. The Claude engine drives your logged-in Claude Code CLI; the local engine talks to your own Ollama. Nexus stores no keys.

Does my code leave my machine?

Only if you use a cloud engine (every engine except Ollama). The Ollama engine is fully local. /redact masks secrets before any cloud send; /offline blocks cloud entirely.

@@ -157,7 +157,7 @@ node darknode.js nexus init # optional: scaffold .nexus/ project
  • Retention & deletion. You can delete your account and its data at any time in the Deck under Settings, Data, Delete account. It takes effect at once and cannot be undone.
  • In-browser tools. Most analysis runs in your browser. Check history and saved domain lists in the Deck spaces are kept in your browser's local storage, unless you turn on the weekly email digest or a monitor (see below). Live checks against a domain you enter are fetched through our edge proxy and are not stored.
  • Weekly email digest. Off unless you turn it on in Settings. While it is on we store your watched domains and your latest certificate-check results (domain, expiry date, issuer) on our servers to build the email, and send it to your account email through our email provider, Resend. Turn it off in Settings or with the unsubscribe link in any digest.
  • -
  • Monitors and the domain watch. When you set up a monitor, including the Free plan's one-domain watch, we store on our servers the domains it watches, its settings, its latest results (such as a certificate's expiry date and issuer, and the domain's SPF and DMARC policy, so a later change can be named) and a log of its runs and alert deliveries. Email alerts go only to your own verified account email, looked up in our sign-in provider when each alert is sent, and are sent through our email provider, Resend; to apply the limit of 5 alert emails a day we keep a count per account for the current UTC day. Webhook and chat URLs you add to a monitor are stored to deliver its alerts. Turn a watch off or delete it under Monitors, or use the stop link in any alert email.
  • +
  • Monitors and the domain watch. When you set up a monitor, including the Free plan's one-domain watch, we store on our servers the domains it watches, its settings, its latest results (such as a certificate's or registration's expiry date, the domain's SPF and DMARC policy, and which security headers its website sends, so a later change can be named; a website watch keeps the URL of an exposed .git or .env file, never its contents) and a log of its runs and alert deliveries. Email alerts go only to your own verified account email, looked up in our sign-in provider when each alert is sent, and are sent through our email provider, Resend; to apply the limit of 5 alert emails a day we keep a count per account for the current UTC day. Webhook and chat URLs you add to a monitor are stored to deliver its alerts. Turn a watch off or delete it under Monitors, or use the stop link in any alert email.
  • Deadlines. We store the deadlines your monitors find (what is due and when, its status, and the reason and account when someone marks one done or dismisses it), the two opt-ins under Deadlines, and the assets you mark as shipped in a product (their names and Security Graph ids). For a Cyber Resilience Act case we also store the CVE, the matched assets, the CISA KEV date, the times you enter for becoming aware and for the fix, the Member States and the measures you type. Deadline alerts go to the channels of the monitor that found them; to apply the limit of 20 Cyber Resilience Act alert emails a day we keep a count per account for the current UTC day. Closed certificate and BOD 22-01 deadlines are deleted after 180 days; Cyber Resilience Act cases are kept as your record until you ask us to delete them. Darknode does not send any of this to a CSIRT, ENISA or anyone else.
  • AI assistant. Questions to the built-in assistant pass through our edge proxy to the model provider and are not logged or stored by us. To apply the daily message limits we keep a count of messages for the current UTC day, per account (or per IP address when you are not signed in); the count holds no message content and is cleared the next day.
  • Integrations. A Deck integration is connected only after a live test of your key, which stays in your browser. Lookups to providers that block browser calls (such as VirusTotal or Shodan) pass your key and the looked-up value through our edge relay to that provider only; we do not log or store the key, the value or the result. The assistant asks before each lookup unless you choose Always allow.
  • diff --git a/public/js/landing.js b/public/js/landing.js index d9399b7d..80001e90 100644 --- a/public/js/landing.js +++ b/public/js/landing.js @@ -688,7 +688,7 @@ ${pageOnly}
  • Personal space: domain, link, secret and data checks
  • Live vulnerability feed (CVE and known-exploited)
  • Local-only security graph & case files
  • -
  • Watch 1 domain: certificate expiry and email/DNS changes, alerts by email
  • +
  • Watch 1 domain: certificate, registration, email/DNS and website changes, alerts by email
  • Darknode AI assistant: 50 messages a day
  • 1 workspace, 1 seat
  • diff --git a/public/js/ui/explain.js b/public/js/ui/explain.js index 79253209..66414d60 100644 --- a/public/js/ui/explain.js +++ b/public/js/ui/explain.js @@ -41,7 +41,7 @@ export const EXPLAIN = { "scene.invest": { title: "Investigations", body: "Browse and filter every entity in your security graph, with severity, status and relationships. Sample data is hidden unless you include it." }, "scene.inventory": { title: "Asset Inventory", body: "One deduplicated view of every host and identity your tools recorded — the same machine or person seen by several tools shown once — plus a coverage matrix of which control sources saw each. Read from your graph; nothing is uploaded." }, "scene.correlations": { title: "Correlations", body: "Cross-tool attack chains: the same host or person flagged by two different tools adds up to a risk neither reports alone — account takeover, a leaver still active, an exploitable exposed host. Deterministic rules read your findings; each chain links back to the findings that prove it. Nothing is written back." }, - "scene.monitors": { title: "Monitors", body: "Scheduled security checks that run on the server and keep running when the Deck is closed — starting with certificate expiry via live certificate-transparency lookups. Only real changes raise an alert, sent by email to your own account address or routed to Slack, Teams, Discord or a signed webhook. The Free plan watches one domain for certificate expiry and email/DNS changes, with alerts by email. Alert channel secrets stay on the server." }, + "scene.monitors": { title: "Monitors", body: "Scheduled security checks that run on the server and keep running when the Deck is closed — certificate expiry (certificate-transparency logs), domain registration (registry RDAP), email and DNS records, website security headers and exposed .git or .env files, and known-exploited CVEs in your graph. Only real changes raise an alert, sent by email to your own account address or routed to Slack, Teams, Discord or a signed webhook. The Free plan watches one domain for all four domain checks, with alerts by email. Alert channel secrets stay on the server." }, "scene.device": { title: "This Computer", body: "Desktop app only. Runs on this machine: a workstation hardening audit mapped to CIS benchmarks, direct DNS, WHOIS and TLS lookups with no relay, the local AI models installed in Ollama, and the native tools." }, "scene.deadlines": { title: "Deadlines", body: "The clocks your findings start, soonest first, each with its steps: a watched certificate's expiry and, only if you opt in, the Cyber Resilience Act Article 14 reporting clocks (early warning 24 hours and notification 72 hours after you become aware of an actively exploited vulnerability in a product you ship, final report 14 days after the fix) and CISA BOD 22-01 due dates. Alerts go out when a clock starts and when a quarter of its time is left. Darknode does not decide whether a law applies and does not submit anything.", src: "Regulation (EU) 2024/2847 Article 14, CISA BOD 22-01 and the CISA KEV catalogue; certificate dates from Certificate Transparency logs." }, "scene.apikeys": { title: "API & Ingest", body: "Issue a workspace API key and push findings in from CI — SARIF, CycloneDX, the Finding JSON contract or a native scanner export (Nessus, Trivy, Snyk and others). Keys are shown once and stored only as a SHA-256 hash. Ingested findings queue on the server and are pulled into your Security Graph here, through the same sink every tool uses." }, diff --git a/test/worker/monitor-do.test.mjs b/test/worker/monitor-do.test.mjs index b3e10e36..66c97b77 100644 --- a/test/worker/monitor-do.test.mjs +++ b/test/worker/monitor-do.test.mjs @@ -521,3 +521,39 @@ group("monitor DO/plan", () => { assert.equal(m.by, "u1"); assert.equal(m.planHeld, undefined); }); }); + +// ---- Website and domain-registration watches ---- +group("monitor DO/web-posture + domain-expiry", () => { + const H = { "strict-transport-security": "max-age=31536000", "content-security-policy": "default-src 'self'; script-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'", "x-content-type-options": "nosniff" }; + const webNet = (headers) => { + const deliveries = []; + const fetch = async (url, opts = {}) => { + if (url === "https://example.com/") return { ok: true, status: 200, url, headers: new Headers(headers), body: null }; + if (url === "http://example.com/") return { ok: false, status: 301, url, headers: new Headers({ location: "https://example.com/" }), body: null }; + if (url.startsWith("https://example.com/.")) return { ok: false, status: 404, url, headers: new Headers(), body: null }; + deliveries.push({ url, body: opts.body }); return { ok: true, status: 200 }; + }; + return { fetch, deliveries }; + }; + test("a header that disappears after the baseline alerts as drift, below minSeverity", async () => { + const st = memState(); const mon = new MonitorDO(st); + await post(mon, { op: "upsert", monitor: { name: "Site", type: "web-posture", config: { domains: ["example.com"] }, channels: [{ type: "webhook", url: "https://hook.test/x" }] } }); + const a = webNet(H); + const r1 = await mon.runDue({ force: true, fetch: a.fetch, sleep: async () => {} }); + assert.equal(r1.ran[0].found, 0); + const { "x-content-type-options": _, ...less } = H; + const b = webNet(less); + await mon.runDue({ force: true, fetch: b.fetch, sleep: async () => {} }); + assert.equal(b.deliveries.length, 1, "nosniff (low) removed after the baseline alerts"); + assert.ok(b.deliveries[0].body.includes("X-Content-Type-Options")); + }); + test("a registration watch on a subdomain baselines the registrable domain", async () => { + const st = memState(); const mon = new MonitorDO(st); + await post(mon, { op: "upsert", monitor: { name: "Reg", type: "domain-expiry", config: { domains: ["www.example.com"] }, channels: [] } }); + const fetch = async (url) => url.includes("iana.org") ? { ok: true, status: 200, json: async () => ({ services: [[["com"], ["https://rdap.test/"]]] }) } + : { ok: true, status: 200, json: async () => ({ status: ["client transfer prohibited"], events: [{ eventAction: "expiration", eventDate: day(200) }] }) }; + await mon.runDue({ force: true, fetch, sleep: async () => {} }); + const m = Object.values(await st.storage.get("monitors"))[0]; + assert.deepEqual(m.baselined, ["example.com"]); + }); +}); diff --git a/test/worker/watch-checks.test.mjs b/test/worker/watch-checks.test.mjs new file mode 100644 index 00000000..e2115f0d --- /dev/null +++ b/test/worker/watch-checks.test.mjs @@ -0,0 +1,175 @@ +// Unit tests for the domain-registration (RDAP) and website watches in worker/checks.js, +// plus the alert copy worker/alert-email.js writes for them. +import { test, group, assert } from "../harness.mjs"; +import { rdapBase, gradeRdap, domainExpiryCheck, gradeWeb, webPostureCheck, looksLikeGitHead, looksLikeEnv, runCheck } from "../../worker/checks.js"; +import { explainEvent } from "../../worker/alert-email.js"; +import { FREE_WATCH, freeWatchDenied } from "../../worker/free-watch.js"; + +const NOW = Date.parse("2026-11-27T00:00:00Z"); +const day = (n) => new Date(NOW + n * 86400000).toISOString(); +const BOOT = { services: [[["com", "net"], ["https://rdap.verisign.example/com/v1/"]], [["uk", "co.uk"], ["http://insecure.example/", "https://rdap.nominet.example"]], [["de"], ["https://rdap.denic.example/"]]] }; +const rdap = (o = {}) => ({ objectClassName: "domain", status: o.status || ["client transfer prohibited"], events: o.exp === null ? [] : [{ eventAction: "expiration", eventDate: o.exp || day(300) }], + entities: [{ roles: ["registrar"], vcardArray: ["vcard", [["version", {}, "text", "4.0"], ["fn", {}, "text", "Example Registrar"]]] }] }); +const res = (status, body, headers = {}, url = "") => ({ + ok: status >= 200 && status < 300, status, url, + headers: new Headers(headers), + json: async () => body, text: async () => typeof body === "string" ? body : JSON.stringify(body), body: null, +}); + +group("checks/domain-expiry: pure grading", () => { + test("rdapBase takes the longest matching TLD and only https servers", () => { + assert.equal(rdapBase(BOOT, "example.com"), "https://rdap.verisign.example/com/v1/"); + assert.equal(rdapBase(BOOT, "shop.example.co.uk"), "https://rdap.nominet.example/"); + assert.equal(rdapBase(BOOT, "example.org"), ""); + assert.equal(rdapBase(null, "example.com"), ""); + }); + test("a healthy, locked registration gives no finding", () => { + assert.equal(gradeRdap("example.com", rdap(), { now: NOW }).findings.length, 0); + }); + test("expiry inside the window is high, the last week critical, past expiry critical", () => { + const at = (n) => gradeRdap("example.com", rdap({ exp: day(n) }), { now: NOW, warnDays: 30 }).findings[0]; + assert.equal(at(20).severity, "high"); + assert.equal(at(20).key, "domain:example.com:expiry"); + assert.ok(/expires in 20 days/.test(at(20).title)); + assert.equal(at(20).registrar, "Example Registrar"); + assert.equal(at(5).severity, "critical"); + assert.ok(/has expired/.test(at(-2).title)); + assert.equal(at(45), undefined); + }); + test("redemption period is critical whatever the date says", () => { + const f = gradeRdap("example.com", rdap({ status: ["redemption period", "client transfer prohibited"], exp: day(200) }), { now: NOW }).findings; + assert.equal(f[0].severity, "critical"); + assert.ok(/redemption period/.test(f[0].title)); + }); + test("an unregistered domain (RDAP 404) is critical", () => { + const f = gradeRdap("example.com", null, { now: NOW }).findings; + assert.equal(f.length, 1); + assert.ok(/is not registered/.test(f[0].title)); + }); + test("a pending transfer is high; an unlocked gTLD is medium; a ccTLD is not judged on the lock", () => { + const f = gradeRdap("example.com", rdap({ status: ["active", "pending transfer"] }), { now: NOW }).findings; + assert.deepEqual(f.map((x) => x.key + "=" + x.severity), ["domain:example.com:transfer=high", "domain:example.com:lock=medium"]); + assert.equal(gradeRdap("example.de", rdap({ status: ["active"] }), { now: NOW }).findings.length, 0); + assert.equal(gradeRdap("example.com", rdap({ status: ["server transfer prohibited"] }), { now: NOW }).findings.length, 0); + }); + test("no expiry event is unknown (held), not a finding", () => { + const g = gradeRdap("example.de", rdap({ exp: null }), { now: NOW }); + assert.equal(g.findings.length, 0); + assert.deepEqual(g.unknown[0].keys, ["domain:example.de:expiry"]); + }); +}); + +group("checks/domain-expiry: network", () => { + const fetcher = (map, log = []) => async (url) => { log.push(url); const v = map[url]; if (v instanceof Error) throw v; return v || res(500, null); }; + const bootUrl = "https://data.iana.org/rdap/dns.json"; + test("subdomains collapse to the registrable domain, looked up once", async () => { + const log = []; + const out = await domainExpiryCheck(["www.example.com", "https://api.example.com/x"], { now: NOW, fetch: fetcher({ [bootUrl]: res(200, BOOT), "https://rdap.verisign.example/com/v1/domain/example.com": res(200, rdap({ exp: day(10) })) }, log) }); + assert.equal(out.length, 1); + assert.deepEqual(out.checked, ["example.com"]); + assert.equal(log.filter((u) => /domain\/example\.com$/.test(u)).length, 1); + }); + test("a registry that does not answer holds the last state; no bootstrap is unreachable", async () => { + const out = await domainExpiryCheck(["example.com"], { now: NOW, fetch: fetcher({ [bootUrl]: res(200, BOOT), "https://rdap.verisign.example/com/v1/domain/example.com": new Error("timeout") }) }); + assert.ok(out.unreachable, "nothing answered"); + const out2 = await domainExpiryCheck(["example.com"], { now: NOW, fetch: fetcher({}) }); + assert.ok(out2.unreachable); + }); + test("a TLD without RDAP is reported as unknown, not unreachable", async () => { + const out = await domainExpiryCheck(["example.org", "example.com"], { now: NOW, fetch: fetcher({ [bootUrl]: res(200, BOOT), "https://rdap.verisign.example/com/v1/domain/example.com": res(200, rdap()) }) }); + assert.ok(!out.unreachable); + assert.equal(out.unknown[0].domain, "example.org"); + assert.ok(out.held.includes("domain:example.org:expiry")); + }); + test("runCheck dispatches domain-expiry with the monitor's warnDays", async () => { + const f = fetcher({ [bootUrl]: res(200, BOOT), "https://rdap.verisign.example/com/v1/domain/example.com": res(200, rdap({ exp: day(50) })) }); + assert.equal((await runCheck("domain-expiry", { domains: ["example.com"] }, { fetch: f, now: NOW })).length, 0); + assert.equal((await runCheck("domain-expiry", { domains: ["example.com"], warnDays: 60 }, { fetch: f, now: NOW })).length, 1); + }); +}); + +const GOOD = { + "strict-transport-security": "max-age=31536000; includeSubDomains", + "content-security-policy": "default-src 'self'; script-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'", + "x-content-type-options": "nosniff", +}; + +group("checks/web-posture: pure", () => { + test("file signatures: a real git HEAD and .env match, an HTML catch-all does not", () => { + assert.ok(looksLikeGitHead("ref: refs/heads/main\n")); + assert.ok(looksLikeGitHead("0123456789abcdef0123456789abcdef01234567")); + assert.ok(!looksLikeGitHead("")); + assert.ok(looksLikeEnv("# app\nDB_PASSWORD=x\nAPI_KEY=y\n", "text/plain")); + assert.ok(!looksLikeEnv("DB_PASSWORD=x\nAPI_KEY=y", "text/html")); + assert.ok(!looksLikeEnv("A=1\nB=2", "")); + assert.ok(!looksLikeEnv("ONLY=1", "text/plain"), "one line is not enough"); + }); + test("a well-configured site gives no finding", () => { + assert.equal(gradeWeb("example.com", { httpsOk: true, headers: GOOD, httpTested: true, httpRedirectsToHttps: true }).length, 0); + }); + test("missing headers and no redirect become keyed findings", () => { + const f = gradeWeb("example.com", { httpsOk: true, headers: {}, httpTested: true, httpRedirectsToHttps: false }); + const keys = f.map((x) => x.key.split(":").pop() + "=" + x.severity); + assert.deepEqual(keys.sort(), ["csp=medium", "frame=medium", "hsts=medium", "nosniff=low", "redirect=medium"]); + }); + test("no HTTPS answer: one HTTPS finding, no header findings", () => { + const f = gradeWeb("example.com", { httpsOk: false, headers: {}, httpTested: true, httpRedirectsToHttps: false }); + assert.deepEqual(f.map((x) => x.key).sort(), ["web:example.com:https", "web:example.com:redirect"]); + }); + test("an exposed .git and .env are critical and carry only the URL", () => { + const f = gradeWeb("example.com", { httpsOk: true, headers: GOOD, httpTested: true, httpRedirectsToHttps: true, git: "https://example.com/.git/HEAD", env: "https://example.com/.env" }); + assert.deepEqual(f.map((x) => x.severity), ["critical", "critical"]); + assert.equal(f[0].url, "https://example.com/.env"); + assert.ok(!JSON.stringify(f).includes("PASSWORD")); + }); +}); + +group("checks/web-posture: network", () => { + const site = (o = {}) => async (url, init = {}) => { + if (o.down) throw new Error("connect failed"); + if (url === "https://example.com/") return res(200, "", o.headers || GOOD, "https://example.com/"); + if (url === "http://example.com/") return o.noRedirect ? res(200, "") : res(301, "", { location: "https://example.com/" }); + if (url === "https://example.com/.git/HEAD") return o.git ? res(200, "ref: refs/heads/main\n", { "content-type": "text/plain" }) : res(200, "", { "content-type": "text/html" }); + if (url === "https://example.com/.env") return o.env ? res(200, "DB_PASSWORD=hunter2\nSECRET_KEY=abc\n", { "content-type": "application/octet-stream" }) : res(404, ""); + return res(404, ""); + }; + test("a good site: no findings, the host is checked", async () => { + const out = await webPostureCheck(["https://example.com/login"], { fetch: site() }); + assert.equal(out.length, 0); + assert.deepEqual(out.checked, ["example.com"]); + }); + test("an SPA catch-all serving HTML for /.git/HEAD is not an exposure", async () => { + assert.equal((await webPostureCheck(["example.com"], { fetch: site() })).filter((f) => /git/.test(f.key)).length, 0); + }); + test("exposed files and a missing redirect are found", async () => { + const out = await webPostureCheck(["example.com"], { fetch: site({ git: true, env: true, noRedirect: true }) }); + assert.deepEqual(out.map((f) => f.key.split(":").pop()).sort(), ["env", "git", "redirect"]); + assert.ok(!JSON.stringify(out).includes("hunter2"), "file contents are never kept"); + }); + test("a site that answers nothing is unreachable, so nothing reads as fixed", async () => { + assert.ok((await webPostureCheck(["example.com"], { fetch: site({ down: true }) })).unreachable); + }); + test("private and local hosts are never requested", async () => { + const log = []; + const out = await webPostureCheck(["localhost", "127.0.0.1", "10.0.0.5"], { fetch: async (u) => { log.push(u); return res(200, ""); } }); + assert.equal(log.length, 0); + assert.equal(out.length, 0); + }); +}); + +group("watch alerts and the Free watch", () => { + test("alert copy explains registration and website findings", () => { + const e = explainEvent({ key: "domain:example.com:expiry", title: "Registration for example.com expires in 9 days", domain: "example.com", daysToExpiry: 9, notAfter: day(9), registrar: "Example Registrar", severity: "high" }); + assert.ok(/Renew example\.com at your registrar \(Example Registrar\)/.test(e.fix)); + assert.ok(/anyone can register it/.test(e.why)); + const w = explainEvent({ key: "web:example.com:env", title: "The .env file of example.com is publicly readable", domain: "example.com", advice: "Rotate.", severity: "critical" }); + assert.ok(/database passwords/.test(w.why)); + assert.equal(w.fix, "Rotate."); + }); + test("the Free watch takes all four domain checks on its one domain", () => { + for (const t of ["domain-expiry", "web-posture"]) assert.ok(FREE_WATCH.types.includes(t)); + const mon = (type, d) => ({ id: type, type, config: { domains: [d] }, channels: [{ type: "email" }], intervalMs: 86400000 }); + assert.equal(freeWatchDenied(mon("web-posture", "example.com"), [mon("cert-expiry", "example.com")]), null); + assert.ok(freeWatchDenied(mon("domain-expiry", "example.org"), [mon("cert-expiry", "example.com")])); + }); +}); diff --git a/worker/alert-email.js b/worker/alert-email.js index 9a526861..e4cbb1a5 100644 --- a/worker/alert-email.js +++ b/worker/alert-email.js @@ -51,6 +51,37 @@ export function explainEvent(ev = {}) { return out(what, why, fix); } + const dm = /^domain:(.+):([a-z]+)$/.exec(key); + if (dm) { + const dom = d || dm[1], id = dm[2], n = Number(ev.daysToExpiry), at = ev.registrar ? "your registrar (" + clip(ev.registrar, 60) + ")" : "your registrar"; + const until = ev.notAfter && !isNaN(Date.parse(ev.notAfter)) ? new Date(ev.notAfter).toISOString().slice(0, 10) : ""; + if (id === "expiry") { + if (/is not registered/.test(ev.title || "")) return out(ev.title, `Anyone can register ${dom} now and receive its mail, serve its website and reset passwords sent to its addresses.`, ev.advice); + const why = `When a registration lapses, the website, the mail and every sign-in on ${dom} stop working, and after the grace period anyone can register it.`; + return out(ev.title, why, `Renew ${dom} at ${at}${until ? " (it is registered until " + until + ")" : ""}, and turn on auto-renew with a payment card that will still be valid.`); + } + if (id === "transfer") return out(ev.title, `A transfer moves ${dom} to another registrar account, which then controls its DNS, its mail and its website.`, ev.advice); + if (id === "lock") return out(ev.title, `Without the lock, anyone who gets into the registrar account, or tricks its support, can move ${dom} away in days.`, ev.advice); + return out(ev.title); + } + + const wm = /^web:(.+):([a-z]+)$/.exec(key); + if (wm) { + const host = d || wm[1], id = wm[2]; + const WHY = { + git: `Anyone can download the site's source code and its full history, including any password or key ever committed.`, + env: `The file usually holds database passwords, API keys and signing secrets, and anyone who requested it has them.`, + https: `Visitors to ${host} cannot reach it securely, so their sessions and logins can be read or changed on the way.`, + redirect: `Visitors who type ${host} without https:// stay on plain HTTP, where their traffic can be read or changed.`, + hsts: `Without HSTS a visitor's first request can be downgraded to plain HTTP by anyone on the same network.`, + csp: `Without a strong Content-Security-Policy, an injected script runs with full access to the page and its visitors' sessions.`, + frame: `Another site can load ${host} in a hidden frame and trick visitors into clicking its buttons (clickjacking).`, + nosniff: `Browsers may guess content types, so an uploaded file can run as a script on ${host}.`, + cookies: `Cookies without the right flags can be sent over plain HTTP or read by injected scripts.`, + }; + return out(ev.title, WHY[id] || "", ev.advice); + } + const em = /^email:(.+):([a-z-]+)$/.exec(key); if (em) { const dom = d || em[1], id = em[2], at = ev.recordAt || "_dmarc." + dom, was = ev.was || "", now = ev.now || ""; diff --git a/worker/checks.js b/worker/checks.js index a022f131..c654c21c 100644 --- a/worker/checks.js +++ b/worker/checks.js @@ -5,7 +5,8 @@ // Findings returned use the monitor shape monitor-core expects: // { key, severity, title, status, ...extra } // `key` is stable across runs so diffFindings can tell a new issue from a persisting one. -import { newestCert, certDaysLeft, gradeEmail, parseSPF, parseDMARC } from "../public/js/dataprotect/posture-engine.js"; +import { newestCert, certDaysLeft, gradeEmail, parseSPF, parseDMARC, gradeTransport, gradeHeaders } from "../public/js/dataprotect/posture-engine.js"; +import { hostAllowed } from "./net-guard.js"; import { registrableDomain } from "../public/js/dataprotect/phish-engine.js"; // Normalise SSLMate certspotter issuances into crt.sh-shaped rows (same mapping the @@ -321,6 +322,8 @@ export const CHECKS = { "cert-expiry": (cfg, deps) => certExpiryCheck((cfg && cfg.domains) || [], { ...deps, warnDays: (cfg && cfg.warnDays) || 21 }), "kev-epss": (cfg, deps) => kevEpssCheck(cfg || {}, deps), "email-posture": (cfg, deps) => emailPostureCheck((cfg && cfg.domains) || [], deps), + "domain-expiry": (cfg, deps) => domainExpiryCheck((cfg && cfg.domains) || [], { ...deps, warnDays: (cfg && cfg.warnDays) || 30 }), + "web-posture": (cfg, deps) => webPostureCheck((cfg && cfg.domains) || [], deps), }; export function runCheck(type, cfg, deps) { @@ -328,3 +331,201 @@ export function runCheck(type, cfg, deps) { if (!fn) return Promise.resolve([]); return fn(cfg, deps); } + +// ---- Domain registration watch (RDAP) --------------------------------------------------- +// A domain whose registration lapses takes the website, the mail and every login on it down +// at once, and can be bought by someone else. The registry's own RDAP record (RFC 9083) gives +// the expiry date and the EPP status codes; the IANA bootstrap file names each TLD's server. +const RDAP_BOOTSTRAP = "https://data.iana.org/rdap/dns.json"; +const timeout = (ms) => (typeof AbortSignal !== "undefined" && AbortSignal.timeout ? AbortSignal.timeout(ms) : undefined); + +// rdapBase(bootstrap, domain) -> the https RDAP base URL (ending in "/") for the domain's +// longest matching TLD entry, or "". PURE. +export function rdapBase(boot, domain) { + const d = String(domain || "").toLowerCase(); + let best = "", len = 0; + for (const svc of (boot && Array.isArray(boot.services) ? boot.services : [])) { + const tlds = Array.isArray(svc) && Array.isArray(svc[0]) ? svc[0] : [], urls = Array.isArray(svc) && Array.isArray(svc[1]) ? svc[1] : []; + const url = urls.find((u) => /^https:\/\//i.test(String(u))); + if (!url) continue; + for (const t of tlds) { + const tl = String(t).toLowerCase(); + if ((d === tl || d.endsWith("." + tl)) && tl.length > len) { best = url.endsWith("/") ? url : url + "/"; len = tl.length; } + } + } + return best; +} + +const ccTld = (d) => /^[a-z]{2}$/.test(String(d).split(".").pop()); + +// gradeRdap(domain, rdap, { now, warnDays }) -> { findings, unknown, expiresAt }. PURE. +// rdap: the registry's domain object, or null for a 404 (the domain is not registered). +// Healthy states yield no finding. The transfer-lock check runs for generic TLDs only: ICANN +// requires gTLD registries to publish EPP statuses, while many country-code registries have +// no registrar lock at all and would read as unlocked. +export function gradeRdap(domain, rdap, opts = {}) { + const now = opts.now || Date.now(), warnDays = opts.warnDays || 30; + const findings = [], unknown = []; + const k = (id) => "domain:" + domain + ":" + id; + const add = (id, severity, title, extra = {}) => findings.push({ key: k(id), severity, status: "open", title, domain, category: "domain", tool: "monitor:domain-expiry", ...extra }); + if (rdap === null) { + add("expiry", "critical", `${domain} is not registered`, { check: "Registration", advice: `Register ${domain} again at a registrar now, before someone else does.` }); + return { findings, unknown, expiresAt: null }; + } + const status = (Array.isArray(rdap && rdap.status) ? rdap.status : []).map((s) => String(s).toLowerCase()); + const ev = (Array.isArray(rdap && rdap.events) ? rdap.events : []).find((e) => e && /^expiration$/i.test(String(e.eventAction || ""))); + const at = ev && Date.parse(ev.eventDate); + const registrar = ((Array.isArray(rdap && rdap.entities) ? rdap.entities : []).find((e) => e && Array.isArray(e.roles) && e.roles.includes("registrar")) || {}); + const regName = (() => { const v = Array.isArray(registrar.vcardArray) ? registrar.vcardArray[1] : null; const fn = Array.isArray(v) && v.find((p) => Array.isArray(p) && p[0] === "fn"); return fn ? String(fn[3] || "") : ""; })(); + const extra = { check: "Registration", ...(regName ? { registrar: regName } : {}) }; + const lapsing = status.find((s) => s === "redemption period" || s === "pending delete" || s === "pending restore"); + if (Number.isFinite(at)) { + const days = Math.floor((at - now) / 86400000), iso = new Date(at).toISOString(); + const s = days < 0 || days <= 7 || lapsing ? "critical" : days <= warnDays ? "high" : null; + if (s) add("expiry", s, lapsing ? `${domain} is in ${lapsing}: its registration has lapsed` : days < 0 ? `Registration for ${domain} has expired` : `Registration for ${domain} expires in ${days} day${days === 1 ? "" : "s"}`, { ...extra, daysToExpiry: days, notAfter: iso }); + } else if (lapsing) add("expiry", "critical", `${domain} is in ${lapsing}: its registration has lapsed`, extra); + else unknown.push({ domain, check: "Registration", reason: "The registry does not publish an expiry date over RDAP.", keys: [k("expiry")] }); + if (status.includes("pending transfer")) add("transfer", "high", `A transfer of ${domain} to another registrar is pending`, { ...extra, check: "Transfer", advice: "If you did not start this transfer, reject it at your registrar today and change the registrar account password." }); + if (!ccTld(domain) && status.length && !status.some((s) => s === "client transfer prohibited" || s === "server transfer prohibited")) { + add("lock", "medium", `Transfer lock is off for ${domain}`, { ...extra, check: "Transfer lock", advice: "Turn on the registrar lock (clientTransferProhibited) at your registrar, so the domain cannot move to another registrar without you unlocking it." }); + } + return { findings, unknown, expiresAt: Number.isFinite(at) ? new Date(at).toISOString() : null }; +} + +// domainExpiryCheck(domains, deps) -> findings[] (+ .held, .unknown, .checked). deps: { fetch, now, warnDays }. +// Each watched hostname is graded by its registrable domain (www.shop.example.co.uk -> example.co.uk). +export async function domainExpiryCheck(domains, deps = {}) { + const f = deps.fetch || (typeof fetch !== "undefined" ? fetch : null); + if (!f) return []; + const regs = [...new Set((domains || []).map(hostOnly).filter(Boolean).map((h) => registrableDomain(h)))]; + if (!regs.length) return []; + let boot = null; + try { const r = await f(RDAP_BOOTSTRAP, { headers: { accept: "application/json" }, signal: timeout(10000) }); if (r && r.ok) boot = await r.json().catch(() => null); } catch (_) {} + if (!boot) return Object.assign([], { unreachable: true }); + const out = [], held = [], unknown = [], checked = []; + for (const dom of regs) { + const base = rdapBase(boot, dom); + const keys = ["expiry", "transfer", "lock"].map((id) => "domain:" + dom + ":" + id); + if (!base) { unknown.push({ domain: dom, check: "Registration", reason: "The ." + dom.split(".").pop() + " registry has no RDAP service.", keys }); held.push(...keys); continue; } + let rdap; + try { + const r = await f(base + "domain/" + encodeURIComponent(dom), { headers: { accept: "application/rdap+json, application/json" }, signal: timeout(10000) }); + rdap = r && r.status === 404 ? null : r && r.ok ? await r.json().catch(() => undefined) : undefined; + } catch (_) { rdap = undefined; } + if (rdap === undefined) { held.push(...keys); continue; } // no answer: keep the last state + checked.push(dom); + const g = gradeRdap(dom, rdap, { now: deps.now, warnDays: deps.warnDays }); + out.push(...g.findings); + for (const u of g.unknown) { unknown.push(u); held.push(...u.keys); } + } + if (!checked.length && !unknown.length) return Object.assign([], { unreachable: true }); + return Object.assign(out, { held, unknown, checked }); +} + +// ---- Website watch ------------------------------------------------------------------------ +// The security headers a site sends, whether plain HTTP still redirects to HTTPS, and whether +// the site serves its git repository or its .env file to anyone. Graded by the same posture +// engine as the browser Posture tool. A file probe reads at most 2 KB to recognise the file, +// and keeps nothing of it: a finding carries only the URL. +const WEB_WATCH = { + "HTTPS": { id: "https", fail: "high" }, + "HTTP to HTTPS redirect": { id: "redirect", fail: "medium" }, + "HSTS": { id: "hsts", fail: "medium", warn: "low" }, + "Content-Security-Policy": { id: "csp", fail: "medium", warn: "low" }, + "Clickjacking protection": { id: "frame", fail: "medium" }, + "X-Content-Type-Options": { id: "nosniff", fail: "low" }, + "Cookie security": { id: "cookies", fail: "medium", warn: "low" }, +}; +export const WEB_KEYS = [...Object.values(WEB_WATCH).map((w) => w.id), "git", "env"]; + +// Is this body (the first bytes) a real git HEAD / .env file, not an HTML catch-all page? PURE. +export const looksLikeGitHead = (t) => /^(ref: refs\/[\w./-]+|[0-9a-f]{40})\s*$/.test(String(t || "").trim().split("\n")[0] || ""); +export function looksLikeEnv(t, contentType = "") { + const s = String(t || ""); + if (/html|json|xml|javascript/i.test(contentType) || /^\s* l.trim() && !/^\s*#/.test(l)); + return lines.length >= 2 && lines.filter((l) => /^\s*(export\s+)?[A-Z][A-Z0-9_]*\s*=/.test(l)).length >= Math.max(2, Math.ceil(lines.length * 0.6)); +} + +// gradeWeb(host, probe) -> findings[]. PURE. probe: { httpsOk, headers, setCookie, httpTested, +// httpRedirectsToHttps, git, env } as webPostureCheck collects it. +export function gradeWeb(host, p = {}) { + const findings = []; + const add = (id, severity, title, extra = {}) => findings.push({ key: "web:" + host + ":" + id, severity, status: "open", title, domain: host, category: "website", tool: "monitor:web-posture", ...extra }); + const cats = [gradeTransport({ headers: p.headers || {}, httpsOk: !!p.httpsOk, httpTested: !!p.httpTested, httpRedirectsToHttps: !!p.httpRedirectsToHttps })]; + if (p.httpsOk) cats.push(gradeHeaders({ headers: p.headers || {}, setCookie: p.setCookie || [] })); + for (const c of cats.flatMap((x) => x.checks)) { + const w = WEB_WATCH[c.name]; + if (!w || (!p.httpsOk && c.name === "HSTS")) continue; // no HTTPS answer: there is no HSTS to grade + const s = w[c.status]; + if (s) add(w.id, s, `${c.name} on ${host}: ${c.detail}`, { check: c.name, detail: c.detail, advice: c.advice || "" }); + } + if (p.git) add("git", "critical", `The git repository of ${host} is publicly readable`, { check: "Exposed files", url: p.git, advice: `Block /.git/ on ${host} in the web server or CDN, then treat every secret ever committed to that repository as leaked and rotate it.` }); + if (p.env) add("env", "critical", `The .env file of ${host} is publicly readable`, { check: "Exposed files", url: p.env, advice: `Remove .env from the web root of ${host} or block it, then rotate every key, password and token it held.` }); + findings.sort((a, b) => a.key.localeCompare(b.key)); + return findings; +} + +async function readHead(r, max = 2048) { + try { + if (!r.body || !r.body.getReader) return (await r.text()).slice(0, max); + const rd = r.body.getReader(), dec = new TextDecoder(); + let s = ""; + while (s.length < max) { const { done, value } = await rd.read(); if (done) break; s += dec.decode(value, { stream: true }); } + rd.cancel().catch(() => {}); + return s.slice(0, max); + } catch (_) { return ""; } +} +const drop = (r) => { try { r && r.body && r.body.cancel && r.body.cancel().catch(() => {}); } catch (_) {} }; + +// webPostureCheck(domains, deps) -> findings[] (+ .held, .checked). deps: { fetch }. +export async function webPostureCheck(domains, deps = {}) { + const f = deps.fetch || (typeof fetch !== "undefined" ? fetch : null); + if (!f) return []; + const UA = { "user-agent": "DarknodeMonitor/1.0 (+https://darknode.ai)" }; + const out = [], held = [], checked = []; + let tried = false; + for (const raw of (domains || [])) { + const host = hostOnly(raw); + if (!host || !hostAllowed(new URL("https://" + host))) continue; + tried = true; + const p = { httpsOk: false, headers: {}, setCookie: [], httpTested: false, httpRedirectsToHttps: false, git: "", env: "" }; + try { + const r = await f("https://" + host + "/", { headers: UA, redirect: "follow", signal: timeout(12000) }); + if (/^https:/i.test(r.url || "https:")) { + p.httpsOk = true; + p.headers = Object.fromEntries(r.headers.entries()); + p.setCookie = typeof r.headers.getSetCookie === "function" ? r.headers.getSetCookie() : []; + } + drop(r); + } catch (_) {} + try { + let url = "http://" + host + "/"; + for (let hop = 0; hop < 4; hop++) { + const r = await f(url, { headers: UA, redirect: "manual", signal: timeout(12000) }); + drop(r); + p.httpTested = true; + const loc = r.status >= 300 && r.status < 400 ? r.headers.get("location") : ""; + if (!loc) break; + const next = new URL(loc, url); + if (next.protocol === "https:") { p.httpRedirectsToHttps = true; break; } + if (next.protocol !== "http:" || !hostAllowed(next)) break; + url = next.href; + } + } catch (_) {} + if (!p.httpsOk && !p.httpTested) { held.push(...WEB_KEYS.map((id) => "web:" + host + ":" + id)); continue; } + checked.push(host); + if (p.httpsOk) { + for (const [field, path, test] of [["git", "/.git/HEAD", (t) => looksLikeGitHead(t)], ["env", "/.env", (t, ct) => looksLikeEnv(t, ct)]]) { + try { + const r = await f("https://" + host + path, { headers: UA, redirect: "manual", signal: timeout(10000) }); + if (r.status === 200 && test(await readHead(r), r.headers.get("content-type") || "")) p[field] = "https://" + host + path; + else drop(r); + } catch (_) { held.push("web:" + host + ":" + field); } + } + } + out.push(...gradeWeb(host, p)); + } + if (tried && !checked.length) return Object.assign([], { unreachable: true }); + return Object.assign(out, { held, checked }); +} diff --git a/worker/free-watch.js b/worker/free-watch.js index 47cb2bfd..75409057 100644 --- a/worker/free-watch.js +++ b/worker/free-watch.js @@ -1,11 +1,11 @@ // Copyright (c) 2026 Darknode-Official. All rights reserved. See LICENSE. // // The Free plan's domain watch. Monitoring is a Pro feature (worker/plan.js FEATURE_PLAN.monitors), -// with one exception every account gets: watch ONE domain for certificate expiry and email/DNS -// changes, with alerts sent to the account's own email. The rules are PURE and enforced on the +// with one exception every account gets: watch ONE domain for certificate expiry, email/DNS changes, domain +// registration and website security, with alerts sent to the account's own email. The rules are PURE and enforced on the // server, inside the workspace's MonitorDO (so the domain count and the write are one step): // - only the personal workspace (handleMonitor refuses Free in a team workspace); -// - only the cert-expiry and email-posture check types; +// - only the cert-expiry, email-posture, domain-expiry and web-posture check types; // - one distinct domain across every monitor in the workspace, paused ones included; // - alerts by email only (Slack, Teams, Discord and webhooks stay Pro); // - checked at most once a day. @@ -13,7 +13,7 @@ import { hostOnly } from "./checks.js"; export const FREE_WATCH = Object.freeze({ - types: ["cert-expiry", "email-posture"], + types: ["cert-expiry", "email-posture", "domain-expiry", "web-posture"], domains: 1, channels: ["email"], minIntervalMs: 24 * 60 * 60 * 1000, @@ -37,7 +37,7 @@ const emailOnly = (m) => (m.channels || []).every((c) => c && c.type === "email" export function freeWatchDenied(next, others = []) { const type = String((next && next.type) || ""); if (!FREE_WATCH.types.includes(type)) { - return (TYPE_LABEL[type] || "This kind of") + " monitoring is part of the Pro plan. On the Free plan you can watch one domain for certificate expiry and email/DNS changes. Request an upgrade under Plans."; + return (TYPE_LABEL[type] || "This kind of") + " monitoring is part of the Pro plan. On the Free plan you can watch one domain for its certificate, email/DNS records, registration and website security. Request an upgrade under Plans."; } if (!emailOnly(next)) return "On the Free plan, alerts go to your account email. Slack, Teams, Discord and webhook alerts are part of the Pro plan."; const mine = monitorDomains(next); diff --git a/worker/monitor.js b/worker/monitor.js index 7d1820b9..226b4b84 100644 --- a/worker/monitor.js +++ b/worker/monitor.js @@ -10,6 +10,7 @@ // clocks) are kept here too, one storage key each ("dl:", CRA cases "cra:"), and // alerted when they start and when a quarter of their time is left (public/js/core/deadlines.js). import { runCheck, cvesFromEntities, hostOnly } from "./checks.js"; +import { registrableDomain } from "../public/js/dataprotect/phish-engine.js"; import { maybeWipe } from "./account-delete.js"; import { diffFindings, diffToEvents, shouldAlert, defaultAlertRules, inQuietHours } from "./monitor-core.js"; import { buildGraphWrite } from "./monitor-graph.js"; @@ -67,9 +68,18 @@ function saveChannels(given, prev, uid, email) { // An alerted event plus the finding fields the alert email explains (what changed, why it matters, // the fix). SPF and DMARC events also carry the record's state on the previous run and now. +// Watches whose domains get a baseline: once a domain answered a run, a new or worsened finding +// on it is drift (a record, header or registration got worse) and alerts regardless of severity. +const DRIFT_TYPES = ["email-posture", "web-posture", "domain-expiry"]; +const UNREACHABLE = { + "email-posture": "no DNS resolver answered; nothing changed this run", + "domain-expiry": "no registry answered over RDAP; nothing changed this run", + "web-posture": "no watched site answered over HTTP or HTTPS; nothing changed this run", +}; + function alertEvent(e, f = {}, before = {}, after = {}) { const out = { kind: e.kind, severity: e.severity, title: e.title, detail: e.detail, key: e.key }; - for (const k of ["domain", "check", "advice", "daysToExpiry", "notAfter", "issuer", "cve", "dueDate", "epss"]) if (f[k] != null && f[k] !== "") out[k] = f[k]; + for (const k of ["domain", "check", "advice", "daysToExpiry", "notAfter", "issuer", "registrar", "url", "cve", "dueDate", "epss"]) if (f[k] != null && f[k] !== "") out[k] = f[k]; const part = f.check === "SPF" ? "spf" : f.check === "DMARC" ? "dmarc" : ""; if (part && f.domain) { const was = (before[f.domain] || {})[part], now = (after[f.domain] || {})[part]; @@ -269,7 +279,7 @@ export class MonitorDO { try { if (m.type === "kev-epss" && extra.cves == null) throw new Error("could not read the workspace's CVE inventory; nothing changed this run"); findings = await runCheck(m.type, m.config || {}, { fetch: deps.fetch, now: t0, ...extra }); - if (findings && findings.unreachable) throw new Error(m.type === "email-posture" ? "no DNS resolver answered; nothing changed this run" : "a feed did not answer; nothing changed this run"); + if (findings && findings.unreachable) throw new Error(UNREACHABLE[m.type] || "a feed did not answer; nothing changed this run"); } catch (e) { await this._log("history", HISTORY_CAP, { id: m.id, at: t0, error: String(e.message || e) }); return { id: m.id, error: String(e.message || e) }; } @@ -301,7 +311,7 @@ export class MonitorDO { // once a domain has a baseline (a run where its records answered), any new or worsened // record on it is drift and alerts regardless of severity (onDrift). A domain's first // answered run, including one added to an existing monitor, obeys minSeverity. - else if (m.type === "email-posture" && real && (m.baselined || []).includes((findings.find((f) => f.key === ev.key) || {}).domain)) ev.kind = "drift"; + else if (DRIFT_TYPES.includes(m.type) && real && (m.baselined || []).includes((findings.find((f) => f.key === ev.key) || {}).domain)) ev.kind = "drift"; const d = shouldAlert(ev, rules, t0); if (d.alert) alerted.push(ev); else if (d.suppressed) held.push(ev); } @@ -350,7 +360,8 @@ export class MonitorDO { m.lastRunAt = t0; // a domain removed from the monitor loses its baseline, so re-adding it starts fresh if (checked) { - const watched = new Set(((m.config && m.config.domains) || []).map(hostOnly)); + // a domain-registration watch on www.shop.example.com checks (and baselines) example.com + const watched = new Set(((m.config && m.config.domains) || []).map(hostOnly).flatMap((h) => [h, registrableDomain(h)])); m.baselined = [...new Set([...(m.baselined || []), ...checked])].filter((d) => watched.has(d)); m.posture = Object.fromEntries(Object.entries({ ...postureBefore, ...postureNow }).filter(([d]) => watched.has(d))); }