diff --git a/public/css/domain-check.css b/public/css/domain-check.css
index 1d8afef9..b1da5000 100644
--- a/public/css/domain-check.css
+++ b/public/css/domain-check.css
@@ -113,4 +113,12 @@ html[data-style] body.landing .hero .dmc-linkbox{background:rgba(255,255,255,.06
.dk .dk-fr-saved{display:flex;flex-wrap:wrap;align-items:center;gap:8px 14px;margin-top:12px;font-size:13px;color:var(--dk-tx2,#56544f)}
.dk-fr-saved b{color:var(--dk-tx,#1d1c1a);font-weight:600}
.dk-fr-saved .dk-tibtn{height:32px}
+/* "Watch this domain" after a check: the Free plan's one-domain watch */
+.dk .dk-fr-watch{display:flex;flex-wrap:wrap;align-items:center;gap:10px 16px;margin-top:12px;padding-top:12px;border-top:1px solid var(--dk-line2,#efeee9);font-size:13px;line-height:1.5;color:var(--dk-tx2,#56544f)}
+.dk .dk-fr-watch[hidden]{display:none}
+.dk-fr-watch .dk-fr-wtx{flex:1 1 320px;min-width:0}
+.dk-fr-watch b{color:var(--dk-tx,#1d1c1a);font-weight:600}
+.dk-fr-watch .dk-fr-wbtns{display:flex;flex-wrap:wrap;gap:8px}
+.dk-fr-watch .dk-tibtn{height:32px}
+.dk-fr-watch.err .dk-fr-wtx{color:#b3261e}
@media (max-width:720px){.dk-fr .dk-actform input{flex:1 1 100%;width:auto}}
diff --git a/public/js/auth.js b/public/js/auth.js
index 94f934da..4520854b 100644
--- a/public/js/auth.js
+++ b/public/js/auth.js
@@ -3003,7 +3003,7 @@ onAuthStateChanged(auth, async (user) => {
const udoc = await getDoc(doc(db, "users", user.uid)).catch(() => null);
// Terms are versioned: bumping TOS_VERSION asks every account to accept the new text,
// including accounts that accepted an earlier version (they also see what changed).
- const TOS_VERSION = "2026-11-07";
+ const TOS_VERSION = "2026-11-25";
const ud = udoc && udoc.exists() ? udoc.data() : {};
const tosAccepted = !!ud.tosAccepted && ud.tosVersion === TOS_VERSION;
const tosReturning = !!ud.tosAccepted && !tosAccepted;
@@ -3014,9 +3014,9 @@ onAuthStateChanged(auth, async (user) => {
${tosReturning ? "We updated our Terms of Service" : "Terms of Service"}
${tosReturning ? "Please review the changes and accept to keep using Darknode." : "Please read and accept before continuing."}
${tosReturning ? `
- What changed (November 7, 2026)
+ What changed (November 25, 2026)
-
When you are signed in to the Nexus terminal agent or the desktop app, it now tells us about every 6 hours that your account uses it, with the app version and operating system. The desktop app also reports how many virtual machines it holds and when one last started, never their names, disks or contents. Turn it off with /shareusage off in Nexus or Settings > Share app usage in the app (Section 14).
+
The Free plan can now watch one domain. If you set up a monitor or the domain watch, we store the domains it watches and its latest results, and send email alerts only to your verified account email through our email provider, Resend. Turn it off under Monitors or with the stop link in any alert email (Section 14).
` : ""}
${TOS_HTML}
diff --git a/public/js/check/first-run.js b/public/js/check/first-run.js
index 2903f38a..3c78ef75 100644
--- a/public/js/check/first-run.js
+++ b/public/js/check/first-run.js
@@ -10,6 +10,11 @@
// Deck" (localStorage dn_first_domain, cleared once it has run), or the user. The sign-up
// email's domain is only offered as a one-click chip, never typed into the field, and
// 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
+// 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).
import { runDomainCheck, normalizeDomain, workDomainFromEmail, domainCheckFindings, domainCheckHeld, runLevel } from "/js/check/domain-check.js?v=1";
import { renderResult, renderPending, escapeHtml as esc } from "/js/check/check-view.js?v=1";
@@ -28,7 +33,7 @@ const isTestIdentity = (u) => !!(u && (u.isAnonymous || u.email === "test@darkno
|| (u.providerData || []).some((p) => p && p.providerId === "test")));
// Survives overview re-renders for this page load: the block is redrawn into each new slot.
-const S = { domain: "", res: null, running: false, saved: null, error: "", seq: 0, slot: null, ctx: null };
+const S = { domain: "", res: null, running: false, saved: null, error: "", seq: 0, slot: null, ctx: null, watch: null };
function toolLabel(id) {
const c = S.ctx;
@@ -50,6 +55,71 @@ function paint() {
} else { out.hidden = true; out.innerHTML = ""; }
saved.hidden = !S.saved;
if (S.saved) saved.innerHTML = savedHtml(S.saved);
+ const watch = slot.querySelector(".dk-fr-watch");
+ const showWatch = !!(S.res && S.res.checks && S.res.checks.length && !S.running);
+ watch.hidden = !showWatch;
+ watch.classList.toggle("err", !!(showWatch && S.watch && S.watch.domain === S.res.domain && S.watch.state === "error"));
+ if (showWatch) watch.innerHTML = watchHtml();
+}
+
+// ---- "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) => ``;
+
+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" : ""}.
+ `;
+ }
+ 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.`;
+ return `
${head} ${body}
${goBtn("monitors", "Open Monitors")}
`;
+ }
+ if (w.state === "conflict") {
+ return `
Your Free plan already watches ${esc(w.other)}. The Free plan watches one domain. To watch ${esc(d)} instead, delete the watch on ${esc(w.other)} under Monitors, or request an upgrade under Plans.
+
${goBtn("monitors", "Open Monitors")}${goBtn("plans", "See Plans")}
`;
+ }
+ return `
${esc(w.msg)}
${w.plan ? goBtn("plans", "See Plans") : ''}
`;
+}
+
+async function watchDomain() {
+ const domain = S.res && S.res.domain;
+ if (!domain || S.running || (S.watch && S.watch.domain === domain && S.watch.state === "busy")) return;
+ const free = isFree();
+ const set = (w) => { if (S.res && S.res.domain === domain) { S.watch = { domain, ...w }; paint(); } };
+ set({ state: "busy" });
+ try {
+ const { monitorApi } = 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 || [];
+ if (free) {
+ const other = [...new Set(mons.flatMap(hostsOf))].filter((h) => h !== domain);
+ if (other.length) return set({ state: "conflict", other: other[0] });
+ }
+ const mine = mons.filter((m) => WATCH_TYPES.includes(m.type) && hostsOf(m).includes(domain));
+ 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);
+ if (r && r.monitor) made.push(r.monitor);
+ }
+ const all = mine.concat(made);
+ const mail = all.flatMap((m) => m.channels || []).find((c) => c.type === "email" && c.mine && c.to);
+ set({ state: "on", already: !made.length, paused: all.some((m) => m.paused), to: mail ? mail.to : "", emailAll: all.every((m) => (m.channels || []).some((c) => c.type === "email")) });
+ } catch (e) {
+ const msg = (e && e.message) || "The watch could not be set up. Try again.";
+ set({ state: "error", plan: !!(e && e.plan), msg: !(e && e.status) && /^Sign in/.test(msg) ? "Sign in with your own account to watch a domain. Alerts go to its verified email address." : msg });
+ }
}
function savedHtml(sv) {
@@ -103,7 +173,7 @@ async function run(raw) {
/**
* Draw the block into `slot` (an empty element at the top of the overview).
- * ctx = { user, pending, isLocked(key), toolName(id), openTool(id), go(scene), onSaved() }
+ * ctx = { user, tier, pending, isLocked(key), toolName(id), openTool(id), go(scene), onSaved() }
*/
export function mountFirstRun(slot, ctx) {
S.slot = slot; S.ctx = ctx;
@@ -116,6 +186,7 @@ export function mountFirstRun(slot, ctx) {
+
`;
const form = slot.querySelector(".dk-fr-form"), input = form.querySelector("input");
form.addEventListener("submit", (e) => { e.preventDefault(); if (!S.running) { run(input.value); input.value = ""; } });
@@ -124,8 +195,9 @@ export function mountFirstRun(slot, ctx) {
if (!t || !slot.contains(t)) return;
if (t.dataset.frDomain && !S.running) run(t.dataset.frDomain);
else if (t.dataset.dmcTool && S.ctx.openTool) S.ctx.openTool(t.dataset.dmcTool);
- else if (t.dataset.frGo === "findings" && S.ctx.go) S.ctx.go("findings");
+ else if (t.dataset.frWatch) watchDomain();
else if (t.dataset.frGo === "secgraph" && S.ctx.openTool) S.ctx.openTool("secgraph");
+ else if (t.dataset.frGo && S.ctx.go) S.ctx.go(t.dataset.frGo);
});
paint();
// a /check/ link or the landing's hand-off runs at once; the hand-off key is
diff --git a/public/js/core/entitlements.js b/public/js/core/entitlements.js
index fe14c4ec..ea0849f1 100644
--- a/public/js/core/entitlements.js
+++ b/public/js/core/entitlements.js
@@ -17,6 +17,7 @@ export const FEATURES = {
cloudSync: "pro", // findings/reports synced across devices
unlimitedReports: "pro", // unlimited saved findings & reports
priorityAI: "pro", // premium AI models (worker/plan.js enforces them)
+ monitors: "pro", // monitors beyond the Free one-domain watch: more domains, KEV/EPSS, chat and webhook alerts
teamWorkspaces: "team", // shared workspaces & roles
vaultServerEnforced: "team", // server-enforced VAULT approvals & audit
integrations: "team", // SIEM / ticketing / chat connectors
@@ -30,6 +31,9 @@ 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
+ // 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 },
};
// Normalise any input into a known tier string.
@@ -85,9 +89,11 @@ export function limit(tier, key) {
// entries. Shared by the Deck sidebar and the AI tool catalog (js/api/catalog.js), so a
// tool an AI can run through the MCP server needs the same plan it needs in the Deck.
export const PLAN_GROUP = { exposure: "pro", code: "pro", identity: "team", detect: "team", finsec: "team", risk: "enterprise", compliance: "enterprise" };
-export const PLAN_ITEM = { enterprise: "team", findings: "pro", inventory: "pro", reports: "pro", activity: "pro", monitors: "pro", phishtriage: "pro", dlp: "pro", leakprobe: "pro", team: "team",
+export const PLAN_ITEM = { enterprise: "team", findings: "pro", inventory: "pro", reports: "pro", activity: "pro", phishtriage: "pro", dlp: "pro", leakprobe: "pro", team: "team",
// Free on every plan: the public vulnerability feed and the local-only graph and case files.
- threat: "free", secgraph: "free", investigation: "free" };
+ threat: "free", secgraph: "free", investigation: "free",
+ // Free: the one-domain watch (Pro adds more monitors; the server enforces both)
+ monitors: "free" };
export const tierFor = (id, group) => (own(PLAN_ITEM, id) && PLAN_ITEM[id]) || (own(PLAN_GROUP, group) && PLAN_GROUP[group]) || "free";
export const planLabel = (tier) => PLAN_LABEL[normTier(tier)] || "Free";
diff --git a/public/js/deck-ui.js b/public/js/deck-ui.js
index 3c3fe538..4e3b2040 100644
--- a/public/js/deck-ui.js
+++ b/public/js/deck-ui.js
@@ -3284,7 +3284,7 @@ export function renderDeck(host, opts) {
if (!frSlot.isConnected) return;
frMod = m;
const pending = frPending; frPending = "";
- m.mountFirstRun(frSlot, { user, pending, isLocked, toolName: (id) => secLabel[id] || "", openTool: (id) => openTool(id, secLabel[id] || id), go, onSaved: refreshGraphScene });
+ m.mountFirstRun(frSlot, { user, tier: planTier, pending, isLocked, toolName: (id) => secLabel[id] || "", openTool: (id) => openTool(id, secLabel[id] || id), go, onSaved: refreshGraphScene });
};
if (frMod) mountFr(frMod);
else import("/js/check/first-run.js?v=1").then(mountFr).catch(() => frSlot.remove());
@@ -4102,7 +4102,7 @@ export function renderDeck(host, opts) {
function repaintCorrelations(g){ corrMod().then((m) => m.repaintCorrelations(g), () => {}); }
function renderInventory(){ lazyScene(sceneEls.inventory, invMod, (m) => m.mountInventory(sceneEls.inventory, { withGraph, esc, IC, IC_SEARCH, openEntityDrawer, openTool, agoISO: agoISO, toast })); }
function renderCorrelations(){ lazyScene(sceneEls.correlations, corrMod, (m) => m.mountCorrelations(sceneEls.correlations, { withGraph, esc, IC, IC_SEARCH, openEntityDrawer, openTool, toast })); }
- function renderMonitors(){ lazyScene(sceneEls.monitors, monMod, (m) => m.mountMonitors(sceneEls.monitors, { esc, IC, toast })); }
+ function renderMonitors(){ lazyScene(sceneEls.monitors, monMod, (m) => m.mountMonitors(sceneEls.monitors, { esc, IC, toast, tier: planTier, go })); }
function renderApiKeys(){ lazyScene(sceneEls.apikeys, keysMod, (m) => m.mountApiKeys(sceneEls.apikeys, { esc, IC, toast })); }
function renderAudit(){ lazyScene(sceneEls.audit, auditMod, (m) => m.mountAudit(sceneEls.audit, { esc, IC, toast })); }
function renderDevice(){ lazyScene(sceneEls.device, deviceMod, (m) => m.mountDevice(sceneEls.device, { esc, IC, toast, askAI })); }
@@ -4209,11 +4209,11 @@ 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", "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 expiry and email/DNS 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.",
- feats: ["Everything in Free", "Exposure and Application Security tools, findings and reports", "Unlimited saved findings & reports", "Premium AI models: Claude Fable 5.1, Claude Opus 5.5, Darknode Max", "500 AI messages a day (150 on Claude)", "Cloud sync across devices", "Email support"],
+ feats: ["Everything in Free", "Exposure and Application Security tools, findings and reports", "Unlimited saved findings & reports", "Premium AI models: Claude Fable 5.1, Claude Opus 5.5, Darknode Max", "500 AI messages a day (150 on Claude)", "Cloud sync across devices", "Monitors for more domains and known-exploited CVEs, with Slack, Teams and webhook alerts", "Email support"],
cta: "Upgrade to Pro" },
{ id: "team", name: "Team", price: "$79", unit: "per user / month", tag: "", a: "#2552c6",
blurb: "Shared workspaces, roles and one audit trail for the whole team.",
diff --git a/public/js/deck/monitor-client.js b/public/js/deck/monitor-client.js
index dee602bd..8f854906 100644
--- a/public/js/deck/monitor-client.js
+++ b/public/js/deck/monitor-client.js
@@ -7,21 +7,24 @@ const proxyBase = () => { try { return String(window.DARKNODE_PROXY_URL || "").r
export function monitoringAvailable() { return !!proxyBase(); }
-// monitorApi(body) -> parsed JSON. Throws a readable Error on any non-2xx (the scene
-// shows 503 "not configured on this deployment" verbatim, so a pre-deploy Deck is honest).
-export async function monitorApi(body) {
+// monitorApi(body, { personal }) -> parsed JSON. Throws a readable Error on any non-2xx (the
+// scene shows 503 "not configured on this deployment" verbatim, so a pre-deploy Deck is honest);
+// the Error carries .status, and .plan when the plan does not include the request (402).
+// personal: send to the caller's own workspace (where the Free plan's one-domain watch lives)
+// whatever workspace is active.
+export async function monitorApi(body, opts = {}) {
const base = proxyBase();
if (!base) throw new Error("Monitoring needs the cloud proxy, which this build has not configured.");
const { auth } = await import("/js/firebase.js?v=20261021a");
const user = (auth && auth.currentUser) || null;
if (!user) throw new Error("Sign in to use monitors.");
- const wid = activeWorkspaceId() || user.uid;
+ const wid = (opts.personal ? "" : activeWorkspaceId()) || user.uid;
const r = await fetch(base + "/api/monitor/" + encodeURIComponent(wid), {
method: "POST",
headers: { Authorization: "Bearer " + (await user.getIdToken()), "Content-Type": "application/json" },
body: JSON.stringify(body || { op: "list" }),
});
let j = {}; try { j = await r.json(); } catch (_) {}
- if (!r.ok) throw new Error(j.error || ("Monitor request failed (" + r.status + ")"));
+ if (!r.ok) throw Object.assign(new Error(j.error || ("Monitor request failed (" + r.status + ")")), { status: r.status, plan: j.plan === true });
return j;
}
diff --git a/public/js/deck/monitors.js b/public/js/deck/monitors.js
index 0222572a..c59aae3a 100644
--- a/public/js/deck/monitors.js
+++ b/public/js/deck/monitors.js
@@ -3,7 +3,12 @@
// webhook. Talks to the MonitorDO through deck/monitor-client.js. The first check type is
// certificate expiry (real CT-log lookups graded by the posture engine); more are added
// server-side as worker-safe engines are extracted.
-import { monitorApi, monitoringAvailable } from "./monitor-client.js";
+//
+// 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
+// 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";
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])));
@@ -11,7 +16,24 @@ const toast = (m, t) => { try { S.ctx && S.ctx.toast && S.ctx.toast(m, t); } cat
const ago = (ts) => { if (!ts) return "never"; const s = Math.floor((Date.now() - ts) / 1000); if (s < 60) return s + "s ago"; if (s < 3600) return Math.floor(s / 60) + "m ago"; if (s < 86400) return Math.floor(s / 3600) + "h ago"; return Math.floor(s / 86400) + "d ago"; };
// 1440 minutes reads as "1d", 90 as "90m"
export const every = (ms) => { const m = Math.round((ms || 0) / 60000); return m && m % 1440 === 0 ? m / 1440 + "d" : m && m % 60 === 0 ? m / 60 + "h" : m + "m"; };
-const CHANNELS =[["slack", "Slack"], ["teams", "Microsoft Teams"], ["discord", "Discord"], ["webhook", "Signed webhook"]];
+const CHANNELS =[["email", "Email (your account address)"], ["slack", "Slack"], ["teams", "Microsoft Teams"], ["discord", "Discord"], ["webhook", "Signed webhook"]];
+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) {
+ const fits = mons.filter((m) => WATCH_TYPES.includes(m.type) && ((m.config && m.config.domains) || []).length === 1 && (m.channels || []).every((c) => c.type === "email"))
+ .sort((a, b) => (a.createdAt || 0) - (b.createdAt || 0) || String(a.id).localeCompare(String(b.id)));
+ if (!fits.length) return null;
+ 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 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(", ");
function injectStyle() {
if (document.getElementById("mon-css")) return;
@@ -36,12 +58,16 @@ function injectStyle() {
.mon-field .hint{font-size:11.5px;color:#5a6680;margin:3px 0 0}
.mon-field input,.mon-field textarea,.mon-field select{width:100%;font:inherit;font-size:13px;border:1px solid rgba(23,33,56,.18);border-radius:7px;padding:7px 9px;box-sizing:border-box}
.mon-field textarea{min-height:52px;resize:vertical}
-.mon-chrow{display:flex;gap:8px}.mon-chrow select{flex:0 0 150px}.mon-chrow input{flex:1}
+.mon-chrow{display:flex;gap:8px;flex-wrap:wrap}.mon-chrow select{flex:0 1 240px}.mon-chrow input{flex:1 1 200px}
.mon-panel{margin:18px 0 0}
.mon-panel h2{font-size:14px;margin:0 0 8px}
.mon-log{font-size:12px;color:#45506a;border-top:1px dashed rgba(23,33,56,.1);padding:5px 0}
.mon-log b{color:#141c2e;font-weight:650}
.mon-off{font-size:12.5px;color:#7a4a00;background:rgba(245,146,11,.1);border-radius:8px;padding:11px 13px;line-height:1.5}
+.mon-watch{display:flex;align-items:center;gap:10px 16px;flex-wrap:wrap;border:1px solid rgba(23,33,56,.12);border-radius:10px;padding:12px 14px;margin:0 0 14px;font-size:12.5px;line-height:1.55;color:#45506a}
+.mon-watch b{color:#141c2e;font-weight:650}
+.mon-watch .tx{flex:1 1 320px;min-width:0}
+.mon-watch .mon-actions{margin-left:0}
`;
document.head.appendChild(st);
}
@@ -50,7 +76,7 @@ export function mountMonitors(el, ctx) {
injectStyle();
S.ctx = ctx || S.ctx; S.el = el; S.adding = false;
el.innerHTML = `
-
Monitors
Scheduled security checks that run on the server and keep running when the Deck is closed. Only real changes raise an alert, routed to Slack, Teams, Discord or a signed webhook.
+
Monitors
Scheduled security checks that run on the server and keep running when the Deck is closed. Only real changes raise an alert, ${isFree() ? "sent by email to your account address" : "sent to your account email, Slack, Teams, Discord or a signed webhook"}.
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.
+
`;
+
box.innerHTML = `
-
${mons.length.toLocaleString()} monitor${mons.length === 1 ? "" : "s"}. Monitors run on the server's own schedule; alerts fire only when something changes.
-
+ ${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." : ""}
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.
`
+ ? `
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.
`
- : `
Hostnames to watch, e.g. test.darknode.ai. Certificate transparency logs are checked; nothing is sent to the domains.
+ : `
Hostnames to watch, e.g. test.darknode.ai. Certificate transparency logs are checked; nothing is sent to the domains.${one}
`;
+ // Free: email alerts only. Above Free a monitor may also have no channel (listed in the Deck only), as before.
+ const chans = free ? CHANNELS.slice(0, 1) : CHANNELS.concat([["none", "None (Deck only)"]]);
+ 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"}
${specific}
-
-
-
-
Optional. For a signed webhook you can add a shared secret below; Slack/Teams/Discord use their own incoming-webhook URL.
+
${free ? '
The Free plan checks once a day (1440 minutes).
' : ""}
+
+
+
${EMAIL_HINT}
-
+
`;
const $ = (s) => slot.querySelector(s);
$("#mfCancel").onclick = () => { S.adding = false; renderForm(); };
$("#mfSave").onclick = () => saveMonitor(slot);
$("#mfTest").onclick = () => testChannel(slot);
+ // the URL and the signing secret only apply to a webhook channel
+ $("#mfChType").onchange = () => {
+ const t = $("#mfChType").value, hook = t !== "email" && t !== "none";
+ $("#mfChUrl").hidden = !hook; $("#mfSecretRow").hidden = t !== "webhook";
+ $("#mfChHint").textContent = t === "email" ? EMAIL_HINT : t === "none" ? "No alerts are sent; runs and changes are listed on this page." : HOOK_HINT;
+ $("#mfTest").hidden = t === "none";
+ };
}
export function hostOf(x) {
@@ -159,8 +211,9 @@ function readForm(slot) {
const chUrl = ($("#mfChUrl").value || "").trim();
const chType = $("#mfChType").value;
const chSecret = ($("#mfChSecret").value || "").trim();
- const channels = chUrl ? [{ type: chType, url: chUrl, ...(chType === "webhook" && chSecret ? { secret: chSecret } : {}) }] : [];
- const intervalMs = Math.max(15, Math.min(10080, Number($("#mfInt").value) || 1440)) * 60000;
+ // an email channel carries no address: the Worker uses the signed-in account's verified one
+ const channels = chType === "email" ? [{ type: "email" }] : chType === "none" ? [] : [{ type: chType, url: chUrl, ...(chType === "webhook" && chSecret ? { secret: chSecret } : {}) }];
+ const intervalMs = Math.max(isFree() ? 1440 : 15, Math.min(10080, Number($("#mfInt").value) || 1440)) * 60000;
if (S.kind === "kev-epss") {
// an empty field is Number("") = 0, which would alert on every CVE with any EPSS score
const floorEl = $("#mfEpss"), floorTxt = floorEl ? floorEl.value.trim() : "", floorRaw = floorTxt ? Number(floorTxt) : NaN;
@@ -189,6 +242,8 @@ async function saveMonitor(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 (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;
try { await monitorApi({ op: "upsert", monitor: mon }); toast("Monitor saved.", "ok"); S.adding = false; await load(); }
catch (e) { toast(e.message || "Could not save.", "error"); }
@@ -197,12 +252,30 @@ async function saveMonitor(slot) {
async function testChannel(slot) {
const mon = readForm(slot);
- if (!mon.channels.length) { toast("Add a channel URL to test.", "warn"); return; }
+ if (!mon.channels.length || (mon.channels[0].type !== "email" && !mon.channels[0].url)) { toast("Add a channel URL to test.", "warn"); return; }
const deckUrl = location.origin + location.pathname + "#monitors";
- try { const r = await monitorApi({ op: "test", channel: mon.channels[0], deckUrl }); toast(r.ok ? "Test alert sent." : "Delivery failed" + (r.error ? ": " + r.error : r.status ? " (HTTP " + r.status + ")" : "") + ". Check the URL.", r.ok ? "ok" : "error"); }
+ const mail = mon.channels[0].type === "email";
+ try {
+ const r = await monitorApi({ op: "test", channel: mon.channels[0], deckUrl });
+ toast(r.ok ? (mail ? "Test email sent to " + (r.to || "your account address") + "." : "Test alert sent.")
+ : "Delivery failed" + (r.error ? ": " + r.error : r.status ? " (HTTP " + r.status + ")" : "") + (mail ? "" : ". Check the URL."), r.ok ? "ok" : "error");
+ if (mail) load(); // the delivery log shows the attempt
+ }
catch (e) { toast(e.message || "Test failed.", "error"); }
}
+// Turn the Free watch off or on: pause or resume every monitor in it.
+async function toggleWatch(fw) {
+ if (!fw || S.busy) return;
+ const paused = !fw.paused;
+ S.busy = true;
+ try {
+ for (const m of fw.list) if (!!m.paused !== paused) await monitorApi({ op: "pause", id: m.id, paused });
+ toast(paused ? "Watch on " + fw.domain + " turned off. No alerts are sent until you turn it on." : "Watch on " + fw.domain + " turned on.", "ok");
+ } catch (e) { toast(e.message || "Could not update the watch.", "error"); }
+ finally { S.busy = false; await load(); }
+}
+
async function act_run(id) {
toast("Running monitor…");
try { await monitorApi({ op: "run", id, deckUrl: location.origin + location.pathname + "#monitors" }); await load(); toast("Run complete.", "ok"); }
diff --git a/public/js/docs.js b/public/js/docs.js
index 7d396d84..13ad5574 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, 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."],
+ ["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, 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."],
["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."],
@@ -120,7 +120,8 @@ node darknode.js nexus init # optional: scaffold .nexus/ project
Where did the console go?
The Darknode Deck is the workspace after you sign in, and every tool opens inside it: use the sidebar or Ctrl K search. The older console view has been retired for users; a link to a tool (darknode.ai/<tool>) opens that tool in the Deck.
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?
Fourteen checks worth 100 points in total, read live from public DNS and HTTP responses: email authentication (SPF 10, DMARC policy 12, DKIM 6, mail servers 4), HTTPS (HTTPS 12, HTTP to HTTPS redirect 8), security headers (HSTS 8, Content-Security-Policy 8, frame protection 5, X-Content-Type-Options 4, Referrer-Policy 3), 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; continuous monitoring is a separate Pro feature.
+ What does the free domain check on the home page look at?
Fourteen checks worth 100 points in total, read live from public DNS and HTTP responses: email authentication (SPF 10, DMARC policy 12, DKIM 6, mail servers 4), HTTPS (HTTPS 12, HTTP to HTTPS redirect 8), security headers (HSTS 8, Content-Security-Policy 8, frame protection 5, X-Content-Type-Options 4, Referrer-Policy 3), 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. 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.
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.
How is Nexus different from Claude Code?
Nexus is not a replacement: its Claude engine drives your Claude Code. It puts Claude Code and five other engines (Gemini, Codex, OpenCode, Aider, local Ollama) behind one set of over 140 commands, and adds lossless cost savers, exact per-turn cost, git checkpoints and a destructive-command check to each of them.
Web Deck. If you sign in, we store your account identifier and preferences to provide the service. We do not sell personal data.
Feedback. Feedback you submit is stored to improve the product and is readable only by you and the maintainers.
Retention & deletion. You may request deletion of your account data at any time via Settings or by contacting the maintainers.
-
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. Live checks against a domain you enter are fetched through our edge proxy and are not stored.
+
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.
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.
Product usage. Signed in to Nexus or the desktop app, it tells us about every 6 hours that your account uses it, with the app version and operating system; the desktop app also sends how many virtual machines it holds and when one last started, never their names, disks or contents. Turn it off with /shareusage off in Nexus or Settings > Share app usage in the app. Signed out, nothing is sent.
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
diff --git a/public/js/legal.js b/public/js/legal.js
index a45ad2ad..60b14ed7 100644
--- a/public/js/legal.js
+++ b/public/js/legal.js
@@ -4,7 +4,7 @@
// whenever this text changes, so every account is asked to accept the new version.
export const TOS_HTML = `
Darknode Terms of Service
-
Last updated: October 31, 2026
+
Last updated: November 25, 2026
By using Darknode ("the Platform"), including darknode.ai, the Darknode command center, the Darknode Deck and its Personal and Organization spaces, the code, cloud, dependency and web-exposure analysis engines, the Darknode CLI, the Nexus agent, Darknode OS, the API and MCP server, and all associated tools, you (and, where you act for an organization, that organization) agree to these terms. If you do not agree, do not use the Platform.
1. Authorized Use Only
@@ -77,6 +77,7 @@ export const TOS_HTML = `
Data retention: your data is retained while your account is active. After deletion, data is purged within 30 days, except where retention is required by law.
Integration relay: Deck integrations with providers that do not accept calls from a browser (such as VirusTotal, Shodan or AbuseIPDB) send your API key and the value you look up through Darknode's edge relay to that provider only. The relay uses the key for that one request and does not log or store the key, the value or the result; the provider processes them under its own terms. Keys stay in your browser, under your account.
Weekly email digest (optional): only if you turn it on, we store your watched domains and latest certificate-check results to build a weekly email, sent to your account email through our email provider (Resend). You can turn it off at any time in Settings or from the unsubscribe link.
+
Monitors and domain watch (optional): only if you set up a monitor, including the Free plan's one-domain watch, we store the domains it watches, its settings and latest results, and a log of its runs and alert deliveries, so it can run on a schedule and report what changed. Email alerts are sent only to your own verified account email, through our email provider (Resend), at most 5 a day. You can turn a watch off under Monitors or from the stop link in any alert email.
Product usage: when you are signed in to the Nexus terminal agent or the Darknode desktop app, it tells us about every 6 hours that your account uses it, with the app version and operating system; the desktop app also reports how many virtual machines its VM manager holds and when one last started (never their names, disks or contents). We use this to know which products and versions to support. Turn it off with /shareusage off in Nexus or Settings > Share app usage in the desktop app.
No selling or sharing: we do not sell, rent, or share your personal data with third parties for marketing purposes.
Cookies: we use only essential cookies and localStorage for session management and user preferences. We do not use tracking cookies or third-party analytics.
diff --git a/public/js/ui/explain.js b/public/js/ui/explain.js
index 2af7539e..78f4a6ba 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, routed to Slack, Teams, Discord or a signed webhook. 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 — 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.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.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." },
"scene.audit": { title: "Audit Log", body: "Every change to this workspace's shared Security Graph, newest first, recorded server-side and hash-chained so each entry commits to the one before it. “Verify chain” walks it from the start and proves nothing has been altered or dropped. Readable by owners and admins." },
diff --git a/test/worker/free-watch.test.mjs b/test/worker/free-watch.test.mjs
new file mode 100644
index 00000000..4205bd43
--- /dev/null
+++ b/test/worker/free-watch.test.mjs
@@ -0,0 +1,407 @@
+// The Free plan's domain watch (worker/free-watch.js) and the email alert channel
+// (worker/alert-email.js), end to end through the MonitorDO with an in-memory storage shim, a fake
+// network and no real sleeps. Nothing here reaches Resend, Firebase or a real DNS resolver.
+import { test, group, assert } from "../harness.mjs";
+import { MonitorDO, handleMonitor, handleWatchStop } from "../../worker/monitor.js";
+import { freeWatchDenied, freeAllowed, FREE_WATCH } from "../../worker/free-watch.js";
+import { buildAlertEmail, buildTestEmail, explainEvent, ALERT_EMAILS_PER_DAY, stopToken, sendEmail, recipient, maskEmail } from "../../worker/alert-email.js";
+import { FROM } from "../../worker/digest.js";
+import { attachPrincipal } from "../../worker/auth.js";
+import { _resetPlanCache } from "../../worker/plan.js";
+import { _resetLocalQuota } from "../../worker/quota.js";
+
+const ME = "test@darknode.ai";
+const ENV = { RESEND_KEY: "re_test_only", DIGEST_SECRET: "unit-test-secret" };
+
+function memState() {
+ const map = new Map(); let alarm = null;
+ const storage = {
+ async get(k) { return map.has(k) ? map.get(k) : undefined; },
+ async put(k, v) { map.set(k, v); },
+ async delete(k) { map.delete(k); },
+ async setAlarm(ts) { alarm = ts; },
+ async getAlarm() { return alarm; },
+ };
+ return { storage, blockConcurrencyWhile: async (fn) => fn(), _map: map };
+}
+const newDO = () => { const st = memState(); const mon = new MonitorDO(st, { ...ENV }); return { st, mon }; };
+
+// a request to the DO as handleMonitor sends it: free = the caller is below Pro
+async function post(mon, body, { uid = "u1", free = false, email = ME, role = "owner", wid = "u1" } = {}) {
+ const headers = { "content-type": "application/json", "x-mon-uid": uid, "x-mon-role": role, "x-mon-wid": wid };
+ if (free) headers["x-mon-plan"] = "free";
+ if (email) headers["x-mon-email"] = encodeURIComponent(email);
+ const res = await mon.fetch(new Request("https://monitor/", { method: "POST", body: JSON.stringify(body), headers }));
+ return { status: res.status, json: await res.json() };
+}
+const watch = (type, domain, extra = {}) => ({ op: "upsert", monitor: { name: "Watch " + domain, type, config: { domains: [domain], ...(type === "cert-expiry" ? { warnDays: 21 } : {}) }, channels: [{ type: "email" }], intervalMs: 86400000, ...extra } });
+
+const day = (n, base = Date.now()) => new Date(base + n * 86400000).toISOString();
+// fake network: crt.sh serves one certificate, DoH serves `zone`, Resend records each email
+function net({ certNotAfter = null, zone = {}, resendStatus = 200 } = {}) {
+ const emails = [], hooks = [];
+ const fetch = async (url, opts = {}) => {
+ url = String(url);
+ if (url.includes("crt.sh")) return { ok: true, status: 200, json: async () => (certNotAfter ? [{ issuer_name: "C=US, O=Example CA, CN=E1", not_after: certNotAfter, not_before: day(-80), name_value: "example.com" }] : []) };
+ if (url.includes("certspotter")) return { ok: false, status: 404, json: async () => null };
+ if (/cloudflare-dns\.com|dns\.google/.test(url)) {
+ const u = new URL(url), type = u.searchParams.get("type"), name = u.searchParams.get("name"), rows = zone[type + " " + name];
+ return { ok: true, status: 200, json: async () => ({ Status: 0, Answer: (rows || []).map((data) => ({ name, type: { TXT: 16, MX: 15, CAA: 257 }[type], data })) }) };
+ }
+ if (url === "https://api.resend.com/emails") { emails.push({ headers: opts.headers, body: JSON.parse(opts.body) }); return { ok: resendStatus < 300, status: resendStatus, json: async () => (resendStatus < 300 ? { id: "e_" + emails.length } : { message: "rejected" }) }; }
+ hooks.push(url); return { ok: true, status: 200 };
+ };
+ return { fetch, emails, hooks };
+}
+const quick = (n, extra = {}) => ({ force: true, fetch: n.fetch, sleep: async () => {}, ...extra });
+
+// ---- the rules (pure) ---------------------------------------------------------------------------
+
+group("free watch/rules", () => {
+ const mon = (type, domains, channels = [{ type: "email", to: ME, uid: "u1" }], id = "m" + Math.random()) => ({ id, type, config: { domains }, channels });
+ test("Free with one domain is allowed: certificate and email/DNS on the same domain", () => {
+ assert.equal(freeWatchDenied(mon("cert-expiry", ["example.com"]), []), null);
+ assert.equal(freeWatchDenied(mon("email-posture", ["https://Example.com/"]), [mon("cert-expiry", ["example.com"])]), null, "same host however it is written");
+ });
+ test("a second domain is denied, naming the one already watched", () => {
+ const no = freeWatchDenied(mon("cert-expiry", ["example.org"]), [mon("cert-expiry", ["example.com"])]);
+ assert.ok(no && /one domain/.test(no) && no.includes("example.com") && no.includes("example.org"), no);
+ assert.ok(freeWatchDenied(mon("cert-expiry", ["example.com", "example.org"]), []), "two domains in one monitor");
+ });
+ test("a paused watch still counts toward the one domain", () => {
+ assert.ok(freeWatchDenied(mon("email-posture", ["example.org"]), [{ ...mon("cert-expiry", ["example.com"]), paused: true }]));
+ });
+ test("kev-epss on Free is denied; so are chat and webhook channels", () => {
+ assert.ok(/Pro plan/.test(freeWatchDenied(mon("kev-epss", []), [])));
+ assert.ok(/account email/.test(freeWatchDenied(mon("cert-expiry", ["example.com"], [{ type: "slack", url: "https://hooks.example.com/x" }]), [])));
+ });
+ test("freeAllowed keeps the earliest-created domain when a lapsed plan left more", () => {
+ const a = { ...mon("cert-expiry", ["example.org"], undefined, "a"), createdAt: 20 };
+ const b = { ...mon("email-posture", ["example.com"], undefined, "b"), createdAt: 10 };
+ const c = { ...mon("cert-expiry", ["example.com"], undefined, "c"), createdAt: 30 };
+ const k = { ...mon("kev-epss", [], undefined, "k"), createdAt: 1 };
+ const hook = { ...mon("cert-expiry", ["example.com"], [{ type: "webhook", url: "https://hooks.example.com/x" }], "h"), createdAt: 0 };
+ assert.deepEqual([...freeAllowed({ a, b, c, k, h: hook })].sort(), ["b", "c"]);
+ });
+});
+
+// ---- the route: who is Free, and the verified address -----------------------------------------
+
+group("free watch/handleMonitor", () => {
+ const capture = () => { const calls = []; return { calls, idFromName: (x) => x, get: () => ({ fetch: async (u, init) => { calls.push(init); return new Response(JSON.stringify({ ok: true }), { status: 200 }); } }) }; };
+ const notFound = async () => ({ ok: false, status: 404, json: async () => ({}) });
+ async function call(wid, body, claims) {
+ _resetPlanCache();
+ const real = globalThis.fetch; globalThis.fetch = notFound; // users/u1 has no tier: Free
+ try {
+ const MONITOR = capture(), json = (b, status = 200) => ({ status, body: b });
+ const req = new Request("https://w.test/x", { method: "POST", body: JSON.stringify(body) });
+ attachPrincipal(req, { kind: "user", uid: "u1", email: ME, token: "tok", claims });
+ const r = await handleMonitor(req, { FIREBASE_PROJECT_ID: "p1", MONITOR }, wid, json);
+ return { ...r, sent: MONITOR.calls[0] };
+ } finally { globalThis.fetch = real; }
+ }
+ test("a Free caller's personal workspace is marked free; Pro is not", async () => {
+ const free = await call("u1", watch("cert-expiry", "example.com"), { email_verified: true });
+ assert.equal(free.sent.headers["x-mon-plan"], "free");
+ const pro = await call("u1", watch("cert-expiry", "example.com"), { email_verified: true, plan: "pro" });
+ assert.equal(pro.sent.headers["x-mon-plan"], undefined);
+ });
+ test("the email header is the token's address, and only when email_verified is true", async () => {
+ assert.equal(decodeURIComponent((await call("u1", { op: "list" }, { email_verified: true })).sent.headers["x-mon-email"]), ME);
+ assert.equal((await call("u1", { op: "list" }, { email_verified: false })).sent.headers["x-mon-email"], undefined);
+ assert.equal((await call("u1", { op: "list" }, {})).sent.headers["x-mon-email"], undefined);
+ });
+});
+
+// ---- the DO enforces it -------------------------------------------------------------------------
+
+group("free watch/MonitorDO", () => {
+ test("Free: one domain, both check types, email to the token's address, once a day", async () => {
+ const { st, mon } = newDO();
+ const a = await post(mon, watch("cert-expiry", "example.com", { intervalMs: 15 * 60000 }), { free: true });
+ assert.equal(a.status, 200, JSON.stringify(a.json));
+ const b = await post(mon, watch("email-posture", "example.com"), { free: true });
+ assert.equal(b.status, 200);
+ const stored = st._map.get("monitors")[a.json.monitor.id];
+ assert.deepEqual(stored.channels, [{ type: "email", to: ME, uid: "u1" }]);
+ assert.equal(stored.intervalMs, FREE_WATCH.minIntervalMs, "a Free watch runs at most once a day");
+ assert.ok(stored.createdAt > 0);
+ assert.equal(a.json.monitor.channels[0].to, ME, "the owner sees their own address");
+ });
+ test("Free: a second domain gets 402 plan:true", async () => {
+ const { mon } = newDO();
+ await post(mon, watch("cert-expiry", "example.com"), { free: true });
+ const r = await post(mon, watch("email-posture", "example.org"), { free: true });
+ assert.equal(r.status, 402); assert.equal(r.json.plan, true);
+ assert.ok(r.json.error.includes("example.com"), r.json.error);
+ });
+ test("Free: kev-epss and webhook channels get 402 plan:true", async () => {
+ const { mon } = newDO();
+ const k = await post(mon, { op: "upsert", monitor: { type: "kev-epss", config: {} } }, { free: true });
+ assert.equal(k.status, 402); assert.equal(k.json.plan, true);
+ const w = await post(mon, { op: "upsert", monitor: { type: "cert-expiry", config: { domains: ["example.com"] }, channels: [{ type: "webhook", url: "https://hooks.example.com/x" }] } }, { free: true });
+ assert.equal(w.status, 402);
+ });
+ test("Pro keeps today's behaviour: many domains, kev-epss, webhooks", async () => {
+ const { mon } = newDO();
+ assert.equal((await post(mon, watch("cert-expiry", "example.com"))).status, 200);
+ assert.equal((await post(mon, watch("cert-expiry", "example.org"))).status, 200);
+ assert.equal((await post(mon, { op: "upsert", monitor: { type: "kev-epss", config: {} } })).status, 200);
+ assert.equal((await post(mon, { op: "upsert", monitor: { type: "cert-expiry", config: { domains: ["example.net"] }, channels: [{ type: "webhook", url: "https://hooks.example.com/x" }] } })).status, 200);
+ });
+ test("an address in the request is ignored: email goes to the verified account only", async () => {
+ const { st, mon } = newDO();
+ const r = await post(mon, { op: "upsert", monitor: { type: "cert-expiry", config: { domains: ["example.com"] }, channels: [{ type: "email", to: "someone@example.org", uid: "u2" }, { type: "email", to: "x@example.org" }] } });
+ assert.deepEqual(st._map.get("monitors")[r.json.monitor.id].channels, [{ type: "email", to: ME, uid: "u1" }], "one email channel, the caller's own address");
+ });
+ test("no verified address: an email channel is refused (400), on any plan", async () => {
+ const { mon } = newDO();
+ assert.equal((await post(mon, watch("cert-expiry", "example.com"), { email: "" })).status, 400);
+ assert.equal((await post(mon, watch("cert-expiry", "example.com"), { email: "", free: true })).status, 400);
+ });
+ test("Free with no channel gets email alerts by default", async () => {
+ const { st, mon } = newDO();
+ const r = await post(mon, { op: "upsert", monitor: { type: "email-posture", config: { domains: ["example.com"] }, channels: [] } }, { free: true });
+ assert.deepEqual(st._map.get("monitors")[r.json.monitor.id].channels, [{ type: "email", to: ME, uid: "u1" }]);
+ });
+ test("another member sees the address masked", async () => {
+ const { mon } = newDO();
+ await post(mon, watch("cert-expiry", "example.com"));
+ const l = await post(mon, { op: "list" }, { uid: "u2", role: "viewer" });
+ assert.equal(l.json.monitors[0].channels[0].to, maskEmail(ME));
+ assert.equal(l.json.monitors[0].channels[0].to, "t***@darknode.ai");
+ });
+ test("Free: Run now runs only the watch, at most once per 10 minutes", async () => {
+ const { st, mon } = newDO();
+ const keep = await post(mon, watch("cert-expiry", "example.com"));
+ st._map.get("monitors")[keep.json.monitor.id].createdAt = 1;
+ await post(mon, watch("cert-expiry", "example.org")); // left over from a paid plan
+ const realFetch = globalThis.fetch; globalThis.fetch = net().fetch;
+ try {
+ const r1 = await post(mon, { op: "run" }, { free: true });
+ assert.equal(r1.status, 200); assert.equal(r1.json.ran.length, 1); assert.equal(r1.json.ran[0].id, keep.json.monitor.id);
+ const r2 = await post(mon, { op: "run" }, { free: true });
+ assert.equal(r2.status, 429); assert.ok(/minute/.test(r2.json.error));
+ } finally { globalThis.fetch = realFetch; }
+ });
+ test("Free: resuming a monitor outside the watch gets 402; the watch itself resumes", async () => {
+ const { st, mon } = newDO();
+ const keep = await post(mon, watch("cert-expiry", "example.com"));
+ st._map.get("monitors")[keep.json.monitor.id].createdAt = 1;
+ const other = await post(mon, watch("cert-expiry", "example.org"));
+ await post(mon, { op: "pause", id: other.json.monitor.id, paused: true });
+ await post(mon, { op: "pause", id: keep.json.monitor.id, paused: true });
+ assert.equal((await post(mon, { op: "pause", id: other.json.monitor.id, paused: false }, { free: true })).status, 402);
+ assert.equal((await post(mon, { op: "pause", id: keep.json.monitor.id, paused: false }, { free: true })).status, 200);
+ });
+ test("the alarm on a Free plan runs the watch and holds everything else", async () => {
+ const { st, mon } = newDO();
+ const keep = await post(mon, watch("cert-expiry", "example.com"));
+ const hook = await post(mon, { op: "upsert", monitor: { type: "cert-expiry", config: { domains: ["example.com"] }, channels: [{ type: "webhook", url: "https://hooks.example.com/x" }] } });
+ await st.storage.put("wid", "u1");
+ mon.env = { ...ENV, FIREBASE_PROJECT_ID: "p1" };
+ mon.planOpts = { token: async () => "sa", cache: new Map(), fetch: async () => ({ ok: true, status: 200, json: async () => ({ fields: { tier: { stringValue: "free" } } }) }) };
+ const realFetch = globalThis.fetch; globalThis.fetch = net().fetch;
+ try { await mon.alarm(); } finally { globalThis.fetch = realFetch; }
+ const mons = st._map.get("monitors");
+ assert.ok(mons[keep.json.monitor.id].lastRunAt > 0, "the watch ran");
+ assert.equal(mons[keep.json.monitor.id].planHeld, undefined);
+ assert.equal(mons[hook.json.monitor.id].planHeld, true, "the webhook monitor is held");
+ });
+});
+
+// ---- the email --------------------------------------------------------------------------------
+
+const NOW = Date.UTC(2026, 10, 25, 9, 30);
+const certEv = { kind: "cert", key: "cert:example.com", severity: "high", title: "Certificate for example.com expires in 9 days", domain: "example.com", daysToExpiry: 9, notAfter: "2026-12-04T09:00:00.000Z", issuer: "C=US, O=Example CA, CN=E1" };
+const dmarcEv = { kind: "drift", key: "email:example.com:dmarc", severity: "medium", title: "DMARC on example.com: DMARC p=none (monitor only).", domain: "example.com", check: "DMARC", advice: "Enforce with p=quarantine then p=reject.", was: "reject", now: "none", recordAt: "_dmarc.example.com" };
+
+group("alert email/content", () => {
+ test("what changed, why it matters, the exact fix", () => {
+ const c = explainEvent(certEv);
+ assert.equal(c.what, "Certificate for example.com expires in 9 days");
+ assert.ok(/browsers block visitors to example.com/.test(c.why));
+ assert.ok(c.fix.includes("Renew the certificate for example.com") && c.fix.includes("issued by Example CA") && c.fix.includes("valid until 2026-12-04"), c.fix);
+ const d = explainEvent(dmarcEv);
+ assert.equal(d.what, "DMARC policy for example.com weakened from reject to none");
+ assert.ok(/phishing in your name/.test(d.why));
+ assert.equal(d.fix, "Set the policy in the TXT record at _dmarc.example.com back to p=reject.");
+ const removed = explainEvent({ ...dmarcEv, now: "missing", title: "DMARC on example.com: No DMARC record." });
+ assert.equal(removed.what, "The DMARC record for example.com was removed (it had p=reject)");
+ assert.ok(removed.fix.startsWith("Publish one TXT record at _dmarc.example.com: v=DMARC1; p=quarantine"));
+ assert.equal(explainEvent({ key: "email:example.com:spf", severity: "low", title: "SPF on example.com: x", domain: "example.com", check: "SPF", was: "-all", now: "~all" }).what, "SPF for example.com weakened from -all to ~all");
+ });
+ test("a sample email: plain text + simple HTML, no tracking, no emojis, a stop link and the Deck path", () => {
+ const stop = "https://darknode-proxy.darknode-ai.workers.dev/api/watch/stop?w=u1&u=u1&t=abc";
+ const m = buildAlertEmail({ monitor: { id: "m1", name: "Watch example.com", type: "email-posture", intervalMs: 86400000 }, events: [dmarcEv], stopUrl: stop, sent: 1, now: NOW });
+ process.stdout.write("\n----- sample alert email (text) -----\nSubject: " + m.subject + "\n\n" + m.text + "\n----- end sample -----\n\n");
+ assert.equal(m.subject, "DMARC policy for example.com weakened from reject to none");
+ for (const s of ["Why it matters:", "Fix: Set the policy in the TXT record at _dmarc.example.com back to p=reject.", "https://darknode.ai/monitors", "Stop these alerts: " + stop, "Monitors, then Pause or Delete", "once a day"]) assert.ok(m.text.includes(s), s);
+ assert.ok(m.html.includes("Why it matters:") && m.html.includes(stop.replace(/&/g, "&")));
+ assert.ok(!/ {
+ const m = buildAlertEmail({ monitor: { name: "Watch example.com", intervalMs: 86400000 }, events: [certEv, dmarcEv], now: NOW });
+ assert.equal(m.subject, "2 changes on example.com need attention");
+ assert.ok(m.text.includes("1. Certificate for example.com expires in 9 days [High]") && m.text.includes("2. DMARC policy for example.com weakened"));
+ assert.ok(!m.text.includes("Stop these alerts:"), "no stop link when none could be signed; the Deck path is still there");
+ assert.ok(m.text.includes("Monitors, then Pause or Delete"));
+ });
+ test("the email that reaches the cap says so", () => {
+ const m = buildAlertEmail({ monitor: {}, events: [certEv], sent: ALERT_EMAILS_PER_DAY, now: NOW });
+ assert.ok(m.text.includes("This is alert email 5 of 5 today, the daily limit"));
+ assert.ok(!buildAlertEmail({ monitor: {}, events: [certEv], sent: 4, now: NOW }).text.includes("daily limit"));
+ });
+ test("escapes what it shows", () => {
+ const m = buildAlertEmail({ monitor: { name: "x" }, events: [{ ...certEv, title: "t", daysToExpiry: NaN }], now: NOW });
+ assert.ok(!m.html.includes("x") && m.html.includes("<b>x</b>"));
+ });
+ test("the Resend payload: digest sender, one recipient, one-click unsubscribe, idempotency key", async () => {
+ const n = net();
+ const r = await sendEmail(ENV, { to: ME, subject: "s", html: "
h
", text: "t", stop: "https://w.test/stop", idempotencyKey: "k1" }, n.fetch);
+ assert.equal(r.ok, true);
+ const e = n.emails[0];
+ assert.equal(e.body.from, FROM); assert.deepEqual(e.body.to, [ME]);
+ assert.equal(e.body.headers["List-Unsubscribe"], "");
+ assert.equal(e.body.headers["List-Unsubscribe-Post"], "List-Unsubscribe=One-Click");
+ assert.equal(e.headers["Idempotency-Key"], "k1");
+ assert.equal((await sendEmail({}, { to: ME, subject: "s", html: "", text: "" }, n.fetch)).ok, false, "no key: a failure, not a silent skip");
+ });
+ test("the recipient is re-checked in Firebase Auth at send time", async () => {
+ const ch = { type: "email", to: ME, uid: "u1" };
+ assert.deepEqual(await recipient({}, ch, { account: async () => ({ email: "new@darknode.ai", verified: true }) }), { to: "new@darknode.ai" });
+ assert.ok((await recipient({}, ch, { account: async () => null })).error);
+ assert.ok((await recipient({}, ch, { account: async () => ({ email: ME, verified: false }) })).error);
+ assert.ok((await recipient({}, ch, { account: async () => ({ email: ME, verified: true, disabled: true }) })).error);
+ assert.ok((await recipient({}, ch, { account: async () => { throw new Error("down"); } })).error);
+ assert.deepEqual(await recipient({}, ch, { account: async () => undefined }), { to: ME }, "no service account: the address verified at setup");
+ assert.ok((await recipient({}, { type: "email" }, {})).error, "a channel without a verified address sends nothing");
+ });
+});
+
+// ---- the DO sends it, and caps it ---------------------------------------------------------------
+
+group("alert email/delivery", () => {
+ test("a certificate run emails the watch's owner, with the stop link and Deck path", async () => {
+ _resetLocalQuota();
+ const { st, mon } = newDO();
+ await st.storage.put("wid", "u1");
+ await post(mon, watch("cert-expiry", "example.com"), { free: true });
+ const n = net({ certNotAfter: day(9, NOW) });
+ const r = await mon.runDue(quick(n, { now: NOW }));
+ assert.equal(r.ran[0].delivered, 1);
+ assert.equal(n.emails.length, 1);
+ const e = n.emails[0].body;
+ assert.deepEqual(e.to, [ME]);
+ assert.equal(e.subject, "Certificate for example.com expires in 9 days");
+ assert.ok(e.text.includes("/api/watch/stop?w=u1&u=u1&t=") && e.headers["List-Unsubscribe-Post"]);
+ const d = st._map.get("deliveries")[0];
+ assert.equal(d.type, "email"); assert.equal(d.ok, true); assert.equal(d.to, "t***@darknode.ai");
+ });
+ test("a DMARC weakening between runs is named: from reject to none", async () => {
+ _resetLocalQuota();
+ const { st, mon } = newDO();
+ await post(mon, watch("email-posture", "example.com"), { free: true });
+ const zone = { "TXT example.com": ["v=spf1 mx -all"], "TXT _dmarc.example.com": ["v=DMARC1; p=reject; rua=mailto:d@example.com"], "MX example.com": ["10 mx.example.net."], "CAA example.com": ['0 issue "ca.example.net"'] };
+ const a = net({ zone });
+ await mon.runDue(quick(a, { now: NOW }));
+ assert.equal(a.emails.length, 0, "a healthy baseline sends nothing");
+ zone["TXT _dmarc.example.com"] = ["v=DMARC1; p=none; rua=mailto:d@example.com"];
+ const b = net({ zone });
+ await mon.runDue(quick(b, { now: NOW + 86400000 }));
+ assert.equal(b.emails.length, 1);
+ assert.equal(b.emails[0].body.subject, "DMARC policy for example.com weakened from reject to none");
+ assert.ok(b.emails[0].body.text.includes("Fix: Set the policy in the TXT record at _dmarc.example.com back to p=reject."));
+ assert.equal(st._map.get("monitors")[Object.keys(st._map.get("monitors"))[0]].posture["example.com"].dmarc, "none");
+ });
+ test("the daily cap: 5 emails, then each further alert is logged as failed, not sent", async () => {
+ _resetLocalQuota();
+ const { st, mon } = newDO();
+ await st.storage.put("wid", "u1");
+ const n = net(); const realFetch = globalThis.fetch; globalThis.fetch = n.fetch;
+ try {
+ const out = [];
+ for (let i = 0; i < ALERT_EMAILS_PER_DAY + 2; i++) out.push((await post(mon, { op: "test", channel: { type: "email", to: "someone@example.org" } }, { free: true })).json);
+ assert.equal(n.emails.length, ALERT_EMAILS_PER_DAY, "only 5 sent");
+ assert.ok(n.emails.every((e) => e.body.to[0] === ME), "always the account's own address, never the one in the request");
+ assert.ok(n.emails[ALERT_EMAILS_PER_DAY - 1].body.text.includes("counts as 5 of 5 today"));
+ assert.equal(out[ALERT_EMAILS_PER_DAY].ok, false); assert.equal(out[ALERT_EMAILS_PER_DAY].status, 429);
+ assert.ok(/Daily alert email limit/.test(out[ALERT_EMAILS_PER_DAY].error));
+ const log = st._map.get("deliveries");
+ assert.equal(log[0].ok, false); assert.ok(/limit/.test(log[0].error), "the capped alert is in the delivery log as failed");
+ } finally { globalThis.fetch = realFetch; }
+ });
+ test("a send that fails every attempt is logged as failed and does not use up the cap", async () => {
+ _resetLocalQuota();
+ const { st, mon } = newDO();
+ await post(mon, watch("cert-expiry", "example.com"), { free: true });
+ const bad = net({ certNotAfter: day(5, NOW), resendStatus: 422 });
+ const r = await mon.runDue(quick(bad, { now: NOW }));
+ assert.equal(r.ran[0].delivered, 0);
+ assert.equal(bad.emails.length, 3, "three attempts");
+ const log = st._map.get("deliveries");
+ assert.equal(log.length, 3); assert.ok(log.every((d) => !d.ok && /Email provider error/.test(d.error)));
+ const quota = []; // the next alert still gets a slot
+ const { mon: m2 } = newDO();
+ await post(m2, watch("cert-expiry", "example.com"), { free: true });
+ await m2.runDue(quick(net({ certNotAfter: day(5, NOW) }), { now: NOW, emailQuota: async (k, l, at, refund) => { quota.push(refund); return { ok: true, used: 1, limit: l }; } }));
+ assert.deepEqual(quota, [false], "a delivered email is charged once and not refunded");
+ });
+ test("a Free test of a webhook channel is refused; an email test needs a verified address", async () => {
+ const { mon } = newDO();
+ assert.equal((await post(mon, { op: "test", channel: { type: "webhook", url: "https://hooks.example.com/x" } }, { free: true })).status, 402);
+ assert.equal((await post(mon, { op: "test", channel: { type: "email" } }, { free: true, email: "" })).status, 400);
+ });
+ test("the test email says it is a test", () => {
+ const t = buildTestEmail({ sent: 1, now: NOW });
+ assert.equal(t.subject, "Darknode alert email test");
+ assert.ok(t.text.includes("This is a test"));
+ });
+});
+
+// ---- the stop link ------------------------------------------------------------------------------
+
+group("alert email/stop link", () => {
+ const setup = async () => {
+ const { st, mon } = newDO();
+ await post(mon, watch("cert-expiry", "example.com"), { free: true });
+ await post(mon, watch("email-posture", "example.com"), { free: true });
+ await post(mon, { op: "upsert", monitor: { type: "cert-expiry", config: { domains: ["example.org"] }, channels: [{ type: "webhook", url: "https://hooks.example.com/x" }] } });
+ const env = { ...ENV, MONITOR: { idFromName: (x) => x, get: () => ({ fetch: (u, init) => mon.fetch(new Request("https://monitor/", init)) }) } };
+ const t = await stopToken("u1", "u1", ENV.DIGEST_SECRET);
+ return { st, env, url: "https://w.test/api/watch/stop?w=u1&u=u1&t=" + t };
+ };
+ const paused = (st) => Object.values(st._map.get("monitors")).map((m) => !!m.paused);
+ test("GET only shows a confirm page (a link scanner stops nothing)", async () => {
+ const { st, env, url } = await setup();
+ const res = await handleWatchStop(new Request(url), env);
+ const html = await res.text();
+ assert.ok(html.includes('